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