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