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