tls_common.c
Go to the documentation of this file.
1 /**
2  * @file tls_common.c
3  * @brief Handshake message processing (TLS client and server)
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2010-2026 Oryx Embedded SARL. All rights reserved.
10  *
11  * This file is part of CycloneSSL Open.
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26  *
27  * @author Oryx Embedded SARL (www.oryx-embedded.com)
28  * @version 2.6.2
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL TLS_TRACE_LEVEL
33 
34 //Dependencies
35 #include "tls/tls.h"
36 #include "tls/tls_cipher_suites.h"
37 #include "tls/tls_handshake.h"
38 #include "tls/tls_client.h"
39 #include "tls/tls_server.h"
40 #include "tls/tls_common.h"
41 #include "tls/tls_certificate.h"
42 #include "tls/tls_sign_generate.h"
43 #include "tls/tls_sign_verify.h"
45 #include "tls/tls_cache.h"
46 #include "tls/tls_record.h"
47 #include "tls/tls_misc.h"
50 #include "dtls/dtls_record.h"
51 #include "quic/tls_quic_misc.h"
52 #include "pkix/pem_import.h"
53 #include "pkix/x509_cert_parse.h"
54 #include "debug.h"
55 
56 //Check TLS library configuration
57 #if (TLS_SUPPORT == ENABLED)
58 
59 
60 /**
61  * @brief Send Certificate message
62  * @param[in] context Pointer to the TLS context
63  * @return Error code
64  **/
65 
67 {
68  error_t error;
69  size_t length;
71 
72  //Initialize status code
73  error = NO_ERROR;
74 
75  //Point to the buffer where to format the message
76  message = (TlsCertificate *) (context->txBuffer + context->txBufferLen);
77 
78 #if (TLS_CLIENT_SUPPORT == ENABLED)
79  //Client mode?
80  if(context->entity == TLS_CONNECTION_END_CLIENT)
81  {
82  //The client must send a Certificate message if the server requests it
83  if(context->clientCertRequested)
84  {
85  //Format Certificate message
86  error = tlsFormatCertificate(context, message, &length);
87 
88  //Check status code
89  if(!error)
90  {
91  //Debug message
92  TRACE_INFO("Sending Certificate message (%" PRIuSIZE " bytes)...\r\n", length);
94 
95  //Send handshake message
96  error = tlsSendHandshakeMessage(context, message, length,
98  }
99  }
100  }
101  else
102 #endif
103 #if (TLS_SERVER_SUPPORT == ENABLED)
104  //Server mode?
105  if(context->entity == TLS_CONNECTION_END_SERVER)
106  {
107  //The server must send a Certificate message whenever the agreed-upon
108  //key exchange method uses certificates for authentication
109  if(context->cert != NULL)
110  {
111  //Format Certificate message
112  error = tlsFormatCertificate(context, message, &length);
113 
114  //Check status code
115  if(!error)
116  {
117  //Debug message
118  TRACE_INFO("Sending Certificate message (%" PRIuSIZE " bytes)...\r\n", length);
120 
121  //Send handshake message
122  error = tlsSendHandshakeMessage(context, message, length,
124  }
125  }
126  }
127  else
128 #endif
129  //Unsupported mode of operation?
130  {
131  //Report an error
132  error = ERROR_FAILURE;
133  }
134 
135  //Check status code
136  if(error == NO_ERROR || error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
137  {
138  //Version of TLS prior to TLS 1.3?
139  if(context->version <= TLS_VERSION_1_2)
140  {
141  //Check whether TLS operates as a client or a server
142  if(context->entity == TLS_CONNECTION_END_CLIENT)
143  {
145  }
146  else
147  {
149  }
150  }
151  else
152  {
153  //Check whether TLS operates as a client or a server
154  if(context->entity == TLS_CONNECTION_END_CLIENT)
155  {
156  //Clients must send a CertificateVerify message whenever
157  //authenticating via a certificate
158  if(context->clientCertRequested)
159  {
161  }
162  else
163  {
165  }
166  }
167  else
168  {
169  //Servers must send a CertificateVerify message whenever
170  //authenticating via a certificate
172  }
173  }
174  }
175 
176  //Return status code
177  return error;
178 }
179 
180 
181 /**
182  * @brief Send CertificateVerify message
183  *
184  * The CertificateVerify message is used to provide explicit verification
185  * of a client certificate. This message is only sent following a client
186  * certificate that has signing capability
187  *
188  * @param[in] context Pointer to the TLS context
189  * @return Error code
190  **/
191 
193 {
194  error_t error;
195  size_t length;
197 
198  //Initialize status code
199  error = NO_ERROR;
200 
201  //The CertificateVerify message is only sent following a client certificate
202  //that has signing capability
203  if(context->cert != NULL)
204  {
205  //Check certificate type
206  if(context->cert->type == TLS_CERT_RSA_SIGN ||
207  context->cert->type == TLS_CERT_RSA_PSS_SIGN ||
208  context->cert->type == TLS_CERT_DSS_SIGN ||
209  context->cert->type == TLS_CERT_ECDSA_SIGN ||
210  context->cert->type == TLS_CERT_SM2_SIGN ||
211  context->cert->type == TLS_CERT_ED25519_SIGN ||
212  context->cert->type == TLS_CERT_ED448_SIGN)
213  {
214  //Point to the buffer where to format the message
215  message = (TlsCertificateVerify *) (context->txBuffer + context->txBufferLen);
216 
217  //Format CertificateVerify message
218  error = tlsFormatCertificateVerify(context, message, &length);
219 
220  //Check status code
221  if(!error)
222  {
223  //Debug message
224  TRACE_INFO("Sending CertificateVerify message (%" PRIuSIZE " bytes)...\r\n", length);
226 
227  //Send handshake message
228  error = tlsSendHandshakeMessage(context, message, length,
230  }
231  }
232  }
233 
234  //Check status code
235  if(error == NO_ERROR || error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
236  {
237  //Version of TLS prior to TLS 1.3?
238  if(context->version <= TLS_VERSION_1_2)
239  {
240  //Send a ChangeCipherSpec message to the server
242  }
243  else
244  {
245  //Send a Finished message to the peer
246  if(context->entity == TLS_CONNECTION_END_CLIENT)
247  {
249  }
250  else
251  {
253  }
254  }
255  }
256 
257  //Return status code
258  return error;
259 }
260 
261 
262 /**
263  * @brief Send ChangeCipherSpec message
264  *
265  * The change cipher spec message is sent by both the client and the
266  * server to notify the receiving party that subsequent records will be
267  * protected under the newly negotiated CipherSpec and keys
268  *
269  * @param[in] context Pointer to the TLS context
270  * @return Error code
271  **/
272 
274 {
275  error_t error;
276  size_t length;
278 
279  //Point to the buffer where to format the message
280  message = (TlsChangeCipherSpec *) (context->txBuffer + context->txBufferLen);
281 
282  //Format ChangeCipherSpec message
283  error = tlsFormatChangeCipherSpec(context, message, &length);
284 
285  //Check status code
286  if(!error)
287  {
288  //Debug message
289  TRACE_INFO("Sending ChangeCipherSpec message (%" PRIuSIZE " bytes)...\r\n", length);
291 
292  //TLS protocol?
293  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_STREAM ||
294  context->transportProtocol == TLS_TRANSPORT_PROTOCOL_EAP)
295  {
296  //Send ChangeCipherSpec message
297  error = tlsWriteProtocolData(context, (uint8_t *) message, length,
299  }
300 #if (DTLS_SUPPORT == ENABLED)
301  //DTLS protocol?
302  else if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
303  {
304  //Send ChangeCipherSpec message
305  error = dtlsWriteProtocolData(context, (uint8_t *) message, length,
307  }
308 #endif
309  //QUIC protocol?
310  else
311  {
312  //QUIC provides no means to carry a change_cipher_spec record (refer
313  //to RFC 9001, section 8.4)
314  error = ERROR_INVALID_PROTOCOL;
315  }
316  }
317 
318  //Check status code
319  if(error == NO_ERROR || error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
320  {
321  //Version of TLS prior to TLS 1.3?
322  if(context->version <= TLS_VERSION_1_2)
323  {
324  //Inform the record layer that subsequent records will be protected
325  //under the newly negotiated encryption algorithm
326  error = tlsUpdateEncryptionEngine(context, context->encryptionEngine,
327  context->entity, TLS_ENCRYPTION_LEVEL_APPLICATION, NULL);
328 
329  //Check status code
330  if(!error)
331  {
332  //Send a Finished message to the peer
333  if(context->entity == TLS_CONNECTION_END_CLIENT)
334  {
336  }
337  else
338  {
340  }
341  }
342  }
343  else
344  {
345 #if (TLS13_MIDDLEBOX_COMPAT_SUPPORT == ENABLED)
346  //The middlebox compatibility mode improves the chance of successfully
347  //connecting through middleboxes
348  if(context->state == TLS_STATE_CLIENT_CHANGE_CIPHER_SPEC ||
349  context->state == TLS_STATE_SERVER_CHANGE_CIPHER_SPEC_2)
350  {
351  //The client can send its second flight
353  }
354  else if(context->state == TLS_STATE_SERVER_CHANGE_CIPHER_SPEC ||
355  context->state == TLS_STATE_CLIENT_CHANGE_CIPHER_SPEC_2)
356  {
357  //All handshake messages after the ServerHello are now encrypted
359  }
360  else
361 #endif
362  {
363  //Middlebox compatibility mode is not implemented
364  error = ERROR_UNEXPECTED_STATE;
365  }
366  }
367  }
368 
369  //Return status code
370  return error;
371 }
372 
373 
374 /**
375  * @brief Send Finished message
376  *
377  * A Finished message is always sent immediately after a change
378  * cipher spec message to verify that the key exchange and
379  * authentication processes were successful. It is essential that a
380  * change cipher spec message be received between the other handshake
381  * messages and the Finished message
382  *
383  * @param[in] context Pointer to the TLS context
384  * @return Error code
385  **/
386 
388 {
389  error_t error;
390  size_t length;
392 
393  //Point to the buffer where to format the message
394  message = (TlsFinished *) (context->txBuffer + context->txBufferLen);
395 
396  //Check whether TLS operates as a client or a server
397  if(context->entity == TLS_CONNECTION_END_CLIENT)
398  {
399  //The verify data is generated from all messages in this handshake
400  //up to but not including the Finished message
402  context->clientVerifyData, &context->clientVerifyDataLen);
403  }
404  else
405  {
406  //The verify data is generated from all messages in this handshake
407  //up to but not including the Finished message
409  context->serverVerifyData, &context->serverVerifyDataLen);
410  }
411 
412  //Check status code
413  if(!error)
414  {
415  //Format Finished message
416  error = tlsFormatFinished(context, message, &length);
417  }
418 
419  //Check status code
420  if(!error)
421  {
422  //Debug message
423  TRACE_INFO("Sending Finished message (%" PRIuSIZE " bytes)...\r\n", length);
425 
426  //Send handshake message
427  error = tlsSendHandshakeMessage(context, message, length,
429  }
430 
431  //Check status code
432  if(error == NO_ERROR || error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
433  {
434  //Version of TLS prior to TLS 1.3?
435  if(context->version <= TLS_VERSION_1_2)
436  {
437  //Check whether TLS operates as a client or a server
438  if(context->entity == TLS_CONNECTION_END_CLIENT)
439  {
440  //Abbreviated or full handshake?
441  if(context->resume)
442  {
443  //The client and server can now exchange application-layer data
445  }
446  else
447  {
448 #if (TLS_TICKET_SUPPORT == ENABLED)
449  //The server uses the SessionTicket extension to indicate to
450  //the client that it will send a new session ticket using the
451  //NewSessionTicket handshake message
452  if(context->sessionTicketExtReceived)
453  {
454  //Wait for a NewSessionTicket message from the server
456  }
457  else
458 #endif
459  {
460  //Wait for a ChangeCipherSpec message from the server
462  }
463  }
464  }
465  else
466  {
467  //Abbreviated or full handshake?
468  if(context->resume)
469  {
470  //Wait for a ChangeCipherSpec message from the client
472  }
473  else
474  {
475  //The client and server can now exchange application-layer data
477  }
478  }
479  }
480  else
481  {
482  //Check whether TLS operates as a client or a server
483  if(context->entity == TLS_CONNECTION_END_CLIENT)
484  {
485  //Compute client application traffic keys
487  }
488  else
489  {
490  //Compute server application traffic keys
492  }
493  }
494  }
495 
496  //Return status code
497  return error;
498 }
499 
500 
501 /**
502  * @brief Send Alert message
503  * @param[in] context Pointer to the TLS context
504  * @param[in] level Severity of the message (warning or fatal)
505  * @param[in] description Description of the alert
506  * @return Error code
507  **/
508 
509 error_t tlsSendAlert(TlsContext *context, uint8_t level, uint8_t description)
510 {
511  error_t error;
512  size_t length;
513  TlsAlert *message;
514 
515  //Point to the buffer where to format the message
516  message = (TlsAlert *) (context->txBuffer + context->txBufferLen);
517 
518  //Format Alert message
519  error = tlsFormatAlert(context, level, description, message, &length);
520 
521  //Check status code
522  if(!error)
523  {
524  //Debug message
525  TRACE_INFO("Sending Alert message (%" PRIuSIZE " bytes)...\r\n", length);
527 
528  //TLS protocol?
529  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_STREAM ||
530  context->transportProtocol == TLS_TRANSPORT_PROTOCOL_EAP)
531  {
532  //Send Alert message
533  error = tlsWriteProtocolData(context, (uint8_t *) message, length,
535  }
536 #if (DTLS_SUPPORT == ENABLED)
537  //DTLS protocol?
538  else if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
539  {
540  //Send Alert message
541  error = dtlsWriteProtocolData(context, (uint8_t *) message, length,
543  }
544 #endif
545 #if (TLS_QUIC_SUPPORT == ENABLED)
546  //QUIC protocol?
547  else if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_QUIC)
548  {
549  //TLS alert messages are carried directly over the QUIC transport
550  //(refer to RFC 9001, section 3)
551  error = tlsSendQuicAlertMessage(context, message, length);
552  }
553 #endif
554  //Unknown protocol?
555  else
556  {
557  //Report an error
558  error = ERROR_INVALID_PROTOCOL;
559  }
560  }
561 
562  //Alert messages convey the severity of the message
563  if(level == TLS_ALERT_LEVEL_WARNING)
564  {
565  //If an alert with a level of warning is sent, generally the
566  //connection can continue normally
568  {
569  //Either party may initiate a close by sending a close_notify alert
570  context->closeNotifySent = TRUE;
571 
572  //Update FSM state
574  }
575  }
576  else if(level == TLS_ALERT_LEVEL_FATAL)
577  {
578  //Alert messages with a level of fatal result in the immediate
579  //termination of the connection
580  context->fatalAlertSent = TRUE;
581 
582 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
583  //Any connection terminated with a fatal alert must not be resumed
584  if(context->entity == TLS_CONNECTION_END_SERVER)
585  {
586  tlsRemoveFromCache(context);
587  }
588 #endif
589 
590  //Servers and clients must forget any session identifiers
591  osMemset(context->sessionId, 0, 32);
592  context->sessionIdLen = 0;
593 
594  //Update FSM state
596  }
597 
598  //Return status code
599  return error;
600 }
601 
602 
603 /**
604  * @brief Format Certificate message
605  * @param[in] context Pointer to the TLS context
606  * @param[out] message Buffer where to format the Certificate message
607  * @param[out] length Length of the resulting Certificate message
608  * @return Error code
609  **/
610 
612  size_t *length)
613 {
614  error_t error;
615  size_t n;
616  uint8_t *p;
617  TlsCertList *certList;
618 
619  //Point to the beginning of the handshake message
620  p = message;
621  //Length of the handshake message
622  *length = 0;
623 
624 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
625  //TLS 1.3 currently selected?
626  if(context->version == TLS_VERSION_1_3)
627  {
628  Tls13CertRequestContext *certRequestContext;
629 
630  //Point to the certificate request context
631  certRequestContext = (Tls13CertRequestContext *) p;
632 
633  //Check whether TLS operates as a client or a server
634  if(context->entity == TLS_CONNECTION_END_CLIENT)
635  {
636  //The value of the certificate_request_context field from server's
637  //CertificateRequest message is echoed in the Certificate message
638  if(context->certRequestContextLen > 0)
639  {
640  //Copy certificate request context
641  osMemcpy(certRequestContext->value, context->certRequestContext,
642  context->certRequestContextLen);
643  }
644 
645  //The context is preceded by a length field
646  certRequestContext->length = (uint8_t) context->certRequestContextLen;
647  }
648  else
649  {
650  //In the case of server authentication, this field shall be zero length
651  certRequestContext->length = 0;
652  }
653 
654  //Point to the next field
655  p += sizeof(Tls13CertRequestContext) + certRequestContext->length;
656  //Adjust the length of the Certificate message
657  *length += sizeof(Tls13CertRequestContext) + certRequestContext->length;
658  }
659 #endif
660 
661  //Point to the chain of certificates
662  certList = (TlsCertList *) p;
663 
664 #if (TLS_RAW_PUBLIC_KEY_SUPPORT == ENABLED)
665  //Check certificate type
666  if(context->certFormat == TLS_CERT_FORMAT_RAW_PUBLIC_KEY)
667  {
668  //Format the raw public key
669  error = tlsFormatRawPublicKey(context, certList->value, &n);
670  }
671  else
672 #endif
673  {
674  //Format the certificate chain
675  error = tlsFormatCertificateList(context, certList->value, &n);
676  }
677 
678  //Check status code
679  if(!error)
680  {
681  //A 3-byte length field shall precede the certificate list
682  STORE24BE(n, certList->length);
683  //Adjust the length of the Certificate message
684  *length += sizeof(TlsCertList) + n;
685  }
686 
687  //Return status code
688  return error;
689 }
690 
691 
692 /**
693  * @brief Format CertificateVerify message
694  * @param[in] context Pointer to the TLS context
695  * @param[out] message Buffer where to format the CertificateVerify message
696  * @param[out] length Length of the resulting CertificateVerify message
697  * @return Error code
698  **/
699 
702 {
703  error_t error;
704 
705  //Length of the handshake message
706  *length = 0;
707 
708 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_1)
709  //TLS 1.0 or TLS 1.1 currently selected?
710  if(context->version <= TLS_VERSION_1_1)
711  {
712  //In TLS version prior to 1.2, the digitally-signed element combines
713  //MD5 and SHA-1
714  error = tlsGenerateSignature(context, message, length);
715  }
716  else
717 #endif
718 #if (TLS_MAX_VERSION >= TLS_VERSION_1_2 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
719  //TLS 1.2 currently selected?
720  if(context->version == TLS_VERSION_1_2)
721  {
722  //In TLS 1.2, the MD5/SHA-1 combination in the digitally-signed element
723  //has been replaced with a single hash. The signed element now includes
724  //a field that explicitly specifies the hash algorithm used
725  error = tls12GenerateSignature(context, message, length);
726  }
727  else
728 #endif
729 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
730  //TLS 1.3 currently selected?
731  if(context->version == TLS_VERSION_1_3)
732  {
733  //In TLS 1.3, the signed element specifies the signature algorithm used.
734  //The content that is covered under the signature is the transcript hash
735  //output
736  error = tls13GenerateSignature(context, message, length);
737  }
738  else
739 #endif
740  //Invalid TLS version?
741  {
742  //Report an error
743  error = ERROR_INVALID_VERSION;
744  }
745 
746  //Return status code
747  return error;
748 }
749 
750 
751 /**
752  * @brief Format ChangeCipherSpec message
753  * @param[in] context Pointer to the TLS context
754  * @param[out] message Buffer where to format the ChangeCipherSpec message
755  * @param[out] length Length of the resulting ChangeCipherSpec message
756  * @return Error code
757  **/
758 
761 {
762  //The message consists of a single byte of value 1
763  message->type = 1;
764 
765  //Length of the ChangeCipherSpec message
766  *length = sizeof(TlsChangeCipherSpec);
767 
768  //Successful processing
769  return NO_ERROR;
770 }
771 
772 
773 /**
774  * @brief Format Finished message
775  * @param[in] context Pointer to the TLS context
776  * @param[out] message Buffer where to format the Finished message
777  * @param[out] length Length of the resulting Finished message
778  * @return Error code
779  **/
780 
782  size_t *length)
783 {
784  //Check whether TLS operates as a client or a server
785  if(context->entity == TLS_CONNECTION_END_CLIENT)
786  {
787  //Copy the client's verify data
788  osMemcpy(message, context->clientVerifyData, context->clientVerifyDataLen);
789  //Length of the handshake message
790  *length = context->clientVerifyDataLen;
791  }
792  else
793  {
794  //Copy the server's verify data
795  osMemcpy(message, context->serverVerifyData, context->serverVerifyDataLen);
796  //Length of the handshake message
797  *length = context->serverVerifyDataLen;
798  }
799 
800  //Successful processing
801  return NO_ERROR;
802 }
803 
804 
805 /**
806  * @brief Format Alert message
807  * @param[in] context Pointer to the TLS context
808  * @param[in] level Severity of the message (warning or fatal)
809  * @param[in] description Description of the alert
810  * @param[out] message Buffer where to format the Alert message
811  * @param[out] length Length of the resulting Alert message
812  * @return Error code
813  **/
814 
815 error_t tlsFormatAlert(TlsContext *context, uint8_t level, uint8_t description,
816  TlsAlert *message, size_t *length)
817 {
818  //Severity of the message
819  message->level = level;
820  //Description of the alert
821  message->description = description;
822 
823  //Length of the Alert message
824  *length = sizeof(TlsAlert);
825 
826  //Successful processing
827  return NO_ERROR;
828 }
829 
830 
831 /**
832  * @brief Format CertificateAuthorities extension
833  * @param[in] context Pointer to the TLS context
834  * @param[in] p Output stream where to write the CertificateAuthorities extension
835  * @param[out] written Total number of bytes that have been written
836  * @return Error code
837  **/
838 
840  size_t *written)
841 {
842  error_t error;
843  size_t n;
844 
845  //Initialize status code
846  error = NO_ERROR;
847  //Initialize length field
848  n = 0;
849 
850 #if (TLS_CERT_AUTHORITIES_SUPPORT == ENABLED)
851  //The CertificateAuthorities extension is optional
852  if(context->certAuthoritiesEnabled)
853  {
854  TlsExtension *extension;
855 
856  //Add the CertificateAuthorities extension
857  extension = (TlsExtension *) p;
858  //Type of the extension
859  extension->type = HTONS(TLS_EXT_CERTIFICATE_AUTHORITIES);
860 
861  //The CertificateAuthorities extension is used to indicate the certificate
862  //authorities (CAs) which an endpoint supports and which should be used by
863  //the receiving endpoint to guide certificate selection
864  error = tlsFormatCertAuthorities(context, extension->value, &n);
865 
866  //Check status code
867  if(!error)
868  {
869  //The list must contains at least one distinguished name
870  if(n > sizeof(TlsCertAuthorities))
871  {
872  //Fix the length of the extension
873  extension->length = htons(n);
874 
875  //Compute the length, in bytes, of the CertificateAuthorities extension
876  n += sizeof(TlsExtension);
877  }
878  else
879  {
880  //The list of distinguished names is empty
881  n = 0;
882  }
883  }
884  }
885 #endif
886 
887  //Total number of bytes that have been written
888  *written = n;
889 
890  //Return status code
891  return error;
892 }
893 
894 
895 /**
896  * @brief Format the list of distinguished names of acceptable CAs
897  * @param[in] context Pointer to the TLS context
898  * @param[in] p Output stream where to write the list of distinguished names
899  * @param[out] written Total number of bytes that have been written
900  * @return Error code
901  **/
902 
904  size_t *written)
905 {
906  error_t error;
907  size_t n;
908  size_t pemCertLen;
909  const char_t *trustedCaList;
910  size_t trustedCaListLen;
911  uint8_t *derCert;
912  size_t derCertLen;
913  X509CertInfo *certInfo;
914  TlsCertAuthorities *certAuthorities;
915 
916  //Initialize status code
917  error = NO_ERROR;
918 
919  //The list contains the distinguished names of acceptable certificate
920  //authorities, represented in DER-encoded format
921  certAuthorities = (TlsCertAuthorities *) p;
922 
923  //Point to the first certificate authority
924  p = certAuthorities->value;
925  //Length of the list in bytes
926  n = 0;
927 
928  //Point to the first trusted CA certificate
929  trustedCaList = context->trustedCaList;
930  //Get the total length, in bytes, of the trusted CA list
931  trustedCaListLen = context->trustedCaListLen;
932 
933  //Allocate a memory buffer to store X.509 certificate info
934  certInfo = tlsAllocMem(sizeof(X509CertInfo));
935 
936  //Successful memory allocation?
937  if(certInfo != NULL)
938  {
939  //Loop through the list of trusted CA certificates
940  while(trustedCaListLen > 0 && error == NO_ERROR)
941  {
942  //The first pass calculates the length of the DER-encoded certificate
943  error = pemImportCertificate(trustedCaList, trustedCaListLen, NULL,
944  &derCertLen, &pemCertLen);
945 
946  //Check status code
947  if(!error)
948  {
949  //Allocate a memory buffer to hold the DER-encoded certificate
950  derCert = tlsAllocMem(derCertLen);
951 
952  //Successful memory allocation?
953  if(derCert != NULL)
954  {
955  //The second pass decodes the PEM certificate
956  error = pemImportCertificate(trustedCaList, trustedCaListLen,
957  derCert, &derCertLen, NULL);
958 
959  //Check status code
960  if(!error)
961  {
962  //Parse X.509 certificate
963  error = x509ParseCertificate(derCert, derCertLen, certInfo);
964  }
965 
966  //Valid CA certificate?
967  if(!error)
968  {
969  //Each distinguished name is preceded by a 2-byte length field
970  STORE16BE(certInfo->tbsCert.subject.raw.length, p);
971 
972  //The distinguished name shall be DER-encoded
973  osMemcpy(p + 2, certInfo->tbsCert.subject.raw.value,
974  certInfo->tbsCert.subject.raw.length);
975 
976  //Advance write pointer
977  p += certInfo->tbsCert.subject.raw.length + 2;
978  n += certInfo->tbsCert.subject.raw.length + 2;
979  }
980  else
981  {
982  //Discard current CA certificate
983  error = NO_ERROR;
984  }
985 
986  //Free previously allocated memory
987  tlsFreeMem(derCert);
988  }
989  else
990  {
991  //Failed to allocate memory
992  error = ERROR_OUT_OF_MEMORY;
993  }
994 
995  //Advance read pointer
996  trustedCaList += pemCertLen;
997  trustedCaListLen -= pemCertLen;
998  }
999  else
1000  {
1001  //End of file detected
1002  trustedCaListLen = 0;
1003  error = NO_ERROR;
1004  }
1005  }
1006 
1007  //Fix the length of the list
1008  certAuthorities->length = htons(n);
1009 
1010  //Free previously allocated memory
1011  tlsFreeMem(certInfo);
1012  }
1013  else
1014  {
1015  //Failed to allocate memory
1016  error = ERROR_OUT_OF_MEMORY;
1017  }
1018 
1019  //Check status code
1020  if(!error)
1021  {
1022  //Total number of bytes that have been written
1023  *written = sizeof(TlsCertAuthorities) + n;
1024  }
1025 
1026  //Return status code
1027  return error;
1028 }
1029 
1030 
1031 /**
1032  * @brief Parse Certificate message
1033  * @param[in] context Pointer to the TLS context
1034  * @param[in] message Incoming Certificate message to parse
1035  * @param[in] length Message length
1036  * @return Error code
1037  **/
1038 
1040  size_t length)
1041 {
1042  error_t error;
1043  size_t n;
1044  const uint8_t *p;
1045  const TlsCertList *certList;
1046 
1047  //Debug message
1048  TRACE_INFO("Certificate message received (%" PRIuSIZE " bytes)...\r\n", length);
1050 
1051  //Check whether TLS operates as a client or a server
1052  if(context->entity == TLS_CONNECTION_END_CLIENT)
1053  {
1054  //Version of TLS prior to TLS 1.3?
1055  if(context->version <= TLS_VERSION_1_2)
1056  {
1057  //Check current state
1058  if(context->state != TLS_STATE_SERVER_CERTIFICATE)
1059  return ERROR_UNEXPECTED_MESSAGE;
1060  }
1061  else
1062  {
1063  //The CertificateRequest message is optional
1064  if(context->state != TLS_STATE_CERTIFICATE_REQUEST &&
1065  context->state != TLS_STATE_SERVER_CERTIFICATE)
1066  {
1067  return ERROR_UNEXPECTED_MESSAGE;
1068  }
1069  }
1070  }
1071  else
1072  {
1073  //Check current state
1074  if(context->state != TLS_STATE_CLIENT_CERTIFICATE)
1075  return ERROR_UNEXPECTED_MESSAGE;
1076  }
1077 
1078  //Point to the beginning of the handshake message
1079  p = message;
1080 
1081 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
1082  //TLS 1.3 currently selected?
1083  if(context->version == TLS_VERSION_1_3)
1084  {
1085  const Tls13CertRequestContext *certRequestContext;
1086 
1087  //Point to the certificate request context
1088  certRequestContext = (Tls13CertRequestContext *) p;
1089 
1090  //Malformed Certificate message?
1091  if(length < sizeof(Tls13CertRequestContext))
1092  return ERROR_DECODING_FAILED;
1093  if(length < (sizeof(Tls13CertRequestContext) + certRequestContext->length))
1094  return ERROR_DECODING_FAILED;
1095 
1096  //Point to the next field
1097  p += sizeof(Tls13CertRequestContext) + certRequestContext->length;
1098  //Remaining bytes to process
1099  length -= sizeof(Tls13CertRequestContext) + certRequestContext->length;
1100  }
1101 #endif
1102 
1103  //Point to the chain of certificates
1104  certList = (TlsCertList *) p;
1105 
1106  //Malformed Certificate message?
1107  if(length < sizeof(TlsCertList))
1108  return ERROR_DECODING_FAILED;
1109 
1110  //Get the size occupied by the certificate list
1111  n = LOAD24BE(certList->length);
1112  //Remaining bytes to process
1113  length -= sizeof(TlsCertList);
1114 
1115  //Malformed Certificate message?
1116  if(n != length)
1117  return ERROR_DECODING_FAILED;
1118 
1119  //Non-empty certificate list?
1120  if(n > 0)
1121  {
1122 #if (TLS_RAW_PUBLIC_KEY_SUPPORT == ENABLED)
1123  //Check certificate type
1124  if(context->peerCertFormat == TLS_CERT_FORMAT_RAW_PUBLIC_KEY)
1125  {
1126  //Parse the raw public key
1127  error = tlsParseRawPublicKey(context, certList->value, n);
1128  }
1129  else
1130 #endif
1131  {
1132  //Parse the certificate chain
1133  error = tlsParseCertificateList(context, certList->value, n);
1134  }
1135  }
1136  else
1137  {
1138 #if (TLS_SERVER_SUPPORT == ENABLED)
1139  //Server mode?
1140  if(context->entity == TLS_CONNECTION_END_SERVER)
1141  {
1142  //Check whether client authentication is required
1143  if(context->clientAuthMode == TLS_CLIENT_AUTH_REQUIRED)
1144  {
1145  //Version of TLS prior to TLS 1.3?
1146  if(context->version <= TLS_VERSION_1_2)
1147  {
1148  //If the client does not send any certificates, the server
1149  //responds with a fatal handshake_failure alert (refer to
1150  //RFC 5246, section 7.4.6)
1151  error = ERROR_HANDSHAKE_FAILED;
1152  }
1153  else
1154  {
1155  //If the client does not send any certificates, the server
1156  //aborts the handshake with a certificate_required alert (refer
1157  //to RFC 8446, section 4.4.2.4)
1159  }
1160  }
1161  else
1162  {
1163  //The client did not send any certificates
1164  context->peerCertType = TLS_CERT_NONE;
1165  //The server may continue the handshake without client authentication
1166  error = NO_ERROR;
1167  }
1168  }
1169  else
1170 #endif
1171  //Client mode?
1172  {
1173  //The server's certificate list must always be non-empty (refer to
1174  //RFC 8446, section 4.4.2)
1175  error = ERROR_DECODING_FAILED;
1176  }
1177  }
1178 
1179  //Check status code
1180  if(!error)
1181  {
1182  //Version of TLS prior to TLS 1.3?
1183  if(context->version <= TLS_VERSION_1_2)
1184  {
1185  //Check whether TLS operates as a client or a server
1186  if(context->entity == TLS_CONNECTION_END_CLIENT)
1187  {
1188  //The server does not send a ServerKeyExchange message when RSA
1189  //key exchange method is used
1190  if(context->keyExchMethod == TLS_KEY_EXCH_RSA)
1191  {
1193  }
1194  else
1195  {
1197  }
1198  }
1199  else
1200  {
1201  //Wait for a ClientKeyExchange message from the client
1203  }
1204  }
1205  else
1206  {
1207  //Check whether TLS operates as a client or a server
1208  if(context->entity == TLS_CONNECTION_END_CLIENT)
1209  {
1210  //The server must send a CertificateVerify message immediately
1211  //after the Certificate message
1213  }
1214  else
1215  {
1216  //The client must send a CertificateVerify message when the
1217  //Certificate message is non-empty
1218  if(context->peerCertType != TLS_CERT_NONE)
1219  {
1221  }
1222  else
1223  {
1225  }
1226  }
1227  }
1228  }
1229 
1230  //Return status code
1231  return error;
1232 }
1233 
1234 
1235 /**
1236  * @brief Parse CertificateVerify message
1237  *
1238  * The CertificateVerify message is used to provide explicit verification
1239  * of a client certificate. This message is only sent following a client
1240  * certificate that has signing capability
1241  *
1242  * @param[in] context Pointer to the TLS context
1243  * @param[in] message Incoming CertificateVerify message to parse
1244  * @param[in] length Message length
1245  * @return Error code
1246  **/
1247 
1249  const TlsCertificateVerify *message, size_t length)
1250 {
1251  error_t error;
1252 
1253  //Debug message
1254  TRACE_INFO("CertificateVerify message received (%" PRIuSIZE " bytes)...\r\n", length);
1256 
1257  //Check whether TLS operates as a client or a server
1258  if(context->entity == TLS_CONNECTION_END_CLIENT)
1259  {
1260  //Check current state
1261  if(context->state != TLS_STATE_SERVER_CERTIFICATE_VERIFY)
1262  return ERROR_UNEXPECTED_MESSAGE;
1263  }
1264  else
1265  {
1266  //Check current state
1267  if(context->state != TLS_STATE_CLIENT_CERTIFICATE_VERIFY)
1268  return ERROR_UNEXPECTED_MESSAGE;
1269  }
1270 
1271 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_1)
1272  //TLS 1.0 or TLS 1.1 currently selected?
1273  if(context->version <= TLS_VERSION_1_1)
1274  {
1275  //In TLS version prior to 1.2, the digitally-signed element combines
1276  //MD5 and SHA-1
1277  error = tlsVerifySignature(context, message, length);
1278  }
1279  else
1280 #endif
1281 #if (TLS_MAX_VERSION >= TLS_VERSION_1_2 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
1282  //TLS 1.2 currently selected?
1283  if(context->version == TLS_VERSION_1_2)
1284  {
1285  //In TLS 1.2, the MD5/SHA-1 combination in the digitally-signed element
1286  //has been replaced with a single hash. The signed element now includes
1287  //a field that explicitly specifies the hash algorithm used
1288  error = tls12VerifySignature(context, message, length);
1289  }
1290  else
1291 #endif
1292 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
1293  //TLS 1.3 currently selected?
1294  if(context->version == TLS_VERSION_1_3)
1295  {
1296  //In TLS 1.3, the signed element specifies the signature algorithm used.
1297  //The content that is covered under the signature is the transcript hash
1298  //output
1299  error = tls13VerifySignature(context, message, length);
1300  }
1301  else
1302 #endif
1303  //Invalid TLS version?
1304  {
1305  //Report an error
1306  error = ERROR_INVALID_VERSION;
1307  }
1308 
1309  //Check status code
1310  if(!error)
1311  {
1312  //Version of TLS prior to TLS 1.3?
1313  if(context->version <= TLS_VERSION_1_2)
1314  {
1315  //Wait for a ChangeCipherSpec message from the client
1317  }
1318  else
1319  {
1320  //Wait for a Finished message from the peer
1321  if(context->entity == TLS_CONNECTION_END_CLIENT)
1322  {
1324  }
1325  else
1326  {
1328  }
1329  }
1330  }
1331 
1332  //Return status code
1333  return error;
1334 }
1335 
1336 
1337 /**
1338  * @brief Parse ChangeCipherSpec message
1339  * @param[in] context Pointer to the TLS context
1340  * @param[in] message Incoming ChangeCipherSpec message to parse
1341  * @param[in] length Message length
1342  * @return Error code
1343  **/
1344 
1346  const TlsChangeCipherSpec *message, size_t length)
1347 {
1348  error_t error;
1349 
1350  //Debug message
1351  TRACE_INFO("ChangeCipherSpec message received (%" PRIuSIZE " bytes)...\r\n", length);
1353 
1354  //Check the length of the ChangeCipherSpec message
1355  if(length != sizeof(TlsChangeCipherSpec))
1356  return ERROR_DECODING_FAILED;
1357 
1358  //The message consists of a single byte of value 1
1359  if(message->type != 0x01)
1360  return ERROR_DECODING_FAILED;
1361 
1362  //Version of TLS prior to TLS 1.3?
1363  if(context->version <= TLS_VERSION_1_2)
1364  {
1365  //Check whether TLS operates as a client or a server
1366  if(context->entity == TLS_CONNECTION_END_CLIENT)
1367  {
1368  //Check current state
1369  if(context->state != TLS_STATE_SERVER_CHANGE_CIPHER_SPEC)
1370  return ERROR_UNEXPECTED_MESSAGE;
1371  }
1372  else
1373  {
1374  //Check current state
1375  if(context->state != TLS_STATE_CLIENT_CHANGE_CIPHER_SPEC)
1376  return ERROR_UNEXPECTED_MESSAGE;
1377  }
1378 
1379  //Check whether TLS operates as a client or a server
1380  if(context->entity == TLS_CONNECTION_END_CLIENT)
1381  {
1382  //Initialize decryption engine using server write keys
1383  error = tlsUpdateEncryptionEngine(context, context->decryptionEngine,
1385  //Any error to report?
1386  if(error)
1387  return error;
1388 
1389  //Wait for a Finished message from the server
1391  }
1392  else
1393  {
1394  //Initialize decryption engine using client write keys
1395  error = tlsUpdateEncryptionEngine(context, context->decryptionEngine,
1397  //Any error to report?
1398  if(error)
1399  return error;
1400 
1401  //Wait for a Finished message from the client
1403  }
1404  }
1405  else
1406  {
1407  //In TLS 1.3, the ChangeCipherSpec message is used only for compatibility
1408  //purposes and must be dropped without further processing
1409  if(context->entity == TLS_CONNECTION_END_CLIENT)
1410  {
1411  //A ChangeCipherSpec message received received before the first
1412  //ClientHello message or after the server's Finished message must
1413  //be treated as an unexpected record type
1414  if(context->state != TLS_STATE_SERVER_HELLO &&
1415  context->state != TLS_STATE_SERVER_HELLO_2 &&
1416  context->state != TLS_STATE_ENCRYPTED_EXTENSIONS &&
1417  context->state != TLS_STATE_CERTIFICATE_REQUEST &&
1418  context->state != TLS_STATE_SERVER_CERTIFICATE &&
1419  context->state != TLS_STATE_SERVER_CERTIFICATE_VERIFY &&
1420  context->state != TLS_STATE_SERVER_FINISHED)
1421  {
1422  //Report an error
1423  return ERROR_UNEXPECTED_MESSAGE;
1424  }
1425  }
1426  else
1427  {
1428  //A ChangeCipherSpec message received received before the first
1429  //ClientHello message or after the client's Finished message must
1430  //be treated as an unexpected record type
1431  if(context->state != TLS_STATE_CLIENT_HELLO_2 &&
1432  context->state != TLS_STATE_CLIENT_CERTIFICATE &&
1433  context->state != TLS_STATE_CLIENT_CERTIFICATE_VERIFY &&
1434  context->state != TLS_STATE_CLIENT_FINISHED)
1435  {
1436  //Report an error
1437  return ERROR_UNEXPECTED_MESSAGE;
1438  }
1439  }
1440 
1441 #if (TLS_MAX_CHANGE_CIPHER_SPEC_MESSAGES > 0)
1442  //Increment the count of consecutive ChangeCipherSpec messages
1443  context->changeCipherSpecCount++;
1444 
1445  //Do not allow too many consecutive ChangeCipherSpec messages
1446  if(context->changeCipherSpecCount > TLS_MAX_CHANGE_CIPHER_SPEC_MESSAGES)
1447  return ERROR_UNEXPECTED_MESSAGE;
1448 #endif
1449  }
1450 
1451  //Successful processing
1452  return NO_ERROR;
1453 }
1454 
1455 
1456 /**
1457  * @brief Parse Finished message
1458  * @param[in] context Pointer to the TLS context
1459  * @param[in] message Incoming Finished message to parse
1460  * @param[in] length Message length
1461  * @return Error code
1462  **/
1463 
1465  size_t length)
1466 {
1467  error_t error;
1468 
1469  //Debug message
1470  TRACE_INFO("Finished message received (%" PRIuSIZE " bytes)...\r\n", length);
1472 
1473  //Check whether TLS operates as a client or a server
1474  if(context->entity == TLS_CONNECTION_END_CLIENT)
1475  {
1476  //Check current state
1477  if(context->state != TLS_STATE_SERVER_FINISHED)
1478  return ERROR_UNEXPECTED_MESSAGE;
1479 
1480  //The verify data is generated from all messages in this handshake
1481  //up to but not including the Finished message
1483  context->serverVerifyData, &context->serverVerifyDataLen);
1484  //Unable to generate the verify data?
1485  if(error)
1486  return error;
1487 
1488  //Check the length of the Finished message
1489  if(length != context->serverVerifyDataLen)
1490  {
1491 #if (TLS_MAX_EMPTY_RECORDS > 0)
1492  return ERROR_INVALID_SIGNATURE;
1493 #else
1494  return ERROR_DECODING_FAILED;
1495 #endif
1496  }
1497 
1498  //Check the resulting verify data
1499  if(osMemcmp(message, context->serverVerifyData, context->serverVerifyDataLen))
1500  return ERROR_INVALID_SIGNATURE;
1501  }
1502  else
1503  {
1504  //Check current state
1505  if(context->state != TLS_STATE_CLIENT_FINISHED)
1506  return ERROR_UNEXPECTED_MESSAGE;
1507 
1508  //The verify data is generated from all messages in this handshake
1509  //up to but not including the Finished message
1511  context->clientVerifyData, &context->clientVerifyDataLen);
1512  //Unable to generate the verify data?
1513  if(error)
1514  return error;
1515 
1516  //Check the length of the Finished message
1517  if(length != context->clientVerifyDataLen)
1518  {
1519 #if (TLS_MAX_EMPTY_RECORDS > 0)
1520  return ERROR_INVALID_SIGNATURE;
1521 #else
1522  return ERROR_DECODING_FAILED;
1523 #endif
1524  }
1525 
1526  //Check the resulting verify data
1527  if(osMemcmp(message, context->clientVerifyData, context->clientVerifyDataLen))
1528  return ERROR_INVALID_SIGNATURE;
1529  }
1530 
1531  //Version of TLS prior to TLS 1.3?
1532  if(context->version <= TLS_VERSION_1_2)
1533  {
1534  //Another handshake message cannot be packed in the same record as the
1535  //Finished
1536  if(context->rxBufferLen != 0)
1537  return ERROR_UNEXPECTED_MESSAGE;
1538 
1539  //Check whether TLS operates as a client or a server
1540  if(context->entity == TLS_CONNECTION_END_CLIENT)
1541  {
1542  //Abbreviated or full handshake?
1543  if(context->resume)
1544  {
1545  //Send a ChangeCipherSpec message to the server
1547  }
1548  else
1549  {
1550  //The client and server can now exchange application-layer data
1552  }
1553  }
1554  else
1555  {
1556  //Abbreviated or full handshake?
1557  if(context->resume)
1558  {
1559  //The client and server can now exchange application-layer data
1561  }
1562  else
1563  {
1564 #if (TLS_TICKET_SUPPORT == ENABLED)
1565  //The server uses the SessionTicket extension to indicate to
1566  //the client that it will send a new session ticket using the
1567  //NewSessionTicket handshake message
1568  if(context->sessionTicketExtSent)
1569  {
1570  //Send a NewSessionTicket message to the client
1572  }
1573  else
1574 #endif
1575  {
1576  //Send a ChangeCipherSpec message to the client
1578  }
1579  }
1580  }
1581  }
1582  else
1583  {
1584  //Check whether TLS operates as a client or a server
1585  if(context->entity == TLS_CONNECTION_END_CLIENT)
1586  {
1587  //Compute server application traffic keys
1589  }
1590  else
1591  {
1592  //Compute client application traffic keys
1594  }
1595  }
1596 
1597  //Successful processing
1598  return NO_ERROR;
1599 }
1600 
1601 
1602 /**
1603  * @brief Parse Alert message
1604  * @param[in] context Pointer to the TLS context
1605  * @param[in] message Incoming Alert message to parse
1606  * @param[in] length Message length
1607  * @return Error code
1608  **/
1609 
1611  size_t length)
1612 {
1613  //Debug message
1614  TRACE_INFO("Alert message received (%" PRIuSIZE " bytes)...\r\n", length);
1616 
1617  //Check message length
1618  if(length != sizeof(TlsAlert))
1619  return ERROR_INVALID_LENGTH;
1620 
1621  //Debug message
1622  TRACE_DEBUG(" Level = %" PRIu8 "\r\n", message->level);
1623  TRACE_DEBUG(" Description = %" PRIu8 "\r\n", message->description);
1624 
1625  //Alert messages convey the severity of the message
1626  if(message->level == TLS_ALERT_LEVEL_WARNING)
1627  {
1628 #if (TLS_MAX_WARNING_ALERTS > 0)
1629  //Increment the count of consecutive warning alerts
1630  context->alertCount++;
1631 
1632  //Do not allow too many consecutive warning alerts
1633  if(context->alertCount > TLS_MAX_WARNING_ALERTS)
1634  return ERROR_UNEXPECTED_MESSAGE;
1635 #endif
1636 
1637  //Check alert type
1638  if(message->description == TLS_ALERT_CLOSE_NOTIFY)
1639  {
1640  //A closure alert has been received
1641  context->closeNotifyReceived = TRUE;
1642 
1643  //Close down the connection immediately
1644  if(context->state == TLS_STATE_APPLICATION_DATA)
1645  {
1647  }
1648  }
1649  else if(message->description == TLS_ALERT_USER_CANCELED)
1650  {
1651  //This alert notifies the recipient that the sender is canceling the
1652  //handshake for some reason unrelated to a protocol failure
1653  }
1654  else
1655  {
1656  //TLS 1.3 currently selected?
1657  if(context->version == TLS_VERSION_1_3)
1658  {
1659  //Unknown alert types must be treated as error alerts
1660  return ERROR_DECODING_FAILED;
1661  }
1662  }
1663  }
1664  else if(message->level == TLS_ALERT_LEVEL_FATAL)
1665  {
1666  //A fatal alert message has been received
1667  context->fatalAlertReceived = TRUE;
1668 
1669 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
1670  //Any connection terminated with a fatal alert must not be resumed
1671  if(context->entity == TLS_CONNECTION_END_SERVER)
1672  {
1673  tlsRemoveFromCache(context);
1674  }
1675 #endif
1676 
1677  //Servers and clients must forget any session identifiers
1678  osMemset(context->sessionId, 0, 32);
1679  context->sessionIdLen = 0;
1680 
1681  //Alert messages with a level of fatal result in the immediate
1682  //termination of the connection
1683  tlsChangeState(context, TLS_STATE_CLOSED);
1684  }
1685  else
1686  {
1687  //Report an error
1688  return ERROR_ILLEGAL_PARAMETER;
1689  }
1690 
1691  //Successful processing
1692  return NO_ERROR;
1693 }
1694 
1695 #endif
#define TLS_MAX_CHANGE_CIPHER_SPEC_MESSAGES
Definition: tls.h:865
#define tlsAllocMem(size)
Definition: tls.h:889
#define htons(value)
Definition: cpu_endian.h:413
@ TLS_CERT_FORMAT_RAW_PUBLIC_KEY
Definition: tls.h:1240
TLS helper functions.
#define TRACE_INFO_ARRAY(p, a, n)
Definition: debug.h:106
X.509 certificate parsing.
error_t tlsFormatCertAuthorities(TlsContext *context, uint8_t *p, size_t *written)
Format the list of distinguished names of acceptable CAs.
Definition: tls_common.c:903
error_t tlsUpdateEncryptionEngine(TlsContext *context, TlsEncryptionEngine *encryptionEngine, TlsConnectionEnd entity, TlsEncryptionLevel level, const uint8_t *secret)
Update encryption engine.
Definition: tls_misc.c:1051
@ TLS_TRANSPORT_PROTOCOL_QUIC
Definition: tls.h:1018
RSA/DSA/ECDSA/SM2/EdDSA signature verification (TLS 1.3)
TLS cipher suites.
X509TbsCertificate tbsCert
Definition: x509_common.h:1123
@ TLS_ALERT_CLOSE_NOTIFY
Definition: tls.h:1145
@ ERROR_WOULD_BLOCK
Definition: error.h:96
error_t tlsSendChangeCipherSpec(TlsContext *context)
Send ChangeCipherSpec message.
Definition: tls_common.c:273
TLS handshake.
@ TLS_STATE_SERVER_KEY_EXCHANGE
Definition: tls.h:1570
__weak_func error_t tlsParseCertificateList(TlsContext *context, const uint8_t *p, size_t length)
Parse certificate chain.
@ ERROR_ILLEGAL_PARAMETER
Definition: error.h:244
error_t tls13VerifySignature(TlsContext *context, const uint8_t *p, size_t length)
Digital signature verification (TLS 1.3)
error_t tlsSendCertificate(TlsContext *context)
Send Certificate message.
Definition: tls_common.c:66
@ ERROR_UNEXPECTED_MESSAGE
Definition: error.h:195
QUIC helper functions.
uint8_t p
Definition: ndp.h:300
uint8_t message[]
Definition: chap.h:154
error_t tls12VerifySignature(TlsContext *context, const uint8_t *p, size_t length)
Digital signature verification (TLS 1.2)
#define TRUE
Definition: os_port.h:50
error_t x509ParseCertificate(const uint8_t *data, size_t length, X509CertInfo *certInfo)
Parse a X.509 certificate.
@ TLS_STATE_CERTIFICATE_REQUEST
Definition: tls.h:1572
@ TLS_TYPE_CHANGE_CIPHER_SPEC
Definition: tls.h:1085
@ TLS_TRANSPORT_PROTOCOL_DATAGRAM
Definition: tls.h:1017
Session cache management.
error_t tlsParseChangeCipherSpec(TlsContext *context, const TlsChangeCipherSpec *message, size_t length)
Parse ChangeCipherSpec message.
Definition: tls_common.c:1345
@ TLS_STATE_APPLICATION_DATA
Definition: tls.h:1589
#define osMemcmp(p1, p2, length)
Definition: os_port.h:156
@ ERROR_HANDSHAKE_FAILED
Definition: error.h:234
@ ERROR_OUT_OF_MEMORY
Definition: error.h:63
@ TLS_STATE_SERVER_APP_TRAFFIC_KEYS
Definition: tls.h:1587
@ TLS_CERT_DSS_SIGN
Definition: tls.h:1253
error_t tlsFormatCertificateVerify(TlsContext *context, TlsCertificateVerify *message, size_t *length)
Format CertificateVerify message.
Definition: tls_common.c:700
TlsChangeCipherSpec
Definition: tls.h:2005
TlsExtension
Definition: tls.h:1716
@ ERROR_INVALID_VERSION
Definition: error.h:118
error_t tlsSendHandshakeMessage(TlsContext *context, const void *data, size_t length, TlsMessageType type)
Send handshake message.
error_t tlsFormatFinished(TlsContext *context, TlsFinished *message, size_t *length)
Format Finished message.
Definition: tls_common.c:781
@ TLS_KEY_EXCH_RSA
Definition: tls.h:1202
__weak_func error_t tlsComputeVerifyData(TlsContext *context, TlsConnectionEnd entity, uint8_t *verifyData, size_t *verifyDataLen)
Compute verify data from previous handshake messages.
@ TLS_TYPE_CERTIFICATE
Definition: tls.h:1111
void TlsFinished
Finished message.
Definition: tls.h:1995
@ TLS_STATE_SERVER_HELLO
Definition: tls.h:1564
@ TLS_ALERT_LEVEL_WARNING
Definition: tls.h:1134
error_t pemImportCertificate(const char_t *input, size_t inputLen, uint8_t *output, size_t *outputLen, size_t *consumed)
Decode a PEM file containing a certificate.
Definition: pem_import.c:55
error_t tlsSendAlert(TlsContext *context, uint8_t level, uint8_t description)
Send Alert message.
Definition: tls_common.c:509
error_t tlsParseAlert(TlsContext *context, const TlsAlert *message, size_t length)
Parse Alert message.
Definition: tls_common.c:1610
PEM file import functions.
TlsCertAuthorities
Definition: tls.h:1682
#define osMemcpy(dest, src, length)
Definition: os_port.h:144
X.509 certificate.
Definition: x509_common.h:1121
#define TlsContext
Definition: tls.h:36
error_t
Error codes.
Definition: error.h:43
error_t tls12GenerateSignature(TlsContext *context, uint8_t *p, size_t *length)
Digital signature generation (TLS 1.2)
DTLS record layer.
@ TLS_CERT_ED25519_SIGN
Definition: tls.h:1266
@ TLS_CONNECTION_END_SERVER
Definition: tls.h:1030
#define TLS_VERSION_1_2
Definition: tls.h:97
void TlsCertificateVerify
CertificateVerify message.
Definition: tls.h:1976
@ ERROR_FAILURE
Generic error code.
Definition: error.h:45
TlsAlert
Definition: tls.h:2016
#define STORE16BE(a, p)
Definition: cpu_endian.h:262
error_t tlsRemoveFromCache(TlsContext *context)
Remove current session from cache.
Definition: tls_cache.c:269
@ TLS_STATE_SERVER_FINISHED
Definition: tls.h:1585
@ TLS_TYPE_ALERT
Definition: tls.h:1086
#define TLS_VERSION_1_3
Definition: tls.h:98
Handshake message processing (TLS client and server)
@ TLS_CERT_RSA_PSS_SIGN
Definition: tls.h:1264
@ ERROR_INVALID_LENGTH
Definition: error.h:111
error_t tlsFormatCertAuthoritiesExtension(TlsContext *context, uint8_t *p, size_t *written)
Format CertificateAuthorities extension.
Definition: tls_common.c:839
error_t tlsFormatAlert(TlsContext *context, uint8_t level, uint8_t description, TlsAlert *message, size_t *length)
Format Alert message.
Definition: tls_common.c:815
TLS record protocol.
@ TLS_STATE_CLIENT_CERTIFICATE_VERIFY
Definition: tls.h:1576
@ TLS_TYPE_CERTIFICATE_VERIFY
Definition: tls.h:1115
@ TLS_STATE_SERVER_CHANGE_CIPHER_SPEC
Definition: tls.h:1583
@ TLS_TRANSPORT_PROTOCOL_EAP
Definition: tls.h:1019
@ TLS_ALERT_USER_CANCELED
Definition: tls.h:1169
@ TLS_CERT_ED448_SIGN
Definition: tls.h:1267
#define TLS_MAX_WARNING_ALERTS
Definition: tls.h:851
error_t tlsFormatRawPublicKey(TlsContext *context, uint8_t *p, size_t *written)
Format raw public key.
error_t tls13GenerateSignature(TlsContext *context, uint8_t *p, size_t *length)
Digital signature generation (TLS 1.3)
@ TLS_EXT_CERTIFICATE_AUTHORITIES
Definition: tls.h:1407
error_t dtlsWriteProtocolData(TlsContext *context, const uint8_t *data, size_t length, TlsContentType contentType)
Write protocol data.
Definition: dtls_record.c:62
@ TLS_CERT_RSA_SIGN
Definition: tls.h:1252
#define TRACE_INFO(...)
Definition: debug.h:105
uint8_t length
Definition: tcp.h:375
@ TLS_STATE_CLIENT_APP_TRAFFIC_KEYS
Definition: tls.h:1580
@ ERROR_INVALID_PROTOCOL
Definition: error.h:101
@ TLS_STATE_NEW_SESSION_TICKET
Definition: tls.h:1581
@ TLS_CERT_SM2_SIGN
Definition: tls.h:1265
@ TLS_STATE_CLIENT_CHANGE_CIPHER_SPEC
Definition: tls.h:1577
TlsCertList
Definition: tls.h:1671
RSA/DSA/ECDSA/EdDSA signature verification.
error_t tlsFormatCertificateList(TlsContext *context, uint8_t *p, size_t *written)
Format certificate chain.
error_t tlsParseCertificate(TlsContext *context, const TlsCertificate *message, size_t length)
Parse Certificate message.
Definition: tls_common.c:1039
Transcript hash calculation.
RSA/DSA/ECDSA/SM2/EdDSA signature generation (TLS 1.3)
@ TLS_STATE_HANDSHAKE_TRAFFIC_KEYS
Definition: tls.h:1567
#define TRACE_DEBUG(...)
Definition: debug.h:119
@ ERROR_TIMEOUT
Definition: error.h:95
char char_t
Definition: compiler_port.h:55
#define TLS_VERSION_1_1
Definition: tls.h:96
@ TLS_ENCRYPTION_LEVEL_APPLICATION
Definition: tls.h:1608
@ TLS_STATE_CLIENT_HELLO_2
Definition: tls.h:1560
@ TLS_STATE_CLOSING
Definition: tls.h:1594
@ TLS_STATE_SERVER_CERTIFICATE_VERIFY
Definition: tls.h:1571
#define TRACE_DEBUG_ARRAY(p, a, n)
Definition: debug.h:120
error_t tlsParseRawPublicKey(TlsContext *context, const uint8_t *p, size_t length)
Parse raw public key.
error_t tlsFormatChangeCipherSpec(TlsContext *context, TlsChangeCipherSpec *message, size_t *length)
Format ChangeCipherSpec message.
Definition: tls_common.c:759
@ TLS_STATE_SERVER_CERTIFICATE
Definition: tls.h:1569
@ TLS_CLIENT_AUTH_REQUIRED
Definition: tls.h:1042
@ TLS_ALERT_LEVEL_FATAL
Definition: tls.h:1135
#define HTONS(value)
Definition: cpu_endian.h:410
uint8_t n
@ ERROR_UNEXPECTED_STATE
Definition: error.h:99
@ TLS_STATE_CLIENT_KEY_EXCHANGE
Definition: tls.h:1575
error_t tlsGenerateSignature(TlsContext *context, uint8_t *p, size_t *length)
Digital signature generation (TLS 1.0 or TLS 1.1)
error_t tlsParseFinished(TlsContext *context, const TlsFinished *message, size_t length)
Parse Finished message.
Definition: tls_common.c:1464
@ TLS_TYPE_FINISHED
Definition: tls.h:1117
@ TLS_STATE_CLIENT_CERTIFICATE
Definition: tls.h:1574
@ TLS_STATE_CLIENT_CHANGE_CIPHER_SPEC_2
Definition: tls.h:1578
@ TLS_STATE_ENCRYPTED_EXTENSIONS
Definition: tls.h:1568
Handshake message processing (TLS server)
error_t tlsWriteProtocolData(TlsContext *context, const uint8_t *data, size_t length, TlsContentType contentType)
Write protocol data.
Definition: tls_record.c:54
#define LOAD24BE(p)
Definition: cpu_endian.h:197
@ TLS_CONNECTION_END_CLIENT
Definition: tls.h:1029
X.509 certificate handling.
error_t tlsSendFinished(TlsContext *context)
Send Finished message.
Definition: tls_common.c:387
TLS (Transport Layer Security)
error_t tlsParseCertificateVerify(TlsContext *context, const TlsCertificateVerify *message, size_t length)
Parse CertificateVerify message.
Definition: tls_common.c:1248
#define STORE24BE(a, p)
Definition: cpu_endian.h:273
@ TLS_CERT_ECDSA_SIGN
Definition: tls.h:1259
@ TLS_TRANSPORT_PROTOCOL_STREAM
Definition: tls.h:1016
const uint8_t * value
Definition: x509_common.h:704
@ TLS_CERT_NONE
Definition: tls.h:1251
Tls13CertRequestContext
Definition: tls13_misc.h:286
@ TLS_STATE_SERVER_CHANGE_CIPHER_SPEC_2
Definition: tls.h:1584
void tlsChangeState(TlsContext *context, TlsState newState)
Update TLS state.
Definition: tls_misc.c:54
error_t tlsVerifySignature(TlsContext *context, const uint8_t *p, size_t length)
Digital signature verification (TLS 1.0 and TLS 1.1)
@ ERROR_DECODING_FAILED
Definition: error.h:242
#define PRIuSIZE
#define osMemset(p, value, length)
Definition: os_port.h:138
Handshake message processing (TLS client)
#define tlsFreeMem(p)
Definition: tls.h:894
@ TLS_STATE_SERVER_HELLO_2
Definition: tls.h:1565
@ TLS_STATE_CLIENT_FINISHED
Definition: tls.h:1579
error_t tlsSendQuicAlertMessage(TlsContext *context, const TlsAlert *message, size_t length)
Send alert message.
@ ERROR_CERTIFICATE_REQUIRED
Definition: error.h:136
@ ERROR_INVALID_SIGNATURE
Definition: error.h:228
error_t tlsFormatCertificate(TlsContext *context, TlsCertificate *message, size_t *length)
Format Certificate message.
Definition: tls_common.c:611
RSA/DSA/ECDSA/EdDSA signature generation.
X509OctetString raw
Definition: x509_common.h:726
@ NO_ERROR
Success.
Definition: error.h:44
Debugging facilities.
error_t tlsSendCertificateVerify(TlsContext *context)
Send CertificateVerify message.
Definition: tls_common.c:192
void TlsCertificate
Certificate message.
Definition: tls.h:1937
uint8_t description
Definition: tls.h:2015
@ TLS_STATE_CLOSED
Definition: tls.h:1595