Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(110)

Side by Side Diff: net/third_party/nss/ssl/ssl3ext.c

Issue 1882433002: Removing NSS files and USE_OPENSSL flag (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Rebase. Created 4 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « net/third_party/nss/ssl/ssl3ecc.c ('k') | net/third_party/nss/ssl/ssl3gthr.c » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * SSL3 Protocol
4 *
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/. */
8
9 /* TLS extension code moved here from ssl3ecc.c */
10
11 #include "nssrenam.h"
12 #include "nss.h"
13 #include "ssl.h"
14 #include "sslproto.h"
15 #include "sslimpl.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"
23
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;
27
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];
31
32 static PRBool session_ticket_keys_initialized = PR_FALSE;
33 #endif
34 static PRCallOnceType generate_session_keys_once;
35
36 /* forward static function declarations */
37 static SECStatus ssl3_ParseEncryptedSessionTicket(sslSocket *ss,
38 SECItem *data, EncryptedSessio nTicket *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, PK11SymKe y **mac_key);
45 #ifndef NO_PKCS11_BYPASS
46 static SECStatus ssl3_GetSessionTicketKeys(const unsigned char **aes_key,
47 PRUint32 *aes_key_length, const unsig ned 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 *da ta);
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 *da ta);
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 *da ta);
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
94 static PRInt32 ssl3_ClientSendSignedCertTimestampXtn(sslSocket *ss,
95 PRBool append,
96 PRUint32 maxBytes);
97 static SECStatus ssl3_ClientHandleSignedCertTimestampXtn(sslSocket *ss,
98 PRUint16 ex_type,
99 SECItem *data);
100 static PRInt32 ssl3_ServerSendSignedCertTimestampXtn(sslSocket *ss,
101 PRBool append,
102 PRUint32 maxBytes);
103 static SECStatus ssl3_ServerHandleSignedCertTimestampXtn(sslSocket *ss,
104 PRUint16 ex_type,
105 SECItem *data);
106 static PRInt32 ssl3_ClientSendDraftVersionXtn(sslSocket *ss, PRBool append,
107 PRUint32 maxBytes);
108 static SECStatus ssl3_ServerHandleDraftVersionXtn(sslSocket *ss, PRUint16 ex_typ e,
109 SECItem *data);
110 static PRInt32 ssl3_SendExtendedMasterSecretXtn(sslSocket *ss, PRBool append,
111 PRUint32 maxBytes);
112 static SECStatus ssl3_HandleExtendedMasterSecretXtn(sslSocket *ss,
113 PRUint16 ex_type,
114 SECItem *data);
115 static PRInt32 tls13_ClientSendKeyShareXtn(sslSocket *ss, PRBool append,
116 PRUint32 maxBytes);
117 static SECStatus tls13_ClientHandleKeyShareXtn(sslSocket *ss,
118 PRUint16 ex_type,
119 SECItem *data);
120 static SECStatus tls13_ServerHandleKeyShareXtn(sslSocket *ss,
121 PRUint16 ex_type,
122 SECItem *data);
123
124 /*
125 * Write bytes. Using this function means the SECItem structure
126 * cannot be freed. The caller is expected to call this function
127 * on a shallow copy of the structure.
128 */
129 static SECStatus
130 ssl3_AppendToItem(SECItem *item, const unsigned char *buf, PRUint32 bytes)
131 {
132 if (bytes > item->len)
133 return SECFailure;
134
135 PORT_Memcpy(item->data, buf, bytes);
136 item->data += bytes;
137 item->len -= bytes;
138 return SECSuccess;
139 }
140
141 /*
142 * Write a number in network byte order. Using this function means the
143 * SECItem structure cannot be freed. The caller is expected to call
144 * this function on a shallow copy of the structure.
145 */
146 static SECStatus
147 ssl3_AppendNumberToItem(SECItem *item, PRUint32 num, PRInt32 lenSize)
148 {
149 SECStatus rv;
150 PRUint8 b[4];
151 PRUint8 *p = b;
152
153 switch (lenSize) {
154 case 4:
155 *p++ = (PRUint8)(num >> 24);
156 case 3:
157 *p++ = (PRUint8)(num >> 16);
158 case 2:
159 *p++ = (PRUint8)(num >> 8);
160 case 1:
161 *p = (PRUint8)num;
162 }
163 rv = ssl3_AppendToItem(item, &b[0], lenSize);
164 return rv;
165 }
166
167 static SECStatus
168 ssl3_SessionTicketShutdown(void *appData, void *nssData)
169 {
170 if (session_ticket_enc_key_pkcs11) {
171 PK11_FreeSymKey(session_ticket_enc_key_pkcs11);
172 session_ticket_enc_key_pkcs11 = NULL;
173 }
174 if (session_ticket_mac_key_pkcs11) {
175 PK11_FreeSymKey(session_ticket_mac_key_pkcs11);
176 session_ticket_mac_key_pkcs11 = NULL;
177 }
178 PORT_Memset(&generate_session_keys_once, 0,
179 sizeof(generate_session_keys_once));
180 return SECSuccess;
181 }
182
183 static PRStatus
184 ssl3_GenerateSessionTicketKeysPKCS11(void *data)
185 {
186 SECStatus rv;
187 sslSocket *ss = (sslSocket *)data;
188 SECKEYPrivateKey *svrPrivKey = ss->serverCerts[kt_rsa].SERVERKEY;
189 SECKEYPublicKey *svrPubKey = ss->serverCerts[kt_rsa].serverKeyPair->pubKey;
190
191 if (svrPrivKey == NULL || svrPubKey == NULL) {
192 SSL_DBG(("%d: SSL[%d]: Pub or priv key(s) is NULL.",
193 SSL_GETPID(), ss->fd));
194 goto loser;
195 }
196
197 /* Get a copy of the session keys from shared memory. */
198 PORT_Memcpy(key_name, SESS_TICKET_KEY_NAME_PREFIX,
199 sizeof(SESS_TICKET_KEY_NAME_PREFIX));
200 if (!ssl_GetSessionTicketKeysPKCS11(svrPrivKey, svrPubKey,
201 ss->pkcs11PinArg, &key_name[SESS_TICKET_ KEY_NAME_PREFIX_LEN],
202 &session_ticket_enc_key_pkcs11, &session _ticket_mac_key_pkcs11))
203 return PR_FAILURE;
204
205 rv = NSS_RegisterShutdown(ssl3_SessionTicketShutdown, NULL);
206 if (rv != SECSuccess)
207 goto loser;
208
209 return PR_SUCCESS;
210
211 loser:
212 ssl3_SessionTicketShutdown(NULL, NULL);
213 return PR_FAILURE;
214 }
215
216 static SECStatus
217 ssl3_GetSessionTicketKeysPKCS11(sslSocket *ss, PK11SymKey **aes_key,
218 PK11SymKey **mac_key)
219 {
220 if (PR_CallOnceWithArg(&generate_session_keys_once,
221 ssl3_GenerateSessionTicketKeysPKCS11, ss) !=
222 PR_SUCCESS)
223 return SECFailure;
224
225 if (session_ticket_enc_key_pkcs11 == NULL ||
226 session_ticket_mac_key_pkcs11 == NULL)
227 return SECFailure;
228
229 *aes_key = session_ticket_enc_key_pkcs11;
230 *mac_key = session_ticket_mac_key_pkcs11;
231 return SECSuccess;
232 }
233
234 #ifndef NO_PKCS11_BYPASS
235 static PRStatus
236 ssl3_GenerateSessionTicketKeys(void)
237 {
238 PORT_Memcpy(key_name, SESS_TICKET_KEY_NAME_PREFIX,
239 sizeof(SESS_TICKET_KEY_NAME_PREFIX));
240
241 if (!ssl_GetSessionTicketKeys(&key_name[SESS_TICKET_KEY_NAME_PREFIX_LEN],
242 session_ticket_enc_key, session_ticket_mac_key ))
243 return PR_FAILURE;
244
245 session_ticket_keys_initialized = PR_TRUE;
246 return PR_SUCCESS;
247 }
248
249 static SECStatus
250 ssl3_GetSessionTicketKeys(const unsigned char **aes_key,
251 PRUint32 *aes_key_length, const unsigned char **mac_ke y,
252 PRUint32 *mac_key_length)
253 {
254 if (PR_CallOnce(&generate_session_keys_once,
255 ssl3_GenerateSessionTicketKeys) != PR_SUCCESS)
256 return SECFailure;
257
258 if (!session_ticket_keys_initialized)
259 return SECFailure;
260
261 *aes_key = session_ticket_enc_key;
262 *aes_key_length = sizeof(session_ticket_enc_key);
263 *mac_key = session_ticket_mac_key;
264 *mac_key_length = sizeof(session_ticket_mac_key);
265
266 return SECSuccess;
267 }
268 #endif
269
270 /* Table of handlers for received TLS hello extensions, one per extension.
271 * In the second generation, this table will be dynamic, and functions
272 * will be registered here.
273 */
274 /* This table is used by the server, to handle client hello extensions. */
275 static const ssl3HelloExtensionHandler clientHelloHandlers[] = {
276 { ssl_server_name_xtn, &ssl3_HandleServerNameXtn },
277 #ifndef NSS_DISABLE_ECC
278 { ssl_elliptic_curves_xtn, &ssl3_HandleSupportedCurvesXtn },
279 { ssl_ec_point_formats_xtn, &ssl3_HandleSupportedPointFormatsXtn },
280 #endif
281 { ssl_session_ticket_xtn, &ssl3_ServerHandleSessionTicketXtn },
282 { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn },
283 { ssl_next_proto_nego_xtn, &ssl3_ServerHandleNextProtoNegoXtn },
284 { ssl_app_layer_protocol_xtn, &ssl3_ServerHandleAppProtoXtn },
285 { ssl_use_srtp_xtn, &ssl3_ServerHandleUseSRTPXtn },
286 { ssl_cert_status_xtn, &ssl3_ServerHandleStatusRequestXtn },
287 { ssl_signature_algorithms_xtn, &ssl3_ServerHandleSigAlgsXtn },
288 { ssl_tls13_draft_version_xtn, &ssl3_ServerHandleDraftVersionXtn },
289 { ssl_extended_master_secret_xtn, &ssl3_HandleExtendedMasterSecretXtn },
290 { ssl_signed_cert_timestamp_xtn, &ssl3_ServerHandleSignedCertTimestampXtn },
291 { ssl_tls13_key_share_xtn, &tls13_ServerHandleKeyShareXtn },
292 { -1, NULL }
293 };
294
295 /* These two tables are used by the client, to handle server hello
296 * extensions. */
297 static const ssl3HelloExtensionHandler serverHelloHandlersTLS[] = {
298 { ssl_server_name_xtn, &ssl3_HandleServerNameXtn },
299 /* TODO: add a handler for ssl_ec_point_formats_xtn */
300 { ssl_session_ticket_xtn, &ssl3_ClientHandleSessionTicketXtn },
301 { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn },
302 { ssl_next_proto_nego_xtn, &ssl3_ClientHandleNextProtoNegoXtn },
303 { ssl_app_layer_protocol_xtn, &ssl3_ClientHandleAppProtoXtn },
304 { ssl_use_srtp_xtn, &ssl3_ClientHandleUseSRTPXtn },
305 { ssl_channel_id_xtn, &ssl3_ClientHandleChannelIDXtn },
306 { ssl_cert_status_xtn, &ssl3_ClientHandleStatusRequestXtn },
307 { ssl_extended_master_secret_xtn, &ssl3_HandleExtendedMasterSecretXtn },
308 { ssl_signed_cert_timestamp_xtn, &ssl3_ClientHandleSignedCertTimestampXtn },
309 { ssl_tls13_key_share_xtn, &tls13_ClientHandleKeyShareXtn },
310 { -1, NULL }
311 };
312
313 static const ssl3HelloExtensionHandler serverHelloHandlersSSL3[] = {
314 { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn },
315 { -1, NULL }
316 };
317
318 /* Tables of functions to format TLS hello extensions, one function per
319 * extension.
320 * These static tables are for the formatting of client hello extensions.
321 * The server's table of hello senders is dynamic, in the socket struct,
322 * and sender functions are registered there.
323 */
324 static const ssl3HelloExtensionSender clientHelloSendersTLS[SSL_MAX_EXTENSIONS] =
325 {
326 { ssl_server_name_xtn, &ssl3_SendServerNameXtn },
327 { ssl_extended_master_secret_xtn, &ssl3_SendExtendedMasterSecretXtn },
328 { ssl_renegotiation_info_xtn, &ssl3_SendRenegotiationInfoXtn },
329 #ifndef NSS_DISABLE_ECC
330 { ssl_elliptic_curves_xtn, &ssl3_SendSupportedCurvesXtn },
331 { ssl_ec_point_formats_xtn, &ssl3_SendSupportedPointFormatsXtn },
332 #endif
333 { ssl_session_ticket_xtn, &ssl3_SendSessionTicketXtn },
334 { ssl_next_proto_nego_xtn, &ssl3_ClientSendNextProtoNegoXtn },
335 { ssl_app_layer_protocol_xtn, &ssl3_ClientSendAppProtoXtn },
336 { ssl_use_srtp_xtn, &ssl3_ClientSendUseSRTPXtn },
337 { ssl_channel_id_xtn, &ssl3_ClientSendChannelIDXtn },
338 { ssl_cert_status_xtn, &ssl3_ClientSendStatusRequestXtn },
339 { ssl_tls13_draft_version_xtn, &ssl3_ClientSendDraftVersionXtn },
340 { ssl_signed_cert_timestamp_xtn, &ssl3_ClientSendSignedCertTimestampXtn },
341 { ssl_tls13_key_share_xtn, &tls13_ClientSendKeyShareXtn },
342 /* Some servers (e.g. WebSphere Application Server 7.0 and Tomcat) will
343 * time out or terminate the connection if the last extension in the
344 * client hello is empty. They are not intolerant of TLS 1.2, so list
345 * signature_algorithms at the end. See bug 1243641. */
346 { ssl_signature_algorithms_xtn, &ssl3_ClientSendSigAlgsXtn },
347 /* any extra entries will appear as { 0, NULL } */
348 };
349
350 static const ssl3HelloExtensionSender clientHelloSendersSSL3[SSL_MAX_EXTENSIONS] =
351 {
352 { ssl_renegotiation_info_xtn, &ssl3_SendRenegotiationInfoXtn }
353 /* any extra entries will appear as { 0, NULL } */
354 };
355
356 static PRBool
357 arrayContainsExtension(const PRUint16 *array, PRUint32 len, PRUint16 ex_type)
358 {
359 unsigned int i;
360 for (i = 0; i < len; i++) {
361 if (ex_type == array[i])
362 return PR_TRUE;
363 }
364 return PR_FALSE;
365 }
366
367 PRBool
368 ssl3_ExtensionNegotiated(sslSocket *ss, PRUint16 ex_type)
369 {
370 TLSExtensionData *xtnData = &ss->xtnData;
371 return arrayContainsExtension(xtnData->negotiated,
372 xtnData->numNegotiated, ex_type);
373 }
374
375 static PRBool
376 ssl3_ClientExtensionAdvertised(sslSocket *ss, PRUint16 ex_type)
377 {
378 TLSExtensionData *xtnData = &ss->xtnData;
379 return arrayContainsExtension(xtnData->advertised,
380 xtnData->numAdvertised, ex_type);
381 }
382
383 /* Format an SNI extension, using the name from the socket's URL,
384 * unless that name is a dotted decimal string.
385 * Used by client and server.
386 */
387 PRInt32
388 ssl3_SendServerNameXtn(sslSocket *ss, PRBool append,
389 PRUint32 maxBytes)
390 {
391 SECStatus rv;
392 if (!ss)
393 return 0;
394 if (!ss->sec.isServer) {
395 PRUint32 len;
396 PRNetAddr netAddr;
397
398 /* must have a hostname */
399 if (!ss->url || !ss->url[0])
400 return 0;
401 /* must not be an IPv4 or IPv6 address */
402 if (PR_SUCCESS == PR_StringToNetAddr(ss->url, &netAddr)) {
403 /* is an IP address (v4 or v6) */
404 return 0;
405 }
406 len = PORT_Strlen(ss->url);
407 if (append && maxBytes >= len + 9) {
408 /* extension_type */
409 rv = ssl3_AppendHandshakeNumber(ss, ssl_server_name_xtn, 2);
410 if (rv != SECSuccess)
411 return -1;
412 /* length of extension_data */
413 rv = ssl3_AppendHandshakeNumber(ss, len + 5, 2);
414 if (rv != SECSuccess)
415 return -1;
416 /* length of server_name_list */
417 rv = ssl3_AppendHandshakeNumber(ss, len + 3, 2);
418 if (rv != SECSuccess)
419 return -1;
420 /* Name Type (sni_host_name) */
421 rv = ssl3_AppendHandshake(ss, "\0", 1);
422 if (rv != SECSuccess)
423 return -1;
424 /* HostName (length and value) */
425 rv = ssl3_AppendHandshakeVariable(ss, (PRUint8 *)ss->url, len, 2);
426 if (rv != SECSuccess)
427 return -1;
428 if (!ss->sec.isServer) {
429 TLSExtensionData *xtnData = &ss->xtnData;
430 xtnData->advertised[xtnData->numAdvertised++] =
431 ssl_server_name_xtn;
432 }
433 }
434 return len + 9;
435 }
436 /* Server side */
437 if (append && maxBytes >= 4) {
438 rv = ssl3_AppendHandshakeNumber(ss, ssl_server_name_xtn, 2);
439 if (rv != SECSuccess)
440 return -1;
441 /* length of extension_data */
442 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
443 if (rv != SECSuccess)
444 return -1;
445 }
446 return 4;
447 }
448
449 /* handle an incoming SNI extension, by ignoring it. */
450 SECStatus
451 ssl3_HandleServerNameXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data)
452 {
453 SECItem *names = NULL;
454 PRUint32 listCount = 0, namesPos = 0, i;
455 TLSExtensionData *xtnData = &ss->xtnData;
456 SECItem ldata;
457 PRInt32 listLenBytes = 0;
458
459 if (!ss->sec.isServer) {
460 return SECSuccess; /* ignore extension */
461 }
462
463 /* Server side - consume client data and register server sender. */
464 /* do not parse the data if don't have user extension handling function. */
465 if (!ss->sniSocketConfig) {
466 return SECSuccess;
467 }
468 /* length of server_name_list */
469 listLenBytes = ssl3_ConsumeHandshakeNumber(ss, 2, &data->data, &data->len);
470 if (listLenBytes < 0) {
471 return SECFailure;
472 }
473 if (listLenBytes == 0 || listLenBytes != data->len) {
474 (void)ssl3_DecodeError(ss);
475 return SECFailure;
476 }
477 ldata = *data;
478 /* Calculate the size of the array.*/
479 while (listLenBytes > 0) {
480 SECItem litem;
481 SECStatus rv;
482 PRInt32 type;
483 /* Skip Name Type (sni_host_name); checks are on the second pass */
484 type = ssl3_ConsumeHandshakeNumber(ss, 1, &ldata.data, &ldata.len);
485 if (type < 0) { /* i.e., SECFailure cast to PRint32 */
486 return SECFailure;
487 }
488 rv = ssl3_ConsumeHandshakeVariable(ss, &litem, 2, &ldata.data, &ldata.le n);
489 if (rv != SECSuccess) {
490 return rv;
491 }
492 /* Adjust total length for consumed item, item len and type.*/
493 listLenBytes -= litem.len + 3;
494 if (listLenBytes > 0 && !ldata.len) {
495 (void)ssl3_DecodeError(ss);
496 return SECFailure;
497 }
498 listCount += 1;
499 }
500 names = PORT_ZNewArray(SECItem, listCount);
501 if (!names) {
502 return SECFailure;
503 }
504 for (i = 0; i < listCount; i++) {
505 unsigned int j;
506 PRInt32 type;
507 SECStatus rv;
508 PRBool nametypePresent = PR_FALSE;
509 /* Name Type (sni_host_name) */
510 type = ssl3_ConsumeHandshakeNumber(ss, 1, &data->data, &data->len);
511 /* Check if we have such type in the list */
512 for (j = 0; j < listCount && names[j].data; j++) {
513 /* TODO bug 998524: .type is not assigned a value */
514 if (names[j].type == type) {
515 nametypePresent = PR_TRUE;
516 break;
517 }
518 }
519 /* HostName (length and value) */
520 rv = ssl3_ConsumeHandshakeVariable(ss, &names[namesPos], 2,
521 &data->data, &data->len);
522 if (rv != SECSuccess) {
523 PORT_Assert(0);
524 PORT_Free(names);
525 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
526 return rv;
527 }
528 if (nametypePresent == PR_FALSE) {
529 namesPos += 1;
530 }
531 }
532 /* Free old and set the new data. */
533 if (xtnData->sniNameArr) {
534 PORT_Free(ss->xtnData.sniNameArr);
535 }
536 xtnData->sniNameArr = names;
537 xtnData->sniNameArrSize = namesPos;
538 xtnData->negotiated[xtnData->numNegotiated++] = ssl_server_name_xtn;
539
540 return SECSuccess;
541 }
542
543 /* Called by both clients and servers.
544 * Clients sends a filled in session ticket if one is available, and otherwise
545 * sends an empty ticket. Servers always send empty tickets.
546 */
547 PRInt32
548 ssl3_SendSessionTicketXtn(
549 sslSocket *ss,
550 PRBool append,
551 PRUint32 maxBytes)
552 {
553 PRInt32 extension_length;
554 NewSessionTicket *session_ticket = NULL;
555 sslSessionID *sid = ss->sec.ci.sid;
556
557 /* Ignore the SessionTicket extension if processing is disabled. */
558 if (!ss->opt.enableSessionTickets)
559 return 0;
560
561 /* Empty extension length = extension_type (2-bytes) +
562 * length(extension_data) (2-bytes)
563 */
564 extension_length = 4;
565
566 /* If we are a client then send a session ticket if one is availble.
567 * Servers that support the extension and are willing to negotiate the
568 * the extension always respond with an empty extension.
569 */
570 if (!ss->sec.isServer) {
571 /* The caller must be holding sid->u.ssl3.lock for reading. We cannot
572 * just acquire and release the lock within this function because the
573 * caller will call this function twice, and we need the inputs to be
574 * consistent between the two calls. Note that currently the caller
575 * will only be holding the lock when we are the client and when we're
576 * attempting to resume an existing session.
577 */
578
579 session_ticket = &sid->u.ssl3.locked.sessionTicket;
580 if (session_ticket->ticket.data) {
581 if (ss->xtnData.ticketTimestampVerified) {
582 extension_length += session_ticket->ticket.len;
583 } else if (!append &&
584 (session_ticket->ticket_lifetime_hint == 0 ||
585 (session_ticket->ticket_lifetime_hint +
586 session_ticket->received_timestamp >
587 ssl_Time()))) {
588 extension_length += session_ticket->ticket.len;
589 ss->xtnData.ticketTimestampVerified = PR_TRUE;
590 }
591 }
592 }
593
594 if (maxBytes < (PRUint32)extension_length) {
595 PORT_Assert(0);
596 return 0;
597 }
598 if (append) {
599 SECStatus rv;
600 /* extension_type */
601 rv = ssl3_AppendHandshakeNumber(ss, ssl_session_ticket_xtn, 2);
602 if (rv != SECSuccess)
603 goto loser;
604 if (session_ticket && session_ticket->ticket.data &&
605 ss->xtnData.ticketTimestampVerified) {
606 rv = ssl3_AppendHandshakeVariable(ss, session_ticket->ticket.data,
607 session_ticket->ticket.len, 2);
608 ss->xtnData.ticketTimestampVerified = PR_FALSE;
609 ss->xtnData.sentSessionTicketInClientHello = PR_TRUE;
610 } else {
611 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
612 }
613 if (rv != SECSuccess)
614 goto loser;
615
616 if (!ss->sec.isServer) {
617 TLSExtensionData *xtnData = &ss->xtnData;
618 xtnData->advertised[xtnData->numAdvertised++] =
619 ssl_session_ticket_xtn;
620 }
621 }
622 return extension_length;
623
624 loser:
625 ss->xtnData.ticketTimestampVerified = PR_FALSE;
626 return -1;
627 }
628
629 /* handle an incoming Next Protocol Negotiation extension. */
630 static SECStatus
631 ssl3_ServerHandleNextProtoNegoXtn(sslSocket *ss, PRUint16 ex_type,
632 SECItem *data)
633 {
634 if (ss->firstHsDone || data->len != 0) {
635 /* Clients MUST send an empty NPN extension, if any. */
636 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
637 return SECFailure;
638 }
639
640 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
641
642 /* TODO: server side NPN support would require calling
643 * ssl3_RegisterServerHelloExtensionSender here in order to echo the
644 * extension back to the client. */
645
646 return SECSuccess;
647 }
648
649 /* ssl3_ValidateNextProtoNego checks that the given block of data is valid: none
650 * of the lengths may be 0 and the sum of the lengths must equal the length of
651 * the block. */
652 SECStatus
653 ssl3_ValidateNextProtoNego(const unsigned char *data, unsigned int length)
654 {
655 unsigned int offset = 0;
656
657 while (offset < length) {
658 unsigned int newOffset = offset + 1 + (unsigned int)data[offset];
659 /* Reject embedded nulls to protect against buggy applications that
660 * store protocol identifiers in null-terminated strings.
661 */
662 if (newOffset > length || data[offset] == 0) {
663 return SECFailure;
664 }
665 offset = newOffset;
666 }
667
668 return SECSuccess;
669 }
670
671 /* protocol selection handler for ALPN (server side) and NPN (client side) */
672 static SECStatus
673 ssl3_SelectAppProtocol(sslSocket *ss, PRUint16 ex_type, SECItem *data)
674 {
675 SECStatus rv;
676 unsigned char resultBuffer[255];
677 SECItem result = { siBuffer, resultBuffer, 0 };
678
679 rv = ssl3_ValidateNextProtoNego(data->data, data->len);
680 if (rv != SECSuccess) {
681 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
682 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
683 return rv;
684 }
685
686 PORT_Assert(ss->nextProtoCallback);
687 /* For ALPN, the cipher suite isn't selected yet. Note that extensions
688 * sometimes affect what cipher suite is selected, e.g., for ECC. */
689 PORT_Assert((ss->ssl3.hs.preliminaryInfo &
690 ssl_preinfo_all & ~ssl_preinfo_cipher_suite) ==
691 (ssl_preinfo_all & ~ssl_preinfo_cipher_suite));
692 rv = ss->nextProtoCallback(ss->nextProtoArg, ss->fd, data->data, data->len,
693 result.data, &result.len, sizeof(resultBuffer));
694 if (rv != SECSuccess) {
695 /* Expect callback to call PORT_SetError() */
696 (void)SSL3_SendAlert(ss, alert_fatal, internal_error);
697 return SECFailure;
698 }
699
700 /* If the callback wrote more than allowed to |result| it has corrupted our
701 * stack. */
702 if (result.len > sizeof(resultBuffer)) {
703 PORT_SetError(SEC_ERROR_OUTPUT_LEN);
704 /* TODO: crash */
705 return SECFailure;
706 }
707
708 SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE);
709
710 if (ex_type == ssl_app_layer_protocol_xtn &&
711 ss->ssl3.nextProtoState != SSL_NEXT_PROTO_NEGOTIATED) {
712 /* The callback might say OK, but then it picks a default value - one
713 * that was not listed. That's OK for NPN, but not ALPN. */
714 (void)SSL3_SendAlert(ss, alert_fatal, no_application_protocol);
715 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_NO_PROTOCOL);
716 return SECFailure;
717 }
718
719 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
720 return SECITEM_CopyItem(NULL, &ss->ssl3.nextProto, &result);
721 }
722
723 /* handle an incoming ALPN extension at the server */
724 static SECStatus
725 ssl3_ServerHandleAppProtoXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data)
726 {
727 int count;
728 SECStatus rv;
729
730 /* We expressly don't want to allow ALPN on renegotiation,
731 * despite it being permitted by the spec. */
732 if (ss->firstHsDone || data->len == 0) {
733 /* Clients MUST send a non-empty ALPN extension. */
734 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
735 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
736 return SECFailure;
737 }
738
739 /* Unlike NPN, ALPN has extra redundant length information so that
740 * the extension is the same in both ClientHello and ServerHello. */
741 count = ssl3_ConsumeHandshakeNumber(ss, 2, &data->data, &data->len);
742 if (count != data->len) {
743 (void)ssl3_DecodeError(ss);
744 return SECFailure;
745 }
746
747 if (!ss->nextProtoCallback) {
748 /* we're not configured for it */
749 return SECSuccess;
750 }
751
752 rv = ssl3_SelectAppProtocol(ss, ex_type, data);
753 if (rv != SECSuccess) {
754 return rv;
755 }
756
757 /* prepare to send back a response, if we negotiated */
758 if (ss->ssl3.nextProtoState == SSL_NEXT_PROTO_NEGOTIATED) {
759 rv = ssl3_RegisterServerHelloExtensionSender(
760 ss, ex_type, ssl3_ServerSendAppProtoXtn);
761 if (rv != SECSuccess) {
762 (void)SSL3_SendAlert(ss, alert_fatal, internal_error);
763 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
764 return rv;
765 }
766 }
767 return SECSuccess;
768 }
769
770 static SECStatus
771 ssl3_ClientHandleNextProtoNegoXtn(sslSocket *ss, PRUint16 ex_type,
772 SECItem *data)
773 {
774 PORT_Assert(!ss->firstHsDone);
775
776 if (ssl3_ExtensionNegotiated(ss, ssl_app_layer_protocol_xtn)) {
777 /* If the server negotiated ALPN then it has already told us what
778 * protocol to use, so it doesn't make sense for us to try to negotiate
779 * a different one by sending the NPN handshake message. However, if
780 * we've negotiated NPN then we're required to send the NPN handshake
781 * message. Thus, these two extensions cannot both be negotiated on the
782 * same connection. */
783 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
784 PORT_SetError(SSL_ERROR_BAD_SERVER);
785 return SECFailure;
786 }
787
788 /* We should only get this call if we sent the extension, so
789 * ss->nextProtoCallback needs to be non-NULL. However, it is possible
790 * that an application erroneously cleared the callback between the time
791 * we sent the ClientHello and now. */
792 if (!ss->nextProtoCallback) {
793 PORT_Assert(0);
794 (void)SSL3_SendAlert(ss, alert_fatal, internal_error);
795 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_NO_CALLBACK);
796 return SECFailure;
797 }
798
799 return ssl3_SelectAppProtocol(ss, ex_type, data);
800 }
801
802 static SECStatus
803 ssl3_ClientHandleAppProtoXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data)
804 {
805 SECStatus rv;
806 PRInt32 list_len;
807 SECItem protocol_name;
808
809 if (ssl3_ExtensionNegotiated(ss, ssl_next_proto_nego_xtn)) {
810 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
811 return SECFailure;
812 }
813
814 /* The extension data from the server has the following format:
815 * uint16 name_list_len;
816 * uint8 len; // where len >= 1
817 * uint8 protocol_name[len]; */
818 if (data->len < 4 || data->len > 2 + 1 + 255) {
819 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
820 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
821 return SECFailure;
822 }
823
824 list_len = ssl3_ConsumeHandshakeNumber(ss, 2, &data->data, &data->len);
825 /* The list has to be the entire extension. */
826 if (list_len != data->len) {
827 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
828 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
829 return SECFailure;
830 }
831
832 rv = ssl3_ConsumeHandshakeVariable(ss, &protocol_name, 1,
833 &data->data, &data->len);
834 /* The list must have exactly one value. */
835 if (rv != SECSuccess || data->len != 0) {
836 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
837 PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
838 return SECFailure;
839 }
840
841 SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE);
842 ss->ssl3.nextProtoState = SSL_NEXT_PROTO_SELECTED;
843 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
844 return SECITEM_CopyItem(NULL, &ss->ssl3.nextProto, &protocol_name);
845 }
846
847 static PRInt32
848 ssl3_ClientSendNextProtoNegoXtn(sslSocket *ss, PRBool append,
849 PRUint32 maxBytes)
850 {
851 PRInt32 extension_length;
852
853 /* Renegotiations do not send this extension. */
854 if (!ss->opt.enableNPN || !ss->nextProtoCallback || ss->firstHsDone) {
855 return 0;
856 }
857
858 extension_length = 4;
859
860 if (maxBytes < (PRUint32)extension_length) {
861 return 0;
862 }
863 if (append) {
864 SECStatus rv;
865 rv = ssl3_AppendHandshakeNumber(ss, ssl_next_proto_nego_xtn, 2);
866 if (rv != SECSuccess)
867 goto loser;
868 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
869 if (rv != SECSuccess)
870 goto loser;
871 ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
872 ssl_next_proto_nego_xtn;
873 }
874
875 return extension_length;
876
877 loser:
878 return -1;
879 }
880
881 static PRInt32
882 ssl3_ClientSendAppProtoXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes)
883 {
884 PRInt32 extension_length;
885 unsigned char *alpn_protos = NULL;
886
887 /* Renegotiations do not send this extension. */
888 if (!ss->opt.enableALPN || !ss->opt.nextProtoNego.data || ss->firstHsDone) {
889 return 0;
890 }
891
892 extension_length = 2 /* extension type */ + 2 /* extension length */ +
893 2 /* protocol name list length */ +
894 ss->opt.nextProtoNego.len;
895
896 if (maxBytes < (PRUint32)extension_length) {
897 return 0;
898 }
899 if (append) {
900 /* NPN requires that the client's fallback protocol is first in the
901 * list. However, ALPN sends protocols in preference order. So we
902 * allocate a buffer and move the first protocol to the end of the
903 * list. */
904 SECStatus rv;
905 const unsigned int len = ss->opt.nextProtoNego.len;
906
907 alpn_protos = PORT_Alloc(len);
908 if (alpn_protos == NULL) {
909 return SECFailure;
910 }
911 if (len > 0) {
912 /* Each protocol string is prefixed with a single byte length. */
913 unsigned int i = ss->opt.nextProtoNego.data[0] + 1;
914 if (i <= len) {
915 memcpy(alpn_protos, &ss->opt.nextProtoNego.data[i], len - i);
916 memcpy(alpn_protos + len - i, ss->opt.nextProtoNego.data, i);
917 } else {
918 /* This seems to be invalid data so we'll send as-is. */
919 memcpy(alpn_protos, ss->opt.nextProtoNego.data, len);
920 }
921 }
922
923 rv = ssl3_AppendHandshakeNumber(ss, ssl_app_layer_protocol_xtn, 2);
924 if (rv != SECSuccess) {
925 goto loser;
926 }
927 rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2);
928 if (rv != SECSuccess) {
929 goto loser;
930 }
931 rv = ssl3_AppendHandshakeVariable(ss, alpn_protos, len, 2);
932 PORT_Free(alpn_protos);
933 alpn_protos = NULL;
934 if (rv != SECSuccess) {
935 goto loser;
936 }
937 ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
938 ssl_app_layer_protocol_xtn;
939 }
940
941 return extension_length;
942
943 loser:
944 if (alpn_protos) {
945 PORT_Free(alpn_protos);
946 }
947 return -1;
948 }
949
950 static PRInt32
951 ssl3_ServerSendAppProtoXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes)
952 {
953 PRInt32 extension_length;
954
955 /* we're in over our heads if any of these fail */
956 PORT_Assert(ss->opt.enableALPN);
957 PORT_Assert(ss->ssl3.nextProto.data);
958 PORT_Assert(ss->ssl3.nextProto.len > 0);
959 PORT_Assert(ss->ssl3.nextProtoState == SSL_NEXT_PROTO_NEGOTIATED);
960 PORT_Assert(!ss->firstHsDone);
961
962 extension_length = 2 /* extension type */ + 2 /* extension length */ +
963 2 /* protocol name list */ + 1 /* name length */ +
964 ss->ssl3.nextProto.len;
965
966 if (maxBytes < (PRUint32)extension_length) {
967 return 0;
968 }
969 if (append) {
970 SECStatus rv;
971 rv = ssl3_AppendHandshakeNumber(ss, ssl_app_layer_protocol_xtn, 2);
972 if (rv != SECSuccess) {
973 return -1;
974 }
975 rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2);
976 if (rv != SECSuccess) {
977 return -1;
978 }
979 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.nextProto.len + 1, 2);
980 if (rv != SECSuccess) {
981 return -1;
982 }
983 rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.nextProto.data,
984 ss->ssl3.nextProto.len, 1);
985 if (rv != SECSuccess) {
986 return -1;
987 }
988 }
989
990 return extension_length;
991 }
992
993 static SECStatus
994 ssl3_ClientHandleChannelIDXtn(sslSocket *ss, PRUint16 ex_type,
995 SECItem *data)
996 {
997 PORT_Assert(ss->getChannelID != NULL);
998
999 if (data->len) {
1000 PORT_SetError(SSL_ERROR_BAD_CHANNEL_ID_DATA);
1001 return SECFailure;
1002 }
1003 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
1004 return SECSuccess;
1005 }
1006
1007 static PRInt32
1008 ssl3_ClientSendChannelIDXtn(sslSocket *ss, PRBool append,
1009 PRUint32 maxBytes)
1010 {
1011 PRInt32 extension_length = 4;
1012
1013 if (!ss->getChannelID)
1014 return 0;
1015
1016 if (maxBytes < extension_length) {
1017 PORT_Assert(0);
1018 return 0;
1019 }
1020
1021 if (ss->sec.ci.sid->cached != never_cached &&
1022 ss->sec.ci.sid->u.ssl3.originalHandshakeHash.len == 0) {
1023 /* We can't do ChannelID on a connection if we're resuming and didn't
1024 * do ChannelID on the original connection: without ChannelID on the
1025 * original connection we didn't record the handshake hashes needed for
1026 * the signature. */
1027 return 0;
1028 }
1029
1030 if (append) {
1031 SECStatus rv;
1032 rv = ssl3_AppendHandshakeNumber(ss, ssl_channel_id_xtn, 2);
1033 if (rv != SECSuccess)
1034 goto loser;
1035 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
1036 if (rv != SECSuccess)
1037 goto loser;
1038 ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
1039 ssl_channel_id_xtn;
1040 }
1041
1042 return extension_length;
1043
1044 loser:
1045 return -1;
1046 }
1047
1048 static SECStatus
1049 ssl3_ClientHandleStatusRequestXtn(sslSocket *ss, PRUint16 ex_type,
1050 SECItem *data)
1051 {
1052 /* The echoed extension must be empty. */
1053 if (data->len != 0) {
1054 return SECSuccess; /* Ignore the extension. */
1055 }
1056
1057 /* Keep track of negotiated extensions. */
1058 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
1059
1060 return SECSuccess;
1061 }
1062
1063 static PRInt32
1064 ssl3_ServerSendStatusRequestXtn(
1065 sslSocket *ss,
1066 PRBool append,
1067 PRUint32 maxBytes)
1068 {
1069 PRInt32 extension_length;
1070 SSLKEAType effectiveExchKeyType;
1071 SECStatus rv;
1072
1073 /* ssl3_SendCertificateStatus (which sents the certificate status data)
1074 * uses the exact same logic to select the server certificate
1075 * and determine if we have the status for that certificate. */
1076
1077 if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa ||
1078 ss->ssl3.hs.kea_def->kea == kea_dhe_rsa) {
1079 effectiveExchKeyType = ssl_kea_rsa;
1080 } else {
1081 effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType;
1082 }
1083
1084 if (!ss->certStatusArray[effectiveExchKeyType] ||
1085 !ss->certStatusArray[effectiveExchKeyType]->len) {
1086 return 0;
1087 }
1088
1089 extension_length = 2 + 2;
1090 if (maxBytes < (PRUint32)extension_length) {
1091 return 0;
1092 }
1093 if (append) {
1094 /* extension_type */
1095 rv = ssl3_AppendHandshakeNumber(ss, ssl_cert_status_xtn, 2);
1096 if (rv != SECSuccess)
1097 return -1;
1098 /* length of extension_data */
1099 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
1100 if (rv != SECSuccess)
1101 return -1;
1102 /* The certificate status data is sent in ssl3_SendCertificateStatus. */
1103 }
1104
1105 return extension_length;
1106 }
1107
1108 /* ssl3_ClientSendStatusRequestXtn builds the status_request extension on the
1109 * client side. See RFC 4366 section 3.6. */
1110 static PRInt32
1111 ssl3_ClientSendStatusRequestXtn(sslSocket *ss, PRBool append,
1112 PRUint32 maxBytes)
1113 {
1114 PRInt32 extension_length;
1115
1116 if (!ss->opt.enableOCSPStapling)
1117 return 0;
1118
1119 /* extension_type (2-bytes) +
1120 * length(extension_data) (2-bytes) +
1121 * status_type (1) +
1122 * responder_id_list length (2) +
1123 * request_extensions length (2)
1124 */
1125 extension_length = 9;
1126
1127 if (maxBytes < (PRUint32)extension_length) {
1128 PORT_Assert(0);
1129 return 0;
1130 }
1131 if (append) {
1132 SECStatus rv;
1133 TLSExtensionData *xtnData;
1134
1135 /* extension_type */
1136 rv = ssl3_AppendHandshakeNumber(ss, ssl_cert_status_xtn, 2);
1137 if (rv != SECSuccess)
1138 return -1;
1139 rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2);
1140 if (rv != SECSuccess)
1141 return -1;
1142 rv = ssl3_AppendHandshakeNumber(ss, 1 /* status_type ocsp */, 1);
1143 if (rv != SECSuccess)
1144 return -1;
1145 /* A zero length responder_id_list means that the responders are
1146 * implicitly known to the server. */
1147 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
1148 if (rv != SECSuccess)
1149 return -1;
1150 /* A zero length request_extensions means that there are no extensions.
1151 * Specifically, we don't set the id-pkix-ocsp-nonce extension. This
1152 * means that the server can replay a cached OCSP response to us. */
1153 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
1154 if (rv != SECSuccess)
1155 return -1;
1156
1157 xtnData = &ss->xtnData;
1158 xtnData->advertised[xtnData->numAdvertised++] = ssl_cert_status_xtn;
1159 }
1160 return extension_length;
1161 }
1162
1163 /*
1164 * NewSessionTicket
1165 * Called from ssl3_HandleFinished
1166 */
1167 SECStatus
1168 ssl3_SendNewSessionTicket(sslSocket *ss)
1169 {
1170 PRUint32 i;
1171 SECStatus rv;
1172 NewSessionTicket ticket;
1173 SECItem plaintext;
1174 SECItem plaintext_item = { 0, NULL, 0 };
1175 SECItem ciphertext = { 0, NULL, 0 };
1176 PRUint32 ciphertext_length;
1177 PRBool ms_is_wrapped;
1178 unsigned char wrapped_ms[SSL3_MASTER_SECRET_LENGTH];
1179 SECItem ms_item = { 0, NULL, 0 };
1180 SSL3KEAType effectiveExchKeyType = ssl_kea_null;
1181 PRUint32 padding_length;
1182 PRUint32 message_length;
1183 PRUint32 cert_length = 0;
1184 PRUint8 length_buf[4];
1185 PRUint32 now;
1186 PK11SymKey *aes_key_pkcs11;
1187 PK11SymKey *mac_key_pkcs11;
1188 #ifndef NO_PKCS11_BYPASS
1189 const unsigned char *aes_key;
1190 const unsigned char *mac_key;
1191 PRUint32 aes_key_length;
1192 PRUint32 mac_key_length;
1193 PRUint64 aes_ctx_buf[MAX_CIPHER_CONTEXT_LLONGS];
1194 AESContext *aes_ctx;
1195 const SECHashObject *hashObj = NULL;
1196 PRUint64 hmac_ctx_buf[MAX_MAC_CONTEXT_LLONGS];
1197 HMACContext *hmac_ctx;
1198 #endif
1199 CK_MECHANISM_TYPE cipherMech = CKM_AES_CBC;
1200 PK11Context *aes_ctx_pkcs11;
1201 CK_MECHANISM_TYPE macMech = CKM_SHA256_HMAC;
1202 PK11Context *hmac_ctx_pkcs11 = NULL;
1203 unsigned char computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH];
1204 unsigned int computed_mac_length;
1205 unsigned char iv[AES_BLOCK_SIZE];
1206 SECItem ivItem;
1207 SECItem *srvName = NULL;
1208 PRUint32 srvNameLen = 0;
1209 CK_MECHANISM_TYPE msWrapMech = 0; /* dummy default value,
1210 * must be >= 0 */
1211
1212 SSL_TRC(3, ("%d: SSL3[%d]: send session_ticket handshake",
1213 SSL_GETPID(), ss->fd));
1214
1215 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
1216 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
1217
1218 ticket.ticket_lifetime_hint = TLS_EX_SESS_TICKET_LIFETIME_HINT;
1219 if (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) {
1220 cert_length = 3 + ss->sec.ci.sid->peerCert->derCert.len;
1221 }
1222
1223 /* Get IV and encryption keys */
1224 ivItem.data = iv;
1225 ivItem.len = sizeof(iv);
1226 rv = PK11_GenerateRandom(iv, sizeof(iv));
1227 if (rv != SECSuccess)
1228 goto loser;
1229
1230 #ifndef NO_PKCS11_BYPASS
1231 if (ss->opt.bypassPKCS11) {
1232 rv = ssl3_GetSessionTicketKeys(&aes_key, &aes_key_length,
1233 &mac_key, &mac_key_length);
1234 } else
1235 #endif
1236 {
1237 rv = ssl3_GetSessionTicketKeysPKCS11(ss, &aes_key_pkcs11,
1238 &mac_key_pkcs11);
1239 }
1240 if (rv != SECSuccess)
1241 goto loser;
1242
1243 if (ss->ssl3.pwSpec->msItem.len && ss->ssl3.pwSpec->msItem.data) {
1244 /* The master secret is available unwrapped. */
1245 ms_item.data = ss->ssl3.pwSpec->msItem.data;
1246 ms_item.len = ss->ssl3.pwSpec->msItem.len;
1247 ms_is_wrapped = PR_FALSE;
1248 } else {
1249 /* Extract the master secret wrapped. */
1250 sslSessionID sid;
1251 PORT_Memset(&sid, 0, sizeof(sslSessionID));
1252
1253 if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa ||
1254 ss->ssl3.hs.kea_def->kea == kea_dhe_rsa) {
1255 effectiveExchKeyType = kt_rsa;
1256 } else {
1257 effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType;
1258 }
1259
1260 rv = ssl3_CacheWrappedMasterSecret(ss, &sid, ss->ssl3.pwSpec,
1261 effectiveExchKeyType);
1262 if (rv == SECSuccess) {
1263 if (sid.u.ssl3.keys.wrapped_master_secret_len > sizeof(wrapped_ms))
1264 goto loser;
1265 memcpy(wrapped_ms, sid.u.ssl3.keys.wrapped_master_secret,
1266 sid.u.ssl3.keys.wrapped_master_secret_len);
1267 ms_item.data = wrapped_ms;
1268 ms_item.len = sid.u.ssl3.keys.wrapped_master_secret_len;
1269 msWrapMech = sid.u.ssl3.masterWrapMech;
1270 } else {
1271 /* TODO: else send an empty ticket. */
1272 goto loser;
1273 }
1274 ms_is_wrapped = PR_TRUE;
1275 }
1276 /* Prep to send negotiated name */
1277 srvName = &ss->ssl3.pwSpec->srvVirtName;
1278 if (srvName->data && srvName->len) {
1279 srvNameLen = 2 + srvName->len; /* len bytes + name len */
1280 }
1281
1282 ciphertext_length =
1283 sizeof(PRUint16) /* ticket_version */
1284 + sizeof(SSL3ProtocolVersion) /* ssl_version */
1285 + sizeof(ssl3CipherSuite) /* ciphersuite */
1286 + 1 /* compression */
1287 + 10 /* cipher spec parameters */
1288 + 1 /* SessionTicket.ms_is_wrapped */
1289 + 1 /* effectiveExchKeyType */
1290 + 4 /* msWrapMech */
1291 + 2 /* master_secret.length */
1292 + ms_item.len /* master_secret */
1293 + 1 /* client_auth_type */
1294 + cert_length /* cert */
1295 + 1 /* server name type */
1296 + srvNameLen /* name len + length field */
1297 + 1 /* extendedMasterSecretUsed */
1298 + sizeof(ticket.ticket_lifetime_hint);
1299 padding_length = AES_BLOCK_SIZE -
1300 (ciphertext_length %
1301 AES_BLOCK_SIZE);
1302 ciphertext_length += padding_length;
1303
1304 message_length =
1305 sizeof(ticket.ticket_lifetime_hint) /* ticket_lifetime_hint */
1306 + 2 /* length field for NewSessionTicket .ticket */
1307 + SESS_TICKET_KEY_NAME_LEN /* key_name */
1308 + AES_BLOCK_SIZE /* iv */
1309 + 2 /* length field for NewSessionTicket .ticket.encrypted_state */
1310 + ciphertext_length /* encrypted_state */
1311 + TLS_EX_SESS_TICKET_MAC_LENGTH; /* mac */
1312
1313 if (SECITEM_AllocItem(NULL, &plaintext_item, ciphertext_length) == NULL)
1314 goto loser;
1315
1316 plaintext = plaintext_item;
1317
1318 /* ticket_version */
1319 rv = ssl3_AppendNumberToItem(&plaintext, TLS_EX_SESS_TICKET_VERSION,
1320 sizeof(PRUint16));
1321 if (rv != SECSuccess)
1322 goto loser;
1323
1324 /* ssl_version */
1325 rv = ssl3_AppendNumberToItem(&plaintext, ss->version,
1326 sizeof(SSL3ProtocolVersion));
1327 if (rv != SECSuccess)
1328 goto loser;
1329
1330 /* ciphersuite */
1331 rv = ssl3_AppendNumberToItem(&plaintext, ss->ssl3.hs.cipher_suite,
1332 sizeof(ssl3CipherSuite));
1333 if (rv != SECSuccess)
1334 goto loser;
1335
1336 /* compression */
1337 rv = ssl3_AppendNumberToItem(&plaintext, ss->ssl3.hs.compression, 1);
1338 if (rv != SECSuccess)
1339 goto loser;
1340
1341 /* cipher spec parameters */
1342 rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.authAlgorithm, 1);
1343 if (rv != SECSuccess)
1344 goto loser;
1345 rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.authKeyBits, 4);
1346 if (rv != SECSuccess)
1347 goto loser;
1348 rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.keaType, 1);
1349 if (rv != SECSuccess)
1350 goto loser;
1351 rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.keaKeyBits, 4);
1352 if (rv != SECSuccess)
1353 goto loser;
1354
1355 /* master_secret */
1356 rv = ssl3_AppendNumberToItem(&plaintext, ms_is_wrapped, 1);
1357 if (rv != SECSuccess)
1358 goto loser;
1359 rv = ssl3_AppendNumberToItem(&plaintext, effectiveExchKeyType, 1);
1360 if (rv != SECSuccess)
1361 goto loser;
1362 rv = ssl3_AppendNumberToItem(&plaintext, msWrapMech, 4);
1363 if (rv != SECSuccess)
1364 goto loser;
1365 rv = ssl3_AppendNumberToItem(&plaintext, ms_item.len, 2);
1366 if (rv != SECSuccess)
1367 goto loser;
1368 rv = ssl3_AppendToItem(&plaintext, ms_item.data, ms_item.len);
1369 if (rv != SECSuccess)
1370 goto loser;
1371
1372 /* client_identity */
1373 if (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) {
1374 rv = ssl3_AppendNumberToItem(&plaintext, CLIENT_AUTH_CERTIFICATE, 1);
1375 if (rv != SECSuccess)
1376 goto loser;
1377 rv = ssl3_AppendNumberToItem(&plaintext,
1378 ss->sec.ci.sid->peerCert->derCert.len, 3);
1379 if (rv != SECSuccess)
1380 goto loser;
1381 rv = ssl3_AppendToItem(&plaintext,
1382 ss->sec.ci.sid->peerCert->derCert.data,
1383 ss->sec.ci.sid->peerCert->derCert.len);
1384 if (rv != SECSuccess)
1385 goto loser;
1386 } else {
1387 rv = ssl3_AppendNumberToItem(&plaintext, 0, 1);
1388 if (rv != SECSuccess)
1389 goto loser;
1390 }
1391
1392 /* timestamp */
1393 now = ssl_Time();
1394 rv = ssl3_AppendNumberToItem(&plaintext, now,
1395 sizeof(ticket.ticket_lifetime_hint));
1396 if (rv != SECSuccess)
1397 goto loser;
1398
1399 if (srvNameLen) {
1400 /* Name Type (sni_host_name) */
1401 rv = ssl3_AppendNumberToItem(&plaintext, srvName->type, 1);
1402 if (rv != SECSuccess)
1403 goto loser;
1404 /* HostName (length and value) */
1405 rv = ssl3_AppendNumberToItem(&plaintext, srvName->len, 2);
1406 if (rv != SECSuccess)
1407 goto loser;
1408 rv = ssl3_AppendToItem(&plaintext, srvName->data, srvName->len);
1409 if (rv != SECSuccess)
1410 goto loser;
1411 } else {
1412 /* No Name */
1413 rv = ssl3_AppendNumberToItem(&plaintext, (char)TLS_STE_NO_SERVER_NAME, 1 );
1414 if (rv != SECSuccess)
1415 goto loser;
1416 }
1417
1418 /* extendedMasterSecretUsed */
1419 rv = ssl3_AppendNumberToItem(
1420 &plaintext, ss->sec.ci.sid->u.ssl3.keys.extendedMasterSecretUsed, 1);
1421 if (rv != SECSuccess)
1422 goto loser;
1423
1424 PORT_Assert(plaintext.len == padding_length);
1425 for (i = 0; i < padding_length; i++)
1426 plaintext.data[i] = (unsigned char)padding_length;
1427
1428 if (SECITEM_AllocItem(NULL, &ciphertext, ciphertext_length) == NULL) {
1429 rv = SECFailure;
1430 goto loser;
1431 }
1432
1433 /* Generate encrypted portion of ticket. */
1434 #ifndef NO_PKCS11_BYPASS
1435 if (ss->opt.bypassPKCS11) {
1436 aes_ctx = (AESContext *)aes_ctx_buf;
1437 rv = AES_InitContext(aes_ctx, aes_key, aes_key_length, iv,
1438 NSS_AES_CBC, 1, AES_BLOCK_SIZE);
1439 if (rv != SECSuccess)
1440 goto loser;
1441
1442 rv = AES_Encrypt(aes_ctx, ciphertext.data, &ciphertext.len,
1443 ciphertext.len, plaintext_item.data,
1444 plaintext_item.len);
1445 if (rv != SECSuccess)
1446 goto loser;
1447 } else
1448 #endif
1449 {
1450 aes_ctx_pkcs11 = PK11_CreateContextBySymKey(cipherMech,
1451 CKA_ENCRYPT, aes_key_pkcs11, &ivItem);
1452 if (!aes_ctx_pkcs11)
1453 goto loser;
1454
1455 rv = PK11_CipherOp(aes_ctx_pkcs11, ciphertext.data,
1456 (int *)&ciphertext.len, ciphertext.len,
1457 plaintext_item.data, plaintext_item.len);
1458 PK11_Finalize(aes_ctx_pkcs11);
1459 PK11_DestroyContext(aes_ctx_pkcs11, PR_TRUE);
1460 if (rv != SECSuccess)
1461 goto loser;
1462 }
1463
1464 /* Convert ciphertext length to network order. */
1465 length_buf[0] = (ciphertext.len >> 8) & 0xff;
1466 length_buf[1] = (ciphertext.len) & 0xff;
1467
1468 /* Compute MAC. */
1469 #ifndef NO_PKCS11_BYPASS
1470 if (ss->opt.bypassPKCS11) {
1471 hmac_ctx = (HMACContext *)hmac_ctx_buf;
1472 hashObj = HASH_GetRawHashObject(HASH_AlgSHA256);
1473 if (HMAC_Init(hmac_ctx, hashObj, mac_key,
1474 mac_key_length, PR_FALSE) != SECSuccess)
1475 goto loser;
1476
1477 HMAC_Begin(hmac_ctx);
1478 HMAC_Update(hmac_ctx, key_name, SESS_TICKET_KEY_NAME_LEN);
1479 HMAC_Update(hmac_ctx, iv, sizeof(iv));
1480 HMAC_Update(hmac_ctx, (unsigned char *)length_buf, 2);
1481 HMAC_Update(hmac_ctx, ciphertext.data, ciphertext.len);
1482 HMAC_Finish(hmac_ctx, computed_mac, &computed_mac_length,
1483 sizeof(computed_mac));
1484 } else
1485 #endif
1486 {
1487 SECItem macParam;
1488 macParam.data = NULL;
1489 macParam.len = 0;
1490 hmac_ctx_pkcs11 = PK11_CreateContextBySymKey(macMech,
1491 CKA_SIGN, mac_key_pkcs11, & macParam);
1492 if (!hmac_ctx_pkcs11)
1493 goto loser;
1494
1495 rv = PK11_DigestBegin(hmac_ctx_pkcs11);
1496 if (rv != SECSuccess)
1497 goto loser;
1498 rv = PK11_DigestOp(hmac_ctx_pkcs11, key_name,
1499 SESS_TICKET_KEY_NAME_LEN);
1500 if (rv != SECSuccess)
1501 goto loser;
1502 rv = PK11_DigestOp(hmac_ctx_pkcs11, iv, sizeof(iv));
1503 if (rv != SECSuccess)
1504 goto loser;
1505 rv = PK11_DigestOp(hmac_ctx_pkcs11, (unsigned char *)length_buf, 2);
1506 if (rv != SECSuccess)
1507 goto loser;
1508 rv = PK11_DigestOp(hmac_ctx_pkcs11, ciphertext.data, ciphertext.len);
1509 if (rv != SECSuccess)
1510 goto loser;
1511 rv = PK11_DigestFinal(hmac_ctx_pkcs11, computed_mac,
1512 &computed_mac_length, sizeof(computed_mac));
1513 if (rv != SECSuccess)
1514 goto loser;
1515 }
1516
1517 /* Serialize the handshake message. */
1518 rv = ssl3_AppendHandshakeHeader(ss, new_session_ticket, message_length);
1519 if (rv != SECSuccess)
1520 goto loser;
1521
1522 rv = ssl3_AppendHandshakeNumber(ss, ticket.ticket_lifetime_hint,
1523 sizeof(ticket.ticket_lifetime_hint));
1524 if (rv != SECSuccess)
1525 goto loser;
1526
1527 rv = ssl3_AppendHandshakeNumber(ss,
1528 message_length - sizeof(ticket.ticket_lifeti me_hint) - 2,
1529 2);
1530 if (rv != SECSuccess)
1531 goto loser;
1532
1533 rv = ssl3_AppendHandshake(ss, key_name, SESS_TICKET_KEY_NAME_LEN);
1534 if (rv != SECSuccess)
1535 goto loser;
1536
1537 rv = ssl3_AppendHandshake(ss, iv, sizeof(iv));
1538 if (rv != SECSuccess)
1539 goto loser;
1540
1541 rv = ssl3_AppendHandshakeVariable(ss, ciphertext.data, ciphertext.len, 2);
1542 if (rv != SECSuccess)
1543 goto loser;
1544
1545 rv = ssl3_AppendHandshake(ss, computed_mac, computed_mac_length);
1546 if (rv != SECSuccess)
1547 goto loser;
1548
1549 loser:
1550 if (hmac_ctx_pkcs11)
1551 PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE);
1552 if (plaintext_item.data)
1553 SECITEM_FreeItem(&plaintext_item, PR_FALSE);
1554 if (ciphertext.data)
1555 SECITEM_FreeItem(&ciphertext, PR_FALSE);
1556
1557 return rv;
1558 }
1559
1560 /* When a client receives a SessionTicket extension a NewSessionTicket
1561 * message is expected during the handshake.
1562 */
1563 SECStatus
1564 ssl3_ClientHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type,
1565 SECItem *data)
1566 {
1567 if (data->len != 0) {
1568 return SECSuccess; /* Ignore the extension. */
1569 }
1570
1571 /* Keep track of negotiated extensions. */
1572 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
1573 return SECSuccess;
1574 }
1575
1576 SECStatus
1577 ssl3_ServerHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type,
1578 SECItem *data)
1579 {
1580 SECStatus rv;
1581 SECItem *decrypted_state = NULL;
1582 SessionTicket *parsed_session_ticket = NULL;
1583 sslSessionID *sid = NULL;
1584 SSL3Statistics *ssl3stats;
1585
1586 /* Ignore the SessionTicket extension if processing is disabled. */
1587 if (!ss->opt.enableSessionTickets) {
1588 return SECSuccess;
1589 }
1590
1591 /* Keep track of negotiated extensions. */
1592 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
1593
1594 /* Parse the received ticket sent in by the client. We are
1595 * lenient about some parse errors, falling back to a fullshake
1596 * instead of terminating the current connection.
1597 */
1598 if (data->len == 0) {
1599 ss->xtnData.emptySessionTicket = PR_TRUE;
1600 } else {
1601 PRUint32 i;
1602 SECItem extension_data;
1603 EncryptedSessionTicket enc_session_ticket;
1604 unsigned char computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH];
1605 unsigned int computed_mac_length;
1606 #ifndef NO_PKCS11_BYPASS
1607 const SECHashObject *hashObj;
1608 const unsigned char *aes_key;
1609 const unsigned char *mac_key;
1610 PRUint32 aes_key_length;
1611 PRUint32 mac_key_length;
1612 PRUint64 hmac_ctx_buf[MAX_MAC_CONTEXT_LLONGS];
1613 HMACContext *hmac_ctx;
1614 PRUint64 aes_ctx_buf[MAX_CIPHER_CONTEXT_LLONGS];
1615 AESContext *aes_ctx;
1616 #endif
1617 PK11SymKey *aes_key_pkcs11;
1618 PK11SymKey *mac_key_pkcs11;
1619 PK11Context *hmac_ctx_pkcs11;
1620 CK_MECHANISM_TYPE macMech = CKM_SHA256_HMAC;
1621 PK11Context *aes_ctx_pkcs11;
1622 CK_MECHANISM_TYPE cipherMech = CKM_AES_CBC;
1623 unsigned char *padding;
1624 PRUint32 padding_length;
1625 unsigned char *buffer;
1626 unsigned int buffer_len;
1627 PRInt32 temp;
1628 SECItem cert_item;
1629 PRInt8 nameType = TLS_STE_NO_SERVER_NAME;
1630
1631 /* Turn off stateless session resumption if the client sends a
1632 * SessionTicket extension, even if the extension turns out to be
1633 * malformed (ss->sec.ci.sid is non-NULL when doing session
1634 * renegotiation.)
1635 */
1636 if (ss->sec.ci.sid != NULL) {
1637 if (ss->sec.uncache)
1638 ss->sec.uncache(ss->sec.ci.sid);
1639 ssl_FreeSID(ss->sec.ci.sid);
1640 ss->sec.ci.sid = NULL;
1641 }
1642
1643 extension_data.data = data->data; /* Keep a copy for future use. */
1644 extension_data.len = data->len;
1645
1646 if (ssl3_ParseEncryptedSessionTicket(ss, data, &enc_session_ticket) !=
1647 SECSuccess) {
1648 return SECSuccess; /* Pretend it isn't there */
1649 }
1650
1651 /* Get session ticket keys. */
1652 #ifndef NO_PKCS11_BYPASS
1653 if (ss->opt.bypassPKCS11) {
1654 rv = ssl3_GetSessionTicketKeys(&aes_key, &aes_key_length,
1655 &mac_key, &mac_key_length);
1656 } else
1657 #endif
1658 {
1659 rv = ssl3_GetSessionTicketKeysPKCS11(ss, &aes_key_pkcs11,
1660 &mac_key_pkcs11);
1661 }
1662 if (rv != SECSuccess) {
1663 SSL_DBG(("%d: SSL[%d]: Unable to get/generate session ticket keys.",
1664 SSL_GETPID(), ss->fd));
1665 goto loser;
1666 }
1667
1668 /* If the ticket sent by the client was generated under a key different
1669 * from the one we have, bypass ticket processing.
1670 */
1671 if (PORT_Memcmp(enc_session_ticket.key_name, key_name,
1672 SESS_TICKET_KEY_NAME_LEN) != 0) {
1673 SSL_DBG(("%d: SSL[%d]: Session ticket key_name sent mismatch.",
1674 SSL_GETPID(), ss->fd));
1675 goto no_ticket;
1676 }
1677
1678 /* Verify the MAC on the ticket. MAC verification may also
1679 * fail if the MAC key has been recently refreshed.
1680 */
1681 #ifndef NO_PKCS11_BYPASS
1682 if (ss->opt.bypassPKCS11) {
1683 hmac_ctx = (HMACContext *)hmac_ctx_buf;
1684 hashObj = HASH_GetRawHashObject(HASH_AlgSHA256);
1685 if (HMAC_Init(hmac_ctx, hashObj, mac_key,
1686 sizeof(session_ticket_mac_key), PR_FALSE) != SECSucces s)
1687 goto no_ticket;
1688 HMAC_Begin(hmac_ctx);
1689 HMAC_Update(hmac_ctx, extension_data.data,
1690 extension_data.len - TLS_EX_SESS_TICKET_MAC_LENGTH);
1691 if (HMAC_Finish(hmac_ctx, computed_mac, &computed_mac_length,
1692 sizeof(computed_mac)) != SECSuccess)
1693 goto no_ticket;
1694 } else
1695 #endif
1696 {
1697 SECItem macParam;
1698 macParam.data = NULL;
1699 macParam.len = 0;
1700 hmac_ctx_pkcs11 = PK11_CreateContextBySymKey(macMech,
1701 CKA_SIGN, mac_key_pkcs1 1, &macParam);
1702 if (!hmac_ctx_pkcs11) {
1703 SSL_DBG(("%d: SSL[%d]: Unable to create HMAC context: %d.",
1704 SSL_GETPID(), ss->fd, PORT_GetError()));
1705 goto no_ticket;
1706 } else {
1707 SSL_DBG(("%d: SSL[%d]: Successfully created HMAC context.",
1708 SSL_GETPID(), ss->fd));
1709 }
1710 rv = PK11_DigestBegin(hmac_ctx_pkcs11);
1711 rv = PK11_DigestOp(hmac_ctx_pkcs11, extension_data.data,
1712 extension_data.len -
1713 TLS_EX_SESS_TICKET_MAC_LENGTH);
1714 if (rv != SECSuccess) {
1715 PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE);
1716 goto no_ticket;
1717 }
1718 rv = PK11_DigestFinal(hmac_ctx_pkcs11, computed_mac,
1719 &computed_mac_length, sizeof(computed_mac));
1720 PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE);
1721 if (rv != SECSuccess)
1722 goto no_ticket;
1723 }
1724 if (NSS_SecureMemcmp(computed_mac, enc_session_ticket.mac,
1725 computed_mac_length) !=
1726 0) {
1727 SSL_DBG(("%d: SSL[%d]: Session ticket MAC mismatch.",
1728 SSL_GETPID(), ss->fd));
1729 goto no_ticket;
1730 }
1731
1732 /* We ignore key_name for now.
1733 * This is ok as MAC verification succeeded.
1734 */
1735
1736 /* Decrypt the ticket. */
1737
1738 /* Plaintext is shorter than the ciphertext due to padding. */
1739 decrypted_state = SECITEM_AllocItem(NULL, NULL,
1740 enc_session_ticket.encrypted_state.l en);
1741
1742 #ifndef NO_PKCS11_BYPASS
1743 if (ss->opt.bypassPKCS11) {
1744 aes_ctx = (AESContext *)aes_ctx_buf;
1745 rv = AES_InitContext(aes_ctx, aes_key,
1746 sizeof(session_ticket_enc_key), enc_session_tic ket.iv,
1747 NSS_AES_CBC, 0, AES_BLOCK_SIZE);
1748 if (rv != SECSuccess) {
1749 SSL_DBG(("%d: SSL[%d]: Unable to create AES context.",
1750 SSL_GETPID(), ss->fd));
1751 goto no_ticket;
1752 }
1753
1754 rv = AES_Decrypt(aes_ctx, decrypted_state->data,
1755 &decrypted_state->len, decrypted_state->len,
1756 enc_session_ticket.encrypted_state.data,
1757 enc_session_ticket.encrypted_state.len);
1758 if (rv != SECSuccess)
1759 goto no_ticket;
1760 } else
1761 #endif
1762 {
1763 SECItem ivItem;
1764 ivItem.data = enc_session_ticket.iv;
1765 ivItem.len = AES_BLOCK_SIZE;
1766 aes_ctx_pkcs11 = PK11_CreateContextBySymKey(cipherMech,
1767 CKA_DECRYPT, aes_key_pkc s11, &ivItem);
1768 if (!aes_ctx_pkcs11) {
1769 SSL_DBG(("%d: SSL[%d]: Unable to create AES context.",
1770 SSL_GETPID(), ss->fd));
1771 goto no_ticket;
1772 }
1773
1774 rv = PK11_CipherOp(aes_ctx_pkcs11, decrypted_state->data,
1775 (int *)&decrypted_state->len, decrypted_state->le n,
1776 enc_session_ticket.encrypted_state.data,
1777 enc_session_ticket.encrypted_state.len);
1778 PK11_Finalize(aes_ctx_pkcs11);
1779 PK11_DestroyContext(aes_ctx_pkcs11, PR_TRUE);
1780 if (rv != SECSuccess)
1781 goto no_ticket;
1782 }
1783
1784 /* Check padding. */
1785 padding_length =
1786 (PRUint32)decrypted_state->data[decrypted_state->len - 1];
1787 if (padding_length == 0 || padding_length > AES_BLOCK_SIZE)
1788 goto no_ticket;
1789
1790 padding = &decrypted_state->data[decrypted_state->len - padding_length];
1791 for (i = 0; i < padding_length; i++, padding++) {
1792 if (padding_length != (PRUint32)*padding)
1793 goto no_ticket;
1794 }
1795
1796 /* Deserialize session state. */
1797 buffer = decrypted_state->data;
1798 buffer_len = decrypted_state->len;
1799
1800 parsed_session_ticket = PORT_ZAlloc(sizeof(SessionTicket));
1801 if (parsed_session_ticket == NULL) {
1802 rv = SECFailure;
1803 goto loser;
1804 }
1805
1806 /* Read ticket_version and reject if the version is wrong */
1807 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1808 if (temp != TLS_EX_SESS_TICKET_VERSION)
1809 goto no_ticket;
1810
1811 parsed_session_ticket->ticket_version = (SSL3ProtocolVersion)temp;
1812
1813 /* Read SSLVersion. */
1814 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1815 if (temp < 0)
1816 goto no_ticket;
1817 parsed_session_ticket->ssl_version = (SSL3ProtocolVersion)temp;
1818
1819 /* Read cipher_suite. */
1820 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1821 if (temp < 0)
1822 goto no_ticket;
1823 parsed_session_ticket->cipher_suite = (ssl3CipherSuite)temp;
1824
1825 /* Read compression_method. */
1826 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1827 if (temp < 0)
1828 goto no_ticket;
1829 parsed_session_ticket->compression_method = (SSLCompressionMethod)temp;
1830
1831 /* Read cipher spec parameters. */
1832 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1833 if (temp < 0)
1834 goto no_ticket;
1835 parsed_session_ticket->authAlgorithm = (SSLSignType)temp;
1836 temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1837 if (temp < 0)
1838 goto no_ticket;
1839 parsed_session_ticket->authKeyBits = (PRUint32)temp;
1840 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1841 if (temp < 0)
1842 goto no_ticket;
1843 parsed_session_ticket->keaType = (SSLKEAType)temp;
1844 temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1845 if (temp < 0)
1846 goto no_ticket;
1847 parsed_session_ticket->keaKeyBits = (PRUint32)temp;
1848
1849 /* Read wrapped master_secret. */
1850 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1851 if (temp < 0)
1852 goto no_ticket;
1853 parsed_session_ticket->ms_is_wrapped = (PRBool)temp;
1854
1855 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1856 if (temp < 0)
1857 goto no_ticket;
1858 parsed_session_ticket->exchKeyType = (SSL3KEAType)temp;
1859
1860 temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1861 if (temp < 0)
1862 goto no_ticket;
1863 parsed_session_ticket->msWrapMech = (CK_MECHANISM_TYPE)temp;
1864
1865 temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len);
1866 if (temp < 0)
1867 goto no_ticket;
1868 parsed_session_ticket->ms_length = (PRUint16)temp;
1869 if (parsed_session_ticket->ms_length == 0 || /* sanity check MS. */
1870 parsed_session_ticket->ms_length >
1871 sizeof(parsed_session_ticket->master_secret))
1872 goto no_ticket;
1873
1874 /* Allow for the wrapped master secret to be longer. */
1875 if (buffer_len < parsed_session_ticket->ms_length)
1876 goto no_ticket;
1877 PORT_Memcpy(parsed_session_ticket->master_secret, buffer,
1878 parsed_session_ticket->ms_length);
1879 buffer += parsed_session_ticket->ms_length;
1880 buffer_len -= parsed_session_ticket->ms_length;
1881
1882 /* Read client_identity */
1883 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1884 if (temp < 0)
1885 goto no_ticket;
1886 parsed_session_ticket->client_identity.client_auth_type =
1887 (ClientAuthenticationType)temp;
1888 switch (parsed_session_ticket->client_identity.client_auth_type) {
1889 case CLIENT_AUTH_ANONYMOUS:
1890 break;
1891 case CLIENT_AUTH_CERTIFICATE:
1892 rv = ssl3_ConsumeHandshakeVariable(ss, &cert_item, 3,
1893 &buffer, &buffer_len);
1894 if (rv != SECSuccess)
1895 goto no_ticket;
1896 rv = SECITEM_CopyItem(NULL, &parsed_session_ticket->peer_cert,
1897 &cert_item);
1898 if (rv != SECSuccess)
1899 goto no_ticket;
1900 break;
1901 default:
1902 goto no_ticket;
1903 }
1904 /* Read timestamp. */
1905 temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len);
1906 if (temp < 0)
1907 goto no_ticket;
1908 parsed_session_ticket->timestamp = (PRUint32)temp;
1909
1910 /* Read server name */
1911 nameType =
1912 ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1913 if (nameType != TLS_STE_NO_SERVER_NAME) {
1914 SECItem name_item;
1915 rv = ssl3_ConsumeHandshakeVariable(ss, &name_item, 2, &buffer,
1916 &buffer_len);
1917 if (rv != SECSuccess)
1918 goto no_ticket;
1919 rv = SECITEM_CopyItem(NULL, &parsed_session_ticket->srvName,
1920 &name_item);
1921 if (rv != SECSuccess)
1922 goto no_ticket;
1923 parsed_session_ticket->srvName.type = nameType;
1924 }
1925
1926 /* Read extendedMasterSecretUsed */
1927 temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len);
1928 if (temp < 0)
1929 goto no_ticket;
1930 PORT_Assert(temp == PR_TRUE || temp == PR_FALSE);
1931 parsed_session_ticket->extendedMasterSecretUsed = (PRBool)temp;
1932
1933 /* Done parsing. Check that all bytes have been consumed. */
1934 if (buffer_len != padding_length)
1935 goto no_ticket;
1936
1937 /* Use the ticket if it has not expired, otherwise free the allocated
1938 * memory since the ticket is of no use.
1939 */
1940 if (parsed_session_ticket->timestamp != 0 &&
1941 parsed_session_ticket->timestamp +
1942 TLS_EX_SESS_TICKET_LIFETIME_HINT >
1943 ssl_Time()) {
1944
1945 sid = ssl3_NewSessionID(ss, PR_TRUE);
1946 if (sid == NULL) {
1947 rv = SECFailure;
1948 goto loser;
1949 }
1950
1951 /* Copy over parameters. */
1952 sid->version = parsed_session_ticket->ssl_version;
1953 sid->u.ssl3.cipherSuite = parsed_session_ticket->cipher_suite;
1954 sid->u.ssl3.compression = parsed_session_ticket->compression_method;
1955 sid->authAlgorithm = parsed_session_ticket->authAlgorithm;
1956 sid->authKeyBits = parsed_session_ticket->authKeyBits;
1957 sid->keaType = parsed_session_ticket->keaType;
1958 sid->keaKeyBits = parsed_session_ticket->keaKeyBits;
1959
1960 /* Copy master secret. */
1961 #ifndef NO_PKCS11_BYPASS
1962 if (ss->opt.bypassPKCS11 &&
1963 parsed_session_ticket->ms_is_wrapped)
1964 goto no_ticket;
1965 #endif
1966 if (parsed_session_ticket->ms_length >
1967 sizeof(sid->u.ssl3.keys.wrapped_master_secret))
1968 goto no_ticket;
1969 PORT_Memcpy(sid->u.ssl3.keys.wrapped_master_secret,
1970 parsed_session_ticket->master_secret,
1971 parsed_session_ticket->ms_length);
1972 sid->u.ssl3.keys.wrapped_master_secret_len =
1973 parsed_session_ticket->ms_length;
1974 sid->u.ssl3.exchKeyType = parsed_session_ticket->exchKeyType;
1975 sid->u.ssl3.masterWrapMech = parsed_session_ticket->msWrapMech;
1976 sid->u.ssl3.keys.msIsWrapped =
1977 parsed_session_ticket->ms_is_wrapped;
1978 sid->u.ssl3.masterValid = PR_TRUE;
1979 sid->u.ssl3.keys.resumable = PR_TRUE;
1980 sid->u.ssl3.keys.extendedMasterSecretUsed = parsed_session_ticket->e xtendedMasterSecretUsed;
1981
1982 /* Copy over client cert from session ticket if there is one. */
1983 if (parsed_session_ticket->peer_cert.data != NULL) {
1984 if (sid->peerCert != NULL)
1985 CERT_DestroyCertificate(sid->peerCert);
1986 sid->peerCert = CERT_NewTempCertificate(ss->dbHandle,
1987 &parsed_session_ticket-> peer_cert, NULL, PR_FALSE, PR_TRUE);
1988 if (sid->peerCert == NULL) {
1989 rv = SECFailure;
1990 goto loser;
1991 }
1992 }
1993 if (parsed_session_ticket->srvName.data != NULL) {
1994 sid->u.ssl3.srvName = parsed_session_ticket->srvName;
1995 }
1996 ss->statelessResume = PR_TRUE;
1997 ss->sec.ci.sid = sid;
1998 }
1999 }
2000
2001 if (0) {
2002 no_ticket:
2003 SSL_DBG(("%d: SSL[%d]: Session ticket parsing failed.",
2004 SSL_GETPID(), ss->fd));
2005 ssl3stats = SSL_GetStatistics();
2006 SSL_AtomicIncrementLong(&ssl3stats->hch_sid_ticket_parse_failures);
2007 }
2008 rv = SECSuccess;
2009
2010 loser:
2011 /* ss->sec.ci.sid == sid if it did NOT come here via goto statement
2012 * in that case do not free sid
2013 */
2014 if (sid && (ss->sec.ci.sid != sid)) {
2015 ssl_FreeSID(sid);
2016 sid = NULL;
2017 }
2018 if (decrypted_state != NULL) {
2019 SECITEM_FreeItem(decrypted_state, PR_TRUE);
2020 decrypted_state = NULL;
2021 }
2022
2023 if (parsed_session_ticket != NULL) {
2024 if (parsed_session_ticket->peer_cert.data) {
2025 SECITEM_FreeItem(&parsed_session_ticket->peer_cert, PR_FALSE);
2026 }
2027 PORT_ZFree(parsed_session_ticket, sizeof(SessionTicket));
2028 }
2029
2030 return rv;
2031 }
2032
2033 /*
2034 * Read bytes. Using this function means the SECItem structure
2035 * cannot be freed. The caller is expected to call this function
2036 * on a shallow copy of the structure.
2037 */
2038 static SECStatus
2039 ssl3_ConsumeFromItem(SECItem *item, unsigned char **buf, PRUint32 bytes)
2040 {
2041 if (bytes > item->len)
2042 return SECFailure;
2043
2044 *buf = item->data;
2045 item->data += bytes;
2046 item->len -= bytes;
2047 return SECSuccess;
2048 }
2049
2050 static SECStatus
2051 ssl3_ParseEncryptedSessionTicket(sslSocket *ss, SECItem *data,
2052 EncryptedSessionTicket *enc_session_ticket)
2053 {
2054 if (ssl3_ConsumeFromItem(data, &enc_session_ticket->key_name,
2055 SESS_TICKET_KEY_NAME_LEN) !=
2056 SECSuccess)
2057 return SECFailure;
2058 if (ssl3_ConsumeFromItem(data, &enc_session_ticket->iv,
2059 AES_BLOCK_SIZE) !=
2060 SECSuccess)
2061 return SECFailure;
2062 if (ssl3_ConsumeHandshakeVariable(ss, &enc_session_ticket->encrypted_state,
2063 2, &data->data, &data->len) !=
2064 SECSuccess)
2065 return SECFailure;
2066 if (ssl3_ConsumeFromItem(data, &enc_session_ticket->mac,
2067 TLS_EX_SESS_TICKET_MAC_LENGTH) !=
2068 SECSuccess)
2069 return SECFailure;
2070 if (data->len != 0) /* Make sure that we have consumed all bytes. */
2071 return SECFailure;
2072
2073 return SECSuccess;
2074 }
2075
2076 /* go through hello extensions in buffer "b".
2077 * For each one, find the extension handler in the table, and
2078 * if present, invoke that handler.
2079 * Servers ignore any extensions with unknown extension types.
2080 * Clients reject any extensions with unadvertised extension types.
2081 * In TLS >= 1.3, the client checks that extensions appear in the
2082 * right phase.
2083 */
2084 SECStatus
2085 ssl3_HandleHelloExtensions(sslSocket *ss, SSL3Opaque **b, PRUint32 *length,
2086 SSL3HandshakeType handshakeMessage)
2087 {
2088 const ssl3HelloExtensionHandler *handlers;
2089 PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
2090
2091 switch (handshakeMessage) {
2092 case client_hello:
2093 handlers = clientHelloHandlers;
2094 break;
2095 case encrypted_extensions:
2096 PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
2097 /* fall through */
2098 case server_hello:
2099 if (ss->version > SSL_LIBRARY_VERSION_3_0) {
2100 handlers = serverHelloHandlersTLS;
2101 } else {
2102 handlers = serverHelloHandlersSSL3;
2103 }
2104 break;
2105 default:
2106 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2107 PORT_Assert(0);
2108 return SECFailure;
2109 }
2110
2111 while (*length) {
2112 const ssl3HelloExtensionHandler *handler;
2113 SECStatus rv;
2114 PRInt32 extension_type;
2115 SECItem extension_data;
2116
2117 /* Get the extension's type field */
2118 extension_type = ssl3_ConsumeHandshakeNumber(ss, 2, b, length);
2119 if (extension_type < 0) /* failure to decode extension_type */
2120 return SECFailure; /* alert already sent */
2121
2122 /* get the data for this extension, so we can pass it or skip it. */
2123 rv = ssl3_ConsumeHandshakeVariable(ss, &extension_data, 2, b, length);
2124 if (rv != SECSuccess)
2125 return rv; /* alert already sent */
2126
2127 /* Check whether the server sent an extension which was not advertised
2128 * in the ClientHello */
2129 if (!ss->sec.isServer &&
2130 !ssl3_ClientExtensionAdvertised(ss, extension_type)) {
2131 (void)SSL3_SendAlert(ss, alert_fatal, unsupported_extension);
2132 return SECFailure;
2133 }
2134
2135 /* Check whether an extension has been sent multiple times. */
2136 if (ssl3_ExtensionNegotiated(ss, extension_type)) {
2137 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
2138 return SECFailure;
2139 }
2140
2141 /* Check that this is a legal extension in TLS 1.3 */
2142 if (isTLS13 && !tls13_ExtensionAllowed(extension_type, handshakeMessage) ) {
2143 if (handshakeMessage == client_hello) {
2144 /* Skip extensions not used in TLS 1.3 */
2145 continue;
2146 }
2147 tls13_FatalError(ss, SSL_ERROR_EXTENSION_DISALLOWED_FOR_VERSION,
2148 unsupported_extension);
2149 return SECFailure;
2150 }
2151
2152 /* find extension_type in table of Hello Extension Handlers */
2153 for (handler = handlers; handler->ex_type >= 0; handler++) {
2154 /* if found, call this handler */
2155 if (handler->ex_type == extension_type) {
2156 rv = (*handler->ex_handler)(ss, (PRUint16)extension_type,
2157 &extension_data);
2158 if (rv != SECSuccess) {
2159 if (!ss->ssl3.fatalAlertSent) {
2160 /* send a generic alert if the handler didn't already */
2161 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure) ;
2162 }
2163 return SECFailure;
2164 }
2165 }
2166 }
2167 }
2168 return SECSuccess;
2169 }
2170
2171 /* Add a callback function to the table of senders of server hello extensions.
2172 */
2173 SECStatus
2174 ssl3_RegisterServerHelloExtensionSender(sslSocket *ss, PRUint16 ex_type,
2175 ssl3HelloExtensionSenderFunc cb)
2176 {
2177 int i;
2178 ssl3HelloExtensionSender *sender;
2179 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
2180 sender = &ss->xtnData.serverHelloSenders[0];
2181 } else {
2182 if (tls13_ExtensionAllowed(ex_type, server_hello)) {
2183 PORT_Assert(!tls13_ExtensionAllowed(ex_type, encrypted_extensions));
2184 sender = &ss->xtnData.serverHelloSenders[0];
2185 } else {
2186 PORT_Assert(tls13_ExtensionAllowed(ex_type, encrypted_extensions));
2187 sender = &ss->xtnData.encryptedExtensionsSenders[0];
2188 }
2189 }
2190
2191 for (i = 0; i < SSL_MAX_EXTENSIONS; ++i, ++sender) {
2192 if (!sender->ex_sender) {
2193 sender->ex_type = ex_type;
2194 sender->ex_sender = cb;
2195 return SECSuccess;
2196 }
2197 /* detect duplicate senders */
2198 PORT_Assert(sender->ex_type != ex_type);
2199 if (sender->ex_type == ex_type) {
2200 /* duplicate */
2201 break;
2202 }
2203 }
2204 PORT_Assert(i < SSL_MAX_EXTENSIONS); /* table needs to grow */
2205 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2206 return SECFailure;
2207 }
2208
2209 /* call each of the extension senders and return the accumulated length */
2210 PRInt32
2211 ssl3_CallHelloExtensionSenders(sslSocket *ss, PRBool append, PRUint32 maxBytes,
2212 const ssl3HelloExtensionSender *sender)
2213 {
2214 PRInt32 total_exten_len = 0;
2215 int i;
2216
2217 if (!sender) {
2218 if (ss->version > SSL_LIBRARY_VERSION_3_0) {
2219 sender = &clientHelloSendersTLS[0];
2220 } else {
2221 sender = &clientHelloSendersSSL3[0];
2222 }
2223 }
2224
2225 for (i = 0; i < SSL_MAX_EXTENSIONS; ++i, ++sender) {
2226 if (sender->ex_sender) {
2227 PRInt32 extLen = (*sender->ex_sender)(ss, append, maxBytes);
2228 if (extLen < 0)
2229 return -1;
2230 maxBytes -= extLen;
2231 total_exten_len += extLen;
2232 }
2233 }
2234 return total_exten_len;
2235 }
2236
2237 /* Extension format:
2238 * Extension number: 2 bytes
2239 * Extension length: 2 bytes
2240 * Verify Data Length: 1 byte
2241 * Verify Data (TLS): 12 bytes (client) or 24 bytes (server)
2242 * Verify Data (SSL): 36 bytes (client) or 72 bytes (server)
2243 */
2244 static PRInt32
2245 ssl3_SendRenegotiationInfoXtn(
2246 sslSocket *ss,
2247 PRBool append,
2248 PRUint32 maxBytes)
2249 {
2250 PRInt32 len = 0;
2251 PRInt32 needed;
2252
2253 /* In draft-ietf-tls-renegotiation-03, it is NOT RECOMMENDED to send
2254 * both the SCSV and the empty RI, so when we send SCSV in
2255 * the initial handshake, we don't also send RI.
2256 */
2257 if (!ss || ss->ssl3.hs.sendingSCSV)
2258 return 0;
2259 if (ss->firstHsDone) {
2260 len = ss->sec.isServer ? ss->ssl3.hs.finishedBytes * 2
2261 : ss->ssl3.hs.finishedBytes;
2262 }
2263 needed = 5 + len;
2264 if (maxBytes < (PRUint32)needed) {
2265 return 0;
2266 }
2267 if (append) {
2268 SECStatus rv;
2269 /* extension_type */
2270 rv = ssl3_AppendHandshakeNumber(ss, ssl_renegotiation_info_xtn, 2);
2271 if (rv != SECSuccess)
2272 return -1;
2273 /* length of extension_data */
2274 rv = ssl3_AppendHandshakeNumber(ss, len + 1, 2);
2275 if (rv != SECSuccess)
2276 return -1;
2277 /* verify_Data from previous Finished message(s) */
2278 rv = ssl3_AppendHandshakeVariable(ss,
2279 ss->ssl3.hs.finishedMsgs.data, len, 1) ;
2280 if (rv != SECSuccess)
2281 return -1;
2282 if (!ss->sec.isServer) {
2283 TLSExtensionData *xtnData = &ss->xtnData;
2284 xtnData->advertised[xtnData->numAdvertised++] =
2285 ssl_renegotiation_info_xtn;
2286 }
2287 }
2288 return needed;
2289 }
2290
2291 static SECStatus
2292 ssl3_ServerHandleStatusRequestXtn(sslSocket *ss, PRUint16 ex_type,
2293 SECItem *data)
2294 {
2295 SECStatus rv = SECSuccess;
2296
2297 /* remember that we got this extension. */
2298 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
2299 PORT_Assert(ss->sec.isServer);
2300 /* prepare to send back the appropriate response */
2301 rv = ssl3_RegisterServerHelloExtensionSender(ss, ex_type,
2302 ssl3_ServerSendStatusRequestXtn );
2303 return rv;
2304 }
2305
2306 /* This function runs in both the client and server. */
2307 static SECStatus
2308 ssl3_HandleRenegotiationInfoXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data)
2309 {
2310 SECStatus rv = SECSuccess;
2311 PRUint32 len = 0;
2312
2313 if (ss->firstHsDone) {
2314 len = ss->sec.isServer ? ss->ssl3.hs.finishedBytes
2315 : ss->ssl3.hs.finishedBytes * 2;
2316 }
2317 if (data->len != 1 + len || data->data[0] != len) {
2318 (void)ssl3_DecodeError(ss);
2319 return SECFailure;
2320 }
2321 if (len && NSS_SecureMemcmp(ss->ssl3.hs.finishedMsgs.data,
2322 data->data + 1, len)) {
2323 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
2324 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
2325 return SECFailure;
2326 }
2327 /* remember that we got this extension and it was correct. */
2328 ss->peerRequestedProtection = 1;
2329 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
2330 if (ss->sec.isServer) {
2331 /* prepare to send back the appropriate response */
2332 rv = ssl3_RegisterServerHelloExtensionSender(ss, ex_type,
2333 ssl3_SendRenegotiationInfoX tn);
2334 }
2335 return rv;
2336 }
2337
2338 static PRInt32
2339 ssl3_ClientSendUseSRTPXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes)
2340 {
2341 PRUint32 ext_data_len;
2342 PRInt16 i;
2343 SECStatus rv;
2344
2345 if (!ss)
2346 return 0;
2347
2348 if (!IS_DTLS(ss) || !ss->ssl3.dtlsSRTPCipherCount)
2349 return 0; /* Not relevant */
2350
2351 ext_data_len = 2 + 2 * ss->ssl3.dtlsSRTPCipherCount + 1;
2352
2353 if (append && maxBytes >= 4 + ext_data_len) {
2354 /* Extension type */
2355 rv = ssl3_AppendHandshakeNumber(ss, ssl_use_srtp_xtn, 2);
2356 if (rv != SECSuccess)
2357 return -1;
2358 /* Length of extension data */
2359 rv = ssl3_AppendHandshakeNumber(ss, ext_data_len, 2);
2360 if (rv != SECSuccess)
2361 return -1;
2362 /* Length of the SRTP cipher list */
2363 rv = ssl3_AppendHandshakeNumber(ss,
2364 2 * ss->ssl3.dtlsSRTPCipherCount,
2365 2);
2366 if (rv != SECSuccess)
2367 return -1;
2368 /* The SRTP ciphers */
2369 for (i = 0; i < ss->ssl3.dtlsSRTPCipherCount; i++) {
2370 rv = ssl3_AppendHandshakeNumber(ss,
2371 ss->ssl3.dtlsSRTPCiphers[i],
2372 2);
2373 }
2374 /* Empty MKI value */
2375 ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
2376
2377 ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
2378 ssl_use_srtp_xtn;
2379 }
2380
2381 return 4 + ext_data_len;
2382 }
2383
2384 static PRInt32
2385 ssl3_ServerSendUseSRTPXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes)
2386 {
2387 SECStatus rv;
2388
2389 /* Server side */
2390 if (!append || maxBytes < 9) {
2391 return 9;
2392 }
2393
2394 /* Extension type */
2395 rv = ssl3_AppendHandshakeNumber(ss, ssl_use_srtp_xtn, 2);
2396 if (rv != SECSuccess)
2397 return -1;
2398 /* Length of extension data */
2399 rv = ssl3_AppendHandshakeNumber(ss, 5, 2);
2400 if (rv != SECSuccess)
2401 return -1;
2402 /* Length of the SRTP cipher list */
2403 rv = ssl3_AppendHandshakeNumber(ss, 2, 2);
2404 if (rv != SECSuccess)
2405 return -1;
2406 /* The selected cipher */
2407 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.dtlsSRTPCipherSuite, 2);
2408 if (rv != SECSuccess)
2409 return -1;
2410 /* Empty MKI value */
2411 ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
2412
2413 return 9;
2414 }
2415
2416 static SECStatus
2417 ssl3_ClientHandleUseSRTPXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data)
2418 {
2419 SECStatus rv;
2420 SECItem ciphers = { siBuffer, NULL, 0 };
2421 PRUint16 i;
2422 PRUint16 cipher = 0;
2423 PRBool found = PR_FALSE;
2424 SECItem litem;
2425
2426 if (!data->data || !data->len) {
2427 (void)ssl3_DecodeError(ss);
2428 return SECFailure;
2429 }
2430
2431 /* Get the cipher list */
2432 rv = ssl3_ConsumeHandshakeVariable(ss, &ciphers, 2,
2433 &data->data, &data->len);
2434 if (rv != SECSuccess) {
2435 return SECFailure; /* fatal alert already sent */
2436 }
2437 /* Now check that the server has picked just 1 (i.e., len = 2) */
2438 if (ciphers.len != 2) {
2439 (void)ssl3_DecodeError(ss);
2440 return SECFailure;
2441 }
2442
2443 /* Get the selected cipher */
2444 cipher = (ciphers.data[0] << 8) | ciphers.data[1];
2445
2446 /* Now check that this is one of the ciphers we offered */
2447 for (i = 0; i < ss->ssl3.dtlsSRTPCipherCount; i++) {
2448 if (cipher == ss->ssl3.dtlsSRTPCiphers[i]) {
2449 found = PR_TRUE;
2450 break;
2451 }
2452 }
2453
2454 if (!found) {
2455 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
2456 PORT_SetError(SSL_ERROR_RX_MALFORMED_SERVER_HELLO);
2457 return SECFailure;
2458 }
2459
2460 /* Get the srtp_mki value */
2461 rv = ssl3_ConsumeHandshakeVariable(ss, &litem, 1,
2462 &data->data, &data->len);
2463 if (rv != SECSuccess) {
2464 return SECFailure; /* alert already sent */
2465 }
2466
2467 /* We didn't offer an MKI, so this must be 0 length */
2468 if (litem.len != 0) {
2469 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
2470 PORT_SetError(SSL_ERROR_RX_MALFORMED_SERVER_HELLO);
2471 return SECFailure;
2472 }
2473
2474 /* extra trailing bytes */
2475 if (data->len != 0) {
2476 (void)ssl3_DecodeError(ss);
2477 return SECFailure;
2478 }
2479
2480 /* OK, this looks fine. */
2481 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ssl_use_srtp_xtn;
2482 ss->ssl3.dtlsSRTPCipherSuite = cipher;
2483 return SECSuccess;
2484 }
2485
2486 static SECStatus
2487 ssl3_ServerHandleUseSRTPXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data)
2488 {
2489 SECStatus rv;
2490 SECItem ciphers = { siBuffer, NULL, 0 };
2491 PRUint16 i;
2492 unsigned int j;
2493 PRUint16 cipher = 0;
2494 PRBool found = PR_FALSE;
2495 SECItem litem;
2496
2497 if (!IS_DTLS(ss) || !ss->ssl3.dtlsSRTPCipherCount) {
2498 /* Ignore the extension if we aren't doing DTLS or no DTLS-SRTP
2499 * preferences have been set. */
2500 return SECSuccess;
2501 }
2502
2503 if (!data->data || data->len < 5) {
2504 (void)ssl3_DecodeError(ss);
2505 return SECFailure;
2506 }
2507
2508 /* Get the cipher list */
2509 rv = ssl3_ConsumeHandshakeVariable(ss, &ciphers, 2,
2510 &data->data, &data->len);
2511 if (rv != SECSuccess) {
2512 return SECFailure; /* alert already sent */
2513 }
2514 /* Check that the list is even length */
2515 if (ciphers.len % 2) {
2516 (void)ssl3_DecodeError(ss);
2517 return SECFailure;
2518 }
2519
2520 /* Walk through the offered list and pick the most preferred of our
2521 * ciphers, if any */
2522 for (i = 0; !found && i < ss->ssl3.dtlsSRTPCipherCount; i++) {
2523 for (j = 0; j + 1 < ciphers.len; j += 2) {
2524 cipher = (ciphers.data[j] << 8) | ciphers.data[j + 1];
2525 if (cipher == ss->ssl3.dtlsSRTPCiphers[i]) {
2526 found = PR_TRUE;
2527 break;
2528 }
2529 }
2530 }
2531
2532 /* Get the srtp_mki value */
2533 rv = ssl3_ConsumeHandshakeVariable(ss, &litem, 1, &data->data, &data->len);
2534 if (rv != SECSuccess) {
2535 return SECFailure;
2536 }
2537
2538 if (data->len != 0) {
2539 (void)ssl3_DecodeError(ss); /* trailing bytes */
2540 return SECFailure;
2541 }
2542
2543 /* Now figure out what to do */
2544 if (!found) {
2545 /* No matching ciphers, pretend we don't support use_srtp */
2546 return SECSuccess;
2547 }
2548
2549 /* OK, we have a valid cipher and we've selected it */
2550 ss->ssl3.dtlsSRTPCipherSuite = cipher;
2551 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ssl_use_srtp_xtn;
2552
2553 return ssl3_RegisterServerHelloExtensionSender(ss, ssl_use_srtp_xtn,
2554 ssl3_ServerSendUseSRTPXtn);
2555 }
2556
2557 /* ssl3_ServerHandleSigAlgsXtn handles the signature_algorithms extension
2558 * from a client.
2559 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
2560 static SECStatus
2561 ssl3_ServerHandleSigAlgsXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data)
2562 {
2563 SECStatus rv;
2564 SECItem algorithms;
2565 const unsigned char *b;
2566 unsigned int numAlgorithms, i;
2567
2568 /* Ignore this extension if we aren't doing TLS 1.2 or greater. */
2569 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_2) {
2570 return SECSuccess;
2571 }
2572
2573 rv = ssl3_ConsumeHandshakeVariable(ss, &algorithms, 2, &data->data,
2574 &data->len);
2575 if (rv != SECSuccess) {
2576 return SECFailure;
2577 }
2578 /* Trailing data, empty value, or odd-length value is invalid. */
2579 if (data->len != 0 || algorithms.len == 0 || (algorithms.len & 1) != 0) {
2580 (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
2581 PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
2582 return SECFailure;
2583 }
2584
2585 numAlgorithms = algorithms.len / 2;
2586
2587 /* We don't care to process excessive numbers of algorithms. */
2588 if (numAlgorithms > 512) {
2589 numAlgorithms = 512;
2590 }
2591
2592 ss->ssl3.hs.clientSigAndHash =
2593 PORT_NewArray(SSLSignatureAndHashAlg, numAlgorithms);
2594 if (!ss->ssl3.hs.clientSigAndHash) {
2595 (void)SSL3_SendAlert(ss, alert_fatal, internal_error);
2596 PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
2597 return SECFailure;
2598 }
2599 ss->ssl3.hs.numClientSigAndHash = 0;
2600
2601 b = algorithms.data;
2602 ss->ssl3.hs.numClientSigAndHash = 0;
2603 for (i = 0; i < numAlgorithms; i++) {
2604 SSLSignatureAndHashAlg *sigAndHash =
2605 &ss->ssl3.hs.clientSigAndHash[ss->ssl3.hs.numClientSigAndHash];
2606 sigAndHash->hashAlg = (SSLHashType) * (b++);
2607 sigAndHash->sigAlg = (SSLSignType) * (b++);
2608 if (ssl3_IsSupportedSignatureAlgorithm(sigAndHash)) {
2609 ++ss->ssl3.hs.numClientSigAndHash;
2610 }
2611 }
2612
2613 if (!ss->ssl3.hs.numClientSigAndHash) {
2614 /* We didn't understand any of the client's requested signature
2615 * formats. We'll use the defaults. */
2616 PORT_Free(ss->ssl3.hs.clientSigAndHash);
2617 ss->ssl3.hs.clientSigAndHash = NULL;
2618 }
2619
2620 /* Keep track of negotiated extensions. */
2621 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
2622 return SECSuccess;
2623 }
2624
2625 /* ssl3_ClientSendSigAlgsXtn sends the signature_algorithm extension for TLS
2626 * 1.2 ClientHellos. */
2627 static PRInt32
2628 ssl3_ClientSendSigAlgsXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes)
2629 {
2630 PRInt32 extension_length;
2631 unsigned int i;
2632 PRInt32 pos = 0;
2633 PRUint32 policy;
2634 PRUint8 buf[MAX_SIGNATURE_ALGORITHMS * 2];
2635
2636 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_2) {
2637 return 0;
2638 }
2639
2640 for (i = 0; i < ss->ssl3.signatureAlgorithmCount; i++) {
2641 SECOidTag hashOID = ssl3_TLSHashAlgorithmToOID(
2642 ss->ssl3.signatureAlgorithms[i].hashAlg);
2643 if ((NSS_GetAlgorithmPolicy(hashOID, &policy) != SECSuccess) ||
2644 (policy & NSS_USE_ALG_IN_SSL_KX)) {
2645 buf[pos++] = ss->ssl3.signatureAlgorithms[i].hashAlg;
2646 buf[pos++] = ss->ssl3.signatureAlgorithms[i].sigAlg;
2647 }
2648 }
2649
2650 extension_length =
2651 2 /* extension type */ +
2652 2 /* extension length */ +
2653 2 /* supported_signature_algorithms length */ +
2654 pos;
2655
2656 if (maxBytes < extension_length) {
2657 PORT_Assert(0);
2658 return 0;
2659 }
2660
2661 if (append) {
2662 SECStatus rv;
2663 rv = ssl3_AppendHandshakeNumber(ss, ssl_signature_algorithms_xtn, 2);
2664 if (rv != SECSuccess) {
2665 return -1;
2666 }
2667 rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2);
2668 if (rv != SECSuccess) {
2669 return -1;
2670 }
2671
2672 rv = ssl3_AppendHandshakeVariable(ss, buf, extension_length - 6, 2);
2673 if (rv != SECSuccess) {
2674 return -1;
2675 }
2676
2677 ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
2678 ssl_signature_algorithms_xtn;
2679 }
2680
2681 return extension_length;
2682 }
2683
2684 unsigned int
2685 ssl3_CalculatePaddingExtensionLength(unsigned int clientHelloLength)
2686 {
2687 unsigned int recordLength = 1 /* handshake message type */ +
2688 3 /* handshake message length */ +
2689 clientHelloLength;
2690 unsigned int extensionLength;
2691
2692 if (recordLength < 256 || recordLength >= 512) {
2693 return 0;
2694 }
2695
2696 extensionLength = 512 - recordLength;
2697 /* Extensions take at least four bytes to encode. Always include at least
2698 * one byte of data if including the extension. WebSphere Application
2699 * Server 7.0 is intolerant to the last extension being zero-length. */
2700 if (extensionLength < 4 + 1) {
2701 extensionLength = 4 + 1;
2702 }
2703
2704 return extensionLength;
2705 }
2706
2707 /* ssl3_AppendPaddingExtension possibly adds an extension which ensures that a
2708 * ClientHello record is either < 256 bytes or is >= 512 bytes. This ensures
2709 * that we don't trigger bugs in F5 products. */
2710 PRInt32
2711 ssl3_AppendPaddingExtension(sslSocket *ss, unsigned int extensionLen,
2712 PRUint32 maxBytes)
2713 {
2714 unsigned int paddingLen = extensionLen - 4;
2715 static unsigned char padding[256];
2716
2717 if (extensionLen == 0) {
2718 return 0;
2719 }
2720
2721 if (extensionLen < 4 ||
2722 extensionLen > maxBytes ||
2723 paddingLen > sizeof(padding)) {
2724 PORT_Assert(0);
2725 return -1;
2726 }
2727
2728 if (SECSuccess != ssl3_AppendHandshakeNumber(ss, ssl_padding_xtn, 2))
2729 return -1;
2730 if (SECSuccess != ssl3_AppendHandshakeNumber(ss, paddingLen, 2))
2731 return -1;
2732 if (SECSuccess != ssl3_AppendHandshake(ss, padding, paddingLen))
2733 return -1;
2734
2735 return extensionLen;
2736 }
2737
2738 /* ssl3_ClientSendDraftVersionXtn sends the TLS 1.3 temporary draft
2739 * version extension.
2740 * TODO(ekr@rtfm.com): Remove when TLS 1.3 is published. */
2741 static PRInt32
2742 ssl3_ClientSendDraftVersionXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes)
2743 {
2744 PRInt32 extension_length;
2745
2746 if (ss->version != SSL_LIBRARY_VERSION_TLS_1_3) {
2747 return 0;
2748 }
2749
2750 extension_length = 6; /* Type + length + number */
2751 if (maxBytes < (PRUint32)extension_length) {
2752 PORT_Assert(0);
2753 return 0;
2754 }
2755 if (append) {
2756 SECStatus rv;
2757 rv = ssl3_AppendHandshakeNumber(ss, ssl_tls13_draft_version_xtn, 2);
2758 if (rv != SECSuccess)
2759 goto loser;
2760 rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2);
2761 if (rv != SECSuccess)
2762 goto loser;
2763 rv = ssl3_AppendHandshakeNumber(ss, TLS_1_3_DRAFT_VERSION, 2);
2764 if (rv != SECSuccess)
2765 goto loser;
2766 ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
2767 ssl_tls13_draft_version_xtn;
2768 }
2769
2770 return extension_length;
2771
2772 loser:
2773 return -1;
2774 }
2775
2776 /* ssl3_ServerHandleDraftVersionXtn handles the TLS 1.3 temporary draft
2777 * version extension.
2778 * TODO(ekr@rtfm.com): Remove when TLS 1.3 is published. */
2779 static SECStatus
2780 ssl3_ServerHandleDraftVersionXtn(sslSocket *ss, PRUint16 ex_type,
2781 SECItem *data)
2782 {
2783 PRInt32 draft_version;
2784
2785 /* Ignore this extension if we aren't doing TLS 1.3 */
2786 if (ss->version != SSL_LIBRARY_VERSION_TLS_1_3) {
2787 return SECSuccess;
2788 }
2789
2790 if (data->len != 2) {
2791 (void)ssl3_DecodeError(ss);
2792 return SECFailure;
2793 }
2794
2795 /* Get the draft version out of the handshake */
2796 draft_version = ssl3_ConsumeHandshakeNumber(ss, 2,
2797 &data->data, &data->len);
2798 if (draft_version < 0) {
2799 return SECFailure;
2800 }
2801
2802 /* Keep track of negotiated extensions. */
2803 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
2804
2805 if (draft_version != TLS_1_3_DRAFT_VERSION) {
2806 /*
2807 * Incompatible/broken TLS 1.3 implementation. Fall back to TLS 1.2.
2808 * TODO(ekr@rtfm.com): It's not entirely clear it's safe to roll back
2809 * here. Need to double-check.
2810 */
2811 SSL_TRC(30, ("%d: SSL3[%d]: Incompatible version of TLS 1.3 (%d), "
2812 "expected %d",
2813 SSL_GETPID(), ss->fd, draft_version, TLS_1_3_DRAFT_VERSION) );
2814 ss->version = SSL_LIBRARY_VERSION_TLS_1_2;
2815 }
2816
2817 return SECSuccess;
2818 }
2819
2820 static PRInt32
2821 ssl3_SendExtendedMasterSecretXtn(sslSocket *ss, PRBool append,
2822 PRUint32 maxBytes)
2823 {
2824 PRInt32 extension_length;
2825
2826 if (!ss->opt.enableExtendedMS) {
2827 return 0;
2828 }
2829
2830 #ifndef NO_PKCS11_BYPASS
2831 /* Extended MS can only be used w/o bypass mode */
2832 if (ss->opt.bypassPKCS11) {
2833 PORT_Assert(0);
2834 PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
2835 return -1;
2836 }
2837 #endif
2838
2839 /* Always send the extension in this function, since the
2840 * client always sends it and this function is only called on
2841 * the server if we negotiated the extension. */
2842 extension_length = 4; /* Type + length (0) */
2843 if (maxBytes < extension_length) {
2844 PORT_Assert(0);
2845 return 0;
2846 }
2847
2848 if (append) {
2849 SECStatus rv;
2850 rv = ssl3_AppendHandshakeNumber(ss, ssl_extended_master_secret_xtn, 2);
2851 if (rv != SECSuccess)
2852 goto loser;
2853 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
2854 if (rv != SECSuccess)
2855 goto loser;
2856 ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
2857 ssl_extended_master_secret_xtn;
2858 }
2859
2860 return extension_length;
2861
2862 loser:
2863 return -1;
2864 }
2865
2866 static SECStatus
2867 ssl3_HandleExtendedMasterSecretXtn(sslSocket *ss, PRUint16 ex_type,
2868 SECItem *data)
2869 {
2870 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_0) {
2871 return SECSuccess;
2872 }
2873
2874 if (!ss->opt.enableExtendedMS) {
2875 return SECSuccess;
2876 }
2877
2878 #ifndef NO_PKCS11_BYPASS
2879 /* Extended MS can only be used w/o bypass mode */
2880 if (ss->opt.bypassPKCS11) {
2881 PORT_Assert(0);
2882 PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
2883 return SECFailure;
2884 }
2885 #endif
2886
2887 if (data->len != 0) {
2888 SSL_TRC(30, ("%d: SSL3[%d]: Bogus extended master secret extension",
2889 SSL_GETPID(), ss->fd));
2890 return SECFailure;
2891 }
2892
2893 SSL_DBG(("%d: SSL[%d]: Negotiated extended master secret extension.",
2894 SSL_GETPID(), ss->fd));
2895
2896 /* Keep track of negotiated extensions. */
2897 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
2898
2899 if (ss->sec.isServer) {
2900 return ssl3_RegisterServerHelloExtensionSender(
2901 ss, ex_type, ssl3_SendExtendedMasterSecretXtn);
2902 }
2903 return SECSuccess;
2904 }
2905
2906 /* ssl3_ClientSendSignedCertTimestampXtn sends the signed_certificate_timestamp
2907 * extension for TLS ClientHellos. */
2908 static PRInt32
2909 ssl3_ClientSendSignedCertTimestampXtn(sslSocket *ss, PRBool append,
2910 PRUint32 maxBytes)
2911 {
2912 PRInt32 extension_length = 2 /* extension_type */ +
2913 2 /* length(extension_data) */;
2914
2915 /* Only send the extension if processing is enabled. */
2916 if (!ss->opt.enableSignedCertTimestamps)
2917 return 0;
2918
2919 if (append && maxBytes >= extension_length) {
2920 SECStatus rv;
2921 /* extension_type */
2922 rv = ssl3_AppendHandshakeNumber(ss,
2923 ssl_signed_cert_timestamp_xtn,
2924 2);
2925 if (rv != SECSuccess)
2926 goto loser;
2927 /* zero length */
2928 rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
2929 if (rv != SECSuccess)
2930 goto loser;
2931 ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
2932 ssl_signed_cert_timestamp_xtn;
2933 } else if (maxBytes < extension_length) {
2934 PORT_Assert(0);
2935 return 0;
2936 }
2937
2938 return extension_length;
2939 loser:
2940 return -1;
2941 }
2942
2943 static SECStatus
2944 ssl3_ClientHandleSignedCertTimestampXtn(sslSocket *ss, PRUint16 ex_type,
2945 SECItem *data)
2946 {
2947 /* We do not yet know whether we'll be resuming a session or creating
2948 * a new one, so we keep a pointer to the data in the TLSExtensionData
2949 * structure. This pointer is only valid in the scope of
2950 * ssl3_HandleServerHello, and, if not resuming a session, the data is
2951 * copied once a new session structure has been set up.
2952 * All parsing is currently left to the application and we accept
2953 * everything, including empty data.
2954 */
2955 SECItem *scts = &ss->xtnData.signedCertTimestamps;
2956 PORT_Assert(!scts->data && !scts->len);
2957
2958 if (!data->len) {
2959 /* Empty extension data: RFC 6962 mandates non-empty contents. */
2960 return SECFailure;
2961 }
2962 *scts = *data;
2963 /* Keep track of negotiated extensions. */
2964 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
2965 return SECSuccess;
2966 }
2967
2968 static PRInt32
2969 ssl3_ServerSendSignedCertTimestampXtn(sslSocket *ss,
2970 PRBool append,
2971 PRUint32 maxBytes)
2972 {
2973 PRInt32 extension_length;
2974 SSLKEAType effectiveExchKeyType;
2975 const SECItem *scts;
2976
2977 if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa ||
2978 ss->ssl3.hs.kea_def->kea == kea_dhe_rsa) {
2979 effectiveExchKeyType = ssl_kea_rsa;
2980 } else {
2981 effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType;
2982 }
2983
2984 scts = &ss->signedCertTimestamps[effectiveExchKeyType];
2985
2986 if (!scts->len) {
2987 /* No timestamps to send */
2988 return 0;
2989 }
2990
2991 extension_length = 2 /* extension_type */ +
2992 2 /* length(extension_data) */ +
2993 scts->len;
2994
2995 if (maxBytes < extension_length) {
2996 PORT_Assert(0);
2997 return 0;
2998 }
2999 if (append) {
3000 SECStatus rv;
3001 /* extension_type */
3002 rv = ssl3_AppendHandshakeNumber(ss,
3003 ssl_signed_cert_timestamp_xtn,
3004 2);
3005 if (rv != SECSuccess)
3006 goto loser;
3007 /* extension_data */
3008 rv = ssl3_AppendHandshakeVariable(ss, scts->data, scts->len, 2);
3009 if (rv != SECSuccess)
3010 goto loser;
3011 }
3012
3013 return extension_length;
3014
3015 loser:
3016 return -1;
3017 }
3018
3019 static SECStatus
3020 ssl3_ServerHandleSignedCertTimestampXtn(sslSocket *ss, PRUint16 ex_type,
3021 SECItem *data)
3022 {
3023 ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type;
3024 PORT_Assert(ss->sec.isServer);
3025 return ssl3_RegisterServerHelloExtensionSender(ss, ex_type,
3026 ssl3_ServerSendSignedCertTime stampXtn);
3027 }
3028
3029 /*
3030 * [draft-ietf-tls-tls13-11] Section 6.3.2.3.
3031 *
3032 * struct {
3033 * NamedGroup group;
3034 * opaque key_exchange<1..2^16-1>;
3035 * } KeyShareEntry;
3036 *
3037 * struct {
3038 * select (role) {
3039 * case client:
3040 * KeyShareEntry client_shares<4..2^16-1>;
3041 *
3042 * case server:
3043 * KeyShareEntry server_share;
3044 * }
3045 * } KeyShare;
3046 */
3047 static SECStatus
3048 tls13_SizeOfKeyShareEntry(ssl3KeyPair *pair)
3049 {
3050 return 2 + 2 + tls13_SizeOfECDHEKeyShareKEX(pair);
3051 }
3052
3053 static SECStatus
3054 tls13_EncodeKeyShareEntry(sslSocket *ss, ssl3KeyPair *pair)
3055 {
3056 SECStatus rv;
3057
3058 /* This currently only works for ECC keys */
3059 PORT_Assert(pair->pubKey->keyType == ecKey);
3060 if (pair->pubKey->keyType != ecKey) {
3061 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3062 return SECFailure;
3063 }
3064
3065 rv = ssl3_AppendHandshakeNumber(ss, tls13_GroupForECDHEKeyShare(pair), 2);
3066 if (rv != SECSuccess)
3067 return rv;
3068
3069 rv = ssl3_AppendHandshakeNumber(ss, tls13_SizeOfECDHEKeyShareKEX(pair), 2);
3070 if (rv != SECSuccess)
3071 return rv;
3072
3073 rv = tls13_EncodeECDHEKeyShareKEX(ss, pair);
3074 if (rv != SECSuccess)
3075 return rv;
3076
3077 return SECSuccess;
3078 }
3079
3080 static PRInt32
3081 tls13_ClientSendKeyShareXtn(sslSocket *ss, PRBool append,
3082 PRUint32 maxBytes)
3083 {
3084 SECStatus rv;
3085 PRUint32 entry_length;
3086 PRUint32 extension_length;
3087
3088 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
3089 return 0;
3090 }
3091
3092 /* Optimistically try to send an ECDHE key using the
3093 * preexisting key (in future will be keys) */
3094 SSL_TRC(3, ("%d: TLS13[%d]: send client key share xtn",
3095 SSL_GETPID(), ss->fd));
3096
3097 entry_length = tls13_SizeOfKeyShareEntry(ss->ephemeralECDHKeyPair);
3098 /* Type + length + vector_length + entry */
3099 extension_length = 2 + 2 + 2 + entry_length;
3100
3101 if (maxBytes < extension_length) {
3102 PORT_Assert(0);
3103 return 0;
3104 }
3105
3106 if (append) {
3107 rv = ssl3_AppendHandshakeNumber(ss, ssl_tls13_key_share_xtn, 2);
3108 if (rv != SECSuccess)
3109 goto loser;
3110 rv = ssl3_AppendHandshakeNumber(ss, entry_length + 2, 2); /* Extension l ength */
3111 if (rv != SECSuccess)
3112 goto loser;
3113 rv = ssl3_AppendHandshakeNumber(ss, entry_length, 2); /* Vector length * /
3114 if (rv != SECSuccess)
3115 goto loser;
3116 rv = tls13_EncodeKeyShareEntry(ss, ss->ephemeralECDHKeyPair);
3117 if (rv != SECSuccess)
3118 goto loser;
3119
3120 ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
3121 ssl_tls13_key_share_xtn;
3122 }
3123
3124 return extension_length;
3125
3126 loser:
3127 return -1;
3128 }
3129
3130 static SECStatus
3131 tls13_HandleKeyShareEntry(sslSocket *ss, SECItem *data)
3132 {
3133 SECStatus rv;
3134 PRInt32 group;
3135 TLS13KeyShareEntry *ks = NULL;
3136 SECItem share = { siBuffer, NULL, 0 };
3137
3138 group = ssl3_ConsumeHandshakeNumber(ss, 2, &data->data, &data->len);
3139 if (group < 0) {
3140 PORT_SetError(SSL_ERROR_RX_MALFORMED_KEY_SHARE);
3141 goto loser;
3142 }
3143
3144 rv = ssl3_ConsumeHandshakeVariable(ss, &share, 2, &data->data,
3145 &data->len);
3146 if (rv != SECSuccess)
3147 goto loser;
3148
3149 ks = PORT_ZNew(TLS13KeyShareEntry);
3150 if (!ks)
3151 goto loser;
3152 ks->group = group;
3153
3154 rv = SECITEM_CopyItem(NULL, &ks->key_exchange, &share);
3155 if (rv != SECSuccess)
3156 goto loser;
3157
3158 PR_APPEND_LINK(&ks->link, &ss->ssl3.hs.remoteKeyShares);
3159 return SECSuccess;
3160
3161 loser:
3162 if (ks)
3163 tls13_DestroyKeyShareEntry(ks);
3164 return SECFailure;
3165 }
3166
3167 /* Handle an incoming KeyShare extension at the client and copy to
3168 * |ss->ssl3.hs.remoteKeyShares| for future use. The key
3169 * share is processed in tls13_HandleServerKeyShare(). */
3170 static SECStatus
3171 tls13_ClientHandleKeyShareXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data)
3172 {
3173 SECStatus rv;
3174
3175 PORT_Assert(!ss->sec.isServer);
3176 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
3177 /* This can't happen because the extension processing
3178 * code filters out TLS 1.3 extensions when not in
3179 * TLS 1.3 mode. */
3180 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
3181 return SECFailure;
3182 }
3183
3184 SSL_TRC(3, ("%d: SSL3[%d]: handle key_share extension",
3185 SSL_GETPID(), ss->fd));
3186
3187 rv = tls13_HandleKeyShareEntry(ss, data);
3188 if (rv != SECSuccess) {
3189 PORT_SetError(SSL_ERROR_RX_MALFORMED_KEY_SHARE);
3190 return SECFailure;
3191 }
3192
3193 if (data->len) {
3194 PORT_SetError(SSL_ERROR_RX_MALFORMED_KEY_SHARE);
3195 return SECFailure;
3196 }
3197
3198 return SECSuccess;
3199 }
3200
3201 /* Handle an incoming KeyShare extension at the server and copy to
3202 * |ss->ssl3.hs.remoteKeyShares| for future use. The key
3203 * share is processed in tls13_HandleClientKeyShare(). */
3204 static SECStatus
3205 tls13_ServerHandleKeyShareXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data)
3206 {
3207 SECStatus rv;
3208 PRInt32 length;
3209
3210 PORT_Assert(ss->sec.isServer);
3211 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
3212 return SECSuccess;
3213 }
3214
3215 SSL_TRC(3, ("%d: SSL3[%d]: handle key_share extension",
3216 SSL_GETPID(), ss->fd));
3217
3218 /* Redundant length because of TLS encoding (this vector consumes
3219 * the entire extension.) */
3220 length = ssl3_ConsumeHandshakeNumber(ss, 2, &data->data,
3221 &data->len);
3222 if (length < 0)
3223 goto loser;
3224 if (length != data->len) {
3225 /* Check for consistency */
3226 PORT_SetError(SSL_ERROR_RX_MALFORMED_KEY_SHARE);
3227 goto loser;
3228 }
3229
3230 while (data->len) {
3231 rv = tls13_HandleKeyShareEntry(ss, data);
3232 if (rv != SECSuccess)
3233 goto loser;
3234 }
3235 return SECSuccess;
3236
3237 loser:
3238 tls13_DestroyKeyShares(&ss->ssl3.hs.remoteKeyShares);
3239 return SECFailure;
3240 }
3241
3242 PRInt32
3243 tls13_ServerSendKeyShareXtn(sslSocket *ss, PRBool append,
3244 PRUint32 maxBytes)
3245 {
3246 PRUint32 extension_length;
3247 PRUint32 entry_length;
3248 SECStatus rv;
3249
3250 switch (ss->ssl3.hs.kea_def->exchKeyType) {
3251 #ifndef NSS_DISABLE_ECC
3252 case ssl_kea_ecdh:
3253 PORT_Assert(ss->ephemeralECDHKeyPair);
3254 break;
3255 #endif
3256 default:
3257 /* got an unknown or unsupported Key Exchange Algorithm.
3258 * Can't happen because tls13_HandleClientKeyShare
3259 * enforces that we are ssl_kea_ecdh. */
3260 PORT_Assert(0);
3261 tls13_FatalError(ss, SEC_ERROR_UNSUPPORTED_KEYALG, internal_error);
3262 return SECFailure;
3263 }
3264
3265 entry_length = tls13_SizeOfKeyShareEntry(ss->ephemeralECDHKeyPair);
3266 extension_length = 2 + 2 + entry_length; /* Type + length + entry_length */
3267 if (maxBytes < extension_length) {
3268 PORT_Assert(0);
3269 return 0;
3270 }
3271
3272 if (append) {
3273 rv = ssl3_AppendHandshakeNumber(ss, ssl_tls13_key_share_xtn, 2);
3274 if (rv != SECSuccess)
3275 goto loser;
3276
3277 rv = ssl3_AppendHandshakeNumber(ss, entry_length, 2);
3278 if (rv != SECSuccess)
3279 goto loser;
3280
3281 rv = tls13_EncodeKeyShareEntry(ss, ss->ephemeralECDHKeyPair);
3282 if (rv != SECSuccess)
3283 goto loser;
3284 }
3285
3286 return extension_length;
3287
3288 loser:
3289 return -1;
3290 }
OLDNEW
« no previous file with comments | « net/third_party/nss/ssl/ssl3ecc.c ('k') | net/third_party/nss/ssl/ssl3gthr.c » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698