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