Move ALPN processing into an extension finalisation function
[openssl.git] / ssl / statem / extensions.c
index c98a2055c2d0f69a28844dbc4bb2a24aced02891..4c8ad7fe6d67f24377d32d550dc5f33feadbe641 100644 (file)
@@ -8,40 +8,51 @@
  */
 
 #include <stdlib.h>
  */
 
 #include <stdlib.h>
-#include <openssl/ocsp.h>
 #include "../ssl_locl.h"
 #include "statem_locl.h"
 
 #include "../ssl_locl.h"
 #include "statem_locl.h"
 
-static int tls_parse_clienthello_renegotiate(SSL *s, PACKET *pkt, int *al);
-static int tls_parse_clienthello_server_name(SSL *s, PACKET *pkt, int *al);
-#ifndef OPENSSL_NO_SRP
-static int tls_parse_clienthello_srp(SSL *s, PACKET *pkt, int *al);
-#endif
-#ifndef OPENSSL_NO_EC
-static int tls_parse_clienthello_ec_pt_formats(SSL *s, PACKET *pkt, int *al);
-static int tls_parse_clienthello_supported_groups(SSL *s, PACKET *pkt, int *al);
-#endif
-static int tls_parse_clienthello_session_ticket(SSL *s, PACKET *pkt, int *al);
-static int tls_parse_clienthello_sig_algs(SSL *s, PACKET *pkt, int *al);
-static int tls_parse_clienthello_status_request(SSL *s, PACKET *pkt, int *al);
+static int tls_ext_final_renegotiate(SSL *s, unsigned int context, int sent,
+                                     int *al);
+static int tls_ext_init_server_name(SSL *s, unsigned int context);
+static int tls_ext_final_server_name(SSL *s, unsigned int context, int sent,
+                                     int *al);
+static int tls_ext_init_status_request(SSL *s, unsigned int context);
 #ifndef OPENSSL_NO_NEXTPROTONEG
 #ifndef OPENSSL_NO_NEXTPROTONEG
-static int tls_parse_clienthello_npn(SSL *s, PACKET *pkt, int *al);
+static int tls_ext_init_npn(SSL *s, unsigned int context);
 #endif
 #endif
-static int tls_parse_clienthello_alpn(SSL *s, PACKET *pkt, int *al);
+static int tls_ext_init_alpn(SSL *s, unsigned int context);
+static int tls_ext_final_alpn(SSL *s, unsigned int context, int sent, int *al);
+static int tls_ext_init_sig_algs(SSL *s, unsigned int context);
+#ifndef OPENSSL_NO_SRP
+static int tls_ext_init_srp(SSL *s, unsigned int context);
+#endif
+static int tls_ext_init_etm(SSL *s, unsigned int context);
 #ifndef OPENSSL_NO_SRTP
 #ifndef OPENSSL_NO_SRTP
-static int tls_parse_clienthello_use_srtp(SSL *s, PACKET *pkt, int *al);
+static int tls_ext_init_srtp(SSL *s, unsigned int context);
 #endif
 #endif
-static int tls_parse_clienthello_etm(SSL *s, PACKET *pkt, int *al);
-static int tls_parse_clienthello_key_share(SSL *s, PACKET *pkt, int *al);
-static int tls_parse_clienthello_ems(SSL *s, PACKET *pkt, int *al);
 
 typedef struct {
     /* The ID for the extension */
     unsigned int type;
 
 typedef struct {
     /* The ID for the extension */
     unsigned int type;
-    int (*server_parse)(SSL *s, PACKET *pkt, int *al);
-    int (*client_parse)(SSL *s, PACKET *pkt, int *al);
-    int (*server_construct)(SSL *s, WPACKET *pkt, int *al);
-    int (*client_construct)(SSL *s, WPACKET *pkt, int *al);
+    /*
+     * Initialise extension before parsing. Always called for relevant contexts
+     * even if extension not present
+     */
+    int (*init_ext)(SSL *s, unsigned int context);
+    /* Parse extension received by server from client */
+    int (*parse_client_ext)(SSL *s, PACKET *pkt, int *al);
+    /* Parse extension received by client from server */
+    int (*parse_server_ext)(SSL *s, PACKET *pkt, int *al);
+    /* Construct extension sent by server */
+    int (*construct_server_ext)(SSL *s, WPACKET *pkt, int *al);
+    /* Construct extension sent by client */
+    int (*construct_client_ext)(SSL *s, WPACKET *pkt, int *al);
+    /*
+     * Finalise extension after parsing. Always called where an extensions was
+     * initialised even if the extension was not present. |sent| is set to 1 if
+     * the extension was seen, or 0 otherwise.
+     */
+    int (*finalise_ext)(SSL *s, unsigned int context, int sent, int *al);
     unsigned int context;
 } EXTENSION_DEFINITION;
 
     unsigned int context;
 } EXTENSION_DEFINITION;
 
@@ -53,161 +64,219 @@ typedef struct {
 static const EXTENSION_DEFINITION ext_defs[] = {
     {
         TLSEXT_TYPE_renegotiate,
 static const EXTENSION_DEFINITION ext_defs[] = {
     {
         TLSEXT_TYPE_renegotiate,
-        tls_parse_clienthello_renegotiate,
-        NULL,
-        NULL,
         NULL,
         NULL,
+        tls_parse_client_renegotiate,
+        tls_parse_server_renegotiate,
+        tls_construct_server_renegotiate,
+        tls_construct_client_renegotiate,
+        tls_ext_final_renegotiate,
         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_SSL3_ALLOWED
         | EXT_TLS1_2_AND_BELOW_ONLY
     },
     {
         TLSEXT_TYPE_server_name,
         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_SSL3_ALLOWED
         | EXT_TLS1_2_AND_BELOW_ONLY
     },
     {
         TLSEXT_TYPE_server_name,
-        tls_parse_clienthello_server_name,
-        NULL,
-        NULL,
-        NULL,
+        tls_ext_init_server_name,
+        tls_parse_client_server_name,
+        tls_parse_server_server_name,
+        tls_construct_server_server_name,
+        tls_construct_client_server_name,
+        tls_ext_final_server_name,
         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
-        | /*EXT_TLS1_3_ENCRYPTED_EXTENSIONS*/EXT_TLS1_3_SERVER_HELLO
+        | EXT_TLS1_3_ENCRYPTED_EXTENSIONS
     },
 #ifndef OPENSSL_NO_SRP
     {
         TLSEXT_TYPE_srp,
     },
 #ifndef OPENSSL_NO_SRP
     {
         TLSEXT_TYPE_srp,
-        tls_parse_clienthello_srp,
+        tls_ext_init_srp,
+        tls_parse_client_srp,
         NULL,
         NULL,
         NULL,
         NULL,
+        tls_construct_client_srp,
         NULL,
         NULL,
-        EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
+        EXT_CLIENT_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
     },
 #endif
 #ifndef OPENSSL_NO_EC
     {
         TLSEXT_TYPE_ec_point_formats,
     },
 #endif
 #ifndef OPENSSL_NO_EC
     {
         TLSEXT_TYPE_ec_point_formats,
-        tls_parse_clienthello_ec_pt_formats,
-        NULL,
         NULL,
         NULL,
+        tls_parse_client_ec_pt_formats,
+        tls_parse_server_ec_pt_formats,
+        tls_construct_server_ec_pt_formats,
+        tls_construct_client_ec_pt_formats,
         NULL,
         EXT_CLIENT_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
     },
     {
         TLSEXT_TYPE_supported_groups,
         NULL,
         EXT_CLIENT_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
     },
     {
         TLSEXT_TYPE_supported_groups,
-        tls_parse_clienthello_supported_groups,
         NULL,
         NULL,
+        tls_parse_client_supported_groups,
         NULL,
         NULL,
+        NULL /* TODO(TLS1.3): Need to add this */,
+        tls_construct_client_supported_groups,
         NULL,
         NULL,
-        EXT_CLIENT_HELLO
-        | /*EXT_TLS1_3_ENCRYPTED_EXTENSIONS*/EXT_TLS1_3_SERVER_HELLO
+        EXT_CLIENT_HELLO | EXT_TLS1_3_ENCRYPTED_EXTENSIONS
     },
 #endif
     {
         TLSEXT_TYPE_session_ticket,
     },
 #endif
     {
         TLSEXT_TYPE_session_ticket,
-        tls_parse_clienthello_session_ticket,
-        NULL,
         NULL,
         NULL,
+        tls_parse_client_session_ticket,
+        tls_parse_server_session_ticket,
+        tls_construct_server_session_ticket,
+        tls_construct_client_session_ticket,
         NULL,
         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
     },
     {
         TLSEXT_TYPE_signature_algorithms,
         NULL,
         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
     },
     {
         TLSEXT_TYPE_signature_algorithms,
-        tls_parse_clienthello_sig_algs,
+        tls_ext_init_sig_algs,
+        tls_parse_client_sig_algs,
         NULL,
         NULL,
         NULL,
         NULL,
+        tls_construct_client_sig_algs,
         NULL,
         EXT_CLIENT_HELLO
     },
         NULL,
         EXT_CLIENT_HELLO
     },
+#ifndef OPENSSL_NO_OCSP
     {
         TLSEXT_TYPE_status_request,
     {
         TLSEXT_TYPE_status_request,
-        tls_parse_clienthello_status_request,
-        NULL,
-        NULL,
+        tls_ext_init_status_request,
+        tls_parse_client_status_request,
+        tls_parse_server_status_request,
+        tls_construct_server_status_request,
+        tls_construct_client_status_request,
         NULL,
         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
         NULL,
         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
-        | /*EXT_TLS1_3_CERTIFICATE*/EXT_TLS1_3_SERVER_HELLO
+        | EXT_TLS1_3_CERTIFICATE
     },
     },
+#endif
 #ifndef OPENSSL_NO_NEXTPROTONEG
     {
         TLSEXT_TYPE_next_proto_neg,
 #ifndef OPENSSL_NO_NEXTPROTONEG
     {
         TLSEXT_TYPE_next_proto_neg,
-        tls_parse_clienthello_npn,
-        NULL,
-        NULL,
+        tls_ext_init_npn,
+        tls_parse_client_npn,
+        tls_parse_server_npn,
+        tls_construct_server_next_proto_neg,
+        tls_construct_client_npn,
         NULL,
         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
     },
 #endif
     {
         NULL,
         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
     },
 #endif
     {
+        /*
+         * Must appear in this list after server_name so that finalisation
+         * happens after server_name callbacks
+         */
         TLSEXT_TYPE_application_layer_protocol_negotiation,
         TLSEXT_TYPE_application_layer_protocol_negotiation,
-        tls_parse_clienthello_alpn,
-        NULL,
-        NULL,
-        NULL,
+        tls_ext_init_alpn,
+        tls_parse_client_alpn,
+        tls_parse_server_alpn,
+        tls_construct_server_alpn,
+        tls_construct_client_alpn,
+        tls_ext_final_alpn,
         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
-        | /*EXT_TLS1_3_ENCRYPTED_EXTENSIONS*/EXT_TLS1_3_SERVER_HELLO
+        | EXT_TLS1_3_ENCRYPTED_EXTENSIONS
     },
     },
+#ifndef OPENSSL_NO_SRTP
     {
         TLSEXT_TYPE_use_srtp,
     {
         TLSEXT_TYPE_use_srtp,
-        tls_parse_clienthello_use_srtp,
-        NULL,
-        NULL,
+        tls_ext_init_srtp,
+        tls_parse_client_use_srtp,
+        tls_parse_server_use_srtp,
+        tls_construct_server_use_srtp,
+        tls_construct_client_use_srtp,
         NULL,
         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
         | EXT_TLS1_3_ENCRYPTED_EXTENSIONS | EXT_DTLS_ONLY
     },
         NULL,
         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
         | EXT_TLS1_3_ENCRYPTED_EXTENSIONS | EXT_DTLS_ONLY
     },
+#endif
     {
         TLSEXT_TYPE_encrypt_then_mac,
     {
         TLSEXT_TYPE_encrypt_then_mac,
-        tls_parse_clienthello_etm,
-        NULL,
-        NULL,
+        tls_ext_init_etm,
+        tls_parse_client_etm,
+        tls_parse_server_etm,
+        tls_construct_server_etm,
+        tls_construct_client_etm,
         NULL,
         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
     },
         NULL,
         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
     },
+#ifndef OPENSSL_NO_CT
     {
         TLSEXT_TYPE_signed_certificate_timestamp,
     {
         TLSEXT_TYPE_signed_certificate_timestamp,
+        NULL,
         /*
          * No server side support for this, but can be provided by a custom
          * extension. This is an exception to the rule that custom extensions
          * cannot override built in ones.
          */
         NULL,
         /*
          * No server side support for this, but can be provided by a custom
          * extension. This is an exception to the rule that custom extensions
          * cannot override built in ones.
          */
         NULL,
+        tls_parse_server_sct,
         NULL,
         NULL,
-        NULL,
+        tls_construct_client_sct,
         NULL,
         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
         NULL,
         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
-        | /*EXT_TLS1_3_CERTIFICATE*/EXT_TLS1_3_SERVER_HELLO
+        | EXT_TLS1_3_CERTIFICATE
     },
     },
+#endif
     {
         TLSEXT_TYPE_extended_master_secret,
     {
         TLSEXT_TYPE_extended_master_secret,
-        tls_parse_clienthello_ems,
-        NULL,
         NULL,
         NULL,
+        tls_parse_client_ems,
+        tls_parse_server_ems,
+        tls_construct_server_ems,
+        tls_construct_client_ems,
         NULL,
         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
     },
     {
         TLSEXT_TYPE_supported_versions,
         NULL,
         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
     },
     {
         TLSEXT_TYPE_supported_versions,
+        NULL,
         /* Processed inline as part of version selection */
         NULL,
         NULL,
         NULL,
         /* Processed inline as part of version selection */
         NULL,
         NULL,
         NULL,
+        tls_construct_client_supported_versions,
         NULL,
         NULL,
-        EXT_CLIENT_HELLO | EXT_TLS_IMPLEMENTATION_ONLY
+        EXT_CLIENT_HELLO | EXT_TLS_IMPLEMENTATION_ONLY | EXT_TLS1_3_ONLY
     },
     {
     },
     {
-        TLSEXT_TYPE_padding,
-        /* We send this, but don't read it */
+        TLSEXT_TYPE_key_share,
         NULL,
         NULL,
+        tls_parse_client_key_share,
+        tls_parse_server_key_share,
+        tls_construct_server_key_share,
+        tls_construct_client_key_share,
         NULL,
         NULL,
+        EXT_CLIENT_HELLO | EXT_TLS1_3_SERVER_HELLO
+        | EXT_TLS1_3_HELLO_RETRY_REQUEST | EXT_TLS_IMPLEMENTATION_ONLY
+        | EXT_TLS1_3_ONLY
+    },
+    {
+        /*
+         * Special unsolicited ServerHello extension only used when
+         * SSL_OP_CRYPTOPRO_TLSEXT_BUG is set
+         */
+        TLSEXT_TYPE_cryptopro_bug,
         NULL,
         NULL,
         NULL,
         NULL,
-        EXT_CLIENT_HELLO
+        NULL,
+        tls_construct_server_cryptopro_bug,
+        NULL,
+        NULL,
+        EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
     },
     {
     },
     {
-        TLSEXT_TYPE_key_share,
-        tls_parse_clienthello_key_share,
+        /* Last in the list because it must be added as the last extension */
+        TLSEXT_TYPE_padding,
         NULL,
         NULL,
+        /* We send this, but don't read it */
         NULL,
         NULL,
         NULL,
         NULL,
-        EXT_CLIENT_HELLO | EXT_TLS1_3_SERVER_HELLO
-        | EXT_TLS1_3_HELLO_RETRY_REQUEST | EXT_TLS_IMPLEMENTATION_ONLY
-        | EXT_TLS1_3_ONLY
+        NULL,
+        tls_construct_client_padding,
+        NULL,
+        EXT_CLIENT_HELLO
     }
 };
 
     }
 };
 
@@ -285,9 +354,24 @@ static int find_extension_definition(SSL *s, unsigned int type,
     return 0;
 }
 
     return 0;
 }
 
+static int extension_is_relevant(SSL *s, unsigned int extctx,
+                                 unsigned int thisctx)
+{
+    if ((SSL_IS_DTLS(s)
+                && (extctx & EXT_TLS_IMPLEMENTATION_ONLY) != 0)
+            || (s->version == SSL3_VERSION
+                    && (extctx & EXT_SSL3_ALLOWED) == 0)
+            || (SSL_IS_TLS13(s)
+                && (extctx & EXT_TLS1_2_AND_BELOW_ONLY) != 0)
+            || (!SSL_IS_TLS13(s) && (extctx & EXT_TLS1_3_ONLY) != 0))
+        return 0;
+
+    return 1;
+}
+
 /*
  * Gather a list of all the extensions from the data in |packet]. |context|
 /*
  * Gather a list of all the extensions from the data in |packet]. |context|
- * tells us which message this extension is for. The raw extension data is
+ * tells us which message this extension is for. Ttls_parse_server_ec_pt_formatshe raw extension data is
  * stored in |*res| with the number of found extensions in |*numfound|. In the
  * event of an error the alert type to use is stored in |*ad|. We don't actually
  * process the content of the extensions yet, except to check their types.
  * stored in |*res| with the number of found extensions in |*numfound|. In the
  * event of an error the alert type to use is stored in |*ad|. We don't actually
  * process the content of the extensions yet, except to check their types.
@@ -298,10 +382,7 @@ static int find_extension_definition(SSL *s, unsigned int type,
  * types, and 0 if the extensions contain duplicates, could not be successfully
  * parsed, or an internal error occurred.
  */
  * types, and 0 if the extensions contain duplicates, could not be successfully
  * parsed, or an internal error occurred.
  */
-/*
- * TODO(TLS1.3): Refactor ServerHello extension parsing to use this and then
- * remove tls1_check_duplicate_extensions()
- */
+
 int tls_collect_extensions(SSL *s, PACKET *packet, unsigned int context,
                            RAW_EXTENSION **res, size_t *numfound, int *ad)
 {
 int tls_collect_extensions(SSL *s, PACKET *packet, unsigned int context,
                            RAW_EXTENSION **res, size_t *numfound, int *ad)
 {
@@ -366,6 +447,26 @@ int tls_collect_extensions(SSL *s, PACKET *packet, unsigned int context,
         }
     }
 
         }
     }
 
+    /*
+     * Initialise all known extensions relevant to this context, whether we have
+     * found them or not
+     */
+    for (i = 0; i < OSSL_NELEM(ext_defs); i++) {
+        if(ext_defs[i].init_ext != NULL && (ext_defs[i].context & context) != 0
+                && extension_is_relevant(s, ext_defs[i].context, context)
+                && !ext_defs[i].init_ext(s, context)) {
+            *ad = SSL_AD_INTERNAL_ERROR;
+            goto err;
+        }
+    }
+
+    /*
+     * Initialise server side custom extensions. Client side is done during
+     * construction of extensions for the ClientHello.
+     */
+    if ((context & (EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_3_SERVER_HELLO)) != 0)
+        custom_ext_init(&s->cert->srv_ext);
+
     *res = raw_extensions;
     *numfound = num_extensions;
     return 1;
     *res = raw_extensions;
     *numfound = num_extensions;
     return 1;
@@ -375,8 +476,15 @@ int tls_collect_extensions(SSL *s, PACKET *packet, unsigned int context,
     return 0;
 }
 
     return 0;
 }
 
-int tls_parse_all_extensions(SSL *s, int context, RAW_EXTENSION *exts,
-                             size_t numexts, int *al)
+/*
+ * Runs the parsers for all of the extensions in the given list |exts|, which
+ * should have |numexts| extensions in it. The parsers are only run if they are
+ * applicable for the given |context| and the parser has not already been run
+ * for that extension. Returns 1 on success or 0 on failure. In the event of a
+ * failure |*al| is populated with a suitable alert code.
+ */
+static int tls_parse_extension_list(SSL *s, int context, RAW_EXTENSION *exts,
+                                    size_t numexts, int *al)
 {
     size_t loop;
 
 {
     size_t loop;
 
@@ -386,7 +494,7 @@ int tls_parse_all_extensions(SSL *s, int context, RAW_EXTENSION *exts,
         int (*parser)(SSL *s, PACKET *pkt, int *al) = NULL;
 
         if (s->tlsext_debug_cb)
         int (*parser)(SSL *s, PACKET *pkt, int *al) = NULL;
 
         if (s->tlsext_debug_cb)
-            s->tlsext_debug_cb(s, 0, currext->type,
+            s->tlsext_debug_cb(s, !s->server, currext->type,
                                PACKET_data(&currext->data),
                                PACKET_remaining(&currext->data),
                                s->tlsext_debug_arg);
                                PACKET_data(&currext->data),
                                PACKET_remaining(&currext->data),
                                s->tlsext_debug_arg);
@@ -399,17 +507,11 @@ int tls_parse_all_extensions(SSL *s, int context, RAW_EXTENSION *exts,
 
         parser = NULL;
         if (find_extension_definition(s, currext->type, &extdef)) {
 
         parser = NULL;
         if (find_extension_definition(s, currext->type, &extdef)) {
-            parser = s->server ? extdef->server_parse : extdef->client_parse;
+            parser = s->server ? extdef->parse_client_ext
+                               : extdef->parse_server_ext;
 
             /* Check if extension is defined for our protocol. If not, skip */
 
             /* Check if extension is defined for our protocol. If not, skip */
-            if ((SSL_IS_DTLS(s)
-                        && (extdef->context & EXT_TLS_IMPLEMENTATION_ONLY) != 0)
-                    || (s->version == SSL3_VERSION
-                            && (extdef->context & EXT_SSL3_ALLOWED) == 0)
-                    || (SSL_IS_TLS13(s)
-                        && (extdef->context & EXT_TLS1_2_AND_BELOW_ONLY) != 0)
-                    || (!SSL_IS_TLS13(s)
-                        && (extdef->context & EXT_TLS1_3_ONLY) != 0))
+            if (!extension_is_relevant(s, extdef->context, context))
                 continue;
         }
 
                 continue;
         }
 
@@ -441,6 +543,48 @@ int tls_parse_all_extensions(SSL *s, int context, RAW_EXTENSION *exts,
     return 1;
 }
 
     return 1;
 }
 
+/*
+ * Parse all remaining extensions that have not yet been parsed. Also calls the
+ * finalisation for all extensions at the end. The given extensions must be in
+ * order of type (which happens by default during collection). Returns 1 for
+ * success or 0 for failure. On failure, |*al| is populated with a suitable
+ * alert code.
+ */
+int tls_parse_all_extensions(SSL *s, int context, RAW_EXTENSION *exts,
+                             size_t numexts, int *al)
+{
+    size_t loop;
+
+    if (!tls_parse_extension_list(s, context, exts, numexts, al))
+        return 0;
+
+    /*
+     * Finalise all known extensions relevant to this context, whether we have
+     * found them or not
+     */
+    for (loop = 0; loop < OSSL_NELEM(ext_defs); loop++) {
+        if(ext_defs[loop].finalise_ext != NULL
+                && (ext_defs[loop].context & context) != 0) {
+            size_t curr;
+
+            /*
+             * Work out whether this extension was sent or not. The sent
+             * extensions in |exts| are sorted by order of type
+             */
+            for (curr = 0; curr < numexts
+                           && exts[curr].type < ext_defs[loop].type; curr++)
+                continue;
+
+            if (!ext_defs[loop].finalise_ext(s, context,
+                    (curr < numexts && exts[curr].type == ext_defs[loop].type),
+                    al))
+            return 0;
+        }
+    }
+
+    return 1;
+}
+
 /*
  * Find a specific extension by |type| in the list |exts| containing |numexts|
  * extensions, and the parse it immediately. Returns 1 on success, or 0 on
 /*
  * Find a specific extension by |type| in the list |exts| containing |numexts|
  * extensions, and the parse it immediately. Returns 1 on success, or 0 on
@@ -455,7 +599,7 @@ int tls_parse_extension(SSL *s, int type, int context, RAW_EXTENSION *exts,
     if (ext == NULL)
         return 1;
 
     if (ext == NULL)
         return 1;
 
-    return tls_parse_all_extensions(s, context, ext, 1, al);
+    return tls_parse_extension_list(s, context, ext, 1, al);
 }
 
 int tls_construct_extensions(SSL *s, WPACKET *pkt, unsigned int context,
 }
 
 int tls_construct_extensions(SSL *s, WPACKET *pkt, unsigned int context,
@@ -463,16 +607,52 @@ int tls_construct_extensions(SSL *s, WPACKET *pkt, unsigned int context,
 {
     size_t loop;
     int addcustom = 0;
 {
     size_t loop;
     int addcustom = 0;
+    int min_version, max_version = 0, reason;
+
+    /*
+     * Normally if something goes wrong during construction its an internal
+     * error. We can always override this later.
+     */
+    *al = SSL_AD_INTERNAL_ERROR;
 
     if (!WPACKET_start_sub_packet_u16(pkt)
                /*
                 * If extensions are of zero length then we don't even add the
 
     if (!WPACKET_start_sub_packet_u16(pkt)
                /*
                 * If extensions are of zero length then we don't even add the
-                * extensions length bytes to a ClientHello
+                * extensions length bytes to a ClientHello/ServerHello in SSLv3
                 */
                 */
-            || ((context & EXT_CLIENT_HELLO) != 0
+            || ((context & (EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO)) != 0
+               && s->version == SSL3_VERSION
                && !WPACKET_set_flags(pkt,
                                      WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH))) {
                && !WPACKET_set_flags(pkt,
                                      WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH))) {
-        *al = SSL_AD_INTERNAL_ERROR;
+        SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, ERR_R_INTERNAL_ERROR);
+        return 0;
+    }
+
+    if ((context & EXT_CLIENT_HELLO) != 0) {
+        reason = ssl_get_client_min_max_version(s, &min_version, &max_version);
+        if (reason != 0) {
+            SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, reason);
+            return 0;
+        }
+    }
+
+    /* Add custom extensions first */
+    if ((context & EXT_CLIENT_HELLO) != 0) {
+        custom_ext_init(&s->cert->cli_ext);
+        addcustom = 1;
+    } else if ((context & EXT_TLS1_2_SERVER_HELLO) != 0) {
+        /*
+         * We already initialised the custom extensions during ClientHello
+         * parsing.
+         * 
+         * TODO(TLS1.3): We're going to need a new custom extension mechanism
+         * for TLS1.3, so that custom extensions can specify which of the
+         * multiple message they wish to add themselves to.
+         */
+        addcustom = 1;
+    }
+
+    if (addcustom && !custom_ext_add(s, s->server, pkt, al)) {
         SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, ERR_R_INTERNAL_ERROR);
         return 0;
     }
         SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, ERR_R_INTERNAL_ERROR);
         return 0;
     }
@@ -484,8 +664,8 @@ int tls_construct_extensions(SSL *s, WPACKET *pkt, unsigned int context,
         if ((ext_defs[loop].context & context) == 0)
             continue;
 
         if ((ext_defs[loop].context & context) == 0)
             continue;
 
-        construct = s->server ? ext_defs[loop].server_construct
-                              : ext_defs[loop].client_construct;
+        construct = s->server ? ext_defs[loop].construct_server_ext
+                              : ext_defs[loop].construct_client_ext;
 
         /* Check if this extension is defined for our protocol. If not, skip */
         if ((SSL_IS_DTLS(s)
 
         /* Check if this extension is defined for our protocol. If not, skip */
         if ((SSL_IS_DTLS(s)
@@ -499,6 +679,9 @@ int tls_construct_extensions(SSL *s, WPACKET *pkt, unsigned int context,
                 || (!SSL_IS_TLS13(s)
                     && (ext_defs[loop].context & EXT_TLS1_3_ONLY) != 0
                     && (context & EXT_CLIENT_HELLO) == 0)
                 || (!SSL_IS_TLS13(s)
                     && (ext_defs[loop].context & EXT_TLS1_3_ONLY) != 0
                     && (context & EXT_CLIENT_HELLO) == 0)
+                || ((ext_defs[loop].context & EXT_TLS1_3_ONLY) != 0
+                    && (context & EXT_CLIENT_HELLO) != 0
+                    && (SSL_IS_DTLS(s) || max_version < TLS1_3_VERSION))
                 || construct == NULL)
             continue;
 
                 || construct == NULL)
             continue;
 
@@ -506,29 +689,7 @@ int tls_construct_extensions(SSL *s, WPACKET *pkt, unsigned int context,
             return 0;
     }
 
             return 0;
     }
 
-    /* Add custom extensions */
-    if ((context & EXT_CLIENT_HELLO) != 0) {
-        custom_ext_init(&s->cert->cli_ext);
-        addcustom = 1;
-    } else if ((context & EXT_TLS1_2_SERVER_HELLO) != 0) {
-        /*
-         * We already initialised the custom extensions during ClientHello
-         * parsing.
-         * 
-         * TODO(TLS1.3): We're going to need a new custom extension mechanism
-         * for TLS1.3, so that custom extensions can specify which of the
-         * multiple message they wish to add themselves to.
-         */
-        addcustom = 1;
-    }
-
-    if (addcustom && !custom_ext_add(s, s->server, pkt, al)) {
-        SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, ERR_R_INTERNAL_ERROR);
-        return 0;
-    }
-
     if (!WPACKET_close(pkt)) {
     if (!WPACKET_close(pkt)) {
-        *al = SSL_AD_INTERNAL_ERROR;
         SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, ERR_R_INTERNAL_ERROR);
         return 0;
     }
         SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, ERR_R_INTERNAL_ERROR);
         return 0;
     }
@@ -536,639 +697,176 @@ int tls_construct_extensions(SSL *s, WPACKET *pkt, unsigned int context,
     return 1;
 }
 
     return 1;
 }
 
-/*
- * Parse the client's renegotiation binding and abort if it's not right
- */
-static int tls_parse_clienthello_renegotiate(SSL *s, PACKET *pkt, int *al)
+static int tls_ext_final_renegotiate(SSL *s, unsigned int context, int sent,
+                                     int *al)
 {
 {
-    unsigned int ilen;
-    const unsigned char *data;
-
-    /* Parse the length byte */
-    if (!PACKET_get_1(pkt, &ilen)
-        || !PACKET_get_bytes(pkt, &data, ilen)) {
-        SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_RENEGOTIATE,
-               SSL_R_RENEGOTIATION_ENCODING_ERR);
-        *al = SSL_AD_ILLEGAL_PARAMETER;
-        return 0;
-    }
-
-    /* Check that the extension matches */
-    if (ilen != s->s3->previous_client_finished_len) {
-        SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_RENEGOTIATE,
-               SSL_R_RENEGOTIATION_MISMATCH);
-        *al = SSL_AD_HANDSHAKE_FAILURE;
-        return 0;
-    }
+    if (!s->server)
+        return 1;
 
 
-    if (memcmp(data, s->s3->previous_client_finished,
-               s->s3->previous_client_finished_len)) {
-        SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_RENEGOTIATE,
-               SSL_R_RENEGOTIATION_MISMATCH);
+    /* Need RI if renegotiating */
+    if (s->renegotiate
+            && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
+            && !sent) {
         *al = SSL_AD_HANDSHAKE_FAILURE;
         *al = SSL_AD_HANDSHAKE_FAILURE;
+        SSLerr(SSL_F_TLS_EXT_FINAL_RENEGOTIATE,
+               SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
         return 0;
     }
 
         return 0;
     }
 
-    s->s3->send_connection_binding = 1;
-
     return 1;
 }
 
     return 1;
 }
 
-static int tls_parse_clienthello_server_name(SSL *s, PACKET *pkt, int *al)
+static int tls_ext_init_server_name(SSL *s, unsigned int context)
 {
 {
-    unsigned int servname_type;
-    PACKET sni, hostname;
-
-    /*-
-     * The servername extension is treated as follows:
-     *
-     * - Only the hostname type is supported with a maximum length of 255.
-     * - The servername is rejected if too long or if it contains zeros,
-     *   in which case an fatal alert is generated.
-     * - The servername field is maintained together with the session cache.
-     * - When a session is resumed, the servername call back invoked in order
-     *   to allow the application to position itself to the right context.
-     * - The servername is acknowledged if it is new for a session or when
-     *   it is identical to a previously used for the same session.
-     *   Applications can control the behaviour.  They can at any time
-     *   set a 'desirable' servername for a new SSL object. This can be the
-     *   case for example with HTTPS when a Host: header field is received and
-     *   a renegotiation is requested. In this case, a possible servername
-     *   presented in the new client hello is only acknowledged if it matches
-     *   the value of the Host: field.
-     * - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
-     *   if they provide for changing an explicit servername context for the
-     *   session, i.e. when the session has been established with a servername
-     *   extension.
-     * - On session reconnect, the servername extension may be absent.
-     *
-     */
-    if (!PACKET_as_length_prefixed_2(pkt, &sni)
-        /* ServerNameList must be at least 1 byte long. */
-        || PACKET_remaining(&sni) == 0) {
-        *al = SSL_AD_DECODE_ERROR;
-        return 0;
-    }
-
-    /*
-     * Although the server_name extension was intended to be
-     * extensible to new name types, RFC 4366 defined the
-     * syntax inextensibility and OpenSSL 1.0.x parses it as
-     * such.
-     * RFC 6066 corrected the mistake but adding new name types
-     * is nevertheless no longer feasible, so act as if no other
-     * SNI types can exist, to simplify parsing.
-     *
-     * Also note that the RFC permits only one SNI value per type,
-     * i.e., we can only have a single hostname.
-     */
-    if (!PACKET_get_1(&sni, &servname_type)
-        || servname_type != TLSEXT_NAMETYPE_host_name
-        || !PACKET_as_length_prefixed_2(&sni, &hostname)) {
-        *al = SSL_AD_DECODE_ERROR;
-        return 0;
-    }
-
-    if (!s->hit) {
-        if (PACKET_remaining(&hostname) > TLSEXT_MAXLEN_host_name) {
-            *al = TLS1_AD_UNRECOGNIZED_NAME;
-            return 0;
-        }
-
-        if (PACKET_contains_zero_byte(&hostname)) {
-            *al = TLS1_AD_UNRECOGNIZED_NAME;
-            return 0;
-        }
-
-        if (!PACKET_strndup(&hostname, &s->session->tlsext_hostname)) {
-            *al = TLS1_AD_INTERNAL_ERROR;
-            return 0;
-        }
-
-        s->servername_done = 1;
-    } else {
-        /*
-         * TODO(openssl-team): if the SNI doesn't match, we MUST
-         * fall back to a full handshake.
-         */
-        s->servername_done = s->session->tlsext_hostname
-            && PACKET_equal(&hostname, s->session->tlsext_hostname,
-                            strlen(s->session->tlsext_hostname));
-    }
+    if (s->server)
+        s->servername_done = 0;
 
     return 1;
 }
 
 
     return 1;
 }
 
-#ifndef OPENSSL_NO_SRP
-static int tls_parse_clienthello_srp(SSL *s, PACKET *pkt, int *al)
+/* Call the servername callback. Returns 1 for success or 0 for failure. */
+static int tls_ext_final_server_name(SSL *s, unsigned int context, int sent,
+                                     int *al)
 {
 {
-    PACKET srp_I;
+    int ret = SSL_TLSEXT_ERR_NOACK;
+    int altmp = SSL_AD_UNRECOGNIZED_NAME;
 
 
-    if (!PACKET_as_length_prefixed_1(pkt, &srp_I)
-            || PACKET_contains_zero_byte(&srp_I)) {
-        *al = SSL_AD_DECODE_ERROR;
-        return 0;
-    }
-
-    /*
-     * TODO(openssl-team): currently, we re-authenticate the user
-     * upon resumption. Instead, we MUST ignore the login.
-     */
-    if (!PACKET_strndup(&srp_I, &s->srp_ctx.login)) {
-        *al = TLS1_AD_INTERNAL_ERROR;
-        return 0;
-    }
-
-    return 1;
-}
-#endif
-
-#ifndef OPENSSL_NO_EC
-static int tls_parse_clienthello_ec_pt_formats(SSL *s, PACKET *pkt, int *al)
-{
-    PACKET ec_point_format_list;
-
-    if (!PACKET_as_length_prefixed_1(pkt, &ec_point_format_list)
-        || PACKET_remaining(&ec_point_format_list) == 0) {
-        *al = SSL_AD_DECODE_ERROR;
-        return 0;
-    }
-
-    if (!s->hit) {
-        if (!PACKET_memdup(&ec_point_format_list,
-                           &s->session->tlsext_ecpointformatlist,
-                           &s->session->tlsext_ecpointformatlist_length)) {
-            *al = TLS1_AD_INTERNAL_ERROR;
-            return 0;
-        }
-    }
-
-    return 1;
-}
-#endif                          /* OPENSSL_NO_EC */
+    if (!s->server)
+        return 1;
 
 
-static int tls_parse_clienthello_session_ticket(SSL *s, PACKET *pkt, int *al)
-{
-    if (s->tls_session_ticket_ext_cb &&
-            !s->tls_session_ticket_ext_cb(s, PACKET_data(pkt),
-                                          PACKET_remaining(pkt),
-                                          s->tls_session_ticket_ext_cb_arg)) {
-        *al = TLS1_AD_INTERNAL_ERROR;
+    if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0)
+        ret = s->ctx->tlsext_servername_callback(s, &altmp,
+                                                 s->ctx->tlsext_servername_arg);
+    else if (s->initial_ctx != NULL
+             && s->initial_ctx->tlsext_servername_callback != 0)
+        ret = s->initial_ctx->tlsext_servername_callback(s, &altmp,
+                                       s->initial_ctx->tlsext_servername_arg);
+
+    switch (ret) {
+    case SSL_TLSEXT_ERR_ALERT_FATAL:
+        *al = altmp;
         return 0;
         return 0;
-    }
-
-    return 1;
-}
 
 
-static int tls_parse_clienthello_sig_algs(SSL *s, PACKET *pkt, int *al)
-{
-    PACKET supported_sig_algs;
+    case SSL_TLSEXT_ERR_ALERT_WARNING:
+        *al = altmp;
+        return 1;
 
 
-    if (!PACKET_as_length_prefixed_2(pkt, &supported_sig_algs)
-            || (PACKET_remaining(&supported_sig_algs) % 2) != 0
-            || PACKET_remaining(&supported_sig_algs) == 0) {
-        *al = SSL_AD_DECODE_ERROR;
-        return 0;
-    }
+    case SSL_TLSEXT_ERR_NOACK:
+        s->servername_done = 0;
+        return 1;
 
 
-    if (!s->hit && !tls1_save_sigalgs(s, PACKET_data(&supported_sig_algs),
-                                      PACKET_remaining(&supported_sig_algs))) {
-        *al = TLS1_AD_INTERNAL_ERROR;
-        return 0;
+    default:
+        return 1;
     }
     }
-
-    return 1;
 }
 
 }
 
-static int tls_parse_clienthello_status_request(SSL *s, PACKET *pkt, int *al)
+static int tls_ext_init_status_request(SSL *s, unsigned int context)
 {
 {
-    if (!PACKET_get_1(pkt, (unsigned int *)&s->tlsext_status_type)) {
-        *al = SSL_AD_DECODE_ERROR;
-        return 0;
-    }
-#ifndef OPENSSL_NO_OCSP
-    if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) {
-        const unsigned char *ext_data;
-        PACKET responder_id_list, exts;
-        if (!PACKET_get_length_prefixed_2 (pkt, &responder_id_list)) {
-            *al = SSL_AD_DECODE_ERROR;
-            return 0;
-        }
-
-        /*
-         * We remove any OCSP_RESPIDs from a previous handshake
-         * to prevent unbounded memory growth - CVE-2016-6304
-         */
-        sk_OCSP_RESPID_pop_free(s->tlsext_ocsp_ids, OCSP_RESPID_free);
-        if (PACKET_remaining(&responder_id_list) > 0) {
-            s->tlsext_ocsp_ids = sk_OCSP_RESPID_new_null();
-            if (s->tlsext_ocsp_ids == NULL) {
-                *al = SSL_AD_INTERNAL_ERROR;
-                return 0;
-            }
-        } else {
-            s->tlsext_ocsp_ids = NULL;
-        }
-
-        while (PACKET_remaining(&responder_id_list) > 0) {
-            OCSP_RESPID *id;
-            PACKET responder_id;
-            const unsigned char *id_data;
-
-            if (!PACKET_get_length_prefixed_2(&responder_id_list,
-                                              &responder_id)
-                    || PACKET_remaining(&responder_id) == 0) {
-                *al = SSL_AD_DECODE_ERROR;
-                return 0;
-            }
-
-            id_data = PACKET_data(&responder_id);
-            /* TODO(size_t): Convert d2i_* to size_t */
-            id = d2i_OCSP_RESPID(NULL, &id_data,
-                                 (int)PACKET_remaining(&responder_id));
-            if (id == NULL) {
-                *al = SSL_AD_DECODE_ERROR;
-                return 0;
-            }
-
-            if (id_data != PACKET_end(&responder_id)) {
-                OCSP_RESPID_free(id);
-                *al = SSL_AD_DECODE_ERROR;
-                return 0;
-            }
-
-            if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) {
-                OCSP_RESPID_free(id);
-                *al = SSL_AD_INTERNAL_ERROR;
-                return 0;
-            }
-        }
-
-        /* Read in request_extensions */
-        if (!PACKET_as_length_prefixed_2(pkt, &exts)) {
-            *al = SSL_AD_DECODE_ERROR;
-            return 0;
-        }
-
-        if (PACKET_remaining(&exts) > 0) {
-            ext_data = PACKET_data(&exts);
-            sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
-                                       X509_EXTENSION_free);
-            s->tlsext_ocsp_exts =
-                d2i_X509_EXTENSIONS(NULL, &ext_data,
-                                    (int)PACKET_remaining(&exts));
-            if (s->tlsext_ocsp_exts == NULL || ext_data != PACKET_end(&exts)) {
-                *al = SSL_AD_DECODE_ERROR;
-                return 0;
-            }
-        }
-    } else
-#endif
-    {
-        /*
-         * We don't know what to do with any other type so ignore it.
-         */
+    if (s->server)
         s->tlsext_status_type = -1;
         s->tlsext_status_type = -1;
-    }
 
     return 1;
 }
 
 #ifndef OPENSSL_NO_NEXTPROTONEG
 
     return 1;
 }
 
 #ifndef OPENSSL_NO_NEXTPROTONEG
-static int tls_parse_clienthello_npn(SSL *s, PACKET *pkt, int *al)
+static int tls_ext_init_npn(SSL *s, unsigned int context)
 {
 {
-    if (s->s3->tmp.finish_md_len == 0) {
-        /*-
-         * We shouldn't accept this extension on a
-         * renegotiation.
-         *
-         * s->new_session will be set on renegotiation, but we
-         * probably shouldn't rely that it couldn't be set on
-         * the initial renegotiation too in certain cases (when
-         * there's some other reason to disallow resuming an
-         * earlier session -- the current code won't be doing
-         * anything like that, but this might change).
-         *
-         * A valid sign that there's been a previous handshake
-         * in this connection is if s->s3->tmp.finish_md_len >
-         * 0.  (We are talking about a check that will happen
-         * in the Hello protocol round, well before a new
-         * Finished message could have been computed.)
-         */
-        s->s3->next_proto_neg_seen = 1;
-    }
+    if (s->server)
+        s->s3->next_proto_neg_seen = 0;
 
     return 1;
 }
 #endif
 
 
     return 1;
 }
 #endif
 
-/*
- * Save the ALPN extension in a ClientHello.
- * pkt: the contents of the ALPN extension, not including type and length.
- * al: a pointer to the  alert value to send in the event of a failure.
- * returns: 1 on success, 0 on error.
- */
-static int tls_parse_clienthello_alpn(SSL *s, PACKET *pkt, int *al)
-{
-    PACKET protocol_list, save_protocol_list, protocol;
-
-    if (s->s3->tmp.finish_md_len != 0)
-        return 1;
-
-    if (!PACKET_as_length_prefixed_2(pkt, &protocol_list)
-        || PACKET_remaining(&protocol_list) < 2) {
-        *al = SSL_AD_DECODE_ERROR;
-        return 0;
-    }
-
-    save_protocol_list = protocol_list;
-    do {
-        /* Protocol names can't be empty. */
-        if (!PACKET_get_length_prefixed_1(&protocol_list, &protocol)
-                || PACKET_remaining(&protocol) == 0) {
-            *al = SSL_AD_DECODE_ERROR;
-            return 0;
-        }
-    } while (PACKET_remaining(&protocol_list) != 0);
-
-    if (!PACKET_memdup(&save_protocol_list,
-                       &s->s3->alpn_proposed, &s->s3->alpn_proposed_len)) {
-        *al = TLS1_AD_INTERNAL_ERROR;
-        return 0;
-    }
-
-    return 1;
-}
-
-#ifndef OPENSSL_NO_SRTP
-static int tls_parse_clienthello_use_srtp(SSL *s, PACKET *pkt, int *al)
+static int tls_ext_init_alpn(SSL *s, unsigned int context)
 {
 {
-    SRTP_PROTECTION_PROFILE *sprof;
-    STACK_OF(SRTP_PROTECTION_PROFILE) *srvr;
-    unsigned int ct, mki_len, id;
-    int i, srtp_pref;
-    PACKET subpkt;
-
-    /* Ignore this if we have no SRTP profiles */
-    if (SSL_get_srtp_profiles(s) == NULL)
-        return 1;
-
-    /* Pull off the length of the cipher suite list  and check it is even */
-    if (!PACKET_get_net_2(pkt, &ct)
-        || (ct & 1) != 0 || !PACKET_get_sub_packet(pkt, &subpkt, ct)) {
-        SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_USE_SRTP,
-               SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
-        *al = SSL_AD_DECODE_ERROR;
-        return 0;
-    }
-
-    srvr = SSL_get_srtp_profiles(s);
-    s->srtp_profile = NULL;
-    /* Search all profiles for a match initially */
-    srtp_pref = sk_SRTP_PROTECTION_PROFILE_num(srvr);
-
-    while (PACKET_remaining(&subpkt)) {
-        if (!PACKET_get_net_2(&subpkt, &id)) {
-            SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_USE_SRTP,
-                   SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
-            *al = SSL_AD_DECODE_ERROR;
-            return 0;
-        }
-
-        /*
-         * Only look for match in profiles of higher preference than
-         * current match.
-         * If no profiles have been have been configured then this
-         * does nothing.
-         */
-        for (i = 0; i < srtp_pref; i++) {
-            sprof = sk_SRTP_PROTECTION_PROFILE_value(srvr, i);
-            if (sprof->id == id) {
-                s->srtp_profile = sprof;
-                srtp_pref = i;
-                break;
-            }
-        }
-    }
-
-    /*
-     * Now extract the MKI value as a sanity check, but discard it for now
-     */
-    if (!PACKET_get_1(pkt, &mki_len)) {
-        SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_USE_SRTP,
-               SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
-        *al = SSL_AD_DECODE_ERROR;
-        return 0;
-    }
-
-    if (!PACKET_forward(pkt, mki_len)
-        || PACKET_remaining(pkt)) {
-        SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_USE_SRTP, SSL_R_BAD_SRTP_MKI_VALUE);
-        *al = SSL_AD_DECODE_ERROR;
-        return 0;
+    if (s->server) {
+        OPENSSL_free(s->s3->alpn_selected);
+        s->s3->alpn_selected = NULL;
+        s->s3->alpn_selected_len = 0;
+        OPENSSL_free(s->s3->alpn_proposed);
+        s->s3->alpn_proposed = NULL;
+        s->s3->alpn_proposed_len = 0;
     }
 
     return 1;
 }
     }
 
     return 1;
 }
-#endif
 
 
-static int tls_parse_clienthello_etm(SSL *s, PACKET *pkt, int *al)
-{
-    if (!(s->options & SSL_OP_NO_ENCRYPT_THEN_MAC))
-        s->s3->flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC;
 
 
-    return 1;
-}
 
 /*
 
 /*
- * Checks a list of |groups| to determine if the |group_id| is in it. If it is
- * and |checkallow| is 1 then additionally check if the group is allowed to be
- * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
- * 1) or 0 otherwise.
+ * Process the ALPN extension in a ClientHello.
+ * al: a pointer to the alert value to send in the event of a failure.
+ * returns 1 on success, 0 on error.
  */
  */
-static int check_in_list(SSL *s, unsigned int group_id,
-                         const unsigned char *groups, size_t num_groups,
-                         int checkallow)
+static int tls_ext_final_alpn(SSL *s, unsigned int context, int sent, int *al)
 {
 {
-    size_t i;
-
-    if (groups == NULL || num_groups == 0)
-        return 0;
-
-    for (i = 0; i < num_groups; i++, groups += 2) {
-        unsigned int share_id = (groups[0] << 8) | (groups[1]);
-
-        if (group_id == share_id
-                && (!checkallow || tls_curve_allowed(s, groups,
-                                                     SSL_SECOP_CURVE_CHECK))) {
-            break;
-        }
-    }
+    const unsigned char *selected = NULL;
+    unsigned char selected_len = 0;
 
 
-    /* If i == num_groups then not in the list */
-    return i < num_groups;
-}
-
-/*
- * Process a key_share extension received in the ClientHello. |pkt| contains
- * the raw PACKET data for the extension. Returns 1 on success or 0 on failure.
- * If a failure occurs then |*al| is set to an appropriate alert value.
- */
-static int tls_parse_clienthello_key_share(SSL *s, PACKET *pkt, int *al)
-{
-    unsigned int group_id;
-    PACKET key_share_list, encoded_pt;
-    const unsigned char *clntcurves, *srvrcurves;
-    size_t clnt_num_curves, srvr_num_curves;
-    int group_nid, found = 0;
-    unsigned int curve_flags;
-
-    if (s->hit)
+    if (!s->server)
         return 1;
 
         return 1;
 
-    /* Sanity check */
-    if (s->s3->peer_tmp != NULL) {
-        *al = SSL_AD_INTERNAL_ERROR;
-        SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_KEY_SHARE, ERR_R_INTERNAL_ERROR);
-        return 0;
-    }
-
-    if (!PACKET_as_length_prefixed_2(pkt, &key_share_list)) {
-        *al = SSL_AD_HANDSHAKE_FAILURE;
-        SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_KEY_SHARE, SSL_R_LENGTH_MISMATCH);
-        return 0;
-    }
-
-    /* Get our list of supported curves */
-    if (!tls1_get_curvelist(s, 0, &srvrcurves, &srvr_num_curves)) {
-        *al = SSL_AD_INTERNAL_ERROR;
-        SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_KEY_SHARE, ERR_R_INTERNAL_ERROR);
-        return 0;
-    }
-
-    /* Get the clients list of supported curves */
-    if (!tls1_get_curvelist(s, 1, &clntcurves, &clnt_num_curves)) {
-        *al = SSL_AD_INTERNAL_ERROR;
-        SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_KEY_SHARE, ERR_R_INTERNAL_ERROR);
-        return 0;
-    }
-
-    while (PACKET_remaining(&key_share_list) > 0) {
-        if (!PACKET_get_net_2(&key_share_list, &group_id)
-                || !PACKET_get_length_prefixed_2(&key_share_list, &encoded_pt)
-                || PACKET_remaining(&encoded_pt) == 0) {
-            *al = SSL_AD_HANDSHAKE_FAILURE;
-            SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_KEY_SHARE,
-                   SSL_R_LENGTH_MISMATCH);
-            return 0;
-        }
-
-        /*
-         * If we already found a suitable key_share we loop through the
-         * rest to verify the structure, but don't process them.
-         */
-        if (found)
-            continue;
+    if (s->ctx->alpn_select_cb != NULL && s->s3->alpn_proposed != NULL) {
+        int r = s->ctx->alpn_select_cb(s, &selected, &selected_len,
+                                       s->s3->alpn_proposed,
+                                       (unsigned int)s->s3->alpn_proposed_len,
+                                       s->ctx->alpn_select_cb_arg);
 
 
-        /* Check if this share is in supported_groups sent from client */
-        if (!check_in_list(s, group_id, clntcurves, clnt_num_curves, 0)) {
-            *al = SSL_AD_HANDSHAKE_FAILURE;
-            SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_KEY_SHARE, SSL_R_BAD_KEY_SHARE);
-            return 0;
-        }
-
-        /* Check if this share is for a group we can use */
-        if (!check_in_list(s, group_id, srvrcurves, srvr_num_curves, 1)) {
-            /* Share not suitable */
-            continue;
-        }
-
-        group_nid = tls1_ec_curve_id2nid(group_id, &curve_flags);
-
-        if (group_nid == 0) {
-            *al = SSL_AD_INTERNAL_ERROR;
-            SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_KEY_SHARE,
-                   SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
-            return 0;
-        }
-
-        if ((curve_flags & TLS_CURVE_TYPE) == TLS_CURVE_CUSTOM) {
-            /* Can happen for some curves, e.g. X25519 */
-            EVP_PKEY *key = EVP_PKEY_new();
-
-            if (key == NULL || !EVP_PKEY_set_type(key, group_nid)) {
+        if (r == SSL_TLSEXT_ERR_OK) {
+            OPENSSL_free(s->s3->alpn_selected);
+            s->s3->alpn_selected = OPENSSL_memdup(selected, selected_len);
+            if (s->s3->alpn_selected == NULL) {
                 *al = SSL_AD_INTERNAL_ERROR;
                 *al = SSL_AD_INTERNAL_ERROR;
-                SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_KEY_SHARE, ERR_R_EVP_LIB);
-                EVP_PKEY_free(key);
                 return 0;
             }
                 return 0;
             }
-            s->s3->peer_tmp = key;
+            s->s3->alpn_selected_len = selected_len;
+#ifndef OPENSSL_NO_NEXTPROTONEG
+            /* ALPN takes precedence over NPN. */
+            s->s3->next_proto_neg_seen = 0;
+#endif
         } else {
         } else {
-            /* Set up EVP_PKEY with named curve as parameters */
-            EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL);
-            if (pctx == NULL
-                    || EVP_PKEY_paramgen_init(pctx) <= 0
-                    || EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx,
-                                                              group_nid) <= 0
-                    || EVP_PKEY_paramgen(pctx, &s->s3->peer_tmp) <= 0) {
-                *al = SSL_AD_INTERNAL_ERROR;
-                SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_KEY_SHARE, ERR_R_EVP_LIB);
-                EVP_PKEY_CTX_free(pctx);
-                return 0;
-            }
-            EVP_PKEY_CTX_free(pctx);
-            pctx = NULL;
-        }
-        s->s3->group_id = group_id;
-
-        if (!EVP_PKEY_set1_tls_encodedpoint(s->s3->peer_tmp,
-                PACKET_data(&encoded_pt),
-                PACKET_remaining(&encoded_pt))) {
-            *al = SSL_AD_DECODE_ERROR;
-            SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_KEY_SHARE, SSL_R_BAD_ECPOINT);
+            *al = SSL_AD_NO_APPLICATION_PROTOCOL;
             return 0;
         }
             return 0;
         }
-
-        found = 1;
     }
 
     return 1;
 }
 
     }
 
     return 1;
 }
 
-#ifndef OPENSSL_NO_EC
-static int tls_parse_clienthello_supported_groups(SSL *s, PACKET *pkt, int *al)
+static int tls_ext_init_sig_algs(SSL *s, unsigned int context)
 {
 {
-    PACKET supported_groups_list;
+    /* Clear any signature algorithms extension received */
+    OPENSSL_free(s->s3->tmp.peer_sigalgs);
+    s->s3->tmp.peer_sigalgs = NULL;
 
 
-    /* Each group is 2 bytes and we must have at least 1. */
-    if (!PACKET_as_length_prefixed_2(pkt, &supported_groups_list)
-            || PACKET_remaining(&supported_groups_list) == 0
-            || (PACKET_remaining(&supported_groups_list) % 2) != 0) {
-        *al = SSL_AD_DECODE_ERROR;
-        return 0;
-    }
+    return 1;
+}
 
 
-    if (!s->hit
-            && !PACKET_memdup(&supported_groups_list,
-                              &s->session->tlsext_supportedgroupslist,
-                              &s->session->tlsext_supportedgroupslist_length)) {
-        *al = SSL_AD_DECODE_ERROR;
-        return 0;
-    }
+#ifndef OPENSSL_NO_SRP
+static int tls_ext_init_srp(SSL *s, unsigned int context)
+{
+    OPENSSL_free(s->srp_ctx.login);
+    s->srp_ctx.login = NULL;
 
     return 1;
 }
 #endif
 
 
     return 1;
 }
 #endif
 
-static int tls_parse_clienthello_ems(SSL *s, PACKET *pkt, int *al)
+static int tls_ext_init_etm(SSL *s, unsigned int context)
 {
 {
-    /* The extension must always be empty */
-    if (PACKET_remaining(pkt) != 0) {
-        *al = SSL_AD_DECODE_ERROR;
-        return 0;
-    }
+    if (s->server)
+        s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;
 
 
-    s->s3->flags |= TLS1_FLAGS_RECEIVED_EXTMS;
+    return 1;
+}
+
+#ifndef OPENSSL_NO_SRTP
+static int tls_ext_init_srtp(SSL *s, unsigned int context)
+{
+    if (s->server)
+        s->srtp_profile = NULL;
 
     return 1;
 }
 
     return 1;
 }
+#endif