ssl3exthandle.c 64 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "nssrenam.h"
#include "nss.h"
#include "ssl.h"
#include "sslproto.h"
#include "sslimpl.h"
#include "pk11pub.h"
#include "blapit.h"
#include "prinit.h"
15
#include "selfencrypt.h"
16
#include "ssl3ext.h"
17
#include "ssl3exthandle.h"
18
#include "tls13ech.h"
19 20
#include "tls13exthandle.h" /* For tls13_ServerSendStatusRequestXtn. */

EKR's avatar
EKR committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
PRBool
ssl_ShouldSendSNIExtension(const sslSocket *ss, const char *url)
{
    PRNetAddr netAddr;

    /* must have a hostname */
    if (!url || !url[0]) {
        return PR_FALSE;
    }
    /* must not be an IPv4 or IPv6 address */
    if (PR_SUCCESS == PR_StringToNetAddr(url, &netAddr)) {
        /* is an IP address (v4 or v6) */
        return PR_FALSE;
    }

    return PR_TRUE;
}

39 40 41 42
/* Format an SNI extension, using the name from the socket's URL,
 * unless that name is a dotted decimal string.
 * Used by client and server.
 */
43
SECStatus
EKR's avatar
EKR committed
44
ssl3_ClientFormatServerNameXtn(const sslSocket *ss, const char *url,
45
                               unsigned int len, TLSExtensionData *xtnData,
EKR's avatar
EKR committed
46
                               sslBuffer *buf)
47 48
{
    SECStatus rv;
49 50 51 52 53

    /* length of server_name_list */
    rv = sslBuffer_AppendNumber(buf, len + 3, 2);
    if (rv != SECSuccess) {
        return SECFailure;
54
    }
55 56 57 58 59 60
    /* Name Type (sni_host_name) */
    rv = sslBuffer_AppendNumber(buf, 0, 1);
    if (rv != SECSuccess) {
        return SECFailure;
    }
    /* HostName (length and value) */
EKR's avatar
EKR committed
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
    rv = sslBuffer_AppendVariable(buf, (const PRUint8 *)url, len, 2);
    if (rv != SECSuccess) {
        return SECFailure;
    }

    return SECSuccess;
}

SECStatus
ssl3_ClientSendServerNameXtn(const sslSocket *ss, TLSExtensionData *xtnData,
                             sslBuffer *buf, PRBool *added)
{
    SECStatus rv;

    const char *url = ss->url;

    if (!ssl_ShouldSendSNIExtension(ss, url)) {
        return SECSuccess;
    }

81 82 83 84 85
    /* If ECH, write the public name. The real server name
     * is emplaced while constructing CHInner extensions. */
    sslEchConfig *cfg = (sslEchConfig *)PR_LIST_HEAD(&ss->echConfigs);
    const char *sniContents = PR_CLIST_IS_EMPTY(&ss->echConfigs) ? url : cfg->contents.publicName;
    rv = ssl3_ClientFormatServerNameXtn(ss, sniContents, strlen(sniContents), xtnData, buf);
86 87 88 89 90 91
    if (rv != SECSuccess) {
        return SECFailure;
    }

    *added = PR_TRUE;
    return SECSuccess;
92 93 94
}

SECStatus
95 96
ssl3_HandleServerNameXtn(const sslSocket *ss, TLSExtensionData *xtnData,
                         SECItem *data)
97 98
{
    SECItem *names = NULL;
99 100
    PRUint32 listLenBytes = 0;
    SECStatus rv;
101 102 103 104 105 106 107 108 109 110 111 112

    if (!ss->sec.isServer) {
        return SECSuccess; /* ignore extension */
    }

    /* Server side - consume client data and register server sender. */
    /* do not parse the data if don't have user extension handling function. */
    if (!ss->sniSocketConfig) {
        return SECSuccess;
    }

    /* length of server_name_list */
113 114
    rv = ssl3_ExtConsumeHandshakeNumber(ss, &listLenBytes, 2, &data->data, &data->len);
    if (rv != SECSuccess) {
115 116 117 118 119 120 121 122 123
        goto loser; /* alert already sent */
    }
    if (listLenBytes == 0 || listLenBytes != data->len) {
        goto alert_loser;
    }

    /* Read ServerNameList. */
    while (data->len > 0) {
        SECItem tmp;
124
        PRUint32 type;
125 126

        /* Read Name Type. */
127 128
        rv = ssl3_ExtConsumeHandshakeNumber(ss, &type, 1, &data->data, &data->len);
        if (rv != SECSuccess) {
129 130 131 132 133
            /* alert sent in ConsumeHandshakeNumber */
            goto loser;
        }

        /* Read ServerName (length and value). */
134
        rv = ssl3_ExtConsumeHandshakeVariable(ss, &tmp, 2, &data->data, &data->len);
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
        if (rv != SECSuccess) {
            goto loser;
        }

        /* Record the value for host_name(0). */
        if (type == sni_nametype_hostname) {
            /* Fail if we encounter a second host_name entry. */
            if (names) {
                goto alert_loser;
            }

            /* Create an array for the only supported NameType. */
            names = PORT_ZNewArray(SECItem, 1);
            if (!names) {
                goto loser;
            }

            /* Copy ServerName into the array. */
            if (SECITEM_CopyItem(NULL, &names[0], &tmp) != SECSuccess) {
                goto loser;
            }
        }

        /* Even if we don't support NameTypes other than host_name at the
         * moment, we continue parsing the whole list to check its validity.
         * We do not check for duplicate entries with NameType != host_name(0).
         */
    }
    if (names) {
        /* Free old and set the new data. */
        ssl3_FreeSniNameArray(xtnData);
        xtnData->sniNameArr = names;
        xtnData->sniNameArrSize = 1;
        xtnData->negotiated[xtnData->numNegotiated++] = ssl_server_name_xtn;
    }
    return SECSuccess;

alert_loser:
173
    ssl3_ExtDecodeError(ss);
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
loser:
    if (names) {
        PORT_Free(names);
    }
    return SECFailure;
}

/* Frees a given xtnData->sniNameArr and its elements. */
void
ssl3_FreeSniNameArray(TLSExtensionData *xtnData)
{
    PRUint32 i;

    if (!xtnData->sniNameArr) {
        return;
    }

    for (i = 0; i < xtnData->sniNameArrSize; i++) {
        SECITEM_FreeItem(&xtnData->sniNameArr[i], PR_FALSE);
    }

    PORT_Free(xtnData->sniNameArr);
    xtnData->sniNameArr = NULL;
    xtnData->sniNameArrSize = 0;
}

/* Called by both clients and servers.
 * Clients sends a filled in session ticket if one is available, and otherwise
 * sends an empty ticket.  Servers always send empty tickets.
 */
PRInt32
205 206
ssl3_ClientSendSessionTicketXtn(const sslSocket *ss, TLSExtensionData *xtnData,
                                sslBuffer *buf, PRBool *added)
207 208 209
{
    NewSessionTicket *session_ticket = NULL;
    sslSessionID *sid = ss->sec.ci.sid;
210 211 212
    SECStatus rv;

    PORT_Assert(!ss->sec.isServer);
213 214 215

    /* Never send an extension with a ticket for TLS 1.3, but
     * OK to send the empty one in case the server does 1.2. */
216
    if ((sid->cached == in_client_cache || sid->cached == in_external_cache) &&
217
        sid->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
218
        return SECSuccess;
219 220 221
    }

    /* Ignore the SessionTicket extension if processing is disabled. */
222 223 224
    if (!ss->opt.enableSessionTickets) {
        return SECSuccess;
    }
225

226 227 228 229 230 231 232 233
    /* Send a session ticket if one is available.
     *
     * The caller must be holding sid->u.ssl3.lock for reading. We cannot
     * just acquire and release the lock within this function because the
     * caller will call this function twice, and we need the inputs to be
     * consistent between the two calls. Note that currently the caller
     * will only be holding the lock when we are the client and when we're
     * attempting to resume an existing session.
234
     */
235 236 237
    session_ticket = &sid->u.ssl3.locked.sessionTicket;
    if (session_ticket->ticket.data &&
        (xtnData->ticketTimestampVerified ||
238
         ssl_TicketTimeValid(ss, session_ticket))) {
239

240
        xtnData->ticketTimestampVerified = PR_FALSE;
241

242 243 244 245
        rv = sslBuffer_Append(buf, session_ticket->ticket.data,
                              session_ticket->ticket.len);
        if (rv != SECSuccess) {
            return SECFailure;
246 247
        }

248
        xtnData->sentSessionTicketInClientHello = PR_TRUE;
249 250
    }

251 252
    *added = PR_TRUE;
    return SECSuccess;
253 254
}

255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
PRBool
ssl_AlpnTagAllowed(const sslSocket *ss, const SECItem *tag)
{
    const unsigned char *data = ss->opt.nextProtoNego.data;
    unsigned int length = ss->opt.nextProtoNego.len;
    unsigned int offset = 0;

    if (!tag->len)
        return PR_TRUE;

    while (offset < length) {
        unsigned int taglen = (unsigned int)data[offset];
        if ((taglen == tag->len) &&
            !PORT_Memcmp(data + offset + 1, tag->data, tag->len))
            return PR_TRUE;
        offset += 1 + taglen;
    }

    return PR_FALSE;
}

276
/* ssl3_ValidateAppProtocol checks that the given block of data is valid: none
277 278 279
 * of the lengths may be 0 and the sum of the lengths must equal the length of
 * the block. */
SECStatus
280
ssl3_ValidateAppProtocol(const unsigned char *data, unsigned int length)
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
{
    unsigned int offset = 0;

    while (offset < length) {
        unsigned int newOffset = offset + 1 + (unsigned int)data[offset];
        /* Reject embedded nulls to protect against buggy applications that
         * store protocol identifiers in null-terminated strings.
         */
        if (newOffset > length || data[offset] == 0) {
            return SECFailure;
        }
        offset = newOffset;
    }

    return SECSuccess;
}

298
/* Protocol selection handler for ALPN. */
299
static SECStatus
300
ssl3_SelectAppProtocol(const sslSocket *ss, TLSExtensionData *xtnData,
301
                       PRUint16 extension, SECItem *data)
302 303 304 305 306
{
    SECStatus rv;
    unsigned char resultBuffer[255];
    SECItem result = { siBuffer, resultBuffer, 0 };

307
    rv = ssl3_ValidateAppProtocol(data->data, data->len);
308
    if (rv != SECSuccess) {
309
        ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
310 311 312 313 314
        PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
        return rv;
    }

    PORT_Assert(ss->nextProtoCallback);
315
    /* Neither the cipher suite nor ECH are selected yet Note that extensions
316 317
     * sometimes affect what cipher suite is selected, e.g., for ECC. */
    PORT_Assert((ss->ssl3.hs.preliminaryInfo &
318 319
                 ssl_preinfo_all & ~ssl_preinfo_cipher_suite & ~ssl_preinfo_ech) ==
                (ssl_preinfo_all & ~ssl_preinfo_cipher_suite & ~ssl_preinfo_ech));
320 321
    /* The callback has to make sure that either rv != SECSuccess or that result
     * is not set if there is no common protocol. */
322 323 324 325
    rv = ss->nextProtoCallback(ss->nextProtoArg, ss->fd, data->data, data->len,
                               result.data, &result.len, sizeof(resultBuffer));
    if (rv != SECSuccess) {
        /* Expect callback to call PORT_SetError() */
326
        ssl3_ExtSendAlert(ss, alert_fatal, internal_error);
327 328 329 330 331 332 333
        return SECFailure;
    }

    /* If the callback wrote more than allowed to |result| it has corrupted our
     * stack. */
    if (result.len > sizeof(resultBuffer)) {
        PORT_SetError(SEC_ERROR_OUTPUT_LEN);
334
        PORT_Assert(PR_FALSE);
335 336 337
        return SECFailure;
    }

338
    SECITEM_FreeItem(&xtnData->nextProto, PR_FALSE);
339

340 341
    if (result.len < 1 || !result.data) {
        /* Check that we actually got a result. */
342
        ssl3_ExtSendAlert(ss, alert_fatal, no_application_protocol);
343 344 345 346
        PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_NO_PROTOCOL);
        return SECFailure;
    }

347
    xtnData->nextProtoState = SSL_NEXT_PROTO_NEGOTIATED;
348
    xtnData->negotiated[xtnData->numNegotiated++] = extension;
349
    return SECITEM_CopyItem(NULL, &xtnData->nextProto, &result);
350 351 352 353
}

/* handle an incoming ALPN extension at the server */
SECStatus
354 355
ssl3_ServerHandleAppProtoXtn(const sslSocket *ss, TLSExtensionData *xtnData,
                             SECItem *data)
356
{
357
    PRUint32 count;
358 359 360 361 362 363
    SECStatus rv;

    /* We expressly don't want to allow ALPN on renegotiation,
     * despite it being permitted by the spec. */
    if (ss->firstHsDone || data->len == 0) {
        /* Clients MUST send a non-empty ALPN extension. */
364
        ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
365 366 367 368
        PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
        return SECFailure;
    }

369
    /* ALPN has extra redundant length information so that
370
     * the extension is the same in both ClientHello and ServerHello. */
371 372
    rv = ssl3_ExtConsumeHandshakeNumber(ss, &count, 2, &data->data, &data->len);
    if (rv != SECSuccess || count != data->len) {
373
        ssl3_ExtDecodeError(ss);
374 375 376 377 378 379 380 381
        return SECFailure;
    }

    if (!ss->nextProtoCallback) {
        /* we're not configured for it */
        return SECSuccess;
    }

382
    rv = ssl3_SelectAppProtocol(ss, xtnData, ssl_app_layer_protocol_xtn, data);
383 384 385 386 387
    if (rv != SECSuccess) {
        return rv;
    }

    /* prepare to send back a response, if we negotiated */
388
    if (xtnData->nextProtoState == SSL_NEXT_PROTO_NEGOTIATED) {
389 390 391
        rv = ssl3_RegisterExtensionSender(ss, xtnData,
                                          ssl_app_layer_protocol_xtn,
                                          ssl3_ServerSendAppProtoXtn);
392
        if (rv != SECSuccess) {
393
            ssl3_ExtSendAlert(ss, alert_fatal, internal_error);
394 395 396 397 398 399 400 401
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
            return rv;
        }
    }
    return SECSuccess;
}

SECStatus
402 403
ssl3_ClientHandleAppProtoXtn(const sslSocket *ss, TLSExtensionData *xtnData,
                             SECItem *data)
404 405
{
    SECStatus rv;
406
    PRUint32 list_len;
407 408 409 410 411 412 413 414 415 416 417 418
    SECItem protocol_name;

    if (ssl3_ExtensionNegotiated(ss, ssl_next_proto_nego_xtn)) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }

    /* The extension data from the server has the following format:
     *   uint16 name_list_len;
     *   uint8 len;  // where len >= 1
     *   uint8 protocol_name[len]; */
    if (data->len < 4 || data->len > 2 + 1 + 255) {
419
        ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
420 421 422 423
        PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
        return SECFailure;
    }

424 425
    rv = ssl3_ExtConsumeHandshakeNumber(ss, &list_len, 2, &data->data,
                                        &data->len);
426
    /* The list has to be the entire extension. */
427
    if (rv != SECSuccess || list_len != data->len) {
428
        ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
429 430 431 432
        PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
        return SECFailure;
    }

433 434
    rv = ssl3_ExtConsumeHandshakeVariable(ss, &protocol_name, 1,
                                          &data->data, &data->len);
435 436
    /* The list must have exactly one value. */
    if (rv != SECSuccess || data->len != 0) {
437
        ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
438 439 440 441
        PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
        return SECFailure;
    }

442 443 444 445 446 447
    if (!ssl_AlpnTagAllowed(ss, &protocol_name)) {
        ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
        PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
        return SECFailure;
    }

448 449
    SECITEM_FreeItem(&xtnData->nextProto, PR_FALSE);
    xtnData->nextProtoState = SSL_NEXT_PROTO_SELECTED;
450
    xtnData->negotiated[xtnData->numNegotiated++] = ssl_app_layer_protocol_xtn;
451
    return SECITEM_CopyItem(NULL, &xtnData->nextProto, &protocol_name);
452 453
}

454 455 456
SECStatus
ssl3_ClientSendAppProtoXtn(const sslSocket *ss, TLSExtensionData *xtnData,
                           sslBuffer *buf, PRBool *added)
457
{
458 459
    SECStatus rv;
    const unsigned int len = ss->opt.nextProtoNego.len;
460 461 462

    /* Renegotiations do not send this extension. */
    if (!ss->opt.enableALPN || !ss->opt.nextProtoNego.data || ss->firstHsDone) {
463
        return SECSuccess;
464 465
    }

466 467 468 469
    if (len > 0) {
        /* Each protocol string is prefixed with a single byte length. */
        rv = sslBuffer_AppendNumber(buf, len, 2);
        if (rv != SECSuccess) {
470 471
            return SECFailure;
        }
472 473 474
        rv = sslBuffer_Append(buf, ss->opt.nextProtoNego.data, len);
        if (rv != SECSuccess) {
            return SECFailure;
475 476 477
        }
    }

478 479
    *added = PR_TRUE;
    return SECSuccess;
480 481
}

482 483 484
SECStatus
ssl3_ServerSendAppProtoXtn(const sslSocket *ss, TLSExtensionData *xtnData,
                           sslBuffer *buf, PRBool *added)
485
{
486
    SECStatus rv;
487

488
    /* We're in over our heads if any of these fail */
489
    PORT_Assert(ss->opt.enableALPN);
490 491 492
    PORT_Assert(xtnData->nextProto.data);
    PORT_Assert(xtnData->nextProto.len > 0);
    PORT_Assert(xtnData->nextProtoState == SSL_NEXT_PROTO_NEGOTIATED);
493 494
    PORT_Assert(!ss->firstHsDone);

495 496 497
    rv = sslBuffer_AppendNumber(buf, xtnData->nextProto.len + 1, 2);
    if (rv != SECSuccess) {
        return SECFailure;
498
    }
499 500 501 502
    rv = sslBuffer_AppendVariable(buf, xtnData->nextProto.data,
                                  xtnData->nextProto.len, 1);
    if (rv != SECSuccess) {
        return SECFailure;
503 504
    }

505 506
    *added = PR_TRUE;
    return SECSuccess;
507 508 509
}

SECStatus
510
ssl3_ServerHandleStatusRequestXtn(const sslSocket *ss, TLSExtensionData *xtnData,
511 512
                                  SECItem *data)
{
513
    sslExtensionBuilderFunc sender;
514 515 516 517

    PORT_Assert(ss->sec.isServer);

    /* remember that we got this extension. */
518
    xtnData->negotiated[xtnData->numNegotiated++] = ssl_cert_status_xtn;
519 520 521 522 523 524

    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
        sender = tls13_ServerSendStatusRequestXtn;
    } else {
        sender = ssl3_ServerSendStatusRequestXtn;
    }
525
    return ssl3_RegisterExtensionSender(ss, xtnData, ssl_cert_status_xtn, sender);
526 527
}

528 529 530
SECStatus
ssl3_ServerSendStatusRequestXtn(const sslSocket *ss, TLSExtensionData *xtnData,
                                sslBuffer *buf, PRBool *added)
531 532 533 534 535
{
    const sslServerCert *serverCert = ss->sec.serverCert;

    if (!serverCert->certStatusArray ||
        !serverCert->certStatusArray->len) {
536
        return SECSuccess;
537 538
    }

539 540
    *added = PR_TRUE;
    return SECSuccess;
541 542 543 544
}

/* ssl3_ClientSendStatusRequestXtn builds the status_request extension on the
 * client side. See RFC 6066 section 8. */
545 546 547
SECStatus
ssl3_ClientSendStatusRequestXtn(const sslSocket *ss, TLSExtensionData *xtnData,
                                sslBuffer *buf, PRBool *added)
548
{
549
    SECStatus rv;
550

551 552
    if (!ss->opt.enableOCSPStapling) {
        return SECSuccess;
553 554
    }

555 556 557 558 559 560 561 562 563
    rv = sslBuffer_AppendNumber(buf, 1 /* status_type ocsp */, 1);
    if (rv != SECSuccess) {
        return SECFailure;
    }
    /* A zero length responder_id_list means that the responders are
     * implicitly known to the server. */
    rv = sslBuffer_AppendNumber(buf, 0, 2);
    if (rv != SECSuccess) {
        return SECFailure;
564
    }
565 566 567 568 569 570 571 572 573 574
    /* A zero length request_extensions means that there are no extensions.
     * Specifically, we don't set the id-pkix-ocsp-nonce extension. This
     * means that the server can replay a cached OCSP response to us. */
    rv = sslBuffer_AppendNumber(buf, 0, 2);
    if (rv != SECSuccess) {
        return SECFailure;
    }

    *added = PR_TRUE;
    return SECSuccess;
575 576 577
}

SECStatus
578
ssl3_ClientHandleStatusRequestXtn(const sslSocket *ss, TLSExtensionData *xtnData,
579 580 581 582 583
                                  SECItem *data)
{
    /* In TLS 1.3, the extension carries the OCSP response. */
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
        SECStatus rv;
584 585
        rv = ssl_ReadCertificateStatus(CONST_CAST(sslSocket, ss),
                                       data->data, data->len);
586 587 588 589
        if (rv != SECSuccess) {
            return SECFailure; /* code already set */
        }
    } else if (data->len != 0) {
590
        ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
591 592 593 594 595
        PORT_SetError(SSL_ERROR_RX_MALFORMED_SERVER_HELLO);
        return SECFailure;
    }

    /* Keep track of negotiated extensions. */
596
    xtnData->negotiated[xtnData->numNegotiated++] = ssl_cert_status_xtn;
597 598 599
    return SECSuccess;
}

600
#define TLS_EX_SESS_TICKET_VERSION (0x010a)
601

602 603 604 605
/*
 * Called from ssl3_SendNewSessionTicket, tls13_SendNewSessionTicket
 */
SECStatus
606 607 608
ssl3_EncodeSessionTicket(sslSocket *ss, const NewSessionTicket *ticket,
                         const PRUint8 *appToken, unsigned int appTokenLen,
                         PK11SymKey *secret, SECItem *ticket_data)
609 610
{
    SECStatus rv;
611
    sslBuffer plaintext = SSL_BUFFER_EMPTY;
612
    SECItem ticket_buf = { 0, NULL, 0 };
613
    sslSessionID sid;
614 615
    unsigned char wrapped_ms[SSL3_MASTER_SECRET_LENGTH];
    SECItem ms_item = { 0, NULL, 0 };
616
    PRTime now;
617
    SECItem *srvName = NULL;
618
    CK_MECHANISM_TYPE msWrapMech;
619
    SECItem *alpnSelection = NULL;
620
    PRUint32 ticketAgeBaseline;
621 622 623 624 625 626 627

    SSL_TRC(3, ("%d: SSL3[%d]: send session_ticket handshake",
                SSL_GETPID(), ss->fd));

    PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
    PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));

628
    /* Extract the master secret wrapped. */
629

630
    PORT_Memset(&sid, 0, sizeof(sslSessionID));
631

632 633 634 635
    PORT_Assert(secret);
    rv = ssl3_CacheWrappedSecret(ss, &sid, secret);
    if (rv == SECSuccess) {
        if (sid.u.ssl3.keys.wrapped_master_secret_len > sizeof(wrapped_ms))
636
            goto loser;
637 638 639 640 641 642 643 644
        memcpy(wrapped_ms, sid.u.ssl3.keys.wrapped_master_secret,
               sid.u.ssl3.keys.wrapped_master_secret_len);
        ms_item.data = wrapped_ms;
        ms_item.len = sid.u.ssl3.keys.wrapped_master_secret_len;
        msWrapMech = sid.u.ssl3.masterWrapMech;
    } else {
        /* TODO: else send an empty ticket. */
        goto loser;
645 646 647 648
    }
    /* Prep to send negotiated name */
    srvName = &ss->sec.ci.sid->u.ssl3.srvName;

649
    /* ticket version */
650 651
    rv = sslBuffer_AppendNumber(&plaintext, TLS_EX_SESS_TICKET_VERSION,
                                sizeof(PRUint16));
652 653 654 655
    if (rv != SECSuccess)
        goto loser;

    /* ssl_version */
656 657
    rv = sslBuffer_AppendNumber(&plaintext, ss->version,
                                sizeof(SSL3ProtocolVersion));
658 659 660 661
    if (rv != SECSuccess)
        goto loser;

    /* ciphersuite */
662 663
    rv = sslBuffer_AppendNumber(&plaintext, ss->ssl3.hs.cipher_suite,
                                sizeof(ssl3CipherSuite));
664 665 666 667
    if (rv != SECSuccess)
        goto loser;

    /* cipher spec parameters */
668
    rv = sslBuffer_AppendNumber(&plaintext, ss->sec.authType, 1);
669 670
    if (rv != SECSuccess)
        goto loser;
671
    rv = sslBuffer_AppendNumber(&plaintext, ss->sec.authKeyBits, 4);
672 673
    if (rv != SECSuccess)
        goto loser;
674
    rv = sslBuffer_AppendNumber(&plaintext, ss->sec.keaType, 1);
675 676
    if (rv != SECSuccess)
        goto loser;
677
    rv = sslBuffer_AppendNumber(&plaintext, ss->sec.keaKeyBits, 4);
678 679 680
    if (rv != SECSuccess)
        goto loser;
    if (ss->sec.keaGroup) {
681
        rv = sslBuffer_AppendNumber(&plaintext, ss->sec.keaGroup->name, 4);
682 683 684 685
        if (rv != SECSuccess)
            goto loser;
    } else {
        /* No kea group. Write 0 as invalid value. */
686
        rv = sslBuffer_AppendNumber(&plaintext, 0, 4);
687 688 689
        if (rv != SECSuccess)
            goto loser;
    }
690
    rv = sslBuffer_AppendNumber(&plaintext, ss->sec.signatureScheme, 4);
691 692 693 694
    if (rv != SECSuccess)
        goto loser;

    /* certificate type */
695 696 697 698 699 700
    PORT_Assert(SSL_CERT_IS(ss->sec.serverCert, ss->sec.authType));
    if (SSL_CERT_IS_EC(ss->sec.serverCert)) {
        const sslServerCert *cert = ss->sec.serverCert;
        PORT_Assert(cert->namedCurve);
        /* EC curves only use the second of the two bytes. */
        PORT_Assert(cert->namedCurve->name < 256);
701
        rv = sslBuffer_AppendNumber(&plaintext, cert->namedCurve->name, 1);
702
    } else {
703
        rv = sslBuffer_AppendNumber(&plaintext, 0, 1);
704 705 706 707 708
    }
    if (rv != SECSuccess)
        goto loser;

    /* master_secret */
709
    rv = sslBuffer_AppendNumber(&plaintext, msWrapMech, 4);
710 711
    if (rv != SECSuccess)
        goto loser;
712
    rv = sslBuffer_AppendVariable(&plaintext, ms_item.data, ms_item.len, 2);
713 714 715
    if (rv != SECSuccess)
        goto loser;

716
    /* client identity */
717
    if (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) {
718
        rv = sslBuffer_AppendNumber(&plaintext, CLIENT_AUTH_CERTIFICATE, 1);
719 720
        if (rv != SECSuccess)
            goto loser;
721 722 723
        rv = sslBuffer_AppendVariable(&plaintext,
                                      ss->sec.ci.sid->peerCert->derCert.data,
                                      ss->sec.ci.sid->peerCert->derCert.len, 2);
724 725 726
        if (rv != SECSuccess)
            goto loser;
    } else {
727
        rv = sslBuffer_AppendNumber(&plaintext, 0, 1);
728 729 730 731 732
        if (rv != SECSuccess)
            goto loser;
    }

    /* timestamp */
733
    now = ssl_Time(ss);
734
    PORT_Assert(sizeof(now) == 8);
735
    rv = sslBuffer_AppendNumber(&plaintext, now, 8);
736 737 738
    if (rv != SECSuccess)
        goto loser;

739
    /* HostName (length and value) */
740
    rv = sslBuffer_AppendVariable(&plaintext, srvName->data, srvName->len, 2);
741 742
    if (rv != SECSuccess)
        goto loser;
743 744

    /* extendedMasterSecretUsed */
745
    rv = sslBuffer_AppendNumber(
746 747 748 749 750
        &plaintext, ss->sec.ci.sid->u.ssl3.keys.extendedMasterSecretUsed, 1);
    if (rv != SECSuccess)
        goto loser;

    /* Flags */
751 752
    rv = sslBuffer_AppendNumber(&plaintext, ticket->flags,
                                sizeof(ticket->flags));
753 754 755
    if (rv != SECSuccess)
        goto loser;

756
    /* ALPN value. */
757 758 759 760
    PORT_Assert(ss->xtnData.nextProtoState == SSL_NEXT_PROTO_SELECTED ||
                ss->xtnData.nextProtoState == SSL_NEXT_PROTO_NEGOTIATED ||
                ss->xtnData.nextProto.len == 0);
    alpnSelection = &ss->xtnData.nextProto;
761
    PORT_Assert(alpnSelection->len < 256);
762 763
    rv = sslBuffer_AppendVariable(&plaintext, alpnSelection->data,
                                  alpnSelection->len, 1);
764 765 766
    if (rv != SECSuccess)
        goto loser;

767
    rv = sslBuffer_AppendNumber(&plaintext, ss->opt.maxEarlyDataSize, 4);
768 769 770
    if (rv != SECSuccess)
        goto loser;

771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
    /*
     * We store this in the ticket:
     *    ticket_age_baseline = 1rtt - ticket_age_add
     *
     * When the client resumes, it will provide:
     *    obfuscated_age = ticket_age_client + ticket_age_add
     *
     * We expect to receive the ticket at:
     *    ticket_create + 1rtt + ticket_age_server
     *
     * We calculate the client's estimate of this as:
     *    ticket_create + ticket_age_baseline + obfuscated_age
     *    = ticket_create + 1rtt + ticket_age_client
     *
     * This is compared to the expected time, which should differ only as a
     * result of clock errors or errors in the RTT estimate.
     */
788
    ticketAgeBaseline = ss->ssl3.hs.rttEstimate / PR_USEC_PER_MSEC;
789
    ticketAgeBaseline -= ticket->ticket_age_add;
790
    rv = sslBuffer_AppendNumber(&plaintext, ticketAgeBaseline, 4);
791 792 793
    if (rv != SECSuccess)
        goto loser;

794
    /* Application token */
795
    rv = sslBuffer_AppendVariable(&plaintext, appToken, appTokenLen, 2);
796 797 798
    if (rv != SECSuccess)
        goto loser;

799 800 801 802 803 804
    /* This really only happens if appTokenLen is too much, and that always
     * comes from the using application. */
    if (SSL_BUFFER_LEN(&plaintext) > 0xffff) {
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
        goto loser;
    }
805

806 807 808
    ticket_buf.len = ssl_SelfEncryptGetProtectedSize(SSL_BUFFER_LEN(&plaintext));
    PORT_Assert(ticket_buf.len > 0);
    if (SECITEM_AllocItem(NULL, &ticket_buf, ticket_buf.len) == NULL) {
809 810 811
        goto loser;
    }

812
    /* Finally, encrypt the ticket. */
813 814
    rv = ssl_SelfEncryptProtect(ss, SSL_BUFFER_BASE(&plaintext),
                                SSL_BUFFER_LEN(&plaintext),
815 816
                                ticket_buf.data, &ticket_buf.len, ticket_buf.len);
    if (rv != SECSuccess) {
817 818 819 820 821
        goto loser;
    }

    /* Give ownership of memory to caller. */
    *ticket_data = ticket_buf;
822

823
    sslBuffer_Clear(&plaintext);
824
    return SECSuccess;
825 826

loser:
827
    sslBuffer_Clear(&plaintext);
828 829 830 831
    if (ticket_buf.data) {
        SECITEM_FreeItem(&ticket_buf, PR_FALSE);
    }

832
    return SECFailure;
833 834 835 836 837 838
}

/* When a client receives a SessionTicket extension a NewSessionTicket
 * message is expected during the handshake.
 */
SECStatus
839
ssl3_ClientHandleSessionTicketXtn(const sslSocket *ss, TLSExtensionData *xtnData,
840 841
                                  SECItem *data)
{
842 843
    PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);

844 845 846 847 848
    if (data->len != 0) {
        return SECSuccess; /* Ignore the extension. */
    }

    /* Keep track of negotiated extensions. */
849
    xtnData->negotiated[xtnData->numNegotiated++] = ssl_session_ticket_xtn;
850 851 852
    return SECSuccess;
}

853 854
PR_STATIC_ASSERT((TLS_EX_SESS_TICKET_VERSION >> 8) == 1);

855 856 857 858 859 860 861
static SECStatus
ssl_ParseSessionTicket(sslSocket *ss, const SECItem *decryptedTicket,
                       SessionTicket *parsedTicket)
{
    PRUint32 temp;
    SECStatus rv;

862
    PRUint8 *buffer = decryptedTicket->data;
863 864 865 866 867 868 869 870 871
    unsigned int len = decryptedTicket->len;

    PORT_Memset(parsedTicket, 0, sizeof(*parsedTicket));
    parsedTicket->valid = PR_FALSE;

    /* If the decrypted ticket is empty, then report success, but leave the
     * ticket marked as invalid. */
    if (decryptedTicket->len == 0) {
        return SECSuccess;
872 873
    }

874 875 876 877 878 879
    /* Read ticket version. */
    rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 2, &buffer, &len);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }
880

881 882 883 884 885 886
    /* All ticket versions start with 0x01, so check to see if this
     * is a ticket or some other self-encrypted thing. */
    if ((temp >> 8) != 1) {
        PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
        return SECFailure;
    }
887 888 889 890 891
    /* Skip the ticket if the version is wrong.  This won't result in a
     * handshake failure, just a failure to resume. */
    if (temp != TLS_EX_SESS_TICKET_VERSION) {
        return SECSuccess;
    }
892 893

    /* Read SSLVersion. */
894 895 896 897 898 899 900 901 902 903 904
    rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 2, &buffer, &len);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }
    parsedTicket->ssl_version = (SSL3ProtocolVersion)temp;
    if (!ssl3_VersionIsSupported(ss->protocolVariant,
                                 parsedTicket->ssl_version)) {
        /* This socket doesn't support the version from the ticket. */
        return SECSuccess;
    }
905 906

    /* Read cipher_suite. */
907 908 909 910 911 912
    rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 2, &buffer, &len);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }
    parsedTicket->cipher_suite = (ssl3CipherSuite)temp;
913 914

    /* Read cipher spec parameters. */
915 916 917 918 919
    rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 1, &buffer, &len);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }
920 921 922 923

#ifndef UNSAFE_FUZZER_MODE
    PORT_Assert(temp < ssl_auth_size);
#else
924
    temp %= (8 * sizeof(SSLAuthType)) - 1;
925 926
#endif

927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
    parsedTicket->authType = (SSLAuthType)temp;
    rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 4, &buffer, &len);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }
    parsedTicket->authKeyBits = temp;
    rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 1, &buffer, &len);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }
    parsedTicket->keaType = (SSLKEAType)temp;
    rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 4, &buffer, &len);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }
    parsedTicket->keaKeyBits = temp;
946 947 948 949 950 951 952 953 954 955 956 957
    rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 4, &buffer, &len);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }
    parsedTicket->originalKeaGroup = temp;
    rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 4, &buffer, &len);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }
    parsedTicket->signatureScheme = (SSLSignatureScheme)temp;
958

959
    /* Read the optional named curve. */
960 961 962 963 964 965 966 967
    rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 1, &buffer, &len);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }
    if (parsedTicket->authType == ssl_auth_ecdsa ||
        parsedTicket->authType == ssl_auth_ecdh_rsa ||
        parsedTicket->authType == ssl_auth_ecdh_ecdsa) {
968 969 970
        const sslNamedGroupDef *group =
            ssl_LookupNamedGroup((SSLNamedGroup)temp);
        if (!group || group->keaType != ssl_kea_ecdh) {
971 972
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
            return SECFailure;
973
        }
974
        parsedTicket->namedCurve = group;
975 976
    }

977 978 979 980 981 982 983
    /* Read the master secret (and how it is wrapped). */
    rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 4, &buffer, &len);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }
    parsedTicket->msWrapMech = (CK_MECHANISM_TYPE)temp;
984

985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
    rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 2, &buffer, &len);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }
    if (temp == 0 || temp > sizeof(parsedTicket->master_secret)) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }
    parsedTicket->ms_length = (PRUint16)temp;

    /* Read the master secret. */
    rv = ssl3_ExtConsumeHandshake(ss, parsedTicket->master_secret,
                                  parsedTicket->ms_length, &buffer, &len);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }
    /* Read client identity */
    rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 1, &buffer, &len);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }
    parsedTicket->client_auth_type = (ClientAuthenticationType)temp;
    switch (parsedTicket->client_auth_type) {
1011 1012 1013
        case CLIENT_AUTH_ANONYMOUS:
            break;
        case CLIENT_AUTH_CERTIFICATE:
1014 1015 1016 1017 1018 1019
            rv = ssl3_ExtConsumeHandshakeVariable(ss, &parsedTicket->peer_cert, 2,
                                                  &buffer, &len);
            if (rv != SECSuccess) {
                PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
                return SECFailure;
            }
1020 1021
            break;
        default:
1022 1023
            PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
            return SECFailure;
1024
    }
1025 1026 1027

    /* Read timestamp.  This is a 64-bit value and
     * ssl3_ExtConsumeHandshakeNumber only reads 32-bits at a time. */
1028 1029 1030 1031 1032
    rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 4, &buffer, &len);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }
1033 1034 1035

    /* Cast to avoid undefined behavior if the top bit is set. */
    parsedTicket->timestamp = (PRTime)((PRUint64)temp << 32);
1036 1037 1038 1039 1040 1041
    rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 4, &buffer, &len);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }
    parsedTicket->timestamp |= (PRTime)temp;
1042 1043

    /* Read server name */
1044 1045 1046 1047 1048
    rv = ssl3_ExtConsumeHandshakeVariable(ss, &parsedTicket->srvName, 2,
                                          &buffer, &len);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
1049 1050 1051
    }

    /* Read extendedMasterSecretUsed */
1052 1053 1054 1055 1056
    rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 1, &buffer, &len);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }
1057 1058
#ifndef UNSAFE_FUZZER_MODE
    /* A well-behaving server should only write 0 or 1. */
1059
    PORT_Assert(temp == PR_TRUE || temp == PR_FALSE);
1060 1061
#endif
    parsedTicket->extendedMasterSecretUsed = temp ? PR_TRUE : PR_FALSE;
1062

1063 1064 1065 1066 1067 1068
    rv = ssl3_ExtConsumeHandshake(ss, &temp, 4, &buffer, &len);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }
    parsedTicket->flags = PR_ntohl(temp);
1069

1070 1071 1072 1073 1074 1075
    rv = ssl3_ExtConsumeHandshakeVariable(ss, &parsedTicket->alpnSelection, 1,
                                          &buffer, &len);
    PORT_Assert(parsedTicket->alpnSelection.len < 256);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
1076 1077
    }

1078
    rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 4, &buffer, &len);
1079
    if (rv != SECSuccess) {
1080 1081
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
1082
    }
1083
    parsedTicket->maxEarlyData = temp;
1084

1085 1086 1087 1088 1089 1090 1091
    rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 4, &buffer, &len);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }
    parsedTicket->ticketAgeBaseline = temp;

1092 1093 1094 1095 1096 1097 1098
    rv = ssl3_ExtConsumeHandshakeVariable(ss, &parsedTicket->applicationToken,
                                          2, &buffer, &len);
    if (rv != SECSuccess) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }

1099
#ifndef UNSAFE_FUZZER_MODE
1100
    /* Done parsing.  Check that all bytes have been consumed. */
1101 1102 1103
    if (len != 0) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
1104 1105
    }
#endif
1106

1107 1108 1109 1110 1111 1112
    parsedTicket->valid = PR_TRUE;
    return SECSuccess;
}

static SECStatus
ssl_CreateSIDFromTicket(sslSocket *ss, const SECItem *rawTicket,
1113
                        SessionTicket *parsedTicket, sslSessionID **out)
1114
{
1115 1116 1117 1118 1119 1120
    sslSessionID *sid;
    SECStatus rv;

    sid = ssl3_NewSessionID(ss, PR_TRUE);
    if (sid == NULL) {
        return SECFailure;
1121 1122 1123 1124
    }

    /* Copy over parameters. */
    sid->version = parsedTicket->ssl_version;
1125
    sid->creationTime = parsedTicket->timestamp;
1126 1127 1128 1129 1130
    sid->u.ssl3.cipherSuite = parsedTicket->cipher_suite;
    sid->authType = parsedTicket->authType;
    sid->authKeyBits = parsedTicket->authKeyBits;
    sid->keaType = parsedTicket->keaType;
    sid->keaKeyBits = parsedTicket->keaKeyBits;
1131
    sid->keaGroup = parsedTicket->originalKeaGroup;
1132
    sid->namedCurve = parsedTicket->namedCurve;
1133
    sid->sigScheme = parsedTicket->signatureScheme;
1134

1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
    rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.locked.sessionTicket.ticket,
                          rawTicket);
    if (rv != SECSuccess) {
        goto loser;
    }
    sid->u.ssl3.locked.sessionTicket.flags = parsedTicket->flags;
    sid->u.ssl3.locked.sessionTicket.max_early_data_size =
        parsedTicket->maxEarlyData;

    if (parsedTicket->ms_length >
        sizeof(sid->u.ssl3.keys.wrapped_master_secret)) {
        goto loser;
    }
    PORT_Memcpy(sid->u.ssl3.keys.wrapped_master_secret,
                parsedTicket->master_secret, parsedTicket->ms_length);
    sid->u.ssl3.keys.wrapped_master_secret_len = parsedTicket->ms_length;
    sid->u.ssl3.masterWrapMech = parsedTicket->msWrapMech;
    sid->u.ssl3.masterValid = PR_TRUE;
    sid->u.ssl3.keys.resumable = PR_TRUE;
    sid->u.ssl3.keys.extendedMasterSecretUsed = parsedTicket->extendedMasterSecretUsed;

    /* Copy over client cert from session ticket if there is one. */
    if (parsedTicket->peer_cert.data != NULL) {
        PORT_Assert(!sid->peerCert);
        sid->peerCert = CERT_NewTempCertificate(ss->dbHandle,
                                                &parsedTicket->peer_cert,
                                                NULL, PR_FALSE, PR_TRUE);
        if (!sid->peerCert) {
1163 1164
            goto loser;
        }
1165
    }
1166

1167 1168 1169 1170 1171 1172 1173
    /* Transfer ownership of the remaining items. */
    if (parsedTicket->srvName.data != NULL) {
        SECITEM_FreeItem(&sid->u.ssl3.srvName, PR_FALSE);
        rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName,
                              &parsedTicket->srvName);
        if (rv != SECSuccess) {
            goto loser;
1174
        }
1175 1176
    }
    if (parsedTicket->alpnSelection.data != NULL) {
1177
        SECITEM_FreeItem(&sid->u.ssl3.alpnSelection, PR_FALSE);
1178 1179 1180 1181
        rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.alpnSelection,
                              &parsedTicket->alpnSelection);
        if (rv != SECSuccess) {
            goto loser;
1182 1183 1184
        }
    }

1185
    *out = sid;
1186 1187 1188
    return SECSuccess;

loser:
1189
    ssl_FreeSID(sid);
1190 1191 1192 1193 1194
    return SECFailure;
}

/* Generic ticket processing code, common to all TLS versions. */
SECStatus
1195 1196
ssl3_ProcessSessionTicketCommon(sslSocket *ss, const SECItem *ticket,
                                SECItem *appToken)
1197 1198 1199
{
    SECItem decryptedTicket = { siBuffer, NULL, 0 };
    SessionTicket parsedTicket;
1200
    sslSessionID *sid = NULL;
1201 1202
    SECStatus rv;

1203 1204 1205 1206 1207 1208
    if (ss->sec.ci.sid != NULL) {
        ssl_UncacheSessionID(ss);
        ssl_FreeSID(ss->sec.ci.sid);
        ss->sec.ci.sid = NULL;
    }

1209
    if (!SECITEM_AllocItem(NULL, &decryptedTicket, ticket->len)) {
1210 1211 1212
        return SECFailure;
    }

1213
    /* Decrypt the ticket. */
1214
    rv = ssl_SelfEncryptUnprotect(ss, ticket->data, ticket->len,
1215 1216 1217
                                  decryptedTicket.data,
                                  &decryptedTicket.len,
                                  decryptedTicket.len);
1218
    if (rv != SECSuccess) {
1219 1220 1221 1222 1223 1224 1225 1226
        /* Ignore decryption failure if we are doing TLS 1.3; that
         * means the server rejects the client's resumption
         * attempt. In TLS 1.2, however, it's a hard failure, unless
         * it's just because we're not the recipient of the ticket. */
        if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 ||
            PORT_GetError() == SEC_ERROR_NOT_A_RECIPIENT) {
            SECITEM_ZfreeItem(&decryptedTicket, PR_FALSE);
            return SECSuccess;
1227 1228
        }

1229 1230
        SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
        goto loser;
1231 1232 1233 1234 1235 1236
    }

    rv = ssl_ParseSessionTicket(ss, &decryptedTicket, &parsedTicket);
    if (rv != SECSuccess) {
        SSL3Statistics *ssl3stats;

1237 1238 1239 1240
        SSL_DBG(("%d: SSL[%d]: Session ticket parsing failed.",
                 SSL_GETPID(), ss->fd));
        ssl3stats = SSL_GetStatistics();
        SSL_AtomicIncrementLong(&ssl3stats->hch_sid_ticket_parse_failures);
1241
        goto loser; /* code already set */
1242 1243
    }

1244
    /* Use the ticket if it is valid and unexpired. */
1245 1246
    PRTime end = parsedTicket.timestamp + (ssl_ticket_lifetime * PR_USEC_PER_SEC);
    if (end > ssl_Time(ss)) {
1247

1248
        rv = ssl_CreateSIDFromTicket(ss, ticket, &parsedTicket, &sid);
1249 1250
        if (rv != SECSuccess) {
            goto loser; /* code already set */
1251
        }
1252 1253 1254 1255 1256 1257 1258 1259
        if (appToken && parsedTicket.applicationToken.len) {
            rv = SECITEM_CopyItem(NULL, appToken,
                                  &parsedTicket.applicationToken);
            if (rv != SECSuccess) {
                goto loser; /* code already set */
            }
        }

1260
        ss->statelessResume = PR_TRUE;
1261
        ss->sec.ci.sid = sid;
1262 1263 1264 1265 1266

        /* We have the baseline value for the obfuscated ticket age here.  Save
         * that in xtnData temporarily.  This value is updated in
         * tls13_ServerHandlePreSharedKeyXtn with the final estimate. */
        ss->xtnData.ticketAge = parsedTicket.ticketAgeBaseline;
1267 1268
    }

1269 1270 1271 1272 1273
    SECITEM_ZfreeItem(&decryptedTicket, PR_FALSE);
    PORT_Memset(&parsedTicket, 0, sizeof(parsedTicket));
    return SECSuccess;

loser:
1274 1275 1276
    if (sid) {
        ssl_FreeSID(sid);
    }
1277 1278 1279
    SECITEM_ZfreeItem(&decryptedTicket, PR_FALSE);
    PORT_Memset(&parsedTicket, 0, sizeof(parsedTicket));
    return SECFailure;
1280 1281 1282
}

SECStatus
1283
ssl3_ServerHandleSessionTicketXtn(const sslSocket *ss, TLSExtensionData *xtnData,
1284 1285
                                  SECItem *data)
{
1286
    PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298

    /* Ignore the SessionTicket extension if processing is disabled. */
    if (!ss->opt.enableSessionTickets) {
        return SECSuccess;
    }

    /* If we are doing TLS 1.3, then ignore this. */
    if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
        return SECSuccess;
    }

    /* Keep track of negotiated extensions. */
1299
    xtnData->negotiated[xtnData->numNegotiated++] = ssl_session_ticket_xtn;
1300 1301 1302 1303 1304 1305

    /* Parse the received ticket sent in by the client.  We are
     * lenient about some parse errors, falling back to a fullshake
     * instead of terminating the current connection.
     */
    if (data->len == 0) {
1306
        xtnData->emptySessionTicket = PR_TRUE;
1307 1308 1309
        return SECSuccess;
    }

1310 1311
    return ssl3_ProcessSessionTicketCommon(CONST_CAST(sslSocket, ss), data,
                                           NULL);
1312 1313 1314 1315 1316 1317 1318 1319 1320
}

/* Extension format:
 * Extension number:   2 bytes
 * Extension length:   2 bytes
 * Verify Data Length: 1 byte
 * Verify Data (TLS): 12 bytes (client) or 24 bytes (server)
 * Verify Data (SSL): 36 bytes (client) or 72 bytes (server)
 */
1321 1322 1323
SECStatus
ssl3_SendRenegotiationInfoXtn(const sslSocket *ss, TLSExtensionData *xtnData,
                              sslBuffer *buf, PRBool *added)
1324 1325
{
    PRInt32 len = 0;
1326
    SECStatus rv;
1327

1328 1329
    /* In RFC 5746, it is NOT RECOMMENDED to send both the SCSV and the empty
     * RI, so when we send SCSV in the initial handshake, we don't also send RI.
1330
     */
1331
    if (ss->ssl3.hs.sendingSCSV) {
1332
        return 0;
1333
    }
1334 1335 1336 1337
    if (ss->firstHsDone) {
        len = ss->sec.isServer ? ss->ssl3.hs.finishedBytes * 2
                               : ss->ssl3.hs.finishedBytes;
    }
1338 1339 1340 1341 1342 1343

    /* verify_Data from previous Finished message(s) */
    rv = sslBuffer_AppendVariable(buf,
                                  ss->ssl3.hs.finishedMsgs.data, len, 1);
    if (rv != SECSuccess) {
        return SECFailure;
1344
    }
1345 1346 1347

    *added = PR_TRUE;
    return SECSuccess;
1348 1349 1350 1351
}

/* This function runs in both the client and server.  */
SECStatus
1352
ssl3_HandleRenegotiationInfoXtn(const sslSocket *ss, TLSExtensionData *xtnData,
1353
                                SECItem *data)
1354 1355 1356 1357
{
    SECStatus rv = SECSuccess;
    PRUint32 len = 0;

1358 1359
    PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);

1360 1361 1362 1363 1364
    if (ss->firstHsDone) {
        len = ss->sec.isServer ? ss->ssl3.hs.finishedBytes
                               : ss->ssl3.hs.finishedBytes * 2;
    }
    if (data->len != 1 + len || data->data[0] != len) {
1365
        ssl3_ExtDecodeError(ss);
1366 1367 1368 1369
        return SECFailure;
    }
    if (len && NSS_SecureMemcmp(ss->ssl3.hs.finishedMsgs.data,
                                data->data + 1, len)) {
1370
        ssl3_ExtSendAlert(ss, alert_fatal, handshake_failure);
1371 1372 1373 1374
        PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
        return SECFailure;
    }
    /* remember that we got this extension and it was correct. */
1375 1376
    CONST_CAST(sslSocket, ss)
        ->peerRequestedProtection = 1;
1377
    xtnData->negotiated[xtnData->numNegotiated++] = ssl_renegotiation_info_xtn;
1378 1379
    if (ss->sec.isServer) {
        /* prepare to send back the appropriate response */
1380 1381
        rv = ssl3_RegisterExtensionSender(ss, xtnData,
                                          ssl_renegotiation_info_xtn,
1382
                                          ssl3_SendRenegotiationInfoXtn);
1383 1384 1385 1386
    }
    return rv;
}

1387 1388 1389
SECStatus
ssl3_ClientSendUseSRTPXtn(const sslSocket *ss, TLSExtensionData *xtnData,
                          sslBuffer *buf, PRBool *added)
1390
{
1391
    unsigned int i;
1392 1393
    SECStatus rv;

1394 1395 1396
    if (!IS_DTLS(ss) || !ss->ssl3.dtlsSRTPCipherCount) {
        return SECSuccess; /* Not relevant */
    }
1397

1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
    /* Length of the SRTP cipher list */
    rv = sslBuffer_AppendNumber(buf, 2 * ss->ssl3.dtlsSRTPCipherCount, 2);
    if (rv != SECSuccess) {
        return SECFailure;
    }
    /* The SRTP ciphers */
    for (i = 0; i < ss->ssl3.dtlsSRTPCipherCount; i++) {
        rv = sslBuffer_AppendNumber(buf, ss->ssl3.dtlsSRTPCiphers[i], 2);
        if (rv != SECSuccess) {
            return SECFailure;
1408
        }
1409 1410 1411 1412 1413
    }
    /* Empty MKI value */
    rv = sslBuffer_AppendNumber(buf, 0, 1);
    if (rv != SECSuccess) {
        return SECFailure;
1414 1415
    }

1416 1417
    *added = PR_TRUE;
    return SECSuccess;
1418 1419
}

1420 1421 1422
SECStatus
ssl3_ServerSendUseSRTPXtn(const sslSocket *ss, TLSExtensionData *xtnData,
                          sslBuffer *buf, PRBool *added)
1423 1424 1425 1426
{
    SECStatus rv;

    /* Length of the SRTP cipher list */
1427 1428 1429 1430
    rv = sslBuffer_AppendNumber(buf, 2, 2);
    if (rv != SECSuccess) {
        return SECFailure;
    }
1431
    /* The selected cipher */
1432 1433 1434 1435
    rv = sslBuffer_AppendNumber