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 "sslimpl.h"
15 #include "sslproto.h"
16 #include "ssl3exthandle.h"
17 #include "tls13err.h"
18 #include "tls13exthandle.h"
19 #include "tls13subcerts.h"
20 
21 /* Callback function that handles a received extension. */
22 typedef SECStatus (*ssl3ExtensionHandlerFunc)(const sslSocket *ss,
23                                               TLSExtensionData *xtnData,
24                                               SECItem *data);
25 
26 /* Row in a table of hello extension handlers. */
27 typedef struct {
28     SSLExtensionType ex_type;
29     ssl3ExtensionHandlerFunc ex_handler;
30 } ssl3ExtensionHandler;
31 
32 /* Table of handlers for received TLS hello extensions, one per extension.
33  * In the second generation, this table will be dynamic, and functions
34  * will be registered here.
35  */
36 /* This table is used by the server, to handle client hello extensions. */
37 static const ssl3ExtensionHandler clientHelloHandlers[] = {
38     { ssl_server_name_xtn, &ssl3_HandleServerNameXtn },
39     { ssl_supported_groups_xtn, &ssl_HandleSupportedGroupsXtn },
40     { ssl_ec_point_formats_xtn, &ssl3_HandleSupportedPointFormatsXtn },
41     { ssl_session_ticket_xtn, &ssl3_ServerHandleSessionTicketXtn },
42     { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn },
43     { ssl_app_layer_protocol_xtn, &ssl3_ServerHandleAppProtoXtn },
44     { ssl_use_srtp_xtn, &ssl3_ServerHandleUseSRTPXtn },
45     { ssl_cert_status_xtn, &ssl3_ServerHandleStatusRequestXtn },
46     { ssl_signature_algorithms_xtn, &ssl3_HandleSigAlgsXtn },
47     { ssl_extended_master_secret_xtn, &ssl3_HandleExtendedMasterSecretXtn },
48     { ssl_signed_cert_timestamp_xtn, &ssl3_ServerHandleSignedCertTimestampXtn },
49     { ssl_delegated_credentials_xtn, &tls13_ServerHandleDelegatedCredentialsXtn },
50     { ssl_tls13_key_share_xtn, &tls13_ServerHandleKeyShareXtn },
51     { ssl_tls13_pre_shared_key_xtn, &tls13_ServerHandlePreSharedKeyXtn },
52     { ssl_tls13_early_data_xtn, &tls13_ServerHandleEarlyDataXtn },
53     { ssl_tls13_psk_key_exchange_modes_xtn, &tls13_ServerHandlePskModesXtn },
54     { ssl_tls13_cookie_xtn, &tls13_ServerHandleCookieXtn },
55     { ssl_tls13_encrypted_sni_xtn, &tls13_ServerHandleEsniXtn },
56     { ssl_tls13_post_handshake_auth_xtn, &tls13_ServerHandlePostHandshakeAuthXtn },
57     { ssl_record_size_limit_xtn, &ssl_HandleRecordSizeLimitXtn },
58     { 0, NULL }
59 };
60 
61 /* These two tables are used by the client, to handle server hello
62  * extensions. */
63 static const ssl3ExtensionHandler serverHelloHandlersTLS[] = {
64     { ssl_server_name_xtn, &ssl3_HandleServerNameXtn },
65     /* TODO: add a handler for ssl_ec_point_formats_xtn */
66     { ssl_session_ticket_xtn, &ssl3_ClientHandleSessionTicketXtn },
67     { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn },
68     { ssl_app_layer_protocol_xtn, &ssl3_ClientHandleAppProtoXtn },
69     { ssl_use_srtp_xtn, &ssl3_ClientHandleUseSRTPXtn },
70     { ssl_cert_status_xtn, &ssl3_ClientHandleStatusRequestXtn },
71     { ssl_extended_master_secret_xtn, &ssl3_HandleExtendedMasterSecretXtn },
72     { ssl_signed_cert_timestamp_xtn, &ssl3_ClientHandleSignedCertTimestampXtn },
73     { ssl_tls13_key_share_xtn, &tls13_ClientHandleKeyShareXtn },
74     { ssl_tls13_pre_shared_key_xtn, &tls13_ClientHandlePreSharedKeyXtn },
75     { ssl_tls13_early_data_xtn, &tls13_ClientHandleEarlyDataXtn },
76     { ssl_record_size_limit_xtn, &ssl_HandleRecordSizeLimitXtn },
77     { 0, NULL }
78 };
79 
80 static const ssl3ExtensionHandler helloRetryRequestHandlers[] = {
81     { ssl_tls13_key_share_xtn, tls13_ClientHandleKeyShareXtnHrr },
82     { ssl_tls13_cookie_xtn, tls13_ClientHandleHrrCookie },
83     { 0, NULL }
84 };
85 
86 static const ssl3ExtensionHandler serverHelloHandlersSSL3[] = {
87     { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn },
88     { 0, NULL }
89 };
90 
91 static const ssl3ExtensionHandler newSessionTicketHandlers[] = {
92     { ssl_tls13_early_data_xtn,
93       &tls13_ClientHandleTicketEarlyDataXtn },
94     { 0, NULL }
95 };
96 
97 /* This table is used by the client to handle server certificates in TLS 1.3 */
98 static const ssl3ExtensionHandler serverCertificateHandlers[] = {
99     { ssl_signed_cert_timestamp_xtn, &ssl3_ClientHandleSignedCertTimestampXtn },
100     { ssl_cert_status_xtn, &ssl3_ClientHandleStatusRequestXtn },
101     { ssl_delegated_credentials_xtn, &tls13_ClientHandleDelegatedCredentialsXtn },
102     { 0, NULL }
103 };
104 
105 static const ssl3ExtensionHandler certificateRequestHandlers[] = {
106     { ssl_signature_algorithms_xtn, &ssl3_HandleSigAlgsXtn },
107     { ssl_tls13_certificate_authorities_xtn,
108       &tls13_ClientHandleCertAuthoritiesXtn },
109     { 0, NULL }
110 };
111 
112 /* Tables of functions to format TLS hello extensions, one function per
113  * extension.
114  * These static tables are for the formatting of client hello extensions.
115  * The server's table of hello senders is dynamic, in the socket struct,
116  * and sender functions are registered there.
117  * NB: the order of these extensions can have an impact on compatibility. Some
118  * servers (e.g. Tomcat) will terminate the connection if the last extension in
119  * the client hello is empty (for example, the extended master secret
120  * extension, if it were listed last). See bug 1243641.
121  */
122 static const sslExtensionBuilder clientHelloSendersTLS[] =
123     {
124       { ssl_server_name_xtn, &ssl3_ClientSendServerNameXtn },
125       { ssl_extended_master_secret_xtn, &ssl3_SendExtendedMasterSecretXtn },
126       { ssl_renegotiation_info_xtn, &ssl3_SendRenegotiationInfoXtn },
127       { ssl_supported_groups_xtn, &ssl_SendSupportedGroupsXtn },
128       { ssl_ec_point_formats_xtn, &ssl3_SendSupportedPointFormatsXtn },
129       { ssl_session_ticket_xtn, &ssl3_ClientSendSessionTicketXtn },
130       { ssl_app_layer_protocol_xtn, &ssl3_ClientSendAppProtoXtn },
131       { ssl_use_srtp_xtn, &ssl3_ClientSendUseSRTPXtn },
132       { ssl_cert_status_xtn, &ssl3_ClientSendStatusRequestXtn },
133       { ssl_delegated_credentials_xtn, &tls13_ClientSendDelegatedCredentialsXtn },
134       { ssl_signed_cert_timestamp_xtn, &ssl3_ClientSendSignedCertTimestampXtn },
135       { ssl_tls13_key_share_xtn, &tls13_ClientSendKeyShareXtn },
136       { ssl_tls13_early_data_xtn, &tls13_ClientSendEarlyDataXtn },
137       /* Some servers (e.g. WebSphere Application Server 7.0 and Tomcat) will
138        * time out or terminate the connection if the last extension in the
139        * client hello is empty. They are not intolerant of TLS 1.2, so list
140        * signature_algorithms at the end. See bug 1243641. */
141       { ssl_tls13_supported_versions_xtn, &tls13_ClientSendSupportedVersionsXtn },
142       { ssl_signature_algorithms_xtn, &ssl3_SendSigAlgsXtn },
143       { ssl_tls13_cookie_xtn, &tls13_ClientSendHrrCookieXtn },
144       { ssl_tls13_psk_key_exchange_modes_xtn, &tls13_ClientSendPskModesXtn },
145       { ssl_tls13_encrypted_sni_xtn, &tls13_ClientSendEsniXtn },
146       { ssl_tls13_post_handshake_auth_xtn, &tls13_ClientSendPostHandshakeAuthXtn },
147       { ssl_record_size_limit_xtn, &ssl_SendRecordSizeLimitXtn },
148       /* The pre_shared_key extension MUST be last. */
149       { ssl_tls13_pre_shared_key_xtn, &tls13_ClientSendPreSharedKeyXtn },
150       { 0, NULL }
151     };
152 
153 static const sslExtensionBuilder clientHelloSendersSSL3[] = {
154     { ssl_renegotiation_info_xtn, &ssl3_SendRenegotiationInfoXtn },
155     { 0, NULL }
156 };
157 
158 static const sslExtensionBuilder tls13_cert_req_senders[] = {
159     { ssl_signature_algorithms_xtn, &ssl3_SendSigAlgsXtn },
160     { ssl_tls13_certificate_authorities_xtn, &tls13_SendCertAuthoritiesXtn },
161     { 0, NULL }
162 };
163 
164 static const sslExtensionBuilder tls13_hrr_senders[] = {
165     { ssl_tls13_key_share_xtn, &tls13_ServerSendHrrKeyShareXtn },
166     { ssl_tls13_cookie_xtn, &tls13_ServerSendHrrCookieXtn },
167     { ssl_tls13_supported_versions_xtn, &tls13_ServerSendSupportedVersionsXtn },
168     { 0, NULL }
169 };
170 
171 static const struct {
172     SSLExtensionType type;
173     SSLExtensionSupport support;
174 } ssl_supported_extensions[] = {
175     { ssl_server_name_xtn, ssl_ext_native_only },
176     { ssl_cert_status_xtn, ssl_ext_native },
177     { ssl_delegated_credentials_xtn, ssl_ext_native },
178     { ssl_supported_groups_xtn, ssl_ext_native_only },
179     { ssl_ec_point_formats_xtn, ssl_ext_native },
180     { ssl_signature_algorithms_xtn, ssl_ext_native_only },
181     { ssl_use_srtp_xtn, ssl_ext_native },
182     { ssl_app_layer_protocol_xtn, ssl_ext_native_only },
183     { ssl_signed_cert_timestamp_xtn, ssl_ext_native },
184     { ssl_padding_xtn, ssl_ext_native },
185     { ssl_extended_master_secret_xtn, ssl_ext_native_only },
186     { ssl_session_ticket_xtn, ssl_ext_native_only },
187     { ssl_tls13_key_share_xtn, ssl_ext_native_only },
188     { ssl_tls13_pre_shared_key_xtn, ssl_ext_native_only },
189     { ssl_tls13_early_data_xtn, ssl_ext_native_only },
190     { ssl_tls13_supported_versions_xtn, ssl_ext_native_only },
191     { ssl_tls13_cookie_xtn, ssl_ext_native_only },
192     { ssl_tls13_psk_key_exchange_modes_xtn, ssl_ext_native_only },
193     { ssl_tls13_ticket_early_data_info_xtn, ssl_ext_native_only },
194     { ssl_tls13_certificate_authorities_xtn, ssl_ext_native },
195     { ssl_renegotiation_info_xtn, ssl_ext_native }
196 };
197 
198 static SSLExtensionSupport
ssl_GetExtensionSupport(PRUint16 type)199 ssl_GetExtensionSupport(PRUint16 type)
200 {
201     unsigned int i;
202     for (i = 0; i < PR_ARRAY_SIZE(ssl_supported_extensions); ++i) {
203         if (type == ssl_supported_extensions[i].type) {
204             return ssl_supported_extensions[i].support;
205         }
206     }
207     return ssl_ext_none;
208 }
209 
210 SECStatus
SSLExp_GetExtensionSupport(PRUint16 type,SSLExtensionSupport * support)211 SSLExp_GetExtensionSupport(PRUint16 type, SSLExtensionSupport *support)
212 {
213     *support = ssl_GetExtensionSupport(type);
214     return SECSuccess;
215 }
216 
217 SECStatus
SSLExp_InstallExtensionHooks(PRFileDesc * fd,PRUint16 extension,SSLExtensionWriter writer,void * writerArg,SSLExtensionHandler handler,void * handlerArg)218 SSLExp_InstallExtensionHooks(PRFileDesc *fd, PRUint16 extension,
219                              SSLExtensionWriter writer, void *writerArg,
220                              SSLExtensionHandler handler, void *handlerArg)
221 {
222     sslSocket *ss = ssl_FindSocket(fd);
223     PRCList *cursor;
224     sslCustomExtensionHooks *hook;
225 
226     if (!ss) {
227         return SECFailure; /* Code already set. */
228     }
229 
230     /* Need to specify both or neither, but not just one. */
231     if ((writer && !handler) || (!writer && handler)) {
232         PORT_SetError(SEC_ERROR_INVALID_ARGS);
233         return SECFailure;
234     }
235 
236     if (ssl_GetExtensionSupport(extension) == ssl_ext_native_only) {
237         PORT_SetError(SEC_ERROR_INVALID_ARGS);
238         return SECFailure;
239     }
240 
241     if (ss->firstHsDone || ((ss->ssl3.hs.ws != idle_handshake) &&
242                             (ss->ssl3.hs.ws != wait_client_hello))) {
243         PORT_SetError(PR_INVALID_STATE_ERROR);
244         return SECFailure;
245     }
246 
247     /* Remove any old handler. */
248     for (cursor = PR_NEXT_LINK(&ss->extensionHooks);
249          cursor != &ss->extensionHooks;
250          cursor = PR_NEXT_LINK(cursor)) {
251         hook = (sslCustomExtensionHooks *)cursor;
252         if (hook->type == extension) {
253             PR_REMOVE_LINK(&hook->link);
254             PORT_Free(hook);
255             break;
256         }
257     }
258 
259     if (!writer && !handler) {
260         return SECSuccess;
261     }
262 
263     hook = PORT_ZNew(sslCustomExtensionHooks);
264     if (!hook) {
265         return SECFailure; /* This removed the old one, oh well. */
266     }
267 
268     hook->type = extension;
269     hook->writer = writer;
270     hook->writerArg = writerArg;
271     hook->handler = handler;
272     hook->handlerArg = handlerArg;
273     PR_APPEND_LINK(&hook->link, &ss->extensionHooks);
274     return SECSuccess;
275 }
276 
277 static sslCustomExtensionHooks *
ssl_FindCustomExtensionHooks(sslSocket * ss,PRUint16 extension)278 ssl_FindCustomExtensionHooks(sslSocket *ss, PRUint16 extension)
279 {
280     PRCList *cursor;
281 
282     for (cursor = PR_NEXT_LINK(&ss->extensionHooks);
283          cursor != &ss->extensionHooks;
284          cursor = PR_NEXT_LINK(cursor)) {
285         sslCustomExtensionHooks *hook = (sslCustomExtensionHooks *)cursor;
286         if (hook->type == extension) {
287             return hook;
288         }
289     }
290 
291     return NULL;
292 }
293 
294 static PRBool
arrayContainsExtension(const PRUint16 * array,PRUint32 len,PRUint16 ex_type)295 arrayContainsExtension(const PRUint16 *array, PRUint32 len, PRUint16 ex_type)
296 {
297     unsigned int i;
298     for (i = 0; i < len; i++) {
299         if (ex_type == array[i])
300             return PR_TRUE;
301     }
302     return PR_FALSE;
303 }
304 
305 PRBool
ssl3_ExtensionNegotiated(const sslSocket * ss,PRUint16 ex_type)306 ssl3_ExtensionNegotiated(const sslSocket *ss, PRUint16 ex_type)
307 {
308     const TLSExtensionData *xtnData = &ss->xtnData;
309     return arrayContainsExtension(xtnData->negotiated,
310                                   xtnData->numNegotiated, ex_type);
311 }
312 
313 /* This checks for whether an extension was advertised.  On the client, this
314  * covers extensions that are sent in ClientHello; on the server, extensions
315  * sent in CertificateRequest (TLS 1.3 only). */
316 PRBool
ssl3_ExtensionAdvertised(const sslSocket * ss,PRUint16 ex_type)317 ssl3_ExtensionAdvertised(const sslSocket *ss, PRUint16 ex_type)
318 {
319     const TLSExtensionData *xtnData = &ss->xtnData;
320     return arrayContainsExtension(xtnData->advertised,
321                                   xtnData->numAdvertised, ex_type);
322 }
323 
324 /* Go through hello extensions in |b| and deserialize
325  * them into the list in |ss->ssl3.hs.remoteExtensions|.
326  * The only checking we do in this point is for duplicates.
327  *
328  * IMPORTANT: This list just contains pointers to the incoming
329  * buffer so they can only be used during ClientHello processing.
330  */
331 SECStatus
ssl3_ParseExtensions(sslSocket * ss,PRUint8 ** b,PRUint32 * length)332 ssl3_ParseExtensions(sslSocket *ss, PRUint8 **b, PRUint32 *length)
333 {
334     /* Clean out the extensions list. */
335     ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
336 
337     while (*length) {
338         SECStatus rv;
339         PRUint32 extension_type;
340         SECItem extension_data = { siBuffer, NULL, 0 };
341         TLSExtension *extension;
342         PRCList *cursor;
343 
344         /* Get the extension's type field */
345         rv = ssl3_ConsumeHandshakeNumber(ss, &extension_type, 2, b, length);
346         if (rv != SECSuccess) {
347             return SECFailure; /* alert already sent */
348         }
349 
350         /* Check whether an extension has been sent multiple times. */
351         for (cursor = PR_NEXT_LINK(&ss->ssl3.hs.remoteExtensions);
352              cursor != &ss->ssl3.hs.remoteExtensions;
353              cursor = PR_NEXT_LINK(cursor)) {
354             if (((TLSExtension *)cursor)->type == extension_type) {
355                 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
356                 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_EXTENSION);
357                 return SECFailure;
358             }
359         }
360 
361         /* Get the data for this extension, so we can pass it or skip it. */
362         rv = ssl3_ConsumeHandshakeVariable(ss, &extension_data, 2, b, length);
363         if (rv != SECSuccess) {
364             return rv; /* alert already sent */
365         }
366 
367         SSL_TRC(10, ("%d: SSL3[%d]: parsed extension %d len=%u",
368                      SSL_GETPID(), ss->fd, extension_type, extension_data.len));
369 
370         extension = PORT_ZNew(TLSExtension);
371         if (!extension) {
372             return SECFailure;
373         }
374 
375         extension->type = (PRUint16)extension_type;
376         extension->data = extension_data;
377         PR_APPEND_LINK(&extension->link, &ss->ssl3.hs.remoteExtensions);
378     }
379 
380     return SECSuccess;
381 }
382 
383 TLSExtension *
ssl3_FindExtension(sslSocket * ss,SSLExtensionType extension_type)384 ssl3_FindExtension(sslSocket *ss, SSLExtensionType extension_type)
385 {
386     PRCList *cursor;
387 
388     for (cursor = PR_NEXT_LINK(&ss->ssl3.hs.remoteExtensions);
389          cursor != &ss->ssl3.hs.remoteExtensions;
390          cursor = PR_NEXT_LINK(cursor)) {
391         TLSExtension *extension = (TLSExtension *)cursor;
392 
393         if (extension->type == extension_type) {
394             return extension;
395         }
396     }
397 
398     return NULL;
399 }
400 
401 static SECStatus
ssl_CallExtensionHandler(sslSocket * ss,SSLHandshakeType handshakeMessage,TLSExtension * extension,const ssl3ExtensionHandler * handler)402 ssl_CallExtensionHandler(sslSocket *ss, SSLHandshakeType handshakeMessage,
403                          TLSExtension *extension,
404                          const ssl3ExtensionHandler *handler)
405 {
406     SECStatus rv = SECSuccess;
407     SSLAlertDescription alert = handshake_failure;
408     sslCustomExtensionHooks *customHooks;
409 
410     customHooks = ssl_FindCustomExtensionHooks(ss, extension->type);
411     if (customHooks) {
412         if (customHooks->handler) {
413             rv = customHooks->handler(ss->fd, handshakeMessage,
414                                       extension->data.data,
415                                       extension->data.len,
416                                       &alert, customHooks->handlerArg);
417         }
418     } else {
419         /* Find extension_type in table of Hello Extension Handlers. */
420         for (; handler->ex_handler != NULL; ++handler) {
421             if (handler->ex_type == extension->type) {
422                 SECItem tmp = extension->data;
423 
424                 rv = (*handler->ex_handler)(ss, &ss->xtnData, &tmp);
425                 break;
426             }
427         }
428     }
429 
430     if (rv != SECSuccess) {
431         if (!ss->ssl3.fatalAlertSent) {
432             /* Send an alert if the handler didn't already. */
433             (void)SSL3_SendAlert(ss, alert_fatal, alert);
434         }
435         return SECFailure;
436     }
437 
438     return SECSuccess;
439 }
440 
441 /* Go through the hello extensions in |ss->ssl3.hs.remoteExtensions|.
442  * For each one, find the extension handler in the table, and
443  * if present, invoke that handler.
444  * Servers ignore any extensions with unknown extension types.
445  * Clients reject any extensions with unadvertised extension types
446  *
447  * In TLS >= 1.3, the client checks that extensions appear in the
448  * right phase.
449  */
450 SECStatus
ssl3_HandleParsedExtensions(sslSocket * ss,SSLHandshakeType message)451 ssl3_HandleParsedExtensions(sslSocket *ss, SSLHandshakeType message)
452 {
453     const ssl3ExtensionHandler *handlers;
454     /* HelloRetryRequest doesn't set ss->version. It might be safe to
455      * do so, but we weren't entirely sure. TODO(ekr@rtfm.com). */
456     PRBool isTLS13 = (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) ||
457                      (message == ssl_hs_hello_retry_request);
458     /* The following messages can include extensions that were not included in
459      * the original ClientHello. */
460     PRBool allowNotOffered = (message == ssl_hs_client_hello) ||
461                              (message == ssl_hs_certificate_request) ||
462                              (message == ssl_hs_new_session_ticket);
463     PRCList *cursor;
464 
465     switch (message) {
466         case ssl_hs_client_hello:
467             handlers = clientHelloHandlers;
468             break;
469         case ssl_hs_new_session_ticket:
470             PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
471             handlers = newSessionTicketHandlers;
472             break;
473         case ssl_hs_hello_retry_request:
474             handlers = helloRetryRequestHandlers;
475             break;
476         case ssl_hs_encrypted_extensions:
477             PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
478         /* fall through */
479         case ssl_hs_server_hello:
480             if (ss->version > SSL_LIBRARY_VERSION_3_0) {
481                 handlers = serverHelloHandlersTLS;
482             } else {
483                 handlers = serverHelloHandlersSSL3;
484             }
485             break;
486         case ssl_hs_certificate:
487             PORT_Assert(!ss->sec.isServer);
488             handlers = serverCertificateHandlers;
489             break;
490         case ssl_hs_certificate_request:
491             PORT_Assert(!ss->sec.isServer);
492             handlers = certificateRequestHandlers;
493             break;
494         default:
495             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
496             PORT_Assert(0);
497             return SECFailure;
498     }
499 
500     for (cursor = PR_NEXT_LINK(&ss->ssl3.hs.remoteExtensions);
501          cursor != &ss->ssl3.hs.remoteExtensions;
502          cursor = PR_NEXT_LINK(cursor)) {
503         TLSExtension *extension = (TLSExtension *)cursor;
504         SECStatus rv;
505 
506         /* Check whether the server sent an extension which was not advertised
507          * in the ClientHello.
508          *
509          * Note that a TLS 1.3 server should check if CertificateRequest
510          * extensions were sent.  But the extensions used for CertificateRequest
511          * do not have any response, so we rely on
512          * ssl3_ExtensionAdvertised to return false on the server.  That
513          * results in the server only rejecting any extension. */
514         if (!allowNotOffered && (extension->type != ssl_tls13_cookie_xtn) &&
515             !ssl3_ExtensionAdvertised(ss, extension->type)) {
516             (void)SSL3_SendAlert(ss, alert_fatal, unsupported_extension);
517             PORT_SetError(SSL_ERROR_RX_UNEXPECTED_EXTENSION);
518             return SECFailure;
519         }
520 
521         /* Check that this is a legal extension in TLS 1.3 */
522         if (isTLS13 &&
523             !ssl_FindCustomExtensionHooks(ss, extension->type)) {
524             switch (tls13_ExtensionStatus(extension->type, message)) {
525                 case tls13_extension_allowed:
526                     break;
527                 case tls13_extension_unknown:
528                     if (allowNotOffered) {
529                         continue; /* Skip over unknown extensions. */
530                     }
531                 /* Fall through. */
532                 case tls13_extension_disallowed:
533                     SSL_TRC(3, ("%d: TLS13: unexpected extension %d in message %d",
534                                 SSL_GETPID(), extension, message));
535                     tls13_FatalError(ss, SSL_ERROR_EXTENSION_DISALLOWED_FOR_VERSION,
536                                      unsupported_extension);
537                     return SECFailure;
538             }
539         }
540 
541         /* Special check for this being the last extension if it's
542          * PreSharedKey */
543         if (ss->sec.isServer && isTLS13 &&
544             (extension->type == ssl_tls13_pre_shared_key_xtn) &&
545             (PR_NEXT_LINK(cursor) != &ss->ssl3.hs.remoteExtensions)) {
546             tls13_FatalError(ss,
547                              SSL_ERROR_RX_MALFORMED_CLIENT_HELLO,
548                              illegal_parameter);
549             return SECFailure;
550         }
551 
552         rv = ssl_CallExtensionHandler(ss, message, extension, handlers);
553         if (rv != SECSuccess) {
554             return SECFailure;
555         }
556     }
557     return SECSuccess;
558 }
559 
560 /* Syntactic sugar around ssl3_ParseExtensions and
561  * ssl3_HandleParsedExtensions. */
562 SECStatus
ssl3_HandleExtensions(sslSocket * ss,PRUint8 ** b,PRUint32 * length,SSLHandshakeType handshakeMessage)563 ssl3_HandleExtensions(sslSocket *ss,
564                       PRUint8 **b, PRUint32 *length,
565                       SSLHandshakeType handshakeMessage)
566 {
567     SECStatus rv;
568 
569     rv = ssl3_ParseExtensions(ss, b, length);
570     if (rv != SECSuccess)
571         return rv;
572 
573     rv = ssl3_HandleParsedExtensions(ss, handshakeMessage);
574     if (rv != SECSuccess)
575         return rv;
576 
577     ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
578     return SECSuccess;
579 }
580 
581 /* Add a callback function to the table of senders of server hello extensions.
582  */
583 SECStatus
ssl3_RegisterExtensionSender(const sslSocket * ss,TLSExtensionData * xtnData,PRUint16 ex_type,sslExtensionBuilderFunc cb)584 ssl3_RegisterExtensionSender(const sslSocket *ss,
585                              TLSExtensionData *xtnData,
586                              PRUint16 ex_type,
587                              sslExtensionBuilderFunc cb)
588 {
589     int i;
590     sslExtensionBuilder *sender;
591     if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
592         sender = &xtnData->serverHelloSenders[0];
593     } else {
594         if (tls13_ExtensionStatus(ex_type, ssl_hs_server_hello) ==
595             tls13_extension_allowed) {
596             PORT_Assert(tls13_ExtensionStatus(ex_type,
597                                               ssl_hs_encrypted_extensions) ==
598                         tls13_extension_disallowed);
599             sender = &xtnData->serverHelloSenders[0];
600         } else if (tls13_ExtensionStatus(ex_type,
601                                          ssl_hs_encrypted_extensions) ==
602                    tls13_extension_allowed) {
603             sender = &xtnData->encryptedExtensionsSenders[0];
604         } else if (tls13_ExtensionStatus(ex_type, ssl_hs_certificate) ==
605                    tls13_extension_allowed) {
606             sender = &xtnData->certificateSenders[0];
607         } else {
608             PORT_Assert(0);
609             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
610             return SECFailure;
611         }
612     }
613     for (i = 0; i < SSL_MAX_EXTENSIONS; ++i, ++sender) {
614         if (!sender->ex_sender) {
615             sender->ex_type = ex_type;
616             sender->ex_sender = cb;
617             return SECSuccess;
618         }
619         /* detect duplicate senders */
620         PORT_Assert(sender->ex_type != ex_type);
621         if (sender->ex_type == ex_type) {
622             /* duplicate */
623             break;
624         }
625     }
626     PORT_Assert(i < SSL_MAX_EXTENSIONS); /* table needs to grow */
627     PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
628     return SECFailure;
629 }
630 
631 static SECStatus
ssl_CallCustomExtensionSenders(sslSocket * ss,sslBuffer * buf,SSLHandshakeType message)632 ssl_CallCustomExtensionSenders(sslSocket *ss, sslBuffer *buf,
633                                SSLHandshakeType message)
634 {
635     sslBuffer tail = SSL_BUFFER_EMPTY;
636     SECStatus rv;
637     PRCList *cursor;
638 
639     /* Save any extensions that want to be last. */
640     if (ss->xtnData.lastXtnOffset) {
641         rv = sslBuffer_Append(&tail, buf->buf + ss->xtnData.lastXtnOffset,
642                               buf->len - ss->xtnData.lastXtnOffset);
643         if (rv != SECSuccess) {
644             return SECFailure;
645         }
646         buf->len = ss->xtnData.lastXtnOffset;
647     }
648 
649     /* Reserve the maximum amount of space possible. */
650     rv = sslBuffer_Grow(buf, 65535);
651     if (rv != SECSuccess) {
652         return SECFailure;
653     }
654 
655     for (cursor = PR_NEXT_LINK(&ss->extensionHooks);
656          cursor != &ss->extensionHooks;
657          cursor = PR_NEXT_LINK(cursor)) {
658         sslCustomExtensionHooks *hook =
659             (sslCustomExtensionHooks *)cursor;
660         PRBool append = PR_FALSE;
661         unsigned int len = 0;
662 
663         if (hook->writer) {
664             /* The writer writes directly into |buf|.  Provide space that allows
665              * for the existing extensions, any tail, plus type and length. */
666             unsigned int space = buf->space - (buf->len + tail.len + 4);
667             append = (*hook->writer)(ss->fd, message,
668                                      buf->buf + buf->len + 4, &len, space,
669                                      hook->writerArg);
670             if (len > space) {
671                 PORT_SetError(SEC_ERROR_APPLICATION_CALLBACK_ERROR);
672                 goto loser;
673             }
674         }
675         if (!append) {
676             continue;
677         }
678 
679         rv = sslBuffer_AppendNumber(buf, hook->type, 2);
680         if (rv != SECSuccess) {
681             goto loser; /* Code already set. */
682         }
683         rv = sslBuffer_AppendNumber(buf, len, 2);
684         if (rv != SECSuccess) {
685             goto loser; /* Code already set. */
686         }
687         buf->len += len;
688 
689         if (message == ssl_hs_client_hello ||
690             message == ssl_hs_certificate_request) {
691             ss->xtnData.advertised[ss->xtnData.numAdvertised++] = hook->type;
692         }
693     }
694 
695     rv = sslBuffer_Append(buf, tail.buf, tail.len);
696     if (rv != SECSuccess) {
697         goto loser; /* Code already set. */
698     }
699 
700     sslBuffer_Clear(&tail);
701     return SECSuccess;
702 
703 loser:
704     sslBuffer_Clear(&tail);
705     return SECFailure;
706 }
707 
708 /* Call extension handlers for the given message. */
709 SECStatus
ssl_ConstructExtensions(sslSocket * ss,sslBuffer * buf,SSLHandshakeType message)710 ssl_ConstructExtensions(sslSocket *ss, sslBuffer *buf, SSLHandshakeType message)
711 {
712     const sslExtensionBuilder *sender;
713     SECStatus rv;
714 
715     PORT_Assert(buf->len == 0);
716 
717     /* Clear out any extensions previously advertised */
718     ss->xtnData.numAdvertised = 0;
719 
720     switch (message) {
721         case ssl_hs_client_hello:
722             if (ss->vrange.max > SSL_LIBRARY_VERSION_3_0) {
723                 sender = clientHelloSendersTLS;
724             } else {
725                 sender = clientHelloSendersSSL3;
726             }
727             break;
728 
729         case ssl_hs_server_hello:
730             sender = ss->xtnData.serverHelloSenders;
731             break;
732 
733         case ssl_hs_certificate_request:
734             PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
735             sender = tls13_cert_req_senders;
736             break;
737 
738         case ssl_hs_certificate:
739             PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
740             sender = ss->xtnData.certificateSenders;
741             break;
742 
743         case ssl_hs_encrypted_extensions:
744             PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
745             sender = ss->xtnData.encryptedExtensionsSenders;
746             break;
747 
748         case ssl_hs_hello_retry_request:
749             PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
750             sender = tls13_hrr_senders;
751             break;
752 
753         default:
754             PORT_Assert(0);
755             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
756             return SECFailure;
757     }
758 
759     for (; sender->ex_sender != NULL; ++sender) {
760         PRBool append = PR_FALSE;
761         unsigned int start = buf->len;
762         unsigned int length;
763 
764         if (ssl_FindCustomExtensionHooks(ss, sender->ex_type)) {
765             continue;
766         }
767 
768         /* Save space for the extension type and length. Note that we don't grow
769          * the buffer now; rely on sslBuffer_Append* to do that. */
770         buf->len += 4;
771         rv = (*sender->ex_sender)(ss, &ss->xtnData, buf, &append);
772         if (rv != SECSuccess) {
773             goto loser;
774         }
775 
776         /* Save the length and go back to the start. */
777         length = buf->len - start - 4;
778         buf->len = start;
779         if (!append) {
780             continue;
781         }
782 
783         buf->len = start;
784         rv = sslBuffer_AppendNumber(buf, sender->ex_type, 2);
785         if (rv != SECSuccess) {
786             goto loser; /* Code already set. */
787         }
788         rv = sslBuffer_AppendNumber(buf, length, 2);
789         if (rv != SECSuccess) {
790             goto loser; /* Code already set. */
791         }
792         /* Skip over the extension body. */
793         buf->len += length;
794 
795         if (message == ssl_hs_client_hello ||
796             message == ssl_hs_certificate_request) {
797             ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
798                 sender->ex_type;
799         }
800     }
801 
802     if (!PR_CLIST_IS_EMPTY(&ss->extensionHooks)) {
803         rv = ssl_CallCustomExtensionSenders(ss, buf, message);
804         if (rv != SECSuccess) {
805             goto loser;
806         }
807     }
808 
809     if (buf->len > 0xffff) {
810         PORT_SetError(SSL_ERROR_TX_RECORD_TOO_LONG);
811         goto loser;
812     }
813 
814     return SECSuccess;
815 
816 loser:
817     sslBuffer_Clear(buf);
818     return SECFailure;
819 }
820 
821 /* This extension sender can be used anywhere that an always empty extension is
822  * needed. Mostly that is for ServerHello where sender registration is dynamic;
823  * ClientHello senders are usually conditional in some way. */
824 SECStatus
ssl_SendEmptyExtension(const sslSocket * ss,TLSExtensionData * xtnData,sslBuffer * buf,PRBool * append)825 ssl_SendEmptyExtension(const sslSocket *ss, TLSExtensionData *xtnData,
826                        sslBuffer *buf, PRBool *append)
827 {
828     *append = PR_TRUE;
829     return SECSuccess;
830 }
831 
832 /* Takes the size of the ClientHello, less the record header, and determines how
833  * much padding is required. */
834 static unsigned int
ssl_CalculatePaddingExtLen(const sslSocket * ss,unsigned int clientHelloLength)835 ssl_CalculatePaddingExtLen(const sslSocket *ss, unsigned int clientHelloLength)
836 {
837     unsigned int recordLength = 1 /* handshake message type */ +
838                                 3 /* handshake message length */ +
839                                 clientHelloLength;
840     unsigned int extensionLen;
841 
842     /* Don't pad for DTLS, for SSLv3, or for renegotiation. */
843     if (IS_DTLS(ss) ||
844         ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_0 ||
845         ss->firstHsDone) {
846         return 0;
847     }
848 
849     /* A padding extension may be included to ensure that the record containing
850      * the ClientHello doesn't have a length between 256 and 511 bytes
851      * (inclusive). Initial ClientHello records with such lengths trigger bugs
852      * in F5 devices. */
853     if (recordLength < 256 || recordLength >= 512) {
854         return 0;
855     }
856 
857     extensionLen = 512 - recordLength;
858     /* Extensions take at least four bytes to encode. Always include at least
859      * one byte of data if we are padding. Some servers will time out or
860      * terminate the connection if the last ClientHello extension is empty. */
861     if (extensionLen < 5) {
862         extensionLen = 5;
863     }
864 
865     return extensionLen - 4;
866 }
867 
868 /* ssl3_SendPaddingExtension possibly adds an extension which ensures that a
869  * ClientHello record is either < 256 bytes or is >= 512 bytes. This ensures
870  * that we don't trigger bugs in F5 products.
871  *
872  * This takes an existing extension buffer, |buf|, and the length of the
873  * remainder of the ClientHello, |prefixLen|.  It modifies the extension buffer
874  * to insert padding at the right place.
875  */
876 SECStatus
ssl_InsertPaddingExtension(const sslSocket * ss,unsigned int prefixLen,sslBuffer * buf)877 ssl_InsertPaddingExtension(const sslSocket *ss, unsigned int prefixLen,
878                            sslBuffer *buf)
879 {
880     static unsigned char padding[252] = { 0 };
881     unsigned int paddingLen;
882     unsigned int tailLen;
883     SECStatus rv;
884 
885     /* Account for the size of the header, the length field of the extensions
886      * block and the size of the existing extensions. */
887     paddingLen = ssl_CalculatePaddingExtLen(ss, prefixLen + 2 + buf->len);
888     if (!paddingLen) {
889         return SECSuccess;
890     }
891 
892     /* Move the tail if there is one. This only happens if we are sending the
893      * TLS 1.3 PSK extension, which needs to be at the end. */
894     if (ss->xtnData.lastXtnOffset) {
895         PORT_Assert(buf->len > ss->xtnData.lastXtnOffset);
896         tailLen = buf->len - ss->xtnData.lastXtnOffset;
897         rv = sslBuffer_Grow(buf, buf->len + 4 + paddingLen);
898         if (rv != SECSuccess) {
899             return SECFailure;
900         }
901         PORT_Memmove(buf->buf + ss->xtnData.lastXtnOffset + 4 + paddingLen,
902                      buf->buf + ss->xtnData.lastXtnOffset,
903                      tailLen);
904         buf->len = ss->xtnData.lastXtnOffset;
905     } else {
906         tailLen = 0;
907     }
908 
909     rv = sslBuffer_AppendNumber(buf, ssl_padding_xtn, 2);
910     if (rv != SECSuccess) {
911         return SECFailure; /* Code already set. */
912     }
913     rv = sslBuffer_AppendVariable(buf, padding, paddingLen, 2);
914     if (rv != SECSuccess) {
915         return SECFailure; /* Code already set. */
916     }
917 
918     buf->len += tailLen;
919 
920     return SECSuccess;
921 }
922 
923 void
ssl3_DestroyRemoteExtensions(PRCList * list)924 ssl3_DestroyRemoteExtensions(PRCList *list)
925 {
926     PRCList *cur_p;
927 
928     while (!PR_CLIST_IS_EMPTY(list)) {
929         cur_p = PR_LIST_TAIL(list);
930         PR_REMOVE_LINK(cur_p);
931         PORT_Free(cur_p);
932     }
933 }
934 
935 /* Initialize the extension data block. */
936 void
ssl3_InitExtensionData(TLSExtensionData * xtnData,const sslSocket * ss)937 ssl3_InitExtensionData(TLSExtensionData *xtnData, const sslSocket *ss)
938 {
939     unsigned int advertisedMax;
940     PRCList *cursor;
941 
942     /* Set things up to the right starting state. */
943     PORT_Memset(xtnData, 0, sizeof(*xtnData));
944     xtnData->peerSupportsFfdheGroups = PR_FALSE;
945     PR_INIT_CLIST(&xtnData->remoteKeyShares);
946 
947     /* Allocate enough to allow for native extensions, plus any custom ones. */
948     if (ss->sec.isServer) {
949         advertisedMax = PR_MAX(PR_ARRAY_SIZE(certificateRequestHandlers),
950                                PR_ARRAY_SIZE(tls13_cert_req_senders));
951     } else {
952         advertisedMax = PR_MAX(PR_ARRAY_SIZE(clientHelloHandlers),
953                                PR_ARRAY_SIZE(clientHelloSendersTLS));
954         ++advertisedMax; /* For the RI SCSV, which we also track. */
955     }
956     for (cursor = PR_NEXT_LINK(&ss->extensionHooks);
957          cursor != &ss->extensionHooks;
958          cursor = PR_NEXT_LINK(cursor)) {
959         ++advertisedMax;
960     }
961     xtnData->advertised = PORT_ZNewArray(PRUint16, advertisedMax);
962     xtnData->peerDelegCred = NULL;
963     xtnData->peerRequestedDelegCred = PR_FALSE;
964     xtnData->sendingDelegCredToPeer = PR_FALSE;
965 }
966 
967 void
ssl3_DestroyExtensionData(TLSExtensionData * xtnData)968 ssl3_DestroyExtensionData(TLSExtensionData *xtnData)
969 {
970     ssl3_FreeSniNameArray(xtnData);
971     PORT_Free(xtnData->sigSchemes);
972     PORT_Free(xtnData->delegCredSigSchemes);
973     PORT_Free(xtnData->delegCredSigSchemesAdvertised);
974     SECITEM_FreeItem(&xtnData->nextProto, PR_FALSE);
975     tls13_DestroyKeyShares(&xtnData->remoteKeyShares);
976     SECITEM_FreeItem(&xtnData->certReqContext, PR_FALSE);
977     SECITEM_FreeItem(&xtnData->applicationToken, PR_FALSE);
978     if (xtnData->certReqAuthorities.arena) {
979         PORT_FreeArena(xtnData->certReqAuthorities.arena, PR_FALSE);
980         xtnData->certReqAuthorities.arena = NULL;
981     }
982     PORT_Free(xtnData->advertised);
983     ssl_FreeEphemeralKeyPair(xtnData->esniPrivateKey);
984     SECITEM_FreeItem(&xtnData->keyShareExtension, PR_FALSE);
985     tls13_DestroyDelegatedCredential(xtnData->peerDelegCred);
986 }
987 
988 /* Free everything that has been allocated and then reset back to
989  * the starting state. */
990 void
ssl3_ResetExtensionData(TLSExtensionData * xtnData,const sslSocket * ss)991 ssl3_ResetExtensionData(TLSExtensionData *xtnData, const sslSocket *ss)
992 {
993     ssl3_DestroyExtensionData(xtnData);
994     ssl3_InitExtensionData(xtnData, ss);
995 }
996 
997 /* Thunks to let extension handlers operate on const sslSocket* objects. */
998 void
ssl3_ExtSendAlert(const sslSocket * ss,SSL3AlertLevel level,SSL3AlertDescription desc)999 ssl3_ExtSendAlert(const sslSocket *ss, SSL3AlertLevel level,
1000                   SSL3AlertDescription desc)
1001 {
1002     (void)SSL3_SendAlert((sslSocket *)ss, level, desc);
1003 }
1004 
1005 void
ssl3_ExtDecodeError(const sslSocket * ss)1006 ssl3_ExtDecodeError(const sslSocket *ss)
1007 {
1008     (void)ssl3_DecodeError((sslSocket *)ss);
1009 }
1010 
1011 SECStatus
ssl3_ExtConsumeHandshake(const sslSocket * ss,void * v,PRUint32 bytes,PRUint8 ** b,PRUint32 * length)1012 ssl3_ExtConsumeHandshake(const sslSocket *ss, void *v, PRUint32 bytes,
1013                          PRUint8 **b, PRUint32 *length)
1014 {
1015     return ssl3_ConsumeHandshake((sslSocket *)ss, v, bytes, b, length);
1016 }
1017 
1018 SECStatus
ssl3_ExtConsumeHandshakeNumber(const sslSocket * ss,PRUint32 * num,PRUint32 bytes,PRUint8 ** b,PRUint32 * length)1019 ssl3_ExtConsumeHandshakeNumber(const sslSocket *ss, PRUint32 *num,
1020                                PRUint32 bytes, PRUint8 **b, PRUint32 *length)
1021 {
1022     return ssl3_ConsumeHandshakeNumber((sslSocket *)ss, num, bytes, b, length);
1023 }
1024 
1025 SECStatus
ssl3_ExtConsumeHandshakeVariable(const sslSocket * ss,SECItem * i,PRUint32 bytes,PRUint8 ** b,PRUint32 * length)1026 ssl3_ExtConsumeHandshakeVariable(const sslSocket *ss, SECItem *i,
1027                                  PRUint32 bytes, PRUint8 **b,
1028                                  PRUint32 *length)
1029 {
1030     return ssl3_ConsumeHandshakeVariable((sslSocket *)ss, i, bytes, b, length);
1031 }
1032