tls.c
Go to the documentation of this file.
1 /**
2  * @file tls.c
3  * @brief TLS (Transport Layer Security)
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.2
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_common.h"
45 #include "tls/tls_certificate.h"
46 #include "tls/tls_key_material.h"
48 #include "tls/tls_record.h"
49 #include "tls/tls_misc.h"
52 #include "tls13/tls13_ticket.h"
53 #include "dtls/dtls_record.h"
54 #include "dtls13/dtls13_misc.h"
55 #include "pkix/pem_import.h"
56 #include "pkix/x509_cert_parse.h"
57 #include "debug.h"
58 
59 //Check TLS library configuration
60 #if (TLS_SUPPORT == ENABLED)
61 
62 
63 /**
64  * @brief TLS context initialization
65  * @return Handle referencing the fully initialized TLS context
66  **/
67 
69 {
70  TlsContext *context;
71 
72  //Allocate a memory buffer to hold the TLS context
73  context = tlsAllocMem(sizeof(TlsContext));
74 
75  //Successful memory allocation?
76  if(context != NULL)
77  {
78  //Clear TLS context
79  osMemset(context, 0, sizeof(TlsContext));
80 
81  //Default state
82  context->state = TLS_STATE_INIT;
83  //Default transport protocol
84  context->transportProtocol = TLS_TRANSPORT_PROTOCOL_STREAM;
85  //Default operation mode
86  context->entity = TLS_CONNECTION_END_CLIENT;
87  //Default client authentication mode
88  context->clientAuthMode = TLS_CLIENT_AUTH_NONE;
89 
90  //Minimum and maximum versions accepted by the implementation
91  context->versionMin = TLS_MIN_VERSION;
92  context->versionMax = TLS_MAX_VERSION;
93 
94  //Default record layer version number
95  context->version = TLS_MIN_VERSION;
96  context->encryptionEngine[0].version = TLS_MIN_VERSION;
97 
98 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
99  //A TLS 1.3 client may pregenerate key shares
100  context->cipherSuiteTypes = TLS_CIPHER_SUITE_TYPE_TLS13 |
102 
103  //Select default named group
105  {
106  context->preferredGroup = TLS_GROUP_X25519;
107  }
108  else if(tls13IsGroupSupported(context, TLS_GROUP_SECP256R1))
109  {
110  context->preferredGroup = TLS_GROUP_SECP256R1;
111  }
112  else
113  {
114  context->preferredGroup = TLS_GROUP_NONE;
115  }
116 #endif
117 
118 #if (DTLS_SUPPORT == ENABLED)
119  //Default PMTU
120  context->pmtu = DTLS_DEFAULT_PMTU;
121  //Default timeout
122  context->timeout = INFINITE_DELAY;
123 #endif
124 
125 #if (DTLS_SUPPORT == ENABLED && DTLS_REPLAY_DETECTION_SUPPORT == ENABLED)
126  //Anti-replay mechanism is enabled by default
127  context->replayDetectionEnabled = TRUE;
128 #endif
129 
130 #if (TLS_QUIC_SUPPORT == ENABLED)
131  //Select initial encryption level
132  context->encryptionEngine[0].level = TLS_ENCRYPTION_LEVEL_INITIAL;
133  context->decryptionEngine[0].level = TLS_ENCRYPTION_LEVEL_INITIAL;
134 #endif
135 
136 #if (TLS_DH_SUPPORT == ENABLED)
137  //Initialize Diffie-Hellman context
138  dhInit(&context->dhContext);
139 #endif
140 
141 #if (TLS_ECDH_SUPPORT == ENABLED || TLS_HYBRID_SUPPORT == ENABLED)
142  //Initialize ECDH context
143  ecdhInit(&context->ecdhContext);
144 #endif
145 
146 #if (TLS_MLKEM_SUPPORT == ENABLED || TLS_HYBRID_SUPPORT == ENABLED)
147  //Initialize KEM context
148  kemInit(&context->kemContext, NULL);
149 #endif
150 
151 #if (TLS_RSA_SUPPORT == ENABLED)
152  //Initialize peer's RSA public key
153  rsaInitPublicKey(&context->peerRsaPublicKey);
154 #endif
155 
156 #if (TLS_DSA_SIGN_SUPPORT == ENABLED)
157  //Initialize peer's DSA public key
158  dsaInitPublicKey(&context->peerDsaPublicKey);
159 #endif
160 
161 #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED || TLS_SM2_SIGN_SUPPORT == ENABLED)
162  //Initialize peer's EC public key
163  ecInitPublicKey(&context->peerEcPublicKey);
164 #endif
165 
166 #if (TLS_ED25519_SIGN_SUPPORT == ENABLED || TLS_ED448_SIGN_SUPPORT == ENABLED)
167  //Initialize peer's EdDSA public key
168  eddsaInitPublicKey(&context->peerEddsaPublicKey);
169 #endif
170 
171  //Maximum number of plaintext data the TX and RX buffers can hold
172  context->txBufferMaxLen = TLS_MAX_RECORD_LENGTH;
173  context->rxBufferMaxLen = TLS_MAX_RECORD_LENGTH;
174 
175 #if (TLS_MAX_FRAG_LEN_SUPPORT == ENABLED)
176  //Maximum fragment length
177  context->maxFragLen = TLS_MAX_RECORD_LENGTH;
178 #endif
179 #if (TLS_RECORD_SIZE_LIMIT_SUPPORT == ENABLED)
180  //Maximum record size the peer is willing to receive
181  context->recordSizeLimit = TLS_MAX_RECORD_LENGTH;
182 #endif
183 
184 #if (DTLS_SUPPORT == ENABLED)
185  //Calculate the required size for the TX buffer
186  context->txBufferSize = context->txBufferMaxLen + sizeof(DtlsRecord) +
188 
189  //Calculate the required size for the RX buffer
190  context->rxBufferSize = context->rxBufferMaxLen + sizeof(DtlsRecord) +
192 #else
193  //Calculate the required size for the TX buffer
194  context->txBufferSize = context->txBufferMaxLen + sizeof(TlsRecord) +
196 
197  //Calculate the required size for the RX buffer
198  context->rxBufferSize = context->rxBufferMaxLen + sizeof(TlsRecord) +
200 #endif
201  }
202 
203  //Return a pointer to the freshly created TLS context
204  return context;
205 }
206 
207 
208 /**
209  * @brief Retrieve current TLS state
210  * @param[in] context Pointer to the TLS context
211  * @return Current TLS state
212  **/
213 
215 {
216  TlsState state;
217 
218  //Valid TLS context?
219  if(context != NULL)
220  {
221  state = context->state;
222  }
223  else
224  {
225  state = TLS_STATE_INIT;
226  }
227 
228  //Return current state
229  return state;
230 }
231 
232 
233 /**
234  * @brief Register TLS state change callback
235  * @param[in] context Pointer to the TLS context
236  * @param[in] stateChangeCallback TLS state change callback
237  * @return Error code
238  **/
239 
241  TlsStateChangeCallback stateChangeCallback)
242 {
243  //Check parameters
244  if(context == NULL || stateChangeCallback == NULL)
246 
247  //Save TLS state change callback
248  context->stateChangeCallback = stateChangeCallback;
249 
250  //Successful processing
251  return NO_ERROR;
252 }
253 
254 
255 /**
256  * @brief Set socket send and receive callbacks
257  * @param[in] context Pointer to the TLS context
258  * @param[in] socketSendCallback Send callback function
259  * @param[in] socketReceiveCallback Receive callback function
260  * @param[in] handle Socket handle
261  * @return Error code
262  **/
263 
265  TlsSocketSendCallback socketSendCallback,
266  TlsSocketReceiveCallback socketReceiveCallback, TlsSocketHandle handle)
267 {
268  //Invalid TLS context?
269  if(context == NULL)
271 
272  //Check parameters
273  if(socketSendCallback == NULL || socketReceiveCallback == NULL)
275 
276  //Save send and receive callback functions
277  context->socketSendCallback = socketSendCallback;
278  context->socketReceiveCallback = socketReceiveCallback;
279 
280  //This socket handle will be directly passed to the callback functions
281  context->socketHandle = handle;
282 
283  //Successful processing
284  return NO_ERROR;
285 }
286 
287 
288 /**
289  * @brief Set minimum and maximum versions permitted
290  * @param[in] context Pointer to the TLS context
291  * @param[in] versionMin Minimum version accepted by the TLS implementation
292  * @param[in] versionMax Maximum version accepted by the TLS implementation
293  * @return Error code
294  **/
295 
296 error_t tlsSetVersion(TlsContext *context, uint16_t versionMin,
297  uint16_t versionMax)
298 {
299  //Invalid TLS context?
300  if(context == NULL)
302 
303  //Check parameters
304  if(versionMin < TLS_VERSION_1_0 || versionMin > TLS_MAX_VERSION)
306 
307  if(versionMax > TLS_VERSION_1_3 || versionMax < TLS_MIN_VERSION)
309 
310  if(versionMin > versionMax)
312 
313  //Minimum version accepted by the implementation
314  context->versionMin = MAX(versionMin, TLS_MIN_VERSION);
315  //Maximum version accepted by the implementation
316  context->versionMax = MIN(versionMax, TLS_MAX_VERSION);
317 
318  //Default record layer version number
319  context->version = context->versionMin;
320  context->encryptionEngine[0].version = context->versionMin;
321 
322  //Successful processing
323  return NO_ERROR;
324 }
325 
326 
327 /**
328  * @brief Set the transport protocol to be used
329  * @param[in] context Pointer to the TLS context
330  * @param[in] transportProtocol Transport protocol to be used
331  * @return Error code
332  **/
333 
335  TlsTransportProtocol transportProtocol)
336 {
337  //Invalid TLS context?
338  if(context == NULL)
340 
341  //Check parameters
342  if(transportProtocol != TLS_TRANSPORT_PROTOCOL_STREAM &&
343  transportProtocol != TLS_TRANSPORT_PROTOCOL_DATAGRAM &&
344  transportProtocol != TLS_TRANSPORT_PROTOCOL_QUIC &&
345  transportProtocol != TLS_TRANSPORT_PROTOCOL_EAP)
346  {
348  }
349 
350  //Set transport protocol
351  context->transportProtocol = transportProtocol;
352 
353  //Successful processing
354  return NO_ERROR;
355 }
356 
357 
358 /**
359  * @brief Set operation mode (client or server)
360  * @param[in] context Pointer to the TLS context
361  * @param[in] entity Specifies whether this entity is considered a client or a server
362  * @return Error code
363  **/
364 
366 {
367  //Invalid TLS context?
368  if(context == NULL)
370 
371  //Check parameters
372  if(entity != TLS_CONNECTION_END_CLIENT && entity != TLS_CONNECTION_END_SERVER)
374 
375  //Check whether TLS operates as a client or a server
376  context->entity = entity;
377 
378  //Successful processing
379  return NO_ERROR;
380 }
381 
382 
383 /**
384  * @brief Set the pseudo-random number generator to be used
385  * @param[in] context Pointer to the TLS context
386  * @param[in] prngAlgo PRNG algorithm
387  * @param[in] prngContext Pointer to the PRNG context
388  * @return Error code
389  **/
390 
391 error_t tlsSetPrng(TlsContext *context, const PrngAlgo *prngAlgo,
392  void *prngContext)
393 {
394  //Invalid TLS context?
395  if(context == NULL)
397 
398  //Check parameters
399  if(prngAlgo == NULL || prngContext == NULL)
401 
402  //PRNG algorithm that will be used to generate random numbers
403  context->prngAlgo = prngAlgo;
404  //PRNG context
405  context->prngContext = prngContext;
406 
407  //Successful processing
408  return NO_ERROR;
409 }
410 
411 
412 /**
413  * @brief Set the server name
414  * @param[in] context Pointer to the TLS context
415  * @param[in] serverName Fully qualified domain name of the server
416  * @return Error code
417  **/
418 
419 error_t tlsSetServerName(TlsContext *context, const char_t *serverName)
420 {
421  size_t i;
422  size_t length;
423 
424  //Check parameters
425  if(context == NULL || serverName == NULL)
427 
428  //Retrieve the length of the server name
429  length = osStrlen(serverName);
430 
431  //Check whether the server name has already been configured
432  if(context->serverName != NULL)
433  {
434  //Release memory
435  tlsFreeMem(context->serverName);
436  context->serverName = NULL;
437  }
438 
439  //Valid server name?
440  if(length > 0)
441  {
442  //Allocate a memory block to hold the hostname
443  context->serverName = tlsAllocMem(length + 1);
444  //Failed to allocate memory?
445  if(context->serverName == NULL)
446  return ERROR_OUT_OF_MEMORY;
447 
448  //Convert the hostname into lowercase
449  for(i = 0; i < length; i++)
450  {
451  context->serverName[i] = osTolower(serverName[i]);
452  }
453 
454  //Properly terminate the string with a NULL character
455  context->serverName[length] = '\0';
456  }
457 
458  //Successful processing
459  return NO_ERROR;
460 }
461 
462 
463 /**
464  * @brief Get the server name
465  * @param[in] context Pointer to the TLS context
466  * @return Fully qualified domain name of the server
467  **/
468 
470 {
471  static const char_t defaultServerName[] = "";
472 
473  //Valid protocol name?
474  if(context != NULL && context->serverName != NULL)
475  {
476  //Return the fully qualified domain name of the server
477  return context->serverName;
478  }
479  else
480  {
481  //Return an empty string
482  return defaultServerName;
483  }
484 }
485 
486 
487 /**
488  * @brief Set session cache
489  * @param[in] context Pointer to the TLS context
490  * @param[in] cache Session cache that will be used to save/resume TLS sessions
491  * @return Error code
492  **/
493 
495 {
496  //Check parameters
497  if(context == NULL)
499 
500  //The cache will be used to save/resume TLS sessions
501  context->cache = cache;
502 
503  //Successful processing
504  return NO_ERROR;
505 }
506 
507 
508 /**
509  * @brief Set client authentication mode (for servers only)
510  * @param[in] context Pointer to the TLS context
511  * @param[in] mode Client authentication mode
512  * @return Error code
513  **/
514 
516 {
517  //Invalid TLS context?
518  if(context == NULL)
520 
521  //Save client authentication mode
522  context->clientAuthMode = mode;
523 
524  //Successful processing
525  return NO_ERROR;
526 }
527 
528 
529 /**
530  * @brief Set TLS buffer size
531  * @param[in] context Pointer to the TLS context
532  * @param[in] txBufferSize TX buffer size
533  * @param[in] rxBufferSize RX buffer size
534  * @return Error code
535  **/
536 
537 error_t tlsSetBufferSize(TlsContext *context, size_t txBufferSize,
538  size_t rxBufferSize)
539 {
540  //Invalid TLS context?
541  if(context == NULL)
543 
544  //Check parameters
545  if(txBufferSize < TLS_MIN_RECORD_LENGTH ||
546  rxBufferSize < TLS_MIN_RECORD_LENGTH)
547  {
549  }
550 
551  //Maximum number of plaintext data the TX and RX buffers can hold
552  context->txBufferMaxLen = txBufferSize;
553  context->rxBufferMaxLen = rxBufferSize;
554 
555 #if (DTLS_SUPPORT == ENABLED)
556  //Calculate the required size for the TX buffer
557  context->txBufferSize = txBufferSize + sizeof(DtlsRecord) +
559 
560  //Calculate the required size for the RX buffer
561  context->rxBufferSize = rxBufferSize + sizeof(DtlsRecord) +
563 #else
564  //Calculate the required size for the TX buffer
565  context->txBufferSize = txBufferSize + sizeof(TlsRecord) +
567 
568  //Calculate the required size for the RX buffer
569  context->rxBufferSize = rxBufferSize + sizeof(TlsRecord) +
571 #endif
572 
573  //Successful processing
574  return NO_ERROR;
575 }
576 
577 
578 /**
579  * @brief Set maximum fragment length
580  * @param[in] context Pointer to the TLS context
581  * @param[in] maxFragLen Maximum fragment length
582  * @return Error code
583  **/
584 
585 error_t tlsSetMaxFragmentLength(TlsContext *context, size_t maxFragLen)
586 {
587 #if (TLS_MAX_FRAG_LEN_SUPPORT == ENABLED)
588  //Invalid TLS context?
589  if(context == NULL)
591 
592  //Make sure the specified value is acceptable (ref to RFC 6066, section 4)
593  if(maxFragLen != 512 && maxFragLen != 1024 &&
594  maxFragLen != 2048 && maxFragLen != 4096 &&
595  maxFragLen != 16384)
596  {
598  }
599 
600  //Set maximum fragment length
601  context->maxFragLen = maxFragLen;
602 
603  //Successful processing
604  return NO_ERROR;
605 #else
606  //Not implemented
607  return ERROR_NOT_IMPLEMENTED;
608 #endif
609 }
610 
611 
612 /**
613  * @brief Specify the list of allowed cipher suites
614  * @param[in] context Pointer to the TLS context
615  * @param[in] cipherSuites List of allowed cipher suites (most preferred
616  * first). This parameter is taken as reference
617  * @param[in] length Number of cipher suites in the list
618  * @return Error code
619  **/
620 
621 error_t tlsSetCipherSuites(TlsContext *context, const uint16_t *cipherSuites,
622  uint_t length)
623 {
624  //Invalid TLS context?
625  if(context == NULL)
627 
628  //Check parameters
629  if(cipherSuites == NULL && length != 0)
631 
632  //Restrict the cipher suites that can be used
633  context->cipherSuites = cipherSuites;
634  context->numCipherSuites = length;
635 
636  //Successful processing
637  return NO_ERROR;
638 }
639 
640 
641 /**
642  * @brief Specify the list of allowed ECDHE and FFDHE groups
643  * @param[in] context Pointer to the TLS context
644  * @param[in] groups List of named groups (most preferred first). This
645  * parameter is taken as reference
646  * @param[in] length Number of named groups in the list
647  * @return Error code
648  **/
649 
650 error_t tlsSetSupportedGroups(TlsContext *context, const uint16_t *groups,
651  uint_t length)
652 {
653  //Invalid TLS context?
654  if(context == NULL)
656 
657  //Check parameters
658  if(groups == NULL && length != 0)
660 
661  //Restrict the named groups that can be used
662  context->supportedGroups = groups;
663  context->numSupportedGroups = length;
664 
665  //Successful processing
666  return NO_ERROR;
667 }
668 
669 
670 /**
671  * @brief Specify the preferred ECDHE or FFDHE group
672  * @param[in] context Pointer to the TLS context
673  * @param[in] group Preferred ECDHE or FFDHE named group
674  * @return Error code
675  **/
676 
677 error_t tlsSetPreferredGroup(TlsContext *context, uint16_t group)
678 {
679 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
680  //Invalid TLS context?
681  if(context == NULL)
683 
684  //Save the preferred named group
685  context->preferredGroup = group;
686 
687  //Successful processing
688  return NO_ERROR;
689 #else
690  //Not implemented
691  return ERROR_NOT_IMPLEMENTED;
692 #endif
693 }
694 
695 
696 /**
697  * @brief Specify the list of allowed signature algorithms
698  * @param[in] context Pointer to the TLS context
699  * @param[in] signAlgos List of signature algorithms (most preferred first). This
700  * parameter is taken as reference
701  * @param[in] length Number of signature algorithms in the list
702  * @return Error code
703  **/
704 
706  const uint16_t *signAlgos, uint_t length)
707 {
708 #if (TLS_MAX_VERSION >= TLS_VERSION_1_2 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
709  //Invalid TLS context?
710  if(context == NULL)
712 
713  //Check parameters
714  if(signAlgos == NULL && length != 0)
716 
717  //Restrict the signature algorithms that can be used
718  context->supportedSignAlgos = signAlgos;
719  context->numSupportedSignAlgos = length;
720 
721  //Successful processing
722  return NO_ERROR;
723 #else
724  //Not implemented
725  return ERROR_NOT_IMPLEMENTED;
726 #endif
727 }
728 
729 
730 /**
731  * @brief Import Diffie-Hellman parameters
732  * @param[in] context Pointer to the TLS context
733  * @param[in] params PEM structure that holds Diffie-Hellman parameters. This
734  * parameter is taken as reference
735  * @param[in] length Total length of the DER structure
736  * @return Error code
737  **/
738 
739 error_t tlsSetDhParameters(TlsContext *context, const char_t *params,
740  size_t length)
741 {
742 #if (TLS_DH_SUPPORT == ENABLED)
743  //Invalid TLS context?
744  if(context == NULL)
746 
747  //Check parameters
748  if(params == NULL && length != 0)
750 
751  //Decode the PEM structure that holds Diffie-Hellman parameters
752  return pemImportDhParameters(&context->dhContext.params, params, length);
753 #else
754  //Diffie-Hellman is not implemented
755  return ERROR_NOT_IMPLEMENTED;
756 #endif
757 }
758 
759 
760 /**
761  * @brief Register ECDH key agreement callback function
762  * @param[in] context Pointer to the TLS context
763  * @param[in] ecdhCallback ECDH callback function
764  * @return Error code
765  **/
766 
768 {
769 #if (TLS_ECC_CALLBACK_SUPPORT == ENABLED)
770  //Check parameters
771  if(context == NULL || ecdhCallback == NULL)
773 
774  //Save ECDH key agreement callback function
775  context->ecdhCallback = ecdhCallback;
776 
777  //Successful processing
778  return NO_ERROR;
779 #else
780  //PSK key exchange is not implemented
781  return ERROR_NOT_IMPLEMENTED;
782 #endif
783 }
784 
785 
786 /**
787  * @brief Register ECDSA signature generation callback function
788  * @param[in] context Pointer to the TLS context
789  * @param[in] ecdsaSignCallback ECDSA signature generation callback function
790  * @return Error code
791  **/
792 
794  TlsEcdsaSignCallback ecdsaSignCallback)
795 {
796 #if (TLS_ECC_CALLBACK_SUPPORT == ENABLED)
797  //Check parameters
798  if(context == NULL || ecdsaSignCallback == NULL)
800 
801  //Save ECDSA signature generation callback function
802  context->ecdsaSignCallback = ecdsaSignCallback;
803 
804  //Successful processing
805  return NO_ERROR;
806 #else
807  //PSK key exchange is not implemented
808  return ERROR_NOT_IMPLEMENTED;
809 #endif
810 }
811 
812 
813 /**
814  * @brief Register ECDSA signature verification callback function
815  * @param[in] context Pointer to the TLS context
816  * @param[in] ecdsaVerifyCallback ECDSA signature verification callback function
817  * @return Error code
818  **/
819 
821  TlsEcdsaVerifyCallback ecdsaVerifyCallback)
822 {
823 #if (TLS_ECC_CALLBACK_SUPPORT == ENABLED)
824  //Check parameters
825  if(context == NULL || ecdsaVerifyCallback == NULL)
827 
828  //Save ECDSA signature verification callback function
829  context->ecdsaVerifyCallback = ecdsaVerifyCallback;
830 
831  //Successful processing
832  return NO_ERROR;
833 #else
834  //PSK key exchange is not implemented
835  return ERROR_NOT_IMPLEMENTED;
836 #endif
837 }
838 
839 
840 /**
841  * @brief Register key logging callback function (for debugging purpose only)
842  * @param[in] context Pointer to the TLS context
843  * @param[in] keyLogCallback Key logging callback function
844  * @return Error code
845  **/
846 
848  TlsKeyLogCallback keyLogCallback)
849 {
850 #if (TLS_KEY_LOG_SUPPORT == ENABLED)
851  //Check parameters
852  if(context == NULL || keyLogCallback == NULL)
854 
855  //Save key logging callback function
856  context->keyLogCallback = keyLogCallback;
857 
858  //Successful processing
859  return NO_ERROR;
860 #else
861  //Key logging is not implemented
862  return ERROR_NOT_IMPLEMENTED;
863 #endif
864 }
865 
866 
867 /**
868  * @brief Allow unknown ALPN protocols
869  * @param[in] context Pointer to the TLS context
870  * @param[in] allowed Specifies whether unknown ALPN protocols are allowed
871  * @return Error code
872  **/
873 
875 {
876 #if (TLS_ALPN_SUPPORT == ENABLED)
877  //Invalid TLS context?
878  if(context == NULL)
880 
881  //Allow or disallow unknown ALPN protocols
882  context->unknownProtocolsAllowed = allowed;
883 
884  //Successful processing
885  return NO_ERROR;
886 #else
887  //ALPN is not implemented
888  return ERROR_NOT_IMPLEMENTED;
889 #endif
890 }
891 
892 
893 /**
894  * @brief Set the list of supported ALPN protocols
895  * @param[in] context Pointer to the TLS context
896  * @param[in] protocolList Comma-delimited list of supported protocols
897  * @return Error code
898  **/
899 
900 error_t tlsSetAlpnProtocolList(TlsContext *context, const char_t *protocolList)
901 {
902 #if (TLS_ALPN_SUPPORT == ENABLED)
903  size_t length;
904 
905  //Check parameters
906  if(context == NULL || protocolList == NULL)
908 
909  //Retrieve the length of the list
910  length = osStrlen(protocolList);
911 
912  //Check whether the list of supported protocols has already been configured
913  if(context->protocolList != NULL)
914  {
915  //Release memory
916  tlsFreeMem(context->protocolList);
917  context->protocolList = NULL;
918  }
919 
920  //Check whether the list of protocols is valid
921  if(length > 0)
922  {
923  //Allocate a memory block to hold the list
924  context->protocolList = tlsAllocMem(length + 1);
925  //Failed to allocate memory?
926  if(context->protocolList == NULL)
927  return ERROR_OUT_OF_MEMORY;
928 
929  //Save the list of supported protocols
930  osStrcpy(context->protocolList, protocolList);
931  }
932 
933  //Successful processing
934  return NO_ERROR;
935 #else
936  //ALPN is not implemented
937  return ERROR_NOT_IMPLEMENTED;
938 #endif
939 }
940 
941 
942 /**
943  * @brief Register ALPN callback function
944  * @param[in] context Pointer to the TLS context
945  * @param[in] alpnCallback ALPN callback function
946  * @return Error code
947  **/
948 
950 {
951 #if (TLS_ALPN_SUPPORT == ENABLED)
952  //Check parameters
953  if(context == NULL || alpnCallback == NULL)
955 
956  //Save ALPN callback function
957  context->alpnCallback = alpnCallback;
958 
959  //Successful processing
960  return NO_ERROR;
961 #else
962  //ALPN is not implemented
963  return ERROR_NOT_IMPLEMENTED;
964 #endif
965 }
966 
967 
968 /**
969  * @brief Get the name of the selected ALPN protocol
970  * @param[in] context Pointer to the TLS context
971  * @return Pointer to the protocol name
972  **/
973 
975 {
976  static const char_t defaultProtocolName[] = "";
977 
978 #if (TLS_ALPN_SUPPORT == ENABLED)
979  //Valid protocol name?
980  if(context != NULL && context->selectedProtocol != NULL)
981  {
982  //Return the name of the selected protocol
983  return context->selectedProtocol;
984  }
985  else
986 #endif
987  {
988  //Return an empty string
989  return defaultProtocolName;
990  }
991 }
992 
993 
994 /**
995  * @brief Set the pre-shared key to be used
996  * @param[in] context Pointer to the TLS context
997  * @param[in] psk Pointer to the pre-shared key
998  * @param[in] length Length of the pre-shared key, in bytes
999  * @return Error code
1000  **/
1001 
1002 error_t tlsSetPsk(TlsContext *context, const uint8_t *psk, size_t length)
1003 {
1004 #if (TLS_PSK_SUPPORT == ENABLED)
1005  //Invalid TLS context?
1006  if(context == NULL)
1007  return ERROR_INVALID_PARAMETER;
1008 
1009  //Check parameters
1010  if(psk == NULL && length != 0)
1011  return ERROR_INVALID_PARAMETER;
1012 
1013  //Check whether the pre-shared key has already been configured
1014  if(context->psk != NULL)
1015  {
1016  //Release memory
1017  osMemset(context->psk, 0, context->pskLen);
1018  tlsFreeMem(context->psk);
1019  context->psk = NULL;
1020  context->pskLen = 0;
1021  }
1022 
1023  //Valid PSK?
1024  if(length > 0)
1025  {
1026  //Allocate a memory block to hold the pre-shared key
1027  context->psk = tlsAllocMem(length);
1028  //Failed to allocate memory?
1029  if(context->psk == NULL)
1030  return ERROR_OUT_OF_MEMORY;
1031 
1032  //Save the pre-shared key
1033  osMemcpy(context->psk, psk, length);
1034  //Save the length of the key
1035  context->pskLen = length;
1036  }
1037 
1038 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
1039  //For externally established PSKs, the hash algorithm must be set when the
1040  //PSK is established, or default to SHA-256 if no such algorithm is defined
1041  context->pskHashAlgo = TLS_HASH_ALGO_SHA256;
1042 
1043  //The cipher suite must be provisioned along with the key
1044  context->pskCipherSuite = 0;
1045 #endif
1046 
1047  //Successful processing
1048  return NO_ERROR;
1049 #else
1050  //PSK key exchange is not implemented
1051  return ERROR_NOT_IMPLEMENTED;
1052 #endif
1053 }
1054 
1055 
1056 /**
1057  * @brief Set the PSK identity to be used by the client
1058  * @param[in] context Pointer to the TLS context
1059  * @param[in] pskIdentity NULL-terminated string that contains the PSK identity
1060  * @return Error code
1061  **/
1062 
1063 error_t tlsSetPskIdentity(TlsContext *context, const char_t *pskIdentity)
1064 {
1065 #if (TLS_PSK_SUPPORT == ENABLED)
1066  size_t length;
1067 
1068  //Check parameters
1069  if(context == NULL || pskIdentity == NULL)
1070  return ERROR_INVALID_PARAMETER;
1071 
1072  //Retrieve the length of the PSK identity
1073  length = osStrlen(pskIdentity);
1074 
1075  //Check whether the PSK identity has already been configured
1076  if(context->pskIdentity != NULL)
1077  {
1078  //Release memory
1079  tlsFreeMem(context->pskIdentity);
1080  context->pskIdentity = NULL;
1081  }
1082 
1083  //Valid PSK identity?
1084  if(length > 0)
1085  {
1086  //Allocate a memory block to hold the PSK identity
1087  context->pskIdentity = tlsAllocMem(length + 1);
1088  //Failed to allocate memory?
1089  if(context->pskIdentity == NULL)
1090  return ERROR_OUT_OF_MEMORY;
1091 
1092  //Save the PSK identity
1093  osStrcpy(context->pskIdentity, pskIdentity);
1094  }
1095 
1096  //Successful processing
1097  return NO_ERROR;
1098 #else
1099  //PSK key exchange is not implemented
1100  return ERROR_NOT_IMPLEMENTED;
1101 #endif
1102 }
1103 
1104 
1105 /**
1106  * @brief Set the PSK identity hint to be used by the server
1107  * @param[in] context Pointer to the TLS context
1108  * @param[in] pskIdentityHint NULL-terminated string that contains the PSK identity hint
1109  * @return Error code
1110  **/
1111 
1112 error_t tlsSetPskIdentityHint(TlsContext *context, const char_t *pskIdentityHint)
1113 {
1114 #if (TLS_PSK_SUPPORT == ENABLED)
1115  size_t length;
1116 
1117  //Check parameters
1118  if(context == NULL || pskIdentityHint == NULL)
1119  return ERROR_INVALID_PARAMETER;
1120 
1121  //Retrieve the length of the PSK identity hint
1122  length = osStrlen(pskIdentityHint);
1123 
1124  //Check whether the PSK identity hint has already been configured
1125  if(context->pskIdentityHint != NULL)
1126  {
1127  //Release memory
1128  tlsFreeMem(context->pskIdentityHint);
1129  context->pskIdentityHint = NULL;
1130  }
1131 
1132  //Valid PSK identity hint?
1133  if(length > 0)
1134  {
1135  //Allocate a memory block to hold the PSK identity hint
1136  context->pskIdentityHint = tlsAllocMem(length + 1);
1137  //Failed to allocate memory?
1138  if(context->pskIdentityHint == NULL)
1139  return ERROR_OUT_OF_MEMORY;
1140 
1141  //Save the PSK identity hint
1142  osStrcpy(context->pskIdentityHint, pskIdentityHint);
1143  }
1144 
1145  //Successful processing
1146  return NO_ERROR;
1147 #else
1148  //PSK key exchange is not implemented
1149  return ERROR_NOT_IMPLEMENTED;
1150 #endif
1151 }
1152 
1153 
1154 /**
1155  * @brief Register PSK callback function
1156  * @param[in] context Pointer to the TLS context
1157  * @param[in] pskCallback PSK callback function
1158  * @return Error code
1159  **/
1160 
1162 {
1163 #if (TLS_PSK_SUPPORT == ENABLED)
1164  //Check parameters
1165  if(context == NULL || pskCallback == NULL)
1166  return ERROR_INVALID_PARAMETER;
1167 
1168  //Save PSK callback function
1169  context->pskCallback = pskCallback;
1170 
1171  //Successful processing
1172  return NO_ERROR;
1173 #else
1174  //PSK key exchange is not implemented
1175  return ERROR_NOT_IMPLEMENTED;
1176 #endif
1177 }
1178 
1179 
1180 /**
1181  * @brief Register the raw public key verification callback function
1182  * @param[in] context Pointer to the TLS context
1183  * @param[in] rpkVerifyCallback RPK verification callback function
1184  * @return Error code
1185  **/
1186 
1188  TlsRpkVerifyCallback rpkVerifyCallback)
1189 {
1190 #if (TLS_RAW_PUBLIC_KEY_SUPPORT == ENABLED)
1191  //Check parameters
1192  if(context == NULL || rpkVerifyCallback == NULL)
1193  return ERROR_INVALID_PARAMETER;
1194 
1195  //Save raw public key verification callback function
1196  context->rpkVerifyCallback = rpkVerifyCallback;
1197 
1198  //Successful processing
1199  return NO_ERROR;
1200 #else
1201  //Raw public keys are not implemented
1202  return ERROR_NOT_IMPLEMENTED;
1203 #endif
1204 }
1205 
1206 
1207 /**
1208  * @brief Import a trusted CA list
1209  * @param[in] context Pointer to the TLS context
1210  * @param[in] trustedCaList List of trusted CA (PEM format)
1211  * @param[in] length Total length of the list
1212  * @return Error code
1213  **/
1214 
1215 error_t tlsSetTrustedCaList(TlsContext *context, const char_t *trustedCaList,
1216  size_t length)
1217 {
1218  //Invalid TLS context?
1219  if(context == NULL)
1220  return ERROR_INVALID_PARAMETER;
1221 
1222  //Check parameters
1223  if(trustedCaList == NULL && length != 0)
1224  return ERROR_INVALID_PARAMETER;
1225 
1226  //Save the list of trusted CA
1227  context->trustedCaList = trustedCaList;
1228  context->trustedCaListLen = length;
1229 
1230  //Successful processing
1231  return NO_ERROR;
1232 }
1233 
1234 
1235 /**
1236  * @brief Load entity's certificate
1237  * @param[in] context Pointer to the TLS context
1238  * @param[in] index Zero-based index identifying a slot
1239  * @param[in] certChain Certificate chain (PEM format). This parameter is
1240  * taken as reference
1241  * @param[in] certChainLen Length of the certificate chain
1242  * @param[in] privateKey Private key (PEM format). This parameter is taken
1243  * as reference
1244  * @param[in] privateKeyLen Length of the private key
1245  * @param[in] password NULL-terminated string containing the password. This
1246  * parameter is required if the private key is encrypted
1247  * @return Error code
1248  **/
1249 
1251  const char_t *certChain, size_t certChainLen, const char_t *privateKey,
1252  size_t privateKeyLen, const char_t *password)
1253 {
1254  error_t error;
1255  uint8_t *derCert;
1256  size_t derCertLen;
1257  X509CertInfo *certInfo;
1258  TlsCertDesc *cert;
1259  TlsCertificateType certType;
1260  TlsNamedGroup namedCurve;
1261  TlsSignatureScheme certSignScheme;
1262 
1263  //Make sure the TLS context is valid
1264  if(context == NULL)
1265  return ERROR_INVALID_PARAMETER;
1266 
1267  //The implementation limits the number of certificates that can be loaded
1268  if(index >= TLS_MAX_CERTIFICATES)
1269  return ERROR_INVALID_PARAMETER;
1270 
1271  //Check whether the certificate chain is valid
1272  if(certChain == NULL || certChainLen == 0)
1273  return ERROR_INVALID_PARAMETER;
1274 
1275  //The private key is optional
1276  if(privateKey == NULL && privateKeyLen != 0)
1277  return ERROR_INVALID_PARAMETER;
1278 
1279  //The password if required only for encrypted private keys
1280  if(password != NULL && osStrlen(password) > TLS_MAX_PASSWORD_LEN)
1281  return ERROR_INVALID_PASSWORD;
1282 
1283  //The first pass calculates the length of the DER-encoded certificate
1284  error = pemImportCertificate(certChain, certChainLen, NULL, &derCertLen,
1285  NULL);
1286 
1287  //Check status code
1288  if(!error)
1289  {
1290  //Allocate a memory buffer to hold the DER-encoded certificate
1291  derCert = tlsAllocMem(derCertLen);
1292 
1293  //Successful memory allocation?
1294  if(derCert != NULL)
1295  {
1296  //The second pass decodes the PEM certificate
1297  error = pemImportCertificate(certChain, certChainLen, derCert,
1298  &derCertLen, NULL);
1299 
1300  //Check status code
1301  if(!error)
1302  {
1303  //Allocate a memory buffer to store X.509 certificate info
1304  certInfo = tlsAllocMem(sizeof(X509CertInfo));
1305 
1306  //Successful memory allocation?
1307  if(certInfo != NULL)
1308  {
1310 
1311  //Additional certificate parsing options
1313  options.ignoreUnknownExtensions = TRUE;
1314 
1315  //Parse X.509 certificate
1316  error = x509ParseCertificateEx(derCert, derCertLen, certInfo,
1317  &options);
1318 
1319  //Check status code
1320  if(!error)
1321  {
1322  //Retrieve the type of the X.509 certificate
1323  error = tlsGetCertificateType(certInfo, &certType,
1324  &namedCurve);
1325  }
1326 
1327  //Check status code
1328  if(!error)
1329  {
1330  //Retrieve the signature algorithm that has been used to sign
1331  //the certificate
1332  error = tlsGetCertificateSignAlgo(certInfo, &certSignScheme);
1333  }
1334 
1335  //Release previously allocated memory
1336  tlsFreeMem(certInfo);
1337  }
1338  else
1339  {
1340  //Failed to allocate memory
1341  error = ERROR_OUT_OF_MEMORY;
1342  }
1343  }
1344 
1345  //Release previously allocated memory
1346  tlsFreeMem(derCert);
1347  }
1348  else
1349  {
1350  //Failed to allocate memory
1351  error = ERROR_OUT_OF_MEMORY;
1352  }
1353  }
1354 
1355  //Check status code
1356  if(!error)
1357  {
1358  //Point to the structure that describes the certificate
1359  cert = &context->certs[index];
1360 
1361  //Save the certificate chain and the corresponding private key
1362  cert->certChain = certChain;
1363  cert->certChainLen = certChainLen;
1364  cert->privateKey = privateKey;
1365  cert->privateKeyLen = privateKeyLen;
1366  cert->type = certType;
1367  cert->signScheme = certSignScheme;
1368  cert->namedCurve = namedCurve;
1369 
1370  //The password if required only for encrypted private keys
1371  if(password != NULL)
1372  {
1373  osStrcpy(cert->password, password);
1374  }
1375  else
1376  {
1377  osStrcpy(cert->password, "");
1378  }
1379  }
1380 
1381  //Return status code
1382  return error;
1383 }
1384 
1385 
1386 /**
1387  * @brief Register certificate verification callback function
1388  * @param[in] context Pointer to the TLS context
1389  * @param[in] certVerifyCallback Certificate verification callback function
1390  * @param[in] param An opaque pointer passed to the callback function
1391  * @return Error code
1392  **/
1393 
1395  TlsCertVerifyCallback certVerifyCallback, void *param)
1396 {
1397  //Invalid TLS context?
1398  if(context == NULL)
1399  return ERROR_INVALID_PARAMETER;
1400 
1401  //Save certificate verification callback function
1402  context->certVerifyCallback = certVerifyCallback;
1403  //This opaque pointer will be directly passed to the callback function
1404  context->certVerifyParam = param;
1405 
1406  //Successful processing
1407  return NO_ERROR;
1408 }
1409 
1410 
1411 /**
1412  * @brief Enable session ticket mechanism
1413  * @param[in] context Pointer to the TLS context
1414  * @param[in] enabled Specifies whether session tickets are allowed
1415  * @return Error code
1416  **/
1417 
1419 {
1420 #if (TLS_TICKET_SUPPORT == ENABLED)
1421  //Invalid TLS context?
1422  if(context == NULL)
1423  return ERROR_INVALID_PARAMETER;
1424 
1425  //Enable or disable session ticket mechanism
1426  context->sessionTicketEnabled = enabled;
1427 
1428  //Successful processing
1429  return NO_ERROR;
1430 #else
1431  //Session ticket mechanism is not implemented
1432  return ERROR_NOT_IMPLEMENTED;
1433 #endif
1434 }
1435 
1436 
1437 /**
1438  * @brief Enable TrustedCaKeys extension
1439  * @param[in] context Pointer to the TLS context
1440  * @param[in] enabled Specifies whether TrustedCaKeys extension is enabled
1441  * @return Error code
1442  **/
1443 
1445 {
1446 #if (TLS_TRUSTED_CA_KEYS_SUPPORT == ENABLED)
1447  //Invalid TLS context?
1448  if(context == NULL)
1449  return ERROR_INVALID_PARAMETER;
1450 
1451  //Enable or disable support for TrustedCaKeys extension
1452  context->trustedCaKeysEnabled = enabled;
1453 
1454  //Successful processing
1455  return NO_ERROR;
1456 #else
1457  //TrustedCaKeys extension is not implemented
1458  return ERROR_NOT_IMPLEMENTED;
1459 #endif
1460 }
1461 
1462 
1463 /**
1464  * @brief Enable CertificateAuthorities extension
1465  * @param[in] context Pointer to the TLS context
1466  * @param[in] enabled Specifies whether CertificateAuthorities extension is
1467  * enabled
1468  * @return Error code
1469  **/
1470 
1472 {
1473 #if (TLS_CERT_AUTHORITIES_SUPPORT == ENABLED)
1474  //Invalid TLS context?
1475  if(context == NULL)
1476  return ERROR_INVALID_PARAMETER;
1477 
1478  //Enable or disable support for CertificateAuthorities extension
1479  context->certAuthoritiesEnabled = enabled;
1480 
1481  //Successful processing
1482  return NO_ERROR;
1483 #else
1484  //CertificateAuthorities extension is not implemented
1485  return ERROR_NOT_IMPLEMENTED;
1486 #endif
1487 }
1488 
1489 
1490 /**
1491  * @brief Enable secure renegotiation
1492  * @param[in] context Pointer to the TLS context
1493  * @param[in] enabled Specifies whether secure renegotiation is allowed
1494  * @return Error code
1495  **/
1496 
1498 {
1499 #if (TLS_SECURE_RENEGOTIATION_SUPPORT == ENABLED)
1500  //Invalid TLS context?
1501  if(context == NULL)
1502  return ERROR_INVALID_PARAMETER;
1503 
1504  //Enable or disable secure renegotiation
1505  context->secureRenegoEnabled = enabled;
1506 
1507  //Successful processing
1508  return NO_ERROR;
1509 #else
1510  //Secure renegotiation is not implemented
1511  return ERROR_NOT_IMPLEMENTED;
1512 #endif
1513 }
1514 
1515 
1516 /**
1517  * @brief Perform fallback retry (for clients only)
1518  * @param[in] context Pointer to the TLS context
1519  * @param[in] enabled Specifies whether FALLBACK_SCSV is enabled
1520  * @return Error code
1521  **/
1522 
1524 {
1525 #if (TLS_FALLBACK_SCSV_SUPPORT == ENABLED)
1526  //Invalid TLS context?
1527  if(context == NULL)
1528  return ERROR_INVALID_PARAMETER;
1529 
1530  //Enable or disable support for FALLBACK_SCSV
1531  context->fallbackScsvEnabled = enabled;
1532 
1533  //Successful processing
1534  return NO_ERROR;
1535 #else
1536  //Not implemented
1537  return ERROR_NOT_IMPLEMENTED;
1538 #endif
1539 }
1540 
1541 
1542 /**
1543  * @brief Set ticket encryption/decryption callbacks
1544  * @param[in] context Pointer to the TLS context
1545  * @param[in] ticketEncryptCallback Ticket encryption callback function
1546  * @param[in] ticketDecryptCallback Ticket decryption callback function
1547  * @param[in] param An opaque pointer passed to the callback functions
1548  * @return Error code
1549  **/
1550 
1552  TlsTicketEncryptCallback ticketEncryptCallback,
1553  TlsTicketDecryptCallback ticketDecryptCallback, void *param)
1554 {
1555 #if (TLS_TICKET_SUPPORT == ENABLED)
1556  //Invalid TLS context?
1557  if(context == NULL)
1558  return ERROR_INVALID_PARAMETER;
1559 
1560  //Save ticket encryption/decryption callback functions
1561  context->ticketEncryptCallback = ticketEncryptCallback;
1562  context->ticketDecryptCallback = ticketDecryptCallback;
1563 
1564  //This opaque pointer will be directly passed to the callback functions
1565  context->ticketParam = param;
1566 
1567  //Successful processing
1568  return NO_ERROR;
1569 #else
1570  //Session ticket mechanism is not implemented
1571  return ERROR_NOT_IMPLEMENTED;
1572 #endif
1573 }
1574 
1575 
1576 /**
1577  * @brief Set PMTU value (for DTLS only)
1578  * @param[in] context Pointer to the TLS context
1579  * @param[in] pmtu PMTU value
1580  * @return Error code
1581  **/
1582 
1583 error_t tlsSetPmtu(TlsContext *context, size_t pmtu)
1584 {
1585 #if (DTLS_SUPPORT == ENABLED)
1586  //Invalid TLS context?
1587  if(context == NULL)
1588  return ERROR_INVALID_PARAMETER;
1589 
1590  //Make sure the PMTU value is acceptable
1591  if(pmtu < DTLS_MIN_PMTU)
1592  return ERROR_INVALID_PARAMETER;
1593 
1594  //Save PMTU value
1595  context->pmtu = pmtu;
1596 
1597  //Successful processing
1598  return NO_ERROR;
1599 #else
1600  //DTLS is not implemented
1601  return ERROR_NOT_IMPLEMENTED;
1602 #endif
1603 }
1604 
1605 
1606 /**
1607  * @brief Set timeout for blocking calls (for DTLS only)
1608  * @param[in] context Pointer to the TLS context
1609  * @param[in] timeout Maximum time to wait
1610  * @return Error code
1611  **/
1612 
1614 {
1615 #if (DTLS_SUPPORT == ENABLED)
1616  //Invalid TLS context?
1617  if(context == NULL)
1618  return ERROR_INVALID_PARAMETER;
1619 
1620  //Save timeout value
1621  context->timeout = timeout;
1622 
1623  //Successful processing
1624  return NO_ERROR;
1625 #else
1626  //DTLS is not implemented
1627  return ERROR_NOT_IMPLEMENTED;
1628 #endif
1629 }
1630 
1631 
1632 /**
1633  * @brief Set cookie generation/verification callbacks (for DTLS only)
1634  * @param[in] context Pointer to the TLS context
1635  * @param[in] cookieGenerateCallback Cookie generation callback function
1636  * @param[in] cookieVerifyCallback Cookie verification callback function
1637  * @param[in] param An opaque pointer passed to the callback functions
1638  * @return Error code
1639  **/
1640 
1642  DtlsCookieGenerateCallback cookieGenerateCallback,
1643  DtlsCookieVerifyCallback cookieVerifyCallback, void *param)
1644 {
1645 #if (DTLS_SUPPORT == ENABLED)
1646  //Invalid TLS context?
1647  if(context == NULL)
1648  return ERROR_INVALID_PARAMETER;
1649 
1650  //Check parameters
1651  if(cookieGenerateCallback == NULL || cookieVerifyCallback == NULL)
1652  return ERROR_INVALID_PARAMETER;
1653 
1654  //Save cookie generation/verification callback functions
1655  context->cookieGenerateCallback = cookieGenerateCallback;
1656  context->cookieVerifyCallback = cookieVerifyCallback;
1657 
1658  //This opaque pointer will be directly passed to the callback functions
1659  context->cookieParam = param;
1660 
1661  //Successful processing
1662  return NO_ERROR;
1663 #else
1664  //DTLS is not implemented
1665  return ERROR_NOT_IMPLEMENTED;
1666 #endif
1667 }
1668 
1669 
1670 /**
1671  * @brief Enable anti-replay mechanism (for DTLS only)
1672  * @param[in] context Pointer to the TLS context
1673  * @param[in] enabled Specifies whether anti-replay protection is enabled
1674  * @return Error code
1675  **/
1676 
1678 {
1679 #if (DTLS_SUPPORT == ENABLED && DTLS_REPLAY_DETECTION_SUPPORT == ENABLED)
1680  //Invalid TLS context?
1681  if(context == NULL)
1682  return ERROR_INVALID_PARAMETER;
1683 
1684  //Enable or disable anti-replay mechanism
1685  context->replayDetectionEnabled = enabled;
1686 
1687  //Successful processing
1688  return NO_ERROR;
1689 #else
1690  //Anti-replay mechanism is not implemented
1691  return ERROR_NOT_IMPLEMENTED;
1692 #endif
1693 }
1694 
1695 
1696 /**
1697  * @brief Send the maximum amount of 0-RTT data the server can accept
1698  * @param[in] context Pointer to the TLS context
1699  * @param[in] maxEarlyDataSize Maximum amount of 0-RTT data that the client
1700  * is allowed to send
1701  * @return Error code
1702  **/
1703 
1704 
1705 error_t tlsSetMaxEarlyDataSize(TlsContext *context, size_t maxEarlyDataSize)
1706 {
1707 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
1708  //Invalid TLS context?
1709  if(context == NULL)
1710  return ERROR_INVALID_PARAMETER;
1711 
1712  //Save the maximum amount of 0-RTT data that the client is allowed to send
1713  context->maxEarlyDataSize = maxEarlyDataSize;
1714 
1715  //Successful processing
1716  return NO_ERROR;
1717 #else
1718  //Not implemented
1719  return ERROR_NOT_IMPLEMENTED;
1720 #endif
1721 }
1722 
1723 
1724 /**
1725  * @brief Send early data to the remote TLS server
1726  * @param[in] context Pointer to the TLS context
1727  * @param[in] data Pointer to a buffer containing the data to be transmitted
1728  * @param[in] length Number of bytes to be transmitted
1729  * @param[out] written Actual number of bytes written (optional parameter)
1730  * @param[in] flags Set of flags that influences the behavior of this function
1731  * @return Error code
1732  **/
1733 
1735  size_t length, size_t *written, uint_t flags)
1736 {
1737 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3 && \
1738  TLS_CLIENT_SUPPORT == ENABLED && TLS13_EARLY_DATA_SUPPORT == ENABLED)
1739  size_t n;
1740  error_t error;
1741 
1742  //Invalid TLS context?
1743  if(context == NULL)
1744  return ERROR_INVALID_PARAMETER;
1745 
1746  //Check parameters
1747  if(data == NULL && length != 0)
1748  return ERROR_INVALID_PARAMETER;
1749 
1750  //Check operation mode
1751  if(context->entity != TLS_CONNECTION_END_CLIENT)
1752  return ERROR_FAILURE;
1753 
1754  //Check transport protocol
1755  if(context->transportProtocol != TLS_TRANSPORT_PROTOCOL_STREAM)
1756  return ERROR_FAILURE;
1757 
1758  //Make sure TLS 1.3 is supported by the client
1759  if(context->versionMax < TLS_VERSION_1_3)
1760  return ERROR_FAILURE;
1761 
1762  //Ensure the send/receive functions are properly registered
1763  if(context->socketSendCallback == NULL || context->socketReceiveCallback == NULL)
1764  return ERROR_NOT_CONFIGURED;
1765 
1766  //Verify that the PRNG is properly set
1767  if(context->prngAlgo == NULL || context->prngContext == NULL)
1768  return ERROR_NOT_CONFIGURED;
1769 
1770 #if (DTLS_SUPPORT == ENABLED)
1771  //Save current time
1772  context->startTime = osGetSystemTime();
1773 #endif
1774 
1775  //Send 0-RTT data
1776  error = tls13SendEarlyData(context, data, length, &n);
1777 
1778  //Total number of data that have been written
1779  if(written != NULL)
1780  {
1781  *written = n;
1782  }
1783 
1784  //Return status code
1785  return error;
1786 #else
1787  //Not implemented
1788  return ERROR_NOT_IMPLEMENTED;
1789 #endif
1790 }
1791 
1792 
1793 /**
1794  * @brief Initiate the TLS handshake
1795  * @param[in] context Pointer to the TLS context
1796  * @return Error code
1797  **/
1798 
1800 {
1801  error_t error;
1802 
1803  //Invalid TLS context?
1804  if(context == NULL)
1805  return ERROR_INVALID_PARAMETER;
1806 
1807  //Ensure the send/receive functions are properly registered
1808  if(context->socketSendCallback == NULL || context->socketReceiveCallback == NULL)
1809  return ERROR_NOT_CONFIGURED;
1810 
1811  //Verify that the PRNG is properly set
1812  if(context->prngAlgo == NULL || context->prngContext == NULL)
1813  return ERROR_NOT_CONFIGURED;
1814 
1815 #if (DTLS_SUPPORT == ENABLED)
1816  //Save current time
1817  context->startTime = osGetSystemTime();
1818 #endif
1819 
1820 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3 && \
1821  TLS_CLIENT_SUPPORT == ENABLED && TLS13_EARLY_DATA_SUPPORT == ENABLED)
1822  //Any 0-RTT data sent by the client?
1823  if(context->entity == TLS_CONNECTION_END_CLIENT &&
1824  context->state == TLS_STATE_EARLY_DATA)
1825  {
1826  //Save current sequence number
1827  context->earlyDataSeqNum = context->encryptionEngine[0].seqNum;
1828  //Wait for a ServerHello message
1830  }
1831 #endif
1832 
1833  //Perform TLS handshake
1834  error = tlsPerformHandshake(context);
1835  //Return status code
1836  return error;
1837 }
1838 
1839 
1840 /**
1841  * @brief Check whether the server has accepted or rejected the early data
1842  * @param[in] context Pointer to the TLS context
1843  * @return TLS_EARLY_DATA_ACCEPTED if the early data was accepted, else
1844  * TLS_EARLY_DATA_REJECT if the early data was rejected
1845  **/
1846 
1848 {
1849  TlsEarlyDataStatus status;
1850 
1851  //Initialize early data status
1852  status = TLS_EARLY_DATA_REJECTED;
1853 
1854 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3 && \
1855  TLS_CLIENT_SUPPORT == ENABLED && TLS13_EARLY_DATA_SUPPORT == ENABLED)
1856  //Make sure the TLS context is valid
1857  if(context != NULL)
1858  {
1859  //Client mode?
1860  if(context->entity == TLS_CONNECTION_END_CLIENT)
1861  {
1862  //Any 0-RTT data sent by the client?
1863  if(context->earlyDataEnabled)
1864  {
1865  //Check whether the server has accepted or rejected the early data
1866  if(context->earlyDataExtReceived && !context->earlyDataRejected)
1867  {
1868  status = TLS_EARLY_DATA_ACCEPTED;
1869  }
1870  }
1871  }
1872  }
1873 #endif
1874 
1875  //Return early data status
1876  return status;
1877 }
1878 
1879 
1880 /**
1881  * @brief Export keying material per RFC 5705 standard
1882  * @param[in] context Pointer to the TLS context
1883  * @param[in] label Identifying label (NULL-terminated string)
1884  * @param[in] useContextValue Specifies whether upper-layer context should
1885  * be used when exporting keying material
1886  * @param[in] contextValue Pointer to the upper-layer context
1887  * @param[in] contextValueLen Length of the upper-layer context
1888  * @param[out] output Buffer where to store the keying material
1889  * @param[in] outputLen Desired output length
1890  * @return Error code
1891  **/
1892 
1894  bool_t useContextValue, const uint8_t *contextValue,
1895  size_t contextValueLen, uint8_t *output, size_t outputLen)
1896 {
1897  error_t error;
1898  size_t n;
1899  uint8_t *seed;
1900 
1901  //Invalid TLS context?
1902  if(context == NULL)
1903  return ERROR_INVALID_PARAMETER;
1904 
1905  //Check parameters
1906  if(label == NULL || output == NULL)
1907  return ERROR_INVALID_PARAMETER;
1908 
1909  //Make sure the upper-layer context is valid
1910  if(contextValue == NULL && contextValueLen != 0)
1911  return ERROR_INVALID_PARAMETER;
1912 
1913  //Calculate the length of the seed
1914  n = 2 * TLS_RANDOM_SIZE;
1915 
1916  //Check whether a context is provided
1917  if(useContextValue)
1918  {
1919  n += contextValueLen + 2;
1920  }
1921 
1922  //Allocate a memory buffer to hold the seed
1923  seed = tlsAllocMem(n);
1924  //Failed to allocate memory?
1925  if(seed == NULL)
1926  return ERROR_OUT_OF_RESOURCES;
1927 
1928  //Concatenate client_random and server_random values
1929  osMemcpy(seed, context->clientRandom, TLS_RANDOM_SIZE);
1930  osMemcpy(seed + 32, context->serverRandom, TLS_RANDOM_SIZE);
1931 
1932  //Check whether a context is provided
1933  if(useContextValue)
1934  {
1935  //The context_value_length is encoded as an unsigned, 16-bit quantity
1936  //representing the length of the context value
1937  STORE16BE(contextValueLen, seed + 64);
1938 
1939  //Copy the context value provided by the application using the exporter
1940  osMemcpy(seed + 66, contextValue, contextValueLen);
1941  }
1942 
1943 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_1)
1944  //TLS 1.0 or TLS 1.1 currently selected?
1945  if(context->version == TLS_VERSION_1_0 || context->version == TLS_VERSION_1_1)
1946  {
1947  //TLS 1.0 and 1.1 use a PRF that combines MD5 and SHA-1
1948  error = tlsPrf(context->masterSecret, TLS_MASTER_SECRET_SIZE,
1949  label, seed, n, output, outputLen);
1950  }
1951  else
1952 #endif
1953 #if (TLS_MAX_VERSION >= TLS_VERSION_1_2 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
1954  //TLS 1.2 currently selected?
1955  if(context->version == TLS_VERSION_1_2)
1956  {
1957  //Make sure the PRF hash algorithm is valid
1958  if(context->cipherSuite.prfHashAlgo != NULL)
1959  {
1960  //TLS 1.2 PRF uses SHA-256 or a stronger hash algorithm as the core
1961  //function in its construction
1962  error = tls12Prf(context->cipherSuite.prfHashAlgo, context->masterSecret,
1963  TLS_MASTER_SECRET_SIZE, label, seed, n, output, outputLen);
1964  }
1965  else
1966  {
1967  //Invalid PRF hash algorithm
1968  error = ERROR_FAILURE;
1969  }
1970  }
1971  else
1972 #endif
1973 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
1974  //TLS 1.3 currently selected?
1975  if(context->version == TLS_VERSION_1_3)
1976  {
1977  const HashAlgo *hash;
1979  uint8_t digest[TLS_MAX_HKDF_DIGEST_SIZE];
1980 
1981  //The hash function used by HKDF is the cipher suite hash algorithm
1982  hash = context->cipherSuite.prfHashAlgo;
1983 
1984  //Make sure the HKDF hash algorithm is valid
1985  if(hash != NULL)
1986  {
1987  //Derive exporter master secret
1988  error = tls13DeriveSecret(context, context->exporterMasterSecret,
1989  hash->digestSize, label, "", 0, secret, hash->digestSize);
1990 
1991  //Check status code
1992  if(!error)
1993  {
1994  //Hash context_value input
1995  error = hash->compute(contextValue, contextValueLen, digest);
1996  }
1997 
1998  //Check status code
1999  if(!error)
2000  {
2001  //Export keying material
2002  error = tls13HkdfExpandLabel(context->transportProtocol, hash,
2003  secret, hash->digestSize, "exporter", digest, hash->digestSize,
2004  output, outputLen);
2005  }
2006  }
2007  else
2008  {
2009  //Invalid HKDF hash algorithm
2010  error = ERROR_FAILURE;
2011  }
2012  }
2013  else
2014 #endif
2015  //Invalid TLS version?
2016  {
2017  //Report an error
2018  error = ERROR_INVALID_VERSION;
2019  }
2020 
2021  //Release previously allocated memory
2022  tlsFreeMem(seed);
2023 
2024  //Return status code
2025  return error;
2026 }
2027 
2028 
2029 /**
2030  * @brief Export channel binding value
2031  * @param[in] context Pointer to the TLS context
2032  * @param[in] type Channel binding type
2033  * @param[out] output Buffer where to store the channel binding value
2034  * @param[out] length Length of the channel binding value, in bytes
2035  * @return Error code
2036  **/
2037 
2039  uint8_t *output, size_t *length)
2040 {
2041  error_t error;
2042 
2043  //Check parameters
2044  if(context == NULL || type == NULL || length == 0)
2045  return ERROR_INVALID_PARAMETER;
2046 
2047  //Initialize status code
2048  error = NO_ERROR;
2049 
2050  //Check channel binding type
2051  if(osStrcmp(type, "tls-unique") == 0)
2052  {
2053  //Check TLS version
2054  if(context->version <= TLS_VERSION_1_2)
2055  {
2056  //The "tls-unique" channel binding value is the first TLS Finished
2057  //message sent in the most recent TLS handshake of the TLS connection
2058  //being bound to (refer to RFC 5929, section 3.1)
2059  if(context->resume)
2060  {
2061  //For abbreviated TLS handshakes (session resumption), the first
2062  //Finished message is sent by the server
2063  if(output != NULL)
2064  {
2065  osMemcpy(output, context->serverVerifyData,
2066  context->serverVerifyDataLen);
2067  }
2068 
2069  //Length of the channel binding value
2070  *length = context->clientVerifyDataLen;
2071 
2072 #if (TLS_EXT_MASTER_SECRET_SUPPORT == ENABLED)
2073  //If a client or server chooses to continue an abbreviated handshake
2074  //to resume a session that does not use the extended master secret,
2075  //then the client must disable any use of the "tls-unique" channel
2076  //binding on the current connection (refer to RFC 7627, section 5.4)
2077  error = (context->emsExtReceived) ? NO_ERROR : ERROR_FAILURE;
2078 #else
2079  //The session does not use the extended master secret
2080  error = ERROR_FAILURE;
2081 #endif
2082  }
2083  else
2084  {
2085  //For full TLS handshakes, the first Finished message is sent by
2086  //the client
2087  if(output != NULL)
2088  {
2089  osMemcpy(output, context->clientVerifyData,
2090  context->clientVerifyDataLen);
2091  }
2092 
2093  //Length of the channel binding value
2094  *length = context->clientVerifyDataLen;
2095  }
2096  }
2097  else
2098  {
2099  //Appendix C.5 of RFC 8446 notes the lack of channel bindings for
2100  //TLS 1.3 (refer to to RFC 9266, section 1)
2101  }
2102  }
2103  else if(osStrcmp(type, "tls-exporter") == 0)
2104  {
2105  //The "tls-exporter" channel binding type uses Exported Keying Material
2106  //(EKM), which is already widely exposed by TLS implementations (refer
2107  //to RFC 9266, section 2)
2108  error = tlsExportKeyingMaterial(context, "EXPORTER-Channel-Binding",
2109  TRUE, NULL, 0, output, 32);
2110 
2111  //Check status code
2112  if(!error)
2113  {
2114  //The derived value consists of 32 bytes
2115  *length = 32;
2116  }
2117  }
2118  else
2119  {
2120  //Report an error
2121  error = ERROR_INVALID_TYPE;
2122  }
2123 
2124  //Return status code
2125  return error;
2126 }
2127 
2128 
2129 /**
2130  * @brief Send application data to the remote host using TLS
2131  * @param[in] context Pointer to the TLS context
2132  * @param[in] data Pointer to a buffer containing the data to be transmitted
2133  * @param[in] length Number of bytes to be transmitted
2134  * @param[out] written Actual number of bytes written (optional parameter)
2135  * @param[in] flags Set of flags that influences the behavior of this function
2136  * @return Error code
2137  **/
2138 
2139 error_t tlsWrite(TlsContext *context, const void *data, size_t length,
2140  size_t *written, uint_t flags)
2141 {
2142  error_t error;
2143  size_t n;
2144  size_t totalLength;
2145 
2146  //Invalid TLS context?
2147  if(context == NULL)
2148  return ERROR_INVALID_PARAMETER;
2149 
2150  //Check parameters
2151  if(data == NULL && length != 0)
2152  return ERROR_INVALID_PARAMETER;
2153 
2154  //Ensure the send/receive functions are properly registered
2155  if(context->socketSendCallback == NULL || context->socketReceiveCallback == NULL)
2156  return ERROR_NOT_CONFIGURED;
2157 
2158 #if (DTLS_SUPPORT == ENABLED)
2159  //Save current time
2160  context->startTime = osGetSystemTime();
2161 #endif
2162 
2163  //Initialize status code
2164  error = NO_ERROR;
2165 
2166  //Actual number of bytes written
2167  totalLength = 0;
2168 
2169  //Send as much data as possible
2170  while(totalLength < length)
2171  {
2172  //Check current state
2173  if(context->state < TLS_STATE_APPLICATION_DATA ||
2174  context->state == TLS_STATE_KEY_UPDATE)
2175  {
2176  //Perform TLS handshake
2177  error = tlsConnect(context);
2178  }
2179  else if(context->state == TLS_STATE_APPLICATION_DATA ||
2180  context->state == TLS_STATE_CLIENT_FINISHED_ACK ||
2181  context->state == TLS_STATE_NEW_SESSION_TICKET_ACK ||
2182  context->state == TLS_STATE_KEY_UPDATE_ACK)
2183  {
2184 #if (DTLS_SUPPORT == ENABLED)
2185  //DTLS protocol?
2186  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
2187  {
2188  //Length of the payload data
2189  n = length;
2190 
2191  //Send a datagram
2192  error = dtlsWriteProtocolData(context, data, n,
2194  }
2195  else
2196 #endif
2197  //TLS protocol?
2198  {
2199  //Calculate the number of bytes to write at a time
2200  n = MIN(length - totalLength, context->txBufferMaxLen);
2201  //The record length must not exceed 16384 bytes
2203 
2204 #if (TLS_MAX_FRAG_LEN_SUPPORT == ENABLED)
2205  //Do not exceed the negotiated maximum fragment length
2206  n = MIN(n, context->maxFragLen);
2207 #endif
2208 
2209 #if (TLS_RECORD_SIZE_LIMIT_SUPPORT == ENABLED)
2210  //Maximum record size the peer is willing to receive
2211  n = MIN(n, context->recordSizeLimit);
2212 #endif
2213 
2214 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_0)
2215  //The 1/n-1 record splitting technique is a workaround for the
2216  //BEAST attack
2217  if(context->version <= TLS_VERSION_1_0 &&
2218  context->cipherSuite.cipherMode == CIPHER_MODE_CBC &&
2219  context->txLastRecordLen != 1 &&
2220  totalLength == 0)
2221  {
2222  n = 1;
2223  }
2224 #endif
2225  //Send application data
2226  error = tlsWriteProtocolData(context, data, n,
2228  }
2229 
2230  //Check status code
2231  if(!error)
2232  {
2233 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_0)
2234  //Save the length of the TLS record
2235  context->txLastRecordLen = n;
2236 #endif
2237  //Advance data pointer
2238  data = (uint8_t *) data + n;
2239  //Update byte counter
2240  totalLength += n;
2241  }
2242  else
2243  {
2244  //Send an alert message to the peer, if applicable
2245  tlsProcessError(context, error);
2246  }
2247  }
2248  else
2249  {
2250  //The connection has not yet been established
2251  error = ERROR_NOT_CONNECTED;
2252  }
2253 
2254  //Any error to report?
2255  if(error)
2256  break;
2257  }
2258 
2259  //Total number of data that have been written
2260  if(written != NULL)
2261  {
2262  *written = totalLength;
2263  }
2264 
2265  //Return status code
2266  return error;
2267 }
2268 
2269 
2270 /**
2271  * @brief Receive application data from a the remote host using TLS
2272  * @param[in] context Pointer to the TLS context
2273  * @param[out] data Buffer into which received data will be placed
2274  * @param[in] size Maximum number of bytes that can be received
2275  * @param[out] received Number of bytes that have been received
2276  * @param[in] flags Set of flags that influences the behavior of this function
2277  * @return Error code
2278  **/
2279 
2280 error_t tlsRead(TlsContext *context, void *data, size_t size, size_t *received,
2281  uint_t flags)
2282 {
2283  error_t error;
2284  size_t i;
2285  size_t n;
2286  uint8_t *p;
2287  TlsContentType contentType;
2288 
2289  //Invalid TLS context?
2290  if(context == NULL)
2291  return ERROR_INVALID_PARAMETER;
2292 
2293  //Check parameters
2294  if(data == NULL || received == NULL)
2295  return ERROR_INVALID_PARAMETER;
2296 
2297  //Ensure the send/receive functions are properly registered
2298  if(context->socketSendCallback == NULL || context->socketReceiveCallback == NULL)
2299  return ERROR_NOT_CONFIGURED;
2300 
2301 #if (DTLS_SUPPORT == ENABLED)
2302  //Save current time
2303  context->startTime = osGetSystemTime();
2304 #endif
2305 
2306  //Initialize status code
2307  error = NO_ERROR;
2308 
2309  //No data has been read yet
2310  *received = 0;
2311 
2312  //Read as much data as possible
2313  while(*received < size)
2314  {
2315  //Check current state
2316  if(context->state < TLS_STATE_APPLICATION_DATA ||
2317  context->state == TLS_STATE_KEY_UPDATE)
2318  {
2319  //Perform TLS handshake
2320  error = tlsConnect(context);
2321  }
2322  else if(context->state == TLS_STATE_APPLICATION_DATA ||
2323  context->state == TLS_STATE_CLIENT_FINISHED_ACK ||
2324  context->state == TLS_STATE_NEW_SESSION_TICKET_ACK ||
2325  context->state == TLS_STATE_KEY_UPDATE_ACK)
2326  {
2327 #if (DTLS_SUPPORT == ENABLED)
2328  //DTLS protocol?
2329  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
2330  {
2331  //Receive a datagram
2332  error = dtlsReadProtocolData(context, &p, &n, &contentType);
2333  }
2334  else
2335 #endif
2336  //TLS protocol?
2337  {
2338  //The record layer receives uninterpreted data from higher layers
2339  error = tlsReadProtocolData(context, &p, &n, &contentType);
2340  }
2341 
2342  //Check status code
2343  if(!error)
2344  {
2345  //Application data received?
2346  if(contentType == TLS_TYPE_APPLICATION_DATA)
2347  {
2348 #if (DTLS_SUPPORT == ENABLED)
2349  //DTLS protocol?
2350  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
2351  {
2352  //Make sure the user buffer is large enough to hold the whole
2353  //datagram
2354  if(n > size)
2355  {
2356  //Report an error
2357  error = ERROR_BUFFER_OVERFLOW;
2358  }
2359  else
2360  {
2361  //Copy data to user buffer
2362  osMemcpy(data, p, n);
2363  //Total number of data that have been read
2364  *received = n;
2365  }
2366 
2367  //If the TLS_FLAG_PEEK flag is set, the data is copied into
2368  //the buffer but is not removed from the receive queue
2369  if((flags & TLS_FLAG_PEEK) == 0)
2370  {
2371  //Flush receive buffer
2372  context->rxBufferPos = 0;
2373  context->rxBufferLen = 0;
2374  }
2375 
2376  //We are done
2377  break;
2378  }
2379  else
2380 #endif
2381  //TLS protocol?
2382  {
2383  //Limit the number of bytes to read at a time
2384  n = MIN(n, size - *received);
2385 
2386  //The TLS_FLAG_BREAK_CHAR flag causes the function to stop reading
2387  //data as soon as the specified break character is encountered
2388  if((flags & TLS_FLAG_BREAK_CHAR) != 0)
2389  {
2390  //Retrieve the break character code
2391  char_t c = LSB(flags);
2392 
2393  //Search for the specified break character
2394  for(i = 0; i < n && p[i] != c; i++)
2395  {
2396  }
2397 
2398  //Adjust the number of data to read
2399  n = MIN(n, i + 1);
2400 
2401  //Copy data to user buffer
2402  osMemcpy(data, p, n);
2403  //Total number of data that have been read
2404  *received += n;
2405 
2406  //Advance data pointer
2407  context->rxBufferPos += n;
2408  //Number of bytes still pending in the receive buffer
2409  context->rxBufferLen -= n;
2410 
2411  //Check whether a break character has been found
2412  if(n > 0 && p[n - 1] == c)
2413  break;
2414  }
2415  else
2416  {
2417  //Copy data to user buffer
2418  osMemcpy(data, p, n);
2419  //Total number of data that have been read
2420  *received += n;
2421 
2422  //Advance data pointer
2423  context->rxBufferPos += n;
2424  //Number of bytes still pending in the receive buffer
2425  context->rxBufferLen -= n;
2426 
2427  //The TLS_FLAG_WAIT_ALL flag causes the function to return
2428  //only when the requested number of bytes have been read
2429  if((flags & TLS_FLAG_WAIT_ALL) == 0)
2430  break;
2431  }
2432 
2433  //Advance data pointer
2434  data = (uint8_t *) data + n;
2435  }
2436  }
2437  //Handshake message received?
2438  else if(contentType == TLS_TYPE_HANDSHAKE)
2439  {
2440  //Advance data pointer
2441  context->rxBufferPos += n;
2442  //Number of bytes still pending in the receive buffer
2443  context->rxBufferLen -= n;
2444 
2445  //Parse handshake message
2446  error = tlsParseHandshakeMessage(context, p, n);
2447  }
2448  //Alert message received?
2449  else if(contentType == TLS_TYPE_ALERT)
2450  {
2451  //Advance data pointer
2452  context->rxBufferPos += n;
2453  //Number of bytes still pending in the receive buffer
2454  context->rxBufferLen -= n;
2455 
2456  //Parse Alert message
2457  error = tlsParseAlert(context, (TlsAlert *) p, n);
2458  }
2459 #if (DTLS_SUPPORT == ENABLED && TLS_MAX_VERSION >= TLS_VERSION_1_3)
2460  //ACK message received?
2461  else if(contentType == TLS_TYPE_ACK)
2462  {
2463  //Advance data pointer
2464  context->rxBufferPos += n;
2465  //Number of bytes still pending in the receive buffer
2466  context->rxBufferLen -= n;
2467 
2468  //Parse ACK message
2469  error = dtls13ParseAck(context, (Dtls13Ack *) p, n);
2470  }
2471 #endif
2472  //An inappropriate message was received?
2473  else
2474  {
2475  //Report an error
2476  error = ERROR_UNEXPECTED_MESSAGE;
2477  }
2478  }
2479 
2480  //Any error to report?
2481  if(error)
2482  {
2483  //Send an alert message to the peer, if applicable
2484  tlsProcessError(context, error);
2485  }
2486  }
2487  else if(context->state == TLS_STATE_CLOSING ||
2488  context->state == TLS_STATE_CLOSED)
2489  {
2490  //Check whether a fatal alert message has been sent or received
2491  if(context->fatalAlertSent || context->fatalAlertReceived)
2492  {
2493  //Alert messages with a level of fatal result in the immediate
2494  //termination of the connection
2495  error = ERROR_FAILURE;
2496  }
2497  else
2498  {
2499  //The user must be satisfied with data already on hand
2500  if(*received > 0)
2501  {
2502  //Some data are pending in the receive buffer
2503  error = NO_ERROR;
2504  break;
2505  }
2506  else
2507  {
2508  //The receive buffer is empty
2509  error = ERROR_END_OF_STREAM;
2510  }
2511  }
2512  }
2513  else
2514  {
2515  //The connection has not yet been established
2516  error = ERROR_NOT_CONNECTED;
2517  }
2518 
2519  //Any error to report?
2520  if(error)
2521  break;
2522  }
2523 
2524  //Return status code
2525  return error;
2526 }
2527 
2528 
2529 /**
2530  * @brief Check whether some data is ready for transmission
2531  * @param[in] context Pointer to the TLS context
2532  * @return The function returns TRUE if some data is ready for transmission.
2533  * Otherwise, FALSE is returned
2534  **/
2535 
2537 {
2538  bool_t ready;
2539 
2540  //Initialize flag
2541  ready = FALSE;
2542 
2543  //Make sure the TLS context is valid
2544  if(context != NULL)
2545  {
2546  //TLS protocol?
2547  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_STREAM ||
2548  context->transportProtocol == TLS_TRANSPORT_PROTOCOL_EAP)
2549  {
2550  //Check whether some data is pending in the transmit buffer
2551  if(context->txBufferPos < context->txBufferLen)
2552  {
2553  ready = TRUE;
2554  }
2555  }
2556  }
2557 
2558  //The function returns TRUE if some data is ready for transmission
2559  return ready;
2560 }
2561 
2562 
2563 /**
2564  * @brief Check whether some data is available in the receive buffer
2565  * @param[in] context Pointer to the TLS context
2566  * @return The function returns TRUE if some data is pending and can be read
2567  * immediately without blocking. Otherwise, FALSE is returned
2568  **/
2569 
2571 {
2572  bool_t ready;
2573 
2574  //Initialize flag
2575  ready = FALSE;
2576 
2577  //Make sure the TLS context is valid
2578  if(context != NULL)
2579  {
2580 #if (DTLS_SUPPORT == ENABLED)
2581  //DTLS protocol?
2582  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
2583  {
2584  //Check whether a datagram is pending in the receive buffer
2585  if(context->rxBufferLen > 0 ||
2586  context->rxRecordLen > 0 ||
2587  context->rxDatagramLen > 0)
2588  {
2589  ready = TRUE;
2590  }
2591  }
2592  else
2593 #endif
2594  //TLS protocol?
2595  {
2596  //Check whether some data is pending in the receive buffer
2597  if(context->rxBufferLen > 0)
2598  {
2599  ready = TRUE;
2600  }
2601  }
2602  }
2603 
2604  //The function returns TRUE if some data can be read immediately without
2605  //blocking
2606  return ready;
2607 }
2608 
2609 
2610 /**
2611  * @brief Gracefully close TLS session
2612  * @param[in] context Pointer to the TLS context
2613  **/
2614 
2616 {
2617  //Either party may initiate a close by sending a close_notify alert
2618  return tlsShutdownEx(context, FALSE);
2619 }
2620 
2621 
2622 /**
2623  * @brief Gracefully close TLS session
2624  * @param[in] context Pointer to the TLS context
2625  * @param[in] waitForCloseNotify Wait for the close notify alert from the peer
2626  **/
2627 
2628 error_t tlsShutdownEx(TlsContext *context, bool_t waitForCloseNotify)
2629 {
2630  error_t error;
2631  size_t n;
2632  uint8_t *p;
2633  TlsContentType contentType;
2634 
2635  //Invalid TLS context?
2636  if(context == NULL)
2637  return ERROR_INVALID_PARAMETER;
2638 
2639  //Ensure the send/receive functions are properly registered
2640  if(context->socketSendCallback == NULL || context->socketReceiveCallback == NULL)
2641  return ERROR_NOT_CONFIGURED;
2642 
2643 #if (DTLS_SUPPORT == ENABLED)
2644  //Save current time
2645  context->startTime = osGetSystemTime();
2646 #endif
2647 
2648  //Initialize status code
2649  error = NO_ERROR;
2650 
2651  //Wait for the TLS session to be closed
2652  while(context->state != TLS_STATE_CLOSED)
2653  {
2654  //Check current state
2655  if(context->state == TLS_STATE_APPLICATION_DATA)
2656  {
2657  //TLS protocol?
2658  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_STREAM ||
2659  context->transportProtocol == TLS_TRANSPORT_PROTOCOL_EAP)
2660  {
2661  //Flush send buffer
2662  error = tlsWriteProtocolData(context, NULL, 0, TLS_TYPE_NONE);
2663  }
2664 
2665  //Check status code
2666  if(!error)
2667  {
2668  //Either party may initiate a close by sending a close_notify alert
2670  }
2671  }
2672  else if(context->state == TLS_STATE_CLOSING)
2673  {
2674  //TLS protocol?
2675  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_STREAM ||
2676  context->transportProtocol == TLS_TRANSPORT_PROTOCOL_EAP)
2677  {
2678  //Flush send buffer
2679  error = tlsWriteProtocolData(context, NULL, 0, TLS_TYPE_NONE);
2680  }
2681 
2682  //Check status code
2683  if(!error)
2684  {
2685  //Unless some other fatal alert has been transmitted, each party
2686  //is required to send a close_notify alert before closing the
2687  //write side of the connection
2688  if(context->fatalAlertSent || context->fatalAlertReceived)
2689  {
2690  //Close the connection immediately
2691  tlsChangeState(context, TLS_STATE_CLOSED);
2692  }
2693  else if(!context->closeNotifySent)
2694  {
2695  //Notifies the recipient that the sender will not send any
2696  //more messages on this connection
2697  error = tlsSendAlert(context, TLS_ALERT_LEVEL_WARNING,
2699  }
2700  else if(!context->closeNotifyReceived && waitForCloseNotify)
2701  {
2702 #if (DTLS_SUPPORT == ENABLED)
2703  //DTLS protocol?
2704  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
2705  {
2706  //Wait for the responding close_notify alert
2707  error = dtlsReadProtocolData(context, &p, &n, &contentType);
2708  }
2709  else
2710 #endif
2711  //TLS protocol?
2712  {
2713  //Wait for the responding close_notify alert
2714  error = tlsReadProtocolData(context, &p, &n, &contentType);
2715  }
2716 
2717  //Check status code
2718  if(!error)
2719  {
2720  //Advance data pointer
2721  context->rxBufferPos += n;
2722  //Number of bytes still pending in the receive buffer
2723  context->rxBufferLen -= n;
2724 
2725  //Application data received?
2726  if(contentType == TLS_TYPE_APPLICATION_DATA)
2727  {
2728  //Discard application data
2729  }
2730  //Alert message received?
2731  else if(contentType == TLS_TYPE_ALERT)
2732  {
2733  //Parse Alert message
2734  error = tlsParseAlert(context, (TlsAlert *) p, n);
2735  }
2736  else if(contentType == TLS_TYPE_HANDSHAKE)
2737  {
2738  //Parse handshake message
2739  error = tlsParseHandshakeMessage(context, p, n);
2740  }
2741  //An inappropriate message was received?
2742  else
2743  {
2744  //Report an error
2745  error = ERROR_UNEXPECTED_MESSAGE;
2746  }
2747  }
2748  }
2749  else
2750  {
2751  //The connection is closed
2752  tlsChangeState(context, TLS_STATE_CLOSED);
2753  }
2754  }
2755  }
2756  else
2757  {
2758  //Report an error
2759  error = ERROR_NOT_CONNECTED;
2760  }
2761 
2762  //Any error to report?
2763  if(error)
2764  break;
2765  }
2766 
2767  //Return status code
2768  return error;
2769 }
2770 
2771 
2772 /**
2773  * @brief Handle periodic operations
2774  * @param[in] context Pointer to the TLS context
2775  * @return Error code
2776  **/
2777 
2779 {
2780  error_t error;
2781 
2782 #if (DTLS_SUPPORT == ENABLED)
2783  //Valid DTLS context?
2784  if(context != NULL &&
2785  context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
2786  {
2787  //Manage retransmission timers
2788  error = dtlsTick(context);
2789  }
2790  else
2791 #endif
2792  {
2793  //Report an error
2794  error = ERROR_INVALID_PARAMETER;
2795  }
2796 
2797  //Return status code
2798  return error;
2799 }
2800 
2801 
2802 /**
2803  * @brief Release TLS context
2804  * @param[in] context Pointer to the TLS context
2805  **/
2806 
2807 void tlsFree(TlsContext *context)
2808 {
2809  uint_t i;
2810 
2811  //Valid TLS context?
2812  if(context != NULL)
2813  {
2814  //Release server name
2815  if(context->serverName != NULL)
2816  {
2817  tlsFreeMem(context->serverName);
2818  }
2819 
2820  //Release cookie
2821  if(context->cookie != NULL)
2822  {
2823  osMemset(context->cookie, 0, context->cookieLen);
2824  tlsFreeMem(context->cookie);
2825  }
2826 
2827  //Release send buffer
2828  if(context->txBuffer != NULL)
2829  {
2830  osMemset(context->txBuffer, 0, context->txBufferSize);
2831  tlsFreeMem(context->txBuffer);
2832  }
2833 
2834  //Release receive buffer
2835  if(context->rxBuffer != NULL)
2836  {
2837  osMemset(context->rxBuffer, 0, context->rxBufferSize);
2838  tlsFreeMem(context->rxBuffer);
2839  }
2840 
2841  //Release transcript hash context
2842  tlsFreeTranscriptHash(context);
2843 
2844  //Release session ticket
2845  if(context->ticket != NULL)
2846  {
2847  osMemset(context->ticket, 0, context->ticketLen);
2848  tlsFreeMem(context->ticket);
2849  }
2850 
2851 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
2852  //Release the ALPN protocol associated with the ticket
2853  if(context->ticketAlpn != NULL)
2854  {
2855  tlsFreeMem(context->ticketAlpn);
2856  }
2857 #endif
2858 
2859 #if (TLS_DH_SUPPORT == ENABLED)
2860  //Release Diffie-Hellman context
2861  dhFree(&context->dhContext);
2862 #endif
2863 
2864 #if (TLS_ECDH_SUPPORT == ENABLED || TLS_HYBRID_SUPPORT == ENABLED)
2865  //Release ECDH context
2866  ecdhFree(&context->ecdhContext);
2867 #endif
2868 
2869 #if (TLS_MLKEM_SUPPORT == ENABLED || TLS_HYBRID_SUPPORT == ENABLED)
2870  //Release KEM context
2871  kemFree(&context->kemContext);
2872 #endif
2873 
2874 #if (TLS_RSA_SUPPORT == ENABLED)
2875  //Release peer's RSA public key
2876  rsaFreePublicKey(&context->peerRsaPublicKey);
2877 #endif
2878 
2879 #if (TLS_DSA_SIGN_SUPPORT == ENABLED)
2880  //Release peer's DSA public key
2881  dsaFreePublicKey(&context->peerDsaPublicKey);
2882 #endif
2883 
2884 #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED || TLS_SM2_SIGN_SUPPORT == ENABLED)
2885  //Release peer's EC public key
2886  ecFreePublicKey(&context->peerEcPublicKey);
2887 #endif
2888 
2889 #if (TLS_ED25519_SIGN_SUPPORT == ENABLED || TLS_ED448_SIGN_SUPPORT == ENABLED)
2890  //Release peer's EdDSA public key
2891  eddsaFreePublicKey(&context->peerEddsaPublicKey);
2892 #endif
2893 
2894 #if (TLS_PSK_SUPPORT == ENABLED)
2895  //Release the pre-shared key
2896  if(context->psk != NULL)
2897  {
2898  osMemset(context->psk, 0, context->pskLen);
2899  tlsFreeMem(context->psk);
2900  }
2901 
2902  //Release the PSK identity
2903  if(context->pskIdentity != NULL)
2904  {
2905  tlsFreeMem(context->pskIdentity);
2906  }
2907 
2908  //Release the PSK identity hint
2909  if(context->pskIdentityHint != NULL)
2910  {
2911  tlsFreeMem(context->pskIdentityHint);
2912  }
2913 #endif
2914 
2915 #if (TLS_ALPN_SUPPORT == ENABLED)
2916  //Release the list of supported ALPN protocols
2917  if(context->protocolList != NULL)
2918  {
2919  tlsFreeMem(context->protocolList);
2920  }
2921 
2922  //Release the selected ALPN protocol
2923  if(context->selectedProtocol != NULL)
2924  {
2925  tlsFreeMem(context->selectedProtocol);
2926  }
2927 #endif
2928 
2929  //Release encryption engines
2930  for(i = 0; i < TLS_MAX_ENCRYPTION_ENGINES; i++)
2931  {
2932  tlsFreeEncryptionEngine(&context->encryptionEngine[i]);
2933  }
2934 
2935  //Release decryption engines
2936  for(i = 0; i < TLS_MAX_DECRYPTION_ENGINES; i++)
2937  {
2938  tlsFreeEncryptionEngine(&context->decryptionEngine[i]);
2939  }
2940 
2941 #if (TLS_QUIC_SUPPORT == ENABLED)
2942  //Release local QUIC transport parameters
2943  if(context->localQuicTransportParams != NULL)
2944  {
2945  tlsFreeMem(context->localQuicTransportParams);
2946  }
2947 
2948  //Release remote QUIC transport parameters
2949  if(context->remoteQuicTransportParams != NULL)
2950  {
2951  tlsFreeMem(context->remoteQuicTransportParams);
2952  }
2953 #endif
2954 
2955  //Clear the TLS context before freeing memory
2956  osMemset(context, 0, sizeof(TlsContext));
2957  tlsFreeMem(context);
2958  }
2959 }
2960 
2961 
2962 /**
2963  * @brief Initialize session state
2964  * @param[in] session Pointer to the session state
2965  * @return Error code
2966  **/
2967 
2969 {
2970  //Make sure the session state is valid
2971  if(session == NULL)
2972  return ERROR_INVALID_PARAMETER;
2973 
2974  //Erase session state
2975  osMemset(session, 0, sizeof(TlsSessionState));
2976 
2977  //Successful initialization
2978  return NO_ERROR;
2979 }
2980 
2981 
2982 /**
2983  * @brief Save TLS session
2984  * @param[in] context Pointer to the TLS context
2985  * @param[out] session Pointer to the session state
2986  * @return Error code
2987  **/
2988 
2990  TlsSessionState *session)
2991 {
2992  error_t error;
2993 
2994  //Check parameters
2995  if(context == NULL || session == NULL)
2996  return ERROR_INVALID_PARAMETER;
2997 
2998  //Release previous session state
2999  tlsFreeSessionState(session);
3000 
3001 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
3002  //TLS 1.0, TLS 1.1 or TLS 1.2 currently selected?
3003  if(context->version >= TLS_VERSION_1_0 && context->version <= TLS_VERSION_1_2)
3004  {
3005  //Valid session?
3006  if(context->ticketLen > 0)
3007  {
3008  //Save session ticket
3009  error = tlsSaveSessionTicket(context, session);
3010  }
3011  else if(context->sessionIdLen > 0)
3012  {
3013  //Save session identifier
3014  error = tlsSaveSessionId(context, session);
3015  }
3016  else
3017  {
3018  //No valid session to save
3019  error = ERROR_INVALID_SESSION;
3020  }
3021  }
3022  else
3023 #endif
3024 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
3025  //TLS 1.3 currently selected?
3026  if(context->version == TLS_VERSION_1_3)
3027  {
3028  //Save session ticket
3029  error = tls13SaveSessionTicket(context, session);
3030  }
3031  else
3032 #endif
3033  //Invalid TLS version?
3034  {
3035  //Do not save session state
3036  error = ERROR_INVALID_VERSION;
3037  }
3038 
3039  //Check status code
3040  if(error)
3041  {
3042  //Clean up side effects
3043  tlsFreeSessionState(session);
3044  }
3045 
3046  //Successful processing
3047  return NO_ERROR;
3048 }
3049 
3050 
3051 /**
3052  * @brief Restore TLS session
3053  * @param[in] context Pointer to the TLS context
3054  * @param[in] session Pointer to the session state to be restored
3055  * @return Error code
3056  **/
3057 
3059  const TlsSessionState *session)
3060 {
3061  //Check parameters
3062  if(context == NULL || session == NULL)
3063  return ERROR_INVALID_PARAMETER;
3064 
3065 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
3066  //TLS 1.0, TLS 1.1 or TLS 1.2 currently selected?
3067  if(session->version >= TLS_VERSION_1_0 && session->version <= TLS_VERSION_1_2)
3068  {
3069  //Valid session?
3070  if(session->ticketLen > 0)
3071  {
3072  //Restore a TLS session using session ticket
3073  tlsRestoreSessionTicket(context, session);
3074  }
3075  else if(session->sessionIdLen > 0)
3076  {
3077  //Restore a TLS session using session ID
3078  tlsRestoreSessionId(context, session);
3079  }
3080  else
3081  {
3082  //No valid session to restore
3083  }
3084  }
3085  else
3086 #endif
3087 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
3088  //TLS 1.3 currently selected?
3089  if(session->version == TLS_VERSION_1_3)
3090  {
3091  //Restore TLS session using session ticket
3092  tls13RestoreSessionTicket(context, session);
3093  }
3094  else
3095 #endif
3096  //Invalid TLS version?
3097  {
3098  //Do not restore session state
3099  }
3100 
3101  //Successful processing
3102  return NO_ERROR;
3103 }
3104 
3105 
3106 /**
3107  * @brief Properly dispose a session state
3108  * @param[in] session Pointer to the session state to be released
3109  **/
3110 
3112 {
3113  //Make sure the session state is valid
3114  if(session != NULL)
3115  {
3116  //Release session ticket
3117  if(session->ticket != NULL)
3118  {
3119  osMemset(session->ticket, 0, session->ticketLen);
3120  tlsFreeMem(session->ticket);
3121  }
3122 
3123 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
3124  //Release the ALPN protocol associated with the ticket
3125  if(session->ticketAlpn != NULL)
3126  {
3127  tlsFreeMem(session->ticketAlpn);
3128  }
3129 #endif
3130 
3131 #if (TLS_SNI_SUPPORT == ENABLED)
3132  //Release server name
3133  if(session->serverName != NULL)
3134  {
3135  tlsFreeMem(session->serverName);
3136  }
3137 #endif
3138 
3139  //Erase session state
3140  osMemset(session, 0, sizeof(TlsSessionState));
3141  }
3142 }
3143 
3144 #endif
TlsContext * tlsInit(void)
TLS context initialization.
Definition: tls.c:68
error_t tlsSetSupportedGroups(TlsContext *context, const uint16_t *groups, uint_t length)
Specify the list of allowed ECDHE and FFDHE groups.
Definition: tls.c:650
Dtls13Ack
Definition: dtls13_misc.h:84
#define TLS_MAX_RECORD_LENGTH
Definition: tls.h:994
#define tlsAllocMem(size)
Definition: tls.h:889
size_t ticketLen
Length of the session ticket.
Definition: tls.h:2229
TLS helper functions.
X.509 certificate parsing.
error_t tlsEnableSecureRenegotiation(TlsContext *context, bool_t enabled)
Enable secure renegotiation.
Definition: tls.c:1497
error_t tlsSetConnectionEnd(TlsContext *context, TlsConnectionEnd entity)
Set operation mode (client or server)
Definition: tls.c:365
@ TLS_TRANSPORT_PROTOCOL_QUIC
Definition: tls.h:1018
error_t tlsSetMaxEarlyDataSize(TlsContext *context, size_t maxEarlyDataSize)
Send the maximum amount of 0-RTT data the server can accept.
Definition: tls.c:1705
int bool_t
Definition: compiler_port.h:63
TLS cipher suites.
void rsaFreePublicKey(RsaPublicKey *key)
Release an RSA public key.
Definition: rsa.c:113
error_t tlsSaveSessionTicket(const TlsContext *context, TlsSessionState *session)
Save session ticket.
Definition: tls_misc.c:502
error_t tlsSetTransportProtocol(TlsContext *context, TlsTransportProtocol transportProtocol)
Set the transport protocol to be used.
Definition: tls.c:334
error_t(* TlsTicketEncryptCallback)(TlsContext *context, const uint8_t *plaintext, size_t plaintextLen, uint8_t *ciphertext, size_t *ciphertextLen, void *param)
Ticket encryption callback function.
Definition: tls.h:2110
@ TLS_ALERT_CLOSE_NOTIFY
Definition: tls.h:1145
@ CIPHER_MODE_CBC
Definition: crypto.h:1063
#define DTLS_DEFAULT_PMTU
Definition: dtls_misc.h:48
error_t tls13DeriveSecret(TlsContext *context, const uint8_t *secret, size_t secretLen, const char_t *label, const char_t *message, size_t messageLen, uint8_t *output, size_t outputLen)
Derive-Secret function.
error_t(* TlsEcdsaVerifyCallback)(TlsContext *context, const uint8_t *digest, size_t digestLen, EcdsaSignature *signature)
ECDSA signature verification callback function.
Definition: tls.h:2143
Key material generation.
error_t tlsPerformHandshake(TlsContext *context)
Perform TLS handshake.
TLS handshake.
#define TLS_MAX_PASSWORD_LEN
Definition: tls.h:788
error_t dtlsTick(TlsContext *context)
Manage retransmission timers.
Definition: dtls_record.c:1633
@ ERROR_BUFFER_OVERFLOW
Definition: error.h:143
uint8_t * ticket
Session ticket.
Definition: tls.h:2228
@ ERROR_NOT_IMPLEMENTED
Definition: error.h:66
#define PrngAlgo
Definition: crypto.h:1035
error_t tlsExportChannelBinding(TlsContext *context, const char_t *type, uint8_t *output, size_t *length)
Export channel binding value.
Definition: tls.c:2038
@ TLS_EARLY_DATA_REJECTED
Definition: tls.h:1052
error_t tlsSetPskIdentityHint(TlsContext *context, const char_t *pskIdentityHint)
Set the PSK identity hint to be used by the server.
Definition: tls.c:1112
error_t tlsPrf(const uint8_t *secret, size_t secretLen, const char_t *label, const uint8_t *seed, size_t seedLen, uint8_t *output, size_t outputLen)
Pseudorandom function (TLS 1.0 and 1.1)
@ ERROR_UNEXPECTED_MESSAGE
Definition: error.h:195
TlsState
TLS FSM states.
Definition: tls.h:1557
DtlsRecord
Definition: dtls_misc.h:185
error_t tlsEnableCertAuthorities(TlsContext *context, bool_t enabled)
Enable CertificateAuthorities extension.
Definition: tls.c:1471
uint8_t p
Definition: ndp.h:300
error_t tlsSetEcdhCallback(TlsContext *context, TlsEcdhCallback ecdhCallback)
Register ECDH key agreement callback function.
Definition: tls.c:767
TlsConnectionEnd
TLS connection end.
Definition: tls.h:1028
error_t tlsSetCertificateVerifyCallback(TlsContext *context, TlsCertVerifyCallback certVerifyCallback, void *param)
Register certificate verification callback function.
Definition: tls.c:1394
#define TRUE
Definition: os_port.h:50
error_t(* DtlsCookieGenerateCallback)(TlsContext *context, const DtlsClientParameters *clientParams, uint8_t *cookie, size_t *length, void *param)
DTLS cookie generation callback function.
Definition: dtls_misc.h:247
@ TLS_ENCRYPTION_LEVEL_INITIAL
Definition: tls.h:1605
uint8_t data[]
Definition: ethernet.h:224
@ TLS_GROUP_SECP256R1
Definition: tls.h:1491
@ TLS_TYPE_HANDSHAKE
Definition: tls.h:1087
size_t digestSize
Definition: crypto.h:1157
error_t(* TlsSocketReceiveCallback)(TlsSocketHandle handle, void *data, size_t size, size_t *received, uint_t flags)
Socket receive callback function.
Definition: tls.h:2070
error_t tlsSetCache(TlsContext *context, TlsCache *cache)
Set session cache.
Definition: tls.c:494
TlsCertificateType type
End entity certificate type.
Definition: tls.h:2267
@ ERROR_OUT_OF_RESOURCES
Definition: error.h:64
TLS 1.3 session tickets.
@ TLS_TRANSPORT_PROTOCOL_DATAGRAM
Definition: tls.h:1017
void ecdhFree(EcdhContext *context)
Release ECDH context.
Definition: ecdh.c:65
error_t tlsSaveSessionId(const TlsContext *context, TlsSessionState *session)
Save session ID.
Definition: tls_misc.c:430
void kemInit(KemContext *context, const KemAlgo *kemAlgo)
Initialize KEM context.
Definition: kem.c:48
@ TLS_STATE_APPLICATION_DATA
Definition: tls.h:1589
error_t tlsEnableTrustedCaKeys(TlsContext *context, bool_t enabled)
Enable TrustedCaKeys extension.
Definition: tls.c:1444
size_t sessionIdLen
Length of the session identifier.
Definition: tls.h:2225
uint8_t type
Definition: coap_common.h:176
error_t tlsSetSupportedSignAlgos(TlsContext *context, const uint16_t *signAlgos, uint_t length)
Specify the list of allowed signature algorithms.
Definition: tls.c:705
error_t tlsSetAlpnCallback(TlsContext *context, TlsAlpnCallback alpnCallback)
Register ALPN callback function.
Definition: tls.c:949
@ ERROR_OUT_OF_MEMORY
Definition: error.h:63
@ TLS_TYPE_ACK
Definition: tls.h:1091
error_t tlsSetEcdsaSignCallback(TlsContext *context, TlsEcdsaSignCallback ecdsaSignCallback)
Register ECDSA signature generation callback function.
Definition: tls.c:793
#define osStrcmp(s1, s2)
Definition: os_port.h:174
@ ERROR_NOT_CONFIGURED
Definition: error.h:218
uint16_t totalLength
Definition: ipv4.h:348
#define osStrlen(s)
Definition: os_port.h:168
error_t tlsEnableReplayDetection(TlsContext *context, bool_t enabled)
Enable anti-replay mechanism (for DTLS only)
Definition: tls.c:1677
Session cache.
Definition: tls.h:2249
error_t tlsShutdownEx(TlsContext *context, bool_t waitForCloseNotify)
Gracefully close TLS session.
Definition: tls.c:2628
@ ERROR_END_OF_STREAM
Definition: error.h:211
error_t tlsSetPmtu(TlsContext *context, size_t pmtu)
Set PMTU value (for DTLS only)
Definition: tls.c:1583
@ ERROR_INVALID_VERSION
Definition: error.h:118
#define TLS_RANDOM_SIZE
Definition: tls.h:998
void kemFree(KemContext *context)
Release KEM context.
Definition: kem.c:62
void tlsFreeSessionState(TlsSessionState *session)
Properly dispose a session state.
Definition: tls.c:3111
@ TLS_CIPHER_SUITE_TYPE_TLS13
error_t(* TlsSocketSendCallback)(TlsSocketHandle handle, const void *data, size_t length, size_t *written, uint_t flags)
Socket send callback function.
Definition: tls.h:2062
#define DTLS_MIN_PMTU
Definition: dtls_misc.h:55
error_t tlsRestoreSessionState(TlsContext *context, const TlsSessionState *session)
Restore TLS session.
Definition: tls.c:3058
Certificate parsing options.
Definition: x509_common.h:1336
error_t pemImportDhParameters(DhParameters *params, const char_t *input, size_t length)
Decode a PEM file containing Diffie-Hellman parameters.
Definition: pem_import.c:137
@ TLS_CIPHER_SUITE_TYPE_SM
error_t(* TlsAlpnCallback)(TlsContext *context, const char_t *selectedProtocol)
ALPN callback function.
Definition: tls.h:2078
error_t tlsSetVersion(TlsContext *context, uint16_t versionMin, uint16_t versionMax)
Set minimum and maximum versions permitted.
Definition: tls.c:296
error_t(* TlsRpkVerifyCallback)(TlsContext *context, const uint8_t *rawPublicKey, size_t rawPublicKeyLen)
Raw public key verification callback function.
Definition: tls.h:2102
error_t tlsEnableFallbackScsv(TlsContext *context, bool_t enabled)
Perform fallback retry (for clients only)
Definition: tls.c:1523
@ TLS_ALERT_LEVEL_WARNING
Definition: tls.h:1134
error_t tlsSetMaxFragmentLength(TlsContext *context, size_t maxFragLen)
Set maximum fragment length.
Definition: tls.c:585
@ TLS_STATE_KEY_UPDATE
Definition: tls.h:1592
const char_t * tlsGetServerName(TlsContext *context)
Get the server name.
Definition: tls.c:469
error_t tls13SaveSessionTicket(const TlsContext *context, TlsSessionState *session)
Save session ticket.
Definition: tls13_ticket.c:89
error_t tlsShutdown(TlsContext *context)
Gracefully close TLS session.
Definition: tls.c:2615
size_t certChainLen
Length of the certificate chain.
Definition: tls.h:2263
#define FALSE
Definition: os_port.h:46
error_t tlsSetPsk(TlsContext *context, const uint8_t *psk, size_t length)
Set the pre-shared key to be used.
Definition: tls.c:1002
error_t pemImportCertificate(const char_t *input, size_t inputLen, uint8_t *output, size_t *outputLen, size_t *consumed)
Decode a PEM file containing a certificate.
Definition: pem_import.c:55
error_t tlsSendAlert(TlsContext *context, uint8_t level, uint8_t description)
Send Alert message.
Definition: tls_common.c:509
error_t tlsParseAlert(TlsContext *context, const TlsAlert *message, size_t length)
Parse Alert message.
Definition: tls_common.c:1610
PEM file import functions.
@ ERROR_INVALID_PARAMETER
Invalid parameter.
Definition: error.h:47
@ TLS_FLAG_PEEK
Definition: tls.h:1063
#define osMemcpy(dest, src, length)
Definition: os_port.h:144
const X509Options X509_DEFAULT_OPTIONS
Definition: x509_common.c:173
error_t tls13SendEarlyData(TlsContext *context, const void *data, size_t length, size_t *written)
Send early data to the remote TLS server.
X.509 certificate.
Definition: x509_common.h:1121
#define TlsContext
Definition: tls.h:36
error_t
Error codes.
Definition: error.h:43
DTLS record layer.
bool_t tls13IsGroupSupported(TlsContext *context, uint16_t namedGroup)
Check whether a given named group is supported.
Definition: tls13_misc.c:947
#define TLS_MAX_DECRYPTION_ENGINES
Definition: tls.h:981
HashAlgoCompute compute
Definition: crypto.h:1160
void ecInitPublicKey(EcPublicKey *key)
Initialize an EC public key.
Definition: ec.c:52
@ TLS_CONNECTION_END_SERVER
Definition: tls.h:1030
#define TLS_MIN_RECORD_LENGTH
Definition: tls.h:992
error_t x509ParseCertificateEx(const uint8_t *data, size_t length, X509CertInfo *certInfo, const X509Options *options)
Parse a X.509 certificate.
void tlsFreeEncryptionEngine(TlsEncryptionEngine *encryptionEngine)
Release encryption engine.
Definition: tls_misc.c:1150
void(* TlsStateChangeCallback)(TlsContext *context, TlsState state)
TLS state change callback.
Definition: tls.h:2055
TlsClientAuthMode
Client authentication mode.
Definition: tls.h:1039
error_t tlsSetTicketCallbacks(TlsContext *context, TlsTicketEncryptCallback ticketEncryptCallback, TlsTicketDecryptCallback ticketDecryptCallback, void *param)
Set ticket encryption/decryption callbacks.
Definition: tls.c:1551
#define TLS_VERSION_1_2
Definition: tls.h:97
@ TLS_FLAG_WAIT_ALL
Definition: tls.h:1064
@ TLS_GROUP_NONE
Definition: tls.h:1468
error_t tlsSetTimeout(TlsContext *context, systime_t timeout)
Set timeout for blocking calls (for DTLS only)
Definition: tls.c:1613
error_t(* TlsEcdhCallback)(TlsContext *context)
ECDH key agreement callback function.
Definition: tls.h:2128
@ ERROR_FAILURE
Generic error code.
Definition: error.h:45
#define TLS_MAX_VERSION
Definition: tls.h:137
TlsEarlyDataStatus tlsGetEarlyDataStatus(TlsContext *context)
Check whether the server has accepted or rejected the early data.
Definition: tls.c:1847
TlsAlert
Definition: tls.h:2016
#define STORE16BE(a, p)
Definition: cpu_endian.h:262
#define TLS_MIN_VERSION
Definition: tls.h:130
@ TLS_TYPE_APPLICATION_DATA
Definition: tls.h:1088
Helper functions for TLS 1.3 client.
DTLS 1.3 (Datagram Transport Layer Security)
@ TLS_TYPE_ALERT
Definition: tls.h:1086
#define TLS_VERSION_1_3
Definition: tls.h:98
@ TLS_STATE_EARLY_DATA
Definition: tls.h:1561
Handshake message processing (TLS client and server)
void dhFree(DhContext *context)
Release Diffie-Hellman context.
Definition: dh.c:71
TlsSignatureScheme signScheme
Signature scheme used to sign the end entity certificate.
Definition: tls.h:2268
bool_t tlsIsTxReady(TlsContext *context)
Check whether some data is ready for transmission.
Definition: tls.c:2536
error_t tlsSetPreferredGroup(TlsContext *context, uint16_t group)
Specify the preferred ECDHE or FFDHE group.
Definition: tls.c:677
TLS record protocol.
#define TLS_MAX_CERTIFICATES
Definition: tls.h:284
error_t tlsReadProtocolData(TlsContext *context, uint8_t **data, size_t *length, TlsContentType *contentType)
Read protocol data.
Definition: tls_record.c:157
@ TLS_TRANSPORT_PROTOCOL_EAP
Definition: tls.h:1019
@ TLS_STATE_SERVER_HELLO_3
Definition: tls.h:1566
@ TLS_HASH_ALGO_SHA256
Definition: tls.h:1281
error_t tlsEnableSessionTickets(TlsContext *context, bool_t enabled)
Enable session ticket mechanism.
Definition: tls.c:1418
@ ERROR_INVALID_TYPE
Definition: error.h:115
error_t dtlsWriteProtocolData(TlsContext *context, const uint8_t *data, size_t length, TlsContentType contentType)
Write protocol data.
Definition: dtls_record.c:62
error_t tlsSaveSessionState(const TlsContext *context, TlsSessionState *session)
Save TLS session.
Definition: tls.c:2989
uint8_t length
Definition: tcp.h:375
#define LSB(x)
Definition: os_port.h:55
error_t tlsRead(TlsContext *context, void *data, size_t size, size_t *received, uint_t flags)
Receive application data from a the remote host using TLS.
Definition: tls.c:2280
@ TLS_CLIENT_AUTH_NONE
Definition: tls.h:1040
#define MIN(a, b)
Definition: os_port.h:63
error_t tlsSetKeyLogCallback(TlsContext *context, TlsKeyLogCallback keyLogCallback)
Register key logging callback function (for debugging purpose only)
Definition: tls.c:847
error_t(* TlsCertVerifyCallback)(TlsContext *context, const X509CertInfo *certInfo, uint_t pathLen, void *param)
Certificate verification callback function.
Definition: tls.h:2094
error_t tls12Prf(const HashAlgo *hash, const uint8_t *secret, size_t secretLen, const char_t *label, const uint8_t *seed, size_t seedLen, uint8_t *output, size_t outputLen)
Pseudorandom function (TLS 1.2)
error_t tlsWriteEarlyData(TlsContext *context, const void *data, size_t length, size_t *written, uint_t flags)
Send early data to the remote TLS server.
Definition: tls.c:1734
TlsCertificateType
Certificate types.
Definition: tls.h:1250
error_t tlsSetServerName(TlsContext *context, const char_t *serverName)
Set the server name.
Definition: tls.c:419
#define TLS_MASTER_SECRET_SIZE
Definition: tls.h:837
size_t privateKeyLen
Length of the private key.
Definition: tls.h:2265
Certificate descriptor.
Definition: tls.h:2261
Transcript hash calculation.
uint8_t secret[TLS_MASTER_SECRET_SIZE]
Master secret.
Definition: tls.h:2027
@ TLS_FLAG_BREAK_CHAR
Definition: tls.h:1065
error_t tlsRestoreSessionId(TlsContext *context, const TlsSessionState *session)
Restore a TLS session using session ID.
Definition: tls_misc.c:556
char_t * serverName
ServerName extension.
Definition: tls.h:2239
uint32_t systime_t
System time.
error_t tlsSetRpkVerifyCallback(TlsContext *context, TlsRpkVerifyCallback rpkVerifyCallback)
Register the raw public key verification callback function.
Definition: tls.c:1187
error_t tlsSetEcdsaVerifyCallback(TlsContext *context, TlsEcdsaVerifyCallback ecdsaVerifyCallback)
Register ECDSA signature verification callback function.
Definition: tls.c:820
bool_t tlsIsRxReady(TlsContext *context)
Check whether some data is available in the receive buffer.
Definition: tls.c:2570
TlsRecord
Definition: tls.h:1885
@ TLS_TYPE_NONE
Definition: tls.h:1084
void ecdhInit(EcdhContext *context)
Initialize ECDH context.
Definition: ecdh.c:49
#define MAX(a, b)
Definition: os_port.h:67
error_t(* TlsEcdsaSignCallback)(TlsContext *context, const uint8_t *digest, size_t digestLen, EcdsaSignature *signature)
ECDSA signature generation callback function.
Definition: tls.h:2135
char char_t
Definition: compiler_port.h:55
error_t dtls13ParseAck(TlsContext *context, const Dtls13Ack *message, size_t length)
Parse ACK message.
Definition: dtls13_misc.c:257
#define TLS_VERSION_1_1
Definition: tls.h:96
TlsContentType
Content type.
Definition: tls.h:1083
@ TLS_STATE_CLOSING
Definition: tls.h:1594
@ TLS_EARLY_DATA_ACCEPTED
Definition: tls.h:1053
error_t dtlsReadProtocolData(TlsContext *context, uint8_t **data, size_t *length, TlsContentType *contentType)
Read protocol data.
Definition: dtls_record.c:167
error_t tlsSetBufferSize(TlsContext *context, size_t txBufferSize, size_t rxBufferSize)
Set TLS buffer size.
Definition: tls.c:537
TLS session state.
Definition: tls.h:2218
@ ERROR_NOT_CONNECTED
Definition: error.h:80
uint8_t n
error_t tlsParseHandshakeMessage(TlsContext *context, const uint8_t *message, size_t length)
Parse handshake message.
TlsTransportProtocol
TLS transport protocols.
Definition: tls.h:1015
TlsState tlsGetState(TlsContext *context)
Retrieve current TLS state.
Definition: tls.c:214
error_t(* DtlsCookieVerifyCallback)(TlsContext *context, const DtlsClientParameters *clientParams, const uint8_t *cookie, size_t length, void *param)
DTLS cookie verification callback function.
Definition: dtls_misc.h:256
error_t tlsSetStateChangeCallback(TlsContext *context, TlsStateChangeCallback stateChangeCallback)
Register TLS state change callback.
Definition: tls.c:240
#define TLS_VERSION_1_0
Definition: tls.h:95
char_t password[TLS_MAX_PASSWORD_LEN+1]
Password used to decrypt the private key.
Definition: tls.h:2266
@ TLS_STATE_INIT
Definition: tls.h:1558
error_t tlsGetCertificateSignAlgo(const X509CertInfo *certInfo, TlsSignatureScheme *signScheme)
Retrieve the signature algorithm used to sign the certificate.
error_t tlsSetPskCallback(TlsContext *context, TlsPskCallback pskCallback)
Register PSK callback function.
Definition: tls.c:1161
error_t tlsWriteProtocolData(TlsContext *context, const uint8_t *data, size_t length, TlsContentType contentType)
Write protocol data.
Definition: tls_record.c:54
@ TLS_STATE_CLIENT_FINISHED_ACK
Definition: tls.h:1590
error_t tlsSetSocketCallbacks(TlsContext *context, TlsSocketSendCallback socketSendCallback, TlsSocketReceiveCallback socketReceiveCallback, TlsSocketHandle handle)
Set socket send and receive callbacks.
Definition: tls.c:264
#define TLS_MAX_HKDF_DIGEST_SIZE
Definition: tls.h:965
error_t tlsSetCipherSuites(TlsContext *context, const uint16_t *cipherSuites, uint_t length)
Specify the list of allowed cipher suites.
Definition: tls.c:621
@ TLS_CONNECTION_END_CLIENT
Definition: tls.h:1029
X.509 certificate handling.
error_t tlsWrite(TlsContext *context, const void *data, size_t length, size_t *written, uint_t flags)
Send application data to the remote host using TLS.
Definition: tls.c:2139
TLS (Transport Layer Security)
uint16_t version
TLS protocol version.
Definition: tls.h:2219
void eddsaFreePublicKey(EddsaPublicKey *key)
Release an EdDSA public key.
Definition: eddsa.c:63
#define osTolower(c)
Definition: os_port.h:270
uint8_t options[]
Definition: tcp.h:364
@ TLS_GROUP_X25519
Definition: tls.h:1497
error_t tlsSetAlpnProtocolList(TlsContext *context, const char_t *protocolList)
Set the list of supported ALPN protocols.
Definition: tls.c:900
error_t tlsLoadCertificate(TlsContext *context, uint_t index, const char_t *certChain, size_t certChainLen, const char_t *privateKey, size_t privateKeyLen, const char_t *password)
Load entity's certificate.
Definition: tls.c:1250
@ TLS_TRANSPORT_PROTOCOL_STREAM
Definition: tls.h:1016
error_t tlsTick(TlsContext *context)
Handle periodic operations.
Definition: tls.c:2778
@ ERROR_INVALID_PASSWORD
Definition: error.h:281
void tlsFree(TlsContext *context)
Release TLS context.
Definition: tls.c:2807
TLS 1.3 key schedule.
const char_t * certChain
End entity certificate chain (PEM format)
Definition: tls.h:2262
Common interface for hash algorithms.
Definition: crypto.h:1151
error_t(* TlsPskCallback)(TlsContext *context, const uint8_t *pskIdentity, size_t pskIdentityLen)
Pre-shared key callback function.
Definition: tls.h:2086
error_t tlsSetClientAuthMode(TlsContext *context, TlsClientAuthMode mode)
Set client authentication mode (for servers only)
Definition: tls.c:515
const char_t * tlsGetAlpnProtocol(TlsContext *context)
Get the name of the selected ALPN protocol.
Definition: tls.c:974
error_t tlsGetCertificateType(const X509CertInfo *certInfo, TlsCertificateType *certType, TlsNamedGroup *namedCurve)
Retrieve the certificate type.
void tlsProcessError(TlsContext *context, error_t errorCode)
Translate an error code to an alert message.
Definition: tls_misc.c:74
error_t tls13HkdfExpandLabel(TlsTransportProtocol transportProtocol, const HashAlgo *hash, const uint8_t *secret, size_t secretLen, const char_t *label, const uint8_t *context, size_t contextLen, uint8_t *output, size_t outputLen)
HKDF-Expand-Label function.
uint8_t flags
Definition: tcp.h:358
error_t tlsAllowUnknownAlpnProtocols(TlsContext *context, bool_t allowed)
Allow unknown ALPN protocols.
Definition: tls.c:874
void tlsChangeState(TlsContext *context, TlsState newState)
Update TLS state.
Definition: tls_misc.c:54
TlsNamedGroup
Named groups.
Definition: tls.h:1467
error_t tlsSetCookieCallbacks(TlsContext *context, DtlsCookieGenerateCallback cookieGenerateCallback, DtlsCookieVerifyCallback cookieVerifyCallback, void *param)
Set cookie generation/verification callbacks (for DTLS only)
Definition: tls.c:1641
const char_t * privateKey
Private key (PEM format)
Definition: tls.h:2264
TlsSignatureScheme
Signature schemes.
Definition: tls.h:1311
void(* TlsKeyLogCallback)(TlsContext *context, const char_t *key)
Key logging callback function (for debugging purpose only)
Definition: tls.h:2151
error_t tlsSetPrng(TlsContext *context, const PrngAlgo *prngAlgo, void *prngContext)
Set the pseudo-random number generator to be used.
Definition: tls.c:391
unsigned int uint_t
Definition: compiler_port.h:57
#define osMemset(p, value, length)
Definition: os_port.h:138
#define tlsFreeMem(p)
Definition: tls.h:894
#define TLS_MAX_RECORD_OVERHEAD
Definition: tls.h:996
error_t tlsSetTrustedCaList(TlsContext *context, const char_t *trustedCaList, size_t length)
Import a trusted CA list.
Definition: tls.c:1215
@ TLS_STATE_KEY_UPDATE_ACK
Definition: tls.h:1593
#define TLS_MAX_ENCRYPTION_ENGINES
Definition: tls.h:972
void eddsaInitPublicKey(EddsaPublicKey *key)
Initialize an EdDSA public key.
Definition: eddsa.c:48
error_t tlsExportKeyingMaterial(TlsContext *context, const char_t *label, bool_t useContextValue, const uint8_t *contextValue, size_t contextValueLen, uint8_t *output, size_t outputLen)
Export keying material per RFC 5705 standard.
Definition: tls.c:1893
error_t tlsInitSessionState(TlsSessionState *session)
Initialize session state.
Definition: tls.c:2968
error_t(* TlsTicketDecryptCallback)(TlsContext *context, const uint8_t *ciphertext, size_t ciphertextLen, uint8_t *plaintext, size_t *plaintextLen, void *param)
Ticket decryption callback function.
Definition: tls.h:2119
#define osStrcpy(s1, s2)
Definition: os_port.h:210
void dhInit(DhContext *context)
Initialize Diffie-Hellman context.
Definition: dh.c:54
error_t tlsSetPskIdentity(TlsContext *context, const char_t *pskIdentity)
Set the PSK identity to be used by the client.
Definition: tls.c:1063
error_t tlsConnect(TlsContext *context)
Initiate the TLS handshake.
Definition: tls.c:1799
void dsaFreePublicKey(DsaPublicKey *key)
Release a DSA public key.
Definition: dsa.c:119
@ ERROR_INVALID_SESSION
Definition: error.h:287
error_t tls13RestoreSessionTicket(TlsContext *context, const TlsSessionState *session)
Restore a TLS session using session ticket.
Definition: tls13_ticket.c:187
TlsNamedGroup namedCurve
Named curve used to generate the EC public key.
Definition: tls.h:2269
void dsaInitPublicKey(DsaPublicKey *key)
Initialize a DSA public key.
Definition: dsa.c:105
error_t tlsSetDhParameters(TlsContext *context, const char_t *params, size_t length)
Import Diffie-Hellman parameters.
Definition: tls.c:739
@ NO_ERROR
Success.
Definition: error.h:44
uint8_t c
Definition: ndp.h:514
Debugging facilities.
@ TLS_STATE_NEW_SESSION_TICKET_ACK
Definition: tls.h:1591
void rsaInitPublicKey(RsaPublicKey *key)
Initialize an RSA public key.
Definition: rsa.c:100
void * TlsSocketHandle
Socket handle.
Definition: tls.h:2048
void ecFreePublicKey(EcPublicKey *key)
Release an EC public key.
Definition: ec.c:68
TlsEarlyDataStatus
Early data status.
Definition: tls.h:1051
char_t * ticketAlpn
ALPN protocol associated with the ticket.
Definition: tls.h:2235
void tlsFreeTranscriptHash(TlsContext *context)
Release transcript hash context.
#define INFINITE_DELAY
Definition: os_port.h:75
systime_t osGetSystemTime(void)
Retrieve system time.
error_t tlsRestoreSessionTicket(TlsContext *context, const TlsSessionState *session)
Restore a TLS session using session ticket.
Definition: tls_misc.c:605
@ TLS_STATE_CLOSED
Definition: tls.h:1595