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  * Copyright (C) 2010-2018 Oryx Embedded SARL. All rights reserved.
8  *
9  * This file is part of CycloneSSL Open.
10  *
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public License
13  * as published by the Free Software Foundation; either version 2
14  * of the License, or (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software Foundation,
23  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
24  *
25  * @author Oryx Embedded SARL (www.oryx-embedded.com)
26  * @version 1.9.0
27  **/
28 
29 //Switch to the appropriate trace level
30 #define TRACE_LEVEL TLS_TRACE_LEVEL
31 
32 //Dependencies
33 #include <string.h>
34 #include "tls.h"
35 #include "tls_cipher_suites.h"
36 #include "tls_handshake.h"
37 #include "tls_client.h"
38 #include "tls_server.h"
39 #include "tls_common.h"
40 #include "tls_certificate.h"
41 #include "tls_signature.h"
42 #include "tls_transcript_hash.h"
43 #include "tls_cache.h"
44 #include "tls_record.h"
45 #include "tls_misc.h"
46 #include "dtls_record.h"
48 #include "debug.h"
49 
50 //Check TLS library configuration
51 #if (TLS_SUPPORT == ENABLED)
52 
53 
54 /**
55  * @brief Send Certificate message
56  * @param[in] context Pointer to the TLS context
57  * @return Error code
58  **/
59 
61 {
62  error_t error;
63  size_t length;
65 
66  //Initialize status code
67  error = NO_ERROR;
68 
69  //Point to the buffer where to format the message
70  message = (TlsCertificate *) (context->txBuffer + context->txBufferLen);
71 
72 #if (TLS_CLIENT_SUPPORT == ENABLED)
73  //TLS operates as a client?
74  if(context->entity == TLS_CONNECTION_END_CLIENT)
75  {
76  //The client must send a Certificate message if the server requests it
77  if(context->clientCertRequested)
78  {
79 #if (TLS_MAX_VERSION >= SSL_VERSION_3_0 && TLS_MIN_VERSION <= SSL_VERSION_3_0)
80  //No suitable certificate available?
81  if(context->cert == NULL && context->version == SSL_VERSION_3_0)
82  {
83  //The client should send a no_certificate alert instead
84  error = tlsSendAlert(context, TLS_ALERT_LEVEL_WARNING,
86  }
87  else
88 #endif
89  {
90  //Format Certificate message
91  error = tlsFormatCertificate(context, message, &length);
92 
93  //Check status code
94  if(!error)
95  {
96  //Debug message
97  TRACE_INFO("Sending Certificate message (%" PRIuSIZE " bytes)...\r\n", length);
99 
100  //Send handshake message
101  error = tlsSendHandshakeMessage(context, message, length,
103  }
104  }
105  }
106  }
107  else
108 #endif
109 #if (TLS_SERVER_SUPPORT == ENABLED)
110  //TLS operates as a server?
111  if(context->entity == TLS_CONNECTION_END_SERVER)
112  {
113  //The server must send a Certificate message whenever the agreed-upon
114  //key exchange method uses certificates for authentication
115  if(context->cert != NULL)
116  {
117  //Format Certificate message
118  error = tlsFormatCertificate(context, message, &length);
119 
120  //Check status code
121  if(!error)
122  {
123  //Debug message
124  TRACE_INFO("Sending Certificate message (%" PRIuSIZE " bytes)...\r\n", length);
126 
127  //Send handshake message
128  error = tlsSendHandshakeMessage(context, message, length,
130  }
131  }
132  }
133  else
134 #endif
135  //Unsupported mode of operation?
136  {
137  //Report an error
138  error = ERROR_FAILURE;
139  }
140 
141  //Check status code
142  if(error == NO_ERROR || error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
143  {
144  //Version of TLS prior to TLS 1.3?
145  if(context->version <= TLS_VERSION_1_2)
146  {
147  //Check whether TLS operates as a client or a server
148  if(context->entity == TLS_CONNECTION_END_CLIENT)
149  context->state = TLS_STATE_CLIENT_KEY_EXCHANGE;
150  else
151  context->state = TLS_STATE_SERVER_KEY_EXCHANGE;
152  }
153  else
154  {
155  //Check whether TLS operates as a client or a server
156  if(context->entity == TLS_CONNECTION_END_CLIENT)
157  {
158  //Clients must send a CertificateVerify message whenever
159  //authenticating via a certificate
160  if(context->clientCertRequested)
161  context->state = TLS_STATE_CLIENT_CERTIFICATE_VERIFY;
162  else
163  context->state = TLS_STATE_CLIENT_FINISHED;
164  }
165  else
166  {
167  //Servers must send a CertificateVerify message whenever
168  //authenticating via a certificate
169  context->state = TLS_STATE_SERVER_CERTIFICATE_VERIFY;
170  }
171  }
172  }
173 
174  //Return status code
175  return error;
176 }
177 
178 
179 /**
180  * @brief Send CertificateVerify message
181  *
182  * The CertificateVerify message is used to provide explicit verification
183  * of a client certificate. This message is only sent following a client
184  * certificate that has signing capability
185  *
186  * @param[in] context Pointer to the TLS context
187  * @return Error code
188  **/
189 
191 {
192  error_t error;
193  size_t length;
195 
196  //Initialize status code
197  error = NO_ERROR;
198 
199  //The CertificateVerify message is only sent following a client certificate
200  //that has signing capability
201  if(context->cert != NULL)
202  {
203  //Check certificate type
204  if(context->cert->type == TLS_CERT_RSA_SIGN ||
205  context->cert->type == TLS_CERT_RSA_PSS_SIGN ||
206  context->cert->type == TLS_CERT_DSS_SIGN ||
207  context->cert->type == TLS_CERT_ECDSA_SIGN ||
208  context->cert->type == TLS_CERT_ED25519_SIGN ||
209  context->cert->type == TLS_CERT_ED448_SIGN)
210  {
211  //Point to the buffer where to format the message
212  message = (TlsCertificateVerify *) (context->txBuffer + context->txBufferLen);
213 
214  //Format CertificateVerify message
215  error = tlsFormatCertificateVerify(context, message, &length);
216 
217  //Check status code
218  if(!error)
219  {
220  //Debug message
221  TRACE_INFO("Sending CertificateVerify message (%" PRIuSIZE " bytes)...\r\n", length);
223 
224  //Send handshake message
225  error = tlsSendHandshakeMessage(context, message, length,
227  }
228  }
229  }
230 
231  //Check status code
232  if(error == NO_ERROR || error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
233  {
234  //Version of TLS prior to TLS 1.3?
235  if(context->version <= TLS_VERSION_1_2)
236  {
237  //Send a ChangeCipherSpec message to the server
238  context->state = TLS_STATE_CLIENT_CHANGE_CIPHER_SPEC;
239  }
240  else
241  {
242  //Send a Finished message to the peer
243  if(context->entity == TLS_CONNECTION_END_CLIENT)
244  context->state = TLS_STATE_CLIENT_FINISHED;
245  else
246  context->state = TLS_STATE_SERVER_FINISHED;
247  }
248  }
249 
250  //Return status code
251  return error;
252 }
253 
254 
255 /**
256  * @brief Send ChangeCipherSpec message
257  *
258  * The change cipher spec message is sent by both the client and the
259  * server to notify the receiving party that subsequent records will be
260  * protected under the newly negotiated CipherSpec and keys
261  *
262  * @param[in] context Pointer to the TLS context
263  * @return Error code
264  **/
265 
267 {
268  error_t error;
269  size_t length;
271 
272  //Point to the buffer where to format the message
273  message = (TlsChangeCipherSpec *) (context->txBuffer + context->txBufferLen);
274 
275  //Format ChangeCipherSpec message
276  error = tlsFormatChangeCipherSpec(context, message, &length);
277 
278  //Check status code
279  if(!error)
280  {
281  //Debug message
282  TRACE_INFO("Sending ChangeCipherSpec message (%" PRIuSIZE " bytes)...\r\n", length);
284 
285 #if (DTLS_SUPPORT == ENABLED)
286  //DTLS protocol?
287  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
288  {
289  //Send ChangeCipherSpec message
290  error = dtlsWriteProtocolData(context, (uint8_t *) message,
292  }
293  else
294 #endif
295  //TLS protocol?
296  {
297  //Send ChangeCipherSpec message
298  error = tlsWriteProtocolData(context, (uint8_t *) message,
300  }
301  }
302 
303  //Check status code
304  if(error == NO_ERROR || error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
305  {
306  //Version of TLS prior to TLS 1.3?
307  if(context->version <= TLS_VERSION_1_2)
308  {
309 #if (DTLS_SUPPORT == ENABLED)
310  //Release previous encryption engine first
311  tlsFreeEncryptionEngine(&context->prevEncryptionEngine);
312 
313  //Save current encryption engine for later use
314  context->prevEncryptionEngine = context->encryptionEngine;
315  //Clear current encryption engine
316  memset(&context->encryptionEngine, 0, sizeof(TlsEncryptionEngine));
317 #else
318  //Release encryption engine first
319  tlsFreeEncryptionEngine(&context->encryptionEngine);
320 #endif
321 
322  //Inform the record layer that subsequent records will be protected
323  //under the newly negotiated encryption algorithm
324  error = tlsInitEncryptionEngine(context, &context->encryptionEngine,
325  context->entity, NULL);
326 
327  //Check status code
328  if(!error)
329  {
330  //Send a Finished message to the peer
331  if(context->entity == TLS_CONNECTION_END_CLIENT)
332  context->state = TLS_STATE_CLIENT_FINISHED;
333  else
334  context->state = TLS_STATE_SERVER_FINISHED;
335  }
336  }
337  else
338  {
339 #if (TLS13_MIDDLEBOX_COMPAT_SUPPORT == ENABLED)
340  //The middlebox compatibility mode improves the chance of successfully
341  //connecting through middleboxes
342  if(context->state == TLS_STATE_CLIENT_CHANGE_CIPHER_SPEC ||
343  context->state == TLS_STATE_SERVER_CHANGE_CIPHER_SPEC_2)
344  {
345  //The client can send its second flight
346  context->state = TLS_STATE_CLIENT_HELLO_2;
347  }
348  else if(context->state == TLS_STATE_SERVER_CHANGE_CIPHER_SPEC ||
349  context->state == TLS_STATE_CLIENT_CHANGE_CIPHER_SPEC_2)
350  {
351  //All handshake messages after the ServerHello are now encrypted
352  context->state = TLS_STATE_HANDSHAKE_TRAFFIC_KEYS;
353  }
354  else
355 #endif
356  {
357  //Middlebox compatibility mode is not implemented
358  error = ERROR_UNEXPECTED_STATE;
359  }
360  }
361  }
362 
363  //Return status code
364  return error;
365 }
366 
367 
368 /**
369  * @brief Send Finished message
370  *
371  * A Finished message is always sent immediately after a change
372  * cipher spec message to verify that the key exchange and
373  * authentication processes were successful. It is essential that a
374  * change cipher spec message be received between the other handshake
375  * messages and the Finished message
376  *
377  * @param[in] context Pointer to the TLS context
378  * @return Error code
379  **/
380 
382 {
383  error_t error;
384  size_t length;
386 
387  //Point to the buffer where to format the message
388  message = (TlsFinished *) (context->txBuffer + context->txBufferLen);
389 
390  //Check whether TLS operates as a client or a server
391  if(context->entity == TLS_CONNECTION_END_CLIENT)
392  {
393  //The verify data is generated from all messages in this handshake
394  //up to but not including the Finished message
396  context->clientVerifyData, &context->clientVerifyDataLen);
397  }
398  else
399  {
400  //The verify data is generated from all messages in this handshake
401  //up to but not including the Finished message
403  context->serverVerifyData, &context->serverVerifyDataLen);
404  }
405 
406  //Check status code
407  if(!error)
408  {
409  //Format Finished message
410  error = tlsFormatFinished(context, message, &length);
411  }
412 
413  //Check status code
414  if(!error)
415  {
416  //Debug message
417  TRACE_INFO("Sending Finished message (%" PRIuSIZE " bytes)...\r\n", length);
419 
420  //Send handshake message
421  error = tlsSendHandshakeMessage(context, message, length,
423  }
424 
425  //Check status code
426  if(error == NO_ERROR || error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
427  {
428  //Version of TLS prior to TLS 1.3?
429  if(context->version <= TLS_VERSION_1_2)
430  {
431  //Check whether TLS operates as a client or a server
432  if(context->entity == TLS_CONNECTION_END_CLIENT)
433  {
434  //Abbreviated or full handshake?
435  if(context->resume)
436  context->state = TLS_STATE_APPLICATION_DATA;
437  else
438  context->state = TLS_STATE_SERVER_CHANGE_CIPHER_SPEC;
439  }
440  else
441  {
442  //Abbreviated or full handshake?
443  if(context->resume)
444  context->state = TLS_STATE_CLIENT_CHANGE_CIPHER_SPEC;
445  else
446  context->state = TLS_STATE_APPLICATION_DATA;
447  }
448  }
449  else
450  {
451  //Check whether TLS operates as a client or a server
452  if(context->entity == TLS_CONNECTION_END_CLIENT)
453  {
454  //Compute client application traffic keys
455  context->state = TLS_STATE_CLIENT_APP_TRAFFIC_KEYS;
456  }
457  else
458  {
459  //Compute server application traffic keys
460  context->state = TLS_STATE_SERVER_APP_TRAFFIC_KEYS;
461  }
462  }
463  }
464 
465  //Return status code
466  return error;
467 }
468 
469 
470 /**
471  * @brief Send Alert message
472  * @param[in] context Pointer to the TLS context
473  * @param[in] level Severity of the message (warning or fatal)
474  * @param[in] description Description of the alert
475  * @return Error code
476  **/
477 
478 error_t tlsSendAlert(TlsContext *context, uint8_t level, uint8_t description)
479 {
480  error_t error;
481  size_t length;
482  TlsAlert *message;
483 
484  //Point to the buffer where to format the message
485  message = (TlsAlert *) (context->txBuffer + context->txBufferLen);
486 
487  //Format Alert message
488  error = tlsFormatAlert(context, level, description, message, &length);
489 
490  //Check status code
491  if(!error)
492  {
493  //Debug message
494  TRACE_INFO("Sending Alert message (%" PRIuSIZE " bytes)...\r\n", length);
496 
497 #if (DTLS_SUPPORT == ENABLED)
498  //DTLS protocol?
499  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
500  {
501  //Send Alert message
502  error = dtlsWriteProtocolData(context, (uint8_t *) message,
504  }
505  else
506 #endif
507  //TLS protocol?
508  {
509  //Send Alert message
510  error = tlsWriteProtocolData(context, (uint8_t *) message,
512  }
513  }
514 
515  //Alert messages convey the severity of the message
517  {
518  //If an alert with a level of warning is sent, generally the
519  //connection can continue normally
521  {
522  //Either party may initiate a close by sending a close_notify alert
523  context->closeNotifySent = TRUE;
524 
525  //Update FSM state
526  context->state = TLS_STATE_CLOSING;
527  }
528  }
529  else if(level == TLS_ALERT_LEVEL_FATAL)
530  {
531  //Alert messages with a level of fatal result in the immediate
532  //termination of the connection
533  context->fatalAlertSent = TRUE;
534 
535 #if (TLS_MAX_VERSION >= SSL_VERSION_3_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
536  //Any connection terminated with a fatal alert must not be resumed
537  if(context->entity == TLS_CONNECTION_END_SERVER)
538  {
539  tlsRemoveFromCache(context);
540  }
541 #endif
542 
543  //Servers and clients must forget any session identifiers
544  memset(context->sessionId, 0, 32);
545  context->sessionIdLen = 0;
546 
547  //Update FSM state
548  context->state = TLS_STATE_CLOSING;
549  }
550 
551  //Return status code
552  return error;
553 }
554 
555 
556 /**
557  * @brief Format Certificate message
558  * @param[in] context Pointer to the TLS context
559  * @param[out] message Buffer where to format the Certificate message
560  * @param[out] length Length of the resulting Certificate message
561  * @return Error code
562  **/
563 
565  TlsCertificate *message, size_t *length)
566 {
567  error_t error;
568  size_t n;
569  uint8_t *p;
570  TlsCertificateList *certificateList;
571 
572  //Point to the beginning of the handshake message
573  p = message;
574  //Length of the handshake message
575  *length = 0;
576 
577 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
578  //TLS 1.3 currently selected?
579  if(context->version == TLS_VERSION_1_3)
580  {
581  Tls13CertRequestContext *certRequestContext;
582 
583  //Point to the certificate request context
584  certRequestContext = (Tls13CertRequestContext *) p;
585 
586  //Check whether TLS operates as a client or a server
587  if(context->entity == TLS_CONNECTION_END_CLIENT)
588  {
589  //The value of the certificate_request_context field from server's
590  //CertificateRequest message is echoed in the Certificate message
591  if(context->certRequestContextLen > 0)
592  {
593  //Copy certificate request context
594  memcpy(certRequestContext->value, context->certRequestContext,
595  context->certRequestContextLen);
596  }
597 
598  //The context is preceded by a length field
599  certRequestContext->length = (uint8_t) context->certRequestContextLen;
600  }
601  else
602  {
603  //In the case of server authentication, this field shall be zero length
604  certRequestContext->length = 0;
605  }
606 
607  //Point to the next field
608  p += sizeof(Tls13CertRequestContext) + certRequestContext->length;
609  //Adjust the length of the Certificate message
610  *length += sizeof(Tls13CertRequestContext) + certRequestContext->length;
611  }
612 #endif
613 
614  //Point to the chain of certificates
615  certificateList = (TlsCertificateList *) p;
616 
617 #if (TLS_RAW_PUBLIC_KEY_SUPPORT == ENABLED)
618  //Check certificate type
619  if(context->certFormat == TLS_CERT_FORMAT_RAW_PUBLIC_KEY)
620  {
621  //Format the raw public key
622  error = tlsFormatRawPublicKey(context, certificateList->value, &n);
623  }
624  else
625 #endif
626  {
627  //Format the certificate chain
628  error = tlsFormatCertificateList(context, certificateList->value, &n);
629  }
630 
631  //Check status code
632  if(!error)
633  {
634  //A 3-byte length field shall precede the certificate list
635  STORE24BE(n, certificateList->length);
636  //Adjust the length of the Certificate message
637  *length += sizeof(TlsCertificateList) + n;
638  }
639 
640  //Return status code
641  return error;
642 }
643 
644 
645 /**
646  * @brief Format CertificateVerify message
647  * @param[in] context Pointer to the TLS context
648  * @param[out] message Buffer where to format the CertificateVerify message
649  * @param[out] length Length of the resulting CertificateVerify message
650  * @return Error code
651  **/
652 
655 {
656  error_t error;
657 
658  //Length of the handshake message
659  *length = 0;
660 
661 #if (TLS_MAX_VERSION >= SSL_VERSION_3_0 && TLS_MIN_VERSION <= TLS_VERSION_1_1)
662  //SSL 3.0, TLS 1.0 or TLS 1.1 currently selected?
663  if(context->version <= TLS_VERSION_1_1)
664  {
665  //In TLS version prior to 1.2, the digitally-signed element combines
666  //MD5 and SHA-1
667  error = tlsGenerateSignature(context, message, length);
668  }
669  else
670 #endif
671 #if (TLS_MAX_VERSION >= TLS_VERSION_1_2 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
672  //TLS 1.2 currently selected?
673  if(context->version == TLS_VERSION_1_2)
674  {
675  //In TLS 1.2, the MD5/SHA-1 combination in the digitally-signed element
676  //has been replaced with a single hash. The signed element now includes
677  //a field that explicitly specifies the hash algorithm used
678  error = tls12GenerateSignature(context, message, length);
679  }
680  else
681 #endif
682 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
683  //TLS 1.3 currently selected?
684  if(context->version == TLS_VERSION_1_3)
685  {
686  //In TLS 1.3, the signed element specifies the signature algorithm used.
687  //The content that is covered under the signature is the transcript hash
688  //output
689  error = tls13GenerateSignature(context, message, length);
690  }
691  else
692 #endif
693  //Invalid TLS version?
694  {
695  //Report an error
696  error = ERROR_INVALID_VERSION;
697  }
698 
699  //Return status code
700  return error;
701 }
702 
703 
704 /**
705  * @brief Format ChangeCipherSpec message
706  * @param[in] context Pointer to the TLS context
707  * @param[out] message Buffer where to format the ChangeCipherSpec message
708  * @param[out] length Length of the resulting ChangeCipherSpec message
709  * @return Error code
710  **/
711 
714 {
715  //The message consists of a single byte of value 1
716  message->type = 1;
717 
718  //Length of the ChangeCipherSpec message
719  *length = sizeof(TlsChangeCipherSpec);
720 
721  //Successful processing
722  return NO_ERROR;
723 }
724 
725 
726 /**
727  * @brief Format Finished message
728  * @param[in] context Pointer to the TLS context
729  * @param[out] message Buffer where to format the Finished message
730  * @param[out] length Length of the resulting Finished message
731  * @return Error code
732  **/
733 
735  TlsFinished *message, size_t *length)
736 {
737  //Check whether TLS operates as a client or a server
738  if(context->entity == TLS_CONNECTION_END_CLIENT)
739  {
740  //Copy the client's verify data
741  memcpy(message, context->clientVerifyData, context->clientVerifyDataLen);
742  //Length of the handshake message
743  *length = context->clientVerifyDataLen;
744  }
745  else
746  {
747  //Copy the server's verify data
748  memcpy(message, context->serverVerifyData, context->serverVerifyDataLen);
749  //Length of the handshake message
750  *length = context->serverVerifyDataLen;
751  }
752 
753  //Successful processing
754  return NO_ERROR;
755 }
756 
757 
758 /**
759  * @brief Format Alert message
760  * @param[in] context Pointer to the TLS context
761  * @param[in] level Severity of the message (warning or fatal)
762  * @param[in] description Description of the alert
763  * @param[out] message Buffer where to format the Alert message
764  * @param[out] length Length of the resulting Alert message
765  * @return Error code
766  **/
767 
769  uint8_t description, TlsAlert *message, size_t *length)
770 {
771  //Severity of the message
772  message->level = level;
773  //Description of the alert
774  message->description = description;
775 
776  //Length of the Alert message
777  *length = sizeof(TlsAlert);
778 
779  //Successful processing
780  return NO_ERROR;
781 }
782 
783 
784 /**
785  * @brief Format SignatureAlgorithms extension
786  * @param[in] context Pointer to the TLS context
787  * @param[in] cipherSuiteTypes Types of cipher suites proposed by the client
788  * @param[in] p Output stream where to write the SignatureAlgorithms extension
789  * @param[out] written Total number of bytes that have been written
790  * @return Error code
791  **/
792 
794  uint_t cipherSuiteTypes, uint8_t *p, size_t *written)
795 {
796  size_t n = 0;
797 
798 #if (TLS_MAX_VERSION >= TLS_VERSION_1_2 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
799  //This extension is not meaningful for TLS versions prior to 1.2. Clients
800  //must not offer it if they are offering prior versions (refer to RFC 5246,
801  //section 7.4.1.4.1)
802  if(context->versionMax >= TLS_VERSION_1_2)
803  {
804  TlsExtension *extension;
805  TlsSignHashAlgos *supportedSignAlgos;
806 
807  //Add the SignatureAlgorithms extension
808  extension = (TlsExtension *) p;
809  //Type of the extension
810  extension->type = HTONS(TLS_EXT_SIGNATURE_ALGORITHMS);
811 
812  //Point to the list of the hash/signature algorithm pairs that the
813  //server is able to verify
814  supportedSignAlgos = (TlsSignHashAlgos *) extension->value;
815 
816  //Enumerate the hash/signature algorithm pairs in descending order
817  //of preference
818  n = 0;
819 
821 #if (TLS_ED25519_SUPPORT == ENABLED)
822  //Ed25519 signature algorithm (PureEdDSA mode)
823  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_ED25519;
824  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_INTRINSIC;
825 #endif
826 #if (TLS_ED448_SUPPORT == ENABLED)
827  //Ed448 signature algorithm (PureEdDSA mode)
828  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_ED448;
829  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_INTRINSIC;
830 #endif
831 #endif
832 
833 #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED)
834  //Any ECC cipher suite proposed by the client?
835  if((cipherSuiteTypes & TLS_CIPHER_SUITE_TYPE_ECC) != 0 ||
836  (cipherSuiteTypes & TLS_CIPHER_SUITE_TYPE_TLS13) != 0)
837  {
838 #if (TLS_SHA256_SUPPORT == ENABLED)
839  //ECDSA signature algorithm with SHA-256
840  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_ECDSA;
841  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA256;
842 #endif
843 #if (TLS_SHA384_SUPPORT == ENABLED)
844  //ECDSA signature algorithm with SHA-384
845  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_ECDSA;
846  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA384;
847 #endif
848 #if (TLS_SHA512_SUPPORT == ENABLED)
849  //ECDSA signature algorithm with SHA-512
850  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_ECDSA;
851  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA512;
852 #endif
853  }
854 #endif
855 
856 #if (TLS_RSA_PSS_SIGN_SUPPORT == ENABLED)
857  //Check whether the X.509 parser supports RSA-PSS signatures
859  {
860 #if (TLS_SHA256_SUPPORT == ENABLED)
861  //RSASSA-PSS PSS signature algorithm with SHA-256
862  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA_PSS_PSS_SHA256;
863  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_INTRINSIC;
864 #endif
865 #if (TLS_SHA384_SUPPORT == ENABLED)
866  //RSASSA-PSS PSS signature algorithm with SHA-384
867  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA_PSS_PSS_SHA384;
868  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_INTRINSIC;
869 #endif
870 #if (TLS_SHA512_SUPPORT == ENABLED)
871  //RSASSA-PSS PSS signature algorithm with SHA-512
872  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA_PSS_PSS_SHA512;
873  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_INTRINSIC;
874 #endif
875  }
876 #endif
877 
878 #if (TLS_RSA_PSS_SIGN_SUPPORT == ENABLED)
879 #if (TLS_SHA256_SUPPORT == ENABLED)
880  //RSASSA-PSS RSAE signature algorithm with SHA-256
881  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA_PSS_RSAE_SHA256;
882  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_INTRINSIC;
883 #endif
884 #if (TLS_SHA384_SUPPORT == ENABLED)
885  //RSASSA-PSS RSAE signature algorithm with SHA-384
886  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA_PSS_RSAE_SHA384;
887  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_INTRINSIC;
888 #endif
889 #if (TLS_SHA512_SUPPORT == ENABLED)
890  //RSASSA-PSS RSAE signature algorithm with SHA-512
891  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA_PSS_RSAE_SHA512;
892  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_INTRINSIC;
893 #endif
894 #endif
895 
896 #if (TLS_RSA_SIGN_SUPPORT == ENABLED)
897 #if (TLS_SHA256_SUPPORT == ENABLED)
898  //RSASSA-PKCS1-v1_5 signature algorithm with SHA-256
899  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA;
900  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA256;
901 #endif
902 #if (TLS_SHA384_SUPPORT == ENABLED)
903  //RSASSA-PKCS1-v1_5 signature algorithm with SHA-384
904  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA;
905  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA384;
906 #endif
907 #if (TLS_SHA512_SUPPORT == ENABLED)
908  //RSASSA-PKCS1-v1_5 signature algorithm with SHA-512
909  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA;
910  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA512;
911 #endif
912 #endif
913 
914 #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED)
915  //Any ECC cipher suite proposed by the client?
916  if((cipherSuiteTypes & TLS_CIPHER_SUITE_TYPE_ECC) != 0 ||
917  (cipherSuiteTypes & TLS_CIPHER_SUITE_TYPE_TLS13) != 0)
918  {
919 #if (TLS_SHA1_SUPPORT == ENABLED)
920  //ECDSA signature algorithm with SHA-1
921  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_ECDSA;
922  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA1;
923 #endif
924 #if (TLS_SHA224_SUPPORT == ENABLED)
925  //ECDSA signature algorithm with SHA-224
926  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_ECDSA;
927  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA224;
928 #endif
929  }
930 #endif
931 
932 #if (TLS_RSA_SIGN_SUPPORT == ENABLED)
933 #if (TLS_SHA1_SUPPORT == ENABLED)
934  //RSASSA-PKCS1-v1_5 signature algorithm with SHA-1
935  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA;
936  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA1;
937 #endif
938 #if (TLS_SHA224_SUPPORT == ENABLED)
939  //RSASSA-PKCS1-v1_5 signature algorithm with SHA-224
940  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA;
941  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA224;
942 #endif
943 #if (TLS_MD5_SUPPORT == ENABLED)
944  //RSASSA-PKCS1-v1_5 signature algorithm with MD5
945  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA;
946  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_MD5;
947 #endif
948 #endif
949 
950 #if (TLS_DSA_SIGN_SUPPORT == ENABLED)
951 #if (TLS_SHA1_SUPPORT == ENABLED)
952  //DSA signature algorithm with SHA-1
953  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_DSA;
954  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA1;
955 #endif
956 #if (TLS_SHA224_SUPPORT == ENABLED)
957  //DSA signature algorithm with SHA-224
958  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_DSA;
959  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA224;
960 #endif
961 #if (TLS_SHA256_SUPPORT == ENABLED)
962  //DSA signature algorithm with SHA-256
963  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_DSA;
964  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA256;
965 #endif
966 #endif
967 
968  //Compute the length, in bytes, of the list
969  n *= sizeof(TlsSignHashAlgo);
970  //Fix the length of the list
971  supportedSignAlgos->length = htons(n);
972 
973  //Consider the 2-byte length field that precedes the list
974  n += sizeof(TlsSignHashAlgos);
975  //Fix the length of the extension
976  extension->length = htons(n);
977 
978  //Compute the length, in bytes, of the SignatureAlgorithms extension
979  n += sizeof(TlsExtension);
980  }
981 #endif
982 
983  //Total number of bytes that have been written
984  *written = n;
985 
986  //Successful processing
987  return NO_ERROR;
988 }
989 
990 
991 /**
992  * @brief Format SignatureAlgorithmsCert extension
993  * @param[in] context Pointer to the TLS context
994  * @param[in] p Output stream where to write the SignatureAlgorithmsCert extension
995  * @param[out] written Total number of bytes that have been written
996  * @return Error code
997  **/
998 
1000  uint8_t *p, size_t *written)
1001 {
1002  size_t n = 0;
1003 
1004 #if (TLS_MAX_VERSION >= TLS_VERSION_1_2 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
1005  //TLS 1.2 implementations should also process this extension
1006  if(context->versionMax >= TLS_VERSION_1_2)
1007  {
1008  TlsExtension *extension;
1009  TlsSignHashAlgos *supportedSignAlgos;
1010 
1011  //Add the SignatureAlgorithmsCert extension
1012  extension = (TlsExtension *) p;
1013  //Type of the extension
1014  extension->type = HTONS(TLS_EXT_SIGNATURE_ALGORITHMS_CERT);
1015 
1016  //The SignatureAlgorithmsCert extension allows a client to indicate
1017  //which signature algorithms it can validate in X.509 certificates
1018  supportedSignAlgos = (TlsSignHashAlgos *) extension->value;
1019 
1020  //Enumerate the hash/signature algorithm pairs in descending order
1021  //of preference
1022  n = 0;
1023 
1024  //Ed25519 signature algorithm (PureEdDSA mode)
1026  {
1027  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_ED25519;
1028  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_INTRINSIC;
1029  }
1030 
1031  //Ed448 signature algorithm (PureEdDSA mode)
1033  {
1034  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_ED448;
1035  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_INTRINSIC;
1036  }
1037 
1038  //ECDSA signature algorithm with SHA-256
1041  {
1042  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_ECDSA;
1043  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA256;
1044  }
1045 
1046  //ECDSA signature algorithm with SHA-384
1049  {
1050  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_ECDSA;
1051  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA384;
1052  }
1053 
1054  //ECDSA signature algorithm with SHA-512
1057  {
1058  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_ECDSA;
1059  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA512;
1060  }
1061 
1062  //RSASSA-PSS PSS signature algorithm with SHA-256
1065  {
1066  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA_PSS_PSS_SHA256;
1067  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_INTRINSIC;
1068  }
1069 
1070  //RSASSA-PSS PSS signature algorithm with SHA-384
1073  {
1074  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA_PSS_PSS_SHA384;
1075  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_INTRINSIC;
1076  }
1077 
1078  //RSASSA-PSS PSS signature algorithm with SHA-512
1081  {
1082  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA_PSS_PSS_SHA512;
1083  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_INTRINSIC;
1084  }
1085 
1086  //RSASSA-PSS RSAE signature algorithm with SHA-256
1089  {
1090  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA_PSS_RSAE_SHA256;
1091  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_INTRINSIC;
1092  }
1093 
1094  //RSASSA-PSS RSAE signature algorithm with SHA-384
1097  {
1098  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA_PSS_RSAE_SHA384;
1099  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_INTRINSIC;
1100  }
1101 
1102  //RSASSA-PSS RSAE signature algorithm with SHA-512
1105  {
1106  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA_PSS_RSAE_SHA512;
1107  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_INTRINSIC;
1108  }
1109 
1110  //RSASSA-PKCS1-v1_5 signature algorithm with SHA-256
1113  {
1114  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA;
1115  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA256;
1116  }
1117 
1118  //RSASSA-PKCS1-v1_5 signature algorithm with SHA-384
1121  {
1122  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA;
1123  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA384;
1124  }
1125 
1126  //RSASSA-PKCS1-v1_5 signature algorithm with SHA-512
1129  {
1130  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA;
1131  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA512;
1132  }
1133 
1134  //ECDSA signature algorithm with SHA-1
1137  {
1138  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_ECDSA;
1139  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA1;
1140  }
1141 
1142  //ECDSA signature algorithm with SHA-224
1145  {
1146  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_ECDSA;
1147  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA224;
1148  }
1149 
1150  //RSASSA-PKCS1-v1_5 signature algorithm with SHA-1
1153  {
1154  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA;
1155  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA1;
1156  }
1157 
1158  //RSASSA-PKCS1-v1_5 signature algorithm with SHA-224
1161  {
1162  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA;
1163  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA224;
1164  }
1165 
1166  //RSASSA-PKCS1-v1_5 signature algorithm with MD5
1169  {
1170  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA;
1171  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_MD5;
1172  }
1173 
1174  //DSA signature algorithm with SHA-1
1177  {
1178  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_DSA;
1179  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA1;
1180  }
1181 
1182  //DSA signature algorithm with SHA-224
1185  {
1186  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_DSA;
1187  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA224;
1188  }
1189 
1190  //DSA signature algorithm with SHA-256
1193  {
1194  supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_DSA;
1195  supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA256;
1196  }
1197 
1198  //Compute the length, in bytes, of the list
1199  n *= sizeof(TlsSignHashAlgo);
1200  //Fix the length of the list
1201  supportedSignAlgos->length = htons(n);
1202 
1203  //Consider the 2-byte length field that precedes the list
1204  n += sizeof(TlsSignHashAlgos);
1205  //Fix the length of the extension
1206  extension->length = htons(n);
1207 
1208  //Compute the length, in bytes, of the SignatureAlgorithmsCert extension
1209  n += sizeof(TlsExtension);
1210  }
1211 #endif
1212 
1213  //Total number of bytes that have been written
1214  *written = n;
1215 
1216  //Successful processing
1217  return NO_ERROR;
1218 }
1219 
1220 
1221 /**
1222  * @brief Parse Certificate message
1223  * @param[in] context Pointer to the TLS context
1224  * @param[in] message Incoming Certificate message to parse
1225  * @param[in] length Message length
1226  * @return Error code
1227  **/
1228 
1230  const TlsCertificate *message, size_t length)
1231 {
1232  error_t error;
1233  size_t n;
1234  const uint8_t *p;
1235  const TlsCertificateList *certificateList;
1236 
1237  //Debug message
1238  TRACE_INFO("Certificate message received (%" PRIuSIZE " bytes)...\r\n", length);
1240 
1241  //Check whether TLS operates as a client or a server
1242  if(context->entity == TLS_CONNECTION_END_CLIENT)
1243  {
1244  //Version of TLS prior to TLS 1.3?
1245  if(context->version <= TLS_VERSION_1_2)
1246  {
1247  //Check current state
1248  if(context->state != TLS_STATE_SERVER_CERTIFICATE)
1249  return ERROR_UNEXPECTED_MESSAGE;
1250  }
1251  else
1252  {
1253  //The CertificateRequest message is optional
1254  if(context->state != TLS_STATE_CERTIFICATE_REQUEST &&
1255  context->state != TLS_STATE_SERVER_CERTIFICATE)
1256  {
1257  return ERROR_UNEXPECTED_MESSAGE;
1258  }
1259  }
1260  }
1261  else
1262  {
1263  //Check current state
1264  if(context->state != TLS_STATE_CLIENT_CERTIFICATE)
1265  return ERROR_UNEXPECTED_MESSAGE;
1266  }
1267 
1268  //Point to the beginning of the handshake message
1269  p = message;
1270 
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  const Tls13CertRequestContext *certRequestContext;
1276 
1277  //Point to the certificate request context
1278  certRequestContext = (Tls13CertRequestContext *) p;
1279 
1280  //Malformed Certificate message?
1281  if(length < sizeof(Tls13CertRequestContext))
1282  return ERROR_DECODING_FAILED;
1283  if(length < (sizeof(Tls13CertRequestContext) + certRequestContext->length))
1284  return ERROR_DECODING_FAILED;
1285 
1286  //Point to the next field
1287  p += sizeof(Tls13CertRequestContext) + certRequestContext->length;
1288  //Remaining bytes to process
1289  length -= sizeof(Tls13CertRequestContext) + certRequestContext->length;
1290  }
1291 #endif
1292 
1293  //Point to the chain of certificates
1294  certificateList = (TlsCertificateList *) p;
1295 
1296  //Malformed Certificate message?
1297  if(length < sizeof(TlsCertificateList))
1298  return ERROR_DECODING_FAILED;
1299 
1300  //Get the size occupied by the certificate list
1301  n = LOAD24BE(certificateList->length);
1302  //Remaining bytes to process
1303  length -= sizeof(TlsCertificateList);
1304 
1305  //Ensure that the chain of certificates is valid
1306  if(n != length)
1307  return ERROR_DECODING_FAILED;
1308 
1309  //Empty certificate list received by the server?
1310  if(context->entity == TLS_CONNECTION_END_SERVER && length == 0)
1311  {
1312  //Check whether mutual authentication is required
1313  if(context->clientAuthMode == TLS_CLIENT_AUTH_REQUIRED)
1314  {
1315  //If client authentication is required by the server for the handshake
1316  //to continue, it may respond with a fatal handshake failure alert
1317  error = ERROR_HANDSHAKE_FAILED;
1318  }
1319  else
1320  {
1321  //Client authentication is optional
1322  context->peerCertType = TLS_CERT_NONE;
1323  //Exit immediately
1324  error = NO_ERROR;
1325  }
1326  }
1327  else
1328  {
1329 #if (TLS_RAW_PUBLIC_KEY_SUPPORT == ENABLED)
1330  //Check certificate type
1331  if(context->peerCertFormat == TLS_CERT_FORMAT_RAW_PUBLIC_KEY)
1332  {
1333  //Parse the raw public key
1334  error = tlsParseRawPublicKey(context, certificateList->value, n);
1335  }
1336  else
1337 #endif
1338  {
1339  //Parse the certificate chain
1340  error = tlsParseCertificateList(context, certificateList->value, n);
1341  }
1342  }
1343 
1344  //Check status code
1345  if(!error)
1346  {
1347  //Version of TLS prior to TLS 1.3?
1348  if(context->version <= TLS_VERSION_1_2)
1349  {
1350  //Check whether TLS operates as a client or a server
1351  if(context->entity == TLS_CONNECTION_END_CLIENT)
1352  {
1353  //The server does not send a ServerKeyExchange message when RSA
1354  //key exchange method is used
1355  if(context->keyExchMethod == TLS_KEY_EXCH_RSA)
1356  context->state = TLS_STATE_CERTIFICATE_REQUEST;
1357  else
1358  context->state = TLS_STATE_SERVER_KEY_EXCHANGE;
1359  }
1360  else
1361  {
1362  //Wait for a ClientKeyExchange message from the client
1363  context->state = TLS_STATE_CLIENT_KEY_EXCHANGE;
1364  }
1365  }
1366  else
1367  {
1368  //Check whether TLS operates as a client or a server
1369  if(context->entity == TLS_CONNECTION_END_CLIENT)
1370  {
1371  //The server must send a CertificateVerify message immediately
1372  //after the Certificate message
1373  context->state = TLS_STATE_SERVER_CERTIFICATE_VERIFY;
1374  }
1375  else
1376  {
1377  //The client must send a CertificateVerify message when the
1378  //Certificate message is non-empty
1379  if(context->peerCertType != TLS_CERT_NONE)
1380  context->state = TLS_STATE_CLIENT_CERTIFICATE_VERIFY;
1381  else
1382  context->state = TLS_STATE_CLIENT_FINISHED;
1383  }
1384  }
1385  }
1386 
1387  //Return status code
1388  return error;
1389 }
1390 
1391 
1392 /**
1393  * @brief Parse CertificateVerify message
1394  *
1395  * The CertificateVerify message is used to provide explicit verification
1396  * of a client certificate. This message is only sent following a client
1397  * certificate that has signing capability
1398  *
1399  * @param[in] context Pointer to the TLS context
1400  * @param[in] message Incoming CertificateVerify message to parse
1401  * @param[in] length Message length
1402  * @return Error code
1403  **/
1404 
1406  const TlsCertificateVerify *message, size_t length)
1407 {
1408  error_t error;
1409 
1410  //Debug message
1411  TRACE_INFO("CertificateVerify message received (%" PRIuSIZE " bytes)...\r\n", length);
1413 
1414  //Check whether TLS operates as a client or a server
1415  if(context->entity == TLS_CONNECTION_END_CLIENT)
1416  {
1417  //Check current state
1418  if(context->state != TLS_STATE_SERVER_CERTIFICATE_VERIFY)
1419  return ERROR_UNEXPECTED_MESSAGE;
1420  }
1421  else
1422  {
1423  //Check current state
1424  if(context->state != TLS_STATE_CLIENT_CERTIFICATE_VERIFY)
1425  return ERROR_UNEXPECTED_MESSAGE;
1426  }
1427 
1428 #if (TLS_MAX_VERSION >= SSL_VERSION_3_0 && TLS_MIN_VERSION <= TLS_VERSION_1_1)
1429  //SSL 3.0, TLS 1.0 or TLS 1.1 currently selected?
1430  if(context->version <= TLS_VERSION_1_1)
1431  {
1432  //In TLS version prior to 1.2, the digitally-signed element combines
1433  //MD5 and SHA-1
1434  error = tlsVerifySignature(context, message, length);
1435  }
1436  else
1437 #endif
1438 #if (TLS_MAX_VERSION >= TLS_VERSION_1_2 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
1439  //TLS 1.2 currently selected?
1440  if(context->version == TLS_VERSION_1_2)
1441  {
1442  //In TLS 1.2, the MD5/SHA-1 combination in the digitally-signed element
1443  //has been replaced with a single hash. The signed element now includes
1444  //a field that explicitly specifies the hash algorithm used
1445  error = tls12VerifySignature(context, message, length);
1446  }
1447  else
1448 #endif
1449 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
1450  //TLS 1.3 currently selected?
1451  if(context->version == TLS_VERSION_1_3)
1452  {
1453  //In TLS 1.3, the signed element specifies the signature algorithm used.
1454  //The content that is covered under the signature is the transcript hash
1455  //output
1456  error = tls13VerifySignature(context, message, length);
1457  }
1458  else
1459 #endif
1460  //Invalid TLS version?
1461  {
1462  //Report an error
1463  error = ERROR_INVALID_VERSION;
1464  }
1465 
1466  //Check status code
1467  if(!error)
1468  {
1469  //Version of TLS prior to TLS 1.3?
1470  if(context->version <= TLS_VERSION_1_2)
1471  {
1472  //Wait for a ChangeCipherSpec message from the client
1473  context->state = TLS_STATE_CLIENT_CHANGE_CIPHER_SPEC;
1474  }
1475  else
1476  {
1477  //Wait for a Finished message from the peer
1478  if(context->entity == TLS_CONNECTION_END_CLIENT)
1479  context->state = TLS_STATE_SERVER_FINISHED;
1480  else
1481  context->state = TLS_STATE_CLIENT_FINISHED;
1482  }
1483  }
1484 
1485  //Return status code
1486  return error;
1487 }
1488 
1489 
1490 /**
1491  * @brief Parse ChangeCipherSpec message
1492  * @param[in] context Pointer to the TLS context
1493  * @param[in] message Incoming ChangeCipherSpec message to parse
1494  * @param[in] length Message length
1495  * @return Error code
1496  **/
1497 
1499  const TlsChangeCipherSpec *message, size_t length)
1500 {
1501  error_t error;
1502 
1503  //Debug message
1504  TRACE_INFO("ChangeCipherSpec message received (%" PRIuSIZE " bytes)...\r\n", length);
1506 
1507  //Check the length of the ChangeCipherSpec message
1508  if(length != sizeof(TlsChangeCipherSpec))
1509  return ERROR_DECODING_FAILED;
1510 
1511  //The message consists of a single byte of value 1
1512  if(message->type != 0x01)
1513  return ERROR_DECODING_FAILED;
1514 
1515  //Version of TLS prior to TLS 1.3?
1516  if(context->version <= TLS_VERSION_1_2)
1517  {
1518  //Check whether TLS operates as a client or a server
1519  if(context->entity == TLS_CONNECTION_END_CLIENT)
1520  {
1521  //Check current state
1522  if(context->state != TLS_STATE_SERVER_CHANGE_CIPHER_SPEC)
1523  return ERROR_UNEXPECTED_MESSAGE;
1524  }
1525  else
1526  {
1527  //Check current state
1528  if(context->state != TLS_STATE_CLIENT_CHANGE_CIPHER_SPEC)
1529  return ERROR_UNEXPECTED_MESSAGE;
1530  }
1531 
1532  //Release decryption engine first
1533  tlsFreeEncryptionEngine(&context->decryptionEngine);
1534 
1535  //Check whether TLS operates as a client or a server
1536  if(context->entity == TLS_CONNECTION_END_CLIENT)
1537  {
1538  //Initialize decryption engine using server write keys
1539  error = tlsInitEncryptionEngine(context, &context->decryptionEngine,
1541  //Any error to report?
1542  if(error)
1543  return error;
1544 
1545  //Wait for a Finished message from the server
1546  context->state = TLS_STATE_SERVER_FINISHED;
1547  }
1548  else
1549  {
1550  //Initialize decryption engine using client write keys
1551  error = tlsInitEncryptionEngine(context, &context->decryptionEngine,
1553  //Any error to report?
1554  if(error)
1555  return error;
1556 
1557  //Wait for a Finished message from the client
1558  context->state = TLS_STATE_CLIENT_FINISHED;
1559  }
1560 
1561 #if (DTLS_SUPPORT == ENABLED)
1562  //DTLS protocol?
1563  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
1564  {
1565  //Initialize sliding window
1566  dtlsInitReplayWindow(context);
1567  }
1568 #endif
1569  }
1570  else
1571  {
1572  //In TLS 1.3, the ChangeCipherSpec message is used only for compatibility
1573  //purposes and must be dropped without further processing
1574  if(context->entity == TLS_CONNECTION_END_CLIENT)
1575  {
1576  //A ChangeCipherSpec message received received before the first
1577  //ClientHello message or after the server's Finished message must
1578  //be treated as an unexpected record type
1579  if(context->state != TLS_STATE_SERVER_HELLO &&
1580  context->state != TLS_STATE_SERVER_HELLO_2 &&
1581  context->state != TLS_STATE_ENCRYPTED_EXTENSIONS &&
1582  context->state != TLS_STATE_CERTIFICATE_REQUEST &&
1583  context->state != TLS_STATE_SERVER_CERTIFICATE &&
1584  context->state != TLS_STATE_SERVER_CERTIFICATE_VERIFY &&
1585  context->state != TLS_STATE_SERVER_FINISHED)
1586  {
1587  //Report an error
1588  return ERROR_UNEXPECTED_MESSAGE;
1589  }
1590  }
1591  else
1592  {
1593  //A ChangeCipherSpec message received received before the first
1594  //ClientHello message or after the client's Finished message must
1595  //be treated as an unexpected record type
1596  if(context->state != TLS_STATE_CLIENT_HELLO_2 &&
1597  context->state != TLS_STATE_CLIENT_CERTIFICATE &&
1598  context->state != TLS_STATE_CLIENT_CERTIFICATE_VERIFY &&
1599  context->state != TLS_STATE_CLIENT_FINISHED)
1600  {
1601  //Report an error
1602  return ERROR_UNEXPECTED_MESSAGE;
1603  }
1604  }
1605 
1606 #if (TLS_MAX_CHANGE_CIPHER_SPEC_MESSAGES > 0)
1607  //Increment the count of consecutive ChangeCipherSpec messages
1608  context->changeCipherSpecCount++;
1609 
1610  //Do not allow too many consecutive ChangeCipherSpec messages
1611  if(context->changeCipherSpecCount > TLS_MAX_CHANGE_CIPHER_SPEC_MESSAGES)
1612  return ERROR_UNEXPECTED_MESSAGE;
1613 #endif
1614  }
1615 
1616  //Successful processing
1617  return NO_ERROR;
1618 }
1619 
1620 
1621 /**
1622  * @brief Parse Finished message
1623  * @param[in] context Pointer to the TLS context
1624  * @param[in] message Incoming Finished message to parse
1625  * @param[in] length Message length
1626  * @return Error code
1627  **/
1628 
1630  const TlsFinished *message, size_t length)
1631 {
1632  error_t error;
1633 
1634  //Debug message
1635  TRACE_INFO("Finished message received (%" PRIuSIZE " bytes)...\r\n", length);
1637 
1638  //Check whether TLS operates as a client or a server
1639  if(context->entity == TLS_CONNECTION_END_CLIENT)
1640  {
1641  //Check current state
1642  if(context->state != TLS_STATE_SERVER_FINISHED)
1643  return ERROR_UNEXPECTED_MESSAGE;
1644 
1645  //The verify data is generated from all messages in this handshake
1646  //up to but not including the Finished message
1648  context->serverVerifyData, &context->serverVerifyDataLen);
1649  //Unable to generate the verify data?
1650  if(error)
1651  return error;
1652 
1653  //Check the length of the Finished message
1654  if(length != context->serverVerifyDataLen)
1655  {
1656 #if (TLS_MAX_EMPTY_RECORDS > 0)
1657  return ERROR_INVALID_SIGNATURE;
1658 #else
1659  return ERROR_DECODING_FAILED;
1660 #endif
1661  }
1662 
1663  //Check the resulting verify data
1664  if(memcmp(message, context->serverVerifyData, context->serverVerifyDataLen))
1665  return ERROR_INVALID_SIGNATURE;
1666  }
1667  else
1668  {
1669  //Check current state
1670  if(context->state != TLS_STATE_CLIENT_FINISHED)
1671  return ERROR_UNEXPECTED_MESSAGE;
1672 
1673  //The verify data is generated from all messages in this handshake
1674  //up to but not including the Finished message
1676  context->clientVerifyData, &context->clientVerifyDataLen);
1677  //Unable to generate the verify data?
1678  if(error)
1679  return error;
1680 
1681  //Check the length of the Finished message
1682  if(length != context->clientVerifyDataLen)
1683  {
1684 #if (TLS_MAX_EMPTY_RECORDS > 0)
1685  return ERROR_INVALID_SIGNATURE;
1686 #else
1687  return ERROR_DECODING_FAILED;
1688 #endif
1689  }
1690 
1691  //Check the resulting verify data
1692  if(memcmp(message, context->clientVerifyData, context->clientVerifyDataLen))
1693  return ERROR_INVALID_SIGNATURE;
1694  }
1695 
1696  //Version of TLS prior to TLS 1.3?
1697  if(context->version <= TLS_VERSION_1_2)
1698  {
1699  //Check whether TLS operates as a client or a server
1700  if(context->entity == TLS_CONNECTION_END_CLIENT)
1701  {
1702  //Abbreviated or full handshake?
1703  if(context->resume)
1704  context->state = TLS_STATE_CLIENT_CHANGE_CIPHER_SPEC;
1705  else
1706  context->state = TLS_STATE_APPLICATION_DATA;
1707  }
1708  else
1709  {
1710  //Abbreviated or full handshake?
1711  if(context->resume)
1712  context->state = TLS_STATE_APPLICATION_DATA;
1713  else
1714  context->state = TLS_STATE_SERVER_CHANGE_CIPHER_SPEC;
1715  }
1716  }
1717  else
1718  {
1719  //Check whether TLS operates as a client or a server
1720  if(context->entity == TLS_CONNECTION_END_CLIENT)
1721  {
1722  //Compute server application traffic keys
1723  context->state = TLS_STATE_SERVER_APP_TRAFFIC_KEYS;
1724  }
1725  else
1726  {
1727  //Compute client application traffic keys
1728  context->state = TLS_STATE_CLIENT_APP_TRAFFIC_KEYS;
1729  }
1730  }
1731 
1732  //Successful processing
1733  return NO_ERROR;
1734 }
1735 
1736 
1737 /**
1738  * @brief Parse Alert message
1739  * @param[in] context Pointer to the TLS context
1740  * @param[in] message Incoming Alert message to parse
1741  * @param[in] length Message length
1742  * @return Error code
1743  **/
1744 
1746  const TlsAlert *message, size_t length)
1747 {
1748  //Debug message
1749  TRACE_INFO("Alert message received (%" PRIuSIZE " bytes)...\r\n", length);
1751 
1752  //Check message length
1753  if(length != sizeof(TlsAlert))
1754  return ERROR_INVALID_LENGTH;
1755 
1756  //Debug message
1757  TRACE_DEBUG(" Level = %" PRIu8 "\r\n", message->level);
1758  TRACE_DEBUG(" Description = %" PRIu8 "\r\n", message->description);
1759 
1760  //Alert messages convey the severity of the message
1761  if(message->level == TLS_ALERT_LEVEL_WARNING)
1762  {
1763 #if (TLS_MAX_WARNING_ALERTS > 0)
1764  //Increment the count of consecutive warning alerts
1765  context->alertCount++;
1766 
1767  //Do not allow too many consecutive warning alerts
1768  if(context->alertCount > TLS_MAX_WARNING_ALERTS)
1769  return ERROR_UNEXPECTED_MESSAGE;
1770 #endif
1771 
1772  //Check alert type
1773  if(message->description == TLS_ALERT_CLOSE_NOTIFY)
1774  {
1775  //A closure alert has been received
1776  context->closeNotifyReceived = TRUE;
1777 
1778  //Close down the connection immediately
1779  if(context->state == TLS_STATE_APPLICATION_DATA)
1780  context->state = TLS_STATE_CLOSING;
1781  }
1782  else if(message->description == TLS_ALERT_USER_CANCELED)
1783  {
1784  //This alert notifies the recipient that the sender is canceling the
1785  //handshake for some reason unrelated to a protocol failure
1786  }
1787  else
1788  {
1789  //TLS 1.3 currently selected?
1790  if(context->version == TLS_VERSION_1_3)
1791  {
1792  //Unknown alert types must be treated as error alerts
1793  return ERROR_DECODING_FAILED;
1794  }
1795  }
1796  }
1797  else if(message->level == TLS_ALERT_LEVEL_FATAL)
1798  {
1799  //A fatal alert message has been received
1800  context->fatalAlertReceived = TRUE;
1801 
1802 #if (TLS_MAX_VERSION >= SSL_VERSION_3_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
1803  //Any connection terminated with a fatal alert must not be resumed
1804  if(context->entity == TLS_CONNECTION_END_SERVER)
1805  {
1806  tlsRemoveFromCache(context);
1807  }
1808 #endif
1809 
1810  //Servers and clients must forget any session identifiers
1811  memset(context->sessionId, 0, 32);
1812  context->sessionIdLen = 0;
1813 
1814  //Alert messages with a level of fatal result in the immediate
1815  //termination of the connection
1816  context->state = TLS_STATE_CLOSED;
1817  }
1818  else
1819  {
1820  //Report an error
1821  return ERROR_ILLEGAL_PARAMETER;
1822  }
1823 
1824  //Successful processing
1825  return NO_ERROR;
1826 }
1827 
1828 #endif
TLS (Transport Layer Security)
error_t tlsFormatSignatureAlgorithmsCertExtension(TlsContext *context, uint8_t *p, size_t *written)
Format SignatureAlgorithmsCert extension.
Definition: tls_common.c:999
error_t tlsParseChangeCipherSpec(TlsContext *context, const TlsChangeCipherSpec *message, size_t length)
Parse ChangeCipherSpec message.
Definition: tls_common.c:1498
Handshake message processing (TLS client)
error_t tls12GenerateSignature(TlsContext *context, uint8_t *p, size_t *length)
Digital signature generation(TLS 1.2)
error_t tlsFormatAlert(TlsContext *context, uint8_t level, uint8_t description, TlsAlert *message, size_t *length)
Format Alert message.
Definition: tls_common.c:768
Debugging facilities.
uint8_t p
Definition: ndp.h:295
error_t tlsFormatSignatureAlgorithmsExtension(TlsContext *context, uint_t cipherSuiteTypes, uint8_t *p, size_t *written)
Format SignatureAlgorithms extension.
Definition: tls_common.c:793
Generic error code.
Definition: error.h:43
error_t tlsRemoveFromCache(TlsContext *context)
Remove current session from cache.
Definition: tls_cache.c:263
uint8_t message[]
Definition: chap.h:150
error_t tlsFormatRawPublicKey(TlsContext *context, uint8_t *p, size_t *written)
Format raw public key.
error_t tlsParseCertificateVerify(TlsContext *context, const TlsCertificateVerify *message, size_t length)
Parse CertificateVerify message.
Definition: tls_common.c:1405
void dtlsInitReplayWindow(TlsContext *context)
Initialize sliding window.
Definition: dtls_misc.c:441
#define TLS_MAX_CHANGE_CIPHER_SPEC_MESSAGES
Definition: tls.h:741
#define TLS_VERSION_1_3
Definition: tls.h:90
error_t tlsSendChangeCipherSpec(TlsContext *context)
Send ChangeCipherSpec message.
Definition: tls_common.c:266
#define htons(value)
Definition: cpu_endian.h:390
#define TRACE_DEBUG_ARRAY(p, a, n)
Definition: debug.h:99
void TlsFinished
Finished message.
Definition: tls.h:1677
uint8_t level
Definition: tls.h:1696
error_t tlsFormatCertificateList(TlsContext *context, uint8_t *p, size_t *written)
Format certificate chain.
error_t tlsSendFinished(TlsContext *context)
Send Finished message.
Definition: tls_common.c:381
__start_packed struct @65 TlsSignHashAlgos
List of signature algorithms.
#define HTONS(value)
Definition: cpu_endian.h:388
__start_packed struct @66 TlsCertificateList
List of certificates.
#define ENABLED
Definition: os_port.h:35
error_t tlsParseAlert(TlsContext *context, const TlsAlert *message, size_t length)
Parse Alert message.
Definition: tls_common.c:1745
#define TRUE
Definition: os_port.h:48
error_t tlsVerifySignature(TlsContext *context, const uint8_t *p, size_t length)
Digital signature verification (SSL 3.0, TLS 1.0 and TLS 1.1)
__start_packed struct @89 TlsAlert
Alert message.
error_t tlsWriteProtocolData(TlsContext *context, const uint8_t *data, size_t length, TlsContentType contentType)
Write protocol data.
Definition: tls_record.c:58
error_t tlsSendCertificateVerify(TlsContext *context)
Send CertificateVerify message.
Definition: tls_common.c:190
TLS record protocol.
error_t tlsFormatCertificateVerify(TlsContext *context, TlsCertificateVerify *message, size_t *length)
Format CertificateVerify message.
Definition: tls_common.c:653
void TlsCertificateVerify
CertificateVerify message.
Definition: tls.h:1670
error_t tlsComputeVerifyData(TlsContext *context, TlsConnectionEnd entity, uint8_t *verifyData, size_t *verifyDataLen)
Compute verify data from previous handshake messages.
TLS helper functions.
__start_packed struct @68 TlsExtension
TLS extension.
TLS handshake.
__start_packed struct @102 Tls13CertRequestContext
Certificate request context.
error_t tls12VerifySignature(TlsContext *context, const uint8_t *p, size_t length)
Digital signature verification (TLS 1.2)
__start_packed struct @88 TlsChangeCipherSpec
ChangeCipherSpec message.
__start_packed struct @64 TlsSignHashAlgo
Signature algorithm.
error_t tlsInitEncryptionEngine(TlsContext *context, TlsEncryptionEngine *encryptionEngine, TlsConnectionEnd entity, const uint8_t *secret)
Initialize encryption engine.
Definition: tls_misc.c:376
#define LOAD24BE(p)
Definition: cpu_endian.h:179
DTLS record protocol.
error_t tlsSendAlert(TlsContext *context, uint8_t level, uint8_t description)
Send Alert message.
Definition: tls_common.c:478
bool_t x509IsHashAlgoSupported(X509HashAlgo hashAlgo)
Check whether a given hash algorithm is supported.
Definition: x509_common.c:373
#define STORE24BE(a, p)
Definition: cpu_endian.h:255
#define TLS_MAX_WARNING_ALERTS
Definition: tls.h:727
Handshake message processing (TLS client and server)
X.509 common definitions.
error_t tls13GenerateSignature(TlsContext *context, uint8_t *p, size_t *length)
Encryption engine.
Definition: tls.h:1926
#define TLS_VERSION_1_2
Definition: tls.h:83
#define TLS_VERSION_1_1
Definition: tls.h:82
bool_t x509IsSignAlgoSupported(X509SignatureAlgo signAlgo)
Check whether a given signature algorithm is supported.
Definition: x509_common.c:305
#define TRACE_INFO(...)
Definition: debug.h:86
TLS cipher suites.
Success.
Definition: error.h:42
error_t tls13VerifySignature(TlsContext *context, const uint8_t *p, size_t length)
error_t
Error codes.
Definition: error.h:40
unsigned int uint_t
Definition: compiler_port.h:43
error_t tlsParseFinished(TlsContext *context, const TlsFinished *message, size_t length)
Parse Finished message.
Definition: tls_common.c:1629
#define TLS_EDDSA_SIGN_SUPPORT
Definition: tls.h:349
error_t tlsParseRawPublicKey(TlsContext *context, const uint8_t *p, size_t length)
Parse raw public key.
#define PRIuSIZE
Definition: compiler_port.h:72
error_t tlsParseCertificate(TlsContext *context, const TlsCertificate *message, size_t length)
Parse Certificate message.
Definition: tls_common.c:1229
error_t tlsGenerateSignature(TlsContext *context, uint8_t *p, size_t *length)
Digital signature generation(SSL 3.0, TLS 1.0 or TLS 1.1)
uint8_t description
Definition: tls.h:1697
error_t tlsSendHandshakeMessage(TlsContext *context, const void *data, size_t length, TlsMessageType type)
Send handshake message.
error_t tlsParseCertificateList(TlsContext *context, const uint8_t *p, size_t length)
Parse certificate chain.
#define TRACE_INFO_ARRAY(p, a, n)
Definition: debug.h:87
error_t tlsSendCertificate(TlsContext *context)
Send Certificate message.
Definition: tls_common.c:60
void tlsFreeEncryptionEngine(TlsEncryptionEngine *encryptionEngine)
Release encryption engine.
Definition: tls_misc.c:599
Transcript hash calculation.
error_t tlsFormatFinished(TlsContext *context, TlsFinished *message, size_t *length)
Format Finished message.
Definition: tls_common.c:734
RSA/DSA/ECDSA/EdDSA signature generation and verification.
error_t tlsFormatChangeCipherSpec(TlsContext *context, TlsChangeCipherSpec *message, size_t *length)
Format ChangeCipherSpec message.
Definition: tls_common.c:712
error_t dtlsWriteProtocolData(TlsContext *context, const uint8_t *data, size_t length, TlsContentType contentType)
Write protocol data.
Definition: dtls_record.c:56
uint8_t length
Definition: dtls_misc.h:140
uint8_t n
error_t tlsFormatCertificate(TlsContext *context, TlsCertificate *message, size_t *length)
Format Certificate message.
Definition: tls_common.c:564
Handshake message processing (TLS server)
#define TlsContext
Definition: tls.h:34
void TlsCertificate
Certificate message.
Definition: tls.h:1631
Session cache management.
Certificate handling.
#define SSL_VERSION_3_0
Definition: tls.h:80
#define TRACE_DEBUG(...)
Definition: debug.h:98