Sergey Pastor / 1

Dependents:   Nucleo

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers tls_server.c Source File

tls_server.c

Go to the documentation of this file.
00001 /**
00002  * @file tls_server.c
00003  * @brief Handshake message processing (TLS server)
00004  *
00005  * @section License
00006  *
00007  * Copyright (C) 2010-2017 Oryx Embedded SARL. All rights reserved.
00008  *
00009  * This file is part of CycloneSSL Open.
00010  *
00011  * This program is free software; you can redistribute it and/or
00012  * modify it under the terms of the GNU General Public License
00013  * as published by the Free Software Foundation; either version 2
00014  * of the License, or (at your option) any later version.
00015  *
00016  * This program is distributed in the hope that it will be useful,
00017  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00018  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00019  * GNU General Public License for more details.
00020  *
00021  * You should have received a copy of the GNU General Public License
00022  * along with this program; if not, write to the Free Software Foundation,
00023  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
00024  *
00025  * @section Description
00026  *
00027  * The TLS protocol provides communications security over the Internet. The
00028  * protocol allows client/server applications to communicate in a way that
00029  * is designed to prevent eavesdropping, tampering, or message forgery
00030  *
00031  * @author Oryx Embedded SARL (www.oryx-embedded.com)
00032  * @version 1.7.6
00033  **/
00034 
00035 //Switch to the appropriate trace level
00036 #define TRACE_LEVEL TLS_TRACE_LEVEL
00037 
00038 //Dependencies
00039 #include <string.h>
00040 #include "tls.h"
00041 #include "tls_cipher_suites.h"
00042 #include "tls_server.h"
00043 #include "tls_server_misc.h"
00044 #include "tls_common.h"
00045 #include "tls_record.h"
00046 #include "tls_cache.h"
00047 #include "tls_misc.h"
00048 #include "x509.h"
00049 #include "pem.h"
00050 #include "date_time.h"
00051 #include "debug.h"
00052 
00053 //Check SSL library configuration
00054 #if (TLS_SUPPORT == ENABLED && TLS_SERVER_SUPPORT == ENABLED)
00055 
00056 
00057 /**
00058  * @brief TLS server handshake
00059  *
00060  * TLS handshake protocol is responsible for the authentication
00061  * and key exchange necessary to establish a secure session
00062  *
00063  * @param[in] context Pointer to the TLS context
00064  * @return Error code
00065  **/
00066 
00067 error_t tlsServerHandshake(TlsContext *context)
00068 {
00069    error_t error;
00070 
00071    //Initialize status code
00072    error = NO_ERROR;
00073 
00074    //Wait for the handshake to complete
00075    do
00076    {
00077       //Flush send buffer
00078       if(context->state != TLS_STATE_CLOSED)
00079          error = tlsWriteProtocolData(context, NULL, 0, TLS_TYPE_NONE);
00080 
00081       //Check status code
00082       if(!error)
00083       {
00084          //Check whether the handshake is complete
00085          if(context->state == TLS_STATE_APPLICATION_DATA)
00086          {
00087             //At this is point, the handshake is complete and the server
00088             //starts to exchange application-layer data
00089             break;
00090          }
00091 
00092          //The TLS handshake is implemented as a state machine
00093          //representing the current location in the protocol
00094          switch(context->state)
00095          {
00096          //Default state?
00097          case TLS_STATE_INIT:
00098             //The client initiates the TLS handshake by sending a ClientHello
00099             //message to the server
00100             context->state = TLS_STATE_CLIENT_HELLO;
00101             break;
00102          //Sending ServerHello message?
00103          case TLS_STATE_SERVER_HELLO:
00104             //The server will send this message in response to a ClientHello
00105             //message when it was able to find an acceptable set of algorithms
00106             error = tlsSendServerHello(context);
00107             break;
00108          //Sending Certificate message?
00109          case TLS_STATE_SERVER_CERTIFICATE:
00110             //The server must send a Certificate message whenever the agreed-
00111             //upon key exchange method uses certificates for authentication. This
00112             //message will always immediately follow the ServerHello message
00113             error = tlsSendCertificate(context);
00114             break;
00115          //Sending ServerKeyExchange message?
00116          case TLS_STATE_SERVER_KEY_EXCHANGE:
00117             //The ServerKeyExchange message is sent by the server only when the
00118             //server Certificate message (if sent) does not contain enough data
00119             //to allow the client to exchange a premaster secret
00120             error = tlsSendServerKeyExchange(context);
00121             break;
00122          //Sending Certificate message?
00123          case TLS_STATE_CERTIFICATE_REQUEST:
00124             //A non-anonymous server can optionally request a certificate from the
00125             //client, if appropriate for the selected cipher suite. This message,
00126             //if sent, will immediately follow the ServerKeyExchange message
00127             error = tlsSendCertificateRequest(context);
00128             break;
00129          //Sending ServerHelloDone message?
00130          case TLS_STATE_SERVER_HELLO_DONE:
00131             //The ServerHelloDone message is sent by the server to indicate the
00132             //end of the ServerHello and associated messages
00133             error = tlsSendServerHelloDone(context);
00134             break;
00135          //Sending ChangeCipherSpec message?
00136          case TLS_STATE_SERVER_CHANGE_CIPHER_SPEC:
00137             //The ChangeCipherSpec message is sent by the server and to notify the
00138             //client that subsequent records will be protected under the newly
00139             //negotiated CipherSpec and keys
00140             error = tlsSendChangeCipherSpec(context);
00141             break;
00142          //Sending Finished message?
00143          case TLS_STATE_SERVER_FINISHED:
00144             //A Finished message is always sent immediately after a changeCipherSpec
00145             //message to verify that the key exchange and authentication processes
00146             //were successful
00147             error = tlsSendFinished(context);
00148             break;
00149          //Waiting for a message from the client?
00150          case TLS_STATE_CLIENT_HELLO:
00151          case TLS_STATE_CLIENT_CERTIFICATE:
00152          case TLS_STATE_CLIENT_KEY_EXCHANGE:
00153          case TLS_STATE_CERTIFICATE_VERIFY:
00154          case TLS_STATE_CLIENT_CHANGE_CIPHER_SPEC:
00155          case TLS_STATE_CLIENT_FINISHED:
00156             //Parse incoming handshake message
00157             error = tlsParseClientMessage(context);
00158             break;
00159          //Sending Alert message?
00160          case TLS_STATE_CLOSING:
00161             //Mark the TLS connection as closed
00162             context->state = TLS_STATE_CLOSED;
00163             break;
00164          //TLS connection closed?
00165          case TLS_STATE_CLOSED:
00166             //Debug message
00167             TRACE_WARNING("TLS handshake failure!\r\n");
00168             //Report an error
00169             error = ERROR_HANDSHAKE_FAILED;
00170             break;
00171          //Invalid state?
00172          default:
00173             //Report an error
00174             error = ERROR_UNEXPECTED_STATE;
00175             break;
00176          }
00177       }
00178 
00179       //Abort TLS handshake if an error was encountered
00180    } while(!error);
00181 
00182    //Successful TLS handshake?
00183    if(!error)
00184    {
00185       //Save current session in the session cache for further reuse
00186       tlsSaveToCache(context);
00187    }
00188    else
00189    {
00190       //Send an alert message to the client, if applicable
00191       tlsProcessError(context, error);
00192    }
00193 
00194    //Return status code
00195    return error;
00196 }
00197 
00198 
00199 /**
00200  * @brief Parse incoming handshake message
00201  * @param[in] context Pointer to the TLS context
00202  * @return Error code
00203  **/
00204 
00205 error_t tlsParseClientMessage(TlsContext *context)
00206 {
00207    error_t error;
00208    size_t length;
00209    void *message;
00210    TlsContentType contentType;
00211 
00212    //A message can be fragmented across several records...
00213    error = tlsReadProtocolData(context, &message, &length, &contentType);
00214 
00215    //Check status code
00216    if(!error)
00217    {
00218       //Handshake message received?
00219       if(contentType == TLS_TYPE_HANDSHAKE)
00220       {
00221          //Check handshake message type
00222          switch(((TlsHandshake *) message)->msgType)
00223          {
00224          //ClientHello message received?
00225          case TLS_TYPE_CLIENT_HELLO:
00226             //When a client first connects to a server, it is required to send
00227             //the ClientHello as its first message
00228             error = tlsParseClientHello(context, message, length);
00229             break;
00230          //Certificate message received?
00231          case TLS_TYPE_CERTIFICATE:
00232             //This is the first message the client can send after receiving a
00233             //ServerHelloDone message. This message is only sent if the server
00234             //requests a certificate
00235             error = tlsParseCertificate(context, message, length);
00236             break;
00237          //ClientKeyExchange message received?
00238          case TLS_TYPE_CLIENT_KEY_EXCHANGE:
00239             //This message is always sent by the client. It must immediately
00240             //follow the client certificate message, if it is sent. Otherwise,
00241             //it must be the first message sent by the client after it receives
00242             //the ServerHelloDone message
00243             error = tlsParseClientKeyExchange(context, message, length);
00244             break;
00245          //CertificateVerify message received?
00246          case TLS_TYPE_CERTIFICATE_VERIFY:
00247             //This message is used to provide explicit verification of a client
00248             //certificate. This message is only sent following a client certificate
00249             //that has signing capability. When sent, it must immediately follow
00250             //the clientKeyExchange message
00251             error = tlsParseCertificateVerify(context, message, length);
00252             break;
00253          //Finished message received?
00254          case TLS_TYPE_FINISHED:
00255             //A Finished message is always sent immediately after a changeCipherSpec
00256             //message to verify that the key exchange and authentication processes
00257             //were successful
00258             error = tlsParseFinished(context, message, length);
00259             break;
00260          //Invalid handshake message received?
00261          default:
00262             //Report an error
00263             error = ERROR_UNEXPECTED_MESSAGE;
00264             break;
00265          }
00266       }
00267       //ChangeCipherSpec message received?
00268       else if(contentType == TLS_TYPE_CHANGE_CIPHER_SPEC)
00269       {
00270          //The ChangeCipherSpec message is sent by the client and to notify the
00271          //server that subsequent records will be protected under the newly
00272          //negotiated CipherSpec and keys
00273          error = tlsParseChangeCipherSpec(context, message, length);
00274       }
00275       //Alert message received?
00276       else if(contentType == TLS_TYPE_ALERT)
00277       {
00278          //Parse Alert message
00279          error = tlsParseAlert(context, message, length);
00280       }
00281       //Application data received?
00282       else
00283       {
00284          //The client cannot transmit application data
00285          //before the handshake is completed
00286          error = ERROR_UNEXPECTED_MESSAGE;
00287       }
00288 
00289       //Advance data pointer
00290       context->rxBufferPos += length;
00291       //Number of bytes still pending in the receive buffer
00292       context->rxBufferLen -= length;
00293    }
00294 
00295    //Return status code
00296    return error;
00297 }
00298 
00299 
00300 /**
00301  * @brief Send ServerHello message
00302  *
00303  * The server will send this message in response to a ClientHello
00304  * message when it was able to find an acceptable set of algorithms.
00305  * If it cannot find such a match, it will respond with a handshake
00306  * failure alert
00307  *
00308  * @param[in] context Pointer to the TLS context
00309  * @return Error code
00310  **/
00311 
00312 error_t tlsSendServerHello(TlsContext *context)
00313 {
00314    error_t error;
00315    size_t length;
00316    TlsServerHello *message;
00317 
00318    //Point to the buffer where to format the message
00319    message = (TlsServerHello *) context->txBuffer;
00320 
00321    //Generate the server random value using a cryptographically-safe
00322    //pseudorandom number generator
00323    error = tlsGenerateRandomValue(context, &context->serverRandom);
00324 
00325    //Check status code
00326    if(!error)
00327    {
00328       //Format ServerHello message
00329       error = tlsFormatServerHello(context, message, &length);
00330    }
00331 
00332    //Check status code
00333    if(!error)
00334    {
00335       //Debug message
00336       TRACE_INFO("Sending ServerHello message (%" PRIuSIZE " bytes)...\r\n", length);
00337       TRACE_DEBUG_ARRAY("  ", message, length);
00338 
00339       //Send handshake message
00340       error = tlsWriteProtocolData(context, message, length, TLS_TYPE_HANDSHAKE);
00341    }
00342 
00343    //Check status code
00344    if(error == NO_ERROR || error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
00345    {
00346 #if (TLS_SESSION_RESUME_SUPPORT == ENABLED)
00347       //Use abbreviated handshake?
00348       if(context->resume)
00349       {
00350          //Derive session keys from the master secret
00351          error = tlsGenerateKeys(context);
00352 
00353          //Key material successfully generated?
00354          if(!error)
00355          {
00356             //At this point, both client and server must send ChangeCipherSpec
00357             //messages and proceed directly to Finished messages
00358             context->state = TLS_STATE_SERVER_CHANGE_CIPHER_SPEC;
00359          }
00360       }
00361       else
00362 #endif
00363       {
00364          //Perform a full handshake
00365          context->state = TLS_STATE_SERVER_CERTIFICATE;
00366       }
00367    }
00368 
00369    //Return status code
00370    return error;
00371 }
00372 
00373 
00374 /**
00375  * @brief Send ServerKeyExchange message
00376  *
00377  * The ServerKeyExchange message is sent by the server only when the
00378  * server Certificate message does not contain enough data to allow
00379  * the client to exchange a premaster secret
00380  *
00381  * @param[in] context Pointer to the TLS context
00382  * @return Error code
00383  **/
00384 
00385 error_t tlsSendServerKeyExchange(TlsContext *context)
00386 {
00387    error_t error;
00388    size_t length;
00389    TlsServerKeyExchange *message;
00390 
00391    //Initialize status code
00392    error = NO_ERROR;
00393 
00394    //Point to the buffer where to format the message
00395    message = (TlsServerKeyExchange *) context->txBuffer;
00396    //Initialize length
00397    length = 0;
00398 
00399    //The ServerKeyExchange message is sent by the server only when the server
00400    //Certificate message (if sent) does not contain enough data to allow the
00401    //client to exchange a premaster secret
00402    if(context->keyExchMethod == TLS_KEY_EXCH_DH_ANON ||
00403       context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
00404       context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS ||
00405       context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK ||
00406       context->keyExchMethod == TLS_KEY_EXCH_ECDH_ANON ||
00407       context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
00408       context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA ||
00409       context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
00410    {
00411       //Format ServerKeyExchange message
00412       error = tlsFormatServerKeyExchange(context, message, &length);
00413    }
00414    else if(context->keyExchMethod == TLS_KEY_EXCH_PSK ||
00415       context->keyExchMethod == TLS_KEY_EXCH_RSA_PSK)
00416    {
00417 #if (TLS_PSK_SUPPORT == ENABLED || TLS_RSA_PSK_SUPPORT == ENABLED || \
00418    TLS_DHE_PSK_SUPPORT == ENABLED || TLS_ECDHE_PSK_SUPPORT == ENABLED)
00419       //If no PSK identity hint is provided by the server, the
00420       //ServerKeyExchange message is omitted...
00421       if(context->pskIdentityHint != NULL)
00422       {
00423          //Format ServerKeyExchange message
00424          error = tlsFormatServerKeyExchange(context, message, &length);
00425       }
00426 #endif
00427    }
00428 
00429    //Check status code
00430    if(!error)
00431    {
00432       //Any message to send?
00433       if(length > 0)
00434       {
00435          //Debug message
00436          TRACE_INFO("Sending ServerKeyExchange message (%" PRIuSIZE " bytes)...\r\n", length);
00437          TRACE_DEBUG_ARRAY("  ", message, length);
00438 
00439          //Send handshake message
00440          error = tlsWriteProtocolData(context, message, length, TLS_TYPE_HANDSHAKE);
00441       }
00442    }
00443 
00444    //Check status code
00445    if(error == NO_ERROR || error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
00446    {
00447       //Prepare to send a CertificateRequest message...
00448       context->state = TLS_STATE_CERTIFICATE_REQUEST;
00449    }
00450 
00451    //Return status code
00452    return error;
00453 }
00454 
00455 
00456 /**
00457  * @brief Send CertificateRequest message
00458  *
00459  * A server can optionally request a certificate from the client, if
00460  * appropriate for the selected cipher suite. This message will
00461  * immediately follow the ServerKeyExchange message
00462  *
00463  * @param[in] context Pointer to the TLS context
00464  * @return Error code
00465  **/
00466 
00467 error_t tlsSendCertificateRequest(TlsContext *context)
00468 {
00469    error_t error;
00470    size_t length;
00471    TlsCertificateRequest *message;
00472 
00473    //Initialize status code
00474    error = NO_ERROR;
00475 
00476 #if (TLS_RSA_SIGN_SUPPORT == ENABLED || TLS_DSA_SIGN_SUPPORT == ENABLED || TLS_ECDSA_SIGN_SUPPORT == ENABLED)
00477    //A server can optionally request a certificate from the client
00478    if(context->clientAuthMode != TLS_CLIENT_AUTH_NONE)
00479    {
00480       //Non-anonymous key exchange?
00481       if(context->keyExchMethod == TLS_KEY_EXCH_RSA ||
00482          context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
00483          context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS ||
00484          context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
00485          context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA ||
00486          context->keyExchMethod == TLS_KEY_EXCH_RSA_PSK)
00487       {
00488          //Point to the buffer where to format the message
00489          message = (TlsCertificateRequest *) context->txBuffer;
00490 
00491          //Format CertificateRequest message
00492          error = tlsFormatCertificateRequest(context, message, &length);
00493 
00494          //Check status code
00495          if(!error)
00496          {
00497             //Debug message
00498             TRACE_INFO("Sending CertificateRequest message (%" PRIuSIZE " bytes)...\r\n", length);
00499             TRACE_DEBUG_ARRAY("  ", message, length);
00500 
00501             //Send handshake message
00502             error = tlsWriteProtocolData(context, message, length, TLS_TYPE_HANDSHAKE);
00503          }
00504       }
00505    }
00506 #endif
00507 
00508    //Check status code
00509    if(error == NO_ERROR || error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
00510    {
00511       //Prepare to send a ServerHelloDone message...
00512       context->state = TLS_STATE_SERVER_HELLO_DONE;
00513    }
00514 
00515    //Return status code
00516    return error;
00517 }
00518 
00519 
00520 /**
00521  * @brief Send ServerHelloDone message
00522  *
00523  * The ServerHelloDone message is sent by the server to indicate the
00524  * end of the ServerHello and associated messages. After sending this
00525  * message, the server will wait for a client response
00526  *
00527  * @param[in] context Pointer to the TLS context
00528  * @return Error code
00529  **/
00530 
00531 error_t tlsSendServerHelloDone(TlsContext *context)
00532 {
00533    error_t error;
00534    size_t length;
00535    TlsServerHelloDone *message;
00536 
00537    //Point to the buffer where to format the message
00538    message = (TlsServerHelloDone *) context->txBuffer;
00539 
00540    //Format ServerHelloDone message
00541    error = tlsFormatServerHelloDone(context, message, &length);
00542 
00543    //Check status code
00544    if(!error)
00545    {
00546       //Debug message
00547       TRACE_INFO("Sending ServerHelloDone message (%" PRIuSIZE " bytes)...\r\n", length);
00548       TRACE_DEBUG_ARRAY("  ", message, length);
00549 
00550       //Send handshake message
00551       error = tlsWriteProtocolData(context, message, length, TLS_TYPE_HANDSHAKE);
00552    }
00553 
00554    //Check status code
00555    if(error == NO_ERROR || error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
00556    {
00557       //The client must send a Certificate message if the server requests it
00558       if(context->clientAuthMode != TLS_CLIENT_AUTH_NONE)
00559          context->state = TLS_STATE_CLIENT_CERTIFICATE;
00560       else
00561          context->state = TLS_STATE_CLIENT_KEY_EXCHANGE;
00562    }
00563 
00564    //Return status code
00565    return error;
00566 }
00567 
00568 
00569 /**
00570  * @brief Format ServerHello message
00571  * @param[in] context Pointer to the TLS context
00572  * @param[out] message Buffer where to format the ServerHello message
00573  * @param[out] length Length of the resulting ServerHello message
00574  * @return Error code
00575  **/
00576 
00577 error_t tlsFormatServerHello(TlsContext *context,
00578    TlsServerHello *message, size_t *length)
00579 {
00580    uint8_t *p;
00581    TlsExtensions *extensionList;
00582 
00583    //Handshake message type
00584    message->msgType = TLS_TYPE_SERVER_HELLO;
00585 
00586    //This field contains the lower of the version suggested by the client
00587    //in the ClientHello and the highest supported by the server
00588    message->serverVersion = htons(context->version);
00589 
00590    //Server random value
00591    message->random = context->serverRandom;
00592 
00593    //Point to the session ID
00594    p = message->sessionId;
00595    //Total length of the message
00596    *length = sizeof(TlsServerHello);
00597 
00598 #if (TLS_SESSION_RESUME_SUPPORT == ENABLED)
00599    //The SessionID uniquely identifies the current session
00600    message->sessionIdLength = (uint8_t)context->sessionIdLen;
00601    memcpy(message->sessionId, context->sessionId, context->sessionIdLen);
00602 #else
00603    //The server may return an empty session ID to indicate that the session
00604    //will not be cached and therefore cannot be resumed
00605    message->sessionIdLength = 0;
00606 #endif
00607 
00608    //Debug message
00609    TRACE_INFO("Session ID (%" PRIu8 " bytes):\r\n", message->sessionIdLength);
00610    TRACE_INFO_ARRAY("  ", message->sessionId, message->sessionIdLength);
00611 
00612    //Advance data pointer
00613    p += message->sessionIdLength;
00614    //Adjust the length of the message
00615    *length += message->sessionIdLength;
00616 
00617    //The single cipher suite selected by the server
00618    STORE16BE(context->cipherSuite, p);
00619    //Advance data pointer
00620    p += sizeof(TlsCipherSuite);
00621    //Adjust the length of the message
00622    *length += sizeof(TlsCipherSuite);
00623 
00624    //The single compression algorithm selected by the server
00625    *p = context->compressionMethod;
00626    //Advance data pointer
00627    p += sizeof(TlsCompressionMethod);
00628    //Adjust the length of the message
00629    *length += sizeof(TlsCompressionMethod);
00630 
00631    //Only extensions offered by the client can appear in the server's list
00632    extensionList = (TlsExtensions *) p;
00633    //Total length of the extension list
00634    extensionList->length = 0;
00635 
00636    //Point to the first extension of the list
00637    p += sizeof(TlsExtensions);
00638 
00639 #if (TLS_ECDH_ANON_SUPPORT == ENABLED || TLS_ECDHE_RSA_SUPPORT == ENABLED || \
00640    TLS_ECDHE_ECDSA_SUPPORT == ENABLED || TLS_ECDHE_PSK_SUPPORT == ENABLED)
00641    //A server that selects an ECC cipher suite in response to a ClientHello
00642    //message including an EcPointFormats extension appends this extension
00643    //to its ServerHello message
00644    if(tlsIsEccCipherSuite(context->cipherSuite) && context->ecPointFormatExtFound)
00645    {
00646       uint_t n;
00647       TlsExtension *extension;
00648       TlsEcPointFormatList *ecPointFormatList;
00649 
00650       //Add the EcPointFormats extension
00651       extension = (TlsExtension *) p;
00652       //Type of the extension
00653       extension->type = HTONS(TLS_EXT_EC_POINT_FORMATS);
00654 
00655       //Point to the list of supported EC point formats
00656       ecPointFormatList = (TlsEcPointFormatList *) extension->value;
00657       //Items in the list are ordered according to server's preferences
00658       n = 0;
00659 
00660       //The server can parse only the uncompressed point format...
00661       ecPointFormatList->value[n++] = TLS_EC_POINT_FORMAT_UNCOMPRESSED;
00662       //Fix the length of the list
00663       ecPointFormatList->length = n;
00664 
00665       //Consider the 2-byte length field that precedes the list
00666       n += sizeof(TlsEcPointFormatList);
00667       //Fix the length of the extension
00668       extension->length = htons(n);
00669 
00670       //Compute the length, in bytes, of the EcPointFormats extension
00671       n += sizeof(TlsExtension);
00672       //Fix the length of the extension list
00673       extensionList->length += n;
00674 
00675       //Point to the next field
00676       p += n;
00677       //Total length of the message
00678       *length += n;
00679    }
00680 #endif
00681 
00682    //Check whether the extension list is empty
00683    if(extensionList->length > 0)
00684    {
00685       //Convert the length of the extension list to network byte order
00686       extensionList->length = htons(extensionList->length);
00687       //Total length of the message
00688       *length += sizeof(TlsExtensions);
00689    }
00690 
00691    //Fix the length field
00692    STORE24BE(*length - sizeof(TlsHandshake), message->length);
00693 
00694    //Successful processing
00695    return NO_ERROR;
00696 }
00697 
00698 
00699 /**
00700  * @brief Format ServerKeyExchange message
00701  * @param[in] context Pointer to the TLS context
00702  * @param[out] message Buffer where to format the ServerKeyExchange message
00703  * @param[out] length Length of the resulting ServerKeyExchange message
00704  * @return Error code
00705  **/
00706 
00707 error_t tlsFormatServerKeyExchange(TlsContext *context,
00708    TlsServerKeyExchange *message, size_t *length)
00709 {
00710    error_t error;
00711    size_t n;
00712    size_t paramsLen;
00713    uint8_t *p;
00714    uint8_t *params;
00715 
00716    //Handshake message type
00717    message->msgType = TLS_TYPE_SERVER_KEY_EXCHANGE;
00718 
00719    //Point to the body of the handshake message
00720    p = message->data;
00721    //Length of the handshake message
00722    *length = 0;
00723 
00724    //PSK key exchange method?
00725    if(context->keyExchMethod == TLS_KEY_EXCH_PSK ||
00726       context->keyExchMethod == TLS_KEY_EXCH_RSA_PSK ||
00727       context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK ||
00728       context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
00729    {
00730       //To help the client in selecting which identity to use, the server
00731       //can provide a PSK identity hint in the ServerKeyExchange message
00732       error = tlsFormatPskIdentityHint(context, p, &n);
00733       //Any error to report?
00734       if(error)
00735          return error;
00736 
00737       //Advance data pointer
00738       p += n;
00739       //Adjust the length of the message
00740       *length += n;
00741    }
00742 
00743    //Diffie-Hellman or ECDH key exchange method?
00744    if(context->keyExchMethod == TLS_KEY_EXCH_DH_ANON ||
00745       context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
00746       context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS ||
00747       context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK ||
00748       context->keyExchMethod == TLS_KEY_EXCH_ECDH_ANON ||
00749       context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
00750       context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA ||
00751       context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
00752    {
00753       //Point to the server's key exchange parameters
00754       params = p;
00755 
00756       //Format server's key exchange parameters
00757       error = tlsFormatServerKeyParams(context, p, &paramsLen);
00758       //Any error to report?
00759       if(error)
00760          return error;
00761 
00762       //Advance data pointer
00763       p += paramsLen;
00764       //Adjust the length of the message
00765       *length += paramsLen;
00766    }
00767 
00768    //For non-anonymous Diffie-Hellman and ECDH key exchanges, a signature
00769    //over the server's key exchange parameters shall be generated
00770    if(context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
00771       context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS ||
00772       context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
00773       context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA)
00774    {
00775       //Sign server's key exchange parameters
00776       error = tlsGenerateServerKeySignature(context, p, params, paramsLen, &n);
00777       //Any error to report?
00778       if(error)
00779          return error;
00780 
00781       //Advance data pointer
00782       p += n;
00783       //Adjust the length of the message
00784       *length += n;
00785    }
00786 
00787    //Fix the length field
00788    STORE24BE(*length, message->length);
00789    //Length of the complete handshake message
00790    *length += sizeof(TlsHandshake);
00791 
00792    //Successful processing
00793    return NO_ERROR;
00794 }
00795 
00796 
00797 /**
00798  * @brief Format CertificateRequest message
00799  * @param[in] context Pointer to the TLS context
00800  * @param[out] message Buffer where to format the CertificateRequest message
00801  * @param[out] length Length of the resulting CertificateRequest message
00802  * @return Error code
00803  **/
00804 
00805 error_t tlsFormatCertificateRequest(TlsContext *context,
00806    TlsCertificateRequest *message, size_t *length)
00807 {
00808    error_t error;
00809    size_t n;
00810    uint8_t *p;
00811    const char_t *pemCert;
00812    size_t pemCertLength;
00813    uint8_t *derCert;
00814    size_t derCertSize;
00815    size_t derCertLength;
00816    X509CertificateInfo *certInfo;
00817    TlsCertAuthorities *certAuthorities;
00818 
00819    //Initialize status code
00820    error = NO_ERROR;
00821 
00822    //Handshake message type
00823    message->msgType = TLS_TYPE_CERTIFICATE_REQUEST;
00824 
00825    //Enumerate the types of certificate types that the client may offer
00826    n = 0;
00827 
00828 #if (TLS_RSA_SIGN_SUPPORT == ENABLED)
00829    //Accept certificates that contain a RSA public key
00830    message->certificateTypes[n++] = TLS_CERT_RSA_SIGN;
00831 #endif
00832 #if (TLS_DSA_SIGN_SUPPORT == ENABLED)
00833    //Accept certificates that contain a DSA public key
00834    message->certificateTypes[n++] = TLS_CERT_DSS_SIGN;
00835 #endif
00836 #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED)
00837    //Accept certificates that contain an ECDSA public key
00838    message->certificateTypes[n++] = TLS_CERT_ECDSA_SIGN;
00839 #endif
00840 
00841    //Set the length of the list
00842    message->certificateTypesLength = (uint8_t) n;
00843    //Total length of the message
00844    *length = sizeof(TlsCertificateRequest) + n;
00845 
00846 #if (TLS_MAX_VERSION >= TLS_VERSION_1_2 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
00847    //Check whether TLS 1.2 is currently used
00848    if(context->version == TLS_VERSION_1_2)
00849    {
00850       TlsSignHashAlgos *supportedSignAlgos;
00851 
00852       //Point to the list of the hash/signature algorithm pairs that
00853       //the server is able to verify
00854       supportedSignAlgos = PTR_OFFSET(message, *length);
00855 
00856       //Enumerate the hash/signature algorithm pairs in descending
00857       //order of preference
00858       n = 0;
00859 
00860 #if (TLS_RSA_SIGN_SUPPORT == ENABLED)
00861       //SHA-1 with RSA is always supported
00862       supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA;
00863       supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA1;
00864 
00865       //The hash algorithm used for PRF operations can also be used for signing
00866       if(context->prfHashAlgo == SHA256_HASH_ALGO)
00867       {
00868          //SHA-256 with RSA is supported
00869          supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA;
00870          supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA256;
00871       }
00872 #if (TLS_SHA384_SUPPORT == ENABLED)
00873       else if(context->prfHashAlgo == SHA384_HASH_ALGO)
00874       {
00875          //SHA-384 with RSA is supported
00876          supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_RSA;
00877          supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA384;
00878       }
00879 #endif
00880 #endif
00881 #if (TLS_DSA_SIGN_SUPPORT == ENABLED)
00882       //DSA with SHA-1 is always supported
00883       supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_DSA;
00884       supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA1;
00885 
00886       //The hash algorithm used for PRF operations can also be used for signing
00887       if(context->prfHashAlgo == SHA256_HASH_ALGO)
00888       {
00889          //DSA with SHA-256 is supported
00890          supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_DSA;
00891          supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA256;
00892       }
00893 #endif
00894 #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED)
00895       //ECDSA with SHA-1 is always supported
00896       supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_ECDSA;
00897       supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA1;
00898 
00899       //The hash algorithm used for PRF operations can also be used for signing
00900       if(context->prfHashAlgo == SHA256_HASH_ALGO)
00901       {
00902          //ECDSA with SHA-256 is supported
00903          supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_ECDSA;
00904          supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA256;
00905       }
00906 #if (TLS_SHA384_SUPPORT == ENABLED)
00907       else if(context->prfHashAlgo == SHA384_HASH_ALGO)
00908       {
00909          //ECDSA with SHA-384 is supported
00910          supportedSignAlgos->value[n].signature = TLS_SIGN_ALGO_ECDSA;
00911          supportedSignAlgos->value[n++].hash = TLS_HASH_ALGO_SHA384;
00912       }
00913 #endif
00914 #endif
00915       //Fix the length of the list
00916       supportedSignAlgos->length = htons(n * sizeof(TlsSignHashAlgo));
00917       //Total length of the message
00918       *length += sizeof(TlsSignHashAlgos) + n * sizeof(TlsSignHashAlgo);
00919    }
00920 #endif
00921 
00922    //Point to the list of the distinguished names of acceptable
00923    //certificate authorities
00924    certAuthorities = PTR_OFFSET(message, *length);
00925    //Total length of the message
00926    *length += sizeof(TlsCertAuthorities);
00927 
00928    //Point to the first certificate authority
00929    p = certAuthorities->value;
00930    //Length of the list in bytes
00931    n = 0;
00932 
00933    //Point to the first trusted CA certificate
00934    pemCert = context->trustedCaList;
00935    //Get the total length, in bytes, of the trusted CA list
00936    pemCertLength = context->trustedCaListLen;
00937 
00938    //DER encoded certificate
00939    derCert = NULL;
00940    derCertSize = 0;
00941    derCertLength = 0;
00942 
00943    //Allocate a memory buffer to store X.509 certificate info
00944    certInfo = tlsAllocMem(sizeof(X509CertificateInfo));
00945 
00946    //Successful memory allocation?
00947    if(certInfo != NULL)
00948    {
00949       //Loop through the list of trusted CA certificates
00950       while(pemCertLength > 0)
00951       {
00952          //Decode PEM certificate
00953          error = pemReadCertificate(&pemCert, &pemCertLength,
00954             &derCert, &derCertSize, &derCertLength);
00955 
00956          //Any error to report?
00957          if(error)
00958          {
00959             //End of file detected
00960             error = NO_ERROR;
00961             break;
00962          }
00963 
00964          //Parse X.509 certificate
00965          error = x509ParseCertificate(derCert, derCertLength, certInfo);
00966          //Failed to parse the X.509 certificate?
00967          if(error)
00968             break;
00969 
00970          //Total length of the message
00971          *length += certInfo->subject.rawDataLen + 2;
00972 
00973          //Prevent the buffer from overflowing
00974          if(*length > context->txRecordMaxLen)
00975          {
00976             //Report an error
00977             error = ERROR_MESSAGE_TOO_LONG;
00978             break;
00979          }
00980 
00981          //Each distinguished name is preceded by a 2-byte length field
00982          STORE16BE(certInfo->subject.rawDataLen, p);
00983          //The distinguished name shall be DER encoded
00984          memcpy(p + 2, certInfo->subject.rawData, certInfo->subject.rawDataLen);
00985 
00986          //Advance data pointer
00987          p += certInfo->subject.rawDataLen + 2;
00988          //Adjust the length of the list
00989          n += certInfo->subject.rawDataLen + 2;
00990       }
00991 
00992       //Free previously allocated memory
00993       tlsFreeMem(derCert);
00994       tlsFreeMem(certInfo);
00995 
00996       //Fix the length of the list
00997       certAuthorities->length = htons(n);
00998 
00999       //Fix the length field
01000       STORE24BE(*length - sizeof(TlsHandshake), message->length);
01001    }
01002    else
01003    {
01004       //Report an error
01005       error = ERROR_OUT_OF_MEMORY;
01006    }
01007 
01008    //Return status code
01009    return error;
01010 }
01011 
01012 
01013 /**
01014  * @brief Format ServerHelloDone message
01015  * @param[in] context Pointer to the TLS context
01016  * @param[out] message Buffer where to format the ServerHelloDone message
01017  * @param[out] length Length of the resulting ServerHelloDone message
01018  * @return Error code
01019  **/
01020 
01021 error_t tlsFormatServerHelloDone(TlsContext *context,
01022    TlsServerHelloDone *message, size_t *length)
01023 {
01024    //Handshake message type
01025    message->msgType = TLS_TYPE_SERVER_HELLO_DONE;
01026 
01027    //The ServerHelloDone message does not contain any data
01028    STORE24BE(0, message->length);
01029 
01030    //Length of the complete handshake message
01031    *length = sizeof(TlsHandshake);
01032 
01033    //Successful processing
01034    return NO_ERROR;
01035 }
01036 
01037 
01038 /**
01039  * @brief Parse ClientHello message
01040  *
01041  * When a client first connects to a server, it is required to send
01042  * the ClientHello as its first message. The client can also send a
01043  * ClientHello in response to a HelloRequest or on its own initiative
01044  * in order to renegotiate the security parameters in an existing
01045  * connection
01046  *
01047  * @param[in] context Pointer to the TLS context
01048  * @param[in] message Incoming ClientHello message to parse
01049  * @param[in] length Message length
01050  * @return Error code
01051  **/
01052 
01053 error_t tlsParseClientHello(TlsContext *context, const TlsClientHello *message, size_t length)
01054 {
01055    error_t error;
01056    size_t i;
01057    size_t j;
01058    size_t k;
01059    size_t n;
01060    bool_t acceptable;
01061    uint8_t certType;
01062    const uint8_t *p;
01063    const TlsCipherSuites *cipherSuites;
01064    const TlsCompressionMethods *compressionMethods;
01065    const TlsExtension *extension;
01066    const TlsSignHashAlgos *supportedSignAlgos;
01067    const TlsEllipticCurveList *curveList;
01068 
01069    //Debug message
01070    TRACE_INFO("ClientHello message received (%" PRIuSIZE " bytes)...\r\n", length);
01071    TRACE_DEBUG_ARRAY("  ", message, length);
01072 
01073    //Check the length of the ClientHello message
01074    if(length < sizeof(TlsClientHello))
01075       return ERROR_DECODING_FAILED;
01076 
01077    //Check current state
01078    if(context->state != TLS_STATE_CLIENT_HELLO)
01079       return ERROR_UNEXPECTED_MESSAGE;
01080 
01081    //Point to the session ID
01082    p = (uint8_t *) message + sizeof(TlsClientHello);
01083    //Remaining bytes to process
01084    n = length - sizeof(TlsClientHello);
01085 
01086    //Check the length of the session ID
01087    if(message->sessionIdLength > n)
01088       return ERROR_DECODING_FAILED;
01089    if(message->sessionIdLength > 32)
01090       return ERROR_ILLEGAL_PARAMETER;
01091 
01092    //Debug message
01093    TRACE_INFO("Session ID (%" PRIu8 " bytes):\r\n", message->sessionIdLength);
01094    TRACE_INFO_ARRAY("  ", message->sessionId, message->sessionIdLength);
01095 
01096    //Point to the next field
01097    p += message->sessionIdLength;
01098    //Remaining bytes to process
01099    n -= message->sessionIdLength;
01100 
01101    //Malformed ClientHello message?
01102    if(n < sizeof(TlsCipherSuites))
01103       return ERROR_DECODING_FAILED;
01104 
01105    //List of cryptographic algorithms supported by the client
01106    cipherSuites = (TlsCipherSuites *) p;
01107    //Remaining bytes to process
01108    n -= sizeof(TlsCipherSuites);
01109 
01110    //Check the length of the list
01111    if(ntohs(cipherSuites->length) < 2)
01112       return ERROR_ILLEGAL_PARAMETER;
01113    if(ntohs(cipherSuites->length) > n)
01114       return ERROR_DECODING_FAILED;
01115 
01116    //Get the number of cipher suite identifiers present in the list
01117    k = ntohs(cipherSuites->length) / 2;
01118 
01119    //Debug message
01120    TRACE_DEBUG("Cipher suites:\r\n");
01121 
01122    //Dump the list of cipher suites
01123    for(i = 0; i < k; i++)
01124    {
01125       //Debug message
01126       TRACE_DEBUG("  0x%04" PRIX16 " (%s)\r\n", ntohs(cipherSuites->value[i]),
01127          tlsGetCipherSuiteName(ntohs(cipherSuites->value[i])));
01128    }
01129 
01130    //Point to the next field
01131    p += sizeof(TlsCipherSuites) + ntohs(cipherSuites->length);
01132    //Remaining bytes to process
01133    n -= ntohs(cipherSuites->length);
01134 
01135    //Malformed ClientHello message?
01136    if(n < sizeof(TlsCompressionMethods))
01137       return ERROR_DECODING_FAILED;
01138 
01139    //List of compression algorithms supported by the client
01140    compressionMethods = (TlsCompressionMethods *) p;
01141    //Remaining bytes to process
01142    n -= sizeof(TlsCompressionMethods);
01143 
01144    //Check the length of the list
01145    if(compressionMethods->length < 1)
01146       return ERROR_ILLEGAL_PARAMETER;
01147    if(compressionMethods->length > n)
01148       return ERROR_DECODING_FAILED;
01149 
01150    //Point to the next field
01151    p += sizeof(TlsCompressionMethods) + compressionMethods->length;
01152    //Remaining bytes to process
01153    n -= compressionMethods->length;
01154 
01155    //Parse the list of extensions offered by the client
01156    extension = tlsGetExtension(p, n, TLS_EXT_ELLIPTIC_CURVES);
01157 
01158    //The EllipticCurves extension was found?
01159    if(extension)
01160    {
01161       //This extension allows a client to enumerate the elliptic curves it supports
01162       curveList = (TlsEllipticCurveList *) extension->value;
01163 
01164       //Check the length of the list
01165       if(ntohs(extension->length) < sizeof(TlsEllipticCurveList))
01166          return ERROR_DECODING_FAILED;
01167       if(ntohs(extension->length) < (sizeof(TlsEllipticCurveList) + ntohs(curveList->length)))
01168          return ERROR_DECODING_FAILED;
01169    }
01170    else
01171    {
01172       //The client may omit the SignatureAlgorithms extension
01173       curveList = NULL;
01174    }
01175 
01176    //Parse the list of extensions offered by the client
01177    extension = tlsGetExtension(p, n, TLS_EXT_EC_POINT_FORMATS);
01178 
01179    //The EcPointFormats extension was found?
01180    if(extension)
01181       context->ecPointFormatExtFound = TRUE;
01182    else
01183       context->ecPointFormatExtFound = FALSE;
01184 
01185    //Parse the list of extensions offered by the client
01186    extension = tlsGetExtension(p, n, TLS_EXT_SIGNATURE_ALGORITHMS);
01187 
01188    //The SignatureAlgorithms extension was found?
01189    if(extension)
01190    {
01191       //Point to the list of supported hash/signature algorithm pairs
01192       supportedSignAlgos = (TlsSignHashAlgos *) extension->value;
01193 
01194       //Check the length of the list
01195       if(ntohs(extension->length) < sizeof(TlsSignHashAlgos))
01196          return ERROR_DECODING_FAILED;
01197       if(ntohs(extension->length) < (sizeof(TlsSignHashAlgos) + ntohs(supportedSignAlgos->length)))
01198          return ERROR_DECODING_FAILED;
01199    }
01200    else
01201    {
01202       //The client may omit the SignatureAlgorithms extension
01203       supportedSignAlgos = NULL;
01204    }
01205 
01206    //Get the version the client wishes to use during this session
01207    context->clientVersion = ntohs(message->clientVersion);
01208 
01209    //If a TLS server receives a ClientHello containing a version number
01210    //greater than the highest version supported by the server, it must
01211    //reply according to the highest version supported by the server
01212    error = tlsSetVersion(context, MIN(context->clientVersion, TLS_MAX_VERSION));
01213    //The specified TLS version is not supported?
01214    if(error)
01215       return error;
01216 
01217    //Save client random value
01218    context->clientRandom = message->random;
01219 
01220 #if (TLS_SESSION_RESUME_SUPPORT == ENABLED)
01221    //Check whether session caching is supported
01222    if(context->cache != NULL)
01223    {
01224       //If the session ID was non-empty, the server will look in
01225       //its session cache for a match
01226       TlsSession *session = tlsFindCache(context->cache,
01227          message->sessionId, message->sessionIdLength);
01228 
01229       //Check whether a matching entry has been found in the cache
01230       if(session != NULL)
01231       {
01232          //Restore session parameters
01233          tlsRestoreSession(context, session);
01234 
01235          //Select the relevant cipher suite
01236          error = tlsSetCipherSuite(context, session->cipherSuite);
01237          //Any error to report?
01238          if(error)
01239             return error;
01240 
01241          //Perform abbreviated handshake
01242          context->resume = TRUE;
01243       }
01244       else
01245       {
01246          //Generate a new random ID
01247          error = context->prngAlgo->read(context->prngContext, context->sessionId, 32);
01248          //Any error to report?
01249          if(error)
01250             return error;
01251 
01252          //Session ID is limited to 32 bytes
01253          context->sessionIdLen = 32;
01254          //Perform a full handshake
01255          context->resume = FALSE;
01256       }
01257    }
01258    else
01259 #endif
01260    {
01261       //This session cannot be resumed
01262       context->sessionIdLen = 0;
01263       //Perform a full handshake
01264       context->resume = FALSE;
01265    }
01266 
01267    //Full handshake?
01268    if(!context->resume)
01269    {
01270       //Get the size of the cipher suite list
01271       k = ntohs(cipherSuites->length) / 2;
01272 
01273       //The cipher suite list contains the combinations of cryptographic algorithms
01274       //supported by the client in order of the client's preference
01275       for(i = 0; i < k; i++)
01276       {
01277          //Check whether the current cipher suite is supported
01278          error = tlsSetCipherSuite(context, ntohs(cipherSuites->value[i]));
01279 
01280          //Successful processing?
01281          if(!error)
01282          {
01283             //ECC cipher suite?
01284             if(context->keyExchMethod == TLS_KEY_EXCH_ECDH_ANON ||
01285                context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
01286                context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA ||
01287                context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
01288             {
01289                //One of the proposed ECC cipher suites must be negotiated only
01290                //if the server can successfully complete the handshake while
01291                //using the curves and point formats supported by the client
01292                error = tlsSelectNamedCurve(context, curveList);
01293             }
01294          }
01295 
01296          //Successful processing?
01297          if(!error)
01298          {
01299             //The server requires a valid certificate whenever the agreed-upon
01300             //key exchange method uses certificates for authentication
01301             if(context->keyExchMethod == TLS_KEY_EXCH_RSA ||
01302                context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
01303                context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
01304                context->keyExchMethod == TLS_KEY_EXCH_RSA_PSK)
01305             {
01306                //RSA, DHE_RSA, ECDHE_RSA and RAS_PSK key exchange methods
01307                //require a RSA certificate
01308                certType = TLS_CERT_RSA_SIGN;
01309             }
01310             else if(context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS)
01311             {
01312                //DHE_DSS key exchange method requires a DSA certificate
01313                certType = TLS_CERT_DSS_SIGN;
01314             }
01315             else if(context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA)
01316             {
01317                //ECDHE_ECDSA key exchange method requires an ECDSA certificate
01318                certType = TLS_CERT_ECDSA_SIGN;
01319             }
01320             else
01321             {
01322                //DH_anon and ECDH_anon key exchange methods do not require any certificate
01323                certType = TLS_CERT_NONE;
01324             }
01325 
01326             //Check whether a certificate is required
01327             if(certType != TLS_CERT_NONE)
01328             {
01329                //Do not accept the specified cipher suite unless a suitable
01330                //certificate has been previously loaded by the user
01331                error = ERROR_NO_CERTIFICATE;
01332 
01333                //Loop through the list of available certificates
01334                for(j = 0; j < context->numCerts; j++)
01335                {
01336                   //Check whether the current certificate is acceptable
01337                   acceptable = tlsIsCertificateAcceptable(&context->certs[j],
01338                      &certType, 1, supportedSignAlgos, curveList, NULL);
01339 
01340                   //Is the certificate suitable for the selected cipher suite?
01341                   if(acceptable)
01342                   {
01343                      //The hash algorithm to be used when generating signatures must be
01344                      //one of those present in the SignatureAlgorithms extension
01345                      error = tlsSelectSignHashAlgo(context,
01346                         context->certs[j].signAlgo, supportedSignAlgos);
01347 
01348                      //If all the requirements were met, the certificate can be
01349                      //used in conjunction with the selected cipher suite
01350                      if(!error)
01351                      {
01352                         context->cert = &context->certs[j];
01353                         break;
01354                      }
01355                   }
01356                }
01357             }
01358          }
01359 
01360          //If the list contains cipher suites the server does not recognize,
01361          //support, or wish to use, the server must ignore those cipher
01362          //suites, and process the remaining ones as usual
01363          if(!error)
01364             break;
01365       }
01366 
01367       //If no acceptable choices are presented, return a handshake failure
01368       //alert and close the connection
01369       if(error)
01370          return ERROR_HANDSHAKE_FAILED;
01371 
01372       //The list of the compression methods supported by the client
01373       //is sorted by client preference
01374       for(i = 0; i < compressionMethods->length; i++)
01375       {
01376          //Check whether the algorithm to be used for data compression is supported
01377          error = tlsSetCompressionMethod(context, compressionMethods->value[i]);
01378 
01379          //If the compression method is not supported, process the remaining ones
01380          if(!error)
01381             break;
01382       }
01383 
01384       //If no compression algorithm is acceptable, return a handshake failure
01385       //alert and close the connection
01386       if(error)
01387          return ERROR_HANDSHAKE_FAILED;
01388    }
01389 
01390    //Initialize handshake message hashing
01391    error = tlsInitHandshakeHash(context);
01392    //Any error to report?
01393    if(error)
01394       return error;
01395 
01396    //Update the hash value with the incoming handshake message
01397    tlsUpdateHandshakeHash(context, message, length);
01398 
01399    //Prepare to send ServerHello message...
01400    context->state = TLS_STATE_SERVER_HELLO;
01401    //Successful processing
01402    return NO_ERROR;
01403 }
01404 
01405 
01406 /**
01407  * @brief Parse ClientKeyExchange message
01408  *
01409  * This message is always sent by the client. It must immediately
01410  * follow the client Certificate message, if it is sent. Otherwise,
01411  * it must be the first message sent by the client after it receives
01412  * the ServerHelloDone message
01413  *
01414  * @param[in] context Pointer to the TLS context
01415  * @param[in] message Incoming ClientKeyExchange message to parse
01416  * @param[in] length Message length
01417  * @return Error code
01418  **/
01419 
01420 error_t tlsParseClientKeyExchange(TlsContext *context, const TlsClientKeyExchange *message, size_t length)
01421 {
01422    error_t error;
01423    size_t n;
01424    const uint8_t *p;
01425 
01426    //Debug message
01427    TRACE_INFO("ClientKeyExchange message received (%" PRIuSIZE " bytes)...\r\n", length);
01428    TRACE_DEBUG_ARRAY("  ", message, length);
01429 
01430    //Check the length of the ClientKeyExchange message
01431    if(length < sizeof(TlsClientKeyExchange))
01432       return ERROR_DECODING_FAILED;
01433 
01434    //Check current state
01435    if(context->state == TLS_STATE_CLIENT_CERTIFICATE)
01436    {
01437       //A an non-anonymous server can optionally request a certificate from the client
01438       if(context->keyExchMethod == TLS_KEY_EXCH_RSA ||
01439          context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
01440          context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS ||
01441          context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
01442          context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA ||
01443          context->keyExchMethod == TLS_KEY_EXCH_RSA_PSK)
01444       {
01445          //If client authentication is required by the server for the handshake
01446          //to continue, it may respond with a fatal handshake failure alert
01447          if(context->clientAuthMode == TLS_CLIENT_AUTH_REQUIRED)
01448             return ERROR_HANDSHAKE_FAILED;
01449       }
01450    }
01451    else if(context->state != TLS_STATE_CLIENT_KEY_EXCHANGE)
01452    {
01453       //Send a fatal alert to the client
01454       return ERROR_UNEXPECTED_MESSAGE;
01455    }
01456 
01457    //Update the hash value with the incoming handshake message
01458    tlsUpdateHandshakeHash(context, message, length);
01459 
01460    //Point to the body of the handshake message
01461    p = message->data;
01462    //Remaining bytes to process
01463    length -= sizeof(TlsClientKeyExchange);
01464 
01465    //PSK key exchange method?
01466    if(context->keyExchMethod == TLS_KEY_EXCH_PSK ||
01467       context->keyExchMethod == TLS_KEY_EXCH_RSA_PSK ||
01468       context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK ||
01469       context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
01470    {
01471       //The PSK identity is sent in cleartext
01472       error = tlsParsePskIdentity(context, p, length, &n);
01473       //Any error to report?
01474       if(error)
01475          return error;
01476 
01477       //Point to the next field
01478       p += n;
01479       //Remaining bytes to process
01480       length -= n;
01481    }
01482 
01483    //RSA, Diffie-Hellman or ECDH key exchange method?
01484    if(context->keyExchMethod != TLS_KEY_EXCH_PSK)
01485    {
01486       //Parse client's key exchange parameters
01487       error = tlsParseClientKeyParams(context, p, length, &n);
01488       //Any error to report?
01489       if(error)
01490          return error;
01491 
01492       //Point to the next field
01493       p += n;
01494       //Remaining bytes to process
01495       length -= n;
01496    }
01497 
01498    //If the amount of data in the message does not precisely match the format
01499    //of the ClientKeyExchange message, then send a fatal alert
01500    if(length != 0)
01501       return ERROR_DECODING_FAILED;
01502 
01503    //PSK key exchange method?
01504    if(context->keyExchMethod == TLS_KEY_EXCH_PSK ||
01505       context->keyExchMethod == TLS_KEY_EXCH_RSA_PSK ||
01506       context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK ||
01507       context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
01508    {
01509       //Generate premaster secret
01510       error = tlsGeneratePskPremasterSecret(context);
01511       //Any error to report?
01512       if(error)
01513          return error;
01514    }
01515 
01516    //Derive session keys from the premaster secret
01517    error = tlsGenerateKeys(context);
01518    //Unable to generate key material?
01519    if(error)
01520       return error;
01521 
01522    //Update FSM state
01523    if(context->peerCertType != TLS_CERT_NONE)
01524       context->state = TLS_STATE_CERTIFICATE_VERIFY;
01525    else
01526       context->state = TLS_STATE_CLIENT_CHANGE_CIPHER_SPEC;
01527 
01528    //Successful processing
01529    return NO_ERROR;
01530 }
01531 
01532 
01533 /**
01534  * @brief Parse CertificateVerify message
01535  *
01536  * The CertificateVerify message is used to provide explicit verification
01537  * of a client certificate. This message is only sent following a client
01538  * certificate that has signing capability
01539  *
01540  * @param[in] context Pointer to the TLS context
01541  * @param[in] message Incoming CertificateVerify message to parse
01542  * @param[in] length Message length
01543  * @return Error code
01544  **/
01545 
01546 error_t tlsParseCertificateVerify(TlsContext *context, const TlsCertificateVerify *message, size_t length)
01547 {
01548    error_t error;
01549    size_t n;
01550 
01551    //Debug message
01552    TRACE_INFO("CertificateVerify message received (%" PRIuSIZE " bytes)...\r\n", length);
01553    TRACE_DEBUG_ARRAY("  ", message, length);
01554 
01555    //Check the length of the CertificateVerify message
01556    if(length < sizeof(TlsCertificateVerify))
01557       return ERROR_DECODING_FAILED;
01558 
01559    //Check current state
01560    if(context->state != TLS_STATE_CERTIFICATE_VERIFY)
01561       return ERROR_UNEXPECTED_MESSAGE;
01562 
01563    //Remaining bytes to process
01564    n = length - sizeof(TlsCertificateVerify);
01565 
01566 #if (TLS_MAX_VERSION >= SSL_VERSION_3_0 && TLS_MIN_VERSION <= TLS_VERSION_1_1)
01567    //SSL 3.0, TLS 1.0 or TLS 1.1 currently selected?
01568    if(context->version <= TLS_VERSION_1_1)
01569    {
01570       //Point to the digitally-signed element
01571       TlsDigitalSignature *signature = (TlsDigitalSignature *) message->signature;
01572 
01573       //Check the length of the digitally-signed element
01574       if(n < sizeof(TlsDigitalSignature))
01575          return ERROR_DECODING_FAILED;
01576       if(n < (sizeof(TlsDigitalSignature) + ntohs(signature->length)))
01577          return ERROR_DECODING_FAILED;
01578 
01579 #if (TLS_RSA_SIGN_SUPPORT == ENABLED)
01580       //The client's certificate contains a valid RSA public key?
01581       if(context->peerCertType == TLS_CERT_RSA_SIGN)
01582       {
01583          //Digest all the handshake messages starting at ClientHello (using MD5)
01584          error = tlsFinalizeHandshakeHash(context, MD5_HASH_ALGO,
01585             context->handshakeMd5Context, "", context->verifyData);
01586          //Any error to report?
01587          if(error)
01588             return error;
01589 
01590          //Digest all the handshake messages starting at ClientHello (using SHA-1)
01591          error = tlsFinalizeHandshakeHash(context, SHA1_HASH_ALGO,
01592             context->handshakeSha1Context, "", context->verifyData + MD5_DIGEST_SIZE);
01593          //Any error to report?
01594          if(error)
01595             return error;
01596 
01597          //Verify RSA signature using client's public key
01598          error = tlsVerifyRsaSignature(&context->peerRsaPublicKey,
01599             context->verifyData, signature->value, ntohs(signature->length));
01600       }
01601       else
01602 #endif
01603 #if (TLS_DSA_SIGN_SUPPORT == ENABLED)
01604       //The client's certificate contains a valid DSA public key?
01605       if(context->peerCertType == TLS_CERT_DSS_SIGN)
01606       {
01607          //Digest all the handshake messages starting at ClientHello
01608          error = tlsFinalizeHandshakeHash(context, SHA1_HASH_ALGO,
01609             context->handshakeSha1Context, "", context->verifyData);
01610          //Any error to report?
01611          if(error)
01612             return error;
01613 
01614          //Verify DSA signature using client's public key
01615          error = tlsVerifyDsaSignature(&context->peerDsaPublicKey, context->verifyData,
01616             SHA1_DIGEST_SIZE, signature->value, ntohs(signature->length));
01617       }
01618       else
01619 #endif
01620 #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED)
01621       //The client's certificate contains a valid ECDSA public key?
01622       if(context->peerCertType == TLS_CERT_ECDSA_SIGN)
01623       {
01624          //Digest all the handshake messages starting at ClientHello
01625          error = tlsFinalizeHandshakeHash(context, SHA1_HASH_ALGO,
01626             context->handshakeSha1Context, "", context->verifyData);
01627          //Any error to report?
01628          if(error)
01629             return error;
01630 
01631          //Verify ECDSA signature using client's public key
01632          error = tlsVerifyEcdsaSignature(&context->peerEcParams, &context->peerEcPublicKey,
01633             context->verifyData, SHA1_DIGEST_SIZE, signature->value, ntohs(signature->length));
01634       }
01635       else
01636 #endif
01637       //Invalid signature algorithm?
01638       {
01639          //Report an error
01640          error = ERROR_UNSUPPORTED_SIGNATURE_ALGO;
01641       }
01642    }
01643    else
01644 #endif
01645 #if (TLS_MAX_VERSION >= TLS_VERSION_1_2 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
01646    //TLS 1.2 currently selected?
01647    if(context->version == TLS_VERSION_1_2)
01648    {
01649       const HashAlgo *hashAlgo;
01650 
01651       //Point to the digitally-signed element
01652       TlsDigitalSignature2 *signature = (TlsDigitalSignature2 *) message->signature;
01653 
01654       //Check the length of the digitally-signed element
01655       if(n < sizeof(TlsDigitalSignature2))
01656          return ERROR_DECODING_FAILED;
01657       if(n < (sizeof(TlsDigitalSignature2) + ntohs(signature->length)))
01658          return ERROR_DECODING_FAILED;
01659 
01660       //Retrieve the hash algorithm used for signing
01661       hashAlgo = tlsGetHashAlgo(signature->algorithm.hash);
01662 
01663       //Digest all the handshake messages starting at ClientHello
01664       if(hashAlgo == SHA1_HASH_ALGO)
01665       {
01666          //Use SHA-1 hash algorithm
01667          error = tlsFinalizeHandshakeHash(context, SHA1_HASH_ALGO,
01668             context->handshakeSha1Context, "", context->verifyData);
01669       }
01670       else if(hashAlgo == context->prfHashAlgo)
01671       {
01672          //Use PRF hash algorithm (SHA-256 or SHA-384)
01673          error = tlsFinalizeHandshakeHash(context, hashAlgo,
01674             context->handshakeHashContext, "", context->verifyData);
01675       }
01676       else
01677       {
01678          //The specified hash algorithm is not supported
01679          error = ERROR_UNSUPPORTED_SIGNATURE_ALGO;
01680       }
01681 
01682       //Any error to report?
01683       if(error)
01684          return error;
01685 
01686 #if (TLS_RSA_SIGN_SUPPORT == ENABLED)
01687       //The client's certificate contains a valid RSA public key?
01688       if(signature->algorithm.signature == TLS_SIGN_ALGO_RSA)
01689       {
01690          //Use the signature verification algorithm defined in PKCS #1 v1.5
01691          error = rsassaPkcs1v15Verify(&context->peerRsaPublicKey, hashAlgo,
01692             context->verifyData, signature->value, ntohs(signature->length));
01693       }
01694       else
01695 #endif
01696 #if (TLS_DSA_SIGN_SUPPORT == ENABLED)
01697       //The client's certificate contains a valid DSA public key?
01698       if(signature->algorithm.signature == TLS_SIGN_ALGO_DSA)
01699       {
01700          //Verify DSA signature using client's public key
01701          error = tlsVerifyDsaSignature(&context->peerDsaPublicKey, context->verifyData,
01702             hashAlgo->digestSize, signature->value, ntohs(signature->length));
01703       }
01704       else
01705 #endif
01706 #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED)
01707       //The client's certificate contains a valid ECDSA public key?
01708       if(signature->algorithm.signature == TLS_SIGN_ALGO_ECDSA)
01709       {
01710          //Verify ECDSA signature using client's public key
01711          error = tlsVerifyEcdsaSignature(&context->peerEcParams, &context->peerEcPublicKey,
01712             context->verifyData, hashAlgo->digestSize, signature->value, ntohs(signature->length));
01713       }
01714       else
01715 #endif
01716       //Invalid signature algorithm?
01717       {
01718          //Report an error
01719          error = ERROR_UNSUPPORTED_SIGNATURE_ALGO;
01720       }
01721    }
01722    else
01723 #endif
01724    {
01725       //The negotiated TLS version is not valid
01726       error = ERROR_INVALID_VERSION;
01727    }
01728 
01729    //Update the hash value with the incoming handshake message
01730    tlsUpdateHandshakeHash(context, message, length);
01731 
01732    //Prepare to receive a ChangeCipherSpec message...
01733    context->state = TLS_STATE_CLIENT_CHANGE_CIPHER_SPEC;
01734    //Return status code
01735    return error;
01736 }
01737 
01738 #endif
01739