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