ssl3ext.c revision 5821806d5e7f356e8fa4b058a389a808ea183019
1/* 2 * SSL3 Protocol 3 * 4 * ***** BEGIN LICENSE BLOCK ***** 5 * Version: MPL 1.1/GPL 2.0/LGPL 2.1 6 * 7 * The contents of this file are subject to the Mozilla Public License Version 8 * 1.1 (the "License"); you may not use this file except in compliance with 9 * the License. You may obtain a copy of the License at 10 * http://www.mozilla.org/MPL/ 11 * 12 * Software distributed under the License is distributed on an "AS IS" basis, 13 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License 14 * for the specific language governing rights and limitations under the 15 * License. 16 * 17 * The Original Code is the Netscape security libraries. 18 * 19 * The Initial Developer of the Original Code is 20 * Netscape Communications Corporation. 21 * Portions created by the Initial Developer are Copyright (C) 1994-2000 22 * the Initial Developer. All Rights Reserved. 23 * 24 * Contributor(s): 25 * Dr Vipul Gupta <vipul.gupta@sun.com> and 26 * Douglas Stebila <douglas@stebila.ca>, Sun Microsystems Laboratories 27 * Nagendra Modadugu <ngm@google.com>, Google Inc. 28 * 29 * Alternatively, the contents of this file may be used under the terms of 30 * either the GNU General Public License Version 2 or later (the "GPL"), or 31 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), 32 * in which case the provisions of the GPL or the LGPL are applicable instead 33 * of those above. If you wish to allow use of your version of this file only 34 * under the terms of either the GPL or the LGPL, and not to allow others to 35 * use your version of this file under the terms of the MPL, indicate your 36 * decision by deleting the provisions above and replace them with the notice 37 * and other provisions required by the GPL or the LGPL. If you do not delete 38 * the provisions above, a recipient may use your version of this file under 39 * the terms of any one of the MPL, the GPL or the LGPL. 40 * 41 * ***** END LICENSE BLOCK ***** */ 42 43/* TLS extension code moved here from ssl3ecc.c */ 44/* $Id: ssl3ext.c,v 1.22 2012/03/12 19:14:12 wtc%google.com Exp $ */ 45 46#include "nssrenam.h" 47#include "nss.h" 48#include "ssl.h" 49#include "sslimpl.h" 50#include "sslproto.h" 51#include "pk11pub.h" 52#include "blapi.h" 53#include "prinit.h" 54 55static unsigned char key_name[SESS_TICKET_KEY_NAME_LEN]; 56static PK11SymKey *session_ticket_enc_key_pkcs11 = NULL; 57static PK11SymKey *session_ticket_mac_key_pkcs11 = NULL; 58 59static unsigned char session_ticket_enc_key[AES_256_KEY_LENGTH]; 60static unsigned char session_ticket_mac_key[SHA256_LENGTH]; 61 62static PRBool session_ticket_keys_initialized = PR_FALSE; 63static PRCallOnceType generate_session_keys_once; 64 65/* forward static function declarations */ 66static SECStatus ssl3_ParseEncryptedSessionTicket(sslSocket *ss, 67 SECItem *data, EncryptedSessionTicket *enc_session_ticket); 68static SECStatus ssl3_AppendToItem(SECItem *item, const unsigned char *buf, 69 PRUint32 bytes); 70static SECStatus ssl3_AppendNumberToItem(SECItem *item, PRUint32 num, 71 PRInt32 lenSize); 72static SECStatus ssl3_GetSessionTicketKeysPKCS11(sslSocket *ss, 73 PK11SymKey **aes_key, PK11SymKey **mac_key); 74static SECStatus ssl3_GetSessionTicketKeys(const unsigned char **aes_key, 75 PRUint32 *aes_key_length, const unsigned char **mac_key, 76 PRUint32 *mac_key_length); 77static PRInt32 ssl3_SendRenegotiationInfoXtn(sslSocket * ss, 78 PRBool append, PRUint32 maxBytes); 79static SECStatus ssl3_HandleRenegotiationInfoXtn(sslSocket *ss, 80 PRUint16 ex_type, SECItem *data); 81static SECStatus ssl3_ClientHandleNextProtoNegoXtn(sslSocket *ss, 82 PRUint16 ex_type, SECItem *data); 83static SECStatus ssl3_ClientHandleChannelIDXtn(sslSocket *ss, 84 PRUint16 ex_type, SECItem *data); 85static SECStatus ssl3_ServerHandleNextProtoNegoXtn(sslSocket *ss, 86 PRUint16 ex_type, SECItem *data); 87static PRInt32 ssl3_ClientSendNextProtoNegoXtn(sslSocket *ss, PRBool append, 88 PRUint32 maxBytes); 89static PRInt32 ssl3_ClientSendChannelIDXtn(sslSocket *ss, PRBool append, 90 PRUint32 maxBytes); 91static PRInt32 ssl3_SendUseSRTPXtn(sslSocket *ss, PRBool append, 92 PRUint32 maxBytes); 93static SECStatus ssl3_HandleUseSRTPXtn(sslSocket * ss, PRUint16 ex_type, 94 SECItem *data); 95 96/* 97 * Write bytes. Using this function means the SECItem structure 98 * cannot be freed. The caller is expected to call this function 99 * on a shallow copy of the structure. 100 */ 101static SECStatus 102ssl3_AppendToItem(SECItem *item, const unsigned char *buf, PRUint32 bytes) 103{ 104 if (bytes > item->len) 105 return SECFailure; 106 107 PORT_Memcpy(item->data, buf, bytes); 108 item->data += bytes; 109 item->len -= bytes; 110 return SECSuccess; 111} 112 113/* 114 * Write a number in network byte order. Using this function means the 115 * SECItem structure cannot be freed. The caller is expected to call 116 * this function on a shallow copy of the structure. 117 */ 118static SECStatus 119ssl3_AppendNumberToItem(SECItem *item, PRUint32 num, PRInt32 lenSize) 120{ 121 SECStatus rv; 122 uint8 b[4]; 123 uint8 * p = b; 124 125 switch (lenSize) { 126 case 4: 127 *p++ = (uint8) (num >> 24); 128 case 3: 129 *p++ = (uint8) (num >> 16); 130 case 2: 131 *p++ = (uint8) (num >> 8); 132 case 1: 133 *p = (uint8) num; 134 } 135 rv = ssl3_AppendToItem(item, &b[0], lenSize); 136 return rv; 137} 138 139static SECStatus ssl3_SessionTicketShutdown(void* appData, void* nssData) 140{ 141 if (session_ticket_enc_key_pkcs11) { 142 PK11_FreeSymKey(session_ticket_enc_key_pkcs11); 143 session_ticket_enc_key_pkcs11 = NULL; 144 } 145 if (session_ticket_mac_key_pkcs11) { 146 PK11_FreeSymKey(session_ticket_mac_key_pkcs11); 147 session_ticket_mac_key_pkcs11 = NULL; 148 } 149 PORT_Memset(&generate_session_keys_once, 0, 150 sizeof(generate_session_keys_once)); 151 return SECSuccess; 152} 153 154 155static PRStatus 156ssl3_GenerateSessionTicketKeysPKCS11(void *data) 157{ 158 SECStatus rv; 159 sslSocket *ss = (sslSocket *)data; 160 SECKEYPrivateKey *svrPrivKey = ss->serverCerts[kt_rsa].SERVERKEY; 161 SECKEYPublicKey *svrPubKey = ss->serverCerts[kt_rsa].serverKeyPair->pubKey; 162 163 if (svrPrivKey == NULL || svrPubKey == NULL) { 164 SSL_DBG(("%d: SSL[%d]: Pub or priv key(s) is NULL.", 165 SSL_GETPID(), ss->fd)); 166 goto loser; 167 } 168 169 /* Get a copy of the session keys from shared memory. */ 170 PORT_Memcpy(key_name, SESS_TICKET_KEY_NAME_PREFIX, 171 sizeof(SESS_TICKET_KEY_NAME_PREFIX)); 172 if (!ssl_GetSessionTicketKeysPKCS11(svrPrivKey, svrPubKey, 173 ss->pkcs11PinArg, &key_name[SESS_TICKET_KEY_NAME_PREFIX_LEN], 174 &session_ticket_enc_key_pkcs11, &session_ticket_mac_key_pkcs11)) 175 return PR_FAILURE; 176 177 rv = NSS_RegisterShutdown(ssl3_SessionTicketShutdown, NULL); 178 if (rv != SECSuccess) 179 goto loser; 180 181 return PR_SUCCESS; 182 183loser: 184 ssl3_SessionTicketShutdown(NULL, NULL); 185 return PR_FAILURE; 186} 187 188static SECStatus 189ssl3_GetSessionTicketKeysPKCS11(sslSocket *ss, PK11SymKey **aes_key, 190 PK11SymKey **mac_key) 191{ 192 if (PR_CallOnceWithArg(&generate_session_keys_once, 193 ssl3_GenerateSessionTicketKeysPKCS11, ss) != PR_SUCCESS) 194 return SECFailure; 195 196 if (session_ticket_enc_key_pkcs11 == NULL || 197 session_ticket_mac_key_pkcs11 == NULL) 198 return SECFailure; 199 200 *aes_key = session_ticket_enc_key_pkcs11; 201 *mac_key = session_ticket_mac_key_pkcs11; 202 return SECSuccess; 203} 204 205static PRStatus 206ssl3_GenerateSessionTicketKeys(void) 207{ 208 PORT_Memcpy(key_name, SESS_TICKET_KEY_NAME_PREFIX, 209 sizeof(SESS_TICKET_KEY_NAME_PREFIX)); 210 211 if (!ssl_GetSessionTicketKeys(&key_name[SESS_TICKET_KEY_NAME_PREFIX_LEN], 212 session_ticket_enc_key, session_ticket_mac_key)) 213 return PR_FAILURE; 214 215 session_ticket_keys_initialized = PR_TRUE; 216 return PR_SUCCESS; 217} 218 219static SECStatus 220ssl3_GetSessionTicketKeys(const unsigned char **aes_key, 221 PRUint32 *aes_key_length, const unsigned char **mac_key, 222 PRUint32 *mac_key_length) 223{ 224 if (PR_CallOnce(&generate_session_keys_once, 225 ssl3_GenerateSessionTicketKeys) != SECSuccess) 226 return SECFailure; 227 228 if (!session_ticket_keys_initialized) 229 return SECFailure; 230 231 *aes_key = session_ticket_enc_key; 232 *aes_key_length = sizeof(session_ticket_enc_key); 233 *mac_key = session_ticket_mac_key; 234 *mac_key_length = sizeof(session_ticket_mac_key); 235 236 return SECSuccess; 237} 238 239/* Table of handlers for received TLS hello extensions, one per extension. 240 * In the second generation, this table will be dynamic, and functions 241 * will be registered here. 242 */ 243/* This table is used by the server, to handle client hello extensions. */ 244static const ssl3HelloExtensionHandler clientHelloHandlers[] = { 245 { ssl_server_name_xtn, &ssl3_HandleServerNameXtn }, 246#ifdef NSS_ENABLE_ECC 247 { ssl_elliptic_curves_xtn, &ssl3_HandleSupportedCurvesXtn }, 248 { ssl_ec_point_formats_xtn, &ssl3_HandleSupportedPointFormatsXtn }, 249#endif 250 { ssl_session_ticket_xtn, &ssl3_ServerHandleSessionTicketXtn }, 251 { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn }, 252 { ssl_next_proto_nego_xtn, &ssl3_ServerHandleNextProtoNegoXtn }, 253 { ssl_use_srtp_xtn, &ssl3_HandleUseSRTPXtn }, 254 { -1, NULL } 255}; 256 257/* These two tables are used by the client, to handle server hello 258 * extensions. */ 259static const ssl3HelloExtensionHandler serverHelloHandlersTLS[] = { 260 { ssl_server_name_xtn, &ssl3_HandleServerNameXtn }, 261 /* TODO: add a handler for ssl_ec_point_formats_xtn */ 262 { ssl_session_ticket_xtn, &ssl3_ClientHandleSessionTicketXtn }, 263 { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn }, 264 { ssl_next_proto_nego_xtn, &ssl3_ClientHandleNextProtoNegoXtn }, 265 { ssl_channel_id_xtn, &ssl3_ClientHandleChannelIDXtn }, 266 { ssl_cert_status_xtn, &ssl3_ClientHandleStatusRequestXtn }, 267 { ssl_use_srtp_xtn, &ssl3_HandleUseSRTPXtn}, 268 { -1, NULL } 269}; 270 271static const ssl3HelloExtensionHandler serverHelloHandlersSSL3[] = { 272 { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn }, 273 { -1, NULL } 274}; 275 276/* Tables of functions to format TLS hello extensions, one function per 277 * extension. 278 * These static tables are for the formatting of client hello extensions. 279 * The server's table of hello senders is dynamic, in the socket struct, 280 * and sender functions are registered there. 281 */ 282static const 283ssl3HelloExtensionSender clientHelloSendersTLS[SSL_MAX_EXTENSIONS] = { 284 { ssl_server_name_xtn, &ssl3_SendServerNameXtn }, 285 { ssl_renegotiation_info_xtn, &ssl3_SendRenegotiationInfoXtn }, 286#ifdef NSS_ENABLE_ECC 287 { ssl_elliptic_curves_xtn, &ssl3_SendSupportedCurvesXtn }, 288 { ssl_ec_point_formats_xtn, &ssl3_SendSupportedPointFormatsXtn }, 289#endif 290 { ssl_session_ticket_xtn, &ssl3_SendSessionTicketXtn }, 291 { ssl_next_proto_nego_xtn, &ssl3_ClientSendNextProtoNegoXtn }, 292 { ssl_channel_id_xtn, &ssl3_ClientSendChannelIDXtn }, 293 { ssl_cert_status_xtn, &ssl3_ClientSendStatusRequestXtn }, 294 { ssl_use_srtp_xtn, &ssl3_SendUseSRTPXtn } 295 /* any extra entries will appear as { 0, NULL } */ 296}; 297 298static const 299ssl3HelloExtensionSender clientHelloSendersSSL3[SSL_MAX_EXTENSIONS] = { 300 { ssl_renegotiation_info_xtn, &ssl3_SendRenegotiationInfoXtn } 301 /* any extra entries will appear as { 0, NULL } */ 302}; 303 304static PRBool 305arrayContainsExtension(const PRUint16 *array, PRUint32 len, PRUint16 ex_type) 306{ 307 int i; 308 for (i = 0; i < len; i++) { 309 if (ex_type == array[i]) 310 return PR_TRUE; 311 } 312 return PR_FALSE; 313} 314 315PRBool 316ssl3_ExtensionNegotiated(sslSocket *ss, PRUint16 ex_type) { 317 TLSExtensionData *xtnData = &ss->xtnData; 318 return arrayContainsExtension(xtnData->negotiated, 319 xtnData->numNegotiated, ex_type); 320} 321 322static PRBool 323ssl3_ClientExtensionAdvertised(sslSocket *ss, PRUint16 ex_type) { 324 TLSExtensionData *xtnData = &ss->xtnData; 325 return arrayContainsExtension(xtnData->advertised, 326 xtnData->numAdvertised, ex_type); 327} 328 329/* Format an SNI extension, using the name from the socket's URL, 330 * unless that name is a dotted decimal string. 331 * Used by client and server. 332 */ 333PRInt32 334ssl3_SendServerNameXtn(sslSocket * ss, PRBool append, 335 PRUint32 maxBytes) 336{ 337 SECStatus rv; 338 if (!ss) 339 return 0; 340 if (!ss->sec.isServer) { 341 PRUint32 len; 342 PRNetAddr netAddr; 343 344 /* must have a hostname */ 345 if (!ss->url || !ss->url[0]) 346 return 0; 347 /* must not be an IPv4 or IPv6 address */ 348 if (PR_SUCCESS == PR_StringToNetAddr(ss->url, &netAddr)) { 349 /* is an IP address (v4 or v6) */ 350 return 0; 351 } 352 len = PORT_Strlen(ss->url); 353 if (append && maxBytes >= len + 9) { 354 /* extension_type */ 355 rv = ssl3_AppendHandshakeNumber(ss, ssl_server_name_xtn, 2); 356 if (rv != SECSuccess) return -1; 357 /* length of extension_data */ 358 rv = ssl3_AppendHandshakeNumber(ss, len + 5, 2); 359 if (rv != SECSuccess) return -1; 360 /* length of server_name_list */ 361 rv = ssl3_AppendHandshakeNumber(ss, len + 3, 2); 362 if (rv != SECSuccess) return -1; 363 /* Name Type (sni_host_name) */ 364 rv = ssl3_AppendHandshake(ss, "\0", 1); 365 if (rv != SECSuccess) return -1; 366 /* HostName (length and value) */ 367 rv = ssl3_AppendHandshakeVariable(ss, (PRUint8 *)ss->url, len, 2); 368 if (rv != SECSuccess) return -1; 369 if (!ss->sec.isServer) { 370 TLSExtensionData *xtnData = &ss->xtnData; 371 xtnData->advertised[xtnData->numAdvertised++] = 372 ssl_server_name_xtn; 373 } 374 } 375 return len + 9; 376 } 377 /* Server side */ 378 if (append && maxBytes >= 4) { 379 rv = ssl3_AppendHandshakeNumber(ss, ssl_server_name_xtn, 2); 380 if (rv != SECSuccess) return -1; 381 /* length of extension_data */ 382 rv = ssl3_AppendHandshakeNumber(ss, 0, 2); 383 if (rv != SECSuccess) return -1; 384 } 385 return 4; 386} 387 388/* handle an incoming SNI extension, by ignoring it. */ 389SECStatus 390ssl3_HandleServerNameXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data) 391{ 392 SECItem *names = NULL; 393 PRUint32 listCount = 0, namesPos = 0, i; 394 TLSExtensionData *xtnData = &ss->xtnData; 395 SECItem ldata; 396 PRInt32 listLenBytes = 0; 397 398 if (!ss->sec.isServer) { 399 /* Verify extension_data is empty. */ 400 if (data->data || data->len || 401 !ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) { 402 /* malformed or was not initiated by the client.*/ 403 return SECFailure; 404 } 405 return SECSuccess; 406 } 407 408 /* Server side - consume client data and register server sender. */ 409 /* do not parse the data if don't have user extension handling function. */ 410 if (!ss->sniSocketConfig) { 411 return SECSuccess; 412 } 413 /* length of server_name_list */ 414 listLenBytes = ssl3_ConsumeHandshakeNumber(ss, 2, &data->data, &data->len); 415 if (listLenBytes == 0 || listLenBytes != data->len) { 416 return SECFailure; 417 } 418 ldata = *data; 419 /* Calculate the size of the array.*/ 420 while (listLenBytes > 0) { 421 SECItem litem; 422 SECStatus rv; 423 PRInt32 type; 424 /* Name Type (sni_host_name) */ 425 type = ssl3_ConsumeHandshakeNumber(ss, 1, &ldata.data, &ldata.len); 426 if (!ldata.len) { 427 return SECFailure; 428 } 429 rv = ssl3_ConsumeHandshakeVariable(ss, &litem, 2, &ldata.data, &ldata.len); 430 if (rv != SECSuccess) { 431 return SECFailure; 432 } 433 /* Adjust total length for cunsumed item, item len and type.*/ 434 listLenBytes -= litem.len + 3; 435 if (listLenBytes > 0 && !ldata.len) { 436 return SECFailure; 437 } 438 listCount += 1; 439 } 440 if (!listCount) { 441 return SECFailure; 442 } 443 names = PORT_ZNewArray(SECItem, listCount); 444 if (!names) { 445 return SECFailure; 446 } 447 for (i = 0;i < listCount;i++) { 448 int j; 449 PRInt32 type; 450 SECStatus rv; 451 PRBool nametypePresent = PR_FALSE; 452 /* Name Type (sni_host_name) */ 453 type = ssl3_ConsumeHandshakeNumber(ss, 1, &data->data, &data->len); 454 /* Check if we have such type in the list */ 455 for (j = 0;j < listCount && names[j].data;j++) { 456 if (names[j].type == type) { 457 nametypePresent = PR_TRUE; 458 break; 459 } 460 } 461 /* HostName (length and value) */ 462 rv = ssl3_ConsumeHandshakeVariable(ss, &names[namesPos], 2, 463 &data->data, &data->len); 464 if (rv != SECSuccess) { 465 goto loser; 466 } 467 if (nametypePresent == PR_FALSE) { 468 namesPos += 1; 469 } 470 } 471 /* Free old and set the new data. */ 472 if (xtnData->sniNameArr) { 473 PORT_Free(ss->xtnData.sniNameArr); 474 } 475 xtnData->sniNameArr = names; 476 xtnData->sniNameArrSize = namesPos; 477 xtnData->negotiated[xtnData->numNegotiated++] = ssl_server_name_xtn; 478 479 return SECSuccess; 480 481loser: 482 PORT_Free(names); 483 return SECFailure; 484} 485 486/* Called by both clients and servers. 487 * Clients sends a filled in session ticket if one is available, and otherwise 488 * sends an empty ticket. Servers always send empty tickets. 489 */ 490PRInt32 491ssl3_SendSessionTicketXtn( 492 sslSocket * ss, 493 PRBool append, 494 PRUint32 maxBytes) 495{ 496 PRInt32 extension_length; 497 NewSessionTicket *session_ticket = NULL; 498 499 /* Ignore the SessionTicket extension if processing is disabled. */ 500 if (!ss->opt.enableSessionTickets) 501 return 0; 502 503 /* Empty extension length = extension_type (2-bytes) + 504 * length(extension_data) (2-bytes) 505 */ 506 extension_length = 4; 507 508 /* If we are a client then send a session ticket if one is availble. 509 * Servers that support the extension and are willing to negotiate the 510 * the extension always respond with an empty extension. 511 */ 512 if (!ss->sec.isServer) { 513 sslSessionID *sid = ss->sec.ci.sid; 514 session_ticket = &sid->u.ssl3.sessionTicket; 515 if (session_ticket->ticket.data) { 516 if (ss->xtnData.ticketTimestampVerified) { 517 extension_length += session_ticket->ticket.len; 518 } else if (!append && 519 (session_ticket->ticket_lifetime_hint == 0 || 520 (session_ticket->ticket_lifetime_hint + 521 session_ticket->received_timestamp > ssl_Time()))) { 522 extension_length += session_ticket->ticket.len; 523 ss->xtnData.ticketTimestampVerified = PR_TRUE; 524 } 525 } 526 } 527 528 if (append && maxBytes >= extension_length) { 529 SECStatus rv; 530 /* extension_type */ 531 rv = ssl3_AppendHandshakeNumber(ss, ssl_session_ticket_xtn, 2); 532 if (rv != SECSuccess) 533 goto loser; 534 if (session_ticket && session_ticket->ticket.data && 535 ss->xtnData.ticketTimestampVerified) { 536 rv = ssl3_AppendHandshakeVariable(ss, session_ticket->ticket.data, 537 session_ticket->ticket.len, 2); 538 ss->xtnData.ticketTimestampVerified = PR_FALSE; 539 } else { 540 rv = ssl3_AppendHandshakeNumber(ss, 0, 2); 541 } 542 if (rv != SECSuccess) 543 goto loser; 544 545 if (!ss->sec.isServer) { 546 TLSExtensionData *xtnData = &ss->xtnData; 547 xtnData->advertised[xtnData->numAdvertised++] = 548 ssl_session_ticket_xtn; 549 } 550 } else if (maxBytes < extension_length) { 551 PORT_Assert(0); 552 return 0; 553 } 554 return extension_length; 555 556 loser: 557 ss->xtnData.ticketTimestampVerified = PR_FALSE; 558 return -1; 559} 560 561/* handle an incoming Next Protocol Negotiation extension. */ 562static SECStatus 563ssl3_ServerHandleNextProtoNegoXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data) 564{ 565 if (ss->firstHsDone || data->len != 0) { 566 /* Clients MUST send an empty NPN extension, if any. */ 567 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID); 568 return SECFailure; 569 } 570 571 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type; 572 573 /* TODO: server side NPN support would require calling 574 * ssl3_RegisterServerHelloExtensionSender here in order to echo the 575 * extension back to the client. */ 576 577 return SECSuccess; 578} 579 580/* ssl3_ValidateNextProtoNego checks that the given block of data is valid: none 581 * of the lengths may be 0 and the sum of the lengths must equal the length of 582 * the block. */ 583SECStatus 584ssl3_ValidateNextProtoNego(const unsigned char* data, unsigned int length) 585{ 586 unsigned int offset = 0; 587 588 while (offset < length) { 589 unsigned int newOffset = offset + 1 + (unsigned int) data[offset]; 590 /* Reject embedded nulls to protect against buggy applications that 591 * store protocol identifiers in null-terminated strings. 592 */ 593 if (newOffset > length || data[offset] == 0) { 594 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID); 595 return SECFailure; 596 } 597 offset = newOffset; 598 } 599 600 if (offset > length) { 601 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID); 602 return SECFailure; 603 } 604 605 return SECSuccess; 606} 607 608static SECStatus 609ssl3_ClientHandleNextProtoNegoXtn(sslSocket *ss, PRUint16 ex_type, 610 SECItem *data) 611{ 612 SECStatus rv; 613 unsigned char resultBuffer[255]; 614 SECItem result = { siBuffer, resultBuffer, 0 }; 615 616 PORT_Assert(!ss->firstHsDone); 617 618 rv = ssl3_ValidateNextProtoNego(data->data, data->len); 619 if (rv != SECSuccess) 620 return rv; 621 622 /* ss->nextProtoCallback cannot normally be NULL if we negotiated the 623 * extension. However, It is possible that an application erroneously 624 * cleared the callback between the time we sent the ClientHello and now. 625 */ 626 PORT_Assert(ss->nextProtoCallback != NULL); 627 if (!ss->nextProtoCallback) { 628 /* XXX Use a better error code. This is an application error, not an 629 * NSS bug. */ 630 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 631 return SECFailure; 632 } 633 634 rv = ss->nextProtoCallback(ss->nextProtoArg, ss->fd, data->data, data->len, 635 result.data, &result.len, sizeof resultBuffer); 636 if (rv != SECSuccess) 637 return rv; 638 /* If the callback wrote more than allowed to |result| it has corrupted our 639 * stack. */ 640 if (result.len > sizeof resultBuffer) { 641 PORT_SetError(SEC_ERROR_OUTPUT_LEN); 642 return SECFailure; 643 } 644 645 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type; 646 647 SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE); 648 return SECITEM_CopyItem(NULL, &ss->ssl3.nextProto, &result); 649} 650 651static PRInt32 652ssl3_ClientSendNextProtoNegoXtn(sslSocket * ss, PRBool append, 653 PRUint32 maxBytes) 654{ 655 PRInt32 extension_length; 656 657 /* Renegotiations do not send this extension. */ 658 if (!ss->nextProtoCallback || ss->firstHsDone) { 659 return 0; 660 } 661 662 extension_length = 4; 663 664 if (append && maxBytes >= extension_length) { 665 SECStatus rv; 666 rv = ssl3_AppendHandshakeNumber(ss, ssl_next_proto_nego_xtn, 2); 667 if (rv != SECSuccess) 668 goto loser; 669 rv = ssl3_AppendHandshakeNumber(ss, 0, 2); 670 if (rv != SECSuccess) 671 goto loser; 672 ss->xtnData.advertised[ss->xtnData.numAdvertised++] = 673 ssl_next_proto_nego_xtn; 674 } else if (maxBytes < extension_length) { 675 return 0; 676 } 677 678 return extension_length; 679 680loser: 681 return -1; 682} 683 684static SECStatus 685ssl3_ClientHandleChannelIDXtn(sslSocket *ss, PRUint16 ex_type, 686 SECItem *data) 687{ 688 PORT_Assert(ss->getChannelID != NULL); 689 690 if (data->len) { 691 PORT_SetError(SSL_ERROR_BAD_CHANNEL_ID_DATA); 692 return SECFailure; 693 } 694 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type; 695 return SECSuccess; 696} 697 698static PRInt32 699ssl3_ClientSendChannelIDXtn(sslSocket * ss, PRBool append, 700 PRUint32 maxBytes) 701{ 702 PRInt32 extension_length = 4; 703 704 if (!ss->getChannelID) 705 return 0; 706 707 if (maxBytes < extension_length) { 708 PORT_Assert(0); 709 return 0; 710 } 711 712 if (append) { 713 SECStatus rv; 714 rv = ssl3_AppendHandshakeNumber(ss, ssl_channel_id_xtn, 2); 715 if (rv != SECSuccess) 716 goto loser; 717 rv = ssl3_AppendHandshakeNumber(ss, 0, 2); 718 if (rv != SECSuccess) 719 goto loser; 720 ss->xtnData.advertised[ss->xtnData.numAdvertised++] = 721 ssl_channel_id_xtn; 722 } 723 724 return extension_length; 725 726loser: 727 return -1; 728} 729 730SECStatus 731ssl3_ClientHandleStatusRequestXtn(sslSocket *ss, PRUint16 ex_type, 732 SECItem *data) 733{ 734 /* If we didn't request this extension, then the server may not echo it. */ 735 if (!ss->opt.enableOCSPStapling) 736 return SECFailure; 737 738 /* The echoed extension must be empty. */ 739 if (data->len != 0) 740 return SECFailure; 741 742 ss->ssl3.hs.may_get_cert_status = PR_TRUE; 743 744 /* Keep track of negotiated extensions. */ 745 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type; 746 747 return SECSuccess; 748} 749 750/* ssl3_ClientSendStatusRequestXtn builds the status_request extension on the 751 * client side. See RFC 4366 section 3.6. */ 752PRInt32 753ssl3_ClientSendStatusRequestXtn(sslSocket * ss, PRBool append, 754 PRUint32 maxBytes) 755{ 756 PRInt32 extension_length; 757 758 if (!ss->opt.enableOCSPStapling) 759 return 0; 760 761 /* extension_type (2-bytes) + 762 * length(extension_data) (2-bytes) + 763 * status_type (1) + 764 * responder_id_list length (2) + 765 * request_extensions length (2) 766 */ 767 extension_length = 9; 768 769 if (append && maxBytes >= extension_length) { 770 SECStatus rv; 771 TLSExtensionData *xtnData; 772 773 /* extension_type */ 774 rv = ssl3_AppendHandshakeNumber(ss, ssl_cert_status_xtn, 2); 775 if (rv != SECSuccess) 776 return -1; 777 rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2); 778 if (rv != SECSuccess) 779 return -1; 780 rv = ssl3_AppendHandshakeNumber(ss, 1 /* status_type ocsp */, 1); 781 if (rv != SECSuccess) 782 return -1; 783 /* A zero length responder_id_list means that the responders are 784 * implicitly known to the server. */ 785 rv = ssl3_AppendHandshakeNumber(ss, 0, 2); 786 if (rv != SECSuccess) 787 return -1; 788 /* A zero length request_extensions means that there are no extensions. 789 * Specifically, we don't set the id-pkix-ocsp-nonce extension. This 790 * means that the server can replay a cached OCSP response to us. */ 791 rv = ssl3_AppendHandshakeNumber(ss, 0, 2); 792 if (rv != SECSuccess) 793 return -1; 794 795 xtnData = &ss->xtnData; 796 xtnData->advertised[xtnData->numAdvertised++] = ssl_cert_status_xtn; 797 } else if (maxBytes < extension_length) { 798 PORT_Assert(0); 799 return 0; 800 } 801 return extension_length; 802} 803 804/* 805 * NewSessionTicket 806 * Called from ssl3_HandleFinished 807 */ 808SECStatus 809ssl3_SendNewSessionTicket(sslSocket *ss) 810{ 811 int i; 812 SECStatus rv; 813 NewSessionTicket ticket; 814 SECItem plaintext; 815 SECItem plaintext_item = {0, NULL, 0}; 816 SECItem ciphertext = {0, NULL, 0}; 817 PRUint32 ciphertext_length; 818 PRBool ms_is_wrapped; 819 unsigned char wrapped_ms[SSL3_MASTER_SECRET_LENGTH]; 820 SECItem ms_item = {0, NULL, 0}; 821 SSL3KEAType effectiveExchKeyType = ssl_kea_null; 822 PRUint32 padding_length; 823 PRUint32 message_length; 824 PRUint32 cert_length; 825 uint8 length_buf[4]; 826 PRUint32 now; 827 PK11SymKey *aes_key_pkcs11; 828 PK11SymKey *mac_key_pkcs11; 829 const unsigned char *aes_key; 830 const unsigned char *mac_key; 831 PRUint32 aes_key_length; 832 PRUint32 mac_key_length; 833 PRUint64 aes_ctx_buf[MAX_CIPHER_CONTEXT_LLONGS]; 834 AESContext *aes_ctx; 835 CK_MECHANISM_TYPE cipherMech = CKM_AES_CBC; 836 PK11Context *aes_ctx_pkcs11; 837 const SECHashObject *hashObj = NULL; 838 PRUint64 hmac_ctx_buf[MAX_MAC_CONTEXT_LLONGS]; 839 HMACContext *hmac_ctx; 840 CK_MECHANISM_TYPE macMech = CKM_SHA256_HMAC; 841 PK11Context *hmac_ctx_pkcs11; 842 unsigned char computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH]; 843 unsigned int computed_mac_length; 844 unsigned char iv[AES_BLOCK_SIZE]; 845 SECItem ivItem; 846 SECItem *srvName = NULL; 847 PRUint32 srvNameLen = 0; 848 CK_MECHANISM_TYPE msWrapMech = 0; /* dummy default value, 849 * must be >= 0 */ 850 851 SSL_TRC(3, ("%d: SSL3[%d]: send session_ticket handshake", 852 SSL_GETPID(), ss->fd)); 853 854 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 855 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 856 857 ticket.ticket_lifetime_hint = TLS_EX_SESS_TICKET_LIFETIME_HINT; 858 cert_length = (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) ? 859 3 + ss->sec.ci.sid->peerCert->derCert.len : 0; 860 861 /* Get IV and encryption keys */ 862 ivItem.data = iv; 863 ivItem.len = sizeof(iv); 864 rv = PK11_GenerateRandom(iv, sizeof(iv)); 865 if (rv != SECSuccess) goto loser; 866 867 if (ss->opt.bypassPKCS11) { 868 rv = ssl3_GetSessionTicketKeys(&aes_key, &aes_key_length, 869 &mac_key, &mac_key_length); 870 } else { 871 rv = ssl3_GetSessionTicketKeysPKCS11(ss, &aes_key_pkcs11, 872 &mac_key_pkcs11); 873 } 874 if (rv != SECSuccess) goto loser; 875 876 if (ss->ssl3.pwSpec->msItem.len && ss->ssl3.pwSpec->msItem.data) { 877 /* The master secret is available unwrapped. */ 878 ms_item.data = ss->ssl3.pwSpec->msItem.data; 879 ms_item.len = ss->ssl3.pwSpec->msItem.len; 880 ms_is_wrapped = PR_FALSE; 881 } else { 882 /* Extract the master secret wrapped. */ 883 sslSessionID sid; 884 PORT_Memset(&sid, 0, sizeof(sslSessionID)); 885 886 if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) { 887 effectiveExchKeyType = kt_rsa; 888 } else { 889 effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType; 890 } 891 892 rv = ssl3_CacheWrappedMasterSecret(ss, &sid, ss->ssl3.pwSpec, 893 effectiveExchKeyType); 894 if (rv == SECSuccess) { 895 if (sid.u.ssl3.keys.wrapped_master_secret_len > sizeof(wrapped_ms)) 896 goto loser; 897 memcpy(wrapped_ms, sid.u.ssl3.keys.wrapped_master_secret, 898 sid.u.ssl3.keys.wrapped_master_secret_len); 899 ms_item.data = wrapped_ms; 900 ms_item.len = sid.u.ssl3.keys.wrapped_master_secret_len; 901 msWrapMech = sid.u.ssl3.masterWrapMech; 902 } else { 903 /* TODO: else send an empty ticket. */ 904 goto loser; 905 } 906 ms_is_wrapped = PR_TRUE; 907 } 908 /* Prep to send negotiated name */ 909 srvName = &ss->ssl3.pwSpec->srvVirtName; 910 if (srvName->data && srvName->len) { 911 srvNameLen = 2 + srvName->len; /* len bytes + name len */ 912 } 913 914 ciphertext_length = 915 sizeof(PRUint16) /* ticket_version */ 916 + sizeof(SSL3ProtocolVersion) /* ssl_version */ 917 + sizeof(ssl3CipherSuite) /* ciphersuite */ 918 + 1 /* compression */ 919 + 10 /* cipher spec parameters */ 920 + 1 /* SessionTicket.ms_is_wrapped */ 921 + 1 /* effectiveExchKeyType */ 922 + 4 /* msWrapMech */ 923 + 2 /* master_secret.length */ 924 + ms_item.len /* master_secret */ 925 + 1 /* client_auth_type */ 926 + cert_length /* cert */ 927 + 1 /* server name type */ 928 + srvNameLen /* name len + length field */ 929 + sizeof(ticket.ticket_lifetime_hint); 930 padding_length = AES_BLOCK_SIZE - 931 (ciphertext_length % AES_BLOCK_SIZE); 932 ciphertext_length += padding_length; 933 934 message_length = 935 sizeof(ticket.ticket_lifetime_hint) /* ticket_lifetime_hint */ 936 + 2 /* length field for NewSessionTicket.ticket */ 937 + SESS_TICKET_KEY_NAME_LEN /* key_name */ 938 + AES_BLOCK_SIZE /* iv */ 939 + 2 /* length field for NewSessionTicket.ticket.encrypted_state */ 940 + ciphertext_length /* encrypted_state */ 941 + TLS_EX_SESS_TICKET_MAC_LENGTH; /* mac */ 942 943 if (SECITEM_AllocItem(NULL, &plaintext_item, ciphertext_length) == NULL) 944 goto loser; 945 946 plaintext = plaintext_item; 947 948 /* ticket_version */ 949 rv = ssl3_AppendNumberToItem(&plaintext, TLS_EX_SESS_TICKET_VERSION, 950 sizeof(PRUint16)); 951 if (rv != SECSuccess) goto loser; 952 953 /* ssl_version */ 954 rv = ssl3_AppendNumberToItem(&plaintext, ss->version, 955 sizeof(SSL3ProtocolVersion)); 956 if (rv != SECSuccess) goto loser; 957 958 /* ciphersuite */ 959 rv = ssl3_AppendNumberToItem(&plaintext, ss->ssl3.hs.cipher_suite, 960 sizeof(ssl3CipherSuite)); 961 if (rv != SECSuccess) goto loser; 962 963 /* compression */ 964 rv = ssl3_AppendNumberToItem(&plaintext, ss->ssl3.hs.compression, 1); 965 if (rv != SECSuccess) goto loser; 966 967 /* cipher spec parameters */ 968 rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.authAlgorithm, 1); 969 if (rv != SECSuccess) goto loser; 970 rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.authKeyBits, 4); 971 if (rv != SECSuccess) goto loser; 972 rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.keaType, 1); 973 if (rv != SECSuccess) goto loser; 974 rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.keaKeyBits, 4); 975 if (rv != SECSuccess) goto loser; 976 977 /* master_secret */ 978 rv = ssl3_AppendNumberToItem(&plaintext, ms_is_wrapped, 1); 979 if (rv != SECSuccess) goto loser; 980 rv = ssl3_AppendNumberToItem(&plaintext, effectiveExchKeyType, 1); 981 if (rv != SECSuccess) goto loser; 982 rv = ssl3_AppendNumberToItem(&plaintext, msWrapMech, 4); 983 if (rv != SECSuccess) goto loser; 984 rv = ssl3_AppendNumberToItem(&plaintext, ms_item.len, 2); 985 if (rv != SECSuccess) goto loser; 986 rv = ssl3_AppendToItem(&plaintext, ms_item.data, ms_item.len); 987 if (rv != SECSuccess) goto loser; 988 989 /* client_identity */ 990 if (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) { 991 rv = ssl3_AppendNumberToItem(&plaintext, CLIENT_AUTH_CERTIFICATE, 1); 992 if (rv != SECSuccess) goto loser; 993 rv = ssl3_AppendNumberToItem(&plaintext, 994 ss->sec.ci.sid->peerCert->derCert.len, 3); 995 if (rv != SECSuccess) goto loser; 996 rv = ssl3_AppendToItem(&plaintext, 997 ss->sec.ci.sid->peerCert->derCert.data, 998 ss->sec.ci.sid->peerCert->derCert.len); 999 if (rv != SECSuccess) goto loser; 1000 } else { 1001 rv = ssl3_AppendNumberToItem(&plaintext, 0, 1); 1002 if (rv != SECSuccess) goto loser; 1003 } 1004 1005 /* timestamp */ 1006 now = ssl_Time(); 1007 rv = ssl3_AppendNumberToItem(&plaintext, now, 1008 sizeof(ticket.ticket_lifetime_hint)); 1009 if (rv != SECSuccess) goto loser; 1010 1011 if (srvNameLen) { 1012 /* Name Type (sni_host_name) */ 1013 rv = ssl3_AppendNumberToItem(&plaintext, srvName->type, 1); 1014 if (rv != SECSuccess) goto loser; 1015 /* HostName (length and value) */ 1016 rv = ssl3_AppendNumberToItem(&plaintext, srvName->len, 2); 1017 if (rv != SECSuccess) goto loser; 1018 rv = ssl3_AppendToItem(&plaintext, srvName->data, srvName->len); 1019 if (rv != SECSuccess) goto loser; 1020 } else { 1021 /* No Name */ 1022 rv = ssl3_AppendNumberToItem(&plaintext, (char)TLS_STE_NO_SERVER_NAME, 1023 1); 1024 if (rv != SECSuccess) goto loser; 1025 } 1026 1027 PORT_Assert(plaintext.len == padding_length); 1028 for (i = 0; i < padding_length; i++) 1029 plaintext.data[i] = (unsigned char)padding_length; 1030 1031 if (SECITEM_AllocItem(NULL, &ciphertext, ciphertext_length) == NULL) { 1032 rv = SECFailure; 1033 goto loser; 1034 } 1035 1036 /* Generate encrypted portion of ticket. */ 1037 if (ss->opt.bypassPKCS11) { 1038 aes_ctx = (AESContext *)aes_ctx_buf; 1039 rv = AES_InitContext(aes_ctx, aes_key, aes_key_length, iv, 1040 NSS_AES_CBC, 1, AES_BLOCK_SIZE); 1041 if (rv != SECSuccess) goto loser; 1042 1043 rv = AES_Encrypt(aes_ctx, ciphertext.data, &ciphertext.len, 1044 ciphertext.len, plaintext_item.data, 1045 plaintext_item.len); 1046 if (rv != SECSuccess) goto loser; 1047 } else { 1048 aes_ctx_pkcs11 = PK11_CreateContextBySymKey(cipherMech, 1049 CKA_ENCRYPT, aes_key_pkcs11, &ivItem); 1050 if (!aes_ctx_pkcs11) 1051 goto loser; 1052 1053 rv = PK11_CipherOp(aes_ctx_pkcs11, ciphertext.data, 1054 (int *)&ciphertext.len, ciphertext.len, 1055 plaintext_item.data, plaintext_item.len); 1056 PK11_Finalize(aes_ctx_pkcs11); 1057 PK11_DestroyContext(aes_ctx_pkcs11, PR_TRUE); 1058 if (rv != SECSuccess) goto loser; 1059 } 1060 1061 /* Convert ciphertext length to network order. */ 1062 length_buf[0] = (ciphertext.len >> 8) & 0xff; 1063 length_buf[1] = (ciphertext.len ) & 0xff; 1064 1065 /* Compute MAC. */ 1066 if (ss->opt.bypassPKCS11) { 1067 hmac_ctx = (HMACContext *)hmac_ctx_buf; 1068 hashObj = HASH_GetRawHashObject(HASH_AlgSHA256); 1069 if (HMAC_Init(hmac_ctx, hashObj, mac_key, 1070 mac_key_length, PR_FALSE) != SECSuccess) 1071 goto loser; 1072 1073 HMAC_Begin(hmac_ctx); 1074 HMAC_Update(hmac_ctx, key_name, SESS_TICKET_KEY_NAME_LEN); 1075 HMAC_Update(hmac_ctx, iv, sizeof(iv)); 1076 HMAC_Update(hmac_ctx, (unsigned char *)length_buf, 2); 1077 HMAC_Update(hmac_ctx, ciphertext.data, ciphertext.len); 1078 HMAC_Finish(hmac_ctx, computed_mac, &computed_mac_length, 1079 sizeof(computed_mac)); 1080 } else { 1081 SECItem macParam; 1082 macParam.data = NULL; 1083 macParam.len = 0; 1084 hmac_ctx_pkcs11 = PK11_CreateContextBySymKey(macMech, 1085 CKA_SIGN, mac_key_pkcs11, &macParam); 1086 if (!hmac_ctx_pkcs11) 1087 goto loser; 1088 1089 rv = PK11_DigestBegin(hmac_ctx_pkcs11); 1090 rv = PK11_DigestOp(hmac_ctx_pkcs11, key_name, 1091 SESS_TICKET_KEY_NAME_LEN); 1092 rv = PK11_DigestOp(hmac_ctx_pkcs11, iv, sizeof(iv)); 1093 rv = PK11_DigestOp(hmac_ctx_pkcs11, (unsigned char *)length_buf, 2); 1094 rv = PK11_DigestOp(hmac_ctx_pkcs11, ciphertext.data, ciphertext.len); 1095 rv = PK11_DigestFinal(hmac_ctx_pkcs11, computed_mac, 1096 &computed_mac_length, sizeof(computed_mac)); 1097 PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE); 1098 if (rv != SECSuccess) goto loser; 1099 } 1100 1101 /* Serialize the handshake message. */ 1102 rv = ssl3_AppendHandshakeHeader(ss, new_session_ticket, message_length); 1103 if (rv != SECSuccess) goto loser; 1104 1105 rv = ssl3_AppendHandshakeNumber(ss, ticket.ticket_lifetime_hint, 1106 sizeof(ticket.ticket_lifetime_hint)); 1107 if (rv != SECSuccess) goto loser; 1108 1109 rv = ssl3_AppendHandshakeNumber(ss, 1110 message_length - sizeof(ticket.ticket_lifetime_hint) - 2, 2); 1111 if (rv != SECSuccess) goto loser; 1112 1113 rv = ssl3_AppendHandshake(ss, key_name, SESS_TICKET_KEY_NAME_LEN); 1114 if (rv != SECSuccess) goto loser; 1115 1116 rv = ssl3_AppendHandshake(ss, iv, sizeof(iv)); 1117 if (rv != SECSuccess) goto loser; 1118 1119 rv = ssl3_AppendHandshakeVariable(ss, ciphertext.data, ciphertext.len, 2); 1120 if (rv != SECSuccess) goto loser; 1121 1122 rv = ssl3_AppendHandshake(ss, computed_mac, computed_mac_length); 1123 if (rv != SECSuccess) goto loser; 1124 1125loser: 1126 if (plaintext_item.data) 1127 SECITEM_FreeItem(&plaintext_item, PR_FALSE); 1128 if (ciphertext.data) 1129 SECITEM_FreeItem(&ciphertext, PR_FALSE); 1130 1131 return rv; 1132} 1133 1134/* When a client receives a SessionTicket extension a NewSessionTicket 1135 * message is expected during the handshake. 1136 */ 1137SECStatus 1138ssl3_ClientHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type, 1139 SECItem *data) 1140{ 1141 if (data->len != 0) 1142 return SECFailure; 1143 1144 /* Keep track of negotiated extensions. */ 1145 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type; 1146 return SECSuccess; 1147} 1148 1149SECStatus 1150ssl3_ServerHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type, 1151 SECItem *data) 1152{ 1153 SECStatus rv; 1154 SECItem *decrypted_state = NULL; 1155 SessionTicket *parsed_session_ticket = NULL; 1156 sslSessionID *sid = NULL; 1157 SSL3Statistics *ssl3stats; 1158 1159 /* Ignore the SessionTicket extension if processing is disabled. */ 1160 if (!ss->opt.enableSessionTickets) 1161 return SECSuccess; 1162 1163 /* Keep track of negotiated extensions. */ 1164 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type; 1165 1166 /* Parse the received ticket sent in by the client. We are 1167 * lenient about some parse errors, falling back to a fullshake 1168 * instead of terminating the current connection. 1169 */ 1170 if (data->len == 0) { 1171 ss->xtnData.emptySessionTicket = PR_TRUE; 1172 } else { 1173 int i; 1174 SECItem extension_data; 1175 EncryptedSessionTicket enc_session_ticket; 1176 unsigned char computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH]; 1177 unsigned int computed_mac_length; 1178 const SECHashObject *hashObj; 1179 const unsigned char *aes_key; 1180 const unsigned char *mac_key; 1181 PK11SymKey *aes_key_pkcs11; 1182 PK11SymKey *mac_key_pkcs11; 1183 PRUint32 aes_key_length; 1184 PRUint32 mac_key_length; 1185 PRUint64 hmac_ctx_buf[MAX_MAC_CONTEXT_LLONGS]; 1186 HMACContext *hmac_ctx; 1187 PK11Context *hmac_ctx_pkcs11; 1188 CK_MECHANISM_TYPE macMech = CKM_SHA256_HMAC; 1189 PRUint64 aes_ctx_buf[MAX_CIPHER_CONTEXT_LLONGS]; 1190 AESContext *aes_ctx; 1191 PK11Context *aes_ctx_pkcs11; 1192 CK_MECHANISM_TYPE cipherMech = CKM_AES_CBC; 1193 unsigned char * padding; 1194 PRUint32 padding_length; 1195 unsigned char *buffer; 1196 unsigned int buffer_len; 1197 PRInt32 temp; 1198 SECItem cert_item; 1199 PRInt8 nameType = TLS_STE_NO_SERVER_NAME; 1200 1201 /* Turn off stateless session resumption if the client sends a 1202 * SessionTicket extension, even if the extension turns out to be 1203 * malformed (ss->sec.ci.sid is non-NULL when doing session 1204 * renegotiation.) 1205 */ 1206 if (ss->sec.ci.sid != NULL) { 1207 if (ss->sec.uncache) 1208 ss->sec.uncache(ss->sec.ci.sid); 1209 ssl_FreeSID(ss->sec.ci.sid); 1210 ss->sec.ci.sid = NULL; 1211 } 1212 1213 extension_data.data = data->data; /* Keep a copy for future use. */ 1214 extension_data.len = data->len; 1215 1216 if (ssl3_ParseEncryptedSessionTicket(ss, data, &enc_session_ticket) 1217 != SECSuccess) 1218 return SECFailure; 1219 1220 /* Get session ticket keys. */ 1221 if (ss->opt.bypassPKCS11) { 1222 rv = ssl3_GetSessionTicketKeys(&aes_key, &aes_key_length, 1223 &mac_key, &mac_key_length); 1224 } else { 1225 rv = ssl3_GetSessionTicketKeysPKCS11(ss, &aes_key_pkcs11, 1226 &mac_key_pkcs11); 1227 } 1228 if (rv != SECSuccess) { 1229 SSL_DBG(("%d: SSL[%d]: Unable to get/generate session ticket keys.", 1230 SSL_GETPID(), ss->fd)); 1231 goto loser; 1232 } 1233 1234 /* If the ticket sent by the client was generated under a key different 1235 * from the one we have, bypass ticket processing. 1236 */ 1237 if (PORT_Memcmp(enc_session_ticket.key_name, key_name, 1238 SESS_TICKET_KEY_NAME_LEN) != 0) { 1239 SSL_DBG(("%d: SSL[%d]: Session ticket key_name sent mismatch.", 1240 SSL_GETPID(), ss->fd)); 1241 goto no_ticket; 1242 } 1243 1244 /* Verify the MAC on the ticket. MAC verification may also 1245 * fail if the MAC key has been recently refreshed. 1246 */ 1247 if (ss->opt.bypassPKCS11) { 1248 hmac_ctx = (HMACContext *)hmac_ctx_buf; 1249 hashObj = HASH_GetRawHashObject(HASH_AlgSHA256); 1250 if (HMAC_Init(hmac_ctx, hashObj, mac_key, 1251 sizeof(session_ticket_mac_key), PR_FALSE) != SECSuccess) 1252 goto no_ticket; 1253 HMAC_Begin(hmac_ctx); 1254 HMAC_Update(hmac_ctx, extension_data.data, 1255 extension_data.len - TLS_EX_SESS_TICKET_MAC_LENGTH); 1256 if (HMAC_Finish(hmac_ctx, computed_mac, &computed_mac_length, 1257 sizeof(computed_mac)) != SECSuccess) 1258 goto no_ticket; 1259 } else { 1260 SECItem macParam; 1261 macParam.data = NULL; 1262 macParam.len = 0; 1263 hmac_ctx_pkcs11 = PK11_CreateContextBySymKey(macMech, 1264 CKA_SIGN, mac_key_pkcs11, &macParam); 1265 if (!hmac_ctx_pkcs11) { 1266 SSL_DBG(("%d: SSL[%d]: Unable to create HMAC context: %d.", 1267 SSL_GETPID(), ss->fd, PORT_GetError())); 1268 goto no_ticket; 1269 } else { 1270 SSL_DBG(("%d: SSL[%d]: Successfully created HMAC context.", 1271 SSL_GETPID(), ss->fd)); 1272 } 1273 rv = PK11_DigestBegin(hmac_ctx_pkcs11); 1274 rv = PK11_DigestOp(hmac_ctx_pkcs11, extension_data.data, 1275 extension_data.len - TLS_EX_SESS_TICKET_MAC_LENGTH); 1276 if (rv != SECSuccess) { 1277 PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE); 1278 goto no_ticket; 1279 } 1280 rv = PK11_DigestFinal(hmac_ctx_pkcs11, computed_mac, 1281 &computed_mac_length, sizeof(computed_mac)); 1282 PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE); 1283 if (rv != SECSuccess) 1284 goto no_ticket; 1285 } 1286 if (NSS_SecureMemcmp(computed_mac, enc_session_ticket.mac, 1287 computed_mac_length) != 0) { 1288 SSL_DBG(("%d: SSL[%d]: Session ticket MAC mismatch.", 1289 SSL_GETPID(), ss->fd)); 1290 goto no_ticket; 1291 } 1292 1293 /* We ignore key_name for now. 1294 * This is ok as MAC verification succeeded. 1295 */ 1296 1297 /* Decrypt the ticket. */ 1298 1299 /* Plaintext is shorter than the ciphertext due to padding. */ 1300 decrypted_state = SECITEM_AllocItem(NULL, NULL, 1301 enc_session_ticket.encrypted_state.len); 1302 1303 if (ss->opt.bypassPKCS11) { 1304 aes_ctx = (AESContext *)aes_ctx_buf; 1305 rv = AES_InitContext(aes_ctx, aes_key, 1306 sizeof(session_ticket_enc_key), enc_session_ticket.iv, 1307 NSS_AES_CBC, 0,AES_BLOCK_SIZE); 1308 if (rv != SECSuccess) { 1309 SSL_DBG(("%d: SSL[%d]: Unable to create AES context.", 1310 SSL_GETPID(), ss->fd)); 1311 goto no_ticket; 1312 } 1313 1314 rv = AES_Decrypt(aes_ctx, decrypted_state->data, 1315 &decrypted_state->len, decrypted_state->len, 1316 enc_session_ticket.encrypted_state.data, 1317 enc_session_ticket.encrypted_state.len); 1318 if (rv != SECSuccess) 1319 goto no_ticket; 1320 } else { 1321 SECItem ivItem; 1322 ivItem.data = enc_session_ticket.iv; 1323 ivItem.len = AES_BLOCK_SIZE; 1324 aes_ctx_pkcs11 = PK11_CreateContextBySymKey(cipherMech, 1325 CKA_DECRYPT, aes_key_pkcs11, &ivItem); 1326 if (!aes_ctx_pkcs11) { 1327 SSL_DBG(("%d: SSL[%d]: Unable to create AES context.", 1328 SSL_GETPID(), ss->fd)); 1329 goto no_ticket; 1330 } 1331 1332 rv = PK11_CipherOp(aes_ctx_pkcs11, decrypted_state->data, 1333 (int *)&decrypted_state->len, decrypted_state->len, 1334 enc_session_ticket.encrypted_state.data, 1335 enc_session_ticket.encrypted_state.len); 1336 PK11_Finalize(aes_ctx_pkcs11); 1337 PK11_DestroyContext(aes_ctx_pkcs11, PR_TRUE); 1338 if (rv != SECSuccess) 1339 goto no_ticket; 1340 } 1341 1342 /* Check padding. */ 1343 padding_length = 1344 (PRUint32)decrypted_state->data[decrypted_state->len - 1]; 1345 if (padding_length == 0 || padding_length > AES_BLOCK_SIZE) 1346 goto no_ticket; 1347 1348 padding = &decrypted_state->data[decrypted_state->len - padding_length]; 1349 for (i = 0; i < padding_length; i++, padding++) { 1350 if (padding_length != (PRUint32)*padding) 1351 goto no_ticket; 1352 } 1353 1354 /* Deserialize session state. */ 1355 buffer = decrypted_state->data; 1356 buffer_len = decrypted_state->len; 1357 1358 parsed_session_ticket = PORT_ZAlloc(sizeof(SessionTicket)); 1359 if (parsed_session_ticket == NULL) { 1360 rv = SECFailure; 1361 goto loser; 1362 } 1363 1364 /* Read ticket_version (which is ignored for now.) */ 1365 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len); 1366 if (temp < 0) goto no_ticket; 1367 parsed_session_ticket->ticket_version = (SSL3ProtocolVersion)temp; 1368 1369 /* Read SSLVersion. */ 1370 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len); 1371 if (temp < 0) goto no_ticket; 1372 parsed_session_ticket->ssl_version = (SSL3ProtocolVersion)temp; 1373 1374 /* Read cipher_suite. */ 1375 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len); 1376 if (temp < 0) goto no_ticket; 1377 parsed_session_ticket->cipher_suite = (ssl3CipherSuite)temp; 1378 1379 /* Read compression_method. */ 1380 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); 1381 if (temp < 0) goto no_ticket; 1382 parsed_session_ticket->compression_method = (SSLCompressionMethod)temp; 1383 1384 /* Read cipher spec parameters. */ 1385 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); 1386 if (temp < 0) goto no_ticket; 1387 parsed_session_ticket->authAlgorithm = (SSLSignType)temp; 1388 temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len); 1389 if (temp < 0) goto no_ticket; 1390 parsed_session_ticket->authKeyBits = (PRUint32)temp; 1391 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); 1392 if (temp < 0) goto no_ticket; 1393 parsed_session_ticket->keaType = (SSLKEAType)temp; 1394 temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len); 1395 if (temp < 0) goto no_ticket; 1396 parsed_session_ticket->keaKeyBits = (PRUint32)temp; 1397 1398 /* Read wrapped master_secret. */ 1399 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); 1400 if (temp < 0) goto no_ticket; 1401 parsed_session_ticket->ms_is_wrapped = (PRBool)temp; 1402 1403 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); 1404 if (temp < 0) goto no_ticket; 1405 parsed_session_ticket->exchKeyType = (SSL3KEAType)temp; 1406 1407 temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len); 1408 if (temp < 0) goto no_ticket; 1409 parsed_session_ticket->msWrapMech = (CK_MECHANISM_TYPE)temp; 1410 1411 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len); 1412 if (temp < 0) goto no_ticket; 1413 parsed_session_ticket->ms_length = (PRUint16)temp; 1414 if (parsed_session_ticket->ms_length == 0 || /* sanity check MS. */ 1415 parsed_session_ticket->ms_length > 1416 sizeof(parsed_session_ticket->master_secret)) 1417 goto no_ticket; 1418 1419 /* Allow for the wrapped master secret to be longer. */ 1420 if (buffer_len < sizeof(SSL3_MASTER_SECRET_LENGTH)) 1421 goto no_ticket; 1422 PORT_Memcpy(parsed_session_ticket->master_secret, buffer, 1423 parsed_session_ticket->ms_length); 1424 buffer += parsed_session_ticket->ms_length; 1425 buffer_len -= parsed_session_ticket->ms_length; 1426 1427 /* Read client_identity */ 1428 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); 1429 if (temp < 0) 1430 goto no_ticket; 1431 parsed_session_ticket->client_identity.client_auth_type = 1432 (ClientAuthenticationType)temp; 1433 switch(parsed_session_ticket->client_identity.client_auth_type) { 1434 case CLIENT_AUTH_ANONYMOUS: 1435 break; 1436 case CLIENT_AUTH_CERTIFICATE: 1437 rv = ssl3_ConsumeHandshakeVariable(ss, &cert_item, 3, 1438 &buffer, &buffer_len); 1439 if (rv != SECSuccess) goto no_ticket; 1440 rv = SECITEM_CopyItem(NULL, &parsed_session_ticket->peer_cert, 1441 &cert_item); 1442 if (rv != SECSuccess) goto no_ticket; 1443 break; 1444 default: 1445 goto no_ticket; 1446 } 1447 /* Read timestamp. */ 1448 temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len); 1449 if (temp < 0) 1450 goto no_ticket; 1451 parsed_session_ticket->timestamp = (PRUint32)temp; 1452 1453 /* Read server name */ 1454 nameType = 1455 ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); 1456 if (nameType != TLS_STE_NO_SERVER_NAME) { 1457 SECItem name_item; 1458 rv = ssl3_ConsumeHandshakeVariable(ss, &name_item, 2, &buffer, 1459 &buffer_len); 1460 if (rv != SECSuccess) goto no_ticket; 1461 rv = SECITEM_CopyItem(NULL, &parsed_session_ticket->srvName, 1462 &name_item); 1463 if (rv != SECSuccess) goto no_ticket; 1464 parsed_session_ticket->srvName.type = nameType; 1465 } 1466 1467 /* Done parsing. Check that all bytes have been consumed. */ 1468 if (buffer_len != padding_length) 1469 goto no_ticket; 1470 1471 /* Use the ticket if it has not expired, otherwise free the allocated 1472 * memory since the ticket is of no use. 1473 */ 1474 if (parsed_session_ticket->timestamp != 0 && 1475 parsed_session_ticket->timestamp + 1476 TLS_EX_SESS_TICKET_LIFETIME_HINT > ssl_Time()) { 1477 1478 sid = ssl3_NewSessionID(ss, PR_TRUE); 1479 if (sid == NULL) { 1480 rv = SECFailure; 1481 goto loser; 1482 } 1483 1484 /* Copy over parameters. */ 1485 sid->version = parsed_session_ticket->ssl_version; 1486 sid->u.ssl3.cipherSuite = parsed_session_ticket->cipher_suite; 1487 sid->u.ssl3.compression = parsed_session_ticket->compression_method; 1488 sid->authAlgorithm = parsed_session_ticket->authAlgorithm; 1489 sid->authKeyBits = parsed_session_ticket->authKeyBits; 1490 sid->keaType = parsed_session_ticket->keaType; 1491 sid->keaKeyBits = parsed_session_ticket->keaKeyBits; 1492 1493 /* Copy master secret. */ 1494 if (ss->opt.bypassPKCS11 && 1495 parsed_session_ticket->ms_is_wrapped) 1496 goto no_ticket; 1497 if (parsed_session_ticket->ms_length > 1498 sizeof(sid->u.ssl3.keys.wrapped_master_secret)) 1499 goto no_ticket; 1500 PORT_Memcpy(sid->u.ssl3.keys.wrapped_master_secret, 1501 parsed_session_ticket->master_secret, 1502 parsed_session_ticket->ms_length); 1503 sid->u.ssl3.keys.wrapped_master_secret_len = 1504 parsed_session_ticket->ms_length; 1505 sid->u.ssl3.exchKeyType = parsed_session_ticket->exchKeyType; 1506 sid->u.ssl3.masterWrapMech = parsed_session_ticket->msWrapMech; 1507 sid->u.ssl3.keys.msIsWrapped = 1508 parsed_session_ticket->ms_is_wrapped; 1509 sid->u.ssl3.masterValid = PR_TRUE; 1510 sid->u.ssl3.keys.resumable = PR_TRUE; 1511 1512 /* Copy over client cert from session ticket if there is one. */ 1513 if (parsed_session_ticket->peer_cert.data != NULL) { 1514 if (sid->peerCert != NULL) 1515 CERT_DestroyCertificate(sid->peerCert); 1516 sid->peerCert = CERT_NewTempCertificate(ss->dbHandle, 1517 &parsed_session_ticket->peer_cert, NULL, PR_FALSE, PR_TRUE); 1518 if (sid->peerCert == NULL) { 1519 rv = SECFailure; 1520 goto loser; 1521 } 1522 } 1523 if (parsed_session_ticket->srvName.data != NULL) { 1524 sid->u.ssl3.srvName = parsed_session_ticket->srvName; 1525 } 1526 ss->statelessResume = PR_TRUE; 1527 ss->sec.ci.sid = sid; 1528 } 1529 } 1530 1531 if (0) { 1532no_ticket: 1533 SSL_DBG(("%d: SSL[%d]: Session ticket parsing failed.", 1534 SSL_GETPID(), ss->fd)); 1535 ssl3stats = SSL_GetStatistics(); 1536 SSL_AtomicIncrementLong(& ssl3stats->hch_sid_ticket_parse_failures ); 1537 } 1538 rv = SECSuccess; 1539 1540loser: 1541 /* ss->sec.ci.sid == sid if it did NOT come here via goto statement 1542 * in that case do not free sid 1543 */ 1544 if (sid && (ss->sec.ci.sid != sid)) { 1545 ssl_FreeSID(sid); 1546 sid = NULL; 1547 } 1548 if (decrypted_state != NULL) { 1549 SECITEM_FreeItem(decrypted_state, PR_TRUE); 1550 decrypted_state = NULL; 1551 } 1552 1553 if (parsed_session_ticket != NULL) { 1554 if (parsed_session_ticket->peer_cert.data) { 1555 SECITEM_FreeItem(&parsed_session_ticket->peer_cert, PR_FALSE); 1556 } 1557 PORT_ZFree(parsed_session_ticket, sizeof(SessionTicket)); 1558 } 1559 1560 return rv; 1561} 1562 1563/* 1564 * Read bytes. Using this function means the SECItem structure 1565 * cannot be freed. The caller is expected to call this function 1566 * on a shallow copy of the structure. 1567 */ 1568static SECStatus 1569ssl3_ConsumeFromItem(SECItem *item, unsigned char **buf, PRUint32 bytes) 1570{ 1571 if (bytes > item->len) 1572 return SECFailure; 1573 1574 *buf = item->data; 1575 item->data += bytes; 1576 item->len -= bytes; 1577 return SECSuccess; 1578} 1579 1580static SECStatus 1581ssl3_ParseEncryptedSessionTicket(sslSocket *ss, SECItem *data, 1582 EncryptedSessionTicket *enc_session_ticket) 1583{ 1584 if (ssl3_ConsumeFromItem(data, &enc_session_ticket->key_name, 1585 SESS_TICKET_KEY_NAME_LEN) != SECSuccess) 1586 return SECFailure; 1587 if (ssl3_ConsumeFromItem(data, &enc_session_ticket->iv, 1588 AES_BLOCK_SIZE) != SECSuccess) 1589 return SECFailure; 1590 if (ssl3_ConsumeHandshakeVariable(ss, &enc_session_ticket->encrypted_state, 1591 2, &data->data, &data->len) != SECSuccess) 1592 return SECFailure; 1593 if (ssl3_ConsumeFromItem(data, &enc_session_ticket->mac, 1594 TLS_EX_SESS_TICKET_MAC_LENGTH) != SECSuccess) 1595 return SECFailure; 1596 if (data->len != 0) /* Make sure that we have consumed all bytes. */ 1597 return SECFailure; 1598 1599 return SECSuccess; 1600} 1601 1602/* go through hello extensions in buffer "b". 1603 * For each one, find the extension handler in the table, and 1604 * if present, invoke that handler. 1605 * Servers ignore any extensions with unknown extension types. 1606 * Clients reject any extensions with unadvertised extension types. 1607 */ 1608SECStatus 1609ssl3_HandleHelloExtensions(sslSocket *ss, SSL3Opaque **b, PRUint32 *length) 1610{ 1611 const ssl3HelloExtensionHandler * handlers; 1612 1613 if (ss->sec.isServer) { 1614 handlers = clientHelloHandlers; 1615 } else if (ss->version > SSL_LIBRARY_VERSION_3_0) { 1616 handlers = serverHelloHandlersTLS; 1617 } else { 1618 handlers = serverHelloHandlersSSL3; 1619 } 1620 1621 while (*length) { 1622 const ssl3HelloExtensionHandler * handler; 1623 SECStatus rv; 1624 PRInt32 extension_type; 1625 SECItem extension_data; 1626 1627 /* Get the extension's type field */ 1628 extension_type = ssl3_ConsumeHandshakeNumber(ss, 2, b, length); 1629 if (extension_type < 0) /* failure to decode extension_type */ 1630 return SECFailure; /* alert already sent */ 1631 1632 /* get the data for this extension, so we can pass it or skip it. */ 1633 rv = ssl3_ConsumeHandshakeVariable(ss, &extension_data, 2, b, length); 1634 if (rv != SECSuccess) 1635 return rv; 1636 1637 /* Check whether the server sent an extension which was not advertised 1638 * in the ClientHello. 1639 */ 1640 if (!ss->sec.isServer && 1641 !ssl3_ClientExtensionAdvertised(ss, extension_type)) 1642 return SECFailure; /* TODO: send unsupported_extension alert */ 1643 1644 /* Check whether an extension has been sent multiple times. */ 1645 if (ssl3_ExtensionNegotiated(ss, extension_type)) 1646 return SECFailure; 1647 1648 /* find extension_type in table of Hello Extension Handlers */ 1649 for (handler = handlers; handler->ex_type >= 0; handler++) { 1650 /* if found, call this handler */ 1651 if (handler->ex_type == extension_type) { 1652 rv = (*handler->ex_handler)(ss, (PRUint16)extension_type, 1653 &extension_data); 1654 /* Ignore this result */ 1655 /* Treat all bad extensions as unrecognized types. */ 1656 break; 1657 } 1658 } 1659 } 1660 return SECSuccess; 1661} 1662 1663/* Add a callback function to the table of senders of server hello extensions. 1664 */ 1665SECStatus 1666ssl3_RegisterServerHelloExtensionSender(sslSocket *ss, PRUint16 ex_type, 1667 ssl3HelloExtensionSenderFunc cb) 1668{ 1669 int i; 1670 ssl3HelloExtensionSender *sender = &ss->xtnData.serverSenders[0]; 1671 1672 for (i = 0; i < SSL_MAX_EXTENSIONS; ++i, ++sender) { 1673 if (!sender->ex_sender) { 1674 sender->ex_type = ex_type; 1675 sender->ex_sender = cb; 1676 return SECSuccess; 1677 } 1678 /* detect duplicate senders */ 1679 PORT_Assert(sender->ex_type != ex_type); 1680 if (sender->ex_type == ex_type) { 1681 /* duplicate */ 1682 break; 1683 } 1684 } 1685 PORT_Assert(i < SSL_MAX_EXTENSIONS); /* table needs to grow */ 1686 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1687 return SECFailure; 1688} 1689 1690/* call each of the extension senders and return the accumulated length */ 1691PRInt32 1692ssl3_CallHelloExtensionSenders(sslSocket *ss, PRBool append, PRUint32 maxBytes, 1693 const ssl3HelloExtensionSender *sender) 1694{ 1695 PRInt32 total_exten_len = 0; 1696 int i; 1697 1698 if (!sender) { 1699 sender = ss->version > SSL_LIBRARY_VERSION_3_0 ? 1700 &clientHelloSendersTLS[0] : &clientHelloSendersSSL3[0]; 1701 } 1702 1703 for (i = 0; i < SSL_MAX_EXTENSIONS; ++i, ++sender) { 1704 if (sender->ex_sender) { 1705 PRInt32 extLen = (*sender->ex_sender)(ss, append, maxBytes); 1706 if (extLen < 0) 1707 return -1; 1708 maxBytes -= extLen; 1709 total_exten_len += extLen; 1710 } 1711 } 1712 return total_exten_len; 1713} 1714 1715 1716/* Extension format: 1717 * Extension number: 2 bytes 1718 * Extension length: 2 bytes 1719 * Verify Data Length: 1 byte 1720 * Verify Data (TLS): 12 bytes (client) or 24 bytes (server) 1721 * Verify Data (SSL): 36 bytes (client) or 72 bytes (server) 1722 */ 1723static PRInt32 1724ssl3_SendRenegotiationInfoXtn( 1725 sslSocket * ss, 1726 PRBool append, 1727 PRUint32 maxBytes) 1728{ 1729 PRInt32 len, needed; 1730 1731 /* In draft-ietf-tls-renegotiation-03, it is NOT RECOMMENDED to send 1732 * both the SCSV and the empty RI, so when we send SCSV in 1733 * the initial handshake, we don't also send RI. 1734 */ 1735 if (!ss || ss->ssl3.hs.sendingSCSV) 1736 return 0; 1737 len = !ss->firstHsDone ? 0 : 1738 (ss->sec.isServer ? ss->ssl3.hs.finishedBytes * 2 1739 : ss->ssl3.hs.finishedBytes); 1740 needed = 5 + len; 1741 if (append && maxBytes >= needed) { 1742 SECStatus rv; 1743 /* extension_type */ 1744 rv = ssl3_AppendHandshakeNumber(ss, ssl_renegotiation_info_xtn, 2); 1745 if (rv != SECSuccess) return -1; 1746 /* length of extension_data */ 1747 rv = ssl3_AppendHandshakeNumber(ss, len + 1, 2); 1748 if (rv != SECSuccess) return -1; 1749 /* verify_Data from previous Finished message(s) */ 1750 rv = ssl3_AppendHandshakeVariable(ss, 1751 ss->ssl3.hs.finishedMsgs.data, len, 1); 1752 if (rv != SECSuccess) return -1; 1753 if (!ss->sec.isServer) { 1754 TLSExtensionData *xtnData = &ss->xtnData; 1755 xtnData->advertised[xtnData->numAdvertised++] = 1756 ssl_renegotiation_info_xtn; 1757 } 1758 } 1759 return needed; 1760} 1761 1762/* This function runs in both the client and server. */ 1763static SECStatus 1764ssl3_HandleRenegotiationInfoXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data) 1765{ 1766 SECStatus rv = SECSuccess; 1767 PRUint32 len = 0; 1768 1769 if (ss->firstHsDone) { 1770 len = ss->sec.isServer ? ss->ssl3.hs.finishedBytes 1771 : ss->ssl3.hs.finishedBytes * 2; 1772 } 1773 if (data->len != 1 + len || 1774 data->data[0] != len || (len && 1775 NSS_SecureMemcmp(ss->ssl3.hs.finishedMsgs.data, 1776 data->data + 1, len))) { 1777 /* Can we do this here? Or, must we arrange for the caller to do it? */ 1778 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure); 1779 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); 1780 return SECFailure; 1781 } 1782 /* remember that we got this extension and it was correct. */ 1783 ss->peerRequestedProtection = 1; 1784 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type; 1785 if (ss->sec.isServer) { 1786 /* prepare to send back the appropriate response */ 1787 rv = ssl3_RegisterServerHelloExtensionSender(ss, ex_type, 1788 ssl3_SendRenegotiationInfoXtn); 1789 } 1790 return rv; 1791} 1792 1793static PRInt32 1794ssl3_SendUseSRTPXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes) 1795{ 1796 PRUint32 ext_data_len; 1797 PRInt16 i; 1798 SECStatus rv; 1799 1800 if (!ss) 1801 return 0; 1802 1803 if (!ss->sec.isServer) { 1804 /* Client side */ 1805 1806 if (!IS_DTLS(ss) || !ss->ssl3.dtlsSRTPCipherCount) 1807 return 0; /* Not relevant */ 1808 1809 ext_data_len = 2 + 2 * ss->ssl3.dtlsSRTPCipherCount + 1; 1810 1811 if (append && maxBytes >= 4 + ext_data_len) { 1812 /* Extension type */ 1813 rv = ssl3_AppendHandshakeNumber(ss, ssl_use_srtp_xtn, 2); 1814 if (rv != SECSuccess) return -1; 1815 /* Length of extension data */ 1816 rv = ssl3_AppendHandshakeNumber(ss, ext_data_len, 2); 1817 if (rv != SECSuccess) return -1; 1818 /* Length of the SRTP cipher list */ 1819 rv = ssl3_AppendHandshakeNumber(ss, 1820 2 * ss->ssl3.dtlsSRTPCipherCount, 1821 2); 1822 if (rv != SECSuccess) return -1; 1823 /* The SRTP ciphers */ 1824 for (i = 0; i < ss->ssl3.dtlsSRTPCipherCount; i++) { 1825 rv = ssl3_AppendHandshakeNumber(ss, 1826 ss->ssl3.dtlsSRTPCiphers[i], 1827 2); 1828 } 1829 /* Empty MKI value */ 1830 ssl3_AppendHandshakeVariable(ss, NULL, 0, 1); 1831 1832 ss->xtnData.advertised[ss->xtnData.numAdvertised++] = 1833 ssl_use_srtp_xtn; 1834 } 1835 1836 return 4 + ext_data_len; 1837 } 1838 1839 /* Server side */ 1840 if (append && maxBytes >= 9) { 1841 /* Extension type */ 1842 rv = ssl3_AppendHandshakeNumber(ss, ssl_use_srtp_xtn, 2); 1843 if (rv != SECSuccess) return -1; 1844 /* Length of extension data */ 1845 rv = ssl3_AppendHandshakeNumber(ss, 5, 2); 1846 if (rv != SECSuccess) return -1; 1847 /* Length of the SRTP cipher list */ 1848 rv = ssl3_AppendHandshakeNumber(ss, 2, 2); 1849 if (rv != SECSuccess) return -1; 1850 /* The selected cipher */ 1851 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.dtlsSRTPCipherSuite, 2); 1852 if (rv != SECSuccess) return -1; 1853 /* Empty MKI value */ 1854 ssl3_AppendHandshakeVariable(ss, NULL, 0, 1); 1855 } 1856 1857 return 9; 1858} 1859 1860static SECStatus 1861ssl3_HandleUseSRTPXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data) 1862{ 1863 SECStatus rv; 1864 SECItem ciphers = {siBuffer, NULL, 0}; 1865 PRInt16 i; 1866 PRInt16 j; 1867 PRUint16 cipher = 0; 1868 PRBool found = PR_FALSE; 1869 SECItem litem; 1870 1871 if (!ss->sec.isServer) { 1872 /* Client side */ 1873 if (!data->data || !data->len) { 1874 /* malformed */ 1875 return SECFailure; 1876 } 1877 1878 /* Get the cipher list */ 1879 rv = ssl3_ConsumeHandshakeVariable(ss, &ciphers, 2, 1880 &data->data, &data->len); 1881 if (rv != SECSuccess) { 1882 return SECFailure; 1883 } 1884 /* Now check that the number of ciphers listed is 1 (len = 2) */ 1885 if (ciphers.len != 2) { 1886 return SECFailure; 1887 } 1888 1889 /* Get the selected cipher */ 1890 cipher = (ciphers.data[0] << 8) | ciphers.data[1]; 1891 1892 /* Now check that this is one of the ciphers we offered */ 1893 for (i = 0; i < ss->ssl3.dtlsSRTPCipherCount; i++) { 1894 if (cipher == ss->ssl3.dtlsSRTPCiphers[i]) { 1895 found = PR_TRUE; 1896 break; 1897 } 1898 } 1899 1900 if (!found) { 1901 return SECFailure; 1902 } 1903 1904 /* Get the srtp_mki value */ 1905 rv = ssl3_ConsumeHandshakeVariable(ss, &litem, 1, 1906 &data->data, &data->len); 1907 if (rv != SECSuccess) { 1908 return SECFailure; 1909 } 1910 1911 /* We didn't offer an MKI, so this must be 0 length */ 1912 /* XXX RFC 5764 Section 4.1.3 says: 1913 * If the client detects a nonzero-length MKI in the server's 1914 * response that is different than the one the client offered, 1915 * then the client MUST abort the handshake and SHOULD send an 1916 * invalid_parameter alert. 1917 * 1918 * Due to a limitation of the ssl3_HandleHelloExtensions function, 1919 * returning SECFailure here won't abort the handshake. It will 1920 * merely cause the use_srtp extension to be not negotiated. We 1921 * should fix this. See NSS bug 753136. 1922 */ 1923 if (litem.len != 0) { 1924 return SECFailure; 1925 } 1926 1927 if (data->len != 0) { 1928 /* malformed */ 1929 return SECFailure; 1930 } 1931 1932 /* OK, this looks fine. */ 1933 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ssl_use_srtp_xtn; 1934 ss->ssl3.dtlsSRTPCipherSuite = cipher; 1935 return SECSuccess; 1936 } 1937 1938 /* Server side */ 1939 if (!IS_DTLS(ss) || !ss->ssl3.dtlsSRTPCipherCount) { 1940 /* Ignore the extension if we aren't doing DTLS or no DTLS-SRTP 1941 * preferences have been set. */ 1942 return SECSuccess; 1943 } 1944 1945 if (!data->data || data->len < 5) { 1946 /* malformed */ 1947 return SECFailure; 1948 } 1949 1950 /* Get the cipher list */ 1951 rv = ssl3_ConsumeHandshakeVariable(ss, &ciphers, 2, 1952 &data->data, &data->len); 1953 if (rv != SECSuccess) { 1954 return SECFailure; 1955 } 1956 /* Check that the list is even length */ 1957 if (ciphers.len % 2) { 1958 return SECFailure; 1959 } 1960 1961 /* Walk through the offered list and pick the most preferred of our 1962 * ciphers, if any */ 1963 for (i = 0; !found && i < ss->ssl3.dtlsSRTPCipherCount; i++) { 1964 for (j = 0; j + 1 < ciphers.len; j += 2) { 1965 cipher = (ciphers.data[j] << 8) | ciphers.data[j + 1]; 1966 if (cipher == ss->ssl3.dtlsSRTPCiphers[i]) { 1967 found = PR_TRUE; 1968 break; 1969 } 1970 } 1971 } 1972 1973 /* Get the srtp_mki value */ 1974 rv = ssl3_ConsumeHandshakeVariable(ss, &litem, 1, &data->data, &data->len); 1975 if (rv != SECSuccess) { 1976 return SECFailure; 1977 } 1978 1979 if (data->len != 0) { 1980 return SECFailure; /* Malformed */ 1981 } 1982 1983 /* Now figure out what to do */ 1984 if (!found) { 1985 /* No matching ciphers */ 1986 return SECSuccess; 1987 } 1988 1989 /* OK, we have a valid cipher and we've selected it */ 1990 ss->ssl3.dtlsSRTPCipherSuite = cipher; 1991 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ssl_use_srtp_xtn; 1992 1993 return ssl3_RegisterServerHelloExtensionSender(ss, ssl_use_srtp_xtn, 1994 ssl3_SendUseSRTPXtn); 1995} 1996