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