source: asp3_tinet_ecnl_rx/trunk/wolfssl-3.12.2/src/tls13.c@ 337

Last change on this file since 337 was 337, checked in by coas-nagasima, 6 years ago

ASP3版ECNLを追加

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-csrc;charset=UTF-8
File size: 222.3 KB
Line 
1/* tls13.c
2 *
3 * Copyright (C) 2006-2017 wolfSSL Inc.
4 *
5 * This file is part of wolfSSL.
6 *
7 * wolfSSL is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * wolfSSL is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
20 */
21
22
23/*
24 * WOLFSSL_TLS13_DRAFT_18
25 * Conform with Draft 18 of the TLS v1.3 specification.
26 * WOLFSSL_EARLY_DATA
27 * Allow 0-RTT Handshake using Early Data extensions and handshake message
28 * WOLFSSL_POST_HANDSHAKE_AUTH
29 * Allow TLS v1.3 code to perform post-handshake authentication of the
30 * client.
31 * WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
32 * Allow a NewSessionTicket message to be sent by server before Client's
33 * Finished message.
34 * See TLS v.13 specification, Section 4.6.1, Paragraph 4 (Note).
35 * TLS13_SUPPORTS_EXPORTERS
36 * Gaurd to compile out any code for exporter keys.
37 * Feature not supported yet.
38 */
39
40#ifdef HAVE_CONFIG_H
41 #include <config.h>
42#endif
43
44#include <wolfssl/wolfcrypt/settings.h>
45
46#ifdef WOLFSSL_TLS13
47#ifdef HAVE_SESSION_TICKET
48 #include <sys/time.h>
49#endif
50
51#ifndef WOLFCRYPT_ONLY
52
53#ifdef HAVE_ERRNO_H
54 #include <errno.h>
55#endif
56
57#include <wolfssl/internal.h>
58#include <wolfssl/error-ssl.h>
59#include <wolfssl/wolfcrypt/asn.h>
60#include <wolfssl/wolfcrypt/dh.h>
61#ifdef NO_INLINE
62 #include <wolfssl/wolfcrypt/misc.h>
63#else
64 #define WOLFSSL_MISC_INCLUDED
65 #include <wolfcrypt/src/misc.c>
66#endif
67
68#ifdef HAVE_NTRU
69 #include "libntruencrypt/ntru_crypto.h"
70#endif
71
72#if defined(DEBUG_WOLFSSL) || defined(WOLFSSL_DEBUG) || \
73 defined(CHACHA_AEAD_TEST) || defined(WOLFSSL_SESSION_EXPORT_DEBUG)
74 #if defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
75 #if MQX_USE_IO_OLD
76 #include <fio.h>
77 #else
78 #include <nio.h>
79 #endif
80 #else
81 #include <stdio.h>
82 #endif
83#endif
84
85#ifdef __sun
86 #include <sys/filio.h>
87#endif
88
89#ifndef TRUE
90 #define TRUE 1
91#endif
92#ifndef FALSE
93 #define FALSE 0
94#endif
95
96/* Set ret to error value and jump to label.
97 *
98 * err The error value to set.
99 * eLabel The label to jump to.
100 */
101#define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; }
102
103
104/* Extract data using HMAC, salt and input.
105 * RFC 5869 - HMAC-based Extract-and-Expand Key Derivation Function (HKDF)
106 *
107 * prk The generated pseudorandom key.
108 * salt The salt.
109 * saltLen The length of the salt.
110 * ikm The input keying material.
111 * ikmLen The length of the input keying material.
112 * mac The type of digest to use.
113 * returns 0 on success, otherwise failure.
114 */
115static int Tls13_HKDF_Extract(byte* prk, const byte* salt, int saltLen,
116 byte* ikm, int ikmLen, int mac)
117{
118 int ret;
119 int hash = 0;
120 int len = 0;
121
122 switch (mac) {
123 #ifndef NO_SHA256
124 case sha256_mac:
125 hash = WC_SHA256;
126 len = WC_SHA256_DIGEST_SIZE;
127 break;
128 #endif
129
130 #ifdef WOLFSSL_SHA384
131 case sha384_mac:
132 hash = WC_SHA384;
133 len = WC_SHA384_DIGEST_SIZE;
134 break;
135 #endif
136
137 #ifdef WOLFSSL_TLS13_TLS13_SHA512
138 case sha512_mac:
139 hash = WC_SHA512;
140 len = WC_SHA512_DIGEST_SIZE;
141 break;
142 #endif
143 }
144
145 /* When length is 0 then use zeroed data of digest length. */
146 if (ikmLen == 0) {
147 ikmLen = len;
148 XMEMSET(ikm, 0, len);
149 }
150
151#ifdef WOLFSSL_DEBUG_TLS
152 WOLFSSL_MSG(" Salt");
153 WOLFSSL_BUFFER(salt, saltLen);
154 WOLFSSL_MSG(" IKM");
155 WOLFSSL_BUFFER(ikm, ikmLen);
156#endif
157
158 ret = wc_HKDF_Extract(hash, salt, saltLen, ikm, ikmLen, prk);
159
160#ifdef WOLFSSL_DEBUG_TLS
161 WOLFSSL_MSG(" PRK");
162 WOLFSSL_BUFFER(prk, len);
163#endif
164
165 return ret;
166}
167
168/* Expand data using HMAC, salt and label and info.
169 * TLS v1.3 defines this function.
170 *
171 * okm The generated pseudorandom key - output key material.
172 * prk The salt - pseudo-random key.
173 * prkLen The length of the salt - pseudo-random key.
174 * protocol The TLS protocol label.
175 * protocolLen The length of the TLS protocol label.
176 * info The information to expand.
177 * infoLen The length of the information.
178 * digest The type of digest to use.
179 * returns 0 on success, otherwise failure.
180 */
181static int HKDF_Expand_Label(byte* okm, word32 okmLen,
182 const byte* prk, word32 prkLen,
183 const byte* protocol, word32 protocolLen,
184 const byte* label, word32 labelLen,
185 const byte* info, word32 infoLen,
186 int digest)
187{
188 int ret = 0;
189 int idx = 0;
190 byte data[MAX_HKDF_LABEL_SZ];
191
192 /* Output length. */
193 data[idx++] = okmLen >> 8;
194 data[idx++] = okmLen;
195 /* Length of protocol | label. */
196 data[idx++] = protocolLen + labelLen;
197 /* Protocol */
198 XMEMCPY(&data[idx], protocol, protocolLen);
199 idx += protocolLen;
200 /* Label */
201 XMEMCPY(&data[idx], label, labelLen);
202 idx += labelLen;
203 /* Length of hash of messages */
204 data[idx++] = infoLen;
205 /* Hash of messages */
206 XMEMCPY(&data[idx], info, infoLen);
207 idx += infoLen;
208
209#ifdef WOLFSSL_DEBUG_TLS
210 WOLFSSL_MSG(" PRK");
211 WOLFSSL_BUFFER(prk, prkLen);
212 WOLFSSL_MSG(" Info");
213 WOLFSSL_BUFFER(data, idx);
214#endif
215
216 ret = wc_HKDF_Expand(digest, prk, prkLen, data, idx, okm, okmLen);
217
218#ifdef WOLFSSL_DEBUG_TLS
219 WOLFSSL_MSG(" OKM");
220 WOLFSSL_BUFFER(okm, okmLen);
221#endif
222
223 ForceZero(data, idx);
224
225 return ret;
226}
227
228#ifdef WOLFSSL_TLS13_DRAFT_18
229/* Size of the TLS v1.3 label use when deriving keys. */
230#define TLS13_PROTOCOL_LABEL_SZ 9
231/* The protocol label for TLS v1.3. */
232static const byte tls13ProtocolLabel[TLS13_PROTOCOL_LABEL_SZ + 1] = "TLS 1.3, ";
233#else
234/* Size of the TLS v1.3 label use when deriving keys. */
235#define TLS13_PROTOCOL_LABEL_SZ 6
236/* The protocol label for TLS v1.3. */
237static const byte tls13ProtocolLabel[TLS13_PROTOCOL_LABEL_SZ + 1] = "tls13 ";
238#endif
239
240#if !defined(WOLFSSL_TLS13_DRAFT_18) || defined(HAVE_SESSION_TICKET) || \
241 !defined(NO_PSK)
242/* Derive a key from a message.
243 *
244 * ssl The SSL/TLS object.
245 * output The buffer to hold the derived key.
246 * outputLen The length of the derived key.
247 * secret The secret used to derive the key (HMAC secret).
248 * label The label used to distinguish the context.
249 * labelLen The length of the label.
250 * msg The message data to derive key from.
251 * msgLen The length of the message data to derive key from.
252 * hashAlgo The hash algorithm to use in the HMAC.
253 * returns 0 on success, otherwise failure.
254 */
255static int DeriveKeyMsg(WOLFSSL* ssl, byte* output, int outputLen,
256 const byte* secret, const byte* label, word32 labelLen,
257 byte* msg, int msgLen, int hashAlgo)
258{
259 byte hash[MAX_DIGEST_SIZE];
260 Digest digest;
261 word32 hashSz = 0;
262 const byte* protocol;
263 word32 protocolLen;
264 int digestAlg;
265 int ret = BAD_FUNC_ARG;
266
267 switch (hashAlgo) {
268#ifndef NO_WOLFSSL_SHA256
269 case sha256_mac:
270 ret = wc_InitSha256_ex(&digest.sha256, ssl->heap, INVALID_DEVID);
271 if (ret == 0) {
272 ret = wc_Sha256Update(&digest.sha256, msg, msgLen);
273 if (ret == 0)
274 ret = wc_Sha256Final(&digest.sha256, hash);
275 wc_Sha256Free(&digest.sha256);
276 }
277 hashSz = WC_SHA256_DIGEST_SIZE;
278 digestAlg = WC_SHA256;
279 break;
280#endif
281#ifdef WOLFSSL_SHA384
282 case sha384_mac:
283 ret = wc_InitSha384_ex(&digest.sha384, ssl->heap, INVALID_DEVID);
284 if (ret == 0) {
285 ret = wc_Sha384Update(&digest.sha384, msg, msgLen);
286 if (ret == 0)
287 ret = wc_Sha384Final(&digest.sha384, hash);
288 wc_Sha384Free(&digest.sha384);
289 }
290 hashSz = WC_SHA384_DIGEST_SIZE;
291 digestAlg = WC_SHA384;
292 break;
293#endif
294#ifdef WOLFSSL_TLS13_SHA512
295 case sha512_mac:
296 ret = wc_InitSha512_ex(&digest.sha512, ssl->heap, INVALID_DEVID);
297 if (ret == 0) {
298 ret = wc_Sha512Update(&digest.sha512, msg, msgLen);
299 if (ret == 0)
300 ret = wc_Sha512Final(&digest.sha512, hash);
301 wc_Sha512Free(&digest.sha512);
302 }
303 hashSz = WC_SHA512_DIGEST_SIZE;
304 digestAlg = WC_SHA512;
305 break;
306#endif
307 }
308
309 if (ret != 0)
310 return ret;
311
312 switch (ssl->version.minor) {
313 case TLSv1_3_MINOR:
314 protocol = tls13ProtocolLabel;
315 protocolLen = TLS13_PROTOCOL_LABEL_SZ;
316 break;
317
318 default:
319 return VERSION_ERROR;
320 }
321 if (outputLen == -1)
322 outputLen = hashSz;
323
324 return HKDF_Expand_Label(output, outputLen, secret, hashSz,
325 protocol, protocolLen, label, labelLen,
326 hash, hashSz, digestAlg);
327}
328#endif
329
330/* Derive a key.
331 *
332 * ssl The SSL/TLS object.
333 * output The buffer to hold the derived key.
334 * outputLen The length of the derived key.
335 * secret The secret used to derive the key (HMAC secret).
336 * label The label used to distinguish the context.
337 * labelLen The length of the label.
338 * hashAlgo The hash algorithm to use in the HMAC.
339 * includeMsgs Whether to include a hash of the handshake messages so far.
340 * returns 0 on success, otherwise failure.
341 */
342static int DeriveKey(WOLFSSL* ssl, byte* output, int outputLen,
343 const byte* secret, const byte* label, word32 labelLen,
344 int hashAlgo, int includeMsgs)
345{
346 int ret = 0;
347 byte hash[MAX_DIGEST_SIZE];
348 word32 hashSz = 0;
349 word32 hashOutSz = 0;
350 const byte* protocol;
351 word32 protocolLen;
352 int digestAlg = 0;
353
354 switch (hashAlgo) {
355 #ifndef NO_SHA256
356 case sha256_mac:
357 hashSz = WC_SHA256_DIGEST_SIZE;
358 digestAlg = WC_SHA256;
359 if (includeMsgs)
360 ret = wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash);
361 break;
362 #endif
363
364 #ifdef WOLFSSL_SHA384
365 case sha384_mac:
366 hashSz = WC_SHA384_DIGEST_SIZE;
367 digestAlg = WC_SHA384;
368 if (includeMsgs)
369 ret = wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash);
370 break;
371 #endif
372
373 #ifdef WOLFSSL_TLS13_SHA512
374 case sha512_mac:
375 hashSz = WC_SHA512_DIGEST_SIZE;
376 digestAlg = WC_SHA512;
377 if (includeMsgs)
378 ret = wc_Sha512GetHash(&ssl->hsHashes->hashSha512, hash);
379 break;
380 #endif
381 }
382 if (ret != 0)
383 return ret;
384
385 /* Only one protocol version defined at this time. */
386 protocol = tls13ProtocolLabel;
387 protocolLen = TLS13_PROTOCOL_LABEL_SZ;
388
389 if (outputLen == -1)
390 outputLen = hashSz;
391 if (includeMsgs)
392 hashOutSz = hashSz;
393
394 return HKDF_Expand_Label(output, outputLen, secret, hashSz,
395 protocol, protocolLen, label, labelLen,
396 hash, hashOutSz, digestAlg);
397}
398
399
400#ifndef NO_PSK
401#ifdef WOLFSSL_TLS13_DRAFT_18
402/* The length of the binder key label. */
403#define BINDER_KEY_LABEL_SZ 23
404/* The binder key label. */
405static const byte binderKeyLabel[BINDER_KEY_LABEL_SZ + 1] =
406 "external psk binder key";
407#else
408/* The length of the binder key label. */
409#define BINDER_KEY_LABEL_SZ 10
410/* The binder key label. */
411static const byte binderKeyLabel[BINDER_KEY_LABEL_SZ + 1] =
412 "ext binder";
413#endif
414/* Derive the binder key.
415 *
416 * ssl The SSL/TLS object.
417 * key The derived key.
418 * returns 0 on success, otherwise failure.
419 */
420static int DeriveBinderKey(WOLFSSL* ssl, byte* key)
421{
422 WOLFSSL_MSG("Derive Binder Key");
423 return DeriveKeyMsg(ssl, key, -1, ssl->arrays->secret,
424 binderKeyLabel, BINDER_KEY_LABEL_SZ,
425 NULL, 0, ssl->specs.mac_algorithm);
426}
427#endif /* !NO_PSK */
428
429#ifdef HAVE_SESSION_TICKET
430#ifdef WOLFSSL_TLS13_DRAFT_18
431/* The length of the binder key resume label. */
432#define BINDER_KEY_RESUME_LABEL_SZ 25
433/* The binder key resume label. */
434static const byte binderKeyResumeLabel[BINDER_KEY_RESUME_LABEL_SZ + 1] =
435 "resumption psk binder key";
436#else
437/* The length of the binder key resume label. */
438#define BINDER_KEY_RESUME_LABEL_SZ 10
439/* The binder key resume label. */
440static const byte binderKeyResumeLabel[BINDER_KEY_RESUME_LABEL_SZ + 1] =
441 "res binder";
442#endif
443/* Derive the binder resumption key.
444 *
445 * ssl The SSL/TLS object.
446 * key The derived key.
447 * returns 0 on success, otherwise failure.
448 */
449static int DeriveBinderKeyResume(WOLFSSL* ssl, byte* key)
450{
451 WOLFSSL_MSG("Derive Binder Key - Resumption");
452 return DeriveKeyMsg(ssl, key, -1, ssl->arrays->secret,
453 binderKeyResumeLabel, BINDER_KEY_RESUME_LABEL_SZ,
454 NULL, 0, ssl->specs.mac_algorithm);
455}
456#endif /* HAVE_SESSION_TICKET */
457
458#ifdef WOLFSSL_EARLY_DATA
459#ifdef WOLFSSL_TLS13_DRAFT_18
460/* The length of the early traffic label. */
461#define EARLY_TRAFFIC_LABEL_SZ 27
462/* The early traffic label. */
463static const byte earlyTrafficLabel[EARLY_TRAFFIC_LABEL_SZ + 1] =
464 "client early traffic secret";
465#else
466/* The length of the early traffic label. */
467#define EARLY_TRAFFIC_LABEL_SZ 11
468/* The early traffic label. */
469static const byte earlyTrafficLabel[EARLY_TRAFFIC_LABEL_SZ + 1] =
470 "c e traffic";
471#endif
472/* Derive the early traffic key.
473 *
474 * ssl The SSL/TLS object.
475 * key The derived key.
476 * returns 0 on success, otherwise failure.
477 */
478static int DeriveEarlyTrafficSecret(WOLFSSL* ssl, byte* key)
479{
480 WOLFSSL_MSG("Derive Early Traffic Secret");
481 return DeriveKey(ssl, key, -1, ssl->arrays->secret,
482 earlyTrafficLabel, EARLY_TRAFFIC_LABEL_SZ,
483 ssl->specs.mac_algorithm, 1);
484}
485
486#ifdef TLS13_SUPPORTS_EXPORTERS
487#ifdef WOLFSSL_TLS13_DRAFT_18
488/* The length of the early exporter label. */
489#define EARLY_EXPORTER_LABEL_SZ 28
490/* The early exporter label. */
491static const byte earlyExporterLabel[EARLY_EXPORTER_LABEL_SZ + 1] =
492 "early exporter master secret";
493#else
494/* The length of the early exporter label. */
495#define EARLY_EXPORTER_LABEL_SZ 12
496/* The early exporter label. */
497static const byte earlyExporterLabel[EARLY_EXPORTER_LABEL_SZ + 1] =
498 "e exp master";
499#endif
500/* Derive the early exporter key.
501 *
502 * ssl The SSL/TLS object.
503 * key The derived key.
504 * returns 0 on success, otherwise failure.
505 */
506static int DeriveEarlyExporterSecret(WOLFSSL* ssl, byte* key)
507{
508 WOLFSSL_MSG("Derive Early Exporter Secret");
509 return DeriveKey(ssl, key, -1, ssl->arrays->secret,
510 earlyExporterLabel, EARLY_EXPORTER_LABEL_SZ,
511 ssl->specs.mac_algorithm, 1);
512}
513#endif
514#endif
515
516#ifdef WOLFSSL_TLS13_DRAFT_18
517/* The length of the client hanshake label. */
518#define CLIENT_HANDSHAKE_LABEL_SZ 31
519/* The client hanshake label. */
520static const byte clientHandshakeLabel[CLIENT_HANDSHAKE_LABEL_SZ + 1] =
521 "client handshake traffic secret";
522#else
523/* The length of the client hanshake label. */
524#define CLIENT_HANDSHAKE_LABEL_SZ 12
525/* The client hanshake label. */
526static const byte clientHandshakeLabel[CLIENT_HANDSHAKE_LABEL_SZ + 1] =
527 "c hs traffic";
528#endif
529/* Derive the client handshake key.
530 *
531 * ssl The SSL/TLS object.
532 * key The derived key.
533 * returns 0 on success, otherwise failure.
534 */
535static int DeriveClientHandshakeSecret(WOLFSSL* ssl, byte* key)
536{
537 WOLFSSL_MSG("Derive Client Handshake Secret");
538 return DeriveKey(ssl, key, -1, ssl->arrays->preMasterSecret,
539 clientHandshakeLabel, CLIENT_HANDSHAKE_LABEL_SZ,
540 ssl->specs.mac_algorithm, 1);
541}
542
543#ifdef WOLFSSL_TLS13_DRAFT_18
544/* The length of the server handshake label. */
545#define SERVER_HANDSHAKE_LABEL_SZ 31
546/* The server handshake label. */
547static const byte serverHandshakeLabel[SERVER_HANDSHAKE_LABEL_SZ + 1] =
548 "server handshake traffic secret";
549#else
550/* The length of the server handshake label. */
551#define SERVER_HANDSHAKE_LABEL_SZ 12
552/* The server handshake label. */
553static const byte serverHandshakeLabel[SERVER_HANDSHAKE_LABEL_SZ + 1] =
554 "s hs traffic";
555#endif
556/* Derive the server handshake key.
557 *
558 * ssl The SSL/TLS object.
559 * key The derived key.
560 * returns 0 on success, otherwise failure.
561 */
562static int DeriveServerHandshakeSecret(WOLFSSL* ssl, byte* key)
563{
564 WOLFSSL_MSG("Derive Server Handshake Secret");
565 return DeriveKey(ssl, key, -1, ssl->arrays->preMasterSecret,
566 serverHandshakeLabel, SERVER_HANDSHAKE_LABEL_SZ,
567 ssl->specs.mac_algorithm, 1);
568}
569
570#ifdef WOLFSSL_TLS13_DRAFT_18
571/* The length of the client application traffic label. */
572#define CLIENT_APP_LABEL_SZ 33
573/* The client application traffic label. */
574static const byte clientAppLabel[CLIENT_APP_LABEL_SZ + 1] =
575 "client application traffic secret";
576#else
577/* The length of the client application traffic label. */
578#define CLIENT_APP_LABEL_SZ 12
579/* The client application traffic label. */
580static const byte clientAppLabel[CLIENT_APP_LABEL_SZ + 1] =
581 "c ap traffic";
582#endif
583/* Derive the client application traffic key.
584 *
585 * ssl The SSL/TLS object.
586 * key The derived key.
587 * returns 0 on success, otherwise failure.
588 */
589static int DeriveClientTrafficSecret(WOLFSSL* ssl, byte* key)
590{
591 WOLFSSL_MSG("Derive Client Traffic Secret");
592 return DeriveKey(ssl, key, -1, ssl->arrays->masterSecret,
593 clientAppLabel, CLIENT_APP_LABEL_SZ,
594 ssl->specs.mac_algorithm, 1);
595}
596
597#ifdef WOLFSSL_TLS13_DRAFT_18
598/* The length of the server application traffic label. */
599#define SERVER_APP_LABEL_SZ 33
600/* The server application traffic label. */
601static const byte serverAppLabel[SERVER_APP_LABEL_SZ + 1] =
602 "server application traffic secret";
603#else
604/* The length of the server application traffic label. */
605#define SERVER_APP_LABEL_SZ 12
606/* The server application traffic label. */
607static const byte serverAppLabel[SERVER_APP_LABEL_SZ + 1] =
608 "s ap traffic";
609#endif
610/* Derive the server application traffic key.
611 *
612 * ssl The SSL/TLS object.
613 * key The derived key.
614 * returns 0 on success, otherwise failure.
615 */
616static int DeriveServerTrafficSecret(WOLFSSL* ssl, byte* key)
617{
618 WOLFSSL_MSG("Derive Server Traffic Secret");
619 return DeriveKey(ssl, key, -1, ssl->arrays->masterSecret,
620 serverAppLabel, SERVER_APP_LABEL_SZ,
621 ssl->specs.mac_algorithm, 1);
622}
623
624#ifdef TLS13_SUPPORTS_EXPORTERS
625#ifdef WOLFSSL_TLS13_DRAFT_18
626/* The length of the exporter master secret label. */
627#define EXPORTER_MASTER_LABEL_SZ 22
628/* The exporter master secret label. */
629static const byte exporterMasterLabel[EXPORTER_MASTER_LABEL_SZ + 1] =
630 "exporter master secret";
631#else
632/* The length of the exporter master secret label. */
633#define EXPORTER_MASTER_LABEL_SZ 10
634/* The exporter master secret label. */
635static const byte exporterMasterLabel[EXPORTER_MASTER_LABEL_SZ + 1] =
636 "exp master";
637#endif
638/* Derive the exporter secret.
639 *
640 * ssl The SSL/TLS object.
641 * key The derived key.
642 * returns 0 on success, otherwise failure.
643 */
644static int DeriveExporterSecret(WOLFSSL* ssl, byte* key)
645{
646 WOLFSSL_MSG("Derive Exporter Secret");
647 return DeriveKey(ssl, key, -1, ssl->arrays->masterSecret,
648 exporterMasterLabel, EXPORTER_MASTER_LABEL_SZ,
649 ssl->specs.mac_algorithm, 1);
650}
651#endif
652
653#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
654#ifdef WOLFSSL_TLS13_DRAFT_18
655/* The length of the resumption master secret label. */
656#define RESUME_MASTER_LABEL_SZ 24
657/* The resumption master secret label. */
658static const byte resumeMasterLabel[RESUME_MASTER_LABEL_SZ + 1] =
659 "resumption master secret";
660#else
661/* The length of the resumption master secret label. */
662#define RESUME_MASTER_LABEL_SZ 10
663/* The resumption master secret label. */
664static const byte resumeMasterLabel[RESUME_MASTER_LABEL_SZ + 1] =
665 "res master";
666#endif
667/* Derive the resumption secret.
668 *
669 * ssl The SSL/TLS object.
670 * key The derived key.
671 * returns 0 on success, otherwise failure.
672 */
673static int DeriveResumptionSecret(WOLFSSL* ssl, byte* key)
674{
675 WOLFSSL_MSG("Derive Resumption Secret");
676 return DeriveKey(ssl, key, -1, ssl->arrays->masterSecret,
677 resumeMasterLabel, RESUME_MASTER_LABEL_SZ,
678 ssl->specs.mac_algorithm, 1);
679}
680#endif
681
682/* Length of the finished label. */
683#define FINISHED_LABEL_SZ 8
684/* Finished label for generating finished key. */
685static const byte finishedLabel[FINISHED_LABEL_SZ+1] = "finished";
686/* Derive the finished secret.
687 *
688 * ssl The SSL/TLS object.
689 * key The key to use with the HMAC.
690 * secret The derived secret.
691 * returns 0 on success, otherwise failure.
692 */
693static int DeriveFinishedSecret(WOLFSSL* ssl, byte* key, byte* secret)
694{
695 WOLFSSL_MSG("Derive Finished Secret");
696 return DeriveKey(ssl, secret, -1, key, finishedLabel, FINISHED_LABEL_SZ,
697 ssl->specs.mac_algorithm, 0);
698}
699
700#ifdef WOLFSSL_TLS13_DRAFT_18
701/* The length of the application traffic label. */
702#define APP_TRAFFIC_LABEL_SZ 26
703/* The application traffic label. */
704static const byte appTrafficLabel[APP_TRAFFIC_LABEL_SZ + 1] =
705 "application traffic secret";
706#else
707/* The length of the application traffic label. */
708#define APP_TRAFFIC_LABEL_SZ 11
709/* The application traffic label. */
710static const byte appTrafficLabel[APP_TRAFFIC_LABEL_SZ + 1] =
711 "traffic upd";
712#endif
713/* Update the traffic secret.
714 *
715 * ssl The SSL/TLS object.
716 * secret The previous secret and derived secret.
717 * returns 0 on success, otherwise failure.
718 */
719static int DeriveTrafficSecret(WOLFSSL* ssl, byte* secret)
720{
721 WOLFSSL_MSG("Derive New Application Traffic Secret");
722 return DeriveKey(ssl, secret, -1, secret,
723 appTrafficLabel, APP_TRAFFIC_LABEL_SZ,
724 ssl->specs.mac_algorithm, 0);
725}
726
727/* Derive the early secret using HKDF Extract.
728 *
729 * ssl The SSL/TLS object.
730 */
731static int DeriveEarlySecret(WOLFSSL* ssl)
732{
733 WOLFSSL_MSG("Derive Early Secret");
734#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
735 return Tls13_HKDF_Extract(ssl->arrays->secret, NULL, 0,
736 ssl->arrays->psk_key, ssl->arrays->psk_keySz,
737 ssl->specs.mac_algorithm);
738#else
739 return Tls13_HKDF_Extract(ssl->arrays->secret, NULL, 0,
740 ssl->arrays->masterSecret, 0, ssl->specs.mac_algorithm);
741#endif
742}
743
744#ifndef WOLFSSL_TLS13_DRAFT_18
745/* The length of the derived label. */
746#define DERIVED_LABEL_SZ 7
747/* The derived label. */
748static const byte derivedLabel[DERIVED_LABEL_SZ + 1] =
749 "derived";
750#endif
751/* Derive the handshake secret using HKDF Extract.
752 *
753 * ssl The SSL/TLS object.
754 */
755static int DeriveHandshakeSecret(WOLFSSL* ssl)
756{
757#ifdef WOLFSSL_TLS13_DRAFT_18
758 WOLFSSL_MSG("Derive Handshake Secret");
759 return Tls13_HKDF_Extract(ssl->arrays->preMasterSecret,
760 ssl->arrays->secret, ssl->specs.hash_size,
761 ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz,
762 ssl->specs.mac_algorithm);
763#else
764 byte key[WC_MAX_DIGEST_SIZE];
765 int ret;
766
767 WOLFSSL_MSG("Derive Handshake Secret");
768
769 ret = DeriveKeyMsg(ssl, key, -1, ssl->arrays->secret,
770 derivedLabel, DERIVED_LABEL_SZ,
771 NULL, 0, ssl->specs.mac_algorithm);
772 if (ret != 0)
773 return ret;
774
775 return Tls13_HKDF_Extract(ssl->arrays->preMasterSecret,
776 key, ssl->specs.hash_size,
777 ssl->arrays->preMasterSecret, ssl->arrays->preMasterSz,
778 ssl->specs.mac_algorithm);
779#endif
780}
781
782/* Derive the master secret using HKDF Extract.
783 *
784 * ssl The SSL/TLS object.
785 */
786static int DeriveMasterSecret(WOLFSSL* ssl)
787{
788#ifdef WOLFSSL_TLS13_DRAFT_18
789 WOLFSSL_MSG("Derive Master Secret");
790 return Tls13_HKDF_Extract(ssl->arrays->masterSecret,
791 ssl->arrays->preMasterSecret, ssl->specs.hash_size,
792 ssl->arrays->masterSecret, 0, ssl->specs.mac_algorithm);
793#else
794 byte key[WC_MAX_DIGEST_SIZE];
795 int ret;
796
797 WOLFSSL_MSG("Derive Master Secret");
798
799 ret = DeriveKeyMsg(ssl, key, -1, ssl->arrays->preMasterSecret,
800 derivedLabel, DERIVED_LABEL_SZ,
801 NULL, 0, ssl->specs.mac_algorithm);
802 if (ret != 0)
803 return ret;
804
805 return Tls13_HKDF_Extract(ssl->arrays->masterSecret,
806 key, ssl->specs.hash_size,
807 ssl->arrays->masterSecret, 0, ssl->specs.mac_algorithm);
808#endif
809}
810
811/* Calculate the HMAC of message data to this point.
812 *
813 * ssl The SSL/TLS object.
814 * key The HMAC key.
815 * hash The hash result - verify data.
816 * returns length of verify data generated.
817 */
818static int BuildTls13HandshakeHmac(WOLFSSL* ssl, byte* key, byte* hash,
819 word32* pHashSz)
820{
821 Hmac verifyHmac;
822 int hashType = WC_SHA256;
823 int hashSz = WC_SHA256_DIGEST_SIZE;
824 int ret = BAD_FUNC_ARG;
825
826 /* Get the hash of the previous handshake messages. */
827 switch (ssl->specs.mac_algorithm) {
828 #ifndef NO_SHA256
829 case sha256_mac:
830 hashType = WC_SHA256;
831 hashSz = WC_SHA256_DIGEST_SIZE;
832 ret = wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash);
833 break;
834 #endif /* !NO_SHA256 */
835 #ifdef WOLFSSL_SHA384
836 case sha384_mac:
837 hashType = WC_SHA384;
838 hashSz = WC_SHA384_DIGEST_SIZE;
839 ret = wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash);
840 break;
841 #endif /* WOLFSSL_SHA384 */
842 #ifdef WOLFSSL_TLS13_SHA512
843 case sha512_mac:
844 hashType = WC_SHA512;
845 hashSz = WC_SHA512_DIGEST_SIZE;
846 ret = wc_Sha512GetHash(&ssl->hsHashes->hashSha512, hash);
847 break;
848 #endif /* WOLFSSL_TLS13_SHA512 */
849 }
850 if (ret != 0)
851 return ret;
852
853 /* Calculate the verify data. */
854 ret = wc_HmacInit(&verifyHmac, ssl->heap, ssl->devId);
855 if (ret == 0) {
856 ret = wc_HmacSetKey(&verifyHmac, hashType, key, ssl->specs.hash_size);
857 if (ret == 0)
858 ret = wc_HmacUpdate(&verifyHmac, hash, hashSz);
859 if (ret == 0)
860 ret = wc_HmacFinal(&verifyHmac, hash);
861 wc_HmacFree(&verifyHmac);
862 }
863
864 if (pHashSz)
865 *pHashSz = hashSz;
866
867 return ret;
868}
869
870/* The length of the label to use when deriving keys. */
871#define WRITE_KEY_LABEL_SZ 3
872/* The length of the label to use when deriving IVs. */
873#define WRITE_IV_LABEL_SZ 2
874/* The label to use when deriving keys. */
875static const byte writeKeyLabel[WRITE_KEY_LABEL_SZ+1] = "key";
876/* The label to use when deriving IVs. */
877static const byte writeIVLabel[WRITE_IV_LABEL_SZ+1] = "iv";
878
879/* Derive the keys and IVs for TLS v1.3.
880 *
881 * ssl The SSL/TLS object.
882 * sercret early_data_key when deriving the key and IV for encrypting early
883 * data application data and end_of_early_data messages.
884 * handshake_key when deriving keys and IVs for encrypting handshake
885 * messages.
886 * traffic_key when deriving first keys and IVs for encrypting
887 * traffic messages.
888 * update_traffic_key when deriving next keys and IVs for encrypting
889 * traffic messages.
890 * side ENCRYPT_SIDE_ONLY when only encryption secret needs to be derived.
891 * DECRYPT_SIDE_ONLY when only decryption secret needs to be derived.
892 * ENCRYPT_AND_DECRYPT_SIDE when both secret needs to be derived.
893 * store 1 indicates to derive the keys and IVs from derived secret and
894 * store ready for provisioning.
895 * returns 0 on success, otherwise failure.
896 */
897static int DeriveTls13Keys(WOLFSSL* ssl, int secret, int side, int store)
898{
899 int ret;
900 int i = 0;
901#ifdef WOLFSSL_SMALL_STACK
902 byte* key_dig;
903#else
904 byte key_dig[MAX_PRF_DIG];
905#endif
906 int provision;
907
908#ifdef WOLFSSL_SMALL_STACK
909 key_dig = (byte*)XMALLOC(MAX_PRF_DIG, ssl->heap, DYNAMIC_TYPE_DIGEST);
910 if (key_dig == NULL)
911 return MEMORY_E;
912#endif
913
914 if (side == ENCRYPT_AND_DECRYPT_SIDE) {
915 provision = PROVISION_CLIENT_SERVER;
916 }
917 else {
918 provision = ((ssl->options.side != WOLFSSL_CLIENT_END) ^
919 (side == ENCRYPT_SIDE_ONLY)) ? PROVISION_CLIENT :
920 PROVISION_SERVER;
921 }
922
923 /* Derive the appropriate secret to use in the HKDF. */
924 switch (secret) {
925#ifdef WOLFSSL_EARLY_DATA
926 case early_data_key:
927 ret = DeriveEarlyTrafficSecret(ssl, ssl->arrays->clientSecret);
928 if (ret != 0)
929 goto end;
930 break;
931#endif
932
933 case handshake_key:
934 if (provision & PROVISION_CLIENT) {
935 ret = DeriveClientHandshakeSecret(ssl,
936 ssl->arrays->clientSecret);
937 if (ret != 0)
938 goto end;
939 }
940 if (provision & PROVISION_SERVER) {
941 ret = DeriveServerHandshakeSecret(ssl,
942 ssl->arrays->serverSecret);
943 if (ret != 0)
944 goto end;
945 }
946 break;
947
948 case traffic_key:
949 if (provision & PROVISION_CLIENT) {
950 ret = DeriveClientTrafficSecret(ssl, ssl->arrays->clientSecret);
951 if (ret != 0)
952 goto end;
953 }
954 if (provision & PROVISION_SERVER) {
955 ret = DeriveServerTrafficSecret(ssl, ssl->arrays->serverSecret);
956 if (ret != 0)
957 goto end;
958 }
959 break;
960
961 case update_traffic_key:
962 if (provision & PROVISION_CLIENT) {
963 ret = DeriveTrafficSecret(ssl, ssl->arrays->clientSecret);
964 if (ret != 0)
965 goto end;
966 }
967 if (provision & PROVISION_SERVER) {
968 ret = DeriveTrafficSecret(ssl, ssl->arrays->serverSecret);
969 if (ret != 0)
970 goto end;
971 }
972 break;
973 }
974
975 if (!store)
976 goto end;
977
978 /* Key data = client key | server key | client IV | server IV */
979
980 if (provision & PROVISION_CLIENT) {
981 /* Derive the client key. */
982 WOLFSSL_MSG("Derive Client Key");
983 ret = DeriveKey(ssl, &key_dig[i], ssl->specs.key_size,
984 ssl->arrays->clientSecret, writeKeyLabel,
985 WRITE_KEY_LABEL_SZ, ssl->specs.mac_algorithm, 0);
986 if (ret != 0)
987 goto end;
988 i += ssl->specs.key_size;
989 }
990
991 if (provision & PROVISION_SERVER) {
992 /* Derive the server key. */
993 WOLFSSL_MSG("Derive Server Key");
994 ret = DeriveKey(ssl, &key_dig[i], ssl->specs.key_size,
995 ssl->arrays->serverSecret, writeKeyLabel,
996 WRITE_KEY_LABEL_SZ, ssl->specs.mac_algorithm, 0);
997 if (ret != 0)
998 goto end;
999 i += ssl->specs.key_size;
1000 }
1001
1002 if (provision & PROVISION_CLIENT) {
1003 /* Derive the client IV. */
1004 WOLFSSL_MSG("Derive Client IV");
1005 ret = DeriveKey(ssl, &key_dig[i], ssl->specs.iv_size,
1006 ssl->arrays->clientSecret, writeIVLabel,
1007 WRITE_IV_LABEL_SZ, ssl->specs.mac_algorithm, 0);
1008 if (ret != 0)
1009 goto end;
1010 i += ssl->specs.iv_size;
1011 }
1012
1013 if (provision & PROVISION_SERVER) {
1014 /* Derive the server IV. */
1015 WOLFSSL_MSG("Derive Server IV");
1016 ret = DeriveKey(ssl, &key_dig[i], ssl->specs.iv_size,
1017 ssl->arrays->serverSecret, writeIVLabel,
1018 WRITE_IV_LABEL_SZ, ssl->specs.mac_algorithm, 0);
1019 if (ret != 0)
1020 goto end;
1021 }
1022
1023 /* Store keys and IVs but don't activate them. */
1024 ret = StoreKeys(ssl, key_dig, provision);
1025
1026end:
1027#ifdef WOLFSSL_SMALL_STACK
1028 XFREE(key_dig, ssl->heap, DYNAMIC_TYPE_DIGEST);
1029#endif
1030
1031 return ret;
1032}
1033
1034#ifdef HAVE_SESSION_TICKET
1035#if defined(USER_TICKS)
1036#if 0
1037 word32 TimeNowInMilliseconds(void)
1038 {
1039 /*
1040 write your own clock tick function if don't want gettimeofday()
1041 needs millisecond accuracy but doesn't have to correlated to EPOCH
1042 */
1043 }
1044#endif
1045
1046#elif defined(TIME_OVERRIDES)
1047 #ifndef HAVE_TIME_T_TYPE
1048 typedef long time_t;
1049 #endif
1050 extern time_t XTIME(time_t * timer);
1051
1052 /* The time in milliseconds.
1053 * Used for tickets to represent difference between when first seen and when
1054 * sending.
1055 *
1056 * returns the time in milliseconds as a 32-bit value.
1057 */
1058 word32 TimeNowInMilliseconds(void)
1059 {
1060 return (word32) XTIME(0) * 1000;
1061 }
1062#elif defined(USE_WINDOWS_API)
1063 /* The time in milliseconds.
1064 * Used for tickets to represent difference between when first seen and when
1065 * sending.
1066 *
1067 * returns the time in milliseconds as a 32-bit value.
1068 */
1069 word32 TimeNowInMilliseconds(void)
1070 {
1071 static int init = 0;
1072 static LARGE_INTEGER freq;
1073 LARGE_INTEGER count;
1074
1075 if (!init) {
1076 QueryPerformanceFrequency(&freq);
1077 init = 1;
1078 }
1079
1080 QueryPerformanceCounter(&count);
1081
1082 return (word32)(count.QuadPart / (freq.QuadPart / 1000));
1083 }
1084
1085#elif defined(HAVE_RTP_SYS)
1086 #include "rtptime.h"
1087
1088 /* The time in milliseconds.
1089 * Used for tickets to represent difference between when first seen and when
1090 * sending.
1091 *
1092 * returns the time in milliseconds as a 32-bit value.
1093 */
1094 word32 TimeNowInMilliseconds(void)
1095 {
1096 return (word32)rtp_get_system_sec() * 1000;
1097 }
1098#elif defined(MICRIUM)
1099 /* The time in milliseconds.
1100 * Used for tickets to represent difference between when first seen and when
1101 * sending.
1102 *
1103 * returns the time in milliseconds as a 32-bit value.
1104 */
1105 word32 TimeNowInMilliseconds(void)
1106 {
1107 OS_TICK ticks = 0;
1108 OS_ERR err;
1109
1110 ticks = OSTimeGet(&err);
1111
1112 return (word32) (ticks / OSCfg_TickRate_Hz) * 1000;
1113 }
1114#elif defined(MICROCHIP_TCPIP_V5)
1115 /* The time in milliseconds.
1116 * Used for tickets to represent difference between when first seen and when
1117 * sending.
1118 *
1119 * returns the time in milliseconds as a 32-bit value.
1120 */
1121 word32 TimeNowInMilliseconds(void)
1122 {
1123 return (word32) (TickGet() / (TICKS_PER_SECOND / 1000));
1124 }
1125#elif defined(MICROCHIP_TCPIP)
1126 #if defined(MICROCHIP_MPLAB_HARMONY)
1127 #include <system/tmr/sys_tmr.h>
1128
1129 /* The time in milliseconds.
1130 * Used for tickets to represent difference between when first seen and when
1131 * sending.
1132 *
1133 * returns the time in milliseconds as a 32-bit value.
1134 */
1135 word32 TimeNowInMilliseconds(void)
1136 {
1137 return (word32)(SYS_TMR_TickCountGet() /
1138 (SYS_TMR_TickCounterFrequencyGet() / 1000));
1139 }
1140 #else
1141 /* The time in milliseconds.
1142 * Used for tickets to represent difference between when first seen and when
1143 * sending.
1144 *
1145 * returns the time in milliseconds as a 32-bit value.
1146 */
1147 word32 TimeNowInMilliseconds(void)
1148 {
1149 return (word32)(SYS_TICK_Get() / (SYS_TICK_TicksPerSecondGet() / 1000));
1150 }
1151
1152 #endif
1153
1154#elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
1155 /* The time in milliseconds.
1156 * Used for tickets to represent difference between when first seen and when
1157 * sending.
1158 *
1159 * returns the time in milliseconds as a 32-bit value.
1160 */
1161 word32 TimeNowInMilliseconds(void)
1162 {
1163 TIME_STRUCT mqxTime;
1164
1165 _time_get_elapsed(&mqxTime);
1166
1167 return (word32) mqxTime.SECONDS * 1000;
1168 }
1169#elif defined(FREESCALE_FREE_RTOS) || defined(FREESCALE_KSDK_FREERTOS)
1170 #include "include/task.h"
1171
1172 /* The time in milliseconds.
1173 * Used for tickets to represent difference between when first seen and when
1174 * sending.
1175 *
1176 * returns the time in milliseconds as a 32-bit value.
1177 */
1178 word32 TimeNowInMilliseconds(void)
1179 {
1180 return (unsigned int)(((float)xTaskGetTickCount()) /
1181 (configTICK_RATE_HZ / 1000));
1182 }
1183#elif defined(FREESCALE_KSDK_BM)
1184 #include "lwip/sys.h" /* lwIP */
1185
1186 /* The time in milliseconds.
1187 * Used for tickets to represent difference between when first seen and when
1188 * sending.
1189 *
1190 * returns the time in milliseconds as a 32-bit value.
1191 */
1192 word32 TimeNowInMilliseconds(void)
1193 {
1194 return sys_now();
1195 }
1196#elif defined(WOLFSSL_TIRTOS)
1197 /* The time in milliseconds.
1198 * Used for tickets to represent difference between when first seen and when
1199 * sending.
1200 *
1201 * returns the time in milliseconds as a 32-bit value.
1202 */
1203 word32 TimeNowInMilliseconds(void)
1204 {
1205 return (word32) Seconds_get() * 1000;
1206 }
1207#elif defined(WOLFSSL_UTASKER)
1208 /* The time in milliseconds.
1209 * Used for tickets to represent difference between when first seen and when
1210 * sending.
1211 *
1212 * returns the time in milliseconds as a 32-bit value.
1213 */
1214 word32 TimeNowInMilliseconds(void)
1215 {
1216 return (word32)(uTaskerSystemTick / (TICK_RESOLUTION / 1000));
1217 }
1218#else
1219 /* The time in milliseconds.
1220 * Used for tickets to represent difference between when first seen and when
1221 * sending.
1222 *
1223 * returns the time in milliseconds as a 32-bit value.
1224 */
1225 word32 TimeNowInMilliseconds(void)
1226 {
1227 struct timeval now;
1228
1229 if (gettimeofday(&now, 0) < 0)
1230 return GETTIME_ERROR;
1231 /* Convert to milliseconds number. */
1232 return (word32)(now.tv_sec * 1000 + now.tv_usec / 1000);
1233 }
1234#endif
1235#endif /* HAVE_SESSION_TICKET || !NO_PSK */
1236
1237
1238#if !defined(NO_WOLFSSL_SERVER) && (defined(HAVE_SESSION_TICKET) || \
1239 !defined(NO_PSK))
1240/* Add input to all handshake hashes.
1241 *
1242 * ssl The SSL/TLS object.
1243 * input The data to hash.
1244 * sz The size of the data to hash.
1245 * returns 0 on success, otherwise failure.
1246 */
1247static int HashInputRaw(WOLFSSL* ssl, const byte* input, int sz)
1248{
1249 int ret = BAD_FUNC_ARG;
1250
1251#ifndef NO_SHA256
1252 ret = wc_Sha256Update(&ssl->hsHashes->hashSha256, input, sz);
1253 if (ret != 0)
1254 return ret;
1255#endif
1256#ifdef WOLFSSL_SHA384
1257 ret = wc_Sha384Update(&ssl->hsHashes->hashSha384, input, sz);
1258 if (ret != 0)
1259 return ret;
1260#endif
1261#ifdef WOLFSSL_TLS13_SHA512
1262 ret = wc_Sha512Update(&ssl->hsHashes->hashSha512, input, sz);
1263 if (ret != 0)
1264 return ret;
1265#endif
1266
1267 return ret;
1268}
1269#endif
1270
1271/* Extract the handshake header information.
1272 *
1273 * ssl The SSL/TLS object.
1274 * input The buffer holding the message data.
1275 * inOutIdx On entry, the index into the buffer of the handshake data.
1276 * On exit, the start of the hanshake data.
1277 * type Type of handshake message.
1278 * size The length of the handshake message data.
1279 * totalSz The total size of data in the buffer.
1280 * returns BUFFER_E if there is not enough input data and 0 on success.
1281 */
1282static int GetHandshakeHeader(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
1283 byte* type, word32* size, word32 totalSz)
1284{
1285 const byte* ptr = input + *inOutIdx;
1286 (void)ssl;
1287
1288 *inOutIdx += HANDSHAKE_HEADER_SZ;
1289 if (*inOutIdx > totalSz)
1290 return BUFFER_E;
1291
1292 *type = ptr[0];
1293 c24to32(&ptr[1], size);
1294
1295 return 0;
1296}
1297
1298/* Add record layer header to message.
1299 *
1300 * output The buffer to write the record layer header into.
1301 * length The length of the record data.
1302 * type The type of record message.
1303 * ssl The SSL/TLS object.
1304 */
1305static void AddTls13RecordHeader(byte* output, word32 length, byte type,
1306 WOLFSSL* ssl)
1307{
1308 RecordLayerHeader* rl;
1309
1310 rl = (RecordLayerHeader*)output;
1311 rl->type = type;
1312 rl->pvMajor = ssl->version.major;
1313 rl->pvMinor = TLSv1_MINOR;
1314 c16toa((word16)length, rl->length);
1315}
1316
1317/* Add handshake header to message.
1318 *
1319 * output The buffer to write the hanshake header into.
1320 * length The length of the handshake data.
1321 * fragOffset The offset of the fragment data. (DTLS)
1322 * fragLength The length of the fragment data. (DTLS)
1323 * type The type of handshake message.
1324 * ssl The SSL/TLS object. (DTLS)
1325 */
1326static void AddTls13HandShakeHeader(byte* output, word32 length,
1327 word32 fragOffset, word32 fragLength,
1328 byte type, WOLFSSL* ssl)
1329{
1330 HandShakeHeader* hs;
1331 (void)fragOffset;
1332 (void)fragLength;
1333 (void)ssl;
1334
1335 /* handshake header */
1336 hs = (HandShakeHeader*)output;
1337 hs->type = type;
1338 c32to24(length, hs->length);
1339}
1340
1341
1342/* Add both record layer and handshake header to message.
1343 *
1344 * output The buffer to write the headers into.
1345 * length The length of the handshake data.
1346 * type The type of record layer message.
1347 * ssl The SSL/TLS object. (DTLS)
1348 */
1349static void AddTls13Headers(byte* output, word32 length, byte type,
1350 WOLFSSL* ssl)
1351{
1352 word32 lengthAdj = HANDSHAKE_HEADER_SZ;
1353 word32 outputAdj = RECORD_HEADER_SZ;
1354
1355 AddTls13RecordHeader(output, length + lengthAdj, handshake, ssl);
1356 AddTls13HandShakeHeader(output + outputAdj, length, 0, length, type, ssl);
1357}
1358
1359
1360#ifndef NO_CERTS
1361/* Add both record layer and fragement handshake header to message.
1362 *
1363 * output The buffer to write the headers into.
1364 * fragOffset The offset of the fragment data. (DTLS)
1365 * fragLength The length of the fragment data. (DTLS)
1366 * length The length of the handshake data.
1367 * type The type of record layer message.
1368 * ssl The SSL/TLS object. (DTLS)
1369 */
1370static void AddTls13FragHeaders(byte* output, word32 fragSz, word32 fragOffset,
1371 word32 length, byte type, WOLFSSL* ssl)
1372{
1373 word32 lengthAdj = HANDSHAKE_HEADER_SZ;
1374 word32 outputAdj = RECORD_HEADER_SZ;
1375 (void)fragSz;
1376
1377 AddTls13RecordHeader(output, fragSz + lengthAdj, handshake, ssl);
1378 AddTls13HandShakeHeader(output + outputAdj, length, fragOffset, fragSz,
1379 type, ssl);
1380}
1381#endif /* NO_CERTS */
1382
1383/* Write the sequence number into the buffer.
1384 * No DTLS v1.3 support.
1385 *
1386 * ssl The SSL/TLS object.
1387 * verifyOrder Which set of sequence numbers to use.
1388 * out The buffer to write into.
1389 */
1390static INLINE void WriteSEQ(WOLFSSL* ssl, int verifyOrder, byte* out)
1391{
1392 word32 seq[2] = {0, 0};
1393
1394 if (verifyOrder) {
1395 seq[0] = ssl->keys.peer_sequence_number_hi;
1396 seq[1] = ssl->keys.peer_sequence_number_lo++;
1397 /* handle rollover */
1398 if (seq[1] > ssl->keys.peer_sequence_number_lo)
1399 ssl->keys.peer_sequence_number_hi++;
1400 }
1401 else {
1402 seq[0] = ssl->keys.sequence_number_hi;
1403 seq[1] = ssl->keys.sequence_number_lo++;
1404 /* handle rollover */
1405 if (seq[1] > ssl->keys.sequence_number_lo)
1406 ssl->keys.sequence_number_hi++;
1407 }
1408
1409 c32toa(seq[0], out);
1410 c32toa(seq[1], out + OPAQUE32_LEN);
1411}
1412
1413/* Build the nonce for TLS v1.3 encryption and decryption.
1414 *
1415 * ssl The SSL/TLS object.
1416 * nonce The nonce data to use when encrypting or decrypting.
1417 * iv The derived IV.
1418 * order The side on which the message is to be or was sent.
1419 */
1420static INLINE void BuildTls13Nonce(WOLFSSL* ssl, byte* nonce, const byte* iv,
1421 int order)
1422{
1423 int i;
1424
1425 /* The nonce is the IV with the sequence XORed into the last bytes. */
1426 WriteSEQ(ssl, order, nonce + AEAD_NONCE_SZ - SEQ_SZ);
1427 for (i = 0; i < AEAD_NONCE_SZ - SEQ_SZ; i++)
1428 nonce[i] = iv[i];
1429 for (; i < AEAD_NONCE_SZ; i++)
1430 nonce[i] ^= iv[i];
1431}
1432
1433#ifdef HAVE_CHACHA
1434/* Encrypt with ChaCha20 and create authenication tag with Poly1305.
1435 *
1436 * ssl The SSL/TLS object.
1437 * output The buffer to write encrypted data and authentication tag into.
1438 * May be the same pointer as input.
1439 * input The data to encrypt.
1440 * sz The number of bytes to encrypt.
1441 * nonce The nonce to use with ChaCha20.
1442 * tag The authentication tag buffer.
1443 * returns 0 on success, otherwise failure.
1444 */
1445static int ChaCha20Poly1305_Encrypt(WOLFSSL* ssl, byte* output,
1446 const byte* input, word16 sz, byte* nonce,
1447 byte* tag)
1448{
1449 int ret = 0;
1450 byte poly[CHACHA20_256_KEY_SIZE];
1451
1452 /* Poly1305 key is 256 bits of zero encrypted with ChaCha20. */
1453 XMEMSET(poly, 0, sizeof(poly));
1454
1455 /* Set the nonce for ChaCha and get Poly1305 key. */
1456 ret = wc_Chacha_SetIV(ssl->encrypt.chacha, nonce, 0);
1457 if (ret != 0)
1458 return ret;
1459 /* Create Poly1305 key using ChaCha20 keystream. */
1460 ret = wc_Chacha_Process(ssl->encrypt.chacha, poly, poly, sizeof(poly));
1461 if (ret != 0)
1462 return ret;
1463 /* Encrypt the plain text. */
1464 ret = wc_Chacha_Process(ssl->encrypt.chacha, output, input, sz);
1465 if (ret != 0) {
1466 ForceZero(poly, sizeof(poly));
1467 return ret;
1468 }
1469
1470 /* Set key for Poly1305. */
1471 ret = wc_Poly1305SetKey(ssl->auth.poly1305, poly, sizeof(poly));
1472 ForceZero(poly, sizeof(poly)); /* done with poly1305 key, clear it */
1473 if (ret != 0)
1474 return ret;
1475 /* Add authentication code of encrypted data to end. */
1476 ret = wc_Poly1305_MAC(ssl->auth.poly1305, NULL, 0, output, sz, tag,
1477 POLY1305_AUTH_SZ);
1478
1479 return ret;
1480}
1481#endif
1482
1483/* Encrypt data for TLS v1.3.
1484 *
1485 * ssl The SSL/TLS object.
1486 * output The buffer to write encrypted data and authentication tag into.
1487 * May be the same pointer as input.
1488 * input The data to encrypt.
1489 * sz The number of bytes to encrypt.
1490 * asyncOkay If non-zero can return WC_PENDING_E, otherwise blocks on crypto
1491 * returns 0 on success, otherwise failure.
1492 */
1493static int EncryptTls13(WOLFSSL* ssl, byte* output, const byte* input,
1494 word16 sz, int asyncOkay)
1495{
1496 int ret = 0;
1497 word16 dataSz = sz - ssl->specs.aead_mac_size;
1498 word16 macSz = ssl->specs.aead_mac_size;
1499 word32 nonceSz = 0;
1500#ifdef WOLFSSL_ASYNC_CRYPT
1501 WC_ASYNC_DEV* asyncDev = NULL;
1502 word32 event_flags = WC_ASYNC_FLAG_CALL_AGAIN;
1503#endif
1504
1505 WOLFSSL_ENTER("EncryptTls13");
1506
1507 (void)output;
1508 (void)input;
1509 (void)sz;
1510 (void)dataSz;
1511 (void)macSz;
1512 (void)asyncOkay;
1513 (void)nonceSz;
1514
1515#ifdef WOLFSSL_ASYNC_CRYPT
1516 if (ssl->error == WC_PENDING_E) {
1517 ssl->error = 0; /* clear async */
1518 }
1519#endif
1520
1521 switch (ssl->encrypt.state) {
1522 case CIPHER_STATE_BEGIN:
1523 {
1524 #ifdef WOLFSSL_DEBUG_TLS
1525 WOLFSSL_MSG("Data to encrypt");
1526 WOLFSSL_BUFFER(input, dataSz);
1527 #endif
1528
1529 if (ssl->encrypt.nonce == NULL)
1530 ssl->encrypt.nonce = (byte*)XMALLOC(AEAD_NONCE_SZ,
1531 ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
1532 if (ssl->encrypt.nonce == NULL)
1533 return MEMORY_E;
1534
1535 BuildTls13Nonce(ssl, ssl->encrypt.nonce, ssl->keys.aead_enc_imp_IV,
1536 CUR_ORDER);
1537
1538 /* Advance state and proceed */
1539 ssl->encrypt.state = CIPHER_STATE_DO;
1540 }
1541 FALL_THROUGH;
1542
1543 case CIPHER_STATE_DO:
1544 {
1545 switch (ssl->specs.bulk_cipher_algorithm) {
1546 #ifdef BUILD_AESGCM
1547 case wolfssl_aes_gcm:
1548 #ifdef WOLFSSL_ASYNC_CRYPT
1549 /* intialize event */
1550 asyncDev = &ssl->encrypt.aes->asyncDev;
1551 ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
1552 if (ret != 0)
1553 break;
1554 #endif
1555
1556 nonceSz = AESGCM_NONCE_SZ;
1557 ret = wc_AesGcmEncrypt(ssl->encrypt.aes, output, input,
1558 dataSz, ssl->encrypt.nonce, nonceSz,
1559 output + dataSz, macSz, NULL, 0);
1560 break;
1561 #endif
1562
1563 #ifdef HAVE_AESCCM
1564 case wolfssl_aes_ccm:
1565 #ifdef WOLFSSL_ASYNC_CRYPT
1566 /* intialize event */
1567 asyncDev = &ssl->encrypt.aes->asyncDev;
1568 ret = wolfSSL_AsyncInit(ssl, asyncDev, event_flags);
1569 if (ret != 0)
1570 break;
1571 #endif
1572
1573 nonceSz = AESCCM_NONCE_SZ;
1574 ret = wc_AesCcmEncrypt(ssl->encrypt.aes, output, input,
1575 dataSz, ssl->encrypt.nonce, nonceSz,
1576 output + dataSz, macSz, NULL, 0);
1577 break;
1578 #endif
1579
1580 #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
1581 case wolfssl_chacha:
1582 ret = ChaCha20Poly1305_Encrypt(ssl, output, input, dataSz,
1583 ssl->encrypt.nonce, output + dataSz);
1584 break;
1585 #endif
1586
1587 default:
1588 WOLFSSL_MSG("wolfSSL Encrypt programming error");
1589 return ENCRYPT_ERROR;
1590 }
1591
1592 /* Advance state */
1593 ssl->encrypt.state = CIPHER_STATE_END;
1594
1595 #ifdef WOLFSSL_ASYNC_CRYPT
1596 if (ret == WC_PENDING_E) {
1597 /* if async is not okay, then block */
1598 if (!asyncOkay) {
1599 ret = wc_AsyncWait(ret, asyncDev, event_flags);
1600 }
1601 else {
1602 /* If pending, then leave and return will resume below */
1603 return wolfSSL_AsyncPush(ssl, asyncDev);
1604 }
1605 }
1606 #endif
1607 }
1608 FALL_THROUGH;
1609
1610 case CIPHER_STATE_END:
1611 {
1612 #ifdef WOLFSSL_DEBUG_TLS
1613 WOLFSSL_MSG("Nonce");
1614 WOLFSSL_BUFFER(ssl->encrypt.nonce, ssl->specs.iv_size);
1615 WOLFSSL_MSG("Encrypted data");
1616 WOLFSSL_BUFFER(output, dataSz);
1617 WOLFSSL_MSG("Authentication Tag");
1618 WOLFSSL_BUFFER(output + dataSz, macSz);
1619 #endif
1620
1621 ForceZero(ssl->encrypt.nonce, AEAD_NONCE_SZ);
1622
1623 break;
1624 }
1625 }
1626
1627 /* Reset state */
1628 ssl->encrypt.state = CIPHER_STATE_BEGIN;
1629
1630 return ret;
1631}
1632
1633#ifdef HAVE_CHACHA
1634/* Decrypt with ChaCha20 and check authenication tag with Poly1305.
1635 *
1636 * ssl The SSL/TLS object.
1637 * output The buffer to write decrypted data into.
1638 * May be the same pointer as input.
1639 * input The data to decrypt.
1640 * sz The number of bytes to decrypt.
1641 * nonce The nonce to use with ChaCha20.
1642 * tagIn The authentication tag data from packet.
1643 * returns 0 on success, otherwise failure.
1644 */
1645static int ChaCha20Poly1305_Decrypt(WOLFSSL* ssl, byte* output,
1646 const byte* input, word16 sz, byte* nonce,
1647 const byte* tagIn)
1648{
1649 int ret;
1650 byte tag[POLY1305_AUTH_SZ];
1651 byte poly[CHACHA20_256_KEY_SIZE]; /* generated key for mac */
1652
1653 /* Poly1305 key is 256 bits of zero encrypted with ChaCha20. */
1654 XMEMSET(poly, 0, sizeof(poly));
1655
1656 /* Set nonce and get Poly1305 key. */
1657 ret = wc_Chacha_SetIV(ssl->decrypt.chacha, nonce, 0);
1658 if (ret != 0)
1659 return ret;
1660 /* Use ChaCha20 keystream to get Poly1305 key for tag. */
1661 ret = wc_Chacha_Process(ssl->decrypt.chacha, poly, poly, sizeof(poly));
1662 if (ret != 0)
1663 return ret;
1664
1665 /* Set key for Poly1305. */
1666 ret = wc_Poly1305SetKey(ssl->auth.poly1305, poly, sizeof(poly));
1667 ForceZero(poly, sizeof(poly)); /* done with poly1305 key, clear it */
1668 if (ret != 0)
1669 return ret;
1670 /* Generate authentication tag for encrypted data. */
1671 if ((ret = wc_Poly1305_MAC(ssl->auth.poly1305, NULL, 0, (byte*)input, sz,
1672 tag, sizeof(tag))) != 0) {
1673 return ret;
1674 }
1675
1676 /* Check tag sent along with packet. */
1677 if (ConstantCompare(tagIn, tag, POLY1305_AUTH_SZ) != 0) {
1678 WOLFSSL_MSG("MAC did not match");
1679 return VERIFY_MAC_ERROR;
1680 }
1681
1682 /* If the tag was good decrypt message. */
1683 ret = wc_Chacha_Process(ssl->decrypt.chacha, output, input, sz);
1684
1685 return ret;
1686}
1687#endif
1688
1689/* Decrypt data for TLS v1.3.
1690 *
1691 * ssl The SSL/TLS object.
1692 * output The buffer to write decrypted data into.
1693 * May be the same pointer as input.
1694 * input The data to encrypt and authentication tag.
1695 * sz The length of the encrypted data plus authentication tag.
1696 * returns 0 on success, otherwise failure.
1697 */
1698int DecryptTls13(WOLFSSL* ssl, byte* output, const byte* input, word16 sz)
1699{
1700 int ret = 0;
1701 word16 dataSz = sz - ssl->specs.aead_mac_size;
1702 word16 macSz = ssl->specs.aead_mac_size;
1703 word32 nonceSz = 0;
1704
1705 WOLFSSL_ENTER("DecryptTls13");
1706
1707#ifdef WOLFSSL_ASYNC_CRYPT
1708 ret = wolfSSL_AsyncPop(ssl, &ssl->decrypt.state);
1709 if (ret != WC_NOT_PENDING_E) {
1710 /* check for still pending */
1711 if (ret == WC_PENDING_E)
1712 return ret;
1713
1714 ssl->error = 0; /* clear async */
1715
1716 /* let failures through so CIPHER_STATE_END logic is run */
1717 }
1718 else
1719#endif
1720 {
1721 /* Reset state */
1722 ret = 0;
1723 ssl->decrypt.state = CIPHER_STATE_BEGIN;
1724 }
1725
1726 (void)output;
1727 (void)input;
1728 (void)sz;
1729 (void)dataSz;
1730 (void)macSz;
1731 (void)nonceSz;
1732
1733 switch (ssl->decrypt.state) {
1734 case CIPHER_STATE_BEGIN:
1735 {
1736 #ifdef WOLFSSL_DEBUG_TLS
1737 WOLFSSL_MSG("Data to decrypt");
1738 WOLFSSL_BUFFER(input, dataSz);
1739 WOLFSSL_MSG("Authentication tag");
1740 WOLFSSL_BUFFER(input + dataSz, macSz);
1741 #endif
1742
1743 if (ssl->decrypt.nonce == NULL)
1744 ssl->decrypt.nonce = (byte*)XMALLOC(AEAD_NONCE_SZ,
1745 ssl->heap, DYNAMIC_TYPE_AES_BUFFER);
1746 if (ssl->decrypt.nonce == NULL)
1747 return MEMORY_E;
1748
1749 BuildTls13Nonce(ssl, ssl->decrypt.nonce, ssl->keys.aead_dec_imp_IV,
1750 PEER_ORDER);
1751
1752 /* Advance state and proceed */
1753 ssl->decrypt.state = CIPHER_STATE_DO;
1754 }
1755 FALL_THROUGH;
1756
1757 case CIPHER_STATE_DO:
1758 {
1759 switch (ssl->specs.bulk_cipher_algorithm) {
1760 #ifdef BUILD_AESGCM
1761 case wolfssl_aes_gcm:
1762 #ifdef WOLFSSL_ASYNC_CRYPT
1763 /* intialize event */
1764 ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
1765 WC_ASYNC_FLAG_CALL_AGAIN);
1766 if (ret != 0)
1767 break;
1768 #endif
1769
1770 nonceSz = AESGCM_NONCE_SZ;
1771 ret = wc_AesGcmDecrypt(ssl->decrypt.aes, output, input,
1772 dataSz, ssl->decrypt.nonce, nonceSz,
1773 input + dataSz, macSz, NULL, 0);
1774 #ifdef WOLFSSL_ASYNC_CRYPT
1775 if (ret == WC_PENDING_E) {
1776 ret = wolfSSL_AsyncPush(ssl,
1777 &ssl->decrypt.aes->asyncDev);
1778 }
1779 #endif
1780 break;
1781 #endif
1782
1783 #ifdef HAVE_AESCCM
1784 case wolfssl_aes_ccm:
1785 #ifdef WOLFSSL_ASYNC_CRYPT
1786 /* intialize event */
1787 ret = wolfSSL_AsyncInit(ssl, &ssl->decrypt.aes->asyncDev,
1788 WC_ASYNC_FLAG_CALL_AGAIN);
1789 if (ret != 0)
1790 break;
1791 #endif
1792
1793 nonceSz = AESCCM_NONCE_SZ;
1794 ret = wc_AesCcmDecrypt(ssl->decrypt.aes, output, input,
1795 dataSz, ssl->decrypt.nonce, nonceSz,
1796 input + dataSz, macSz, NULL, 0);
1797 #ifdef WOLFSSL_ASYNC_CRYPT
1798 if (ret == WC_PENDING_E) {
1799 ret = wolfSSL_AsyncPush(ssl,
1800 &ssl->decrypt.aes->asyncDev);
1801 }
1802 #endif
1803 break;
1804 #endif
1805
1806 #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
1807 case wolfssl_chacha:
1808 ret = ChaCha20Poly1305_Decrypt(ssl, output, input, dataSz,
1809 ssl->decrypt.nonce, input + dataSz);
1810 break;
1811 #endif
1812
1813 default:
1814 WOLFSSL_MSG("wolfSSL Decrypt programming error");
1815 return DECRYPT_ERROR;
1816 }
1817
1818 /* Advance state */
1819 ssl->decrypt.state = CIPHER_STATE_END;
1820
1821 #ifdef WOLFSSL_ASYNC_CRYPT
1822 /* If pending, leave now */
1823 if (ret == WC_PENDING_E) {
1824 return ret;
1825 }
1826 #endif
1827 }
1828 FALL_THROUGH;
1829
1830 case CIPHER_STATE_END:
1831 {
1832 #ifdef WOLFSSL_DEBUG_TLS
1833 WOLFSSL_MSG("Nonce");
1834 WOLFSSL_BUFFER(ssl->decrypt.nonce, ssl->specs.iv_size);
1835 WOLFSSL_MSG("Decrypted data");
1836 WOLFSSL_BUFFER(output, dataSz);
1837 #endif
1838
1839 ForceZero(ssl->decrypt.nonce, AEAD_NONCE_SZ);
1840
1841 break;
1842 }
1843 }
1844
1845#ifndef WOLFSSL_EARLY_DATA
1846 if (ret < 0) {
1847 SendAlert(ssl, alert_fatal, bad_record_mac);
1848 ret = VERIFY_MAC_ERROR;
1849 }
1850#endif
1851
1852 return ret;
1853}
1854
1855/* Persistable BuildTls13Message arguments */
1856typedef struct BuildMsg13Args {
1857 word32 sz;
1858 word32 idx;
1859 word32 headerSz;
1860 word16 size;
1861} BuildMsg13Args;
1862
1863static void FreeBuildMsg13Args(WOLFSSL* ssl, void* pArgs)
1864{
1865 BuildMsg13Args* args = (BuildMsg13Args*)pArgs;
1866
1867 (void)ssl;
1868 (void)args;
1869
1870 /* no allocations in BuildTls13Message */
1871}
1872
1873/* Build SSL Message, encrypted.
1874 * TLS v1.3 encryption is AEAD only.
1875 *
1876 * ssl The SSL/TLS object.
1877 * output The buffer to write record message to.
1878 * outSz Size of the buffer being written into.
1879 * input The record data to encrypt (excluding record header).
1880 * inSz The size of the record data.
1881 * type The recorder header content type.
1882 * hashOutput Whether to hash the unencrypted record data.
1883 * sizeOnly Only want the size of the record message.
1884 * asyncOkay If non-zero can return WC_PENDING_E, otherwise blocks on crypto
1885 * returns the size of the encrypted record message or negative value on error.
1886 */
1887int BuildTls13Message(WOLFSSL* ssl, byte* output, int outSz, const byte* input,
1888 int inSz, int type, int hashOutput, int sizeOnly, int asyncOkay)
1889{
1890 int ret = 0;
1891 BuildMsg13Args* args;
1892 BuildMsg13Args lcl_args;
1893#ifdef WOLFSSL_ASYNC_CRYPT
1894 args = (BuildMsg13Args*)ssl->async.args;
1895 typedef char args_test[sizeof(ssl->async.args) >= sizeof(*args) ? 1 : -1];
1896 (void)sizeof(args_test);
1897#endif
1898
1899 WOLFSSL_ENTER("BuildTls13Message");
1900
1901 ret = WC_NOT_PENDING_E;
1902#ifdef WOLFSSL_ASYNC_CRYPT
1903 if (asyncOkay) {
1904 ret = wolfSSL_AsyncPop(ssl, &ssl->options.buildMsgState);
1905 if (ret != WC_NOT_PENDING_E) {
1906 /* Check for error */
1907 if (ret < 0)
1908 goto exit_buildmsg;
1909 }
1910 }
1911 else
1912#endif
1913 {
1914 args = &lcl_args;
1915 }
1916
1917 /* Reset state */
1918 if (ret == WC_NOT_PENDING_E) {
1919 ret = 0;
1920 ssl->options.buildMsgState = BUILD_MSG_BEGIN;
1921 XMEMSET(args, 0, sizeof(BuildMsg13Args));
1922
1923 args->sz = RECORD_HEADER_SZ + inSz;
1924 args->idx = RECORD_HEADER_SZ;
1925 args->headerSz = RECORD_HEADER_SZ;
1926 #ifdef WOLFSSL_ASYNC_CRYPT
1927 ssl->async.freeArgs = FreeBuildMsg13Args;
1928 #endif
1929 }
1930
1931 switch (ssl->options.buildMsgState) {
1932 case BUILD_MSG_BEGIN:
1933 {
1934 if (output == NULL || input == NULL)
1935 return BAD_FUNC_ARG;
1936 /* catch mistaken sizeOnly parameter */
1937 if (sizeOnly && (output || input)) {
1938 WOLFSSL_MSG("BuildTls13Message with sizeOnly doesn't need "
1939 "input or output");
1940 return BAD_FUNC_ARG;
1941 }
1942
1943 /* Record layer content type at the end of record data. */
1944 args->sz++;
1945 /* Authentication data at the end. */
1946 args->sz += ssl->specs.aead_mac_size;
1947
1948 if (sizeOnly)
1949 return args->sz;
1950
1951 if (args->sz > (word32)outSz) {
1952 WOLFSSL_MSG("Oops, want to write past output buffer size");
1953 return BUFFER_E;
1954 }
1955
1956 /* Record data length. */
1957 args->size = (word16)(args->sz - args->headerSz);
1958 /* Write/update the record header with the new size.
1959 * Always have the content type as application data for encrypted
1960 * messages in TLS v1.3.
1961 */
1962 AddTls13RecordHeader(output, args->size, application_data, ssl);
1963
1964 /* TLS v1.3 can do in place encryption. */
1965 if (input != output + args->idx)
1966 XMEMCPY(output + args->idx, input, inSz);
1967 args->idx += inSz;
1968
1969 ssl->options.buildMsgState = BUILD_MSG_HASH;
1970 }
1971 FALL_THROUGH;
1972
1973 case BUILD_MSG_HASH:
1974 {
1975 if (hashOutput) {
1976 ret = HashOutput(ssl, output, args->headerSz + inSz, 0);
1977 if (ret != 0)
1978 goto exit_buildmsg;
1979 }
1980
1981 ssl->options.buildMsgState = BUILD_MSG_ENCRYPT;
1982 }
1983 FALL_THROUGH;
1984
1985 case BUILD_MSG_ENCRYPT:
1986 {
1987 /* The real record content type goes at the end of the data. */
1988 output[args->idx++] = type;
1989
1990 #ifdef ATOMIC_USER
1991 if (ssl->ctx->MacEncryptCb) {
1992 /* User Record Layer Callback handling */
1993 byte* mac = output + args->idx;
1994 output += args->headerSz;
1995
1996 ret = ssl->ctx->MacEncryptCb(ssl, mac, output, inSz, type, 0,
1997 output, output, args->size, ssl->MacEncryptCtx);
1998 }
1999 else
2000 #endif
2001 {
2002 output += args->headerSz;
2003 ret = EncryptTls13(ssl, output, output, args->size, asyncOkay);
2004 }
2005 break;
2006 }
2007 }
2008
2009exit_buildmsg:
2010
2011 WOLFSSL_LEAVE("BuildTls13Message", ret);
2012
2013#ifdef WOLFSSL_ASYNC_CRYPT
2014 if (ret == WC_PENDING_E) {
2015 return ret;
2016 }
2017#endif
2018
2019 /* make sure build message state is reset */
2020 ssl->options.buildMsgState = BUILD_MSG_BEGIN;
2021
2022 /* return sz on success */
2023 if (ret == 0)
2024 ret = args->sz;
2025
2026 /* Final cleanup */
2027 FreeBuildMsg13Args(ssl, args);
2028
2029 return ret;
2030}
2031
2032#ifndef NO_WOLFSSL_CLIENT
2033#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
2034/* Setup pre-shared key based on the details in the extension data.
2035 *
2036 * ssl SSL/TLS object.
2037 * psk Pre-shared key extension data.
2038 * returns 0 on success, PSK_KEY_ERROR when the client PSK callback fails and
2039 * other negative value on failure.
2040 */
2041static int SetupPskKey(WOLFSSL* ssl, PreSharedKey* psk)
2042{
2043 int ret;
2044
2045 ssl->options.cipherSuite0 = psk->cipherSuite0;
2046 ssl->options.cipherSuite = psk->cipherSuite;
2047 if ((ret = SetCipherSpecs(ssl)) != 0)
2048 return ret;
2049
2050#ifdef HAVE_SESSION_TICKET
2051 if (psk->resumption) {
2052 #ifdef WOLFSSL_EARLY_DATA
2053 if (ssl->session.maxEarlyDataSz == 0)
2054 ssl->earlyData = 0;
2055 #endif
2056 /* Resumption PSK is master secret. */
2057 ssl->arrays->psk_keySz = ssl->specs.hash_size;
2058 XMEMCPY(ssl->arrays->psk_key, ssl->session.masterSecret,
2059 ssl->arrays->psk_keySz);
2060 }
2061#endif
2062#ifndef NO_PSK
2063 if (!psk->resumption) {
2064 /* Get the pre-shared key. */
2065 ssl->arrays->psk_keySz = ssl->options.client_psk_cb(ssl,
2066 (char *)psk->identity, ssl->arrays->client_identity,
2067 MAX_PSK_ID_LEN, ssl->arrays->psk_key, MAX_PSK_KEY_LEN);
2068 if (ssl->arrays->psk_keySz == 0 ||
2069 ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN) {
2070 return PSK_KEY_ERROR;
2071 }
2072 }
2073#endif
2074
2075 /* Derive the early secret using the PSK. */
2076 return DeriveEarlySecret(ssl);
2077}
2078
2079/* Derive and write the binders into the ClientHello in space left when
2080 * writing the Pre-Shared Key extension.
2081 *
2082 * ssl The SSL/TLS object.
2083 * output The buffer containing the ClientHello.
2084 * idx The index at the end of the completed ClientHello.
2085 * returns 0 on success and otherwise failure.
2086 */
2087static int WritePSKBinders(WOLFSSL* ssl, byte* output, word32 idx)
2088{
2089 int ret;
2090 TLSX* ext;
2091 PreSharedKey* current;
2092 byte binderKey[MAX_DIGEST_SIZE];
2093 word16 len;
2094
2095 ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
2096 if (ext == NULL)
2097 return SANITY_MSG_E;
2098
2099 /* Get the size of the binders to determine where to write binders. */
2100 idx -= TLSX_PreSharedKey_GetSizeBinders((PreSharedKey*)ext->data,
2101 client_hello);
2102
2103 /* Hash truncated ClientHello - up to binders. */
2104 ret = HashOutput(ssl, output, idx, 0);
2105 if (ret != 0)
2106 return ret;
2107
2108 current = (PreSharedKey*)ext->data;
2109 /* Calculate the binder for each identity based on previous handshake data.
2110 */
2111 while (current != NULL) {
2112 if ((ret = SetupPskKey(ssl, current)) != 0)
2113 return ret;
2114
2115 #ifdef HAVE_SESSION_TICKET
2116 if (current->resumption)
2117 ret = DeriveBinderKeyResume(ssl, binderKey);
2118 #endif
2119 #ifndef NO_PSK
2120 if (!current->resumption)
2121 ret = DeriveBinderKey(ssl, binderKey);
2122 #endif
2123 if (ret != 0)
2124 return ret;
2125
2126 /* Derive the Finished message secret. */
2127 ret = DeriveFinishedSecret(ssl, binderKey,
2128 ssl->keys.client_write_MAC_secret);
2129 if (ret != 0)
2130 return ret;
2131
2132 /* Build the HMAC of the handshake message data = binder. */
2133 ret = BuildTls13HandshakeHmac(ssl, ssl->keys.client_write_MAC_secret,
2134 current->binder, &current->binderLen);
2135 if (ret != 0)
2136 return ret;
2137
2138 current = current->next;
2139 }
2140
2141 /* Data entered into extension, now write to message. */
2142 len = TLSX_PreSharedKey_WriteBinders((PreSharedKey*)ext->data, output + idx,
2143 client_hello);
2144
2145 /* Hash binders to complete the hash of the ClientHello. */
2146 ret = HashOutputRaw(ssl, output + idx, len);
2147 if (ret < 0)
2148 return ret;
2149
2150 #ifdef WOLFSSL_EARLY_DATA
2151 if (ssl->earlyData) {
2152 if ((ret = SetupPskKey(ssl, (PreSharedKey*)ext->data)) != 0)
2153 return ret;
2154
2155 /* Derive early data encryption key. */
2156 ret = DeriveTls13Keys(ssl, early_data_key, ENCRYPT_SIDE_ONLY, 1);
2157 if (ret != 0)
2158 return ret;
2159 if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
2160 return ret;
2161 }
2162 #endif
2163 return ret;
2164}
2165#endif
2166
2167/* Send a ClientHello message to the server.
2168 * Include the information required to start a handshake with servers using
2169 * protocol versions less than TLS v1.3.
2170 * Only a client will send this message.
2171 *
2172 * ssl The SSL/TLS object.
2173 * returns 0 on success and otherwise failure.
2174 */
2175int SendTls13ClientHello(WOLFSSL* ssl)
2176{
2177 byte* output;
2178 word32 length;
2179 word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
2180 int sendSz;
2181 int ret;
2182
2183 WOLFSSL_ENTER("SendTls13ClientHello");
2184
2185#ifdef HAVE_SESSION_TICKET
2186 if (ssl->options.resuming &&
2187 (ssl->session.version.major != ssl->version.major ||
2188 ssl->session.version.minor != ssl->version.minor)) {
2189 /* Cannot resume with a different protocol version - new handshake. */
2190 ssl->options.resuming = 0;
2191 ssl->version.major = ssl->session.version.major;
2192 ssl->version.minor = ssl->session.version.minor;
2193 return SendClientHello(ssl);
2194 }
2195#endif
2196
2197 if (ssl->suites == NULL) {
2198 WOLFSSL_MSG("Bad suites pointer in SendTls13ClientHello");
2199 return SUITES_ERROR;
2200 }
2201
2202 /* Version | Random | Session Id | Cipher Suites | Compression | Ext */
2203 length = VERSION_SZ + RAN_LEN + ENUM_LEN + ssl->suites->suiteSz +
2204 SUITE_LEN + COMP_LEN + ENUM_LEN;
2205
2206 /* Auto populate extensions supported unless user defined. */
2207 if ((ret = TLSX_PopulateExtensions(ssl, 0)) != 0)
2208 return ret;
2209#ifdef WOLFSSL_EARLY_DATA
2210 #ifndef NO_PSK
2211 if (!ssl->options.resuming && ssl->options.client_psk_cb == NULL)
2212 #else
2213 if (!ssl->options.resuming)
2214 #endif
2215 ssl->earlyData = 0;
2216 if (ssl->earlyData && (ret = TLSX_EarlyData_Use(ssl, 0)) < 0)
2217 return ret;
2218#endif
2219#ifdef HAVE_QSH
2220 if (QSH_Init(ssl) != 0)
2221 return MEMORY_E;
2222#endif
2223 /* Include length of TLS extensions. */
2224 length += TLSX_GetRequestSize(ssl, client_hello);
2225
2226 /* Total message size. */
2227 sendSz = length + HANDSHAKE_HEADER_SZ + RECORD_HEADER_SZ;
2228
2229 /* Check buffers are big enough and grow if needed. */
2230 if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
2231 return ret;
2232
2233 /* Get position in output buffer to write new message to. */
2234 output = ssl->buffers.outputBuffer.buffer +
2235 ssl->buffers.outputBuffer.length;
2236
2237 /* Put the record and handshake headers on. */
2238 AddTls13Headers(output, length, client_hello, ssl);
2239
2240 /* Protocol version. */
2241 output[idx++] = SSLv3_MAJOR;
2242 output[idx++] = TLSv1_2_MINOR;
2243 ssl->chVersion = ssl->version;
2244
2245 /* Client Random */
2246 if (ssl->options.connectState == CONNECT_BEGIN) {
2247 ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, RAN_LEN);
2248 if (ret != 0)
2249 return ret;
2250
2251 /* Store random for possible second ClientHello. */
2252 XMEMCPY(ssl->arrays->clientRandom, output + idx, RAN_LEN);
2253 }
2254 else
2255 XMEMCPY(output + idx, ssl->arrays->clientRandom, RAN_LEN);
2256 idx += RAN_LEN;
2257
2258 /* TLS v1.3 does not use session id - 0 length. */
2259 output[idx++] = 0;
2260
2261 /* Cipher suites */
2262 c16toa(ssl->suites->suiteSz, output + idx);
2263 idx += OPAQUE16_LEN;
2264 XMEMCPY(output + idx, &ssl->suites->suites, ssl->suites->suiteSz);
2265 idx += ssl->suites->suiteSz;
2266
2267 /* Compression not supported in TLS v1.3. */
2268 output[idx++] = COMP_LEN;
2269 output[idx++] = NO_COMPRESSION;
2270
2271 /* Write out extensions for a request. */
2272 idx += TLSX_WriteRequest(ssl, output + idx, client_hello);
2273
2274#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
2275 /* Resumption has a specific set of extensions and binder is calculated
2276 * for each identity.
2277 */
2278 if (TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY))
2279 ret = WritePSKBinders(ssl, output, idx);
2280 else
2281#endif
2282 ret = HashOutput(ssl, output, idx, 0);
2283 if (ret != 0)
2284 return ret;
2285
2286 ssl->options.clientState = CLIENT_HELLO_COMPLETE;
2287
2288#ifdef WOLFSSL_CALLBACKS
2289 if (ssl->hsInfoOn) AddPacketName("ClientHello", &ssl->handShakeInfo);
2290 if (ssl->toInfoOn) {
2291 AddPacketInfo("ClientHello", &ssl->timeoutInfo, output, sendSz,
2292 ssl->heap);
2293 }
2294#endif
2295
2296 ssl->buffers.outputBuffer.length += sendSz;
2297
2298 ret = SendBuffered(ssl);
2299
2300 WOLFSSL_LEAVE("SendTls13ClientHello", ret);
2301
2302 return ret;
2303}
2304
2305#ifndef WOLFSSL_TLS13_DRAFT_18
2306#ifdef WOLFSSL_SEND_HRR_COOKIE
2307/* Create Cookie extension using the hash of the first ClientHello.
2308 *
2309 * ssl SSL/TLS object.
2310 * hash The hash data.
2311 * hashSz The size of the hash data in bytes.
2312 * returns 0 on success, otherwise failure.
2313 */
2314static int CreateCookie(WOLFSSL* ssl, byte* hash, byte hashSz)
2315{
2316 int ret;
2317 byte mac[MAX_DIGEST_SIZE];
2318 Hmac cookieHmac;
2319 byte cookieType;
2320 byte macSz;
2321
2322#if !defined(NO_SHA) && defined(NO_SHA256)
2323 cookieType = SHA;
2324 macSz = WC_SHA_DIGEST_SIZE;
2325#endif /* NO_SHA */
2326#ifndef NO_SHA256
2327 cookieType = WC_SHA256;
2328 macSz = WC_SHA256_DIGEST_SIZE;
2329#endif /* NO_SHA256 */
2330
2331 ret = wc_HmacSetKey(&cookieHmac, cookieType,
2332 ssl->buffers.tls13CookieSecret.buffer,
2333 ssl->buffers.tls13CookieSecret.length);
2334 if (ret != 0)
2335 return ret;
2336 if ((ret = wc_HmacUpdate(&cookieHmac, hash, hashSz)) != 0)
2337 return ret;
2338 if ((ret = wc_HmacFinal(&cookieHmac, mac)) != 0)
2339 return ret;
2340
2341 /* The cookie data is the hash and the integrity check. */
2342 return TLSX_Cookie_Use(ssl, hash, hashSz, mac, macSz, 1);
2343}
2344#endif
2345
2346/* Restart the Hanshake hash with a hash of the previous messages.
2347 *
2348 * ssl The SSL/TLS object.
2349 * returns 0 on success, otherwise failure.
2350 */
2351static int RestartHandshakeHash(WOLFSSL* ssl)
2352{
2353 int ret;
2354 Hashes hashes;
2355 byte header[HANDSHAKE_HEADER_SZ];
2356 byte* hash = NULL;
2357 byte hashSz = 0;
2358
2359 ret = BuildCertHashes(ssl, &hashes);
2360 if (ret != 0)
2361 return ret;
2362 switch (ssl->specs.mac_algorithm) {
2363 #ifndef NO_SHA256
2364 case sha256_mac:
2365 hash = hashes.sha256;
2366 break;
2367 #endif
2368 #ifdef WOLFSSL_SHA384
2369 case sha384_mac:
2370 hash = hashes.sha384;
2371 break;
2372 #endif
2373 #ifdef WOLFSSL_TLS13_SHA512
2374 case sha512_mac:
2375 hash = hashes.sha512;
2376 break;
2377 #endif
2378 }
2379 hashSz = ssl->specs.hash_size;
2380 AddTls13HandShakeHeader(header, hashSz, 0, 0, message_hash, ssl);
2381
2382 WOLFSSL_MSG("Restart Hash");
2383 WOLFSSL_BUFFER(hash, hashSz);
2384
2385#ifdef WOLFSSL_SEND_HRR_COOKIE
2386 if (ssl->options.sendCookie) {
2387 byte cookie[OPAQUE8_LEN + MAX_DIGEST_SIZE + OPAQUE16_LEN * 2];
2388 TLSX* ext;
2389 word32 idx = 0;
2390
2391 /* Cookie Data = Hash Len | Hash | CS | KeyShare Group */
2392 cookie[idx++] = hashSz;
2393 XMEMCPY(cookie + idx, hash, hashSz);
2394 idx += hashSz;
2395 cookie[idx++] = ssl->options.cipherSuite0;
2396 cookie[idx++] = ssl->options.cipherSuite;
2397 if ((ext = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE)) != NULL) {
2398 KeyShareEntry* kse = (KeyShareEntry*)ext->data;
2399 c16toa(kse->group, cookie + idx);
2400 idx += OPAQUE16_LEN;
2401 }
2402 return CreateCookie(ssl, cookie, idx);
2403 }
2404#endif
2405
2406 ret = InitHandshakeHashes(ssl);
2407 if (ret != 0)
2408 return ret;
2409 ret = HashOutputRaw(ssl, header, sizeof(header));
2410 if (ret != 0)
2411 return ret;
2412 return HashOutputRaw(ssl, hash, hashSz);
2413}
2414#endif
2415
2416/* Parse and handle a HelloRetryRequest message.
2417 * Only a client will receive this message.
2418 *
2419 * ssl The SSL/TLS object.
2420 * input The message buffer.
2421 * inOutIdx On entry, the index into the message buffer of
2422 * HelloRetryRequest.
2423 * On exit, the index of byte after the HelloRetryRequest message.
2424 * totalSz The length of the current handshake message.
2425 * returns 0 on success and otherwise failure.
2426 */
2427static int DoTls13HelloRetryRequest(WOLFSSL* ssl, const byte* input,
2428 word32* inOutIdx, word32 totalSz)
2429{
2430 int ret;
2431 word32 begin = *inOutIdx;
2432 word32 i = begin;
2433 word16 totalExtSz;
2434 ProtocolVersion pv;
2435
2436 WOLFSSL_ENTER("DoTls13HelloRetryRequest");
2437
2438#ifdef WOLFSSL_CALLBACKS
2439 if (ssl->hsInfoOn) AddPacketName("HelloRetryRequest", &ssl->handShakeInfo);
2440 if (ssl->toInfoOn) AddLateName("HelloRetryRequest", &ssl->timeoutInfo);
2441#endif
2442
2443 /* Version info and length field of extension data. */
2444 if (totalSz < i - begin + OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
2445 return BUFFER_ERROR;
2446
2447 /* Protocol version. */
2448 XMEMCPY(&pv, input + i, OPAQUE16_LEN);
2449 i += OPAQUE16_LEN;
2450 ret = CheckVersion(ssl, pv);
2451 if (ret != 0)
2452 return ret;
2453
2454#ifndef WOLFSSL_TLS13_DRAFT_18
2455 /* Set the cipher suite from the message. */
2456 ssl->options.cipherSuite0 = input[i++];
2457 ssl->options.cipherSuite = input[i++];
2458
2459 ret = SetCipherSpecs(ssl);
2460 if (ret != 0)
2461 return ret;
2462#endif
2463
2464 /* Length of extension data. */
2465 ato16(&input[i], &totalExtSz);
2466 i += OPAQUE16_LEN;
2467 if (totalExtSz == 0) {
2468 WOLFSSL_MSG("HelloRetryRequest must contain extensions");
2469 return MISSING_HANDSHAKE_DATA;
2470 }
2471
2472 /* Extension data. */
2473 if (i - begin + totalExtSz > totalSz)
2474 return BUFFER_ERROR;
2475 if ((ret = TLSX_Parse(ssl, (byte *)(input + i), totalExtSz,
2476 hello_retry_request, NULL)) != 0)
2477 return ret;
2478 /* The KeyShare extension parsing fails when not valid. */
2479
2480 /* Move index to byte after message. */
2481 *inOutIdx = i + totalExtSz;
2482
2483 ssl->options.tls1_3 = 1;
2484 ssl->options.serverState = SERVER_HELLO_RETRY_REQUEST;
2485
2486#ifndef WOLFSSL_TLS13_DRAFT_18
2487 ret = RestartHandshakeHash(ssl);
2488#endif
2489
2490 WOLFSSL_LEAVE("DoTls13HelloRetryRequest", ret);
2491
2492 return ret;
2493}
2494
2495/* Handle the ServerHello message from the server.
2496 * Only a client will receive this message.
2497 *
2498 * ssl The SSL/TLS object.
2499 * input The message buffer.
2500 * inOutIdx On entry, the index into the message buffer of ServerHello.
2501 * On exit, the index of byte after the ServerHello message.
2502 * helloSz The length of the current handshake message.
2503 * returns 0 on success and otherwise failure.
2504 */
2505int DoTls13ServerHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
2506 word32 helloSz)
2507{
2508 ProtocolVersion pv;
2509 word32 i = *inOutIdx;
2510 word32 begin = i;
2511 int ret;
2512 word16 totalExtSz;
2513#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
2514 TLSX* ext;
2515 PreSharedKey* psk = NULL;
2516#endif
2517
2518 WOLFSSL_ENTER("DoTls13ServerHello");
2519
2520#ifdef WOLFSSL_CALLBACKS
2521 if (ssl->hsInfoOn) AddPacketName("ServerHello", &ssl->handShakeInfo);
2522 if (ssl->toInfoOn) AddLateName("ServerHello", &ssl->timeoutInfo);
2523#endif
2524
2525 /* Protocol version length check. */
2526 if (OPAQUE16_LEN > helloSz)
2527 return BUFFER_ERROR;
2528
2529 /* Protocol version */
2530 XMEMCPY(&pv, input + i, OPAQUE16_LEN);
2531 i += OPAQUE16_LEN;
2532 ret = CheckVersion(ssl, pv);
2533 if (ret != 0)
2534 return ret;
2535 if (!IsAtLeastTLSv1_3(pv) && pv.major != TLS_DRAFT_MAJOR) {
2536 if (ssl->options.downgrade) {
2537 ssl->version = pv;
2538 return DoServerHello(ssl, input, inOutIdx, helloSz);
2539 }
2540
2541 WOLFSSL_MSG("CLient using higher version, fatal error");
2542 return VERSION_ERROR;
2543 }
2544
2545 /* Random, cipher suite and extensions length check. */
2546 if ((i - begin) + RAN_LEN + OPAQUE16_LEN + OPAQUE16_LEN > helloSz)
2547 return BUFFER_ERROR;
2548
2549 /* Server random - keep for debugging. */
2550 XMEMCPY(ssl->arrays->serverRandom, input + i, RAN_LEN);
2551 i += RAN_LEN;
2552
2553 /* Set the cipher suite from the message. */
2554 ssl->options.cipherSuite0 = input[i++];
2555 ssl->options.cipherSuite = input[i++];
2556
2557 /* Get extension length and length check. */
2558 ato16(&input[i], &totalExtSz);
2559 i += OPAQUE16_LEN;
2560 if ((i - begin) + totalExtSz > helloSz)
2561 return BUFFER_ERROR;
2562
2563 /* Parse and handle extensions. */
2564 ret = TLSX_Parse(ssl, (byte *) input + i, totalExtSz, server_hello, NULL);
2565 if (ret != 0)
2566 return ret;
2567
2568 i += totalExtSz;
2569 *inOutIdx = i;
2570
2571 ssl->options.serverState = SERVER_HELLO_COMPLETE;
2572
2573#ifdef HAVE_SECRET_CALLBACK
2574 if (ssl->sessionSecretCb != NULL) {
2575 int secretSz = SECRET_LEN;
2576 ret = ssl->sessionSecretCb(ssl, ssl->session.masterSecret,
2577 &secretSz, ssl->sessionSecretCtx);
2578 if (ret != 0 || secretSz != SECRET_LEN)
2579 return SESSION_SECRET_CB_E;
2580 }
2581#endif /* HAVE_SECRET_CALLBACK */
2582
2583 ret = SetCipherSpecs(ssl);
2584 if (ret != 0)
2585 return ret;
2586
2587#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
2588 ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
2589 if (ext != NULL)
2590 psk = (PreSharedKey*)ext->data;
2591 while (psk != NULL && !psk->chosen)
2592 psk = psk->next;
2593 if (psk == NULL) {
2594 ssl->options.resuming = 0;
2595 ssl->arrays->psk_keySz = 0;
2596 XMEMSET(ssl->arrays->psk_key, 0, MAX_PSK_KEY_LEN);
2597 }
2598 else if ((ret = SetupPskKey(ssl, psk)) != 0)
2599 return ret;
2600#endif
2601
2602 ssl->keys.encryptionOn = 1;
2603
2604 WOLFSSL_LEAVE("DoTls13ServerHello", ret);
2605
2606 return ret;
2607}
2608
2609/* Parse and handle an EncryptedExtensions message.
2610 * Only a client will receive this message.
2611 *
2612 * ssl The SSL/TLS object.
2613 * input The message buffer.
2614 * inOutIdx On entry, the index into the message buffer of
2615 * EncryptedExtensions.
2616 * On exit, the index of byte after the EncryptedExtensions
2617 * message.
2618 * totalSz The length of the current handshake message.
2619 * returns 0 on success and otherwise failure.
2620 */
2621static int DoTls13EncryptedExtensions(WOLFSSL* ssl, const byte* input,
2622 word32* inOutIdx, word32 totalSz)
2623{
2624 int ret;
2625 word32 begin = *inOutIdx;
2626 word32 i = begin;
2627 word16 totalExtSz;
2628
2629 WOLFSSL_ENTER("DoTls13EncryptedExtensions");
2630
2631#ifdef WOLFSSL_CALLBACKS
2632 if (ssl->hsInfoOn) AddPacketName("EncryptedExtensions",
2633 &ssl->handShakeInfo);
2634 if (ssl->toInfoOn) AddLateName("EncryptedExtensions", &ssl->timeoutInfo);
2635#endif
2636
2637 /* Length field of extension data. */
2638 if (totalSz < i - begin + OPAQUE16_LEN)
2639 return BUFFER_ERROR;
2640 ato16(&input[i], &totalExtSz);
2641 i += OPAQUE16_LEN;
2642
2643 /* Extension data. */
2644 if (i - begin + totalExtSz > totalSz)
2645 return BUFFER_ERROR;
2646 if ((ret = TLSX_Parse(ssl, (byte *)(input + i), totalExtSz,
2647 encrypted_extensions, NULL)))
2648 return ret;
2649
2650 /* Move index to byte after message. */
2651 *inOutIdx = i + totalExtSz;
2652
2653 /* Always encrypted. */
2654 *inOutIdx += ssl->keys.padSz;
2655
2656#ifdef WOLFSSL_EARLY_DATA
2657 if (ssl->earlyData) {
2658 TLSX* ext = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
2659 if (ext == NULL || !ext->val)
2660 ssl->earlyData = 0;
2661 }
2662#endif
2663
2664 WOLFSSL_LEAVE("DoTls13EncryptedExtensions", ret);
2665
2666 return ret;
2667}
2668
2669/* Handle a TLS v1.3 CertificateRequest message.
2670 * This message is always encrypted.
2671 * Only a client will receive this message.
2672 *
2673 * ssl The SSL/TLS object.
2674 * input The message buffer.
2675 * inOutIdx On entry, the index into the message buffer of CertificateRequest.
2676 * On exit, the index of byte after the CertificateRequest message.
2677 * size The length of the current handshake message.
2678 * returns 0 on success and otherwise failure.
2679 */
2680static int DoTls13CertificateRequest(WOLFSSL* ssl, const byte* input,
2681 word32* inOutIdx, word32 size)
2682{
2683 word16 len;
2684 word32 begin = *inOutIdx;
2685 int ret = 0;
2686#ifndef WOLFSSL_TLS13_DRAFT_18
2687 Suites peerSuites;
2688#endif
2689#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
2690 CertReqCtx* certReqCtx;
2691#endif
2692
2693 WOLFSSL_ENTER("DoTls13CertificateRequest");
2694
2695#ifdef WOLFSSL_CALLBACKS
2696 if (ssl->hsInfoOn) AddPacketName("CertificateRequest", &ssl->handShakeInfo);
2697 if (ssl->toInfoOn) AddLateName("CertificateRequest", &ssl->timeoutInfo);
2698#endif
2699
2700 if ((*inOutIdx - begin) + OPAQUE8_LEN > size)
2701 return BUFFER_ERROR;
2702
2703 /* Length of the request context. */
2704 len = input[(*inOutIdx)++];
2705 if ((*inOutIdx - begin) + len > size)
2706 return BUFFER_ERROR;
2707 if (ssl->options.connectState < FINISHED_DONE && len > 0)
2708 return BUFFER_ERROR;
2709
2710#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
2711 /* CertReqCtx has one byte at end for context value.
2712 * Increase size to handle other implementations sending more than one byte.
2713 * That is, allocate extra space, over one byte, to hold the context value.
2714 */
2715 certReqCtx = (CertReqCtx*)XMALLOC(sizeof(CertReqCtx) + len - 1, ssl->heap,
2716 DYNAMIC_TYPE_TMP_BUFFER);
2717 if (certReqCtx == NULL)
2718 return MEMORY_E;
2719 certReqCtx->next = ssl->certReqCtx;
2720 certReqCtx->len = len;
2721 XMEMCPY(&certReqCtx->ctx, input + *inOutIdx, len);
2722 ssl->certReqCtx = certReqCtx;
2723#endif
2724 *inOutIdx += len;
2725
2726#ifdef WOLFSSL_TLS13_DRAFT_18
2727 /* Signature and hash algorithms. */
2728 if ((*inOutIdx - begin) + OPAQUE16_LEN > size)
2729 return BUFFER_ERROR;
2730 ato16(input + *inOutIdx, &len);
2731 *inOutIdx += OPAQUE16_LEN;
2732 if ((*inOutIdx - begin) + len > size)
2733 return BUFFER_ERROR;
2734 PickHashSigAlgo(ssl, input + *inOutIdx, len);
2735 *inOutIdx += len;
2736
2737 /* Length of certificate authority data. */
2738 if ((*inOutIdx - begin) + OPAQUE16_LEN > size)
2739 return BUFFER_ERROR;
2740 ato16(input + *inOutIdx, &len);
2741 *inOutIdx += OPAQUE16_LEN;
2742 if ((*inOutIdx - begin) + len > size)
2743 return BUFFER_ERROR;
2744
2745 /* Certificate authorities. */
2746 while (len) {
2747 word16 dnSz;
2748
2749 if ((*inOutIdx - begin) + OPAQUE16_LEN > size)
2750 return BUFFER_ERROR;
2751
2752 ato16(input + *inOutIdx, &dnSz);
2753 *inOutIdx += OPAQUE16_LEN;
2754
2755 if ((*inOutIdx - begin) + dnSz > size)
2756 return BUFFER_ERROR;
2757
2758 *inOutIdx += dnSz;
2759 len -= OPAQUE16_LEN + dnSz;
2760 }
2761
2762 /* Certificate extensions */
2763 if ((*inOutIdx - begin) + OPAQUE16_LEN > size)
2764 return BUFFER_ERROR;
2765 ato16(input + *inOutIdx, &len);
2766 *inOutIdx += OPAQUE16_LEN;
2767 if ((*inOutIdx - begin) + len > size)
2768 return BUFFER_ERROR;
2769 *inOutIdx += len;
2770#else
2771 /* TODO: Add support for more extensions:
2772 * signed_certificate_timestamp, certificate_authorities, oid_filters.
2773 */
2774 /* Certificate extensions */
2775 if ((*inOutIdx - begin) + OPAQUE16_LEN > size)
2776 return BUFFER_ERROR;
2777 ato16(input + *inOutIdx, &len);
2778 *inOutIdx += OPAQUE16_LEN;
2779 if ((*inOutIdx - begin) + len > size)
2780 return BUFFER_ERROR;
2781 if (len == 0)
2782 return INVALID_PARAMETER;
2783 if ((ret = TLSX_Parse(ssl, (byte *)(input + *inOutIdx), len,
2784 certificate_request, &peerSuites))) {
2785 return ret;
2786 }
2787 *inOutIdx += len;
2788
2789 PickHashSigAlgo(ssl, peerSuites.hashSigAlgo, peerSuites.hashSigAlgoSz);
2790#endif
2791
2792 if (ssl->buffers.certificate && ssl->buffers.certificate->buffer &&
2793 ssl->buffers.key && ssl->buffers.key->buffer)
2794 ssl->options.sendVerify = SEND_CERT;
2795 else
2796 ssl->options.sendVerify = SEND_BLANK_CERT;
2797
2798 /* This message is always encrypted so add encryption padding. */
2799 *inOutIdx += ssl->keys.padSz;
2800
2801#if !defined(NO_WOLFSSL_CLIENT) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
2802 if (ssl->options.side == WOLFSSL_CLIENT_END &&
2803 ssl->options.handShakeState == HANDSHAKE_DONE) {
2804 /* reset handshake states */
2805 ssl->options.clientState = CLIENT_HELLO_COMPLETE;
2806 ssl->options.connectState = FIRST_REPLY_DONE;
2807 ssl->options.handShakeState = CLIENT_HELLO_COMPLETE;
2808 }
2809#endif
2810
2811 WOLFSSL_LEAVE("DoTls13CertificateRequest", ret);
2812
2813 return ret;
2814}
2815
2816#endif /* !NO_WOLFSSL_CLIENT */
2817
2818#ifndef NO_WOLFSSL_SERVER
2819#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
2820/* Handle any Pre-Shared Key (PSK) extension.
2821 * Must do this in ClientHello as it requires a hash of the truncated message.
2822 * Don't know size of binders until Pre-Shared Key extension has been parsed.
2823 *
2824 * ssl The SSL/TLS object.
2825 * input The ClientHello message.
2826 * helloSz The size of the ClientHello message (including binders if present).
2827 * usingPSK Indicates handshake is using Pre-Shared Keys.
2828 * returns 0 on success and otherwise failure.
2829 */
2830static int DoPreSharedKeys(WOLFSSL* ssl, const byte* input, word32 helloSz,
2831 int* usingPSK)
2832{
2833 int ret;
2834 TLSX* ext;
2835 word16 bindersLen;
2836 PreSharedKey* current;
2837 byte binderKey[MAX_DIGEST_SIZE];
2838 byte binder[MAX_DIGEST_SIZE];
2839 word32 binderLen;
2840 word16 modes;
2841#ifdef WOLFSSL_EARLY_DATA
2842 int pskCnt = 0;
2843 TLSX* extEarlyData;
2844#endif
2845
2846 ext = TLSX_Find(ssl->extensions, TLSX_PRE_SHARED_KEY);
2847 if (ext == NULL) {
2848#ifdef WOLFSSL_EARLY_DATA
2849 ssl->earlyData = 0;
2850#endif
2851 return 0;
2852 }
2853
2854 /* Extensions pushed on stack/list and PSK must be last. */
2855 if (ssl->extensions != ext)
2856 return PSK_KEY_ERROR;
2857
2858 /* Assume we are going to resume with a pre-shared key. */
2859 ssl->options.resuming = 1;
2860
2861 /* Find the pre-shared key extension and calculate hash of truncated
2862 * ClientHello for binders.
2863 */
2864 bindersLen = TLSX_PreSharedKey_GetSizeBinders((PreSharedKey*)ext->data,
2865 client_hello);
2866
2867 /* Hash data up to binders for deriving binders in PSK extension. */
2868 ret = HashInput(ssl, input, helloSz - bindersLen);
2869 if (ret != 0)
2870 return ret;
2871
2872 /* Look through all client's pre-shared keys for a match. */
2873 current = (PreSharedKey*)ext->data;
2874 while (current != NULL) {
2875 #ifdef WOLFSSL_EARLY_DATA
2876 pskCnt++;
2877 #endif
2878
2879 #ifndef NO_PSK
2880 XMEMCPY(ssl->arrays->client_identity, current->identity,
2881 current->identityLen);
2882 ssl->arrays->client_identity[current->identityLen] = '\0';
2883 #endif
2884
2885 #ifdef HAVE_SESSION_TICKET
2886 /* Decode the identity. */
2887 if ((ret = DoClientTicket(ssl, current->identity, current->identityLen))
2888 == WOLFSSL_TICKET_RET_OK) {
2889 word32 now;
2890 int diff;
2891
2892 now = TimeNowInMilliseconds();
2893 if (now == (word32)GETTIME_ERROR)
2894 return now;
2895 diff = now - ssl->session.ticketSeen;
2896 diff -= current->ticketAge - ssl->session.ticketAdd;
2897 /* Check session and ticket age timeout.
2898 * Allow +/- 1000 milliseconds on ticket age.
2899 */
2900 if (diff > (int)ssl->timeout * 1000 || diff < -1000 ||
2901 diff - MAX_TICKET_AGE_SECS * 1000 > 1000) {
2902 /* Invalid difference, fallback to full handshake. */
2903 ssl->options.resuming = 0;
2904 break;
2905 }
2906
2907 #ifdef WOLFSSL_EARLY_DATA
2908 ssl->options.maxEarlyDataSz = ssl->session.maxEarlyDataSz;
2909 #endif
2910 /* Use the same cipher suite as before and set up for use. */
2911 ssl->options.cipherSuite0 = ssl->session.cipherSuite0;
2912 ssl->options.cipherSuite = ssl->session.cipherSuite;
2913 ret = SetCipherSpecs(ssl);
2914 if (ret != 0)
2915 return ret;
2916
2917 /* Resumption PSK is resumption master secret. */
2918 ssl->arrays->psk_keySz = ssl->specs.hash_size;
2919 XMEMCPY(ssl->arrays->psk_key, ssl->session.masterSecret,
2920 ssl->specs.hash_size);
2921
2922 /* Derive the early secret using the PSK. */
2923 ret = DeriveEarlySecret(ssl);
2924 if (ret != 0)
2925 return ret;
2926 /* Derive the binder key to use to with HMAC. */
2927 ret = DeriveBinderKeyResume(ssl, binderKey);
2928 if (ret != 0)
2929 return ret;
2930 }
2931 else
2932 #endif
2933 #ifndef NO_PSK
2934 if (ssl->options.server_psk_cb != NULL &&
2935 (ssl->arrays->psk_keySz = ssl->options.server_psk_cb(ssl,
2936 ssl->arrays->client_identity, ssl->arrays->psk_key,
2937 MAX_PSK_KEY_LEN)) != 0) {
2938 if (ssl->arrays->psk_keySz > MAX_PSK_KEY_LEN)
2939 return PSK_KEY_ERROR;
2940
2941 ssl->options.resuming = 0;
2942
2943 /* PSK age is always zero. */
2944 if (current->ticketAge != ssl->session.ticketAdd)
2945 return PSK_KEY_ERROR;
2946
2947 /* TODO: Callback should be able to change ciphersuite. */
2948 /* Default to ciphersuite if cb doesn't specify. */
2949 ssl->options.cipherSuite0 = TLS13_BYTE;
2950 ssl->options.cipherSuite = WOLFSSL_DEF_PSK_CIPHER;
2951 ret = SetCipherSpecs(ssl);
2952 if (ret != 0)
2953 return ret;
2954
2955 /* Derive the early secret using the PSK. */
2956 ret = DeriveEarlySecret(ssl);
2957 if (ret != 0)
2958 return ret;
2959 /* Derive the binder key to use to with HMAC. */
2960 ret = DeriveBinderKey(ssl, binderKey);
2961 if (ret != 0)
2962 return ret;
2963 }
2964 else
2965 #endif
2966 {
2967 current = current->next;
2968 continue;
2969 }
2970
2971 ssl->options.sendVerify = 0;
2972
2973 /* Derive the Finished message secret. */
2974 ret = DeriveFinishedSecret(ssl, binderKey,
2975 ssl->keys.client_write_MAC_secret);
2976 if (ret != 0)
2977 return ret;
2978
2979 /* Derive the binder and compare with the one in the extension. */
2980 ret = BuildTls13HandshakeHmac(ssl,
2981 ssl->keys.client_write_MAC_secret, binder, &binderLen);
2982 if (ret != 0)
2983 return ret;
2984 if (binderLen != current->binderLen ||
2985 XMEMCMP(binder, current->binder, binderLen) != 0) {
2986 return BAD_BINDER;
2987 }
2988
2989 /* This PSK works, no need to try any more. */
2990 current->chosen = 1;
2991 ext->resp = 1;
2992 break;
2993 }
2994
2995 /* Hash the rest of the ClientHello. */
2996 ret = HashInputRaw(ssl, input + helloSz - bindersLen, bindersLen);
2997 if (ret != 0)
2998 return ret;
2999
3000#ifdef WOLFSSL_EARLY_DATA
3001 extEarlyData = TLSX_Find(ssl->extensions, TLSX_EARLY_DATA);
3002 if (extEarlyData != NULL) {
3003 if (ssl->earlyData && current == ext->data) {
3004 extEarlyData->resp = 1;
3005
3006 /* Derive early data decryption key. */
3007 ret = DeriveTls13Keys(ssl, early_data_key, DECRYPT_SIDE_ONLY, 1);
3008 if (ret != 0)
3009 return ret;
3010 if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
3011 return ret;
3012
3013 ssl->earlyData = 2;
3014 }
3015 else
3016 extEarlyData->resp = 0;
3017 }
3018#endif
3019
3020 /* Get the PSK key exchange modes the client wants to negotiate. */
3021 ext = TLSX_Find(ssl->extensions, TLSX_PSK_KEY_EXCHANGE_MODES);
3022 if (ext == NULL)
3023 return MISSING_HANDSHAKE_DATA;
3024 modes = ext->val;
3025
3026 ext = TLSX_Find(ssl->extensions, TLSX_KEY_SHARE);
3027 /* Use (EC)DHE for forward-security if possible. */
3028 if ((modes & (1 << PSK_DHE_KE)) != 0 && !ssl->options.noPskDheKe &&
3029 ext != NULL) {
3030 /* Only use named group used in last session. */
3031 ssl->namedGroup = ssl->session.namedGroup;
3032
3033 /* Try to establish a new secret. */
3034 ret = TLSX_KeyShare_Establish(ssl);
3035 if (ret == KEY_SHARE_ERROR)
3036 return PSK_KEY_ERROR;
3037 else if (ret < 0)
3038 return ret;
3039
3040 /* Send new public key to client. */
3041 ext->resp = 1;
3042 }
3043 else if ((modes & (1 << PSK_KE)) == 0)
3044 return PSK_KEY_ERROR;
3045
3046 *usingPSK = 1;
3047
3048 return ret;
3049}
3050#endif
3051
3052#if !defined(WOLFSSL_TLS13_DRAFT_18) && defined(WOLFSSL_SEND_HRR_COOKIE)
3053/* Check that the Cookie data's integrity.
3054 *
3055 * ssl SSL/TLS object.
3056 * cookie The cookie data - hash and MAC.
3057 * cookieSz The length of the cookie data in bytes.
3058 * returns Length of the hash on success, otherwise failure.
3059 */
3060static int CheckCookie(WOLFSSL* ssl, byte* cookie, byte cookieSz)
3061{
3062 int ret;
3063 byte mac[MAX_DIGEST_SIZE];
3064 Hmac cookieHmac;
3065 byte cookieType;
3066 byte macSz;
3067
3068#if !defined(NO_SHA) && defined(NO_SHA256)
3069 cookieType = SHA;
3070 macSz = WC_SHA_DIGEST_SIZE;
3071#endif /* NO_SHA */
3072#ifndef NO_SHA256
3073 cookieType = WC_SHA256;
3074 macSz = WC_SHA256_DIGEST_SIZE;
3075#endif /* NO_SHA256 */
3076
3077 if (cookieSz < ssl->specs.hash_size + macSz)
3078 return HRR_COOKIE_ERROR;
3079 cookieSz -= macSz;
3080
3081 ret = wc_HmacSetKey(&cookieHmac, cookieType,
3082 ssl->buffers.tls13CookieSecret.buffer,
3083 ssl->buffers.tls13CookieSecret.length);
3084 if (ret != 0)
3085 return ret;
3086 if ((ret = wc_HmacUpdate(&cookieHmac, cookie, cookieSz)) != 0)
3087 return ret;
3088 if ((ret = wc_HmacFinal(&cookieHmac, mac)) != 0)
3089 return ret;
3090
3091 if (ConstantCompare(cookie + cookieSz, mac, macSz) != 0)
3092 return HRR_COOKIE_ERROR;
3093 return cookieSz;
3094}
3095
3096/* Length of the KeyShare Extension */
3097#define HRR_KEY_SHARE_SZ (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
3098/* Length of the Cookie Extension excluding cookie data */
3099#define HRR_COOKIE_HDR_SZ (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
3100/* PV | CipherSuite | Ext Len */
3101#define HRR_BODY_SZ (OPAQUE16_LEN + OPAQUE16_LEN + OPAQUE16_LEN)
3102/* HH | PV | CipherSuite | Ext Len | Key Share | Cookie */
3103#define MAX_HRR_SZ (HANDSHAKE_HEADER_SZ + \
3104 HRR_BODY_SZ + \
3105 HRR_KEY_SHARE_SZ + \
3106 HRR_COOKIE_HDR_SZ)
3107/* Restart the Hanshake hash from the cookie value.
3108 *
3109 * ssl SSL/TLS object.
3110 * cookie Cookie data from client.
3111 * returns 0 on success, otherwise failure.
3112 */
3113static int RestartHandshakeHashWithCookie(WOLFSSL* ssl, Cookie* cookie)
3114{
3115 byte header[HANDSHAKE_HEADER_SZ];
3116 byte hrr[MAX_HRR_SZ];
3117 int hrrIdx;
3118 word32 idx;
3119 byte hashSz;
3120 byte* cookieData;
3121 byte cookieDataSz;
3122 word16 length;
3123 int keyShareExt = 0;
3124 int ret;
3125
3126 cookieDataSz = ret = CheckCookie(ssl, &cookie->data, cookie->len);
3127 if (ret < 0)
3128 return ret;
3129 hashSz = cookie->data;
3130 cookieData = &cookie->data;
3131 idx = OPAQUE8_LEN;
3132
3133 /* Restart handshake hash with synthetic message hash. */
3134 AddTls13HandShakeHeader(header, hashSz, 0, 0, message_hash, ssl);
3135 if ((ret = InitHandshakeHashes(ssl)) != 0)
3136 return ret;
3137 if ((ret = HashOutputRaw(ssl, header, sizeof(header))) != 0)
3138 return ret;
3139 if ((ret = HashOutputRaw(ssl, cookieData + idx, hashSz)) != 0)
3140 return ret;
3141
3142 /* Reconstruct the HelloRetryMessage for handshake hash. */
3143 length = HRR_BODY_SZ + HRR_COOKIE_HDR_SZ + cookie->len;
3144 if (cookieDataSz > hashSz + OPAQUE16_LEN) {
3145 keyShareExt = 1;
3146 length += HRR_KEY_SHARE_SZ;
3147 }
3148 AddTls13HandShakeHeader(hrr, length, 0, 0, hello_retry_request, ssl);
3149
3150 idx += hashSz;
3151 hrrIdx = HANDSHAKE_HEADER_SZ;
3152 /* TODO: [TLS13] Replace existing code with code in comment.
3153 * Use the TLS v1.3 draft version for now.
3154 *
3155 * Change to:
3156 * hrr[hrrIdx++] = ssl->version.major;
3157 * hrr[hrrIdx++] = ssl->version.minor;
3158 */
3159 /* The negotiated protocol version. */
3160 hrr[hrrIdx++] = TLS_DRAFT_MAJOR;
3161 hrr[hrrIdx++] = TLS_DRAFT_MINOR;
3162 /* Cipher Suite */
3163 hrr[hrrIdx++] = cookieData[idx++];
3164 hrr[hrrIdx++] = cookieData[idx++];
3165
3166 /* Extensions' length */
3167 length -= HRR_BODY_SZ;
3168 c16toa(length, hrr + hrrIdx);
3169 hrrIdx += 2;
3170 /* Optional KeyShare Extension */
3171 if (keyShareExt) {
3172 c16toa(TLSX_KEY_SHARE, hrr + hrrIdx);
3173 hrrIdx += 2;
3174 c16toa(OPAQUE16_LEN, hrr + hrrIdx);
3175 hrrIdx += 2;
3176 hrr[hrrIdx++] = cookieData[idx++];
3177 hrr[hrrIdx++] = cookieData[idx++];
3178 }
3179 /* Mandatory Cookie Extension */
3180 c16toa(TLSX_COOKIE, hrr + hrrIdx);
3181 hrrIdx += 2;
3182 c16toa(cookie->len + OPAQUE16_LEN, hrr + hrrIdx);
3183 hrrIdx += 2;
3184 c16toa(cookie->len, hrr + hrrIdx);
3185 hrrIdx += 2;
3186
3187#ifdef WOLFSSL_DEBUG_TLS
3188 WOLFSSL_MSG("Reconstucted HelloRetryRequest");
3189 WOLFSSL_BUFFER(hrr, hrrIdx);
3190 WOLFSSL_MSG("Cookie");
3191 WOLFSSL_BUFFER(cookieData, cookie->len);
3192#endif
3193
3194 if ((ret = HashOutputRaw(ssl, hrr, hrrIdx)) != 0)
3195 return ret;
3196 return HashOutputRaw(ssl, cookieData, cookie->len);
3197}
3198#endif
3199
3200/* Handle a ClientHello handshake message.
3201 * If the protocol version in the message is not TLS v1.3 or higher, use
3202 * DoClientHello()
3203 * Only a server will receive this message.
3204 *
3205 * ssl The SSL/TLS object.
3206 * input The message buffer.
3207 * inOutIdx On entry, the index into the message buffer of ClientHello.
3208 * On exit, the index of byte after the ClientHello message and
3209 * padding.
3210 * helloSz The length of the current handshake message.
3211 * returns 0 on success and otherwise failure.
3212 */
3213int DoTls13ClientHello(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
3214 word32 helloSz)
3215{
3216 int ret;
3217 byte b;
3218 ProtocolVersion pv;
3219 Suites clSuites;
3220 word32 i = *inOutIdx;
3221 word32 begin = i;
3222 word16 totalExtSz;
3223 int usingPSK = 0;
3224 byte sessIdSz;
3225
3226 WOLFSSL_ENTER("DoTls13ClientHello");
3227
3228#ifdef WOLFSSL_CALLBACKS
3229 if (ssl->hsInfoOn) AddPacketName("ClientHello", &ssl->handShakeInfo);
3230 if (ssl->toInfoOn) AddLateName("ClientHello", &ssl->timeoutInfo);
3231#endif
3232
3233 /* protocol version, random and session id length check */
3234 if ((i - begin) + OPAQUE16_LEN + RAN_LEN + OPAQUE8_LEN > helloSz)
3235 return BUFFER_ERROR;
3236
3237 /* Protocol version */
3238 XMEMCPY(&pv, input + i, OPAQUE16_LEN);
3239 ssl->chVersion = pv; /* store */
3240 i += OPAQUE16_LEN;
3241
3242 if (ssl->version.major == SSLv3_MAJOR && ssl->version.minor < TLSv1_3_MINOR)
3243 return DoClientHello(ssl, input, inOutIdx, helloSz);
3244
3245 /* Client random */
3246 XMEMCPY(ssl->arrays->clientRandom, input + i, RAN_LEN);
3247 i += RAN_LEN;
3248
3249#ifdef WOLFSSL_DEBUG_TLS
3250 WOLFSSL_MSG("client random");
3251 WOLFSSL_BUFFER(ssl->arrays->clientRandom, RAN_LEN);
3252#endif
3253
3254 /* Session id - empty in TLS v1.3 */
3255 sessIdSz = input[i++];
3256 if (sessIdSz > 0) {
3257 WOLFSSL_MSG("Client sent session id - not supported");
3258 return BUFFER_ERROR;
3259 }
3260
3261 /* Cipher suites */
3262 if ((i - begin) + OPAQUE16_LEN > helloSz)
3263 return BUFFER_ERROR;
3264 ato16(&input[i], &clSuites.suiteSz);
3265 i += OPAQUE16_LEN;
3266 /* suites and compression length check */
3267 if ((i - begin) + clSuites.suiteSz + OPAQUE8_LEN > helloSz)
3268 return BUFFER_ERROR;
3269 if (clSuites.suiteSz > WOLFSSL_MAX_SUITE_SZ)
3270 return BUFFER_ERROR;
3271 XMEMCPY(clSuites.suites, input + i, clSuites.suiteSz);
3272 i += clSuites.suiteSz;
3273 clSuites.hashSigAlgoSz = 0;
3274
3275 /* Compression */
3276 b = input[i++];
3277 if ((i - begin) + b > helloSz)
3278 return BUFFER_ERROR;
3279 if (b != COMP_LEN) {
3280 WOLFSSL_MSG("Must be one compression type in list");
3281 return INVALID_PARAMETER;
3282 }
3283 b = input[i++];
3284 if (b != NO_COMPRESSION) {
3285 WOLFSSL_MSG("Must be no compression type in list");
3286 return INVALID_PARAMETER;
3287 }
3288
3289 /* TLS v1.3 ClientHello messages will have extensions. */
3290 if ((i - begin) >= helloSz) {
3291 WOLFSSL_MSG("ClientHello must have extensions in TLS v1.3");
3292 return BUFFER_ERROR;
3293 }
3294 if ((i - begin) + OPAQUE16_LEN > helloSz)
3295 return BUFFER_ERROR;
3296 ato16(&input[i], &totalExtSz);
3297 i += OPAQUE16_LEN;
3298 if ((i - begin) + totalExtSz > helloSz)
3299 return BUFFER_ERROR;
3300
3301#ifdef HAVE_QSH
3302 QSH_Init(ssl);
3303#endif
3304
3305 /* Auto populate extensions supported unless user defined. */
3306 if ((ret = TLSX_PopulateExtensions(ssl, 1)) != 0)
3307 return ret;
3308
3309 /* Parse extensions */
3310 if ((ret = TLSX_Parse(ssl, (byte*)input + i, totalExtSz, client_hello,
3311 &clSuites))) {
3312 return ret;
3313 }
3314
3315#ifdef HAVE_STUNNEL
3316 if ((ret = SNI_Callback(ssl)) != 0)
3317 return ret;
3318#endif /*HAVE_STUNNEL*/
3319
3320 if (TLSX_Find(ssl->extensions, TLSX_SUPPORTED_VERSIONS) == NULL) {
3321 if (!ssl->options.downgrade) {
3322 WOLFSSL_MSG("Client trying to connect with lesser version");
3323 return VERSION_ERROR;
3324 }
3325 ssl->version.minor = pv.minor;
3326 }
3327
3328#ifdef WOLFSSL_SEND_HRR_COOKIE
3329 if (ssl->options.sendCookie &&
3330 ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST) {
3331 TLSX* ext;
3332
3333 if ((ext = TLSX_Find(ssl->extensions, TLSX_COOKIE)) == NULL)
3334 return HRR_COOKIE_ERROR;
3335 /* Ensure the cookie came from client and isn't the one in the response
3336 * - HelloRetryRequest.
3337 */
3338 if (ext->resp == 1)
3339 return HRR_COOKIE_ERROR;
3340 ret = RestartHandshakeHashWithCookie(ssl, (Cookie*)ext->data);
3341 if (ret != 0)
3342 return ret;
3343 }
3344#endif
3345
3346 ssl->options.sendVerify = SEND_CERT;
3347
3348#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
3349 /* Process the Pre-Shared Key extension if present. */
3350 ret = DoPreSharedKeys(ssl, input + begin, helloSz, &usingPSK);
3351 if (ret != 0)
3352 return ret;
3353#endif
3354
3355 if (!usingPSK) {
3356 if ((ret = MatchSuite(ssl, &clSuites)) < 0) {
3357 WOLFSSL_MSG("Unsupported cipher suite, ClientHello");
3358 return ret;
3359 }
3360
3361#ifdef HAVE_SESSION_TICKET
3362 if (ssl->options.resuming) {
3363 ssl->options.resuming = 0;
3364 XMEMSET(ssl->arrays->psk_key, 0, ssl->specs.hash_size);
3365 /* May or may not have done any hashing. */
3366 if ((ret = InitHandshakeHashes(ssl)) != 0)
3367 return ret;
3368 }
3369#endif
3370
3371 if ((ret = HashInput(ssl, input + begin, helloSz)) != 0)
3372 return ret;
3373
3374 /* Derive early secret for handshake secret. */
3375 if ((ret = DeriveEarlySecret(ssl)) != 0)
3376 return ret;
3377 }
3378
3379 i += totalExtSz;
3380 *inOutIdx = i;
3381
3382 ssl->options.clientState = CLIENT_HELLO_COMPLETE;
3383
3384 WOLFSSL_LEAVE("DoTls13ClientHello", ret);
3385
3386 return ret;
3387}
3388
3389/* Send the HelloRetryRequest message to indicate the negotiated protocol
3390 * version and security parameters the server is willing to use.
3391 * Only a server will send this message.
3392 *
3393 * ssl The SSL/TLS object.
3394 * returns 0 on success, otherwise failure.
3395 */
3396int SendTls13HelloRetryRequest(WOLFSSL* ssl)
3397{
3398 int ret;
3399 byte* output;
3400 word32 length;
3401 word32 len;
3402 word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
3403 int sendSz;
3404
3405 WOLFSSL_ENTER("SendTls13HelloRetryRequest");
3406
3407#ifndef WOLFSSL_TLS13_DRAFT_18
3408 if ((ret = RestartHandshakeHash(ssl)) < 0)
3409 return ret;
3410#endif
3411
3412 /* Get the length of the extensions that will be written. */
3413 len = TLSX_GetResponseSize(ssl, hello_retry_request);
3414 /* There must be extensions sent to indicate what client needs to do. */
3415 if (len == 0)
3416 return MISSING_HANDSHAKE_DATA;
3417
3418#ifndef WOLFSSL_TLS13_DRAFT_18
3419 /* Protocol version + CipherSuite + Extensions */
3420 length = OPAQUE16_LEN + OPAQUE16_LEN + len;
3421#else
3422 /* Protocol version + Extensions */
3423 length = OPAQUE16_LEN + len;
3424#endif
3425 sendSz = idx + length;
3426
3427 /* Check buffers are big enough and grow if needed. */
3428 if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
3429 return ret;
3430
3431 /* Get position in output buffer to write new message to. */
3432 output = ssl->buffers.outputBuffer.buffer +
3433 ssl->buffers.outputBuffer.length;
3434 /* Add record and hanshake headers. */
3435 AddTls13Headers(output, length, hello_retry_request, ssl);
3436
3437 /* TODO: [TLS13] Replace existing code with code in comment.
3438 * Use the TLS v1.3 draft version for now.
3439 *
3440 * Change to:
3441 * output[idx++] = ssl->version.major;
3442 * output[idx++] = ssl->version.minor;
3443 */
3444 /* The negotiated protocol version. */
3445 output[idx++] = TLS_DRAFT_MAJOR;
3446 output[idx++] = TLS_DRAFT_MINOR;
3447
3448#ifndef WOLFSSL_TLS13_DRAFT_18
3449 /* Chosen cipher suite */
3450 output[idx++] = ssl->options.cipherSuite0;
3451 output[idx++] = ssl->options.cipherSuite;
3452#endif
3453
3454 /* Add TLS extensions. */
3455 TLSX_WriteResponse(ssl, output + idx, hello_retry_request);
3456 idx += len;
3457
3458#ifdef WOLFSSL_CALLBACKS
3459 if (ssl->hsInfoOn)
3460 AddPacketName("HelloRetryRequest", &ssl->handShakeInfo);
3461 if (ssl->toInfoOn) {
3462 AddPacketInfo("HelloRetryRequest", &ssl->timeoutInfo, output, sendSz,
3463 ssl->heap);
3464 }
3465#endif
3466
3467 if ((ret = HashOutput(ssl, output, idx, 0)) != 0)
3468 return ret;
3469
3470 ssl->buffers.outputBuffer.length += sendSz;
3471
3472 if (!ssl->options.groupMessages)
3473 ret = SendBuffered(ssl);
3474
3475 WOLFSSL_LEAVE("SendTls13HelloRetryRequest", ret);
3476
3477 return ret;
3478}
3479
3480/* Send TLS v1.3 ServerHello message to client.
3481 * Only a server will send this message.
3482 *
3483 * ssl The SSL/TLS object.
3484 * returns 0 on success, otherwise failure.
3485 */
3486static int SendTls13ServerHello(WOLFSSL* ssl)
3487{
3488 byte* output;
3489 word32 length;
3490 word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
3491 int sendSz;
3492 int ret;
3493
3494 WOLFSSL_ENTER("SendTls13ServerHello");
3495
3496 /* Protocol version, server random, cipher suite and extensions. */
3497 length = VERSION_SZ + RAN_LEN + SUITE_LEN +
3498 TLSX_GetResponseSize(ssl, server_hello);
3499 sendSz = idx + length;
3500
3501 /* Check buffers are big enough and grow if needed. */
3502 if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
3503 return ret;
3504
3505 /* Get position in output buffer to write new message to. */
3506 output = ssl->buffers.outputBuffer.buffer +
3507 ssl->buffers.outputBuffer.length;
3508
3509 /* Put the record and handshake headers on. */
3510 AddTls13Headers(output, length, server_hello, ssl);
3511
3512 /* TODO: [TLS13] Replace existing code with code in comment.
3513 * Use the TLS v1.3 draft version for now.
3514 *
3515 * Change to:
3516 * output[idx++] = ssl->version.major;
3517 * output[idx++] = ssl->version.minor;
3518 */
3519 /* The negotiated protocol version. */
3520 output[idx++] = TLS_DRAFT_MAJOR;
3521 output[idx++] = TLS_DRAFT_MINOR;
3522
3523 /* Generate server random. */
3524 if ((ret = wc_RNG_GenerateBlock(ssl->rng, output + idx, RAN_LEN)) != 0)
3525 return ret;
3526 /* Store in SSL for debugging. */
3527 XMEMCPY(ssl->arrays->serverRandom, output + idx, RAN_LEN);
3528 idx += RAN_LEN;
3529
3530#ifdef WOLFSSL_DEBUG_TLS
3531 WOLFSSL_MSG("Server random");
3532 WOLFSSL_BUFFER(ssl->arrays->serverRandom, RAN_LEN);
3533#endif
3534
3535 /* Chosen cipher suite */
3536 output[idx++] = ssl->options.cipherSuite0;
3537 output[idx++] = ssl->options.cipherSuite;
3538
3539 /* Extensions */
3540 TLSX_WriteResponse(ssl, output + idx, server_hello);
3541
3542 ssl->buffers.outputBuffer.length += sendSz;
3543
3544 if ((ret = HashOutput(ssl, output, sendSz, 0)) != 0)
3545 return ret;
3546
3547 #ifdef WOLFSSL_CALLBACKS
3548 if (ssl->hsInfoOn)
3549 AddPacketName("ServerHello", &ssl->handShakeInfo);
3550 if (ssl->toInfoOn) {
3551 AddPacketInfo("ServerHello", &ssl->timeoutInfo, output, sendSz,
3552 ssl->heap);
3553 }
3554 #endif
3555
3556 ssl->options.serverState = SERVER_HELLO_COMPLETE;
3557
3558 if (!ssl->options.groupMessages)
3559 ret = SendBuffered(ssl);
3560
3561 WOLFSSL_LEAVE("SendTls13ServerHello", ret);
3562
3563 return ret;
3564}
3565
3566/* Send the rest of the extensions encrypted under the handshake key.
3567 * This message is always encrypted in TLS v1.3.
3568 * Only a server will send this message.
3569 *
3570 * ssl The SSL/TLS object.
3571 * returns 0 on success, otherwise failure.
3572 */
3573static int SendTls13EncryptedExtensions(WOLFSSL* ssl)
3574{
3575 int ret;
3576 byte* output;
3577 word32 length;
3578 word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
3579 int sendSz;
3580
3581 WOLFSSL_ENTER("SendTls13EncryptedExtensions");
3582
3583 ssl->keys.encryptionOn = 1;
3584
3585 /* Derive the handshake secret now that we are at first message to be
3586 * encrypted under the keys.
3587 */
3588 if ((ret = DeriveHandshakeSecret(ssl)) != 0)
3589 return ret;
3590 if ((ret = DeriveTls13Keys(ssl, handshake_key,
3591 ENCRYPT_AND_DECRYPT_SIDE, 1)) != 0)
3592 return ret;
3593
3594 /* Setup encrypt/decrypt keys for following messages. */
3595#ifdef WOLFSSL_EARLY_DATA
3596 if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
3597 return ret;
3598 if (ssl->earlyData != 2) {
3599 if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
3600 return ret;
3601 }
3602#else
3603 if ((ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE)) != 0)
3604 return ret;
3605#endif
3606
3607 length = TLSX_GetResponseSize(ssl, encrypted_extensions);
3608 sendSz = idx + length;
3609 /* Encryption always on. */
3610 sendSz += MAX_MSG_EXTRA;
3611
3612 /* Check buffers are big enough and grow if needed. */
3613 ret = CheckAvailableSize(ssl, sendSz);
3614 if (ret != 0)
3615 return ret;
3616
3617 /* Get position in output buffer to write new message to. */
3618 output = ssl->buffers.outputBuffer.buffer +
3619 ssl->buffers.outputBuffer.length;
3620
3621 /* Put the record and handshake headers on. */
3622 AddTls13Headers(output, length, encrypted_extensions, ssl);
3623
3624 TLSX_WriteResponse(ssl, output + idx, encrypted_extensions);
3625 idx += length;
3626
3627#ifdef WOLFSSL_CALLBACKS
3628 if (ssl->hsInfoOn)
3629 AddPacketName("EncryptedExtensions", &ssl->handShakeInfo);
3630 if (ssl->toInfoOn) {
3631 AddPacketInfo("EncryptedExtensions", &ssl->timeoutInfo, output,
3632 sendSz, ssl->heap);
3633 }
3634#endif
3635
3636 /* This handshake message is always encrypted. */
3637 sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ,
3638 idx - RECORD_HEADER_SZ, handshake, 1, 0, 0);
3639 if (sendSz < 0)
3640 return sendSz;
3641
3642 ssl->buffers.outputBuffer.length += sendSz;
3643
3644 ssl->options.serverState = SERVER_ENCRYPTED_EXTENSIONS_COMPLETE;
3645
3646 if (!ssl->options.groupMessages)
3647 ret = SendBuffered(ssl);
3648
3649 WOLFSSL_LEAVE("SendTls13EncryptedExtensions", ret);
3650
3651 return ret;
3652}
3653
3654#ifndef NO_CERTS
3655/* Send the TLS v1.3 CertificateRequest message.
3656 * This message is always encrypted in TLS v1.3.
3657 * Only a server will send this message.
3658 *
3659 * ssl SSL/TLS object.
3660 * reqCtx Request context.
3661 * reqCtxLen Length of context. 0 when sending as part of handshake.
3662 * returns 0 on success, otherwise failure.
3663 */
3664static int SendTls13CertificateRequest(WOLFSSL* ssl, byte* reqCtx,
3665 int reqCtxLen)
3666{
3667 byte* output;
3668 int ret;
3669 int sendSz;
3670 word32 i;
3671 int reqSz;
3672#ifndef WOLFSSL_TLS13_DRAFT_18
3673 TLSX* ext;
3674#endif
3675
3676 WOLFSSL_ENTER("SendTls13CertificateRequest");
3677
3678 if (ssl->options.side == WOLFSSL_SERVER_END)
3679 InitSuitesHashSigAlgo(ssl->suites, 1, 1, 0, 1, ssl->buffers.keySz);
3680
3681#ifdef WOLFSSL_TLS13_DRAFT_18
3682 i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
3683 reqSz = OPAQUE8_LEN + reqCtxLen + REQ_HEADER_SZ + REQ_HEADER_SZ;
3684 reqSz += LENGTH_SZ + ssl->suites->hashSigAlgoSz;
3685
3686 sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ + reqSz;
3687 /* Always encrypted and make room for padding. */
3688 sendSz += MAX_MSG_EXTRA;
3689
3690 /* Check buffers are big enough and grow if needed. */
3691 if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
3692 return ret;
3693
3694 /* Get position in output buffer to write new message to. */
3695 output = ssl->buffers.outputBuffer.buffer +
3696 ssl->buffers.outputBuffer.length;
3697
3698 /* Put the record and handshake headers on. */
3699 AddTls13Headers(output, reqSz, certificate_request, ssl);
3700
3701 /* Certificate request context. */
3702 output[i++] = reqCtxLen;
3703 if (reqCtxLen != 0) {
3704 XMEMCPY(output + i, reqCtx, reqCtxLen);
3705 i += reqCtxLen;
3706 }
3707
3708 /* supported hash/sig */
3709 c16toa(ssl->suites->hashSigAlgoSz, &output[i]);
3710 i += LENGTH_SZ;
3711
3712 XMEMCPY(&output[i], ssl->suites->hashSigAlgo, ssl->suites->hashSigAlgoSz);
3713 i += ssl->suites->hashSigAlgoSz;
3714
3715 /* Certificate authorities not supported yet - empty buffer. */
3716 c16toa(0, &output[i]);
3717 i += REQ_HEADER_SZ;
3718
3719 /* Certificate extensions. */
3720 c16toa(0, &output[i]); /* auth's */
3721 i += REQ_HEADER_SZ;
3722#else
3723 ext = TLSX_Find(ssl->extensions, TLSX_SIGNATURE_ALGORITHMS);
3724 if (ext == NULL)
3725 return EXT_MISSING;
3726 ext->resp = 0;
3727
3728 i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
3729 reqSz = OPAQUE8_LEN + reqCtxLen +
3730 TLSX_GetRequestSize(ssl, certificate_request);
3731
3732 sendSz = i + reqSz;
3733 /* Always encrypted and make room for padding. */
3734 sendSz += MAX_MSG_EXTRA;
3735
3736 /* Check buffers are big enough and grow if needed. */
3737 if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
3738 return ret;
3739
3740 /* Get position in output buffer to write new message to. */
3741 output = ssl->buffers.outputBuffer.buffer +
3742 ssl->buffers.outputBuffer.length;
3743
3744 /* Put the record and handshake headers on. */
3745 AddTls13Headers(output, reqSz, certificate_request, ssl);
3746
3747 /* Certificate request context. */
3748 output[i++] = reqCtxLen;
3749 if (reqCtxLen != 0) {
3750 XMEMCPY(output + i, reqCtx, reqCtxLen);
3751 i += reqCtxLen;
3752 }
3753
3754 /* Certificate extensions. */
3755 i += TLSX_WriteRequest(ssl, output + i, certificate_request);
3756#endif
3757
3758 /* Always encrypted. */
3759 sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ,
3760 i - RECORD_HEADER_SZ, handshake, 1, 0, 0);
3761 if (sendSz < 0)
3762 return sendSz;
3763
3764 #ifdef WOLFSSL_CALLBACKS
3765 if (ssl->hsInfoOn)
3766 AddPacketName("CertificateRequest", &ssl->handShakeInfo);
3767 if (ssl->toInfoOn) {
3768 AddPacketInfo("CertificateRequest", &ssl->timeoutInfo, output,
3769 sendSz, ssl->heap);
3770 }
3771 #endif
3772
3773 ssl->buffers.outputBuffer.length += sendSz;
3774 if (!ssl->options.groupMessages)
3775 ret = SendBuffered(ssl);
3776
3777 WOLFSSL_LEAVE("SendTls13CertificateRequest", ret);
3778
3779 return ret;
3780}
3781#endif /* NO_CERTS */
3782#endif /* NO_WOLFSSL_SERVER */
3783
3784#ifndef NO_CERTS
3785#if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519)
3786/* Encode the signature algorithm into buffer.
3787 *
3788 * hashalgo The hash algorithm.
3789 * hsType The signature type.
3790 * output The buffer to encode into.
3791 */
3792static INLINE void EncodeSigAlg(byte hashAlgo, byte hsType, byte* output)
3793{
3794 switch (hsType) {
3795#ifdef HAVE_ECC
3796 case ecc_dsa_sa_algo:
3797 output[0] = hashAlgo;
3798 output[1] = ecc_dsa_sa_algo;
3799 break;
3800#endif
3801#ifdef HAVE_ED25519
3802 /* ED25519: 0x0807 */
3803 case ed25519_sa_algo:
3804 output[0] = ED25519_SA_MAJOR;
3805 output[1] = ED25519_SA_MINOR;
3806 (void)hashAlgo;
3807 break;
3808#endif
3809#ifndef NO_RSA
3810 /* PSS signatures: 0x080[4-6] */
3811 case rsa_pss_sa_algo:
3812 output[0] = rsa_pss_sa_algo;
3813 output[1] = hashAlgo;
3814 break;
3815#endif
3816 /* ED448: 0x0808 */
3817 }
3818}
3819
3820/* Decode the signature algorithm.
3821 *
3822 * input The encoded signature algorithm.
3823 * hashalgo The hash algorithm.
3824 * hsType The signature type.
3825 */
3826static INLINE void DecodeSigAlg(byte* input, byte* hashAlgo, byte* hsType)
3827{
3828 switch (input[0]) {
3829 case NEW_SA_MAJOR:
3830 /* PSS signatures: 0x080[4-6] */
3831 if (input[1] <= sha512_mac) {
3832 *hsType = input[0];
3833 *hashAlgo = input[1];
3834 }
3835 #ifdef HAVE_ED25519
3836 /* ED25519: 0x0807 */
3837 if (input[1] == ED25519_SA_MINOR) {
3838 *hsType = ed25519_sa_algo;
3839 /* Hash performed as part of sign/verify operation. */
3840 *hashAlgo = sha512_mac;
3841 }
3842 #endif
3843 /* ED448: 0x0808 */
3844 break;
3845 default:
3846 *hashAlgo = input[0];
3847 *hsType = input[1];
3848 break;
3849 }
3850}
3851
3852/* Get the hash of the messages so far.
3853 *
3854 * ssl The SSL/TLS object.
3855 * hash The buffer to write the hash to.
3856 * returns the length of the hash.
3857 */
3858static INLINE int GetMsgHash(WOLFSSL* ssl, byte* hash)
3859{
3860 int ret = 0;
3861 switch (ssl->specs.mac_algorithm) {
3862 #ifndef NO_SHA256
3863 case sha256_mac:
3864 ret = wc_Sha256GetHash(&ssl->hsHashes->hashSha256, hash);
3865 if (ret == 0)
3866 ret = WC_SHA256_DIGEST_SIZE;
3867 break;
3868 #endif /* !NO_SHA256 */
3869 #ifdef WOLFSSL_SHA384
3870 case sha384_mac:
3871 ret = wc_Sha384GetHash(&ssl->hsHashes->hashSha384, hash);
3872 if (ret == 0)
3873 ret = WC_SHA384_DIGEST_SIZE;
3874 break;
3875 #endif /* WOLFSSL_SHA384 */
3876 #ifdef WOLFSSL_TLS13_SHA512
3877 case sha512_mac:
3878 ret = wc_Sha512GetHash(&ssl->hsHashes->hashSha512, hash);
3879 if (ret == 0)
3880 ret = WC_SHA512_DIGEST_SIZE;
3881 break;
3882 #endif /* WOLFSSL_TLS13_SHA512 */
3883 }
3884 return ret;
3885}
3886
3887/* The length of the certificate verification label - client and server. */
3888#define CERT_VFY_LABEL_SZ 34
3889/* The server certificate verification label. */
3890static const byte serverCertVfyLabel[CERT_VFY_LABEL_SZ] =
3891 "TLS 1.3, server CertificateVerify";
3892/* The client certificate verification label. */
3893static const byte clientCertVfyLabel[CERT_VFY_LABEL_SZ] =
3894 "TLS 1.3, client CertificateVerify";
3895
3896/* The number of prefix bytes for signature data. */
3897#define SIGNING_DATA_PREFIX_SZ 64
3898/* The prefix byte in the signature data. */
3899#define SIGNING_DATA_PREFIX_BYTE 0x20
3900/* Maximum length of the signature data. */
3901#define MAX_SIG_DATA_SZ (SIGNING_DATA_PREFIX_SZ + \
3902 CERT_VFY_LABEL_SZ + \
3903 MAX_DIGEST_SIZE)
3904
3905/* Create the signature data for TLS v1.3 certificate verification.
3906 *
3907 * ssl The SSL/TLS object.
3908 * sigData The signature data.
3909 * sigDataSz The length of the signature data.
3910 * check Indicates this is a check not create.
3911 */
3912static int CreateSigData(WOLFSSL* ssl, byte* sigData, word16* sigDataSz,
3913 int check)
3914{
3915 word16 idx;
3916 int side = ssl->options.side;
3917 int ret;
3918
3919 /* Signature Data = Prefix | Label | Handshake Hash */
3920 XMEMSET(sigData, SIGNING_DATA_PREFIX_BYTE, SIGNING_DATA_PREFIX_SZ);
3921 idx = SIGNING_DATA_PREFIX_SZ;
3922
3923 if ((side == WOLFSSL_SERVER_END && check) ||
3924 (side == WOLFSSL_CLIENT_END && !check)) {
3925 XMEMCPY(&sigData[idx], clientCertVfyLabel, CERT_VFY_LABEL_SZ);
3926 }
3927 if ((side == WOLFSSL_CLIENT_END && check) ||
3928 (side == WOLFSSL_SERVER_END && !check)) {
3929 XMEMCPY(&sigData[idx], serverCertVfyLabel, CERT_VFY_LABEL_SZ);
3930 }
3931 idx += CERT_VFY_LABEL_SZ;
3932
3933 ret = GetMsgHash(ssl, &sigData[idx]);
3934 if (ret < 0)
3935 return ret;
3936
3937 *sigDataSz = idx + ret;
3938 ret = 0;
3939
3940 return ret;
3941}
3942
3943#ifndef NO_RSA
3944/* Encode the PKCS #1.5 RSA signature.
3945 *
3946 * sig The buffer to place the encoded signature into.
3947 * sigData The data to be signed.
3948 * sigDataSz The size of the data to be signed.
3949 * hashAlgo The hash algorithm to use when signing.
3950 * returns the length of the encoded signature or negative on error.
3951 */
3952static int CreateRSAEncodedSig(byte* sig, byte* sigData, int sigDataSz,
3953 int sigAlgo, int hashAlgo)
3954{
3955 Digest digest;
3956 int hashSz = 0;
3957 int ret = BAD_FUNC_ARG;
3958 byte* hash;
3959
3960 (void)sigAlgo;
3961
3962 hash = sig;
3963
3964 /* Digest the signature data. */
3965 switch (hashAlgo) {
3966#ifndef NO_WOLFSSL_SHA256
3967 case sha256_mac:
3968 ret = wc_InitSha256(&digest.sha256);
3969 if (ret == 0) {
3970 ret = wc_Sha256Update(&digest.sha256, sigData, sigDataSz);
3971 if (ret == 0)
3972 ret = wc_Sha256Final(&digest.sha256, hash);
3973 wc_Sha256Free(&digest.sha256);
3974 }
3975 hashSz = WC_SHA256_DIGEST_SIZE;
3976 break;
3977#endif
3978#ifdef WOLFSSL_SHA384
3979 case sha384_mac:
3980 ret = wc_InitSha384(&digest.sha384);
3981 if (ret == 0) {
3982 ret = wc_Sha384Update(&digest.sha384, sigData, sigDataSz);
3983 if (ret == 0)
3984 ret = wc_Sha384Final(&digest.sha384, hash);
3985 wc_Sha384Free(&digest.sha384);
3986 }
3987 hashSz = WC_SHA384_DIGEST_SIZE;
3988 break;
3989#endif
3990#ifdef WOLFSSL_SHA512
3991 case sha512_mac:
3992 ret = wc_InitSha512(&digest.sha512);
3993 if (ret == 0) {
3994 ret = wc_Sha512Update(&digest.sha512, sigData, sigDataSz);
3995 if (ret == 0)
3996 ret = wc_Sha512Final(&digest.sha512, hash);
3997 wc_Sha512Free(&digest.sha512);
3998 }
3999 hashSz = WC_SHA512_DIGEST_SIZE;
4000 break;
4001#endif
4002 }
4003
4004 if (ret != 0)
4005 return ret;
4006
4007 return hashSz;
4008}
4009#endif /* !NO_RSA */
4010
4011#ifdef HAVE_ECC
4012/* Encode the ECC signature.
4013 *
4014 * sigData The data to be signed.
4015 * sigDataSz The size of the data to be signed.
4016 * hashAlgo The hash algorithm to use when signing.
4017 * returns the length of the encoded signature or negative on error.
4018 */
4019static int CreateECCEncodedSig(byte* sigData, int sigDataSz, int hashAlgo)
4020{
4021 Digest digest;
4022 int hashSz = 0;
4023 int ret = BAD_FUNC_ARG;
4024
4025 /* Digest the signature data. */
4026 switch (hashAlgo) {
4027#ifndef NO_WOLFSSL_SHA256
4028 case sha256_mac:
4029 ret = wc_InitSha256(&digest.sha256);
4030 if (ret == 0) {
4031 ret = wc_Sha256Update(&digest.sha256, sigData, sigDataSz);
4032 if (ret == 0)
4033 ret = wc_Sha256Final(&digest.sha256, sigData);
4034 wc_Sha256Free(&digest.sha256);
4035 }
4036 hashSz = WC_SHA256_DIGEST_SIZE;
4037 break;
4038#endif
4039#ifdef WOLFSSL_SHA384
4040 case sha384_mac:
4041 ret = wc_InitSha384(&digest.sha384);
4042 if (ret == 0) {
4043 ret = wc_Sha384Update(&digest.sha384, sigData, sigDataSz);
4044 if (ret == 0)
4045 ret = wc_Sha384Final(&digest.sha384, sigData);
4046 wc_Sha384Free(&digest.sha384);
4047 }
4048 hashSz = WC_SHA384_DIGEST_SIZE;
4049 break;
4050#endif
4051#ifdef WOLFSSL_SHA512
4052 case sha512_mac:
4053 ret = wc_InitSha512(&digest.sha512);
4054 if (ret == 0) {
4055 ret = wc_Sha512Update(&digest.sha512, sigData, sigDataSz);
4056 if (ret == 0)
4057 ret = wc_Sha512Final(&digest.sha512, sigData);
4058 wc_Sha512Free(&digest.sha512);
4059 }
4060 hashSz = WC_SHA512_DIGEST_SIZE;
4061 break;
4062#endif
4063 }
4064
4065 if (ret != 0)
4066 return ret;
4067
4068 return hashSz;
4069}
4070#endif /* HAVE_ECC */
4071
4072#ifndef NO_RSA
4073/* Check that the decrypted signature matches the encoded signature
4074 * based on the digest of the signature data.
4075 *
4076 * ssl The SSL/TLS object.
4077 * hashAlgo The signature algorithm used to generate signature.
4078 * hashAlgo The hash algorithm used to generate signature.
4079 * decSig The decrypted signature.
4080 * decSigSz The size of the decrypted signature.
4081 * returns 0 on success, otherwise failure.
4082 */
4083static int CheckRSASignature(WOLFSSL* ssl, int sigAlgo, int hashAlgo,
4084 byte* decSig, word32 decSigSz)
4085{
4086 int ret = 0;
4087 byte sigData[MAX_SIG_DATA_SZ];
4088 word16 sigDataSz;
4089 word32 sigSz;
4090
4091 ret = CreateSigData(ssl, sigData, &sigDataSz, 1);
4092 if (ret != 0)
4093 return ret;
4094
4095 if (sigAlgo == rsa_pss_sa_algo) {
4096 enum wc_HashType hashType = WC_HASH_TYPE_NONE;
4097
4098 ret = ConvertHashPss(hashAlgo, &hashType, NULL);
4099 if (ret < 0)
4100 return ret;
4101
4102 /* PSS signature can be done in-pace */
4103 ret = CreateRSAEncodedSig(sigData, sigData, sigDataSz,
4104 sigAlgo, hashAlgo);
4105 if (ret < 0)
4106 return ret;
4107 sigSz = ret;
4108
4109 ret = wc_RsaPSS_CheckPadding(sigData, sigSz, decSig, decSigSz,
4110 hashType);
4111 }
4112
4113 return ret;
4114}
4115#endif /* !NO_RSA */
4116#endif /* !NO_RSA || HAVE_ECC */
4117
4118/* Get the next certificate from the list for writing into the TLS v1.3
4119 * Certificate message.
4120 *
4121 * data The certificate list.
4122 * length The length of the certificate data in the list.
4123 * idx The index of the next certificate.
4124 * returns the length of the certificate data. 0 indicates no more certificates
4125 * in the list.
4126 */
4127static word32 NextCert(byte* data, word32 length, word32* idx)
4128{
4129 word32 len;
4130
4131 /* Is index at end of list. */
4132 if (*idx == length)
4133 return 0;
4134
4135 /* Length of the current ASN.1 encoded certificate. */
4136 c24to32(data + *idx, &len);
4137 /* Include the length field. */
4138 len += 3;
4139
4140 /* Move index to next certificate and return the current certificate's
4141 * length.
4142 */
4143 *idx += len;
4144 return len;
4145}
4146
4147/* Add certificate data and empty extension to output up to the fragment size.
4148 *
4149 * cert The certificate data to write out.
4150 * len The length of the certificate data.
4151 * idx The start of the certificate data to write out.
4152 * fragSz The maximum size of this fragment.
4153 * output The buffer to write to.
4154 * returns the number of bytes written.
4155 */
4156static word32 AddCertExt(byte* cert, word32 len, word32 idx, word32 fragSz,
4157 byte* output)
4158{
4159 word32 i = 0;
4160 word32 copySz = min(len - idx, fragSz);
4161
4162 if (idx < len) {
4163 XMEMCPY(output, cert + idx, copySz);
4164 i = copySz;
4165 }
4166
4167 if (copySz + OPAQUE16_LEN <= fragSz) {
4168 /* Empty extension */
4169 output[i++] = 0;
4170 output[i++] = 0;
4171 }
4172
4173 return i;
4174}
4175
4176/* Send the certificate for this end and any CAs that help with validation.
4177 * This message is always encrypted in TLS v1.3.
4178 *
4179 * ssl The SSL/TLS object.
4180 * returns 0 on success, otherwise failure.
4181 */
4182static int SendTls13Certificate(WOLFSSL* ssl)
4183{
4184 int ret = 0;
4185 word32 certSz, certChainSz, headerSz, listSz, payloadSz;
4186 word32 length, maxFragment;
4187 word32 len = 0;
4188 word32 idx = 0;
4189 word32 offset = OPAQUE16_LEN;
4190 byte* p = NULL;
4191 byte certReqCtxLen = 0;
4192 byte* certReqCtx = NULL;
4193
4194 WOLFSSL_ENTER("SendTls13Certificate");
4195
4196#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
4197 if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->certReqCtx != NULL) {
4198 certReqCtxLen = ssl->certReqCtx->len;
4199 certReqCtx = &ssl->certReqCtx->ctx;
4200 }
4201#endif
4202
4203 if (ssl->options.sendVerify == SEND_BLANK_CERT) {
4204 certSz = 0;
4205 certChainSz = 0;
4206 headerSz = OPAQUE8_LEN + certReqCtxLen + CERT_HEADER_SZ;
4207 length = headerSz;
4208 listSz = 0;
4209 }
4210 else {
4211 if (!ssl->buffers.certificate) {
4212 WOLFSSL_MSG("Send Cert missing certificate buffer");
4213 return BUFFER_ERROR;
4214 }
4215 /* Certificate Data */
4216 certSz = ssl->buffers.certificate->length;
4217 /* Cert Req Ctx Len | Cert Req Ctx | Cert List Len | Cert Data Len */
4218 headerSz = OPAQUE8_LEN + certReqCtxLen + CERT_HEADER_SZ +
4219 CERT_HEADER_SZ;
4220 /* Length of message data with one certificate and empty extensions. */
4221 length = headerSz + certSz + OPAQUE16_LEN;
4222 /* Length of list data with one certificate and empty extensions. */
4223 listSz = CERT_HEADER_SZ + certSz + OPAQUE16_LEN;
4224
4225 /* Send rest of chain if sending cert (chain has leading size/s). */
4226 if (certSz > 0 && ssl->buffers.certChainCnt > 0) {
4227 /* The pointer to the current spot in the cert chain buffer. */
4228 p = ssl->buffers.certChain->buffer;
4229 /* Chain length including extensions. */
4230 certChainSz = ssl->buffers.certChain->length +
4231 OPAQUE16_LEN * ssl->buffers.certChainCnt;
4232 length += certChainSz;
4233 listSz += certChainSz;
4234 }
4235 else
4236 certChainSz = 0;
4237 }
4238
4239 payloadSz = length;
4240
4241 if (ssl->fragOffset != 0)
4242 length -= (ssl->fragOffset + headerSz);
4243
4244 maxFragment = MAX_RECORD_SIZE;
4245
4246 #ifdef HAVE_MAX_FRAGMENT
4247 if (ssl->max_fragment != 0 && maxFragment >= ssl->max_fragment)
4248 maxFragment = ssl->max_fragment;
4249 #endif /* HAVE_MAX_FRAGMENT */
4250
4251 while (length > 0 && ret == 0) {
4252 byte* output = NULL;
4253 word32 fragSz = 0;
4254 word32 i = RECORD_HEADER_SZ;
4255 int sendSz = RECORD_HEADER_SZ;
4256
4257 if (ssl->fragOffset == 0) {
4258 if (headerSz + certSz + OPAQUE16_LEN + certChainSz <=
4259 maxFragment - HANDSHAKE_HEADER_SZ) {
4260
4261 fragSz = headerSz + certSz + OPAQUE16_LEN + certChainSz;
4262 }
4263 else {
4264 fragSz = maxFragment - HANDSHAKE_HEADER_SZ;
4265 }
4266 sendSz += fragSz + HANDSHAKE_HEADER_SZ;
4267 i += HANDSHAKE_HEADER_SZ;
4268 }
4269 else {
4270 fragSz = min(length, maxFragment);
4271 sendSz += fragSz;
4272 }
4273
4274 sendSz += MAX_MSG_EXTRA;
4275
4276 /* Check buffers are big enough and grow if needed. */
4277 if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
4278 return ret;
4279
4280 /* Get position in output buffer to write new message to. */
4281 output = ssl->buffers.outputBuffer.buffer +
4282 ssl->buffers.outputBuffer.length;
4283
4284 if (ssl->fragOffset == 0) {
4285 AddTls13FragHeaders(output, fragSz, 0, payloadSz, certificate, ssl);
4286
4287 /* Request context. */
4288 output[i++] = certReqCtxLen;
4289 if (certReqCtxLen > 0) {
4290 XMEMCPY(output + i, certReqCtx, certReqCtxLen);
4291 i += certReqCtxLen;
4292 }
4293 length -= OPAQUE8_LEN + certReqCtxLen;
4294 fragSz -= OPAQUE8_LEN + certReqCtxLen;
4295 /* Certificate list length. */
4296 c32to24(listSz, output + i);
4297 i += CERT_HEADER_SZ;
4298 length -= CERT_HEADER_SZ;
4299 fragSz -= CERT_HEADER_SZ;
4300 /* Leaf certificate data length. */
4301 if (certSz > 0) {
4302 c32to24(certSz, output + i);
4303 i += CERT_HEADER_SZ;
4304 length -= CERT_HEADER_SZ;
4305 fragSz -= CERT_HEADER_SZ;
4306 }
4307 }
4308 else
4309 AddTls13RecordHeader(output, fragSz, handshake, ssl);
4310
4311 if (certSz > 0 && ssl->fragOffset < certSz + OPAQUE16_LEN) {
4312 /* Put in the leaf certificate and empty extension. */
4313 word32 copySz = AddCertExt(ssl->buffers.certificate->buffer, certSz,
4314 ssl->fragOffset, fragSz, output + i);
4315
4316 i += copySz;
4317 ssl->fragOffset += copySz;
4318 length -= copySz;
4319 fragSz -= copySz;
4320 }
4321 if (certChainSz > 0 && fragSz > 0) {
4322 /* Put in the CA certificates with empty extensions. */
4323 while (fragSz > 0) {
4324 word32 l;
4325
4326 if (offset == len + OPAQUE16_LEN) {
4327 /* Find next CA certificate to write out. */
4328 offset = 0;
4329 len = NextCert(ssl->buffers.certChain->buffer,
4330 ssl->buffers.certChain->length, &idx);
4331 if (len == 0)
4332 break;
4333 }
4334
4335 /* Write out certificate and empty extension. */
4336 l = AddCertExt(p, len, offset, fragSz, output + i);
4337 i += l;
4338 ssl->fragOffset += l;
4339 length -= l;
4340 fragSz -= l;
4341 offset += l;
4342 }
4343 }
4344
4345 if ((int)i - RECORD_HEADER_SZ < 0) {
4346 WOLFSSL_MSG("Send Cert bad inputSz");
4347 return BUFFER_E;
4348 }
4349
4350 /* This message is always encrypted. */
4351 sendSz = BuildTls13Message(ssl, output, sendSz,
4352 output + RECORD_HEADER_SZ,
4353 i - RECORD_HEADER_SZ, handshake, 1, 0, 0);
4354 if (sendSz < 0)
4355 return sendSz;
4356
4357 #ifdef WOLFSSL_CALLBACKS
4358 if (ssl->hsInfoOn)
4359 AddPacketName("Certificate", &ssl->handShakeInfo);
4360 if (ssl->toInfoOn) {
4361 AddPacketInfo("Certificate", &ssl->timeoutInfo, output, sendSz,
4362 ssl->heap);
4363 }
4364 #endif
4365
4366 ssl->buffers.outputBuffer.length += sendSz;
4367 if (!ssl->options.groupMessages)
4368 ret = SendBuffered(ssl);
4369 }
4370
4371 if (ret != WANT_WRITE) {
4372 /* Clean up the fragment offset. */
4373 ssl->fragOffset = 0;
4374 if (ssl->options.side == WOLFSSL_SERVER_END)
4375 ssl->options.serverState = SERVER_CERT_COMPLETE;
4376 }
4377
4378#ifdef WOLFSSL_POST_HANDSHAKE_AUTH
4379 if (ssl->options.side == WOLFSSL_CLIENT_END && ssl->certReqCtx != NULL) {
4380 CertReqCtx* ctx = ssl->certReqCtx;
4381 ssl->certReqCtx = ssl->certReqCtx->next;
4382 XFREE(ctx, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
4383 }
4384#endif
4385
4386 WOLFSSL_LEAVE("SendTls13Certificate", ret);
4387
4388 return ret;
4389}
4390
4391typedef struct Scv13Args {
4392 byte* output; /* not allocated */
4393#ifndef NO_RSA
4394 byte* verifySig;
4395#endif
4396 byte* verify; /* not allocated */
4397 word32 idx;
4398 word32 sigLen;
4399 int sendSz;
4400 word16 length;
4401
4402 byte sigAlgo;
4403 byte* sigData;
4404 word16 sigDataSz;
4405} Scv13Args;
4406
4407static void FreeScv13Args(WOLFSSL* ssl, void* pArgs)
4408{
4409 Scv13Args* args = (Scv13Args*)pArgs;
4410
4411 (void)ssl;
4412
4413#ifndef NO_RSA
4414 if (args->verifySig) {
4415 XFREE(args->verifySig, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
4416 args->verifySig = NULL;
4417 }
4418#endif
4419 if (args->sigData) {
4420 XFREE(args->sigData, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
4421 args->sigData = NULL;
4422 }
4423}
4424
4425/* Send the TLS v1.3 CertificateVerify message.
4426 * A hash of all the message so far is used.
4427 * The signed data is:
4428 * 0x20 * 64 | context string | 0x00 | hash of messages
4429 * This message is always encrypted in TLS v1.3.
4430 *
4431 * ssl The SSL/TLS object.
4432 * returns 0 on success, otherwise failure.
4433 */
4434static int SendTls13CertificateVerify(WOLFSSL* ssl)
4435{
4436 int ret = 0;
4437 buffer* sig = &ssl->buffers.sig;
4438#ifdef WOLFSSL_ASYNC_CRYPT
4439 Scv13Args* args = (Scv13Args*)ssl->async.args;
4440 typedef char args_test[sizeof(ssl->async.args) >= sizeof(*args) ? 1 : -1];
4441 (void)sizeof(args_test);
4442#else
4443 Scv13Args args[1];
4444#endif
4445
4446 WOLFSSL_ENTER("SendTls13CertificateVerify");
4447
4448#ifdef WOLFSSL_ASYNC_CRYPT
4449 ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
4450 if (ret != WC_NOT_PENDING_E) {
4451 /* Check for error */
4452 if (ret < 0)
4453 goto exit_scv;
4454 }
4455 else
4456#endif
4457 {
4458 /* Reset state */
4459 ret = 0;
4460 ssl->options.asyncState = TLS_ASYNC_BEGIN;
4461 XMEMSET(args, 0, sizeof(Scv13Args));
4462 #ifdef WOLFSSL_ASYNC_CRYPT
4463 ssl->async.freeArgs = FreeScv13Args;
4464 #endif
4465 }
4466
4467 switch(ssl->options.asyncState)
4468 {
4469 case TLS_ASYNC_BEGIN:
4470 {
4471 if (ssl->options.sendVerify == SEND_BLANK_CERT) {
4472 return 0; /* sent blank cert, can't verify */
4473 }
4474
4475 args->sendSz = MAX_CERT_VERIFY_SZ;
4476 /* Always encrypted. */
4477 args->sendSz += MAX_MSG_EXTRA;
4478
4479 /* check for available size */
4480 if ((ret = CheckAvailableSize(ssl, args->sendSz)) != 0) {
4481 goto exit_scv;
4482 }
4483
4484 /* get output buffer */
4485 args->output = ssl->buffers.outputBuffer.buffer +
4486 ssl->buffers.outputBuffer.length;
4487
4488 /* Advance state and proceed */
4489 ssl->options.asyncState = TLS_ASYNC_BUILD;
4490 } /* case TLS_ASYNC_BEGIN */
4491 FALL_THROUGH;
4492
4493 case TLS_ASYNC_BUILD:
4494 {
4495 /* idx is used to track verify pointer offset to output */
4496 args->idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
4497 args->verify =
4498 &args->output[RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ];
4499
4500 ret = DecodePrivateKey(ssl, &args->length);
4501 if (ret != 0)
4502 goto exit_scv;
4503
4504 /* Add signature algorithm. */
4505 if (ssl->hsType == DYNAMIC_TYPE_RSA)
4506 args->sigAlgo = rsa_pss_sa_algo;
4507 else if (ssl->hsType == DYNAMIC_TYPE_ECC)
4508 args->sigAlgo = ecc_dsa_sa_algo;
4509 #ifdef HAVE_ED25519
4510 else if (ssl->hsType == DYNAMIC_TYPE_ED25519)
4511 args->sigAlgo = ed25519_sa_algo;
4512 #endif
4513 EncodeSigAlg(ssl->suites->hashAlgo, args->sigAlgo, args->verify);
4514
4515 /* Create the data to be signed. */
4516 args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
4517 DYNAMIC_TYPE_SIGNATURE);
4518 if (args->sigData == NULL) {
4519 ERROR_OUT(MEMORY_E, exit_scv);
4520 }
4521
4522 ret = CreateSigData(ssl, args->sigData, &args->sigDataSz, 0);
4523 if (ret != 0)
4524 goto exit_scv;
4525
4526 #ifndef NO_RSA
4527 if (ssl->hsType == DYNAMIC_TYPE_RSA) {
4528 /* build encoded signature buffer */
4529 sig->length = MAX_ENCODED_SIG_SZ;
4530 sig->buffer = (byte*)XMALLOC(sig->length, ssl->heap,
4531 DYNAMIC_TYPE_SIGNATURE);
4532 if (sig->buffer == NULL) {
4533 ERROR_OUT(MEMORY_E, exit_scv);
4534 }
4535
4536 ret = CreateRSAEncodedSig(sig->buffer, args->sigData,
4537 args->sigDataSz, args->sigAlgo, ssl->suites->hashAlgo);
4538 if (ret < 0)
4539 goto exit_scv;
4540 sig->length = ret;
4541 ret = 0;
4542
4543 /* Maximum size of RSA Signature. */
4544 args->sigLen = args->length;
4545 }
4546 #endif /* !NO_RSA */
4547 #ifdef HAVE_ECC
4548 if (ssl->hsType == DYNAMIC_TYPE_ECC) {
4549 sig->length = args->sendSz - args->idx - HASH_SIG_SIZE -
4550 VERIFY_HEADER;
4551 ret = CreateECCEncodedSig(args->sigData,
4552 args->sigDataSz, ssl->suites->hashAlgo);
4553 if (ret < 0)
4554 goto exit_scv;
4555 args->sigDataSz = ret;
4556 ret = 0;
4557 }
4558 #endif /* HAVE_ECC */
4559 #ifdef HAVE_ED25519
4560 if (ssl->hsType == DYNAMIC_TYPE_ED25519) {
4561 /* Nothing to do */
4562 sig->length = ED25519_SIG_SIZE;
4563 }
4564 #endif /* HAVE_ECC */
4565
4566 /* Advance state and proceed */
4567 ssl->options.asyncState = TLS_ASYNC_DO;
4568 } /* case TLS_ASYNC_BUILD */
4569 FALL_THROUGH;
4570
4571 case TLS_ASYNC_DO:
4572 {
4573 #ifdef HAVE_ECC
4574 if (ssl->hsType == DYNAMIC_TYPE_ECC) {
4575 ret = EccSign(ssl, args->sigData, args->sigDataSz,
4576 args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
4577 &sig->length, (ecc_key*)ssl->hsKey,
4578 #if defined(HAVE_PK_CALLBACKS)
4579 ssl->buffers.key->buffer, ssl->buffers.key->length,
4580 ssl->EccSignCtx
4581 #else
4582 NULL, 0, NULL
4583 #endif
4584 );
4585 args->length = sig->length;
4586 }
4587 #endif /* HAVE_ECC */
4588 #ifdef HAVE_ED25519
4589 if (ssl->hsType == DYNAMIC_TYPE_ED25519) {
4590 ret = Ed25519Sign(ssl, args->sigData, args->sigDataSz,
4591 args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
4592 &sig->length, (ed25519_key*)ssl->hsKey,
4593 #if defined(HAVE_PK_CALLBACKS)
4594 ssl->buffers.key->buffer, ssl->buffers.key->length,
4595 ssl->Ed25519SignCtx
4596 #else
4597 NULL, 0, NULL
4598 #endif
4599 );
4600 args->length = sig->length;
4601 }
4602 #endif
4603 #ifndef NO_RSA
4604 if (ssl->hsType == DYNAMIC_TYPE_RSA) {
4605
4606 ret = RsaSign(ssl, sig->buffer, sig->length,
4607 args->verify + HASH_SIG_SIZE + VERIFY_HEADER, &args->sigLen,
4608 args->sigAlgo, ssl->suites->hashAlgo,
4609 (RsaKey*)ssl->hsKey,
4610 ssl->buffers.key->buffer, ssl->buffers.key->length,
4611 #ifdef HAVE_PK_CALLBACKS
4612 ssl->RsaSignCtx
4613 #else
4614 NULL
4615 #endif
4616 );
4617 args->length = args->sigLen;
4618 }
4619 #endif /* !NO_RSA */
4620
4621 /* Check for error */
4622 if (ret != 0) {
4623 goto exit_scv;
4624 }
4625
4626 /* Add signature length. */
4627 c16toa(args->length, args->verify + HASH_SIG_SIZE);
4628
4629 /* Advance state and proceed */
4630 ssl->options.asyncState = TLS_ASYNC_VERIFY;
4631 } /* case TLS_ASYNC_DO */
4632 FALL_THROUGH;
4633
4634 case TLS_ASYNC_VERIFY:
4635 {
4636 #ifndef NO_RSA
4637 if (ssl->hsType == DYNAMIC_TYPE_RSA) {
4638 if (args->verifySig == NULL) {
4639 args->verifySig = (byte*)XMALLOC(args->sigLen, ssl->heap,
4640 DYNAMIC_TYPE_SIGNATURE);
4641 if (args->verifySig == NULL) {
4642 ERROR_OUT(MEMORY_E, exit_scv);
4643 }
4644 XMEMCPY(args->verifySig,
4645 args->verify + HASH_SIG_SIZE + VERIFY_HEADER,
4646 args->sigLen);
4647 }
4648
4649 /* check for signature faults */
4650 ret = VerifyRsaSign(ssl, args->verifySig, args->sigLen,
4651 sig->buffer, sig->length, args->sigAlgo,
4652 ssl->suites->hashAlgo, (RsaKey*)ssl->hsKey);
4653 }
4654 #endif /* !NO_RSA */
4655
4656 /* Check for error */
4657 if (ret != 0) {
4658 goto exit_scv;
4659 }
4660
4661 /* Advance state and proceed */
4662 ssl->options.asyncState = TLS_ASYNC_FINALIZE;
4663 } /* case TLS_ASYNC_VERIFY */
4664 FALL_THROUGH;
4665
4666 case TLS_ASYNC_FINALIZE:
4667 {
4668 /* Put the record and handshake headers on. */
4669 AddTls13Headers(args->output, args->length + HASH_SIG_SIZE +
4670 VERIFY_HEADER, certificate_verify, ssl);
4671
4672 args->sendSz = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ +
4673 args->length + HASH_SIG_SIZE + VERIFY_HEADER;
4674
4675 /* Advance state and proceed */
4676 ssl->options.asyncState = TLS_ASYNC_END;
4677 } /* case TLS_ASYNC_FINALIZE */
4678 FALL_THROUGH;
4679
4680 case TLS_ASYNC_END:
4681 {
4682 /* This message is always encrypted. */
4683 ret = BuildTls13Message(ssl, args->output,
4684 MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA,
4685 args->output + RECORD_HEADER_SZ,
4686 args->sendSz - RECORD_HEADER_SZ, handshake,
4687 1, 0, 0);
4688
4689 if (ret < 0) {
4690 goto exit_scv;
4691 }
4692 else {
4693 args->sendSz = ret;
4694 ret = 0;
4695 }
4696
4697 #ifdef WOLFSSL_CALLBACKS
4698 if (ssl->hsInfoOn)
4699 AddPacketName("CertificateVerify", &ssl->handShakeInfo);
4700 if (ssl->toInfoOn) {
4701 AddPacketInfo("CertificateVerify", &ssl->timeoutInfo,
4702 args->output, args->sendSz, ssl->heap);
4703 }
4704 #endif
4705
4706 ssl->buffers.outputBuffer.length += args->sendSz;
4707
4708 if (!ssl->options.groupMessages)
4709 ret = SendBuffered(ssl);
4710 break;
4711 }
4712 default:
4713 ret = INPUT_CASE_ERROR;
4714 } /* switch(ssl->options.asyncState) */
4715
4716exit_scv:
4717
4718 WOLFSSL_LEAVE("SendTls13CertificateVerify", ret);
4719
4720#ifdef WOLFSSL_ASYNC_CRYPT
4721 /* Handle async operation */
4722 if (ret == WC_PENDING_E) {
4723 return ret;
4724 }
4725#endif /* WOLFSSL_ASYNC_CRYPT */
4726
4727 /* Final cleanup */
4728 FreeScv13Args(ssl, args);
4729 FreeKeyExchange(ssl);
4730
4731 return ret;
4732}
4733
4734
4735/* Parse and handle a TLS v1.3 Certificate message.
4736 *
4737 * ssl The SSL/TLS object.
4738 * input The message buffer.
4739 * inOutIdx On entry, the index into the message buffer of Certificate.
4740 * On exit, the index of byte after the Certificate message.
4741 * totalSz The length of the current handshake message.
4742 * returns 0 on success and otherwise failure.
4743 */
4744static int DoTls13Certificate(WOLFSSL* ssl, byte* input, word32* inOutIdx,
4745 word32 totalSz)
4746{
4747 int ret;
4748
4749 WOLFSSL_ENTER("DoTls13Certificate");
4750
4751 ret = ProcessPeerCerts(ssl, input, inOutIdx, totalSz);
4752
4753#if !defined(NO_WOLFSSL_SERVER) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
4754 if (ret == 0 && ssl->options.side == WOLFSSL_SERVER_END &&
4755 ssl->options.handShakeState == HANDSHAKE_DONE) {
4756 /* reset handshake states */
4757 ssl->options.serverState = SERVER_FINISHED_COMPLETE;
4758 ssl->options.acceptState = TICKET_SENT;
4759 ssl->options.handShakeState = SERVER_FINISHED_COMPLETE;
4760 }
4761#endif
4762
4763 WOLFSSL_LEAVE("DoTls13Certificate", ret);
4764
4765 return ret;
4766}
4767
4768#if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519)
4769
4770typedef struct Dcv13Args {
4771 byte* output; /* not allocated */
4772 word32 sendSz;
4773 word16 sz;
4774 word32 sigSz;
4775 word32 idx;
4776 word32 begin;
4777 byte hashAlgo;
4778 byte sigAlgo;
4779
4780 byte* sigData;
4781 word16 sigDataSz;
4782} Dcv13Args;
4783
4784static void FreeDcv13Args(WOLFSSL* ssl, void* pArgs)
4785{
4786 Dcv13Args* args = (Dcv13Args*)pArgs;
4787
4788 if (args->sigData != NULL) {
4789 XFREE(args->sigData, ssl->heap, DYNAMIC_TYPE_SIGNATURE);
4790 args->sigData = NULL;
4791 }
4792
4793 (void)ssl;
4794}
4795
4796/* Parse and handle a TLS v1.3 CertificateVerify message.
4797 *
4798 * ssl The SSL/TLS object.
4799 * input The message buffer.
4800 * inOutIdx On entry, the index into the message buffer of
4801 * CertificateVerify.
4802 * On exit, the index of byte after the CertificateVerify message.
4803 * totalSz The length of the current handshake message.
4804 * returns 0 on success and otherwise failure.
4805 */
4806static int DoTls13CertificateVerify(WOLFSSL* ssl, byte* input,
4807 word32* inOutIdx, word32 totalSz)
4808{
4809 int ret = 0;
4810 buffer* sig = &ssl->buffers.sig;
4811#ifdef WOLFSSL_ASYNC_CRYPT
4812 Dcv13Args* args = (Dcv13Args*)ssl->async.args;
4813 typedef char args_test[sizeof(ssl->async.args) >= sizeof(*args) ? 1 : -1];
4814 (void)sizeof(args_test);
4815#else
4816 Dcv13Args args[1];
4817#endif
4818
4819 WOLFSSL_ENTER("DoTls13CertificateVerify");
4820
4821#ifdef WOLFSSL_ASYNC_CRYPT
4822 ret = wolfSSL_AsyncPop(ssl, &ssl->options.asyncState);
4823 if (ret != WC_NOT_PENDING_E) {
4824 /* Check for error */
4825 if (ret < 0)
4826 goto exit_dcv;
4827 }
4828 else
4829#endif
4830 {
4831 /* Reset state */
4832 ret = 0;
4833 ssl->options.asyncState = TLS_ASYNC_BEGIN;
4834 XMEMSET(args, 0, sizeof(Dcv13Args));
4835 args->hashAlgo = sha_mac;
4836 args->sigAlgo = anonymous_sa_algo;
4837 args->idx = *inOutIdx;
4838 args->begin = *inOutIdx;
4839 #ifdef WOLFSSL_ASYNC_CRYPT
4840 ssl->async.freeArgs = FreeDcv13Args;
4841 #endif
4842 }
4843
4844 switch(ssl->options.asyncState)
4845 {
4846 case TLS_ASYNC_BEGIN:
4847 {
4848 #ifdef WOLFSSL_CALLBACKS
4849 if (ssl->hsInfoOn) AddPacketName("CertificateVerify",
4850 &ssl->handShakeInfo);
4851 if (ssl->toInfoOn) AddLateName("CertificateVerify",
4852 &ssl->timeoutInfo);
4853 #endif
4854
4855 /* Advance state and proceed */
4856 ssl->options.asyncState = TLS_ASYNC_BUILD;
4857 } /* case TLS_ASYNC_BEGIN */
4858 FALL_THROUGH;
4859
4860 case TLS_ASYNC_BUILD:
4861 {
4862 /* Signature algorithm. */
4863 if ((args->idx - args->begin) + ENUM_LEN + ENUM_LEN > totalSz) {
4864 ERROR_OUT(BUFFER_ERROR, exit_dcv);
4865 }
4866 DecodeSigAlg(input + args->idx, &args->hashAlgo, &args->sigAlgo);
4867 args->idx += OPAQUE16_LEN;
4868
4869 /* Signature length. */
4870 if ((args->idx - args->begin) + OPAQUE16_LEN > totalSz) {
4871 ERROR_OUT(BUFFER_ERROR, exit_dcv);
4872 }
4873 ato16(input + args->idx, &args->sz);
4874 args->idx += OPAQUE16_LEN;
4875
4876 /* Signature data. */
4877 if ((args->idx - args->begin) + args->sz > totalSz ||
4878 args->sz > ENCRYPT_LEN) {
4879 ERROR_OUT(BUFFER_ERROR, exit_dcv);
4880 }
4881
4882 /* Check for public key of required type. */
4883 #ifdef HAVE_ED25519
4884 if (args->sigAlgo == ed25519_sa_algo &&
4885 !ssl->peerEd25519KeyPresent) {
4886 WOLFSSL_MSG("Oops, peer sent ED25519 key but not in verify");
4887 }
4888 #endif
4889 #ifdef HAVE_ECC
4890 if (args->sigAlgo == ecc_dsa_sa_algo &&
4891 !ssl->peerEccDsaKeyPresent) {
4892 WOLFSSL_MSG("Oops, peer sent ECC key but not in verify");
4893 }
4894 #endif
4895 #ifndef NO_RSA
4896 if ((args->sigAlgo == rsa_sa_algo ||
4897 args->sigAlgo == rsa_pss_sa_algo) &&
4898 (ssl->peerRsaKey == NULL || !ssl->peerRsaKeyPresent)) {
4899 WOLFSSL_MSG("Oops, peer sent RSA key but not in verify");
4900 }
4901 #endif
4902
4903 sig->buffer = (byte*)XMALLOC(args->sz, ssl->heap,
4904 DYNAMIC_TYPE_SIGNATURE);
4905 if (sig->buffer == NULL) {
4906 ERROR_OUT(MEMORY_E, exit_dcv);
4907 }
4908 sig->length = args->sz;
4909 XMEMCPY(sig->buffer, input + args->idx, args->sz);
4910
4911 #ifdef HAVE_ECC
4912 if (ssl->peerEccDsaKeyPresent) {
4913 WOLFSSL_MSG("Doing ECC peer cert verify");
4914
4915 args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
4916 DYNAMIC_TYPE_SIGNATURE);
4917 if (args->sigData == NULL) {
4918 ERROR_OUT(MEMORY_E, exit_dcv);
4919 }
4920
4921 ret = CreateSigData(ssl, args->sigData, &args->sigDataSz, 1);
4922 if (ret != 0)
4923 goto exit_dcv;
4924 ret = CreateECCEncodedSig(args->sigData,
4925 args->sigDataSz, args->hashAlgo);
4926 if (ret < 0)
4927 goto exit_dcv;
4928 args->sigDataSz = ret;
4929 ret = 0;
4930 }
4931 #endif
4932 #ifdef HAVE_ED25519
4933 if (ssl->peerEd25519KeyPresent) {
4934 WOLFSSL_MSG("Doing ED25519 peer cert verify");
4935
4936 args->sigData = (byte*)XMALLOC(MAX_SIG_DATA_SZ, ssl->heap,
4937 DYNAMIC_TYPE_SIGNATURE);
4938 if (args->sigData == NULL) {
4939 ERROR_OUT(MEMORY_E, exit_dcv);
4940 }
4941
4942 CreateSigData(ssl, args->sigData, &args->sigDataSz, 1);
4943 ret = 0;
4944 }
4945 #endif
4946
4947 /* Advance state and proceed */
4948 ssl->options.asyncState = TLS_ASYNC_DO;
4949 } /* case TLS_ASYNC_BUILD */
4950 FALL_THROUGH;
4951
4952 case TLS_ASYNC_DO:
4953 {
4954 #ifndef NO_RSA
4955 if (args->sigAlgo == rsa_sa_algo ||
4956 args->sigAlgo == rsa_pss_sa_algo) {
4957 WOLFSSL_MSG("Doing RSA peer cert verify");
4958
4959 ret = RsaVerify(ssl, sig->buffer, sig->length, &args->output,
4960 args->sigAlgo, args->hashAlgo, ssl->peerRsaKey,
4961 #ifdef HAVE_PK_CALLBACKS
4962 ssl->buffers.peerRsaKey.buffer,
4963 ssl->buffers.peerRsaKey.length,
4964 ssl->RsaVerifyCtx
4965 #else
4966 NULL, 0, NULL
4967 #endif
4968 );
4969 if (ret >= 0) {
4970 args->sendSz = ret;
4971 ret = 0;
4972 }
4973 }
4974 #endif /* !NO_RSA */
4975 #ifdef HAVE_ECC
4976 if (ssl->peerEccDsaKeyPresent) {
4977 WOLFSSL_MSG("Doing ECC peer cert verify");
4978
4979 ret = EccVerify(ssl, input + args->idx, args->sz,
4980 args->sigData, args->sigDataSz,
4981 ssl->peerEccDsaKey,
4982 #ifdef HAVE_PK_CALLBACKS
4983 ssl->buffers.peerEccDsaKey.buffer,
4984 ssl->buffers.peerEccDsaKey.length,
4985 ssl->EccVerifyCtx
4986 #else
4987 NULL, 0, NULL
4988 #endif
4989 );
4990 }
4991 #endif /* HAVE_ECC */
4992 #ifdef HAVE_ED25519
4993 if (ssl->peerEd25519KeyPresent) {
4994 WOLFSSL_MSG("Doing ED25519 peer cert verify");
4995
4996 ret = Ed25519Verify(ssl, input + args->idx, args->sz,
4997 args->sigData, args->sigDataSz,
4998 ssl->peerEd25519Key,
4999 #ifdef HAVE_PK_CALLBACKS
5000 ssl->buffers.peerEd25519Key.buffer,
5001 ssl->buffers.peerEd25519Key.length,
5002 ssl->Ed25519VerifyCtx
5003 #else
5004 NULL, 0, NULL
5005 #endif
5006 );
5007 }
5008 #endif
5009
5010 /* Check for error */
5011 if (ret != 0) {
5012 goto exit_dcv;
5013 }
5014
5015 /* Advance state and proceed */
5016 ssl->options.asyncState = TLS_ASYNC_VERIFY;
5017 } /* case TLS_ASYNC_DO */
5018 FALL_THROUGH;
5019
5020 case TLS_ASYNC_VERIFY:
5021 {
5022 #ifndef NO_RSA
5023 if (ssl->peerRsaKey != NULL && ssl->peerRsaKeyPresent != 0) {
5024 ret = CheckRSASignature(ssl, args->sigAlgo, args->hashAlgo,
5025 args->output, args->sendSz);
5026 if (ret != 0)
5027 goto exit_dcv;
5028 }
5029 #endif /* !NO_RSA */
5030
5031 /* Advance state and proceed */
5032 ssl->options.asyncState = TLS_ASYNC_FINALIZE;
5033 } /* case TLS_ASYNC_VERIFY */
5034 FALL_THROUGH;
5035
5036 case TLS_ASYNC_FINALIZE:
5037 {
5038 ssl->options.havePeerVerify = 1;
5039
5040 /* Set final index */
5041 args->idx += args->sz;
5042 *inOutIdx = args->idx;
5043
5044 /* Encryption is always on: add padding */
5045 *inOutIdx += ssl->keys.padSz;
5046
5047 /* Advance state and proceed */
5048 ssl->options.asyncState = TLS_ASYNC_END;
5049 } /* case TLS_ASYNC_FINALIZE */
5050
5051 case TLS_ASYNC_END:
5052 {
5053 break;
5054 }
5055 default:
5056 ret = INPUT_CASE_ERROR;
5057 } /* switch(ssl->options.asyncState) */
5058
5059exit_dcv:
5060
5061 WOLFSSL_LEAVE("DoTls13CertificateVerify", ret);
5062
5063#ifdef WOLFSSL_ASYNC_CRYPT
5064 /* Handle async operation */
5065 if (ret == WC_PENDING_E) {
5066 /* Mark message as not recevied so it can process again */
5067 ssl->msgsReceived.got_certificate_verify = 0;
5068
5069 return ret;
5070 }
5071#endif /* WOLFSSL_ASYNC_CRYPT */
5072
5073 /* Final cleanup */
5074 FreeDcv13Args(ssl, args);
5075 FreeKeyExchange(ssl);
5076
5077 return ret;
5078}
5079#endif /* !NO_RSA || HAVE_ECC */
5080
5081/* Parse and handle a TLS v1.3 Finished message.
5082 *
5083 * ssl The SSL/TLS object.
5084 * input The message buffer.
5085 * inOutIdx On entry, the index into the message buffer of Finished.
5086 * On exit, the index of byte after the Finished message and padding.
5087 * size Length of message data.
5088 * totalSz Length of remaining data in the message buffer.
5089 * sniff Indicates whether we are sniffing packets.
5090 * returns 0 on success and otherwise failure.
5091 */
5092static int DoTls13Finished(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
5093 word32 size, word32 totalSz, int sniff)
5094{
5095 int ret;
5096 word32 finishedSz = 0;
5097 byte* secret;
5098 byte mac[MAX_DIGEST_SIZE];
5099
5100 WOLFSSL_ENTER("DoTls13Finished");
5101
5102 /* check against totalSz */
5103 if (*inOutIdx + size + ssl->keys.padSz > totalSz)
5104 return BUFFER_E;
5105
5106 if (ssl->options.side == WOLFSSL_CLIENT_END) {
5107 /* All the handshake messages have been received to calculate
5108 * client and server finished keys.
5109 */
5110 ret = DeriveFinishedSecret(ssl, ssl->arrays->clientSecret,
5111 ssl->keys.client_write_MAC_secret);
5112 if (ret != 0)
5113 return ret;
5114
5115 ret = DeriveFinishedSecret(ssl, ssl->arrays->serverSecret,
5116 ssl->keys.server_write_MAC_secret);
5117 if (ret != 0)
5118 return ret;
5119
5120 secret = ssl->keys.server_write_MAC_secret;
5121 }
5122 else
5123 secret = ssl->keys.client_write_MAC_secret;
5124
5125 ret = BuildTls13HandshakeHmac(ssl, secret, mac, &finishedSz);
5126 if (ret != 0)
5127 return ret;
5128 if (size != finishedSz)
5129 return BUFFER_ERROR;
5130
5131 #ifdef WOLFSSL_CALLBACKS
5132 if (ssl->hsInfoOn) AddPacketName("Finished", &ssl->handShakeInfo);
5133 if (ssl->toInfoOn) AddLateName("Finished", &ssl->timeoutInfo);
5134 #endif
5135
5136 if (sniff == NO_SNIFF) {
5137 /* Actually check verify data. */
5138 if (XMEMCMP(input + *inOutIdx, mac, size) != 0){
5139 WOLFSSL_MSG("Verify finished error on hashes");
5140 return VERIFY_FINISHED_ERROR;
5141 }
5142 }
5143
5144 /* Force input exhaustion at ProcessReply by consuming padSz. */
5145 *inOutIdx += size + ssl->keys.padSz;
5146
5147 if (ssl->options.side == WOLFSSL_SERVER_END &&
5148 !ssl->options.handShakeDone) {
5149#ifdef WOLFSSL_EARLY_DATA
5150 if (ssl->earlyData) {
5151 if ((ret = DeriveTls13Keys(ssl, no_key, DECRYPT_SIDE_ONLY, 1)) != 0)
5152 return ret;
5153 }
5154#endif
5155 /* Setup keys for application data messages from client. */
5156 if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
5157 return ret;
5158 }
5159
5160#ifndef NO_WOLFSSL_CLIENT
5161 if (ssl->options.side == WOLFSSL_CLIENT_END)
5162 ssl->options.serverState = SERVER_FINISHED_COMPLETE;
5163#endif
5164#ifndef NO_WOLFSSL_SERVER
5165 if (ssl->options.side == WOLFSSL_SERVER_END) {
5166 ssl->options.clientState = CLIENT_FINISHED_COMPLETE;
5167 ssl->options.handShakeState = HANDSHAKE_DONE;
5168 ssl->options.handShakeDone = 1;
5169 }
5170#endif
5171
5172 WOLFSSL_LEAVE("DoTls13Finished", 0);
5173
5174 return 0;
5175}
5176#endif /* NO_CERTS */
5177
5178/* Send the TLS v1.3 Finished message.
5179 *
5180 * ssl The SSL/TLS object.
5181 * returns 0 on success, otherwise failure.
5182 */
5183static int SendTls13Finished(WOLFSSL* ssl)
5184{
5185 int sendSz;
5186 int finishedSz = ssl->specs.hash_size;
5187 byte* input;
5188 byte* output;
5189 int ret;
5190 int headerSz = HANDSHAKE_HEADER_SZ;
5191 int outputSz;
5192 byte* secret;
5193
5194 WOLFSSL_ENTER("SendTls13Finished");
5195
5196 outputSz = MAX_DIGEST_SIZE + DTLS_HANDSHAKE_HEADER_SZ + MAX_MSG_EXTRA;
5197 /* Check buffers are big enough and grow if needed. */
5198 if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
5199 return ret;
5200
5201 /* get output buffer */
5202 output = ssl->buffers.outputBuffer.buffer +
5203 ssl->buffers.outputBuffer.length;
5204 input = output + RECORD_HEADER_SZ;
5205
5206 AddTls13HandShakeHeader(input, finishedSz, 0, finishedSz, finished, ssl);
5207
5208 /* make finished hashes */
5209 if (ssl->options.side == WOLFSSL_CLIENT_END)
5210 secret = ssl->keys.client_write_MAC_secret;
5211 else {
5212 /* All the handshake messages have been done to calculate client and
5213 * server finished keys.
5214 */
5215 ret = DeriveFinishedSecret(ssl, ssl->arrays->clientSecret,
5216 ssl->keys.client_write_MAC_secret);
5217 if (ret != 0)
5218 return ret;
5219
5220 ret = DeriveFinishedSecret(ssl, ssl->arrays->serverSecret,
5221 ssl->keys.server_write_MAC_secret);
5222 if (ret != 0)
5223 return ret;
5224
5225 secret = ssl->keys.server_write_MAC_secret;
5226 }
5227 ret = BuildTls13HandshakeHmac(ssl, secret, &input[headerSz], NULL);
5228 if (ret != 0)
5229 return ret;
5230
5231 /* This message is always encrypted. */
5232 sendSz = BuildTls13Message(ssl, output, outputSz, input,
5233 headerSz + finishedSz, handshake, 1, 0, 0);
5234 if (sendSz < 0)
5235 return BUILD_MSG_ERROR;
5236
5237 if (!ssl->options.resuming) {
5238#ifndef NO_SESSION_CACHE
5239 AddSession(ssl); /* just try */
5240#endif
5241 }
5242
5243 #ifdef WOLFSSL_CALLBACKS
5244 if (ssl->hsInfoOn) AddPacketName("Finished", &ssl->handShakeInfo);
5245 if (ssl->toInfoOn) {
5246 AddPacketInfo("Finished", &ssl->timeoutInfo, output, sendSz,
5247 ssl->heap);
5248 }
5249 #endif
5250
5251 ssl->buffers.outputBuffer.length += sendSz;
5252
5253 if ((ret = SendBuffered(ssl)) != 0)
5254 return ret;
5255
5256 if (ssl->options.side == WOLFSSL_SERVER_END) {
5257 /* Can send application data now. */
5258 if ((ret = DeriveMasterSecret(ssl)) != 0)
5259 return ret;
5260#ifdef WOLFSSL_EARLY_DATA
5261 if ((ret = DeriveTls13Keys(ssl, traffic_key, ENCRYPT_SIDE_ONLY, 1))
5262 != 0) {
5263 return ret;
5264 }
5265 if ((ret = DeriveTls13Keys(ssl, traffic_key, DECRYPT_SIDE_ONLY,
5266 !ssl->earlyData)) != 0) {
5267 return ret;
5268 }
5269#else
5270 if ((ret = DeriveTls13Keys(ssl, traffic_key, ENCRYPT_AND_DECRYPT_SIDE,
5271 1)) != 0) {
5272 return ret;
5273 }
5274#endif
5275 if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
5276 return ret;
5277 }
5278
5279 if (ssl->options.side == WOLFSSL_CLIENT_END &&
5280 !ssl->options.handShakeDone) {
5281#ifdef WOLFSSL_EARLY_DATA
5282 if (ssl->earlyData) {
5283 if ((ret = DeriveTls13Keys(ssl, no_key, ENCRYPT_AND_DECRYPT_SIDE,
5284 1)) != 0) {
5285 return ret;
5286 }
5287 }
5288#endif
5289 /* Setup keys for application data messages. */
5290 if ((ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE)) != 0)
5291 return ret;
5292
5293#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
5294 ret = DeriveResumptionSecret(ssl, ssl->session.masterSecret);
5295#endif
5296 }
5297
5298 if (ssl->options.resuming) {
5299 if (ssl->options.side == WOLFSSL_CLIENT_END) {
5300 ssl->options.handShakeState = HANDSHAKE_DONE;
5301 ssl->options.handShakeDone = 1;
5302 }
5303 }
5304#ifndef NO_WOLFSSL_CLIENT
5305 if (ssl->options.side == WOLFSSL_CLIENT_END) {
5306 if (!ssl->options.resuming) {
5307 ssl->options.handShakeState = HANDSHAKE_DONE;
5308 ssl->options.handShakeDone = 1;
5309 }
5310 }
5311#endif
5312
5313 WOLFSSL_LEAVE("SendTls13Finished", ret);
5314
5315 return ret;
5316}
5317
5318/* Send the TLS v1.3 KeyUpdate message.
5319 *
5320 * ssl The SSL/TLS object.
5321 * returns 0 on success, otherwise failure.
5322 */
5323static int SendTls13KeyUpdate(WOLFSSL* ssl)
5324{
5325 int sendSz;
5326 byte* input;
5327 byte* output;
5328 int ret;
5329 int headerSz = HANDSHAKE_HEADER_SZ;
5330 int outputSz;
5331 word32 i = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
5332
5333 WOLFSSL_ENTER("SendTls13KeyUpdate");
5334
5335 outputSz = OPAQUE8_LEN + MAX_MSG_EXTRA;
5336 /* Check buffers are big enough and grow if needed. */
5337 if ((ret = CheckAvailableSize(ssl, outputSz)) != 0)
5338 return ret;
5339
5340 /* get output buffer */
5341 output = ssl->buffers.outputBuffer.buffer +
5342 ssl->buffers.outputBuffer.length;
5343 input = output + RECORD_HEADER_SZ;
5344
5345 AddTls13Headers(output, OPAQUE8_LEN, key_update, ssl);
5346
5347 /* If:
5348 * 1. I haven't sent a KeyUpdate requesting a response and
5349 * 2. This isn't responding to peer KeyUpdate requiring a response then,
5350 * I want a response.
5351 */
5352 ssl->keys.updateResponseReq = output[i++] =
5353 !ssl->keys.updateResponseReq && !ssl->keys.keyUpdateRespond;
5354 /* Sent response, no longer need to respond. */
5355 ssl->keys.keyUpdateRespond = 0;
5356
5357 /* This message is always encrypted. */
5358 sendSz = BuildTls13Message(ssl, output, outputSz, input,
5359 headerSz + OPAQUE8_LEN, handshake, 0, 0, 0);
5360 if (sendSz < 0)
5361 return BUILD_MSG_ERROR;
5362
5363 #ifdef WOLFSSL_CALLBACKS
5364 if (ssl->hsInfoOn) AddPacketName("KeyUpdate", &ssl->handShakeInfo);
5365 if (ssl->toInfoOn) {
5366 AddPacketInfo("KeyUpdate", &ssl->timeoutInfo, output, sendSz,
5367 ssl->heap);
5368 }
5369 #endif
5370
5371 ssl->buffers.outputBuffer.length += sendSz;
5372
5373 ret = SendBuffered(ssl);
5374 if (ret != 0 && ret != WANT_WRITE)
5375 return ret;
5376
5377 /* Future traffic uses new encryption keys. */
5378 if ((ret = DeriveTls13Keys(ssl, update_traffic_key, ENCRYPT_SIDE_ONLY, 1))
5379 != 0)
5380 return ret;
5381 if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
5382 return ret;
5383
5384 WOLFSSL_LEAVE("SendTls13KeyUpdate", ret);
5385
5386 return ret;
5387}
5388
5389/* Parse and handle a TLS v1.3 KeyUpdate message.
5390 *
5391 * ssl The SSL/TLS object.
5392 * input The message buffer.
5393 * inOutIdx On entry, the index into the message buffer of Finished.
5394 * On exit, the index of byte after the Finished message and padding.
5395 * totalSz The length of the current handshake message.
5396 * returns 0 on success and otherwise failure.
5397 */
5398static int DoTls13KeyUpdate(WOLFSSL* ssl, const byte* input, word32* inOutIdx,
5399 word32 totalSz)
5400{
5401 int ret;
5402 word32 i = *inOutIdx;
5403
5404 WOLFSSL_ENTER("DoTls13KeyUpdate");
5405
5406 /* check against totalSz */
5407 if (OPAQUE8_LEN != totalSz)
5408 return BUFFER_E;
5409
5410 switch (input[i]) {
5411 case update_not_requested:
5412 /* This message in response to any oustanding request. */
5413 ssl->keys.keyUpdateRespond = 0;
5414 ssl->keys.updateResponseReq = 0;
5415 break;
5416 case update_requested:
5417 /* New key update requiring a response. */
5418 ssl->keys.keyUpdateRespond = 1;
5419 break;
5420 default:
5421 return INVALID_PARAMETER;
5422 break;
5423 }
5424
5425 /* Move index to byte after message. */
5426 *inOutIdx += totalSz;
5427 /* Always encrypted. */
5428 *inOutIdx += ssl->keys.padSz;
5429
5430 /* Future traffic uses new decryption keys. */
5431 if ((ret = DeriveTls13Keys(ssl, update_traffic_key, DECRYPT_SIDE_ONLY, 1))
5432 != 0) {
5433 return ret;
5434 }
5435 if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
5436 return ret;
5437
5438 if (ssl->keys.keyUpdateRespond)
5439 return SendTls13KeyUpdate(ssl);
5440
5441 WOLFSSL_LEAVE("DoTls13KeyUpdate", ret);
5442
5443 return 0;
5444}
5445
5446#ifdef WOLFSSL_EARLY_DATA
5447#ifndef NO_WOLFSSL_CLIENT
5448/* Send the TLS v1.3 EndOfEarlyData message to indicate that there will be no
5449 * more early application data.
5450 * The encryption key now changes to the pre-calculated handshake key.
5451 *
5452 * ssl The SSL/TLS object.
5453 * returns 0 on success and otherwise failure.
5454 */
5455static int SendTls13EndOfEarlyData(WOLFSSL* ssl)
5456{
5457 byte* output;
5458 int ret;
5459 int sendSz;
5460 word32 length;
5461 word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
5462
5463 WOLFSSL_ENTER("SendTls13EndOfEarlyData");
5464
5465 length = 0;
5466 sendSz = idx + length + MAX_MSG_EXTRA;
5467
5468 /* Check buffers are big enough and grow if needed. */
5469 if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
5470 return ret;
5471
5472 /* Get position in output buffer to write new message to. */
5473 output = ssl->buffers.outputBuffer.buffer +
5474 ssl->buffers.outputBuffer.length;
5475
5476 /* Put the record and handshake headers on. */
5477 AddTls13Headers(output, length, end_of_early_data, ssl);
5478
5479 /* This message is always encrypted. */
5480 sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ,
5481 idx - RECORD_HEADER_SZ, handshake, 1, 0, 0);
5482 if (sendSz < 0)
5483 return sendSz;
5484
5485 ssl->buffers.outputBuffer.length += sendSz;
5486
5487 if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
5488 return ret;
5489
5490 if (!ssl->options.groupMessages)
5491 ret = SendBuffered(ssl);
5492
5493 WOLFSSL_LEAVE("SendTls13EndOfEarlyData", ret);
5494
5495 return ret;
5496}
5497#endif /* !NO_WOLFSSL_CLIENT */
5498
5499#ifndef NO_WOLFSSL_SERVER
5500/* Parse the TLS v1.3 EndOfEarlyData message that indicates that there will be
5501 * no more early application data.
5502 * The decryption key now changes to the pre-calculated handshake key.
5503 *
5504 * ssl The SSL/TLS object.
5505 * returns 0 on success and otherwise failure.
5506 */
5507static int DoTls13EndOfEarlyData(WOLFSSL* ssl, const byte* input,
5508 word32* inOutIdx, word32 size)
5509{
5510 int ret;
5511 word32 begin = *inOutIdx;
5512
5513 (void)input;
5514
5515 WOLFSSL_ENTER("DoTls13EndOfEarlyData");
5516
5517 if ((*inOutIdx - begin) != size)
5518 return BUFFER_ERROR;
5519
5520 /* Always encrypted. */
5521 *inOutIdx += ssl->keys.padSz;
5522
5523 ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY);
5524
5525 WOLFSSL_LEAVE("SendTls13EndOfEarlyData", ret);
5526
5527 return ret;
5528}
5529#endif /* !NO_WOLFSSL_SERVER */
5530#endif /* WOLFSSL_EARLY_DATA */
5531
5532#ifndef NO_WOLFSSL_CLIENT
5533/* Handle a New Session Ticket handshake message.
5534 * Message contains the information required to perform resumption.
5535 *
5536 * ssl The SSL/TLS object.
5537 * input The message buffer.
5538 * inOutIdx On entry, the index into the message buffer of Finished.
5539 * On exit, the index of byte after the Finished message and padding.
5540 * size The length of the current handshake message.
5541 * retuns 0 on success, otherwise failure.
5542 */
5543static int DoTls13NewSessionTicket(WOLFSSL* ssl, const byte* input,
5544 word32* inOutIdx, word32 size)
5545{
5546#ifdef HAVE_SESSION_TICKET
5547 int ret;
5548 word32 begin = *inOutIdx;
5549 word32 lifetime;
5550 word32 ageAdd;
5551 word16 length;
5552 word32 now;
5553
5554 WOLFSSL_ENTER("DoTls13NewSessionTicket");
5555
5556 /* Lifetime hint. */
5557 if ((*inOutIdx - begin) + SESSION_HINT_SZ > size)
5558 return BUFFER_ERROR;
5559 ato32(input + *inOutIdx, &lifetime);
5560 *inOutIdx += SESSION_HINT_SZ;
5561 if (lifetime > MAX_LIFETIME)
5562 return SERVER_HINT_ERROR;
5563
5564 /* Age add. */
5565 if ((*inOutIdx - begin) + SESSION_ADD_SZ > size)
5566 return BUFFER_ERROR;
5567 ato32(input + *inOutIdx, &ageAdd);
5568 *inOutIdx += SESSION_ADD_SZ;
5569
5570 /* Ticket length. */
5571 if ((*inOutIdx - begin) + LENGTH_SZ > size)
5572 return BUFFER_ERROR;
5573 ato16(input + *inOutIdx, &length);
5574 *inOutIdx += LENGTH_SZ;
5575 if ((*inOutIdx - begin) + length > size)
5576 return BUFFER_ERROR;
5577
5578 if ((ret = SetTicket(ssl, input + *inOutIdx, length)) != 0)
5579 return ret;
5580 *inOutIdx += length;
5581
5582 now = TimeNowInMilliseconds();
5583 if (now == (word32)GETTIME_ERROR)
5584 return now;
5585 /* Copy in ticket data (server identity). */
5586 ssl->timeout = lifetime;
5587 ssl->session.timeout = lifetime;
5588 ssl->session.cipherSuite0 = ssl->options.cipherSuite0;
5589 ssl->session.cipherSuite = ssl->options.cipherSuite;
5590 ssl->session.ticketSeen = now;
5591 ssl->session.ticketAdd = ageAdd;
5592 #ifdef WOLFSSL_EARLY_DATA
5593 ssl->session.maxEarlyDataSz = ssl->options.maxEarlyDataSz;
5594 #endif
5595
5596 if ((*inOutIdx - begin) + EXTS_SZ > size)
5597 return BUFFER_ERROR;
5598 ato16(input + *inOutIdx, &length);
5599 *inOutIdx += EXTS_SZ;
5600 if ((*inOutIdx - begin) + length != size)
5601 return BUFFER_ERROR;
5602 #ifdef WOLFSSL_EARLY_DATA
5603 ret = TLSX_Parse(ssl, (byte *)input + (*inOutIdx), length, session_ticket,
5604 NULL);
5605 if (ret != 0)
5606 return ret;
5607 #endif
5608 *inOutIdx += length;
5609
5610 #ifndef NO_SESSION_CACHE
5611 AddSession(ssl);
5612 #endif
5613
5614 /* Always encrypted. */
5615 *inOutIdx += ssl->keys.padSz;
5616
5617 ssl->expect_session_ticket = 0;
5618#else
5619 (void)ssl;
5620 (void)input;
5621
5622 WOLFSSL_ENTER("DoTls13NewSessionTicket");
5623
5624 *inOutIdx += size + ssl->keys.padSz;
5625#endif /* HAVE_SESSION_TICKET */
5626
5627 WOLFSSL_LEAVE("DoTls13NewSessionTicket", 0);
5628
5629 return 0;
5630}
5631#endif /* NO_WOLFSSL_CLIENT */
5632
5633#ifndef NO_WOLFSSL_SERVER
5634 #ifdef HAVE_SESSION_TICKET
5635
5636#ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
5637/* Offset of the MAC size in the finished message. */
5638#define FINISHED_MSG_SIZE_OFFSET 3
5639
5640/* Calculate the resumption secret which includes the unseen client finished
5641 * message.
5642 *
5643 * ssl The SSL/TLS object.
5644 * retuns 0 on success, otherwise failure.
5645 */
5646static int ExpectedResumptionSecret(WOLFSSL* ssl)
5647{
5648 int ret;
5649 word32 finishedSz = 0;
5650 byte mac[MAX_DIGEST_SIZE];
5651 Digest digest;
5652 static byte header[] = { 0x14, 0x00, 0x00, 0x00 };
5653
5654 /* Copy the running hash so we cna restore it after. */
5655 switch (ssl->specs.mac_algorithm) {
5656 #ifndef NO_SHA256
5657 case sha256_mac:
5658 ret = wc_Sha256Copy(&ssl->hsHashes->hashSha256, &digest.sha256);
5659 if (ret != 0)
5660 return ret;
5661 break;
5662 #endif
5663 #ifdef WOLFSSL_SHA384
5664 case sha384_mac:
5665 ret = wc_Sha384Copy(&ssl->hsHashes->hashSha384, &digest.sha384);
5666 if (ret != 0)
5667 return ret;
5668 break;
5669 #endif
5670 #ifdef WOLFSSL_TLS13_SHA512
5671 case sha512_mac:
5672 ret = wc_Sha512Copy(&ssl->hsHashes->hashSha512, &digest.sha512);
5673 if (ret != 0)
5674 return ret;
5675 break;
5676 #endif
5677 }
5678
5679 /* Generate the Client's Finished message and hash it. */
5680 ret = BuildTls13HandshakeHmac(ssl, ssl->keys.client_write_MAC_secret, mac,
5681 &finishedSz);
5682 if (ret != 0)
5683 return ret;
5684 header[FINISHED_MSG_SIZE_OFFSET] = finishedSz;
5685#ifdef WOLFSSL_EARLY_DATA
5686 if (ssl->earlyData) {
5687 static byte endOfEarlyData[] = { 0x05, 0x00, 0x00, 0x00 };
5688 ret = HashInputRaw(ssl, endOfEarlyData, sizeof(endOfEarlyData));
5689 if (ret != 0)
5690 return ret;
5691 }
5692#endif
5693 if ((ret = HashInputRaw(ssl, header, sizeof(header))) != 0)
5694 return ret;
5695 if ((ret = HashInputRaw(ssl, mac, finishedSz)) != 0)
5696 return ret;
5697
5698 if ((ret = DeriveResumptionSecret(ssl, ssl->session.masterSecret)) != 0)
5699 return ret;
5700
5701 /* Restore the hash inline with currently seen messages. */
5702 switch (ssl->specs.mac_algorithm) {
5703 #ifndef NO_SHA256
5704 case sha256_mac:
5705 ret = wc_Sha256Copy(&digest.sha256, &ssl->hsHashes->hashSha256);
5706 if (ret != 0)
5707 return ret;
5708 break;
5709 #endif
5710 #ifdef WOLFSSL_SHA384
5711 case sha384_mac:
5712 ret = wc_Sha384Copy(&digest.sha384, &ssl->hsHashes->hashSha384);
5713 if (ret != 0)
5714 return ret;
5715 break;
5716 #endif
5717 #ifdef WOLFSSL_TLS13_SHA512
5718 case sha512_mac:
5719 ret = wc_Sha512Copy(&digest.sha512, &ssl->hsHashes->hashSha384);
5720 if (ret != 0)
5721 return ret;
5722 break;
5723 #endif
5724 }
5725
5726 return ret;
5727}
5728#endif
5729
5730/* Send New Session Ticket handshake message.
5731 * Message contains the information required to perform resumption.
5732 *
5733 * ssl The SSL/TLS object.
5734 * retuns 0 on success, otherwise failure.
5735 */
5736static int SendTls13NewSessionTicket(WOLFSSL* ssl)
5737{
5738 byte* output;
5739 int ret;
5740 int sendSz;
5741 word32 extSz;
5742 word32 length;
5743 word32 idx = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
5744
5745 WOLFSSL_ENTER("SendTls13NewSessionTicket");
5746
5747#ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
5748 if (!ssl->msgsReceived.got_finished) {
5749 if ((ret = ExpectedResumptionSecret(ssl)) != 0)
5750 return ret;
5751 }
5752#endif
5753
5754 if (!ssl->options.noTicketTls13) {
5755 if ((ret = CreateTicket(ssl)) != 0)
5756 return ret;
5757 }
5758
5759#ifdef WOLFSSL_EARLY_DATA
5760 ssl->session.maxEarlyDataSz = ssl->options.maxEarlyDataSz;
5761 if (ssl->session.maxEarlyDataSz > 0)
5762 TLSX_EarlyData_Use(ssl, ssl->session.maxEarlyDataSz);
5763 extSz = TLSX_GetResponseSize(ssl, session_ticket);
5764#else
5765 extSz = EXTS_SZ;
5766#endif
5767
5768 /* Lifetime | Age Add | Ticket | Extensions */
5769 length = SESSION_HINT_SZ + SESSION_ADD_SZ + LENGTH_SZ +
5770 ssl->session.ticketLen + extSz;
5771 sendSz = idx + length + MAX_MSG_EXTRA;
5772
5773 /* Check buffers are big enough and grow if needed. */
5774 if ((ret = CheckAvailableSize(ssl, sendSz)) != 0)
5775 return ret;
5776
5777 /* Get position in output buffer to write new message to. */
5778 output = ssl->buffers.outputBuffer.buffer +
5779 ssl->buffers.outputBuffer.length;
5780
5781 /* Put the record and handshake headers on. */
5782 AddTls13Headers(output, length, session_ticket, ssl);
5783
5784 /* Lifetime hint */
5785 c32toa(ssl->ctx->ticketHint, output + idx);
5786 idx += SESSION_HINT_SZ;
5787 /* Age add - obfuscator */
5788 c32toa(ssl->session.ticketAdd, output + idx);
5789 idx += SESSION_ADD_SZ;
5790
5791 /* length */
5792 c16toa(ssl->session.ticketLen, output + idx);
5793 idx += LENGTH_SZ;
5794 /* ticket */
5795 XMEMCPY(output + idx, ssl->session.ticket, ssl->session.ticketLen);
5796 idx += ssl->session.ticketLen;
5797
5798#ifdef WOLFSSL_EARLY_DATA
5799 idx += TLSX_WriteResponse(ssl, output + idx, session_ticket);
5800#else
5801 /* No extension support - empty extensions. */
5802 c16toa(0, output + idx);
5803 idx += EXTS_SZ;
5804#endif
5805
5806 ssl->options.haveSessionId = 1;
5807
5808 #ifndef NO_SESSION_CACHE
5809 AddSession(ssl);
5810 #endif
5811
5812 /* This message is always encrypted. */
5813 sendSz = BuildTls13Message(ssl, output, sendSz, output + RECORD_HEADER_SZ,
5814 idx - RECORD_HEADER_SZ, handshake, 0, 0, 0);
5815 if (sendSz < 0)
5816 return sendSz;
5817
5818 ssl->buffers.outputBuffer.length += sendSz;
5819
5820 if (!ssl->options.groupMessages)
5821 ret = SendBuffered(ssl);
5822
5823 WOLFSSL_LEAVE("SendTls13NewSessionTicket", 0);
5824
5825 return ret;
5826}
5827 #endif /* HAVE_SESSION_TICKET */
5828#endif /* NO_WOLFSSL_SERVER */
5829
5830/* Make sure no duplicates, no fast forward, or other problems
5831 *
5832 * ssl The SSL/TLS object.
5833 * type Type of handshake message received.
5834 * returns 0 on success, otherwise failure.
5835 */
5836static int SanityCheckTls13MsgReceived(WOLFSSL* ssl, byte type)
5837{
5838 /* verify not a duplicate, mark received, check state */
5839 switch (type) {
5840
5841#ifndef NO_WOLFSSL_SERVER
5842 case client_hello:
5843 if (ssl->msgsReceived.got_client_hello == 2) {
5844 WOLFSSL_MSG("Too many ClientHello received");
5845 return DUPLICATE_MSG_E;
5846 }
5847 ssl->msgsReceived.got_client_hello++;
5848
5849 break;
5850#endif
5851
5852#ifndef NO_WOLFSSL_CLIENT
5853 case server_hello:
5854 if (ssl->msgsReceived.got_server_hello) {
5855 WOLFSSL_MSG("Duplicate ServerHello received");
5856 return DUPLICATE_MSG_E;
5857 }
5858 ssl->msgsReceived.got_server_hello = 1;
5859
5860 break;
5861#endif
5862
5863#ifndef NO_WOLFSSL_CLIENT
5864 case session_ticket:
5865 if (ssl->msgsReceived.got_session_ticket) {
5866 WOLFSSL_MSG("Duplicate SessionTicket received");
5867 return DUPLICATE_MSG_E;
5868 }
5869 ssl->msgsReceived.got_session_ticket = 1;
5870
5871 break;
5872#endif
5873
5874#ifndef NO_WOLFSSL_SERVER
5875 #ifdef WOLFSSL_EARLY_DATA
5876 case end_of_early_data:
5877 if (ssl->msgsReceived.got_end_of_early_data == 1) {
5878 WOLFSSL_MSG("Too many EndOfEarlyData received");
5879 return DUPLICATE_MSG_E;
5880 }
5881 ssl->msgsReceived.got_end_of_early_data++;
5882
5883 break;
5884 #endif
5885#endif
5886
5887#ifndef NO_WOLFSSL_CLIENT
5888 case hello_retry_request:
5889 if (ssl->msgsReceived.got_hello_retry_request) {
5890 WOLFSSL_MSG("Duplicate HelloRetryRequest received");
5891 return DUPLICATE_MSG_E;
5892 }
5893 ssl->msgsReceived.got_hello_retry_request = 1;
5894
5895 break;
5896#endif
5897
5898#ifndef NO_WOLFSSL_CLIENT
5899 case encrypted_extensions:
5900 if (ssl->msgsReceived.got_encrypted_extensions) {
5901 WOLFSSL_MSG("Duplicate EncryptedExtensions received");
5902 return DUPLICATE_MSG_E;
5903 }
5904 ssl->msgsReceived.got_encrypted_extensions = 1;
5905
5906 break;
5907#endif
5908
5909 case certificate:
5910 if (ssl->msgsReceived.got_certificate) {
5911 WOLFSSL_MSG("Duplicate Certificate received");
5912 return DUPLICATE_MSG_E;
5913 }
5914 ssl->msgsReceived.got_certificate = 1;
5915
5916#ifndef NO_WOLFSSL_CLIENT
5917 if (ssl->options.side == WOLFSSL_CLIENT_END) {
5918 if ( ssl->msgsReceived.got_server_hello == 0) {
5919 WOLFSSL_MSG("No ServerHello before Cert");
5920 return OUT_OF_ORDER_E;
5921 }
5922 }
5923#endif
5924#ifndef NO_WOLFSSL_SERVER
5925 if (ssl->options.side == WOLFSSL_SERVER_END) {
5926 if ( ssl->msgsReceived.got_client_hello == 0) {
5927 WOLFSSL_MSG("No ClientHello before Cert");
5928 return OUT_OF_ORDER_E;
5929 }
5930 }
5931#endif
5932 break;
5933
5934#ifndef NO_WOLFSSL_CLIENT
5935 case certificate_request:
5936 #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
5937 if (ssl->msgsReceived.got_finished)
5938 ;
5939 else
5940 #endif
5941 if (ssl->msgsReceived.got_certificate_request) {
5942 WOLFSSL_MSG("Duplicate CertificateRequest received");
5943 return DUPLICATE_MSG_E;
5944 }
5945 ssl->msgsReceived.got_certificate_request = 1;
5946
5947 break;
5948#endif
5949
5950 case certificate_verify:
5951 if (ssl->msgsReceived.got_certificate_verify) {
5952 WOLFSSL_MSG("Duplicate CertificateVerify received");
5953 return DUPLICATE_MSG_E;
5954 }
5955 ssl->msgsReceived.got_certificate_verify = 1;
5956
5957 if (ssl->msgsReceived.got_certificate == 0) {
5958 WOLFSSL_MSG("No Cert before CertVerify");
5959 return OUT_OF_ORDER_E;
5960 }
5961 break;
5962
5963 case finished:
5964 #ifdef WOLFSSL_POST_HANDSHAKE_AUTH
5965 if (1) {
5966 }
5967 else
5968 #endif
5969 if (ssl->msgsReceived.got_finished) {
5970 WOLFSSL_MSG("Duplicate Finished received");
5971 return DUPLICATE_MSG_E;
5972 }
5973 ssl->msgsReceived.got_finished = 1;
5974
5975 break;
5976
5977 case key_update:
5978 if (!ssl->msgsReceived.got_finished) {
5979 WOLFSSL_MSG("No KeyUpdate before Finished");
5980 return OUT_OF_ORDER_E;
5981 }
5982 break;
5983
5984 default:
5985 WOLFSSL_MSG("Unknown message type");
5986 return SANITY_MSG_E;
5987 }
5988
5989 return 0;
5990}
5991
5992/* Handle a type of handshake message that has been received.
5993 *
5994 * ssl The SSL/TLS object.
5995 * input The message buffer.
5996 * inOutIdx On entry, the index into the buffer of the current message.
5997 * On exit, the index into the buffer of the next message.
5998 * size The length of the current handshake message.
5999 * totalSz Length of remaining data in the message buffer.
6000 * returns 0 on success and otherwise failure.
6001 */
6002int DoTls13HandShakeMsgType(WOLFSSL* ssl, byte* input, word32* inOutIdx,
6003 byte type, word32 size, word32 totalSz)
6004{
6005 int ret = 0;
6006 (void)totalSz;
6007 word32 inIdx = *inOutIdx;
6008
6009 WOLFSSL_ENTER("DoTls13HandShakeMsgType");
6010
6011 /* make sure can read the message */
6012 if (*inOutIdx + size > totalSz)
6013 return INCOMPLETE_DATA;
6014
6015 /* sanity check msg received */
6016 if ( (ret = SanityCheckTls13MsgReceived(ssl, type)) != 0) {
6017 WOLFSSL_MSG("Sanity Check on handshake message type received failed");
6018 return ret;
6019 }
6020
6021#ifdef WOLFSSL_CALLBACKS
6022 /* add name later, add on record and handshake header part back on */
6023 if (ssl->toInfoOn) {
6024 int add = RECORD_HEADER_SZ + HANDSHAKE_HEADER_SZ;
6025 AddPacketInfo(0, &ssl->timeoutInfo, input + *inOutIdx - add,
6026 size + add, ssl->heap);
6027 AddLateRecordHeader(&ssl->curRL, &ssl->timeoutInfo);
6028 }
6029#endif
6030
6031 if (ssl->options.handShakeState == HANDSHAKE_DONE &&
6032 type != session_ticket && type != certificate_request &&
6033 type != certificate && type != key_update) {
6034 WOLFSSL_MSG("HandShake message after handshake complete");
6035 SendAlert(ssl, alert_fatal, unexpected_message);
6036 return OUT_OF_ORDER_E;
6037 }
6038
6039 if (ssl->options.side == WOLFSSL_CLIENT_END &&
6040 ssl->options.serverState == NULL_STATE &&
6041 type != server_hello && type != hello_retry_request) {
6042 WOLFSSL_MSG("First server message not server hello");
6043 SendAlert(ssl, alert_fatal, unexpected_message);
6044 return OUT_OF_ORDER_E;
6045 }
6046
6047 if (ssl->options.side == WOLFSSL_SERVER_END &&
6048 ssl->options.clientState == NULL_STATE && type != client_hello) {
6049 WOLFSSL_MSG("First client message not client hello");
6050 SendAlert(ssl, alert_fatal, unexpected_message);
6051 return OUT_OF_ORDER_E;
6052 }
6053
6054 /* above checks handshake state */
6055 switch (type) {
6056
6057#ifndef NO_WOLFSSL_CLIENT
6058 case hello_retry_request:
6059 WOLFSSL_MSG("processing hello rety request");
6060 ret = DoTls13HelloRetryRequest(ssl, input, inOutIdx, size);
6061 break;
6062
6063 case server_hello:
6064 WOLFSSL_MSG("processing server hello");
6065 ret = DoTls13ServerHello(ssl, input, inOutIdx, size);
6066 break;
6067
6068#ifndef NO_CERTS
6069 case certificate_request:
6070 WOLFSSL_MSG("processing certificate request");
6071 ret = DoTls13CertificateRequest(ssl, input, inOutIdx, size);
6072 break;
6073#endif
6074
6075 case session_ticket:
6076 WOLFSSL_MSG("processing new session ticket");
6077 ret = DoTls13NewSessionTicket(ssl, input, inOutIdx, size);
6078 break;
6079
6080 case encrypted_extensions:
6081 WOLFSSL_MSG("processing encrypted extensions");
6082 ret = DoTls13EncryptedExtensions(ssl, input, inOutIdx, size);
6083 break;
6084#endif /* !NO_WOLFSSL_CLIENT */
6085
6086#ifndef NO_CERTS
6087 case certificate:
6088 WOLFSSL_MSG("processing certificate");
6089 ret = DoTls13Certificate(ssl, input, inOutIdx, size);
6090 break;
6091#endif
6092
6093#if !defined(NO_RSA) || defined(HAVE_ECC) || defined(HAVE_ED25519)
6094 case certificate_verify:
6095 WOLFSSL_MSG("processing certificate verify");
6096 ret = DoTls13CertificateVerify(ssl, input, inOutIdx, size);
6097 break;
6098#endif /* !NO_RSA || HAVE_ECC */
6099
6100#ifdef WOLFSSL_EARLY_DATA
6101 #ifndef NO_WOLFSSL_SERVER
6102 case end_of_early_data:
6103 WOLFSSL_MSG("processing end of early data");
6104 ret = DoTls13EndOfEarlyData(ssl, input, inOutIdx, size);
6105 break;
6106 #endif
6107#endif
6108
6109 case finished:
6110 WOLFSSL_MSG("processing finished");
6111 ret = DoTls13Finished(ssl, input, inOutIdx, size, totalSz, NO_SNIFF);
6112 break;
6113
6114 case key_update:
6115 WOLFSSL_MSG("processing finished");
6116 ret = DoTls13KeyUpdate(ssl, input, inOutIdx, size);
6117 break;
6118
6119#ifndef NO_WOLFSSL_SERVER
6120 case client_hello:
6121 WOLFSSL_MSG("processing client hello");
6122 ret = DoTls13ClientHello(ssl, input, inOutIdx, size);
6123 break;
6124#endif /* !NO_WOLFSSL_SERVER */
6125
6126 default:
6127 WOLFSSL_MSG("Unknown handshake message type");
6128 ret = UNKNOWN_HANDSHAKE_TYPE;
6129 break;
6130 }
6131
6132 /* reset error */
6133 if (ret == 0 && ssl->error == WC_PENDING_E)
6134 ssl->error = 0;
6135
6136
6137 if (ret == 0 && type != client_hello && type != session_ticket &&
6138 type != key_update && ssl->error != WC_PENDING_E) {
6139 ret = HashInput(ssl, input + inIdx, size);
6140 }
6141
6142 if (ret == BUFFER_ERROR || ret == MISSING_HANDSHAKE_DATA)
6143 SendAlert(ssl, alert_fatal, decode_error);
6144
6145 if (ret == EXT_NOT_ALLOWED || ret == PEER_KEY_ERROR ||
6146 ret == ECC_PEERKEY_ERROR || ret == BAD_KEY_SHARE_DATA ||
6147 ret == PSK_KEY_ERROR || ret == INVALID_PARAMETER) {
6148 SendAlert(ssl, alert_fatal, illegal_parameter);
6149 }
6150
6151 if (ssl->options.tls1_3) {
6152 if (type == server_hello && ssl->options.side == WOLFSSL_CLIENT_END) {
6153 if ((ret = DeriveEarlySecret(ssl)) != 0)
6154 return ret;
6155 if ((ret = DeriveHandshakeSecret(ssl)) != 0)
6156 return ret;
6157
6158 if ((ret = DeriveTls13Keys(ssl, handshake_key,
6159 ENCRYPT_AND_DECRYPT_SIDE, 1)) != 0) {
6160 return ret;
6161 }
6162#ifdef WOLFSSL_EARLY_DATA
6163 if ((ret = SetKeysSide(ssl, DECRYPT_SIDE_ONLY)) != 0)
6164 return ret;
6165#else
6166 if ((ret = SetKeysSide(ssl, ENCRYPT_AND_DECRYPT_SIDE)) != 0)
6167 return ret;
6168#endif
6169 }
6170#ifdef WOLFSSL_EARLY_DATA
6171 if (type == encrypted_extensions &&
6172 ssl->options.side == WOLFSSL_CLIENT_END) {
6173 if (!ssl->earlyData)
6174 {
6175 if ((ret = SetKeysSide(ssl, ENCRYPT_SIDE_ONLY)) != 0)
6176 return ret;
6177 }
6178 }
6179#endif
6180
6181 if (type == finished && ssl->options.side == WOLFSSL_CLIENT_END) {
6182 if ((ret = DeriveMasterSecret(ssl)) != 0)
6183 return ret;
6184#ifdef WOLFSSL_EARLY_DATA
6185 if ((ret = DeriveTls13Keys(ssl, traffic_key,
6186 ENCRYPT_AND_DECRYPT_SIDE, !ssl->earlyData)) != 0) {
6187 return ret;
6188 }
6189#else
6190 if ((ret = DeriveTls13Keys(ssl, traffic_key,
6191 ENCRYPT_AND_DECRYPT_SIDE, 1)) != 0) {
6192 return ret;
6193 }
6194#endif
6195 }
6196
6197#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
6198 if (type == finished && ssl->options.side == WOLFSSL_SERVER_END) {
6199 ret = DeriveResumptionSecret(ssl, ssl->session.masterSecret);
6200 if (ret != 0)
6201 return ret;
6202 }
6203#endif
6204 }
6205
6206#ifdef WOLFSSL_ASYNC_CRYPT
6207 /* if async, offset index so this msg will be processed again */
6208 if (ret == WC_PENDING_E && *inOutIdx > 0) {
6209 *inOutIdx -= HANDSHAKE_HEADER_SZ;
6210 }
6211#endif
6212
6213 WOLFSSL_LEAVE("DoTls13HandShakeMsgType()", ret);
6214 return ret;
6215}
6216
6217
6218/* Handle a handshake message that has been received.
6219 *
6220 * ssl The SSL/TLS object.
6221 * input The message buffer.
6222 * inOutIdx On entry, the index into the buffer of the current message.
6223 * On exit, the index into the buffer of the next message.
6224 * totalSz Length of remaining data in the message buffer.
6225 * returns 0 on success and otherwise failure.
6226 */
6227int DoTls13HandShakeMsg(WOLFSSL* ssl, byte* input, word32* inOutIdx,
6228 word32 totalSz)
6229{
6230 int ret = 0;
6231 word32 inputLength;
6232
6233 WOLFSSL_ENTER("DoTls13HandShakeMsg()");
6234
6235 if (ssl->arrays == NULL) {
6236 byte type;
6237 word32 size;
6238
6239 if (GetHandshakeHeader(ssl,input,inOutIdx,&type, &size, totalSz) != 0)
6240 return PARSE_ERROR;
6241
6242 return DoTls13HandShakeMsgType(ssl, input, inOutIdx, type, size,
6243 totalSz);
6244 }
6245
6246 inputLength = ssl->buffers.inputBuffer.length - *inOutIdx - ssl->keys.padSz;
6247
6248 /* If there is a pending fragmented handshake message,
6249 * pending message size will be non-zero. */
6250 if (ssl->arrays->pendingMsgSz == 0) {
6251 byte type;
6252 word32 size;
6253
6254 if (GetHandshakeHeader(ssl,input, inOutIdx, &type, &size, totalSz) != 0)
6255 return PARSE_ERROR;
6256
6257 /* Cap the maximum size of a handshake message to something reasonable.
6258 * By default is the maximum size of a certificate message assuming
6259 * nine 2048-bit RSA certificates in the chain. */
6260 if (size > MAX_HANDSHAKE_SZ) {
6261 WOLFSSL_MSG("Handshake message too large");
6262 return HANDSHAKE_SIZE_ERROR;
6263 }
6264
6265 /* size is the size of the certificate message payload */
6266 if (inputLength - HANDSHAKE_HEADER_SZ < size) {
6267 ssl->arrays->pendingMsgType = type;
6268 ssl->arrays->pendingMsgSz = size + HANDSHAKE_HEADER_SZ;
6269 ssl->arrays->pendingMsg = (byte*)XMALLOC(size + HANDSHAKE_HEADER_SZ,
6270 ssl->heap,
6271 DYNAMIC_TYPE_ARRAYS);
6272 if (ssl->arrays->pendingMsg == NULL)
6273 return MEMORY_E;
6274 XMEMCPY(ssl->arrays->pendingMsg,
6275 input + *inOutIdx - HANDSHAKE_HEADER_SZ,
6276 inputLength);
6277 ssl->arrays->pendingMsgOffset = inputLength;
6278 *inOutIdx += inputLength + ssl->keys.padSz - HANDSHAKE_HEADER_SZ;
6279 return 0;
6280 }
6281
6282 ret = DoTls13HandShakeMsgType(ssl, input, inOutIdx, type, size,
6283 totalSz);
6284 }
6285 else {
6286 if (inputLength + ssl->arrays->pendingMsgOffset >
6287 ssl->arrays->pendingMsgSz) {
6288 return BUFFER_ERROR;
6289 }
6290
6291 XMEMCPY(ssl->arrays->pendingMsg + ssl->arrays->pendingMsgOffset,
6292 input + *inOutIdx, inputLength);
6293 ssl->arrays->pendingMsgOffset += inputLength;
6294 *inOutIdx += inputLength + ssl->keys.padSz;
6295
6296 if (ssl->arrays->pendingMsgOffset == ssl->arrays->pendingMsgSz)
6297 {
6298 word32 idx = 0;
6299 ret = DoTls13HandShakeMsgType(ssl,
6300 ssl->arrays->pendingMsg + HANDSHAKE_HEADER_SZ,
6301 &idx, ssl->arrays->pendingMsgType,
6302 ssl->arrays->pendingMsgSz - HANDSHAKE_HEADER_SZ,
6303 ssl->arrays->pendingMsgSz);
6304 #ifdef WOLFSSL_ASYNC_CRYPT
6305 if (ret == WC_PENDING_E) {
6306 /* setup to process fragment again */
6307 ssl->arrays->pendingMsgOffset -= inputLength;
6308 *inOutIdx -= inputLength + ssl->keys.padSz;
6309 }
6310 else
6311 #endif
6312 {
6313 XFREE(ssl->arrays->pendingMsg, ssl->heap, DYNAMIC_TYPE_ARRAYS);
6314 ssl->arrays->pendingMsg = NULL;
6315 ssl->arrays->pendingMsgSz = 0;
6316 }
6317 }
6318 }
6319
6320 WOLFSSL_LEAVE("DoTls13HandShakeMsg()", ret);
6321 return ret;
6322}
6323
6324
6325/* The client connecting to the server.
6326 * The protocol version is expecting to be TLS v1.3.
6327 * If the server downgrades, and older versions of the protocol are compiled
6328 * in, the client will fallback to wolfSSL_connect().
6329 * Please see note at top of README if you get an error from connect.
6330 *
6331 * ssl The SSL/TLS object.
6332 * returns WOLFSSL_SUCCESS on successful handshake, WOLFSSL_FATAL_ERROR when
6333 * unrecoverable error occurs and 0 otherwise.
6334 * For more error information use wolfSSL_get_error().
6335 */
6336int wolfSSL_connect_TLSv13(WOLFSSL* ssl)
6337{
6338 int neededState;
6339
6340 WOLFSSL_ENTER("wolfSSL_connect_TLSv13()");
6341
6342 #ifdef HAVE_ERRNO_H
6343 errno = 0;
6344 #endif
6345
6346 if (ssl->options.side != WOLFSSL_CLIENT_END) {
6347 WOLFSSL_ERROR(ssl->error = SIDE_ERROR);
6348 return WOLFSSL_FATAL_ERROR;
6349 }
6350
6351 if (ssl->buffers.outputBuffer.length > 0) {
6352 if ((ssl->error = SendBuffered(ssl)) == 0) {
6353 /* fragOffset is non-zero when sending fragments. On the last
6354 * fragment, fragOffset is zero again, and the state can be
6355 * advanced. */
6356 if (ssl->fragOffset == 0) {
6357 ssl->options.connectState++;
6358 WOLFSSL_MSG("connect state: "
6359 "Advanced from last buffered fragment send");
6360 }
6361 else {
6362 WOLFSSL_MSG("connect state: "
6363 "Not advanced, more fragments to send");
6364 }
6365 }
6366 else {
6367 WOLFSSL_ERROR(ssl->error);
6368 return WOLFSSL_FATAL_ERROR;
6369 }
6370 }
6371
6372 switch (ssl->options.connectState) {
6373
6374 case CONNECT_BEGIN:
6375 /* Always send client hello first. */
6376 if ((ssl->error = SendTls13ClientHello(ssl)) != 0) {
6377 WOLFSSL_ERROR(ssl->error);
6378 return WOLFSSL_FATAL_ERROR;
6379 }
6380
6381 ssl->options.connectState = CLIENT_HELLO_SENT;
6382 WOLFSSL_MSG("connect state: CLIENT_HELLO_SENT");
6383 #ifdef WOLFSSL_EARLY_DATA
6384 if (ssl->earlyData) {
6385 ssl->options.handShakeState = CLIENT_HELLO_COMPLETE;
6386 return WOLFSSL_SUCCESS;
6387 }
6388 #endif
6389 FALL_THROUGH;
6390
6391 case CLIENT_HELLO_SENT:
6392 neededState = ssl->options.resuming ? SERVER_FINISHED_COMPLETE :
6393 SERVER_HELLODONE_COMPLETE;
6394 /* Get the response/s from the server. */
6395 while (ssl->options.serverState < neededState) {
6396 if ((ssl->error = ProcessReply(ssl)) < 0) {
6397 WOLFSSL_ERROR(ssl->error);
6398 return WOLFSSL_FATAL_ERROR;
6399 }
6400 /* if resumption failed, reset needed state. */
6401 if (neededState == SERVER_FINISHED_COMPLETE &&
6402 !ssl->options.resuming) {
6403 neededState = SERVER_HELLODONE_COMPLETE;
6404 }
6405 }
6406
6407 ssl->options.connectState = HELLO_AGAIN;
6408 WOLFSSL_MSG("connect state: HELLO_AGAIN");
6409 FALL_THROUGH;
6410
6411 case HELLO_AGAIN:
6412 if (ssl->options.certOnly)
6413 return WOLFSSL_SUCCESS;
6414
6415 if (!ssl->options.tls1_3) {
6416 if (ssl->options.downgrade)
6417 return wolfSSL_connect(ssl);
6418
6419 WOLFSSL_MSG("Client using higher version, fatal error");
6420 return VERSION_ERROR;
6421 }
6422
6423 if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST) {
6424 ssl->options.serverState = NULL_STATE;
6425 /* Try again with different security parameters. */
6426 if ((ssl->error = SendTls13ClientHello(ssl)) != 0) {
6427 WOLFSSL_ERROR(ssl->error);
6428 return WOLFSSL_FATAL_ERROR;
6429 }
6430 }
6431
6432 ssl->options.connectState = HELLO_AGAIN_REPLY;
6433 WOLFSSL_MSG("connect state: HELLO_AGAIN_REPLY");
6434 FALL_THROUGH;
6435
6436 case HELLO_AGAIN_REPLY:
6437 if (ssl->options.serverState == NULL_STATE ||
6438 ssl->error == WC_PENDING_E) {
6439 neededState = ssl->options.resuming ? SERVER_FINISHED_COMPLETE :
6440 SERVER_HELLODONE_COMPLETE;
6441
6442 /* Get the response/s from the server. */
6443 while (ssl->options.serverState < neededState) {
6444 if ((ssl->error = ProcessReply(ssl)) < 0) {
6445 WOLFSSL_ERROR(ssl->error);
6446 return WOLFSSL_FATAL_ERROR;
6447 }
6448 /* if resumption failed, reset needed state */
6449 else if (neededState == SERVER_FINISHED_COMPLETE) {
6450 if (!ssl->options.resuming)
6451 neededState = SERVER_HELLODONE_COMPLETE;
6452 }
6453 }
6454 }
6455
6456 ssl->options.connectState = FIRST_REPLY_DONE;
6457 WOLFSSL_MSG("connect state: FIRST_REPLY_DONE");
6458 FALL_THROUGH;
6459
6460 case FIRST_REPLY_DONE:
6461 #ifdef WOLFSSL_EARLY_DATA
6462 if (ssl->earlyData) {
6463 if ((ssl->error = SendTls13EndOfEarlyData(ssl)) != 0) {
6464 WOLFSSL_ERROR(ssl->error);
6465 return WOLFSSL_FATAL_ERROR;
6466 }
6467 WOLFSSL_MSG("sent: end_of_early_data");
6468 }
6469 #endif
6470
6471 ssl->options.connectState = FIRST_REPLY_FIRST;
6472 WOLFSSL_MSG("connect state: FIRST_REPLY_FIRST");
6473 FALL_THROUGH;
6474
6475 case FIRST_REPLY_FIRST:
6476 #ifndef NO_CERTS
6477 if (!ssl->options.resuming && ssl->options.sendVerify) {
6478 ssl->error = SendTls13Certificate(ssl);
6479 if (ssl->error != 0) {
6480 WOLFSSL_ERROR(ssl->error);
6481 return WOLFSSL_FATAL_ERROR;
6482 }
6483 WOLFSSL_MSG("sent: certificate");
6484 }
6485 #endif
6486
6487 ssl->options.connectState = FIRST_REPLY_SECOND;
6488 WOLFSSL_MSG("connect state: FIRST_REPLY_SECOND");
6489 FALL_THROUGH;
6490
6491 case FIRST_REPLY_SECOND:
6492
6493 #ifndef NO_CERTS
6494 if (!ssl->options.resuming && ssl->options.sendVerify) {
6495 ssl->error = SendTls13CertificateVerify(ssl);
6496 if (ssl->error != 0) {
6497 WOLFSSL_ERROR(ssl->error);
6498 return WOLFSSL_FATAL_ERROR;
6499 }
6500 WOLFSSL_MSG("sent: certificate verify");
6501 }
6502 #endif
6503
6504 ssl->options.connectState = FIRST_REPLY_THIRD;
6505 WOLFSSL_MSG("connect state: FIRST_REPLY_THIRD");
6506 FALL_THROUGH;
6507
6508 case FIRST_REPLY_THIRD:
6509 if ((ssl->error = SendTls13Finished(ssl)) != 0) {
6510 WOLFSSL_ERROR(ssl->error);
6511 return WOLFSSL_FATAL_ERROR;
6512 }
6513 WOLFSSL_MSG("sent: finished");
6514
6515 ssl->options.connectState = FINISHED_DONE;
6516 WOLFSSL_MSG("connect state: FINISHED_DONE");
6517 FALL_THROUGH;
6518
6519 case FINISHED_DONE:
6520 #ifndef NO_HANDSHAKE_DONE_CB
6521 if (ssl->hsDoneCb != NULL) {
6522 int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
6523 if (cbret < 0) {
6524 ssl->error = cbret;
6525 WOLFSSL_MSG("HandShake Done Cb don't continue error");
6526 return WOLFSSL_FATAL_ERROR;
6527 }
6528 }
6529 #endif /* NO_HANDSHAKE_DONE_CB */
6530
6531 WOLFSSL_LEAVE("wolfSSL_connect_TLSv13()", WOLFSSL_SUCCESS);
6532 return WOLFSSL_SUCCESS;
6533
6534 default:
6535 WOLFSSL_MSG("Unknown connect state ERROR");
6536 return WOLFSSL_FATAL_ERROR; /* unknown connect state */
6537 }
6538}
6539
6540#if defined(WOLFSSL_SEND_HRR_COOKIE) && !defined(NO_WOLFSSL_SERVER)
6541/* Send a cookie with the HelloRetryRequest to avoid storing state.
6542 *
6543 * ssl SSL/TLS object.
6544 * secret Secret to use when generating integrity check for cookie.
6545 * A value of NULL indicates to generate a new random secret.
6546 * secretSz Size of secret data in bytes.
6547 * Use a value of 0 to indicate use of default size.
6548 * returns BAD_FUNC_ARG when ssl is NULL or not using TLS v1.3, SIDE_ERROR when
6549 * called on a client; WOLFSSL_SUCCESS on success and otherwise failure.
6550 */
6551int wolfSSL_send_hrr_cookie(WOLFSSL* ssl, const unsigned char* secret,
6552 unsigned int secretSz)
6553{
6554 int ret;
6555
6556 if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
6557 return BAD_FUNC_ARG;
6558 if (ssl->options.side == WOLFSSL_CLIENT_END)
6559 return SIDE_ERROR;
6560
6561 if (secretSz == 0) {
6562 #if !defined(NO_SHA) && defined(NO_SHA256)
6563 secretSz = WC_SHA_DIGEST_SIZE;
6564 #endif /* NO_SHA */
6565 #ifndef NO_SHA256
6566 secretSz = WC_SHA256_DIGEST_SIZE;
6567 #endif /* NO_SHA256 */
6568 }
6569
6570 if (secretSz != ssl->buffers.tls13CookieSecret.length) {
6571 byte* newSecret;
6572
6573 if (ssl->buffers.tls13CookieSecret.buffer != NULL) {
6574 ForceZero(ssl->buffers.tls13CookieSecret.buffer,
6575 ssl->buffers.tls13CookieSecret.length);
6576 XFREE(ssl->buffers.tls13CookieSecret.buffer,
6577 ssl->heap, DYNAMIC_TYPE_COOKIE_PWD);
6578 }
6579
6580 newSecret = (byte*)XMALLOC(secretSz, ssl->heap,
6581 DYNAMIC_TYPE_COOKIE_PWD);
6582 if (newSecret == NULL) {
6583 ssl->buffers.tls13CookieSecret.buffer = NULL;
6584 ssl->buffers.tls13CookieSecret.length = 0;
6585 WOLFSSL_MSG("couldn't allocate new cookie secret");
6586 return MEMORY_ERROR;
6587 }
6588 ssl->buffers.tls13CookieSecret.buffer = newSecret;
6589 ssl->buffers.tls13CookieSecret.length = secretSz;
6590 }
6591
6592 /* If the supplied secret is NULL, randomly generate a new secret. */
6593 if (secret == NULL) {
6594 ret = wc_RNG_GenerateBlock(ssl->rng,
6595 ssl->buffers.tls13CookieSecret.buffer, secretSz);
6596 if (ret < 0)
6597 return ret;
6598 }
6599 else
6600 XMEMCPY(ssl->buffers.tls13CookieSecret.buffer, secret, secretSz);
6601
6602 ssl->options.sendCookie = 1;
6603
6604 return WOLFSSL_SUCCESS;
6605}
6606#endif
6607
6608/* Create a key share entry from group.
6609 * Generates a key pair.
6610 *
6611 * ssl The SSL/TLS object.
6612 * group The named group.
6613 * returns 0 on success, otherwise failure.
6614 */
6615int wolfSSL_UseKeyShare(WOLFSSL* ssl, word16 group)
6616{
6617 int ret;
6618
6619 if (ssl == NULL)
6620 return BAD_FUNC_ARG;
6621 if (ssl->options.side == WOLFSSL_SERVER_END)
6622 return SIDE_ERROR;
6623
6624 ret = TLSX_KeyShare_Use(ssl, group, 0, NULL, NULL);
6625 if (ret != 0)
6626 return ret;
6627
6628 return WOLFSSL_SUCCESS;
6629}
6630
6631/* Send no key share entries - use HelloRetryRequest to negotiate shared group.
6632 *
6633 * ssl The SSL/TLS object.
6634 * returns 0 on success, otherwise failure.
6635 */
6636int wolfSSL_NoKeyShares(WOLFSSL* ssl)
6637{
6638 int ret;
6639
6640 if (ssl == NULL)
6641 return BAD_FUNC_ARG;
6642 if (ssl->options.side == WOLFSSL_SERVER_END)
6643 return SIDE_ERROR;
6644
6645 ret = TLSX_KeyShare_Empty(ssl);
6646 if (ret != 0)
6647 return ret;
6648
6649 return WOLFSSL_SUCCESS;
6650}
6651
6652/* Do not send a ticket after TLS v1.3 handshake for resumption.
6653 *
6654 * ctx The SSL/TLS CTX object.
6655 * returns BAD_FUNC_ARG when ctx is NULL and 0 on success.
6656 */
6657int wolfSSL_CTX_no_ticket_TLSv13(WOLFSSL_CTX* ctx)
6658{
6659 if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
6660 return BAD_FUNC_ARG;
6661 if (ctx->method->side == WOLFSSL_CLIENT_END)
6662 return SIDE_ERROR;
6663
6664#ifdef HAVE_SESSION_TICKET
6665 ctx->noTicketTls13 = 1;
6666#endif
6667
6668 return 0;
6669}
6670
6671/* Do not send a ticket after TLS v1.3 handshake for resumption.
6672 *
6673 * ssl The SSL/TLS object.
6674 * returns BAD_FUNC_ARG when ssl is NULL, not using TLS v1.3, or called on
6675 * a client and 0 on success.
6676 */
6677int wolfSSL_no_ticket_TLSv13(WOLFSSL* ssl)
6678{
6679 if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
6680 return BAD_FUNC_ARG;
6681 if (ssl->options.side == WOLFSSL_CLIENT_END)
6682 return SIDE_ERROR;
6683
6684#ifdef HAVE_SESSION_TICKET
6685 ssl->options.noTicketTls13 = 1;
6686#endif
6687
6688 return 0;
6689}
6690
6691/* Disallow (EC)DHE key exchange when using pre-shared keys.
6692 *
6693 * ctx The SSL/TLS CTX object.
6694 * returns BAD_FUNC_ARG when ctx is NULL and 0 on success.
6695 */
6696int wolfSSL_CTX_no_dhe_psk(WOLFSSL_CTX* ctx)
6697{
6698 if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
6699 return BAD_FUNC_ARG;
6700
6701 ctx->noPskDheKe = 1;
6702
6703 return 0;
6704}
6705
6706/* Disallow (EC)DHE key exchange when using pre-shared keys.
6707 *
6708 * ssl The SSL/TLS object.
6709 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3 and 0 on
6710 * success.
6711 */
6712int wolfSSL_no_dhe_psk(WOLFSSL* ssl)
6713{
6714 if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
6715 return BAD_FUNC_ARG;
6716
6717 ssl->options.noPskDheKe = 1;
6718
6719 return 0;
6720}
6721
6722/* Update the keys for encryption and decryption.
6723 * If using non-blocking I/O and WOLFSSL_ERROR_WANT_WRITE is returned then
6724 * calling wolfSSL_write() will have the message sent when ready.
6725 *
6726 * ssl The SSL/TLS object.
6727 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
6728 * WOLFSSL_ERROR_WANT_WRITE when non-blocking I/O is not ready to write,
6729 * WOLFSSL_SUCCESS on success and otherwise failure.
6730 */
6731int wolfSSL_update_keys(WOLFSSL* ssl)
6732{
6733 int ret;
6734
6735 if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
6736 return BAD_FUNC_ARG;
6737
6738 ret = SendTls13KeyUpdate(ssl);
6739 if (ret == WANT_WRITE)
6740 ret = WOLFSSL_ERROR_WANT_WRITE;
6741 else if (ret == 0)
6742 ret = WOLFSSL_SUCCESS;
6743 return ret;
6744}
6745
6746#if !defined(NO_CERTS) && defined(WOLFSSL_POST_HANDSHAKE_AUTH)
6747/* Allow post-handshake authentication in TLS v1.3 connections.
6748 *
6749 * ctx The SSL/TLS CTX object.
6750 * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a server and
6751 * 0 on success.
6752 */
6753int wolfSSL_CTX_allow_post_handshake_auth(WOLFSSL_CTX* ctx)
6754{
6755 if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
6756 return BAD_FUNC_ARG;
6757 if (ctx->method->side == WOLFSSL_SERVER_END)
6758 return SIDE_ERROR;
6759
6760 ctx->postHandshakeAuth = 1;
6761
6762 return 0;
6763}
6764
6765/* Allow post-handshake authentication in TLS v1.3 connection.
6766 *
6767 * ssl The SSL/TLS object.
6768 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
6769 * SIDE_ERROR when not a server and 0 on success.
6770 */
6771int wolfSSL_allow_post_handshake_auth(WOLFSSL* ssl)
6772{
6773 if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
6774 return BAD_FUNC_ARG;
6775 if (ssl->options.side == WOLFSSL_SERVER_END)
6776 return SIDE_ERROR;
6777
6778 ssl->options.postHandshakeAuth = 1;
6779
6780 return 0;
6781}
6782
6783/* Request a certificate of the client.
6784 * Can be called any time after handshake completion.
6785 * A maximum of 256 requests can be sent on a connection.
6786 *
6787 * ssl SSL/TLS object.
6788 */
6789int wolfSSL_request_certificate(WOLFSSL* ssl)
6790{
6791 int ret;
6792 CertReqCtx* certReqCtx;
6793
6794 if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
6795 return BAD_FUNC_ARG;
6796 if (ssl->options.side == WOLFSSL_CLIENT_END)
6797 return SIDE_ERROR;
6798 if (ssl->options.handShakeState != HANDSHAKE_DONE)
6799 return NOT_READY_ERROR;
6800 if (!ssl->options.postHandshakeAuth)
6801 return POST_HAND_AUTH_ERROR;
6802
6803 certReqCtx = (CertReqCtx*)XMALLOC(sizeof(CertReqCtx), ssl->heap,
6804 DYNAMIC_TYPE_TMP_BUFFER);
6805 if (certReqCtx == NULL)
6806 return MEMORY_E;
6807 XMEMSET(certReqCtx, 0, sizeof(CertReqCtx));
6808 certReqCtx->next = ssl->certReqCtx;
6809 certReqCtx->len = 1;
6810 if (certReqCtx->next != NULL)
6811 certReqCtx->ctx = certReqCtx->next->ctx + 1;
6812 ssl->certReqCtx = certReqCtx;
6813
6814 ret = SendTls13CertificateRequest(ssl, &certReqCtx->ctx, certReqCtx->len);
6815 if (ret == WANT_WRITE)
6816 ret = WOLFSSL_ERROR_WANT_WRITE;
6817 else if (ret == 0)
6818 ret = WOLFSSL_SUCCESS;
6819 return ret;
6820}
6821#endif /* !NO_CERTS && WOLFSSL_POST_HANDSHAKE_AUTH */
6822
6823#ifndef NO_WOLFSSL_SERVER
6824/* The server accepting a connection from a client.
6825 * The protocol version is expecting to be TLS v1.3.
6826 * If the client downgrades, and older versions of the protocol are compiled
6827 * in, the server will fallback to wolfSSL_accept().
6828 * Please see note at top of README if you get an error from accept.
6829 *
6830 * ssl The SSL/TLS object.
6831 * returns WOLFSSL_SUCCESS on successful handshake, WOLFSSL_FATAL_ERROR when
6832 * unrecoverable error occurs and 0 otherwise.
6833 * For more error information use wolfSSL_get_error().
6834 */
6835int wolfSSL_accept_TLSv13(WOLFSSL* ssl)
6836{
6837 word16 havePSK = 0;
6838 word16 haveAnon = 0;
6839 WOLFSSL_ENTER("SSL_accept_TLSv13()");
6840
6841#ifdef HAVE_ERRNO_H
6842 errno = 0;
6843#endif
6844
6845#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
6846 havePSK = ssl->options.havePSK;
6847#endif
6848 (void)havePSK;
6849
6850#ifdef HAVE_ANON
6851 haveAnon = ssl->options.haveAnon;
6852#endif
6853 (void)haveAnon;
6854
6855 if (ssl->options.side != WOLFSSL_SERVER_END) {
6856 WOLFSSL_ERROR(ssl->error = SIDE_ERROR);
6857 return WOLFSSL_FATAL_ERROR;
6858 }
6859
6860#ifndef NO_CERTS
6861 /* in case used set_accept_state after init */
6862 if (!havePSK && !haveAnon &&
6863 (!ssl->buffers.certificate ||
6864 !ssl->buffers.certificate->buffer ||
6865 !ssl->buffers.key ||
6866 !ssl->buffers.key->buffer)) {
6867 WOLFSSL_MSG("accept error: don't have server cert and key");
6868 ssl->error = NO_PRIVATE_KEY;
6869 WOLFSSL_ERROR(ssl->error);
6870 return WOLFSSL_FATAL_ERROR;
6871 }
6872#endif
6873
6874 if (ssl->buffers.outputBuffer.length > 0) {
6875 if ((ssl->error = SendBuffered(ssl)) == 0) {
6876 /* fragOffset is non-zero when sending fragments. On the last
6877 * fragment, fragOffset is zero again, and the state can be
6878 * advanced. */
6879 if (ssl->fragOffset == 0) {
6880 ssl->options.acceptState++;
6881 WOLFSSL_MSG("accept state: "
6882 "Advanced from last buffered fragment send");
6883 }
6884 else {
6885 WOLFSSL_MSG("accept state: "
6886 "Not advanced, more fragments to send");
6887 }
6888 }
6889 else {
6890 WOLFSSL_ERROR(ssl->error);
6891 return WOLFSSL_FATAL_ERROR;
6892 }
6893 }
6894
6895 switch (ssl->options.acceptState) {
6896
6897 case ACCEPT_BEGIN :
6898 /* get response */
6899 while (ssl->options.clientState < CLIENT_HELLO_COMPLETE)
6900 if ((ssl->error = ProcessReply(ssl)) < 0) {
6901 WOLFSSL_ERROR(ssl->error);
6902 return WOLFSSL_FATAL_ERROR;
6903 }
6904
6905 ssl->options.acceptState = ACCEPT_CLIENT_HELLO_DONE;
6906 WOLFSSL_MSG("accept state ACCEPT_CLIENT_HELLO_DONE");
6907 FALL_THROUGH;
6908
6909 case ACCEPT_CLIENT_HELLO_DONE :
6910 if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST) {
6911 if ((ssl->error = SendTls13HelloRetryRequest(ssl)) != 0) {
6912 WOLFSSL_ERROR(ssl->error);
6913 return WOLFSSL_FATAL_ERROR;
6914 }
6915 }
6916 ssl->options.acceptState = ACCEPT_HELLO_RETRY_REQUEST_DONE;
6917 WOLFSSL_MSG("accept state ACCEPT_HELLO_RETRY_REQUEST_DONE");
6918 FALL_THROUGH;
6919
6920 case ACCEPT_HELLO_RETRY_REQUEST_DONE :
6921 if (ssl->options.serverState == SERVER_HELLO_RETRY_REQUEST) {
6922 if ( (ssl->error = ProcessReply(ssl)) < 0) {
6923 WOLFSSL_ERROR(ssl->error);
6924 return WOLFSSL_FATAL_ERROR;
6925 }
6926 }
6927 ssl->options.acceptState = ACCEPT_FIRST_REPLY_DONE;
6928 WOLFSSL_MSG("accept state ACCEPT_FIRST_REPLY_DONE");
6929 FALL_THROUGH;
6930
6931 case ACCEPT_FIRST_REPLY_DONE :
6932 if ((ssl->error = SendTls13ServerHello(ssl)) != 0) {
6933 WOLFSSL_ERROR(ssl->error);
6934 return WOLFSSL_FATAL_ERROR;
6935 }
6936 ssl->options.acceptState = SERVER_HELLO_SENT;
6937 WOLFSSL_MSG("accept state SERVER_HELLO_SENT");
6938 FALL_THROUGH;
6939
6940 case SERVER_HELLO_SENT :
6941 if ((ssl->error = SendTls13EncryptedExtensions(ssl)) != 0) {
6942 WOLFSSL_ERROR(ssl->error);
6943 return WOLFSSL_FATAL_ERROR;
6944 }
6945 ssl->options.acceptState = SERVER_EXTENSIONS_SENT;
6946 WOLFSSL_MSG("accept state SERVER_EXTENSIONS_SENT");
6947 FALL_THROUGH;
6948
6949 case SERVER_EXTENSIONS_SENT :
6950#ifndef NO_CERTS
6951 if (!ssl->options.resuming) {
6952 if (ssl->options.verifyPeer) {
6953 ssl->error = SendTls13CertificateRequest(ssl, NULL, 0);
6954 if (ssl->error != 0) {
6955 WOLFSSL_ERROR(ssl->error);
6956 return WOLFSSL_FATAL_ERROR;
6957 }
6958 }
6959 }
6960#endif
6961 ssl->options.acceptState = CERT_REQ_SENT;
6962 WOLFSSL_MSG("accept state CERT_REQ_SENT");
6963 FALL_THROUGH;
6964
6965 case CERT_REQ_SENT :
6966 ssl->options.acceptState = KEY_EXCHANGE_SENT;
6967#ifndef NO_CERTS
6968 if (!ssl->options.resuming && ssl->options.sendVerify) {
6969 if ((ssl->error = SendTls13Certificate(ssl)) != 0) {
6970 WOLFSSL_ERROR(ssl->error);
6971 return WOLFSSL_FATAL_ERROR;
6972 }
6973 }
6974#endif
6975 ssl->options.acceptState = CERT_SENT;
6976 WOLFSSL_MSG("accept state CERT_SENT");
6977 FALL_THROUGH;
6978
6979 case CERT_SENT :
6980#ifndef NO_CERTS
6981 if (!ssl->options.resuming && ssl->options.sendVerify) {
6982 if ((ssl->error = SendTls13CertificateVerify(ssl)) != 0) {
6983 WOLFSSL_ERROR(ssl->error);
6984 return WOLFSSL_FATAL_ERROR;
6985 }
6986 }
6987#endif
6988 ssl->options.acceptState = CERT_STATUS_SENT;
6989 WOLFSSL_MSG("accept state CERT_STATUS_SENT");
6990 FALL_THROUGH;
6991
6992 case CERT_VERIFY_SENT :
6993 if ((ssl->error = SendTls13Finished(ssl)) != 0) {
6994 WOLFSSL_ERROR(ssl->error);
6995 return WOLFSSL_FATAL_ERROR;
6996 }
6997
6998 ssl->options.acceptState = ACCEPT_FINISHED_DONE;
6999 WOLFSSL_MSG("accept state ACCEPT_FINISHED_DONE");
7000#ifdef WOLFSSL_EARLY_DATA
7001 if (ssl->earlyData) {
7002 ssl->options.handShakeState = SERVER_FINISHED_COMPLETE;
7003 return WOLFSSL_SUCCESS;
7004 }
7005#endif
7006 FALL_THROUGH;
7007
7008 case ACCEPT_FINISHED_DONE :
7009#ifdef HAVE_SESSION_TICKET
7010 #ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
7011 if (!ssl->options.resuming && !ssl->options.verifyPeer &&
7012 !ssl->options.noTicketTls13 && ssl->ctx->ticketEncCb != NULL) {
7013 if ((ssl->error = SendTls13NewSessionTicket(ssl)) != 0) {
7014 WOLFSSL_ERROR(ssl->error);
7015 return WOLFSSL_FATAL_ERROR;
7016 }
7017 }
7018 #endif
7019#endif /* HAVE_SESSION_TICKET */
7020 ssl->options.acceptState = TICKET_SENT;
7021 WOLFSSL_MSG("accept state TICKET_SENT");
7022 FALL_THROUGH;
7023
7024 case TICKET_SENT:
7025 while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE)
7026 if ( (ssl->error = ProcessReply(ssl)) < 0) {
7027 WOLFSSL_ERROR(ssl->error);
7028 return WOLFSSL_FATAL_ERROR;
7029 }
7030
7031 ssl->options.acceptState = ACCEPT_SECOND_REPLY_DONE;
7032 WOLFSSL_MSG("accept state ACCEPT_SECOND_REPLY_DONE");
7033 FALL_THROUGH;
7034
7035 case ACCEPT_SECOND_REPLY_DONE :
7036#ifdef HAVE_SESSION_TICKET
7037 #ifdef WOLFSSL_TLS13_TICKET_BEFORE_FINISHED
7038 if (!ssl->options.verifyPeer) {
7039 }
7040 else
7041 #endif
7042 if (!ssl->options.resuming &&
7043 !ssl->options.noTicketTls13 && ssl->ctx->ticketEncCb != NULL) {
7044 if ((ssl->error = SendTls13NewSessionTicket(ssl)) != 0) {
7045 WOLFSSL_ERROR(ssl->error);
7046 return WOLFSSL_FATAL_ERROR;
7047 }
7048 }
7049#endif /* HAVE_SESSION_TICKET */
7050 ssl->options.acceptState = ACCEPT_THIRD_REPLY_DONE;
7051 WOLFSSL_MSG("accept state ACCEPT_THIRD_REPLY_DONE");
7052 FALL_THROUGH;
7053
7054 case ACCEPT_THIRD_REPLY_DONE:
7055#ifndef NO_HANDSHAKE_DONE_CB
7056 if (ssl->hsDoneCb) {
7057 int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
7058 if (cbret < 0) {
7059 ssl->error = cbret;
7060 WOLFSSL_MSG("HandShake Done Cb don't continue error");
7061 return WOLFSSL_FATAL_ERROR;
7062 }
7063 }
7064#endif /* NO_HANDSHAKE_DONE_CB */
7065
7066 WOLFSSL_LEAVE("SSL_accept()", WOLFSSL_SUCCESS);
7067 return WOLFSSL_SUCCESS;
7068
7069 default :
7070 WOLFSSL_MSG("Unknown accept state ERROR");
7071 return WOLFSSL_FATAL_ERROR;
7072 }
7073}
7074#endif
7075
7076#ifdef WOLFSSL_EARLY_DATA
7077/* Sets the maximum amount of early data that can be seen by server when using
7078 * session tickets for resumption.
7079 * A value of zero indicates no early data is to be sent by client using session
7080 * tickets.
7081 *
7082 * ctx The SSL/TLS CTX object.
7083 * sz Maximum size of the early data.
7084 * returns BAD_FUNC_ARG when ctx is NULL, SIDE_ERROR when not a server and
7085 * 0 on success.
7086 */
7087int wolfSSL_CTX_set_max_early_data(WOLFSSL_CTX* ctx, unsigned int sz)
7088{
7089 if (ctx == NULL || !IsAtLeastTLSv1_3(ctx->method->version))
7090 return BAD_FUNC_ARG;
7091 if (ctx->method->side == WOLFSSL_CLIENT_END)
7092 return SIDE_ERROR;
7093
7094 ctx->maxEarlyDataSz = sz;
7095
7096 return 0;
7097}
7098
7099/* Sets the maximum amount of early data that can be seen by server when using
7100 * session tickets for resumption.
7101 * A value of zero indicates no early data is to be sent by client using session
7102 * tickets.
7103 *
7104 * ssl The SSL/TLS object.
7105 * sz Maximum size of the early data.
7106 * returns BAD_FUNC_ARG when ssl is NULL, or not using TLS v1.3,
7107 * SIDE_ERROR when not a server and 0 on success.
7108 */
7109int wolfSSL_set_max_early_data(WOLFSSL* ssl, unsigned int sz)
7110{
7111 if (ssl == NULL || !IsAtLeastTLSv1_3(ssl->version))
7112 return BAD_FUNC_ARG;
7113 if (ssl->options.side == WOLFSSL_CLIENT_END)
7114 return SIDE_ERROR;
7115
7116 ssl->options.maxEarlyDataSz = sz;
7117
7118 return 0;
7119}
7120
7121/* Write early data to the server.
7122 *
7123 * ssl The SSL/TLS object.
7124 * data Early data to write
7125 * sz The size of the eary data in bytes.
7126 * outSz The number of early data bytes written.
7127 * returns BAD_FUNC_ARG when: ssl, data or outSz is NULL; sz is negative;
7128 * or not using TLS v1.3. SIDE ERROR when not a server. Otherwise the number of
7129 * early data bytes written.
7130 */
7131int wolfSSL_write_early_data(WOLFSSL* ssl, const void* data, int sz, int* outSz)
7132{
7133 int ret = 0;
7134
7135 WOLFSSL_ENTER("SSL_write_early_data()");
7136
7137 if (ssl == NULL || data == NULL || sz < 0 || outSz == NULL)
7138 return BAD_FUNC_ARG;
7139 if (!IsAtLeastTLSv1_3(ssl->version))
7140 return BAD_FUNC_ARG;
7141
7142 if (ssl->options.side == WOLFSSL_SERVER_END)
7143 return SIDE_ERROR;
7144
7145 if (ssl->options.handShakeState == NULL_STATE) {
7146 ssl->earlyData = 1;
7147 ret = wolfSSL_connect_TLSv13(ssl);
7148 if (ret <= 0)
7149 return WOLFSSL_FATAL_ERROR;
7150 }
7151 if (ssl->options.handShakeState == CLIENT_HELLO_COMPLETE) {
7152 ret = SendData(ssl, data, sz);
7153 if (ret > 0)
7154 *outSz = ret;
7155 }
7156
7157 WOLFSSL_LEAVE("SSL_write_early_data()", ret);
7158
7159 if (ret < 0)
7160 ret = WOLFSSL_FATAL_ERROR;
7161 return ret;
7162}
7163
7164/* Read the any early data from the client.
7165 *
7166 * ssl The SSL/TLS object.
7167 * data Buffer to put the early data into.
7168 * sz The size of the buffer in bytes.
7169 * outSz The number of early data bytes read.
7170 * returns BAD_FUNC_ARG when: ssl, data or outSz is NULL; sz is negative;
7171 * or not using TLS v1.3. SIDE ERROR when not a server. Otherwise the number of
7172 * early data bytes read.
7173 */
7174int wolfSSL_read_early_data(WOLFSSL* ssl, void* data, int sz, int* outSz)
7175{
7176 int ret;
7177
7178 WOLFSSL_ENTER("wolfSSL_read_early_data()");
7179
7180
7181 if (ssl == NULL || data == NULL || sz < 0 || outSz == NULL)
7182 return BAD_FUNC_ARG;
7183 if (!IsAtLeastTLSv1_3(ssl->version))
7184 return BAD_FUNC_ARG;
7185
7186 if (ssl->options.side == WOLFSSL_CLIENT_END)
7187 return SIDE_ERROR;
7188
7189 if (ssl->options.handShakeState == NULL_STATE) {
7190 ssl->earlyData = 1;
7191 ret = wolfSSL_accept_TLSv13(ssl);
7192 if (ret <= 0)
7193 return WOLFSSL_FATAL_ERROR;
7194 }
7195 if (ssl->options.handShakeState == SERVER_FINISHED_COMPLETE) {
7196 ret = ReceiveData(ssl, (byte*)data, sz, FALSE);
7197 if (ret > 0)
7198 *outSz = ret;
7199 if (ssl->error == ZERO_RETURN)
7200 ssl->error = WOLFSSL_ERROR_NONE;
7201 }
7202 else
7203 ret = 0;
7204
7205 WOLFSSL_LEAVE("wolfSSL_read_early_data()", ret);
7206
7207 if (ret < 0)
7208 ret = WOLFSSL_FATAL_ERROR;
7209 return ret;
7210}
7211#endif
7212
7213#undef ERROR_OUT
7214
7215#endif /* !WOLFCRYPT_ONLY */
7216
7217#endif /* WOLFSSL_TLS13 */
Note: See TracBrowser for help on using the repository browser.