ssl3ext.c revision a36e5920737c6adbddd3e43b760e5de8431db6e0
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
728    /* Renegotiations do not send this extension. */
729    if (!ss->opt.nextProtoNego.data || ss->firstHsDone) {
730	return 0;
731    }
732
733    extension_length = 2 /* extension type */ + 2 /* extension length */ +
734                       2 /* protocol name list length */ +
735                       ss->opt.nextProtoNego.len;
736
737    if (append && maxBytes >= extension_length) {
738	SECStatus rv;
739	rv = ssl3_AppendHandshakeNumber(ss, ssl_app_layer_protocol_xtn, 2);
740	if (rv != SECSuccess)
741	    goto loser;
742	rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2);
743	if (rv != SECSuccess)
744	    goto loser;
745	rv = ssl3_AppendHandshakeVariable(ss, ss->opt.nextProtoNego.data,
746					  ss->opt.nextProtoNego.len, 2);
747	if (rv != SECSuccess)
748	    goto loser;
749	ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
750		ssl_app_layer_protocol_xtn;
751    } else if (maxBytes < extension_length) {
752	return 0;
753    }
754
755    return extension_length;
756
757loser:
758    return -1;
759}
760
761static SECStatus
762ssl3_ClientHandleChannelIDXtn(sslSocket *ss, PRUint16 ex_type,
763			     SECItem *data)
764{
765    PORT_Assert(ss->getChannelID != NULL);
766
767    if (data->len) {
768	PORT_SetError(SSL_ERROR_BAD_CHANNEL_ID_DATA);
769	return SECFailure;
770    }
771    ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
772    return SECSuccess;
773}
774
775static PRInt32
776ssl3_ClientSendChannelIDXtn(sslSocket * ss, PRBool append,
777			    PRUint32 maxBytes)
778{
779    PRInt32 extension_length = 4;
780
781    if (!ss->getChannelID)
782	return 0;
783
784    if (maxBytes < extension_length) {
785	PORT_Assert(0);
786	return 0;
787    }
788
789    if (append) {
790	SECStatus rv;
791	rv = ssl3_AppendHandshakeNumber(ss, ssl_channel_id_xtn, 2);
792	if (rv != SECSuccess)
793	    goto loser;
794	rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
795	if (rv != SECSuccess)
796	    goto loser;
797	ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
798		ssl_channel_id_xtn;
799    }
800
801    return extension_length;
802
803loser:
804    return -1;
805}
806
807static SECStatus
808ssl3_ClientHandleStatusRequestXtn(sslSocket *ss, PRUint16 ex_type,
809                                 SECItem *data)
810{
811    /* The echoed extension must be empty. */
812    if (data->len != 0)
813       return SECFailure;
814
815    /* Keep track of negotiated extensions. */
816    ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
817
818    return SECSuccess;
819}
820
821static PRInt32
822ssl3_ServerSendStatusRequestXtn(
823			sslSocket * ss,
824			PRBool      append,
825			PRUint32    maxBytes)
826{
827    PRInt32 extension_length;
828    SECStatus rv;
829    int i;
830    PRBool haveStatus = PR_FALSE;
831
832    for (i = kt_null; i < kt_kea_size; i++) {
833	/* TODO: This is a temporary workaround.
834	 *       The correct code needs to see if we have an OCSP response for
835	 *       the server certificate being used, rather than if we have any
836	 *       OCSP response. See also ssl3_SendCertificateStatus.
837	 */
838	if (ss->certStatusArray[i] && ss->certStatusArray[i]->len) {
839	    haveStatus = PR_TRUE;
840	    break;
841	}
842    }
843    if (!haveStatus)
844	return 0;
845
846    extension_length = 2 + 2;
847    if (append && maxBytes >= extension_length) {
848	/* extension_type */
849	rv = ssl3_AppendHandshakeNumber(ss, ssl_cert_status_xtn, 2);
850	if (rv != SECSuccess)
851	    return -1;
852	/* length of extension_data */
853	rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
854	if (rv != SECSuccess)
855	    return -1;
856    }
857
858    return extension_length;
859}
860
861/* ssl3_ClientSendStatusRequestXtn builds the status_request extension on the
862 * client side. See RFC 4366 section 3.6. */
863static PRInt32
864ssl3_ClientSendStatusRequestXtn(sslSocket * ss, PRBool append,
865                               PRUint32 maxBytes)
866{
867    PRInt32 extension_length;
868
869    if (!ss->opt.enableOCSPStapling)
870       return 0;
871
872    /* extension_type (2-bytes) +
873     * length(extension_data) (2-bytes) +
874     * status_type (1) +
875     * responder_id_list length (2) +
876     * request_extensions length (2)
877     */
878    extension_length = 9;
879
880    if (append && maxBytes >= extension_length) {
881       SECStatus rv;
882       TLSExtensionData *xtnData;
883
884       /* extension_type */
885       rv = ssl3_AppendHandshakeNumber(ss, ssl_cert_status_xtn, 2);
886       if (rv != SECSuccess)
887           return -1;
888       rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2);
889       if (rv != SECSuccess)
890           return -1;
891       rv = ssl3_AppendHandshakeNumber(ss, 1 /* status_type ocsp */, 1);
892       if (rv != SECSuccess)
893           return -1;
894       /* A zero length responder_id_list means that the responders are
895        * implicitly known to the server. */
896       rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
897       if (rv != SECSuccess)
898           return -1;
899       /* A zero length request_extensions means that there are no extensions.
900        * Specifically, we don't set the id-pkix-ocsp-nonce extension. This
901        * means that the server can replay a cached OCSP response to us. */
902       rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
903       if (rv != SECSuccess)
904           return -1;
905
906       xtnData = &ss->xtnData;
907       xtnData->advertised[xtnData->numAdvertised++] = ssl_cert_status_xtn;
908    } else if (maxBytes < extension_length) {
909       PORT_Assert(0);
910       return 0;
911    }
912    return extension_length;
913}
914
915/*
916 * NewSessionTicket
917 * Called from ssl3_HandleFinished
918 */
919SECStatus
920ssl3_SendNewSessionTicket(sslSocket *ss)
921{
922    int                  i;
923    SECStatus            rv;
924    NewSessionTicket     ticket;
925    SECItem              plaintext;
926    SECItem              plaintext_item = {0, NULL, 0};
927    SECItem              ciphertext     = {0, NULL, 0};
928    PRUint32             ciphertext_length;
929    PRBool               ms_is_wrapped;
930    unsigned char        wrapped_ms[SSL3_MASTER_SECRET_LENGTH];
931    SECItem              ms_item = {0, NULL, 0};
932    SSL3KEAType          effectiveExchKeyType = ssl_kea_null;
933    PRUint32             padding_length;
934    PRUint32             message_length;
935    PRUint32             cert_length;
936    PRUint8              length_buf[4];
937    PRUint32             now;
938    PK11SymKey          *aes_key_pkcs11;
939    PK11SymKey          *mac_key_pkcs11;
940#ifndef NO_PKCS11_BYPASS
941    const unsigned char *aes_key;
942    const unsigned char *mac_key;
943    PRUint32             aes_key_length;
944    PRUint32             mac_key_length;
945    PRUint64             aes_ctx_buf[MAX_CIPHER_CONTEXT_LLONGS];
946    AESContext          *aes_ctx;
947    const SECHashObject *hashObj = NULL;
948    PRUint64             hmac_ctx_buf[MAX_MAC_CONTEXT_LLONGS];
949    HMACContext         *hmac_ctx;
950#endif
951    CK_MECHANISM_TYPE    cipherMech = CKM_AES_CBC;
952    PK11Context         *aes_ctx_pkcs11;
953    CK_MECHANISM_TYPE    macMech = CKM_SHA256_HMAC;
954    PK11Context         *hmac_ctx_pkcs11;
955    unsigned char        computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH];
956    unsigned int         computed_mac_length;
957    unsigned char        iv[AES_BLOCK_SIZE];
958    SECItem              ivItem;
959    SECItem             *srvName = NULL;
960    PRUint32             srvNameLen = 0;
961    CK_MECHANISM_TYPE    msWrapMech = 0; /* dummy default value,
962                                          * must be >= 0 */
963
964    SSL_TRC(3, ("%d: SSL3[%d]: send session_ticket handshake",
965		SSL_GETPID(), ss->fd));
966
967    PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
968    PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
969
970    ticket.ticket_lifetime_hint = TLS_EX_SESS_TICKET_LIFETIME_HINT;
971    cert_length = (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) ?
972	3 + ss->sec.ci.sid->peerCert->derCert.len : 0;
973
974    /* Get IV and encryption keys */
975    ivItem.data = iv;
976    ivItem.len = sizeof(iv);
977    rv = PK11_GenerateRandom(iv, sizeof(iv));
978    if (rv != SECSuccess) goto loser;
979
980#ifndef NO_PKCS11_BYPASS
981    if (ss->opt.bypassPKCS11) {
982	rv = ssl3_GetSessionTicketKeys(&aes_key, &aes_key_length,
983	    &mac_key, &mac_key_length);
984    } else
985#endif
986    {
987	rv = ssl3_GetSessionTicketKeysPKCS11(ss, &aes_key_pkcs11,
988	    &mac_key_pkcs11);
989    }
990    if (rv != SECSuccess) goto loser;
991
992    if (ss->ssl3.pwSpec->msItem.len && ss->ssl3.pwSpec->msItem.data) {
993	/* The master secret is available unwrapped. */
994	ms_item.data = ss->ssl3.pwSpec->msItem.data;
995	ms_item.len = ss->ssl3.pwSpec->msItem.len;
996	ms_is_wrapped = PR_FALSE;
997    } else {
998	/* Extract the master secret wrapped. */
999	sslSessionID sid;
1000	PORT_Memset(&sid, 0, sizeof(sslSessionID));
1001
1002	if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) {
1003	    effectiveExchKeyType = kt_rsa;
1004	} else {
1005	    effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType;
1006	}
1007
1008	rv = ssl3_CacheWrappedMasterSecret(ss, &sid, ss->ssl3.pwSpec,
1009	    effectiveExchKeyType);
1010	if (rv == SECSuccess) {
1011	    if (sid.u.ssl3.keys.wrapped_master_secret_len > sizeof(wrapped_ms))
1012		goto loser;
1013	    memcpy(wrapped_ms, sid.u.ssl3.keys.wrapped_master_secret,
1014		sid.u.ssl3.keys.wrapped_master_secret_len);
1015	    ms_item.data = wrapped_ms;
1016	    ms_item.len = sid.u.ssl3.keys.wrapped_master_secret_len;
1017	    msWrapMech = sid.u.ssl3.masterWrapMech;
1018	} else {
1019	    /* TODO: else send an empty ticket. */
1020	    goto loser;
1021	}
1022	ms_is_wrapped = PR_TRUE;
1023    }
1024    /* Prep to send negotiated name */
1025    srvName = &ss->ssl3.pwSpec->srvVirtName;
1026    if (srvName->data && srvName->len) {
1027        srvNameLen = 2 + srvName->len; /* len bytes + name len */
1028    }
1029
1030    ciphertext_length =
1031	sizeof(PRUint16)                     /* ticket_version */
1032	+ sizeof(SSL3ProtocolVersion)        /* ssl_version */
1033	+ sizeof(ssl3CipherSuite)            /* ciphersuite */
1034	+ 1                                  /* compression */
1035	+ 10                                 /* cipher spec parameters */
1036	+ 1                                  /* SessionTicket.ms_is_wrapped */
1037	+ 1                                  /* effectiveExchKeyType */
1038	+ 4                                  /* msWrapMech */
1039	+ 2                                  /* master_secret.length */
1040	+ ms_item.len                        /* master_secret */
1041	+ 1                                  /* client_auth_type */
1042	+ cert_length                        /* cert */
1043        + 1                                  /* server name type */
1044        + srvNameLen                         /* name len + length field */
1045	+ sizeof(ticket.ticket_lifetime_hint);
1046    padding_length =  AES_BLOCK_SIZE -
1047	(ciphertext_length % AES_BLOCK_SIZE);
1048    ciphertext_length += padding_length;
1049
1050    message_length =
1051	sizeof(ticket.ticket_lifetime_hint)    /* ticket_lifetime_hint */
1052	+ 2 /* length field for NewSessionTicket.ticket */
1053	+ SESS_TICKET_KEY_NAME_LEN             /* key_name */
1054	+ AES_BLOCK_SIZE                       /* iv */
1055	+ 2 /* length field for NewSessionTicket.ticket.encrypted_state */
1056	+ ciphertext_length                    /* encrypted_state */
1057	+ TLS_EX_SESS_TICKET_MAC_LENGTH;       /* mac */
1058
1059    if (SECITEM_AllocItem(NULL, &plaintext_item, ciphertext_length) == NULL)
1060	goto loser;
1061
1062    plaintext = plaintext_item;
1063
1064    /* ticket_version */
1065    rv = ssl3_AppendNumberToItem(&plaintext, TLS_EX_SESS_TICKET_VERSION,
1066	sizeof(PRUint16));
1067    if (rv != SECSuccess) goto loser;
1068
1069    /* ssl_version */
1070    rv = ssl3_AppendNumberToItem(&plaintext, ss->version,
1071	sizeof(SSL3ProtocolVersion));
1072    if (rv != SECSuccess) goto loser;
1073
1074    /* ciphersuite */
1075    rv = ssl3_AppendNumberToItem(&plaintext, ss->ssl3.hs.cipher_suite,
1076	sizeof(ssl3CipherSuite));
1077    if (rv != SECSuccess) goto loser;
1078
1079    /* compression */
1080    rv = ssl3_AppendNumberToItem(&plaintext, ss->ssl3.hs.compression, 1);
1081    if (rv != SECSuccess) goto loser;
1082
1083    /* cipher spec parameters */
1084    rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.authAlgorithm, 1);
1085    if (rv != SECSuccess) goto loser;
1086    rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.authKeyBits, 4);
1087    if (rv != SECSuccess) goto loser;
1088    rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.keaType, 1);
1089    if (rv != SECSuccess) goto loser;
1090    rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.keaKeyBits, 4);
1091    if (rv != SECSuccess) goto loser;
1092
1093    /* master_secret */
1094    rv = ssl3_AppendNumberToItem(&plaintext, ms_is_wrapped, 1);
1095    if (rv != SECSuccess) goto loser;
1096    rv = ssl3_AppendNumberToItem(&plaintext, effectiveExchKeyType, 1);
1097    if (rv != SECSuccess) goto loser;
1098    rv = ssl3_AppendNumberToItem(&plaintext, msWrapMech, 4);
1099    if (rv != SECSuccess) goto loser;
1100    rv = ssl3_AppendNumberToItem(&plaintext, ms_item.len, 2);
1101    if (rv != SECSuccess) goto loser;
1102    rv = ssl3_AppendToItem(&plaintext, ms_item.data, ms_item.len);
1103    if (rv != SECSuccess) goto loser;
1104
1105    /* client_identity */
1106    if (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) {
1107	rv = ssl3_AppendNumberToItem(&plaintext, CLIENT_AUTH_CERTIFICATE, 1);
1108	if (rv != SECSuccess) goto loser;
1109	rv = ssl3_AppendNumberToItem(&plaintext,
1110	    ss->sec.ci.sid->peerCert->derCert.len, 3);
1111	if (rv != SECSuccess) goto loser;
1112	rv = ssl3_AppendToItem(&plaintext,
1113	    ss->sec.ci.sid->peerCert->derCert.data,
1114	    ss->sec.ci.sid->peerCert->derCert.len);
1115	if (rv != SECSuccess) goto loser;
1116    } else {
1117	rv = ssl3_AppendNumberToItem(&plaintext, 0, 1);
1118	if (rv != SECSuccess) goto loser;
1119    }
1120
1121    /* timestamp */
1122    now = ssl_Time();
1123    rv = ssl3_AppendNumberToItem(&plaintext, now,
1124	sizeof(ticket.ticket_lifetime_hint));
1125    if (rv != SECSuccess) goto loser;
1126
1127    if (srvNameLen) {
1128        /* Name Type (sni_host_name) */
1129        rv = ssl3_AppendNumberToItem(&plaintext, srvName->type, 1);
1130        if (rv != SECSuccess) goto loser;
1131        /* HostName (length and value) */
1132        rv = ssl3_AppendNumberToItem(&plaintext, srvName->len, 2);
1133        if (rv != SECSuccess) goto loser;
1134        rv = ssl3_AppendToItem(&plaintext, srvName->data, srvName->len);
1135        if (rv != SECSuccess) goto loser;
1136    } else {
1137        /* No Name */
1138        rv = ssl3_AppendNumberToItem(&plaintext, (char)TLS_STE_NO_SERVER_NAME,
1139                                     1);
1140        if (rv != SECSuccess) goto loser;
1141    }
1142
1143    PORT_Assert(plaintext.len == padding_length);
1144    for (i = 0; i < padding_length; i++)
1145	plaintext.data[i] = (unsigned char)padding_length;
1146
1147    if (SECITEM_AllocItem(NULL, &ciphertext, ciphertext_length) == NULL) {
1148	rv = SECFailure;
1149	goto loser;
1150    }
1151
1152    /* Generate encrypted portion of ticket. */
1153#ifndef NO_PKCS11_BYPASS
1154    if (ss->opt.bypassPKCS11) {
1155	aes_ctx = (AESContext *)aes_ctx_buf;
1156	rv = AES_InitContext(aes_ctx, aes_key, aes_key_length, iv,
1157	    NSS_AES_CBC, 1, AES_BLOCK_SIZE);
1158	if (rv != SECSuccess) goto loser;
1159
1160	rv = AES_Encrypt(aes_ctx, ciphertext.data, &ciphertext.len,
1161	    ciphertext.len, plaintext_item.data,
1162	    plaintext_item.len);
1163	if (rv != SECSuccess) goto loser;
1164    } else
1165#endif
1166    {
1167	aes_ctx_pkcs11 = PK11_CreateContextBySymKey(cipherMech,
1168	    CKA_ENCRYPT, aes_key_pkcs11, &ivItem);
1169	if (!aes_ctx_pkcs11)
1170	    goto loser;
1171
1172	rv = PK11_CipherOp(aes_ctx_pkcs11, ciphertext.data,
1173	    (int *)&ciphertext.len, ciphertext.len,
1174	    plaintext_item.data, plaintext_item.len);
1175	PK11_Finalize(aes_ctx_pkcs11);
1176	PK11_DestroyContext(aes_ctx_pkcs11, PR_TRUE);
1177	if (rv != SECSuccess) goto loser;
1178    }
1179
1180    /* Convert ciphertext length to network order. */
1181    length_buf[0] = (ciphertext.len >> 8) & 0xff;
1182    length_buf[1] = (ciphertext.len     ) & 0xff;
1183
1184    /* Compute MAC. */
1185#ifndef NO_PKCS11_BYPASS
1186    if (ss->opt.bypassPKCS11) {
1187	hmac_ctx = (HMACContext *)hmac_ctx_buf;
1188	hashObj = HASH_GetRawHashObject(HASH_AlgSHA256);
1189	if (HMAC_Init(hmac_ctx, hashObj, mac_key,
1190		mac_key_length, PR_FALSE) != SECSuccess)
1191	    goto loser;
1192
1193	HMAC_Begin(hmac_ctx);
1194	HMAC_Update(hmac_ctx, key_name, SESS_TICKET_KEY_NAME_LEN);
1195	HMAC_Update(hmac_ctx, iv, sizeof(iv));
1196	HMAC_Update(hmac_ctx, (unsigned char *)length_buf, 2);
1197	HMAC_Update(hmac_ctx, ciphertext.data, ciphertext.len);
1198	HMAC_Finish(hmac_ctx, computed_mac, &computed_mac_length,
1199	    sizeof(computed_mac));
1200    } else
1201#endif
1202    {
1203	SECItem macParam;
1204	macParam.data = NULL;
1205	macParam.len = 0;
1206	hmac_ctx_pkcs11 = PK11_CreateContextBySymKey(macMech,
1207	    CKA_SIGN, mac_key_pkcs11, &macParam);
1208	if (!hmac_ctx_pkcs11)
1209	    goto loser;
1210
1211	rv = PK11_DigestBegin(hmac_ctx_pkcs11);
1212	rv = PK11_DigestOp(hmac_ctx_pkcs11, key_name,
1213	    SESS_TICKET_KEY_NAME_LEN);
1214	rv = PK11_DigestOp(hmac_ctx_pkcs11, iv, sizeof(iv));
1215	rv = PK11_DigestOp(hmac_ctx_pkcs11, (unsigned char *)length_buf, 2);
1216	rv = PK11_DigestOp(hmac_ctx_pkcs11, ciphertext.data, ciphertext.len);
1217	rv = PK11_DigestFinal(hmac_ctx_pkcs11, computed_mac,
1218	    &computed_mac_length, sizeof(computed_mac));
1219	PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE);
1220	if (rv != SECSuccess) goto loser;
1221    }
1222
1223    /* Serialize the handshake message. */
1224    rv = ssl3_AppendHandshakeHeader(ss, new_session_ticket, message_length);
1225    if (rv != SECSuccess) goto loser;
1226
1227    rv = ssl3_AppendHandshakeNumber(ss, ticket.ticket_lifetime_hint,
1228	sizeof(ticket.ticket_lifetime_hint));
1229    if (rv != SECSuccess) goto loser;
1230
1231    rv = ssl3_AppendHandshakeNumber(ss,
1232	message_length - sizeof(ticket.ticket_lifetime_hint) - 2, 2);
1233    if (rv != SECSuccess) goto loser;
1234
1235    rv = ssl3_AppendHandshake(ss, key_name, SESS_TICKET_KEY_NAME_LEN);
1236    if (rv != SECSuccess) goto loser;
1237
1238    rv = ssl3_AppendHandshake(ss, iv, sizeof(iv));
1239    if (rv != SECSuccess) goto loser;
1240
1241    rv = ssl3_AppendHandshakeVariable(ss, ciphertext.data, ciphertext.len, 2);
1242    if (rv != SECSuccess) goto loser;
1243
1244    rv = ssl3_AppendHandshake(ss, computed_mac, computed_mac_length);
1245    if (rv != SECSuccess) goto loser;
1246
1247loser:
1248    if (plaintext_item.data)
1249	SECITEM_FreeItem(&plaintext_item, PR_FALSE);
1250    if (ciphertext.data)
1251	SECITEM_FreeItem(&ciphertext, PR_FALSE);
1252
1253    return rv;
1254}
1255
1256/* When a client receives a SessionTicket extension a NewSessionTicket
1257 * message is expected during the handshake.
1258 */
1259SECStatus
1260ssl3_ClientHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type,
1261                                  SECItem *data)
1262{
1263    if (data->len != 0)
1264	return SECFailure;
1265
1266    /* Keep track of negotiated extensions. */
1267    ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
1268    return SECSuccess;
1269}
1270
1271SECStatus
1272ssl3_ServerHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type,
1273                                  SECItem *data)
1274{
1275    SECStatus rv;
1276    SECItem *decrypted_state = NULL;
1277    SessionTicket *parsed_session_ticket = NULL;
1278    sslSessionID *sid = NULL;
1279    SSL3Statistics *ssl3stats;
1280
1281    /* Ignore the SessionTicket extension if processing is disabled. */
1282    if (!ss->opt.enableSessionTickets)
1283	return SECSuccess;
1284
1285    /* Keep track of negotiated extensions. */
1286    ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
1287
1288    /* Parse the received ticket sent in by the client.  We are
1289     * lenient about some parse errors, falling back to a fullshake
1290     * instead of terminating the current connection.
1291     */
1292    if (data->len == 0) {
1293	ss->xtnData.emptySessionTicket = PR_TRUE;
1294    } else {
1295	int                    i;
1296	SECItem                extension_data;
1297	EncryptedSessionTicket enc_session_ticket;
1298	unsigned char          computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH];
1299	unsigned int           computed_mac_length;
1300#ifndef NO_PKCS11_BYPASS
1301	const SECHashObject   *hashObj;
1302	const unsigned char   *aes_key;
1303	const unsigned char   *mac_key;
1304	PRUint32               aes_key_length;
1305	PRUint32               mac_key_length;
1306	PRUint64               hmac_ctx_buf[MAX_MAC_CONTEXT_LLONGS];
1307	HMACContext           *hmac_ctx;
1308	PRUint64               aes_ctx_buf[MAX_CIPHER_CONTEXT_LLONGS];
1309	AESContext            *aes_ctx;
1310#endif
1311	PK11SymKey            *aes_key_pkcs11;
1312	PK11SymKey            *mac_key_pkcs11;
1313	PK11Context           *hmac_ctx_pkcs11;
1314	CK_MECHANISM_TYPE      macMech = CKM_SHA256_HMAC;
1315	PK11Context           *aes_ctx_pkcs11;
1316	CK_MECHANISM_TYPE      cipherMech = CKM_AES_CBC;
1317	unsigned char *        padding;
1318	PRUint32               padding_length;
1319	unsigned char         *buffer;
1320	unsigned int           buffer_len;
1321	PRInt32                temp;
1322	SECItem                cert_item;
1323        PRInt8                 nameType = TLS_STE_NO_SERVER_NAME;
1324
1325	/* Turn off stateless session resumption if the client sends a
1326	 * SessionTicket extension, even if the extension turns out to be
1327	 * malformed (ss->sec.ci.sid is non-NULL when doing session
1328	 * renegotiation.)
1329	 */
1330	if (ss->sec.ci.sid != NULL) {
1331	    if (ss->sec.uncache)
1332		ss->sec.uncache(ss->sec.ci.sid);
1333	    ssl_FreeSID(ss->sec.ci.sid);
1334	    ss->sec.ci.sid = NULL;
1335	}
1336
1337	extension_data.data = data->data; /* Keep a copy for future use. */
1338	extension_data.len = data->len;
1339
1340	if (ssl3_ParseEncryptedSessionTicket(ss, data, &enc_session_ticket)
1341	    != SECSuccess)
1342	    return SECFailure;
1343
1344	/* Get session ticket keys. */
1345#ifndef NO_PKCS11_BYPASS
1346	if (ss->opt.bypassPKCS11) {
1347	    rv = ssl3_GetSessionTicketKeys(&aes_key, &aes_key_length,
1348		&mac_key, &mac_key_length);
1349	} else
1350#endif
1351	{
1352	    rv = ssl3_GetSessionTicketKeysPKCS11(ss, &aes_key_pkcs11,
1353		&mac_key_pkcs11);
1354	}
1355	if (rv != SECSuccess) {
1356	    SSL_DBG(("%d: SSL[%d]: Unable to get/generate session ticket keys.",
1357			SSL_GETPID(), ss->fd));
1358	    goto loser;
1359	}
1360
1361	/* If the ticket sent by the client was generated under a key different
1362	 * from the one we have, bypass ticket processing.
1363	 */
1364	if (PORT_Memcmp(enc_session_ticket.key_name, key_name,
1365		SESS_TICKET_KEY_NAME_LEN) != 0) {
1366	    SSL_DBG(("%d: SSL[%d]: Session ticket key_name sent mismatch.",
1367			SSL_GETPID(), ss->fd));
1368	    goto no_ticket;
1369	}
1370
1371	/* Verify the MAC on the ticket.  MAC verification may also
1372	 * fail if the MAC key has been recently refreshed.
1373	 */
1374#ifndef NO_PKCS11_BYPASS
1375	if (ss->opt.bypassPKCS11) {
1376	    hmac_ctx = (HMACContext *)hmac_ctx_buf;
1377	    hashObj = HASH_GetRawHashObject(HASH_AlgSHA256);
1378	    if (HMAC_Init(hmac_ctx, hashObj, mac_key,
1379		    sizeof(session_ticket_mac_key), PR_FALSE) != SECSuccess)
1380		goto no_ticket;
1381	    HMAC_Begin(hmac_ctx);
1382	    HMAC_Update(hmac_ctx, extension_data.data,
1383		extension_data.len - TLS_EX_SESS_TICKET_MAC_LENGTH);
1384	    if (HMAC_Finish(hmac_ctx, computed_mac, &computed_mac_length,
1385		    sizeof(computed_mac)) != SECSuccess)
1386		goto no_ticket;
1387	} else
1388#endif
1389	{
1390	    SECItem macParam;
1391	    macParam.data = NULL;
1392	    macParam.len = 0;
1393	    hmac_ctx_pkcs11 = PK11_CreateContextBySymKey(macMech,
1394		CKA_SIGN, mac_key_pkcs11, &macParam);
1395	    if (!hmac_ctx_pkcs11) {
1396		SSL_DBG(("%d: SSL[%d]: Unable to create HMAC context: %d.",
1397			    SSL_GETPID(), ss->fd, PORT_GetError()));
1398		goto no_ticket;
1399	    } else {
1400		SSL_DBG(("%d: SSL[%d]: Successfully created HMAC context.",
1401			    SSL_GETPID(), ss->fd));
1402	    }
1403	    rv = PK11_DigestBegin(hmac_ctx_pkcs11);
1404	    rv = PK11_DigestOp(hmac_ctx_pkcs11, extension_data.data,
1405		extension_data.len - TLS_EX_SESS_TICKET_MAC_LENGTH);
1406	    if (rv != SECSuccess) {
1407		PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE);
1408		goto no_ticket;
1409	    }
1410	    rv = PK11_DigestFinal(hmac_ctx_pkcs11, computed_mac,
1411		&computed_mac_length, sizeof(computed_mac));
1412	    PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE);
1413	    if (rv != SECSuccess)
1414		goto no_ticket;
1415	}
1416	if (NSS_SecureMemcmp(computed_mac, enc_session_ticket.mac,
1417		computed_mac_length) != 0) {
1418	    SSL_DBG(("%d: SSL[%d]: Session ticket MAC mismatch.",
1419			SSL_GETPID(), ss->fd));
1420	    goto no_ticket;
1421	}
1422
1423	/* We ignore key_name for now.
1424	 * This is ok as MAC verification succeeded.
1425	 */
1426
1427	/* Decrypt the ticket. */
1428
1429	/* Plaintext is shorter than the ciphertext due to padding. */
1430	decrypted_state = SECITEM_AllocItem(NULL, NULL,
1431	    enc_session_ticket.encrypted_state.len);
1432
1433#ifndef NO_PKCS11_BYPASS
1434	if (ss->opt.bypassPKCS11) {
1435	    aes_ctx = (AESContext *)aes_ctx_buf;
1436	    rv = AES_InitContext(aes_ctx, aes_key,
1437		sizeof(session_ticket_enc_key), enc_session_ticket.iv,
1438		NSS_AES_CBC, 0,AES_BLOCK_SIZE);
1439	    if (rv != SECSuccess) {
1440		SSL_DBG(("%d: SSL[%d]: Unable to create AES context.",
1441			    SSL_GETPID(), ss->fd));
1442		goto no_ticket;
1443	    }
1444
1445	    rv = AES_Decrypt(aes_ctx, decrypted_state->data,
1446		&decrypted_state->len, decrypted_state->len,
1447		enc_session_ticket.encrypted_state.data,
1448		enc_session_ticket.encrypted_state.len);
1449	    if (rv != SECSuccess)
1450		goto no_ticket;
1451	} else
1452#endif
1453	{
1454	    SECItem ivItem;
1455	    ivItem.data = enc_session_ticket.iv;
1456	    ivItem.len = AES_BLOCK_SIZE;
1457	    aes_ctx_pkcs11 = PK11_CreateContextBySymKey(cipherMech,
1458		CKA_DECRYPT, aes_key_pkcs11, &ivItem);
1459	    if (!aes_ctx_pkcs11) {
1460		SSL_DBG(("%d: SSL[%d]: Unable to create AES context.",
1461			    SSL_GETPID(), ss->fd));
1462		goto no_ticket;
1463	    }
1464
1465	    rv = PK11_CipherOp(aes_ctx_pkcs11, decrypted_state->data,
1466		(int *)&decrypted_state->len, decrypted_state->len,
1467		enc_session_ticket.encrypted_state.data,
1468		enc_session_ticket.encrypted_state.len);
1469	    PK11_Finalize(aes_ctx_pkcs11);
1470	    PK11_DestroyContext(aes_ctx_pkcs11, PR_TRUE);
1471	    if (rv != SECSuccess)
1472		goto no_ticket;
1473	}
1474
1475	/* Check padding. */
1476	padding_length =
1477	    (PRUint32)decrypted_state->data[decrypted_state->len - 1];
1478	if (padding_length == 0 || padding_length > AES_BLOCK_SIZE)
1479	    goto no_ticket;
1480
1481	padding = &decrypted_state->data[decrypted_state->len - padding_length];
1482	for (i = 0; i < padding_length; i++, padding++) {
1483	    if (padding_length != (PRUint32)*padding)
1484		goto no_ticket;
1485	}
1486
1487	/* Deserialize session state. */
1488	buffer = decrypted_state->data;
1489	buffer_len = decrypted_state->len;
1490
1491	parsed_session_ticket = PORT_ZAlloc(sizeof(SessionTicket));
1492	if (parsed_session_ticket == NULL) {
1493	    rv = SECFailure;
1494	    goto loser;
1495	}
1496
1497	/* Read ticket_version (which is ignored for now.) */
1498	temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1499	if (temp < 0) goto no_ticket;
1500	parsed_session_ticket->ticket_version = (SSL3ProtocolVersion)temp;
1501
1502	/* Read SSLVersion. */
1503	temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1504	if (temp < 0) goto no_ticket;
1505	parsed_session_ticket->ssl_version = (SSL3ProtocolVersion)temp;
1506
1507	/* Read cipher_suite. */
1508	temp =  ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1509	if (temp < 0) goto no_ticket;
1510	parsed_session_ticket->cipher_suite = (ssl3CipherSuite)temp;
1511
1512	/* Read compression_method. */
1513	temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1514	if (temp < 0) goto no_ticket;
1515	parsed_session_ticket->compression_method = (SSLCompressionMethod)temp;
1516
1517	/* Read cipher spec parameters. */
1518	temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1519	if (temp < 0) goto no_ticket;
1520	parsed_session_ticket->authAlgorithm = (SSLSignType)temp;
1521	temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1522	if (temp < 0) goto no_ticket;
1523	parsed_session_ticket->authKeyBits = (PRUint32)temp;
1524	temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1525	if (temp < 0) goto no_ticket;
1526	parsed_session_ticket->keaType = (SSLKEAType)temp;
1527	temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1528	if (temp < 0) goto no_ticket;
1529	parsed_session_ticket->keaKeyBits = (PRUint32)temp;
1530
1531	/* Read wrapped master_secret. */
1532	temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1533	if (temp < 0) goto no_ticket;
1534	parsed_session_ticket->ms_is_wrapped = (PRBool)temp;
1535
1536	temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1537	if (temp < 0) goto no_ticket;
1538	parsed_session_ticket->exchKeyType = (SSL3KEAType)temp;
1539
1540	temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1541	if (temp < 0) goto no_ticket;
1542	parsed_session_ticket->msWrapMech = (CK_MECHANISM_TYPE)temp;
1543
1544	temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1545	if (temp < 0) goto no_ticket;
1546	parsed_session_ticket->ms_length = (PRUint16)temp;
1547	if (parsed_session_ticket->ms_length == 0 ||  /* sanity check MS. */
1548	    parsed_session_ticket->ms_length >
1549	    sizeof(parsed_session_ticket->master_secret))
1550	    goto no_ticket;
1551
1552	/* Allow for the wrapped master secret to be longer. */
1553	if (buffer_len < sizeof(SSL3_MASTER_SECRET_LENGTH))
1554	    goto no_ticket;
1555	PORT_Memcpy(parsed_session_ticket->master_secret, buffer,
1556	    parsed_session_ticket->ms_length);
1557	buffer += parsed_session_ticket->ms_length;
1558	buffer_len -= parsed_session_ticket->ms_length;
1559
1560	/* Read client_identity */
1561	temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1562	if (temp < 0)
1563	    goto no_ticket;
1564	parsed_session_ticket->client_identity.client_auth_type =
1565	    (ClientAuthenticationType)temp;
1566	switch(parsed_session_ticket->client_identity.client_auth_type) {
1567            case CLIENT_AUTH_ANONYMOUS:
1568		break;
1569            case CLIENT_AUTH_CERTIFICATE:
1570		rv = ssl3_ConsumeHandshakeVariable(ss, &cert_item, 3,
1571		    &buffer, &buffer_len);
1572		if (rv != SECSuccess) goto no_ticket;
1573		rv = SECITEM_CopyItem(NULL, &parsed_session_ticket->peer_cert,
1574		    &cert_item);
1575		if (rv != SECSuccess) goto no_ticket;
1576		break;
1577            default:
1578		goto no_ticket;
1579	}
1580	/* Read timestamp. */
1581	temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1582	if (temp < 0)
1583	    goto no_ticket;
1584	parsed_session_ticket->timestamp = (PRUint32)temp;
1585
1586        /* Read server name */
1587        nameType =
1588                ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1589        if (nameType != TLS_STE_NO_SERVER_NAME) {
1590            SECItem name_item;
1591            rv = ssl3_ConsumeHandshakeVariable(ss, &name_item, 2, &buffer,
1592                                               &buffer_len);
1593            if (rv != SECSuccess) goto no_ticket;
1594            rv = SECITEM_CopyItem(NULL, &parsed_session_ticket->srvName,
1595                                  &name_item);
1596            if (rv != SECSuccess) goto no_ticket;
1597            parsed_session_ticket->srvName.type = nameType;
1598        }
1599
1600	/* Done parsing.  Check that all bytes have been consumed. */
1601	if (buffer_len != padding_length)
1602	    goto no_ticket;
1603
1604	/* Use the ticket if it has not expired, otherwise free the allocated
1605	 * memory since the ticket is of no use.
1606	 */
1607	if (parsed_session_ticket->timestamp != 0 &&
1608	    parsed_session_ticket->timestamp +
1609	    TLS_EX_SESS_TICKET_LIFETIME_HINT > ssl_Time()) {
1610
1611	    sid = ssl3_NewSessionID(ss, PR_TRUE);
1612	    if (sid == NULL) {
1613		rv = SECFailure;
1614		goto loser;
1615	    }
1616
1617	    /* Copy over parameters. */
1618	    sid->version = parsed_session_ticket->ssl_version;
1619	    sid->u.ssl3.cipherSuite = parsed_session_ticket->cipher_suite;
1620	    sid->u.ssl3.compression = parsed_session_ticket->compression_method;
1621	    sid->authAlgorithm = parsed_session_ticket->authAlgorithm;
1622	    sid->authKeyBits = parsed_session_ticket->authKeyBits;
1623	    sid->keaType = parsed_session_ticket->keaType;
1624	    sid->keaKeyBits = parsed_session_ticket->keaKeyBits;
1625
1626	    /* Copy master secret. */
1627#ifndef NO_PKCS11_BYPASS
1628	    if (ss->opt.bypassPKCS11 &&
1629		    parsed_session_ticket->ms_is_wrapped)
1630		goto no_ticket;
1631#endif
1632	    if (parsed_session_ticket->ms_length >
1633		    sizeof(sid->u.ssl3.keys.wrapped_master_secret))
1634		goto no_ticket;
1635	    PORT_Memcpy(sid->u.ssl3.keys.wrapped_master_secret,
1636		parsed_session_ticket->master_secret,
1637		parsed_session_ticket->ms_length);
1638	    sid->u.ssl3.keys.wrapped_master_secret_len =
1639		parsed_session_ticket->ms_length;
1640	    sid->u.ssl3.exchKeyType = parsed_session_ticket->exchKeyType;
1641	    sid->u.ssl3.masterWrapMech = parsed_session_ticket->msWrapMech;
1642	    sid->u.ssl3.keys.msIsWrapped =
1643		parsed_session_ticket->ms_is_wrapped;
1644	    sid->u.ssl3.masterValid    = PR_TRUE;
1645	    sid->u.ssl3.keys.resumable = PR_TRUE;
1646
1647	    /* Copy over client cert from session ticket if there is one. */
1648	    if (parsed_session_ticket->peer_cert.data != NULL) {
1649		if (sid->peerCert != NULL)
1650		    CERT_DestroyCertificate(sid->peerCert);
1651		sid->peerCert = CERT_NewTempCertificate(ss->dbHandle,
1652		    &parsed_session_ticket->peer_cert, NULL, PR_FALSE, PR_TRUE);
1653		if (sid->peerCert == NULL) {
1654		    rv = SECFailure;
1655		    goto loser;
1656		}
1657	    }
1658	    if (parsed_session_ticket->srvName.data != NULL) {
1659                sid->u.ssl3.srvName = parsed_session_ticket->srvName;
1660            }
1661	    ss->statelessResume = PR_TRUE;
1662	    ss->sec.ci.sid = sid;
1663	}
1664    }
1665
1666    if (0) {
1667no_ticket:
1668	SSL_DBG(("%d: SSL[%d]: Session ticket parsing failed.",
1669			SSL_GETPID(), ss->fd));
1670	ssl3stats = SSL_GetStatistics();
1671	SSL_AtomicIncrementLong(& ssl3stats->hch_sid_ticket_parse_failures );
1672    }
1673    rv = SECSuccess;
1674
1675loser:
1676	/* ss->sec.ci.sid == sid if it did NOT come here via goto statement
1677	 * in that case do not free sid
1678	 */
1679	if (sid && (ss->sec.ci.sid != sid)) {
1680	    ssl_FreeSID(sid);
1681	    sid = NULL;
1682	}
1683    if (decrypted_state != NULL) {
1684	SECITEM_FreeItem(decrypted_state, PR_TRUE);
1685	decrypted_state = NULL;
1686    }
1687
1688    if (parsed_session_ticket != NULL) {
1689	if (parsed_session_ticket->peer_cert.data) {
1690	    SECITEM_FreeItem(&parsed_session_ticket->peer_cert, PR_FALSE);
1691	}
1692	PORT_ZFree(parsed_session_ticket, sizeof(SessionTicket));
1693    }
1694
1695    return rv;
1696}
1697
1698/*
1699 * Read bytes.  Using this function means the SECItem structure
1700 * cannot be freed.  The caller is expected to call this function
1701 * on a shallow copy of the structure.
1702 */
1703static SECStatus
1704ssl3_ConsumeFromItem(SECItem *item, unsigned char **buf, PRUint32 bytes)
1705{
1706    if (bytes > item->len)
1707	return SECFailure;
1708
1709    *buf = item->data;
1710    item->data += bytes;
1711    item->len -= bytes;
1712    return SECSuccess;
1713}
1714
1715static SECStatus
1716ssl3_ParseEncryptedSessionTicket(sslSocket *ss, SECItem *data,
1717                                 EncryptedSessionTicket *enc_session_ticket)
1718{
1719    if (ssl3_ConsumeFromItem(data, &enc_session_ticket->key_name,
1720	    SESS_TICKET_KEY_NAME_LEN) != SECSuccess)
1721	return SECFailure;
1722    if (ssl3_ConsumeFromItem(data, &enc_session_ticket->iv,
1723	    AES_BLOCK_SIZE) != SECSuccess)
1724	return SECFailure;
1725    if (ssl3_ConsumeHandshakeVariable(ss, &enc_session_ticket->encrypted_state,
1726	    2, &data->data, &data->len) != SECSuccess)
1727	return SECFailure;
1728    if (ssl3_ConsumeFromItem(data, &enc_session_ticket->mac,
1729	    TLS_EX_SESS_TICKET_MAC_LENGTH) != SECSuccess)
1730	return SECFailure;
1731    if (data->len != 0)  /* Make sure that we have consumed all bytes. */
1732	return SECFailure;
1733
1734    return SECSuccess;
1735}
1736
1737/* go through hello extensions in buffer "b".
1738 * For each one, find the extension handler in the table, and
1739 * if present, invoke that handler.
1740 * Servers ignore any extensions with unknown extension types.
1741 * Clients reject any extensions with unadvertised extension types.
1742 */
1743SECStatus
1744ssl3_HandleHelloExtensions(sslSocket *ss, SSL3Opaque **b, PRUint32 *length)
1745{
1746    const ssl3HelloExtensionHandler * handlers;
1747
1748    if (ss->sec.isServer) {
1749        handlers = clientHelloHandlers;
1750    } else if (ss->version > SSL_LIBRARY_VERSION_3_0) {
1751        handlers = serverHelloHandlersTLS;
1752    } else {
1753        handlers = serverHelloHandlersSSL3;
1754    }
1755
1756    while (*length) {
1757	const ssl3HelloExtensionHandler * handler;
1758	SECStatus rv;
1759	PRInt32   extension_type;
1760	SECItem   extension_data;
1761
1762	/* Get the extension's type field */
1763	extension_type = ssl3_ConsumeHandshakeNumber(ss, 2, b, length);
1764	if (extension_type < 0)  /* failure to decode extension_type */
1765	    return SECFailure;   /* alert already sent */
1766
1767	/* get the data for this extension, so we can pass it or skip it. */
1768	rv = ssl3_ConsumeHandshakeVariable(ss, &extension_data, 2, b, length);
1769	if (rv != SECSuccess)
1770	    return rv;
1771
1772	/* Check whether the server sent an extension which was not advertised
1773	 * in the ClientHello.
1774	 */
1775	if (!ss->sec.isServer &&
1776	    !ssl3_ClientExtensionAdvertised(ss, extension_type))
1777	    return SECFailure;  /* TODO: send unsupported_extension alert */
1778
1779	/* Check whether an extension has been sent multiple times. */
1780	if (ssl3_ExtensionNegotiated(ss, extension_type))
1781	    return SECFailure;
1782
1783	/* find extension_type in table of Hello Extension Handlers */
1784	for (handler = handlers; handler->ex_type >= 0; handler++) {
1785	    /* if found, call this handler */
1786	    if (handler->ex_type == extension_type) {
1787		rv = (*handler->ex_handler)(ss, (PRUint16)extension_type,
1788	                                         	&extension_data);
1789		/* Ignore this result */
1790		/* Treat all bad extensions as unrecognized types. */
1791	        break;
1792	    }
1793	}
1794    }
1795    return SECSuccess;
1796}
1797
1798/* Add a callback function to the table of senders of server hello extensions.
1799 */
1800SECStatus
1801ssl3_RegisterServerHelloExtensionSender(sslSocket *ss, PRUint16 ex_type,
1802				        ssl3HelloExtensionSenderFunc cb)
1803{
1804    int i;
1805    ssl3HelloExtensionSender *sender = &ss->xtnData.serverSenders[0];
1806
1807    for (i = 0; i < SSL_MAX_EXTENSIONS; ++i, ++sender) {
1808        if (!sender->ex_sender) {
1809	    sender->ex_type   = ex_type;
1810	    sender->ex_sender = cb;
1811	    return SECSuccess;
1812	}
1813	/* detect duplicate senders */
1814	PORT_Assert(sender->ex_type != ex_type);
1815	if (sender->ex_type == ex_type) {
1816	    /* duplicate */
1817	    break;
1818	}
1819    }
1820    PORT_Assert(i < SSL_MAX_EXTENSIONS); /* table needs to grow */
1821    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1822    return SECFailure;
1823}
1824
1825/* call each of the extension senders and return the accumulated length */
1826PRInt32
1827ssl3_CallHelloExtensionSenders(sslSocket *ss, PRBool append, PRUint32 maxBytes,
1828                               const ssl3HelloExtensionSender *sender)
1829{
1830    PRInt32 total_exten_len = 0;
1831    int i;
1832
1833    if (!sender) {
1834    	sender = ss->version > SSL_LIBRARY_VERSION_3_0 ?
1835                 &clientHelloSendersTLS[0] : &clientHelloSendersSSL3[0];
1836    }
1837
1838    for (i = 0; i < SSL_MAX_EXTENSIONS; ++i, ++sender) {
1839	if (sender->ex_sender) {
1840	    PRInt32 extLen = (*sender->ex_sender)(ss, append, maxBytes);
1841	    if (extLen < 0)
1842	    	return -1;
1843	    maxBytes        -= extLen;
1844	    total_exten_len += extLen;
1845	}
1846    }
1847    return total_exten_len;
1848}
1849
1850
1851/* Extension format:
1852 * Extension number:   2 bytes
1853 * Extension length:   2 bytes
1854 * Verify Data Length: 1 byte
1855 * Verify Data (TLS): 12 bytes (client) or 24 bytes (server)
1856 * Verify Data (SSL): 36 bytes (client) or 72 bytes (server)
1857 */
1858static PRInt32
1859ssl3_SendRenegotiationInfoXtn(
1860			sslSocket * ss,
1861			PRBool      append,
1862			PRUint32    maxBytes)
1863{
1864    PRInt32 len, needed;
1865
1866    /* In draft-ietf-tls-renegotiation-03, it is NOT RECOMMENDED to send
1867     * both the SCSV and the empty RI, so when we send SCSV in
1868     * the initial handshake, we don't also send RI.
1869     */
1870    if (!ss || ss->ssl3.hs.sendingSCSV)
1871    	return 0;
1872    len = !ss->firstHsDone ? 0 :
1873	   (ss->sec.isServer ? ss->ssl3.hs.finishedBytes * 2
1874			     : ss->ssl3.hs.finishedBytes);
1875    needed = 5 + len;
1876    if (append && maxBytes >= needed) {
1877	SECStatus rv;
1878	/* extension_type */
1879	rv = ssl3_AppendHandshakeNumber(ss, ssl_renegotiation_info_xtn, 2);
1880	if (rv != SECSuccess) return -1;
1881	/* length of extension_data */
1882	rv = ssl3_AppendHandshakeNumber(ss, len + 1, 2);
1883	if (rv != SECSuccess) return -1;
1884	/* verify_Data from previous Finished message(s) */
1885	rv = ssl3_AppendHandshakeVariable(ss,
1886		  ss->ssl3.hs.finishedMsgs.data, len, 1);
1887	if (rv != SECSuccess) return -1;
1888	if (!ss->sec.isServer) {
1889	    TLSExtensionData *xtnData = &ss->xtnData;
1890	    xtnData->advertised[xtnData->numAdvertised++] =
1891	                                           ssl_renegotiation_info_xtn;
1892	}
1893    }
1894    return needed;
1895}
1896
1897static SECStatus
1898ssl3_ServerHandleStatusRequestXtn(sslSocket *ss, PRUint16 ex_type,
1899				  SECItem *data)
1900{
1901    SECStatus rv = SECSuccess;
1902
1903    /* remember that we got this extension. */
1904    ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
1905    PORT_Assert(ss->sec.isServer);
1906    /* prepare to send back the appropriate response */
1907    rv = ssl3_RegisterServerHelloExtensionSender(ss, ex_type,
1908					    ssl3_ServerSendStatusRequestXtn);
1909    return rv;
1910}
1911
1912/* This function runs in both the client and server.  */
1913static SECStatus
1914ssl3_HandleRenegotiationInfoXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data)
1915{
1916    SECStatus rv = SECSuccess;
1917    PRUint32 len = 0;
1918
1919    if (ss->firstHsDone) {
1920	len = ss->sec.isServer ? ss->ssl3.hs.finishedBytes
1921	                       : ss->ssl3.hs.finishedBytes * 2;
1922    }
1923    if (data->len != 1 + len  ||
1924	data->data[0] != len  || (len &&
1925	NSS_SecureMemcmp(ss->ssl3.hs.finishedMsgs.data,
1926	                 data->data + 1, len))) {
1927	/* Can we do this here? Or, must we arrange for the caller to do it? */
1928	(void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
1929	PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1930	return SECFailure;
1931    }
1932    /* remember that we got this extension and it was correct. */
1933    ss->peerRequestedProtection = 1;
1934    ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
1935    if (ss->sec.isServer) {
1936	/* prepare to send back the appropriate response */
1937	rv = ssl3_RegisterServerHelloExtensionSender(ss, ex_type,
1938					     ssl3_SendRenegotiationInfoXtn);
1939    }
1940    return rv;
1941}
1942
1943static PRInt32
1944ssl3_SendUseSRTPXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes)
1945{
1946    PRUint32 ext_data_len;
1947    PRInt16 i;
1948    SECStatus rv;
1949
1950    if (!ss)
1951	return 0;
1952
1953    if (!ss->sec.isServer) {
1954	/* Client side */
1955
1956	if (!IS_DTLS(ss) || !ss->ssl3.dtlsSRTPCipherCount)
1957	    return 0;  /* Not relevant */
1958
1959	ext_data_len = 2 + 2 * ss->ssl3.dtlsSRTPCipherCount + 1;
1960
1961	if (append && maxBytes >= 4 + ext_data_len) {
1962	    /* Extension type */
1963	    rv = ssl3_AppendHandshakeNumber(ss, ssl_use_srtp_xtn, 2);
1964	    if (rv != SECSuccess) return -1;
1965	    /* Length of extension data */
1966	    rv = ssl3_AppendHandshakeNumber(ss, ext_data_len, 2);
1967	    if (rv != SECSuccess) return -1;
1968	    /* Length of the SRTP cipher list */
1969	    rv = ssl3_AppendHandshakeNumber(ss,
1970					    2 * ss->ssl3.dtlsSRTPCipherCount,
1971					    2);
1972	    if (rv != SECSuccess) return -1;
1973	    /* The SRTP ciphers */
1974	    for (i = 0; i < ss->ssl3.dtlsSRTPCipherCount; i++) {
1975		rv = ssl3_AppendHandshakeNumber(ss,
1976						ss->ssl3.dtlsSRTPCiphers[i],
1977						2);
1978	    }
1979	    /* Empty MKI value */
1980	    ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
1981
1982	    ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
1983		ssl_use_srtp_xtn;
1984	}
1985
1986	return 4 + ext_data_len;
1987    }
1988
1989    /* Server side */
1990    if (append && maxBytes >= 9) {
1991	/* Extension type */
1992	rv = ssl3_AppendHandshakeNumber(ss, ssl_use_srtp_xtn, 2);
1993	if (rv != SECSuccess) return -1;
1994	/* Length of extension data */
1995	rv = ssl3_AppendHandshakeNumber(ss, 5, 2);
1996	if (rv != SECSuccess) return -1;
1997	/* Length of the SRTP cipher list */
1998	rv = ssl3_AppendHandshakeNumber(ss, 2, 2);
1999	if (rv != SECSuccess) return -1;
2000	/* The selected cipher */
2001	rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.dtlsSRTPCipherSuite, 2);
2002	if (rv != SECSuccess) return -1;
2003	/* Empty MKI value */
2004	ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
2005    }
2006
2007    return 9;
2008}
2009
2010static SECStatus
2011ssl3_HandleUseSRTPXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data)
2012{
2013    SECStatus rv;
2014    SECItem ciphers = {siBuffer, NULL, 0};
2015    PRUint16 i;
2016    unsigned int j;
2017    PRUint16 cipher = 0;
2018    PRBool found = PR_FALSE;
2019    SECItem litem;
2020
2021    if (!ss->sec.isServer) {
2022	/* Client side */
2023	if (!data->data || !data->len) {
2024            /* malformed */
2025            return SECFailure;
2026	}
2027
2028	/* Get the cipher list */
2029	rv = ssl3_ConsumeHandshakeVariable(ss, &ciphers, 2,
2030					   &data->data, &data->len);
2031	if (rv != SECSuccess) {
2032	    return SECFailure;
2033	}
2034	/* Now check that the number of ciphers listed is 1 (len = 2) */
2035	if (ciphers.len != 2) {
2036	    return SECFailure;
2037	}
2038
2039	/* Get the selected cipher */
2040	cipher = (ciphers.data[0] << 8) | ciphers.data[1];
2041
2042	/* Now check that this is one of the ciphers we offered */
2043	for (i = 0; i < ss->ssl3.dtlsSRTPCipherCount; i++) {
2044	    if (cipher == ss->ssl3.dtlsSRTPCiphers[i]) {
2045		found = PR_TRUE;
2046		break;
2047	    }
2048	}
2049
2050	if (!found) {
2051	    return SECFailure;
2052	}
2053
2054	/* Get the srtp_mki value */
2055        rv = ssl3_ConsumeHandshakeVariable(ss, &litem, 1,
2056					   &data->data, &data->len);
2057        if (rv != SECSuccess) {
2058            return SECFailure;
2059        }
2060
2061	/* We didn't offer an MKI, so this must be 0 length */
2062	/* XXX RFC 5764 Section 4.1.3 says:
2063	 *   If the client detects a nonzero-length MKI in the server's
2064	 *   response that is different than the one the client offered,
2065	 *   then the client MUST abort the handshake and SHOULD send an
2066	 *   invalid_parameter alert.
2067	 *
2068	 * Due to a limitation of the ssl3_HandleHelloExtensions function,
2069	 * returning SECFailure here won't abort the handshake.  It will
2070	 * merely cause the use_srtp extension to be not negotiated.  We
2071	 * should fix this.  See NSS bug 753136.
2072	 */
2073	if (litem.len != 0) {
2074	    return SECFailure;
2075	}
2076
2077	if (data->len != 0) {
2078            /* malformed */
2079            return SECFailure;
2080	}
2081
2082	/* OK, this looks fine. */
2083	ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ssl_use_srtp_xtn;
2084	ss->ssl3.dtlsSRTPCipherSuite = cipher;
2085	return SECSuccess;
2086    }
2087
2088    /* Server side */
2089    if (!IS_DTLS(ss) || !ss->ssl3.dtlsSRTPCipherCount) {
2090	/* Ignore the extension if we aren't doing DTLS or no DTLS-SRTP
2091	 * preferences have been set. */
2092	return SECSuccess;
2093    }
2094
2095    if (!data->data || data->len < 5) {
2096	/* malformed */
2097	return SECFailure;
2098    }
2099
2100    /* Get the cipher list */
2101    rv = ssl3_ConsumeHandshakeVariable(ss, &ciphers, 2,
2102				       &data->data, &data->len);
2103    if (rv != SECSuccess) {
2104	return SECFailure;
2105    }
2106    /* Check that the list is even length */
2107    if (ciphers.len % 2) {
2108	return SECFailure;
2109    }
2110
2111    /* Walk through the offered list and pick the most preferred of our
2112     * ciphers, if any */
2113    for (i = 0; !found && i < ss->ssl3.dtlsSRTPCipherCount; i++) {
2114	for (j = 0; j + 1 < ciphers.len; j += 2) {
2115	    cipher = (ciphers.data[j] << 8) | ciphers.data[j + 1];
2116	    if (cipher == ss->ssl3.dtlsSRTPCiphers[i]) {
2117		found = PR_TRUE;
2118		break;
2119	    }
2120	}
2121    }
2122
2123    /* Get the srtp_mki value */
2124    rv = ssl3_ConsumeHandshakeVariable(ss, &litem, 1, &data->data, &data->len);
2125    if (rv != SECSuccess) {
2126	return SECFailure;
2127    }
2128
2129    if (data->len != 0) {
2130	return SECFailure; /* Malformed */
2131    }
2132
2133    /* Now figure out what to do */
2134    if (!found) {
2135	/* No matching ciphers */
2136	return SECSuccess;
2137    }
2138
2139    /* OK, we have a valid cipher and we've selected it */
2140    ss->ssl3.dtlsSRTPCipherSuite = cipher;
2141    ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ssl_use_srtp_xtn;
2142
2143    return ssl3_RegisterServerHelloExtensionSender(ss, ssl_use_srtp_xtn,
2144						   ssl3_SendUseSRTPXtn);
2145}
2146
2147/* ssl3_ServerHandleSigAlgsXtn handles the signature_algorithms extension
2148 * from a client.
2149 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
2150static SECStatus
2151ssl3_ServerHandleSigAlgsXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data)
2152{
2153    SECStatus rv;
2154    SECItem algorithms;
2155    const unsigned char *b;
2156    unsigned int numAlgorithms, i;
2157
2158    /* Ignore this extension if we aren't doing TLS 1.2 or greater. */
2159    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_2) {
2160	return SECSuccess;
2161    }
2162
2163    /* Keep track of negotiated extensions. */
2164    ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
2165
2166    rv = ssl3_ConsumeHandshakeVariable(ss, &algorithms, 2, &data->data,
2167				       &data->len);
2168    if (rv != SECSuccess) {
2169	return SECFailure;
2170    }
2171    /* Trailing data, empty value, or odd-length value is invalid. */
2172    if (data->len != 0 || algorithms.len == 0 || (algorithms.len & 1) != 0) {
2173	PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
2174	return SECFailure;
2175    }
2176
2177    numAlgorithms = algorithms.len/2;
2178
2179    /* We don't care to process excessive numbers of algorithms. */
2180    if (numAlgorithms > 512) {
2181	numAlgorithms = 512;
2182    }
2183
2184    ss->ssl3.hs.clientSigAndHash =
2185	    PORT_NewArray(SSL3SignatureAndHashAlgorithm, numAlgorithms);
2186    if (!ss->ssl3.hs.clientSigAndHash) {
2187	return SECFailure;
2188    }
2189    ss->ssl3.hs.numClientSigAndHash = 0;
2190
2191    b = algorithms.data;
2192    for (i = 0; i < numAlgorithms; i++) {
2193	unsigned char tls_hash = *(b++);
2194	unsigned char tls_sig = *(b++);
2195	SECOidTag hash = ssl3_TLSHashAlgorithmToOID(tls_hash);
2196
2197	if (hash == SEC_OID_UNKNOWN) {
2198	    /* We ignore formats that we don't understand. */
2199	    continue;
2200	}
2201	/* tls_sig support will be checked later in
2202	 * ssl3_PickSignatureHashAlgorithm. */
2203	ss->ssl3.hs.clientSigAndHash[i].hashAlg = hash;
2204	ss->ssl3.hs.clientSigAndHash[i].sigAlg = tls_sig;
2205	ss->ssl3.hs.numClientSigAndHash++;
2206    }
2207
2208    if (!ss->ssl3.hs.numClientSigAndHash) {
2209	/* We didn't understand any of the client's requested signature
2210	 * formats. We'll use the defaults. */
2211	PORT_Free(ss->ssl3.hs.clientSigAndHash);
2212	ss->ssl3.hs.clientSigAndHash = NULL;
2213    }
2214
2215    return SECSuccess;
2216}
2217
2218/* ssl3_ClientSendSigAlgsXtn sends the signature_algorithm extension for TLS
2219 * 1.2 ClientHellos. */
2220static PRInt32
2221ssl3_ClientSendSigAlgsXtn(sslSocket * ss, PRBool append, PRUint32 maxBytes)
2222{
2223    static const unsigned char signatureAlgorithms[] = {
2224	/* This block is the contents of our signature_algorithms extension, in
2225	 * wire format. See
2226	 * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
2227	tls_hash_sha256, tls_sig_rsa,
2228	tls_hash_sha384, tls_sig_rsa,
2229	tls_hash_sha1,   tls_sig_rsa,
2230#ifdef NSS_ENABLE_ECC
2231	tls_hash_sha256, tls_sig_ecdsa,
2232	tls_hash_sha384, tls_sig_ecdsa,
2233	tls_hash_sha1,   tls_sig_ecdsa,
2234#endif
2235	tls_hash_sha256, tls_sig_dsa,
2236	tls_hash_sha1,   tls_sig_dsa,
2237    };
2238    PRInt32 extension_length;
2239
2240    if (ss->version < SSL_LIBRARY_VERSION_TLS_1_2) {
2241	return 0;
2242    }
2243
2244    extension_length =
2245	2 /* extension type */ +
2246	2 /* extension length */ +
2247	2 /* supported_signature_algorithms length */ +
2248	sizeof(signatureAlgorithms);
2249
2250    if (append && maxBytes >= extension_length) {
2251	SECStatus rv;
2252	rv = ssl3_AppendHandshakeNumber(ss, ssl_signature_algorithms_xtn, 2);
2253	if (rv != SECSuccess)
2254	    goto loser;
2255	rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2);
2256	if (rv != SECSuccess)
2257	    goto loser;
2258	rv = ssl3_AppendHandshakeVariable(ss, signatureAlgorithms,
2259					  sizeof(signatureAlgorithms), 2);
2260	if (rv != SECSuccess)
2261	    goto loser;
2262	ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
2263		ssl_signature_algorithms_xtn;
2264    } else if (maxBytes < extension_length) {
2265	PORT_Assert(0);
2266	return 0;
2267    }
2268
2269    return extension_length;
2270
2271loser:
2272    return -1;
2273}
2274