Avoid repeatedly scanning the list of extensions
[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 tls_ext_final_renegotiate(SSL *s, unsigned int context, int sent,
14                                      int *al);
15 static int tls_ext_init_server_name(SSL *s, unsigned int context);
16 static int tls_ext_final_server_name(SSL *s, unsigned int context, int sent,
17                                      int *al);
18 static int tls_ext_init_status_request(SSL *s, unsigned int context);
19 #ifndef OPENSSL_NO_NEXTPROTONEG
20 static int tls_ext_init_npn(SSL *s, unsigned int context);
21 #endif
22 static int tls_ext_init_alpn(SSL *s, unsigned int context);
23 static int tls_ext_final_alpn(SSL *s, unsigned int context, int sent, int *al);
24 static int tls_ext_init_sig_algs(SSL *s, unsigned int context);
25 #ifndef OPENSSL_NO_SRP
26 static int tls_ext_init_srp(SSL *s, unsigned int context);
27 #endif
28 static int tls_ext_init_etm(SSL *s, unsigned int context);
29 #ifndef OPENSSL_NO_SRTP
30 static int tls_ext_init_srtp(SSL *s, unsigned int context);
31 #endif
32
33 /* Structure to define a built-in extension */
34 typedef struct {
35     /* The ID for the extension */
36     unsigned int type;
37     /*
38      * Initialise extension before parsing. Always called for relevant contexts
39      * even if extension not present
40      */
41     int (*init_ext)(SSL *s, unsigned int context);
42     /* Parse extension received by server from client */
43     int (*parse_client_ext)(SSL *s, PACKET *pkt, int *al);
44     /* Parse extension received by client from server */
45     int (*parse_server_ext)(SSL *s, PACKET *pkt, int *al);
46     /* Construct extension sent by server */
47     int (*construct_server_ext)(SSL *s, WPACKET *pkt, int *al);
48     /* Construct extension sent by client */
49     int (*construct_client_ext)(SSL *s, WPACKET *pkt, int *al);
50     /*
51      * Finalise extension after parsing. Always called where an extensions was
52      * initialised even if the extension was not present. |sent| is set to 1 if
53      * the extension was seen, or 0 otherwise.
54      */
55     int (*finalise_ext)(SSL *s, unsigned int context, int sent, int *al);
56     unsigned int context;
57 } EXTENSION_DEFINITION;
58
59 /*
60  * Definitions of all built-in extensions. NOTE: Changes in the number or order
61  * of these extensions should be mirrored with equivalent changes to the indexes
62  * defined in statem_locl.h.
63  * Each extension has an initialiser, a client and
64  * server side parser and a finaliser. The initialiser is called (if the
65  * extension is relevant to the given context) even if we did not see the
66  * extension in the message that we received. The parser functions are only
67  * called if we see the extension in the message. The finalisers are always
68  * called if the initialiser was called.
69  * There are also server and client side constructor functions which are always
70  * called during message construction if the extension is relevant for the
71  * given context.
72  * The initialisation, parsing, finalisation and construction functions are
73  * always called in the order defined in this list. Some extensions may depend
74  * on others having been processed first, so the order of this list is
75  * significant.
76  * The extension context is defined by a series of flags which specify which
77  * messages the extension is relevant to. These flags also specify whether the
78  * extension is relevant to a paricular protocol or protocol version.
79  * 
80  * TODO(TLS1.3): Make sure we have a test to check the consistency of these
81  */
82 static const EXTENSION_DEFINITION ext_defs[] = {
83     {
84         TLSEXT_TYPE_renegotiate,
85         NULL,
86         tls_parse_client_renegotiate,
87         tls_parse_server_renegotiate,
88         tls_construct_server_renegotiate,
89         tls_construct_client_renegotiate,
90         tls_ext_final_renegotiate,
91         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_SSL3_ALLOWED
92         | EXT_TLS1_2_AND_BELOW_ONLY
93     },
94     {
95         TLSEXT_TYPE_server_name,
96         tls_ext_init_server_name,
97         tls_parse_client_server_name,
98         tls_parse_server_server_name,
99         tls_construct_server_server_name,
100         tls_construct_client_server_name,
101         tls_ext_final_server_name,
102         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
103         | EXT_TLS1_3_ENCRYPTED_EXTENSIONS
104     },
105 #ifndef OPENSSL_NO_SRP
106     {
107         TLSEXT_TYPE_srp,
108         tls_ext_init_srp,
109         tls_parse_client_srp,
110         NULL,
111         NULL,
112         tls_construct_client_srp,
113         NULL,
114         EXT_CLIENT_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
115     },
116 #endif
117 #ifndef OPENSSL_NO_EC
118     {
119         TLSEXT_TYPE_ec_point_formats,
120         NULL,
121         tls_parse_client_ec_pt_formats,
122         tls_parse_server_ec_pt_formats,
123         tls_construct_server_ec_pt_formats,
124         tls_construct_client_ec_pt_formats,
125         NULL,
126         EXT_CLIENT_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
127     },
128     {
129         TLSEXT_TYPE_supported_groups,
130         NULL,
131         tls_parse_client_supported_groups,
132         NULL,
133         NULL /* TODO(TLS1.3): Need to add this */,
134         tls_construct_client_supported_groups,
135         NULL,
136         EXT_CLIENT_HELLO | EXT_TLS1_3_ENCRYPTED_EXTENSIONS
137     },
138 #endif
139     {
140         TLSEXT_TYPE_session_ticket,
141         NULL,
142         tls_parse_client_session_ticket,
143         tls_parse_server_session_ticket,
144         tls_construct_server_session_ticket,
145         tls_construct_client_session_ticket,
146         NULL,
147         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
148     },
149     {
150         TLSEXT_TYPE_signature_algorithms,
151         tls_ext_init_sig_algs,
152         tls_parse_client_sig_algs,
153         NULL,
154         NULL,
155         tls_construct_client_sig_algs,
156         NULL,
157         EXT_CLIENT_HELLO
158     },
159 #ifndef OPENSSL_NO_OCSP
160     {
161         TLSEXT_TYPE_status_request,
162         tls_ext_init_status_request,
163         tls_parse_client_status_request,
164         tls_parse_server_status_request,
165         tls_construct_server_status_request,
166         tls_construct_client_status_request,
167         NULL,
168         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
169         | EXT_TLS1_3_CERTIFICATE
170     },
171 #endif
172 #ifndef OPENSSL_NO_NEXTPROTONEG
173     {
174         TLSEXT_TYPE_next_proto_neg,
175         tls_ext_init_npn,
176         tls_parse_client_npn,
177         tls_parse_server_npn,
178         tls_construct_server_next_proto_neg,
179         tls_construct_client_npn,
180         NULL,
181         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
182     },
183 #endif
184     {
185         /*
186          * Must appear in this list after server_name so that finalisation
187          * happens after server_name callbacks
188          */
189         TLSEXT_TYPE_application_layer_protocol_negotiation,
190         tls_ext_init_alpn,
191         tls_parse_client_alpn,
192         tls_parse_server_alpn,
193         tls_construct_server_alpn,
194         tls_construct_client_alpn,
195         tls_ext_final_alpn,
196         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
197         | EXT_TLS1_3_ENCRYPTED_EXTENSIONS
198     },
199 #ifndef OPENSSL_NO_SRTP
200     {
201         TLSEXT_TYPE_use_srtp,
202         tls_ext_init_srtp,
203         tls_parse_client_use_srtp,
204         tls_parse_server_use_srtp,
205         tls_construct_server_use_srtp,
206         tls_construct_client_use_srtp,
207         NULL,
208         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
209         | EXT_TLS1_3_ENCRYPTED_EXTENSIONS | EXT_DTLS_ONLY
210     },
211 #endif
212     {
213         TLSEXT_TYPE_encrypt_then_mac,
214         tls_ext_init_etm,
215         tls_parse_client_etm,
216         tls_parse_server_etm,
217         tls_construct_server_etm,
218         tls_construct_client_etm,
219         NULL,
220         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
221     },
222 #ifndef OPENSSL_NO_CT
223     {
224         TLSEXT_TYPE_signed_certificate_timestamp,
225         NULL,
226         /*
227          * No server side support for this, but can be provided by a custom
228          * extension. This is an exception to the rule that custom extensions
229          * cannot override built in ones.
230          */
231         NULL,
232         tls_parse_server_sct,
233         NULL,
234         tls_construct_client_sct,
235         NULL,
236         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
237         | EXT_TLS1_3_CERTIFICATE
238     },
239 #endif
240     {
241         TLSEXT_TYPE_extended_master_secret,
242         NULL,
243         tls_parse_client_ems,
244         tls_parse_server_ems,
245         tls_construct_server_ems,
246         tls_construct_client_ems,
247         NULL,
248         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
249     },
250     {
251         TLSEXT_TYPE_supported_versions,
252         NULL,
253         /* Processed inline as part of version selection */
254         NULL,
255         NULL,
256         NULL,
257         tls_construct_client_supported_versions,
258         NULL,
259         EXT_CLIENT_HELLO | EXT_TLS_IMPLEMENTATION_ONLY | EXT_TLS1_3_ONLY
260     },
261     {
262         /*
263          * Must be in this list after supported_groups. We need that to have
264          * been parsed before we do this one.
265          */
266         TLSEXT_TYPE_key_share,
267         NULL,
268         tls_parse_client_key_share,
269         tls_parse_server_key_share,
270         tls_construct_server_key_share,
271         tls_construct_client_key_share,
272         NULL,
273         EXT_CLIENT_HELLO | EXT_TLS1_3_SERVER_HELLO
274         | EXT_TLS1_3_HELLO_RETRY_REQUEST | EXT_TLS_IMPLEMENTATION_ONLY
275         | EXT_TLS1_3_ONLY
276     },
277     {
278         /*
279          * Special unsolicited ServerHello extension only used when
280          * SSL_OP_CRYPTOPRO_TLSEXT_BUG is set
281          */
282         TLSEXT_TYPE_cryptopro_bug,
283         NULL,
284         NULL,
285         NULL,
286         tls_construct_server_cryptopro_bug,
287         NULL,
288         NULL,
289         EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
290     },
291     {
292         /* Last in the list because it must be added as the last extension */
293         TLSEXT_TYPE_padding,
294         NULL,
295         /* We send this, but don't read it */
296         NULL,
297         NULL,
298         NULL,
299         tls_construct_client_padding,
300         NULL,
301         EXT_CLIENT_HELLO
302     }
303 };
304
305 /*
306  * Verify whether we are allowed to use the extension |type| in the current
307  * |context|. Returns 1 to indicate the extension is allowed or unknown or 0 to
308  * indicate the extension is not allowed. If returning 1 then |*found| is set to
309  * 1 if we found a definition for the extension, and |*idx| is set to its index
310  */
311 static int verify_extension(SSL *s, unsigned int context, unsigned int type,
312                             custom_ext_methods *meths, int *found, size_t *idx)
313 {
314     size_t i;
315     size_t builtin_num = OSSL_NELEM(ext_defs);
316
317     for (i = 0; i < builtin_num; i++) {
318         if (type == ext_defs[i].type) {
319             /* Check we're allowed to use this extension in this context */
320             if ((context & ext_defs[i].context) == 0)
321                 return 0;
322
323             if (SSL_IS_DTLS(s)) {
324                 if ((ext_defs[i].context & EXT_TLS_ONLY) != 0)
325                     return 0;
326             } else if ((ext_defs[i].context & EXT_DTLS_ONLY) != 0) {
327                     return 0;
328             }
329
330             *found = 1;
331             *idx = i;
332             return 1;
333         }
334     }
335
336     if ((context & (EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO)) == 0) {
337         /*
338          * Custom extensions only apply to <=TLS1.2. This extension is unknown
339          * in this context - we allow it
340          */
341         *found = 0;
342         return 1;
343     }
344
345     /* Check the custom extensions */
346     if (meths != NULL) {
347         for (i = builtin_num; i < builtin_num + meths->meths_count; i++) {
348             if (meths->meths[i - builtin_num].ext_type == type) {
349                 *found = 1;
350                 *idx = i;
351                 return 1;
352             }
353         }
354     }
355
356     /* Unknown extension. We allow it */
357     *found = 0;
358     return 1;
359 }
360
361 /*
362  * Check whether the context defined for an extension |extctx| means whether
363  * the extension is relevant for the current context |thisctx| or not. Returns
364  * 1 if the extension is relevant for this context, and 0 otherwise
365  */
366 static int extension_is_relevant(SSL *s, unsigned int extctx,
367                                  unsigned int thisctx)
368 {
369     if ((SSL_IS_DTLS(s)
370                 && (extctx & EXT_TLS_IMPLEMENTATION_ONLY) != 0)
371             || (s->version == SSL3_VERSION
372                     && (extctx & EXT_SSL3_ALLOWED) == 0)
373             || (SSL_IS_TLS13(s)
374                 && (extctx & EXT_TLS1_2_AND_BELOW_ONLY) != 0)
375             || (!SSL_IS_TLS13(s) && (extctx & EXT_TLS1_3_ONLY) != 0))
376         return 0;
377
378     return 1;
379 }
380
381 /*
382  * Gather a list of all the extensions from the data in |packet]. |context|
383  * tells us which message this extension is for. The raw extension data is
384  * stored in |*res|. In the event of an error the alert type to use is stored in
385  * |*al|. We don't actually process the content of the extensions yet, except to
386  * check their types. This function also runs the initialiser functions for all
387  * known extensions (whether we have collected them or not).
388  *
389  * Per http://tools.ietf.org/html/rfc5246#section-7.4.1.4, there may not be
390  * more than one extension of the same type in a ClientHello or ServerHello.
391  * This function returns 1 if all extensions are unique and we have parsed their
392  * types, and 0 if the extensions contain duplicates, could not be successfully
393  * collected, or an internal error occurred. We only check duplicates for
394  * extensions that we know about. We ignore others.
395  */
396 int tls_collect_extensions(SSL *s, PACKET *packet, unsigned int context,
397                            RAW_EXTENSION **res, int *al)
398 {
399     PACKET extensions = *packet;
400     size_t i = 0, idx;
401     int found = 0;
402     custom_ext_methods *exts = NULL;
403     RAW_EXTENSION *raw_extensions = NULL;
404
405     /*
406      * Initialise server side custom extensions. Client side is done during
407      * construction of extensions for the ClientHello.
408      */
409     if ((context & EXT_CLIENT_HELLO) != 0) {
410         exts = &s->cert->srv_ext;
411         custom_ext_init(&s->cert->srv_ext);
412     } else if ((context & EXT_TLS1_2_SERVER_HELLO) != 0) {
413         exts = &s->cert->cli_ext;
414     }
415
416     raw_extensions = OPENSSL_zalloc((OSSL_NELEM(ext_defs)
417                                      + (exts != NULL ? exts->meths_count : 0))
418                                      * sizeof(RAW_EXTENSION));
419     if (raw_extensions == NULL) {
420         *al = SSL_AD_INTERNAL_ERROR;
421         SSLerr(SSL_F_TLS_COLLECT_EXTENSIONS, ERR_R_MALLOC_FAILURE);
422         return 0;
423     }
424
425     while (PACKET_remaining(&extensions) > 0) {
426         unsigned int type;
427         PACKET extension;
428
429         if (!PACKET_get_net_2(&extensions, &type) ||
430             !PACKET_get_length_prefixed_2(&extensions, &extension)) {
431             SSLerr(SSL_F_TLS_COLLECT_EXTENSIONS, SSL_R_BAD_EXTENSION);
432             *al = SSL_AD_DECODE_ERROR;
433             goto err;
434         }
435         /*
436          * Verify this extension is allowed. We only check duplicates for
437          * extensions that we recognise.
438          */
439         if (!verify_extension(s, context, type, exts, &found, &idx)
440                 || (found == 1
441                     && raw_extensions[idx].present == 1)) {
442             SSLerr(SSL_F_TLS_COLLECT_EXTENSIONS, SSL_R_BAD_EXTENSION);
443             *al = SSL_AD_ILLEGAL_PARAMETER;
444             goto err;
445         }
446         if (found) {
447             raw_extensions[idx].data = extension;
448             raw_extensions[idx].present = 1;
449             raw_extensions[idx].type = type;
450         }
451     }
452
453     /*
454      * Initialise all known extensions relevant to this context, whether we have
455      * found them or not
456      */
457     for (i = 0; i < OSSL_NELEM(ext_defs); i++) {
458         if(ext_defs[i].init_ext != NULL && (ext_defs[i].context & context) != 0
459                 && extension_is_relevant(s, ext_defs[i].context, context)
460                 && !ext_defs[i].init_ext(s, context)) {
461             *al = SSL_AD_INTERNAL_ERROR;
462             goto err;
463         }
464     }
465
466     *res = raw_extensions;
467     return 1;
468
469  err:
470     OPENSSL_free(raw_extensions);
471     return 0;
472 }
473
474 /*
475  * Runs the parser for a given extension with index |idx|. |exts| contains the
476  * list of all parsed extensions previously collected by
477  * tls_collect_extensions(). The parser is only run if it is applicable for the
478  * given |context| and the parser has not already been run. Returns 1 on success
479  * or 0 on failure. In the event of a failure |*al| is populated with a suitable
480  * alert code. If an extension is not present this counted as success.
481  */
482 int tls_parse_extension(SSL *s, unsigned int idx, int context,
483                         RAW_EXTENSION *exts, int *al)
484 {
485     RAW_EXTENSION *currext = &exts[idx];
486     int (*parser)(SSL *s, PACKET *pkt, int *al) = NULL;
487
488     /* Skip if the extension is not present */
489     if (!currext->present)
490         return 1;
491
492     if (s->tlsext_debug_cb)
493         s->tlsext_debug_cb(s, !s->server, currext->type,
494                            PACKET_data(&currext->data),
495                            PACKET_remaining(&currext->data),
496                            s->tlsext_debug_arg);
497
498     /* Skip if we've already parsed this extension */
499     if (currext->parsed)
500         return 1;
501
502     currext->parsed = 1;
503
504     if (idx < OSSL_NELEM(ext_defs)) {
505         /* We are handling a built-in extension */
506         const EXTENSION_DEFINITION *extdef = &ext_defs[idx];
507
508         /* Check if extension is defined for our protocol. If not, skip */
509         if (!extension_is_relevant(s, extdef->context, context))
510             return 1;
511
512         parser = s->server ? extdef->parse_client_ext : extdef->parse_server_ext;
513
514         if (parser != NULL) {
515             if (!parser(s, &currext->data, al))
516                 return 0;
517
518             return 1;
519         }
520
521         /*
522          * If the parser is NULL we fall through to the custom extension
523          * processing
524          */
525     }
526
527     /*
528      * This is a custom extension. We only allow this if it is a non
529      * resumed session on the server side.
530      *
531      * TODO(TLS1.3): We only allow old style <=TLS1.2 custom extensions.
532      * We're going to need a new mechanism for TLS1.3 to specify which
533      * messages to add the custom extensions to.
534      */
535     if ((!s->hit || !s->server)
536             && (context
537                 & (EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO)) != 0
538             && custom_ext_parse(s, s->server, currext->type,
539                                 PACKET_data(&currext->data),
540                                 PACKET_remaining(&currext->data),
541                                 al) <= 0)
542         return 0;
543
544     return 1;
545 }
546
547 /*
548  * Parse all remaining extensions that have not yet been parsed. Also calls the
549  * finalisation for all extensions at the end, whether we collected them or not.
550  * Returns 1 for success or 0 for failure. On failure, |*al| is populated with a
551  * suitable alert code.
552  */
553 int tls_parse_all_extensions(SSL *s, int context, RAW_EXTENSION *exts, int *al)
554 {
555     size_t loop, numexts = OSSL_NELEM(ext_defs);
556
557     /* Calculate the number of extensions in the extensions list */
558     if ((context & EXT_CLIENT_HELLO) != 0) {
559         numexts += s->cert->srv_ext.meths_count;
560     } else if ((context & EXT_TLS1_2_SERVER_HELLO) != 0) {
561         numexts += s->cert->cli_ext.meths_count;
562     }
563
564     /* Parse each extension in turn */
565     for (loop = 0; loop < numexts; loop++) {
566         if (!tls_parse_extension(s, loop, context, exts, al))
567             return 0;
568     }
569
570     /*
571      * Finalise all known extensions relevant to this context, whether we have
572      * found them or not
573      */
574     for (loop = 0; loop < OSSL_NELEM(ext_defs); loop++) {
575         if(ext_defs[loop].finalise_ext != NULL
576                 && (ext_defs[loop].context & context) != 0
577                 && !ext_defs[loop].finalise_ext(s, context, exts[loop].present,
578                                                 al))
579             return 0;
580     }
581
582     return 1;
583 }
584
585 /*
586  * Construct all the extensions relevant to the current |context| and write
587  * them to |pkt|. Returns 1 on success or 0 on failure. If a failure occurs then
588  * |al| is populated with a suitable alert code.
589  */
590 int tls_construct_extensions(SSL *s, WPACKET *pkt, unsigned int context,
591                              int *al)
592 {
593     size_t loop;
594     int addcustom = 0;
595     int min_version, max_version = 0, reason, tmpal;
596
597     /*
598      * Normally if something goes wrong during construction it's an internal
599      * error. We can always override this later.
600      */
601     tmpal = SSL_AD_INTERNAL_ERROR;
602
603     if (!WPACKET_start_sub_packet_u16(pkt)
604                /*
605                 * If extensions are of zero length then we don't even add the
606                 * extensions length bytes to a ClientHello/ServerHello in SSLv3
607                 */
608             || ((context & (EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO)) != 0
609                && s->version == SSL3_VERSION
610                && !WPACKET_set_flags(pkt,
611                                      WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH))) {
612         SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, ERR_R_INTERNAL_ERROR);
613         goto err;
614     }
615
616     if ((context & EXT_CLIENT_HELLO) != 0) {
617         reason = ssl_get_client_min_max_version(s, &min_version, &max_version);
618         if (reason != 0) {
619             SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, reason);
620             goto err;
621         }
622     }
623
624     /* Add custom extensions first */
625     if ((context & EXT_CLIENT_HELLO) != 0) {
626         custom_ext_init(&s->cert->cli_ext);
627         addcustom = 1;
628     } else if ((context & EXT_TLS1_2_SERVER_HELLO) != 0) {
629         /*
630          * We already initialised the custom extensions during ClientHello
631          * parsing.
632          * 
633          * TODO(TLS1.3): We're going to need a new custom extension mechanism
634          * for TLS1.3, so that custom extensions can specify which of the
635          * multiple message they wish to add themselves to.
636          */
637         addcustom = 1;
638     }
639
640     if (addcustom && !custom_ext_add(s, s->server, pkt, &tmpal)) {
641         SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, ERR_R_INTERNAL_ERROR);
642         goto err;
643     }
644
645     for (loop = 0; loop < OSSL_NELEM(ext_defs); loop++) {
646         int (*construct)(SSL *s, WPACKET *pkt, int *al);
647
648         /* Skip if not relevant for our context */
649         if ((ext_defs[loop].context & context) == 0)
650             continue;
651
652         construct = s->server ? ext_defs[loop].construct_server_ext
653                               : ext_defs[loop].construct_client_ext;
654
655         /* Check if this extension is defined for our protocol. If not, skip */
656         if ((SSL_IS_DTLS(s)
657                     && (ext_defs[loop].context & EXT_TLS_IMPLEMENTATION_ONLY)
658                        != 0)
659                 || (s->version == SSL3_VERSION
660                         && (ext_defs[loop].context & EXT_SSL3_ALLOWED) == 0)
661                 || (SSL_IS_TLS13(s)
662                     && (ext_defs[loop].context & EXT_TLS1_2_AND_BELOW_ONLY)
663                        != 0)
664                 || (!SSL_IS_TLS13(s)
665                     && (ext_defs[loop].context & EXT_TLS1_3_ONLY) != 0
666                     && (context & EXT_CLIENT_HELLO) == 0)
667                 || ((ext_defs[loop].context & EXT_TLS1_3_ONLY) != 0
668                     && (context & EXT_CLIENT_HELLO) != 0
669                     && (SSL_IS_DTLS(s) || max_version < TLS1_3_VERSION))
670                 || construct == NULL)
671             continue;
672
673         if (!construct(s, pkt, &tmpal))
674             goto err;
675     }
676
677     if (!WPACKET_close(pkt)) {
678         SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, ERR_R_INTERNAL_ERROR);
679         goto err;
680     }
681
682     return 1;
683
684  err:
685     *al = tmpal;
686     return 0;
687 }
688
689 /*
690  * Built in extension finalisation and initialisation functions. All initialise
691  * or finalise the associated extension type for the given |context|. For
692  * finalisers |sent| is set to 1 if we saw the extension during parsing, and 0
693  * otherwise. These functions return 1 on success or 0 on failure. In the event
694  * of a failure then |*al| is populated with a suitable error code.
695  */
696
697 static int tls_ext_final_renegotiate(SSL *s, unsigned int context, int sent,
698                                      int *al)
699 {
700     if (!s->server)
701         return 1;
702
703     /* Need RI if renegotiating */
704     if (s->renegotiate
705             && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
706             && !sent) {
707         *al = SSL_AD_HANDSHAKE_FAILURE;
708         SSLerr(SSL_F_TLS_EXT_FINAL_RENEGOTIATE,
709                SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
710         return 0;
711     }
712
713     return 1;
714 }
715
716 static int tls_ext_init_server_name(SSL *s, unsigned int context)
717 {
718     if (s->server)
719         s->servername_done = 0;
720
721     return 1;
722 }
723
724 static int tls_ext_final_server_name(SSL *s, unsigned int context, int sent,
725                                      int *al)
726 {
727     int ret = SSL_TLSEXT_ERR_NOACK;
728     int altmp = SSL_AD_UNRECOGNIZED_NAME;
729
730     if (!s->server)
731         return 1;
732
733     if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0)
734         ret = s->ctx->tlsext_servername_callback(s, &altmp,
735                                                  s->ctx->tlsext_servername_arg);
736     else if (s->initial_ctx != NULL
737              && s->initial_ctx->tlsext_servername_callback != 0)
738         ret = s->initial_ctx->tlsext_servername_callback(s, &altmp,
739                                        s->initial_ctx->tlsext_servername_arg);
740
741     switch (ret) {
742     case SSL_TLSEXT_ERR_ALERT_FATAL:
743         *al = altmp;
744         return 0;
745
746     case SSL_TLSEXT_ERR_ALERT_WARNING:
747         *al = altmp;
748         return 1;
749
750     case SSL_TLSEXT_ERR_NOACK:
751         s->servername_done = 0;
752         return 1;
753
754     default:
755         return 1;
756     }
757 }
758
759 static int tls_ext_init_status_request(SSL *s, unsigned int context)
760 {
761     if (s->server)
762         s->tlsext_status_type = -1;
763
764     return 1;
765 }
766
767 #ifndef OPENSSL_NO_NEXTPROTONEG
768 static int tls_ext_init_npn(SSL *s, unsigned int context)
769 {
770     if (s->server)
771         s->s3->next_proto_neg_seen = 0;
772
773     return 1;
774 }
775 #endif
776
777 static int tls_ext_init_alpn(SSL *s, unsigned int context)
778 {
779     if (s->server) {
780         OPENSSL_free(s->s3->alpn_selected);
781         s->s3->alpn_selected = NULL;
782         s->s3->alpn_selected_len = 0;
783         OPENSSL_free(s->s3->alpn_proposed);
784         s->s3->alpn_proposed = NULL;
785         s->s3->alpn_proposed_len = 0;
786     }
787
788     return 1;
789 }
790
791 static int tls_ext_final_alpn(SSL *s, unsigned int context, int sent, int *al)
792 {
793     const unsigned char *selected = NULL;
794     unsigned char selected_len = 0;
795
796     if (!s->server)
797         return 1;
798
799     if (s->ctx->alpn_select_cb != NULL && s->s3->alpn_proposed != NULL) {
800         int r = s->ctx->alpn_select_cb(s, &selected, &selected_len,
801                                        s->s3->alpn_proposed,
802                                        (unsigned int)s->s3->alpn_proposed_len,
803                                        s->ctx->alpn_select_cb_arg);
804
805         if (r == SSL_TLSEXT_ERR_OK) {
806             OPENSSL_free(s->s3->alpn_selected);
807             s->s3->alpn_selected = OPENSSL_memdup(selected, selected_len);
808             if (s->s3->alpn_selected == NULL) {
809                 *al = SSL_AD_INTERNAL_ERROR;
810                 return 0;
811             }
812             s->s3->alpn_selected_len = selected_len;
813 #ifndef OPENSSL_NO_NEXTPROTONEG
814             /* ALPN takes precedence over NPN. */
815             s->s3->next_proto_neg_seen = 0;
816 #endif
817         } else {
818             *al = SSL_AD_NO_APPLICATION_PROTOCOL;
819             return 0;
820         }
821     }
822
823     return 1;
824 }
825
826 static int tls_ext_init_sig_algs(SSL *s, unsigned int context)
827 {
828     /* Clear any signature algorithms extension received */
829     OPENSSL_free(s->s3->tmp.peer_sigalgs);
830     s->s3->tmp.peer_sigalgs = NULL;
831
832     return 1;
833 }
834
835 #ifndef OPENSSL_NO_SRP
836 static int tls_ext_init_srp(SSL *s, unsigned int context)
837 {
838     OPENSSL_free(s->srp_ctx.login);
839     s->srp_ctx.login = NULL;
840
841     return 1;
842 }
843 #endif
844
845 static int tls_ext_init_etm(SSL *s, unsigned int context)
846 {
847     if (s->server)
848         s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;
849
850     return 1;
851 }
852
853 #ifndef OPENSSL_NO_SRTP
854 static int tls_ext_init_srtp(SSL *s, unsigned int context)
855 {
856     if (s->server)
857         s->srtp_profile = NULL;
858
859     return 1;
860 }
861 #endif