Fix a bogus uninit variable warning
[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 static int final_key_share(SSL *s, unsigned int context, int sent, int *al);
40 #ifndef OPENSSL_NO_SRTP
41 static int init_srtp(SSL *s, unsigned int context);
42 #endif
43 static int final_sig_algs(SSL *s, unsigned int context, int sent, int *al);
44
45 /* Structure to define a built-in extension */
46 typedef struct extensions_definition_st {
47     /* The defined type for the extension */
48     unsigned int type;
49     /*
50      * The context that this extension applies to, e.g. what messages and
51      * protocol versions
52      */
53     unsigned int context;
54     /*
55      * Initialise extension before parsing. Always called for relevant contexts
56      * even if extension not present
57      */
58     int (*init)(SSL *s, unsigned int context);
59     /* Parse extension sent from client to server */
60     int (*parse_ctos)(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
61                       size_t chainidx, int *al);
62     /* Parse extension send from server to client */
63     int (*parse_stoc)(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
64                       size_t chainidx, int *al);
65     /* Construct extension sent from server to client */
66     int (*construct_stoc)(SSL *s, WPACKET *pkt, unsigned int context, X509 *x,
67                           size_t chainidx, int *al);
68     /* Construct extension sent from client to server */
69     int (*construct_ctos)(SSL *s, WPACKET *pkt, unsigned int context, X509 *x,
70                           size_t chainidx, int *al);
71     /*
72      * Finalise extension after parsing. Always called where an extensions was
73      * initialised even if the extension was not present. |sent| is set to 1 if
74      * the extension was seen, or 0 otherwise.
75      */
76     int (*final)(SSL *s, unsigned int context, int sent, int *al);
77 } EXTENSION_DEFINITION;
78
79 /*
80  * Definitions of all built-in extensions. NOTE: Changes in the number or order
81  * of these extensions should be mirrored with equivalent changes to the 
82  * indexes ( TLSEXT_IDX_* ) defined in ssl_locl.h.
83  * Each extension has an initialiser, a client and
84  * server side parser and a finaliser. The initialiser is called (if the
85  * extension is relevant to the given context) even if we did not see the
86  * extension in the message that we received. The parser functions are only
87  * called if we see the extension in the message. The finalisers are always
88  * called if the initialiser was called.
89  * There are also server and client side constructor functions which are always
90  * called during message construction if the extension is relevant for the
91  * given context.
92  * The initialisation, parsing, finalisation and construction functions are
93  * always called in the order defined in this list. Some extensions may depend
94  * on others having been processed first, so the order of this list is
95  * significant.
96  * The extension context is defined by a series of flags which specify which
97  * messages the extension is relevant to. These flags also specify whether the
98  * extension is relevant to a particular protocol or protocol version.
99  *
100  * TODO(TLS1.3): Make sure we have a test to check the consistency of these
101  */
102 #define INVALID_EXTENSION { 0x10000, 0, NULL, NULL, NULL, NULL, NULL, NULL }
103 static const EXTENSION_DEFINITION ext_defs[] = {
104     {
105         TLSEXT_TYPE_renegotiate,
106         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_SSL3_ALLOWED
107         | EXT_TLS1_2_AND_BELOW_ONLY,
108         NULL, tls_parse_ctos_renegotiate, tls_parse_stoc_renegotiate,
109         tls_construct_stoc_renegotiate, tls_construct_ctos_renegotiate,
110         final_renegotiate
111     },
112     {
113         TLSEXT_TYPE_server_name,
114         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
115         | EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
116         init_server_name,
117         tls_parse_ctos_server_name, tls_parse_stoc_server_name,
118         tls_construct_stoc_server_name, tls_construct_ctos_server_name,
119         final_server_name
120     },
121 #ifndef OPENSSL_NO_SRP
122     {
123         TLSEXT_TYPE_srp,
124         EXT_CLIENT_HELLO | EXT_TLS1_2_AND_BELOW_ONLY,
125         init_srp, tls_parse_ctos_srp, NULL, NULL, tls_construct_ctos_srp, NULL
126     },
127 #else
128     INVALID_EXTENSION,
129 #endif
130 #ifndef OPENSSL_NO_EC
131     {
132         TLSEXT_TYPE_ec_point_formats,
133         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY,
134         NULL, tls_parse_ctos_ec_pt_formats, tls_parse_stoc_ec_pt_formats,
135         tls_construct_stoc_ec_pt_formats, tls_construct_ctos_ec_pt_formats,
136         final_ec_pt_formats
137     },
138     {
139         TLSEXT_TYPE_supported_groups,
140         EXT_CLIENT_HELLO | EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
141         NULL, tls_parse_ctos_supported_groups, NULL,
142         NULL /* TODO(TLS1.3): Need to add this */,
143         tls_construct_ctos_supported_groups, NULL
144     },
145 #else
146     INVALID_EXTENSION,
147     INVALID_EXTENSION,
148 #endif
149     {
150         TLSEXT_TYPE_session_ticket,
151         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY,
152         init_session_ticket, tls_parse_ctos_session_ticket,
153         tls_parse_stoc_session_ticket, tls_construct_stoc_session_ticket,
154         tls_construct_ctos_session_ticket, NULL
155     },
156     {
157         TLSEXT_TYPE_signature_algorithms,
158         EXT_CLIENT_HELLO,
159         init_sig_algs, tls_parse_ctos_sig_algs, NULL, NULL,
160         tls_construct_ctos_sig_algs, final_sig_algs
161     },
162 #ifndef OPENSSL_NO_OCSP
163     {
164         TLSEXT_TYPE_status_request,
165         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
166         | EXT_TLS1_3_CERTIFICATE,
167         init_status_request, tls_parse_ctos_status_request,
168         tls_parse_stoc_status_request, tls_construct_stoc_status_request,
169         tls_construct_ctos_status_request, NULL
170     },
171 #else
172     INVALID_EXTENSION,
173 #endif
174 #ifndef OPENSSL_NO_NEXTPROTONEG
175     {
176         TLSEXT_TYPE_next_proto_neg,
177         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY,
178         init_npn, tls_parse_ctos_npn, tls_parse_stoc_npn,
179         tls_construct_stoc_next_proto_neg, tls_construct_ctos_npn, NULL
180     },
181 #else
182     INVALID_EXTENSION,
183 #endif
184     {
185         /*
186          * Must appear in this list after server_name so that finalisation
187          * happens after server_name callbacks
188          */
189         TLSEXT_TYPE_application_layer_protocol_negotiation,
190         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
191         | EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
192         init_alpn, tls_parse_ctos_alpn, tls_parse_stoc_alpn,
193         tls_construct_stoc_alpn, tls_construct_ctos_alpn, final_alpn
194     },
195 #ifndef OPENSSL_NO_SRTP
196     {
197         TLSEXT_TYPE_use_srtp,
198         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
199         | EXT_TLS1_3_ENCRYPTED_EXTENSIONS | EXT_DTLS_ONLY,
200         init_srtp, tls_parse_ctos_use_srtp, tls_parse_stoc_use_srtp,
201         tls_construct_stoc_use_srtp, tls_construct_ctos_use_srtp, NULL
202     },
203 #else
204     INVALID_EXTENSION,
205 #endif
206     {
207         TLSEXT_TYPE_encrypt_then_mac,
208         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY,
209         init_etm, tls_parse_ctos_etm, tls_parse_stoc_etm,
210         tls_construct_stoc_etm, tls_construct_ctos_etm, NULL
211     },
212 #ifndef OPENSSL_NO_CT
213     {
214         TLSEXT_TYPE_signed_certificate_timestamp,
215         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
216         | EXT_TLS1_3_CERTIFICATE,
217         NULL,
218         /*
219          * No server side support for this, but can be provided by a custom
220          * extension. This is an exception to the rule that custom extensions
221          * cannot override built in ones.
222          */
223         NULL, tls_parse_stoc_sct, NULL, tls_construct_ctos_sct,  NULL
224     },
225 #else
226     INVALID_EXTENSION,
227 #endif
228     {
229         TLSEXT_TYPE_extended_master_secret,
230         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY,
231         init_ems, tls_parse_ctos_ems, tls_parse_stoc_ems,
232         tls_construct_stoc_ems, tls_construct_ctos_ems, final_ems
233     },
234     {
235         TLSEXT_TYPE_supported_versions,
236         EXT_CLIENT_HELLO | EXT_TLS_IMPLEMENTATION_ONLY | EXT_TLS1_3_ONLY,
237         NULL,
238         /* Processed inline as part of version selection */
239         NULL, NULL, NULL, tls_construct_ctos_supported_versions, NULL
240     },
241     {
242         TLSEXT_TYPE_psk_kex_modes,
243         EXT_CLIENT_HELLO | EXT_TLS_IMPLEMENTATION_ONLY | EXT_TLS1_3_ONLY,
244         init_psk_kex_modes, tls_parse_ctos_psk_kex_modes, NULL, NULL,
245         tls_construct_ctos_psk_kex_modes, NULL
246     },
247     {
248         /*
249          * Must be in this list after supported_groups. We need that to have
250          * been parsed before we do this one.
251          */
252         TLSEXT_TYPE_key_share,
253         EXT_CLIENT_HELLO | EXT_TLS1_3_SERVER_HELLO
254         | EXT_TLS1_3_HELLO_RETRY_REQUEST | EXT_TLS_IMPLEMENTATION_ONLY
255         | EXT_TLS1_3_ONLY,
256         NULL, tls_parse_ctos_key_share, tls_parse_stoc_key_share,
257         tls_construct_stoc_key_share, tls_construct_ctos_key_share,
258         final_key_share
259     },
260     {
261         /*
262          * Special unsolicited ServerHello extension only used when
263          * SSL_OP_CRYPTOPRO_TLSEXT_BUG is set
264          */
265         TLSEXT_TYPE_cryptopro_bug,
266         EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY,
267         NULL, NULL, NULL, tls_construct_stoc_cryptopro_bug, NULL, NULL
268     },
269     {
270         /* Must be immediately before pre_shared_key */
271         /* TODO(TLS1.3): Fix me */
272         TLSEXT_TYPE_padding,
273         EXT_CLIENT_HELLO,
274         NULL,
275         /* We send this, but don't read it */
276         NULL, NULL, NULL, tls_construct_ctos_padding, NULL
277     },
278     {
279         /* Required by the TLSv1.3 spec to always be the last extension */
280         TLSEXT_TYPE_psk,
281         EXT_CLIENT_HELLO | EXT_TLS1_3_SERVER_HELLO | EXT_TLS_IMPLEMENTATION_ONLY
282         | EXT_TLS1_3_ONLY,
283         NULL, tls_parse_ctos_psk, tls_parse_stoc_psk, tls_construct_stoc_psk,
284         tls_construct_ctos_psk, NULL
285     }
286 };
287
288 /*
289  * Verify whether we are allowed to use the extension |type| in the current
290  * |context|. Returns 1 to indicate the extension is allowed or unknown or 0 to
291  * indicate the extension is not allowed. If returning 1 then |*found| is set to
292  * 1 if we found a definition for the extension, and |*idx| is set to its index
293  */
294 static int verify_extension(SSL *s, unsigned int context, unsigned int type,
295                             custom_ext_methods *meths, RAW_EXTENSION *rawexlist,
296                             RAW_EXTENSION **found)
297 {
298     size_t i;
299     size_t builtin_num = OSSL_NELEM(ext_defs);
300     const EXTENSION_DEFINITION *thisext;
301
302     for (i = 0, thisext = ext_defs; i < builtin_num; i++, thisext++) {
303         if (type == thisext->type) {
304             /* Check we're allowed to use this extension in this context */
305             if ((context & thisext->context) == 0)
306                 return 0;
307
308             if (SSL_IS_DTLS(s)) {
309                 if ((thisext->context & EXT_TLS_ONLY) != 0)
310                     return 0;
311             } else if ((thisext->context & EXT_DTLS_ONLY) != 0) {
312                     return 0;
313             }
314
315             *found = &rawexlist[i];
316             return 1;
317         }
318     }
319
320     if ((context & (EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO)) == 0) {
321         /*
322          * Custom extensions only apply to <=TLS1.2. This extension is unknown
323          * in this context - we allow it
324          */
325         *found = NULL;
326         return 1;
327     }
328
329     /* Check the custom extensions */
330     if (meths != NULL) {
331         for (i = builtin_num; i < builtin_num + meths->meths_count; i++) {
332             if (meths->meths[i - builtin_num].ext_type == type) {
333                 *found = &rawexlist[i];
334                 return 1;
335             }
336         }
337     }
338
339     /* Unknown extension. We allow it */
340     *found = NULL;
341     return 1;
342 }
343
344 /*
345  * Check whether the context defined for an extension |extctx| means whether
346  * the extension is relevant for the current context |thisctx| or not. Returns
347  * 1 if the extension is relevant for this context, and 0 otherwise
348  */
349 static int extension_is_relevant(SSL *s, unsigned int extctx,
350                                  unsigned int thisctx)
351 {
352     if ((SSL_IS_DTLS(s)
353                 && (extctx & EXT_TLS_IMPLEMENTATION_ONLY) != 0)
354             || (s->version == SSL3_VERSION
355                     && (extctx & EXT_SSL3_ALLOWED) == 0)
356             || (SSL_IS_TLS13(s)
357                 && (extctx & EXT_TLS1_2_AND_BELOW_ONLY) != 0)
358             || (!SSL_IS_TLS13(s) && (extctx & EXT_TLS1_3_ONLY) != 0))
359         return 0;
360
361     return 1;
362 }
363
364 /*
365  * Gather a list of all the extensions from the data in |packet]. |context|
366  * tells us which message this extension is for. The raw extension data is
367  * stored in |*res| on success. In the event of an error the alert type to use
368  * is stored in |*al|. We don't actually process the content of the extensions
369  * yet, except to check their types. This function also runs the initialiser
370  * functions for all known extensions (whether we have collected them or not).
371  * If successful the caller is responsible for freeing the contents of |*res|.
372  *
373  * Per http://tools.ietf.org/html/rfc5246#section-7.4.1.4, there may not be
374  * more than one extension of the same type in a ClientHello or ServerHello.
375  * This function returns 1 if all extensions are unique and we have parsed their
376  * types, and 0 if the extensions contain duplicates, could not be successfully
377  * found, or an internal error occurred. We only check duplicates for
378  * extensions that we know about. We ignore others.
379  */
380 int tls_collect_extensions(SSL *s, PACKET *packet, unsigned int context,
381                            RAW_EXTENSION **res, int *al)
382 {
383     PACKET extensions = *packet;
384     size_t i = 0;
385     custom_ext_methods *exts = NULL;
386     RAW_EXTENSION *raw_extensions = NULL;
387     const EXTENSION_DEFINITION *thisexd;
388
389     *res = NULL;
390
391     /*
392      * Initialise server side custom extensions. Client side is done during
393      * construction of extensions for the ClientHello.
394      */
395     if ((context & EXT_CLIENT_HELLO) != 0) {
396         exts = &s->cert->srv_ext;
397         custom_ext_init(&s->cert->srv_ext);
398     } else if ((context & EXT_TLS1_2_SERVER_HELLO) != 0) {
399         exts = &s->cert->cli_ext;
400     }
401
402     raw_extensions = OPENSSL_zalloc((OSSL_NELEM(ext_defs)
403                                      + (exts != NULL ? exts->meths_count : 0))
404                                      * sizeof(*raw_extensions));
405     if (raw_extensions == NULL) {
406         *al = SSL_AD_INTERNAL_ERROR;
407         SSLerr(SSL_F_TLS_COLLECT_EXTENSIONS, ERR_R_MALLOC_FAILURE);
408         return 0;
409     }
410
411     while (PACKET_remaining(&extensions) > 0) {
412         unsigned int type;
413         PACKET extension;
414         RAW_EXTENSION *thisex;
415
416         if (!PACKET_get_net_2(&extensions, &type) ||
417             !PACKET_get_length_prefixed_2(&extensions, &extension)) {
418             SSLerr(SSL_F_TLS_COLLECT_EXTENSIONS, SSL_R_BAD_EXTENSION);
419             *al = SSL_AD_DECODE_ERROR;
420             goto err;
421         }
422         /*
423          * Verify this extension is allowed. We only check duplicates for
424          * extensions that we recognise.
425          */
426         if (!verify_extension(s, context, type, exts, raw_extensions, &thisex)
427                 || (thisex != NULL && thisex->present == 1)) {
428             SSLerr(SSL_F_TLS_COLLECT_EXTENSIONS, SSL_R_BAD_EXTENSION);
429             *al = SSL_AD_ILLEGAL_PARAMETER;
430             goto err;
431         }
432         if (thisex != NULL) {
433             thisex->data = extension;
434             thisex->present = 1;
435             thisex->type = type;
436         }
437     }
438
439     /*
440      * Initialise all known extensions relevant to this context, whether we have
441      * found them or not
442      */
443     for (thisexd = ext_defs, i = 0; i < OSSL_NELEM(ext_defs); i++, thisexd++) {
444         if(thisexd->init != NULL && (thisexd->context & context) != 0
445                 && extension_is_relevant(s, thisexd->context, context)
446                 && !thisexd->init(s, context)) {
447             *al = SSL_AD_INTERNAL_ERROR;
448             goto err;
449         }
450     }
451
452     *res = raw_extensions;
453     return 1;
454
455  err:
456     OPENSSL_free(raw_extensions);
457     return 0;
458 }
459
460 /*
461  * Runs the parser for a given extension with index |idx|. |exts| contains the
462  * list of all parsed extensions previously collected by
463  * tls_collect_extensions(). The parser is only run if it is applicable for the
464  * given |context| and the parser has not already been run. If this is for a
465  * Certificate message, then we also provide the parser with the relevant
466  * Certificate |x| and its position in the |chainidx| with 0 being the first
467  * Certificate. Returns 1 on success or 0 on failure. In the event of a failure
468  * |*al| is populated with a suitable alert code. If an extension is not present
469  * this counted as success.
470  */
471 int tls_parse_extension(SSL *s, TLSEXT_INDEX idx, int context,
472                         RAW_EXTENSION *exts, X509 *x, size_t chainidx, int *al)
473 {
474     RAW_EXTENSION *currext = &exts[idx];
475     int (*parser)(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
476                   size_t chainidx, int *al) = NULL;
477
478     /* Skip if the extension is not present */
479     if (!currext->present)
480         return 1;
481
482     if (s->ext.debug_cb)
483         s->ext.debug_cb(s, !s->server, currext->type,
484                         PACKET_data(&currext->data),
485                         PACKET_remaining(&currext->data),
486                         s->ext.debug_arg);
487
488     /* Skip if we've already parsed this extension */
489     if (currext->parsed)
490         return 1;
491
492     currext->parsed = 1;
493
494     if (idx < OSSL_NELEM(ext_defs)) {
495         /* We are handling a built-in extension */
496         const EXTENSION_DEFINITION *extdef = &ext_defs[idx];
497
498         /* Check if extension is defined for our protocol. If not, skip */
499         if (!extension_is_relevant(s, extdef->context, context))
500             return 1;
501
502         parser = s->server ? extdef->parse_ctos : extdef->parse_stoc;
503
504         if (parser != NULL)
505             return parser(s, &currext->data, context, x, chainidx, al);
506
507         /*
508          * If the parser is NULL we fall through to the custom extension
509          * processing
510          */
511     }
512
513     /*
514      * This is a custom extension. We only allow this if it is a non
515      * resumed session on the server side.
516      *chain
517      * TODO(TLS1.3): We only allow old style <=TLS1.2 custom extensions.
518      * We're going to need a new mechanism for TLS1.3 to specify which
519      * messages to add the custom extensions to.
520      */
521     if ((!s->hit || !s->server)
522             && (context
523                 & (EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO)) != 0
524             && custom_ext_parse(s, s->server, currext->type,
525                                 PACKET_data(&currext->data),
526                                 PACKET_remaining(&currext->data),
527                                 al) <= 0)
528         return 0;
529
530     return 1;
531 }
532
533 /*
534  * Parse all remaining extensions that have not yet been parsed. Also calls the
535  * finalisation for all extensions at the end, whether we collected them or not.
536  * Returns 1 for success or 0 for failure. If we are working on a Certificate
537  * message then we also pass the Certificate |x| and its position in the
538  * |chainidx|, with 0 being the first certificate. On failure, |*al| is
539  * populated with a suitable alert code.
540  */
541 int tls_parse_all_extensions(SSL *s, int context, RAW_EXTENSION *exts, X509 *x,
542                              size_t chainidx, int *al)
543 {
544     size_t i, numexts = OSSL_NELEM(ext_defs);
545     const EXTENSION_DEFINITION *thisexd;
546
547     /* Calculate the number of extensions in the extensions list */
548     if ((context & EXT_CLIENT_HELLO) != 0) {
549         numexts += s->cert->srv_ext.meths_count;
550     } else if ((context & EXT_TLS1_2_SERVER_HELLO) != 0) {
551         numexts += s->cert->cli_ext.meths_count;
552     }
553
554     /* Parse each extension in turn */
555     for (i = 0; i < numexts; i++) {
556         if (!tls_parse_extension(s, i, context, exts, x, chainidx, al))
557             return 0;
558     }
559
560     /*
561      * Finalise all known extensions relevant to this context, whether we have
562      * found them or not
563      */
564     for (i = 0, thisexd = ext_defs; i < OSSL_NELEM(ext_defs); i++, thisexd++) {
565         if(thisexd->final != NULL
566                 && (thisexd->context & context) != 0
567                 && !thisexd->final(s, context, exts[i].present, al))
568             return 0;
569     }
570
571     return 1;
572 }
573
574 /*
575  * Construct all the extensions relevant to the current |context| and write
576  * them to |pkt|. If this is an extension for a Certificate in a Certificate
577  * message, then |x| will be set to the Certificate we are handling, and
578  * |chainidx| will indicate the position in the chainidx we are processing (with
579  * 0 being the first in the chain). Returns 1 on success or 0 on failure. If a
580  * failure occurs then |al| is populated with a suitable alert code. On a
581  * failure construction stops at the first extension to fail to construct.
582  */
583 int tls_construct_extensions(SSL *s, WPACKET *pkt, unsigned int context,
584                              X509 *x, size_t chainidx, int *al)
585 {
586     size_t i;
587     int addcustom = 0, min_version, max_version = 0, reason, tmpal;
588     const EXTENSION_DEFINITION *thisexd;
589
590     /*
591      * Normally if something goes wrong during construction it's an internal
592      * error. We can always override this later.
593      */
594     tmpal = SSL_AD_INTERNAL_ERROR;
595
596     if (!WPACKET_start_sub_packet_u16(pkt)
597                /*
598                 * If extensions are of zero length then we don't even add the
599                 * extensions length bytes to a ClientHello/ServerHello in SSLv3
600                 */
601             || ((context & (EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO)) != 0
602                && s->version == SSL3_VERSION
603                && !WPACKET_set_flags(pkt,
604                                      WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH))) {
605         SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, ERR_R_INTERNAL_ERROR);
606         goto err;
607     }
608
609     if ((context & EXT_CLIENT_HELLO) != 0) {
610         reason = ssl_get_client_min_max_version(s, &min_version, &max_version);
611         if (reason != 0) {
612             SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, reason);
613             goto err;
614         }
615     }
616
617     /* Add custom extensions first */
618     if ((context & EXT_CLIENT_HELLO) != 0) {
619         custom_ext_init(&s->cert->cli_ext);
620         addcustom = 1;
621     } else if ((context & EXT_TLS1_2_SERVER_HELLO) != 0) {
622         /*
623          * We already initialised the custom extensions during ClientHello
624          * parsing.
625          *
626          * TODO(TLS1.3): We're going to need a new custom extension mechanism
627          * for TLS1.3, so that custom extensions can specify which of the
628          * multiple message they wish to add themselves to.
629          */
630         addcustom = 1;
631     }
632
633     if (addcustom && !custom_ext_add(s, s->server, pkt, &tmpal)) {
634         SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, ERR_R_INTERNAL_ERROR);
635         goto err;
636     }
637
638     for (i = 0, thisexd = ext_defs; i < OSSL_NELEM(ext_defs); i++, thisexd++) {
639         int (*construct)(SSL *s, WPACKET *pkt, unsigned int context, X509 *x,
640                          size_t chainidx, int *al);
641
642         /* Skip if not relevant for our context */
643         if ((thisexd->context & context) == 0)
644             continue;
645
646         construct = s->server ? thisexd->construct_stoc
647                               : thisexd->construct_ctos;
648
649         /* Check if this extension is defined for our protocol. If not, skip */
650         if ((SSL_IS_DTLS(s)
651                     && (thisexd->context & EXT_TLS_IMPLEMENTATION_ONLY)
652                        != 0)
653                 || (s->version == SSL3_VERSION
654                         && (thisexd->context & EXT_SSL3_ALLOWED) == 0)
655                 || (SSL_IS_TLS13(s)
656                     && (thisexd->context & EXT_TLS1_2_AND_BELOW_ONLY)
657                        != 0)
658                 || (!SSL_IS_TLS13(s)
659                     && (thisexd->context & EXT_TLS1_3_ONLY) != 0
660                     && (context & EXT_CLIENT_HELLO) == 0)
661                 || ((thisexd->context & EXT_TLS1_3_ONLY) != 0
662                     && (context & EXT_CLIENT_HELLO) != 0
663                     && (SSL_IS_DTLS(s) || max_version < TLS1_3_VERSION))
664                 || construct == NULL)
665             continue;
666
667         if (!construct(s, pkt, context, x, chainidx, &tmpal))
668             goto err;
669     }
670
671     if (!WPACKET_close(pkt)) {
672         SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, ERR_R_INTERNAL_ERROR);
673         goto err;
674     }
675
676     return 1;
677
678  err:
679     *al = tmpal;
680     return 0;
681 }
682
683 /*
684  * Built in extension finalisation and initialisation functions. All initialise
685  * or finalise the associated extension type for the given |context|. For
686  * finalisers |sent| is set to 1 if we saw the extension during parsing, and 0
687  * otherwise. These functions return 1 on success or 0 on failure. In the event
688  * of a failure then |*al| is populated with a suitable error code.
689  */
690
691 static int final_renegotiate(SSL *s, unsigned int context, int sent,
692                                      int *al)
693 {
694     if (!s->server) {
695         /*
696          * Check if we can connect to a server that doesn't support safe
697          * renegotiation
698          */
699         if (!(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
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         return 1;
709     }
710
711     /* Need RI if renegotiating */
712     if (s->renegotiate
713             && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
714             && !sent) {
715         *al = SSL_AD_HANDSHAKE_FAILURE;
716         SSLerr(SSL_F_FINAL_RENEGOTIATE,
717                SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
718         return 0;
719     }
720
721
722     return 1;
723 }
724
725 static int init_server_name(SSL *s, unsigned int context)
726 {
727     if (s->server)
728         s->servername_done = 0;
729
730     return 1;
731 }
732
733 static int final_server_name(SSL *s, unsigned int context, int sent,
734                                      int *al)
735 {
736     int ret = SSL_TLSEXT_ERR_NOACK;
737     int altmp = SSL_AD_UNRECOGNIZED_NAME;
738
739     if (s->ctx != NULL && s->ctx->ext.servername_cb != 0)
740         ret = s->ctx->ext.servername_cb(s, &altmp,
741                                         s->ctx->ext.servername_arg);
742     else if (s->session_ctx != NULL
743              && s->session_ctx->ext.servername_cb != 0)
744         ret = s->session_ctx->ext.servername_cb(s, &altmp,
745                                        s->session_ctx->ext.servername_arg);
746
747     switch (ret) {
748     case SSL_TLSEXT_ERR_ALERT_FATAL:
749         *al = altmp;
750         return 0;
751
752     case SSL_TLSEXT_ERR_ALERT_WARNING:
753         *al = altmp;
754         return 1;
755
756     case SSL_TLSEXT_ERR_NOACK:
757         s->servername_done = 0;
758         return 1;
759
760     default:
761         return 1;
762     }
763 }
764
765 #ifndef OPENSSL_NO_EC
766 static int final_ec_pt_formats(SSL *s, unsigned int context, int sent,
767                                        int *al)
768 {
769     unsigned long alg_k, alg_a;
770
771     if (s->server)
772         return 1;
773
774     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
775     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
776
777     /*
778      * If we are client and using an elliptic curve cryptography cipher
779      * suite, then if server returns an EC point formats lists extension it
780      * must contain uncompressed.
781      */
782     if (s->ext.ecpointformats != NULL
783             && s->ext.ecpointformats_len > 0
784             && s->session->ext.ecpointformats != NULL
785             && s->session->ext.ecpointformats_len > 0
786             && ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA))) {
787         /* we are using an ECC cipher */
788         size_t i;
789         unsigned char *list = s->session->ext.ecpointformats;
790
791         for (i = 0; i < s->session->ext.ecpointformats_len; i++) {
792             if (*list++ == TLSEXT_ECPOINTFORMAT_uncompressed)
793                 break;
794         }
795         if (i == s->session->ext.ecpointformats_len) {
796             SSLerr(SSL_F_FINAL_EC_PT_FORMATS,
797                    SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
798             return 0;
799         }
800     }
801
802     return 1;
803 }
804 #endif
805
806 static int init_session_ticket(SSL *s, unsigned int context)
807 {
808     if (!s->server)
809         s->ext.ticket_expected = 0;
810
811     return 1;
812 }
813
814 #ifndef OPENSSL_NO_OCSP
815 static int init_status_request(SSL *s, unsigned int context)
816 {
817     if (s->server) {
818         s->ext.status_type = TLSEXT_STATUSTYPE_nothing;
819     } else {
820         /*
821          * Ensure we get sensible values passed to tlsext_status_cb in the event
822          * that we don't receive a status message
823          */
824         OPENSSL_free(s->ext.ocsp.resp);
825         s->ext.ocsp.resp = NULL;
826         s->ext.ocsp.resp_len = 0;
827     }
828
829     return 1;
830 }
831 #endif
832
833 #ifndef OPENSSL_NO_NEXTPROTONEG
834 static int init_npn(SSL *s, unsigned int context)
835 {
836     s->s3->npn_seen = 0;
837
838     return 1;
839 }
840 #endif
841
842 static int init_alpn(SSL *s, unsigned int context)
843 {
844     OPENSSL_free(s->s3->alpn_selected);
845     s->s3->alpn_selected = NULL;
846     if (s->server) {
847         s->s3->alpn_selected_len = 0;
848         OPENSSL_free(s->s3->alpn_proposed);
849         s->s3->alpn_proposed = NULL;
850         s->s3->alpn_proposed_len = 0;
851     }
852     return 1;
853 }
854
855 static int final_alpn(SSL *s, unsigned int context, int sent, int *al)
856 {
857     const unsigned char *selected = NULL;
858     unsigned char selected_len = 0;
859
860     if (!s->server)
861         return 1;
862
863     if (s->ctx->ext.alpn_select_cb != NULL && s->s3->alpn_proposed != NULL) {
864         int r = s->ctx->ext.alpn_select_cb(s, &selected, &selected_len,
865                                            s->s3->alpn_proposed,
866                                            (unsigned int)s->s3->alpn_proposed_len,
867                                            s->ctx->ext.alpn_select_cb_arg);
868
869         if (r == SSL_TLSEXT_ERR_OK) {
870             OPENSSL_free(s->s3->alpn_selected);
871             s->s3->alpn_selected = OPENSSL_memdup(selected, selected_len);
872             if (s->s3->alpn_selected == NULL) {
873                 *al = SSL_AD_INTERNAL_ERROR;
874                 return 0;
875             }
876             s->s3->alpn_selected_len = selected_len;
877 #ifndef OPENSSL_NO_NEXTPROTONEG
878             /* ALPN takes precedence over NPN. */
879             s->s3->npn_seen = 0;
880 #endif
881         } else {
882             *al = SSL_AD_NO_APPLICATION_PROTOCOL;
883             return 0;
884         }
885     }
886
887     return 1;
888 }
889
890 static int init_sig_algs(SSL *s, unsigned int context)
891 {
892     /* Clear any signature algorithms extension received */
893     OPENSSL_free(s->s3->tmp.peer_sigalgs);
894     s->s3->tmp.peer_sigalgs = NULL;
895
896     return 1;
897 }
898
899 #ifndef OPENSSL_NO_SRP
900 static int init_srp(SSL *s, unsigned int context)
901 {
902     OPENSSL_free(s->srp_ctx.login);
903     s->srp_ctx.login = NULL;
904
905     return 1;
906 }
907 #endif
908
909 static int init_etm(SSL *s, unsigned int context)
910 {
911     s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;
912
913     return 1;
914 }
915
916 static int init_ems(SSL *s, unsigned int context)
917 {
918     if (!s->server)
919         s->s3->flags &= ~TLS1_FLAGS_RECEIVED_EXTMS;
920
921     return 1;
922 }
923
924 static int final_ems(SSL *s, unsigned int context, int sent, int *al)
925 {
926     if (!s->server && s->hit) {
927         /*
928          * Check extended master secret extension is consistent with
929          * original session.
930          */
931         if (!(s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS) !=
932             !(s->session->flags & SSL_SESS_FLAG_EXTMS)) {
933             *al = SSL_AD_HANDSHAKE_FAILURE;
934             SSLerr(SSL_F_FINAL_EMS, SSL_R_INCONSISTENT_EXTMS);
935             return 0;
936         }
937     }
938
939     return 1;
940 }
941
942 #ifndef OPENSSL_NO_SRTP
943 static int init_srtp(SSL *s, unsigned int context)
944 {
945     if (s->server)
946         s->srtp_profile = NULL;
947
948     return 1;
949 }
950 #endif
951
952 static int final_sig_algs(SSL *s, unsigned int context, int sent, int *al)
953 {
954     if (!sent && SSL_IS_TLS13(s)) {
955         *al = TLS13_AD_MISSING_EXTENSION;
956         SSLerr(SSL_F_FINAL_SIG_ALGS, SSL_R_MISSING_SIGALGS_EXTENSION);
957         return 0;
958     }
959
960     return 1;
961 }
962
963
964 static int final_key_share(SSL *s, unsigned int context, int sent, int *al)
965 {
966     if (!SSL_IS_TLS13(s))
967         return 1;
968
969     /*
970      * If
971      *     we are a client
972      *     AND
973      *     we have no key_share
974      *     AND
975      *     (we are not resuming
976      *      OR the kex_mode doesn't allow non key_share resumes)
977      * THEN
978      *     fail;
979      */
980     if (!s->server
981             && !sent
982             && (!s->hit
983                 || (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE) == 0)) {
984         /* Nothing left we can do - just fail */
985         *al = SSL_AD_HANDSHAKE_FAILURE;
986         SSLerr(SSL_F_FINAL_KEY_SHARE, SSL_R_NO_SUITABLE_KEY_SHARE);
987         return 0;
988     }
989     /*
990      * If
991      *     we are a server
992      *     AND
993      *     we have no key_share
994      * THEN
995      *     If
996      *         we didn't already send a HelloRetryRequest
997      *         AND
998      *         the client sent a key_share extension
999      *         AND
1000      *         (we are not resuming
1001      *          OR the kex_mode allows key_share resumes)
1002      *         AND
1003      *         a shared group exists
1004      *     THEN
1005      *         send a HelloRetryRequest
1006      *     ELSE If
1007      *         we are not resuming
1008      *         OR
1009      *         the kex_mode doesn't allow non key_share resumes
1010      *     THEN
1011      *         fail;
1012      */
1013     if (s->server && s->s3->peer_tmp == NULL) {
1014         /* No suitable share */
1015         if (s->hello_retry_request == 0 && sent
1016                 && (!s->hit
1017                     || (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE_DHE)
1018                        != 0)) {
1019             const unsigned char *pcurves, *pcurvestmp, *clntcurves;
1020             size_t num_curves, clnt_num_curves, i;
1021             unsigned int group_id = 0;
1022
1023             /* Check if a shared group exists */
1024
1025             /* Get the clients list of supported groups. */
1026             if (!tls1_get_curvelist(s, 1, &clntcurves, &clnt_num_curves)) {
1027                 *al = SSL_AD_INTERNAL_ERROR;
1028                 SSLerr(SSL_F_FINAL_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1029                 return 0;
1030             }
1031
1032             /* Get our list of available groups */
1033             if (!tls1_get_curvelist(s, 0, &pcurves, &num_curves)) {
1034                 *al = SSL_AD_INTERNAL_ERROR;
1035                 SSLerr(SSL_F_FINAL_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1036                 return 0;
1037             }
1038
1039             /* Find the first group we allow that is also in client's list */
1040             for (i = 0, pcurvestmp = pcurves; i < num_curves;
1041                  i++, pcurvestmp += 2) {
1042                 group_id = bytestogroup(pcurvestmp);
1043
1044                 if (check_in_list(s, group_id, clntcurves, clnt_num_curves, 1))
1045                     break;
1046             }
1047
1048             if (i < num_curves) {
1049                 /* A shared group exists so send a HelloRetryRequest */
1050                 s->s3->group_id = group_id;
1051                 s->hello_retry_request = 1;
1052                 return 1;
1053             }
1054         }
1055         if (!s->hit
1056                 || (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE) == 0) {
1057             /* Nothing left we can do - just fail */
1058             *al = SSL_AD_HANDSHAKE_FAILURE;
1059             SSLerr(SSL_F_FINAL_KEY_SHARE, SSL_R_NO_SUITABLE_KEY_SHARE);
1060             return 0;
1061         }
1062     }
1063
1064     /* We have a key_share so don't send any more HelloRetryRequest messages */
1065     if (s->server)
1066         s->hello_retry_request = 0;
1067
1068     /*
1069      * For a client side resumption with no key_share we need to generate
1070      * the handshake secret (otherwise this is done during key_share
1071      * processing).
1072      */
1073     if (!sent && !s->server && !tls13_generate_handshake_secret(s, NULL, 0)) {
1074         *al = SSL_AD_INTERNAL_ERROR;
1075         SSLerr(SSL_F_FINAL_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1076         return 0;
1077     }
1078
1079     return 1;
1080 }
1081
1082 static int init_psk_kex_modes(SSL *s, unsigned int context)
1083 {
1084     s->ext.psk_kex_mode = TLSEXT_KEX_MODE_FLAG_NONE;
1085     return 1;
1086 }
1087
1088 int tls_psk_do_binder(SSL *s, const EVP_MD *md, const unsigned char *msgstart,
1089                       size_t binderoffset, const unsigned char *binderin,
1090                       unsigned char *binderout,
1091                       SSL_SESSION *sess, int sign)
1092 {
1093     EVP_PKEY *mackey = NULL;
1094     EVP_MD_CTX *mctx = NULL;
1095     unsigned char hash[EVP_MAX_MD_SIZE], binderkey[EVP_MAX_MD_SIZE];
1096     unsigned char finishedkey[EVP_MAX_MD_SIZE], tmpbinder[EVP_MAX_MD_SIZE];
1097     const char resumption_label[] = "resumption psk binder key";
1098     size_t bindersize, hashsize = EVP_MD_size(md);
1099     int ret = -1;
1100
1101     /* Generate the early_secret */
1102     if (!tls13_generate_secret(s, md, NULL, sess->master_key,
1103                                sess->master_key_length,
1104                                (unsigned char *)&s->early_secret)) {
1105         SSLerr(SSL_F_TLS_PSK_DO_BINDER, ERR_R_INTERNAL_ERROR);
1106         goto err;
1107     }
1108
1109     /*
1110      * Create the handshake hash for the binder key...the messages so far are
1111      * empty!
1112      */
1113     mctx = EVP_MD_CTX_new();
1114     if (mctx == NULL
1115             || EVP_DigestInit_ex(mctx, md, NULL) <= 0
1116             || EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {
1117         SSLerr(SSL_F_TLS_PSK_DO_BINDER, ERR_R_INTERNAL_ERROR);
1118         goto err;
1119     }
1120
1121     /* Generate the binder key */
1122     if (!tls13_hkdf_expand(s, md, s->early_secret,
1123                            (unsigned char *)resumption_label,
1124                            sizeof(resumption_label) - 1, hash, binderkey,
1125                            hashsize)) {
1126         SSLerr(SSL_F_TLS_PSK_DO_BINDER, ERR_R_INTERNAL_ERROR);
1127         goto err;
1128     }
1129
1130     /* Generate the finished key */
1131     if (!tls13_derive_finishedkey(s, md, binderkey, finishedkey, hashsize)) {
1132         SSLerr(SSL_F_TLS_PSK_DO_BINDER, ERR_R_INTERNAL_ERROR);
1133         goto err;
1134     }
1135
1136     if (EVP_DigestInit_ex(mctx, md, NULL) <= 0) {
1137         SSLerr(SSL_F_TLS_PSK_DO_BINDER, ERR_R_INTERNAL_ERROR);
1138         goto err;
1139     }
1140
1141     /*
1142      * Get a hash of the ClientHello up to the start of the binders. If we are
1143      * following a HelloRetryRequest then this includes the hash of the first
1144      * ClientHello and the HelloRetryRequest itself.
1145      */
1146     if (s->hello_retry_request) {
1147         size_t hdatalen;
1148         void *hdata;
1149
1150         hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
1151         if (hdatalen <= 0) {
1152             SSLerr(SSL_F_TLS_PSK_DO_BINDER, SSL_R_BAD_HANDSHAKE_LENGTH);
1153             goto err;
1154         }
1155
1156         /*
1157          * For servers the handshake buffer data will include the second
1158          * ClientHello - which we don't want - so we need to take that bit off.
1159          */
1160         if (s->server) {
1161             if (hdatalen < s->init_num + SSL3_HM_HEADER_LENGTH) {
1162                 SSLerr(SSL_F_TLS_PSK_DO_BINDER, ERR_R_INTERNAL_ERROR);
1163                 goto err;
1164             }
1165             hdatalen -= s->init_num + SSL3_HM_HEADER_LENGTH;
1166         }
1167
1168         if (EVP_DigestUpdate(mctx, hdata, hdatalen) <= 0) {
1169             SSLerr(SSL_F_TLS_PSK_DO_BINDER, ERR_R_INTERNAL_ERROR);
1170             goto err;
1171         }
1172     }
1173
1174     if (EVP_DigestUpdate(mctx, msgstart, binderoffset) <= 0
1175             || EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {
1176         SSLerr(SSL_F_TLS_PSK_DO_BINDER, ERR_R_INTERNAL_ERROR);
1177         goto err;
1178     }
1179
1180     mackey = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, finishedkey, hashsize);
1181     if (mackey == NULL) {
1182         SSLerr(SSL_F_TLS_PSK_DO_BINDER, ERR_R_INTERNAL_ERROR);
1183         goto err;
1184     }
1185
1186     if (!sign)
1187         binderout = tmpbinder;
1188
1189     bindersize = hashsize;
1190     if (EVP_DigestSignInit(mctx, NULL, md, NULL, mackey) <= 0
1191             || EVP_DigestSignUpdate(mctx, hash, hashsize) <= 0
1192             || EVP_DigestSignFinal(mctx, binderout, &bindersize) <= 0
1193             || bindersize != hashsize) {
1194         SSLerr(SSL_F_TLS_PSK_DO_BINDER, ERR_R_INTERNAL_ERROR);
1195         goto err;
1196     }
1197
1198     if (sign) {
1199         ret = 1;
1200     } else {
1201         /* HMAC keys can't do EVP_DigestVerify* - use CRYPTO_memcmp instead */
1202         ret = (CRYPTO_memcmp(binderin, binderout, hashsize) == 0);
1203     }
1204
1205  err:
1206     OPENSSL_cleanse(binderkey, sizeof(binderkey));
1207     OPENSSL_cleanse(finishedkey, sizeof(finishedkey));
1208     EVP_PKEY_free(mackey);
1209     EVP_MD_CTX_free(mctx);
1210
1211     return ret;
1212 }