Windows should animate when they are about to get docked at screen edges.
[chromium-blink-merge.git] / net / third_party / nss / ssl / ssl3ext.c
blob04157701e9028e670098fa47469960ffc05513c9
1 /*
2 * SSL3 Protocol
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/. */
8 /* TLS extension code moved here from ssl3ecc.c */
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"
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;
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];
31 static PRBool session_ticket_keys_initialized = PR_FALSE;
32 #endif
33 static PRCallOnceType generate_session_keys_once;
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);
86 * Write bytes. Using this function means the SECItem structure
87 * cannot be freed. The caller is expected to call this function
88 * on a shallow copy of the structure.
90 static SECStatus
91 ssl3_AppendToItem(SECItem *item, const unsigned char *buf, PRUint32 bytes)
93 if (bytes > item->len)
94 return SECFailure;
96 PORT_Memcpy(item->data, buf, bytes);
97 item->data += bytes;
98 item->len -= bytes;
99 return SECSuccess;
103 * Write a number in network byte order. Using this function means the
104 * SECItem structure cannot be freed. The caller is expected to call
105 * this function on a shallow copy of the structure.
107 static SECStatus
108 ssl3_AppendNumberToItem(SECItem *item, PRUint32 num, PRInt32 lenSize)
110 SECStatus rv;
111 PRUint8 b[4];
112 PRUint8 * p = b;
114 switch (lenSize) {
115 case 4:
116 *p++ = (PRUint8) (num >> 24);
117 case 3:
118 *p++ = (PRUint8) (num >> 16);
119 case 2:
120 *p++ = (PRUint8) (num >> 8);
121 case 1:
122 *p = (PRUint8) num;
124 rv = ssl3_AppendToItem(item, &b[0], lenSize);
125 return rv;
128 static SECStatus ssl3_SessionTicketShutdown(void* appData, void* nssData)
130 if (session_ticket_enc_key_pkcs11) {
131 PK11_FreeSymKey(session_ticket_enc_key_pkcs11);
132 session_ticket_enc_key_pkcs11 = NULL;
134 if (session_ticket_mac_key_pkcs11) {
135 PK11_FreeSymKey(session_ticket_mac_key_pkcs11);
136 session_ticket_mac_key_pkcs11 = NULL;
138 PORT_Memset(&generate_session_keys_once, 0,
139 sizeof(generate_session_keys_once));
140 return SECSuccess;
144 static PRStatus
145 ssl3_GenerateSessionTicketKeysPKCS11(void *data)
147 SECStatus rv;
148 sslSocket *ss = (sslSocket *)data;
149 SECKEYPrivateKey *svrPrivKey = ss->serverCerts[kt_rsa].SERVERKEY;
150 SECKEYPublicKey *svrPubKey = ss->serverCerts[kt_rsa].serverKeyPair->pubKey;
152 if (svrPrivKey == NULL || svrPubKey == NULL) {
153 SSL_DBG(("%d: SSL[%d]: Pub or priv key(s) is NULL.",
154 SSL_GETPID(), ss->fd));
155 goto loser;
158 /* Get a copy of the session keys from shared memory. */
159 PORT_Memcpy(key_name, SESS_TICKET_KEY_NAME_PREFIX,
160 sizeof(SESS_TICKET_KEY_NAME_PREFIX));
161 if (!ssl_GetSessionTicketKeysPKCS11(svrPrivKey, svrPubKey,
162 ss->pkcs11PinArg, &key_name[SESS_TICKET_KEY_NAME_PREFIX_LEN],
163 &session_ticket_enc_key_pkcs11, &session_ticket_mac_key_pkcs11))
164 return PR_FAILURE;
166 rv = NSS_RegisterShutdown(ssl3_SessionTicketShutdown, NULL);
167 if (rv != SECSuccess)
168 goto loser;
170 return PR_SUCCESS;
172 loser:
173 ssl3_SessionTicketShutdown(NULL, NULL);
174 return PR_FAILURE;
177 static SECStatus
178 ssl3_GetSessionTicketKeysPKCS11(sslSocket *ss, PK11SymKey **aes_key,
179 PK11SymKey **mac_key)
181 if (PR_CallOnceWithArg(&generate_session_keys_once,
182 ssl3_GenerateSessionTicketKeysPKCS11, ss) != PR_SUCCESS)
183 return SECFailure;
185 if (session_ticket_enc_key_pkcs11 == NULL ||
186 session_ticket_mac_key_pkcs11 == NULL)
187 return SECFailure;
189 *aes_key = session_ticket_enc_key_pkcs11;
190 *mac_key = session_ticket_mac_key_pkcs11;
191 return SECSuccess;
194 #ifndef NO_PKCS11_BYPASS
195 static PRStatus
196 ssl3_GenerateSessionTicketKeys(void)
198 PORT_Memcpy(key_name, SESS_TICKET_KEY_NAME_PREFIX,
199 sizeof(SESS_TICKET_KEY_NAME_PREFIX));
201 if (!ssl_GetSessionTicketKeys(&key_name[SESS_TICKET_KEY_NAME_PREFIX_LEN],
202 session_ticket_enc_key, session_ticket_mac_key))
203 return PR_FAILURE;
205 session_ticket_keys_initialized = PR_TRUE;
206 return PR_SUCCESS;
209 static SECStatus
210 ssl3_GetSessionTicketKeys(const unsigned char **aes_key,
211 PRUint32 *aes_key_length, const unsigned char **mac_key,
212 PRUint32 *mac_key_length)
214 if (PR_CallOnce(&generate_session_keys_once,
215 ssl3_GenerateSessionTicketKeys) != PR_SUCCESS)
216 return SECFailure;
218 if (!session_ticket_keys_initialized)
219 return SECFailure;
221 *aes_key = session_ticket_enc_key;
222 *aes_key_length = sizeof(session_ticket_enc_key);
223 *mac_key = session_ticket_mac_key;
224 *mac_key_length = sizeof(session_ticket_mac_key);
226 return SECSuccess;
228 #endif
230 /* Table of handlers for received TLS hello extensions, one per extension.
231 * In the second generation, this table will be dynamic, and functions
232 * will be registered here.
234 /* This table is used by the server, to handle client hello extensions. */
235 static const ssl3HelloExtensionHandler clientHelloHandlers[] = {
236 { ssl_server_name_xtn, &ssl3_HandleServerNameXtn },
237 #ifdef NSS_ENABLE_ECC
238 { ssl_elliptic_curves_xtn, &ssl3_HandleSupportedCurvesXtn },
239 { ssl_ec_point_formats_xtn, &ssl3_HandleSupportedPointFormatsXtn },
240 #endif
241 { ssl_session_ticket_xtn, &ssl3_ServerHandleSessionTicketXtn },
242 { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn },
243 { ssl_next_proto_nego_xtn, &ssl3_ServerHandleNextProtoNegoXtn },
244 { ssl_use_srtp_xtn, &ssl3_HandleUseSRTPXtn },
245 { ssl_cert_status_xtn, &ssl3_ServerHandleStatusRequestXtn },
246 { ssl_signature_algorithms_xtn, &ssl3_ServerHandleSigAlgsXtn },
247 { -1, NULL }
250 /* These two tables are used by the client, to handle server hello
251 * extensions. */
252 static const ssl3HelloExtensionHandler serverHelloHandlersTLS[] = {
253 { ssl_server_name_xtn, &ssl3_HandleServerNameXtn },
254 /* TODO: add a handler for ssl_ec_point_formats_xtn */
255 { ssl_session_ticket_xtn, &ssl3_ClientHandleSessionTicketXtn },
256 { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn },
257 { ssl_next_proto_nego_xtn, &ssl3_ClientHandleNextProtoNegoXtn },
258 { ssl_app_layer_protocol_xtn, &ssl3_ClientHandleAppProtoXtn },
259 { ssl_use_srtp_xtn, &ssl3_HandleUseSRTPXtn },
260 { ssl_channel_id_xtn, &ssl3_ClientHandleChannelIDXtn },
261 { ssl_cert_status_xtn, &ssl3_ClientHandleStatusRequestXtn },
262 { -1, NULL }
265 static const ssl3HelloExtensionHandler serverHelloHandlersSSL3[] = {
266 { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn },
267 { -1, NULL }
270 /* Tables of functions to format TLS hello extensions, one function per
271 * extension.
272 * These static tables are for the formatting of client hello extensions.
273 * The server's table of hello senders is dynamic, in the socket struct,
274 * and sender functions are registered there.
276 static const
277 ssl3HelloExtensionSender clientHelloSendersTLS[SSL_MAX_EXTENSIONS] = {
278 { ssl_server_name_xtn, &ssl3_SendServerNameXtn },
279 { ssl_renegotiation_info_xtn, &ssl3_SendRenegotiationInfoXtn },
280 #ifdef NSS_ENABLE_ECC
281 { ssl_elliptic_curves_xtn, &ssl3_SendSupportedCurvesXtn },
282 { ssl_ec_point_formats_xtn, &ssl3_SendSupportedPointFormatsXtn },
283 #endif
284 { ssl_session_ticket_xtn, &ssl3_SendSessionTicketXtn },
285 { ssl_next_proto_nego_xtn, &ssl3_ClientSendNextProtoNegoXtn },
286 { ssl_app_layer_protocol_xtn, &ssl3_ClientSendAppProtoXtn },
287 { ssl_use_srtp_xtn, &ssl3_SendUseSRTPXtn },
288 { ssl_channel_id_xtn, &ssl3_ClientSendChannelIDXtn },
289 { ssl_cert_status_xtn, &ssl3_ClientSendStatusRequestXtn },
290 { ssl_signature_algorithms_xtn, &ssl3_ClientSendSigAlgsXtn }
291 /* any extra entries will appear as { 0, NULL } */
294 static const
295 ssl3HelloExtensionSender clientHelloSendersSSL3[SSL_MAX_EXTENSIONS] = {
296 { ssl_renegotiation_info_xtn, &ssl3_SendRenegotiationInfoXtn }
297 /* any extra entries will appear as { 0, NULL } */
300 static PRBool
301 arrayContainsExtension(const PRUint16 *array, PRUint32 len, PRUint16 ex_type)
303 int i;
304 for (i = 0; i < len; i++) {
305 if (ex_type == array[i])
306 return PR_TRUE;
308 return PR_FALSE;
311 PRBool
312 ssl3_ExtensionNegotiated(sslSocket *ss, PRUint16 ex_type) {
313 TLSExtensionData *xtnData = &ss->xtnData;
314 return arrayContainsExtension(xtnData->negotiated,
315 xtnData->numNegotiated, ex_type);
318 static PRBool
319 ssl3_ClientExtensionAdvertised(sslSocket *ss, PRUint16 ex_type) {
320 TLSExtensionData *xtnData = &ss->xtnData;
321 return arrayContainsExtension(xtnData->advertised,
322 xtnData->numAdvertised, ex_type);
325 /* Format an SNI extension, using the name from the socket's URL,
326 * unless that name is a dotted decimal string.
327 * Used by client and server.
329 PRInt32
330 ssl3_SendServerNameXtn(sslSocket * ss, PRBool append,
331 PRUint32 maxBytes)
333 SECStatus rv;
334 if (!ss)
335 return 0;
336 if (!ss->sec.isServer) {
337 PRUint32 len;
338 PRNetAddr netAddr;
340 /* must have a hostname */
341 if (!ss->url || !ss->url[0])
342 return 0;
343 /* must not be an IPv4 or IPv6 address */
344 if (PR_SUCCESS == PR_StringToNetAddr(ss->url, &netAddr)) {
345 /* is an IP address (v4 or v6) */
346 return 0;
348 len = PORT_Strlen(ss->url);
349 if (append && maxBytes >= len + 9) {
350 /* extension_type */
351 rv = ssl3_AppendHandshakeNumber(ss, ssl_server_name_xtn, 2);
352 if (rv != SECSuccess) return -1;
353 /* length of extension_data */
354 rv = ssl3_AppendHandshakeNumber(ss, len + 5, 2);
355 if (rv != SECSuccess) return -1;
356 /* length of server_name_list */
357 rv = ssl3_AppendHandshakeNumber(ss, len + 3, 2);
358 if (rv != SECSuccess) return -1;
359 /* Name Type (sni_host_name) */
360 rv = ssl3_AppendHandshake(ss, "\0", 1);
361 if (rv != SECSuccess) return -1;
362 /* HostName (length and value) */
363 rv = ssl3_AppendHandshakeVariable(ss, (PRUint8 *)ss->url, len, 2);
364 if (rv != SECSuccess) return -1;
365 if (!ss->sec.isServer) {
366 TLSExtensionData *xtnData = &ss->xtnData;
367 xtnData->advertised[xtnData->numAdvertised++] =
368 ssl_server_name_xtn;
371 return len + 9;
373 /* Server side */
374 if (append && maxBytes >= 4) {
375 rv = ssl3_AppendHandshakeNumber(ss, ssl_server_name_xtn, 2);
376 if (rv != SECSuccess) return -1;
377 /* length of extension_data */
378 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
379 if (rv != SECSuccess) return -1;
381 return 4;
384 /* handle an incoming SNI extension, by ignoring it. */
385 SECStatus
386 ssl3_HandleServerNameXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data)
388 SECItem *names = NULL;
389 PRUint32 listCount = 0, namesPos = 0, i;
390 TLSExtensionData *xtnData = &ss->xtnData;
391 SECItem ldata;
392 PRInt32 listLenBytes = 0;
394 if (!ss->sec.isServer) {
395 /* Verify extension_data is empty. */
396 if (data->data || data->len ||
397 !ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) {
398 /* malformed or was not initiated by the client.*/
399 return SECFailure;
401 return SECSuccess;
404 /* Server side - consume client data and register server sender. */
405 /* do not parse the data if don't have user extension handling function. */
406 if (!ss->sniSocketConfig) {
407 return SECSuccess;
409 /* length of server_name_list */
410 listLenBytes = ssl3_ConsumeHandshakeNumber(ss, 2, &data->data, &data->len);
411 if (listLenBytes == 0 || listLenBytes != data->len) {
412 return SECFailure;
414 ldata = *data;
415 /* Calculate the size of the array.*/
416 while (listLenBytes > 0) {
417 SECItem litem;
418 SECStatus rv;
419 PRInt32 type;
420 /* Name Type (sni_host_name) */
421 type = ssl3_ConsumeHandshakeNumber(ss, 1, &ldata.data, &ldata.len);
422 if (!ldata.len) {
423 return SECFailure;
425 rv = ssl3_ConsumeHandshakeVariable(ss, &litem, 2, &ldata.data, &ldata.len);
426 if (rv != SECSuccess) {
427 return SECFailure;
429 /* Adjust total length for cunsumed item, item len and type.*/
430 listLenBytes -= litem.len + 3;
431 if (listLenBytes > 0 && !ldata.len) {
432 return SECFailure;
434 listCount += 1;
436 if (!listCount) {
437 return SECFailure;
439 names = PORT_ZNewArray(SECItem, listCount);
440 if (!names) {
441 return SECFailure;
443 for (i = 0;i < listCount;i++) {
444 int j;
445 PRInt32 type;
446 SECStatus rv;
447 PRBool nametypePresent = PR_FALSE;
448 /* Name Type (sni_host_name) */
449 type = ssl3_ConsumeHandshakeNumber(ss, 1, &data->data, &data->len);
450 /* Check if we have such type in the list */
451 for (j = 0;j < listCount && names[j].data;j++) {
452 if (names[j].type == type) {
453 nametypePresent = PR_TRUE;
454 break;
457 /* HostName (length and value) */
458 rv = ssl3_ConsumeHandshakeVariable(ss, &names[namesPos], 2,
459 &data->data, &data->len);
460 if (rv != SECSuccess) {
461 goto loser;
463 if (nametypePresent == PR_FALSE) {
464 namesPos += 1;
467 /* Free old and set the new data. */
468 if (xtnData->sniNameArr) {
469 PORT_Free(ss->xtnData.sniNameArr);
471 xtnData->sniNameArr = names;
472 xtnData->sniNameArrSize = namesPos;
473 xtnData->negotiated[xtnData->numNegotiated++] = ssl_server_name_xtn;
475 return SECSuccess;
477 loser:
478 PORT_Free(names);
479 return SECFailure;
482 /* Called by both clients and servers.
483 * Clients sends a filled in session ticket if one is available, and otherwise
484 * sends an empty ticket. Servers always send empty tickets.
486 PRInt32
487 ssl3_SendSessionTicketXtn(
488 sslSocket * ss,
489 PRBool append,
490 PRUint32 maxBytes)
492 PRInt32 extension_length;
493 NewSessionTicket *session_ticket = NULL;
495 /* Ignore the SessionTicket extension if processing is disabled. */
496 if (!ss->opt.enableSessionTickets)
497 return 0;
499 /* Empty extension length = extension_type (2-bytes) +
500 * length(extension_data) (2-bytes)
502 extension_length = 4;
504 /* If we are a client then send a session ticket if one is availble.
505 * Servers that support the extension and are willing to negotiate the
506 * the extension always respond with an empty extension.
508 if (!ss->sec.isServer) {
509 sslSessionID *sid = ss->sec.ci.sid;
510 session_ticket = &sid->u.ssl3.sessionTicket;
511 if (session_ticket->ticket.data) {
512 if (ss->xtnData.ticketTimestampVerified) {
513 extension_length += session_ticket->ticket.len;
514 } else if (!append &&
515 (session_ticket->ticket_lifetime_hint == 0 ||
516 (session_ticket->ticket_lifetime_hint +
517 session_ticket->received_timestamp > ssl_Time()))) {
518 extension_length += session_ticket->ticket.len;
519 ss->xtnData.ticketTimestampVerified = PR_TRUE;
524 if (append && maxBytes >= extension_length) {
525 SECStatus rv;
526 /* extension_type */
527 rv = ssl3_AppendHandshakeNumber(ss, ssl_session_ticket_xtn, 2);
528 if (rv != SECSuccess)
529 goto loser;
530 if (session_ticket && session_ticket->ticket.data &&
531 ss->xtnData.ticketTimestampVerified) {
532 rv = ssl3_AppendHandshakeVariable(ss, session_ticket->ticket.data,
533 session_ticket->ticket.len, 2);
534 ss->xtnData.ticketTimestampVerified = PR_FALSE;
535 } else {
536 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
538 if (rv != SECSuccess)
539 goto loser;
541 if (!ss->sec.isServer) {
542 TLSExtensionData *xtnData = &ss->xtnData;
543 xtnData->advertised[xtnData->numAdvertised++] =
544 ssl_session_ticket_xtn;
546 } else if (maxBytes < extension_length) {
547 PORT_Assert(0);
548 return 0;
550 return extension_length;
552 loser:
553 ss->xtnData.ticketTimestampVerified = PR_FALSE;
554 return -1;
557 /* handle an incoming Next Protocol Negotiation extension. */
558 static SECStatus
559 ssl3_ServerHandleNextProtoNegoXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data)
561 if (ss->firstHsDone || data->len != 0) {
562 /* Clients MUST send an empty NPN extension, if any. */
563 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
564 return SECFailure;
567 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
569 /* TODO: server side NPN support would require calling
570 * ssl3_RegisterServerHelloExtensionSender here in order to echo the
571 * extension back to the client. */
573 return SECSuccess;
576 /* ssl3_ValidateNextProtoNego checks that the given block of data is valid: none
577 * of the lengths may be 0 and the sum of the lengths must equal the length of
578 * the block. */
579 SECStatus
580 ssl3_ValidateNextProtoNego(const unsigned char* data, unsigned int length)
582 unsigned int offset = 0;
584 while (offset < length) {
585 unsigned int newOffset = offset + 1 + (unsigned int) data[offset];
586 /* Reject embedded nulls to protect against buggy applications that
587 * store protocol identifiers in null-terminated strings.
589 if (newOffset > length || data[offset] == 0) {
590 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
591 return SECFailure;
593 offset = newOffset;
596 if (offset > length) {
597 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
598 return SECFailure;
601 return SECSuccess;
604 static SECStatus
605 ssl3_ClientHandleNextProtoNegoXtn(sslSocket *ss, PRUint16 ex_type,
606 SECItem *data)
608 SECStatus rv;
609 unsigned char resultBuffer[255];
610 SECItem result = { siBuffer, resultBuffer, 0 };
612 PORT_Assert(!ss->firstHsDone);
614 if (ssl3_ExtensionNegotiated(ss, ssl_app_layer_protocol_xtn)) {
615 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
616 return SECFailure;
619 rv = ssl3_ValidateNextProtoNego(data->data, data->len);
620 if (rv != SECSuccess)
621 return rv;
623 /* ss->nextProtoCallback cannot normally be NULL if we negotiated the
624 * extension. However, It is possible that an application erroneously
625 * cleared the callback between the time we sent the ClientHello and now.
627 PORT_Assert(ss->nextProtoCallback != NULL);
628 if (!ss->nextProtoCallback) {
629 /* XXX Use a better error code. This is an application error, not an
630 * NSS bug. */
631 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
632 return SECFailure;
635 rv = ss->nextProtoCallback(ss->nextProtoArg, ss->fd, data->data, data->len,
636 result.data, &result.len, sizeof resultBuffer);
637 if (rv != SECSuccess)
638 return rv;
639 /* If the callback wrote more than allowed to |result| it has corrupted our
640 * stack. */
641 if (result.len > sizeof resultBuffer) {
642 PORT_SetError(SEC_ERROR_OUTPUT_LEN);
643 return SECFailure;
646 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
648 SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE);
649 return SECITEM_CopyItem(NULL, &ss->ssl3.nextProto, &result);
652 static SECStatus
653 ssl3_ClientHandleAppProtoXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data)
655 const unsigned char* d = data->data;
656 PRUint16 name_list_len;
657 SECItem protocol_name;
659 if (ssl3_ExtensionNegotiated(ss, ssl_next_proto_nego_xtn)) {
660 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
661 return SECFailure;
664 /* The extension data from the server has the following format:
665 * uint16 name_list_len;
666 * uint8 len;
667 * uint8 protocol_name[len]; */
668 if (data->len < 4 || data->len > 2 + 1 + 255) {
669 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
670 return SECFailure;
673 name_list_len = ((PRUint16) d[0]) << 8 |
674 ((PRUint16) d[1]);
675 if (name_list_len != data->len - 2 ||
676 d[2] != data->len - 3) {
677 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
678 return SECFailure;
681 protocol_name.data = data->data + 3;
682 protocol_name.len = data->len - 3;
684 SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE);
685 ss->ssl3.nextProtoState = SSL_NEXT_PROTO_SELECTED;
686 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
687 return SECITEM_CopyItem(NULL, &ss->ssl3.nextProto, &protocol_name);
690 static PRInt32
691 ssl3_ClientSendNextProtoNegoXtn(sslSocket * ss, PRBool append,
692 PRUint32 maxBytes)
694 PRInt32 extension_length;
696 /* Renegotiations do not send this extension. */
697 if (!ss->nextProtoCallback || ss->firstHsDone) {
698 return 0;
701 extension_length = 4;
703 if (append && maxBytes >= extension_length) {
704 SECStatus rv;
705 rv = ssl3_AppendHandshakeNumber(ss, ssl_next_proto_nego_xtn, 2);
706 if (rv != SECSuccess)
707 goto loser;
708 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
709 if (rv != SECSuccess)
710 goto loser;
711 ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
712 ssl_next_proto_nego_xtn;
713 } else if (maxBytes < extension_length) {
714 return 0;
717 return extension_length;
719 loser:
720 return -1;
723 static PRInt32
724 ssl3_ClientSendAppProtoXtn(sslSocket * ss, PRBool append, PRUint32 maxBytes)
726 PRInt32 extension_length;
727 unsigned char *alpn_protos = NULL;
729 /* Renegotiations do not send this extension. */
730 if (!ss->opt.nextProtoNego.data || ss->firstHsDone) {
731 return 0;
734 extension_length = 2 /* extension type */ + 2 /* extension length */ +
735 2 /* protocol name list length */ +
736 ss->opt.nextProtoNego.len;
738 if (append && maxBytes >= extension_length) {
739 /* NPN requires that the client's fallback protocol is first in the
740 * list. However, ALPN sends protocols in preference order. So we
741 * allocate a buffer and move the first protocol to the end of the
742 * list. */
743 SECStatus rv;
744 const unsigned int len = ss->opt.nextProtoNego.len;
746 alpn_protos = PORT_Alloc(len);
747 if (alpn_protos == NULL) {
748 return SECFailure;
750 if (len > 0) {
751 /* Each protocol string is prefixed with a single byte length. */
752 unsigned int i = ss->opt.nextProtoNego.data[0] + 1;
753 if (i <= len) {
754 memcpy(alpn_protos, &ss->opt.nextProtoNego.data[i], len - i);
755 memcpy(alpn_protos + len - i, ss->opt.nextProtoNego.data, i);
756 } else {
757 /* This seems to be invalid data so we'll send as-is. */
758 memcpy(alpn_protos, ss->opt.nextProtoNego.data, len);
762 rv = ssl3_AppendHandshakeNumber(ss, ssl_app_layer_protocol_xtn, 2);
763 if (rv != SECSuccess)
764 goto loser;
765 rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2);
766 if (rv != SECSuccess)
767 goto loser;
768 rv = ssl3_AppendHandshakeVariable(ss, alpn_protos, len, 2);
769 PORT_Free(alpn_protos);
770 alpn_protos = NULL;
771 if (rv != SECSuccess)
772 goto loser;
773 ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
774 ssl_app_layer_protocol_xtn;
775 } else if (maxBytes < extension_length) {
776 return 0;
779 return extension_length;
781 loser:
782 if (alpn_protos)
783 PORT_Free(alpn_protos);
784 return -1;
787 static SECStatus
788 ssl3_ClientHandleChannelIDXtn(sslSocket *ss, PRUint16 ex_type,
789 SECItem *data)
791 PORT_Assert(ss->getChannelID != NULL);
793 if (data->len) {
794 PORT_SetError(SSL_ERROR_BAD_CHANNEL_ID_DATA);
795 return SECFailure;
797 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
798 return SECSuccess;
801 static PRInt32
802 ssl3_ClientSendChannelIDXtn(sslSocket * ss, PRBool append,
803 PRUint32 maxBytes)
805 PRInt32 extension_length = 4;
807 if (!ss->getChannelID)
808 return 0;
810 if (maxBytes < extension_length) {
811 PORT_Assert(0);
812 return 0;
815 if (append) {
816 SECStatus rv;
817 rv = ssl3_AppendHandshakeNumber(ss, ssl_channel_id_xtn, 2);
818 if (rv != SECSuccess)
819 goto loser;
820 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
821 if (rv != SECSuccess)
822 goto loser;
823 ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
824 ssl_channel_id_xtn;
827 return extension_length;
829 loser:
830 return -1;
833 static SECStatus
834 ssl3_ClientHandleStatusRequestXtn(sslSocket *ss, PRUint16 ex_type,
835 SECItem *data)
837 /* The echoed extension must be empty. */
838 if (data->len != 0)
839 return SECFailure;
841 /* Keep track of negotiated extensions. */
842 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
844 return SECSuccess;
847 static PRInt32
848 ssl3_ServerSendStatusRequestXtn(
849 sslSocket * ss,
850 PRBool append,
851 PRUint32 maxBytes)
853 PRInt32 extension_length;
854 SECStatus rv;
855 int i;
856 PRBool haveStatus = PR_FALSE;
858 for (i = kt_null; i < kt_kea_size; i++) {
859 /* TODO: This is a temporary workaround.
860 * The correct code needs to see if we have an OCSP response for
861 * the server certificate being used, rather than if we have any
862 * OCSP response. See also ssl3_SendCertificateStatus.
864 if (ss->certStatusArray[i] && ss->certStatusArray[i]->len) {
865 haveStatus = PR_TRUE;
866 break;
869 if (!haveStatus)
870 return 0;
872 extension_length = 2 + 2;
873 if (append && maxBytes >= extension_length) {
874 /* extension_type */
875 rv = ssl3_AppendHandshakeNumber(ss, ssl_cert_status_xtn, 2);
876 if (rv != SECSuccess)
877 return -1;
878 /* length of extension_data */
879 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
880 if (rv != SECSuccess)
881 return -1;
884 return extension_length;
887 /* ssl3_ClientSendStatusRequestXtn builds the status_request extension on the
888 * client side. See RFC 4366 section 3.6. */
889 static PRInt32
890 ssl3_ClientSendStatusRequestXtn(sslSocket * ss, PRBool append,
891 PRUint32 maxBytes)
893 PRInt32 extension_length;
895 if (!ss->opt.enableOCSPStapling)
896 return 0;
898 /* extension_type (2-bytes) +
899 * length(extension_data) (2-bytes) +
900 * status_type (1) +
901 * responder_id_list length (2) +
902 * request_extensions length (2)
904 extension_length = 9;
906 if (append && maxBytes >= extension_length) {
907 SECStatus rv;
908 TLSExtensionData *xtnData;
910 /* extension_type */
911 rv = ssl3_AppendHandshakeNumber(ss, ssl_cert_status_xtn, 2);
912 if (rv != SECSuccess)
913 return -1;
914 rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2);
915 if (rv != SECSuccess)
916 return -1;
917 rv = ssl3_AppendHandshakeNumber(ss, 1 /* status_type ocsp */, 1);
918 if (rv != SECSuccess)
919 return -1;
920 /* A zero length responder_id_list means that the responders are
921 * implicitly known to the server. */
922 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
923 if (rv != SECSuccess)
924 return -1;
925 /* A zero length request_extensions means that there are no extensions.
926 * Specifically, we don't set the id-pkix-ocsp-nonce extension. This
927 * means that the server can replay a cached OCSP response to us. */
928 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
929 if (rv != SECSuccess)
930 return -1;
932 xtnData = &ss->xtnData;
933 xtnData->advertised[xtnData->numAdvertised++] = ssl_cert_status_xtn;
934 } else if (maxBytes < extension_length) {
935 PORT_Assert(0);
936 return 0;
938 return extension_length;
942 * NewSessionTicket
943 * Called from ssl3_HandleFinished
945 SECStatus
946 ssl3_SendNewSessionTicket(sslSocket *ss)
948 int i;
949 SECStatus rv;
950 NewSessionTicket ticket;
951 SECItem plaintext;
952 SECItem plaintext_item = {0, NULL, 0};
953 SECItem ciphertext = {0, NULL, 0};
954 PRUint32 ciphertext_length;
955 PRBool ms_is_wrapped;
956 unsigned char wrapped_ms[SSL3_MASTER_SECRET_LENGTH];
957 SECItem ms_item = {0, NULL, 0};
958 SSL3KEAType effectiveExchKeyType = ssl_kea_null;
959 PRUint32 padding_length;
960 PRUint32 message_length;
961 PRUint32 cert_length;
962 PRUint8 length_buf[4];
963 PRUint32 now;
964 PK11SymKey *aes_key_pkcs11;
965 PK11SymKey *mac_key_pkcs11;
966 #ifndef NO_PKCS11_BYPASS
967 const unsigned char *aes_key;
968 const unsigned char *mac_key;
969 PRUint32 aes_key_length;
970 PRUint32 mac_key_length;
971 PRUint64 aes_ctx_buf[MAX_CIPHER_CONTEXT_LLONGS];
972 AESContext *aes_ctx;
973 const SECHashObject *hashObj = NULL;
974 PRUint64 hmac_ctx_buf[MAX_MAC_CONTEXT_LLONGS];
975 HMACContext *hmac_ctx;
976 #endif
977 CK_MECHANISM_TYPE cipherMech = CKM_AES_CBC;
978 PK11Context *aes_ctx_pkcs11;
979 CK_MECHANISM_TYPE macMech = CKM_SHA256_HMAC;
980 PK11Context *hmac_ctx_pkcs11;
981 unsigned char computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH];
982 unsigned int computed_mac_length;
983 unsigned char iv[AES_BLOCK_SIZE];
984 SECItem ivItem;
985 SECItem *srvName = NULL;
986 PRUint32 srvNameLen = 0;
987 CK_MECHANISM_TYPE msWrapMech = 0; /* dummy default value,
988 * must be >= 0 */
990 SSL_TRC(3, ("%d: SSL3[%d]: send session_ticket handshake",
991 SSL_GETPID(), ss->fd));
993 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
994 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
996 ticket.ticket_lifetime_hint = TLS_EX_SESS_TICKET_LIFETIME_HINT;
997 cert_length = (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) ?
998 3 + ss->sec.ci.sid->peerCert->derCert.len : 0;
1000 /* Get IV and encryption keys */
1001 ivItem.data = iv;
1002 ivItem.len = sizeof(iv);
1003 rv = PK11_GenerateRandom(iv, sizeof(iv));
1004 if (rv != SECSuccess) goto loser;
1006 #ifndef NO_PKCS11_BYPASS
1007 if (ss->opt.bypassPKCS11) {
1008 rv = ssl3_GetSessionTicketKeys(&aes_key, &aes_key_length,
1009 &mac_key, &mac_key_length);
1010 } else
1011 #endif
1013 rv = ssl3_GetSessionTicketKeysPKCS11(ss, &aes_key_pkcs11,
1014 &mac_key_pkcs11);
1016 if (rv != SECSuccess) goto loser;
1018 if (ss->ssl3.pwSpec->msItem.len && ss->ssl3.pwSpec->msItem.data) {
1019 /* The master secret is available unwrapped. */
1020 ms_item.data = ss->ssl3.pwSpec->msItem.data;
1021 ms_item.len = ss->ssl3.pwSpec->msItem.len;
1022 ms_is_wrapped = PR_FALSE;
1023 } else {
1024 /* Extract the master secret wrapped. */
1025 sslSessionID sid;
1026 PORT_Memset(&sid, 0, sizeof(sslSessionID));
1028 if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) {
1029 effectiveExchKeyType = kt_rsa;
1030 } else {
1031 effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType;
1034 rv = ssl3_CacheWrappedMasterSecret(ss, &sid, ss->ssl3.pwSpec,
1035 effectiveExchKeyType);
1036 if (rv == SECSuccess) {
1037 if (sid.u.ssl3.keys.wrapped_master_secret_len > sizeof(wrapped_ms))
1038 goto loser;
1039 memcpy(wrapped_ms, sid.u.ssl3.keys.wrapped_master_secret,
1040 sid.u.ssl3.keys.wrapped_master_secret_len);
1041 ms_item.data = wrapped_ms;
1042 ms_item.len = sid.u.ssl3.keys.wrapped_master_secret_len;
1043 msWrapMech = sid.u.ssl3.masterWrapMech;
1044 } else {
1045 /* TODO: else send an empty ticket. */
1046 goto loser;
1048 ms_is_wrapped = PR_TRUE;
1050 /* Prep to send negotiated name */
1051 srvName = &ss->ssl3.pwSpec->srvVirtName;
1052 if (srvName->data && srvName->len) {
1053 srvNameLen = 2 + srvName->len; /* len bytes + name len */
1056 ciphertext_length =
1057 sizeof(PRUint16) /* ticket_version */
1058 + sizeof(SSL3ProtocolVersion) /* ssl_version */
1059 + sizeof(ssl3CipherSuite) /* ciphersuite */
1060 + 1 /* compression */
1061 + 10 /* cipher spec parameters */
1062 + 1 /* SessionTicket.ms_is_wrapped */
1063 + 1 /* effectiveExchKeyType */
1064 + 4 /* msWrapMech */
1065 + 2 /* master_secret.length */
1066 + ms_item.len /* master_secret */
1067 + 1 /* client_auth_type */
1068 + cert_length /* cert */
1069 + 1 /* server name type */
1070 + srvNameLen /* name len + length field */
1071 + sizeof(ticket.ticket_lifetime_hint);
1072 padding_length = AES_BLOCK_SIZE -
1073 (ciphertext_length % AES_BLOCK_SIZE);
1074 ciphertext_length += padding_length;
1076 message_length =
1077 sizeof(ticket.ticket_lifetime_hint) /* ticket_lifetime_hint */
1078 + 2 /* length field for NewSessionTicket.ticket */
1079 + SESS_TICKET_KEY_NAME_LEN /* key_name */
1080 + AES_BLOCK_SIZE /* iv */
1081 + 2 /* length field for NewSessionTicket.ticket.encrypted_state */
1082 + ciphertext_length /* encrypted_state */
1083 + TLS_EX_SESS_TICKET_MAC_LENGTH; /* mac */
1085 if (SECITEM_AllocItem(NULL, &plaintext_item, ciphertext_length) == NULL)
1086 goto loser;
1088 plaintext = plaintext_item;
1090 /* ticket_version */
1091 rv = ssl3_AppendNumberToItem(&plaintext, TLS_EX_SESS_TICKET_VERSION,
1092 sizeof(PRUint16));
1093 if (rv != SECSuccess) goto loser;
1095 /* ssl_version */
1096 rv = ssl3_AppendNumberToItem(&plaintext, ss->version,
1097 sizeof(SSL3ProtocolVersion));
1098 if (rv != SECSuccess) goto loser;
1100 /* ciphersuite */
1101 rv = ssl3_AppendNumberToItem(&plaintext, ss->ssl3.hs.cipher_suite,
1102 sizeof(ssl3CipherSuite));
1103 if (rv != SECSuccess) goto loser;
1105 /* compression */
1106 rv = ssl3_AppendNumberToItem(&plaintext, ss->ssl3.hs.compression, 1);
1107 if (rv != SECSuccess) goto loser;
1109 /* cipher spec parameters */
1110 rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.authAlgorithm, 1);
1111 if (rv != SECSuccess) goto loser;
1112 rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.authKeyBits, 4);
1113 if (rv != SECSuccess) goto loser;
1114 rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.keaType, 1);
1115 if (rv != SECSuccess) goto loser;
1116 rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.keaKeyBits, 4);
1117 if (rv != SECSuccess) goto loser;
1119 /* master_secret */
1120 rv = ssl3_AppendNumberToItem(&plaintext, ms_is_wrapped, 1);
1121 if (rv != SECSuccess) goto loser;
1122 rv = ssl3_AppendNumberToItem(&plaintext, effectiveExchKeyType, 1);
1123 if (rv != SECSuccess) goto loser;
1124 rv = ssl3_AppendNumberToItem(&plaintext, msWrapMech, 4);
1125 if (rv != SECSuccess) goto loser;
1126 rv = ssl3_AppendNumberToItem(&plaintext, ms_item.len, 2);
1127 if (rv != SECSuccess) goto loser;
1128 rv = ssl3_AppendToItem(&plaintext, ms_item.data, ms_item.len);
1129 if (rv != SECSuccess) goto loser;
1131 /* client_identity */
1132 if (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) {
1133 rv = ssl3_AppendNumberToItem(&plaintext, CLIENT_AUTH_CERTIFICATE, 1);
1134 if (rv != SECSuccess) goto loser;
1135 rv = ssl3_AppendNumberToItem(&plaintext,
1136 ss->sec.ci.sid->peerCert->derCert.len, 3);
1137 if (rv != SECSuccess) goto loser;
1138 rv = ssl3_AppendToItem(&plaintext,
1139 ss->sec.ci.sid->peerCert->derCert.data,
1140 ss->sec.ci.sid->peerCert->derCert.len);
1141 if (rv != SECSuccess) goto loser;
1142 } else {
1143 rv = ssl3_AppendNumberToItem(&plaintext, 0, 1);
1144 if (rv != SECSuccess) goto loser;
1147 /* timestamp */
1148 now = ssl_Time();
1149 rv = ssl3_AppendNumberToItem(&plaintext, now,
1150 sizeof(ticket.ticket_lifetime_hint));
1151 if (rv != SECSuccess) goto loser;
1153 if (srvNameLen) {
1154 /* Name Type (sni_host_name) */
1155 rv = ssl3_AppendNumberToItem(&plaintext, srvName->type, 1);
1156 if (rv != SECSuccess) goto loser;
1157 /* HostName (length and value) */
1158 rv = ssl3_AppendNumberToItem(&plaintext, srvName->len, 2);
1159 if (rv != SECSuccess) goto loser;
1160 rv = ssl3_AppendToItem(&plaintext, srvName->data, srvName->len);
1161 if (rv != SECSuccess) goto loser;
1162 } else {
1163 /* No Name */
1164 rv = ssl3_AppendNumberToItem(&plaintext, (char)TLS_STE_NO_SERVER_NAME,
1166 if (rv != SECSuccess) goto loser;
1169 PORT_Assert(plaintext.len == padding_length);
1170 for (i = 0; i < padding_length; i++)
1171 plaintext.data[i] = (unsigned char)padding_length;
1173 if (SECITEM_AllocItem(NULL, &ciphertext, ciphertext_length) == NULL) {
1174 rv = SECFailure;
1175 goto loser;
1178 /* Generate encrypted portion of ticket. */
1179 #ifndef NO_PKCS11_BYPASS
1180 if (ss->opt.bypassPKCS11) {
1181 aes_ctx = (AESContext *)aes_ctx_buf;
1182 rv = AES_InitContext(aes_ctx, aes_key, aes_key_length, iv,
1183 NSS_AES_CBC, 1, AES_BLOCK_SIZE);
1184 if (rv != SECSuccess) goto loser;
1186 rv = AES_Encrypt(aes_ctx, ciphertext.data, &ciphertext.len,
1187 ciphertext.len, plaintext_item.data,
1188 plaintext_item.len);
1189 if (rv != SECSuccess) goto loser;
1190 } else
1191 #endif
1193 aes_ctx_pkcs11 = PK11_CreateContextBySymKey(cipherMech,
1194 CKA_ENCRYPT, aes_key_pkcs11, &ivItem);
1195 if (!aes_ctx_pkcs11)
1196 goto loser;
1198 rv = PK11_CipherOp(aes_ctx_pkcs11, ciphertext.data,
1199 (int *)&ciphertext.len, ciphertext.len,
1200 plaintext_item.data, plaintext_item.len);
1201 PK11_Finalize(aes_ctx_pkcs11);
1202 PK11_DestroyContext(aes_ctx_pkcs11, PR_TRUE);
1203 if (rv != SECSuccess) goto loser;
1206 /* Convert ciphertext length to network order. */
1207 length_buf[0] = (ciphertext.len >> 8) & 0xff;
1208 length_buf[1] = (ciphertext.len ) & 0xff;
1210 /* Compute MAC. */
1211 #ifndef NO_PKCS11_BYPASS
1212 if (ss->opt.bypassPKCS11) {
1213 hmac_ctx = (HMACContext *)hmac_ctx_buf;
1214 hashObj = HASH_GetRawHashObject(HASH_AlgSHA256);
1215 if (HMAC_Init(hmac_ctx, hashObj, mac_key,
1216 mac_key_length, PR_FALSE) != SECSuccess)
1217 goto loser;
1219 HMAC_Begin(hmac_ctx);
1220 HMAC_Update(hmac_ctx, key_name, SESS_TICKET_KEY_NAME_LEN);
1221 HMAC_Update(hmac_ctx, iv, sizeof(iv));
1222 HMAC_Update(hmac_ctx, (unsigned char *)length_buf, 2);
1223 HMAC_Update(hmac_ctx, ciphertext.data, ciphertext.len);
1224 HMAC_Finish(hmac_ctx, computed_mac, &computed_mac_length,
1225 sizeof(computed_mac));
1226 } else
1227 #endif
1229 SECItem macParam;
1230 macParam.data = NULL;
1231 macParam.len = 0;
1232 hmac_ctx_pkcs11 = PK11_CreateContextBySymKey(macMech,
1233 CKA_SIGN, mac_key_pkcs11, &macParam);
1234 if (!hmac_ctx_pkcs11)
1235 goto loser;
1237 rv = PK11_DigestBegin(hmac_ctx_pkcs11);
1238 rv = PK11_DigestOp(hmac_ctx_pkcs11, key_name,
1239 SESS_TICKET_KEY_NAME_LEN);
1240 rv = PK11_DigestOp(hmac_ctx_pkcs11, iv, sizeof(iv));
1241 rv = PK11_DigestOp(hmac_ctx_pkcs11, (unsigned char *)length_buf, 2);
1242 rv = PK11_DigestOp(hmac_ctx_pkcs11, ciphertext.data, ciphertext.len);
1243 rv = PK11_DigestFinal(hmac_ctx_pkcs11, computed_mac,
1244 &computed_mac_length, sizeof(computed_mac));
1245 PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE);
1246 if (rv != SECSuccess) goto loser;
1249 /* Serialize the handshake message. */
1250 rv = ssl3_AppendHandshakeHeader(ss, new_session_ticket, message_length);
1251 if (rv != SECSuccess) goto loser;
1253 rv = ssl3_AppendHandshakeNumber(ss, ticket.ticket_lifetime_hint,
1254 sizeof(ticket.ticket_lifetime_hint));
1255 if (rv != SECSuccess) goto loser;
1257 rv = ssl3_AppendHandshakeNumber(ss,
1258 message_length - sizeof(ticket.ticket_lifetime_hint) - 2, 2);
1259 if (rv != SECSuccess) goto loser;
1261 rv = ssl3_AppendHandshake(ss, key_name, SESS_TICKET_KEY_NAME_LEN);
1262 if (rv != SECSuccess) goto loser;
1264 rv = ssl3_AppendHandshake(ss, iv, sizeof(iv));
1265 if (rv != SECSuccess) goto loser;
1267 rv = ssl3_AppendHandshakeVariable(ss, ciphertext.data, ciphertext.len, 2);
1268 if (rv != SECSuccess) goto loser;
1270 rv = ssl3_AppendHandshake(ss, computed_mac, computed_mac_length);
1271 if (rv != SECSuccess) goto loser;
1273 loser:
1274 if (plaintext_item.data)
1275 SECITEM_FreeItem(&plaintext_item, PR_FALSE);
1276 if (ciphertext.data)
1277 SECITEM_FreeItem(&ciphertext, PR_FALSE);
1279 return rv;
1282 /* When a client receives a SessionTicket extension a NewSessionTicket
1283 * message is expected during the handshake.
1285 SECStatus
1286 ssl3_ClientHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type,
1287 SECItem *data)
1289 if (data->len != 0)
1290 return SECFailure;
1292 /* Keep track of negotiated extensions. */
1293 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
1294 return SECSuccess;
1297 SECStatus
1298 ssl3_ServerHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type,
1299 SECItem *data)
1301 SECStatus rv;
1302 SECItem *decrypted_state = NULL;
1303 SessionTicket *parsed_session_ticket = NULL;
1304 sslSessionID *sid = NULL;
1305 SSL3Statistics *ssl3stats;
1307 /* Ignore the SessionTicket extension if processing is disabled. */
1308 if (!ss->opt.enableSessionTickets)
1309 return SECSuccess;
1311 /* Keep track of negotiated extensions. */
1312 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
1314 /* Parse the received ticket sent in by the client. We are
1315 * lenient about some parse errors, falling back to a fullshake
1316 * instead of terminating the current connection.
1318 if (data->len == 0) {
1319 ss->xtnData.emptySessionTicket = PR_TRUE;
1320 } else {
1321 int i;
1322 SECItem extension_data;
1323 EncryptedSessionTicket enc_session_ticket;
1324 unsigned char computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH];
1325 unsigned int computed_mac_length;
1326 #ifndef NO_PKCS11_BYPASS
1327 const SECHashObject *hashObj;
1328 const unsigned char *aes_key;
1329 const unsigned char *mac_key;
1330 PRUint32 aes_key_length;
1331 PRUint32 mac_key_length;
1332 PRUint64 hmac_ctx_buf[MAX_MAC_CONTEXT_LLONGS];
1333 HMACContext *hmac_ctx;
1334 PRUint64 aes_ctx_buf[MAX_CIPHER_CONTEXT_LLONGS];
1335 AESContext *aes_ctx;
1336 #endif
1337 PK11SymKey *aes_key_pkcs11;
1338 PK11SymKey *mac_key_pkcs11;
1339 PK11Context *hmac_ctx_pkcs11;
1340 CK_MECHANISM_TYPE macMech = CKM_SHA256_HMAC;
1341 PK11Context *aes_ctx_pkcs11;
1342 CK_MECHANISM_TYPE cipherMech = CKM_AES_CBC;
1343 unsigned char * padding;
1344 PRUint32 padding_length;
1345 unsigned char *buffer;
1346 unsigned int buffer_len;
1347 PRInt32 temp;
1348 SECItem cert_item;
1349 PRInt8 nameType = TLS_STE_NO_SERVER_NAME;
1351 /* Turn off stateless session resumption if the client sends a
1352 * SessionTicket extension, even if the extension turns out to be
1353 * malformed (ss->sec.ci.sid is non-NULL when doing session
1354 * renegotiation.)
1356 if (ss->sec.ci.sid != NULL) {
1357 if (ss->sec.uncache)
1358 ss->sec.uncache(ss->sec.ci.sid);
1359 ssl_FreeSID(ss->sec.ci.sid);
1360 ss->sec.ci.sid = NULL;
1363 extension_data.data = data->data; /* Keep a copy for future use. */
1364 extension_data.len = data->len;
1366 if (ssl3_ParseEncryptedSessionTicket(ss, data, &enc_session_ticket)
1367 != SECSuccess)
1368 return SECFailure;
1370 /* Get session ticket keys. */
1371 #ifndef NO_PKCS11_BYPASS
1372 if (ss->opt.bypassPKCS11) {
1373 rv = ssl3_GetSessionTicketKeys(&aes_key, &aes_key_length,
1374 &mac_key, &mac_key_length);
1375 } else
1376 #endif
1378 rv = ssl3_GetSessionTicketKeysPKCS11(ss, &aes_key_pkcs11,
1379 &mac_key_pkcs11);
1381 if (rv != SECSuccess) {
1382 SSL_DBG(("%d: SSL[%d]: Unable to get/generate session ticket keys.",
1383 SSL_GETPID(), ss->fd));
1384 goto loser;
1387 /* If the ticket sent by the client was generated under a key different
1388 * from the one we have, bypass ticket processing.
1390 if (PORT_Memcmp(enc_session_ticket.key_name, key_name,
1391 SESS_TICKET_KEY_NAME_LEN) != 0) {
1392 SSL_DBG(("%d: SSL[%d]: Session ticket key_name sent mismatch.",
1393 SSL_GETPID(), ss->fd));
1394 goto no_ticket;
1397 /* Verify the MAC on the ticket. MAC verification may also
1398 * fail if the MAC key has been recently refreshed.
1400 #ifndef NO_PKCS11_BYPASS
1401 if (ss->opt.bypassPKCS11) {
1402 hmac_ctx = (HMACContext *)hmac_ctx_buf;
1403 hashObj = HASH_GetRawHashObject(HASH_AlgSHA256);
1404 if (HMAC_Init(hmac_ctx, hashObj, mac_key,
1405 sizeof(session_ticket_mac_key), PR_FALSE) != SECSuccess)
1406 goto no_ticket;
1407 HMAC_Begin(hmac_ctx);
1408 HMAC_Update(hmac_ctx, extension_data.data,
1409 extension_data.len - TLS_EX_SESS_TICKET_MAC_LENGTH);
1410 if (HMAC_Finish(hmac_ctx, computed_mac, &computed_mac_length,
1411 sizeof(computed_mac)) != SECSuccess)
1412 goto no_ticket;
1413 } else
1414 #endif
1416 SECItem macParam;
1417 macParam.data = NULL;
1418 macParam.len = 0;
1419 hmac_ctx_pkcs11 = PK11_CreateContextBySymKey(macMech,
1420 CKA_SIGN, mac_key_pkcs11, &macParam);
1421 if (!hmac_ctx_pkcs11) {
1422 SSL_DBG(("%d: SSL[%d]: Unable to create HMAC context: %d.",
1423 SSL_GETPID(), ss->fd, PORT_GetError()));
1424 goto no_ticket;
1425 } else {
1426 SSL_DBG(("%d: SSL[%d]: Successfully created HMAC context.",
1427 SSL_GETPID(), ss->fd));
1429 rv = PK11_DigestBegin(hmac_ctx_pkcs11);
1430 rv = PK11_DigestOp(hmac_ctx_pkcs11, extension_data.data,
1431 extension_data.len - TLS_EX_SESS_TICKET_MAC_LENGTH);
1432 if (rv != SECSuccess) {
1433 PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE);
1434 goto no_ticket;
1436 rv = PK11_DigestFinal(hmac_ctx_pkcs11, computed_mac,
1437 &computed_mac_length, sizeof(computed_mac));
1438 PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE);
1439 if (rv != SECSuccess)
1440 goto no_ticket;
1442 if (NSS_SecureMemcmp(computed_mac, enc_session_ticket.mac,
1443 computed_mac_length) != 0) {
1444 SSL_DBG(("%d: SSL[%d]: Session ticket MAC mismatch.",
1445 SSL_GETPID(), ss->fd));
1446 goto no_ticket;
1449 /* We ignore key_name for now.
1450 * This is ok as MAC verification succeeded.
1453 /* Decrypt the ticket. */
1455 /* Plaintext is shorter than the ciphertext due to padding. */
1456 decrypted_state = SECITEM_AllocItem(NULL, NULL,
1457 enc_session_ticket.encrypted_state.len);
1459 #ifndef NO_PKCS11_BYPASS
1460 if (ss->opt.bypassPKCS11) {
1461 aes_ctx = (AESContext *)aes_ctx_buf;
1462 rv = AES_InitContext(aes_ctx, aes_key,
1463 sizeof(session_ticket_enc_key), enc_session_ticket.iv,
1464 NSS_AES_CBC, 0,AES_BLOCK_SIZE);
1465 if (rv != SECSuccess) {
1466 SSL_DBG(("%d: SSL[%d]: Unable to create AES context.",
1467 SSL_GETPID(), ss->fd));
1468 goto no_ticket;
1471 rv = AES_Decrypt(aes_ctx, decrypted_state->data,
1472 &decrypted_state->len, decrypted_state->len,
1473 enc_session_ticket.encrypted_state.data,
1474 enc_session_ticket.encrypted_state.len);
1475 if (rv != SECSuccess)
1476 goto no_ticket;
1477 } else
1478 #endif
1480 SECItem ivItem;
1481 ivItem.data = enc_session_ticket.iv;
1482 ivItem.len = AES_BLOCK_SIZE;
1483 aes_ctx_pkcs11 = PK11_CreateContextBySymKey(cipherMech,
1484 CKA_DECRYPT, aes_key_pkcs11, &ivItem);
1485 if (!aes_ctx_pkcs11) {
1486 SSL_DBG(("%d: SSL[%d]: Unable to create AES context.",
1487 SSL_GETPID(), ss->fd));
1488 goto no_ticket;
1491 rv = PK11_CipherOp(aes_ctx_pkcs11, decrypted_state->data,
1492 (int *)&decrypted_state->len, decrypted_state->len,
1493 enc_session_ticket.encrypted_state.data,
1494 enc_session_ticket.encrypted_state.len);
1495 PK11_Finalize(aes_ctx_pkcs11);
1496 PK11_DestroyContext(aes_ctx_pkcs11, PR_TRUE);
1497 if (rv != SECSuccess)
1498 goto no_ticket;
1501 /* Check padding. */
1502 padding_length =
1503 (PRUint32)decrypted_state->data[decrypted_state->len - 1];
1504 if (padding_length == 0 || padding_length > AES_BLOCK_SIZE)
1505 goto no_ticket;
1507 padding = &decrypted_state->data[decrypted_state->len - padding_length];
1508 for (i = 0; i < padding_length; i++, padding++) {
1509 if (padding_length != (PRUint32)*padding)
1510 goto no_ticket;
1513 /* Deserialize session state. */
1514 buffer = decrypted_state->data;
1515 buffer_len = decrypted_state->len;
1517 parsed_session_ticket = PORT_ZAlloc(sizeof(SessionTicket));
1518 if (parsed_session_ticket == NULL) {
1519 rv = SECFailure;
1520 goto loser;
1523 /* Read ticket_version (which is ignored for now.) */
1524 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1525 if (temp < 0) goto no_ticket;
1526 parsed_session_ticket->ticket_version = (SSL3ProtocolVersion)temp;
1528 /* Read SSLVersion. */
1529 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1530 if (temp < 0) goto no_ticket;
1531 parsed_session_ticket->ssl_version = (SSL3ProtocolVersion)temp;
1533 /* Read cipher_suite. */
1534 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1535 if (temp < 0) goto no_ticket;
1536 parsed_session_ticket->cipher_suite = (ssl3CipherSuite)temp;
1538 /* Read compression_method. */
1539 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1540 if (temp < 0) goto no_ticket;
1541 parsed_session_ticket->compression_method = (SSLCompressionMethod)temp;
1543 /* Read cipher spec parameters. */
1544 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1545 if (temp < 0) goto no_ticket;
1546 parsed_session_ticket->authAlgorithm = (SSLSignType)temp;
1547 temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1548 if (temp < 0) goto no_ticket;
1549 parsed_session_ticket->authKeyBits = (PRUint32)temp;
1550 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1551 if (temp < 0) goto no_ticket;
1552 parsed_session_ticket->keaType = (SSLKEAType)temp;
1553 temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1554 if (temp < 0) goto no_ticket;
1555 parsed_session_ticket->keaKeyBits = (PRUint32)temp;
1557 /* Read wrapped master_secret. */
1558 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1559 if (temp < 0) goto no_ticket;
1560 parsed_session_ticket->ms_is_wrapped = (PRBool)temp;
1562 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1563 if (temp < 0) goto no_ticket;
1564 parsed_session_ticket->exchKeyType = (SSL3KEAType)temp;
1566 temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1567 if (temp < 0) goto no_ticket;
1568 parsed_session_ticket->msWrapMech = (CK_MECHANISM_TYPE)temp;
1570 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1571 if (temp < 0) goto no_ticket;
1572 parsed_session_ticket->ms_length = (PRUint16)temp;
1573 if (parsed_session_ticket->ms_length == 0 || /* sanity check MS. */
1574 parsed_session_ticket->ms_length >
1575 sizeof(parsed_session_ticket->master_secret))
1576 goto no_ticket;
1578 /* Allow for the wrapped master secret to be longer. */
1579 if (buffer_len < sizeof(SSL3_MASTER_SECRET_LENGTH))
1580 goto no_ticket;
1581 PORT_Memcpy(parsed_session_ticket->master_secret, buffer,
1582 parsed_session_ticket->ms_length);
1583 buffer += parsed_session_ticket->ms_length;
1584 buffer_len -= parsed_session_ticket->ms_length;
1586 /* Read client_identity */
1587 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1588 if (temp < 0)
1589 goto no_ticket;
1590 parsed_session_ticket->client_identity.client_auth_type =
1591 (ClientAuthenticationType)temp;
1592 switch(parsed_session_ticket->client_identity.client_auth_type) {
1593 case CLIENT_AUTH_ANONYMOUS:
1594 break;
1595 case CLIENT_AUTH_CERTIFICATE:
1596 rv = ssl3_ConsumeHandshakeVariable(ss, &cert_item, 3,
1597 &buffer, &buffer_len);
1598 if (rv != SECSuccess) goto no_ticket;
1599 rv = SECITEM_CopyItem(NULL, &parsed_session_ticket->peer_cert,
1600 &cert_item);
1601 if (rv != SECSuccess) goto no_ticket;
1602 break;
1603 default:
1604 goto no_ticket;
1606 /* Read timestamp. */
1607 temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1608 if (temp < 0)
1609 goto no_ticket;
1610 parsed_session_ticket->timestamp = (PRUint32)temp;
1612 /* Read server name */
1613 nameType =
1614 ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1615 if (nameType != TLS_STE_NO_SERVER_NAME) {
1616 SECItem name_item;
1617 rv = ssl3_ConsumeHandshakeVariable(ss, &name_item, 2, &buffer,
1618 &buffer_len);
1619 if (rv != SECSuccess) goto no_ticket;
1620 rv = SECITEM_CopyItem(NULL, &parsed_session_ticket->srvName,
1621 &name_item);
1622 if (rv != SECSuccess) goto no_ticket;
1623 parsed_session_ticket->srvName.type = nameType;
1626 /* Done parsing. Check that all bytes have been consumed. */
1627 if (buffer_len != padding_length)
1628 goto no_ticket;
1630 /* Use the ticket if it has not expired, otherwise free the allocated
1631 * memory since the ticket is of no use.
1633 if (parsed_session_ticket->timestamp != 0 &&
1634 parsed_session_ticket->timestamp +
1635 TLS_EX_SESS_TICKET_LIFETIME_HINT > ssl_Time()) {
1637 sid = ssl3_NewSessionID(ss, PR_TRUE);
1638 if (sid == NULL) {
1639 rv = SECFailure;
1640 goto loser;
1643 /* Copy over parameters. */
1644 sid->version = parsed_session_ticket->ssl_version;
1645 sid->u.ssl3.cipherSuite = parsed_session_ticket->cipher_suite;
1646 sid->u.ssl3.compression = parsed_session_ticket->compression_method;
1647 sid->authAlgorithm = parsed_session_ticket->authAlgorithm;
1648 sid->authKeyBits = parsed_session_ticket->authKeyBits;
1649 sid->keaType = parsed_session_ticket->keaType;
1650 sid->keaKeyBits = parsed_session_ticket->keaKeyBits;
1652 /* Copy master secret. */
1653 #ifndef NO_PKCS11_BYPASS
1654 if (ss->opt.bypassPKCS11 &&
1655 parsed_session_ticket->ms_is_wrapped)
1656 goto no_ticket;
1657 #endif
1658 if (parsed_session_ticket->ms_length >
1659 sizeof(sid->u.ssl3.keys.wrapped_master_secret))
1660 goto no_ticket;
1661 PORT_Memcpy(sid->u.ssl3.keys.wrapped_master_secret,
1662 parsed_session_ticket->master_secret,
1663 parsed_session_ticket->ms_length);
1664 sid->u.ssl3.keys.wrapped_master_secret_len =
1665 parsed_session_ticket->ms_length;
1666 sid->u.ssl3.exchKeyType = parsed_session_ticket->exchKeyType;
1667 sid->u.ssl3.masterWrapMech = parsed_session_ticket->msWrapMech;
1668 sid->u.ssl3.keys.msIsWrapped =
1669 parsed_session_ticket->ms_is_wrapped;
1670 sid->u.ssl3.masterValid = PR_TRUE;
1671 sid->u.ssl3.keys.resumable = PR_TRUE;
1673 /* Copy over client cert from session ticket if there is one. */
1674 if (parsed_session_ticket->peer_cert.data != NULL) {
1675 if (sid->peerCert != NULL)
1676 CERT_DestroyCertificate(sid->peerCert);
1677 sid->peerCert = CERT_NewTempCertificate(ss->dbHandle,
1678 &parsed_session_ticket->peer_cert, NULL, PR_FALSE, PR_TRUE);
1679 if (sid->peerCert == NULL) {
1680 rv = SECFailure;
1681 goto loser;
1684 if (parsed_session_ticket->srvName.data != NULL) {
1685 sid->u.ssl3.srvName = parsed_session_ticket->srvName;
1687 ss->statelessResume = PR_TRUE;
1688 ss->sec.ci.sid = sid;
1692 if (0) {
1693 no_ticket:
1694 SSL_DBG(("%d: SSL[%d]: Session ticket parsing failed.",
1695 SSL_GETPID(), ss->fd));
1696 ssl3stats = SSL_GetStatistics();
1697 SSL_AtomicIncrementLong(& ssl3stats->hch_sid_ticket_parse_failures );
1699 rv = SECSuccess;
1701 loser:
1702 /* ss->sec.ci.sid == sid if it did NOT come here via goto statement
1703 * in that case do not free sid
1705 if (sid && (ss->sec.ci.sid != sid)) {
1706 ssl_FreeSID(sid);
1707 sid = NULL;
1709 if (decrypted_state != NULL) {
1710 SECITEM_FreeItem(decrypted_state, PR_TRUE);
1711 decrypted_state = NULL;
1714 if (parsed_session_ticket != NULL) {
1715 if (parsed_session_ticket->peer_cert.data) {
1716 SECITEM_FreeItem(&parsed_session_ticket->peer_cert, PR_FALSE);
1718 PORT_ZFree(parsed_session_ticket, sizeof(SessionTicket));
1721 return rv;
1725 * Read bytes. Using this function means the SECItem structure
1726 * cannot be freed. The caller is expected to call this function
1727 * on a shallow copy of the structure.
1729 static SECStatus
1730 ssl3_ConsumeFromItem(SECItem *item, unsigned char **buf, PRUint32 bytes)
1732 if (bytes > item->len)
1733 return SECFailure;
1735 *buf = item->data;
1736 item->data += bytes;
1737 item->len -= bytes;
1738 return SECSuccess;
1741 static SECStatus
1742 ssl3_ParseEncryptedSessionTicket(sslSocket *ss, SECItem *data,
1743 EncryptedSessionTicket *enc_session_ticket)
1745 if (ssl3_ConsumeFromItem(data, &enc_session_ticket->key_name,
1746 SESS_TICKET_KEY_NAME_LEN) != SECSuccess)
1747 return SECFailure;
1748 if (ssl3_ConsumeFromItem(data, &enc_session_ticket->iv,
1749 AES_BLOCK_SIZE) != SECSuccess)
1750 return SECFailure;
1751 if (ssl3_ConsumeHandshakeVariable(ss, &enc_session_ticket->encrypted_state,
1752 2, &data->data, &data->len) != SECSuccess)
1753 return SECFailure;
1754 if (ssl3_ConsumeFromItem(data, &enc_session_ticket->mac,
1755 TLS_EX_SESS_TICKET_MAC_LENGTH) != SECSuccess)
1756 return SECFailure;
1757 if (data->len != 0) /* Make sure that we have consumed all bytes. */
1758 return SECFailure;
1760 return SECSuccess;
1763 /* go through hello extensions in buffer "b".
1764 * For each one, find the extension handler in the table, and
1765 * if present, invoke that handler.
1766 * Servers ignore any extensions with unknown extension types.
1767 * Clients reject any extensions with unadvertised extension types.
1769 SECStatus
1770 ssl3_HandleHelloExtensions(sslSocket *ss, SSL3Opaque **b, PRUint32 *length)
1772 const ssl3HelloExtensionHandler * handlers;
1774 if (ss->sec.isServer) {
1775 handlers = clientHelloHandlers;
1776 } else if (ss->version > SSL_LIBRARY_VERSION_3_0) {
1777 handlers = serverHelloHandlersTLS;
1778 } else {
1779 handlers = serverHelloHandlersSSL3;
1782 while (*length) {
1783 const ssl3HelloExtensionHandler * handler;
1784 SECStatus rv;
1785 PRInt32 extension_type;
1786 SECItem extension_data;
1788 /* Get the extension's type field */
1789 extension_type = ssl3_ConsumeHandshakeNumber(ss, 2, b, length);
1790 if (extension_type < 0) /* failure to decode extension_type */
1791 return SECFailure; /* alert already sent */
1793 /* get the data for this extension, so we can pass it or skip it. */
1794 rv = ssl3_ConsumeHandshakeVariable(ss, &extension_data, 2, b, length);
1795 if (rv != SECSuccess)
1796 return rv;
1798 /* Check whether the server sent an extension which was not advertised
1799 * in the ClientHello.
1801 if (!ss->sec.isServer &&
1802 !ssl3_ClientExtensionAdvertised(ss, extension_type))
1803 return SECFailure; /* TODO: send unsupported_extension alert */
1805 /* Check whether an extension has been sent multiple times. */
1806 if (ssl3_ExtensionNegotiated(ss, extension_type))
1807 return SECFailure;
1809 /* find extension_type in table of Hello Extension Handlers */
1810 for (handler = handlers; handler->ex_type >= 0; handler++) {
1811 /* if found, call this handler */
1812 if (handler->ex_type == extension_type) {
1813 rv = (*handler->ex_handler)(ss, (PRUint16)extension_type,
1814 &extension_data);
1815 /* Ignore this result */
1816 /* Treat all bad extensions as unrecognized types. */
1817 break;
1821 return SECSuccess;
1824 /* Add a callback function to the table of senders of server hello extensions.
1826 SECStatus
1827 ssl3_RegisterServerHelloExtensionSender(sslSocket *ss, PRUint16 ex_type,
1828 ssl3HelloExtensionSenderFunc cb)
1830 int i;
1831 ssl3HelloExtensionSender *sender = &ss->xtnData.serverSenders[0];
1833 for (i = 0; i < SSL_MAX_EXTENSIONS; ++i, ++sender) {
1834 if (!sender->ex_sender) {
1835 sender->ex_type = ex_type;
1836 sender->ex_sender = cb;
1837 return SECSuccess;
1839 /* detect duplicate senders */
1840 PORT_Assert(sender->ex_type != ex_type);
1841 if (sender->ex_type == ex_type) {
1842 /* duplicate */
1843 break;
1846 PORT_Assert(i < SSL_MAX_EXTENSIONS); /* table needs to grow */
1847 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
1848 return SECFailure;
1851 /* call each of the extension senders and return the accumulated length */
1852 PRInt32
1853 ssl3_CallHelloExtensionSenders(sslSocket *ss, PRBool append, PRUint32 maxBytes,
1854 const ssl3HelloExtensionSender *sender)
1856 PRInt32 total_exten_len = 0;
1857 int i;
1859 if (!sender) {
1860 sender = ss->version > SSL_LIBRARY_VERSION_3_0 ?
1861 &clientHelloSendersTLS[0] : &clientHelloSendersSSL3[0];
1864 for (i = 0; i < SSL_MAX_EXTENSIONS; ++i, ++sender) {
1865 if (sender->ex_sender) {
1866 PRInt32 extLen = (*sender->ex_sender)(ss, append, maxBytes);
1867 if (extLen < 0)
1868 return -1;
1869 maxBytes -= extLen;
1870 total_exten_len += extLen;
1873 return total_exten_len;
1877 /* Extension format:
1878 * Extension number: 2 bytes
1879 * Extension length: 2 bytes
1880 * Verify Data Length: 1 byte
1881 * Verify Data (TLS): 12 bytes (client) or 24 bytes (server)
1882 * Verify Data (SSL): 36 bytes (client) or 72 bytes (server)
1884 static PRInt32
1885 ssl3_SendRenegotiationInfoXtn(
1886 sslSocket * ss,
1887 PRBool append,
1888 PRUint32 maxBytes)
1890 PRInt32 len, needed;
1892 /* In draft-ietf-tls-renegotiation-03, it is NOT RECOMMENDED to send
1893 * both the SCSV and the empty RI, so when we send SCSV in
1894 * the initial handshake, we don't also send RI.
1896 if (!ss || ss->ssl3.hs.sendingSCSV)
1897 return 0;
1898 len = !ss->firstHsDone ? 0 :
1899 (ss->sec.isServer ? ss->ssl3.hs.finishedBytes * 2
1900 : ss->ssl3.hs.finishedBytes);
1901 needed = 5 + len;
1902 if (append && maxBytes >= needed) {
1903 SECStatus rv;
1904 /* extension_type */
1905 rv = ssl3_AppendHandshakeNumber(ss, ssl_renegotiation_info_xtn, 2);
1906 if (rv != SECSuccess) return -1;
1907 /* length of extension_data */
1908 rv = ssl3_AppendHandshakeNumber(ss, len + 1, 2);
1909 if (rv != SECSuccess) return -1;
1910 /* verify_Data from previous Finished message(s) */
1911 rv = ssl3_AppendHandshakeVariable(ss,
1912 ss->ssl3.hs.finishedMsgs.data, len, 1);
1913 if (rv != SECSuccess) return -1;
1914 if (!ss->sec.isServer) {
1915 TLSExtensionData *xtnData = &ss->xtnData;
1916 xtnData->advertised[xtnData->numAdvertised++] =
1917 ssl_renegotiation_info_xtn;
1920 return needed;
1923 static SECStatus
1924 ssl3_ServerHandleStatusRequestXtn(sslSocket *ss, PRUint16 ex_type,
1925 SECItem *data)
1927 SECStatus rv = SECSuccess;
1929 /* remember that we got this extension. */
1930 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
1931 PORT_Assert(ss->sec.isServer);
1932 /* prepare to send back the appropriate response */
1933 rv = ssl3_RegisterServerHelloExtensionSender(ss, ex_type,
1934 ssl3_ServerSendStatusRequestXtn);
1935 return rv;
1938 /* This function runs in both the client and server. */
1939 static SECStatus
1940 ssl3_HandleRenegotiationInfoXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data)
1942 SECStatus rv = SECSuccess;
1943 PRUint32 len = 0;
1945 if (ss->firstHsDone) {
1946 len = ss->sec.isServer ? ss->ssl3.hs.finishedBytes
1947 : ss->ssl3.hs.finishedBytes * 2;
1949 if (data->len != 1 + len ||
1950 data->data[0] != len || (len &&
1951 NSS_SecureMemcmp(ss->ssl3.hs.finishedMsgs.data,
1952 data->data + 1, len))) {
1953 /* Can we do this here? Or, must we arrange for the caller to do it? */
1954 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
1955 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
1956 return SECFailure;
1958 /* remember that we got this extension and it was correct. */
1959 ss->peerRequestedProtection = 1;
1960 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
1961 if (ss->sec.isServer) {
1962 /* prepare to send back the appropriate response */
1963 rv = ssl3_RegisterServerHelloExtensionSender(ss, ex_type,
1964 ssl3_SendRenegotiationInfoXtn);
1966 return rv;
1969 static PRInt32
1970 ssl3_SendUseSRTPXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes)
1972 PRUint32 ext_data_len;
1973 PRInt16 i;
1974 SECStatus rv;
1976 if (!ss)
1977 return 0;
1979 if (!ss->sec.isServer) {
1980 /* Client side */
1982 if (!IS_DTLS(ss) || !ss->ssl3.dtlsSRTPCipherCount)
1983 return 0; /* Not relevant */
1985 ext_data_len = 2 + 2 * ss->ssl3.dtlsSRTPCipherCount + 1;
1987 if (append && maxBytes >= 4 + ext_data_len) {
1988 /* Extension type */
1989 rv = ssl3_AppendHandshakeNumber(ss, ssl_use_srtp_xtn, 2);
1990 if (rv != SECSuccess) return -1;
1991 /* Length of extension data */
1992 rv = ssl3_AppendHandshakeNumber(ss, ext_data_len, 2);
1993 if (rv != SECSuccess) return -1;
1994 /* Length of the SRTP cipher list */
1995 rv = ssl3_AppendHandshakeNumber(ss,
1996 2 * ss->ssl3.dtlsSRTPCipherCount,
1998 if (rv != SECSuccess) return -1;
1999 /* The SRTP ciphers */
2000 for (i = 0; i < ss->ssl3.dtlsSRTPCipherCount; i++) {
2001 rv = ssl3_AppendHandshakeNumber(ss,
2002 ss->ssl3.dtlsSRTPCiphers[i],
2005 /* Empty MKI value */
2006 ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
2008 ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
2009 ssl_use_srtp_xtn;
2012 return 4 + ext_data_len;
2015 /* Server side */
2016 if (append && maxBytes >= 9) {
2017 /* Extension type */
2018 rv = ssl3_AppendHandshakeNumber(ss, ssl_use_srtp_xtn, 2);
2019 if (rv != SECSuccess) return -1;
2020 /* Length of extension data */
2021 rv = ssl3_AppendHandshakeNumber(ss, 5, 2);
2022 if (rv != SECSuccess) return -1;
2023 /* Length of the SRTP cipher list */
2024 rv = ssl3_AppendHandshakeNumber(ss, 2, 2);
2025 if (rv != SECSuccess) return -1;
2026 /* The selected cipher */
2027 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.dtlsSRTPCipherSuite, 2);
2028 if (rv != SECSuccess) return -1;
2029 /* Empty MKI value */
2030 ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
2033 return 9;
2036 static SECStatus
2037 ssl3_HandleUseSRTPXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data)
2039 SECStatus rv;
2040 SECItem ciphers = {siBuffer, NULL, 0};
2041 PRUint16 i;
2042 unsigned int j;
2043 PRUint16 cipher = 0;
2044 PRBool found = PR_FALSE;
2045 SECItem litem;
2047 if (!ss->sec.isServer) {
2048 /* Client side */
2049 if (!data->data || !data->len) {
2050 /* malformed */
2051 return SECFailure;
2054 /* Get the cipher list */
2055 rv = ssl3_ConsumeHandshakeVariable(ss, &ciphers, 2,
2056 &data->data, &data->len);
2057 if (rv != SECSuccess) {
2058 return SECFailure;
2060 /* Now check that the number of ciphers listed is 1 (len = 2) */
2061 if (ciphers.len != 2) {
2062 return SECFailure;
2065 /* Get the selected cipher */
2066 cipher = (ciphers.data[0] << 8) | ciphers.data[1];
2068 /* Now check that this is one of the ciphers we offered */
2069 for (i = 0; i < ss->ssl3.dtlsSRTPCipherCount; i++) {
2070 if (cipher == ss->ssl3.dtlsSRTPCiphers[i]) {
2071 found = PR_TRUE;
2072 break;
2076 if (!found) {
2077 return SECFailure;
2080 /* Get the srtp_mki value */
2081 rv = ssl3_ConsumeHandshakeVariable(ss, &litem, 1,
2082 &data->data, &data->len);
2083 if (rv != SECSuccess) {
2084 return SECFailure;
2087 /* We didn't offer an MKI, so this must be 0 length */
2088 /* XXX RFC 5764 Section 4.1.3 says:
2089 * If the client detects a nonzero-length MKI in the server's
2090 * response that is different than the one the client offered,
2091 * then the client MUST abort the handshake and SHOULD send an
2092 * invalid_parameter alert.
2094 * Due to a limitation of the ssl3_HandleHelloExtensions function,
2095 * returning SECFailure here won't abort the handshake. It will
2096 * merely cause the use_srtp extension to be not negotiated. We
2097 * should fix this. See NSS bug 753136.
2099 if (litem.len != 0) {
2100 return SECFailure;
2103 if (data->len != 0) {
2104 /* malformed */
2105 return SECFailure;
2108 /* OK, this looks fine. */
2109 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ssl_use_srtp_xtn;
2110 ss->ssl3.dtlsSRTPCipherSuite = cipher;
2111 return SECSuccess;
2114 /* Server side */
2115 if (!IS_DTLS(ss) || !ss->ssl3.dtlsSRTPCipherCount) {
2116 /* Ignore the extension if we aren't doing DTLS or no DTLS-SRTP
2117 * preferences have been set. */
2118 return SECSuccess;
2121 if (!data->data || data->len < 5) {
2122 /* malformed */
2123 return SECFailure;
2126 /* Get the cipher list */
2127 rv = ssl3_ConsumeHandshakeVariable(ss, &ciphers, 2,
2128 &data->data, &data->len);
2129 if (rv != SECSuccess) {
2130 return SECFailure;
2132 /* Check that the list is even length */
2133 if (ciphers.len % 2) {
2134 return SECFailure;
2137 /* Walk through the offered list and pick the most preferred of our
2138 * ciphers, if any */
2139 for (i = 0; !found && i < ss->ssl3.dtlsSRTPCipherCount; i++) {
2140 for (j = 0; j + 1 < ciphers.len; j += 2) {
2141 cipher = (ciphers.data[j] << 8) | ciphers.data[j + 1];
2142 if (cipher == ss->ssl3.dtlsSRTPCiphers[i]) {
2143 found = PR_TRUE;
2144 break;
2149 /* Get the srtp_mki value */
2150 rv = ssl3_ConsumeHandshakeVariable(ss, &litem, 1, &data->data, &data->len);
2151 if (rv != SECSuccess) {
2152 return SECFailure;
2155 if (data->len != 0) {
2156 return SECFailure; /* Malformed */
2159 /* Now figure out what to do */
2160 if (!found) {
2161 /* No matching ciphers */
2162 return SECSuccess;
2165 /* OK, we have a valid cipher and we've selected it */
2166 ss->ssl3.dtlsSRTPCipherSuite = cipher;
2167 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ssl_use_srtp_xtn;
2169 return ssl3_RegisterServerHelloExtensionSender(ss, ssl_use_srtp_xtn,
2170 ssl3_SendUseSRTPXtn);
2173 /* ssl3_ServerHandleSigAlgsXtn handles the signature_algorithms extension
2174 * from a client.
2175 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
2176 static SECStatus
2177 ssl3_ServerHandleSigAlgsXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data)
2179 SECStatus rv;
2180 SECItem algorithms;
2181 const unsigned char *b;
2182 unsigned int numAlgorithms, i;
2184 /* Ignore this extension if we aren't doing TLS 1.2 or greater. */
2185 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_2) {
2186 return SECSuccess;
2189 /* Keep track of negotiated extensions. */
2190 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
2192 rv = ssl3_ConsumeHandshakeVariable(ss, &algorithms, 2, &data->data,
2193 &data->len);
2194 if (rv != SECSuccess) {
2195 return SECFailure;
2197 /* Trailing data, empty value, or odd-length value is invalid. */
2198 if (data->len != 0 || algorithms.len == 0 || (algorithms.len & 1) != 0) {
2199 PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
2200 return SECFailure;
2203 numAlgorithms = algorithms.len/2;
2205 /* We don't care to process excessive numbers of algorithms. */
2206 if (numAlgorithms > 512) {
2207 numAlgorithms = 512;
2210 ss->ssl3.hs.clientSigAndHash =
2211 PORT_NewArray(SSL3SignatureAndHashAlgorithm, numAlgorithms);
2212 if (!ss->ssl3.hs.clientSigAndHash) {
2213 return SECFailure;
2215 ss->ssl3.hs.numClientSigAndHash = 0;
2217 b = algorithms.data;
2218 for (i = 0; i < numAlgorithms; i++) {
2219 unsigned char tls_hash = *(b++);
2220 unsigned char tls_sig = *(b++);
2221 SECOidTag hash = ssl3_TLSHashAlgorithmToOID(tls_hash);
2223 if (hash == SEC_OID_UNKNOWN) {
2224 /* We ignore formats that we don't understand. */
2225 continue;
2227 /* tls_sig support will be checked later in
2228 * ssl3_PickSignatureHashAlgorithm. */
2229 ss->ssl3.hs.clientSigAndHash[i].hashAlg = hash;
2230 ss->ssl3.hs.clientSigAndHash[i].sigAlg = tls_sig;
2231 ss->ssl3.hs.numClientSigAndHash++;
2234 if (!ss->ssl3.hs.numClientSigAndHash) {
2235 /* We didn't understand any of the client's requested signature
2236 * formats. We'll use the defaults. */
2237 PORT_Free(ss->ssl3.hs.clientSigAndHash);
2238 ss->ssl3.hs.clientSigAndHash = NULL;
2241 return SECSuccess;
2244 /* ssl3_ClientSendSigAlgsXtn sends the signature_algorithm extension for TLS
2245 * 1.2 ClientHellos. */
2246 static PRInt32
2247 ssl3_ClientSendSigAlgsXtn(sslSocket * ss, PRBool append, PRUint32 maxBytes)
2249 static const unsigned char signatureAlgorithms[] = {
2250 /* This block is the contents of our signature_algorithms extension, in
2251 * wire format. See
2252 * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
2253 tls_hash_sha256, tls_sig_rsa,
2254 tls_hash_sha384, tls_sig_rsa,
2255 tls_hash_sha1, tls_sig_rsa,
2256 #ifdef NSS_ENABLE_ECC
2257 tls_hash_sha256, tls_sig_ecdsa,
2258 tls_hash_sha384, tls_sig_ecdsa,
2259 tls_hash_sha1, tls_sig_ecdsa,
2260 #endif
2261 tls_hash_sha256, tls_sig_dsa,
2262 tls_hash_sha1, tls_sig_dsa,
2264 PRInt32 extension_length;
2266 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_2) {
2267 return 0;
2270 extension_length =
2271 2 /* extension type */ +
2272 2 /* extension length */ +
2273 2 /* supported_signature_algorithms length */ +
2274 sizeof(signatureAlgorithms);
2276 if (append && maxBytes >= extension_length) {
2277 SECStatus rv;
2278 rv = ssl3_AppendHandshakeNumber(ss, ssl_signature_algorithms_xtn, 2);
2279 if (rv != SECSuccess)
2280 goto loser;
2281 rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2);
2282 if (rv != SECSuccess)
2283 goto loser;
2284 rv = ssl3_AppendHandshakeVariable(ss, signatureAlgorithms,
2285 sizeof(signatureAlgorithms), 2);
2286 if (rv != SECSuccess)
2287 goto loser;
2288 ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
2289 ssl_signature_algorithms_xtn;
2290 } else if (maxBytes < extension_length) {
2291 PORT_Assert(0);
2292 return 0;
2295 return extension_length;
2297 loser:
2298 return -1;