4f54c3f7716eff62d000036941576d77ba13f934
[openssl.git] / ssl / statem / extensions.c
1 /*
2  * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include "../ssl_locl.h"
11 #include "statem_locl.h"
12
13 static int final_renegotiate(SSL *s, unsigned int context, int sent,
14                                      int *al);
15 static int init_server_name(SSL *s, unsigned int context);
16 static int final_server_name(SSL *s, unsigned int context, int sent,
17                                      int *al);
18 #ifndef OPENSSL_NO_EC
19 static int final_ec_pt_formats(SSL *s, unsigned int context, int sent,
20                                        int *al);
21 #endif
22 static int init_session_ticket(SSL *s, unsigned int context);
23 #ifndef OPENSSL_NO_OCSP
24 static int init_status_request(SSL *s, unsigned int context);
25 #endif
26 #ifndef OPENSSL_NO_NEXTPROTONEG
27 static int init_npn(SSL *s, unsigned int context);
28 #endif
29 static int init_alpn(SSL *s, unsigned int context);
30 static int final_alpn(SSL *s, unsigned int context, int sent, int *al);
31 static int init_sig_algs(SSL *s, unsigned int context);
32 #ifndef OPENSSL_NO_SRP
33 static int init_srp(SSL *s, unsigned int context);
34 #endif
35 static int init_etm(SSL *s, unsigned int context);
36 static int init_ems(SSL *s, unsigned int context);
37 static int final_ems(SSL *s, unsigned int context, int sent, int *al);
38 #ifndef OPENSSL_NO_SRTP
39 static int init_srtp(SSL *s, unsigned int context);
40 #endif
41 static int final_sig_algs(SSL *s, unsigned int context, int sent, int *al);
42
43 /* Structure to define a built-in extension */
44 typedef struct extensions_definition_st {
45     /* The defined type for the extension */
46     unsigned int type;
47     /*
48      * The context that this extension applies to, e.g. what messages and
49      * protocol versions
50      */
51     unsigned int context;
52     /*
53      * Initialise extension before parsing. Always called for relevant contexts
54      * even if extension not present
55      */
56     int (*init)(SSL *s, unsigned int context);
57     /* Parse extension sent from client to server */
58     int (*parse_ctos)(SSL *s, PACKET *pkt, X509 *x, size_t chainidx, int *al);
59     /* Parse extension send from server to client */
60     int (*parse_stoc)(SSL *s, PACKET *pkt, X509 *x, size_t chainidx, int *al);
61     /* Construct extension sent from server to client */
62     int (*construct_stoc)(SSL *s, WPACKET *pkt, X509 *x, size_t chainidx,
63                           int *al);
64     /* Construct extension sent from client to server */
65     int (*construct_ctos)(SSL *s, WPACKET *pkt, X509 *x, size_t chainidx,
66                           int *al);
67     /*
68      * Finalise extension after parsing. Always called where an extensions was
69      * initialised even if the extension was not present. |sent| is set to 1 if
70      * the extension was seen, or 0 otherwise.
71      */
72     int (*final)(SSL *s, unsigned int context, int sent, int *al);
73 } EXTENSION_DEFINITION;
74
75 /*
76  * Definitions of all built-in extensions. NOTE: Changes in the number or order
77  * of these extensions should be mirrored with equivalent changes to the indexes
78  * defined in statem_locl.h.
79  * Each extension has an initialiser, a client and
80  * server side parser and a finaliser. The initialiser is called (if the
81  * extension is relevant to the given context) even if we did not see the
82  * extension in the message that we received. The parser functions are only
83  * called if we see the extension in the message. The finalisers are always
84  * called if the initialiser was called.
85  * There are also server and client side constructor functions which are always
86  * called during message construction if the extension is relevant for the
87  * given context.
88  * The initialisation, parsing, finalisation and construction functions are
89  * always called in the order defined in this list. Some extensions may depend
90  * on others having been processed first, so the order of this list is
91  * significant.
92  * The extension context is defined by a series of flags which specify which
93  * messages the extension is relevant to. These flags also specify whether the
94  * extension is relevant to a paricular protocol or protocol version.
95  *
96  * TODO(TLS1.3): Make sure we have a test to check the consistency of these
97  */
98 #define INVALID_EXTENSION { 0x10000, 0, NULL, NULL, NULL, NULL, NULL, NULL }
99 static const EXTENSION_DEFINITION ext_defs[] = {
100     {
101         TLSEXT_TYPE_renegotiate,
102         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_SSL3_ALLOWED
103         | EXT_TLS1_2_AND_BELOW_ONLY,
104         NULL, tls_parse_ctos_renegotiate, tls_parse_stoc_renegotiate,
105         tls_construct_stoc_renegotiate, tls_construct_ctos_renegotiate,
106         final_renegotiate
107     },
108     {
109         TLSEXT_TYPE_server_name,
110         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
111         | EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
112         init_server_name,
113         tls_parse_ctos_server_name, tls_parse_stoc_server_name,
114         tls_construct_stoc_server_name, tls_construct_ctos_server_name,
115         final_server_name
116     },
117 #ifndef OPENSSL_NO_SRP
118     {
119         TLSEXT_TYPE_srp,
120         EXT_CLIENT_HELLO | EXT_TLS1_2_AND_BELOW_ONLY,
121         init_srp, tls_parse_ctos_srp, NULL, NULL, tls_construct_ctos_srp, NULL
122     },
123 #else
124     INVALID_EXTENSION,
125 #endif
126 #ifndef OPENSSL_NO_EC
127     {
128         TLSEXT_TYPE_ec_point_formats,
129         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY,
130         NULL, tls_parse_ctos_ec_pt_formats, tls_parse_stoc_ec_pt_formats,
131         tls_construct_stoc_ec_pt_formats, tls_construct_ctos_ec_pt_formats,
132         final_ec_pt_formats
133     },
134     {
135         TLSEXT_TYPE_supported_groups,
136         EXT_CLIENT_HELLO | EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
137         NULL, tls_parse_ctos_supported_groups, NULL,
138         NULL /* TODO(TLS1.3): Need to add this */,
139         tls_construct_ctos_supported_groups, NULL
140     },
141 #else
142     INVALID_EXTENSION,
143     INVALID_EXTENSION,
144 #endif
145     {
146         TLSEXT_TYPE_session_ticket,
147         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY,
148         init_session_ticket, tls_parse_ctos_session_ticket,
149         tls_parse_stoc_session_ticket, tls_construct_stoc_session_ticket,
150         tls_construct_ctos_session_ticket, NULL
151     },
152     {
153         TLSEXT_TYPE_signature_algorithms,
154         EXT_CLIENT_HELLO,
155         init_sig_algs, tls_parse_ctos_sig_algs, NULL, NULL,
156         tls_construct_ctos_sig_algs, final_sig_algs
157     },
158 #ifndef OPENSSL_NO_OCSP
159     {
160         TLSEXT_TYPE_status_request,
161         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
162         | EXT_TLS1_3_CERTIFICATE,
163         init_status_request, tls_parse_ctos_status_request,
164         tls_parse_stoc_status_request, tls_construct_stoc_status_request,
165         tls_construct_ctos_status_request, NULL
166     },
167 #else
168     INVALID_EXTENSION,
169 #endif
170 #ifndef OPENSSL_NO_NEXTPROTONEG
171     {
172         TLSEXT_TYPE_next_proto_neg,
173         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY,
174         init_npn, tls_parse_ctos_npn, tls_parse_stoc_npn,
175         tls_construct_stoc_next_proto_neg, tls_construct_ctos_npn, NULL
176     },
177 #else
178     INVALID_EXTENSION,
179 #endif
180     {
181         /*
182          * Must appear in this list after server_name so that finalisation
183          * happens after server_name callbacks
184          */
185         TLSEXT_TYPE_application_layer_protocol_negotiation,
186         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
187         | EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
188         init_alpn, tls_parse_ctos_alpn, tls_parse_stoc_alpn,
189         tls_construct_stoc_alpn, tls_construct_ctos_alpn, final_alpn
190     },
191 #ifndef OPENSSL_NO_SRTP
192     {
193         TLSEXT_TYPE_use_srtp,
194         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
195         | EXT_TLS1_3_ENCRYPTED_EXTENSIONS | EXT_DTLS_ONLY,
196         init_srtp, tls_parse_ctos_use_srtp, tls_parse_stoc_use_srtp,
197         tls_construct_stoc_use_srtp, tls_construct_ctos_use_srtp, NULL
198     },
199 #else
200     INVALID_EXTENSION,
201 #endif
202     {
203         TLSEXT_TYPE_encrypt_then_mac,
204         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY,
205         init_etm, tls_parse_ctos_etm, tls_parse_stoc_etm,
206         tls_construct_stoc_etm, tls_construct_ctos_etm, NULL
207     },
208 #ifndef OPENSSL_NO_CT
209     {
210         TLSEXT_TYPE_signed_certificate_timestamp,
211         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
212         | EXT_TLS1_3_CERTIFICATE,
213         NULL,
214         /*
215          * No server side support for this, but can be provided by a custom
216          * extension. This is an exception to the rule that custom extensions
217          * cannot override built in ones.
218          */
219         NULL, tls_parse_stoc_sct, NULL, tls_construct_ctos_sct,  NULL
220     },
221 #else
222     INVALID_EXTENSION,
223 #endif
224     {
225         TLSEXT_TYPE_extended_master_secret,
226         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY,
227         init_ems, tls_parse_ctos_ems, tls_parse_stoc_ems,
228         tls_construct_stoc_ems, tls_construct_ctos_ems, final_ems
229     },
230     {
231         TLSEXT_TYPE_supported_versions,
232         EXT_CLIENT_HELLO | EXT_TLS_IMPLEMENTATION_ONLY | EXT_TLS1_3_ONLY,
233         NULL,
234         /* Processed inline as part of version selection */
235         NULL, NULL, NULL, tls_construct_ctos_supported_versions, NULL
236     },
237     {
238         /*
239          * Must be in this list after supported_groups. We need that to have
240          * been parsed before we do this one.
241          */
242         TLSEXT_TYPE_key_share,
243         EXT_CLIENT_HELLO | EXT_TLS1_3_SERVER_HELLO
244         | EXT_TLS1_3_HELLO_RETRY_REQUEST | EXT_TLS_IMPLEMENTATION_ONLY
245         | EXT_TLS1_3_ONLY,
246         NULL, tls_parse_ctos_key_share, tls_parse_stoc_key_share,
247         tls_construct_stoc_key_share, tls_construct_ctos_key_share, NULL
248     },
249     {
250         /*
251          * Special unsolicited ServerHello extension only used when
252          * SSL_OP_CRYPTOPRO_TLSEXT_BUG is set
253          */
254         TLSEXT_TYPE_cryptopro_bug,
255         EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY,
256         NULL, NULL, NULL, tls_construct_stoc_cryptopro_bug, NULL, NULL
257     },
258     {
259         /* Last in the list because it must be added as the last extension */
260         TLSEXT_TYPE_padding,
261         EXT_CLIENT_HELLO,
262         NULL,
263         /* We send this, but don't read it */
264         NULL, NULL, NULL, tls_construct_ctos_padding, NULL
265     }
266 };
267
268 /*
269  * Verify whether we are allowed to use the extension |type| in the current
270  * |context|. Returns 1 to indicate the extension is allowed or unknown or 0 to
271  * indicate the extension is not allowed. If returning 1 then |*found| is set to
272  * 1 if we found a definition for the extension, and |*idx| is set to its index
273  */
274 static int verify_extension(SSL *s, unsigned int context, unsigned int type,
275                             custom_ext_methods *meths, RAW_EXTENSION *rawexlist,
276                             RAW_EXTENSION **found)
277 {
278     size_t i;
279     size_t builtin_num = OSSL_NELEM(ext_defs);
280     const EXTENSION_DEFINITION *thisext;
281
282     for (i = 0, thisext = ext_defs; i < builtin_num; i++, thisext++) {
283         if (type == thisext->type) {
284             /* Check we're allowed to use this extension in this context */
285             if ((context & thisext->context) == 0)
286                 return 0;
287
288             if (SSL_IS_DTLS(s)) {
289                 if ((thisext->context & EXT_TLS_ONLY) != 0)
290                     return 0;
291             } else if ((thisext->context & EXT_DTLS_ONLY) != 0) {
292                     return 0;
293             }
294
295             *found = &rawexlist[i];
296             return 1;
297         }
298     }
299
300     if ((context & (EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO)) == 0) {
301         /*
302          * Custom extensions only apply to <=TLS1.2. This extension is unknown
303          * in this context - we allow it
304          */
305         *found = NULL;
306         return 1;
307     }
308
309     /* Check the custom extensions */
310     if (meths != NULL) {
311         for (i = builtin_num; i < builtin_num + meths->meths_count; i++) {
312             if (meths->meths[i - builtin_num].ext_type == type) {
313                 *found = &rawexlist[i];
314                 return 1;
315             }
316         }
317     }
318
319     /* Unknown extension. We allow it */
320     *found = NULL;
321     return 1;
322 }
323
324 /*
325  * Check whether the context defined for an extension |extctx| means whether
326  * the extension is relevant for the current context |thisctx| or not. Returns
327  * 1 if the extension is relevant for this context, and 0 otherwise
328  */
329 static int extension_is_relevant(SSL *s, unsigned int extctx,
330                                  unsigned int thisctx)
331 {
332     if ((SSL_IS_DTLS(s)
333                 && (extctx & EXT_TLS_IMPLEMENTATION_ONLY) != 0)
334             || (s->version == SSL3_VERSION
335                     && (extctx & EXT_SSL3_ALLOWED) == 0)
336             || (SSL_IS_TLS13(s)
337                 && (extctx & EXT_TLS1_2_AND_BELOW_ONLY) != 0)
338             || (!SSL_IS_TLS13(s) && (extctx & EXT_TLS1_3_ONLY) != 0))
339         return 0;
340
341     return 1;
342 }
343
344 /*
345  * Gather a list of all the extensions from the data in |packet]. |context|
346  * tells us which message this extension is for. The raw extension data is
347  * stored in |*res| on success. In the event of an error the alert type to use
348  * is stored in |*al|. We don't actually process the content of the extensions
349  * yet, except to check their types. This function also runs the initialiser
350  * functions for all known extensions (whether we have collected them or not).
351  * If successful the caller is responsible for freeing the contents of |*res|.
352  *
353  * Per http://tools.ietf.org/html/rfc5246#section-7.4.1.4, there may not be
354  * more than one extension of the same type in a ClientHello or ServerHello.
355  * This function returns 1 if all extensions are unique and we have parsed their
356  * types, and 0 if the extensions contain duplicates, could not be successfully
357  * found, or an internal error occurred. We only check duplicates for
358  * extensions that we know about. We ignore others.
359  */
360 int tls_collect_extensions(SSL *s, PACKET *packet, unsigned int context,
361                            RAW_EXTENSION **res, int *al)
362 {
363     PACKET extensions = *packet;
364     size_t i = 0;
365     custom_ext_methods *exts = NULL;
366     RAW_EXTENSION *raw_extensions = NULL;
367     const EXTENSION_DEFINITION *thisexd;
368
369     *res = NULL;
370
371     /*
372      * Initialise server side custom extensions. Client side is done during
373      * construction of extensions for the ClientHello.
374      */
375     if ((context & EXT_CLIENT_HELLO) != 0) {
376         exts = &s->cert->srv_ext;
377         custom_ext_init(&s->cert->srv_ext);
378     } else if ((context & EXT_TLS1_2_SERVER_HELLO) != 0) {
379         exts = &s->cert->cli_ext;
380     }
381
382     raw_extensions = OPENSSL_zalloc((OSSL_NELEM(ext_defs)
383                                      + (exts != NULL ? exts->meths_count : 0))
384                                      * sizeof(*raw_extensions));
385     if (raw_extensions == NULL) {
386         *al = SSL_AD_INTERNAL_ERROR;
387         SSLerr(SSL_F_TLS_COLLECT_EXTENSIONS, ERR_R_MALLOC_FAILURE);
388         return 0;
389     }
390
391     while (PACKET_remaining(&extensions) > 0) {
392         unsigned int type;
393         PACKET extension;
394         RAW_EXTENSION *thisex;
395
396         if (!PACKET_get_net_2(&extensions, &type) ||
397             !PACKET_get_length_prefixed_2(&extensions, &extension)) {
398             SSLerr(SSL_F_TLS_COLLECT_EXTENSIONS, SSL_R_BAD_EXTENSION);
399             *al = SSL_AD_DECODE_ERROR;
400             goto err;
401         }
402         /*
403          * Verify this extension is allowed. We only check duplicates for
404          * extensions that we recognise.
405          */
406         if (!verify_extension(s, context, type, exts, raw_extensions, &thisex)
407                 || (thisex != NULL && thisex->present == 1)) {
408             SSLerr(SSL_F_TLS_COLLECT_EXTENSIONS, SSL_R_BAD_EXTENSION);
409             *al = SSL_AD_ILLEGAL_PARAMETER;
410             goto err;
411         }
412         if (thisex != NULL) {
413             thisex->data = extension;
414             thisex->present = 1;
415             thisex->type = type;
416         }
417     }
418
419     /*
420      * Initialise all known extensions relevant to this context, whether we have
421      * found them or not
422      */
423     for (thisexd = ext_defs, i = 0; i < OSSL_NELEM(ext_defs); i++, thisexd++) {
424         if(thisexd->init != NULL && (thisexd->context & context) != 0
425                 && extension_is_relevant(s, thisexd->context, context)
426                 && !thisexd->init(s, context)) {
427             *al = SSL_AD_INTERNAL_ERROR;
428             goto err;
429         }
430     }
431
432     *res = raw_extensions;
433     return 1;
434
435  err:
436     OPENSSL_free(raw_extensions);
437     return 0;
438 }
439
440 /*
441  * Runs the parser for a given extension with index |idx|. |exts| contains the
442  * list of all parsed extensions previously collected by
443  * tls_collect_extensions(). The parser is only run if it is applicable for the
444  * given |context| and the parser has not already been run. If this is for a
445  * Certificate message, then we also provide the parser with the relevant
446  * Certificate |x| and its position in the |chainidx| with 0 being the first
447  * Certificate. Returns 1 on success or 0 on failure. In the event of a failure
448  * |*al| is populated with a suitable alert code. If an extension is not present
449  * this counted as success.
450  */
451 int tls_parse_extension(SSL *s, TLSEXT_INDEX idx, int context,
452                         RAW_EXTENSION *exts, X509 *x, size_t chainidx, int *al)
453 {
454     RAW_EXTENSION *currext = &exts[idx];
455     int (*parser)(SSL *s, PACKET *pkt, X509 *x, size_t chainidx, int *al) = NULL;
456
457     /* Skip if the extension is not present */
458     if (!currext->present)
459         return 1;
460
461     if (s->ext.debug_cb)
462         s->ext.debug_cb(s, !s->server, currext->type,
463                         PACKET_data(&currext->data),
464                         PACKET_remaining(&currext->data),
465                         s->ext.debug_arg);
466
467     /* Skip if we've already parsed this extension */
468     if (currext->parsed)
469         return 1;
470
471     currext->parsed = 1;
472
473     if (idx < OSSL_NELEM(ext_defs)) {
474         /* We are handling a built-in extension */
475         const EXTENSION_DEFINITION *extdef = &ext_defs[idx];
476
477         /* Check if extension is defined for our protocol. If not, skip */
478         if (!extension_is_relevant(s, extdef->context, context))
479             return 1;
480
481         parser = s->server ? extdef->parse_ctos : extdef->parse_stoc;
482
483         if (parser != NULL)
484             return parser(s, &currext->data, x, chainidx, al);
485
486         /*
487          * If the parser is NULL we fall through to the custom extension
488          * processing
489          */
490     }
491
492     /*
493      * This is a custom extension. We only allow this if it is a non
494      * resumed session on the server side.
495      *chain
496      * TODO(TLS1.3): We only allow old style <=TLS1.2 custom extensions.
497      * We're going to need a new mechanism for TLS1.3 to specify which
498      * messages to add the custom extensions to.
499      */
500     if ((!s->hit || !s->server)
501             && (context
502                 & (EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO)) != 0
503             && custom_ext_parse(s, s->server, currext->type,
504                                 PACKET_data(&currext->data),
505                                 PACKET_remaining(&currext->data),
506                                 al) <= 0)
507         return 0;
508
509     return 1;
510 }
511
512 /*
513  * Parse all remaining extensions that have not yet been parsed. Also calls the
514  * finalisation for all extensions at the end, whether we collected them or not.
515  * Returns 1 for success or 0 for failure. If we are working on a Certificate
516  * message then we also pass the Certificate |x| and its position in the
517  * |chainidx|, with 0 being the first certificate. On failure, |*al| is
518  * populated with a suitable alert code.
519  */
520 int tls_parse_all_extensions(SSL *s, int context, RAW_EXTENSION *exts, X509 *x,
521                              size_t chainidx, int *al)
522 {
523     size_t i, numexts = OSSL_NELEM(ext_defs);
524     const EXTENSION_DEFINITION *thisexd;
525
526     /* Calculate the number of extensions in the extensions list */
527     if ((context & EXT_CLIENT_HELLO) != 0) {
528         numexts += s->cert->srv_ext.meths_count;
529     } else if ((context & EXT_TLS1_2_SERVER_HELLO) != 0) {
530         numexts += s->cert->cli_ext.meths_count;
531     }
532
533     /* Parse each extension in turn */
534     for (i = 0; i < numexts; i++) {
535         if (!tls_parse_extension(s, i, context, exts, x, chainidx, al))
536             return 0;
537     }
538
539     /*
540      * Finalise all known extensions relevant to this context, whether we have
541      * found them or not
542      */
543     for (i = 0, thisexd = ext_defs; i < OSSL_NELEM(ext_defs); i++, thisexd++) {
544         if(thisexd->final != NULL
545                 && (thisexd->context & context) != 0
546                 && !thisexd->final(s, context, exts[i].present, al))
547             return 0;
548     }
549
550     return 1;
551 }
552
553 /*
554  * Construct all the extensions relevant to the current |context| and write
555  * them to |pkt|. If this is an extension for a Certificate in a Certificate
556  * message, then |x| will be set to the Certificate we are handling, and
557  * |chainidx| will indicate the position in the chainidx we are processing (with
558  * 0 being the first in the chain). Returns 1 on success or 0 on failure. If a
559  * failure occurs then |al| is populated with a suitable alert code. On a
560  * failure construction stops at the first extension to fail to construct.
561  */
562 int tls_construct_extensions(SSL *s, WPACKET *pkt, unsigned int context,
563                              X509 *x, size_t chainidx, int *al)
564 {
565     size_t i;
566     int addcustom = 0, min_version, max_version = 0, reason, tmpal;
567     const EXTENSION_DEFINITION *thisexd;
568
569     /*
570      * Normally if something goes wrong during construction it's an internal
571      * error. We can always override this later.
572      */
573     tmpal = SSL_AD_INTERNAL_ERROR;
574
575     if (!WPACKET_start_sub_packet_u16(pkt)
576                /*
577                 * If extensions are of zero length then we don't even add the
578                 * extensions length bytes to a ClientHello/ServerHello in SSLv3
579                 */
580             || ((context & (EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO)) != 0
581                && s->version == SSL3_VERSION
582                && !WPACKET_set_flags(pkt,
583                                      WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH))) {
584         SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, ERR_R_INTERNAL_ERROR);
585         goto err;
586     }
587
588     if ((context & EXT_CLIENT_HELLO) != 0) {
589         reason = ssl_get_client_min_max_version(s, &min_version, &max_version);
590         if (reason != 0) {
591             SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, reason);
592             goto err;
593         }
594     }
595
596     /* Add custom extensions first */
597     if ((context & EXT_CLIENT_HELLO) != 0) {
598         custom_ext_init(&s->cert->cli_ext);
599         addcustom = 1;
600     } else if ((context & EXT_TLS1_2_SERVER_HELLO) != 0) {
601         /*
602          * We already initialised the custom extensions during ClientHello
603          * parsing.
604          *
605          * TODO(TLS1.3): We're going to need a new custom extension mechanism
606          * for TLS1.3, so that custom extensions can specify which of the
607          * multiple message they wish to add themselves to.
608          */
609         addcustom = 1;
610     }
611
612     if (addcustom && !custom_ext_add(s, s->server, pkt, &tmpal)) {
613         SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, ERR_R_INTERNAL_ERROR);
614         goto err;
615     }
616
617     for (i = 0, thisexd = ext_defs; i < OSSL_NELEM(ext_defs); i++, thisexd++) {
618         int (*construct)(SSL *s, WPACKET *pkt, X509 *x, size_t chainidx,
619                          int *al);
620
621         /* Skip if not relevant for our context */
622         if ((thisexd->context & context) == 0)
623             continue;
624
625         construct = s->server ? thisexd->construct_stoc
626                               : thisexd->construct_ctos;
627
628         /* Check if this extension is defined for our protocol. If not, skip */
629         if ((SSL_IS_DTLS(s)
630                     && (thisexd->context & EXT_TLS_IMPLEMENTATION_ONLY)
631                        != 0)
632                 || (s->version == SSL3_VERSION
633                         && (thisexd->context & EXT_SSL3_ALLOWED) == 0)
634                 || (SSL_IS_TLS13(s)
635                     && (thisexd->context & EXT_TLS1_2_AND_BELOW_ONLY)
636                        != 0)
637                 || (!SSL_IS_TLS13(s)
638                     && (thisexd->context & EXT_TLS1_3_ONLY) != 0
639                     && (context & EXT_CLIENT_HELLO) == 0)
640                 || ((thisexd->context & EXT_TLS1_3_ONLY) != 0
641                     && (context & EXT_CLIENT_HELLO) != 0
642                     && (SSL_IS_DTLS(s) || max_version < TLS1_3_VERSION))
643                 || construct == NULL)
644             continue;
645
646         if (!construct(s, pkt, x, chainidx, &tmpal))
647             goto err;
648     }
649
650     if (!WPACKET_close(pkt)) {
651         SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, ERR_R_INTERNAL_ERROR);
652         goto err;
653     }
654
655     return 1;
656
657  err:
658     *al = tmpal;
659     return 0;
660 }
661
662 /*
663  * Built in extension finalisation and initialisation functions. All initialise
664  * or finalise the associated extension type for the given |context|. For
665  * finalisers |sent| is set to 1 if we saw the extension during parsing, and 0
666  * otherwise. These functions return 1 on success or 0 on failure. In the event
667  * of a failure then |*al| is populated with a suitable error code.
668  */
669
670 static int final_renegotiate(SSL *s, unsigned int context, int sent,
671                                      int *al)
672 {
673     if (!s->server) {
674         /*
675          * Check if we can connect to a server that doesn't support safe
676          * renegotiation
677          */
678         if (!(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
679                 && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
680                 && !sent) {
681             *al = SSL_AD_HANDSHAKE_FAILURE;
682             SSLerr(SSL_F_FINAL_RENEGOTIATE,
683                    SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
684             return 0;
685         }
686
687         return 1;
688     }
689
690     /* Need RI if renegotiating */
691     if (s->renegotiate
692             && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
693             && !sent) {
694         *al = SSL_AD_HANDSHAKE_FAILURE;
695         SSLerr(SSL_F_FINAL_RENEGOTIATE,
696                SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
697         return 0;
698     }
699
700
701     return 1;
702 }
703
704 static int init_server_name(SSL *s, unsigned int context)
705 {
706     if (s->server)
707         s->servername_done = 0;
708
709     return 1;
710 }
711
712 static int final_server_name(SSL *s, unsigned int context, int sent,
713                                      int *al)
714 {
715     int ret = SSL_TLSEXT_ERR_NOACK;
716     int altmp = SSL_AD_UNRECOGNIZED_NAME;
717
718     if (s->ctx != NULL && s->ctx->ext.servername_cb != 0)
719         ret = s->ctx->ext.servername_cb(s, &altmp,
720                                         s->ctx->ext.servername_arg);
721     else if (s->initial_ctx != NULL
722              && s->initial_ctx->ext.servername_cb != 0)
723         ret = s->initial_ctx->ext.servername_cb(s, &altmp,
724                                        s->initial_ctx->ext.servername_arg);
725
726     switch (ret) {
727     case SSL_TLSEXT_ERR_ALERT_FATAL:
728         *al = altmp;
729         return 0;
730
731     case SSL_TLSEXT_ERR_ALERT_WARNING:
732         *al = altmp;
733         return 1;
734
735     case SSL_TLSEXT_ERR_NOACK:
736         s->servername_done = 0;
737         return 1;
738
739     default:
740         return 1;
741     }
742 }
743
744 #ifndef OPENSSL_NO_EC
745 static int final_ec_pt_formats(SSL *s, unsigned int context, int sent,
746                                        int *al)
747 {
748     unsigned long alg_k, alg_a;
749
750     if (s->server)
751         return 1;
752
753     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
754     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
755
756     /*
757      * If we are client and using an elliptic curve cryptography cipher
758      * suite, then if server returns an EC point formats lists extension it
759      * must contain uncompressed.
760      */
761     if (s->ext.ecpointformats != NULL
762             && s->ext.ecpointformats_len > 0
763             && s->session->ext.ecpointformats != NULL
764             && s->session->ext.ecpointformats_len > 0
765             && ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA))) {
766         /* we are using an ECC cipher */
767         size_t i;
768         unsigned char *list = s->session->ext.ecpointformats;
769
770         for (i = 0; i < s->session->ext.ecpointformats_len; i++) {
771             if (*list++ == TLSEXT_ECPOINTFORMAT_uncompressed)
772                 break;
773         }
774         if (i == s->session->ext.ecpointformats_len) {
775             SSLerr(SSL_F_FINAL_EC_PT_FORMATS,
776                    SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
777             return 0;
778         }
779     }
780
781     return 1;
782 }
783 #endif
784
785 static int init_session_ticket(SSL *s, unsigned int context)
786 {
787     if (!s->server)
788         s->ext.ticket_expected = 0;
789
790     return 1;
791 }
792
793 #ifndef OPENSSL_NO_OCSP
794 static int init_status_request(SSL *s, unsigned int context)
795 {
796     if (s->server) {
797         s->ext.status_type = TLSEXT_STATUSTYPE_nothing;
798     } else {
799         /*
800          * Ensure we get sensible values passed to tlsext_status_cb in the event
801          * that we don't receive a status message
802          */
803         OPENSSL_free(s->ext.ocsp.resp);
804         s->ext.ocsp.resp = NULL;
805         s->ext.ocsp.resp_len = 0;
806     }
807
808     return 1;
809 }
810 #endif
811
812 #ifndef OPENSSL_NO_NEXTPROTONEG
813 static int init_npn(SSL *s, unsigned int context)
814 {
815     s->s3->npn_seen = 0;
816
817     return 1;
818 }
819 #endif
820
821 static int init_alpn(SSL *s, unsigned int context)
822 {
823     OPENSSL_free(s->s3->alpn_selected);
824     s->s3->alpn_selected = NULL;
825     if (s->server) {
826         s->s3->alpn_selected_len = 0;
827         OPENSSL_free(s->s3->alpn_proposed);
828         s->s3->alpn_proposed = NULL;
829         s->s3->alpn_proposed_len = 0;
830     }
831     return 1;
832 }
833
834 static int final_alpn(SSL *s, unsigned int context, int sent, int *al)
835 {
836     const unsigned char *selected = NULL;
837     unsigned char selected_len = 0;
838
839     if (!s->server)
840         return 1;
841
842     if (s->ctx->ext.alpn_select_cb != NULL && s->s3->alpn_proposed != NULL) {
843         int r = s->ctx->ext.alpn_select_cb(s, &selected, &selected_len,
844                                            s->s3->alpn_proposed,
845                                            (unsigned int)s->s3->alpn_proposed_len,
846                                            s->ctx->ext.alpn_select_cb_arg);
847
848         if (r == SSL_TLSEXT_ERR_OK) {
849             OPENSSL_free(s->s3->alpn_selected);
850             s->s3->alpn_selected = OPENSSL_memdup(selected, selected_len);
851             if (s->s3->alpn_selected == NULL) {
852                 *al = SSL_AD_INTERNAL_ERROR;
853                 return 0;
854             }
855             s->s3->alpn_selected_len = selected_len;
856 #ifndef OPENSSL_NO_NEXTPROTONEG
857             /* ALPN takes precedence over NPN. */
858             s->s3->npn_seen = 0;
859 #endif
860         } else {
861             *al = SSL_AD_NO_APPLICATION_PROTOCOL;
862             return 0;
863         }
864     }
865
866     return 1;
867 }
868
869 static int init_sig_algs(SSL *s, unsigned int context)
870 {
871     /* Clear any signature algorithms extension received */
872     OPENSSL_free(s->s3->tmp.peer_sigalgs);
873     s->s3->tmp.peer_sigalgs = NULL;
874
875     return 1;
876 }
877
878 #ifndef OPENSSL_NO_SRP
879 static int init_srp(SSL *s, unsigned int context)
880 {
881     OPENSSL_free(s->srp_ctx.login);
882     s->srp_ctx.login = NULL;
883
884     return 1;
885 }
886 #endif
887
888 static int init_etm(SSL *s, unsigned int context)
889 {
890     s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;
891
892     return 1;
893 }
894
895 static int init_ems(SSL *s, unsigned int context)
896 {
897     if (!s->server)
898         s->s3->flags &= ~TLS1_FLAGS_RECEIVED_EXTMS;
899
900     return 1;
901 }
902
903 static int final_ems(SSL *s, unsigned int context, int sent, int *al)
904 {
905     if (!s->server && s->hit) {
906         /*
907          * Check extended master secret extension is consistent with
908          * original session.
909          */
910         if (!(s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS) !=
911             !(s->session->flags & SSL_SESS_FLAG_EXTMS)) {
912             *al = SSL_AD_HANDSHAKE_FAILURE;
913             SSLerr(SSL_F_FINAL_EMS, SSL_R_INCONSISTENT_EXTMS);
914             return 0;
915         }
916     }
917
918     return 1;
919 }
920
921 #ifndef OPENSSL_NO_SRTP
922 static int init_srtp(SSL *s, unsigned int context)
923 {
924     if (s->server)
925         s->srtp_profile = NULL;
926
927     return 1;
928 }
929 #endif
930
931 static int final_sig_algs(SSL *s, unsigned int context, int sent, int *al)
932 {
933     if (!sent && SSL_IS_TLS13(s)) {
934         *al = TLS13_AD_MISSING_EXTENSION;
935         SSLerr(SSL_F_FINAL_SIG_ALGS, SSL_R_MISSING_SIGALGS_EXTENSION);
936         return 0;
937     }
938
939     return 1;
940 }