PageRenderTime 95ms CodeModel.GetById 10ms app.highlight 74ms RepoModel.GetById 1ms app.codeStats 1ms

/security/nss/lib/ssl/ssl3ext.c

http://github.com/zpao/v8monkey
C | 1649 lines | 1230 code | 175 blank | 244 comment | 378 complexity | f231d734ef3053f506af435dfc1388c7 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   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.20 2011/11/16 19:12:35 kaie%kuix.de Exp $ */
  45
  46#include "nssrenam.h"
  47#include "nss.h"
  48#include "ssl.h"
  49#include "sslproto.h"
  50#include "sslimpl.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_ServerHandleNextProtoNegoXtn(sslSocket *ss,
  84			PRUint16 ex_type, SECItem *data);
  85static PRInt32 ssl3_ClientSendNextProtoNegoXtn(sslSocket *ss, PRBool append,
  86					       PRUint32 maxBytes);
  87
  88/*
  89 * Write bytes.  Using this function means the SECItem structure
  90 * cannot be freed.  The caller is expected to call this function
  91 * on a shallow copy of the structure.
  92 */
  93static SECStatus
  94ssl3_AppendToItem(SECItem *item, const unsigned char *buf, PRUint32 bytes)
  95{
  96    if (bytes > item->len)
  97	return SECFailure;
  98
  99    PORT_Memcpy(item->data, buf, bytes);
 100    item->data += bytes;
 101    item->len -= bytes;
 102    return SECSuccess;
 103}
 104
 105/*
 106 * Write a number in network byte order. Using this function means the
 107 * SECItem structure cannot be freed.  The caller is expected to call
 108 * this function on a shallow copy of the structure.
 109 */
 110static SECStatus
 111ssl3_AppendNumberToItem(SECItem *item, PRUint32 num, PRInt32 lenSize)
 112{
 113    SECStatus rv;
 114    uint8     b[4];
 115    uint8 *   p = b;
 116
 117    switch (lenSize) {
 118    case 4:
 119	*p++ = (uint8) (num >> 24);
 120    case 3:
 121	*p++ = (uint8) (num >> 16);
 122    case 2:
 123	*p++ = (uint8) (num >> 8);
 124    case 1:
 125	*p = (uint8) num;
 126    }
 127    rv = ssl3_AppendToItem(item, &b[0], lenSize);
 128    return rv;
 129}
 130
 131static SECStatus ssl3_SessionTicketShutdown(void* appData, void* nssData)
 132{
 133    if (session_ticket_enc_key_pkcs11) {
 134	PK11_FreeSymKey(session_ticket_enc_key_pkcs11);
 135	session_ticket_enc_key_pkcs11 = NULL;
 136    }
 137    if (session_ticket_mac_key_pkcs11) {
 138	PK11_FreeSymKey(session_ticket_mac_key_pkcs11);
 139	session_ticket_mac_key_pkcs11 = NULL;
 140    }
 141    PORT_Memset(&generate_session_keys_once, 0,
 142	sizeof(generate_session_keys_once));
 143    return SECSuccess;
 144}
 145
 146
 147static PRStatus
 148ssl3_GenerateSessionTicketKeysPKCS11(void *data)
 149{
 150    SECStatus rv;
 151    sslSocket *ss = (sslSocket *)data;
 152    SECKEYPrivateKey *svrPrivKey = ss->serverCerts[kt_rsa].SERVERKEY;
 153    SECKEYPublicKey *svrPubKey = ss->serverCerts[kt_rsa].serverKeyPair->pubKey;
 154
 155    if (svrPrivKey == NULL || svrPubKey == NULL) {
 156	SSL_DBG(("%d: SSL[%d]: Pub or priv key(s) is NULL.",
 157			SSL_GETPID(), ss->fd));
 158	goto loser;
 159    }
 160
 161    /* Get a copy of the session keys from shared memory. */
 162    PORT_Memcpy(key_name, SESS_TICKET_KEY_NAME_PREFIX,
 163	sizeof(SESS_TICKET_KEY_NAME_PREFIX));
 164    if (!ssl_GetSessionTicketKeysPKCS11(svrPrivKey, svrPubKey,
 165	    ss->pkcs11PinArg, &key_name[SESS_TICKET_KEY_NAME_PREFIX_LEN],
 166	    &session_ticket_enc_key_pkcs11, &session_ticket_mac_key_pkcs11))
 167	return PR_FAILURE;
 168
 169    rv = NSS_RegisterShutdown(ssl3_SessionTicketShutdown, NULL);
 170    if (rv != SECSuccess)
 171	goto loser;
 172
 173    return PR_SUCCESS;
 174
 175loser:
 176    ssl3_SessionTicketShutdown(NULL, NULL);
 177    return PR_FAILURE;
 178}
 179
 180static SECStatus
 181ssl3_GetSessionTicketKeysPKCS11(sslSocket *ss, PK11SymKey **aes_key,
 182                                PK11SymKey **mac_key)
 183{
 184    if (PR_CallOnceWithArg(&generate_session_keys_once,
 185	    ssl3_GenerateSessionTicketKeysPKCS11, ss) != PR_SUCCESS)
 186	return SECFailure;
 187
 188    if (session_ticket_enc_key_pkcs11 == NULL ||
 189	session_ticket_mac_key_pkcs11 == NULL)
 190	return SECFailure;
 191
 192    *aes_key = session_ticket_enc_key_pkcs11;
 193    *mac_key = session_ticket_mac_key_pkcs11;
 194    return SECSuccess;
 195}
 196
 197static PRStatus
 198ssl3_GenerateSessionTicketKeys(void)
 199{
 200    PORT_Memcpy(key_name, SESS_TICKET_KEY_NAME_PREFIX,
 201	sizeof(SESS_TICKET_KEY_NAME_PREFIX));
 202
 203    if (!ssl_GetSessionTicketKeys(&key_name[SESS_TICKET_KEY_NAME_PREFIX_LEN],
 204	    session_ticket_enc_key, session_ticket_mac_key))
 205	return PR_FAILURE;
 206
 207    session_ticket_keys_initialized = PR_TRUE;
 208    return PR_SUCCESS;
 209}
 210
 211static SECStatus
 212ssl3_GetSessionTicketKeys(const unsigned char **aes_key,
 213    PRUint32 *aes_key_length, const unsigned char **mac_key,
 214    PRUint32 *mac_key_length)
 215{
 216    if (PR_CallOnce(&generate_session_keys_once,
 217	    ssl3_GenerateSessionTicketKeys) != SECSuccess)
 218	return SECFailure;
 219
 220    if (!session_ticket_keys_initialized)
 221	return SECFailure;
 222
 223    *aes_key = session_ticket_enc_key;
 224    *aes_key_length = sizeof(session_ticket_enc_key);
 225    *mac_key = session_ticket_mac_key;
 226    *mac_key_length = sizeof(session_ticket_mac_key);
 227
 228    return SECSuccess;
 229}
 230
 231/* Table of handlers for received TLS hello extensions, one per extension.
 232 * In the second generation, this table will be dynamic, and functions
 233 * will be registered here.
 234 */
 235/* This table is used by the server, to handle client hello extensions. */
 236static const ssl3HelloExtensionHandler clientHelloHandlers[] = {
 237    { ssl_server_name_xtn,        &ssl3_HandleServerNameXtn },
 238#ifdef NSS_ENABLE_ECC
 239    { ssl_elliptic_curves_xtn,    &ssl3_HandleSupportedCurvesXtn },
 240    { ssl_ec_point_formats_xtn,   &ssl3_HandleSupportedPointFormatsXtn },
 241#endif
 242    { ssl_session_ticket_xtn,     &ssl3_ServerHandleSessionTicketXtn },
 243    { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn },
 244    { ssl_next_proto_neg_xtn,     &ssl3_ServerHandleNextProtoNegoXtn },
 245    { -1, NULL }
 246};
 247
 248/* These two tables are used by the client, to handle server hello
 249 * extensions. */
 250static const ssl3HelloExtensionHandler serverHelloHandlersTLS[] = {
 251    { ssl_server_name_xtn,        &ssl3_HandleServerNameXtn },
 252    /* TODO: add a handler for ssl_ec_point_formats_xtn */
 253    { ssl_session_ticket_xtn,     &ssl3_ClientHandleSessionTicketXtn },
 254    { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn },
 255    { ssl_next_proto_neg_xtn,     &ssl3_ClientHandleNextProtoNegoXtn },
 256    { -1, NULL }
 257};
 258
 259static const ssl3HelloExtensionHandler serverHelloHandlersSSL3[] = {
 260    { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn },
 261    { -1, NULL }
 262};
 263
 264/* Tables of functions to format TLS hello extensions, one function per
 265 * extension.
 266 * These static tables are for the formatting of client hello extensions.
 267 * The server's table of hello senders is dynamic, in the socket struct,
 268 * and sender functions are registered there.
 269 */
 270static const 
 271ssl3HelloExtensionSender clientHelloSendersTLS[SSL_MAX_EXTENSIONS] = {
 272    { ssl_server_name_xtn,        &ssl3_SendServerNameXtn        },
 273    { ssl_renegotiation_info_xtn, &ssl3_SendRenegotiationInfoXtn },
 274#ifdef NSS_ENABLE_ECC
 275    { ssl_elliptic_curves_xtn,    &ssl3_SendSupportedCurvesXtn },
 276    { ssl_ec_point_formats_xtn,   &ssl3_SendSupportedPointFormatsXtn },
 277#endif
 278    { ssl_session_ticket_xtn,     &ssl3_SendSessionTicketXtn },
 279    { ssl_next_proto_neg_xtn,     &ssl3_ClientSendNextProtoNegoXtn }
 280    /* any extra entries will appear as { 0, NULL }    */
 281};
 282
 283static const 
 284ssl3HelloExtensionSender clientHelloSendersSSL3[SSL_MAX_EXTENSIONS] = {
 285    { ssl_renegotiation_info_xtn, &ssl3_SendRenegotiationInfoXtn }
 286    /* any extra entries will appear as { 0, NULL }    */
 287};
 288
 289static PRBool
 290arrayContainsExtension(const PRUint16 *array, PRUint32 len, PRUint16 ex_type)
 291{
 292    int i;
 293    for (i = 0; i < len; i++) {
 294	if (ex_type == array[i])
 295	    return PR_TRUE;
 296    }
 297    return PR_FALSE;
 298}
 299
 300PRBool
 301ssl3_ExtensionNegotiated(sslSocket *ss, PRUint16 ex_type) {
 302    TLSExtensionData *xtnData = &ss->xtnData;
 303    return arrayContainsExtension(xtnData->negotiated,
 304	                          xtnData->numNegotiated, ex_type);
 305}
 306
 307static PRBool
 308ssl3_ClientExtensionAdvertised(sslSocket *ss, PRUint16 ex_type) {
 309    TLSExtensionData *xtnData = &ss->xtnData;
 310    return arrayContainsExtension(xtnData->advertised,
 311	                          xtnData->numAdvertised, ex_type);
 312}
 313
 314/* Format an SNI extension, using the name from the socket's URL,
 315 * unless that name is a dotted decimal string.
 316 * Used by client and server.
 317 */
 318PRInt32
 319ssl3_SendServerNameXtn(sslSocket * ss, PRBool append,
 320                       PRUint32 maxBytes)
 321{
 322    SECStatus rv;
 323    if (!ss)
 324    	return 0;
 325    if (!ss->sec.isServer) {
 326        PRUint32 len;
 327        PRNetAddr netAddr;
 328        
 329        /* must have a hostname */
 330        if (!ss->url || !ss->url[0])
 331            return 0;
 332        /* must not be an IPv4 or IPv6 address */
 333        if (PR_SUCCESS == PR_StringToNetAddr(ss->url, &netAddr)) {
 334            /* is an IP address (v4 or v6) */
 335            return 0;
 336        }
 337        len  = PORT_Strlen(ss->url);
 338        if (append && maxBytes >= len + 9) {
 339            /* extension_type */
 340            rv = ssl3_AppendHandshakeNumber(ss, ssl_server_name_xtn, 2); 
 341            if (rv != SECSuccess) return -1;
 342            /* length of extension_data */
 343            rv = ssl3_AppendHandshakeNumber(ss, len + 5, 2); 
 344            if (rv != SECSuccess) return -1;
 345            /* length of server_name_list */
 346            rv = ssl3_AppendHandshakeNumber(ss, len + 3, 2);
 347            if (rv != SECSuccess) return -1;
 348            /* Name Type (sni_host_name) */
 349            rv = ssl3_AppendHandshake(ss,       "\0",    1);
 350            if (rv != SECSuccess) return -1;
 351            /* HostName (length and value) */
 352            rv = ssl3_AppendHandshakeVariable(ss, (PRUint8 *)ss->url, len, 2);
 353            if (rv != SECSuccess) return -1;
 354            if (!ss->sec.isServer) {
 355                TLSExtensionData *xtnData = &ss->xtnData;
 356                xtnData->advertised[xtnData->numAdvertised++] = 
 357		    ssl_server_name_xtn;
 358            }
 359        }
 360        return len + 9;
 361    }
 362    /* Server side */
 363    if (append && maxBytes >= 4) {
 364        rv = ssl3_AppendHandshakeNumber(ss, ssl_server_name_xtn, 2);
 365        if (rv != SECSuccess)  return -1;
 366        /* length of extension_data */
 367        rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
 368        if (rv != SECSuccess) return -1;
 369    }
 370    return 4;
 371}
 372
 373/* handle an incoming SNI extension, by ignoring it. */
 374SECStatus
 375ssl3_HandleServerNameXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data)
 376{
 377    SECItem *names = NULL;
 378    PRUint32 listCount = 0, namesPos = 0, i;
 379    TLSExtensionData *xtnData = &ss->xtnData;
 380    SECItem  ldata;
 381    PRInt32  listLenBytes = 0;
 382
 383    if (!ss->sec.isServer) {
 384        /* Verify extension_data is empty. */
 385        if (data->data || data->len ||
 386            !ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) {
 387            /* malformed or was not initiated by the client.*/
 388            return SECFailure;
 389        }
 390        return SECSuccess;
 391    }
 392
 393    /* Server side - consume client data and register server sender. */
 394    /* do not parse the data if don't have user extension handling function. */
 395    if (!ss->sniSocketConfig) {
 396        return SECSuccess;
 397    }
 398    /* length of server_name_list */
 399    listLenBytes = ssl3_ConsumeHandshakeNumber(ss, 2, &data->data, &data->len); 
 400    if (listLenBytes == 0 || listLenBytes != data->len) {
 401        return SECFailure;
 402    }
 403    ldata = *data;
 404    /* Calculate the size of the array.*/
 405    while (listLenBytes > 0) {
 406        SECItem litem;
 407        SECStatus rv;
 408        PRInt32  type;
 409        /* Name Type (sni_host_name) */
 410        type = ssl3_ConsumeHandshakeNumber(ss, 1, &ldata.data, &ldata.len); 
 411        if (!ldata.len) {
 412            return SECFailure;
 413        }
 414        rv = ssl3_ConsumeHandshakeVariable(ss, &litem, 2, &ldata.data, &ldata.len);
 415        if (rv != SECSuccess) {
 416            return SECFailure;
 417        }
 418        /* Adjust total length for cunsumed item, item len and type.*/
 419        listLenBytes -= litem.len + 3;
 420        if (listLenBytes > 0 && !ldata.len) {
 421            return SECFailure;
 422        }
 423        listCount += 1;
 424    }
 425    if (!listCount) {
 426        return SECFailure;
 427    }
 428    names = PORT_ZNewArray(SECItem, listCount);
 429    if (!names) {
 430        return SECFailure;
 431    }
 432    for (i = 0;i < listCount;i++) {
 433        int j;
 434        PRInt32  type;
 435        SECStatus rv;
 436        PRBool nametypePresent = PR_FALSE;
 437        /* Name Type (sni_host_name) */
 438        type = ssl3_ConsumeHandshakeNumber(ss, 1, &data->data, &data->len); 
 439        /* Check if we have such type in the list */
 440        for (j = 0;j < listCount && names[j].data;j++) {
 441            if (names[j].type == type) {
 442                nametypePresent = PR_TRUE;
 443                break;
 444            }
 445        }
 446        /* HostName (length and value) */
 447        rv = ssl3_ConsumeHandshakeVariable(ss, &names[namesPos], 2,
 448                                           &data->data, &data->len);
 449        if (rv != SECSuccess) {
 450            goto loser;
 451        }
 452        if (nametypePresent == PR_FALSE) {
 453            namesPos += 1;
 454        }
 455    }
 456    /* Free old and set the new data. */
 457    if (xtnData->sniNameArr) {
 458        PORT_Free(ss->xtnData.sniNameArr);
 459    }
 460    xtnData->sniNameArr = names;
 461    xtnData->sniNameArrSize = namesPos;
 462    xtnData->negotiated[xtnData->numNegotiated++] = ssl_server_name_xtn;
 463
 464    return SECSuccess;
 465
 466loser:
 467    PORT_Free(names);
 468    return SECFailure;
 469}
 470        
 471/* Called by both clients and servers.
 472 * Clients sends a filled in session ticket if one is available, and otherwise
 473 * sends an empty ticket.  Servers always send empty tickets.
 474 */
 475PRInt32
 476ssl3_SendSessionTicketXtn(
 477			sslSocket * ss,
 478			PRBool      append,
 479			PRUint32    maxBytes)
 480{
 481    PRInt32 extension_length;
 482    NewSessionTicket *session_ticket = NULL;
 483
 484    /* Ignore the SessionTicket extension if processing is disabled. */
 485    if (!ss->opt.enableSessionTickets)
 486	return 0;
 487
 488    /* Empty extension length = extension_type (2-bytes) +
 489     * length(extension_data) (2-bytes)
 490     */
 491    extension_length = 4;
 492
 493    /* If we are a client then send a session ticket if one is availble.
 494     * Servers that support the extension and are willing to negotiate the
 495     * the extension always respond with an empty extension.
 496     */
 497    if (!ss->sec.isServer) {
 498	sslSessionID *sid = ss->sec.ci.sid;
 499	session_ticket = &sid->u.ssl3.sessionTicket;
 500	if (session_ticket->ticket.data) {
 501	    if (ss->xtnData.ticketTimestampVerified) {
 502		extension_length += session_ticket->ticket.len;
 503	    } else if (!append &&
 504		(session_ticket->ticket_lifetime_hint == 0 ||
 505		(session_ticket->ticket_lifetime_hint +
 506		    session_ticket->received_timestamp > ssl_Time()))) {
 507		extension_length += session_ticket->ticket.len;
 508		ss->xtnData.ticketTimestampVerified = PR_TRUE;
 509	    }
 510	}
 511    }
 512
 513    if (append && maxBytes >= extension_length) {
 514	SECStatus rv;
 515	/* extension_type */
 516        rv = ssl3_AppendHandshakeNumber(ss, ssl_session_ticket_xtn, 2);
 517        if (rv != SECSuccess)
 518	    goto loser;
 519	if (session_ticket && session_ticket->ticket.data &&
 520	    ss->xtnData.ticketTimestampVerified) {
 521	    rv = ssl3_AppendHandshakeVariable(ss, session_ticket->ticket.data,
 522		session_ticket->ticket.len, 2);
 523	    ss->xtnData.ticketTimestampVerified = PR_FALSE;
 524	} else {
 525	    rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
 526	}
 527        if (rv != SECSuccess)
 528	    goto loser;
 529
 530	if (!ss->sec.isServer) {
 531	    TLSExtensionData *xtnData = &ss->xtnData;
 532	    xtnData->advertised[xtnData->numAdvertised++] = 
 533		ssl_session_ticket_xtn;
 534	}
 535    } else if (maxBytes < extension_length) {
 536	PORT_Assert(0);
 537        return 0;
 538    }
 539    return extension_length;
 540
 541 loser:
 542    ss->xtnData.ticketTimestampVerified = PR_FALSE;
 543    return -1;
 544}
 545
 546/* handle an incoming Next Protocol Negotiation extension. */
 547static SECStatus
 548ssl3_ServerHandleNextProtoNegoXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data)
 549{
 550    if (ss->firstHsDone || data->len != 0) {
 551	/* Clients MUST send an empty NPN extension, if any. */
 552	PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
 553	return SECFailure;
 554    }
 555
 556    return SECSuccess;
 557}
 558
 559/* ssl3_ValidateNextProtoNego checks that the given block of data is valid: none
 560 * of the lengths may be 0 and the sum of the lengths must equal the length of
 561 * the block. */
 562SECStatus
 563ssl3_ValidateNextProtoNego(const unsigned char* data, unsigned int length)
 564{
 565    unsigned int offset = 0;
 566
 567    while (offset < length) {
 568	unsigned int newOffset = offset + 1 + (unsigned int) data[offset];
 569	/* Reject embedded nulls to protect against buggy applications that
 570	 * store protocol identifiers in null-terminated strings.
 571	 */
 572	if (newOffset > length || data[offset] == 0) {
 573	    PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
 574	    return SECFailure;
 575	}
 576	offset = newOffset;
 577    }
 578
 579    if (offset > length) {
 580	PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
 581	return SECFailure;
 582    }
 583
 584    return SECSuccess;
 585}
 586
 587static SECStatus
 588ssl3_ClientHandleNextProtoNegoXtn(sslSocket *ss, PRUint16 ex_type,
 589				  SECItem *data)
 590{
 591    SECStatus rv;
 592    unsigned char resultBuffer[255];
 593    SECItem result = { siBuffer, resultBuffer, 0 };
 594
 595    if (ss->firstHsDone) {
 596	PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
 597	return SECFailure;
 598    }
 599
 600    rv = ssl3_ValidateNextProtoNego(data->data, data->len);
 601    if (rv != SECSuccess)
 602	return rv;
 603
 604    /* ss->nextProtoCallback cannot normally be NULL if we negotiated the
 605     * extension. However, It is possible that an application erroneously
 606     * cleared the callback between the time we sent the ClientHello and now.
 607     */
 608    PORT_Assert(ss->nextProtoCallback != NULL);
 609    if (!ss->nextProtoCallback) {
 610	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
 611	return SECFailure;
 612    }
 613
 614    rv = ss->nextProtoCallback(ss->nextProtoArg, ss->fd, data->data, data->len,
 615			       result.data, &result.len, sizeof resultBuffer);
 616    if (rv != SECSuccess)
 617	return rv;
 618    /* If the callback wrote more than allowed to |result| it has corrupted our
 619     * stack. */
 620    if (result.len > sizeof result) {
 621	PORT_SetError(SEC_ERROR_OUTPUT_LEN);
 622	return SECFailure;
 623    }
 624
 625    SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE);
 626    return SECITEM_CopyItem(NULL, &ss->ssl3.nextProto, &result);
 627}
 628
 629static PRInt32
 630ssl3_ClientSendNextProtoNegoXtn(sslSocket * ss, PRBool append,
 631				PRUint32 maxBytes)
 632{
 633    PRInt32 extension_length;
 634
 635    /* Renegotiations do not send this extension. */
 636    if (!ss->nextProtoCallback || ss->firstHsDone) {
 637	return 0;
 638    }
 639
 640    extension_length = 4;
 641
 642    if (append && maxBytes >= extension_length) {
 643	SECStatus rv;
 644	rv = ssl3_AppendHandshakeNumber(ss, ssl_next_proto_neg_xtn, 2);
 645	if (rv != SECSuccess)
 646	    goto loser;
 647	rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
 648	if (rv != SECSuccess)
 649	    goto loser;
 650	ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
 651		ssl_next_proto_neg_xtn;
 652    } else if (maxBytes < extension_length) {
 653	return 0;
 654    }
 655
 656    return extension_length;
 657
 658loser:
 659    return -1;
 660}
 661
 662/*
 663 * NewSessionTicket
 664 * Called from ssl3_HandleFinished
 665 */
 666SECStatus
 667ssl3_SendNewSessionTicket(sslSocket *ss)
 668{
 669    int                  i;
 670    SECStatus            rv;
 671    NewSessionTicket     ticket;
 672    SECItem              plaintext;
 673    SECItem              plaintext_item = {0, NULL, 0};
 674    SECItem              ciphertext     = {0, NULL, 0};
 675    PRUint32             ciphertext_length;
 676    PRBool               ms_is_wrapped;
 677    unsigned char        wrapped_ms[SSL3_MASTER_SECRET_LENGTH];
 678    SECItem              ms_item = {0, NULL, 0};
 679    SSL3KEAType          effectiveExchKeyType = ssl_kea_null;
 680    PRUint32             padding_length;
 681    PRUint32             message_length;
 682    PRUint32             cert_length;
 683    uint8                length_buf[4];
 684    PRUint32             now;
 685    PK11SymKey          *aes_key_pkcs11;
 686    PK11SymKey          *mac_key_pkcs11;
 687    const unsigned char *aes_key;
 688    const unsigned char *mac_key;
 689    PRUint32             aes_key_length;
 690    PRUint32             mac_key_length;
 691    PRUint64             aes_ctx_buf[MAX_CIPHER_CONTEXT_LLONGS];
 692    AESContext          *aes_ctx;
 693    CK_MECHANISM_TYPE    cipherMech = CKM_AES_CBC;
 694    PK11Context         *aes_ctx_pkcs11;
 695    const SECHashObject *hashObj = NULL;
 696    PRUint64             hmac_ctx_buf[MAX_MAC_CONTEXT_LLONGS];
 697    HMACContext         *hmac_ctx;
 698    CK_MECHANISM_TYPE    macMech = CKM_SHA256_HMAC;
 699    PK11Context         *hmac_ctx_pkcs11;
 700    unsigned char        computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH];
 701    unsigned int         computed_mac_length;
 702    unsigned char        iv[AES_BLOCK_SIZE];
 703    SECItem              ivItem;
 704    SECItem             *srvName = NULL;
 705    PRUint32             srvNameLen = 0;
 706    CK_MECHANISM_TYPE    msWrapMech = 0; /* dummy default value,
 707                                          * must be >= 0 */
 708
 709    SSL_TRC(3, ("%d: SSL3[%d]: send session_ticket handshake",
 710		SSL_GETPID(), ss->fd));
 711
 712    PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
 713    PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
 714
 715    ticket.ticket_lifetime_hint = TLS_EX_SESS_TICKET_LIFETIME_HINT;
 716    cert_length = (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) ?
 717	3 + ss->sec.ci.sid->peerCert->derCert.len : 0;
 718
 719    /* Get IV and encryption keys */
 720    ivItem.data = iv;
 721    ivItem.len = sizeof(iv);
 722    rv = PK11_GenerateRandom(iv, sizeof(iv));
 723    if (rv != SECSuccess) goto loser;
 724
 725    if (ss->opt.bypassPKCS11) {
 726	rv = ssl3_GetSessionTicketKeys(&aes_key, &aes_key_length,
 727	    &mac_key, &mac_key_length);
 728    } else {
 729	rv = ssl3_GetSessionTicketKeysPKCS11(ss, &aes_key_pkcs11,
 730	    &mac_key_pkcs11);
 731    }
 732    if (rv != SECSuccess) goto loser;
 733
 734    if (ss->ssl3.pwSpec->msItem.len && ss->ssl3.pwSpec->msItem.data) {
 735	/* The master secret is available unwrapped. */
 736	ms_item.data = ss->ssl3.pwSpec->msItem.data;
 737	ms_item.len = ss->ssl3.pwSpec->msItem.len;
 738	ms_is_wrapped = PR_FALSE;
 739    } else {
 740	/* Extract the master secret wrapped. */
 741	sslSessionID sid;
 742	PORT_Memset(&sid, 0, sizeof(sslSessionID));
 743
 744	if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) {
 745	    effectiveExchKeyType = kt_rsa;
 746	} else {
 747	    effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType;
 748	}
 749
 750	rv = ssl3_CacheWrappedMasterSecret(ss, &sid, ss->ssl3.pwSpec,
 751	    effectiveExchKeyType);
 752	if (rv == SECSuccess) {
 753	    if (sid.u.ssl3.keys.wrapped_master_secret_len > sizeof(wrapped_ms))
 754		goto loser;
 755	    memcpy(wrapped_ms, sid.u.ssl3.keys.wrapped_master_secret,
 756		sid.u.ssl3.keys.wrapped_master_secret_len);
 757	    ms_item.data = wrapped_ms;
 758	    ms_item.len = sid.u.ssl3.keys.wrapped_master_secret_len;
 759	    msWrapMech = sid.u.ssl3.masterWrapMech;
 760	} else {
 761	    /* TODO: else send an empty ticket. */
 762	    goto loser;
 763	}
 764	ms_is_wrapped = PR_TRUE;
 765    }
 766    /* Prep to send negotiated name */
 767    srvName = &ss->ssl3.pwSpec->srvVirtName;
 768    if (srvName->data && srvName->len) {
 769        srvNameLen = 2 + srvName->len; /* len bytes + name len */
 770    }
 771
 772    ciphertext_length = 
 773	sizeof(PRUint16)                     /* ticket_version */
 774	+ sizeof(SSL3ProtocolVersion)        /* ssl_version */
 775	+ sizeof(ssl3CipherSuite)            /* ciphersuite */
 776	+ 1                                  /* compression */
 777	+ 10                                 /* cipher spec parameters */
 778	+ 1                                  /* SessionTicket.ms_is_wrapped */
 779	+ 1                                  /* effectiveExchKeyType */
 780	+ 4                                  /* msWrapMech */
 781	+ 2                                  /* master_secret.length */
 782	+ ms_item.len                        /* master_secret */
 783	+ 1                                  /* client_auth_type */
 784	+ cert_length                        /* cert */
 785        + 1                                  /* server name type */
 786        + srvNameLen                         /* name len + length field */
 787	+ sizeof(ticket.ticket_lifetime_hint);
 788    padding_length =  AES_BLOCK_SIZE -
 789	(ciphertext_length % AES_BLOCK_SIZE);
 790    ciphertext_length += padding_length;
 791
 792    message_length =
 793	sizeof(ticket.ticket_lifetime_hint)    /* ticket_lifetime_hint */
 794	+ 2 /* length field for NewSessionTicket.ticket */
 795	+ SESS_TICKET_KEY_NAME_LEN             /* key_name */
 796	+ AES_BLOCK_SIZE                       /* iv */
 797	+ 2 /* length field for NewSessionTicket.ticket.encrypted_state */
 798	+ ciphertext_length                    /* encrypted_state */
 799	+ TLS_EX_SESS_TICKET_MAC_LENGTH;       /* mac */
 800
 801    if (SECITEM_AllocItem(NULL, &plaintext_item, ciphertext_length) == NULL)
 802	goto loser;
 803
 804    plaintext = plaintext_item;
 805
 806    /* ticket_version */
 807    rv = ssl3_AppendNumberToItem(&plaintext, TLS_EX_SESS_TICKET_VERSION,
 808	sizeof(PRUint16));
 809    if (rv != SECSuccess) goto loser;
 810
 811    /* ssl_version */
 812    rv = ssl3_AppendNumberToItem(&plaintext, ss->version,
 813	sizeof(SSL3ProtocolVersion));
 814    if (rv != SECSuccess) goto loser;
 815
 816    /* ciphersuite */
 817    rv = ssl3_AppendNumberToItem(&plaintext, ss->ssl3.hs.cipher_suite, 
 818	sizeof(ssl3CipherSuite));
 819    if (rv != SECSuccess) goto loser;
 820    
 821    /* compression */
 822    rv = ssl3_AppendNumberToItem(&plaintext, ss->ssl3.hs.compression, 1);
 823    if (rv != SECSuccess) goto loser;
 824
 825    /* cipher spec parameters */
 826    rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.authAlgorithm, 1);
 827    if (rv != SECSuccess) goto loser;
 828    rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.authKeyBits, 4);
 829    if (rv != SECSuccess) goto loser;
 830    rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.keaType, 1);
 831    if (rv != SECSuccess) goto loser;
 832    rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.keaKeyBits, 4);
 833    if (rv != SECSuccess) goto loser;
 834
 835    /* master_secret */
 836    rv = ssl3_AppendNumberToItem(&plaintext, ms_is_wrapped, 1);
 837    if (rv != SECSuccess) goto loser;
 838    rv = ssl3_AppendNumberToItem(&plaintext, effectiveExchKeyType, 1);
 839    if (rv != SECSuccess) goto loser;
 840    rv = ssl3_AppendNumberToItem(&plaintext, msWrapMech, 4);
 841    if (rv != SECSuccess) goto loser;
 842    rv = ssl3_AppendNumberToItem(&plaintext, ms_item.len, 2);
 843    if (rv != SECSuccess) goto loser;
 844    rv = ssl3_AppendToItem(&plaintext, ms_item.data, ms_item.len);
 845    if (rv != SECSuccess) goto loser;
 846
 847    /* client_identity */
 848    if (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) {
 849	rv = ssl3_AppendNumberToItem(&plaintext, CLIENT_AUTH_CERTIFICATE, 1);
 850	if (rv != SECSuccess) goto loser;
 851	rv = ssl3_AppendNumberToItem(&plaintext,
 852	    ss->sec.ci.sid->peerCert->derCert.len, 3);
 853	if (rv != SECSuccess) goto loser;
 854	rv = ssl3_AppendToItem(&plaintext,
 855	    ss->sec.ci.sid->peerCert->derCert.data,
 856	    ss->sec.ci.sid->peerCert->derCert.len);
 857	if (rv != SECSuccess) goto loser;
 858    } else {
 859	rv = ssl3_AppendNumberToItem(&plaintext, 0, 1);
 860	if (rv != SECSuccess) goto loser;
 861    }
 862
 863    /* timestamp */
 864    now = ssl_Time();
 865    rv = ssl3_AppendNumberToItem(&plaintext, now,
 866	sizeof(ticket.ticket_lifetime_hint));
 867    if (rv != SECSuccess) goto loser;
 868
 869    if (srvNameLen) {
 870        /* Name Type (sni_host_name) */
 871        rv = ssl3_AppendNumberToItem(&plaintext, srvName->type, 1);
 872        if (rv != SECSuccess) goto loser;
 873        /* HostName (length and value) */
 874        rv = ssl3_AppendNumberToItem(&plaintext, srvName->len, 2);
 875        if (rv != SECSuccess) goto loser;
 876        rv = ssl3_AppendToItem(&plaintext, srvName->data, srvName->len);
 877        if (rv != SECSuccess) goto loser;
 878    } else {
 879        /* No Name */
 880        rv = ssl3_AppendNumberToItem(&plaintext, (char)TLS_STE_NO_SERVER_NAME,
 881                                     1);
 882        if (rv != SECSuccess) goto loser;
 883    }
 884
 885    PORT_Assert(plaintext.len == padding_length);
 886    for (i = 0; i < padding_length; i++)
 887	plaintext.data[i] = (unsigned char)padding_length;
 888
 889    if (SECITEM_AllocItem(NULL, &ciphertext, ciphertext_length) == NULL) {
 890	rv = SECFailure;
 891	goto loser;
 892    }
 893
 894    /* Generate encrypted portion of ticket. */
 895    if (ss->opt.bypassPKCS11) {
 896	aes_ctx = (AESContext *)aes_ctx_buf;
 897	rv = AES_InitContext(aes_ctx, aes_key, aes_key_length, iv, 
 898	    NSS_AES_CBC, 1, AES_BLOCK_SIZE);
 899	if (rv != SECSuccess) goto loser;
 900
 901	rv = AES_Encrypt(aes_ctx, ciphertext.data, &ciphertext.len,
 902	    ciphertext.len, plaintext_item.data,
 903	    plaintext_item.len);
 904	if (rv != SECSuccess) goto loser;
 905    } else {
 906	aes_ctx_pkcs11 = PK11_CreateContextBySymKey(cipherMech,
 907	    CKA_ENCRYPT, aes_key_pkcs11, &ivItem);
 908	if (!aes_ctx_pkcs11) 
 909	    goto loser;
 910
 911	rv = PK11_CipherOp(aes_ctx_pkcs11, ciphertext.data,
 912	    (int *)&ciphertext.len, ciphertext.len,
 913	    plaintext_item.data, plaintext_item.len);
 914	PK11_Finalize(aes_ctx_pkcs11);
 915	PK11_DestroyContext(aes_ctx_pkcs11, PR_TRUE);
 916	if (rv != SECSuccess) goto loser;
 917    }
 918
 919    /* Convert ciphertext length to network order. */
 920    length_buf[0] = (ciphertext.len >> 8) & 0xff;
 921    length_buf[1] = (ciphertext.len     ) & 0xff;
 922
 923    /* Compute MAC. */
 924    if (ss->opt.bypassPKCS11) {
 925	hmac_ctx = (HMACContext *)hmac_ctx_buf;
 926	hashObj = HASH_GetRawHashObject(HASH_AlgSHA256);
 927	if (HMAC_Init(hmac_ctx, hashObj, mac_key,
 928		mac_key_length, PR_FALSE) != SECSuccess)
 929	    goto loser;
 930
 931	HMAC_Begin(hmac_ctx);
 932	HMAC_Update(hmac_ctx, key_name, SESS_TICKET_KEY_NAME_LEN);
 933	HMAC_Update(hmac_ctx, iv, sizeof(iv));
 934	HMAC_Update(hmac_ctx, (unsigned char *)length_buf, 2);
 935	HMAC_Update(hmac_ctx, ciphertext.data, ciphertext.len);
 936	HMAC_Finish(hmac_ctx, computed_mac, &computed_mac_length,
 937	    sizeof(computed_mac));
 938    } else {
 939	SECItem macParam;
 940	macParam.data = NULL;
 941	macParam.len = 0;
 942	hmac_ctx_pkcs11 = PK11_CreateContextBySymKey(macMech,
 943	    CKA_SIGN, mac_key_pkcs11, &macParam);
 944	if (!hmac_ctx_pkcs11)
 945	    goto loser;
 946
 947	rv = PK11_DigestBegin(hmac_ctx_pkcs11);
 948	rv = PK11_DigestOp(hmac_ctx_pkcs11, key_name,
 949	    SESS_TICKET_KEY_NAME_LEN);
 950	rv = PK11_DigestOp(hmac_ctx_pkcs11, iv, sizeof(iv));
 951	rv = PK11_DigestOp(hmac_ctx_pkcs11, (unsigned char *)length_buf, 2);
 952	rv = PK11_DigestOp(hmac_ctx_pkcs11, ciphertext.data, ciphertext.len);
 953	rv = PK11_DigestFinal(hmac_ctx_pkcs11, computed_mac,
 954	    &computed_mac_length, sizeof(computed_mac));
 955	PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE);
 956	if (rv != SECSuccess) goto loser;
 957    }
 958
 959    /* Serialize the handshake message. */
 960    rv = ssl3_AppendHandshakeHeader(ss, new_session_ticket, message_length);
 961    if (rv != SECSuccess) goto loser;
 962
 963    rv = ssl3_AppendHandshakeNumber(ss, ticket.ticket_lifetime_hint,
 964	sizeof(ticket.ticket_lifetime_hint));
 965    if (rv != SECSuccess) goto loser;
 966
 967    rv = ssl3_AppendHandshakeNumber(ss,
 968	message_length - sizeof(ticket.ticket_lifetime_hint) - 2, 2);
 969    if (rv != SECSuccess) goto loser;
 970
 971    rv = ssl3_AppendHandshake(ss, key_name, SESS_TICKET_KEY_NAME_LEN);
 972    if (rv != SECSuccess) goto loser;
 973
 974    rv = ssl3_AppendHandshake(ss, iv, sizeof(iv));
 975    if (rv != SECSuccess) goto loser;
 976
 977    rv = ssl3_AppendHandshakeVariable(ss, ciphertext.data, ciphertext.len, 2);
 978    if (rv != SECSuccess) goto loser;
 979
 980    rv = ssl3_AppendHandshake(ss, computed_mac, computed_mac_length);
 981    if (rv != SECSuccess) goto loser;
 982
 983loser:
 984    if (plaintext_item.data)
 985	SECITEM_FreeItem(&plaintext_item, PR_FALSE);
 986    if (ciphertext.data)
 987	SECITEM_FreeItem(&ciphertext, PR_FALSE);
 988
 989    return rv;
 990}
 991
 992/* When a client receives a SessionTicket extension a NewSessionTicket
 993 * message is expected during the handshake.
 994 */
 995SECStatus
 996ssl3_ClientHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type,
 997                                  SECItem *data)
 998{
 999    if (data->len != 0)
1000	return SECFailure;
1001
1002    /* Keep track of negotiated extensions. */
1003    ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
1004    return SECSuccess;
1005}
1006
1007SECStatus
1008ssl3_ServerHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type,
1009                                  SECItem *data)
1010{
1011    SECStatus rv;
1012    SECItem *decrypted_state = NULL;
1013    SessionTicket *parsed_session_ticket = NULL;
1014    sslSessionID *sid = NULL;
1015    SSL3Statistics *ssl3stats;
1016
1017    /* Ignore the SessionTicket extension if processing is disabled. */
1018    if (!ss->opt.enableSessionTickets)
1019	return SECSuccess;
1020
1021    /* Keep track of negotiated extensions. */
1022    ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
1023
1024    /* Parse the received ticket sent in by the client.  We are
1025     * lenient about some parse errors, falling back to a fullshake
1026     * instead of terminating the current connection.
1027     */
1028    if (data->len == 0) {
1029	ss->xtnData.emptySessionTicket = PR_TRUE;
1030    } else {
1031	int                    i;
1032	SECItem                extension_data;
1033	EncryptedSessionTicket enc_session_ticket;
1034	unsigned char          computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH];
1035	unsigned int           computed_mac_length;
1036	const SECHashObject   *hashObj;
1037	const unsigned char   *aes_key;
1038	const unsigned char   *mac_key;
1039	PK11SymKey            *aes_key_pkcs11;
1040	PK11SymKey            *mac_key_pkcs11;
1041	PRUint32               aes_key_length;
1042	PRUint32               mac_key_length;
1043	PRUint64               hmac_ctx_buf[MAX_MAC_CONTEXT_LLONGS];
1044	HMACContext           *hmac_ctx;
1045	PK11Context           *hmac_ctx_pkcs11;
1046	CK_MECHANISM_TYPE      macMech = CKM_SHA256_HMAC;
1047	PRUint64               aes_ctx_buf[MAX_CIPHER_CONTEXT_LLONGS];
1048	AESContext            *aes_ctx;
1049	PK11Context           *aes_ctx_pkcs11;
1050	CK_MECHANISM_TYPE      cipherMech = CKM_AES_CBC;
1051	unsigned char *        padding;
1052	PRUint32               padding_length;
1053	unsigned char         *buffer;
1054	unsigned int           buffer_len;
1055	PRInt32                temp;
1056	SECItem                cert_item;
1057        PRInt8                 nameType = TLS_STE_NO_SERVER_NAME;
1058
1059	/* Turn off stateless session resumption if the client sends a
1060	 * SessionTicket extension, even if the extension turns out to be
1061	 * malformed (ss->sec.ci.sid is non-NULL when doing session
1062	 * renegotiation.)
1063	 */
1064	if (ss->sec.ci.sid != NULL) {
1065	    ss->sec.uncache(ss->sec.ci.sid);
1066	    ssl_FreeSID(ss->sec.ci.sid);
1067	    ss->sec.ci.sid = NULL;
1068	}
1069
1070	extension_data.data = data->data; /* Keep a copy for future use. */
1071	extension_data.len = data->len;
1072
1073	if (ssl3_ParseEncryptedSessionTicket(ss, data, &enc_session_ticket)
1074	    != SECSuccess)
1075	    return SECFailure;
1076
1077	/* Get session ticket keys. */
1078	if (ss->opt.bypassPKCS11) {
1079	    rv = ssl3_GetSessionTicketKeys(&aes_key, &aes_key_length,
1080		&mac_key, &mac_key_length);
1081	} else {
1082	    rv = ssl3_GetSessionTicketKeysPKCS11(ss, &aes_key_pkcs11,
1083		&mac_key_pkcs11);
1084	}
1085	if (rv != SECSuccess) {
1086	    SSL_DBG(("%d: SSL[%d]: Unable to get/generate session ticket keys.",
1087			SSL_GETPID(), ss->fd));
1088	    goto loser;
1089	}
1090
1091	/* If the ticket sent by the client was generated under a key different
1092	 * from the one we have, bypass ticket processing.
1093	 */
1094	if (PORT_Memcmp(enc_session_ticket.key_name, key_name,
1095		SESS_TICKET_KEY_NAME_LEN) != 0) {
1096	    SSL_DBG(("%d: SSL[%d]: Session ticket key_name sent mismatch.",
1097			SSL_GETPID(), ss->fd));
1098	    goto no_ticket;
1099	}
1100
1101	/* Verify the MAC on the ticket.  MAC verification may also
1102	 * fail if the MAC key has been recently refreshed.
1103	 */
1104	if (ss->opt.bypassPKCS11) {
1105	    hmac_ctx = (HMACContext *)hmac_ctx_buf;
1106	    hashObj = HASH_GetRawHashObject(HASH_AlgSHA256);
1107	    if (HMAC_Init(hmac_ctx, hashObj, mac_key,
1108		    sizeof(session_ticket_mac_key), PR_FALSE) != SECSuccess)
1109		goto no_ticket;
1110	    HMAC_Begin(hmac_ctx);
1111	    HMAC_Update(hmac_ctx, extension_data.data,
1112		extension_data.len - TLS_EX_SESS_TICKET_MAC_LENGTH);
1113	    if (HMAC_Finish(hmac_ctx, computed_mac, &computed_mac_length,
1114		    sizeof(computed_mac)) != SECSuccess)
1115		goto no_ticket;
1116	} else {
1117	    SECItem macParam;
1118	    macParam.data = NULL;
1119	    macParam.len = 0;
1120	    hmac_ctx_pkcs11 = PK11_CreateContextBySymKey(macMech,
1121		CKA_SIGN, mac_key_pkcs11, &macParam);
1122	    if (!hmac_ctx_pkcs11) {
1123		SSL_DBG(("%d: SSL[%d]: Unable to create HMAC context: %d.",
1124			    SSL_GETPID(), ss->fd, PORT_GetError()));
1125		goto no_ticket;
1126	    } else {
1127		SSL_DBG(("%d: SSL[%d]: Successfully created HMAC context.",
1128			    SSL_GETPID(), ss->fd));
1129	    }
1130	    rv = PK11_DigestBegin(hmac_ctx_pkcs11);
1131	    rv = PK11_DigestOp(hmac_ctx_pkcs11, extension_data.data,
1132		extension_data.len - TLS_EX_SESS_TICKET_MAC_LENGTH);
1133	    if (rv != SECSuccess) {
1134		PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE);
1135		goto no_ticket;
1136	    }
1137	    rv = PK11_DigestFinal(hmac_ctx_pkcs11, computed_mac,
1138		&computed_mac_length, sizeof(computed_mac));
1139	    PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE);
1140	    if (rv != SECSuccess)
1141		goto no_ticket;
1142	}
1143	if (NSS_SecureMemcmp(computed_mac, enc_session_ticket.mac,
1144		computed_mac_length) != 0) {
1145	    SSL_DBG(("%d: SSL[%d]: Session ticket MAC mismatch.",
1146			SSL_GETPID(), ss->fd));
1147	    goto no_ticket;
1148	}
1149
1150	/* We ignore key_name for now.
1151	 * This is ok as MAC verification succeeded.
1152	 */
1153
1154	/* Decrypt the ticket. */
1155
1156	/* Plaintext is shorter than the ciphertext due to padding. */
1157	decrypted_state = SECITEM_AllocItem(NULL, NULL,
1158	    enc_session_ticket.encrypted_state.len);
1159
1160	if (ss->opt.bypassPKCS11) {
1161	    aes_ctx = (AESContext *)aes_ctx_buf;
1162	    rv = AES_InitContext(aes_ctx, aes_key,
1163		sizeof(session_ticket_enc_key), enc_session_ticket.iv,
1164		NSS_AES_CBC, 0,AES_BLOCK_SIZE);
1165	    if (rv != SECSuccess) {
1166		SSL_DBG(("%d: SSL[%d]: Unable to create AES context.",
1167			    SSL_GETPID(), ss->fd));
1168		goto no_ticket;
1169	    }
1170
1171	    rv = AES_Decrypt(aes_ctx, decrypted_state->data,
1172		&decrypted_state->len, decrypted_state->len,
1173		enc_session_ticket.encrypted_state.data,
1174		enc_session_ticket.encrypted_state.len);
1175	    if (rv != SECSuccess)
1176		goto no_ticket;
1177	} else {
1178	    SECItem ivItem;
1179	    ivItem.data = enc_session_ticket.iv;
1180	    ivItem.len = AES_BLOCK_SIZE;
1181	    aes_ctx_pkcs11 = PK11_CreateContextBySymKey(cipherMech,
1182		CKA_DECRYPT, aes_key_pkcs11, &ivItem);
1183	    if (!aes_ctx_pkcs11) {
1184		SSL_DBG(("%d: SSL[%d]: Unable to create AES context.",
1185			    SSL_GETPID(), ss->fd));
1186		goto no_ticket;
1187	    }
1188
1189	    rv = PK11_CipherOp(aes_ctx_pkcs11, decrypted_state->data,
1190		(int *)&decrypted_state->len, decrypted_state->len,
1191		enc_session_ticket.encrypted_state.data,
1192		enc_session_ticket.encrypted_state.len);
1193	    PK11_Finalize(aes_ctx_pkcs11);
1194	    PK11_DestroyContext(aes_ctx_pkcs11, PR_TRUE);
1195	    if (rv != SECSuccess)
1196		goto no_ticket;
1197	}
1198
1199	/* Check padding. */
1200	padding_length = 
1201	    (PRUint32)decrypted_state->data[decrypted_state->len - 1];
1202	if (padding_length == 0 || padding_length > AES_BLOCK_SIZE)
1203	    goto no_ticket;
1204
1205	padding = &decrypted_state->data[decrypted_state->len - padding_length];
1206	for (i = 0; i < padding_length; i++, padding++) {
1207	    if (padding_length != (PRUint32)*padding)
1208		goto no_ticket;
1209	}
1210
1211	/* Deserialize session state. */
1212	buffer = decrypted_state->data;
1213	buffer_len = decrypted_state->len;
1214
1215	parsed_session_ticket = PORT_ZAlloc(sizeof(SessionTicket));
1216	if (parsed_session_ticket == NULL) {
1217	    rv = SECFailure;
1218	    goto loser;
1219	}
1220
1221	/* Read ticket_version (which is ignored for now.) */
1222	temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1223	if (temp < 0) goto no_ticket;
1224	parsed_session_ticket->ticket_version = (SSL3ProtocolVersion)temp;
1225
1226	/* Read SSLVersion. */
1227	temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1228	if (temp < 0) goto no_ticket;
1229	parsed_session_ticket->ssl_version = (SSL3ProtocolVersion)temp;
1230
1231	/* Read cipher_suite. */
1232	temp =  ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1233	if (temp < 0) goto no_ticket;
1234	parsed_session_ticket->cipher_suite = (ssl3CipherSuite)temp;
1235
1236	/* Read compression_method. */
1237	temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1238	if (temp < 0) goto no_ticket;
1239	parsed_session_ticket->compression_method = (SSLCompressionMethod)temp;
1240
1241	/* Read cipher spec parameters. */
1242	temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1243	if (temp < 0) goto no_ticket;
1244	parsed_session_ticket->authAlgorithm = (SSLSignType)temp;
1245	temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1246	if (temp < 0) goto no_ticket;
1247	parsed_session_ticket->authKeyBits = (PRUint32)temp;
1248	temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1249	if (temp < 0) goto no_ticket;
1250	parsed_session_ticket->keaType = (SSLKEAType)temp;
1251	temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1252	if (temp < 0) goto no_ticket;
1253	parsed_session_ticket->keaKeyBits = (PRUint32)temp;
1254
1255	/* Read wrapped master_secret. */
1256	temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1257	if (temp < 0) goto no_ticket;
1258	parsed_session_ticket->ms_is_wrapped = (PRBool)temp;
1259
1260	temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1261	if (temp < 0) goto no_ticket;
1262	parsed_session_ticket->exchKeyType = (SSL3KEAType)temp;
1263
1264	temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1265	if (temp < 0) goto no_ticket;
1266	parsed_session_ticket->msWrapMech = (CK_MECHANISM_TYPE)temp;
1267
1268	temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1269	if (temp < 0) goto no_ticket;
1270	parsed_session_ticket->ms_length = (PRUint16)temp;
1271	if (parsed_session_ticket->ms_length == 0 ||  /* sanity check MS. */
1272	    parsed_session_ticket->ms_length >
1273	    sizeof(parsed_session_ticket->master_secret))
1274	    goto no_ticket;
1275	
1276	/* Allow for the wrapped master secret to be longer. */
1277	if (buffer_len < sizeof(SSL3_MASTER_SECRET_LENGTH))
1278	    goto no_ticket;
1279	PORT_Memcpy(parsed_session_ticket->master_secret, buffer,
1280	    parsed_session_ticket->ms_length);
1281	buffer += parsed_session_ticket->ms_length;
1282	buffer_len -= parsed_session_ticket->ms_length;
1283
1284	/* Read client_identity */
1285	temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1286	if (temp < 0)
1287	    goto no_ticket;
1288	parsed_session_ticket->client_identity.client_auth_type = 
1289	    (ClientAuthenticationType)temp;
1290	switch(parsed_session_ticket->client_identity.client_auth_type) {
1291            case CLIENT_AUTH_ANONYMOUS:
1292		break;
1293            case CLIENT_AUTH_CERTIFICATE:
1294		rv = ssl3_ConsumeHandshakeVariable(ss, &cert_item, 3,
1295		    &buffer, &buffer_len);
1296		if (rv != SECSuccess) goto no_ticket;
1297		rv = SECITEM_CopyItem(NULL, &parsed_session_ticket->peer_cert,
1298		    &cert_item);
1299		if (rv != SECSuccess) goto no_ticket;
1300		break;
1301            default:
1302		goto no_ticket;
1303	}
1304	/* Read timestamp. */
1305	temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1306	if (temp < 0)
1307	    goto no_ticket;
1308	parsed_session_ticket->timestamp = (PRUint32)temp;
1309
1310        /* Read server name */
1311        nameType =
1312                ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); 
1313        if (nameType != TLS_STE_NO_SERVER_NAME) {
1314            SECItem name_item;
1315            rv = ssl3_ConsumeHandshakeVariable(ss, &name_item, 2, &buffer,
1316                                               &buffer_len);
1317            if (rv != SECSuccess) goto no_ticket;
1318            rv = SECITEM_CopyItem(NULL, &parsed_session_ticket->srvName,
1319                                  &name_item);
1320            if (rv != SECSuccess) goto no_ticket;
1321            parsed_session_ticket->srvName.type = nameType;
1322        }
1323
1324	/* Done parsing.  Check that all bytes have been consumed. */
1325	if (buffer_len != padding_length)
1326	    goto no_ticket;
1327
1328	/* Use the ticket if it has not expired, otherwise free the allocated
1329	 * memory since the ticket is of no use.
1330	 */
1331	if (parsed_session_ticket->timestamp != 0 &&
1332	    parsed_session_ticket->timestamp +
1333	    TLS_EX_SESS_TICKET_LIFETIME_HINT > ssl_Time()) {
1334
1335	    sid = ssl3_NewSessionID(ss, PR_TRUE);
1336	    if (sid == NULL) {
1337		rv = SECFailure;
1338		goto loser;
1339	    }
1340
1341	    /* Copy over parameters. */
1342	    sid->version = parsed_session_ticket->ssl_version;
1343	    sid->u.ssl3.cipherSuite = parsed_session_ticket->cipher_suite;
1344	    sid->u.ssl3.compression = parsed_session_ticket->compression_method;
1345	    sid->authAlgorithm = parsed_session_ticket->authAlgorithm;
1346	    sid->authKeyBits = parsed_session_ticket->authKeyBits;
1347	    sid->keaType = parsed_session_ticket->keaType;
1348	    sid->keaKeyBits = parsed_session_ticket->keaKeyBits;
1349
1350	    /* Copy master secret. */
1351	    if (ss->opt.bypassPKCS11 &&
1352		    parsed_session_ticket->ms_is_wrapped)
1353		goto no_ticket;
1354	    if (parsed_session_ticket->ms_length >
1355		    sizeof(sid->u.ssl3.keys.wrapped_master_secret))
1356		goto no_ticket;
1357	    PORT_Memcpy(sid->u.ssl3.keys.wrapped_master_secret,
1358		parsed_session_ticket->master_secret,
1359		parsed_session_ticket->ms_length);
1360	    sid->u.ssl3.keys.wrapped_master_secret_len =
1361		parsed_session_ticket->ms_length;
1362	    sid->u.ssl3.exchKeyType = parsed_session_ticket->exchKeyType;
1363	    sid->u.ssl3.masterWrapMech = parsed_session_ticket->msWrapMech;
1364	    sid->u.ssl3.keys.msIsWrapped =
1365		parsed_session_ticket->ms_is_wrapped;
1366	    sid->u.ssl3.masterValid    = PR_TRUE;
1367	    sid->u.ssl3.keys.resumable = PR_TRUE;
1368
1369	    /* Copy over client cert from session ticket if there is one. */
1370	    if (parsed_session_ticket->peer_cert.data != NULL) {
1371		if (sid->peerCert != NULL)
1372		    CERT_DestroyCertificate(sid->peerCert);
1373		sid->peerCert = CERT_NewTempCertificate(ss->dbHandle,
1374		    &parsed_session_ticket->peer_cert, NULL, PR_FALSE, PR_TRUE);
1375		if (sid->peerCert == NULL) {
1376		    rv = SECFailure;
1377		    goto loser;
1378		}
1379	    }
1380	    if (parsed_session_ticket->srvName.data != NULL) {
1381                sid->u.ssl3.srvName = parsed_session_ticket->srvName;
1382            }
1383	    ss->statelessResume = PR_TRUE;
1384	    ss->sec.ci.sid = sid;
1385	}
1386    }
1387
1388    if (0) {
1389no_ticket:
1390	SSL_DBG(("%d: SSL[%d]: Session ticket parsing failed.",
1391			SSL_GETPID(), ss->fd));
1392	ssl3stats = SSL_GetStatistics();
1393	SSL_AtomicIncrementLong(& ssl3stats->hch_sid_ticket_parse_failures );
1394    }
1395    rv = SECSuccess;
1396
1397loser:
1398	/* ss->sec.ci.sid == sid if it did NOT come here via goto statement
1399	 * in that case do not free sid
1400	 */
1401	if (sid && (ss->sec.ci.sid != sid)) {
1402	    ssl_FreeSID(sid);
1403	    sid = NULL;
1404	}
1405    if (decrypted_state != NULL) {
1406	SECITEM_FreeItem(decrypted_state, PR_TRUE);
1407	decrypted_state = NULL;
1408    }
1409
1410    if (parsed_session_ticket != NULL) {
1411	if (parsed_session_ticket->peer_cert.data) {
1412	    SECITEM_FreeItem(&parsed_session_ticket->peer_cert, PR_FALSE);
1413	}
1414	PORT_ZFree(parsed_session_ticket, sizeof(SessionTicket));
1415    }
1416
1417    return rv;
1418}
1419
1420/*
1421 * Read bytes.  Using this function means the SECItem structure
1422 * cannot be freed.  The caller is expected to call this function
1423 * on a shallow copy of the structure.
1424 */
1425static SECStatus 
1426ssl3_ConsumeFromItem(SECItem *item, unsigned char **buf, PRUint32 bytes)
1427{
1428    if (bytes > item->len)
1429	return SECFailure;
1430
1431    *buf = item->data;
1432    item->data += bytes;
1433    item->len -= bytes;
1434    return SECSuccess;
1435}
1436
1437static SECStatus
1438ssl3_ParseEncryptedSessionTicket(sslSocket *ss, SECItem *data,
1439                                 EncryptedSessionTicket *enc_session_ticket)
1440{
1441    if (ssl3_ConsumeFromItem(data, &enc_session_ticket->key_name,
1442	    SESS_TICKET_KEY_NAME_LEN) != SECSuccess)
1443	return SECFailure;
1444    if (ssl3_ConsumeFromItem(data, &enc_session_ticket->iv,
1445	    AES_BLOCK_SIZE) != SECSuccess)
1446	return SECFailure;
1447    if (ssl3_ConsumeHandshakeVariable(ss, &enc_session_ticket->encrypted_state,
1448	    2, &data->data, &data->len) != SECSuccess)
1449	return SECFailure;
1450    if (ssl3_ConsumeFromItem(data, &enc_session_ticket->mac,
1451	    TLS_EX_SESS_TICKET_MAC_LENGTH) != SECSuccess)
1452	return SECFailure;
1453    if (data->len != 0)  /* Make sure that we have consumed all bytes. */
1454	return SECFailure;
1455
1456    return SECSuccess;
1457}
1458
1459/* go through hello extensions in buffer "b"…

Large files files are truncated, but you can click here to view the full file