Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Fork of wolfSSL by
tls13.c
00001 /* tls13.c 00002 * 00003 * Copyright (C) 2006-2016 wolfSSL Inc. 00004 * 00005 * This file is part of wolfSSL. 00006 * 00007 * wolfSSL is free software; you can redistribute it and/or modify 00008 * it under the terms of the GNU General Public License as published by 00009 * the Free Software Foundation; either version 2 of the License, or 00010 * (at your option) any later version. 00011 * 00012 * wolfSSL is distributed in the hope that it will be useful, 00013 * but WITHOUT ANY WARRANTY; without even the implied warranty of 00014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00015 * GNU General Public License for more details. 00016 * 00017 * You should have received a copy of the GNU General Public License 00018 * along with this program; if not, write to the Free Software 00019 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA 00020 */ 00021 00022 00023 00024 #ifdef HAVE_CONFIG_H 00025 #include <config.h> 00026 #endif 00027 00028 #include <wolfssl/wolfcrypt/settings.h> 00029 00030 #ifdef WOLFSSL_TLS13 00031 #if defined(HAVE_SESSION_TICKET) 00032 #include <sys/time.h> 00033 #endif 00034 00035 #include <wolfssl/wolfcrypt/settings.h> 00036 00037 #ifndef WOLFCRYPT_ONLY 00038 00039 #ifdef HAVE_ERRNO_H 00040 #include <errno.h> 00041 #endif 00042 00043 #include <wolfssl/internal.h> 00044 #include <wolfssl/error-ssl.h> 00045 #include <wolfssl/wolfcrypt/asn.h> 00046 #include <wolfssl/wolfcrypt/dh.h> 00047 #ifdef NO_INLINE 00048 #include <wolfssl/wolfcrypt/misc.h> 00049 #else 00050 #define WOLFSSL_MISC_INCLUDED 00051 #include <wolfcrypt/src/misc.c> 00052 #endif 00053 00054 #ifdef HAVE_NTRU 00055 #include "libntruencrypt/ntru_crypto.h" 00056 #endif 00057 00058 #if defined(DEBUG_WOLFSSL) || defined(WOLFSSL_DEBUG) || \ 00059 defined(CHACHA_AEAD_TEST) || defined(WOLFSSL_SESSION_EXPORT_DEBUG) 00060 #if defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX) 00061 #if MQX_USE_IO_OLD 00062 #include <fio.h> 00063 #else 00064 #include <nio.h> 00065 #endif 00066 #else 00067 #include <stdio.h> 00068 #endif 00069 #endif 00070 00071 #ifdef __sun 00072 #include <sys/filio.h> 00073 #endif 00074 00075 #ifndef TRUE 00076 #define TRUE 1 00077 #endif 00078 #ifndef FALSE 00079 #define FALSE 0 00080 #endif 00081 00082 /* Set ret to error value and jump to label. 00083 * 00084 * err The error value to set. 00085 * eLabel The label to jump to. 00086 */ 00087 #define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; } 00088 00089 00090 #ifndef WOLFSSL_HAVE_MIN 00091 #define WOLFSSL_HAVE_MIN 00092 /* Return the minimum of the two values. 00093 * 00094 * a First value. 00095 * b Second value. 00096 * returns the minimum of a and b. 00097 */ 00098 static INLINE word32 min(word32 a, word32 b) 00099 { 00100 return a > b ? b : a; 00101 } 00102 #endif /* WOLFSSL_HAVE_MIN */ 00103 00104 /* Convert 16-bit integer to opaque data. 00105 * 00106 * u16 Unsigned 16-bit value. 00107 * c The buffer to write to. 00108 */ 00109 static INLINE void c16toa(word16 u16, byte* c) 00110 { 00111 c[0] = (u16 >> 8) & 0xff; 00112 c[1] = u16 & 0xff; 00113 } 00114 00115 /* Convert 32-bit integer to opaque data. 00116 * 00117 * u32 Unsigned 32-bit value. 00118 * c The buffer to write to. 00119 */ 00120 static INLINE void c32toa(word32 u32, byte* c) 00121 { 00122 c[0] = (u32 >> 24) & 0xff; 00123 c[1] = (u32 >> 16) & 0xff; 00124 c[2] = (u32 >> 8) & 0xff; 00125 c[3] = u32 & 0xff; 00126 } 00127 00128 00129 /* Convert 24-bit opaque data into a 32-bit value. 00130 * 00131 * u24 The opaque data holding a 24-bit integer. 00132 * u32 Unsigned 32-bit value. 00133 */ 00134 static INLINE void c24to32(const word24 u24, word32* u32) 00135 { 00136 *u32 = (u24[0] << 16) | (u24[1] << 8) | u24[2]; 00137 } 00138 00139 00140 /* Convert opaque data into a 16-bit value. 00141 * 00142 * c The opaque data. 00143 * u16 Unsigned 16-bit value. 00144 */ 00145 static INLINE void ato16(const byte* c, word16* u16) 00146 { 00147 *u16 = (word16) ((c[0] << 8) | (c[1])); 00148 } 00149 00150 #ifndef NO_WOLFSSL_CLIENT 00151 #ifdef HAVE_SESSION_TICKET 00152 /* Convert opaque data into a 32-bit value. 00153 * 00154 * c The opaque data. 00155 * u32 Unsigned 32-bit value. 00156 */ 00157 static INLINE void ato32(const byte* c, word32* u32) 00158 { 00159 *u32 = (c[0] << 24) | (c[1] << 16) | (c[2] << 8) | c[3]; 00160 } 00161 #endif 00162 #endif 00163 00164 /* Extract data using HMAC, salt and input. 00165 * RFC 5869 - HMAC-based Extract-and-Expand Key Derivation Function (HKDF) 00166 * 00167 * prk The generated pseudorandom key. 00168 * salt The salt. 00169 * saltLen The length of the salt. 00170 * ikm The input keying material. 00171 * ikmLen The length of the input keying material. 00172 * mac The type of digest to use. 00173 * returns 0 on success, otherwise failure. 00174 */ 00175 static int Tls13_HKDF_Extract(byte* prk, const byte* salt, int saltLen, 00176 byte* ikm, int ikmLen, int mac) 00177 { 00178 int ret; 00179 int hash; 00180 int len; 00181 00182 switch (mac) { 00183 #ifndef NO_SHA256 00184 case sha256_mac: 00185 hash = SHA256; 00186 len = SHA256_DIGEST_SIZE; 00187 break; 00188 #endif 00189 00190 #ifdef WOLFSSL_SHA384 00191 case sha384_mac: 00192 hash = SHA384; 00193 len = SHA384_DIGEST_SIZE; 00194 break; 00195 #endif 00196 00197 #ifdef WOLFSSL_SHA512 00198 case sha512_mac: 00199 hash = SHA512; 00200 len = SHA512_DIGEST_SIZE; 00201 break; 00202 #endif 00203 00204 default: 00205 return BAD_FUNC_ARG; 00206 } 00207 00208 /* When length is 0 then use zeroed data of digest length. */ 00209 if (ikmLen == 0) { 00210 ikmLen = len; 00211 XMEMSET(ikm, 0, len); 00212 } 00213 00214 #ifdef WOLFSSL_DEBUG_TLS 00215 WOLFSSL_MSG("Salt"); 00216 WOLFSSL_BUFFER(salt, saltLen); 00217 WOLFSSL_MSG("IKM"); 00218 WOLFSSL_BUFFER(ikm, ikmLen); 00219 #endif 00220 00221 ret = wc_HKDF_Extract(hash, salt, saltLen, ikm, ikmLen, prk); 00222 00223 #ifdef WOLFSSL_DEBUG_TLS 00224 WOLFSSL_MSG("PRK"); 00225 WOLFSSL_BUFFER(prk, len); 00226 #endif 00227 00228 return ret; 00229 } 00230 00231 /* Expand data using HMAC, salt and label and info. 00232 * TLS v1.3 defines this function. 00233 * 00234 * okm The generated pseudorandom key - output key material. 00235 * prk The salt - pseudo-random key. 00236 * prkLen The length of the salt - pseudo-random key. 00237 * protocol The TLS protocol label. 00238 * protocolLen The length of the TLS protocol label. 00239 * info The information to expand. 00240 * infoLen The length of the information. 00241 * digest The type of digest to use. 00242 * returns 0 on success, otherwise failure. 00243 */ 00244 static int HKDF_Expand_Label(byte* okm, word32 okmLen, 00245 const byte* prk, word32 prkLen, 00246 const byte* protocol, word32 protocolLen, 00247 const byte* label, word32 labelLen, 00248 const byte* info, word32 infoLen, 00249 int digest) 00250 { 00251 int ret = 0; 00252 int idx = 0; 00253 byte data[MAX_HKDF_LABEL_SZ]; 00254 00255 /* Output length. */ 00256 data[idx++] = okmLen >> 8; 00257 data[idx++] = okmLen; 00258 /* Length of protocol | label. */ 00259 data[idx++] = protocolLen + labelLen; 00260 /* Protocol */ 00261 XMEMCPY(&data[idx], protocol, protocolLen); 00262 idx += protocolLen; 00263 /* Label */ 00264 XMEMCPY(&data[idx], label, labelLen); 00265 idx += labelLen; 00266 /* Length of hash of messages */ 00267 data[idx++] = infoLen; 00268 /* Hash of messages */ 00269 XMEMCPY(&data[idx], info, infoLen); 00270 idx += infoLen; 00271 00272 #ifdef WOLFSSL_DEBUG_TLS 00273 WOLFSSL_MSG("PRK"); 00274 WOLFSSL_BUFFER(prk, prkLen); 00275 WOLFSSL_MSG("Info"); 00276 WOLFSSL_BUFFER(data, idx); 00277 #endif 00278 00279 ret = wc_HKDF_Expand(digest, prk, prkLen, data, idx, okm, okmLen); 00280 00281 #ifdef WOLFSSL_DEBUG_TLS 00282 WOLFSSL_MSG("OKM"); 00283 WOLFSSL_BUFFER(okm, okmLen); 00284 #endif 00285 00286 ForceZero(data, idx); 00287 00288 return ret; 00289 } 00290 00291 /* Size of the TLS v1.3 label use when deriving keys. */ 00292 #define TLS13_PROTOCOL_LABEL_SZ 9 00293 /* The protocol label for TLS v1.3. */ 00294 static const byte tls13ProtocolLabel[TLS13_PROTOCOL_LABEL_SZ + 1] = "TLS 1.3, "; 00295 00296 /* Derive a key from a message. 00297 * 00298 * ssl The SSL/TLS object. 00299 * output The buffer to hold the derived key. 00300 * outputLen The length of the derived key. 00301 * secret The secret used to derive the key (HMAC secret). 00302 * label The label used to distinguish the context. 00303 * labelLen The length of the label. 00304 * msg The message data to derive key from. 00305 * msgLen The length of the message data to derive key from. 00306 * hashAlgo The hash algorithm to use in the HMAC. 00307 * returns 0 on success, otherwise failure. 00308 */ 00309 static int DeriveKeyMsg(WOLFSSL* ssl, byte* output, int outputLen, 00310 const byte* secret, const byte* label, word32 labelLen, 00311 byte* msg, int msgLen, int hashAlgo) 00312 { 00313 byte hash[MAX_DIGEST_SIZE]; 00314 Digest digest; 00315 word32 hashSz = 0; 00316 const byte* protocol; 00317 word32 protocolLen; 00318 int digestAlg; 00319 00320 switch (hashAlgo) { 00321 #ifndef NO_WOLFSSL_SHA256 00322 case sha256_mac: 00323 wc_InitSha256(&digest.sha256); 00324 wc_Sha256Update(&digest.sha256, msg, msgLen); 00325 wc_Sha256Final(&digest.sha256, hash); 00326 wc_Sha256Free(&digest.sha256); 00327 hashSz = SHA256_DIGEST_SIZE; 00328 digestAlg = SHA256; 00329 break; 00330 #endif 00331 #ifdef WOLFSSL_SHA384 00332 case sha384_mac: 00333 wc_InitSha384(&digest.sha384); 00334 wc_Sha384Update(&digest.sha384, msg, msgLen); 00335 wc_Sha384Final(&digest.sha384, hash); 00336 wc_Sha384Free(&digest.sha384); 00337 hashSz = SHA384_DIGEST_SIZE; 00338 digestAlg = SHA384; 00339 break; 00340 #endif 00341 #ifdef WOLFSSL_SHA512 00342 case sha512_mac: 00343 wc_InitSha512(&digest.sha512); 00344 wc_Sha512Update(&digest.sha512, msg, msgLen); 00345 wc_Sha512Final(&digest.sha512, hash); 00346 wc_Sha512Free(&digest.sha512); 00347 hashSz = SHA512_DIGEST_SIZE; 00348 digestAlg = SHA512; 00349 break; 00350 #endif 00351 00352 default: 00353 return BAD_FUNC_ARG; 00354 } 00355 00356 switch (ssl->version.minor) { 00357 case TLSv1_3_MINOR: 00358 protocol = tls13ProtocolLabel; 00359 protocolLen = TLS13_PROTOCOL_LABEL_SZ; 00360 break; 00361 00362 default: 00363 return VERSION_ERROR; 00364 } 00365 if (outputLen == -1) 00366 outputLen = hashSz; 00367 00368 return HKDF_Expand_Label(output, outputLen, secret, hashSz, 00369 protocol, protocolLen, label, labelLen, 00370 hash, hashSz, digestAlg); 00371 } 00372 00373 /* Derive a key. 00374 * 00375 * ssl The SSL/TLS object. 00376 * output The buffer to hold the derived key. 00377 * outputLen The length of the derived key. 00378 * secret The secret used to derive the key (HMAC secret). 00379 * label The label used to distinguish the context. 00380 * labelLen The length of the label. 00381 * hashAlgo The hash algorithm to use in the HMAC. 00382 * includeMsgs Whether to include a hash of the handshake messages so far. 00383 * returns 0 on success, otherwise failure. 00384 */ 00385 static int DeriveKey(WOLFSSL* ssl, byte* output, int outputLen, 00386 const byte* secret, const byte* label, word32 labelLen, 00387 int hashAlgo, int includeMsgs) 00388 { 00389 int ret = 0; 00390 byte hash[MAX_DIGEST_SIZE]; 00391 word32 hashSz = 0; 00392 word32 hashOutSz = 0; 00393 const byte* protocol; 00394 word32 protocolLen; 00395 int digestAlg; 00396 00397 switch (hashAlgo) { 00398 #ifndef NO_SHA256 00399 case sha256_mac: 00400 hashSz = SHA256_DIGEST_SIZE; 00401 digestAlg = SHA256; 00402 if (includeMsgs) 00403 ret = wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash); 00404 break; 00405 #endif 00406 00407 #ifdef WOLFSSL_SHA384 00408 case sha384_mac: 00409 hashSz = SHA384_DIGEST_SIZE; 00410 digestAlg = SHA384; 00411 if (includeMsgs) 00412 ret = wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash); 00413 break; 00414 #endif 00415 00416 #ifdef WOLFSSL_SHA512 00417 case sha512_mac: 00418 hashSz = SHA512_DIGEST_SIZE; 00419 digestAlg = SHA512; 00420 if (includeMsgs) 00421 ret = wc_Sha512GetHash(&ssl->hsHashes->hashSha512, hash); 00422 break; 00423 #endif 00424 00425 default: 00426 ret = BAD_FUNC_ARG; 00427 break; 00428 } 00429 if (ret != 0) 00430 return ret; 00431 00432 /* Only one protocol version defined at this time. */ 00433 protocol = tls13ProtocolLabel; 00434 protocolLen = TLS13_PROTOCOL_LABEL_SZ; 00435 00436 if (outputLen == -1) 00437 outputLen = hashSz; 00438 if (includeMsgs) 00439 hashOutSz = hashSz; 00440 00441 return HKDF_Expand_Label(output, outputLen, secret, hashSz, 00442 protocol, protocolLen, label, labelLen, 00443 hash, hashOutSz, digestAlg); 00444 } 00445 00446 00447 #if defined(HAVE_SESSION_TICKET) && !defined(NO_PSK) 00448 /* The length of the binder key label. */ 00449 #define BINDER_KEY_LABEL_SZ 23 00450 /* The binder key label. */ 00451 static const byte binderKeyLabel[BINDER_KEY_LABEL_SZ + 1] = 00452 "external psk binder key"; 00453 /* Derive the binder key. 00454 * 00455 * ssl The SSL/TLS object. 00456 * key The derived key. 00457 * returns 0 on success, otherwise failure. 00458 */ 00459 static int DeriveBinderKey(WOLFSSL* ssl, byte* key) 00460 { 00461 WOLFSSL_MSG("Derive Binder Key"); 00462 return DeriveKeyMsg(ssl, key, -1, ssl->arrays->secret, 00463 binderKeyLabel, BINDER_KEY_LABEL_SZ, 00464 NULL, 0, ssl->specs.mac_algorithm); 00465 } 00466 00467 /* The length of the binder key resume label. */ 00468 #define BINDER_KEY_RESUME_LABEL_SZ 25 00469 /* The binder key resume label. */ 00470 static const byte binderKeyResumeLabel[BINDER_KEY_RESUME_LABEL_SZ + 1] = 00471 "resumption psk binder key"; 00472 /* Derive the binder resumption key. 00473 * 00474 * ssl The SSL/TLS object. 00475 * key The derived key. 00476 * returns 0 on success, otherwise failure. 00477 */ 00478 static int DeriveBinderKeyResume(WOLFSSL* ssl, byte* key) 00479 { 00480 WOLFSSL_MSG("Derive Binder Key - Resumption"); 00481 return DeriveKeyMsg(ssl, key, -1, ssl->arrays->secret, 00482 binderKeyResumeLabel, BINDER_KEY_RESUME_LABEL_SZ, 00483 NULL, 0, ssl->specs.mac_algorithm); 00484 } 00485 #endif 00486 00487 #ifdef TLS13_SUPPORTS_0RTT 00488 /* The length of the early traffic label. */ 00489 #define EARLY_TRAFFIC_LABEL_SZ 27 00490 /* The early traffic label. */ 00491 static const byte earlyTrafficLabel[EARLY_TRAFFIC_LABEL_SZ + 1] = 00492 "client early traffic secret"; 00493 /* Derive the early traffic key. 00494 * 00495 * ssl The SSL/TLS object. 00496 * key The derived key. 00497 * returns 0 on success, otherwise failure. 00498 */ 00499 static int DeriveEarlyTrafficSecret(WOLFSSL* ssl, byte* key) 00500 { 00501 WOLFSSL_MSG("Derive Early Traffic Secret"); 00502 return DeriveKey(ssl, key, -1, ssl->arrays->secret, 00503 earlyTrafficLabel, EARLY_TRAFFIC_LABEL_SZ, 00504 ssl->specs.mac_algorithm, 1); 00505 } 00506 00507 #ifdef TLS13_SUPPORTS_EXPORTERS 00508 /* The length of the early exporter label. */ 00509 #define EARLY_EXPORTER_LABEL_SZ 28 00510 /* The early exporter label. */ 00511 static const byte earlyExporterLabel[EARLY_EXPORTER_LABEL_SZ + 1] = 00512 "early exporter master secret"; 00513 /* Derive the early exporter key. 00514 * 00515 * ssl The SSL/TLS object. 00516 * key The derived key. 00517 * returns 0 on success, otherwise failure. 00518 */ 00519 static int DeriveEarlyExporterSecret(WOLFSSL* ssl, byte* key) 00520 { 00521 WOLFSSL_MSG("Derive Early Exporter Secret"); 00522 return DeriveKey(ssl, key, -1, ssl->arrays->secret, 00523 earlyExporterLabel, EARLY_EXPORTER_LABEL_SZ, 00524 ssl->specs.mac_algorithm, 1); 00525 } 00526 #endif 00527 #endif 00528 00529 /* The length of the client hanshake label. */ 00530 #define CLIENT_HANDSHAKE_LABEL_SZ 31 00531 /* The client hanshake label. */ 00532 static const byte clientHandshakeLabel[CLIENT_HANDSHAKE_LABEL_SZ + 1] = 00533 "client handshake traffic secret"; 00534 /* Derive the client handshake key. 00535 * 00536 * ssl The SSL/TLS object. 00537 * key The derived key. 00538 * returns 0 on success, otherwise failure. 00539 */ 00540 static int DeriveClientHandshakeSecret(WOLFSSL* ssl, byte* key) 00541 { 00542 WOLFSSL_MSG("Derive Client Handshake Secret"); 00543 return DeriveKey(ssl, key, -1, ssl->arrays->preMasterSecret, 00544 clientHandshakeLabel, CLIENT_HANDSHAKE_LABEL_SZ, 00545 ssl->specs.mac_algorithm, 1); 00546 } 00547 00548 /* The length of the server handshake label. */ 00549 #define SERVER_HANDSHAKE_LABEL_SZ 31 00550 /* The server handshake label. */ 00551 static const byte serverHandshakeLabel[SERVER_HANDSHAKE_LABEL_SZ + 1] = 00552 "server handshake traffic secret"; 00553 /* Derive the server handshake key. 00554 * 00555 * ssl The SSL/TLS object. 00556 * key The derived key. 00557 * returns 0 on success, otherwise failure. 00558 */ 00559 static int DeriveServerHandshakeSecret(WOLFSSL* ssl, byte* key) 00560 { 00561 WOLFSSL_MSG("Derive Server Handshake Secret"); 00562 return DeriveKey(ssl, key, -1, ssl->arrays->preMasterSecret, 00563 serverHandshakeLabel, SERVER_HANDSHAKE_LABEL_SZ, 00564 ssl->specs.mac_algorithm, 1); 00565 } 00566 00567 /* The length of the client application traffic label. */ 00568 #define CLIENT_APP_LABEL_SZ 33 00569 /* The client application traffic label. */ 00570 static const byte clientAppLabel[CLIENT_APP_LABEL_SZ + 1] = 00571 "client application traffic secret"; 00572 /* Derive the client application traffic key. 00573 * 00574 * ssl The SSL/TLS object. 00575 * key The derived key. 00576 * returns 0 on success, otherwise failure. 00577 */ 00578 static int DeriveClientTrafficSecret(WOLFSSL* ssl, byte* key) 00579 { 00580 WOLFSSL_MSG("Derive Client Traffic Secret"); 00581 return DeriveKey(ssl, key, -1, ssl->arrays->masterSecret, 00582 clientAppLabel, CLIENT_APP_LABEL_SZ, 00583 ssl->specs.mac_algorithm, 1); 00584 } 00585 00586 /* The length of the server application traffic label. */ 00587 #define SERVER_APP_LABEL_SZ 33 00588 /* The server application traffic label. */ 00589 static const byte serverAppLabel[SERVER_APP_LABEL_SZ + 1] = 00590 "server application traffic secret"; 00591 /* Derive the server application traffic key. 00592 * 00593 * ssl The SSL/TLS object. 00594 * key The derived key. 00595 * returns 0 on success, otherwise failure. 00596 */ 00597 static int DeriveServerTrafficSecret(WOLFSSL* ssl, byte* key) 00598 { 00599 WOLFSSL_MSG("Derive Server Traffic Secret"); 00600 return DeriveKey(ssl, key, -1, ssl->arrays->masterSecret, 00601 serverAppLabel, SERVER_APP_LABEL_SZ, 00602 ssl->specs.mac_algorithm, 1); 00603 } 00604 00605 #ifdef TLS13_SUPPORTS_EXPORTERS 00606 /* The length of the exporter master secret label. */ 00607 #define EXPORTER_MASTER_LABEL_SZ 22 00608 /* The exporter master secret label. */ 00609 static const byte exporterMasterLabel[EXPORTER_MASTER_LABEL_SZ + 1] = 00610 "exporter master secret"; 00611 /* Derive the exporter secret. 00612 * 00613 * ssl The SSL/TLS object. 00614 * key The derived key. 00615 * returns 0 on success, otherwise failure. 00616 */ 00617 static int DeriveExporterSecret(WOLFSSL* ssl, byte* key) 00618 { 00619 WOLFSSL_MSG("Derive Exporter Secret"); 00620 return DeriveKey(ssl, key, -1, ssl->arrays->masterSecret, 00621 exporterMasterLabel, EXPORTER_MASTER_LABEL_SZ, 00622 ssl->specs.mac_algorithm, 1); 00623 } 00624 #endif 00625 00626 #ifndef NO_PSK 00627 /* The length of the resumption master secret label. */ 00628 #define RESUME_MASTER_LABEL_SZ 24 00629 /* The resumption master secret label. */ 00630 static const byte resumeMasterLabel[RESUME_MASTER_LABEL_SZ + 1] = 00631 "resumption master secret"; 00632 /* Derive the resumption secret. 00633 * 00634 * ssl The SSL/TLS object. 00635 * key The derived key. 00636 * returns 0 on success, otherwise failure. 00637 */ 00638 static int DeriveResumptionSecret(WOLFSSL* ssl, byte* key) 00639 { 00640 WOLFSSL_MSG("Derive Resumption Secret"); 00641 return DeriveKey(ssl, key, -1, ssl->arrays->masterSecret, 00642 resumeMasterLabel, RESUME_MASTER_LABEL_SZ, 00643 ssl->specs.mac_algorithm, 1); 00644 } 00645 #endif 00646 00647 /* Length of the finished label. */ 00648 #define FINISHED_LABEL_SZ 8 00649 /* Finished label for generating finished key. */ 00650 static const byte finishedLabel[FINISHED_LABEL_SZ+1] = "finished"; 00651 /* Derive the finished secret. 00652 * 00653 * ssl The SSL/TLS object. 00654 * key The key to use with the HMAC. 00655 * secret The derived secret. 00656 * returns 0 on success, otherwise failure. 00657 */ 00658 static int DeriveFinishedSecret(WOLFSSL* ssl, byte* key, byte* secret) 00659 { 00660 WOLFSSL_MSG("Derive Finished Secret"); 00661 return DeriveKey(ssl, secret, -1, key, finishedLabel, FINISHED_LABEL_SZ, 00662 ssl->specs.mac_algorithm, 0); 00663 } 00664 00665 /* The length of the application traffic label. */ 00666 #define APP_TRAFFIC_LABEL_SZ 26 00667 /* The application traffic label. */ 00668 static const byte appTrafficLabel[APP_TRAFFIC_LABEL_SZ + 1] = 00669 "application traffic secret"; 00670 /* Update the traffic secret. 00671 * 00672 * ssl The SSL/TLS object. 00673 * secret The previous secret and derived secret. 00674 * returns 0 on success, otherwise failure. 00675 */ 00676 static int DeriveTrafficSecret(WOLFSSL* ssl, byte* secret) 00677 { 00678 WOLFSSL_MSG("Derive New Application Traffic Secret"); 00679 return DeriveKeyMsg(ssl, secret, -1, secret, 00680 appTrafficLabel, APP_TRAFFIC_LABEL_SZ, 00681 NULL, 0, ssl->specs.mac_algorithm); 00682 } 00683 00684 /* Derive the early secret using HKDF Extract. 00685 * 00686 * ssl The SSL/TLS object. 00687 */ 00688 static int DeriveEarlySecret(WOLFSSL* ssl) 00689 { 00690 WOLFSSL_MSG("Derive Early Secret"); 00691 #ifndef NO_PSK 00692 return Tls13_HKDF_Extract(ssl->arrays->secret, NULL, 0, 00693 ssl->arrays->psk_key, ssl->arrays->psk_keySz, 00694 ssl->specs.mac_algorithm); 00695 #else 00696 return Tls13_HKDF_Extract(ssl->arrays->secret, NULL, 0, 00697 ssl->arrays->masterSecret, 0, ssl->specs.mac_algorithm); 00698 #endif 00699 } 00700 00701 /* Derive the handshake secret using HKDF Extract. 00702 * 00703 * ssl The SSL/TLS object. 00704 */ 00705 static int DeriveHandshakeSecret(WOLFSSL* ssl) 00706 { 00707 WOLFSSL_MSG("Derive Handshake Secret"); 00708 return Tls13_HKDF_Extract(ssl->arrays->preMasterSecret, 00709 ssl->arrays->secret, ssl->specs.hash_size, 00710 ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz, 00711 ssl->specs.mac_algorithm); 00712 } 00713 00714 /* Derive the master secret using HKDF Extract. 00715 * 00716 * ssl The SSL/TLS object. 00717 */ 00718 static int DeriveMasterSecret(WOLFSSL* ssl) 00719 { 00720 WOLFSSL_MSG("Derive Master Secret"); 00721 return Tls13_HKDF_Extract(ssl->arrays->masterSecret, 00722 ssl->arrays->preMasterSecret, ssl->specs.hash_size, 00723 ssl->arrays->masterSecret, 0, ssl->specs.mac_algorithm); 00724 } 00725 00726 /* Calculate the HMAC of message data to this point. 00727 * 00728 * ssl The SSL/TLS object. 00729 * key The HMAC key. 00730 * hash The hash result - verify data. 00731 * returns length of verify data generated. 00732 */ 00733 static int BuildTls13HandshakeHmac(WOLFSSL* ssl, byte* key, byte* hash) 00734 { 00735 Hmac verifyHmac; 00736 int hashType = SHA256; 00737 int hashSz = SHA256_DIGEST_SIZE; 00738 00739 /* Get the hash of the previous handshake messages. */ 00740 switch (ssl->specs.mac_algorithm) { 00741 #ifndef NO_SHA256 00742 case sha256_mac: 00743 hashType = SHA256; 00744 hashSz = SHA256_DIGEST_SIZE; 00745 wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash); 00746 break; 00747 #endif /* !NO_SHA256 */ 00748 #ifdef WOLFSSL_SHA384 00749 case sha384_mac: 00750 hashType = SHA384; 00751 hashSz = SHA384_DIGEST_SIZE; 00752 wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash); 00753 break; 00754 #endif /* WOLFSSL_SHA384 */ 00755 #ifdef WOLFSSL_SHA512 00756 case sha512_mac: 00757 hashType = SHA512; 00758 hashSz = SHA512_DIGEST_SIZE; 00759 wc_Sha512GetHash(&ssl->hsHashes->hashSha512, hash); 00760 break; 00761 #endif /* WOLFSSL_SHA512 */ 00762 } 00763 00764 /* Calculate the verify data. */ 00765 wc_HmacSetKey(&verifyHmac, hashType, key, ssl->specs.hash_size); 00766 wc_HmacUpdate(&verifyHmac, hash, hashSz); 00767 wc_HmacFinal(&verifyHmac, hash); 00768 00769 return hashSz; 00770 } 00771 00772 /* The length of the label to use when deriving keys. */ 00773 #define WRITE_KEY_LABEL_SZ 3 00774 /* The length of the label to use when deriving IVs. */ 00775 #define WRITE_IV_LABEL_SZ 2 00776 /* The label to use when deriving keys. */ 00777 static const byte writeKeyLabel[WRITE_KEY_LABEL_SZ+1] = "key"; 00778 /* The label to use when deriving IVs. */ 00779 static const byte writeIVLabel[WRITE_IV_LABEL_SZ+1] = "iv"; 00780 00781 /* Derive the keys and IVs for TLS v1.3. 00782 * 00783 * ssl The SSL/TLS object. 00784 * sercret handshake_key when deriving keys and IVs for encrypting handshake 00785 * messages. 00786 * traffic_key when deriving first keys and IVs for encrypting 00787 * traffic messages. 00788 * update_traffic_key when deriving next keys and IVs for encrypting 00789 * traffic messages. 00790 * side ENCRYPT_SIDE_ONLY when only encryption secret needs to be derived. 00791 * DECRYPT_SIDE_ONLY when only decryption secret needs to be derived. 00792 * ENCRYPT_AND_DECRYPT_SIDE when both secret needs to be derived. 00793 * returns 0 on success, otherwise failure. 00794 */ 00795 static int DeriveTls13Keys(WOLFSSL* ssl, int secret, int side) 00796 { 00797 int ret; 00798 int i = 0; 00799 #ifdef WOLFSSL_SMALL_STACK 00800 byte* key_data; 00801 #else 00802 byte key_data[MAX_PRF_DIG]; 00803 #endif 00804 int deriveClient = 0; 00805 int deriveServer = 0; 00806 00807 #ifdef WOLFSSL_SMALL_STACK 00808 key_data = (byte*)XMALLOC(MAX_PRF_DIG, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); 00809 if (key_data == NULL) 00810 return MEMORY_E; 00811 #endif 00812 00813 if (side == ENCRYPT_AND_DECRYPT_SIDE) { 00814 deriveClient = 1; 00815 deriveServer = 1; 00816 } 00817 else { 00818 deriveClient = (ssl->options.side != WOLFSSL_CLIENT_END) ^ 00819 (side == ENCRYPT_SIDE_ONLY); 00820 deriveServer = !deriveClient; 00821 } 00822 00823 /* Derive the appropriate secret to use in the HKDF. */ 00824 switch (secret) { 00825 case handshake_key: 00826 if (deriveClient) { 00827 ret = DeriveClientHandshakeSecret(ssl, 00828 ssl->arrays->clientSecret); 00829 if (ret != 0) 00830 goto end; 00831 } 00832 if (deriveServer) { 00833 ret = DeriveServerHandshakeSecret(ssl, 00834 ssl->arrays->serverSecret); 00835 if (ret != 0) 00836 goto end; 00837 } 00838 break; 00839 00840 case traffic_key: 00841 if (deriveClient) { 00842 ret = DeriveClientTrafficSecret(ssl, ssl->arrays->clientSecret); 00843 if (ret != 0) 00844 goto end; 00845 } 00846 if (deriveServer) { 00847 ret = DeriveServerTrafficSecret(ssl, ssl->arrays->serverSecret); 00848 if (ret != 0) 00849 goto end; 00850 } 00851 break; 00852 00853 case update_traffic_key: 00854 if (deriveClient) { 00855 ret = DeriveTrafficSecret(ssl, ssl->arrays->clientSecret); 00856 if (ret != 0) 00857 goto end; 00858 } 00859 if (deriveServer) { 00860 ret = DeriveTrafficSecret(ssl, ssl->arrays->serverSecret); 00861 if (ret != 0) 00862 goto end; 00863 } 00864 break; 00865 } 00866 00867 /* Key data = client key | server key | client IV | server IV */ 00868 00869 /* Derive the client key. */ 00870 WOLFSSL_MSG("Derive Client Key"); 00871 ret = DeriveKey(ssl, &key_data[i], ssl->specs.key_size, 00872 ssl->arrays->clientSecret, writeKeyLabel, 00873 WRITE_KEY_LABEL_SZ, ssl->specs.mac_algorithm, 0); 00874 if (ret != 0) 00875 goto end; 00876 i += ssl->specs.key_size; 00877 00878 /* Derive the server key. */ 00879 WOLFSSL_MSG("Derive Server Key"); 00880 ret = DeriveKey(ssl, &key_data[i], ssl->specs.key_size, 00881 ssl->arrays->serverSecret, writeKeyLabel, 00882 WRITE_KEY_LABEL_SZ, ssl->specs.mac_algorithm, 0); 00883 if (ret != 0) 00884 goto end; 00885 i += ssl->specs.key_size; 00886 00887 /* Derive the client IV. */ 00888 WOLFSSL_MSG("Derive Client IV"); 00889 ret = DeriveKey(ssl, &key_data[i], ssl->specs.iv_size, 00890 ssl->arrays->clientSecret, writeIVLabel, WRITE_IV_LABEL_SZ, 00891 ssl->specs.mac_algorithm, 0); 00892 if (ret != 0) 00893 goto end; 00894 i += ssl->specs.iv_size; 00895 00896 /* Derive the server IV. */ 00897 WOLFSSL_MSG("Derive Server IV"); 00898 ret = DeriveKey(ssl, &key_data[i], ssl->specs.iv_size, 00899 ssl->arrays->serverSecret, writeIVLabel, WRITE_IV_LABEL_SZ, 00900 ssl->specs.mac_algorithm, 0); 00901 if (ret != 0) 00902 goto end; 00903 00904 /* Store keys and IVs but don't activate them. */ 00905 ret = StoreKeys(ssl, key_data); 00906 00907 end: 00908 #ifdef WOLFSSL_SMALL_STACK 00909 XFREE(key_data, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); 00910 #endif 00911 00912 return ret; 00913 } 00914 00915 #if defined(HAVE_SESSION_TICKET) 00916 #if defined(USER_TICKS) 00917 #if 0 00918 word32 TimeNowInMilliseconds(void) 00919 { 00920 /* 00921 write your own clock tick function if don't want gettimeofday() 00922 needs millisecond accuracy but doesn't have to correlated to EPOCH 00923 */ 00924 } 00925 #endif 00926 00927 #elif defined(TIME_OVERRIDES) 00928 #ifndef HAVE_TIME_T_TYPE 00929 typedef long time_t; 00930 #endif 00931 extern time_t XTIME(time_t * timer); 00932 00933 /* The time in milliseconds. 00934 * Used for tickets to represent difference between when first seen and when 00935 * sending. 00936 * 00937 * returns the time in milliseconds as a 32-bit value. 00938 */ 00939 word32 TimeNowInMilliseconds(void) 00940 { 00941 return (word32) XTIME(0) * 1000; 00942 } 00943 #elif defined(USE_WINDOWS_API) 00944 /* The time in milliseconds. 00945 * Used for tickets to represent difference between when first seen and when 00946 * sending. 00947 * 00948 * returns the time in milliseconds as a 32-bit value. 00949 */ 00950 word32 TimeNowInMilliseconds(void) 00951 { 00952 static int init = 0; 00953 static LARGE_INTEGER freq; 00954 LARGE_INTEGER count; 00955 00956 if (!init) { 00957 QueryPerformanceFrequency(&freq); 00958 init = 1; 00959 } 00960 00961 QueryPerformanceCounter(&count); 00962 00963 return (word32)(count.QuadPart / (freq.QuadPart / 1000)); 00964 } 00965 00966 #elif defined(HAVE_RTP_SYS) 00967 #include "rtptime.h" 00968 00969 /* The time in milliseconds. 00970 * Used for tickets to represent difference between when first seen and when 00971 * sending. 00972 * 00973 * returns the time in milliseconds as a 32-bit value. 00974 */ 00975 word32 TimeNowInMilliseconds(void) 00976 { 00977 return (word32)rtp_get_system_sec() * 1000; 00978 } 00979 #elif defined(MICRIUM) 00980 /* The time in milliseconds. 00981 * Used for tickets to represent difference between when first seen and when 00982 * sending. 00983 * 00984 * returns the time in milliseconds as a 32-bit value. 00985 */ 00986 word32 TimeNowInMilliseconds(void) 00987 { 00988 NET_SECURE_OS_TICK clk = 0; 00989 00990 #if (NET_SECURE_MGR_CFG_EN == DEF_ENABLED) 00991 clk = NetSecure_OS_TimeGet(); 00992 #endif 00993 return (word32)clk * 1000; 00994 } 00995 #elif defined(MICROCHIP_TCPIP_V5) 00996 /* The time in milliseconds. 00997 * Used for tickets to represent difference between when first seen and when 00998 * sending. 00999 * 01000 * returns the time in milliseconds as a 32-bit value. 01001 */ 01002 word32 TimeNowInMilliseconds(void) 01003 { 01004 return (word32) (TickGet() / (TICKS_PER_SECOND / 1000)); 01005 } 01006 #elif defined(MICROCHIP_TCPIP) 01007 #if defined(MICROCHIP_MPLAB_HARMONY) 01008 #include <system/tmr/sys_tmr.h> 01009 01010 /* The time in milliseconds. 01011 * Used for tickets to represent difference between when first seen and when 01012 * sending. 01013 * 01014 * returns the time in milliseconds as a 32-bit value. 01015 */ 01016 word32 TimeNowInMilliseconds(void) 01017 { 01018 return (word32) (SYS_TMR_TickCountGet() / 01019 (SYS_TMR_TickCounterFrequencyGet() / 1000)); 01020 } 01021 #else 01022 /* The time in milliseconds. 01023 * Used for tickets to represent difference between when first seen and when 01024 * sending. 01025 * 01026 * returns the time in milliseconds as a 32-bit value. 01027 */ 01028 word32 TimeNowInMilliseconds(void) 01029 { 01030 return (word32) (SYS_TICK_Get() / (SYS_TICK_TicksPerSecondGet() / 1000)); 01031 } 01032 01033 #endif 01034 01035 #elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX) 01036 /* The time in milliseconds. 01037 * Used for tickets to represent difference between when first seen and when 01038 * sending. 01039 * 01040 * returns the time in milliseconds as a 32-bit value. 01041 */ 01042 word32 TimeNowInMilliseconds(void) 01043 { 01044 TIME_STRUCT mqxTime; 01045 01046 _time_get_elapsed(&mqxTime); 01047 01048 return (word32) mqxTime.SECONDS * 1000; 01049 } 01050 #elif defined(FREESCALE_FREE_RTOS) || defined(FREESCALE_KSDK_FREERTOS) 01051 #include "include/task.h" 01052 01053 /* The time in milliseconds. 01054 * Used for tickets to represent difference between when first seen and when 01055 * sending. 01056 * 01057 * returns the time in milliseconds as a 32-bit value. 01058 */ 01059 word32 TimeNowInMilliseconds(void) 01060 { 01061 return (unsigned int)(((float)xTaskGetTickCount()) / 01062 (configTICK_RATE_HZ / 1000)); 01063 } 01064 #elif defined(FREESCALE_KSDK_BM) 01065 #include "lwip/sys.h" /* lwIP */ 01066 01067 /* The time in milliseconds. 01068 * Used for tickets to represent difference between when first seen and when 01069 * sending. 01070 * 01071 * returns the time in milliseconds as a 32-bit value. 01072 */ 01073 word32 TimeNowInMilliseconds(void) 01074 { 01075 return sys_now(); 01076 } 01077 #elif defined(WOLFSSL_TIRTOS) 01078 /* The time in milliseconds. 01079 * Used for tickets to represent difference between when first seen and when 01080 * sending. 01081 * 01082 * returns the time in milliseconds as a 32-bit value. 01083 */ 01084 word32 TimeNowInMilliseconds(void) 01085 { 01086 return (word32) Seconds_get() * 1000; 01087 } 01088 #elif defined(WOLFSSL_UTASKER) 01089 /* The time in milliseconds. 01090 * Used for tickets to represent difference between when first seen and when 01091 * sending. 01092 * 01093 * returns the time in milliseconds as a 32-bit value. 01094 */ 01095 word32 TimeNowInMilliseconds(void) 01096 { 01097 return (word32)(uTaskerSystemTick / (TICK_RESOLUTION / 1000)); 01098 } 01099 #else 01100 /* The time in milliseconds. 01101 * Used for tickets to represent difference between when first seen and when 01102 * sending. 01103 * 01104 * returns the time in milliseconds as a 32-bit value. 01105 */ 01106 word32 TimeNowInMilliseconds(void) 01107 { 01108 struct timeval now; 01109 01110 if (gettimeofday(&now, 0) < 0) 01111 return GETTIME_ERROR; 01112 /* Convert to milliseconds number. */ 01113 return (word32)(now.tv_sec * 1000 + now.tv_usec / 1000); 01114 } 01115 #endif 01116 #endif /* HAVE_SESSION_TICKET */ 01117 01118 01119 #if !defined(NO_WOLFSSL_SERVER) && (defined(HAVE_SESSION_TICKET) && \ 01120 !defined(NO_PSK)) 01121 /* Add input to all handshake hashes. 01122 * 01123 * ssl The SSL/TLS object. 01124 * input The data to hash. 01125 * sz The size of the data to hash. 01126 * returns 0 on success, otherwise failure. 01127 */ 01128 static int HashInputRaw(WOLFSSL* ssl, const byte* input, int sz) 01129 { 01130 int ret = 0; 01131 01132 #ifndef NO_OLD_TLS 01133 #ifndef NO_SHA 01134 wc_ShaUpdate(&ssl->hsHashes->hashSha, input, sz); 01135 #endif 01136 #ifndef NO_MD5 01137 wc_Md5Update(&ssl->hsHashes->hashMd5, input, sz); 01138 #endif 01139 #endif 01140 01141 #ifndef NO_SHA256 01142 ret = wc_Sha256Update(&ssl->hsHashes->hashSha256, input, sz); 01143 if (ret != 0) 01144 return ret; 01145 #endif 01146 #ifdef WOLFSSL_SHA384 01147 ret = wc_Sha384Update(&ssl->hsHashes->hashSha384, input, sz); 01148 if (ret != 0) 01149 return ret; 01150 #endif 01151 #ifdef WOLFSSL_SHA512 01152 ret = wc_Sha512Update(&ssl->hsHashes->hashSha512, input, sz); 01153 if (ret != 0) 01154 return ret; 01155 #endif 01156 01157 return ret; 01158 } 01159 #endif 01160 01161 /* Extract the handshake header information. 01162 * 01163 * ssl The SSL/TLS object. 01164 * input The buffer holding the message data. 01165 * inOutIdx On entry, the index into the buffer of the handshake data. 01166 * On exit, the start of the hanshake data. 01167 * type Type of handshake message. 01168 * size The length of the handshake message data. 01169 * totalSz The total size of data in the buffer. 01170 * returns BUFFER_E if there is not enough input data and 0 on success. 01171 */ 01172 static int GetHandshakeHeader(WOLFSSL* ssl, const byte* input, word32* inOutIdx, 01173 byte *type, word32 *size, word32 totalSz) 01174 { 01175 const byte *ptr = input + *inOutIdx; 01176 (void)ssl; 01177 01178 *inOutIdx += HANDSHAKE_HEADER_SZ; 01179 if (*inOutIdx > totalSz) 01180 return BUFFER_E; 01181 01182 *type = ptr[0]; 01183 c24to32(&ptr[1], size); 01184 01185 return 0; 01186 } 01187 01188 /* Add record layer header to message. 01189 * 01190 * output The buffer to write the record layer header into. 01191 * length The length of the record data. 01192 * type The type of record message. 01193 * ssl The SSL/TLS object. 01194 */ 01195 static void AddTls13RecordHeader(byte* output, word32 length, byte type, 01196 WOLFSSL* ssl) 01197 { 01198 RecordLayerHeader* rl; 01199 01200 rl = (RecordLayerHeader*)output; 01201 rl->type = type; 01202 rl->pvMajor = ssl->version.major; 01203 rl->pvMinor = TLSv1_MINOR; 01204 c16toa((word16)length, rl->length); 01205 } 01206 01207 /* Add handshake header to message. 01208 * 01209 * output The buffer to write the hanshake header into. 01210 * length The length of the handshake data. 01211 * fragOffset The offset of the fragment data. (DTLS) 01212 * fragLength The length of the fragment data. (DTLS) 01213 * type The type of handshake message. 01214 * ssl The SSL/TLS object. (DTLS) 01215 */ 01216 static void AddTls13HandShakeHeader(byte* output, word32 length, 01217 word32 fragOffset, word32 fragLength, 01218 byte type, WOLFSSL* ssl) 01219 { 01220 HandShakeHeader* hs; 01221 (void)fragOffset; 01222 (void)fragLength; 01223 (void)ssl; 01224 01225 /* handshake header */ 01226 hs = (HandShakeHeader*)output; 01227 hs->type = type; 01228 c32to24(length, hs->length); 01229 } 01230 01231 01232 /* Add both record layer and handshake header to message. 01233 * 01234 * output The buffer to write the headers into. 01235 * length The length of the handshake data. 01236 * type The type of record layer message. 01237 * ssl The SSL/TLS object. (DTLS) 01238 */ 01239 static void AddTls13Headers(byte* output, word32 length, byte type, WOLFSSL* ssl) 01240 { 01241 word32 lengthAdj = HANDSHAKE_HEADER_SZ; 01242 word32 outputAdj = RECORD_HEADER_SZ; 01243 01244 AddTls13RecordHeader(output, length + lengthAdj, handshake, ssl); 01245 AddTls13HandShakeHeader(output + outputAdj, length, 0, length, type, ssl); 01246 } 01247 01248 01249 #ifndef NO_CERTS 01250 /* Add both record layer and fragement handshake header to message. 01251 * 01252 * output The buffer to write the headers into. 01253 * fragOffset The offset of the fragment data. (DTLS) 01254 * fragLength The length of the fragment data. (DTLS) 01255 * length The length of the handshake data. 01256 * type The type of record layer message. 01257 * ssl The SSL/TLS object. (DTLS) 01258 */ 01259 static void AddTls13FragHeaders(byte* output, word32 fragSz, word32 fragOffset, 01260 word32 length, byte type, WOLFSSL* ssl) 01261 { 01262 word32 lengthAdj = HANDSHAKE_HEADER_SZ; 01263 word32 outputAdj = RECORD_HEADER_SZ; 01264 (void)fragSz; 01265 01266 AddTls13RecordHeader(output, fragSz + lengthAdj, handshake, ssl); 01267 AddTls13HandShakeHeader(output + outputAdj, length, fragOffset, fragSz, 01268 type, ssl); 01269 } 01270 #endif /* NO_CERTS */ 01271 01272 /* Write the sequence number into the buffer. 01273 * No DTLS v1.3 support. 01274 * 01275 * ssl The SSL/TLS object. 01276 * verifyOrder Which set of sequence numbers to use. 01277 * out The buffer to write into. 01278 */ 01279 static INLINE void WriteSEQ(WOLFSSL* ssl, int verifyOrder, byte* out) 01280 { 01281 word32 seq[2] = {0, 0}; 01282 01283 if (verifyOrder) { 01284 seq[0] = ssl->keys.peer_sequence_number_hi; 01285 seq[1] = ssl->keys.peer_sequence_number_lo++; 01286 /* handle rollover */ 01287 if (seq[1] > ssl->keys.peer_sequence_number_lo) 01288 ssl->keys.peer_sequence_number_hi++; 01289 } 01290 else { 01291 seq[0] = ssl->keys.sequence_number_hi; 01292 seq[1] = ssl->keys.sequence_number_lo++; 01293 /* handle rollover */ 01294 if (seq[1] > ssl->keys.sequence_number_lo) 01295 ssl->keys.sequence_number_hi++; 01296 } 01297 01298 c32toa(seq[0], out); 01299 c32toa(seq[1], out + OPAQUE32_LEN); 01300 } 01301 01302 /* Build the nonce for TLS v1.3 encryption and decryption. 01303 * 01304 * ssl The SSL/TLS object. 01305 * nonce The nonce data to use when encrypting or decrypting. 01306 * iv The derived IV. 01307 * order The side on which the message is to be or was sent. 01308 */ 01309 static INLINE void BuildTls13Nonce(WOLFSSL* ssl, byte *nonce, const byte* iv, 01310 int order) 01311 { 01312 int i; 01313 01314 /* The nonce is the IV with the sequence XORed into the last bytes. */ 01315 WriteSEQ(ssl, order, nonce + AEAD_NONCE_SZ - SEQ_SZ); 01316 for (i = 0; i < AEAD_NONCE_SZ - SEQ_SZ; i++) 01317 nonce[i] = iv[i]; 01318 for (; i < AEAD_NONCE_SZ; i++) 01319 nonce[i] ^= iv[i]; 01320 } 01321 01322 /* Encrypt with ChaCha20 and create authenication tag with Poly1305. 01323 * 01324 * ssl The SSL/TLS object. 01325 * output The buffer to write encrypted data and authentication tag into. 01326 * May be the same pointer as input. 01327 * input The data to encrypt. 01328 * sz The number of bytes to encrypt. 01329 * nonce The nonce to use with ChaCha20. 01330 * tag The authentication tag buffer. 01331 * returns 0 on success, otherwise failure. 01332 */ 01333 static int ChaCha20Poly1305_Encrypt(WOLFSSL* ssl, byte* output, 01334 const byte* input, word16 sz, byte* nonce, 01335 byte* tag) 01336 { 01337 int ret = 0; 01338 byte poly[CHACHA20_256_KEY_SIZE]; 01339 01340 /* Poly1305 key is 256 bits of zero encrypted with ChaCha20. */ 01341 XMEMSET(poly, 0, sizeof(poly)); 01342 01343 /* Set the nonce for ChaCha and get Poly1305 key. */ 01344 ret = wc_Chacha_SetIV(ssl->encrypt.chacha, nonce, 0); 01345 if (ret != 0) 01346 return ret; 01347 /* Create Poly1305 key using ChaCha20 keystream. */ 01348 ret = wc_Chacha_Process(ssl->encrypt.chacha, poly, poly, sizeof(poly)); 01349 if (ret != 0) 01350 return ret; 01351 /* Encrypt the plain text. */ 01352 ret = wc_Chacha_Process(ssl->encrypt.chacha, output, input, sz); 01353 if (ret != 0) { 01354 ForceZero(poly, sizeof(poly)); 01355 return ret; 01356 } 01357 01358 /* Set key for Poly1305. */ 01359 ret = wc_Poly1305SetKey(ssl->auth.poly1305, poly, sizeof(poly)); 01360 ForceZero(poly, sizeof(poly)); /* done with poly1305 key, clear it */ 01361 if (ret != 0) 01362 return ret; 01363 /* Add authentication code of encrypted data to end. */ 01364 ret = wc_Poly1305_MAC(ssl->auth.poly1305, NULL, 0, output, sz, tag, 01365 POLY1305_AUTH_SZ); 01366 01367 return ret; 01368 } 01369 01370 /* Encrypt data for TLS v1.3. 01371 * 01372 * ssl The SSL/TLS object. 01373 * output The buffer to write encrypted data and authentication tag into. 01374 * May be the same pointer as input. 01375 * input The data to encrypt. 01376 * sz The number of bytes to encrypt. 01377 * returns 0 on success, otherwise failure. 01378 */ 01379 static int EncryptTls13(WOLFSSL* ssl, byte* output, const byte* input, 01380 word16 sz) 01381 { 01382 int ret = 0; 01383 word16 dataSz = sz - ssl->specs.aead_mac_size; 01384 word16 macSz = ssl->specs.aead_mac_size; 01385 byte nonce[AEAD_NONCE_SZ]; 01386 01387 (void)output; 01388 (void)input; 01389 (void)sz; 01390 (void)dataSz; 01391 (void)macSz; 01392 01393 #ifdef WOLFSSL_DEBUG_TLS 01394 WOLFSSL_MSG("Data to encrypt"); 01395 WOLFSSL_BUFFER(input, dataSz); 01396 #endif 01397 01398 BuildTls13Nonce(ssl, nonce, ssl->keys.aead_enc_imp_IV, CUR_ORDER); 01399 01400 switch (ssl->specs.bulk_cipher_algorithm) { 01401 #ifdef BUILD_AESGCM 01402 case wolfssl_aes_gcm: 01403 ret = wc_AesGcmEncrypt(ssl->encrypt.aes, output, input, dataSz, 01404 nonce, AESGCM_NONCE_SZ, output + dataSz, macSz, NULL, 0); 01405 break; 01406 #endif 01407 01408 #ifdef HAVE_AESCCM 01409 case wolfssl_aes_ccm: 01410 ret = wc_AesCcmEncrypt(ssl->encrypt.aes, output, input, dataSz, 01411 nonce, AESCCM_NONCE_SZ, output + dataSz, macSz, NULL, 0); 01412 break; 01413 #endif 01414 01415 #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) 01416 case wolfssl_chacha: 01417 ret = ChaCha20Poly1305_Encrypt(ssl, output, input, dataSz, nonce, 01418 output + dataSz); 01419 break; 01420 #endif 01421 01422 default: 01423 WOLFSSL_MSG("wolfSSL Encrypt programming error"); 01424 return ENCRYPT_ERROR; 01425 } 01426 01427 ForceZero(nonce, AEAD_NONCE_SZ); 01428 01429 #ifdef WOLFSSL_DEBUG_TLS 01430 WOLFSSL_MSG("Encrypted data"); 01431 WOLFSSL_BUFFER(output, dataSz); 01432 WOLFSSL_MSG("Authentication Tag"); 01433 WOLFSSL_BUFFER(output + dataSz, macSz); 01434 #endif 01435 01436 return ret; 01437 } 01438 01439 /* Decrypt with ChaCha20 and check authenication tag with Poly1305. 01440 * 01441 * ssl The SSL/TLS object. 01442 * output The buffer to write decrypted data into. 01443 * May be the same pointer as input. 01444 * input The data to decrypt. 01445 * sz The number of bytes to decrypt. 01446 * nonce The nonce to use with ChaCha20. 01447 * tagIn The authentication tag data from packet. 01448 * returns 0 on success, otherwise failure. 01449 */ 01450 static int ChaCha20Poly1305_Decrypt(WOLFSSL *ssl, byte* output, 01451 const byte* input, word16 sz, byte* nonce, 01452 const byte* tagIn) 01453 { 01454 int ret; 01455 byte tag[POLY1305_AUTH_SZ]; 01456 byte poly[CHACHA20_256_KEY_SIZE]; /* generated key for mac */ 01457 01458 /* Poly1305 key is 256 bits of zero encrypted with ChaCha20. */ 01459 XMEMSET(poly, 0, sizeof(poly)); 01460 01461 /* Set nonce and get Poly1305 key. */ 01462 ret = wc_Chacha_SetIV(ssl->decrypt.chacha, nonce, 0); 01463 if (ret != 0) 01464 return ret; 01465 /* Use ChaCha20 keystream to get Poly1305 key for tag. */ 01466 ret = wc_Chacha_Process(ssl->decrypt.chacha, poly, poly, sizeof(poly)); 01467 if (ret != 0) 01468 return ret; 01469 01470 /* Set key for Poly1305. */ 01471 ret = wc_Poly1305SetKey(ssl->auth.poly1305, poly, sizeof(poly)); 01472 ForceZero(poly, sizeof(poly)); /* done with poly1305 key, clear it */ 01473 if (ret != 0) 01474 return ret; 01475 /* Generate authentication tag for encrypted data. */ 01476 if ((ret = wc_Poly1305_MAC(ssl->auth.poly1305, NULL, 0, (byte*)input, sz, 01477 tag, sizeof(tag))) != 0) { 01478 return ret; 01479 } 01480 01481 /* Check tag sent along with packet. */ 01482 if (ConstantCompare(tagIn, tag, POLY1305_AUTH_SZ) != 0) { 01483 WOLFSSL_MSG("MAC did not match"); 01484 return VERIFY_MAC_ERROR; 01485 } 01486 01487 /* If the tag was good decrypt message. */ 01488 ret = wc_Chacha_Process(ssl->decrypt.chacha, output, input, sz); 01489 01490 return ret; 01491 } 01492 01493 /* Decrypt data for TLS v1.3. 01494 * 01495 * ssl The SSL/TLS object. 01496 * output The buffer to write decrypted data into. 01497 * May be the same pointer as input. 01498 * input The data to encrypt and authentication tag. 01499 * sz The length of the encrypted data plus authentication tag. 01500 * returns 0 on success, otherwise failure. 01501 */ 01502 int DecryptTls13(WOLFSSL* ssl, byte* output, const byte* input, word16 sz) 01503 { 01504 int ret = 0; 01505 word16 dataSz = sz - ssl->specs.aead_mac_size; 01506 word16 macSz = ssl->specs.aead_mac_size; 01507 byte nonce[AEAD_NONCE_SZ]; 01508 01509 (void)output; 01510 (void)input; 01511 (void)sz; 01512 (void)dataSz; 01513 (void)macSz; 01514 01515 #ifdef WOLFSSL_DEBUG_TLS 01516 WOLFSSL_MSG("Data to decrypt"); 01517 WOLFSSL_BUFFER(input, dataSz); 01518 WOLFSSL_MSG("Authentication tag"); 01519 WOLFSSL_BUFFER(input + dataSz, macSz); 01520 #endif 01521 01522 BuildTls13Nonce(ssl, nonce, ssl->keys.aead_dec_imp_IV, PEER_ORDER); 01523 01524 switch (ssl->specs.bulk_cipher_algorithm) { 01525 #ifdef BUILD_AESGCM 01526 case wolfssl_aes_gcm: 01527 ret = wc_AesGcmDecrypt(ssl->decrypt.aes, output, input, dataSz, 01528 nonce, AESGCM_NONCE_SZ, input + dataSz, macSz, NULL, 0); 01529 break; 01530 #endif 01531 01532 #ifdef HAVE_AESCCM 01533 case wolfssl_aes_ccm: 01534 ret = wc_AesCcmDecrypt(ssl->decrypt.aes, output, input, dataSz, 01535 nonce, AESCCM_NONCE_SZ, input + dataSz, macSz, NULL, 0); 01536 break; 01537 #endif 01538 01539 #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305) 01540 case wolfssl_chacha: 01541 ret = ChaCha20Poly1305_Decrypt(ssl, output, input, dataSz, nonce, 01542 input + dataSz); 01543 break; 01544 #endif 01545 01546 default: 01547 WOLFSSL_MSG("wolfSSL Decrypt programming error"); 01548 return DECRYPT_ERROR; 01549 } 01550 01551 ForceZero(nonce, AEAD_NONCE_SZ); 01552 if (ret < 0 && !ssl->options.dtls) { 01553 SendAlert(ssl, alert_fatal, bad_record_mac); 01554 ret = VERIFY_MAC_ERROR; 01555 } 01556 01557 #ifdef WOLFSSL_DEBUG_TLS 01558 WOLFSSL_MSG("Decrypted data"); 01559 WOLFSSL_BUFFER(output, dataSz); 01560 #endif 01561 01562 return ret; 01563 } 01564 01565 /* Build SSL Message, encrypted. 01566 * TLS v1.3 encryption is AEAD only. 01567 * 01568 * ssl The SSL/TLS object. 01569 * output The buffer to write record message to. 01570 * outSz Size of the buffer being written into. 01571 * input The record data to encrypt (excluding record header). 01572 * inSz The size of the record data. 01573 * type The recorder header content type. 01574 * hashOutput Whether to hash the unencrypted record data. 01575 * sizeOnly Only want the size of the record message. 01576 * returns the size of the encrypted record message or negative value on error. 01577 */ 01578 int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input, 01579 int inSz, int type, int hashOutput, int sizeOnly) 01580 { 01581 word32 sz = RECORD_HEADER_SZ + inSz; 01582 word32 idx = RECORD_HEADER_SZ; 01583 word32 headerSz = RECORD_HEADER_SZ; 01584 word16 size; 01585 int ret = 0; 01586 int atomicUser = 0; 01587 01588 if (ssl == NULL) 01589 return BAD_FUNC_ARG; 01590 if (!sizeOnly && (output == NULL || input == NULL)) 01591 return BAD_FUNC_ARG; 01592 /* catch mistaken sizeOnly parameter */ 01593 if (sizeOnly && (output || input)) { 01594 WOLFSSL_MSG("BuildMessage with sizeOnly doesn't need input or output"); 01595 return BAD_FUNC_ARG; 01596 } 01597 01598 /* Record layer content type at the end of record data. */ 01599 sz++; 01600 /* Authentication data at the end. */ 01601 sz += ssl->specs.aead_mac_size; 01602 01603 if (sizeOnly) 01604 return sz; 01605 01606 if (sz > (word32)outSz) { 01607 WOLFSSL_MSG("Oops, want to write past output buffer size"); 01608 return BUFFER_E; 01609 } 01610 01611 /* Record data length. */ 01612 size = (word16)(sz - headerSz); 01613 /* Write/update the record header with the new size. 01614 * Always have the content type as application data for encrypted 01615 * messages in TLS v1.3. 01616 */ 01617 AddTls13RecordHeader(output, size, application_data, ssl); 01618 01619 /* TLS v1.3 can do in place encryption. */ 01620 if (input != output + idx) 01621 XMEMCPY(output + idx, input, inSz); 01622 idx += inSz; 01623 01624 if (hashOutput) { 01625 ret = HashOutput(ssl, output, headerSz + inSz, 0); 01626 if (ret != 0) 01627 return ret; 01628 } 01629 01630 /* The real record content type goes at the end of the data. */ 01631 output[idx++] = type; 01632 01633 #ifdef ATOMIC_USER 01634 if (ssl->ctx->MacEncryptCb) 01635 atomicUser = 1; 01636 #endif 01637 01638 if (atomicUser) { /* User Record Layer Callback handling */ 01639 #ifdef ATOMIC_USER 01640 byte* mac = output + idx; 01641 output += headerSz; 01642 01643 if ((ret = ssl->ctx->MacEncryptCb(ssl, mac, output, inSz, type, 0, 01644 output, output, size, ssl->MacEncryptCtx)) != 0) { 01645 return ret; 01646 } 01647 #endif 01648 } 01649 else { 01650 output += headerSz; 01651 if ((ret = EncryptTls13(ssl, output, output, size)) != 0) 01652 return ret; 01653 } 01654 01655 return sz; 01656 } 01657 01658 #ifndef NO_WOLFSSL_CLIENT 01659 #if defined(HAVE_SESSION_TICKET) && !defined(NO_PSK) 01660 /* Get the size of the message hash. 01661 * 01662 * ssl The SSL/TLS object. 01663 * returns the length of the hash. 01664 */ 01665 static int GetMsgHashSize(WOLFSSL *ssl) 01666 { 01667 switch (ssl->specs.mac_algorithm) { 01668 #ifndef NO_SHA256 01669 case sha256_mac: 01670 return SHA256_DIGEST_SIZE; 01671 #endif /* !NO_SHA256 */ 01672 #ifdef WOLFSSL_SHA384 01673 case sha384_mac: 01674 return SHA384_DIGEST_SIZE; 01675 #endif /* WOLFSSL_SHA384 */ 01676 #ifdef WOLFSSL_SHA512 01677 case sha512_mac: 01678 return SHA512_DIGEST_SIZE; 01679 #endif /* WOLFSSL_SHA512 */ 01680 } 01681 return 0; 01682 } 01683 01684 /* Derive and write the binders into the ClientHello in space left when 01685 * writing the Pre-Shared Key extension. 01686 * 01687 * ssl The SSL/TLS object. 01688 * output The buffer containing the ClientHello. 01689 * idx The index at the end of the completed ClientHello. 01690 * returns 0 on success and otherwise failure. 01691 */ 01692 static int WritePSKBinders(WOLFSSL* ssl, byte* output, word32 idx) 01693 { 01694 int ret; 01695 TLSX* ext; 01696 PreSharedKey* current; 01697 byte binderKey[MAX_DIGEST_SIZE]; 01698 word16 len; 01699 01700 ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY); 01701 if (ext == NULL) 01702 return SANITY_MSG_E; 01703 01704 /* Get the size of the binders to determine where to write binders. */ 01705 idx -= TLSX_PreSharedKey_GetSizeBinders(ext->data, client_hello); 01706 01707 /* Hash truncated ClientHello - up to binders. */ 01708 ret = HashOutput(ssl, output, idx, 0); 01709 if (ret != 0) 01710 return ret; 01711 01712 current = ext->data; 01713 /* Calculate the binder for each identity based on previous handshake data. 01714 */ 01715 while (current != NULL) { 01716 if (current->resumption) { 01717 /* Set the HMAC to use based on the one for the session (set into 01718 * the extension data at the start of this function based on the 01719 * cipher suite in the session information. 01720 */ 01721 ssl->specs.mac_algorithm = current->hmac; 01722 01723 /* Resumption PSK is master secret. */ 01724 ssl->arrays->psk_keySz = GetMsgHashSize(ssl); 01725 XMEMCPY(ssl->arrays->psk_key, ssl->session.masterSecret, 01726 ssl->arrays->psk_keySz); 01727 /* Derive the early secret using the PSK. */ 01728 DeriveEarlySecret(ssl); 01729 /* Derive the binder key to use to with HMAC. */ 01730 DeriveBinderKeyResume(ssl, binderKey); 01731 } 01732 else { 01733 /* TODO: [TLS13] Support non-ticket PSK. */ 01734 /* Get the pre-shared key. */ 01735 ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl, 01736 (char *)current->identity, ssl->arrays->client_identity, 01737 MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN); 01738 /* Derive the early secret using the PSK. */ 01739 DeriveEarlySecret(ssl); 01740 /* Derive the binder key to use to with HMAC. */ 01741 DeriveBinderKey(ssl, binderKey); 01742 } 01743 01744 /* Derive the Finished message secret. */ 01745 DeriveFinishedSecret(ssl, binderKey, ssl->keys.client_write_MAC_secret); 01746 /* Build the HMAC of the handshake message data = binder. */ 01747 current->binderLen = BuildTls13HandshakeHmac(ssl, 01748 ssl->keys.client_write_MAC_secret, current->binder); 01749 01750 current = current->next; 01751 } 01752 01753 /* Data entered into extension, now write to message. */ 01754 len = TLSX_PreSharedKey_WriteBinders(ext->data, output + idx, client_hello); 01755 01756 /* Hash binders to complete the hash of the ClientHello. */ 01757 return HashOutputRaw(ssl, output + idx, len); 01758 } 01759 #endif 01760 01761 /* Send a ClientHello message to the server. 01762 * Include the information required to start a handshake with servers using 01763 * protocol versions less than TLS v1.3. 01764 * Only a client will send this message. 01765 * 01766 * ssl The SSL/TLS object. 01767 * returns 0 on success and otherwise failure. 01768 */ 01769 int SendTls13ClientHello(WOLFSSL* ssl) 01770 { 01771 byte* output; 01772 word32 length; 01773 word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ; 01774 int sendSz; 01775 int ret; 01776 01777 #if defined(WOLFSSL_TLS13) && defined(HAVE_SESSION_TICKET) && !defined(NO_PSK) 01778 if (ssl->options.resuming && 01779 (ssl->session.version.major != ssl->version.major || 01780 ssl->session.version.minor != ssl->version.minor)) { 01781 ssl->version.major = ssl->session.version.major; 01782 ssl->version.minor = ssl->session.version.minor; 01783 return SendClientHello(ssl); 01784 } 01785 #endif 01786 01787 if (ssl->suites == NULL) { 01788 WOLFSSL_MSG("Bad suites pointer in SendTls13ClientHello"); 01789 return SUITES_ERROR; 01790 } 01791 01792 /* Version | Random | Session Id | Cipher Suites | Compression | Ext */ 01793 length = VERSION_SZ + RAN_LEN + ENUM_LEN + ssl->suites->suiteSz + 01794 SUITE_LEN + COMP_LEN + ENUM_LEN; 01795 01796 /* Auto populate extensions supported unless user defined. */ 01797 if ((ret = TLSX_PopulateExtensions(ssl, 0)) != 0) 01798 return ret; 01799 #ifdef HAVE_QSH 01800 if (QSH_Init(ssl) != 0) 01801 return MEMORY_E; 01802 #endif 01803 /* Include length of TLS extensions. */ 01804 length += TLSX_GetRequestSize(ssl); 01805 01806 /* Total message size. */ 01807 sendSz = length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ; 01808 01809 /* Check buffers are big enough and grow if needed. */ 01810 if ((ret = CheckAvailableSize(ssl, sendSz)) != 0) 01811 return ret; 01812 01813 /* Get position in output buffer to write new message to. */ 01814 output = ssl->buffers.outputBuffer.buffer + 01815 ssl->buffers.outputBuffer.length; 01816 01817 /* Put the record and handshake headers on. */ 01818 AddTls13Headers(output, length, client_hello, ssl); 01819 01820 /* Protocol version. */ 01821 output[idx++] = SSLv3_MAJOR; 01822 output[idx++] = TLSv1_2_MINOR; 01823 ssl->chVersion = ssl->version; 01824 01825 /* Client Random */ 01826 if (ssl->options.connectState == CONNECT_BEGIN) { 01827 ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, RAN_LEN); 01828 if (ret != 0) 01829 return ret; 01830 01831 /* Store random for possible second ClientHello. */ 01832 XMEMCPY(ssl->arrays->clientRandom, output + idx, RAN_LEN); 01833 } 01834 else 01835 XMEMCPY(output + idx, ssl->arrays->clientRandom, RAN_LEN); 01836 idx += RAN_LEN; 01837 01838 /* TLS v1.3 does not use session id - 0 length. */ 01839 output[idx++] = 0; 01840 01841 /* Cipher suites */ 01842 c16toa(ssl->suites->suiteSz, output + idx); 01843 idx += OPAQUE16_LEN; 01844 XMEMCPY(output + idx, &ssl->suites->suites, ssl->suites->suiteSz); 01845 idx += ssl->suites->suiteSz; 01846 01847 /* Compression not supported in TLS v1.3. */ 01848 output[idx++] = COMP_LEN; 01849 output[idx++] = NO_COMPRESSION; 01850 01851 /* Write out extensions for a request. */ 01852 idx += TLSX_WriteRequest(ssl, output + idx); 01853 01854 #if defined(HAVE_SESSION_TICKET) && !defined(NO_PSK) 01855 /* Resumption has a specific set of extensions and binder is calculated 01856 * for each identity. 01857 */ 01858 if (ssl->options.resuming) 01859 ret = WritePSKBinders(ssl, output, idx); 01860 else 01861 #endif 01862 ret = HashOutput(ssl, output, idx, 0); 01863 if (ret != 0) 01864 return ret; 01865 01866 ssl->options.clientState = CLIENT_HELLO_COMPLETE; 01867 01868 #ifdef WOLFSSL_CALLBACKS 01869 if (ssl->hsInfoOn) AddPacketName("ClientHello", &ssl->handShakeInfo); 01870 if (ssl->toInfoOn) 01871 AddPacketInfo("ClientHello", &ssl->timeoutInfo, output, sendSz, 01872 ssl->heap); 01873 #endif 01874 01875 ssl->buffers.outputBuffer.length += sendSz; 01876 01877 return SendBuffered(ssl); 01878 } 01879 01880 /* Parse and handle a HelloRetryRequest message. 01881 * Only a client will receive this message. 01882 * 01883 * ssl The SSL/TLS object. 01884 * input The message buffer. 01885 * inOutIdx On entry, the index into the message buffer of 01886 * HelloRetryRequest. 01887 * On exit, the index of byte after the HelloRetryRequest message. 01888 * totalSz The length of the current handshake message. 01889 * returns 0 on success and otherwise failure. 01890 */ 01891 static int DoTls13HelloRetryRequest(WOLFSSL* ssl, const byte* input, 01892 word32* inOutIdx, word32 totalSz) 01893 { 01894 int ret; 01895 word32 begin = *inOutIdx; 01896 word32 i = begin; 01897 word16 totalExtSz; 01898 ProtocolVersion pv; 01899 01900 #ifdef WOLFSSL_CALLBACKS 01901 if (ssl->hsInfoOn) AddPacketName("HelloRetryRequest", &ssl->handShakeInfo); 01902 if (ssl->toInfoOn) AddLateName("HelloRetryRequest", &ssl->timeoutInfo); 01903 #endif 01904 01905 /* Version info and length field of extension data. */ 01906 if (totalSz < i - begin + OPAQUE16_LEN + OPAQUE16_LEN) 01907 return BUFFER_ERROR; 01908 01909 /* Protocol version. */ 01910 XMEMCPY(&pv, input + i, OPAQUE16_LEN); 01911 i += OPAQUE16_LEN; 01912 ret = CheckVersion(ssl, pv); 01913 if (ret != 0) 01914 return ret; 01915 01916 /* Length of extension data. */ 01917 ato16(&input[i], &totalExtSz); 01918 i += OPAQUE16_LEN; 01919 if (totalExtSz == 0) { 01920 WOLFSSL_MSG("HelloRetryRequest must contain extensions"); 01921 return MISSING_HANDSHAKE_DATA; 01922 } 01923 01924 /* Extension data. */ 01925 if (i - begin + totalExtSz > totalSz) 01926 return BUFFER_ERROR; 01927 if ((ret = TLSX_Parse(ssl, (byte *)(input + i), totalExtSz, 01928 hello_retry_request, NULL))) 01929 return ret; 01930 /* The KeyShare extension parsing fails when not valid. */ 01931 01932 /* Move index to byte after message. */ 01933 *inOutIdx = i + totalExtSz; 01934 01935 ssl->options.tls1_3 = 1; 01936 ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST; 01937 01938 return 0; 01939 } 01940 01941 /* Handle the ServerHello message from the server. 01942 * Only a client will receive this message. 01943 * 01944 * ssl The SSL/TLS object. 01945 * input The message buffer. 01946 * inOutIdx On entry, the index into the message buffer of ServerHello. 01947 * On exit, the index of byte after the ServerHello message. 01948 * helloSz The length of the current handshake message. 01949 * returns 0 on success and otherwise failure. 01950 */ 01951 int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, 01952 word32 helloSz) 01953 { 01954 ProtocolVersion pv; 01955 word32 i = *inOutIdx; 01956 word32 begin = i; 01957 int ret; 01958 word16 totalExtSz; 01959 01960 #ifdef WOLFSSL_CALLBACKS 01961 if (ssl->hsInfoOn) AddPacketName("ServerHello", &ssl->handShakeInfo); 01962 if (ssl->toInfoOn) AddLateName("ServerHello", &ssl->timeoutInfo); 01963 #endif 01964 01965 /* Protocol version length check. */ 01966 if (OPAQUE16_LEN > helloSz) 01967 return BUFFER_ERROR; 01968 01969 /* Protocol version */ 01970 XMEMCPY(&pv, input + i, OPAQUE16_LEN); 01971 i += OPAQUE16_LEN; 01972 ret = CheckVersion(ssl, pv); 01973 if (ret != 0) 01974 return ret; 01975 if (!IsAtLeastTLSv1_3(pv) && pv.major != TLS_DRAFT_MAJOR) { 01976 ssl->version = pv; 01977 return DoServerHello(ssl, input, inOutIdx, helloSz); 01978 } 01979 01980 /* Random, cipher suite and extensions length check. */ 01981 if ((i - begin) + RAN_LEN + OPAQUE16_LEN + OPAQUE16_LEN > helloSz) 01982 return BUFFER_ERROR; 01983 01984 /* Server random - keep for debugging. */ 01985 XMEMCPY(ssl->arrays->serverRandom, input + i, RAN_LEN); 01986 i += RAN_LEN; 01987 /* TODO: [TLS13] Check last 8 bytes. */ 01988 01989 /* Set the cipher suite from the message. */ 01990 ssl->options.cipherSuite0 = input[i++]; 01991 ssl->options.cipherSuite = input[i++]; 01992 01993 /* Get extension length and length check. */ 01994 ato16(&input[i], &totalExtSz); 01995 i += OPAQUE16_LEN; 01996 if ((i - begin) + totalExtSz > helloSz) 01997 return BUFFER_ERROR; 01998 01999 /* Parse and handle extensions. */ 02000 ret = TLSX_Parse(ssl, (byte *) input + i, totalExtSz, server_hello, NULL); 02001 if (ret != 0) 02002 return ret; 02003 02004 i += totalExtSz; 02005 *inOutIdx = i; 02006 02007 ssl->options.serverState = SERVER_HELLO_COMPLETE; 02008 02009 #ifdef HAVE_SECRET_CALLBACK 02010 if (ssl->sessionSecretCb != NULL) { 02011 int secretSz = SECRET_LEN, ret; 02012 ret = ssl->sessionSecretCb(ssl, ssl->session.masterSecret, 02013 &secretSz, ssl->sessionSecretCtx); 02014 if (ret != 0 || secretSz != SECRET_LEN) 02015 return SESSION_SECRET_CB_E; 02016 } 02017 #endif /* HAVE_SECRET_CALLBACK */ 02018 02019 ret = SetCipherSpecs(ssl); 02020 if (ret != 0) 02021 return ret; 02022 02023 #ifndef NO_PSK 02024 if (ssl->options.resuming) { 02025 PreSharedKey *psk = NULL; 02026 TLSX* ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY); 02027 if (ext != NULL) 02028 psk = (PreSharedKey*)ext->data; 02029 while (psk != NULL && !psk->chosen) 02030 psk = psk->next; 02031 if (psk == NULL) { 02032 ssl->options.resuming = 0; 02033 ssl->arrays->psk_keySz = ssl->specs.hash_size; 02034 XMEMSET(ssl->arrays->psk_key, 0, ssl->arrays->psk_keySz); 02035 } 02036 } 02037 #endif 02038 02039 ssl->keys.encryptionOn = 1; 02040 02041 return ret; 02042 } 02043 02044 /* Parse and handle an EncryptedExtensions message. 02045 * Only a client will receive this message. 02046 * 02047 * ssl The SSL/TLS object. 02048 * input The message buffer. 02049 * inOutIdx On entry, the index into the message buffer of 02050 * EncryptedExtensions. 02051 * On exit, the index of byte after the EncryptedExtensions 02052 * message. 02053 * totalSz The length of the current handshake message. 02054 * returns 0 on success and otherwise failure. 02055 */ 02056 static int DoTls13EncryptedExtensions(WOLFSSL* ssl, const byte* input, 02057 word32* inOutIdx, word32 totalSz) 02058 { 02059 int ret; 02060 word32 begin = *inOutIdx; 02061 word32 i = begin; 02062 word16 totalExtSz; 02063 02064 #ifdef WOLFSSL_CALLBACKS 02065 if (ssl->hsInfoOn) AddPacketName("EncryptedExtensions", 02066 &ssl->handShakeInfo); 02067 if (ssl->toInfoOn) AddLateName("EncryptedExtensions", &ssl->timeoutInfo); 02068 #endif 02069 02070 /* Length field of extension data. */ 02071 if (totalSz < i - begin + OPAQUE16_LEN) 02072 return BUFFER_ERROR; 02073 ato16(&input[i], &totalExtSz); 02074 i += OPAQUE16_LEN; 02075 02076 /* Extension data. */ 02077 if (i - begin + totalExtSz > totalSz) 02078 return BUFFER_ERROR; 02079 if ((ret = TLSX_Parse(ssl, (byte *)(input + i), totalExtSz, 02080 encrypted_extensions, NULL))) 02081 return ret; 02082 02083 /* Move index to byte after message. */ 02084 *inOutIdx = i + totalExtSz; 02085 02086 /* Always encrypted. */ 02087 *inOutIdx += ssl->keys.padSz; 02088 02089 return 0; 02090 } 02091 02092 /* Handle a TLS v1.3 CertificateRequest message. 02093 * This message is always encrypted. 02094 * Only a client will receive this message. 02095 * 02096 * ssl The SSL/TLS object. 02097 * input The message buffer. 02098 * inOutIdx On entry, the index into the message buffer of CertificateRequest. 02099 * On exit, the index of byte after the CertificateRequest message. 02100 * size The length of the current handshake message. 02101 * returns 0 on success and otherwise failure. 02102 */ 02103 static int DoTls13CertificateRequest(WOLFSSL* ssl, const byte* input, 02104 word32* inOutIdx, word32 size) 02105 { 02106 word16 len; 02107 word32 begin = *inOutIdx; 02108 02109 #ifdef WOLFSSL_CALLBACKS 02110 if (ssl->hsInfoOn) AddPacketName("CertificateRequest", 02111 &ssl->handShakeInfo); 02112 if (ssl->toInfoOn) AddLateName("CertificateRequest", &ssl->timeoutInfo); 02113 #endif 02114 02115 if ((*inOutIdx - begin) + OPAQUE8_LEN > size) 02116 return BUFFER_ERROR; 02117 02118 /* Length of the request context. */ 02119 len = input[(*inOutIdx)++]; 02120 if ((*inOutIdx - begin) + len > size) 02121 return BUFFER_ERROR; 02122 if (ssl->options.connectState < FINISHED_DONE && len > 0) 02123 return BUFFER_ERROR; 02124 02125 /* Request context parsed here. */ 02126 /* TODO: [TLS13] Request context for post-handshake auth. 02127 * Store the value and return it in Certificate message. 02128 * Must be unique in the scope of the connection. 02129 */ 02130 *inOutIdx += len; 02131 02132 /* Signature and hash algorithms. */ 02133 if ((*inOutIdx - begin) + OPAQUE16_LEN > size) 02134 return BUFFER_ERROR; 02135 ato16(input + *inOutIdx, &len); 02136 *inOutIdx += OPAQUE16_LEN; 02137 if ((*inOutIdx - begin) + len > size) 02138 return BUFFER_ERROR; 02139 PickHashSigAlgo(ssl, input + *inOutIdx, len); 02140 *inOutIdx += len; 02141 02142 /* Length of certificate authority data. */ 02143 if ((*inOutIdx - begin) + OPAQUE16_LEN > size) 02144 return BUFFER_ERROR; 02145 ato16(input + *inOutIdx, &len); 02146 *inOutIdx += OPAQUE16_LEN; 02147 if ((*inOutIdx - begin) + len > size) 02148 return BUFFER_ERROR; 02149 02150 /* Certificate authorities. */ 02151 while (len) { 02152 word16 dnSz; 02153 02154 if ((*inOutIdx - begin) + OPAQUE16_LEN > size) 02155 return BUFFER_ERROR; 02156 02157 ato16(input + *inOutIdx, &dnSz); 02158 *inOutIdx += OPAQUE16_LEN; 02159 02160 if ((*inOutIdx - begin) + dnSz > size) 02161 return BUFFER_ERROR; 02162 02163 *inOutIdx += dnSz; 02164 len -= OPAQUE16_LEN + dnSz; 02165 } 02166 02167 /* TODO: [TLS13] Add extension handling. */ 02168 /* Certificate extensions */ 02169 if ((*inOutIdx - begin) + OPAQUE16_LEN > size) 02170 return BUFFER_ERROR; 02171 ato16(input + *inOutIdx, &len); 02172 *inOutIdx += OPAQUE16_LEN; 02173 if ((*inOutIdx - begin) + len > size) 02174 return BUFFER_ERROR; 02175 /* Skip over extensions for now. */ 02176 *inOutIdx += len; 02177 02178 ssl->options.sendVerify = SEND_CERT; 02179 02180 /* This message is always encrypted so add encryption padding. */ 02181 *inOutIdx += ssl->keys.padSz; 02182 02183 return 0; 02184 } 02185 02186 #endif /* !NO_WOLFSSL_CLIENT */ 02187 02188 #ifndef NO_WOLFSSL_SERVER 02189 #if defined(HAVE_SESSION_TICKET) && !defined(NO_PSK) 02190 /* Handle any Pre-Shared Key (PSK) extension. 02191 * Must do this in ClientHello as it requires a hash of the truncated message. 02192 * Don't know size of binders until Pre-Shared Key extension has been parsed. 02193 * 02194 * ssl The SSL/TLS object. 02195 * input The ClientHello message. 02196 * helloSz The size of the ClientHello message (including binders if present). 02197 * usingPSK Indicates handshake is using Pre-Shared Keys. 02198 * returns 0 on success and otherwise failure. 02199 */ 02200 static int DoPreSharedKeys(WOLFSSL *ssl, const byte* input, word32 helloSz, 02201 int* usingPSK) 02202 { 02203 int ret; 02204 TLSX* ext; 02205 word16 bindersLen; 02206 PreSharedKey* current; 02207 byte binderKey[MAX_DIGEST_SIZE]; 02208 byte binder[MAX_DIGEST_SIZE]; 02209 word16 binderLen; 02210 word16 modes; 02211 02212 ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY); 02213 if (ext == NULL) 02214 return 0; 02215 02216 /* Extensions pushed on stack/list and PSK must be last. */ 02217 if (ssl->extensions != ext) 02218 return PSK_KEY_ERROR; 02219 02220 /* Assume we are going to resume with a pre-shared key. */ 02221 ssl->options.resuming = 1; 02222 02223 /* Find the pre-shared key extension and calculate hash of truncated 02224 * ClientHello for binders. 02225 */ 02226 bindersLen = TLSX_PreSharedKey_GetSizeBinders(ext->data, client_hello); 02227 02228 /* Hash data up to binders for deriving binders in PSK extension. */ 02229 ret = HashInput(ssl, input, helloSz - bindersLen); 02230 if (ret != 0) 02231 return ret; 02232 02233 /* Look through all client's pre-shared keys for a match. */ 02234 current = (PreSharedKey*)ext->data; 02235 while (current != NULL) { 02236 /* TODO: [TLS13] Support non-ticket PSK. */ 02237 /* Decode the identity. */ 02238 ret = DoClientTicket(ssl, current->identity, current->identityLen); 02239 if (ret != WOLFSSL_TICKET_RET_OK) 02240 continue; 02241 02242 if (current->resumption) { 02243 /* Check the ticket isn't too old or new. */ 02244 int diff = TimeNowInMilliseconds() - ssl->session.ticketSeen; 02245 diff -= current->ticketAge - ssl->session.ticketAdd; 02246 /* TODO: [TLS13] What should the value be? Configurable? */ 02247 if (diff < -1000 || diff > 1000) { 02248 /* Invalid difference, fallback to full handshake. */ 02249 ssl->options.resuming = 0; 02250 break; 02251 } 02252 02253 /* Use the same cipher suite as before and set up for use. */ 02254 ssl->options.cipherSuite0 = ssl->session.cipherSuite0; 02255 ssl->options.cipherSuite = ssl->session.cipherSuite; 02256 ret = SetCipherSpecs(ssl); 02257 if (ret != 0) 02258 return ret; 02259 02260 /* Resumption PSK is resumption master secret. */ 02261 ssl->arrays->psk_keySz = ssl->specs.hash_size; 02262 XMEMCPY(ssl->arrays->psk_key, ssl->session.masterSecret, 02263 ssl->specs.hash_size); 02264 /* Derive the early secret using the PSK. */ 02265 DeriveEarlySecret(ssl); 02266 /* Derive the binder key to use to with HMAC. */ 02267 DeriveBinderKeyResume(ssl, binderKey); 02268 } 02269 else { 02270 /* PSK age is always zero. */ 02271 if (current->ticketAge != ssl->session.ticketAdd) 02272 return PSK_KEY_ERROR; 02273 02274 /* Get the pre-shared key. */ 02275 ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl, 02276 (char*)current->identity, ssl->arrays->client_identity, 02277 MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN); 02278 /* Derive the early secret using the PSK. */ 02279 DeriveEarlySecret(ssl); 02280 /* Derive the binder key to use to with HMAC. */ 02281 DeriveBinderKey(ssl, binderKey); 02282 } 02283 02284 /* Derive the Finished message secret. */ 02285 DeriveFinishedSecret(ssl, binderKey, ssl->keys.client_write_MAC_secret); 02286 /* Derive the binder and compare with the one in the extension. */ 02287 binderLen = BuildTls13HandshakeHmac(ssl, 02288 ssl->keys.client_write_MAC_secret, binder); 02289 if (binderLen != current->binderLen || 02290 XMEMCMP(binder, current->binder, binderLen) != 0) { 02291 return BAD_BINDER; 02292 } 02293 02294 /* This PSK works, no need to try any more. */ 02295 current->chosen = 1; 02296 ext->resp = 1; 02297 break; 02298 } 02299 02300 /* Hash the rest of the ClientHello. */ 02301 ret = HashInputRaw(ssl, input + helloSz - bindersLen, bindersLen); 02302 if (ret != 0) 02303 return ret; 02304 02305 /* Get the PSK key exchange modes the client wants to negotiate. */ 02306 ext = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES); 02307 if (ext == NULL) 02308 return MISSING_HANDSHAKE_DATA; 02309 modes = ext->val; 02310 02311 ext = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE); 02312 /* Use (EC)DHE for forward-security if possible. */ 02313 if (ext != NULL && (modes & (1 << PSK_DHE_KE)) != 0 && 02314 !ssl->options.noPskDheKe) { 02315 /* Only use named group used in last session. */ 02316 ssl->namedGroup = ssl->session.namedGroup; 02317 02318 /* Try to establish a new secret. */ 02319 ret = TLSX_KeyShare_Establish(ssl); 02320 if (ret == KEY_SHARE_ERROR) 02321 return PSK_KEY_ERROR; 02322 else if (ret > 0) 02323 ret = 0; 02324 02325 /* Send new public key to client. */ 02326 ext->resp = 1; 02327 } 02328 else if ((modes & (1 << PSK_KE)) != 0) { 02329 /* Don't send a key share extension back. */ 02330 if (ext != NULL) 02331 ext->resp = 0; 02332 } 02333 else 02334 return PSK_KEY_ERROR; 02335 02336 *usingPSK = 1; 02337 02338 return ret; 02339 } 02340 #endif 02341 02342 /* Handle a ClientHello handshake message. 02343 * If the protocol version in the message is not TLS v1.3 or higher, use 02344 * DoClientHello() 02345 * Only a server will receive this message. 02346 * 02347 * ssl The SSL/TLS object. 02348 * input The message buffer. 02349 * inOutIdx On entry, the index into the message buffer of ClientHello. 02350 * On exit, the index of byte after the ClientHello message and 02351 * padding. 02352 * helloSz The length of the current handshake message. 02353 * returns 0 on success and otherwise failure. 02354 */ 02355 static int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx, 02356 word32 helloSz) 02357 { 02358 int ret; 02359 byte b; 02360 ProtocolVersion pv; 02361 Suites clSuites; 02362 word32 i = *inOutIdx; 02363 word32 begin = i; 02364 word16 totalExtSz; 02365 int usingPSK = 0; 02366 02367 #ifdef WOLFSSL_CALLBACKS 02368 if (ssl->hsInfoOn) AddPacketName("ClientHello", &ssl->handShakeInfo); 02369 if (ssl->toInfoOn) AddLateName("ClientHello", &ssl->timeoutInfo); 02370 #endif 02371 02372 /* protocol version, random and session id length check */ 02373 if ((i - begin) + OPAQUE16_LEN + RAN_LEN + OPAQUE8_LEN > helloSz) 02374 return BUFFER_ERROR; 02375 02376 /* Protocol version */ 02377 XMEMCPY(&pv, input + i, OPAQUE16_LEN); 02378 ssl->chVersion = pv; /* store */ 02379 i += OPAQUE16_LEN; 02380 02381 if ((ssl->version.major == SSLv3_MAJOR && 02382 ssl->version.minor < TLSv1_3_MINOR) || ssl->options.dtls) { 02383 return DoClientHello(ssl, input, inOutIdx, helloSz); 02384 } 02385 02386 /* Client random */ 02387 XMEMCPY(ssl->arrays->clientRandom, input + i, RAN_LEN); 02388 i += RAN_LEN; 02389 02390 #ifdef WOLFSSL_DEBUG_TLS 02391 WOLFSSL_MSG("client random"); 02392 WOLFSSL_BUFFER(ssl->arrays->clientRandom, RAN_LEN); 02393 #endif 02394 02395 02396 /* Session id - empty in TLS v1.3 */ 02397 b = input[i++]; 02398 if (b != 0) { 02399 WOLFSSL_MSG("Client sent session id - not supported"); 02400 return BUFFER_ERROR; 02401 } 02402 02403 /* Cipher suites */ 02404 if ((i - begin) + OPAQUE16_LEN > helloSz) 02405 return BUFFER_ERROR; 02406 ato16(&input[i], &clSuites.suiteSz); 02407 i += OPAQUE16_LEN; 02408 /* suites and compression length check */ 02409 if ((i - begin) + clSuites.suiteSz + OPAQUE8_LEN > helloSz) 02410 return BUFFER_ERROR; 02411 if (clSuites.suiteSz > WOLFSSL_MAX_SUITE_SZ) 02412 return BUFFER_ERROR; 02413 XMEMCPY(clSuites.suites, input + i, clSuites.suiteSz); 02414 i += clSuites.suiteSz; 02415 clSuites.hashSigAlgoSz = 0; 02416 02417 /* Compression */ 02418 b = input[i++]; 02419 if ((i - begin) + b > helloSz) 02420 return BUFFER_ERROR; 02421 if (b != COMP_LEN) { 02422 WOLFSSL_MSG("Must be one compression type in list"); 02423 return INVALID_PARAMETER; 02424 } 02425 b = input[i++]; 02426 if (b != NO_COMPRESSION) { 02427 WOLFSSL_MSG("Must be no compression type in list"); 02428 return INVALID_PARAMETER; 02429 } 02430 02431 /* TLS v1.3 ClientHello messages will have extensions. */ 02432 if ((i - begin) >= helloSz) { 02433 WOLFSSL_MSG("ClientHello must have extensions in TLS v1.3"); 02434 return BUFFER_ERROR; 02435 } 02436 if ((i - begin) + OPAQUE16_LEN > helloSz) 02437 return BUFFER_ERROR; 02438 ato16(&input[i], &totalExtSz); 02439 i += OPAQUE16_LEN; 02440 if ((i - begin) + totalExtSz > helloSz) 02441 return BUFFER_ERROR; 02442 02443 #ifdef HAVE_QSH 02444 QSH_Init(ssl); 02445 #endif 02446 02447 /* Auto populate extensions supported unless user defined. */ 02448 if ((ret = TLSX_PopulateExtensions(ssl, 1)) != 0) 02449 return ret; 02450 02451 /* Parse extensions */ 02452 if ((ret = TLSX_Parse(ssl, (byte*)input + i, totalExtSz, client_hello, 02453 &clSuites))) { 02454 return ret; 02455 } 02456 02457 #ifdef HAVE_STUNNEL 02458 if ((ret = SNI_Callback(ssl)) != 0) 02459 return ret; 02460 #endif /*HAVE_STUNNEL*/ 02461 02462 if (TLSX_Find(ssl->extensions, TLSX_SUPPORTED_VERSIONS) == NULL) 02463 ssl->version.minor = pv.minor; 02464 02465 #if defined(HAVE_SESSION_TICKET) && !defined(NO_PSK) 02466 /* Process the Pre-Shared Key extension if present. */ 02467 ret = DoPreSharedKeys(ssl, input + begin, helloSz, &usingPSK); 02468 if (ret != 0) 02469 return ret; 02470 #endif 02471 02472 if (!usingPSK) { 02473 ret = MatchSuite(ssl, &clSuites); 02474 if (ret < 0) { 02475 WOLFSSL_MSG("Unsupported cipher suite, ClientHello"); 02476 return ret; 02477 } 02478 02479 #ifndef NO_PSK 02480 if (ssl->options.resuming) { 02481 ssl->options.resuming = 0; 02482 XMEMSET(ssl->arrays->psk_key, 0, ssl->specs.hash_size); 02483 /* May or may not have done any hashing. */ 02484 ret = InitHandshakeHashes(ssl); 02485 if (ret != 0) 02486 return ret; 02487 } 02488 #endif 02489 02490 ret = HashInput(ssl, input + begin, helloSz); 02491 if (ret != 0) 02492 return ret; 02493 } 02494 02495 i += totalExtSz; 02496 *inOutIdx = i; 02497 02498 ssl->options.clientState = CLIENT_HELLO_COMPLETE; 02499 02500 return 0; 02501 } 02502 02503 /* Send the HelloRetryRequest message to indicate the negotiated protocol 02504 * version and security parameters the server is willing to use. 02505 * Only a server will send this message. 02506 * 02507 * ssl The SSL/TLS object. 02508 * returns 0 on success, otherwise failure. 02509 */ 02510 int SendTls13HelloRetryRequest(WOLFSSL *ssl) 02511 { 02512 int ret; 02513 byte* output; 02514 word32 length; 02515 word32 len; 02516 word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ; 02517 int sendSz; 02518 02519 /* Get the length of the extensions that will be written. */ 02520 len = TLSX_GetResponseSize(ssl, hello_retry_request); 02521 /* There must be extensions sent to indicate what client needs to do. */ 02522 if (len == 0) 02523 return MISSING_HANDSHAKE_DATA; 02524 02525 /* Protocol version + Extensions */ 02526 length = OPAQUE16_LEN + len; 02527 sendSz = idx + length; 02528 02529 /* Check buffers are big enough and grow if needed. */ 02530 ret = CheckAvailableSize(ssl, sendSz); 02531 if (ret != 0) 02532 return ret; 02533 02534 /* Get position in output buffer to write new message to. */ 02535 output = ssl->buffers.outputBuffer.buffer + 02536 ssl->buffers.outputBuffer.length; 02537 /* Add record and hanshake headers. */ 02538 AddTls13Headers(output, length, hello_retry_request, ssl); 02539 02540 /* TODO: [TLS13] Replace existing code with code in comment. 02541 * Use the TLS v1.3 draft version for now. 02542 * 02543 * Change to: 02544 * output[idx++] = ssl->version.major; 02545 * output[idx++] = ssl->version.minor; 02546 */ 02547 /* The negotiated protocol version. */ 02548 output[idx++] = TLS_DRAFT_MAJOR; 02549 output[idx++] = TLS_DRAFT_MINOR; 02550 02551 /* Add TLS extensions. */ 02552 TLSX_WriteResponse(ssl, output + idx, hello_retry_request); 02553 idx += len; 02554 02555 #ifdef WOLFSSL_CALLBACKS 02556 if (ssl->hsInfoOn) 02557 AddPacketName("HelloRetryRequest", &ssl->handShakeInfo); 02558 if (ssl->toInfoOn) 02559 AddPacketInfo("HelloRetryRequest", &ssl->timeoutInfo, output, sendSz, 02560 ssl->heap); 02561 #endif 02562 02563 ret = HashOutput(ssl, output, idx, 0); 02564 if (ret != 0) 02565 return ret; 02566 02567 ssl->buffers.outputBuffer.length += sendSz; 02568 02569 if (ssl->options.groupMessages) 02570 return 0; 02571 else 02572 return SendBuffered(ssl); 02573 } 02574 02575 /* Send TLS v1.3 ServerHello message to client. 02576 * Only a server will send this message. 02577 * 02578 * ssl The SSL/TLS object. 02579 * returns 0 on success, otherwise failure. 02580 */ 02581 int SendTls13ServerHello(WOLFSSL* ssl) 02582 { 02583 byte* output; 02584 word32 length; 02585 word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ; 02586 int sendSz; 02587 int ret; 02588 02589 /* Protocol version, server random, cipher suite and extensions. */ 02590 length = VERSION_SZ + RAN_LEN + SUITE_LEN + 02591 TLSX_GetResponseSize(ssl, server_hello); 02592 sendSz = idx + length; 02593 02594 /* Check buffers are big enough and grow if needed. */ 02595 if ((ret = CheckAvailableSize(ssl, sendSz)) != 0) 02596 return ret; 02597 02598 /* Get position in output buffer to write new message to. */ 02599 output = ssl->buffers.outputBuffer.buffer + 02600 ssl->buffers.outputBuffer.length; 02601 02602 /* Put the record and handshake headers on. */ 02603 AddTls13Headers(output, length, server_hello, ssl); 02604 02605 /* TODO: [TLS13] Replace existing code with code in comment. 02606 * Use the TLS v1.3 draft version for now. 02607 * 02608 * Change to: 02609 * output[idx++] = ssl->version.major; 02610 * output[idx++] = ssl->version.minor; 02611 */ 02612 /* The negotiated protocol version. */ 02613 output[idx++] = TLS_DRAFT_MAJOR; 02614 output[idx++] = TLS_DRAFT_MINOR; 02615 02616 /* TODO: [TLS13] Last 8 bytes have special meaning. */ 02617 /* Generate server random. */ 02618 ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, RAN_LEN); 02619 if (ret != 0) 02620 return ret; 02621 /* Store in SSL for debugging. */ 02622 XMEMCPY(ssl->arrays->serverRandom, output + idx, RAN_LEN); 02623 idx += RAN_LEN; 02624 02625 #ifdef WOLFSSL_DEBUG_TLS 02626 WOLFSSL_MSG("Server random"); 02627 WOLFSSL_BUFFER(ssl->arrays->serverRandom, RAN_LEN); 02628 #endif 02629 02630 /* Chosen cipher suite */ 02631 output[idx++] = ssl->options.cipherSuite0; 02632 output[idx++] = ssl->options.cipherSuite; 02633 02634 /* Extensions */ 02635 TLSX_WriteResponse(ssl, output + idx, server_hello); 02636 02637 ssl->buffers.outputBuffer.length += sendSz; 02638 02639 ret = HashOutput(ssl, output, sendSz, 0); 02640 if (ret != 0) 02641 return ret; 02642 02643 #ifdef WOLFSSL_CALLBACKS 02644 if (ssl->hsInfoOn) 02645 AddPacketName("ServerHello", &ssl->handShakeInfo); 02646 if (ssl->toInfoOn) 02647 AddPacketInfo("ServerHello", &ssl->timeoutInfo, output, sendSz, 02648 ssl->heap); 02649 #endif 02650 02651 ssl->options.serverState = SERVER_HELLO_COMPLETE; 02652 02653 if (ssl->options.groupMessages) 02654 return 0; 02655 else 02656 return SendBuffered(ssl); 02657 } 02658 02659 /* Send the rest of the extensions encrypted under the handshake key. 02660 * This message is always encrypted in TLS v1.3. 02661 * Only a server will send this message. 02662 * 02663 * ssl The SSL/TLS object. 02664 * returns 0 on success, otherwise failure. 02665 */ 02666 int SendTls13EncryptedExtensions(WOLFSSL *ssl) 02667 { 02668 int ret; 02669 byte* output; 02670 word32 length; 02671 word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ; 02672 int sendSz; 02673 02674 ssl->keys.encryptionOn = 1; 02675 02676 /* Derive early secret for handshake secret. */ 02677 if ((ret = DeriveEarlySecret(ssl)) != 0) 02678 return ret; 02679 /* Derive the handshake secret now that we are at first message to be 02680 * encrypted under the keys. 02681 */ 02682 if ((ret = DeriveHandshakeSecret(ssl)) != 0) 02683 return ret; 02684 if ((ret = DeriveTls13Keys(ssl, handshake_key, 02685 ENCRYPT_AND_DECRYPT_SIDE)) != 0) 02686 return ret; 02687 02688 /* Setup encrypt/decrypt keys for following messages. */ 02689 if ((ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE)) != 0) 02690 return ret; 02691 02692 length = TLSX_GetResponseSize(ssl, encrypted_extensions); 02693 sendSz = idx + length; 02694 /* Encryption always on. */ 02695 sendSz += MAX_MSG_EXTRA; 02696 02697 /* Check buffers are big enough and grow if needed. */ 02698 ret = CheckAvailableSize(ssl, sendSz); 02699 if (ret != 0) 02700 return ret; 02701 02702 /* Get position in output buffer to write new message to. */ 02703 output = ssl->buffers.outputBuffer.buffer + 02704 ssl->buffers.outputBuffer.length; 02705 02706 /* Put the record and handshake headers on. */ 02707 AddTls13Headers(output, length, encrypted_extensions, ssl); 02708 02709 TLSX_WriteResponse(ssl, output + idx, encrypted_extensions); 02710 idx += length; 02711 02712 #ifdef WOLFSSL_CALLBACKS 02713 if (ssl->hsInfoOn) 02714 AddPacketName("EncryptedExtensions", &ssl->handShakeInfo); 02715 if (ssl->toInfoOn) 02716 AddPacketInfo("EncryptedExtensions", &ssl->timeoutInfo, output, 02717 sendSz, ssl->heap); 02718 #endif 02719 02720 /* This handshake message is always encrypted. */ 02721 sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ, 02722 idx - RECORD_HEADER_SZ, handshake, 1, 0); 02723 if (sendSz < 0) 02724 return sendSz; 02725 02726 ssl->buffers.outputBuffer.length += sendSz; 02727 02728 ssl->options.serverState = SERVER_ENCRYPTED_EXTENSIONS_COMPLETE; 02729 02730 if (ssl->options.groupMessages) 02731 return 0; 02732 else 02733 return SendBuffered(ssl); 02734 } 02735 02736 #ifndef NO_CERTS 02737 /* Send the TLS v1.3 CertificateRequest message. 02738 * This message is always encrypted in TLS v1.3. 02739 * Only a server will send this message. 02740 * 02741 * ssl The SSL/TLS object. 02742 * returns 0 on success, otherwise failure. 02743 */ 02744 int SendTls13CertificateRequest(WOLFSSL* ssl) 02745 { 02746 byte *output; 02747 int ret; 02748 int sendSz; 02749 int reqCtxLen = 0; 02750 word32 i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ; 02751 02752 int reqSz = OPAQUE8_LEN + reqCtxLen + REQ_HEADER_SZ + REQ_HEADER_SZ; 02753 02754 reqSz += LENGTH_SZ + ssl->suites->hashSigAlgoSz; 02755 02756 if (ssl->options.usingPSK_cipher || ssl->options.usingAnon_cipher) 02757 return 0; /* not needed */ 02758 02759 sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ + reqSz; 02760 /* Always encrypted and make room for padding. */ 02761 sendSz += MAX_MSG_EXTRA; 02762 02763 /* Check buffers are big enough and grow if needed. */ 02764 if ((ret = CheckAvailableSize(ssl, sendSz)) != 0) 02765 return ret; 02766 02767 /* Get position in output buffer to write new message to. */ 02768 output = ssl->buffers.outputBuffer.buffer + 02769 ssl->buffers.outputBuffer.length; 02770 02771 /* Put the record and handshake headers on. */ 02772 AddTls13Headers(output, reqSz, certificate_request, ssl); 02773 02774 /* Certificate request context. */ 02775 /* TODO: [TLS13] Request context for post-handshake auth. 02776 * Must be unique in the scope of the connection. 02777 */ 02778 output[i++] = reqCtxLen; 02779 02780 /* supported hash/sig */ 02781 c16toa(ssl->suites->hashSigAlgoSz, &output[i]); 02782 i += LENGTH_SZ; 02783 02784 XMEMCPY(&output[i], ssl->suites->hashSigAlgo, ssl->suites->hashSigAlgoSz); 02785 i += ssl->suites->hashSigAlgoSz; 02786 02787 /* Certificate authorities not supported yet - empty buffer. */ 02788 c16toa(0, &output[i]); 02789 i += REQ_HEADER_SZ; 02790 02791 /* Certificate extensions. */ 02792 /* TODO: [TLS13] Add extension handling. */ 02793 c16toa(0, &output[i]); /* auth's */ 02794 i += REQ_HEADER_SZ; 02795 02796 /* Always encrypted. */ 02797 sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ, 02798 i - RECORD_HEADER_SZ, handshake, 1, 0); 02799 if (sendSz < 0) 02800 return sendSz; 02801 02802 #ifdef WOLFSSL_CALLBACKS 02803 if (ssl->hsInfoOn) 02804 AddPacketName("CertificateRequest", &ssl->handShakeInfo); 02805 if (ssl->toInfoOn) 02806 AddPacketInfo("CertificateRequest", &ssl->timeoutInfo, output, 02807 sendSz, ssl->heap); 02808 #endif 02809 02810 ssl->buffers.outputBuffer.length += sendSz; 02811 if (!ssl->options.groupMessages) 02812 return SendBuffered(ssl); 02813 return 0; 02814 } 02815 #endif /* NO_CERTS */ 02816 #endif /* NO_WOLFSSL_SERVER */ 02817 02818 #ifndef NO_CERTS 02819 #if !defined(NO_RSA) || defined(HAVE_ECC) 02820 /* Encode the signature algorithm into buffer. 02821 * 02822 * hashalgo The hash algorithm. 02823 * hsType The signature type. 02824 * output The buffer to encode into. 02825 */ 02826 static INLINE void EncodeSigAlg(byte hashAlgo, byte hsType, byte* output) 02827 { 02828 switch (hsType) { 02829 #ifdef HAVE_ECC 02830 case DYNAMIC_TYPE_ECC: 02831 output[0] = hashAlgo; 02832 output[1] = ecc_dsa_sa_algo; 02833 break; 02834 #endif 02835 #ifndef NO_RSA 02836 case DYNAMIC_TYPE_RSA: 02837 output[0] = hashAlgo; 02838 output[1] = rsa_sa_algo; 02839 break; 02840 #endif 02841 /* PSS signatures: 0x080[4-6] */ 02842 /* ED25519: 0x0807 */ 02843 /* ED448: 0x0808 */ 02844 } 02845 } 02846 02847 /* Decode the signature algorithm. 02848 * 02849 * input The encoded signature algorithm. 02850 * hashalgo The hash algorithm. 02851 * hsType The signature type. 02852 */ 02853 static INLINE void DecodeSigAlg(byte* input, byte* hashAlgo, byte* hsType) 02854 { 02855 switch (input[0]) { 02856 case 0x08: 02857 /* PSS signatures: 0x080[4-6] */ 02858 if (input[1] <= 0x06) { 02859 *hsType = input[0]; 02860 *hashAlgo = input[1]; 02861 } 02862 break; 02863 /* ED25519: 0x0807 */ 02864 /* ED448: 0x0808 */ 02865 default: 02866 *hashAlgo = input[0]; 02867 *hsType = input[1]; 02868 break; 02869 } 02870 } 02871 02872 /* Get the hash of the messages so far. 02873 * 02874 * ssl The SSL/TLS object. 02875 * hash The buffer to write the hash to. 02876 * returns the length of the hash. 02877 */ 02878 static INLINE int GetMsgHash(WOLFSSL *ssl, byte* hash) 02879 { 02880 switch (ssl->specs.mac_algorithm) { 02881 #ifndef NO_SHA256 02882 case sha256_mac: 02883 wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash); 02884 return SHA256_DIGEST_SIZE; 02885 #endif /* !NO_SHA256 */ 02886 #ifdef WOLFSSL_SHA384 02887 case sha384_mac: 02888 wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash); 02889 return SHA384_DIGEST_SIZE; 02890 #endif /* WOLFSSL_SHA384 */ 02891 #ifdef WOLFSSL_SHA512 02892 case sha512_mac: 02893 wc_Sha512GetHash(&ssl->hsHashes->hashSha512, hash); 02894 return SHA512_DIGEST_SIZE; 02895 #endif /* WOLFSSL_SHA512 */ 02896 } 02897 return 0; 02898 } 02899 02900 /* The length of the certificate verification label - client and server. */ 02901 #define CERT_VFY_LABEL_SZ 34 02902 /* The server certificate verification label. */ 02903 static const byte serverCertVfyLabel[CERT_VFY_LABEL_SZ] = 02904 "TLS 1.3, server CertificateVerify"; 02905 /* The client certificate verification label. */ 02906 static const byte clientCertVfyLabel[CERT_VFY_LABEL_SZ] = 02907 "TLS 1.3, client CertificateVerify"; 02908 02909 /* The number of prefix bytes for signature data. */ 02910 #define SIGNING_DATA_PREFIX_SZ 64 02911 /* The prefix byte in the signature data. */ 02912 #define SIGNING_DATA_PREFIX_BYTE 0x20 02913 /* Maximum length of the signature data. */ 02914 #define MAX_SIG_DATA_SZ (SIGNING_DATA_PREFIX_SZ + \ 02915 CERT_VFY_LABEL_SZ + \ 02916 MAX_DIGEST_SIZE) 02917 02918 /* Create the signature data for TLS v1.3 certificate verification. 02919 * 02920 * ssl The SSL/TLS object. 02921 * sigData The signature data. 02922 * sigDataSz The length of the signature data. 02923 * check Indicates this is a check not create. 02924 */ 02925 static void CreateSigData(WOLFSSL* ssl, byte* sigData, word16* sigDataSz, 02926 int check) 02927 { 02928 word16 idx; 02929 int side = ssl->options.side; 02930 02931 /* Signature Data = Prefix | Label | Handshake Hash */ 02932 XMEMSET(sigData, SIGNING_DATA_PREFIX_BYTE, SIGNING_DATA_PREFIX_SZ); 02933 idx = SIGNING_DATA_PREFIX_SZ; 02934 02935 #ifndef NO_WOLFSSL_SERVER 02936 if ((side == WOLFSSL_SERVER_END && check) || 02937 (side == WOLFSSL_CLIENT_END && !check)) { 02938 XMEMCPY(&sigData[idx], clientCertVfyLabel, CERT_VFY_LABEL_SZ); 02939 } 02940 #endif 02941 #ifndef NO_WOLFSSL_CLIENT 02942 if ((side == WOLFSSL_CLIENT_END && check) || 02943 (side == WOLFSSL_SERVER_END && !check)) { 02944 XMEMCPY(&sigData[idx], serverCertVfyLabel, CERT_VFY_LABEL_SZ); 02945 } 02946 #endif 02947 idx += CERT_VFY_LABEL_SZ; 02948 02949 *sigDataSz = idx + GetMsgHash(ssl, &sigData[idx]); 02950 } 02951 02952 #ifndef NO_RSA 02953 /* Encode the PKCS #1.5 RSA signature. 02954 * 02955 * sig The buffer to place the encoded signature into. 02956 * sigData The data to be signed. 02957 * sigDataSz The size of the data to be signed. 02958 * hashAlgo The hash algorithm to use when signing. 02959 * returns the length of the encoded signature or negative on error. 02960 */ 02961 static int CreateRSAEncodedSig(byte* sig, byte* sigData, int sigDataSz, 02962 int hashAlgo) 02963 { 02964 Digest digest; 02965 int hashSz = 0; 02966 int hashOid = 0; 02967 02968 /* Digest the signature data. */ 02969 switch (hashAlgo) { 02970 #ifndef NO_WOLFSSL_SHA256 02971 case sha256_mac: 02972 wc_InitSha256(&digest.sha256); 02973 wc_Sha256Update(&digest.sha256, sigData, sigDataSz); 02974 wc_Sha256Final(&digest.sha256, sigData); 02975 wc_Sha256Free(&digest.sha256); 02976 hashSz = SHA256_DIGEST_SIZE; 02977 hashOid = SHA256h; 02978 break; 02979 #endif 02980 #ifdef WOLFSSL_SHA384 02981 case sha384_mac: 02982 wc_InitSha384(&digest.sha384); 02983 wc_Sha384Update(&digest.sha384, sigData, sigDataSz); 02984 wc_Sha384Final(&digest.sha384, sigData); 02985 wc_Sha384Free(&digest.sha384); 02986 hashSz = SHA384_DIGEST_SIZE; 02987 hashOid = SHA384h; 02988 break; 02989 #endif 02990 #ifdef WOLFSSL_SHA512 02991 case sha512_mac: 02992 wc_InitSha512(&digest.sha512); 02993 wc_Sha512Update(&digest.sha512, sigData, sigDataSz); 02994 wc_Sha512Final(&digest.sha512, sigData); 02995 wc_Sha512Free(&digest.sha512); 02996 hashSz = SHA512_DIGEST_SIZE; 02997 hashOid = SHA512h; 02998 break; 02999 #endif 03000 } 03001 03002 /* Encode the signature data as per PKCS #1.5 */ 03003 return wc_EncodeSignature(sig, sigData, hashSz, hashOid); 03004 } 03005 03006 #ifdef HAVE_ECC 03007 /* Encode the ECC signature. 03008 * 03009 * sigData The data to be signed. 03010 * sigDataSz The size of the data to be signed. 03011 * hashAlgo The hash algorithm to use when signing. 03012 * returns the length of the encoded signature or negative on error. 03013 */ 03014 static int CreateECCEncodedSig(byte* sigData, int sigDataSz, int hashAlgo) 03015 { 03016 Digest digest; 03017 int hashSz = 0; 03018 03019 /* Digest the signature data. */ 03020 switch (hashAlgo) { 03021 #ifndef NO_WOLFSSL_SHA256 03022 case sha256_mac: 03023 wc_InitSha256(&digest.sha256); 03024 wc_Sha256Update(&digest.sha256, sigData, sigDataSz); 03025 wc_Sha256Final(&digest.sha256, sigData); 03026 wc_Sha256Free(&digest.sha256); 03027 hashSz = SHA256_DIGEST_SIZE; 03028 break; 03029 #endif 03030 #ifdef WOLFSSL_SHA384 03031 case sha384_mac: 03032 wc_InitSha384(&digest.sha384); 03033 wc_Sha384Update(&digest.sha384, sigData, sigDataSz); 03034 wc_Sha384Final(&digest.sha384, sigData); 03035 wc_Sha384Free(&digest.sha384); 03036 hashSz = SHA384_DIGEST_SIZE; 03037 break; 03038 #endif 03039 #ifdef WOLFSSL_SHA512 03040 case sha512_mac: 03041 wc_InitSha512(&digest.sha512); 03042 wc_Sha512Update(&digest.sha512, sigData, sigDataSz); 03043 wc_Sha512Final(&digest.sha512, sigData); 03044 wc_Sha512Free(&digest.sha512); 03045 hashSz = SHA512_DIGEST_SIZE; 03046 break; 03047 #endif 03048 } 03049 03050 return hashSz; 03051 } 03052 #endif 03053 03054 03055 /* Check that the decrypted signature matches the encoded signature 03056 * based on the digest of the signature data. 03057 * 03058 * ssl The SSL/TLS object. 03059 * hashAlgo The signature algorithm used to generate signature. 03060 * hashAlgo The hash algorithm used to generate signature. 03061 * decSig The decrypted signature. 03062 * decSigSz The size of the decrypted signature. 03063 * returns 0 on success, otherwise failure. 03064 */ 03065 static int CheckRSASignature(WOLFSSL* ssl, int sigAlgo, int hashAlgo, 03066 byte* decSig, word32 decSigSz) 03067 { 03068 int ret = 0; 03069 byte sigData[MAX_SIG_DATA_SZ]; 03070 word16 sigDataSz; 03071 #ifdef WOLFSSL_SMALL_STACK 03072 byte* encodedSig = NULL; 03073 #else 03074 byte encodedSig[MAX_ENCODED_SIG_SZ]; 03075 #endif 03076 word32 sigSz; 03077 03078 if (sigAlgo == rsa_sa_algo) { 03079 #ifdef WOLFSSL_SMALL_STACK 03080 encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, ssl->heap, 03081 DYNAMIC_TYPE_TMP_BUFFER); 03082 if (encodedSig == NULL) { 03083 ret = MEMORY_E; 03084 goto end; 03085 } 03086 #endif 03087 03088 CreateSigData(ssl, sigData, &sigDataSz, 1); 03089 sigSz = CreateRSAEncodedSig(encodedSig, sigData, sigDataSz, hashAlgo); 03090 /* Check the encoded and decrypted signature data match. */ 03091 if (decSigSz != sigSz || decSig == NULL || 03092 XMEMCMP(decSig, encodedSig, sigSz) != 0) { 03093 ret = VERIFY_CERT_ERROR; 03094 } 03095 } 03096 else { 03097 CreateSigData(ssl, sigData, &sigDataSz, 1); 03098 sigSz = CreateECCEncodedSig(sigData, sigDataSz, hashAlgo); 03099 if (decSigSz != sigSz || decSig == NULL) 03100 ret = VERIFY_CERT_ERROR; 03101 else { 03102 decSig -= 2 * decSigSz; 03103 XMEMCPY(decSig, sigData, decSigSz); 03104 decSig -= 8; 03105 XMEMSET(decSig, 0, 8); 03106 CreateECCEncodedSig(decSig, 8 + decSigSz * 2, hashAlgo); 03107 if (XMEMCMP(decSig, decSig + 8 + decSigSz * 2, decSigSz) != 0) 03108 ret = VERIFY_CERT_ERROR; 03109 } 03110 } 03111 03112 #ifdef WOLFSSL_SMALL_STACK 03113 end: 03114 if (encodedSig != NULL) 03115 XFREE(encodedSig, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); 03116 #endif 03117 03118 return ret; 03119 } 03120 #endif /* !NO_RSA */ 03121 #endif /* !NO_RSA || HAVE_ECC */ 03122 03123 /* Get the next certificate from the list for writing into the TLS v1.3 03124 * Certificate message. 03125 * 03126 * data The certificate list. 03127 * length The length of the certificate data in the list. 03128 * idx The index of the next certificate. 03129 * returns the length of the certificate data. 0 indicates no more certificates 03130 * in the list. 03131 */ 03132 static word32 NextCert(byte* data, word32 length, word32* idx) 03133 { 03134 word32 len; 03135 03136 /* Is index at end of list. */ 03137 if (*idx == length) 03138 return 0; 03139 03140 /* Length of the current ASN.1 encoded certificate. */ 03141 c24to32(data + *idx, &len); 03142 /* Include the length field. */ 03143 len += 3; 03144 03145 /* Move index to next certificate and return the current certificate's 03146 * length. 03147 */ 03148 *idx += len; 03149 return len; 03150 } 03151 03152 /* Add certificate data and empty extension to output up to the fragment size. 03153 * 03154 * cert The certificate data to write out. 03155 * len The length of the certificate data. 03156 * idx The start of the certificate data to write out. 03157 * fragSz The maximum size of this fragment. 03158 * output The buffer to write to. 03159 * returns the number of bytes written. 03160 */ 03161 static word32 AddCertExt(byte* cert, word32 len, word32 idx, word32 fragSz, 03162 byte* output) 03163 { 03164 word32 i = 0; 03165 word32 copySz = min(len - idx, fragSz); 03166 03167 if (idx < len) { 03168 XMEMCPY(output, cert + idx, copySz); 03169 i = copySz; 03170 } 03171 03172 if (copySz + OPAQUE16_LEN <= fragSz) { 03173 /* Empty extension */ 03174 output[i++] = 0; 03175 output[i++] = 0; 03176 } 03177 03178 return i; 03179 } 03180 03181 /* Send the certificate for this end and any CAs that help with validation. 03182 * This message is always encrypted in TLS v1.3. 03183 * 03184 * ssl The SSL/TLS object. 03185 * returns 0 on success, otherwise failure. 03186 */ 03187 int SendTls13Certificate(WOLFSSL* ssl) 03188 { 03189 int ret = 0; 03190 word32 certSz, certChainSz, headerSz, listSz, payloadSz; 03191 word32 length, maxFragment; 03192 word32 len = 0; 03193 word32 idx = 0; 03194 word32 offset = OPAQUE16_LEN; 03195 byte* p = NULL; 03196 03197 03198 /* TODO: [TLS13] Request context for post-handshake auth. 03199 * Taken from request if post-handshake. 03200 */ 03201 03202 if (ssl->options.sendVerify == SEND_BLANK_CERT) { 03203 certSz = 0; 03204 certChainSz = 0; 03205 headerSz = CERT_HEADER_SZ; 03206 length = CERT_HEADER_SZ; 03207 listSz = 0; 03208 } 03209 else { 03210 if (!ssl->buffers.certificate) { 03211 WOLFSSL_MSG("Send Cert missing certificate buffer"); 03212 return BUFFER_ERROR; 03213 } 03214 /* Certificate Data */ 03215 certSz = ssl->buffers.certificate->length; 03216 /* Cert Req Ctx Len | Cert List Len | Cert Data Len */ 03217 headerSz = OPAQUE8_LEN + CERT_HEADER_SZ + CERT_HEADER_SZ; 03218 /* Length of message data with one certificate and empty extensions. */ 03219 length = headerSz + certSz + OPAQUE16_LEN; 03220 /* Length of list data with one certificate and empty extensions. */ 03221 listSz = CERT_HEADER_SZ + certSz + OPAQUE16_LEN; 03222 03223 /* Send rest of chain if sending cert (chain has leading size/s). */ 03224 if (certSz > 0 && ssl->buffers.certChainCnt > 0) { 03225 /* The pointer to the current spot in the cert chain buffer. */ 03226 p = ssl->buffers.certChain->buffer; 03227 /* Chain length including extensions. */ 03228 certChainSz = ssl->buffers.certChain->length + 03229 OPAQUE16_LEN * ssl->buffers.certChainCnt; 03230 length += certChainSz; 03231 listSz += certChainSz; 03232 } 03233 else 03234 certChainSz = 0; 03235 } 03236 03237 payloadSz = length; 03238 03239 if (ssl->fragOffset != 0) 03240 length -= (ssl->fragOffset + headerSz); 03241 03242 maxFragment = MAX_RECORD_SIZE; 03243 03244 #ifdef HAVE_MAX_FRAGMENT 03245 if (ssl->max_fragment != 0 && maxFragment >= ssl->max_fragment) 03246 maxFragment = ssl->max_fragment; 03247 #endif /* HAVE_MAX_FRAGMENT */ 03248 03249 while (length > 0 && ret == 0) { 03250 byte* output = NULL; 03251 word32 fragSz = 0; 03252 word32 i = RECORD_HEADER_SZ; 03253 int sendSz = RECORD_HEADER_SZ; 03254 03255 if (ssl->fragOffset == 0) { 03256 if (headerSz + certSz + OPAQUE16_LEN + certChainSz <= 03257 maxFragment - HANDSHAKE_HEADER_SZ) { 03258 03259 fragSz = headerSz + certSz + OPAQUE16_LEN + certChainSz; 03260 } 03261 else { 03262 fragSz = maxFragment - HANDSHAKE_HEADER_SZ; 03263 } 03264 sendSz += fragSz + HANDSHAKE_HEADER_SZ; 03265 i += HANDSHAKE_HEADER_SZ; 03266 } 03267 else { 03268 fragSz = min(length, maxFragment); 03269 sendSz += fragSz; 03270 } 03271 03272 sendSz += MAX_MSG_EXTRA; 03273 03274 /* Check buffers are big enough and grow if needed. */ 03275 if ((ret = CheckAvailableSize(ssl, sendSz)) != 0) 03276 return ret; 03277 03278 /* Get position in output buffer to write new message to. */ 03279 output = ssl->buffers.outputBuffer.buffer + 03280 ssl->buffers.outputBuffer.length; 03281 03282 if (ssl->fragOffset == 0) { 03283 AddTls13FragHeaders(output, fragSz, 0, payloadSz, certificate, ssl); 03284 03285 /* Request context. */ 03286 output[i++] = 0; 03287 length -= 1; 03288 fragSz -= 1; 03289 /* Certificate list length. */ 03290 c32to24(listSz, output + i); 03291 i += CERT_HEADER_SZ; 03292 length -= CERT_HEADER_SZ; 03293 fragSz -= CERT_HEADER_SZ; 03294 /* Leaf certificate data length. */ 03295 if (certSz > 0) { 03296 c32to24(certSz, output + i); 03297 i += CERT_HEADER_SZ; 03298 length -= CERT_HEADER_SZ; 03299 fragSz -= CERT_HEADER_SZ; 03300 } 03301 } 03302 else 03303 AddTls13RecordHeader(output, fragSz, handshake, ssl); 03304 03305 /* TODO: [TLS13] Test with fragments and multiple CA certs */ 03306 if (certSz > 0 && ssl->fragOffset < certSz + OPAQUE16_LEN) { 03307 /* Put in the leaf certificate and empty extension. */ 03308 word32 copySz = AddCertExt(ssl->buffers.certificate->buffer, certSz, 03309 ssl->fragOffset, fragSz, output + i); 03310 03311 i += copySz; 03312 ssl->fragOffset += copySz; 03313 length -= copySz; 03314 fragSz -= copySz; 03315 } 03316 if (certChainSz > 0 && fragSz > 0) { 03317 /* Put in the CA certificates with empty extensions. */ 03318 while (fragSz > 0) { 03319 word32 l; 03320 03321 if (offset == len + OPAQUE16_LEN) { 03322 /* Find next CA certificate to write out. */ 03323 offset = 0; 03324 len = NextCert(ssl->buffers.certChain->buffer, 03325 ssl->buffers.certChain->length, &idx); 03326 if (len == 0) 03327 break; 03328 } 03329 03330 /* Write out certificate and empty extension. */ 03331 l = AddCertExt(p, len, offset, fragSz, output + i); 03332 i += l; 03333 ssl->fragOffset += l; 03334 length -= l; 03335 fragSz -= l; 03336 offset += l; 03337 } 03338 } 03339 03340 if ((int)i - RECORD_HEADER_SZ < 0) { 03341 WOLFSSL_MSG("Send Cert bad inputSz"); 03342 return BUFFER_E; 03343 } 03344 03345 /* This message is always encrypted. */ 03346 sendSz = BuildTls13Message(ssl, output, sendSz, 03347 output + RECORD_HEADER_SZ, 03348 i - RECORD_HEADER_SZ, handshake, 1, 0); 03349 if (sendSz < 0) 03350 return sendSz; 03351 03352 #ifdef WOLFSSL_CALLBACKS 03353 if (ssl->hsInfoOn) 03354 AddPacketName("Certificate", &ssl->handShakeInfo); 03355 if (ssl->toInfoOn) 03356 AddPacketInfo("Certificate", &ssl->timeoutInfo, output, sendSz, 03357 ssl->heap); 03358 #endif 03359 03360 ssl->buffers.outputBuffer.length += sendSz; 03361 if (!ssl->options.groupMessages) 03362 ret = SendBuffered(ssl); 03363 } 03364 03365 if (ret != WANT_WRITE) { 03366 /* Clean up the fragment offset. */ 03367 ssl->fragOffset = 0; 03368 if (ssl->options.side == WOLFSSL_SERVER_END) 03369 ssl->options.serverState = SERVER_CERT_COMPLETE; 03370 } 03371 03372 return ret; 03373 } 03374 03375 typedef struct Scv13Args { 03376 byte* output; /* not allocated */ 03377 #ifndef NO_RSA 03378 byte* verifySig; 03379 #endif 03380 byte* verify; /* not allocated */ 03381 byte* input; 03382 word32 idx; 03383 word32 sigLen; 03384 int sendSz; 03385 word16 length; 03386 03387 byte* sigData; 03388 word16 sigDataSz; 03389 } Scv13Args; 03390 03391 static void FreeScv13Args(WOLFSSL* ssl, void* pArgs) 03392 { 03393 Scv13Args* args = (Scv13Args*)pArgs; 03394 03395 (void)ssl; 03396 03397 #ifndef NO_RSA 03398 if (args->verifySig) { 03399 XFREE(args->verifySig, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); 03400 args->verifySig = NULL; 03401 } 03402 #endif 03403 if (args->sigData) { 03404 XFREE(args->sigData, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); 03405 args->sigData = NULL; 03406 } 03407 if (args->input) { 03408 XFREE(args->input, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); 03409 args->input = NULL; 03410 } 03411 } 03412 03413 /* Send the TLS v1.3 CertificateVerify message. 03414 * A hash of all the message so far is used. 03415 * The signed data is: 03416 * 0x20 * 64 | context string | 0x00 | hash of messages 03417 * This message is always encrypted in TLS v1.3. 03418 * 03419 * ssl The SSL/TLS object. 03420 * returns 0 on success, otherwise failure. 03421 */ 03422 int SendTls13CertificateVerify(WOLFSSL* ssl) 03423 { 03424 int ret = 0; 03425 buffer* sig = &ssl->buffers.sig; 03426 #ifdef WOLFSSL_ASYNC_CRYPT 03427 Scv13Args* args = (Scv13Args*)ssl->async.args; 03428 typedef char args_test[sizeof(ssl->async.args) >= sizeof(*args) ? 1 : -1]; 03429 (void)sizeof(args_test); 03430 #else 03431 Scv13Args args[1]; 03432 #endif 03433 03434 WOLFSSL_ENTER("SendTls13CertificateVerify"); 03435 03436 #ifdef WOLFSSL_ASYNC_CRYPT 03437 ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState); 03438 if (ret != WC_NOT_PENDING_E) { 03439 /* Check for error */ 03440 if (ret < 0) 03441 goto exit_scv; 03442 } 03443 else 03444 #endif 03445 { 03446 /* Reset state */ 03447 ret = 0; 03448 ssl->options.asyncState = TLS_ASYNC_BEGIN; 03449 XMEMSET(args, 0, sizeof(Scv13Args)); 03450 #ifdef WOLFSSL_ASYNC_CRYPT 03451 ssl->async.freeArgs = FreeScv13Args; 03452 #endif 03453 } 03454 03455 switch(ssl->options.asyncState) 03456 { 03457 case TLS_ASYNC_BEGIN: 03458 { 03459 if (ssl->options.sendVerify == SEND_BLANK_CERT) { 03460 return 0; /* sent blank cert, can't verify */ 03461 } 03462 03463 args->sendSz = MAX_CERT_VERIFY_SZ; 03464 /* Always encrypted. */ 03465 args->sendSz += MAX_MSG_EXTRA; 03466 03467 /* check for available size */ 03468 if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0) { 03469 goto exit_scv; 03470 } 03471 03472 /* get output buffer */ 03473 args->output = ssl->buffers.outputBuffer.buffer + 03474 ssl->buffers.outputBuffer.length; 03475 03476 /* Advance state and proceed */ 03477 ssl->options.asyncState = TLS_ASYNC_BUILD; 03478 } /* case TLS_ASYNC_BEGIN */ 03479 03480 case TLS_ASYNC_BUILD: 03481 { 03482 /* idx is used to track verify pointer offset to output */ 03483 args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ; 03484 args->verify = &args->output[RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ]; 03485 03486 ret = DecodePrivateKey(ssl, &args->length); 03487 if (ret != 0) 03488 goto exit_scv; 03489 03490 /* Add signature algorithm. */ 03491 EncodeSigAlg(ssl->suites->hashAlgo, ssl->hsType, args->verify); 03492 03493 /* Create the data to be signed. */ 03494 args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap, 03495 DYNAMIC_TYPE_TMP_BUFFER); 03496 if (args->sigData == NULL) { 03497 ERROR_OUT(MEMORY_E, exit_scv); 03498 } 03499 03500 CreateSigData(ssl, args->sigData, &args->sigDataSz, 0); 03501 03502 #ifndef NO_RSA 03503 if (ssl->hsType == DYNAMIC_TYPE_RSA) { 03504 /* build encoded signature buffer */ 03505 sig->length = MAX_ENCODED_SIG_SZ; 03506 sig->buffer = (byte*)XMALLOC(sig->length, ssl->heap, 03507 DYNAMIC_TYPE_TMP_BUFFER); 03508 if (sig->buffer == NULL) 03509 return MEMORY_E; 03510 03511 /* Digest the signature data and encode. Used in verify too. */ 03512 sig->length = CreateRSAEncodedSig(sig->buffer, args->sigData, 03513 args->sigDataSz, ssl->suites->hashAlgo); 03514 if (ret != 0) 03515 goto exit_scv; 03516 03517 /* Maximum size of RSA Signature. */ 03518 args->sigLen = args->length; 03519 } 03520 #endif /* !NO_RSA */ 03521 #ifdef HAVE_ECC 03522 if (ssl->hsType == DYNAMIC_TYPE_ECC) { 03523 sig->length = args->sendSz - args->idx - HASH_SIG_SIZE - 03524 VERIFY_HEADER; 03525 args->sigDataSz = CreateECCEncodedSig(args->sigData, 03526 args->sigDataSz, ssl->suites->hashAlgo); 03527 } 03528 #endif /* HAVE_ECC */ 03529 03530 /* Advance state and proceed */ 03531 ssl->options.asyncState = TLS_ASYNC_DO; 03532 } /* case TLS_ASYNC_BUILD */ 03533 03534 case TLS_ASYNC_DO: 03535 { 03536 #ifdef HAVE_ECC 03537 if (ssl->hsType == DYNAMIC_TYPE_ECC) { 03538 ret = EccSign(ssl, args->sigData, args->sigDataSz, 03539 args->verify + HASH_SIG_SIZE + VERIFY_HEADER, 03540 &sig->length, (ecc_key*)ssl->hsKey, 03541 #if defined(HAVE_PK_CALLBACKS) 03542 ssl->buffers.key->buffer, ssl->buffers.key->length, 03543 ssl->EccSignCtx 03544 #else 03545 NULL, 0, NULL 03546 #endif 03547 ); 03548 args->length = sig->length; 03549 } 03550 #endif /* HAVE_ECC */ 03551 #ifndef NO_RSA 03552 if (ssl->hsType == DYNAMIC_TYPE_RSA) { 03553 /* restore verify pointer */ 03554 args->verify = &args->output[args->idx]; 03555 03556 ret = RsaSign(ssl, sig->buffer, sig->length, 03557 args->verify + HASH_SIG_SIZE + VERIFY_HEADER, &args->sigLen, 03558 (RsaKey*)ssl->hsKey, 03559 ssl->buffers.key->buffer, ssl->buffers.key->length, 03560 #ifdef HAVE_PK_CALLBACKS 03561 ssl->RsaSignCtx 03562 #else 03563 NULL 03564 #endif 03565 ); 03566 args->length = args->sigLen; 03567 } 03568 #endif /* !NO_RSA */ 03569 03570 /* Check for error */ 03571 if (ret != 0) { 03572 goto exit_scv; 03573 } 03574 03575 /* Add signature length. */ 03576 c16toa(args->length, args->verify + HASH_SIG_SIZE); 03577 03578 /* Advance state and proceed */ 03579 ssl->options.asyncState = TLS_ASYNC_VERIFY; 03580 } /* case TLS_ASYNC_DO */ 03581 03582 case TLS_ASYNC_VERIFY: 03583 { 03584 /* restore verify pointer */ 03585 args->verify = &args->output[args->idx]; 03586 03587 #ifndef NO_RSA 03588 if (ssl->hsType == DYNAMIC_TYPE_RSA) { 03589 if (args->verifySig == NULL) { 03590 args->verifySig = (byte*)XMALLOC(args->sigLen, ssl->heap, 03591 DYNAMIC_TYPE_TMP_BUFFER); 03592 if (args->verifySig == NULL) { 03593 ERROR_OUT(MEMORY_E, exit_scv); 03594 } 03595 XMEMCPY(args->verifySig, 03596 args->verify + HASH_SIG_SIZE + VERIFY_HEADER, 03597 args->sigLen); 03598 } 03599 03600 /* check for signature faults */ 03601 ret = VerifyRsaSign(ssl, args->verifySig, args->sigLen, 03602 sig->buffer, sig->length, (RsaKey*)ssl->hsKey); 03603 } 03604 #endif /* !NO_RSA */ 03605 03606 /* Check for error */ 03607 if (ret != 0) { 03608 goto exit_scv; 03609 } 03610 03611 /* Advance state and proceed */ 03612 ssl->options.asyncState = TLS_ASYNC_FINALIZE; 03613 } /* case TLS_ASYNC_VERIFY */ 03614 03615 case TLS_ASYNC_FINALIZE: 03616 { 03617 /* Put the record and handshake headers on. */ 03618 AddTls13Headers(args->output, args->length + HASH_SIG_SIZE + VERIFY_HEADER, 03619 certificate_verify, ssl); 03620 03621 args->sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ + args->length + 03622 HASH_SIG_SIZE + VERIFY_HEADER; 03623 03624 /* This message is always encrypted. */ 03625 args->sendSz = BuildTls13Message(ssl, args->output, 03626 MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA, 03627 args->output + RECORD_HEADER_SZ, 03628 args->sendSz - RECORD_HEADER_SZ, handshake, 03629 1, 0); 03630 if (args->sendSz < 0) { 03631 ret = args->sendSz; 03632 goto exit_scv; 03633 } 03634 03635 /* Advance state and proceed */ 03636 ssl->options.asyncState = TLS_ASYNC_END; 03637 } /* case TLS_ASYNC_FINALIZE */ 03638 03639 case TLS_ASYNC_END: 03640 { 03641 #ifdef WOLFSSL_CALLBACKS 03642 if (ssl->hsInfoOn) 03643 AddPacketName("CertificateVerify", &ssl->handShakeInfo); 03644 if (ssl->toInfoOn) 03645 AddPacketInfo("CertificateVerify", &ssl->timeoutInfo, 03646 args->output, args->sendSz, ssl->heap); 03647 #endif 03648 03649 ssl->buffers.outputBuffer.length += args->sendSz; 03650 03651 if (!ssl->options.groupMessages) 03652 ret = SendBuffered(ssl); 03653 break; 03654 } 03655 default: 03656 ret = INPUT_CASE_ERROR; 03657 } /* switch(ssl->options.asyncState) */ 03658 03659 exit_scv: 03660 03661 WOLFSSL_LEAVE("SendTls13CertificateVerify", ret); 03662 03663 #ifdef WOLFSSL_ASYNC_CRYPT 03664 /* Handle async operation */ 03665 if (ret == WC_PENDING_E) { 03666 return ret; 03667 } 03668 #endif /* WOLFSSL_ASYNC_CRYPT */ 03669 03670 /* Final cleanup */ 03671 FreeScv13Args(ssl, args); 03672 FreeKeyExchange(ssl); 03673 03674 return ret; 03675 } 03676 03677 03678 /* Parse and handle a TLS v1.3 Certificate message. 03679 * 03680 * ssl The SSL/TLS object. 03681 * input The message buffer. 03682 * inOutIdx On entry, the index into the message buffer of Certificate. 03683 * On exit, the index of byte after the Certificate message. 03684 * totalSz The length of the current handshake message. 03685 * returns 0 on success and otherwise failure. 03686 */ 03687 static int DoTls13Certificate(WOLFSSL* ssl, byte* input, word32* inOutIdx, 03688 word32 totalSz) 03689 { 03690 return ProcessPeerCerts(ssl, input, inOutIdx, totalSz); 03691 } 03692 03693 #if !defined(NO_RSA) || defined(HAVE_ECC) 03694 03695 typedef struct Dcv13Args { 03696 byte* output; /* not allocated */ 03697 word32 sendSz; 03698 word16 sz; 03699 word32 sigSz; 03700 word32 idx; 03701 word32 begin; 03702 byte hashAlgo; 03703 byte sigAlgo; 03704 03705 byte* sigData; 03706 word16 sigDataSz; 03707 } Dcv13Args; 03708 03709 static void FreeDcv13Args(WOLFSSL* ssl, void* pArgs) 03710 { 03711 Dcv13Args* args = (Dcv13Args*)pArgs; 03712 03713 if (args->sigData) { 03714 XFREE(args->sigData, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); 03715 args->sigData = NULL; 03716 } 03717 03718 (void)ssl; 03719 } 03720 03721 /* Parse and handle a TLS v1.3 CertificateVerify message. 03722 * 03723 * ssl The SSL/TLS object. 03724 * input The message buffer. 03725 * inOutIdx On entry, the index into the message buffer of 03726 * CertificateVerify. 03727 * On exit, the index of byte after the CertificateVerify message. 03728 * totalSz The length of the current handshake message. 03729 * returns 0 on success and otherwise failure. 03730 */ 03731 static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input, 03732 word32* inOutIdx, word32 totalSz) 03733 { 03734 int ret = 0; 03735 buffer* sig = &ssl->buffers.sig; 03736 #ifdef WOLFSSL_ASYNC_CRYPT 03737 Dcv13Args* args = (Dcv13Args*)ssl->async.args; 03738 typedef char args_test[sizeof(ssl->async.args) >= sizeof(*args) ? 1 : -1]; 03739 (void)sizeof(args_test); 03740 #else 03741 Dcv13Args args[1]; 03742 #endif 03743 03744 WOLFSSL_ENTER("DoTls13CertificateVerify"); 03745 03746 #ifdef WOLFSSL_ASYNC_CRYPT 03747 ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState); 03748 if (ret != WC_NOT_PENDING_E) { 03749 /* Check for error */ 03750 if (ret < 0) 03751 goto exit_dcv; 03752 } 03753 else 03754 #endif 03755 { 03756 /* Reset state */ 03757 ret = 0; 03758 ssl->options.asyncState = TLS_ASYNC_BEGIN; 03759 XMEMSET(args, 0, sizeof(Dcv13Args)); 03760 args->hashAlgo = sha_mac; 03761 args->sigAlgo = anonymous_sa_algo; 03762 args->idx = *inOutIdx; 03763 args->begin = *inOutIdx; 03764 #ifdef WOLFSSL_ASYNC_CRYPT 03765 ssl->async.freeArgs = FreeDcv13Args; 03766 #endif 03767 } 03768 03769 switch(ssl->options.asyncState) 03770 { 03771 case TLS_ASYNC_BEGIN: 03772 { 03773 #ifdef WOLFSSL_CALLBACKS 03774 if (ssl->hsInfoOn) AddPacketName("CertificateVerify", 03775 &ssl->handShakeInfo); 03776 if (ssl->toInfoOn) AddLateName("CertificateVerify", 03777 &ssl->timeoutInfo); 03778 #endif 03779 03780 /* Advance state and proceed */ 03781 ssl->options.asyncState = TLS_ASYNC_BUILD; 03782 } /* case TLS_ASYNC_BEGIN */ 03783 03784 case TLS_ASYNC_BUILD: 03785 { 03786 /* Signature algorithm. */ 03787 if ((args->idx - args->begin) + ENUM_LEN + ENUM_LEN > totalSz) { 03788 ERROR_OUT(BUFFER_ERROR, exit_dcv); 03789 } 03790 DecodeSigAlg(input + args->idx, &args->hashAlgo, &args->sigAlgo); 03791 args->idx += OPAQUE16_LEN; 03792 /* TODO: [TLS13] was it in SignatureAlgorithms extension? */ 03793 03794 /* Signature length. */ 03795 if ((args->idx - args->begin) + OPAQUE16_LEN > totalSz) { 03796 ERROR_OUT(BUFFER_ERROR, exit_dcv); 03797 } 03798 ato16(input + args->idx, &args->sz); 03799 args->idx += OPAQUE16_LEN; 03800 03801 /* Signature data. */ 03802 if ((args->idx - args->begin) + args->sz > totalSz || 03803 args->sz > ENCRYPT_LEN) { 03804 ERROR_OUT(BUFFER_ERROR, exit_dcv); 03805 } 03806 03807 /* Check for public key of required type. */ 03808 if (args->sigAlgo == ecc_dsa_sa_algo && 03809 !ssl->peerEccDsaKeyPresent) { 03810 WOLFSSL_MSG("Oops, peer sent ECC key but not in verify"); 03811 } 03812 if ((args->sigAlgo == rsa_sa_algo || 03813 args->sigAlgo == rsa_pss_sa_algo) && 03814 (ssl->peerRsaKey == NULL || !ssl->peerRsaKeyPresent)) { 03815 WOLFSSL_MSG("Oops, peer sent RSA key but not in verify"); 03816 } 03817 03818 sig->buffer = XMALLOC(args->sz, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER); 03819 if (sig->buffer == NULL) { 03820 ERROR_OUT(MEMORY_E, exit_dcv); 03821 } 03822 sig->length = args->sz; 03823 XMEMCPY(sig->buffer, input + args->idx, args->sz); 03824 03825 #ifdef HAVE_ECC 03826 if (ssl->peerEccDsaKeyPresent) { 03827 WOLFSSL_MSG("Doing ECC peer cert verify"); 03828 03829 args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap, 03830 DYNAMIC_TYPE_TMP_BUFFER); 03831 if (args->sigData == NULL) { 03832 ERROR_OUT(MEMORY_E, exit_dcv); 03833 } 03834 03835 CreateSigData(ssl, args->sigData, &args->sigDataSz, 1); 03836 args->sigDataSz = CreateECCEncodedSig(args->sigData, 03837 args->sigDataSz, args->hashAlgo); 03838 } 03839 #endif 03840 03841 /* Advance state and proceed */ 03842 ssl->options.asyncState = TLS_ASYNC_DO; 03843 } /* case TLS_ASYNC_BUILD */ 03844 03845 case TLS_ASYNC_DO: 03846 { 03847 #ifndef NO_RSA 03848 if (args->sigAlgo == rsa_sa_algo || 03849 args->sigAlgo == rsa_pss_sa_algo) { 03850 WOLFSSL_MSG("Doing RSA peer cert verify"); 03851 03852 ret = RsaVerify(ssl, sig->buffer, sig->length, &args->output, 03853 args->sigAlgo, args->hashAlgo, ssl->peerRsaKey, 03854 #ifdef HAVE_PK_CALLBACKS 03855 ssl->buffers.peerRsaKey.buffer, 03856 ssl->buffers.peerRsaKey.length, 03857 ssl->RsaVerifyCtx 03858 #else 03859 NULL, 0, NULL 03860 #endif 03861 ); 03862 if (ret >= 0) { 03863 args->sendSz = ret; 03864 ret = 0; 03865 } 03866 } 03867 #endif /* !NO_RSA */ 03868 #ifdef HAVE_ECC 03869 if (ssl->peerEccDsaKeyPresent) { 03870 WOLFSSL_MSG("Doing ECC peer cert verify"); 03871 03872 ret = EccVerify(ssl, input + args->idx, args->sz, 03873 args->sigData, args->sigDataSz, 03874 ssl->peerEccDsaKey, 03875 #ifdef HAVE_PK_CALLBACKS 03876 ssl->buffers.peerEccDsaKey.buffer, 03877 ssl->buffers.peerEccDsaKey.length, 03878 ssl->EccVerifyCtx 03879 #else 03880 NULL, 0, NULL 03881 #endif 03882 ); 03883 } 03884 #endif /* HAVE_ECC */ 03885 03886 /* Check for error */ 03887 if (ret != 0) { 03888 goto exit_dcv; 03889 } 03890 03891 /* Advance state and proceed */ 03892 ssl->options.asyncState = TLS_ASYNC_VERIFY; 03893 } /* case TLS_ASYNC_DO */ 03894 03895 case TLS_ASYNC_VERIFY: 03896 { 03897 #ifndef NO_RSA 03898 if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) { 03899 ret = CheckRSASignature(ssl, args->sigAlgo, args->hashAlgo, 03900 args->output, args->sendSz); 03901 if (ret != 0) 03902 goto exit_dcv; 03903 } 03904 #endif /* !NO_RSA */ 03905 03906 /* Advance state and proceed */ 03907 ssl->options.asyncState = TLS_ASYNC_FINALIZE; 03908 } /* case TLS_ASYNC_VERIFY */ 03909 03910 case TLS_ASYNC_FINALIZE: 03911 { 03912 ssl->options.havePeerVerify = 1; 03913 03914 /* Set final index */ 03915 args->idx += args->sz; 03916 *inOutIdx = args->idx; 03917 03918 /* Encryption is always on: add padding */ 03919 *inOutIdx += ssl->keys.padSz; 03920 03921 /* Advance state and proceed */ 03922 ssl->options.asyncState = TLS_ASYNC_END; 03923 } /* case TLS_ASYNC_FINALIZE */ 03924 03925 case TLS_ASYNC_END: 03926 { 03927 break; 03928 } 03929 default: 03930 ret = INPUT_CASE_ERROR; 03931 } /* switch(ssl->options.asyncState) */ 03932 03933 exit_dcv: 03934 03935 WOLFSSL_LEAVE("DoTls13CertificateVerify", ret); 03936 03937 #ifdef WOLFSSL_ASYNC_CRYPT 03938 /* Handle async operation */ 03939 if (ret == WC_PENDING_E) { 03940 /* Mark message as not recevied so it can process again */ 03941 ssl->msgsReceived.got_certificate_verify = 0; 03942 03943 return ret; 03944 } 03945 #endif /* WOLFSSL_ASYNC_CRYPT */ 03946 03947 /* Final cleanup */ 03948 FreeDcv13Args(ssl, args); 03949 FreeKeyExchange(ssl); 03950 03951 return ret; 03952 } 03953 #endif /* !NO_RSA || HAVE_ECC */ 03954 03955 /* Parse and handle a TLS v1.3 Finished message. 03956 * 03957 * ssl The SSL/TLS object. 03958 * input The message buffer. 03959 * inOutIdx On entry, the index into the message buffer of Finished. 03960 * On exit, the index of byte after the Finished message and padding. 03961 * size Length of message data. 03962 * totalSz Length of remaining data in the message buffer. 03963 * sniff Indicates whether we are sniffing packets. 03964 * returns 0 on success and otherwise failure. 03965 */ 03966 static int DoTls13Finished(WOLFSSL* ssl, const byte* input, word32* inOutIdx, 03967 word32 size, word32 totalSz, int sniff) 03968 { 03969 int ret; 03970 word32 finishedSz = 0; 03971 byte* secret; 03972 byte mac[MAX_DIGEST_SIZE]; 03973 03974 /* check against totalSz */ 03975 if (*inOutIdx + size + ssl->keys.padSz > totalSz) 03976 return BUFFER_E; 03977 03978 if (ssl->options.side == WOLFSSL_CLIENT_END) { 03979 /* All the handshake messages have been received to calculate 03980 * client and server finished keys. 03981 */ 03982 ret = DeriveFinishedSecret(ssl, ssl->arrays->clientSecret, 03983 ssl->keys.client_write_MAC_secret); 03984 if (ret != 0) 03985 return ret; 03986 03987 ret = DeriveFinishedSecret(ssl, ssl->arrays->serverSecret, 03988 ssl->keys.server_write_MAC_secret); 03989 if (ret != 0) 03990 return ret; 03991 03992 secret = ssl->keys.server_write_MAC_secret; 03993 } 03994 else 03995 secret = ssl->keys.client_write_MAC_secret; 03996 finishedSz = BuildTls13HandshakeHmac(ssl, secret, mac); 03997 if (size != finishedSz) 03998 return BUFFER_ERROR; 03999 04000 #ifdef WOLFSSL_CALLBACKS 04001 if (ssl->hsInfoOn) AddPacketName("Finished", &ssl->handShakeInfo); 04002 if (ssl->toInfoOn) AddLateName("Finished", &ssl->timeoutInfo); 04003 #endif 04004 04005 if (sniff == NO_SNIFF) { 04006 /* Actually check verify data. */ 04007 if (XMEMCMP(input + *inOutIdx, mac, size) != 0){ 04008 WOLFSSL_MSG("Verify finished error on hashes"); 04009 return VERIFY_FINISHED_ERROR; 04010 } 04011 } 04012 04013 /* Force input exhaustion at ProcessReply by consuming padSz. */ 04014 *inOutIdx += size + ssl->keys.padSz; 04015 04016 if (ssl->options.side == WOLFSSL_SERVER_END) { 04017 /* Setup keys for application data messages from client. */ 04018 if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0) 04019 return ret; 04020 } 04021 04022 #ifndef NO_WOLFSSL_SERVER 04023 if (ssl->options.side == WOLFSSL_CLIENT_END) { 04024 ssl->options.serverState = SERVER_FINISHED_COMPLETE; 04025 if (!ssl->options.resuming) { 04026 ssl->options.handShakeState = HANDSHAKE_DONE; 04027 ssl->options.handShakeDone = 1; 04028 } 04029 } 04030 #endif 04031 #ifndef NO_WOLFSSL_CLIENT 04032 if (ssl->options.side == WOLFSSL_SERVER_END) { 04033 ssl->options.clientState = CLIENT_FINISHED_COMPLETE; 04034 ssl->options.handShakeState = HANDSHAKE_DONE; 04035 ssl->options.handShakeDone = 1; 04036 } 04037 #endif 04038 04039 return 0; 04040 } 04041 #endif /* NO_CERTS */ 04042 04043 /* Send the TLS v1.3 Finished message. 04044 * 04045 * ssl The SSL/TLS object. 04046 * returns 0 on success, otherwise failure. 04047 */ 04048 int SendTls13Finished(WOLFSSL* ssl) 04049 { 04050 int sendSz; 04051 int finishedSz = ssl->specs.hash_size; 04052 byte* input; 04053 byte* output; 04054 int ret; 04055 int headerSz = HANDSHAKE_HEADER_SZ; 04056 int outputSz; 04057 byte* secret; 04058 04059 outputSz = MAX_DIGEST_SIZE + DTLS_HANDSHAKE_HEADER_SZ + MAX_MSG_EXTRA; 04060 /* Check buffers are big enough and grow if needed. */ 04061 if ((ret = CheckAvailableSize(ssl, outputSz)) != 0) 04062 return ret; 04063 04064 /* get output buffer */ 04065 output = ssl->buffers.outputBuffer.buffer + 04066 ssl->buffers.outputBuffer.length; 04067 input = output + RECORD_HEADER_SZ; 04068 04069 AddTls13HandShakeHeader(input, finishedSz, 0, finishedSz, finished, ssl); 04070 04071 /* make finished hashes */ 04072 if (ssl->options.side == WOLFSSL_CLIENT_END) 04073 secret = ssl->keys.client_write_MAC_secret; 04074 else { 04075 /* All the handshake messages have been done to calculate client and 04076 * server finished keys. 04077 */ 04078 ret = DeriveFinishedSecret(ssl, ssl->arrays->clientSecret, 04079 ssl->keys.client_write_MAC_secret); 04080 if (ret != 0) 04081 return ret; 04082 04083 ret = DeriveFinishedSecret(ssl, ssl->arrays->serverSecret, 04084 ssl->keys.server_write_MAC_secret); 04085 if (ret != 0) 04086 return ret; 04087 04088 secret = ssl->keys.server_write_MAC_secret; 04089 } 04090 BuildTls13HandshakeHmac(ssl, secret, &input[headerSz]); 04091 04092 /* This message is always encrypted. */ 04093 sendSz = BuildTls13Message(ssl, output, outputSz, input, 04094 headerSz + finishedSz, handshake, 1, 0); 04095 if (sendSz < 0) 04096 return BUILD_MSG_ERROR; 04097 04098 if (!ssl->options.resuming) { 04099 #ifndef NO_SESSION_CACHE 04100 AddSession(ssl); /* just try */ 04101 #endif 04102 } 04103 else { 04104 if (ssl->options.side == WOLFSSL_CLIENT_END) { 04105 ssl->options.handShakeState = HANDSHAKE_DONE; 04106 ssl->options.handShakeDone = 1; 04107 } 04108 } 04109 04110 #ifdef WOLFSSL_CALLBACKS 04111 if (ssl->hsInfoOn) AddPacketName("Finished", &ssl->handShakeInfo); 04112 if (ssl->toInfoOn) 04113 AddPacketInfo("Finished", &ssl->timeoutInfo, output, sendSz, 04114 ssl->heap); 04115 #endif 04116 04117 ssl->buffers.outputBuffer.length += sendSz; 04118 04119 ret = SendBuffered(ssl); 04120 if (ret != 0) 04121 return ret; 04122 04123 if (ssl->options.side == WOLFSSL_SERVER_END) { 04124 /* Can send application data now. */ 04125 if ((ret = DeriveMasterSecret(ssl)) != 0) 04126 return ret; 04127 if ((ret = DeriveTls13Keys(ssl, traffic_key, 04128 ENCRYPT_AND_DECRYPT_SIDE)) != 0) 04129 return ret; 04130 if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0) 04131 return ret; 04132 } 04133 04134 if (ssl->options.side == WOLFSSL_CLIENT_END) { 04135 /* Setup keys for application data messages. */ 04136 if ((ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE)) != 0) 04137 return ret; 04138 04139 #ifndef NO_PSK 04140 ret = DeriveResumptionSecret(ssl, ssl->session.masterSecret); 04141 #endif 04142 } 04143 04144 return ret; 04145 } 04146 04147 /* Send the TLS v1.3 KeyUpdate message. 04148 * 04149 * ssl The SSL/TLS object. 04150 * returns 0 on success, otherwise failure. 04151 */ 04152 static int SendTls13KeyUpdate(WOLFSSL* ssl) 04153 { 04154 int sendSz; 04155 byte* input; 04156 byte* output; 04157 int ret; 04158 int headerSz = HANDSHAKE_HEADER_SZ; 04159 int outputSz; 04160 word32 i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ; 04161 04162 outputSz = OPAQUE8_LEN + MAX_MSG_EXTRA; 04163 /* Check buffers are big enough and grow if needed. */ 04164 if ((ret = CheckAvailableSize(ssl, outputSz)) != 0) 04165 return ret; 04166 04167 /* get output buffer */ 04168 output = ssl->buffers.outputBuffer.buffer + 04169 ssl->buffers.outputBuffer.length; 04170 input = output + RECORD_HEADER_SZ; 04171 04172 AddTls13Headers(output, OPAQUE8_LEN, key_update, ssl); 04173 04174 /* If: 04175 * 1. I haven't sent a KeyUpdate requesting a response and 04176 * 2. This isn't responding to peer KeyUpdate requiring a response then, 04177 * I want a response. 04178 */ 04179 ssl->keys.updateResponseReq = output[i++] = 04180 !ssl->keys.updateResponseReq && !ssl->keys.keyUpdateRespond; 04181 /* Sent response, no longer need to respond. */ 04182 ssl->keys.keyUpdateRespond = 0; 04183 04184 /* This message is always encrypted. */ 04185 sendSz = BuildTls13Message(ssl, output, outputSz, input, 04186 headerSz + OPAQUE8_LEN, handshake, 0, 0); 04187 if (sendSz < 0) 04188 return BUILD_MSG_ERROR; 04189 04190 #ifdef WOLFSSL_CALLBACKS 04191 if (ssl->hsInfoOn) AddPacketName("KeyUpdate", &ssl->handShakeInfo); 04192 if (ssl->toInfoOn) 04193 AddPacketInfo("KeyUpdate", &ssl->timeoutInfo, output, sendSz, 04194 ssl->heap); 04195 #endif 04196 04197 ssl->buffers.outputBuffer.length += sendSz; 04198 04199 ret = SendBuffered(ssl); 04200 if (ret != 0 && ret != WANT_WRITE) 04201 return ret; 04202 04203 /* Future traffic uses new encryption keys. */ 04204 if ((ret = DeriveTls13Keys(ssl, update_traffic_key, ENCRYPT_SIDE_ONLY)) 04205 != 0) 04206 return ret; 04207 if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0) 04208 return ret; 04209 04210 return ret; 04211 } 04212 04213 /* Parse and handle a TLS v1.3 KeyUpdate message. 04214 * 04215 * ssl The SSL/TLS object. 04216 * input The message buffer. 04217 * inOutIdx On entry, the index into the message buffer of Finished. 04218 * On exit, the index of byte after the Finished message and padding. 04219 * totalSz The length of the current handshake message. 04220 * returns 0 on success and otherwise failure. 04221 */ 04222 static int DoTls13KeyUpdate(WOLFSSL* ssl, const byte* input, word32* inOutIdx, 04223 word32 totalSz) 04224 { 04225 int ret; 04226 word32 i = *inOutIdx; 04227 04228 /* check against totalSz */ 04229 if (OPAQUE8_LEN != totalSz) 04230 return BUFFER_E; 04231 04232 switch (input[i]) { 04233 case update_not_requested: 04234 /* This message in response to any oustanding request. */ 04235 ssl->keys.keyUpdateRespond = 0; 04236 ssl->keys.updateResponseReq = 0; 04237 break; 04238 case update_requested: 04239 /* New key update requiring a response. */ 04240 ssl->keys.keyUpdateRespond = 1; 04241 break; 04242 default: 04243 return INVALID_PARAMETER; 04244 break; 04245 } 04246 04247 /* Move index to byte after message. */ 04248 *inOutIdx += totalSz; 04249 /* Always encrypted. */ 04250 *inOutIdx += ssl->keys.padSz; 04251 04252 /* Future traffic uses new decryption keys. */ 04253 if ((ret = DeriveTls13Keys(ssl, update_traffic_key, DECRYPT_SIDE_ONLY)) != 0) 04254 return ret; 04255 if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0) 04256 return ret; 04257 04258 if (ssl->keys.keyUpdateRespond) 04259 return SendTls13KeyUpdate(ssl); 04260 return 0; 04261 } 04262 04263 #ifndef NO_WOLFSSL_CLIENT 04264 /* Handle a New Session Ticket handshake message. 04265 * Message contains the information required to perform resumption. 04266 * 04267 * ssl The SSL/TLS object. 04268 * input The message buffer. 04269 * inOutIdx On entry, the index into the message buffer of Finished. 04270 * On exit, the index of byte after the Finished message and padding. 04271 * size The length of the current handshake message. 04272 * retuns 0 on success, otherwise failure. 04273 */ 04274 static int DoTls13NewSessionTicket(WOLFSSL* ssl, const byte* input, 04275 word32* inOutIdx, word32 size) 04276 { 04277 #ifdef HAVE_SESSION_TICKET 04278 word32 begin = *inOutIdx; 04279 word32 lifetime; 04280 word32 ageAdd; 04281 word16 length; 04282 04283 /* Lifetime hint. */ 04284 if ((*inOutIdx - begin) + SESSION_HINT_SZ > size) 04285 return BUFFER_ERROR; 04286 ato32(input + *inOutIdx, &lifetime); 04287 *inOutIdx += SESSION_HINT_SZ; 04288 if (lifetime > MAX_LIFETIME) 04289 return SERVER_HINT_ERROR; 04290 04291 /* Age add. */ 04292 if ((*inOutIdx - begin) + SESSION_ADD_SZ > size) 04293 return BUFFER_ERROR; 04294 ato32(input + *inOutIdx, &ageAdd); 04295 *inOutIdx += SESSION_ADD_SZ; 04296 04297 /* Ticket length. */ 04298 if ((*inOutIdx - begin) + LENGTH_SZ > size) 04299 return BUFFER_ERROR; 04300 ato16(input + *inOutIdx, &length); 04301 *inOutIdx += LENGTH_SZ; 04302 if ((*inOutIdx - begin) + length > size) 04303 return BUFFER_ERROR; 04304 04305 /* Free old dynamic ticket if we already had one. */ 04306 if (ssl->session.isDynamic) { 04307 XFREE(ssl->session.ticket, ssl->heap, DYNAMIC_TYPE_SESSION_TICK); 04308 /* Reset back to static by default. */ 04309 ssl->session.ticket = NULL; 04310 ssl->session.isDynamic = 0; 04311 ssl->session.ticket = ssl->session.staticTicket; 04312 } 04313 /* Use dynamic ticket if required.*/ 04314 if (length > sizeof(ssl->session.staticTicket)) { 04315 ssl->session.ticket = (byte*)XMALLOC(length, ssl->heap, 04316 DYNAMIC_TYPE_SESSION_TICK); 04317 if (ssl->session.ticket == NULL) 04318 return MEMORY_E; 04319 ssl->session.isDynamic = 1; 04320 } 04321 04322 /* Copy in ticket data (server identity). */ 04323 XMEMCPY(ssl->session.ticket, input + *inOutIdx, length); 04324 *inOutIdx += length; 04325 ssl->timeout = lifetime; 04326 ssl->session.ticketLen = length; 04327 ssl->session.timeout = lifetime; 04328 ssl->session.ticketAdd = ageAdd; 04329 ssl->session.ticketSeen = TimeNowInMilliseconds(); 04330 if (ssl->session_ticket_cb != NULL) { 04331 ssl->session_ticket_cb(ssl, ssl->session.ticket, 04332 ssl->session.ticketLen, 04333 ssl->session_ticket_ctx); 04334 } 04335 ssl->options.haveSessionId = 1; 04336 XMEMCPY(ssl->arrays->sessionID, ssl->session.ticket + length - ID_LEN, 04337 ID_LEN); 04338 ssl->session.cipherSuite0 = ssl->options.cipherSuite0; 04339 ssl->session.cipherSuite = ssl->options.cipherSuite; 04340 #ifndef NO_SESSION_CACHE 04341 AddSession(ssl); 04342 #endif 04343 04344 /* No extension support - skip over extensions. */ 04345 if ((*inOutIdx - begin) + EXTS_SZ > size) 04346 return BUFFER_ERROR; 04347 ato16(input + *inOutIdx, &length); 04348 *inOutIdx += EXTS_SZ; 04349 if ((*inOutIdx - begin) + length != size) 04350 return BUFFER_ERROR; 04351 *inOutIdx += length; 04352 04353 /* Always encrypted. */ 04354 *inOutIdx += ssl->keys.padSz; 04355 04356 ssl->expect_session_ticket = 0; 04357 #else 04358 (void)ssl; 04359 (void)input; 04360 *inOutIdx += size + ssl->keys.padSz; 04361 #endif /* HAVE_SESSION_TICKET */ 04362 04363 return 0; 04364 } 04365 #endif /* NO_WOLFSSL_CLIENT */ 04366 04367 #ifndef NO_WOLFSSL_SERVER 04368 #ifdef HAVE_SESSION_TICKET 04369 /* Send New Session Ticket handshake message. 04370 * Message contains the information required to perform resumption. 04371 * 04372 * ssl The SSL/TLS object. 04373 * retuns 0 on success, otherwise failure. 04374 */ 04375 int SendTls13NewSessionTicket(WOLFSSL* ssl) 04376 { 04377 byte* output; 04378 int ret; 04379 int sendSz; 04380 word32 length; 04381 word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ; 04382 04383 if (!ssl->options.noTicketTls13) { 04384 ret = CreateTicket(ssl); 04385 if (ret != 0) return ret; 04386 } 04387 04388 /* Lifetime | Age Add | Ticket | Extensions */ 04389 length = SESSION_HINT_SZ + SESSION_ADD_SZ + LENGTH_SZ + 04390 ssl->session.ticketLen + EXTS_SZ; 04391 sendSz = idx + length + MAX_MSG_EXTRA; 04392 04393 /* Check buffers are big enough and grow if needed. */ 04394 if ((ret = CheckAvailableSize(ssl, sendSz)) != 0) 04395 return ret; 04396 04397 /* Get position in output buffer to write new message to. */ 04398 output = ssl->buffers.outputBuffer.buffer + 04399 ssl->buffers.outputBuffer.length; 04400 04401 /* Put the record and handshake headers on. */ 04402 AddTls13Headers(output, length, session_ticket, ssl); 04403 04404 /* Lifetime hint */ 04405 c32toa(ssl->ctx->ticketHint, output + idx); 04406 idx += SESSION_HINT_SZ; 04407 /* Age add - obfuscator */ 04408 c32toa(ssl->session.ticketAdd, output + idx); 04409 idx += SESSION_ADD_SZ; 04410 04411 /* length */ 04412 c16toa(ssl->session.ticketLen, output + idx); 04413 idx += LENGTH_SZ; 04414 /* ticket */ 04415 XMEMCPY(output + idx, ssl->session.ticket, ssl->session.ticketLen); 04416 idx += ssl->session.ticketLen; 04417 04418 /* No extension support - empty extensions. */ 04419 c16toa(0, output + idx); 04420 idx += EXTS_SZ; 04421 04422 ssl->options.haveSessionId = 1; 04423 04424 #ifndef NO_SESSION_CACHE 04425 AddSession(ssl); 04426 #endif 04427 04428 /* This message is always encrypted. */ 04429 sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ, 04430 idx - RECORD_HEADER_SZ, handshake, 0, 0); 04431 if (sendSz < 0) 04432 return sendSz; 04433 04434 ssl->buffers.outputBuffer.length += sendSz; 04435 04436 return SendBuffered(ssl); 04437 } 04438 #endif /* HAVE_SESSION_TICKET */ 04439 #endif /* NO_WOLFSSL_SERVER */ 04440 04441 /* Make sure no duplicates, no fast forward, or other problems 04442 * 04443 * ssl The SSL/TLS object. 04444 * type Type of handshake message received. 04445 * returns 0 on success, otherwise failure. 04446 */ 04447 static int SanityCheckTls13MsgReceived(WOLFSSL* ssl, byte type) 04448 { 04449 /* verify not a duplicate, mark received, check state */ 04450 switch (type) { 04451 04452 #ifndef NO_WOLFSSL_SERVER 04453 case client_hello: 04454 if (ssl->msgsReceived.got_client_hello == 2) { 04455 WOLFSSL_MSG("Too many ClientHello received"); 04456 return DUPLICATE_MSG_E; 04457 } 04458 ssl->msgsReceived.got_client_hello++; 04459 04460 break; 04461 #endif 04462 04463 #ifndef NO_WOLFSSL_CLIENT 04464 case server_hello: 04465 if (ssl->msgsReceived.got_server_hello) { 04466 WOLFSSL_MSG("Duplicate ServerHello received"); 04467 return DUPLICATE_MSG_E; 04468 } 04469 ssl->msgsReceived.got_server_hello = 1; 04470 04471 break; 04472 #endif 04473 04474 #ifndef NO_WOLFSSL_CLIENT 04475 case session_ticket: 04476 if (ssl->msgsReceived.got_session_ticket) { 04477 WOLFSSL_MSG("Duplicate SessionTicket received"); 04478 return DUPLICATE_MSG_E; 04479 } 04480 ssl->msgsReceived.got_session_ticket = 1; 04481 04482 break; 04483 #endif 04484 04485 #ifndef NO_WOLFSSL_CLIENT 04486 case hello_retry_request: 04487 if (ssl->msgsReceived.got_hello_retry_request) { 04488 WOLFSSL_MSG("Duplicate HelloRetryRequest received"); 04489 return DUPLICATE_MSG_E; 04490 } 04491 ssl->msgsReceived.got_hello_retry_request = 1; 04492 04493 break; 04494 #endif 04495 04496 #ifndef NO_WOLFSSL_CLIENT 04497 case encrypted_extensions: 04498 if (ssl->msgsReceived.got_encrypted_extensions) { 04499 WOLFSSL_MSG("Duplicate EncryptedExtensions received"); 04500 return DUPLICATE_MSG_E; 04501 } 04502 ssl->msgsReceived.got_encrypted_extensions = 1; 04503 04504 break; 04505 #endif 04506 04507 case certificate: 04508 if (ssl->msgsReceived.got_certificate) { 04509 WOLFSSL_MSG("Duplicate Certificate received"); 04510 return DUPLICATE_MSG_E; 04511 } 04512 ssl->msgsReceived.got_certificate = 1; 04513 04514 #ifndef NO_WOLFSSL_CLIENT 04515 if (ssl->options.side == WOLFSSL_CLIENT_END) { 04516 if ( ssl->msgsReceived.got_server_hello == 0) { 04517 WOLFSSL_MSG("No ServerHello before Cert"); 04518 return OUT_OF_ORDER_E; 04519 } 04520 } 04521 #endif 04522 #ifndef NO_WOLFSSL_SERVER 04523 if (ssl->options.side == WOLFSSL_SERVER_END) { 04524 if ( ssl->msgsReceived.got_client_hello == 0) { 04525 WOLFSSL_MSG("No ClientHello before Cert"); 04526 return OUT_OF_ORDER_E; 04527 } 04528 } 04529 #endif 04530 break; 04531 04532 #ifndef NO_WOLFSSL_CLIENT 04533 case certificate_request: 04534 if (ssl->msgsReceived.got_certificate_request) { 04535 WOLFSSL_MSG("Duplicate CertificateRequest received"); 04536 return DUPLICATE_MSG_E; 04537 } 04538 ssl->msgsReceived.got_certificate_request = 1; 04539 04540 break; 04541 #endif 04542 04543 case certificate_verify: 04544 if (ssl->msgsReceived.got_certificate_verify) { 04545 WOLFSSL_MSG("Duplicate CertificateVerify received"); 04546 return DUPLICATE_MSG_E; 04547 } 04548 ssl->msgsReceived.got_certificate_verify = 1; 04549 04550 if (ssl->msgsReceived.got_certificate == 0) { 04551 WOLFSSL_MSG("No Cert before CertVerify"); 04552 return OUT_OF_ORDER_E; 04553 } 04554 break; 04555 04556 case finished: 04557 if (ssl->msgsReceived.got_finished) { 04558 WOLFSSL_MSG("Duplicate Finished received"); 04559 return DUPLICATE_MSG_E; 04560 } 04561 ssl->msgsReceived.got_finished = 1; 04562 04563 break; 04564 04565 case key_update: 04566 if (!ssl->msgsReceived.got_finished) { 04567 WOLFSSL_MSG("No KeyUpdate before Finished"); 04568 return OUT_OF_ORDER_E; 04569 } 04570 break; 04571 04572 default: 04573 WOLFSSL_MSG("Unknown message type"); 04574 return SANITY_MSG_E; 04575 } 04576 04577 return 0; 04578 } 04579 04580 /* Handle a type of handshake message that has been received. 04581 * 04582 * ssl The SSL/TLS object. 04583 * input The message buffer. 04584 * inOutIdx On entry, the index into the buffer of the current message. 04585 * On exit, the index into the buffer of the next message. 04586 * size The length of the current handshake message. 04587 * totalSz Length of remaining data in the message buffer. 04588 * returns 0 on success and otherwise failure. 04589 */ 04590 int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx, 04591 byte type, word32 size, word32 totalSz) 04592 { 04593 int ret = 0; 04594 (void)totalSz; 04595 word32 inIdx = *inOutIdx; 04596 04597 WOLFSSL_ENTER("DoTls13HandShakeMsgType"); 04598 04599 /* make sure can read the message */ 04600 if (*inOutIdx + size > totalSz) 04601 return INCOMPLETE_DATA; 04602 04603 /* sanity check msg received */ 04604 if ( (ret = SanityCheckTls13MsgReceived(ssl, type)) != 0) { 04605 WOLFSSL_MSG("Sanity Check on handshake message type received failed"); 04606 return ret; 04607 } 04608 04609 #ifdef WOLFSSL_CALLBACKS 04610 /* add name later, add on record and handshake header part back on */ 04611 if (ssl->toInfoOn) { 04612 int add = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ; 04613 AddPacketInfo(0, &ssl->timeoutInfo, input + *inOutIdx - add, 04614 size + add, ssl->heap); 04615 AddLateRecordHeader(&ssl->curRL, &ssl->timeoutInfo); 04616 } 04617 #endif 04618 04619 if (ssl->options.handShakeState == HANDSHAKE_DONE && 04620 type != session_ticket && type != certificate_request && 04621 type != key_update) { 04622 WOLFSSL_MSG("HandShake message after handshake complete"); 04623 SendAlert(ssl, alert_fatal, unexpected_message); 04624 return OUT_OF_ORDER_E; 04625 } 04626 04627 if (ssl->options.side == WOLFSSL_CLIENT_END && !ssl->options.dtls && 04628 ssl->options.serverState == NULL_STATE && 04629 type != server_hello && type != hello_retry_request) { 04630 WOLFSSL_MSG("First server message not server hello"); 04631 SendAlert(ssl, alert_fatal, unexpected_message); 04632 return OUT_OF_ORDER_E; 04633 } 04634 04635 if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->options.dtls && 04636 type == server_hello_done && 04637 ssl->options.serverState < SERVER_HELLO_COMPLETE) { 04638 WOLFSSL_MSG("Server hello done received before server hello in DTLS"); 04639 SendAlert(ssl, alert_fatal, unexpected_message); 04640 return OUT_OF_ORDER_E; 04641 } 04642 04643 if (ssl->options.side == WOLFSSL_SERVER_END && 04644 ssl->options.clientState == NULL_STATE && type != client_hello) { 04645 WOLFSSL_MSG("First client message not client hello"); 04646 SendAlert(ssl, alert_fatal, unexpected_message); 04647 return OUT_OF_ORDER_E; 04648 } 04649 04650 /* above checks handshake state */ 04651 switch (type) { 04652 04653 #ifndef NO_WOLFSSL_CLIENT 04654 case hello_retry_request: 04655 WOLFSSL_MSG("processing hello rety request"); 04656 ret = DoTls13HelloRetryRequest(ssl, input, inOutIdx, size); 04657 break; 04658 04659 case server_hello: 04660 WOLFSSL_MSG("processing server hello"); 04661 ret = DoTls13ServerHello(ssl, input, inOutIdx, size); 04662 break; 04663 04664 #ifndef NO_CERTS 04665 case certificate_request: 04666 WOLFSSL_MSG("processing certificate request"); 04667 ret = DoTls13CertificateRequest(ssl, input, inOutIdx, size); 04668 break; 04669 #endif 04670 04671 case session_ticket: 04672 WOLFSSL_MSG("processing new session ticket"); 04673 ret = DoTls13NewSessionTicket(ssl, input, inOutIdx, size); 04674 break; 04675 04676 case encrypted_extensions: 04677 WOLFSSL_MSG("processing encrypted extensions"); 04678 ret = DoTls13EncryptedExtensions(ssl, input, inOutIdx, size); 04679 break; 04680 #endif /* !NO_WOLFSSL_CLIENT */ 04681 04682 #ifndef NO_CERTS 04683 case certificate: 04684 WOLFSSL_MSG("processing certificate"); 04685 ret = DoTls13Certificate(ssl, input, inOutIdx, size); 04686 break; 04687 #endif 04688 04689 #if !defined(NO_RSA) || defined(HAVE_ECC) 04690 case certificate_verify: 04691 WOLFSSL_MSG("processing certificate verify"); 04692 ret = DoTls13CertificateVerify(ssl, input, inOutIdx, size); 04693 break; 04694 #endif /* !NO_RSA || HAVE_ECC */ 04695 04696 case finished: 04697 WOLFSSL_MSG("processing finished"); 04698 ret = DoTls13Finished(ssl, input, inOutIdx, size, totalSz, NO_SNIFF); 04699 break; 04700 04701 case key_update: 04702 WOLFSSL_MSG("processing finished"); 04703 ret = DoTls13KeyUpdate(ssl, input, inOutIdx, size); 04704 break; 04705 04706 #ifndef NO_WOLFSSL_SERVER 04707 case client_hello: 04708 WOLFSSL_MSG("processing client hello"); 04709 ret = DoTls13ClientHello(ssl, input, inOutIdx, size); 04710 break; 04711 #endif /* !NO_WOLFSSL_SERVER */ 04712 04713 default: 04714 WOLFSSL_MSG("Unknown handshake message type"); 04715 ret = UNKNOWN_HANDSHAKE_TYPE; 04716 break; 04717 } 04718 04719 if (ret == 0 && type != client_hello && type != session_ticket && 04720 type != key_update && ssl->error != WC_PENDING_E) { 04721 ret = HashInput(ssl, input + inIdx, size); 04722 } 04723 04724 if (ret == BUFFER_ERROR || ret == MISSING_HANDSHAKE_DATA) 04725 SendAlert(ssl, alert_fatal, decode_error); 04726 04727 if (ret == EXT_NOT_ALLOWED || ret == PEER_KEY_ERROR || 04728 ret == ECC_PEERKEY_ERROR || ret == BAD_KEY_SHARE_DATA || 04729 ret == PSK_KEY_ERROR || ret == INVALID_PARAMETER) { 04730 SendAlert(ssl, alert_fatal, illegal_parameter); 04731 } 04732 04733 if (ssl->options.tls1_3) { 04734 if (type == server_hello && ssl->options.side == WOLFSSL_CLIENT_END) { 04735 if ((ret = DeriveEarlySecret(ssl)) != 0) 04736 return ret; 04737 if ((ret = DeriveHandshakeSecret(ssl)) != 0) 04738 return ret; 04739 if ((ret = DeriveTls13Keys(ssl, handshake_key, 04740 ENCRYPT_AND_DECRYPT_SIDE)) != 0) 04741 return ret; 04742 04743 /* setup decrypt keys for following messages */ 04744 if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0) 04745 return ret; 04746 if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0) 04747 return ret; 04748 } 04749 04750 if (type == finished && ssl->options.side == WOLFSSL_CLIENT_END) { 04751 if ((ret = DeriveMasterSecret(ssl)) != 0) 04752 return ret; 04753 if ((ret = DeriveTls13Keys(ssl, traffic_key, 04754 ENCRYPT_AND_DECRYPT_SIDE)) != 0) 04755 return ret; 04756 } 04757 04758 #ifndef NO_PSK 04759 if (type == finished && ssl->options.side == WOLFSSL_SERVER_END) 04760 DeriveResumptionSecret(ssl, ssl->session.masterSecret); 04761 #endif 04762 } 04763 04764 #ifdef WOLFSSL_ASYNC_CRYPT 04765 /* if async, offset index so this msg will be processed again */ 04766 if (ret == WC_PENDING_E) { 04767 *inOutIdx -= HANDSHAKE_HEADER_SZ; 04768 } 04769 #endif 04770 04771 WOLFSSL_LEAVE("DoTls13HandShakeMsgType()", ret); 04772 return ret; 04773 } 04774 04775 04776 /* Handle a handshake message that has been received. 04777 * 04778 * ssl The SSL/TLS object. 04779 * input The message buffer. 04780 * inOutIdx On entry, the index into the buffer of the current message. 04781 * On exit, the index into the buffer of the next message. 04782 * totalSz Length of remaining data in the message buffer. 04783 * returns 0 on success and otherwise failure. 04784 */ 04785 int DoTls13HandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx, 04786 word32 totalSz) 04787 { 04788 int ret = 0; 04789 word32 inputLength; 04790 04791 WOLFSSL_ENTER("DoTls13HandShakeMsg()"); 04792 04793 if (ssl->arrays == NULL) { 04794 byte type; 04795 word32 size; 04796 04797 if (GetHandshakeHeader(ssl,input,inOutIdx,&type, &size, totalSz) != 0) 04798 return PARSE_ERROR; 04799 04800 return DoTls13HandShakeMsgType(ssl, input, inOutIdx, type, size, 04801 totalSz); 04802 } 04803 04804 inputLength = ssl->buffers.inputBuffer.length - *inOutIdx; 04805 04806 /* If there is a pending fragmented handshake message, 04807 * pending message size will be non-zero. */ 04808 if (ssl->arrays->pendingMsgSz == 0) { 04809 byte type; 04810 word32 size; 04811 04812 if (GetHandshakeHeader(ssl,input, inOutIdx, &type, &size, totalSz) != 0) 04813 return PARSE_ERROR; 04814 04815 /* Cap the maximum size of a handshake message to something reasonable. 04816 * By default is the maximum size of a certificate message assuming 04817 * nine 2048-bit RSA certificates in the chain. */ 04818 if (size > MAX_HANDSHAKE_SZ) { 04819 WOLFSSL_MSG("Handshake message too large"); 04820 return HANDSHAKE_SIZE_ERROR; 04821 } 04822 04823 /* size is the size of the certificate message payload */ 04824 if (inputLength - HANDSHAKE_HEADER_SZ < size) { 04825 ssl->arrays->pendingMsgType = type; 04826 ssl->arrays->pendingMsgSz = size + HANDSHAKE_HEADER_SZ; 04827 ssl->arrays->pendingMsg = (byte*)XMALLOC(size + HANDSHAKE_HEADER_SZ, 04828 ssl->heap, 04829 DYNAMIC_TYPE_ARRAYS); 04830 if (ssl->arrays->pendingMsg == NULL) 04831 return MEMORY_E; 04832 XMEMCPY(ssl->arrays->pendingMsg, 04833 input + *inOutIdx - HANDSHAKE_HEADER_SZ, 04834 inputLength); 04835 ssl->arrays->pendingMsgOffset = inputLength; 04836 *inOutIdx += inputLength - HANDSHAKE_HEADER_SZ; 04837 return 0; 04838 } 04839 04840 ret = DoTls13HandShakeMsgType(ssl, input, inOutIdx, type, size, 04841 totalSz); 04842 } 04843 else { 04844 if (inputLength + ssl->arrays->pendingMsgOffset > 04845 ssl->arrays->pendingMsgSz) { 04846 return BUFFER_ERROR; 04847 } 04848 04849 XMEMCPY(ssl->arrays->pendingMsg + ssl->arrays->pendingMsgOffset, 04850 input + *inOutIdx, inputLength); 04851 ssl->arrays->pendingMsgOffset += inputLength; 04852 *inOutIdx += inputLength; 04853 04854 if (ssl->arrays->pendingMsgOffset == ssl->arrays->pendingMsgSz) 04855 { 04856 word32 idx = 0; 04857 ret = DoTls13HandShakeMsgType(ssl, 04858 ssl->arrays->pendingMsg + HANDSHAKE_HEADER_SZ, 04859 &idx, ssl->arrays->pendingMsgType, 04860 ssl->arrays->pendingMsgSz - HANDSHAKE_HEADER_SZ, 04861 ssl->arrays->pendingMsgSz); 04862 XFREE(ssl->arrays->pendingMsg, ssl->heap, DYNAMIC_TYPE_ARRAYS); 04863 ssl->arrays->pendingMsg = NULL; 04864 ssl->arrays->pendingMsgSz = 0; 04865 } 04866 } 04867 04868 WOLFSSL_LEAVE("DoTls13HandShakeMsg()", ret); 04869 return ret; 04870 } 04871 04872 /* The client connecting to the server. 04873 * The protocol version is expecting to be TLS v1.3. 04874 * If the server downgrades, and older versions of the protocol are compiled 04875 * in, the client will fallback to wolfSSL_connect(). 04876 * Please see note at top of README if you get an error from connect. 04877 * 04878 * ssl The SSL/TLS object. 04879 * returns SSL_SUCCESS on successful handshake, SSL_FATAL_ERROR when 04880 * unrecoverable error occurs and 0 otherwise. 04881 * For more error information use wolfSSL_get_error(). 04882 */ 04883 int wolfSSL_connect_TLSv13(WOLFSSL* ssl) 04884 { 04885 int neededState; 04886 04887 WOLFSSL_ENTER("wolfSSL_connect_TLSv13()"); 04888 04889 #ifdef HAVE_ERRNO_H 04890 errno = 0; 04891 #endif 04892 04893 if (ssl->options.side != WOLFSSL_CLIENT_END) { 04894 WOLFSSL_ERROR(ssl->error = SIDE_ERROR); 04895 return SSL_FATAL_ERROR; 04896 } 04897 04898 if (ssl->buffers.outputBuffer.length > 0) { 04899 if ((ssl->error = SendBuffered(ssl)) == 0) { 04900 /* fragOffset is non-zero when sending fragments. On the last 04901 * fragment, fragOffset is zero again, and the state can be 04902 * advanced. */ 04903 if (ssl->fragOffset == 0) { 04904 ssl->options.connectState++; 04905 WOLFSSL_MSG("connect state: " 04906 "Advanced from last buffered fragment send"); 04907 } 04908 else { 04909 WOLFSSL_MSG("connect state: " 04910 "Not advanced, more fragments to send"); 04911 } 04912 } 04913 else { 04914 WOLFSSL_ERROR(ssl->error); 04915 return SSL_FATAL_ERROR; 04916 } 04917 } 04918 04919 switch (ssl->options.connectState) { 04920 04921 case CONNECT_BEGIN: 04922 /* Always send client hello first. */ 04923 if ((ssl->error = SendTls13ClientHello(ssl)) != 0) { 04924 WOLFSSL_ERROR(ssl->error); 04925 return SSL_FATAL_ERROR; 04926 } 04927 04928 ssl->options.connectState = CLIENT_HELLO_SENT; 04929 WOLFSSL_MSG("connect state: CLIENT_HELLO_SENT"); 04930 04931 case CLIENT_HELLO_SENT: 04932 neededState = ssl->options.resuming ? SERVER_FINISHED_COMPLETE : 04933 SERVER_HELLODONE_COMPLETE; 04934 /* Get the response/s from the server. */ 04935 while (ssl->options.serverState < neededState) { 04936 if ((ssl->error = ProcessReply(ssl)) < 0) { 04937 WOLFSSL_ERROR(ssl->error); 04938 return SSL_FATAL_ERROR; 04939 } 04940 /* if resumption failed, reset needed state. */ 04941 if (neededState == SERVER_FINISHED_COMPLETE && 04942 !ssl->options.resuming) { 04943 neededState = SERVER_HELLODONE_COMPLETE; 04944 } 04945 } 04946 04947 ssl->options.connectState = HELLO_AGAIN; 04948 WOLFSSL_MSG("connect state: HELLO_AGAIN"); 04949 case HELLO_AGAIN: 04950 if (ssl->options.certOnly) 04951 return SSL_SUCCESS; 04952 04953 if (!ssl->options.tls1_3) 04954 return wolfSSL_connect(ssl); 04955 04956 if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST) { 04957 ssl->options.serverState = NULL_STATE; 04958 /* Try again with different security parameters. */ 04959 if ((ssl->error = SendTls13ClientHello(ssl)) != 0) { 04960 WOLFSSL_ERROR(ssl->error); 04961 return SSL_FATAL_ERROR; 04962 } 04963 } 04964 04965 ssl->options.connectState = HELLO_AGAIN_REPLY; 04966 WOLFSSL_MSG("connect state: HELLO_AGAIN_REPLY"); 04967 04968 case HELLO_AGAIN_REPLY: 04969 if (ssl->options.serverState == NULL_STATE) { 04970 neededState = ssl->options.resuming ? SERVER_FINISHED_COMPLETE : 04971 SERVER_HELLODONE_COMPLETE; 04972 04973 /* Get the response/s from the server. */ 04974 while (ssl->options.serverState < neededState) { 04975 if ((ssl->error = ProcessReply(ssl)) < 0) { 04976 WOLFSSL_ERROR(ssl->error); 04977 return SSL_FATAL_ERROR; 04978 } 04979 /* if resumption failed, reset needed state */ 04980 else if (neededState == SERVER_FINISHED_COMPLETE) { 04981 if (!ssl->options.resuming) 04982 neededState = SERVER_HELLODONE_COMPLETE; 04983 } 04984 } 04985 } 04986 04987 ssl->options.connectState = FIRST_REPLY_DONE; 04988 WOLFSSL_MSG("connect state: FIRST_REPLY_DONE"); 04989 04990 case FIRST_REPLY_DONE: 04991 #ifndef NO_CERTS 04992 if (!ssl->options.resuming && ssl->options.sendVerify) { 04993 ssl->error = SendTls13Certificate(ssl); 04994 if (ssl->error != 0) { 04995 WOLFSSL_ERROR(ssl->error); 04996 return SSL_FATAL_ERROR; 04997 } 04998 WOLFSSL_MSG("sent: certificate"); 04999 } 05000 #endif 05001 05002 ssl->options.connectState = FIRST_REPLY_FIRST; 05003 WOLFSSL_MSG("connect state: FIRST_REPLY_FIRST"); 05004 05005 case FIRST_REPLY_FIRST: 05006 #ifndef NO_CERTS 05007 if (!ssl->options.resuming && ssl->options.sendVerify) { 05008 ssl->error = SendTls13CertificateVerify(ssl); 05009 if (ssl->error != 0) { 05010 WOLFSSL_ERROR(ssl->error); 05011 return SSL_FATAL_ERROR; 05012 } 05013 WOLFSSL_MSG("sent: certificate verify"); 05014 } 05015 #endif 05016 05017 ssl->options.connectState = FIRST_REPLY_SECOND; 05018 WOLFSSL_MSG("connect state: FIRST_REPLY_SECOND"); 05019 05020 case FIRST_REPLY_SECOND: 05021 if ((ssl->error = SendTls13Finished(ssl)) != 0) { 05022 WOLFSSL_ERROR(ssl->error); 05023 return SSL_FATAL_ERROR; 05024 } 05025 WOLFSSL_MSG("sent: finished"); 05026 05027 ssl->options.connectState = FINISHED_DONE; 05028 WOLFSSL_MSG("connect state: FINISHED_DONE"); 05029 05030 case FINISHED_DONE: 05031 #ifndef NO_HANDSHAKE_DONE_CB 05032 if (ssl->hsDoneCb != NULL) { 05033 int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx); 05034 if (cbret < 0) { 05035 ssl->error = cbret; 05036 WOLFSSL_MSG("HandShake Done Cb don't continue error"); 05037 return SSL_FATAL_ERROR; 05038 } 05039 } 05040 #endif /* NO_HANDSHAKE_DONE_CB */ 05041 05042 WOLFSSL_LEAVE("SSL_connect()", SSL_SUCCESS); 05043 return SSL_SUCCESS; 05044 05045 default: 05046 WOLFSSL_MSG("Unknown connect state ERROR"); 05047 return SSL_FATAL_ERROR; /* unknown connect state */ 05048 } 05049 } 05050 05051 /* Create a key share entry from group. 05052 * Generates a key pair. 05053 * 05054 * ssl The SSL/TLS object. 05055 * group The named group. 05056 * returns 0 on success, otherwise failure. 05057 */ 05058 int wolfSSL_UseKeyShare(WOLFSSL* ssl, word16 group) 05059 { 05060 int ret = BAD_FUNC_ARG; 05061 05062 if (ssl == NULL) 05063 return BAD_FUNC_ARG; 05064 05065 ret = TLSX_KeyShare_Use(ssl, group, 0, NULL, NULL); 05066 if (ret != 0) 05067 return ret; 05068 05069 return SSL_SUCCESS; 05070 } 05071 05072 /* Send no key share entries - use HelloRetryRequest to negotiate shared group. 05073 * 05074 * ssl The SSL/TLS object. 05075 * returns 0 on success, otherwise failure. 05076 */ 05077 int wolfSSL_NoKeyShares(WOLFSSL* ssl) 05078 { 05079 int ret = BAD_FUNC_ARG; 05080 05081 if (ssl == NULL) 05082 return BAD_FUNC_ARG; 05083 05084 ret = TLSX_KeyShare_Empty(ssl); 05085 if (ret != 0) 05086 return ret; 05087 05088 return SSL_SUCCESS; 05089 } 05090 05091 /* Do not send a ticket after TLS v1.3 handshake for resumption. 05092 * 05093 * ctx The SSL/TLS CTX object. 05094 * returns BAD_FUNC_ARG when ctx is NULL and 0 on success. 05095 */ 05096 int wolfSSL_CTX_no_ticket_TLSv13(WOLFSSL_CTX* ctx) 05097 { 05098 if (ctx == NULL) 05099 return BAD_FUNC_ARG; 05100 05101 #ifdef HAVE_SESSION_TICKET 05102 ctx->noTicketTls13 = 1; 05103 #endif 05104 05105 return 0; 05106 } 05107 05108 /* Do not send a ticket after TLS v1.3 handshake for resumption. 05109 * 05110 * ssl The SSL/TLS object. 05111 * returns BAD_FUNC_ARG when ssl is NULL, not using TLS v1.3, or called on 05112 * a client and 0 on success. 05113 */ 05114 int wolfSSL_no_ticket_TLSv13(WOLFSSL* ssl) 05115 { 05116 if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version) || 05117 ssl->options.side == WOLFSSL_CLIENT_END) 05118 return BAD_FUNC_ARG; 05119 05120 #ifdef HAVE_SESSION_TICKET 05121 ssl->options.noTicketTls13 = 1; 05122 #endif 05123 05124 return 0; 05125 } 05126 05127 /* Disallow (EC)DHE key exchange when using pre-shared keys. 05128 * 05129 * ctx The SSL/TLS CTX object. 05130 * returns BAD_FUNC_ARG when ctx is NULL and 0 on success. 05131 */ 05132 int wolfSSL_CTX_no_dhe_psk(WOLFSSL_CTX* ctx) 05133 { 05134 if (ctx == NULL) 05135 return BAD_FUNC_ARG; 05136 05137 ctx->noPskDheKe = 1; 05138 05139 return 0; 05140 } 05141 05142 /* Disallow (EC)DHE key exchange when using pre-shared keys. 05143 * 05144 * ssl The SSL/TLS object. 05145 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3 and 0 on 05146 * success. 05147 */ 05148 int wolfSSL_no_dhe_psk(WOLFSSL* ssl) 05149 { 05150 if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version)) 05151 return BAD_FUNC_ARG; 05152 05153 ssl->options.noPskDheKe = 1; 05154 05155 return 0; 05156 } 05157 05158 /* Update the keys for encryption and decryption. 05159 * If using non-blocking I/O and SSL_ERROR_WANT_WRITE is returned then 05160 * calling wolfSSL_write() will have the message sent when ready. 05161 * 05162 * ssl The SSL/TLS object. 05163 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3, 05164 * SSL_ERROR_WANT_WRITE when non-blocking I/O is not ready to write, 05165 * SSL_SUCCESS on success and otherwise failure. 05166 */ 05167 int wolfSSL_update_keys(WOLFSSL* ssl) 05168 { 05169 int ret; 05170 05171 if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version)) 05172 return BAD_FUNC_ARG; 05173 05174 ret = SendTls13KeyUpdate(ssl); 05175 if (ret == WANT_WRITE) 05176 ret = SSL_ERROR_WANT_WRITE; 05177 else if (ret == 0) 05178 ret = SSL_SUCCESS; 05179 return ret; 05180 } 05181 05182 /* The server accepting a connection from a client. 05183 * The protocol version is expecting to be TLS v1.3. 05184 * If the client downgrades, and older versions of the protocol are compiled 05185 * in, the server will fallback to wolfSSL_accept(). 05186 * Please see note at top of README if you get an error from accept. 05187 * 05188 * ssl The SSL/TLS object. 05189 * returns SSL_SUCCESS on successful handshake, SSL_FATAL_ERROR when 05190 * unrecoverable error occurs and 0 otherwise. 05191 * For more error information use wolfSSL_get_error(). 05192 */ 05193 int wolfSSL_accept_TLSv13(WOLFSSL* ssl) 05194 { 05195 word16 havePSK = 0; 05196 word16 haveAnon = 0; 05197 WOLFSSL_ENTER("SSL_accept_TLSv13()"); 05198 05199 #ifdef HAVE_ERRNO_H 05200 errno = 0; 05201 #endif 05202 05203 #ifndef NO_PSK 05204 havePSK = ssl->options.havePSK; 05205 #endif 05206 (void)havePSK; 05207 05208 #ifdef HAVE_ANON 05209 haveAnon = ssl->options.haveAnon; 05210 #endif 05211 (void)haveAnon; 05212 05213 if (ssl->options.side != WOLFSSL_SERVER_END) { 05214 WOLFSSL_ERROR(ssl->error = SIDE_ERROR); 05215 return SSL_FATAL_ERROR; 05216 } 05217 05218 #ifndef NO_CERTS 05219 /* in case used set_accept_state after init */ 05220 if (!havePSK && !haveAnon && 05221 (!ssl->buffers.certificate || 05222 !ssl->buffers.certificate->buffer || 05223 !ssl->buffers.key || 05224 !ssl->buffers.key->buffer)) { 05225 WOLFSSL_MSG("accept error: don't have server cert and key"); 05226 ssl->error = NO_PRIVATE_KEY; 05227 WOLFSSL_ERROR(ssl->error); 05228 return SSL_FATAL_ERROR; 05229 } 05230 #endif 05231 #ifdef WOLFSSL_DTLS 05232 if (ssl->version.major == DTLS_MAJOR) { 05233 ssl->options.dtls = 1; 05234 ssl->options.tls = 1; 05235 ssl->options.tls1_1 = 1; 05236 } 05237 #endif 05238 05239 if (ssl->buffers.outputBuffer.length > 0) { 05240 if ((ssl->error = SendBuffered(ssl)) == 0) { 05241 /* fragOffset is non-zero when sending fragments. On the last 05242 * fragment, fragOffset is zero again, and the state can be 05243 * advanced. */ 05244 if (ssl->fragOffset == 0) { 05245 ssl->options.acceptState++; 05246 WOLFSSL_MSG("accept state: " 05247 "Advanced from last buffered fragment send"); 05248 } 05249 else { 05250 WOLFSSL_MSG("accept state: " 05251 "Not advanced, more fragments to send"); 05252 } 05253 } 05254 else { 05255 WOLFSSL_ERROR(ssl->error); 05256 return SSL_FATAL_ERROR; 05257 } 05258 } 05259 05260 switch (ssl->options.acceptState) { 05261 05262 case ACCEPT_BEGIN : 05263 /* get response */ 05264 while (ssl->options.clientState < CLIENT_HELLO_COMPLETE) 05265 if ((ssl->error = ProcessReply(ssl)) < 0) { 05266 WOLFSSL_ERROR(ssl->error); 05267 return SSL_FATAL_ERROR; 05268 } 05269 05270 ssl->options.acceptState = ACCEPT_CLIENT_HELLO_DONE; 05271 WOLFSSL_MSG("accept state ACCEPT_CLIENT_HELLO_DONE"); 05272 05273 case ACCEPT_CLIENT_HELLO_DONE : 05274 if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST) { 05275 if ((ssl->error = SendTls13HelloRetryRequest(ssl)) != 0) { 05276 WOLFSSL_ERROR(ssl->error); 05277 return SSL_FATAL_ERROR; 05278 } 05279 } 05280 ssl->options.acceptState = ACCEPT_HELLO_RETRY_REQUEST_DONE; 05281 WOLFSSL_MSG("accept state ACCEPT_HELLO_RETRY_REQUEST_DONE"); 05282 05283 case ACCEPT_HELLO_RETRY_REQUEST_DONE : 05284 if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST) { 05285 if ( (ssl->error = ProcessReply(ssl)) < 0) { 05286 WOLFSSL_ERROR(ssl->error); 05287 return SSL_FATAL_ERROR; 05288 } 05289 } 05290 ssl->options.acceptState = ACCEPT_FIRST_REPLY_DONE; 05291 WOLFSSL_MSG("accept state ACCEPT_FIRST_REPLY_DONE"); 05292 05293 case ACCEPT_FIRST_REPLY_DONE : 05294 if ((ssl->error = SendTls13ServerHello(ssl)) != 0) { 05295 WOLFSSL_ERROR(ssl->error); 05296 return SSL_FATAL_ERROR; 05297 } 05298 ssl->options.acceptState = SERVER_HELLO_SENT; 05299 WOLFSSL_MSG("accept state SERVER_HELLO_SENT"); 05300 05301 case SERVER_HELLO_SENT : 05302 if ((ssl->error = SendTls13EncryptedExtensions(ssl)) != 0) { 05303 WOLFSSL_ERROR(ssl->error); 05304 return SSL_FATAL_ERROR; 05305 } 05306 ssl->options.acceptState = SERVER_EXTENSIONS_SENT; 05307 WOLFSSL_MSG("accept state SERVER_EXTENSIONS_SENT"); 05308 case SERVER_EXTENSIONS_SENT : 05309 #ifndef NO_CERTS 05310 if (!ssl->options.resuming) 05311 if (ssl->options.verifyPeer) 05312 ssl->error = SendTls13CertificateRequest(ssl); 05313 if (ssl->error != 0) { 05314 WOLFSSL_ERROR(ssl->error); 05315 return SSL_FATAL_ERROR; 05316 } 05317 #endif 05318 ssl->options.acceptState = CERT_REQ_SENT; 05319 WOLFSSL_MSG("accept state CERT_REQ_SENT"); 05320 05321 case CERT_REQ_SENT : 05322 ssl->options.acceptState = KEY_EXCHANGE_SENT; 05323 #ifndef NO_CERTS 05324 if (!ssl->options.resuming) { 05325 if ((ssl->error = SendTls13Certificate(ssl)) != 0) { 05326 WOLFSSL_ERROR(ssl->error); 05327 return SSL_FATAL_ERROR; 05328 } 05329 } 05330 #endif 05331 ssl->options.acceptState = CERT_SENT; 05332 WOLFSSL_MSG("accept state CERT_SENT"); 05333 05334 case CERT_SENT : 05335 #ifndef NO_CERTS 05336 if (!ssl->options.resuming) { 05337 if ((ssl->error = SendTls13CertificateVerify(ssl)) != 0) { 05338 WOLFSSL_ERROR(ssl->error); 05339 return SSL_FATAL_ERROR; 05340 } 05341 } 05342 #endif 05343 ssl->options.acceptState = CERT_STATUS_SENT; 05344 WOLFSSL_MSG("accept state CERT_STATUS_SENT"); 05345 05346 case CERT_VERIFY_SENT : 05347 if ((ssl->error = SendTls13Finished(ssl)) != 0) { 05348 WOLFSSL_ERROR(ssl->error); 05349 return SSL_FATAL_ERROR; 05350 } 05351 05352 ssl->options.acceptState = ACCEPT_FINISHED_DONE; 05353 WOLFSSL_MSG("accept state ACCEPT_FINISHED_DONE"); 05354 05355 case ACCEPT_FINISHED_DONE : 05356 #ifdef HAVE_SESSION_TICKET 05357 /* TODO: [TLS13] Section 4.5.1 Note. */ 05358 if (!ssl->options.resuming && !ssl->options.verifyPeer && 05359 !ssl->options.noTicketTls13 && ssl->ctx->ticketEncCb != NULL) { 05360 if ((ssl->error = SendTls13NewSessionTicket(ssl)) != 0) { 05361 WOLFSSL_ERROR(ssl->error); 05362 return SSL_FATAL_ERROR; 05363 } 05364 } 05365 #endif /* HAVE_SESSION_TICKET */ 05366 ssl->options.acceptState = TICKET_SENT; 05367 WOLFSSL_MSG("accept state TICKET_SENT"); 05368 05369 case TICKET_SENT: 05370 while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) 05371 if ( (ssl->error = ProcessReply(ssl)) < 0) { 05372 WOLFSSL_ERROR(ssl->error); 05373 return SSL_FATAL_ERROR; 05374 } 05375 05376 ssl->options.acceptState = ACCEPT_SECOND_REPLY_DONE; 05377 WOLFSSL_MSG("accept state ACCEPT_SECOND_REPLY_DONE"); 05378 case ACCEPT_SECOND_REPLY_DONE : 05379 #ifdef HAVE_SESSION_TICKET 05380 if (!ssl->options.resuming && ssl->options.verifyPeer && 05381 !ssl->options.noTicketTls13 && ssl->ctx->ticketEncCb != NULL) { 05382 if ((ssl->error = SendTls13NewSessionTicket(ssl)) != 0) { 05383 WOLFSSL_ERROR(ssl->error); 05384 return SSL_FATAL_ERROR; 05385 } 05386 } 05387 #endif /* HAVE_SESSION_TICKET */ 05388 ssl->options.acceptState = ACCEPT_THIRD_REPLY_DONE; 05389 WOLFSSL_MSG("accept state ACCEPT_THIRD_REPLY_DONE"); 05390 05391 case ACCEPT_THIRD_REPLY_DONE: 05392 #ifndef NO_HANDSHAKE_DONE_CB 05393 if (ssl->hsDoneCb) { 05394 int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx); 05395 if (cbret < 0) { 05396 ssl->error = cbret; 05397 WOLFSSL_MSG("HandShake Done Cb don't continue error"); 05398 return SSL_FATAL_ERROR; 05399 } 05400 } 05401 #endif /* NO_HANDSHAKE_DONE_CB */ 05402 05403 #ifdef WOLFSSL_SESSION_EXPORT 05404 if (ssl->dtls_export) { 05405 if ((ssl->error = wolfSSL_send_session(ssl)) != 0) { 05406 WOLFSSL_MSG("Export DTLS session error"); 05407 WOLFSSL_ERROR(ssl->error); 05408 return SSL_FATAL_ERROR; 05409 } 05410 } 05411 #endif 05412 05413 WOLFSSL_LEAVE("SSL_accept()", SSL_SUCCESS); 05414 return SSL_SUCCESS; 05415 05416 default : 05417 WOLFSSL_MSG("Unknown accept state ERROR"); 05418 return SSL_FATAL_ERROR; 05419 } 05420 } 05421 05422 05423 #undef ERROR_OUT 05424 05425 #endif /* WOLFCRYPT_ONLY */ 05426 05427 #endif /* WOLFSSL_TLS13 */ 05428
Generated on Tue Jul 12 2022 23:31:02 by
1.7.2
