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