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