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