Ignore:
Timestamp:
Feb 7, 2019, 8:36:33 AM (5 years ago)
Author:
coas-nagasima
Message:

wolfsslを3.15.7にバージョンアップ

File:
1 edited

Legend:

Unmodified
Added
Removed
  • asp3_tinet_ecnl_rx/trunk/wolfssl-3.12.2/src/tls13.c

    r337 r372  
    2222
    2323/*
    24  * WOLFSSL_TLS13_DRAFT_18
    25  *    Conform with Draft 18 of the TLS v1.3 specification.
     24 * BUILD_GCM
     25 *    Enables AES-GCM ciphersuites.
     26 * HAVE_AESCCM
     27 *    Enables AES-CCM ciphersuites.
     28 * HAVE_SESSION_TICKET
     29 *    Enables session tickets - required for TLS 1.3 resumption.
     30 * NO_PSK
     31 *    Do not enable Pre-Shared Keys.
     32 * TLS13_SUPPORTS_EXPORTERS
     33 *    Gaurd to compile out any code for exporter keys.
     34 *    Feature not supported yet.
     35 * WOLFSSL_ASYNC_CRYPT
     36 *    Enables the use of asynchornous cryptographic operations.
     37 *    This is available for ciphers and certificates.
     38 * HAVE_CHACHA && HAVE_POLY1305
     39 *    Enables use of CHACHA20-POLY1305 ciphersuites.
     40 * WOLFSSL_DEBUG_TLS
     41 *    Writes out details of TLS 1.3 protocol including hanshake message buffers
     42 *    and key generation input and output.
    2643 * WOLFSSL_EARLY_DATA
    2744 *    Allow 0-RTT Handshake using Early Data extensions and handshake message
     45 * WOLFSSL_EARLY_DATA_GROUP
     46 *    Group EarlyData message with ClientHello when sending
     47 * WOLFSSL_NO_SERVER_GROUPS_EXT
     48 *    Do not send the server's groups in an extension when the server's top
     49 *    preference is not in client's list.
    2850 * WOLFSSL_POST_HANDSHAKE_AUTH
    2951 *    Allow TLS v1.3 code to perform post-handshake authentication of the
    3052 *    client.
     53 * WOLFSSL_SEND_HRR_COOKIE
     54 *    Send a cookie in hello_retry_request message to enable stateless tracking
     55 *    of ClientHello replies.
     56 * WOLFSSL_TLS13
     57 *    Enable TLS 1.3 protocol implementation.
     58 * WOLFSSL_TLS13_DRAFT_18
     59 *    Conform with Draft 18 of the TLS v1.3 specification.
     60 * WOLFSSL_TLS13_DRAFT_22
     61 *    Conform with Draft 22 of the TLS v1.3 specification.
     62 * WOLFSSL_TLS13_DRAFT_23
     63 *    Conform with Draft 23 of the TLS v1.3 specification.
     64 * WOLFSSL_TLS13_MIDDLEBOX_COMPAT
     65 *    Enable middlebox compatability in the TLS 1.3 handshake.
     66 *    This includes sending ChangeCipherSpec before encrypted messages and
     67 *    including a session id.
     68 * WOLFSSL_TLS13_SHA512
     69 *    Allow generation of SHA-512 digests in handshake - no ciphersuite
     70 *    requires SHA-512 at this time.
    3171 * WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
    3272 *    Allow a NewSessionTicket message to be sent by server before Client's
    3373 *    Finished message.
    34  *    See TLS v.13 specification, Section 4.6.1, Paragraph 4 (Note).
    35  * TLS13_SUPPORTS_EXPORTERS
    36  *    Gaurd to compile out any code for exporter keys.
    37  *    Feature not supported yet.
     74 *    See TLS v1.3 specification, Section 4.6.1, Paragraph 4 (Note).
    3875 */
    3976
     
    4683#ifdef WOLFSSL_TLS13
    4784#ifdef HAVE_SESSION_TICKET
    48     #include <sys/time.h>
     85    #include <wolfssl/wolfcrypt/wc_port.h>
    4986#endif
    5087
     
    94131#endif
    95132
     133#ifndef HAVE_HKDF
     134    #error The build option HAVE_HKDF is required for TLS 1.3
     135#endif
     136
     137
    96138/* Set ret to error value and jump to label.
    97139 *
     
    135177        #endif
    136178
    137         #ifdef WOLFSSL_TLS13_TLS13_SHA512
     179        #ifdef WOLFSSL_TLS13_SHA512
    138180        case sha512_mac:
    139181            hash = WC_SHA512;
     
    170212 *
    171213 * okm          The generated pseudorandom key - output key material.
     214 * okmLen       The length of generated pseudorandom key - output key material.
    172215 * prk          The salt - pseudo-random key.
    173216 * prkLen       The length of the salt - pseudo-random key.
     
    191234
    192235    /* Output length. */
    193     data[idx++] = okmLen >> 8;
    194     data[idx++] = okmLen;
     236    data[idx++] = (byte)(okmLen >> 8);
     237    data[idx++] = (byte)okmLen;
    195238    /* Length of protocol | label. */
    196     data[idx++] = protocolLen + labelLen;
     239    data[idx++] = (byte)(protocolLen + labelLen);
    197240    /* Protocol */
    198241    XMEMCPY(&data[idx], protocol, protocolLen);
     
    202245    idx += labelLen;
    203246    /* Length of hash of messages */
    204     data[idx++] = infoLen;
     247    data[idx++] = (byte)infoLen;
    205248    /* Hash of messages */
    206249    XMEMCPY(&data[idx], info, infoLen);
     
    257300                        byte* msg, int msgLen, int hashAlgo)
    258301{
    259     byte        hash[MAX_DIGEST_SIZE];
     302    byte        hash[WC_MAX_DIGEST_SIZE];
    260303    Digest      digest;
    261304    word32      hashSz = 0;
    262305    const byte* protocol;
    263306    word32      protocolLen;
    264     int         digestAlg;
     307    int         digestAlg = -1;
    265308    int         ret = BAD_FUNC_ARG;
    266309
     
    305348            break;
    306349#endif
    307     }
     350        default:
     351            digestAlg = -1;
     352            break;
     353    }
     354
     355    if (digestAlg < 0)
     356        return HASH_TYPE_E;
    308357
    309358    if (ret != 0)
     
    345394{
    346395    int         ret = 0;
    347     byte        hash[MAX_DIGEST_SIZE];
     396    byte        hash[WC_MAX_DIGEST_SIZE];
    348397    word32      hashSz = 0;
    349398    word32      hashOutSz = 0;
     
    808857#endif
    809858}
     859
     860#ifndef WOLFSSL_TLS13_DRAFT_18
     861#if defined(HAVE_SESSION_TICKET)
     862/* Length of the resumption label. */
     863#define RESUMPTION_LABEL_SZ         10
     864/* Resumption label for generating PSK assocated with the ticket. */
     865static const byte resumptionLabel[RESUMPTION_LABEL_SZ+1] = "resumption";
     866/* Derive the PSK assocated with the ticket.
     867 *
     868 * ssl       The SSL/TLS object.
     869 * nonce     The nonce to derive with.
     870 * nonceLen  The length of the nonce to derive with.
     871 * secret    The derived secret.
     872 * returns 0 on success, otherwise failure.
     873 */
     874static int DeriveResumptionPSK(WOLFSSL* ssl, byte* nonce, byte nonceLen,
     875                               byte* secret)
     876{
     877    int         digestAlg;
     878    /* Only one protocol version defined at this time. */
     879    const byte* protocol    = tls13ProtocolLabel;
     880    word32      protocolLen = TLS13_PROTOCOL_LABEL_SZ;
     881
     882    WOLFSSL_MSG("Derive Resumption PSK");
     883
     884    switch (ssl->specs.mac_algorithm) {
     885        #ifndef NO_SHA256
     886        case sha256_mac:
     887            digestAlg = WC_SHA256;
     888            break;
     889        #endif
     890
     891        #ifdef WOLFSSL_SHA384
     892        case sha384_mac:
     893            digestAlg = WC_SHA384;
     894            break;
     895        #endif
     896
     897        #ifdef WOLFSSL_TLS13_SHA512
     898        case sha512_mac:
     899            digestAlg = WC_SHA512;
     900            break;
     901        #endif
     902
     903        default:
     904            return BAD_FUNC_ARG;
     905    }
     906
     907    return HKDF_Expand_Label(secret, ssl->specs.hash_size,
     908                             ssl->session.masterSecret, ssl->specs.hash_size,
     909                             protocol, protocolLen, resumptionLabel,
     910                             RESUMPTION_LABEL_SZ, nonce, nonceLen, digestAlg);
     911}
     912#endif /* HAVE_SESSION_TICKET */
     913#endif /* WOLFSSL_TLS13_DRAFT_18 */
     914
    810915
    811916/* Calculate the HMAC of message data to this point.
     
    8971002static int DeriveTls13Keys(WOLFSSL* ssl, int secret, int side, int store)
    8981003{
    899     int   ret;
     1004    int   ret = BAD_FUNC_ARG; /* Assume failure */
    9001005    int   i = 0;
    9011006#ifdef WOLFSSL_SMALL_STACK
     
    9251030#ifdef WOLFSSL_EARLY_DATA
    9261031        case early_data_key:
    927             ret = DeriveEarlyTrafficSecret(ssl, ssl->arrays->clientSecret);
     1032            ret = DeriveEarlyTrafficSecret(ssl, ssl->clientSecret);
    9281033            if (ret != 0)
    9291034                goto end;
     
    9341039            if (provision & PROVISION_CLIENT) {
    9351040                ret = DeriveClientHandshakeSecret(ssl,
    936                                                   ssl->arrays->clientSecret);
     1041                                                  ssl->clientSecret);
    9371042                if (ret != 0)
    9381043                    goto end;
     
    9401045            if (provision & PROVISION_SERVER) {
    9411046                ret = DeriveServerHandshakeSecret(ssl,
    942                                                   ssl->arrays->serverSecret);
     1047                                                  ssl->serverSecret);
    9431048                if (ret != 0)
    9441049                    goto end;
     
    9481053        case traffic_key:
    9491054            if (provision & PROVISION_CLIENT) {
    950                 ret = DeriveClientTrafficSecret(ssl, ssl->arrays->clientSecret);
     1055                ret = DeriveClientTrafficSecret(ssl, ssl->clientSecret);
    9511056                if (ret != 0)
    9521057                    goto end;
    9531058            }
    9541059            if (provision & PROVISION_SERVER) {
    955                 ret = DeriveServerTrafficSecret(ssl, ssl->arrays->serverSecret);
     1060                ret = DeriveServerTrafficSecret(ssl, ssl->serverSecret);
    9561061                if (ret != 0)
    9571062                    goto end;
     
    9611066        case update_traffic_key:
    9621067            if (provision & PROVISION_CLIENT) {
    963                 ret = DeriveTrafficSecret(ssl, ssl->arrays->clientSecret);
     1068                ret = DeriveTrafficSecret(ssl, ssl->clientSecret);
    9641069                if (ret != 0)
    9651070                    goto end;
    9661071            }
    9671072            if (provision & PROVISION_SERVER) {
    968                 ret = DeriveTrafficSecret(ssl, ssl->arrays->serverSecret);
     1073                ret = DeriveTrafficSecret(ssl, ssl->serverSecret);
    9691074                if (ret != 0)
    9701075                    goto end;
     
    9821087        WOLFSSL_MSG("Derive Client Key");
    9831088        ret = DeriveKey(ssl, &key_dig[i], ssl->specs.key_size,
    984                         ssl->arrays->clientSecret, writeKeyLabel,
     1089                        ssl->clientSecret, writeKeyLabel,
    9851090                        WRITE_KEY_LABEL_SZ, ssl->specs.mac_algorithm, 0);
    9861091        if (ret != 0)
     
    9931098        WOLFSSL_MSG("Derive Server Key");
    9941099        ret = DeriveKey(ssl, &key_dig[i], ssl->specs.key_size,
    995                         ssl->arrays->serverSecret, writeKeyLabel,
     1100                        ssl->serverSecret, writeKeyLabel,
    9961101                        WRITE_KEY_LABEL_SZ, ssl->specs.mac_algorithm, 0);
    9971102        if (ret != 0)
     
    10041109        WOLFSSL_MSG("Derive Client IV");
    10051110        ret = DeriveKey(ssl, &key_dig[i], ssl->specs.iv_size,
    1006                         ssl->arrays->clientSecret, writeIVLabel,
     1111                        ssl->clientSecret, writeIVLabel,
    10071112                        WRITE_IV_LABEL_SZ, ssl->specs.mac_algorithm, 0);
    10081113        if (ret != 0)
     
    10151120        WOLFSSL_MSG("Derive Server IV");
    10161121        ret = DeriveKey(ssl, &key_dig[i], ssl->specs.iv_size,
    1017                         ssl->arrays->serverSecret, writeIVLabel,
     1122                        ssl->serverSecret, writeIVLabel,
    10181123                        WRITE_IV_LABEL_SZ, ssl->specs.mac_algorithm, 0);
    10191124        if (ret != 0)
     
    13111416    rl->type    = type;
    13121417    rl->pvMajor = ssl->version.major;
     1418#ifdef WOLFSSL_TLS13_DRAFT_18
    13131419    rl->pvMinor = TLSv1_MINOR;
     1420#else
     1421    /* NOTE: May be TLSv1_MINOR when sending first ClientHello. */
     1422    rl->pvMinor = TLSv1_2_MINOR;
     1423#endif
    13141424    c16toa((word16)length, rl->length);
    13151425}
     
    13881498 * out          The buffer to write into.
    13891499 */
    1390 static INLINE void WriteSEQ(WOLFSSL* ssl, int verifyOrder, byte* out)
     1500static WC_INLINE void WriteSEQ(WOLFSSL* ssl, int verifyOrder, byte* out)
    13911501{
    13921502    word32 seq[2] = {0, 0};
     
    14181528 * order  The side on which the message is to be or was sent.
    14191529 */
    1420 static INLINE void BuildTls13Nonce(WOLFSSL* ssl, byte* nonce, const byte* iv,
     1530static WC_INLINE void BuildTls13Nonce(WOLFSSL* ssl, byte* nonce, const byte* iv,
    14211531                                   int order)
    14221532{
     
    14311541}
    14321542
    1433 #ifdef HAVE_CHACHA
     1543#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
    14341544/* Encrypt with ChaCha20 and create authenication tag with Poly1305.
    14351545 *
     
    14401550 * sz      The number of bytes to encrypt.
    14411551 * nonce   The nonce to use with ChaCha20.
     1552 * aad     The additional authentication data.
     1553 * aadSz   The size of the addition authentication data.
    14421554 * tag     The authentication tag buffer.
    14431555 * returns 0 on success, otherwise failure.
     
    14451557static int ChaCha20Poly1305_Encrypt(WOLFSSL* ssl, byte* output,
    14461558                                    const byte* input, word16 sz, byte* nonce,
    1447                                     byte* tag)
     1559                                    const byte* aad, word16 aadSz, byte* tag)
    14481560{
    14491561    int    ret    = 0;
     
    14741586        return ret;
    14751587    /* Add authentication code of encrypted data to end. */
    1476     ret = wc_Poly1305_MAC(ssl->auth.poly1305, NULL, 0, output, sz, tag,
    1477                           POLY1305_AUTH_SZ);
     1588    ret = wc_Poly1305_MAC(ssl->auth.poly1305, (byte*)aad, aadSz, output, sz,
     1589                          tag, POLY1305_AUTH_SZ);
    14781590
    14791591    return ret;
     
    14861598 * output  The buffer to write encrypted data and authentication tag into.
    14871599 *         May be the same pointer as input.
    1488  * input   The data to encrypt.
     1600 * input   The record header and data to encrypt.
    14891601 * sz      The number of bytes to encrypt.
     1602 * aad     The additional authentication data.
     1603 * aadSz   The size of the addition authentication data.
    14901604 * asyncOkay If non-zero can return WC_PENDING_E, otherwise blocks on crypto
    14911605 * returns 0 on success, otherwise failure.
    14921606 */
    14931607static int EncryptTls13(WOLFSSL* ssl, byte* output, const byte* input,
    1494                         word16 sz, int asyncOkay)
     1608                        word16 sz, const byte* aad, word16 aadSz, int asyncOkay)
    14951609{
    14961610    int    ret    = 0;
     
    15251639            WOLFSSL_MSG("Data to encrypt");
    15261640            WOLFSSL_BUFFER(input, dataSz);
     1641#if !defined(WOLFSSL_TLS13_DRAFT_18) && !defined(WOLFSSL_TLS13_DRAFT_22) && \
     1642                                        !defined(WOLFSSL_TLS13_DRAFT_23)
     1643            WOLFSSL_MSG("Additional Authentication Data");
     1644            WOLFSSL_BUFFER(aad, aadSz);
     1645#endif
    15271646        #endif
    15281647
     
    15471666                case wolfssl_aes_gcm:
    15481667                #ifdef WOLFSSL_ASYNC_CRYPT
    1549                     /* intialize event */
     1668                    /* initialize event */
    15501669                    asyncDev = &ssl->encrypt.aes->asyncDev;
    15511670                    ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
     
    15571676                    ret = wc_AesGcmEncrypt(ssl->encrypt.aes, output, input,
    15581677                        dataSz, ssl->encrypt.nonce, nonceSz,
    1559                         output + dataSz, macSz, NULL, 0);
     1678                        output + dataSz, macSz, aad, aadSz);
    15601679                    break;
    15611680            #endif
     
    15641683                case wolfssl_aes_ccm:
    15651684                #ifdef WOLFSSL_ASYNC_CRYPT
    1566                     /* intialize event */
     1685                    /* initialize event */
    15671686                    asyncDev = &ssl->encrypt.aes->asyncDev;
    15681687                    ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
     
    15741693                    ret = wc_AesCcmEncrypt(ssl->encrypt.aes, output, input,
    15751694                        dataSz, ssl->encrypt.nonce, nonceSz,
    1576                         output + dataSz, macSz, NULL, 0);
     1695                        output + dataSz, macSz, aad, aadSz);
    15771696                    break;
    15781697            #endif
     
    15811700                case wolfssl_chacha:
    15821701                    ret = ChaCha20Poly1305_Encrypt(ssl, output, input, dataSz,
    1583                         ssl->encrypt.nonce, output + dataSz);
     1702                        ssl->encrypt.nonce, aad, aadSz, output + dataSz);
    15841703                    break;
    15851704            #endif
     
    16311750}
    16321751
    1633 #ifdef HAVE_CHACHA
     1752#if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
    16341753/* Decrypt with ChaCha20 and check authenication tag with Poly1305.
    16351754 *
     
    16401759 * sz      The number of bytes to decrypt.
    16411760 * nonce   The nonce to use with ChaCha20.
     1761 * aad     The additional authentication data.
     1762 * aadSz   The size of the addition authentication data.
    16421763 * tagIn   The authentication tag data from packet.
    16431764 * returns 0 on success, otherwise failure.
     
    16451766static int ChaCha20Poly1305_Decrypt(WOLFSSL* ssl, byte* output,
    16461767                                    const byte* input, word16 sz, byte* nonce,
     1768                                    const byte* aad, word16 aadSz,
    16471769                                    const byte* tagIn)
    16481770{
     
    16691791        return ret;
    16701792    /* Generate authentication tag for encrypted data. */
    1671     if ((ret = wc_Poly1305_MAC(ssl->auth.poly1305, NULL, 0, (byte*)input, sz,
    1672                                tag, sizeof(tag))) != 0) {
     1793    if ((ret = wc_Poly1305_MAC(ssl->auth.poly1305, (byte*)aad, aadSz,
     1794                                    (byte*)input, sz, tag, sizeof(tag))) != 0) {
    16731795        return ret;
    16741796    }
     
    16921814 * output  The buffer to write decrypted data into.
    16931815 *         May be the same pointer as input.
    1694  * input   The data to encrypt and authentication tag.
     1816 * input   The data to decrypt and authentication tag.
    16951817 * sz      The length of the encrypted data plus authentication tag.
     1818 * aad     The additional authentication data.
     1819 * aadSz   The size of the addition authentication data.
    16961820 * returns 0 on success, otherwise failure.
    16971821 */
    1698 int DecryptTls13(WOLFSSL* ssl, byte* output, const byte* input, word16 sz)
     1822int DecryptTls13(WOLFSSL* ssl, byte* output, const byte* input, word16 sz,
     1823                 const byte* aad, word16 aadSz)
    16991824{
    17001825    int    ret    = 0;
     
    17371862            WOLFSSL_MSG("Data to decrypt");
    17381863            WOLFSSL_BUFFER(input, dataSz);
     1864#if !defined(WOLFSSL_TLS13_DRAFT_18) && !defined(WOLFSSL_TLS13_DRAFT_22) && \
     1865                                        !defined(WOLFSSL_TLS13_DRAFT_23)
     1866            WOLFSSL_MSG("Additional Authentication Data");
     1867            WOLFSSL_BUFFER(aad, aadSz);
     1868#endif
    17391869            WOLFSSL_MSG("Authentication tag");
    17401870            WOLFSSL_BUFFER(input + dataSz, macSz);
     
    17611891                case wolfssl_aes_gcm:
    17621892                #ifdef WOLFSSL_ASYNC_CRYPT
    1763                     /* intialize event */
     1893                    /* initialize event */
    17641894                    ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
    17651895                        WC_ASYNC_FLAG_CALL_AGAIN);
     
    17711901                    ret = wc_AesGcmDecrypt(ssl->decrypt.aes, output, input,
    17721902                        dataSz, ssl->decrypt.nonce, nonceSz,
    1773                         input + dataSz, macSz, NULL, 0);
     1903                        input + dataSz, macSz, aad, aadSz);
    17741904                #ifdef WOLFSSL_ASYNC_CRYPT
    17751905                    if (ret == WC_PENDING_E) {
     
    17841914                case wolfssl_aes_ccm:
    17851915                #ifdef WOLFSSL_ASYNC_CRYPT
    1786                     /* intialize event */
     1916                    /* initialize event */
    17871917                    ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
    17881918                        WC_ASYNC_FLAG_CALL_AGAIN);
     
    17941924                    ret = wc_AesCcmDecrypt(ssl->decrypt.aes, output, input,
    17951925                        dataSz, ssl->decrypt.nonce, nonceSz,
    1796                         input + dataSz, macSz, NULL, 0);
     1926                        input + dataSz, macSz, aad, aadSz);
    17971927                #ifdef WOLFSSL_ASYNC_CRYPT
    17981928                    if (ret == WC_PENDING_E) {
     
    18071937                case wolfssl_chacha:
    18081938                    ret = ChaCha20Poly1305_Decrypt(ssl, output, input, dataSz,
    1809                         ssl->decrypt.nonce, input + dataSz);
     1939                        ssl->decrypt.nonce, aad, aadSz, input + dataSz);
    18101940                    break;
    18111941            #endif
     
    19322062        case BUILD_MSG_BEGIN:
    19332063        {
    1934             if (output == NULL || input == NULL)
    1935                 return BAD_FUNC_ARG;
    19362064            /* catch mistaken sizeOnly parameter */
    1937             if (sizeOnly && (output || input)) {
    1938                 WOLFSSL_MSG("BuildTls13Message with sizeOnly doesn't need "
    1939                             "input or output");
     2065            if (sizeOnly) {
     2066                if (output || input) {
     2067                    WOLFSSL_MSG("BuildTls13Message with sizeOnly "
     2068                                "doesn't need input or output");
     2069                    return BAD_FUNC_ARG;
     2070                }
     2071            }
     2072            else if (output == NULL || input == NULL) {
    19402073                return BAD_FUNC_ARG;
    19412074            }
     
    19862119        {
    19872120            /* The real record content type goes at the end of the data. */
    1988             output[args->idx++] = type;
     2121            output[args->idx++] = (byte)type;
    19892122
    19902123        #ifdef ATOMIC_USER
     
    20002133        #endif
    20012134            {
     2135#if defined(WOLFSSL_TLS13_DRAFT_18) || defined(WOLFSSL_TLS13_DRAFT_22) || \
     2136                                       defined(WOLFSSL_TLS13_DRAFT_23)
    20022137                output += args->headerSz;
    2003                 ret = EncryptTls13(ssl, output, output, args->size, asyncOkay);
     2138                ret = EncryptTls13(ssl, output, output, args->size, NULL, 0,
     2139                                                                     asyncOkay);
     2140#else
     2141                const byte* aad = output;
     2142                output += args->headerSz;
     2143                ret = EncryptTls13(ssl, output, output, args->size, aad,
     2144                                   RECORD_HEADER_SZ, asyncOkay);
     2145#endif
    20042146            }
    20052147            break;
     
    20302172}
    20312173
    2032 #ifndef NO_WOLFSSL_CLIENT
    20332174#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
    2034 /* Setup pre-shared key based on the details in the extension data.
    2035  *
    2036  * ssl  SSL/TLS object.
    2037  * psk  Pre-shared key extension data.
    2038  * returns 0 on success, PSK_KEY_ERROR when the client PSK callback fails and
    2039  * other negative value on failure.
    2040  */
    2041 static int SetupPskKey(WOLFSSL* ssl, PreSharedKey* psk)
    2042 {
    2043     int ret;
    2044 
    2045     ssl->options.cipherSuite0 = psk->cipherSuite0;
    2046     ssl->options.cipherSuite  = psk->cipherSuite;
    2047     if ((ret = SetCipherSpecs(ssl)) != 0)
    2048         return ret;
    2049 
    2050 #ifdef HAVE_SESSION_TICKET
    2051     if (psk->resumption) {
    2052     #ifdef WOLFSSL_EARLY_DATA
    2053         if (ssl->session.maxEarlyDataSz == 0)
    2054             ssl->earlyData = 0;
    2055     #endif
    2056         /* Resumption PSK is master secret. */
    2057         ssl->arrays->psk_keySz = ssl->specs.hash_size;
    2058         XMEMCPY(ssl->arrays->psk_key, ssl->session.masterSecret,
    2059                 ssl->arrays->psk_keySz);
    2060     }
    2061 #endif
    2062 #ifndef NO_PSK
    2063     if (!psk->resumption) {
    2064         /* Get the pre-shared key. */
    2065         ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
    2066                 (char *)psk->identity, ssl->arrays->client_identity,
    2067                 MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
    2068         if (ssl->arrays->psk_keySz == 0 ||
    2069                                  ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
    2070             return PSK_KEY_ERROR;
     2175/* Find the cipher suite in the suites set in the SSL.
     2176 *
     2177 * ssl    SSL/TLS object.
     2178 * suite  Cipher suite to look for.
     2179 * returns 1 when suite is found in SSL/TLS object's list and 0 otherwise.
     2180 */
     2181static int FindSuite(WOLFSSL* ssl, byte* suite)
     2182{
     2183    int i;
     2184
     2185    for (i = 0; i < ssl->suites->suiteSz; i += 2) {
     2186        if (ssl->suites->suites[i+0] == suite[0] &&
     2187            ssl->suites->suites[i+1] == suite[1]) {
     2188            return 1;
    20712189        }
    20722190    }
    2073 #endif
    2074 
    2075     /* Derive the early secret using the PSK. */
    2076     return DeriveEarlySecret(ssl);
    2077 }
    2078 
    2079 /* Derive and write the binders into the ClientHello in space left when
    2080  * writing the Pre-Shared Key extension.
    2081  *
    2082  * ssl     The SSL/TLS object.
    2083  * output  The buffer containing the ClientHello.
    2084  * idx     The index at the end of the completed ClientHello.
    2085  * returns 0 on success and otherwise failure.
    2086  */
    2087 static int WritePSKBinders(WOLFSSL* ssl, byte* output, word32 idx)
    2088 {
    2089     int           ret;
    2090     TLSX*         ext;
    2091     PreSharedKey* current;
    2092     byte          binderKey[MAX_DIGEST_SIZE];
    2093     word16        len;
    2094 
    2095     ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
    2096     if (ext == NULL)
    2097         return SANITY_MSG_E;
    2098 
    2099     /* Get the size of the binders to determine where to write binders. */
    2100     idx -= TLSX_PreSharedKey_GetSizeBinders((PreSharedKey*)ext->data,
    2101                                             client_hello);
    2102 
    2103     /* Hash truncated ClientHello - up to binders. */
    2104     ret = HashOutput(ssl, output, idx, 0);
    2105     if (ret != 0)
    2106         return ret;
    2107 
    2108     current = (PreSharedKey*)ext->data;
    2109     /* Calculate the binder for each identity based on previous handshake data.
    2110      */
    2111     while (current != NULL) {
    2112         if ((ret = SetupPskKey(ssl, current)) != 0)
    2113             return ret;
    2114 
    2115     #ifdef HAVE_SESSION_TICKET
    2116         if (current->resumption)
    2117             ret = DeriveBinderKeyResume(ssl, binderKey);
    2118     #endif
    2119     #ifndef NO_PSK
    2120         if (!current->resumption)
    2121             ret = DeriveBinderKey(ssl, binderKey);
    2122     #endif
    2123         if (ret != 0)
    2124             return ret;
    2125 
    2126         /* Derive the Finished message secret. */
    2127         ret = DeriveFinishedSecret(ssl, binderKey,
    2128                                              ssl->keys.client_write_MAC_secret);
    2129         if (ret != 0)
    2130             return ret;
    2131 
    2132         /* Build the HMAC of the handshake message data = binder. */
    2133         ret = BuildTls13HandshakeHmac(ssl, ssl->keys.client_write_MAC_secret,
    2134             current->binder, &current->binderLen);
    2135         if (ret != 0)
    2136             return ret;
    2137 
    2138         current = current->next;
    2139     }
    2140 
    2141     /* Data entered into extension, now write to message. */
    2142     len = TLSX_PreSharedKey_WriteBinders((PreSharedKey*)ext->data, output + idx,
    2143                                          client_hello);
    2144 
    2145     /* Hash binders to complete the hash of the ClientHello. */
    2146     ret = HashOutputRaw(ssl, output + idx, len);
    2147     if (ret < 0)
    2148         return ret;
    2149 
    2150     #ifdef WOLFSSL_EARLY_DATA
    2151     if (ssl->earlyData) {
    2152         if ((ret = SetupPskKey(ssl, (PreSharedKey*)ext->data)) != 0)
    2153             return ret;
    2154 
    2155         /* Derive early data encryption key. */
    2156         ret = DeriveTls13Keys(ssl, early_data_key, ENCRYPT_SIDE_ONLY, 1);
    2157         if (ret != 0)
    2158             return ret;
    2159         if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
    2160             return ret;
    2161     }
    2162     #endif
    2163     return ret;
    2164 }
    2165 #endif
    2166 
    2167 /* Send a ClientHello message to the server.
    2168  * Include the information required to start a handshake with servers using
    2169  * protocol versions less than TLS v1.3.
    2170  * Only a client will send this message.
    2171  *
    2172  * ssl  The SSL/TLS object.
    2173  * returns 0 on success and otherwise failure.
    2174  */
    2175 int SendTls13ClientHello(WOLFSSL* ssl)
    2176 {
    2177     byte*  output;
    2178     word32 length;
    2179     word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
    2180     int    sendSz;
    2181     int    ret;
    2182 
    2183     WOLFSSL_ENTER("SendTls13ClientHello");
    2184 
    2185 #ifdef HAVE_SESSION_TICKET
    2186     if (ssl->options.resuming &&
    2187             (ssl->session.version.major != ssl->version.major ||
    2188              ssl->session.version.minor != ssl->version.minor)) {
    2189         /* Cannot resume with a different protocol version - new handshake. */
    2190         ssl->options.resuming = 0;
    2191         ssl->version.major = ssl->session.version.major;
    2192         ssl->version.minor = ssl->session.version.minor;
    2193         return SendClientHello(ssl);
    2194     }
    2195 #endif
    2196 
    2197     if (ssl->suites == NULL) {
    2198         WOLFSSL_MSG("Bad suites pointer in SendTls13ClientHello");
    2199         return SUITES_ERROR;
    2200     }
    2201 
    2202     /* Version | Random | Session Id | Cipher Suites | Compression | Ext  */
    2203     length = VERSION_SZ + RAN_LEN + ENUM_LEN + ssl->suites->suiteSz +
    2204              SUITE_LEN + COMP_LEN + ENUM_LEN;
    2205 
    2206     /* Auto populate extensions supported unless user defined. */
    2207     if ((ret = TLSX_PopulateExtensions(ssl, 0)) != 0)
    2208         return ret;
    2209 #ifdef WOLFSSL_EARLY_DATA
    2210     #ifndef NO_PSK
    2211         if (!ssl->options.resuming && ssl->options.client_psk_cb == NULL)
    2212     #else
    2213         if (!ssl->options.resuming)
    2214     #endif
    2215             ssl->earlyData = 0;
    2216     if (ssl->earlyData && (ret = TLSX_EarlyData_Use(ssl, 0)) < 0)
    2217         return ret;
    2218 #endif
    2219 #ifdef HAVE_QSH
    2220     if (QSH_Init(ssl) != 0)
    2221         return MEMORY_E;
    2222 #endif
    2223     /* Include length of TLS extensions. */
    2224     length += TLSX_GetRequestSize(ssl, client_hello);
    2225 
    2226     /* Total message size. */
    2227     sendSz = length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
    2228 
    2229     /* Check buffers are big enough and grow if needed. */
    2230     if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
    2231         return ret;
    2232 
    2233     /* Get position in output buffer to write new message to. */
    2234     output = ssl->buffers.outputBuffer.buffer +
    2235              ssl->buffers.outputBuffer.length;
    2236 
    2237     /* Put the record and handshake headers on. */
    2238     AddTls13Headers(output, length, client_hello, ssl);
    2239 
    2240     /* Protocol version. */
    2241     output[idx++] = SSLv3_MAJOR;
    2242     output[idx++] = TLSv1_2_MINOR;
    2243     ssl->chVersion = ssl->version;
    2244 
    2245     /* Client Random */
    2246     if (ssl->options.connectState == CONNECT_BEGIN) {
    2247         ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, RAN_LEN);
    2248         if (ret != 0)
    2249             return ret;
    2250 
    2251         /* Store random for possible second ClientHello. */
    2252         XMEMCPY(ssl->arrays->clientRandom, output + idx, RAN_LEN);
    2253     }
    2254     else
    2255         XMEMCPY(output + idx, ssl->arrays->clientRandom, RAN_LEN);
    2256     idx += RAN_LEN;
    2257 
    2258     /* TLS v1.3 does not use session id - 0 length. */
    2259     output[idx++] = 0;
    2260 
    2261     /* Cipher suites */
    2262     c16toa(ssl->suites->suiteSz, output + idx);
    2263     idx += OPAQUE16_LEN;
    2264     XMEMCPY(output + idx, &ssl->suites->suites, ssl->suites->suiteSz);
    2265     idx += ssl->suites->suiteSz;
    2266 
    2267     /* Compression not supported in TLS v1.3. */
    2268     output[idx++] = COMP_LEN;
    2269     output[idx++] = NO_COMPRESSION;
    2270 
    2271     /* Write out extensions for a request. */
    2272     idx += TLSX_WriteRequest(ssl, output + idx, client_hello);
    2273 
    2274 #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
    2275     /* Resumption has a specific set of extensions and binder is calculated
    2276      * for each identity.
    2277      */
    2278     if (TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY))
    2279         ret = WritePSKBinders(ssl, output, idx);
    2280     else
    2281 #endif
    2282         ret = HashOutput(ssl, output, idx, 0);
    2283     if (ret != 0)
    2284         return ret;
    2285 
    2286     ssl->options.clientState = CLIENT_HELLO_COMPLETE;
    2287 
    2288 #ifdef WOLFSSL_CALLBACKS
    2289     if (ssl->hsInfoOn) AddPacketName("ClientHello", &ssl->handShakeInfo);
    2290     if (ssl->toInfoOn) {
    2291         AddPacketInfo("ClientHello", &ssl->timeoutInfo, output, sendSz,
    2292                       ssl->heap);
    2293     }
    2294 #endif
    2295 
    2296     ssl->buffers.outputBuffer.length += sendSz;
    2297 
    2298     ret = SendBuffered(ssl);
    2299 
    2300     WOLFSSL_LEAVE("SendTls13ClientHello", ret);
    2301 
    2302     return ret;
    2303 }
     2191
     2192    return 0;
     2193}
     2194#endif
    23042195
    23052196#ifndef WOLFSSL_TLS13_DRAFT_18
    2306 #ifdef WOLFSSL_SEND_HRR_COOKIE
     2197#if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
    23072198/* Create Cookie extension using the hash of the first ClientHello.
    23082199 *
     
    23152206{
    23162207    int  ret;
    2317     byte mac[MAX_DIGEST_SIZE];
     2208    byte mac[WC_MAX_DIGEST_SIZE];
    23182209    Hmac cookieHmac;
    23192210    byte cookieType;
     
    23832274    WOLFSSL_BUFFER(hash, hashSz);
    23842275
    2385 #ifdef WOLFSSL_SEND_HRR_COOKIE
     2276#if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
    23862277    if (ssl->options.sendCookie) {
    2387         byte   cookie[OPAQUE8_LEN + MAX_DIGEST_SIZE + OPAQUE16_LEN * 2];
     2278        byte   cookie[OPAQUE8_LEN + WC_MAX_DIGEST_SIZE + OPAQUE16_LEN * 2];
    23882279        TLSX*  ext;
    23892280        word32 idx = 0;
     
    24122303    return HashOutputRaw(ssl, hash, hashSz);
    24132304}
    2414 #endif
    2415 
     2305
     2306/* The value in the random field of a ServerHello to indicate
     2307 * HelloRetryRequest.
     2308 */
     2309static byte helloRetryRequestRandom[] = {
     2310    0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
     2311    0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
     2312    0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
     2313    0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C
     2314};
     2315#endif /* WOLFSSL_TLS13_DRAFT_18 */
     2316
     2317#ifndef NO_WOLFSSL_CLIENT
     2318#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
     2319/* Setup pre-shared key based on the details in the extension data.
     2320 *
     2321 * ssl  SSL/TLS object.
     2322 * psk  Pre-shared key extension data.
     2323 * returns 0 on success, PSK_KEY_ERROR when the client PSK callback fails and
     2324 * other negative value on failure.
     2325 */
     2326static int SetupPskKey(WOLFSSL* ssl, PreSharedKey* psk)
     2327{
     2328    int ret;
     2329    byte suite[2];
     2330
     2331    if (ssl->options.noPskDheKe && ssl->arrays->preMasterSz != 0)
     2332        return PSK_KEY_ERROR;
     2333
     2334    suite[0] = psk->cipherSuite0;
     2335    suite[1] = psk->cipherSuite;
     2336    if (!FindSuite(ssl, suite))
     2337        return PSK_KEY_ERROR;
     2338
     2339    ssl->options.cipherSuite0 = psk->cipherSuite0;
     2340    ssl->options.cipherSuite  = psk->cipherSuite;
     2341    if ((ret = SetCipherSpecs(ssl)) != 0)
     2342        return ret;
     2343
     2344#ifdef HAVE_SESSION_TICKET
     2345    if (psk->resumption) {
     2346    #ifdef WOLFSSL_EARLY_DATA
     2347        if (ssl->session.maxEarlyDataSz == 0)
     2348            ssl->earlyData = no_early_data;
     2349    #endif
     2350        /* Resumption PSK is master secret. */
     2351        ssl->arrays->psk_keySz = ssl->specs.hash_size;
     2352#ifdef WOLFSSL_TLS13_DRAFT_18
     2353        XMEMCPY(ssl->arrays->psk_key, ssl->session.masterSecret,
     2354                ssl->arrays->psk_keySz);
     2355#else
     2356        if ((ret = DeriveResumptionPSK(ssl, ssl->session.ticketNonce.data,
     2357                    ssl->session.ticketNonce.len, ssl->arrays->psk_key)) != 0) {
     2358            return ret;
     2359        }
     2360#endif
     2361    }
     2362#endif
     2363#ifndef NO_PSK
     2364    if (!psk->resumption) {
     2365        const char* cipherName = NULL;
     2366        byte cipherSuite0 = TLS13_BYTE, cipherSuite = WOLFSSL_DEF_PSK_CIPHER;
     2367
     2368        /* Get the pre-shared key. */
     2369        if (ssl->options.client_psk_tls13_cb != NULL) {
     2370            ssl->arrays->psk_keySz = ssl->options.client_psk_tls13_cb(ssl,
     2371                    (char *)psk->identity, ssl->arrays->client_identity,
     2372                    MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN,
     2373                    &cipherName);
     2374            if (GetCipherSuiteFromName(cipherName, &cipherSuite0,
     2375                                                           &cipherSuite) != 0) {
     2376                return PSK_KEY_ERROR;
     2377            }
     2378        }
     2379        else {
     2380        ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
     2381                (char *)psk->identity, ssl->arrays->client_identity,
     2382                MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
     2383        }
     2384        if (ssl->arrays->psk_keySz == 0 ||
     2385                                 ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
     2386            return PSK_KEY_ERROR;
     2387        }
     2388
     2389        if (psk->cipherSuite0 != cipherSuite0 ||
     2390                                              psk->cipherSuite != cipherSuite) {
     2391            return PSK_KEY_ERROR;
     2392        }
     2393    }
     2394#endif
     2395
     2396    /* Derive the early secret using the PSK. */
     2397    return DeriveEarlySecret(ssl);
     2398}
     2399
     2400/* Derive and write the binders into the ClientHello in space left when
     2401 * writing the Pre-Shared Key extension.
     2402 *
     2403 * ssl     The SSL/TLS object.
     2404 * output  The buffer containing the ClientHello.
     2405 * idx     The index at the end of the completed ClientHello.
     2406 * returns 0 on success and otherwise failure.
     2407 */
     2408static int WritePSKBinders(WOLFSSL* ssl, byte* output, word32 idx)
     2409{
     2410    int           ret;
     2411    TLSX*         ext;
     2412    PreSharedKey* current;
     2413    byte          binderKey[WC_MAX_DIGEST_SIZE];
     2414    word16        len;
     2415
     2416    WOLFSSL_ENTER("WritePSKBinders");
     2417
     2418    ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
     2419    if (ext == NULL)
     2420        return SANITY_MSG_E;
     2421
     2422    /* Get the size of the binders to determine where to write binders. */
     2423    idx -= TLSX_PreSharedKey_GetSizeBinders((PreSharedKey*)ext->data,
     2424                                            client_hello);
     2425
     2426    /* Hash truncated ClientHello - up to binders. */
     2427    ret = HashOutput(ssl, output, idx, 0);
     2428    if (ret != 0)
     2429        return ret;
     2430
     2431    current = (PreSharedKey*)ext->data;
     2432    /* Calculate the binder for each identity based on previous handshake data.
     2433     */
     2434    while (current != NULL) {
     2435        if ((ret = SetupPskKey(ssl, current)) != 0)
     2436            return ret;
     2437
     2438    #ifdef HAVE_SESSION_TICKET
     2439        if (current->resumption)
     2440            ret = DeriveBinderKeyResume(ssl, binderKey);
     2441    #endif
     2442    #ifndef NO_PSK
     2443        if (!current->resumption)
     2444            ret = DeriveBinderKey(ssl, binderKey);
     2445    #endif
     2446        if (ret != 0)
     2447            return ret;
     2448
     2449        /* Derive the Finished message secret. */
     2450        ret = DeriveFinishedSecret(ssl, binderKey,
     2451                                             ssl->keys.client_write_MAC_secret);
     2452        if (ret != 0)
     2453            return ret;
     2454
     2455        /* Build the HMAC of the handshake message data = binder. */
     2456        ret = BuildTls13HandshakeHmac(ssl, ssl->keys.client_write_MAC_secret,
     2457            current->binder, &current->binderLen);
     2458        if (ret != 0)
     2459            return ret;
     2460
     2461        current = current->next;
     2462    }
     2463
     2464    /* Data entered into extension, now write to message. */
     2465    len = TLSX_PreSharedKey_WriteBinders((PreSharedKey*)ext->data, output + idx,
     2466                                         client_hello);
     2467
     2468    /* Hash binders to complete the hash of the ClientHello. */
     2469    ret = HashOutputRaw(ssl, output + idx, len);
     2470    if (ret < 0)
     2471        return ret;
     2472
     2473    #ifdef WOLFSSL_EARLY_DATA
     2474    if (ssl->earlyData != no_early_data) {
     2475        if ((ret = SetupPskKey(ssl, (PreSharedKey*)ext->data)) != 0)
     2476            return ret;
     2477
     2478        /* Derive early data encryption key. */
     2479        ret = DeriveTls13Keys(ssl, early_data_key, ENCRYPT_SIDE_ONLY, 1);
     2480        if (ret != 0)
     2481            return ret;
     2482        if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
     2483            return ret;
     2484    }
     2485    #endif
     2486
     2487    WOLFSSL_LEAVE("WritePSKBinders", ret);
     2488
     2489    return ret;
     2490}
     2491#endif
     2492
     2493/* handle generation of TLS 1.3 client_hello (1) */
     2494/* Send a ClientHello message to the server.
     2495 * Include the information required to start a handshake with servers using
     2496 * protocol versions less than TLS v1.3.
     2497 * Only a client will send this message.
     2498 *
     2499 * ssl  The SSL/TLS object.
     2500 * returns 0 on success and otherwise failure.
     2501 */
     2502int SendTls13ClientHello(WOLFSSL* ssl)
     2503{
     2504    byte*  output;
     2505    word16 length;
     2506    word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
     2507    int    sendSz;
     2508    int    ret;
     2509
     2510    WOLFSSL_START(WC_FUNC_CLIENT_HELLO_SEND);
     2511    WOLFSSL_ENTER("SendTls13ClientHello");
     2512
     2513#ifdef HAVE_SESSION_TICKET
     2514    if (ssl->options.resuming &&
     2515            (ssl->session.version.major != ssl->version.major ||
     2516             ssl->session.version.minor != ssl->version.minor)) {
     2517    #ifndef WOLFSSL_NO_TLS12
     2518        if (ssl->session.version.major == ssl->version.major &&
     2519            ssl->session.version.minor < ssl->version.minor) {
     2520            /* Cannot resume with a different protocol version. */
     2521        ssl->options.resuming = 0;
     2522        ssl->version.major = ssl->session.version.major;
     2523        ssl->version.minor = ssl->session.version.minor;
     2524        return SendClientHello(ssl);
     2525    }
     2526        else
     2527    #endif
     2528            return VERSION_ERROR;
     2529    }
     2530#endif
     2531
     2532    if (ssl->suites == NULL) {
     2533        WOLFSSL_MSG("Bad suites pointer in SendTls13ClientHello");
     2534        return SUITES_ERROR;
     2535    }
     2536
     2537    /* Version | Random | Session Id | Cipher Suites | Compression */
     2538    length = VERSION_SZ + RAN_LEN + ENUM_LEN + ssl->suites->suiteSz +
     2539             SUITE_LEN + COMP_LEN + ENUM_LEN;
     2540#ifndef WOLFSSL_TLS13_DRAFT_18
     2541    #if defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
     2542    length += ID_LEN;
     2543    #else
     2544    if (ssl->session.sessionIDSz > 0)
     2545        length += ssl->session.sessionIDSz;
     2546    #endif
     2547#endif
     2548
     2549    /* Auto populate extensions supported unless user defined. */
     2550    if ((ret = TLSX_PopulateExtensions(ssl, 0)) != 0)
     2551        return ret;
     2552#ifdef WOLFSSL_EARLY_DATA
     2553    #ifndef NO_PSK
     2554        if (!ssl->options.resuming &&
     2555                                     ssl->options.client_psk_tls13_cb == NULL &&
     2556                                     ssl->options.client_psk_cb == NULL)
     2557    #else
     2558        if (!ssl->options.resuming)
     2559    #endif
     2560            ssl->earlyData = no_early_data;
     2561    if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE)
     2562        ssl->earlyData = no_early_data;
     2563    if (ssl->earlyData == no_early_data)
     2564        TLSX_Remove(&ssl->extensions, TLSX_EARLY_DATA, ssl->heap);
     2565    if (ssl->earlyData != no_early_data &&
     2566                                       (ret = TLSX_EarlyData_Use(ssl, 0)) < 0) {
     2567        return ret;
     2568    }
     2569#endif
     2570#ifdef HAVE_QSH
     2571    if (QSH_Init(ssl) != 0)
     2572        return MEMORY_E;
     2573#endif
     2574    /* Include length of TLS extensions. */
     2575    ret = TLSX_GetRequestSize(ssl, client_hello, &length);
     2576    if (ret != 0)
     2577        return ret;
     2578
     2579    /* Total message size. */
     2580    sendSz = length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
     2581
     2582    /* Check buffers are big enough and grow if needed. */
     2583    if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
     2584        return ret;
     2585
     2586    /* Get position in output buffer to write new message to. */
     2587    output = ssl->buffers.outputBuffer.buffer +
     2588             ssl->buffers.outputBuffer.length;
     2589
     2590    /* Put the record and handshake headers on. */
     2591    AddTls13Headers(output, length, client_hello, ssl);
     2592
     2593    /* Protocol version - negotiation now in extension: supported_versions. */
     2594    output[idx++] = SSLv3_MAJOR;
     2595    output[idx++] = TLSv1_2_MINOR;
     2596    /* Keep for downgrade. */
     2597    ssl->chVersion = ssl->version;
     2598
     2599    /* Client Random */
     2600    if (ssl->options.connectState == CONNECT_BEGIN) {
     2601        ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, RAN_LEN);
     2602        if (ret != 0)
     2603            return ret;
     2604
     2605        /* Store random for possible second ClientHello. */
     2606        XMEMCPY(ssl->arrays->clientRandom, output + idx, RAN_LEN);
     2607    }
     2608    else
     2609        XMEMCPY(output + idx, ssl->arrays->clientRandom, RAN_LEN);
     2610    idx += RAN_LEN;
     2611
     2612#ifdef WOLFSSL_TLS13_DRAFT_18
     2613    /* TLS v1.3 does not use session id - 0 length. */
     2614    output[idx++] = 0;
     2615#else
     2616    if (ssl->session.sessionIDSz > 0) {
     2617        /* Session resumption for old versions of protocol. */
     2618        output[idx++] = ID_LEN;
     2619        XMEMCPY(output + idx, ssl->session.sessionID, ssl->session.sessionIDSz);
     2620        idx += ID_LEN;
     2621    }
     2622    else {
     2623    #ifdef WOLFSSL_TLS13_MIDDLEBOX_COMPAT
     2624        output[idx++] = ID_LEN;
     2625        XMEMCPY(output + idx, ssl->arrays->clientRandom, ID_LEN);
     2626        idx += ID_LEN;
     2627    #else
     2628    /* TLS v1.3 does not use session id - 0 length. */
     2629    output[idx++] = 0;
     2630    #endif /* WOLFSSL_TLS13_MIDDLEBOX_COMPAT */
     2631    }
     2632#endif /* WOLFSSL_TLS13_DRAFT_18 */
     2633
     2634    /* Cipher suites */
     2635    c16toa(ssl->suites->suiteSz, output + idx);
     2636    idx += OPAQUE16_LEN;
     2637    XMEMCPY(output + idx, &ssl->suites->suites, ssl->suites->suiteSz);
     2638    idx += ssl->suites->suiteSz;
     2639
     2640    /* Compression not supported in TLS v1.3. */
     2641    output[idx++] = COMP_LEN;
     2642    output[idx++] = NO_COMPRESSION;
     2643
     2644    /* Write out extensions for a request. */
     2645    length = 0;
     2646    ret = TLSX_WriteRequest(ssl, output + idx, client_hello, &length);
     2647    if (ret != 0)
     2648        return ret;
     2649    idx += length;
     2650
     2651#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
     2652    /* Resumption has a specific set of extensions and binder is calculated
     2653     * for each identity.
     2654     */
     2655    if (TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY))
     2656        ret = WritePSKBinders(ssl, output, idx);
     2657    else
     2658#endif
     2659        ret = HashOutput(ssl, output, idx, 0);
     2660    if (ret != 0)
     2661        return ret;
     2662
     2663    ssl->options.clientState = CLIENT_HELLO_COMPLETE;
     2664
     2665#ifdef WOLFSSL_CALLBACKS
     2666    if (ssl->hsInfoOn) AddPacketName(ssl, "ClientHello");
     2667    if (ssl->toInfoOn) {
     2668        AddPacketInfo(ssl, "ClientHello", handshake, output, sendSz,
     2669                      WRITE_PROTO, ssl->heap);
     2670    }
     2671#endif
     2672
     2673    ssl->buffers.outputBuffer.length += sendSz;
     2674
     2675#ifdef WOLFSSL_EARLY_DATA_GROUP
     2676    if (ssl->earlyData == no_early_data)
     2677#endif
     2678    ret = SendBuffered(ssl);
     2679
     2680
     2681    WOLFSSL_LEAVE("SendTls13ClientHello", ret);
     2682    WOLFSSL_END(WC_FUNC_CLIENT_HELLO_SEND);
     2683
     2684    return ret;
     2685}
     2686
     2687#ifdef WOLFSSL_TLS13_DRAFT_18
     2688/* handle rocessing of TLS 1.3 hello_retry_request (6) */
    24162689/* Parse and handle a HelloRetryRequest message.
    24172690 * Only a client will receive this message.
     
    24372710
    24382711#ifdef WOLFSSL_CALLBACKS
    2439     if (ssl->hsInfoOn) AddPacketName("HelloRetryRequest", &ssl->handShakeInfo);
     2712    if (ssl->hsInfoOn) AddPacketName(ssl, "HelloRetryRequest");
    24402713    if (ssl->toInfoOn) AddLateName("HelloRetryRequest", &ssl->timeoutInfo);
    24412714#endif
     
    24512724    if (ret != 0)
    24522725        return ret;
    2453 
    2454 #ifndef WOLFSSL_TLS13_DRAFT_18
    2455     /* Set the cipher suite from the message. */
    2456     ssl->options.cipherSuite0 = input[i++];
    2457     ssl->options.cipherSuite  = input[i++];
    2458 
    2459     ret = SetCipherSpecs(ssl);
    2460     if (ret != 0)
    2461         return ret;
    2462 #endif
    24632726
    24642727    /* Length of extension data. */
     
    24822745
    24832746    ssl->options.tls1_3 = 1;
    2484     ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST;
    2485 
    2486 #ifndef WOLFSSL_TLS13_DRAFT_18
    2487     ret = RestartHandshakeHash(ssl);
    2488 #endif
     2747    ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
    24892748
    24902749    WOLFSSL_LEAVE("DoTls13HelloRetryRequest", ret);
     
    24922751    return ret;
    24932752}
    2494 
     2753#endif
     2754
     2755
     2756/* handle processing of TLS 1.3 server_hello (2) and hello_retry_request (6) */
    24952757/* Handle the ServerHello message from the server.
    24962758 * Only a client will receive this message.
     
    25042766 */
    25052767int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
    2506                        word32 helloSz)
     2768                       word32 helloSz, byte* extMsgType)
    25072769{
    25082770    ProtocolVersion pv;
     
    25102772    word32          begin = i;
    25112773    int             ret;
     2774#ifndef WOLFSSL_TLS13_DRAFT_18
     2775    byte            sessIdSz;
     2776    const byte*     sessId;
     2777    byte            b;
     2778#endif
    25122779    word16          totalExtSz;
    25132780#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
     
    25162783#endif
    25172784
     2785    WOLFSSL_START(WC_FUNC_SERVER_HELLO_DO);
    25182786    WOLFSSL_ENTER("DoTls13ServerHello");
    25192787
    25202788#ifdef WOLFSSL_CALLBACKS
    2521     if (ssl->hsInfoOn) AddPacketName("ServerHello", &ssl->handShakeInfo);
     2789    if (ssl->hsInfoOn) AddPacketName(ssl, "ServerHello");
    25222790    if (ssl->toInfoOn) AddLateName("ServerHello", &ssl->timeoutInfo);
    25232791#endif
     
    25302798    XMEMCPY(&pv, input + i, OPAQUE16_LEN);
    25312799    i += OPAQUE16_LEN;
     2800#ifdef WOLFSSL_TLS13_DRAFT_18
    25322801    ret = CheckVersion(ssl, pv);
    25332802    if (ret != 0)
    25342803        return ret;
    25352804    if (!IsAtLeastTLSv1_3(pv) && pv.major != TLS_DRAFT_MAJOR) {
     2805#ifndef WOLFSSL_NO_TLS12
    25362806        if (ssl->options.downgrade) {
    25372807            ssl->version = pv;
    25382808            return DoServerHello(ssl, input, inOutIdx, helloSz);
    25392809        }
    2540 
    2541         WOLFSSL_MSG("CLient using higher version, fatal error");
     2810#endif
     2811
     2812        WOLFSSL_MSG("Client using higher version, fatal error");
    25422813        return VERSION_ERROR;
    25432814    }
    2544 
    2545     /* Random, cipher suite and extensions length check. */
    2546     if ((i - begin) + RAN_LEN + OPAQUE16_LEN + OPAQUE16_LEN > helloSz)
     2815#else
     2816#ifndef WOLFSSL_NO_TLS12
     2817    if (pv.major == ssl->version.major  && pv.minor < TLSv1_2_MINOR &&
     2818                                                       ssl->options.downgrade) {
     2819        /* Force client hello version 1.2 to work for static RSA. */
     2820        ssl->chVersion.minor = TLSv1_2_MINOR;
     2821        ssl->version.minor = TLSv1_2_MINOR;
     2822        return DoServerHello(ssl, input, inOutIdx, helloSz);
     2823    }
     2824#endif
     2825    if (pv.major != ssl->version.major || pv.minor != TLSv1_2_MINOR)
     2826        return VERSION_ERROR;
     2827#endif
     2828
     2829#ifdef WOLFSSL_TLS13_DRAFT_18
     2830    /* Random length check */
     2831    if ((i - begin) + RAN_LEN > helloSz)
    25472832        return BUFFER_ERROR;
     2833#else
     2834    /* Random and session id length check */
     2835    if ((i - begin) + RAN_LEN + ENUM_LEN > helloSz)
     2836        return BUFFER_ERROR;
     2837
     2838    if (XMEMCMP(input + i, helloRetryRequestRandom, RAN_LEN) == 0)
     2839        *extMsgType = hello_retry_request;
     2840#endif
    25482841
    25492842    /* Server random - keep for debugging. */
     
    25512844    i += RAN_LEN;
    25522845
     2846#ifndef WOLFSSL_TLS13_DRAFT_18
     2847    /* Session id */
     2848    sessIdSz = input[i++];
     2849    if ((i - begin) + sessIdSz > helloSz)
     2850        return BUFFER_ERROR;
     2851    sessId = input + i;
     2852    i += sessIdSz;
     2853#endif /* WOLFSSL_TLS13_DRAFT_18 */
     2854    ssl->options.haveSessionId = 1;
     2855
     2856#ifdef WOLFSSL_TLS13_DRAFT_18
     2857    /* Ciphersuite check */
     2858    if ((i - begin) + OPAQUE16_LEN + OPAQUE16_LEN > helloSz)
     2859        return BUFFER_ERROR;
     2860#else
     2861    /* Ciphersuite and compression check */
     2862    if ((i - begin) + OPAQUE16_LEN + OPAQUE8_LEN > helloSz)
     2863        return BUFFER_ERROR;
     2864#endif
     2865
    25532866    /* Set the cipher suite from the message. */
    25542867    ssl->options.cipherSuite0 = input[i++];
    25552868    ssl->options.cipherSuite  = input[i++];
    25562869
     2870#ifndef WOLFSSL_TLS13_DRAFT_18
     2871    /* Compression */
     2872    b = input[i++];
     2873    if (b != 0) {
     2874        WOLFSSL_MSG("Must be no compression types in list");
     2875        return INVALID_PARAMETER;
     2876    }
     2877#endif
     2878
     2879#ifndef WOLFSSL_TLS13_DRAFT_18
     2880    if ((i - begin) + OPAQUE16_LEN > helloSz) {
     2881        if (!ssl->options.downgrade)
     2882            return BUFFER_ERROR;
     2883#ifndef WOLFSSL_NO_TLS12
     2884        ssl->version.minor = TLSv1_2_MINOR;
     2885#endif
     2886        ssl->options.haveEMS = 0;
     2887    }
     2888    if ((i - begin) < helloSz)
     2889#endif
     2890    {
    25572891    /* Get extension length and length check. */
     2892        if ((i - begin) + OPAQUE16_LEN > helloSz)
     2893            return BUFFER_ERROR;
    25582894    ato16(&input[i], &totalExtSz);
    25592895    i += OPAQUE16_LEN;
     
    25612897        return BUFFER_ERROR;
    25622898
     2899#ifndef WOLFSSL_TLS13_DRAFT_18
     2900        if (ssl->options.downgrade)
     2901            ssl->version.minor = TLSv1_2_MINOR;
     2902#endif
    25632903    /* Parse and handle extensions. */
    2564     ret = TLSX_Parse(ssl, (byte *) input + i, totalExtSz, server_hello, NULL);
     2904        ret = TLSX_Parse(ssl, (byte *) input + i, totalExtSz, *extMsgType,
     2905                                                                          NULL);
    25652906    if (ret != 0)
    25662907        return ret;
    25672908
    25682909    i += totalExtSz;
     2910    }
    25692911    *inOutIdx = i;
    25702912
     
    25812923#endif /* HAVE_SECRET_CALLBACK */
    25822924
     2925#ifndef WOLFSSL_TLS13_DRAFT_18
     2926    /* Version only negotiated in extensions for TLS v1.3.
     2927     * Only now do we know how to deal with session id.
     2928     */
     2929    if (!IsAtLeastTLSv1_3(ssl->version)) {
     2930#ifndef WOLFSSL_NO_TLS12
     2931        ssl->arrays->sessionIDSz = sessIdSz;
     2932
     2933        if (ssl->arrays->sessionIDSz > ID_LEN) {
     2934            WOLFSSL_MSG("Invalid session ID size");
     2935            ssl->arrays->sessionIDSz = 0;
     2936            return BUFFER_ERROR;
     2937        }
     2938        else if (ssl->arrays->sessionIDSz) {
     2939            XMEMCPY(ssl->arrays->sessionID, sessId, ssl->arrays->sessionIDSz);
     2940            ssl->options.haveSessionId = 1;
     2941        }
     2942
     2943        /* Force client hello version 1.2 to work for static RSA. */
     2944        ssl->chVersion.minor = TLSv1_2_MINOR;
     2945        /* Complete TLS v1.2 processing of ServerHello. */
     2946        ret = CompleteServerHello(ssl);
     2947#else
     2948        WOLFSSL_MSG("Client using higher version, fatal error");
     2949        ret = VERSION_ERROR;
     2950#endif
     2951
     2952        WOLFSSL_LEAVE("DoTls13ServerHello", ret);
     2953
     2954        return ret;
     2955    }
     2956
     2957    #ifdef WOLFSSL_TLS13_MIDDLEBOX_COMPAT
     2958    if (sessIdSz == 0)
     2959        return INVALID_PARAMETER;
     2960    if (ssl->session.sessionIDSz != 0) {
     2961        if (ssl->session.sessionIDSz != sessIdSz ||
     2962                   XMEMCMP(ssl->session.sessionID, sessId, sessIdSz) != 0) {
     2963            return INVALID_PARAMETER;
     2964        }
     2965    }
     2966    else if (XMEMCMP(ssl->arrays->clientRandom, sessId, sessIdSz) != 0)
     2967        return INVALID_PARAMETER;
     2968    #else
     2969    if (sessIdSz != ssl->session.sessionIDSz || (sessIdSz > 0 &&
     2970                  XMEMCMP(ssl->session.sessionID, sessId, sessIdSz) != 0)) {
     2971        WOLFSSL_MSG("Server sent different session id");
     2972        return INVALID_PARAMETER;
     2973    }
     2974    #endif /* WOLFSSL_TLS13_MIDDLEBOX_COMPAT */
     2975#endif
     2976
    25832977    ret = SetCipherSpecs(ssl);
    25842978    if (ret != 0)
     
    25862980
    25872981#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
     2982#ifndef WOLFSSL_TLS13_DRAFT_18
     2983    if (*extMsgType == server_hello)
     2984#endif
     2985    {
    25882986    ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
    25892987    if (ext != NULL)
     
    25982996    else if ((ret = SetupPskKey(ssl, psk)) != 0)
    25992997        return ret;
    2600 #endif
    2601 
     2998    }
     2999#endif
     3000
     3001#ifdef WOLFSSL_TLS13_DRAFT_18
    26023002    ssl->keys.encryptionOn = 1;
     3003#else
     3004    if (*extMsgType == server_hello) {
     3005    ssl->keys.encryptionOn = 1;
     3006        ssl->options.serverState = SERVER_HELLO_COMPLETE;
     3007    }
     3008    else {
     3009        ssl->options.tls1_3 = 1;
     3010        ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
     3011
     3012        ret = RestartHandshakeHash(ssl);
     3013    }
     3014#endif
    26033015
    26043016    WOLFSSL_LEAVE("DoTls13ServerHello", ret);
     3017    WOLFSSL_END(WC_FUNC_SERVER_HELLO_DO);
    26053018
    26063019    return ret;
    26073020}
    26083021
     3022/* handle processing TLS 1.3 encrypted_extensions (8) */
    26093023/* Parse and handle an EncryptedExtensions message.
    26103024 * Only a client will receive this message.
     
    26273041    word16 totalExtSz;
    26283042
     3043    WOLFSSL_START(WC_FUNC_ENCRYPTED_EXTENSIONS_DO);
    26293044    WOLFSSL_ENTER("DoTls13EncryptedExtensions");
    26303045
    26313046#ifdef WOLFSSL_CALLBACKS
    2632     if (ssl->hsInfoOn) AddPacketName("EncryptedExtensions",
    2633                                      &ssl->handShakeInfo);
     3047    if (ssl->hsInfoOn) AddPacketName(ssl, "EncryptedExtensions");
    26343048    if (ssl->toInfoOn) AddLateName("EncryptedExtensions", &ssl->timeoutInfo);
    26353049#endif
     
    26553069
    26563070#ifdef WOLFSSL_EARLY_DATA
    2657     if (ssl->earlyData) {
     3071    if (ssl->earlyData != no_early_data) {
    26583072        TLSX* ext = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
    26593073        if (ext == NULL || !ext->val)
    2660             ssl->earlyData = 0;
    2661     }
    2662 #endif
     3074            ssl->earlyData = no_early_data;
     3075    }
     3076#endif
     3077
     3078#ifdef WOLFSSL_EARLY_DATA
     3079    if (ssl->earlyData == no_early_data) {
     3080        ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY);
     3081        if (ret != 0)
     3082            return ret;
     3083    }
     3084#endif
     3085
     3086    ssl->options.serverState = SERVER_ENCRYPTED_EXTENSIONS_COMPLETE;
    26633087
    26643088    WOLFSSL_LEAVE("DoTls13EncryptedExtensions", ret);
     3089    WOLFSSL_END(WC_FUNC_ENCRYPTED_EXTENSIONS_DO);
    26653090
    26663091    return ret;
    26673092}
    26683093
     3094/* handle processing TLS v1.3 certificate_request (13) */
    26693095/* Handle a TLS v1.3 CertificateRequest message.
    26703096 * This message is always encrypted.
     
    26913117#endif
    26923118
     3119    WOLFSSL_START(WC_FUNC_CERTIFICATE_REQUEST_DO);
    26933120    WOLFSSL_ENTER("DoTls13CertificateRequest");
    26943121
    26953122#ifdef WOLFSSL_CALLBACKS
    2696     if (ssl->hsInfoOn) AddPacketName("CertificateRequest", &ssl->handShakeInfo);
     3123    if (ssl->hsInfoOn) AddPacketName(ssl, "CertificateRequest");
    26973124    if (ssl->toInfoOn) AddLateName("CertificateRequest", &ssl->timeoutInfo);
    26983125#endif
     
    27993226    *inOutIdx += ssl->keys.padSz;
    28003227
    2801 #if !defined(NO_WOLFSSL_CLIENT) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
    2802     if (ssl->options.side == WOLFSSL_CLIENT_END &&
    2803                                 ssl->options.handShakeState == HANDSHAKE_DONE) {
    2804         /* reset handshake states */
    2805         ssl->options.clientState = CLIENT_HELLO_COMPLETE;
    2806         ssl->options.connectState  = FIRST_REPLY_DONE;
    2807         ssl->options.handShakeState = CLIENT_HELLO_COMPLETE;
    2808     }
    2809 #endif
    2810 
    28113228    WOLFSSL_LEAVE("DoTls13CertificateRequest", ret);
     3229    WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_DO);
    28123230
    28133231    return ret;
     
    28183236#ifndef NO_WOLFSSL_SERVER
    28193237#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
     3238/* Refine list of supported cipher suites to those common to server and client.
     3239 *
     3240 * ssl         SSL/TLS object.
     3241 * peerSuites  The peer's advertised list of supported cipher suites.
     3242 */
     3243static void RefineSuites(WOLFSSL* ssl, Suites* peerSuites)
     3244{
     3245    byte suites[WOLFSSL_MAX_SUITE_SZ];
     3246    int suiteSz = 0;
     3247    int i, j;
     3248
     3249    for (i = 0; i < ssl->suites->suiteSz; i += 2) {
     3250        for (j = 0; j < peerSuites->suiteSz; j += 2) {
     3251            if (ssl->suites->suites[i+0] == peerSuites->suites[j+0] &&
     3252                ssl->suites->suites[i+1] == peerSuites->suites[j+1]) {
     3253                suites[suiteSz++] = peerSuites->suites[j+0];
     3254                suites[suiteSz++] = peerSuites->suites[j+1];
     3255            }
     3256        }
     3257    }
     3258
     3259    ssl->suites->suiteSz = suiteSz;
     3260    XMEMCPY(ssl->suites->suites, &suites, sizeof(suites));
     3261}
     3262
    28203263/* Handle any Pre-Shared Key (PSK) extension.
    28213264 * Must do this in ClientHello as it requires a hash of the truncated message.
     
    28353278    word16        bindersLen;
    28363279    PreSharedKey* current;
    2837     byte          binderKey[MAX_DIGEST_SIZE];
    2838     byte          binder[MAX_DIGEST_SIZE];
     3280    byte          binderKey[WC_MAX_DIGEST_SIZE];
     3281    byte          binder[WC_MAX_DIGEST_SIZE];
    28393282    word32        binderLen;
    28403283    word16        modes;
     3284    byte          suite[2];
    28413285#ifdef WOLFSSL_EARLY_DATA
    28423286    int           pskCnt = 0;
    28433287    TLSX*         extEarlyData;
    28443288#endif
     3289#ifndef NO_PSK
     3290    const char*   cipherName = NULL;
     3291    byte          cipherSuite0 = TLS13_BYTE;
     3292    byte          cipherSuite  = WOLFSSL_DEF_PSK_CIPHER;
     3293#endif
     3294
     3295    WOLFSSL_ENTER("DoPreSharedKeys");
    28453296
    28463297    ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
    28473298    if (ext == NULL) {
    28483299#ifdef WOLFSSL_EARLY_DATA
    2849         ssl->earlyData = 0;
     3300        ssl->earlyData = no_early_data;
    28503301#endif
    28513302        return 0;
     
    29053356            }
    29063357
     3358            /* Check whether resumption is possible based on suites in SSL and
     3359             * ciphersuite in ticket.
     3360             */
     3361            suite[0] = ssl->session.cipherSuite0;
     3362            suite[1] = ssl->session.cipherSuite;
     3363            if (!FindSuite(ssl, suite)) {
     3364                current = current->next;
     3365                continue;
     3366            }
     3367
    29073368        #ifdef WOLFSSL_EARLY_DATA
    29083369            ssl->options.maxEarlyDataSz = ssl->session.maxEarlyDataSz;
     
    29173378            /* Resumption PSK is resumption master secret. */
    29183379            ssl->arrays->psk_keySz = ssl->specs.hash_size;
     3380        #ifdef WOLFSSL_TLS13_DRAFT_18
    29193381            XMEMCPY(ssl->arrays->psk_key, ssl->session.masterSecret,
    2920                     ssl->specs.hash_size);
     3382                    ssl->arrays->psk_keySz);
     3383        #else
     3384            if ((ret = DeriveResumptionPSK(ssl, ssl->session.ticketNonce.data,
     3385                    ssl->session.ticketNonce.len, ssl->arrays->psk_key)) != 0) {
     3386                return ret;
     3387            }
     3388        #endif
    29213389
    29223390            /* Derive the early secret using the PSK. */
     
    29323400    #endif
    29333401    #ifndef NO_PSK
    2934         if (ssl->options.server_psk_cb != NULL &&
     3402        if ((ssl->options.server_psk_tls13_cb != NULL &&
     3403             (ssl->arrays->psk_keySz = ssl->options.server_psk_tls13_cb(ssl,
     3404                             ssl->arrays->client_identity, ssl->arrays->psk_key,
     3405                             MAX_PSK_KEY_LEN, &cipherName)) != 0 &&
     3406             GetCipherSuiteFromName(cipherName, &cipherSuite0,
     3407                                                          &cipherSuite) == 0) ||
     3408            (ssl->options.server_psk_cb != NULL &&
    29353409            (ssl->arrays->psk_keySz = ssl->options.server_psk_cb(ssl,
    29363410                             ssl->arrays->client_identity, ssl->arrays->psk_key,
    2937                              MAX_PSK_KEY_LEN)) != 0) {
     3411                             MAX_PSK_KEY_LEN)) != 0)) {
    29383412            if (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN)
    29393413                return PSK_KEY_ERROR;
    29403414
     3415            /* Check whether PSK ciphersuite is in SSL. */
     3416            suite[0] = cipherSuite0;
     3417            suite[1] = cipherSuite;
     3418            if (!FindSuite(ssl, suite)) {
     3419                current = current->next;
     3420                continue;
     3421            }
     3422
     3423            /* Default to ciphersuite if cb doesn't specify. */
    29413424            ssl->options.resuming = 0;
    29423425
     
    29453428                return PSK_KEY_ERROR;
    29463429
    2947             /* TODO: Callback should be able to change ciphersuite. */
    2948             /* Default to ciphersuite if cb doesn't specify. */
    2949             ssl->options.cipherSuite0 = TLS13_BYTE;
    2950             ssl->options.cipherSuite  = WOLFSSL_DEF_PSK_CIPHER;
     3430            /* Set PSK ciphersuite into SSL. */
     3431            ssl->options.cipherSuite0 = cipherSuite0;
     3432            ssl->options.cipherSuite  = cipherSuite;
    29513433            ret = SetCipherSpecs(ssl);
    29523434            if (ret != 0)
     
    29933475    }
    29943476
     3477    if (current == NULL) {
     3478#ifdef WOLFSSL_PSK_ID_PROTECTION
     3479    #ifndef NO_CERTS
     3480        if (ssl->buffers.certChainCnt != 0)
     3481            return 0;
     3482    #endif
     3483        return BAD_BINDER;
     3484#else
     3485        return 0;
     3486#endif
     3487    }
     3488
    29953489    /* Hash the rest of the ClientHello. */
    29963490    ret = HashInputRaw(ssl, input + helloSz - bindersLen, bindersLen);
     
    30013495    extEarlyData = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
    30023496    if (extEarlyData != NULL) {
    3003         if (ssl->earlyData && current == ext->data) {
     3497        if (ssl->earlyData != no_early_data && current == ext->data) {
    30043498            extEarlyData->resp = 1;
    30053499
     
    30113505                return ret;
    30123506
    3013             ssl->earlyData = 2;
     3507            ssl->earlyData = process_early_data;
    30143508        }
    30153509        else
     
    30313525        ssl->namedGroup = ssl->session.namedGroup;
    30323526
    3033         /* Try to establish a new secret. */
     3527        /* Pick key share and Generate a new key if not present. */
    30343528        ret = TLSX_KeyShare_Establish(ssl);
    3035         if (ret == KEY_SHARE_ERROR)
    3036             return PSK_KEY_ERROR;
     3529        if (ret == KEY_SHARE_ERROR) {
     3530            ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST_COMPLETE;
     3531            ret = 0;
     3532        }
    30373533        else if (ret < 0)
    30383534            return ret;
     
    30413537        ext->resp = 1;
    30423538    }
    3043     else if ((modes & (1 << PSK_KE)) == 0)
     3539    else {
     3540        if ((modes & (1 << PSK_KE)) == 0)
    30443541        return PSK_KEY_ERROR;
     3542        ssl->options.noPskDheKe = 1;
     3543    }
    30453544
    30463545    *usingPSK = 1;
     3546
     3547    WOLFSSL_LEAVE("DoPreSharedKeys", ret);
    30473548
    30483549    return ret;
     
    30613562{
    30623563    int  ret;
    3063     byte mac[MAX_DIGEST_SIZE];
     3564    byte mac[WC_MAX_DIGEST_SIZE];
    30643565    Hmac cookieHmac;
    30653566    byte cookieType;
     
    30963597/* Length of the KeyShare Extension */
    30973598#define HRR_KEY_SHARE_SZ   (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
     3599/* Length of the Supported Vresions Extension */
     3600#define HRR_VERSIONS_SZ    (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
    30983601/* Length of the Cookie Extension excluding cookie data */
    30993602#define HRR_COOKIE_HDR_SZ  (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
     3603#ifdef WOLFSSL_TLS13_DRAFT_18
    31003604/* PV | CipherSuite | Ext Len */
    31013605#define HRR_BODY_SZ        (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
     
    31053609                          HRR_KEY_SHARE_SZ + \
    31063610                          HRR_COOKIE_HDR_SZ)
     3611#else
     3612/* PV | Random | Session Id | CipherSuite | Compression | Ext Len */
     3613#define HRR_BODY_SZ        (VERSION_SZ + RAN_LEN + ENUM_LEN + ID_LEN + \
     3614                            SUITE_LEN + COMP_LEN + OPAQUE16_LEN)
     3615/* HH | PV | CipherSuite | Ext Len | Key Share | Supported Version | Cookie */
     3616#define MAX_HRR_SZ   (HANDSHAKE_HEADER_SZ   + \
     3617                        HRR_BODY_SZ         + \
     3618                          HRR_KEY_SHARE_SZ  + \
     3619                          HRR_VERSIONS_SZ   + \
     3620                          HRR_COOKIE_HDR_SZ)
     3621#endif
     3622
    31073623/* Restart the Hanshake hash from the cookie value.
    31083624 *
     
    31413657
    31423658    /* Reconstruct the HelloRetryMessage for handshake hash. */
     3659#ifdef WOLFSSL_TLS13_DRAFT_18
    31433660    length = HRR_BODY_SZ + HRR_COOKIE_HDR_SZ + cookie->len;
     3661#else
     3662    length = HRR_BODY_SZ - ID_LEN + ssl->session.sessionIDSz +
     3663             HRR_COOKIE_HDR_SZ + cookie->len;
     3664    length += HRR_VERSIONS_SZ;
     3665#endif
    31443666    if (cookieDataSz > hashSz + OPAQUE16_LEN) {
    31453667        keyShareExt = 1;
    31463668        length += HRR_KEY_SHARE_SZ;
    31473669    }
     3670#ifdef WOLFSSL_TLS13_DRAFT_18
    31483671    AddTls13HandShakeHeader(hrr, length, 0, 0, hello_retry_request, ssl);
    31493672
    31503673    idx += hashSz;
    31513674    hrrIdx = HANDSHAKE_HEADER_SZ;
    3152     /* TODO: [TLS13] Replace existing code with code in comment.
    3153      * Use the TLS v1.3 draft version for now.
    3154      *
    3155      * Change to:
    3156      * hrr[hrrIdx++] = ssl->version.major;
    3157      * hrr[hrrIdx++] = ssl->version.minor;
    3158      */
    31593675    /* The negotiated protocol version. */
    31603676    hrr[hrrIdx++] = TLS_DRAFT_MAJOR;
     
    31683684    c16toa(length, hrr + hrrIdx);
    31693685    hrrIdx += 2;
     3686#else
     3687    AddTls13HandShakeHeader(hrr, length, 0, 0, server_hello, ssl);
     3688
     3689    idx += hashSz;
     3690    hrrIdx = HANDSHAKE_HEADER_SZ;
     3691
     3692    /* The negotiated protocol version. */
     3693    hrr[hrrIdx++] = ssl->version.major;
     3694    hrr[hrrIdx++] = TLSv1_2_MINOR;
     3695
     3696    /* HelloRetryRequest message has fixed value for random. */
     3697    XMEMCPY(hrr + hrrIdx, helloRetryRequestRandom, RAN_LEN);
     3698    hrrIdx += RAN_LEN;
     3699
     3700    hrr[hrrIdx++] = ssl->session.sessionIDSz;
     3701    if (ssl->session.sessionIDSz > 0) {
     3702        XMEMCPY(hrr + hrrIdx, ssl->session.sessionID, ssl->session.sessionIDSz);
     3703        hrrIdx += ssl->session.sessionIDSz;
     3704    }
     3705
     3706    /* Cipher Suite */
     3707    hrr[hrrIdx++] = cookieData[idx++];
     3708    hrr[hrrIdx++] = cookieData[idx++];
     3709
     3710    /* Compression not supported in TLS v1.3. */
     3711    hrr[hrrIdx++] = 0;
     3712
     3713    /* Extensions' length */
     3714    length -= HRR_BODY_SZ - ID_LEN + ssl->session.sessionIDSz;
     3715    c16toa(length, hrr + hrrIdx);
     3716    hrrIdx += 2;
     3717
     3718#endif
    31703719    /* Optional KeyShare Extension */
    31713720    if (keyShareExt) {
     
    31773726        hrr[hrrIdx++] = cookieData[idx++];
    31783727    }
     3728#ifndef WOLFSSL_TLS13_DRAFT_18
     3729    c16toa(TLSX_SUPPORTED_VERSIONS, hrr + hrrIdx);
     3730    hrrIdx += 2;
     3731    c16toa(OPAQUE16_LEN, hrr + hrrIdx);
     3732    hrrIdx += 2;
     3733    #ifdef WOLFSSL_TLS13_DRAFT
     3734        hrr[hrrIdx++] = TLS_DRAFT_MAJOR;
     3735        hrr[hrrIdx++] = TLS_DRAFT_MINOR;
     3736    #else
     3737        hrr[hrrIdx++] = ssl->version.major;
     3738        hrr[hrrIdx++] = ssl->version.minor;
     3739    #endif
     3740#endif
    31793741    /* Mandatory Cookie Extension */
    31803742    c16toa(TLSX_COOKIE, hrr + hrrIdx);
     
    32143776                       word32 helloSz)
    32153777{
    3216     int             ret;
     3778    int             ret = VERSION_ERROR;
    32173779    byte            b;
    32183780    ProtocolVersion pv;
     
    32203782    word32          i = *inOutIdx;
    32213783    word32          begin = i;
    3222     word16          totalExtSz;
     3784    word16          totalExtSz = 0;
    32233785    int             usingPSK = 0;
    32243786    byte            sessIdSz;
    3225 
     3787#ifndef WOLFSSL_NO_TLS12
     3788    int             bogusID = 0;
     3789#endif
     3790
     3791    WOLFSSL_START(WC_FUNC_CLIENT_HELLO_DO);
    32263792    WOLFSSL_ENTER("DoTls13ClientHello");
    32273793
    32283794#ifdef WOLFSSL_CALLBACKS
    3229     if (ssl->hsInfoOn) AddPacketName("ClientHello", &ssl->handShakeInfo);
     3795    if (ssl->hsInfoOn) AddPacketName(ssl, "ClientHello");
    32303796    if (ssl->toInfoOn) AddLateName("ClientHello", &ssl->timeoutInfo);
    32313797#endif
     
    32393805    ssl->chVersion = pv;   /* store */
    32403806    i += OPAQUE16_LEN;
    3241 
     3807    /* Legacy protocol version cannot negotiate TLS 1.3 or higher. */
     3808    if (pv.major == SSLv3_MAJOR && pv.minor >= TLSv1_3_MINOR)
     3809        pv.minor = TLSv1_2_MINOR;
     3810
     3811#ifndef WOLFSSL_NO_TLS12
    32423812    if (ssl->version.major == SSLv3_MAJOR && ssl->version.minor < TLSv1_3_MINOR)
    32433813        return DoClientHello(ssl, input, inOutIdx, helloSz);
     3814#endif
     3815
     3816#ifdef HAVE_SESSION_TICKET
     3817    if (ssl->options.downgrade) {
     3818       if ((ret = HashInput(ssl, input + begin, helloSz)) != 0)
     3819            return ret;
     3820    }
     3821#endif
    32443822
    32453823    /* Client random */
     
    32523830#endif
    32533831
     3832#ifdef WOLFSSL_TLS13_DRAFT_18
    32543833    /* Session id - empty in TLS v1.3 */
    32553834    sessIdSz = input[i++];
    3256     if (sessIdSz > 0) {
     3835    if (sessIdSz > 0 && !ssl->options.downgrade) {
    32573836        WOLFSSL_MSG("Client sent session id - not supported");
    32583837        return BUFFER_ERROR;
    32593838    }
     3839#else
     3840    sessIdSz = input[i++];
     3841    if (sessIdSz != ID_LEN && sessIdSz != 0)
     3842        return INVALID_PARAMETER;
     3843#endif
     3844    ssl->session.sessionIDSz = sessIdSz;
     3845    if (sessIdSz == ID_LEN) {
     3846        XMEMCPY(ssl->session.sessionID, input + i, sessIdSz);
     3847        i += ID_LEN;
     3848    }
     3849#ifndef WOLFSSL_NO_TLS12
     3850    #ifdef HAVE_SESSION_TICKET
     3851        if (sessIdSz > 0 && sessIdSz < ID_LEN)
     3852            bogusID = 1;
     3853    #endif
     3854#endif
    32603855
    32613856    /* Cipher suites */
     
    32873882    }
    32883883
    3289     /* TLS v1.3 ClientHello messages will have extensions. */
    3290     if ((i - begin) >= helloSz) {
    3291         WOLFSSL_MSG("ClientHello must have extensions in TLS v1.3");
    3292         return BUFFER_ERROR;
    3293     }
     3884    if ((i - begin) < helloSz) {
    32943885    if ((i - begin) + OPAQUE16_LEN > helloSz)
    32953886        return BUFFER_ERROR;
     
    33133904    }
    33143905
    3315 #ifdef HAVE_STUNNEL
     3906#if defined(OPENSSL_ALL) || defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
     3907                                                        defined(WOLFSSL_HAPROXY)
    33163908    if ((ret = SNI_Callback(ssl)) != 0)
    33173909        return ret;
    3318 #endif /*HAVE_STUNNEL*/
     3910        ssl->options.side = WOLFSSL_SERVER_END;
     3911#endif /* OPENSSL_ALL || HAVE_STUNNEL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
     3912    }
     3913
     3914    i += totalExtSz;
     3915    *inOutIdx = i;
    33193916
    33203917    if (TLSX_Find(ssl->extensions, TLSX_SUPPORTED_VERSIONS) == NULL) {
    33213918        if (!ssl->options.downgrade) {
    3322             WOLFSSL_MSG("Client trying to connect with lesser version");
     3919            WOLFSSL_MSG("Client trying to connect with lesser version than "
     3920                        "TLS v1.3");
    33233921            return VERSION_ERROR;
    33243922        }
     3923
     3924        if (pv.minor < ssl->options.minDowngrade)
     3925            return VERSION_ERROR;
    33253926        ssl->version.minor = pv.minor;
    33263927    }
    33273928
    3328 #ifdef WOLFSSL_SEND_HRR_COOKIE
     3929    ssl->options.sendVerify = SEND_CERT;
     3930
     3931    ssl->options.clientState = CLIENT_HELLO_COMPLETE;
     3932    ssl->options.haveSessionId = 1;
     3933
     3934    if (IsAtLeastTLSv1_3(ssl->version)) {
     3935#if !defined(WOLFSSL_TLS13_DRAFT_18) && defined(WOLFSSL_SEND_HRR_COOKIE)
    33293936    if (ssl->options.sendCookie &&
    3330                        ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST) {
     3937              ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
    33313938        TLSX* ext;
    33323939
    33333940        if ((ext = TLSX_Find(ssl->extensions, TLSX_COOKIE)) == NULL)
    33343941            return HRR_COOKIE_ERROR;
    3335         /* Ensure the cookie came from client and isn't the one in the response
    3336          * - HelloRetryRequest.
     3942            /* Ensure the cookie came from client and isn't the one in the
     3943             * response - HelloRetryRequest.
    33373944         */
    33383945        if (ext->resp == 1)
     
    33443951#endif
    33453952
    3346     ssl->options.sendVerify = SEND_CERT;
    3347 
    33483953#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
     3954        if (ssl->options.downgrade) {
     3955            if ((ret = InitHandshakeHashes(ssl)) != 0)
     3956                return ret;
     3957        }
     3958
     3959        /* Refine list for PSK processing. */
     3960        RefineSuites(ssl, &clSuites);
     3961
    33493962    /* Process the Pre-Shared Key extension if present. */
    33503963    ret = DoPreSharedKeys(ssl, input + begin, helloSz, &usingPSK);
    33513964    if (ret != 0)
    33523965        return ret;
     3966#endif
     3967    }
     3968#ifndef WOLFSSL_NO_TLS12
     3969    else if (ssl->options.resuming) {
     3970        ret = HandleTlsResumption(ssl, bogusID, &clSuites);
     3971        if (ret != 0)
     3972            return ret;
     3973        /* Check wheter resuming has been chosen */
     3974        if (ssl->options.clientState == CLIENT_KEYEXCHANGE_COMPLETE) {
     3975            WOLFSSL_LEAVE("DoTls13ClientHello", ret);
     3976            WOLFSSL_END(WC_FUNC_CLIENT_HELLO_DO);
     3977
     3978            return ret;
     3979        }
     3980    }
     3981#else
     3982    else {
     3983        WOLFSSL_MSG("Negotiated lesser version than TLS v1.3");
     3984        return VERSION_ERROR;
     3985    }
    33533986#endif
    33543987
     
    33583991            return ret;
    33593992        }
     3993
     3994        /* Check that the negotiated ciphersuite matches protocol version. */
     3995        if (IsAtLeastTLSv1_3(ssl->version)) {
     3996            if (ssl->options.cipherSuite0 != TLS13_BYTE) {
     3997                WOLFSSL_MSG("Negotiated ciphersuite from lesser version than "
     3998                            "TLS v1.3");
     3999                return VERSION_ERROR;
     4000            }
     4001        }
     4002        /* VerifyServerSuite handles when version is less than 1.3 */
    33604003
    33614004#ifdef HAVE_SESSION_TICKET
     
    33694012#endif
    33704013
     4014#ifdef HAVE_SESSION_TICKET
     4015        if (IsAtLeastTLSv1_3(ssl->version) || !ssl->options.downgrade)
     4016#endif
     4017        {
    33714018        if ((ret = HashInput(ssl, input + begin,  helloSz)) != 0)
    33724019            return ret;
    3373 
     4020        }
     4021
     4022        if (IsAtLeastTLSv1_3(ssl->version)) {
    33744023        /* Derive early secret for handshake secret. */
    33754024        if ((ret = DeriveEarlySecret(ssl)) != 0)
    33764025            return ret;
    33774026    }
    3378 
    3379     i += totalExtSz;
    3380     *inOutIdx = i;
    3381 
    3382     ssl->options.clientState = CLIENT_HELLO_COMPLETE;
     4027    }
    33834028
    33844029    WOLFSSL_LEAVE("DoTls13ClientHello", ret);
     4030    WOLFSSL_END(WC_FUNC_CLIENT_HELLO_DO);
    33854031
    33864032    return ret;
    33874033}
    33884034
     4035#ifdef WOLFSSL_TLS13_DRAFT_18
     4036/* handle generation of TLS 1.3 hello_retry_request (6) */
    33894037/* Send the HelloRetryRequest message to indicate the negotiated protocol
    33904038 * version and security parameters the server is willing to use.
     
    33994047    byte*  output;
    34004048    word32 length;
    3401     word32 len;
     4049    word16 len;
    34024050    word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
    34034051    int    sendSz;
     
    34054053    WOLFSSL_ENTER("SendTls13HelloRetryRequest");
    34064054
    3407 #ifndef WOLFSSL_TLS13_DRAFT_18
    3408     if ((ret = RestartHandshakeHash(ssl)) < 0)
    3409         return ret;
    3410 #endif
    3411 
    34124055    /* Get the length of the extensions that will be written. */
    3413     len = TLSX_GetResponseSize(ssl, hello_retry_request);
     4056    len = 0;
     4057    ret = TLSX_GetResponseSize(ssl, hello_retry_request, &len);
    34144058    /* There must be extensions sent to indicate what client needs to do. */
    3415     if (len == 0)
     4059    if (ret != 0)
    34164060        return MISSING_HANDSHAKE_DATA;
    34174061
    3418 #ifndef WOLFSSL_TLS13_DRAFT_18
    3419     /* Protocol version + CipherSuite + Extensions */
    3420     length = OPAQUE16_LEN + OPAQUE16_LEN + len;
    3421 #else
    34224062    /* Protocol version + Extensions */
    34234063    length = OPAQUE16_LEN + len;
    3424 #endif
    34254064    sendSz = idx + length;
    34264065
     
    34354074    AddTls13Headers(output, length, hello_retry_request, ssl);
    34364075
    3437     /* TODO: [TLS13] Replace existing code with code in comment.
    3438      * Use the TLS v1.3 draft version for now.
    3439      *
    3440      * Change to:
    3441      * output[idx++] = ssl->version.major;
    3442      * output[idx++] = ssl->version.minor;
    3443      */
    34444076    /* The negotiated protocol version. */
    34454077    output[idx++] = TLS_DRAFT_MAJOR;
    34464078    output[idx++] = TLS_DRAFT_MINOR;
    34474079
     4080    /* Add TLS extensions. */
     4081    ret = TLSX_WriteResponse(ssl, output + idx, hello_retry_request, NULL);
     4082    if (ret != 0)
     4083        return ret;
     4084    idx += len;
     4085
     4086#ifdef WOLFSSL_CALLBACKS
     4087    if (ssl->hsInfoOn)
     4088        AddPacketName(ssl, "HelloRetryRequest");
     4089    if (ssl->toInfoOn) {
     4090        AddPacketInfo(ssl, "HelloRetryRequest", handshake, output, sendSz,
     4091                      WRITE_PROTO, ssl->heap);
     4092    }
     4093#endif
     4094    if ((ret = HashOutput(ssl, output, idx, 0)) != 0)
     4095        return ret;
     4096
     4097    ssl->buffers.outputBuffer.length += sendSz;
     4098
     4099    if (!ssl->options.groupMessages)
     4100        ret = SendBuffered(ssl);
     4101
     4102    WOLFSSL_LEAVE("SendTls13HelloRetryRequest", ret);
     4103
     4104    return ret;
     4105}
     4106#endif /* WOLFSSL_TLS13_DRAFT_18 */
     4107
     4108/* Send TLS v1.3 ServerHello message to client.
     4109 * Only a server will send this message.
     4110 *
     4111 * ssl  The SSL/TLS object.
     4112 * returns 0 on success, otherwise failure.
     4113 */
     4114#ifdef WOLFSSL_TLS13_DRAFT_18
     4115static
     4116#endif
     4117/* handle generation of TLS 1.3 server_hello (2) */
     4118int SendTls13ServerHello(WOLFSSL* ssl, byte extMsgType)
     4119{
     4120    int    ret;
     4121    byte*  output;
     4122    word16 length;
     4123    word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
     4124    int    sendSz;
     4125
     4126    WOLFSSL_START(WC_FUNC_SERVER_HELLO_SEND);
     4127    WOLFSSL_ENTER("SendTls13ServerHello");
     4128
    34484129#ifndef WOLFSSL_TLS13_DRAFT_18
     4130    if (extMsgType == hello_retry_request) {
     4131        if ((ret = RestartHandshakeHash(ssl)) < 0)
     4132            return ret;
     4133    }
     4134#endif
     4135
     4136#ifdef WOLFSSL_TLS13_DRAFT_18
     4137    /* Protocol version, server random, cipher suite and extensions. */
     4138    length = VERSION_SZ + RAN_LEN + SUITE_LEN;
     4139    ret = TLSX_GetResponseSize(ssl, server_hello, &length);
     4140    if (ret != 0)
     4141        return ret;
     4142#else
     4143    /* Protocol version, server random, session id, cipher suite, compression
     4144     * and extensions.
     4145     */
     4146    length = VERSION_SZ + RAN_LEN + ENUM_LEN + ssl->session.sessionIDSz +
     4147             SUITE_LEN + COMP_LEN;
     4148    ret = TLSX_GetResponseSize(ssl, extMsgType, &length);
     4149    if (ret != 0)
     4150        return ret;
     4151#endif
     4152    sendSz = idx + length;
     4153
     4154    /* Check buffers are big enough and grow if needed. */
     4155    if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
     4156        return ret;
     4157
     4158    /* Get position in output buffer to write new message to. */
     4159    output = ssl->buffers.outputBuffer.buffer +
     4160             ssl->buffers.outputBuffer.length;
     4161
     4162    /* Put the record and handshake headers on. */
     4163    AddTls13Headers(output, length, server_hello, ssl);
     4164
     4165#ifdef WOLFSSL_TLS13_DRAFT_18
     4166    /* The negotiated protocol version. */
     4167    output[idx++] = TLS_DRAFT_MAJOR;
     4168    output[idx++] = TLS_DRAFT_MINOR;
     4169#else
     4170    /* The protocol version must be TLS v1.2 for middleboxes. */
     4171    output[idx++] = ssl->version.major;
     4172    output[idx++] = TLSv1_2_MINOR;
     4173#endif
     4174
     4175    if (extMsgType == server_hello) {
     4176    /* Generate server random. */
     4177    if ((ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, RAN_LEN)) != 0)
     4178        return ret;
     4179    }
     4180#ifndef WOLFSSL_TLS13_DRAFT_18
     4181    else {
     4182        /* HelloRetryRequest message has fixed value for random. */
     4183        XMEMCPY(output + idx, helloRetryRequestRandom, RAN_LEN);
     4184    }
     4185#endif
     4186    /* Store in SSL for debugging. */
     4187    XMEMCPY(ssl->arrays->serverRandom, output + idx, RAN_LEN);
     4188    idx += RAN_LEN;
     4189
     4190#ifdef WOLFSSL_DEBUG_TLS
     4191    WOLFSSL_MSG("Server random");
     4192    WOLFSSL_BUFFER(ssl->arrays->serverRandom, RAN_LEN);
     4193#endif
     4194
     4195#ifndef WOLFSSL_TLS13_DRAFT_18
     4196    output[idx++] = ssl->session.sessionIDSz;
     4197    if (ssl->session.sessionIDSz > 0) {
     4198        XMEMCPY(output + idx, ssl->session.sessionID, ssl->session.sessionIDSz);
     4199        idx += ssl->session.sessionIDSz;
     4200    }
     4201#endif
     4202
    34494203    /* Chosen cipher suite */
    34504204    output[idx++] = ssl->options.cipherSuite0;
    34514205    output[idx++] = ssl->options.cipherSuite;
    3452 #endif
    3453 
    3454     /* Add TLS extensions. */
    3455     TLSX_WriteResponse(ssl, output + idx, hello_retry_request);
    3456     idx += len;
    3457 
    3458 #ifdef WOLFSSL_CALLBACKS
    3459     if (ssl->hsInfoOn)
    3460         AddPacketName("HelloRetryRequest", &ssl->handShakeInfo);
    3461     if (ssl->toInfoOn) {
    3462         AddPacketInfo("HelloRetryRequest", &ssl->timeoutInfo, output, sendSz,
    3463                       ssl->heap);
    3464     }
    3465 #endif
    3466 
    3467     if ((ret = HashOutput(ssl, output, idx, 0)) != 0)
    3468         return ret;
    3469 
    3470     ssl->buffers.outputBuffer.length += sendSz;
    3471 
    3472     if (!ssl->options.groupMessages)
    3473         ret = SendBuffered(ssl);
    3474 
    3475     WOLFSSL_LEAVE("SendTls13HelloRetryRequest", ret);
    3476 
    3477     return ret;
    3478 }
    3479 
    3480 /* Send TLS v1.3 ServerHello message to client.
    3481  * Only a server will send this message.
    3482  *
    3483  * ssl  The SSL/TLS object.
    3484  * returns 0 on success, otherwise failure.
    3485  */
    3486 static int SendTls13ServerHello(WOLFSSL* ssl)
    3487 {
    3488     byte*  output;
    3489     word32 length;
    3490     word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
    3491     int    sendSz;
    3492     int    ret;
    3493 
    3494     WOLFSSL_ENTER("SendTls13ServerHello");
    3495 
    3496     /* Protocol version, server random, cipher suite and extensions. */
    3497     length = VERSION_SZ + RAN_LEN + SUITE_LEN +
    3498              TLSX_GetResponseSize(ssl, server_hello);
    3499     sendSz = idx + length;
    3500 
    3501     /* Check buffers are big enough and grow if needed. */
    3502     if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
    3503         return ret;
    3504 
    3505     /* Get position in output buffer to write new message to. */
    3506     output = ssl->buffers.outputBuffer.buffer +
    3507              ssl->buffers.outputBuffer.length;
    3508 
    3509     /* Put the record and handshake headers on. */
    3510     AddTls13Headers(output, length, server_hello, ssl);
    3511 
    3512     /* TODO: [TLS13] Replace existing code with code in comment.
    3513      * Use the TLS v1.3 draft version for now.
    3514      *
    3515      * Change to:
    3516      * output[idx++] = ssl->version.major;
    3517      * output[idx++] = ssl->version.minor;
    3518      */
    3519     /* The negotiated protocol version. */
    3520     output[idx++] = TLS_DRAFT_MAJOR;
    3521     output[idx++] = TLS_DRAFT_MINOR;
    3522 
    3523     /* Generate server random. */
    3524     if ((ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, RAN_LEN)) != 0)
    3525         return ret;
    3526     /* Store in SSL for debugging. */
    3527     XMEMCPY(ssl->arrays->serverRandom, output + idx, RAN_LEN);
    3528     idx += RAN_LEN;
    3529 
    3530 #ifdef WOLFSSL_DEBUG_TLS
    3531     WOLFSSL_MSG("Server random");
    3532     WOLFSSL_BUFFER(ssl->arrays->serverRandom, RAN_LEN);
    3533 #endif
    3534 
    3535     /* Chosen cipher suite */
    3536     output[idx++] = ssl->options.cipherSuite0;
    3537     output[idx++] = ssl->options.cipherSuite;
     4206
     4207#ifndef WOLFSSL_TLS13_DRAFT_18
     4208    /* Compression not supported in TLS v1.3. */
     4209    output[idx++] = 0;
     4210#endif
    35384211
    35394212    /* Extensions */
    3540     TLSX_WriteResponse(ssl, output + idx, server_hello);
     4213    ret = TLSX_WriteResponse(ssl, output + idx, extMsgType, NULL);
     4214    if (ret != 0)
     4215        return ret;
    35414216
    35424217    ssl->buffers.outputBuffer.length += sendSz;
     
    35474222    #ifdef WOLFSSL_CALLBACKS
    35484223    if (ssl->hsInfoOn)
    3549         AddPacketName("ServerHello", &ssl->handShakeInfo);
     4224        AddPacketName(ssl, "ServerHello");
    35504225    if (ssl->toInfoOn) {
    3551         AddPacketInfo("ServerHello", &ssl->timeoutInfo, output, sendSz,
    3552                       ssl->heap);
     4226        AddPacketInfo(ssl, "ServerHello", handshake, output, sendSz,
     4227                      WRITE_PROTO, ssl->heap);
    35534228    }
    35544229    #endif
    35554230
     4231#ifdef WOLFSSL_TLS13_DRAFT_18
    35564232    ssl->options.serverState = SERVER_HELLO_COMPLETE;
    3557 
     4233#else
     4234    if (extMsgType == server_hello)
     4235    ssl->options.serverState = SERVER_HELLO_COMPLETE;
     4236#endif
     4237
     4238#ifdef WOLFSSL_TLS13_DRAFT_18
    35584239    if (!ssl->options.groupMessages)
     4240#else
     4241    if (!ssl->options.groupMessages || extMsgType != server_hello)
     4242#endif
    35594243        ret = SendBuffered(ssl);
    35604244
    35614245    WOLFSSL_LEAVE("SendTls13ServerHello", ret);
     4246    WOLFSSL_END(WC_FUNC_SERVER_HELLO_SEND);
    35624247
    35634248    return ret;
    35644249}
    35654250
     4251/* handle generation of TLS 1.3 encrypted_extensions (8) */
    35664252/* Send the rest of the extensions encrypted under the handshake key.
    35674253 * This message is always encrypted in TLS v1.3.
     
    35754261    int    ret;
    35764262    byte*  output;
    3577     word32 length;
     4263    word16 length = 0;
    35784264    word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
    35794265    int    sendSz;
    35804266
     4267    WOLFSSL_START(WC_FUNC_ENCRYPTED_EXTENSIONS_SEND);
    35814268    WOLFSSL_ENTER("SendTls13EncryptedExtensions");
    35824269
    35834270    ssl->keys.encryptionOn = 1;
     4271
     4272#ifndef WOLFSSL_NO_SERVER_GROUPS_EXT
     4273    if ((ret = TLSX_SupportedCurve_CheckPriority(ssl)) != 0)
     4274        return ret;
     4275#endif
    35844276
    35854277    /* Derive the handshake secret now that we are at first message to be
     
    35964288    if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
    35974289        return ret;
    3598     if (ssl->earlyData != 2) {
     4290    if (ssl->earlyData != process_early_data) {
    35994291        if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
    36004292            return ret;
     
    36054297#endif
    36064298
    3607     length = TLSX_GetResponseSize(ssl, encrypted_extensions);
     4299    ret = TLSX_GetResponseSize(ssl, encrypted_extensions, &length);
     4300    if (ret != 0)
     4301        return ret;
     4302
    36084303    sendSz = idx + length;
    36094304    /* Encryption always on. */
     
    36224317    AddTls13Headers(output, length, encrypted_extensions, ssl);
    36234318
    3624     TLSX_WriteResponse(ssl, output + idx, encrypted_extensions);
     4319    ret = TLSX_WriteResponse(ssl, output + idx, encrypted_extensions, NULL);
     4320    if (ret != 0)
     4321        return ret;
    36254322    idx += length;
    36264323
    36274324#ifdef WOLFSSL_CALLBACKS
    36284325    if (ssl->hsInfoOn)
    3629         AddPacketName("EncryptedExtensions", &ssl->handShakeInfo);
     4326        AddPacketName(ssl, "EncryptedExtensions");
    36304327    if (ssl->toInfoOn) {
    3631         AddPacketInfo("EncryptedExtensions", &ssl->timeoutInfo, output,
    3632                       sendSz, ssl->heap);
     4328        AddPacketInfo(ssl, "EncryptedExtensions", handshake, output,
     4329                      sendSz, WRITE_PROTO, ssl->heap);
    36334330    }
    36344331#endif
     
    36484345
    36494346    WOLFSSL_LEAVE("SendTls13EncryptedExtensions", ret);
     4347    WOLFSSL_END(WC_FUNC_ENCRYPTED_EXTENSIONS_SEND);
    36504348
    36514349    return ret;
     
    36534351
    36544352#ifndef NO_CERTS
     4353/* handle generation TLS v1.3 certificate_request (13) */
    36554354/* Send the TLS v1.3 CertificateRequest message.
    36564355 * This message is always encrypted in TLS v1.3.
     
    36694368    int    sendSz;
    36704369    word32 i;
    3671     int    reqSz;
     4370    word16 reqSz;
    36724371#ifndef WOLFSSL_TLS13_DRAFT_18
    36734372    TLSX*  ext;
    36744373#endif
    36754374
     4375    WOLFSSL_START(WC_FUNC_CERTIFICATE_REQUEST_SEND);
    36764376    WOLFSSL_ENTER("SendTls13CertificateRequest");
    36774377
     
    37274427
    37284428    i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
    3729     reqSz = OPAQUE8_LEN + reqCtxLen +
    3730         TLSX_GetRequestSize(ssl, certificate_request);
     4429    reqSz = (word16)(OPAQUE8_LEN + reqCtxLen);
     4430    ret = TLSX_GetRequestSize(ssl, certificate_request, &reqSz);
     4431    if (ret != 0)
     4432        return ret;
    37314433
    37324434    sendSz = i + reqSz;
     
    37464448
    37474449    /* Certificate request context. */
    3748     output[i++] = reqCtxLen;
     4450    output[i++] = (byte)reqCtxLen;
    37494451    if (reqCtxLen != 0) {
    37504452        XMEMCPY(output + i, reqCtx, reqCtxLen);
     
    37534455
    37544456    /* Certificate extensions. */
    3755     i += TLSX_WriteRequest(ssl, output + i, certificate_request);
     4457    reqSz = 0;
     4458    ret = TLSX_WriteRequest(ssl, output + i, certificate_request, &reqSz);
     4459    if (ret != 0)
     4460        return ret;
     4461    i += reqSz;
    37564462#endif
    37574463
     
    37644470    #ifdef WOLFSSL_CALLBACKS
    37654471        if (ssl->hsInfoOn)
    3766             AddPacketName("CertificateRequest", &ssl->handShakeInfo);
     4472            AddPacketName(ssl, "CertificateRequest");
    37674473        if (ssl->toInfoOn) {
    3768             AddPacketInfo("CertificateRequest", &ssl->timeoutInfo, output,
    3769                           sendSz, ssl->heap);
     4474            AddPacketInfo(ssl, "CertificateRequest", handshake, output,
     4475                          sendSz, WRITE_PROTO, ssl->heap);
    37704476        }
    37714477    #endif
     
    37764482
    37774483    WOLFSSL_LEAVE("SendTls13CertificateRequest", ret);
     4484    WOLFSSL_END(WC_FUNC_CERTIFICATE_REQUEST_SEND);
    37784485
    37794486    return ret;
     
    37904497 * output    The buffer to encode into.
    37914498 */
    3792 static INLINE void EncodeSigAlg(byte hashAlgo, byte hsType, byte* output)
     4499static WC_INLINE void EncodeSigAlg(byte hashAlgo, byte hsType, byte* output)
    37934500{
    37944501    switch (hsType) {
     
    38244531 * hsType   The signature type.
    38254532 */
    3826 static INLINE void DecodeSigAlg(byte* input, byte* hashAlgo, byte* hsType)
     4533static WC_INLINE void DecodeSigAlg(byte* input, byte* hashAlgo, byte* hsType)
    38274534{
    38284535    switch (input[0]) {
     
    38564563 * returns the length of the hash.
    38574564 */
    3858 static INLINE int GetMsgHash(WOLFSSL* ssl, byte* hash)
     4565static WC_INLINE int GetMsgHash(WOLFSSL* ssl, byte* hash)
    38594566{
    38604567    int ret = 0;
     
    39014608#define MAX_SIG_DATA_SZ            (SIGNING_DATA_PREFIX_SZ + \
    39024609                                    CERT_VFY_LABEL_SZ      + \
    3903                                     MAX_DIGEST_SIZE)
     4610                                    WC_MAX_DIGEST_SIZE)
    39044611
    39054612/* Create the signature data for TLS v1.3 certificate verification.
     
    39354642        return ret;
    39364643
    3937     *sigDataSz = idx + ret;
     4644    *sigDataSz = (word16)(idx + ret);
    39384645    ret = 0;
    39394646
     
    40754782 *
    40764783 * ssl       The SSL/TLS object.
    4077  * hashAlgo  The signature algorithm used to generate signature.
     4784 * sigAlgo   The signature algorithm used to generate signature.
    40784785 * hashAlgo  The hash algorithm used to generate signature.
    40794786 * decSig    The decrypted signature.
     
    41004807            return ret;
    41014808
    4102         /* PSS signature can be done in-pace */
     4809        /* PSS signature can be done in-place */
    41034810        ret = CreateRSAEncodedSig(sigData, sigData, sigDataSz,
    41044811                                  sigAlgo, hashAlgo);
     
    41474854/* Add certificate data and empty extension to output up to the fragment size.
    41484855 *
     4856 * ssl     SSL/TLS object.
    41494857 * cert    The certificate data to write out.
    41504858 * len     The length of the certificate data.
     4859 * extSz   Length of the extension data with the certificate.
    41514860 * idx     The start of the certificate data to write out.
    41524861 * fragSz  The maximum size of this fragment.
     
    41544863 * returns the number of bytes written.
    41554864 */
    4156 static word32 AddCertExt(byte* cert, word32 len, word32 idx, word32 fragSz,
    4157                          byte* output)
     4865static word32 AddCertExt(WOLFSSL* ssl, byte* cert, word32 len, word16 extSz,
     4866                         word32 idx, word32 fragSz, byte* output)
    41584867{
    41594868    word32 i = 0;
     
    41634872        XMEMCPY(output, cert + idx, copySz);
    41644873        i = copySz;
    4165     }
    4166 
    4167     if (copySz + OPAQUE16_LEN <= fragSz) {
     4874        if (copySz == fragSz)
     4875            return i;
     4876    }
     4877    copySz = len + extSz - idx - i;
     4878
     4879    if (extSz == OPAQUE16_LEN) {
     4880        if (copySz <= fragSz) {
    41684881        /* Empty extension */
    41694882        output[i++] = 0;
    41704883        output[i++] = 0;
    41714884    }
     4885    }
     4886    else {
     4887        byte* certExts = ssl->buffers.certExts->buffer + idx + i - len;
     4888        /* Put out as much of the extensions' data as will fit in fragment. */
     4889        if (copySz > fragSz - i)
     4890            copySz = fragSz - i;
     4891        XMEMCPY(output + i, certExts, copySz);
     4892        i += copySz;
     4893    }
    41724894
    41734895    return i;
    41744896}
    41754897
     4898/* handle generation TLS v1.3 certificate (11) */
    41764899/* Send the certificate for this end and any CAs that help with validation.
    41774900 * This message is always encrypted in TLS v1.3.
     
    41844907    int    ret = 0;
    41854908    word32 certSz, certChainSz, headerSz, listSz, payloadSz;
     4909    word16 extSz = 0;
    41864910    word32 length, maxFragment;
    41874911    word32 len = 0;
     
    41924916    byte*  certReqCtx = NULL;
    41934917
     4918    WOLFSSL_START(WC_FUNC_CERTIFICATE_SEND);
    41944919    WOLFSSL_ENTER("SendTls13Certificate");
    41954920
     
    42184943        headerSz = OPAQUE8_LEN + certReqCtxLen + CERT_HEADER_SZ +
    42194944                   CERT_HEADER_SZ;
    4220         /* Length of message data with one certificate and empty extensions. */
    4221         length = headerSz + certSz + OPAQUE16_LEN;
    4222         /* Length of list data with one certificate and empty extensions. */
    4223         listSz = CERT_HEADER_SZ + certSz + OPAQUE16_LEN;
     4945
     4946        ret = TLSX_GetResponseSize(ssl, certificate, &extSz);
     4947        if (ret < 0)
     4948            return ret;
     4949
     4950        /* Create extensions' data if none already present. */
     4951        if (extSz > OPAQUE16_LEN && ssl->buffers.certExts == NULL) {
     4952            ret = AllocDer(&ssl->buffers.certExts, extSz, CERT_TYPE, ssl->heap);
     4953            if (ret < 0)
     4954                return ret;
     4955
     4956            ret = TLSX_WriteResponse(ssl, ssl->buffers.certExts->buffer,
     4957                                                           certificate, &extSz);
     4958            if (ret < 0)
     4959                return ret;
     4960        }
     4961
     4962        /* Length of message data with one certificate and extensions. */
     4963        length = headerSz + certSz + extSz;
     4964        /* Length of list data with one certificate and extensions. */
     4965        listSz = CERT_HEADER_SZ + certSz + extSz;
    42244966
    42254967        /* Send rest of chain if sending cert (chain has leading size/s). */
    42264968        if (certSz > 0 && ssl->buffers.certChainCnt > 0) {
    4227             /* The pointer to the current spot in the cert chain buffer. */
    42284969            p = ssl->buffers.certChain->buffer;
    42294970            /* Chain length including extensions. */
     
    42424983        length -= (ssl->fragOffset + headerSz);
    42434984
    4244     maxFragment = MAX_RECORD_SIZE;
    4245 
    4246     #ifdef HAVE_MAX_FRAGMENT
    4247     if (ssl->max_fragment != 0 && maxFragment >= ssl->max_fragment)
    4248         maxFragment = ssl->max_fragment;
    4249     #endif /* HAVE_MAX_FRAGMENT */
     4985    maxFragment = wolfSSL_GetMaxRecordSize(ssl, MAX_RECORD_SIZE);
    42504986
    42514987    while (length > 0 && ret == 0) {
     
    42564992
    42574993        if (ssl->fragOffset == 0)  {
    4258             if (headerSz + certSz + OPAQUE16_LEN + certChainSz <=
     4994            if (headerSz + certSz + extSz + certChainSz <=
    42594995                maxFragment - HANDSHAKE_HEADER_SZ) {
    4260 
    4261                 fragSz = headerSz + certSz + OPAQUE16_LEN + certChainSz;
    4262             }
    4263             else {
     4996                fragSz = headerSz + certSz + extSz + certChainSz;
     4997            }
     4998            else
    42644999                fragSz = maxFragment - HANDSHAKE_HEADER_SZ;
    4265             }
     5000
    42665001            sendSz += fragSz + HANDSHAKE_HEADER_SZ;
    42675002            i += HANDSHAKE_HEADER_SZ;
     
    43095044            AddTls13RecordHeader(output, fragSz, handshake, ssl);
    43105045
    4311         if (certSz > 0 && ssl->fragOffset < certSz + OPAQUE16_LEN) {
    4312             /* Put in the leaf certificate and empty extension. */
    4313             word32 copySz = AddCertExt(ssl->buffers.certificate->buffer, certSz,
    4314                                        ssl->fragOffset, fragSz, output + i);
    4315 
     5046        if (certSz > 0 && ssl->fragOffset < certSz + extSz) {
     5047            /* Put in the leaf certificate with extensions. */
     5048            word32 copySz = AddCertExt(ssl, ssl->buffers.certificate->buffer,
     5049                            certSz, extSz, ssl->fragOffset, fragSz, output + i);
    43165050            i += copySz;
    43175051            ssl->fragOffset += copySz;
    43185052            length -= copySz;
    43195053            fragSz -= copySz;
     5054            if (ssl->fragOffset == certSz + extSz)
     5055                FreeDer(&ssl->buffers.certExts);
    43205056        }
    43215057        if (certChainSz > 0 && fragSz > 0) {
     
    43275063                    /* Find next CA certificate to write out. */
    43285064                    offset = 0;
     5065                    /* Point to the start of current cert in chain buffer. */
     5066                    p = ssl->buffers.certChain->buffer + idx;
    43295067                    len = NextCert(ssl->buffers.certChain->buffer,
    43305068                                   ssl->buffers.certChain->length, &idx);
     
    43345072
    43355073                /* Write out certificate and empty extension. */
    4336                 l = AddCertExt(p, len, offset, fragSz, output + i);
     5074                l = AddCertExt(ssl, p, len, OPAQUE16_LEN, offset, fragSz,
     5075                                                                    output + i);
    43375076                i += l;
    43385077                ssl->fragOffset += l;
     
    43575096        #ifdef WOLFSSL_CALLBACKS
    43585097            if (ssl->hsInfoOn)
    4359                 AddPacketName("Certificate", &ssl->handShakeInfo);
     5098                AddPacketName(ssl, "Certificate");
    43605099            if (ssl->toInfoOn) {
    4361                 AddPacketInfo("Certificate", &ssl->timeoutInfo, output, sendSz,
    4362                               ssl->heap);
     5100                AddPacketInfo(ssl, "Certificate", handshake, output,
     5101                        sendSz, WRITE_PROTO, ssl->heap);
    43635102            }
    43645103        #endif
     
    43855124
    43865125    WOLFSSL_LEAVE("SendTls13Certificate", ret);
     5126    WOLFSSL_END(WC_FUNC_CERTIFICATE_SEND);
    43875127
    43885128    return ret;
     
    43915131typedef struct Scv13Args {
    43925132    byte*  output; /* not allocated */
    4393 #ifndef NO_RSA
    4394     byte*  verifySig;
    4395 #endif
    43965133    byte*  verify; /* not allocated */
    43975134    word32 idx;
     
    44115148    (void)ssl;
    44125149
    4413 #ifndef NO_RSA
    4414     if (args->verifySig) {
    4415         XFREE(args->verifySig, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
    4416         args->verifySig = NULL;
    4417     }
    4418 #endif
    44195150    if (args->sigData) {
    44205151        XFREE(args->sigData, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
     
    44235154}
    44245155
     5156/* handle generation TLS v1.3 certificate_verify (15) */
    44255157/* Send the TLS v1.3 CertificateVerify message.
    44265158 * A hash of all the message so far is used.
     
    44445176#endif
    44455177
     5178    WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_SEND);
    44465179    WOLFSSL_ENTER("SendTls13CertificateVerify");
    44475180
     
    44735206            }
    44745207
    4475             args->sendSz = MAX_CERT_VERIFY_SZ;
     5208            args->sendSz = MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA;
    44765209            /* Always encrypted.  */
    44775210            args->sendSz += MAX_MSG_EXTRA;
     
    44985231                          &args->output[RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ];
    44995232
     5233            if (ssl->buffers.key == NULL) {
     5234            #ifdef HAVE_PK_CALLBACKS
     5235                if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx))
     5236                    args->length = GetPrivateKeySigSize(ssl);
     5237                else
     5238            #endif
     5239                    ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
     5240            }
     5241            else {
    45005242            ret = DecodePrivateKey(ssl, &args->length);
    45015243            if (ret != 0)
    45025244                goto exit_scv;
     5245            }
     5246
     5247            if (args->length <= 0) {
     5248                ERROR_OUT(NO_PRIVATE_KEY, exit_scv);
     5249            }
    45035250
    45045251            /* Add signature algorithm. */
     
    45135260            EncodeSigAlg(ssl->suites->hashAlgo, args->sigAlgo, args->verify);
    45145261
    4515             /* Create the data to be signed. */
     5262            if (ssl->hsType == DYNAMIC_TYPE_RSA) {
     5263                int sigLen = MAX_SIG_DATA_SZ;
     5264                if (args->length > MAX_SIG_DATA_SZ)
     5265                    sigLen = args->length;
     5266                args->sigData = (byte*)XMALLOC(sigLen, ssl->heap,
     5267                                                        DYNAMIC_TYPE_SIGNATURE);
     5268            }
     5269            else {
    45165270            args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
    45175271                                                    DYNAMIC_TYPE_SIGNATURE);
     5272            }
    45185273            if (args->sigData == NULL) {
    45195274                ERROR_OUT(MEMORY_E, exit_scv);
    45205275            }
    45215276
     5277            /* Create the data to be signed. */
    45225278            ret = CreateSigData(ssl, args->sigData, &args->sigDataSz, 0);
    45235279            if (ret != 0)
     
    45275283            if (ssl->hsType == DYNAMIC_TYPE_RSA) {
    45285284                /* build encoded signature buffer */
    4529                 sig->length = MAX_ENCODED_SIG_SZ;
     5285                sig->length = WC_MAX_DIGEST_SIZE;
    45305286                sig->buffer = (byte*)XMALLOC(sig->length, ssl->heap,
    45315287                                                    DYNAMIC_TYPE_SIGNATURE);
     
    45535309                if (ret < 0)
    45545310                    goto exit_scv;
    4555                 args->sigDataSz = ret;
     5311                args->sigDataSz = (word16)ret;
    45565312                ret = 0;
    45575313            }
     
    45595315        #ifdef HAVE_ED25519
    45605316            if (ssl->hsType == DYNAMIC_TYPE_ED25519) {
    4561                 /* Nothing to do */
     5317                ret = Ed25519CheckPubKey(ssl);
     5318                if (ret < 0) {
     5319                    ERROR_OUT(ret, exit_scv);
     5320                }
    45625321                sig->length = ED25519_SIG_SIZE;
    45635322            }
     
    45765335                    args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
    45775336                    &sig->length, (ecc_key*)ssl->hsKey,
    4578             #if defined(HAVE_PK_CALLBACKS)
    4579                     ssl->buffers.key->buffer, ssl->buffers.key->length,
    4580                     ssl->EccSignCtx
     5337            #ifdef HAVE_PK_CALLBACKS
     5338                    ssl->buffers.key
    45815339            #else
    4582                     NULL, 0, NULL
     5340                    NULL
    45835341            #endif
    45845342                );
    4585                 args->length = sig->length;
     5343                args->length = (word16)sig->length;
    45865344            }
    45875345        #endif /* HAVE_ECC */
     
    45915349                    args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
    45925350                    &sig->length, (ed25519_key*)ssl->hsKey,
    4593             #if defined(HAVE_PK_CALLBACKS)
    4594                     ssl->buffers.key->buffer, ssl->buffers.key->length,
    4595                     ssl->Ed25519SignCtx
     5351            #ifdef HAVE_PK_CALLBACKS
     5352                    ssl->buffers.key
    45965353            #else
    4597                     NULL, 0, NULL
     5354                    NULL
    45985355            #endif
    45995356                );
     
    46085365                    args->sigAlgo, ssl->suites->hashAlgo,
    46095366                    (RsaKey*)ssl->hsKey,
    4610                     ssl->buffers.key->buffer, ssl->buffers.key->length,
    4611                 #ifdef HAVE_PK_CALLBACKS
    4612                     ssl->RsaSignCtx
    4613                 #else
    4614                     NULL
    4615                 #endif
     5367                    ssl->buffers.key
    46165368                );
    4617                 args->length = args->sigLen;
     5369                if (ret == 0) {
     5370                    args->length = (word16)args->sigLen;
     5371
     5372                    XMEMCPY(args->sigData,
     5373                        args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
     5374                        args->sigLen);
     5375                }
    46185376            }
    46195377        #endif /* !NO_RSA */
     
    46365394        #ifndef NO_RSA
    46375395            if (ssl->hsType == DYNAMIC_TYPE_RSA) {
    4638                 if (args->verifySig == NULL) {
    4639                     args->verifySig = (byte*)XMALLOC(args->sigLen, ssl->heap,
    4640                                                    DYNAMIC_TYPE_SIGNATURE);
    4641                     if (args->verifySig == NULL) {
    4642                         ERROR_OUT(MEMORY_E, exit_scv);
    4643                     }
    4644                     XMEMCPY(args->verifySig,
    4645                         args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
    4646                         args->sigLen);
    4647                 }
    4648 
    46495396                /* check for signature faults */
    4650                 ret = VerifyRsaSign(ssl, args->verifySig, args->sigLen,
     5397                ret = VerifyRsaSign(ssl, args->sigData, args->sigLen,
    46515398                    sig->buffer, sig->length, args->sigAlgo,
    4652                     ssl->suites->hashAlgo, (RsaKey*)ssl->hsKey);
     5399                    ssl->suites->hashAlgo, (RsaKey*)ssl->hsKey,
     5400                    ssl->buffers.key
     5401                );
    46535402            }
    46545403        #endif /* !NO_RSA */
     
    46975446        #ifdef WOLFSSL_CALLBACKS
    46985447            if (ssl->hsInfoOn)
    4699                 AddPacketName("CertificateVerify", &ssl->handShakeInfo);
     5448                AddPacketName(ssl, "CertificateVerify");
    47005449            if (ssl->toInfoOn) {
    4701                 AddPacketInfo("CertificateVerify", &ssl->timeoutInfo,
    4702                               args->output, args->sendSz, ssl->heap);
     5450                AddPacketInfo(ssl, "CertificateVerify", handshake,
     5451                            args->output, args->sendSz, WRITE_PROTO, ssl->heap);
    47035452            }
    47045453        #endif
     
    47175466
    47185467    WOLFSSL_LEAVE("SendTls13CertificateVerify", ret);
     5468    WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_SEND);
    47195469
    47205470#ifdef WOLFSSL_ASYNC_CRYPT
     
    47325482}
    47335483
    4734 
     5484/* handle processing TLS v1.3 certificate (11) */
    47355485/* Parse and handle a TLS v1.3 Certificate message.
    47365486 *
     
    47475497    int ret;
    47485498
     5499    WOLFSSL_START(WC_FUNC_CERTIFICATE_DO);
    47495500    WOLFSSL_ENTER("DoTls13Certificate");
    47505501
    47515502    ret = ProcessPeerCerts(ssl, input, inOutIdx, totalSz);
    4752 
     5503    if (ret == 0) {
     5504#if !defined(NO_WOLFSSL_CLIENT)
     5505        if (ssl->options.side == WOLFSSL_CLIENT_END)
     5506            ssl->options.serverState = SERVER_CERT_COMPLETE;
     5507#endif
    47535508#if !defined(NO_WOLFSSL_SERVER) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
    4754     if (ret == 0 && ssl->options.side == WOLFSSL_SERVER_END &&
     5509        if (ssl->options.side == WOLFSSL_SERVER_END &&
    47555510                                ssl->options.handShakeState == HANDSHAKE_DONE) {
    47565511        /* reset handshake states */
     
    47605515    }
    47615516#endif
     5517    }
    47625518
    47635519    WOLFSSL_LEAVE("DoTls13Certificate", ret);
     5520    WOLFSSL_END(WC_FUNC_CERTIFICATE_DO);
    47645521
    47655522    return ret;
     
    47945551}
    47955552
     5553/* handle processing TLS v1.3 certificate_verify (15) */
    47965554/* Parse and handle a TLS v1.3 CertificateVerify message.
    47975555 *
     
    48175575#endif
    48185576
     5577    WOLFSSL_START(WC_FUNC_CERTIFICATE_VERIFY_DO);
    48195578    WOLFSSL_ENTER("DoTls13CertificateVerify");
    48205579
     
    48475606        {
    48485607        #ifdef WOLFSSL_CALLBACKS
    4849             if (ssl->hsInfoOn) AddPacketName("CertificateVerify",
    4850                                              &ssl->handShakeInfo);
     5608            if (ssl->hsInfoOn) AddPacketName(ssl, "CertificateVerify");
    48515609            if (ssl->toInfoOn) AddLateName("CertificateVerify",
    48525610                                           &ssl->timeoutInfo);
     
    49265684                if (ret < 0)
    49275685                    goto exit_dcv;
    4928                 args->sigDataSz = ret;
     5686                args->sigDataSz = (word16)ret;
    49295687                ret = 0;
    49305688            }
     
    49535711        {
    49545712        #ifndef NO_RSA
    4955             if (args->sigAlgo == rsa_sa_algo ||
    4956                                              args->sigAlgo == rsa_pss_sa_algo) {
     5713            if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) {
    49575714                WOLFSSL_MSG("Doing RSA peer cert verify");
    49585715
     
    49605717                    args->sigAlgo, args->hashAlgo, ssl->peerRsaKey,
    49615718                #ifdef HAVE_PK_CALLBACKS
    4962                     ssl->buffers.peerRsaKey.buffer,
    4963                     ssl->buffers.peerRsaKey.length,
    4964                     ssl->RsaVerifyCtx
     5719                    &ssl->buffers.peerRsaKey
    49655720                #else
    4966                     NULL, 0, NULL
     5721                    NULL
    49675722                #endif
    49685723                );
     
    49705725                    args->sendSz = ret;
    49715726                    ret = 0;
     5727
     5728                    FreeKey(ssl, DYNAMIC_TYPE_RSA, (void**)&ssl->peerRsaKey);
     5729                    ssl->peerRsaKeyPresent = 0;
    49725730                }
    49735731            }
     
    49815739                    ssl->peerEccDsaKey,
    49825740                #ifdef HAVE_PK_CALLBACKS
    4983                     ssl->buffers.peerEccDsaKey.buffer,
    4984                     ssl->buffers.peerEccDsaKey.length,
    4985                     ssl->EccVerifyCtx
     5741                    &ssl->buffers.peerEccDsaKey
    49865742                #else
    4987                     NULL, 0, NULL
     5743                    NULL
    49885744                #endif
    49895745                );
     5746
     5747                if (ret >= 0) {
     5748                    FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccDsaKey);
     5749                    ssl->peerEccDsaKeyPresent = 0;
     5750                }
    49905751            }
    49915752        #endif /* HAVE_ECC */
     
    49985759                    ssl->peerEd25519Key,
    49995760                #ifdef HAVE_PK_CALLBACKS
    5000                     ssl->buffers.peerEd25519Key.buffer,
    5001                     ssl->buffers.peerEd25519Key.length,
    5002                     ssl->Ed25519VerifyCtx
     5761                    &ssl->buffers.peerEd25519Key
    50035762                #else
    5004                     NULL, 0, NULL
     5763                    NULL
    50055764                #endif
    50065765                );
     5766
     5767                if (ret >= 0) {
     5768                    FreeKey(ssl, DYNAMIC_TYPE_ED25519,
     5769                                                  (void**)&ssl->peerEd25519Key);
     5770                    ssl->peerEd25519KeyPresent = 0;
     5771                }
    50075772            }
    50085773        #endif
     
    50605825
    50615826    WOLFSSL_LEAVE("DoTls13CertificateVerify", ret);
     5827    WOLFSSL_END(WC_FUNC_CERTIFICATE_VERIFY_DO);
    50625828
    50635829#ifdef WOLFSSL_ASYNC_CRYPT
    50645830    /* Handle async operation */
    50655831    if (ret == WC_PENDING_E) {
    5066         /* Mark message as not recevied so it can process again */
     5832        /* Mark message as not received so it can process again */
    50675833        ssl->msgsReceived.got_certificate_verify = 0;
    50685834
    50695835        return ret;
    50705836    }
     5837    else
    50715838#endif /* WOLFSSL_ASYNC_CRYPT */
     5839    if (ret != 0)
     5840        SendAlert(ssl, alert_fatal, decrypt_error);
    50725841
    50735842    /* Final cleanup */
     
    50965865    word32 finishedSz = 0;
    50975866    byte*  secret;
    5098     byte   mac[MAX_DIGEST_SIZE];
    5099 
     5867    byte   mac[WC_MAX_DIGEST_SIZE];
     5868
     5869    WOLFSSL_START(WC_FUNC_FINISHED_DO);
    51005870    WOLFSSL_ENTER("DoTls13Finished");
    51015871
     
    51045874        return BUFFER_E;
    51055875
    5106     if (ssl->options.side == WOLFSSL_CLIENT_END) {
     5876    if (ssl->options.handShakeDone) {
     5877        ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
     5878                                   ssl->keys.client_write_MAC_secret);
     5879        if (ret != 0)
     5880            return ret;
     5881
     5882        secret = ssl->keys.client_write_MAC_secret;
     5883    }
     5884    else if (ssl->options.side == WOLFSSL_CLIENT_END) {
    51075885        /* All the handshake messages have been received to calculate
    51085886         * client and server finished keys.
    51095887         */
    5110         ret = DeriveFinishedSecret(ssl, ssl->arrays->clientSecret,
     5888        ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
    51115889                                   ssl->keys.client_write_MAC_secret);
    51125890        if (ret != 0)
    51135891            return ret;
    51145892
    5115         ret = DeriveFinishedSecret(ssl, ssl->arrays->serverSecret,
     5893        ret = DeriveFinishedSecret(ssl, ssl->serverSecret,
    51165894                                   ssl->keys.server_write_MAC_secret);
    51175895        if (ret != 0)
     
    51305908
    51315909    #ifdef WOLFSSL_CALLBACKS
    5132         if (ssl->hsInfoOn) AddPacketName("Finished", &ssl->handShakeInfo);
     5910        if (ssl->hsInfoOn) AddPacketName(ssl, "Finished");
    51335911        if (ssl->toInfoOn) AddLateName("Finished", &ssl->timeoutInfo);
    51345912    #endif
     
    51385916        if (XMEMCMP(input + *inOutIdx, mac, size) != 0){
    51395917            WOLFSSL_MSG("Verify finished error on hashes");
     5918            SendAlert(ssl, alert_fatal, decrypt_error);
    51405919            return VERIFY_FINISHED_ERROR;
    51415920        }
     
    51485927                                                  !ssl->options.handShakeDone) {
    51495928#ifdef WOLFSSL_EARLY_DATA
    5150         if (ssl->earlyData) {
     5929        if (ssl->earlyData != no_early_data) {
    51515930            if ((ret = DeriveTls13Keys(ssl, no_key, DECRYPT_SIDE_ONLY, 1)) != 0)
    51525931                return ret;
     
    51715950
    51725951    WOLFSSL_LEAVE("DoTls13Finished", 0);
     5952    WOLFSSL_END(WC_FUNC_FINISHED_DO);
    51735953
    51745954    return 0;
     
    51925972    byte* secret;
    51935973
     5974    WOLFSSL_START(WC_FUNC_FINISHED_SEND);
    51945975    WOLFSSL_ENTER("SendTls13Finished");
    51955976
    5196     outputSz = MAX_DIGEST_SIZE + DTLS_HANDSHAKE_HEADER_SZ + MAX_MSG_EXTRA;
     5977    outputSz = WC_MAX_DIGEST_SIZE + DTLS_HANDSHAKE_HEADER_SZ + MAX_MSG_EXTRA;
    51975978    /* Check buffers are big enough and grow if needed. */
    51985979    if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
     
    52075988
    52085989    /* make finished hashes */
    5209     if (ssl->options.side == WOLFSSL_CLIENT_END)
     5990    if (ssl->options.handShakeDone) {
     5991        ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
     5992                                   ssl->keys.client_write_MAC_secret);
     5993        if (ret != 0)
     5994            return ret;
     5995
     5996        secret = ssl->keys.client_write_MAC_secret;
     5997    }
     5998    else if (ssl->options.side == WOLFSSL_CLIENT_END)
    52105999        secret = ssl->keys.client_write_MAC_secret;
    52116000    else {
     
    52136002         * server finished keys.
    52146003         */
    5215         ret = DeriveFinishedSecret(ssl, ssl->arrays->clientSecret,
     6004        ret = DeriveFinishedSecret(ssl, ssl->clientSecret,
    52166005                                   ssl->keys.client_write_MAC_secret);
    52176006        if (ret != 0)
    52186007            return ret;
    52196008
    5220         ret = DeriveFinishedSecret(ssl, ssl->arrays->serverSecret,
     6009        ret = DeriveFinishedSecret(ssl, ssl->serverSecret,
    52216010                                   ssl->keys.server_write_MAC_secret);
    52226011        if (ret != 0)
     
    52356024        return BUILD_MSG_ERROR;
    52366025
    5237     if (!ssl->options.resuming) {
     6026    if (!ssl->options.resuming && ssl->options.side == WOLFSSL_SERVER_END) {
    52386027#ifndef NO_SESSION_CACHE
    52396028        AddSession(ssl);    /* just try */
     
    52426031
    52436032    #ifdef WOLFSSL_CALLBACKS
    5244         if (ssl->hsInfoOn) AddPacketName("Finished", &ssl->handShakeInfo);
     6033        if (ssl->hsInfoOn) AddPacketName(ssl, "Finished");
    52456034        if (ssl->toInfoOn) {
    5246             AddPacketInfo("Finished", &ssl->timeoutInfo, output, sendSz,
    5247                           ssl->heap);
     6035            AddPacketInfo(ssl, "Finished", handshake, output, sendSz,
     6036                          WRITE_PROTO, ssl->heap);
    52486037        }
    52496038    #endif
    52506039
    52516040    ssl->buffers.outputBuffer.length += sendSz;
    5252 
    5253     if ((ret = SendBuffered(ssl)) != 0)
    5254         return ret;
    52556041
    52566042    if (ssl->options.side == WOLFSSL_SERVER_END) {
     
    52646050        }
    52656051        if ((ret = DeriveTls13Keys(ssl, traffic_key, DECRYPT_SIDE_ONLY,
    5266                                                        !ssl->earlyData)) != 0) {
     6052                                       ssl->earlyData == no_early_data)) != 0) {
    52676053            return ret;
    52686054        }
     
    52806066                                                  !ssl->options.handShakeDone) {
    52816067#ifdef WOLFSSL_EARLY_DATA
    5282         if (ssl->earlyData) {
     6068        if (ssl->earlyData != no_early_data) {
    52836069            if ((ret = DeriveTls13Keys(ssl, no_key, ENCRYPT_AND_DECRYPT_SIDE,
    52846070                                                                     1)) != 0) {
     
    52936079#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
    52946080        ret = DeriveResumptionSecret(ssl, ssl->session.masterSecret);
    5295 #endif
    5296     }
    5297 
    5298     if (ssl->options.resuming) {
    5299         if (ssl->options.side == WOLFSSL_CLIENT_END) {
     6081        if (ret != 0)
     6082            return ret;
     6083#endif
     6084    }
     6085
     6086#ifndef NO_WOLFSSL_CLIENT
     6087    if (ssl->options.side == WOLFSSL_CLIENT_END) {
     6088        ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
    53006089            ssl->options.handShakeState = HANDSHAKE_DONE;
    53016090            ssl->options.handShakeDone  = 1;
    53026091        }
    5303     }
    5304 #ifndef NO_WOLFSSL_CLIENT
    5305     if (ssl->options.side == WOLFSSL_CLIENT_END) {
    5306         if (!ssl->options.resuming) {
    5307             ssl->options.handShakeState = HANDSHAKE_DONE;
    5308             ssl->options.handShakeDone  = 1;
    5309         }
    5310     }
    5311 #endif
     6092#endif
     6093#ifndef NO_WOLFSSL_SERVER
     6094    if (ssl->options.side == WOLFSSL_SERVER_END) {
     6095        ssl->options.serverState = SERVER_FINISHED_COMPLETE;
     6096    }
     6097#endif
     6098
     6099    if ((ret = SendBuffered(ssl)) != 0)
     6100        return ret;
    53126101
    53136102    WOLFSSL_LEAVE("SendTls13Finished", ret);
     6103    WOLFSSL_END(WC_FUNC_FINISHED_SEND);
    53146104
    53156105    return ret;
    53166106}
    53176107
     6108/* handle generation TLS v1.3 key_update (24) */
    53186109/* Send the TLS v1.3 KeyUpdate message.
    53196110 *
     
    53316122    word32 i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
    53326123
     6124    WOLFSSL_START(WC_FUNC_KEY_UPDATE_SEND);
    53336125    WOLFSSL_ENTER("SendTls13KeyUpdate");
    53346126
     
    53626154
    53636155    #ifdef WOLFSSL_CALLBACKS
    5364         if (ssl->hsInfoOn) AddPacketName("KeyUpdate", &ssl->handShakeInfo);
     6156        if (ssl->hsInfoOn) AddPacketName(ssl, "KeyUpdate");
    53656157        if (ssl->toInfoOn) {
    5366             AddPacketInfo("KeyUpdate", &ssl->timeoutInfo, output, sendSz,
    5367                           ssl->heap);
     6158            AddPacketInfo(ssl, "KeyUpdate", handshake, output, sendSz,
     6159                          WRITE_PROTO, ssl->heap);
    53686160        }
    53696161    #endif
     
    53836175
    53846176    WOLFSSL_LEAVE("SendTls13KeyUpdate", ret);
     6177    WOLFSSL_END(WC_FUNC_KEY_UPDATE_SEND);
    53856178
    53866179    return ret;
    53876180}
    53886181
     6182/* handle processing TLS v1.3 key_update (24) */
    53896183/* Parse and handle a TLS v1.3 KeyUpdate message.
    53906184 *
     
    54026196    word32 i = *inOutIdx;
    54036197
     6198    WOLFSSL_START(WC_FUNC_KEY_UPDATE_DO);
    54046199    WOLFSSL_ENTER("DoTls13KeyUpdate");
    54056200
     
    54406235
    54416236    WOLFSSL_LEAVE("DoTls13KeyUpdate", ret);
     6237    WOLFSSL_END(WC_FUNC_KEY_UPDATE_DO);
    54426238
    54436239    return 0;
     
    54616257    word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
    54626258
     6259    WOLFSSL_START(WC_FUNC_END_OF_EARLY_DATA_SEND);
    54636260    WOLFSSL_ENTER("SendTls13EndOfEarlyData");
    54646261
     
    54926289
    54936290    WOLFSSL_LEAVE("SendTls13EndOfEarlyData", ret);
     6291    WOLFSSL_END(WC_FUNC_END_OF_EARLY_DATA_SEND);
    54946292
    54956293    return ret;
     
    54986296
    54996297#ifndef NO_WOLFSSL_SERVER
     6298/* handle processing of TLS 1.3 end_of_early_data (5) */
    55006299/* Parse the TLS v1.3 EndOfEarlyData message that indicates that there will be
    55016300 * no more early application data.
     
    55136312    (void)input;
    55146313
     6314    WOLFSSL_START(WC_FUNC_END_OF_EARLY_DATA_DO);
    55156315    WOLFSSL_ENTER("DoTls13EndOfEarlyData");
    55166316
     
    55186318        return BUFFER_ERROR;
    55196319
     6320    if (ssl->earlyData == no_early_data) {
     6321        WOLFSSL_MSG("EndOfEarlyData recieved unexpectedly");
     6322        SendAlert(ssl, alert_fatal, unexpected_message);
     6323        return OUT_OF_ORDER_E;
     6324    }
     6325
     6326    ssl->earlyData = done_early_data;
     6327
    55206328    /* Always encrypted. */
    55216329    *inOutIdx += ssl->keys.padSz;
     
    55236331    ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY);
    55246332
    5525     WOLFSSL_LEAVE("SendTls13EndOfEarlyData", ret);
     6333    WOLFSSL_LEAVE("DoTls13EndOfEarlyData", ret);
     6334    WOLFSSL_END(WC_FUNC_END_OF_EARLY_DATA_DO);
    55266335
    55276336    return ret;
     
    55516360    word16 length;
    55526361    word32 now;
    5553 
     6362#ifndef WOLFSSL_TLS13_DRAFT_18
     6363    const byte*  nonce;
     6364    byte         nonceLength;
     6365#endif
     6366
     6367    WOLFSSL_START(WC_FUNC_NEW_SESSION_TICKET_DO);
    55546368    WOLFSSL_ENTER("DoTls13NewSessionTicket");
    55556369
     
    55676381    ato32(input + *inOutIdx, &ageAdd);
    55686382    *inOutIdx += SESSION_ADD_SZ;
     6383
     6384#ifndef WOLFSSL_TLS13_DRAFT_18
     6385    /* Ticket nonce. */
     6386    if ((*inOutIdx - begin) + 1 > size)
     6387        return BUFFER_ERROR;
     6388    nonceLength = input[*inOutIdx];
     6389    if (nonceLength > MAX_TICKET_NONCE_SZ) {
     6390        WOLFSSL_MSG("Nonce length not supported");
     6391        return INVALID_PARAMETER;
     6392    }
     6393    *inOutIdx += 1;
     6394    if ((*inOutIdx - begin) + nonceLength > size)
     6395        return BUFFER_ERROR;
     6396    nonce = input + *inOutIdx;
     6397    *inOutIdx += nonceLength;
     6398#endif
    55696399
    55706400    /* Ticket length. */
     
    55936423    ssl->session.maxEarlyDataSz = ssl->options.maxEarlyDataSz;
    55946424    #endif
     6425#ifndef WOLFSSL_TLS13_DRAFT_18
     6426    ssl->session.ticketNonce.len = nonceLength;
     6427    if (nonceLength > 0)
     6428        XMEMCPY(&ssl->session.ticketNonce.data, nonce, nonceLength);
     6429#endif
     6430    ssl->session.namedGroup     = ssl->namedGroup;
    55956431
    55966432    if ((*inOutIdx - begin) + EXTS_SZ > size)
     
    56266462
    56276463    WOLFSSL_LEAVE("DoTls13NewSessionTicket", 0);
     6464    WOLFSSL_END(WC_FUNC_NEW_SESSION_TICKET_DO);
    56286465
    56296466    return 0;
     
    56486485    int         ret;
    56496486    word32      finishedSz = 0;
    5650     byte        mac[MAX_DIGEST_SIZE];
     6487    byte        mac[WC_MAX_DIGEST_SIZE];
    56516488    Digest      digest;
    56526489    static byte header[] = { 0x14, 0x00, 0x00, 0x00 };
     
    56846521    header[FINISHED_MSG_SIZE_OFFSET] = finishedSz;
    56856522#ifdef WOLFSSL_EARLY_DATA
    5686     if (ssl->earlyData) {
     6523    if (ssl->earlyData != no_early_data) {
    56876524        static byte endOfEarlyData[] = { 0x05, 0x00, 0x00, 0x00 };
    56886525        ret = HashInputRaw(ssl, endOfEarlyData, sizeof(endOfEarlyData));
     
    57396576    int    ret;
    57406577    int    sendSz;
    5741     word32 extSz;
     6578    word16 extSz;
    57426579    word32 length;
    57436580    word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
    57446581
     6582    WOLFSSL_START(WC_FUNC_NEW_SESSION_TICKET_SEND);
    57456583    WOLFSSL_ENTER("SendTls13NewSessionTicket");
    57466584
     
    57526590#endif
    57536591
     6592#ifndef WOLFSSL_TLS13_DRAFT_18
     6593    /* Start ticket nonce at 0 and go up to 255. */
     6594    if (ssl->session.ticketNonce.len == 0) {
     6595        ssl->session.ticketNonce.len = DEF_TICKET_NONCE_SZ;
     6596        ssl->session.ticketNonce.data[0] = 0;
     6597    }
     6598    else
     6599        ssl->session.ticketNonce.data[0]++;
     6600#endif
     6601
    57546602    if (!ssl->options.noTicketTls13) {
    57556603        if ((ret = CreateTicket(ssl)) != 0)
     
    57616609    if (ssl->session.maxEarlyDataSz > 0)
    57626610        TLSX_EarlyData_Use(ssl, ssl->session.maxEarlyDataSz);
    5763     extSz = TLSX_GetResponseSize(ssl, session_ticket);
     6611    extSz = 0;
     6612    ret = TLSX_GetResponseSize(ssl, session_ticket, &extSz);
     6613    if (ret != 0)
     6614        return ret;
    57646615#else
    57656616    extSz = EXTS_SZ;
     
    57696620    length = SESSION_HINT_SZ + SESSION_ADD_SZ + LENGTH_SZ +
    57706621             ssl->session.ticketLen + extSz;
     6622#ifndef WOLFSSL_TLS13_DRAFT_18
     6623    /* Nonce */
     6624    length += TICKET_NONCE_LEN_SZ + DEF_TICKET_NONCE_SZ;
     6625#endif
    57716626    sendSz = idx + length + MAX_MSG_EXTRA;
    57726627
     
    57896644    idx += SESSION_ADD_SZ;
    57906645
     6646#ifndef WOLFSSL_TLS13_DRAFT_18
     6647    output[idx++] = ssl->session.ticketNonce.len;
     6648    output[idx++] = ssl->session.ticketNonce.data[0];
     6649#endif
     6650
    57916651    /* length */
    57926652    c16toa(ssl->session.ticketLen, output + idx);
     
    57976657
    57986658#ifdef WOLFSSL_EARLY_DATA
    5799     idx += TLSX_WriteResponse(ssl, output + idx, session_ticket);
     6659    extSz = 0;
     6660    ret = TLSX_WriteResponse(ssl, output + idx, session_ticket, &extSz);
     6661    if (ret != 0)
     6662        return ret;
     6663    idx += extSz;
    58006664#else
    58016665    /* No extension support - empty extensions. */
     
    58226686
    58236687    WOLFSSL_LEAVE("SendTls13NewSessionTicket", 0);
     6688    WOLFSSL_END(WC_FUNC_NEW_SESSION_TICKET_SEND);
    58246689
    58256690    return ret;
     
    58416706#ifndef NO_WOLFSSL_SERVER
    58426707        case client_hello:
     6708        #ifndef NO_WOLFSSL_CLIENT
     6709            if (ssl->options.side == WOLFSSL_CLIENT_END) {
     6710                WOLFSSL_MSG("ClientHello received by client");
     6711                return OUT_OF_ORDER_E;
     6712            }
     6713        #endif
     6714            if (ssl->options.clientState >= CLIENT_HELLO_COMPLETE) {
     6715                WOLFSSL_MSG("ClientHello received out of order");
     6716                return OUT_OF_ORDER_E;
     6717            }
    58436718            if (ssl->msgsReceived.got_client_hello == 2) {
    58446719                WOLFSSL_MSG("Too many ClientHello received");
     
    58526727#ifndef NO_WOLFSSL_CLIENT
    58536728        case server_hello:
     6729        #ifndef NO_WOLFSSL_SERVER
     6730            if (ssl->options.side == WOLFSSL_SERVER_END) {
     6731                WOLFSSL_MSG("ServerHello received by server");
     6732                return OUT_OF_ORDER_E;
     6733            }
     6734        #endif
     6735        #ifdef WOLFSSL_TLS13_DRAFT_18
    58546736            if (ssl->msgsReceived.got_server_hello) {
    58556737                WOLFSSL_MSG("Duplicate ServerHello received");
     
    58576739            }
    58586740            ssl->msgsReceived.got_server_hello = 1;
     6741        #else
     6742            if (ssl->msgsReceived.got_server_hello == 2) {
     6743                WOLFSSL_MSG("Duplicate ServerHello received");
     6744                return DUPLICATE_MSG_E;
     6745            }
     6746            ssl->msgsReceived.got_server_hello++;
     6747        #endif
    58596748
    58606749            break;
     
    58636752#ifndef NO_WOLFSSL_CLIENT
    58646753        case session_ticket:
    5865             if (ssl->msgsReceived.got_session_ticket) {
    5866                 WOLFSSL_MSG("Duplicate SessionTicket received");
    5867                 return DUPLICATE_MSG_E;
     6754        #ifndef NO_WOLFSSL_SERVER
     6755            if (ssl->options.side == WOLFSSL_SERVER_END) {
     6756                WOLFSSL_MSG("NewSessionTicket received by server");
     6757                return OUT_OF_ORDER_E;
     6758            }
     6759        #endif
     6760            if (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
     6761                WOLFSSL_MSG("NewSessionTicket received out of order");
     6762                return OUT_OF_ORDER_E;
    58686763            }
    58696764            ssl->msgsReceived.got_session_ticket = 1;
     
    58756770    #ifdef WOLFSSL_EARLY_DATA
    58766771        case end_of_early_data:
     6772        #ifndef NO_WOLFSSL_CLIENT
     6773            if (ssl->options.side == WOLFSSL_CLIENT_END) {
     6774                WOLFSSL_MSG("EndOfEarlyData received by client");
     6775                return OUT_OF_ORDER_E;
     6776            }
     6777        #endif
     6778            if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
     6779                WOLFSSL_MSG("EndOfEarlyData received out of order");
     6780                return OUT_OF_ORDER_E;
     6781            }
     6782            if (ssl->options.clientState >= CLIENT_FINISHED_COMPLETE) {
     6783                WOLFSSL_MSG("EndOfEarlyData received out of order");
     6784                return OUT_OF_ORDER_E;
     6785            }
    58776786            if (ssl->msgsReceived.got_end_of_early_data == 1) {
    58786787                WOLFSSL_MSG("Too many EndOfEarlyData received");
     
    58856794#endif
    58866795
     6796#ifdef WOLFSSL_TLS13_DRAFT_18
    58876797#ifndef NO_WOLFSSL_CLIENT
    58886798        case hello_retry_request:
     6799        #ifndef NO_WOLFSSL_SERVER
     6800            if (ssl->options.side == WOLFSSL_SERVER_END) {
     6801                WOLFSSL_MSG("HelloRetryRequest received by server");
     6802                return OUT_OF_ORDER_E;
     6803            }
     6804        #endif
     6805            if (ssl->options.clientState > CLIENT_FINISHED_COMPLETE) {
     6806                WOLFSSL_MSG("HelloRetryRequest received out of order");
     6807                return OUT_OF_ORDER_E;
     6808            }
    58896809            if (ssl->msgsReceived.got_hello_retry_request) {
    58906810                WOLFSSL_MSG("Duplicate HelloRetryRequest received");
     
    58956815            break;
    58966816#endif
     6817#endif
    58976818
    58986819#ifndef NO_WOLFSSL_CLIENT
    58996820        case encrypted_extensions:
     6821        #ifndef NO_WOLFSSL_SERVER
     6822            if (ssl->options.side == WOLFSSL_SERVER_END) {
     6823                WOLFSSL_MSG("EncryptedExtensions received by server");
     6824                return OUT_OF_ORDER_E;
     6825            }
     6826        #endif
     6827            if (ssl->options.serverState != SERVER_HELLO_COMPLETE) {
     6828                WOLFSSL_MSG("EncryptedExtensions received out of order");
     6829                return OUT_OF_ORDER_E;
     6830            }
    59006831            if (ssl->msgsReceived.got_encrypted_extensions) {
    59016832                WOLFSSL_MSG("Duplicate EncryptedExtensions received");
     
    59086839
    59096840        case certificate:
     6841    #ifndef NO_WOLFSSL_CLIENT
     6842            if (ssl->options.side == WOLFSSL_CLIENT_END &&
     6843                ssl->options.serverState !=
     6844                                         SERVER_ENCRYPTED_EXTENSIONS_COMPLETE) {
     6845                WOLFSSL_MSG("Certificate received out of order - Client");
     6846                return OUT_OF_ORDER_E;
     6847            }
     6848        #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
     6849            /* Server's authenticating with PSK must not send this. */
     6850            if (ssl->options.side == WOLFSSL_CLIENT_END &&
     6851                             ssl->options.serverState == SERVER_CERT_COMPLETE &&
     6852                             ssl->arrays->psk_keySz != 0) {
     6853                WOLFSSL_MSG("Certificate received while using PSK");
     6854                return SANITY_MSG_E;
     6855            }
     6856        #endif
     6857    #endif
     6858    #ifndef NO_WOLFSSL_SERVER
     6859            if (ssl->options.side == WOLFSSL_SERVER_END &&
     6860                ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
     6861                WOLFSSL_MSG("Certificate received out of order - Server");
     6862                return OUT_OF_ORDER_E;
     6863            }
     6864    #endif
    59106865            if (ssl->msgsReceived.got_certificate) {
    59116866                WOLFSSL_MSG("Duplicate Certificate received");
     
    59146869            ssl->msgsReceived.got_certificate = 1;
    59156870
     6871            break;
     6872
    59166873#ifndef NO_WOLFSSL_CLIENT
    5917             if (ssl->options.side == WOLFSSL_CLIENT_END) {
    5918                 if ( ssl->msgsReceived.got_server_hello == 0) {
    5919                     WOLFSSL_MSG("No ServerHello before Cert");
     6874        case certificate_request:
     6875        #ifndef NO_WOLFSSL_SERVER
     6876            if (ssl->options.side == WOLFSSL_SERVER_END) {
     6877                WOLFSSL_MSG("CertificateRequest received by server");
    59206878                    return OUT_OF_ORDER_E;
    59216879                }
    5922             }
    5923 #endif
    5924 #ifndef NO_WOLFSSL_SERVER
    5925             if (ssl->options.side == WOLFSSL_SERVER_END) {
    5926                 if ( ssl->msgsReceived.got_client_hello == 0) {
    5927                     WOLFSSL_MSG("No ClientHello before Cert");
     6880#endif
     6881        #ifndef WOLFSSL_POST_HANDSHAKE_AUTH
     6882            if (ssl->options.serverState !=
     6883                                         SERVER_ENCRYPTED_EXTENSIONS_COMPLETE) {
     6884                WOLFSSL_MSG("CertificateRequest received out of order");
    59286885                    return OUT_OF_ORDER_E;
    59296886                }
    5930             }
    5931 #endif
    5932             break;
    5933 
    5934 #ifndef NO_WOLFSSL_CLIENT
    5935         case certificate_request:
    5936     #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
    5937             if (ssl->msgsReceived.got_finished)
    5938                 ;
    5939             else
     6887        #else
     6888            if (ssl->options.serverState !=
     6889                                         SERVER_ENCRYPTED_EXTENSIONS_COMPLETE &&
     6890                       (ssl->options.serverState != SERVER_FINISHED_COMPLETE ||
     6891                        ssl->options.clientState != CLIENT_FINISHED_COMPLETE)) {
     6892                WOLFSSL_MSG("CertificateRequest received out of order");
     6893                return OUT_OF_ORDER_E;
     6894            }
     6895#endif
     6896        #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
     6897            /* Server's authenticating with PSK must not send this. */
     6898            if (ssl->options.serverState ==
     6899                                         SERVER_ENCRYPTED_EXTENSIONS_COMPLETE &&
     6900                                                  ssl->arrays->psk_keySz != 0) {
     6901                WOLFSSL_MSG("CertificateRequset received while using PSK");
     6902                return SANITY_MSG_E;
     6903            }
    59406904    #endif
     6905        #ifndef WOLFSSL_POST_HANDSHAKE_AUTH
    59416906            if (ssl->msgsReceived.got_certificate_request) {
    59426907                WOLFSSL_MSG("Duplicate CertificateRequest received");
    59436908                return DUPLICATE_MSG_E;
    59446909            }
     6910        #endif
    59456911            ssl->msgsReceived.got_certificate_request = 1;
    59466912
     
    59496915
    59506916        case certificate_verify:
     6917    #ifndef NO_WOLFSSL_CLIENT
     6918            if (ssl->options.side == WOLFSSL_CLIENT_END) {
     6919                if (ssl->options.serverState != SERVER_CERT_COMPLETE) {
     6920                    WOLFSSL_MSG("No Cert before CertVerify");
     6921                    return OUT_OF_ORDER_E;
     6922                }
     6923            #if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
     6924                /* Server's authenticating with PSK must not send this. */
     6925                if (ssl->options.serverState == SERVER_CERT_COMPLETE &&
     6926                                                  ssl->arrays->psk_keySz != 0) {
     6927                    WOLFSSL_MSG("CertificateVerify received while using PSK");
     6928                    return SANITY_MSG_E;
     6929                }
     6930            #endif
     6931            }
     6932    #endif
     6933    #ifndef NO_WOLFSSL_SERVER
     6934            if (ssl->options.side == WOLFSSL_SERVER_END) {
     6935                if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
     6936                    WOLFSSL_MSG("CertificateVerify received out of order");
     6937                    return OUT_OF_ORDER_E;
     6938                }
     6939                if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
     6940                    WOLFSSL_MSG("CertificateVerify before ClientHello done");
     6941                    return OUT_OF_ORDER_E;
     6942                }
     6943                if (!ssl->msgsReceived.got_certificate) {
     6944                    WOLFSSL_MSG("No Cert before CertificateVerify");
     6945                    return OUT_OF_ORDER_E;
     6946                }
     6947            }
     6948    #endif
    59516949            if (ssl->msgsReceived.got_certificate_verify) {
    59526950                WOLFSSL_MSG("Duplicate CertificateVerify received");
     
    59556953            ssl->msgsReceived.got_certificate_verify = 1;
    59566954
    5957             if (ssl->msgsReceived.got_certificate == 0) {
    5958                 WOLFSSL_MSG("No Cert before CertVerify");
    5959                 return OUT_OF_ORDER_E;
    5960             }
    59616955            break;
    59626956
    59636957        case finished:
    5964     #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
    5965             if (1) {
    5966             }
    5967             else
     6958        #ifndef NO_WOLFSSL_CLIENT
     6959            if (ssl->options.side == WOLFSSL_CLIENT_END) {
     6960                if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
     6961                    WOLFSSL_MSG("Finished received out of order");
     6962                    return OUT_OF_ORDER_E;
     6963                }
     6964                if (ssl->options.serverState <
     6965                                         SERVER_ENCRYPTED_EXTENSIONS_COMPLETE) {
     6966                    WOLFSSL_MSG("Finished received out of order");
     6967                    return OUT_OF_ORDER_E;
     6968                }
     6969            }
     6970        #endif
     6971        #ifndef NO_WOLFSSL_SERVER
     6972            if (ssl->options.side == WOLFSSL_SERVER_END) {
     6973                if (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
     6974                    WOLFSSL_MSG("Finished received out of order");
     6975                    return OUT_OF_ORDER_E;
     6976                }
     6977                if (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
     6978                    WOLFSSL_MSG("Finished received out of order");
     6979                    return OUT_OF_ORDER_E;
     6980                }
     6981            #ifdef WOLFSSL_EARLY_DATA
     6982                if (ssl->earlyData == process_early_data) {
     6983                    return OUT_OF_ORDER_E;
     6984                }
     6985            #endif
     6986            }
    59686987    #endif
    59696988            if (ssl->msgsReceived.got_finished) {
     
    60047023{
    60057024    int ret = 0;
     7025    word32 inIdx = *inOutIdx;
     7026
    60067027    (void)totalSz;
    6007     word32 inIdx = *inOutIdx;
    60087028
    60097029    WOLFSSL_ENTER("DoTls13HandShakeMsgType");
     
    60167036    if ( (ret = SanityCheckTls13MsgReceived(ssl, type)) != 0) {
    60177037        WOLFSSL_MSG("Sanity Check on handshake message type received failed");
     7038        SendAlert(ssl, alert_fatal, unexpected_message);
    60187039        return ret;
    60197040    }
     
    60237044    if (ssl->toInfoOn) {
    60247045        int add = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
    6025         AddPacketInfo(0, &ssl->timeoutInfo, input + *inOutIdx - add,
    6026                       size + add, ssl->heap);
     7046        AddPacketInfo(ssl, 0, handshake, input + *inOutIdx - add,
     7047                      size + add, READ_PROTO, ssl->heap);
    60277048        AddLateRecordHeader(&ssl->curRL, &ssl->timeoutInfo);
    60287049    }
     
    60547075    /* above checks handshake state */
    60557076    switch (type) {
    6056 
    60577077#ifndef NO_WOLFSSL_CLIENT
     7078    /* Messages only recieved by client. */
     7079    #ifdef WOLFSSL_TLS13_DRAFT_18
    60587080    case hello_retry_request:
    60597081        WOLFSSL_MSG("processing hello rety request");
    60607082        ret = DoTls13HelloRetryRequest(ssl, input, inOutIdx, size);
    60617083        break;
     7084    #endif
    60627085
    60637086    case server_hello:
    60647087        WOLFSSL_MSG("processing server hello");
    6065         ret = DoTls13ServerHello(ssl, input, inOutIdx, size);
     7088        ret = DoTls13ServerHello(ssl, input, inOutIdx, size, &type);
     7089    #if !defined(WOLFSSL_NO_CLIENT_AUTH) && defined(HAVE_ED25519) && \
     7090                                                !defined(NO_ED25519_CLIENT_AUTH)
     7091        if (ssl->options.resuming || !IsAtLeastTLSv1_2(ssl) ||
     7092                                               IsAtLeastTLSv1_3(ssl->version)) {
     7093            ssl->options.cacheMessages = 0;
     7094            if (ssl->hsHashes->messages != NULL) {
     7095                XFREE(ssl->hsHashes->messages, ssl->heap, DYNAMIC_TYPE_HASHES);
     7096                ssl->hsHashes->messages = NULL;
     7097            }
     7098        }
     7099    #endif
     7100        break;
     7101
     7102    case encrypted_extensions:
     7103        WOLFSSL_MSG("processing encrypted extensions");
     7104        ret = DoTls13EncryptedExtensions(ssl, input, inOutIdx, size);
    60667105        break;
    60677106
     
    60777116        ret = DoTls13NewSessionTicket(ssl, input, inOutIdx, size);
    60787117        break;
    6079 
    6080     case encrypted_extensions:
    6081         WOLFSSL_MSG("processing encrypted extensions");
    6082         ret = DoTls13EncryptedExtensions(ssl, input, inOutIdx, size);
     7118#endif /* !NO_WOLFSSL_CLIENT */
     7119
     7120#ifndef NO_WOLFSSL_SERVER
     7121    /* Messages only recieved by server. */
     7122    case client_hello:
     7123        WOLFSSL_MSG("processing client hello");
     7124        ret = DoTls13ClientHello(ssl, input, inOutIdx, size);
    60837125        break;
    6084 #endif /* !NO_WOLFSSL_CLIENT */
    6085 
     7126
     7127    #ifdef WOLFSSL_EARLY_DATA
     7128    case end_of_early_data:
     7129        WOLFSSL_MSG("processing end of early data");
     7130        ret = DoTls13EndOfEarlyData(ssl, input, inOutIdx, size);
     7131        break;
     7132    #endif
     7133#endif /* !NO_WOLFSSL_SERVER */
     7134
     7135    /* Messages recieved by both client and server. */
    60867136#ifndef NO_CERTS
    60877137    case certificate:
     
    60987148#endif /* !NO_RSA || HAVE_ECC */
    60997149
    6100 #ifdef WOLFSSL_EARLY_DATA
    6101     #ifndef NO_WOLFSSL_SERVER
    6102     case end_of_early_data:
    6103         WOLFSSL_MSG("processing end of early data");
    6104         ret = DoTls13EndOfEarlyData(ssl, input, inOutIdx, size);
    6105         break;
    6106     #endif
    6107 #endif
    6108 
    61097150    case finished:
    61107151        WOLFSSL_MSG("processing finished");
     
    61177158        break;
    61187159
    6119 #ifndef NO_WOLFSSL_SERVER
    6120     case client_hello:
    6121         WOLFSSL_MSG("processing client hello");
    6122         ret = DoTls13ClientHello(ssl, input, inOutIdx, size);
    6123         break;
    6124 #endif /* !NO_WOLFSSL_SERVER */
    6125 
    61267160    default:
    61277161        WOLFSSL_MSG("Unknown handshake message type");
     
    61347168        ssl->error = 0;
    61357169
    6136 
    61377170    if (ret == 0 && type != client_hello && type != session_ticket &&
    6138                              type != key_update && ssl->error != WC_PENDING_E) {
     7171                                                           type != key_update) {
    61397172        ret = HashInput(ssl, input + inIdx, size);
     7173    }
     7174    if (ret == 0 && ssl->buffers.inputBuffer.dynamicFlag) {
     7175        ShrinkInputBuffer(ssl, NO_FORCED_FREE);
    61407176    }
    61417177
    61427178    if (ret == BUFFER_ERROR || ret == MISSING_HANDSHAKE_DATA)
    61437179        SendAlert(ssl, alert_fatal, decode_error);
    6144 
    6145     if (ret == EXT_NOT_ALLOWED || ret == PEER_KEY_ERROR ||
     7180    else if (ret == EXT_NOT_ALLOWED || ret == PEER_KEY_ERROR ||
    61467181            ret == ECC_PEERKEY_ERROR || ret == BAD_KEY_SHARE_DATA ||
    61477182            ret == PSK_KEY_ERROR || ret == INVALID_PARAMETER) {
     
    61507185
    61517186    if (ssl->options.tls1_3) {
    6152         if (type == server_hello && ssl->options.side == WOLFSSL_CLIENT_END) {
     7187        /* Need to hash input message before deriving secrets. */
     7188    #ifndef NO_WOLFSSL_CLIENT
     7189        if (ssl->options.side == WOLFSSL_CLIENT_END) {
     7190            if (type == server_hello) {
    61537191            if ((ret = DeriveEarlySecret(ssl)) != 0)
    61547192                return ret;
     
    61687206#endif
    61697207        }
    6170 #ifdef WOLFSSL_EARLY_DATA
    6171         if (type == encrypted_extensions &&
    6172                                       ssl->options.side == WOLFSSL_CLIENT_END) {
    6173             if (!ssl->earlyData)
    6174             {
    6175                 if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
    6176                     return ret;
    6177             }
    6178         }
    6179 #endif
    6180 
    6181         if (type == finished && ssl->options.side == WOLFSSL_CLIENT_END) {
     7208
     7209            if (type == finished) {
    61827210            if ((ret = DeriveMasterSecret(ssl)) != 0)
    61837211                return ret;
    61847212#ifdef WOLFSSL_EARLY_DATA
    61857213            if ((ret = DeriveTls13Keys(ssl, traffic_key,
    6186                              ENCRYPT_AND_DECRYPT_SIDE, !ssl->earlyData)) != 0) {
     7214                                       ENCRYPT_AND_DECRYPT_SIDE,
     7215                                       ssl->earlyData == no_early_data)) != 0) {
    61877216                return ret;
    61887217            }
     
    61947223#endif
    61957224        }
    6196 
     7225        #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
     7226            if (type == certificate_request &&
     7227                                ssl->options.handShakeState == HANDSHAKE_DONE) {
     7228                /* reset handshake states */
     7229                ssl->options.clientState = CLIENT_HELLO_COMPLETE;
     7230                ssl->options.connectState  = FIRST_REPLY_DONE;
     7231                ssl->options.handShakeState = CLIENT_HELLO_COMPLETE;
     7232
     7233                if (wolfSSL_connect_TLSv13(ssl) != SSL_SUCCESS)
     7234                    ret = POST_HAND_AUTH_ERROR;
     7235            }
     7236        #endif
     7237        }
     7238    #endif /* NO_WOLFSSL_CLIENT */
     7239
     7240#ifndef NO_WOLFSSL_SERVER
    61977241#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
    6198         if (type == finished && ssl->options.side == WOLFSSL_SERVER_END) {
     7242        if (ssl->options.side == WOLFSSL_SERVER_END && type == finished) {
    61997243            ret = DeriveResumptionSecret(ssl, ssl->session.masterSecret);
    62007244            if (ret != 0)
     
    62027246        }
    62037247#endif
     7248#endif /* NO_WOLFSSL_SERVER */
    62047249    }
    62057250
     
    62867331        if (inputLength + ssl->arrays->pendingMsgOffset >
    62877332                                                    ssl->arrays->pendingMsgSz) {
    6288             return BUFFER_ERROR;
     7333            inputLength = ssl->arrays->pendingMsgSz -
     7334                                                  ssl->arrays->pendingMsgOffset;
    62897335        }
    6290 
    62917336        XMEMCPY(ssl->arrays->pendingMsg + ssl->arrays->pendingMsgOffset,
    62927337                input + *inOutIdx, inputLength);
     
    63227367}
    63237368
     7369#ifndef NO_WOLFSSL_CLIENT
    63247370
    63257371/* The client connecting to the server.
     
    63367382int wolfSSL_connect_TLSv13(WOLFSSL* ssl)
    63377383{
    6338     int neededState;
    6339 
    63407384    WOLFSSL_ENTER("wolfSSL_connect_TLSv13()");
    63417385
     
    63827426            WOLFSSL_MSG("connect state: CLIENT_HELLO_SENT");
    63837427    #ifdef WOLFSSL_EARLY_DATA
    6384             if (ssl->earlyData) {
     7428            if (ssl->earlyData != no_early_data) {
     7429        #if !defined(WOLFSSL_TLS13_DRAFT_18) && \
     7430                                         defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
     7431                if ((ssl->error = SendChangeCipher(ssl)) != 0) {
     7432                    WOLFSSL_ERROR(ssl->error);
     7433                    return WOLFSSL_FATAL_ERROR;
     7434                }
     7435                ssl->options.sentChangeCipher = 1;
     7436        #endif
    63857437                ssl->options.handShakeState = CLIENT_HELLO_COMPLETE;
    63867438                return WOLFSSL_SUCCESS;
     
    63907442
    63917443        case CLIENT_HELLO_SENT:
    6392             neededState = ssl->options.resuming ? SERVER_FINISHED_COMPLETE :
    6393                                                   SERVER_HELLODONE_COMPLETE;
    63947444            /* Get the response/s from the server. */
    6395             while (ssl->options.serverState < neededState) {
     7445            while (ssl->options.serverState <
     7446                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
    63967447                if ((ssl->error = ProcessReply(ssl)) < 0) {
    63977448                    WOLFSSL_ERROR(ssl->error);
    63987449                    return WOLFSSL_FATAL_ERROR;
    63997450                }
    6400                 /* if resumption failed, reset needed state. */
    6401                 if (neededState == SERVER_FINISHED_COMPLETE &&
    6402                         !ssl->options.resuming) {
    6403                     neededState = SERVER_HELLODONE_COMPLETE;
    6404                 }
    64057451            }
    64067452
     
    64147460
    64157461            if (!ssl->options.tls1_3) {
     7462    #ifndef WOLFSSL_NO_TLS12
    64167463                if (ssl->options.downgrade)
    64177464                    return wolfSSL_connect(ssl);
     7465    #endif
    64187466
    64197467                WOLFSSL_MSG("Client using higher version, fatal error");
     
    64217469            }
    64227470
    6423             if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST) {
    6424                 ssl->options.serverState = NULL_STATE;
     7471            if (ssl->options.serverState ==
     7472                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
     7473        #if !defined(WOLFSSL_TLS13_DRAFT_18) && \
     7474                                         defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
     7475                if (!ssl->options.sentChangeCipher) {
     7476                    if ((ssl->error = SendChangeCipher(ssl)) != 0) {
     7477                        WOLFSSL_ERROR(ssl->error);
     7478                        return WOLFSSL_FATAL_ERROR;
     7479                    }
     7480                    ssl->options.sentChangeCipher = 1;
     7481                }
     7482        #endif
    64257483                /* Try again with different security parameters. */
    64267484                if ((ssl->error = SendTls13ClientHello(ssl)) != 0) {
     
    64357493
    64367494        case HELLO_AGAIN_REPLY:
    6437             if (ssl->options.serverState == NULL_STATE ||
    6438                                                 ssl->error == WC_PENDING_E) {
    6439                 neededState = ssl->options.resuming ? SERVER_FINISHED_COMPLETE :
    6440                                                       SERVER_HELLODONE_COMPLETE;
    6441 
    64427495                /* Get the response/s from the server. */
    6443                 while (ssl->options.serverState < neededState) {
     7496            while (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
    64447497                    if ((ssl->error = ProcessReply(ssl)) < 0) {
    64457498                            WOLFSSL_ERROR(ssl->error);
    64467499                            return WOLFSSL_FATAL_ERROR;
    64477500                    }
    6448                     /* if resumption failed, reset needed state */
    6449                     else if (neededState == SERVER_FINISHED_COMPLETE) {
    6450                         if (!ssl->options.resuming)
    6451                             neededState = SERVER_HELLODONE_COMPLETE;
    6452                     }
    6453                 }
    64547501            }
    64557502
     
    64607507        case FIRST_REPLY_DONE:
    64617508        #ifdef WOLFSSL_EARLY_DATA
    6462             if (ssl->earlyData) {
     7509            if (ssl->earlyData != no_early_data) {
    64637510                if ((ssl->error = SendTls13EndOfEarlyData(ssl)) != 0) {
    64647511                    WOLFSSL_ERROR(ssl->error);
     
    64747521
    64757522        case FIRST_REPLY_FIRST:
     7523        #if !defined(WOLFSSL_TLS13_DRAFT_18) && \
     7524                                         defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
     7525            if (!ssl->options.sentChangeCipher) {
     7526                if ((ssl->error = SendChangeCipher(ssl)) != 0) {
     7527                    WOLFSSL_ERROR(ssl->error);
     7528                    return WOLFSSL_FATAL_ERROR;
     7529                }
     7530                ssl->options.sentChangeCipher = 1;
     7531            }
     7532        #endif
     7533
     7534            ssl->options.connectState = FIRST_REPLY_SECOND;
     7535            WOLFSSL_MSG("connect state: FIRST_REPLY_SECOND");
     7536            FALL_THROUGH;
     7537
     7538        case FIRST_REPLY_SECOND:
    64767539        #ifndef NO_CERTS
    64777540            if (!ssl->options.resuming && ssl->options.sendVerify) {
     
    64857548        #endif
    64867549
    6487             ssl->options.connectState = FIRST_REPLY_SECOND;
    6488             WOLFSSL_MSG("connect state: FIRST_REPLY_SECOND");
     7550            ssl->options.connectState = FIRST_REPLY_THIRD;
     7551            WOLFSSL_MSG("connect state: FIRST_REPLY_THIRD");
    64897552            FALL_THROUGH;
    64907553
    6491         case FIRST_REPLY_SECOND:
    6492 
     7554        case FIRST_REPLY_THIRD:
    64937555        #ifndef NO_CERTS
    64947556            if (!ssl->options.resuming && ssl->options.sendVerify) {
     
    65027564        #endif
    65037565
    6504             ssl->options.connectState = FIRST_REPLY_THIRD;
    6505             WOLFSSL_MSG("connect state: FIRST_REPLY_THIRD");
     7566            ssl->options.connectState = FIRST_REPLY_FOURTH;
     7567            WOLFSSL_MSG("connect state: FIRST_REPLY_FOURTH");
    65067568            FALL_THROUGH;
    65077569
    6508         case FIRST_REPLY_THIRD:
     7570        case FIRST_REPLY_FOURTH:
    65097571            if ((ssl->error = SendTls13Finished(ssl)) != 0) {
    65107572                WOLFSSL_ERROR(ssl->error);
     
    65297591        #endif /* NO_HANDSHAKE_DONE_CB */
    65307592
     7593            if (!ssl->options.keepResources) {
     7594                FreeHandshakeResources(ssl);
     7595            }
     7596
    65317597            WOLFSSL_LEAVE("wolfSSL_connect_TLSv13()", WOLFSSL_SUCCESS);
    65327598            return WOLFSSL_SUCCESS;
     
    65377603    }
    65387604}
    6539 
    6540 #if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
     7605#endif
     7606
     7607#if defined(WOLFSSL_SEND_HRR_COOKIE)
    65417608/* Send a cookie with the HelloRetryRequest to avoid storing state.
    65427609 *
     
    65567623    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
    65577624        return BAD_FUNC_ARG;
     7625 #ifndef NO_WOLFSSL_SERVER
    65587626    if (ssl->options.side == WOLFSSL_CLIENT_END)
    65597627        return SIDE_ERROR;
     
    66027670    ssl->options.sendCookie = 1;
    66037671
    6604     return WOLFSSL_SUCCESS;
     7672    ret = WOLFSSL_SUCCESS;
     7673#else
     7674    (void)secret;
     7675    (void)secretSz;
     7676
     7677    ret = SIDE_ERROR;
     7678#endif
     7679
     7680    return ret;
    66057681}
    66067682#endif
     
    66197695    if (ssl == NULL)
    66207696        return BAD_FUNC_ARG;
    6621     if (ssl->options.side == WOLFSSL_SERVER_END)
    6622         return SIDE_ERROR;
    66237697
    66247698    ret = TLSX_KeyShare_Use(ssl, group, 0, NULL, NULL);
     
    67487822 *
    67497823 * ctx  The SSL/TLS CTX object.
    6750  * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a server and
     7824 * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a client and
    67517825 * 0 on success.
    67527826 */
     
    67677841 * ssl  The SSL/TLS object.
    67687842 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
    6769  * SIDE_ERROR when not a server and 0 on success.
     7843 * SIDE_ERROR when not a client and 0 on success.
    67707844 */
    67717845int wolfSSL_allow_post_handshake_auth(WOLFSSL* ssl)
     
    67907864{
    67917865    int         ret;
     7866#ifndef NO_WOLFSSL_SERVER
    67927867    CertReqCtx* certReqCtx;
     7868#endif
    67937869
    67947870    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
    67957871        return BAD_FUNC_ARG;
     7872#ifndef NO_WOLFSSL_SERVER
    67967873    if (ssl->options.side == WOLFSSL_CLIENT_END)
    67977874        return SIDE_ERROR;
     
    68127889    ssl->certReqCtx = certReqCtx;
    68137890
     7891    ssl->msgsReceived.got_certificate = 0;
     7892    ssl->msgsReceived.got_certificate_verify = 0;
     7893    ssl->msgsReceived.got_finished = 0;
     7894
    68147895    ret = SendTls13CertificateRequest(ssl, &certReqCtx->ctx, certReqCtx->len);
    68157896    if (ret == WANT_WRITE)
     
    68177898    else if (ret == 0)
    68187899        ret = WOLFSSL_SUCCESS;
     7900#else
     7901    ret = SIDE_ERROR;
     7902#endif
     7903
    68197904    return ret;
    68207905}
    68217906#endif /* !NO_CERTS && WOLFSSL_POST_HANDSHAKE_AUTH */
     7907
     7908#if !defined(WOLFSSL_NO_SERVER_GROUPS_EXT)
     7909/* Get the preferred key exchange group.
     7910 *
     7911 * ssl  The SSL/TLS object.
     7912 * returns BAD_FUNC_ARG when ssl is NULL or not using TLS v1.3,
     7913 * SIDE_ERROR when not a client, NOT_READY_ERROR when handshake not complete
     7914 * and group number on success.
     7915 */
     7916int wolfSSL_preferred_group(WOLFSSL* ssl)
     7917{
     7918    if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
     7919        return BAD_FUNC_ARG;
     7920#ifndef NO_WOLFSSL_CLIENT
     7921    if (ssl->options.side == WOLFSSL_SERVER_END)
     7922        return SIDE_ERROR;
     7923    if (ssl->options.handShakeState != HANDSHAKE_DONE)
     7924        return NOT_READY_ERROR;
     7925
     7926    /* Return supported groups only. */
     7927    return TLSX_SupportedCurve_Preferred(ssl, 1);
     7928#else
     7929    return SIDE_ERROR;
     7930#endif
     7931}
     7932#endif
     7933
     7934/* Sets the key exchange groups in rank order on a context.
     7935 *
     7936 * ctx     SSL/TLS context object.
     7937 * groups  Array of groups.
     7938 * count   Number of groups in array.
     7939 * returns BAD_FUNC_ARG when ctx or groups is NULL, not using TLS v1.3 or
     7940 * count is greater than WOLFSSL_MAX_GROUP_COUNT and WOLFSSL_SUCCESS on success.
     7941 */
     7942int wolfSSL_CTX_set_groups(WOLFSSL_CTX* ctx, int* groups, int count)
     7943{
     7944    int i;
     7945
     7946    if (ctx == NULL || groups == NULL || count > WOLFSSL_MAX_GROUP_COUNT)
     7947        return BAD_FUNC_ARG;
     7948    if (!IsAtLeastTLSv1_3(ctx->method->version))
     7949        return BAD_FUNC_ARG;
     7950
     7951    for (i = 0; i < count; i++)
     7952        ctx->group[i] = (word16)groups[i];
     7953    ctx->numGroups = (byte)count;
     7954
     7955    return WOLFSSL_SUCCESS;
     7956}
     7957
     7958/* Sets the key exchange groups in rank order.
     7959 *
     7960 * ssl     SSL/TLS object.
     7961 * groups  Array of groups.
     7962 * count   Number of groups in array.
     7963 * returns BAD_FUNC_ARG when ssl or groups is NULL, not using TLS v1.3 or
     7964 * count is greater than WOLFSSL_MAX_GROUP_COUNT and WOLFSSL_SUCCESS on success.
     7965 */
     7966int wolfSSL_set_groups(WOLFSSL* ssl, int* groups, int count)
     7967{
     7968    int i;
     7969
     7970    if (ssl == NULL || groups == NULL || count > WOLFSSL_MAX_GROUP_COUNT)
     7971        return BAD_FUNC_ARG;
     7972    if (!IsAtLeastTLSv1_3(ssl->version))
     7973        return BAD_FUNC_ARG;
     7974
     7975    for (i = 0; i < count; i++)
     7976        ssl->group[i] = (word16)groups[i];
     7977    ssl->numGroups = (byte)count;
     7978
     7979    return WOLFSSL_SUCCESS;
     7980}
     7981
     7982#ifndef NO_PSK
     7983void wolfSSL_CTX_set_psk_client_tls13_callback(WOLFSSL_CTX* ctx,
     7984                                               wc_psk_client_tls13_callback cb)
     7985{
     7986    WOLFSSL_ENTER("SSL_CTX_set_psk_client_tls13_callback");
     7987
     7988    if (ctx == NULL)
     7989        return;
     7990
     7991    ctx->havePSK = 1;
     7992    ctx->client_psk_tls13_cb = cb;
     7993}
     7994
     7995
     7996void wolfSSL_set_psk_client_tls13_callback(WOLFSSL* ssl,
     7997                                           wc_psk_client_tls13_callback cb)
     7998{
     7999    byte haveRSA = 1;
     8000    int  keySz   = 0;
     8001
     8002    WOLFSSL_ENTER("SSL_set_psk_client_tls13_callback");
     8003
     8004    if (ssl == NULL)
     8005        return;
     8006
     8007    ssl->options.havePSK = 1;
     8008    ssl->options.client_psk_tls13_cb = cb;
     8009
     8010    #ifdef NO_RSA
     8011        haveRSA = 0;
     8012    #endif
     8013    #ifndef NO_CERTS
     8014        keySz = ssl->buffers.keySz;
     8015    #endif
     8016    InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
     8017               ssl->options.haveDH, ssl->options.haveNTRU,
     8018               ssl->options.haveECDSAsig, ssl->options.haveECC,
     8019               ssl->options.haveStaticECC, ssl->options.side);
     8020}
     8021
     8022
     8023void wolfSSL_CTX_set_psk_server_tls13_callback(WOLFSSL_CTX* ctx,
     8024                                               wc_psk_server_tls13_callback cb)
     8025{
     8026    WOLFSSL_ENTER("SSL_CTX_set_psk_server_tls13_callback");
     8027    if (ctx == NULL)
     8028        return;
     8029    ctx->havePSK = 1;
     8030    ctx->server_psk_tls13_cb = cb;
     8031}
     8032
     8033
     8034void wolfSSL_set_psk_server_tls13_callback(WOLFSSL* ssl,
     8035                                           wc_psk_server_tls13_callback cb)
     8036{
     8037    byte haveRSA = 1;
     8038    int  keySz   = 0;
     8039
     8040    WOLFSSL_ENTER("SSL_set_psk_server_tls13_callback");
     8041    if (ssl == NULL)
     8042        return;
     8043
     8044    ssl->options.havePSK = 1;
     8045    ssl->options.server_psk_tls13_cb = cb;
     8046
     8047    #ifdef NO_RSA
     8048        haveRSA = 0;
     8049    #endif
     8050    #ifndef NO_CERTS
     8051        keySz = ssl->buffers.keySz;
     8052    #endif
     8053    InitSuites(ssl->suites, ssl->version, keySz, haveRSA, TRUE,
     8054               ssl->options.haveDH, ssl->options.haveNTRU,
     8055               ssl->options.haveECDSAsig, ssl->options.haveECC,
     8056               ssl->options.haveStaticECC, ssl->options.side);
     8057}
     8058#endif
     8059
    68228060
    68238061#ifndef NO_WOLFSSL_SERVER
     
    68368074{
    68378075    word16 havePSK = 0;
    6838     word16 haveAnon = 0;
    68398076    WOLFSSL_ENTER("SSL_accept_TLSv13()");
    68408077
     
    68478084#endif
    68488085    (void)havePSK;
    6849 
    6850 #ifdef HAVE_ANON
    6851     haveAnon = ssl->options.haveAnon;
    6852 #endif
    6853     (void)haveAnon;
    68548086
    68558087    if (ssl->options.side != WOLFSSL_SERVER_END) {
     
    68598091
    68608092#ifndef NO_CERTS
    6861     /* in case used set_accept_state after init */
    6862     if (!havePSK && !haveAnon &&
    6863         (!ssl->buffers.certificate ||
    6864          !ssl->buffers.certificate->buffer ||
    6865          !ssl->buffers.key ||
    6866          !ssl->buffers.key->buffer)) {
    6867         WOLFSSL_MSG("accept error: don't have server cert and key");
    6868         ssl->error = NO_PRIVATE_KEY;
    6869         WOLFSSL_ERROR(ssl->error);
     8093    /* allow no private key if using PK callbacks and CB is set */
     8094    if (!havePSK) {
     8095        if (!ssl->buffers.certificate ||
     8096            !ssl->buffers.certificate->buffer) {
     8097
     8098            WOLFSSL_MSG("accept error: server cert required");
     8099            WOLFSSL_ERROR(ssl->error = NO_PRIVATE_KEY);
    68708100        return WOLFSSL_FATAL_ERROR;
     8101    }
     8102
     8103    #ifdef HAVE_PK_CALLBACKS
     8104        if (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx)) {
     8105            WOLFSSL_MSG("Using PK for server private key");
     8106        }
     8107        else
     8108    #endif
     8109        if (!ssl->buffers.key || !ssl->buffers.key->buffer) {
     8110            WOLFSSL_MSG("accept error: server key required");
     8111            WOLFSSL_ERROR(ssl->error = NO_PRIVATE_KEY);
     8112            return WOLFSSL_FATAL_ERROR;
     8113        }
    68718114    }
    68728115#endif
     
    68958138    switch (ssl->options.acceptState) {
    68968139
    6897         case ACCEPT_BEGIN :
    6898             /* get response */
    6899             while (ssl->options.clientState < CLIENT_HELLO_COMPLETE)
     8140        case TLS13_ACCEPT_BEGIN :
     8141            /* get client_hello */
     8142            while (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
    69008143                if ((ssl->error = ProcessReply(ssl)) < 0) {
    69018144                    WOLFSSL_ERROR(ssl->error);
    69028145                    return WOLFSSL_FATAL_ERROR;
    69038146                }
    6904 
    6905             ssl->options.acceptState = ACCEPT_CLIENT_HELLO_DONE;
     8147            }
     8148
     8149            ssl->options.acceptState = TLS13_ACCEPT_CLIENT_HELLO_DONE;
    69068150            WOLFSSL_MSG("accept state ACCEPT_CLIENT_HELLO_DONE");
    69078151            FALL_THROUGH;
    69088152
    6909         case ACCEPT_CLIENT_HELLO_DONE :
    6910             if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST) {
     8153        case TLS13_ACCEPT_CLIENT_HELLO_DONE :
     8154#ifdef WOLFSSL_TLS13_DRAFT_18
     8155            if (ssl->options.serverState ==
     8156                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
    69118157                if ((ssl->error = SendTls13HelloRetryRequest(ssl)) != 0) {
    69128158                    WOLFSSL_ERROR(ssl->error);
     
    69148160                }
    69158161            }
    6916             ssl->options.acceptState = ACCEPT_HELLO_RETRY_REQUEST_DONE;
    6917             WOLFSSL_MSG("accept state ACCEPT_HELLO_RETRY_REQUEST_DONE");
     8162
     8163            ssl->options.acceptState = TLS13_ACCEPT_FIRST_REPLY_DONE;
     8164            WOLFSSL_MSG("accept state ACCEPT_FIRST_REPLY_DONE");
    69188165            FALL_THROUGH;
    69198166
    6920         case ACCEPT_HELLO_RETRY_REQUEST_DONE :
    6921             if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST) {
    6922                 if ( (ssl->error = ProcessReply(ssl)) < 0) {
     8167        case TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE :
     8168#else
     8169            if (ssl->options.serverState ==
     8170                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
     8171                if ((ssl->error = SendTls13ServerHello(ssl,
     8172                                                   hello_retry_request)) != 0) {
    69238173                    WOLFSSL_ERROR(ssl->error);
    69248174                    return WOLFSSL_FATAL_ERROR;
    69258175                }
    69268176            }
    6927             ssl->options.acceptState = ACCEPT_FIRST_REPLY_DONE;
     8177
     8178            ssl->options.acceptState = TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE;
     8179            WOLFSSL_MSG("accept state ACCEPT_HELLO_RETRY_REQUEST_DONE");
     8180            FALL_THROUGH;
     8181
     8182        case TLS13_ACCEPT_HELLO_RETRY_REQUEST_DONE :
     8183    #ifdef WOLFSSL_TLS13_MIDDLEBOX_COMPAT
     8184            if (ssl->options.serverState ==
     8185                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
     8186                if ((ssl->error = SendChangeCipher(ssl)) != 0) {
     8187                    WOLFSSL_ERROR(ssl->error);
     8188                    return WOLFSSL_FATAL_ERROR;
     8189                }
     8190                ssl->options.sentChangeCipher = 1;
     8191            }
     8192    #endif
     8193            ssl->options.acceptState = TLS13_ACCEPT_FIRST_REPLY_DONE;
    69288194            WOLFSSL_MSG("accept state ACCEPT_FIRST_REPLY_DONE");
    69298195            FALL_THROUGH;
    6930 
    6931         case ACCEPT_FIRST_REPLY_DONE :
    6932             if ((ssl->error = SendTls13ServerHello(ssl)) != 0) {
     8196#endif
     8197
     8198        case TLS13_ACCEPT_FIRST_REPLY_DONE :
     8199            if (ssl->options.serverState ==
     8200                                          SERVER_HELLO_RETRY_REQUEST_COMPLETE) {
     8201                ssl->options.clientState = CLIENT_HELLO_RETRY;
     8202                while (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
     8203                    if ((ssl->error = ProcessReply(ssl)) < 0) {
     8204                        WOLFSSL_ERROR(ssl->error);
     8205                        return WOLFSSL_FATAL_ERROR;
     8206                    }
     8207                }
     8208            }
     8209
     8210            ssl->options.acceptState = TLS13_ACCEPT_SECOND_REPLY_DONE;
     8211            WOLFSSL_MSG("accept state ACCEPT_SECOND_REPLY_DONE");
     8212            FALL_THROUGH;
     8213
     8214        case TLS13_ACCEPT_SECOND_REPLY_DONE :
     8215            if ((ssl->error = SendTls13ServerHello(ssl, server_hello)) != 0) {
    69338216                WOLFSSL_ERROR(ssl->error);
    69348217                return WOLFSSL_FATAL_ERROR;
    69358218            }
    6936             ssl->options.acceptState = SERVER_HELLO_SENT;
     8219            ssl->options.acceptState = TLS13_SERVER_HELLO_SENT;
    69378220            WOLFSSL_MSG("accept state SERVER_HELLO_SENT");
    69388221            FALL_THROUGH;
    69398222
    6940         case SERVER_HELLO_SENT :
     8223        case TLS13_SERVER_HELLO_SENT :
     8224    #if !defined(WOLFSSL_TLS13_DRAFT_18) && \
     8225                                         defined(WOLFSSL_TLS13_MIDDLEBOX_COMPAT)
     8226            if (!ssl->options.sentChangeCipher) {
     8227                if ((ssl->error = SendChangeCipher(ssl)) != 0) {
     8228                    WOLFSSL_ERROR(ssl->error);
     8229                    return WOLFSSL_FATAL_ERROR;
     8230                }
     8231                ssl->options.sentChangeCipher = 1;
     8232            }
     8233    #endif
     8234
     8235            ssl->options.acceptState = TLS13_ACCEPT_THIRD_REPLY_DONE;
     8236            WOLFSSL_MSG("accept state ACCEPT_THIRD_REPLY_DONE");
     8237            FALL_THROUGH;
     8238
     8239        case TLS13_ACCEPT_THIRD_REPLY_DONE :
     8240            if (!ssl->options.noPskDheKe) {
     8241                ssl->error = TLSX_KeyShare_DeriveSecret(ssl);
     8242                if (ssl->error != 0)
     8243                    return WOLFSSL_FATAL_ERROR;
     8244            }
     8245
    69418246            if ((ssl->error = SendTls13EncryptedExtensions(ssl)) != 0) {
    69428247                WOLFSSL_ERROR(ssl->error);
    69438248                return WOLFSSL_FATAL_ERROR;
    69448249            }
    6945             ssl->options.acceptState = SERVER_EXTENSIONS_SENT;
     8250            ssl->options.acceptState = TLS13_SERVER_EXTENSIONS_SENT;
    69468251            WOLFSSL_MSG("accept state SERVER_EXTENSIONS_SENT");
    69478252            FALL_THROUGH;
    69488253
    6949         case SERVER_EXTENSIONS_SENT :
     8254        case TLS13_SERVER_EXTENSIONS_SENT :
    69508255#ifndef NO_CERTS
    69518256            if (!ssl->options.resuming) {
     
    69598264            }
    69608265#endif
    6961             ssl->options.acceptState = CERT_REQ_SENT;
     8266            ssl->options.acceptState = TLS13_CERT_REQ_SENT;
    69628267            WOLFSSL_MSG("accept state CERT_REQ_SENT");
    69638268            FALL_THROUGH;
    69648269
    6965         case CERT_REQ_SENT :
    6966             ssl->options.acceptState = KEY_EXCHANGE_SENT;
     8270        case TLS13_CERT_REQ_SENT :
    69678271#ifndef NO_CERTS
    69688272            if (!ssl->options.resuming && ssl->options.sendVerify) {
     
    69738277            }
    69748278#endif
    6975             ssl->options.acceptState = CERT_SENT;
     8279            ssl->options.acceptState = TLS13_CERT_SENT;
    69768280            WOLFSSL_MSG("accept state CERT_SENT");
    69778281            FALL_THROUGH;
    69788282
    6979         case CERT_SENT :
     8283        case TLS13_CERT_SENT :
    69808284#ifndef NO_CERTS
    69818285            if (!ssl->options.resuming && ssl->options.sendVerify) {
     
    69868290            }
    69878291#endif
    6988             ssl->options.acceptState = CERT_STATUS_SENT;
    6989             WOLFSSL_MSG("accept state CERT_STATUS_SENT");
     8292            ssl->options.acceptState = TLS13_CERT_VERIFY_SENT;
     8293            WOLFSSL_MSG("accept state CERT_VERIFY_SENT");
    69908294            FALL_THROUGH;
    69918295
    6992         case CERT_VERIFY_SENT :
     8296        case TLS13_CERT_VERIFY_SENT :
    69938297            if ((ssl->error = SendTls13Finished(ssl)) != 0) {
    69948298                WOLFSSL_ERROR(ssl->error);
     
    69968300            }
    69978301
    6998             ssl->options.acceptState = ACCEPT_FINISHED_DONE;
    6999             WOLFSSL_MSG("accept state ACCEPT_FINISHED_DONE");
     8302            ssl->options.acceptState = TLS13_ACCEPT_FINISHED_SENT;
     8303            WOLFSSL_MSG("accept state ACCEPT_FINISHED_SENT");
    70008304#ifdef WOLFSSL_EARLY_DATA
    7001             if (ssl->earlyData) {
     8305            if (ssl->earlyData != no_early_data) {
    70028306                ssl->options.handShakeState = SERVER_FINISHED_COMPLETE;
    70038307                return WOLFSSL_SUCCESS;
     
    70068310            FALL_THROUGH;
    70078311
    7008         case ACCEPT_FINISHED_DONE :
     8312        case TLS13_ACCEPT_FINISHED_SENT :
    70098313#ifdef HAVE_SESSION_TICKET
    70108314    #ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
     
    70188322    #endif
    70198323#endif /* HAVE_SESSION_TICKET */
    7020             ssl->options.acceptState = TICKET_SENT;
     8324            ssl->options.acceptState = TLS13_PRE_TICKET_SENT;
    70218325            WOLFSSL_MSG("accept state  TICKET_SENT");
    70228326            FALL_THROUGH;
    70238327
    7024         case TICKET_SENT:
     8328        case TLS13_PRE_TICKET_SENT :
    70258329            while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE)
    70268330                if ( (ssl->error = ProcessReply(ssl)) < 0) {
     
    70298333                }
    70308334
    7031             ssl->options.acceptState = ACCEPT_SECOND_REPLY_DONE;
    7032             WOLFSSL_MSG("accept state ACCEPT_SECOND_REPLY_DONE");
     8335            ssl->options.acceptState = TLS13_ACCEPT_FINISHED_DONE;
     8336            WOLFSSL_MSG("accept state ACCEPT_FINISHED_DONE");
    70338337            FALL_THROUGH;
    70348338
    7035         case ACCEPT_SECOND_REPLY_DONE :
     8339        case TLS13_ACCEPT_FINISHED_DONE :
    70368340#ifdef HAVE_SESSION_TICKET
    70378341    #ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
     
    70488352            }
    70498353#endif /* HAVE_SESSION_TICKET */
    7050             ssl->options.acceptState = ACCEPT_THIRD_REPLY_DONE;
    7051             WOLFSSL_MSG("accept state ACCEPT_THIRD_REPLY_DONE");
     8354            ssl->options.acceptState = TLS13_TICKET_SENT;
     8355            WOLFSSL_MSG("accept state TICKET_SENT");
    70528356            FALL_THROUGH;
    70538357
    7054         case ACCEPT_THIRD_REPLY_DONE:
     8358        case TLS13_TICKET_SENT :
    70558359#ifndef NO_HANDSHAKE_DONE_CB
    70568360            if (ssl->hsDoneCb) {
     
    70648368#endif /* NO_HANDSHAKE_DONE_CB */
    70658369
     8370            if (!ssl->options.keepResources) {
     8371                FreeHandshakeResources(ssl);
     8372            }
     8373
    70668374            WOLFSSL_LEAVE("SSL_accept()", WOLFSSL_SUCCESS);
    70678375            return WOLFSSL_SUCCESS;
     
    71408448        return BAD_FUNC_ARG;
    71418449
     8450#ifndef NO_WOLFSSL_CLIENT
    71428451    if (ssl->options.side == WOLFSSL_SERVER_END)
    71438452        return SIDE_ERROR;
    71448453
    71458454    if (ssl->options.handShakeState == NULL_STATE) {
    7146         ssl->earlyData = 1;
     8455        ssl->earlyData = expecting_early_data;
    71478456        ret = wolfSSL_connect_TLSv13(ssl);
    7148         if (ret <= 0)
     8457        if (ret != WOLFSSL_SUCCESS)
    71498458            return WOLFSSL_FATAL_ERROR;
    71508459    }
     
    71548463            *outSz = ret;
    71558464    }
     8465#else
     8466    return SIDE_ERROR;
     8467#endif
    71568468
    71578469    WOLFSSL_LEAVE("SSL_write_early_data()", ret);
     
    71748486int wolfSSL_read_early_data(WOLFSSL* ssl, void* data, int sz, int* outSz)
    71758487{
    7176     int ret;
     8488    int ret = 0;
    71778489
    71788490    WOLFSSL_ENTER("wolfSSL_read_early_data()");
     
    71848496        return BAD_FUNC_ARG;
    71858497
     8498#ifndef NO_WOLFSSL_SERVER
    71868499    if (ssl->options.side == WOLFSSL_CLIENT_END)
    71878500        return SIDE_ERROR;
    71888501
    71898502    if (ssl->options.handShakeState == NULL_STATE) {
    7190         ssl->earlyData = 1;
     8503        ssl->earlyData = expecting_early_data;
    71918504        ret = wolfSSL_accept_TLSv13(ssl);
    71928505        if (ret <= 0)
     
    72028515    else
    72038516        ret = 0;
     8517#else
     8518    return SIDE_ERROR;
     8519#endif
    72048520
    72058521    WOLFSSL_LEAVE("wolfSSL_read_early_data()", ret);
Note: See TracChangeset for help on using the changeset viewer.