tls_client.c
Go to the documentation of this file.
1 /**
2  * @file tls_client.c
3  * @brief Handshake message processing (TLS client)
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2010-2026 Oryx Embedded SARL. All rights reserved.
10  *
11  * This file is part of CycloneSSL Open.
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26  *
27  * @section Description
28  *
29  * The TLS protocol provides communications security over the Internet. The
30  * protocol allows client/server applications to communicate in a way that
31  * is designed to prevent eavesdropping, tampering, or message forgery
32  *
33  * @author Oryx Embedded SARL (www.oryx-embedded.com)
34  * @version 2.6.6
35  **/
36 
37 //Switch to the appropriate trace level
38 #define TRACE_LEVEL TLS_TRACE_LEVEL
39 
40 //Dependencies
41 #include "tls/tls.h"
42 #include "tls/tls_cipher_suites.h"
43 #include "tls/tls_handshake.h"
44 #include "tls/tls_client.h"
46 #include "tls/tls_client_misc.h"
47 #include "tls/tls_common.h"
48 #include "tls/tls_extensions.h"
49 #include "tls/tls_certificate.h"
50 #include "tls/tls_sign_misc.h"
51 #include "tls/tls_key_material.h"
53 #include "tls/tls_record.h"
54 #include "tls/tls_misc.h"
55 #include "tls13/tls13_client.h"
58 #include "dtls/dtls_record.h"
59 #include "dtls/dtls_misc.h"
60 #include "quic/tls_quic_misc.h"
61 #include "date_time.h"
62 #include "debug.h"
63 
64 //Check TLS library configuration
65 #if (TLS_SUPPORT == ENABLED && TLS_CLIENT_SUPPORT == ENABLED)
66 
67 
68 /**
69  * @brief Send ClientHello message
70  *
71  * When a client first connects to a server, it is required to send
72  * the ClientHello as its first message. The client can also send a
73  * ClientHello in response to a HelloRequest or on its own initiative
74  * in order to renegotiate the security parameters in an existing
75  * connection
76  *
77  * @param[in] context Pointer to the TLS context
78  * @return Error code
79  **/
80 
82 {
83  error_t error;
84  size_t length;
86 
87  //Point to the buffer where to format the message
88  message = (TlsClientHello *) (context->txBuffer + context->txBufferLen);
89 
90  //Initial or updated ClientHello?
91  if(context->state == TLS_STATE_CLIENT_HELLO)
92  {
93  //Generate the client random value using a cryptographically-safe
94  //pseudorandom number generator
95  error = tlsGenerateRandomValue(context, context->clientRandom);
96  }
97  else
98  {
99  //When responding to a HelloVerifyRequest or a HelloRetryRequest, the
100  //client must use the same random value as it did in the initial
101  //ClientHello
102  error = NO_ERROR;
103  }
104 
105 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
106  //Check status code
107  if(!error)
108  {
109  //In versions of TLS prior to TLS 1.3, the SessionTicket extension is used
110  //to resume a TLS session without requiring session-specific state at the
111  //TLS server
112  if(context->versionMin <= TLS_VERSION_1_2)
113  {
114  //Initial ClientHello?
115  if(context->state == TLS_STATE_CLIENT_HELLO)
116  {
117 #if (TLS_TICKET_SUPPORT == ENABLED)
118  //When presenting a ticket, the client may generate and include a
119  //session ID in the TLS ClientHello
120  if(tlsIsTicketValid(context) && context->sessionIdLen == 0)
121  {
122  //If the server accepts the ticket and the session ID is not
123  //empty, then it must respond with the same session ID present in
124  //the ClientHello. This allows the client to easily differentiate
125  //when the server is resuming a session from when it is falling
126  //back to a full handshake
127  error = tlsGenerateSessionId(context, 32);
128  }
129 #endif
130  }
131  }
132  }
133 #endif
134 
135 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
136  //Check status code
137  if(!error)
138  {
139  //TLS 1.3 supported by the client?
140  if(context->versionMax >= TLS_VERSION_1_3)
141  {
142  //Initial or updated ClientHello?
143  if(context->state == TLS_STATE_CLIENT_HELLO)
144  {
145 #if (TLS13_MIDDLEBOX_COMPAT_SUPPORT == ENABLED)
146  //In compatibility mode the session ID field must be non-empty
147  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_STREAM &&
148  context->sessionIdLen == 0)
149  {
150  //A client not offering a pre-TLS 1.3 session must generate a
151  //new 32-byte value. This value need not be random but should
152  //be unpredictable to avoid implementations fixating on a
153  //specific value (refer to RFC 8446, section 4.1.2)
154  error = tlsGenerateSessionId(context, 32);
155  }
156 #endif
157  //Check status code
158  if(!error)
159  {
160  //Any preferred ECDHE or FFDHE group?
161  if(tls13IsGroupSupported(context, context->preferredGroup))
162  {
163  //Pregenerate key share using preferred named group
164  error = tls13GenerateKeyShare(context, context->preferredGroup);
165  }
166  else
167  {
168  //Request group selection from the server, at the cost of an
169  //additional round trip
170  context->preferredGroup = TLS_GROUP_NONE;
171  }
172  }
173  }
174  else
175  {
176  //The updated ClientHello message is not encrypted
177  tlsFreeEncryptionEngine(&context->encryptionEngine[0]);
178  }
179  }
180 
181  //Save current time
182  context->clientHelloTimestamp = osGetSystemTime();
183  }
184 #endif
185 
186  //Check status code
187  if(!error)
188  {
189  //Format ClientHello message
190  error = tlsFormatClientHello(context, message, &length);
191  }
192 
193  //Check status code
194  if(!error)
195  {
196  //Debug message
197  TRACE_INFO("Sending ClientHello message (%" PRIuSIZE " bytes)...\r\n", length);
199 
200  //Send handshake message
201  error = tlsSendHandshakeMessage(context, message, length,
203  }
204 
205  //Check status code
206  if(error == NO_ERROR || error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
207  {
208  //Initial ClientHello?
209  if(context->state == TLS_STATE_CLIENT_HELLO)
210  {
211  //Wait for a ServerHello or HelloRetryRequest message
213  }
214  else
215  {
216  //Wait for a ServerHello message
218  }
219  }
220 
221  //Return status code
222  return error;
223 }
224 
225 
226 /**
227  * @brief Send ClientKeyExchange message
228  *
229  * This message is always sent by the client. It must immediately
230  * follow the client Certificate message, if it is sent. Otherwise,
231  * it must be the first message sent by the client after it receives
232  * the ServerHelloDone message
233  *
234  * @param[in] context Pointer to the TLS context
235  * @return Error code
236  **/
237 
239 {
240  error_t error;
241  size_t length;
243 
244  //Point to the buffer where to format the message
245  message = (TlsClientKeyExchange *) (context->txBuffer + context->txBufferLen);
246 
247  //Format ClientKeyExchange message
248  error = tlsFormatClientKeyExchange(context, message, &length);
249 
250  //Check status code
251  if(!error)
252  {
253  //Debug message
254  TRACE_INFO("Sending ClientKeyExchange message (%" PRIuSIZE " bytes)...\r\n", length);
256 
257  //Send handshake message
258  error = tlsSendHandshakeMessage(context, message, length,
260  }
261 
262  //Check status code
263  if(error == NO_ERROR || error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
264  {
265  //Derive session keys from the premaster secret
266  error = tlsGenerateSessionKeys(context);
267 
268  //Key material successfully generated?
269  if(!error)
270  {
271  //Send a CertificateVerify message to the server
273  }
274  }
275 
276  //Return status code
277  return error;
278 }
279 
280 
281 /**
282  * @brief Format ClientHello message
283  * @param[in] context Pointer to the TLS context
284  * @param[out] message Buffer where to format the ClientHello message
285  * @param[out] length Length of the resulting ClientHello message
286  * @return Error code
287  **/
288 
290  TlsClientHello *message, size_t *length)
291 {
292  error_t error;
293  size_t n;
294  uint8_t *p;
295  TlsExtensionList *extensionList;
296 
297  //In TLS 1.3, the client indicates its version preferences in the
298  //SupportedVersions extension and the legacy_version field must be set
299  //to 0x0303, which is the version number for TLS 1.2
300  context->clientVersion = MIN(context->versionMax, TLS_VERSION_1_2);
301 
302 #if (DTLS_SUPPORT == ENABLED)
303  //DTLS protocol?
304  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
305  {
306  //Translate TLS version into DTLS version
307  context->clientVersion = dtlsTranslateVersion(context->clientVersion);
308  }
309 #endif
310 
311  //In previous versions of TLS, the version field is used for version
312  //negotiation and represents the highest version number supported by the
313  //client
314  message->clientVersion = htons(context->clientVersion);
315 
316  //Client random value
317  osMemcpy(message->random, context->clientRandom, 32);
318 
319  //Point to the session ID
320  p = message->sessionId;
321  //Length of the handshake message
322  *length = sizeof(TlsClientHello);
323 
324  //The session ID value identifies a session the client wishes to reuse for
325  //this connection
326  error = tlsFormatSessionId(context, p, &n);
327  //Any error to report?
328  if(error)
329  return error;
330 
331  //Fix the length of the session ID
332  message->sessionIdLen = (uint8_t) n;
333 
334  //Point to the next field
335  p += n;
336  //Adjust the length of the message
337  *length += n;
338 
339 #if (DTLS_SUPPORT == ENABLED)
340  //DTLS protocol?
341  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
342  {
343  //Format Cookie field
344  error = dtlsFormatCookie(context, p, &n);
345  //Any error to report?
346  if(error)
347  return error;
348 
349  //Point to the next field
350  p += n;
351  //Adjust the length of the message
352  *length += n;
353  }
354 #endif
355 
356  //Format the list of cipher suites supported by the client
357  error = tlsFormatCipherSuites(context, p, &n);
358  //Any error to report?
359  if(error)
360  return error;
361 
362  //Point to the next field
363  p += n;
364  //Adjust the length of the message
365  *length += n;
366 
367  //Format the list of compression methods supported by the client
368  error = tlsFormatCompressMethods(context, p, &n);
369  //Any error to report?
370  if(error)
371  return error;
372 
373  //Point to the next field
374  p += n;
375  //Adjust the length of the message
376  *length += n;
377 
378  //Clients may request extended functionality from servers by sending
379  //data in the extensions field
380  extensionList = (TlsExtensionList *) p;
381  //Total length of the extension list
382  extensionList->length = 0;
383 
384  //Point to the first extension of the list
385  p += sizeof(TlsExtensionList);
386 
387  //In TLS 1.2, the client can indicate its version preferences in the
388  //SupportedVersions extension
389  error = tlsFormatClientSupportedVersionsExtension(context, p, &n);
390  //Any error to report?
391  if(error)
392  return error;
393 
394  //Fix the length of the extension list
395  extensionList->length += (uint16_t) n;
396  //Point to the next field
397  p += n;
398 
399 #if (TLS_SNI_SUPPORT == ENABLED)
400  //In order to provide the server name, clients may include a ServerName
401  //extension
402  error = tlsFormatClientSniExtension(context, p, &n);
403  //Any error to report?
404  if(error)
405  return error;
406 
407  //Fix the length of the extension list
408  extensionList->length += (uint16_t) n;
409  //Point to the next field
410  p += n;
411 #endif
412 
413 #if (TLS_MAX_FRAG_LEN_SUPPORT == ENABLED)
414  //In order to negotiate smaller maximum fragment lengths, clients may
415  //include a MaxFragmentLength extension
416  error = tlsFormatClientMaxFragLenExtension(context, p, &n);
417  //Any error to report?
418  if(error)
419  return error;
420 
421  //Fix the length of the extension list
422  extensionList->length += (uint16_t) n;
423  //Point to the next field
424  p += n;
425 #endif
426 
427 #if (TLS_RECORD_SIZE_LIMIT_SUPPORT == ENABLED)
428  //The value of RecordSizeLimit is the maximum size of record in octets
429  //that the endpoint is willing to receive
430  error = tlsFormatClientRecordSizeLimitExtension(context, p, &n);
431  //Any error to report?
432  if(error)
433  return error;
434 
435  //Fix the length of the extension list
436  extensionList->length += (uint16_t) n;
437  //Point to the next field
438  p += n;
439 #endif
440 
441  //A client that proposes ECC/FFDHE cipher suites in its ClientHello message
442  //should send the SupportedGroups extension
443  error = tlsFormatSupportedGroupsExtension(context, p, &n);
444  //Any error to report?
445  if(error)
446  return error;
447 
448  //Fix the length of the extension list
449  extensionList->length += (uint16_t) n;
450  //Point to the next field
451  p += n;
452 
453  //A client that proposes ECC cipher suites in its ClientHello message
454  //should send the EcPointFormats extension
455  error = tlsFormatClientEcPointFormatsExtension(context, p, &n);
456  //Any error to report?
457  if(error)
458  return error;
459 
460  //Fix the length of the extension list
461  extensionList->length += (uint16_t) n;
462  //Point to the next field
463  p += n;
464 
465  //Check whether the client supports certificate-based authentication
466  if((context->cipherSuiteTypes & TLS_CIPHER_SUITE_TYPE_RSA) != 0 ||
467  (context->cipherSuiteTypes & TLS_CIPHER_SUITE_TYPE_ECDSA) != 0 ||
468  (context->cipherSuiteTypes & TLS_CIPHER_SUITE_TYPE_DSA) != 0 ||
469  (context->cipherSuiteTypes & TLS_CIPHER_SUITE_TYPE_TLS13) != 0 ||
470  (context->cipherSuiteTypes & TLS_CIPHER_SUITE_TYPE_SM) != 0)
471  {
472  //Include the SignatureAlgorithms extension only if TLS 1.2 is supported
473  error = tlsFormatSignAlgosExtension(context, p, &n);
474  //Any error to report?
475  if(error)
476  return error;
477 
478  //Fix the length of the extension list
479  extensionList->length += (uint16_t) n;
480  //Point to the next field
481  p += n;
482 
483 #if (TLS_SIGN_ALGOS_CERT_SUPPORT == ENABLED)
484  //The SignatureAlgorithmsCert extension allows a client to indicate which
485  //signature algorithms it can validate in X.509 certificates
486  error = tlsFormatSignAlgosCertExtension(context, p, &n);
487  //Any error to report?
488  if(error)
489  return error;
490 
491  //Fix the length of the extension list
492  extensionList->length += (uint16_t) n;
493  //Point to the next field
494  p += n;
495 #endif
496  }
497 
498 #if (TLS_ALPN_SUPPORT == ENABLED)
499  //The ALPN extension contains the list of protocols advertised by the
500  //client, in descending order of preference
501  error = tlsFormatClientAlpnExtension(context, p, &n);
502  //Any error to report?
503  if(error)
504  return error;
505 
506  //Fix the length of the extension list
507  extensionList->length += (uint16_t) n;
508  //Point to the next field
509  p += n;
510 #endif
511 
512 #if (TLS_RAW_PUBLIC_KEY_SUPPORT == ENABLED)
513  //In order to indicate the support of raw public keys, clients include the
514  //ClientCertType extension in an extended ClientHello message
515  error = tlsFormatClientCertTypeListExtension(context, p, &n);
516  //Any error to report?
517  if(error)
518  return error;
519 
520  //Fix the length of the extension list
521  extensionList->length += (uint16_t) n;
522  //Point to the next field
523  p += n;
524 
525  //In order to indicate the support of raw public keys, clients include the
526  //ServerCertType extension in an extended ClientHello message
527  error = tlsFormatServerCertTypeListExtension(context, p, &n);
528  //Any error to report?
529  if(error)
530  return error;
531 
532  //Fix the length of the extension list
533  extensionList->length += (uint16_t) n;
534  //Point to the next field
535  p += n;
536 #endif
537 
538 #if (TLS_ENCRYPT_THEN_MAC_SUPPORT == ENABLED)
539  //On connecting, the client includes the EncryptThenMac extension in its
540  //ClientHello if it wishes to use encrypt-then-MAC rather than the default
541  //MAC-then-encrypt (refer to RFC 7366, section 2)
542  error = tlsFormatClientEtmExtension(context, p, &n);
543  //Any error to report?
544  if(error)
545  return error;
546 
547  //Fix the length of the extension list
548  extensionList->length += (uint16_t) n;
549  //Point to the next field
550  p += n;
551 #endif
552 
553 #if (TLS_EXT_MASTER_SECRET_SUPPORT == ENABLED)
554  //In all handshakes, a client implementing RFC 7627 must send the
555  //ExtendedMasterSecret extension in its ClientHello
556  error = tlsFormatClientEmsExtension(context, p, &n);
557  //Any error to report?
558  if(error)
559  return error;
560 
561  //Fix the length of the extension list
562  extensionList->length += (uint16_t) n;
563  //Point to the next field
564  p += n;
565 #endif
566 
567 #if (TLS_TRUSTED_CA_KEYS_SUPPORT == ENABLED)
568  //In order to indicate which CA root keys they possess, clients may include
569  //an extension of type "trusted_ca_keys" in the extended ClientHello message
570  //(refer to RFC 6066, section 6)
571  error = tlsFormatTrustedCaKeysExtension(context, p, &n);
572  //Any error to report?
573  if(error)
574  return error;
575 
576  //Fix the length of the extension list
577  extensionList->length += (uint16_t) n;
578  //Point to the next field
579  p += n;
580 #endif
581 
582 #if (TLS_TICKET_SUPPORT == ENABLED)
583  //The SessionTicket extension is used to resume a TLS session without
584  //requiring session-specific state at the TLS server
585  error = tlsFormatClientSessionTicketExtension(context, p, &n);
586  //Any error to report?
587  if(error)
588  return error;
589 
590  //Fix the length of the extension list
591  extensionList->length += (uint16_t) n;
592  //Point to the next field
593  p += n;
594 #endif
595 
596 #if (TLS_SECURE_RENEGOTIATION_SUPPORT == ENABLED)
597  //If the connection's secure_renegotiation flag is set to TRUE, the client
598  //must include a RenegotiationInfo extension in its ClientHello message
599  error = tlsFormatClientRenegoInfoExtension(context, p, &n);
600  //Any error to report?
601  if(error)
602  return error;
603 
604  //Fix the length of the extension list
605  extensionList->length += (uint16_t) n;
606  //Point to the next field
607  p += n;
608 #endif
609 
610 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
611  //TLS 1.3 supported by the client?
612  if(context->versionMax >= TLS_VERSION_1_3)
613  {
614  Tls13PskIdentityList *identityList;
615  Tls13PskBinderList *binderList;
616 
617  //Updated ClientHello?
618  if(context->state == TLS_STATE_CLIENT_HELLO_2 &&
619  context->version == TLS_VERSION_1_3)
620  {
621  //When sending the new ClientHello, the client must copy the contents
622  //of the Cookie extension received in the HelloRetryRequest into a
623  //Cookie extension in the new ClientHello
624  error = tls13FormatClientCookieExtension(context, p, &n);
625  //Any error to report?
626  if(error)
627  return error;
628 
629  //Fix the length of the extension list
630  extensionList->length += (uint16_t) n;
631  //Point to the next field
632  p += n;
633  }
634 
635  //The KeyShare extension contains the client's cryptographic parameters
636  error = tls13FormatClientKeyShareExtension(context, p, &n);
637  //Any error to report?
638  if(error)
639  return error;
640 
641  //Fix the length of the extension list
642  extensionList->length += (uint16_t) n;
643  //Point to the next field
644  p += n;
645 
646 #if (TLS13_EARLY_DATA_SUPPORT == ENABLED)
647  //If the client opts to send application data in its first flight of
648  //messages, it must supply both the PreSharedKey and EarlyData extensions
649  error = tls13FormatClientEarlyDataExtension(context, p, &n);
650  //Any error to report?
651  if(error)
652  return error;
653 
654  //Fix the length of the extension list
655  extensionList->length += (uint16_t) n;
656  //Point to the next field
657  p += n;
658 #endif
659 
660  //In order to use PSKs, clients must send a PskKeyExchangeModes extension
661  error = tls13FormatPskKeModesExtension(context, p, &n);
662  //Any error to report?
663  if(error)
664  return error;
665 
666  //Fix the length of the extension list
667  extensionList->length += (uint16_t) n;
668  //Point to the next field
669  p += n;
670 
671 #if (TLS_CERT_AUTHORITIES_SUPPORT == ENABLED)
672  //The CertificateAuthorities extension is used to indicate the CAs which
673  //an endpoint supports and which should be used by the receiving endpoint
674  //to guide certificate selection
675  error = tlsFormatCertAuthoritiesExtension(context, p, &n);
676  //Any error to report?
677  if(error)
678  return error;
679 
680  //Fix the length of the extension list
681  extensionList->length += (uint16_t) n;
682  //Point to the next field
683  p += n;
684 #endif
685 
686 #if (TLS_QUIC_SUPPORT == ENABLED)
687  //QUIC transport?
688  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_QUIC)
689  {
690  //QUIC transport parameters are carried in a TLS extension (refer to
691  //RFC 9001, section 8.2)
692  error = tlsFormatQuicTransportParamsExtension(context, p, &n);
693  //Any error to report?
694  if(error)
695  return error;
696 
697  //Fix the length of the extension list
698  extensionList->length += (uint16_t) n;
699  //Point to the next field
700  p += n;
701  }
702 #endif
703 
704 #if (TLS_CLIENT_HELLO_PADDING_SUPPORT == ENABLED)
705  //The first pass calculates the length of the PreSharedKey extension
706  error = tls13FormatClientPreSharedKeyExtension(context, p, &n,
707  &identityList, &binderList);
708  //Any error to report?
709  if(error)
710  return error;
711 
712  //Determine the length of the resulting message
713  n += *length + sizeof(TlsExtensionList) + extensionList->length;
714 
715  //Add a padding extension to ensure the ClientHello is never between
716  //256 and 511 bytes in length
717  error = tlsFormatClientHelloPaddingExtension(context, n, p, &n);
718  //Any error to report?
719  if(error)
720  return error;
721 
722  //Fix the length of the extension list
723  extensionList->length += (uint16_t) n;
724  //Point to the next field
725  p += n;
726 #endif
727 
728  //The extensions may appear in any order, with the exception of
729  //PreSharedKey which must be the last extension in the ClientHello
730  error = tls13FormatClientPreSharedKeyExtension(context, p, &n,
731  &identityList, &binderList);
732  //Any error to report?
733  if(error)
734  return error;
735 
736  //Fix the length of the extension list
737  extensionList->length += (uint16_t) n;
738  //Point to the next field
739  p += n;
740 
741  //Convert the length of the extension list to network byte order
742  extensionList->length = htons(extensionList->length);
743  //Total length of the message
744  *length += sizeof(TlsExtensionList) + htons(extensionList->length);
745 
746  //Fix PSK binder values in the PreSharedKey extension
747  error = tls13ComputePskBinders(context, message, *length, identityList,
748  binderList);
749  //Any error to report?
750  if(error)
751  return error;
752  }
753  else
754 #endif
755  {
756 #if (TLS_CLIENT_HELLO_PADDING_SUPPORT == ENABLED)
757  //Retrieve the actual length of the message
758  n = *length;
759 
760  //Any extensions included in the ClientHello message?
761  if(extensionList->length > 0)
762  {
763  n += sizeof(TlsExtensionList) + extensionList->length;
764  }
765 
766  //Add a padding extension to ensure the ClientHello is never between
767  //256 and 511 bytes in length
768  error = tlsFormatClientHelloPaddingExtension(context, n, p, &n);
769  //Any error to report?
770  if(error)
771  return error;
772 
773  //Fix the length of the extension list
774  extensionList->length += (uint16_t) n;
775  //Point to the next field
776  p += n;
777 #endif
778 
779  //Any extensions included in the ClientHello message?
780  if(extensionList->length > 0)
781  {
782  //Convert the length of the extension list to network byte order
783  extensionList->length = htons(extensionList->length);
784  //Total length of the message
785  *length += sizeof(TlsExtensionList) + htons(extensionList->length);
786  }
787  }
788 
789  //Successful processing
790  return NO_ERROR;
791 }
792 
793 
794 /**
795  * @brief Format ClientKeyExchange message
796  * @param[in] context Pointer to the TLS context
797  * @param[out] message Buffer where to format the ClientKeyExchange message
798  * @param[out] length Length of the resulting ClientKeyExchange message
799  * @return Error code
800  **/
801 
804 {
805  error_t error;
806  size_t n;
807  uint8_t *p;
808 
809  //Point to the beginning of the handshake message
810  p = message;
811  //Length of the handshake message
812  *length = 0;
813 
814 #if (TLS_PSK_KE_SUPPORT == ENABLED || TLS_RSA_PSK_KE_SUPPORT == ENABLED || \
815  TLS_DHE_PSK_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
816  //PSK key exchange method?
817  if(context->keyExchMethod == TLS_KEY_EXCH_PSK ||
818  context->keyExchMethod == TLS_KEY_EXCH_RSA_PSK ||
819  context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK ||
820  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
821  {
822  //The client indicates which key to use by including a PSK identity
823  //in the ClientKeyExchange message
824  error = tlsFormatPskIdentity(context, p, &n);
825  //Any error to report?
826  if(error)
827  return error;
828 
829  //Advance data pointer
830  p += n;
831  //Adjust the length of the message
832  *length += n;
833  }
834 #endif
835 
836  //RSA, Diffie-Hellman or ECDH key exchange method?
837  if(context->keyExchMethod != TLS_KEY_EXCH_PSK)
838  {
839  //Format client's key exchange parameters
840  error = tlsFormatClientKeyParams(context, p, &n);
841  //Any error to report?
842  if(error)
843  return error;
844 
845  //Advance data pointer
846  p += n;
847  //Adjust the length of the message
848  *length += n;
849  }
850 
851 #if (TLS_PSK_KE_SUPPORT == ENABLED || TLS_RSA_PSK_KE_SUPPORT == ENABLED || \
852  TLS_DHE_PSK_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
853  //PSK key exchange method?
854  if(context->keyExchMethod == TLS_KEY_EXCH_PSK ||
855  context->keyExchMethod == TLS_KEY_EXCH_RSA_PSK ||
856  context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK ||
857  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
858  {
859  //Invalid pre-shared key?
860  if(context->pskLen == 0)
862 
863  //Generate premaster secret
864  error = tlsGeneratePskPremasterSecret(context);
865  //Any error to report?
866  if(error)
867  return error;
868  }
869 #endif
870 
871  //Successful processing
872  return NO_ERROR;
873 }
874 
875 
876 /**
877  * @brief Parse HelloRequest message
878  *
879  * HelloRequest is a simple notification that the client should begin the
880  * negotiation process anew. In response, the client should send a ClientHello
881  * message when convenient
882  *
883  * @param[in] context Pointer to the TLS context
884  * @param[in] message Incoming HelloRequest message to parse
885  * @param[in] length Message length
886  * @return Error code
887  **/
888 
890  const TlsHelloRequest *message, size_t length)
891 {
892  error_t error;
893 
894  //Debug message
895  TRACE_INFO("HelloRequest message received (%" PRIuSIZE " bytes)...\r\n", length);
897 
898  //Check TLS version
899  if(context->version > TLS_VERSION_1_2)
901 
902  //The HelloRequest message does not contain any data
903  if(length != 0)
904  return ERROR_DECODING_FAILED;
905 
906  //Check current state
907  if(context->state == TLS_STATE_APPLICATION_DATA)
908  {
909 #if (TLS_SECURE_RENEGOTIATION_SUPPORT == ENABLED)
910  //Check whether the secure_renegotiation flag is set
911  if(context->secureRenegoEnabled && context->secureRenegoFlag)
912  {
913  //Release existing session ticket, if any
914  if(context->ticket != NULL)
915  {
916  osMemset(context->ticket, 0, context->ticketLen);
917  tlsFreeMem(context->ticket);
918  context->ticket = NULL;
919  context->ticketLen = 0;
920  }
921 
922 #if (DTLS_SUPPORT == ENABLED)
923  //Release cookie
924  if(context->cookie != NULL)
925  {
926  tlsFreeMem(context->cookie);
927  context->cookie = NULL;
928  context->cookieLen = 0;
929  }
930 #endif
931  //HelloRequest is a simple notification that the client should begin
932  //the negotiation process anew
934 
935  //Continue processing
936  error = NO_ERROR;
937  }
938  else
939 #endif
940  {
941  //If the connection's secure_renegotiation flag is set to FALSE, it
942  //is recommended that clients refuse this renegotiation request (refer
943  //to RFC 5746, section 4.2)
944  error = tlsSendAlert(context, TLS_ALERT_LEVEL_FATAL,
946  }
947  }
948  else
949  {
950  //The HelloRequest message can be sent at any time but it should be
951  //ignored by the client if it arrives in the middle of a handshake
952  error = NO_ERROR;
953  }
954 
955  //Return status code
956  return error;
957 }
958 
959 
960 /**
961  * @brief Parse ServerHello message
962  *
963  * The server will send this message in response to a ClientHello
964  * message when it was able to find an acceptable set of algorithms.
965  * If it cannot find such a match, it will respond with a handshake
966  * failure alert
967  *
968  * @param[in] context Pointer to the TLS context
969  * @param[in] message Incoming ServerHello message to parse
970  * @param[in] length Message length
971  * @return Error code
972  **/
973 
975  const TlsServerHello *message, size_t length)
976 {
977  error_t error;
978  uint16_t cipherSuite;
979  uint8_t compressMethod;
980  const uint8_t *p;
982 
983  //Debug message
984  TRACE_INFO("ServerHello message received (%" PRIuSIZE " bytes)...\r\n", length);
986 
987  //Check current state
988  if(context->state != TLS_STATE_SERVER_HELLO &&
989  context->state != TLS_STATE_SERVER_HELLO_2 &&
990  context->state != TLS_STATE_SERVER_HELLO_3)
991  {
992  //Report an error
994  }
995 
996  //Check the length of the ServerHello message
997  if(length < sizeof(TlsServerHello))
998  return ERROR_DECODING_FAILED;
999 
1000  //Point to the session ID
1001  p = message->sessionId;
1002  //Remaining bytes to process
1003  length -= sizeof(TlsServerHello);
1004 
1005  //Check the length of the session ID
1006  if(message->sessionIdLen > length)
1007  return ERROR_DECODING_FAILED;
1008  if(message->sessionIdLen > 32)
1009  return ERROR_DECODING_FAILED;
1010 
1011  //Point to the next field
1012  p += message->sessionIdLen;
1013  //Remaining bytes to process
1014  length -= message->sessionIdLen;
1015 
1016  //Malformed ServerHello message?
1017  if(length < sizeof(uint16_t))
1018  return ERROR_DECODING_FAILED;
1019 
1020  //Get the negotiated cipher suite
1021  cipherSuite = LOAD16BE(p);
1022  //Point to the next field
1023  p += sizeof(uint16_t);
1024  //Remaining bytes to process
1025  length -= sizeof(uint16_t);
1026 
1027  //Malformed ServerHello message?
1028  if(length < sizeof(uint8_t))
1029  return ERROR_DECODING_FAILED;
1030 
1031  //Get the negotiated compression method
1032  compressMethod = *p;
1033  //Point to the next field
1034  p += sizeof(uint8_t);
1035  //Remaining bytes to process
1036  length -= sizeof(uint8_t);
1037 
1038  //Server version
1039  TRACE_INFO(" serverVersion = 0x%04" PRIX16 " (%s)\r\n",
1040  ntohs(message->serverVersion),
1041  tlsGetVersionName(ntohs(message->serverVersion)));
1042 
1043  //Server random value
1044  TRACE_DEBUG(" random\r\n");
1045  TRACE_DEBUG_ARRAY(" ", message->random, 32);
1046 
1047  //Session identifier
1048  TRACE_DEBUG(" sessionId\r\n");
1049  TRACE_DEBUG_ARRAY(" ", message->sessionId, message->sessionIdLen);
1050 
1051  //Cipher suite identifier
1052  TRACE_INFO(" cipherSuite = 0x%04" PRIX16 " (%s)\r\n",
1054 
1055  //Compression method
1056  TRACE_DEBUG(" compressMethod = 0x%02" PRIX8 "\r\n", compressMethod);
1057 
1058  //The CRIME exploit takes advantage of TLS compression, so conservative
1059  //implementations do not accept compression at the TLS level
1060  if(compressMethod != TLS_COMPRESSION_METHOD_NULL)
1061  return ERROR_ILLEGAL_PARAMETER;
1062 
1063  //Parse the list of extensions offered by the server
1065  &extensions);
1066  //Any error to report?
1067  if(error)
1068  return error;
1069 
1070  //TLS protocol?
1071  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_STREAM ||
1072  context->transportProtocol == TLS_TRANSPORT_PROTOCOL_QUIC ||
1073  context->transportProtocol == TLS_TRANSPORT_PROTOCOL_EAP)
1074  {
1075  //Check whether the ServerHello message is received in response to the
1076  //initial ClientHello
1077  if(context->state != TLS_STATE_SERVER_HELLO_2)
1078  {
1079  //Release transcript hash context
1080  tlsFreeTranscriptHash(context);
1081 
1082  //Format initial ClientHello message
1083  error = tlsFormatInitialClientHello(context);
1084  //Any error to report?
1085  if(error)
1086  return error;
1087  }
1088  }
1089 
1090  //Select TLS version
1091  error = tlsSelectClientVersion(context, message, &extensions);
1092  //TLS version not supported?
1093  if(error)
1094  return error;
1095 
1096  //Check the list of extensions offered by the server
1097  error = tlsCheckHelloExtensions(TLS_TYPE_SERVER_HELLO, context->version,
1098  &extensions);
1099  //Any error to report?
1100  if(error)
1101  return error;
1102 
1103  //Save server random value
1104  osMemcpy(context->serverRandom, message->random, 32);
1105 
1106 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
1107  //TLS 1.0, TLS 1.1 or TLS 1.2 currently selected?
1108  if(context->version <= TLS_VERSION_1_2)
1109  {
1110  //Reset the named group to its default value
1111  context->namedGroup = TLS_GROUP_NONE;
1112 
1113  //Check whether the server has decided to resume a previous session
1114  error = tlsResumeSession(context, message->sessionId,
1115  message->sessionIdLen, cipherSuite);
1116  //Any error to report?
1117  if(error)
1118  return error;
1119 
1120  //Set cipher suite
1121  error = tlsSelectCipherSuite(context, cipherSuite);
1122  //Specified cipher suite not supported?
1123  if(error)
1124  return error;
1125 
1126  //Initialize handshake message hashing
1127  error = tlsInitTranscriptHash(context);
1128  //Any error to report?
1129  if(error)
1130  return error;
1131 
1132  //Save session identifier
1133  osMemcpy(context->sessionId, message->sessionId, message->sessionIdLen);
1134  context->sessionIdLen = message->sessionIdLen;
1135 
1136 #if (TLS_TICKET_SUPPORT == ENABLED)
1137  //Parse SessionTicket extension
1138  error = tlsParseServerSessionTicketExtension(context,
1139  extensions.sessionTicket);
1140  //Any error to report?
1141  if(error)
1142  return error;
1143 #endif
1144 
1145 #if (TLS_SECURE_RENEGOTIATION_SUPPORT == ENABLED)
1146  //Parse RenegotiationInfo extension
1147  error = tlsParseServerRenegoInfoExtension(context, &extensions);
1148  //Any error to report?
1149  if(error)
1150  return error;
1151 #endif
1152 
1153 #if (TLS_SNI_SUPPORT == ENABLED)
1154  //When the server includes a ServerName extension, the data field of
1155  //this extension may be empty
1156  error = tlsParseServerSniExtension(context, extensions.serverNameList);
1157  //Any error to report?
1158  if(error)
1159  return error;
1160 #endif
1161 
1162 #if (TLS_MAX_FRAG_LEN_SUPPORT == ENABLED)
1163  //Servers that receive an ClientHello containing a MaxFragmentLength
1164  //extension may accept the requested maximum fragment length by including
1165  //an extension of type MaxFragmentLength in the ServerHello
1166  error = tlsParseServerMaxFragLenExtension(context, extensions.maxFragLen);
1167  //Any error to report?
1168  if(error)
1169  return error;
1170 #endif
1171 
1172 #if (TLS_RECORD_SIZE_LIMIT_SUPPORT == ENABLED)
1173  //The value of RecordSizeLimit is the maximum size of record in octets
1174  //that the peer is willing to receive
1176  extensions.recordSizeLimit);
1177  //Any error to report?
1178  if(error)
1179  return error;
1180 #endif
1181 
1182 #if (TLS_ECDH_ANON_KE_SUPPORT == ENABLED || TLS_ECDHE_RSA_KE_SUPPORT == ENABLED || \
1183  TLS_ECDHE_ECDSA_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
1184  //A server that selects an ECC cipher suite in response to a ClientHello
1185  //message including an EcPointFormats extension appends this extension
1186  //to its ServerHello message
1187  error = tlsParseServerEcPointFormatsExtension(context,
1188  extensions.ecPointFormatList);
1189  //Any error to report?
1190  if(error)
1191  return error;
1192 #endif
1193 
1194 #if (TLS_ALPN_SUPPORT == ENABLED)
1195  //Parse ALPN extension
1196  error = tlsParseServerAlpnExtension(context, extensions.protocolNameList);
1197  //Any error to report?
1198  if(error)
1199  return error;
1200 #endif
1201 
1202 #if (TLS_RAW_PUBLIC_KEY_SUPPORT == ENABLED)
1203  //Parse ClientCertType extension
1204  error = tlsParseClientCertTypeExtension(context, extensions.clientCertType);
1205  //Any error to report?
1206  if(error)
1207  return error;
1208 
1209  //Parse ServerCertType extension
1210  error = tlsParseServerCertTypeExtension(context, extensions.serverCertType);
1211  //Any error to report?
1212  if(error)
1213  return error;
1214 #endif
1215 
1216 #if (TLS_ENCRYPT_THEN_MAC_SUPPORT == ENABLED)
1217  //Parse EncryptThenMac extension
1218  error = tlsParseServerEtmExtension(context, extensions.encryptThenMac);
1219  //Any error to report?
1220  if(error)
1221  return error;
1222 #endif
1223 
1224 #if (TLS_EXT_MASTER_SECRET_SUPPORT == ENABLED)
1225  //Parse ExtendedMasterSecret extension
1226  error = tlsParseServerEmsExtension(context, extensions.extendedMasterSecret);
1227  //Any error to report?
1228  if(error)
1229  return error;
1230 #endif
1231 
1232 #if (TLS_SESSION_RESUME_SUPPORT == ENABLED)
1233  //Use abbreviated handshake?
1234  if(context->resume)
1235  {
1236  //Derive session keys from the master secret
1237  error = tlsGenerateSessionKeys(context);
1238  //Unable to generate key material?
1239  if(error)
1240  return error;
1241 
1242 #if (TLS_TICKET_SUPPORT == ENABLED)
1243  //The server uses the SessionTicket extension to indicate to the client
1244  //that it will send a new session ticket using the NewSessionTicket
1245  //handshake message
1246  if(context->sessionTicketExtReceived)
1247  {
1248  //Wait for a NewSessionTicket message from the server
1250  }
1251  else
1252 #endif
1253  {
1254  //At this point, both client and server must send ChangeCipherSpec
1255  //messages and proceed directly to Finished messages
1257  }
1258  }
1259  else
1260 #endif
1261  {
1262  //Perform a full handshake
1263  if(context->keyExchMethod == TLS_KEY_EXCH_PSK ||
1264  context->keyExchMethod == TLS_KEY_EXCH_DH_ANON ||
1265  context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK ||
1266  context->keyExchMethod == TLS_KEY_EXCH_ECDH_ANON ||
1267  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
1268  {
1269  //The Certificate message is omitted from the server's response
1271  }
1272  else
1273  {
1274  //The server is required to send a Certificate message
1276  }
1277  }
1278  }
1279  else
1280 #endif
1281 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
1282  //TLS 1.3 currently selected?
1283  if(context->version == TLS_VERSION_1_3)
1284  {
1285  //DTLS protocol?
1286  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
1287  {
1288  //DTLS 1.3 clients must abort the handshake with an illegal_parameter
1289  //alert if the legacy_session_id_echo field is not empty
1290  if(message->sessionIdLen != 0)
1291  return ERROR_ILLEGAL_PARAMETER;
1292  }
1293  else
1294  {
1295  //A client which receives a legacy_session_id_echo field that does not
1296  //match what it sent in the ClientHello must abort the handshake with
1297  //an illegal_parameter alert (RFC 8446, section 4.1.3)
1298  if(message->sessionIdLen != context->sessionIdLen ||
1299  osMemcmp(message->sessionId, context->sessionId,
1300  message->sessionIdLen))
1301  {
1302  return ERROR_ILLEGAL_PARAMETER;
1303  }
1304  }
1305 
1306  //Check whether the ServerHello message is received in response to the
1307  //initial or the updated ClientHello
1308  if(context->state != TLS_STATE_SERVER_HELLO_2)
1309  {
1310  //Set cipher suite
1311  error = tlsSelectCipherSuite(context, cipherSuite);
1312  //Specified cipher suite not supported?
1313  if(error)
1314  return error;
1315 
1316  //Initialize handshake message hashing
1317  error = tlsInitTranscriptHash(context);
1318  //Any error to report?
1319  if(error)
1320  return error;
1321  }
1322  else
1323  {
1324  //Clients must check that the cipher suite supplied in the ServerHello
1325  //is the same as that in the HelloRetryRequest and otherwise abort the
1326  //handshake with an illegal_parameter alert
1327  if(cipherSuite != context->cipherSuite.identifier)
1328  return ERROR_ILLEGAL_PARAMETER;
1329  }
1330 
1331  //If using (EC)DHE key establishment, servers offer exactly one
1332  //KeyShareEntry in the ServerHello
1333  error = tls13ParseServerKeyShareExtension(context,
1334  extensions.serverShare);
1335  //Any error to report?
1336  if(error)
1337  return error;
1338 
1339  //The PreSharedKey extension contains the selected PSK identity
1340  error = tls13ParseServerPreSharedKeyExtension(context,
1341  extensions.selectedIdentity);
1342  //Any error to report?
1343  if(error)
1344  return error;
1345 
1346  //In TLS 1.3, the cipher suite concept has been changed. The key exchange
1347  //mechanism is negotiated separately from the cipher suite
1348  if(context->keyExchMethod == TLS_KEY_EXCH_NONE)
1349  return ERROR_HANDSHAKE_FAILED;
1350 
1351 #if (TLS13_MIDDLEBOX_COMPAT_SUPPORT == ENABLED)
1352  //The middlebox compatibility mode improves the chance of successfully
1353  //connecting through middleboxes
1354  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_STREAM &&
1355  context->state == TLS_STATE_SERVER_HELLO)
1356  {
1357  //In middlebox compatibility mode, the client sends a dummy
1358  //ChangeCipherSpec record immediately before its second flight
1360  }
1361  else
1362 #endif
1363  {
1364  //All handshake messages after the ServerHello are now encrypted
1366  }
1367  }
1368  else
1369 #endif
1370  //Invalid TLS version?
1371  {
1372  //Just for sanity
1373  return ERROR_INVALID_VERSION;
1374  }
1375 
1376  //Successful processing
1377  return NO_ERROR;
1378 }
1379 
1380 
1381 /**
1382  * @brief Parse ServerKeyExchange message
1383  *
1384  * The ServerKeyExchange message is sent by the server only when the
1385  * server Certificate message does not contain enough data to allow
1386  * the client to exchange a premaster secret
1387  *
1388  * @param[in] context Pointer to the TLS context
1389  * @param[in] message Incoming ServerKeyExchange message to parse
1390  * @param[in] length Message length
1391  * @return Error code
1392  **/
1393 
1395  const TlsServerKeyExchange *message, size_t length)
1396 {
1397  error_t error;
1398  size_t n;
1399  size_t paramsLen;
1400  const uint8_t *p;
1401  const uint8_t *params;
1402 
1403  //Initialize variables
1404  params = NULL;
1405  paramsLen = 0;
1406 
1407  //Debug message
1408  TRACE_INFO("ServerKeyExchange message received (%" PRIuSIZE " bytes)...\r\n", length);
1410 
1411  //Check TLS version
1412  if(context->version > TLS_VERSION_1_2)
1413  return ERROR_UNEXPECTED_MESSAGE;
1414 
1415  //Check current state
1416  if(context->state != TLS_STATE_SERVER_KEY_EXCHANGE)
1417  return ERROR_UNEXPECTED_MESSAGE;
1418 
1419  //Point to the beginning of the handshake message
1420  p = message;
1421 
1422 #if (TLS_PSK_KE_SUPPORT == ENABLED || TLS_RSA_PSK_KE_SUPPORT == ENABLED || \
1423  TLS_DHE_PSK_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
1424  //PSK key exchange method?
1425  if(context->keyExchMethod == TLS_KEY_EXCH_PSK ||
1426  context->keyExchMethod == TLS_KEY_EXCH_RSA_PSK ||
1427  context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK ||
1428  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
1429  {
1430  //To help the client in selecting which identity to use, the server
1431  //can provide a PSK identity hint in the ServerKeyExchange message
1432  error = tlsParsePskIdentityHint(context, p, length, &n);
1433  //Any error to report?
1434  if(error)
1435  return error;
1436 
1437  //Point to the next field
1438  p += n;
1439  //Remaining bytes to process
1440  length -= n;
1441  }
1442 #endif
1443 
1444  //Diffie-Hellman or ECDH key exchange method?
1445  if(context->keyExchMethod == TLS_KEY_EXCH_DH_ANON ||
1446  context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
1447  context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS ||
1448  context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK ||
1449  context->keyExchMethod == TLS_KEY_EXCH_ECDH_ANON ||
1450  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
1451  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA ||
1452  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
1453  {
1454  //Point to the server's key exchange parameters
1455  params = p;
1456 
1457  //Parse server's key exchange parameters
1458  error = tlsParseServerKeyParams(context, p, length, &paramsLen);
1459  //Any error to report?
1460  if(error)
1461  return error;
1462 
1463  //Point to the next field
1464  p += paramsLen;
1465  //Remaining bytes to process
1466  length -= paramsLen;
1467  }
1468 
1469  //For non-anonymous Diffie-Hellman and ECDH key exchanges, the signature
1470  //over the server's key exchange parameters shall be verified
1471  if(context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
1472  context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS ||
1473  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
1474  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA)
1475  {
1476 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_1)
1477  //TLS 1.0 or TLS 1.1 currently selected?
1478  if(context->version <= TLS_VERSION_1_1)
1479  {
1480  //Signature verification
1481  error = tlsVerifyServerKeySignature(context,
1482  (TlsDigitalSignature *) p, length, params, paramsLen, &n);
1483  }
1484  else
1485 #endif
1486 #if (TLS_MAX_VERSION >= TLS_VERSION_1_2 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
1487  //TLS 1.2 currently selected?
1488  if(context->version == TLS_VERSION_1_2)
1489  {
1490  //Signature verification
1491  error = tls12VerifyServerKeySignature(context,
1492  (Tls12DigitalSignature *) p, length, params, paramsLen, &n);
1493  }
1494  else
1495 #endif
1496  {
1497  //Just for sanity
1498  (void) params;
1499  //Report an error
1500  error = ERROR_INVALID_VERSION;
1501  }
1502 
1503  //Any error to report?
1504  if(error)
1505  return error;
1506 
1507  //Point to the next field
1508  p += n;
1509  //Remaining bytes to process
1510  length -= n;
1511  }
1512 
1513  //If the amount of data in the message does not precisely match the format
1514  //of the ServerKeyExchange message, then send a fatal alert
1515  if(length != 0)
1516  return ERROR_DECODING_FAILED;
1517 
1518  //Anomynous server?
1519  if(context->keyExchMethod == TLS_KEY_EXCH_PSK ||
1520  context->keyExchMethod == TLS_KEY_EXCH_DH_ANON ||
1521  context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK ||
1522  context->keyExchMethod == TLS_KEY_EXCH_ECDH_ANON ||
1523  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
1524  {
1525  //An anonymous server cannot request client authentication
1527  }
1528  else
1529  {
1530  //A non-anonymous server can optionally request a certificate from
1531  //the client, if appropriate for the selected cipher suite
1533  }
1534 
1535  //Successful processing
1536  return NO_ERROR;
1537 }
1538 
1539 
1540 /**
1541  * @brief Parse CertificateRequest message
1542  *
1543  * A server can optionally request a certificate from the client, if
1544  * appropriate for the selected cipher suite. This message will
1545  * immediately follow the ServerKeyExchange message
1546  *
1547  * @param[in] context Pointer to the TLS context
1548  * @param[in] message Incoming CertificateRequest message to parse
1549  * @param[in] length Message length
1550  * @return Error code
1551  **/
1552 
1554  const TlsCertificateRequest *message, size_t length)
1555 {
1556  error_t error;
1557  uint_t i;
1558  uint_t j;
1559  size_t n;
1560  uint_t certTypesLen;
1561  bool_t acceptable;
1562  const uint8_t *p;
1563  const uint8_t *certTypes;
1564  const TlsCertAuthorities *certAuthorities;
1565  const TlsSignSchemeList *signAlgoList;
1566  const TlsSignSchemeList *certSignAlgoList;
1567 
1568  //Debug message
1569  TRACE_INFO("CertificateRequest message received (%" PRIuSIZE " bytes)...\r\n", length);
1571 
1572  //Check key exchange method
1573  if(context->keyExchMethod == TLS_KEY_EXCH_PSK ||
1574  context->keyExchMethod == TLS_KEY_EXCH_DH_ANON ||
1575  context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK ||
1576  context->keyExchMethod == TLS_KEY_EXCH_ECDH_ANON ||
1577  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
1578  {
1579  //It is a fatal handshake failure alert for an anonymous server to
1580  //request client authentication
1581  return ERROR_HANDSHAKE_FAILED;
1582  }
1583  else if(context->keyExchMethod == TLS_KEY_EXCH_RSA_PSK)
1584  {
1585  //If no PSK identity hint is provided by the server, then the
1586  //ServerKeyExchange message is omitted
1587  if(context->state != TLS_STATE_SERVER_KEY_EXCHANGE &&
1588  context->state != TLS_STATE_CERTIFICATE_REQUEST)
1589  {
1590  //Handshake failure
1591  return ERROR_UNEXPECTED_MESSAGE;
1592  }
1593  }
1594  else if(context->keyExchMethod == TLS13_KEY_EXCH_PSK ||
1595  context->keyExchMethod == TLS13_KEY_EXCH_PSK_DHE ||
1596  context->keyExchMethod == TLS13_KEY_EXCH_PSK_ECDHE ||
1597  context->keyExchMethod == TLS13_KEY_EXCH_PSK_HYBRID)
1598  {
1599  //Servers which are authenticating with a PSK must not send the
1600  //CertificateRequest message in the main handshake
1601  return ERROR_UNEXPECTED_MESSAGE;
1602  }
1603  else
1604  {
1605  //Check current state
1606  if(context->state != TLS_STATE_CERTIFICATE_REQUEST)
1607  return ERROR_UNEXPECTED_MESSAGE;
1608  }
1609 
1610  //The server requests a certificate from the client, so that connection
1611  //can be mutually authenticated
1612  context->clientCertRequested = TRUE;
1613 
1614  //Point to the beginning of the handshake message
1615  p = (uint8_t *) message;
1616 
1617 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
1618  //Version of TLS prior to TLS 1.3?
1619  if(context->version <= TLS_VERSION_1_2)
1620  {
1621  //Check the length of the ServerKeyExchange message
1622  if(length < sizeof(TlsCertificateRequest))
1623  return ERROR_DECODING_FAILED;
1624 
1625  //Remaining bytes to process
1626  length -= sizeof(TlsCertificateRequest);
1627 
1628  //Retrieve the length of the list
1629  n = message->certificateTypesLen;
1630  //Malformed CertificateRequest message?
1631  if(n > length)
1632  return ERROR_DECODING_FAILED;
1633 
1634  //Point to the list of supported certificate types
1635  certTypes = message->certificateTypes;
1636  certTypesLen = message->certificateTypesLen;
1637 
1638  //Point to the next field
1639  p += sizeof(TlsCertificateRequest) + n;
1640  //Remaining bytes to process
1641  length -= n;
1642 
1643  //TLS 1.2 currently selected?
1644  if(context->version == TLS_VERSION_1_2)
1645  {
1646  //Malformed CertificateRequest message?
1647  if(length < sizeof(TlsSignSchemeList))
1648  return ERROR_DECODING_FAILED;
1649 
1650  //Point to the list of the hash/signature algorithm pairs
1651  signAlgoList = (TlsSignSchemeList *) p;
1652  //Remaining bytes to process
1653  length -= sizeof(TlsSignSchemeList);
1654 
1655  //Retrieve the length of the list
1656  n = ntohs(signAlgoList->length);
1657  //Malformed CertificateRequest message?
1658  if(n > length)
1659  return ERROR_DECODING_FAILED;
1660 
1661  //The supported_signature_algorithms field cannot be empty (refer to
1662  //RFC 5246, section 7.4.4)
1663  if(n == 0)
1664  return ERROR_DECODING_FAILED;
1665  if((n % 2) != 0)
1666  return ERROR_DECODING_FAILED;
1667 
1668  //Point to the next field
1669  p += sizeof(TlsSignSchemeList) + n;
1670  //Remaining bytes to process
1671  length -= n;
1672  }
1673  else
1674  {
1675  //Implementations prior to TLS 1.2 do not include a list of supported
1676  //hash/signature algorithm pairs
1677  signAlgoList = NULL;
1678  }
1679 
1680  //List of signature algorithms that may appear in X.509 certificates
1681  certSignAlgoList = signAlgoList;
1682 
1683  //Malformed CertificateRequest message?
1684  if(length < sizeof(TlsCertAuthorities))
1685  return ERROR_DECODING_FAILED;
1686 
1687  //Point to the list of acceptable certificate authorities
1688  certAuthorities = (TlsCertAuthorities *) p;
1689  //Remaining bytes to process
1690  length -= sizeof(TlsCertAuthorities);
1691 
1692  //Retrieve the length of the list
1693  n = ntohs(certAuthorities->length);
1694  //Malformed CertificateRequest message?
1695  if(n != length)
1696  return ERROR_DECODING_FAILED;
1697  }
1698  else
1699 #endif
1700 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
1701  //TLS 1.3 currently selected?
1702  if(context->version == TLS_VERSION_1_3)
1703  {
1705  const Tls13CertRequestContext *certRequestContext;
1706 
1707  //Unused parameters
1708  certTypes = NULL;
1709  certTypesLen = 0;
1710 
1711  //Malformed CertificateRequest message?
1712  if(length < sizeof(Tls13CertRequestContext))
1713  return ERROR_DECODING_FAILED;
1714 
1715  //Point to the certificate_request_context field
1716  certRequestContext = (Tls13CertRequestContext *) p;
1717  //Remaining bytes to process
1718  length -= sizeof(Tls13CertRequestContext);
1719 
1720  //Retrieve the length of the field
1721  n = certRequestContext->length;
1722  //Malformed CertificateRequest message?
1723  if(n > length)
1724  return ERROR_DECODING_FAILED;
1725 
1726  //The certificate_request_context field shall be zero length unless
1727  //used for the post-handshake authentication exchange
1728  if(certRequestContext->length != 0)
1729  return ERROR_ILLEGAL_PARAMETER;
1730 
1731  //Point to the next field
1732  p += sizeof(Tls13CertRequestContext) + n;
1733  //Remaining bytes to process
1734  length -= n;
1735 
1736  //The extensions describe the parameters of the certificate being
1737  //requested
1739  length, &extensions);
1740  //Any error to report?
1741  if(error)
1742  return error;
1743 
1744  //Check the list of extensions offered by the server
1746  context->version, &extensions);
1747  //Any error to report?
1748  if(error)
1749  return error;
1750 
1751  //The SignatureAlgorithms extension must be specified (refer to RFC 8446,
1752  //section 4.3.2)
1753  if(extensions.signAlgoList == NULL)
1754  return ERROR_MISSING_EXTENSION;
1755 
1756  //Point to the list of the hash/signature algorithm pairs that
1757  //the server is able to verify
1758  signAlgoList = extensions.signAlgoList;
1759 
1760  //If no SignatureAlgorithmsCert extension is present, then the
1761  //SignatureAlgorithms extension also applies to signatures appearing
1762  //in certificates (RFC 8446, section 4.2.3)
1763  if(extensions.certSignAlgoList != NULL)
1764  {
1765  certSignAlgoList = extensions.certSignAlgoList;
1766  }
1767  else
1768  {
1769  certSignAlgoList = extensions.signAlgoList;
1770  }
1771 
1772  //The CertificateAuthorities extension is used to indicate the CAs which
1773  //an endpoint supports and which should be used by the receiving endpoint
1774  //to guide certificate selection
1775  certAuthorities = extensions.certAuthorities;
1776  }
1777  else
1778 #endif
1779  //Invalid TLS version?
1780  {
1781  //Report an error
1782  return ERROR_INVALID_VERSION;
1783  }
1784 
1785  //No suitable certificate has been found for the moment
1786  context->cert = NULL;
1787  acceptable = FALSE;
1788 
1789  //Select the most appropriate certificate (2-pass process)
1790  for(i = 0; i < 2 && !acceptable; i++)
1791  {
1792  //Loop through the list of available certificates
1793  for(j = 0; j < TLS_MAX_CERTIFICATES && !acceptable; j++)
1794  {
1795  //Check whether the current certificate is suitable
1796  acceptable = tlsIsCertificateAcceptable(context, &context->certs[j],
1797  certTypes, certTypesLen, NULL, certSignAlgoList, certAuthorities);
1798 
1799  //TLS 1.2 and TLS 1.3 require additional examinations
1800  if(acceptable)
1801  {
1802  //The hash and signature algorithms used in the signature of the
1803  //CertificateVerify message must be one of those present in the
1804  //SupportedSignatureAlgorithms field
1805  error = tlsSelectSignAlgo(context, &context->certs[j],
1806  signAlgoList);
1807 
1808  //Check status code
1809  if(error)
1810  {
1811  acceptable = FALSE;
1812  }
1813  }
1814 
1815  //If all the requirements were met, the certificate can be used
1816  if(acceptable)
1817  {
1818  context->cert = &context->certs[j];
1819  }
1820  }
1821 
1822  //The second pass relaxes the constraints
1823  certSignAlgoList = NULL;
1824  certAuthorities = NULL;
1825  }
1826 
1827  //Version of TLS prior to TLS 1.3?
1828  if(context->version <= TLS_VERSION_1_2)
1829  {
1830  //Wait for a ServerHelloDone message
1832  }
1833  else
1834  {
1835  //Wait for a Certificate message
1837  }
1838 
1839  //Successful processing
1840  return NO_ERROR;
1841 }
1842 
1843 
1844 /**
1845  * @brief Parse ServerHelloDone message
1846  *
1847  * The ServerHelloDone message is sent by the server to indicate the
1848  * end of the ServerHello and associated messages. After sending this
1849  * message, the server will wait for a client response
1850  *
1851  * @param[in] context Pointer to the TLS context
1852  * @param[in] message Incoming ServerHelloDone message to parse
1853  * @param[in] length Message length
1854  * @return Error code
1855  **/
1856 
1858  const TlsServerHelloDone *message, size_t length)
1859 {
1860  //Debug message
1861  TRACE_INFO("ServerHelloDone message received (%" PRIuSIZE " bytes)...\r\n", length);
1863 
1864  //Check TLS version
1865  if(context->version > TLS_VERSION_1_2)
1866  return ERROR_UNEXPECTED_MESSAGE;
1867 
1868  //Check key exchange method
1869  if(context->keyExchMethod == TLS_KEY_EXCH_RSA ||
1870  context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
1871  context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS ||
1872  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
1873  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA)
1874  {
1875  //The server may omit the CertificateRequest message and go
1876  //directly to the ServerHelloDone message
1877  if(context->state != TLS_STATE_CERTIFICATE_REQUEST &&
1878  context->state != TLS_STATE_SERVER_HELLO_DONE)
1879  {
1880  //Handshake failure
1881  return ERROR_UNEXPECTED_MESSAGE;
1882  }
1883  }
1884  else if(context->keyExchMethod == TLS_KEY_EXCH_PSK)
1885  {
1886  //If no PSK identity hint is provided by the server, the
1887  //ServerKeyExchange message is omitted
1888  if(context->state != TLS_STATE_SERVER_KEY_EXCHANGE &&
1889  context->state != TLS_STATE_SERVER_HELLO_DONE)
1890  {
1891  //Handshake failure
1892  return ERROR_UNEXPECTED_MESSAGE;
1893  }
1894  }
1895  else if(context->keyExchMethod == TLS_KEY_EXCH_RSA_PSK)
1896  {
1897  //The server may omit the ServerKeyExchange message and/or
1898  //the CertificateRequest message
1899  if(context->state != TLS_STATE_SERVER_KEY_EXCHANGE &&
1900  context->state != TLS_STATE_CERTIFICATE_REQUEST &&
1901  context->state != TLS_STATE_SERVER_HELLO_DONE)
1902  {
1903  //Handshake failure
1904  return ERROR_UNEXPECTED_MESSAGE;
1905  }
1906  }
1907  else
1908  {
1909  //Check current state
1910  if(context->state != TLS_STATE_SERVER_HELLO_DONE)
1911  return ERROR_UNEXPECTED_MESSAGE;
1912  }
1913 
1914  //The ServerHelloDone message does not contain any data
1915  if(length != 0)
1916  return ERROR_DECODING_FAILED;
1917 
1918  //Another handshake message cannot be packed in the same record as the
1919  //ServerHelloDone
1920  if(context->rxBufferLen != 0)
1921  return ERROR_UNEXPECTED_MESSAGE;
1922 
1923  //The client must send a Certificate message if the server requests it
1925 
1926  //Successful processing
1927  return NO_ERROR;
1928 }
1929 
1930 
1931 /**
1932  * @brief Parse NewSessionTicket message
1933  *
1934  * This NewSessionTicket message is sent by the server during the TLS handshake
1935  * before the ChangeCipherSpec message
1936  *
1937  * @param[in] context Pointer to the TLS context
1938  * @param[in] message Incoming NewSessionTicket message to parse
1939  * @param[in] length Message length
1940  * @return Error code
1941  **/
1942 
1944  const TlsNewSessionTicket *message, size_t length)
1945 {
1946  size_t n;
1947 
1948  //Debug message
1949  TRACE_INFO("NewSessionTicket message received (%" PRIuSIZE " bytes)...\r\n", length);
1951 
1952  //Check TLS version
1953  if(context->version > TLS_VERSION_1_2)
1954  return ERROR_UNEXPECTED_MESSAGE;
1955 
1956  //Check current state
1957  if(context->state != TLS_STATE_NEW_SESSION_TICKET)
1958  return ERROR_UNEXPECTED_MESSAGE;
1959 
1960  //Check the length of the NewSessionTicket message
1961  if(length < sizeof(TlsNewSessionTicket))
1962  return ERROR_DECODING_FAILED;
1963 
1964  //Retrieve the length of the ticket
1965  n = ntohs(message->ticketLen);
1966 
1967  //Malformed NewSessionTicket message?
1968  if(length != (sizeof(TlsNewSessionTicket) + n))
1969  return ERROR_DECODING_FAILED;
1970 
1971 #if (TLS_TICKET_SUPPORT == ENABLED)
1972  //This message must not be sent if the server did not include a SessionTicket
1973  //extension in the ServerHello (refer to RFC 5077, section 3.3)
1974  if(!context->sessionTicketExtReceived)
1975  return ERROR_UNEXPECTED_MESSAGE;
1976 
1977  //Check the length of the session ticket
1978  if(n > 0 && n <= TLS_MAX_TICKET_SIZE)
1979  {
1980  //Release existing session ticket, if any
1981  if(context->ticket != NULL)
1982  {
1983  osMemset(context->ticket, 0, context->ticketLen);
1984  tlsFreeMem(context->ticket);
1985  context->ticket = NULL;
1986  context->ticketLen = 0;
1987  }
1988 
1989  //Allocate a memory block to hold the ticket
1990  context->ticket = tlsAllocMem(n);
1991  //Failed to allocate memory?
1992  if(context->ticket == NULL)
1993  return ERROR_OUT_OF_MEMORY;
1994 
1995  //Copy session ticket
1996  osMemcpy(context->ticket, message->ticket, n);
1997  context->ticketLen = n;
1998 
1999  //The lifetime is relative to when the ticket is received (refer to
2000  //RFC 5077, appendix A)
2001  context->ticketTimestamp = osGetSystemTime();
2002 
2003  //The ticket_lifetime_hint field contains a hint from the server about
2004  //how long the ticket should be stored. A ticket lifetime value of zero
2005  //indicates that the lifetime of the ticket is unspecified
2006  context->ticketLifetime = ntohl(message->ticketLifetimeHint);
2007 
2008  //If the client receives a session ticket from the server, then it
2009  //discards any session ID that was sent in the ServerHello (refer to
2010  //RFC 5077, section 3.4)
2011  context->sessionIdLen = 0;
2012  }
2013 #endif
2014 
2015  //The NewSessionTicket message is sent by the server during the TLS handshake
2016  //before the ChangeCipherSpec message
2018 
2019  //Successful processing
2020  return NO_ERROR;
2021 }
2022 
2023 #endif
@ TLS13_KEY_EXCH_PSK
Definition: tls.h:1247
error_t tlsParseHelloRequest(TlsContext *context, const TlsHelloRequest *message, size_t length)
Parse HelloRequest message.
Definition: tls_client.c:889
#define tlsAllocMem(size)
Definition: tls.h:911
#define htons(value)
Definition: cpu_endian.h:413
DTLS (Datagram Transport Layer Security)
Parsing and checking of TLS extensions.
@ TLS_CIPHER_SUITE_TYPE_RSA
TLS helper functions.
Date and time management.
uint8_t extensions[]
Definition: ntp_common.h:213
@ TLS_TRANSPORT_PROTOCOL_QUIC
Definition: tls.h:1040
Tls13PskBinderList
Definition: tls13_misc.h:275
int bool_t
Definition: compiler_port.h:63
TLS cipher suites.
uint16_t cipherSuite
Cipher suite identifier.
Definition: tls.h:2052
TlsDigitalSignature
Definition: tls.h:1886
@ TLS_ALERT_NO_RENEGOTIATION
Definition: tls.h:1192
@ ERROR_WOULD_BLOCK
Definition: error.h:96
void TlsServerHelloDone
ServerHelloDone message.
Definition: tls.h:1988
@ TLS13_KEY_EXCH_PSK_DHE
Definition: tls.h:1248
error_t tlsFormatClientSupportedVersionsExtension(TlsContext *context, uint8_t *p, size_t *written)
Format SupportedVersions extension.
error_t tlsGenerateSessionId(TlsContext *context, size_t length)
Generate a random session identifier.
Definition: tls_misc.c:268
Key material generation.
TLS handshake.
@ TLS_STATE_SERVER_KEY_EXCHANGE
Definition: tls.h:1596
error_t tlsGeneratePskPremasterSecret(TlsContext *context)
Premaster secret generation (for PSK cipher suites)
@ TLS_COMPRESSION_METHOD_NULL
Definition: tls.h:1213
error_t tlsFormatClientEcPointFormatsExtension(TlsContext *context, uint8_t *p, size_t *written)
Format EcPointFormats extension.
error_t tlsVerifyServerKeySignature(TlsContext *context, const TlsDigitalSignature *signature, size_t length, const uint8_t *params, size_t paramsLen, size_t *consumed)
Verify server's key exchange parameters signature (TLS 1.0 and TLS 1.1)
@ ERROR_ILLEGAL_PARAMETER
Definition: error.h:244
@ ERROR_UNEXPECTED_MESSAGE
Definition: error.h:195
error_t tlsFormatCipherSuites(TlsContext *context, uint8_t *p, size_t *written)
Format the list of cipher suites supported by the client.
QUIC helper functions.
uint8_t p
Definition: ndp.h:300
Helper functions for TLS client.
TlsCertificateRequest
Definition: tls.h:1981
uint8_t message[]
Definition: chap.h:154
#define TRUE
Definition: os_port.h:50
bool_t tlsIsCertificateAcceptable(TlsContext *context, const TlsCertDesc *cert, const uint8_t *certTypes, size_t numCertTypes, const TlsSupportedGroupList *curveList, const TlsSignSchemeList *certSignAlgoList, const TlsCertAuthorities *certAuthorities)
Check whether a certificate is acceptable.
@ TLS_STATE_CERTIFICATE_REQUEST
Definition: tls.h:1598
error_t tlsResumeSession(TlsContext *context, const uint8_t *sessionId, size_t sessionIdLen, uint16_t cipherSuite)
Resume TLS session via session ID.
error_t tlsFormatClientKeyExchange(TlsContext *context, TlsClientKeyExchange *message, size_t *length)
Format ClientKeyExchange message.
Definition: tls_client.c:802
error_t tls13ParseServerKeyShareExtension(TlsContext *context, const Tls13KeyShareEntry *serverShare)
Parse KeyShare extension (ServerHello message)
error_t tlsParseServerRecordSizeLimitExtension(TlsContext *context, const TlsExtension *recordSizeLimit)
Parse RecordSizeLimit extension.
@ TLS_TRANSPORT_PROTOCOL_DATAGRAM
Definition: tls.h:1039
error_t tlsFormatSignAlgosExtension(TlsContext *context, uint8_t *p, size_t *written)
Format SignatureAlgorithms extension.
@ TLS_STATE_APPLICATION_DATA
Definition: tls.h:1615
error_t tlsFormatClientSessionTicketExtension(TlsContext *context, uint8_t *p, size_t *written)
Format SessionTicket extension.
#define osMemcmp(p1, p2, length)
Definition: os_port.h:159
@ ERROR_HANDSHAKE_FAILED
Definition: error.h:234
@ ERROR_OUT_OF_MEMORY
Definition: error.h:63
error_t tlsFormatSessionId(TlsContext *context, uint8_t *p, size_t *written)
Format session ID.
error_t tlsParseServerSniExtension(TlsContext *context, const TlsServerNameList *serverNameList)
Parse SNI extension.
error_t tlsParseClientCertTypeExtension(TlsContext *context, const TlsExtension *clientCertType)
Parse ClientCertType extension.
@ ERROR_INVALID_VERSION
Definition: error.h:118
error_t tlsSendHandshakeMessage(TlsContext *context, const void *data, size_t length, TlsMessageType type)
Send handshake message.
@ TLS_CIPHER_SUITE_TYPE_TLS13
@ TLS13_KEY_EXCH_PSK_HYBRID
Definition: tls.h:1251
error_t tlsParsePskIdentityHint(TlsContext *context, const uint8_t *p, size_t length, size_t *consumed)
Parse PSK identity hint.
error_t tlsFormatSupportedGroupsExtension(TlsContext *context, uint8_t *p, size_t *written)
Format SupportedGroups extension.
error_t tlsFormatClientSniExtension(TlsContext *context, uint8_t *p, size_t *written)
Format SNI extension.
@ TLS_STATE_CLIENT_HELLO
Definition: tls.h:1585
@ TLS_CIPHER_SUITE_TYPE_SM
error_t tls13FormatClientEarlyDataExtension(TlsContext *context, uint8_t *p, size_t *written)
Format EarlyData extension.
@ TLS_KEY_EXCH_RSA
Definition: tls.h:1225
error_t tlsParseServerEtmExtension(TlsContext *context, const TlsExtension *encryptThenMac)
Parse EncryptThenMac extension.
@ TLS_CIPHER_SUITE_TYPE_ECDSA
TlsExtensionList
Definition: tls.h:1753
@ TLS_STATE_SERVER_HELLO
Definition: tls.h:1590
error_t tlsFormatTrustedCaKeysExtension(TlsContext *context, uint8_t *p, size_t *written)
Format TrustedCaKeys extension.
@ TLS_KEY_EXCH_ECDHE_ECDSA
Definition: tls.h:1234
@ TLS_KEY_EXCH_ECDHE_RSA
Definition: tls.h:1232
#define FALSE
Definition: os_port.h:46
@ TLS_KEY_EXCH_ECDH_ANON
Definition: tls.h:1235
error_t tlsSendAlert(TlsContext *context, uint8_t level, uint8_t description)
Send Alert message.
Definition: tls_common.c:512
error_t tlsParseServerMaxFragLenExtension(TlsContext *context, const TlsExtension *maxFragLen)
Parse MaxFragmentLength extension.
TlsCertAuthorities
Definition: tls.h:1708
#define osMemcpy(dest, src, length)
Definition: os_port.h:147
#define TlsContext
Definition: tls.h:36
error_t
Error codes.
Definition: error.h:43
error_t tlsParseServerCertTypeExtension(TlsContext *context, const TlsExtension *serverCertType)
Parse ServerCertType extension.
DTLS record layer.
error_t tlsSendClientKeyExchange(TlsContext *context)
Send ClientKeyExchange message.
Definition: tls_client.c:238
bool_t tls13IsGroupSupported(TlsContext *context, uint16_t namedGroup)
Check whether a given named group is supported.
Definition: tls13_misc.c:949
error_t tlsFormatClientRenegoInfoExtension(TlsContext *context, uint8_t *p, size_t *written)
Format RenegotiationInfo extension.
error_t tlsFormatClientEtmExtension(TlsContext *context, uint8_t *p, size_t *written)
Format EncryptThenMac extension.
void tlsFreeEncryptionEngine(TlsEncryptionEngine *encryptionEngine)
Release encryption engine.
Definition: tls_misc.c:1150
#define TLS_VERSION_1_2
Definition: tls.h:98
@ TLS_GROUP_NONE
Definition: tls.h:1494
@ TLS_KEY_EXCH_DH_ANON
Definition: tls.h:1230
error_t tlsSelectCipherSuite(TlsContext *context, uint16_t identifier)
Set cipher suite.
Definition: tls_misc.c:333
error_t tlsParseHelloExtensions(TlsMessageType msgType, const uint8_t *p, size_t length, TlsHelloExtensions *extensions)
Parse Hello extensions.
error_t tlsFormatQuicTransportParamsExtension(TlsContext *context, uint8_t *p, size_t *written)
Format QuicTransportParameters extension.
Definition: tls_quic_misc.c:57
error_t tlsParseServerSessionTicketExtension(TlsContext *context, const TlsExtension *sessionTicket)
Parse SessionTicket extension.
@ TLS_TYPE_CLIENT_HELLO
Definition: tls.h:1124
error_t tlsSelectClientVersion(TlsContext *context, const TlsServerHello *message, const TlsHelloExtensions *extensions)
Version selection.
Tls12DigitalSignature
Definition: tls.h:1898
Helper functions for TLS 1.3 client.
error_t tls13FormatClientKeyShareExtension(TlsContext *context, uint8_t *p, size_t *written)
Format KeyShare extension (ClientHello message)
@ ERROR_MISSING_EXTENSION
Definition: error.h:245
#define TLS_VERSION_1_3
Definition: tls.h:99
error_t tls13FormatClientCookieExtension(TlsContext *context, uint8_t *p, size_t *written)
Format Cookie extension.
@ TLS_TYPE_SERVER_HELLO
Definition: tls.h:1125
Handshake message processing (TLS client and server)
error_t tlsSelectSignAlgo(TlsContext *context, const TlsCertDesc *cert, const TlsSignSchemeList *signAlgoList)
Select the algorithm to be used when generating digital signatures.
Definition: tls_sign_misc.c:88
@ ERROR_INVALID_KEY_LENGTH
Definition: error.h:107
__weak_func error_t tls12VerifyServerKeySignature(TlsContext *context, const Tls12DigitalSignature *signature, size_t length, const uint8_t *params, size_t paramsLen, size_t *consumed)
Verify server's key exchange parameters signature (TLS 1.2)
error_t tlsFormatCertAuthoritiesExtension(TlsContext *context, uint8_t *p, size_t *written)
Format CertificateAuthorities extension.
Definition: tls_common.c:842
TLS record protocol.
@ TLS_STATE_CLIENT_CERTIFICATE_VERIFY
Definition: tls.h:1602
@ TLS_STATE_SERVER_CHANGE_CIPHER_SPEC
Definition: tls.h:1609
#define TLS_MAX_CERTIFICATES
Definition: tls.h:285
error_t tlsFormatClientAlpnExtension(TlsContext *context, uint8_t *p, size_t *written)
Format ALPN extension.
TlsSignSchemeList
Definition: tls.h:1686
@ TLS_TRANSPORT_PROTOCOL_EAP
Definition: tls.h:1041
@ TLS_STATE_SERVER_HELLO_3
Definition: tls.h:1592
error_t tlsParseServerEcPointFormatsExtension(TlsContext *context, const TlsEcPointFormatList *ecPointFormatList)
Parse EcPointFormats extension.
error_t tlsFormatInitialClientHello(TlsContext *context)
Format initial ClientHello message.
error_t tls13FormatClientPreSharedKeyExtension(TlsContext *context, uint8_t *p, size_t *written, Tls13PskIdentityList **identityList, Tls13PskBinderList **binderList)
Format PreSharedKey extension.
#define TRACE_INFO(...)
Definition: debug.h:105
uint8_t length
Definition: tcp.h:375
#define MIN(a, b)
Definition: os_port.h:63
@ TLS_TYPE_CLIENT_KEY_EXCHANGE
Definition: tls.h:1138
@ TLS_KEY_EXCH_DHE_PSK
Definition: tls.h:1238
@ TLS_STATE_NEW_SESSION_TICKET
Definition: tls.h:1607
uint16_t dtlsTranslateVersion(uint16_t version)
Translate TLS version into DTLS version.
Definition: dtls_misc.c:124
Hello extensions.
Definition: tls.h:2304
Transcript hash calculation.
@ TLS_STATE_HANDSHAKE_TRAFFIC_KEYS
Definition: tls.h:1593
@ TLS_KEY_EXCH_RSA_PSK
Definition: tls.h:1237
Formatting and parsing of extensions (TLS client)
#define ntohs(value)
Definition: cpu_endian.h:421
error_t tlsFormatClientHelloPaddingExtension(TlsContext *context, size_t clientHelloLen, uint8_t *p, size_t *written)
Format ClientHello Padding extension.
#define TRACE_DEBUG(...)
Definition: debug.h:119
error_t tls13ComputePskBinders(TlsContext *context, const void *clientHello, size_t clientHelloLen, const Tls13PskIdentityList *identityList, Tls13PskBinderList *binderList)
Compute PSK binder values.
@ ERROR_TIMEOUT
Definition: error.h:95
#define TLS_VERSION_1_1
Definition: tls.h:97
@ TLS_KEY_EXCH_NONE
Definition: tls.h:1224
__weak_func error_t tlsFormatClientKeyParams(TlsContext *context, uint8_t *p, size_t *written)
Format client's key exchange parameters.
@ TLS13_KEY_EXCH_PSK_ECDHE
Definition: tls.h:1249
@ TLS_STATE_CLIENT_HELLO_2
Definition: tls.h:1586
error_t tlsParseServerEmsExtension(TlsContext *context, const TlsExtension *extendedMasterSecret)
Parse ExtendedMasterSecret extension.
#define TRACE_DEBUG_ARRAY(p, a, n)
Definition: debug.h:120
const char_t * tlsGetCipherSuiteName(uint16_t identifier)
Convert cipher suite identifier to string representation.
TlsServerHello
Definition: tls.h:1956
void TlsClientKeyExchange
ClientKeyExchange message.
Definition: tls.h:1995
@ TLS_STATE_SERVER_CERTIFICATE
Definition: tls.h:1595
error_t tls13GenerateKeyShare(TlsContext *context, uint16_t namedGroup)
Key share generation.
Definition: tls13_misc.c:234
@ TLS_ALERT_LEVEL_FATAL
Definition: tls.h:1157
uint8_t n
error_t tls13ParseServerPreSharedKeyExtension(TlsContext *context, const TlsExtension *selectedIdentity)
Parse PreSharedKey extension.
void TlsHelloRequest
HelloRequest message.
Definition: tls.h:1930
@ TLS_STATE_CLIENT_CERTIFICATE
Definition: tls.h:1600
@ TLS_STATE_CLIENT_CHANGE_CIPHER_SPEC_2
Definition: tls.h:1604
error_t tlsFormatClientEmsExtension(TlsContext *context, uint8_t *p, size_t *written)
Format ExtendedMasterSecret extension.
@ TLS_KEY_EXCH_PSK
Definition: tls.h:1236
error_t tlsInitTranscriptHash(TlsContext *context)
Initialize handshake message hashing.
@ TLS_KEY_EXCH_ECDHE_PSK
Definition: tls.h:1239
error_t tls13FormatPskKeModesExtension(TlsContext *context, uint8_t *p, size_t *written)
Format PskKeyExchangeModes extension.
error_t tlsParseServerHelloDone(TlsContext *context, const TlsServerHelloDone *message, size_t length)
Parse ServerHelloDone message.
Definition: tls_client.c:1857
TlsClientHello
Definition: tls.h:1943
X.509 certificate handling.
Formatting and parsing of extensions (TLS 1.3 client)
Helper functions for signature generation and verification.
error_t tlsParseServerHello(TlsContext *context, const TlsServerHello *message, size_t length)
Parse ServerHello message.
Definition: tls_client.c:974
error_t tlsFormatClientCertTypeListExtension(TlsContext *context, uint8_t *p, size_t *written)
Format ClientCertType extension.
@ TLS_TYPE_CERTIFICATE_REQUEST
Definition: tls.h:1135
TLS (Transport Layer Security)
@ TLS_KEY_EXCH_DHE_DSS
Definition: tls.h:1229
error_t tlsParseCertificateRequest(TlsContext *context, const TlsCertificateRequest *message, size_t length)
Parse CertificateRequest message.
Definition: tls_client.c:1553
@ TLS_TRANSPORT_PROTOCOL_STREAM
Definition: tls.h:1038
error_t tlsCheckHelloExtensions(TlsMessageType msgType, uint16_t version, TlsHelloExtensions *extensions)
Check Hello extensions.
error_t tlsParseServerRenegoInfoExtension(TlsContext *context, const TlsHelloExtensions *extensions)
Parse RenegotiationInfo extension.
error_t tlsFormatClientRecordSizeLimitExtension(TlsContext *context, uint8_t *p, size_t *written)
Format RecordSizeLimit extension.
error_t tlsParseServerKeyParams(TlsContext *context, const uint8_t *p, size_t length, size_t *consumed)
Parse server's key exchange parameters.
Tls13CertRequestContext
Definition: tls13_misc.h:286
error_t tlsParseServerAlpnExtension(TlsContext *context, const TlsProtocolNameList *protocolNameList)
Parse ALPN extension.
error_t tlsSendClientHello(TlsContext *context)
Send ClientHello message.
Definition: tls_client.c:81
error_t tlsGenerateSessionKeys(TlsContext *context)
Generate session keys.
error_t tlsFormatSignAlgosCertExtension(TlsContext *context, uint8_t *p, size_t *written)
Format SignatureAlgorithmsCert extension.
const char_t * tlsGetVersionName(uint16_t version)
Convert TLS version to string representation.
Definition: tls_misc.c:1370
void tlsChangeState(TlsContext *context, TlsState newState)
Update TLS state.
Definition: tls_misc.c:54
error_t tlsFormatServerCertTypeListExtension(TlsContext *context, uint8_t *p, size_t *written)
Format ServerCertType extension.
@ ERROR_DECODING_FAILED
Definition: error.h:242
error_t tlsFormatPskIdentity(TlsContext *context, uint8_t *p, size_t *written)
Format PSK identity.
Tls13PskIdentityList
Definition: tls13_misc.h:253
#define PRIuSIZE
unsigned int uint_t
Definition: compiler_port.h:57
#define LOAD16BE(p)
Definition: cpu_endian.h:186
#define osMemset(p, value, length)
Definition: os_port.h:141
error_t tlsParseNewSessionTicket(TlsContext *context, const TlsNewSessionTicket *message, size_t length)
Parse NewSessionTicket message.
Definition: tls_client.c:1943
Handshake message processing (TLS client)
@ TLS_STATE_SERVER_HELLO_DONE
Definition: tls.h:1599
#define tlsFreeMem(p)
Definition: tls.h:916
@ TLS_STATE_SERVER_HELLO_2
Definition: tls.h:1591
error_t tlsGenerateRandomValue(TlsContext *context, uint8_t *random)
Generate client or server random value.
Definition: tls_misc.c:207
@ TLS_CIPHER_SUITE_TYPE_DSA
TlsNewSessionTicket
Definition: tls.h:2014
Handshake message processing (TLS 1.3 client)
error_t dtlsFormatCookie(TlsContext *context, uint8_t *p, size_t *written)
Format Cookie field.
Definition: dtls_misc.c:156
@ TLS_KEY_EXCH_DHE_RSA
Definition: tls.h:1227
error_t tlsParseServerKeyExchange(TlsContext *context, const TlsServerKeyExchange *message, size_t length)
Parse ServerKeyExchange message.
Definition: tls_client.c:1394
void TlsServerKeyExchange
ServerKeyExchange message.
Definition: tls.h:1970
#define ntohl(value)
Definition: cpu_endian.h:422
#define TLS_MAX_TICKET_SIZE
Definition: tls.h:173
@ NO_ERROR
Success.
Definition: error.h:44
Debugging facilities.
error_t tlsFormatClientHello(TlsContext *context, TlsClientHello *message, size_t *length)
Format ClientHello message.
Definition: tls_client.c:289
void tlsFreeTranscriptHash(TlsContext *context)
Release transcript hash context.
error_t tlsFormatCompressMethods(TlsContext *context, uint8_t *p, size_t *written)
Format the list of compression methods supported by the client.
bool_t tlsIsTicketValid(TlsContext *context)
Check whether a session ticket is valid.
error_t tlsFormatClientMaxFragLenExtension(TlsContext *context, uint8_t *p, size_t *written)
Format MaxFragmentLength extension.
systime_t osGetSystemTime(void)
Retrieve system time.