[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Bug#1003484: bullseye-pu: package openssl/1.1.1m-0+deb11u1



Package: release.debian.org
User: release.debian.org@packages.debian.org
Usertags: pu
Tags: bullseye
Severity: normal

This is an update to the latest stable update of the openssl package
provided by upstream. It contains fixes for bugs which were not
identified as security critical but still worth fixing.

The m release is in unstable the 24th December with no regression
reports so far. I haven't seen any fixes for regression in the stable
branch as of now. The testsuite passed for Bullseye during package
build and I deployed on a VM for testing (with nginx and openvpn
instance).

Once this is done, I would continue in #959469.

Sebastian
diff -Nru openssl-1.1.1k/apps/ciphers.c openssl-1.1.1m/apps/ciphers.c
--- openssl-1.1.1k/apps/ciphers.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/apps/ciphers.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -172,6 +172,7 @@
     if (convert != NULL) {
         BIO_printf(bio_out, "OpenSSL cipher name: %s\n",
                    OPENSSL_cipher_name(convert));
+        ret = 0;
         goto end;
     }
 
diff -Nru openssl-1.1.1k/apps/crl2p7.c openssl-1.1.1m/apps/crl2p7.c
--- openssl-1.1.1k/apps/crl2p7.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/apps/crl2p7.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -120,19 +120,20 @@
 
     if (!ASN1_INTEGER_set(p7s->version, 1))
         goto end;
-    if ((crl_stack = sk_X509_CRL_new_null()) == NULL)
-        goto end;
-    p7s->crl = crl_stack;
+
     if (crl != NULL) {
+        if ((crl_stack = sk_X509_CRL_new_null()) == NULL)
+            goto end;
+        p7s->crl = crl_stack;
         sk_X509_CRL_push(crl_stack, crl);
         crl = NULL;             /* now part of p7 for OPENSSL_freeing */
     }
 
-    if ((cert_stack = sk_X509_new_null()) == NULL)
-        goto end;
-    p7s->cert = cert_stack;
+    if (certflst != NULL) {
+        if ((cert_stack = sk_X509_new_null()) == NULL)
+            goto end;
+        p7s->cert = cert_stack;
 
-    if (certflst != NULL)
         for (i = 0; i < sk_OPENSSL_STRING_num(certflst); i++) {
             certfile = sk_OPENSSL_STRING_value(certflst, i);
             if (add_certs_from_file(cert_stack, certfile) < 0) {
@@ -141,6 +142,7 @@
                 goto end;
             }
         }
+    }
 
     out = bio_open_default(outfile, 'w', outformat);
     if (out == NULL)
diff -Nru openssl-1.1.1k/apps/dgst.c openssl-1.1.1m/apps/dgst.c
--- openssl-1.1.1k/apps/dgst.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/apps/dgst.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -316,7 +316,7 @@
         EVP_MD_CTX *mctx = NULL;
         EVP_PKEY_CTX *pctx = NULL;
         int r;
-        if (!BIO_get_md_ctx(bmd, &mctx)) {
+        if (BIO_get_md_ctx(bmd, &mctx) <= 0) {
             BIO_printf(bio_err, "Error getting context\n");
             ERR_print_errors(bio_err);
             goto end;
@@ -345,7 +345,7 @@
     /* we use md as a filter, reading from 'in' */
     else {
         EVP_MD_CTX *mctx = NULL;
-        if (!BIO_get_md_ctx(bmd, &mctx)) {
+        if (BIO_get_md_ctx(bmd, &mctx) <= 0) {
             BIO_printf(bio_err, "Error getting context\n");
             ERR_print_errors(bio_err);
             goto end;
diff -Nru openssl-1.1.1k/apps/enc.c openssl-1.1.1m/apps/enc.c
--- openssl-1.1.1k/apps/enc.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/apps/enc.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -81,7 +81,7 @@
     {"", OPT_CIPHER, '-', "Any supported cipher"},
     OPT_R_OPTIONS,
 #ifdef ZLIB
-    {"z", OPT_Z, '-', "Use zlib as the 'encryption'"},
+    {"z", OPT_Z, '-', "Compress or decompress encrypted data using zlib"},
 #endif
 #ifndef OPENSSL_NO_ENGINE
     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
diff -Nru openssl-1.1.1k/apps/s_cb.c openssl-1.1.1m/apps/s_cb.c
--- openssl-1.1.1k/apps/s_cb.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/apps/s_cb.c	2021-12-14 16:45:01.000000000 +0100
@@ -819,7 +819,9 @@
 {
     unsigned int temp;
     int res = generate_cookie_callback(ssl, cookie, &temp);
-    *cookie_len = temp;
+
+    if (res != 0)
+        *cookie_len = temp;
     return res;
 }
 
diff -Nru openssl-1.1.1k/apps/s_client.c openssl-1.1.1m/apps/s_client.c
--- openssl-1.1.1k/apps/s_client.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/apps/s_client.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  * Copyright 2005 Nokia. All rights reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
@@ -3151,6 +3151,8 @@
 #endif
     OPENSSL_free(connectstr);
     OPENSSL_free(bindstr);
+    OPENSSL_free(bindhost);
+    OPENSSL_free(bindport);
     OPENSSL_free(host);
     OPENSSL_free(port);
     X509_VERIFY_PARAM_free(vpm);
diff -Nru openssl-1.1.1k/apps/speed.c openssl-1.1.1m/apps/speed.c
--- openssl-1.1.1k/apps/speed.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/apps/speed.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
@@ -1590,6 +1590,10 @@
         case OPT_MULTI:
 #ifndef NO_FORK
             multi = atoi(opt_arg());
+            if (multi >= INT_MAX / (int)sizeof(int)) {
+                BIO_printf(bio_err, "%s: multi argument too large\n", prog);
+                return 0;
+            }
 #endif
             break;
         case OPT_ASYNCJOBS:
@@ -3490,7 +3494,7 @@
             close(fd[1]);
             mr = 1;
             usertime = 0;
-            free(fds);
+            OPENSSL_free(fds);
             return 0;
         }
         printf("Forked child %d\n", n);
@@ -3603,7 +3607,7 @@
 
         fclose(f);
     }
-    free(fds);
+    OPENSSL_free(fds);
     return 1;
 }
 #endif
diff -Nru openssl-1.1.1k/apps/s_server.c openssl-1.1.1m/apps/s_server.c
--- openssl-1.1.1k/apps/s_server.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/apps/s_server.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
  * Copyright 2005 Nokia. All rights reserved.
  *
@@ -133,6 +133,17 @@
 
     if (s_debug)
         BIO_printf(bio_s_out, "psk_server_cb\n");
+
+    if (!SSL_is_dtls(ssl) && SSL_version(ssl) >= TLS1_3_VERSION) {
+        /*
+         * This callback is designed for use in (D)TLSv1.2 (or below). It is
+         * possible to use a single callback for all protocol versions - but it
+         * is preferred to use a dedicated callback for TLSv1.3. For TLSv1.3 we
+         * have psk_find_session_cb.
+         */
+        return 0;
+    }
+
     if (identity == NULL) {
         BIO_printf(bio_err, "Error: client did not send PSK identity\n");
         goto out_err;
diff -Nru openssl-1.1.1k/apps/s_socket.c openssl-1.1.1m/apps/s_socket.c
--- openssl-1.1.1k/apps/s_socket.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/apps/s_socket.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -214,6 +214,8 @@
     const BIO_ADDRINFO *next;
     int sock_family, sock_type, sock_protocol, sock_port;
     const BIO_ADDR *sock_address;
+    int sock_family_fallback = AF_UNSPEC;
+    const BIO_ADDR *sock_address_fallback = NULL;
     int sock_options = BIO_SOCK_REUSEADDR;
     int ret = 0;
 
@@ -244,6 +246,10 @@
             && BIO_ADDRINFO_protocol(next) == sock_protocol) {
         if (sock_family == AF_INET
                 && BIO_ADDRINFO_family(next) == AF_INET6) {
+            /* In case AF_INET6 is returned but not supported by the
+             * kernel, retry with the first detected address family */
+            sock_family_fallback = sock_family;
+            sock_address_fallback = sock_address;
             sock_family = AF_INET6;
             sock_address = BIO_ADDRINFO_address(next);
         } else if (sock_family == AF_INET6
@@ -253,6 +259,10 @@
     }
 
     asock = BIO_socket(sock_family, sock_type, sock_protocol, 0);
+    if (asock == INVALID_SOCKET && sock_family_fallback != AF_UNSPEC) {
+        asock = BIO_socket(sock_family_fallback, sock_type, sock_protocol, 0);
+        sock_address = sock_address_fallback;
+    }
     if (asock == INVALID_SOCKET
         || !BIO_listen(asock, sock_address, sock_options)) {
         BIO_ADDRINFO_free(res);
diff -Nru openssl-1.1.1k/CHANGES openssl-1.1.1m/CHANGES
--- openssl-1.1.1k/CHANGES	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/CHANGES	2021-12-14 16:45:01.000000000 +0100
@@ -7,6 +7,91 @@
  https://github.com/openssl/openssl/commits/ and pick the appropriate
  release branch.
 
+ Changes between 1.1.1l and 1.1.1m [14 Dec 2021]
+
+  *) Avoid loading of a dynamic engine twice.
+
+     [Bernd Edlinger]
+
+  *) Fixed building on Debian with kfreebsd kernels
+
+     [Mattias Ellert]
+
+  *) Prioritise DANE TLSA issuer certs over peer certs
+
+     [Viktor Dukhovni]
+
+  *) Fixed random API for MacOS prior to 10.12
+
+     These MacOS versions don't support the CommonCrypto APIs
+
+     [Lenny Primak]
+
+ Changes between 1.1.1k and 1.1.1l [24 Aug 2021]
+
+  *) Fixed an SM2 Decryption Buffer Overflow.
+
+     In order to decrypt SM2 encrypted data an application is expected to call the
+     API function EVP_PKEY_decrypt(). Typically an application will call this
+     function twice. The first time, on entry, the "out" parameter can be NULL and,
+     on exit, the "outlen" parameter is populated with the buffer size required to
+     hold the decrypted plaintext. The application can then allocate a sufficiently
+     sized buffer and call EVP_PKEY_decrypt() again, but this time passing a non-NULL
+     value for the "out" parameter.
+
+     A bug in the implementation of the SM2 decryption code means that the
+     calculation of the buffer size required to hold the plaintext returned by the
+     first call to EVP_PKEY_decrypt() can be smaller than the actual size required by
+     the second call. This can lead to a buffer overflow when EVP_PKEY_decrypt() is
+     called by the application a second time with a buffer that is too small.
+
+     A malicious attacker who is able present SM2 content for decryption to an
+     application could cause attacker chosen data to overflow the buffer by up to a
+     maximum of 62 bytes altering the contents of other data held after the
+     buffer, possibly changing application behaviour or causing the application to
+     crash. The location of the buffer is application dependent but is typically
+     heap allocated.
+     (CVE-2021-3711)
+     [Matt Caswell]
+
+  *) Fixed various read buffer overruns processing ASN.1 strings
+
+     ASN.1 strings are represented internally within OpenSSL as an ASN1_STRING
+     structure which contains a buffer holding the string data and a field holding
+     the buffer length. This contrasts with normal C strings which are repesented as
+     a buffer for the string data which is terminated with a NUL (0) byte.
+
+     Although not a strict requirement, ASN.1 strings that are parsed using OpenSSL's
+     own "d2i" functions (and other similar parsing functions) as well as any string
+     whose value has been set with the ASN1_STRING_set() function will additionally
+     NUL terminate the byte array in the ASN1_STRING structure.
+
+     However, it is possible for applications to directly construct valid ASN1_STRING
+     structures which do not NUL terminate the byte array by directly setting the
+     "data" and "length" fields in the ASN1_STRING array. This can also happen by
+     using the ASN1_STRING_set0() function.
+
+     Numerous OpenSSL functions that print ASN.1 data have been found to assume that
+     the ASN1_STRING byte array will be NUL terminated, even though this is not
+     guaranteed for strings that have been directly constructed. Where an application
+     requests an ASN.1 structure to be printed, and where that ASN.1 structure
+     contains ASN1_STRINGs that have been directly constructed by the application
+     without NUL terminating the "data" field, then a read buffer overrun can occur.
+
+     The same thing can also occur during name constraints processing of certificates
+     (for example if a certificate has been directly constructed by the application
+     instead of loading it via the OpenSSL parsing functions, and the certificate
+     contains non NUL terminated ASN1_STRING structures). It can also occur in the
+     X509_get1_email(), X509_REQ_get1_email() and X509_get1_ocsp() functions.
+
+     If a malicious actor can cause an application to directly construct an
+     ASN1_STRING and then process it through one of the affected OpenSSL functions
+     then this issue could be hit. This might result in a crash (causing a Denial of
+     Service attack). It could also result in the disclosure of private memory
+     contents (such as private keys, or sensitive plaintext).
+     (CVE-2021-3712)
+     [Matt Caswell]
+
  Changes between 1.1.1j and 1.1.1k [25 Mar 2021]
 
   *) Fixed a problem with verifying a certificate chain when using the
diff -Nru openssl-1.1.1k/Configurations/10-main.conf openssl-1.1.1m/Configurations/10-main.conf
--- openssl-1.1.1k/Configurations/10-main.conf	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/Configurations/10-main.conf	2021-12-14 16:45:01.000000000 +0100
@@ -754,6 +754,13 @@
         multilib         => "64",
     },
 
+    # riscv64 below refers to contemporary RISCV Architecture
+    # specifications,
+    "linux64-riscv64" => {
+        inherit_from     => [ "linux-generic64"],
+        perlasm_scheme   => "linux64",
+    },
+
     #### IA-32 targets...
     #### These two targets are a bit aged and are to be used on older Linux
     #### machines where gcc doesn't understand -m32 and -m64
diff -Nru openssl-1.1.1k/Configurations/15-android.conf openssl-1.1.1m/Configurations/15-android.conf
--- openssl-1.1.1k/Configurations/15-android.conf	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/Configurations/15-android.conf	2021-12-14 16:45:01.000000000 +0100
@@ -29,18 +29,18 @@
                 $ndk = $ENV{$ndk_var};
                 last if defined $ndk;
             }
-            die "\$ANDROID_NDK_HOME is not defined"  if (!$ndk);
-            if (!-d "$ndk/platforms" && !-f "$ndk/AndroidVersion.txt") {
-                # $ndk/platforms is traditional "all-inclusive" NDK, while
-                # $ndk/AndroidVersion.txt is so-called standalone toolchain
-                # tailored for specific target down to API level.
+            die "\$ANDROID_NDK_HOME is not defined" if (!$ndk);
+            my $is_standalone_toolchain = -f "$ndk/AndroidVersion.txt";
+            my $ndk_src_props = "$ndk/source.properties";
+            my $is_ndk = -f $ndk_src_props;
+            if ($is_ndk == $is_standalone_toolchain) {
                 die "\$ANDROID_NDK_HOME=$ndk is invalid";
             }
             $ndk = canonpath($ndk);
 
             my $ndkver = undef;
 
-            if (open my $fh, "<$ndk/source.properties") {
+            if (open my $fh, "<$ndk_src_props") {
                 local $_;
                 while(<$fh>) {
                     if (m|Pkg\.Revision\s*=\s*([0-9]+)|) {
@@ -59,7 +59,7 @@
             if ($sysroot = $ENV{CROSS_SYSROOT}) {
                 $sysroot =~ m|/android-([0-9]+)/arch-(\w+)/?$|;
                 ($api, $arch) = ($1, $2);
-            } elsif (-f "$ndk/AndroidVersion.txt") {
+            } elsif ($is_standalone_toolchain) {
                 $sysroot = "$ndk/sysroot";
             } else {
                 $api = "*";
@@ -72,17 +72,31 @@
                     }
                 }
 
-                # list available platforms (numerically)
-                my @platforms = sort { $a =~ m/-([0-9]+)$/; my $aa = $1;
-                                       $b =~ m/-([0-9]+)$/; $aa <=> $1;
-                                     } glob("$ndk/platforms/android-$api");
-                die "no $ndk/platforms/android-$api" if ($#platforms < 0);
-
-                $sysroot = "@platforms[$#platforms]/arch-$arch";
-                $sysroot =~ m|/android-([0-9]+)/arch-$arch|;
-                $api = $1;
+                if (-d "$ndk/platforms") {
+                    # list available platforms (numerically)
+                    my @platforms = sort { $a =~ m/-([0-9]+)$/; my $aa = $1;
+                                           $b =~ m/-([0-9]+)$/; $aa <=> $1;
+                                         } glob("$ndk/platforms/android-$api");
+                    die "no $ndk/platforms/android-$api" if ($#platforms < 0);
+
+                    $sysroot = "@platforms[$#platforms]/arch-$arch";
+                    $sysroot =~ m|/android-([0-9]+)/arch-$arch|;
+                    $api = $1;
+                } elsif ($api eq "*") {
+                    # r22 Removed platforms dir, use this JSON file
+                    my $path = "$ndk/meta/platforms.json";
+                    open my $fh, $path or die "Could not open '$path' $!";
+                    while (<$fh>) {
+                        if (/"max": (\d+),/) {
+                            $api = $1;
+                            last;
+                        }
+                    }
+                    close $fh;
+                }
+                die "Could not get default API Level" if ($api eq "*");
             }
-            die "no sysroot=$sysroot"   if (!-d $sysroot);
+            die "no sysroot=$sysroot" if (length $sysroot && !-d $sysroot);
 
             my $triarch = $triplet{$arch};
             my $cflags;
@@ -95,17 +109,21 @@
                 my $arm = $ndkver > 16 ? "armv7a" : "armv5te";
                 (my $tridefault = $triarch) =~ s/^arm-/$arm-/;
                 (my $tritools   = $triarch) =~ s/(?:x|i6)86(_64)?-.*/x86$1/;
-                $cflags .= " -target $tridefault "
-                        .  "-gcc-toolchain \$($ndk_var)/toolchains"
-                        .  "/$tritools-4.9/prebuilt/$host";
-                $user{CC} = "clang" if ($user{CC} !~ m|clang|);
+                if (length $sysroot) {
+                    $cflags .= " -target $tridefault "
+                            .  "-gcc-toolchain \$($ndk_var)/toolchains"
+                            .  "/$tritools-4.9/prebuilt/$host";
+                    $user{CC} = "clang" if ($user{CC} !~ m|clang|);
+                } else {
+                    $user{CC} = "$tridefault$api-clang";
+                }
                 $user{CROSS_COMPILE} = undef;
                 if (which("llvm-ar") =~ m|^$ndk/.*/prebuilt/([^/]+)/|) {
                     $user{AR} = "llvm-ar";
                     $user{ARFLAGS} = [ "rs" ];
                     $user{RANLIB} = ":";
                 }
-            } elsif (-f "$ndk/AndroidVersion.txt") {    #"standalone toolchain"
+            } elsif ($is_standalone_toolchain) {
                 my $cc = $user{CC} // "clang";
                 # One can probably argue that both clang and gcc should be
                 # probed, but support for "standalone toolchain" was added
@@ -127,19 +145,21 @@
                 $user{CROSS_COMPILE} = "$triarch-";
             }
 
-            if (!-d "$sysroot/usr/include") {
-                my $incroot = "$ndk/sysroot/usr/include";
-                die "no $incroot"          if (!-d $incroot);
-                die "no $incroot/$triarch" if (!-d "$incroot/$triarch");
-                $incroot =~ s|^$ndk/||;
-                $cppflags  = "-D__ANDROID_API__=$api";
-                $cppflags .= " -isystem \$($ndk_var)/$incroot/$triarch";
-                $cppflags .= " -isystem \$($ndk_var)/$incroot";
+            if (length $sysroot) {
+                if (!-d "$sysroot/usr/include") {
+                    my $incroot = "$ndk/sysroot/usr/include";
+                    die "no $incroot"          if (!-d $incroot);
+                    die "no $incroot/$triarch" if (!-d "$incroot/$triarch");
+                    $incroot =~ s|^$ndk/||;
+                    $cppflags  = "-D__ANDROID_API__=$api";
+                    $cppflags .= " -isystem \$($ndk_var)/$incroot/$triarch";
+                    $cppflags .= " -isystem \$($ndk_var)/$incroot";
+                }
+                $sysroot =~ s|^$ndk/||;
+                $sysroot = " --sysroot=\$($ndk_var)/$sysroot";
             }
-
-            $sysroot =~ s|^$ndk/||;
             $android_ndk = {
-                cflags   => "$cflags --sysroot=\$($ndk_var)/$sysroot",
+                cflags   => $cflags . $sysroot,
                 cppflags => $cppflags,
                 bn_ops   => $arch =~ m/64$/ ? "SIXTY_FOUR_BIT_LONG"
                                             : "BN_LLONG",
diff -Nru openssl-1.1.1k/Configurations/unix-Makefile.tmpl openssl-1.1.1m/Configurations/unix-Makefile.tmpl
--- openssl-1.1.1k/Configurations/unix-Makefile.tmpl	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/Configurations/unix-Makefile.tmpl	2021-12-14 16:45:01.000000000 +0100
@@ -523,7 +523,6 @@
 	$(RM) -r test/test-runs
 	$(RM) openssl.pc libcrypto.pc libssl.pc
 	-$(RM) `find . -type l \! -name '.*' -print`
-	$(RM) $(TARFILE)
 
 distclean: clean
 	$(RM) configdata.pm
diff -Nru openssl-1.1.1k/Configurations/windows-makefile.tmpl openssl-1.1.1m/Configurations/windows-makefile.tmpl
--- openssl-1.1.1k/Configurations/windows-makefile.tmpl	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/Configurations/windows-makefile.tmpl	2021-12-14 16:45:01.000000000 +0100
@@ -324,15 +324,15 @@
 # Convenience target to prebuild all generated files, not just the mandatory
 # ones
 build_all_generated: $(GENERATED_MANDATORY) $(GENERATED)
-	@{- output_off() if $disabled{makedepend}; "" -}
+	@{- output_off() if $disabled{makedepend}; "\@rem" -}
 	@$(ECHO) "Warning: consider configuring with no-makedepend, because if"
 	@$(ECHO) "         target system doesn't have $(PERL),"
 	@$(ECHO) "         then make will fail..."
-	@{- output_on() if $disabled{makedepend}; "" -}
+	@{- output_on() if $disabled{makedepend}; "\@rem" -}
 
 test: tests
 {- dependmagic('tests'); -}: build_programs_nodep build_engines_nodep
-	@{- output_off() if $disabled{tests}; "" -}
+	@{- output_off() if $disabled{tests}; "\@rem" -}
 	-mkdir $(BLDDIR)\test\test-runs
 	set SRCTOP=$(SRCDIR)
 	set BLDTOP=$(BLDDIR)
@@ -341,17 +341,17 @@
 	set OPENSSL_ENGINES=$(MAKEDIR)\engines
 	set OPENSSL_DEBUG_MEMORY=on
 	"$(PERL)" "$(SRCDIR)\test\run_tests.pl" $(TESTS)
-	@{- if ($disabled{tests}) { output_on(); } else { output_off(); } "" -}
+	@{- if ($disabled{tests}) { output_on(); } else { output_off(); } "\@rem" -}
 	@$(ECHO) "Tests are not supported with your chosen Configure options"
-	@{- output_on() if !$disabled{tests}; "" -}
+	@{- output_on() if !$disabled{tests}; "\@rem" -}
 
 list-tests:
-	@{- output_off() if $disabled{tests}; "" -}
+	@{- output_off() if $disabled{tests}; "\@rem" -}
 	@set SRCTOP=$(SRCDIR)
 	@"$(PERL)" "$(SRCDIR)\test\run_tests.pl" list
-	@{- if ($disabled{tests}) { output_on(); } else { output_off(); } "" -}
+	@{- if ($disabled{tests}) { output_on(); } else { output_off(); } "\@rem" -}
 	@$(ECHO) "Tests are not supported with your chosen Configure options"
-	@{- output_on() if !$disabled{tests}; "" -}
+	@{- output_on() if !$disabled{tests}; "\@rem" -}
 
 install: install_sw install_ssldirs install_docs
 
@@ -362,7 +362,7 @@
 	-del /Q /F $(LIBS) libcrypto.* libssl.* ossl_static.pdb
 
 clean: libclean
-	{- join("\n\t", map { "-del /Q /F $_" } @PROGRAMS) -}
+	{- join("\n\t", map { "-del /Q /F $_" } @PROGRAMS) || "\@rem" -}
 	-del /Q /F $(ENGINES)
 	-del /Q /F $(SCRIPTS)
 	-del /Q /F $(GENERATED_MANDATORY)
@@ -378,9 +378,9 @@
 	-del /Q /F makefile
 
 depend:
-	@ {- output_off() if $disabled{makedepend}; "" -}
+	@ {- output_off() if $disabled{makedepend}; "\@rem" -}
 	@ "$(PERL)" "$(SRCDIR)\util\add-depends.pl" "VC"
-	@ {- output_on() if $disabled{makedepend}; "" -}
+	@ {- output_on() if $disabled{makedepend}; "\@rem" -}
 
 # Install helper targets #############################################
 
@@ -413,10 +413,10 @@
 	@if "$(INSTALLTOP)"=="" ( $(ECHO) "INSTALLTOP should not be empty" & exit 1 )
 	@$(ECHO) "*** Installing development files"
 	@"$(PERL)" "$(SRCDIR)\util\mkdir-p.pl" "$(INSTALLTOP)\include\openssl"
-	@{- output_off() unless grep { $_ eq "OPENSSL_USE_APPLINK" } (@{$target{defines}}, @{$config{defines}}); "" -}
+	@{- output_off() unless grep { $_ eq "OPENSSL_USE_APPLINK" } (@{$target{defines}}, @{$config{defines}}); "\@rem" -}
 	@"$(PERL)" "$(SRCDIR)\util\copy.pl" "$(SRCDIR)\ms\applink.c" \
 				       "$(INSTALLTOP)\include\openssl"
-	@{- output_on() unless grep { $_ eq "OPENSSL_USE_APPLINK" } (@{$target{defines}}, @{$config{defines}}); "" -}
+	@{- output_on() unless grep { $_ eq "OPENSSL_USE_APPLINK" } (@{$target{defines}}, @{$config{defines}}); "\@rem" -}
 	@"$(PERL)" "$(SRCDIR)\util\copy.pl" "-exclude_re=/__DECC_" \
 				       "$(SRCDIR)\include\openssl\*.h" \
 				       "$(INSTALLTOP)\include\openssl"
diff -Nru openssl-1.1.1k/Configure openssl-1.1.1m/Configure
--- openssl-1.1.1k/Configure	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/Configure	2021-12-14 16:45:01.000000000 +0100
@@ -1304,16 +1304,19 @@
 
 unless ($disabled{asan}) {
     push @{$config{cflags}}, "-fsanitize=address";
+    push @{$config{cxxflags}}, "-fsanitize=address" if $config{CXX};
 }
 
 unless ($disabled{ubsan}) {
     # -DPEDANTIC or -fnosanitize=alignment may also be required on some
     # platforms.
     push @{$config{cflags}}, "-fsanitize=undefined", "-fno-sanitize-recover=all";
+    push @{$config{cxxflags}}, "-fsanitize=undefined", "-fno-sanitize-recover=all" if $config{CXX};
 }
 
 unless ($disabled{msan}) {
   push @{$config{cflags}}, "-fsanitize=memory";
+  push @{$config{cxxflags}}, "-fsanitize=memory" if $config{CXX};
 }
 
 unless ($disabled{"fuzz-libfuzzer"} && $disabled{"fuzz-afl"}
diff -Nru openssl-1.1.1k/crypto/armcap.c openssl-1.1.1m/crypto/armcap.c
--- openssl-1.1.1k/crypto/armcap.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/armcap.c	2021-12-14 16:45:01.000000000 +0100
@@ -68,6 +68,12 @@
 #   include <sys/auxv.h>
 #   define OSSL_IMPLEMENT_GETAUXVAL
 #  endif
+# elif defined(__ANDROID_API__)
+/* see https://developer.android.google.cn/ndk/guides/cpu-features */
+#  if __ANDROID_API__ >= 18
+#   include <sys/auxv.h>
+#   define OSSL_IMPLEMENT_GETAUXVAL
+#  endif
 # endif
 # if defined(__FreeBSD__)
 #  include <sys/param.h>
@@ -88,23 +94,35 @@
 # endif
 
 /*
+ * Android: according to https://developer.android.com/ndk/guides/cpu-features,
+ * getauxval is supported starting with API level 18
+ */
+#  if defined(__ANDROID__) && defined(__ANDROID_API__) && __ANDROID_API__ >= 18
+#   include <sys/auxv.h>
+#   define OSSL_IMPLEMENT_GETAUXVAL
+#  endif
+
+/*
  * ARM puts the feature bits for Crypto Extensions in AT_HWCAP2, whereas
  * AArch64 used AT_HWCAP.
  */
+# ifndef AT_HWCAP
+#  define AT_HWCAP               16
+# endif
+# ifndef AT_HWCAP2
+#  define AT_HWCAP2              26
+# endif
 # if defined(__arm__) || defined (__arm)
-#  define HWCAP                  16
-                                  /* AT_HWCAP */
+#  define HWCAP                  AT_HWCAP
 #  define HWCAP_NEON             (1 << 12)
 
-#  define HWCAP_CE               26
-                                  /* AT_HWCAP2 */
+#  define HWCAP_CE               AT_HWCAP2
 #  define HWCAP_CE_AES           (1 << 0)
 #  define HWCAP_CE_PMULL         (1 << 1)
 #  define HWCAP_CE_SHA1          (1 << 2)
 #  define HWCAP_CE_SHA256        (1 << 3)
 # elif defined(__aarch64__)
-#  define HWCAP                  16
-                                  /* AT_HWCAP */
+#  define HWCAP                  AT_HWCAP
 #  define HWCAP_NEON             (1 << 1)
 
 #  define HWCAP_CE               HWCAP
diff -Nru openssl-1.1.1k/crypto/asn1/a_object.c openssl-1.1.1m/crypto/asn1/a_object.c
--- openssl-1.1.1k/crypto/asn1/a_object.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/asn1/a_object.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -286,16 +286,13 @@
         }
     }
 
-    /*
-     * only the ASN1_OBJECTs from the 'table' will have values for ->sn or
-     * ->ln
-     */
     if ((a == NULL) || ((*a) == NULL) ||
         !((*a)->flags & ASN1_OBJECT_FLAG_DYNAMIC)) {
         if ((ret = ASN1_OBJECT_new()) == NULL)
             return NULL;
-    } else
+    } else {
         ret = (*a);
+    }
 
     p = *pp;
     /* detach data from object */
@@ -313,6 +310,12 @@
         ret->flags |= ASN1_OBJECT_FLAG_DYNAMIC_DATA;
     }
     memcpy(data, p, length);
+    /* If there are dynamic strings, free them here, and clear the flag */
+    if ((ret->flags & ASN1_OBJECT_FLAG_DYNAMIC_STRINGS) != 0) {
+        OPENSSL_free((char *)ret->sn);
+        OPENSSL_free((char *)ret->ln);
+        ret->flags &= ~ASN1_OBJECT_FLAG_DYNAMIC_STRINGS;
+    }
     /* reattach data to object, after which it remains const */
     ret->data = data;
     ret->length = length;
diff -Nru openssl-1.1.1k/crypto/asn1/a_print.c openssl-1.1.1m/crypto/asn1/a_print.c
--- openssl-1.1.1k/crypto/asn1/a_print.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/asn1/a_print.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -18,12 +18,13 @@
     int ia5 = 0;
     int t61 = 0;
 
-    if (len <= 0)
-        len = -1;
     if (s == NULL)
         return V_ASN1_PRINTABLESTRING;
 
-    while ((*s) && (len-- != 0)) {
+    if (len < 0)
+        len = strlen((const char *)s);
+
+    while (len-- > 0) {
         c = *(s++);
         if (!ossl_isasn1print(c))
             ia5 = 1;
diff -Nru openssl-1.1.1k/crypto/asn1/asn1_lib.c openssl-1.1.1m/crypto/asn1/asn1_lib.c
--- openssl-1.1.1k/crypto/asn1/asn1_lib.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/asn1/asn1_lib.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -292,7 +292,12 @@
     }
     if ((size_t)str->length <= len || str->data == NULL) {
         c = str->data;
+#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
+        /* No NUL terminator in fuzzing builds */
+        str->data = OPENSSL_realloc(c, len != 0 ? len : 1);
+#else
         str->data = OPENSSL_realloc(c, len + 1);
+#endif
         if (str->data == NULL) {
             ASN1err(ASN1_F_ASN1_STRING_SET, ERR_R_MALLOC_FAILURE);
             str->data = c;
@@ -302,8 +307,17 @@
     str->length = len;
     if (data != NULL) {
         memcpy(str->data, data, len);
-        /* an allowance for strings :-) */
+#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
+        /* Set the unused byte to something non NUL and printable. */
+        if (len == 0)
+            str->data[len] = '~';
+#else
+        /*
+         * Add a NUL terminator. This should not be necessary - but we add it as
+         * a safety precaution
+         */
         str->data[len] = '\0';
+#endif
     }
     return 1;
 }
@@ -365,7 +379,8 @@
 
     i = (a->length - b->length);
     if (i == 0) {
-        i = memcmp(a->data, b->data, a->length);
+        if (a->length != 0)
+            i = memcmp(a->data, b->data, a->length);
         if (i == 0)
             return a->type - b->type;
         else
diff -Nru openssl-1.1.1k/crypto/asn1/a_strex.c openssl-1.1.1m/crypto/asn1/a_strex.c
--- openssl-1.1.1k/crypto/asn1/a_strex.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/asn1/a_strex.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -280,6 +280,8 @@
     t.type = str->type;
     t.value.ptr = (char *)str;
     der_len = i2d_ASN1_TYPE(&t, NULL);
+    if (der_len <= 0)
+        return -1;
     if ((der_buf = OPENSSL_malloc(der_len)) == NULL) {
         ASN1err(ASN1_F_DO_DUMP, ERR_R_MALLOC_FAILURE);
         return -1;
diff -Nru openssl-1.1.1k/crypto/asn1/bio_asn1.c openssl-1.1.1m/crypto/asn1/bio_asn1.c
--- openssl-1.1.1k/crypto/asn1/bio_asn1.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/asn1/bio_asn1.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2006-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -138,6 +138,11 @@
     if (ctx == NULL)
         return 0;
 
+    if (ctx->prefix_free != NULL)
+        ctx->prefix_free(b, &ctx->ex_buf, &ctx->ex_len, &ctx->ex_arg);
+    if (ctx->suffix_free != NULL)
+        ctx->suffix_free(b, &ctx->ex_buf, &ctx->ex_len, &ctx->ex_arg);
+
     OPENSSL_free(ctx->buf);
     OPENSSL_free(ctx);
     BIO_set_data(b, NULL);
diff -Nru openssl-1.1.1k/crypto/asn1/bio_ndef.c openssl-1.1.1m/crypto/asn1/bio_ndef.c
--- openssl-1.1.1k/crypto/asn1/bio_ndef.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/asn1/bio_ndef.c	2021-12-14 16:45:01.000000000 +0100
@@ -142,6 +142,9 @@
 
     ndef_aux = *(NDEF_SUPPORT **)parg;
 
+    if (ndef_aux == NULL)
+        return 0;
+
     OPENSSL_free(ndef_aux->derbuf);
 
     ndef_aux->derbuf = NULL;
diff -Nru openssl-1.1.1k/crypto/asn1/d2i_pr.c openssl-1.1.1m/crypto/asn1/d2i_pr.c
--- openssl-1.1.1k/crypto/asn1/d2i_pr.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/asn1/d2i_pr.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -78,13 +78,53 @@
  * type
  */
 
+static EVP_PKEY *key_as_pkcs8(const unsigned char **pp, long length, int *carry_on)
+{
+    const unsigned char *p = *pp;
+    PKCS8_PRIV_KEY_INFO *p8 = d2i_PKCS8_PRIV_KEY_INFO(NULL, &p, length);
+    EVP_PKEY *ret;
+
+    if (p8 == NULL)
+        return NULL;
+
+    ret = EVP_PKCS82PKEY(p8);
+    if (ret == NULL)
+        *carry_on = 0;
+
+    PKCS8_PRIV_KEY_INFO_free(p8);
+
+    if (ret != NULL)
+        *pp = p;
+
+    return ret;
+}
+
 EVP_PKEY *d2i_AutoPrivateKey(EVP_PKEY **a, const unsigned char **pp,
                              long length)
 {
     STACK_OF(ASN1_TYPE) *inkey;
     const unsigned char *p;
     int keytype;
+    EVP_PKEY *ret = NULL;
+    int carry_on = 1;
+
+    ERR_set_mark();
+    ret = key_as_pkcs8(pp, length, &carry_on);
+    if (ret != NULL) {
+        ERR_clear_last_mark();
+        if (a != NULL)
+            *a = ret;
+        return ret;
+    }
+
+    if (carry_on == 0) {
+        ERR_clear_last_mark();
+        ASN1err(ASN1_F_D2I_AUTOPRIVATEKEY,
+                ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE);
+        return NULL;
+    }
     p = *pp;
+
     /*
      * Dirty trick: read in the ASN1 data into a STACK_OF(ASN1_TYPE): by
      * analyzing it we can determine the passed structure: this assumes the
@@ -100,28 +140,15 @@
         keytype = EVP_PKEY_DSA;
     else if (sk_ASN1_TYPE_num(inkey) == 4)
         keytype = EVP_PKEY_EC;
-    else if (sk_ASN1_TYPE_num(inkey) == 3) { /* This seems to be PKCS8, not
-                                              * traditional format */
-        PKCS8_PRIV_KEY_INFO *p8 = d2i_PKCS8_PRIV_KEY_INFO(NULL, &p, length);
-        EVP_PKEY *ret;
-
-        sk_ASN1_TYPE_pop_free(inkey, ASN1_TYPE_free);
-        if (!p8) {
-            ASN1err(ASN1_F_D2I_AUTOPRIVATEKEY,
-                    ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE);
-            return NULL;
-        }
-        ret = EVP_PKCS82PKEY(p8);
-        PKCS8_PRIV_KEY_INFO_free(p8);
-        if (ret == NULL)
-            return NULL;
-        *pp = p;
-        if (a) {
-            *a = ret;
-        }
-        return ret;
-    } else
+    else
         keytype = EVP_PKEY_RSA;
     sk_ASN1_TYPE_pop_free(inkey, ASN1_TYPE_free);
-    return d2i_PrivateKey(keytype, a, pp, length);
+
+    ret = d2i_PrivateKey(keytype, a, pp, length);
+    if (ret != NULL)
+        ERR_pop_to_mark();
+    else
+        ERR_clear_last_mark();
+
+    return ret;
 }
diff -Nru openssl-1.1.1k/crypto/asn1/t_spki.c openssl-1.1.1m/crypto/asn1/t_spki.c
--- openssl-1.1.1k/crypto/asn1/t_spki.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/asn1/t_spki.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -38,7 +38,7 @@
     }
     chal = spki->spkac->challenge;
     if (chal->length)
-        BIO_printf(out, "  Challenge String: %s\n", chal->data);
+        BIO_printf(out, "  Challenge String: %.*s\n", chal->length, chal->data);
     i = OBJ_obj2nid(spki->sig_algor.algorithm);
     BIO_printf(out, "  Signature Algorithm: %s",
                (i == NID_undef) ? "UNKNOWN" : OBJ_nid2ln(i));
diff -Nru openssl-1.1.1k/crypto/bio/b_addr.c openssl-1.1.1m/crypto/bio/b_addr.c
--- openssl-1.1.1k/crypto/bio/b_addr.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/bio/b_addr.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -689,7 +689,7 @@
         hints.ai_protocol = protocol;
 # ifdef AI_ADDRCONFIG
 #  ifdef AF_UNSPEC
-        if (family == AF_UNSPEC)
+        if (host != NULL && family == AF_UNSPEC)
 #  endif
             hints.ai_flags |= AI_ADDRCONFIG;
 # endif
diff -Nru openssl-1.1.1k/crypto/bio/b_sock2.c openssl-1.1.1m/crypto/bio/b_sock2.c
--- openssl-1.1.1k/crypto/bio/b_sock2.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/bio/b_sock2.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -243,7 +243,8 @@
         }
     }
 
-# ifdef IPV6_V6ONLY
+  /* On OpenBSD it is always ipv6 only with ipv6 sockets thus read-only */
+# if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
     if (BIO_ADDR_family(addr) == AF_INET6) {
         /*
          * Note: Windows default of IPV6_V6ONLY is ON, and Linux is OFF.
diff -Nru openssl-1.1.1k/crypto/bio/bss_dgram.c openssl-1.1.1m/crypto/bio/bss_dgram.c
--- openssl-1.1.1k/crypto/bio/bss_dgram.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/bio/bss_dgram.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2005-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2005-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -7,6 +7,10 @@
  * https://www.openssl.org/source/license.html
  */
 
+#ifndef _GNU_SOURCE
+# define _GNU_SOURCE
+#endif
+
 #include <stdio.h>
 #include <errno.h>
 
diff -Nru openssl-1.1.1k/crypto/bio/bss_mem.c openssl-1.1.1m/crypto/bio/bss_mem.c
--- openssl-1.1.1k/crypto/bio/bss_mem.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/bio/bss_mem.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -280,7 +280,7 @@
         ret = (long)bm->length;
         if (ptr != NULL) {
             pptr = (char **)ptr;
-            *pptr = (char *)&(bm->data[0]);
+            *pptr = (char *)bm->data;
         }
         break;
     case BIO_C_SET_BUF_MEM:
diff -Nru openssl-1.1.1k/crypto/bn/asm/mips.pl openssl-1.1.1m/crypto/bn/asm/mips.pl
--- openssl-1.1.1k/crypto/bn/asm/mips.pl	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/bn/asm/mips.pl	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 #! /usr/bin/env perl
-# Copyright 2010-2020 The OpenSSL Project Authors. All Rights Reserved.
+# Copyright 2010-2021 The OpenSSL Project Authors. All Rights Reserved.
 #
 # Licensed under the OpenSSL license (the "License").  You may not use
 # this file except in compliance with the License.  You can obtain a copy
@@ -1984,6 +1984,8 @@
 	sltu	$at,$c_2,$t_1
 	$ADDU	$c_3,$t_2,$at
 	$ST	$c_2,$BNSZ($a0)
+	sltu	$at,$c_3,$t_2
+	$ADDU	$c_1,$at
 	mflo	($t_1,$a_2,$a_0)
 	mfhi	($t_2,$a_2,$a_0)
 ___
@@ -2194,6 +2196,8 @@
 	sltu	$at,$c_2,$t_1
 	$ADDU	$c_3,$t_2,$at
 	$ST	$c_2,$BNSZ($a0)
+	sltu	$at,$c_3,$t_2
+	$ADDU	$c_1,$at
 	mflo	($t_1,$a_2,$a_0)
 	mfhi	($t_2,$a_2,$a_0)
 ___
diff -Nru openssl-1.1.1k/crypto/bn/bn_div.c openssl-1.1.1m/crypto/bn/bn_div.c
--- openssl-1.1.1k/crypto/bn/bn_div.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/bn/bn_div.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -268,7 +268,7 @@
     BIGNUM *tmp, *snum, *sdiv, *res;
     BN_ULONG *resp, *wnum, *wnumtop;
     BN_ULONG d0, d1;
-    int num_n, div_n;
+    int num_n, div_n, num_neg;
 
     assert(divisor->top > 0 && divisor->d[divisor->top - 1] != 0);
 
@@ -326,7 +326,8 @@
     /* Setup quotient */
     if (!bn_wexpand(res, loop))
         goto err;
-    res->neg = (num->neg ^ divisor->neg);
+    num_neg = num->neg;
+    res->neg = (num_neg ^ divisor->neg);
     res->top = loop;
     res->flags |= BN_FLG_FIXED_TOP;
     resp = &(res->d[loop]);
@@ -442,7 +443,7 @@
         *--resp = q;
     }
     /* snum holds remainder, it's as wide as divisor */
-    snum->neg = num->neg;
+    snum->neg = num_neg;
     snum->top = div_n;
     snum->flags |= BN_FLG_FIXED_TOP;
     if (rm != NULL)
diff -Nru openssl-1.1.1k/crypto/chacha/asm/chacha-x86_64.pl openssl-1.1.1m/crypto/chacha/asm/chacha-x86_64.pl
--- openssl-1.1.1k/crypto/chacha/asm/chacha-x86_64.pl	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/chacha/asm/chacha-x86_64.pl	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 #! /usr/bin/env perl
-# Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved.
+# Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
 #
 # Licensed under the OpenSSL license (the "License").  You may not use
 # this file except in compliance with the License.  You can obtain a copy
@@ -471,7 +471,7 @@
 	&por	($b,$t);
 }
 
-my $xframe = $win64 ? 32+8 : 8;
+my $xframe = $win64 ? 160+8 : 8;
 
 $code.=<<___;
 .type	ChaCha20_ssse3,\@function,5
@@ -2499,7 +2499,7 @@
 	&vprold	($b,$b,7);
 }
 
-my $xframe = $win64 ? 32+8 : 8;
+my $xframe = $win64 ? 160+8 : 8;
 
 $code.=<<___;
 .type	ChaCha20_avx512,\@function,5
@@ -2515,8 +2515,16 @@
 	sub	\$64+$xframe,%rsp
 ___
 $code.=<<___	if ($win64);
-	movaps	%xmm6,-0x28(%r9)
-	movaps	%xmm7,-0x18(%r9)
+	movaps	%xmm6,-0xa8(%r9)
+	movaps	%xmm7,-0x98(%r9)
+	movaps	%xmm8,-0x88(%r9)
+	movaps	%xmm9,-0x78(%r9)
+	movaps	%xmm10,-0x68(%r9)
+	movaps	%xmm11,-0x58(%r9)
+	movaps	%xmm12,-0x48(%r9)
+	movaps	%xmm13,-0x38(%r9)
+	movaps	%xmm14,-0x28(%r9)
+	movaps	%xmm15,-0x18(%r9)
 .Lavx512_body:
 ___
 $code.=<<___;
@@ -2683,8 +2691,16 @@
 	vzeroall
 ___
 $code.=<<___	if ($win64);
-	movaps	-0x28(%r9),%xmm6
-	movaps	-0x18(%r9),%xmm7
+	movaps	-0xa8(%r9),%xmm6
+	movaps	-0x98(%r9),%xmm7
+	movaps	-0x88(%r9),%xmm8
+	movaps	-0x78(%r9),%xmm9
+	movaps	-0x68(%r9),%xmm10
+	movaps	-0x58(%r9),%xmm11
+	movaps	-0x48(%r9),%xmm12
+	movaps	-0x38(%r9),%xmm13
+	movaps	-0x28(%r9),%xmm14
+	movaps	-0x18(%r9),%xmm15
 ___
 $code.=<<___;
 	lea	(%r9),%rsp
@@ -2711,8 +2727,16 @@
 	sub	\$64+$xframe,%rsp
 ___
 $code.=<<___	if ($win64);
-	movaps	%xmm6,-0x28(%r9)
-	movaps	%xmm7,-0x18(%r9)
+	movaps	%xmm6,-0xa8(%r9)
+	movaps	%xmm7,-0x98(%r9)
+	movaps	%xmm8,-0x88(%r9)
+	movaps	%xmm9,-0x78(%r9)
+	movaps	%xmm10,-0x68(%r9)
+	movaps	%xmm11,-0x58(%r9)
+	movaps	%xmm12,-0x48(%r9)
+	movaps	%xmm13,-0x38(%r9)
+	movaps	%xmm14,-0x28(%r9)
+	movaps	%xmm15,-0x18(%r9)
 .Lavx512vl_body:
 ___
 $code.=<<___;
@@ -2836,8 +2860,16 @@
 	vzeroall
 ___
 $code.=<<___	if ($win64);
-	movaps	-0x28(%r9),%xmm6
-	movaps	-0x18(%r9),%xmm7
+	movaps	-0xa8(%r9),%xmm6
+	movaps	-0x98(%r9),%xmm7
+	movaps	-0x88(%r9),%xmm8
+	movaps	-0x78(%r9),%xmm9
+	movaps	-0x68(%r9),%xmm10
+	movaps	-0x58(%r9),%xmm11
+	movaps	-0x48(%r9),%xmm12
+	movaps	-0x38(%r9),%xmm13
+	movaps	-0x28(%r9),%xmm14
+	movaps	-0x18(%r9),%xmm15
 ___
 $code.=<<___;
 	lea	(%r9),%rsp
diff -Nru openssl-1.1.1k/crypto/cms/cms_env.c openssl-1.1.1m/crypto/cms/cms_env.c
--- openssl-1.1.1k/crypto/cms/cms_env.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/cms/cms_env.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2008-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -737,6 +737,7 @@
         goto err;
     }
 
+    OPENSSL_clear_free(ec->key, ec->keylen);
     ec->key = ukey;
     ec->keylen = ukeylen;
 
diff -Nru openssl-1.1.1k/crypto/dh/dh_ameth.c openssl-1.1.1m/crypto/dh/dh_ameth.c
--- openssl-1.1.1k/crypto/dh/dh_ameth.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/dh/dh_ameth.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -629,16 +629,18 @@
         goto err;
 
     pk = EVP_PKEY_CTX_get0_pkey(pctx);
-    if (!pk)
-        goto err;
-    if (pk->type != EVP_PKEY_DHX)
+    if (pk == NULL || pk->type != EVP_PKEY_DHX)
         goto err;
+
     /* Get parameters from parent key */
     dhpeer = DHparams_dup(pk->pkey.dh);
+    if (dhpeer == NULL)
+        goto err;
+
     /* We have parameters now set public key */
     plen = ASN1_STRING_length(pubkey);
     p = ASN1_STRING_get0_data(pubkey);
-    if (!p || !plen)
+    if (p == NULL || plen == 0)
         goto err;
 
     if ((public_key = d2i_ASN1_INTEGER(NULL, &p, plen)) == NULL) {
@@ -655,6 +657,7 @@
     pkpeer = EVP_PKEY_new();
     if (pkpeer == NULL)
         goto err;
+
     EVP_PKEY_assign(pkpeer, pk->ameth->pkey_id, dhpeer);
     dhpeer = NULL;
     if (EVP_PKEY_derive_set_peer(pctx, pkpeer) > 0)
diff -Nru openssl-1.1.1k/crypto/dsa/dsa_prn.c openssl-1.1.1m/crypto/dsa/dsa_prn.c
--- openssl-1.1.1k/crypto/dsa/dsa_prn.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/dsa/dsa_prn.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -49,9 +49,11 @@
     EVP_PKEY *pk;
     int ret;
     pk = EVP_PKEY_new();
-    if (pk == NULL || !EVP_PKEY_set1_DSA(pk, (DSA *)x))
+    if (pk == NULL)
         return 0;
-    ret = EVP_PKEY_print_private(bp, pk, off, NULL);
+    ret = EVP_PKEY_set1_DSA(pk, (DSA *)x);
+    if (ret)
+        ret = EVP_PKEY_print_private(bp, pk, off, NULL);
     EVP_PKEY_free(pk);
     return ret;
 }
@@ -61,9 +63,11 @@
     EVP_PKEY *pk;
     int ret;
     pk = EVP_PKEY_new();
-    if (pk == NULL || !EVP_PKEY_set1_DSA(pk, (DSA *)x))
+    if (pk == NULL)
         return 0;
-    ret = EVP_PKEY_print_params(bp, pk, 4, NULL);
+    ret = EVP_PKEY_set1_DSA(pk, (DSA *)x);
+    if (ret)
+        ret = EVP_PKEY_print_params(bp, pk, 4, NULL);
     EVP_PKEY_free(pk);
     return ret;
 }
diff -Nru openssl-1.1.1k/crypto/ec/curve448/field.h openssl-1.1.1m/crypto/ec/curve448/field.h
--- openssl-1.1.1k/crypto/ec/curve448/field.h	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/ec/curve448/field.h	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved.
  * Copyright 2014 Cryptography Research, Inc.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
@@ -62,7 +62,7 @@
 mask_t gf_lobit(const gf x);
 mask_t gf_hibit(const gf x);
 
-void gf_serialize(uint8_t *serial, const gf x, int with_highbit);
+void gf_serialize(uint8_t serial[SER_BYTES], const gf x, int with_highbit);
 mask_t gf_deserialize(gf x, const uint8_t serial[SER_BYTES], int with_hibit,
                       uint8_t hi_nmask);
 
diff -Nru openssl-1.1.1k/crypto/ec/ec2_oct.c openssl-1.1.1m/crypto/ec/ec2_oct.c
--- openssl-1.1.1k/crypto/ec/ec2_oct.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/ec/ec2_oct.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2011-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2011-2021 The OpenSSL Project Authors. All Rights Reserved.
  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
@@ -247,9 +247,21 @@
         ECerr(EC_F_EC_GF2M_SIMPLE_OCT2POINT, EC_R_BUFFER_TOO_SMALL);
         return 0;
     }
-    form = buf[0];
-    y_bit = form & 1;
-    form = form & ~1U;
+
+    /*
+     * The first octet is the point converison octet PC, see X9.62, page 4
+     * and section 4.4.2.  It must be:
+     *     0x00          for the point at infinity
+     *     0x02 or 0x03  for compressed form
+     *     0x04          for uncompressed form
+     *     0x06 or 0x07  for hybrid form.
+     * For compressed or hybrid forms, we store the last bit of buf[0] as
+     * y_bit and clear it from buf[0] so as to obtain a POINT_CONVERSION_*.
+     * We error if buf[0] contains any but the above values.
+     */
+    y_bit = buf[0] & 1;
+    form = buf[0] & ~1U;
+
     if ((form != 0) && (form != POINT_CONVERSION_COMPRESSED)
         && (form != POINT_CONVERSION_UNCOMPRESSED)
         && (form != POINT_CONVERSION_HYBRID)) {
@@ -261,6 +273,7 @@
         return 0;
     }
 
+    /* The point at infinity is represented by a single zero octet. */
     if (form == 0) {
         if (len != 1) {
             ECerr(EC_F_EC_GF2M_SIMPLE_OCT2POINT, EC_R_INVALID_ENCODING);
@@ -312,11 +325,23 @@
             goto err;
         }
         if (form == POINT_CONVERSION_HYBRID) {
-            if (!group->meth->field_div(group, yxi, y, x, ctx))
-                goto err;
-            if (y_bit != BN_is_odd(yxi)) {
-                ECerr(EC_F_EC_GF2M_SIMPLE_OCT2POINT, EC_R_INVALID_ENCODING);
-                goto err;
+            /*
+             * Check that the form in the encoding was set correctly
+             * according to X9.62 4.4.2.a, 4(c), see also first paragraph
+             * of X9.62, 4.4.1.b.
+             */
+            if (BN_is_zero(x)) {
+                if (y_bit != 0) {
+                    ECerr(ERR_LIB_EC, EC_R_INVALID_ENCODING);
+                    goto err;
+                }
+            } else {
+                if (!group->meth->field_div(group, yxi, y, x, ctx))
+                    goto err;
+                if (y_bit != BN_is_odd(yxi)) {
+                    ECerr(ERR_LIB_EC, EC_R_INVALID_ENCODING);
+                    goto err;
+                }
             }
         }
 
diff -Nru openssl-1.1.1k/crypto/ec/ec_asn1.c openssl-1.1.1m/crypto/ec/ec_asn1.c
--- openssl-1.1.1k/crypto/ec/ec_asn1.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/ec/ec_asn1.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2002-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -548,7 +548,7 @@
             ECPARAMETERS_free(ret->value.parameters);
     }
 
-    if (EC_GROUP_get_asn1_flag(group)) {
+    if (EC_GROUP_get_asn1_flag(group) == OPENSSL_EC_NAMED_CURVE) {
         /*
          * use the asn1 OID to describe the elliptic curve parameters
          */
@@ -761,7 +761,10 @@
         ret->seed_len = params->curve->seed->length;
     }
 
-    if (!params->order || !params->base || !params->base->data) {
+    if (params->order == NULL
+            || params->base == NULL
+            || params->base->data == NULL
+            || params->base->length == 0) {
         ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);
         goto err;
     }
diff -Nru openssl-1.1.1k/crypto/ec/ec_curve.c openssl-1.1.1m/crypto/ec/ec_curve.c
--- openssl-1.1.1k/crypto/ec/ec_curve.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/ec/ec_curve.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2002-2021 The OpenSSL Project Authors. All Rights Reserved.
  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
@@ -12,6 +12,7 @@
 #include "ec_local.h"
 #include <openssl/err.h>
 #include <openssl/obj_mac.h>
+#include <openssl/objects.h>
 #include <openssl/opensslconf.h>
 #include "internal/nelem.h"
 
@@ -3097,6 +3098,32 @@
             goto err;
         }
     }
+
+    if (EC_GROUP_get_asn1_flag(group) == OPENSSL_EC_NAMED_CURVE) {
+        /*
+         * Some curves don't have an associated OID: for those we should not
+         * default to `OPENSSL_EC_NAMED_CURVE` encoding of parameters and
+         * instead set the ASN1 flag to `OPENSSL_EC_EXPLICIT_CURVE`.
+         *
+         * Note that `OPENSSL_EC_NAMED_CURVE` is set as the default ASN1 flag on
+         * `EC_GROUP_new()`, when we don't have enough elements to determine if
+         * an OID for the curve name actually exists.
+         * We could implement this check on `EC_GROUP_set_curve_name()` but
+         * overloading the simple setter with this lookup could have a negative
+         * performance impact and unexpected consequences.
+         */
+        ASN1_OBJECT *asn1obj = OBJ_nid2obj(curve.nid);
+
+        if (asn1obj == NULL) {
+            ECerr(EC_F_EC_GROUP_NEW_FROM_DATA, ERR_R_OBJ_LIB);
+            goto err;
+        }
+        if (OBJ_length(asn1obj) == 0)
+            EC_GROUP_set_asn1_flag(group, OPENSSL_EC_EXPLICIT_CURVE);
+
+        ASN1_OBJECT_free(asn1obj);
+    }
+
     ok = 1;
  err:
     if (!ok) {
diff -Nru openssl-1.1.1k/crypto/engine/eng_dyn.c openssl-1.1.1m/crypto/engine/eng_dyn.c
--- openssl-1.1.1k/crypto/engine/eng_dyn.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/engine/eng_dyn.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -477,7 +477,9 @@
     engine_set_all_null(e);
 
     /* Try to bind the ENGINE onto our own ENGINE structure */
-    if (!ctx->bind_engine(e, ctx->engine_id, &fns)) {
+    if (!engine_add_dynamic_id(e, (ENGINE_DYNAMIC_ID)ctx->bind_engine, 1)
+            || !ctx->bind_engine(e, ctx->engine_id, &fns)) {
+        engine_remove_dynamic_id(e, 1);
         ctx->bind_engine = NULL;
         ctx->v_check = NULL;
         DSO_free(ctx->dynamic_dso);
diff -Nru openssl-1.1.1k/crypto/engine/eng_lib.c openssl-1.1.1m/crypto/engine/eng_lib.c
--- openssl-1.1.1k/crypto/engine/eng_lib.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/engine/eng_lib.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -67,6 +67,7 @@
     e->load_pubkey = NULL;
     e->cmd_defns = NULL;
     e->flags = 0;
+    e->dynamic_id = NULL;
 }
 
 int engine_free_util(ENGINE *e, int not_locked)
@@ -92,6 +93,7 @@
      */
     if (e->destroy)
         e->destroy(e);
+    engine_remove_dynamic_id(e, not_locked);
     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_ENGINE, e, &e->ex_data);
     OPENSSL_free(e);
     return 1;
diff -Nru openssl-1.1.1k/crypto/engine/eng_list.c openssl-1.1.1m/crypto/engine/eng_list.c
--- openssl-1.1.1k/crypto/engine/eng_list.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/engine/eng_list.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved.
  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
@@ -25,6 +25,12 @@
 static ENGINE *engine_list_tail = NULL;
 
 /*
+ * The linked list of currently loaded dynamic engines.
+ */
+static ENGINE *engine_dyn_list_head = NULL;
+static ENGINE *engine_dyn_list_tail = NULL;
+
+/*
  * This cleanup function is only needed internally. If it should be called,
  * we register it with the "engine_cleanup_int()" stack to be called during
  * cleanup.
@@ -126,6 +132,85 @@
     return 1;
 }
 
+/* Add engine to dynamic engine list. */
+int engine_add_dynamic_id(ENGINE *e, ENGINE_DYNAMIC_ID dynamic_id,
+                          int not_locked)
+{
+    int result = 0;
+    ENGINE *iterator = NULL;
+
+    if (e == NULL)
+        return 0;
+
+    if (e->dynamic_id == NULL && dynamic_id == NULL)
+        return 0;
+
+    if (not_locked && !CRYPTO_THREAD_write_lock(global_engine_lock))
+        return 0;
+
+    if (dynamic_id != NULL) {
+        iterator = engine_dyn_list_head;
+        while (iterator != NULL) {
+            if (iterator->dynamic_id == dynamic_id)
+                goto err;
+            iterator = iterator->next;
+        }
+        if (e->dynamic_id != NULL)
+            goto err;
+        e->dynamic_id = dynamic_id;
+    }
+
+    if (engine_dyn_list_head == NULL) {
+        /* We are adding to an empty list. */
+        if (engine_dyn_list_tail != NULL)
+            goto err;
+        engine_dyn_list_head = e;
+        e->prev_dyn = NULL;
+    } else {
+        /* We are adding to the tail of an existing list. */
+        if (engine_dyn_list_tail == NULL
+            || engine_dyn_list_tail->next_dyn != NULL)
+            goto err;
+        engine_dyn_list_tail->next_dyn = e;
+        e->prev_dyn = engine_dyn_list_tail;
+    }
+
+    engine_dyn_list_tail = e;
+    e->next_dyn = NULL;
+    result = 1;
+
+ err:
+    if (not_locked)
+        CRYPTO_THREAD_unlock(global_engine_lock);
+    return result;
+}
+
+/* Remove engine from dynamic engine list. */
+void engine_remove_dynamic_id(ENGINE *e, int not_locked)
+{
+    if (e == NULL || e->dynamic_id == NULL)
+        return;
+
+    if (not_locked && !CRYPTO_THREAD_write_lock(global_engine_lock))
+        return;
+
+    e->dynamic_id = NULL;
+
+    /* un-link e from the chain. */
+    if (e->next_dyn != NULL)
+        e->next_dyn->prev_dyn = e->prev_dyn;
+    if (e->prev_dyn != NULL)
+        e->prev_dyn->next_dyn = e->next_dyn;
+    /* Correct our head/tail if necessary. */
+    if (engine_dyn_list_head == e)
+        engine_dyn_list_head = e->next_dyn;
+    if (engine_dyn_list_tail == e)
+        engine_dyn_list_tail = e->prev_dyn;
+
+    if (not_locked)
+        CRYPTO_THREAD_unlock(global_engine_lock);
+}
+
 /* Get the first/last "ENGINE" type available. */
 ENGINE *ENGINE_get_first(void)
 {
@@ -272,6 +357,8 @@
     dest->load_pubkey = src->load_pubkey;
     dest->cmd_defns = src->cmd_defns;
     dest->flags = src->flags;
+    dest->dynamic_id = src->dynamic_id;
+    engine_add_dynamic_id(dest, NULL, 0);
 }
 
 ENGINE *ENGINE_by_id(const char *id)
diff -Nru openssl-1.1.1k/crypto/engine/eng_local.h openssl-1.1.1m/crypto/engine/eng_local.h
--- openssl-1.1.1k/crypto/engine/eng_local.h	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/engine/eng_local.h	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved.
  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
@@ -118,6 +118,11 @@
 extern CRYPTO_ONCE engine_lock_init;
 DECLARE_RUN_ONCE(do_engine_lock_init)
 
+typedef void (*ENGINE_DYNAMIC_ID)(void);
+int engine_add_dynamic_id(ENGINE *e, ENGINE_DYNAMIC_ID dynamic_id,
+                          int not_locked);
+void engine_remove_dynamic_id(ENGINE *e, int not_locked);
+
 /*
  * This is a structure for storing implementations of various crypto
  * algorithms and functions.
@@ -162,6 +167,10 @@
     /* Used to maintain the linked-list of engines. */
     struct engine_st *prev;
     struct engine_st *next;
+    /* Used to maintain the linked-list of dynamic engines. */
+    struct engine_st *prev_dyn;
+    struct engine_st *next_dyn;
+    ENGINE_DYNAMIC_ID dynamic_id;
 };
 
 typedef struct st_engine_pile ENGINE_PILE;
diff -Nru openssl-1.1.1k/crypto/err/err.c openssl-1.1.1m/crypto/err/err.c
--- openssl-1.1.1k/crypto/err/err.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/err/err.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -129,6 +129,7 @@
     {ERR_R_INTERNAL_ERROR, "internal error"},
     {ERR_R_DISABLED, "called a function that was disabled at compile-time"},
     {ERR_R_INIT_FAIL, "init fail"},
+    {ERR_R_PASSED_INVALID_ARGUMENT, "passed invalid argument"},
     {ERR_R_OPERATION_FAIL, "operation fail"},
 
     {0, NULL},
diff -Nru openssl-1.1.1k/crypto/err/openssl.txt openssl-1.1.1m/crypto/err/openssl.txt
--- openssl-1.1.1k/crypto/err/openssl.txt	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/err/openssl.txt	2021-12-14 16:45:01.000000000 +0100
@@ -1160,6 +1160,7 @@
 SSL_F_FINAL_EMS:486:final_ems
 SSL_F_FINAL_KEY_SHARE:503:final_key_share
 SSL_F_FINAL_MAXFRAGMENTLEN:557:final_maxfragmentlen
+SSL_F_FINAL_PSK:639:final_psk
 SSL_F_FINAL_RENEGOTIATE:483:final_renegotiate
 SSL_F_FINAL_SERVER_NAME:558:final_server_name
 SSL_F_FINAL_SIG_ALGS:497:final_sig_algs
@@ -1652,6 +1653,7 @@
 X509V3_F_I2S_ASN1_IA5STRING:149:i2s_ASN1_IA5STRING
 X509V3_F_I2S_ASN1_INTEGER:120:i2s_ASN1_INTEGER
 X509V3_F_I2V_AUTHORITY_INFO_ACCESS:138:i2v_AUTHORITY_INFO_ACCESS
+X509V3_F_I2V_AUTHORITY_KEYID:173:i2v_AUTHORITY_KEYID
 X509V3_F_LEVEL_ADD_NODE:168:level_add_node
 X509V3_F_NOTICE_SECTION:132:notice_section
 X509V3_F_NREF_NOS:133:nref_nos
@@ -1692,6 +1694,7 @@
 X509V3_F_V2I_TLS_FEATURE:165:v2i_TLS_FEATURE
 X509V3_F_V3_GENERIC_EXTENSION:116:v3_generic_extension
 X509V3_F_X509V3_ADD1_I2D:140:X509V3_add1_i2d
+X509V3_F_X509V3_ADD_LEN_VALUE:174:x509v3_add_len_value
 X509V3_F_X509V3_ADD_VALUE:105:X509V3_add_value
 X509V3_F_X509V3_EXT_ADD:104:X509V3_EXT_add
 X509V3_F_X509V3_EXT_ADD_ALIAS:106:X509V3_EXT_add_alias
@@ -2741,6 +2744,7 @@
 SSL_R_MISSING_ECDSA_SIGNING_CERT:381:missing ecdsa signing cert
 SSL_R_MISSING_FATAL:256:missing fatal
 SSL_R_MISSING_PARAMETERS:290:missing parameters
+SSL_R_MISSING_PSK_KEX_MODES_EXTENSION:310:missing psk kex modes extension
 SSL_R_MISSING_RSA_CERTIFICATE:168:missing rsa certificate
 SSL_R_MISSING_RSA_ENCRYPTING_CERT:169:missing rsa encrypting cert
 SSL_R_MISSING_RSA_SIGNING_CERT:170:missing rsa signing cert
@@ -2784,6 +2788,7 @@
 SSL_R_NO_VERIFY_COOKIE_CALLBACK:403:no verify cookie callback
 SSL_R_NULL_SSL_CTX:195:null ssl ctx
 SSL_R_NULL_SSL_METHOD_PASSED:196:null ssl method passed
+SSL_R_OCSP_CALLBACK_FAILURE:294:ocsp callback failure
 SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED:197:old session cipher not returned
 SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED:344:\
 	old session compression algorithm not returned
diff -Nru openssl-1.1.1k/crypto/evp/e_aes.c openssl-1.1.1m/crypto/evp/e_aes.c
--- openssl-1.1.1k/crypto/evp/e_aes.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/evp/e_aes.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -611,22 +611,22 @@
  */
 void aes128_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
                            size_t len, const AES_KEY *key,
-                           unsigned char *ivec);
+                           unsigned char *ivec, int /*unused*/);
 void aes128_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
                            size_t len, const AES_KEY *key,
-                           unsigned char *ivec);
+                           unsigned char *ivec, int /*unused*/);
 void aes192_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
                            size_t len, const AES_KEY *key,
-                           unsigned char *ivec);
+                           unsigned char *ivec, int /*unused*/);
 void aes192_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
                            size_t len, const AES_KEY *key,
-                           unsigned char *ivec);
+                           unsigned char *ivec, int /*unused*/);
 void aes256_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
                            size_t len, const AES_KEY *key,
-                           unsigned char *ivec);
+                           unsigned char *ivec, int /*unused*/);
 void aes256_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
                            size_t len, const AES_KEY *key,
-                           unsigned char *ivec);
+                           unsigned char *ivec, int /*unused*/);
 void aes128_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out,
                              size_t blocks, const AES_KEY *key,
                              unsigned char *ivec);
@@ -1168,9 +1168,9 @@
 static int s390x_aes_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
                               const unsigned char *iv, int enc);
 
-# define S390X_aes_128_cbc_CAPABLE	1	/* checked by callee */
-# define S390X_aes_192_cbc_CAPABLE	1
-# define S390X_aes_256_cbc_CAPABLE	1
+# define S390X_aes_128_cbc_CAPABLE	0	/* checked by callee */
+# define S390X_aes_192_cbc_CAPABLE	0
+# define S390X_aes_256_cbc_CAPABLE	0
 # define S390X_AES_CBC_CTX		EVP_AES_KEY
 
 # define s390x_aes_cbc_init_key aes_init_key
@@ -1190,11 +1190,11 @@
     S390X_AES_ECB_CTX *cctx = EVP_C_DATA(S390X_AES_ECB_CTX, ctx);
     const int keylen = EVP_CIPHER_CTX_key_length(ctx);
 
-    cctx->fc = S390X_AES_FC(keylen);
-    if (!enc)
-        cctx->fc |= S390X_DECRYPT;
+    cctx->fc = S390X_AES_FC(keylen) | (enc ? 0 : S390X_DECRYPT);
+
+    if (key != NULL)
+        memcpy(cctx->km.param.k, key, keylen);
 
-    memcpy(cctx->km.param.k, key, keylen);
     return 1;
 }
 
@@ -1222,14 +1222,17 @@
                                   const unsigned char *ivec, int enc)
 {
     S390X_AES_OFB_CTX *cctx = EVP_C_DATA(S390X_AES_OFB_CTX, ctx);
-    const unsigned char *iv = EVP_CIPHER_CTX_original_iv(ctx);
+    const unsigned char *oiv = EVP_CIPHER_CTX_original_iv(ctx);
     const int keylen = EVP_CIPHER_CTX_key_length(ctx);
     const int ivlen = EVP_CIPHER_CTX_iv_length(ctx);
 
-    memcpy(cctx->kmo.param.cv, iv, ivlen);
-    memcpy(cctx->kmo.param.k, key, keylen);
     cctx->fc = S390X_AES_FC(keylen);
+
+    if (key != NULL)
+        memcpy(cctx->kmo.param.k, key, keylen);
+
     cctx->res = 0;
+    memcpy(cctx->kmo.param.cv, oiv, ivlen);
     return 1;
 }
 
@@ -1237,9 +1240,12 @@
                                 const unsigned char *in, size_t len)
 {
     S390X_AES_OFB_CTX *cctx = EVP_C_DATA(S390X_AES_OFB_CTX, ctx);
+    const int ivlen = EVP_CIPHER_CTX_iv_length(ctx);
+    unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
     int n = cctx->res;
     int rem;
 
+    memcpy(cctx->kmo.param.cv, iv, ivlen);
     while (n && len) {
         *out = *in ^ cctx->kmo.param.cv[n];
         n = (n + 1) & 0xf;
@@ -1268,6 +1274,7 @@
         }
     }
 
+    memcpy(iv, cctx->kmo.param.cv, ivlen);
     cctx->res = n;
     return 1;
 }
@@ -1287,18 +1294,18 @@
                                   const unsigned char *ivec, int enc)
 {
     S390X_AES_CFB_CTX *cctx = EVP_C_DATA(S390X_AES_CFB_CTX, ctx);
-    const unsigned char *iv = EVP_CIPHER_CTX_original_iv(ctx);
+    const unsigned char *oiv = EVP_CIPHER_CTX_original_iv(ctx);
     const int keylen = EVP_CIPHER_CTX_key_length(ctx);
     const int ivlen = EVP_CIPHER_CTX_iv_length(ctx);
 
-    cctx->fc = S390X_AES_FC(keylen);
-    cctx->fc |= 16 << 24;   /* 16 bytes cipher feedback */
-    if (!enc)
-        cctx->fc |= S390X_DECRYPT;
+    cctx->fc = S390X_AES_FC(keylen) | (enc ? 0 : S390X_DECRYPT)
+               | (16 << 24); /* 16 bytes cipher feedback */
+
+    if (key != NULL)
+        memcpy(cctx->kmf.param.k, key, keylen);
 
     cctx->res = 0;
-    memcpy(cctx->kmf.param.cv, iv, ivlen);
-    memcpy(cctx->kmf.param.k, key, keylen);
+    memcpy(cctx->kmf.param.cv, oiv, ivlen);
     return 1;
 }
 
@@ -1308,10 +1315,13 @@
     S390X_AES_CFB_CTX *cctx = EVP_C_DATA(S390X_AES_CFB_CTX, ctx);
     const int keylen = EVP_CIPHER_CTX_key_length(ctx);
     const int enc = EVP_CIPHER_CTX_encrypting(ctx);
+    const int ivlen = EVP_CIPHER_CTX_iv_length(ctx);
+    unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
     int n = cctx->res;
     int rem;
     unsigned char tmp;
 
+    memcpy(cctx->kmf.param.cv, iv, ivlen);
     while (n && len) {
         tmp = *in;
         *out = cctx->kmf.param.cv[n] ^ tmp;
@@ -1344,6 +1354,7 @@
         }
     }
 
+    memcpy(iv, cctx->kmf.param.cv, ivlen);
     cctx->res = n;
     return 1;
 }
@@ -1360,17 +1371,18 @@
                                    const unsigned char *ivec, int enc)
 {
     S390X_AES_CFB_CTX *cctx = EVP_C_DATA(S390X_AES_CFB_CTX, ctx);
-    const unsigned char *iv = EVP_CIPHER_CTX_original_iv(ctx);
+    const unsigned char *oiv = EVP_CIPHER_CTX_original_iv(ctx);
     const int keylen = EVP_CIPHER_CTX_key_length(ctx);
     const int ivlen = EVP_CIPHER_CTX_iv_length(ctx);
 
-    cctx->fc = S390X_AES_FC(keylen);
-    cctx->fc |= 1 << 24;   /* 1 byte cipher feedback */
-    if (!enc)
-        cctx->fc |= S390X_DECRYPT;
+    cctx->fc = S390X_AES_FC(keylen) | (enc ? 0 : S390X_DECRYPT)
+               | (1 << 24); /* 1 byte cipher feedback flag */
 
-    memcpy(cctx->kmf.param.cv, iv, ivlen);
-    memcpy(cctx->kmf.param.k, key, keylen);
+    if (key != NULL)
+        memcpy(cctx->kmf.param.k, key, keylen);
+
+    cctx->res = 0;
+    memcpy(cctx->kmf.param.cv, oiv, ivlen);
     return 1;
 }
 
@@ -1378,8 +1390,12 @@
                                  const unsigned char *in, size_t len)
 {
     S390X_AES_CFB_CTX *cctx = EVP_C_DATA(S390X_AES_CFB_CTX, ctx);
+    const int ivlen = EVP_CIPHER_CTX_iv_length(ctx);
+    unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
 
+    memcpy(cctx->kmf.param.cv, iv, ivlen);
     s390x_kmf(in, len, out, cctx->fc, &cctx->kmf.param);
+    memcpy(iv, cctx->kmf.param.cv, ivlen);
     return 1;
 }
 
@@ -1393,9 +1409,9 @@
 static int s390x_aes_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                                  const unsigned char *in, size_t len);
 
-# define S390X_aes_128_ctr_CAPABLE	1	/* checked by callee */
-# define S390X_aes_192_ctr_CAPABLE	1
-# define S390X_aes_256_ctr_CAPABLE	1
+# define S390X_aes_128_ctr_CAPABLE	0	/* checked by callee */
+# define S390X_aes_192_ctr_CAPABLE	0
+# define S390X_aes_256_ctr_CAPABLE	0
 # define S390X_AES_CTR_CTX		EVP_AES_KEY
 
 # define s390x_aes_ctr_init_key aes_init_key
@@ -1563,8 +1579,7 @@
 /*-
  * Initialize context structure. Code is big-endian.
  */
-static void s390x_aes_gcm_setiv(S390X_AES_GCM_CTX *ctx,
-                                const unsigned char *iv)
+static void s390x_aes_gcm_setiv(S390X_AES_GCM_CTX *ctx)
 {
     ctx->kma.param.t.g[0] = 0;
     ctx->kma.param.t.g[1] = 0;
@@ -1575,12 +1590,11 @@
     ctx->kreslen = 0;
 
     if (ctx->ivlen == 12) {
-        memcpy(&ctx->kma.param.j0, iv, ctx->ivlen);
+        memcpy(&ctx->kma.param.j0, ctx->iv, ctx->ivlen);
         ctx->kma.param.j0.w[3] = 1;
         ctx->kma.param.cv.w = 1;
     } else {
         /* ctx->iv has the right size and is already padded. */
-        memcpy(ctx->iv, iv, ctx->ivlen);
         s390x_kma(ctx->iv, S390X_gcm_ivpadlen(ctx->ivlen), NULL, 0, NULL,
                   ctx->fc, &ctx->kma.param);
         ctx->fc |= S390X_KMA_HS;
@@ -1694,7 +1708,7 @@
         if (gctx->iv_gen == 0 || gctx->key_set == 0)
             return 0;
 
-        s390x_aes_gcm_setiv(gctx, gctx->iv);
+        s390x_aes_gcm_setiv(gctx);
 
         if (arg <= 0 || arg > gctx->ivlen)
             arg = gctx->ivlen;
@@ -1714,7 +1728,7 @@
             return 0;
 
         memcpy(gctx->iv + gctx->ivlen - arg, ptr, arg);
-        s390x_aes_gcm_setiv(gctx, gctx->iv);
+        s390x_aes_gcm_setiv(gctx);
         gctx->iv_set = 1;
         return 1;
 
@@ -1770,43 +1784,36 @@
 }
 
 /*-
- * Set key and/or iv. Returns 1 on success. Otherwise 0 is returned.
+ * Set key or iv or enc/dec. Returns 1 on success. Otherwise 0 is returned.
  */
 static int s390x_aes_gcm_init_key(EVP_CIPHER_CTX *ctx,
                                   const unsigned char *key,
                                   const unsigned char *iv, int enc)
 {
     S390X_AES_GCM_CTX *gctx = EVP_C_DATA(S390X_AES_GCM_CTX, ctx);
-    int keylen;
+    const int keylen = EVP_CIPHER_CTX_key_length(ctx);
 
-    if (iv == NULL && key == NULL)
-        return 1;
+    gctx->fc = S390X_AES_FC(keylen) | (enc ? 0 : S390X_DECRYPT);
 
     if (key != NULL) {
-        keylen = EVP_CIPHER_CTX_key_length(ctx);
+        gctx->fc &= ~S390X_KMA_HS;
         memcpy(&gctx->kma.param.k, key, keylen);
-
-        gctx->fc = S390X_AES_FC(keylen);
-        if (!enc)
-            gctx->fc |= S390X_DECRYPT;
-
-        if (iv == NULL && gctx->iv_set)
-            iv = gctx->iv;
-
-        if (iv != NULL) {
-            s390x_aes_gcm_setiv(gctx, iv);
-            gctx->iv_set = 1;
-        }
         gctx->key_set = 1;
-    } else {
-        if (gctx->key_set)
-            s390x_aes_gcm_setiv(gctx, iv);
-        else
-            memcpy(gctx->iv, iv, gctx->ivlen);
+    }
 
-        gctx->iv_set = 1;
+    if (iv != NULL) {
+        memcpy(gctx->iv, iv, gctx->ivlen);
         gctx->iv_gen = 0;
+        gctx->iv_set = 1;
     }
+
+    if (gctx->key_set && gctx->iv_set)
+            s390x_aes_gcm_setiv(gctx);
+
+    gctx->fc &= ~(S390X_KMA_LPC | S390X_KMA_LAAD);
+    gctx->areslen = 0;
+    gctx->mreslen = 0;
+    gctx->kreslen = 0;
     return 1;
 }
 
@@ -1895,7 +1902,6 @@
         /* recall that we already did en-/decrypt gctx->mres
          * and returned it to caller... */
         OPENSSL_cleanse(tmp, gctx->mreslen);
-        gctx->iv_set = 0;
 
         enc = EVP_CIPHER_CTX_encrypting(ctx);
         if (enc) {
@@ -1929,8 +1935,8 @@
 }
 
 # define S390X_AES_XTS_CTX		EVP_AES_XTS_CTX
-# define S390X_aes_128_xts_CAPABLE	1	/* checked by callee */
-# define S390X_aes_256_xts_CAPABLE	1
+# define S390X_aes_128_xts_CAPABLE	0	/* checked by callee */
+# define S390X_aes_256_xts_CAPABLE	0
 
 # define s390x_aes_xts_init_key aes_xts_init_key
 static int s390x_aes_xts_init_key(EVP_CIPHER_CTX *ctx,
@@ -2134,9 +2140,10 @@
                                     const unsigned char *in, size_t len)
 {
     S390X_AES_CCM_CTX *cctx = EVP_C_DATA(S390X_AES_CCM_CTX, ctx);
-    unsigned char *ivec = EVP_CIPHER_CTX_iv_noconst(ctx);
+    const unsigned char *ivec = EVP_CIPHER_CTX_iv(ctx);
     unsigned char *buf = EVP_CIPHER_CTX_buf_noconst(ctx);
     const int enc = EVP_CIPHER_CTX_encrypting(ctx);
+    unsigned char iv[EVP_MAX_IV_LENGTH];
 
     if (out != in
             || len < (EVP_CCM_TLS_EXPLICIT_IV_LEN + (size_t)cctx->aes.ccm.m))
@@ -2152,8 +2159,9 @@
      * Get explicit iv (sequence number). We already have fixed iv
      * (server/client_write_iv) here.
      */
-    memcpy(ivec + EVP_CCM_TLS_FIXED_IV_LEN, in, EVP_CCM_TLS_EXPLICIT_IV_LEN);
-    s390x_aes_ccm_setiv(cctx, ivec, len);
+    memcpy(iv, ivec, sizeof(iv));
+    memcpy(iv + EVP_CCM_TLS_FIXED_IV_LEN, in, EVP_CCM_TLS_EXPLICIT_IV_LEN);
+    s390x_aes_ccm_setiv(cctx, iv, len);
 
     /* Process aad (sequence number|type|version|length) */
     s390x_aes_ccm_aad(cctx, buf, cctx->aes.ccm.tls_aad_len);
@@ -2180,42 +2188,35 @@
 }
 
 /*-
- * Set key and flag field and/or iv. Returns 1 if successful. Otherwise 0 is
- * returned.
+ * Set key or iv or enc/dec. Returns 1 if successful.
+ * Otherwise 0 is returned.
  */
 static int s390x_aes_ccm_init_key(EVP_CIPHER_CTX *ctx,
                                   const unsigned char *key,
                                   const unsigned char *iv, int enc)
 {
     S390X_AES_CCM_CTX *cctx = EVP_C_DATA(S390X_AES_CCM_CTX, ctx);
-    unsigned char *ivec;
-    int keylen;
+    const int keylen  = EVP_CIPHER_CTX_key_length(ctx);
+    unsigned char *ivec = EVP_CIPHER_CTX_iv_noconst(ctx);
 
-    if (iv == NULL && key == NULL)
-        return 1;
+    cctx->aes.ccm.fc = S390X_AES_FC(keylen);
 
     if (key != NULL) {
-        keylen = EVP_CIPHER_CTX_key_length(ctx);
-        cctx->aes.ccm.fc = S390X_AES_FC(keylen);
         memcpy(cctx->aes.ccm.kmac_param.k, key, keylen);
-
-        /* Store encoded m and l. */
-        cctx->aes.ccm.nonce.b[0] = ((cctx->aes.ccm.l - 1) & 0x7)
-                                 | (((cctx->aes.ccm.m - 2) >> 1) & 0x7) << 3;
-        memset(cctx->aes.ccm.nonce.b + 1, 0,
-               sizeof(cctx->aes.ccm.nonce.b));
-        cctx->aes.ccm.blocks = 0;
-
         cctx->aes.ccm.key_set = 1;
     }
-
     if (iv != NULL) {
-        ivec = EVP_CIPHER_CTX_iv_noconst(ctx);
         memcpy(ivec, iv, 15 - cctx->aes.ccm.l);
-
         cctx->aes.ccm.iv_set = 1;
     }
 
+    /* Store encoded m and l. */
+    cctx->aes.ccm.nonce.b[0] = ((cctx->aes.ccm.l - 1) & 0x7)
+                             | (((cctx->aes.ccm.m - 2) >> 1) & 0x7) << 3;
+    memset(cctx->aes.ccm.nonce.b + 1, 0, sizeof(cctx->aes.ccm.nonce.b) - 1);
+
+    cctx->aes.ccm.blocks = 0;
+    cctx->aes.ccm.len_set = 0;
     return 1;
 }
 
@@ -2230,8 +2231,9 @@
 {
     S390X_AES_CCM_CTX *cctx = EVP_C_DATA(S390X_AES_CCM_CTX, ctx);
     const int enc = EVP_CIPHER_CTX_encrypting(ctx);
+    const unsigned char *ivec = EVP_CIPHER_CTX_iv(ctx);
+    unsigned char *buf;
     int rv;
-    unsigned char *buf, *ivec;
 
     if (!cctx->aes.ccm.key_set)
         return -1;
@@ -2253,7 +2255,6 @@
     if (out == NULL) {
         /* Update(): Pass message length. */
         if (in == NULL) {
-            ivec = EVP_CIPHER_CTX_iv_noconst(ctx);
             s390x_aes_ccm_setiv(cctx, ivec, len);
 
             cctx->aes.ccm.len_set = 1;
@@ -2279,7 +2280,6 @@
          * In case message length was not previously set explicitly via
          * Update(), set it now.
          */
-        ivec = EVP_CIPHER_CTX_iv_noconst(ctx);
         s390x_aes_ccm_setiv(cctx, ivec, len);
 
         cctx->aes.ccm.len_set = 1;
@@ -2304,9 +2304,6 @@
         if (rv == -1)
             OPENSSL_cleanse(out, len);
 
-        cctx->aes.ccm.iv_set = 0;
-        cctx->aes.ccm.tag_set = 0;
-        cctx->aes.ccm.len_set = 0;
         return rv;
     }
 }
@@ -2414,9 +2411,6 @@
             return 0;
 
         memcpy(ptr, cctx->aes.ccm.kmac_param.icv.b, cctx->aes.ccm.m);
-        cctx->aes.ccm.tag_set = 0;
-        cctx->aes.ccm.iv_set = 0;
-        cctx->aes.ccm.len_set = 0;
         return 1;
 
     case EVP_CTRL_COPY:
@@ -2453,7 +2447,7 @@
     nid##_##keylen##_##nmode,blocksize,					\
     keylen / 8,								\
     ivlen,								\
-    flags | EVP_CIPH_##MODE##_MODE,					\
+    flags | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_##MODE##_MODE,		\
     s390x_aes_##mode##_init_key,					\
     s390x_aes_##mode##_cipher,						\
     NULL,								\
@@ -2490,7 +2484,7 @@
     blocksize,								\
     (EVP_CIPH_##MODE##_MODE == EVP_CIPH_XTS_MODE ? 2 : 1) * keylen / 8,	\
     ivlen,								\
-    flags | EVP_CIPH_##MODE##_MODE,					\
+    flags | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_##MODE##_MODE,		\
     s390x_aes_##mode##_init_key,					\
     s390x_aes_##mode##_cipher,						\
     s390x_aes_##mode##_cleanup,						\
diff -Nru openssl-1.1.1k/crypto/evp/e_camellia.c openssl-1.1.1m/crypto/evp/e_camellia.c
--- openssl-1.1.1k/crypto/evp/e_camellia.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/evp/e_camellia.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2006-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -55,16 +55,16 @@
 
 void cmll128_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
                             size_t len, const CAMELLIA_KEY *key,
-                            unsigned char *ivec);
+                            unsigned char *ivec, int /*unused*/);
 void cmll128_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
                             size_t len, const CAMELLIA_KEY *key,
-                            unsigned char *ivec);
+                            unsigned char *ivec, int /*unused*/);
 void cmll256_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
                             size_t len, const CAMELLIA_KEY *key,
-                            unsigned char *ivec);
+                            unsigned char *ivec, int /*unused*/);
 void cmll256_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
                             size_t len, const CAMELLIA_KEY *key,
-                            unsigned char *ivec);
+                            unsigned char *ivec, int /*unused*/);
 void cmll128_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out,
                               size_t blocks, const CAMELLIA_KEY *key,
                               unsigned char *ivec);
diff -Nru openssl-1.1.1k/crypto/evp/evp_enc.c openssl-1.1.1m/crypto/evp/evp_enc.c
--- openssl-1.1.1k/crypto/evp/evp_enc.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/evp/evp_enc.c	2021-12-14 16:45:01.000000000 +0100
@@ -85,7 +85,11 @@
          * previous check attempted to avoid this if the same ENGINE and
          * EVP_CIPHER could be used).
          */
-        if (ctx->cipher) {
+        if (ctx->cipher
+#ifndef OPENSSL_NO_ENGINE
+                || ctx->engine
+#endif
+                || ctx->cipher_data) {
             unsigned long flags = ctx->flags;
             EVP_CIPHER_CTX_reset(ctx);
             /* Restore encrypt and flags */
@@ -105,11 +109,7 @@
             /* There's an ENGINE for this job ... (apparently) */
             const EVP_CIPHER *c = ENGINE_get_cipher(impl, cipher->nid);
             if (!c) {
-                /*
-                 * One positive side-effect of US's export control history,
-                 * is that we should at least be able to avoid using US
-                 * misspellings of "initialisation"?
-                 */
+                ENGINE_finish(impl);
                 EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
                 return 0;
             }
diff -Nru openssl-1.1.1k/crypto/evp/p_lib.c openssl-1.1.1m/crypto/evp/p_lib.c
--- openssl-1.1.1k/crypto/evp/p_lib.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/evp/p_lib.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -212,10 +212,15 @@
     }
     if (pkey) {
         pkey->ameth = ameth;
-        pkey->engine = e;
-
         pkey->type = pkey->ameth->pkey_id;
         pkey->save_type = type;
+# ifndef OPENSSL_NO_ENGINE
+        if (eptr == NULL && e != NULL && !ENGINE_init(e)) {
+            EVPerr(EVP_F_PKEY_SET_TYPE, EVP_R_INITIALIZATION_ERROR);
+            return 0;
+        }
+# endif
+        pkey->engine = e;
     }
     return 1;
 }
@@ -520,7 +525,7 @@
 
 EC_KEY *EVP_PKEY_get0_EC_KEY(EVP_PKEY *pkey)
 {
-    if (pkey->type != EVP_PKEY_EC) {
+    if (EVP_PKEY_base_id(pkey) != EVP_PKEY_EC) {
         EVPerr(EVP_F_EVP_PKEY_GET0_EC_KEY, EVP_R_EXPECTING_A_EC_KEY);
         return NULL;
     }
diff -Nru openssl-1.1.1k/crypto/hmac/hm_ameth.c openssl-1.1.1m/crypto/hmac/hm_ameth.c
--- openssl-1.1.1k/crypto/hmac/hm_ameth.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/hmac/hm_ameth.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -47,7 +47,8 @@
 
 static int hmac_pkey_public_cmp(const EVP_PKEY *a, const EVP_PKEY *b)
 {
-    return ASN1_OCTET_STRING_cmp(EVP_PKEY_get0(a), EVP_PKEY_get0(b));
+    /* the ameth pub_cmp must return 1 on match, 0 on mismatch */
+    return ASN1_OCTET_STRING_cmp(EVP_PKEY_get0(a), EVP_PKEY_get0(b)) == 0;
 }
 
 static int hmac_set_priv_key(EVP_PKEY *pkey, const unsigned char *priv,
diff -Nru openssl-1.1.1k/crypto/objects/o_names.c openssl-1.1.1m/crypto/objects/o_names.c
--- openssl-1.1.1k/crypto/objects/o_names.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/objects/o_names.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1998-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -67,8 +67,14 @@
 DEFINE_RUN_ONCE_STATIC(o_names_init)
 {
     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
-    names_lh = lh_OBJ_NAME_new(obj_name_hash, obj_name_cmp);
+    names_lh = NULL;
     obj_lock = CRYPTO_THREAD_lock_new();
+    if (obj_lock != NULL)
+        names_lh = lh_OBJ_NAME_new(obj_name_hash, obj_name_cmp);
+    if (names_lh == NULL) {
+        CRYPTO_THREAD_lock_free(obj_lock);
+        obj_lock = NULL;
+    }
     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
     return names_lh != NULL && obj_lock != NULL;
 }
@@ -217,10 +223,8 @@
     type &= ~OBJ_NAME_ALIAS;
 
     onp = OPENSSL_malloc(sizeof(*onp));
-    if (onp == NULL) {
-        /* ERROR */
-        goto unlock;
-    }
+    if (onp == NULL)
+        return 0;
 
     onp->name = name;
     onp->alias = alias;
diff -Nru openssl-1.1.1k/crypto/pem/pem_lib.c openssl-1.1.1m/crypto/pem/pem_lib.c
--- openssl-1.1.1k/crypto/pem/pem_lib.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/pem/pem_lib.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -899,18 +899,13 @@
 int PEM_read_bio_ex(BIO *bp, char **name_out, char **header,
                     unsigned char **data, long *len_out, unsigned int flags)
 {
-    EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new();
+    EVP_ENCODE_CTX *ctx = NULL;
     const BIO_METHOD *bmeth;
     BIO *headerB = NULL, *dataB = NULL;
     char *name = NULL;
     int len, taillen, headerlen, ret = 0;
     BUF_MEM * buf_mem;
 
-    if (ctx == NULL) {
-        PEMerr(PEM_F_PEM_READ_BIO_EX, ERR_R_MALLOC_FAILURE);
-        return 0;
-    }
-
     *len_out = 0;
     *name_out = *header = NULL;
     *data = NULL;
@@ -933,9 +928,20 @@
     if (!get_header_and_data(bp, &headerB, &dataB, name, flags))
         goto end;
 
-    EVP_DecodeInit(ctx);
     BIO_get_mem_ptr(dataB, &buf_mem);
     len = buf_mem->length;
+
+    /* There was no data in the PEM file */
+    if (len == 0)
+        goto end;
+
+    ctx = EVP_ENCODE_CTX_new();
+    if (ctx == NULL) {
+        PEMerr(PEM_F_PEM_READ_BIO_EX, ERR_R_MALLOC_FAILURE);
+        goto end;
+    }
+
+    EVP_DecodeInit(ctx);
     if (EVP_DecodeUpdate(ctx, (unsigned char*)buf_mem->data, &len,
                          (unsigned char*)buf_mem->data, len) < 0
             || EVP_DecodeFinal(ctx, (unsigned char*)&(buf_mem->data[len]),
@@ -946,9 +952,6 @@
     len += taillen;
     buf_mem->length = len;
 
-    /* There was no data in the PEM file; avoid malloc(0). */
-    if (len == 0)
-        goto end;
     headerlen = BIO_get_mem_data(headerB, NULL);
     *header = pem_malloc(headerlen + 1, flags);
     *data = pem_malloc(len, flags);
diff -Nru openssl-1.1.1k/crypto/pkcs12/p12_key.c openssl-1.1.1m/crypto/pkcs12/p12_key.c
--- openssl-1.1.1k/crypto/pkcs12/p12_key.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/pkcs12/p12_key.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -101,7 +101,7 @@
 #endif
     v = EVP_MD_block_size(md_type);
     u = EVP_MD_size(md_type);
-    if (u < 0 || v <= 0)
+    if (u <= 0 || v <= 0)
         goto err;
     D = OPENSSL_malloc(v);
     Ai = OPENSSL_malloc(u);
diff -Nru openssl-1.1.1k/crypto/poly1305/poly1305_ameth.c openssl-1.1.1m/crypto/poly1305/poly1305_ameth.c
--- openssl-1.1.1k/crypto/poly1305/poly1305_ameth.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/poly1305/poly1305_ameth.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -43,7 +43,7 @@
 
 static int poly1305_pkey_public_cmp(const EVP_PKEY *a, const EVP_PKEY *b)
 {
-    return ASN1_OCTET_STRING_cmp(EVP_PKEY_get0(a), EVP_PKEY_get0(b));
+    return ASN1_OCTET_STRING_cmp(EVP_PKEY_get0(a), EVP_PKEY_get0(b)) == 0;
 }
 
 static int poly1305_set_priv_key(EVP_PKEY *pkey, const unsigned char *priv,
diff -Nru openssl-1.1.1k/crypto/ppccap.c openssl-1.1.1m/crypto/ppccap.c
--- openssl-1.1.1k/crypto/ppccap.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/ppccap.c	2021-12-14 16:45:01.000000000 +0100
@@ -211,6 +211,12 @@
 # if __GLIBC_PREREQ(2, 16)
 #  include <sys/auxv.h>
 #  define OSSL_IMPLEMENT_GETAUXVAL
+# elif defined(__ANDROID_API__)
+/* see https://developer.android.google.cn/ndk/guides/cpu-features */
+#  if __ANDROID_API__ >= 18
+#   include <sys/auxv.h>
+#   define OSSL_IMPLEMENT_GETAUXVAL
+#  endif
 # endif
 #endif
 
diff -Nru openssl-1.1.1k/crypto/rand/rand_unix.c openssl-1.1.1m/crypto/rand/rand_unix.c
--- openssl-1.1.1k/crypto/rand/rand_unix.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/rand/rand_unix.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -378,6 +378,11 @@
         if (errno != ENOSYS)
             return -1;
     }
+#  elif defined(OPENSSL_APPLE_CRYPTO_RANDOM)
+    if (CCRandomGenerateBytes(buf, buflen) == kCCSuccess)
+	    return (ssize_t)buflen;
+
+    return -1;
 #  else
     union {
         void *p;
diff -Nru openssl-1.1.1k/crypto/rand/rand_vms.c openssl-1.1.1m/crypto/rand/rand_vms.c
--- openssl-1.1.1k/crypto/rand/rand_vms.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/rand/rand_vms.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -484,7 +484,7 @@
     struct {
         pid_t pid;
         CRYPTO_THREAD_ID tid;
-        uint64_t time;
+        unsigned __int64 time;
     } data = { 0 };
 
     /*
@@ -582,7 +582,7 @@
 {
     struct {
         CRYPTO_THREAD_ID tid;
-        uint64_t time;
+        unsigned __int64 time;
     } data = { 0 };
 
     /*
diff -Nru openssl-1.1.1k/crypto/rsa/rsa_prn.c openssl-1.1.1m/crypto/rsa/rsa_prn.c
--- openssl-1.1.1k/crypto/rsa/rsa_prn.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/rsa/rsa_prn.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2006-2017 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -34,9 +34,11 @@
     EVP_PKEY *pk;
     int ret;
     pk = EVP_PKEY_new();
-    if (pk == NULL || !EVP_PKEY_set1_RSA(pk, (RSA *)x))
+    if (pk == NULL)
         return 0;
-    ret = EVP_PKEY_print_private(bp, pk, off, NULL);
+    ret = EVP_PKEY_set1_RSA(pk, (RSA *)x);
+    if (ret)
+        ret = EVP_PKEY_print_private(bp, pk, off, NULL);
     EVP_PKEY_free(pk);
     return ret;
 }
diff -Nru openssl-1.1.1k/crypto/siphash/siphash_ameth.c openssl-1.1.1m/crypto/siphash/siphash_ameth.c
--- openssl-1.1.1k/crypto/siphash/siphash_ameth.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/siphash/siphash_ameth.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2007-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -44,7 +44,7 @@
 
 static int siphash_pkey_public_cmp(const EVP_PKEY *a, const EVP_PKEY *b)
 {
-    return ASN1_OCTET_STRING_cmp(EVP_PKEY_get0(a), EVP_PKEY_get0(b));
+    return ASN1_OCTET_STRING_cmp(EVP_PKEY_get0(a), EVP_PKEY_get0(b)) == 0;
 }
 
 static int siphash_set_priv_key(EVP_PKEY *pkey, const unsigned char *priv,
diff -Nru openssl-1.1.1k/crypto/sm2/sm2_crypt.c openssl-1.1.1m/crypto/sm2/sm2_crypt.c
--- openssl-1.1.1k/crypto/sm2/sm2_crypt.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/sm2/sm2_crypt.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved.
  * Copyright 2017 Ribose Inc. All Rights Reserved.
  * Ported from Ribose contributions from Botan.
  *
@@ -61,29 +61,20 @@
     return field_size;
 }
 
-int sm2_plaintext_size(const EC_KEY *key, const EVP_MD *digest, size_t msg_len,
-                       size_t *pt_size)
+int sm2_plaintext_size(const unsigned char *ct, size_t ct_size, size_t *pt_size)
 {
-    const size_t field_size = ec_field_size(EC_KEY_get0_group(key));
-    const int md_size = EVP_MD_size(digest);
-    size_t overhead;
+    struct SM2_Ciphertext_st *sm2_ctext = NULL;
 
-    if (md_size < 0) {
-        SM2err(SM2_F_SM2_PLAINTEXT_SIZE, SM2_R_INVALID_DIGEST);
-        return 0;
-    }
-    if (field_size == 0) {
-        SM2err(SM2_F_SM2_PLAINTEXT_SIZE, SM2_R_INVALID_FIELD);
-        return 0;
-    }
+    sm2_ctext = d2i_SM2_Ciphertext(NULL, &ct, ct_size);
 
-    overhead = 10 + 2 * field_size + (size_t)md_size;
-    if (msg_len <= overhead) {
+    if (sm2_ctext == NULL) {
         SM2err(SM2_F_SM2_PLAINTEXT_SIZE, SM2_R_INVALID_ENCODING);
         return 0;
     }
 
-    *pt_size = msg_len - overhead;
+    *pt_size = sm2_ctext->C2->length;
+    SM2_Ciphertext_free(sm2_ctext);
+
     return 1;
 }
 
@@ -303,6 +294,10 @@
     C2 = sm2_ctext->C2->data;
     C3 = sm2_ctext->C3->data;
     msg_len = sm2_ctext->C2->length;
+    if (*ptext_len < (size_t)msg_len) {
+        SM2err(SM2_F_SM2_DECRYPT, SM2_R_BUFFER_TOO_SMALL);
+        goto done;
+    }
 
     ctx = BN_CTX_new();
     if (ctx == NULL) {
diff -Nru openssl-1.1.1k/crypto/sm2/sm2_pmeth.c openssl-1.1.1m/crypto/sm2/sm2_pmeth.c
--- openssl-1.1.1k/crypto/sm2/sm2_pmeth.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/sm2/sm2_pmeth.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2006-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -151,7 +151,7 @@
     const EVP_MD *md = (dctx->md == NULL) ? EVP_sm3() : dctx->md;
 
     if (out == NULL) {
-        if (!sm2_plaintext_size(ec, md, inlen, outlen))
+        if (!sm2_plaintext_size(in, inlen, outlen))
             return -1;
         else
             return 1;
diff -Nru openssl-1.1.1k/crypto/sparcv9cap.c openssl-1.1.1m/crypto/sparcv9cap.c
--- openssl-1.1.1k/crypto/sparcv9cap.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/sparcv9cap.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2005-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2005-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -16,6 +16,7 @@
 #include <unistd.h>
 #include <openssl/bn.h>
 #include "internal/cryptlib.h"
+#include "bn/bn_local.h"    /* for definition of bn_mul_mont */
 
 #include "sparc_arch.h"
 
diff -Nru openssl-1.1.1k/crypto/srp/srp_vfy.c openssl-1.1.1m/crypto/srp/srp_vfy.c
--- openssl-1.1.1k/crypto/srp/srp_vfy.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/srp/srp_vfy.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2004-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved.
  * Copyright (c) 2004, EdelKey Project. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
@@ -684,7 +684,7 @@
     BIGNUM *x = NULL;
     BN_CTX *bn_ctx = BN_CTX_new();
     unsigned char tmp2[MAX_LEN];
-    BIGNUM *salttmp = NULL;
+    BIGNUM *salttmp = NULL, *verif;
 
     if ((user == NULL) ||
         (pass == NULL) ||
@@ -707,17 +707,18 @@
     if (x == NULL)
         goto err;
 
-    *verifier = BN_new();
-    if (*verifier == NULL)
+    verif = BN_new();
+    if (verif == NULL)
         goto err;
 
-    if (!BN_mod_exp(*verifier, g, x, N, bn_ctx)) {
-        BN_clear_free(*verifier);
+    if (!BN_mod_exp(verif, g, x, N, bn_ctx)) {
+        BN_clear_free(verif);
         goto err;
     }
 
     result = 1;
     *salt = salttmp;
+    *verifier = verif;
 
  err:
     if (salt != NULL && *salt != salttmp)
diff -Nru openssl-1.1.1k/crypto/store/loader_file.c openssl-1.1.1m/crypto/store/loader_file.c
--- openssl-1.1.1k/crypto/store/loader_file.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/store/loader_file.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -370,6 +370,7 @@
     mem->data = (char *)new_data;
     mem->max = mem->length = (size_t)new_data_len;
     X509_SIG_free(p8);
+    p8 = NULL;
 
     store_info = ossl_store_info_new_EMBEDDED(PEM_STRING_PKCS8INF, mem);
     if (store_info == NULL) {
diff -Nru openssl-1.1.1k/crypto/ts/ts_rsp_verify.c openssl-1.1.1m/crypto/ts/ts_rsp_verify.c
--- openssl-1.1.1k/crypto/ts/ts_rsp_verify.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/ts/ts_rsp_verify.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2006-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -612,6 +612,7 @@
  err:
     EVP_MD_CTX_free(md_ctx);
     X509_ALGOR_free(*md_alg);
+    *md_alg = NULL;
     OPENSSL_free(*imprint);
     *imprint_len = 0;
     *imprint = 0;
diff -Nru openssl-1.1.1k/crypto/ts/ts_verify_ctx.c openssl-1.1.1m/crypto/ts/ts_verify_ctx.c
--- openssl-1.1.1k/crypto/ts/ts_verify_ctx.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/ts/ts_verify_ctx.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -70,6 +70,7 @@
 unsigned char *TS_VERIFY_CTX_set_imprint(TS_VERIFY_CTX *ctx,
                                          unsigned char *hexstr, long len)
 {
+    OPENSSL_free(ctx->imprint);
     ctx->imprint = hexstr;
     ctx->imprint_len = len;
     return ctx->imprint;
@@ -126,6 +127,8 @@
         goto err;
     msg = imprint->hashed_msg;
     ret->imprint_len = ASN1_STRING_length(msg);
+    if (ret->imprint_len <= 0)
+        goto err;
     if ((ret->imprint = OPENSSL_malloc(ret->imprint_len)) == NULL)
         goto err;
     memcpy(ret->imprint, ASN1_STRING_get0_data(msg), ret->imprint_len);
diff -Nru openssl-1.1.1k/crypto/uid.c openssl-1.1.1m/crypto/uid.c
--- openssl-1.1.1k/crypto/uid.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/uid.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -17,7 +17,7 @@
     return 0;
 }
 
-#elif defined(__OpenBSD__) || (defined(__FreeBSD__) && __FreeBSD__ > 2) || defined(__DragonFly__)
+#elif defined(__OpenBSD__) || (defined(__FreeBSD__) && __FreeBSD__ > 2) || defined(__DragonFly__) || (defined(__GLIBC__) && defined(__FreeBSD_kernel__))
 
 # include OPENSSL_UNISTD
 
@@ -36,6 +36,12 @@
 #   include <sys/auxv.h>
 #   define OSSL_IMPLEMENT_GETAUXVAL
 #  endif
+# elif defined(__ANDROID_API__)
+/* see https://developer.android.google.cn/ndk/guides/cpu-features */
+#  if __ANDROID_API__ >= 18
+#   include <sys/auxv.h>
+#   define OSSL_IMPLEMENT_GETAUXVAL
+#  endif
 # endif
 
 int OPENSSL_issetugid(void)
diff -Nru openssl-1.1.1k/crypto/x509/t_x509.c openssl-1.1.1m/crypto/x509/t_x509.c
--- openssl-1.1.1k/crypto/x509/t_x509.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/x509/t_x509.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -365,9 +365,9 @@
         BIO_puts(out, "\n");
     } else
         BIO_printf(out, "%*sNo Rejected Uses.\n", indent, "");
-    alias = X509_alias_get0(x, NULL);
+    alias = X509_alias_get0(x, &i);
     if (alias)
-        BIO_printf(out, "%*sAlias: %s\n", indent, "", alias);
+        BIO_printf(out, "%*sAlias: %.*s\n", indent, "", i, alias);
     keyid = X509_keyid_get0(x, &keyidlen);
     if (keyid) {
         BIO_printf(out, "%*sKey Id: ", indent, "");
diff -Nru openssl-1.1.1k/crypto/x509/x509_vfy.c openssl-1.1.1m/crypto/x509/x509_vfy.c
--- openssl-1.1.1k/crypto/x509/x509_vfy.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/x509/x509_vfy.c	2021-12-14 16:45:01.000000000 +0100
@@ -2924,6 +2924,26 @@
     return ok;
 }
 
+static int augment_stack(STACK_OF(X509) *src, STACK_OF(X509) **dstPtr)
+{
+    if (src) {
+        STACK_OF(X509) *dst;
+        int i;
+
+        if (*dstPtr == NULL)
+            return ((*dstPtr = sk_X509_dup(src)) != NULL);
+
+        for (dst = *dstPtr, i = 0; i < sk_X509_num(src); ++i) {
+            if (!sk_X509_push(dst, sk_X509_value(src, i))) {
+                sk_X509_free(dst);
+                *dstPtr = NULL;
+                return 0;
+            }
+        }
+    }
+    return 1;
+}
+
 static int build_chain(X509_STORE_CTX *ctx)
 {
     SSL_DANE *dane = ctx->dane;
@@ -2967,18 +2987,7 @@
     }
 
     /*
-     * Shallow-copy the stack of untrusted certificates (with TLS, this is
-     * typically the content of the peer's certificate message) so can make
-     * multiple passes over it, while free to remove elements as we go.
-     */
-    if (ctx->untrusted && (sktmp = sk_X509_dup(ctx->untrusted)) == NULL) {
-        X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
-        ctx->error = X509_V_ERR_OUT_OF_MEM;
-        return 0;
-    }
-
-    /*
-     * If we got any "DANE-TA(2) Cert(0) Full(0)" trust-anchors from DNS, add
+     * If we got any "Cert(0) Full(0)" issuer certificates from DNS, *prepend*
      * them to our working copy of the untrusted certificate stack.  Since the
      * caller of X509_STORE_CTX_init() may have provided only a leaf cert with
      * no corresponding stack of untrusted certificates, we may need to create
@@ -2987,20 +2996,21 @@
      * containing at least the leaf certificate, but we must be prepared for
      * this to change. ]
      */
-    if (DANETLS_ENABLED(dane) && dane->certs != NULL) {
-        if (sktmp == NULL && (sktmp = sk_X509_new_null()) == NULL) {
-            X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
-            ctx->error = X509_V_ERR_OUT_OF_MEM;
-            return 0;
-        }
-        for (i = 0; i < sk_X509_num(dane->certs); ++i) {
-            if (!sk_X509_push(sktmp, sk_X509_value(dane->certs, i))) {
-                sk_X509_free(sktmp);
-                X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
-                ctx->error = X509_V_ERR_OUT_OF_MEM;
-                return 0;
-            }
-        }
+    if (DANETLS_ENABLED(dane) && !augment_stack(dane->certs, &sktmp)) {
+        X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
+        ctx->error = X509_V_ERR_OUT_OF_MEM;
+        return 0;
+    }
+
+    /*
+     * Shallow-copy the stack of untrusted certificates (with TLS, this is
+     * typically the content of the peer's certificate message) so can make
+     * multiple passes over it, while free to remove elements as we go.
+     */
+    if (!augment_stack(ctx->untrusted, &sktmp)) {
+        X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
+        ctx->error = X509_V_ERR_OUT_OF_MEM;
+        return 0;
     }
 
     /*
diff -Nru openssl-1.1.1k/crypto/x509/x509_vpm.c openssl-1.1.1m/crypto/x509/x509_vpm.c
--- openssl-1.1.1k/crypto/x509/x509_vpm.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/x509/x509_vpm.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2004-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -199,7 +199,8 @@
             return 0;
     }
 
-    /* Copy the host flags if and only if we're copying the host list */
+    x509_verify_param_copy(hostflags, 0);
+
     if (test_x509_verify_param_copy(hosts, NULL)) {
         sk_OPENSSL_STRING_pop_free(dest->hosts, str_free);
         dest->hosts = NULL;
@@ -208,7 +209,6 @@
                 sk_OPENSSL_STRING_deep_copy(src->hosts, str_copy, str_free);
             if (dest->hosts == NULL)
                 return 0;
-            dest->hostflags = src->hostflags;
         }
     }
 
diff -Nru openssl-1.1.1k/crypto/x509/x_name.c openssl-1.1.1m/crypto/x509/x_name.c
--- openssl-1.1.1k/crypto/x509/x_name.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/x509/x_name.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -217,8 +217,8 @@
         if (ret < 0)
             return ret;
         ret = x509_name_canon(a);
-        if (ret < 0)
-            return ret;
+        if (!ret)
+            return -1;
     }
     ret = a->bytes->length;
     if (out != NULL) {
diff -Nru openssl-1.1.1k/crypto/x509v3/v3_akey.c openssl-1.1.1m/crypto/x509v3/v3_akey.c
--- openssl-1.1.1k/crypto/x509v3/v3_akey.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/x509v3/v3_akey.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -39,20 +39,48 @@
                                                  STACK_OF(CONF_VALUE)
                                                  *extlist)
 {
-    char *tmp;
+    char *tmp = NULL;
+    STACK_OF(CONF_VALUE) *origextlist = extlist, *tmpextlist;
+
     if (akeyid->keyid) {
         tmp = OPENSSL_buf2hexstr(akeyid->keyid->data, akeyid->keyid->length);
-        X509V3_add_value("keyid", tmp, &extlist);
+        if (tmp == NULL) {
+            X509V3err(X509V3_F_I2V_AUTHORITY_KEYID, ERR_R_MALLOC_FAILURE);
+            return NULL;
+        }
+        if (!X509V3_add_value("keyid", tmp, &extlist)) {
+            OPENSSL_free(tmp);
+            X509V3err(X509V3_F_I2V_AUTHORITY_KEYID, ERR_R_X509_LIB);
+            goto err;
+        }
         OPENSSL_free(tmp);
     }
-    if (akeyid->issuer)
-        extlist = i2v_GENERAL_NAMES(NULL, akeyid->issuer, extlist);
+    if (akeyid->issuer) {
+        tmpextlist = i2v_GENERAL_NAMES(NULL, akeyid->issuer, extlist);
+        if (tmpextlist == NULL) {
+            X509V3err(X509V3_F_I2V_AUTHORITY_KEYID, ERR_R_X509_LIB);
+            goto err;
+        }
+        extlist = tmpextlist;
+    }
     if (akeyid->serial) {
         tmp = OPENSSL_buf2hexstr(akeyid->serial->data, akeyid->serial->length);
-        X509V3_add_value("serial", tmp, &extlist);
+        if (tmp == NULL) {
+            X509V3err(X509V3_F_I2V_AUTHORITY_KEYID, ERR_R_MALLOC_FAILURE);
+            goto err;
+        }
+        if (!X509V3_add_value("serial", tmp, &extlist)) {
+            OPENSSL_free(tmp);
+            X509V3err(X509V3_F_I2V_AUTHORITY_KEYID, ERR_R_X509_LIB);
+            goto err;
+        }
         OPENSSL_free(tmp);
     }
     return extlist;
+ err:
+    if (origextlist == NULL)
+        sk_CONF_VALUE_pop_free(extlist, X509V3_conf_free);
+    return NULL;
 }
 
 /*-
diff -Nru openssl-1.1.1k/crypto/x509v3/v3_alt.c openssl-1.1.1m/crypto/x509v3/v3_alt.c
--- openssl-1.1.1k/crypto/x509v3/v3_alt.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/x509v3/v3_alt.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -9,6 +9,7 @@
 
 #include <stdio.h>
 #include "internal/cryptlib.h"
+#include "crypto/x509.h"
 #include <openssl/conf.h>
 #include <openssl/x509v3.h>
 #include "ext_dat.h"
@@ -99,17 +100,20 @@
         break;
 
     case GEN_EMAIL:
-        if (!X509V3_add_value_uchar("email", gen->d.ia5->data, &ret))
+        if (!x509v3_add_len_value_uchar("email", gen->d.ia5->data,
+                                        gen->d.ia5->length, &ret))
             return NULL;
         break;
 
     case GEN_DNS:
-        if (!X509V3_add_value_uchar("DNS", gen->d.ia5->data, &ret))
+        if (!x509v3_add_len_value_uchar("DNS", gen->d.ia5->data,
+                                        gen->d.ia5->length, &ret))
             return NULL;
         break;
 
     case GEN_URI:
-        if (!X509V3_add_value_uchar("URI", gen->d.ia5->data, &ret))
+        if (!x509v3_add_len_value_uchar("URI", gen->d.ia5->data,
+                                        gen->d.ia5->length, &ret))
             return NULL;
         break;
 
diff -Nru openssl-1.1.1k/crypto/x509v3/v3_cpols.c openssl-1.1.1m/crypto/x509v3/v3_cpols.c
--- openssl-1.1.1k/crypto/x509v3/v3_cpols.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/x509v3/v3_cpols.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -422,7 +422,8 @@
         qualinfo = sk_POLICYQUALINFO_value(quals, i);
         switch (OBJ_obj2nid(qualinfo->pqualid)) {
         case NID_id_qt_cps:
-            BIO_printf(out, "%*sCPS: %s\n", indent, "",
+            BIO_printf(out, "%*sCPS: %.*s\n", indent, "",
+                       qualinfo->d.cpsuri->length,
                        qualinfo->d.cpsuri->data);
             break;
 
@@ -447,7 +448,8 @@
     if (notice->noticeref) {
         NOTICEREF *ref;
         ref = notice->noticeref;
-        BIO_printf(out, "%*sOrganization: %s\n", indent, "",
+        BIO_printf(out, "%*sOrganization: %.*s\n", indent, "",
+                   ref->organization->length,
                    ref->organization->data);
         BIO_printf(out, "%*sNumber%s: ", indent, "",
                    sk_ASN1_INTEGER_num(ref->noticenos) > 1 ? "s" : "");
@@ -470,7 +472,8 @@
         BIO_puts(out, "\n");
     }
     if (notice->exptext)
-        BIO_printf(out, "%*sExplicit Text: %s\n", indent, "",
+        BIO_printf(out, "%*sExplicit Text: %.*s\n", indent, "",
+                   notice->exptext->length,
                    notice->exptext->data);
 }
 
diff -Nru openssl-1.1.1k/crypto/x509v3/v3err.c openssl-1.1.1m/crypto/x509v3/v3err.c
--- openssl-1.1.1k/crypto/x509v3/v3err.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/x509v3/v3err.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,6 +1,6 @@
 /*
  * Generated by util/mkerr.pl DO NOT EDIT
- * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -39,6 +39,8 @@
      "i2s_ASN1_INTEGER"},
     {ERR_PACK(ERR_LIB_X509V3, X509V3_F_I2V_AUTHORITY_INFO_ACCESS, 0),
      "i2v_AUTHORITY_INFO_ACCESS"},
+    {ERR_PACK(ERR_LIB_X509V3, X509V3_F_I2V_AUTHORITY_KEYID, 0),
+     "i2v_AUTHORITY_KEYID"},
     {ERR_PACK(ERR_LIB_X509V3, X509V3_F_LEVEL_ADD_NODE, 0), "level_add_node"},
     {ERR_PACK(ERR_LIB_X509V3, X509V3_F_NOTICE_SECTION, 0), "notice_section"},
     {ERR_PACK(ERR_LIB_X509V3, X509V3_F_NREF_NOS, 0), "nref_nos"},
@@ -104,6 +106,8 @@
     {ERR_PACK(ERR_LIB_X509V3, X509V3_F_V3_GENERIC_EXTENSION, 0),
      "v3_generic_extension"},
     {ERR_PACK(ERR_LIB_X509V3, X509V3_F_X509V3_ADD1_I2D, 0), "X509V3_add1_i2d"},
+    {ERR_PACK(ERR_LIB_X509V3, X509V3_F_X509V3_ADD_LEN_VALUE, 0),
+     "x509v3_add_len_value"},
     {ERR_PACK(ERR_LIB_X509V3, X509V3_F_X509V3_ADD_VALUE, 0),
      "X509V3_add_value"},
     {ERR_PACK(ERR_LIB_X509V3, X509V3_F_X509V3_EXT_ADD, 0), "X509V3_EXT_add"},
diff -Nru openssl-1.1.1k/crypto/x509v3/v3_ncons.c openssl-1.1.1m/crypto/x509v3/v3_ncons.c
--- openssl-1.1.1k/crypto/x509v3/v3_ncons.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/x509v3/v3_ncons.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2003-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -63,8 +63,31 @@
 IMPLEMENT_ASN1_ALLOC_FUNCTIONS(GENERAL_SUBTREE)
 IMPLEMENT_ASN1_ALLOC_FUNCTIONS(NAME_CONSTRAINTS)
 
+
+#define IA5_OFFSET_LEN(ia5base, offset) \
+    ((ia5base)->length - ((unsigned char *)(offset) - (ia5base)->data))
+
+/* Like memchr but for ASN1_IA5STRING. Additionally you can specify the
+ * starting point to search from
+ */
+# define ia5memchr(str, start, c) memchr(start, c, IA5_OFFSET_LEN(str, start))
+
+/* Like memrrchr but for ASN1_IA5STRING */
+static char *ia5memrchr(ASN1_IA5STRING *str, int c)
+{
+    int i;
+
+    for (i = str->length; i > 0 && str->data[i - 1] != c; i--);
+
+    if (i == 0)
+        return NULL;
+
+    return (char *)&str->data[i - 1];
+}
+
 /*
- * We cannot use strncasecmp here because that applies locale specific rules.
+ * We cannot use strncasecmp here because that applies locale specific rules. It
+ * also doesn't work with ASN1_STRINGs that may have embedded NUL characters.
  * For example in Turkish 'I' is not the uppercase character for 'i'. We need to
  * do a simple ASCII case comparison ignoring the locale (that is why we use
  * numeric constants below).
@@ -89,20 +112,12 @@
 
             /* c1 > c2 */
             return 1;
-        } else if (*s1 == 0) {
-            /* If we get here we know that *s2 == 0 too */
-            return 0;
         }
     }
 
     return 0;
 }
 
-static int ia5casecmp(const char *s1, const char *s2)
-{
-    return ia5ncasecmp(s1, s2, SIZE_MAX);
-}
-
 static void *v2i_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method,
                                   X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval)
 {
@@ -337,7 +352,7 @@
         --utf8_length;
 
     /* Reject *embedded* NULs */
-    if ((size_t)utf8_length != strlen((char *)utf8_value)) {
+    if (memchr(utf8_value, 0, utf8_length) != NULL) {
         OPENSSL_free(utf8_value);
         return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
     }
@@ -536,9 +551,14 @@
 {
     char *baseptr = (char *)base->data;
     char *dnsptr = (char *)dns->data;
+
     /* Empty matches everything */
-    if (!*baseptr)
+    if (base->length == 0)
         return X509_V_OK;
+
+    if (dns->length < base->length)
+        return X509_V_ERR_PERMITTED_VIOLATION;
+
     /*
      * Otherwise can add zero or more components on the left so compare RHS
      * and if dns is longer and expect '.' as preceding character.
@@ -549,7 +569,7 @@
             return X509_V_ERR_PERMITTED_VIOLATION;
     }
 
-    if (ia5casecmp(baseptr, dnsptr))
+    if (ia5ncasecmp(baseptr, dnsptr, base->length))
         return X509_V_ERR_PERMITTED_VIOLATION;
 
     return X509_V_OK;
@@ -560,16 +580,17 @@
 {
     const char *baseptr = (char *)base->data;
     const char *emlptr = (char *)eml->data;
+    const char *baseat = ia5memrchr(base, '@');
+    const char *emlat = ia5memrchr(eml, '@');
+    size_t basehostlen, emlhostlen;
 
-    const char *baseat = strchr(baseptr, '@');
-    const char *emlat = strchr(emlptr, '@');
     if (!emlat)
         return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
     /* Special case: initial '.' is RHS match */
-    if (!baseat && (*baseptr == '.')) {
+    if (!baseat && base->length > 0 && (*baseptr == '.')) {
         if (eml->length > base->length) {
             emlptr += eml->length - base->length;
-            if (ia5casecmp(baseptr, emlptr) == 0)
+            if (ia5ncasecmp(baseptr, emlptr, base->length) == 0)
                 return X509_V_OK;
         }
         return X509_V_ERR_PERMITTED_VIOLATION;
@@ -581,6 +602,9 @@
         if (baseat != baseptr) {
             if ((baseat - baseptr) != (emlat - emlptr))
                 return X509_V_ERR_PERMITTED_VIOLATION;
+            if (memchr(baseptr, 0, baseat - baseptr) ||
+                memchr(emlptr, 0, emlat - emlptr))
+                return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
             /* Case sensitive match of local part */
             if (strncmp(baseptr, emlptr, emlat - emlptr))
                 return X509_V_ERR_PERMITTED_VIOLATION;
@@ -589,8 +613,10 @@
         baseptr = baseat + 1;
     }
     emlptr = emlat + 1;
+    basehostlen = IA5_OFFSET_LEN(base, baseptr);
+    emlhostlen = IA5_OFFSET_LEN(eml, emlptr);
     /* Just have hostname left to match: case insensitive */
-    if (ia5casecmp(baseptr, emlptr))
+    if (basehostlen != emlhostlen || ia5ncasecmp(baseptr, emlptr, emlhostlen))
         return X509_V_ERR_PERMITTED_VIOLATION;
 
     return X509_V_OK;
@@ -601,10 +627,14 @@
 {
     const char *baseptr = (char *)base->data;
     const char *hostptr = (char *)uri->data;
-    const char *p = strchr(hostptr, ':');
+    const char *p = ia5memchr(uri, (char *)uri->data, ':');
     int hostlen;
+
     /* Check for foo:// and skip past it */
-    if (!p || (p[1] != '/') || (p[2] != '/'))
+    if (p == NULL
+            || IA5_OFFSET_LEN(uri, p) < 3
+            || p[1] != '/'
+            || p[2] != '/')
         return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
     hostptr = p + 3;
 
@@ -612,13 +642,13 @@
 
     /* Look for a port indicator as end of hostname first */
 
-    p = strchr(hostptr, ':');
+    p = ia5memchr(uri, hostptr, ':');
     /* Otherwise look for trailing slash */
-    if (!p)
-        p = strchr(hostptr, '/');
+    if (p == NULL)
+        p = ia5memchr(uri, hostptr, '/');
 
-    if (!p)
-        hostlen = strlen(hostptr);
+    if (p == NULL)
+        hostlen = IA5_OFFSET_LEN(uri, hostptr);
     else
         hostlen = p - hostptr;
 
@@ -626,7 +656,7 @@
         return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
 
     /* Special case: initial '.' is RHS match */
-    if (*baseptr == '.') {
+    if (base->length > 0 && *baseptr == '.') {
         if (hostlen > base->length) {
             p = hostptr + hostlen - base->length;
             if (ia5ncasecmp(p, baseptr, base->length) == 0)
diff -Nru openssl-1.1.1k/crypto/x509v3/v3_pci.c openssl-1.1.1m/crypto/x509v3/v3_pci.c
--- openssl-1.1.1k/crypto/x509v3/v3_pci.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/x509v3/v3_pci.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2004-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -77,7 +77,8 @@
     i2a_ASN1_OBJECT(out, pci->proxyPolicy->policyLanguage);
     BIO_puts(out, "\n");
     if (pci->proxyPolicy->policy && pci->proxyPolicy->policy->data)
-        BIO_printf(out, "%*sPolicy Text: %s\n", indent, "",
+        BIO_printf(out, "%*sPolicy Text: %.*s\n", indent, "",
+                   pci->proxyPolicy->policy->length,
                    pci->proxyPolicy->policy->data);
     return 1;
 }
diff -Nru openssl-1.1.1k/crypto/x509v3/v3_utl.c openssl-1.1.1m/crypto/x509v3/v3_utl.c
--- openssl-1.1.1k/crypto/x509v3/v3_utl.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/crypto/x509v3/v3_utl.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2017 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -12,6 +12,7 @@
 #include "e_os.h"
 #include "internal/cryptlib.h"
 #include <stdio.h>
+#include <string.h>
 #include "crypto/ctype.h"
 #include <openssl/conf.h>
 #include <openssl/crypto.h>
@@ -34,17 +35,26 @@
 
 /* Add a CONF_VALUE name value pair to stack */
 
-int X509V3_add_value(const char *name, const char *value,
-                     STACK_OF(CONF_VALUE) **extlist)
+static int x509v3_add_len_value(const char *name, const char *value,
+                                size_t vallen, STACK_OF(CONF_VALUE) **extlist)
 {
     CONF_VALUE *vtmp = NULL;
     char *tname = NULL, *tvalue = NULL;
     int sk_allocated = (*extlist == NULL);
 
-    if (name && (tname = OPENSSL_strdup(name)) == NULL)
-        goto err;
-    if (value && (tvalue = OPENSSL_strdup(value)) == NULL)
+    if (name != NULL && (tname = OPENSSL_strdup(name)) == NULL)
         goto err;
+    if (value != NULL && vallen > 0) {
+        /*
+         * We tolerate a single trailing NUL character, but otherwise no
+         * embedded NULs
+         */
+        if (memchr(value, 0, vallen - 1) != NULL)
+            goto err;
+        tvalue = OPENSSL_strndup(value, vallen);
+        if (tvalue == NULL)
+            goto err;
+    }
     if ((vtmp = OPENSSL_malloc(sizeof(*vtmp))) == NULL)
         goto err;
     if (sk_allocated && (*extlist = sk_CONF_VALUE_new_null()) == NULL)
@@ -56,7 +66,7 @@
         goto err;
     return 1;
  err:
-    X509V3err(X509V3_F_X509V3_ADD_VALUE, ERR_R_MALLOC_FAILURE);
+    X509V3err(X509V3_F_X509V3_ADD_LEN_VALUE, ERR_R_MALLOC_FAILURE);
     if (sk_allocated) {
         sk_CONF_VALUE_free(*extlist);
         *extlist = NULL;
@@ -67,10 +77,26 @@
     return 0;
 }
 
+int X509V3_add_value(const char *name, const char *value,
+                     STACK_OF(CONF_VALUE) **extlist)
+{
+    return x509v3_add_len_value(name, value,
+                                value != NULL ? strlen((const char *)value) : 0,
+                                extlist);
+}
+
 int X509V3_add_value_uchar(const char *name, const unsigned char *value,
                            STACK_OF(CONF_VALUE) **extlist)
 {
-    return X509V3_add_value(name, (const char *)value, extlist);
+    return x509v3_add_len_value(name, (const char *)value,
+                                value != NULL ? strlen((const char *)value) : 0,
+                                extlist);
+}
+
+int x509v3_add_len_value_uchar(const char *name, const unsigned char *value,
+                               size_t vallen, STACK_OF(CONF_VALUE) **extlist)
+{
+    return x509v3_add_len_value(name, (const char *)value, vallen, extlist);
 }
 
 /* Free function for STACK_OF(CONF_VALUE) */
@@ -502,18 +528,26 @@
     /* First some sanity checks */
     if (email->type != V_ASN1_IA5STRING)
         return 1;
-    if (!email->data || !email->length)
+    if (email->data == NULL || email->length == 0)
+        return 1;
+    if (memchr(email->data, 0, email->length) != NULL)
         return 1;
     if (*sk == NULL)
         *sk = sk_OPENSSL_STRING_new(sk_strcmp);
     if (*sk == NULL)
         return 0;
+
+    emtmp = OPENSSL_strndup((char *)email->data, email->length);
+    if (emtmp == NULL)
+        return 0;
+
     /* Don't add duplicates */
-    if (sk_OPENSSL_STRING_find(*sk, (char *)email->data) != -1)
+    if (sk_OPENSSL_STRING_find(*sk, emtmp) != -1) {
+        OPENSSL_free(emtmp);
         return 1;
-    emtmp = OPENSSL_strdup((char *)email->data);
-    if (emtmp == NULL || !sk_OPENSSL_STRING_push(*sk, emtmp)) {
-        OPENSSL_free(emtmp);    /* free on push failure */
+    }
+    if (!sk_OPENSSL_STRING_push(*sk, emtmp)) {
+        OPENSSL_free(emtmp); /* free on push failure */
         X509_email_free(*sk);
         *sk = NULL;
         return 0;
diff -Nru openssl-1.1.1k/debian/changelog openssl-1.1.1m/debian/changelog
--- openssl-1.1.1k/debian/changelog	2021-08-24 10:28:12.000000000 +0200
+++ openssl-1.1.1m/debian/changelog	2022-01-09 21:34:51.000000000 +0100
@@ -1,3 +1,9 @@
+openssl (1.1.1m-0+deb11u1) bullseye; urgency=medium
+
+  * New upstream version.
+
+ -- Sebastian Andrzej Siewior <sebastian@breakpoint.cc>  Sun, 09 Jan 2022 21:34:51 +0100
+
 openssl (1.1.1k-1+deb11u1) bullseye-security; urgency=medium
 
   * CVE-2021-3711 (SM2 Decryption Buffer Overflow).
diff -Nru openssl-1.1.1k/debian/patches/Allow-fuzz-builds-to-detect-string-overruns.patch openssl-1.1.1m/debian/patches/Allow-fuzz-builds-to-detect-string-overruns.patch
--- openssl-1.1.1k/debian/patches/Allow-fuzz-builds-to-detect-string-overruns.patch	2021-08-24 10:28:12.000000000 +0200
+++ openssl-1.1.1m/debian/patches/Allow-fuzz-builds-to-detect-string-overruns.patch	1970-01-01 01:00:00.000000000 +0100
@@ -1,32 +0,0 @@
-From: Matt Caswell <matt@openssl.org>
-Date: Thu, 19 Aug 2021 15:25:04 +0100
-Subject: Allow fuzz builds to detect string overruns
-
-If FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION is defined then we don't NUL
-terminate ASN1_STRING datatypes. This shouldn't be necessary but we add it
-any for safety in normal builds.
----
- crypto/asn1/asn1_lib.c | 9 +++++++++
- 1 file changed, 9 insertions(+)
-
-diff --git a/crypto/asn1/asn1_lib.c b/crypto/asn1/asn1_lib.c
-index 366afc5f6c6b..2b61a7e57679 100644
---- a/crypto/asn1/asn1_lib.c
-+++ b/crypto/asn1/asn1_lib.c
-@@ -303,7 +303,16 @@ int ASN1_STRING_set(ASN1_STRING *str, const void *_data, int len_in)
-     if (data != NULL) {
-         memcpy(str->data, data, len);
-         /* an allowance for strings :-) */
-+#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
-+        /*
-+         * Arbitrary byte on the end, which should never be read if the string
-+         * length is being properly respected.
-+         */
-+        str->data[len] = 'x';
-+#else
-+        /* This should not be necessary - but we add it as a safety precaution */
-         str->data[len] = '\0';
-+#endif
-     }
-     return 1;
- }
diff -Nru openssl-1.1.1k/debian/patches/Check-the-plaintext-buffer-is-large-enough-when-decryptin.patch openssl-1.1.1m/debian/patches/Check-the-plaintext-buffer-is-large-enough-when-decryptin.patch
--- openssl-1.1.1k/debian/patches/Check-the-plaintext-buffer-is-large-enough-when-decryptin.patch	2021-08-24 10:28:12.000000000 +0200
+++ openssl-1.1.1m/debian/patches/Check-the-plaintext-buffer-is-large-enough-when-decryptin.patch	1970-01-01 01:00:00.000000000 +0100
@@ -1,26 +0,0 @@
-From: Matt Caswell <matt@openssl.org>
-Date: Fri, 13 Aug 2021 16:58:21 +0100
-Subject: Check the plaintext buffer is large enough when decrypting SM2
-
-Previously there was no check that the supplied buffer was large enough.
-It was just assumed to be sufficient. Instead we should check and fail if
-not.
----
- crypto/sm2/sm2_crypt.c | 4 ++++
- 1 file changed, 4 insertions(+)
-
-diff --git a/crypto/sm2/sm2_crypt.c b/crypto/sm2/sm2_crypt.c
-index 1188abfc6b57..00055a4e510e 100644
---- a/crypto/sm2/sm2_crypt.c
-+++ b/crypto/sm2/sm2_crypt.c
-@@ -294,6 +294,10 @@ int sm2_decrypt(const EC_KEY *key,
-     C2 = sm2_ctext->C2->data;
-     C3 = sm2_ctext->C3->data;
-     msg_len = sm2_ctext->C2->length;
-+    if (*ptext_len < (size_t)msg_len) {
-+        SM2err(SM2_F_SM2_DECRYPT, SM2_R_BUFFER_TOO_SMALL);
-+        goto done;
-+    }
- 
-     ctx = BN_CTX_new();
-     if (ctx == NULL) {
diff -Nru openssl-1.1.1k/debian/patches/Correctly-calculate-the-length-of-SM2-plaintext-given-the.patch openssl-1.1.1m/debian/patches/Correctly-calculate-the-length-of-SM2-plaintext-given-the.patch
--- openssl-1.1.1k/debian/patches/Correctly-calculate-the-length-of-SM2-plaintext-given-the.patch	2021-08-24 10:28:12.000000000 +0200
+++ openssl-1.1.1m/debian/patches/Correctly-calculate-the-length-of-SM2-plaintext-given-the.patch	1970-01-01 01:00:00.000000000 +0100
@@ -1,113 +0,0 @@
-From: Matt Caswell <matt@openssl.org>
-Date: Fri, 13 Aug 2021 14:14:51 +0100
-Subject: Correctly calculate the length of SM2 plaintext given the ciphertext
-
-Previously the length of the SM2 plaintext could be incorrectly calculated.
-The plaintext length was calculated by taking the ciphertext length and
-taking off an "overhead" value.
-
-The overhead value was assumed to have a "fixed" element of 10 bytes.
-This is incorrect since in some circumstances it can be more than 10 bytes.
-Additionally the overhead included the length of two integers C1x and C1y,
-which were assumed to be the same length as the field size (32 bytes for
-the SM2 curve). However in some cases these integers can have an additional
-padding byte when the msb is set, to disambiguate them from negative
-integers. Additionally the integers can also be less than 32 bytes in
-length in some cases.
-
-If the calculated overhead is incorrect and larger than the actual value
-this can result in the calculated plaintext length being too small.
-Applications are likely to allocate buffer sizes based on this and therefore
-a buffer overrun can occur.
-
-CVE-2021-3711
-
-Issue reported by John Ouyang.
----
- crypto/sm2/sm2_crypt.c   | 23 +++++++----------------
- crypto/sm2/sm2_pmeth.c   |  2 +-
- include/crypto/sm2.h     |  3 +--
- test/sm2_internal_test.c |  2 +-
- 4 files changed, 10 insertions(+), 20 deletions(-)
-
-diff --git a/crypto/sm2/sm2_crypt.c b/crypto/sm2/sm2_crypt.c
-index ef505f64412b..1188abfc6b57 100644
---- a/crypto/sm2/sm2_crypt.c
-+++ b/crypto/sm2/sm2_crypt.c
-@@ -61,29 +61,20 @@ static size_t ec_field_size(const EC_GROUP *group)
-     return field_size;
- }
- 
--int sm2_plaintext_size(const EC_KEY *key, const EVP_MD *digest, size_t msg_len,
--                       size_t *pt_size)
-+int sm2_plaintext_size(const unsigned char *ct, size_t ct_size, size_t *pt_size)
- {
--    const size_t field_size = ec_field_size(EC_KEY_get0_group(key));
--    const int md_size = EVP_MD_size(digest);
--    size_t overhead;
-+    struct SM2_Ciphertext_st *sm2_ctext = NULL;
- 
--    if (md_size < 0) {
--        SM2err(SM2_F_SM2_PLAINTEXT_SIZE, SM2_R_INVALID_DIGEST);
--        return 0;
--    }
--    if (field_size == 0) {
--        SM2err(SM2_F_SM2_PLAINTEXT_SIZE, SM2_R_INVALID_FIELD);
--        return 0;
--    }
-+    sm2_ctext = d2i_SM2_Ciphertext(NULL, &ct, ct_size);
- 
--    overhead = 10 + 2 * field_size + (size_t)md_size;
--    if (msg_len <= overhead) {
-+    if (sm2_ctext == NULL) {
-         SM2err(SM2_F_SM2_PLAINTEXT_SIZE, SM2_R_INVALID_ENCODING);
-         return 0;
-     }
- 
--    *pt_size = msg_len - overhead;
-+    *pt_size = sm2_ctext->C2->length;
-+    SM2_Ciphertext_free(sm2_ctext);
-+
-     return 1;
- }
- 
-diff --git a/crypto/sm2/sm2_pmeth.c b/crypto/sm2/sm2_pmeth.c
-index b42a14c32f26..27025fbf3a2c 100644
---- a/crypto/sm2/sm2_pmeth.c
-+++ b/crypto/sm2/sm2_pmeth.c
-@@ -151,7 +151,7 @@ static int pkey_sm2_decrypt(EVP_PKEY_CTX *ctx,
-     const EVP_MD *md = (dctx->md == NULL) ? EVP_sm3() : dctx->md;
- 
-     if (out == NULL) {
--        if (!sm2_plaintext_size(ec, md, inlen, outlen))
-+        if (!sm2_plaintext_size(in, inlen, outlen))
-             return -1;
-         else
-             return 1;
-diff --git a/include/crypto/sm2.h b/include/crypto/sm2.h
-index 76ee80baff19..50851a83cea2 100644
---- a/include/crypto/sm2.h
-+++ b/include/crypto/sm2.h
-@@ -60,8 +60,7 @@ int sm2_verify(const unsigned char *dgst, int dgstlen,
- int sm2_ciphertext_size(const EC_KEY *key, const EVP_MD *digest, size_t msg_len,
-                         size_t *ct_size);
- 
--int sm2_plaintext_size(const EC_KEY *key, const EVP_MD *digest, size_t msg_len,
--                       size_t *pt_size);
-+int sm2_plaintext_size(const unsigned char *ct, size_t ct_size, size_t *pt_size);
- 
- int sm2_encrypt(const EC_KEY *key,
-                 const EVP_MD *digest,
-diff --git a/test/sm2_internal_test.c b/test/sm2_internal_test.c
-index 2bb73947ff3b..41827bb82fcb 100644
---- a/test/sm2_internal_test.c
-+++ b/test/sm2_internal_test.c
-@@ -185,7 +185,7 @@ static int test_sm2_crypt(const EC_GROUP *group,
-     if (!TEST_mem_eq(ctext, ctext_len, expected, ctext_len))
-         goto done;
- 
--    if (!TEST_true(sm2_plaintext_size(key, digest, ctext_len, &ptext_len))
-+    if (!TEST_true(sm2_plaintext_size(ctext, ctext_len, &ptext_len))
-             || !TEST_int_eq(ptext_len, msg_len))
-         goto done;
- 
diff -Nru openssl-1.1.1k/debian/patches/Extend-tests-for-SM2-decryption.patch openssl-1.1.1m/debian/patches/Extend-tests-for-SM2-decryption.patch
--- openssl-1.1.1k/debian/patches/Extend-tests-for-SM2-decryption.patch	2021-08-24 10:28:12.000000000 +0200
+++ openssl-1.1.1m/debian/patches/Extend-tests-for-SM2-decryption.patch	1970-01-01 01:00:00.000000000 +0100
@@ -1,32 +0,0 @@
-From: Matt Caswell <matt@openssl.org>
-Date: Fri, 13 Aug 2021 14:49:47 +0100
-Subject: Extend tests for SM2 decryption
-
-Check the case where C1y < 32 bytes in length (i.e. short overhead), and
-also the case with longer plaintext and C1x and C1y > 32 bytes in length
-(i.e. long overhead)
----
- test/recipes/30-test_evp_data/evppkey.txt | 10 ++++++++++
- 1 file changed, 10 insertions(+)
-
-diff --git a/test/recipes/30-test_evp_data/evppkey.txt b/test/recipes/30-test_evp_data/evppkey.txt
-index 736e0ce4d33f..c3947cb000e1 100644
---- a/test/recipes/30-test_evp_data/evppkey.txt
-+++ b/test/recipes/30-test_evp_data/evppkey.txt
-@@ -18444,6 +18444,16 @@ Decrypt = SM2_key1
- Input = 30818A0220466BE2EF5C11782EC77864A0055417F407A5AFC11D653C6BCE69E417BB1D05B6022062B572E21FF0DDF5C726BD3F9FF2EAE56E6294713A607E9B9525628965F62CC804203C1B5713B5DB2728EB7BF775E44F4689FC32668BDC564F52EA45B09E8DF2A5F40422084A9D0CC2997092B7D3C404FCE95956EB604D732B2307A8E5B8900ED6608CA5B197
- Output = "The floofy bunnies hop at midnight"
- 
-+# Test with an C1y value < 32 bytes in length (self generated)
-+Decrypt = SM2_key1
-+Input = 3072022070DAD60CDA7C30D64CF4F278A849003581223F5324BFEC9BB329229BFFAD21A6021F18AFAB2B35459D2643243B242BE4EA80C6FA5071D2D847340CC57EB9309E5D04200B772E4DB664B2601E3B85E39C4AA8C2C1910308BE13B331E009C5A9258C29FD040B6D588BE9260A94DA18E0E6
-+Output = "Hello World"
-+
-+# Test with an C1x and C1y valuey > 32 bytes in length, and longer plaintext (self generated)
-+Decrypt = SM2_key1
-+Input = 3081DD022100CD49634BBCB21CAFFFA6D33669A5A867231CB2A942A14352EF4CAF6DC3344D54022100C35B41D4DEBB3A2735EFEE821B9EBA566BD86900176A0C06672E30EE5CC04E930420C4190A3D80D86C4BD20E99F7E4B59BF6427C6808793533EEA9591D1188EC56B50473747295470E81D951BED279AC1B86A1AFE388CD2833FA9632799EC199C7D364E5663D5A94888BB2358CFCBF6283184DE0CBC41CCEA91D24746E99D231A1DA77AFD83CDF908190ED628B7369724494568A27C782A1D1D7294BCAD80C34569ED22859896301128A8118F48924D8CCD43E998D9533
-+Output = "Some longer plaintext for testing SM2 decryption. Blah blah blah blah blah blah blah blah blah blah blah blah blah."
-+
- # This is a "fake" test as it does only verify that the SM2 EVP_PKEY interface
- # is capable of creating a signature without failing, but it does not say
- # anything about the generated signature being valid, nor does it test the
diff -Nru openssl-1.1.1k/debian/patches/Fix-append_ia5-function-to-not-assume-NUL-terminated-stri.patch openssl-1.1.1m/debian/patches/Fix-append_ia5-function-to-not-assume-NUL-terminated-stri.patch
--- openssl-1.1.1k/debian/patches/Fix-append_ia5-function-to-not-assume-NUL-terminated-stri.patch	2021-08-24 10:28:12.000000000 +0200
+++ openssl-1.1.1m/debian/patches/Fix-append_ia5-function-to-not-assume-NUL-terminated-stri.patch	1970-01-01 01:00:00.000000000 +0100
@@ -1,45 +0,0 @@
-From: Matt Caswell <matt@openssl.org>
-Date: Wed, 18 Aug 2021 17:58:23 +0100
-Subject: Fix append_ia5 function to not assume NUL terminated strings
-
-ASN.1 strings may not be NUL terminated. Don't assume they are.
----
- crypto/x509v3/v3_utl.c | 18 +++++++++++++-----
- 1 file changed, 13 insertions(+), 5 deletions(-)
-
-diff --git a/crypto/x509v3/v3_utl.c b/crypto/x509v3/v3_utl.c
-index 99add36a764a..706dd22ffaba 100644
---- a/crypto/x509v3/v3_utl.c
-+++ b/crypto/x509v3/v3_utl.c
-@@ -525,18 +525,26 @@ static int append_ia5(STACK_OF(OPENSSL_STRING) **sk, const ASN1_IA5STRING *email
-     /* First some sanity checks */
-     if (email->type != V_ASN1_IA5STRING)
-         return 1;
--    if (!email->data || !email->length)
-+    if (email->data == NULL || email->length == 0)
-+        return 1;
-+    if (memchr(email->data, 0, email->length) != NULL)
-         return 1;
-     if (*sk == NULL)
-         *sk = sk_OPENSSL_STRING_new(sk_strcmp);
-     if (*sk == NULL)
-         return 0;
-+
-+    emtmp = OPENSSL_strndup((char *)email->data, email->length);
-+    if (emtmp == NULL)
-+        return 0;
-+
-     /* Don't add duplicates */
--    if (sk_OPENSSL_STRING_find(*sk, (char *)email->data) != -1)
-+    if (sk_OPENSSL_STRING_find(*sk, emtmp) != -1) {
-+        OPENSSL_free(emtmp);
-         return 1;
--    emtmp = OPENSSL_strdup((char *)email->data);
--    if (emtmp == NULL || !sk_OPENSSL_STRING_push(*sk, emtmp)) {
--        OPENSSL_free(emtmp);    /* free on push failure */
-+    }
-+    if (!sk_OPENSSL_STRING_push(*sk, emtmp)) {
-+        OPENSSL_free(emtmp); /* free on push failure */
-         X509_email_free(*sk);
-         *sk = NULL;
-         return 0;
diff -Nru openssl-1.1.1k/debian/patches/Fix-a-read-buffer-overrun-in-X509_aux_print.patch openssl-1.1.1m/debian/patches/Fix-a-read-buffer-overrun-in-X509_aux_print.patch
--- openssl-1.1.1k/debian/patches/Fix-a-read-buffer-overrun-in-X509_aux_print.patch	2021-08-24 10:28:12.000000000 +0200
+++ openssl-1.1.1m/debian/patches/Fix-a-read-buffer-overrun-in-X509_aux_print.patch	1970-01-01 01:00:00.000000000 +0100
@@ -1,56 +0,0 @@
-From: Ingo Schwarze <schwarze@openbsd.org>
-Date: Sun, 18 Jul 2021 17:48:06 +0200
-Subject: Fix a read buffer overrun in X509_aux_print().
-
-The ASN1_STRING_get0_data(3) manual explitely cautions the reader
-that the data is not necessarily NUL-terminated, and the function
-X509_alias_set1(3) does not sanitize the data passed into it in any
-way either, so we must assume the return value from X509_alias_get0(3)
-is merely a byte array and not necessarily a string in the sense
-of the C language.
-
-I found this bug while writing manual pages for X509_print_ex(3)
-and related functions.  Theo Buehler <tb@openbsd.org> checked my
-patch to fix the same bug in LibreSSL, see
-
-http://cvsweb.openbsd.org/src/lib/libcrypto/asn1/t_x509a.c#rev1.9
-
-As an aside, note that the function still produces incomplete and
-misleading results when the data contains a NUL byte in the middle
-and that error handling is consistently absent throughout, even
-though the function provides an "int" return value obviously intended
-to be 1 for success and 0 for failure, and even though this function
-is called by another function that also wants to return 1 for success
-and 0 for failure and even does so in many of its code paths, though
-not in others.  But let's stay focussed.  Many things would be nice
-to have in the wide wild world, but a buffer overflow must not be
-allowed to remain in our backyard.
-
-CLA: trivial
-
-Reviewed-by: Tim Hudson <tjh@openssl.org>
-Reviewed-by: Paul Dale <pauli@openssl.org>
-Reviewed-by: Tomas Mraz <tomas@openssl.org>
-(Merged from https://github.com/openssl/openssl/pull/16108)
-
-(cherry picked from commit c5dc9ab965f2a69bca964c709e648158f3e4cd67)
----
- crypto/x509/t_x509.c | 4 ++--
- 1 file changed, 2 insertions(+), 2 deletions(-)
-
-diff --git a/crypto/x509/t_x509.c b/crypto/x509/t_x509.c
-index 12d807f705ed..3ba0b3a045fe 100644
---- a/crypto/x509/t_x509.c
-+++ b/crypto/x509/t_x509.c
-@@ -365,9 +365,9 @@ int X509_aux_print(BIO *out, X509 *x, int indent)
-         BIO_puts(out, "\n");
-     } else
-         BIO_printf(out, "%*sNo Rejected Uses.\n", indent, "");
--    alias = X509_alias_get0(x, NULL);
-+    alias = X509_alias_get0(x, &i);
-     if (alias)
--        BIO_printf(out, "%*sAlias: %s\n", indent, "", alias);
-+        BIO_printf(out, "%*sAlias: %.*s\n", indent, "", i, alias);
-     keyid = X509_keyid_get0(x, &keyidlen);
-     if (keyid) {
-         BIO_printf(out, "%*sKey Id: ", indent, "");
diff -Nru openssl-1.1.1k/debian/patches/Fix-EC_GROUP_new_from_ecparameters-to-check-the-base-leng.patch openssl-1.1.1m/debian/patches/Fix-EC_GROUP_new_from_ecparameters-to-check-the-base-leng.patch
--- openssl-1.1.1k/debian/patches/Fix-EC_GROUP_new_from_ecparameters-to-check-the-base-leng.patch	2021-08-24 10:28:12.000000000 +0200
+++ openssl-1.1.1m/debian/patches/Fix-EC_GROUP_new_from_ecparameters-to-check-the-base-leng.patch	1970-01-01 01:00:00.000000000 +0100
@@ -1,26 +0,0 @@
-From: Matt Caswell <matt@openssl.org>
-Date: Thu, 19 Aug 2021 12:24:17 +0100
-Subject: Fix EC_GROUP_new_from_ecparameters to check the base length
-
-Check that there's at least one byte in params->base before trying to
-read it.
----
- crypto/ec/ec_asn1.c | 5 ++++-
- 1 file changed, 4 insertions(+), 1 deletion(-)
-
-diff --git a/crypto/ec/ec_asn1.c b/crypto/ec/ec_asn1.c
-index 7b7c75ce8443..e497a259095d 100644
---- a/crypto/ec/ec_asn1.c
-+++ b/crypto/ec/ec_asn1.c
-@@ -761,7 +761,10 @@ EC_GROUP *EC_GROUP_new_from_ecparameters(const ECPARAMETERS *params)
-         ret->seed_len = params->curve->seed->length;
-     }
- 
--    if (!params->order || !params->base || !params->base->data) {
-+    if (params->order == NULL
-+            || params->base == NULL
-+            || params->base->data == NULL
-+            || params->base->length == 0) {
-         ECerr(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, EC_R_ASN1_ERROR);
-         goto err;
-     }
diff -Nru openssl-1.1.1k/debian/patches/Fix-i2v_GENERAL_NAME-to-not-assume-NUL-terminated-strings.patch openssl-1.1.1m/debian/patches/Fix-i2v_GENERAL_NAME-to-not-assume-NUL-terminated-strings.patch
--- openssl-1.1.1k/debian/patches/Fix-i2v_GENERAL_NAME-to-not-assume-NUL-terminated-strings.patch	2021-08-24 10:28:12.000000000 +0200
+++ openssl-1.1.1m/debian/patches/Fix-i2v_GENERAL_NAME-to-not-assume-NUL-terminated-strings.patch	1970-01-01 01:00:00.000000000 +0100
@@ -1,136 +0,0 @@
-From: Matt Caswell <matt@openssl.org>
-Date: Wed, 18 Aug 2021 12:24:22 +0100
-Subject: Fix i2v_GENERAL_NAME to not assume NUL terminated strings
-
-ASN.1 strings may not be NUL terminated. Don't assume they are.
----
- crypto/x509v3/v3_alt.c | 10 +++++++---
- crypto/x509v3/v3_utl.c | 35 +++++++++++++++++++++++++++++------
- include/crypto/x509.h  |  5 +++++
- 3 files changed, 41 insertions(+), 9 deletions(-)
-
-diff --git a/crypto/x509v3/v3_alt.c b/crypto/x509v3/v3_alt.c
-index 4dce0041012e..6e5f9f8b0eac 100644
---- a/crypto/x509v3/v3_alt.c
-+++ b/crypto/x509v3/v3_alt.c
-@@ -9,6 +9,7 @@
- 
- #include <stdio.h>
- #include "internal/cryptlib.h"
-+#include "crypto/x509.h"
- #include <openssl/conf.h>
- #include <openssl/x509v3.h>
- #include "ext_dat.h"
-@@ -99,17 +100,20 @@ STACK_OF(CONF_VALUE) *i2v_GENERAL_NAME(X509V3_EXT_METHOD *method,
-         break;
- 
-     case GEN_EMAIL:
--        if (!X509V3_add_value_uchar("email", gen->d.ia5->data, &ret))
-+        if (!x509v3_add_len_value_uchar("email", gen->d.ia5->data,
-+                                        gen->d.ia5->length, &ret))
-             return NULL;
-         break;
- 
-     case GEN_DNS:
--        if (!X509V3_add_value_uchar("DNS", gen->d.ia5->data, &ret))
-+        if (!x509v3_add_len_value_uchar("DNS", gen->d.ia5->data,
-+                                        gen->d.ia5->length, &ret))
-             return NULL;
-         break;
- 
-     case GEN_URI:
--        if (!X509V3_add_value_uchar("URI", gen->d.ia5->data, &ret))
-+        if (!x509v3_add_len_value_uchar("URI", gen->d.ia5->data,
-+                                        gen->d.ia5->length, &ret))
-             return NULL;
-         break;
- 
-diff --git a/crypto/x509v3/v3_utl.c b/crypto/x509v3/v3_utl.c
-index 7281a7b917a8..99add36a764a 100644
---- a/crypto/x509v3/v3_utl.c
-+++ b/crypto/x509v3/v3_utl.c
-@@ -12,6 +12,7 @@
- #include "e_os.h"
- #include "internal/cryptlib.h"
- #include <stdio.h>
-+#include <string.h>
- #include "crypto/ctype.h"
- #include <openssl/conf.h>
- #include <openssl/crypto.h>
-@@ -34,17 +35,23 @@ static int ipv6_hex(unsigned char *out, const char *in, int inlen);
- 
- /* Add a CONF_VALUE name value pair to stack */
- 
--int X509V3_add_value(const char *name, const char *value,
--                     STACK_OF(CONF_VALUE) **extlist)
-+static int x509v3_add_len_value(const char *name, const char *value,
-+                                size_t vallen, STACK_OF(CONF_VALUE) **extlist)
- {
-     CONF_VALUE *vtmp = NULL;
-     char *tname = NULL, *tvalue = NULL;
-     int sk_allocated = (*extlist == NULL);
- 
--    if (name && (tname = OPENSSL_strdup(name)) == NULL)
--        goto err;
--    if (value && (tvalue = OPENSSL_strdup(value)) == NULL)
-+    if (name != NULL && (tname = OPENSSL_strdup(name)) == NULL)
-         goto err;
-+    if (value != NULL) {
-+        /* We don't allow embeded NUL characters */
-+        if (memchr(value, 0, vallen) != NULL)
-+            goto err;
-+        tvalue = OPENSSL_strndup(value, vallen);
-+        if (tvalue == NULL)
-+            goto err;
-+    }
-     if ((vtmp = OPENSSL_malloc(sizeof(*vtmp))) == NULL)
-         goto err;
-     if (sk_allocated && (*extlist = sk_CONF_VALUE_new_null()) == NULL)
-@@ -67,10 +74,26 @@ int X509V3_add_value(const char *name, const char *value,
-     return 0;
- }
- 
-+int X509V3_add_value(const char *name, const char *value,
-+                     STACK_OF(CONF_VALUE) **extlist)
-+{
-+    return x509v3_add_len_value(name, value,
-+                                value != NULL ? strlen((const char *)value) : 0,
-+                                extlist);
-+}
-+
- int X509V3_add_value_uchar(const char *name, const unsigned char *value,
-                            STACK_OF(CONF_VALUE) **extlist)
- {
--    return X509V3_add_value(name, (const char *)value, extlist);
-+    return x509v3_add_len_value(name, (const char *)value,
-+                                value != NULL ? strlen((const char *)value) : 0,
-+                                extlist);
-+}
-+
-+int x509v3_add_len_value_uchar(const char *name, const unsigned char *value,
-+                               size_t vallen, STACK_OF(CONF_VALUE) **extlist)
-+{
-+    return x509v3_add_len_value(name, (const char *)value, vallen, extlist);
- }
- 
- /* Free function for STACK_OF(CONF_VALUE) */
-diff --git a/include/crypto/x509.h b/include/crypto/x509.h
-index b53c2b03c39e..7ffb8abfe71b 100644
---- a/include/crypto/x509.h
-+++ b/include/crypto/x509.h
-@@ -8,6 +8,8 @@
-  */
- 
- #include "internal/refcount.h"
-+#include <openssl/x509.h>
-+#include <openssl/conf.h>
- 
- /* Internal X509 structures and functions: not for application use */
- 
-@@ -284,3 +286,6 @@ int a2i_ipadd(unsigned char *ipout, const char *ipasc);
- int x509_set1_time(ASN1_TIME **ptm, const ASN1_TIME *tm);
- 
- void x509_init_sig_info(X509 *x);
-+
-+int x509v3_add_len_value_uchar(const char *name, const unsigned char *value,
-+                               size_t vallen, STACK_OF(CONF_VALUE) **extlist);
diff -Nru openssl-1.1.1k/debian/patches/Fix-NETSCAPE_SPKI_print-function-to-not-assume-NUL-termin.patch openssl-1.1.1m/debian/patches/Fix-NETSCAPE_SPKI_print-function-to-not-assume-NUL-termin.patch
--- openssl-1.1.1k/debian/patches/Fix-NETSCAPE_SPKI_print-function-to-not-assume-NUL-termin.patch	2021-08-24 10:28:12.000000000 +0200
+++ openssl-1.1.1m/debian/patches/Fix-NETSCAPE_SPKI_print-function-to-not-assume-NUL-termin.patch	1970-01-01 01:00:00.000000000 +0100
@@ -1,23 +0,0 @@
-From: Matt Caswell <matt@openssl.org>
-Date: Thu, 19 Aug 2021 12:23:38 +0100
-Subject: Fix NETSCAPE_SPKI_print function to not assume NUL terminated
- strings
-
-ASN.1 strings may not be NUL terminated. Don't assume they are.
----
- crypto/asn1/t_spki.c | 2 +-
- 1 file changed, 1 insertion(+), 1 deletion(-)
-
-diff --git a/crypto/asn1/t_spki.c b/crypto/asn1/t_spki.c
-index 51b56d0aa9f7..64ee77eeecba 100644
---- a/crypto/asn1/t_spki.c
-+++ b/crypto/asn1/t_spki.c
-@@ -38,7 +38,7 @@ int NETSCAPE_SPKI_print(BIO *out, NETSCAPE_SPKI *spki)
-     }
-     chal = spki->spkac->challenge;
-     if (chal->length)
--        BIO_printf(out, "  Challenge String: %s\n", chal->data);
-+        BIO_printf(out, "  Challenge String: %.*s\n", chal->length, chal->data);
-     i = OBJ_obj2nid(spki->sig_algor.algorithm);
-     BIO_printf(out, "  Signature Algorithm: %s",
-                (i == NID_undef) ? "UNKNOWN" : OBJ_nid2ln(i));
diff -Nru openssl-1.1.1k/debian/patches/Fix-POLICYINFO-printing-to-not-assume-NUL-terminated-stri.patch openssl-1.1.1m/debian/patches/Fix-POLICYINFO-printing-to-not-assume-NUL-terminated-stri.patch
--- openssl-1.1.1k/debian/patches/Fix-POLICYINFO-printing-to-not-assume-NUL-terminated-stri.patch	2021-08-24 10:28:12.000000000 +0200
+++ openssl-1.1.1m/debian/patches/Fix-POLICYINFO-printing-to-not-assume-NUL-terminated-stri.patch	1970-01-01 01:00:00.000000000 +0100
@@ -1,43 +0,0 @@
-From: Matt Caswell <matt@openssl.org>
-Date: Wed, 18 Aug 2021 12:31:38 +0100
-Subject: Fix POLICYINFO printing to not assume NUL terminated strings
-
-ASN.1 strings may not be NUL terminated. Don't assume they are.
----
- crypto/x509v3/v3_cpols.c | 9 ++++++---
- 1 file changed, 6 insertions(+), 3 deletions(-)
-
-diff --git a/crypto/x509v3/v3_cpols.c b/crypto/x509v3/v3_cpols.c
-index 1d12c899125c..861e8455dd08 100644
---- a/crypto/x509v3/v3_cpols.c
-+++ b/crypto/x509v3/v3_cpols.c
-@@ -422,7 +422,8 @@ static void print_qualifiers(BIO *out, STACK_OF(POLICYQUALINFO) *quals,
-         qualinfo = sk_POLICYQUALINFO_value(quals, i);
-         switch (OBJ_obj2nid(qualinfo->pqualid)) {
-         case NID_id_qt_cps:
--            BIO_printf(out, "%*sCPS: %s\n", indent, "",
-+            BIO_printf(out, "%*sCPS: %.*s\n", indent, "",
-+                       qualinfo->d.cpsuri->length,
-                        qualinfo->d.cpsuri->data);
-             break;
- 
-@@ -447,7 +448,8 @@ static void print_notice(BIO *out, USERNOTICE *notice, int indent)
-     if (notice->noticeref) {
-         NOTICEREF *ref;
-         ref = notice->noticeref;
--        BIO_printf(out, "%*sOrganization: %s\n", indent, "",
-+        BIO_printf(out, "%*sOrganization: %.*s\n", indent, "",
-+                   ref->organization->length,
-                    ref->organization->data);
-         BIO_printf(out, "%*sNumber%s: ", indent, "",
-                    sk_ASN1_INTEGER_num(ref->noticenos) > 1 ? "s" : "");
-@@ -470,7 +472,8 @@ static void print_notice(BIO *out, USERNOTICE *notice, int indent)
-         BIO_puts(out, "\n");
-     }
-     if (notice->exptext)
--        BIO_printf(out, "%*sExplicit Text: %s\n", indent, "",
-+        BIO_printf(out, "%*sExplicit Text: %.*s\n", indent, "",
-+                   notice->exptext->length,
-                    notice->exptext->data);
- }
- 
diff -Nru openssl-1.1.1k/debian/patches/Fix-printing-of-PROXY_CERT_INFO_EXTENSION-to-not-assume-N.patch openssl-1.1.1m/debian/patches/Fix-printing-of-PROXY_CERT_INFO_EXTENSION-to-not-assume-N.patch
--- openssl-1.1.1k/debian/patches/Fix-printing-of-PROXY_CERT_INFO_EXTENSION-to-not-assume-N.patch	2021-08-24 10:28:12.000000000 +0200
+++ openssl-1.1.1m/debian/patches/Fix-printing-of-PROXY_CERT_INFO_EXTENSION-to-not-assume-N.patch	1970-01-01 01:00:00.000000000 +0100
@@ -1,24 +0,0 @@
-From: Matt Caswell <matt@openssl.org>
-Date: Wed, 18 Aug 2021 14:02:40 +0100
-Subject: Fix printing of PROXY_CERT_INFO_EXTENSION to not assume NUL
- terminated strings
-
-ASN.1 strings may not be NUL terminated. Don't assume they are.
----
- crypto/x509v3/v3_pci.c | 3 ++-
- 1 file changed, 2 insertions(+), 1 deletion(-)
-
-diff --git a/crypto/x509v3/v3_pci.c b/crypto/x509v3/v3_pci.c
-index 3d124fa6d95d..98b6ef25e280 100644
---- a/crypto/x509v3/v3_pci.c
-+++ b/crypto/x509v3/v3_pci.c
-@@ -77,7 +77,8 @@ static int i2r_pci(X509V3_EXT_METHOD *method, PROXY_CERT_INFO_EXTENSION *pci,
-     i2a_ASN1_OBJECT(out, pci->proxyPolicy->policyLanguage);
-     BIO_puts(out, "\n");
-     if (pci->proxyPolicy->policy && pci->proxyPolicy->policy->data)
--        BIO_printf(out, "%*sPolicy Text: %s\n", indent, "",
-+        BIO_printf(out, "%*sPolicy Text: %.*s\n", indent, "",
-+                   pci->proxyPolicy->policy->length,
-                    pci->proxyPolicy->policy->data);
-     return 1;
- }
diff -Nru openssl-1.1.1k/debian/patches/Fix-test-code-to-not-assume-NUL-terminated-strings.patch openssl-1.1.1m/debian/patches/Fix-test-code-to-not-assume-NUL-terminated-strings.patch
--- openssl-1.1.1k/debian/patches/Fix-test-code-to-not-assume-NUL-terminated-strings.patch	2021-08-24 10:28:12.000000000 +0200
+++ openssl-1.1.1m/debian/patches/Fix-test-code-to-not-assume-NUL-terminated-strings.patch	1970-01-01 01:00:00.000000000 +0100
@@ -1,30 +0,0 @@
-From: Matt Caswell <matt@openssl.org>
-Date: Wed, 18 Aug 2021 17:37:41 +0100
-Subject: Fix test code to not assume NUL terminated strings
-
-ASN.1 strings may not be NUL terminated. Don't assume they are.
----
- test/x509_time_test.c | 10 ++++++----
- 1 file changed, 6 insertions(+), 4 deletions(-)
-
-diff --git a/test/x509_time_test.c b/test/x509_time_test.c
-index b6fd38a5c587..d0993d9c0416 100644
---- a/test/x509_time_test.c
-+++ b/test/x509_time_test.c
-@@ -330,10 +330,12 @@ static int test_x509_time(int idx)
- 
-     /* if t is not NULL but expected_string is NULL, it is an 'OK' case too */
-     if (t != NULL && x509_format_tests[idx].expected_string) {
--        if (!TEST_str_eq((const char *)t->data,
--                    x509_format_tests[idx].expected_string)) {
--            TEST_info("test_x509_time(%d) failed: expected_string %s, got %s\n",
--                    idx, x509_format_tests[idx].expected_string, t->data);
-+        if (!TEST_mem_eq((const char *)t->data, t->length,
-+                    x509_format_tests[idx].expected_string,
-+                    strlen(x509_format_tests[idx].expected_string))) {
-+            TEST_info("test_x509_time(%d) failed: expected_string %s, got %.*s\n",
-+                    idx, x509_format_tests[idx].expected_string, t->length,
-+                    t->data);
-             goto out;
-         }
-     }
diff -Nru openssl-1.1.1k/debian/patches/Fix-the-error-handling-in-i2v_AUTHORITY_KEYID.patch openssl-1.1.1m/debian/patches/Fix-the-error-handling-in-i2v_AUTHORITY_KEYID.patch
--- openssl-1.1.1k/debian/patches/Fix-the-error-handling-in-i2v_AUTHORITY_KEYID.patch	2021-08-24 10:28:12.000000000 +0200
+++ openssl-1.1.1m/debian/patches/Fix-the-error-handling-in-i2v_AUTHORITY_KEYID.patch	1970-01-01 01:00:00.000000000 +0100
@@ -1,67 +0,0 @@
-From: Matt Caswell <matt@openssl.org>
-Date: Fri, 20 Aug 2021 15:23:32 +0100
-Subject: Fix the error handling in i2v_AUTHORITY_KEYID
-
-Previously if an error path is entered a leak could result.
----
- crypto/x509v3/v3_akey.c | 38 +++++++++++++++++++++++++++++++++-----
- 1 file changed, 33 insertions(+), 5 deletions(-)
-
-diff --git a/crypto/x509v3/v3_akey.c b/crypto/x509v3/v3_akey.c
-index d9f770433cfb..f917142223b7 100644
---- a/crypto/x509v3/v3_akey.c
-+++ b/crypto/x509v3/v3_akey.c
-@@ -39,20 +39,48 @@ static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_KEYID(X509V3_EXT_METHOD *method,
-                                                  STACK_OF(CONF_VALUE)
-                                                  *extlist)
- {
--    char *tmp;
-+    char *tmp = NULL;
-+    STACK_OF(CONF_VALUE) *origextlist = extlist, *tmpextlist;
-+
-     if (akeyid->keyid) {
-         tmp = OPENSSL_buf2hexstr(akeyid->keyid->data, akeyid->keyid->length);
--        X509V3_add_value("keyid", tmp, &extlist);
-+        if (tmp == NULL) {
-+            X509V3err(X509V3_F_V2I_AUTHORITY_KEYID, ERR_R_MALLOC_FAILURE);
-+            return NULL;
-+        }
-+        if (!X509V3_add_value("keyid", tmp, &extlist)) {
-+            OPENSSL_free(tmp);
-+            X509V3err(X509V3_F_V2I_AUTHORITY_KEYID, ERR_R_X509_LIB);
-+            goto err;
-+        }
-         OPENSSL_free(tmp);
-     }
--    if (akeyid->issuer)
--        extlist = i2v_GENERAL_NAMES(NULL, akeyid->issuer, extlist);
-+    if (akeyid->issuer) {
-+        tmpextlist = i2v_GENERAL_NAMES(NULL, akeyid->issuer, extlist);
-+        if (tmpextlist == NULL) {
-+            X509V3err(X509V3_F_V2I_AUTHORITY_KEYID, ERR_R_X509_LIB);
-+            goto err;
-+        }
-+        extlist = tmpextlist;
-+    }
-     if (akeyid->serial) {
-         tmp = OPENSSL_buf2hexstr(akeyid->serial->data, akeyid->serial->length);
--        X509V3_add_value("serial", tmp, &extlist);
-+        if (tmp == NULL) {
-+            X509V3err(X509V3_F_V2I_AUTHORITY_KEYID, ERR_R_MALLOC_FAILURE);
-+            goto err;
-+        }
-+        if (!X509V3_add_value("serial", tmp, &extlist)) {
-+            OPENSSL_free(tmp);
-+            X509V3err(X509V3_F_V2I_AUTHORITY_KEYID, ERR_R_X509_LIB);
-+            goto err;
-+        }
-         OPENSSL_free(tmp);
-     }
-     return extlist;
-+ err:
-+    if (origextlist == NULL)
-+        sk_CONF_VALUE_pop_free(extlist, X509V3_conf_free);
-+    return NULL;
- }
- 
- /*-
diff -Nru openssl-1.1.1k/debian/patches/Fix-the-name-constraints-code-to-not-assume-NUL-terminate.patch openssl-1.1.1m/debian/patches/Fix-the-name-constraints-code-to-not-assume-NUL-terminate.patch
--- openssl-1.1.1k/debian/patches/Fix-the-name-constraints-code-to-not-assume-NUL-terminate.patch	2021-08-24 10:28:12.000000000 +0200
+++ openssl-1.1.1m/debian/patches/Fix-the-name-constraints-code-to-not-assume-NUL-terminate.patch	1970-01-01 01:00:00.000000000 +0100
@@ -1,191 +0,0 @@
-From: Matt Caswell <matt@openssl.org>
-Date: Wed, 18 Aug 2021 17:08:58 +0100
-Subject: Fix the name constraints code to not assume NUL terminated strings
-
-ASN.1 strings may not be NUL terminated. Don't assume they are.
----
- crypto/x509v3/v3_ncons.c | 89 +++++++++++++++++++++++++++++++++++-------------
- 1 file changed, 65 insertions(+), 24 deletions(-)
-
-diff --git a/crypto/x509v3/v3_ncons.c b/crypto/x509v3/v3_ncons.c
-index 2a7b4f0992a8..4cb05ac6ae73 100644
---- a/crypto/x509v3/v3_ncons.c
-+++ b/crypto/x509v3/v3_ncons.c
-@@ -63,6 +63,43 @@ ASN1_SEQUENCE(NAME_CONSTRAINTS) = {
- IMPLEMENT_ASN1_ALLOC_FUNCTIONS(GENERAL_SUBTREE)
- IMPLEMENT_ASN1_ALLOC_FUNCTIONS(NAME_CONSTRAINTS)
- 
-+
-+#define IA5_OFFSET_LEN(ia5base, offset) \
-+    ((ia5base)->length - ((unsigned char *)(offset) - (ia5base)->data))
-+
-+/* Like strchr but for ASN1_IA5STRING. Additionally you can specify the
-+ * starting point to search from
-+ */
-+static char *ia5strchr(ASN1_IA5STRING *str, const char *start, int c)
-+{
-+    int i;
-+    int offset = (int)(start - (char *)str->data);
-+
-+    /* Should not happen */
-+    if (offset > str->length || offset < 0)
-+        return NULL;
-+
-+    for (i = offset; i < str->length && str->data[i] != c; i++);
-+
-+    if (i == str->length)
-+        return NULL;
-+
-+    return (char *)&str->data[i];
-+}
-+
-+/* Like strrchr but for ASN1_IA5STRING */
-+static char *ia5strrchr(ASN1_IA5STRING *str, int c)
-+{
-+    int i;
-+
-+    for (i = str->length; i > 0 && str->data[i - 1] != c; i--);
-+
-+    if (i == 0)
-+        return NULL;
-+
-+    return (char *)&str->data[i - 1];
-+}
-+
- /*
-  * We cannot use strncasecmp here because that applies locale specific rules.
-  * For example in Turkish 'I' is not the uppercase character for 'i'. We need to
-@@ -89,20 +126,12 @@ static int ia5ncasecmp(const char *s1, const char *s2, size_t n)
- 
-             /* c1 > c2 */
-             return 1;
--        } else if (*s1 == 0) {
--            /* If we get here we know that *s2 == 0 too */
--            return 0;
-         }
-     }
- 
-     return 0;
- }
- 
--static int ia5casecmp(const char *s1, const char *s2)
--{
--    return ia5ncasecmp(s1, s2, SIZE_MAX);
--}
--
- static void *v2i_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method,
-                                   X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval)
- {
-@@ -337,7 +366,7 @@ static int cn2dnsid(ASN1_STRING *cn, unsigned char **dnsid, size_t *idlen)
-         --utf8_length;
- 
-     /* Reject *embedded* NULs */
--    if ((size_t)utf8_length != strlen((char *)utf8_value)) {
-+    if (memchr(utf8_value, 0, utf8_length) != NULL) {
-         OPENSSL_free(utf8_value);
-         return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
-     }
-@@ -536,9 +565,14 @@ static int nc_dns(ASN1_IA5STRING *dns, ASN1_IA5STRING *base)
- {
-     char *baseptr = (char *)base->data;
-     char *dnsptr = (char *)dns->data;
-+
-     /* Empty matches everything */
--    if (!*baseptr)
-+    if (base->length == 0)
-         return X509_V_OK;
-+
-+    if (dns->length < base->length)
-+        return X509_V_ERR_PERMITTED_VIOLATION;
-+
-     /*
-      * Otherwise can add zero or more components on the left so compare RHS
-      * and if dns is longer and expect '.' as preceding character.
-@@ -549,7 +583,7 @@ static int nc_dns(ASN1_IA5STRING *dns, ASN1_IA5STRING *base)
-             return X509_V_ERR_PERMITTED_VIOLATION;
-     }
- 
--    if (ia5casecmp(baseptr, dnsptr))
-+    if (ia5ncasecmp(baseptr, dnsptr, base->length))
-         return X509_V_ERR_PERMITTED_VIOLATION;
- 
-     return X509_V_OK;
-@@ -560,16 +594,17 @@ static int nc_email(ASN1_IA5STRING *eml, ASN1_IA5STRING *base)
- {
-     const char *baseptr = (char *)base->data;
-     const char *emlptr = (char *)eml->data;
-+    const char *baseat = ia5strrchr(base, '@');
-+    const char *emlat = ia5strrchr(eml, '@');
-+    size_t basehostlen, emlhostlen;
- 
--    const char *baseat = strchr(baseptr, '@');
--    const char *emlat = strchr(emlptr, '@');
-     if (!emlat)
-         return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
-     /* Special case: initial '.' is RHS match */
--    if (!baseat && (*baseptr == '.')) {
-+    if (!baseat && base->length > 0 && (*baseptr == '.')) {
-         if (eml->length > base->length) {
-             emlptr += eml->length - base->length;
--            if (ia5casecmp(baseptr, emlptr) == 0)
-+            if (ia5ncasecmp(baseptr, emlptr, base->length) == 0)
-                 return X509_V_OK;
-         }
-         return X509_V_ERR_PERMITTED_VIOLATION;
-@@ -589,8 +624,10 @@ static int nc_email(ASN1_IA5STRING *eml, ASN1_IA5STRING *base)
-         baseptr = baseat + 1;
-     }
-     emlptr = emlat + 1;
-+    basehostlen = IA5_OFFSET_LEN(base, baseptr);
-+    emlhostlen = IA5_OFFSET_LEN(eml, emlptr);
-     /* Just have hostname left to match: case insensitive */
--    if (ia5casecmp(baseptr, emlptr))
-+    if (basehostlen != emlhostlen || ia5ncasecmp(baseptr, emlptr, emlhostlen))
-         return X509_V_ERR_PERMITTED_VIOLATION;
- 
-     return X509_V_OK;
-@@ -601,10 +638,14 @@ static int nc_uri(ASN1_IA5STRING *uri, ASN1_IA5STRING *base)
- {
-     const char *baseptr = (char *)base->data;
-     const char *hostptr = (char *)uri->data;
--    const char *p = strchr(hostptr, ':');
-+    const char *p = ia5strchr(uri, (char *)uri->data, ':');
-     int hostlen;
-+
-     /* Check for foo:// and skip past it */
--    if (!p || (p[1] != '/') || (p[2] != '/'))
-+    if (p == NULL
-+            || IA5_OFFSET_LEN(uri, p) < 3
-+            || p[1] != '/'
-+            || p[2] != '/')
-         return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
-     hostptr = p + 3;
- 
-@@ -612,13 +653,13 @@ static int nc_uri(ASN1_IA5STRING *uri, ASN1_IA5STRING *base)
- 
-     /* Look for a port indicator as end of hostname first */
- 
--    p = strchr(hostptr, ':');
-+    p = ia5strchr(uri, hostptr, ':');
-     /* Otherwise look for trailing slash */
--    if (!p)
--        p = strchr(hostptr, '/');
-+    if (p == NULL)
-+        p = ia5strchr(uri, hostptr, '/');
- 
--    if (!p)
--        hostlen = strlen(hostptr);
-+    if (p == NULL)
-+        hostlen = IA5_OFFSET_LEN(uri, hostptr);
-     else
-         hostlen = p - hostptr;
- 
-@@ -626,7 +667,7 @@ static int nc_uri(ASN1_IA5STRING *uri, ASN1_IA5STRING *base)
-         return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
- 
-     /* Special case: initial '.' is RHS match */
--    if (*baseptr == '.') {
-+    if (base->length > 0 && *baseptr == '.') {
-         if (hostlen > base->length) {
-             p = hostptr + hostlen - base->length;
-             if (ia5ncasecmp(p, baseptr, base->length) == 0)
diff -Nru openssl-1.1.1k/debian/patches/fixup-Allow-fuzz-builds-to-detect-string-overruns.patch openssl-1.1.1m/debian/patches/fixup-Allow-fuzz-builds-to-detect-string-overruns.patch
--- openssl-1.1.1k/debian/patches/fixup-Allow-fuzz-builds-to-detect-string-overruns.patch	2021-08-24 10:28:12.000000000 +0200
+++ openssl-1.1.1m/debian/patches/fixup-Allow-fuzz-builds-to-detect-string-overruns.patch	1970-01-01 01:00:00.000000000 +0100
@@ -1,44 +0,0 @@
-From: Matt Caswell <matt@openssl.org>
-Date: Mon, 23 Aug 2021 13:56:22 +0100
-Subject: fixup! Allow fuzz builds to detect string overruns
-
----
- crypto/asn1/asn1_lib.c | 15 ++++++++-------
- 1 file changed, 8 insertions(+), 7 deletions(-)
-
-diff --git a/crypto/asn1/asn1_lib.c b/crypto/asn1/asn1_lib.c
-index 2b61a7e57679..8e62f3307443 100644
---- a/crypto/asn1/asn1_lib.c
-+++ b/crypto/asn1/asn1_lib.c
-@@ -292,7 +292,12 @@ int ASN1_STRING_set(ASN1_STRING *str, const void *_data, int len_in)
-     }
-     if ((size_t)str->length <= len || str->data == NULL) {
-         c = str->data;
-+#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
-+        /* No NUL terminator in fuzzing builds */
-+        str->data = OPENSSL_realloc(c, len);
-+#else
-         str->data = OPENSSL_realloc(c, len + 1);
-+#endif
-         if (str->data == NULL) {
-             ASN1err(ASN1_F_ASN1_STRING_SET, ERR_R_MALLOC_FAILURE);
-             str->data = c;
-@@ -302,15 +307,11 @@ int ASN1_STRING_set(ASN1_STRING *str, const void *_data, int len_in)
-     str->length = len;
-     if (data != NULL) {
-         memcpy(str->data, data, len);
--        /* an allowance for strings :-) */
--#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
-+#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
-         /*
--         * Arbitrary byte on the end, which should never be read if the string
--         * length is being properly respected.
-+         * Add a NUL terminator. This should not be necessary - but we add it as
-+         * a safety precaution
-          */
--        str->data[len] = 'x';
--#else
--        /* This should not be necessary - but we add it as a safety precaution */
-         str->data[len] = '\0';
- #endif
-     }
diff -Nru openssl-1.1.1k/debian/patches/fixup-Fix-i2v_GENERAL_NAME-to-not-assume-NUL-terminated-s.patch openssl-1.1.1m/debian/patches/fixup-Fix-i2v_GENERAL_NAME-to-not-assume-NUL-terminated-s.patch
--- openssl-1.1.1k/debian/patches/fixup-Fix-i2v_GENERAL_NAME-to-not-assume-NUL-terminated-s.patch	2021-08-24 10:28:12.000000000 +0200
+++ openssl-1.1.1m/debian/patches/fixup-Fix-i2v_GENERAL_NAME-to-not-assume-NUL-terminated-s.patch	1970-01-01 01:00:00.000000000 +0100
@@ -1,28 +0,0 @@
-From: Matt Caswell <matt@openssl.org>
-Date: Mon, 23 Aug 2021 20:41:38 +0100
-Subject: fixup! Fix i2v_GENERAL_NAME to not assume NUL terminated strings
-
----
- crypto/x509v3/v3_utl.c | 9 ++++++---
- 1 file changed, 6 insertions(+), 3 deletions(-)
-
-diff --git a/crypto/x509v3/v3_utl.c b/crypto/x509v3/v3_utl.c
-index 706dd22ffaba..513dc68b0809 100644
---- a/crypto/x509v3/v3_utl.c
-+++ b/crypto/x509v3/v3_utl.c
-@@ -44,9 +44,12 @@ static int x509v3_add_len_value(const char *name, const char *value,
- 
-     if (name != NULL && (tname = OPENSSL_strdup(name)) == NULL)
-         goto err;
--    if (value != NULL) {
--        /* We don't allow embeded NUL characters */
--        if (memchr(value, 0, vallen) != NULL)
-+    if (value != NULL && vallen > 0) {
-+        /*
-+         * We tolerate a single trailing NUL character, but otherwise no
-+         * embedded NULs
-+         */
-+        if (memchr(value, 0, vallen - 1) != NULL)
-             goto err;
-         tvalue = OPENSSL_strndup(value, vallen);
-         if (tvalue == NULL)
diff -Nru openssl-1.1.1k/debian/patches/fixup-Fix-the-name-constraints-code-to-not-assume-NUL-ter.patch openssl-1.1.1m/debian/patches/fixup-Fix-the-name-constraints-code-to-not-assume-NUL-ter.patch
--- openssl-1.1.1k/debian/patches/fixup-Fix-the-name-constraints-code-to-not-assume-NUL-ter.patch	2021-08-24 10:28:12.000000000 +0200
+++ openssl-1.1.1m/debian/patches/fixup-Fix-the-name-constraints-code-to-not-assume-NUL-ter.patch	1970-01-01 01:00:00.000000000 +0100
@@ -1,89 +0,0 @@
-From: Matt Caswell <matt@openssl.org>
-Date: Mon, 23 Aug 2021 14:01:08 +0100
-Subject: fixup! Fix the name constraints code to not assume NUL terminated
- strings
-
----
- crypto/x509v3/v3_ncons.c | 36 +++++++++++-------------------------
- 1 file changed, 11 insertions(+), 25 deletions(-)
-
-diff --git a/crypto/x509v3/v3_ncons.c b/crypto/x509v3/v3_ncons.c
-index 4cb05ac6ae73..cb701c4d844b 100644
---- a/crypto/x509v3/v3_ncons.c
-+++ b/crypto/x509v3/v3_ncons.c
-@@ -67,28 +67,13 @@ IMPLEMENT_ASN1_ALLOC_FUNCTIONS(NAME_CONSTRAINTS)
- #define IA5_OFFSET_LEN(ia5base, offset) \
-     ((ia5base)->length - ((unsigned char *)(offset) - (ia5base)->data))
- 
--/* Like strchr but for ASN1_IA5STRING. Additionally you can specify the
-+/* Like memchr but for ASN1_IA5STRING. Additionally you can specify the
-  * starting point to search from
-  */
--static char *ia5strchr(ASN1_IA5STRING *str, const char *start, int c)
--{
--    int i;
--    int offset = (int)(start - (char *)str->data);
-+# define ia5memchr(str, start, c) memchr(start, c, IA5_OFFSET_LEN(str, start))
- 
--    /* Should not happen */
--    if (offset > str->length || offset < 0)
--        return NULL;
--
--    for (i = offset; i < str->length && str->data[i] != c; i++);
--
--    if (i == str->length)
--        return NULL;
--
--    return (char *)&str->data[i];
--}
--
--/* Like strrchr but for ASN1_IA5STRING */
--static char *ia5strrchr(ASN1_IA5STRING *str, int c)
-+/* Like memrrchr but for ASN1_IA5STRING */
-+static char *ia5memrchr(ASN1_IA5STRING *str, int c)
- {
-     int i;
- 
-@@ -101,7 +86,8 @@ static char *ia5strrchr(ASN1_IA5STRING *str, int c)
- }
- 
- /*
-- * We cannot use strncasecmp here because that applies locale specific rules.
-+ * We cannot use strncasecmp here because that applies locale specific rules. It
-+ * also doesn't work with ASN1_STRINGs that may have embedded NUL characters.
-  * For example in Turkish 'I' is not the uppercase character for 'i'. We need to
-  * do a simple ASCII case comparison ignoring the locale (that is why we use
-  * numeric constants below).
-@@ -594,8 +580,8 @@ static int nc_email(ASN1_IA5STRING *eml, ASN1_IA5STRING *base)
- {
-     const char *baseptr = (char *)base->data;
-     const char *emlptr = (char *)eml->data;
--    const char *baseat = ia5strrchr(base, '@');
--    const char *emlat = ia5strrchr(eml, '@');
-+    const char *baseat = ia5memrchr(base, '@');
-+    const char *emlat = ia5memrchr(eml, '@');
-     size_t basehostlen, emlhostlen;
- 
-     if (!emlat)
-@@ -638,7 +624,7 @@ static int nc_uri(ASN1_IA5STRING *uri, ASN1_IA5STRING *base)
- {
-     const char *baseptr = (char *)base->data;
-     const char *hostptr = (char *)uri->data;
--    const char *p = ia5strchr(uri, (char *)uri->data, ':');
-+    const char *p = ia5memchr(uri, (char *)uri->data, ':');
-     int hostlen;
- 
-     /* Check for foo:// and skip past it */
-@@ -653,10 +639,10 @@ static int nc_uri(ASN1_IA5STRING *uri, ASN1_IA5STRING *base)
- 
-     /* Look for a port indicator as end of hostname first */
- 
--    p = ia5strchr(uri, hostptr, ':');
-+    p = ia5memchr(uri, hostptr, ':');
-     /* Otherwise look for trailing slash */
-     if (p == NULL)
--        p = ia5strchr(uri, hostptr, '/');
-+        p = ia5memchr(uri, hostptr, '/');
- 
-     if (p == NULL)
-         hostlen = IA5_OFFSET_LEN(uri, hostptr);
diff -Nru openssl-1.1.1k/debian/patches/man-section.patch openssl-1.1.1m/debian/patches/man-section.patch
--- openssl-1.1.1k/debian/patches/man-section.patch	2021-08-24 10:28:12.000000000 +0200
+++ openssl-1.1.1m/debian/patches/man-section.patch	2022-01-08 22:17:21.000000000 +0100
@@ -8,7 +8,7 @@
  2 files changed, 6 insertions(+), 3 deletions(-)
 
 diff --git a/Configurations/unix-Makefile.tmpl b/Configurations/unix-Makefile.tmpl
-index 41648c952667..e013d464bd73 100644
+index 66617d6f4f90..68e391c08859 100644
 --- a/Configurations/unix-Makefile.tmpl
 +++ b/Configurations/unix-Makefile.tmpl
 @@ -281,7 +281,8 @@ HTMLDIR=$(DOCDIR)/html
@@ -21,7 +21,7 @@
  HTMLSUFFIX=html
  
  # For "optional" echo messages, to get "real" silence
-@@ -824,7 +825,8 @@ uninstall_runtime: uninstall_programs uninstall_runtime_libs
+@@ -823,7 +824,8 @@ uninstall_runtime: uninstall_programs uninstall_runtime_libs
  	@[ -n "$(INSTALLTOP)" ] || (echo INSTALLTOP should not be empty; exit 1)
  	@$(ECHO) "*** Installing manpages"
  	$(PERL) $(SRCDIR)/util/process_docs.pl \
diff -Nru openssl-1.1.1k/debian/patches/series openssl-1.1.1m/debian/patches/series
--- openssl-1.1.1k/debian/patches/series	2021-08-24 10:28:12.000000000 +0200
+++ openssl-1.1.1m/debian/patches/series	2022-01-08 22:17:21.000000000 +0100
@@ -4,20 +4,3 @@
 pic.patch
 c_rehash-compat.patch
 Set-systemwide-default-settings-for-libssl-users.patch
-Correctly-calculate-the-length-of-SM2-plaintext-given-the.patch
-Extend-tests-for-SM2-decryption.patch
-Check-the-plaintext-buffer-is-large-enough-when-decryptin.patch
-Fix-a-read-buffer-overrun-in-X509_aux_print.patch
-Fix-i2v_GENERAL_NAME-to-not-assume-NUL-terminated-strings.patch
-Fix-POLICYINFO-printing-to-not-assume-NUL-terminated-stri.patch
-Fix-printing-of-PROXY_CERT_INFO_EXTENSION-to-not-assume-N.patch
-Fix-the-name-constraints-code-to-not-assume-NUL-terminate.patch
-Fix-test-code-to-not-assume-NUL-terminated-strings.patch
-Fix-append_ia5-function-to-not-assume-NUL-terminated-stri.patch
-Fix-NETSCAPE_SPKI_print-function-to-not-assume-NUL-termin.patch
-Fix-EC_GROUP_new_from_ecparameters-to-check-the-base-leng.patch
-Allow-fuzz-builds-to-detect-string-overruns.patch
-Fix-the-error-handling-in-i2v_AUTHORITY_KEYID.patch
-fixup-Allow-fuzz-builds-to-detect-string-overruns.patch
-fixup-Fix-the-name-constraints-code-to-not-assume-NUL-ter.patch
-fixup-Fix-i2v_GENERAL_NAME-to-not-assume-NUL-terminated-s.patch
diff -Nru openssl-1.1.1k/demos/bio/client-arg.c openssl-1.1.1m/demos/bio/client-arg.c
--- openssl-1.1.1k/demos/bio/client-arg.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/demos/bio/client-arg.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2013-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2013-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -93,12 +93,6 @@
         ERR_print_errors_fp(stderr);
         goto end;
     }
-
-    if (BIO_do_handshake(sbio) <= 0) {
-        fprintf(stderr, "Error establishing SSL connection\n");
-        ERR_print_errors_fp(stderr);
-        goto end;
-    }
 
     /* Could examine ssl here to get connection info */
 
diff -Nru openssl-1.1.1k/demos/bio/client-conf.c openssl-1.1.1m/demos/bio/client-conf.c
--- openssl-1.1.1k/demos/bio/client-conf.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/demos/bio/client-conf.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2013-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2013-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -101,12 +101,6 @@
         ERR_print_errors_fp(stderr);
         goto end;
     }
-
-    if (BIO_do_handshake(sbio) <= 0) {
-        fprintf(stderr, "Error establishing SSL connection\n");
-        ERR_print_errors_fp(stderr);
-        goto end;
-    }
 
     /* Could examine ssl here to get connection info */
 
diff -Nru openssl-1.1.1k/doc/man1/enc.pod openssl-1.1.1m/doc/man1/enc.pod
--- openssl-1.1.1k/doc/man1/enc.pod	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/doc/man1/enc.pod	2021-12-14 16:45:01.000000000 +0100
@@ -180,8 +180,8 @@
 
 =item B<-z>
 
-Compress or decompress clear text using zlib before encryption or after
-decryption. This option exists only if OpenSSL with compiled with zlib
+Compress or decompress encrypted data using zlib after encryption or before
+decryption. This option exists only if OpenSSL was compiled with the zlib
 or zlib-dynamic option.
 
 =item B<-none>
diff -Nru openssl-1.1.1k/doc/man1/passwd.pod openssl-1.1.1m/doc/man1/passwd.pod
--- openssl-1.1.1k/doc/man1/passwd.pod	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/doc/man1/passwd.pod	2021-12-14 16:45:01.000000000 +0100
@@ -31,8 +31,6 @@
 run-time or the hash of each password in a list.  The password list is
 taken from the named file for option B<-in file>, from stdin for
 option B<-stdin>, or from the command line, or from the terminal otherwise.
-The Unix standard algorithm B<crypt> and the MD5-based BSD password
-algorithm B<1>, its Apache variant B<apr1>, and its AIX variant are available.
 
 =head1 OPTIONS
 
@@ -122,7 +120,7 @@
 
 =head1 COPYRIGHT
 
-Copyright 2000-2018 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
 
 Licensed under the OpenSSL license (the "License").  You may not use
 this file except in compliance with the License.  You can obtain a copy
diff -Nru openssl-1.1.1k/doc/man1/pkeyutl.pod openssl-1.1.1m/doc/man1/pkeyutl.pod
--- openssl-1.1.1k/doc/man1/pkeyutl.pod	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/doc/man1/pkeyutl.pod	2021-12-14 16:45:01.000000000 +0100
@@ -246,6 +246,11 @@
 For PSS and OAEP padding sets the MGF1 digest. If the MGF1 digest is not
 explicitly set in PSS mode then the signing digest is used.
 
+=item B<rsa_oaep_md:>I<digest>
+
+Sets the digest used for the OAEP hash function. If not explicitly set then
+SHA1 is used.
+
 =back
 
 =head1 RSA-PSS ALGORITHM
@@ -319,6 +324,11 @@
  openssl pkeyutl -kdf TLS1-PRF -kdflen 48 -pkeyopt md:SHA256 \
     -pkeyopt hexsecret:ff -pkeyopt hexseed:ff -hexdump
 
+Decrypt some data using a private key with OAEP padding using SHA256:
+
+ openssl pkeyutl -decrypt -in file -inkey key.pem -out secret \
+    -pkeyopt rsa_padding_mode:oaep -pkeyopt rsa_oaep_md:sha256
+
 =head1 SEE ALSO
 
 L<genpkey(1)>, L<pkey(1)>, L<rsautl(1)>
diff -Nru openssl-1.1.1k/doc/man1/s_client.pod openssl-1.1.1m/doc/man1/s_client.pod
--- openssl-1.1.1k/doc/man1/s_client.pod	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/doc/man1/s_client.pod	2021-12-14 16:45:01.000000000 +0100
@@ -797,7 +797,7 @@
 
 The B<s_client> utility is a test tool and is designed to continue the
 handshake after any certificate verification errors. As a result it will
-accept any certificate chain (trusted or not) sent by the peer. None test
+accept any certificate chain (trusted or not) sent by the peer. Non-test
 applications should B<not> do this as it makes them vulnerable to a MITM
 attack. This behaviour can be changed by with the B<-verify_return_error>
 option: any verify errors are then returned aborting the handshake.
diff -Nru openssl-1.1.1k/doc/man1/s_server.pod openssl-1.1.1m/doc/man1/s_server.pod
--- openssl-1.1.1k/doc/man1/s_server.pod	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/doc/man1/s_server.pod	2021-12-14 16:45:01.000000000 +0100
@@ -701,7 +701,7 @@
 
 =item B<-alpn val>, B<-nextprotoneg val>
 
-These flags enable the Enable the Application-Layer Protocol Negotiation
+These flags enable the Application-Layer Protocol Negotiation
 or Next Protocol Negotiation (NPN) extension, respectively. ALPN is the
 IETF standard and replaces NPN.
 The B<val> list is a comma-separated list of supported protocol
diff -Nru openssl-1.1.1k/doc/man3/BIO_f_ssl.pod openssl-1.1.1m/doc/man3/BIO_f_ssl.pod
--- openssl-1.1.1k/doc/man3/BIO_f_ssl.pod	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/doc/man3/BIO_f_ssl.pod	2021-12-14 16:45:01.000000000 +0100
@@ -54,26 +54,26 @@
 If the close flag is set when an SSL BIO is freed then the internal
 SSL structure is also freed using SSL_free().
 
-BIO_set_ssl() sets the internal SSL pointer of BIO B<b> to B<ssl> using
+BIO_set_ssl() sets the internal SSL pointer of SSL BIO B<b> to B<ssl> using
 the close flag B<c>.
 
-BIO_get_ssl() retrieves the SSL pointer of BIO B<b>, it can then be
+BIO_get_ssl() retrieves the SSL pointer of SSL BIO B<b>, it can then be
 manipulated using the standard SSL library functions.
 
 BIO_set_ssl_mode() sets the SSL BIO mode to B<client>. If B<client>
 is 1 client mode is set. If B<client> is 0 server mode is set.
 
-BIO_set_ssl_renegotiate_bytes() sets the renegotiate byte count
+BIO_set_ssl_renegotiate_bytes() sets the renegotiate byte count of SSL BIO B<b>
 to B<num>. When set after every B<num> bytes of I/O (read and write)
 the SSL session is automatically renegotiated. B<num> must be at
 least 512 bytes.
 
-BIO_set_ssl_renegotiate_timeout() sets the renegotiate timeout to
-B<seconds>. When the renegotiate timeout elapses the session is
-automatically renegotiated.
+BIO_set_ssl_renegotiate_timeout() sets the renegotiate timeout of SSL BIO B<b>
+to B<seconds>.
+When the renegotiate timeout elapses the session is automatically renegotiated.
 
 BIO_get_num_renegotiates() returns the total number of session
-renegotiations due to I/O or timeout.
+renegotiations due to I/O or timeout of SSL BIO B<b>.
 
 BIO_new_ssl() allocates an SSL BIO using SSL_CTX B<ctx> and using
 client mode if B<client> is non zero.
@@ -82,8 +82,7 @@
 SSL BIO (using B<ctx>) followed by a connect BIO.
 
 BIO_new_buffer_ssl_connect() creates a new BIO chain consisting
-of a buffering BIO, an SSL BIO (using B<ctx>) and a connect
-BIO.
+of a buffering BIO, an SSL BIO (using B<ctx>), and a connect BIO.
 
 BIO_ssl_copy_session_id() copies an SSL session id between
 BIO chains B<from> and B<to>. It does this by locating the
@@ -185,11 +184,6 @@
      ERR_print_errors_fp(stderr);
      exit(1);
  }
- if (BIO_do_handshake(sbio) <= 0) {
-     fprintf(stderr, "Error establishing SSL connection\n");
-     ERR_print_errors_fp(stderr);
-     exit(1);
- }
 
  /* XXX Could examine ssl here to get connection info */
 
@@ -298,7 +292,7 @@
 
 =head1 COPYRIGHT
 
-Copyright 2000-2019 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
 
 Licensed under the OpenSSL license (the "License").  You may not use
 this file except in compliance with the License.  You can obtain a copy
diff -Nru openssl-1.1.1k/doc/man3/BIO_push.pod openssl-1.1.1m/doc/man3/BIO_push.pod
--- openssl-1.1.1k/doc/man3/BIO_push.pod	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/doc/man3/BIO_push.pod	2021-12-14 16:45:01.000000000 +0100
@@ -8,22 +8,27 @@
 
  #include <openssl/bio.h>
 
- BIO *BIO_push(BIO *b, BIO *append);
+ BIO *BIO_push(BIO *b, BIO *next);
  BIO *BIO_pop(BIO *b);
  void BIO_set_next(BIO *b, BIO *next);
 
 =head1 DESCRIPTION
 
-The BIO_push() function appends the BIO B<append> to B<b>, it returns
-B<b>.
-
-BIO_pop() removes the BIO B<b> from a chain and returns the next BIO
-in the chain, or NULL if there is no next BIO. The removed BIO then
-becomes a single BIO with no association with the original chain,
-it can thus be freed or attached to a different chain.
+BIO_push() pushes I<b> on I<next>.
+If I<b> is NULL the function does nothing and returns I<next>.
+Otherwise it prepends I<b>, which may be a single BIO or a chain of BIOs,
+to I<next> (unless I<next> is NULL).
+It then makes a control call on I<b> and returns I<b>.
+
+BIO_pop() removes the BIO I<b> from any chain is is part of.
+If I<b> is NULL the function does nothing and returns NULL.
+Otherwise it makes a control call on I<b> and
+returns the next BIO in the chain, or NULL if there is no next BIO.
+The removed BIO becomes a single BIO with no association with
+the original chain, it can thus be freed or be made part of a different chain.
 
 BIO_set_next() replaces the existing next BIO in a chain with the BIO pointed to
-by B<next>. The new chain may include some of the same BIOs from the old chain
+by I<next>. The new chain may include some of the same BIOs from the old chain
 or it may be completely different.
 
 =head1 NOTES
@@ -33,41 +38,45 @@
 the deleted BIO does not need to be at the end of a chain.
 
 The process of calling BIO_push() and BIO_pop() on a BIO may have additional
-consequences (a control call is made to the affected BIOs) any effects will
-be noted in the descriptions of individual BIOs.
+consequences (a control call is made to the affected BIOs).
+Any effects will be noted in the descriptions of individual BIOs.
 
 =head1 RETURN VALUES
 
-BIO_push() returns the end of the chain, B<b>.
+BIO_push() returns the head of the chain,
+which usually is I<b>, or I<next> if I<b> is NULL.
 
-BIO_pop() returns the next BIO in the chain, or NULL if there is no next
-BIO.
+BIO_pop() returns the next BIO in the chain,
+or NULL if there is no next BIO.
 
 =head1 EXAMPLES
 
-For these examples suppose B<md1> and B<md2> are digest BIOs, B<b64> is
-a base64 BIO and B<f> is a file BIO.
+For these examples suppose I<md1> and I<md2> are digest BIOs,
+I<b64> is a base64 BIO and I<f> is a file BIO.
 
 If the call:
 
  BIO_push(b64, f);
 
-is made then the new chain will be B<b64-f>. After making the calls
+is made then the new chain will be I<b64-f>. After making the calls
 
  BIO_push(md2, b64);
  BIO_push(md1, md2);
 
-the new chain is B<md1-md2-b64-f>. Data written to B<md1> will be digested
-by B<md1> and B<md2>, B<base64> encoded and written to B<f>.
+the new chain is I<md1-md2-b64-f>. Data written to I<md1> will be digested
+by I<md1> and I<md2>, base64 encoded, and finally written to I<f>.
 
 It should be noted that reading causes data to pass in the reverse
-direction, that is data is read from B<f>, base64 B<decoded> and digested
-by B<md1> and B<md2>. If the call:
+direction, that is data is read from I<f>, base64 decoded,
+and digested by I<md2> and then I<md1>.
+
+The call:
 
  BIO_pop(md2);
 
-The call will return B<b64> and the new chain will be B<md1-b64-f> data can
-be written to B<md1> as before.
+will return I<b64> and the new chain will be I<md1-b64-f>.
+Data can be written to and read from I<md1> as before,
+except that I<md2> will no more be applied.
 
 =head1 SEE ALSO
 
@@ -79,7 +88,7 @@
 
 =head1 COPYRIGHT
 
-Copyright 2000-2019 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
 
 Licensed under the OpenSSL license (the "License").  You may not use
 this file except in compliance with the License.  You can obtain a copy
diff -Nru openssl-1.1.1k/doc/man3/BN_cmp.pod openssl-1.1.1m/doc/man3/BN_cmp.pod
--- openssl-1.1.1k/doc/man3/BN_cmp.pod	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/doc/man3/BN_cmp.pod	2021-12-14 16:45:01.000000000 +0100
@@ -2,42 +2,47 @@
 
 =head1 NAME
 
-BN_cmp, BN_ucmp, BN_is_zero, BN_is_one, BN_is_word, BN_is_odd - BIGNUM comparison and test functions
+BN_cmp, BN_ucmp, BN_is_zero, BN_is_one, BN_is_word, BN_abs_is_word, BN_is_odd - BIGNUM comparison and test functions
 
 =head1 SYNOPSIS
 
  #include <openssl/bn.h>
 
- int BN_cmp(BIGNUM *a, BIGNUM *b);
- int BN_ucmp(BIGNUM *a, BIGNUM *b);
+ int BN_cmp(const BIGNUM *a, const BIGNUM *b);
+ int BN_ucmp(const BIGNUM *a, const BIGNUM *b);
 
- int BN_is_zero(BIGNUM *a);
- int BN_is_one(BIGNUM *a);
- int BN_is_word(BIGNUM *a, BN_ULONG w);
- int BN_is_odd(BIGNUM *a);
+ int BN_is_zero(const BIGNUM *a);
+ int BN_is_one(const BIGNUM *a);
+ int BN_is_word(const BIGNUM *a, const BN_ULONG w);
+ int BN_abs_is_word(const BIGNUM *a, const BN_ULONG w);
+ int BN_is_odd(const BIGNUM *a);
 
 =head1 DESCRIPTION
 
-BN_cmp() compares the numbers B<a> and B<b>. BN_ucmp() compares their
+BN_cmp() compares the numbers I<a> and I<b>. BN_ucmp() compares their
 absolute values.
 
-BN_is_zero(), BN_is_one() and BN_is_word() test if B<a> equals 0, 1,
-or B<w> respectively. BN_is_odd() tests if a is odd.
-
-BN_is_zero(), BN_is_one(), BN_is_word() and BN_is_odd() are macros.
+BN_is_zero(), BN_is_one(), BN_is_word() and BN_abs_is_word() test if
+I<a> equals 0, 1, I<w>, or E<verbar>I<w>E<verbar> respectively.
+BN_is_odd() tests if I<a> is odd.
 
 =head1 RETURN VALUES
 
-BN_cmp() returns -1 if B<a> E<lt> B<b>, 0 if B<a> == B<b> and 1 if
-B<a> E<gt> B<b>. BN_ucmp() is the same using the absolute values
-of B<a> and B<b>.
+BN_cmp() returns -1 if I<a> E<lt> I<b>, 0 if I<a> == I<b> and 1 if
+I<a> E<gt> I<b>. BN_ucmp() is the same using the absolute values
+of I<a> and I<b>.
+
+BN_is_zero(), BN_is_one() BN_is_word(), BN_abs_is_word() and
+BN_is_odd() return 1 if the condition is true, 0 otherwise.
+
+=head1 HISTORY
 
-BN_is_zero(), BN_is_one() BN_is_word() and BN_is_odd() return 1 if
-the condition is true, 0 otherwise.
+Prior to OpenSSL 1.1.0, BN_is_zero(), BN_is_one(), BN_is_word(),
+BN_abs_is_word() and BN_is_odd() were macros.
 
 =head1 COPYRIGHT
 
-Copyright 2000-2017 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
 
 Licensed under the OpenSSL license (the "License").  You may not use
 this file except in compliance with the License.  You can obtain a copy
diff -Nru openssl-1.1.1k/doc/man3/BN_rand.pod openssl-1.1.1m/doc/man3/BN_rand.pod
--- openssl-1.1.1k/doc/man3/BN_rand.pod	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/doc/man3/BN_rand.pod	2021-12-14 16:45:01.000000000 +0100
@@ -38,7 +38,7 @@
 numbers will always have 2*B<bits> length.
 If B<bottom> is B<BN_RAND_BOTTOM_ODD>, the number will be odd; if it
 is B<BN_RAND_BOTTOM_ANY> it can be odd or even.
-If B<bits> is 1 then B<top> cannot also be B<BN_RAND_FLG_TOPTWO>.
+If B<bits> is 1 then B<top> cannot also be B<BN_RAND_TOP_TWO>.
 
 BN_rand_range() generates a cryptographically strong pseudo-random
 number B<rnd> in the range 0 E<lt>= B<rnd> E<lt> B<range>.
@@ -89,7 +89,7 @@
 
 =head1 COPYRIGHT
 
-Copyright 2000-2019 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
 
 Licensed under the OpenSSL license (the "License").  You may not use
 this file except in compliance with the License.  You can obtain a copy
diff -Nru openssl-1.1.1k/doc/man3/d2i_PrivateKey.pod openssl-1.1.1m/doc/man3/d2i_PrivateKey.pod
--- openssl-1.1.1k/doc/man3/d2i_PrivateKey.pod	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/doc/man3/d2i_PrivateKey.pod	2021-12-14 16:45:01.000000000 +0100
@@ -42,6 +42,10 @@
 
 =head1 NOTES
 
+All the functions that operate on data in memory update the data pointer I<*pp>
+after a successful operation, just like the other d2i and i2d functions;
+see L<d2i_X509(3)>.
+
 All these functions use DER format and unencrypted keys. Applications wishing
 to encrypt or decrypt private keys should use other functions such as
 d2i_PKCS8PrivateKey() instead.
@@ -71,7 +75,7 @@
 
 =head1 COPYRIGHT
 
-Copyright 2017-2019 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved.
 
 Licensed under the OpenSSL license (the "License").  You may not use
 this file except in compliance with the License.  You can obtain a copy
diff -Nru openssl-1.1.1k/doc/man3/d2i_X509.pod openssl-1.1.1m/doc/man3/d2i_X509.pod
--- openssl-1.1.1k/doc/man3/d2i_X509.pod	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/doc/man3/d2i_X509.pod	2021-12-14 16:45:01.000000000 +0100
@@ -158,6 +158,8 @@
 d2i_TS_TST_INFO_fp,
 d2i_USERNOTICE,
 d2i_X509,
+d2i_X509_bio,
+d2i_X509_fp,
 d2i_X509_ALGOR,
 d2i_X509_ALGORS,
 d2i_X509_ATTRIBUTE,
@@ -338,6 +340,8 @@
 i2d_TS_TST_INFO_fp,
 i2d_USERNOTICE,
 i2d_X509,
+i2d_X509_bio,
+i2d_X509_fp,
 i2d_X509_ALGOR,
 i2d_X509_ALGORS,
 i2d_X509_ATTRIBUTE,
@@ -612,7 +616,7 @@
 
 =head1 COPYRIGHT
 
-Copyright 1998-2020 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 1998-2021 The OpenSSL Project Authors. All Rights Reserved.
 
 Licensed under the OpenSSL license (the "License").  You may not use
 this file except in compliance with the License.  You can obtain a copy
diff -Nru openssl-1.1.1k/doc/man3/ENGINE_add.pod openssl-1.1.1m/doc/man3/ENGINE_add.pod
--- openssl-1.1.1k/doc/man3/ENGINE_add.pod	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/doc/man3/ENGINE_add.pod	2021-12-14 16:45:01.000000000 +0100
@@ -597,8 +597,7 @@
 
 All ENGINE_register_TYPE() functions return 1 on success or 0 on error.
 
-ENGINE_register_complete() and ENGINE_register_all_complete() return 1 on success
-or 0 on error.
+ENGINE_register_complete() and ENGINE_register_all_complete() always return 1.
 
 ENGINE_ctrl() returns a positive value on success or others on error.
 
@@ -609,7 +608,7 @@
 ENGINE_new() returns a valid B<ENGINE> structure on success or NULL if an error
 occurred.
 
-ENGINE_free() returns 1 on success or 0 on error.
+ENGINE_free() always returns 1.
 
 ENGINE_up_ref() returns 1 on success or 0 on error.
 
@@ -657,7 +656,7 @@
 
 =head1 COPYRIGHT
 
-Copyright 2002-2020 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2002-2021 The OpenSSL Project Authors. All Rights Reserved.
 
 Licensed under the OpenSSL license (the "License").  You may not use
 this file except in compliance with the License.  You can obtain a copy
diff -Nru openssl-1.1.1k/doc/man3/ERR_load_strings.pod openssl-1.1.1m/doc/man3/ERR_load_strings.pod
--- openssl-1.1.1k/doc/man3/ERR_load_strings.pod	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/doc/man3/ERR_load_strings.pod	2021-12-14 16:45:01.000000000 +0100
@@ -9,7 +9,7 @@
 
  #include <openssl/err.h>
 
- void ERR_load_strings(int lib, ERR_STRING_DATA str[]);
+ int ERR_load_strings(int lib, ERR_STRING_DATA *str);
 
  int ERR_get_next_error_library(void);
 
@@ -38,7 +38,7 @@
 
 =head1 RETURN VALUES
 
-ERR_load_strings() returns no value. ERR_PACK() return the error code.
+ERR_load_strings() returns 1 for success and 0 for failure. ERR_PACK() returns the error code.
 ERR_get_next_error_library() returns zero on failure, otherwise a new
 library number.
 
@@ -48,7 +48,7 @@
 
 =head1 COPYRIGHT
 
-Copyright 2000-2018 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
 
 Licensed under the OpenSSL license (the "License").  You may not use
 this file except in compliance with the License.  You can obtain a copy
diff -Nru openssl-1.1.1k/doc/man3/EVP_EncryptInit.pod openssl-1.1.1m/doc/man3/EVP_EncryptInit.pod
--- openssl-1.1.1k/doc/man3/EVP_EncryptInit.pod	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/doc/man3/EVP_EncryptInit.pod	2021-12-14 16:45:01.000000000 +0100
@@ -380,18 +380,20 @@
 
 =item EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, taglen, tag)
 
-Sets the expected tag to C<taglen> bytes from C<tag>.
-The tag length can only be set before specifying an IV.
+When decrypting, this call sets the expected tag to C<taglen> bytes from C<tag>.
 C<taglen> must be between 1 and 16 inclusive.
+The tag must be set prior to any call to EVP_DecryptFinal() or
+EVP_DecryptFinal_ex().
 
 For GCM, this call is only valid when decrypting data.
 
 For OCB, this call is valid when decrypting data to set the expected tag,
-and before encryption to set the desired tag length.
+and when encrypting to set the desired tag length.
 
-In OCB mode, calling this before encryption with C<tag> set to C<NULL> sets the
-tag length.  If this is not called prior to encryption, a default tag length is
-used.
+In OCB mode, calling this when encrypting with C<tag> set to C<NULL> sets the
+tag length. The tag length can only be set before specifying an IV. If this is
+not called prior to setting the IV during encryption, then a default tag length
+is used.
 
 For OCB AES, the default tag length is 16 (i.e. 128 bits).  It is also the
 maximum tag length for OCB.
@@ -659,7 +661,7 @@
 
 =head1 COPYRIGHT
 
-Copyright 2000-2020 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
 
 Licensed under the OpenSSL license (the "License").  You may not use
 this file except in compliance with the License.  You can obtain a copy
diff -Nru openssl-1.1.1k/doc/man3/OBJ_nid2obj.pod openssl-1.1.1m/doc/man3/OBJ_nid2obj.pod
--- openssl-1.1.1k/doc/man3/OBJ_nid2obj.pod	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/doc/man3/OBJ_nid2obj.pod	2021-12-14 16:45:01.000000000 +0100
@@ -46,26 +46,26 @@
 The ASN1 object utility functions process ASN1_OBJECT structures which are
 a representation of the ASN1 OBJECT IDENTIFIER (OID) type.
 For convenience, OIDs are usually represented in source code as numeric
-identifiers, or B<NID>s.  OpenSSL has an internal table of OIDs that
+identifiers, or I<NID>s.  OpenSSL has an internal table of OIDs that
 are generated when the library is built, and their corresponding NIDs
 are available as defined constants.  For the functions below, application
 code should treat all returned values -- OIDs, NIDs, or names -- as
 constants.
 
-OBJ_nid2obj(), OBJ_nid2ln() and OBJ_nid2sn() convert the NID B<n> to
+OBJ_nid2obj(), OBJ_nid2ln() and OBJ_nid2sn() convert the NID I<n> to
 an ASN1_OBJECT structure, its long name and its short name respectively,
 or B<NULL> if an error occurred.
 
 OBJ_obj2nid(), OBJ_ln2nid(), OBJ_sn2nid() return the corresponding NID
-for the object B<o>, the long name <ln> or the short name <sn> respectively
+for the object I<o>, the long name <ln> or the short name <sn> respectively
 or NID_undef if an error occurred.
 
-OBJ_txt2nid() returns NID corresponding to text string <s>. B<s> can be
+OBJ_txt2nid() returns NID corresponding to text string I<s>. I<s> can be
 a long name, a short name or the numerical representation of an object.
 
-OBJ_txt2obj() converts the text string B<s> into an ASN1_OBJECT structure.
-If B<no_name> is 0 then long names and short names will be interpreted
-as well as numerical forms. If B<no_name> is 1 only the numerical form
+OBJ_txt2obj() converts the text string I<s> into an ASN1_OBJECT structure.
+If I<no_name> is 0 then long names and short names will be interpreted
+as well as numerical forms. If I<no_name> is 1 only the numerical form
 is acceptable.
 
 OBJ_obj2txt() converts the B<ASN1_OBJECT> B<a> into a textual representation.
@@ -76,20 +76,20 @@
 the numerical form will be used. If B<no_name> is 1 then the numerical
 form will always be used.
 
-i2t_ASN1_OBJECT() is the same as OBJ_obj2txt() with the B<no_name> set to zero.
+i2t_ASN1_OBJECT() is the same as OBJ_obj2txt() with the I<no_name> set to zero.
 
-OBJ_cmp() compares B<a> to B<b>. If the two are identical 0 is returned.
+OBJ_cmp() compares I<a> to I<b>. If the two are identical 0 is returned.
 
-OBJ_dup() returns a copy of B<o>.
+OBJ_dup() returns a copy of I<o>.
 
-OBJ_create() adds a new object to the internal table. B<oid> is the
-numerical form of the object, B<sn> the short name and B<ln> the
+OBJ_create() adds a new object to the internal table. I<oid> is the
+numerical form of the object, I<sn> the short name and I<ln> the
 long name. A new NID is returned for the created object in case of
 success and NID_undef in case of failure.
 
-OBJ_length() returns the size of the content octets of B<obj>.
+OBJ_length() returns the size of the content octets of I<obj>.
 
-OBJ_get0_data() returns a pointer to the content octets of B<obj>.
+OBJ_get0_data() returns a pointer to the content octets of I<obj>.
 The returned pointer is an internal pointer which B<must not> be freed.
 
 OBJ_cleanup() releases any resources allocated by creating new objects.
@@ -181,7 +181,7 @@
 
 =head1 COPYRIGHT
 
-Copyright 2002-2019 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2002-2021 The OpenSSL Project Authors. All Rights Reserved.
 
 Licensed under the OpenSSL license (the "License").  You may not use
 this file except in compliance with the License.  You can obtain a copy
diff -Nru openssl-1.1.1k/doc/man3/SSL_CTX_set_num_tickets.pod openssl-1.1.1m/doc/man3/SSL_CTX_set_num_tickets.pod
--- openssl-1.1.1k/doc/man3/SSL_CTX_set_num_tickets.pod	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/doc/man3/SSL_CTX_set_num_tickets.pod	2021-12-14 16:45:01.000000000 +0100
@@ -25,10 +25,10 @@
 the B<num_tickets> argument. Typically these functions should be called before
 the start of the handshake.
 
-The default number of tickets is 2; the default number of tickets sent following
-a resumption handshake is 1 but this cannot be changed using these functions.
-The number of tickets following a resumption handshake can be reduced to 0 using
-custom session ticket callbacks (see L<SSL_CTX_set_session_ticket_cb(3)>).
+The default number of tickets is 2. Following a resumption the number of tickets
+issued will never be more than 1 regardless of the value set via
+SSL_set_num_tickets() or SSL_CTX_set_num_tickets(). If B<num_tickets> is set to
+0 then no tickets will be issued for either a normal connection or a resumption.
 
 Tickets are also issued on receipt of a post-handshake certificate from the
 client following a request by the server using
@@ -58,7 +58,7 @@
 
 =head1 COPYRIGHT
 
-Copyright 2018 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2018-2021 The OpenSSL Project Authors. All Rights Reserved.
 
 Licensed under the OpenSSL license (the "License").  You may not use
 this file except in compliance with the License.  You can obtain a copy
diff -Nru openssl-1.1.1k/doc/man3/SSL_CTX_set_tlsext_ticket_key_cb.pod openssl-1.1.1m/doc/man3/SSL_CTX_set_tlsext_ticket_key_cb.pod
--- openssl-1.1.1k/doc/man3/SSL_CTX_set_tlsext_ticket_key_cb.pod	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/doc/man3/SSL_CTX_set_tlsext_ticket_key_cb.pod	2021-12-14 16:45:01.000000000 +0100
@@ -123,7 +123,7 @@
 
 =head1 RETURN VALUES
 
-returns 0 to indicate the callback function was set.
+Returns 1 to indicate the callback function was set and 0 otherwise.
 
 =head1 EXAMPLES
 
@@ -193,7 +193,7 @@
 
 =head1 COPYRIGHT
 
-Copyright 2014-2020 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2014-2021 The OpenSSL Project Authors. All Rights Reserved.
 
 Licensed under the OpenSSL license (the "License").  You may not use
 this file except in compliance with the License.  You can obtain a copy
diff -Nru openssl-1.1.1k/doc/man3/SSL_get_session.pod openssl-1.1.1m/doc/man3/SSL_get_session.pod
--- openssl-1.1.1k/doc/man3/SSL_get_session.pod	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/doc/man3/SSL_get_session.pod	2021-12-14 16:45:01.000000000 +0100
@@ -37,8 +37,11 @@
 SSL_SESSION object can be used for resumption or not.
 
 Additionally, in TLSv1.3, a server can send multiple messages that establish a
-session for a single connection. In that case the above functions will only
-return information on the last session that was received.
+session for a single connection. In that case, on the client side, the above
+functions will only return information on the last session that was received. On
+the server side they will only return information on the last session that was
+sent, or if no session tickets were sent then the session for the current
+connection.
 
 The preferred way for applications to obtain a resumable SSL_SESSION object is
 to use a new session callback as described in L<SSL_CTX_sess_set_new_cb(3)>.
@@ -100,7 +103,7 @@
 
 =head1 COPYRIGHT
 
-Copyright 2000-2018 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
 
 Licensed under the OpenSSL license (the "License").  You may not use
 this file except in compliance with the License.  You can obtain a copy
diff -Nru openssl-1.1.1k/doc/man3/SSL_set_fd.pod openssl-1.1.1m/doc/man3/SSL_set_fd.pod
--- openssl-1.1.1k/doc/man3/SSL_set_fd.pod	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/doc/man3/SSL_set_fd.pod	2021-12-14 16:45:01.000000000 +0100
@@ -45,6 +45,17 @@
 
 =back
 
+=head1 NOTES
+
+On Windows, a socket handle is a 64-bit data type (UINT_PTR), which leads to a
+compiler warning (conversion from 'SOCKET' to 'int', possible loss of data) when
+passing the socket handle to SSL_set_*fd(). For the time being, this warning can
+safely be ignored, because although the Microsoft documentation claims that the
+upper limit is INVALID_SOCKET-1 (2^64 - 2), in practice the current socket()
+implementation returns an index into the kernel handle table, the size of which
+is limited to 2^24.
+
+
 =head1 SEE ALSO
 
 L<SSL_get_fd(3)>, L<SSL_set_bio(3)>,
@@ -53,7 +64,7 @@
 
 =head1 COPYRIGHT
 
-Copyright 2000-2020 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
 
 Licensed under the OpenSSL license (the "License").  You may not use
 this file except in compliance with the License.  You can obtain a copy
diff -Nru openssl-1.1.1k/doc/man7/ossl_store.pod openssl-1.1.1m/doc/man7/ossl_store.pod
--- openssl-1.1.1k/doc/man7/ossl_store.pod	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/doc/man7/ossl_store.pod	2021-12-14 16:45:01.000000000 +0100
@@ -58,7 +58,7 @@
       * here just one example
       */
      switch (OSSL_STORE_INFO_get_type(info)) {
-     case OSSL_STORE_INFO_X509:
+     case OSSL_STORE_INFO_CERT:
          /* Print the X.509 certificate text */
          X509_print_fp(stdout, OSSL_STORE_INFO_get0_CERT(info));
          /* Print the X.509 certificate PEM output */
@@ -77,7 +77,7 @@
 
 =head1 COPYRIGHT
 
-Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
 
 Licensed under the OpenSSL license (the "License").  You may not use
 this file except in compliance with the License.  You can obtain a copy
diff -Nru openssl-1.1.1k/doc/man7/x509.pod openssl-1.1.1m/doc/man7/x509.pod
--- openssl-1.1.1k/doc/man7/x509.pod	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/doc/man7/x509.pod	2021-12-14 16:45:01.000000000 +0100
@@ -11,7 +11,7 @@
 =head1 DESCRIPTION
 
 An X.509 certificate is a structured grouping of information about
-an individual, a device, or anything one can imagine.  A X.509 CRL
+an individual, a device, or anything one can imagine.  An X.509 CRL
 (certificate revocation list) is a tool to help determine if a
 certificate is still valid.  The exact definition of those can be
 found in the X.509 document from ITU-T, or in RFC3280 from PKIX.
@@ -24,7 +24,7 @@
 
 To handle some complex parts of a certificate, there are the types
 X509_NAME (to express a certificate name), X509_ATTRIBUTE (to express
-a certificate attributes), X509_EXTENSION (to express a certificate
+a certificate attribute), X509_EXTENSION (to express a certificate
 extension) and a few more.
 
 Finally, there's the supertype X509_INFO, which can contain a CRL, a
@@ -63,7 +63,7 @@
 
 =head1 COPYRIGHT
 
-Copyright 2003-2017 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2003-2021 The OpenSSL Project Authors. All Rights Reserved.
 
 Licensed under the OpenSSL license (the "License").  You may not use
 this file except in compliance with the License.  You can obtain a copy
diff -Nru openssl-1.1.1k/engines/e_afalg.c openssl-1.1.1m/engines/e_afalg.c
--- openssl-1.1.1k/engines/e_afalg.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/engines/e_afalg.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -624,11 +624,8 @@
     }
 
     actx = (afalg_ctx *) EVP_CIPHER_CTX_get_cipher_data(ctx);
-    if (actx == NULL || actx->init_done != MAGIC_INIT_NUM) {
-        ALG_WARN("%s afalg ctx passed\n",
-                 ctx == NULL ? "NULL" : "Uninitialised");
-        return 0;
-    }
+    if (actx == NULL || actx->init_done != MAGIC_INIT_NUM)
+        return 1;
 
     close(actx->sfd);
     close(actx->bfd);
diff -Nru openssl-1.1.1k/engines/e_dasync.c openssl-1.1.1m/engines/e_dasync.c
--- openssl-1.1.1k/engines/e_dasync.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/engines/e_dasync.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2015-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -182,8 +182,8 @@
                                    const int **nids, int nid);
 
 static int dasync_cipher_nids[] = {
-    NID_aes_128_cbc,
     NID_aes_128_cbc_hmac_sha1,
+    NID_aes_128_cbc,
     0
 };
 
@@ -244,7 +244,8 @@
             || !EVP_CIPHER_meth_set_flags(_hidden_aes_128_cbc,
                                           EVP_CIPH_FLAG_DEFAULT_ASN1
                                           | EVP_CIPH_CBC_MODE
-                                          | EVP_CIPH_FLAG_PIPELINE)
+                                          | EVP_CIPH_FLAG_PIPELINE
+                                          | EVP_CIPH_CUSTOM_COPY)
             || !EVP_CIPHER_meth_set_init(_hidden_aes_128_cbc,
                                          dasync_aes128_init_key)
             || !EVP_CIPHER_meth_set_do_cipher(_hidden_aes_128_cbc,
@@ -264,12 +265,14 @@
                                                 16 /* block size */,
                                                 16 /* key len */);
     if (_hidden_aes_128_cbc_hmac_sha1 == NULL
+            || EVP_aes_128_cbc_hmac_sha1() == NULL
             || !EVP_CIPHER_meth_set_iv_length(_hidden_aes_128_cbc_hmac_sha1,16)
             || !EVP_CIPHER_meth_set_flags(_hidden_aes_128_cbc_hmac_sha1,
                                             EVP_CIPH_CBC_MODE
                                           | EVP_CIPH_FLAG_DEFAULT_ASN1
                                           | EVP_CIPH_FLAG_AEAD_CIPHER
-                                          | EVP_CIPH_FLAG_PIPELINE)
+                                          | EVP_CIPH_FLAG_PIPELINE
+                                          | EVP_CIPH_CUSTOM_COPY)
             || !EVP_CIPHER_meth_set_init(_hidden_aes_128_cbc_hmac_sha1,
                                          dasync_aes128_cbc_hmac_sha1_init_key)
             || !EVP_CIPHER_meth_set_do_cipher(_hidden_aes_128_cbc_hmac_sha1,
@@ -371,6 +374,10 @@
     int ok = 1;
     if (cipher == NULL) {
         /* We are returning a list of supported nids */
+        if (dasync_aes_128_cbc_hmac_sha1() == NULL) {
+            *nids = dasync_cipher_nids + 1;
+            return 1;
+        }
         *nids = dasync_cipher_nids;
         return (sizeof(dasync_cipher_nids) -
                 1) / sizeof(dasync_cipher_nids[0]);
@@ -624,6 +631,21 @@
             }
         }
 
+        case EVP_CTRL_COPY:
+        {
+            const EVP_CIPHER *cipher = aeadcapable
+                                       ? EVP_aes_128_cbc_hmac_sha1()
+                                       : EVP_aes_128_cbc();
+            size_t data_size = EVP_CIPHER_impl_ctx_size(cipher);
+            void *cipher_data = OPENSSL_malloc(data_size);
+
+            if (cipher_data == NULL)
+                return 0;
+            memcpy(cipher_data, pipe_ctx->inner_cipher_data, data_size);
+            pipe_ctx->inner_cipher_data = cipher_data;
+            return 1;
+        }
+
         default:
             return 0;
     }
diff -Nru openssl-1.1.1k/include/crypto/rand.h openssl-1.1.1m/include/crypto/rand.h
--- openssl-1.1.1k/include/crypto/rand.h	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/include/crypto/rand.h	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2016-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -20,6 +20,16 @@
 
 # include <openssl/rand.h>
 
+# if defined(__APPLE__) && !defined(OPENSSL_NO_APPLE_CRYPTO_RANDOM)
+#  include <Availability.h>
+#  if (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200) || \
+     (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000)
+#   define OPENSSL_APPLE_CRYPTO_RANDOM 1
+#   include <CommonCrypto/CommonCryptoError.h>
+#   include <CommonCrypto/CommonRandom.h>
+#  endif
+# endif
+
 /* forward declaration */
 typedef struct rand_pool_st RAND_POOL;
 
diff -Nru openssl-1.1.1k/include/crypto/sm2.h openssl-1.1.1m/include/crypto/sm2.h
--- openssl-1.1.1k/include/crypto/sm2.h	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/include/crypto/sm2.h	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved.
  * Copyright 2017 Ribose Inc. All Rights Reserved.
  * Ported from Ribose contributions from Botan.
  *
@@ -60,8 +60,7 @@
 int sm2_ciphertext_size(const EC_KEY *key, const EVP_MD *digest, size_t msg_len,
                         size_t *ct_size);
 
-int sm2_plaintext_size(const EC_KEY *key, const EVP_MD *digest, size_t msg_len,
-                       size_t *pt_size);
+int sm2_plaintext_size(const unsigned char *ct, size_t ct_size, size_t *pt_size);
 
 int sm2_encrypt(const EC_KEY *key,
                 const EVP_MD *digest,
diff -Nru openssl-1.1.1k/include/crypto/x509.h openssl-1.1.1m/include/crypto/x509.h
--- openssl-1.1.1k/include/crypto/x509.h	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/include/crypto/x509.h	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -8,6 +8,8 @@
  */
 
 #include "internal/refcount.h"
+#include <openssl/x509.h>
+#include <openssl/conf.h>
 
 /* Internal X509 structures and functions: not for application use */
 
@@ -284,3 +286,6 @@
 int x509_set1_time(ASN1_TIME **ptm, const ASN1_TIME *tm);
 
 void x509_init_sig_info(X509 *x);
+
+int x509v3_add_len_value_uchar(const char *name, const unsigned char *value,
+                               size_t vallen, STACK_OF(CONF_VALUE) **extlist);
diff -Nru openssl-1.1.1k/include/openssl/ec.h openssl-1.1.1m/include/openssl/ec.h
--- openssl-1.1.1k/include/openssl/ec.h	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/include/openssl/ec.h	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2002-2021 The OpenSSL Project Authors. All Rights Reserved.
  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
@@ -793,12 +793,15 @@
 EC_GROUP *d2i_ECPKParameters(EC_GROUP **, const unsigned char **in, long len);
 int i2d_ECPKParameters(const EC_GROUP *, unsigned char **out);
 
-# define d2i_ECPKParameters_bio(bp,x) ASN1_d2i_bio_of(EC_GROUP,NULL,d2i_ECPKParameters,bp,x)
-# define i2d_ECPKParameters_bio(bp,x) ASN1_i2d_bio_of_const(EC_GROUP,i2d_ECPKParameters,bp,x)
-# define d2i_ECPKParameters_fp(fp,x) (EC_GROUP *)ASN1_d2i_fp(NULL, \
-                (char *(*)())d2i_ECPKParameters,(fp),(unsigned char **)(x))
-# define i2d_ECPKParameters_fp(fp,x) ASN1_i2d_fp(i2d_ECPKParameters,(fp), \
-                (unsigned char *)(x))
+# define d2i_ECPKParameters_bio(bp,x) \
+    ASN1_d2i_bio_of(EC_GROUP, NULL, d2i_ECPKParameters, bp, x)
+# define i2d_ECPKParameters_bio(bp,x) \
+    ASN1_i2d_bio_of_const(EC_GROUP, i2d_ECPKParameters, bp, x)
+# define d2i_ECPKParameters_fp(fp,x) \
+    (EC_GROUP *)ASN1_d2i_fp(NULL, (d2i_of_void *)d2i_ECPKParameters, (fp), \
+                            (void **)(x))
+# define i2d_ECPKParameters_fp(fp,x) \
+    ASN1_i2d_fp((i2d_of_void *)i2d_ECPKParameters, (fp), (void *)(x))
 
 int ECPKParameters_print(BIO *bp, const EC_GROUP *x, int off);
 # ifndef OPENSSL_NO_STDIO
diff -Nru openssl-1.1.1k/include/openssl/e_os2.h openssl-1.1.1m/include/openssl/e_os2.h
--- openssl-1.1.1k/include/openssl/e_os2.h	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/include/openssl/e_os2.h	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -279,7 +279,8 @@
 #  define ossl_inline inline
 # endif
 
-# if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
+# if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && \
+     !defined(__cplusplus) 
 #  define ossl_noreturn _Noreturn
 # elif defined(__GNUC__) && __GNUC__ >= 2
 #  define ossl_noreturn __attribute__((noreturn))
diff -Nru openssl-1.1.1k/include/openssl/opensslv.h openssl-1.1.1m/include/openssl/opensslv.h
--- openssl-1.1.1k/include/openssl/opensslv.h	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/include/openssl/opensslv.h	2021-12-14 16:45:01.000000000 +0100
@@ -39,8 +39,8 @@
  * (Prior to 0.9.5a beta1, a different scheme was used: MMNNFFRBB for
  *  major minor fix final patch/beta)
  */
-# define OPENSSL_VERSION_NUMBER  0x101010bfL
-# define OPENSSL_VERSION_TEXT    "OpenSSL 1.1.1k  25 Mar 2021"
+# define OPENSSL_VERSION_NUMBER  0x101010dfL
+# define OPENSSL_VERSION_TEXT    "OpenSSL 1.1.1m  14 Dec 2021"
 
 /*-
  * The macros below are to be used for shared library (.so, .dll, ...)
diff -Nru openssl-1.1.1k/include/openssl/sslerr.h openssl-1.1.1m/include/openssl/sslerr.h
--- openssl-1.1.1k/include/openssl/sslerr.h	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/include/openssl/sslerr.h	2021-12-14 16:45:01.000000000 +0100
@@ -1,6 +1,6 @@
 /*
  * Generated by util/mkerr.pl DO NOT EDIT
- * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -70,6 +70,7 @@
 # define SSL_F_FINAL_EMS                                  486
 # define SSL_F_FINAL_KEY_SHARE                            503
 # define SSL_F_FINAL_MAXFRAGMENTLEN                       557
+# define SSL_F_FINAL_PSK                                  639
 # define SSL_F_FINAL_RENEGOTIATE                          483
 # define SSL_F_FINAL_SERVER_NAME                          558
 # define SSL_F_FINAL_SIG_ALGS                             497
@@ -592,6 +593,7 @@
 # define SSL_R_MISSING_ECDSA_SIGNING_CERT                 381
 # define SSL_R_MISSING_FATAL                              256
 # define SSL_R_MISSING_PARAMETERS                         290
+# define SSL_R_MISSING_PSK_KEX_MODES_EXTENSION            310
 # define SSL_R_MISSING_RSA_CERTIFICATE                    168
 # define SSL_R_MISSING_RSA_ENCRYPTING_CERT                169
 # define SSL_R_MISSING_RSA_SIGNING_CERT                   170
@@ -633,6 +635,7 @@
 # define SSL_R_NO_VERIFY_COOKIE_CALLBACK                  403
 # define SSL_R_NULL_SSL_CTX                               195
 # define SSL_R_NULL_SSL_METHOD_PASSED                     196
+# define SSL_R_OCSP_CALLBACK_FAILURE                      294
 # define SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED            197
 # define SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED 344
 # define SSL_R_OVERFLOW_ERROR                             237
diff -Nru openssl-1.1.1k/include/openssl/x509v3err.h openssl-1.1.1m/include/openssl/x509v3err.h
--- openssl-1.1.1k/include/openssl/x509v3err.h	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/include/openssl/x509v3err.h	2021-12-14 16:45:01.000000000 +0100
@@ -1,6 +1,6 @@
 /*
  * Generated by util/mkerr.pl DO NOT EDIT
- * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -38,6 +38,7 @@
 # define X509V3_F_I2S_ASN1_IA5STRING                      149
 # define X509V3_F_I2S_ASN1_INTEGER                        120
 # define X509V3_F_I2V_AUTHORITY_INFO_ACCESS               138
+# define X509V3_F_I2V_AUTHORITY_KEYID                     173
 # define X509V3_F_LEVEL_ADD_NODE                          168
 # define X509V3_F_NOTICE_SECTION                          132
 # define X509V3_F_NREF_NOS                                133
@@ -78,6 +79,7 @@
 # define X509V3_F_V2I_TLS_FEATURE                         165
 # define X509V3_F_V3_GENERIC_EXTENSION                    116
 # define X509V3_F_X509V3_ADD1_I2D                         140
+# define X509V3_F_X509V3_ADD_LEN_VALUE                    174
 # define X509V3_F_X509V3_ADD_VALUE                        105
 # define X509V3_F_X509V3_EXT_ADD                          104
 # define X509V3_F_X509V3_EXT_ADD_ALIAS                    106
diff -Nru openssl-1.1.1k/NEWS openssl-1.1.1m/NEWS
--- openssl-1.1.1k/NEWS	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/NEWS	2021-12-14 16:45:01.000000000 +0100
@@ -5,6 +5,15 @@
   This file gives a brief overview of the major changes between each OpenSSL
   release. For more details please read the CHANGES file.
 
+  Major changes between OpenSSL 1.1.1l and OpenSSL 1.1.1m [14 Dec 2021]
+
+      o None
+
+  Major changes between OpenSSL 1.1.1k and OpenSSL 1.1.1l [24 Aug 2021]
+
+      o Fixed an SM2 Decryption Buffer Overflow (CVE-2021-3711)
+      o Fixed various read buffer overruns processing ASN.1 strings (CVE-2021-3712)
+
   Major changes between OpenSSL 1.1.1j and OpenSSL 1.1.1k [25 Mar 2021]
 
       o Fixed a problem with verifying a certificate chain when using the
diff -Nru openssl-1.1.1k/README openssl-1.1.1m/README
--- openssl-1.1.1k/README	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/README	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 
- OpenSSL 1.1.1k 25 Mar 2021
+ OpenSSL 1.1.1m 14 Dec 2021
 
  Copyright (c) 1998-2021 The OpenSSL Project
  Copyright (c) 1995-1998 Eric A. Young, Tim J. Hudson
diff -Nru openssl-1.1.1k/ssl/bio_ssl.c openssl-1.1.1m/ssl/bio_ssl.c
--- openssl-1.1.1k/ssl/bio_ssl.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/bio_ssl.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -76,13 +76,12 @@
     if (a == NULL)
         return 0;
     bs = BIO_get_data(a);
-    if (bs->ssl != NULL)
-        SSL_shutdown(bs->ssl);
     if (BIO_get_shutdown(a)) {
+        if (bs->ssl != NULL)
+            SSL_shutdown(bs->ssl);
         if (BIO_get_init(a))
             SSL_free(bs->ssl);
-        /* Clear all flags */
-        BIO_clear_flags(a, ~0);
+        BIO_clear_flags(a, ~0); /* Clear all flags */
         BIO_set_init(a, 0);
     }
     OPENSSL_free(bs);
@@ -451,6 +450,7 @@
         goto err;
     return ret;
  err:
+    BIO_free(ssl);
     BIO_free(con);
 #endif
     return NULL;
diff -Nru openssl-1.1.1k/ssl/d1_lib.c openssl-1.1.1m/ssl/d1_lib.c
--- openssl-1.1.1k/ssl/d1_lib.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/d1_lib.c	2021-12-14 16:45:01.000000000 +0100
@@ -342,12 +342,11 @@
     return 1;
 }
 
-void dtls1_double_timeout(SSL *s)
+static void dtls1_double_timeout(SSL *s)
 {
     s->d1->timeout_duration_us *= 2;
     if (s->d1->timeout_duration_us > 60000000)
         s->d1->timeout_duration_us = 60000000;
-    dtls1_start_timer(s);
 }
 
 void dtls1_stop_timer(SSL *s)
diff -Nru openssl-1.1.1k/ssl/record/rec_layer_s3.c openssl-1.1.1m/ssl/record/rec_layer_s3.c
--- openssl-1.1.1k/ssl/record/rec_layer_s3.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/record/rec_layer_s3.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -172,9 +172,9 @@
     /*
      * If extend == 0, obtain new n-byte packet; if extend == 1, increase
      * packet by another n bytes. The packet will be in the sub-array of
-     * s->s3->rbuf.buf specified by s->packet and s->packet_length. (If
-     * s->rlayer.read_ahead is set, 'max' bytes may be stored in rbuf [plus
-     * s->packet_length bytes if extend == 1].)
+     * s->rlayer.rbuf.buf specified by s->rlayer.packet and
+     * s->rlayer.packet_length. (If s->rlayer.read_ahead is set, 'max' bytes may
+     * be stored in rbuf [plus s->rlayer.packet_length bytes if extend == 1].)
      * if clearold == 1, move the packet to the start of the buffer; if
      * clearold == 0 then leave any old packets where they were
      */
diff -Nru openssl-1.1.1k/ssl/record/ssl3_buffer.c openssl-1.1.1m/ssl/record/ssl3_buffer.c
--- openssl-1.1.1k/ssl/record/ssl3_buffer.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/record/ssl3_buffer.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -74,7 +74,6 @@
         b->len = len;
     }
 
-    RECORD_LAYER_set_packet(&s->rlayer, &(b->buf[0]));
     return 1;
 }
 
diff -Nru openssl-1.1.1k/ssl/record/ssl3_record.c openssl-1.1.1m/ssl/record/ssl3_record.c
--- openssl-1.1.1k/ssl/record/ssl3_record.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/record/ssl3_record.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -405,7 +405,7 @@
             more = thisrr->length;
         }
         if (more > 0) {
-            /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
+            /* now s->rlayer.packet_length == SSL3_RT_HEADER_LENGTH */
 
             rret = ssl3_read_n(s, more, more, 1, 0, &n);
             if (rret <= 0)
@@ -416,9 +416,9 @@
         RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
 
         /*
-         * At this point, s->packet_length == SSL3_RT_HEADER_LENGTH
-         * + thisrr->length, or s->packet_length == SSL2_RT_HEADER_LENGTH
-         * + thisrr->length and we have that many bytes in s->packet
+         * At this point, s->rlayer.packet_length == SSL3_RT_HEADER_LENGTH
+         * + thisrr->length, or s->rlayer.packet_length == SSL2_RT_HEADER_LENGTH
+         * + thisrr->length and we have that many bytes in s->rlayer.packet
          */
         if (thisrr->rec_version == SSL2_VERSION) {
             thisrr->input =
@@ -429,11 +429,11 @@
         }
 
         /*
-         * ok, we can now read from 's->packet' data into 'thisrr' thisrr->input
-         * points at thisrr->length bytes, which need to be copied into
-         * thisrr->data by either the decryption or by the decompression When
-         * the data is 'copied' into the thisrr->data buffer, thisrr->input will
-         * be pointed at the new buffer
+         * ok, we can now read from 's->rlayer.packet' data into 'thisrr'.
+         * thisrr->input points at thisrr->length bytes, which need to be copied
+         * into thisrr->data by either the decryption or by the decompression.
+         * When the data is 'copied' into the thisrr->data buffer,
+         * thisrr->input will be updated to point at the new buffer
          */
 
         /*
@@ -1039,7 +1039,7 @@
 
                 if (SSL_IS_DTLS(s)) {
                     /* DTLS does not support pipelining */
-                    unsigned char dtlsseq[9], *p = dtlsseq;
+                    unsigned char dtlsseq[8], *p = dtlsseq;
 
                     s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
                         DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
@@ -1616,16 +1616,16 @@
     sess = s->session;
 
     /*
-     * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
-     * and we have that many bytes in s->packet
+     * At this point, s->rlayer.packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
+     * and we have that many bytes in s->rlayer.packet
      */
     rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
 
     /*
-     * ok, we can now read from 's->packet' data into 'rr' rr->input points
-     * at rr->length bytes, which need to be copied into rr->data by either
-     * the decryption or by the decompression When the data is 'copied' into
-     * the rr->data buffer, rr->input will be pointed at the new buffer
+     * ok, we can now read from 's->rlayer.packet' data into 'rr'. rr->input
+     * points at rr->length bytes, which need to be copied into rr->data by
+     * either the decryption or by the decompression. When the data is 'copied'
+     * into the rr->data buffer, rr->input will be pointed at the new buffer
      */
 
     /*
@@ -1947,7 +1947,7 @@
 
     if (rr->length >
         RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
-        /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
+        /* now s->rlayer.packet_length == DTLS1_RT_HEADER_LENGTH */
         more = rr->length;
         rret = ssl3_read_n(s, more, more, 1, 1, &n);
         /* this packet contained a partial record, dump it */
@@ -1963,7 +1963,7 @@
         }
 
         /*
-         * now n == rr->length, and s->packet_length ==
+         * now n == rr->length, and s->rlayer.packet_length ==
          * DTLS1_RT_HEADER_LENGTH + rr->length
          */
     }
diff -Nru openssl-1.1.1k/ssl/s3_cbc.c openssl-1.1.1m/ssl/s3_cbc.c
--- openssl-1.1.1k/ssl/s3_cbc.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/s3_cbc.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2012-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2012-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -128,7 +128,7 @@
 int ssl3_cbc_digest_record(const EVP_MD_CTX *ctx,
                            unsigned char *md_out,
                            size_t *md_out_size,
-                           const unsigned char header[13],
+                           const unsigned char *header,
                            const unsigned char *data,
                            size_t data_plus_mac_size,
                            size_t data_plus_mac_plus_padding_size,
diff -Nru openssl-1.1.1k/ssl/s3_msg.c openssl-1.1.1m/ssl/s3_msg.c
--- openssl-1.1.1k/ssl/s3_msg.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/s3_msg.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -48,6 +48,8 @@
                                           * protocol_version alerts */
     if (desc < 0)
         return -1;
+    if (s->shutdown & SSL_SENT_SHUTDOWN && desc != SSL_AD_CLOSE_NOTIFY)
+        return -1;
     /* If a fatal one, remove from cache */
     if ((level == SSL3_AL_FATAL) && (s->session != NULL))
         SSL_CTX_remove_session(s->session_ctx, s->session);
diff -Nru openssl-1.1.1k/ssl/ssl_asn1.c openssl-1.1.1m/ssl/ssl_asn1.c
--- openssl-1.1.1k/ssl/ssl_asn1.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/ssl_asn1.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  * Copyright 2005 Nokia. All rights reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
@@ -225,7 +225,7 @@
 static int ssl_session_memcpy(unsigned char *dst, size_t *pdstlen,
                               ASN1_OCTET_STRING *src, size_t maxlen)
 {
-    if (src == NULL) {
+    if (src == NULL || src->length == 0) {
         *pdstlen = 0;
         return 1;
     }
diff -Nru openssl-1.1.1k/ssl/ssl_cert.c openssl-1.1.1m/ssl/ssl_cert.c
--- openssl-1.1.1k/ssl/ssl_cert.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/ssl_cert.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
@@ -876,18 +876,36 @@
     return 1;
 }
 
+int ssl_get_security_level_bits(const SSL *s, const SSL_CTX *ctx, int *levelp)
+{
+    int level;
+    static const int minbits_table[5 + 1] = { 0, 80, 112, 128, 192, 256 };
+
+    if (ctx != NULL)
+        level = SSL_CTX_get_security_level(ctx);
+    else
+        level = SSL_get_security_level(s);
+
+    if (level > 5)
+        level = 5;
+    else if (level < 0)
+        level = 0;
+
+    if (levelp != NULL)
+        *levelp = level;
+
+    return minbits_table[level];
+}
+
 static int ssl_security_default_callback(const SSL *s, const SSL_CTX *ctx,
                                          int op, int bits, int nid, void *other,
                                          void *ex)
 {
     int level, minbits;
-    static const int minbits_table[5] = { 80, 112, 128, 192, 256 };
-    if (ctx)
-        level = SSL_CTX_get_security_level(ctx);
-    else
-        level = SSL_get_security_level(s);
 
-    if (level <= 0) {
+    minbits = ssl_get_security_level_bits(s, ctx, &level);
+
+    if (level == 0) {
         /*
          * No EDH keys weaker than 1024-bits even at level 0, otherwise,
          * anything goes.
@@ -896,9 +914,6 @@
             return 0;
         return 1;
     }
-    if (level > 5)
-        level = 5;
-    minbits = minbits_table[level - 1];
     switch (op) {
     case SSL_SECOP_CIPHER_SUPPORTED:
     case SSL_SECOP_CIPHER_SHARED:
diff -Nru openssl-1.1.1k/ssl/ssl_ciph.c openssl-1.1.1m/ssl/ssl_ciph.c
--- openssl-1.1.1k/ssl/ssl_ciph.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/ssl_ciph.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
  * Copyright 2005 Nokia. All rights reserved.
  *
@@ -1601,6 +1601,7 @@
     for (i = 0; i < sk_SSL_CIPHER_num(tls13_ciphersuites); i++) {
         if (!sk_SSL_CIPHER_push(cipherstack,
                                 sk_SSL_CIPHER_value(tls13_ciphersuites, i))) {
+            OPENSSL_free(co_list);
             sk_SSL_CIPHER_free(cipherstack);
             return NULL;
         }
diff -Nru openssl-1.1.1k/ssl/ssl_err.c openssl-1.1.1m/ssl/ssl_err.c
--- openssl-1.1.1k/ssl/ssl_err.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/ssl_err.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,6 +1,6 @@
 /*
  * Generated by util/mkerr.pl DO NOT EDIT
- * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -85,6 +85,7 @@
     {ERR_PACK(ERR_LIB_SSL, SSL_F_FINAL_KEY_SHARE, 0), "final_key_share"},
     {ERR_PACK(ERR_LIB_SSL, SSL_F_FINAL_MAXFRAGMENTLEN, 0),
      "final_maxfragmentlen"},
+    {ERR_PACK(ERR_LIB_SSL, SSL_F_FINAL_PSK, 0), "final_psk"},
     {ERR_PACK(ERR_LIB_SSL, SSL_F_FINAL_RENEGOTIATE, 0), "final_renegotiate"},
     {ERR_PACK(ERR_LIB_SSL, SSL_F_FINAL_SERVER_NAME, 0), "final_server_name"},
     {ERR_PACK(ERR_LIB_SSL, SSL_F_FINAL_SIG_ALGS, 0), "final_sig_algs"},
@@ -948,6 +949,8 @@
     "missing ecdsa signing cert"},
     {ERR_PACK(ERR_LIB_SSL, 0, SSL_R_MISSING_FATAL), "missing fatal"},
     {ERR_PACK(ERR_LIB_SSL, 0, SSL_R_MISSING_PARAMETERS), "missing parameters"},
+    {ERR_PACK(ERR_LIB_SSL, 0, SSL_R_MISSING_PSK_KEX_MODES_EXTENSION),
+    "missing psk kex modes extension"},
     {ERR_PACK(ERR_LIB_SSL, 0, SSL_R_MISSING_RSA_CERTIFICATE),
     "missing rsa certificate"},
     {ERR_PACK(ERR_LIB_SSL, 0, SSL_R_MISSING_RSA_ENCRYPTING_CERT),
@@ -1018,6 +1021,8 @@
     {ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NULL_SSL_CTX), "null ssl ctx"},
     {ERR_PACK(ERR_LIB_SSL, 0, SSL_R_NULL_SSL_METHOD_PASSED),
     "null ssl method passed"},
+    {ERR_PACK(ERR_LIB_SSL, 0, SSL_R_OCSP_CALLBACK_FAILURE),
+    "ocsp callback failure"},
     {ERR_PACK(ERR_LIB_SSL, 0, SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED),
     "old session cipher not returned"},
     {ERR_PACK(ERR_LIB_SSL, 0, SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED),
diff -Nru openssl-1.1.1k/ssl/ssl_lib.c openssl-1.1.1m/ssl/ssl_lib.c
--- openssl-1.1.1k/ssl/ssl_lib.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/ssl_lib.c	2021-12-14 16:45:01.000000000 +0100
@@ -1684,6 +1684,8 @@
         if (s->waitctx == NULL)
             return -1;
     }
+
+    s->rwstate = SSL_NOTHING;
     switch (ASYNC_start_job(&s->job, s->waitctx, &ret, func, args,
                             sizeof(struct ssl_async_args))) {
     case ASYNC_ERR:
@@ -2119,6 +2121,11 @@
         return 0;
     }
 
+    if (RECORD_LAYER_write_pending(&s->rlayer)) {
+        SSLerr(SSL_F_SSL_KEY_UPDATE, SSL_R_BAD_WRITE_RETRY);
+        return 0;
+    }
+
     ossl_statem_set_in_init(s, 1);
     s->key_update = updatetype;
     return 1;
@@ -2829,6 +2836,19 @@
 }
 #endif
 
+static int alpn_value_ok(const unsigned char *protos, unsigned int protos_len)
+{
+    unsigned int idx;
+
+    if (protos_len < 2 || protos == NULL)
+        return 0;
+
+    for (idx = 0; idx < protos_len; idx += protos[idx] + 1) {
+        if (protos[idx] == 0)
+            return 0;
+    }
+    return idx == protos_len;
+}
 /*
  * SSL_CTX_set_alpn_protos sets the ALPN protocol list on |ctx| to |protos|.
  * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
@@ -2837,13 +2857,25 @@
 int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos,
                             unsigned int protos_len)
 {
-    OPENSSL_free(ctx->ext.alpn);
-    ctx->ext.alpn = OPENSSL_memdup(protos, protos_len);
-    if (ctx->ext.alpn == NULL) {
+    unsigned char *alpn;
+
+    if (protos_len == 0 || protos == NULL) {
+        OPENSSL_free(ctx->ext.alpn);
+        ctx->ext.alpn = NULL;
         ctx->ext.alpn_len = 0;
+        return 0;
+    }
+    /* Not valid per RFC */
+    if (!alpn_value_ok(protos, protos_len))
+        return 1;
+
+    alpn = OPENSSL_memdup(protos, protos_len);
+    if (alpn == NULL) {
         SSLerr(SSL_F_SSL_CTX_SET_ALPN_PROTOS, ERR_R_MALLOC_FAILURE);
         return 1;
     }
+    OPENSSL_free(ctx->ext.alpn);
+    ctx->ext.alpn = alpn;
     ctx->ext.alpn_len = protos_len;
 
     return 0;
@@ -2857,13 +2889,25 @@
 int SSL_set_alpn_protos(SSL *ssl, const unsigned char *protos,
                         unsigned int protos_len)
 {
-    OPENSSL_free(ssl->ext.alpn);
-    ssl->ext.alpn = OPENSSL_memdup(protos, protos_len);
-    if (ssl->ext.alpn == NULL) {
+    unsigned char *alpn;
+
+    if (protos_len == 0 || protos == NULL) {
+        OPENSSL_free(ssl->ext.alpn);
+        ssl->ext.alpn = NULL;
         ssl->ext.alpn_len = 0;
+        return 0;
+    }
+    /* Not valid per RFC */
+    if (!alpn_value_ok(protos, protos_len))
+        return 1;
+
+    alpn = OPENSSL_memdup(protos, protos_len);
+    if (alpn == NULL) {
         SSLerr(SSL_F_SSL_SET_ALPN_PROTOS, ERR_R_MALLOC_FAILURE);
         return 1;
     }
+    OPENSSL_free(ssl->ext.alpn);
+    ssl->ext.alpn = alpn;
     ssl->ext.alpn_len = protos_len;
 
     return 0;
@@ -4520,8 +4564,11 @@
     }
 
     ctx = EVP_MD_CTX_new();
-    if (ctx == NULL)
+    if (ctx == NULL) {
+        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_HANDSHAKE_HASH,
+                 ERR_R_INTERNAL_ERROR);
         goto err;
+    }
 
     if (!EVP_MD_CTX_copy_ex(ctx, hdgst)
         || EVP_DigestFinal_ex(ctx, out, NULL) <= 0) {
diff -Nru openssl-1.1.1k/ssl/ssl_local.h openssl-1.1.1m/ssl/ssl_local.h
--- openssl-1.1.1k/ssl/ssl_local.h	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/ssl_local.h	2021-12-14 16:45:01.000000000 +0100
@@ -2305,6 +2305,7 @@
 __owur int ssl_security(const SSL *s, int op, int bits, int nid, void *other);
 __owur int ssl_ctx_security(const SSL_CTX *ctx, int op, int bits, int nid,
                             void *other);
+int ssl_get_security_level_bits(const SSL *s, const SSL_CTX *ctx, int *levelp);
 
 __owur int ssl_cert_lookup_by_nid(int nid, size_t *pidx);
 __owur const SSL_CERT_LOOKUP *ssl_cert_lookup_by_pkey(const EVP_PKEY *pk,
@@ -2426,7 +2427,6 @@
 void dtls1_start_timer(SSL *s);
 void dtls1_stop_timer(SSL *s);
 __owur int dtls1_is_timer_expired(SSL *s);
-void dtls1_double_timeout(SSL *s);
 __owur int dtls_raw_hello_verify_request(WPACKET *pkt, unsigned char *cookie,
                                          size_t cookie_len);
 __owur size_t dtls1_min_mtu(SSL *s);
@@ -2622,7 +2622,7 @@
 __owur int ssl3_cbc_digest_record(const EVP_MD_CTX *ctx,
                                   unsigned char *md_out,
                                   size_t *md_out_size,
-                                  const unsigned char header[13],
+                                  const unsigned char *header,
                                   const unsigned char *data,
                                   size_t data_plus_mac_size,
                                   size_t data_plus_mac_plus_padding_size,
diff -Nru openssl-1.1.1k/ssl/statem/extensions.c openssl-1.1.1m/ssl/statem/extensions.c
--- openssl-1.1.1k/ssl/statem/extensions.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/statem/extensions.c	2021-12-14 16:45:01.000000000 +0100
@@ -18,6 +18,7 @@
 static int init_server_name(SSL *s, unsigned int context);
 static int final_server_name(SSL *s, unsigned int context, int sent);
 #ifndef OPENSSL_NO_EC
+static int init_ec_point_formats(SSL *s, unsigned int context);
 static int final_ec_pt_formats(SSL *s, unsigned int context, int sent);
 #endif
 static int init_session_ticket(SSL *s, unsigned int context);
@@ -56,6 +57,7 @@
 static int final_early_data(SSL *s, unsigned int context, int sent);
 static int final_maxfragmentlen(SSL *s, unsigned int context, int sent);
 static int init_post_handshake_auth(SSL *s, unsigned int context);
+static int final_psk(SSL *s, unsigned int context, int sent);
 
 /* Structure to define a built-in extension */
 typedef struct extensions_definition_st {
@@ -158,7 +160,7 @@
         TLSEXT_TYPE_ec_point_formats,
         SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
         | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
-        NULL, tls_parse_ctos_ec_pt_formats, tls_parse_stoc_ec_pt_formats,
+        init_ec_point_formats, tls_parse_ctos_ec_pt_formats, tls_parse_stoc_ec_pt_formats,
         tls_construct_stoc_ec_pt_formats, tls_construct_ctos_ec_pt_formats,
         final_ec_pt_formats
     },
@@ -389,7 +391,7 @@
         SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_SERVER_HELLO
         | SSL_EXT_TLS_IMPLEMENTATION_ONLY | SSL_EXT_TLS1_3_ONLY,
         NULL, tls_parse_ctos_psk, tls_parse_stoc_psk, tls_construct_stoc_psk,
-        tls_construct_ctos_psk, NULL
+        tls_construct_ctos_psk, final_psk
     }
 };
 
@@ -1026,6 +1028,15 @@
 }
 
 #ifndef OPENSSL_NO_EC
+static int init_ec_point_formats(SSL *s, unsigned int context)
+{
+    OPENSSL_free(s->ext.peer_ecpointformats);
+    s->ext.peer_ecpointformats = NULL;
+    s->ext.peer_ecpointformats_len = 0;
+
+    return 1;
+}
+
 static int final_ec_pt_formats(SSL *s, unsigned int context, int sent)
 {
     unsigned long alg_k, alg_a;
@@ -1718,3 +1729,19 @@
 
     return 1;
 }
+
+/*
+ * If clients offer "pre_shared_key" without a "psk_key_exchange_modes"
+ * extension, servers MUST abort the handshake.
+ */
+static int final_psk(SSL *s, unsigned int context, int sent)
+{
+    if (s->server && sent && s->clienthello != NULL
+            && !s->clienthello->pre_proc_exts[TLSEXT_IDX_psk_kex_modes].present) {
+        SSLfatal(s, TLS13_AD_MISSING_EXTENSION, SSL_F_FINAL_PSK,
+                 SSL_R_MISSING_PSK_KEX_MODES_EXTENSION);
+        return 0;
+    }
+
+    return 1;
+}
diff -Nru openssl-1.1.1k/ssl/statem/extensions_clnt.c openssl-1.1.1m/ssl/statem/extensions_clnt.c
--- openssl-1.1.1k/ssl/statem/extensions_clnt.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/statem/extensions_clnt.c	2021-12-14 16:45:01.000000000 +0100
@@ -1741,7 +1741,9 @@
     /* Ignore if inappropriate ciphersuite */
     if (!(s->options & SSL_OP_NO_ENCRYPT_THEN_MAC)
             && s->s3->tmp.new_cipher->algorithm_mac != SSL_AEAD
-            && s->s3->tmp.new_cipher->algorithm_enc != SSL_RC4)
+            && s->s3->tmp.new_cipher->algorithm_enc != SSL_RC4
+            && s->s3->tmp.new_cipher->algorithm_enc != SSL_eGOST2814789CNT
+            && s->s3->tmp.new_cipher->algorithm_enc != SSL_eGOST2814789CNT12)
         s->ext.use_etm = 1;
 
     return 1;
@@ -1872,6 +1874,7 @@
     if (skey == NULL || EVP_PKEY_copy_parameters(skey, ckey) <= 0) {
         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PARSE_STOC_KEY_SHARE,
                  ERR_R_MALLOC_FAILURE);
+        EVP_PKEY_free(skey);
         return 0;
     }
     if (!EVP_PKEY_set1_tls_encodedpoint(skey, PACKET_data(&encoded_pt),
diff -Nru openssl-1.1.1k/ssl/statem/extensions_cust.c openssl-1.1.1m/ssl/statem/extensions_cust.c
--- openssl-1.1.1k/ssl/statem/extensions_cust.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/statem/extensions_cust.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2014-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2014-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -146,11 +146,12 @@
     }
 
     /*
-     * Extensions received in the ClientHello are marked with the
-     * SSL_EXT_FLAG_RECEIVED. This is so we know to add the equivalent
-     * extensions in the ServerHello/EncryptedExtensions message
+     * Extensions received in the ClientHello or CertificateRequest are marked
+     * with the SSL_EXT_FLAG_RECEIVED. This is so we know to add the equivalent
+     * extensions in the response messages
      */
-    if ((context & SSL_EXT_CLIENT_HELLO) != 0)
+    if ((context & (SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST))
+            != 0)
         meth->ext_flags |= SSL_EXT_FLAG_RECEIVED;
 
     /* If no parse function set return success */
@@ -192,7 +193,7 @@
                         | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
                         | SSL_EXT_TLS1_3_CERTIFICATE
                         | SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST)) != 0) {
-            /* Only send extensions present in ClientHello. */
+            /* Only send extensions present in ClientHello/CertificateRequest */
             if (!(meth->ext_flags & SSL_EXT_FLAG_RECEIVED))
                 continue;
         }
diff -Nru openssl-1.1.1k/ssl/statem/extensions_srvr.c openssl-1.1.1m/ssl/statem/extensions_srvr.c
--- openssl-1.1.1k/ssl/statem/extensions_srvr.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/statem/extensions_srvr.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -1714,6 +1714,13 @@
         }
         return EXT_RETURN_NOT_SENT;
     }
+    if (s->hit && (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE_DHE) == 0) {
+        /*
+         * PSK ('hit') and explicitly not doing DHE (if the client sent the
+         * DHE option we always take it); don't send key share.
+         */
+        return EXT_RETURN_NOT_SENT;
+    }
 
     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_key_share)
             || !WPACKET_start_sub_packet_u16(pkt)
diff -Nru openssl-1.1.1k/ssl/statem/README openssl-1.1.1m/ssl/statem/README
--- openssl-1.1.1k/ssl/statem/README	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/statem/README	2021-12-14 16:45:01.000000000 +0100
@@ -55,7 +55,7 @@
                |       |                   |      |
    ____________V_______V________   ________V______V_______________
   |                             | |                               |
-  | statem_both.c               | | statem_dtls.c                 |
+  | statem_lib.c                | | statem_dtls.c                 |
   |                             | |                               |
   | Non core functions common   | | Non core functions common to  |
   | to both servers and clients | | both DTLS servers and clients |
diff -Nru openssl-1.1.1k/ssl/statem/statem_clnt.c openssl-1.1.1m/ssl/statem/statem_clnt.c
--- openssl-1.1.1k/ssl/statem/statem_clnt.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/statem/statem_clnt.c	2021-12-14 16:45:01.000000000 +0100
@@ -1001,7 +1001,8 @@
         return CCS_MAX_LENGTH;
 
     case TLS_ST_CR_SESSION_TICKET:
-        return SSL3_RT_MAX_PLAIN_LENGTH;
+        return (SSL_IS_TLS13(s)) ? SESSION_TICKET_MAX_LENGTH_TLS13
+                                 : SESSION_TICKET_MAX_LENGTH_TLS12;
 
     case TLS_ST_CR_FINISHED:
         return FINISHED_MAX_LENGTH;
@@ -2833,7 +2834,7 @@
         if (ret < 0) {
             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
                      SSL_F_TLS_PROCESS_INITIAL_SERVER_FLIGHT,
-                     ERR_R_MALLOC_FAILURE);
+                     SSL_R_OCSP_CALLBACK_FAILURE);
             return 0;
         }
     }
diff -Nru openssl-1.1.1k/ssl/statem/statem_lib.c openssl-1.1.1m/ssl/statem/statem_lib.c
--- openssl-1.1.1k/ssl/statem/statem_lib.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/statem/statem_lib.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
@@ -2410,6 +2410,8 @@
             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
                      SSL_F_TLS13_SAVE_HANDSHAKE_DIGEST_FOR_PHA,
                      ERR_R_INTERNAL_ERROR);
+            EVP_MD_CTX_free(s->pha_dgst);
+            s->pha_dgst = NULL;
             return 0;
         }
     }
diff -Nru openssl-1.1.1k/ssl/statem/statem_local.h openssl-1.1.1m/ssl/statem/statem_local.h
--- openssl-1.1.1k/ssl/statem/statem_local.h	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/statem/statem_local.h	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2015-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -22,6 +22,8 @@
 #define SERVER_HELLO_MAX_LENGTH         20000
 #define HELLO_RETRY_REQUEST_MAX_LENGTH  20000
 #define ENCRYPTED_EXTENSIONS_MAX_LENGTH 20000
+#define SESSION_TICKET_MAX_LENGTH_TLS13 131338
+#define SESSION_TICKET_MAX_LENGTH_TLS12 65541
 #define SERVER_KEY_EXCH_MAX_LENGTH      102400
 #define SERVER_HELLO_DONE_MAX_LENGTH    0
 #define KEY_UPDATE_MAX_LENGTH           1
diff -Nru openssl-1.1.1k/ssl/statem/statem_srvr.c openssl-1.1.1m/ssl/statem/statem_srvr.c
--- openssl-1.1.1k/ssl/statem/statem_srvr.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/statem/statem_srvr.c	2021-12-14 16:45:01.000000000 +0100
@@ -3753,6 +3753,7 @@
 
     sk_X509_pop_free(s->session->peer_chain, X509_free);
     s->session->peer_chain = sk;
+    sk = NULL;
 
     /*
      * Freeze the handshake buffer. For <TLS1.3 we do this after the CKE
@@ -3767,7 +3768,6 @@
      * Inconsistency alert: cert_chain does *not* include the peer's own
      * certificate, while we do include it in statem_clnt.c
      */
-    sk = NULL;
 
     /* Save the current hash state for when we receive the CertificateVerify */
     if (SSL_IS_TLS13(s)) {
@@ -4139,9 +4139,12 @@
     }
 
     if (tctx->generate_ticket_cb != NULL &&
-        tctx->generate_ticket_cb(s, tctx->ticket_cb_data) == 0)
+        tctx->generate_ticket_cb(s, tctx->ticket_cb_data) == 0) {
+        SSLfatal(s, SSL_AD_INTERNAL_ERROR,
+                 SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
+                 ERR_R_INTERNAL_ERROR);
         goto err;
-
+    }
     /*
      * If we are using anti-replay protection then we behave as if
      * SSL_OP_NO_TICKET is set - we are caching tickets anyway so there
diff -Nru openssl-1.1.1k/ssl/t1_lib.c openssl-1.1.1m/ssl/t1_lib.c
--- openssl-1.1.1k/ssl/t1_lib.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/ssl/t1_lib.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -2441,7 +2441,8 @@
 {
     DH *dhp = NULL;
     BIGNUM *p = NULL, *g = NULL;
-    int dh_secbits = 80;
+    int dh_secbits = 80, sec_level_bits;
+
     if (s->cert->dh_tmp_auto != 2) {
         if (s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aPSK)) {
             if (s->s3->tmp.new_cipher->strength_bits == 256)
@@ -2464,6 +2465,12 @@
         BN_free(g);
         return NULL;
     }
+
+    /* Do not pick a prime that is too weak for the current security level */
+    sec_level_bits = ssl_get_security_level_bits(s, NULL, NULL);
+    if (dh_secbits < sec_level_bits)
+        dh_secbits = sec_level_bits;
+
     if (dh_secbits >= 192)
         p = BN_get_rfc3526_prime_8192(NULL);
     else if (dh_secbits >= 152)
diff -Nru openssl-1.1.1k/test/afalgtest.c openssl-1.1.1m/test/afalgtest.c
--- openssl-1.1.1k/test/afalgtest.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/afalgtest.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2016-2017 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -21,26 +21,7 @@
 
 #ifndef OPENSSL_NO_ENGINE
 static ENGINE *e;
-#endif
-
 
-#ifndef OPENSSL_NO_AFALGENG
-# include <linux/version.h>
-# define K_MAJ   4
-# define K_MIN1  1
-# define K_MIN2  0
-# if LINUX_VERSION_CODE < KERNEL_VERSION(K_MAJ, K_MIN1, K_MIN2)
-/*
- * If we get here then it looks like there is a mismatch between the linux
- * headers and the actual kernel version, so we have tried to compile with
- * afalg support, but then skipped it in e_afalg.c. As far as this test is
- * concerned we behave as if we had been configured without support
- */
-#  define OPENSSL_NO_AFALGENG
-# endif
-#endif
-
-#ifndef OPENSSL_NO_AFALGENG
 static int test_afalg_aes_cbc(int keysize_idx)
 {
     EVP_CIPHER_CTX *ctx;
@@ -112,9 +93,25 @@
     EVP_CIPHER_CTX_free(ctx);
     return ret;
 }
-#endif
 
-#ifndef OPENSSL_NO_ENGINE
+static int test_pr16743(void)
+{
+    int ret = 0;
+    const EVP_CIPHER * cipher;
+    EVP_CIPHER_CTX *ctx;
+
+    if (!TEST_true(ENGINE_init(e)))
+        return 0;
+    cipher = ENGINE_get_cipher(e, NID_aes_128_cbc);
+    ctx = EVP_CIPHER_CTX_new();
+    if (cipher != NULL && ctx != NULL)
+        ret = EVP_EncryptInit_ex(ctx, cipher, e, NULL, NULL);
+    TEST_true(ret);
+    EVP_CIPHER_CTX_free(ctx);
+    ENGINE_finish(e);
+    return ret;
+}
+
 int global_init(void)
 {
     ENGINE_load_builtin_engines();
@@ -132,9 +129,8 @@
         /* Probably a platform env issue, not a test failure. */
         TEST_info("Can't load AFALG engine");
     } else {
-# ifndef OPENSSL_NO_AFALGENG
         ADD_ALL_TESTS(test_afalg_aes_cbc, 3);
-# endif
+        ADD_TEST(test_pr16743);
     }
 #endif
 
diff -Nru openssl-1.1.1k/test/asn1_decode_test.c openssl-1.1.1m/test/asn1_decode_test.c
--- openssl-1.1.1k/test/asn1_decode_test.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/asn1_decode_test.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2017-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -12,6 +12,7 @@
 
 #include <openssl/rand.h>
 #include <openssl/asn1t.h>
+#include <openssl/obj_mac.h>
 #include "internal/numbers.h"
 #include "testutil.h"
 
@@ -195,6 +196,30 @@
     return 0;
 }
 
+static int test_reuse_asn1_object(void)
+{
+    static unsigned char cn_der[] = { 0x06, 0x03, 0x55, 0x04, 0x06 };
+    static unsigned char oid_der[] = {
+        0x06, 0x06, 0x2a, 0x03, 0x04, 0x05, 0x06, 0x07
+    };
+    int ret = 0;
+    ASN1_OBJECT *obj;
+    unsigned char const *p = oid_der;
+
+    /* Create an object that owns dynamically allocated 'sn' and 'ln' fields */
+
+    if (!TEST_ptr(obj = ASN1_OBJECT_create(NID_undef, cn_der, sizeof(cn_der),
+                                           "C", "countryName")))
+        goto err;
+    /* reuse obj - this should not leak sn and ln */
+    if (!TEST_ptr(d2i_ASN1_OBJECT(&obj, &p, sizeof(oid_der))))
+        goto err;
+    ret = 1;
+err:
+    ASN1_OBJECT_free(obj);
+    return ret;
+}
+
 int setup_tests(void)
 {
 #if OPENSSL_API_COMPAT < 0x10200000L
@@ -205,5 +230,6 @@
     ADD_TEST(test_int64);
     ADD_TEST(test_uint64);
     ADD_TEST(test_invalid_template);
+    ADD_TEST(test_reuse_asn1_object);
     return 1;
 }
diff -Nru openssl-1.1.1k/test/bio_memleak_test.c openssl-1.1.1m/test/bio_memleak_test.c
--- openssl-1.1.1k/test/bio_memleak_test.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/bio_memleak_test.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2018-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2018-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -10,6 +10,8 @@
 #include <string.h>
 #include <openssl/buffer.h>
 #include <openssl/bio.h>
+#include <openssl/pkcs7.h>
+#include <openssl/obj_mac.h>
 
 #include "testutil.h"
 
@@ -35,7 +37,7 @@
         goto finish;
     ok = 1;
 
-finish:
+ finish:
     BIO_free(bio);
     return ok;
 }
@@ -62,7 +64,7 @@
         goto finish;
     ok = 1;
 
-finish:
+ finish:
     BIO_free(bio);
     BUF_MEM_free(bufmem);
     return ok;
@@ -98,7 +100,7 @@
         goto finish;
     ok = 1;
 
-finish:
+ finish:
     BIO_free(bio);
     return ok;
 }
@@ -139,7 +141,7 @@
         goto finish;
     ok = 1;
 
-finish:
+ finish:
     BIO_free(bio);
     BIO_free(bio2);
     return ok;
@@ -176,7 +178,7 @@
 
     ok = 1;
 
-finish:
+ finish:
     BIO_free(bio);
     return ok;
 }
@@ -216,11 +218,72 @@
 
     ok = 1;
 
-finish:
+ finish:
     BIO_free(bio);
     return ok;
 }
 
+static int error_callback_fired;
+static long BIO_error_callback(BIO *bio, int cmd, const char *argp,
+                               size_t len, int argi,
+                               long argl, int ret, size_t *processed)
+{
+    if ((cmd & (BIO_CB_READ | BIO_CB_RETURN)) != 0) {
+        error_callback_fired = 1;
+        ret = 0;  /* fail for read operations to simulate error in input BIO */
+    }
+    return ret;
+}
+
+/* Checks i2d_ASN1_bio_stream() is freeing all memory when input BIO ends unexpectedly. */
+static int test_bio_i2d_ASN1_mime(void)
+{
+    int ok = 0;
+    BIO *bio = NULL, *out = NULL;
+    BUF_MEM bufmem;
+    static const char str[] = "BIO mime test\n";
+    PKCS7 *p7 = NULL;
+
+    if (!TEST_ptr(bio = BIO_new(BIO_s_mem())))
+        goto finish;
+
+    bufmem.length = sizeof(str);
+    bufmem.data = (char *) str;
+    bufmem.max = bufmem.length;
+    BIO_set_mem_buf(bio, &bufmem, BIO_NOCLOSE);
+    BIO_set_flags(bio, BIO_FLAGS_MEM_RDONLY);
+    BIO_set_callback_ex(bio, BIO_error_callback);
+
+    if (!TEST_ptr(out = BIO_new(BIO_s_mem())))
+        goto finish;
+    if (!TEST_ptr(p7 = PKCS7_new()))
+        goto finish;
+    if (!TEST_true(PKCS7_set_type(p7, NID_pkcs7_data)))
+        goto finish;
+
+    error_callback_fired = 0;
+
+    /*
+     * The call succeeds even if the input stream ends unexpectedly as
+     * there is no handling for this case in SMIME_crlf_copy().
+     */
+    if (!TEST_true(i2d_ASN1_bio_stream(out, (ASN1_VALUE*) p7, bio,
+                                       SMIME_STREAM | SMIME_BINARY,
+                                       ASN1_ITEM_rptr(PKCS7))))
+        goto finish;
+
+    if (!TEST_int_eq(error_callback_fired, 1))
+        goto finish;
+
+    ok = 1;
+
+ finish:
+    BIO_free(bio);
+    BIO_free(out);
+    PKCS7_free(p7);
+    return ok;
+}
+
 int global_init(void)
 {
     CRYPTO_set_mem_debug(1);
@@ -236,5 +299,6 @@
     ADD_TEST(test_bio_rdonly_mem_buf);
     ADD_TEST(test_bio_rdwr_rdonly);
     ADD_TEST(test_bio_nonclear_rst);
+    ADD_TEST(test_bio_i2d_ASN1_mime);
     return 1;
 }
diff -Nru openssl-1.1.1k/test/bntest.c openssl-1.1.1m/test/bntest.c
--- openssl-1.1.1k/test/bntest.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/bntest.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -27,7 +27,6 @@
 /*
  * Things in boring, not in openssl.  TODO we should add them.
  */
-#define HAVE_BN_PADDED 0
 #define HAVE_BN_SQRT 0
 
 typedef struct filetest_st {
@@ -305,6 +304,75 @@
     return st;
 }
 
+static struct {
+    int n, divisor, result, remainder;
+} signed_mod_tests[] = {
+    {  10,   3,   3,   1 },
+    { -10,   3,  -3,  -1 },
+    {  10,  -3,  -3,   1 },
+    { -10,  -3,   3,  -1 },
+};
+
+static BIGNUM *set_signed_bn(int value)
+{
+    BIGNUM *bn = BN_new();
+
+    if (bn == NULL)
+        return NULL;
+    if (!BN_set_word(bn, value < 0 ? -value : value)) {
+        BN_free(bn);
+        return NULL;
+    }
+    BN_set_negative(bn, value < 0);
+    return bn;
+}
+
+static int test_signed_mod_replace_ab(int n)
+{
+    BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL;
+    int st = 0;
+
+    if (!TEST_ptr(a = set_signed_bn(signed_mod_tests[n].n))
+            || !TEST_ptr(b = set_signed_bn(signed_mod_tests[n].divisor))
+            || !TEST_ptr(c = set_signed_bn(signed_mod_tests[n].result))
+            || !TEST_ptr(d = set_signed_bn(signed_mod_tests[n].remainder)))
+        goto err;
+
+    if (TEST_true(BN_div(a, b, a, b, ctx))
+            && TEST_BN_eq(a, c)
+            && TEST_BN_eq(b, d))
+        st = 1;
+ err:
+    BN_free(a);
+    BN_free(b);
+    BN_free(c);
+    BN_free(d);
+    return st;
+}
+
+static int test_signed_mod_replace_ba(int n)
+{
+    BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL;
+    int st = 0;
+
+    if (!TEST_ptr(a = set_signed_bn(signed_mod_tests[n].n))
+            || !TEST_ptr(b = set_signed_bn(signed_mod_tests[n].divisor))
+            || !TEST_ptr(c = set_signed_bn(signed_mod_tests[n].result))
+            || !TEST_ptr(d = set_signed_bn(signed_mod_tests[n].remainder)))
+        goto err;
+
+    if (TEST_true(BN_div(b, a, a, b, ctx))
+            && TEST_BN_eq(b, c)
+            && TEST_BN_eq(a, d))
+        st = 1;
+ err:
+    BN_free(a);
+    BN_free(b);
+    BN_free(c);
+    BN_free(d);
+    return st;
+}
+
 static int test_mod(void)
 {
     BIGNUM *a = NULL, *b = NULL, *c = NULL, *d = NULL, *e = NULL;
@@ -326,8 +394,10 @@
         BN_set_negative(b, rand_neg());
         if (!(TEST_true(BN_mod(c, a, b, ctx))
                 && TEST_true(BN_div(d, e, a, b, ctx))
-                && TEST_true(BN_sub(e, e, c))
-                && TEST_BN_eq_zero(e)))
+                && TEST_BN_eq(e, c)
+                && TEST_true(BN_mul(c, d, b, ctx))
+                && TEST_true(BN_add(d, c, e))
+                && TEST_BN_eq(d, a)))
             goto err;
     }
     st = 1;
@@ -557,6 +627,51 @@
     if (!TEST_BN_eq(c, d))
         goto err;
 
+    /*
+     * Regression test for overflow bug in bn_sqr_comba4/8 for
+     * mips-linux-gnu and mipsel-linux-gnu 32bit targets.
+     */
+    {
+        static const char *ehex[] = {
+            "95564994a96c45954227b845a1e99cb939d5a1da99ee91acc962396ae999a9ee",
+            "38603790448f2f7694c242a875f0cad0aae658eba085f312d2febbbd128dd2b5",
+            "8f7d1149f03724215d704344d0d62c587ae3c5939cba4b9b5f3dc5e8e911ef9a",
+            "5ce1a5a749a4989d0d8368f6e1f8cdf3a362a6c97fb02047ff152b480a4ad985",
+            "2d45efdf0770542992afca6a0590d52930434bba96017afbc9f99e112950a8b1",
+            "a359473ec376f329bdae6a19f503be6d4be7393c4e43468831234e27e3838680",
+            "b949390d2e416a3f9759e5349ab4c253f6f29f819a6fe4cbfd27ada34903300e",
+            "da021f62839f5878a36f1bc3085375b00fd5fa3e68d316c0fdace87a97558465",
+            NULL};
+        static const char *phex[] = {
+            "f95dc0f980fbd22e90caa5a387cc4a369f3f830d50dd321c40db8c09a7e1a241",
+            "a536e096622d3280c0c1ba849c1f4a79bf490f60006d081e8cf69960189f0d31",
+            "2cd9e17073a3fba7881b21474a13b334116cb2f5dbf3189a6de3515d0840f053",
+            "c776d3982d391b6d04d642dda5cc6d1640174c09875addb70595658f89efb439",
+            "dc6fbd55f903aadd307982d3f659207f265e1ec6271b274521b7a5e28e8fd7a5",
+            "5df089292820477802a43cf5b6b94e999e8c9944ddebb0d0e95a60f88cb7e813",
+            "ba110d20e1024774107dd02949031864923b3cb8c3f7250d6d1287b0a40db6a4",
+            "7bd5a469518eb65aa207ddc47d8c6e5fc8e0c105be8fc1d4b57b2e27540471d5",
+            NULL};
+        static const char *mhex[] = {
+            "fef15d5ce4625f1bccfbba49fc8439c72bf8202af039a2259678941b60bb4a8f",
+            "2987e965d58fd8cf86a856674d519763d0e1211cc9f8596971050d56d9b35db3",
+            "785866cfbca17cfdbed6060be3629d894f924a89fdc1efc624f80d41a22f1900",
+            "9503fcc3824ef62ccb9208430c26f2d8ceb2c63488ec4c07437aa4c96c43dd8b",
+            "9289ed00a712ff66ee195dc71f5e4ead02172b63c543d69baf495f5fd63ba7bc",
+            "c633bd309c016e37736da92129d0b053d4ab28d21ad7d8b6fab2a8bbdc8ee647",
+            "d2fbcf2cf426cf892e6f5639e0252993965dfb73ccd277407014ea784aaa280c",
+            "b7b03972bc8b0baa72360bdb44b82415b86b2f260f877791cd33ba8f2d65229b",
+            NULL};
+
+        if (!TEST_true(parse_bigBN(&e, ehex))
+                || !TEST_true(parse_bigBN(&p, phex))
+                || !TEST_true(parse_bigBN(&m, mhex))
+                || !TEST_true(BN_mod_exp_mont_consttime(d, e, p, m, ctx, NULL))
+                || !TEST_true(BN_mod_exp_simple(a, e, p, m, ctx))
+                || !TEST_BN_eq(a, d))
+            goto err;
+    }
+
     /* Zero input */
     if (!TEST_true(BN_bntest_rand(p, 1024, 0, 0)))
         goto err;
@@ -1660,52 +1775,52 @@
 
 static int test_bn2padded(void)
 {
-#if HAVE_BN_PADDED
     uint8_t zeros[256], out[256], reference[128];
-    BIGNUM *n = BN_new();
+    size_t bytes;
+    BIGNUM *n;
     int st = 0;
 
     /* Test edge case at 0. */
-    if (n == NULL)
+    if (!TEST_ptr((n = BN_new())))
         goto err;
-    if (!TEST_true(BN_bn2bin_padded(NULL, 0, n)))
+    if (!TEST_int_eq(BN_bn2binpad(n, NULL, 0), 0))
         goto err;
     memset(out, -1, sizeof(out));
-    if (!TEST_true(BN_bn2bin_padded(out, sizeof(out)), n))
+    if (!TEST_int_eq(BN_bn2binpad(n, out, sizeof(out)), sizeof(out)))
         goto err;
     memset(zeros, 0, sizeof(zeros));
     if (!TEST_mem_eq(zeros, sizeof(zeros), out, sizeof(out)))
         goto err;
 
     /* Test a random numbers at various byte lengths. */
-    for (size_t bytes = 128 - 7; bytes <= 128; bytes++) {
+    for (bytes = 128 - 7; bytes <= 128; bytes++) {
 # define TOP_BIT_ON 0
 # define BOTTOM_BIT_NOTOUCH 0
         if (!TEST_true(BN_rand(n, bytes * 8, TOP_BIT_ON, BOTTOM_BIT_NOTOUCH)))
             goto err;
-        if (!TEST_int_eq(BN_num_bytes(n),A) bytes
-                || TEST_int_eq(BN_bn2bin(n, reference), bytes))
+        if (!TEST_int_eq(BN_num_bytes(n), bytes)
+                || !TEST_int_eq(BN_bn2bin(n, reference), bytes))
             goto err;
         /* Empty buffer should fail. */
-        if (!TEST_int_eq(BN_bn2bin_padded(NULL, 0, n)), 0)
+        if (!TEST_int_eq(BN_bn2binpad(n, NULL, 0), -1))
             goto err;
         /* One byte short should fail. */
-        if (BN_bn2bin_padded(out, bytes - 1, n))
+        if (!TEST_int_eq(BN_bn2binpad(n, out, bytes - 1), -1))
             goto err;
         /* Exactly right size should encode. */
-        if (!TEST_true(BN_bn2bin_padded(out, bytes, n))
-                || TEST_mem_eq(out, bytes, reference, bytes))
+        if (!TEST_int_eq(BN_bn2binpad(n, out, bytes), bytes)
+                || !TEST_mem_eq(out, bytes, reference, bytes))
             goto err;
         /* Pad up one byte extra. */
-        if (!TEST_true(BN_bn2bin_padded(out, bytes + 1, n))
+        if (!TEST_int_eq(BN_bn2binpad(n, out, bytes + 1), bytes + 1)
                 || !TEST_mem_eq(out + 1, bytes, reference, bytes)
                 || !TEST_mem_eq(out, 1, zeros, 1))
             goto err;
         /* Pad up to 256. */
-        if (!TEST_true(BN_bn2bin_padded(out, sizeof(out)), n)
+        if (!TEST_int_eq(BN_bn2binpad(n, out, sizeof(out)), sizeof(out))
                 || !TEST_mem_eq(out + sizeof(out) - bytes, bytes,
                                 reference, bytes)
-                || !TEST_mem_eq(out, sizseof(out) - bytes,
+                || !TEST_mem_eq(out, sizeof(out) - bytes,
                                 zeros, sizeof(out) - bytes))
             goto err;
     }
@@ -1714,9 +1829,6 @@
  err:
     BN_free(n);
     return st;
-#else
-    return ctx != NULL;
-#endif
 }
 
 static int test_dec2bn(void)
@@ -2759,6 +2871,8 @@
     if (n == 0) {
         ADD_TEST(test_sub);
         ADD_TEST(test_div_recip);
+        ADD_ALL_TESTS(test_signed_mod_replace_ab, OSSL_NELEM(signed_mod_tests));
+        ADD_ALL_TESTS(test_signed_mod_replace_ba, OSSL_NELEM(signed_mod_tests));
         ADD_TEST(test_mod);
         ADD_TEST(test_modexp_mont5);
         ADD_TEST(test_kronecker);
diff -Nru openssl-1.1.1k/test/build.info openssl-1.1.1m/test/build.info
--- openssl-1.1.1k/test/build.info	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/build.info	2021-12-14 16:45:01.000000000 +0100
@@ -515,9 +515,11 @@
     INCLUDE[sm4_internal_test]=.. ../include
     DEPEND[sm4_internal_test]=../libcrypto.a libtestutil.a
 
-    SOURCE[ec_internal_test]=ec_internal_test.c
+    SOURCE[ec_internal_test]=ec_internal_test.c \
+                             {- rebase_files("../apps",
+                                  split(/\s+/, $target{apps_init_src})) -}
     INCLUDE[ec_internal_test]=../include ../crypto/ec
-    DEPEND[ec_internal_test]=../libcrypto.a libtestutil.a
+    DEPEND[ec_internal_test]=../apps/libapps.a ../libcrypto.a libtestutil.a
 
     SOURCE[curve448_internal_test]=curve448_internal_test.c
     INCLUDE[curve448_internal_test]=.. ../include ../crypto/ec/curve448
diff -Nru openssl-1.1.1k/test/certs/cross-key.pem openssl-1.1.1m/test/certs/cross-key.pem
--- openssl-1.1.1k/test/certs/cross-key.pem	1970-01-01 01:00:00.000000000 +0100
+++ openssl-1.1.1m/test/certs/cross-key.pem	2021-12-14 16:45:01.000000000 +0100
@@ -0,0 +1,28 @@
+-----BEGIN PRIVATE KEY-----
+MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCSkfwkYXTJFL4I
+ICRQFXji6eX9I1NI97GBu2Yk8ejwctMttcJTlBLYpYRFQnZgsLwVEhA25KKlSNPz
+PPrEVipT5Ll5J6uhWEBGLHETh8Qx4sI508B2zUP+2tnDapYtk5MNSVdQZXVt6wJu
+sXY8vd58nHPLo4zr61MTwrj3Ld0lU18YHtxnGSMMYPPTxecE0mjYU038ELxZMdlT
++VSC0KOBJddj64+kXRdiDtQGVWE58MtX5/18LgSY3J/hvNhmcWuY611pgXcmwDPr
+Sn1fDeRqG87Qs8KniS1dtWHDCVW/5KZOQeLcK6VTaEdnwdPYQ7BiJp4+3ypKmErd
+T9TYBs8XAgMBAAECggEABIxdeGpm8DjGRgSQLjLg88CNPWG89sBrQk0SbvQ1HJfq
+dJXRDxgMFtBsFTfX6kla3xfyHpQ/dY4qJZvmQNBXIQ/oiqumw9Ah153qlGJJmXdG
+PEQDEz7+2lExawwmjgk6Uvs58LMHmCNUibUdzHgsdZcwudq8R6FWZ8lvIIo6GOJg
+1gOoPbeAQtNAx8LPr+eDvpXoWJrCKJKuZCSRLV2CDmEH/+KH123cD4Lg+MsPNBJd
+DsOitnVczlqnKDf5gSUXy3cwQlKFtOBa/0pN9wZvZDEWa30RmJmXI2bLo/h6GxGB
+JXK57mTJG3UboWFIgNBU9IudPOdzDfJE1ul/Jon/AQKBgQC7/mmZg31a/8zlPLji
+oWoEEutyNu0O28BCbBrw9t1SqtPFLm53AzIzB4RFVjn9i5dnxljh618KQiY4FbKM
+mz1Yuzf7zCV7n8c1NakGwmW9Ezl8ZoLE44Nu7Pccukorl6uEY7kZa2vGa7krmIcI
+6kFbvVbl4scbXlDL88hGHezhoQKBgQDHl3O8kOvOhIwfVH6qIjIO+0oR57Tqtwaw
+A3oq6Ppdp65GK9G4f+/5L0z/Ay69MyauBLRA6+9LlW6SmAACSK69juvPMK6gd5uS
+yWQ8imh6l304BAryjOHiNXHtpnmiaPAGNgFZKPsPbWlOo4ZexTEBq23i4JM1TUph
+xpCmGY1ltwKBgEuYyPo0iAo55zkfq/Fmm2079nYdZEKfV7beJg9UFjgR/crDGyS8
+okkm8qe3PuaYZbATcNaYgcVsSFYxU3V7T7YIw0B8HW6TF9Zr16aiMatQucMurdNi
+8g1/OPfSadURzqUUPPDd458M3o+LbHHHUbUEdJdJFGwLB06cn6KikglBAoGAMz8M
+xV7EXOsleynbt9090yDsPLqsdhN2UR0jcf8NwZw7H+NCXsfimq1tbJCpoISQqt+k
+VIL/lv2QPW1vmyaET0FyBGmwfJ0ZQdAZv32eI9Pfn9FR6kMIAGfOj8FNu8iL0Fxv
+bjAafjSOdFWCO7UPxyj39ufIhEgLEB3GqA8pgfMCgYEAn/1Ov1Lu4MWq+72LygqG
+78rxk6rIGGET64grG1CSjkylQ9mo14jG6O1lM4fwTjlbGQrKGtzQtL785dW+t5uH
+zC2lDRDp8of+ErC31e+N4YDMdUHWeRBgHDYgsx4EgI0jNb02/UlziL1eARBpnfz6
+tw1erVdMmlA3LRBR5Mj+xso=
+-----END PRIVATE KEY-----
diff -Nru openssl-1.1.1k/test/certs/cross-root.pem openssl-1.1.1m/test/certs/cross-root.pem
--- openssl-1.1.1k/test/certs/cross-root.pem	1970-01-01 01:00:00.000000000 +0100
+++ openssl-1.1.1m/test/certs/cross-root.pem	2021-12-14 16:45:01.000000000 +0100
@@ -0,0 +1,18 @@
+-----BEGIN CERTIFICATE-----
+MIIC+jCCAeKgAwIBAgIBATANBgkqhkiG9w0BAQsFADAVMRMwEQYDVQQDDApDcm9z
+cyBSb290MCAXDTIxMDgzMDE4MzMyNloYDzIxMjEwODMxMTgzMzI2WjAVMRMwEQYD
+VQQDDApDcm9zcyBSb290MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
+kpH8JGF0yRS+CCAkUBV44unl/SNTSPexgbtmJPHo8HLTLbXCU5QS2KWERUJ2YLC8
+FRIQNuSipUjT8zz6xFYqU+S5eSeroVhARixxE4fEMeLCOdPAds1D/trZw2qWLZOT
+DUlXUGV1besCbrF2PL3efJxzy6OM6+tTE8K49y3dJVNfGB7cZxkjDGDz08XnBNJo
+2FNN/BC8WTHZU/lUgtCjgSXXY+uPpF0XYg7UBlVhOfDLV+f9fC4EmNyf4bzYZnFr
+mOtdaYF3JsAz60p9Xw3kahvO0LPCp4ktXbVhwwlVv+SmTkHi3CulU2hHZ8HT2EOw
+YiaePt8qSphK3U/U2AbPFwIDAQABo1MwUTAdBgNVHQ4EFgQUL16/ihJvr2w9I5k6
+3jjZ13SPW20wHwYDVR0jBBgwFoAUL16/ihJvr2w9I5k63jjZ13SPW20wDwYDVR0T
+AQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAUiqf8oQaPX3aW6I+dcRhsq5g
+bpYF0X5jePk6UqWu86YcmpoRtGLH7e5aHGJYqrVrkOoo0q4eTL3Pm1/sB3omPRMb
+ey/i7Z70wwd5yI8iz/WBmQDahYxq5wSDsUSdZDL0kSyoU2jCwXUPtuC6F1kMZBFI
+uUeaFcF8oKVGuOHvZgj/FMBpT7tyjdPpDG4uo6AT04AKGhf5xO5UY2N+uqmEsXHK
+HsKAEMrVhdeU5mbrfifvSkMYcYgJOX1KFP+t4U+ogqCHy1/Nfhq+WG1XN5GwhtuO
+ze25NqI6ZvA2og4AoeIzvJ/+Nfl5PNtClm0IjbGvR77oOBMs71lO4GjUYj9eiw==
+-----END CERTIFICATE-----
diff -Nru openssl-1.1.1k/test/certs/ee-self-signed.pem openssl-1.1.1m/test/certs/ee-self-signed.pem
--- openssl-1.1.1k/test/certs/ee-self-signed.pem	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/certs/ee-self-signed.pem	2021-12-14 16:45:01.000000000 +0100
@@ -1,19 +1,18 @@
 -----BEGIN CERTIFICATE-----
-MIIDIjCCAgqgAwIBAgIUT99h/YrAdcDg3fdLy5UajB8e994wDQYJKoZIhvcNAQEL
-BQAwGTEXMBUGA1UEAwwOZWUtc2VsZi1zaWduZWQwIBcNMjAwNzI4MTQxNjA4WhgP
-MjEyMDA3MDQxNDE2MDhaMBkxFzAVBgNVBAMMDmVlLXNlbGYtc2lnbmVkMIIBIjAN
-BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqP+JWGGFrt7bLA/Vc/vit6gbenVg
-K9R9PHN2ta7eky9/JJBtyRz0ijjNn6KAFlbLtCy7k+UXH/8NxkP+MTT4KNh16aO7
-iILvo3LiU2IFRU3gMZfvqp0Q0lgNngaeMrsbCFZdZQ8/Zo7CNqAR/8BZNf1JHN0c
-QjMGeK4EOCPl53Vn05StWqlAH6xZEPUMwWStSsTGNVOzlmqCGxWL0Zmr5J5vlKrS
-luVX+4yRZIo8JBbG0hm+gmATO2Kw7T4ds8r5a98xuXqeS0dopynHP0riIie075Bj
-1+/Qckk+W625G9Qrb4Zo3dVzErhDydxBD6KjRk+LZ4iED2H+eTQfSokftwIDAQAB
-o2AwXjAdBgNVHQ4EFgQU55viKq2KbDrLdlHljgeYIpfhc6IwHwYDVR0jBBgwFoAU
-55viKq2KbDrLdlHljgeYIpfhc6IwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMC
-B4AwDQYJKoZIhvcNAQELBQADggEBAGDEbS5kJArjjQNK02oxhQyz1dbDy23evRxm
-WW/NtlJAQAgEMXoNo9fioj0L4cvDy40r87V6/RsV2eijwZEfwGloACif7v78w8QO
-h4XiW9oGxcQkdMIYZLDVW9AZPDIkK5NHNfQaeAxCprAufYnRMv035UotLzCBRrkG
-G2TIs45vRp/6mYFVtm0Nf9CFvu4dXH8W+GlBONG0FAiBW+JzgTr9OmrzfqJTEDrf
-vv/hOiu8XvvlF5piPBqKE76rEvkXUSjgDZ2/Ju1fjqpV2I8Hz1Mj9w9tRE8g4E9o
-ZcRXX3MNPaHxnNhgYSPdpywwkyILz2AHwmAzh07cdttRFFPw+fM=
+MIICzzCCAbegAwIBAgIUBP7iEKPlKuinZGQNFxSY3IBIb0swDQYJKoZIhvcNAQEL
+BQAwGTEXMBUGA1UEAwwOZWUtc2VsZi1zaWduZWQwHhcNMjAwNjI4MTA1MTQ1WhcN
+MjAwNzI4MTA1MTQ1WjAZMRcwFQYDVQQDDA5lZS1zZWxmLXNpZ25lZDCCASIwDQYJ
+KoZIhvcNAQEBBQADggEPADCCAQoCggEBAKj/iVhhha7e2ywP1XP74reoG3p1YCvU
+fTxzdrWu3pMvfySQbckc9Io4zZ+igBZWy7Qsu5PlFx//DcZD/jE0+CjYdemju4iC
+76Ny4lNiBUVN4DGX76qdENJYDZ4GnjK7GwhWXWUPP2aOwjagEf/AWTX9SRzdHEIz
+BniuBDgj5ed1Z9OUrVqpQB+sWRD1DMFkrUrExjVTs5ZqghsVi9GZq+Seb5Sq0pbl
+V/uMkWSKPCQWxtIZvoJgEztisO0+HbPK+WvfMbl6nktHaKcpxz9K4iIntO+QY9fv
+0HJJPlutuRvUK2+GaN3VcxK4Q8ncQQ+io0ZPi2eIhA9h/nk0H0qJH7cCAwEAAaMP
+MA0wCwYDVR0PBAQDAgeAMA0GCSqGSIb3DQEBCwUAA4IBAQBiLmIUCGb+hmRGbmpO
+lDqEwiRVdxHBs4OSb3IA9QgU1QKUDRqn7q27RRelmzTXllubZZcX3K6o+dunRW5G
+d3f3FVr+3Z7wnmkQtC2y3NWtGuWNczss+6rMLzKvla5CjRiNPlSvluMNpcs7BJxI
+ppk1LxlaiYlQkDW32OPyxzXWDNv1ZkphcOcoCkHAagnq9x1SszvLTjAlo5XpYrm5
+CPgBOEnVwFCgne5Ab4QPTgkxPh/Ta508I/FKaPLJqci1EfGKipZkS7mMGTUJEeVK
+wZrn4z7RiTfJ4PdqO5iv8eOpt03fqdPEXQWe8DrKyfGM6/e369FaXMFhcd2ZxZy2
+WHoc
 -----END CERTIFICATE-----
diff -Nru openssl-1.1.1k/test/certs/root-cross-cert.pem openssl-1.1.1m/test/certs/root-cross-cert.pem
--- openssl-1.1.1k/test/certs/root-cross-cert.pem	1970-01-01 01:00:00.000000000 +0100
+++ openssl-1.1.1m/test/certs/root-cross-cert.pem	2021-12-14 16:45:01.000000000 +0100
@@ -0,0 +1,18 @@
+-----BEGIN CERTIFICATE-----
+MIIC9zCCAd+gAwIBAgIBAjANBgkqhkiG9w0BAQsFADAVMRMwEQYDVQQDDApDcm9z
+cyBSb290MCAXDTIxMDgzMDE4MzYzOFoYDzIxMjEwODMxMTgzNjM4WjASMRAwDgYD
+VQQDDAdSb290IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4eYA
+9Qa8oEY4eQ8/HnEZE20C3yubdmv8rLAh7daRCEI7pWM17FJboKJKxdYAlAOXWj25
+ZyjSfeMhXKTtxjyNjoTRnVTDPdl0opZ2Z3H5xhpQd7P9eO5b4OOMiSPCmiLsPtQ3
+ngfNwCtVERc6NEIcaQ06GLDtFZRexv2eh8Yc55QaksBfBcFzQ+UD3gmRySTO2I6L
+fi7gMUjRhipqVSZ66As2Tpex4KTJ2lxpSwOACFaDox+yKrjBTP7FsU3UwAGq7b7O
+Jb3uaa32B81uK6GJVPVo65gJ7clgZsszYkoDsGjWDqtfwTVVfv1G7rrr3Laio+2F
+f3fftWgiQ35mJCOvxQIDAQABo1MwUTAdBgNVHQ4EFgQUjvUlrx6ba4Q9fICayVOc
+TXL3o1IwHwYDVR0jBBgwFoAUL16/ihJvr2w9I5k63jjZ13SPW20wDwYDVR0TAQH/
+BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAHi+qdZF/jJrR/F3L60JVLOOUhTpi
+LxFFBksZPVaiVf+6R8pSMy0WtDEkzGT430ji6V4i8O/70HXIG9n9pCye8sLsOl6D
+exXj/MkwwSd3J0Y58zd8ZwMrK9m/jyFrk9TlWokfIFL/eC8VFsu7qmSSRLIjMuxc
+YPPisgR5+WPcus7Jf8auqcYw8eW0GPc1ugJobwucs5e/TinksMfwQrzEydmOPoWI
+Pfur7MjPr5IQXROtQv+CihMigPIHvi73YzSe5zdPCw8JcuZ5vBi2pwquvzvGLtMM
+Btln/SwonyQMks5WV4dOk6NOB73mCMywCir4ybp9ElJMaUGEF9nLO+h8Fg==
+-----END CERTIFICATE-----
diff -Nru openssl-1.1.1k/test/certs/setup.sh openssl-1.1.1m/test/certs/setup.sh
--- openssl-1.1.1k/test/certs/setup.sh	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/certs/setup.sh	2021-12-14 16:45:01.000000000 +0100
@@ -9,6 +9,8 @@
 ./mkcert.sh genss "Root CA" root-key root-nonca
 ./mkcert.sh genroot "Root CA" root-key2 root-cert2
 ./mkcert.sh genroot "Root Cert 2" root-key root-name2
+./mkcert.sh genroot "Cross Root" cross-key cross-root
+./mkcert.sh genca "Root CA" root-key root-cross-cert cross-key cross-root
 #
 openssl x509 -in root-cert.pem -trustout \
     -addtrust serverAuth -out root+serverAuth.pem
diff -Nru openssl-1.1.1k/test/clienthellotest.c openssl-1.1.1m/test/clienthellotest.c
--- openssl-1.1.1k/test/clienthellotest.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/clienthellotest.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2015-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -45,10 +45,16 @@
 
 static const char *sessionfile = NULL;
 /* Dummy ALPN protocols used to pad out the size of the ClientHello */
+/* ASCII 'O' = 79 = 0x4F = EBCDIC '|'*/
+#ifdef CHARSET_EBCDIC
 static const char alpn_prots[] =
-    "0123456789012345678901234567890123456789012345678901234567890123456789"
-    "0123456789012345678901234567890123456789012345678901234567890123456789"
-    "01234567890123456789";
+    "|1234567890123456789012345678901234567890123456789012345678901234567890123456789"
+    "|1234567890123456789012345678901234567890123456789012345678901234567890123456789";
+#else
+static const char alpn_prots[] =
+    "O1234567890123456789012345678901234567890123456789012345678901234567890123456789"
+    "O1234567890123456789012345678901234567890123456789012345678901234567890123456789";
+#endif
 
 static int test_client_hello(int currtest)
 {
diff -Nru openssl-1.1.1k/test/dane-cross.in openssl-1.1.1m/test/dane-cross.in
--- openssl-1.1.1k/test/dane-cross.in	1970-01-01 01:00:00.000000000 +0100
+++ openssl-1.1.1m/test/dane-cross.in	2021-12-14 16:45:01.000000000 +0100
@@ -0,0 +1,113 @@
+# Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+#
+# Licensed under the OpenSSL license (the "License").  You may not use
+# this file except in compliance with the License.  You can obtain a copy
+# in the file LICENSE in the source distribution or at
+# https://www.openssl.org/source/license.html
+#
+# Blank and comment lines ignored.
+#
+# The first line in each block takes the form:
+#
+#       <TLSA-count> <cert-count> <nonamechecks> <desired-verify-result> <desired-match-depth>
+#
+# It is followed by <TLSA-count> lines of the form:
+#
+#       <usage> <selector> <mtype> <hex-data>
+#
+# and finally, by <cert-count> certificates.
+
+# 1
+# Ensure TLSA with direct root works when peer chain provides a
+# cross-cert.
+1 4 0 0 2
+2 0 0 308202f1308201d9a003020102020101300d06092a864886f70d01010b050030123110300e06035504030c07526f6f742043413020170d3136303131353038313934395a180f32313136303131363038313934395a30123110300e06035504030c07526f6f7420434130820122300d06092a864886f70d01010105000382010f003082010a0282010100e1e600f506bca04638790f3f1e7119136d02df2b9b766bfcacb021edd69108423ba56335ec525ba0a24ac5d6009403975a3db96728d27de3215ca4edc63c8d8e84d19d54c33dd974a296766771f9c61a5077b3fd78ee5be0e38c8923c29a22ec3ed4379e07cdc02b5511173a34421c690d3a18b0ed15945ec6fd9e87c61ce7941a92c05f05c17343e503de0991c924ced88e8b7e2ee03148d1862a6a55267ae80b364e97b1e0a4c9da5c694b0380085683a31fb22ab8c14cfec5b14dd4c001aaedbece25bdee69adf607cd6e2ba18954f568eb9809edc96066cb33624a03b068d60eab5fc135557efd46eebaebdcb6a2a3ed857f77dfb56822437e662423afc50203010001a350304e301d0603551d0e041604148ef525af1e9b6b843d7c809ac9539c4d72f7a352301f0603551d230418301680148ef525af1e9b6b843d7c809ac9539c4d72f7a352300c0603551d13040530030101ff300d06092a864886f70d01010b05000382010100c91449c76ed660ea203d76693df00cb7ca6d6a9affba02d618b9706f32b24a8c8ba68576fd8340bd300607dd2216aeb1fee8e3acae35fc44b4a77bf7f3f41fbb1a36e2071981cfe860b57652a47eb860b1ebca763962d872d06c011b5858e1203e11c56fd695c5c3902b2647b62bc35f4c0b197fa7a99a075fd21899cd2c6e944144ccf146c0a16f30f9adef6467936b8248c0e8327b8d88761a2b4e33aa085370ddf7ea64ddb084905520472f6a37f93e0327aa1f541c6f92d4f8c4e6970f1b9b2ce630e05981d7a0b4ee07b2170130ed39e0a481dd649f04f0ce6c4859d2f9bf970eb74c68bcf3220cb65926714da0d112a979023de86e907aa1f2285de9f0
+subject=CN = server.example
+issuer=CN = CA
+notBefore=Jan 15 08:19:49 2016 GMT
+notAfter=Jan 16 08:19:49 2116 GMT
+-----BEGIN CERTIFICATE-----
+MIIDIDCCAgigAwIBAgIBAjANBgkqhkiG9w0BAQsFADANMQswCQYDVQQDDAJDQTAg
+Fw0xNjAxMTUwODE5NDlaGA8yMTE2MDExNjA4MTk0OVowGTEXMBUGA1UEAwwOc2Vy
+dmVyLmV4YW1wbGUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCo/4lY
+YYWu3tssD9Vz++K3qBt6dWAr1H08c3a1rt6TL38kkG3JHPSKOM2fooAWVsu0LLuT
+5Rcf/w3GQ/4xNPgo2HXpo7uIgu+jcuJTYgVFTeAxl++qnRDSWA2eBp4yuxsIVl1l
+Dz9mjsI2oBH/wFk1/Ukc3RxCMwZ4rgQ4I+XndWfTlK1aqUAfrFkQ9QzBZK1KxMY1
+U7OWaoIbFYvRmavknm+UqtKW5Vf7jJFkijwkFsbSGb6CYBM7YrDtPh2zyvlr3zG5
+ep5LR2inKcc/SuIiJ7TvkGPX79ByST5brbkb1Ctvhmjd1XMSuEPJ3EEPoqNGT4tn
+iIQPYf55NB9KiR+3AgMBAAGjfTB7MB0GA1UdDgQWBBTnm+IqrYpsOst2UeWOB5gi
+l+FzojAfBgNVHSMEGDAWgBS0ETPx1+Je91OeICIQT4YGvx/JXjAJBgNVHRMEAjAA
+MBMGA1UdJQQMMAoGCCsGAQUFBwMBMBkGA1UdEQQSMBCCDnNlcnZlci5leGFtcGxl
+MA0GCSqGSIb3DQEBCwUAA4IBAQBBtDxPYULl5b7VFC7/U0NgV8vTJk4zpPnUMMQ4
+QF2AWDFAek8oLKrz18KQ8M/DEhDxgkaoeXEMLT6BJUEVNYuFEYHEDGarl0nMDRXL
+xOgAExfz3Tf/pjsLaha5aWH7NyCSKWC+lYkIOJ/Kb/m/6QsDJoXsEC8AhrPfqJhz
+UzsCoxIlaDWqawH4+S8bdeX0tvs2VtJk/WOJHxMqXra6kgI4fAgyvr2kIZHinQ3y
+cgX40uAC38bwpE95kJ7FhSfQlE1Rt7sOspUj098Dd0RNDn2uKyOTxEqIELHfw4AX
+O3XAzt8qDyho8nEd/xiQ6qgsQnvXa+hSRJw42g3/czVskxRx
+-----END CERTIFICATE-----
+subject=CN = CA
+issuer=CN = Root CA
+notBefore=Jan 15 08:19:49 2016 GMT
+notAfter=Jan 16 08:19:49 2116 GMT
+-----BEGIN CERTIFICATE-----
+MIIC7DCCAdSgAwIBAgIBAjANBgkqhkiG9w0BAQsFADASMRAwDgYDVQQDDAdSb290
+IENBMCAXDTE2MDExNTA4MTk0OVoYDzIxMTYwMTE2MDgxOTQ5WjANMQswCQYDVQQD
+DAJDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJadpD0ASxxfxsvd
+j9IxsogVzMSGLFziaYuE9KejU9+R479RifvwfBANO62sNWJ19X//9G5UjwWmkiOz
+n1k50DkYsBBA3mJzik6wjt/c58lBIlSEgAgpvDU8ht8w3t20JP9+YqXAeugqFj/W
+l9rFQtsvaWSRywjXVlp5fxuEQelNnXcJEKhsKTNExsBUZebo4/J1BWpklWzA9P0l
+YW5INvDAAwcF1nzlEf0Y6Eot03IMNyg2MTE4hehxjdgCSci8GYnFirE/ojXqqpAc
+ZGh7r2dqWgZUD1Dh+bT2vjrUzj8eTH3GdzI+oljt29102JIUaqj3yzRYkah8FLF9
+CLNNsUcCAwEAAaNQME4wHQYDVR0OBBYEFLQRM/HX4l73U54gIhBPhga/H8leMB8G
+A1UdIwQYMBaAFI71Ja8em2uEPXyAmslTnE1y96NSMAwGA1UdEwQFMAMBAf8wDQYJ
+KoZIhvcNAQELBQADggEBADnZ9uXGAdwfNC3xuERIlBwgLROeBRGgcfHWdXZB/tWk
+IM9ox88wYKWynanPbra4n0zhepooKt+naeY2HLR8UgwT6sTi0Yfld9mjytA8/DP6
+AcqtIDDf60vNI00sgxjgZqofVayA9KShzIPzjBec4zI1sg5YzoSNyH28VXFstEpi
+8CVtmRYQHhc2gDI9MGge4sHRYwaIFkegzpwcEUnp6tTVe9ZvHawgsXF/rCGfH4M6
+uNO0D+9Md1bdW7382yOtWbkyibsugqnfBYCUH6hAhDlfYzpba2Smb0roc6Crq7HR
+5HpEYY6qEir9wFMkD5MZsWrNRGRuzd5am82J+aaHz/4=
+-----END CERTIFICATE-----
+subject=CN = Root CA
+issuer=CN = Cross Root
+notBefore=Aug 30 18:36:38 2021 GMT
+notAfter=Aug 31 18:36:38 2121 GMT
+-----BEGIN CERTIFICATE-----
+MIIC9zCCAd+gAwIBAgIBAjANBgkqhkiG9w0BAQsFADAVMRMwEQYDVQQDDApDcm9z
+cyBSb290MCAXDTIxMDgzMDE4MzYzOFoYDzIxMjEwODMxMTgzNjM4WjASMRAwDgYD
+VQQDDAdSb290IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4eYA
+9Qa8oEY4eQ8/HnEZE20C3yubdmv8rLAh7daRCEI7pWM17FJboKJKxdYAlAOXWj25
+ZyjSfeMhXKTtxjyNjoTRnVTDPdl0opZ2Z3H5xhpQd7P9eO5b4OOMiSPCmiLsPtQ3
+ngfNwCtVERc6NEIcaQ06GLDtFZRexv2eh8Yc55QaksBfBcFzQ+UD3gmRySTO2I6L
+fi7gMUjRhipqVSZ66As2Tpex4KTJ2lxpSwOACFaDox+yKrjBTP7FsU3UwAGq7b7O
+Jb3uaa32B81uK6GJVPVo65gJ7clgZsszYkoDsGjWDqtfwTVVfv1G7rrr3Laio+2F
+f3fftWgiQ35mJCOvxQIDAQABo1MwUTAdBgNVHQ4EFgQUjvUlrx6ba4Q9fICayVOc
+TXL3o1IwHwYDVR0jBBgwFoAUL16/ihJvr2w9I5k63jjZ13SPW20wDwYDVR0TAQH/
+BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAHi+qdZF/jJrR/F3L60JVLOOUhTpi
+LxFFBksZPVaiVf+6R8pSMy0WtDEkzGT430ji6V4i8O/70HXIG9n9pCye8sLsOl6D
+exXj/MkwwSd3J0Y58zd8ZwMrK9m/jyFrk9TlWokfIFL/eC8VFsu7qmSSRLIjMuxc
+YPPisgR5+WPcus7Jf8auqcYw8eW0GPc1ugJobwucs5e/TinksMfwQrzEydmOPoWI
+Pfur7MjPr5IQXROtQv+CihMigPIHvi73YzSe5zdPCw8JcuZ5vBi2pwquvzvGLtMM
+Btln/SwonyQMks5WV4dOk6NOB73mCMywCir4ybp9ElJMaUGEF9nLO+h8Fg==
+-----END CERTIFICATE-----
+subject=CN = Cross Root
+issuer=CN = Cross Root
+notBefore=Aug 30 18:33:26 2021 GMT
+notAfter=Aug 31 18:33:26 2121 GMT
+-----BEGIN CERTIFICATE-----
+MIIC+jCCAeKgAwIBAgIBATANBgkqhkiG9w0BAQsFADAVMRMwEQYDVQQDDApDcm9z
+cyBSb290MCAXDTIxMDgzMDE4MzMyNloYDzIxMjEwODMxMTgzMzI2WjAVMRMwEQYD
+VQQDDApDcm9zcyBSb290MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
+kpH8JGF0yRS+CCAkUBV44unl/SNTSPexgbtmJPHo8HLTLbXCU5QS2KWERUJ2YLC8
+FRIQNuSipUjT8zz6xFYqU+S5eSeroVhARixxE4fEMeLCOdPAds1D/trZw2qWLZOT
+DUlXUGV1besCbrF2PL3efJxzy6OM6+tTE8K49y3dJVNfGB7cZxkjDGDz08XnBNJo
+2FNN/BC8WTHZU/lUgtCjgSXXY+uPpF0XYg7UBlVhOfDLV+f9fC4EmNyf4bzYZnFr
+mOtdaYF3JsAz60p9Xw3kahvO0LPCp4ktXbVhwwlVv+SmTkHi3CulU2hHZ8HT2EOw
+YiaePt8qSphK3U/U2AbPFwIDAQABo1MwUTAdBgNVHQ4EFgQUL16/ihJvr2w9I5k6
+3jjZ13SPW20wHwYDVR0jBBgwFoAUL16/ihJvr2w9I5k63jjZ13SPW20wDwYDVR0T
+AQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAUiqf8oQaPX3aW6I+dcRhsq5g
+bpYF0X5jePk6UqWu86YcmpoRtGLH7e5aHGJYqrVrkOoo0q4eTL3Pm1/sB3omPRMb
+ey/i7Z70wwd5yI8iz/WBmQDahYxq5wSDsUSdZDL0kSyoU2jCwXUPtuC6F1kMZBFI
+uUeaFcF8oKVGuOHvZgj/FMBpT7tyjdPpDG4uo6AT04AKGhf5xO5UY2N+uqmEsXHK
+HsKAEMrVhdeU5mbrfifvSkMYcYgJOX1KFP+t4U+ogqCHy1/Nfhq+WG1XN5GwhtuO
+ze25NqI6ZvA2og4AoeIzvJ/+Nfl5PNtClm0IjbGvR77oOBMs71lO4GjUYj9eiw==
+-----END CERTIFICATE-----
diff -Nru openssl-1.1.1k/test/danetest.c openssl-1.1.1m/test/danetest.c
--- openssl-1.1.1k/test/danetest.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/danetest.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2015-2017 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -152,7 +152,7 @@
 
 static char *read_to_eol(BIO *f)
 {
-    static char buf[1024];
+    static char buf[4096];
     int n;
 
     if (!BIO_gets(f, buf, sizeof(buf)))
diff -Nru openssl-1.1.1k/test/data.bin openssl-1.1.1m/test/data.bin
--- openssl-1.1.1k/test/data.bin	1970-01-01 01:00:00.000000000 +0100
+++ openssl-1.1.1m/test/data.bin	2021-12-14 16:45:01.000000000 +0100
@@ -0,0 +1,4 @@
+TEST DATA
+
+Please note that if a test involves a new testing executable,
+you will need to do some additions in test/build.info.
diff -Nru openssl-1.1.1k/test/ec_internal_test.c openssl-1.1.1m/test/ec_internal_test.c
--- openssl-1.1.1k/test/ec_internal_test.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/ec_internal_test.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2019-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the Apache License 2.0 (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -283,6 +283,47 @@
     return testresult;
 }
 
+static
+int ecpkparams_i2d2i_test(int n)
+{
+    EC_GROUP *g1 = NULL, *g2 = NULL;
+    FILE *fp = NULL;
+    int nid = curves[n].nid;
+    int testresult = 0;
+
+    /* create group */
+    if (!TEST_ptr(g1 = EC_GROUP_new_by_curve_name(nid)))
+        goto end;
+
+    /* encode params to file */
+    if (!TEST_ptr(fp = fopen("params.der", "wb"))
+            || !TEST_true(i2d_ECPKParameters_fp(fp, g1)))
+        goto end;
+
+    /* flush and close file */
+    if (!TEST_int_eq(fclose(fp), 0)) {
+        fp = NULL;
+        goto end;
+    }
+    fp = NULL;
+
+    /* decode params from file */
+    if (!TEST_ptr(fp = fopen("params.der", "rb"))
+            || !TEST_ptr(g2 = d2i_ECPKParameters_fp(fp, NULL)))
+        goto end;
+
+    testresult = 1; /* PASS */
+
+end:
+    if (fp != NULL)
+        fclose(fp);
+
+    EC_GROUP_free(g1);
+    EC_GROUP_free(g2);
+
+    return testresult;
+}
+
 int setup_tests(void)
 {
     crv_len = EC_get_builtin_curves(NULL, 0);
@@ -297,6 +338,8 @@
 #endif
     ADD_ALL_TESTS(field_tests_default, crv_len);
     ADD_TEST(decoded_flag_test);
+    ADD_ALL_TESTS(ecpkparams_i2d2i_test, crv_len);
+
     return 1;
 }
 
diff -Nru openssl-1.1.1k/test/ectest.c openssl-1.1.1m/test/ectest.c
--- openssl-1.1.1k/test/ectest.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/ectest.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved.
  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
@@ -1124,7 +1124,56 @@
     BN_free(yplusone);
     return r;
 }
-# endif
+
+static int hybrid_point_encoding_test(void)
+{
+    BIGNUM *x = NULL, *y = NULL;
+    EC_GROUP *group = NULL;
+    EC_POINT *point = NULL;
+    unsigned char *buf = NULL;
+    size_t len;
+    int r = 0;
+
+    if (!TEST_true(BN_dec2bn(&x, "0"))
+        || !TEST_true(BN_dec2bn(&y, "1"))
+        || !TEST_ptr(group = EC_GROUP_new_by_curve_name(NID_sect571k1))
+        || !TEST_ptr(point = EC_POINT_new(group))
+        || !TEST_true(EC_POINT_set_affine_coordinates(group, point, x, y, NULL))
+        || !TEST_size_t_ne(0, (len = EC_POINT_point2oct(group,
+                                                        point,
+                                                        POINT_CONVERSION_HYBRID,
+                                                        NULL,
+                                                        0,
+                                                        NULL)))
+        || !TEST_ptr(buf = OPENSSL_malloc(len))
+        || !TEST_size_t_eq(len, EC_POINT_point2oct(group,
+                                                   point,
+                                                   POINT_CONVERSION_HYBRID,
+                                                   buf,
+                                                   len,
+                                                   NULL)))
+        goto err;
+
+    r = 1;
+
+    /* buf contains a valid hybrid point, check that we can decode it. */
+    if (!TEST_true(EC_POINT_oct2point(group, point, buf, len, NULL)))
+        r = 0;
+
+    /* Flip the y_bit and verify that the invalid encoding is rejected. */
+    buf[0] ^= 1;
+    if (!TEST_false(EC_POINT_oct2point(group, point, buf, len, NULL)))
+        r = 0;
+
+err:
+    BN_free(x);
+    BN_free(y);
+    EC_GROUP_free(group);
+    EC_POINT_free(point);
+    OPENSSL_free(buf);
+    return r;
+}
+#endif
 
 static int internal_curve_test(int n)
 {
@@ -2195,6 +2244,7 @@
     ADD_ALL_TESTS(cardinality_test, crv_len);
     ADD_TEST(prime_field_tests);
 # ifndef OPENSSL_NO_EC2M
+    ADD_TEST(hybrid_point_encoding_test);
     ADD_TEST(char2_field_tests);
     ADD_ALL_TESTS(char2_curve_test, OSSL_NELEM(char2_curve_tests));
 # endif
diff -Nru openssl-1.1.1k/test/evp_extra_test.c openssl-1.1.1m/test/evp_extra_test.c
--- openssl-1.1.1k/test/evp_extra_test.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/evp_extra_test.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2015-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -10,6 +10,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <openssl/aes.h>
 #include <openssl/bio.h>
 #include <openssl/crypto.h>
 #include <openssl/err.h>
@@ -19,6 +20,7 @@
 #include <openssl/pem.h>
 #include <openssl/kdf.h>
 #include <openssl/dh.h>
+#include <openssl/engine.h>
 #include "testutil.h"
 #include "internal/nelem.h"
 #include "crypto/evp.h"
@@ -320,6 +322,96 @@
 };
 #endif
 
+static const unsigned char kCFBDefaultKey[] = {
+    0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88,
+    0x09, 0xCF, 0x4F, 0x3C
+};
+
+static const unsigned char kGCMDefaultKey[32] = { 0 };
+
+static const unsigned char kGCMResetKey[] = {
+    0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, 0x6d, 0x6a, 0x8f, 0x94,
+    0x67, 0x30, 0x83, 0x08, 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c,
+    0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08
+};
+
+static const unsigned char iCFBIV[] = {
+    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
+    0x0C, 0x0D, 0x0E, 0x0F
+};
+
+static const unsigned char iGCMDefaultIV[12] = { 0 };
+
+static const unsigned char iGCMResetIV1[] = {
+    0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad
+};
+
+static const unsigned char iGCMResetIV2[] = {
+    0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad, 0xde, 0xca, 0xf8, 0x88
+};
+
+static const unsigned char cfbPlaintext[] = {
+    0x6B, 0xC1, 0xBE, 0xE2, 0x2E, 0x40, 0x9F, 0x96, 0xE9, 0x3D, 0x7E, 0x11,
+    0x73, 0x93, 0x17, 0x2A
+};
+
+static const unsigned char gcmDefaultPlaintext[16] = { 0 };
+
+static const unsigned char gcmResetPlaintext[] = {
+    0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, 0xa5, 0x59, 0x09, 0xc5,
+    0xaf, 0xf5, 0x26, 0x9a, 0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda,
+    0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72, 0x1c, 0x3c, 0x0c, 0x95,
+    0x95, 0x68, 0x09, 0x53, 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25,
+    0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57, 0xba, 0x63, 0x7b, 0x39
+};
+
+static const unsigned char cfbCiphertext[] = {
+    0x3B, 0x3F, 0xD9, 0x2E, 0xB7, 0x2D, 0xAD, 0x20, 0x33, 0x34, 0x49, 0xF8,
+    0xE8, 0x3C, 0xFB, 0x4A
+};
+
+static const unsigned char gcmDefaultCiphertext[] = {
+    0xce, 0xa7, 0x40, 0x3d, 0x4d, 0x60, 0x6b, 0x6e, 0x07, 0x4e, 0xc5, 0xd3,
+    0xba, 0xf3, 0x9d, 0x18
+};
+
+static const unsigned char gcmResetCiphertext1[] = {
+    0xc3, 0x76, 0x2d, 0xf1, 0xca, 0x78, 0x7d, 0x32, 0xae, 0x47, 0xc1, 0x3b,
+    0xf1, 0x98, 0x44, 0xcb, 0xaf, 0x1a, 0xe1, 0x4d, 0x0b, 0x97, 0x6a, 0xfa,
+    0xc5, 0x2f, 0xf7, 0xd7, 0x9b, 0xba, 0x9d, 0xe0, 0xfe, 0xb5, 0x82, 0xd3,
+    0x39, 0x34, 0xa4, 0xf0, 0x95, 0x4c, 0xc2, 0x36, 0x3b, 0xc7, 0x3f, 0x78,
+    0x62, 0xac, 0x43, 0x0e, 0x64, 0xab, 0xe4, 0x99, 0xf4, 0x7c, 0x9b, 0x1f
+};
+
+static const unsigned char gcmResetCiphertext2[] = {
+    0x52, 0x2d, 0xc1, 0xf0, 0x99, 0x56, 0x7d, 0x07, 0xf4, 0x7f, 0x37, 0xa3,
+    0x2a, 0x84, 0x42, 0x7d, 0x64, 0x3a, 0x8c, 0xdc, 0xbf, 0xe5, 0xc0, 0xc9,
+    0x75, 0x98, 0xa2, 0xbd, 0x25, 0x55, 0xd1, 0xaa, 0x8c, 0xb0, 0x8e, 0x48,
+    0x59, 0x0d, 0xbb, 0x3d, 0xa7, 0xb0, 0x8b, 0x10, 0x56, 0x82, 0x88, 0x38,
+    0xc5, 0xf6, 0x1e, 0x63, 0x93, 0xba, 0x7a, 0x0a, 0xbc, 0xc9, 0xf6, 0x62
+};
+
+static const unsigned char gcmAAD[] = {
+    0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef, 0xfe, 0xed, 0xfa, 0xce,
+    0xde, 0xad, 0xbe, 0xef, 0xab, 0xad, 0xda, 0xd2
+};
+
+static const unsigned char gcmDefaultTag[] = {
+    0xd0, 0xd1, 0xc8, 0xa7, 0x99, 0x99, 0x6b, 0xf0, 0x26, 0x5b, 0x98, 0xb5,
+    0xd4, 0x8a, 0xb9, 0x19
+};
+
+static const unsigned char gcmResetTag1[] = {
+    0x3a, 0x33, 0x7d, 0xbf, 0x46, 0xa7, 0x92, 0xc4, 0x5e, 0x45, 0x49, 0x13,
+    0xfe, 0x2e, 0xa8, 0xf2
+};
+
+static const unsigned char gcmResetTag2[] = {
+    0x76, 0xfc, 0x6e, 0xce, 0x0f, 0x4e, 0x17, 0x68, 0xcd, 0xdf, 0x88, 0x53,
+    0xbb, 0x2d, 0x55, 0x1b
+};
+
+
 typedef struct APK_DATA_st {
     const unsigned char *kder;
     size_t size;
@@ -330,6 +422,494 @@
     int type; /* 0 for private, 1 for public, 2 for params */
 } APK_DATA;
 
+typedef struct {
+    const char *cipher;
+    const unsigned char *key;
+    const unsigned char *iv;
+    const unsigned char *input;
+    const unsigned char *expected;
+    const unsigned char *tag;
+    size_t ivlen; /* 0 if we do not need to set a specific IV len */
+    size_t inlen;
+    size_t expectedlen;
+    size_t taglen;
+    int keyfirst;
+    int initenc;
+    int finalenc;
+} EVP_INIT_TEST_st;
+
+static const EVP_INIT_TEST_st evp_init_tests[] = {
+    {
+        "aes-128-cfb", kCFBDefaultKey, iCFBIV, cfbPlaintext,
+        cfbCiphertext, NULL, 0, sizeof(cfbPlaintext), sizeof(cfbCiphertext),
+        0, 1, 0, 1
+    },
+    {
+        "aes-256-gcm", kGCMDefaultKey, iGCMDefaultIV, gcmDefaultPlaintext,
+        gcmDefaultCiphertext, gcmDefaultTag, sizeof(iGCMDefaultIV),
+        sizeof(gcmDefaultPlaintext), sizeof(gcmDefaultCiphertext),
+        sizeof(gcmDefaultTag), 1, 0, 1
+    },
+    {
+        "aes-128-cfb", kCFBDefaultKey, iCFBIV, cfbPlaintext,
+        cfbCiphertext, NULL, 0, sizeof(cfbPlaintext), sizeof(cfbCiphertext),
+        0, 0, 0, 1
+    },
+    {
+        "aes-256-gcm", kGCMDefaultKey, iGCMDefaultIV, gcmDefaultPlaintext,
+        gcmDefaultCiphertext, gcmDefaultTag, sizeof(iGCMDefaultIV),
+        sizeof(gcmDefaultPlaintext), sizeof(gcmDefaultCiphertext),
+        sizeof(gcmDefaultTag), 0, 0, 1
+    },
+    {
+        "aes-128-cfb", kCFBDefaultKey, iCFBIV, cfbCiphertext,
+        cfbPlaintext, NULL, 0, sizeof(cfbCiphertext), sizeof(cfbPlaintext),
+        0, 1, 1, 0
+    },
+    {
+        "aes-256-gcm", kGCMDefaultKey, iGCMDefaultIV, gcmDefaultCiphertext,
+        gcmDefaultPlaintext, gcmDefaultTag, sizeof(iGCMDefaultIV),
+        sizeof(gcmDefaultCiphertext), sizeof(gcmDefaultPlaintext),
+        sizeof(gcmDefaultTag), 1, 1, 0
+    },
+    {
+        "aes-128-cfb", kCFBDefaultKey, iCFBIV, cfbCiphertext,
+        cfbPlaintext, NULL, 0, sizeof(cfbCiphertext), sizeof(cfbPlaintext),
+        0, 0, 1, 0
+    },
+    {
+        "aes-256-gcm", kGCMDefaultKey, iGCMDefaultIV, gcmDefaultCiphertext,
+        gcmDefaultPlaintext, gcmDefaultTag, sizeof(iGCMDefaultIV),
+        sizeof(gcmDefaultCiphertext), sizeof(gcmDefaultPlaintext),
+        sizeof(gcmDefaultTag), 0, 1, 0
+    }
+};
+
+static int evp_init_seq_set_iv(EVP_CIPHER_CTX *ctx, const EVP_INIT_TEST_st *t)
+{
+    int res = 0;
+
+    if (t->ivlen != 0) {
+        if (!TEST_true(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, t->ivlen, NULL)))
+            goto err;
+    }
+    if (!TEST_true(EVP_CipherInit_ex(ctx, NULL, NULL, NULL, t->iv, -1)))
+        goto err;
+    res = 1;
+ err:
+    return res;
+}
+
+/*
+ * Test step-wise cipher initialization via EVP_CipherInit_ex where the
+ * arguments are given one at a time and a final adjustment to the enc
+ * parameter sets the correct operation.
+ */
+static int test_evp_init_seq(int idx)
+{
+    int outlen1, outlen2;
+    int testresult = 0;
+    unsigned char outbuf[1024];
+    unsigned char tag[16];
+    const EVP_INIT_TEST_st *t = &evp_init_tests[idx];
+    EVP_CIPHER_CTX *ctx = NULL;
+    const EVP_CIPHER *type = NULL;
+    size_t taglen = sizeof(tag);
+    char *errmsg = NULL;
+
+    ctx = EVP_CIPHER_CTX_new();
+    if (ctx == NULL) {
+        errmsg = "CTX_ALLOC";
+        goto err;
+    }
+    if (!TEST_ptr(type = EVP_get_cipherbyname(t->cipher))) {
+        errmsg = "GET_CIPHERBYNAME";
+        goto err;
+    }
+    if (!TEST_true(EVP_CipherInit_ex(ctx, type, NULL, NULL, NULL, t->initenc))) {
+        errmsg = "EMPTY_ENC_INIT";
+        goto err;
+    }
+    if (!TEST_true(EVP_CIPHER_CTX_set_padding(ctx, 0))) {
+        errmsg = "PADDING";
+        goto err;
+    }
+    if (t->keyfirst && !TEST_true(EVP_CipherInit_ex(ctx, NULL, NULL, t->key, NULL, -1))) {
+        errmsg = "KEY_INIT (before iv)";
+        goto err;
+    }
+    if (!evp_init_seq_set_iv(ctx, t)) {
+        errmsg = "IV_INIT";
+        goto err;
+    }
+    if (t->keyfirst == 0 &&  !TEST_true(EVP_CipherInit_ex(ctx, NULL, NULL, t->key, NULL, -1))) {
+        errmsg = "KEY_INIT (after iv)";
+        goto err;
+    }
+    if (!TEST_true(EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, t->finalenc))) {
+        errmsg = "FINAL_ENC_INIT";
+        goto err;
+    }
+    if (!TEST_true(EVP_CipherUpdate(ctx, outbuf, &outlen1, t->input, t->inlen))) {
+        errmsg = "CIPHER_UPDATE";
+        goto err;
+    }
+    if (t->finalenc == 0 && t->tag != NULL) {
+        /* Set expected tag */
+        if (!TEST_true(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
+                                           t->taglen, (void *)t->tag))) {
+            errmsg = "SET_TAG";
+            goto err;
+        }
+    }
+    if (!TEST_true(EVP_CipherFinal_ex(ctx, outbuf + outlen1, &outlen2))) {
+        errmsg = "CIPHER_FINAL";
+        goto err;
+    }
+    if (!TEST_mem_eq(t->expected, t->expectedlen, outbuf, outlen1 + outlen2)) {
+        errmsg = "WRONG_RESULT";
+        goto err;
+    }
+    if (t->finalenc != 0 && t->tag != NULL) {
+        if (!TEST_true(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag))) {
+            errmsg = "GET_TAG";
+            goto err;
+        }
+        if (!TEST_mem_eq(t->tag, t->taglen, tag, taglen)) {
+            errmsg = "TAG_ERROR";
+            goto err;
+        }
+    }
+    testresult = 1;
+ err:
+    if (errmsg != NULL)
+        TEST_info("evp_init_test %d: %s", idx, errmsg);
+    EVP_CIPHER_CTX_free(ctx);
+    return testresult;
+}
+
+typedef struct {
+    const unsigned char *input;
+    const unsigned char *expected;
+    size_t inlen;
+    size_t expectedlen;
+    int enc;
+} EVP_RESET_TEST_st;
+
+static const EVP_RESET_TEST_st evp_reset_tests[] = {
+    {
+        cfbPlaintext, cfbCiphertext,
+        sizeof(cfbPlaintext), sizeof(cfbCiphertext), 1
+    },
+    {
+        cfbCiphertext, cfbPlaintext,
+        sizeof(cfbCiphertext), sizeof(cfbPlaintext), 0
+    }
+};
+
+/*
+ * Test a reset of a cipher via EVP_CipherInit_ex after the cipher has already
+ * been used.
+ */
+static int test_evp_reset(int idx)
+{
+    const EVP_RESET_TEST_st *t = &evp_reset_tests[idx];
+    int outlen1, outlen2;
+    int testresult = 0;
+    unsigned char outbuf[1024];
+    EVP_CIPHER_CTX *ctx = NULL;
+    const EVP_CIPHER *type = NULL;
+    char *errmsg = NULL;
+
+    if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new())) {
+        errmsg = "CTX_ALLOC";
+        goto err;
+    }
+    if (!TEST_ptr(type = EVP_get_cipherbyname("aes-128-cfb"))) {
+        errmsg = "GET_CIPHERBYNAME";
+        goto err;
+    }
+    if (!TEST_true(EVP_CipherInit_ex(ctx, type, NULL, kCFBDefaultKey, iCFBIV, t->enc))) {
+        errmsg = "CIPHER_INIT";
+        goto err;
+    }
+    if (!TEST_true(EVP_CIPHER_CTX_set_padding(ctx, 0))) {
+        errmsg = "PADDING";
+        goto err;
+    }
+    if (!TEST_true(EVP_CipherUpdate(ctx, outbuf, &outlen1, t->input, t->inlen))) {
+        errmsg = "CIPHER_UPDATE";
+        goto err;
+    }
+    if (!TEST_true(EVP_CipherFinal_ex(ctx, outbuf + outlen1, &outlen2))) {
+        errmsg = "CIPHER_FINAL";
+        goto err;
+    }
+    if (!TEST_mem_eq(t->expected, t->expectedlen, outbuf, outlen1 + outlen2)) {
+        errmsg = "WRONG_RESULT";
+        goto err;
+    }
+    if (!TEST_true(EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, -1))) {
+        errmsg = "CIPHER_REINIT";
+        goto err;
+    }
+    if (!TEST_true(EVP_CipherUpdate(ctx, outbuf, &outlen1, t->input, t->inlen))) {
+        errmsg = "CIPHER_UPDATE (reinit)";
+        goto err;
+    }
+    if (!TEST_true(EVP_CipherFinal_ex(ctx, outbuf + outlen1, &outlen2))) {
+        errmsg = "CIPHER_FINAL (reinit)";
+        goto err;
+    }
+    if (!TEST_mem_eq(t->expected, t->expectedlen, outbuf, outlen1 + outlen2)) {
+        errmsg = "WRONG_RESULT (reinit)";
+        goto err;
+    }
+    testresult = 1;
+ err:
+    if (errmsg != NULL)
+        TEST_info("test_evp_reset %d: %s", idx, errmsg);
+    EVP_CIPHER_CTX_free(ctx);
+    return testresult;
+}
+
+typedef struct {
+    const unsigned char *iv1;
+    const unsigned char *iv2;
+    const unsigned char *expected1;
+    const unsigned char *expected2;
+    const unsigned char *tag1;
+    const unsigned char *tag2;
+    size_t ivlen1;
+    size_t ivlen2;
+    size_t expectedlen1;
+    size_t expectedlen2;
+} TEST_GCM_IV_REINIT_st;
+
+static const TEST_GCM_IV_REINIT_st gcm_reinit_tests[] = {
+    {
+        iGCMResetIV1, iGCMResetIV2, gcmResetCiphertext1, gcmResetCiphertext2,
+        gcmResetTag1, gcmResetTag2, sizeof(iGCMResetIV1), sizeof(iGCMResetIV2),
+        sizeof(gcmResetCiphertext1), sizeof(gcmResetCiphertext2)
+    },
+    {
+        iGCMResetIV2, iGCMResetIV1, gcmResetCiphertext2, gcmResetCiphertext1,
+        gcmResetTag2, gcmResetTag1, sizeof(iGCMResetIV2), sizeof(iGCMResetIV1),
+        sizeof(gcmResetCiphertext2), sizeof(gcmResetCiphertext1)
+    }
+};
+
+static int test_gcm_reinit(int idx)
+{
+    int outlen1, outlen2, outlen3;
+    int testresult = 0;
+    unsigned char outbuf[1024];
+    unsigned char tag[16];
+    const TEST_GCM_IV_REINIT_st *t = &gcm_reinit_tests[idx];
+    EVP_CIPHER_CTX *ctx = NULL;
+    const EVP_CIPHER *type = NULL;
+    size_t taglen = sizeof(tag);
+    char *errmsg = NULL;
+
+    if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new())) {
+        errmsg = "CTX_ALLOC";
+        goto err;
+    }
+    if (!TEST_ptr(type = EVP_get_cipherbyname("aes-256-gcm"))) {
+        errmsg = "GET_CIPHERBYNAME";
+        goto err;
+    }
+    if (!TEST_true(EVP_CipherInit_ex(ctx, type, NULL, NULL, NULL, 1))) {
+        errmsg = "ENC_INIT";
+        goto err;
+    }
+    if (!TEST_true(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, t->ivlen1, NULL))) {
+        errmsg = "SET_IVLEN1";
+        goto err;
+    }
+    if (!TEST_true(EVP_CipherInit_ex(ctx, NULL, NULL, kGCMResetKey, t->iv1, 1))) {
+        errmsg = "SET_IV1";
+        goto err;
+    }
+    if (!TEST_true(EVP_CipherUpdate(ctx, NULL, &outlen3, gcmAAD, sizeof(gcmAAD)))) {
+        errmsg = "AAD1";
+        goto err;
+    }
+    EVP_CIPHER_CTX_set_padding(ctx, 0);
+    if (!TEST_true(EVP_CipherUpdate(ctx, outbuf, &outlen1, gcmResetPlaintext,
+                                    sizeof(gcmResetPlaintext)))) {
+        errmsg = "CIPHER_UPDATE1";
+        goto err;
+    }
+    if (!TEST_true(EVP_CipherFinal_ex(ctx, outbuf + outlen1, &outlen2))) {
+        errmsg = "CIPHER_FINAL1";
+        goto err;
+    }
+    if (!TEST_mem_eq(t->expected1, t->expectedlen1, outbuf, outlen1 + outlen2)) {
+        errmsg = "WRONG_RESULT1";
+        goto err;
+    }
+    if (!TEST_true(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag))) {
+        errmsg = "GET_TAG1";
+        goto err;
+    }
+    if (!TEST_mem_eq(t->tag1, taglen, tag, taglen)) {
+        errmsg = "TAG_ERROR1";
+        goto err;
+    }
+    /* Now reinit */
+    if (!TEST_true(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, t->ivlen2, NULL))) {
+        errmsg = "SET_IVLEN2";
+        goto err;
+    }
+    if (!TEST_true(EVP_CipherInit_ex(ctx, NULL, NULL, NULL, t->iv2, -1))) {
+        errmsg = "SET_IV2";
+        goto err;
+    }
+    if (!TEST_true(EVP_CipherUpdate(ctx, NULL, &outlen3, gcmAAD, sizeof(gcmAAD)))) {
+        errmsg = "AAD2";
+        goto err;
+    }
+    if (!TEST_true(EVP_CipherUpdate(ctx, outbuf, &outlen1, gcmResetPlaintext,
+                                    sizeof(gcmResetPlaintext)))) {
+        errmsg = "CIPHER_UPDATE2";
+        goto err;
+    }
+    if (!TEST_true(EVP_CipherFinal_ex(ctx, outbuf + outlen1, &outlen2))) {
+        errmsg = "CIPHER_FINAL2";
+        goto err;
+    }
+    if (!TEST_mem_eq(t->expected2, t->expectedlen2, outbuf, outlen1 + outlen2)) {
+        errmsg = "WRONG_RESULT2";
+        goto err;
+    }
+    if (!TEST_true(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag))) {
+        errmsg = "GET_TAG2";
+        goto err;
+    }
+    if (!TEST_mem_eq(t->tag2, taglen, tag, taglen)) {
+        errmsg = "TAG_ERROR2";
+        goto err;
+    }
+    testresult = 1;
+ err:
+    if (errmsg != NULL)
+        TEST_info("evp_init_test %d: %s", idx, errmsg);
+    EVP_CIPHER_CTX_free(ctx);
+    return testresult;
+}
+
+typedef struct {
+    const char *cipher;
+    int enc;
+} EVP_UPDATED_IV_TEST_st;
+
+static const EVP_UPDATED_IV_TEST_st evp_updated_iv_tests[] = {
+    {
+        "aes-128-cfb", 1
+    },
+    {
+        "aes-128-cfb", 0
+    },
+    {
+        "aes-128-cfb1", 1
+    },
+    {
+        "aes-128-cfb1", 0
+    },
+    {
+        "aes-128-cfb128", 1
+    },
+    {
+        "aes-128-cfb128", 0
+    },
+    {
+        "aes-128-cfb8", 1
+    },
+    {
+        "aes-128-cfb8", 0
+    },
+    {
+        "aes-128-ofb", 1
+    },
+    {
+        "aes-128-ofb", 0
+    },
+    {
+        "aes-128-ctr", 1
+    },
+    {
+        "aes-128-ctr", 0
+    },
+    {
+        "aes-128-cbc", 1
+    },
+    {
+        "aes-128-cbc", 0
+    }
+};
+
+/*
+ * Test that the IV in the context is updated during a crypto operation for CFB
+ * and OFB.
+ */
+static int test_evp_updated_iv(int idx)
+{
+    const EVP_UPDATED_IV_TEST_st *t = &evp_updated_iv_tests[idx];
+    int outlen1, outlen2;
+    int testresult = 0;
+    unsigned char outbuf[1024];
+    EVP_CIPHER_CTX *ctx = NULL;
+    const EVP_CIPHER *type = NULL;
+    const unsigned char *updated_iv;
+    int iv_len;
+    char *errmsg = NULL;
+
+    if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new())) {
+        errmsg = "CTX_ALLOC";
+        goto err;
+    }
+    if ((type = EVP_get_cipherbyname(t->cipher)) == NULL) {
+        TEST_info("cipher %s not supported, skipping", t->cipher);
+        goto ok;
+    }
+    if (!TEST_true(EVP_CipherInit_ex(ctx, type, NULL, kCFBDefaultKey, iCFBIV, t->enc))) {
+        errmsg = "CIPHER_INIT";
+        goto err;
+    }
+    if (!TEST_true(EVP_CIPHER_CTX_set_padding(ctx, 0))) {
+        errmsg = "PADDING";
+        goto err;
+    }
+    if (!TEST_true(EVP_CipherUpdate(ctx, outbuf, &outlen1, cfbPlaintext, sizeof(cfbPlaintext)))) {
+        errmsg = "CIPHER_UPDATE";
+        goto err;
+    }
+    if (!TEST_ptr(updated_iv = EVP_CIPHER_CTX_iv(ctx))) {
+        errmsg = "CIPHER_CTX_IV";
+        goto err;
+    }
+    if (!TEST_true(iv_len = EVP_CIPHER_CTX_iv_length(ctx))) {
+        errmsg = "CIPHER_CTX_IV_LEN";
+        goto err;
+    }
+    if (!TEST_mem_ne(iCFBIV, sizeof(iCFBIV), updated_iv, iv_len)) {
+        errmsg = "IV_NOT_UPDATED";
+        goto err;
+    }
+    if (!TEST_true(EVP_CipherFinal_ex(ctx, outbuf + outlen1, &outlen2))) {
+        errmsg = "CIPHER_FINAL";
+        goto err;
+    }
+ ok:
+    testresult = 1;
+ err:
+    if (errmsg != NULL)
+        TEST_info("test_evp_updated_iv %d: %s", idx, errmsg);
+    EVP_CIPHER_CTX_free(ctx);
+    return testresult;
+}
+
 static APK_DATA keydata[] = {
     {kExampleRSAKeyDER, sizeof(kExampleRSAKeyDER), EVP_PKEY_RSA},
     {kExampleRSAKeyPKCS8, sizeof(kExampleRSAKeyPKCS8), EVP_PKEY_RSA},
@@ -818,10 +1398,14 @@
 } keys[] = {
     {
         EVP_PKEY_HMAC, "0123456789", NULL
+#ifndef OPENSSL_NO_POLY1305
     }, {
         EVP_PKEY_POLY1305, "01234567890123456789012345678901", NULL
+#endif
+#ifndef OPENSSL_NO_SIPHASH
     }, {
         EVP_PKEY_SIPHASH, "0123456789012345", NULL
+#endif
     },
 #ifndef OPENSSL_NO_EC
     {
@@ -851,18 +1435,22 @@
     EVP_PKEY *pkey;
 
     /* Check if this algorithm supports public keys */
-    if (keys[tst].pub == NULL)
+    if (pub && keys[tst].pub == NULL)
         return 1;
 
     memset(buf, 0, sizeof(buf));
 
     if (pub) {
+#ifndef OPENSSL_NO_EC
         inlen = strlen(keys[tst].pub);
         in = (unsigned char *)keys[tst].pub;
         pkey = EVP_PKEY_new_raw_public_key(keys[tst].type,
                                            NULL,
                                            in,
                                            inlen);
+#else
+        return 1;
+#endif
     } else {
         inlen = strlen(keys[tst].priv);
         in = (unsigned char *)keys[tst].priv;
@@ -873,6 +1461,7 @@
     }
 
     if (!TEST_ptr(pkey)
+            || !TEST_int_eq(EVP_PKEY_cmp(pkey, pkey), 1)
             || (!pub && !TEST_true(EVP_PKEY_get_raw_private_key(pkey, NULL, &len)))
             || (pub && !TEST_true(EVP_PKEY_get_raw_public_key(pkey, NULL, &len)))
             || !TEST_true(len == inlen)
@@ -1171,10 +1760,172 @@
 
     return ret;
 }
-#endif
+#endif /* OPENSSL_NO_DH */
+
+#if !defined(OPENSSL_NO_ENGINE) && !defined(OPENSSL_NO_DYNAMIC_ENGINE)
+/* Test we can create a signature keys with an associated ENGINE */
+static int test_signatures_with_engine(int tst)
+{
+    ENGINE *e;
+    const char *engine_id = "dasync";
+    EVP_PKEY *pkey = NULL;
+    const unsigned char badcmackey[] = { 0x00, 0x01 };
+    const unsigned char cmackey[] = {
+        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
+        0x0c, 0x0d, 0x0e, 0x0f
+    };
+    const unsigned char ed25519key[] = {
+        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
+        0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
+        0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
+    };
+    const unsigned char msg[] = { 0x00, 0x01, 0x02, 0x03 };
+    int testresult = 0;
+    EVP_MD_CTX *ctx = NULL;
+    unsigned char *mac = NULL;
+    size_t maclen = 0;
+    int ret;
+
+#  ifdef OPENSSL_NO_CMAC
+    /* Skip CMAC tests in a no-cmac build */
+    if (tst <= 1)
+        return 1;
+#  endif
+
+    if (!TEST_ptr(e = ENGINE_by_id(engine_id)))
+        return 0;
+
+    if (!TEST_true(ENGINE_init(e))) {
+        ENGINE_free(e);
+        return 0;
+    }
+
+    switch (tst) {
+    case 0:
+        pkey = EVP_PKEY_new_CMAC_key(e, cmackey, sizeof(cmackey),
+                                     EVP_aes_128_cbc());
+        break;
+    case 1:
+        pkey = EVP_PKEY_new_CMAC_key(e, badcmackey, sizeof(badcmackey),
+                                     EVP_aes_128_cbc());
+        break;
+    case 2:
+        pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, e, ed25519key,
+                                            sizeof(ed25519key));
+        break;
+    default:
+        TEST_error("Invalid test case");
+        goto err;
+    }
+    if (tst == 1) {
+        /*
+         * In 1.1.1 CMAC keys will fail to during EVP_PKEY_new_CMAC_key() if the
+         * key is bad. In later versions this isn't detected until later.
+         */
+        if (!TEST_ptr_null(pkey))
+            goto err;
+    } else {
+        if (!TEST_ptr(pkey))
+            goto err;
+    }
+
+    if (tst == 0 || tst == 1) {
+        /*
+         * We stop the test here for tests 0 and 1. The dasync engine doesn't
+         * actually support CMAC in 1.1.1.
+         */
+        testresult = 1;
+        goto err;
+    }
+
+    if (!TEST_ptr(ctx = EVP_MD_CTX_new()))
+        goto err;
+
+    ret = EVP_DigestSignInit(ctx, NULL, tst == 2 ? NULL : EVP_sha256(), NULL,
+                             pkey);
+    if (tst == 0) {
+        if (!TEST_true(ret))
+            goto err;
+
+        if (!TEST_true(EVP_DigestSignUpdate(ctx, msg, sizeof(msg)))
+                || !TEST_true(EVP_DigestSignFinal(ctx, NULL, &maclen)))
+            goto err;
+
+        if (!TEST_ptr(mac = OPENSSL_malloc(maclen)))
+            goto err;
+
+        if (!TEST_true(EVP_DigestSignFinal(ctx, mac, &maclen)))
+            goto err;
+    } else {
+        /* We used a bad key. We expect a failure here */
+        if (!TEST_false(ret))
+            goto err;
+    }
+
+    testresult = 1;
+ err:
+    EVP_MD_CTX_free(ctx);
+    OPENSSL_free(mac);
+    EVP_PKEY_free(pkey);
+    ENGINE_finish(e);
+    ENGINE_free(e);
+
+    return testresult;
+}
+
+static int test_cipher_with_engine(void)
+{
+    ENGINE *e;
+    const char *engine_id = "dasync";
+    const unsigned char keyiv[] = {
+        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
+        0x0c, 0x0d, 0x0e, 0x0f
+    };
+    const unsigned char msg[] = { 0x00, 0x01, 0x02, 0x03 };
+    int testresult = 0;
+    EVP_CIPHER_CTX *ctx = NULL, *ctx2 = NULL;
+    unsigned char buf[AES_BLOCK_SIZE];
+    int len = 0;
+
+    if (!TEST_ptr(e = ENGINE_by_id(engine_id)))
+        return 0;
+
+    if (!TEST_true(ENGINE_init(e))) {
+        ENGINE_free(e);
+        return 0;
+    }
+
+    if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new())
+            || !TEST_ptr(ctx2 = EVP_CIPHER_CTX_new()))
+        goto err;
+
+    if (!TEST_true(EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), e, keyiv, keyiv)))
+        goto err;
+
+    /* Copy the ctx, and complete the operation with the new ctx */
+    if (!TEST_true(EVP_CIPHER_CTX_copy(ctx2, ctx)))
+        goto err;
+
+    if (!TEST_true(EVP_EncryptUpdate(ctx2, buf, &len, msg, sizeof(msg)))
+            || !TEST_true(EVP_EncryptFinal_ex(ctx2, buf + len, &len)))
+        goto err;
+
+    testresult = 1;
+ err:
+    EVP_CIPHER_CTX_free(ctx);
+    EVP_CIPHER_CTX_free(ctx2);
+    ENGINE_finish(e);
+    ENGINE_free(e);
+
+    return testresult;
+}
+#endif /* !defined(OPENSSL_NO_ENGINE) && !defined(OPENSSL_NO_DYNAMIC_ENGINE) */
 
 int setup_tests(void)
 {
+#if !defined(OPENSSL_NO_ENGINE) && !defined(OPENSSL_NO_DYNAMIC_ENGINE)
+    ENGINE_load_builtin_engines();
+#endif
     ADD_TEST(test_EVP_DigestSignInit);
     ADD_TEST(test_EVP_DigestVerifyInit);
     ADD_TEST(test_EVP_Enveloped);
@@ -1209,5 +1960,19 @@
     ADD_TEST(test_EVP_PKEY_set1_DH);
 #endif
 
+    ADD_ALL_TESTS(test_evp_init_seq, OSSL_NELEM(evp_init_tests));
+    ADD_ALL_TESTS(test_evp_reset, OSSL_NELEM(evp_reset_tests));
+    ADD_ALL_TESTS(test_gcm_reinit, OSSL_NELEM(gcm_reinit_tests));
+    ADD_ALL_TESTS(test_evp_updated_iv, OSSL_NELEM(evp_updated_iv_tests));
+
+#if !defined(OPENSSL_NO_ENGINE) && !defined(OPENSSL_NO_DYNAMIC_ENGINE)
+# ifndef OPENSSL_NO_EC
+    ADD_ALL_TESTS(test_signatures_with_engine, 3);
+# else
+    ADD_ALL_TESTS(test_signatures_with_engine, 2);
+# endif
+    ADD_TEST(test_cipher_with_engine);
+#endif
+
     return 1;
 }
diff -Nru openssl-1.1.1k/test/evp_test.c openssl-1.1.1m/test/evp_test.c
--- openssl-1.1.1k/test/evp_test.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/evp_test.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2015-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -1777,7 +1777,7 @@
     unsigned char *got = NULL;
     size_t got_len = expected->output_len;
 
-    if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
+    if (!TEST_ptr(got = OPENSSL_malloc(got_len == 0 ? 1 : got_len))) {
         t->err = "INTERNAL_ERROR";
         goto err;
     }
diff -Nru openssl-1.1.1k/test/packettest.c openssl-1.1.1m/test/packettest.c
--- openssl-1.1.1k/test/packettest.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/packettest.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -302,7 +302,7 @@
 
 static int test_PACKET_buf_init(void)
 {
-    unsigned char buf1[BUF_LEN];
+    unsigned char buf1[BUF_LEN] = { 0 };
     PACKET pkt;
 
     /* Also tests PACKET_remaining() */
diff -Nru openssl-1.1.1k/test/recipes/01-test_symbol_presence.t openssl-1.1.1m/test/recipes/01-test_symbol_presence.t
--- openssl-1.1.1k/test/recipes/01-test_symbol_presence.t	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/recipes/01-test_symbol_presence.t	2021-12-14 16:45:01.000000000 +0100
@@ -1,6 +1,6 @@
 #! /usr/bin/env perl
 # -*- mode: Perl -*-
-# Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
+# Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
 #
 # Licensed under the OpenSSL license (the "License").  You may not use
 # this file except in compliance with the License.  You can obtain a copy
@@ -37,12 +37,12 @@
         *OSTDOUT = *STDOUT;
         open STDERR, ">", devnull();
         open STDOUT, ">", devnull();
-        my @nm_lines = map { s|\R$||; $_ } `nm -Pg $shlibpath 2> /dev/null`;
+        my @nm_lines = map { s|\R$||; $_ } `nm -DPg $shlibpath 2> /dev/null`;
         close STDERR;
         close STDOUT;
         *STDERR = *OSTDERR;
         *STDOUT = *OSTDOUT;
-        skip "Can't run 'nm -Pg $shlibpath' => $?...  ignoring", 2
+        skip "Can't run 'nm -DPg $shlibpath' => $?...  ignoring", 2
             unless $? == 0;
 
         my $bldtop = bldtop_dir();
@@ -57,7 +57,17 @@
         note "Number of lines in \@def_lines before massaging: ", scalar @def_lines;
 
         # Massage the nm output to only contain defined symbols
-        @nm_lines = sort map { s| .*||; $_ } grep(m|.* [BCDST] .*|, @nm_lines);
+        @nm_lines =
+            sort
+            map {
+                # Drop the first space and everything following it
+                s| .*||;
+                # Drop OpenSSL dynamic version information if there is any
+                s|\@\@OPENSSL_[0-9._]+[a-z]?$||;
+                # Return the result
+                $_
+            }
+            grep(m|.* [BCDST] .*|, @nm_lines);
 
         # Massage the mkdef.pl output to only contain global symbols
         # The output we got is in Unix .map format, which has a global
diff -Nru openssl-1.1.1k/test/recipes/20-test_dgst.t openssl-1.1.1m/test/recipes/20-test_dgst.t
--- openssl-1.1.1k/test/recipes/20-test_dgst.t	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/recipes/20-test_dgst.t	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 #! /usr/bin/env perl
-# Copyright 2017-2020 The OpenSSL Project Authors. All Rights Reserved.
+# Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved.
 #
 # Licensed under the Apache License 2.0 (the "License").  You may not use
 # this file except in compliance with the License.  You can obtain a copy
@@ -11,12 +11,12 @@
 use warnings;
 
 use File::Spec;
-use OpenSSL::Test qw/:DEFAULT with srctop_file/;
+use OpenSSL::Test qw/:DEFAULT with srctop_file bldtop_file/;
 use OpenSSL::Test::Utils;
 
 setup("test_dgst");
 
-plan tests => 5;
+plan tests => 6;
 
 sub tsignverify {
     my $testtext = shift;
@@ -102,3 +102,22 @@
                     srctop_file("test","tested448pub.pem"));
     };
 }
+
+SKIP: {
+    skip "dgst with engine is not supported by this OpenSSL build", 1
+        if disabled("engine") || disabled("dynamic-engine");
+
+    subtest "SHA1 generation by engine with `dgst` CLI" => sub {
+        plan tests => 1;
+
+        my $testdata = srctop_file('test', 'data.bin');
+        # intentionally using -engine twice, please do not remove the duplicate line
+        my @macdata = run(app(['openssl', 'dgst', '-sha1',
+                               '-engine', $^O eq 'linux' ? bldtop_file("engines", "ossltest.so") : "ossltest",
+                               '-engine', $^O eq 'linux' ? bldtop_file("engines", "ossltest.so") : "ossltest",
+                               $testdata]), capture => 1);
+        chomp(@macdata);
+        my $expected = qr/SHA1\(\Q$testdata\E\)= 000102030405060708090a0b0c0d0e0f10111213/;
+        ok($macdata[0] =~ $expected, "SHA1: Check HASH value is as expected ($macdata[0]) vs ($expected)");
+    }
+}
diff -Nru openssl-1.1.1k/test/recipes/25-test_req.t openssl-1.1.1m/test/recipes/25-test_req.t
--- openssl-1.1.1k/test/recipes/25-test_req.t	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/recipes/25-test_req.t	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 #! /usr/bin/env perl
-# Copyright 2015-2020 The OpenSSL Project Authors. All Rights Reserved.
+# Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
 #
 # Licensed under the OpenSSL license (the "License").  You may not use
 # this file except in compliance with the License.  You can obtain a copy
@@ -47,7 +47,7 @@
 ok(!run(app([@addext_args, "-addext", $val2, "-addext", $val3])));
 
 subtest "generating certificate requests with RSA" => sub {
-    plan tests => 2;
+    plan tests => 6;
 
     SKIP: {
         skip "RSA is not supported by this OpenSSL build", 2
@@ -63,6 +63,29 @@
                     "-config", srctop_file("test", "test.cnf"),
                     "-verify", "-in", "testreq.pem", "-noout"])),
            "Verifying signature on request");
+
+        ok(run(app(["openssl", "req",
+                    "-config", srctop_file("test", "test.cnf"),
+                    "-new", "-out", "testreq_withattrs_pem.pem", "-utf8",
+                    "-key", srctop_file("test", "testrsa_withattrs.pem")])),
+           "Generating request from a key with extra attributes - PEM");
+
+        ok(run(app(["openssl", "req",
+                    "-config", srctop_file("test", "test.cnf"),
+                    "-verify", "-in", "testreq_withattrs_pem.pem", "-noout"])),
+           "Verifying signature on request from a key with extra attributes - PEM");
+
+        ok(run(app(["openssl", "req",
+                    "-config", srctop_file("test", "test.cnf"),
+                    "-new", "-out", "testreq_withattrs_der.pem", "-utf8",
+                    "-key", srctop_file("test", "testrsa_withattrs.der"),
+	            "-keyform", "DER"])),
+           "Generating request from a key with extra attributes - PEM");
+
+        ok(run(app(["openssl", "req",
+                    "-config", srctop_file("test", "test.cnf"),
+                    "-verify", "-in", "testreq_withattrs_der.pem", "-noout"])),
+           "Verifying signature on request from a key with extra attributes - PEM");
     }
 };
 
@@ -165,7 +188,7 @@
 run_conversion('req conversions -- testreq2',
                srctop_file("test", "testreq2.pem"));
 
-unlink "testkey.pem", "testreq.pem";
+unlink "testkey.pem", "testreq.pem", "testreq_withattrs_pem.pem", "testreq_withattrs_der.pem";
 
 sub run_conversion {
     my $title = shift;
diff -Nru openssl-1.1.1k/test/recipes/25-test_verify.t openssl-1.1.1m/test/recipes/25-test_verify.t
--- openssl-1.1.1k/test/recipes/25-test_verify.t	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/recipes/25-test_verify.t	2021-12-14 16:45:01.000000000 +0100
@@ -396,7 +396,8 @@
 ok(verify("root-cert-rsa2", "sslserver", ["root-cert-rsa2"], [], "-check_ss_sig"),
     "Public Key Algorithm rsa instead of rsaEncryption");
 
-    ok(verify("ee-self-signed", "sslserver", ["ee-self-signed"], []),
+ok(verify("ee-self-signed", "sslserver", ["ee-self-signed"], [],
+          "-attime", "1593565200"),
        "accept trusted self-signed EE cert excluding key usage keyCertSign");
 
 SKIP: {
diff -Nru openssl-1.1.1k/test/recipes/30-test_evp_data/evpkdf.txt openssl-1.1.1m/test/recipes/30-test_evp_data/evpkdf.txt
--- openssl-1.1.1k/test/recipes/30-test_evp_data/evpkdf.txt	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/recipes/30-test_evp_data/evpkdf.txt	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 2001-2017 The OpenSSL Project Authors. All Rights Reserved.
+# Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved.
 #
 # Licensed under the OpenSSL license (the "License").  You may not use
 # this file except in compliance with the License.  You can obtain a copy
@@ -301,5 +301,5 @@
 Ctrl.N = N:1048576
 Ctrl.r = r:8
 Ctrl.p = p:1
-Result = INTERNAL_ERROR
+Result = KDF_MISMATCH
 
diff -Nru openssl-1.1.1k/test/recipes/30-test_evp_data/evppkey.txt openssl-1.1.1m/test/recipes/30-test_evp_data/evppkey.txt
--- openssl-1.1.1k/test/recipes/30-test_evp_data/evppkey.txt	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/recipes/30-test_evp_data/evppkey.txt	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 #
-# Copyright 2001-2018 The OpenSSL Project Authors. All Rights Reserved.
+# Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved.
 #
 # Licensed under the OpenSSL license (the "License").  You may not use
 # this file except in compliance with the License.  You can obtain a copy
@@ -18444,6 +18444,16 @@
 Input = 30818A0220466BE2EF5C11782EC77864A0055417F407A5AFC11D653C6BCE69E417BB1D05B6022062B572E21FF0DDF5C726BD3F9FF2EAE56E6294713A607E9B9525628965F62CC804203C1B5713B5DB2728EB7BF775E44F4689FC32668BDC564F52EA45B09E8DF2A5F40422084A9D0CC2997092B7D3C404FCE95956EB604D732B2307A8E5B8900ED6608CA5B197
 Output = "The floofy bunnies hop at midnight"
 
+# Test with an C1y value < 32 bytes in length (self generated)
+Decrypt = SM2_key1
+Input = 3072022070DAD60CDA7C30D64CF4F278A849003581223F5324BFEC9BB329229BFFAD21A6021F18AFAB2B35459D2643243B242BE4EA80C6FA5071D2D847340CC57EB9309E5D04200B772E4DB664B2601E3B85E39C4AA8C2C1910308BE13B331E009C5A9258C29FD040B6D588BE9260A94DA18E0E6
+Output = "Hello World"
+
+# Test with an C1x and C1y valuey > 32 bytes in length, and longer plaintext (self generated)
+Decrypt = SM2_key1
+Input = 3081DD022100CD49634BBCB21CAFFFA6D33669A5A867231CB2A942A14352EF4CAF6DC3344D54022100C35B41D4DEBB3A2735EFEE821B9EBA566BD86900176A0C06672E30EE5CC04E930420C4190A3D80D86C4BD20E99F7E4B59BF6427C6808793533EEA9591D1188EC56B50473747295470E81D951BED279AC1B86A1AFE388CD2833FA9632799EC199C7D364E5663D5A94888BB2358CFCBF6283184DE0CBC41CCEA91D24746E99D231A1DA77AFD83CDF908190ED628B7369724494568A27C782A1D1D7294BCAD80C34569ED22859896301128A8118F48924D8CCD43E998D9533
+Output = "Some longer plaintext for testing SM2 decryption. Blah blah blah blah blah blah blah blah blah blah blah blah blah."
+
 # This is a "fake" test as it does only verify that the SM2 EVP_PKEY interface
 # is capable of creating a signature without failing, but it does not say
 # anything about the generated signature being valid, nor does it test the
diff -Nru openssl-1.1.1k/test/recipes/70-test_tls13kexmodes.t openssl-1.1.1m/test/recipes/70-test_tls13kexmodes.t
--- openssl-1.1.1k/test/recipes/70-test_tls13kexmodes.t	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/recipes/70-test_tls13kexmodes.t	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 #! /usr/bin/env perl
-# Copyright 2017-2019 The OpenSSL Project Authors. All Rights Reserved.
+# Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved.
 #
 # Licensed under the OpenSSL license (the "License").  You may not use
 # this file except in compliance with the License.  You can obtain a copy
@@ -195,17 +195,14 @@
 plan tests => 11;
 ok(TLSProxy::Message->success(), "Initial connection");
 
-#Test 2: Attempt a resume with no kex modes extension. Should not resume
+#Test 2: Attempt a resume with no kex modes extension. Should fail (server
+#        MUST abort handshake with pre_shared key and no psk_kex_modes)
 $proxy->clear();
 $proxy->clientflags("-sess_in ".$session);
 my $testtype = DELETE_EXTENSION;
 $proxy->filter(\&modify_kex_modes_filter);
 $proxy->start();
-checkhandshake($proxy, checkhandshake::DEFAULT_HANDSHAKE,
-               checkhandshake::DEFAULT_EXTENSIONS
-               | checkhandshake::KEY_SHARE_SRV_EXTENSION
-               | checkhandshake::PSK_CLI_EXTENSION,
-               "Resume with no kex modes");
+ok(TLSProxy::Message->fail(), "Resume with no kex modes");
 
 #Test 3: Attempt a resume with empty kex modes extension. Should fail (empty
 #        extension is invalid)
@@ -243,6 +240,7 @@
                "Resume with non-dhe kex mode");
 
 #Test 6: Attempt a resume with only unrecognised kex modes. Should not resume
+#        but rather fall back to full handshake
 $proxy->clear();
 $proxy->clientflags("-sess_in ".$session);
 $testtype = UNKNOWN_KEX_MODES;
@@ -252,7 +250,7 @@
                | checkhandshake::PSK_KEX_MODES_EXTENSION
                | checkhandshake::KEY_SHARE_SRV_EXTENSION
                | checkhandshake::PSK_CLI_EXTENSION,
-               "Resume with empty kex modes");
+               "Resume with unrecognized kex mode");
 
 #Test 7: Attempt a resume with both non-dhe and dhe kex mode. Should resume with
 #        a key_share
diff -Nru openssl-1.1.1k/test/recipes/80-test_dane.t openssl-1.1.1m/test/recipes/80-test_dane.t
--- openssl-1.1.1k/test/recipes/80-test_dane.t	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/recipes/80-test_dane.t	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 #! /usr/bin/env perl
-# Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved.
+# Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
 #
 # Licensed under the OpenSSL license (the "License").  You may not use
 # this file except in compliance with the License.  You can obtain a copy
@@ -17,8 +17,12 @@
 plan skip_all => "test_dane uses ec which is not supported by this OpenSSL build"
     if disabled("ec");
 
-plan tests => 1;                # The number of tests being performed
+plan tests => 2;                # The number of tests being performed
 
 ok(run(test(["danetest", "example.com",
              srctop_file("test", "danetest.pem"),
              srctop_file("test", "danetest.in")])), "dane tests");
+
+ok(run(test(["danetest", "server.example",
+             srctop_file("test", "certs", "cross-root.pem"),
+             srctop_file("test", "dane-cross.in")])), "dane cross CA test");
diff -Nru openssl-1.1.1k/test/recipes/80-test_ssl_old.t openssl-1.1.1m/test/recipes/80-test_ssl_old.t
--- openssl-1.1.1k/test/recipes/80-test_ssl_old.t	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/recipes/80-test_ssl_old.t	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 #! /usr/bin/env perl
-# Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved.
+# Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
 #
 # Licensed under the OpenSSL license (the "License").  You may not use
 # this file except in compliance with the License.  You can obtain a copy
@@ -476,10 +476,10 @@
     subtest 'RSA/(EC)DHE/PSK tests' => sub {
 	######################################################################
 
-	plan tests => 5;
+	plan tests => 6;
 
       SKIP: {
-	  skip "TLSv1.0 is not supported by this OpenSSL build", 5
+	  skip "TLSv1.0 is not supported by this OpenSSL build", 6
 	      if $no_tls1;
 
 	SKIP: {
@@ -514,6 +514,14 @@
 	    ok(run(test([@ssltest, "-bio_pair", "-tls1", "-cipher", "PSK", "-psk", "abc123"])),
 	       'test tls1 with PSK via BIO pair');
 	  }
+
+	SKIP: {
+	    skip "skipping auto PSK tests", 1
+	        if ($no_dh || $no_psk || $no_ec);
+
+	    ok(run(test(['ssltest_old', '-dhe2048', '-psk', '0102030405', '-cipher', '@SECLEVEL=2:DHE-PSK-AES128-CCM'])),
+	       'test auto DH meets security strength');
+	  }
 	}
 
     };
diff -Nru openssl-1.1.1k/test/rsa_test.c openssl-1.1.1m/test/rsa_test.c
--- openssl-1.1.1k/test/rsa_test.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/rsa_test.c	2021-12-14 16:45:01.000000000 +0100
@@ -306,7 +306,6 @@
     int ret = 0;
     RSA *key = NULL;
     unsigned char ptext[256];
-    unsigned char ctext[256];
     static unsigned char ptext_ex[] = "\x54\x85\x9b\x34\x2c\x49\xea\x2a";
     unsigned char ctext_ex[256];
     int plen;
@@ -328,17 +327,17 @@
 
     /* Try decrypting corrupted ciphertexts. */
     for (n = 0; n < clen; ++n) {
-        ctext[n] ^= 1;
-        num = RSA_private_decrypt(clen, ctext, ptext, key,
+        ctext_ex[n] ^= 1;
+        num = RSA_private_decrypt(clen, ctext_ex, ptext, key,
                                       RSA_PKCS1_OAEP_PADDING);
         if (!TEST_int_le(num, 0))
             goto err;
-        ctext[n] ^= 1;
+        ctext_ex[n] ^= 1;
     }
 
     /* Test truncated ciphertexts, as well as negative length. */
     for (n = -1; n < clen; ++n) {
-        num = RSA_private_decrypt(n, ctext, ptext, key,
+        num = RSA_private_decrypt(n, ctext_ex, ptext, key,
                                   RSA_PKCS1_OAEP_PADDING);
         if (!TEST_int_le(num, 0))
             goto err;
diff -Nru openssl-1.1.1k/test/sm2_internal_test.c openssl-1.1.1m/test/sm2_internal_test.c
--- openssl-1.1.1k/test/sm2_internal_test.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/sm2_internal_test.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2017-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -185,7 +185,7 @@
     if (!TEST_mem_eq(ctext, ctext_len, expected, ctext_len))
         goto done;
 
-    if (!TEST_true(sm2_plaintext_size(key, digest, ctext_len, &ptext_len))
+    if (!TEST_true(sm2_plaintext_size(ctext, ctext_len, &ptext_len))
             || !TEST_int_eq(ptext_len, msg_len))
         goto done;
 
@@ -210,6 +210,7 @@
 static int sm2_crypt_test(void)
 {
     int testresult = 0;
+    EC_GROUP *gm_group = NULL;
     EC_GROUP *test_group =
         create_EC_group
         ("8542D69E4C044F18E8B92435BF6FF7DE457283915C45517D722EDB8B08F1DFC3",
@@ -252,9 +253,49 @@
             "88E3C5AAFC0413229E6C9AEE2BB92CAD649FE2C035689785DA33"))
         goto done;
 
+    /* From Annex C in both GM/T0003.5-2012 and GB/T 32918.5-2016.*/
+    gm_group = create_EC_group(
+         "fffffffeffffffffffffffffffffffffffffffff00000000ffffffffffffffff",
+         "fffffffeffffffffffffffffffffffffffffffff00000000fffffffffffffffc",
+         "28e9fa9e9d9f5e344d5a9e4bcf6509a7f39789f515ab8f92ddbcbd414d940e93",
+         "32c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7",
+         "bc3736a2f4f6779c59bdcee36b692153d0a9877cc62a474002df32e52139f0a0",
+         "fffffffeffffffffffffffffffffffff7203df6b21c6052b53bbf40939d54123",
+         "1");
+
+    if (!TEST_ptr(gm_group))
+        goto done;
+
+    if (!test_sm2_crypt(
+            gm_group,
+            EVP_sm3(),
+            /* privkey (from which the encrypting public key is derived) */
+            "3945208F7B2144B13F36E38AC6D39F95889393692860B51A42FB81EF4DF7C5B8",
+            /* plaintext message */
+            "encryption standard",
+            /* ephemeral nonce k */
+            "59276E27D506861A16680F3AD9C02DCCEF3CC1FA3CDBE4CE6D54B80DEAC1BC21",
+            /*
+             * expected ciphertext, the field values are from GM/T 0003.5-2012
+             * (Annex C), but serialized following the ASN.1 format specified
+             * in GM/T 0009-2012 (Sec. 7.2).
+             */
+            "307C" /* SEQUENCE, 0x7c bytes */
+              "0220" /* INTEGER, 0x20 bytes */
+                "04EBFC718E8D1798620432268E77FEB6415E2EDE0E073C0F4F640ECD2E149A73"
+              "0221" /* INTEGER, 0x21 bytes */
+                "00" /* leading 00 due to DER for pos. int with topmost bit set */
+                "E858F9D81E5430A57B36DAAB8F950A3C64E6EE6A63094D99283AFF767E124DF0"
+              "0420" /* OCTET STRING, 0x20 bytes */
+                "59983C18F809E262923C53AEC295D30383B54E39D609D160AFCB1908D0BD8766"
+              "0413" /* OCTET STRING, 0x13 bytes */
+                "21886CA989CA9C7D58087307CA93092D651EFA"))
+        goto done;
+
     testresult = 1;
  done:
     EC_GROUP_free(test_group);
+    EC_GROUP_free(gm_group);
 
     return testresult;
 }
diff -Nru openssl-1.1.1k/test/sslapitest.c openssl-1.1.1m/test/sslapitest.c
--- openssl-1.1.1k/test/sslapitest.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/sslapitest.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -17,6 +17,7 @@
 #include <openssl/srp.h>
 #include <openssl/txt_db.h>
 #include <openssl/aes.h>
+#include <openssl/x509v3.h>
 
 #include "ssltestlib.h"
 #include "testutil.h"
@@ -1826,8 +1827,10 @@
 
     /* Verify changing the rbio/wbio directly does not cause leaks */
     if (change_bio != NO_BIO_CHANGE) {
-        if (!TEST_ptr(membio2 = BIO_new(BIO_s_mem())))
+        if (!TEST_ptr(membio2 = BIO_new(BIO_s_mem()))) {
+            ssl = NULL;
             goto end;
+        }
         if (change_bio == CHANGE_RBIO)
             SSL_set0_rbio(ssl, membio2);
         else
@@ -4107,6 +4110,11 @@
     return SSL_TLSEXT_ERR_OK;
 }
 
+static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
+{
+    return 1;
+}
+
 /*
  * Custom call back tests.
  * Test 0: Old style callbacks in TLSv1.2
@@ -4114,6 +4122,7 @@
  * Test 2: New style callbacks in TLSv1.2 with SNI
  * Test 3: New style callbacks in TLSv1.3. Extensions in CH and EE
  * Test 4: New style callbacks in TLSv1.3. Extensions in CH, SH, EE, Cert + NST
+ * Test 5: New style callbacks in TLSv1.3. Extensions in CR + Client Cert
  */
 static int test_custom_exts(int tst)
 {
@@ -4155,7 +4164,19 @@
             SSL_CTX_set_options(sctx2, SSL_OP_NO_TLSv1_3);
     }
 
-    if (tst == 4) {
+    if (tst == 5) {
+        context = SSL_EXT_TLS1_3_CERTIFICATE_REQUEST
+                  | SSL_EXT_TLS1_3_CERTIFICATE;
+        SSL_CTX_set_verify(sctx,
+                           SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
+                           verify_cb);
+        if (!TEST_int_eq(SSL_CTX_use_certificate_file(cctx, cert,
+                                                      SSL_FILETYPE_PEM), 1)
+                || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(cctx, privkey,
+                                                            SSL_FILETYPE_PEM), 1)
+                || !TEST_int_eq(SSL_CTX_check_private_key(cctx), 1))
+            goto end;
+    } else if (tst == 4) {
         context = SSL_EXT_CLIENT_HELLO
                   | SSL_EXT_TLS1_2_SERVER_HELLO
                   | SSL_EXT_TLS1_3_SERVER_HELLO
@@ -4251,6 +4272,12 @@
                 || (tst != 2 && snicb != 0)
                 || (tst == 2 && snicb != 1))
             goto end;
+    } else if (tst == 5) {
+        if (clntaddnewcb != 1
+                || clntparsenewcb != 1
+                || srvaddnewcb != 1
+                || srvparsenewcb != 1)
+            goto end;
     } else {
         /* In this case there 2 NewSessionTicket messages created */
         if (clntaddnewcb != 1
@@ -4267,8 +4294,8 @@
     SSL_free(clientssl);
     serverssl = clientssl = NULL;
 
-    if (tst == 3) {
-        /* We don't bother with the resumption aspects for this test */
+    if (tst == 3 || tst == 5) {
+        /* We don't bother with the resumption aspects for these tests */
         testresult = 1;
         goto end;
     }
@@ -6247,11 +6274,6 @@
     return 1;
 }
 
-static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
-{
-    return 1;
-}
-
 static int test_client_cert_cb(int tst)
 {
     SSL_CTX *cctx = NULL, *sctx = NULL;
@@ -6713,6 +6735,118 @@
     return testresult;
 }
 #endif
+/*
+ * Test that setting an ALPN does not violate RFC
+ */
+static int test_set_alpn(void)
+{
+    SSL_CTX *ctx = NULL;
+    SSL *ssl = NULL;
+    int testresult = 0;
+
+    unsigned char bad0[] = { 0x00, 'b', 'a', 'd' };
+    unsigned char good[] = { 0x04, 'g', 'o', 'o', 'd' };
+    unsigned char bad1[] = { 0x01, 'b', 'a', 'd' };
+    unsigned char bad2[] = { 0x03, 'b', 'a', 'd', 0x00};
+    unsigned char bad3[] = { 0x03, 'b', 'a', 'd', 0x01, 'b', 'a', 'd'};
+    unsigned char bad4[] = { 0x03, 'b', 'a', 'd', 0x06, 'b', 'a', 'd'};
+
+    /* Create an initial SSL_CTX with no certificate configured */
+    ctx = SSL_CTX_new(TLS_server_method());
+    if (!TEST_ptr(ctx))
+        goto end;
+
+    /* the set_alpn functions return 0 (false) on success, non-zero (true) on failure */
+    if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, NULL, 2)))
+        goto end;
+    if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, good, 0)))
+        goto end;
+    if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, good, sizeof(good))))
+        goto end;
+    if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, good, 1)))
+        goto end;
+    if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad0, sizeof(bad0))))
+        goto end;
+    if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad1, sizeof(bad1))))
+        goto end;
+    if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad2, sizeof(bad2))))
+        goto end;
+    if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad3, sizeof(bad3))))
+        goto end;
+    if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad4, sizeof(bad4))))
+        goto end;
+
+    ssl = SSL_new(ctx);
+    if (!TEST_ptr(ssl))
+        goto end;
+
+    if (!TEST_false(SSL_set_alpn_protos(ssl, NULL, 2)))
+        goto end;
+    if (!TEST_false(SSL_set_alpn_protos(ssl, good, 0)))
+        goto end;
+    if (!TEST_false(SSL_set_alpn_protos(ssl, good, sizeof(good))))
+        goto end;
+    if (!TEST_true(SSL_set_alpn_protos(ssl, good, 1)))
+        goto end;
+    if (!TEST_true(SSL_set_alpn_protos(ssl, bad0, sizeof(bad0))))
+        goto end;
+    if (!TEST_true(SSL_set_alpn_protos(ssl, bad1, sizeof(bad1))))
+        goto end;
+    if (!TEST_true(SSL_set_alpn_protos(ssl, bad2, sizeof(bad2))))
+        goto end;
+    if (!TEST_true(SSL_set_alpn_protos(ssl, bad3, sizeof(bad3))))
+        goto end;
+    if (!TEST_true(SSL_set_alpn_protos(ssl, bad4, sizeof(bad4))))
+        goto end;
+
+    testresult = 1;
+
+end:
+    SSL_free(ssl);
+    SSL_CTX_free(ctx);
+    return testresult;
+}
+
+static int test_inherit_verify_param(void)
+{
+    int testresult = 0;
+
+    SSL_CTX *ctx = NULL;
+    X509_VERIFY_PARAM *cp = NULL;
+    SSL *ssl = NULL;
+    X509_VERIFY_PARAM *sp = NULL;
+    int hostflags = X509_CHECK_FLAG_NEVER_CHECK_SUBJECT;
+
+    ctx = SSL_CTX_new(TLS_server_method());
+    if (!TEST_ptr(ctx))
+        goto end;
+
+    cp = SSL_CTX_get0_param(ctx);
+    if (!TEST_ptr(cp))
+        goto end;
+    if (!TEST_int_eq(X509_VERIFY_PARAM_get_hostflags(cp), 0))
+        goto end;
+
+    X509_VERIFY_PARAM_set_hostflags(cp, hostflags);
+
+    ssl = SSL_new(ctx);
+    if (!TEST_ptr(ssl))
+        goto end;
+
+    sp = SSL_get0_param(ssl);
+    if (!TEST_ptr(sp))
+        goto end;
+    if (!TEST_int_eq(X509_VERIFY_PARAM_get_hostflags(sp), hostflags))
+        goto end;
+
+    testresult = 1;
+
+ end:
+    SSL_free(ssl);
+    SSL_CTX_free(ctx);
+
+    return testresult;
+}
 
 int setup_tests(void)
 {
@@ -6807,7 +6941,7 @@
 #else
     ADD_ALL_TESTS(test_tls13_psk, 4);
 #endif  /* OPENSSL_NO_PSK */
-    ADD_ALL_TESTS(test_custom_exts, 5);
+    ADD_ALL_TESTS(test_custom_exts, 6);
     ADD_TEST(test_stateless);
     ADD_TEST(test_pha_key_update);
 #else
@@ -6840,6 +6974,8 @@
 #ifndef OPENSSL_NO_TLS1_3
     ADD_TEST(test_sni_tls13);
 #endif
+    ADD_TEST(test_set_alpn);
+    ADD_TEST(test_inherit_verify_param);
     return 1;
 }
 
diff -Nru openssl-1.1.1k/test/ssltest_old.c openssl-1.1.1m/test/ssltest_old.c
--- openssl-1.1.1k/test/ssltest_old.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/ssltest_old.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
  * Copyright 2005 Nokia. All rights reserved.
  *
@@ -95,6 +95,7 @@
 static DH *get_dh512(void);
 static DH *get_dh1024(void);
 static DH *get_dh1024dsa(void);
+static DH *get_dh2048(void);
 #endif
 
 static char *psk_key = NULL;    /* by default PSK is not used */
@@ -641,6 +642,8 @@
             " -dhe1024      - use 1024 bit key (safe prime) for DHE (default, no-op)\n");
     fprintf(stderr,
             " -dhe1024dsa   - use 1024 bit key (with 160-bit subprime) for DHE\n");
+    fprintf(stderr,
+            " -dhe2048      - use 2048 bit key (rfc3526 pime) for DHE\n");
     fprintf(stderr, " -no_dhe       - disable DHE\n");
 #endif
 #ifndef OPENSSL_NO_EC
@@ -838,12 +841,14 @@
 
 static int write_session(const char *filename, SSL_SESSION *sess)
 {
-    BIO *f = BIO_new_file(filename, "w");
+    BIO *f;
 
     if (sess == NULL) {
         BIO_printf(bio_err, "No session information\n");
         return 0;
     }
+
+    f = BIO_new_file(filename, "w");
     if (f == NULL) {
         BIO_printf(bio_err, "Can't open session file %s\n", filename);
         ERR_print_errors(bio_err);
@@ -895,6 +900,7 @@
 #ifndef OPENSSL_NO_DH
     DH *dh;
     int dhe512 = 0, dhe1024dsa = 0;
+    int dhe2048 = 0;
 #endif
     int no_dhe = 0;
     int no_psk = 0;
@@ -990,6 +996,13 @@
             fprintf(stderr,
                     "ignoring -dhe512, since I'm compiled without DH\n");
 #endif
+        } else if (strcmp(*argv, "-dhe2048") == 0) {
+#ifndef OPENSSL_NO_DH
+            dhe2048 = 1;
+#else
+            fprintf(stderr,
+                    "ignoring -dhe2048, since I'm compiled without DH\n");
+#endif
         } else if (strcmp(*argv, "-dhe1024dsa") == 0) {
 #ifndef OPENSSL_NO_DH
             dhe1024dsa = 1;
@@ -1482,6 +1495,8 @@
             dh = get_dh1024dsa();
         } else if (dhe512)
             dh = get_dh512();
+        else if (dhe2048)
+            dh = get_dh2048();
         else
             dh = get_dh1024();
         SSL_CTX_set_tmp_dh(s_ctx, dh);
@@ -3019,6 +3034,34 @@
     DH_set_length(dh, 160);
     return dh;
 }
+
+static DH *get_dh2048(void)
+{
+    BIGNUM *p = NULL, *g = NULL;
+    DH *dh = NULL;
+
+    if ((dh = DH_new()) == NULL)
+        return NULL;
+
+    g = BN_new();
+    if (g == NULL || !BN_set_word(g, 2))
+        goto err;
+
+    p = BN_get_rfc3526_prime_2048(NULL);
+    if (p == NULL)
+        goto err;
+
+    if (!DH_set0_pqg(dh, p, NULL, g))
+        goto err;
+
+    return dh;
+
+ err:
+    DH_free(dh);
+    BN_free(p);
+    BN_free(g);
+    return NULL;
+}
 #endif
 
 #ifndef OPENSSL_NO_PSK
Binary files /home/bigeasy/tmp/2v8m8QG3ez/openssl-1.1.1k/test/testrsa_withattrs.der and /home/bigeasy/tmp/7D1rZVRsW7/openssl-1.1.1m/test/testrsa_withattrs.der differ
diff -Nru openssl-1.1.1k/test/testrsa_withattrs.pem openssl-1.1.1m/test/testrsa_withattrs.pem
--- openssl-1.1.1k/test/testrsa_withattrs.pem	1970-01-01 01:00:00.000000000 +0100
+++ openssl-1.1.1m/test/testrsa_withattrs.pem	2021-12-14 16:45:01.000000000 +0100
@@ -0,0 +1,29 @@
+-----BEGIN PRIVATE KEY-----
+MIIE+QIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDsh7QWxhftrqng
+RC3Ms+HxH2NFCX1sRoiIV4cYK2z0DQdEiNpFdpHlcs3weTuudcpr8XursodVFMTB
+eHjROhgwO/LT9xReEUiaoHJgfv6KcKcxEvntCjQkzGhkw03OH5VYdtTRAbwpwcYt
+groPiZ2STINpQOmFabzai+K+3rddwTGkkca3C5kY7KOMlnt9IuvmycksRqH6MPKz
+P5QbztlgY95rtra+OEzKLYQ1ux6hkaUlpxT5eGKfzYdccwKJWa0dUXyT/8F6rpTm
+Zbz3BxdKGAWMywaTfh5ywhNmVNTeIumxIRc3+PInn0rqKTaDrWylxiBdb3t27HxQ
+InDZmPwdAgMBAAECggEBAMTRrzN8JxEq1ES/tvStgodoPOyHlwxwLNB3NP0RtZnm
+9XM8BZTjs0egnmlKGDV14riruuMGrcJIg+kR3EcN9m68k7V51kLoUugINuTBCAIe
+96DIT5vFb9pnFT8znRy1/0obp787mF2O1t+r9jNTqgDBFmCRGUBg2jtpR4bYQPEL
+ZjXMDPcsmOlmbBdsyQvjlOHqXjCoUWwOCBEZdtaLzxaOPrBW5Jh2h3Xz1pV3NdZ/
+xufAYRhpJamPNiSipRehBZAeQP2ZAyHj/5x3tgEcA+C04Ki8NvuwJx/6T/lGKD+1
+x3DKsniNi6fEbGlpST/Zp1GY4WyVPcrLa8JxyO+UagECgYEA+gvBBI+LSK5enPXu
+WooEQP17fKzdZG7Cic8TfTPbtBIcXjNQFLHjFoBNk+TBFCjZma7L+fEcKcDm+Bg1
+qa4xihOP6BoQqHXZZNZ+9ZU96MPmI9Zb60CMG9lM1VVhSqrm2n3Q+tefod/a2bQk
+oz8QsdpsUFqVFCF5l+Tb6lp2QN0CgYEA8imPEml6LG35snBY1H6t0ASCHT1oFdHP
+o01WKQas/tuLO+pMfZrA0zLZBExxZuUJloC6COsTcOrlK+hGM60Ab6TgSPbUvYqH
+8yMV7SYLvheEngqIiFExmHg79mxnys3Rgv9KMxAV2Ip2wBrBMwUOaURU9pUKXlIN
+xiaUuevSVEECgYEA0Dbrcs3JUSuKM7AC3DfjlO6/XrFf5hrpOfJKq058m/Uc1EBs
+Zd8/V2RdtVKeiRf/Ix9QUYA6UHaGnn8iaHpaXD0v7zmNN4pzDaojrIKrO+GtCZid
+kEd+pE4N0fO4AYJQnA567/aPwi7zQaflfl6smz1kRoE3dLzvUNHNYtgTcq0CgYAm
+Op1VgMVCwlHK86VyVlVGI5AO4aTO3QJ0ez8A1wb0bOA8Iy7UHVwXe017Oj4kyj+L
+POMhiUrWZp6rIc4DVmpdNaAapKzNB1OS9JT/jSQJbFkJQgxvyLGVqlV8/3wbLgbH
+MVobWYy5VJKOnSqmzUOLJrhq/PhYD4gRIgIUn7/igQKBgQCptqrREOq9fXDEpozC
+39TL4vDrKJWpB1uK6pBEjgEVD/+tcfziVN40j5hnNFDUu/8kxxp9/4w8mPjdJ0CF
+hWIvrXasjnnFehy6IewWCljNH5CfOM64rDoXaF+ESIM4rLBHbQ8KYvaKkMjOcdNB
+JG1sRWVU01AwEhnvxS1zbyBtiqA4MDYGCCqFAwIJAwgBMSoEKBqiSOXm8r5I7hEA
++gglN/s0bbRCnzopEhuEorpcnDXrktVtjQrmMi0=
+-----END PRIVATE KEY-----
diff -Nru openssl-1.1.1k/test/testutil/format_output.c openssl-1.1.1m/test/testutil/format_output.c
--- openssl-1.1.1k/test/testutil/format_output.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/testutil/format_output.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -107,8 +107,10 @@
             if (diff && i > 0)
                 test_printf_stderr("% 4s    %s\n", "", bdiff);
         }
-        m1 += n1;
-        m2 += n2;
+        if (m1 != NULL)
+            m1 += n1;
+        if (m2 != NULL)
+            m2 += n2;
         l1 -= n1;
         l2 -= n2;
         cnt += width;
@@ -495,8 +497,10 @@
             if (diff && i > 0)
                 test_printf_stderr("% 4s  %s\n", "", bdiff);
         }
-        m1 += n1;
-        m2 += n2;
+        if (m1 != NULL)
+            m1 += n1;
+        if (m2 != NULL)
+            m2 += n2;
         l1 -= n1;
         l2 -= n2;
         cnt += bytes;
diff -Nru openssl-1.1.1k/test/testutil/tests.c openssl-1.1.1m/test/testutil/tests.c
--- openssl-1.1.1k/test/testutil/tests.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/testutil/tests.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2017 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -393,8 +393,8 @@
 
     if (a != NULL && BN_is_word(a, w))
         return 1;
-    bw = BN_new();
-    BN_set_word(bw, w);
+    if ((bw = BN_new()) != NULL)
+        BN_set_word(bw, w);
     test_fail_bignum_message(NULL, file, line, "BIGNUM", bns, ws, "==", a, bw);
     BN_free(bw);
     return 0;
@@ -407,10 +407,10 @@
 
     if (a != NULL && BN_abs_is_word(a, w))
         return 1;
-    bw = BN_new();
-    aa = BN_dup(a);
-    BN_set_negative(aa, 0);
-    BN_set_word(bw, w);
+    if ((aa = BN_dup(a)) != NULL)
+        BN_set_negative(aa, 0);
+    if ((bw = BN_new()) != NULL)
+        BN_set_word(bw, w);
     test_fail_bignum_message(NULL, file, line, "BIGNUM", bns, ws, "abs==",
                              aa, bw);
     BN_free(bw);
diff -Nru openssl-1.1.1k/test/x509_time_test.c openssl-1.1.1m/test/x509_time_test.c
--- openssl-1.1.1k/test/x509_time_test.c	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/test/x509_time_test.c	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -330,10 +330,12 @@
 
     /* if t is not NULL but expected_string is NULL, it is an 'OK' case too */
     if (t != NULL && x509_format_tests[idx].expected_string) {
-        if (!TEST_str_eq((const char *)t->data,
-                    x509_format_tests[idx].expected_string)) {
-            TEST_info("test_x509_time(%d) failed: expected_string %s, got %s\n",
-                    idx, x509_format_tests[idx].expected_string, t->data);
+        if (!TEST_mem_eq((const char *)t->data, t->length,
+                    x509_format_tests[idx].expected_string,
+                    strlen(x509_format_tests[idx].expected_string))) {
+            TEST_info("test_x509_time(%d) failed: expected_string %s, got %.*s\n",
+                    idx, x509_format_tests[idx].expected_string, t->length,
+                    t->data);
             goto out;
         }
     }
diff -Nru openssl-1.1.1k/util/mkdir-p.pl openssl-1.1.1m/util/mkdir-p.pl
--- openssl-1.1.1k/util/mkdir-p.pl	2021-03-25 14:28:38.000000000 +0100
+++ openssl-1.1.1m/util/mkdir-p.pl	2021-12-14 16:45:01.000000000 +0100
@@ -1,5 +1,5 @@
 #! /usr/bin/env perl
-# Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
+# Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
 #
 # Licensed under the OpenSSL license (the "License").  You may not use
 # this file except in compliance with the License.  You can obtain a copy
@@ -34,11 +34,12 @@
   }
 
   unless (mkdir($dir, 0777)) {
+    local($err) = $!;
     if (-d $dir) {
       # We raced against another instance doing the same thing.
       return;
     }
-    die "Cannot create directory $dir: $!\n";
+    die "Cannot create directory $dir: $err\n";
   }
   print "created directory `$dir'\n";
 }

Reply to: