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