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