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-2022 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.2.0
35  **/
36 
37 //Switch to the appropriate trace level
38 #define TRACE_LEVEL TLS_TRACE_LEVEL
39 
40 //Dependencies
41 #include <string.h>
42 #include <ctype.h>
43 #include "tls.h"
44 #include "tls_handshake.h"
45 #include "tls_common.h"
46 #include "tls_certificate.h"
47 #include "tls_transcript_hash.h"
48 #include "tls_record.h"
49 #include "tls_misc.h"
50 #include "tls13_client_misc.h"
51 #include "tls13_ticket.h"
52 #include "dtls_record.h"
53 #include "pkix/pem_import.h"
54 #include "pkix/x509_cert_parse.h"
55 #include "debug.h"
56 
57 //Check TLS library configuration
58 #if (TLS_SUPPORT == ENABLED)
59 
60 
61 /**
62  * @brief TLS context initialization
63  * @return Handle referencing the fully initialized TLS context
64  **/
65 
67 {
68  TlsContext *context;
69 
70  //Allocate a memory buffer to hold the TLS context
71  context = tlsAllocMem(sizeof(TlsContext));
72 
73  //Successful memory allocation?
74  if(context != NULL)
75  {
76  //Clear TLS context
77  osMemset(context, 0, sizeof(TlsContext));
78 
79  //Default state
80  context->state = TLS_STATE_INIT;
81  //Default transport protocol
82  context->transportProtocol = TLS_TRANSPORT_PROTOCOL_STREAM;
83  //Default operation mode
84  context->entity = TLS_CONNECTION_END_CLIENT;
85  //Default client authentication mode
86  context->clientAuthMode = TLS_CLIENT_AUTH_NONE;
87 
88  //Minimum and maximum versions accepted by the implementation
89  context->versionMin = TLS_MIN_VERSION;
90  context->versionMax = TLS_MAX_VERSION;
91 
92  //Default record layer version number
93  context->version = TLS_MIN_VERSION;
94  context->encryptionEngine.version = TLS_MIN_VERSION;
95 
96 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
97  //Select default named group
99  {
100  context->preferredGroup = TLS_GROUP_ECDH_X25519;
101  }
102  else if(tls13IsGroupSupported(context, TLS_GROUP_SECP256R1))
103  {
104  context->preferredGroup = TLS_GROUP_SECP256R1;
105  }
106  else
107  {
108  context->preferredGroup = TLS_GROUP_NONE;
109  }
110 #endif
111 
112 #if (DTLS_SUPPORT == ENABLED)
113  //Default PMTU
114  context->pmtu = DTLS_DEFAULT_PMTU;
115  //Default timeout
116  context->timeout = INFINITE_DELAY;
117 #endif
118 
119 #if (DTLS_SUPPORT == ENABLED && DTLS_REPLAY_DETECTION_SUPPORT == ENABLED)
120  //Anti-replay mechanism is enabled by default
121  context->replayDetectionEnabled = TRUE;
122 #endif
123 
124 #if (TLS_DH_SUPPORT == ENABLED)
125  //Initialize Diffie-Hellman context
126  dhInit(&context->dhContext);
127 #endif
128 
129 #if (TLS_ECDH_SUPPORT == ENABLED)
130  //Initialize ECDH context
131  ecdhInit(&context->ecdhContext);
132 #endif
133 
134 #if (TLS_RSA_SUPPORT == ENABLED)
135  //Initialize peer's RSA public key
136  rsaInitPublicKey(&context->peerRsaPublicKey);
137 #endif
138 
139 #if (TLS_DSA_SIGN_SUPPORT == ENABLED)
140  //Initialize peer's DSA public key
141  dsaInitPublicKey(&context->peerDsaPublicKey);
142 #endif
143 
144 #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED || TLS_EDDSA_SIGN_SUPPORT == ENABLED)
145  //Initialize peer's EC domain parameters
146  ecInitDomainParameters(&context->peerEcParams);
147  //Initialize peer's EC public key
148  ecInitPublicKey(&context->peerEcPublicKey);
149 #endif
150 
151  //Maximum number of plaintext data the TX and RX buffers can hold
152  context->txBufferMaxLen = TLS_MAX_RECORD_LENGTH;
153  context->rxBufferMaxLen = TLS_MAX_RECORD_LENGTH;
154 
155 #if (TLS_MAX_FRAG_LEN_SUPPORT == ENABLED)
156  //Maximum fragment length
157  context->maxFragLen = TLS_MAX_RECORD_LENGTH;
158 #endif
159 #if (TLS_RECORD_SIZE_LIMIT_SUPPORT == ENABLED)
160  //Maximum record size the peer is willing to receive
161  context->recordSizeLimit = TLS_MAX_RECORD_LENGTH;
162 #endif
163 
164 #if (DTLS_SUPPORT == ENABLED)
165  //Calculate the required size for the TX buffer
166  context->txBufferSize = context->txBufferMaxLen + sizeof(DtlsRecord) +
168 
169  //Calculate the required size for the RX buffer
170  context->rxBufferSize = context->rxBufferMaxLen + sizeof(DtlsRecord) +
172 #else
173  //Calculate the required size for the TX buffer
174  context->txBufferSize = context->txBufferMaxLen + sizeof(TlsRecord) +
176 
177  //Calculate the required size for the RX buffer
178  context->rxBufferSize = context->rxBufferMaxLen + sizeof(TlsRecord) +
180 #endif
181  }
182 
183  //Return a pointer to the freshly created TLS context
184  return context;
185 }
186 
187 
188 /**
189  * @brief Retrieve current state
190  * @param[in] context Pointer to the TLS context
191  * @return Current TLS state
192  **/
193 
195 {
196  TlsState state;
197 
198  //Valid TLS context?
199  if(context != NULL)
200  state = context->state;
201  else
202  state = TLS_STATE_INIT;
203 
204  //Return current state
205  return state;
206 }
207 
208 
209 /**
210  * @brief Set socket send and receive callbacks
211  * @param[in] context Pointer to the TLS context
212  * @param[in] socketSendCallback Send callback function
213  * @param[in] socketReceiveCallback Receive callback function
214  * @param[in] handle Socket handle
215  * @return Error code
216  **/
217 
219  TlsSocketSendCallback socketSendCallback,
220  TlsSocketReceiveCallback socketReceiveCallback, TlsSocketHandle handle)
221 {
222  //Invalid TLS context?
223  if(context == NULL)
225 
226  //Check parameters
227  if(socketSendCallback == NULL || socketReceiveCallback == NULL)
229 
230  //Save send and receive callback functions
231  context->socketSendCallback = socketSendCallback;
232  context->socketReceiveCallback = socketReceiveCallback;
233 
234  //This socket handle will be directly passed to the callback functions
235  context->socketHandle = handle;
236 
237  //Successful processing
238  return NO_ERROR;
239 }
240 
241 
242 /**
243  * @brief Set minimum and maximum versions permitted
244  * @param[in] context Pointer to the TLS context
245  * @param[in] versionMin Minimum version accepted by the TLS implementation
246  * @param[in] versionMax Maximum version accepted by the TLS implementation
247  * @return Error code
248  **/
249 
250 error_t tlsSetVersion(TlsContext *context, uint16_t versionMin,
251  uint16_t versionMax)
252 {
253  //Invalid TLS context?
254  if(context == NULL)
256 
257  //Check parameters
258  if(versionMin < TLS_MIN_VERSION || versionMax > TLS_MAX_VERSION)
260  if(versionMin > versionMax)
262 
263  //Minimum version accepted by the implementation
264  context->versionMin = versionMin;
265  //Maximum version accepted by the implementation
266  context->versionMax = versionMax;
267 
268  //Default record layer version number
269  context->version = context->versionMin;
270  context->encryptionEngine.version = context->versionMin;
271 
272  //Successful processing
273  return NO_ERROR;
274 }
275 
276 
277 /**
278  * @brief Set the transport protocol to be used
279  * @param[in] context Pointer to the TLS context
280  * @param[in] transportProtocol Transport protocol to be used
281  * @return Error code
282  **/
283 
285  TlsTransportProtocol transportProtocol)
286 {
287  //Invalid TLS context?
288  if(context == NULL)
290 
291  //Check parameters
292  if(transportProtocol != TLS_TRANSPORT_PROTOCOL_STREAM &&
293  transportProtocol != TLS_TRANSPORT_PROTOCOL_DATAGRAM)
294  {
296  }
297 
298  //Set transport protocol
299  context->transportProtocol = transportProtocol;
300 
301  //Successful processing
302  return NO_ERROR;
303 }
304 
305 
306 /**
307  * @brief Set operation mode (client or server)
308  * @param[in] context Pointer to the TLS context
309  * @param[in] entity Specifies whether this entity is considered a client or a server
310  * @return Error code
311  **/
312 
314 {
315  //Invalid TLS context?
316  if(context == NULL)
318 
319  //Check parameters
320  if(entity != TLS_CONNECTION_END_CLIENT && entity != TLS_CONNECTION_END_SERVER)
322 
323  //Check whether TLS operates as a client or a server
324  context->entity = entity;
325 
326  //Successful processing
327  return NO_ERROR;
328 }
329 
330 
331 /**
332  * @brief Set the pseudo-random number generator to be used
333  * @param[in] context Pointer to the TLS context
334  * @param[in] prngAlgo PRNG algorithm
335  * @param[in] prngContext Pointer to the PRNG context
336  * @return Error code
337  **/
338 
339 error_t tlsSetPrng(TlsContext *context, const PrngAlgo *prngAlgo,
340  void *prngContext)
341 {
342  //Invalid TLS context?
343  if(context == NULL)
345 
346  //Check parameters
347  if(prngAlgo == NULL || prngContext == NULL)
349 
350  //PRNG algorithm that will be used to generate random numbers
351  context->prngAlgo = prngAlgo;
352  //PRNG context
353  context->prngContext = prngContext;
354 
355  //Successful processing
356  return NO_ERROR;
357 }
358 
359 
360 /**
361  * @brief Set the server name
362  * @param[in] context Pointer to the TLS context
363  * @param[in] serverName Fully qualified domain name of the server
364  * @return Error code
365  **/
366 
367 error_t tlsSetServerName(TlsContext *context, const char_t *serverName)
368 {
369  size_t i;
370  size_t length;
371 
372  //Check parameters
373  if(context == NULL || serverName == NULL)
375 
376  //Retrieve the length of the server name
377  length = osStrlen(serverName);
378 
379  //Check whether the server name has already been configured
380  if(context->serverName != NULL)
381  {
382  //Release memory
383  tlsFreeMem(context->serverName);
384  context->serverName = NULL;
385  }
386 
387  //Valid server name?
388  if(length > 0)
389  {
390  //Allocate a memory block to hold the hostname
391  context->serverName = tlsAllocMem(length + 1);
392  //Failed to allocate memory?
393  if(context->serverName == NULL)
394  return ERROR_OUT_OF_MEMORY;
395 
396  //Convert the hostname into lowercase
397  for(i = 0; i < length; i++)
398  context->serverName[i] = osTolower(serverName[i]);
399 
400  //Properly terminate the string with a NULL character
401  context->serverName[length] = '\0';
402  }
403 
404  //Successful processing
405  return NO_ERROR;
406 }
407 
408 
409 /**
410  * @brief Get the server name
411  * @param[in] context Pointer to the TLS context
412  * @return Fully qualified domain name of the server
413  **/
414 
416 {
417  static const char_t defaultServerName[] = "";
418 
419  //Valid protocol name?
420  if(context != NULL && context->serverName != NULL)
421  {
422  //Return the fully qualified domain name of the server
423  return context->serverName;
424  }
425  else
426  {
427  //Return an empty string
428  return defaultServerName;
429  }
430 }
431 
432 
433 /**
434  * @brief Set session cache
435  * @param[in] context Pointer to the TLS context
436  * @param[in] cache Session cache that will be used to save/resume TLS sessions
437  * @return Error code
438  **/
439 
441 {
442  //Check parameters
443  if(context == NULL)
445 
446  //The cache will be used to save/resume TLS sessions
447  context->cache = cache;
448 
449  //Successful processing
450  return NO_ERROR;
451 }
452 
453 
454 /**
455  * @brief Set client authentication mode (for servers only)
456  * @param[in] context Pointer to the TLS context
457  * @param[in] mode Client authentication mode
458  * @return Error code
459  **/
460 
462 {
463  //Invalid TLS context?
464  if(context == NULL)
466 
467  //Save client authentication mode
468  context->clientAuthMode = mode;
469 
470  //Successful processing
471  return NO_ERROR;
472 }
473 
474 
475 /**
476  * @brief Set TLS buffer size
477  * @param[in] context Pointer to the TLS context
478  * @param[in] txBufferSize TX buffer size
479  * @param[in] rxBufferSize RX buffer size
480  * @return Error code
481  **/
482 
483 error_t tlsSetBufferSize(TlsContext *context, size_t txBufferSize,
484  size_t rxBufferSize)
485 {
486  //Invalid TLS context?
487  if(context == NULL)
489 
490  //Check parameters
491  if(txBufferSize < TLS_MIN_RECORD_LENGTH ||
492  rxBufferSize < TLS_MIN_RECORD_LENGTH)
493  {
495  }
496 
497  //Maximum number of plaintext data the TX and RX buffers can hold
498  context->txBufferMaxLen = txBufferSize;
499  context->rxBufferMaxLen = rxBufferSize;
500 
501 #if (DTLS_SUPPORT == ENABLED)
502  //Calculate the required size for the TX buffer
503  context->txBufferSize = txBufferSize + sizeof(DtlsRecord) +
505 
506  //Calculate the required size for the RX buffer
507  context->rxBufferSize = rxBufferSize + sizeof(DtlsRecord) +
509 #else
510  //Calculate the required size for the TX buffer
511  context->txBufferSize = txBufferSize + sizeof(TlsRecord) +
513 
514  //Calculate the required size for the RX buffer
515  context->rxBufferSize = rxBufferSize + sizeof(TlsRecord) +
517 #endif
518 
519  //Successful processing
520  return NO_ERROR;
521 }
522 
523 
524 /**
525  * @brief Set maximum fragment length
526  * @param[in] context Pointer to the TLS context
527  * @param[in] maxFragLen Maximum fragment length
528  * @return Error code
529  **/
530 
531 error_t tlsSetMaxFragmentLength(TlsContext *context, size_t maxFragLen)
532 {
533 #if (TLS_MAX_FRAG_LEN_SUPPORT == ENABLED)
534  //Invalid TLS context?
535  if(context == NULL)
537 
538  //Make sure the specified value is acceptable (ref to RFC 6066, section 4)
539  if(maxFragLen != 512 && maxFragLen != 1024 &&
540  maxFragLen != 2048 && maxFragLen != 4096 &&
541  maxFragLen != 16384)
542  {
544  }
545 
546  //Set maximum fragment length
547  context->maxFragLen = maxFragLen;
548 
549  //Successful processing
550  return NO_ERROR;
551 #else
552  //Not implemented
553  return ERROR_NOT_IMPLEMENTED;
554 #endif
555 }
556 
557 
558 /**
559  * @brief Specify the list of allowed cipher suites
560  * @param[in] context Pointer to the TLS context
561  * @param[in] cipherSuites List of allowed cipher suites (most preferred
562  * first). This parameter is taken as reference
563  * @param[in] length Number of cipher suites in the list
564  * @return Error code
565  **/
566 
567 error_t tlsSetCipherSuites(TlsContext *context, const uint16_t *cipherSuites,
568  uint_t length)
569 {
570  //Invalid TLS context?
571  if(context == NULL)
573 
574  //Check parameters
575  if(cipherSuites == NULL && length != 0)
577 
578  //Restrict the cipher suites that can be used
579  context->cipherSuites = cipherSuites;
580  context->numCipherSuites = length;
581 
582  //Successful processing
583  return NO_ERROR;
584 }
585 
586 
587 /**
588  * @brief Specify the list of allowed ECDHE and FFDHE groups
589  * @param[in] context Pointer to the TLS context
590  * @param[in] groups List of named groups (most preferred first). This
591  * parameter is taken as reference
592  * @param[in] length Number of named groups in the list
593  * @return Error code
594  **/
595 
596 error_t tlsSetSupportedGroups(TlsContext *context, const uint16_t *groups,
597  uint_t length)
598 {
599  //Invalid TLS context?
600  if(context == NULL)
602 
603  //Check parameters
604  if(groups == NULL && length != 0)
606 
607  //Restrict the named groups that can be used
608  context->supportedGroups = groups;
609  context->numSupportedGroups = length;
610 
611  //Successful processing
612  return NO_ERROR;
613 }
614 
615 
616 /**
617  * @brief Specify the preferred ECDHE or FFDHE group
618  * @param[in] context Pointer to the TLS context
619  * @param[in] group Preferred ECDHE or FFDHE named group
620  * @return Error code
621  **/
622 
624 {
625 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
626  //Invalid TLS context?
627  if(context == NULL)
629 
630  //Save the preferred named group
631  context->preferredGroup = group;
632 
633  //Successful processing
634  return NO_ERROR;
635 #else
636  //Not implemented
637  return ERROR_NOT_IMPLEMENTED;
638 #endif
639 }
640 
641 
642 /**
643  * @brief Import Diffie-Hellman parameters
644  * @param[in] context Pointer to the TLS context
645  * @param[in] params PEM structure that holds Diffie-Hellman parameters. This
646  * parameter is taken as reference
647  * @param[in] length Total length of the DER structure
648  * @return Error code
649  **/
650 
651 error_t tlsSetDhParameters(TlsContext *context, const char_t *params,
652  size_t length)
653 {
654 #if (TLS_DH_SUPPORT == ENABLED)
655  //Invalid TLS context?
656  if(context == NULL)
658 
659  //Check parameters
660  if(params == NULL && length != 0)
662 
663  //Decode the PEM structure that holds Diffie-Hellman parameters
664  return pemImportDhParameters(params, length, &context->dhContext.params);
665 #else
666  //Diffie-Hellman is not implemented
667  return ERROR_NOT_IMPLEMENTED;
668 #endif
669 }
670 
671 
672 /**
673  * @brief Register ECDH key agreement callback function
674  * @param[in] context Pointer to the TLS context
675  * @param[in] ecdhCallback ECDH callback function
676  * @return Error code
677  **/
678 
680 {
681 #if (TLS_ECC_CALLBACK_SUPPORT == ENABLED)
682  //Check parameters
683  if(context == NULL || ecdhCallback == NULL)
685 
686  //Save the ECDH key agreement callback function
687  context->ecdhCallback = ecdhCallback;
688 
689  //Successful processing
690  return NO_ERROR;
691 #else
692  //PSK key exchange is not implemented
693  return ERROR_NOT_IMPLEMENTED;
694 #endif
695 }
696 
697 
698 /**
699  * @brief ECDSA signature generation callback function
700  * @param[in] context Pointer to the TLS context
701  * @param[in] ecdsaSignCallback ECDSA signature generation callback function
702  * @return Error code
703  **/
704 
706  TlsEcdsaSignCallback ecdsaSignCallback)
707 {
708 #if (TLS_ECC_CALLBACK_SUPPORT == ENABLED)
709  //Check parameters
710  if(context == NULL || ecdsaSignCallback == NULL)
712 
713  //Save the ECDSA signature generation callback function
714  context->ecdsaSignCallback = ecdsaSignCallback;
715 
716  //Successful processing
717  return NO_ERROR;
718 #else
719  //PSK key exchange is not implemented
720  return ERROR_NOT_IMPLEMENTED;
721 #endif
722 }
723 
724 
725 /**
726  * @brief Register ECDSA signature verification callback function
727  * @param[in] context Pointer to the TLS context
728  * @param[in] ecdsaVerifyCallback ECDSA signature verification callback function
729  * @return Error code
730  **/
731 
733  TlsEcdsaVerifyCallback ecdsaVerifyCallback)
734 {
735 #if (TLS_ECC_CALLBACK_SUPPORT == ENABLED)
736  //Check parameters
737  if(context == NULL || ecdsaVerifyCallback == NULL)
739 
740  //Save the ECDSA signature verification callback function
741  context->ecdsaVerifyCallback = ecdsaVerifyCallback;
742 
743  //Successful processing
744  return NO_ERROR;
745 #else
746  //PSK key exchange is not implemented
747  return ERROR_NOT_IMPLEMENTED;
748 #endif
749 }
750 
751 
752 /**
753  * @brief Register key logging callback function (for debugging purpose only)
754  * @param[in] context Pointer to the TLS context
755  * @param[in] keyLogCallback Key logging callback function
756  * @return Error code
757  **/
758 
760  TlsKeyLogCallback keyLogCallback)
761 {
762 #if (TLS_KEY_LOG_SUPPORT == ENABLED)
763  //Check parameters
764  if(context == NULL || keyLogCallback == NULL)
766 
767  //Save the key logging callback function
768  context->keyLogCallback = keyLogCallback;
769 
770  //Successful processing
771  return NO_ERROR;
772 #else
773  //Key logging is not implemented
774  return ERROR_NOT_IMPLEMENTED;
775 #endif
776 }
777 
778 
779 /**
780  * @brief Allow unknown ALPN protocols
781  * @param[in] context Pointer to the TLS context
782  * @param[in] allowed Specifies whether unknown ALPN protocols are allowed
783  * @return Error code
784  **/
785 
787 {
788 #if (TLS_ALPN_SUPPORT == ENABLED)
789  //Invalid TLS context?
790  if(context == NULL)
792 
793  //Allow or disallow unknown ALPN protocols
794  context->unknownProtocolsAllowed = allowed;
795 
796  //Successful processing
797  return NO_ERROR;
798 #else
799  //ALPN is not implemented
800  return ERROR_NOT_IMPLEMENTED;
801 #endif
802 }
803 
804 
805 /**
806  * @brief Set the list of supported ALPN protocols
807  * @param[in] context Pointer to the TLS context
808  * @param[in] protocolList Comma-delimited list of supported protocols
809  * @return Error code
810  **/
811 
812 error_t tlsSetAlpnProtocolList(TlsContext *context, const char_t *protocolList)
813 {
814 #if (TLS_ALPN_SUPPORT == ENABLED)
815  size_t length;
816 
817  //Check parameters
818  if(context == NULL || protocolList == NULL)
820 
821  //Retrieve the length of the list
822  length = osStrlen(protocolList);
823 
824  //Check whether the list of supported protocols has already been configured
825  if(context->protocolList != NULL)
826  {
827  //Release memory
828  tlsFreeMem(context->protocolList);
829  context->protocolList = NULL;
830  }
831 
832  //Check whether the list of protocols is valid
833  if(length > 0)
834  {
835  //Allocate a memory block to hold the list
836  context->protocolList = tlsAllocMem(length + 1);
837  //Failed to allocate memory?
838  if(context->protocolList == NULL)
839  return ERROR_OUT_OF_MEMORY;
840 
841  //Save the list of supported protocols
842  osStrcpy(context->protocolList, protocolList);
843  }
844 
845  //Successful processing
846  return NO_ERROR;
847 #else
848  //ALPN is not implemented
849  return ERROR_NOT_IMPLEMENTED;
850 #endif
851 }
852 
853 
854 /**
855  * @brief Register ALPN callback function
856  * @param[in] context Pointer to the TLS context
857  * @param[in] alpnCallback ALPN callback function
858  * @return Error code
859  **/
860 
862 {
863 #if (TLS_ALPN_SUPPORT == ENABLED)
864  //Check parameters
865  if(context == NULL || alpnCallback == NULL)
867 
868  //Save the ALPN callback function
869  context->alpnCallback = alpnCallback;
870 
871  //Successful processing
872  return NO_ERROR;
873 #else
874  //ALPN is not implemented
875  return ERROR_NOT_IMPLEMENTED;
876 #endif
877 }
878 
879 
880 /**
881  * @brief Get the name of the selected ALPN protocol
882  * @param[in] context Pointer to the TLS context
883  * @return Pointer to the protocol name
884  **/
885 
887 {
888  static const char_t defaultProtocolName[] = "";
889 
890 #if (TLS_ALPN_SUPPORT == ENABLED)
891  //Valid protocol name?
892  if(context != NULL && context->selectedProtocol != NULL)
893  {
894  //Return the name of the selected protocol
895  return context->selectedProtocol;
896  }
897  else
898 #endif
899  {
900  //Return an empty string
901  return defaultProtocolName;
902  }
903 }
904 
905 
906 /**
907  * @brief Set the pre-shared key to be used
908  * @param[in] context Pointer to the TLS context
909  * @param[in] psk Pointer to the pre-shared key
910  * @param[in] length Length of the pre-shared key, in bytes
911  * @return Error code
912  **/
913 
914 error_t tlsSetPsk(TlsContext *context, const uint8_t *psk, size_t length)
915 {
916 #if (TLS_PSK_SUPPORT == ENABLED)
917  //Invalid TLS context?
918  if(context == NULL)
920 
921  //Check parameters
922  if(psk == NULL && length != 0)
924 
925  //Check whether the pre-shared key has already been configured
926  if(context->psk != NULL)
927  {
928  //Release memory
929  osMemset(context->psk, 0, context->pskLen);
930  tlsFreeMem(context->psk);
931  context->psk = NULL;
932  context->pskLen = 0;
933  }
934 
935  //Valid PSK?
936  if(length > 0)
937  {
938  //Allocate a memory block to hold the pre-shared key
939  context->psk = tlsAllocMem(length);
940  //Failed to allocate memory?
941  if(context->psk == NULL)
942  return ERROR_OUT_OF_MEMORY;
943 
944  //Save the pre-shared key
945  osMemcpy(context->psk, psk, length);
946  //Save the length of the key
947  context->pskLen = length;
948  }
949 
950 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
951  //For externally established PSKs, the hash algorithm must be set when the
952  //PSK is established, or default to SHA-256 if no such algorithm is defined
953  context->pskHashAlgo = TLS_HASH_ALGO_SHA256;
954 
955  //The cipher suite must be provisioned along with the key
956  context->pskCipherSuite = 0;
957 #endif
958 
959  //Successful processing
960  return NO_ERROR;
961 #else
962  //PSK key exchange is not implemented
963  return ERROR_NOT_IMPLEMENTED;
964 #endif
965 }
966 
967 
968 /**
969  * @brief Set the PSK identity to be used by the client
970  * @param[in] context Pointer to the TLS context
971  * @param[in] pskIdentity NULL-terminated string that contains the PSK identity
972  * @return Error code
973  **/
974 
975 error_t tlsSetPskIdentity(TlsContext *context, const char_t *pskIdentity)
976 {
977 #if (TLS_PSK_SUPPORT == ENABLED)
978  size_t length;
979 
980  //Check parameters
981  if(context == NULL || pskIdentity == NULL)
983 
984  //Retrieve the length of the PSK identity
985  length = osStrlen(pskIdentity);
986 
987  //Check whether the PSK identity has already been configured
988  if(context->pskIdentity != NULL)
989  {
990  //Release memory
991  tlsFreeMem(context->pskIdentity);
992  context->pskIdentity = NULL;
993  }
994 
995  //Valid PSK identity?
996  if(length > 0)
997  {
998  //Allocate a memory block to hold the PSK identity
999  context->pskIdentity = tlsAllocMem(length + 1);
1000  //Failed to allocate memory?
1001  if(context->pskIdentity == NULL)
1002  return ERROR_OUT_OF_MEMORY;
1003 
1004  //Save the PSK identity
1005  osStrcpy(context->pskIdentity, pskIdentity);
1006  }
1007 
1008  //Successful processing
1009  return NO_ERROR;
1010 #else
1011  //PSK key exchange is not implemented
1012  return ERROR_NOT_IMPLEMENTED;
1013 #endif
1014 }
1015 
1016 
1017 /**
1018  * @brief Set the PSK identity hint to be used by the server
1019  * @param[in] context Pointer to the TLS context
1020  * @param[in] pskIdentityHint NULL-terminated string that contains the PSK identity hint
1021  * @return Error code
1022  **/
1023 
1024 error_t tlsSetPskIdentityHint(TlsContext *context, const char_t *pskIdentityHint)
1025 {
1026 #if (TLS_PSK_SUPPORT == ENABLED)
1027  size_t length;
1028 
1029  //Check parameters
1030  if(context == NULL || pskIdentityHint == NULL)
1031  return ERROR_INVALID_PARAMETER;
1032 
1033  //Retrieve the length of the PSK identity hint
1034  length = osStrlen(pskIdentityHint);
1035 
1036  //Check whether the PSK identity hint has already been configured
1037  if(context->pskIdentityHint != NULL)
1038  {
1039  //Release memory
1040  tlsFreeMem(context->pskIdentityHint);
1041  context->pskIdentityHint = NULL;
1042  }
1043 
1044  //Valid PSK identity hint?
1045  if(length > 0)
1046  {
1047  //Allocate a memory block to hold the PSK identity hint
1048  context->pskIdentityHint = tlsAllocMem(length + 1);
1049  //Failed to allocate memory?
1050  if(context->pskIdentityHint == NULL)
1051  return ERROR_OUT_OF_MEMORY;
1052 
1053  //Save the PSK identity hint
1054  osStrcpy(context->pskIdentityHint, pskIdentityHint);
1055  }
1056 
1057  //Successful processing
1058  return NO_ERROR;
1059 #else
1060  //PSK key exchange is not implemented
1061  return ERROR_NOT_IMPLEMENTED;
1062 #endif
1063 }
1064 
1065 
1066 /**
1067  * @brief Register PSK callback function
1068  * @param[in] context Pointer to the TLS context
1069  * @param[in] pskCallback PSK callback function
1070  * @return Error code
1071  **/
1072 
1074 {
1075 #if (TLS_PSK_SUPPORT == ENABLED)
1076  //Check parameters
1077  if(context == NULL || pskCallback == NULL)
1078  return ERROR_INVALID_PARAMETER;
1079 
1080  //Save the PSK callback function
1081  context->pskCallback = pskCallback;
1082 
1083  //Successful processing
1084  return NO_ERROR;
1085 #else
1086  //PSK key exchange is not implemented
1087  return ERROR_NOT_IMPLEMENTED;
1088 #endif
1089 }
1090 
1091 
1092 /**
1093  * @brief Register the raw public key verification callback function
1094  * @param[in] context Pointer to the TLS context
1095  * @param[in] rpkVerifyCallback RPK verification callback function
1096  * @return Error code
1097  **/
1098 
1100  TlsRpkVerifyCallback rpkVerifyCallback)
1101 {
1102 #if (TLS_RAW_PUBLIC_KEY_SUPPORT == ENABLED)
1103  //Check parameters
1104  if(context == NULL || rpkVerifyCallback == NULL)
1105  return ERROR_INVALID_PARAMETER;
1106 
1107  //Save the raw public key verification callback function
1108  context->rpkVerifyCallback = rpkVerifyCallback;
1109 
1110  //Successful processing
1111  return NO_ERROR;
1112 #else
1113  //Raw public keys are not implemented
1114  return ERROR_NOT_IMPLEMENTED;
1115 #endif
1116 }
1117 
1118 
1119 /**
1120  * @brief Import a trusted CA list
1121  * @param[in] context Pointer to the TLS context
1122  * @param[in] trustedCaList List of trusted CA (PEM format)
1123  * @param[in] length Total length of the list
1124  * @return Error code
1125  **/
1126 
1128  const char_t *trustedCaList, size_t length)
1129 {
1130  //Invalid TLS context?
1131  if(context == NULL)
1132  return ERROR_INVALID_PARAMETER;
1133 
1134  //Check parameters
1135  if(trustedCaList == NULL && length != 0)
1136  return ERROR_INVALID_PARAMETER;
1137 
1138  //Save the list of trusted CA
1139  context->trustedCaList = trustedCaList;
1140  context->trustedCaListLen = length;
1141 
1142  //Successful processing
1143  return NO_ERROR;
1144 }
1145 
1146 
1147 /**
1148  * @brief Import a certificate and the corresponding private key
1149  * @param[in] context Pointer to the TLS context
1150  * @param[in] certChain Certificate chain (PEM format). This parameter is
1151  * taken as reference
1152  * @param[in] certChainLen Total length of the certificate chain
1153  * @param[in] privateKey Private key (PEM format). This parameter is taken
1154  * as reference
1155  * @param[in] privateKeyLen Total length of the private key
1156  * @return Error code
1157  **/
1158 
1159 error_t tlsAddCertificate(TlsContext *context, const char_t *certChain,
1160  size_t certChainLen, const char_t *privateKey, size_t privateKeyLen)
1161 {
1162  error_t error;
1163  uint8_t *derCert;
1164  size_t derCertLen;
1165  X509CertificateInfo *certInfo;
1166  TlsCertificateType certType;
1167  TlsSignatureAlgo certSignAlgo;
1168  TlsHashAlgo certHashAlgo;
1169  TlsNamedGroup namedCurve;
1170 
1171  //Invalid TLS context?
1172  if(context == NULL)
1173  return ERROR_INVALID_PARAMETER;
1174 
1175  //Check whether the certificate chain is valid
1176  if(certChain == NULL || certChainLen == 0)
1177  return ERROR_INVALID_PARAMETER;
1178 
1179  //The private key is optional
1180  if(privateKey == NULL && privateKeyLen != 0)
1181  return ERROR_INVALID_PARAMETER;
1182 
1183  //Make sure there is enough room to add the certificate
1184  if(context->numCerts >= TLS_MAX_CERTIFICATES)
1185  return ERROR_OUT_OF_RESOURCES;
1186 
1187  //Initialize variables
1188  derCert = NULL;
1189  certInfo = NULL;
1190 
1191  //Start of exception handling block
1192  do
1193  {
1194  //The first pass calculates the length of the DER-encoded certificate
1195  error = pemImportCertificate(certChain, certChainLen, NULL, &derCertLen,
1196  NULL);
1197  //Any error to report?
1198  if(error)
1199  break;
1200 
1201  //Allocate a memory buffer to hold the DER-encoded certificate
1202  derCert = tlsAllocMem(derCertLen);
1203  //Failed to allocate memory?
1204  if(derCert == NULL)
1205  {
1206  error = ERROR_OUT_OF_MEMORY;
1207  break;
1208  }
1209 
1210  //The second pass decodes the PEM certificate
1211  error = pemImportCertificate(certChain, certChainLen, derCert,
1212  &derCertLen, NULL);
1213  //Any error to report?
1214  if(error)
1215  break;
1216 
1217  //Allocate a memory buffer to store X.509 certificate info
1218  certInfo = tlsAllocMem(sizeof(X509CertificateInfo));
1219  //Failed to allocate memory?
1220  if(certInfo == NULL)
1221  {
1222  error = ERROR_OUT_OF_MEMORY;
1223  break;
1224  }
1225 
1226  //Parse X.509 certificate
1227  error = x509ParseCertificateEx(derCert, derCertLen, certInfo, TRUE);
1228  //Failed to parse the X.509 certificate?
1229  if(error)
1230  break;
1231 
1232  //Retrieve the signature algorithm that has been used to sign the
1233  //certificate
1234  error = tlsGetCertificateType(certInfo, &certType, &certSignAlgo,
1235  &certHashAlgo, &namedCurve);
1236  //The specified signature algorithm is not supported?
1237  if(error)
1238  break;
1239 
1240  //End of exception handling block
1241  } while(0);
1242 
1243  //Valid certificate?
1244  if(!error)
1245  {
1246  //Point to the structure that describes the certificate
1247  TlsCertDesc *cert = &context->certs[context->numCerts];
1248 
1249  //Save the certificate chain and the corresponding private key
1250  cert->certChain = certChain;
1251  cert->certChainLen = certChainLen;
1252  cert->privateKey = privateKey;
1253  cert->privateKeyLen = privateKeyLen;
1254  cert->type = certType;
1255  cert->signAlgo = certSignAlgo;
1256  cert->hashAlgo = certHashAlgo;
1257  cert->namedCurve = namedCurve;
1258 
1259  //Update the number of certificates
1260  context->numCerts++;
1261  }
1262 
1263  //Release previously allocated memory
1264  tlsFreeMem(derCert);
1265  tlsFreeMem(certInfo);
1266 
1267  //Return status code
1268  return error;
1269 }
1270 
1271 
1272 /**
1273  * @brief Set certificate verification callback
1274  * @param[in] context Pointer to the TLS context
1275  * @param[in] certVerifyCallback Certificate verification callback
1276  * @param[in] param An opaque pointer passed to the callback function
1277  * @return Error code
1278  **/
1279 
1281  TlsCertVerifyCallback certVerifyCallback, void *param)
1282 {
1283  //Invalid TLS context?
1284  if(context == NULL)
1285  return ERROR_INVALID_PARAMETER;
1286 
1287  //Save certificate verification callback
1288  context->certVerifyCallback = certVerifyCallback;
1289  //This opaque pointer will be directly passed to the callback function
1290  context->certVerifyParam = param;
1291 
1292  //Successful processing
1293  return NO_ERROR;
1294 }
1295 
1296 
1297 /**
1298  * @brief Enable session ticket mechanism
1299  * @param[in] context Pointer to the TLS context
1300  * @param[in] enabled Specifies whether session tickets are allowed
1301  * @return Error code
1302  **/
1303 
1305 {
1306 #if (TLS_TICKET_SUPPORT == ENABLED)
1307  //Invalid TLS context?
1308  if(context == NULL)
1309  return ERROR_INVALID_PARAMETER;
1310 
1311  //Enable or disable session ticket mechanism
1312  context->sessionTicketEnabled = enabled;
1313 
1314  //Successful processing
1315  return NO_ERROR;
1316 #else
1317  //Session ticket mechanism is not implemented
1318  return ERROR_NOT_IMPLEMENTED;
1319 #endif
1320 }
1321 
1322 
1323 /**
1324  * @brief Enable secure renegotiation
1325  * @param[in] context Pointer to the TLS context
1326  * @param[in] enabled Specifies whether secure renegotiation is allowed
1327  * @return Error code
1328  **/
1329 
1331 {
1332 #if (TLS_SECURE_RENEGOTIATION_SUPPORT == ENABLED)
1333  //Invalid TLS context?
1334  if(context == NULL)
1335  return ERROR_INVALID_PARAMETER;
1336 
1337  //Enable or disable secure renegotiation
1338  context->secureRenegoEnabled = enabled;
1339 
1340  //Successful processing
1341  return NO_ERROR;
1342 #else
1343  //Secure renegotiation is not implemented
1344  return ERROR_NOT_IMPLEMENTED;
1345 #endif
1346 }
1347 
1348 
1349 /**
1350  * @brief Perform fallback retry (for clients only)
1351  * @param[in] context Pointer to the TLS context
1352  * @param[in] enabled Specifies whether FALLBACK_SCSV is enabled
1353  * @return Error code
1354  **/
1355 
1357 {
1358 #if (TLS_FALLBACK_SCSV_SUPPORT == ENABLED)
1359  //Invalid TLS context?
1360  if(context == NULL)
1361  return ERROR_INVALID_PARAMETER;
1362 
1363  //Enable or disable support for FALLBACK_SCSV
1364  context->fallbackScsvEnabled = enabled;
1365 
1366  //Successful processing
1367  return NO_ERROR;
1368 #else
1369  //Not implemented
1370  return ERROR_NOT_IMPLEMENTED;
1371 #endif
1372 }
1373 
1374 
1375 /**
1376  * @brief Set ticket encryption/decryption callbacks
1377  * @param[in] context Pointer to the TLS context
1378  * @param[in] ticketEncryptCallback Ticket encryption callback function
1379  * @param[in] ticketDecryptCallback Ticket decryption callback function
1380  * @param[in] param An opaque pointer passed to the callback functions
1381  * @return Error code
1382  **/
1383 
1385  TlsTicketEncryptCallback ticketEncryptCallback,
1386  TlsTicketDecryptCallback ticketDecryptCallback, void *param)
1387 {
1388 #if (TLS_TICKET_SUPPORT == ENABLED)
1389  //Invalid TLS context?
1390  if(context == NULL)
1391  return ERROR_INVALID_PARAMETER;
1392 
1393  //Save ticket encryption/decryption callback functions
1394  context->ticketEncryptCallback = ticketEncryptCallback;
1395  context->ticketDecryptCallback = ticketDecryptCallback;
1396 
1397  //This opaque pointer will be directly passed to the callback functions
1398  context->ticketParam = param;
1399 
1400  //Successful processing
1401  return NO_ERROR;
1402 #else
1403  //Session ticket mechanism is not implemented
1404  return ERROR_NOT_IMPLEMENTED;
1405 #endif
1406 }
1407 
1408 
1409 /**
1410  * @brief Set PMTU value (for DTLS only)
1411  * @param[in] context Pointer to the TLS context
1412  * @param[in] pmtu PMTU value
1413  * @return Error code
1414  **/
1415 
1416 error_t tlsSetPmtu(TlsContext *context, size_t pmtu)
1417 {
1418 #if (DTLS_SUPPORT == ENABLED)
1419  //Invalid TLS context?
1420  if(context == NULL)
1421  return ERROR_INVALID_PARAMETER;
1422 
1423  //Make sure the PMTU value is acceptable
1424  if(pmtu < DTLS_MIN_PMTU)
1425  return ERROR_INVALID_PARAMETER;
1426 
1427  //Save PMTU value
1428  context->pmtu = pmtu;
1429 
1430  //Successful processing
1431  return NO_ERROR;
1432 #else
1433  //DTLS is not implemented
1434  return ERROR_NOT_IMPLEMENTED;
1435 #endif
1436 }
1437 
1438 
1439 /**
1440  * @brief Set timeout for blocking calls (for DTLS only)
1441  * @param[in] context Pointer to the TLS context
1442  * @param[in] timeout Maximum time to wait
1443  * @return Error code
1444  **/
1445 
1447 {
1448 #if (DTLS_SUPPORT == ENABLED)
1449  //Invalid TLS context?
1450  if(context == NULL)
1451  return ERROR_INVALID_PARAMETER;
1452 
1453  //Save timeout value
1454  context->timeout = timeout;
1455 
1456  //Successful processing
1457  return NO_ERROR;
1458 #else
1459  //DTLS is not implemented
1460  return ERROR_NOT_IMPLEMENTED;
1461 #endif
1462 }
1463 
1464 
1465 /**
1466  * @brief Set cookie generation/verification callbacks (for DTLS only)
1467  * @param[in] context Pointer to the TLS context
1468  * @param[in] cookieGenerateCallback Cookie generation callback function
1469  * @param[in] cookieVerifyCallback Cookie verification callback function
1470  * @param[in] param An opaque pointer passed to the callback functions
1471  * @return Error code
1472  **/
1473 
1475  DtlsCookieGenerateCallback cookieGenerateCallback,
1476  DtlsCookieVerifyCallback cookieVerifyCallback, void *param)
1477 {
1478 #if (DTLS_SUPPORT == ENABLED)
1479  //Invalid TLS context?
1480  if(context == NULL)
1481  return ERROR_INVALID_PARAMETER;
1482 
1483  //Check parameters
1484  if(cookieGenerateCallback == NULL || cookieVerifyCallback == NULL)
1485  return ERROR_INVALID_PARAMETER;
1486 
1487  //Save cookie generation/verification callback functions
1488  context->cookieGenerateCallback = cookieGenerateCallback;
1489  context->cookieVerifyCallback = cookieVerifyCallback;
1490 
1491  //This opaque pointer will be directly passed to the callback functions
1492  context->cookieParam = param;
1493 
1494  //Successful processing
1495  return NO_ERROR;
1496 #else
1497  //DTLS is not implemented
1498  return ERROR_NOT_IMPLEMENTED;
1499 #endif
1500 }
1501 
1502 
1503 /**
1504  * @brief Enable anti-replay mechanism (for DTLS only)
1505  * @param[in] context Pointer to the TLS context
1506  * @param[in] enabled Specifies whether anti-replay protection is enabled
1507  * @return Error code
1508  **/
1509 
1511 {
1512 #if (DTLS_SUPPORT == ENABLED && DTLS_REPLAY_DETECTION_SUPPORT == ENABLED)
1513  //Invalid TLS context?
1514  if(context == NULL)
1515  return ERROR_INVALID_PARAMETER;
1516 
1517  //Enable or disable anti-replay mechanism
1518  context->replayDetectionEnabled = enabled;
1519 
1520  //Successful processing
1521  return NO_ERROR;
1522 #else
1523  //Anti-replay mechanism is not implemented
1524  return ERROR_NOT_IMPLEMENTED;
1525 #endif
1526 }
1527 
1528 
1529 /**
1530  * @brief Send the maximum amount of 0-RTT data the server can accept
1531  * @param[in] context Pointer to the TLS context
1532  * @param[in] maxEarlyDataSize Maximum amount of 0-RTT data that the client
1533  * is allowed to send
1534  * @return Error code
1535  **/
1536 
1537 
1538 error_t tlsSetMaxEarlyDataSize(TlsContext *context, size_t maxEarlyDataSize)
1539 {
1540 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
1541  //Invalid TLS context?
1542  if(context == NULL)
1543  return ERROR_INVALID_PARAMETER;
1544 
1545  //Save the maximum amount of 0-RTT data that the client is allowed to send
1546  context->maxEarlyDataSize = maxEarlyDataSize;
1547 
1548  //Successful processing
1549  return NO_ERROR;
1550 #else
1551  //Not implemented
1552  return ERROR_NOT_IMPLEMENTED;
1553 #endif
1554 }
1555 
1556 
1557 /**
1558  * @brief Send early data to the remote TLS server
1559  * @param[in] context Pointer to the TLS context
1560  * @param[in] data Pointer to a buffer containing the data to be transmitted
1561  * @param[in] length Number of bytes to be transmitted
1562  * @param[out] written Actual number of bytes written (optional parameter)
1563  * @param[in] flags Set of flags that influences the behavior of this function
1564  * @return Error code
1565  **/
1566 
1568  size_t length, size_t *written, uint_t flags)
1569 {
1570 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3 && \
1571  TLS_CLIENT_SUPPORT == ENABLED && TLS13_EARLY_DATA_SUPPORT == ENABLED)
1572  size_t n;
1573  error_t error;
1574 
1575  //Invalid TLS context?
1576  if(context == NULL)
1577  return ERROR_INVALID_PARAMETER;
1578 
1579  //Check parameters
1580  if(data == NULL && length != 0)
1581  return ERROR_INVALID_PARAMETER;
1582 
1583  //Check operation mode
1584  if(context->entity != TLS_CONNECTION_END_CLIENT)
1585  return ERROR_FAILURE;
1586 
1587  //Make sure TLS 1.3 is supported by the client
1588  if(context->versionMax < TLS_VERSION_1_3)
1589  return ERROR_FAILURE;
1590 
1591  //Check transport protocol
1592  if(context->transportProtocol != TLS_TRANSPORT_PROTOCOL_STREAM)
1593  return ERROR_FAILURE;
1594 
1595  //Ensure the send/receive functions are properly registered
1596  if(context->socketSendCallback == NULL || context->socketReceiveCallback == NULL)
1597  return ERROR_NOT_CONFIGURED;
1598 
1599  //Verify that the PRNG is properly set
1600  if(context->prngAlgo == NULL || context->prngContext == NULL)
1601  return ERROR_NOT_CONFIGURED;
1602 
1603 #if (DTLS_SUPPORT == ENABLED)
1604  //Save current time
1605  context->startTime = osGetSystemTime();
1606 #endif
1607 
1608  //Send 0-RTT data
1609  error = tls13SendEarlyData(context, data, length, &n);
1610 
1611  //Total number of data that have been written
1612  if(written != NULL)
1613  *written = n;
1614 
1615  //Return status code
1616  return error;
1617 #else
1618  //Not implemented
1619  return ERROR_NOT_IMPLEMENTED;
1620 #endif
1621 }
1622 
1623 
1624 /**
1625  * @brief Initiate the TLS handshake
1626  * @param[in] context Pointer to the TLS context
1627  * @return Error code
1628  **/
1629 
1631 {
1632  error_t error;
1633 
1634  //Invalid TLS context?
1635  if(context == NULL)
1636  return ERROR_INVALID_PARAMETER;
1637 
1638  //Ensure the send/receive functions are properly registered
1639  if(context->socketSendCallback == NULL || context->socketReceiveCallback == NULL)
1640  return ERROR_NOT_CONFIGURED;
1641 
1642  //Verify that the PRNG is properly set
1643  if(context->prngAlgo == NULL || context->prngContext == NULL)
1644  return ERROR_NOT_CONFIGURED;
1645 
1646 #if (DTLS_SUPPORT == ENABLED)
1647  //Save current time
1648  context->startTime = osGetSystemTime();
1649 #endif
1650 
1651 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3 && \
1652  TLS_CLIENT_SUPPORT == ENABLED && TLS13_EARLY_DATA_SUPPORT == ENABLED)
1653  //Any 0-RTT data sent by the client?
1654  if(context->entity == TLS_CONNECTION_END_CLIENT &&
1655  context->state == TLS_STATE_EARLY_DATA)
1656  {
1657  //Save current sequence number
1658  context->earlyDataSeqNum = context->encryptionEngine.seqNum;
1659  //Wait for a ServerHello message
1660  context->state = TLS_STATE_SERVER_HELLO_3;
1661  }
1662 #endif
1663 
1664  //Perform TLS handshake
1665  error = tlsPerformHandshake(context);
1666  //Return status code
1667  return error;
1668 }
1669 
1670 
1671 /**
1672  * @brief Check whether the server has accepted or rejected the early data
1673  * @param[in] context Pointer to the TLS context
1674  * @return TLS_EARLY_DATA_ACCEPTED if the early data was accepted, else
1675  * TLS_EARLY_DATA_REJECT if the early data was rejected
1676  **/
1677 
1679 {
1680  TlsEarlyDataStatus status;
1681 
1682  //Initialize early data status
1683  status = TLS_EARLY_DATA_REJECTED;
1684 
1685 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3 && \
1686  TLS_CLIENT_SUPPORT == ENABLED && TLS13_EARLY_DATA_SUPPORT == ENABLED)
1687  //Make sure the TLS context is valid
1688  if(context != NULL)
1689  {
1690  //Client mode?
1691  if(context->entity == TLS_CONNECTION_END_CLIENT)
1692  {
1693  //Any 0-RTT data sent by the client?
1694  if(context->earlyDataEnabled)
1695  {
1696  //Check whether the server has accepted or rejected the early data
1697  if(context->earlyDataExtReceived && !context->earlyDataRejected)
1698  {
1699  status = TLS_EARLY_DATA_ACCEPTED;
1700  }
1701  }
1702  }
1703  }
1704 #endif
1705 
1706  //Return early data status
1707  return status;
1708 }
1709 
1710 
1711 /**
1712  * @brief Send application data to the remote host using TLS
1713  * @param[in] context Pointer to the TLS context
1714  * @param[in] data Pointer to a buffer containing the data to be transmitted
1715  * @param[in] length Number of bytes to be transmitted
1716  * @param[out] written Actual number of bytes written (optional parameter)
1717  * @param[in] flags Set of flags that influences the behavior of this function
1718  * @return Error code
1719  **/
1720 
1721 error_t tlsWrite(TlsContext *context, const void *data,
1722  size_t length, size_t *written, uint_t flags)
1723 {
1724  error_t error;
1725  size_t n;
1726  size_t totalLength;
1727 
1728  //Invalid TLS context?
1729  if(context == NULL)
1730  return ERROR_INVALID_PARAMETER;
1731 
1732  //Check parameters
1733  if(data == NULL && length != 0)
1734  return ERROR_INVALID_PARAMETER;
1735 
1736  //Ensure the send/receive functions are properly registered
1737  if(context->socketSendCallback == NULL || context->socketReceiveCallback == NULL)
1738  return ERROR_NOT_CONFIGURED;
1739 
1740 #if (DTLS_SUPPORT == ENABLED)
1741  //Save current time
1742  context->startTime = osGetSystemTime();
1743 #endif
1744 
1745  //Initialize status code
1746  error = NO_ERROR;
1747 
1748  //Actual number of bytes written
1749  totalLength = 0;
1750 
1751  //Send as much data as possible
1752  while(totalLength < length)
1753  {
1754  //Check current state
1755  if(context->state < TLS_STATE_APPLICATION_DATA)
1756  {
1757  //Perform TLS handshake
1758  error = tlsConnect(context);
1759  }
1760  else if(context->state == TLS_STATE_APPLICATION_DATA)
1761  {
1762 #if (DTLS_SUPPORT == ENABLED)
1763  //DTLS protocol?
1764  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
1765  {
1766  //Length of the payload data
1767  n = length;
1768 
1769  //Send a datagram
1770  error = dtlsWriteProtocolData(context, data, n,
1772  }
1773  else
1774 #endif
1775  //TLS protocol?
1776  {
1777  //Calculate the number of bytes to write at a time
1778  n = MIN(length - totalLength, context->txBufferMaxLen);
1779  //The record length must not exceed 16384 bytes
1781 
1782 #if (TLS_MAX_FRAG_LEN_SUPPORT == ENABLED)
1783  //Do not exceed the negotiated maximum fragment length
1784  n = MIN(n, context->maxFragLen);
1785 #endif
1786 
1787 #if (TLS_RECORD_SIZE_LIMIT_SUPPORT == ENABLED)
1788  //Maximum record size the peer is willing to receive
1789  n = MIN(n, context->recordSizeLimit);
1790 #endif
1791 
1792 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_0)
1793  //The 1/n-1 record splitting technique is a workaround for the
1794  //BEAST attack
1795  if(context->version <= TLS_VERSION_1_0 &&
1796  context->cipherSuite.cipherMode == CIPHER_MODE_CBC &&
1797  context->txLastRecordLen != 1 &&
1798  totalLength == 0)
1799  {
1800  n = 1;
1801  }
1802 #endif
1803  //Send application data
1804  error = tlsWriteProtocolData(context, data, n,
1806  }
1807 
1808  //Check status code
1809  if(!error)
1810  {
1811 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_0)
1812  //Save the length of the TLS record
1813  context->txLastRecordLen = n;
1814 #endif
1815  //Advance data pointer
1816  data = (uint8_t *) data + n;
1817  //Update byte counter
1818  totalLength += n;
1819  }
1820  else
1821  {
1822  //Send an alert message to the peer, if applicable
1823  tlsProcessError(context, error);
1824  }
1825  }
1826  else
1827  {
1828  //The connection has not yet been established
1829  error = ERROR_NOT_CONNECTED;
1830  }
1831 
1832  //Any error to report?
1833  if(error)
1834  break;
1835  }
1836 
1837  //Total number of data that have been written
1838  if(written != NULL)
1839  *written = totalLength;
1840 
1841  //Return status code
1842  return error;
1843 }
1844 
1845 
1846 /**
1847  * @brief Receive application data from a the remote host using TLS
1848  * @param[in] context Pointer to the TLS context
1849  * @param[out] data Buffer into which received data will be placed
1850  * @param[in] size Maximum number of bytes that can be received
1851  * @param[out] received Number of bytes that have been received
1852  * @param[in] flags Set of flags that influences the behavior of this function
1853  * @return Error code
1854  **/
1855 
1856 error_t tlsRead(TlsContext *context, void *data,
1857  size_t size, size_t *received, uint_t flags)
1858 {
1859  error_t error;
1860  size_t i;
1861  size_t n;
1862  uint8_t *p;
1863  TlsContentType contentType;
1864 
1865  //Invalid TLS context?
1866  if(context == NULL)
1867  return ERROR_INVALID_PARAMETER;
1868 
1869  //Check parameters
1870  if(data == NULL || received == NULL)
1871  return ERROR_INVALID_PARAMETER;
1872 
1873  //Ensure the send/receive functions are properly registered
1874  if(context->socketSendCallback == NULL || context->socketReceiveCallback == NULL)
1875  return ERROR_NOT_CONFIGURED;
1876 
1877 #if (DTLS_SUPPORT == ENABLED)
1878  //Save current time
1879  context->startTime = osGetSystemTime();
1880 #endif
1881 
1882  //Initialize status code
1883  error = NO_ERROR;
1884 
1885  //No data has been read yet
1886  *received = 0;
1887 
1888  //Read as much data as possible
1889  while(*received < size)
1890  {
1891  //Check current state
1892  if(context->state < TLS_STATE_APPLICATION_DATA)
1893  {
1894  //Perform TLS handshake
1895  error = tlsConnect(context);
1896  }
1897  else if(context->state == TLS_STATE_APPLICATION_DATA)
1898  {
1899 #if (DTLS_SUPPORT == ENABLED)
1900  //DTLS protocol?
1901  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
1902  {
1903  //Receive a datagram
1904  error = dtlsReadProtocolData(context, &p, &n, &contentType);
1905  }
1906  else
1907 #endif
1908  //TLS protocol?
1909  {
1910  //The record layer receives uninterpreted data from higher layers
1911  error = tlsReadProtocolData(context, &p, &n, &contentType);
1912  }
1913 
1914  //Check status code
1915  if(!error)
1916  {
1917  //Application data received?
1918  if(contentType == TLS_TYPE_APPLICATION_DATA)
1919  {
1920 #if (DTLS_SUPPORT == ENABLED)
1921  //DTLS protocol?
1922  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
1923  {
1924  //Make sure the user buffer is large enough to hold the whole
1925  //datagram
1926  if(n > size)
1927  {
1928  //Report an error
1929  error = ERROR_BUFFER_OVERFLOW;
1930  }
1931  else
1932  {
1933  //Copy data to user buffer
1934  osMemcpy(data, p, n);
1935  //Total number of data that have been read
1936  *received = n;
1937  }
1938 
1939  //If the TLS_FLAG_PEEK flag is set, the data is copied into
1940  //the buffer but is not removed from the receive queue
1941  if((flags & TLS_FLAG_PEEK) == 0)
1942  {
1943  //Flush receive buffer
1944  context->rxBufferPos = 0;
1945  context->rxBufferLen = 0;
1946  }
1947 
1948  //We are done
1949  break;
1950  }
1951  else
1952 #endif
1953  //TLS protocol?
1954  {
1955  //Limit the number of bytes to read at a time
1956  n = MIN(n, size - *received);
1957 
1958  //The TLS_FLAG_BREAK_CHAR flag causes the function to stop reading
1959  //data as soon as the specified break character is encountered
1960  if((flags & TLS_FLAG_BREAK_CHAR) != 0)
1961  {
1962  //Retrieve the break character code
1963  char_t c = LSB(flags);
1964 
1965  //Search for the specified break character
1966  for(i = 0; i < n && p[i] != c; i++);
1967  //Adjust the number of data to read
1968  n = MIN(n, i + 1);
1969 
1970  //Copy data to user buffer
1971  osMemcpy(data, p, n);
1972  //Total number of data that have been read
1973  *received += n;
1974 
1975  //Advance data pointer
1976  context->rxBufferPos += n;
1977  //Number of bytes still pending in the receive buffer
1978  context->rxBufferLen -= n;
1979 
1980  //Check whether a break character has been found
1981  if(n > 0 && p[n - 1] == c)
1982  break;
1983  }
1984  else
1985  {
1986  //Copy data to user buffer
1987  osMemcpy(data, p, n);
1988  //Total number of data that have been read
1989  *received += n;
1990 
1991  //Advance data pointer
1992  context->rxBufferPos += n;
1993  //Number of bytes still pending in the receive buffer
1994  context->rxBufferLen -= n;
1995 
1996  //The TLS_FLAG_WAIT_ALL flag causes the function to return
1997  //only when the requested number of bytes have been read
1998  if((flags & TLS_FLAG_WAIT_ALL) == 0)
1999  break;
2000  }
2001 
2002  //Advance data pointer
2003  data = (uint8_t *) data + n;
2004  }
2005  }
2006  //Handshake message received?
2007  else if(contentType == TLS_TYPE_HANDSHAKE)
2008  {
2009  //Advance data pointer
2010  context->rxBufferPos += n;
2011  //Number of bytes still pending in the receive buffer
2012  context->rxBufferLen -= n;
2013 
2014  //Parse handshake message
2015  error = tlsParseHandshakeMessage(context, p, n);
2016  }
2017  //Alert message received?
2018  else if(contentType == TLS_TYPE_ALERT)
2019  {
2020  //Advance data pointer
2021  context->rxBufferPos += n;
2022  //Number of bytes still pending in the receive buffer
2023  context->rxBufferLen -= n;
2024 
2025  //Parse Alert message
2026  error = tlsParseAlert(context, (TlsAlert *) p, n);
2027  }
2028  //An inappropriate message was received?
2029  else
2030  {
2031  //Report an error
2032  error = ERROR_UNEXPECTED_MESSAGE;
2033  }
2034  }
2035 
2036  //Any error to report?
2037  if(error)
2038  {
2039  //Send an alert message to the peer, if applicable
2040  tlsProcessError(context, error);
2041  }
2042  }
2043  else if(context->state == TLS_STATE_CLOSING ||
2044  context->state == TLS_STATE_CLOSED)
2045  {
2046  //Check whether a fatal alert message has been sent or received
2047  if(context->fatalAlertSent || context->fatalAlertReceived)
2048  {
2049  //Alert messages with a level of fatal result in the immediate
2050  //termination of the connection
2051  error = ERROR_FAILURE;
2052  }
2053  else
2054  {
2055  //The user must be satisfied with data already on hand
2056  if(*received > 0)
2057  {
2058  //Some data are pending in the receive buffer
2059  error = NO_ERROR;
2060  break;
2061  }
2062  else
2063  {
2064  //The receive buffer is empty
2065  error = ERROR_END_OF_STREAM;
2066  }
2067  }
2068  }
2069  else
2070  {
2071  //The connection has not yet been established
2072  error = ERROR_NOT_CONNECTED;
2073  }
2074 
2075  //Any error to report?
2076  if(error)
2077  break;
2078  }
2079 
2080  //Return status code
2081  return error;
2082 }
2083 
2084 
2085 /**
2086  * @brief Check whether some data is ready for transmission
2087  * @param[in] context Pointer to the TLS context
2088  * @return The function returns TRUE if some data is ready for transmission.
2089  * Otherwise, FALSE is returned
2090  **/
2091 
2093 {
2094  bool_t ready;
2095 
2096  //Initialize flag
2097  ready = FALSE;
2098 
2099  //Make sure the TLS context is valid
2100  if(context != NULL)
2101  {
2102  //TLS protocol?
2103  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_STREAM)
2104  {
2105  //Check whether some data is pending in the transmit buffer
2106  if(context->txBufferPos < context->txBufferLen)
2107  {
2108  ready = TRUE;
2109  }
2110  }
2111  }
2112 
2113  //The function returns TRUE if some data is ready for transmission
2114  return ready;
2115 }
2116 
2117 
2118 /**
2119  * @brief Check whether some data is available in the receive buffer
2120  * @param[in] context Pointer to the TLS context
2121  * @return The function returns TRUE if some data is pending and can be read
2122  * immediately without blocking. Otherwise, FALSE is returned
2123  **/
2124 
2126 {
2127  bool_t ready;
2128 
2129  //Initialize flag
2130  ready = FALSE;
2131 
2132  //Make sure the TLS context is valid
2133  if(context != NULL)
2134  {
2135 #if (DTLS_SUPPORT == ENABLED)
2136  //DTLS protocol?
2137  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
2138  {
2139  //Check whether a datagram is pending in the receive buffer
2140  if(context->rxBufferLen > 0 ||
2141  context->rxRecordLen > 0 ||
2142  context->rxDatagramLen > 0)
2143  {
2144  ready = TRUE;
2145  }
2146  }
2147  else
2148 #endif
2149  //TLS protocol?
2150  {
2151  //Check whether some data is pending in the receive buffer
2152  if(context->rxBufferLen > 0)
2153  {
2154  ready = TRUE;
2155  }
2156  }
2157  }
2158 
2159  //The function returns TRUE if some data can be read immediately
2160  //without blocking
2161  return ready;
2162 }
2163 
2164 
2165 /**
2166  * @brief Gracefully close TLS session
2167  * @param[in] context Pointer to the TLS context
2168  **/
2169 
2171 {
2172  //Either party may initiate a close by sending a close_notify alert
2173  return tlsShutdownEx(context, FALSE);
2174 }
2175 
2176 
2177 /**
2178  * @brief Gracefully close TLS session
2179  * @param[in] context Pointer to the TLS context
2180  * @param[in] waitForCloseNotify Wait for the close notify alert from the peer
2181  **/
2182 
2183 error_t tlsShutdownEx(TlsContext *context, bool_t waitForCloseNotify)
2184 {
2185  error_t error;
2186  size_t n;
2187  uint8_t *p;
2188  TlsContentType contentType;
2189 
2190  //Invalid TLS context?
2191  if(context == NULL)
2192  return ERROR_INVALID_PARAMETER;
2193 
2194  //Ensure the send/receive functions are properly registered
2195  if(context->socketSendCallback == NULL || context->socketReceiveCallback == NULL)
2196  return ERROR_NOT_CONFIGURED;
2197 
2198 #if (DTLS_SUPPORT == ENABLED)
2199  //Save current time
2200  context->startTime = osGetSystemTime();
2201 #endif
2202 
2203  //Initialize status code
2204  error = NO_ERROR;
2205 
2206  //Wait for the TLS session to be closed
2207  while(context->state != TLS_STATE_CLOSED)
2208  {
2209  //Check current state
2210  if(context->state == TLS_STATE_APPLICATION_DATA)
2211  {
2212  //TLS protocol?
2213  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_STREAM)
2214  {
2215  //Flush send buffer
2216  error = tlsWriteProtocolData(context, NULL, 0, TLS_TYPE_NONE);
2217  }
2218 
2219  //Check status code
2220  if(!error)
2221  {
2222  //Either party may initiate a close by sending a close_notify alert
2223  context->state = TLS_STATE_CLOSING;
2224  }
2225  }
2226  else if(context->state == TLS_STATE_CLOSING)
2227  {
2228  //TLS protocol?
2229  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_STREAM)
2230  {
2231  //Flush send buffer
2232  error = tlsWriteProtocolData(context, NULL, 0, TLS_TYPE_NONE);
2233  }
2234 
2235  //Check status code
2236  if(!error)
2237  {
2238  //Unless some other fatal alert has been transmitted, each party
2239  //is required to send a close_notify alert before closing the
2240  //write side of the connection
2241  if(context->fatalAlertSent || context->fatalAlertReceived)
2242  {
2243  //Close the connection immediately
2244  context->state = TLS_STATE_CLOSED;
2245  }
2246  else if(!context->closeNotifySent)
2247  {
2248  //Notifies the recipient that the sender will not send any
2249  //more messages on this connection
2250  error = tlsSendAlert(context, TLS_ALERT_LEVEL_WARNING,
2252  }
2253  else if(!context->closeNotifyReceived && waitForCloseNotify)
2254  {
2255 #if (DTLS_SUPPORT == ENABLED)
2256  //DTLS protocol?
2257  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
2258  {
2259  //Wait for the responding close_notify alert
2260  error = dtlsReadProtocolData(context, &p, &n, &contentType);
2261  }
2262  else
2263 #endif
2264  //TLS protocol?
2265  {
2266  //Wait for the responding close_notify alert
2267  error = tlsReadProtocolData(context, &p, &n, &contentType);
2268  }
2269 
2270  //Check status code
2271  if(!error)
2272  {
2273  //Advance data pointer
2274  context->rxBufferPos += n;
2275  //Number of bytes still pending in the receive buffer
2276  context->rxBufferLen -= n;
2277 
2278  //Application data received?
2279  if(contentType == TLS_TYPE_APPLICATION_DATA)
2280  {
2281  //Discard application data
2282  }
2283  //Alert message received?
2284  else if(contentType == TLS_TYPE_ALERT)
2285  {
2286  //Parse Alert message
2287  error = tlsParseAlert(context, (TlsAlert *) p, n);
2288  }
2289  else if(contentType == TLS_TYPE_HANDSHAKE)
2290  {
2291  //Parse handshake message
2292  error = tlsParseHandshakeMessage(context, p, n);
2293  }
2294  //An inappropriate message was received?
2295  else
2296  {
2297  //Report an error
2298  error = ERROR_UNEXPECTED_MESSAGE;
2299  }
2300  }
2301  }
2302  else
2303  {
2304  //The connection is closed
2305  context->state = TLS_STATE_CLOSED;
2306  }
2307  }
2308  }
2309  else
2310  {
2311  //Report an error
2312  error = ERROR_NOT_CONNECTED;
2313  }
2314 
2315  //Any error to report?
2316  if(error)
2317  break;
2318  }
2319 
2320  //Return status code
2321  return error;
2322 }
2323 
2324 
2325 /**
2326  * @brief Release TLS context
2327  * @param[in] context Pointer to the TLS context
2328  **/
2329 
2330 void tlsFree(TlsContext *context)
2331 {
2332  //Valid TLS context?
2333  if(context != NULL)
2334  {
2335  //Release server name
2336  if(context->serverName != NULL)
2337  {
2338  tlsFreeMem(context->serverName);
2339  }
2340 
2341  //Release cookie
2342  if(context->cookie != NULL)
2343  {
2344  osMemset(context->cookie, 0, context->cookieLen);
2345  tlsFreeMem(context->cookie);
2346  }
2347 
2348  //Release send buffer
2349  if(context->txBuffer != NULL)
2350  {
2351  osMemset(context->txBuffer, 0, context->txBufferSize);
2352  tlsFreeMem(context->txBuffer);
2353  }
2354 
2355  //Release receive buffer
2356  if(context->rxBuffer != NULL)
2357  {
2358  osMemset(context->rxBuffer, 0, context->rxBufferSize);
2359  tlsFreeMem(context->rxBuffer);
2360  }
2361 
2362  //Release transcript hash context
2363  tlsFreeTranscriptHash(context);
2364 
2365  //Release session ticket
2366  if(context->ticket != NULL)
2367  {
2368  osMemset(context->ticket, 0, context->ticketLen);
2369  tlsFreeMem(context->ticket);
2370  }
2371 
2372 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
2373  //Release the ALPN protocol associated with the ticket
2374  if(context->ticketAlpn != NULL)
2375  {
2376  tlsFreeMem(context->ticketAlpn);
2377  }
2378 #endif
2379 
2380 #if (TLS_DH_SUPPORT == ENABLED)
2381  //Release Diffie-Hellman context
2382  dhFree(&context->dhContext);
2383 #endif
2384 
2385 #if (TLS_ECDH_SUPPORT == ENABLED)
2386  //Release ECDH context
2387  ecdhFree(&context->ecdhContext);
2388 #endif
2389 
2390 #if (TLS_RSA_SUPPORT == ENABLED)
2391  //Release peer's RSA public key
2392  rsaFreePublicKey(&context->peerRsaPublicKey);
2393 #endif
2394 
2395 #if (TLS_DSA_SIGN_SUPPORT == ENABLED)
2396  //Release peer's DSA public key
2397  dsaFreePublicKey(&context->peerDsaPublicKey);
2398 #endif
2399 
2400 #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED || TLS_EDDSA_SIGN_SUPPORT == ENABLED)
2401  //Release peer's EC domain parameters
2402  ecFreeDomainParameters(&context->peerEcParams);
2403  //Release peer's EC public key
2404  ecFreePublicKey(&context->peerEcPublicKey);
2405 #endif
2406 
2407 #if (TLS_PSK_SUPPORT == ENABLED)
2408  //Release the pre-shared key
2409  if(context->psk != NULL)
2410  {
2411  osMemset(context->psk, 0, context->pskLen);
2412  tlsFreeMem(context->psk);
2413  }
2414 
2415  //Release the PSK identity
2416  if(context->pskIdentity != NULL)
2417  {
2418  tlsFreeMem(context->pskIdentity);
2419  }
2420 
2421  //Release the PSK identity hint
2422  if(context->pskIdentityHint != NULL)
2423  {
2424  tlsFreeMem(context->pskIdentityHint);
2425  }
2426 #endif
2427 
2428 #if (TLS_ALPN_SUPPORT == ENABLED)
2429  //Release the list of supported ALPN protocols
2430  if(context->protocolList != NULL)
2431  {
2432  tlsFreeMem(context->protocolList);
2433  }
2434 
2435  //Release the selected ALPN protocol
2436  if(context->selectedProtocol != NULL)
2437  {
2438  tlsFreeMem(context->selectedProtocol);
2439  }
2440 #endif
2441 
2442  //Release encryption engine
2443  tlsFreeEncryptionEngine(&context->encryptionEngine);
2444  //Release decryption engine
2445  tlsFreeEncryptionEngine(&context->decryptionEngine);
2446 
2447 #if (DTLS_SUPPORT == ENABLED)
2448  //Release previous encryption engine
2449  tlsFreeEncryptionEngine(&context->prevEncryptionEngine);
2450 #endif
2451 
2452  //Clear the TLS context before freeing memory
2453  osMemset(context, 0, sizeof(TlsContext));
2454  tlsFreeMem(context);
2455  }
2456 }
2457 
2458 
2459 /**
2460  * @brief Initialize session state
2461  * @param[in] session Pointer to the session state
2462  * @return Error code
2463  **/
2464 
2466 {
2467  //Make sure the session state is valid
2468  if(session == NULL)
2469  return ERROR_INVALID_PARAMETER;
2470 
2471  //Erase session state
2472  osMemset(session, 0, sizeof(TlsSessionState));
2473 
2474  //Successful initialization
2475  return NO_ERROR;
2476 }
2477 
2478 
2479 /**
2480  * @brief Save TLS session
2481  * @param[in] context Pointer to the TLS context
2482  * @param[out] session Pointer to the session state
2483  * @return Error code
2484  **/
2485 
2487  TlsSessionState *session)
2488 {
2489  error_t error;
2490 
2491  //Check parameters
2492  if(context == NULL || session == NULL)
2493  return ERROR_INVALID_PARAMETER;
2494 
2495  //Release previous session state
2496  tlsFreeSessionState(session);
2497 
2498 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
2499  //TLS 1.0, TLS 1.1 or TLS 1.2 currently selected?
2500  if(context->version >= TLS_VERSION_1_0 && context->version <= TLS_VERSION_1_2)
2501  {
2502  //Valid session?
2503  if(context->ticketLen > 0)
2504  {
2505  //Save session ticket
2506  error = tlsSaveSessionTicket(context, session);
2507  }
2508  else if(context->sessionIdLen > 0)
2509  {
2510  //Save session identifier
2511  error = tlsSaveSessionId(context, session);
2512  }
2513  else
2514  {
2515  //No valid session to save
2516  error = ERROR_INVALID_SESSION;
2517  }
2518  }
2519  else
2520 #endif
2521 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
2522  //TLS 1.3 currently selected?
2523  if(context->version == TLS_VERSION_1_3)
2524  {
2525  //Save session ticket
2526  error = tls13SaveSessionTicket(context, session);
2527  }
2528  else
2529 #endif
2530  //Invalid TLS version?
2531  {
2532  //Do not save session state
2533  error = ERROR_INVALID_VERSION;
2534  }
2535 
2536  //Check status code
2537  if(error)
2538  {
2539  //Clean up side effects
2540  tlsFreeSessionState(session);
2541  }
2542 
2543  //Successful processing
2544  return NO_ERROR;
2545 }
2546 
2547 
2548 /**
2549  * @brief Restore TLS session
2550  * @param[in] context Pointer to the TLS context
2551  * @param[in] session Pointer to the session state to be restored
2552  * @return Error code
2553  **/
2554 
2556  const TlsSessionState *session)
2557 {
2558  //Check parameters
2559  if(context == NULL || session == NULL)
2560  return ERROR_INVALID_PARAMETER;
2561 
2562 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
2563  //TLS 1.0, TLS 1.1 or TLS 1.2 currently selected?
2564  if(session->version >= TLS_VERSION_1_0 && session->version <= TLS_VERSION_1_2)
2565  {
2566  //Valid session?
2567  if(session->ticketLen > 0)
2568  {
2569  //Restore a TLS session using session ticket
2570  tlsRestoreSessionTicket(context, session);
2571  }
2572  else if(session->sessionIdLen > 0)
2573  {
2574  //Restore a TLS session using session ID
2575  tlsRestoreSessionId(context, session);
2576  }
2577  else
2578  {
2579  //No valid session to restore
2580  }
2581  }
2582  else
2583 #endif
2584 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
2585  //TLS 1.3 currently selected?
2586  if(session->version == TLS_VERSION_1_3)
2587  {
2588  //Restore TLS session using session ticket
2589  tls13RestoreSessionTicket(context, session);
2590  }
2591  else
2592 #endif
2593  //Invalid TLS version?
2594  {
2595  //Do not restore session state
2596  }
2597 
2598  //Successful processing
2599  return NO_ERROR;
2600 }
2601 
2602 
2603 /**
2604  * @brief Properly dispose a session state
2605  * @param[in] session Pointer to the session state to be released
2606  **/
2607 
2609 {
2610  //Make sure the session state is valid
2611  if(session != NULL)
2612  {
2613  //Release session ticket
2614  if(session->ticket != NULL)
2615  {
2616  osMemset(session->ticket, 0, session->ticketLen);
2617  tlsFreeMem(session->ticket);
2618  }
2619 
2620 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
2621  //Release the ALPN protocol associated with the ticket
2622  if(session->ticketAlpn != NULL)
2623  {
2624  tlsFreeMem(session->ticketAlpn);
2625  }
2626 #endif
2627 
2628 #if (TLS_SNI_SUPPORT == ENABLED)
2629  //Release server name
2630  if(session->serverName != NULL)
2631  {
2632  tlsFreeMem(session->serverName);
2633  }
2634 #endif
2635 
2636  //Erase session state
2637  osMemset(session, 0, sizeof(TlsSessionState));
2638  }
2639 }
2640 
2641 #endif
TlsContext * tlsInit(void)
TLS context initialization.
Definition: tls.c:66
error_t tlsSetSupportedGroups(TlsContext *context, const uint16_t *groups, uint_t length)
Specify the list of allowed ECDHE and FFDHE groups.
Definition: tls.c:596
#define TLS_MAX_RECORD_LENGTH
Definition: tls.h:879
#define tlsAllocMem(size)
Definition: tls.h:806
size_t ticketLen
Length of the session ticket.
Definition: tls.h:1954
uint8_t length
Definition: coap_common.h:193
TLS helper functions.
X.509 certificate parsing.
error_t tlsEnableSecureRenegotiation(TlsContext *context, bool_t enabled)
Enable secure renegotiation.
Definition: tls.c:1330
error_t tlsSetConnectionEnd(TlsContext *context, TlsConnectionEnd entity)
Set operation mode (client or server)
Definition: tls.c:313
error_t tlsSetMaxEarlyDataSize(TlsContext *context, size_t maxEarlyDataSize)
Send the maximum amount of 0-RTT data the server can accept.
Definition: tls.c:1538
int bool_t
Definition: compiler_port.h:48
void rsaFreePublicKey(RsaPublicKey *key)
Release an RSA public key.
Definition: rsa.c:118
error_t tlsSaveSessionTicket(const TlsContext *context, TlsSessionState *session)
Save session ticket.
Definition: tls_misc.c:481
error_t tlsSetTransportProtocol(TlsContext *context, TlsTransportProtocol transportProtocol)
Set the transport protocol to be used.
Definition: tls.c:284
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:1872
@ TLS_ALERT_CLOSE_NOTIFY
Definition: tls.h:1024
@ CIPHER_MODE_CBC
Definition: crypto.h:861
#define DTLS_DEFAULT_PMTU
Definition: dtls_misc.h:48
uint8_t data[]
Definition: ethernet.h:220
error_t(* TlsEcdsaVerifyCallback)(TlsContext *context, const uint8_t *digest, size_t digestLen, EcdsaSignature *signature)
ECDSA signature verification callback function.
Definition: tls.h:1905
error_t tlsPerformHandshake(TlsContext *context)
Perform TLS handshake.
TLS handshake.
@ ERROR_BUFFER_OVERFLOW
Definition: error.h:141
uint8_t * ticket
Session ticket.
Definition: tls.h:1953
@ ERROR_NOT_IMPLEMENTED
Definition: error.h:66
#define PrngAlgo
Definition: crypto.h:833
void ecInitDomainParameters(EcDomainParameters *params)
Initialize EC domain parameters.
Definition: ec.c:51
@ TLS_EARLY_DATA_REJECTED
Definition: tls.h:931
error_t tlsSetPskIdentityHint(TlsContext *context, const char_t *pskIdentityHint)
Set the PSK identity hint to be used by the server.
Definition: tls.c:1024
@ ERROR_UNEXPECTED_MESSAGE
Definition: error.h:193
TlsState
TLS FSM states.
Definition: tls.h:1359
uint8_t p
Definition: ndp.h:298
error_t tlsSetEcdhCallback(TlsContext *context, TlsEcdhCallback ecdhCallback)
Register ECDH key agreement callback function.
Definition: tls.c:679
TlsConnectionEnd
TLS connection end.
Definition: tls.h:907
error_t tlsSetCertificateVerifyCallback(TlsContext *context, TlsCertVerifyCallback certVerifyCallback, void *param)
Set certificate verification callback.
Definition: tls.c:1280
#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:236
@ TLS_GROUP_SECP256R1
Definition: tls.h:1300
@ TLS_TYPE_HANDSHAKE
Definition: tls.h:966
error_t(* TlsSocketReceiveCallback)(TlsSocketHandle handle, void *data, size_t size, size_t *received, uint_t flags)
Socket receive callback function.
Definition: tls.h:1832
TlsHashAlgo hashAlgo
Hash algorithm used to sign the end entity certificate.
Definition: tls.h:1993
error_t tlsSetCache(TlsContext *context, TlsCache *cache)
Set session cache.
Definition: tls.c:440
TlsCertificateType type
End entity certificate type.
Definition: tls.h:1991
X.509 certificate.
Definition: x509_common.h:932
@ ERROR_OUT_OF_RESOURCES
Definition: error.h:64
TLS 1.3 session tickets.
@ TLS_TRANSPORT_PROTOCOL_DATAGRAM
Definition: tls.h:898
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:409
@ TLS_STATE_APPLICATION_DATA
Definition: tls.h:1390
size_t sessionIdLen
Length of the session identifier.
Definition: tls.h:1950
error_t tlsSetAlpnCallback(TlsContext *context, TlsAlpnCallback alpnCallback)
Register ALPN callback function.
Definition: tls.c:861
TlsHashAlgo
Hash algorithms.
Definition: tls.h:1149
@ ERROR_OUT_OF_MEMORY
Definition: error.h:63
error_t tlsSetEcdsaSignCallback(TlsContext *context, TlsEcdsaSignCallback ecdsaSignCallback)
ECDSA signature generation callback function.
Definition: tls.c:705
@ ERROR_NOT_CONFIGURED
Definition: error.h:216
#define osStrlen(s)
Definition: os_port.h:155
error_t tlsEnableReplayDetection(TlsContext *context, bool_t enabled)
Enable anti-replay mechanism (for DTLS only)
Definition: tls.c:1510
Session cache.
Definition: tls.h:1974
error_t tlsShutdownEx(TlsContext *context, bool_t waitForCloseNotify)
Gracefully close TLS session.
Definition: tls.c:2183
@ ERROR_END_OF_STREAM
Definition: error.h:209
error_t tlsSetPmtu(TlsContext *context, size_t pmtu)
Set PMTU value (for DTLS only)
Definition: tls.c:1416
@ ERROR_INVALID_VERSION
Definition: error.h:117
void ecFreeDomainParameters(EcDomainParameters *params)
Release EC domain parameters.
Definition: ec.c:72
void tlsFreeSessionState(TlsSessionState *session)
Properly dispose a session state.
Definition: tls.c:2608
error_t(* TlsSocketSendCallback)(TlsSocketHandle handle, const void *data, size_t length, size_t *written, uint_t flags)
Socket send callback function.
Definition: tls.h:1824
#define DTLS_MIN_PMTU
Definition: dtls_misc.h:55
error_t tlsRestoreSessionState(TlsContext *context, const TlsSessionState *session)
Restore TLS session.
Definition: tls.c:2555
error_t(* TlsAlpnCallback)(TlsContext *context, const char_t *selectedProtocol)
ALPN callback function.
Definition: tls.h:1840
__start_packed struct @29 TlsAlert
Alert message.
error_t tlsSetVersion(TlsContext *context, uint16_t versionMin, uint16_t versionMax)
Set minimum and maximum versions permitted.
Definition: tls.c:250
error_t(* TlsRpkVerifyCallback)(TlsContext *context, const uint8_t *rawPublicKey, size_t rawPublicKeyLen)
Raw public key verification callback function.
Definition: tls.h:1864
error_t tlsEnableFallbackScsv(TlsContext *context, bool_t enabled)
Perform fallback retry (for clients only)
Definition: tls.c:1356
@ TLS_ALERT_LEVEL_WARNING
Definition: tls.h:1013
error_t tlsSetMaxFragmentLength(TlsContext *context, size_t maxFragLen)
Set maximum fragment length.
Definition: tls.c:531
const char_t * tlsGetServerName(TlsContext *context)
Get the server name.
Definition: tls.c:415
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:2170
size_t certChainLen
Length of the certificate chain.
Definition: tls.h:1988
#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:914
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:60
error_t tlsSendAlert(TlsContext *context, uint8_t level, uint8_t description)
Send Alert message.
Definition: tls_common.c:512
error_t tlsParseAlert(TlsContext *context, const TlsAlert *message, size_t length)
Parse Alert message.
Definition: tls_common.c:1846
PEM file import functions.
@ ERROR_INVALID_PARAMETER
Invalid parameter.
Definition: error.h:47
@ TLS_FLAG_PEEK
Definition: tls.h:942
#define osMemcpy(dest, src, length)
Definition: os_port.h:137
error_t tls13SendEarlyData(TlsContext *context, const void *data, size_t length, size_t *written)
Send early data to the remote TLS server.
@ TLS_GROUP_ECDH_X25519
Definition: tls.h:1306
#define TlsContext
Definition: tls.h:36
error_t
Error codes.
Definition: error.h:43
DTLS record protocol.
bool_t tls13IsGroupSupported(TlsContext *context, uint16_t namedGroup)
Check whether a given named group is supported.
Definition: tls13_misc.c:583
void ecInitPublicKey(EcPublicKey *key)
Initialize an EC public key.
Definition: ec.c:153
@ TLS_CONNECTION_END_SERVER
Definition: tls.h:909
#define TLS_MIN_RECORD_LENGTH
Definition: tls.h:877
void tlsFreeEncryptionEngine(TlsEncryptionEngine *encryptionEngine)
Release encryption engine.
Definition: tls_misc.c:891
TlsClientAuthMode
Client authentication mode.
Definition: tls.h:918
error_t tlsSetTicketCallbacks(TlsContext *context, TlsTicketEncryptCallback ticketEncryptCallback, TlsTicketDecryptCallback ticketDecryptCallback, void *param)
Set ticket encryption/decryption callbacks.
Definition: tls.c:1384
#define TLS_VERSION_1_2
Definition: tls.h:98
@ TLS_FLAG_WAIT_ALL
Definition: tls.h:943
@ TLS_GROUP_NONE
Definition: tls.h:1277
error_t tlsSetTimeout(TlsContext *context, systime_t timeout)
Set timeout for blocking calls (for DTLS only)
Definition: tls.c:1446
error_t(* TlsEcdhCallback)(TlsContext *context)
ECDH key agreement callback function.
Definition: tls.h:1890
@ ERROR_FAILURE
Generic error code.
Definition: error.h:45
#define TLS_MAX_VERSION
Definition: tls.h:131
TlsEarlyDataStatus tlsGetEarlyDataStatus(TlsContext *context)
Check whether the server has accepted or rejected the early data.
Definition: tls.c:1678
#define TLS_MIN_VERSION
Definition: tls.h:124
@ TLS_TYPE_APPLICATION_DATA
Definition: tls.h:967
Helper functions for TLS 1.3 client.
error_t tlsAddCertificate(TlsContext *context, const char_t *certChain, size_t certChainLen, const char_t *privateKey, size_t privateKeyLen)
Import a certificate and the corresponding private key.
Definition: tls.c:1159
@ TLS_TYPE_ALERT
Definition: tls.h:965
#define TLS_VERSION_1_3
Definition: tls.h:99
@ TLS_STATE_EARLY_DATA
Definition: tls.h:1363
Handshake message processing (TLS client and server)
void dhFree(DhContext *context)
Release Diffie-Hellman context.
Definition: dh.c:71
bool_t tlsIsTxReady(TlsContext *context)
Check whether some data is ready for transmission.
Definition: tls.c:2092
error_t tlsSetPreferredGroup(TlsContext *context, uint16_t group)
Specify the preferred ECDHE or FFDHE group.
Definition: tls.c:623
TLS record protocol.
#define TLS_MAX_CERTIFICATES
Definition: tls.h:250
error_t tlsReadProtocolData(TlsContext *context, uint8_t **data, size_t *length, TlsContentType *contentType)
Read protocol data.
Definition: tls_record.c:158
@ TLS_STATE_SERVER_HELLO_3
Definition: tls.h:1368
@ TLS_HASH_ALGO_SHA256
Definition: tls.h:1154
error_t tlsEnableSessionTickets(TlsContext *context, bool_t enabled)
Enable session ticket mechanism.
Definition: tls.c:1304
error_t dtlsWriteProtocolData(TlsContext *context, const uint8_t *data, size_t length, TlsContentType contentType)
Write protocol data.
Definition: dtls_record.c:59
error_t tlsSaveSessionState(const TlsContext *context, TlsSessionState *session)
Save TLS session.
Definition: tls.c:2486
#define LSB(x)
Definition: os_port.h:54
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:1856
@ TLS_CLIENT_AUTH_NONE
Definition: tls.h:919
#define MIN(a, b)
Definition: os_port.h:62
error_t tlsSetKeyLogCallback(TlsContext *context, TlsKeyLogCallback keyLogCallback)
Register key logging callback function (for debugging purpose only)
Definition: tls.c:759
__start_packed struct @22 TlsRecord
TLS record.
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:1567
TlsCertificateType
Certificate types.
Definition: tls.h:1124
error_t tlsSetServerName(TlsContext *context, const char_t *serverName)
Set the server name.
Definition: tls.c:367
size_t privateKeyLen
Length of the private key.
Definition: tls.h:1990
Certificate descriptor.
Definition: tls.h:1986
Transcript hash calculation.
@ TLS_FLAG_BREAK_CHAR
Definition: tls.h:944
error_t tlsRestoreSessionId(TlsContext *context, const TlsSessionState *session)
Restore a TLS session using session ID.
Definition: tls_misc.c:535
char_t * serverName
ServerName extension.
Definition: tls.h:1964
uint32_t systime_t
System time.
error_t tlsSetRpkVerifyCallback(TlsContext *context, TlsRpkVerifyCallback rpkVerifyCallback)
Register the raw public key verification callback function.
Definition: tls.c:1099
error_t tlsSetEcdsaVerifyCallback(TlsContext *context, TlsEcdsaVerifyCallback ecdsaVerifyCallback)
Register ECDSA signature verification callback function.
Definition: tls.c:732
bool_t tlsIsRxReady(TlsContext *context)
Check whether some data is available in the receive buffer.
Definition: tls.c:2125
uint16_t group
Definition: tls13_misc.h:206
uint8_t flags
Definition: tcp.h:349
@ TLS_TYPE_NONE
Definition: tls.h:963
void ecdhInit(EcdhContext *context)
Initialize ECDH context.
Definition: ecdh.c:48
error_t(* TlsEcdsaSignCallback)(TlsContext *context, const uint8_t *digest, size_t digestLen, EcdsaSignature *signature)
ECDSA signature generation callback function.
Definition: tls.h:1897
TlsSignatureAlgo signAlgo
Signature algorithm used to sign the end entity certificate.
Definition: tls.h:1992
char char_t
Definition: compiler_port.h:43
error_t x509ParseCertificateEx(const uint8_t *data, size_t length, X509CertificateInfo *certInfo, bool_t ignoreUnknown)
Parse a X.509 certificate.
TlsContentType
Content type.
Definition: tls.h:962
@ TLS_STATE_CLOSING
Definition: tls.h:1391
@ TLS_EARLY_DATA_ACCEPTED
Definition: tls.h:932
error_t dtlsReadProtocolData(TlsContext *context, uint8_t **data, size_t *length, TlsContentType *contentType)
Read protocol data.
Definition: dtls_record.c:131
error_t tlsSetBufferSize(TlsContext *context, size_t txBufferSize, size_t rxBufferSize)
Set TLS buffer size.
Definition: tls.c:483
TLS session state.
Definition: tls.h:1943
@ ERROR_NOT_CONNECTED
Definition: error.h:79
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:896
TlsState tlsGetState(TlsContext *context)
Retrieve current state.
Definition: tls.c:194
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:245
#define TLS_VERSION_1_0
Definition: tls.h:96
@ TLS_STATE_INIT
Definition: tls.h:1360
error_t tlsSetPskCallback(TlsContext *context, TlsPskCallback pskCallback)
Register PSK callback function.
Definition: tls.c:1073
error_t tlsWriteProtocolData(TlsContext *context, const uint8_t *data, size_t length, TlsContentType contentType)
Write protocol data.
Definition: tls_record.c:55
error_t tlsSetSocketCallbacks(TlsContext *context, TlsSocketSendCallback socketSendCallback, TlsSocketReceiveCallback socketReceiveCallback, TlsSocketHandle handle)
Set socket send and receive callbacks.
Definition: tls.c:218
error_t tlsSetCipherSuites(TlsContext *context, const uint16_t *cipherSuites, uint_t length)
Specify the list of allowed cipher suites.
Definition: tls.c:567
TlsSignatureAlgo
Signature algorithms.
Definition: tls.h:1166
@ TLS_CONNECTION_END_CLIENT
Definition: tls.h:908
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:1721
TLS (Transport Layer Security)
uint16_t version
TLS protocol version.
Definition: tls.h:1944
#define osTolower(c)
Definition: os_port.h:245
error_t tlsSetAlpnProtocolList(TlsContext *context, const char_t *protocolList)
Set the list of supported ALPN protocols.
Definition: tls.c:812
@ TLS_TRANSPORT_PROTOCOL_STREAM
Definition: tls.h:897
uint8_t mode
Definition: ntp_common.h:149
void tlsFree(TlsContext *context)
Release TLS context.
Definition: tls.c:2330
const char_t * certChain
End entity certificate chain (PEM format)
Definition: tls.h:1987
error_t(* TlsPskCallback)(TlsContext *context, const uint8_t *pskIdentity, size_t pskIdentityLen)
Pre-shared key callback function.
Definition: tls.h:1848
__start_packed struct @3 DtlsRecord
DTLS record.
error_t tlsSetClientAuthMode(TlsContext *context, TlsClientAuthMode mode)
Set client authentication mode (for servers only)
Definition: tls.c:461
const char_t * tlsGetAlpnProtocol(TlsContext *context)
Get the name of the selected ALPN protocol.
Definition: tls.c:886
void tlsProcessError(TlsContext *context, error_t errorCode)
Translate an error code to an alert message.
Definition: tls_misc.c:55
error_t tlsAllowUnknownAlpnProtocols(TlsContext *context, bool_t allowed)
Allow unknown ALPN protocols.
Definition: tls.c:786
TlsNamedGroup
Named groups.
Definition: tls.h:1276
error_t tlsSetCookieCallbacks(TlsContext *context, DtlsCookieGenerateCallback cookieGenerateCallback, DtlsCookieVerifyCallback cookieVerifyCallback, void *param)
Set cookie generation/verification callbacks (for DTLS only)
Definition: tls.c:1474
const char_t * privateKey
Private key (PEM format)
Definition: tls.h:1989
void(* TlsKeyLogCallback)(TlsContext *context, const char_t *key)
Key logging callback function (for debugging purpose only)
Definition: tls.h:1913
error_t tlsSetPrng(TlsContext *context, const PrngAlgo *prngAlgo, void *prngContext)
Set the pseudo-random number generator to be used.
Definition: tls.c:339
error_t(* TlsCertVerifyCallback)(TlsContext *context, const X509CertificateInfo *certInfo, uint_t pathLen, void *param)
Certificate verification callback function.
Definition: tls.h:1856
unsigned int uint_t
Definition: compiler_port.h:45
#define osMemset(p, value, length)
Definition: os_port.h:131
#define tlsFreeMem(p)
Definition: tls.h:811
#define TLS_MAX_RECORD_OVERHEAD
Definition: tls.h:881
error_t tlsSetTrustedCaList(TlsContext *context, const char_t *trustedCaList, size_t length)
Import a trusted CA list.
Definition: tls.c:1127
error_t pemImportDhParameters(const char_t *input, size_t length, DhParameters *params)
Decode a PEM file containing Diffie-Hellman parameters.
Definition: pem_import.c:148
error_t tlsInitSessionState(TlsSessionState *session)
Initialize session state.
Definition: tls.c:2465
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:1881
#define osStrcpy(s1, s2)
Definition: os_port.h:197
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:975
error_t tlsConnect(TlsContext *context)
Initiate the TLS handshake.
Definition: tls.c:1630
void dsaFreePublicKey(DsaPublicKey *key)
Release a DSA public key.
Definition: dsa.c:119
@ ERROR_INVALID_SESSION
Definition: error.h:284
error_t tls13RestoreSessionTicket(TlsContext *context, const TlsSessionState *session)
Restore a TLS session using session ticket.
Definition: tls13_ticket.c:183
TlsNamedGroup namedCurve
Named curve used to generate the EC public key.
Definition: tls.h:1994
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:651
@ NO_ERROR
Success.
Definition: error.h:44
uint8_t c
Definition: ndp.h:512
Debugging facilities.
void rsaInitPublicKey(RsaPublicKey *key)
Initialize an RSA public key.
Definition: rsa.c:105
void * TlsSocketHandle
Socket handle.
Definition: tls.h:1817
void ecFreePublicKey(EcPublicKey *key)
Release an EC public key.
Definition: ec.c:165
TlsEarlyDataStatus
Early data status.
Definition: tls.h:930
char_t * ticketAlpn
ALPN protocol associated with the ticket.
Definition: tls.h:1960
void tlsFreeTranscriptHash(TlsContext *context)
Release transcript hash context.
#define INFINITE_DELAY
Definition: os_port.h:74
error_t tlsGetCertificateType(const X509CertificateInfo *certInfo, TlsCertificateType *certType, TlsSignatureAlgo *certSignAlgo, TlsHashAlgo *certHashAlgo, TlsNamedGroup *namedCurve)
Retrieve the certificate type.
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:584
@ TLS_STATE_CLOSED
Definition: tls.h:1392