Module Name:    src
Committed By:   christos
Date:           Sat Aug 18 08:59:05 UTC 2018

Modified Files:
        src/crypto/external/bsd/openssl/dist: CHANGES Configure NEWS README
        src/crypto/external/bsd/openssl/dist/apps: ca.c ocsp.c s_client.c
            s_server.c speed.c
        src/crypto/external/bsd/openssl/dist/crypto: arm_arch.h armcap.c
            cryptlib.c ex_data.c
        src/crypto/external/bsd/openssl/dist/crypto/asn1: a_strex.c asn_mime.c
            tasn_enc.c
        src/crypto/external/bsd/openssl/dist/crypto/bio: b_sock.c bss_log.c
        src/crypto/external/bsd/openssl/dist/crypto/bn: bn_exp.c bn_lcl.h
            bn_lib.c bn_mont.c
        src/crypto/external/bsd/openssl/dist/crypto/dso: dso_dlfcn.c
        src/crypto/external/bsd/openssl/dist/crypto/ec: ec2_smpl.c ec_ameth.c
            ec_lcl.h ec_lib.c ecp_smpl.c
        src/crypto/external/bsd/openssl/dist/crypto/engine: eng_lib.c
        src/crypto/external/bsd/openssl/dist/crypto/rsa: rsa_oaep.c rsa_pk1.c
        src/crypto/external/bsd/openssl/dist/crypto/ui: ui_openssl.c
        src/crypto/external/bsd/openssl/dist/crypto/x509: x509_vfy.c
        src/crypto/external/bsd/openssl/dist/doc/apps: genpkey.pod
        src/crypto/external/bsd/openssl/dist/doc/crypto: EVP_DigestInit.pod
        src/crypto/external/bsd/openssl/dist/ssl: ssl_ciph.c ssl_lib.c
            ssl_locl.h ssl_sess.c t1_lib.c
        src/crypto/external/bsd/openssl/dist/test: evp_test.c
        src/crypto/external/bsd/openssl/dist/util: mkdef.pl
Removed Files:
        src/crypto/external/bsd/openssl/dist/Configurations: 90-team.conf

Log Message:
merge conflicts


To generate a diff of this commit:
cvs rdiff -u -r1.15 -r1.16 src/crypto/external/bsd/openssl/dist/CHANGES \
    src/crypto/external/bsd/openssl/dist/NEWS \
    src/crypto/external/bsd/openssl/dist/README
cvs rdiff -u -r1.19 -r1.20 src/crypto/external/bsd/openssl/dist/Configure
cvs rdiff -u -r1.1.1.1 -r0 \
    src/crypto/external/bsd/openssl/dist/Configurations/90-team.conf
cvs rdiff -u -r1.15 -r1.16 src/crypto/external/bsd/openssl/dist/apps/ca.c \
    src/crypto/external/bsd/openssl/dist/apps/s_client.c \
    src/crypto/external/bsd/openssl/dist/apps/s_server.c
cvs rdiff -u -r1.14 -r1.15 src/crypto/external/bsd/openssl/dist/apps/ocsp.c
cvs rdiff -u -r1.13 -r1.14 src/crypto/external/bsd/openssl/dist/apps/speed.c
cvs rdiff -u -r1.4 -r1.5 \
    src/crypto/external/bsd/openssl/dist/crypto/arm_arch.h
cvs rdiff -u -r1.5 -r1.6 src/crypto/external/bsd/openssl/dist/crypto/armcap.c
cvs rdiff -u -r1.10 -r1.11 \
    src/crypto/external/bsd/openssl/dist/crypto/cryptlib.c
cvs rdiff -u -r1.3 -r1.4 \
    src/crypto/external/bsd/openssl/dist/crypto/ex_data.c
cvs rdiff -u -r1.6 -r1.7 \
    src/crypto/external/bsd/openssl/dist/crypto/asn1/a_strex.c
cvs rdiff -u -r1.9 -r1.10 \
    src/crypto/external/bsd/openssl/dist/crypto/asn1/asn_mime.c
cvs rdiff -u -r1.7 -r1.8 \
    src/crypto/external/bsd/openssl/dist/crypto/asn1/tasn_enc.c
cvs rdiff -u -r1.8 -r1.9 \
    src/crypto/external/bsd/openssl/dist/crypto/bio/b_sock.c
cvs rdiff -u -r1.7 -r1.8 \
    src/crypto/external/bsd/openssl/dist/crypto/bio/bss_log.c
cvs rdiff -u -r1.15 -r1.16 \
    src/crypto/external/bsd/openssl/dist/crypto/bn/bn_exp.c
cvs rdiff -u -r1.6 -r1.7 \
    src/crypto/external/bsd/openssl/dist/crypto/bn/bn_lcl.h
cvs rdiff -u -r1.7 -r1.8 \
    src/crypto/external/bsd/openssl/dist/crypto/bn/bn_lib.c
cvs rdiff -u -r1.9 -r1.10 \
    src/crypto/external/bsd/openssl/dist/crypto/bn/bn_mont.c
cvs rdiff -u -r1.11 -r1.12 \
    src/crypto/external/bsd/openssl/dist/crypto/dso/dso_dlfcn.c
cvs rdiff -u -r1.5 -r1.6 \
    src/crypto/external/bsd/openssl/dist/crypto/ec/ec2_smpl.c \
    src/crypto/external/bsd/openssl/dist/crypto/ec/ec_ameth.c
cvs rdiff -u -r1.3 -r1.4 \
    src/crypto/external/bsd/openssl/dist/crypto/ec/ec_lcl.h \
    src/crypto/external/bsd/openssl/dist/crypto/ec/ec_lib.c
cvs rdiff -u -r1.6 -r1.7 \
    src/crypto/external/bsd/openssl/dist/crypto/ec/ecp_smpl.c
cvs rdiff -u -r1.3 -r1.4 \
    src/crypto/external/bsd/openssl/dist/crypto/engine/eng_lib.c
cvs rdiff -u -r1.6 -r1.7 \
    src/crypto/external/bsd/openssl/dist/crypto/rsa/rsa_oaep.c
cvs rdiff -u -r1.4 -r1.5 \
    src/crypto/external/bsd/openssl/dist/crypto/rsa/rsa_pk1.c
cvs rdiff -u -r1.10 -r1.11 \
    src/crypto/external/bsd/openssl/dist/crypto/ui/ui_openssl.c
cvs rdiff -u -r1.12 -r1.13 \
    src/crypto/external/bsd/openssl/dist/crypto/x509/x509_vfy.c
cvs rdiff -u -r1.4 -r1.5 \
    src/crypto/external/bsd/openssl/dist/doc/apps/genpkey.pod
cvs rdiff -u -r1.4 -r1.5 \
    src/crypto/external/bsd/openssl/dist/doc/crypto/EVP_DigestInit.pod
cvs rdiff -u -r1.14 -r1.15 \
    src/crypto/external/bsd/openssl/dist/ssl/ssl_ciph.c
cvs rdiff -u -r1.11 -r1.12 src/crypto/external/bsd/openssl/dist/ssl/ssl_lib.c
cvs rdiff -u -r1.17 -r1.18 \
    src/crypto/external/bsd/openssl/dist/ssl/ssl_locl.h
cvs rdiff -u -r1.5 -r1.6 src/crypto/external/bsd/openssl/dist/ssl/ssl_sess.c
cvs rdiff -u -r1.25 -r1.26 src/crypto/external/bsd/openssl/dist/ssl/t1_lib.c
cvs rdiff -u -r1.2 -r1.3 src/crypto/external/bsd/openssl/dist/test/evp_test.c
cvs rdiff -u -r1.7 -r1.8 src/crypto/external/bsd/openssl/dist/util/mkdef.pl

Please note that diffs are not public domain; they are subject to the
copyright notices on the relevant files.

Modified files:

Index: src/crypto/external/bsd/openssl/dist/CHANGES
diff -u src/crypto/external/bsd/openssl/dist/CHANGES:1.15 src/crypto/external/bsd/openssl/dist/CHANGES:1.16
--- src/crypto/external/bsd/openssl/dist/CHANGES:1.15	Fri Apr  6 19:04:43 2018
+++ src/crypto/external/bsd/openssl/dist/CHANGES	Sat Aug 18 04:59:03 2018
@@ -7,6 +7,81 @@
  https://github.com/openssl/openssl/commits/ and pick the appropriate
  release branch.
 
+ Changes between 1.1.0h and 1.1.0i [14 Aug 2018]
+
+  *) Client DoS due to large DH parameter
+
+     During key agreement in a TLS handshake using a DH(E) based ciphersuite a
+     malicious server can send a very large prime value to the client. This will
+     cause the client to spend an unreasonably long period of time generating a
+     key for this prime resulting in a hang until the client has finished. This
+     could be exploited in a Denial Of Service attack.
+
+     This issue was reported to OpenSSL on 5th June 2018 by Guido Vranken
+     (CVE-2018-0732)
+     [Guido Vranken]
+
+  *) Cache timing vulnerability in RSA Key Generation
+
+     The OpenSSL RSA Key generation algorithm has been shown to be vulnerable to
+     a cache timing side channel attack. An attacker with sufficient access to
+     mount cache timing attacks during the RSA key generation process could
+     recover the private key.
+
+     This issue was reported to OpenSSL on 4th April 2018 by Alejandro Cabrera
+     Aldaya, Billy Brumley, Cesar Pereida Garcia and Luis Manuel Alvarez Tapia.
+     (CVE-2018-0737)
+     [Billy Brumley]
+
+  *) Make EVP_PKEY_asn1_new() a bit stricter about its input.  A NULL pem_str
+     parameter is no longer accepted, as it leads to a corrupt table.  NULL
+     pem_str is reserved for alias entries only.
+     [Richard Levitte]
+
+  *) Revert blinding in ECDSA sign and instead make problematic addition
+     length-invariant. Switch even to fixed-length Montgomery multiplication.
+     [Andy Polyakov]
+
+  *) Change generating and checking of primes so that the error rate of not
+     being prime depends on the intended use based on the size of the input.
+     For larger primes this will result in more rounds of Miller-Rabin.
+     The maximal error rate for primes with more than 1080 bits is lowered
+     to 2^-128.
+     [Kurt Roeckx, Annie Yousar]
+
+  *) Increase the number of Miller-Rabin rounds for DSA key generating to 64.
+     [Kurt Roeckx]
+
+  *) Add blinding to ECDSA and DSA signatures to protect against side channel
+     attacks discovered by Keegan Ryan (NCC Group).
+     [Matt Caswell]
+
+  *) When unlocking a pass phrase protected PEM file or PKCS#8 container, we
+     now allow empty (zero character) pass phrases.
+     [Richard Levitte]
+
+  *) Certificate time validation (X509_cmp_time) enforces stricter
+     compliance with RFC 5280. Fractional seconds and timezone offsets
+     are no longer allowed.
+     [Emilia Käsper]
+
+  *) Fixed a text canonicalisation bug in CMS
+
+     Where a CMS detached signature is used with text content the text goes
+     through a canonicalisation process first prior to signing or verifying a
+     signature. This process strips trailing space at the end of lines, converts
+     line terminators to CRLF and removes additional trailing line terminators
+     at the end of a file. A bug in the canonicalisation process meant that
+     some characters, such as form-feed, were incorrectly treated as whitespace
+     and removed. This is contrary to the specification (RFC5485). This fix
+     could mean that detached text data signed with an earlier version of
+     OpenSSL 1.1.0 may fail to verify using the fixed version, or text data
+     signed with a fixed OpenSSL may fail to verify with an earlier version of
+     OpenSSL 1.1.0. A workaround is to only verify the canonicalised text data
+     and use the "-binary" flag (for the "cms" command line application) or set
+     the SMIME_BINARY/PKCS7_BINARY/CMS_BINARY flags (if using CMS_verify()).
+     [Matt Caswell]
+
  Changes between 1.1.0g and 1.1.0h [27 Mar 2018]
 
   *) Constructed ASN.1 types with a recursive definition could exceed the stack
Index: src/crypto/external/bsd/openssl/dist/NEWS
diff -u src/crypto/external/bsd/openssl/dist/NEWS:1.15 src/crypto/external/bsd/openssl/dist/NEWS:1.16
--- src/crypto/external/bsd/openssl/dist/NEWS:1.15	Fri Apr  6 19:04:43 2018
+++ src/crypto/external/bsd/openssl/dist/NEWS	Sat Aug 18 04:59:03 2018
@@ -5,6 +5,11 @@
   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.0h and OpenSSL 1.1.0i [14 Aug 2018]
+
+      o Client DoS due to large DH parameter (CVE-2018-0732)
+      o Cache timing vulnerability in RSA Key Generation (CVE-2018-0737)
+
   Major changes between OpenSSL 1.1.0g and OpenSSL 1.1.0h [27 Mar 2018]
 
       o Constructed ASN.1 types with a recursive definition could exceed the
Index: src/crypto/external/bsd/openssl/dist/README
diff -u src/crypto/external/bsd/openssl/dist/README:1.15 src/crypto/external/bsd/openssl/dist/README:1.16
--- src/crypto/external/bsd/openssl/dist/README:1.15	Fri Apr  6 19:04:43 2018
+++ src/crypto/external/bsd/openssl/dist/README	Sat Aug 18 04:59:03 2018
@@ -1,7 +1,7 @@
 
- OpenSSL 1.1.0h 27 Mar 2018
+ OpenSSL 1.1.0i 14 Aug 2018
 
- Copyright (c) 1998-2016 The OpenSSL Project
+ Copyright (c) 1998-2018 The OpenSSL Project
  Copyright (c) 1995-1998 Eric A. Young, Tim J. Hudson
  All rights reserved.
 

Index: src/crypto/external/bsd/openssl/dist/Configure
diff -u src/crypto/external/bsd/openssl/dist/Configure:1.19 src/crypto/external/bsd/openssl/dist/Configure:1.20
--- src/crypto/external/bsd/openssl/dist/Configure:1.19	Fri Apr  6 19:04:43 2018
+++ src/crypto/external/bsd/openssl/dist/Configure	Sat Aug 18 04:59:03 2018
@@ -20,6 +20,9 @@ use OpenSSL::Glob;
 
 # see INSTALL for instructions.
 
+my $orig_death_handler = $SIG{__DIE__};
+$SIG{__DIE__} = \&death_handler;
+
 my $usage="Usage: Configure [no-<cipher> ...] [enable-<cipher> ...] [-Dxxx] [-lxxx] [-Lxxx] [-fxxx] [-Kxxx] [no-hw-xxx|no-hw] [[no-]threads] [[no-]shared] [[no-]zlib|zlib-dynamic] [no-asm] [no-dso] [no-egd] [sctp] [386] [--prefix=DIR] [--openssldir=OPENSSLDIR] [--with-xxx[=vvv]] [--config=FILE] os/compiler[:flags]\n";
 
 # Options:
@@ -756,21 +759,21 @@ while (@argvcopy)
 		else
 			{ $config{options} .= " ".$_; }
 		}
+	}
 
-        if (defined($config{api}) && !exists $apitable->{$config{api}}) {
-		die "***** Unsupported api compatibility level: $config{api}\n",
-        }
+if (defined($config{api}) && !exists $apitable->{$config{api}}) {
+	die "***** Unsupported api compatibility level: $config{api}\n",
+}
 
-	if (keys %deprecated_options)
-		{
-		warn "***** Deprecated options: ",
-			join(", ", keys %deprecated_options), "\n";
-		}
-	if (keys %unsupported_options)
-		{
-		die "***** Unsupported options: ",
-			join(", ", keys %unsupported_options), "\n";
-		}
+if (keys %deprecated_options)
+	{
+	warn "***** Deprecated options: ",
+		join(", ", keys %deprecated_options), "\n";
+	}
+if (keys %unsupported_options)
+	{
+	die "***** Unsupported options: ",
+		join(", ", keys %unsupported_options), "\n";
 	}
 
 if ($libs =~ /(^|\s)-Wl,-rpath,/
@@ -908,11 +911,12 @@ if ($d) {
 	$target = $t;
     }
 }
+
+&usage if !$table{$target} || $table{$target}->{template};
+
 $config{target} = $target;
 my %target = resolve_config($target);
 
-&usage if (!%target || $target{template});
-
 my %conf_files = map { $_ => 1 } (@{$target{_conf_fname_int}});
 $config{conf_files} = [ sort keys %conf_files ];
 %target = ( %{$table{DEFAULTS}}, %target );
@@ -1215,8 +1219,10 @@ if ($^O ne "VMS") {
 
     if (!$disabled{makedepend}) {
 	# We know that GNU C version 3 and up as well as all clang
-	# versions support dependency generation
-	if ($predefined{__GNUC__} >= 3) {
+	# versions support dependency generation, but Xcode did not
+	# handle $cc -M before clang support (but claims __GNUC__ = 3)
+	if (($predefined{__GNUC__} // -1) >= 3
+		&& !($predefined{__APPLE_CC__} && !$predefined{__clang__})) {
 	    $config{makedepprog} = $cc;
 	} else {
 	    $config{makedepprog} = which('makedepend');
@@ -2125,6 +2131,8 @@ my %builders = (
 
 $builders{$builder}->($builder_platform, @builder_opts);
 
+$SIG{__DIE__} = $orig_death_handler;
+
 print <<"EOF";
 
 Configured for $target.
@@ -2153,6 +2161,24 @@ exit(0);
 # Helpers and utility functions
 #
 
+# Death handler, to print a helpful message in case of failure #######
+#
+sub death_handler {
+    die @_ if $^S;              # To prevent the added message in eval blocks
+    my $build_file = $target{build_file} // "build file";
+    my @message = ( <<"_____", @_ );
+
+Failure!  $build_file wasn't produced.
+Please read INSTALL and associated NOTES files.  You may also have to look over
+your available compiler tool chain or change your configuration.
+
+_____
+
+    # Dying is terminal, so it's ok to reset the signal handler here.
+    $SIG{__DIE__} = $orig_death_handler;
+    die @message;
+}
+
 # Configuration file reading #########################################
 
 # Note: All of the helper functions are for lazy evaluation.  They all

Index: src/crypto/external/bsd/openssl/dist/apps/ca.c
diff -u src/crypto/external/bsd/openssl/dist/apps/ca.c:1.15 src/crypto/external/bsd/openssl/dist/apps/ca.c:1.16
--- src/crypto/external/bsd/openssl/dist/apps/ca.c:1.15	Fri Apr  6 19:04:43 2018
+++ src/crypto/external/bsd/openssl/dist/apps/ca.c	Sat Aug 18 04:59:04 2018
@@ -725,10 +725,10 @@ end_of_options:
 
     /*****************************************************************/
     if (req || gencrl) {
-        /* FIXME: Is it really always text? */
-        Sout = bio_open_default(outfile, 'w', FORMAT_TEXT);
-        if (Sout == NULL)
-            goto end;
+        if (spkac_file != NULL) {
+            output_der = 1;
+            batch = 1;
+        }
     }
 
     if (md == NULL
@@ -872,10 +872,6 @@ end_of_options:
                     BIO_printf(bio_err, "Memory allocation failure\n");
                     goto end;
                 }
-                if (outfile) {
-                    output_der = 1;
-                    batch = 1;
-                }
             }
         }
         if (ss_cert_file != NULL) {
@@ -929,10 +925,13 @@ end_of_options:
             if (j > 0) {
                 total_done++;
                 BIO_printf(bio_err, "\n");
-                if (!BN_add_word(serial, 1))
+                if (!BN_add_word(serial, 1)) {
+                    X509_free(x);
                     goto end;
+                }
                 if (!sk_X509_push(cert_sk, x)) {
                     BIO_printf(bio_err, "Memory allocation failure\n");
+                    X509_free(x);
                     goto end;
                 }
             }
@@ -1017,6 +1016,11 @@ end_of_options:
             if (verbose)
                 BIO_printf(bio_err, "writing %s\n", buf[2]);
 
+            Sout = bio_open_default(outfile, 'w',
+                                    output_der ? FORMAT_ASN1 : FORMAT_TEXT);
+            if (Sout == NULL)
+                goto end;
+
             Cout = BIO_new_file(buf[2], "w");
             if (Cout == NULL) {
                 perror(buf[2]);
@@ -1025,6 +1029,8 @@ end_of_options:
             write_new_certificate(Cout, xi, 0, notext);
             write_new_certificate(Sout, xi, output_der, notext);
             BIO_free_all(Cout);
+            BIO_free_all(Sout);
+            Sout = NULL;
         }
 
         if (sk_X509_num(cert_sk)) {
@@ -1173,6 +1179,11 @@ end_of_options:
         if (!do_X509_CRL_sign(crl, pkey, dgst, sigopts))
             goto end;
 
+        Sout = bio_open_default(outfile, 'w',
+                                output_der ? FORMAT_ASN1 : FORMAT_TEXT);
+        if (Sout == NULL)
+            goto end;
+
         PEM_write_bio_X509_CRL(Sout, crl);
 
         if (crlnumberfile != NULL) /* Rename the crlnumber file */
Index: src/crypto/external/bsd/openssl/dist/apps/s_client.c
diff -u src/crypto/external/bsd/openssl/dist/apps/s_client.c:1.15 src/crypto/external/bsd/openssl/dist/apps/s_client.c:1.16
--- src/crypto/external/bsd/openssl/dist/apps/s_client.c:1.15	Fri Apr  6 19:04:44 2018
+++ src/crypto/external/bsd/openssl/dist/apps/s_client.c	Sat Aug 18 04:59:04 2018
@@ -593,7 +593,8 @@ OPTIONS s_client_options[] = {
      "Disable name checks when matching DANE-EE(3) TLSA records"},
     {"reconnect", OPT_RECONNECT, '-',
      "Drop and re-make the connection with the same Session-ID"},
-    {"showcerts", OPT_SHOWCERTS, '-', "Show all certificates in the chain"},
+    {"showcerts", OPT_SHOWCERTS, '-',
+     "Show all certificates sent by the server"},
     {"debug", OPT_DEBUG, '-', "Extra output"},
     {"msg", OPT_MSG, '-', "Show protocol messages"},
     {"msgfile", OPT_MSGFILE, '>',
@@ -2124,8 +2125,7 @@ int s_client_main(int argc, char **argv)
             goto shut;
         }
 
-        if ((SSL_version(con) == DTLS1_VERSION) &&
-            DTLSv1_get_timeout(con, &timeout))
+        if (SSL_is_dtls(con) && DTLSv1_get_timeout(con, &timeout))
             timeoutp = &timeout;
         else
             timeoutp = NULL;
@@ -2245,10 +2245,8 @@ int s_client_main(int argc, char **argv)
             }
         }
 
-        if ((SSL_version(con) == DTLS1_VERSION)
-            && DTLSv1_handle_timeout(con) > 0) {
+        if (SSL_is_dtls(con) && DTLSv1_handle_timeout(con) > 0)
             BIO_printf(bio_err, "TIMEOUT occurred\n");
-        }
 
         if (!ssl_pending && FD_ISSET(SSL_get_fd(con), &writefds)) {
             k = SSL_write(con, &(cbuf[cbuf_off]), (unsigned int)cbuf_len);
Index: src/crypto/external/bsd/openssl/dist/apps/s_server.c
diff -u src/crypto/external/bsd/openssl/dist/apps/s_server.c:1.15 src/crypto/external/bsd/openssl/dist/apps/s_server.c:1.16
--- src/crypto/external/bsd/openssl/dist/apps/s_server.c:1.15	Fri Apr  6 19:04:44 2018
+++ src/crypto/external/bsd/openssl/dist/apps/s_server.c	Sat Aug 18 04:59:04 2018
@@ -2012,9 +2012,7 @@ static int sv_body(int s, int stype, uns
     SSL *con = NULL;
     BIO *sbio;
     struct timeval timeout;
-#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
-    struct timeval tv;
-#else
+#if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS))
     struct timeval *timeoutp;
 #endif
 
@@ -2154,26 +2152,23 @@ static int sv_body(int s, int stype, uns
              * second and check for any keypress. In a proper Windows
              * application we wouldn't do this because it is inefficient.
              */
-            tv.tv_sec = 1;
-            tv.tv_usec = 0;
-            i = select(width, (void *)&readfds, NULL, NULL, &tv);
+            timeout.tv_sec = 1;
+            timeout.tv_usec = 0;
+            i = select(width, (void *)&readfds, NULL, NULL, &timeout);
             if (has_stdin_waiting())
                 read_from_terminal = 1;
             if ((i < 0) || (!i && !read_from_terminal))
                 continue;
 #else
-            if ((SSL_version(con) == DTLS1_VERSION) &&
-                DTLSv1_get_timeout(con, &timeout))
+            if (SSL_is_dtls(con) && DTLSv1_get_timeout(con, &timeout))
                 timeoutp = &timeout;
             else
                 timeoutp = NULL;
 
             i = select(width, (void *)&readfds, NULL, NULL, timeoutp);
 
-            if ((SSL_version(con) == DTLS1_VERSION)
-                && DTLSv1_handle_timeout(con) > 0) {
+            if ((SSL_is_dtls(con)) && DTLSv1_handle_timeout(con) > 0)
                 BIO_printf(bio_err, "TIMEOUT occurred\n");
-            }
 
             if (i <= 0)
                 continue;

Index: src/crypto/external/bsd/openssl/dist/apps/ocsp.c
diff -u src/crypto/external/bsd/openssl/dist/apps/ocsp.c:1.14 src/crypto/external/bsd/openssl/dist/apps/ocsp.c:1.15
--- src/crypto/external/bsd/openssl/dist/apps/ocsp.c:1.14	Fri Apr  6 19:04:43 2018
+++ src/crypto/external/bsd/openssl/dist/apps/ocsp.c	Sat Aug 18 04:59:04 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2001-2018 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
@@ -639,7 +639,6 @@ int ocsp_main(int argc, char **argv)
                    OCSP_response_status_str(i), i);
         if (ignore_err)
             goto redo_accept;
-        ret = 0;
         goto end;
     }
 

Index: src/crypto/external/bsd/openssl/dist/apps/speed.c
diff -u src/crypto/external/bsd/openssl/dist/apps/speed.c:1.13 src/crypto/external/bsd/openssl/dist/apps/speed.c:1.14
--- src/crypto/external/bsd/openssl/dist/apps/speed.c:1.13	Fri Apr  6 19:04:44 2018
+++ src/crypto/external/bsd/openssl/dist/apps/speed.c	Sat Aug 18 04:59:04 2018
@@ -129,13 +129,6 @@
 #define BUFSIZE (1024*16+1)
 #define MAX_MISALIGNMENT 63
 
-#define ALGOR_NUM       30
-#define SIZE_NUM        6
-#define PRIME_NUM       3
-#define RSA_NUM         7
-#define DSA_NUM         3
-
-#define EC_NUM          17
 #define MAX_ECDH_SIZE   256
 #define MISALIGN        64
 
@@ -144,37 +137,6 @@ static volatile int run = 0;
 static int mr = 0;
 static int usertime = 1;
 
-typedef void *(*kdf_fn) (
-        const void *in, size_t inlen, void *out, size_t *xoutlen);
-
-typedef struct loopargs_st {
-    ASYNC_JOB *inprogress_job;
-    ASYNC_WAIT_CTX *wait_ctx;
-    unsigned char *buf;
-    unsigned char *buf2;
-    unsigned char *buf_malloc;
-    unsigned char *buf2_malloc;
-    unsigned int siglen;
-#ifndef OPENSSL_NO_RSA
-    RSA *rsa_key[RSA_NUM];
-#endif
-#ifndef OPENSSL_NO_DSA
-    DSA *dsa_key[DSA_NUM];
-#endif
-#ifndef OPENSSL_NO_EC
-    EC_KEY *ecdsa[EC_NUM];
-    EC_KEY *ecdh_a[EC_NUM];
-    EC_KEY *ecdh_b[EC_NUM];
-    unsigned char *secret_a;
-    unsigned char *secret_b;
-    size_t      outlen;
-    kdf_fn      kdf;
-#endif
-    EVP_CIPHER_CTX *ctx;
-    HMAC_CTX *hctx;
-    GCM128_CONTEXT *gcm_ctx;
-} loopargs_t;
-
 #ifndef OPENSSL_NO_MD2
 static int EVP_Digest_MD2_loop(void *args);
 #endif
@@ -227,7 +189,6 @@ static int ECDSA_sign_loop(void *args);
 static int ECDSA_verify_loop(void *args);
 static int ECDH_compute_key_loop(void *args);
 #endif
-static int run_benchmark(int async_jobs, int (*loop_function)(void *), loopargs_t *loopargs);
 
 static double Time_F(int s);
 static void print_message(const char *s, long num, int length);
@@ -238,32 +199,10 @@ static void print_result(int alg, int ru
 static int do_multi(int multi);
 #endif
 
-static const char *names[ALGOR_NUM] = {
-    "md2", "mdc2", "md4", "md5", "hmac(md5)", "sha1", "rmd160", "rc4",
-    "des cbc", "des ede3", "idea cbc", "seed cbc",
-    "rc2 cbc", "rc5-32/12 cbc", "blowfish cbc", "cast cbc",
-    "aes-128 cbc", "aes-192 cbc", "aes-256 cbc",
-    "camellia-128 cbc", "camellia-192 cbc", "camellia-256 cbc",
-    "evp", "sha256", "sha512", "whirlpool",
-    "aes-128 ige", "aes-192 ige", "aes-256 ige", "ghash"
-};
-
-static double results[ALGOR_NUM][SIZE_NUM];
-
-static const int lengths[SIZE_NUM] = {
+static const int lengths[] = {
     16, 64, 256, 1024, 8 * 1024, 16 * 1024
 };
-
-#ifndef OPENSSL_NO_RSA
-static double rsa_results[RSA_NUM][2];
-#endif
-#ifndef OPENSSL_NO_DSA
-static double dsa_results[DSA_NUM][2];
-#endif
-#ifndef OPENSSL_NO_EC
-static double ecdsa_results[EC_NUM][2];
-static double ecdh_results[EC_NUM][1];
-#endif
+#define SIZE_NUM       OSSL_NELEM(lengths)
 
 #if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_EC)
 static const char rnd_seed[] =
@@ -348,9 +287,14 @@ static double Time_F(int s)
 
 static void multiblock_speed(const EVP_CIPHER *evp_cipher);
 
-static int found(const char *name, const OPT_PAIR *pairs, int *result)
+#define found(value, pairs, result)\
+    opt_found(value, result, pairs, OSSL_NELEM(pairs))
+static int opt_found(const char *name, unsigned int *result,
+                     const OPT_PAIR pairs[], unsigned int nbelem)
 {
-    for (; pairs->name; pairs++)
+    unsigned int idx;
+
+    for (idx = 0; idx < nbelem; ++idx, pairs++)
         if (strcmp(name, pairs->name) == 0) {
             *result = pairs->retval;
             return 1;
@@ -387,7 +331,7 @@ OPTIONS speed_options[] = {
 #ifndef OPENSSL_NO_ENGINE
     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
 #endif
-    {NULL},
+    {NULL}
 };
 
 #define D_MD2           0
@@ -420,7 +364,19 @@ OPTIONS speed_options[] = {
 #define D_IGE_192_AES   27
 #define D_IGE_256_AES   28
 #define D_GHASH         29
-static OPT_PAIR doit_choices[] = {
+/* name of algorithms to test */
+static const char *names[] = {
+    "md2", "mdc2", "md4", "md5", "hmac(md5)", "sha1", "rmd160", "rc4",
+    "des cbc", "des ede3", "idea cbc", "seed cbc",
+    "rc2 cbc", "rc5-32/12 cbc", "blowfish cbc", "cast cbc",
+    "aes-128 cbc", "aes-192 cbc", "aes-256 cbc",
+    "camellia-128 cbc", "camellia-192 cbc", "camellia-256 cbc",
+    "evp", "sha256", "sha512", "whirlpool",
+    "aes-128 ige", "aes-192 ige", "aes-256 ige", "ghash"
+};
+#define ALGOR_NUM       OSSL_NELEM(names)
+/* list of configured algorithm (remaining) */
+static const OPT_PAIR doit_choices[] = {
 #ifndef OPENSSL_NO_MD2
     {"md2", D_MD2},
 #endif
@@ -484,21 +440,24 @@ static OPT_PAIR doit_choices[] = {
     {"cast", D_CBC_CAST},
     {"cast5", D_CBC_CAST},
 #endif
-    {"ghash", D_GHASH},
-    {NULL}
+    {"ghash", D_GHASH}
 };
 
+static double results[ALGOR_NUM][SIZE_NUM];
+
 #ifndef OPENSSL_NO_DSA
 # define R_DSA_512       0
 # define R_DSA_1024      1
 # define R_DSA_2048      2
-static OPT_PAIR dsa_choices[] = {
+static const OPT_PAIR dsa_choices[] = {
     {"dsa512", R_DSA_512},
     {"dsa1024", R_DSA_1024},
-    {"dsa2048", R_DSA_2048},
-    {NULL},
+    {"dsa2048", R_DSA_2048}
 };
-#endif
+# define DSA_NUM         OSSL_NELEM(dsa_choices)
+
+static double dsa_results[DSA_NUM][2];  /* 2 ops: sign then verify */
+#endif  /* OPENSSL_NO_DSA */
 
 #define R_RSA_512       0
 #define R_RSA_1024      1
@@ -507,16 +466,18 @@ static OPT_PAIR dsa_choices[] = {
 #define R_RSA_4096      4
 #define R_RSA_7680      5
 #define R_RSA_15360     6
-static OPT_PAIR rsa_choices[] = {
+static const OPT_PAIR rsa_choices[] = {
     {"rsa512", R_RSA_512},
     {"rsa1024", R_RSA_1024},
     {"rsa2048", R_RSA_2048},
     {"rsa3072", R_RSA_3072},
     {"rsa4096", R_RSA_4096},
     {"rsa7680", R_RSA_7680},
-    {"rsa15360", R_RSA_15360},
-    {NULL}
+    {"rsa15360", R_RSA_15360}
 };
+# define RSA_NUM OSSL_NELEM(rsa_choices)
+
+static double rsa_results[RSA_NUM][2];  /* 2 ops: sign then verify */
 
 #define R_EC_P160    0
 #define R_EC_P192    1
@@ -536,7 +497,7 @@ static OPT_PAIR rsa_choices[] = {
 #define R_EC_B571    15
 #define R_EC_X25519  16
 #ifndef OPENSSL_NO_EC
-static OPT_PAIR ecdsa_choices[] = {
+static const OPT_PAIR ecdsa_choices[] = {
     {"ecdsap160", R_EC_P160},
     {"ecdsap192", R_EC_P192},
     {"ecdsap224", R_EC_P224},
@@ -552,11 +513,13 @@ static OPT_PAIR ecdsa_choices[] = {
     {"ecdsab233", R_EC_B233},
     {"ecdsab283", R_EC_B283},
     {"ecdsab409", R_EC_B409},
-    {"ecdsab571", R_EC_B571},
-    {NULL}
+    {"ecdsab571", R_EC_B571}
 };
+# define ECDSA_NUM       OSSL_NELEM(ecdsa_choices)
+
+static double ecdsa_results[ECDSA_NUM][2];    /* 2 ops: sign then verify */
 
-static OPT_PAIR ecdh_choices[] = {
+static const OPT_PAIR ecdh_choices[] = {
     {"ecdhp160", R_EC_P160},
     {"ecdhp192", R_EC_P192},
     {"ecdhp224", R_EC_P224},
@@ -576,7 +539,10 @@ static OPT_PAIR ecdh_choices[] = {
     {"ecdhx25519", R_EC_X25519},
     {NULL}
 };
-#endif
+# define EC_NUM       OSSL_NELEM(ecdh_choices)
+
+static double ecdh_results[EC_NUM][1];  /* 1 op: derivation */
+#endif /* OPENSSL_NO_EC */
 
 #ifndef SIGALRM
 # define COND(d) (count < (d))
@@ -586,7 +552,40 @@ static OPT_PAIR ecdh_choices[] = {
 # define COUNT(d) (count)
 #endif                         /* SIGALRM */
 
-static int testnum;
+static unsigned int testnum;
+typedef void *(*kdf_fn) (const void *in, size_t inlen, void *out,
+                         size_t *xoutlen);
+
+typedef struct loopargs_st {
+    ASYNC_JOB *inprogress_job;
+    ASYNC_WAIT_CTX *wait_ctx;
+    unsigned char *buf;
+    unsigned char *buf2;
+    unsigned char *buf_malloc;
+    unsigned char *buf2_malloc;
+    unsigned int siglen;
+#ifndef OPENSSL_NO_RSA
+    RSA *rsa_key[RSA_NUM];
+#endif
+#ifndef OPENSSL_NO_DSA
+    DSA *dsa_key[DSA_NUM];
+#endif
+#ifndef OPENSSL_NO_EC
+    EC_KEY *ecdsa[ECDSA_NUM];
+    EC_KEY *ecdh_a[EC_NUM];
+    EC_KEY *ecdh_b[EC_NUM];
+    unsigned char *secret_a;
+    unsigned char *secret_b;
+    size_t      outlen;
+    kdf_fn      kdf;
+#endif
+    EVP_CIPHER_CTX *ctx;
+    HMAC_CTX *hctx;
+    GCM128_CONTEXT *gcm_ctx;
+} loopargs_t;
+
+static int run_benchmark(int async_jobs, int (*loop_function) (void *),
+                         loopargs_t * loopargs);
 
 /* Nb of iterations to do per algorithm and key-size */
 static long c[ALGOR_NUM][SIZE_NUM];
@@ -995,7 +994,7 @@ static int DSA_verify_loop(void *args)
 #endif
 
 #ifndef OPENSSL_NO_EC
-static long ecdsa_c[EC_NUM][2];
+static long ecdsa_c[ECDSA_NUM][2];
 static int ECDSA_sign_loop(void *args)
 {
     loopargs_t *tempargs = *(loopargs_t **)args;
@@ -1222,26 +1221,23 @@ int speed_main(int argc, char **argv)
 {
     ENGINE *e = NULL;
     loopargs_t *loopargs = NULL;
-    int async_init = 0;
-    int loopargs_len = 0;
-    char *prog;
+    const char *prog;
     const char *engine_id = NULL;
     const EVP_CIPHER *evp_cipher = NULL;
     double d = 0.0;
     OPTION_CHOICE o;
-    int multiblock = 0, pr_header = 0;
+    int async_init = 0, multiblock = 0, pr_header = 0;
     int doit[ALGOR_NUM] = { 0 };
-    int ret = 1, i, k, misalign = 0;
+    int ret = 1, misalign = 0;
     long count = 0;
+    unsigned int i, k, loop, loopargs_len = 0, async_jobs = 0;
 #ifndef NO_FORK
     int multi = 0;
 #endif
-    unsigned int async_jobs = 0;
 #if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA) \
     || !defined(OPENSSL_NO_EC)
     long rsa_count = 1;
 #endif
-    size_t loop;
 
     /* What follows are the buffers and key material. */
 #ifndef OPENSSL_NO_RC5
@@ -1325,7 +1321,7 @@ int speed_main(int argc, char **argv)
     /*
      * We only test over the following curves as they are representative, To
      * add tests over more curves, simply add the curve NID and curve name to
-     * the following arrays and increase the EC_NUM value accordingly.
+     * the following arrays and increase the |ecdh_choices| list accordingly.
      */
     static const unsigned int test_curves[EC_NUM] = {
         /* Prime Curves */
@@ -1360,7 +1356,7 @@ int speed_main(int argc, char **argv)
         571, 253 /* X25519 */
     };
 
-    int ecdsa_doit[EC_NUM] = { 0 };
+    int ecdsa_doit[ECDSA_NUM] = { 0 };
     int ecdh_doit[EC_NUM] = { 0 };
 #endif                          /* ndef OPENSSL_NO_EC */
 
@@ -1418,9 +1414,7 @@ int speed_main(int argc, char **argv)
                 goto opterr;
             }
             if (async_jobs > 99999) {
-                BIO_printf(bio_err,
-                           "%s: too many async_jobs\n",
-                           prog);
+                BIO_printf(bio_err, "%s: too many async_jobs\n", prog);
                 goto opterr;
             }
 #endif
@@ -1471,10 +1465,8 @@ int speed_main(int argc, char **argv)
         if (strcmp(*argv, "openssl") == 0)
             continue;
         if (strcmp(*argv, "rsa") == 0) {
-            rsa_doit[R_RSA_512] = rsa_doit[R_RSA_1024] =
-                rsa_doit[R_RSA_2048] = rsa_doit[R_RSA_3072] =
-                rsa_doit[R_RSA_4096] = rsa_doit[R_RSA_7680] =
-                rsa_doit[R_RSA_15360] = 1;
+            for (loop = 0; loop < OSSL_NELEM(rsa_doit); loop++)
+                rsa_doit[loop] = 1;
             continue;
         }
         if (found(*argv, rsa_choices, &i)) {
@@ -1507,8 +1499,8 @@ int speed_main(int argc, char **argv)
 #endif
 #ifndef OPENSSL_NO_EC
         if (strcmp(*argv, "ecdsa") == 0) {
-            for (loop = 0; loop < OSSL_NELEM(ecdsa_choices); loop++)
-                ecdsa_doit[ecdsa_choices[loop].retval] = 1;
+            for (loop = 0; loop < OSSL_NELEM(ecdsa_doit); loop++)
+                ecdsa_doit[loop] = 1;
             continue;
         }
         if (found(*argv, ecdsa_choices, &i)) {
@@ -1516,8 +1508,8 @@ int speed_main(int argc, char **argv)
             continue;
         }
         if (strcmp(*argv, "ecdh") == 0) {
-            for (loop = 0; loop < OSSL_NELEM(ecdh_choices); loop++)
-                ecdh_doit[ecdh_choices[loop].retval] = 1;
+            for (loop = 0; loop < OSSL_NELEM(ecdh_doit); loop++)
+                ecdh_doit[loop] = 1;
             continue;
         }
         if (found(*argv, ecdh_choices, &i)) {
@@ -1584,10 +1576,10 @@ int speed_main(int argc, char **argv)
             dsa_doit[i] = 1;
 #endif
 #ifndef OPENSSL_NO_EC
-        for (loop = 0; loop < OSSL_NELEM(ecdsa_choices); loop++)
-            ecdsa_doit[ecdsa_choices[loop].retval] = 1;
-        for (loop = 0; loop < OSSL_NELEM(ecdh_choices); loop++)
-            ecdh_doit[ecdh_choices[loop].retval] = 1;
+        for (loop = 0; loop < OSSL_NELEM(ecdsa_doit); loop++)
+            ecdsa_doit[loop] = 1;
+        for (loop = 0; loop < OSSL_NELEM(ecdh_doit); loop++)
+            ecdh_doit[loop] = 1;
 #endif
     }
     for (i = 0; i < ALGOR_NUM; i++)
@@ -1850,6 +1842,8 @@ int speed_main(int argc, char **argv)
             }
         }
     }
+    /* default iteration count for the last EC Curve */
+    ecdh_c[R_EC_X25519][0] = count / 1800;
 #  endif
 
 # else
@@ -2472,7 +2466,7 @@ int speed_main(int argc, char **argv)
     if (RAND_status() != 1) {
         RAND_seed(rnd_seed, sizeof(rnd_seed));
     }
-    for (testnum = 0; testnum < EC_NUM; testnum++) {
+    for (testnum = 0; testnum < ECDSA_NUM; testnum++) {
         int st = 1;
 
         if (!ecdsa_doit[testnum])
@@ -2584,7 +2578,7 @@ int speed_main(int argc, char **argv)
                     ecdh_checks = 0;
                     rsa_count = 1;
                 } else {
-                    int secret_size_a, secret_size_b;
+                    int secret_size_a, secret_size_b, j;
                     /*
                      * If field size is not more than 24 octets, then use SHA-1
                      * hash of result; otherwise, use result (see section 4.8 of
@@ -2613,8 +2607,8 @@ int speed_main(int argc, char **argv)
                     else
                         ecdh_checks = 1;
 
-                    for (k = 0; k < secret_size_a && ecdh_checks == 1; k++) {
-                        if (loopargs[i].secret_a[k] != loopargs[i].secret_b[k])
+                    for (j = 0; j < secret_size_a && ecdh_checks == 1; j++) {
+                        if (loopargs[i].secret_a[j] != loopargs[i].secret_b[j])
                             ecdh_checks = 0;
                     }
 
@@ -2644,7 +2638,7 @@ int speed_main(int argc, char **argv)
 
         if (rsa_count <= 1) {
             /* if longer than 10s, don't do any more */
-            for (testnum++; testnum < EC_NUM; testnum++)
+            for (testnum++; testnum < OSSL_NELEM(ecdh_doit); testnum++)
                 ecdh_doit[testnum] = 0;
         }
     }
@@ -2693,7 +2687,7 @@ int speed_main(int argc, char **argv)
         if (!doit[k])
             continue;
         if (mr)
-            printf("+F:%d:%s", k, names[k]);
+            printf("+F:%u:%s", k, names[k]);
         else
             printf("%-13s", names[k]);
         for (testnum = 0; testnum < SIZE_NUM; testnum++) {
@@ -2742,7 +2736,7 @@ int speed_main(int argc, char **argv)
 #endif
 #ifndef OPENSSL_NO_EC
     testnum = 1;
-    for (k = 0; k < EC_NUM; k++) {
+    for (k = 0; k < OSSL_NELEM(ecdsa_doit); k++) {
         if (!ecdsa_doit[k])
             continue;
         if (testnum && !mr) {
@@ -2800,8 +2794,9 @@ int speed_main(int argc, char **argv)
             DSA_free(loopargs[i].dsa_key[k]);
 #endif
 #ifndef OPENSSL_NO_EC
-        for (k = 0; k < EC_NUM; k++) {
+        for (k = 0; k < ECDSA_NUM; k++)
             EC_KEY_free(loopargs[i].ecdsa[k]);
+        for (k = 0; k < EC_NUM; k++) {
             EC_KEY_free(loopargs[i].ecdh_a[k]);
             EC_KEY_free(loopargs[i].ecdh_b[k]);
         }
@@ -2950,7 +2945,7 @@ static int do_multi(int multi)
             printf("Got: %s from %d\n", buf, n);
             if (strncmp(buf, "+F:", 3) == 0) {
                 int alg;
-                int j;
+                unsigned int j;
 
                 p = buf + 3;
                 alg = atoi(sstrsep(&p, sep));

Index: src/crypto/external/bsd/openssl/dist/crypto/arm_arch.h
diff -u src/crypto/external/bsd/openssl/dist/crypto/arm_arch.h:1.4 src/crypto/external/bsd/openssl/dist/crypto/arm_arch.h:1.5
--- src/crypto/external/bsd/openssl/dist/crypto/arm_arch.h:1.4	Thu Feb  8 16:51:24 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/arm_arch.h	Sat Aug 18 04:59:04 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2011-2018 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
@@ -69,7 +69,7 @@
 #  endif
 # endif
 
-# if !__ASSEMBLER__
+# ifndef __ASSEMBLER__
 extern unsigned int OPENSSL_armcap_P;
 # endif
 

Index: src/crypto/external/bsd/openssl/dist/crypto/armcap.c
diff -u src/crypto/external/bsd/openssl/dist/crypto/armcap.c:1.5 src/crypto/external/bsd/openssl/dist/crypto/armcap.c:1.6
--- src/crypto/external/bsd/openssl/dist/crypto/armcap.c:1.5	Thu Feb  8 16:51:24 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/armcap.c	Sat Aug 18 04:59:04 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 2011-2017 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2011-2018 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
@@ -13,6 +13,7 @@
 #include <setjmp.h>
 #include <signal.h>
 #include <openssl/crypto.h>
+#include <internal/cryptlib.h>
 
 #include "arm_arch.h"
 

Index: src/crypto/external/bsd/openssl/dist/crypto/cryptlib.c
diff -u src/crypto/external/bsd/openssl/dist/crypto/cryptlib.c:1.10 src/crypto/external/bsd/openssl/dist/crypto/cryptlib.c:1.11
--- src/crypto/external/bsd/openssl/dist/crypto/cryptlib.c:1.10	Fri Apr  6 19:04:44 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/cryptlib.c	Sat Aug 18 04:59:04 2018
@@ -23,29 +23,97 @@
 extern unsigned int OPENSSL_ia32cap_P[4];
 
 # if defined(OPENSSL_CPUID_OBJ) && !defined(OPENSSL_NO_ASM) && !defined(I386_ONLY)
-#include <stdio.h>
+
+/*
+ * Purpose of these minimalistic and character-type-agnostic subroutines
+ * is to break dependency on MSVCRT (on Windows) and locale. This makes
+ * OPENSSL_cpuid_setup safe to use as "constructor". "Character-type-
+ * agnostic" means that they work with either wide or 8-bit characters,
+ * exploiting the fact that first 127 characters can be simply casted
+ * between the sets, while the rest would be simply rejected by ossl_is*
+ * subroutines.
+ */
+#  ifdef _WIN32
+typedef WCHAR variant_char;
+
+static variant_char *ossl_getenv(const char *name)
+{
+    /*
+     * Since we pull only one environment variable, it's simpler to
+     * to just ignore |name| and use equivalent wide-char L-literal.
+     * As well as to ignore excessively long values...
+     */
+    static WCHAR value[48];
+    DWORD len = GetEnvironmentVariableW(L"OPENSSL_ia32cap", value, 48);
+
+    return (len > 0 && len < 48) ? value : NULL;
+}
+#  else
+typedef char variant_char;
+#   define ossl_getenv getenv
+#  endif
+
+static int todigit(variant_char c)
+{
+    if (c >= '0' && c <= '9')
+        return c - '0';
+    else if (c >= 'A' && c <= 'F')
+        return c - 'A' + 10;
+    else if (c >= 'a' && c <= 'f')
+        return c - 'a' + 10;
+
+    /* return largest base value to make caller terminate the loop */
+    return 16;
+}
+
+static uint64_t ossl_strtouint64(const variant_char *str)
+{
+    uint64_t ret = 0;
+    unsigned int digit, base = 10;
+
+    if (*str == '0') {
+        base = 8, str++;
+        if (*str == 'x' || *str == 'X')
+            base = 16, str++;
+    }
+
+    while((digit = todigit(*str++)) < base)
+        ret = ret * base + digit;
+
+    return ret;
+}
+
+static variant_char *ossl_strchr(const variant_char *str, char srch)
+{   variant_char c;
+
+    while((c = *str)) {
+        if (c == srch)
+	    return (variant_char *)str;
+        str++;
+    }
+
+    return NULL;
+}
+
 #  define OPENSSL_CPUID_SETUP
 typedef uint64_t IA32CAP;
+
 void OPENSSL_cpuid_setup(void)
 {
     static int trigger = 0;
     IA32CAP OPENSSL_ia32_cpuid(unsigned int *);
     IA32CAP vec;
-    char *env;
+    const variant_char *env;
 
     if (trigger)
         return;
 
     trigger = 1;
-    if ((env = getenv("OPENSSL_ia32cap"))) {
+    if ((env = ossl_getenv("OPENSSL_ia32cap")) != NULL) {
         int off = (env[0] == '~') ? 1 : 0;
-#  if defined(_WIN32)
-        if (!sscanf(env + off, "%I64i", &vec))
-            vec = strtoul(env + off, NULL, 0);
-#  else
-        if (!sscanf(env + off, "%lli", (long long *)&vec))
-            vec = strtoul(env + off, NULL, 0);
-#  endif
+
+        vec = ossl_strtouint64(env + off);
+
         if (off) {
             IA32CAP mask = vec;
             vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P) & ~mask;
@@ -64,15 +132,17 @@ void OPENSSL_cpuid_setup(void)
             vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P);
         }
 
-        if ((env = strchr(env, ':'))) {
-            unsigned int vecx;
+        if ((env = ossl_strchr(env, ':')) != NULL) {
+            IA32CAP vecx;
+
             env++;
             off = (env[0] == '~') ? 1 : 0;
-            vecx = strtoul(env + off, NULL, 0);
-            if (off)
-                OPENSSL_ia32cap_P[2] &= ~vecx;
-            else
-                OPENSSL_ia32cap_P[2] = vecx;
+            vecx = ossl_strtouint64(env + off);
+            if (off) {
+                OPENSSL_ia32cap_P[2] &= ~(unsigned int)vecx;
+            } else {
+                OPENSSL_ia32cap_P[2] = (unsigned int)vecx;
+            }
         } else {
             OPENSSL_ia32cap_P[2] = 0;
         }
@@ -128,10 +198,14 @@ int OPENSSL_isservice(void)
 
     if (_OPENSSL_isservice.p == NULL) {
         HANDLE mod = GetModuleHandle(NULL);
+        FARPROC f;
+
         if (mod != NULL)
-            _OPENSSL_isservice.f = GetProcAddress(mod, "_OPENSSL_isservice");
-        if (_OPENSSL_isservice.p == NULL)
+            f = GetProcAddress(mod, "_OPENSSL_isservice");
+        if (f == NULL)
             _OPENSSL_isservice.p = (void *)-1;
+        else
+            _OPENSSL_isservice.f = f;
     }
 
     if (_OPENSSL_isservice.p != (void *)-1)

Index: src/crypto/external/bsd/openssl/dist/crypto/ex_data.c
diff -u src/crypto/external/bsd/openssl/dist/crypto/ex_data.c:1.3 src/crypto/external/bsd/openssl/dist/crypto/ex_data.c:1.4
--- src/crypto/external/bsd/openssl/dist/crypto/ex_data.c:1.3	Thu Feb  8 16:51:24 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/ex_data.c	Sat Aug 18 04:59:04 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2018 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,8 @@ static CRYPTO_ONCE ex_data_init = CRYPTO
 
 DEFINE_RUN_ONCE_STATIC(do_ex_data_init)
 {
-    OPENSSL_init_crypto(0, NULL);
+    if (!OPENSSL_init_crypto(0, NULL))
+        return 0;
     ex_data_lock = CRYPTO_THREAD_lock_new();
     return ex_data_lock != NULL;
 }

Index: src/crypto/external/bsd/openssl/dist/crypto/asn1/a_strex.c
diff -u src/crypto/external/bsd/openssl/dist/crypto/asn1/a_strex.c:1.6 src/crypto/external/bsd/openssl/dist/crypto/asn1/a_strex.c:1.7
--- src/crypto/external/bsd/openssl/dist/crypto/asn1/a_strex.c:1.6	Fri Apr  6 19:04:44 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/asn1/a_strex.c	Sat Aug 18 04:59:04 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2000-2018 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
@@ -139,7 +139,7 @@ static int do_buf(unsigned char *buf, in
                   int type, unsigned short flags, char *quotes, char_io *io_ch,
                   void *arg)
 {
-    int i, outlen, len;
+    int i, outlen, len, charwidth;
     unsigned short orflags;
     unsigned char *p, *q;
     unsigned long c;
@@ -147,12 +147,32 @@ static int do_buf(unsigned char *buf, in
     p = buf;
     q = buf + buflen;
     outlen = 0;
+    charwidth = type & BUF_TYPE_WIDTH_MASK;
+
+    switch (charwidth) {
+    case 4:
+        if (buflen & 3) {
+            ASN1err(ASN1_F_DO_BUF, ASN1_R_INVALID_UNIVERSALSTRING_LENGTH);
+            return -1;
+        }
+        break;
+    case 2:
+        if (buflen & 1) {
+            ASN1err(ASN1_F_DO_BUF, ASN1_R_INVALID_BMPSTRING_LENGTH);
+            return -1;
+        }
+        break;
+    default:
+        break;
+    }
+
     while (p != q) {
         if (p == buf && flags & ASN1_STRFLGS_ESC_2253)
             orflags = CHARTYPE_FIRST_ESC_2253;
         else
             orflags = 0;
-        switch (type & BUF_TYPE_WIDTH_MASK) {
+
+        switch (charwidth) {
         case 4:
             c = ((unsigned long)*p++) << 24;
             c |= ((unsigned long)*p++) << 16;
@@ -173,6 +193,7 @@ static int do_buf(unsigned char *buf, in
             i = UTF8_getc(p, buflen, &c);
             if (i < 0)
                 return -1;      /* Invalid UTF8String */
+            buflen -= i;
             p += i;
             break;
         default:
@@ -592,53 +613,3 @@ int ASN1_STRING_to_UTF8(unsigned char **
     *out = stmp.data;
     return stmp.length;
 }
-
-/* Return 1 if host is a valid hostname and 0 otherwise */
-int asn1_valid_host(const ASN1_STRING *host)
-{
-    int hostlen = host->length;
-    const unsigned char *hostptr = host->data;
-    int type = host->type;
-    int i;
-    signed char width = -1;
-    unsigned short chflags = 0, prevchflags;
-
-    if (type > 0 && type < 31)
-        width = tag2nbyte[type];
-    if (width == -1 || hostlen == 0)
-        return 0;
-    /* Treat UTF8String as width 1 as any MSB set is invalid */
-    if (width == 0)
-        width = 1;
-    for (i = 0 ; i < hostlen; i+= width) {
-        prevchflags = chflags;
-        /* Value must be <= 0x7F: check upper bytes are all zeroes */
-        if (width == 4) {
-            if (*hostptr++ != 0 || *hostptr++ != 0 || *hostptr++ != 0)
-                return 0;
-        } else if (width == 2) {
-            if (*hostptr++ != 0)
-                return 0;
-        }
-        if (*hostptr > 0x7f)
-            return 0;
-        chflags = char_type[*hostptr++];
-        if (!(chflags & (CHARTYPE_HOST_ANY | CHARTYPE_HOST_WILD))) {
-            /* Nothing else allowed at start or end of string */
-            if (i == 0 || i == hostlen - 1)
-                return 0;
-            /* Otherwise invalid if not dot or hyphen */
-            if (!(chflags & (CHARTYPE_HOST_DOT | CHARTYPE_HOST_HYPHEN)))
-                return 0;
-            /*
-             * If previous is dot or hyphen then illegal unless both
-             * are hyphens: as .- -. .. are all illegal
-             */
-            if (prevchflags & (CHARTYPE_HOST_DOT | CHARTYPE_HOST_HYPHEN)
-                && ((prevchflags & CHARTYPE_HOST_DOT)
-                    || (chflags & CHARTYPE_HOST_DOT)))
-                return 0;
-        }
-    }
-    return 1;
-}

Index: src/crypto/external/bsd/openssl/dist/crypto/asn1/asn_mime.c
diff -u src/crypto/external/bsd/openssl/dist/crypto/asn1/asn_mime.c:1.9 src/crypto/external/bsd/openssl/dist/crypto/asn1/asn_mime.c:1.10
--- src/crypto/external/bsd/openssl/dist/crypto/asn1/asn_mime.c:1.9	Fri Apr  6 19:04:44 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/asn1/asn_mime.c	Sat Aug 18 04:59:04 2018
@@ -969,12 +969,14 @@ static int strip_eol(char *linebuf, int 
     p = linebuf + len - 1;
     for (p = linebuf + len - 1; len > 0; len--, p--) {
         c = *p;
-        if (c == '\n')
+        if (c == '\n') {
             is_eol = 1;
-        else if (is_eol && flags & SMIME_ASCIICRLF && c < 33)
+        } else if (is_eol && flags & SMIME_ASCIICRLF && c == 32) {
+            /* Strip trailing space on a line; 32 == ASCII for ' ' */
             continue;
-        else if (c != '\r')
+        } else if (c != '\r') {
             break;
+        }
     }
     *plen = len;
     return is_eol;

Index: src/crypto/external/bsd/openssl/dist/crypto/asn1/tasn_enc.c
diff -u src/crypto/external/bsd/openssl/dist/crypto/asn1/tasn_enc.c:1.7 src/crypto/external/bsd/openssl/dist/crypto/asn1/tasn_enc.c:1.8
--- src/crypto/external/bsd/openssl/dist/crypto/asn1/tasn_enc.c:1.7	Thu Feb  8 16:51:24 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/asn1/tasn_enc.c	Sat Aug 18 04:59:04 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2000-2018 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
@@ -528,6 +528,8 @@ static int asn1_ex_i2c(ASN1_VALUE **pval
         otmp = (ASN1_OBJECT *)*pval;
         cont = otmp->data;
         len = otmp->length;
+        if (cont == NULL || len == 0)
+            return -1;
         break;
 
     case V_ASN1_NULL:

Index: src/crypto/external/bsd/openssl/dist/crypto/bio/b_sock.c
diff -u src/crypto/external/bsd/openssl/dist/crypto/bio/b_sock.c:1.8 src/crypto/external/bsd/openssl/dist/crypto/bio/b_sock.c:1.9
--- src/crypto/external/bsd/openssl/dist/crypto/bio/b_sock.c:1.8	Thu Feb  8 16:51:25 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/bio/b_sock.c	Sat Aug 18 04:59:04 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2018 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
@@ -317,7 +317,7 @@ int BIO_socket_nbio(int s, int mode)
 
     l = fcntl(s, F_GETFL, 0);
     if (l == -1) {
-        SYSerr(SYS_F_FCNTL, get_last_rtl_error());
+        SYSerr(SYS_F_FCNTL, get_last_sys_error());
         ret = -1;
     } else {
 #  if defined(O_NONBLOCK)
@@ -335,7 +335,7 @@ int BIO_socket_nbio(int s, int mode)
         ret = fcntl(s, F_SETFL, l);
 
         if (ret < 0) {
-            SYSerr(SYS_F_FCNTL, get_last_rtl_error());
+            SYSerr(SYS_F_FCNTL, get_last_sys_error());
         }
     }
 # else

Index: src/crypto/external/bsd/openssl/dist/crypto/bio/bss_log.c
diff -u src/crypto/external/bsd/openssl/dist/crypto/bio/bss_log.c:1.7 src/crypto/external/bsd/openssl/dist/crypto/bio/bss_log.c:1.8
--- src/crypto/external/bsd/openssl/dist/crypto/bio/bss_log.c:1.7	Fri Apr  6 19:04:44 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/bio/bss_log.c	Sat Aug 18 04:59:04 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2017 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1999-2018 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
@@ -196,7 +196,7 @@ static int slg_write(BIO *b, const char 
     if ((buf = OPENSSL_malloc(inl + 1)) == NULL) {
         return (0);
     }
-    strncpy(buf, in, inl);
+    memcpy(buf, in, inl);
     buf[inl] = '\0';
 
     i = 0;

Index: src/crypto/external/bsd/openssl/dist/crypto/bn/bn_exp.c
diff -u src/crypto/external/bsd/openssl/dist/crypto/bn/bn_exp.c:1.15 src/crypto/external/bsd/openssl/dist/crypto/bn/bn_exp.c:1.16
--- src/crypto/external/bsd/openssl/dist/crypto/bn/bn_exp.c:1.15	Fri Apr  6 19:04:44 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/bn/bn_exp.c	Sat Aug 18 04:59:04 2018
@@ -192,8 +192,8 @@ int BN_mod_exp_recp(BIGNUM *r, const BIG
 
     bits = BN_num_bits(p);
     if (bits == 0) {
-        /* x**0 mod 1 is still zero. */
-        if (BN_is_one(m)) {
+        /* x**0 mod 1, or x**0 mod -1 is still zero. */
+        if (BN_abs_is_word(m, 1)) {
             ret = 1;
             BN_zero(r);
         } else {
@@ -334,8 +334,8 @@ int BN_mod_exp_mont(BIGNUM *rr, const BI
     }
     bits = BN_num_bits(p);
     if (bits == 0) {
-        /* x**0 mod 1 is still zero. */
-        if (BN_is_one(m)) {
+        /* x**0 mod 1, or x**0 mod -1 is still zero. */
+        if (BN_abs_is_word(m, 1)) {
             ret = 1;
             BN_zero(rr);
         } else {
@@ -375,17 +375,17 @@ int BN_mod_exp_mont(BIGNUM *rr, const BI
         ret = 1;
         goto err;
     }
-    if (!BN_to_montgomery(val[0], aa, mont, ctx))
+    if (!bn_to_mont_fixed_top(val[0], aa, mont, ctx))
         goto err;               /* 1 */
 
     window = BN_window_bits_for_exponent_size(bits);
     if (window > 1) {
-        if (!BN_mod_mul_montgomery(d, val[0], val[0], mont, ctx))
+        if (!bn_mul_mont_fixed_top(d, val[0], val[0], mont, ctx))
             goto err;           /* 2 */
         j = 1 << (window - 1);
         for (i = 1; i < j; i++) {
             if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
-                !BN_mod_mul_montgomery(val[i], val[i - 1], d, mont, ctx))
+                !bn_mul_mont_fixed_top(val[i], val[i - 1], d, mont, ctx))
                 goto err;
         }
     }
@@ -407,19 +407,15 @@ int BN_mod_exp_mont(BIGNUM *rr, const BI
         for (i = 1; i < j; i++)
             r->d[i] = (~m->d[i]) & BN_MASK2;
         r->top = j;
-        /*
-         * Upper words will be zero if the corresponding words of 'm' were
-         * 0xfff[...], so decrement r->top accordingly.
-         */
-        bn_correct_top(r);
+        r->flags |= BN_FLG_FIXED_TOP;
     } else
 #endif
-    if (!BN_to_montgomery(r, BN_value_one(), mont, ctx))
+    if (!bn_to_mont_fixed_top(r, BN_value_one(), mont, ctx))
         goto err;
     for (;;) {
         if (BN_is_bit_set(p, wstart) == 0) {
             if (!start) {
-                if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
+                if (!bn_mul_mont_fixed_top(r, r, r, mont, ctx))
                     goto err;
             }
             if (wstart == 0)
@@ -450,12 +446,12 @@ int BN_mod_exp_mont(BIGNUM *rr, const BI
         /* add the 'bytes above' */
         if (!start)
             for (i = 0; i < j; i++) {
-                if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
+                if (!bn_mul_mont_fixed_top(r, r, r, mont, ctx))
                     goto err;
             }
 
         /* wvalue will be an odd number < 2^window */
-        if (!BN_mod_mul_montgomery(r, r, val[wvalue >> 1], mont, ctx))
+        if (!bn_mul_mont_fixed_top(r, r, val[wvalue >> 1], mont, ctx))
             goto err;
 
         /* move the 'window' down further */
@@ -465,6 +461,11 @@ int BN_mod_exp_mont(BIGNUM *rr, const BI
         if (wstart < 0)
             break;
     }
+    /*
+     * Done with zero-padded intermediate BIGNUMs. Final BN_from_montgomery
+     * removes padding [if any] and makes return value suitable for public
+     * API consumer.
+     */
 #if defined(SPARC_T4_MONT)
     if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) {
         j = mont->N.top;        /* borrow j */
@@ -591,7 +592,7 @@ static int MOD_EXP_CTIME_COPY_FROM_PREBU
     }
 
     b->top = top;
-    bn_correct_top(b);
+    b->flags |= BN_FLG_FIXED_TOP;
     return 1;
 }
 
@@ -643,8 +644,8 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr
      */
     bits = p->top * BN_BITS2;
     if (bits == 0) {
-        /* x**0 mod 1 is still zero. */
-        if (BN_is_one(m)) {
+        /* x**0 mod 1, or x**0 mod -1 is still zero. */
+        if (BN_abs_is_word(m, 1)) {
             ret = 1;
             BN_zero(rr);
         } else {
@@ -761,16 +762,16 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr
         tmp.top = top;
     } else
 #endif
-    if (!BN_to_montgomery(&tmp, BN_value_one(), mont, ctx))
+    if (!bn_to_mont_fixed_top(&tmp, BN_value_one(), mont, ctx))
         goto err;
 
     /* prepare a^1 in Montgomery domain */
     if (a->neg || BN_ucmp(a, m) >= 0) {
         if (!BN_mod(&am, a, m, ctx))
             goto err;
-        if (!BN_to_montgomery(&am, &am, mont, ctx))
+        if (!bn_to_mont_fixed_top(&am, &am, mont, ctx))
             goto err;
-    } else if (!BN_to_montgomery(&am, a, mont, ctx))
+    } else if (!bn_to_mont_fixed_top(&am, a, mont, ctx))
         goto err;
 
 #if defined(SPARC_T4_MONT)
@@ -1037,14 +1038,14 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr
          * performance advantage of sqr over mul).
          */
         if (window > 1) {
-            if (!BN_mod_mul_montgomery(&tmp, &am, &am, mont, ctx))
+            if (!bn_mul_mont_fixed_top(&tmp, &am, &am, mont, ctx))
                 goto err;
             if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 2,
                                               window))
                 goto err;
             for (i = 3; i < numPowers; i++) {
                 /* Calculate a^i = a^(i-1) * a */
-                if (!BN_mod_mul_montgomery(&tmp, &am, &tmp, mont, ctx))
+                if (!bn_mul_mont_fixed_top(&tmp, &am, &tmp, mont, ctx))
                     goto err;
                 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, i,
                                                   window))
@@ -1068,7 +1069,7 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr
 
             /* Scan the window, squaring the result as we go */
             for (i = 0; i < window; i++, bits--) {
-                if (!BN_mod_mul_montgomery(&tmp, &tmp, &tmp, mont, ctx))
+                if (!bn_mul_mont_fixed_top(&tmp, &tmp, &tmp, mont, ctx))
                     goto err;
                 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
             }
@@ -1081,12 +1082,16 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr
                 goto err;
 
             /* Multiply the result into the intermediate result */
-            if (!BN_mod_mul_montgomery(&tmp, &tmp, &am, mont, ctx))
+            if (!bn_mul_mont_fixed_top(&tmp, &tmp, &am, mont, ctx))
                 goto err;
         }
     }
 
-    /* Convert the final result from montgomery to standard format */
+    /*
+     * Done with zero-padded intermediate BIGNUMs. Final BN_from_montgomery
+     * removes padding [if any] and makes return value suitable for public
+     * API consumer.
+     */
 #if defined(SPARC_T4_MONT)
     if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) {
         am.d[0] = 1;            /* borrow am */
@@ -1155,8 +1160,8 @@ int BN_mod_exp_mont_word(BIGNUM *rr, BN_
 
     bits = BN_num_bits(p);
     if (bits == 0) {
-        /* x**0 mod 1 is still zero. */
-        if (BN_is_one(m)) {
+        /* x**0 mod 1, or x**0 mod -1 is still zero. */
+        if (BN_abs_is_word(m, 1)) {
             ret = 1;
             BN_zero(rr);
         } else {
@@ -1277,9 +1282,9 @@ int BN_mod_exp_simple(BIGNUM *r, const B
     }
 
     bits = BN_num_bits(p);
-   if (bits == 0) {
-        /* x**0 mod 1 is still zero. */
-        if (BN_is_one(m)) {
+    if (bits == 0) {
+        /* x**0 mod 1, or x**0 mod -1 is still zero. */
+        if (BN_abs_is_word(m, 1)) {
             ret = 1;
             BN_zero(r);
         } else {

Index: src/crypto/external/bsd/openssl/dist/crypto/bn/bn_lcl.h
diff -u src/crypto/external/bsd/openssl/dist/crypto/bn/bn_lcl.h:1.6 src/crypto/external/bsd/openssl/dist/crypto/bn/bn_lcl.h:1.7
--- src/crypto/external/bsd/openssl/dist/crypto/bn/bn_lcl.h:1.6	Thu Feb  8 16:51:25 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/bn/bn_lcl.h	Sat Aug 18 04:59:04 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2018 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
@@ -145,7 +145,16 @@ extern "C" {
  */
 
 # ifdef BN_DEBUG
-
+/*
+ * The new BN_FLG_FIXED_TOP flag marks vectors that were not treated with
+ * bn_correct_top, in other words such vectors are permitted to have zeros
+ * in most significant limbs. Such vectors are used internally to achieve
+ * execution time invariance for critical operations with private keys.
+ * It's BN_DEBUG-only flag, because user application is not supposed to
+ * observe it anyway. Moreover, optimizing compiler would actually remove
+ * all operations manipulating the bit in question in non-BN_DEBUG build.
+ */
+#  define BN_FLG_FIXED_TOP 0x10000
 #  ifdef BN_DEBUG_RAND
 /* To avoid "make update" cvs wars due to BN_DEBUG, use some tricks */
 #   ifndef RAND_bytes
@@ -177,8 +186,10 @@ int RAND_bytes(unsigned char *buf, int n
         do { \
                 const BIGNUM *_bnum2 = (a); \
                 if (_bnum2 != NULL) { \
-                        OPENSSL_assert(((_bnum2->top == 0) && !_bnum2->neg) || \
-                                (_bnum2->top && (_bnum2->d[_bnum2->top - 1] != 0))); \
+                        int _top = _bnum2->top; \
+                        OPENSSL_assert((_top == 0 && !_bnum2->neg) || \
+                               (_top && ((_bnum2->flags & BN_FLG_FIXED_TOP) \
+                                         || _bnum2->d[_top - 1] != 0))); \
                         bn_pollute(_bnum2); \
                 } \
         } while(0)
@@ -197,6 +208,7 @@ int RAND_bytes(unsigned char *buf, int n
 
 # else                          /* !BN_DEBUG */
 
+#  define BN_FLG_FIXED_TOP 0
 #  define bn_pollute(a)
 #  define bn_check_top(a)
 #  define bn_fix_top(a)           bn_correct_top(a)
@@ -228,7 +240,8 @@ struct bignum_st {
 /* Used for montgomery multiplication */
 struct bn_mont_ctx_st {
     int ri;                     /* number of bits in R */
-    BIGNUM RR;                  /* used to convert to montgomery form */
+    BIGNUM RR;                  /* used to convert to montgomery form,
+                                   possibly zero-padded */
     BIGNUM N;                   /* The modulus */
     BIGNUM Ni;                  /* R*(1/R mod N) - N*Ni = 1 (Ni is only
                                  * stored for bignum algorithm) */

Index: src/crypto/external/bsd/openssl/dist/crypto/bn/bn_lib.c
diff -u src/crypto/external/bsd/openssl/dist/crypto/bn/bn_lib.c:1.7 src/crypto/external/bsd/openssl/dist/crypto/bn/bn_lib.c:1.8
--- src/crypto/external/bsd/openssl/dist/crypto/bn/bn_lib.c:1.7	Fri Apr  6 19:04:44 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/bn/bn_lib.c	Sat Aug 18 04:59:04 2018
@@ -12,6 +12,7 @@
 #include "internal/cryptlib.h"
 #include "bn_lcl.h"
 #include <openssl/opensslconf.h>
+#include "internal/constant_time_locl.h"
 
 /* This stuff appears to be completely unused, so is deprecated */
 #if OPENSSL_API_COMPAT < 0x00908000L
@@ -222,8 +223,6 @@ static BN_ULONG *bn_expand_internal(cons
     const BN_ULONG *B;
     int i;
 
-    bn_check_top(b);
-
     if (words > (INT_MAX / (4 * BN_BITS2))) {
         BNerr(BN_F_BN_EXPAND_INTERNAL, BN_R_BIGNUM_TOO_LONG);
         return NULL;
@@ -298,8 +297,6 @@ static BN_ULONG *bn_expand_internal(cons
 
 BIGNUM *bn_expand2(BIGNUM *b, int words)
 {
-    bn_check_top(b);
-
     if (words > b->dmax) {
         BN_ULONG *a = bn_expand_internal(b, words);
         if (!a)
@@ -312,7 +309,6 @@ BIGNUM *bn_expand2(BIGNUM *b, int words)
         b->dmax = words;
     }
 
-    bn_check_top(b);
     return b;
 }
 
@@ -379,12 +375,19 @@ BIGNUM *BN_copy(BIGNUM *a, const BIGNUM 
     memcpy(a->d, b->d, sizeof(b->d[0]) * b->top);
 #endif
 
-    a->top = b->top;
     a->neg = b->neg;
+    a->top = b->top;
+    a->flags |= b->flags & BN_FLG_FIXED_TOP;
     bn_check_top(a);
     return (a);
 }
 
+#define FLAGS_DATA(flags) ((flags) & (BN_FLG_STATIC_DATA \
+                                    | BN_FLG_CONSTTIME   \
+                                    | BN_FLG_SECURE      \
+                                    | BN_FLG_FIXED_TOP))
+#define FLAGS_STRUCT(flags) ((flags) & (BN_FLG_MALLOCED))
+
 void BN_swap(BIGNUM *a, BIGNUM *b)
 {
     int flags_old_a, flags_old_b;
@@ -412,10 +415,8 @@ void BN_swap(BIGNUM *a, BIGNUM *b)
     b->dmax = tmp_dmax;
     b->neg = tmp_neg;
 
-    a->flags =
-        (flags_old_a & BN_FLG_MALLOCED) | (flags_old_b & BN_FLG_STATIC_DATA);
-    b->flags =
-        (flags_old_b & BN_FLG_MALLOCED) | (flags_old_a & BN_FLG_STATIC_DATA);
+    a->flags = FLAGS_STRUCT(flags_old_a) | FLAGS_DATA(flags_old_b);
+    b->flags = FLAGS_STRUCT(flags_old_b) | FLAGS_DATA(flags_old_a);
     bn_check_top(a);
     bn_check_top(b);
 }
@@ -425,8 +426,9 @@ void BN_clear(BIGNUM *a)
     bn_check_top(a);
     if (a->d != NULL)
         OPENSSL_cleanse(a->d, sizeof(*a->d) * a->dmax);
-    a->top = 0;
     a->neg = 0;
+    a->top = 0;
+    a->flags &= ~BN_FLG_FIXED_TOP;
 }
 
 BN_ULONG BN_get_word(const BIGNUM *a)
@@ -447,6 +449,7 @@ int BN_set_word(BIGNUM *a, BN_ULONG w)
     a->neg = 0;
     a->d[0] = w;
     a->top = (w ? 1 : 0);
+    a->flags &= ~BN_FLG_FIXED_TOP;
     bn_check_top(a);
     return (1);
 }
@@ -499,24 +502,29 @@ BIGNUM *BN_bin2bn(const unsigned char *s
 /* ignore negative */
 static int bn2binpad(const BIGNUM *a, unsigned char *to, int tolen)
 {
-    int i;
+    int n;
+    size_t i, inc, lasti, j;
     BN_ULONG l;
 
-    bn_check_top(a);
-    i = BN_num_bytes(a);
+    n = BN_num_bytes(a);
     if (tolen == -1)
-        tolen = i;
-    else if (tolen < i)
+        tolen = n;
+    else if (tolen < n)
         return -1;
-    /* Add leading zeroes if necessary */
-    if (tolen > i) {
-        memset(to, 0, tolen - i);
-        to += tolen - i;
+
+    if (n == 0) {
+        OPENSSL_cleanse(to, tolen);
+        return tolen;
     }
-    while (i--) {
+
+    lasti = n - 1;
+    for (i = 0, inc = 1, j = tolen; j > 0;) {
         l = a->d[i / BN_BYTES];
-        *(to++) = (unsigned char)(l >> (8 * (i % BN_BYTES))) & 0xff;
+        to[--j] = (unsigned char)(l >> (8 * (i % BN_BYTES)) & (0 - inc));
+        inc = (i - lasti) >> (8 * sizeof(i) - 1);
+        i += inc; /* stay on top limb */
     }
+
     return tolen;
 }
 
@@ -683,6 +691,7 @@ int BN_set_bit(BIGNUM *a, int n)
         for (k = a->top; k < i + 1; k++)
             a->d[k] = 0;
         a->top = i + 1;
+        a->flags &= ~BN_FLG_FIXED_TOP;
     }
 
     a->d[i] |= (((BN_ULONG)1) << j);
@@ -824,6 +833,34 @@ void BN_consttime_swap(BN_ULONG conditio
     a->top ^= t;
     b->top ^= t;
 
+    t = (a->neg ^ b->neg) & condition;
+    a->neg ^= t;
+    b->neg ^= t;
+
+    /*-
+     * Idea behind BN_FLG_STATIC_DATA is actually to
+     * indicate that data may not be written to.
+     * Intention is actually to treat it as it's
+     * read-only data, and some (if not most) of it does
+     * reside in read-only segment. In other words
+     * observation of BN_FLG_STATIC_DATA in
+     * BN_consttime_swap should be treated as fatal
+     * condition. It would either cause SEGV or
+     * effectively cause data corruption.
+     * BN_FLG_MALLOCED refers to BN structure itself,
+     * and hence must be preserved. Remaining flags are
+     * BN_FLG_CONSTIME and BN_FLG_SECURE. Latter must be
+     * preserved, because it determines how x->d was
+     * allocated and hence how to free it. This leaves
+     * BN_FLG_CONSTTIME that one can do something about.
+     * To summarize it's sufficient to mask and swap
+     * BN_FLG_CONSTTIME alone. BN_FLG_STATIC_DATA should
+     * be treated as fatal.
+     */
+    t = ((a->flags ^ b->flags) & BN_FLG_CONSTTIME) & condition;
+    a->flags ^= t;
+    b->flags ^= t;
+
 #define BN_CONSTTIME_SWAP(ind) \
         do { \
                 t = (a->d[ind] ^ b->d[ind]) & condition; \
@@ -887,8 +924,9 @@ int BN_security_bits(int L, int N)
 
 void BN_zero_ex(BIGNUM *a)
 {
-    a->top = 0;
     a->neg = 0;
+    a->top = 0;
+    a->flags &= ~BN_FLG_FIXED_TOP;
 }
 
 int BN_abs_is_word(const BIGNUM *a, const BN_ULONG w)
@@ -1012,5 +1050,6 @@ void bn_correct_top(BIGNUM *a)
     }
     if (a->top == 0)
         a->neg = 0;
+    a->flags &= ~BN_FLG_FIXED_TOP;
     bn_pollute(a);
 }

Index: src/crypto/external/bsd/openssl/dist/crypto/bn/bn_mont.c
diff -u src/crypto/external/bsd/openssl/dist/crypto/bn/bn_mont.c:1.9 src/crypto/external/bsd/openssl/dist/crypto/bn/bn_mont.c:1.10
--- src/crypto/external/bsd/openssl/dist/crypto/bn/bn_mont.c:1.9	Fri Apr  6 19:04:44 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/bn/bn_mont.c	Sat Aug 18 04:59:04 2018
@@ -20,29 +20,43 @@
 #define MONT_WORD               /* use the faster word-based algorithm */
 
 #ifdef MONT_WORD
-static int BN_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont);
+static int bn_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont);
 #endif
 
 int BN_mod_mul_montgomery(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
                           BN_MONT_CTX *mont, BN_CTX *ctx)
 {
+    int ret = bn_mul_mont_fixed_top(r, a, b, mont, ctx);
+
+    bn_correct_top(r);
+    bn_check_top(r);
+
+    return ret;
+}
+
+int bn_mul_mont_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
+                          BN_MONT_CTX *mont, BN_CTX *ctx)
+{
     BIGNUM *tmp;
     int ret = 0;
-#if defined(OPENSSL_BN_ASM_MONT) && defined(MONT_WORD)
     int num = mont->N.top;
 
+#if defined(OPENSSL_BN_ASM_MONT) && defined(MONT_WORD)
     if (num > 1 && a->top == num && b->top == num) {
         if (bn_wexpand(r, num) == NULL)
             return (0);
         if (bn_mul_mont(r->d, a->d, b->d, mont->N.d, mont->n0, num)) {
             r->neg = a->neg ^ b->neg;
             r->top = num;
-            bn_correct_top(r);
+            r->flags |= BN_FLG_FIXED_TOP;
             return (1);
         }
     }
 #endif
 
+    if ((a->top + b->top) > 2 * num)
+        return 0;
+
     BN_CTX_start(ctx);
     tmp = BN_CTX_get(ctx);
     if (tmp == NULL)
@@ -58,13 +72,12 @@ int BN_mod_mul_montgomery(BIGNUM *r, con
     }
     /* reduce from aRR to aR */
 #ifdef MONT_WORD
-    if (!BN_from_montgomery_word(r, tmp, mont))
+    if (!bn_from_montgomery_word(r, tmp, mont))
         goto err;
 #else
     if (!BN_from_montgomery(r, tmp, mont, ctx))
         goto err;
 #endif
-    bn_check_top(r);
     ret = 1;
  err:
     BN_CTX_end(ctx);
@@ -72,7 +85,7 @@ int BN_mod_mul_montgomery(BIGNUM *r, con
 }
 
 #ifdef MONT_WORD
-static int BN_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont)
+static int bn_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont)
 {
     BIGNUM *n;
     BN_ULONG *ap, *np, *rp, n0, v, carry;
@@ -99,6 +112,7 @@ static int BN_from_montgomery_word(BIGNU
         memset(&rp[r->top], 0, sizeof(*rp) * i);
 
     r->top = max;
+    r->flags |= BN_FLG_FIXED_TOP;
     n0 = mont->n0[0];
 
     /*
@@ -117,6 +131,7 @@ static int BN_from_montgomery_word(BIGNU
     if (bn_wexpand(ret, nl) == NULL)
         return (0);
     ret->top = nl;
+    ret->flags |= BN_FLG_FIXED_TOP;
     ret->neg = r->neg;
 
     rp = ret->d;
@@ -127,20 +142,16 @@ static int BN_from_montgomery_word(BIGNU
      */
     ap = &(r->d[nl]);
 
+    carry -= bn_sub_words(rp, ap, np, nl);
     /*
-     * |v| is one if |ap| - |np| underflowed or zero if it did not. Note |v|
-     * cannot be -1. That would imply the subtraction did not fit in |nl| words,
-     * and we know at most one subtraction is needed.
+     * |carry| is -1 if |ap| - |np| underflowed or zero if it did not. Note
+     * |carry| cannot be 1. That would imply the subtraction did not fit in
+     * |nl| words, and we know at most one subtraction is needed.
      */
-    v = bn_sub_words(rp, ap, np, nl) - carry;
-    v = 0 - v;
     for (i = 0; i < nl; i++) {
-        rp[i] = (v & ap[i]) | (~v & rp[i]);
+        rp[i] = (carry & ap[i]) | (~carry & rp[i]);
         ap[i] = 0;
     }
-    bn_correct_top(r);
-    bn_correct_top(ret);
-    bn_check_top(ret);
 
     return (1);
 }
@@ -154,8 +165,11 @@ int BN_from_montgomery(BIGNUM *ret, cons
     BIGNUM *t;
 
     BN_CTX_start(ctx);
-    if ((t = BN_CTX_get(ctx)) && BN_copy(t, a))
-        retn = BN_from_montgomery_word(ret, t, mont);
+    if ((t = BN_CTX_get(ctx)) && BN_copy(t, a)) {
+        retn = bn_from_montgomery_word(ret, t, mont);
+        bn_correct_top(ret);
+        bn_check_top(ret);
+    }
     BN_CTX_end(ctx);
 #else                           /* !MONT_WORD */
     BIGNUM *t1, *t2;
@@ -195,6 +209,12 @@ int BN_from_montgomery(BIGNUM *ret, cons
     return (retn);
 }
 
+int bn_to_mont_fixed_top(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont,
+                         BN_CTX *ctx)
+{
+    return bn_mul_mont_fixed_top(r, a, &(mont->RR), mont, ctx);
+}
+
 BN_MONT_CTX *BN_MONT_CTX_new(void)
 {
     BN_MONT_CTX *ret;
@@ -231,7 +251,7 @@ void BN_MONT_CTX_free(BN_MONT_CTX *mont)
 
 int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *mod, BN_CTX *ctx)
 {
-    int ret = 0;
+    int i, ret = 0;
     BIGNUM *Ri, *R;
 
     if (BN_is_zero(mod))
@@ -280,7 +300,9 @@ int BN_MONT_CTX_set(BN_MONT_CTX *mont, c
         if ((buf[1] = mod->top > 1 ? mod->d[1] : 0))
             tmod.top = 2;
 
-        if ((BN_mod_inverse(Ri, R, &tmod, ctx)) == NULL)
+        if (BN_is_one(&tmod))
+            BN_zero(Ri);
+        else if ((BN_mod_inverse(Ri, R, &tmod, ctx)) == NULL)
             goto err;
         if (!BN_lshift(Ri, Ri, 2 * BN_BITS2))
             goto err;           /* R*Ri */
@@ -313,7 +335,9 @@ int BN_MONT_CTX_set(BN_MONT_CTX *mont, c
         buf[1] = 0;
         tmod.top = buf[0] != 0 ? 1 : 0;
         /* Ri = R^-1 mod N */
-        if ((BN_mod_inverse(Ri, R, &tmod, ctx)) == NULL)
+        if (BN_is_one(&tmod))
+            BN_zero(Ri);
+        else if ((BN_mod_inverse(Ri, R, &tmod, ctx)) == NULL)
             goto err;
         if (!BN_lshift(Ri, Ri, BN_BITS2))
             goto err;           /* R*Ri */
@@ -362,6 +386,11 @@ int BN_MONT_CTX_set(BN_MONT_CTX *mont, c
     if (!BN_mod(&(mont->RR), &(mont->RR), &(mont->N), ctx))
         goto err;
 
+    for (i = mont->RR.top, ret = mont->N.top; i < ret; i++)
+        mont->RR.d[i] = 0;
+    mont->RR.top = ret;
+    mont->RR.flags |= BN_FLG_FIXED_TOP;
+
     ret = 1;
  err:
     BN_CTX_end(ctx);

Index: src/crypto/external/bsd/openssl/dist/crypto/dso/dso_dlfcn.c
diff -u src/crypto/external/bsd/openssl/dist/crypto/dso/dso_dlfcn.c:1.11 src/crypto/external/bsd/openssl/dist/crypto/dso/dso_dlfcn.c:1.12
--- src/crypto/external/bsd/openssl/dist/crypto/dso/dso_dlfcn.c:1.11	Thu Feb  8 16:51:27 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/dso/dso_dlfcn.c	Sat Aug 18 04:59:04 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2000-2018 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
@@ -26,7 +26,7 @@
 #  endif
 #  include <dlfcn.h>
 #  define HAVE_DLINFO 1
-#  if defined(_AIX) || defined(__CYGWIN__) || \
+#  if defined(__CYGWIN__) || \
      defined(__SCO_VERSION__) || defined(_SCO_ELF) || \
      (defined(__osf__) && !defined(RTLD_NEXT))     || \
      (defined(__OpenBSD__) && !defined(RTLD_SELF)) || \
@@ -308,6 +308,76 @@ static int dladdr(void *address, Dl_info
 }
 # endif                         /* __sgi */
 
+# ifdef _AIX
+/*-
+ * See IBM's AIX Version 7.2, Technical Reference:
+ *  Base Operating System and Extensions, Volume 1 and 2
+ *  https://www.ibm.com/support/knowledgecenter/ssw_aix_72/com.ibm.aix.base/technicalreferences.htm
+ */
+#  include <sys/ldr.h>
+#  include <errno.h>
+/* ~ 64 * (sizeof(struct ld_info) + _XOPEN_PATH_MAX + _XOPEN_NAME_MAX) */
+#  define DLFCN_LDINFO_SIZE 86976
+typedef struct Dl_info {
+    const char *dli_fname;
+} Dl_info;
+/*
+ * This dladdr()-implementation will also find the ptrgl (Pointer Glue) virtual
+ * address of a function, which is just located in the DATA segment instead of
+ * the TEXT segment.
+ */
+static int dladdr(void *ptr, Dl_info *dl)
+{
+    uintptr_t addr = (uintptr_t)ptr;
+    unsigned int found = 0;
+    struct ld_info *ldinfos, *next_ldi, *this_ldi;
+
+    if ((ldinfos = (struct ld_info *)OPENSSL_malloc(DLFCN_LDINFO_SIZE)) == NULL) {
+        errno = ENOMEM;
+        dl->dli_fname = NULL;
+        return 0;
+    }
+
+    if ((loadquery(L_GETINFO, (void *)ldinfos, DLFCN_LDINFO_SIZE)) < 0) {
+        /*-
+         * Error handling is done through errno and dlerror() reading errno:
+         *  ENOMEM (ldinfos buffer is too small),
+         *  EINVAL (invalid flags),
+         *  EFAULT (invalid ldinfos ptr)
+         */
+        OPENSSL_free((void *)ldinfos);
+        dl->dli_fname = NULL;
+        return 0;
+    }
+    next_ldi = ldinfos;
+
+    do {
+        this_ldi = next_ldi;
+        if (((addr >= (uintptr_t)this_ldi->ldinfo_textorg)
+             && (addr < ((uintptr_t)this_ldi->ldinfo_textorg +
+                         this_ldi->ldinfo_textsize)))
+            || ((addr >= (uintptr_t)this_ldi->ldinfo_dataorg)
+                && (addr < ((uintptr_t)this_ldi->ldinfo_dataorg +
+                            this_ldi->ldinfo_datasize)))) {
+            found = 1;
+            /*
+             * Ignoring the possibility of a member name and just returning
+             * the path name. See docs: sys/ldr.h, loadquery() and
+             * dlopen()/RTLD_MEMBER.
+             */
+            if ((dl->dli_fname =
+                 OPENSSL_strdup(this_ldi->ldinfo_filename)) == NULL)
+                errno = ENOMEM;
+        } else {
+            next_ldi =
+                (struct ld_info *)((uintptr_t)this_ldi + this_ldi->ldinfo_next);
+        }
+    } while (this_ldi->ldinfo_next && !found);
+    OPENSSL_free((void *)ldinfos);
+    return (found && dl->dli_fname != NULL);
+}
+# endif                         /* _AIX */
+
 static int dlfcn_pathbyaddr(void *addr, char *path, int sz)
 {
 # ifdef HAVE_DLINFO
@@ -326,12 +396,19 @@ static int dlfcn_pathbyaddr(void *addr, 
 
     if (dladdr(addr, &dli)) {
         len = (int)strlen(dli.dli_fname);
-        if (sz <= 0)
+        if (sz <= 0) {
+#  ifdef _AIX
+            OPENSSL_free((void *)dli.dli_fname);
+#  endif
             return len + 1;
+        }
         if (len >= sz)
             len = sz - 1;
         memcpy(path, dli.dli_fname, len);
         path[len++] = 0;
+#  ifdef _AIX
+        OPENSSL_free((void *)dli.dli_fname);
+#  endif
         return len;
     }
 

Index: src/crypto/external/bsd/openssl/dist/crypto/ec/ec2_smpl.c
diff -u src/crypto/external/bsd/openssl/dist/crypto/ec/ec2_smpl.c:1.5 src/crypto/external/bsd/openssl/dist/crypto/ec/ec2_smpl.c:1.6
--- src/crypto/external/bsd/openssl/dist/crypto/ec/ec2_smpl.c:1.5	Thu Feb  8 16:51:27 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/ec/ec2_smpl.c	Sat Aug 18 04:59:04 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2002-2018 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,6 +330,7 @@ int ec_GF2m_simple_point_copy(EC_POINT *
     if (!BN_copy(dest->Z, src->Z))
         return 0;
     dest->Z_is_one = src->Z_is_one;
+    dest->curve_name = src->curve_name;
 
     return 1;
 }
Index: src/crypto/external/bsd/openssl/dist/crypto/ec/ec_ameth.c
diff -u src/crypto/external/bsd/openssl/dist/crypto/ec/ec_ameth.c:1.5 src/crypto/external/bsd/openssl/dist/crypto/ec/ec_ameth.c:1.6
--- src/crypto/external/bsd/openssl/dist/crypto/ec/ec_ameth.c:1.5	Thu Feb  8 16:51:27 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/ec/ec_ameth.c	Sat Aug 18 04:59:04 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2006-2018 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
@@ -92,19 +92,19 @@ static int eckey_pub_encode(X509_PUBKEY 
 static EC_KEY *eckey_type2param(int ptype, const void *pval)
 {
     EC_KEY *eckey = NULL;
+    EC_GROUP *group = NULL;
+
     if (ptype == V_ASN1_SEQUENCE) {
         const ASN1_STRING *pstr = pval;
-        const unsigned char *pm = NULL;
-        int pmlen;
-        pm = pstr->data;
-        pmlen = pstr->length;
+        const unsigned char *pm = pstr->data;
+        int pmlen = pstr->length;
+
         if ((eckey = d2i_ECParameters(NULL, &pm, pmlen)) == NULL) {
             ECerr(EC_F_ECKEY_TYPE2PARAM, EC_R_DECODE_ERROR);
             goto ecerr;
         }
     } else if (ptype == V_ASN1_OBJECT) {
         const ASN1_OBJECT *poid = pval;
-        EC_GROUP *group;
 
         /*
          * type == V_ASN1_OBJECT => the parameters are given by an asn1 OID
@@ -129,6 +129,7 @@ static EC_KEY *eckey_type2param(int ptyp
 
  ecerr:
     EC_KEY_free(eckey);
+    EC_GROUP_free(group);
     return NULL;
 }
 

Index: src/crypto/external/bsd/openssl/dist/crypto/ec/ec_lcl.h
diff -u src/crypto/external/bsd/openssl/dist/crypto/ec/ec_lcl.h:1.3 src/crypto/external/bsd/openssl/dist/crypto/ec/ec_lcl.h:1.4
--- src/crypto/external/bsd/openssl/dist/crypto/ec/ec_lcl.h:1.3	Thu Feb  8 16:51:27 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/ec/ec_lcl.h	Sat Aug 18 04:59:04 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2001-2018 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
@@ -269,6 +269,8 @@ struct ec_key_st {
 
 struct ec_point_st {
     const EC_METHOD *meth;
+    /* NID for the curve if known */
+    int curve_name;
     /*
      * All members except 'meth' are handled by the method functions, even if
      * they appear generic
@@ -281,6 +283,20 @@ struct ec_point_st {
                                  * special case */
 };
 
+
+static ossl_inline int ec_point_is_compat(const EC_POINT *point,
+                                          const EC_GROUP *group)
+{
+    if (group->meth != point->meth
+        || (group->curve_name != 0
+            && point->curve_name != 0
+            && group->curve_name != point->curve_name))
+        return 0;
+
+    return 1;
+}
+
+
 NISTP224_PRE_COMP *EC_nistp224_pre_comp_dup(NISTP224_PRE_COMP *);
 NISTP256_PRE_COMP *EC_nistp256_pre_comp_dup(NISTP256_PRE_COMP *);
 NISTP521_PRE_COMP *EC_nistp521_pre_comp_dup(NISTP521_PRE_COMP *);
Index: src/crypto/external/bsd/openssl/dist/crypto/ec/ec_lib.c
diff -u src/crypto/external/bsd/openssl/dist/crypto/ec/ec_lib.c:1.3 src/crypto/external/bsd/openssl/dist/crypto/ec/ec_lib.c:1.4
--- src/crypto/external/bsd/openssl/dist/crypto/ec/ec_lib.c:1.3	Thu Feb  8 16:51:27 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/ec/ec_lib.c	Sat Aug 18 04:59:04 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2001-2018 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
@@ -140,6 +140,8 @@ int EC_GROUP_copy(EC_GROUP *dest, const 
     if (dest == src)
         return 1;
 
+    dest->curve_name = src->curve_name;
+
     /* Copy precomputed */
     dest->pre_comp_type = src->pre_comp_type;
     switch (src->pre_comp_type) {
@@ -202,7 +204,6 @@ int EC_GROUP_copy(EC_GROUP *dest, const 
             return 0;
     }
 
-    dest->curve_name = src->curve_name;
     dest->asn1_flag = src->asn1_flag;
     dest->asn1_form = src->asn1_form;
 
@@ -563,6 +564,7 @@ EC_POINT *EC_POINT_new(const EC_GROUP *g
     }
 
     ret->meth = group->meth;
+    ret->curve_name = group->curve_name;
 
     if (!ret->meth->point_init(ret)) {
         OPENSSL_free(ret);
@@ -600,7 +602,10 @@ int EC_POINT_copy(EC_POINT *dest, const 
         ECerr(EC_F_EC_POINT_COPY, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
         return 0;
     }
-    if (dest->meth != src->meth) {
+    if (dest->meth != src->meth
+            || (dest->curve_name != src->curve_name
+                && dest->curve_name != 0
+                && src->curve_name != 0)) {
         ECerr(EC_F_EC_POINT_COPY, EC_R_INCOMPATIBLE_OBJECTS);
         return 0;
     }
@@ -657,7 +662,7 @@ int EC_POINT_set_Jprojective_coordinates
               ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
         return 0;
     }
-    if (group->meth != point->meth) {
+    if (!ec_point_is_compat(point, group)) {
         ECerr(EC_F_EC_POINT_SET_JPROJECTIVE_COORDINATES_GFP,
               EC_R_INCOMPATIBLE_OBJECTS);
         return 0;
@@ -676,7 +681,7 @@ int EC_POINT_get_Jprojective_coordinates
               ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
         return 0;
     }
-    if (group->meth != point->meth) {
+    if (!ec_point_is_compat(point, group)) {
         ECerr(EC_F_EC_POINT_GET_JPROJECTIVE_COORDINATES_GFP,
               EC_R_INCOMPATIBLE_OBJECTS);
         return 0;
@@ -694,7 +699,7 @@ int EC_POINT_set_affine_coordinates_GFp(
               ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
         return 0;
     }
-    if (group->meth != point->meth) {
+    if (!ec_point_is_compat(point, group)) {
         ECerr(EC_F_EC_POINT_SET_AFFINE_COORDINATES_GFP,
               EC_R_INCOMPATIBLE_OBJECTS);
         return 0;
@@ -720,7 +725,7 @@ int EC_POINT_set_affine_coordinates_GF2m
               ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
         return 0;
     }
-    if (group->meth != point->meth) {
+    if (!ec_point_is_compat(point, group)) {
         ECerr(EC_F_EC_POINT_SET_AFFINE_COORDINATES_GF2M,
               EC_R_INCOMPATIBLE_OBJECTS);
         return 0;
@@ -746,7 +751,7 @@ int EC_POINT_get_affine_coordinates_GFp(
               ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
         return 0;
     }
-    if (group->meth != point->meth) {
+    if (!ec_point_is_compat(point, group)) {
         ECerr(EC_F_EC_POINT_GET_AFFINE_COORDINATES_GFP,
               EC_R_INCOMPATIBLE_OBJECTS);
         return 0;
@@ -764,7 +769,7 @@ int EC_POINT_get_affine_coordinates_GF2m
               ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
         return 0;
     }
-    if (group->meth != point->meth) {
+    if (!ec_point_is_compat(point, group)) {
         ECerr(EC_F_EC_POINT_GET_AFFINE_COORDINATES_GF2M,
               EC_R_INCOMPATIBLE_OBJECTS);
         return 0;
@@ -780,8 +785,8 @@ int EC_POINT_add(const EC_GROUP *group, 
         ECerr(EC_F_EC_POINT_ADD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
         return 0;
     }
-    if ((group->meth != r->meth) || (r->meth != a->meth)
-        || (a->meth != b->meth)) {
+    if (!ec_point_is_compat(r, group) || !ec_point_is_compat(a, group)
+        || !ec_point_is_compat(b, group)) {
         ECerr(EC_F_EC_POINT_ADD, EC_R_INCOMPATIBLE_OBJECTS);
         return 0;
     }
@@ -795,7 +800,7 @@ int EC_POINT_dbl(const EC_GROUP *group, 
         ECerr(EC_F_EC_POINT_DBL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
         return 0;
     }
-    if ((group->meth != r->meth) || (r->meth != a->meth)) {
+    if (!ec_point_is_compat(r, group) || !ec_point_is_compat(a, group)) {
         ECerr(EC_F_EC_POINT_DBL, EC_R_INCOMPATIBLE_OBJECTS);
         return 0;
     }
@@ -808,7 +813,7 @@ int EC_POINT_invert(const EC_GROUP *grou
         ECerr(EC_F_EC_POINT_INVERT, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
         return 0;
     }
-    if (group->meth != a->meth) {
+    if (!ec_point_is_compat(a, group)) {
         ECerr(EC_F_EC_POINT_INVERT, EC_R_INCOMPATIBLE_OBJECTS);
         return 0;
     }
@@ -822,7 +827,7 @@ int EC_POINT_is_at_infinity(const EC_GRO
               ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
         return 0;
     }
-    if (group->meth != point->meth) {
+    if (!ec_point_is_compat(point, group)) {
         ECerr(EC_F_EC_POINT_IS_AT_INFINITY, EC_R_INCOMPATIBLE_OBJECTS);
         return 0;
     }
@@ -843,7 +848,7 @@ int EC_POINT_is_on_curve(const EC_GROUP 
         ECerr(EC_F_EC_POINT_IS_ON_CURVE, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
         return 0;
     }
-    if (group->meth != point->meth) {
+    if (!ec_point_is_compat(point, group)) {
         ECerr(EC_F_EC_POINT_IS_ON_CURVE, EC_R_INCOMPATIBLE_OBJECTS);
         return 0;
     }
@@ -857,7 +862,7 @@ int EC_POINT_cmp(const EC_GROUP *group, 
         ECerr(EC_F_EC_POINT_CMP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
         return -1;
     }
-    if ((group->meth != a->meth) || (a->meth != b->meth)) {
+    if (!ec_point_is_compat(a, group) || !ec_point_is_compat(b, group)) {
         ECerr(EC_F_EC_POINT_CMP, EC_R_INCOMPATIBLE_OBJECTS);
         return -1;
     }
@@ -870,7 +875,7 @@ int EC_POINT_make_affine(const EC_GROUP 
         ECerr(EC_F_EC_POINT_MAKE_AFFINE, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
         return 0;
     }
-    if (group->meth != point->meth) {
+    if (!ec_point_is_compat(point, group)) {
         ECerr(EC_F_EC_POINT_MAKE_AFFINE, EC_R_INCOMPATIBLE_OBJECTS);
         return 0;
     }
@@ -887,7 +892,7 @@ int EC_POINTs_make_affine(const EC_GROUP
         return 0;
     }
     for (i = 0; i < num; i++) {
-        if (group->meth != points[i]->meth) {
+        if (!ec_point_is_compat(points[i], group)) {
             ECerr(EC_F_EC_POINTS_MAKE_AFFINE, EC_R_INCOMPATIBLE_OBJECTS);
             return 0;
         }

Index: src/crypto/external/bsd/openssl/dist/crypto/ec/ecp_smpl.c
diff -u src/crypto/external/bsd/openssl/dist/crypto/ec/ecp_smpl.c:1.6 src/crypto/external/bsd/openssl/dist/crypto/ec/ecp_smpl.c:1.7
--- src/crypto/external/bsd/openssl/dist/crypto/ec/ecp_smpl.c:1.6	Fri Apr  6 19:04:44 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/ec/ecp_smpl.c	Sat Aug 18 04:59:04 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2001-2018 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
@@ -352,6 +352,7 @@ int ec_GFp_simple_point_copy(EC_POINT *d
     if (!BN_copy(dest->Z, src->Z))
         return 0;
     dest->Z_is_one = src->Z_is_one;
+    dest->curve_name = src->curve_name;
 
     return 1;
 }

Index: src/crypto/external/bsd/openssl/dist/crypto/engine/eng_lib.c
diff -u src/crypto/external/bsd/openssl/dist/crypto/engine/eng_lib.c:1.3 src/crypto/external/bsd/openssl/dist/crypto/engine/eng_lib.c:1.4
--- src/crypto/external/bsd/openssl/dist/crypto/engine/eng_lib.c:1.3	Thu Feb  8 16:51:28 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/engine/eng_lib.c	Sat Aug 18 04:59:04 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2001-2018 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,7 +18,8 @@ CRYPTO_ONCE engine_lock_init = CRYPTO_ON
 
 DEFINE_RUN_ONCE(do_engine_lock_init)
 {
-    OPENSSL_init_crypto(0, NULL);
+    if (!OPENSSL_init_crypto(0, NULL))
+        return 0;
     global_engine_lock = CRYPTO_THREAD_lock_new();
     return global_engine_lock != NULL;
 }
@@ -143,8 +144,10 @@ void engine_cleanup_add_last(ENGINE_CLEA
     if (!int_cleanup_check(1))
         return;
     item = int_cleanup_item(cb);
-    if (item)
-        sk_ENGINE_CLEANUP_ITEM_push(cleanup_stack, item);
+    if (item != NULL) {
+        if (sk_ENGINE_CLEANUP_ITEM_push(cleanup_stack, item) <= 0)
+            OPENSSL_free(item);
+    }
 }
 
 /* The API function that performs all cleanup */

Index: src/crypto/external/bsd/openssl/dist/crypto/rsa/rsa_oaep.c
diff -u src/crypto/external/bsd/openssl/dist/crypto/rsa/rsa_oaep.c:1.6 src/crypto/external/bsd/openssl/dist/crypto/rsa/rsa_oaep.c:1.7
--- src/crypto/external/bsd/openssl/dist/crypto/rsa/rsa_oaep.c:1.6	Thu Feb  8 16:51:31 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/rsa/rsa_oaep.c	Sat Aug 18 04:59:04 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1999-2018 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
@@ -155,32 +155,40 @@ int RSA_padding_check_PKCS1_OAEP_mgf1(un
 
     dblen = num - mdlen - 1;
     db = OPENSSL_malloc(dblen);
-    em = OPENSSL_malloc(num);
-    if (db == NULL || em == NULL) {
+    if (db == NULL) {
         RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_OAEP_MGF1, ERR_R_MALLOC_FAILURE);
         goto cleanup;
     }
 
-    /*
-     * Always do this zero-padding copy (even when num == flen) to avoid
-     * leaking that information. The copy still leaks some side-channel
-     * information, but it's impossible to have a fixed  memory access
-     * pattern since we can't read out of the bounds of |from|.
-     *
-     * TODO(emilia): Consider porting BN_bn2bin_padded from BoringSSL.
-     */
-    memset(em, 0, num);
-    memcpy(em + num - flen, from, flen);
+    if (flen != num) {
+        em = OPENSSL_zalloc(num);
+        if (em == NULL) {
+            RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_OAEP_MGF1,
+                   ERR_R_MALLOC_FAILURE);
+            goto cleanup;
+        }
+
+        /*
+         * Caller is encouraged to pass zero-padded message created with
+         * BN_bn2binpad, but if it doesn't, we do this zero-padding copy
+         * to avoid leaking that information. The copy still leaks some
+         * side-channel information, but it's impossible to have a fixed
+         * memory access pattern since we can't read out of the bounds of
+         * |from|.
+         */
+        memcpy(em + num - flen, from, flen);
+        from = em;
+    }
 
     /*
      * The first byte must be zero, however we must not leak if this is
      * true. See James H. Manger, "A Chosen Ciphertext  Attack on RSA
      * Optimal Asymmetric Encryption Padding (OAEP) [...]", CRYPTO 2001).
      */
-    good = constant_time_is_zero(em[0]);
+    good = constant_time_is_zero(from[0]);
 
-    maskedseed = em + 1;
-    maskeddb = em + 1 + mdlen;
+    maskedseed = from + 1;
+    maskeddb = from + 1 + mdlen;
 
     if (PKCS1_MGF1(seed, mdlen, maskeddb, dblen, mgf1md))
         goto cleanup;

Index: src/crypto/external/bsd/openssl/dist/crypto/rsa/rsa_pk1.c
diff -u src/crypto/external/bsd/openssl/dist/crypto/rsa/rsa_pk1.c:1.4 src/crypto/external/bsd/openssl/dist/crypto/rsa/rsa_pk1.c:1.5
--- src/crypto/external/bsd/openssl/dist/crypto/rsa/rsa_pk1.c:1.4	Thu Feb  8 16:51:31 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/rsa/rsa_pk1.c	Sat Aug 18 04:59:04 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2018 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
@@ -175,27 +175,30 @@ int RSA_padding_check_PKCS1_type_2(unsig
     if (num < 11)
         goto err;
 
-    em = OPENSSL_zalloc(num);
-    if (em == NULL) {
-        RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_2, ERR_R_MALLOC_FAILURE);
-        return -1;
+    if (flen != num) {
+        em = OPENSSL_zalloc(num);
+        if (em == NULL) {
+            RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_2, ERR_R_MALLOC_FAILURE);
+            return -1;
+        }
+        /*
+         * Caller is encouraged to pass zero-padded message created with
+         * BN_bn2binpad, but if it doesn't, we do this zero-padding copy
+         * to avoid leaking that information. The copy still leaks some
+         * side-channel information, but it's impossible to have a fixed
+         * memory access pattern since we can't read out of the bounds of
+         * |from|.
+         */
+        memcpy(em + num - flen, from, flen);
+        from = em;
     }
-    /*
-     * Always do this zero-padding copy (even when num == flen) to avoid
-     * leaking that information. The copy still leaks some side-channel
-     * information, but it's impossible to have a fixed memory access
-     * pattern since we can't read out of the bounds of |from|.
-     *
-     * TODO(emilia): Consider porting BN_bn2bin_padded from BoringSSL.
-     */
-    memcpy(em + num - flen, from, flen);
 
-    good = constant_time_is_zero(em[0]);
-    good &= constant_time_eq(em[1], 2);
+    good = constant_time_is_zero(from[0]);
+    good &= constant_time_eq(from[1], 2);
 
     found_zero_byte = 0;
     for (i = 2; i < num; i++) {
-        unsigned int equals0 = constant_time_is_zero(em[i]);
+        unsigned int equals0 = constant_time_is_zero(from[i]);
         zero_index =
             constant_time_select_int(~found_zero_byte & equals0, i,
                                      zero_index);
@@ -203,7 +206,7 @@ int RSA_padding_check_PKCS1_type_2(unsig
     }
 
     /*
-     * PS must be at least 8 bytes long, and it starts two bytes into |em|.
+     * PS must be at least 8 bytes long, and it starts two bytes into |from|.
      * If we never found a 0-byte, then |zero_index| is 0 and the check
      * also fails.
      */
@@ -232,7 +235,7 @@ int RSA_padding_check_PKCS1_type_2(unsig
         goto err;
     }
 
-    memcpy(to, em + msg_index, mlen);
+    memcpy(to, from + msg_index, mlen);
 
  err:
     OPENSSL_clear_free(em, num);

Index: src/crypto/external/bsd/openssl/dist/crypto/ui/ui_openssl.c
diff -u src/crypto/external/bsd/openssl/dist/crypto/ui/ui_openssl.c:1.10 src/crypto/external/bsd/openssl/dist/crypto/ui/ui_openssl.c:1.11
--- src/crypto/external/bsd/openssl/dist/crypto/ui/ui_openssl.c:1.10	Thu Feb  8 16:51:32 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/ui/ui_openssl.c	Sat Aug 18 04:59:04 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2001-2018 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
@@ -519,17 +519,13 @@ static int echo_console(UI *ui)
 {
 #if defined(TTY_set) && !defined(OPENSSL_SYS_VMS)
     memcpy(&(tty_new), &(tty_orig), sizeof(tty_orig));
-    tty_new.TTY_FLAGS |= ECHO;
-#endif
-
-#if defined(TTY_set) && !defined(OPENSSL_SYS_VMS)
     if (is_a_tty && (TTY_set(fileno(tty_in), &tty_new) == -1))
         return 0;
 #endif
 #ifdef OPENSSL_SYS_VMS
     if (is_a_tty) {
         tty_new[0] = tty_orig[0];
-        tty_new[1] = tty_orig[1] & ~TT$M_NOECHO;
+        tty_new[1] = tty_orig[1];
         tty_new[2] = tty_orig[2];
         status = sys$qiow(0, channel, IO$_SETMODE, &iosb, 0, 0, tty_new, 12,
                           0, 0, 0, 0);
@@ -550,7 +546,6 @@ static int echo_console(UI *ui)
 #if defined(_WIN32) && !defined(_WIN32_WCE)
     if (is_a_tty) {
         tty_new = tty_orig;
-        tty_new |= ENABLE_ECHO_INPUT;
         SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), tty_new);
     }
 #endif

Index: src/crypto/external/bsd/openssl/dist/crypto/x509/x509_vfy.c
diff -u src/crypto/external/bsd/openssl/dist/crypto/x509/x509_vfy.c:1.12 src/crypto/external/bsd/openssl/dist/crypto/x509/x509_vfy.c:1.13
--- src/crypto/external/bsd/openssl/dist/crypto/x509/x509_vfy.c:1.12	Thu Feb  8 16:51:32 2018
+++ src/crypto/external/bsd/openssl/dist/crypto/x509/x509_vfy.c	Sat Aug 18 04:59:05 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2018 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,7 @@
  * https://www.openssl.org/source/license.html
  */
 
+#include <ctype.h>
 #include <stdio.h>
 #include <time.h>
 #include <errno.h>
@@ -557,6 +558,27 @@ static int check_chain_extensions(X509_S
     return 1;
 }
 
+static int has_san_id(X509 *x, int gtype)
+{
+    int i;
+    int ret = 0;
+    GENERAL_NAMES *gs = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
+
+    if (gs == NULL)
+        return 0;
+
+    for (i = 0; i < sk_GENERAL_NAME_num(gs); i++) {
+        GENERAL_NAME *g = sk_GENERAL_NAME_value(gs, i);
+
+        if (g->type == gtype) {
+            ret = 1;
+            break;
+        }
+    }
+    GENERAL_NAMES_free(gs);
+    return ret;
+}
+
 static int check_name_constraints(X509_STORE_CTX *ctx)
 {
     int i;
@@ -655,7 +677,12 @@ static int check_name_constraints(X509_S
                 int rv = NAME_CONSTRAINTS_check(x, nc);
 
                 /* If EE certificate check commonName too */
-                if (rv == X509_V_OK && i == 0)
+                if (rv == X509_V_OK && i == 0
+                    && (ctx->param->hostflags
+                        & X509_CHECK_FLAG_NEVER_CHECK_SUBJECT) == 0
+                    && ((ctx->param->hostflags
+                         & X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT) != 0
+                        || !has_san_id(x, GEN_DNS)))
                     rv = NAME_CONSTRAINTS_check_CN(x, nc);
 
                 switch (rv) {
@@ -1756,119 +1783,67 @@ int X509_cmp_current_time(const ASN1_TIM
 
 int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time)
 {
-    char *str;
-    ASN1_TIME atm;
-    long offset;
-    char buff1[24], buff2[24], *p;
-    int i, j, remaining;
-
-    p = buff1;
-    remaining = ctm->length;
-    str = (char *)ctm->data;
+    static const size_t utctime_length = sizeof("YYMMDDHHMMSSZ") - 1;
+    static const size_t generalizedtime_length = sizeof("YYYYMMDDHHMMSSZ") - 1;
+    ASN1_TIME *asn1_cmp_time = NULL;
+    int i, day, sec, ret = 0;
+
     /*
-     * Note that the following (historical) code allows much more slack in the
-     * time format than RFC5280. In RFC5280, the representation is fixed:
+     * Note that ASN.1 allows much more slack in the time format than RFC5280.
+     * In RFC5280, the representation is fixed:
      * UTCTime: YYMMDDHHMMSSZ
      * GeneralizedTime: YYYYMMDDHHMMSSZ
-     */
-    if (ctm->type == V_ASN1_UTCTIME) {
-        /* YYMMDDHHMM[SS]Z or YYMMDDHHMM[SS](+-)hhmm */
-        int min_length = sizeof("YYMMDDHHMMZ") - 1;
-        int max_length = sizeof("YYMMDDHHMMSS+hhmm") - 1;
-        if (remaining < min_length || remaining > max_length)
-            return 0;
-        memcpy(p, str, 10);
-        p += 10;
-        str += 10;
-        remaining -= 10;
-    } else {
-        /* YYYYMMDDHHMM[SS[.fff]]Z or YYYYMMDDHHMM[SS[.f[f[f]]]](+-)hhmm */
-        int min_length = sizeof("YYYYMMDDHHMMZ") - 1;
-        int max_length = sizeof("YYYYMMDDHHMMSS.fff+hhmm") - 1;
-        if (remaining < min_length || remaining > max_length)
-            return 0;
-        memcpy(p, str, 12);
-        p += 12;
-        str += 12;
-        remaining -= 12;
-    }
-
-    if ((*str == 'Z') || (*str == '-') || (*str == '+')) {
-        *(p++) = '0';
-        *(p++) = '0';
-    } else {
-        /* SS (seconds) */
-        if (remaining < 2)
+     *
+     * We do NOT currently enforce the following RFC 5280 requirement:
+     * "CAs conforming to this profile MUST always encode certificate
+     *  validity dates through the year 2049 as UTCTime; certificate validity
+     *  dates in 2050 or later MUST be encoded as GeneralizedTime."
+     */
+    switch (ctm->type) {
+    case V_ASN1_UTCTIME:
+        if (ctm->length != (int)(utctime_length))
             return 0;
-        *(p++) = *(str++);
-        *(p++) = *(str++);
-        remaining -= 2;
-        /*
-         * Skip any (up to three) fractional seconds...
-         * TODO(emilia): in RFC5280, fractional seconds are forbidden.
-         * Can we just kill them altogether?
-         */
-        if (remaining && *str == '.') {
-            str++;
-            remaining--;
-            for (i = 0; i < 3 && remaining; i++, str++, remaining--) {
-                if (*str < '0' || *str > '9')
-                    break;
-            }
-        }
-
+        break;
+    case V_ASN1_GENERALIZEDTIME:
+        if (ctm->length != (int)(generalizedtime_length))
+            return 0;
+        break;
+    default:
+        return 0;
     }
-    *(p++) = 'Z';
-    *(p++) = '\0';
 
-    /* We now need either a terminating 'Z' or an offset. */
-    if (!remaining)
-        return 0;
-    if (*str == 'Z') {
-        if (remaining != 1)
-            return 0;
-        offset = 0;
-    } else {
-        /* (+-)HHMM */
-        if ((*str != '+') && (*str != '-'))
-            return 0;
-        /* Historical behaviour: the (+-)hhmm offset is forbidden in RFC5280. */
-        if (remaining != 5)
-            return 0;
-        if (str[1] < '0' || str[1] > '9' || str[2] < '0' || str[2] > '9' ||
-            str[3] < '0' || str[3] > '9' || str[4] < '0' || str[4] > '9')
+    /**
+     * Verify the format: the ASN.1 functions we use below allow a more
+     * flexible format than what's mandated by RFC 5280.
+     * Digit and date ranges will be verified in the conversion methods.
+     */
+    for (i = 0; i < ctm->length - 1; i++) {
+        if (!isdigit(ctm->data[i]))
             return 0;
-        offset = ((str[1] - '0') * 10 + (str[2] - '0')) * 60;
-        offset += (str[3] - '0') * 10 + (str[4] - '0');
-        if (*str == '-')
-            offset = -offset;
-    }
-    atm.type = ctm->type;
-    atm.flags = 0;
-    atm.length = sizeof(buff2);
-    atm.data = (unsigned char *)buff2;
-
-    if (X509_time_adj(&atm, offset * 60, cmp_time) == NULL)
-        return 0;
-
-    if (ctm->type == V_ASN1_UTCTIME) {
-        i = (buff1[0] - '0') * 10 + (buff1[1] - '0');
-        if (i < 50)
-            i += 100;           /* cf. RFC 2459 */
-        j = (buff2[0] - '0') * 10 + (buff2[1] - '0');
-        if (j < 50)
-            j += 100;
-
-        if (i < j)
-            return -1;
-        if (i > j)
-            return 1;
     }
-    i = strcmp(buff1, buff2);
-    if (i == 0)                 /* wait a second then return younger :-) */
-        return -1;
-    else
-        return i;
+    if (ctm->data[ctm->length - 1] != 'Z')
+        return 0;
+
+    /*
+     * There is ASN1_UTCTIME_cmp_time_t but no
+     * ASN1_GENERALIZEDTIME_cmp_time_t or ASN1_TIME_cmp_time_t,
+     * so we go through ASN.1
+     */
+    asn1_cmp_time = X509_time_adj(NULL, 0, cmp_time);
+    if (asn1_cmp_time == NULL)
+        goto err;
+    if (!ASN1_TIME_diff(&day, &sec, ctm, asn1_cmp_time))
+        goto err;
+
+    /*
+     * X509_cmp_time comparison is <=.
+     * The return value 0 is reserved for errors.
+     */
+    ret = (day >= 0 && sec >= 0) ? -1 : 1;
+
+ err:
+    ASN1_TIME_free(asn1_cmp_time);
+    return ret;
 }
 
 ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj)
@@ -3264,6 +3239,10 @@ static int check_sig_level(X509_STORE_CT
     if (level > NUM_AUTH_LEVELS)
         level = NUM_AUTH_LEVELS;
 
+    /* We are not able to look up the CA MD for RSA PSS in this version */
+    if (nid == NID_rsassaPss)
+        return 1;
+
     /* Lookup signature algorithm digest */
     if (nid && OBJ_find_sigid_algs(nid, &mdnid, NULL)) {
         const EVP_MD *md;

Index: src/crypto/external/bsd/openssl/dist/doc/apps/genpkey.pod
diff -u src/crypto/external/bsd/openssl/dist/doc/apps/genpkey.pod:1.4 src/crypto/external/bsd/openssl/dist/doc/apps/genpkey.pod:1.5
--- src/crypto/external/bsd/openssl/dist/doc/apps/genpkey.pod:1.4	Thu Feb  8 16:51:34 2018
+++ src/crypto/external/bsd/openssl/dist/doc/apps/genpkey.pod	Sat Aug 18 04:59:05 2018
@@ -12,7 +12,7 @@ B<openssl> B<genpkey>
 [B<-out filename>]
 [B<-outform PEM|DER>]
 [B<-pass arg>]
-[B<-cipher>]
+[B<-I<cipher>>]
 [B<-engine id>]
 [B<-paramfile file>]
 [B<-algorithm alg>]
@@ -39,21 +39,21 @@ standard output is used.
 
 =item B<-outform DER|PEM>
 
-This specifies the output format DER or PEM.
+This specifies the output format DER or PEM. The default format is PEM.
 
 =item B<-pass arg>
 
-the output file password source. For more information about the format of B<arg>
+The output file password source. For more information about the format of B<arg>
 see the B<PASS PHRASE ARGUMENTS> section in L<openssl(1)>.
 
-=item B<-cipher>
+=item B<-I<cipher>>
 
 This option encrypts the private key with the supplied cipher. Any algorithm
 name accepted by EVP_get_cipherbyname() is acceptable such as B<des3>.
 
 =item B<-engine id>
 
-specifying an engine (by its unique B<id> string) will cause B<genpkey>
+Specifying an engine (by its unique B<id> string) will cause B<genpkey>
 to attempt to obtain a functional reference to the specified engine,
 thus initialising it if needed. The engine will then be set as the default
 for all available algorithms. If used this option should precede all other
@@ -61,19 +61,32 @@ options.
 
 =item B<-algorithm alg>
 
-public key algorithm to use such as RSA, DSA or DH. If used this option must
+Public key algorithm to use such as RSA, DSA or DH. If used this option must
 precede any B<-pkeyopt> options. The options B<-paramfile> and B<-algorithm>
-are mutually exclusive.
+are mutually exclusive. Engines may add algorithms in addition to the standard
+built-in ones.
+
+Valid built-in algorithm names for private key generation are RSA and EC.
+
+Valid built-in algorithm names for parameter generation (see the B<-genparam>
+option) are DH, DSA and EC.
+
+Note that the algorithm name X9.42 DH may be used as a synonym for the DH
+algorithm. These are identical and do not indicate the type of parameters that
+will be generated. Use the B<dh_paramgen_type> option to indicate whether PKCS#3
+or X9.42 DH parameters are required. See L<DH Parameter Generation Options>
+below for more details.
 
 =item B<-pkeyopt opt:value>
 
-set the public key algorithm option B<opt> to B<value>. The precise set of
+Set the public key algorithm option B<opt> to B<value>. The precise set of
 options supported depends on the public key algorithm used and its
-implementation. See B<KEY GENERATION OPTIONS> below for more details.
+implementation. See L<KEY GENERATION OPTIONS> and
+L<PARAMETER GENERATION OPTIONS> below for more details.
 
 =item B<-genparam>
 
-generate a set of parameters instead of a private key. If used this option must
+Generate a set of parameters instead of a private key. If used this option must
 precede any B<-algorithm>, B<-paramfile> or B<-pkeyopt> options.
 
 =item B<-paramfile filename>
@@ -97,7 +110,7 @@ The options supported by each algorithm 
 algorithm can vary. The options for the OpenSSL implementations are detailed
 below.
 
-=head1 RSA KEY GENERATION OPTIONS
+=head2 RSA Key Generation Options
 
 =over 4
 
@@ -112,91 +125,92 @@ hexadecimal value if preceded by B<0x>. 
 
 =back
 
-=head1 DSA PARAMETER GENERATION OPTIONS
+=head2 EC Key Generation Options
+
+The EC key generation options can also be used for parameter generation.
 
 =over 4
 
-=item B<dsa_paramgen_bits:numbits>
+=item B<ec_paramgen_curve:curve>
+
+The EC curve to use. OpenSSL supports NIST curve names such as "P-256".
+
+=item B<ec_param_enc:encoding>
 
-The number of bits in the generated parameters. If not specified 1024 is used.
+The encoding to use for parameters. The "encoding" parameter must be either
+"named_curve" or "explicit". The default value is "named_curve".
 
 =back
 
-=head1 DH PARAMETER GENERATION OPTIONS
+=head1 PARAMETER GENERATION OPTIONS
+
+The options supported by each algorithm and indeed each implementation of an
+algorithm can vary. The options for the OpenSSL implementations are detailed
+below.
+
+=head2 DSA Parameter Generation Options
 
 =over 4
 
-=item B<dh_paramgen_prime_len:numbits>
+=item B<dsa_paramgen_bits:numbits>
 
-The number of bits in the prime parameter B<p>.
+The number of bits in the generated prime. If not specified 1024 is used.
 
-=item B<dh_paramgen_generator:value>
+=item B<dsa_paramgen_q_bits:numbits>
 
-The value to use for the generator B<g>.
+The number of bits in the q parameter. Must be one of 160, 224 or 256. If not
+specified 160 is used.
 
-=item B<dh_rfc5114:num>
+=item B<dsa_paramgen_md:digest>
 
-If this option is set then the appropriate RFC5114 parameters are used
-instead of generating new parameters. The value B<num> can take the
-values 1, 2 or 3 corresponding to RFC5114 DH parameters consisting of
-1024 bit group with 160 bit subgroup, 2048 bit group with 224 bit subgroup
-and 2048 bit group with 256 bit subgroup as mentioned in RFC5114 sections
-2.1, 2.2 and 2.3 respectively.
+The digest to use during parameter generation. Must be one of B<sha1>, B<sha224>
+or B<sha256>. If set, then the number of bits in B<q> will match the output size
+of the specified digest and the B<dsa_paramgen_q_bits> parameter will be
+ignored. If not set, then a digest will be used that gives an output matching
+the number of bits in B<q>, i.e. B<sha1> if q length is 160, B<sha224> if it 224
+or B<sha256> if it is 256.
 
 =back
 
-=head1 EC PARAMETER GENERATION OPTIONS
-
-The EC parameter generation options below can also
-be supplied as EC key generation options. This can (for example) generate a
-key from a named curve without the need to use an explicit parameter file.
+=head2 DH Parameter Generation Options
 
 =over 4
 
-=item B<ec_paramgen_curve:curve>
+=item B<dh_paramgen_prime_len:numbits>
 
-the EC curve to use. OpenSSL supports NIST curve names such as "P-256".
+The number of bits in the prime parameter B<p>. The default is 1024.
 
-=item B<ec_param_enc:encoding>
+=item B<dh_paramgen_subprime_len:numbits>
 
-the encoding to use for parameters. The "encoding" parameter must be either
-"named_curve" or "explicit".
+The number of bits in the sub prime parameter B<q>. The default is 256 if the
+prime is at least 2048 bits long or 160 otherwise. Only relevant if used in
+conjunction with the B<dh_paramgen_type> option to generate X9.42 DH parameters.
 
-=back
+=item B<dh_paramgen_generator:value>
 
-=head1 GOST2001 KEY GENERATION AND PARAMETER OPTIONS
+The value to use for the generator B<g>. The default is 2.
 
-Gost 2001 support is not enabled by default. To enable this algorithm,
-one should load the ccgost engine in the OpenSSL configuration file.
-See README.gost file in the engines/ccgost directory of the source
-distribution for more details.
-
-Use of a parameter file for the GOST R 34.10 algorithm is optional.
-Parameters can be specified during key generation directly as well as
-during generation of parameter file.
+=item B<dh_paramgen_type:value>
 
-=over 4
+The type of DH parameters to generate. Use 0 for PKCS#3 DH and 1 for X9.42 DH.
+The default is 0.
 
-=item B<paramset:name>
+=item B<dh_rfc5114:num>
 
-Specifies GOST R 34.10-2001 parameter set according to RFC 4357.
-Parameter set can be specified using abbreviated name, object short name or
-numeric OID. Following parameter sets are supported:
-
-  paramset   OID               Usage
-  A          1.2.643.2.2.35.1  Signature
-  B          1.2.643.2.2.35.2  Signature
-  C          1.2.643.2.2.35.3  Signature
-  XA         1.2.643.2.2.36.0  Key exchange
-  XB         1.2.643.2.2.36.1  Key exchange
-  test       1.2.643.2.2.35.0  Test purposes
+If this option is set, then the appropriate RFC5114 parameters are used
+instead of generating new parameters. The value B<num> can take the
+values 1, 2 or 3 corresponding to RFC5114 DH parameters consisting of
+1024 bit group with 160 bit subgroup, 2048 bit group with 224 bit subgroup
+and 2048 bit group with 256 bit subgroup as mentioned in RFC5114 sections
+2.1, 2.2 and 2.3 respectively. If present this overrides all other DH parameter
+options.
 
 =back
 
-=head1 X25519 KEY GENERATION OPTIONS
-
-The X25519 algorithm does not currently support any key generation options.
+=head2 EC Parameter Generation Options
 
+The EC parameter generation options are the same as for key generation. See
+L<EC Key Generation Options> above.
 
 =head1 NOTES
 
@@ -219,19 +233,25 @@ Generate a 2048 bit RSA key using 3 as t
  openssl genpkey -algorithm RSA -out key.pem -pkeyopt rsa_keygen_bits:2048 \
                                                 -pkeyopt rsa_keygen_pubexp:3
 
-Generate 1024 bit DSA parameters:
+Generate 2048 bit DSA parameters:
 
  openssl genpkey -genparam -algorithm DSA -out dsap.pem \
-                                                -pkeyopt dsa_paramgen_bits:1024
+                                                -pkeyopt dsa_paramgen_bits:2048
 
 Generate DSA key from parameters:
 
  openssl genpkey -paramfile dsap.pem -out dsakey.pem
 
-Generate 1024 bit DH parameters:
+Generate 2048 bit DH parameters:
 
  openssl genpkey -genparam -algorithm DH -out dhp.pem \
-                                        -pkeyopt dh_paramgen_prime_len:1024
+                                        -pkeyopt dh_paramgen_prime_len:2048
+
+Generate 2048 bit X9.42 DH parameters:
+
+ openssl genpkey -genparam -algorithm DH -out dhpx.pem \
+                                        -pkeyopt dh_paramgen_prime_len:2048 \
+                                        -pkeyopt dh_paramgen_type:1
 
 Output RFC5114 2048 bit DH parameters with 224 bit subgroup:
 
@@ -264,11 +284,12 @@ Generate an X25519 private key:
 =head1 HISTORY
 
 The ability to use NIST curve names, and to generate an EC key directly,
-were added in OpenSSL 1.0.2.
+were added in OpenSSL 1.0.2. The ability to generate X25519 keys was added in
+OpenSSL 1.1.0.
 
 =head1 COPYRIGHT
 
-Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2006-2018 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

Index: src/crypto/external/bsd/openssl/dist/doc/crypto/EVP_DigestInit.pod
diff -u src/crypto/external/bsd/openssl/dist/doc/crypto/EVP_DigestInit.pod:1.4 src/crypto/external/bsd/openssl/dist/doc/crypto/EVP_DigestInit.pod:1.5
--- src/crypto/external/bsd/openssl/dist/doc/crypto/EVP_DigestInit.pod:1.4	Thu Feb  8 16:51:35 2018
+++ src/crypto/external/bsd/openssl/dist/doc/crypto/EVP_DigestInit.pod	Sat Aug 18 04:59:05 2018
@@ -3,11 +3,12 @@
 =head1 NAME
 
 EVP_MD_CTX_new, EVP_MD_CTX_reset, EVP_MD_CTX_free, EVP_MD_CTX_copy_ex,
+EVP_MD_CTX_set_flags, EVP_MD_CTX_clear_flags, EVP_MD_CTX_test_flags,
 EVP_DigestInit_ex, EVP_DigestUpdate, EVP_DigestFinal_ex,
 EVP_DigestInit, EVP_DigestFinal, EVP_MD_CTX_copy, EVP_MD_type,
 EVP_MD_pkey_type, EVP_MD_size, EVP_MD_block_size, EVP_MD_CTX_md, EVP_MD_CTX_size,
-EVP_MD_CTX_block_size, EVP_MD_CTX_type, EVP_md_null, EVP_md2, EVP_md5, EVP_sha1,
-EVP_sha224, EVP_sha256, EVP_sha384, EVP_sha512, EVP_mdc2,
+EVP_MD_CTX_block_size, EVP_MD_CTX_type, EVP_MD_CTX_md_data, EVP_md_null, EVP_md2,
+EVP_md5, EVP_sha1, EVP_sha224, EVP_sha256, EVP_sha384, EVP_sha512, EVP_mdc2,
 EVP_ripemd160, EVP_blake2b512, EVP_blake2s256, EVP_get_digestbyname,
 EVP_get_digestbynid, EVP_get_digestbyobj - EVP digest routines
 
@@ -18,6 +19,9 @@ EVP_get_digestbynid, EVP_get_digestbyobj
  EVP_MD_CTX *EVP_MD_CTX_new(void);
  int EVP_MD_CTX_reset(EVP_MD_CTX *ctx);
  void EVP_MD_CTX_free(EVP_MD_CTX *ctx);
+ void EVP_MD_CTX_set_flags(EVP_MD_CTX *ctx, int flags);
+ void EVP_MD_CTX_clear_flags(EVP_MD_CTX *ctx, int flags);
+ int EVP_MD_CTX_test_flags(const EVP_MD_CTX *ctx, int flags);
 
  int EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *impl);
  int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *d, size_t cnt);
@@ -41,6 +45,7 @@ EVP_get_digestbynid, EVP_get_digestbyobj
  int EVP_MD_CTX_size(const EVP_MD *ctx);
  int EVP_MD_CTX_block_size(const EVP_MD *ctx);
  int EVP_MD_CTX_type(const EVP_MD *ctx);
+ void *EVP_MD_CTX_md_data(const EVP_MD_CTX *ctx);
 
  const EVP_MD *EVP_md_null(void);
  const EVP_MD *EVP_md2(void);
@@ -73,6 +78,9 @@ to reuse an already existing context.
 EVP_MD_CTX_free() cleans up digest context B<ctx> and frees up the
 space allocated to it.
 
+EVP_MD_CTX_set_flags(), EVP_MD_CTX_clear_flags() and EVP_MD_CTX_test_flags()
+sets, clears and tests B<ctx> flags.  See L</FLAGS> below for more information.
+
 EVP_DigestInit_ex() sets up digest context B<ctx> to use a digest
 B<type> from ENGINE B<impl>. B<ctx> must be initialized before calling this
 function. B<type> will typically be supplied by a function such as EVP_sha1().
@@ -117,6 +125,11 @@ representing the given message digest wh
 For example EVP_MD_type(EVP_sha1()) returns B<NID_sha1>. This function is
 normally used when setting ASN1 OIDs.
 
+EVP_MD_CTX_md_data() return the digest method private data for the passed
+B<EVP_MD_CTX>.
+The space is allocated by OpenSSL and has the size originally set with
+EVP_MD_meth_set_app_datasize().
+
 EVP_MD_CTX_md() returns the B<EVP_MD> structure corresponding to the passed
 B<EVP_MD_CTX>.
 
@@ -139,6 +152,38 @@ EVP_get_digestbyname(), EVP_get_digestby
 return an B<EVP_MD> structure when passed a digest name, a digest NID or
 an ASN1_OBJECT structure respectively.
 
+=head1 FLAGS
+
+EVP_MD_CTX_set_flags(), EVP_MD_CTX_clear_flags() and EVP_MD_CTX_test_flags()
+can be used the manipulate and test these B<EVP_MD_CTX> flags:
+
+=over 4
+
+=item EVP_MD_CTX_FLAG_ONESHOT
+
+This flag instructs the digest to optimize for one update only, if possible.
+
+=for comment EVP_MD_CTX_FLAG_CLEANED is internal, don't mention it
+
+=for comment EVP_MD_CTX_FLAG_REUSE is internal, don't mention it
+
+=for comment We currently avoid documenting flags that are only bit holder:
+EVP_MD_CTX_FLAG_NON_FIPS_ALLOW, EVP_MD_CTX_FLAGS_PAD_*
+
+=item EVP_MD_CTX_FLAG_NO_INIT
+
+This flag instructs EVP_DigestInit() and similar not to initialise the
+implementation specific data.
+
+=item EVP_MD_CTX_FLAG_FINALISE
+
+Some functions such as EVP_DigestSign only finalise copies of internal
+contexts so additional data can be included after the finalisation call.
+This is inefficient if this functionality is not required, and can be
+disabled with this flag.
+
+=back
+
 =head1 RETURN VALUES
 
 EVP_DigestInit_ex(), EVP_DigestUpdate() and EVP_DigestFinal_ex() return 1 for
@@ -249,7 +294,7 @@ was removed in OpenSSL 1.1.0
 
 =head1 COPYRIGHT
 
-Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
+Copyright 2000-2018 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

Index: src/crypto/external/bsd/openssl/dist/ssl/ssl_ciph.c
diff -u src/crypto/external/bsd/openssl/dist/ssl/ssl_ciph.c:1.14 src/crypto/external/bsd/openssl/dist/ssl/ssl_ciph.c:1.15
--- src/crypto/external/bsd/openssl/dist/ssl/ssl_ciph.c:1.14	Fri Apr  6 19:04:45 2018
+++ src/crypto/external/bsd/openssl/dist/ssl/ssl_ciph.c	Sat Aug 18 04:59:05 2018
@@ -101,10 +101,7 @@ static const ssl_cipher_table ssl_cipher
     {SSL_CHACHA20POLY1305, NID_chacha20_poly1305},
 };
 
-static const EVP_CIPHER *ssl_cipher_methods[SSL_ENC_NUM_IDX] = {
-    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
-    NULL, NULL
-};
+static const EVP_CIPHER *ssl_cipher_methods[SSL_ENC_NUM_IDX];
 
 #define SSL_COMP_NULL_IDX       0
 #define SSL_COMP_ZLIB_IDX       1

Index: src/crypto/external/bsd/openssl/dist/ssl/ssl_lib.c
diff -u src/crypto/external/bsd/openssl/dist/ssl/ssl_lib.c:1.11 src/crypto/external/bsd/openssl/dist/ssl/ssl_lib.c:1.12
--- src/crypto/external/bsd/openssl/dist/ssl/ssl_lib.c:1.11	Fri Apr  6 19:04:45 2018
+++ src/crypto/external/bsd/openssl/dist/ssl/ssl_lib.c	Sat Aug 18 04:59:05 2018
@@ -2213,28 +2213,37 @@ int SSL_set_cipher_list(SSL *s, const ch
     return 1;
 }
 
-char *SSL_get_shared_ciphers(const SSL *s, char *buf, int len)
+char *SSL_get_shared_ciphers(const SSL *s, char *buf, int size)
 {
     char *p;
-    STACK_OF(SSL_CIPHER) *sk;
+    STACK_OF(SSL_CIPHER) *clntsk, *srvrsk;
     const SSL_CIPHER *c;
     int i;
 
-    if ((s->session == NULL) || (s->session->ciphers == NULL) || (len < 2))
-        return (NULL);
+    if (!s->server
+            || s->session == NULL
+            || s->session->ciphers == NULL
+            || size < 2)
+        return NULL;
 
     p = buf;
-    sk = s->session->ciphers;
+    clntsk = s->session->ciphers;
+    srvrsk = SSL_get_ciphers(s);
+    if (clntsk == NULL || srvrsk == NULL)
+        return NULL;
 
-    if (sk_SSL_CIPHER_num(sk) == 0)
+    if (sk_SSL_CIPHER_num(clntsk) == 0 || sk_SSL_CIPHER_num(srvrsk) == 0)
         return NULL;
 
-    for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
+    for (i = 0; i < sk_SSL_CIPHER_num(clntsk); i++) {
         int n;
 
-        c = sk_SSL_CIPHER_value(sk, i);
+        c = sk_SSL_CIPHER_value(clntsk, i);
+        if (sk_SSL_CIPHER_find(srvrsk, c) < 0)
+            continue;
+
         n = strlen(c->name);
-        if (n + 1 > len) {
+        if (n + 1 > size) {
             if (p != buf)
                 --p;
             *p = '\0';
@@ -2243,7 +2252,7 @@ char *SSL_get_shared_ciphers(const SSL *
         memcpy(p, c->name, n + 1);
         p += n;
         *(p++) = ':';
-        len -= n + 1;
+        size -= n + 1;
     }
     p[-1] = '\0';
     return (buf);
@@ -3035,12 +3044,13 @@ void ssl_update_cache(SSL *s, int mode)
     /*
      * If sid_ctx_length is 0 there is no specific application context
      * associated with this session, so when we try to resume it and
-     * SSL_VERIFY_PEER is requested, we have no indication that this is
-     * actually a session for the proper application context, and the
-     * *handshake* will fail, not just the resumption attempt.
-     * Do not cache these sessions that are not resumable.
+     * SSL_VERIFY_PEER is requested to verify the client identity, we have no
+     * indication that this is actually a session for the proper application
+     * context, and the *handshake* will fail, not just the resumption attempt.
+     * Do not cache (on the server) these sessions that are not resumable
+     * (clients can set SSL_VERIFY_PEER without needing a sid_ctx set).
      */
-    if (s->session->sid_ctx_length == 0
+    if (s->server && s->session->sid_ctx_length == 0
             && (s->verify_mode & SSL_VERIFY_PEER) != 0)
         return;
 
@@ -3519,7 +3529,6 @@ void ssl_free_wbio_buffer(SSL *s)
         return;
 
     s->wbio = BIO_pop(s->wbio);
-    assert(s->wbio != NULL);
     BIO_free(s->bbio);
     s->bbio = NULL;
 }

Index: src/crypto/external/bsd/openssl/dist/ssl/ssl_locl.h
diff -u src/crypto/external/bsd/openssl/dist/ssl/ssl_locl.h:1.17 src/crypto/external/bsd/openssl/dist/ssl/ssl_locl.h:1.18
--- src/crypto/external/bsd/openssl/dist/ssl/ssl_locl.h:1.17	Fri Apr  6 19:04:45 2018
+++ src/crypto/external/bsd/openssl/dist/ssl/ssl_locl.h	Sat Aug 18 04:59:05 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2018 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
@@ -164,6 +164,8 @@
                            (c)[1]=(unsigned char)(((l)>> 8)&0xff), \
                            (c)[2]=(unsigned char)(((l)    )&0xff)),(c)+=3)
 
+# define SSL_MAX_2_BYTE_LEN     (0xffff)
+
 /*
  * DTLS version numbers are strange because they're inverted. Except for
  * DTLS1_BAD_VER, which should be considered "lower" than the rest.
@@ -347,6 +349,9 @@
 
 /* we have used 0000003f - 26 bits left to go */
 
+# define SSL_IS_FIRST_HANDSHAKE(S) ((s)->s3->tmp.finish_md_len == 0 \
+                                    || (s)->s3->tmp.peer_finish_md_len == 0)
+
 /* Check if an SSL structure is using DTLS */
 # define SSL_IS_DTLS(s)  (s->method->ssl3_enc->enc_flags & SSL_ENC_FLAG_DTLS)
 /* See if we need explicit IV */
@@ -537,7 +542,7 @@ struct ssl_session_st {
     const SSL_CIPHER *cipher;
     unsigned long cipher_id;    /* when ASN.1 loaded, this needs to be used to
                                  * load the 'cipher' structure */
-    STACK_OF(SSL_CIPHER) *ciphers; /* shared ciphers? */
+    STACK_OF(SSL_CIPHER) *ciphers; /* ciphers offered by the client */
     CRYPTO_EX_DATA ex_data;     /* application specific data */
     /*
      * These are used to make removal of session-ids more efficient and to

Index: src/crypto/external/bsd/openssl/dist/ssl/ssl_sess.c
diff -u src/crypto/external/bsd/openssl/dist/ssl/ssl_sess.c:1.5 src/crypto/external/bsd/openssl/dist/ssl/ssl_sess.c:1.6
--- src/crypto/external/bsd/openssl/dist/ssl/ssl_sess.c:1.5	Fri Apr  6 19:04:45 2018
+++ src/crypto/external/bsd/openssl/dist/ssl/ssl_sess.c	Sat Aug 18 04:59:05 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2018 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
@@ -734,11 +734,11 @@ static int remove_session_lock(SSL_CTX *
         if (lck)
             CRYPTO_THREAD_unlock(ctx->lock);
 
-        if (ret)
-            SSL_SESSION_free(r);
-
         if (ctx->remove_session_cb != NULL)
             ctx->remove_session_cb(ctx, c);
+
+        if (ret)
+            SSL_SESSION_free(r);
     } else
         ret = 0;
     return (ret);

Index: src/crypto/external/bsd/openssl/dist/ssl/t1_lib.c
diff -u src/crypto/external/bsd/openssl/dist/ssl/t1_lib.c:1.25 src/crypto/external/bsd/openssl/dist/ssl/t1_lib.c:1.26
--- src/crypto/external/bsd/openssl/dist/ssl/t1_lib.c:1.25	Fri Apr  6 19:04:45 2018
+++ src/crypto/external/bsd/openssl/dist/ssl/t1_lib.c	Sat Aug 18 04:59:05 2018
@@ -408,7 +408,7 @@ int tls1_set_curves(unsigned char **pext
     return 1;
 }
 
-# define MAX_CURVELIST   28
+# define MAX_CURVELIST   OSSL_NELEM(nid_list)
 
 typedef struct {
     size_t nidcnt;
@@ -490,13 +490,16 @@ static int tls1_set_ec_id(unsigned char 
     return 1;
 }
 
+# define DONT_CHECK_OWN_GROUPS  0
+# define CHECK_OWN_GROUPS       1
 /* Check an EC key is compatible with extensions */
-static int tls1_check_ec_key(SSL *s,
-                             unsigned char *curve_id, unsigned char *comp_id)
+static int tls1_check_ec_key(SSL *s, unsigned char *curve_id,
+                             unsigned char *comp_id, int check_own_groups)
 {
     const unsigned char *pformats, *pcurves;
     size_t num_formats, num_curves, i;
     int j;
+
     /*
      * If point formats extension present check it, otherwise everything is
      * supported (see RFC4492).
@@ -513,8 +516,12 @@ static int tls1_check_ec_key(SSL *s,
     }
     if (!curve_id)
         return 1;
+
+    if (!s->server && !check_own_groups)
+        return 1;
+
     /* Check curve is consistent with client and server preferences */
-    for (j = 0; j <= 1; j++) {
+    for (j = check_own_groups ? 0 : 1; j <= 1; j++) {
         if (!tls1_get_curvelist(s, j, &pcurves, &num_curves))
             return 0;
         if (j == 1 && num_curves == 0) {
@@ -579,9 +586,12 @@ static int tls1_check_cert_param(SSL *s,
         return 0;
     /*
      * Can't check curve_id for client certs as we don't have a supported
-     * curves extension.
+     * curves extension. For server certs we will tolerate certificates that
+     * aren't in our own list of curves. If we've been configured to use an EC
+     * cert then we should use it - therefore we use DONT_CHECK_OWN_GROUPS here.
      */
-    rv = tls1_check_ec_key(s, s->server ? curve_id : NULL, &comp_id);
+    rv = tls1_check_ec_key(s, s->server ? curve_id : NULL, &comp_id,
+                           DONT_CHECK_OWN_GROUPS);
     if (!rv)
         return 0;
     /*
@@ -644,7 +654,7 @@ int tls1_check_ec_tmp_key(SSL *s, unsign
             return 0;
         curve_id[0] = 0;
         /* Check this curve is acceptable */
-        if (!tls1_check_ec_key(s, curve_id, NULL))
+        if (!tls1_check_ec_key(s, curve_id, NULL, CHECK_OWN_GROUPS))
             return 0;
         return 1;
     }
@@ -746,8 +756,9 @@ size_t tls12_get_psigalgs(SSL *s, int se
 }
 
 /*
- * Check signature algorithm is consistent with sent supported signature
- * algorithms and if so return relevant digest.
+ * Check signature algorithm received from the peer with a signature is
+ * consistent with the sent supported signature algorithms and if so return
+ * relevant digest.
  */
 int tls12_check_peer_sigalg(const EVP_MD **pmd, SSL *s,
                             const unsigned char *sig, EVP_PKEY *pkey)
@@ -769,7 +780,8 @@ int tls12_check_peer_sigalg(const EVP_MD
         /* Check compression and curve matches extensions */
         if (!tls1_set_ec_id(curve_id, &comp_id, EVP_PKEY_get0_EC_KEY(pkey)))
             return 0;
-        if (!s->server && !tls1_check_ec_key(s, curve_id, &comp_id)) {
+        if (!s->server && !tls1_check_ec_key(s, curve_id, &comp_id,
+                                             CHECK_OWN_GROUPS)) {
             SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_CURVE);
             return 0;
         }
@@ -2144,6 +2156,10 @@ static int ssl_scan_clienthello_tlsext(S
                 }
             }
         } else if (type == TLSEXT_TYPE_status_request) {
+            /* Ignore this if resuming */
+            if (s->hit)
+                continue;
+
             if (!PACKET_get_1(&extension,
                               (unsigned int *)&s->tlsext_status_type)) {
                 return 0;
@@ -2784,7 +2800,7 @@ int tls1_set_server_sigalgs(SSL *s)
         if (!s->cert->shared_sigalgs) {
             SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
                    SSL_R_NO_SHARED_SIGNATURE_ALGORITHMS);
-            al = SSL_AD_ILLEGAL_PARAMETER;
+            al = SSL_AD_HANDSHAKE_FAILURE;
             goto err;
         }
     } else {
@@ -4125,13 +4141,16 @@ DH *ssl_get_auto_dh(SSL *s)
         if (dhp == NULL)
             return NULL;
         g = BN_new();
-        if (g != NULL)
-            BN_set_word(g, 2);
+        if (g == NULL || !BN_set_word(g, 2)) {
+            DH_free(dhp);
+            BN_free(g);
+            return NULL;
+        }
         if (dh_secbits >= 192)
             p = BN_get_rfc3526_prime_8192(NULL);
         else
             p = BN_get_rfc3526_prime_3072(NULL);
-        if (p == NULL || g == NULL || !DH_set0_pqg(dhp, p, NULL, g)) {
+        if (p == NULL || !DH_set0_pqg(dhp, p, NULL, g)) {
             DH_free(dhp);
             BN_free(p);
             BN_free(g);
@@ -4172,6 +4191,9 @@ static int ssl_security_cert_sig(SSL *s,
     if ((X509_get_extension_flags(x) & EXFLAG_SS) != 0)
         return 1;
     sig_nid = X509_get_signature_nid(x);
+    /* We are not able to look up the CA MD for RSA PSS in this version */
+    if (sig_nid == NID_rsassaPss)
+        return 1;
     if (sig_nid && OBJ_find_sigid_algs(sig_nid, &md_nid, NULL)) {
         const EVP_MD *md;
         if (md_nid && (md = EVP_get_digestbynid(md_nid)))

Index: src/crypto/external/bsd/openssl/dist/test/evp_test.c
diff -u src/crypto/external/bsd/openssl/dist/test/evp_test.c:1.2 src/crypto/external/bsd/openssl/dist/test/evp_test.c:1.3
--- src/crypto/external/bsd/openssl/dist/test/evp_test.c:1.2	Thu Feb  8 16:51:37 2018
+++ src/crypto/external/bsd/openssl/dist/test/evp_test.c	Sat Aug 18 04:59:05 2018
@@ -1,5 +1,5 @@
 /*
- * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2015-2018 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
@@ -1592,19 +1592,19 @@ static int pderive_test_run(struct evp_t
     struct pkey_data *kdata = t->data;
     unsigned char *out = NULL;
     size_t out_len;
-    const char *err = "INTERNAL_ERROR";
+    const char *err = "DERIVE_ERROR";
 
-    out_len = kdata->output_len;
+    if (EVP_PKEY_derive(kdata->ctx, NULL, &out_len) <= 0)
+        goto err;
     out = OPENSSL_malloc(out_len);
     if (!out) {
         fprintf(stderr, "Error allocating output buffer!\n");
         exit(1);
     }
-    err = "DERIVE_ERROR";
     if (EVP_PKEY_derive(kdata->ctx, out, &out_len) <= 0)
         goto err;
     err = "SHARED_SECRET_LENGTH_MISMATCH";
-    if (out_len != kdata->output_len)
+    if (kdata->output == NULL || out_len != kdata->output_len)
         goto err;
     err = "SHARED_SECRET_MISMATCH";
     if (check_output(t, kdata->output, out, out_len))

Index: src/crypto/external/bsd/openssl/dist/util/mkdef.pl
diff -u src/crypto/external/bsd/openssl/dist/util/mkdef.pl:1.7 src/crypto/external/bsd/openssl/dist/util/mkdef.pl:1.8
--- src/crypto/external/bsd/openssl/dist/util/mkdef.pl:1.7	Fri Apr  6 19:04:46 2018
+++ src/crypto/external/bsd/openssl/dist/util/mkdef.pl	Sat Aug 18 04:59:05 2018
@@ -252,6 +252,7 @@ $crypto.=" include/internal/o_dir.h";
 $crypto.=" include/internal/o_str.h";
 $crypto.=" include/internal/err.h";
 $crypto.=" include/internal/asn1t.h";
+$crypto.=" include/internal/sslconf.h";
 $crypto.=" include/openssl/des.h" ; # unless $no_des;
 $crypto.=" include/openssl/idea.h" ; # unless $no_idea;
 $crypto.=" include/openssl/rc4.h" ; # unless $no_rc4;
@@ -1335,7 +1336,7 @@ EOF
 	} elsif ($VMS) {
             print OUT ")\n";
             (my $libvmaj, my $libvmin, my $libvedit) =
-                $currversion =~ /^(\d+)_(\d+)_(\d+)$/;
+                $currversion =~ /^(\d+)_(\d+)_(\d+)[a-z]{0,2}$/;
             # The reason to multiply the edit number with 100 is to make space
             # for the possibility that we want to encode the patch letters
             print OUT "GSMATCH=LEQUAL,",($libvmaj * 100 + $libvmin),",",($libvedit * 100),"\n";

Reply via email to