Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / net / third_party / nss / ssl / ssl3ext.c
blob9214a2e6b3bdc2e923d0beba0245b6ba71bf5838
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * SSL3 Protocol
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
9 /* TLS extension code moved here from ssl3ecc.c */
11 #include "nssrenam.h"
12 #include "nss.h"
13 #include "ssl.h"
14 #include "sslimpl.h"
15 #include "sslproto.h"
16 #include "pk11pub.h"
17 #ifdef NO_PKCS11_BYPASS
18 #include "blapit.h"
19 #else
20 #include "blapi.h"
21 #endif
22 #include "prinit.h"
24 static unsigned char key_name[SESS_TICKET_KEY_NAME_LEN];
25 static PK11SymKey *session_ticket_enc_key_pkcs11 = NULL;
26 static PK11SymKey *session_ticket_mac_key_pkcs11 = NULL;
28 #ifndef NO_PKCS11_BYPASS
29 static unsigned char session_ticket_enc_key[AES_256_KEY_LENGTH];
30 static unsigned char session_ticket_mac_key[SHA256_LENGTH];
32 static PRBool session_ticket_keys_initialized = PR_FALSE;
33 #endif
34 static PRCallOnceType generate_session_keys_once;
36 /* forward static function declarations */
37 static SECStatus ssl3_ParseEncryptedSessionTicket(sslSocket *ss,
38 SECItem *data, EncryptedSessionTicket *enc_session_ticket);
39 static SECStatus ssl3_AppendToItem(SECItem *item, const unsigned char *buf,
40 PRUint32 bytes);
41 static SECStatus ssl3_AppendNumberToItem(SECItem *item, PRUint32 num,
42 PRInt32 lenSize);
43 static SECStatus ssl3_GetSessionTicketKeysPKCS11(sslSocket *ss,
44 PK11SymKey **aes_key, PK11SymKey **mac_key);
45 #ifndef NO_PKCS11_BYPASS
46 static SECStatus ssl3_GetSessionTicketKeys(const unsigned char **aes_key,
47 PRUint32 *aes_key_length, const unsigned char **mac_key,
48 PRUint32 *mac_key_length);
49 #endif
50 static PRInt32 ssl3_SendRenegotiationInfoXtn(sslSocket * ss,
51 PRBool append, PRUint32 maxBytes);
52 static SECStatus ssl3_HandleRenegotiationInfoXtn(sslSocket *ss,
53 PRUint16 ex_type, SECItem *data);
54 static SECStatus ssl3_ClientHandleNextProtoNegoXtn(sslSocket *ss,
55 PRUint16 ex_type, SECItem *data);
56 static SECStatus ssl3_ClientHandleAppProtoXtn(sslSocket *ss,
57 PRUint16 ex_type, SECItem *data);
58 static SECStatus ssl3_ServerHandleNextProtoNegoXtn(sslSocket *ss,
59 PRUint16 ex_type, SECItem *data);
60 static SECStatus ssl3_ServerHandleAppProtoXtn(sslSocket *ss, PRUint16 ex_type,
61 SECItem *data);
62 static PRInt32 ssl3_ClientSendNextProtoNegoXtn(sslSocket *ss, PRBool append,
63 PRUint32 maxBytes);
64 static PRInt32 ssl3_ClientSendAppProtoXtn(sslSocket *ss, PRBool append,
65 PRUint32 maxBytes);
66 static PRInt32 ssl3_ServerSendAppProtoXtn(sslSocket *ss, PRBool append,
67 PRUint32 maxBytes);
68 static PRInt32 ssl3_ClientSendUseSRTPXtn(sslSocket *ss, PRBool append,
69 PRUint32 maxBytes);
70 static PRInt32 ssl3_ServerSendUseSRTPXtn(sslSocket *ss, PRBool append,
71 PRUint32 maxBytes);
72 static SECStatus ssl3_ClientHandleUseSRTPXtn(sslSocket * ss, PRUint16 ex_type,
73 SECItem *data);
74 static SECStatus ssl3_ServerHandleUseSRTPXtn(sslSocket * ss, PRUint16 ex_type,
75 SECItem *data);
76 static SECStatus ssl3_ClientHandleChannelIDXtn(sslSocket *ss,
77 PRUint16 ex_type, SECItem *data);
78 static PRInt32 ssl3_ClientSendChannelIDXtn(sslSocket *ss, PRBool append,
79 PRUint32 maxBytes);
80 static PRInt32 ssl3_ServerSendStatusRequestXtn(sslSocket * ss,
81 PRBool append, PRUint32 maxBytes);
82 static SECStatus ssl3_ServerHandleStatusRequestXtn(sslSocket *ss,
83 PRUint16 ex_type, SECItem *data);
84 static SECStatus ssl3_ClientHandleStatusRequestXtn(sslSocket *ss,
85 PRUint16 ex_type,
86 SECItem *data);
87 static PRInt32 ssl3_ClientSendStatusRequestXtn(sslSocket * ss, PRBool append,
88 PRUint32 maxBytes);
89 static PRInt32 ssl3_ClientSendSigAlgsXtn(sslSocket *ss, PRBool append,
90 PRUint32 maxBytes);
91 static SECStatus ssl3_ServerHandleSigAlgsXtn(sslSocket *ss, PRUint16 ex_type,
92 SECItem *data);
93 static PRInt32 ssl3_ClientSendSignedCertTimestampXtn(sslSocket *ss,
94 PRBool append,
95 PRUint32 maxBytes);
96 static SECStatus ssl3_ClientHandleSignedCertTimestampXtn(sslSocket *ss,
97 PRUint16 ex_type,
98 SECItem *data);
100 static PRInt32 ssl3_ClientSendDraftVersionXtn(sslSocket *ss, PRBool append,
101 PRUint32 maxBytes);
102 static SECStatus ssl3_ServerHandleDraftVersionXtn(sslSocket *ss, PRUint16 ex_type,
103 SECItem *data);
106 * Write bytes. Using this function means the SECItem structure
107 * cannot be freed. The caller is expected to call this function
108 * on a shallow copy of the structure.
110 static SECStatus
111 ssl3_AppendToItem(SECItem *item, const unsigned char *buf, PRUint32 bytes)
113 if (bytes > item->len)
114 return SECFailure;
116 PORT_Memcpy(item->data, buf, bytes);
117 item->data += bytes;
118 item->len -= bytes;
119 return SECSuccess;
123 * Write a number in network byte order. Using this function means the
124 * SECItem structure cannot be freed. The caller is expected to call
125 * this function on a shallow copy of the structure.
127 static SECStatus
128 ssl3_AppendNumberToItem(SECItem *item, PRUint32 num, PRInt32 lenSize)
130 SECStatus rv;
131 PRUint8 b[4];
132 PRUint8 * p = b;
134 switch (lenSize) {
135 case 4:
136 *p++ = (PRUint8) (num >> 24);
137 case 3:
138 *p++ = (PRUint8) (num >> 16);
139 case 2:
140 *p++ = (PRUint8) (num >> 8);
141 case 1:
142 *p = (PRUint8) num;
144 rv = ssl3_AppendToItem(item, &b[0], lenSize);
145 return rv;
148 static SECStatus ssl3_SessionTicketShutdown(void* appData, void* nssData)
150 if (session_ticket_enc_key_pkcs11) {
151 PK11_FreeSymKey(session_ticket_enc_key_pkcs11);
152 session_ticket_enc_key_pkcs11 = NULL;
154 if (session_ticket_mac_key_pkcs11) {
155 PK11_FreeSymKey(session_ticket_mac_key_pkcs11);
156 session_ticket_mac_key_pkcs11 = NULL;
158 PORT_Memset(&generate_session_keys_once, 0,
159 sizeof(generate_session_keys_once));
160 return SECSuccess;
164 static PRStatus
165 ssl3_GenerateSessionTicketKeysPKCS11(void *data)
167 SECStatus rv;
168 sslSocket *ss = (sslSocket *)data;
169 SECKEYPrivateKey *svrPrivKey = ss->serverCerts[kt_rsa].SERVERKEY;
170 SECKEYPublicKey *svrPubKey = ss->serverCerts[kt_rsa].serverKeyPair->pubKey;
172 if (svrPrivKey == NULL || svrPubKey == NULL) {
173 SSL_DBG(("%d: SSL[%d]: Pub or priv key(s) is NULL.",
174 SSL_GETPID(), ss->fd));
175 goto loser;
178 /* Get a copy of the session keys from shared memory. */
179 PORT_Memcpy(key_name, SESS_TICKET_KEY_NAME_PREFIX,
180 sizeof(SESS_TICKET_KEY_NAME_PREFIX));
181 if (!ssl_GetSessionTicketKeysPKCS11(svrPrivKey, svrPubKey,
182 ss->pkcs11PinArg, &key_name[SESS_TICKET_KEY_NAME_PREFIX_LEN],
183 &session_ticket_enc_key_pkcs11, &session_ticket_mac_key_pkcs11))
184 return PR_FAILURE;
186 rv = NSS_RegisterShutdown(ssl3_SessionTicketShutdown, NULL);
187 if (rv != SECSuccess)
188 goto loser;
190 return PR_SUCCESS;
192 loser:
193 ssl3_SessionTicketShutdown(NULL, NULL);
194 return PR_FAILURE;
197 static SECStatus
198 ssl3_GetSessionTicketKeysPKCS11(sslSocket *ss, PK11SymKey **aes_key,
199 PK11SymKey **mac_key)
201 if (PR_CallOnceWithArg(&generate_session_keys_once,
202 ssl3_GenerateSessionTicketKeysPKCS11, ss) != PR_SUCCESS)
203 return SECFailure;
205 if (session_ticket_enc_key_pkcs11 == NULL ||
206 session_ticket_mac_key_pkcs11 == NULL)
207 return SECFailure;
209 *aes_key = session_ticket_enc_key_pkcs11;
210 *mac_key = session_ticket_mac_key_pkcs11;
211 return SECSuccess;
214 #ifndef NO_PKCS11_BYPASS
215 static PRStatus
216 ssl3_GenerateSessionTicketKeys(void)
218 PORT_Memcpy(key_name, SESS_TICKET_KEY_NAME_PREFIX,
219 sizeof(SESS_TICKET_KEY_NAME_PREFIX));
221 if (!ssl_GetSessionTicketKeys(&key_name[SESS_TICKET_KEY_NAME_PREFIX_LEN],
222 session_ticket_enc_key, session_ticket_mac_key))
223 return PR_FAILURE;
225 session_ticket_keys_initialized = PR_TRUE;
226 return PR_SUCCESS;
229 static SECStatus
230 ssl3_GetSessionTicketKeys(const unsigned char **aes_key,
231 PRUint32 *aes_key_length, const unsigned char **mac_key,
232 PRUint32 *mac_key_length)
234 if (PR_CallOnce(&generate_session_keys_once,
235 ssl3_GenerateSessionTicketKeys) != PR_SUCCESS)
236 return SECFailure;
238 if (!session_ticket_keys_initialized)
239 return SECFailure;
241 *aes_key = session_ticket_enc_key;
242 *aes_key_length = sizeof(session_ticket_enc_key);
243 *mac_key = session_ticket_mac_key;
244 *mac_key_length = sizeof(session_ticket_mac_key);
246 return SECSuccess;
248 #endif
250 /* Table of handlers for received TLS hello extensions, one per extension.
251 * In the second generation, this table will be dynamic, and functions
252 * will be registered here.
254 /* This table is used by the server, to handle client hello extensions. */
255 static const ssl3HelloExtensionHandler clientHelloHandlers[] = {
256 { ssl_server_name_xtn, &ssl3_HandleServerNameXtn },
257 #ifndef NSS_DISABLE_ECC
258 { ssl_elliptic_curves_xtn, &ssl3_HandleSupportedCurvesXtn },
259 { ssl_ec_point_formats_xtn, &ssl3_HandleSupportedPointFormatsXtn },
260 #endif
261 { ssl_session_ticket_xtn, &ssl3_ServerHandleSessionTicketXtn },
262 { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn },
263 { ssl_next_proto_nego_xtn, &ssl3_ServerHandleNextProtoNegoXtn },
264 { ssl_app_layer_protocol_xtn, &ssl3_ServerHandleAppProtoXtn },
265 { ssl_use_srtp_xtn, &ssl3_ServerHandleUseSRTPXtn },
266 { ssl_cert_status_xtn, &ssl3_ServerHandleStatusRequestXtn },
267 { ssl_signature_algorithms_xtn, &ssl3_ServerHandleSigAlgsXtn },
268 { ssl_tls13_draft_version_xtn, &ssl3_ServerHandleDraftVersionXtn },
269 { -1, NULL }
272 /* These two tables are used by the client, to handle server hello
273 * extensions. */
274 static const ssl3HelloExtensionHandler serverHelloHandlersTLS[] = {
275 { ssl_server_name_xtn, &ssl3_HandleServerNameXtn },
276 /* TODO: add a handler for ssl_ec_point_formats_xtn */
277 { ssl_session_ticket_xtn, &ssl3_ClientHandleSessionTicketXtn },
278 { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn },
279 { ssl_next_proto_nego_xtn, &ssl3_ClientHandleNextProtoNegoXtn },
280 { ssl_app_layer_protocol_xtn, &ssl3_ClientHandleAppProtoXtn },
281 { ssl_use_srtp_xtn, &ssl3_ClientHandleUseSRTPXtn },
282 { ssl_channel_id_xtn, &ssl3_ClientHandleChannelIDXtn },
283 { ssl_cert_status_xtn, &ssl3_ClientHandleStatusRequestXtn },
284 { ssl_signed_certificate_timestamp_xtn,
285 &ssl3_ClientHandleSignedCertTimestampXtn },
286 { -1, NULL }
289 static const ssl3HelloExtensionHandler serverHelloHandlersSSL3[] = {
290 { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn },
291 { -1, NULL }
294 /* Tables of functions to format TLS hello extensions, one function per
295 * extension.
296 * These static tables are for the formatting of client hello extensions.
297 * The server's table of hello senders is dynamic, in the socket struct,
298 * and sender functions are registered there.
300 static const
301 ssl3HelloExtensionSender clientHelloSendersTLS[SSL_MAX_EXTENSIONS] = {
302 { ssl_server_name_xtn, &ssl3_SendServerNameXtn },
303 { ssl_renegotiation_info_xtn, &ssl3_SendRenegotiationInfoXtn },
304 #ifndef NSS_DISABLE_ECC
305 { ssl_elliptic_curves_xtn, &ssl3_SendSupportedCurvesXtn },
306 { ssl_ec_point_formats_xtn, &ssl3_SendSupportedPointFormatsXtn },
307 #endif
308 { ssl_session_ticket_xtn, &ssl3_SendSessionTicketXtn },
309 { ssl_next_proto_nego_xtn, &ssl3_ClientSendNextProtoNegoXtn },
310 { ssl_app_layer_protocol_xtn, &ssl3_ClientSendAppProtoXtn },
311 { ssl_use_srtp_xtn, &ssl3_ClientSendUseSRTPXtn },
312 { ssl_channel_id_xtn, &ssl3_ClientSendChannelIDXtn },
313 { ssl_cert_status_xtn, &ssl3_ClientSendStatusRequestXtn },
314 { ssl_signed_certificate_timestamp_xtn,
315 &ssl3_ClientSendSignedCertTimestampXtn },
316 /* WebSphere Application Server 7.0 is intolerant to the last extension
317 * being zero-length. It is not intolerant of TLS 1.2, so ensure that
318 * signature_algorithms is at the end to guarantee a non-empty
319 * extension. */
320 { ssl_signature_algorithms_xtn, &ssl3_ClientSendSigAlgsXtn },
321 { ssl_tls13_draft_version_xtn, &ssl3_ClientSendDraftVersionXtn },
322 /* any extra entries will appear as { 0, NULL } */
325 static const
326 ssl3HelloExtensionSender clientHelloSendersSSL3[SSL_MAX_EXTENSIONS] = {
327 { ssl_renegotiation_info_xtn, &ssl3_SendRenegotiationInfoXtn }
328 /* any extra entries will appear as { 0, NULL } */
331 static PRBool
332 arrayContainsExtension(const PRUint16 *array, PRUint32 len, PRUint16 ex_type)
334 int i;
335 for (i = 0; i < len; i++) {
336 if (ex_type == array[i])
337 return PR_TRUE;
339 return PR_FALSE;
342 PRBool
343 ssl3_ExtensionNegotiated(sslSocket *ss, PRUint16 ex_type) {
344 TLSExtensionData *xtnData = &ss->xtnData;
345 return arrayContainsExtension(xtnData->negotiated,
346 xtnData->numNegotiated, ex_type);
349 static PRBool
350 ssl3_ClientExtensionAdvertised(sslSocket *ss, PRUint16 ex_type) {
351 TLSExtensionData *xtnData = &ss->xtnData;
352 return arrayContainsExtension(xtnData->advertised,
353 xtnData->numAdvertised, ex_type);
356 /* Format an SNI extension, using the name from the socket's URL,
357 * unless that name is a dotted decimal string.
358 * Used by client and server.
360 PRInt32
361 ssl3_SendServerNameXtn(sslSocket * ss, PRBool append,
362 PRUint32 maxBytes)
364 SECStatus rv;
365 if (!ss)
366 return 0;
367 if (!ss->sec.isServer) {
368 PRUint32 len;
369 PRNetAddr netAddr;
371 /* must have a hostname */
372 if (!ss->url || !ss->url[0])
373 return 0;
374 /* must not be an IPv4 or IPv6 address */
375 if (PR_SUCCESS == PR_StringToNetAddr(ss->url, &netAddr)) {
376 /* is an IP address (v4 or v6) */
377 return 0;
379 len = PORT_Strlen(ss->url);
380 if (append && maxBytes >= len + 9) {
381 /* extension_type */
382 rv = ssl3_AppendHandshakeNumber(ss, ssl_server_name_xtn, 2);
383 if (rv != SECSuccess) return -1;
384 /* length of extension_data */
385 rv = ssl3_AppendHandshakeNumber(ss, len + 5, 2);
386 if (rv != SECSuccess) return -1;
387 /* length of server_name_list */
388 rv = ssl3_AppendHandshakeNumber(ss, len + 3, 2);
389 if (rv != SECSuccess) return -1;
390 /* Name Type (sni_host_name) */
391 rv = ssl3_AppendHandshake(ss, "\0", 1);
392 if (rv != SECSuccess) return -1;
393 /* HostName (length and value) */
394 rv = ssl3_AppendHandshakeVariable(ss, (PRUint8 *)ss->url, len, 2);
395 if (rv != SECSuccess) return -1;
396 if (!ss->sec.isServer) {
397 TLSExtensionData *xtnData = &ss->xtnData;
398 xtnData->advertised[xtnData->numAdvertised++] =
399 ssl_server_name_xtn;
402 return len + 9;
404 /* Server side */
405 if (append && maxBytes >= 4) {
406 rv = ssl3_AppendHandshakeNumber(ss, ssl_server_name_xtn, 2);
407 if (rv != SECSuccess) return -1;
408 /* length of extension_data */
409 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
410 if (rv != SECSuccess) return -1;
412 return 4;
415 /* handle an incoming SNI extension, by ignoring it. */
416 SECStatus
417 ssl3_HandleServerNameXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data)
419 SECItem *names = NULL;
420 PRUint32 listCount = 0, namesPos = 0, i;
421 TLSExtensionData *xtnData = &ss->xtnData;
422 SECItem ldata;
423 PRInt32 listLenBytes = 0;
425 if (!ss->sec.isServer) {
426 return SECSuccess; /* ignore extension */
429 /* Server side - consume client data and register server sender. */
430 /* do not parse the data if don't have user extension handling function. */
431 if (!ss->sniSocketConfig) {
432 return SECSuccess;
434 /* length of server_name_list */
435 listLenBytes = ssl3_ConsumeHandshakeNumber(ss, 2, &data->data, &data->len);
436 if (listLenBytes < 0 || listLenBytes != data->len) {
437 (void)ssl3_DecodeError(ss);
438 return SECFailure;
440 if (listLenBytes == 0) {
441 return SECSuccess; /* ignore an empty extension */
443 ldata = *data;
444 /* Calculate the size of the array.*/
445 while (listLenBytes > 0) {
446 SECItem litem;
447 SECStatus rv;
448 PRInt32 type;
449 /* Skip Name Type (sni_host_name); checks are on the second pass */
450 type = ssl3_ConsumeHandshakeNumber(ss, 1, &ldata.data, &ldata.len);
451 if (type < 0) { /* i.e., SECFailure cast to PRint32 */
452 return SECFailure;
454 rv = ssl3_ConsumeHandshakeVariable(ss, &litem, 2, &ldata.data, &ldata.len);
455 if (rv != SECSuccess) {
456 return rv;
458 /* Adjust total length for consumed item, item len and type.*/
459 listLenBytes -= litem.len + 3;
460 if (listLenBytes > 0 && !ldata.len) {
461 (void)ssl3_DecodeError(ss);
462 return SECFailure;
464 listCount += 1;
466 if (!listCount) {
467 return SECFailure; /* nothing we can act on */
469 names = PORT_ZNewArray(SECItem, listCount);
470 if (!names) {
471 return SECFailure;
473 for (i = 0;i < listCount;i++) {
474 int j;
475 PRInt32 type;
476 SECStatus rv;
477 PRBool nametypePresent = PR_FALSE;
478 /* Name Type (sni_host_name) */
479 type = ssl3_ConsumeHandshakeNumber(ss, 1, &data->data, &data->len);
480 /* Check if we have such type in the list */
481 for (j = 0;j < listCount && names[j].data;j++) {
482 /* TODO bug 998524: .type is not assigned a value */
483 if (names[j].type == type) {
484 nametypePresent = PR_TRUE;
485 break;
488 /* HostName (length and value) */
489 rv = ssl3_ConsumeHandshakeVariable(ss, &names[namesPos], 2,
490 &data->data, &data->len);
491 if (rv != SECSuccess) {
492 PORT_Assert(0);
493 PORT_Free(names);
494 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
495 return rv;
497 if (nametypePresent == PR_FALSE) {
498 namesPos += 1;
501 /* Free old and set the new data. */
502 if (xtnData->sniNameArr) {
503 PORT_Free(ss->xtnData.sniNameArr);
505 xtnData->sniNameArr = names;
506 xtnData->sniNameArrSize = namesPos;
507 xtnData->negotiated[xtnData->numNegotiated++] = ssl_server_name_xtn;
509 return SECSuccess;
512 /* Called by both clients and servers.
513 * Clients sends a filled in session ticket if one is available, and otherwise
514 * sends an empty ticket. Servers always send empty tickets.
516 PRInt32
517 ssl3_SendSessionTicketXtn(
518 sslSocket * ss,
519 PRBool append,
520 PRUint32 maxBytes)
522 PRInt32 extension_length;
523 NewSessionTicket *session_ticket = NULL;
524 sslSessionID *sid = ss->sec.ci.sid;
526 /* Ignore the SessionTicket extension if processing is disabled. */
527 if (!ss->opt.enableSessionTickets)
528 return 0;
530 /* Empty extension length = extension_type (2-bytes) +
531 * length(extension_data) (2-bytes)
533 extension_length = 4;
535 /* If we are a client then send a session ticket if one is availble.
536 * Servers that support the extension and are willing to negotiate the
537 * the extension always respond with an empty extension.
539 if (!ss->sec.isServer) {
540 /* The caller must be holding sid->u.ssl3.lock for reading. We cannot
541 * just acquire and release the lock within this function because the
542 * caller will call this function twice, and we need the inputs to be
543 * consistent between the two calls. Note that currently the caller
544 * will only be holding the lock when we are the client and when we're
545 * attempting to resume an existing session.
548 session_ticket = &sid->u.ssl3.locked.sessionTicket;
549 if (session_ticket->ticket.data) {
550 if (ss->xtnData.ticketTimestampVerified) {
551 extension_length += session_ticket->ticket.len;
552 } else if (!append &&
553 (session_ticket->ticket_lifetime_hint == 0 ||
554 (session_ticket->ticket_lifetime_hint +
555 session_ticket->received_timestamp > ssl_Time()))) {
556 extension_length += session_ticket->ticket.len;
557 ss->xtnData.ticketTimestampVerified = PR_TRUE;
562 if (append && maxBytes >= extension_length) {
563 SECStatus rv;
564 /* extension_type */
565 rv = ssl3_AppendHandshakeNumber(ss, ssl_session_ticket_xtn, 2);
566 if (rv != SECSuccess)
567 goto loser;
568 if (session_ticket && session_ticket->ticket.data &&
569 ss->xtnData.ticketTimestampVerified) {
570 rv = ssl3_AppendHandshakeVariable(ss, session_ticket->ticket.data,
571 session_ticket->ticket.len, 2);
572 ss->xtnData.ticketTimestampVerified = PR_FALSE;
573 ss->xtnData.sentSessionTicketInClientHello = PR_TRUE;
574 } else {
575 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
577 if (rv != SECSuccess)
578 goto loser;
580 if (!ss->sec.isServer) {
581 TLSExtensionData *xtnData = &ss->xtnData;
582 xtnData->advertised[xtnData->numAdvertised++] =
583 ssl_session_ticket_xtn;
585 } else if (maxBytes < extension_length) {
586 PORT_Assert(0);
587 return 0;
589 return extension_length;
591 loser:
592 ss->xtnData.ticketTimestampVerified = PR_FALSE;
593 return -1;
596 /* handle an incoming Next Protocol Negotiation extension. */
597 static SECStatus
598 ssl3_ServerHandleNextProtoNegoXtn(sslSocket * ss, PRUint16 ex_type,
599 SECItem *data)
601 if (ss->firstHsDone || data->len != 0) {
602 /* Clients MUST send an empty NPN extension, if any. */
603 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
604 return SECFailure;
607 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
609 /* TODO: server side NPN support would require calling
610 * ssl3_RegisterServerHelloExtensionSender here in order to echo the
611 * extension back to the client. */
613 return SECSuccess;
616 /* ssl3_ValidateNextProtoNego checks that the given block of data is valid: none
617 * of the lengths may be 0 and the sum of the lengths must equal the length of
618 * the block. */
619 SECStatus
620 ssl3_ValidateNextProtoNego(const unsigned char* data, unsigned int length)
622 unsigned int offset = 0;
624 while (offset < length) {
625 unsigned int newOffset = offset + 1 + (unsigned int) data[offset];
626 /* Reject embedded nulls to protect against buggy applications that
627 * store protocol identifiers in null-terminated strings.
629 if (newOffset > length || data[offset] == 0) {
630 return SECFailure;
632 offset = newOffset;
635 return SECSuccess;
638 /* protocol selection handler for ALPN (server side) and NPN (client side) */
639 static SECStatus
640 ssl3_SelectAppProtocol(sslSocket *ss, PRUint16 ex_type, SECItem *data)
642 SECStatus rv;
643 unsigned char resultBuffer[255];
644 SECItem result = { siBuffer, resultBuffer, 0 };
646 rv = ssl3_ValidateNextProtoNego(data->data, data->len);
647 if (rv != SECSuccess) {
648 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
649 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
650 return rv;
653 PORT_Assert(ss->nextProtoCallback);
654 rv = ss->nextProtoCallback(ss->nextProtoArg, ss->fd, data->data, data->len,
655 result.data, &result.len, sizeof(resultBuffer));
656 if (rv != SECSuccess) {
657 /* Expect callback to call PORT_SetError() */
658 (void)SSL3_SendAlert(ss, alert_fatal, internal_error);
659 return SECFailure;
662 /* If the callback wrote more than allowed to |result| it has corrupted our
663 * stack. */
664 if (result.len > sizeof(resultBuffer)) {
665 PORT_SetError(SEC_ERROR_OUTPUT_LEN);
666 /* TODO: crash */
667 return SECFailure;
670 SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE);
672 if (ex_type == ssl_app_layer_protocol_xtn &&
673 ss->ssl3.nextProtoState != SSL_NEXT_PROTO_NEGOTIATED) {
674 /* The callback might say OK, but then it picks a default value - one
675 * that was not listed. That's OK for NPN, but not ALPN. */
676 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_NO_PROTOCOL);
677 (void)SSL3_SendAlert(ss, alert_fatal, no_application_protocol);
678 return SECFailure;
681 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
682 return SECITEM_CopyItem(NULL, &ss->ssl3.nextProto, &result);
685 /* handle an incoming ALPN extension at the server */
686 static SECStatus
687 ssl3_ServerHandleAppProtoXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data)
689 int count;
690 SECStatus rv;
692 /* We expressly don't want to allow ALPN on renegotiation,
693 * despite it being permitted by the spec. */
694 if (ss->firstHsDone || data->len == 0) {
695 /* Clients MUST send a non-empty ALPN extension. */
696 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
697 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
698 return SECFailure;
701 /* Unlike NPN, ALPN has extra redundant length information so that
702 * the extension is the same in both ClientHello and ServerHello. */
703 count = ssl3_ConsumeHandshakeNumber(ss, 2, &data->data, &data->len);
704 if (count != data->len) {
705 (void)ssl3_DecodeError(ss);
706 return SECFailure;
709 if (!ss->nextProtoCallback) {
710 /* we're not configured for it */
711 return SECSuccess;
714 rv = ssl3_SelectAppProtocol(ss, ex_type, data);
715 if (rv != SECSuccess) {
716 return rv;
719 /* prepare to send back a response, if we negotiated */
720 if (ss->ssl3.nextProtoState == SSL_NEXT_PROTO_NEGOTIATED) {
721 rv = ssl3_RegisterServerHelloExtensionSender(
722 ss, ex_type, ssl3_ServerSendAppProtoXtn);
723 if (rv != SECSuccess) {
724 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
725 (void)SSL3_SendAlert(ss, alert_fatal, internal_error);
726 return rv;
729 return SECSuccess;
732 static SECStatus
733 ssl3_ClientHandleNextProtoNegoXtn(sslSocket *ss, PRUint16 ex_type,
734 SECItem *data)
736 PORT_Assert(!ss->firstHsDone);
738 if (ssl3_ExtensionNegotiated(ss, ssl_app_layer_protocol_xtn)) {
739 /* If the server negotiated ALPN then it has already told us what
740 * protocol to use, so it doesn't make sense for us to try to negotiate
741 * a different one by sending the NPN handshake message. However, if
742 * we've negotiated NPN then we're required to send the NPN handshake
743 * message. Thus, these two extensions cannot both be negotiated on the
744 * same connection. */
745 PORT_SetError(SSL_ERROR_BAD_SERVER);
746 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
747 return SECFailure;
750 /* We should only get this call if we sent the extension, so
751 * ss->nextProtoCallback needs to be non-NULL. However, it is possible
752 * that an application erroneously cleared the callback between the time
753 * we sent the ClientHello and now. */
754 if (!ss->nextProtoCallback) {
755 PORT_Assert(0);
756 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_NO_CALLBACK);
757 (void)SSL3_SendAlert(ss, alert_fatal, internal_error);
758 return SECFailure;
761 return ssl3_SelectAppProtocol(ss, ex_type, data);
764 static SECStatus
765 ssl3_ClientHandleAppProtoXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data)
767 SECStatus rv;
768 PRInt32 list_len;
769 SECItem protocol_name;
771 if (ssl3_ExtensionNegotiated(ss, ssl_next_proto_nego_xtn)) {
772 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
773 return SECFailure;
776 /* The extension data from the server has the following format:
777 * uint16 name_list_len;
778 * uint8 len; // where len >= 1
779 * uint8 protocol_name[len]; */
780 if (data->len < 4 || data->len > 2 + 1 + 255) {
781 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
782 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
783 return SECFailure;
786 list_len = ssl3_ConsumeHandshakeNumber(ss, 2, &data->data, &data->len);
787 /* The list has to be the entire extension. */
788 if (list_len != data->len) {
789 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
790 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
791 return SECFailure;
794 rv = ssl3_ConsumeHandshakeVariable(ss, &protocol_name, 1,
795 &data->data, &data->len);
796 /* The list must have exactly one value. */
797 if (rv != SECSuccess || data->len != 0) {
798 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
799 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
800 return SECFailure;
803 SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE);
804 ss->ssl3.nextProtoState = SSL_NEXT_PROTO_SELECTED;
805 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
806 return SECITEM_CopyItem(NULL, &ss->ssl3.nextProto, &protocol_name);
809 static PRInt32
810 ssl3_ClientSendNextProtoNegoXtn(sslSocket * ss, PRBool append,
811 PRUint32 maxBytes)
813 PRInt32 extension_length;
815 /* Renegotiations do not send this extension. */
816 if (!ss->opt.enableNPN || !ss->nextProtoCallback || ss->firstHsDone) {
817 return 0;
820 extension_length = 4;
822 if (append && maxBytes >= extension_length) {
823 SECStatus rv;
824 rv = ssl3_AppendHandshakeNumber(ss, ssl_next_proto_nego_xtn, 2);
825 if (rv != SECSuccess)
826 goto loser;
827 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
828 if (rv != SECSuccess)
829 goto loser;
830 ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
831 ssl_next_proto_nego_xtn;
832 } else if (maxBytes < extension_length) {
833 return 0;
836 return extension_length;
838 loser:
839 return -1;
842 static PRInt32
843 ssl3_ClientSendAppProtoXtn(sslSocket * ss, PRBool append, PRUint32 maxBytes)
845 PRInt32 extension_length;
846 unsigned char *alpn_protos = NULL;
848 /* Renegotiations do not send this extension. */
849 if (!ss->opt.enableALPN || !ss->opt.nextProtoNego.data || ss->firstHsDone) {
850 return 0;
853 extension_length = 2 /* extension type */ + 2 /* extension length */ +
854 2 /* protocol name list length */ +
855 ss->opt.nextProtoNego.len;
857 if (append && maxBytes >= extension_length) {
858 /* NPN requires that the client's fallback protocol is first in the
859 * list. However, ALPN sends protocols in preference order. So we
860 * allocate a buffer and move the first protocol to the end of the
861 * list. */
862 SECStatus rv;
863 const unsigned int len = ss->opt.nextProtoNego.len;
865 alpn_protos = PORT_Alloc(len);
866 if (alpn_protos == NULL) {
867 return SECFailure;
869 if (len > 0) {
870 /* Each protocol string is prefixed with a single byte length. */
871 unsigned int i = ss->opt.nextProtoNego.data[0] + 1;
872 if (i <= len) {
873 memcpy(alpn_protos, &ss->opt.nextProtoNego.data[i], len - i);
874 memcpy(alpn_protos + len - i, ss->opt.nextProtoNego.data, i);
875 } else {
876 /* This seems to be invalid data so we'll send as-is. */
877 memcpy(alpn_protos, ss->opt.nextProtoNego.data, len);
881 rv = ssl3_AppendHandshakeNumber(ss, ssl_app_layer_protocol_xtn, 2);
882 if (rv != SECSuccess) {
883 goto loser;
885 rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2);
886 if (rv != SECSuccess) {
887 goto loser;
889 rv = ssl3_AppendHandshakeVariable(ss, alpn_protos, len, 2);
890 PORT_Free(alpn_protos);
891 alpn_protos = NULL;
892 if (rv != SECSuccess) {
893 goto loser;
895 ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
896 ssl_app_layer_protocol_xtn;
897 } else if (maxBytes < extension_length) {
898 return 0;
901 return extension_length;
903 loser:
904 if (alpn_protos) {
905 PORT_Free(alpn_protos);
907 return -1;
910 static PRInt32
911 ssl3_ServerSendAppProtoXtn(sslSocket * ss, PRBool append, PRUint32 maxBytes)
913 PRInt32 extension_length;
915 /* we're in over our heads if any of these fail */
916 PORT_Assert(ss->opt.enableALPN);
917 PORT_Assert(ss->ssl3.nextProto.data);
918 PORT_Assert(ss->ssl3.nextProto.len > 0);
919 PORT_Assert(ss->ssl3.nextProtoState == SSL_NEXT_PROTO_NEGOTIATED);
920 PORT_Assert(!ss->firstHsDone);
922 extension_length = 2 /* extension type */ + 2 /* extension length */ +
923 2 /* protocol name list */ + 1 /* name length */ +
924 ss->ssl3.nextProto.len;
926 if (append && maxBytes >= extension_length) {
927 SECStatus rv;
928 rv = ssl3_AppendHandshakeNumber(ss, ssl_app_layer_protocol_xtn, 2);
929 if (rv != SECSuccess) {
930 return -1;
932 rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2);
933 if (rv != SECSuccess) {
934 return -1;
936 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.nextProto.len + 1, 2);
937 if (rv != SECSuccess) {
938 return -1;
940 rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.nextProto.data,
941 ss->ssl3.nextProto.len, 1);
942 if (rv != SECSuccess) {
943 return -1;
945 } else if (maxBytes < extension_length) {
946 return 0;
949 return extension_length;
952 static SECStatus
953 ssl3_ClientHandleChannelIDXtn(sslSocket *ss, PRUint16 ex_type,
954 SECItem *data)
956 PORT_Assert(ss->getChannelID != NULL);
958 if (data->len) {
959 PORT_SetError(SSL_ERROR_BAD_CHANNEL_ID_DATA);
960 return SECFailure;
962 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
963 return SECSuccess;
966 static PRInt32
967 ssl3_ClientSendChannelIDXtn(sslSocket * ss, PRBool append,
968 PRUint32 maxBytes)
970 PRInt32 extension_length = 4;
972 if (!ss->getChannelID)
973 return 0;
975 if (maxBytes < extension_length) {
976 PORT_Assert(0);
977 return 0;
980 if (ss->sec.ci.sid->cached != never_cached &&
981 ss->sec.ci.sid->u.ssl3.originalHandshakeHash.len == 0) {
982 /* We can't do ChannelID on a connection if we're resuming and didn't
983 * do ChannelID on the original connection: without ChannelID on the
984 * original connection we didn't record the handshake hashes needed for
985 * the signature. */
986 return 0;
989 if (append) {
990 SECStatus rv;
991 rv = ssl3_AppendHandshakeNumber(ss, ssl_channel_id_xtn, 2);
992 if (rv != SECSuccess)
993 goto loser;
994 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
995 if (rv != SECSuccess)
996 goto loser;
997 ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
998 ssl_channel_id_xtn;
1001 return extension_length;
1003 loser:
1004 return -1;
1007 static SECStatus
1008 ssl3_ClientHandleStatusRequestXtn(sslSocket *ss, PRUint16 ex_type,
1009 SECItem *data)
1011 /* The echoed extension must be empty. */
1012 if (data->len != 0) {
1013 return SECSuccess; /* Ignore the extension. */
1016 /* Keep track of negotiated extensions. */
1017 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
1019 return SECSuccess;
1022 static PRInt32
1023 ssl3_ServerSendStatusRequestXtn(
1024 sslSocket * ss,
1025 PRBool append,
1026 PRUint32 maxBytes)
1028 PRInt32 extension_length;
1029 SECStatus rv;
1030 int i;
1031 PRBool haveStatus = PR_FALSE;
1033 for (i = kt_null; i < kt_kea_size; i++) {
1034 /* TODO: This is a temporary workaround.
1035 * The correct code needs to see if we have an OCSP response for
1036 * the server certificate being used, rather than if we have any
1037 * OCSP response. See also ssl3_SendCertificateStatus.
1039 if (ss->certStatusArray[i] && ss->certStatusArray[i]->len) {
1040 haveStatus = PR_TRUE;
1041 break;
1044 if (!haveStatus)
1045 return 0;
1047 extension_length = 2 + 2;
1048 if (append && maxBytes >= extension_length) {
1049 /* extension_type */
1050 rv = ssl3_AppendHandshakeNumber(ss, ssl_cert_status_xtn, 2);
1051 if (rv != SECSuccess)
1052 return -1;
1053 /* length of extension_data */
1054 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
1055 if (rv != SECSuccess)
1056 return -1;
1059 return extension_length;
1062 /* ssl3_ClientSendStatusRequestXtn builds the status_request extension on the
1063 * client side. See RFC 4366 section 3.6. */
1064 static PRInt32
1065 ssl3_ClientSendStatusRequestXtn(sslSocket * ss, PRBool append,
1066 PRUint32 maxBytes)
1068 PRInt32 extension_length;
1070 if (!ss->opt.enableOCSPStapling)
1071 return 0;
1073 /* extension_type (2-bytes) +
1074 * length(extension_data) (2-bytes) +
1075 * status_type (1) +
1076 * responder_id_list length (2) +
1077 * request_extensions length (2)
1079 extension_length = 9;
1081 if (append && maxBytes >= extension_length) {
1082 SECStatus rv;
1083 TLSExtensionData *xtnData;
1085 /* extension_type */
1086 rv = ssl3_AppendHandshakeNumber(ss, ssl_cert_status_xtn, 2);
1087 if (rv != SECSuccess)
1088 return -1;
1089 rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2);
1090 if (rv != SECSuccess)
1091 return -1;
1092 rv = ssl3_AppendHandshakeNumber(ss, 1 /* status_type ocsp */, 1);
1093 if (rv != SECSuccess)
1094 return -1;
1095 /* A zero length responder_id_list means that the responders are
1096 * implicitly known to the server. */
1097 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
1098 if (rv != SECSuccess)
1099 return -1;
1100 /* A zero length request_extensions means that there are no extensions.
1101 * Specifically, we don't set the id-pkix-ocsp-nonce extension. This
1102 * means that the server can replay a cached OCSP response to us. */
1103 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
1104 if (rv != SECSuccess)
1105 return -1;
1107 xtnData = &ss->xtnData;
1108 xtnData->advertised[xtnData->numAdvertised++] = ssl_cert_status_xtn;
1109 } else if (maxBytes < extension_length) {
1110 PORT_Assert(0);
1111 return 0;
1113 return extension_length;
1117 * NewSessionTicket
1118 * Called from ssl3_HandleFinished
1120 SECStatus
1121 ssl3_SendNewSessionTicket(sslSocket *ss)
1123 int i;
1124 SECStatus rv;
1125 NewSessionTicket ticket;
1126 SECItem plaintext;
1127 SECItem plaintext_item = {0, NULL, 0};
1128 SECItem ciphertext = {0, NULL, 0};
1129 PRUint32 ciphertext_length;
1130 PRBool ms_is_wrapped;
1131 unsigned char wrapped_ms[SSL3_MASTER_SECRET_LENGTH];
1132 SECItem ms_item = {0, NULL, 0};
1133 SSL3KEAType effectiveExchKeyType = ssl_kea_null;
1134 PRUint32 padding_length;
1135 PRUint32 message_length;
1136 PRUint32 cert_length;
1137 PRUint8 length_buf[4];
1138 PRUint32 now;
1139 PK11SymKey *aes_key_pkcs11;
1140 PK11SymKey *mac_key_pkcs11;
1141 #ifndef NO_PKCS11_BYPASS
1142 const unsigned char *aes_key;
1143 const unsigned char *mac_key;
1144 PRUint32 aes_key_length;
1145 PRUint32 mac_key_length;
1146 PRUint64 aes_ctx_buf[MAX_CIPHER_CONTEXT_LLONGS];
1147 AESContext *aes_ctx;
1148 const SECHashObject *hashObj = NULL;
1149 PRUint64 hmac_ctx_buf[MAX_MAC_CONTEXT_LLONGS];
1150 HMACContext *hmac_ctx;
1151 #endif
1152 CK_MECHANISM_TYPE cipherMech = CKM_AES_CBC;
1153 PK11Context *aes_ctx_pkcs11;
1154 CK_MECHANISM_TYPE macMech = CKM_SHA256_HMAC;
1155 PK11Context *hmac_ctx_pkcs11;
1156 unsigned char computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH];
1157 unsigned int computed_mac_length;
1158 unsigned char iv[AES_BLOCK_SIZE];
1159 SECItem ivItem;
1160 SECItem *srvName = NULL;
1161 PRUint32 srvNameLen = 0;
1162 CK_MECHANISM_TYPE msWrapMech = 0; /* dummy default value,
1163 * must be >= 0 */
1165 SSL_TRC(3, ("%d: SSL3[%d]: send session_ticket handshake",
1166 SSL_GETPID(), ss->fd));
1168 PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
1169 PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1171 ticket.ticket_lifetime_hint = TLS_EX_SESS_TICKET_LIFETIME_HINT;
1172 cert_length = (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) ?
1173 3 + ss->sec.ci.sid->peerCert->derCert.len : 0;
1175 /* Get IV and encryption keys */
1176 ivItem.data = iv;
1177 ivItem.len = sizeof(iv);
1178 rv = PK11_GenerateRandom(iv, sizeof(iv));
1179 if (rv != SECSuccess) goto loser;
1181 #ifndef NO_PKCS11_BYPASS
1182 if (ss->opt.bypassPKCS11) {
1183 rv = ssl3_GetSessionTicketKeys(&aes_key, &aes_key_length,
1184 &mac_key, &mac_key_length);
1185 } else
1186 #endif
1188 rv = ssl3_GetSessionTicketKeysPKCS11(ss, &aes_key_pkcs11,
1189 &mac_key_pkcs11);
1191 if (rv != SECSuccess) goto loser;
1193 if (ss->ssl3.pwSpec->msItem.len && ss->ssl3.pwSpec->msItem.data) {
1194 /* The master secret is available unwrapped. */
1195 ms_item.data = ss->ssl3.pwSpec->msItem.data;
1196 ms_item.len = ss->ssl3.pwSpec->msItem.len;
1197 ms_is_wrapped = PR_FALSE;
1198 } else {
1199 /* Extract the master secret wrapped. */
1200 sslSessionID sid;
1201 PORT_Memset(&sid, 0, sizeof(sslSessionID));
1203 if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) {
1204 effectiveExchKeyType = kt_rsa;
1205 } else {
1206 effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType;
1209 rv = ssl3_CacheWrappedMasterSecret(ss, &sid, ss->ssl3.pwSpec,
1210 effectiveExchKeyType);
1211 if (rv == SECSuccess) {
1212 if (sid.u.ssl3.keys.wrapped_master_secret_len > sizeof(wrapped_ms))
1213 goto loser;
1214 memcpy(wrapped_ms, sid.u.ssl3.keys.wrapped_master_secret,
1215 sid.u.ssl3.keys.wrapped_master_secret_len);
1216 ms_item.data = wrapped_ms;
1217 ms_item.len = sid.u.ssl3.keys.wrapped_master_secret_len;
1218 msWrapMech = sid.u.ssl3.masterWrapMech;
1219 } else {
1220 /* TODO: else send an empty ticket. */
1221 goto loser;
1223 ms_is_wrapped = PR_TRUE;
1225 /* Prep to send negotiated name */
1226 srvName = &ss->ssl3.pwSpec->srvVirtName;
1227 if (srvName->data && srvName->len) {
1228 srvNameLen = 2 + srvName->len; /* len bytes + name len */
1231 ciphertext_length =
1232 sizeof(PRUint16) /* ticket_version */
1233 + sizeof(SSL3ProtocolVersion) /* ssl_version */
1234 + sizeof(ssl3CipherSuite) /* ciphersuite */
1235 + 1 /* compression */
1236 + 10 /* cipher spec parameters */
1237 + 1 /* SessionTicket.ms_is_wrapped */
1238 + 1 /* effectiveExchKeyType */
1239 + 4 /* msWrapMech */
1240 + 2 /* master_secret.length */
1241 + ms_item.len /* master_secret */
1242 + 1 /* client_auth_type */
1243 + cert_length /* cert */
1244 + 1 /* server name type */
1245 + srvNameLen /* name len + length field */
1246 + sizeof(ticket.ticket_lifetime_hint);
1247 padding_length = AES_BLOCK_SIZE -
1248 (ciphertext_length % AES_BLOCK_SIZE);
1249 ciphertext_length += padding_length;
1251 message_length =
1252 sizeof(ticket.ticket_lifetime_hint) /* ticket_lifetime_hint */
1253 + 2 /* length field for NewSessionTicket.ticket */
1254 + SESS_TICKET_KEY_NAME_LEN /* key_name */
1255 + AES_BLOCK_SIZE /* iv */
1256 + 2 /* length field for NewSessionTicket.ticket.encrypted_state */
1257 + ciphertext_length /* encrypted_state */
1258 + TLS_EX_SESS_TICKET_MAC_LENGTH; /* mac */
1260 if (SECITEM_AllocItem(NULL, &plaintext_item, ciphertext_length) == NULL)
1261 goto loser;
1263 plaintext = plaintext_item;
1265 /* ticket_version */
1266 rv = ssl3_AppendNumberToItem(&plaintext, TLS_EX_SESS_TICKET_VERSION,
1267 sizeof(PRUint16));
1268 if (rv != SECSuccess) goto loser;
1270 /* ssl_version */
1271 rv = ssl3_AppendNumberToItem(&plaintext, ss->version,
1272 sizeof(SSL3ProtocolVersion));
1273 if (rv != SECSuccess) goto loser;
1275 /* ciphersuite */
1276 rv = ssl3_AppendNumberToItem(&plaintext, ss->ssl3.hs.cipher_suite,
1277 sizeof(ssl3CipherSuite));
1278 if (rv != SECSuccess) goto loser;
1280 /* compression */
1281 rv = ssl3_AppendNumberToItem(&plaintext, ss->ssl3.hs.compression, 1);
1282 if (rv != SECSuccess) goto loser;
1284 /* cipher spec parameters */
1285 rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.authAlgorithm, 1);
1286 if (rv != SECSuccess) goto loser;
1287 rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.authKeyBits, 4);
1288 if (rv != SECSuccess) goto loser;
1289 rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.keaType, 1);
1290 if (rv != SECSuccess) goto loser;
1291 rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.keaKeyBits, 4);
1292 if (rv != SECSuccess) goto loser;
1294 /* master_secret */
1295 rv = ssl3_AppendNumberToItem(&plaintext, ms_is_wrapped, 1);
1296 if (rv != SECSuccess) goto loser;
1297 rv = ssl3_AppendNumberToItem(&plaintext, effectiveExchKeyType, 1);
1298 if (rv != SECSuccess) goto loser;
1299 rv = ssl3_AppendNumberToItem(&plaintext, msWrapMech, 4);
1300 if (rv != SECSuccess) goto loser;
1301 rv = ssl3_AppendNumberToItem(&plaintext, ms_item.len, 2);
1302 if (rv != SECSuccess) goto loser;
1303 rv = ssl3_AppendToItem(&plaintext, ms_item.data, ms_item.len);
1304 if (rv != SECSuccess) goto loser;
1306 /* client_identity */
1307 if (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) {
1308 rv = ssl3_AppendNumberToItem(&plaintext, CLIENT_AUTH_CERTIFICATE, 1);
1309 if (rv != SECSuccess) goto loser;
1310 rv = ssl3_AppendNumberToItem(&plaintext,
1311 ss->sec.ci.sid->peerCert->derCert.len, 3);
1312 if (rv != SECSuccess) goto loser;
1313 rv = ssl3_AppendToItem(&plaintext,
1314 ss->sec.ci.sid->peerCert->derCert.data,
1315 ss->sec.ci.sid->peerCert->derCert.len);
1316 if (rv != SECSuccess) goto loser;
1317 } else {
1318 rv = ssl3_AppendNumberToItem(&plaintext, 0, 1);
1319 if (rv != SECSuccess) goto loser;
1322 /* timestamp */
1323 now = ssl_Time();
1324 rv = ssl3_AppendNumberToItem(&plaintext, now,
1325 sizeof(ticket.ticket_lifetime_hint));
1326 if (rv != SECSuccess) goto loser;
1328 if (srvNameLen) {
1329 /* Name Type (sni_host_name) */
1330 rv = ssl3_AppendNumberToItem(&plaintext, srvName->type, 1);
1331 if (rv != SECSuccess) goto loser;
1332 /* HostName (length and value) */
1333 rv = ssl3_AppendNumberToItem(&plaintext, srvName->len, 2);
1334 if (rv != SECSuccess) goto loser;
1335 rv = ssl3_AppendToItem(&plaintext, srvName->data, srvName->len);
1336 if (rv != SECSuccess) goto loser;
1337 } else {
1338 /* No Name */
1339 rv = ssl3_AppendNumberToItem(&plaintext, (char)TLS_STE_NO_SERVER_NAME,
1341 if (rv != SECSuccess) goto loser;
1344 PORT_Assert(plaintext.len == padding_length);
1345 for (i = 0; i < padding_length; i++)
1346 plaintext.data[i] = (unsigned char)padding_length;
1348 if (SECITEM_AllocItem(NULL, &ciphertext, ciphertext_length) == NULL) {
1349 rv = SECFailure;
1350 goto loser;
1353 /* Generate encrypted portion of ticket. */
1354 #ifndef NO_PKCS11_BYPASS
1355 if (ss->opt.bypassPKCS11) {
1356 aes_ctx = (AESContext *)aes_ctx_buf;
1357 rv = AES_InitContext(aes_ctx, aes_key, aes_key_length, iv,
1358 NSS_AES_CBC, 1, AES_BLOCK_SIZE);
1359 if (rv != SECSuccess) goto loser;
1361 rv = AES_Encrypt(aes_ctx, ciphertext.data, &ciphertext.len,
1362 ciphertext.len, plaintext_item.data,
1363 plaintext_item.len);
1364 if (rv != SECSuccess) goto loser;
1365 } else
1366 #endif
1368 aes_ctx_pkcs11 = PK11_CreateContextBySymKey(cipherMech,
1369 CKA_ENCRYPT, aes_key_pkcs11, &ivItem);
1370 if (!aes_ctx_pkcs11)
1371 goto loser;
1373 rv = PK11_CipherOp(aes_ctx_pkcs11, ciphertext.data,
1374 (int *)&ciphertext.len, ciphertext.len,
1375 plaintext_item.data, plaintext_item.len);
1376 PK11_Finalize(aes_ctx_pkcs11);
1377 PK11_DestroyContext(aes_ctx_pkcs11, PR_TRUE);
1378 if (rv != SECSuccess) goto loser;
1381 /* Convert ciphertext length to network order. */
1382 length_buf[0] = (ciphertext.len >> 8) & 0xff;
1383 length_buf[1] = (ciphertext.len ) & 0xff;
1385 /* Compute MAC. */
1386 #ifndef NO_PKCS11_BYPASS
1387 if (ss->opt.bypassPKCS11) {
1388 hmac_ctx = (HMACContext *)hmac_ctx_buf;
1389 hashObj = HASH_GetRawHashObject(HASH_AlgSHA256);
1390 if (HMAC_Init(hmac_ctx, hashObj, mac_key,
1391 mac_key_length, PR_FALSE) != SECSuccess)
1392 goto loser;
1394 HMAC_Begin(hmac_ctx);
1395 HMAC_Update(hmac_ctx, key_name, SESS_TICKET_KEY_NAME_LEN);
1396 HMAC_Update(hmac_ctx, iv, sizeof(iv));
1397 HMAC_Update(hmac_ctx, (unsigned char *)length_buf, 2);
1398 HMAC_Update(hmac_ctx, ciphertext.data, ciphertext.len);
1399 HMAC_Finish(hmac_ctx, computed_mac, &computed_mac_length,
1400 sizeof(computed_mac));
1401 } else
1402 #endif
1404 SECItem macParam;
1405 macParam.data = NULL;
1406 macParam.len = 0;
1407 hmac_ctx_pkcs11 = PK11_CreateContextBySymKey(macMech,
1408 CKA_SIGN, mac_key_pkcs11, &macParam);
1409 if (!hmac_ctx_pkcs11)
1410 goto loser;
1412 rv = PK11_DigestBegin(hmac_ctx_pkcs11);
1413 rv = PK11_DigestOp(hmac_ctx_pkcs11, key_name,
1414 SESS_TICKET_KEY_NAME_LEN);
1415 rv = PK11_DigestOp(hmac_ctx_pkcs11, iv, sizeof(iv));
1416 rv = PK11_DigestOp(hmac_ctx_pkcs11, (unsigned char *)length_buf, 2);
1417 rv = PK11_DigestOp(hmac_ctx_pkcs11, ciphertext.data, ciphertext.len);
1418 rv = PK11_DigestFinal(hmac_ctx_pkcs11, computed_mac,
1419 &computed_mac_length, sizeof(computed_mac));
1420 PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE);
1421 if (rv != SECSuccess) goto loser;
1424 /* Serialize the handshake message. */
1425 rv = ssl3_AppendHandshakeHeader(ss, new_session_ticket, message_length);
1426 if (rv != SECSuccess) goto loser;
1428 rv = ssl3_AppendHandshakeNumber(ss, ticket.ticket_lifetime_hint,
1429 sizeof(ticket.ticket_lifetime_hint));
1430 if (rv != SECSuccess) goto loser;
1432 rv = ssl3_AppendHandshakeNumber(ss,
1433 message_length - sizeof(ticket.ticket_lifetime_hint) - 2, 2);
1434 if (rv != SECSuccess) goto loser;
1436 rv = ssl3_AppendHandshake(ss, key_name, SESS_TICKET_KEY_NAME_LEN);
1437 if (rv != SECSuccess) goto loser;
1439 rv = ssl3_AppendHandshake(ss, iv, sizeof(iv));
1440 if (rv != SECSuccess) goto loser;
1442 rv = ssl3_AppendHandshakeVariable(ss, ciphertext.data, ciphertext.len, 2);
1443 if (rv != SECSuccess) goto loser;
1445 rv = ssl3_AppendHandshake(ss, computed_mac, computed_mac_length);
1446 if (rv != SECSuccess) goto loser;
1448 loser:
1449 if (plaintext_item.data)
1450 SECITEM_FreeItem(&plaintext_item, PR_FALSE);
1451 if (ciphertext.data)
1452 SECITEM_FreeItem(&ciphertext, PR_FALSE);
1454 return rv;
1457 /* When a client receives a SessionTicket extension a NewSessionTicket
1458 * message is expected during the handshake.
1460 SECStatus
1461 ssl3_ClientHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type,
1462 SECItem *data)
1464 if (data->len != 0) {
1465 return SECSuccess; /* Ignore the extension. */
1468 /* Keep track of negotiated extensions. */
1469 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
1470 return SECSuccess;
1473 SECStatus
1474 ssl3_ServerHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type,
1475 SECItem *data)
1477 SECStatus rv;
1478 SECItem *decrypted_state = NULL;
1479 SessionTicket *parsed_session_ticket = NULL;
1480 sslSessionID *sid = NULL;
1481 SSL3Statistics *ssl3stats;
1483 /* Ignore the SessionTicket extension if processing is disabled. */
1484 if (!ss->opt.enableSessionTickets) {
1485 return SECSuccess;
1488 /* Keep track of negotiated extensions. */
1489 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
1491 /* Parse the received ticket sent in by the client. We are
1492 * lenient about some parse errors, falling back to a fullshake
1493 * instead of terminating the current connection.
1495 if (data->len == 0) {
1496 ss->xtnData.emptySessionTicket = PR_TRUE;
1497 } else {
1498 int i;
1499 SECItem extension_data;
1500 EncryptedSessionTicket enc_session_ticket;
1501 unsigned char computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH];
1502 unsigned int computed_mac_length;
1503 #ifndef NO_PKCS11_BYPASS
1504 const SECHashObject *hashObj;
1505 const unsigned char *aes_key;
1506 const unsigned char *mac_key;
1507 PRUint32 aes_key_length;
1508 PRUint32 mac_key_length;
1509 PRUint64 hmac_ctx_buf[MAX_MAC_CONTEXT_LLONGS];
1510 HMACContext *hmac_ctx;
1511 PRUint64 aes_ctx_buf[MAX_CIPHER_CONTEXT_LLONGS];
1512 AESContext *aes_ctx;
1513 #endif
1514 PK11SymKey *aes_key_pkcs11;
1515 PK11SymKey *mac_key_pkcs11;
1516 PK11Context *hmac_ctx_pkcs11;
1517 CK_MECHANISM_TYPE macMech = CKM_SHA256_HMAC;
1518 PK11Context *aes_ctx_pkcs11;
1519 CK_MECHANISM_TYPE cipherMech = CKM_AES_CBC;
1520 unsigned char * padding;
1521 PRUint32 padding_length;
1522 unsigned char *buffer;
1523 unsigned int buffer_len;
1524 PRInt32 temp;
1525 SECItem cert_item;
1526 PRInt8 nameType = TLS_STE_NO_SERVER_NAME;
1528 /* Turn off stateless session resumption if the client sends a
1529 * SessionTicket extension, even if the extension turns out to be
1530 * malformed (ss->sec.ci.sid is non-NULL when doing session
1531 * renegotiation.)
1533 if (ss->sec.ci.sid != NULL) {
1534 if (ss->sec.uncache)
1535 ss->sec.uncache(ss->sec.ci.sid);
1536 ssl_FreeSID(ss->sec.ci.sid);
1537 ss->sec.ci.sid = NULL;
1540 extension_data.data = data->data; /* Keep a copy for future use. */
1541 extension_data.len = data->len;
1543 if (ssl3_ParseEncryptedSessionTicket(ss, data, &enc_session_ticket)
1544 != SECSuccess) {
1545 return SECSuccess; /* Pretend it isn't there */
1548 /* Get session ticket keys. */
1549 #ifndef NO_PKCS11_BYPASS
1550 if (ss->opt.bypassPKCS11) {
1551 rv = ssl3_GetSessionTicketKeys(&aes_key, &aes_key_length,
1552 &mac_key, &mac_key_length);
1553 } else
1554 #endif
1556 rv = ssl3_GetSessionTicketKeysPKCS11(ss, &aes_key_pkcs11,
1557 &mac_key_pkcs11);
1559 if (rv != SECSuccess) {
1560 SSL_DBG(("%d: SSL[%d]: Unable to get/generate session ticket keys.",
1561 SSL_GETPID(), ss->fd));
1562 goto loser;
1565 /* If the ticket sent by the client was generated under a key different
1566 * from the one we have, bypass ticket processing.
1568 if (PORT_Memcmp(enc_session_ticket.key_name, key_name,
1569 SESS_TICKET_KEY_NAME_LEN) != 0) {
1570 SSL_DBG(("%d: SSL[%d]: Session ticket key_name sent mismatch.",
1571 SSL_GETPID(), ss->fd));
1572 goto no_ticket;
1575 /* Verify the MAC on the ticket. MAC verification may also
1576 * fail if the MAC key has been recently refreshed.
1578 #ifndef NO_PKCS11_BYPASS
1579 if (ss->opt.bypassPKCS11) {
1580 hmac_ctx = (HMACContext *)hmac_ctx_buf;
1581 hashObj = HASH_GetRawHashObject(HASH_AlgSHA256);
1582 if (HMAC_Init(hmac_ctx, hashObj, mac_key,
1583 sizeof(session_ticket_mac_key), PR_FALSE) != SECSuccess)
1584 goto no_ticket;
1585 HMAC_Begin(hmac_ctx);
1586 HMAC_Update(hmac_ctx, extension_data.data,
1587 extension_data.len - TLS_EX_SESS_TICKET_MAC_LENGTH);
1588 if (HMAC_Finish(hmac_ctx, computed_mac, &computed_mac_length,
1589 sizeof(computed_mac)) != SECSuccess)
1590 goto no_ticket;
1591 } else
1592 #endif
1594 SECItem macParam;
1595 macParam.data = NULL;
1596 macParam.len = 0;
1597 hmac_ctx_pkcs11 = PK11_CreateContextBySymKey(macMech,
1598 CKA_SIGN, mac_key_pkcs11, &macParam);
1599 if (!hmac_ctx_pkcs11) {
1600 SSL_DBG(("%d: SSL[%d]: Unable to create HMAC context: %d.",
1601 SSL_GETPID(), ss->fd, PORT_GetError()));
1602 goto no_ticket;
1603 } else {
1604 SSL_DBG(("%d: SSL[%d]: Successfully created HMAC context.",
1605 SSL_GETPID(), ss->fd));
1607 rv = PK11_DigestBegin(hmac_ctx_pkcs11);
1608 rv = PK11_DigestOp(hmac_ctx_pkcs11, extension_data.data,
1609 extension_data.len - TLS_EX_SESS_TICKET_MAC_LENGTH);
1610 if (rv != SECSuccess) {
1611 PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE);
1612 goto no_ticket;
1614 rv = PK11_DigestFinal(hmac_ctx_pkcs11, computed_mac,
1615 &computed_mac_length, sizeof(computed_mac));
1616 PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE);
1617 if (rv != SECSuccess)
1618 goto no_ticket;
1620 if (NSS_SecureMemcmp(computed_mac, enc_session_ticket.mac,
1621 computed_mac_length) != 0) {
1622 SSL_DBG(("%d: SSL[%d]: Session ticket MAC mismatch.",
1623 SSL_GETPID(), ss->fd));
1624 goto no_ticket;
1627 /* We ignore key_name for now.
1628 * This is ok as MAC verification succeeded.
1631 /* Decrypt the ticket. */
1633 /* Plaintext is shorter than the ciphertext due to padding. */
1634 decrypted_state = SECITEM_AllocItem(NULL, NULL,
1635 enc_session_ticket.encrypted_state.len);
1637 #ifndef NO_PKCS11_BYPASS
1638 if (ss->opt.bypassPKCS11) {
1639 aes_ctx = (AESContext *)aes_ctx_buf;
1640 rv = AES_InitContext(aes_ctx, aes_key,
1641 sizeof(session_ticket_enc_key), enc_session_ticket.iv,
1642 NSS_AES_CBC, 0,AES_BLOCK_SIZE);
1643 if (rv != SECSuccess) {
1644 SSL_DBG(("%d: SSL[%d]: Unable to create AES context.",
1645 SSL_GETPID(), ss->fd));
1646 goto no_ticket;
1649 rv = AES_Decrypt(aes_ctx, decrypted_state->data,
1650 &decrypted_state->len, decrypted_state->len,
1651 enc_session_ticket.encrypted_state.data,
1652 enc_session_ticket.encrypted_state.len);
1653 if (rv != SECSuccess)
1654 goto no_ticket;
1655 } else
1656 #endif
1658 SECItem ivItem;
1659 ivItem.data = enc_session_ticket.iv;
1660 ivItem.len = AES_BLOCK_SIZE;
1661 aes_ctx_pkcs11 = PK11_CreateContextBySymKey(cipherMech,
1662 CKA_DECRYPT, aes_key_pkcs11, &ivItem);
1663 if (!aes_ctx_pkcs11) {
1664 SSL_DBG(("%d: SSL[%d]: Unable to create AES context.",
1665 SSL_GETPID(), ss->fd));
1666 goto no_ticket;
1669 rv = PK11_CipherOp(aes_ctx_pkcs11, decrypted_state->data,
1670 (int *)&decrypted_state->len, decrypted_state->len,
1671 enc_session_ticket.encrypted_state.data,
1672 enc_session_ticket.encrypted_state.len);
1673 PK11_Finalize(aes_ctx_pkcs11);
1674 PK11_DestroyContext(aes_ctx_pkcs11, PR_TRUE);
1675 if (rv != SECSuccess)
1676 goto no_ticket;
1679 /* Check padding. */
1680 padding_length =
1681 (PRUint32)decrypted_state->data[decrypted_state->len - 1];
1682 if (padding_length == 0 || padding_length > AES_BLOCK_SIZE)
1683 goto no_ticket;
1685 padding = &decrypted_state->data[decrypted_state->len - padding_length];
1686 for (i = 0; i < padding_length; i++, padding++) {
1687 if (padding_length != (PRUint32)*padding)
1688 goto no_ticket;
1691 /* Deserialize session state. */
1692 buffer = decrypted_state->data;
1693 buffer_len = decrypted_state->len;
1695 parsed_session_ticket = PORT_ZAlloc(sizeof(SessionTicket));
1696 if (parsed_session_ticket == NULL) {
1697 rv = SECFailure;
1698 goto loser;
1701 /* Read ticket_version (which is ignored for now.) */
1702 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1703 if (temp < 0) goto no_ticket;
1704 parsed_session_ticket->ticket_version = (SSL3ProtocolVersion)temp;
1706 /* Read SSLVersion. */
1707 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1708 if (temp < 0) goto no_ticket;
1709 parsed_session_ticket->ssl_version = (SSL3ProtocolVersion)temp;
1711 /* Read cipher_suite. */
1712 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1713 if (temp < 0) goto no_ticket;
1714 parsed_session_ticket->cipher_suite = (ssl3CipherSuite)temp;
1716 /* Read compression_method. */
1717 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1718 if (temp < 0) goto no_ticket;
1719 parsed_session_ticket->compression_method = (SSLCompressionMethod)temp;
1721 /* Read cipher spec parameters. */
1722 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1723 if (temp < 0) goto no_ticket;
1724 parsed_session_ticket->authAlgorithm = (SSLSignType)temp;
1725 temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1726 if (temp < 0) goto no_ticket;
1727 parsed_session_ticket->authKeyBits = (PRUint32)temp;
1728 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1729 if (temp < 0) goto no_ticket;
1730 parsed_session_ticket->keaType = (SSLKEAType)temp;
1731 temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1732 if (temp < 0) goto no_ticket;
1733 parsed_session_ticket->keaKeyBits = (PRUint32)temp;
1735 /* Read wrapped master_secret. */
1736 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1737 if (temp < 0) goto no_ticket;
1738 parsed_session_ticket->ms_is_wrapped = (PRBool)temp;
1740 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1741 if (temp < 0) goto no_ticket;
1742 parsed_session_ticket->exchKeyType = (SSL3KEAType)temp;
1744 temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1745 if (temp < 0) goto no_ticket;
1746 parsed_session_ticket->msWrapMech = (CK_MECHANISM_TYPE)temp;
1748 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1749 if (temp < 0) goto no_ticket;
1750 parsed_session_ticket->ms_length = (PRUint16)temp;
1751 if (parsed_session_ticket->ms_length == 0 || /* sanity check MS. */
1752 parsed_session_ticket->ms_length >
1753 sizeof(parsed_session_ticket->master_secret))
1754 goto no_ticket;
1756 /* Allow for the wrapped master secret to be longer. */
1757 if (buffer_len < parsed_session_ticket->ms_length)
1758 goto no_ticket;
1759 PORT_Memcpy(parsed_session_ticket->master_secret, buffer,
1760 parsed_session_ticket->ms_length);
1761 buffer += parsed_session_ticket->ms_length;
1762 buffer_len -= parsed_session_ticket->ms_length;
1764 /* Read client_identity */
1765 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1766 if (temp < 0)
1767 goto no_ticket;
1768 parsed_session_ticket->client_identity.client_auth_type =
1769 (ClientAuthenticationType)temp;
1770 switch(parsed_session_ticket->client_identity.client_auth_type) {
1771 case CLIENT_AUTH_ANONYMOUS:
1772 break;
1773 case CLIENT_AUTH_CERTIFICATE:
1774 rv = ssl3_ConsumeHandshakeVariable(ss, &cert_item, 3,
1775 &buffer, &buffer_len);
1776 if (rv != SECSuccess) goto no_ticket;
1777 rv = SECITEM_CopyItem(NULL, &parsed_session_ticket->peer_cert,
1778 &cert_item);
1779 if (rv != SECSuccess) goto no_ticket;
1780 break;
1781 default:
1782 goto no_ticket;
1784 /* Read timestamp. */
1785 temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1786 if (temp < 0)
1787 goto no_ticket;
1788 parsed_session_ticket->timestamp = (PRUint32)temp;
1790 /* Read server name */
1791 nameType =
1792 ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1793 if (nameType != TLS_STE_NO_SERVER_NAME) {
1794 SECItem name_item;
1795 rv = ssl3_ConsumeHandshakeVariable(ss, &name_item, 2, &buffer,
1796 &buffer_len);
1797 if (rv != SECSuccess) goto no_ticket;
1798 rv = SECITEM_CopyItem(NULL, &parsed_session_ticket->srvName,
1799 &name_item);
1800 if (rv != SECSuccess) goto no_ticket;
1801 parsed_session_ticket->srvName.type = nameType;
1804 /* Done parsing. Check that all bytes have been consumed. */
1805 if (buffer_len != padding_length)
1806 goto no_ticket;
1808 /* Use the ticket if it has not expired, otherwise free the allocated
1809 * memory since the ticket is of no use.
1811 if (parsed_session_ticket->timestamp != 0 &&
1812 parsed_session_ticket->timestamp +
1813 TLS_EX_SESS_TICKET_LIFETIME_HINT > ssl_Time()) {
1815 sid = ssl3_NewSessionID(ss, PR_TRUE);
1816 if (sid == NULL) {
1817 rv = SECFailure;
1818 goto loser;
1821 /* Copy over parameters. */
1822 sid->version = parsed_session_ticket->ssl_version;
1823 sid->u.ssl3.cipherSuite = parsed_session_ticket->cipher_suite;
1824 sid->u.ssl3.compression = parsed_session_ticket->compression_method;
1825 sid->authAlgorithm = parsed_session_ticket->authAlgorithm;
1826 sid->authKeyBits = parsed_session_ticket->authKeyBits;
1827 sid->keaType = parsed_session_ticket->keaType;
1828 sid->keaKeyBits = parsed_session_ticket->keaKeyBits;
1830 /* Copy master secret. */
1831 #ifndef NO_PKCS11_BYPASS
1832 if (ss->opt.bypassPKCS11 &&
1833 parsed_session_ticket->ms_is_wrapped)
1834 goto no_ticket;
1835 #endif
1836 if (parsed_session_ticket->ms_length >
1837 sizeof(sid->u.ssl3.keys.wrapped_master_secret))
1838 goto no_ticket;
1839 PORT_Memcpy(sid->u.ssl3.keys.wrapped_master_secret,
1840 parsed_session_ticket->master_secret,
1841 parsed_session_ticket->ms_length);
1842 sid->u.ssl3.keys.wrapped_master_secret_len =
1843 parsed_session_ticket->ms_length;
1844 sid->u.ssl3.exchKeyType = parsed_session_ticket->exchKeyType;
1845 sid->u.ssl3.masterWrapMech = parsed_session_ticket->msWrapMech;
1846 sid->u.ssl3.keys.msIsWrapped =
1847 parsed_session_ticket->ms_is_wrapped;
1848 sid->u.ssl3.masterValid = PR_TRUE;
1849 sid->u.ssl3.keys.resumable = PR_TRUE;
1851 /* Copy over client cert from session ticket if there is one. */
1852 if (parsed_session_ticket->peer_cert.data != NULL) {
1853 if (sid->peerCert != NULL)
1854 CERT_DestroyCertificate(sid->peerCert);
1855 sid->peerCert = CERT_NewTempCertificate(ss->dbHandle,
1856 &parsed_session_ticket->peer_cert, NULL, PR_FALSE, PR_TRUE);
1857 if (sid->peerCert == NULL) {
1858 rv = SECFailure;
1859 goto loser;
1862 if (parsed_session_ticket->srvName.data != NULL) {
1863 sid->u.ssl3.srvName = parsed_session_ticket->srvName;
1865 ss->statelessResume = PR_TRUE;
1866 ss->sec.ci.sid = sid;
1870 if (0) {
1871 no_ticket:
1872 SSL_DBG(("%d: SSL[%d]: Session ticket parsing failed.",
1873 SSL_GETPID(), ss->fd));
1874 ssl3stats = SSL_GetStatistics();
1875 SSL_AtomicIncrementLong(& ssl3stats->hch_sid_ticket_parse_failures );
1877 rv = SECSuccess;
1879 loser:
1880 /* ss->sec.ci.sid == sid if it did NOT come here via goto statement
1881 * in that case do not free sid
1883 if (sid && (ss->sec.ci.sid != sid)) {
1884 ssl_FreeSID(sid);
1885 sid = NULL;
1887 if (decrypted_state != NULL) {
1888 SECITEM_FreeItem(decrypted_state, PR_TRUE);
1889 decrypted_state = NULL;
1892 if (parsed_session_ticket != NULL) {
1893 if (parsed_session_ticket->peer_cert.data) {
1894 SECITEM_FreeItem(&parsed_session_ticket->peer_cert, PR_FALSE);
1896 PORT_ZFree(parsed_session_ticket, sizeof(SessionTicket));
1899 return rv;
1903 * Read bytes. Using this function means the SECItem structure
1904 * cannot be freed. The caller is expected to call this function
1905 * on a shallow copy of the structure.
1907 static SECStatus
1908 ssl3_ConsumeFromItem(SECItem *item, unsigned char **buf, PRUint32 bytes)
1910 if (bytes > item->len)
1911 return SECFailure;
1913 *buf = item->data;
1914 item->data += bytes;
1915 item->len -= bytes;
1916 return SECSuccess;
1919 static SECStatus
1920 ssl3_ParseEncryptedSessionTicket(sslSocket *ss, SECItem *data,
1921 EncryptedSessionTicket *enc_session_ticket)
1923 if (ssl3_ConsumeFromItem(data, &enc_session_ticket->key_name,
1924 SESS_TICKET_KEY_NAME_LEN) != SECSuccess)
1925 return SECFailure;
1926 if (ssl3_ConsumeFromItem(data, &enc_session_ticket->iv,
1927 AES_BLOCK_SIZE) != SECSuccess)
1928 return SECFailure;
1929 if (ssl3_ConsumeHandshakeVariable(ss, &enc_session_ticket->encrypted_state,
1930 2, &data->data, &data->len) != SECSuccess)
1931 return SECFailure;
1932 if (ssl3_ConsumeFromItem(data, &enc_session_ticket->mac,
1933 TLS_EX_SESS_TICKET_MAC_LENGTH) != SECSuccess)
1934 return SECFailure;
1935 if (data->len != 0) /* Make sure that we have consumed all bytes. */
1936 return SECFailure;
1938 return SECSuccess;
1941 /* go through hello extensions in buffer "b".
1942 * For each one, find the extension handler in the table, and
1943 * if present, invoke that handler.
1944 * Servers ignore any extensions with unknown extension types.
1945 * Clients reject any extensions with unadvertised extension types.
1947 SECStatus
1948 ssl3_HandleHelloExtensions(sslSocket *ss, SSL3Opaque **b, PRUint32 *length)
1950 const ssl3HelloExtensionHandler * handlers;
1952 if (ss->sec.isServer) {
1953 handlers = clientHelloHandlers;
1954 } else if (ss->version > SSL_LIBRARY_VERSION_3_0) {
1955 handlers = serverHelloHandlersTLS;
1956 } else {
1957 handlers = serverHelloHandlersSSL3;
1960 while (*length) {
1961 const ssl3HelloExtensionHandler * handler;
1962 SECStatus rv;
1963 PRInt32 extension_type;
1964 SECItem extension_data;
1966 /* Get the extension's type field */
1967 extension_type = ssl3_ConsumeHandshakeNumber(ss, 2, b, length);
1968 if (extension_type < 0) /* failure to decode extension_type */
1969 return SECFailure; /* alert already sent */
1971 /* get the data for this extension, so we can pass it or skip it. */
1972 rv = ssl3_ConsumeHandshakeVariable(ss, &extension_data, 2, b, length);
1973 if (rv != SECSuccess)
1974 return rv; /* alert already sent */
1976 /* Check whether the server sent an extension which was not advertised
1977 * in the ClientHello.
1979 if (!ss->sec.isServer &&
1980 !ssl3_ClientExtensionAdvertised(ss, extension_type)) {
1981 (void)SSL3_SendAlert(ss, alert_fatal, unsupported_extension);
1982 return SECFailure;
1985 /* Check whether an extension has been sent multiple times. */
1986 if (ssl3_ExtensionNegotiated(ss, extension_type)) {
1987 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
1988 return SECFailure;
1991 /* find extension_type in table of Hello Extension Handlers */
1992 for (handler = handlers; handler->ex_type >= 0; handler++) {
1993 /* if found, call this handler */
1994 if (handler->ex_type == extension_type) {
1995 rv = (*handler->ex_handler)(ss, (PRUint16)extension_type,
1996 &extension_data);
1997 if (rv != SECSuccess) {
1998 if (!ss->ssl3.fatalAlertSent) {
1999 /* send a generic alert if the handler didn't already */
2000 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
2002 return SECFailure;
2007 return SECSuccess;
2010 /* Add a callback function to the table of senders of server hello extensions.
2012 SECStatus
2013 ssl3_RegisterServerHelloExtensionSender(sslSocket *ss, PRUint16 ex_type,
2014 ssl3HelloExtensionSenderFunc cb)
2016 int i;
2017 ssl3HelloExtensionSender *sender = &ss->xtnData.serverSenders[0];
2019 for (i = 0; i < SSL_MAX_EXTENSIONS; ++i, ++sender) {
2020 if (!sender->ex_sender) {
2021 sender->ex_type = ex_type;
2022 sender->ex_sender = cb;
2023 return SECSuccess;
2025 /* detect duplicate senders */
2026 PORT_Assert(sender->ex_type != ex_type);
2027 if (sender->ex_type == ex_type) {
2028 /* duplicate */
2029 break;
2032 PORT_Assert(i < SSL_MAX_EXTENSIONS); /* table needs to grow */
2033 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2034 return SECFailure;
2037 /* call each of the extension senders and return the accumulated length */
2038 PRInt32
2039 ssl3_CallHelloExtensionSenders(sslSocket *ss, PRBool append, PRUint32 maxBytes,
2040 const ssl3HelloExtensionSender *sender)
2042 PRInt32 total_exten_len = 0;
2043 int i;
2045 if (!sender) {
2046 sender = ss->version > SSL_LIBRARY_VERSION_3_0 ?
2047 &clientHelloSendersTLS[0] : &clientHelloSendersSSL3[0];
2050 for (i = 0; i < SSL_MAX_EXTENSIONS; ++i, ++sender) {
2051 if (sender->ex_sender) {
2052 PRInt32 extLen = (*sender->ex_sender)(ss, append, maxBytes);
2053 if (extLen < 0)
2054 return -1;
2055 maxBytes -= extLen;
2056 total_exten_len += extLen;
2059 return total_exten_len;
2063 /* Extension format:
2064 * Extension number: 2 bytes
2065 * Extension length: 2 bytes
2066 * Verify Data Length: 1 byte
2067 * Verify Data (TLS): 12 bytes (client) or 24 bytes (server)
2068 * Verify Data (SSL): 36 bytes (client) or 72 bytes (server)
2070 static PRInt32
2071 ssl3_SendRenegotiationInfoXtn(
2072 sslSocket * ss,
2073 PRBool append,
2074 PRUint32 maxBytes)
2076 PRInt32 len, needed;
2078 /* In draft-ietf-tls-renegotiation-03, it is NOT RECOMMENDED to send
2079 * both the SCSV and the empty RI, so when we send SCSV in
2080 * the initial handshake, we don't also send RI.
2082 if (!ss || ss->ssl3.hs.sendingSCSV)
2083 return 0;
2084 len = !ss->firstHsDone ? 0 :
2085 (ss->sec.isServer ? ss->ssl3.hs.finishedBytes * 2
2086 : ss->ssl3.hs.finishedBytes);
2087 needed = 5 + len;
2088 if (append && maxBytes >= needed) {
2089 SECStatus rv;
2090 /* extension_type */
2091 rv = ssl3_AppendHandshakeNumber(ss, ssl_renegotiation_info_xtn, 2);
2092 if (rv != SECSuccess) return -1;
2093 /* length of extension_data */
2094 rv = ssl3_AppendHandshakeNumber(ss, len + 1, 2);
2095 if (rv != SECSuccess) return -1;
2096 /* verify_Data from previous Finished message(s) */
2097 rv = ssl3_AppendHandshakeVariable(ss,
2098 ss->ssl3.hs.finishedMsgs.data, len, 1);
2099 if (rv != SECSuccess) return -1;
2100 if (!ss->sec.isServer) {
2101 TLSExtensionData *xtnData = &ss->xtnData;
2102 xtnData->advertised[xtnData->numAdvertised++] =
2103 ssl_renegotiation_info_xtn;
2106 return needed;
2109 static SECStatus
2110 ssl3_ServerHandleStatusRequestXtn(sslSocket *ss, PRUint16 ex_type,
2111 SECItem *data)
2113 SECStatus rv = SECSuccess;
2115 /* remember that we got this extension. */
2116 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
2117 PORT_Assert(ss->sec.isServer);
2118 /* prepare to send back the appropriate response */
2119 rv = ssl3_RegisterServerHelloExtensionSender(ss, ex_type,
2120 ssl3_ServerSendStatusRequestXtn);
2121 return rv;
2124 /* This function runs in both the client and server. */
2125 static SECStatus
2126 ssl3_HandleRenegotiationInfoXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data)
2128 SECStatus rv = SECSuccess;
2129 PRUint32 len = 0;
2131 if (ss->firstHsDone) {
2132 len = ss->sec.isServer ? ss->ssl3.hs.finishedBytes
2133 : ss->ssl3.hs.finishedBytes * 2;
2135 if (data->len != 1 + len || data->data[0] != len ) {
2136 (void)ssl3_DecodeError(ss);
2137 return SECFailure;
2139 if (len && NSS_SecureMemcmp(ss->ssl3.hs.finishedMsgs.data,
2140 data->data + 1, len)) {
2141 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
2142 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
2143 return SECFailure;
2145 /* remember that we got this extension and it was correct. */
2146 ss->peerRequestedProtection = 1;
2147 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
2148 if (ss->sec.isServer) {
2149 /* prepare to send back the appropriate response */
2150 rv = ssl3_RegisterServerHelloExtensionSender(ss, ex_type,
2151 ssl3_SendRenegotiationInfoXtn);
2153 return rv;
2156 static PRInt32
2157 ssl3_ClientSendUseSRTPXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes)
2159 PRUint32 ext_data_len;
2160 PRInt16 i;
2161 SECStatus rv;
2163 if (!ss)
2164 return 0;
2166 if (!IS_DTLS(ss) || !ss->ssl3.dtlsSRTPCipherCount)
2167 return 0; /* Not relevant */
2169 ext_data_len = 2 + 2 * ss->ssl3.dtlsSRTPCipherCount + 1;
2171 if (append && maxBytes >= 4 + ext_data_len) {
2172 /* Extension type */
2173 rv = ssl3_AppendHandshakeNumber(ss, ssl_use_srtp_xtn, 2);
2174 if (rv != SECSuccess) return -1;
2175 /* Length of extension data */
2176 rv = ssl3_AppendHandshakeNumber(ss, ext_data_len, 2);
2177 if (rv != SECSuccess) return -1;
2178 /* Length of the SRTP cipher list */
2179 rv = ssl3_AppendHandshakeNumber(ss,
2180 2 * ss->ssl3.dtlsSRTPCipherCount,
2182 if (rv != SECSuccess) return -1;
2183 /* The SRTP ciphers */
2184 for (i = 0; i < ss->ssl3.dtlsSRTPCipherCount; i++) {
2185 rv = ssl3_AppendHandshakeNumber(ss,
2186 ss->ssl3.dtlsSRTPCiphers[i],
2189 /* Empty MKI value */
2190 ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
2192 ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
2193 ssl_use_srtp_xtn;
2196 return 4 + ext_data_len;
2199 static PRInt32
2200 ssl3_ServerSendUseSRTPXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes)
2202 SECStatus rv;
2204 /* Server side */
2205 if (!append || maxBytes < 9) {
2206 return 9;
2209 /* Extension type */
2210 rv = ssl3_AppendHandshakeNumber(ss, ssl_use_srtp_xtn, 2);
2211 if (rv != SECSuccess) return -1;
2212 /* Length of extension data */
2213 rv = ssl3_AppendHandshakeNumber(ss, 5, 2);
2214 if (rv != SECSuccess) return -1;
2215 /* Length of the SRTP cipher list */
2216 rv = ssl3_AppendHandshakeNumber(ss, 2, 2);
2217 if (rv != SECSuccess) return -1;
2218 /* The selected cipher */
2219 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.dtlsSRTPCipherSuite, 2);
2220 if (rv != SECSuccess) return -1;
2221 /* Empty MKI value */
2222 ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
2224 return 9;
2227 static SECStatus
2228 ssl3_ClientHandleUseSRTPXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data)
2230 SECStatus rv;
2231 SECItem ciphers = {siBuffer, NULL, 0};
2232 PRUint16 i;
2233 PRUint16 cipher = 0;
2234 PRBool found = PR_FALSE;
2235 SECItem litem;
2237 if (!data->data || !data->len) {
2238 (void)ssl3_DecodeError(ss);
2239 return SECFailure;
2242 /* Get the cipher list */
2243 rv = ssl3_ConsumeHandshakeVariable(ss, &ciphers, 2,
2244 &data->data, &data->len);
2245 if (rv != SECSuccess) {
2246 return SECFailure; /* fatal alert already sent */
2248 /* Now check that the server has picked just 1 (i.e., len = 2) */
2249 if (ciphers.len != 2) {
2250 (void)ssl3_DecodeError(ss);
2251 return SECFailure;
2254 /* Get the selected cipher */
2255 cipher = (ciphers.data[0] << 8) | ciphers.data[1];
2257 /* Now check that this is one of the ciphers we offered */
2258 for (i = 0; i < ss->ssl3.dtlsSRTPCipherCount; i++) {
2259 if (cipher == ss->ssl3.dtlsSRTPCiphers[i]) {
2260 found = PR_TRUE;
2261 break;
2265 if (!found) {
2266 PORT_SetError(SSL_ERROR_RX_MALFORMED_SERVER_HELLO);
2267 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
2268 return SECFailure;
2271 /* Get the srtp_mki value */
2272 rv = ssl3_ConsumeHandshakeVariable(ss, &litem, 1,
2273 &data->data, &data->len);
2274 if (rv != SECSuccess) {
2275 return SECFailure; /* alert already sent */
2278 /* We didn't offer an MKI, so this must be 0 length */
2279 if (litem.len != 0) {
2280 PORT_SetError(SSL_ERROR_RX_MALFORMED_SERVER_HELLO);
2281 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
2282 return SECFailure;
2285 /* extra trailing bytes */
2286 if (data->len != 0) {
2287 (void)ssl3_DecodeError(ss);
2288 return SECFailure;
2291 /* OK, this looks fine. */
2292 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ssl_use_srtp_xtn;
2293 ss->ssl3.dtlsSRTPCipherSuite = cipher;
2294 return SECSuccess;
2297 static SECStatus
2298 ssl3_ServerHandleUseSRTPXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data)
2300 SECStatus rv;
2301 SECItem ciphers = {siBuffer, NULL, 0};
2302 PRUint16 i;
2303 unsigned int j;
2304 PRUint16 cipher = 0;
2305 PRBool found = PR_FALSE;
2306 SECItem litem;
2308 if (!IS_DTLS(ss) || !ss->ssl3.dtlsSRTPCipherCount) {
2309 /* Ignore the extension if we aren't doing DTLS or no DTLS-SRTP
2310 * preferences have been set. */
2311 return SECSuccess;
2314 if (!data->data || data->len < 5) {
2315 (void)ssl3_DecodeError(ss);
2316 return SECFailure;
2319 /* Get the cipher list */
2320 rv = ssl3_ConsumeHandshakeVariable(ss, &ciphers, 2,
2321 &data->data, &data->len);
2322 if (rv != SECSuccess) {
2323 return SECFailure; /* alert already sent */
2325 /* Check that the list is even length */
2326 if (ciphers.len % 2) {
2327 (void)ssl3_DecodeError(ss);
2328 return SECFailure;
2331 /* Walk through the offered list and pick the most preferred of our
2332 * ciphers, if any */
2333 for (i = 0; !found && i < ss->ssl3.dtlsSRTPCipherCount; i++) {
2334 for (j = 0; j + 1 < ciphers.len; j += 2) {
2335 cipher = (ciphers.data[j] << 8) | ciphers.data[j + 1];
2336 if (cipher == ss->ssl3.dtlsSRTPCiphers[i]) {
2337 found = PR_TRUE;
2338 break;
2343 /* Get the srtp_mki value */
2344 rv = ssl3_ConsumeHandshakeVariable(ss, &litem, 1, &data->data, &data->len);
2345 if (rv != SECSuccess) {
2346 return SECFailure;
2349 if (data->len != 0) {
2350 (void)ssl3_DecodeError(ss); /* trailing bytes */
2351 return SECFailure;
2354 /* Now figure out what to do */
2355 if (!found) {
2356 /* No matching ciphers, pretend we don't support use_srtp */
2357 return SECSuccess;
2360 /* OK, we have a valid cipher and we've selected it */
2361 ss->ssl3.dtlsSRTPCipherSuite = cipher;
2362 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ssl_use_srtp_xtn;
2364 return ssl3_RegisterServerHelloExtensionSender(ss, ssl_use_srtp_xtn,
2365 ssl3_ServerSendUseSRTPXtn);
2368 /* ssl3_ServerHandleSigAlgsXtn handles the signature_algorithms extension
2369 * from a client.
2370 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
2371 static SECStatus
2372 ssl3_ServerHandleSigAlgsXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data)
2374 SECStatus rv;
2375 SECItem algorithms;
2376 const unsigned char *b;
2377 unsigned int numAlgorithms, i, j;
2379 /* Ignore this extension if we aren't doing TLS 1.2 or greater. */
2380 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_2) {
2381 return SECSuccess;
2384 rv = ssl3_ConsumeHandshakeVariable(ss, &algorithms, 2, &data->data,
2385 &data->len);
2386 if (rv != SECSuccess) {
2387 return SECFailure;
2389 /* Trailing data, empty value, or odd-length value is invalid. */
2390 if (data->len != 0 || algorithms.len == 0 || (algorithms.len & 1) != 0) {
2391 PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
2392 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
2393 return SECFailure;
2396 numAlgorithms = algorithms.len/2;
2398 /* We don't care to process excessive numbers of algorithms. */
2399 if (numAlgorithms > 512) {
2400 numAlgorithms = 512;
2403 ss->ssl3.hs.clientSigAndHash =
2404 PORT_NewArray(SSL3SignatureAndHashAlgorithm, numAlgorithms);
2405 if (!ss->ssl3.hs.clientSigAndHash) {
2406 PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
2407 (void)SSL3_SendAlert(ss, alert_fatal, internal_error);
2408 return SECFailure;
2410 ss->ssl3.hs.numClientSigAndHash = 0;
2412 b = algorithms.data;
2413 for (i = j = 0; i < numAlgorithms; i++) {
2414 unsigned char tls_hash = *(b++);
2415 unsigned char tls_sig = *(b++);
2416 SECOidTag hash = ssl3_TLSHashAlgorithmToOID(tls_hash);
2418 if (hash == SEC_OID_UNKNOWN) {
2419 /* We ignore formats that we don't understand. */
2420 continue;
2422 /* tls_sig support will be checked later in
2423 * ssl3_PickSignatureHashAlgorithm. */
2424 ss->ssl3.hs.clientSigAndHash[j].hashAlg = hash;
2425 ss->ssl3.hs.clientSigAndHash[j].sigAlg = tls_sig;
2426 ++j;
2427 ++ss->ssl3.hs.numClientSigAndHash;
2430 if (!ss->ssl3.hs.numClientSigAndHash) {
2431 /* We didn't understand any of the client's requested signature
2432 * formats. We'll use the defaults. */
2433 PORT_Free(ss->ssl3.hs.clientSigAndHash);
2434 ss->ssl3.hs.clientSigAndHash = NULL;
2437 /* Keep track of negotiated extensions. */
2438 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
2439 return SECSuccess;
2442 /* ssl3_ClientSendSigAlgsXtn sends the signature_algorithm extension for TLS
2443 * 1.2 ClientHellos. */
2444 static PRInt32
2445 ssl3_ClientSendSigAlgsXtn(sslSocket * ss, PRBool append, PRUint32 maxBytes)
2447 static const unsigned char signatureAlgorithms[] = {
2448 /* This block is the contents of our signature_algorithms extension, in
2449 * wire format. See
2450 * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
2451 tls_hash_sha256, tls_sig_rsa,
2452 tls_hash_sha384, tls_sig_rsa,
2453 tls_hash_sha512, tls_sig_rsa,
2454 tls_hash_sha1, tls_sig_rsa,
2455 #ifndef NSS_DISABLE_ECC
2456 tls_hash_sha256, tls_sig_ecdsa,
2457 tls_hash_sha384, tls_sig_ecdsa,
2458 tls_hash_sha512, tls_sig_ecdsa,
2459 tls_hash_sha1, tls_sig_ecdsa,
2460 #endif
2461 tls_hash_sha256, tls_sig_dsa,
2462 tls_hash_sha1, tls_sig_dsa,
2464 PRInt32 extension_length;
2466 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_2) {
2467 return 0;
2470 extension_length =
2471 2 /* extension type */ +
2472 2 /* extension length */ +
2473 2 /* supported_signature_algorithms length */ +
2474 sizeof(signatureAlgorithms);
2476 if (append && maxBytes >= extension_length) {
2477 SECStatus rv;
2478 rv = ssl3_AppendHandshakeNumber(ss, ssl_signature_algorithms_xtn, 2);
2479 if (rv != SECSuccess)
2480 goto loser;
2481 rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2);
2482 if (rv != SECSuccess)
2483 goto loser;
2484 rv = ssl3_AppendHandshakeVariable(ss, signatureAlgorithms,
2485 sizeof(signatureAlgorithms), 2);
2486 if (rv != SECSuccess)
2487 goto loser;
2488 ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
2489 ssl_signature_algorithms_xtn;
2490 } else if (maxBytes < extension_length) {
2491 PORT_Assert(0);
2492 return 0;
2495 return extension_length;
2497 loser:
2498 return -1;
2501 unsigned int
2502 ssl3_CalculatePaddingExtensionLength(unsigned int clientHelloLength)
2504 unsigned int recordLength = 1 /* handshake message type */ +
2505 3 /* handshake message length */ +
2506 clientHelloLength;
2507 unsigned int extensionLength;
2509 if (recordLength < 256 || recordLength >= 512) {
2510 return 0;
2513 extensionLength = 512 - recordLength;
2514 /* Extensions take at least four bytes to encode. Always include at least
2515 * one byte of data if including the extension. WebSphere Application
2516 * Server 7.0 is intolerant to the last extension being zero-length. */
2517 if (extensionLength < 4 + 1) {
2518 extensionLength = 4 + 1;
2521 return extensionLength;
2524 /* ssl3_AppendPaddingExtension possibly adds an extension which ensures that a
2525 * ClientHello record is either < 256 bytes or is >= 512 bytes. This ensures
2526 * that we don't trigger bugs in F5 products. */
2527 PRInt32
2528 ssl3_AppendPaddingExtension(sslSocket *ss, unsigned int extensionLen,
2529 PRUint32 maxBytes)
2531 unsigned int paddingLen = extensionLen - 4;
2532 static unsigned char padding[256];
2534 if (extensionLen == 0) {
2535 return 0;
2538 if (extensionLen < 4 ||
2539 extensionLen > maxBytes ||
2540 paddingLen > sizeof(padding)) {
2541 PORT_Assert(0);
2542 return -1;
2545 if (SECSuccess != ssl3_AppendHandshakeNumber(ss, ssl_padding_xtn, 2))
2546 return -1;
2547 if (SECSuccess != ssl3_AppendHandshakeNumber(ss, paddingLen, 2))
2548 return -1;
2549 if (SECSuccess != ssl3_AppendHandshake(ss, padding, paddingLen))
2550 return -1;
2552 return extensionLen;
2555 /* ssl3_ClientSendDraftVersionXtn sends the TLS 1.3 temporary draft
2556 * version extension.
2557 * TODO(ekr@rtfm.com): Remove when TLS 1.3 is published. */
2558 static PRInt32
2559 ssl3_ClientSendDraftVersionXtn(sslSocket * ss, PRBool append, PRUint32 maxBytes)
2561 PRInt32 extension_length;
2563 if (ss->version != SSL_LIBRARY_VERSION_TLS_1_3) {
2564 return 0;
2567 extension_length = 6; /* Type + length + number */
2568 if (append && maxBytes >= extension_length) {
2569 SECStatus rv;
2570 rv = ssl3_AppendHandshakeNumber(ss, ssl_tls13_draft_version_xtn, 2);
2571 if (rv != SECSuccess)
2572 goto loser;
2573 rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2);
2574 if (rv != SECSuccess)
2575 goto loser;
2576 rv = ssl3_AppendHandshakeNumber(ss, TLS_1_3_DRAFT_VERSION, 2);
2577 if (rv != SECSuccess)
2578 goto loser;
2579 ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
2580 ssl_tls13_draft_version_xtn;
2581 } else if (maxBytes < extension_length) {
2582 PORT_Assert(0);
2583 return 0;
2586 return extension_length;
2588 loser:
2589 return -1;
2592 /* ssl3_ServerHandleDraftVersionXtn handles the TLS 1.3 temporary draft
2593 * version extension.
2594 * TODO(ekr@rtfm.com): Remove when TLS 1.3 is published. */
2595 static SECStatus
2596 ssl3_ServerHandleDraftVersionXtn(sslSocket * ss, PRUint16 ex_type,
2597 SECItem *data)
2599 PRInt32 draft_version;
2601 /* Ignore this extension if we aren't doing TLS 1.3 */
2602 if (ss->version != SSL_LIBRARY_VERSION_TLS_1_3) {
2603 return SECSuccess;
2606 if (data->len != 2) {
2607 (void)ssl3_DecodeError(ss);
2608 return SECFailure;
2611 /* Get the draft version out of the handshake */
2612 draft_version = ssl3_ConsumeHandshakeNumber(ss, 2,
2613 &data->data, &data->len);
2614 if (draft_version < 0) {
2615 return SECFailure;
2618 /* Keep track of negotiated extensions. */
2619 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
2621 if (draft_version != TLS_1_3_DRAFT_VERSION) {
2623 * Incompatible/broken TLS 1.3 implementation. Fall back to TLS 1.2.
2624 * TODO(ekr@rtfm.com): It's not entirely clear it's safe to roll back
2625 * here. Need to double-check.
2627 SSL_TRC(30, ("%d: SSL3[%d]: Incompatible version of TLS 1.3 (%d), "
2628 "expected %d",
2629 SSL_GETPID(), ss->fd, draft_version, TLS_1_3_DRAFT_VERSION));
2630 ss->version = SSL_LIBRARY_VERSION_TLS_1_2;
2633 return SECSuccess;
2636 /* ssl3_ClientSendSignedCertTimestampXtn sends the signed_certificate_timestamp
2637 * extension for TLS ClientHellos. */
2638 static PRInt32
2639 ssl3_ClientSendSignedCertTimestampXtn(sslSocket *ss, PRBool append,
2640 PRUint32 maxBytes)
2642 PRInt32 extension_length = 2 /* extension_type */ +
2643 2 /* length(extension_data) */;
2645 /* Only send the extension if processing is enabled. */
2646 if (!ss->opt.enableSignedCertTimestamps)
2647 return 0;
2649 if (append && maxBytes >= extension_length) {
2650 SECStatus rv;
2651 /* extension_type */
2652 rv = ssl3_AppendHandshakeNumber(ss,
2653 ssl_signed_certificate_timestamp_xtn,
2655 if (rv != SECSuccess)
2656 goto loser;
2657 /* zero length */
2658 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
2659 if (rv != SECSuccess)
2660 goto loser;
2661 ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
2662 ssl_signed_certificate_timestamp_xtn;
2663 } else if (maxBytes < extension_length) {
2664 PORT_Assert(0);
2665 return 0;
2668 return extension_length;
2669 loser:
2670 return -1;
2673 static SECStatus
2674 ssl3_ClientHandleSignedCertTimestampXtn(sslSocket *ss, PRUint16 ex_type,
2675 SECItem *data)
2677 /* We do not yet know whether we'll be resuming a session or creating
2678 * a new one, so we keep a pointer to the data in the TLSExtensionData
2679 * structure. This pointer is only valid in the scope of
2680 * ssl3_HandleServerHello, and, if not resuming a session, the data is
2681 * copied once a new session structure has been set up.
2682 * All parsing is currently left to the application and we accept
2683 * everything, including empty data.
2685 SECItem *scts = &ss->xtnData.signedCertTimestamps;
2686 PORT_Assert(!scts->data && !scts->len);
2688 if (!data->len) {
2689 /* Empty extension data: RFC 6962 mandates non-empty contents. */
2690 return SECFailure;
2692 *scts = *data;
2693 /* Keep track of negotiated extensions. */
2694 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
2695 return SECSuccess;