• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * SSL3 Protocol
3  *
4  * ***** BEGIN LICENSE BLOCK *****
5  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
6  *
7  * The contents of this file are subject to the Mozilla Public License Version
8  * 1.1 (the "License"); you may not use this file except in compliance with
9  * the License. You may obtain a copy of the License at
10  * http://www.mozilla.org/MPL/
11  *
12  * Software distributed under the License is distributed on an "AS IS" basis,
13  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14  * for the specific language governing rights and limitations under the
15  * License.
16  *
17  * The Original Code is the Netscape security libraries.
18  *
19  * The Initial Developer of the Original Code is
20  * Netscape Communications Corporation.
21  * Portions created by the Initial Developer are Copyright (C) 1994-2000
22  * the Initial Developer. All Rights Reserved.
23  *
24  * Contributor(s):
25  *   Dr Vipul Gupta <vipul.gupta@sun.com> and
26  *   Douglas Stebila <douglas@stebila.ca>, Sun Microsystems Laboratories
27  *   Nagendra Modadugu <ngm@google.com>, Google Inc.
28  *
29  * Alternatively, the contents of this file may be used under the terms of
30  * either the GNU General Public License Version 2 or later (the "GPL"), or
31  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
32  * in which case the provisions of the GPL or the LGPL are applicable instead
33  * of those above. If you wish to allow use of your version of this file only
34  * under the terms of either the GPL or the LGPL, and not to allow others to
35  * use your version of this file under the terms of the MPL, indicate your
36  * decision by deleting the provisions above and replace them with the notice
37  * and other provisions required by the GPL or the LGPL. If you do not delete
38  * the provisions above, a recipient may use your version of this file under
39  * the terms of any one of the MPL, the GPL or the LGPL.
40  *
41  * ***** END LICENSE BLOCK ***** */
42 
43 /* TLS extension code moved here from ssl3ecc.c */
44 /* $Id: ssl3ext.c,v 1.5 2009/11/07 18:23:06 wtc%google.com Exp $ */
45 
46 #include "nssrenam.h"
47 #include "nss.h"
48 #include "ssl.h"
49 #include "sslimpl.h"
50 #include "pk11pub.h"
51 #include "blapi.h"
52 #include "prinit.h"
53 
54 static unsigned char  key_name[SESS_TICKET_KEY_NAME_LEN];
55 static PK11SymKey    *session_ticket_enc_key_pkcs11 = NULL;
56 static PK11SymKey    *session_ticket_mac_key_pkcs11 = NULL;
57 
58 static unsigned char  session_ticket_enc_key[32];
59 static unsigned char  session_ticket_mac_key[SHA256_LENGTH];
60 
61 static PRBool         session_ticket_keys_initialized = PR_FALSE;
62 static PRCallOnceType generate_session_keys_once;
63 
64 static PRInt32 ssl3_SendServerNameXtn(sslSocket * ss,
65     PRBool append, PRUint32 maxBytes);
66 static SECStatus ssl3_ParseEncryptedSessionTicket(sslSocket *ss,
67     SECItem *data, EncryptedSessionTicket *enc_session_ticket);
68 static SECStatus ssl3_AppendToItem(SECItem *item, const unsigned char *buf,
69     PRUint32 bytes);
70 static SECStatus ssl3_AppendNumberToItem(SECItem *item, PRUint32 num,
71     PRInt32 lenSize);
72 static SECStatus ssl3_GetSessionTicketKeysPKCS11(sslSocket *ss,
73     PK11SymKey **aes_key, PK11SymKey **mac_key);
74 static SECStatus ssl3_GetSessionTicketKeys(const unsigned char **aes_key,
75     PRUint32 *aes_key_length, const unsigned char **mac_key,
76     PRUint32 *mac_key_length);
77 
78 /*
79  * Write bytes.  Using this function means the SECItem structure
80  * cannot be freed.  The caller is expected to call this function
81  * on a shallow copy of the structure.
82  */
83 static SECStatus
ssl3_AppendToItem(SECItem * item,const unsigned char * buf,PRUint32 bytes)84 ssl3_AppendToItem(SECItem *item, const unsigned char *buf, PRUint32 bytes)
85 {
86     if (bytes > item->len)
87 	return SECFailure;
88 
89     PORT_Memcpy(item->data, buf, bytes);
90     item->data += bytes;
91     item->len -= bytes;
92     return SECSuccess;
93 }
94 
95 /*
96  * Write a number in network byte order. Using this function means the
97  * SECItem structure cannot be freed.  The caller is expected to call
98  * this function on a shallow copy of the structure.
99  */
100 static SECStatus
ssl3_AppendNumberToItem(SECItem * item,PRUint32 num,PRInt32 lenSize)101 ssl3_AppendNumberToItem(SECItem *item, PRUint32 num, PRInt32 lenSize)
102 {
103     SECStatus rv;
104     uint8     b[4];
105     uint8 *   p = b;
106 
107     switch (lenSize) {
108     case 4:
109 	*p++ = (uint8) (num >> 24);
110     case 3:
111 	*p++ = (uint8) (num >> 16);
112     case 2:
113 	*p++ = (uint8) (num >> 8);
114     case 1:
115 	*p = (uint8) num;
116     }
117     rv = ssl3_AppendToItem(item, &b[0], lenSize);
118     return rv;
119 }
120 
ssl3_SessionTicketShutdown(void * appData,void * nssData)121 static SECStatus ssl3_SessionTicketShutdown(void* appData, void* nssData)
122 {
123     if (session_ticket_enc_key_pkcs11) {
124 	PK11_FreeSymKey(session_ticket_enc_key_pkcs11);
125 	session_ticket_enc_key_pkcs11 = NULL;
126     }
127     if (session_ticket_mac_key_pkcs11) {
128 	PK11_FreeSymKey(session_ticket_mac_key_pkcs11);
129 	session_ticket_mac_key_pkcs11 = NULL;
130     }
131     PORT_Memset(&generate_session_keys_once, 0,
132 	sizeof(generate_session_keys_once));
133     return SECSuccess;
134 }
135 
136 
137 static PRStatus
ssl3_GenerateSessionTicketKeysPKCS11(void * data)138 ssl3_GenerateSessionTicketKeysPKCS11(void *data)
139 {
140     SECStatus rv;
141     sslSocket *ss = (sslSocket *)data;
142     SECKEYPrivateKey *svrPrivKey = ss->serverCerts[kt_rsa].SERVERKEY;
143     SECKEYPublicKey *svrPubKey = ss->serverCerts[kt_rsa].serverKeyPair->pubKey;
144 
145     if (svrPrivKey == NULL || svrPubKey == NULL) {
146 	SSL_DBG(("%d: SSL[%d]: Pub or priv key(s) is NULL.",
147 			SSL_GETPID(), ss->fd));
148 	goto loser;
149     }
150 
151     /* Get a copy of the session keys from shared memory. */
152     PORT_Memcpy(key_name, SESS_TICKET_KEY_NAME_PREFIX,
153 	sizeof(SESS_TICKET_KEY_NAME_PREFIX));
154     if (!ssl_GetSessionTicketKeysPKCS11(svrPrivKey, svrPubKey,
155 	    ss->pkcs11PinArg, &key_name[SESS_TICKET_KEY_NAME_PREFIX_LEN],
156 	    &session_ticket_enc_key_pkcs11, &session_ticket_mac_key_pkcs11))
157 	return PR_FAILURE;
158 
159     rv = NSS_RegisterShutdown(ssl3_SessionTicketShutdown, NULL);
160     if (rv != SECSuccess)
161 	goto loser;
162 
163     return PR_SUCCESS;
164 
165 loser:
166     ssl3_SessionTicketShutdown(NULL, NULL);
167     return PR_FAILURE;
168 }
169 
170 static SECStatus
ssl3_GetSessionTicketKeysPKCS11(sslSocket * ss,PK11SymKey ** aes_key,PK11SymKey ** mac_key)171 ssl3_GetSessionTicketKeysPKCS11(sslSocket *ss, PK11SymKey **aes_key,
172                                 PK11SymKey **mac_key)
173 {
174     if (PR_CallOnceWithArg(&generate_session_keys_once,
175 	    ssl3_GenerateSessionTicketKeysPKCS11, ss) != PR_SUCCESS)
176 	return SECFailure;
177 
178     if (session_ticket_enc_key_pkcs11 == NULL ||
179 	session_ticket_mac_key_pkcs11 == NULL)
180 	return SECFailure;
181 
182     *aes_key = session_ticket_enc_key_pkcs11;
183     *mac_key = session_ticket_mac_key_pkcs11;
184     return SECSuccess;
185 }
186 
187 static PRStatus
ssl3_GenerateSessionTicketKeys(void)188 ssl3_GenerateSessionTicketKeys(void)
189 {
190     PORT_Memcpy(key_name, SESS_TICKET_KEY_NAME_PREFIX,
191 	sizeof(SESS_TICKET_KEY_NAME_PREFIX));
192 
193     if (!ssl_GetSessionTicketKeys(&key_name[SESS_TICKET_KEY_NAME_PREFIX_LEN],
194 	    session_ticket_enc_key, session_ticket_mac_key))
195 	return PR_FAILURE;
196 
197     session_ticket_keys_initialized = PR_TRUE;
198     return PR_SUCCESS;
199 }
200 
201 static SECStatus
ssl3_GetSessionTicketKeys(const unsigned char ** aes_key,PRUint32 * aes_key_length,const unsigned char ** mac_key,PRUint32 * mac_key_length)202 ssl3_GetSessionTicketKeys(const unsigned char **aes_key,
203     PRUint32 *aes_key_length, const unsigned char **mac_key,
204     PRUint32 *mac_key_length)
205 {
206     if (PR_CallOnce(&generate_session_keys_once,
207 	    ssl3_GenerateSessionTicketKeys) != SECSuccess)
208 	return SECFailure;
209 
210     if (!session_ticket_keys_initialized)
211 	return SECFailure;
212 
213     *aes_key = session_ticket_enc_key;
214     *aes_key_length = sizeof(session_ticket_enc_key);
215     *mac_key = session_ticket_mac_key;
216     *mac_key_length = sizeof(session_ticket_mac_key);
217 
218     return SECSuccess;
219 }
220 
221 /* Table of handlers for received TLS hello extensions, one per extension.
222  * In the second generation, this table will be dynamic, and functions
223  * will be registered here.
224  */
225 static const ssl3HelloExtensionHandler clientHelloHandlers[] = {
226     { server_name_xtn, &ssl3_HandleServerNameXtn },
227 #ifdef NSS_ENABLE_ECC
228     { elliptic_curves_xtn, &ssl3_HandleSupportedCurvesXtn },
229     { ec_point_formats_xtn, &ssl3_HandleSupportedPointFormatsXtn },
230 #endif
231     { session_ticket_xtn, &ssl3_ServerHandleSessionTicketXtn },
232     { next_proto_neg_xtn, &ssl3_ServerHandleNextProtoNegoXtn },
233     { -1, NULL }
234 };
235 
236 static const ssl3HelloExtensionHandler serverHelloHandlers[] = {
237     { server_name_xtn, &ssl3_HandleServerNameXtn },
238     /* TODO: add a handler for ec_point_formats_xtn */
239     { session_ticket_xtn, &ssl3_ClientHandleSessionTicketXtn },
240     { next_proto_neg_xtn, &ssl3_ClientHandleNextProtoNegoXtn },
241     { -1, NULL }
242 };
243 
244 /* Table of functions to format TLS hello extensions, one per extension.
245  * This static table is for the formatting of client hello extensions.
246  * The server's table of hello senders is dynamic, in the socket struct,
247  * and sender functions are registered there.
248  */
249 static const
250 ssl3HelloExtensionSender clientHelloSenders[MAX_EXTENSIONS] = {
251     { server_name_xtn, &ssl3_SendServerNameXtn },
252 #ifdef NSS_ENABLE_ECC
253     { elliptic_curves_xtn, &ssl3_SendSupportedCurvesXtn },
254     { ec_point_formats_xtn, &ssl3_SendSupportedPointFormatsXtn },
255 #else
256     { -1, NULL },
257     { -1, NULL },
258 #endif
259     { session_ticket_xtn, ssl3_SendSessionTicketXtn },
260     { next_proto_neg_xtn, ssl3_ClientSendNextProtoNegoXtn }
261 };
262 
263 static PRBool
arrayContainsExtension(const PRUint16 * array,PRUint32 len,PRUint16 ex_type)264 arrayContainsExtension(const PRUint16 *array, PRUint32 len, PRUint16 ex_type)
265 {
266     int i;
267     for (i = 0; i < len; i++) {
268 	if (ex_type == array[i])
269 	    return PR_TRUE;
270     }
271     return PR_FALSE;
272 }
273 
274 PRBool
ssl3_ExtensionNegotiated(sslSocket * ss,PRUint16 ex_type)275 ssl3_ExtensionNegotiated(sslSocket *ss, PRUint16 ex_type) {
276     TLSExtensionData *xtnData = &ss->xtnData;
277     return arrayContainsExtension(xtnData->negotiated,
278 	                          xtnData->numNegotiated, ex_type);
279 }
280 
281 static PRBool
ssl3_ClientExtensionAdvertised(sslSocket * ss,PRUint16 ex_type)282 ssl3_ClientExtensionAdvertised(sslSocket *ss, PRUint16 ex_type) {
283     TLSExtensionData *xtnData = &ss->xtnData;
284     return arrayContainsExtension(xtnData->advertised,
285 	                          xtnData->numAdvertised, ex_type);
286 }
287 
288 /* Format an SNI extension, using the name from the socket's URL,
289  * unless that name is a dotted decimal string.
290  */
291 static PRInt32
ssl3_SendServerNameXtn(sslSocket * ss,PRBool append,PRUint32 maxBytes)292 ssl3_SendServerNameXtn(
293 			sslSocket * ss,
294 			PRBool      append,
295 			PRUint32    maxBytes)
296 {
297     PRUint32 len;
298     PRNetAddr netAddr;
299 
300     /* must have a hostname */
301     if (!ss || !ss->url || !ss->url[0])
302     	return 0;
303     /* must not be an IPv4 or IPv6 address */
304     if (PR_SUCCESS == PR_StringToNetAddr(ss->url, &netAddr)) {
305         /* is an IP address (v4 or v6) */
306         return 0;
307     }
308     len  = PORT_Strlen(ss->url);
309     if (append && maxBytes >= len + 9) {
310 	SECStatus rv;
311 	/* extension_type */
312 	rv = ssl3_AppendHandshakeNumber(ss, server_name_xtn, 2);
313 	if (rv != SECSuccess) return -1;
314 	/* length of extension_data */
315 	rv = ssl3_AppendHandshakeNumber(ss, len + 5, 2);
316 	if (rv != SECSuccess) return -1;
317 	/* length of server_name_list */
318 	rv = ssl3_AppendHandshakeNumber(ss, len + 3, 2);
319 	if (rv != SECSuccess) return -1;
320 	/* Name Type (host_name) */
321 	rv = ssl3_AppendHandshake(ss,       "\0",    1);
322 	if (rv != SECSuccess) return -1;
323 	/* HostName (length and value) */
324 	rv = ssl3_AppendHandshakeVariable(ss, (unsigned char *)ss->url, len, 2);
325 	if (rv != SECSuccess) return -1;
326 	if (!ss->sec.isServer) {
327 	    TLSExtensionData *xtnData = &ss->xtnData;
328 	    xtnData->advertised[xtnData->numAdvertised++] = server_name_xtn;
329 	}
330     }
331     return len + 9;
332 }
333 
334 /* handle an incoming SNI extension, by ignoring it. */
335 SECStatus
ssl3_HandleServerNameXtn(sslSocket * ss,PRUint16 ex_type,SECItem * data)336 ssl3_HandleServerNameXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data)
337 {
338     /* TODO: if client, should verify extension_data is empty. */
339     /* TODO: if server, should send empty extension_data. */
340     /* For now, we ignore this, as if we didn't understand it. :-)  */
341     return SECSuccess;
342 }
343 
344 /* Called by both clients and servers.
345  * Clients sends a filled in session ticket if one is available, and otherwise
346  * sends an empty ticket.  Servers always send empty tickets.
347  */
348 PRInt32
ssl3_SendSessionTicketXtn(sslSocket * ss,PRBool append,PRUint32 maxBytes)349 ssl3_SendSessionTicketXtn(
350 			sslSocket * ss,
351 			PRBool      append,
352 			PRUint32    maxBytes)
353 {
354     PRInt32 extension_length;
355     NewSessionTicket *session_ticket = NULL;
356 
357     /* Ignore the SessionTicket extension if processing is disabled. */
358     if (!ss->opt.enableSessionTickets)
359 	return 0;
360 
361     /* Empty extension length = extension_type (2-bytes) +
362      * length(extension_data) (2-bytes)
363      */
364     extension_length = 4;
365 
366     /* If we are a client then send a session ticket if one is availble.
367      * Servers that support the extension and are willing to negotiate the
368      * the extension always respond with an empty extension.
369      */
370     if (!ss->sec.isServer) {
371 	sslSessionID *sid = ss->sec.ci.sid;
372 	session_ticket = &sid->u.ssl3.sessionTicket;
373 	if (session_ticket->ticket.data) {
374 	    if (ss->xtnData.ticketTimestampVerified) {
375 		extension_length += session_ticket->ticket.len;
376 	    } else if (!append &&
377 		(session_ticket->ticket_lifetime_hint == 0 ||
378 		(session_ticket->ticket_lifetime_hint +
379 		    session_ticket->received_timestamp > ssl_Time()))) {
380 		extension_length += session_ticket->ticket.len;
381 		ss->xtnData.ticketTimestampVerified = PR_TRUE;
382 	    }
383 	}
384     }
385 
386     if (append && maxBytes >= extension_length) {
387 	SECStatus rv;
388 	/* extension_type */
389         rv = ssl3_AppendHandshakeNumber(ss, session_ticket_xtn, 2);
390         if (rv != SECSuccess)
391 	    goto loser;
392 	if (session_ticket && session_ticket->ticket.data &&
393 	    ss->xtnData.ticketTimestampVerified) {
394 	    rv = ssl3_AppendHandshakeVariable(ss, session_ticket->ticket.data,
395 		session_ticket->ticket.len, 2);
396 	    ss->xtnData.ticketTimestampVerified = PR_FALSE;
397 	} else {
398 	    rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
399 	}
400         if (rv != SECSuccess)
401 	    goto loser;
402 
403 	if (!ss->sec.isServer) {
404 	    TLSExtensionData *xtnData = &ss->xtnData;
405 	    xtnData->advertised[xtnData->numAdvertised++] = session_ticket_xtn;
406 	}
407     } else if (maxBytes < extension_length) {
408 	PORT_Assert(0);
409         return 0;
410     }
411     return extension_length;
412 
413  loser:
414     ss->xtnData.ticketTimestampVerified = PR_FALSE;
415     return -1;
416 }
417 
418 /* handle an incoming Next Protocol Negotiation extension. */
419 SECStatus
ssl3_ServerHandleNextProtoNegoXtn(sslSocket * ss,PRUint16 ex_type,SECItem * data)420 ssl3_ServerHandleNextProtoNegoXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data)
421 {
422     if (data->len != 0) {
423 	/* Clients MUST send an empty NPN extension, if any. */
424 	return SECFailure;
425     }
426 
427     ss->ssl3.hs.nextProtoNego = PR_TRUE;
428     return SECSuccess;
429 }
430 
431 /* ssl3_ValidateNextProtoNego checks that the given block of data is valid: none
432  * of the length may be 0 and the sum of the lengths must equal the length of
433  * the block. */
434 SECStatus
ssl3_ValidateNextProtoNego(const unsigned char * data,unsigned short length)435 ssl3_ValidateNextProtoNego(const unsigned char* data, unsigned short length)
436 {
437     unsigned int offset = 0;
438 
439     while (offset < length) {
440 	if (data[offset] == 0) {
441 	    return SECFailure;
442 	}
443 	offset += (unsigned int)data[offset] + 1;
444     }
445 
446     if (offset > length)
447 	return SECFailure;
448 
449     return SECSuccess;
450 }
451 
452 SECStatus
ssl3_ClientHandleNextProtoNegoXtn(sslSocket * ss,PRUint16 ex_type,SECItem * data)453 ssl3_ClientHandleNextProtoNegoXtn(sslSocket *ss, PRUint16 ex_type,
454                                  SECItem *data)
455 {
456     unsigned int i, j;
457     SECStatus rv;
458     unsigned char *result;
459 
460     if (data->len == 0) {
461 	/* The server supports the extension, but doesn't have any
462 	 * protocols configured. In this case we request our favoured
463 	 * protocol. */
464 	goto pick_first;
465     }
466 
467     rv = ssl3_ValidateNextProtoNego(data->data, data->len);
468     if (rv != SECSuccess)
469 	return rv;
470 
471     /* For each protocol in server preference order, see if we support it. */
472     for (i = 0; i < data->len; ) {
473 	for (j = 0; j < ss->opt.nextProtoNego.len; ) {
474 	    if (data->data[i] == ss->opt.nextProtoNego.data[j] &&
475 		memcmp(&data->data[i+1], &ss->opt.nextProtoNego.data[j+1],
476 		       data->data[i]) == 0) {
477 		/* We found a match */
478 		ss->ssl3.nextProtoState = SSL_NEXT_PROTO_NEGOTIATED;
479 		result = &data->data[i];
480 		goto found;
481 	    }
482 	    j += (unsigned int)ss->opt.nextProtoNego.data[j] + 1;
483 	}
484 
485 	i += (unsigned int)data->data[i] + 1;
486     }
487 
488   pick_first:
489     ss->ssl3.nextProtoState = SSL_NEXT_PROTO_NO_OVERLAP;
490     result = ss->opt.nextProtoNego.data;
491 
492   found:
493     if (ss->ssl3.nextProto.data)
494 	PORT_Free(ss->ssl3.nextProto.data);
495     ss->ssl3.nextProto.data = PORT_Alloc(result[0]);
496     PORT_Memcpy(ss->ssl3.nextProto.data, result + 1, result[0]);
497     ss->ssl3.nextProto.len = result[0];
498     return SECSuccess;
499 }
500 
501 PRInt32
ssl3_ClientSendNextProtoNegoXtn(sslSocket * ss,PRBool append,PRUint32 maxBytes)502 ssl3_ClientSendNextProtoNegoXtn(sslSocket * ss,
503 			       PRBool      append,
504 			       PRUint32    maxBytes)
505 {
506     PRInt32 extension_length;
507 
508     /* Renegotiations do not send this extension. */
509     if (ss->opt.nextProtoNego.len == 0 || ss->firstHsDone) {
510 	return 0;
511     }
512 
513     extension_length = 4;
514 
515     if (append && maxBytes >= extension_length) {
516 	SECStatus rv;
517 	TLSExtensionData *xtnData;
518 	rv = ssl3_AppendHandshakeNumber(ss, next_proto_neg_xtn, 2);
519 	if (rv != SECSuccess)
520 	    goto loser;
521 	rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
522 	if (rv != SECSuccess)
523 	    goto loser;
524 	xtnData = &ss->xtnData;
525 	xtnData->advertised[xtnData->numAdvertised++] = next_proto_neg_xtn;
526     } else if (maxBytes < extension_length) {
527 	return 0;
528     }
529 
530     return extension_length;
531 
532  loser:
533     return -1;
534 }
535 
536 /*
537  * NewSessionTicket
538  * Called from ssl3_HandleFinished
539  */
540 SECStatus
ssl3_SendNewSessionTicket(sslSocket * ss)541 ssl3_SendNewSessionTicket(sslSocket *ss)
542 {
543     int                  i;
544     SECStatus            rv;
545     NewSessionTicket     ticket;
546     SECItem              plaintext;
547     SECItem              plaintext_item = {0, NULL, 0};
548     SECItem              ciphertext     = {0, NULL, 0};
549     PRUint32             ciphertext_length;
550     PRBool               ms_is_wrapped;
551     unsigned char        wrapped_ms[SSL3_MASTER_SECRET_LENGTH];
552     SECItem              ms_item = {0, NULL, 0};
553     SSL3KEAType          effectiveExchKeyType = ssl_kea_null;
554     PRUint32             padding_length;
555     PRUint32             message_length;
556     PRUint32             cert_length;
557     uint8                length_buf[4];
558     PRUint32             now;
559     PK11SymKey          *aes_key_pkcs11;
560     PK11SymKey          *mac_key_pkcs11;
561     const unsigned char *aes_key;
562     const unsigned char *mac_key;
563     PRUint32             aes_key_length;
564     PRUint32             mac_key_length;
565     PRUint64             aes_ctx_buf[MAX_CIPHER_CONTEXT_LLONGS];
566     AESContext          *aes_ctx;
567     CK_MECHANISM_TYPE    cipherMech = CKM_AES_CBC;
568     PK11Context         *aes_ctx_pkcs11;
569     const SECHashObject *hashObj = NULL;
570     PRUint64             hmac_ctx_buf[MAX_MAC_CONTEXT_LLONGS];
571     HMACContext         *hmac_ctx;
572     CK_MECHANISM_TYPE    macMech = CKM_SHA256_HMAC;
573     PK11Context         *hmac_ctx_pkcs11;
574     unsigned char        computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH];
575     unsigned int         computed_mac_length;
576     unsigned char        iv[AES_BLOCK_SIZE];
577     SECItem              ivItem;
578     CK_MECHANISM_TYPE    msWrapMech = 0; /* dummy default value,
579                                           * must be >= 0 */
580 
581     SSL_TRC(3, ("%d: SSL3[%d]: send session_ticket handshake",
582 		SSL_GETPID(), ss->fd));
583 
584     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
585     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
586 
587     ticket.ticket_lifetime_hint = TLS_EX_SESS_TICKET_LIFETIME_HINT;
588     cert_length = (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) ?
589 	3 + ss->sec.ci.sid->peerCert->derCert.len : 0;
590 
591     /* Get IV and encryption keys */
592     ivItem.data = iv;
593     ivItem.len = sizeof(iv);
594     rv = PK11_GenerateRandom(iv, sizeof(iv));
595     if (rv != SECSuccess) goto loser;
596 
597     if (ss->opt.bypassPKCS11) {
598 	rv = ssl3_GetSessionTicketKeys(&aes_key, &aes_key_length,
599 	    &mac_key, &mac_key_length);
600     } else {
601 	rv = ssl3_GetSessionTicketKeysPKCS11(ss, &aes_key_pkcs11,
602 	    &mac_key_pkcs11);
603     }
604     if (rv != SECSuccess) goto loser;
605 
606     if (ss->ssl3.pwSpec->msItem.len && ss->ssl3.pwSpec->msItem.data) {
607 	/* The master secret is available unwrapped. */
608 	ms_item.data = ss->ssl3.pwSpec->msItem.data;
609 	ms_item.len = ss->ssl3.pwSpec->msItem.len;
610 	ms_is_wrapped = PR_FALSE;
611     } else {
612 	/* Extract the master secret wrapped. */
613 	sslSessionID sid;
614 	PORT_Memset(&sid, 0, sizeof(sslSessionID));
615 
616 	if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) {
617 	    effectiveExchKeyType = kt_rsa;
618 	} else {
619 	    effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType;
620 	}
621 
622 	rv = ssl3_CacheWrappedMasterSecret(ss, &sid, ss->ssl3.pwSpec,
623 	    effectiveExchKeyType);
624 	if (rv == SECSuccess) {
625 	    if (sid.u.ssl3.keys.wrapped_master_secret_len > sizeof(wrapped_ms))
626 		goto loser;
627 	    memcpy(wrapped_ms, sid.u.ssl3.keys.wrapped_master_secret,
628 		sid.u.ssl3.keys.wrapped_master_secret_len);
629 	    ms_item.data = wrapped_ms;
630 	    ms_item.len = sid.u.ssl3.keys.wrapped_master_secret_len;
631 	    msWrapMech = sid.u.ssl3.masterWrapMech;
632 	} else {
633 	    /* TODO: else send an empty ticket. */
634 	    goto loser;
635 	}
636 	ms_is_wrapped = PR_TRUE;
637     }
638 
639     ciphertext_length =
640 	sizeof(PRUint16)                     /* ticket_version */
641 	+ sizeof(SSL3ProtocolVersion)        /* ssl_version */
642 	+ sizeof(ssl3CipherSuite)            /* ciphersuite */
643 	+ 1                                  /* compression */
644 	+ 10                                 /* cipher spec parameters */
645 	+ 1                                  /* SessionTicket.ms_is_wrapped */
646 	+ 1                                  /* effectiveExchKeyType */
647 	+ 4                                  /* msWrapMech */
648 	+ 2                                  /* master_secret.length */
649 	+ ms_item.len                        /* master_secret */
650 	+ 1                                  /* client_auth_type */
651 	+ cert_length                        /* cert */
652 	+ sizeof(ticket.ticket_lifetime_hint);
653     padding_length =  AES_BLOCK_SIZE -
654 	(ciphertext_length % AES_BLOCK_SIZE);
655     ciphertext_length += padding_length;
656 
657     message_length =
658 	sizeof(ticket.ticket_lifetime_hint)    /* ticket_lifetime_hint */
659 	+ 2 /* length field for NewSessionTicket.ticket */
660 	+ SESS_TICKET_KEY_NAME_LEN             /* key_name */
661 	+ AES_BLOCK_SIZE                       /* iv */
662 	+ 2 /* length field for NewSessionTicket.ticket.encrypted_state */
663 	+ ciphertext_length                    /* encrypted_state */
664 	+ TLS_EX_SESS_TICKET_MAC_LENGTH;       /* mac */
665 
666     if (SECITEM_AllocItem(NULL, &plaintext_item, ciphertext_length) == NULL)
667 	goto loser;
668 
669     plaintext = plaintext_item;
670 
671     /* ticket_version */
672     rv = ssl3_AppendNumberToItem(&plaintext, TLS_EX_SESS_TICKET_VERSION,
673 	sizeof(PRUint16));
674     if (rv != SECSuccess) goto loser;
675 
676     /* ssl_version */
677     rv = ssl3_AppendNumberToItem(&plaintext, ss->version,
678 	sizeof(SSL3ProtocolVersion));
679     if (rv != SECSuccess) goto loser;
680 
681     /* ciphersuite */
682     rv = ssl3_AppendNumberToItem(&plaintext, ss->ssl3.hs.cipher_suite,
683 	sizeof(ssl3CipherSuite));
684     if (rv != SECSuccess) goto loser;
685 
686     /* compression */
687     rv = ssl3_AppendNumberToItem(&plaintext, ss->ssl3.hs.compression, 1);
688     if (rv != SECSuccess) goto loser;
689 
690     /* cipher spec parameters */
691     rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.authAlgorithm, 1);
692     if (rv != SECSuccess) goto loser;
693     rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.authKeyBits, 4);
694     if (rv != SECSuccess) goto loser;
695     rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.keaType, 1);
696     if (rv != SECSuccess) goto loser;
697     rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.keaKeyBits, 4);
698     if (rv != SECSuccess) goto loser;
699 
700     /* master_secret */
701     rv = ssl3_AppendNumberToItem(&plaintext, ms_is_wrapped, 1);
702     if (rv != SECSuccess) goto loser;
703     rv = ssl3_AppendNumberToItem(&plaintext, effectiveExchKeyType, 1);
704     if (rv != SECSuccess) goto loser;
705     rv = ssl3_AppendNumberToItem(&plaintext, msWrapMech, 4);
706     if (rv != SECSuccess) goto loser;
707     rv = ssl3_AppendNumberToItem(&plaintext, ms_item.len, 2);
708     if (rv != SECSuccess) goto loser;
709     rv = ssl3_AppendToItem(&plaintext, ms_item.data, ms_item.len);
710     if (rv != SECSuccess) goto loser;
711 
712     /* client_identity */
713     if (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) {
714 	rv = ssl3_AppendNumberToItem(&plaintext, CLIENT_AUTH_CERTIFICATE, 1);
715 	if (rv != SECSuccess) goto loser;
716 	rv = ssl3_AppendNumberToItem(&plaintext,
717 	    ss->sec.ci.sid->peerCert->derCert.len, 3);
718 	if (rv != SECSuccess) goto loser;
719 	rv = ssl3_AppendToItem(&plaintext,
720 	    ss->sec.ci.sid->peerCert->derCert.data,
721 	    ss->sec.ci.sid->peerCert->derCert.len);
722 	if (rv != SECSuccess) goto loser;
723     } else {
724 	rv = ssl3_AppendNumberToItem(&plaintext, 0, 1);
725 	if (rv != SECSuccess) goto loser;
726     }
727 
728     /* timestamp */
729     now = ssl_Time();
730     rv = ssl3_AppendNumberToItem(&plaintext, now,
731 	sizeof(ticket.ticket_lifetime_hint));
732     if (rv != SECSuccess) goto loser;
733 
734     PORT_Assert(plaintext.len == padding_length);
735     for (i = 0; i < padding_length; i++)
736 	plaintext.data[i] = (unsigned char)padding_length;
737 
738     if (SECITEM_AllocItem(NULL, &ciphertext, ciphertext_length) == NULL) {
739 	rv = SECFailure;
740 	goto loser;
741     }
742 
743     /* Generate encrypted portion of ticket. */
744     if (ss->opt.bypassPKCS11) {
745 	aes_ctx = (AESContext *)aes_ctx_buf;
746 	rv = AES_InitContext(aes_ctx, aes_key, aes_key_length, iv,
747 	    NSS_AES_CBC, 1, AES_BLOCK_SIZE);
748 	if (rv != SECSuccess) goto loser;
749 
750 	rv = AES_Encrypt(aes_ctx, ciphertext.data, &ciphertext.len,
751 	    ciphertext.len, plaintext_item.data,
752 	    plaintext_item.len);
753 	if (rv != SECSuccess) goto loser;
754     } else {
755 	aes_ctx_pkcs11 = PK11_CreateContextBySymKey(cipherMech,
756 	    CKA_ENCRYPT, aes_key_pkcs11, &ivItem);
757 	if (!aes_ctx_pkcs11)
758 	    goto loser;
759 
760 	rv = PK11_CipherOp(aes_ctx_pkcs11, ciphertext.data,
761 	    (int *)&ciphertext.len, ciphertext.len,
762 	    plaintext_item.data, plaintext_item.len);
763 	PK11_Finalize(aes_ctx_pkcs11);
764 	PK11_DestroyContext(aes_ctx_pkcs11, PR_TRUE);
765 	if (rv != SECSuccess) goto loser;
766     }
767 
768     /* Convert ciphertext length to network order. */
769     length_buf[0] = (ciphertext.len >> 8) & 0xff;
770     length_buf[1] = (ciphertext.len     ) & 0xff;
771 
772     /* Compute MAC. */
773     if (ss->opt.bypassPKCS11) {
774 	hmac_ctx = (HMACContext *)hmac_ctx_buf;
775 	hashObj = HASH_GetRawHashObject(HASH_AlgSHA256);
776 	if (HMAC_Init(hmac_ctx, hashObj, mac_key,
777 		mac_key_length, PR_FALSE) != SECSuccess)
778 	    goto loser;
779 
780 	HMAC_Begin(hmac_ctx);
781 	HMAC_Update(hmac_ctx, key_name, SESS_TICKET_KEY_NAME_LEN);
782 	HMAC_Update(hmac_ctx, iv, sizeof(iv));
783 	HMAC_Update(hmac_ctx, (unsigned char *)length_buf, 2);
784 	HMAC_Update(hmac_ctx, ciphertext.data, ciphertext.len);
785 	HMAC_Finish(hmac_ctx, computed_mac, &computed_mac_length,
786 	    sizeof(computed_mac));
787     } else {
788 	SECItem macParam;
789 	macParam.data = NULL;
790 	macParam.len = 0;
791 	hmac_ctx_pkcs11 = PK11_CreateContextBySymKey(macMech,
792 	    CKA_SIGN, mac_key_pkcs11, &macParam);
793 	if (!hmac_ctx_pkcs11)
794 	    goto loser;
795 
796 	rv = PK11_DigestBegin(hmac_ctx_pkcs11);
797 	rv = PK11_DigestOp(hmac_ctx_pkcs11, key_name,
798 	    SESS_TICKET_KEY_NAME_LEN);
799 	rv = PK11_DigestOp(hmac_ctx_pkcs11, iv, sizeof(iv));
800 	rv = PK11_DigestOp(hmac_ctx_pkcs11, (unsigned char *)length_buf, 2);
801 	rv = PK11_DigestOp(hmac_ctx_pkcs11, ciphertext.data, ciphertext.len);
802 	rv = PK11_DigestFinal(hmac_ctx_pkcs11, computed_mac,
803 	    &computed_mac_length, sizeof(computed_mac));
804 	PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE);
805 	if (rv != SECSuccess) goto loser;
806     }
807 
808     /* Serialize the handshake message. */
809     rv = ssl3_AppendHandshakeHeader(ss, new_session_ticket, message_length);
810     if (rv != SECSuccess) goto loser;
811 
812     rv = ssl3_AppendHandshakeNumber(ss, ticket.ticket_lifetime_hint,
813 	sizeof(ticket.ticket_lifetime_hint));
814     if (rv != SECSuccess) goto loser;
815 
816     rv = ssl3_AppendHandshakeNumber(ss,
817 	message_length - sizeof(ticket.ticket_lifetime_hint) - 2, 2);
818     if (rv != SECSuccess) goto loser;
819 
820     rv = ssl3_AppendHandshake(ss, key_name, SESS_TICKET_KEY_NAME_LEN);
821     if (rv != SECSuccess) goto loser;
822 
823     rv = ssl3_AppendHandshake(ss, iv, sizeof(iv));
824     if (rv != SECSuccess) goto loser;
825 
826     rv = ssl3_AppendHandshakeVariable(ss, ciphertext.data, ciphertext.len, 2);
827     if (rv != SECSuccess) goto loser;
828 
829     rv = ssl3_AppendHandshake(ss, computed_mac, computed_mac_length);
830     if (rv != SECSuccess) goto loser;
831 
832 loser:
833     if (plaintext_item.data)
834 	SECITEM_FreeItem(&plaintext_item, PR_FALSE);
835     if (ciphertext.data)
836 	SECITEM_FreeItem(&ciphertext, PR_FALSE);
837 
838     return rv;
839 }
840 
841 /* When a client receives a SessionTicket extension a NewSessionTicket
842  * message is expected during the handshake.
843  */
844 SECStatus
ssl3_ClientHandleSessionTicketXtn(sslSocket * ss,PRUint16 ex_type,SECItem * data)845 ssl3_ClientHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type,
846                                   SECItem *data)
847 {
848     if (data->len != 0)
849 	return SECFailure;
850 
851     /* Keep track of negotiated extensions. */
852     ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
853     return SECSuccess;
854 }
855 
856 SECStatus
ssl3_ServerHandleSessionTicketXtn(sslSocket * ss,PRUint16 ex_type,SECItem * data)857 ssl3_ServerHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type,
858                                   SECItem *data)
859 {
860     SECStatus rv;
861     SECItem *decrypted_state = NULL;
862     SessionTicket *parsed_session_ticket = NULL;
863     sslSessionID *sid = NULL;
864     SSL3Statistics *ssl3stats;
865 
866     /* Ignore the SessionTicket extension if processing is disabled. */
867     if (!ss->opt.enableSessionTickets)
868 	return SECSuccess;
869 
870     /* Keep track of negotiated extensions. */
871     ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
872 
873     /* Parse the received ticket sent in by the client.  We are
874      * lenient about some parse errors, falling back to a fullshake
875      * instead of terminating the current connection.
876      */
877     if (data->len == 0) {
878 	ss->xtnData.emptySessionTicket = PR_TRUE;
879     } else {
880 	int                    i;
881 	SECItem                extension_data;
882 	EncryptedSessionTicket enc_session_ticket;
883 	unsigned char          computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH];
884 	unsigned int           computed_mac_length;
885 	const SECHashObject   *hashObj;
886 	const unsigned char   *aes_key;
887 	const unsigned char   *mac_key;
888 	PK11SymKey            *aes_key_pkcs11;
889 	PK11SymKey            *mac_key_pkcs11;
890 	PRUint32               aes_key_length;
891 	PRUint32               mac_key_length;
892 	PRUint64               hmac_ctx_buf[MAX_MAC_CONTEXT_LLONGS];
893 	HMACContext           *hmac_ctx;
894 	PK11Context           *hmac_ctx_pkcs11;
895 	CK_MECHANISM_TYPE      macMech = CKM_SHA256_HMAC;
896 	PRUint64               aes_ctx_buf[MAX_CIPHER_CONTEXT_LLONGS];
897 	AESContext            *aes_ctx;
898 	PK11Context           *aes_ctx_pkcs11;
899 	CK_MECHANISM_TYPE      cipherMech = CKM_AES_CBC;
900 	unsigned char *        padding;
901 	PRUint32               padding_length;
902 	unsigned char         *buffer;
903 	unsigned int           buffer_len;
904 	PRInt32                temp;
905 	SECItem                cert_item;
906 
907 	/* Turn off stateless session resumption if the client sends a
908 	 * SessionTicket extension, even if the extension turns out to be
909 	 * malformed (ss->sec.ci.sid is non-NULL when doing session
910 	 * renegotiation.)
911 	 */
912 	if (ss->sec.ci.sid != NULL) {
913 	    ss->sec.uncache(ss->sec.ci.sid);
914 	    ssl_FreeSID(ss->sec.ci.sid);
915 	    ss->sec.ci.sid = NULL;
916 	}
917 
918 	extension_data.data = data->data; /* Keep a copy for future use. */
919 	extension_data.len = data->len;
920 
921 	if (ssl3_ParseEncryptedSessionTicket(ss, data, &enc_session_ticket)
922 	    != SECSuccess)
923 	    return SECFailure;
924 
925 	/* Get session ticket keys. */
926 	if (ss->opt.bypassPKCS11) {
927 	    rv = ssl3_GetSessionTicketKeys(&aes_key, &aes_key_length,
928 		&mac_key, &mac_key_length);
929 	} else {
930 	    rv = ssl3_GetSessionTicketKeysPKCS11(ss, &aes_key_pkcs11,
931 		&mac_key_pkcs11);
932 	}
933 	if (rv != SECSuccess) {
934 	    SSL_DBG(("%d: SSL[%d]: Unable to get/generate session ticket keys.",
935 			SSL_GETPID(), ss->fd));
936 	    goto loser;
937 	}
938 
939 	/* If the ticket sent by the client was generated under a key different
940 	 * from the one we have, bypass ticket processing.
941 	 */
942 	if (PORT_Memcmp(enc_session_ticket.key_name, key_name,
943 		SESS_TICKET_KEY_NAME_LEN) != 0) {
944 	    SSL_DBG(("%d: SSL[%d]: Session ticket key_name sent mismatch.",
945 			SSL_GETPID(), ss->fd));
946 	    goto no_ticket;
947 	}
948 
949 	/* Verify the MAC on the ticket.  MAC verification may also
950 	 * fail if the MAC key has been recently refreshed.
951 	 */
952 	if (ss->opt.bypassPKCS11) {
953 	    hmac_ctx = (HMACContext *)hmac_ctx_buf;
954 	    hashObj = HASH_GetRawHashObject(HASH_AlgSHA256);
955 	    if (HMAC_Init(hmac_ctx, hashObj, mac_key,
956 		    sizeof(session_ticket_mac_key), PR_FALSE) != SECSuccess)
957 		goto no_ticket;
958 	    HMAC_Begin(hmac_ctx);
959 	    HMAC_Update(hmac_ctx, extension_data.data,
960 		extension_data.len - TLS_EX_SESS_TICKET_MAC_LENGTH);
961 	    if (HMAC_Finish(hmac_ctx, computed_mac, &computed_mac_length,
962 		    sizeof(computed_mac)) != SECSuccess)
963 		goto no_ticket;
964 	} else {
965 	    SECItem macParam;
966 	    macParam.data = NULL;
967 	    macParam.len = 0;
968 	    hmac_ctx_pkcs11 = PK11_CreateContextBySymKey(macMech,
969 		CKA_SIGN, mac_key_pkcs11, &macParam);
970 	    if (!hmac_ctx_pkcs11) {
971 		SSL_DBG(("%d: SSL[%d]: Unable to create HMAC context: %d.",
972 			    SSL_GETPID(), ss->fd, PORT_GetError()));
973 		goto no_ticket;
974 	    } else {
975 		SSL_DBG(("%d: SSL[%d]: Successfully created HMAC context.",
976 			    SSL_GETPID(), ss->fd));
977 	    }
978 	    rv = PK11_DigestBegin(hmac_ctx_pkcs11);
979 	    rv = PK11_DigestOp(hmac_ctx_pkcs11, extension_data.data,
980 		extension_data.len - TLS_EX_SESS_TICKET_MAC_LENGTH);
981 	    if (rv != SECSuccess) {
982 		PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE);
983 		goto no_ticket;
984 	    }
985 	    rv = PK11_DigestFinal(hmac_ctx_pkcs11, computed_mac,
986 		&computed_mac_length, sizeof(computed_mac));
987 	    PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE);
988 	    if (rv != SECSuccess)
989 		goto no_ticket;
990 	}
991 	if (NSS_SecureMemcmp(computed_mac, enc_session_ticket.mac,
992 		computed_mac_length) != 0) {
993 	    SSL_DBG(("%d: SSL[%d]: Session ticket MAC mismatch.",
994 			SSL_GETPID(), ss->fd));
995 	    goto no_ticket;
996 	}
997 
998 	/* We ignore key_name for now.
999 	 * This is ok as MAC verification succeeded.
1000 	 */
1001 
1002 	/* Decrypt the ticket. */
1003 
1004 	/* Plaintext is shorter than the ciphertext due to padding. */
1005 	decrypted_state = SECITEM_AllocItem(NULL, NULL,
1006 	    enc_session_ticket.encrypted_state.len);
1007 
1008 	if (ss->opt.bypassPKCS11) {
1009 	    aes_ctx = (AESContext *)aes_ctx_buf;
1010 	    rv = AES_InitContext(aes_ctx, aes_key,
1011 		sizeof(session_ticket_enc_key), enc_session_ticket.iv,
1012 		NSS_AES_CBC, 0,AES_BLOCK_SIZE);
1013 	    if (rv != SECSuccess) {
1014 		SSL_DBG(("%d: SSL[%d]: Unable to create AES context.",
1015 			    SSL_GETPID(), ss->fd));
1016 		goto no_ticket;
1017 	    }
1018 
1019 	    rv = AES_Decrypt(aes_ctx, decrypted_state->data,
1020 		&decrypted_state->len, decrypted_state->len,
1021 		enc_session_ticket.encrypted_state.data,
1022 		enc_session_ticket.encrypted_state.len);
1023 	    if (rv != SECSuccess)
1024 		goto no_ticket;
1025 	} else {
1026 	    SECItem ivItem;
1027 	    ivItem.data = enc_session_ticket.iv;
1028 	    ivItem.len = AES_BLOCK_SIZE;
1029 	    aes_ctx_pkcs11 = PK11_CreateContextBySymKey(cipherMech,
1030 		CKA_DECRYPT, aes_key_pkcs11, &ivItem);
1031 	    if (!aes_ctx_pkcs11) {
1032 		SSL_DBG(("%d: SSL[%d]: Unable to create AES context.",
1033 			    SSL_GETPID(), ss->fd));
1034 		goto no_ticket;
1035 	    }
1036 
1037 	    rv = PK11_CipherOp(aes_ctx_pkcs11, decrypted_state->data,
1038 		(int *)&decrypted_state->len, decrypted_state->len,
1039 		enc_session_ticket.encrypted_state.data,
1040 		enc_session_ticket.encrypted_state.len);
1041 	    PK11_Finalize(aes_ctx_pkcs11);
1042 	    PK11_DestroyContext(aes_ctx_pkcs11, PR_TRUE);
1043 	    if (rv != SECSuccess)
1044 		goto no_ticket;
1045 	}
1046 
1047 	/* Check padding. */
1048 	padding_length =
1049 	    (PRUint32)decrypted_state->data[decrypted_state->len - 1];
1050 	if (padding_length == 0 || padding_length > AES_BLOCK_SIZE)
1051 	    goto no_ticket;
1052 
1053 	padding = &decrypted_state->data[decrypted_state->len - padding_length];
1054 	for (i = 0; i < padding_length; i++, padding++) {
1055 	    if (padding_length != (PRUint32)*padding)
1056 		goto no_ticket;
1057 	}
1058 
1059 	/* Deserialize session state. */
1060 	buffer = decrypted_state->data;
1061 	buffer_len = decrypted_state->len;
1062 
1063 	parsed_session_ticket = PORT_ZAlloc(sizeof(SessionTicket));
1064 	if (parsed_session_ticket == NULL) {
1065 	    rv = SECFailure;
1066 	    goto loser;
1067 	}
1068 
1069 	/* Read ticket_version (which is ignored for now.) */
1070 	temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1071 	if (temp < 0) goto no_ticket;
1072 	parsed_session_ticket->ticket_version = (SSL3ProtocolVersion)temp;
1073 
1074 	/* Read SSLVersion. */
1075 	temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1076 	if (temp < 0) goto no_ticket;
1077 	parsed_session_ticket->ssl_version = (SSL3ProtocolVersion)temp;
1078 
1079 	/* Read cipher_suite. */
1080 	temp =  ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1081 	if (temp < 0) goto no_ticket;
1082 	parsed_session_ticket->cipher_suite = (ssl3CipherSuite)temp;
1083 
1084 	/* Read compression_method. */
1085 	temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1086 	if (temp < 0) goto no_ticket;
1087 	parsed_session_ticket->compression_method = (SSLCompressionMethod)temp;
1088 
1089 	/* Read cipher spec parameters. */
1090 	temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1091 	if (temp < 0) goto no_ticket;
1092 	parsed_session_ticket->authAlgorithm = (SSLSignType)temp;
1093 	temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1094 	if (temp < 0) goto no_ticket;
1095 	parsed_session_ticket->authKeyBits = (PRUint32)temp;
1096 	temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1097 	if (temp < 0) goto no_ticket;
1098 	parsed_session_ticket->keaType = (SSLKEAType)temp;
1099 	temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1100 	if (temp < 0) goto no_ticket;
1101 	parsed_session_ticket->keaKeyBits = (PRUint32)temp;
1102 
1103 	/* Read wrapped master_secret. */
1104 	temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1105 	if (temp < 0) goto no_ticket;
1106 	parsed_session_ticket->ms_is_wrapped = (PRBool)temp;
1107 
1108 	temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1109 	if (temp < 0) goto no_ticket;
1110 	parsed_session_ticket->exchKeyType = (SSL3KEAType)temp;
1111 
1112 	temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1113 	if (temp < 0) goto no_ticket;
1114 	parsed_session_ticket->msWrapMech = (CK_MECHANISM_TYPE)temp;
1115 
1116 	temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1117 	if (temp < 0) goto no_ticket;
1118 	parsed_session_ticket->ms_length = (PRUint16)temp;
1119 	if (parsed_session_ticket->ms_length == 0 ||  /* sanity check MS. */
1120 	    parsed_session_ticket->ms_length >
1121 	    sizeof(parsed_session_ticket->master_secret))
1122 	    goto no_ticket;
1123 
1124 	/* Allow for the wrapped master secret to be longer. */
1125 	if (buffer_len < sizeof(SSL3_MASTER_SECRET_LENGTH))
1126 	    goto no_ticket;
1127 	PORT_Memcpy(parsed_session_ticket->master_secret, buffer,
1128 	    parsed_session_ticket->ms_length);
1129 	buffer += parsed_session_ticket->ms_length;
1130 	buffer_len -= parsed_session_ticket->ms_length;
1131 
1132 	/* Read client_identity */
1133 	temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1134 	if (temp < 0)
1135 	    goto no_ticket;
1136 	parsed_session_ticket->client_identity.client_auth_type =
1137 	    (ClientAuthenticationType)temp;
1138 	switch(parsed_session_ticket->client_identity.client_auth_type) {
1139             case CLIENT_AUTH_ANONYMOUS:
1140 		break;
1141             case CLIENT_AUTH_CERTIFICATE:
1142 		rv = ssl3_ConsumeHandshakeVariable(ss, &cert_item, 3,
1143 		    &buffer, &buffer_len);
1144 		if (rv != SECSuccess) goto no_ticket;
1145 		rv = SECITEM_CopyItem(NULL, &parsed_session_ticket->peer_cert,
1146 		    &cert_item);
1147 		if (rv != SECSuccess) goto no_ticket;
1148 		break;
1149             default:
1150 		goto no_ticket;
1151 	}
1152 	/* Read timestamp. */
1153 	temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1154 	if (temp < 0)
1155 	    goto no_ticket;
1156 	parsed_session_ticket->timestamp = (PRUint32)temp;
1157 
1158 	/* Done parsing.  Check that all bytes have been consumed. */
1159 	if (buffer_len != padding_length)
1160 	    goto no_ticket;
1161 
1162 	/* Use the ticket if it has not expired, otherwise free the allocated
1163 	 * memory since the ticket is of no use.
1164 	 */
1165 	if (parsed_session_ticket->timestamp != 0 &&
1166 	    parsed_session_ticket->timestamp +
1167 	    TLS_EX_SESS_TICKET_LIFETIME_HINT > ssl_Time()) {
1168 
1169 	    sid = ssl3_NewSessionID(ss, PR_TRUE);
1170 	    if (sid == NULL) {
1171 		rv = SECFailure;
1172 		goto loser;
1173 	    }
1174 
1175 	    /* Copy over parameters. */
1176 	    sid->version = parsed_session_ticket->ssl_version;
1177 	    sid->u.ssl3.cipherSuite = parsed_session_ticket->cipher_suite;
1178 	    sid->u.ssl3.compression = parsed_session_ticket->compression_method;
1179 	    sid->authAlgorithm = parsed_session_ticket->authAlgorithm;
1180 	    sid->authKeyBits = parsed_session_ticket->authKeyBits;
1181 	    sid->keaType = parsed_session_ticket->keaType;
1182 	    sid->keaKeyBits = parsed_session_ticket->keaKeyBits;
1183 
1184 	    /* Copy master secret. */
1185 	    if (ss->opt.bypassPKCS11 &&
1186 		    parsed_session_ticket->ms_is_wrapped)
1187 		goto no_ticket;
1188 	    if (parsed_session_ticket->ms_length >
1189 		    sizeof(sid->u.ssl3.keys.wrapped_master_secret))
1190 		goto no_ticket;
1191 	    PORT_Memcpy(sid->u.ssl3.keys.wrapped_master_secret,
1192 		parsed_session_ticket->master_secret,
1193 		parsed_session_ticket->ms_length);
1194 	    sid->u.ssl3.keys.wrapped_master_secret_len =
1195 		parsed_session_ticket->ms_length;
1196 	    sid->u.ssl3.exchKeyType = parsed_session_ticket->exchKeyType;
1197 	    sid->u.ssl3.masterWrapMech = parsed_session_ticket->msWrapMech;
1198 	    sid->u.ssl3.keys.msIsWrapped =
1199 		parsed_session_ticket->ms_is_wrapped;
1200 	    sid->u.ssl3.masterValid    = PR_TRUE;
1201 	    sid->u.ssl3.keys.resumable = PR_TRUE;
1202 
1203 	    /* Copy over client cert from session ticket if there is one. */
1204 	    if (parsed_session_ticket->peer_cert.data != NULL) {
1205 		if (sid->peerCert != NULL)
1206 		    CERT_DestroyCertificate(sid->peerCert);
1207 		sid->peerCert = CERT_NewTempCertificate(ss->dbHandle,
1208 		    &parsed_session_ticket->peer_cert, NULL, PR_FALSE, PR_TRUE);
1209 		if (sid->peerCert == NULL) {
1210 		    rv = SECFailure;
1211 		    goto loser;
1212 		}
1213 	    }
1214 	    ss->statelessResume = PR_TRUE;
1215 	    ss->sec.ci.sid = sid;
1216 	}
1217     }
1218 
1219     if (0) {
1220 no_ticket:
1221 	SSL_DBG(("%d: SSL[%d]: Session ticket parsing failed.",
1222 			SSL_GETPID(), ss->fd));
1223 	ssl3stats = SSL_GetStatistics();
1224 	SSL_AtomicIncrementLong(& ssl3stats->hch_sid_ticket_parse_failures );
1225 	if (sid) {
1226 	    ssl_FreeSID(sid);
1227 	    sid = NULL;
1228 	}
1229     }
1230     rv = SECSuccess;
1231 
1232 loser:
1233     if (decrypted_state != NULL) {
1234 	SECITEM_FreeItem(decrypted_state, PR_TRUE);
1235 	decrypted_state = NULL;
1236     }
1237 
1238     if (parsed_session_ticket != NULL) {
1239 	if (parsed_session_ticket->peer_cert.data) {
1240 	    SECITEM_FreeItem(&parsed_session_ticket->peer_cert, PR_FALSE);
1241 	}
1242 	PORT_ZFree(parsed_session_ticket, sizeof(SessionTicket));
1243     }
1244 
1245     return rv;
1246 }
1247 
1248 /*
1249  * Read bytes.  Using this function means the SECItem structure
1250  * cannot be freed.  The caller is expected to call this function
1251  * on a shallow copy of the structure.
1252  */
1253 static SECStatus
ssl3_ConsumeFromItem(SECItem * item,unsigned char ** buf,PRUint32 bytes)1254 ssl3_ConsumeFromItem(SECItem *item, unsigned char **buf, PRUint32 bytes)
1255 {
1256     if (bytes > item->len)
1257 	return SECFailure;
1258 
1259     *buf = item->data;
1260     item->data += bytes;
1261     item->len -= bytes;
1262     return SECSuccess;
1263 }
1264 
1265 static SECStatus
ssl3_ParseEncryptedSessionTicket(sslSocket * ss,SECItem * data,EncryptedSessionTicket * enc_session_ticket)1266 ssl3_ParseEncryptedSessionTicket(sslSocket *ss, SECItem *data,
1267                                  EncryptedSessionTicket *enc_session_ticket)
1268 {
1269     if (ssl3_ConsumeFromItem(data, &enc_session_ticket->key_name,
1270 	    SESS_TICKET_KEY_NAME_LEN) != SECSuccess)
1271 	return SECFailure;
1272     if (ssl3_ConsumeFromItem(data, &enc_session_ticket->iv,
1273 	    AES_BLOCK_SIZE) != SECSuccess)
1274 	return SECFailure;
1275     if (ssl3_ConsumeHandshakeVariable(ss, &enc_session_ticket->encrypted_state,
1276 	    2, &data->data, &data->len) != SECSuccess)
1277 	return SECFailure;
1278     if (ssl3_ConsumeFromItem(data, &enc_session_ticket->mac,
1279 	    TLS_EX_SESS_TICKET_MAC_LENGTH) != SECSuccess)
1280 	return SECFailure;
1281     if (data->len != 0)  /* Make sure that we have consumed all bytes. */
1282 	return SECFailure;
1283 
1284     return SECSuccess;
1285 }
1286 
1287 /* go through hello extensions in buffer "b".
1288  * For each one, find the extension handler in the table, and
1289  * if present, invoke that handler.
1290  * Servers ignore any extensions with unknown extension types.
1291  * Clients reject any extensions with unadvertised extension types.
1292  */
1293 SECStatus
ssl3_HandleHelloExtensions(sslSocket * ss,SSL3Opaque ** b,PRUint32 * length)1294 ssl3_HandleHelloExtensions(sslSocket *ss, SSL3Opaque **b, PRUint32 *length)
1295 {
1296     const ssl3HelloExtensionHandler * handlers =
1297 	ss->sec.isServer ? clientHelloHandlers : serverHelloHandlers;
1298 
1299     while (*length) {
1300 	const ssl3HelloExtensionHandler * handler;
1301 	SECStatus rv;
1302 	PRInt32   extension_type;
1303 	SECItem   extension_data;
1304 
1305 	/* Get the extension's type field */
1306 	extension_type = ssl3_ConsumeHandshakeNumber(ss, 2, b, length);
1307 	if (extension_type < 0)  /* failure to decode extension_type */
1308 	    return SECFailure;   /* alert already sent */
1309 
1310 	/* get the data for this extension, so we can pass it or skip it. */
1311 	rv = ssl3_ConsumeHandshakeVariable(ss, &extension_data, 2, b, length);
1312 	if (rv != SECSuccess)
1313 	    return rv;
1314 
1315 	/* Check whether the server sent an extension which was not advertised
1316 	 * in the ClientHello.
1317 	 */
1318 	if (!ss->sec.isServer &&
1319 	    !ssl3_ClientExtensionAdvertised(ss, extension_type))
1320 	    return SECFailure;  /* TODO: send unsupported_extension alert */
1321 
1322 	/* Check whether an extension has been sent multiple times. */
1323 	if (ssl3_ExtensionNegotiated(ss, extension_type))
1324 	    return SECFailure;
1325 
1326 	/* find extension_type in table of Hello Extension Handlers */
1327 	for (handler = handlers; handler->ex_type >= 0; handler++) {
1328 	    /* if found, call this handler */
1329 	    if (handler->ex_type == extension_type) {
1330 		rv = (*handler->ex_handler)(ss, (PRUint16)extension_type,
1331 	                                         	&extension_data);
1332 		/* Ignore this result */
1333 		/* Treat all bad extensions as unrecognized types. */
1334 	        break;
1335 	    }
1336 	}
1337     }
1338     return SECSuccess;
1339 }
1340 
1341 /* Add a callback function to the table of senders of server hello extensions.
1342  */
1343 SECStatus
ssl3_RegisterServerHelloExtensionSender(sslSocket * ss,PRUint16 ex_type,ssl3HelloExtensionSenderFunc cb)1344 ssl3_RegisterServerHelloExtensionSender(sslSocket *ss, PRUint16 ex_type,
1345 				        ssl3HelloExtensionSenderFunc cb)
1346 {
1347     int i;
1348     ssl3HelloExtensionSender *sender = &ss->xtnData.serverSenders[0];
1349 
1350     for (i = 0; i < MAX_EXTENSIONS; ++i, ++sender) {
1351         if (!sender->ex_sender) {
1352 	    sender->ex_type   = ex_type;
1353 	    sender->ex_sender = cb;
1354 	    return SECSuccess;
1355 	}
1356 	/* detect duplicate senders */
1357 	PORT_Assert(sender->ex_type != ex_type);
1358 	if (sender->ex_type == ex_type) {
1359 	    /* duplicate */
1360 	    break;
1361 	}
1362     }
1363     PORT_Assert(i < MAX_EXTENSIONS); /* table needs to grow */
1364     PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1365     return SECFailure;
1366 }
1367 
1368 /* call each of the extension senders and return the accumulated length */
1369 PRInt32
ssl3_CallHelloExtensionSenders(sslSocket * ss,PRBool append,PRUint32 maxBytes,const ssl3HelloExtensionSender * sender)1370 ssl3_CallHelloExtensionSenders(sslSocket *ss, PRBool append, PRUint32 maxBytes,
1371                                const ssl3HelloExtensionSender *sender)
1372 {
1373     PRInt32 total_exten_len = 0;
1374     int i;
1375 
1376     if (!sender)
1377     	sender = &clientHelloSenders[0];
1378 
1379     for (i = 0; i < MAX_EXTENSIONS; ++i, ++sender) {
1380 	if (sender->ex_sender) {
1381 	    PRInt32 extLen = (*sender->ex_sender)(ss, append, maxBytes);
1382 	    if (extLen < 0)
1383 	    	return -1;
1384 	    maxBytes        -= extLen;
1385 	    total_exten_len += extLen;
1386 	}
1387     }
1388     return total_exten_len;
1389 }
1390