Construct the client side psk extension for TLSv1.3
[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         /* Must be immediately before pre_shared_key */
268         /* TODO(TLS1.3): Fix me */
269         TLSEXT_TYPE_padding,
270         EXT_CLIENT_HELLO,
271         NULL,
272         /* We send this, but don't read it */
273         NULL, NULL, NULL, tls_construct_ctos_padding, NULL
274     },
275     {
276         /* Required by the TLSv1.3 spec to always be the last extension */
277         TLSEXT_TYPE_psk,
278         EXT_CLIENT_HELLO | EXT_TLS1_3_SERVER_HELLO | EXT_TLS_IMPLEMENTATION_ONLY
279         | EXT_TLS1_3_ONLY,
280         NULL, NULL, NULL, NULL, tls_construct_ctos_psk, NULL
281     }
282 };
283
284 /*
285  * Verify whether we are allowed to use the extension |type| in the current
286  * |context|. Returns 1 to indicate the extension is allowed or unknown or 0 to
287  * indicate the extension is not allowed. If returning 1 then |*found| is set to
288  * 1 if we found a definition for the extension, and |*idx| is set to its index
289  */
290 static int verify_extension(SSL *s, unsigned int context, unsigned int type,
291                             custom_ext_methods *meths, RAW_EXTENSION *rawexlist,
292                             RAW_EXTENSION **found)
293 {
294     size_t i;
295     size_t builtin_num = OSSL_NELEM(ext_defs);
296     const EXTENSION_DEFINITION *thisext;
297
298     for (i = 0, thisext = ext_defs; i < builtin_num; i++, thisext++) {
299         if (type == thisext->type) {
300             /* Check we're allowed to use this extension in this context */
301             if ((context & thisext->context) == 0)
302                 return 0;
303
304             if (SSL_IS_DTLS(s)) {
305                 if ((thisext->context & EXT_TLS_ONLY) != 0)
306                     return 0;
307             } else if ((thisext->context & EXT_DTLS_ONLY) != 0) {
308                     return 0;
309             }
310
311             *found = &rawexlist[i];
312             return 1;
313         }
314     }
315
316     if ((context & (EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO)) == 0) {
317         /*
318          * Custom extensions only apply to <=TLS1.2. This extension is unknown
319          * in this context - we allow it
320          */
321         *found = NULL;
322         return 1;
323     }
324
325     /* Check the custom extensions */
326     if (meths != NULL) {
327         for (i = builtin_num; i < builtin_num + meths->meths_count; i++) {
328             if (meths->meths[i - builtin_num].ext_type == type) {
329                 *found = &rawexlist[i];
330                 return 1;
331             }
332         }
333     }
334
335     /* Unknown extension. We allow it */
336     *found = NULL;
337     return 1;
338 }
339
340 /*
341  * Check whether the context defined for an extension |extctx| means whether
342  * the extension is relevant for the current context |thisctx| or not. Returns
343  * 1 if the extension is relevant for this context, and 0 otherwise
344  */
345 static int extension_is_relevant(SSL *s, unsigned int extctx,
346                                  unsigned int thisctx)
347 {
348     if ((SSL_IS_DTLS(s)
349                 && (extctx & EXT_TLS_IMPLEMENTATION_ONLY) != 0)
350             || (s->version == SSL3_VERSION
351                     && (extctx & EXT_SSL3_ALLOWED) == 0)
352             || (SSL_IS_TLS13(s)
353                 && (extctx & EXT_TLS1_2_AND_BELOW_ONLY) != 0)
354             || (!SSL_IS_TLS13(s) && (extctx & EXT_TLS1_3_ONLY) != 0))
355         return 0;
356
357     return 1;
358 }
359
360 /*
361  * Gather a list of all the extensions from the data in |packet]. |context|
362  * tells us which message this extension is for. The raw extension data is
363  * stored in |*res| on success. In the event of an error the alert type to use
364  * is stored in |*al|. We don't actually process the content of the extensions
365  * yet, except to check their types. This function also runs the initialiser
366  * functions for all known extensions (whether we have collected them or not).
367  * If successful the caller is responsible for freeing the contents of |*res|.
368  *
369  * Per http://tools.ietf.org/html/rfc5246#section-7.4.1.4, there may not be
370  * more than one extension of the same type in a ClientHello or ServerHello.
371  * This function returns 1 if all extensions are unique and we have parsed their
372  * types, and 0 if the extensions contain duplicates, could not be successfully
373  * found, or an internal error occurred. We only check duplicates for
374  * extensions that we know about. We ignore others.
375  */
376 int tls_collect_extensions(SSL *s, PACKET *packet, unsigned int context,
377                            RAW_EXTENSION **res, int *al)
378 {
379     PACKET extensions = *packet;
380     size_t i = 0;
381     custom_ext_methods *exts = NULL;
382     RAW_EXTENSION *raw_extensions = NULL;
383     const EXTENSION_DEFINITION *thisexd;
384
385     *res = NULL;
386
387     /*
388      * Initialise server side custom extensions. Client side is done during
389      * construction of extensions for the ClientHello.
390      */
391     if ((context & EXT_CLIENT_HELLO) != 0) {
392         exts = &s->cert->srv_ext;
393         custom_ext_init(&s->cert->srv_ext);
394     } else if ((context & EXT_TLS1_2_SERVER_HELLO) != 0) {
395         exts = &s->cert->cli_ext;
396     }
397
398     raw_extensions = OPENSSL_zalloc((OSSL_NELEM(ext_defs)
399                                      + (exts != NULL ? exts->meths_count : 0))
400                                      * sizeof(*raw_extensions));
401     if (raw_extensions == NULL) {
402         *al = SSL_AD_INTERNAL_ERROR;
403         SSLerr(SSL_F_TLS_COLLECT_EXTENSIONS, ERR_R_MALLOC_FAILURE);
404         return 0;
405     }
406
407     while (PACKET_remaining(&extensions) > 0) {
408         unsigned int type;
409         PACKET extension;
410         RAW_EXTENSION *thisex;
411
412         if (!PACKET_get_net_2(&extensions, &type) ||
413             !PACKET_get_length_prefixed_2(&extensions, &extension)) {
414             SSLerr(SSL_F_TLS_COLLECT_EXTENSIONS, SSL_R_BAD_EXTENSION);
415             *al = SSL_AD_DECODE_ERROR;
416             goto err;
417         }
418         /*
419          * Verify this extension is allowed. We only check duplicates for
420          * extensions that we recognise.
421          */
422         if (!verify_extension(s, context, type, exts, raw_extensions, &thisex)
423                 || (thisex != NULL && thisex->present == 1)) {
424             SSLerr(SSL_F_TLS_COLLECT_EXTENSIONS, SSL_R_BAD_EXTENSION);
425             *al = SSL_AD_ILLEGAL_PARAMETER;
426             goto err;
427         }
428         if (thisex != NULL) {
429             thisex->data = extension;
430             thisex->present = 1;
431             thisex->type = type;
432         }
433     }
434
435     /*
436      * Initialise all known extensions relevant to this context, whether we have
437      * found them or not
438      */
439     for (thisexd = ext_defs, i = 0; i < OSSL_NELEM(ext_defs); i++, thisexd++) {
440         if(thisexd->init != NULL && (thisexd->context & context) != 0
441                 && extension_is_relevant(s, thisexd->context, context)
442                 && !thisexd->init(s, context)) {
443             *al = SSL_AD_INTERNAL_ERROR;
444             goto err;
445         }
446     }
447
448     *res = raw_extensions;
449     return 1;
450
451  err:
452     OPENSSL_free(raw_extensions);
453     return 0;
454 }
455
456 /*
457  * Runs the parser for a given extension with index |idx|. |exts| contains the
458  * list of all parsed extensions previously collected by
459  * tls_collect_extensions(). The parser is only run if it is applicable for the
460  * given |context| and the parser has not already been run. If this is for a
461  * Certificate message, then we also provide the parser with the relevant
462  * Certificate |x| and its position in the |chainidx| with 0 being the first
463  * Certificate. Returns 1 on success or 0 on failure. In the event of a failure
464  * |*al| is populated with a suitable alert code. If an extension is not present
465  * this counted as success.
466  */
467 int tls_parse_extension(SSL *s, TLSEXT_INDEX idx, int context,
468                         RAW_EXTENSION *exts, X509 *x, size_t chainidx, int *al)
469 {
470     RAW_EXTENSION *currext = &exts[idx];
471     int (*parser)(SSL *s, PACKET *pkt, X509 *x, size_t chainidx, int *al) = NULL;
472
473     /* Skip if the extension is not present */
474     if (!currext->present)
475         return 1;
476
477     if (s->ext.debug_cb)
478         s->ext.debug_cb(s, !s->server, currext->type,
479                         PACKET_data(&currext->data),
480                         PACKET_remaining(&currext->data),
481                         s->ext.debug_arg);
482
483     /* Skip if we've already parsed this extension */
484     if (currext->parsed)
485         return 1;
486
487     currext->parsed = 1;
488
489     if (idx < OSSL_NELEM(ext_defs)) {
490         /* We are handling a built-in extension */
491         const EXTENSION_DEFINITION *extdef = &ext_defs[idx];
492
493         /* Check if extension is defined for our protocol. If not, skip */
494         if (!extension_is_relevant(s, extdef->context, context))
495             return 1;
496
497         parser = s->server ? extdef->parse_ctos : extdef->parse_stoc;
498
499         if (parser != NULL)
500             return parser(s, &currext->data, x, chainidx, al);
501
502         /*
503          * If the parser is NULL we fall through to the custom extension
504          * processing
505          */
506     }
507
508     /*
509      * This is a custom extension. We only allow this if it is a non
510      * resumed session on the server side.
511      *chain
512      * TODO(TLS1.3): We only allow old style <=TLS1.2 custom extensions.
513      * We're going to need a new mechanism for TLS1.3 to specify which
514      * messages to add the custom extensions to.
515      */
516     if ((!s->hit || !s->server)
517             && (context
518                 & (EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO)) != 0
519             && custom_ext_parse(s, s->server, currext->type,
520                                 PACKET_data(&currext->data),
521                                 PACKET_remaining(&currext->data),
522                                 al) <= 0)
523         return 0;
524
525     return 1;
526 }
527
528 /*
529  * Parse all remaining extensions that have not yet been parsed. Also calls the
530  * finalisation for all extensions at the end, whether we collected them or not.
531  * Returns 1 for success or 0 for failure. If we are working on a Certificate
532  * message then we also pass the Certificate |x| and its position in the
533  * |chainidx|, with 0 being the first certificate. On failure, |*al| is
534  * populated with a suitable alert code.
535  */
536 int tls_parse_all_extensions(SSL *s, int context, RAW_EXTENSION *exts, X509 *x,
537                              size_t chainidx, int *al)
538 {
539     size_t i, numexts = OSSL_NELEM(ext_defs);
540     const EXTENSION_DEFINITION *thisexd;
541
542     /* Calculate the number of extensions in the extensions list */
543     if ((context & EXT_CLIENT_HELLO) != 0) {
544         numexts += s->cert->srv_ext.meths_count;
545     } else if ((context & EXT_TLS1_2_SERVER_HELLO) != 0) {
546         numexts += s->cert->cli_ext.meths_count;
547     }
548
549     /* Parse each extension in turn */
550     for (i = 0; i < numexts; i++) {
551         if (!tls_parse_extension(s, i, context, exts, x, chainidx, al))
552             return 0;
553     }
554
555     /*
556      * Finalise all known extensions relevant to this context, whether we have
557      * found them or not
558      */
559     for (i = 0, thisexd = ext_defs; i < OSSL_NELEM(ext_defs); i++, thisexd++) {
560         if(thisexd->final != NULL
561                 && (thisexd->context & context) != 0
562                 && !thisexd->final(s, context, exts[i].present, al))
563             return 0;
564     }
565
566     return 1;
567 }
568
569 /*
570  * Construct all the extensions relevant to the current |context| and write
571  * them to |pkt|. If this is an extension for a Certificate in a Certificate
572  * message, then |x| will be set to the Certificate we are handling, and
573  * |chainidx| will indicate the position in the chainidx we are processing (with
574  * 0 being the first in the chain). Returns 1 on success or 0 on failure. If a
575  * failure occurs then |al| is populated with a suitable alert code. On a
576  * failure construction stops at the first extension to fail to construct.
577  */
578 int tls_construct_extensions(SSL *s, WPACKET *pkt, unsigned int context,
579                              X509 *x, size_t chainidx, int *al)
580 {
581     size_t i;
582     int addcustom = 0, min_version, max_version = 0, reason, tmpal;
583     const EXTENSION_DEFINITION *thisexd;
584
585     /*
586      * Normally if something goes wrong during construction it's an internal
587      * error. We can always override this later.
588      */
589     tmpal = SSL_AD_INTERNAL_ERROR;
590
591     if (!WPACKET_start_sub_packet_u16(pkt)
592                /*
593                 * If extensions are of zero length then we don't even add the
594                 * extensions length bytes to a ClientHello/ServerHello in SSLv3
595                 */
596             || ((context & (EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO)) != 0
597                && s->version == SSL3_VERSION
598                && !WPACKET_set_flags(pkt,
599                                      WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH))) {
600         SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, ERR_R_INTERNAL_ERROR);
601         goto err;
602     }
603
604     if ((context & EXT_CLIENT_HELLO) != 0) {
605         reason = ssl_get_client_min_max_version(s, &min_version, &max_version);
606         if (reason != 0) {
607             SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, reason);
608             goto err;
609         }
610     }
611
612     /* Add custom extensions first */
613     if ((context & EXT_CLIENT_HELLO) != 0) {
614         custom_ext_init(&s->cert->cli_ext);
615         addcustom = 1;
616     } else if ((context & EXT_TLS1_2_SERVER_HELLO) != 0) {
617         /*
618          * We already initialised the custom extensions during ClientHello
619          * parsing.
620          *
621          * TODO(TLS1.3): We're going to need a new custom extension mechanism
622          * for TLS1.3, so that custom extensions can specify which of the
623          * multiple message they wish to add themselves to.
624          */
625         addcustom = 1;
626     }
627
628     if (addcustom && !custom_ext_add(s, s->server, pkt, &tmpal)) {
629         SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, ERR_R_INTERNAL_ERROR);
630         goto err;
631     }
632
633     for (i = 0, thisexd = ext_defs; i < OSSL_NELEM(ext_defs); i++, thisexd++) {
634         int (*construct)(SSL *s, WPACKET *pkt, X509 *x, size_t chainidx,
635                          int *al);
636
637         /* Skip if not relevant for our context */
638         if ((thisexd->context & context) == 0)
639             continue;
640
641         construct = s->server ? thisexd->construct_stoc
642                               : thisexd->construct_ctos;
643
644         /* Check if this extension is defined for our protocol. If not, skip */
645         if ((SSL_IS_DTLS(s)
646                     && (thisexd->context & EXT_TLS_IMPLEMENTATION_ONLY)
647                        != 0)
648                 || (s->version == SSL3_VERSION
649                         && (thisexd->context & EXT_SSL3_ALLOWED) == 0)
650                 || (SSL_IS_TLS13(s)
651                     && (thisexd->context & EXT_TLS1_2_AND_BELOW_ONLY)
652                        != 0)
653                 || (!SSL_IS_TLS13(s)
654                     && (thisexd->context & EXT_TLS1_3_ONLY) != 0
655                     && (context & EXT_CLIENT_HELLO) == 0)
656                 || ((thisexd->context & EXT_TLS1_3_ONLY) != 0
657                     && (context & EXT_CLIENT_HELLO) != 0
658                     && (SSL_IS_DTLS(s) || max_version < TLS1_3_VERSION))
659                 || construct == NULL)
660             continue;
661
662         if (!construct(s, pkt, x, chainidx, &tmpal))
663             goto err;
664     }
665
666     if (!WPACKET_close(pkt)) {
667         SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, ERR_R_INTERNAL_ERROR);
668         goto err;
669     }
670
671     return 1;
672
673  err:
674     *al = tmpal;
675     return 0;
676 }
677
678 /*
679  * Built in extension finalisation and initialisation functions. All initialise
680  * or finalise the associated extension type for the given |context|. For
681  * finalisers |sent| is set to 1 if we saw the extension during parsing, and 0
682  * otherwise. These functions return 1 on success or 0 on failure. In the event
683  * of a failure then |*al| is populated with a suitable error code.
684  */
685
686 static int final_renegotiate(SSL *s, unsigned int context, int sent,
687                                      int *al)
688 {
689     if (!s->server) {
690         /*
691          * Check if we can connect to a server that doesn't support safe
692          * renegotiation
693          */
694         if (!(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
695                 && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
696                 && !sent) {
697             *al = SSL_AD_HANDSHAKE_FAILURE;
698             SSLerr(SSL_F_FINAL_RENEGOTIATE,
699                    SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
700             return 0;
701         }
702
703         return 1;
704     }
705
706     /* Need RI if renegotiating */
707     if (s->renegotiate
708             && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
709             && !sent) {
710         *al = SSL_AD_HANDSHAKE_FAILURE;
711         SSLerr(SSL_F_FINAL_RENEGOTIATE,
712                SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
713         return 0;
714     }
715
716
717     return 1;
718 }
719
720 static int init_server_name(SSL *s, unsigned int context)
721 {
722     if (s->server)
723         s->servername_done = 0;
724
725     return 1;
726 }
727
728 static int final_server_name(SSL *s, unsigned int context, int sent,
729                                      int *al)
730 {
731     int ret = SSL_TLSEXT_ERR_NOACK;
732     int altmp = SSL_AD_UNRECOGNIZED_NAME;
733
734     if (s->ctx != NULL && s->ctx->ext.servername_cb != 0)
735         ret = s->ctx->ext.servername_cb(s, &altmp,
736                                         s->ctx->ext.servername_arg);
737     else if (s->initial_ctx != NULL
738              && s->initial_ctx->ext.servername_cb != 0)
739         ret = s->initial_ctx->ext.servername_cb(s, &altmp,
740                                        s->initial_ctx->ext.servername_arg);
741
742     switch (ret) {
743     case SSL_TLSEXT_ERR_ALERT_FATAL:
744         *al = altmp;
745         return 0;
746
747     case SSL_TLSEXT_ERR_ALERT_WARNING:
748         *al = altmp;
749         return 1;
750
751     case SSL_TLSEXT_ERR_NOACK:
752         s->servername_done = 0;
753         return 1;
754
755     default:
756         return 1;
757     }
758 }
759
760 #ifndef OPENSSL_NO_EC
761 static int final_ec_pt_formats(SSL *s, unsigned int context, int sent,
762                                        int *al)
763 {
764     unsigned long alg_k, alg_a;
765
766     if (s->server)
767         return 1;
768
769     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
770     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
771
772     /*
773      * If we are client and using an elliptic curve cryptography cipher
774      * suite, then if server returns an EC point formats lists extension it
775      * must contain uncompressed.
776      */
777     if (s->ext.ecpointformats != NULL
778             && s->ext.ecpointformats_len > 0
779             && s->session->ext.ecpointformats != NULL
780             && s->session->ext.ecpointformats_len > 0
781             && ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA))) {
782         /* we are using an ECC cipher */
783         size_t i;
784         unsigned char *list = s->session->ext.ecpointformats;
785
786         for (i = 0; i < s->session->ext.ecpointformats_len; i++) {
787             if (*list++ == TLSEXT_ECPOINTFORMAT_uncompressed)
788                 break;
789         }
790         if (i == s->session->ext.ecpointformats_len) {
791             SSLerr(SSL_F_FINAL_EC_PT_FORMATS,
792                    SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
793             return 0;
794         }
795     }
796
797     return 1;
798 }
799 #endif
800
801 static int init_session_ticket(SSL *s, unsigned int context)
802 {
803     if (!s->server)
804         s->ext.ticket_expected = 0;
805
806     return 1;
807 }
808
809 #ifndef OPENSSL_NO_OCSP
810 static int init_status_request(SSL *s, unsigned int context)
811 {
812     if (s->server) {
813         s->ext.status_type = TLSEXT_STATUSTYPE_nothing;
814     } else {
815         /*
816          * Ensure we get sensible values passed to tlsext_status_cb in the event
817          * that we don't receive a status message
818          */
819         OPENSSL_free(s->ext.ocsp.resp);
820         s->ext.ocsp.resp = NULL;
821         s->ext.ocsp.resp_len = 0;
822     }
823
824     return 1;
825 }
826 #endif
827
828 #ifndef OPENSSL_NO_NEXTPROTONEG
829 static int init_npn(SSL *s, unsigned int context)
830 {
831     s->s3->npn_seen = 0;
832
833     return 1;
834 }
835 #endif
836
837 static int init_alpn(SSL *s, unsigned int context)
838 {
839     OPENSSL_free(s->s3->alpn_selected);
840     s->s3->alpn_selected = NULL;
841     if (s->server) {
842         s->s3->alpn_selected_len = 0;
843         OPENSSL_free(s->s3->alpn_proposed);
844         s->s3->alpn_proposed = NULL;
845         s->s3->alpn_proposed_len = 0;
846     }
847     return 1;
848 }
849
850 static int final_alpn(SSL *s, unsigned int context, int sent, int *al)
851 {
852     const unsigned char *selected = NULL;
853     unsigned char selected_len = 0;
854
855     if (!s->server)
856         return 1;
857
858     if (s->ctx->ext.alpn_select_cb != NULL && s->s3->alpn_proposed != NULL) {
859         int r = s->ctx->ext.alpn_select_cb(s, &selected, &selected_len,
860                                            s->s3->alpn_proposed,
861                                            (unsigned int)s->s3->alpn_proposed_len,
862                                            s->ctx->ext.alpn_select_cb_arg);
863
864         if (r == SSL_TLSEXT_ERR_OK) {
865             OPENSSL_free(s->s3->alpn_selected);
866             s->s3->alpn_selected = OPENSSL_memdup(selected, selected_len);
867             if (s->s3->alpn_selected == NULL) {
868                 *al = SSL_AD_INTERNAL_ERROR;
869                 return 0;
870             }
871             s->s3->alpn_selected_len = selected_len;
872 #ifndef OPENSSL_NO_NEXTPROTONEG
873             /* ALPN takes precedence over NPN. */
874             s->s3->npn_seen = 0;
875 #endif
876         } else {
877             *al = SSL_AD_NO_APPLICATION_PROTOCOL;
878             return 0;
879         }
880     }
881
882     return 1;
883 }
884
885 static int init_sig_algs(SSL *s, unsigned int context)
886 {
887     /* Clear any signature algorithms extension received */
888     OPENSSL_free(s->s3->tmp.peer_sigalgs);
889     s->s3->tmp.peer_sigalgs = NULL;
890
891     return 1;
892 }
893
894 #ifndef OPENSSL_NO_SRP
895 static int init_srp(SSL *s, unsigned int context)
896 {
897     OPENSSL_free(s->srp_ctx.login);
898     s->srp_ctx.login = NULL;
899
900     return 1;
901 }
902 #endif
903
904 static int init_etm(SSL *s, unsigned int context)
905 {
906     s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;
907
908     return 1;
909 }
910
911 static int init_ems(SSL *s, unsigned int context)
912 {
913     if (!s->server)
914         s->s3->flags &= ~TLS1_FLAGS_RECEIVED_EXTMS;
915
916     return 1;
917 }
918
919 static int final_ems(SSL *s, unsigned int context, int sent, int *al)
920 {
921     if (!s->server && s->hit) {
922         /*
923          * Check extended master secret extension is consistent with
924          * original session.
925          */
926         if (!(s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS) !=
927             !(s->session->flags & SSL_SESS_FLAG_EXTMS)) {
928             *al = SSL_AD_HANDSHAKE_FAILURE;
929             SSLerr(SSL_F_FINAL_EMS, SSL_R_INCONSISTENT_EXTMS);
930             return 0;
931         }
932     }
933
934     return 1;
935 }
936
937 #ifndef OPENSSL_NO_SRTP
938 static int init_srtp(SSL *s, unsigned int context)
939 {
940     if (s->server)
941         s->srtp_profile = NULL;
942
943     return 1;
944 }
945 #endif
946
947 static int final_sig_algs(SSL *s, unsigned int context, int sent, int *al)
948 {
949     if (!sent && SSL_IS_TLS13(s)) {
950         *al = TLS13_AD_MISSING_EXTENSION;
951         SSLerr(SSL_F_FINAL_SIG_ALGS, SSL_R_MISSING_SIGALGS_EXTENSION);
952         return 0;
953     }
954
955     return 1;
956 }
957
958 static int init_psk_kex_modes(SSL *s, unsigned int context)
959 {
960     s->ext.psk_kex_mode = TLSEXT_KEX_MODE_FLAG_NONE;
961
962     return 1;
963 }