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