Index: vendor-crypto/openssl/dist/CHANGES =================================================================== --- vendor-crypto/openssl/dist/CHANGES (revision 318896) +++ vendor-crypto/openssl/dist/CHANGES (revision 318897) @@ -1,11444 +1,11450 @@ OpenSSL CHANGES _______________ + Changes between 1.0.2k and 1.0.2l [25 May 2017] + + *) Have 'config' recognise 64-bit mingw and choose 'mingw64' as the target + platform rather than 'mingw'. + [Richard Levitte] + Changes between 1.0.2j and 1.0.2k [26 Jan 2017] *) Truncated packet could crash via OOB read If one side of an SSL/TLS path is running on a 32-bit host and a specific cipher is being used, then a truncated packet can cause that host to perform an out-of-bounds read, usually resulting in a crash. This issue was reported to OpenSSL by Robert Święcki of Google. (CVE-2017-3731) [Andy Polyakov] *) BN_mod_exp may produce incorrect results on x86_64 There is a carry propagating bug in the x86_64 Montgomery squaring procedure. No EC algorithms are affected. Analysis suggests that attacks against RSA and DSA as a result of this defect would be very difficult to perform and are not believed likely. Attacks against DH are considered just feasible (although very difficult) because most of the work necessary to deduce information about a private key may be performed offline. The amount of resources required for such an attack would be very significant and likely only accessible to a limited number of attackers. An attacker would additionally need online access to an unpatched system using the target private key in a scenario with persistent DH parameters and a private key that is shared between multiple clients. For example this can occur by default in OpenSSL DHE based SSL/TLS ciphersuites. Note: This issue is very similar to CVE-2015-3193 but must be treated as a separate problem. This issue was reported to OpenSSL by the OSS-Fuzz project. (CVE-2017-3732) [Andy Polyakov] *) Montgomery multiplication may produce incorrect results There is a carry propagating bug in the Broadwell-specific Montgomery multiplication procedure that handles input lengths divisible by, but longer than 256 bits. Analysis suggests that attacks against RSA, DSA and DH private keys are impossible. This is because the subroutine in question is not used in operations with the private key itself and an input of the attacker's direct choice. Otherwise the bug can manifest itself as transient authentication and key negotiation failures or reproducible erroneous outcome of public-key operations with specially crafted input. Among EC algorithms only Brainpool P-512 curves are affected and one presumably can attack ECDH key negotiation. Impact was not analyzed in detail, because pre-requisites for attack are considered unlikely. Namely multiple clients have to choose the curve in question and the server has to share the private key among them, neither of which is default behaviour. Even then only clients that chose the curve will be affected. This issue was publicly reported as transient failures and was not initially recognized as a security issue. Thanks to Richard Morgan for providing reproducible case. (CVE-2016-7055) [Andy Polyakov] *) OpenSSL now fails if it receives an unrecognised record type in TLS1.0 or TLS1.1. Previously this only happened in SSLv3 and TLS1.2. This is to prevent issues where no progress is being made and the peer continually sends unrecognised record types, using up resources processing them. [Matt Caswell] Changes between 1.0.2i and 1.0.2j [26 Sep 2016] *) Missing CRL sanity check A bug fix which included a CRL sanity check was added to OpenSSL 1.1.0 but was omitted from OpenSSL 1.0.2i. As a result any attempt to use CRLs in OpenSSL 1.0.2i will crash with a null pointer exception. This issue only affects the OpenSSL 1.0.2i (CVE-2016-7052) [Matt Caswell] Changes between 1.0.2h and 1.0.2i [22 Sep 2016] *) OCSP Status Request extension unbounded memory growth A malicious client can send an excessively large OCSP Status Request extension. If that client continually requests renegotiation, sending a large OCSP Status Request extension each time, then there will be unbounded memory growth on the server. This will eventually lead to a Denial Of Service attack through memory exhaustion. Servers with a default configuration are vulnerable even if they do not support OCSP. Builds using the "no-ocsp" build time option are not affected. This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.) (CVE-2016-6304) [Matt Caswell] *) In order to mitigate the SWEET32 attack, the DES ciphers were moved from HIGH to MEDIUM. This issue was reported to OpenSSL Karthikeyan Bhargavan and Gaetan Leurent (INRIA) (CVE-2016-2183) [Rich Salz] *) OOB write in MDC2_Update() An overflow can occur in MDC2_Update() either if called directly or through the EVP_DigestUpdate() function using MDC2. If an attacker is able to supply very large amounts of input data after a previous call to EVP_EncryptUpdate() with a partial block then a length check can overflow resulting in a heap corruption. The amount of data needed is comparable to SIZE_MAX which is impractical on most platforms. This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.) (CVE-2016-6303) [Stephen Henson] *) Malformed SHA512 ticket DoS If a server uses SHA512 for TLS session ticket HMAC it is vulnerable to a DoS attack where a malformed ticket will result in an OOB read which will ultimately crash. The use of SHA512 in TLS session tickets is comparatively rare as it requires a custom server callback and ticket lookup mechanism. This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.) (CVE-2016-6302) [Stephen Henson] *) OOB write in BN_bn2dec() The function BN_bn2dec() does not check the return value of BN_div_word(). This can cause an OOB write if an application uses this function with an overly large BIGNUM. This could be a problem if an overly large certificate or CRL is printed out from an untrusted source. TLS is not affected because record limits will reject an oversized certificate before it is parsed. This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.) (CVE-2016-2182) [Stephen Henson] *) OOB read in TS_OBJ_print_bio() The function TS_OBJ_print_bio() misuses OBJ_obj2txt(): the return value is the total length the OID text representation would use and not the amount of data written. This will result in OOB reads when large OIDs are presented. This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.) (CVE-2016-2180) [Stephen Henson] *) Pointer arithmetic undefined behaviour Avoid some undefined pointer arithmetic A common idiom in the codebase is to check limits in the following manner: "p + len > limit" Where "p" points to some malloc'd data of SIZE bytes and limit == p + SIZE "len" here could be from some externally supplied data (e.g. from a TLS message). The rules of C pointer arithmetic are such that "p + len" is only well defined where len <= SIZE. Therefore the above idiom is actually undefined behaviour. For example this could cause problems if some malloc implementation provides an address for "p" such that "p + len" actually overflows for values of len that are too big and therefore p + len < limit. This issue was reported to OpenSSL by Guido Vranken (CVE-2016-2177) [Matt Caswell] *) Constant time flag not preserved in DSA signing Operations in the DSA signing algorithm should run in constant time in order to avoid side channel attacks. A flaw in the OpenSSL DSA implementation means that a non-constant time codepath is followed for certain operations. This has been demonstrated through a cache-timing attack to be sufficient for an attacker to recover the private DSA key. This issue was reported by César Pereida (Aalto University), Billy Brumley (Tampere University of Technology), and Yuval Yarom (The University of Adelaide and NICTA). (CVE-2016-2178) [César Pereida] *) DTLS buffered message DoS In a DTLS connection where handshake messages are delivered out-of-order those messages that OpenSSL is not yet ready to process will be buffered for later use. Under certain circumstances, a flaw in the logic means that those messages do not get removed from the buffer even though the handshake has been completed. An attacker could force up to approx. 15 messages to remain in the buffer when they are no longer required. These messages will be cleared when the DTLS connection is closed. The default maximum size for a message is 100k. Therefore the attacker could force an additional 1500k to be consumed per connection. By opening many simulataneous connections an attacker could cause a DoS attack through memory exhaustion. This issue was reported to OpenSSL by Quan Luo. (CVE-2016-2179) [Matt Caswell] *) DTLS replay protection DoS A flaw in the DTLS replay attack protection mechanism means that records that arrive for future epochs update the replay protection "window" before the MAC for the record has been validated. This could be exploited by an attacker by sending a record for the next epoch (which does not have to decrypt or have a valid MAC), with a very large sequence number. This means that all subsequent legitimate packets are dropped causing a denial of service for a specific DTLS connection. This issue was reported to OpenSSL by the OCAP audit team. (CVE-2016-2181) [Matt Caswell] *) Certificate message OOB reads In OpenSSL 1.0.2 and earlier some missing message length checks can result in OOB reads of up to 2 bytes beyond an allocated buffer. There is a theoretical DoS risk but this has not been observed in practice on common platforms. The messages affected are client certificate, client certificate request and server certificate. As a result the attack can only be performed against a client or a server which enables client authentication. This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.) (CVE-2016-6306) [Stephen Henson] Changes between 1.0.2g and 1.0.2h [3 May 2016] *) Prevent padding oracle in AES-NI CBC MAC check A MITM attacker can use a padding oracle attack to decrypt traffic when the connection uses an AES CBC cipher and the server support AES-NI. This issue was introduced as part of the fix for Lucky 13 padding attack (CVE-2013-0169). The padding check was rewritten to be in constant time by making sure that always the same bytes are read and compared against either the MAC or padding bytes. But it no longer checked that there was enough data to have both the MAC and padding bytes. This issue was reported by Juraj Somorovsky using TLS-Attacker. (CVE-2016-2107) [Kurt Roeckx] *) Fix EVP_EncodeUpdate overflow An overflow can occur in the EVP_EncodeUpdate() function which is used for Base64 encoding of binary data. If an attacker is able to supply very large amounts of input data then a length check can overflow resulting in a heap corruption. Internally to OpenSSL the EVP_EncodeUpdate() function is primarly used by the PEM_write_bio* family of functions. These are mainly used within the OpenSSL command line applications, so any application which processes data from an untrusted source and outputs it as a PEM file should be considered vulnerable to this issue. User applications that call these APIs directly with large amounts of untrusted data may also be vulnerable. This issue was reported by Guido Vranken. (CVE-2016-2105) [Matt Caswell] *) Fix EVP_EncryptUpdate overflow An overflow can occur in the EVP_EncryptUpdate() function. If an attacker is able to supply very large amounts of input data after a previous call to EVP_EncryptUpdate() with a partial block then a length check can overflow resulting in a heap corruption. Following an analysis of all OpenSSL internal usage of the EVP_EncryptUpdate() function all usage is one of two forms. The first form is where the EVP_EncryptUpdate() call is known to be the first called function after an EVP_EncryptInit(), and therefore that specific call must be safe. The second form is where the length passed to EVP_EncryptUpdate() can be seen from the code to be some small value and therefore there is no possibility of an overflow. Since all instances are one of these two forms, it is believed that there can be no overflows in internal code due to this problem. It should be noted that EVP_DecryptUpdate() can call EVP_EncryptUpdate() in certain code paths. Also EVP_CipherUpdate() is a synonym for EVP_EncryptUpdate(). All instances of these calls have also been analysed too and it is believed there are no instances in internal usage where an overflow could occur. This issue was reported by Guido Vranken. (CVE-2016-2106) [Matt Caswell] *) Prevent ASN.1 BIO excessive memory allocation When ASN.1 data is read from a BIO using functions such as d2i_CMS_bio() a short invalid encoding can casuse allocation of large amounts of memory potentially consuming excessive resources or exhausting memory. Any application parsing untrusted data through d2i BIO functions is affected. The memory based functions such as d2i_X509() are *not* affected. Since the memory based functions are used by the TLS library, TLS applications are not affected. This issue was reported by Brian Carpenter. (CVE-2016-2109) [Stephen Henson] *) EBCDIC overread ASN1 Strings that are over 1024 bytes can cause an overread in applications using the X509_NAME_oneline() function on EBCDIC systems. This could result in arbitrary stack data being returned in the buffer. This issue was reported by Guido Vranken. (CVE-2016-2176) [Matt Caswell] *) Modify behavior of ALPN to invoke callback after SNI/servername callback, such that updates to the SSL_CTX affect ALPN. [Todd Short] *) Remove LOW from the DEFAULT cipher list. This removes singles DES from the default. [Kurt Roeckx] *) Only remove the SSLv2 methods with the no-ssl2-method option. When the methods are enabled and ssl2 is disabled the methods return NULL. [Kurt Roeckx] Changes between 1.0.2f and 1.0.2g [1 Mar 2016] * Disable weak ciphers in SSLv3 and up in default builds of OpenSSL. Builds that are not configured with "enable-weak-ssl-ciphers" will not provide any "EXPORT" or "LOW" strength ciphers. [Viktor Dukhovni] * Disable SSLv2 default build, default negotiation and weak ciphers. SSLv2 is by default disabled at build-time. Builds that are not configured with "enable-ssl2" will not support SSLv2. Even if "enable-ssl2" is used, users who want to negotiate SSLv2 via the version-flexible SSLv23_method() will need to explicitly call either of: SSL_CTX_clear_options(ctx, SSL_OP_NO_SSLv2); or SSL_clear_options(ssl, SSL_OP_NO_SSLv2); as appropriate. Even if either of those is used, or the application explicitly uses the version-specific SSLv2_method() or its client and server variants, SSLv2 ciphers vulnerable to exhaustive search key recovery have been removed. Specifically, the SSLv2 40-bit EXPORT ciphers, and SSLv2 56-bit DES are no longer available. (CVE-2016-0800) [Viktor Dukhovni] *) Fix a double-free in DSA code A double free bug was discovered when OpenSSL parses malformed DSA private keys and could lead to a DoS attack or memory corruption for applications that receive DSA private keys from untrusted sources. This scenario is considered rare. This issue was reported to OpenSSL by Adam Langley(Google/BoringSSL) using libFuzzer. (CVE-2016-0705) [Stephen Henson] *) Disable SRP fake user seed to address a server memory leak. Add a new method SRP_VBASE_get1_by_user that handles the seed properly. SRP_VBASE_get_by_user had inconsistent memory management behaviour. In order to fix an unavoidable memory leak, SRP_VBASE_get_by_user was changed to ignore the "fake user" SRP seed, even if the seed is configured. Users should use SRP_VBASE_get1_by_user instead. Note that in SRP_VBASE_get1_by_user, caller must free the returned value. Note also that even though configuring the SRP seed attempts to hide invalid usernames by continuing the handshake with fake credentials, this behaviour is not constant time and no strong guarantees are made that the handshake is indistinguishable from that of a valid user. (CVE-2016-0798) [Emilia Käsper] *) Fix BN_hex2bn/BN_dec2bn NULL pointer deref/heap corruption In the BN_hex2bn function the number of hex digits is calculated using an int value |i|. Later |bn_expand| is called with a value of |i * 4|. For large values of |i| this can result in |bn_expand| not allocating any memory because |i * 4| is negative. This can leave the internal BIGNUM data field as NULL leading to a subsequent NULL ptr deref. For very large values of |i|, the calculation |i * 4| could be a positive value smaller than |i|. In this case memory is allocated to the internal BIGNUM data field, but it is insufficiently sized leading to heap corruption. A similar issue exists in BN_dec2bn. This could have security consequences if BN_hex2bn/BN_dec2bn is ever called by user applications with very large untrusted hex/dec data. This is anticipated to be a rare occurrence. All OpenSSL internal usage of these functions use data that is not expected to be untrusted, e.g. config file data or application command line arguments. If user developed applications generate config file data based on untrusted data then it is possible that this could also lead to security consequences. This is also anticipated to be rare. This issue was reported to OpenSSL by Guido Vranken. (CVE-2016-0797) [Matt Caswell] *) Fix memory issues in BIO_*printf functions The internal |fmtstr| function used in processing a "%s" format string in the BIO_*printf functions could overflow while calculating the length of a string and cause an OOB read when printing very long strings. Additionally the internal |doapr_outch| function can attempt to write to an OOB memory location (at an offset from the NULL pointer) in the event of a memory allocation failure. In 1.0.2 and below this could be caused where the size of a buffer to be allocated is greater than INT_MAX. E.g. this could be in processing a very long "%s" format string. Memory leaks can also occur. The first issue may mask the second issue dependent on compiler behaviour. These problems could enable attacks where large amounts of untrusted data is passed to the BIO_*printf functions. If applications use these functions in this way then they could be vulnerable. OpenSSL itself uses these functions when printing out human-readable dumps of ASN.1 data. Therefore applications that print this data could be vulnerable if the data is from untrusted sources. OpenSSL command line applications could also be vulnerable where they print out ASN.1 data, or if untrusted data is passed as command line arguments. Libssl is not considered directly vulnerable. Additionally certificates etc received via remote connections via libssl are also unlikely to be able to trigger these issues because of message size limits enforced within libssl. This issue was reported to OpenSSL Guido Vranken. (CVE-2016-0799) [Matt Caswell] *) Side channel attack on modular exponentiation A side-channel attack was found which makes use of cache-bank conflicts on the Intel Sandy-Bridge microarchitecture which could lead to the recovery of RSA keys. The ability to exploit this issue is limited as it relies on an attacker who has control of code in a thread running on the same hyper-threaded core as the victim thread which is performing decryptions. This issue was reported to OpenSSL by Yuval Yarom, The University of Adelaide and NICTA, Daniel Genkin, Technion and Tel Aviv University, and Nadia Heninger, University of Pennsylvania with more information at http://cachebleed.info. (CVE-2016-0702) [Andy Polyakov] *) Change the req app to generate a 2048-bit RSA/DSA key by default, if no keysize is specified with default_bits. This fixes an omission in an earlier change that changed all RSA/DSA key generation apps to use 2048 bits by default. [Emilia Käsper] Changes between 1.0.2e and 1.0.2f [28 Jan 2016] *) DH small subgroups Historically OpenSSL only ever generated DH parameters based on "safe" primes. More recently (in version 1.0.2) support was provided for generating X9.42 style parameter files such as those required for RFC 5114 support. The primes used in such files may not be "safe". Where an application is using DH configured with parameters based on primes that are not "safe" then an attacker could use this fact to find a peer's private DH exponent. This attack requires that the attacker complete multiple handshakes in which the peer uses the same private DH exponent. For example this could be used to discover a TLS server's private DH exponent if it's reusing the private DH exponent or it's using a static DH ciphersuite. OpenSSL provides the option SSL_OP_SINGLE_DH_USE for ephemeral DH (DHE) in TLS. It is not on by default. If the option is not set then the server reuses the same private DH exponent for the life of the server process and would be vulnerable to this attack. It is believed that many popular applications do set this option and would therefore not be at risk. The fix for this issue adds an additional check where a "q" parameter is available (as is the case in X9.42 based parameters). This detects the only known attack, and is the only possible defense for static DH ciphersuites. This could have some performance impact. Additionally the SSL_OP_SINGLE_DH_USE option has been switched on by default and cannot be disabled. This could have some performance impact. This issue was reported to OpenSSL by Antonio Sanso (Adobe). (CVE-2016-0701) [Matt Caswell] *) SSLv2 doesn't block disabled ciphers A malicious client can negotiate SSLv2 ciphers that have been disabled on the server and complete SSLv2 handshakes even if all SSLv2 ciphers have been disabled, provided that the SSLv2 protocol was not also disabled via SSL_OP_NO_SSLv2. This issue was reported to OpenSSL on 26th December 2015 by Nimrod Aviram and Sebastian Schinzel. (CVE-2015-3197) [Viktor Dukhovni] *) Reject DH handshakes with parameters shorter than 1024 bits. [Kurt Roeckx] Changes between 1.0.2d and 1.0.2e [3 Dec 2015] *) BN_mod_exp may produce incorrect results on x86_64 There is a carry propagating bug in the x86_64 Montgomery squaring procedure. No EC algorithms are affected. Analysis suggests that attacks against RSA and DSA as a result of this defect would be very difficult to perform and are not believed likely. Attacks against DH are considered just feasible (although very difficult) because most of the work necessary to deduce information about a private key may be performed offline. The amount of resources required for such an attack would be very significant and likely only accessible to a limited number of attackers. An attacker would additionally need online access to an unpatched system using the target private key in a scenario with persistent DH parameters and a private key that is shared between multiple clients. For example this can occur by default in OpenSSL DHE based SSL/TLS ciphersuites. This issue was reported to OpenSSL by Hanno Böck. (CVE-2015-3193) [Andy Polyakov] *) Certificate verify crash with missing PSS parameter The signature verification routines will crash with a NULL pointer dereference if presented with an ASN.1 signature using the RSA PSS algorithm and absent mask generation function parameter. Since these routines are used to verify certificate signature algorithms this can be used to crash any certificate verification operation and exploited in a DoS attack. Any application which performs certificate verification is vulnerable including OpenSSL clients and servers which enable client authentication. This issue was reported to OpenSSL by Loïc Jonas Etienne (Qnective AG). (CVE-2015-3194) [Stephen Henson] *) X509_ATTRIBUTE memory leak When presented with a malformed X509_ATTRIBUTE structure OpenSSL will leak memory. This structure is used by the PKCS#7 and CMS routines so any application which reads PKCS#7 or CMS data from untrusted sources is affected. SSL/TLS is not affected. This issue was reported to OpenSSL by Adam Langley (Google/BoringSSL) using libFuzzer. (CVE-2015-3195) [Stephen Henson] *) Rewrite EVP_DecodeUpdate (base64 decoding) to fix several bugs. This changes the decoding behaviour for some invalid messages, though the change is mostly in the more lenient direction, and legacy behaviour is preserved as much as possible. [Emilia Käsper] *) In DSA_generate_parameters_ex, if the provided seed is too short, use a random seed, as already documented. [Rich Salz and Ismo Puustinen ] Changes between 1.0.2c and 1.0.2d [9 Jul 2015] *) Alternate chains certificate forgery During certificate verfification, OpenSSL will attempt to find an alternative certificate chain if the first attempt to build such a chain fails. An error in the implementation of this logic can mean that an attacker could cause certain checks on untrusted certificates to be bypassed, such as the CA flag, enabling them to use a valid leaf certificate to act as a CA and "issue" an invalid certificate. This issue was reported to OpenSSL by Adam Langley/David Benjamin (Google/BoringSSL). (CVE-2015-1793) [Matt Caswell] *) Race condition handling PSK identify hint If PSK identity hints are received by a multi-threaded client then the values are wrongly updated in the parent SSL_CTX structure. This can result in a race condition potentially leading to a double free of the identify hint data. (CVE-2015-3196) [Stephen Henson] Changes between 1.0.2b and 1.0.2c [12 Jun 2015] *) Fix HMAC ABI incompatibility. The previous version introduced an ABI incompatibility in the handling of HMAC. The previous ABI has now been restored. Changes between 1.0.2a and 1.0.2b [11 Jun 2015] *) Malformed ECParameters causes infinite loop When processing an ECParameters structure OpenSSL enters an infinite loop if the curve specified is over a specially malformed binary polynomial field. This can be used to perform denial of service against any system which processes public keys, certificate requests or certificates. This includes TLS clients and TLS servers with client authentication enabled. This issue was reported to OpenSSL by Joseph Barr-Pixton. (CVE-2015-1788) [Andy Polyakov] *) Exploitable out-of-bounds read in X509_cmp_time X509_cmp_time does not properly check the length of the ASN1_TIME string and can read a few bytes out of bounds. In addition, X509_cmp_time accepts an arbitrary number of fractional seconds in the time string. An attacker can use this to craft malformed certificates and CRLs of various sizes and potentially cause a segmentation fault, resulting in a DoS on applications that verify certificates or CRLs. TLS clients that verify CRLs are affected. TLS clients and servers with client authentication enabled may be affected if they use custom verification callbacks. This issue was reported to OpenSSL by Robert Swiecki (Google), and independently by Hanno Böck. (CVE-2015-1789) [Emilia Käsper] *) PKCS7 crash with missing EnvelopedContent The PKCS#7 parsing code does not handle missing inner EncryptedContent correctly. An attacker can craft malformed ASN.1-encoded PKCS#7 blobs with missing content and trigger a NULL pointer dereference on parsing. Applications that decrypt PKCS#7 data or otherwise parse PKCS#7 structures from untrusted sources are affected. OpenSSL clients and servers are not affected. This issue was reported to OpenSSL by Michal Zalewski (Google). (CVE-2015-1790) [Emilia Käsper] *) CMS verify infinite loop with unknown hash function When verifying a signedData message the CMS code can enter an infinite loop if presented with an unknown hash function OID. This can be used to perform denial of service against any system which verifies signedData messages using the CMS code. This issue was reported to OpenSSL by Johannes Bauer. (CVE-2015-1792) [Stephen Henson] *) Race condition handling NewSessionTicket If a NewSessionTicket is received by a multi-threaded client when attempting to reuse a previous ticket then a race condition can occur potentially leading to a double free of the ticket data. (CVE-2015-1791) [Matt Caswell] *) Removed support for the two export grade static DH ciphersuites EXP-DH-RSA-DES-CBC-SHA and EXP-DH-DSS-DES-CBC-SHA. These two ciphersuites were newly added (along with a number of other static DH ciphersuites) to 1.0.2. However the two export ones have *never* worked since they were introduced. It seems strange in any case to be adding new export ciphersuites, and given "logjam" it also does not seem correct to fix them. [Matt Caswell] *) Only support 256-bit or stronger elliptic curves with the 'ecdh_auto' setting (server) or by default (client). Of supported curves, prefer P-256 (both). [Emilia Kasper] *) Reject DH handshakes with parameters shorter than 768 bits. [Kurt Roeckx and Emilia Kasper] Changes between 1.0.2 and 1.0.2a [19 Mar 2015] *) ClientHello sigalgs DoS fix If a client connects to an OpenSSL 1.0.2 server and renegotiates with an invalid signature algorithms extension a NULL pointer dereference will occur. This can be exploited in a DoS attack against the server. This issue was was reported to OpenSSL by David Ramos of Stanford University. (CVE-2015-0291) [Stephen Henson and Matt Caswell] *) Multiblock corrupted pointer fix OpenSSL 1.0.2 introduced the "multiblock" performance improvement. This feature only applies on 64 bit x86 architecture platforms that support AES NI instructions. A defect in the implementation of "multiblock" can cause OpenSSL's internal write buffer to become incorrectly set to NULL when using non-blocking IO. Typically, when the user application is using a socket BIO for writing, this will only result in a failed connection. However if some other BIO is used then it is likely that a segmentation fault will be triggered, thus enabling a potential DoS attack. This issue was reported to OpenSSL by Daniel Danner and Rainer Mueller. (CVE-2015-0290) [Matt Caswell] *) Segmentation fault in DTLSv1_listen fix The DTLSv1_listen function is intended to be stateless and processes the initial ClientHello from many peers. It is common for user code to loop over the call to DTLSv1_listen until a valid ClientHello is received with an associated cookie. A defect in the implementation of DTLSv1_listen means that state is preserved in the SSL object from one invocation to the next that can lead to a segmentation fault. Errors processing the initial ClientHello can trigger this scenario. An example of such an error could be that a DTLS1.0 only client is attempting to connect to a DTLS1.2 only server. This issue was reported to OpenSSL by Per Allansson. (CVE-2015-0207) [Matt Caswell] *) Segmentation fault in ASN1_TYPE_cmp fix The function ASN1_TYPE_cmp will crash with an invalid read if an attempt is made to compare ASN.1 boolean types. Since ASN1_TYPE_cmp is used to check certificate signature algorithm consistency this can be used to crash any certificate verification operation and exploited in a DoS attack. Any application which performs certificate verification is vulnerable including OpenSSL clients and servers which enable client authentication. (CVE-2015-0286) [Stephen Henson] *) Segmentation fault for invalid PSS parameters fix The signature verification routines will crash with a NULL pointer dereference if presented with an ASN.1 signature using the RSA PSS algorithm and invalid parameters. Since these routines are used to verify certificate signature algorithms this can be used to crash any certificate verification operation and exploited in a DoS attack. Any application which performs certificate verification is vulnerable including OpenSSL clients and servers which enable client authentication. This issue was was reported to OpenSSL by Brian Carpenter. (CVE-2015-0208) [Stephen Henson] *) ASN.1 structure reuse memory corruption fix Reusing a structure in ASN.1 parsing may allow an attacker to cause memory corruption via an invalid write. Such reuse is and has been strongly discouraged and is believed to be rare. Applications that parse structures containing CHOICE or ANY DEFINED BY components may be affected. Certificate parsing (d2i_X509 and related functions) are however not affected. OpenSSL clients and servers are not affected. (CVE-2015-0287) [Stephen Henson] *) PKCS7 NULL pointer dereferences fix The PKCS#7 parsing code does not handle missing outer ContentInfo correctly. An attacker can craft malformed ASN.1-encoded PKCS#7 blobs with missing content and trigger a NULL pointer dereference on parsing. Applications that verify PKCS#7 signatures, decrypt PKCS#7 data or otherwise parse PKCS#7 structures from untrusted sources are affected. OpenSSL clients and servers are not affected. This issue was reported to OpenSSL by Michal Zalewski (Google). (CVE-2015-0289) [Emilia Käsper] *) DoS via reachable assert in SSLv2 servers fix A malicious client can trigger an OPENSSL_assert (i.e., an abort) in servers that both support SSLv2 and enable export cipher suites by sending a specially crafted SSLv2 CLIENT-MASTER-KEY message. This issue was discovered by Sean Burford (Google) and Emilia Käsper (OpenSSL development team). (CVE-2015-0293) [Emilia Käsper] *) Empty CKE with client auth and DHE fix If client auth is used then a server can seg fault in the event of a DHE ciphersuite being selected and a zero length ClientKeyExchange message being sent by the client. This could be exploited in a DoS attack. (CVE-2015-1787) [Matt Caswell] *) Handshake with unseeded PRNG fix Under certain conditions an OpenSSL 1.0.2 client can complete a handshake with an unseeded PRNG. The conditions are: - The client is on a platform where the PRNG has not been seeded automatically, and the user has not seeded manually - A protocol specific client method version has been used (i.e. not SSL_client_methodv23) - A ciphersuite is used that does not require additional random data from the PRNG beyond the initial ClientHello client random (e.g. PSK-RC4-SHA). If the handshake succeeds then the client random that has been used will have been generated from a PRNG with insufficient entropy and therefore the output may be predictable. For example using the following command with an unseeded openssl will succeed on an unpatched platform: openssl s_client -psk 1a2b3c4d -tls1_2 -cipher PSK-RC4-SHA (CVE-2015-0285) [Matt Caswell] *) Use After Free following d2i_ECPrivatekey error fix A malformed EC private key file consumed via the d2i_ECPrivateKey function could cause a use after free condition. This, in turn, could cause a double free in several private key parsing functions (such as d2i_PrivateKey or EVP_PKCS82PKEY) and could lead to a DoS attack or memory corruption for applications that receive EC private keys from untrusted sources. This scenario is considered rare. This issue was discovered by the BoringSSL project and fixed in their commit 517073cd4b. (CVE-2015-0209) [Matt Caswell] *) X509_to_X509_REQ NULL pointer deref fix The function X509_to_X509_REQ will crash with a NULL pointer dereference if the certificate key is invalid. This function is rarely used in practice. This issue was discovered by Brian Carpenter. (CVE-2015-0288) [Stephen Henson] *) Removed the export ciphers from the DEFAULT ciphers [Kurt Roeckx] Changes between 1.0.1l and 1.0.2 [22 Jan 2015] *) Change RSA and DH/DSA key generation apps to generate 2048-bit keys by default. [Kurt Roeckx] *) Facilitate "universal" ARM builds targeting range of ARM ISAs, e.g. ARMv5 through ARMv8, as opposite to "locking" it to single one. So far those who have to target multiple plaforms would compromise and argue that binary targeting say ARMv5 would still execute on ARMv8. "Universal" build resolves this compromise by providing near-optimal performance even on newer platforms. [Andy Polyakov] *) Accelerated NIST P-256 elliptic curve implementation for x86_64 (other platforms pending). [Shay Gueron & Vlad Krasnov (Intel Corp), Andy Polyakov] *) Add support for the SignedCertificateTimestampList certificate and OCSP response extensions from RFC6962. [Rob Stradling] *) Fix ec_GFp_simple_points_make_affine (thus, EC_POINTs_mul etc.) for corner cases. (Certain input points at infinity could lead to bogus results, with non-infinity inputs mapped to infinity too.) [Bodo Moeller] *) Initial support for PowerISA 2.0.7, first implemented in POWER8. This covers AES, SHA256/512 and GHASH. "Initial" means that most common cases are optimized and there still is room for further improvements. Vector Permutation AES for Altivec is also added. [Andy Polyakov] *) Add support for little-endian ppc64 Linux target. [Marcelo Cerri (IBM)] *) Initial support for AMRv8 ISA crypto extensions. This covers AES, SHA1, SHA256 and GHASH. "Initial" means that most common cases are optimized and there still is room for further improvements. Both 32- and 64-bit modes are supported. [Andy Polyakov, Ard Biesheuvel (Linaro)] *) Improved ARMv7 NEON support. [Andy Polyakov] *) Support for SPARC Architecture 2011 crypto extensions, first implemented in SPARC T4. This covers AES, DES, Camellia, SHA1, SHA256/512, MD5, GHASH and modular exponentiation. [Andy Polyakov, David Miller] *) Accelerated modular exponentiation for Intel processors, a.k.a. RSAZ. [Shay Gueron & Vlad Krasnov (Intel Corp)] *) Support for new and upcoming Intel processors, including AVX2, BMI and SHA ISA extensions. This includes additional "stitched" implementations, AESNI-SHA256 and GCM, and multi-buffer support for TLS encrypt. This work was sponsored by Intel Corp. [Andy Polyakov] *) Support for DTLS 1.2. This adds two sets of DTLS methods: DTLS_*_method() supports both DTLS 1.2 and 1.0 and should use whatever version the peer supports and DTLSv1_2_*_method() which supports DTLS 1.2 only. [Steve Henson] *) Use algorithm specific chains in SSL_CTX_use_certificate_chain_file(): this fixes a limiation in previous versions of OpenSSL. [Steve Henson] *) Extended RSA OAEP support via EVP_PKEY API. Options to specify digest, MGF1 digest and OAEP label. [Steve Henson] *) Add EVP support for key wrapping algorithms, to avoid problems with existing code the flag EVP_CIPHER_CTX_WRAP_ALLOW has to be set in the EVP_CIPHER_CTX or an error is returned. Add AES and DES3 wrap algorithms and include tests cases. [Steve Henson] *) Add functions to allocate and set the fields of an ECDSA_METHOD structure. [Douglas E. Engert, Steve Henson] *) New functions OPENSSL_gmtime_diff and ASN1_TIME_diff to find the difference in days and seconds between two tm or ASN1_TIME structures. [Steve Henson] *) Add -rev test option to s_server to just reverse order of characters received by client and send back to server. Also prints an abbreviated summary of the connection parameters. [Steve Henson] *) New option -brief for s_client and s_server to print out a brief summary of connection parameters. [Steve Henson] *) Add callbacks for arbitrary TLS extensions. [Trevor Perrin and Ben Laurie] *) New option -crl_download in several openssl utilities to download CRLs from CRLDP extension in certificates. [Steve Henson] *) New options -CRL and -CRLform for s_client and s_server for CRLs. [Steve Henson] *) New function X509_CRL_diff to generate a delta CRL from the difference of two full CRLs. Add support to "crl" utility. [Steve Henson] *) New functions to set lookup_crls function and to retrieve X509_STORE from X509_STORE_CTX. [Steve Henson] *) Print out deprecated issuer and subject unique ID fields in certificates. [Steve Henson] *) Extend OCSP I/O functions so they can be used for simple general purpose HTTP as well as OCSP. New wrapper function which can be used to download CRLs using the OCSP API. [Steve Henson] *) Delegate command line handling in s_client/s_server to SSL_CONF APIs. [Steve Henson] *) SSL_CONF* functions. These provide a common framework for application configuration using configuration files or command lines. [Steve Henson] *) SSL/TLS tracing code. This parses out SSL/TLS records using the message callback and prints the results. Needs compile time option "enable-ssl-trace". New options to s_client and s_server to enable tracing. [Steve Henson] *) New ctrl and macro to retrieve supported points extensions. Print out extension in s_server and s_client. [Steve Henson] *) New functions to retrieve certificate signature and signature OID NID. [Steve Henson] *) Add functions to retrieve and manipulate the raw cipherlist sent by a client to OpenSSL. [Steve Henson] *) New Suite B modes for TLS code. These use and enforce the requirements of RFC6460: restrict ciphersuites, only permit Suite B algorithms and only use Suite B curves. The Suite B modes can be set by using the strings "SUITEB128", "SUITEB192" or "SUITEB128ONLY" for the cipherstring. [Steve Henson] *) New chain verification flags for Suite B levels of security. Check algorithms are acceptable when flags are set in X509_verify_cert. [Steve Henson] *) Make tls1_check_chain return a set of flags indicating checks passed by a certificate chain. Add additional tests to handle client certificates: checks for matching certificate type and issuer name comparison. [Steve Henson] *) If an attempt is made to use a signature algorithm not in the peer preference list abort the handshake. If client has no suitable signature algorithms in response to a certificate request do not use the certificate. [Steve Henson] *) If server EC tmp key is not in client preference list abort handshake. [Steve Henson] *) Add support for certificate stores in CERT structure. This makes it possible to have different stores per SSL structure or one store in the parent SSL_CTX. Include distint stores for certificate chain verification and chain building. New ctrl SSL_CTRL_BUILD_CERT_CHAIN to build and store a certificate chain in CERT structure: returing an error if the chain cannot be built: this will allow applications to test if a chain is correctly configured. Note: if the CERT based stores are not set then the parent SSL_CTX store is used to retain compatibility with existing behaviour. [Steve Henson] *) New function ssl_set_client_disabled to set a ciphersuite disabled mask based on the current session, check mask when sending client hello and checking the requested ciphersuite. [Steve Henson] *) New ctrls to retrieve and set certificate types in a certificate request message. Print out received values in s_client. If certificate types is not set with custom values set sensible values based on supported signature algorithms. [Steve Henson] *) Support for distinct client and server supported signature algorithms. [Steve Henson] *) Add certificate callback. If set this is called whenever a certificate is required by client or server. An application can decide which certificate chain to present based on arbitrary criteria: for example supported signature algorithms. Add very simple example to s_server. This fixes many of the problems and restrictions of the existing client certificate callback: for example you can now clear an existing certificate and specify the whole chain. [Steve Henson] *) Add new "valid_flags" field to CERT_PKEY structure which determines what the certificate can be used for (if anything). Set valid_flags field in new tls1_check_chain function. Simplify ssl_set_cert_masks which used to have similar checks in it. Add new "cert_flags" field to CERT structure and include a "strict mode". This enforces some TLS certificate requirements (such as only permitting certificate signature algorithms contained in the supported algorithms extension) which some implementations ignore: this option should be used with caution as it could cause interoperability issues. [Steve Henson] *) Update and tidy signature algorithm extension processing. Work out shared signature algorithms based on preferences and peer algorithms and print them out in s_client and s_server. Abort handshake if no shared signature algorithms. [Steve Henson] *) Add new functions to allow customised supported signature algorithms for SSL and SSL_CTX structures. Add options to s_client and s_server to support them. [Steve Henson] *) New function SSL_certs_clear() to delete all references to certificates from an SSL structure. Before this once a certificate had been added it couldn't be removed. [Steve Henson] *) Integrate hostname, email address and IP address checking with certificate verification. New verify options supporting checking in opensl utility. [Steve Henson] *) Fixes and wildcard matching support to hostname and email checking functions. Add manual page. [Florian Weimer (Red Hat Product Security Team)] *) New functions to check a hostname email or IP address against a certificate. Add options x509 utility to print results of checks against a certificate. [Steve Henson] *) Fix OCSP checking. [Rob Stradling and Ben Laurie] *) Initial experimental support for explicitly trusted non-root CAs. OpenSSL still tries to build a complete chain to a root but if an intermediate CA has a trust setting included that is used. The first setting is used: whether to trust (e.g., -addtrust option to the x509 utility) or reject. [Steve Henson] *) Add -trusted_first option which attempts to find certificates in the trusted store even if an untrusted chain is also supplied. [Steve Henson] *) MIPS assembly pack updates: support for MIPS32r2 and SmartMIPS ASE, platform support for Linux and Android. [Andy Polyakov] *) Support for linux-x32, ILP32 environment in x86_64 framework. [Andy Polyakov] *) Experimental multi-implementation support for FIPS capable OpenSSL. When in FIPS mode the approved implementations are used as normal, when not in FIPS mode the internal unapproved versions are used instead. This means that the FIPS capable OpenSSL isn't forced to use the (often lower perfomance) FIPS implementations outside FIPS mode. [Steve Henson] *) Transparently support X9.42 DH parameters when calling PEM_read_bio_DHparameters. This means existing applications can handle the new parameter format automatically. [Steve Henson] *) Initial experimental support for X9.42 DH parameter format: mainly to support use of 'q' parameter for RFC5114 parameters. [Steve Henson] *) Add DH parameters from RFC5114 including test data to dhtest. [Steve Henson] *) Support for automatic EC temporary key parameter selection. If enabled the most preferred EC parameters are automatically used instead of hardcoded fixed parameters. Now a server just has to call: SSL_CTX_set_ecdh_auto(ctx, 1) and the server will automatically support ECDH and use the most appropriate parameters. [Steve Henson] *) Enhance and tidy EC curve and point format TLS extension code. Use static structures instead of allocation if default values are used. New ctrls to set curves we wish to support and to retrieve shared curves. Print out shared curves in s_server. New options to s_server and s_client to set list of supported curves. [Steve Henson] *) New ctrls to retrieve supported signature algorithms and supported curve values as an array of NIDs. Extend openssl utility to print out received values. [Steve Henson] *) Add new APIs EC_curve_nist2nid and EC_curve_nid2nist which convert between NIDs and the more common NIST names such as "P-256". Enhance ecparam utility and ECC method to recognise the NIST names for curves. [Steve Henson] *) Enhance SSL/TLS certificate chain handling to support different chains for each certificate instead of one chain in the parent SSL_CTX. [Steve Henson] *) Support for fixed DH ciphersuite client authentication: where both server and client use DH certificates with common parameters. [Steve Henson] *) Support for fixed DH ciphersuites: those requiring DH server certificates. [Steve Henson] *) New function i2d_re_X509_tbs for re-encoding the TBS portion of the certificate. Note: Related 1.0.2-beta specific macros X509_get_cert_info, X509_CINF_set_modified, X509_CINF_get_issuer, X509_CINF_get_extensions and X509_CINF_get_signature were reverted post internal team review. Changes between 1.0.1k and 1.0.1l [15 Jan 2015] *) Build fixes for the Windows and OpenVMS platforms [Matt Caswell and Richard Levitte] Changes between 1.0.1j and 1.0.1k [8 Jan 2015] *) Fix DTLS segmentation fault in dtls1_get_record. A carefully crafted DTLS message can cause a segmentation fault in OpenSSL due to a NULL pointer dereference. This could lead to a Denial Of Service attack. Thanks to Markus Stenberg of Cisco Systems, Inc. for reporting this issue. (CVE-2014-3571) [Steve Henson] *) Fix DTLS memory leak in dtls1_buffer_record. A memory leak can occur in the dtls1_buffer_record function under certain conditions. In particular this could occur if an attacker sent repeated DTLS records with the same sequence number but for the next epoch. The memory leak could be exploited by an attacker in a Denial of Service attack through memory exhaustion. Thanks to Chris Mueller for reporting this issue. (CVE-2015-0206) [Matt Caswell] *) Fix issue where no-ssl3 configuration sets method to NULL. When openssl is built with the no-ssl3 option and a SSL v3 ClientHello is received the ssl method would be set to NULL which could later result in a NULL pointer dereference. Thanks to Frank Schmirler for reporting this issue. (CVE-2014-3569) [Kurt Roeckx] *) Abort handshake if server key exchange message is omitted for ephemeral ECDH ciphersuites. Thanks to Karthikeyan Bhargavan of the PROSECCO team at INRIA for reporting this issue. (CVE-2014-3572) [Steve Henson] *) Remove non-export ephemeral RSA code on client and server. This code violated the TLS standard by allowing the use of temporary RSA keys in non-export ciphersuites and could be used by a server to effectively downgrade the RSA key length used to a value smaller than the server certificate. Thanks for Karthikeyan Bhargavan of the PROSECCO team at INRIA or reporting this issue. (CVE-2015-0204) [Steve Henson] *) Fixed issue where DH client certificates are accepted without verification. An OpenSSL server will accept a DH certificate for client authentication without the certificate verify message. This effectively allows a client to authenticate without the use of a private key. This only affects servers which trust a client certificate authority which issues certificates containing DH keys: these are extremely rare and hardly ever encountered. Thanks for Karthikeyan Bhargavan of the PROSECCO team at INRIA or reporting this issue. (CVE-2015-0205) [Steve Henson] *) Ensure that the session ID context of an SSL is updated when its SSL_CTX is updated via SSL_set_SSL_CTX. The session ID context is typically set from the parent SSL_CTX, and can vary with the CTX. [Adam Langley] *) Fix various certificate fingerprint issues. By using non-DER or invalid encodings outside the signed portion of a certificate the fingerprint can be changed without breaking the signature. Although no details of the signed portion of the certificate can be changed this can cause problems with some applications: e.g. those using the certificate fingerprint for blacklists. 1. Reject signatures with non zero unused bits. If the BIT STRING containing the signature has non zero unused bits reject the signature. All current signature algorithms require zero unused bits. 2. Check certificate algorithm consistency. Check the AlgorithmIdentifier inside TBS matches the one in the certificate signature. NB: this will result in signature failure errors for some broken certificates. Thanks to Konrad Kraszewski from Google for reporting this issue. 3. Check DSA/ECDSA signatures use DER. Reencode DSA/ECDSA signatures and compare with the original received signature. Return an error if there is a mismatch. This will reject various cases including garbage after signature (thanks to Antti Karjalainen and Tuomo Untinen from the Codenomicon CROSS program for discovering this case) and use of BER or invalid ASN.1 INTEGERs (negative or with leading zeroes). Further analysis was conducted and fixes were developed by Stephen Henson of the OpenSSL core team. (CVE-2014-8275) [Steve Henson] *) Correct Bignum squaring. Bignum squaring (BN_sqr) may produce incorrect results on some platforms, including x86_64. This bug occurs at random with a very low probability, and is not known to be exploitable in any way, though its exact impact is difficult to determine. Thanks to Pieter Wuille (Blockstream) who reported this issue and also suggested an initial fix. Further analysis was conducted by the OpenSSL development team and Adam Langley of Google. The final fix was developed by Andy Polyakov of the OpenSSL core team. (CVE-2014-3570) [Andy Polyakov] *) Do not resume sessions on the server if the negotiated protocol version does not match the session's version. Resuming with a different version, while not strictly forbidden by the RFC, is of questionable sanity and breaks all known clients. [David Benjamin, Emilia Käsper] *) Tighten handling of the ChangeCipherSpec (CCS) message: reject early CCS messages during renegotiation. (Note that because renegotiation is encrypted, this early CCS was not exploitable.) [Emilia Käsper] *) Tighten client-side session ticket handling during renegotiation: ensure that the client only accepts a session ticket if the server sends the extension anew in the ServerHello. Previously, a TLS client would reuse the old extension state and thus accept a session ticket if one was announced in the initial ServerHello. Similarly, ensure that the client requires a session ticket if one was advertised in the ServerHello. Previously, a TLS client would ignore a missing NewSessionTicket message. [Emilia Käsper] Changes between 1.0.1i and 1.0.1j [15 Oct 2014] *) SRTP Memory Leak. A flaw in the DTLS SRTP extension parsing code allows an attacker, who sends a carefully crafted handshake message, to cause OpenSSL to fail to free up to 64k of memory causing a memory leak. This could be exploited in a Denial Of Service attack. This issue affects OpenSSL 1.0.1 server implementations for both SSL/TLS and DTLS regardless of whether SRTP is used or configured. Implementations of OpenSSL that have been compiled with OPENSSL_NO_SRTP defined are not affected. The fix was developed by the OpenSSL team. (CVE-2014-3513) [OpenSSL team] *) Session Ticket Memory Leak. When an OpenSSL SSL/TLS/DTLS server receives a session ticket the integrity of that ticket is first verified. In the event of a session ticket integrity check failing, OpenSSL will fail to free memory causing a memory leak. By sending a large number of invalid session tickets an attacker could exploit this issue in a Denial Of Service attack. (CVE-2014-3567) [Steve Henson] *) Build option no-ssl3 is incomplete. When OpenSSL is configured with "no-ssl3" as a build option, servers could accept and complete a SSL 3.0 handshake, and clients could be configured to send them. (CVE-2014-3568) [Akamai and the OpenSSL team] *) Add support for TLS_FALLBACK_SCSV. Client applications doing fallback retries should call SSL_set_mode(s, SSL_MODE_SEND_FALLBACK_SCSV). (CVE-2014-3566) [Adam Langley, Bodo Moeller] *) Add additional DigestInfo checks. Reencode DigestInto in DER and check against the original when verifying RSA signature: this will reject any improperly encoded DigestInfo structures. Note: this is a precautionary measure and no attacks are currently known. [Steve Henson] Changes between 1.0.1h and 1.0.1i [6 Aug 2014] *) Fix SRP buffer overrun vulnerability. Invalid parameters passed to the SRP code can be overrun an internal buffer. Add sanity check that g, A, B < N to SRP code. Thanks to Sean Devlin and Watson Ladd of Cryptography Services, NCC Group for discovering this issue. (CVE-2014-3512) [Steve Henson] *) A flaw in the OpenSSL SSL/TLS server code causes the server to negotiate TLS 1.0 instead of higher protocol versions when the ClientHello message is badly fragmented. This allows a man-in-the-middle attacker to force a downgrade to TLS 1.0 even if both the server and the client support a higher protocol version, by modifying the client's TLS records. Thanks to David Benjamin and Adam Langley (Google) for discovering and researching this issue. (CVE-2014-3511) [David Benjamin] *) OpenSSL DTLS clients enabling anonymous (EC)DH ciphersuites are subject to a denial of service attack. A malicious server can crash the client with a null pointer dereference (read) by specifying an anonymous (EC)DH ciphersuite and sending carefully crafted handshake messages. Thanks to Felix Gröbert (Google) for discovering and researching this issue. (CVE-2014-3510) [Emilia Käsper] *) By sending carefully crafted DTLS packets an attacker could cause openssl to leak memory. This can be exploited through a Denial of Service attack. Thanks to Adam Langley for discovering and researching this issue. (CVE-2014-3507) [Adam Langley] *) An attacker can force openssl to consume large amounts of memory whilst processing DTLS handshake messages. This can be exploited through a Denial of Service attack. Thanks to Adam Langley for discovering and researching this issue. (CVE-2014-3506) [Adam Langley] *) An attacker can force an error condition which causes openssl to crash whilst processing DTLS packets due to memory being freed twice. This can be exploited through a Denial of Service attack. Thanks to Adam Langley and Wan-Teh Chang for discovering and researching this issue. (CVE-2014-3505) [Adam Langley] *) If a multithreaded client connects to a malicious server using a resumed session and the server sends an ec point format extension it could write up to 255 bytes to freed memory. Thanks to Gabor Tyukasz (LogMeIn Inc) for discovering and researching this issue. (CVE-2014-3509) [Gabor Tyukasz] *) A malicious server can crash an OpenSSL client with a null pointer dereference (read) by specifying an SRP ciphersuite even though it was not properly negotiated with the client. This can be exploited through a Denial of Service attack. Thanks to Joonas Kuorilehto and Riku Hietamäki (Codenomicon) for discovering and researching this issue. (CVE-2014-5139) [Steve Henson] *) A flaw in OBJ_obj2txt may cause pretty printing functions such as X509_name_oneline, X509_name_print_ex et al. to leak some information from the stack. Applications may be affected if they echo pretty printing output to the attacker. Thanks to Ivan Fratric (Google) for discovering this issue. (CVE-2014-3508) [Emilia Käsper, and Steve Henson] *) Fix ec_GFp_simple_points_make_affine (thus, EC_POINTs_mul etc.) for corner cases. (Certain input points at infinity could lead to bogus results, with non-infinity inputs mapped to infinity too.) [Bodo Moeller] Changes between 1.0.1g and 1.0.1h [5 Jun 2014] *) Fix for SSL/TLS MITM flaw. An attacker using a carefully crafted handshake can force the use of weak keying material in OpenSSL SSL/TLS clients and servers. Thanks to KIKUCHI Masashi (Lepidum Co. Ltd.) for discovering and researching this issue. (CVE-2014-0224) [KIKUCHI Masashi, Steve Henson] *) Fix DTLS recursion flaw. By sending an invalid DTLS handshake to an OpenSSL DTLS client the code can be made to recurse eventually crashing in a DoS attack. Thanks to Imre Rad (Search-Lab Ltd.) for discovering this issue. (CVE-2014-0221) [Imre Rad, Steve Henson] *) Fix DTLS invalid fragment vulnerability. A buffer overrun attack can be triggered by sending invalid DTLS fragments to an OpenSSL DTLS client or server. This is potentially exploitable to run arbitrary code on a vulnerable client or server. Thanks to Jüri Aedla for reporting this issue. (CVE-2014-0195) [Jüri Aedla, Steve Henson] *) Fix bug in TLS code where clients enable anonymous ECDH ciphersuites are subject to a denial of service attack. Thanks to Felix Gröbert and Ivan Fratric at Google for discovering this issue. (CVE-2014-3470) [Felix Gröbert, Ivan Fratric, Steve Henson] *) Harmonize version and its documentation. -f flag is used to display compilation flags. [mancha ] *) Fix eckey_priv_encode so it immediately returns an error upon a failure in i2d_ECPrivateKey. Thanks to Ted Unangst for feedback on this issue. [mancha ] *) Fix some double frees. These are not thought to be exploitable. [mancha ] Changes between 1.0.1f and 1.0.1g [7 Apr 2014] *) A missing bounds check in the handling of the TLS heartbeat extension can be used to reveal up to 64k of memory to a connected client or server. Thanks for Neel Mehta of Google Security for discovering this bug and to Adam Langley and Bodo Moeller for preparing the fix (CVE-2014-0160) [Adam Langley, Bodo Moeller] *) Fix for the attack described in the paper "Recovering OpenSSL ECDSA Nonces Using the FLUSH+RELOAD Cache Side-channel Attack" by Yuval Yarom and Naomi Benger. Details can be obtained from: http://eprint.iacr.org/2014/140 Thanks to Yuval Yarom and Naomi Benger for discovering this flaw and to Yuval Yarom for supplying a fix (CVE-2014-0076) [Yuval Yarom and Naomi Benger] *) TLS pad extension: draft-agl-tls-padding-03 Workaround for the "TLS hang bug" (see FAQ and PR#2771): if the TLS client Hello record length value would otherwise be > 255 and less that 512 pad with a dummy extension containing zeroes so it is at least 512 bytes long. [Adam Langley, Steve Henson] Changes between 1.0.1e and 1.0.1f [6 Jan 2014] *) Fix for TLS record tampering bug. A carefully crafted invalid handshake could crash OpenSSL with a NULL pointer exception. Thanks to Anton Johansson for reporting this issues. (CVE-2013-4353) *) Keep original DTLS digest and encryption contexts in retransmission structures so we can use the previous session parameters if they need to be resent. (CVE-2013-6450) [Steve Henson] *) Add option SSL_OP_SAFARI_ECDHE_ECDSA_BUG (part of SSL_OP_ALL) which avoids preferring ECDHE-ECDSA ciphers when the client appears to be Safari on OS X. Safari on OS X 10.8..10.8.3 advertises support for several ECDHE-ECDSA ciphers, but fails to negotiate them. The bug is fixed in OS X 10.8.4, but Apple have ruled out both hot fixing 10.8..10.8.3 and forcing users to upgrade to 10.8.4 or newer. [Rob Stradling, Adam Langley] Changes between 1.0.1d and 1.0.1e [11 Feb 2013] *) Correct fix for CVE-2013-0169. The original didn't work on AES-NI supporting platforms or when small records were transferred. [Andy Polyakov, Steve Henson] Changes between 1.0.1c and 1.0.1d [5 Feb 2013] *) Make the decoding of SSLv3, TLS and DTLS CBC records constant time. This addresses the flaw in CBC record processing discovered by Nadhem Alfardan and Kenny Paterson. Details of this attack can be found at: http://www.isg.rhul.ac.uk/tls/ Thanks go to Nadhem Alfardan and Kenny Paterson of the Information Security Group at Royal Holloway, University of London (www.isg.rhul.ac.uk) for discovering this flaw and Adam Langley and Emilia Käsper for the initial patch. (CVE-2013-0169) [Emilia Käsper, Adam Langley, Ben Laurie, Andy Polyakov, Steve Henson] *) Fix flaw in AESNI handling of TLS 1.2 and 1.1 records for CBC mode ciphersuites which can be exploited in a denial of service attack. Thanks go to and to Adam Langley for discovering and detecting this bug and to Wolfgang Ettlinger for independently discovering this issue. (CVE-2012-2686) [Adam Langley] *) Return an error when checking OCSP signatures when key is NULL. This fixes a DoS attack. (CVE-2013-0166) [Steve Henson] *) Make openssl verify return errors. [Chris Palmer and Ben Laurie] *) Call OCSP Stapling callback after ciphersuite has been chosen, so the right response is stapled. Also change SSL_get_certificate() so it returns the certificate actually sent. See http://rt.openssl.org/Ticket/Display.html?id=2836. [Rob Stradling ] *) Fix possible deadlock when decoding public keys. [Steve Henson] *) Don't use TLS 1.0 record version number in initial client hello if renegotiating. [Steve Henson] Changes between 1.0.1b and 1.0.1c [10 May 2012] *) Sanity check record length before skipping explicit IV in TLS 1.2, 1.1 and DTLS to fix DoS attack. Thanks to Codenomicon for discovering this issue using Fuzz-o-Matic fuzzing as a service testing platform. (CVE-2012-2333) [Steve Henson] *) Initialise tkeylen properly when encrypting CMS messages. Thanks to Solar Designer of Openwall for reporting this issue. [Steve Henson] *) In FIPS mode don't try to use composite ciphers as they are not approved. [Steve Henson] Changes between 1.0.1a and 1.0.1b [26 Apr 2012] *) OpenSSL 1.0.0 sets SSL_OP_ALL to 0x80000FFFL and OpenSSL 1.0.1 and 1.0.1a set SSL_OP_NO_TLSv1_1 to 0x00000400L which would unfortunately mean any application compiled against OpenSSL 1.0.0 headers setting SSL_OP_ALL would also set SSL_OP_NO_TLSv1_1, unintentionally disablng TLS 1.1 also. Fix this by changing the value of SSL_OP_NO_TLSv1_1 to 0x10000000L Any application which was previously compiled against OpenSSL 1.0.1 or 1.0.1a headers and which cares about SSL_OP_NO_TLSv1_1 will need to be recompiled as a result. Letting be results in inability to disable specifically TLS 1.1 and in client context, in unlike event, limit maximum offered version to TLS 1.0 [see below]. [Steve Henson] *) In order to ensure interoperabilty SSL_OP_NO_protocolX does not disable just protocol X, but all protocols above X *if* there are protocols *below* X still enabled. In more practical terms it means that if application wants to disable TLS1.0 in favor of TLS1.1 and above, it's not sufficient to pass SSL_OP_NO_TLSv1, one has to pass SSL_OP_NO_TLSv1|SSL_OP_NO_SSLv3|SSL_OP_NO_SSLv2. This applies to client side. [Andy Polyakov] Changes between 1.0.1 and 1.0.1a [19 Apr 2012] *) Check for potentially exploitable overflows in asn1_d2i_read_bio BUF_mem_grow and BUF_mem_grow_clean. Refuse attempts to shrink buffer in CRYPTO_realloc_clean. Thanks to Tavis Ormandy, Google Security Team, for discovering this issue and to Adam Langley for fixing it. (CVE-2012-2110) [Adam Langley (Google), Tavis Ormandy, Google Security Team] *) Don't allow TLS 1.2 SHA-256 ciphersuites in TLS 1.0, 1.1 connections. [Adam Langley] *) Workarounds for some broken servers that "hang" if a client hello record length exceeds 255 bytes. 1. Do not use record version number > TLS 1.0 in initial client hello: some (but not all) hanging servers will now work. 2. If we set OPENSSL_MAX_TLS1_2_CIPHER_LENGTH this will truncate the number of ciphers sent in the client hello. This should be set to an even number, such as 50, for example by passing: -DOPENSSL_MAX_TLS1_2_CIPHER_LENGTH=50 to config or Configure. Most broken servers should now work. 3. If all else fails setting OPENSSL_NO_TLS1_2_CLIENT will disable TLS 1.2 client support entirely. [Steve Henson] *) Fix SEGV in Vector Permutation AES module observed in OpenSSH. [Andy Polyakov] Changes between 1.0.0h and 1.0.1 [14 Mar 2012] *) Add compatibility with old MDC2 signatures which use an ASN1 OCTET STRING form instead of a DigestInfo. [Steve Henson] *) The format used for MDC2 RSA signatures is inconsistent between EVP and the RSA_sign/RSA_verify functions. This was made more apparent when OpenSSL used RSA_sign/RSA_verify for some RSA signatures in particular those which went through EVP_PKEY_METHOD in 1.0.0 and later. Detect the correct format in RSA_verify so both forms transparently work. [Steve Henson] *) Some servers which support TLS 1.0 can choke if we initially indicate support for TLS 1.2 and later renegotiate using TLS 1.0 in the RSA encrypted premaster secret. As a workaround use the maximum pemitted client version in client hello, this should keep such servers happy and still work with previous versions of OpenSSL. [Steve Henson] *) Add support for TLS/DTLS heartbeats. [Robin Seggelmann ] *) Add support for SCTP. [Robin Seggelmann ] *) Improved PRNG seeding for VOS. [Paul Green ] *) Extensive assembler packs updates, most notably: - x86[_64]: AES-NI, PCLMULQDQ, RDRAND support; - x86[_64]: SSSE3 support (SHA1, vector-permutation AES); - x86_64: bit-sliced AES implementation; - ARM: NEON support, contemporary platforms optimizations; - s390x: z196 support; - *: GHASH and GF(2^m) multiplication implementations; [Andy Polyakov] *) Make TLS-SRP code conformant with RFC 5054 API cleanup (removal of unnecessary code) [Peter Sylvester ] *) Add TLS key material exporter from RFC 5705. [Eric Rescorla] *) Add DTLS-SRTP negotiation from RFC 5764. [Eric Rescorla] *) Add Next Protocol Negotiation, http://tools.ietf.org/html/draft-agl-tls-nextprotoneg-00. Can be disabled with a no-npn flag to config or Configure. Code donated by Google. [Adam Langley and Ben Laurie] *) Add optional 64-bit optimized implementations of elliptic curves NIST-P224, NIST-P256, NIST-P521, with constant-time single point multiplication on typical inputs. Compiler support for the nonstandard type __uint128_t is required to use this (present in gcc 4.4 and later, for 64-bit builds). Code made available under Apache License version 2.0. Specify "enable-ec_nistp_64_gcc_128" on the Configure (or config) command line to include this in your build of OpenSSL, and run "make depend" (or "make update"). This enables the following EC_METHODs: EC_GFp_nistp224_method() EC_GFp_nistp256_method() EC_GFp_nistp521_method() EC_GROUP_new_by_curve_name() will automatically use these (while EC_GROUP_new_curve_GFp() currently prefers the more flexible implementations). [Emilia Käsper, Adam Langley, Bodo Moeller (Google)] *) Use type ossl_ssize_t instad of ssize_t which isn't available on all platforms. Move ssize_t definition from e_os.h to the public header file e_os2.h as it now appears in public header file cms.h [Steve Henson] *) New -sigopt option to the ca, req and x509 utilities. Additional signature parameters can be passed using this option and in particular PSS. [Steve Henson] *) Add RSA PSS signing function. This will generate and set the appropriate AlgorithmIdentifiers for PSS based on those in the corresponding EVP_MD_CTX structure. No application support yet. [Steve Henson] *) Support for companion algorithm specific ASN1 signing routines. New function ASN1_item_sign_ctx() signs a pre-initialised EVP_MD_CTX structure and sets AlgorithmIdentifiers based on the appropriate parameters. [Steve Henson] *) Add new algorithm specific ASN1 verification initialisation function to EVP_PKEY_ASN1_METHOD: this is not in EVP_PKEY_METHOD since the ASN1 handling will be the same no matter what EVP_PKEY_METHOD is used. Add a PSS handler to support verification of PSS signatures: checked against a number of sample certificates. [Steve Henson] *) Add signature printing for PSS. Add PSS OIDs. [Steve Henson, Martin Kaiser ] *) Add algorithm specific signature printing. An individual ASN1 method can now print out signatures instead of the standard hex dump. More complex signatures (e.g. PSS) can print out more meaningful information. Include DSA version that prints out the signature parameters r, s. [Steve Henson] *) Password based recipient info support for CMS library: implementing RFC3211. [Steve Henson] *) Split password based encryption into PBES2 and PBKDF2 functions. This neatly separates the code into cipher and PBE sections and is required for some algorithms that split PBES2 into separate pieces (such as password based CMS). [Steve Henson] *) Session-handling fixes: - Fix handling of connections that are resuming with a session ID, but also support Session Tickets. - Fix a bug that suppressed issuing of a new ticket if the client presented a ticket with an expired session. - Try to set the ticket lifetime hint to something reasonable. - Make tickets shorter by excluding irrelevant information. - On the client side, don't ignore renewed tickets. [Adam Langley, Bodo Moeller (Google)] *) Fix PSK session representation. [Bodo Moeller] *) Add RC4-MD5 and AESNI-SHA1 "stitched" implementations. This work was sponsored by Intel. [Andy Polyakov] *) Add GCM support to TLS library. Some custom code is needed to split the IV between the fixed (from PRF) and explicit (from TLS record) portions. This adds all GCM ciphersuites supported by RFC5288 and RFC5289. Generalise some AES* cipherstrings to inlclude GCM and add a special AESGCM string for GCM only. [Steve Henson] *) Expand range of ctrls for AES GCM. Permit setting invocation field on decrypt and retrieval of invocation field only on encrypt. [Steve Henson] *) Add HMAC ECC ciphersuites from RFC5289. Include SHA384 PRF support. As required by RFC5289 these ciphersuites cannot be used if for versions of TLS earlier than 1.2. [Steve Henson] *) For FIPS capable OpenSSL interpret a NULL default public key method as unset and return the appopriate default but do *not* set the default. This means we can return the appopriate method in applications that swicth between FIPS and non-FIPS modes. [Steve Henson] *) Redirect HMAC and CMAC operations to FIPS module in FIPS mode. If an ENGINE is used then we cannot handle that in the FIPS module so we keep original code iff non-FIPS operations are allowed. [Steve Henson] *) Add -attime option to openssl utilities. [Peter Eckersley , Ben Laurie and Steve Henson] *) Redirect DSA and DH operations to FIPS module in FIPS mode. [Steve Henson] *) Redirect ECDSA and ECDH operations to FIPS module in FIPS mode. Also use FIPS EC methods unconditionally for now. [Steve Henson] *) New build option no-ec2m to disable characteristic 2 code. [Steve Henson] *) Backport libcrypto audit of return value checking from 1.1.0-dev; not all cases can be covered as some introduce binary incompatibilities. [Steve Henson] *) Redirect RSA operations to FIPS module including keygen, encrypt, decrypt, sign and verify. Block use of non FIPS RSA methods. [Steve Henson] *) Add similar low level API blocking to ciphers. [Steve Henson] *) Low level digest APIs are not approved in FIPS mode: any attempt to use these will cause a fatal error. Applications that *really* want to use them can use the private_* version instead. [Steve Henson] *) Redirect cipher operations to FIPS module for FIPS builds. [Steve Henson] *) Redirect digest operations to FIPS module for FIPS builds. [Steve Henson] *) Update build system to add "fips" flag which will link in fipscanister.o for static and shared library builds embedding a signature if needed. [Steve Henson] *) Output TLS supported curves in preference order instead of numerical order. This is currently hardcoded for the highest order curves first. This should be configurable so applications can judge speed vs strength. [Steve Henson] *) Add TLS v1.2 server support for client authentication. [Steve Henson] *) Add support for FIPS mode in ssl library: disable SSLv3, non-FIPS ciphers and enable MD5. [Steve Henson] *) Functions FIPS_mode_set() and FIPS_mode() which call the underlying FIPS modules versions. [Steve Henson] *) Add TLS v1.2 client side support for client authentication. Keep cache of handshake records longer as we don't know the hash algorithm to use until after the certificate request message is received. [Steve Henson] *) Initial TLS v1.2 client support. Add a default signature algorithms extension including all the algorithms we support. Parse new signature format in client key exchange. Relax some ECC signing restrictions for TLS v1.2 as indicated in RFC5246. [Steve Henson] *) Add server support for TLS v1.2 signature algorithms extension. Switch to new signature format when needed using client digest preference. All server ciphersuites should now work correctly in TLS v1.2. No client support yet and no support for client certificates. [Steve Henson] *) Initial TLS v1.2 support. Add new SHA256 digest to ssl code, switch to SHA256 for PRF when using TLS v1.2 and later. Add new SHA256 based ciphersuites. At present only RSA key exchange ciphersuites work with TLS v1.2. Add new option for TLS v1.2 replacing the old and obsolete SSL_OP_PKCS1_CHECK flags with SSL_OP_NO_TLSv1_2. New TLSv1.2 methods and version checking. [Steve Henson] *) New option OPENSSL_NO_SSL_INTERN. If an application can be compiled with this defined it will not be affected by any changes to ssl internal structures. Add several utility functions to allow openssl application to work with OPENSSL_NO_SSL_INTERN defined. [Steve Henson] *) Add SRP support. [Tom Wu and Ben Laurie] *) Add functions to copy EVP_PKEY_METHOD and retrieve flags and id. [Steve Henson] *) Permit abbreviated handshakes when renegotiating using the function SSL_renegotiate_abbreviated(). [Robin Seggelmann ] *) Add call to ENGINE_register_all_complete() to ENGINE_load_builtin_engines(), so some implementations get used automatically instead of needing explicit application support. [Steve Henson] *) Add support for TLS key exporter as described in RFC5705. [Robin Seggelmann , Steve Henson] *) Initial TLSv1.1 support. Since TLSv1.1 is very similar to TLS v1.0 only a few changes are required: Add SSL_OP_NO_TLSv1_1 flag. Add TLSv1_1 methods. Update version checking logic to handle version 1.1. Add explicit IV handling (ported from DTLS code). Add command line options to s_client/s_server. [Steve Henson] Changes between 1.0.0g and 1.0.0h [12 Mar 2012] *) Fix MMA (Bleichenbacher's attack on PKCS #1 v1.5 RSA padding) weakness in CMS and PKCS7 code. When RSA decryption fails use a random key for content decryption and always return the same error. Note: this attack needs on average 2^20 messages so it only affects automated senders. The old behaviour can be reenabled in the CMS code by setting the CMS_DEBUG_DECRYPT flag: this is useful for debugging and testing where an MMA defence is not necessary. Thanks to Ivan Nestlerode for discovering this issue. (CVE-2012-0884) [Steve Henson] *) Fix CVE-2011-4619: make sure we really are receiving a client hello before rejecting multiple SGC restarts. Thanks to Ivan Nestlerode for discovering this bug. [Steve Henson] Changes between 1.0.0f and 1.0.0g [18 Jan 2012] *) Fix for DTLS DoS issue introduced by fix for CVE-2011-4109. Thanks to Antonio Martin, Enterprise Secure Access Research and Development, Cisco Systems, Inc. for discovering this bug and preparing a fix. (CVE-2012-0050) [Antonio Martin] Changes between 1.0.0e and 1.0.0f [4 Jan 2012] *) Nadhem Alfardan and Kenny Paterson have discovered an extension of the Vaudenay padding oracle attack on CBC mode encryption which enables an efficient plaintext recovery attack against the OpenSSL implementation of DTLS. Their attack exploits timing differences arising during decryption processing. A research paper describing this attack can be found at: http://www.isg.rhul.ac.uk/~kp/dtls.pdf Thanks go to Nadhem Alfardan and Kenny Paterson of the Information Security Group at Royal Holloway, University of London (www.isg.rhul.ac.uk) for discovering this flaw and to Robin Seggelmann and Michael Tuexen for preparing the fix. (CVE-2011-4108) [Robin Seggelmann, Michael Tuexen] *) Clear bytes used for block padding of SSL 3.0 records. (CVE-2011-4576) [Adam Langley (Google)] *) Only allow one SGC handshake restart for SSL/TLS. Thanks to George Kadianakis for discovering this issue and Adam Langley for preparing the fix. (CVE-2011-4619) [Adam Langley (Google)] *) Check parameters are not NULL in GOST ENGINE. (CVE-2012-0027) [Andrey Kulikov ] *) Prevent malformed RFC3779 data triggering an assertion failure. Thanks to Andrew Chi, BBN Technologies, for discovering the flaw and Rob Austein for fixing it. (CVE-2011-4577) [Rob Austein ] *) Improved PRNG seeding for VOS. [Paul Green ] *) Fix ssl_ciph.c set-up race. [Adam Langley (Google)] *) Fix spurious failures in ecdsatest.c. [Emilia Käsper (Google)] *) Fix the BIO_f_buffer() implementation (which was mixing different interpretations of the '..._len' fields). [Adam Langley (Google)] *) Fix handling of BN_BLINDING: now BN_BLINDING_invert_ex (rather than BN_BLINDING_invert_ex) calls BN_BLINDING_update, ensuring that concurrent threads won't reuse the same blinding coefficients. This also avoids the need to obtain the CRYPTO_LOCK_RSA_BLINDING lock to call BN_BLINDING_invert_ex, and avoids one use of BN_BLINDING_update for each BN_BLINDING structure (previously, the last update always remained unused). [Emilia Käsper (Google)] *) In ssl3_clear, preserve s3->init_extra along with s3->rbuf. [Bob Buckholz (Google)] Changes between 1.0.0d and 1.0.0e [6 Sep 2011] *) Fix bug where CRLs with nextUpdate in the past are sometimes accepted by initialising X509_STORE_CTX properly. (CVE-2011-3207) [Kaspar Brand ] *) Fix SSL memory handling for (EC)DH ciphersuites, in particular for multi-threaded use of ECDH. (CVE-2011-3210) [Adam Langley (Google)] *) Fix x509_name_ex_d2i memory leak on bad inputs. [Bodo Moeller] *) Remove hard coded ecdsaWithSHA1 signature tests in ssl code and check signature public key algorithm by using OID xref utilities instead. Before this you could only use some ECC ciphersuites with SHA1 only. [Steve Henson] *) Add protection against ECDSA timing attacks as mentioned in the paper by Billy Bob Brumley and Nicola Tuveri, see: http://eprint.iacr.org/2011/232.pdf [Billy Bob Brumley and Nicola Tuveri] Changes between 1.0.0c and 1.0.0d [8 Feb 2011] *) Fix parsing of OCSP stapling ClientHello extension. CVE-2011-0014 [Neel Mehta, Adam Langley, Bodo Moeller (Google)] *) Fix bug in string printing code: if *any* escaping is enabled we must escape the escape character (backslash) or the resulting string is ambiguous. [Steve Henson] Changes between 1.0.0b and 1.0.0c [2 Dec 2010] *) Disable code workaround for ancient and obsolete Netscape browsers and servers: an attacker can use it in a ciphersuite downgrade attack. Thanks to Martin Rex for discovering this bug. CVE-2010-4180 [Steve Henson] *) Fixed J-PAKE implementation error, originally discovered by Sebastien Martini, further info and confirmation from Stefan Arentz and Feng Hao. Note that this fix is a security fix. CVE-2010-4252 [Ben Laurie] Changes between 1.0.0a and 1.0.0b [16 Nov 2010] *) Fix extension code to avoid race conditions which can result in a buffer overrun vulnerability: resumed sessions must not be modified as they can be shared by multiple threads. CVE-2010-3864 [Steve Henson] *) Fix WIN32 build system to correctly link an ENGINE directory into a DLL. [Steve Henson] Changes between 1.0.0 and 1.0.0a [01 Jun 2010] *) Check return value of int_rsa_verify in pkey_rsa_verifyrecover (CVE-2010-1633) [Steve Henson, Peter-Michael Hager ] Changes between 0.9.8n and 1.0.0 [29 Mar 2010] *) Add "missing" function EVP_CIPHER_CTX_copy(). This copies a cipher context. The operation can be customised via the ctrl mechanism in case ENGINEs want to include additional functionality. [Steve Henson] *) Tolerate yet another broken PKCS#8 key format: private key value negative. [Steve Henson] *) Add new -subject_hash_old and -issuer_hash_old options to x509 utility to output hashes compatible with older versions of OpenSSL. [Willy Weisz ] *) Fix compression algorithm handling: if resuming a session use the compression algorithm of the resumed session instead of determining it from client hello again. Don't allow server to change algorithm. [Steve Henson] *) Add load_crls() function to apps tidying load_certs() too. Add option to verify utility to allow additional CRLs to be included. [Steve Henson] *) Update OCSP request code to permit adding custom headers to the request: some responders need this. [Steve Henson] *) The function EVP_PKEY_sign() returns <=0 on error: check return code correctly. [Julia Lawall ] *) Update verify callback code in apps/s_cb.c and apps/verify.c, it needlessly dereferenced structures, used obsolete functions and didn't handle all updated verify codes correctly. [Steve Henson] *) Disable MD2 in the default configuration. [Steve Henson] *) In BIO_pop() and BIO_push() use the ctrl argument (which was NULL) to indicate the initial BIO being pushed or popped. This makes it possible to determine whether the BIO is the one explicitly called or as a result of the ctrl being passed down the chain. Fix BIO_pop() and SSL BIOs so it handles reference counts correctly and doesn't zero out the I/O bio when it is not being explicitly popped. WARNING: applications which included workarounds for the old buggy behaviour will need to be modified or they could free up already freed BIOs. [Steve Henson] *) Extend the uni2asc/asc2uni => OPENSSL_uni2asc/OPENSSL_asc2uni renaming to all platforms (within the 0.9.8 branch, this was done conditionally on Netware platforms to avoid a name clash). [Guenter ] *) Add ECDHE and PSK support to DTLS. [Michael Tuexen ] *) Add CHECKED_STACK_OF macro to safestack.h, otherwise safestack can't be used on C++. [Steve Henson] *) Add "missing" function EVP_MD_flags() (without this the only way to retrieve a digest flags is by accessing the structure directly. Update EVP_MD_do_all*() and EVP_CIPHER_do_all*() to include the name a digest or cipher is registered as in the "from" argument. Print out all registered digests in the dgst usage message instead of manually attempting to work them out. [Steve Henson] *) If no SSLv2 ciphers are used don't use an SSLv2 compatible client hello: this allows the use of compression and extensions. Change default cipher string to remove SSLv2 ciphersuites. This effectively avoids ancient SSLv2 by default unless an application cipher string requests it. [Steve Henson] *) Alter match criteria in PKCS12_parse(). It used to try to use local key ids to find matching certificates and keys but some PKCS#12 files don't follow the (somewhat unwritten) rules and this strategy fails. Now just gather all certificates together and the first private key then look for the first certificate that matches the key. [Steve Henson] *) Support use of registered digest and cipher names for dgst and cipher commands instead of having to add each one as a special case. So now you can do: openssl sha256 foo as well as: openssl dgst -sha256 foo and this works for ENGINE based algorithms too. [Steve Henson] *) Update Gost ENGINE to support parameter files. [Victor B. Wagner ] *) Support GeneralizedTime in ca utility. [Oliver Martin , Steve Henson] *) Enhance the hash format used for certificate directory links. The new form uses the canonical encoding (meaning equivalent names will work even if they aren't identical) and uses SHA1 instead of MD5. This form is incompatible with the older format and as a result c_rehash should be used to rebuild symbolic links. [Steve Henson] *) Make PKCS#8 the default write format for private keys, replacing the traditional format. This form is standardised, more secure and doesn't include an implicit MD5 dependency. [Steve Henson] *) Add a $gcc_devteam_warn option to Configure. The idea is that any code committed to OpenSSL should pass this lot as a minimum. [Steve Henson] *) Add session ticket override functionality for use by EAP-FAST. [Jouni Malinen ] *) Modify HMAC functions to return a value. Since these can be implemented in an ENGINE errors can occur. [Steve Henson] *) Type-checked OBJ_bsearch_ex. [Ben Laurie] *) Type-checked OBJ_bsearch. Also some constification necessitated by type-checking. Still to come: TXT_DB, bsearch(?), OBJ_bsearch_ex, qsort, CRYPTO_EX_DATA, ASN1_VALUE, ASN1_STRING, CONF_VALUE. [Ben Laurie] *) New function OPENSSL_gmtime_adj() to add a specific number of days and seconds to a tm structure directly, instead of going through OS specific date routines. This avoids any issues with OS routines such as the year 2038 bug. New *_adj() functions for ASN1 time structures and X509_time_adj_ex() to cover the extended range. The existing X509_time_adj() is still usable and will no longer have any date issues. [Steve Henson] *) Delta CRL support. New use deltas option which will attempt to locate and search any appropriate delta CRLs available. This work was sponsored by Google. [Steve Henson] *) Support for CRLs partitioned by reason code. Reorganise CRL processing code and add additional score elements. Validate alternate CRL paths as part of the CRL checking and indicate a new error "CRL path validation error" in this case. Applications wanting additional details can use the verify callback and check the new "parent" field. If this is not NULL CRL path validation is taking place. Existing applications wont see this because it requires extended CRL support which is off by default. This work was sponsored by Google. [Steve Henson] *) Support for freshest CRL extension. This work was sponsored by Google. [Steve Henson] *) Initial indirect CRL support. Currently only supported in the CRLs passed directly and not via lookup. Process certificate issuer CRL entry extension and lookup CRL entries by bother issuer name and serial number. Check and process CRL issuer entry in IDP extension. This work was sponsored by Google. [Steve Henson] *) Add support for distinct certificate and CRL paths. The CRL issuer certificate is validated separately in this case. Only enabled if an extended CRL support flag is set: this flag will enable additional CRL functionality in future. This work was sponsored by Google. [Steve Henson] *) Add support for policy mappings extension. This work was sponsored by Google. [Steve Henson] *) Fixes to pathlength constraint, self issued certificate handling, policy processing to align with RFC3280 and PKITS tests. This work was sponsored by Google. [Steve Henson] *) Support for name constraints certificate extension. DN, email, DNS and URI types are currently supported. This work was sponsored by Google. [Steve Henson] *) To cater for systems that provide a pointer-based thread ID rather than numeric, deprecate the current numeric thread ID mechanism and replace it with a structure and associated callback type. This mechanism allows a numeric "hash" to be extracted from a thread ID in either case, and on platforms where pointers are larger than 'long', mixing is done to help ensure the numeric 'hash' is usable even if it can't be guaranteed unique. The default mechanism is to use "&errno" as a pointer-based thread ID to distinguish between threads. Applications that want to provide their own thread IDs should now use CRYPTO_THREADID_set_callback() to register a callback that will call either CRYPTO_THREADID_set_numeric() or CRYPTO_THREADID_set_pointer(). Note that ERR_remove_state() is now deprecated, because it is tied to the assumption that thread IDs are numeric. ERR_remove_state(0) to free the current thread's error state should be replaced by ERR_remove_thread_state(NULL). (This new approach replaces the functions CRYPTO_set_idptr_callback(), CRYPTO_get_idptr_callback(), and CRYPTO_thread_idptr() that existed in OpenSSL 0.9.9-dev between June 2006 and August 2008. Also, if an application was previously providing a numeric thread callback that was inappropriate for distinguishing threads, then uniqueness might have been obtained with &errno that happened immediately in the intermediate development versions of OpenSSL; this is no longer the case, the numeric thread callback will now override the automatic use of &errno.) [Geoff Thorpe, with help from Bodo Moeller] *) Initial support for different CRL issuing certificates. This covers a simple case where the self issued certificates in the chain exist and the real CRL issuer is higher in the existing chain. This work was sponsored by Google. [Steve Henson] *) Removed effectively defunct crypto/store from the build. [Ben Laurie] *) Revamp of STACK to provide stronger type-checking. Still to come: TXT_DB, bsearch(?), OBJ_bsearch, qsort, CRYPTO_EX_DATA, ASN1_VALUE, ASN1_STRING, CONF_VALUE. [Ben Laurie] *) Add a new SSL_MODE_RELEASE_BUFFERS mode flag to release unused buffer RAM on SSL connections. This option can save about 34k per idle SSL. [Nick Mathewson] *) Revamp of LHASH to provide stronger type-checking. Still to come: STACK, TXT_DB, bsearch, qsort. [Ben Laurie] *) Initial support for Cryptographic Message Syntax (aka CMS) based on RFC3850, RFC3851 and RFC3852. New cms directory and cms utility, support for data, signedData, compressedData, digestedData and encryptedData, envelopedData types included. Scripts to check against RFC4134 examples draft and interop and consistency checks of many content types and variants. [Steve Henson] *) Add options to enc utility to support use of zlib compression BIO. [Steve Henson] *) Extend mk1mf to support importing of options and assembly language files from Configure script, currently only included in VC-WIN32. The assembly language rules can now optionally generate the source files from the associated perl scripts. [Steve Henson] *) Implement remaining functionality needed to support GOST ciphersuites. Interop testing has been performed using CryptoPro implementations. [Victor B. Wagner ] *) s390x assembler pack. [Andy Polyakov] *) ARMv4 assembler pack. ARMv4 refers to v4 and later ISA, not CPU "family." [Andy Polyakov] *) Implement Opaque PRF Input TLS extension as specified in draft-rescorla-tls-opaque-prf-input-00.txt. Since this is not an official specification yet and no extension type assignment by IANA exists, this extension (for now) will have to be explicitly enabled when building OpenSSL by providing the extension number to use. For example, specify an option -DTLSEXT_TYPE_opaque_prf_input=0x9527 to the "config" or "Configure" script to enable the extension, assuming extension number 0x9527 (which is a completely arbitrary and unofficial assignment based on the MD5 hash of the Internet Draft). Note that by doing so, you potentially lose interoperability with other TLS implementations since these might be using the same extension number for other purposes. SSL_set_tlsext_opaque_prf_input(ssl, src, len) is used to set the opaque PRF input value to use in the handshake. This will create an interal copy of the length-'len' string at 'src', and will return non-zero for success. To get more control and flexibility, provide a callback function by using SSL_CTX_set_tlsext_opaque_prf_input_callback(ctx, cb) SSL_CTX_set_tlsext_opaque_prf_input_callback_arg(ctx, arg) where int (*cb)(SSL *, void *peerinput, size_t len, void *arg); void *arg; Callback function 'cb' will be called in handshakes, and is expected to use SSL_set_tlsext_opaque_prf_input() as appropriate. Argument 'arg' is for application purposes (the value as given to SSL_CTX_set_tlsext_opaque_prf_input_callback_arg() will directly be provided to the callback function). The callback function has to return non-zero to report success: usually 1 to use opaque PRF input just if possible, or 2 to enforce use of the opaque PRF input. In the latter case, the library will abort the handshake if opaque PRF input is not successfully negotiated. Arguments 'peerinput' and 'len' given to the callback function will always be NULL and 0 in the case of a client. A server will see the client's opaque PRF input through these variables if available (NULL and 0 otherwise). Note that if the server provides an opaque PRF input, the length must be the same as the length of the client's opaque PRF input. Note that the callback function will only be called when creating a new session (session resumption can resume whatever was previously negotiated), and will not be called in SSL 2.0 handshakes; thus, SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2) or SSL_set_options(ssl, SSL_OP_NO_SSLv2) is especially recommended for applications that need to enforce opaque PRF input. [Bodo Moeller] *) Update ssl code to support digests other than SHA1+MD5 for handshake MAC. [Victor B. Wagner ] *) Add RFC4507 support to OpenSSL. This includes the corrections in RFC4507bis. The encrypted ticket format is an encrypted encoded SSL_SESSION structure, that way new session features are automatically supported. If a client application caches session in an SSL_SESSION structure support is transparent because tickets are now stored in the encoded SSL_SESSION. The SSL_CTX structure automatically generates keys for ticket protection in servers so again support should be possible with no application modification. If a client or server wishes to disable RFC4507 support then the option SSL_OP_NO_TICKET can be set. Add a TLS extension debugging callback to allow the contents of any client or server extensions to be examined. This work was sponsored by Google. [Steve Henson] *) Final changes to avoid use of pointer pointer casts in OpenSSL. OpenSSL should now compile cleanly on gcc 4.2 [Peter Hartley , Steve Henson] *) Update SSL library to use new EVP_PKEY MAC API. Include generic MAC support including streaming MAC support: this is required for GOST ciphersuite support. [Victor B. Wagner , Steve Henson] *) Add option -stream to use PKCS#7 streaming in smime utility. New function i2d_PKCS7_bio_stream() and PEM_write_PKCS7_bio_stream() to output in BER and PEM format. [Steve Henson] *) Experimental support for use of HMAC via EVP_PKEY interface. This allows HMAC to be handled via the EVP_DigestSign*() interface. The EVP_PKEY "key" in this case is the HMAC key, potentially allowing ENGINE support for HMAC keys which are unextractable. New -mac and -macopt options to dgst utility. [Steve Henson] *) New option -sigopt to dgst utility. Update dgst to use EVP_Digest{Sign,Verify}*. These two changes make it possible to use alternative signing paramaters such as X9.31 or PSS in the dgst utility. [Steve Henson] *) Change ssl_cipher_apply_rule(), the internal function that does the work each time a ciphersuite string requests enabling ("foo+bar"), moving ("+foo+bar"), disabling ("-foo+bar", or removing ("!foo+bar") a class of ciphersuites: Now it maintains the order of disabled ciphersuites such that those ciphersuites that most recently went from enabled to disabled not only stay in order with respect to each other, but also have higher priority than other disabled ciphersuites the next time ciphersuites are enabled again. This means that you can now say, e.g., "PSK:-PSK:HIGH" to enable the same ciphersuites as with "HIGH" alone, but in a specific order where the PSK ciphersuites come first (since they are the most recently disabled ciphersuites when "HIGH" is parsed). Also, change ssl_create_cipher_list() (using this new funcionality) such that between otherwise identical cihpersuites, ephemeral ECDH is preferred over ephemeral DH in the default order. [Bodo Moeller] *) Change ssl_create_cipher_list() so that it automatically arranges the ciphersuites in reasonable order before starting to process the rule string. Thus, the definition for "DEFAULT" (SSL_DEFAULT_CIPHER_LIST) now is just "ALL:!aNULL:!eNULL", but remains equivalent to "AES:ALL:!aNULL:!eNULL:+aECDH:+kRSA:+RC4:@STRENGTH". This makes it much easier to arrive at a reasonable default order in applications for which anonymous ciphers are OK (meaning that you can't actually use DEFAULT). [Bodo Moeller; suggested by Victor Duchovni] *) Split the SSL/TLS algorithm mask (as used for ciphersuite string processing) into multiple integers instead of setting "SSL_MKEY_MASK" bits, "SSL_AUTH_MASK" bits, "SSL_ENC_MASK", "SSL_MAC_MASK", and "SSL_SSL_MASK" bits all in a single integer. (These masks as well as the individual bit definitions are hidden away into the non-exported interface ssl/ssl_locl.h, so this change to the definition of the SSL_CIPHER structure shouldn't affect applications.) This give us more bits for each of these categories, so there is no longer a need to coagulate AES128 and AES256 into a single algorithm bit, and to coagulate Camellia128 and Camellia256 into a single algorithm bit, which has led to all kinds of kludges. Thus, among other things, the kludge introduced in 0.9.7m and 0.9.8e for masking out AES256 independently of AES128 or masking out Camellia256 independently of AES256 is not needed here in 0.9.9. With the change, we also introduce new ciphersuite aliases that so far were missing: "AES128", "AES256", "CAMELLIA128", and "CAMELLIA256". [Bodo Moeller] *) Add support for dsa-with-SHA224 and dsa-with-SHA256. Use the leftmost N bytes of the signature input if the input is larger than the prime q (with N being the size in bytes of q). [Nils Larsch] *) Very *very* experimental PKCS#7 streaming encoder support. Nothing uses it yet and it is largely untested. [Steve Henson] *) Add support for the ecdsa-with-SHA224/256/384/512 signature types. [Nils Larsch] *) Initial incomplete changes to avoid need for function casts in OpenSSL some compilers (gcc 4.2 and later) reject their use. Safestack is reimplemented. Update ASN1 to avoid use of legacy functions. [Steve Henson] *) Win32/64 targets are linked with Winsock2. [Andy Polyakov] *) Add an X509_CRL_METHOD structure to allow CRL processing to be redirected to external functions. This can be used to increase CRL handling efficiency especially when CRLs are very large by (for example) storing the CRL revoked certificates in a database. [Steve Henson] *) Overhaul of by_dir code. Add support for dynamic loading of CRLs so new CRLs added to a directory can be used. New command line option -verify_return_error to s_client and s_server. This causes real errors to be returned by the verify callback instead of carrying on no matter what. This reflects the way a "real world" verify callback would behave. [Steve Henson] *) GOST engine, supporting several GOST algorithms and public key formats. Kindly donated by Cryptocom. [Cryptocom] *) Partial support for Issuing Distribution Point CRL extension. CRLs partitioned by DP are handled but no indirect CRL or reason partitioning (yet). Complete overhaul of CRL handling: now the most suitable CRL is selected via a scoring technique which handles IDP and AKID in CRLs. [Steve Henson] *) New X509_STORE_CTX callbacks lookup_crls() and lookup_certs() which will ultimately be used for all verify operations: this will remove the X509_STORE dependency on certificate verification and allow alternative lookup methods. X509_STORE based implementations of these two callbacks. [Steve Henson] *) Allow multiple CRLs to exist in an X509_STORE with matching issuer names. Modify get_crl() to find a valid (unexpired) CRL if possible. [Steve Henson] *) New function X509_CRL_match() to check if two CRLs are identical. Normally this would be called X509_CRL_cmp() but that name is already used by a function that just compares CRL issuer names. Cache several CRL extensions in X509_CRL structure and cache CRLDP in X509. [Steve Henson] *) Store a "canonical" representation of X509_NAME structure (ASN1 Name) this maps equivalent X509_NAME structures into a consistent structure. Name comparison can then be performed rapidly using memcmp(). [Steve Henson] *) Non-blocking OCSP request processing. Add -timeout option to ocsp utility. [Steve Henson] *) Allow digests to supply their own micalg string for S/MIME type using the ctrl EVP_MD_CTRL_MICALG. [Steve Henson] *) During PKCS7 signing pass the PKCS7 SignerInfo structure to the EVP_PKEY_METHOD before and after signing via the EVP_PKEY_CTRL_PKCS7_SIGN ctrl. It can then customise the structure before and/or after signing if necessary. [Steve Henson] *) New function OBJ_add_sigid() to allow application defined signature OIDs to be added to OpenSSLs internal tables. New function OBJ_sigid_free() to free up any added signature OIDs. [Steve Henson] *) New functions EVP_CIPHER_do_all(), EVP_CIPHER_do_all_sorted(), EVP_MD_do_all() and EVP_MD_do_all_sorted() to enumerate internal digest and cipher tables. New options added to openssl utility: list-message-digest-algorithms and list-cipher-algorithms. [Steve Henson] *) Change the array representation of binary polynomials: the list of degrees of non-zero coefficients is now terminated with -1. Previously it was terminated with 0, which was also part of the value; thus, the array representation was not applicable to polynomials where t^0 has coefficient zero. This change makes the array representation useful in a more general context. [Douglas Stebila] *) Various modifications and fixes to SSL/TLS cipher string handling. For ECC, the code now distinguishes between fixed ECDH with RSA certificates on the one hand and with ECDSA certificates on the other hand, since these are separate ciphersuites. The unused code for Fortezza ciphersuites has been removed. For consistency with EDH, ephemeral ECDH is now called "EECDH" (not "ECDHE"). For consistency with the code for DH certificates, use of ECDH certificates is now considered ECDH authentication, not RSA or ECDSA authentication (the latter is merely the CA's signing algorithm and not actively used in the protocol). The temporary ciphersuite alias "ECCdraft" is no longer available, and ECC ciphersuites are no longer excluded from "ALL" and "DEFAULT". The following aliases now exist for RFC 4492 ciphersuites, most of these by analogy with the DH case: kECDHr - ECDH cert, signed with RSA kECDHe - ECDH cert, signed with ECDSA kECDH - ECDH cert (signed with either RSA or ECDSA) kEECDH - ephemeral ECDH ECDH - ECDH cert or ephemeral ECDH aECDH - ECDH cert aECDSA - ECDSA cert ECDSA - ECDSA cert AECDH - anonymous ECDH EECDH - non-anonymous ephemeral ECDH (equivalent to "kEECDH:-AECDH") [Bodo Moeller] *) Add additional S/MIME capabilities for AES and GOST ciphers if supported. Use correct micalg parameters depending on digest(s) in signed message. [Steve Henson] *) Add engine support for EVP_PKEY_ASN1_METHOD. Add functions to process an ENGINE asn1 method. Support ENGINE lookups in the ASN1 code. [Steve Henson] *) Initial engine support for EVP_PKEY_METHOD. New functions to permit an engine to register a method. Add ENGINE lookups for methods and functional reference processing. [Steve Henson] *) New functions EVP_Digest{Sign,Verify)*. These are enchance versions of EVP_{Sign,Verify}* which allow an application to customise the signature process. [Steve Henson] *) New -resign option to smime utility. This adds one or more signers to an existing PKCS#7 signedData structure. Also -md option to use an alternative message digest algorithm for signing. [Steve Henson] *) Tidy up PKCS#7 routines and add new functions to make it easier to create PKCS7 structures containing multiple signers. Update smime application to support multiple signers. [Steve Henson] *) New -macalg option to pkcs12 utility to allow setting of an alternative digest MAC. [Steve Henson] *) Initial support for PKCS#5 v2.0 PRFs other than default SHA1 HMAC. Reorganize PBE internals to lookup from a static table using NIDs, add support for HMAC PBE OID translation. Add a EVP_CIPHER ctrl: EVP_CTRL_PBE_PRF_NID this allows a cipher to specify an alternative PRF which will be automatically used with PBES2. [Steve Henson] *) Replace the algorithm specific calls to generate keys in "req" with the new API. [Steve Henson] *) Update PKCS#7 enveloped data routines to use new API. This is now supported by any public key method supporting the encrypt operation. A ctrl is added to allow the public key algorithm to examine or modify the PKCS#7 RecipientInfo structure if it needs to: for RSA this is a no op. [Steve Henson] *) Add a ctrl to asn1 method to allow a public key algorithm to express a default digest type to use. In most cases this will be SHA1 but some algorithms (such as GOST) need to specify an alternative digest. The return value indicates how strong the prefernce is 1 means optional and 2 is mandatory (that is it is the only supported type). Modify ASN1_item_sign() to accept a NULL digest argument to indicate it should use the default md. Update openssl utilities to use the default digest type for signing if it is not explicitly indicated. [Steve Henson] *) Use OID cross reference table in ASN1_sign() and ASN1_verify(). New EVP_MD flag EVP_MD_FLAG_PKEY_METHOD_SIGNATURE. This uses the relevant signing method from the key type. This effectively removes the link between digests and public key types. [Steve Henson] *) Add an OID cross reference table and utility functions. Its purpose is to translate between signature OIDs such as SHA1WithrsaEncryption and SHA1, rsaEncryption. This will allow some of the algorithm specific hackery needed to use the correct OID to be removed. [Steve Henson] *) Remove algorithm specific dependencies when setting PKCS7_SIGNER_INFO structures for PKCS7_sign(). They are now set up by the relevant public key ASN1 method. [Steve Henson] *) Add provisional EC pkey method with support for ECDSA and ECDH. [Steve Henson] *) Add support for key derivation (agreement) in the API, DH method and pkeyutl. [Steve Henson] *) Add DSA pkey method and DH pkey methods, extend DH ASN1 method to support public and private key formats. As a side effect these add additional command line functionality not previously available: DSA signatures can be generated and verified using pkeyutl and DH key support and generation in pkey, genpkey. [Steve Henson] *) BeOS support. [Oliver Tappe ] *) New make target "install_html_docs" installs HTML renditions of the manual pages. [Oliver Tappe ] *) New utility "genpkey" this is analagous to "genrsa" etc except it can generate keys for any algorithm. Extend and update EVP_PKEY_METHOD to support key and parameter generation and add initial key generation functionality for RSA. [Steve Henson] *) Add functions for main EVP_PKEY_method operations. The undocumented functions EVP_PKEY_{encrypt,decrypt} have been renamed to EVP_PKEY_{encrypt,decrypt}_old. [Steve Henson] *) Initial definitions for EVP_PKEY_METHOD. This will be a high level public key API, doesn't do much yet. [Steve Henson] *) New function EVP_PKEY_asn1_get0_info() to retrieve information about public key algorithms. New option to openssl utility: "list-public-key-algorithms" to print out info. [Steve Henson] *) Implement the Supported Elliptic Curves Extension for ECC ciphersuites from draft-ietf-tls-ecc-12.txt. [Douglas Stebila] *) Don't free up OIDs in OBJ_cleanup() if they are in use by EVP_MD or EVP_CIPHER structures to avoid later problems in EVP_cleanup(). [Steve Henson] *) New utilities pkey and pkeyparam. These are similar to algorithm specific utilities such as rsa, dsa, dsaparam etc except they process any key type. [Steve Henson] *) Transfer public key printing routines to EVP_PKEY_ASN1_METHOD. New functions EVP_PKEY_print_public(), EVP_PKEY_print_private(), EVP_PKEY_print_param() to print public key data from an EVP_PKEY structure. [Steve Henson] *) Initial support for pluggable public key ASN1. De-spaghettify the public key ASN1 handling. Move public and private key ASN1 handling to a new EVP_PKEY_ASN1_METHOD structure. Relocate algorithm specific handling to a single module within the relevant algorithm directory. Add functions to allow (near) opaque processing of public and private key structures. [Steve Henson] *) Implement the Supported Point Formats Extension for ECC ciphersuites from draft-ietf-tls-ecc-12.txt. [Douglas Stebila] *) Add initial support for RFC 4279 PSK TLS ciphersuites. Add members for the psk identity [hint] and the psk callback functions to the SSL_SESSION, SSL and SSL_CTX structure. New ciphersuites: PSK-RC4-SHA, PSK-3DES-EDE-CBC-SHA, PSK-AES128-CBC-SHA, PSK-AES256-CBC-SHA New functions: SSL_CTX_use_psk_identity_hint SSL_get_psk_identity_hint SSL_get_psk_identity SSL_use_psk_identity_hint [Mika Kousa and Pasi Eronen of Nokia Corporation] *) Add RFC 3161 compliant time stamp request creation, response generation and response verification functionality. [Zoltán Glózik , The OpenTSA Project] *) Add initial support for TLS extensions, specifically for the server_name extension so far. The SSL_SESSION, SSL_CTX, and SSL data structures now have new members for a host name. The SSL data structure has an additional member SSL_CTX *initial_ctx so that new sessions can be stored in that context to allow for session resumption, even after the SSL has been switched to a new SSL_CTX in reaction to a client's server_name extension. New functions (subject to change): SSL_get_servername() SSL_get_servername_type() SSL_set_SSL_CTX() New CTRL codes and macros (subject to change): SSL_CTRL_SET_TLSEXT_SERVERNAME_CB - SSL_CTX_set_tlsext_servername_callback() SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG - SSL_CTX_set_tlsext_servername_arg() SSL_CTRL_SET_TLSEXT_HOSTNAME - SSL_set_tlsext_host_name() openssl s_client has a new '-servername ...' option. openssl s_server has new options '-servername_host ...', '-cert2 ...', '-key2 ...', '-servername_fatal' (subject to change). This allows testing the HostName extension for a specific single host name ('-cert' and '-key' remain fallbacks for handshakes without HostName negotiation). If the unrecogninzed_name alert has to be sent, this by default is a warning; it becomes fatal with the '-servername_fatal' option. [Peter Sylvester, Remy Allais, Christophe Renou] *) Whirlpool hash implementation is added. [Andy Polyakov] *) BIGNUM code on 64-bit SPARCv9 targets is switched from bn(64,64) to bn(64,32). Because of instruction set limitations it doesn't have any negative impact on performance. This was done mostly in order to make it possible to share assembler modules, such as bn_mul_mont implementations, between 32- and 64-bit builds without hassle. [Andy Polyakov] *) Move code previously exiled into file crypto/ec/ec2_smpt.c to ec2_smpl.c, and no longer require the OPENSSL_EC_BIN_PT_COMP macro. [Bodo Moeller] *) New candidate for BIGNUM assembler implementation, bn_mul_mont, dedicated Montgomery multiplication procedure, is introduced. BN_MONT_CTX is modified to allow bn_mul_mont to reach for higher "64-bit" performance on certain 32-bit targets. [Andy Polyakov] *) New option SSL_OP_NO_COMP to disable use of compression selectively in SSL structures. New SSL ctrl to set maximum send fragment size. Save memory by seeting the I/O buffer sizes dynamically instead of using the maximum available value. [Steve Henson] *) New option -V for 'openssl ciphers'. This prints the ciphersuite code in addition to the text details. [Bodo Moeller] *) Very, very preliminary EXPERIMENTAL support for printing of general ASN1 structures. This currently produces rather ugly output and doesn't handle several customised structures at all. [Steve Henson] *) Integrated support for PVK file format and some related formats such as MS PUBLICKEYBLOB and PRIVATEKEYBLOB. Command line switches to support these in the 'rsa' and 'dsa' utilities. [Steve Henson] *) Support for PKCS#1 RSAPublicKey format on rsa utility command line. [Steve Henson] *) Remove the ancient ASN1_METHOD code. This was only ever used in one place for the (very old) "NETSCAPE" format certificates which are now handled using new ASN1 code equivalents. [Steve Henson] *) Let the TLSv1_method() etc. functions return a 'const' SSL_METHOD pointer and make the SSL_METHOD parameter in SSL_CTX_new, SSL_CTX_set_ssl_version and SSL_set_ssl_method 'const'. [Nils Larsch] *) Modify CRL distribution points extension code to print out previously unsupported fields. Enhance extension setting code to allow setting of all fields. [Steve Henson] *) Add print and set support for Issuing Distribution Point CRL extension. [Steve Henson] *) Change 'Configure' script to enable Camellia by default. [NTT] Changes between 0.9.8m and 0.9.8n [24 Mar 2010] *) When rejecting SSL/TLS records due to an incorrect version number, never update s->server with a new major version number. As of - OpenSSL 0.9.8m if 'short' is a 16-bit type, - OpenSSL 0.9.8f if 'short' is longer than 16 bits, the previous behavior could result in a read attempt at NULL when receiving specific incorrect SSL/TLS records once record payload protection is active. (CVE-2010-0740) [Bodo Moeller, Adam Langley ] *) Fix for CVE-2010-0433 where some kerberos enabled versions of OpenSSL could be crashed if the relevant tables were not present (e.g. chrooted). [Tomas Hoger ] Changes between 0.9.8l and 0.9.8m [25 Feb 2010] *) Always check bn_wexpend() return values for failure. (CVE-2009-3245) [Martin Olsson, Neel Mehta] *) Fix X509_STORE locking: Every 'objs' access requires a lock (to accommodate for stack sorting, always a write lock!). [Bodo Moeller] *) On some versions of WIN32 Heap32Next is very slow. This can cause excessive delays in the RAND_poll(): over a minute. As a workaround include a time check in the inner Heap32Next loop too. [Steve Henson] *) The code that handled flushing of data in SSL/TLS originally used the BIO_CTRL_INFO ctrl to see if any data was pending first. This caused the problem outlined in PR#1949. The fix suggested there however can trigger problems with buggy BIO_CTRL_WPENDING (e.g. some versions of Apache). So instead simplify the code to flush unconditionally. This should be fine since flushing with no data to flush is a no op. [Steve Henson] *) Handle TLS versions 2.0 and later properly and correctly use the highest version of TLS/SSL supported. Although TLS >= 2.0 is some way off ancient servers have a habit of sticking around for a while... [Steve Henson] *) Modify compression code so it frees up structures without using the ex_data callbacks. This works around a problem where some applications call CRYPTO_cleanup_all_ex_data() before application exit (e.g. when restarting) then use compression (e.g. SSL with compression) later. This results in significant per-connection memory leaks and has caused some security issues including CVE-2008-1678 and CVE-2009-4355. [Steve Henson] *) Constify crypto/cast (i.e., ): a CAST_KEY doesn't change when encrypting or decrypting. [Bodo Moeller] *) Add option SSL_OP_LEGACY_SERVER_CONNECT which will allow clients to connect and renegotiate with servers which do not support RI. Until RI is more widely deployed this option is enabled by default. [Steve Henson] *) Add "missing" ssl ctrls to clear options and mode. [Steve Henson] *) If client attempts to renegotiate and doesn't support RI respond with a no_renegotiation alert as required by RFC5746. Some renegotiating TLS clients will continue a connection gracefully when they receive the alert. Unfortunately OpenSSL mishandled this alert and would hang waiting for a server hello which it will never receive. Now we treat a received no_renegotiation alert as a fatal error. This is because applications requesting a renegotiation might well expect it to succeed and would have no code in place to handle the server denying it so the only safe thing to do is to terminate the connection. [Steve Henson] *) Add ctrl macro SSL_get_secure_renegotiation_support() which returns 1 if peer supports secure renegotiation and 0 otherwise. Print out peer renegotiation support in s_client/s_server. [Steve Henson] *) Replace the highly broken and deprecated SPKAC certification method with the updated NID creation version. This should correctly handle UTF8. [Steve Henson] *) Implement RFC5746. Re-enable renegotiation but require the extension as needed. Unfortunately, SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION turns out to be a bad idea. It has been replaced by SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION which can be set with SSL_CTX_set_options(). This is really not recommended unless you know what you are doing. [Eric Rescorla , Ben Laurie, Steve Henson] *) Fixes to stateless session resumption handling. Use initial_ctx when issuing and attempting to decrypt tickets in case it has changed during servername handling. Use a non-zero length session ID when attempting stateless session resumption: this makes it possible to determine if a resumption has occurred immediately after receiving server hello (several places in OpenSSL subtly assume this) instead of later in the handshake. [Steve Henson] *) The functions ENGINE_ctrl(), OPENSSL_isservice(), CMS_get1_RecipientRequest() and RAND_bytes() can return <=0 on error fixes for a few places where the return code is not checked correctly. [Julia Lawall ] *) Add --strict-warnings option to Configure script to include devteam warnings in other configurations. [Steve Henson] *) Add support for --libdir option and LIBDIR variable in makefiles. This makes it possible to install openssl libraries in locations which have names other than "lib", for example "/usr/lib64" which some systems need. [Steve Henson, based on patch from Jeremy Utley] *) Don't allow the use of leading 0x80 in OIDs. This is a violation of X690 8.9.12 and can produce some misleading textual output of OIDs. [Steve Henson, reported by Dan Kaminsky] *) Delete MD2 from algorithm tables. This follows the recommendation in several standards that it is not used in new applications due to several cryptographic weaknesses. For binary compatibility reasons the MD2 API is still compiled in by default. [Steve Henson] *) Add compression id to {d2i,i2d}_SSL_SESSION so it is correctly saved and restored. [Steve Henson] *) Rename uni2asc and asc2uni functions to OPENSSL_uni2asc and OPENSSL_asc2uni conditionally on Netware platforms to avoid a name clash. [Guenter ] *) Fix the server certificate chain building code to use X509_verify_cert(), it used to have an ad-hoc builder which was unable to cope with anything other than a simple chain. [David Woodhouse , Steve Henson] *) Don't check self signed certificate signatures in X509_verify_cert() by default (a flag can override this): it just wastes time without adding any security. As a useful side effect self signed root CAs with non-FIPS digests are now usable in FIPS mode. [Steve Henson] *) In dtls1_process_out_of_seq_message() the check if the current message is already buffered was missing. For every new message was memory allocated, allowing an attacker to perform an denial of service attack with sending out of seq handshake messages until there is no memory left. Additionally every future messege was buffered, even if the sequence number made no sense and would be part of another handshake. So only messages with sequence numbers less than 10 in advance will be buffered. (CVE-2009-1378) [Robin Seggelmann, discovered by Daniel Mentz] *) Records are buffered if they arrive with a future epoch to be processed after finishing the corresponding handshake. There is currently no limitation to this buffer allowing an attacker to perform a DOS attack with sending records with future epochs until there is no memory left. This patch adds the pqueue_size() function to detemine the size of a buffer and limits the record buffer to 100 entries. (CVE-2009-1377) [Robin Seggelmann, discovered by Daniel Mentz] *) Keep a copy of frag->msg_header.frag_len so it can be used after the parent structure is freed. (CVE-2009-1379) [Daniel Mentz] *) Handle non-blocking I/O properly in SSL_shutdown() call. [Darryl Miles ] *) Add 2.5.4.* OIDs [Ilya O. ] Changes between 0.9.8k and 0.9.8l [5 Nov 2009] *) Disable renegotiation completely - this fixes a severe security problem (CVE-2009-3555) at the cost of breaking all renegotiation. Renegotiation can be re-enabled by setting SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION in s3->flags at run-time. This is really not recommended unless you know what you're doing. [Ben Laurie] Changes between 0.9.8j and 0.9.8k [25 Mar 2009] *) Don't set val to NULL when freeing up structures, it is freed up by underlying code. If sizeof(void *) > sizeof(long) this can result in zeroing past the valid field. (CVE-2009-0789) [Paolo Ganci ] *) Fix bug where return value of CMS_SignerInfo_verify_content() was not checked correctly. This would allow some invalid signed attributes to appear to verify correctly. (CVE-2009-0591) [Ivan Nestlerode ] *) Reject UniversalString and BMPString types with invalid lengths. This prevents a crash in ASN1_STRING_print_ex() which assumes the strings have a legal length. (CVE-2009-0590) [Steve Henson] *) Set S/MIME signing as the default purpose rather than setting it unconditionally. This allows applications to override it at the store level. [Steve Henson] *) Permit restricted recursion of ASN1 strings. This is needed in practice to handle some structures. [Steve Henson] *) Improve efficiency of mem_gets: don't search whole buffer each time for a '\n' [Jeremy Shapiro ] *) New -hex option for openssl rand. [Matthieu Herrb] *) Print out UTF8String and NumericString when parsing ASN1. [Steve Henson] *) Support NumericString type for name components. [Steve Henson] *) Allow CC in the environment to override the automatically chosen compiler. Note that nothing is done to ensure flags work with the chosen compiler. [Ben Laurie] Changes between 0.9.8i and 0.9.8j [07 Jan 2009] *) Properly check EVP_VerifyFinal() and similar return values (CVE-2008-5077). [Ben Laurie, Bodo Moeller, Google Security Team] *) Enable TLS extensions by default. [Ben Laurie] *) Allow the CHIL engine to be loaded, whether the application is multithreaded or not. (This does not release the developer from the obligation to set up the dynamic locking callbacks.) [Sander Temme ] *) Use correct exit code if there is an error in dgst command. [Steve Henson; problem pointed out by Roland Dirlewanger] *) Tweak Configure so that you need to say "experimental-jpake" to enable JPAKE, and need to use -DOPENSSL_EXPERIMENTAL_JPAKE in applications. [Bodo Moeller] *) Add experimental JPAKE support, including demo authentication in s_client and s_server. [Ben Laurie] *) Set the comparison function in v3_addr_canonize(). [Rob Austein ] *) Add support for XMPP STARTTLS in s_client. [Philip Paeps ] *) Change the server-side SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG behavior to ensure that even with this option, only ciphersuites in the server's preference list will be accepted. (Note that the option applies only when resuming a session, so the earlier behavior was just about the algorithm choice for symmetric cryptography.) [Bodo Moeller] Changes between 0.9.8h and 0.9.8i [15 Sep 2008] *) Fix NULL pointer dereference if a DTLS server received ChangeCipherSpec as first record (CVE-2009-1386). [PR #1679] *) Fix a state transitition in s3_srvr.c and d1_srvr.c (was using SSL3_ST_CW_CLNT_HELLO_B, should be ..._ST_SW_SRVR_...). [Nagendra Modadugu] *) The fix in 0.9.8c that supposedly got rid of unsafe double-checked locking was incomplete for RSA blinding, addressing just one layer of what turns out to have been doubly unsafe triple-checked locking. So now fix this for real by retiring the MONT_HELPER macro in crypto/rsa/rsa_eay.c. [Bodo Moeller; problem pointed out by Marius Schilder] *) Various precautionary measures: - Avoid size_t integer overflow in HASH_UPDATE (md32_common.h). - Avoid a buffer overflow in d2i_SSL_SESSION() (ssl_asn1.c). (NB: This would require knowledge of the secret session ticket key to exploit, in which case you'd be SOL either way.) - Change bn_nist.c so that it will properly handle input BIGNUMs outside the expected range. - Enforce the 'num' check in BN_div() (bn_div.c) for non-BN_DEBUG builds. [Neel Mehta, Bodo Moeller] *) Allow engines to be "soft loaded" - i.e. optionally don't die if the load fails. Useful for distros. [Ben Laurie and the FreeBSD team] *) Add support for Local Machine Keyset attribute in PKCS#12 files. [Steve Henson] *) Fix BN_GF2m_mod_arr() top-bit cleanup code. [Huang Ying] *) Expand ENGINE to support engine supplied SSL client certificate functions. This work was sponsored by Logica. [Steve Henson] *) Add CryptoAPI ENGINE to support use of RSA and DSA keys held in Windows keystores. Support for SSL/TLS client authentication too. Not compiled unless enable-capieng specified to Configure. This work was sponsored by Logica. [Steve Henson] *) Fix bug in X509_ATTRIBUTE creation: dont set attribute using ASN1_TYPE_set1 if MBSTRING flag set. This bug would crash certain attribute creation routines such as certifcate requests and PKCS#12 files. [Steve Henson] Changes between 0.9.8g and 0.9.8h [28 May 2008] *) Fix flaw if 'Server Key exchange message' is omitted from a TLS handshake which could lead to a cilent crash as found using the Codenomicon TLS test suite (CVE-2008-1672) [Steve Henson, Mark Cox] *) Fix double free in TLS server name extensions which could lead to a remote crash found by Codenomicon TLS test suite (CVE-2008-0891) [Joe Orton] *) Clear error queue in SSL_CTX_use_certificate_chain_file() Clear the error queue to ensure that error entries left from older function calls do not interfere with the correct operation. [Lutz Jaenicke, Erik de Castro Lopo] *) Remove root CA certificates of commercial CAs: The OpenSSL project does not recommend any specific CA and does not have any policy with respect to including or excluding any CA. Therefore it does not make any sense to ship an arbitrary selection of root CA certificates with the OpenSSL software. [Lutz Jaenicke] *) RSA OAEP patches to fix two separate invalid memory reads. The first one involves inputs when 'lzero' is greater than 'SHA_DIGEST_LENGTH' (it would read about SHA_DIGEST_LENGTH bytes before the beginning of from). The second one involves inputs where the 'db' section contains nothing but zeroes (there is a one-byte invalid read after the end of 'db'). [Ivan Nestlerode ] *) Partial backport from 0.9.9-dev: Introduce bn_mul_mont (dedicated Montgomery multiplication procedure) as a candidate for BIGNUM assembler implementation. While 0.9.9-dev uses assembler for various architectures, only x86_64 is available by default here in the 0.9.8 branch, and 32-bit x86 is available through a compile-time setting. To try the 32-bit x86 assembler implementation, use Configure option "enable-montasm" (which exists only for this backport). As "enable-montasm" for 32-bit x86 disclaims code stability anyway, in this constellation we activate additional code backported from 0.9.9-dev for further performance improvements, namely BN_from_montgomery_word. (To enable this otherwise, e.g. x86_64, try "-DMONT_FROM_WORD___NON_DEFAULT_0_9_8_BUILD".) [Andy Polyakov (backport partially by Bodo Moeller)] *) Add TLS session ticket callback. This allows an application to set TLS ticket cipher and HMAC keys rather than relying on hardcoded fixed values. This is useful for key rollover for example where several key sets may exist with different names. [Steve Henson] *) Reverse ENGINE-internal logic for caching default ENGINE handles. This was broken until now in 0.9.8 releases, such that the only way a registered ENGINE could be used (assuming it initialises successfully on the host) was to explicitly set it as the default for the relevant algorithms. This is in contradiction with 0.9.7 behaviour and the documentation. With this fix, when an ENGINE is registered into a given algorithm's table of implementations, the 'uptodate' flag is reset so that auto-discovery will be used next time a new context for that algorithm attempts to select an implementation. [Ian Lister (tweaked by Geoff Thorpe)] *) Backport of CMS code to OpenSSL 0.9.8. This differs from the 0.9.9 implemention in the following ways: Lack of EVP_PKEY_ASN1_METHOD means algorithm parameters have to be hard coded. Lack of BER streaming support means one pass streaming processing is only supported if data is detached: setting the streaming flag is ignored for embedded content. CMS support is disabled by default and must be explicitly enabled with the enable-cms configuration option. [Steve Henson] *) Update the GMP engine glue to do direct copies between BIGNUM and mpz_t when openssl and GMP use the same limb size. Otherwise the existing "conversion via a text string export" trick is still used. [Paul Sheer ] *) Zlib compression BIO. This is a filter BIO which compressed and uncompresses any data passed through it. [Steve Henson] *) Add AES_wrap_key() and AES_unwrap_key() functions to implement RFC3394 compatible AES key wrapping. [Steve Henson] *) Add utility functions to handle ASN1 structures. ASN1_STRING_set0(): sets string data without copying. X509_ALGOR_set0() and X509_ALGOR_get0(): set and retrieve X509_ALGOR (AlgorithmIdentifier) data. Attribute function X509at_get0_data_by_OBJ(): retrieves data from an X509_ATTRIBUTE structure optionally checking it occurs only once. ASN1_TYPE_set1(): set and ASN1_TYPE structure copying supplied data. [Steve Henson] *) Fix BN flag handling in RSA_eay_mod_exp() and BN_MONT_CTX_set() to get the expected BN_FLG_CONSTTIME behavior. [Bodo Moeller (Google)] *) Netware support: - fixed wrong usage of ioctlsocket() when build for LIBC BSD sockets - fixed do_tests.pl to run the test suite with CLIB builds too (CLIB_OPT) - added some more tests to do_tests.pl - fixed RunningProcess usage so that it works with newer LIBC NDKs too - removed usage of BN_LLONG for CLIB builds to avoid runtime dependency - added new Configure targets netware-clib-bsdsock, netware-clib-gcc, netware-clib-bsdsock-gcc, netware-libc-bsdsock-gcc - various changes to netware.pl to enable gcc-cross builds on Win32 platform - changed crypto/bio/b_sock.c to work with macro functions (CLIB BSD) - various changes to fix missing prototype warnings - fixed x86nasm.pl to create correct asm files for NASM COFF output - added AES, WHIRLPOOL and CPUID assembler code to build files - added missing AES assembler make rules to mk1mf.pl - fixed order of includes in apps/ocsp.c so that e_os.h settings apply [Guenter Knauf ] *) Implement certificate status request TLS extension defined in RFC3546. A client can set the appropriate parameters and receive the encoded OCSP response via a callback. A server can query the supplied parameters and set the encoded OCSP response in the callback. Add simplified examples to s_client and s_server. [Steve Henson] Changes between 0.9.8f and 0.9.8g [19 Oct 2007] *) Fix various bugs: + Binary incompatibility of ssl_ctx_st structure + DTLS interoperation with non-compliant servers + Don't call get_session_cb() without proposed session + Fix ia64 assembler code [Andy Polyakov, Steve Henson] Changes between 0.9.8e and 0.9.8f [11 Oct 2007] *) DTLS Handshake overhaul. There were longstanding issues with OpenSSL DTLS implementation, which were making it impossible for RFC 4347 compliant client to communicate with OpenSSL server. Unfortunately just fixing these incompatibilities would "cut off" pre-0.9.8f clients. To allow for hassle free upgrade post-0.9.8e server keeps tolerating non RFC compliant syntax. The opposite is not true, 0.9.8f client can not communicate with earlier server. This update even addresses CVE-2007-4995. [Andy Polyakov] *) Changes to avoid need for function casts in OpenSSL: some compilers (gcc 4.2 and later) reject their use. [Kurt Roeckx , Peter Hartley , Steve Henson] *) Add RFC4507 support to OpenSSL. This includes the corrections in RFC4507bis. The encrypted ticket format is an encrypted encoded SSL_SESSION structure, that way new session features are automatically supported. If a client application caches session in an SSL_SESSION structure support is transparent because tickets are now stored in the encoded SSL_SESSION. The SSL_CTX structure automatically generates keys for ticket protection in servers so again support should be possible with no application modification. If a client or server wishes to disable RFC4507 support then the option SSL_OP_NO_TICKET can be set. Add a TLS extension debugging callback to allow the contents of any client or server extensions to be examined. This work was sponsored by Google. [Steve Henson] *) Add initial support for TLS extensions, specifically for the server_name extension so far. The SSL_SESSION, SSL_CTX, and SSL data structures now have new members for a host name. The SSL data structure has an additional member SSL_CTX *initial_ctx so that new sessions can be stored in that context to allow for session resumption, even after the SSL has been switched to a new SSL_CTX in reaction to a client's server_name extension. New functions (subject to change): SSL_get_servername() SSL_get_servername_type() SSL_set_SSL_CTX() New CTRL codes and macros (subject to change): SSL_CTRL_SET_TLSEXT_SERVERNAME_CB - SSL_CTX_set_tlsext_servername_callback() SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG - SSL_CTX_set_tlsext_servername_arg() SSL_CTRL_SET_TLSEXT_HOSTNAME - SSL_set_tlsext_host_name() openssl s_client has a new '-servername ...' option. openssl s_server has new options '-servername_host ...', '-cert2 ...', '-key2 ...', '-servername_fatal' (subject to change). This allows testing the HostName extension for a specific single host name ('-cert' and '-key' remain fallbacks for handshakes without HostName negotiation). If the unrecogninzed_name alert has to be sent, this by default is a warning; it becomes fatal with the '-servername_fatal' option. [Peter Sylvester, Remy Allais, Christophe Renou, Steve Henson] *) Add AES and SSE2 assembly language support to VC++ build. [Steve Henson] *) Mitigate attack on final subtraction in Montgomery reduction. [Andy Polyakov] *) Fix crypto/ec/ec_mult.c to work properly with scalars of value 0 (which previously caused an internal error). [Bodo Moeller] *) Squeeze another 10% out of IGE mode when in != out. [Ben Laurie] *) AES IGE mode speedup. [Dean Gaudet (Google)] *) Add the Korean symmetric 128-bit cipher SEED (see http://www.kisa.or.kr/kisa/seed/jsp/seed_eng.jsp) and add SEED ciphersuites from RFC 4162: TLS_RSA_WITH_SEED_CBC_SHA = "SEED-SHA" TLS_DHE_DSS_WITH_SEED_CBC_SHA = "DHE-DSS-SEED-SHA" TLS_DHE_RSA_WITH_SEED_CBC_SHA = "DHE-RSA-SEED-SHA" TLS_DH_anon_WITH_SEED_CBC_SHA = "ADH-SEED-SHA" To minimize changes between patchlevels in the OpenSSL 0.9.8 series, SEED remains excluded from compilation unless OpenSSL is configured with 'enable-seed'. [KISA, Bodo Moeller] *) Mitigate branch prediction attacks, which can be practical if a single processor is shared, allowing a spy process to extract information. For detailed background information, see http://eprint.iacr.org/2007/039 (O. Aciicmez, S. Gueron, J.-P. Seifert, "New Branch Prediction Vulnerabilities in OpenSSL and Necessary Software Countermeasures"). The core of the change are new versions BN_div_no_branch() and BN_mod_inverse_no_branch() of BN_div() and BN_mod_inverse(), respectively, which are slower, but avoid the security-relevant conditional branches. These are automatically called by BN_div() and BN_mod_inverse() if the flag BN_FLG_CONSTTIME is set for one of the input BIGNUMs. Also, BN_is_bit_set() has been changed to remove a conditional branch. BN_FLG_CONSTTIME is the new name for the previous BN_FLG_EXP_CONSTTIME flag, since it now affects more than just modular exponentiation. (Since OpenSSL 0.9.7h, setting this flag in the exponent causes BN_mod_exp_mont() to use the alternative implementation in BN_mod_exp_mont_consttime().) The old name remains as a deprecated alias. Similary, RSA_FLAG_NO_EXP_CONSTTIME is replaced by a more general RSA_FLAG_NO_CONSTTIME flag since the RSA implementation now uses constant-time implementations for more than just exponentiation. Here too the old name is kept as a deprecated alias. BN_BLINDING_new() will now use BN_dup() for the modulus so that the BN_BLINDING structure gets an independent copy of the modulus. This means that the previous "BIGNUM *m" argument to BN_BLINDING_new() and to BN_BLINDING_create_param() now essentially becomes "const BIGNUM *m", although we can't actually change this in the header file before 0.9.9. It allows RSA_setup_blinding() to use BN_with_flags() on the modulus to enable BN_FLG_CONSTTIME. [Matthew D Wood (Intel Corp)] *) In the SSL/TLS server implementation, be strict about session ID context matching (which matters if an application uses a single external cache for different purposes). Previously, out-of-context reuse was forbidden only if SSL_VERIFY_PEER was set. This did ensure strict client verification, but meant that, with applications using a single external cache for quite different requirements, clients could circumvent ciphersuite restrictions for a given session ID context by starting a session in a different context. [Bodo Moeller] *) Include "!eNULL" in SSL_DEFAULT_CIPHER_LIST to make sure that a ciphersuite string such as "DEFAULT:RSA" cannot enable authentication-only ciphersuites. [Bodo Moeller] *) Update the SSL_get_shared_ciphers() fix CVE-2006-3738 which was not complete and could lead to a possible single byte overflow (CVE-2007-5135) [Ben Laurie] Changes between 0.9.8d and 0.9.8e [23 Feb 2007] *) Since AES128 and AES256 (and similarly Camellia128 and Camellia256) share a single mask bit in the logic of ssl/ssl_ciph.c, the code for masking out disabled ciphers needs a kludge to work properly if AES128 is available and AES256 isn't (or if Camellia128 is available and Camellia256 isn't). [Victor Duchovni] *) Fix the BIT STRING encoding generated by crypto/ec/ec_asn1.c (within i2d_ECPrivateKey, i2d_ECPKParameters, i2d_ECParameters): When a point or a seed is encoded in a BIT STRING, we need to prevent the removal of trailing zero bits to get the proper DER encoding. (By default, crypto/asn1/a_bitstr.c assumes the case of a NamedBitList, for which trailing 0 bits need to be removed.) [Bodo Moeller] *) Have SSL/TLS server implementation tolerate "mismatched" record protocol version while receiving ClientHello even if the ClientHello is fragmented. (The server can't insist on the particular protocol version it has chosen before the ServerHello message has informed the client about his choice.) [Bodo Moeller] *) Add RFC 3779 support. [Rob Austein for ARIN, Ben Laurie] *) Load error codes if they are not already present instead of using a static variable. This allows them to be cleanly unloaded and reloaded. Improve header file function name parsing. [Steve Henson] *) extend SMTP and IMAP protocol emulation in s_client to use EHLO or CAPABILITY handshake as required by RFCs. [Goetz Babin-Ebell] Changes between 0.9.8c and 0.9.8d [28 Sep 2006] *) Introduce limits to prevent malicious keys being able to cause a denial of service. (CVE-2006-2940) [Steve Henson, Bodo Moeller] *) Fix ASN.1 parsing of certain invalid structures that can result in a denial of service. (CVE-2006-2937) [Steve Henson] *) Fix buffer overflow in SSL_get_shared_ciphers() function. (CVE-2006-3738) [Tavis Ormandy and Will Drewry, Google Security Team] *) Fix SSL client code which could crash if connecting to a malicious SSLv2 server. (CVE-2006-4343) [Tavis Ormandy and Will Drewry, Google Security Team] *) Since 0.9.8b, ciphersuite strings naming explicit ciphersuites match only those. Before that, "AES256-SHA" would be interpreted as a pattern and match "AES128-SHA" too (since AES128-SHA got the same strength classification in 0.9.7h) as we currently only have a single AES bit in the ciphersuite description bitmap. That change, however, also applied to ciphersuite strings such as "RC4-MD5" that intentionally matched multiple ciphersuites -- namely, SSL 2.0 ciphersuites in addition to the more common ones from SSL 3.0/TLS 1.0. So we change the selection algorithm again: Naming an explicit ciphersuite selects this one ciphersuite, and any other similar ciphersuite (same bitmap) from *other* protocol versions. Thus, "RC4-MD5" again will properly select both the SSL 2.0 ciphersuite and the SSL 3.0/TLS 1.0 ciphersuite. Since SSL 2.0 does not have any ciphersuites for which the 128/256 bit distinction would be relevant, this works for now. The proper fix will be to use different bits for AES128 and AES256, which would have avoided the problems from the beginning; however, bits are scarce, so we can only do this in a new release (not just a patchlevel) when we can change the SSL_CIPHER definition to split the single 'unsigned long mask' bitmap into multiple values to extend the available space. [Bodo Moeller] Changes between 0.9.8b and 0.9.8c [05 Sep 2006] *) Avoid PKCS #1 v1.5 signature attack discovered by Daniel Bleichenbacher (CVE-2006-4339) [Ben Laurie and Google Security Team] *) Add AES IGE and biIGE modes. [Ben Laurie] *) Change the Unix randomness entropy gathering to use poll() when possible instead of select(), since the latter has some undesirable limitations. [Darryl Miles via Richard Levitte and Bodo Moeller] *) Disable "ECCdraft" ciphersuites more thoroughly. Now special treatment in ssl/ssl_ciph.s makes sure that these ciphersuites cannot be implicitly activated as part of, e.g., the "AES" alias. However, please upgrade to OpenSSL 0.9.9[-dev] for non-experimental use of the ECC ciphersuites to get TLS extension support, which is required for curve and point format negotiation to avoid potential handshake problems. [Bodo Moeller] *) Disable rogue ciphersuites: - SSLv2 0x08 0x00 0x80 ("RC4-64-MD5") - SSLv3/TLSv1 0x00 0x61 ("EXP1024-RC2-CBC-MD5") - SSLv3/TLSv1 0x00 0x60 ("EXP1024-RC4-MD5") The latter two were purportedly from draft-ietf-tls-56-bit-ciphersuites-0[01].txt, but do not really appear there. Also deactivate the remaining ciphersuites from draft-ietf-tls-56-bit-ciphersuites-01.txt. These are just as unofficial, and the ID has long expired. [Bodo Moeller] *) Fix RSA blinding Heisenbug (problems sometimes occured on dual-core machines) and other potential thread-safety issues. [Bodo Moeller] *) Add the symmetric cipher Camellia (128-bit, 192-bit, 256-bit key versions), which is now available for royalty-free use (see http://info.isl.ntt.co.jp/crypt/eng/info/chiteki.html). Also, add Camellia TLS ciphersuites from RFC 4132. To minimize changes between patchlevels in the OpenSSL 0.9.8 series, Camellia remains excluded from compilation unless OpenSSL is configured with 'enable-camellia'. [NTT] *) Disable the padding bug check when compression is in use. The padding bug check assumes the first packet is of even length, this is not necessarily true if compresssion is enabled and can result in false positives causing handshake failure. The actual bug test is ancient code so it is hoped that implementations will either have fixed it by now or any which still have the bug do not support compression. [Steve Henson] Changes between 0.9.8a and 0.9.8b [04 May 2006] *) When applying a cipher rule check to see if string match is an explicit cipher suite and only match that one cipher suite if it is. [Steve Henson] *) Link in manifests for VC++ if needed. [Austin Ziegler ] *) Update support for ECC-based TLS ciphersuites according to draft-ietf-tls-ecc-12.txt with proposed changes (but without TLS extensions, which are supported starting with the 0.9.9 branch, not in the OpenSSL 0.9.8 branch). [Douglas Stebila] *) New functions EVP_CIPHER_CTX_new() and EVP_CIPHER_CTX_free() to support opaque EVP_CIPHER_CTX handling. [Steve Henson] *) Fixes and enhancements to zlib compression code. We now only use "zlib1.dll" and use the default __cdecl calling convention on Win32 to conform with the standards mentioned here: http://www.zlib.net/DLL_FAQ.txt Static zlib linking now works on Windows and the new --with-zlib-include --with-zlib-lib options to Configure can be used to supply the location of the headers and library. Gracefully handle case where zlib library can't be loaded. [Steve Henson] *) Several fixes and enhancements to the OID generation code. The old code sometimes allowed invalid OIDs (1.X for X >= 40 for example), couldn't handle numbers larger than ULONG_MAX, truncated printing and had a non standard OBJ_obj2txt() behaviour. [Steve Henson] *) Add support for building of engines under engine/ as shared libraries under VC++ build system. [Steve Henson] *) Corrected the numerous bugs in the Win32 path splitter in DSO. Hopefully, we will not see any false combination of paths any more. [Richard Levitte] Changes between 0.9.8 and 0.9.8a [11 Oct 2005] *) Remove the functionality of SSL_OP_MSIE_SSLV2_RSA_PADDING (part of SSL_OP_ALL). This option used to disable the countermeasure against man-in-the-middle protocol-version rollback in the SSL 2.0 server implementation, which is a bad idea. (CVE-2005-2969) [Bodo Moeller; problem pointed out by Yutaka Oiwa (Research Center for Information Security, National Institute of Advanced Industrial Science and Technology [AIST], Japan)] *) Add two function to clear and return the verify parameter flags. [Steve Henson] *) Keep cipherlists sorted in the source instead of sorting them at runtime, thus removing the need for a lock. [Nils Larsch] *) Avoid some small subgroup attacks in Diffie-Hellman. [Nick Mathewson and Ben Laurie] *) Add functions for well-known primes. [Nick Mathewson] *) Extended Windows CE support. [Satoshi Nakamura and Andy Polyakov] *) Initialize SSL_METHOD structures at compile time instead of during runtime, thus removing the need for a lock. [Steve Henson] *) Make PKCS7_decrypt() work even if no certificate is supplied by attempting to decrypt each encrypted key in turn. Add support to smime utility. [Steve Henson] Changes between 0.9.7h and 0.9.8 [05 Jul 2005] [NB: OpenSSL 0.9.7i and later 0.9.7 patch levels were released after OpenSSL 0.9.8.] *) Add libcrypto.pc and libssl.pc for those who feel they need them. [Richard Levitte] *) Change CA.sh and CA.pl so they don't bundle the CSR and the private key into the same file any more. [Richard Levitte] *) Add initial support for Win64, both IA64 and AMD64/x64 flavors. [Andy Polyakov] *) Add -utf8 command line and config file option to 'ca'. [Stefan and Geoff Thorpe] *) Add attribute functions to EVP_PKEY structure. Modify PKCS12_create() to recognize a CSP name attribute and use it. Make -CSP option work again in pkcs12 utility. [Steve Henson] *) Add new functionality to the bn blinding code: - automatic re-creation of the BN_BLINDING parameters after a fixed number of uses (currently 32) - add new function for parameter creation - introduce flags to control the update behaviour of the BN_BLINDING parameters - hide BN_BLINDING structure Add a second BN_BLINDING slot to the RSA structure to improve performance when a single RSA object is shared among several threads. [Nils Larsch] *) Add support for DTLS. [Nagendra Modadugu and Ben Laurie] *) Add support for DER encoded private keys (SSL_FILETYPE_ASN1) to SSL_CTX_use_PrivateKey_file() and SSL_use_PrivateKey_file() [Walter Goulet] *) Remove buggy and incompletet DH cert support from ssl/ssl_rsa.c and ssl/s3_both.c [Nils Larsch] *) Use SHA-1 instead of MD5 as the default digest algorithm for the apps/openssl applications. [Nils Larsch] *) Compile clean with "-Wall -Wmissing-prototypes -Wstrict-prototypes -Wmissing-declarations -Werror". Currently DEBUG_SAFESTACK must also be set. [Ben Laurie] *) Change ./Configure so that certain algorithms can be disabled by default. The new counterpiece to "no-xxx" is "enable-xxx". The patented RC5 and MDC2 algorithms will now be disabled unless "enable-rc5" and "enable-mdc2", respectively, are specified. (IDEA remains enabled despite being patented. This is because IDEA is frequently required for interoperability, and there is no license fee for non-commercial use. As before, "no-idea" can be used to avoid this algorithm.) [Bodo Moeller] *) Add processing of proxy certificates (see RFC 3820). This work was sponsored by KTH (The Royal Institute of Technology in Stockholm) and EGEE (Enabling Grids for E-science in Europe). [Richard Levitte] *) RC4 performance overhaul on modern architectures/implementations, such as Intel P4, IA-64 and AMD64. [Andy Polyakov] *) New utility extract-section.pl. This can be used specify an alternative section number in a pod file instead of having to treat each file as a separate case in Makefile. This can be done by adding two lines to the pod file: =for comment openssl_section:XXX The blank line is mandatory. [Steve Henson] *) New arguments -certform, -keyform and -pass for s_client and s_server to allow alternative format key and certificate files and passphrase sources. [Steve Henson] *) New structure X509_VERIFY_PARAM which combines current verify parameters, update associated structures and add various utility functions. Add new policy related verify parameters, include policy checking in standard verify code. Enhance 'smime' application with extra parameters to support policy checking and print out. [Steve Henson] *) Add a new engine to support VIA PadLock ACE extensions in the VIA C3 Nehemiah processors. These extensions support AES encryption in hardware as well as RNG (though RNG support is currently disabled). [Michal Ludvig , with help from Andy Polyakov] *) Deprecate BN_[get|set]_params() functions (they were ignored internally). [Geoff Thorpe] *) New FIPS 180-2 algorithms, SHA-224/-256/-384/-512 are implemented. [Andy Polyakov and a number of other people] *) Improved PowerPC platform support. Most notably BIGNUM assembler implementation contributed by IBM. [Suresh Chari, Peter Waltenberg, Andy Polyakov] *) The new 'RSA_generate_key_ex' function now takes a BIGNUM for the public exponent rather than 'unsigned long'. There is a corresponding change to the new 'rsa_keygen' element of the RSA_METHOD structure. [Jelte Jansen, Geoff Thorpe] *) Functionality for creating the initial serial number file is now moved from CA.pl to the 'ca' utility with a new option -create_serial. (Before OpenSSL 0.9.7e, CA.pl used to initialize the serial number file to 1, which is bound to cause problems. To avoid the problems while respecting compatibility between different 0.9.7 patchlevels, 0.9.7e employed 'openssl x509 -next_serial' in CA.pl for serial number initialization. With the new release 0.9.8, we can fix the problem directly in the 'ca' utility.) [Steve Henson] *) Reduced header interdepencies by declaring more opaque objects in ossl_typ.h. As a consequence, including some headers (eg. engine.h) will give fewer recursive includes, which could break lazy source code - so this change is covered by the OPENSSL_NO_DEPRECATED symbol. As always, developers should define this symbol when building and using openssl to ensure they track the recommended behaviour, interfaces, [etc], but backwards-compatible behaviour prevails when this isn't defined. [Geoff Thorpe] *) New function X509_POLICY_NODE_print() which prints out policy nodes. [Steve Henson] *) Add new EVP function EVP_CIPHER_CTX_rand_key and associated functionality. This will generate a random key of the appropriate length based on the cipher context. The EVP_CIPHER can provide its own random key generation routine to support keys of a specific form. This is used in the des and 3des routines to generate a key of the correct parity. Update S/MIME code to use new functions and hence generate correct parity DES keys. Add EVP_CHECK_DES_KEY #define to return an error if the key is not valid (weak or incorrect parity). [Steve Henson] *) Add a local set of CRLs that can be used by X509_verify_cert() as well as looking them up. This is useful when the verified structure may contain CRLs, for example PKCS#7 signedData. Modify PKCS7_verify() to use any CRLs present unless the new PKCS7_NO_CRL flag is asserted. [Steve Henson] *) Extend ASN1 oid configuration module. It now additionally accepts the syntax: shortName = some long name, 1.2.3.4 [Steve Henson] *) Reimplemented the BN_CTX implementation. There is now no more static limitation on the number of variables it can handle nor the depth of the "stack" handling for BN_CTX_start()/BN_CTX_end() pairs. The stack information can now expand as required, and rather than having a single static array of bignums, BN_CTX now uses a linked-list of such arrays allowing it to expand on demand whilst maintaining the usefulness of BN_CTX's "bundling". [Geoff Thorpe] *) Add a missing BN_CTX parameter to the 'rsa_mod_exp' callback in RSA_METHOD to allow all RSA operations to function using a single BN_CTX. [Geoff Thorpe] *) Preliminary support for certificate policy evaluation and checking. This is initially intended to pass the tests outlined in "Conformance Testing of Relying Party Client Certificate Path Processing Logic" v1.07. [Steve Henson] *) bn_dup_expand() has been deprecated, it was introduced in 0.9.7 and remained unused and not that useful. A variety of other little bignum tweaks and fixes have also been made continuing on from the audit (see below). [Geoff Thorpe] *) Constify all or almost all d2i, c2i, s2i and r2i functions, along with associated ASN1, EVP and SSL functions and old ASN1 macros. [Richard Levitte] *) BN_zero() only needs to set 'top' and 'neg' to zero for correct results, and this should never fail. So the return value from the use of BN_set_word() (which can fail due to needless expansion) is now deprecated; if OPENSSL_NO_DEPRECATED is defined, BN_zero() is a void macro. [Geoff Thorpe] *) BN_CTX_get() should return zero-valued bignums, providing the same initialised value as BN_new(). [Geoff Thorpe, suggested by Ulf Möller] *) Support for inhibitAnyPolicy certificate extension. [Steve Henson] *) An audit of the BIGNUM code is underway, for which debugging code is enabled when BN_DEBUG is defined. This makes stricter enforcements on what is considered valid when processing BIGNUMs, and causes execution to assert() when a problem is discovered. If BN_DEBUG_RAND is defined, further steps are taken to deliberately pollute unused data in BIGNUM structures to try and expose faulty code further on. For now, openssl will (in its default mode of operation) continue to tolerate the inconsistent forms that it has tolerated in the past, but authors and packagers should consider trying openssl and their own applications when compiled with these debugging symbols defined. It will help highlight potential bugs in their own code, and will improve the test coverage for OpenSSL itself. At some point, these tighter rules will become openssl's default to improve maintainability, though the assert()s and other overheads will remain only in debugging configurations. See bn.h for more details. [Geoff Thorpe, Nils Larsch, Ulf Möller] *) BN_CTX_init() has been deprecated, as BN_CTX is an opaque structure that can only be obtained through BN_CTX_new() (which implicitly initialises it). The presence of this function only made it possible to overwrite an existing structure (and cause memory leaks). [Geoff Thorpe] *) Because of the callback-based approach for implementing LHASH as a template type, lh_insert() adds opaque objects to hash-tables and lh_doall() or lh_doall_arg() are typically used with a destructor callback to clean up those corresponding objects before destroying the hash table (and losing the object pointers). So some over-zealous constifications in LHASH have been relaxed so that lh_insert() does not take (nor store) the objects as "const" and the lh_doall[_arg] callback wrappers are not prototyped to have "const" restrictions on the object pointers they are given (and so aren't required to cast them away any more). [Geoff Thorpe] *) The tmdiff.h API was so ugly and minimal that our own timing utility (speed) prefers to use its own implementation. The two implementations haven't been consolidated as yet (volunteers?) but the tmdiff API has had its object type properly exposed (MS_TM) instead of casting to/from "char *". This may still change yet if someone realises MS_TM and "ms_time_***" aren't necessarily the greatest nomenclatures - but this is what was used internally to the implementation so I've used that for now. [Geoff Thorpe] *) Ensure that deprecated functions do not get compiled when OPENSSL_NO_DEPRECATED is defined. Some "openssl" subcommands and a few of the self-tests were still using deprecated key-generation functions so these have been updated also. [Geoff Thorpe] *) Reorganise PKCS#7 code to separate the digest location functionality into PKCS7_find_digest(), digest addtion into PKCS7_bio_add_digest(). New function PKCS7_set_digest() to set the digest type for PKCS#7 digestedData type. Add additional code to correctly generate the digestedData type and add support for this type in PKCS7 initialization functions. [Steve Henson] *) New function PKCS7_set0_type_other() this initializes a PKCS7 structure of type "other". [Steve Henson] *) Fix prime generation loop in crypto/bn/bn_prime.pl by making sure the loop does correctly stop and breaking ("division by zero") modulus operations are not performed. The (pre-generated) prime table crypto/bn/bn_prime.h was already correct, but it could not be re-generated on some platforms because of the "division by zero" situation in the script. [Ralf S. Engelschall] *) Update support for ECC-based TLS ciphersuites according to draft-ietf-tls-ecc-03.txt: the KDF1 key derivation function with SHA-1 now is only used for "small" curves (where the representation of a field element takes up to 24 bytes); for larger curves, the field element resulting from ECDH is directly used as premaster secret. [Douglas Stebila (Sun Microsystems Laboratories)] *) Add code for kP+lQ timings to crypto/ec/ectest.c, and add SEC2 curve secp160r1 to the tests. [Douglas Stebila (Sun Microsystems Laboratories)] *) Add the possibility to load symbols globally with DSO. [Götz Babin-Ebell via Richard Levitte] *) Add the functions ERR_set_mark() and ERR_pop_to_mark() for better control of the error stack. [Richard Levitte] *) Add support for STORE in ENGINE. [Richard Levitte] *) Add the STORE type. The intention is to provide a common interface to certificate and key stores, be they simple file-based stores, or HSM-type store, or LDAP stores, or... NOTE: The code is currently UNTESTED and isn't really used anywhere. [Richard Levitte] *) Add a generic structure called OPENSSL_ITEM. This can be used to pass a list of arguments to any function as well as provide a way for a function to pass data back to the caller. [Richard Levitte] *) Add the functions BUF_strndup() and BUF_memdup(). BUF_strndup() works like BUF_strdup() but can be used to duplicate a portion of a string. The copy gets NUL-terminated. BUF_memdup() duplicates a memory area. [Richard Levitte] *) Add the function sk_find_ex() which works like sk_find(), but will return an index to an element even if an exact match couldn't be found. The index is guaranteed to point at the element where the searched-for key would be inserted to preserve sorting order. [Richard Levitte] *) Add the function OBJ_bsearch_ex() which works like OBJ_bsearch() but takes an extra flags argument for optional functionality. Currently, the following flags are defined: OBJ_BSEARCH_VALUE_ON_NOMATCH This one gets OBJ_bsearch_ex() to return a pointer to the first element where the comparing function returns a negative or zero number. OBJ_BSEARCH_FIRST_VALUE_ON_MATCH This one gets OBJ_bsearch_ex() to return a pointer to the first element where the comparing function returns zero. This is useful if there are more than one element where the comparing function returns zero. [Richard Levitte] *) Make it possible to create self-signed certificates with 'openssl ca' in such a way that the self-signed certificate becomes part of the CA database and uses the same mechanisms for serial number generation as all other certificate signing. The new flag '-selfsign' enables this functionality. Adapt CA.sh and CA.pl.in. [Richard Levitte] *) Add functionality to check the public key of a certificate request against a given private. This is useful to check that a certificate request can be signed by that key (self-signing). [Richard Levitte] *) Make it possible to have multiple active certificates with the same subject in the CA index file. This is done only if the keyword 'unique_subject' is set to 'no' in the main CA section (default if 'CA_default') of the configuration file. The value is saved with the database itself in a separate index attribute file, named like the index file with '.attr' appended to the name. [Richard Levitte] *) Generate muti valued AVAs using '+' notation in config files for req and dirName. [Steve Henson] *) Support for nameConstraints certificate extension. [Steve Henson] *) Support for policyConstraints certificate extension. [Steve Henson] *) Support for policyMappings certificate extension. [Steve Henson] *) Make sure the default DSA_METHOD implementation only uses its dsa_mod_exp() and/or bn_mod_exp() handlers if they are non-NULL, and change its own handlers to be NULL so as to remove unnecessary indirection. This lets alternative implementations fallback to the default implementation more easily. [Geoff Thorpe] *) Support for directoryName in GeneralName related extensions in config files. [Steve Henson] *) Make it possible to link applications using Makefile.shared. Make that possible even when linking against static libraries! [Richard Levitte] *) Support for single pass processing for S/MIME signing. This now means that S/MIME signing can be done from a pipe, in addition cleartext signing (multipart/signed type) is effectively streaming and the signed data does not need to be all held in memory. This is done with a new flag PKCS7_STREAM. When this flag is set PKCS7_sign() only initializes the PKCS7 structure and the actual signing is done after the data is output (and digests calculated) in SMIME_write_PKCS7(). [Steve Henson] *) Add full support for -rpath/-R, both in shared libraries and applications, at least on the platforms where it's known how to do it. [Richard Levitte] *) In crypto/ec/ec_mult.c, implement fast point multiplication with precomputation, based on wNAF splitting: EC_GROUP_precompute_mult() will now compute a table of multiples of the generator that makes subsequent invocations of EC_POINTs_mul() or EC_POINT_mul() faster (notably in the case of a single point multiplication, scalar * generator). [Nils Larsch, Bodo Moeller] *) IPv6 support for certificate extensions. The various extensions which use the IP:a.b.c.d can now take IPv6 addresses using the formats of RFC1884 2.2 . IPv6 addresses are now also displayed correctly. [Steve Henson] *) Added an ENGINE that implements RSA by performing private key exponentiations with the GMP library. The conversions to and from GMP's mpz_t format aren't optimised nor are any montgomery forms cached, and on x86 it appears OpenSSL's own performance has caught up. However there are likely to be other architectures where GMP could provide a boost. This ENGINE is not built in by default, but it can be specified at Configure time and should be accompanied by the necessary linker additions, eg; ./config -DOPENSSL_USE_GMP -lgmp [Geoff Thorpe] *) "openssl engine" will not display ENGINE/DSO load failure errors when testing availability of engines with "-t" - the old behaviour is produced by increasing the feature's verbosity with "-tt". [Geoff Thorpe] *) ECDSA routines: under certain error conditions uninitialized BN objects could be freed. Solution: make sure initialization is performed early enough. (Reported and fix supplied by Nils Larsch via PR#459) [Lutz Jaenicke] *) Key-generation can now be implemented in RSA_METHOD, DSA_METHOD and DH_METHOD (eg. by ENGINE implementations) to override the normal software implementations. For DSA and DH, parameter generation can also be overriden by providing the appropriate method callbacks. [Geoff Thorpe] *) Change the "progress" mechanism used in key-generation and primality testing to functions that take a new BN_GENCB pointer in place of callback/argument pairs. The new API functions have "_ex" postfixes and the older functions are reimplemented as wrappers for the new ones. The OPENSSL_NO_DEPRECATED symbol can be used to hide declarations of the old functions to help (graceful) attempts to migrate to the new functions. Also, the new key-generation API functions operate on a caller-supplied key-structure and return success/failure rather than returning a key or NULL - this is to help make "keygen" another member function of RSA_METHOD etc. Example for using the new callback interface: int (*my_callback)(int a, int b, BN_GENCB *cb) = ...; void *my_arg = ...; BN_GENCB my_cb; BN_GENCB_set(&my_cb, my_callback, my_arg); return BN_is_prime_ex(some_bignum, BN_prime_checks, NULL, &cb); /* For the meaning of a, b in calls to my_callback(), see the * documentation of the function that calls the callback. * cb will point to my_cb; my_arg can be retrieved as cb->arg. * my_callback should return 1 if it wants BN_is_prime_ex() * to continue, or 0 to stop. */ [Geoff Thorpe] *) Change the ZLIB compression method to be stateful, and make it available to TLS with the number defined in draft-ietf-tls-compression-04.txt. [Richard Levitte] *) Add the ASN.1 structures and functions for CertificatePair, which is defined as follows (according to X.509_4thEditionDraftV6.pdf): CertificatePair ::= SEQUENCE { forward [0] Certificate OPTIONAL, reverse [1] Certificate OPTIONAL, -- at least one of the pair shall be present -- } Also implement the PEM functions to read and write certificate pairs, and defined the PEM tag as "CERTIFICATE PAIR". This needed to be defined, mostly for the sake of the LDAP attribute crossCertificatePair, but may prove useful elsewhere as well. [Richard Levitte] *) Make it possible to inhibit symlinking of shared libraries in Makefile.shared, for Cygwin's sake. [Richard Levitte] *) Extend the BIGNUM API by creating a function void BN_set_negative(BIGNUM *a, int neg); and a macro that behave like int BN_is_negative(const BIGNUM *a); to avoid the need to access 'a->neg' directly in applications. [Nils Larsch] *) Implement fast modular reduction for pseudo-Mersenne primes used in NIST curves (crypto/bn/bn_nist.c, crypto/ec/ecp_nist.c). EC_GROUP_new_curve_GFp() will now automatically use this if applicable. [Nils Larsch ] *) Add new lock type (CRYPTO_LOCK_BN). [Bodo Moeller] *) Change the ENGINE framework to automatically load engines dynamically from specific directories unless they could be found to already be built in or loaded. Move all the current engines except for the cryptodev one to a new directory engines/. The engines in engines/ are built as shared libraries if the "shared" options was given to ./Configure or ./config. Otherwise, they are inserted in libcrypto.a. /usr/local/ssl/engines is the default directory for dynamic engines, but that can be overriden at configure time through the usual use of --prefix and/or --openssldir, and at run time with the environment variable OPENSSL_ENGINES. [Geoff Thorpe and Richard Levitte] *) Add Makefile.shared, a helper makefile to build shared libraries. Addapt Makefile.org. [Richard Levitte] *) Add version info to Win32 DLLs. [Peter 'Luna' Runestig" ] *) Add new 'medium level' PKCS#12 API. Certificates and keys can be added using this API to created arbitrary PKCS#12 files while avoiding the low level API. New options to PKCS12_create(), key or cert can be NULL and will then be omitted from the output file. The encryption algorithm NIDs can be set to -1 for no encryption, the mac iteration count can be set to 0 to omit the mac. Enhance pkcs12 utility by making the -nokeys and -nocerts options work when creating a PKCS#12 file. New option -nomac to omit the mac, NONE can be set for an encryption algorithm. New code is modified to use the enhanced PKCS12_create() instead of the low level API. [Steve Henson] *) Extend ASN1 encoder to support indefinite length constructed encoding. This can output sequences tags and octet strings in this form. Modify pk7_asn1.c to support indefinite length encoding. This is experimental and needs additional code to be useful, such as an ASN1 bio and some enhanced streaming PKCS#7 code. Extend template encode functionality so that tagging is passed down to the template encoder. [Steve Henson] *) Let 'openssl req' fail if an argument to '-newkey' is not recognized instead of using RSA as a default. [Bodo Moeller] *) Add support for ECC-based ciphersuites from draft-ietf-tls-ecc-01.txt. As these are not official, they are not included in "ALL"; the "ECCdraft" ciphersuite group alias can be used to select them. [Vipul Gupta and Sumit Gupta (Sun Microsystems Laboratories)] *) Add ECDH engine support. [Nils Gura and Douglas Stebila (Sun Microsystems Laboratories)] *) Add ECDH in new directory crypto/ecdh/. [Douglas Stebila (Sun Microsystems Laboratories)] *) Let BN_rand_range() abort with an error after 100 iterations without success (which indicates a broken PRNG). [Bodo Moeller] *) Change BN_mod_sqrt() so that it verifies that the input value is really the square of the return value. (Previously, BN_mod_sqrt would show GIGO behaviour.) [Bodo Moeller] *) Add named elliptic curves over binary fields from X9.62, SECG, and WAP/WTLS; add OIDs that were still missing. [Sheueling Chang Shantz and Douglas Stebila (Sun Microsystems Laboratories)] *) Extend the EC library for elliptic curves over binary fields (new files ec2_smpl.c, ec2_smpt.c, ec2_mult.c in crypto/ec/). New EC_METHOD: EC_GF2m_simple_method New API functions: EC_GROUP_new_curve_GF2m EC_GROUP_set_curve_GF2m EC_GROUP_get_curve_GF2m EC_POINT_set_affine_coordinates_GF2m EC_POINT_get_affine_coordinates_GF2m EC_POINT_set_compressed_coordinates_GF2m Point compression for binary fields is disabled by default for patent reasons (compile with OPENSSL_EC_BIN_PT_COMP defined to enable it). As binary polynomials are represented as BIGNUMs, various members of the EC_GROUP and EC_POINT data structures can be shared between the implementations for prime fields and binary fields; the above ..._GF2m functions (except for EX_GROUP_new_curve_GF2m) are essentially identical to their ..._GFp counterparts. (For simplicity, the '..._GFp' prefix has been dropped from various internal method names.) An internal 'field_div' method (similar to 'field_mul' and 'field_sqr') has been added; this is used only for binary fields. [Sheueling Chang Shantz and Douglas Stebila (Sun Microsystems Laboratories)] *) Optionally dispatch EC_POINT_mul(), EC_POINT_precompute_mult() through methods ('mul', 'precompute_mult'). The generic implementations (now internally called 'ec_wNAF_mul' and 'ec_wNAF_precomputed_mult') remain the default if these methods are undefined. [Sheueling Chang Shantz and Douglas Stebila (Sun Microsystems Laboratories)] *) New function EC_GROUP_get_degree, which is defined through EC_METHOD. For curves over prime fields, this returns the bit length of the modulus. [Sheueling Chang Shantz and Douglas Stebila (Sun Microsystems Laboratories)] *) New functions EC_GROUP_dup, EC_POINT_dup. (These simply call ..._new and ..._copy). [Sheueling Chang Shantz and Douglas Stebila (Sun Microsystems Laboratories)] *) Add binary polynomial arithmetic software in crypto/bn/bn_gf2m.c. Polynomials are represented as BIGNUMs (where the sign bit is not used) in the following functions [macros]: BN_GF2m_add BN_GF2m_sub [= BN_GF2m_add] BN_GF2m_mod [wrapper for BN_GF2m_mod_arr] BN_GF2m_mod_mul [wrapper for BN_GF2m_mod_mul_arr] BN_GF2m_mod_sqr [wrapper for BN_GF2m_mod_sqr_arr] BN_GF2m_mod_inv BN_GF2m_mod_exp [wrapper for BN_GF2m_mod_exp_arr] BN_GF2m_mod_sqrt [wrapper for BN_GF2m_mod_sqrt_arr] BN_GF2m_mod_solve_quad [wrapper for BN_GF2m_mod_solve_quad_arr] BN_GF2m_cmp [= BN_ucmp] (Note that only the 'mod' functions are actually for fields GF(2^m). BN_GF2m_add() is misnomer, but this is for the sake of consistency.) For some functions, an the irreducible polynomial defining a field can be given as an 'unsigned int[]' with strictly decreasing elements giving the indices of those bits that are set; i.e., p[] represents the polynomial f(t) = t^p[0] + t^p[1] + ... + t^p[k] where p[0] > p[1] > ... > p[k] = 0. This applies to the following functions: BN_GF2m_mod_arr BN_GF2m_mod_mul_arr BN_GF2m_mod_sqr_arr BN_GF2m_mod_inv_arr [wrapper for BN_GF2m_mod_inv] BN_GF2m_mod_div_arr [wrapper for BN_GF2m_mod_div] BN_GF2m_mod_exp_arr BN_GF2m_mod_sqrt_arr BN_GF2m_mod_solve_quad_arr BN_GF2m_poly2arr BN_GF2m_arr2poly Conversion can be performed by the following functions: BN_GF2m_poly2arr BN_GF2m_arr2poly bntest.c has additional tests for binary polynomial arithmetic. Two implementations for BN_GF2m_mod_div() are available. The default algorithm simply uses BN_GF2m_mod_inv() and BN_GF2m_mod_mul(). The alternative algorithm is compiled in only if OPENSSL_SUN_GF2M_DIV is defined (patent pending; read the copyright notice in crypto/bn/bn_gf2m.c before enabling it). [Sheueling Chang Shantz and Douglas Stebila (Sun Microsystems Laboratories)] *) Add new error code 'ERR_R_DISABLED' that can be used when some functionality is disabled at compile-time. [Douglas Stebila ] *) Change default behaviour of 'openssl asn1parse' so that more information is visible when viewing, e.g., a certificate: Modify asn1_parse2 (crypto/asn1/asn1_par.c) so that in non-'dump' mode the content of non-printable OCTET STRINGs is output in a style similar to INTEGERs, but with '[HEX DUMP]' prepended to avoid the appearance of a printable string. [Nils Larsch ] *) Add 'asn1_flag' and 'asn1_form' member to EC_GROUP with access functions EC_GROUP_set_asn1_flag() EC_GROUP_get_asn1_flag() EC_GROUP_set_point_conversion_form() EC_GROUP_get_point_conversion_form() These control ASN1 encoding details: - Curves (i.e., groups) are encoded explicitly unless asn1_flag has been set to OPENSSL_EC_NAMED_CURVE. - Points are encoded in uncompressed form by default; options for asn1_for are as for point2oct, namely POINT_CONVERSION_COMPRESSED POINT_CONVERSION_UNCOMPRESSED POINT_CONVERSION_HYBRID Also add 'seed' and 'seed_len' members to EC_GROUP with access functions EC_GROUP_set_seed() EC_GROUP_get0_seed() EC_GROUP_get_seed_len() This is used only for ASN1 purposes (so far). [Nils Larsch ] *) Add 'field_type' member to EC_METHOD, which holds the NID of the appropriate field type OID. The new function EC_METHOD_get_field_type() returns this value. [Nils Larsch ] *) Add functions EC_POINT_point2bn() EC_POINT_bn2point() EC_POINT_point2hex() EC_POINT_hex2point() providing useful interfaces to EC_POINT_point2oct() and EC_POINT_oct2point(). [Nils Larsch ] *) Change internals of the EC library so that the functions EC_GROUP_set_generator() EC_GROUP_get_generator() EC_GROUP_get_order() EC_GROUP_get_cofactor() are implemented directly in crypto/ec/ec_lib.c and not dispatched to methods, which would lead to unnecessary code duplication when adding different types of curves. [Nils Larsch with input by Bodo Moeller] *) Implement compute_wNAF (crypto/ec/ec_mult.c) without BIGNUM arithmetic, and such that modified wNAFs are generated (which avoid length expansion in many cases). [Bodo Moeller] *) Add a function EC_GROUP_check_discriminant() (defined via EC_METHOD) that verifies that the curve discriminant is non-zero. Add a function EC_GROUP_check() that makes some sanity tests on a EC_GROUP, its generator and order. This includes EC_GROUP_check_discriminant(). [Nils Larsch ] *) Add ECDSA in new directory crypto/ecdsa/. Add applications 'openssl ecparam' and 'openssl ecdsa' (these are based on 'openssl dsaparam' and 'openssl dsa'). ECDSA support is also included in various other files across the library. Most notably, - 'openssl req' now has a '-newkey ecdsa:file' option; - EVP_PKCS82PKEY (crypto/evp/evp_pkey.c) now can handle ECDSA; - X509_PUBKEY_get (crypto/asn1/x_pubkey.c) and d2i_PublicKey (crypto/asn1/d2i_pu.c) have been modified to make them suitable for ECDSA where domain parameters must be extracted before the specific public key; - ECDSA engine support has been added. [Nils Larsch ] *) Include some named elliptic curves, and add OIDs from X9.62, SECG, and WAP/WTLS. Each curve can be obtained from the new function EC_GROUP_new_by_curve_name(), and the list of available named curves can be obtained with EC_get_builtin_curves(). Also add a 'curve_name' member to EC_GROUP objects, which can be accessed via EC_GROUP_set_curve_name() EC_GROUP_get_curve_name() [Nils Larsch ] *) Include "!eNULL" in SSL_DEFAULT_CIPHER_LIST to make sure that a ciphersuite string such as "DEFAULT:RSA" cannot enable authentication-only ciphersuites. [Bodo Moeller] *) Since AES128 and AES256 share a single mask bit in the logic of ssl/ssl_ciph.c, the code for masking out disabled ciphers needs a kludge to work properly if AES128 is available and AES256 isn't. [Victor Duchovni] *) Expand security boundary to match 1.1.1 module. [Steve Henson] *) Remove redundant features: hash file source, editing of test vectors modify fipsld to use external fips_premain.c signature. [Steve Henson] *) New perl script mkfipsscr.pl to create shell scripts or batch files to run algorithm test programs. [Steve Henson] *) Make algorithm test programs more tolerant of whitespace. [Steve Henson] *) Have SSL/TLS server implementation tolerate "mismatched" record protocol version while receiving ClientHello even if the ClientHello is fragmented. (The server can't insist on the particular protocol version it has chosen before the ServerHello message has informed the client about his choice.) [Bodo Moeller] *) Load error codes if they are not already present instead of using a static variable. This allows them to be cleanly unloaded and reloaded. [Steve Henson] Changes between 0.9.7k and 0.9.7l [28 Sep 2006] *) Introduce limits to prevent malicious keys being able to cause a denial of service. (CVE-2006-2940) [Steve Henson, Bodo Moeller] *) Fix ASN.1 parsing of certain invalid structures that can result in a denial of service. (CVE-2006-2937) [Steve Henson] *) Fix buffer overflow in SSL_get_shared_ciphers() function. (CVE-2006-3738) [Tavis Ormandy and Will Drewry, Google Security Team] *) Fix SSL client code which could crash if connecting to a malicious SSLv2 server. (CVE-2006-4343) [Tavis Ormandy and Will Drewry, Google Security Team] *) Change ciphersuite string processing so that an explicit ciphersuite selects this one ciphersuite (so that "AES256-SHA" will no longer include "AES128-SHA"), and any other similar ciphersuite (same bitmap) from *other* protocol versions (so that "RC4-MD5" will still include both the SSL 2.0 ciphersuite and the SSL 3.0/TLS 1.0 ciphersuite). This is a backport combining changes from 0.9.8b and 0.9.8d. [Bodo Moeller] Changes between 0.9.7j and 0.9.7k [05 Sep 2006] *) Avoid PKCS #1 v1.5 signature attack discovered by Daniel Bleichenbacher (CVE-2006-4339) [Ben Laurie and Google Security Team] *) Change the Unix randomness entropy gathering to use poll() when possible instead of select(), since the latter has some undesirable limitations. [Darryl Miles via Richard Levitte and Bodo Moeller] *) Disable rogue ciphersuites: - SSLv2 0x08 0x00 0x80 ("RC4-64-MD5") - SSLv3/TLSv1 0x00 0x61 ("EXP1024-RC2-CBC-MD5") - SSLv3/TLSv1 0x00 0x60 ("EXP1024-RC4-MD5") The latter two were purportedly from draft-ietf-tls-56-bit-ciphersuites-0[01].txt, but do not really appear there. Also deactive the remaining ciphersuites from draft-ietf-tls-56-bit-ciphersuites-01.txt. These are just as unofficial, and the ID has long expired. [Bodo Moeller] *) Fix RSA blinding Heisenbug (problems sometimes occured on dual-core machines) and other potential thread-safety issues. [Bodo Moeller] Changes between 0.9.7i and 0.9.7j [04 May 2006] *) Adapt fipsld and the build system to link against the validated FIPS module in FIPS mode. [Steve Henson] *) Fixes for VC++ 2005 build under Windows. [Steve Henson] *) Add new Windows build target VC-32-GMAKE for VC++. This uses GNU make from a Windows bash shell such as MSYS. It is autodetected from the "config" script when run from a VC++ environment. Modify standard VC++ build to use fipscanister.o from the GNU make build. [Steve Henson] Changes between 0.9.7h and 0.9.7i [14 Oct 2005] *) Wrapped the definition of EVP_MAX_MD_SIZE in a #ifdef OPENSSL_FIPS. The value now differs depending on if you build for FIPS or not. BEWARE! A program linked with a shared FIPSed libcrypto can't be safely run with a non-FIPSed libcrypto, as it may crash because of the difference induced by this change. [Andy Polyakov] Changes between 0.9.7g and 0.9.7h [11 Oct 2005] *) Remove the functionality of SSL_OP_MSIE_SSLV2_RSA_PADDING (part of SSL_OP_ALL). This option used to disable the countermeasure against man-in-the-middle protocol-version rollback in the SSL 2.0 server implementation, which is a bad idea. (CVE-2005-2969) [Bodo Moeller; problem pointed out by Yutaka Oiwa (Research Center for Information Security, National Institute of Advanced Industrial Science and Technology [AIST], Japan)] *) Minimal support for X9.31 signatures and PSS padding modes. This is mainly for FIPS compliance and not fully integrated at this stage. [Steve Henson] *) For DSA signing, unless DSA_FLAG_NO_EXP_CONSTTIME is set, perform the exponentiation using a fixed-length exponent. (Otherwise, the information leaked through timing could expose the secret key after many signatures; cf. Bleichenbacher's attack on DSA with biased k.) [Bodo Moeller] *) Make a new fixed-window mod_exp implementation the default for RSA, DSA, and DH private-key operations so that the sequence of squares and multiplies and the memory access pattern are independent of the particular secret key. This will mitigate cache-timing and potential related attacks. BN_mod_exp_mont_consttime() is the new exponentiation implementation, and this is automatically used by BN_mod_exp_mont() if the new flag BN_FLG_EXP_CONSTTIME is set for the exponent. RSA, DSA, and DH will use this BN flag for private exponents unless the flag RSA_FLAG_NO_EXP_CONSTTIME, DSA_FLAG_NO_EXP_CONSTTIME, or DH_FLAG_NO_EXP_CONSTTIME, respectively, is set. [Matthew D Wood (Intel Corp), with some changes by Bodo Moeller] *) Change the client implementation for SSLv23_method() and SSLv23_client_method() so that is uses the SSL 3.0/TLS 1.0 Client Hello message format if the SSL_OP_NO_SSLv2 option is set. (Previously, the SSL 2.0 backwards compatible Client Hello message format would be used even with SSL_OP_NO_SSLv2.) [Bodo Moeller] *) Add support for smime-type MIME parameter in S/MIME messages which some clients need. [Steve Henson] *) New function BN_MONT_CTX_set_locked() to set montgomery parameters in a threadsafe manner. Modify rsa code to use new function and add calls to dsa and dh code (which had race conditions before). [Steve Henson] *) Include the fixed error library code in the C error file definitions instead of fixing them up at runtime. This keeps the error code structures constant. [Steve Henson] Changes between 0.9.7f and 0.9.7g [11 Apr 2005] [NB: OpenSSL 0.9.7h and later 0.9.7 patch levels were released after OpenSSL 0.9.8.] *) Fixes for newer kerberos headers. NB: the casts are needed because the 'length' field is signed on one version and unsigned on another with no (?) obvious way to tell the difference, without these VC++ complains. Also the "definition" of FAR (blank) is no longer included nor is the error ENOMEM. KRB5_PRIVATE has to be set to 1 to pick up some needed definitions. [Steve Henson] *) Undo Cygwin change. [Ulf Möller] *) Added support for proxy certificates according to RFC 3820. Because they may be a security thread to unaware applications, they must be explicitely allowed in run-time. See docs/HOWTO/proxy_certificates.txt for further information. [Richard Levitte] Changes between 0.9.7e and 0.9.7f [22 Mar 2005] *) Use (SSL_RANDOM_VALUE - 4) bytes of pseudo random data when generating server and client random values. Previously (SSL_RANDOM_VALUE - sizeof(time_t)) would be used which would result in less random data when sizeof(time_t) > 4 (some 64 bit platforms). This change has negligible security impact because: 1. Server and client random values still have 24 bytes of pseudo random data. 2. Server and client random values are sent in the clear in the initial handshake. 3. The master secret is derived using the premaster secret (48 bytes in size for static RSA ciphersuites) as well as client server and random values. The OpenSSL team would like to thank the UK NISCC for bringing this issue to our attention. [Stephen Henson, reported by UK NISCC] *) Use Windows randomness collection on Cygwin. [Ulf Möller] *) Fix hang in EGD/PRNGD query when communication socket is closed prematurely by EGD/PRNGD. [Darren Tucker via Lutz Jänicke, resolves #1014] *) Prompt for pass phrases when appropriate for PKCS12 input format. [Steve Henson] *) Back-port of selected performance improvements from development branch, as well as improved support for PowerPC platforms. [Andy Polyakov] *) Add lots of checks for memory allocation failure, error codes to indicate failure and freeing up memory if a failure occurs. [Nauticus Networks SSL Team , Steve Henson] *) Add new -passin argument to dgst. [Steve Henson] *) Perform some character comparisons of different types in X509_NAME_cmp: this is needed for some certificates that reencode DNs into UTF8Strings (in violation of RFC3280) and can't or wont issue name rollover certificates. [Steve Henson] *) Make an explicit check during certificate validation to see that the CA setting in each certificate on the chain is correct. As a side effect always do the following basic checks on extensions, not just when there's an associated purpose to the check: - if there is an unhandled critical extension (unless the user has chosen to ignore this fault) - if the path length has been exceeded (if one is set at all) - that certain extensions fit the associated purpose (if one has been given) [Richard Levitte] Changes between 0.9.7d and 0.9.7e [25 Oct 2004] *) Avoid a race condition when CRLs are checked in a multi threaded environment. This would happen due to the reordering of the revoked entries during signature checking and serial number lookup. Now the encoding is cached and the serial number sort performed under a lock. Add new STACK function sk_is_sorted(). [Steve Henson] *) Add Delta CRL to the extension code. [Steve Henson] *) Various fixes to s3_pkt.c so alerts are sent properly. [David Holmes ] *) Reduce the chances of duplicate issuer name and serial numbers (in violation of RFC3280) using the OpenSSL certificate creation utilities. This is done by creating a random 64 bit value for the initial serial number when a serial number file is created or when a self signed certificate is created using 'openssl req -x509'. The initial serial number file is created using 'openssl x509 -next_serial' in CA.pl rather than being initialized to 1. [Steve Henson] Changes between 0.9.7c and 0.9.7d [17 Mar 2004] *) Fix null-pointer assignment in do_change_cipher_spec() revealed by using the Codenomicon TLS Test Tool (CVE-2004-0079) [Joe Orton, Steve Henson] *) Fix flaw in SSL/TLS handshaking when using Kerberos ciphersuites (CVE-2004-0112) [Joe Orton, Steve Henson] *) Make it possible to have multiple active certificates with the same subject in the CA index file. This is done only if the keyword 'unique_subject' is set to 'no' in the main CA section (default if 'CA_default') of the configuration file. The value is saved with the database itself in a separate index attribute file, named like the index file with '.attr' appended to the name. [Richard Levitte] *) X509 verify fixes. Disable broken certificate workarounds when X509_V_FLAGS_X509_STRICT is set. Check CRL issuer has cRLSign set if keyUsage extension present. Don't accept CRLs with unhandled critical extensions: since verify currently doesn't process CRL extensions this rejects a CRL with *any* critical extensions. Add new verify error codes for these cases. [Steve Henson] *) When creating an OCSP nonce use an OCTET STRING inside the extnValue. A clarification of RFC2560 will require the use of OCTET STRINGs and some implementations cannot handle the current raw format. Since OpenSSL copies and compares OCSP nonces as opaque blobs without any attempt at parsing them this should not create any compatibility issues. [Steve Henson] *) New md flag EVP_MD_CTX_FLAG_REUSE this allows md_data to be reused when calling EVP_MD_CTX_copy_ex() to avoid calling OPENSSL_malloc(). Without this HMAC (and other) operations are several times slower than OpenSSL < 0.9.7. [Steve Henson] *) Print out GeneralizedTime and UTCTime in ASN1_STRING_print_ex(). [Peter Sylvester ] *) Use the correct content when signing type "other". [Steve Henson] Changes between 0.9.7b and 0.9.7c [30 Sep 2003] *) Fix various bugs revealed by running the NISCC test suite: Stop out of bounds reads in the ASN1 code when presented with invalid tags (CVE-2003-0543 and CVE-2003-0544). Free up ASN1_TYPE correctly if ANY type is invalid (CVE-2003-0545). If verify callback ignores invalid public key errors don't try to check certificate signature with the NULL public key. [Steve Henson] *) New -ignore_err option in ocsp application to stop the server exiting on the first error in a request. [Steve Henson] *) In ssl3_accept() (ssl/s3_srvr.c) only accept a client certificate if the server requested one: as stated in TLS 1.0 and SSL 3.0 specifications. [Steve Henson] *) In ssl3_get_client_hello() (ssl/s3_srvr.c), tolerate additional extra data after the compression methods not only for TLS 1.0 but also for SSL 3.0 (as required by the specification). [Bodo Moeller; problem pointed out by Matthias Loepfe] *) Change X509_certificate_type() to mark the key as exported/exportable when it's 512 *bits* long, not 512 bytes. [Richard Levitte] *) Change AES_cbc_encrypt() so it outputs exact multiple of blocks during encryption. [Richard Levitte] *) Various fixes to base64 BIO and non blocking I/O. On write flushes were not handled properly if the BIO retried. On read data was not being buffered properly and had various logic bugs. This also affects blocking I/O when the data being decoded is a certain size. [Steve Henson] *) Various S/MIME bugfixes and compatibility changes: output correct application/pkcs7 MIME type if PKCS7_NOOLDMIMETYPE is set. Tolerate some broken signatures. Output CR+LF for EOL if PKCS7_CRLFEOL is set (this makes opening of files as .eml work). Correctly handle very long lines in MIME parser. [Steve Henson] Changes between 0.9.7a and 0.9.7b [10 Apr 2003] *) Countermeasure against the Klima-Pokorny-Rosa extension of Bleichbacher's attack on PKCS #1 v1.5 padding: treat a protocol version number mismatch like a decryption error in ssl3_get_client_key_exchange (ssl/s3_srvr.c). [Bodo Moeller] *) Turn on RSA blinding by default in the default implementation to avoid a timing attack. Applications that don't want it can call RSA_blinding_off() or use the new flag RSA_FLAG_NO_BLINDING. They would be ill-advised to do so in most cases. [Ben Laurie, Steve Henson, Geoff Thorpe, Bodo Moeller] *) Change RSA blinding code so that it works when the PRNG is not seeded (in this case, the secret RSA exponent is abused as an unpredictable seed -- if it is not unpredictable, there is no point in blinding anyway). Make RSA blinding thread-safe by remembering the creator's thread ID in rsa->blinding and having all other threads use local one-time blinding factors (this requires more computation than sharing rsa->blinding, but avoids excessive locking; and if an RSA object is not shared between threads, blinding will still be very fast). [Bodo Moeller] *) Fixed a typo bug that would cause ENGINE_set_default() to set an ENGINE as defaults for all supported algorithms irrespective of the 'flags' parameter. 'flags' is now honoured, so applications should make sure they are passing it correctly. [Geoff Thorpe] *) Target "mingw" now allows native Windows code to be generated in the Cygwin environment as well as with the MinGW compiler. [Ulf Moeller] Changes between 0.9.7 and 0.9.7a [19 Feb 2003] *) In ssl3_get_record (ssl/s3_pkt.c), minimize information leaked via timing by performing a MAC computation even if incorrrect block cipher padding has been found. This is a countermeasure against active attacks where the attacker has to distinguish between bad padding and a MAC verification error. (CVE-2003-0078) [Bodo Moeller; problem pointed out by Brice Canvel (EPFL), Alain Hiltgen (UBS), Serge Vaudenay (EPFL), and Martin Vuagnoux (EPFL, Ilion)] *) Make the no-err option work as intended. The intention with no-err is not to have the whole error stack handling routines removed from libcrypto, it's only intended to remove all the function name and reason texts, thereby removing some of the footprint that may not be interesting if those errors aren't displayed anyway. NOTE: it's still possible for any application or module to have it's own set of error texts inserted. The routines are there, just not used by default when no-err is given. [Richard Levitte] *) Add support for FreeBSD on IA64. [dirk.meyer@dinoex.sub.org via Richard Levitte, resolves #454] *) Adjust DES_cbc_cksum() so it returns the same value as the MIT Kerberos function mit_des_cbc_cksum(). Before this change, the value returned by DES_cbc_cksum() was like the one from mit_des_cbc_cksum(), except the bytes were swapped. [Kevin Greaney and Richard Levitte] *) Allow an application to disable the automatic SSL chain building. Before this a rather primitive chain build was always performed in ssl3_output_cert_chain(): an application had no way to send the correct chain if the automatic operation produced an incorrect result. Now the chain builder is disabled if either: 1. Extra certificates are added via SSL_CTX_add_extra_chain_cert(). 2. The mode flag SSL_MODE_NO_AUTO_CHAIN is set. The reasoning behind this is that an application would not want the auto chain building to take place if extra chain certificates are present and it might also want a means of sending no additional certificates (for example the chain has two certificates and the root is omitted). [Steve Henson] *) Add the possibility to build without the ENGINE framework. [Steven Reddie via Richard Levitte] *) Under Win32 gmtime() can return NULL: check return value in OPENSSL_gmtime(). Add error code for case where gmtime() fails. [Steve Henson] *) DSA routines: under certain error conditions uninitialized BN objects could be freed. Solution: make sure initialization is performed early enough. (Reported and fix supplied by Ivan D Nestlerode , Nils Larsch via PR#459) [Lutz Jaenicke] *) Another fix for SSLv2 session ID handling: the session ID was incorrectly checked on reconnect on the client side, therefore session resumption could still fail with a "ssl session id is different" error. This behaviour is masked when SSL_OP_ALL is used due to SSL_OP_MICROSOFT_SESS_ID_BUG being set. Behaviour observed by Crispin Flowerday as followup to PR #377. [Lutz Jaenicke] *) IA-32 assembler support enhancements: unified ELF targets, support for SCO/Caldera platforms, fix for Cygwin shared build. [Andy Polyakov] *) Add support for FreeBSD on sparc64. As a consequence, support for FreeBSD on non-x86 processors is separate from x86 processors on the config script, much like the NetBSD support. [Richard Levitte & Kris Kennaway ] Changes between 0.9.6h and 0.9.7 [31 Dec 2002] [NB: OpenSSL 0.9.6i and later 0.9.6 patch levels were released after OpenSSL 0.9.7.] *) Fix session ID handling in SSLv2 client code: the SERVER FINISHED code (06) was taken as the first octet of the session ID and the last octet was ignored consequently. As a result SSLv2 client side session caching could not have worked due to the session ID mismatch between client and server. Behaviour observed by Crispin Flowerday as PR #377. [Lutz Jaenicke] *) Change the declaration of needed Kerberos libraries to use EX_LIBS instead of the special (and badly supported) LIBKRB5. LIBKRB5 is removed entirely. [Richard Levitte] *) The hw_ncipher.c engine requires dynamic locks. Unfortunately, it seems that in spite of existing for more than a year, many application author have done nothing to provide the necessary callbacks, which means that this particular engine will not work properly anywhere. This is a very unfortunate situation which forces us, in the name of usability, to give the hw_ncipher.c a static lock, which is part of libcrypto. NOTE: This is for the 0.9.7 series ONLY. This hack will never appear in 0.9.8 or later. We EXPECT application authors to have dealt properly with this when 0.9.8 is released (unless we actually make such changes in the libcrypto locking code that changes will have to be made anyway). [Richard Levitte] *) In asn1_d2i_read_bio() repeatedly call BIO_read() until all content octets have been read, EOF or an error occurs. Without this change some truncated ASN1 structures will not produce an error. [Steve Henson] *) Disable Heimdal support, since it hasn't been fully implemented. Still give the possibility to force the use of Heimdal, but with warnings and a request that patches get sent to openssl-dev. [Richard Levitte] *) Add the VC-CE target, introduce the WINCE sysname, and add INSTALL.WCE and appropriate conditionals to make it build. [Steven Reddie via Richard Levitte] *) Change the DLL names for Cygwin to cygcrypto-x.y.z.dll and cygssl-x.y.z.dll, where x, y and z are the major, minor and edit numbers of the version. [Corinna Vinschen and Richard Levitte] *) Introduce safe string copy and catenation functions (BUF_strlcpy() and BUF_strlcat()). [Ben Laurie (CHATS) and Richard Levitte] *) Avoid using fixed-size buffers for one-line DNs. [Ben Laurie (CHATS)] *) Add BUF_MEM_grow_clean() to avoid information leakage when resizing buffers containing secrets, and use where appropriate. [Ben Laurie (CHATS)] *) Avoid using fixed size buffers for configuration file location. [Ben Laurie (CHATS)] *) Avoid filename truncation for various CA files. [Ben Laurie (CHATS)] *) Use sizeof in preference to magic numbers. [Ben Laurie (CHATS)] *) Avoid filename truncation in cert requests. [Ben Laurie (CHATS)] *) Add assertions to check for (supposedly impossible) buffer overflows. [Ben Laurie (CHATS)] *) Don't cache truncated DNS entries in the local cache (this could potentially lead to a spoofing attack). [Ben Laurie (CHATS)] *) Fix various buffers to be large enough for hex/decimal representations in a platform independent manner. [Ben Laurie (CHATS)] *) Add CRYPTO_realloc_clean() to avoid information leakage when resizing buffers containing secrets, and use where appropriate. [Ben Laurie (CHATS)] *) Add BIO_indent() to avoid much slightly worrying code to do indents. [Ben Laurie (CHATS)] *) Convert sprintf()/BIO_puts() to BIO_printf(). [Ben Laurie (CHATS)] *) buffer_gets() could terminate with the buffer only half full. Fixed. [Ben Laurie (CHATS)] *) Add assertions to prevent user-supplied crypto functions from overflowing internal buffers by having large block sizes, etc. [Ben Laurie (CHATS)] *) New OPENSSL_assert() macro (similar to assert(), but enabled unconditionally). [Ben Laurie (CHATS)] *) Eliminate unused copy of key in RC4. [Ben Laurie (CHATS)] *) Eliminate unused and incorrectly sized buffers for IV in pem.h. [Ben Laurie (CHATS)] *) Fix off-by-one error in EGD path. [Ben Laurie (CHATS)] *) If RANDFILE path is too long, ignore instead of truncating. [Ben Laurie (CHATS)] *) Eliminate unused and incorrectly sized X.509 structure CBCParameter. [Ben Laurie (CHATS)] *) Eliminate unused and dangerous function knumber(). [Ben Laurie (CHATS)] *) Eliminate unused and dangerous structure, KSSL_ERR. [Ben Laurie (CHATS)] *) Protect against overlong session ID context length in an encoded session object. Since these are local, this does not appear to be exploitable. [Ben Laurie (CHATS)] *) Change from security patch (see 0.9.6e below) that did not affect the 0.9.6 release series: Remote buffer overflow in SSL3 protocol - an attacker could supply an oversized master key in Kerberos-enabled versions. (CVE-2002-0657) [Ben Laurie (CHATS)] *) Change the SSL kerb5 codes to match RFC 2712. [Richard Levitte] *) Make -nameopt work fully for req and add -reqopt switch. [Michael Bell , Steve Henson] *) The "block size" for block ciphers in CFB and OFB mode should be 1. [Steve Henson, reported by Yngve Nysaeter Pettersen ] *) Make sure tests can be performed even if the corresponding algorithms have been removed entirely. This was also the last step to make OpenSSL compilable with DJGPP under all reasonable conditions. [Richard Levitte, Doug Kaufman ] *) Add cipher selection rules COMPLEMENTOFALL and COMPLEMENTOFDEFAULT to allow version independent disabling of normally unselected ciphers, which may be activated as a side-effect of selecting a single cipher. (E.g., cipher list string "RSA" enables ciphersuites that are left out of "ALL" because they do not provide symmetric encryption. "RSA:!COMPLEMEMENTOFALL" avoids these unsafe ciphersuites.) [Lutz Jaenicke, Bodo Moeller] *) Add appropriate support for separate platform-dependent build directories. The recommended way to make a platform-dependent build directory is the following (tested on Linux), maybe with some local tweaks: # Place yourself outside of the OpenSSL source tree. In # this example, the environment variable OPENSSL_SOURCE # is assumed to contain the absolute OpenSSL source directory. mkdir -p objtree/"`uname -s`-`uname -r`-`uname -m`" cd objtree/"`uname -s`-`uname -r`-`uname -m`" (cd $OPENSSL_SOURCE; find . -type f) | while read F; do mkdir -p `dirname $F` ln -s $OPENSSL_SOURCE/$F $F done To be absolutely sure not to disturb the source tree, a "make clean" is a good thing. If it isn't successfull, don't worry about it, it probably means the source directory is very clean. [Richard Levitte] *) Make sure any ENGINE control commands make local copies of string pointers passed to them whenever necessary. Otherwise it is possible the caller may have overwritten (or deallocated) the original string data when a later ENGINE operation tries to use the stored values. [Götz Babin-Ebell ] *) Improve diagnostics in file reading and command-line digests. [Ben Laurie aided and abetted by Solar Designer ] *) Add AES modes CFB and OFB to the object database. Correct an error in AES-CFB decryption. [Richard Levitte] *) Remove most calls to EVP_CIPHER_CTX_cleanup() in evp_enc.c, this allows existing EVP_CIPHER_CTX structures to be reused after calling EVP_*Final(). This behaviour is used by encryption BIOs and some applications. This has the side effect that applications must explicitly clean up cipher contexts with EVP_CIPHER_CTX_cleanup() or they will leak memory. [Steve Henson] *) Check the values of dna and dnb in bn_mul_recursive before calling bn_mul_comba (a non zero value means the a or b arrays do not contain n2 elements) and fallback to bn_mul_normal if either is not zero. [Steve Henson] *) Fix escaping of non-ASCII characters when using the -subj option of the "openssl req" command line tool. (Robert Joop ) [Lutz Jaenicke] *) Make object definitions compliant to LDAP (RFC2256): SN is the short form for "surname", serialNumber has no short form. Use "mail" as the short name for "rfc822Mailbox" according to RFC2798; therefore remove "mail" short name for "internet 7". The OID for unique identifiers in X509 certificates is x500UniqueIdentifier, not uniqueIdentifier. Some more OID additions. (Michael Bell ) [Lutz Jaenicke] *) Add an "init" command to the ENGINE config module and auto initialize ENGINEs. Without any "init" command the ENGINE will be initialized after all ctrl commands have been executed on it. If init=1 the ENGINE is initailized at that point (ctrls before that point are run on the uninitialized ENGINE and after on the initialized one). If init=0 then the ENGINE will not be iniatialized at all. [Steve Henson] *) Fix the 'app_verify_callback' interface so that the user-defined argument is actually passed to the callback: In the SSL_CTX_set_cert_verify_callback() prototype, the callback declaration has been changed from int (*cb)() into int (*cb)(X509_STORE_CTX *,void *); in ssl_verify_cert_chain (ssl/ssl_cert.c), the call i=s->ctx->app_verify_callback(&ctx) has been changed into i=s->ctx->app_verify_callback(&ctx, s->ctx->app_verify_arg). To update applications using SSL_CTX_set_cert_verify_callback(), a dummy argument can be added to their callback functions. [D. K. Smetters ] *) Added the '4758cca' ENGINE to support IBM 4758 cards. [Maurice Gittens , touchups by Geoff Thorpe] *) Add and OPENSSL_LOAD_CONF define which will cause OpenSSL_add_all_algorithms() to load the openssl.cnf config file. This allows older applications to transparently support certain OpenSSL features: such as crypto acceleration and dynamic ENGINE loading. Two new functions OPENSSL_add_all_algorithms_noconf() which will never load the config file and OPENSSL_add_all_algorithms_conf() which will always load it have also been added. [Steve Henson] *) Add the OFB, CFB and CTR (all with 128 bit feedback) to AES. Adjust NIDs and EVP layer. [Stephen Sprunk and Richard Levitte] *) Config modules support in openssl utility. Most commands now load modules from the config file, though in a few (such as version) this isn't done because it couldn't be used for anything. In the case of ca and req the config file used is the same as the utility itself: that is the -config command line option can be used to specify an alternative file. [Steve Henson] *) Move default behaviour from OPENSSL_config(). If appname is NULL use "openssl_conf" if filename is NULL use default openssl config file. [Steve Henson] *) Add an argument to OPENSSL_config() to allow the use of an alternative config section name. Add a new flag to tolerate a missing config file and move code to CONF_modules_load_file(). [Steve Henson] *) Support for crypto accelerator cards from Accelerated Encryption Processing, www.aep.ie. (Use engine 'aep') The support was copied from 0.9.6c [engine] and adapted/corrected to work with the new engine framework. [AEP Inc. and Richard Levitte] *) Support for SureWare crypto accelerator cards from Baltimore Technologies. (Use engine 'sureware') The support was copied from 0.9.6c [engine] and adapted to work with the new engine framework. [Richard Levitte] *) Have the CHIL engine fork-safe (as defined by nCipher) and actually make the newer ENGINE framework commands for the CHIL engine work. [Toomas Kiisk and Richard Levitte] *) Make it possible to produce shared libraries on ReliantUNIX. [Robert Dahlem via Richard Levitte] *) Add the configuration target debug-linux-ppro. Make 'openssl rsa' use the general key loading routines implemented in apps.c, and make those routines able to handle the key format FORMAT_NETSCAPE and the variant FORMAT_IISSGC. [Toomas Kiisk via Richard Levitte] *) Fix a crashbug and a logic bug in hwcrhk_load_pubkey(). [Toomas Kiisk via Richard Levitte] *) Add -keyform to rsautl, and document -engine. [Richard Levitte, inspired by Toomas Kiisk ] *) Change BIO_new_file (crypto/bio/bss_file.c) to use new BIO_R_NO_SUCH_FILE error code rather than the generic ERR_R_SYS_LIB error code if fopen() fails with ENOENT. [Ben Laurie] *) Add new functions ERR_peek_last_error ERR_peek_last_error_line ERR_peek_last_error_line_data. These are similar to ERR_peek_error ERR_peek_error_line ERR_peek_error_line_data, but report on the latest error recorded rather than the first one still in the error queue. [Ben Laurie, Bodo Moeller] *) default_algorithms option in ENGINE config module. This allows things like: default_algorithms = ALL default_algorithms = RSA, DSA, RAND, CIPHERS, DIGESTS [Steve Henson] *) Prelminary ENGINE config module. [Steve Henson] *) New experimental application configuration code. [Steve Henson] *) Change the AES code to follow the same name structure as all other symmetric ciphers, and behave the same way. Move everything to the directory crypto/aes, thereby obsoleting crypto/rijndael. [Stephen Sprunk and Richard Levitte] *) SECURITY: remove unsafe setjmp/signal interaction from ui_openssl.c. [Ben Laurie and Theo de Raadt] *) Add option to output public keys in req command. [Massimiliano Pala madwolf@openca.org] *) Use wNAFs in EC_POINTs_mul() for improved efficiency (up to about 10% better than before for P-192 and P-224). [Bodo Moeller] *) New functions/macros SSL_CTX_set_msg_callback(ctx, cb) SSL_CTX_set_msg_callback_arg(ctx, arg) SSL_set_msg_callback(ssl, cb) SSL_set_msg_callback_arg(ssl, arg) to request calling a callback function void cb(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg) whenever a protocol message has been completely received (write_p == 0) or sent (write_p == 1). Here 'version' is the protocol version according to which the SSL library interprets the current protocol message (SSL2_VERSION, SSL3_VERSION, or TLS1_VERSION). 'content_type' is 0 in the case of SSL 2.0, or the content type as defined in the SSL 3.0/TLS 1.0 protocol specification (change_cipher_spec(20), alert(21), handshake(22)). 'buf' and 'len' point to the actual message, 'ssl' to the SSL object, and 'arg' is the application-defined value set by SSL[_CTX]_set_msg_callback_arg(). 'openssl s_client' and 'openssl s_server' have new '-msg' options to enable a callback that displays all protocol messages. [Bodo Moeller] *) Change the shared library support so shared libraries are built as soon as the corresponding static library is finished, and thereby get openssl and the test programs linked against the shared library. This still only happens when the keyword "shard" has been given to the configuration scripts. NOTE: shared library support is still an experimental thing, and backward binary compatibility is still not guaranteed. ["Maciej W. Rozycki" and Richard Levitte] *) Add support for Subject Information Access extension. [Peter Sylvester ] *) Make BUF_MEM_grow() behaviour more consistent: Initialise to zero additional bytes when new memory had to be allocated, not just when reusing an existing buffer. [Bodo Moeller] *) New command line and configuration option 'utf8' for the req command. This allows field values to be specified as UTF8 strings. [Steve Henson] *) Add -multi and -mr options to "openssl speed" - giving multiple parallel runs for the former and machine-readable output for the latter. [Ben Laurie] *) Add '-noemailDN' option to 'openssl ca'. This prevents inclusion of the e-mail address in the DN (i.e., it will go into a certificate extension only). The new configuration file option 'email_in_dn = no' has the same effect. [Massimiliano Pala madwolf@openca.org] *) Change all functions with names starting with des_ to be starting with DES_ instead. Add wrappers that are compatible with libdes, but are named _ossl_old_des_*. Finally, add macros that map the des_* symbols to the corresponding _ossl_old_des_* if libdes compatibility is desired. If OpenSSL 0.9.6c compatibility is desired, the des_* symbols will be mapped to DES_*, with one exception. Since we provide two compatibility mappings, the user needs to define the macro OPENSSL_DES_LIBDES_COMPATIBILITY if libdes compatibility is desired. The default (i.e., when that macro isn't defined) is OpenSSL 0.9.6c compatibility. There are also macros that enable and disable the support of old des functions altogether. Those are OPENSSL_ENABLE_OLD_DES_SUPPORT and OPENSSL_DISABLE_OLD_DES_SUPPORT. If none or both of those are defined, the default will apply: to support the old des routines. In either case, one must include openssl/des.h to get the correct definitions. Do not try to just include openssl/des_old.h, that won't work. NOTE: This is a major break of an old API into a new one. Software authors are encouraged to switch to the DES_ style functions. Some time in the future, des_old.h and the libdes compatibility functions will be disable (i.e. OPENSSL_DISABLE_OLD_DES_SUPPORT will be the default), and then completely removed. [Richard Levitte] *) Test for certificates which contain unsupported critical extensions. If such a certificate is found during a verify operation it is rejected by default: this behaviour can be overridden by either handling the new error X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION or by setting the verify flag X509_V_FLAG_IGNORE_CRITICAL. A new function X509_supported_extension() has also been added which returns 1 if a particular extension is supported. [Steve Henson] *) Modify the behaviour of EVP cipher functions in similar way to digests to retain compatibility with existing code. [Steve Henson] *) Modify the behaviour of EVP_DigestInit() and EVP_DigestFinal() to retain compatibility with existing code. In particular the 'ctx' parameter does not have to be to be initialized before the call to EVP_DigestInit() and it is tidied up after a call to EVP_DigestFinal(). New function EVP_DigestFinal_ex() which does not tidy up the ctx. Similarly function EVP_MD_CTX_copy() changed to not require the destination to be initialized valid and new function EVP_MD_CTX_copy_ex() added which requires the destination to be valid. Modify all the OpenSSL digest calls to use EVP_DigestInit_ex(), EVP_DigestFinal_ex() and EVP_MD_CTX_copy_ex(). [Steve Henson] *) Change ssl3_get_message (ssl/s3_both.c) and the functions using it so that complete 'Handshake' protocol structures are kept in memory instead of overwriting 'msg_type' and 'length' with 'body' data. [Bodo Moeller] *) Add an implementation of SSL_add_dir_cert_subjects_to_stack for Win32. [Massimo Santin via Richard Levitte] *) Major restructuring to the underlying ENGINE code. This includes reduction of linker bloat, separation of pure "ENGINE" manipulation (initialisation, etc) from functionality dealing with implementations of specific crypto iterfaces. This change also introduces integrated support for symmetric ciphers and digest implementations - so ENGINEs can now accelerate these by providing EVP_CIPHER and EVP_MD implementations of their own. This is detailed in crypto/engine/README as it couldn't be adequately described here. However, there are a few API changes worth noting - some RSA, DSA, DH, and RAND functions that were changed in the original introduction of ENGINE code have now reverted back - the hooking from this code to ENGINE is now a good deal more passive and at run-time, operations deal directly with RSA_METHODs, DSA_METHODs (etc) as they did before, rather than dereferencing through an ENGINE pointer any more. Also, the ENGINE functions dealing with BN_MOD_EXP[_CRT] handlers have been removed - they were not being used by the framework as there is no concept of a BIGNUM_METHOD and they could not be generalised to the new 'ENGINE_TABLE' mechanism that underlies the new code. Similarly, ENGINE_cpy() has been removed as it cannot be consistently defined in the new code. [Geoff Thorpe] *) Change ASN1_GENERALIZEDTIME_check() to allow fractional seconds. [Steve Henson] *) Change mkdef.pl to sort symbols that get the same entry number, and make sure the automatically generated functions ERR_load_* become part of libeay.num as well. [Richard Levitte] *) New function SSL_renegotiate_pending(). This returns true once renegotiation has been requested (either SSL_renegotiate() call or HelloRequest/ClientHello receveived from the peer) and becomes false once a handshake has been completed. (For servers, SSL_renegotiate() followed by SSL_do_handshake() sends a HelloRequest, but does not ensure that a handshake takes place. SSL_renegotiate_pending() is useful for checking if the client has followed the request.) [Bodo Moeller] *) New SSL option SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION. By default, clients may request session resumption even during renegotiation (if session ID contexts permit); with this option, session resumption is possible only in the first handshake. SSL_OP_ALL is now 0x00000FFFL instead of 0x000FFFFFL. This makes more bits available for options that should not be part of SSL_OP_ALL (such as SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION). [Bodo Moeller] *) Add some demos for certificate and certificate request creation. [Steve Henson] *) Make maximum certificate chain size accepted from the peer application settable (SSL*_get/set_max_cert_list()), as proposed by "Douglas E. Engert" . [Lutz Jaenicke] *) Add support for shared libraries for Unixware-7 (Boyd Lynn Gerber ). [Lutz Jaenicke] *) Add a "destroy" handler to ENGINEs that allows structural cleanup to be done prior to destruction. Use this to unload error strings from ENGINEs that load their own error strings. NB: This adds two new API functions to "get" and "set" this destroy handler in an ENGINE. [Geoff Thorpe] *) Alter all existing ENGINE implementations (except "openssl" and "openbsd") to dynamically instantiate their own error strings. This makes them more flexible to be built both as statically-linked ENGINEs and self-contained shared-libraries loadable via the "dynamic" ENGINE. Also, add stub code to each that makes building them as self-contained shared-libraries easier (see README.ENGINE). [Geoff Thorpe] *) Add a "dynamic" ENGINE that provides a mechanism for binding ENGINE implementations into applications that are completely implemented in self-contained shared-libraries. The "dynamic" ENGINE exposes control commands that can be used to configure what shared-library to load and to control aspects of the way it is handled. Also, made an update to the README.ENGINE file that brings its information up-to-date and provides some information and instructions on the "dynamic" ENGINE (ie. how to use it, how to build "dynamic"-loadable ENGINEs, etc). [Geoff Thorpe] *) Make it possible to unload ranges of ERR strings with a new "ERR_unload_strings" function. [Geoff Thorpe] *) Add a copy() function to EVP_MD. [Ben Laurie] *) Make EVP_MD routines take a context pointer instead of just the md_data void pointer. [Ben Laurie] *) Add flags to EVP_MD and EVP_MD_CTX. EVP_MD_FLAG_ONESHOT indicates that the digest can only process a single chunk of data (typically because it is provided by a piece of hardware). EVP_MD_CTX_FLAG_ONESHOT indicates that the application is only going to provide a single chunk of data, and hence the framework needn't accumulate the data for oneshot drivers. [Ben Laurie] *) As with "ERR", make it possible to replace the underlying "ex_data" functions. This change also alters the storage and management of global ex_data state - it's now all inside ex_data.c and all "class" code (eg. RSA, BIO, SSL_CTX, etc) no longer stores its own STACKS and per-class index counters. The API functions that use this state have been changed to take a "class_index" rather than pointers to the class's local STACK and counter, and there is now an API function to dynamically create new classes. This centralisation allows us to (a) plug a lot of the thread-safety problems that existed, and (b) makes it possible to clean up all allocated state using "CRYPTO_cleanup_all_ex_data()". W.r.t. (b) such data would previously have always leaked in application code and workarounds were in place to make the memory debugging turn a blind eye to it. Application code that doesn't use this new function will still leak as before, but their memory debugging output will announce it now rather than letting it slide. Besides the addition of CRYPTO_cleanup_all_ex_data(), another API change induced by the "ex_data" overhaul is that X509_STORE_CTX_init() now has a return value to indicate success or failure. [Geoff Thorpe] *) Make it possible to replace the underlying "ERR" functions such that the global state (2 LHASH tables and 2 locks) is only used by the "default" implementation. This change also adds two functions to "get" and "set" the implementation prior to it being automatically set the first time any other ERR function takes place. Ie. an application can call "get", pass the return value to a module it has just loaded, and that module can call its own "set" function using that value. This means the module's "ERR" operations will use (and modify) the error state in the application and not in its own statically linked copy of OpenSSL code. [Geoff Thorpe] *) Give DH, DSA, and RSA types their own "**_up_ref()" function to increment reference counts. This performs normal REF_PRINT/REF_CHECK macros on the operation, and provides a more encapsulated way for external code (crypto/evp/ and ssl/) to do this. Also changed the evp and ssl code to use these functions rather than manually incrementing the counts. Also rename "DSO_up()" function to more descriptive "DSO_up_ref()". [Geoff Thorpe] *) Add EVP test program. [Ben Laurie] *) Add symmetric cipher support to ENGINE. Expect the API to change! [Ben Laurie] *) New CRL functions: X509_CRL_set_version(), X509_CRL_set_issuer_name() X509_CRL_set_lastUpdate(), X509_CRL_set_nextUpdate(), X509_CRL_sort(), X509_REVOKED_set_serialNumber(), and X509_REVOKED_set_revocationDate(). These allow a CRL to be built without having to access X509_CRL fields directly. Modify 'ca' application to use new functions. [Steve Henson] *) Move SSL_OP_TLS_ROLLBACK_BUG out of the SSL_OP_ALL list of recommended bug workarounds. Rollback attack detection is a security feature. The problem will only arise on OpenSSL servers when TLSv1 is not available (sslv3_server_method() or SSL_OP_NO_TLSv1). Software authors not wanting to support TLSv1 will have special reasons for their choice and can explicitly enable this option. [Bodo Moeller, Lutz Jaenicke] *) Rationalise EVP so it can be extended: don't include a union of cipher/digest structures, add init/cleanup functions for EVP_MD_CTX (similar to those existing for EVP_CIPHER_CTX). Usage example: EVP_MD_CTX md; EVP_MD_CTX_init(&md); /* new function call */ EVP_DigestInit(&md, EVP_sha1()); EVP_DigestUpdate(&md, in, len); EVP_DigestFinal(&md, out, NULL); EVP_MD_CTX_cleanup(&md); /* new function call */ [Ben Laurie] *) Make DES key schedule conform to the usual scheme, as well as correcting its structure. This means that calls to DES functions now have to pass a pointer to a des_key_schedule instead of a plain des_key_schedule (which was actually always a pointer anyway): E.g., des_key_schedule ks; des_set_key_checked(..., &ks); des_ncbc_encrypt(..., &ks, ...); (Note that a later change renames 'des_...' into 'DES_...'.) [Ben Laurie] *) Initial reduction of linker bloat: the use of some functions, such as PEM causes large amounts of unused functions to be linked in due to poor organisation. For example pem_all.c contains every PEM function which has a knock on effect of linking in large amounts of (unused) ASN1 code. Grouping together similar functions and splitting unrelated functions prevents this. [Steve Henson] *) Cleanup of EVP macros. [Ben Laurie] *) Change historical references to {NID,SN,LN}_des_ede and ede3 to add the correct _ecb suffix. [Ben Laurie] *) Add initial OCSP responder support to ocsp application. The revocation information is handled using the text based index use by the ca application. The responder can either handle requests generated internally, supplied in files (for example via a CGI script) or using an internal minimal server. [Steve Henson] *) Add configuration choices to get zlib compression for TLS. [Richard Levitte] *) Changes to Kerberos SSL for RFC 2712 compliance: 1. Implemented real KerberosWrapper, instead of just using KRB5 AP_REQ message. [Thanks to Simon Wilkinson ] 2. Implemented optional authenticator field of KerberosWrapper. Added openssl-style ASN.1 macros for Kerberos ticket, ap_req, and authenticator structs; see crypto/krb5/. Generalized Kerberos calls to support multiple Kerberos libraries. [Vern Staats , Jeffrey Altman via Richard Levitte] *) Cause 'openssl speed' to use fully hard-coded DSA keys as it already does with RSA. testdsa.h now has 'priv_key/pub_key' values for each of the key sizes rather than having just parameters (and 'speed' generating keys each time). [Geoff Thorpe] *) Speed up EVP routines. Before: encrypt type 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes des-cbc 4408.85k 5560.51k 5778.46k 5862.20k 5825.16k des-cbc 4389.55k 5571.17k 5792.23k 5846.91k 5832.11k des-cbc 4394.32k 5575.92k 5807.44k 5848.37k 5841.30k decrypt des-cbc 3482.66k 5069.49k 5496.39k 5614.16k 5639.28k des-cbc 3480.74k 5068.76k 5510.34k 5609.87k 5635.52k des-cbc 3483.72k 5067.62k 5504.60k 5708.01k 5724.80k After: encrypt des-cbc 4660.16k 5650.19k 5807.19k 5827.13k 5783.32k decrypt des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k [Ben Laurie] *) Added the OS2-EMX target. ["Brian Havard" and Richard Levitte] *) Rewrite apps to use NCONF routines instead of the old CONF. New functions to support NCONF routines in extension code. New function CONF_set_nconf() to allow functions which take an NCONF to also handle the old LHASH structure: this means that the old CONF compatible routines can be retained (in particular wrt extensions) without having to duplicate the code. New function X509V3_add_ext_nconf_sk to add extensions to a stack. [Steve Henson] *) Enhance the general user interface with mechanisms for inner control and with possibilities to have yes/no kind of prompts. [Richard Levitte] *) Change all calls to low level digest routines in the library and applications to use EVP. Add missing calls to HMAC_cleanup() and don't assume HMAC_CTX can be copied using memcpy(). [Verdon Walker , Steve Henson] *) Add the possibility to control engines through control names but with arbitrary arguments instead of just a string. Change the key loaders to take a UI_METHOD instead of a callback function pointer. NOTE: this breaks binary compatibility with earlier versions of OpenSSL [engine]. Adapt the nCipher code for these new conditions and add a card insertion callback. [Richard Levitte] *) Enhance the general user interface with mechanisms to better support dialog box interfaces, application-defined prompts, the possibility to use defaults (for example default passwords from somewhere else) and interrupts/cancellations. [Richard Levitte] *) Tidy up PKCS#12 attribute handling. Add support for the CSP name attribute in PKCS#12 files, add new -CSP option to pkcs12 utility. [Steve Henson] *) Fix a memory leak in 'sk_dup()' in the case reallocation fails. (Also tidy up some unnecessarily weird code in 'sk_new()'). [Geoff, reported by Diego Tartara ] *) Change the key loading routines for ENGINEs to use the same kind callback (pem_password_cb) as all other routines that need this kind of callback. [Richard Levitte] *) Increase ENTROPY_NEEDED to 32 bytes, as Rijndael can operate with 256 bit (=32 byte) keys. Of course seeding with more entropy bytes than this minimum value is recommended. [Lutz Jaenicke] *) New random seeder for OpenVMS, using the system process statistics that are easily reachable. [Richard Levitte] *) Windows apparently can't transparently handle global variables defined in DLLs. Initialisations such as: const ASN1_ITEM *it = &ASN1_INTEGER_it; wont compile. This is used by the any applications that need to declare their own ASN1 modules. This was fixed by adding the option EXPORT_VAR_AS_FN to all Win32 platforms, although this isn't strictly needed for static libraries under Win32. [Steve Henson] *) New functions X509_PURPOSE_set() and X509_TRUST_set() to handle setting of purpose and trust fields. New X509_STORE trust and purpose functions and tidy up setting in other SSL functions. [Steve Henson] *) Add copies of X509_STORE_CTX fields and callbacks to X509_STORE structure. These are inherited by X509_STORE_CTX when it is initialised. This allows various defaults to be set in the X509_STORE structure (such as flags for CRL checking and custom purpose or trust settings) for functions which only use X509_STORE_CTX internally such as S/MIME. Modify X509_STORE_CTX_purpose_inherit() so it only sets purposes and trust settings if they are not set in X509_STORE. This allows X509_STORE purposes and trust (in S/MIME for example) to override any set by default. Add command line options for CRL checking to smime, s_client and s_server applications. [Steve Henson] *) Initial CRL based revocation checking. If the CRL checking flag(s) are set then the CRL is looked up in the X509_STORE structure and its validity and signature checked, then if the certificate is found in the CRL the verify fails with a revoked error. Various new CRL related callbacks added to X509_STORE_CTX structure. Command line options added to 'verify' application to support this. This needs some additional work, such as being able to handle multiple CRLs with different times, extension based lookup (rather than just by subject name) and ultimately more complete V2 CRL extension handling. [Steve Henson] *) Add a general user interface API (crypto/ui/). This is designed to replace things like des_read_password and friends (backward compatibility functions using this new API are provided). The purpose is to remove prompting functions from the DES code section as well as provide for prompting through dialog boxes in a window system and the like. [Richard Levitte] *) Add "ex_data" support to ENGINE so implementations can add state at a per-structure level rather than having to store it globally. [Geoff] *) Make it possible for ENGINE structures to be copied when retrieved by ENGINE_by_id() if the ENGINE specifies a new flag: ENGINE_FLAGS_BY_ID_COPY. This causes the "original" ENGINE structure to act like a template, analogous to the RSA vs. RSA_METHOD type of separation. Because of this operational state can be localised to each ENGINE structure, despite the fact they all share the same "methods". New ENGINE structures returned in this case have no functional references and the return value is the single structural reference. This matches the single structural reference returned by ENGINE_by_id() normally, when it is incremented on the pre-existing ENGINE structure. [Geoff] *) Fix ASN1 decoder when decoding type ANY and V_ASN1_OTHER: since this needs to match any other type at all we need to manually clear the tag cache. [Steve Henson] *) Changes to the "openssl engine" utility to include; - verbosity levels ('-v', '-vv', and '-vvv') that provide information about an ENGINE's available control commands. - executing control commands from command line arguments using the '-pre' and '-post' switches. '-post' is only used if '-t' is specified and the ENGINE is successfully initialised. The syntax for the individual commands are colon-separated, for example; openssl engine chil -pre FORK_CHECK:0 -pre SO_PATH:/lib/test.so [Geoff] *) New dynamic control command support for ENGINEs. ENGINEs can now declare their own commands (numbers), names (strings), descriptions, and input types for run-time discovery by calling applications. A subset of these commands are implicitly classed as "executable" depending on their input type, and only these can be invoked through the new string-based API function ENGINE_ctrl_cmd_string(). (Eg. this can be based on user input, config files, etc). The distinction is that "executable" commands cannot return anything other than a boolean result and can only support numeric or string input, whereas some discoverable commands may only be for direct use through ENGINE_ctrl(), eg. supporting the exchange of binary data, function pointers, or other custom uses. The "executable" commands are to support parameterisations of ENGINE behaviour that can be unambiguously defined by ENGINEs and used consistently across any OpenSSL-based application. Commands have been added to all the existing hardware-supporting ENGINEs, noticeably "SO_PATH" to allow control over shared-library paths without source code alterations. [Geoff] *) Changed all ENGINE implementations to dynamically allocate their ENGINEs rather than declaring them statically. Apart from this being necessary with the removal of the ENGINE_FLAGS_MALLOCED distinction, this also allows the implementations to compile without using the internal engine_int.h header. [Geoff] *) Minor adjustment to "rand" code. RAND_get_rand_method() now returns a 'const' value. Any code that should be able to modify a RAND_METHOD should already have non-const pointers to it (ie. they should only modify their own ones). [Geoff] *) Made a variety of little tweaks to the ENGINE code. - "atalla" and "ubsec" string definitions were moved from header files to C code. "nuron" string definitions were placed in variables rather than hard-coded - allowing parameterisation of these values later on via ctrl() commands. - Removed unused "#if 0"'d code. - Fixed engine list iteration code so it uses ENGINE_free() to release structural references. - Constified the RAND_METHOD element of ENGINE structures. - Constified various get/set functions as appropriate and added missing functions (including a catch-all ENGINE_cpy that duplicates all ENGINE values onto a new ENGINE except reference counts/state). - Removed NULL parameter checks in get/set functions. Setting a method or function to NULL is a way of cancelling out a previously set value. Passing a NULL ENGINE parameter is just plain stupid anyway and doesn't justify the extra error symbols and code. - Deprecate the ENGINE_FLAGS_MALLOCED define and move the area for flags from engine_int.h to engine.h. - Changed prototypes for ENGINE handler functions (init(), finish(), ctrl(), key-load functions, etc) to take an (ENGINE*) parameter. [Geoff] *) Implement binary inversion algorithm for BN_mod_inverse in addition to the algorithm using long division. The binary algorithm can be used only if the modulus is odd. On 32-bit systems, it is faster only for relatively small moduli (roughly 20-30% for 128-bit moduli, roughly 5-15% for 256-bit moduli), so we use it only for moduli up to 450 bits. In 64-bit environments, the binary algorithm appears to be advantageous for much longer moduli; here we use it for moduli up to 2048 bits. [Bodo Moeller] *) Rewrite CHOICE field setting in ASN1_item_ex_d2i(). The old code could not support the combine flag in choice fields. [Steve Henson] *) Add a 'copy_extensions' option to the 'ca' utility. This copies extensions from a certificate request to the certificate. [Steve Henson] *) Allow multiple 'certopt' and 'nameopt' options to be separated by commas. Add 'namopt' and 'certopt' options to the 'ca' config file: this allows the display of the certificate about to be signed to be customised, to allow certain fields to be included or excluded and extension details. The old system didn't display multicharacter strings properly, omitted fields not in the policy and couldn't display additional details such as extensions. [Steve Henson] *) Function EC_POINTs_mul for multiple scalar multiplication of an arbitrary number of elliptic curve points \sum scalars[i]*points[i], optionally including the generator defined for the EC_GROUP: scalar*generator + \sum scalars[i]*points[i]. EC_POINT_mul is a simple wrapper function for the typical case that the point list has just one item (besides the optional generator). [Bodo Moeller] *) First EC_METHODs for curves over GF(p): EC_GFp_simple_method() uses the basic BN_mod_mul and BN_mod_sqr operations and provides various method functions that can also operate with faster implementations of modular arithmetic. EC_GFp_mont_method() reuses most functions that are part of EC_GFp_simple_method, but uses Montgomery arithmetic. [Bodo Moeller; point addition and point doubling implementation directly derived from source code provided by Lenka Fibikova ] *) Framework for elliptic curves (crypto/ec/ec.h, crypto/ec/ec_lcl.h, crypto/ec/ec_lib.c): Curves are EC_GROUP objects (with an optional group generator) based on EC_METHODs that are built into the library. Points are EC_POINT objects based on EC_GROUP objects. Most of the framework would be able to handle curves over arbitrary finite fields, but as there are no obvious types for fields other than GF(p), some functions are limited to that for now. [Bodo Moeller] *) Add the -HTTP option to s_server. It is similar to -WWW, but requires that the file contains a complete HTTP response. [Richard Levitte] *) Add the ec directory to mkdef.pl and mkfiles.pl. In mkdef.pl change the def and num file printf format specifier from "%-40sXXX" to "%-39s XXX". The latter will always guarantee a space after the field while the former will cause them to run together if the field is 40 of more characters long. [Steve Henson] *) Constify the cipher and digest 'method' functions and structures and modify related functions to take constant EVP_MD and EVP_CIPHER pointers. [Steve Henson] *) Hide BN_CTX structure details in bn_lcl.h instead of publishing them in . Also further increase BN_CTX_NUM to 32. [Bodo Moeller] *) Modify EVP_Digest*() routines so they now return values. Although the internal software routines can never fail additional hardware versions might. [Steve Henson] *) Clean up crypto/err/err.h and change some error codes to avoid conflicts: Previously ERR_R_FATAL was too small and coincided with ERR_LIB_PKCS7 (= ERR_R_PKCS7_LIB); it is now 64 instead of 32. ASN1 error codes ERR_R_NESTED_ASN1_ERROR ... ERR_R_MISSING_ASN1_EOS were 4 .. 9, conflicting with ERR_LIB_RSA (= ERR_R_RSA_LIB) ... ERR_LIB_PEM (= ERR_R_PEM_LIB). They are now 58 .. 63 (i.e., just below ERR_R_FATAL). Add new error code 'ERR_R_INTERNAL_ERROR'. [Bodo Moeller] *) Don't overuse locks in crypto/err/err.c: For data retrieval, CRYPTO_r_lock suffices. [Bodo Moeller] *) New option '-subj arg' for 'openssl req' and 'openssl ca'. This sets the subject name for a new request or supersedes the subject name in a given request. Formats that can be parsed are 'CN=Some Name, OU=myOU, C=IT' and 'CN=Some Name/OU=myOU/C=IT'. Add options '-batch' and '-verbose' to 'openssl req'. [Massimiliano Pala ] *) Introduce the possibility to access global variables through functions on platform were that's the best way to handle exporting global variables in shared libraries. To enable this functionality, one must configure with "EXPORT_VAR_AS_FN" or defined the C macro "OPENSSL_EXPORT_VAR_AS_FUNCTION" in crypto/opensslconf.h (the latter is normally done by Configure or something similar). To implement a global variable, use the macro OPENSSL_IMPLEMENT_GLOBAL in the source file (foo.c) like this: OPENSSL_IMPLEMENT_GLOBAL(int,foo)=1; OPENSSL_IMPLEMENT_GLOBAL(double,bar); To declare a global variable, use the macros OPENSSL_DECLARE_GLOBAL and OPENSSL_GLOBAL_REF in the header file (foo.h) like this: OPENSSL_DECLARE_GLOBAL(int,foo); #define foo OPENSSL_GLOBAL_REF(foo) OPENSSL_DECLARE_GLOBAL(double,bar); #define bar OPENSSL_GLOBAL_REF(bar) The #defines are very important, and therefore so is including the header file everywhere where the defined globals are used. The macro OPENSSL_EXPORT_VAR_AS_FUNCTION also affects the definition of ASN.1 items, but that structure is a bit different. The largest change is in util/mkdef.pl which has been enhanced with better and easier to understand logic to choose which symbols should go into the Windows .def files as well as a number of fixes and code cleanup (among others, algorithm keywords are now sorted lexicographically to avoid constant rewrites). [Richard Levitte] *) In BN_div() keep a copy of the sign of 'num' before writing the result to 'rm' because if rm==num the value will be overwritten and produce the wrong result if 'num' is negative: this caused problems with BN_mod() and BN_nnmod(). [Steve Henson] *) Function OCSP_request_verify(). This checks the signature on an OCSP request and verifies the signer certificate. The signer certificate is just checked for a generic purpose and OCSP request trust settings. [Steve Henson] *) Add OCSP_check_validity() function to check the validity of OCSP responses. OCSP responses are prepared in real time and may only be a few seconds old. Simply checking that the current time lies between thisUpdate and nextUpdate max reject otherwise valid responses caused by either OCSP responder or client clock inaccuracy. Instead we allow thisUpdate and nextUpdate to fall within a certain period of the current time. The age of the response can also optionally be checked. Two new options -validity_period and -status_age added to ocsp utility. [Steve Henson] *) If signature or public key algorithm is unrecognized print out its OID rather that just UNKNOWN. [Steve Henson] *) Change OCSP_cert_to_id() to tolerate a NULL subject certificate and OCSP_cert_id_new() a NULL serialNumber. This allows a partial certificate ID to be generated from the issuer certificate alone which can then be passed to OCSP_id_issuer_cmp(). [Steve Henson] *) New compilation option ASN1_ITEM_FUNCTIONS. This causes the new ASN1 modules to export functions returning ASN1_ITEM pointers instead of the ASN1_ITEM structures themselves. This adds several new macros which allow the underlying ASN1 function/structure to be accessed transparently. As a result code should not use ASN1_ITEM references directly (such as &X509_it) but instead use the relevant macros (such as ASN1_ITEM_rptr(X509)). This option is to allow use of the new ASN1 code on platforms where exporting structures is problematical (for example in shared libraries) but exporting functions returning pointers to structures is not. [Steve Henson] *) Add support for overriding the generation of SSL/TLS session IDs. These callbacks can be registered either in an SSL_CTX or per SSL. The purpose of this is to allow applications to control, if they wish, the arbitrary values chosen for use as session IDs, particularly as it can be useful for session caching in multiple-server environments. A command-line switch for testing this (and any client code that wishes to use such a feature) has been added to "s_server". [Geoff Thorpe, Lutz Jaenicke] *) Modify mkdef.pl to recognise and parse preprocessor conditionals of the form '#if defined(...) || defined(...) || ...' and '#if !defined(...) && !defined(...) && ...'. This also avoids the growing number of special cases it was previously handling. [Richard Levitte] *) Make all configuration macros available for application by making sure they are available in opensslconf.h, by giving them names starting with "OPENSSL_" to avoid conflicts with other packages and by making sure e_os2.h will cover all platform-specific cases together with opensslconf.h. Additionally, it is now possible to define configuration/platform- specific names (called "system identities"). In the C code, these are prefixed with "OPENSSL_SYSNAME_". e_os2.h will create another macro with the name beginning with "OPENSSL_SYS_", which is determined from "OPENSSL_SYSNAME_*" or compiler-specific macros depending on what is available. [Richard Levitte] *) New option -set_serial to 'req' and 'x509' this allows the serial number to use to be specified on the command line. Previously self signed certificates were hard coded with serial number 0 and the CA options of 'x509' had to use a serial number in a file which was auto incremented. [Steve Henson] *) New options to 'ca' utility to support V2 CRL entry extensions. Currently CRL reason, invalidity date and hold instruction are supported. Add new CRL extensions to V3 code and some new objects. [Steve Henson] *) New function EVP_CIPHER_CTX_set_padding() this is used to disable standard block padding (aka PKCS#5 padding) in the EVP API, which was previously mandatory. This means that the data is not padded in any way and so the total length much be a multiple of the block size, otherwise an error occurs. [Steve Henson] *) Initial (incomplete) OCSP SSL support. [Steve Henson] *) New function OCSP_parse_url(). This splits up a URL into its host, port and path components: primarily to parse OCSP URLs. New -url option to ocsp utility. [Steve Henson] *) New nonce behavior. The return value of OCSP_check_nonce() now reflects the various checks performed. Applications can decide whether to tolerate certain situations such as an absent nonce in a response when one was present in a request: the ocsp application just prints out a warning. New function OCSP_add1_basic_nonce() this is to allow responders to include a nonce in a response even if the request is nonce-less. [Steve Henson] *) Disable stdin buffering in load_cert (apps/apps.c) so that no certs are skipped when using openssl x509 multiple times on a single input file, e.g. "(openssl x509 -out cert1; openssl x509 -out cert2) ] *) New OCSP verify flag OCSP_TRUSTOTHER. When set the "other" certificates passed by the function are trusted implicitly. If any of them signed the response then it is assumed to be valid and is not verified. [Steve Henson] *) In PKCS7_set_type() initialise content_type in PKCS7_ENC_CONTENT to data. This was previously part of the PKCS7 ASN1 code. This was causing problems with OpenSSL created PKCS#12 and PKCS#7 structures. [Steve Henson, reported by Kenneth R. Robinette ] *) Add CRYPTO_push_info() and CRYPTO_pop_info() calls to new ASN1 routines: without these tracing memory leaks is very painful. Fix leaks in PKCS12 and PKCS7 routines. [Steve Henson] *) Make X509_time_adj() cope with the new behaviour of ASN1_TIME_new(). Previously it initialised the 'type' argument to V_ASN1_UTCTIME which effectively meant GeneralizedTime would never be used. Now it is initialised to -1 but X509_time_adj() now has to check the value and use ASN1_TIME_set() if the value is not V_ASN1_UTCTIME or V_ASN1_GENERALIZEDTIME, without this it always uses GeneralizedTime. [Steve Henson, reported by Kenneth R. Robinette ] *) Fixes to BN_to_ASN1_INTEGER when bn is zero. This would previously result in a zero length in the ASN1_INTEGER structure which was not consistent with the structure when d2i_ASN1_INTEGER() was used and would cause ASN1_INTEGER_cmp() to fail. Enhance s2i_ASN1_INTEGER() to cope with hex and negative integers. Fix bug in i2a_ASN1_INTEGER() where it did not print out a minus for negative ASN1_INTEGER. [Steve Henson] *) Add summary printout to ocsp utility. The various functions which convert status values to strings have been renamed to: OCSP_response_status_str(), OCSP_cert_status_str() and OCSP_crl_reason_str() and are no longer static. New options to verify nonce values and to disable verification. OCSP response printout format cleaned up. [Steve Henson] *) Add additional OCSP certificate checks. These are those specified in RFC2560. This consists of two separate checks: the CA of the certificate being checked must either be the OCSP signer certificate or the issuer of the OCSP signer certificate. In the latter case the OCSP signer certificate must contain the OCSP signing extended key usage. This check is performed by attempting to match the OCSP signer or the OCSP signer CA to the issuerNameHash and issuerKeyHash in the OCSP_CERTID structures of the response. [Steve Henson] *) Initial OCSP certificate verification added to OCSP_basic_verify() and related routines. This uses the standard OpenSSL certificate verify routines to perform initial checks (just CA validity) and to obtain the certificate chain. Then additional checks will be performed on the chain. Currently the root CA is checked to see if it is explicitly trusted for OCSP signing. This is used to set a root CA as a global signing root: that is any certificate that chains to that CA is an acceptable OCSP signing certificate. [Steve Henson] *) New '-extfile ...' option to 'openssl ca' for reading X.509v3 extensions from a separate configuration file. As when reading extensions from the main configuration file, the '-extensions ...' option may be used for specifying the section to use. [Massimiliano Pala ] *) New OCSP utility. Allows OCSP requests to be generated or read. The request can be sent to a responder and the output parsed, outputed or printed in text form. Not complete yet: still needs to check the OCSP response validity. [Steve Henson] *) New subcommands for 'openssl ca': 'openssl ca -status ' prints the status of the cert with the given serial number (according to the index file). 'openssl ca -updatedb' updates the expiry status of certificates in the index file. [Massimiliano Pala ] *) New '-newreq-nodes' command option to CA.pl. This is like '-newreq', but calls 'openssl req' with the '-nodes' option so that the resulting key is not encrypted. [Damien Miller ] *) New configuration for the GNU Hurd. [Jonathan Bartlett via Richard Levitte] *) Initial code to implement OCSP basic response verify. This is currently incomplete. Currently just finds the signer's certificate and verifies the signature on the response. [Steve Henson] *) New SSLeay_version code SSLEAY_DIR to determine the compiled-in value of OPENSSLDIR. This is available via the new '-d' option to 'openssl version', and is also included in 'openssl version -a'. [Bodo Moeller] *) Allowing defining memory allocation callbacks that will be given file name and line number information in additional arguments (a const char* and an int). The basic functionality remains, as well as the original possibility to just replace malloc(), realloc() and free() by functions that do not know about these additional arguments. To register and find out the current settings for extended allocation functions, the following functions are provided: CRYPTO_set_mem_ex_functions CRYPTO_set_locked_mem_ex_functions CRYPTO_get_mem_ex_functions CRYPTO_get_locked_mem_ex_functions These work the same way as CRYPTO_set_mem_functions and friends. CRYPTO_get_[locked_]mem_functions now writes 0 where such an extended allocation function is enabled. Similarly, CRYPTO_get_[locked_]mem_ex_functions writes 0 where a conventional allocation function is enabled. [Richard Levitte, Bodo Moeller] *) Finish off removing the remaining LHASH function pointer casts. There should no longer be any prototype-casting required when using the LHASH abstraction, and any casts that remain are "bugs". See the callback types and macros at the head of lhash.h for details (and "OBJ_cleanup" in crypto/objects/obj_dat.c as an example). [Geoff Thorpe] *) Add automatic query of EGD sockets in RAND_poll() for the unix variant. If /dev/[u]random devices are not available or do not return enough entropy, EGD style sockets (served by EGD or PRNGD) will automatically be queried. The locations /var/run/egd-pool, /dev/egd-pool, /etc/egd-pool, and /etc/entropy will be queried once each in this sequence, quering stops when enough entropy was collected without querying more sockets. [Lutz Jaenicke] *) Change the Unix RAND_poll() variant to be able to poll several random devices, as specified by DEVRANDOM, until a sufficient amount of data has been collected. We spend at most 10 ms on each file (select timeout) and read in non-blocking mode. DEVRANDOM now defaults to the list "/dev/urandom", "/dev/random", "/dev/srandom" (previously it was just the string "/dev/urandom"), so on typical platforms the 10 ms delay will never occur. Also separate out the Unix variant to its own file, rand_unix.c. For VMS, there's a currently-empty rand_vms.c. [Richard Levitte] *) Move OCSP client related routines to ocsp_cl.c. These provide utility functions which an application needing to issue a request to an OCSP responder and analyse the response will typically need: as opposed to those which an OCSP responder itself would need which will be added later. OCSP_request_sign() signs an OCSP request with an API similar to PKCS7_sign(). OCSP_response_status() returns status of OCSP response. OCSP_response_get1_basic() extracts basic response from response. OCSP_resp_find_status(): finds and extracts status information from an OCSP_CERTID structure (which will be created when the request structure is built). These are built from lower level functions which work on OCSP_SINGLERESP structures but wont normally be used unless the application wishes to examine extensions in the OCSP response for example. Replace nonce routines with a pair of functions. OCSP_request_add1_nonce() adds a nonce value and optionally generates a random value. OCSP_check_nonce() checks the validity of the nonce in an OCSP response. [Steve Henson] *) Change function OCSP_request_add() to OCSP_request_add0_id(). This doesn't copy the supplied OCSP_CERTID and avoids the need to free up the newly created id. Change return type to OCSP_ONEREQ to return the internal OCSP_ONEREQ structure. This can then be used to add extensions to the request. Deleted OCSP_request_new(), since most of its functionality is now in OCSP_REQUEST_new() (and the case insensitive name clash) apart from the ability to set the request name which will be added elsewhere. [Steve Henson] *) Update OCSP API. Remove obsolete extensions argument from various functions. Extensions are now handled using the new OCSP extension code. New simple OCSP HTTP function which can be used to send requests and parse the response. [Steve Henson] *) Fix the PKCS#7 (S/MIME) code to work with new ASN1. Two new ASN1_ITEM structures help with sign and verify. PKCS7_ATTR_SIGN uses the special reorder version of SET OF to sort the attributes and reorder them to match the encoded order. This resolves a long standing problem: a verify on a PKCS7 structure just after signing it used to fail because the attribute order did not match the encoded order. PKCS7_ATTR_VERIFY does not reorder the attributes: it uses the received order. This is necessary to tolerate some broken software that does not order SET OF. This is handled by encoding as a SEQUENCE OF but using implicit tagging (with UNIVERSAL class) to produce the required SET OF. [Steve Henson] *) Have mk1mf.pl generate the macros OPENSSL_BUILD_SHLIBCRYPTO and OPENSSL_BUILD_SHLIBSSL and use them appropriately in the header files to get correct declarations of the ASN.1 item variables. [Richard Levitte] *) Rewrite of PKCS#12 code to use new ASN1 functionality. Replace many PKCS#12 macros with real functions. Fix two unrelated ASN1 bugs: asn1_check_tlen() would sometimes attempt to use 'ctx' when it was NULL and ASN1_TYPE was not dereferenced properly in asn1_ex_c2i(). New ASN1 macro: DECLARE_ASN1_ITEM() which just declares the relevant ASN1_ITEM and no wrapper functions. [Steve Henson] *) New functions or ASN1_item_d2i_fp() and ASN1_item_d2i_bio(). These replace the old function pointer based I/O routines. Change most of the *_d2i_bio() and *_d2i_fp() functions to use these. [Steve Henson] *) Enhance mkdef.pl to be more accepting about spacing in C preprocessor lines, recognice more "algorithms" that can be deselected, and make it complain about algorithm deselection that isn't recognised. [Richard Levitte] *) New ASN1 functions to handle dup, sign, verify, digest, pack and unpack operations in terms of ASN1_ITEM. Modify existing wrappers to use new functions. Add NO_ASN1_OLD which can be set to remove some old style ASN1 functions: this can be used to determine if old code will still work when these eventually go away. [Steve Henson] *) New extension functions for OCSP structures, these follow the same conventions as certificates and CRLs. [Steve Henson] *) New function X509V3_add1_i2d(). This automatically encodes and adds an extension. Its behaviour can be customised with various flags to append, replace or delete. Various wrappers added for certifcates and CRLs. [Steve Henson] *) Fix to avoid calling the underlying ASN1 print routine when an extension cannot be parsed. Correct a typo in the OCSP_SERVICELOC extension. Tidy up print OCSP format. [Steve Henson] *) Make mkdef.pl parse some of the ASN1 macros and add apropriate entries for variables. [Steve Henson] *) Add functionality to apps/openssl.c for detecting locking problems: As the program is single-threaded, all we have to do is register a locking callback using an array for storing which locks are currently held by the program. [Bodo Moeller] *) Use a lock around the call to CRYPTO_get_ex_new_index() in SSL_get_ex_data_X509_STORE_idx(), which is used in ssl_verify_cert_chain() and thus can be called at any time during TLS/SSL handshakes so that thread-safety is essential. Unfortunately, the ex_data design is not at all suited for multi-threaded use, so it probably should be abolished. [Bodo Moeller] *) Added Broadcom "ubsec" ENGINE to OpenSSL. [Broadcom, tweaked and integrated by Geoff Thorpe] *) Move common extension printing code to new function X509V3_print_extensions(). Reorganise OCSP print routines and implement some needed OCSP ASN1 functions. Add OCSP extensions. [Steve Henson] *) New function X509_signature_print() to remove duplication in some print routines. [Steve Henson] *) Add a special meaning when SET OF and SEQUENCE OF flags are both set (this was treated exactly the same as SET OF previously). This is used to reorder the STACK representing the structure to match the encoding. This will be used to get round a problem where a PKCS7 structure which was signed could not be verified because the STACK order did not reflect the encoded order. [Steve Henson] *) Reimplement the OCSP ASN1 module using the new code. [Steve Henson] *) Update the X509V3 code to permit the use of an ASN1_ITEM structure for its ASN1 operations. The old style function pointers still exist for now but they will eventually go away. [Steve Henson] *) Merge in replacement ASN1 code from the ASN1 branch. This almost completely replaces the old ASN1 functionality with a table driven encoder and decoder which interprets an ASN1_ITEM structure describing the ASN1 module. Compatibility with the existing ASN1 API (i2d,d2i) is largely maintained. Almost all of the old asn1_mac.h macro based ASN1 has also been converted to the new form. [Steve Henson] *) Change BN_mod_exp_recp so that negative moduli are tolerated (the sign is ignored). Similarly, ignore the sign in BN_MONT_CTX_set so that BN_mod_exp_mont and BN_mod_exp_mont_word work for negative moduli. [Bodo Moeller] *) Fix BN_uadd and BN_usub: Always return non-negative results instead of not touching the result's sign bit. [Bodo Moeller] *) BN_div bugfix: If the result is 0, the sign (res->neg) must not be set. [Bodo Moeller] *) Changed the LHASH code to use prototypes for callbacks, and created macros to declare and implement thin (optionally static) functions that provide type-safety and avoid function pointer casting for the type-specific callbacks. [Geoff Thorpe] *) Added Kerberos Cipher Suites to be used with TLS, as written in RFC 2712. [Veers Staats , Jeffrey Altman , via Richard Levitte] *) Reformat the FAQ so the different questions and answers can be divided in sections depending on the subject. [Richard Levitte] *) Have the zlib compression code load ZLIB.DLL dynamically under Windows. [Richard Levitte] *) New function BN_mod_sqrt for computing square roots modulo a prime (using the probabilistic Tonelli-Shanks algorithm unless p == 3 (mod 4) or p == 5 (mod 8), which are cases that can be handled deterministically). [Lenka Fibikova , Bodo Moeller] *) Make BN_mod_inverse faster by explicitly handling small quotients in the Euclid loop. (Speed gain about 20% for small moduli [256 or 512 bits], about 30% for larger ones [1024 or 2048 bits].) [Bodo Moeller] *) New function BN_kronecker. [Bodo Moeller] *) Fix BN_gcd so that it works on negative inputs; the result is positive unless both parameters are zero. Previously something reasonably close to an infinite loop was possible because numbers could be growing instead of shrinking in the implementation of Euclid's algorithm. [Bodo Moeller] *) Fix BN_is_word() and BN_is_one() macros to take into account the sign of the number in question. Fix BN_is_word(a,w) to work correctly for w == 0. The old BN_is_word(a,w) macro is now called BN_abs_is_word(a,w) because its test if the absolute value of 'a' equals 'w'. Note that BN_abs_is_word does *not* handle w == 0 reliably; it exists mostly for use in the implementations of BN_is_zero(), BN_is_one(), and BN_is_word(). [Bodo Moeller] *) New function BN_swap. [Bodo Moeller] *) Use BN_nnmod instead of BN_mod in crypto/bn/bn_exp.c so that the exponentiation functions are more likely to produce reasonable results on negative inputs. [Bodo Moeller] *) Change BN_mod_mul so that the result is always non-negative. Previously, it could be negative if one of the factors was negative; I don't think anyone really wanted that behaviour. [Bodo Moeller] *) Move BN_mod_... functions into new file crypto/bn/bn_mod.c (except for exponentiation, which stays in crypto/bn/bn_exp.c, and BN_mod_mul_reciprocal, which stays in crypto/bn/bn_recp.c) and add new functions: BN_nnmod BN_mod_sqr BN_mod_add BN_mod_add_quick BN_mod_sub BN_mod_sub_quick BN_mod_lshift1 BN_mod_lshift1_quick BN_mod_lshift BN_mod_lshift_quick These functions always generate non-negative results. BN_nnmod otherwise is like BN_mod (if BN_mod computes a remainder r such that |m| < r < 0, BN_nnmod will output rem + |m| instead). BN_mod_XXX_quick(r, a, [b,] m) generates the same result as BN_mod_XXX(r, a, [b,] m, ctx), but requires that a [and b] be reduced modulo m. [Lenka Fibikova , Bodo Moeller] #if 0 The following entry accidentily appeared in the CHANGES file distributed with OpenSSL 0.9.7. The modifications described in it do *not* apply to OpenSSL 0.9.7. *) Remove a few calls to bn_wexpand() in BN_sqr() (the one in there was actually never needed) and in BN_mul(). The removal in BN_mul() required a small change in bn_mul_part_recursive() and the addition of the functions bn_cmp_part_words(), bn_sub_part_words() and bn_add_part_words(), which do the same thing as bn_cmp_words(), bn_sub_words() and bn_add_words() except they take arrays with differing sizes. [Richard Levitte] #endif *) In 'openssl passwd', verify passwords read from the terminal unless the '-salt' option is used (which usually means that verification would just waste user's time since the resulting hash is going to be compared with some given password hash) or the new '-noverify' option is used. This is an incompatible change, but it does not affect non-interactive use of 'openssl passwd' (passwords on the command line, '-stdin' option, '-in ...' option) and thus should not cause any problems. [Bodo Moeller] *) Remove all references to RSAref, since there's no more need for it. [Richard Levitte] *) Make DSO load along a path given through an environment variable (SHLIB_PATH) with shl_load(). [Richard Levitte] *) Constify the ENGINE code as a result of BIGNUM constification. Also constify the RSA code and most things related to it. In a few places, most notable in the depth of the ASN.1 code, ugly casts back to non-const were required (to be solved at a later time) [Richard Levitte] *) Make it so the openssl application has all engines loaded by default. [Richard Levitte] *) Constify the BIGNUM routines a little more. [Richard Levitte] *) Add the following functions: ENGINE_load_cswift() ENGINE_load_chil() ENGINE_load_atalla() ENGINE_load_nuron() ENGINE_load_builtin_engines() That way, an application can itself choose if external engines that are built-in in OpenSSL shall ever be used or not. The benefit is that applications won't have to be linked with libdl or other dso libraries unless it's really needed. Changed 'openssl engine' to load all engines on demand. Changed the engine header files to avoid the duplication of some declarations (they differed!). [Richard Levitte] *) 'openssl engine' can now list capabilities. [Richard Levitte] *) Better error reporting in 'openssl engine'. [Richard Levitte] *) Never call load_dh_param(NULL) in s_server. [Bodo Moeller] *) Add engine application. It can currently list engines by name and identity, and test if they are actually available. [Richard Levitte] *) Improve RPM specification file by forcing symbolic linking and making sure the installed documentation is also owned by root.root. [Damien Miller ] *) Give the OpenSSL applications more possibilities to make use of keys (public as well as private) handled by engines. [Richard Levitte] *) Add OCSP code that comes from CertCo. [Richard Levitte] *) Add VMS support for the Rijndael code. [Richard Levitte] *) Added untested support for Nuron crypto accelerator. [Ben Laurie] *) Add support for external cryptographic devices. This code was previously distributed separately as the "engine" branch. [Geoff Thorpe, Richard Levitte] *) Rework the filename-translation in the DSO code. It is now possible to have far greater control over how a "name" is turned into a filename depending on the operating environment and any oddities about the different shared library filenames on each system. [Geoff Thorpe] *) Support threads on FreeBSD-elf in Configure. [Richard Levitte] *) Fix for SHA1 assembly problem with MASM: it produces warnings about corrupt line number information when assembling with debugging information. This is caused by the overlapping of two sections. [Bernd Matthes , Steve Henson] *) NCONF changes. NCONF_get_number() has no error checking at all. As a replacement, NCONF_get_number_e() is defined (_e for "error checking") and is promoted strongly. The old NCONF_get_number is kept around for binary backward compatibility. Make it possible for methods to load from something other than a BIO, by providing a function pointer that is given a name instead of a BIO. For example, this could be used to load configuration data from an LDAP server. [Richard Levitte] *) Fix for non blocking accept BIOs. Added new I/O special reason BIO_RR_ACCEPT to cover this case. Previously use of accept BIOs with non blocking I/O was not possible because no retry code was implemented. Also added new SSL code SSL_WANT_ACCEPT to cover this case. [Steve Henson] *) Added the beginnings of Rijndael support. [Ben Laurie] *) Fix for bug in DirectoryString mask setting. Add support for X509_NAME_print_ex() in 'req' and X509_print_ex() function to allow certificate printing to more controllable, additional 'certopt' option to 'x509' to allow new printing options to be set. [Steve Henson] *) Clean old EAY MD5 hack from e_os.h. [Richard Levitte] Changes between 0.9.6l and 0.9.6m [17 Mar 2004] *) Fix null-pointer assignment in do_change_cipher_spec() revealed by using the Codenomicon TLS Test Tool (CVE-2004-0079) [Joe Orton, Steve Henson] Changes between 0.9.6k and 0.9.6l [04 Nov 2003] *) Fix additional bug revealed by the NISCC test suite: Stop bug triggering large recursion when presented with certain ASN.1 tags (CVE-2003-0851) [Steve Henson] Changes between 0.9.6j and 0.9.6k [30 Sep 2003] *) Fix various bugs revealed by running the NISCC test suite: Stop out of bounds reads in the ASN1 code when presented with invalid tags (CVE-2003-0543 and CVE-2003-0544). If verify callback ignores invalid public key errors don't try to check certificate signature with the NULL public key. [Steve Henson] *) In ssl3_accept() (ssl/s3_srvr.c) only accept a client certificate if the server requested one: as stated in TLS 1.0 and SSL 3.0 specifications. [Steve Henson] *) In ssl3_get_client_hello() (ssl/s3_srvr.c), tolerate additional extra data after the compression methods not only for TLS 1.0 but also for SSL 3.0 (as required by the specification). [Bodo Moeller; problem pointed out by Matthias Loepfe] *) Change X509_certificate_type() to mark the key as exported/exportable when it's 512 *bits* long, not 512 bytes. [Richard Levitte] Changes between 0.9.6i and 0.9.6j [10 Apr 2003] *) Countermeasure against the Klima-Pokorny-Rosa extension of Bleichbacher's attack on PKCS #1 v1.5 padding: treat a protocol version number mismatch like a decryption error in ssl3_get_client_key_exchange (ssl/s3_srvr.c). [Bodo Moeller] *) Turn on RSA blinding by default in the default implementation to avoid a timing attack. Applications that don't want it can call RSA_blinding_off() or use the new flag RSA_FLAG_NO_BLINDING. They would be ill-advised to do so in most cases. [Ben Laurie, Steve Henson, Geoff Thorpe, Bodo Moeller] *) Change RSA blinding code so that it works when the PRNG is not seeded (in this case, the secret RSA exponent is abused as an unpredictable seed -- if it is not unpredictable, there is no point in blinding anyway). Make RSA blinding thread-safe by remembering the creator's thread ID in rsa->blinding and having all other threads use local one-time blinding factors (this requires more computation than sharing rsa->blinding, but avoids excessive locking; and if an RSA object is not shared between threads, blinding will still be very fast). [Bodo Moeller] Changes between 0.9.6h and 0.9.6i [19 Feb 2003] *) In ssl3_get_record (ssl/s3_pkt.c), minimize information leaked via timing by performing a MAC computation even if incorrrect block cipher padding has been found. This is a countermeasure against active attacks where the attacker has to distinguish between bad padding and a MAC verification error. (CVE-2003-0078) [Bodo Moeller; problem pointed out by Brice Canvel (EPFL), Alain Hiltgen (UBS), Serge Vaudenay (EPFL), and Martin Vuagnoux (EPFL, Ilion)] Changes between 0.9.6g and 0.9.6h [5 Dec 2002] *) New function OPENSSL_cleanse(), which is used to cleanse a section of memory from it's contents. This is done with a counter that will place alternating values in each byte. This can be used to solve two issues: 1) the removal of calls to memset() by highly optimizing compilers, and 2) cleansing with other values than 0, since those can be read through on certain media, for example a swap space on disk. [Geoff Thorpe] *) Bugfix: client side session caching did not work with external caching, because the session->cipher setting was not restored when reloading from the external cache. This problem was masked, when SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG (part of SSL_OP_ALL) was set. (Found by Steve Haslam .) [Lutz Jaenicke] *) Fix client_certificate (ssl/s2_clnt.c): The permissible total length of the REQUEST-CERTIFICATE message is 18 .. 34, not 17 .. 33. [Zeev Lieber ] *) Undo an undocumented change introduced in 0.9.6e which caused repeated calls to OpenSSL_add_all_ciphers() and OpenSSL_add_all_digests() to be ignored, even after calling EVP_cleanup(). [Richard Levitte] *) Change the default configuration reader to deal with last line not being properly terminated. [Richard Levitte] *) Change X509_NAME_cmp() so it applies the special rules on handling DN values that are of type PrintableString, as well as RDNs of type emailAddress where the value has the type ia5String. [stefank@valicert.com via Richard Levitte] *) Add a SSL_SESS_CACHE_NO_INTERNAL_STORE flag to take over half the job SSL_SESS_CACHE_NO_INTERNAL_LOOKUP was inconsistently doing, define a new flag (SSL_SESS_CACHE_NO_INTERNAL) to be the bitwise-OR of the two for use by the majority of applications wanting this behaviour, and update the docs. The documented behaviour and actual behaviour were inconsistent and had been changing anyway, so this is more a bug-fix than a behavioural change. [Geoff Thorpe, diagnosed by Nadav Har'El] *) Don't impose a 16-byte length minimum on session IDs in ssl/s3_clnt.c (the SSL 3.0 and TLS 1.0 specifications allow any length up to 32 bytes). [Bodo Moeller] *) Fix initialization code race conditions in SSLv23_method(), SSLv23_client_method(), SSLv23_server_method(), SSLv2_method(), SSLv2_client_method(), SSLv2_server_method(), SSLv3_method(), SSLv3_client_method(), SSLv3_server_method(), TLSv1_method(), TLSv1_client_method(), TLSv1_server_method(), ssl2_get_cipher_by_char(), ssl3_get_cipher_by_char(). [Patrick McCormick , Bodo Moeller] *) Reorder cleanup sequence in SSL_CTX_free(): only remove the ex_data after the cached sessions are flushed, as the remove_cb() might use ex_data contents. Bug found by Sam Varshavchik (see [openssl.org #212]). [Geoff Thorpe, Lutz Jaenicke] *) Fix typo in OBJ_txt2obj which incorrectly passed the content length, instead of the encoding length to d2i_ASN1_OBJECT. [Steve Henson] Changes between 0.9.6f and 0.9.6g [9 Aug 2002] *) [In 0.9.6g-engine release:] Fix crypto/engine/vendor_defns/cswift.h for WIN32 (use '_stdcall'). [Lynn Gazis ] Changes between 0.9.6e and 0.9.6f [8 Aug 2002] *) Fix ASN1 checks. Check for overflow by comparing with LONG_MAX and get fix the header length calculation. [Florian Weimer , Alon Kantor (and others), Steve Henson] *) Use proper error handling instead of 'assertions' in buffer overflow checks added in 0.9.6e. This prevents DoS (the assertions could call abort()). [Arne Ansper , Bodo Moeller] Changes between 0.9.6d and 0.9.6e [30 Jul 2002] *) Add various sanity checks to asn1_get_length() to reject the ASN1 length bytes if they exceed sizeof(long), will appear negative or the content length exceeds the length of the supplied buffer. [Steve Henson, Adi Stav , James Yonan ] *) Fix cipher selection routines: ciphers without encryption had no flags for the cipher strength set and where therefore not handled correctly by the selection routines (PR #130). [Lutz Jaenicke] *) Fix EVP_dsa_sha macro. [Nils Larsch] *) New option SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS for disabling the SSL 3.0/TLS 1.0 CBC vulnerability countermeasure that was added in OpenSSL 0.9.6d. As the countermeasure turned out to be incompatible with some broken SSL implementations, the new option is part of SSL_OP_ALL. SSL_OP_ALL is usually employed when compatibility with weird SSL implementations is desired (e.g. '-bugs' option to 's_client' and 's_server'), so the new option is automatically set in many applications. [Bodo Moeller] *) Changes in security patch: Changes marked "(CHATS)" were sponsored by the Defense Advanced Research Projects Agency (DARPA) and Air Force Research Laboratory, Air Force Materiel Command, USAF, under agreement number F30602-01-2-0537. *) Add various sanity checks to asn1_get_length() to reject the ASN1 length bytes if they exceed sizeof(long), will appear negative or the content length exceeds the length of the supplied buffer. (CVE-2002-0659) [Steve Henson, Adi Stav , James Yonan ] *) Assertions for various potential buffer overflows, not known to happen in practice. [Ben Laurie (CHATS)] *) Various temporary buffers to hold ASCII versions of integers were too small for 64 bit platforms. (CVE-2002-0655) [Matthew Byng-Maddick and Ben Laurie (CHATS)> *) Remote buffer overflow in SSL3 protocol - an attacker could supply an oversized session ID to a client. (CVE-2002-0656) [Ben Laurie (CHATS)] *) Remote buffer overflow in SSL2 protocol - an attacker could supply an oversized client master key. (CVE-2002-0656) [Ben Laurie (CHATS)] Changes between 0.9.6c and 0.9.6d [9 May 2002] *) Fix crypto/asn1/a_sign.c so that 'parameters' is omitted (not encoded as NULL) with id-dsa-with-sha1. [Nils Larsch ; problem pointed out by Bodo Moeller] *) Check various X509_...() return values in apps/req.c. [Nils Larsch ] *) Fix BASE64 decode (EVP_DecodeUpdate) for data with CR/LF ended lines: an end-of-file condition would erronously be flagged, when the CRLF was just at the end of a processed block. The bug was discovered when processing data through a buffering memory BIO handing the data to a BASE64-decoding BIO. Bug fund and patch submitted by Pavel Tsekov and Nedelcho Stanev. [Lutz Jaenicke] *) Implement a countermeasure against a vulnerability recently found in CBC ciphersuites in SSL 3.0/TLS 1.0: Send an empty fragment before application data chunks to avoid the use of known IVs with data potentially chosen by the attacker. [Bodo Moeller] *) Fix length checks in ssl3_get_client_hello(). [Bodo Moeller] *) TLS/SSL library bugfix: use s->s3->in_read_app_data differently to prevent ssl3_read_internal() from incorrectly assuming that ssl3_read_bytes() found application data while handshake processing was enabled when in fact s->s3->in_read_app_data was merely automatically cleared during the initial handshake. [Bodo Moeller; problem pointed out by Arne Ansper ] *) Fix object definitions for Private and Enterprise: they were not recognized in their shortname (=lowercase) representation. Extend obj_dat.pl to issue an error when using undefined keywords instead of silently ignoring the problem (Svenning Sorensen ). [Lutz Jaenicke] *) Fix DH_generate_parameters() so that it works for 'non-standard' generators, i.e. generators other than 2 and 5. (Previously, the code did not properly initialise the 'add' and 'rem' values to BN_generate_prime().) In the new general case, we do not insist that 'generator' is actually a primitive root: This requirement is rather pointless; a generator of the order-q subgroup is just as good, if not better. [Bodo Moeller] *) Map new X509 verification errors to alerts. Discovered and submitted by Tom Wu . [Lutz Jaenicke] *) Fix ssl3_pending() (ssl/s3_lib.c) to prevent SSL_pending() from returning non-zero before the data has been completely received when using non-blocking I/O. [Bodo Moeller; problem pointed out by John Hughes] *) Some of the ciphers missed the strength entry (SSL_LOW etc). [Ben Laurie, Lutz Jaenicke] *) Fix bug in SSL_clear(): bad sessions were not removed (found by Yoram Zahavi ). [Lutz Jaenicke] *) Add information about CygWin 1.3 and on, and preserve proper configuration for the versions before that. [Corinna Vinschen and Richard Levitte] *) Make removal from session cache (SSL_CTX_remove_session()) more robust: check whether we deal with a copy of a session and do not delete from the cache in this case. Problem reported by "Izhar Shoshani Levi" . [Lutz Jaenicke] *) Do not store session data into the internal session cache, if it is never intended to be looked up (SSL_SESS_CACHE_NO_INTERNAL_LOOKUP flag is set). Proposed by Aslam . [Lutz Jaenicke] *) Have ASN1_BIT_STRING_set_bit() really clear a bit when the requested value is 0. [Richard Levitte] *) [In 0.9.6d-engine release:] Fix a crashbug and a logic bug in hwcrhk_load_pubkey(). [Toomas Kiisk via Richard Levitte] *) Add the configuration target linux-s390x. [Neale Ferguson via Richard Levitte] *) The earlier bugfix for the SSL3_ST_SW_HELLO_REQ_C case of ssl3_accept (ssl/s3_srvr.c) incorrectly used a local flag variable as an indication that a ClientHello message has been received. As the flag value will be lost between multiple invocations of ssl3_accept when using non-blocking I/O, the function may not be aware that a handshake has actually taken place, thus preventing a new session from being added to the session cache. To avoid this problem, we now set s->new_session to 2 instead of using a local variable. [Lutz Jaenicke, Bodo Moeller] *) Bugfix: Return -1 from ssl3_get_server_done (ssl3/s3_clnt.c) if the SSL_R_LENGTH_MISMATCH error is detected. [Geoff Thorpe, Bodo Moeller] *) New 'shared_ldflag' column in Configure platform table. [Richard Levitte] *) Fix EVP_CIPHER_mode macro. ["Dan S. Camper" ] *) Fix ssl3_read_bytes (ssl/s3_pkt.c): To ignore messages of unknown type, we must throw them away by setting rr->length to 0. [D P Chang ] Changes between 0.9.6b and 0.9.6c [21 dec 2001] *) Fix BN_rand_range bug pointed out by Dominikus Scherkl . (The previous implementation worked incorrectly for those cases where range = 10..._2 and 3*range is two bits longer than range.) [Bodo Moeller] *) Only add signing time to PKCS7 structures if it is not already present. [Steve Henson] *) Fix crypto/objects/objects.h: "ld-ce" should be "id-ce", OBJ_ld_ce should be OBJ_id_ce. Also some ip-pda OIDs in crypto/objects/objects.txt were incorrect (cf. RFC 3039). [Matt Cooper, Frederic Giudicelli, Bodo Moeller] *) Release CRYPTO_LOCK_DYNLOCK when CRYPTO_destroy_dynlockid() returns early because it has nothing to do. [Andy Schneider ] *) [In 0.9.6c-engine release:] Fix mutex callback return values in crypto/engine/hw_ncipher.c. [Andy Schneider ] *) [In 0.9.6c-engine release:] Add support for Cryptographic Appliance's keyserver technology. (Use engine 'keyclient') [Cryptographic Appliances and Geoff Thorpe] *) Add a configuration entry for OS/390 Unix. The C compiler 'c89' is called via tools/c89.sh because arguments have to be rearranged (all '-L' options must appear before the first object modules). [Richard Shapiro ] *) [In 0.9.6c-engine release:] Add support for Broadcom crypto accelerator cards, backported from 0.9.7. [Broadcom, Nalin Dahyabhai , Mark Cox] *) [In 0.9.6c-engine release:] Add support for SureWare crypto accelerator cards from Baltimore Technologies. (Use engine 'sureware') [Baltimore Technologies and Mark Cox] *) [In 0.9.6c-engine release:] Add support for crypto accelerator cards from Accelerated Encryption Processing, www.aep.ie. (Use engine 'aep') [AEP Inc. and Mark Cox] *) Add a configuration entry for gcc on UnixWare. [Gary Benson ] *) Change ssl/s2_clnt.c and ssl/s2_srvr.c so that received handshake messages are stored in a single piece (fixed-length part and variable-length part combined) and fix various bugs found on the way. [Bodo Moeller] *) Disable caching in BIO_gethostbyname(), directly use gethostbyname() instead. BIO_gethostbyname() does not know what timeouts are appropriate, so entries would stay in cache even when they have become invalid. [Bodo Moeller; problem pointed out by Rich Salz *) Change ssl23_get_client_hello (ssl/s23_srvr.c) behaviour when faced with a pathologically small ClientHello fragment that does not contain client_version: Instead of aborting with an error, simply choose the highest available protocol version (i.e., TLS 1.0 unless it is disabled). In practice, ClientHello messages are never sent like this, but this change gives us strictly correct behaviour at least for TLS. [Bodo Moeller] *) Fix SSL handshake functions and SSL_clear() such that SSL_clear() never resets s->method to s->ctx->method when called from within one of the SSL handshake functions. [Bodo Moeller; problem pointed out by Niko Baric] *) In ssl3_get_client_hello (ssl/s3_srvr.c), generate a fatal alert (sent using the client's version number) if client_version is smaller than the protocol version in use. Also change ssl23_get_client_hello (ssl/s23_srvr.c) to select TLS 1.0 if the client demanded SSL 3.0 but only TLS 1.0 is enabled; then the client will at least see that alert. [Bodo Moeller] *) Fix ssl3_get_message (ssl/s3_both.c) to handle message fragmentation correctly. [Bodo Moeller] *) Avoid infinite loop in ssl3_get_message (ssl/s3_both.c) if a client receives HelloRequest while in a handshake. [Bodo Moeller; bug noticed by Andy Schneider ] *) Bugfix in ssl3_accept (ssl/s3_srvr.c): Case SSL3_ST_SW_HELLO_REQ_C should end in 'break', not 'goto end' which circuments various cleanups done in state SSL_ST_OK. But session related stuff must be disabled for SSL_ST_OK in the case that we just sent a HelloRequest. Also avoid some overhead by not calling ssl_init_wbio_buffer() before just sending a HelloRequest. [Bodo Moeller, Eric Rescorla ] *) Fix ssl/s3_enc.c, ssl/t1_enc.c and ssl/s3_pkt.c so that we don't reveal whether illegal block cipher padding was found or a MAC verification error occured. (Neither SSLerr() codes nor alerts are directly visible to potential attackers, but the information may leak via logfiles.) Similar changes are not required for the SSL 2.0 implementation because the number of padding bytes is sent in clear for SSL 2.0, and the extra bytes are just ignored. However ssl/s2_pkt.c failed to verify that the purported number of padding bytes is in the legal range. [Bodo Moeller] *) Add OpenUNIX-8 support including shared libraries (Boyd Lynn Gerber ). [Lutz Jaenicke] *) Improve RSA_padding_check_PKCS1_OAEP() check again to avoid 'wristwatch attack' using huge encoding parameters (cf. James H. Manger's CRYPTO 2001 paper). Note that the RSA_PKCS1_OAEP_PADDING case of RSA_private_decrypt() does not use encoding parameters and hence was not vulnerable. [Bodo Moeller] *) BN_sqr() bug fix. [Ulf Möller, reported by Jim Ellis ] *) Rabin-Miller test analyses assume uniformly distributed witnesses, so use BN_pseudo_rand_range() instead of using BN_pseudo_rand() followed by modular reduction. [Bodo Moeller; pointed out by Adam Young ] *) Add BN_pseudo_rand_range() with obvious functionality: BN_rand_range() equivalent based on BN_pseudo_rand() instead of BN_rand(). [Bodo Moeller] *) s3_srvr.c: allow sending of large client certificate lists (> 16 kB). This function was broken, as the check for a new client hello message to handle SGC did not allow these large messages. (Tracked down by "Douglas E. Engert" .) [Lutz Jaenicke] *) Add alert descriptions for TLSv1 to SSL_alert_desc_string[_long](). [Lutz Jaenicke] *) Fix buggy behaviour of BIO_get_num_renegotiates() and BIO_ctrl() for BIO_C_GET_WRITE_BUF_SIZE ("Stephen Hinton" ). [Lutz Jaenicke] *) Rework the configuration and shared library support for Tru64 Unix. The configuration part makes use of modern compiler features and still retains old compiler behavior for those that run older versions of the OS. The shared library support part includes a variant that uses the RPATH feature, and is available through the special configuration target "alpha-cc-rpath", which will never be selected automatically. [Tim Mooney via Richard Levitte] *) In ssl3_get_key_exchange (ssl/s3_clnt.c), call ssl3_get_message() with the same message size as in ssl3_get_certificate_request(). Otherwise, if no ServerKeyExchange message occurs, CertificateRequest messages might inadvertently be reject as too long. [Petr Lampa ] *) Enhanced support for IA-64 Unix platforms (well, Linux and HP-UX). [Andy Polyakov] *) Modified SSL library such that the verify_callback that has been set specificly for an SSL object with SSL_set_verify() is actually being used. Before the change, a verify_callback set with this function was ignored and the verify_callback() set in the SSL_CTX at the time of the call was used. New function X509_STORE_CTX_set_verify_cb() introduced to allow the necessary settings. [Lutz Jaenicke] *) Initialize static variable in crypto/dsa/dsa_lib.c and crypto/dh/dh_lib.c explicitly to NULL, as at least on Solaris 8 this seems not always to be done automatically (in contradiction to the requirements of the C standard). This made problems when used from OpenSSH. [Lutz Jaenicke] *) In OpenSSL 0.9.6a and 0.9.6b, crypto/dh/dh_key.c ignored dh->length and always used BN_rand_range(priv_key, dh->p). BN_rand_range() is not necessary for Diffie-Hellman, and this specific range makes Diffie-Hellman unnecessarily inefficient if dh->length (recommended exponent length) is much smaller than the length of dh->p. We could use BN_rand_range() if the order of the subgroup was stored in the DH structure, but we only have dh->length. So switch back to BN_rand(priv_key, l, ...) where 'l' is dh->length if this is defined, or BN_num_bits(dh->p)-1 otherwise. [Bodo Moeller] *) In RSA_eay_public_encrypt RSA_eay_private_decrypt RSA_eay_private_encrypt (signing) RSA_eay_public_decrypt (signature verification) (default implementations for RSA_public_encrypt, RSA_private_decrypt, RSA_private_encrypt, RSA_public_decrypt), always reject numbers >= n. [Bodo Moeller] *) In crypto/rand/md_rand.c, use a new short-time lock CRYPTO_LOCK_RAND2 to synchronize access to 'locking_thread'. This is necessary on systems where access to 'locking_thread' (an 'unsigned long' variable) is not atomic. [Bodo Moeller] *) In crypto/rand/md_rand.c, set 'locking_thread' to current thread's ID *before* setting the 'crypto_lock_rand' flag. The previous code had a race condition if 0 is a valid thread ID. [Travis Vitek ] *) Add support for shared libraries under Irix. [Albert Chin-A-Young ] *) Add configuration option to build on Linux on both big-endian and little-endian MIPS. [Ralf Baechle ] *) Add the possibility to create shared libraries on HP-UX. [Richard Levitte] Changes between 0.9.6a and 0.9.6b [9 Jul 2001] *) Change ssleay_rand_bytes (crypto/rand/md_rand.c) to avoid a SSLeay/OpenSSL PRNG weakness pointed out by Markku-Juhani O. Saarinen : PRNG state recovery was possible based on the output of one PRNG request appropriately sized to gain knowledge on 'md' followed by enough consecutive 1-byte PRNG requests to traverse all of 'state'. 1. When updating 'md_local' (the current thread's copy of 'md') during PRNG output generation, hash all of the previous 'md_local' value, not just the half used for PRNG output. 2. Make the number of bytes from 'state' included into the hash independent from the number of PRNG bytes requested. The first measure alone would be sufficient to avoid Markku-Juhani's attack. (Actually it had never occurred to me that the half of 'md_local' used for chaining was the half from which PRNG output bytes were taken -- I had always assumed that the secret half would be used.) The second measure makes sure that additional data from 'state' is never mixed into 'md_local' in small portions; this heuristically further strengthens the PRNG. [Bodo Moeller] *) Fix crypto/bn/asm/mips3.s. [Andy Polyakov] *) When only the key is given to "enc", the IV is undefined. Print out an error message in this case. [Lutz Jaenicke] *) Handle special case when X509_NAME is empty in X509 printing routines. [Steve Henson] *) In dsa_do_verify (crypto/dsa/dsa_ossl.c), verify that r and s are positive and less than q. [Bodo Moeller] *) Don't change *pointer in CRYPTO_add_lock() is add_lock_callback is used: it isn't thread safe and the add_lock_callback should handle that itself. [Paul Rose ] *) Verify that incoming data obeys the block size in ssl3_enc (ssl/s3_enc.c) and tls1_enc (ssl/t1_enc.c). [Bodo Moeller] *) Fix OAEP check. [Ulf Möller, Bodo Möller] *) The countermeasure against Bleichbacher's attack on PKCS #1 v1.5 RSA encryption was accidentally removed in s3_srvr.c in OpenSSL 0.9.5 when fixing the server behaviour for backwards-compatible 'client hello' messages. (Note that the attack is impractical against SSL 3.0 and TLS 1.0 anyway because length and version checking means that the probability of guessing a valid ciphertext is around 2^-40; see section 5 in Bleichenbacher's CRYPTO '98 paper.) Before 0.9.5, the countermeasure (hide the error by generating a random 'decryption result') did not work properly because ERR_clear_error() was missing, meaning that SSL_get_error() would detect the supposedly ignored error. Both problems are now fixed. [Bodo Moeller] *) In crypto/bio/bf_buff.c, increase DEFAULT_BUFFER_SIZE to 4096 (previously it was 1024). [Bodo Moeller] *) Fix for compatibility mode trust settings: ignore trust settings unless some valid trust or reject settings are present. [Steve Henson] *) Fix for blowfish EVP: its a variable length cipher. [Steve Henson] *) Fix various bugs related to DSA S/MIME verification. Handle missing parameters in DSA public key structures and return an error in the DSA routines if parameters are absent. [Steve Henson] *) In versions up to 0.9.6, RAND_file_name() resorted to file ".rnd" in the current directory if neither $RANDFILE nor $HOME was set. RAND_file_name() in 0.9.6a returned NULL in this case. This has caused some confusion to Windows users who haven't defined $HOME. Thus RAND_file_name() is changed again: e_os.h can define a DEFAULT_HOME, which will be used if $HOME is not set. For Windows, we use "C:"; on other platforms, we still require environment variables. *) Move 'if (!initialized) RAND_poll()' into regions protected by CRYPTO_LOCK_RAND. This is not strictly necessary, but avoids having multiple threads call RAND_poll() concurrently. [Bodo Moeller] *) In crypto/rand/md_rand.c, replace 'add_do_not_lock' flag by a combination of a flag and a thread ID variable. Otherwise while one thread is in ssleay_rand_bytes (which sets the flag), *other* threads can enter ssleay_add_bytes without obeying the CRYPTO_LOCK_RAND lock (and may even illegally release the lock that they do not hold after the first thread unsets add_do_not_lock). [Bodo Moeller] *) Change bctest again: '-x' expressions are not available in all versions of 'test'. [Bodo Moeller] Changes between 0.9.6 and 0.9.6a [5 Apr 2001] *) Fix a couple of memory leaks in PKCS7_dataDecode() [Steve Henson, reported by Heyun Zheng ] *) Change Configure and Makefiles to provide EXE_EXT, which will contain the default extension for executables, if any. Also, make the perl scripts that use symlink() to test if it really exists and use "cp" if it doesn't. All this made OpenSSL compilable and installable in CygWin. [Richard Levitte] *) Fix for asn1_GetSequence() for indefinite length constructed data. If SEQUENCE is length is indefinite just set c->slen to the total amount of data available. [Steve Henson, reported by shige@FreeBSD.org] [This change does not apply to 0.9.7.] *) Change bctest to avoid here-documents inside command substitution (workaround for FreeBSD /bin/sh bug). For compatibility with Ultrix, avoid shell functions (introduced in the bctest version that searches along $PATH). [Bodo Moeller] *) Rename 'des_encrypt' to 'des_encrypt1'. This avoids the clashes with des_encrypt() defined on some operating systems, like Solaris and UnixWare. [Richard Levitte] *) Check the result of RSA-CRT (see D. Boneh, R. DeMillo, R. Lipton: On the Importance of Eliminating Errors in Cryptographic Computations, J. Cryptology 14 (2001) 2, 101-119, http://theory.stanford.edu/~dabo/papers/faults.ps.gz). [Ulf Moeller] *) MIPS assembler BIGNUM division bug fix. [Andy Polyakov] *) Disabled incorrect Alpha assembler code. [Richard Levitte] *) Fix PKCS#7 decode routines so they correctly update the length after reading an EOC for the EXPLICIT tag. [Steve Henson] [This change does not apply to 0.9.7.] *) Fix bug in PKCS#12 key generation routines. This was triggered if a 3DES key was generated with a 0 initial byte. Include PKCS12_BROKEN_KEYGEN compilation option to retain the old (but broken) behaviour. [Steve Henson] *) Enhance bctest to search for a working bc along $PATH and print it when found. [Tim Rice via Richard Levitte] *) Fix memory leaks in err.c: free err_data string if necessary; don't write to the wrong index in ERR_set_error_data. [Bodo Moeller] *) Implement ssl23_peek (analogous to ssl23_read), which previously did not exist. [Bodo Moeller] *) Replace rdtsc with _emit statements for VC++ version 5. [Jeremy Cooper ] *) Make it possible to reuse SSLv2 sessions. [Richard Levitte] *) In copy_email() check for >= 0 as a return value for X509_NAME_get_index_by_NID() since 0 is a valid index. [Steve Henson reported by Massimiliano Pala ] *) Avoid coredump with unsupported or invalid public keys by checking if X509_get_pubkey() fails in PKCS7_verify(). Fix memory leak when PKCS7_verify() fails with non detached data. [Steve Henson] *) Don't use getenv in library functions when run as setuid/setgid. New function OPENSSL_issetugid(). [Ulf Moeller] *) Avoid false positives in memory leak detection code (crypto/mem_dbg.c) due to incorrect handling of multi-threading: 1. Fix timing glitch in the MemCheck_off() portion of CRYPTO_mem_ctrl(). 2. Fix logical glitch in is_MemCheck_on() aka CRYPTO_is_mem_check_on(). 3. Count how many times MemCheck_off() has been called so that nested use can be treated correctly. This also avoids inband-signalling in the previous code (which relied on the assumption that thread ID 0 is impossible). [Bodo Moeller] *) Add "-rand" option also to s_client and s_server. [Lutz Jaenicke] *) Fix CPU detection on Irix 6.x. [Kurt Hockenbury and "Bruce W. Forsberg" ] *) Fix X509_NAME bug which produced incorrect encoding if X509_NAME was empty. [Steve Henson] [This change does not apply to 0.9.7.] *) Use the cached encoding of an X509_NAME structure rather than copying it. This is apparently the reason for the libsafe "errors" but the code is actually correct. [Steve Henson] *) Add new function BN_rand_range(), and fix DSA_sign_setup() to prevent Bleichenbacher's DSA attack. Extend BN_[pseudo_]rand: As before, top=1 forces the highest two bits to be set and top=0 forces the highest bit to be set; top=-1 is new and leaves the highest bit random. [Ulf Moeller, Bodo Moeller] *) In the NCONF_...-based implementations for CONF_... queries (crypto/conf/conf_lib.c), if the input LHASH is NULL, avoid using a temporary CONF structure with the data component set to NULL (which gives segmentation faults in lh_retrieve). Instead, use NULL for the CONF pointer in CONF_get_string and CONF_get_number (which may use environment variables) and directly return NULL from CONF_get_section. [Bodo Moeller] *) Fix potential buffer overrun for EBCDIC. [Ulf Moeller] *) Tolerate nonRepudiation as being valid for S/MIME signing and certSign keyUsage if basicConstraints absent for a CA. [Steve Henson] *) Make SMIME_write_PKCS7() write mail header values with a format that is more generally accepted (no spaces before the semicolon), since some programs can't parse those values properly otherwise. Also make sure BIO's that break lines after each write do not create invalid headers. [Richard Levitte] *) Make the CRL encoding routines work with empty SEQUENCE OF. The macros previously used would not encode an empty SEQUENCE OF and break the signature. [Steve Henson] [This change does not apply to 0.9.7.] *) Zero the premaster secret after deriving the master secret in DH ciphersuites. [Steve Henson] *) Add some EVP_add_digest_alias registrations (as found in OpenSSL_add_all_digests()) to SSL_library_init() aka OpenSSL_add_ssl_algorithms(). This provides improved compatibility with peers using X.509 certificates with unconventional AlgorithmIdentifier OIDs. [Bodo Moeller] *) Fix for Irix with NO_ASM. ["Bruce W. Forsberg" ] *) ./config script fixes. [Ulf Moeller, Richard Levitte] *) Fix 'openssl passwd -1'. [Bodo Moeller] *) Change PKCS12_key_gen_asc() so it can cope with non null terminated strings whose length is passed in the passlen parameter, for example from PEM callbacks. This was done by adding an extra length parameter to asc2uni(). [Steve Henson, reported by ] *) Fix C code generated by 'openssl dsaparam -C': If a BN_bin2bn call failed, free the DSA structure. [Bodo Moeller] *) Fix to uni2asc() to cope with zero length Unicode strings. These are present in some PKCS#12 files. [Steve Henson] *) Increase s2->wbuf allocation by one byte in ssl2_new (ssl/s2_lib.c). Otherwise do_ssl_write (ssl/s2_pkt.c) will write beyond buffer limits when writing a 32767 byte record. [Bodo Moeller; problem reported by Eric Day ] *) In RSA_eay_public_{en,ed}crypt and RSA_eay_mod_exp (rsa_eay.c), obtain lock CRYPTO_LOCK_RSA before setting rsa->_method_mod_{n,p,q}. (RSA objects have a reference count access to which is protected by CRYPTO_LOCK_RSA [see rsa_lib.c, s3_srvr.c, ssl_cert.c, ssl_rsa.c], so they are meant to be shared between threads.) [Bodo Moeller, Geoff Thorpe; original patch submitted by "Reddie, Steven" ] *) Fix a deadlock in CRYPTO_mem_leaks(). [Bodo Moeller] *) Use better test patterns in bntest. [Ulf Möller] *) rand_win.c fix for Borland C. [Ulf Möller] *) BN_rshift bugfix for n == 0. [Bodo Moeller] *) Add a 'bctest' script that checks for some known 'bc' bugs so that 'make test' does not abort just because 'bc' is broken. [Bodo Moeller] *) Store verify_result within SSL_SESSION also for client side to avoid potential security hole. (Re-used sessions on the client side always resulted in verify_result==X509_V_OK, not using the original result of the server certificate verification.) [Lutz Jaenicke] *) Fix ssl3_pending: If the record in s->s3->rrec is not of type SSL3_RT_APPLICATION_DATA, return 0. Similarly, change ssl2_pending to return 0 if SSL_in_init(s) is true. [Bodo Moeller] *) Fix SSL_peek: Both ssl2_peek and ssl3_peek, which were totally broken in earlier releases, have been re-implemented by renaming the previous implementations of ssl2_read and ssl3_read to ssl2_read_internal and ssl3_read_internal, respectively, and adding 'peek' parameters to them. The new ssl[23]_{read,peek} functions are calls to ssl[23]_read_internal with the 'peek' flag set appropriately. A 'peek' parameter has also been added to ssl3_read_bytes, which does the actual work for ssl3_read_internal. [Bodo Moeller] *) Initialise "ex_data" member of RSA/DSA/DH structures prior to calling the method-specific "init()" handler. Also clean up ex_data after calling the method-specific "finish()" handler. Previously, this was happening the other way round. [Geoff Thorpe] *) Increase BN_CTX_NUM (the number of BIGNUMs in a BN_CTX) to 16. The previous value, 12, was not always sufficient for BN_mod_exp(). [Bodo Moeller] *) Make sure that shared libraries get the internal name engine with the full version number and not just 0. This should mark the shared libraries as not backward compatible. Of course, this should be changed again when we can guarantee backward binary compatibility. [Richard Levitte] *) Fix typo in get_cert_by_subject() in by_dir.c [Jean-Marc Desperrier ] *) Rework the system to generate shared libraries: - Make note of the expected extension for the shared libraries and if there is a need for symbolic links from for example libcrypto.so.0 to libcrypto.so.0.9.7. There is extended info in Configure for that. - Make as few rebuilds of the shared libraries as possible. - Still avoid linking the OpenSSL programs with the shared libraries. - When installing, install the shared libraries separately from the static ones. [Richard Levitte] *) Fix SSL_CTX_set_read_ahead macro to actually use its argument. Copy SSL_CTX's read_ahead flag to SSL object directly in SSL_new and not in SSL_clear because the latter is also used by the accept/connect functions; previously, the settings made by SSL_set_read_ahead would be lost during the handshake. [Bodo Moeller; problems reported by Anders Gertz ] *) Correct util/mkdef.pl to be selective about disabled algorithms. Previously, it would create entries for disableed algorithms no matter what. [Richard Levitte] *) Added several new manual pages for SSL_* function. [Lutz Jaenicke] Changes between 0.9.5a and 0.9.6 [24 Sep 2000] *) In ssl23_get_client_hello, generate an error message when faced with an initial SSL 3.0/TLS record that is too small to contain the first two bytes of the ClientHello message, i.e. client_version. (Note that this is a pathologic case that probably has never happened in real life.) The previous approach was to use the version number from the record header as a substitute; but our protocol choice should not depend on that one because it is not authenticated by the Finished messages. [Bodo Moeller] *) More robust randomness gathering functions for Windows. [Jeffrey Altman ] *) For compatibility reasons if the flag X509_V_FLAG_ISSUER_CHECK is not set then we don't setup the error code for issuer check errors to avoid possibly overwriting other errors which the callback does handle. If an application does set the flag then we assume it knows what it is doing and can handle the new informational codes appropriately. [Steve Henson] *) Fix for a nasty bug in ASN1_TYPE handling. ASN1_TYPE is used for a general "ANY" type, as such it should be able to decode anything including tagged types. However it didn't check the class so it would wrongly interpret tagged types in the same way as their universal counterpart and unknown types were just rejected. Changed so that the tagged and unknown types are handled in the same way as a SEQUENCE: that is the encoding is stored intact. There is also a new type "V_ASN1_OTHER" which is used when the class is not universal, in this case we have no idea what the actual type is so we just lump them all together. [Steve Henson] *) On VMS, stdout may very well lead to a file that is written to in a record-oriented fashion. That means that every write() will write a separate record, which will be read separately by the programs trying to read from it. This can be very confusing. The solution is to put a BIO filter in the way that will buffer text until a linefeed is reached, and then write everything a line at a time, so every record written will be an actual line, not chunks of lines and not (usually doesn't happen, but I've seen it once) several lines in one record. BIO_f_linebuffer() is the answer. Currently, it's a VMS-only method, because that's where it has been tested well enough. [Richard Levitte] *) Remove 'optimized' squaring variant in BN_mod_mul_montgomery, it can return incorrect results. (Note: The buggy variant was not enabled in OpenSSL 0.9.5a, but it was in 0.9.6-beta[12].) [Bodo Moeller] *) Disable the check for content being present when verifying detached signatures in pk7_smime.c. Some versions of Netscape (wrongly) include zero length content when signing messages. [Steve Henson] *) New BIO_shutdown_wr macro, which invokes the BIO_C_SHUTDOWN_WR BIO_ctrl (for BIO pairs). [Bodo Möller] *) Add DSO method for VMS. [Richard Levitte] *) Bug fix: Montgomery multiplication could produce results with the wrong sign. [Ulf Möller] *) Add RPM specification openssl.spec and modify it to build three packages. The default package contains applications, application documentation and run-time libraries. The devel package contains include files, static libraries and function documentation. The doc package contains the contents of the doc directory. The original openssl.spec was provided by Damien Miller . [Richard Levitte] *) Add a large number of documentation files for many SSL routines. [Lutz Jaenicke ] *) Add a configuration entry for Sony News 4. [NAKAJI Hiroyuki ] *) Don't set the two most significant bits to one when generating a random number < q in the DSA library. [Ulf Möller] *) New SSL API mode 'SSL_MODE_AUTO_RETRY'. This disables the default behaviour that SSL_read may result in SSL_ERROR_WANT_READ (even if the underlying transport is blocking) if a handshake took place. (The default behaviour is needed by applications such as s_client and s_server that use select() to determine when to use SSL_read; but for applications that know in advance when to expect data, it just makes things more complicated.) [Bodo Moeller] *) Add RAND_egd_bytes(), which gives control over the number of bytes read from EGD. [Ben Laurie] *) Add a few more EBCDIC conditionals that make `req' and `x509' work better on such systems. [Martin Kraemer ] *) Add two demo programs for PKCS12_parse() and PKCS12_create(). Update PKCS12_parse() so it copies the friendlyName and the keyid to the certificates aux info. [Steve Henson] *) Fix bug in PKCS7_verify() which caused an infinite loop if there was more than one signature. [Sven Uszpelkat ] *) Major change in util/mkdef.pl to include extra information about each symbol, as well as presentig variables as well as functions. This change means that there's n more need to rebuild the .num files when some algorithms are excluded. [Richard Levitte] *) Allow the verify time to be set by an application, rather than always using the current time. [Steve Henson] *) Phase 2 verify code reorganisation. The certificate verify code now looks up an issuer certificate by a number of criteria: subject name, authority key id and key usage. It also verifies self signed certificates by the same criteria. The main comparison function is X509_check_issued() which performs these checks. Lot of changes were necessary in order to support this without completely rewriting the lookup code. Authority and subject key identifier are now cached. The LHASH 'certs' is X509_STORE has now been replaced by a STACK_OF(X509_OBJECT). This is mainly because an LHASH can't store or retrieve multiple objects with the same hash value. As a result various functions (which were all internal use only) have changed to handle the new X509_STORE structure. This will break anything that messed round with X509_STORE internally. The functions X509_STORE_add_cert() now checks for an exact match, rather than just subject name. The X509_STORE API doesn't directly support the retrieval of multiple certificates matching a given criteria, however this can be worked round by performing a lookup first (which will fill the cache with candidate certificates) and then examining the cache for matches. This is probably the best we can do without throwing out X509_LOOKUP entirely (maybe later...). The X509_VERIFY_CTX structure has been enhanced considerably. All certificate lookup operations now go via a get_issuer() callback. Although this currently uses an X509_STORE it can be replaced by custom lookups. This is a simple way to bypass the X509_STORE hackery necessary to make this work and makes it possible to use more efficient techniques in future. A very simple version which uses a simple STACK for its trusted certificate store is also provided using X509_STORE_CTX_trusted_stack(). The verify_cb() and verify() callbacks now have equivalents in the X509_STORE_CTX structure. X509_STORE_CTX also has a 'flags' field which can be used to customise the verify behaviour. [Steve Henson] *) Add new PKCS#7 signing option PKCS7_NOSMIMECAP which excludes S/MIME capabilities. [Steve Henson] *) When a certificate request is read in keep a copy of the original encoding of the signed data and use it when outputing again. Signatures then use the original encoding rather than a decoded, encoded version which may cause problems if the request is improperly encoded. [Steve Henson] *) For consistency with other BIO_puts implementations, call buffer_write(b, ...) directly in buffer_puts instead of calling BIO_write(b, ...). In BIO_puts, increment b->num_write as in BIO_write. [Peter.Sylvester@EdelWeb.fr] *) Fix BN_mul_word for the case where the word is 0. (We have to use BN_zero, we may not return a BIGNUM with an array consisting of words set to zero.) [Bodo Moeller] *) Avoid calling abort() from within the library when problems are detected, except if preprocessor symbols have been defined (such as REF_CHECK, BN_DEBUG etc.). [Bodo Moeller] *) New openssl application 'rsautl'. This utility can be used for low level RSA operations. DER public key BIO/fp routines also added. [Steve Henson] *) New Configure entry and patches for compiling on QNX 4. [Andreas Schneider ] *) A demo state-machine implementation was sponsored by Nuron (http://www.nuron.com/) and is now available in demos/state_machine. [Ben Laurie] *) New options added to the 'dgst' utility for signature generation and verification. [Steve Henson] *) Unrecognized PKCS#7 content types are now handled via a catch all ASN1_TYPE structure. This allows unsupported types to be stored as a "blob" and an application can encode and decode it manually. [Steve Henson] *) Fix various signed/unsigned issues to make a_strex.c compile under VC++. [Oscar Jacobsson ] *) ASN1 fixes. i2d_ASN1_OBJECT was not returning the correct length if passed a buffer. ASN1_INTEGER_to_BN failed if passed a NULL BN and its argument was negative. [Steve Henson, pointed out by Sven Heiberg ] *) Modification to PKCS#7 encoding routines to output definite length encoding. Since currently the whole structures are in memory there's not real point in using indefinite length constructed encoding. However if OpenSSL is compiled with the flag PKCS7_INDEFINITE_ENCODING the old form is used. [Steve Henson] *) Added BIO_vprintf() and BIO_vsnprintf(). [Richard Levitte] *) Added more prefixes to parse for in the the strings written through a logging bio, to cover all the levels that are available through syslog. The prefixes are now: PANIC, EMERG, EMR => LOG_EMERG ALERT, ALR => LOG_ALERT CRIT, CRI => LOG_CRIT ERROR, ERR => LOG_ERR WARNING, WARN, WAR => LOG_WARNING NOTICE, NOTE, NOT => LOG_NOTICE INFO, INF => LOG_INFO DEBUG, DBG => LOG_DEBUG and as before, if none of those prefixes are present at the beginning of the string, LOG_ERR is chosen. On Win32, the LOG_* levels are mapped according to this: LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR => EVENTLOG_ERROR_TYPE LOG_WARNING => EVENTLOG_WARNING_TYPE LOG_NOTICE, LOG_INFO, LOG_DEBUG => EVENTLOG_INFORMATION_TYPE [Richard Levitte] *) Made it possible to reconfigure with just the configuration argument "reconf" or "reconfigure". The command line arguments are stored in Makefile.ssl in the variable CONFIGURE_ARGS, and are retrieved from there when reconfiguring. [Richard Levitte] *) MD4 implemented. [Assar Westerlund , Richard Levitte] *) Add the arguments -CAfile and -CApath to the pkcs12 utility. [Richard Levitte] *) The obj_dat.pl script was messing up the sorting of object names. The reason was that it compared the quoted version of strings as a result "OCSP" > "OCSP Signing" because " > SPACE. Changed script to store unquoted versions of names and add quotes on output. It was also omitting some names from the lookup table if they were given a default value (that is if SN is missing it is given the same value as LN and vice versa), these are now added on the grounds that if an object has a name we should be able to look it up. Finally added warning output when duplicate short or long names are found. [Steve Henson] *) Changes needed for Tandem NSK. [Scott Uroff ] *) Fix SSL 2.0 rollback checking: Due to an off-by-one error in RSA_padding_check_SSLv23(), special padding was never detected and thus the SSL 3.0/TLS 1.0 countermeasure against protocol version rollback attacks was not effective. In s23_clnt.c, don't use special rollback-attack detection padding (RSA_SSLV23_PADDING) if SSL 2.0 is the only protocol enabled in the client; similarly, in s23_srvr.c, don't do the rollback check if SSL 2.0 is the only protocol enabled in the server. [Bodo Moeller] *) Make it possible to get hexdumps of unprintable data with 'openssl asn1parse'. By implication, the functions ASN1_parse_dump() and BIO_dump_indent() are added. [Richard Levitte] *) New functions ASN1_STRING_print_ex() and X509_NAME_print_ex() these print out strings and name structures based on various flags including RFC2253 support and proper handling of multibyte characters. Added options to the 'x509' utility to allow the various flags to be set. [Steve Henson] *) Various fixes to use ASN1_TIME instead of ASN1_UTCTIME. Also change the functions X509_cmp_current_time() and X509_gmtime_adj() work with an ASN1_TIME structure, this will enable certificates using GeneralizedTime in validity dates to be checked. [Steve Henson] *) Make the NEG_PUBKEY_BUG code (which tolerates invalid negative public key encodings) on by default, NO_NEG_PUBKEY_BUG can be set to disable it. [Steve Henson] *) New function c2i_ASN1_OBJECT() which acts on ASN1_OBJECT content octets. An i2c_ASN1_OBJECT is unnecessary because the encoding can be trivially obtained from the structure. [Steve Henson] *) crypto/err.c locking bugfix: Use write locks (CRYPTO_w_[un]lock), not read locks (CRYPTO_r_[un]lock). [Bodo Moeller] *) A first attempt at creating official support for shared libraries through configuration. I've kept it so the default is static libraries only, and the OpenSSL programs are always statically linked for now, but there are preparations for dynamic linking in place. This has been tested on Linux and Tru64. [Richard Levitte] *) Randomness polling function for Win9x, as described in: Peter Gutmann, Software Generation of Practically Strong Random Numbers. [Ulf Möller] *) Fix so PRNG is seeded in req if using an already existing DSA key. [Steve Henson] *) New options to smime application. -inform and -outform allow alternative formats for the S/MIME message including PEM and DER. The -content option allows the content to be specified separately. This should allow things like Netscape form signing output easier to verify. [Steve Henson] *) Fix the ASN1 encoding of tags using the 'long form'. [Steve Henson] *) New ASN1 functions, i2c_* and c2i_* for INTEGER and BIT STRING types. These convert content octets to and from the underlying type. The actual tag and length octets are already assumed to have been read in and checked. These are needed because all other string types have virtually identical handling apart from the tag. By having versions of the ASN1 functions that just operate on content octets IMPLICIT tagging can be handled properly. It also allows the ASN1_ENUMERATED code to be cut down because ASN1_ENUMERATED and ASN1_INTEGER are identical apart from the tag. [Steve Henson] *) Change the handling of OID objects as follows: - New object identifiers are inserted in objects.txt, following the syntax given in objects.README. - objects.pl is used to process obj_mac.num and create a new obj_mac.h. - obj_dat.pl is used to create a new obj_dat.h, using the data in obj_mac.h. This is currently kind of a hack, and the perl code in objects.pl isn't very elegant, but it works as I intended. The simplest way to check that it worked correctly is to look in obj_dat.h and check the array nid_objs and make sure the objects haven't moved around (this is important!). Additions are OK, as well as consistent name changes. [Richard Levitte] *) Add BSD-style MD5-based passwords to 'openssl passwd' (option '-1'). [Bodo Moeller] *) Addition of the command line parameter '-rand file' to 'openssl req'. The given file adds to whatever has already been seeded into the random pool through the RANDFILE configuration file option or environment variable, or the default random state file. [Richard Levitte] *) mkstack.pl now sorts each macro group into lexical order. Previously the output order depended on the order the files appeared in the directory, resulting in needless rewriting of safestack.h . [Steve Henson] *) Patches to make OpenSSL compile under Win32 again. Mostly work arounds for the VC++ problem that it treats func() as func(void). Also stripped out the parts of mkdef.pl that added extra typesafe functions: these no longer exist. [Steve Henson] *) Reorganisation of the stack code. The macros are now all collected in safestack.h . Each macro is defined in terms of a "stack macro" of the form SKM_(type, a, b). The DEBUG_SAFESTACK is now handled in terms of function casts, this has the advantage of retaining type safety without the use of additional functions. If DEBUG_SAFESTACK is not defined then the non typesafe macros are used instead. Also modified the mkstack.pl script to handle the new form. Needs testing to see if which (if any) compilers it chokes and maybe make DEBUG_SAFESTACK the default if no major problems. Similar behaviour for ASN1_SET_OF and PKCS12_STACK_OF. [Steve Henson] *) When some versions of IIS use the 'NET' form of private key the key derivation algorithm is different. Normally MD5(password) is used as a 128 bit RC4 key. In the modified case MD5(MD5(password) + "SGCKEYSALT") is used insted. Added some new functions i2d_RSA_NET(), d2i_RSA_NET() etc which are the same as the old Netscape_RSA functions except they have an additional 'sgckey' parameter which uses the modified algorithm. Also added an -sgckey command line option to the rsa utility. Thanks to Adrian Peck for posting details of the modified algorithm to openssl-dev. [Steve Henson] *) The evp_local.h macros were using 'c.##kname' which resulted in invalid expansion on some systems (SCO 5.0.5 for example). Corrected to 'c.kname'. [Phillip Porch ] *) New X509_get1_email() and X509_REQ_get1_email() functions that return a STACK of email addresses from a certificate or request, these look in the subject name and the subject alternative name extensions and omit any duplicate addresses. [Steve Henson] *) Re-implement BN_mod_exp2_mont using independent (and larger) windows. This makes DSA verification about 2 % faster. [Bodo Moeller] *) Increase maximum window size in BN_mod_exp_... to 6 bits instead of 5 (meaning that now 2^5 values will be precomputed, which is only 4 KB plus overhead for 1024 bit moduli). This makes exponentiations about 0.5 % faster for 1024 bit exponents (as measured by "openssl speed rsa2048"). [Bodo Moeller] *) Rename memory handling macros to avoid conflicts with other software: Malloc => OPENSSL_malloc Malloc_locked => OPENSSL_malloc_locked Realloc => OPENSSL_realloc Free => OPENSSL_free [Richard Levitte] *) New function BN_mod_exp_mont_word for small bases (roughly 15% faster than BN_mod_exp_mont, i.e. 7% for a full DH exchange). [Bodo Moeller] *) CygWin32 support. [John Jarvie ] *) The type-safe stack code has been rejigged. It is now only compiled in when OpenSSL is configured with the DEBUG_SAFESTACK option and by default all type-specific stack functions are "#define"d back to standard stack functions. This results in more streamlined output but retains the type-safety checking possibilities of the original approach. [Geoff Thorpe] *) The STACK code has been cleaned up, and certain type declarations that didn't make a lot of sense have been brought in line. This has also involved a cleanup of sorts in safestack.h to more correctly map type-safe stack functions onto their plain stack counterparts. This work has also resulted in a variety of "const"ifications of lots of the code, especially "_cmp" operations which should normally be prototyped with "const" parameters anyway. [Geoff Thorpe] *) When generating bytes for the first time in md_rand.c, 'stir the pool' by seeding with STATE_SIZE dummy bytes (with zero entropy count). (The PRNG state consists of two parts, the large pool 'state' and 'md', where all of 'md' is used each time the PRNG is used, but 'state' is used only indexed by a cyclic counter. As entropy may not be well distributed from the beginning, 'md' is important as a chaining variable. However, the output function chains only half of 'md', i.e. 80 bits. ssleay_rand_add, on the other hand, chains all of 'md', and seeding with STATE_SIZE dummy bytes will result in all of 'state' being rewritten, with the new values depending on virtually all of 'md'. This overcomes the 80 bit limitation.) [Bodo Moeller] *) In ssl/s2_clnt.c and ssl/s3_clnt.c, call ERR_clear_error() when the handshake is continued after ssl_verify_cert_chain(); otherwise, if SSL_VERIFY_NONE is set, remaining error codes can lead to 'unexplainable' connection aborts later. [Bodo Moeller; problem tracked down by Lutz Jaenicke] *) Major EVP API cipher revision. Add hooks for extra EVP features. This allows various cipher parameters to be set in the EVP interface. Support added for variable key length ciphers via the EVP_CIPHER_CTX_set_key_length() function and setting of RC2 and RC5 parameters. Modify EVP_OpenInit() and EVP_SealInit() to cope with variable key length ciphers. Remove lots of duplicated code from the EVP library. For example *every* cipher init() function handles the 'iv' in the same way according to the cipher mode. They also all do nothing if the 'key' parameter is NULL and for CFB and OFB modes they zero ctx->num. New functionality allows removal of S/MIME code RC2 hack. Most of the routines have the same form and so can be declared in terms of macros. By shifting this to the top level EVP_CipherInit() it can be removed from all individual ciphers. If the cipher wants to handle IVs or keys differently it can set the EVP_CIPH_CUSTOM_IV or EVP_CIPH_ALWAYS_CALL_INIT flags. Change lots of functions like EVP_EncryptUpdate() to now return a value: although software versions of the algorithms cannot fail any installed hardware versions can. [Steve Henson] *) Implement SSL_OP_TLS_ROLLBACK_BUG: In ssl3_get_client_key_exchange, if this option is set, tolerate broken clients that send the negotiated protocol version number instead of the requested protocol version number. [Bodo Moeller] *) Call dh_tmp_cb (set by ..._TMP_DH_CB) with correct 'is_export' flag; i.e. non-zero for export ciphersuites, zero otherwise. Previous versions had this flag inverted, inconsistent with rsa_tmp_cb (..._TMP_RSA_CB). [Bodo Moeller; problem reported by Amit Chopra] *) Add missing DSA library text string. Work around for some IIS key files with invalid SEQUENCE encoding. [Steve Henson] *) Add a document (doc/standards.txt) that list all kinds of standards and so on that are implemented in OpenSSL. [Richard Levitte] *) Enhance c_rehash script. Old version would mishandle certificates with the same subject name hash and wouldn't handle CRLs at all. Added -fingerprint option to crl utility, to support new c_rehash features. [Steve Henson] *) Eliminate non-ANSI declarations in crypto.h and stack.h. [Ulf Möller] *) Fix for SSL server purpose checking. Server checking was rejecting certificates which had extended key usage present but no ssl client purpose. [Steve Henson, reported by Rene Grosser ] *) Make PKCS#12 code work with no password. The PKCS#12 spec is a little unclear about how a blank password is handled. Since the password in encoded as a BMPString with terminating double NULL a zero length password would end up as just the double NULL. However no password at all is different and is handled differently in the PKCS#12 key generation code. NS treats a blank password as zero length. MSIE treats it as no password on export: but it will try both on import. We now do the same: PKCS12_parse() tries zero length and no password if the password is set to "" or NULL (NULL is now a valid password: it wasn't before) as does the pkcs12 application. [Steve Henson] *) Bugfixes in apps/x509.c: Avoid a memory leak; and don't use perror when PEM_read_bio_X509_REQ fails, the error message must be obtained from the error queue. [Bodo Moeller] *) Avoid 'thread_hash' memory leak in crypto/err/err.c by freeing it in ERR_remove_state if appropriate, and change ERR_get_state accordingly to avoid race conditions (this is necessary because thread_hash is no longer constant once set). [Bodo Moeller] *) Bugfix for linux-elf makefile.one. [Ulf Möller] *) RSA_get_default_method() will now cause a default RSA_METHOD to be chosen if one doesn't exist already. Previously this was only set during a call to RSA_new() or RSA_new_method(NULL) meaning it was possible for RSA_get_default_method() to return NULL. [Geoff Thorpe] *) Added native name translation to the existing DSO code that will convert (if the flag to do so is set) filenames that are sufficiently small and have no path information into a canonical native form. Eg. "blah" converted to "libblah.so" or "blah.dll" etc. [Geoff Thorpe] *) New function ERR_error_string_n(e, buf, len) which is like ERR_error_string(e, buf), but writes at most 'len' bytes including the 0 terminator. For ERR_error_string_n, 'buf' may not be NULL. [Damien Miller , Bodo Moeller] *) CONF library reworked to become more general. A new CONF configuration file reader "class" is implemented as well as a new functions (NCONF_*, for "New CONF") to handle it. The now old CONF_* functions are still there, but are reimplemented to work in terms of the new functions. Also, a set of functions to handle the internal storage of the configuration data is provided to make it easier to write new configuration file reader "classes" (I can definitely see something reading a configuration file in XML format, for example), called _CONF_*, or "the configuration storage API"... The new configuration file reading functions are: NCONF_new, NCONF_free, NCONF_load, NCONF_load_fp, NCONF_load_bio, NCONF_get_section, NCONF_get_string, NCONF_get_numbre NCONF_default, NCONF_WIN32 NCONF_dump_fp, NCONF_dump_bio NCONF_default and NCONF_WIN32 are method (or "class") choosers, NCONF_new creates a new CONF object. This works in the same way as other interfaces in OpenSSL, like the BIO interface. NCONF_dump_* dump the internal storage of the configuration file, which is useful for debugging. All other functions take the same arguments as the old CONF_* functions wth the exception of the first that must be a `CONF *' instead of a `LHASH *'. To make it easer to use the new classes with the old CONF_* functions, the function CONF_set_default_method is provided. [Richard Levitte] *) Add '-tls1' option to 'openssl ciphers', which was already mentioned in the documentation but had not been implemented. (This option is not yet really useful because even the additional experimental TLS 1.0 ciphers are currently treated as SSL 3.0 ciphers.) [Bodo Moeller] *) Initial DSO code added into libcrypto for letting OpenSSL (and OpenSSL-based applications) load shared libraries and bind to them in a portable way. [Geoff Thorpe, with contributions from Richard Levitte] Changes between 0.9.5 and 0.9.5a [1 Apr 2000] *) Make sure _lrotl and _lrotr are only used with MSVC. *) Use lock CRYPTO_LOCK_RAND correctly in ssleay_rand_status (the default implementation of RAND_status). *) Rename openssl x509 option '-crlext', which was added in 0.9.5, to '-clrext' (= clear extensions), as intended and documented. [Bodo Moeller; inconsistency pointed out by Michael Attili ] *) Fix for HMAC. It wasn't zeroing the rest of the block if the key length was larger than the MD block size. [Steve Henson, pointed out by Yost William ] *) Modernise PKCS12_parse() so it uses STACK_OF(X509) for its ca argument fix a leak when the ca argument was passed as NULL. Stop X509_PUBKEY_set() using the passed key: if the passed key was a private key the result of X509_print(), for example, would be to print out all the private key components. [Steve Henson] *) des_quad_cksum() byte order bug fix. [Ulf Möller, using the problem description in krb4-0.9.7, where the solution is attributed to Derrick J Brashear ] *) Fix so V_ASN1_APP_CHOOSE works again: however its use is strongly discouraged. [Steve Henson, pointed out by Brian Korver ] *) For easily testing in shell scripts whether some command 'openssl XXX' exists, the new pseudo-command 'openssl no-XXX' returns with exit code 0 iff no command of the given name is available. 'no-XXX' is printed in this case, 'XXX' otherwise. In both cases, the output goes to stdout and nothing is printed to stderr. Additional arguments are always ignored. Since for each cipher there is a command of the same name, the 'no-cipher' compilation switches can be tested this way. ('openssl no-XXX' is not able to detect pseudo-commands such as 'quit', 'list-XXX-commands', or 'no-XXX' itself.) [Bodo Moeller] *) Update test suite so that 'make test' succeeds in 'no-rsa' configuration. [Bodo Moeller] *) For SSL_[CTX_]set_tmp_dh, don't create a DH key if SSL_OP_SINGLE_DH_USE is set; it will be thrown away anyway because each handshake creates its own key. ssl_cert_dup, which is used by SSL_new, now copies DH keys in addition to parameters -- in previous versions (since OpenSSL 0.9.3) the 'default key' from SSL_CTX_set_tmp_dh would always be lost, meanining you effectivly got SSL_OP_SINGLE_DH_USE when using this macro. [Bodo Moeller] *) New s_client option -ign_eof: EOF at stdin is ignored, and 'Q' and 'R' lose their special meanings (quit/renegotiate). This is part of what -quiet does; unlike -quiet, -ign_eof does not suppress any output. [Richard Levitte] *) Add compatibility options to the purpose and trust code. The purpose X509_PURPOSE_ANY is "any purpose" which automatically accepts a certificate or CA, this was the previous behaviour, with all the associated security issues. X509_TRUST_COMPAT is the old trust behaviour: only and automatically trust self signed roots in certificate store. A new trust setting X509_TRUST_DEFAULT is used to specify that a purpose has no associated trust setting and it should instead use the value in the default purpose. [Steve Henson] *) Fix the PKCS#8 DSA private key code so it decodes keys again and fix a memory leak. [Steve Henson] *) In util/mkerr.pl (which implements 'make errors'), preserve reason strings from the previous version of the .c file, as the default to have only downcase letters (and digits) in automatically generated reasons codes is not always appropriate. [Bodo Moeller] *) In ERR_load_ERR_strings(), build an ERR_LIB_SYS error reason table using strerror. Previously, ERR_reason_error_string() returned library names as reason strings for SYSerr; but SYSerr is a special case where small numbers are errno values, not library numbers. [Bodo Moeller] *) Add '-dsaparam' option to 'openssl dhparam' application. This converts DSA parameters into DH parameters. (When creating parameters, DSA_generate_parameters is used.) [Bodo Moeller] *) Include 'length' (recommended exponent length) in C code generated by 'openssl dhparam -C'. [Bodo Moeller] *) The second argument to set_label in perlasm was already being used so couldn't be used as a "file scope" flag. Moved to third argument which was free. [Steve Henson] *) In PEM_ASN1_write_bio and some other functions, use RAND_pseudo_bytes instead of RAND_bytes for encryption IVs and salts. [Bodo Moeller] *) Include RAND_status() into RAND_METHOD instead of implementing it only for md_rand.c Otherwise replacing the PRNG by calling RAND_set_rand_method would be impossible. [Bodo Moeller] *) Don't let DSA_generate_key() enter an infinite loop if the random number generation fails. [Bodo Moeller] *) New 'rand' application for creating pseudo-random output. [Bodo Moeller] *) Added configuration support for Linux/IA64 [Rolf Haberrecker ] *) Assembler module support for Mingw32. [Ulf Möller] *) Shared library support for HPUX (in shlib/). [Lutz Jaenicke and Anonymous] *) Shared library support for Solaris gcc. [Lutz Behnke ] Changes between 0.9.4 and 0.9.5 [28 Feb 2000] *) PKCS7_encrypt() was adding text MIME headers twice because they were added manually and by SMIME_crlf_copy(). [Steve Henson] *) In bntest.c don't call BN_rand with zero bits argument. [Steve Henson, pointed out by Andrew W. Gray ] *) BN_mul bugfix: In bn_mul_part_recursion() only the a>a[n] && b>b[n] case was implemented. This caused BN_div_recp() to fail occasionally. [Ulf Möller] *) Add an optional second argument to the set_label() in the perl assembly language builder. If this argument exists and is set to 1 it signals that the assembler should use a symbol whose scope is the entire file, not just the current function. This is needed with MASM which uses the format label:: for this scope. [Steve Henson, pointed out by Peter Runestig ] *) Change the ASN1 types so they are typedefs by default. Before almost all types were #define'd to ASN1_STRING which was causing STACK_OF() problems: you couldn't declare STACK_OF(ASN1_UTF8STRING) for example. [Steve Henson] *) Change names of new functions to the new get1/get0 naming convention: After 'get1', the caller owns a reference count and has to call ..._free; 'get0' returns a pointer to some data structure without incrementing reference counters. (Some of the existing 'get' functions increment a reference counter, some don't.) Similarly, 'set1' and 'add1' functions increase reference counters or duplicate objects. [Steve Henson] *) Allow for the possibility of temp RSA key generation failure: the code used to assume it always worked and crashed on failure. [Steve Henson] *) Fix potential buffer overrun problem in BIO_printf(). [Ulf Möller, using public domain code by Patrick Powell; problem pointed out by David Sacerdote ] *) Support EGD . New functions RAND_egd() and RAND_status(). In the command line application, the EGD socket can be specified like a seed file using RANDFILE or -rand. [Ulf Möller] *) Allow the string CERTIFICATE to be tolerated in PKCS#7 structures. Some CAs (e.g. Verisign) distribute certificates in this form. [Steve Henson] *) Remove the SSL_ALLOW_ADH compile option and set the default cipher list to exclude them. This means that no special compilation option is needed to use anonymous DH: it just needs to be included in the cipher list. [Steve Henson] *) Change the EVP_MD_CTX_type macro so its meaning consistent with EVP_MD_type. The old functionality is available in a new macro called EVP_MD_md(). Change code that uses it and update docs. [Steve Henson] *) ..._ctrl functions now have corresponding ..._callback_ctrl functions where the 'void *' argument is replaced by a function pointer argument. Previously 'void *' was abused to point to functions, which works on many platforms, but is not correct. As these functions are usually called by macros defined in OpenSSL header files, most source code should work without changes. [Richard Levitte] *) (which is created by Configure) now contains sections with information on -D... compiler switches used for compiling the library so that applications can see them. To enable one of these sections, a pre-processor symbol OPENSSL_..._DEFINES must be defined. E.g., #define OPENSSL_ALGORITHM_DEFINES #include defines all pertinent NO_ symbols, such as NO_IDEA, NO_RSA, etc. [Richard Levitte, Ulf and Bodo Möller] *) Bugfix: Tolerate fragmentation and interleaving in the SSL 3/TLS record layer. [Bodo Moeller] *) Change the 'other' type in certificate aux info to a STACK_OF X509_ALGOR. Although not an AlgorithmIdentifier as such it has the required ASN1 format: arbitrary types determined by an OID. [Steve Henson] *) Add some PEM_write_X509_REQ_NEW() functions and a command line argument to 'req'. This is not because the function is newer or better than others it just uses the work 'NEW' in the certificate request header lines. Some software needs this. [Steve Henson] *) Reorganise password command line arguments: now passwords can be obtained from various sources. Delete the PEM_cb function and make it the default behaviour: i.e. if the callback is NULL and the usrdata argument is not NULL interpret it as a null terminated pass phrase. If usrdata and the callback are NULL then the pass phrase is prompted for as usual. [Steve Henson] *) Add support for the Compaq Atalla crypto accelerator. If it is installed, the support is automatically enabled. The resulting binaries will autodetect the card and use it if present. [Ben Laurie and Compaq Inc.] *) Work around for Netscape hang bug. This sends certificate request and server done in one record. Since this is perfectly legal in the SSL/TLS protocol it isn't a "bug" option and is on by default. See the bugs/SSLv3 entry for more info. [Steve Henson] *) HP-UX tune-up: new unified configs, HP C compiler bug workaround. [Andy Polyakov] *) Add -rand argument to smime and pkcs12 applications and read/write of seed file. [Steve Henson] *) New 'passwd' tool for crypt(3) and apr1 password hashes. [Bodo Moeller] *) Add command line password options to the remaining applications. [Steve Henson] *) Bug fix for BN_div_recp() for numerators with an even number of bits. [Ulf Möller] *) More tests in bntest.c, and changed test_bn output. [Ulf Möller] *) ./config recognizes MacOS X now. [Andy Polyakov] *) Bug fix for BN_div() when the first words of num and divsor are equal (it gave wrong results if (rem=(n1-q*d0)&BN_MASK2) < d0). [Ulf Möller] *) Add support for various broken PKCS#8 formats, and command line options to produce them. [Steve Henson] *) New functions BN_CTX_start(), BN_CTX_get() and BT_CTX_end() to get temporary BIGNUMs from a BN_CTX. [Ulf Möller] *) Correct return values in BN_mod_exp_mont() and BN_mod_exp2_mont() for p == 0. [Ulf Möller] *) Change the SSLeay_add_all_*() functions to OpenSSL_add_all_*() and include a #define from the old name to the new. The original intent was that statically linked binaries could for example just call SSLeay_add_all_ciphers() to just add ciphers to the table and not link with digests. This never worked becayse SSLeay_add_all_digests() and SSLeay_add_all_ciphers() were in the same source file so calling one would link with the other. They are now in separate source files. [Steve Henson] *) Add a new -notext option to 'ca' and a -pubkey option to 'spkac'. [Steve Henson] *) Use a less unusual form of the Miller-Rabin primality test (it used a binary algorithm for exponentiation integrated into the Miller-Rabin loop, our standard modexp algorithms are faster). [Bodo Moeller] *) Support for the EBCDIC character set completed. [Martin Kraemer ] *) Source code cleanups: use const where appropriate, eliminate casts, use void * instead of char * in lhash. [Ulf Möller] *) Bugfix: ssl3_send_server_key_exchange was not restartable (the state was not changed to SSL3_ST_SW_KEY_EXCH_B, and because of this the server could overwrite ephemeral keys that the client has already seen). [Bodo Moeller] *) Turn DSA_is_prime into a macro that calls BN_is_prime, using 50 iterations of the Rabin-Miller test. DSA_generate_parameters now uses BN_is_prime_fasttest (with 50 iterations of the Rabin-Miller test as required by the appendix to FIPS PUB 186[-1]) instead of DSA_is_prime. As BN_is_prime_fasttest includes trial division, DSA parameter generation becomes much faster. This implies a change for the callback functions in DSA_is_prime and DSA_generate_parameters: The callback function is called once for each positive witness in the Rabin-Miller test, not just occasionally in the inner loop; and the parameters to the callback function now provide an iteration count for the outer loop rather than for the current invocation of the inner loop. DSA_generate_parameters additionally can call the callback function with an 'iteration count' of -1, meaning that a candidate has passed the trial division test (when q is generated from an application-provided seed, trial division is skipped). [Bodo Moeller] *) New function BN_is_prime_fasttest that optionally does trial division before starting the Rabin-Miller test and has an additional BN_CTX * argument (whereas BN_is_prime always has to allocate at least one BN_CTX). 'callback(1, -1, cb_arg)' is called when a number has passed the trial division stage. [Bodo Moeller] *) Fix for bug in CRL encoding. The validity dates weren't being handled as ASN1_TIME. [Steve Henson] *) New -pkcs12 option to CA.pl script to write out a PKCS#12 file. [Steve Henson] *) New function BN_pseudo_rand(). [Ulf Möller] *) Clean up BN_mod_mul_montgomery(): replace the broken (and unreadable) bignum version of BN_from_montgomery() with the working code from SSLeay 0.9.0 (the word based version is faster anyway), and clean up the comments. [Ulf Möller] *) Avoid a race condition in s2_clnt.c (function get_server_hello) that made it impossible to use the same SSL_SESSION data structure in SSL2 clients in multiple threads. [Bodo Moeller] *) The return value of RAND_load_file() no longer counts bytes obtained by stat(). RAND_load_file(..., -1) is new and uses the complete file to seed the PRNG (previously an explicit byte count was required). [Ulf Möller, Bodo Möller] *) Clean up CRYPTO_EX_DATA functions, some of these didn't have prototypes used (char *) instead of (void *) and had casts all over the place. [Steve Henson] *) Make BN_generate_prime() return NULL on error if ret!=NULL. [Ulf Möller] *) Retain source code compatibility for BN_prime_checks macro: BN_is_prime(..., BN_prime_checks, ...) now uses BN_prime_checks_for_size to determine the appropriate number of Rabin-Miller iterations. [Ulf Möller] *) Diffie-Hellman uses "safe" primes: DH_check() return code renamed to DH_CHECK_P_NOT_SAFE_PRIME. (Check if this is true? OpenPGP calls them "strong".) [Ulf Möller] *) Merge the functionality of "dh" and "gendh" programs into a new program "dhparam". The old programs are retained for now but will handle DH keys (instead of parameters) in future. [Steve Henson] *) Make the ciphers, s_server and s_client programs check the return values when a new cipher list is set. [Steve Henson] *) Enhance the SSL/TLS cipher mechanism to correctly handle the TLS 56bit ciphers. Before when the 56bit ciphers were enabled the sorting was wrong. The syntax for the cipher sorting has been extended to support sorting by cipher-strength (using the strength_bits hard coded in the tables). The new command is "@STRENGTH" (see also doc/apps/ciphers.pod). Fix a bug in the cipher-command parser: when supplying a cipher command string with an "undefined" symbol (neither command nor alphanumeric [A-Za-z0-9], ssl_set_cipher_list used to hang in an endless loop. Now an error is flagged. Due to the strength-sorting extension, the code of the ssl_create_cipher_list() function was completely rearranged. I hope that the readability was also increased :-) [Lutz Jaenicke ] *) Minor change to 'x509' utility. The -CAcreateserial option now uses 1 for the first serial number and places 2 in the serial number file. This avoids problems when the root CA is created with serial number zero and the first user certificate has the same issuer name and serial number as the root CA. [Steve Henson] *) Fixes to X509_ATTRIBUTE utilities, change the 'req' program so it uses the new code. Add documentation for this stuff. [Steve Henson] *) Changes to X509_ATTRIBUTE utilities. These have been renamed from X509_*() to X509at_*() on the grounds that they don't handle X509 structures and behave in an analagous way to the X509v3 functions: they shouldn't be called directly but wrapper functions should be used instead. So we also now have some wrapper functions that call the X509at functions when passed certificate requests. (TO DO: similar things can be done with PKCS#7 signed and unsigned attributes, PKCS#12 attributes and a few other things. Some of these need some d2i or i2d and print functionality because they handle more complex structures.) [Steve Henson] *) Add missing #ifndefs that caused missing symbols when building libssl as a shared library without RSA. Use #ifndef NO_SSL2 instead of NO_RSA in ssl/s2*.c. [Kris Kennaway , modified by Ulf Möller] *) Precautions against using the PRNG uninitialized: RAND_bytes() now has a return value which indicates the quality of the random data (1 = ok, 0 = not seeded). Also an error is recorded on the thread's error queue. New function RAND_pseudo_bytes() generates output that is guaranteed to be unique but not unpredictable. RAND_add is like RAND_seed, but takes an extra argument for an entropy estimate (RAND_seed always assumes full entropy). [Ulf Möller] *) Do more iterations of Rabin-Miller probable prime test (specifically, 3 for 1024-bit primes, 6 for 512-bit primes, 12 for 256-bit primes instead of only 2 for all lengths; see BN_prime_checks_for_size definition in crypto/bn/bn_prime.c for the complete table). This guarantees a false-positive rate of at most 2^-80 for random input. [Bodo Moeller] *) Rewrite ssl3_read_n (ssl/s3_pkt.c) avoiding a couple of bugs. [Bodo Moeller] *) New function X509_CTX_rget_chain() (renamed to X509_CTX_get1_chain in the 0.9.5 release), this returns the chain from an X509_CTX structure with a dup of the stack and all the X509 reference counts upped: so the stack will exist after X509_CTX_cleanup() has been called. Modify pkcs12.c to use this. Also make SSL_SESSION_print() print out the verify return code. [Steve Henson] *) Add manpage for the pkcs12 command. Also change the default behaviour so MAC iteration counts are used unless the new -nomaciter option is used. This improves file security and only older versions of MSIE (4.0 for example) need it. [Steve Henson] *) Honor the no-xxx Configure options when creating .DEF files. [Ulf Möller] *) Add PKCS#10 attributes to field table: challengePassword, unstructuredName and unstructuredAddress. These are taken from draft PKCS#9 v2.0 but are compatible with v1.2 provided no international characters are used. More changes to X509_ATTRIBUTE code: allow the setting of types based on strings. Remove the 'loc' parameter when adding attributes because these will be a SET OF encoding which is sorted in ASN1 order. [Steve Henson] *) Initial changes to the 'req' utility to allow request generation automation. This will allow an application to just generate a template file containing all the field values and have req construct the request. Initial support for X509_ATTRIBUTE handling. Stacks of these are used all over the place including certificate requests and PKCS#7 structures. They are currently handled manually where necessary with some primitive wrappers for PKCS#7. The new functions behave in a manner analogous to the X509 extension functions: they allow attributes to be looked up by NID and added. Later something similar to the X509V3 code would be desirable to automatically handle the encoding, decoding and printing of the more complex types. The string types like challengePassword can be handled by the string table functions. Also modified the multi byte string table handling. Now there is a 'global mask' which masks out certain types. The table itself can use the flag STABLE_NO_MASK to ignore the mask setting: this is useful when for example there is only one permissible type (as in countryName) and using the mask might result in no valid types at all. [Steve Henson] *) Clean up 'Finished' handling, and add functions SSL_get_finished and SSL_get_peer_finished to allow applications to obtain the latest Finished messages sent to the peer or expected from the peer, respectively. (SSL_get_peer_finished is usually the Finished message actually received from the peer, otherwise the protocol will be aborted.) As the Finished message are message digests of the complete handshake (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can be used for external authentication procedures when the authentication provided by SSL/TLS is not desired or is not enough. [Bodo Moeller] *) Enhanced support for Alpha Linux is added. Now ./config checks if the host supports BWX extension and if Compaq C is present on the $PATH. Just exploiting of the BWX extension results in 20-30% performance kick for some algorithms, e.g. DES and RC4 to mention a couple. Compaq C in turn generates ~20% faster code for MD5 and SHA1. [Andy Polyakov] *) Add support for MS "fast SGC". This is arguably a violation of the SSL3/TLS protocol. Netscape SGC does two handshakes: the first with weak crypto and after checking the certificate is SGC a second one with strong crypto. MS SGC stops the first handshake after receiving the server certificate message and sends a second client hello. Since a server will typically do all the time consuming operations before expecting any further messages from the client (server key exchange is the most expensive) there is little difference between the two. To get OpenSSL to support MS SGC we have to permit a second client hello message after we have sent server done. In addition we have to reset the MAC if we do get this second client hello. [Steve Henson] *) Add a function 'd2i_AutoPrivateKey()' this will automatically decide if a DER encoded private key is RSA or DSA traditional format. Changed d2i_PrivateKey_bio() to use it. This is only needed for the "traditional" format DER encoded private key. Newer code should use PKCS#8 format which has the key type encoded in the ASN1 structure. Added DER private key support to pkcs8 application. [Steve Henson] *) SSL 3/TLS 1 servers now don't request certificates when an anonymous ciphersuites has been selected (as required by the SSL 3/TLS 1 specifications). Exception: When SSL_VERIFY_FAIL_IF_NO_PEER_CERT is set, we interpret this as a request to violate the specification (the worst that can happen is a handshake failure, and 'correct' behaviour would result in a handshake failure anyway). [Bodo Moeller] *) In SSL_CTX_add_session, take into account that there might be multiple SSL_SESSION structures with the same session ID (e.g. when two threads concurrently obtain them from an external cache). The internal cache can handle only one SSL_SESSION with a given ID, so if there's a conflict, we now throw out the old one to achieve consistency. [Bodo Moeller] *) Add OIDs for idea and blowfish in CBC mode. This will allow both to be used in PKCS#5 v2.0 and S/MIME. Also add checking to some routines that use cipher OIDs: some ciphers do not have OIDs defined and so they cannot be used for S/MIME and PKCS#5 v2.0 for example. [Steve Henson] *) Simplify the trust setting structure and code. Now we just have two sequences of OIDs for trusted and rejected settings. These will typically have values the same as the extended key usage extension and any application specific purposes. The trust checking code now has a default behaviour: it will just check for an object with the same NID as the passed id. Functions can be provided to override either the default behaviour or the behaviour for a given id. SSL client, server and email already have functions in place for compatibility: they check the NID and also return "trusted" if the certificate is self signed. [Steve Henson] *) Add d2i,i2d bio/fp functions for PrivateKey: these convert the traditional format into an EVP_PKEY structure. [Steve Henson] *) Add a password callback function PEM_cb() which either prompts for a password if usr_data is NULL or otherwise assumes it is a null terminated password. Allow passwords to be passed on command line environment or config files in a few more utilities. [Steve Henson] *) Add a bunch of DER and PEM functions to handle PKCS#8 format private keys. Add some short names for PKCS#8 PBE algorithms and allow them to be specified on the command line for the pkcs8 and pkcs12 utilities. Update documentation. [Steve Henson] *) Support for ASN1 "NULL" type. This could be handled before by using ASN1_TYPE but there wasn't any function that would try to read a NULL and produce an error if it couldn't. For compatibility we also have ASN1_NULL_new() and ASN1_NULL_free() functions but these are faked and don't allocate anything because they don't need to. [Steve Henson] *) Initial support for MacOS is now provided. Examine INSTALL.MacOS for details. [Andy Polyakov, Roy Woods ] *) Rebuild of the memory allocation routines used by OpenSSL code and possibly others as well. The purpose is to make an interface that provide hooks so anyone can build a separate set of allocation and deallocation routines to be used by OpenSSL, for example memory pool implementations, or something else, which was previously hard since Malloc(), Realloc() and Free() were defined as macros having the values malloc, realloc and free, respectively (except for Win32 compilations). The same is provided for memory debugging code. OpenSSL already comes with functionality to find memory leaks, but this gives people a chance to debug other memory problems. With these changes, a new set of functions and macros have appeared: CRYPTO_set_mem_debug_functions() [F] CRYPTO_get_mem_debug_functions() [F] CRYPTO_dbg_set_options() [F] CRYPTO_dbg_get_options() [F] CRYPTO_malloc_debug_init() [M] The memory debug functions are NULL by default, unless the library is compiled with CRYPTO_MDEBUG or friends is defined. If someone wants to debug memory anyway, CRYPTO_malloc_debug_init() (which gives the standard debugging functions that come with OpenSSL) or CRYPTO_set_mem_debug_functions() (tells OpenSSL to use functions provided by the library user) must be used. When the standard debugging functions are used, CRYPTO_dbg_set_options can be used to request additional information: CRYPTO_dbg_set_options(V_CYRPTO_MDEBUG_xxx) corresponds to setting the CRYPTO_MDEBUG_xxx macro when compiling the library. Also, things like CRYPTO_set_mem_functions will always give the expected result (the new set of functions is used for allocation and deallocation) at all times, regardless of platform and compiler options. To finish it up, some functions that were never use in any other way than through macros have a new API and new semantic: CRYPTO_dbg_malloc() CRYPTO_dbg_realloc() CRYPTO_dbg_free() All macros of value have retained their old syntax. [Richard Levitte and Bodo Moeller] *) Some S/MIME fixes. The OID for SMIMECapabilities was wrong, the ordering of SMIMECapabilities wasn't in "strength order" and there was a missing NULL in the AlgorithmIdentifier for the SHA1 signature algorithm. [Steve Henson] *) Some ASN1 types with illegal zero length encoding (INTEGER, ENUMERATED and OBJECT IDENTIFIER) choked the ASN1 routines. [Frans Heymans , modified by Steve Henson] *) Merge in my S/MIME library for OpenSSL. This provides a simple S/MIME API on top of the PKCS#7 code, a MIME parser (with enough functionality to handle multipart/signed properly) and a utility called 'smime' to call all this stuff. This is based on code I originally wrote for Celo who have kindly allowed it to be included in OpenSSL. [Steve Henson] *) Add variants des_set_key_checked and des_set_key_unchecked of des_set_key (aka des_key_sched). Global variable des_check_key decides which of these is called by des_set_key; this way des_check_key behaves as it always did, but applications and the library itself, which was buggy for des_check_key == 1, have a cleaner way to pick the version they need. [Bodo Moeller] *) New function PKCS12_newpass() which changes the password of a PKCS12 structure. [Steve Henson] *) Modify X509_TRUST and X509_PURPOSE so it also uses a static and dynamic mix. In both cases the ids can be used as an index into the table. Also modified the X509_TRUST_add() and X509_PURPOSE_add() functions so they accept a list of the field values and the application doesn't need to directly manipulate the X509_TRUST structure. [Steve Henson] *) Modify the ASN1_STRING_TABLE stuff so it also uses bsearch and doesn't need initialising. [Steve Henson] *) Modify the way the V3 extension code looks up extensions. This now works in a similar way to the object code: we have some "standard" extensions in a static table which is searched with OBJ_bsearch() and the application can add dynamic ones if needed. The file crypto/x509v3/ext_dat.h now has the info: this file needs to be updated whenever a new extension is added to the core code and kept in ext_nid order. There is a simple program 'tabtest.c' which checks this. New extensions are not added too often so this file can readily be maintained manually. There are two big advantages in doing things this way. The extensions can be looked up immediately and no longer need to be "added" using X509V3_add_standard_extensions(): this function now does nothing. [Side note: I get *lots* of email saying the extension code doesn't work because people forget to call this function] Also no dynamic allocation is done unless new extensions are added: so if we don't add custom extensions there is no need to call X509V3_EXT_cleanup(). [Steve Henson] *) Modify enc utility's salting as follows: make salting the default. Add a magic header, so unsalted files fail gracefully instead of just decrypting to garbage. This is because not salting is a big security hole, so people should be discouraged from doing it. [Ben Laurie] *) Fixes and enhancements to the 'x509' utility. It allowed a message digest to be passed on the command line but it only used this parameter when signing a certificate. Modified so all relevant operations are affected by the digest parameter including the -fingerprint and -x509toreq options. Also -x509toreq choked if a DSA key was used because it didn't fix the digest. [Steve Henson] *) Initial certificate chain verify code. Currently tests the untrusted certificates for consistency with the verify purpose (which is set when the X509_STORE_CTX structure is set up) and checks the pathlength. There is a NO_CHAIN_VERIFY compilation option to keep the old behaviour: this is because it will reject chains with invalid extensions whereas every previous version of OpenSSL and SSLeay made no checks at all. Trust code: checks the root CA for the relevant trust settings. Trust settings have an initial value consistent with the verify purpose: e.g. if the verify purpose is for SSL client use it expects the CA to be trusted for SSL client use. However the default value can be changed to permit custom trust settings: one example of this would be to only trust certificates from a specific "secure" set of CAs. Also added X509_STORE_CTX_new() and X509_STORE_CTX_free() functions which should be used for version portability: especially since the verify structure is likely to change more often now. SSL integration. Add purpose and trust to SSL_CTX and SSL and functions to set them. If not set then assume SSL clients will verify SSL servers and vice versa. Two new options to the verify program: -untrusted allows a set of untrusted certificates to be passed in and -purpose which sets the intended purpose of the certificate. If a purpose is set then the new chain verify code is used to check extension consistency. [Steve Henson] *) Support for the authority information access extension. [Steve Henson] *) Modify RSA and DSA PEM read routines to transparently handle PKCS#8 format private keys. New *_PUBKEY_* functions that handle public keys in a format compatible with certificate SubjectPublicKeyInfo structures. Unfortunately there were already functions called *_PublicKey_* which used various odd formats so these are retained for compatibility: however the DSA variants were never in a public release so they have been deleted. Changed dsa/rsa utilities to handle the new format: note no releases ever handled public keys so we should be OK. The primary motivation for this change is to avoid the same fiasco that dogs private keys: there are several incompatible private key formats some of which are standard and some OpenSSL specific and require various evil hacks to allow partial transparent handling and even then it doesn't work with DER formats. Given the option anything other than PKCS#8 should be dumped: but the other formats have to stay in the name of compatibility. With public keys and the benefit of hindsight one standard format is used which works with EVP_PKEY, RSA or DSA structures: though it clearly returns an error if you try to read the wrong kind of key. Added a -pubkey option to the 'x509' utility to output the public key. Also rename the EVP_PKEY_get_*() to EVP_PKEY_rget_*() (renamed to EVP_PKEY_get1_*() in the OpenSSL 0.9.5 release) and add EVP_PKEY_rset_*() functions (renamed to EVP_PKEY_set1_*()) that do the same as the EVP_PKEY_assign_*() except they up the reference count of the added key (they don't "swallow" the supplied key). [Steve Henson] *) Fixes to crypto/x509/by_file.c the code to read in certificates and CRLs would fail if the file contained no certificates or no CRLs: added a new function to read in both types and return the number read: this means that if none are read it will be an error. The DER versions of the certificate and CRL reader would always fail because it isn't possible to mix certificates and CRLs in DER format without choking one or the other routine. Changed this to just read a certificate: this is the best we can do. Also modified the code in apps/verify.c to take notice of return codes: it was previously attempting to read in certificates from NULL pointers and ignoring any errors: this is one reason why the cert and CRL reader seemed to work. It doesn't check return codes from the default certificate routines: these may well fail if the certificates aren't installed. [Steve Henson] *) Code to support otherName option in GeneralName. [Steve Henson] *) First update to verify code. Change the verify utility so it warns if it is passed a self signed certificate: for consistency with the normal behaviour. X509_verify has been modified to it will now verify a self signed certificate if *exactly* the same certificate appears in the store: it was previously impossible to trust a single self signed certificate. This means that: openssl verify ss.pem now gives a warning about a self signed certificate but openssl verify -CAfile ss.pem ss.pem is OK. [Steve Henson] *) For servers, store verify_result in SSL_SESSION data structure (and add it to external session representation). This is needed when client certificate verifications fails, but an application-provided verification callback (set by SSL_CTX_set_cert_verify_callback) allows accepting the session anyway (i.e. leaves x509_store_ctx->error != X509_V_OK but returns 1): When the session is reused, we have to set ssl->verify_result to the appropriate error code to avoid security holes. [Bodo Moeller, problem pointed out by Lutz Jaenicke] *) Fix a bug in the new PKCS#7 code: it didn't consider the case in PKCS7_dataInit() where the signed PKCS7 structure didn't contain any existing data because it was being created. [Po-Cheng Chen , slightly modified by Steve Henson] *) Add a salt to the key derivation routines in enc.c. This forms the first 8 bytes of the encrypted file. Also add a -S option to allow a salt to be input on the command line. [Steve Henson] *) New function X509_cmp(). Oddly enough there wasn't a function to compare two certificates. We do this by working out the SHA1 hash and comparing that. X509_cmp() will be needed by the trust code. [Steve Henson] *) SSL_get1_session() is like SSL_get_session(), but increments the reference count in the SSL_SESSION returned. [Geoff Thorpe ] *) Fix for 'req': it was adding a null to request attributes. Also change the X509_LOOKUP and X509_INFO code to handle certificate auxiliary information. [Steve Henson] *) Add support for 40 and 64 bit RC2 and RC4 algorithms: document the 'enc' command. [Steve Henson] *) Add the possibility to add extra information to the memory leak detecting output, to form tracebacks, showing from where each allocation was originated: CRYPTO_push_info("constant string") adds the string plus current file name and line number to a per-thread stack, CRYPTO_pop_info() does the obvious, CRYPTO_remove_all_info() is like calling CYRPTO_pop_info() until the stack is empty. Also updated memory leak detection code to be multi-thread-safe. [Richard Levitte] *) Add options -text and -noout to pkcs7 utility and delete the encryption options which never did anything. Update docs. [Steve Henson] *) Add options to some of the utilities to allow the pass phrase to be included on either the command line (not recommended on OSes like Unix) or read from the environment. Update the manpages and fix a few bugs. [Steve Henson] *) Add a few manpages for some of the openssl commands. [Steve Henson] *) Fix the -revoke option in ca. It was freeing up memory twice, leaking and not finding already revoked certificates. [Steve Henson] *) Extensive changes to support certificate auxiliary information. This involves the use of X509_CERT_AUX structure and X509_AUX functions. An X509_AUX function such as PEM_read_X509_AUX() can still read in a certificate file in the usual way but it will also read in any additional "auxiliary information". By doing things this way a fair degree of compatibility can be retained: existing certificates can have this information added using the new 'x509' options. Current auxiliary information includes an "alias" and some trust settings. The trust settings will ultimately be used in enhanced certificate chain verification routines: currently a certificate can only be trusted if it is self signed and then it is trusted for all purposes. [Steve Henson] *) Fix assembler for Alpha (tested only on DEC OSF not Linux or *BSD). The problem was that one of the replacement routines had not been working since SSLeay releases. For now the offending routine has been replaced with non-optimised assembler. Even so, this now gives around 95% performance improvement for 1024 bit RSA signs. [Mark Cox] *) Hack to fix PKCS#7 decryption when used with some unorthodox RC2 handling. Most clients have the effective key size in bits equal to the key length in bits: so a 40 bit RC2 key uses a 40 bit (5 byte) key. A few however don't do this and instead use the size of the decrypted key to determine the RC2 key length and the AlgorithmIdentifier to determine the effective key length. In this case the effective key length can still be 40 bits but the key length can be 168 bits for example. This is fixed by manually forcing an RC2 key into the EVP_PKEY structure because the EVP code can't currently handle unusual RC2 key sizes: it always assumes the key length and effective key length are equal. [Steve Henson] *) Add a bunch of functions that should simplify the creation of X509_NAME structures. Now you should be able to do: X509_NAME_add_entry_by_txt(nm, "CN", MBSTRING_ASC, "Steve", -1, -1, 0); and have it automatically work out the correct field type and fill in the structures. The more adventurous can try: X509_NAME_add_entry_by_txt(nm, field, MBSTRING_UTF8, str, -1, -1, 0); and it will (hopefully) work out the correct multibyte encoding. [Steve Henson] *) Change the 'req' utility to use the new field handling and multibyte copy routines. Before the DN field creation was handled in an ad hoc way in req, ca, and x509 which was rather broken and didn't support BMPStrings or UTF8Strings. Since some software doesn't implement BMPStrings or UTF8Strings yet, they can be enabled using the config file using the dirstring_type option. See the new comment in the default openssl.cnf for more info. [Steve Henson] *) Make crypto/rand/md_rand.c more robust: - Assure unique random numbers after fork(). - Make sure that concurrent threads access the global counter and md serializably so that we never lose entropy in them or use exactly the same state in multiple threads. Access to the large state is not always serializable because the additional locking could be a performance killer, and md should be large enough anyway. [Bodo Moeller] *) New file apps/app_rand.c with commonly needed functionality for handling the random seed file. Use the random seed file in some applications that previously did not: ca, dsaparam -genkey (which also ignored its '-rand' option), s_client, s_server, x509 (when signing). Except on systems with /dev/urandom, it is crucial to have a random seed file at least for key creation, DSA signing, and for DH exchanges; for RSA signatures we could do without one. gendh and gendsa (unlike genrsa) used to read only the first byte of each file listed in the '-rand' option. The function as previously found in genrsa is now in app_rand.c and is used by all programs that support '-rand'. [Bodo Moeller] *) In RAND_write_file, use mode 0600 for creating files; don't just chmod when it may be too late. [Bodo Moeller] *) Report an error from X509_STORE_load_locations when X509_LOOKUP_load_file or X509_LOOKUP_add_dir failed. [Bill Perry] *) New function ASN1_mbstring_copy() this copies a string in either ASCII, Unicode, Universal (4 bytes per character) or UTF8 format into an ASN1_STRING type. A mask of permissible types is passed and it chooses the "minimal" type to use or an error if not type is suitable. [Steve Henson] *) Add function equivalents to the various macros in asn1.h. The old macros are retained with an M_ prefix. Code inside the library can use the M_ macros. External code (including the openssl utility) should *NOT* in order to be "shared library friendly". [Steve Henson] *) Add various functions that can check a certificate's extensions to see if it usable for various purposes such as SSL client, server or S/MIME and CAs of these types. This is currently VERY EXPERIMENTAL but will ultimately be used for certificate chain verification. Also added a -purpose flag to x509 utility to print out all the purposes. [Steve Henson] *) Add a CRYPTO_EX_DATA to X509 certificate structure and associated functions. [Steve Henson] *) New X509V3_{X509,CRL,REVOKED}_get_d2i() functions. These will search for, obtain and decode and extension and obtain its critical flag. This allows all the necessary extension code to be handled in a single function call. [Steve Henson] *) RC4 tune-up featuring 30-40% performance improvement on most RISC platforms. See crypto/rc4/rc4_enc.c for further details. [Andy Polyakov] *) New -noout option to asn1parse. This causes no output to be produced its main use is when combined with -strparse and -out to extract data from a file (which may not be in ASN.1 format). [Steve Henson] *) Fix for pkcs12 program. It was hashing an invalid certificate pointer when producing the local key id. [Richard Levitte ] *) New option -dhparam in s_server. This allows a DH parameter file to be stated explicitly. If it is not stated then it tries the first server certificate file. The previous behaviour hard coded the filename "server.pem". [Steve Henson] *) Add -pubin and -pubout options to the rsa and dsa commands. These allow a public key to be input or output. For example: openssl rsa -in key.pem -pubout -out pubkey.pem Also added necessary DSA public key functions to handle this. [Steve Henson] *) Fix so PKCS7_dataVerify() doesn't crash if no certificates are contained in the message. This was handled by allowing X509_find_by_issuer_and_serial() to tolerate a NULL passed to it. [Steve Henson, reported by Sampo Kellomaki ] *) Fix for bug in d2i_ASN1_bytes(): other ASN1 functions add an extra null to the end of the strings whereas this didn't. This would cause problems if strings read with d2i_ASN1_bytes() were later modified. [Steve Henson, reported by Arne Ansper ] *) Fix for base64 decode bug. When a base64 bio reads only one line of data and it contains EOF it will end up returning an error. This is caused by input 46 bytes long. The cause is due to the way base64 BIOs find the start of base64 encoded data. They do this by trying a trial decode on each line until they find one that works. When they do a flag is set and it starts again knowing it can pass all the data directly through the decoder. Unfortunately it doesn't reset the context it uses. This means that if EOF is reached an attempt is made to pass two EOFs through the context and this causes the resulting error. This can also cause other problems as well. As is usual with these problems it takes *ages* to find and the fix is trivial: move one line. [Steve Henson, reported by ian@uns.ns.ac.yu (Ivan Nejgebauer) ] *) Ugly workaround to get s_client and s_server working under Windows. The old code wouldn't work because it needed to select() on sockets and the tty (for keypresses and to see if data could be written). Win32 only supports select() on sockets so we select() with a 1s timeout on the sockets and then see if any characters are waiting to be read, if none are present then we retry, we also assume we can always write data to the tty. This isn't nice because the code then blocks until we've received a complete line of data and it is effectively polling the keyboard at 1s intervals: however it's quite a bit better than not working at all :-) A dedicated Windows application might handle this with an event loop for example. [Steve Henson] *) Enhance RSA_METHOD structure. Now there are two extra methods, rsa_sign and rsa_verify. When the RSA_FLAGS_SIGN_VER option is set these functions will be called when RSA_sign() and RSA_verify() are used. This is useful if rsa_pub_dec() and rsa_priv_enc() equivalents are not available. For this to work properly RSA_public_decrypt() and RSA_private_encrypt() should *not* be used: RSA_sign() and RSA_verify() must be used instead. This necessitated the support of an extra signature type NID_md5_sha1 for SSL signatures and modifications to the SSL library to use it instead of calling RSA_public_decrypt() and RSA_private_encrypt(). [Steve Henson] *) Add new -verify -CAfile and -CApath options to the crl program, these will lookup a CRL issuers certificate and verify the signature in a similar way to the verify program. Tidy up the crl program so it no longer accesses structures directly. Make the ASN1 CRL parsing a bit less strict. It will now permit CRL extensions even if it is not a V2 CRL: this will allow it to tolerate some broken CRLs. [Steve Henson] *) Initialize all non-automatic variables each time one of the openssl sub-programs is started (this is necessary as they may be started multiple times from the "OpenSSL>" prompt). [Lennart Bang, Bodo Moeller] *) Preliminary compilation option RSA_NULL which disables RSA crypto without removing all other RSA functionality (this is what NO_RSA does). This is so (for example) those in the US can disable those operations covered by the RSA patent while allowing storage and parsing of RSA keys and RSA key generation. [Steve Henson] *) Non-copying interface to BIO pairs. (still largely untested) [Bodo Moeller] *) New function ANS1_tag2str() to convert an ASN1 tag to a descriptive ASCII string. This was handled independently in various places before. [Steve Henson] *) New functions UTF8_getc() and UTF8_putc() that parse and generate UTF8 strings a character at a time. [Steve Henson] *) Use client_version from client hello to select the protocol (s23_srvr.c) and for RSA client key exchange verification (s3_srvr.c), as required by the SSL 3.0/TLS 1.0 specifications. [Bodo Moeller] *) Add various utility functions to handle SPKACs, these were previously handled by poking round in the structure internals. Added new function NETSCAPE_SPKI_print() to print out SPKAC and a new utility 'spkac' to print, verify and generate SPKACs. Based on an original idea from Massimiliano Pala but extensively modified. [Steve Henson] *) RIPEMD160 is operational on all platforms and is back in 'make test'. [Andy Polyakov] *) Allow the config file extension section to be overwritten on the command line. Based on an original idea from Massimiliano Pala . The new option is called -extensions and can be applied to ca, req and x509. Also -reqexts to override the request extensions in req and -crlexts to override the crl extensions in ca. [Steve Henson] *) Add new feature to the SPKAC handling in ca. Now you can include the same field multiple times by preceding it by "XXXX." for example: 1.OU="Unit name 1" 2.OU="Unit name 2" this is the same syntax as used in the req config file. [Steve Henson] *) Allow certificate extensions to be added to certificate requests. These are specified in a 'req_extensions' option of the req section of the config file. They can be printed out with the -text option to req but are otherwise ignored at present. [Steve Henson] *) Fix a horrible bug in enc_read() in crypto/evp/bio_enc.c: if the first data read consists of only the final block it would not decrypted because EVP_CipherUpdate() would correctly report zero bytes had been decrypted. A misplaced 'break' also meant the decrypted final block might not be copied until the next read. [Steve Henson] *) Initial support for DH_METHOD. Again based on RSA_METHOD. Also added a few extra parameters to the DH structure: these will be useful if for example we want the value of 'q' or implement X9.42 DH. [Steve Henson] *) Initial support for DSA_METHOD. This is based on the RSA_METHOD and provides hooks that allow the default DSA functions or functions on a "per key" basis to be replaced. This allows hardware acceleration and hardware key storage to be handled without major modification to the library. Also added low level modexp hooks and CRYPTO_EX structure and associated functions. [Steve Henson] *) Add a new flag to memory BIOs, BIO_FLAG_MEM_RDONLY. This marks the BIO as "read only": it can't be written to and the buffer it points to will not be freed. Reading from a read only BIO is much more efficient than a normal memory BIO. This was added because there are several times when an area of memory needs to be read from a BIO. The previous method was to create a memory BIO and write the data to it, this results in two copies of the data and an O(n^2) reading algorithm. There is a new function BIO_new_mem_buf() which creates a read only memory BIO from an area of memory. Also modified the PKCS#7 routines to use read only memory BIOs. [Steve Henson] *) Bugfix: ssl23_get_client_hello did not work properly when called in state SSL23_ST_SR_CLNT_HELLO_B, i.e. when the first 7 bytes of a SSLv2-compatible client hello for SSLv3 or TLSv1 could be read, but a retry condition occured while trying to read the rest. [Bodo Moeller] *) The PKCS7_ENC_CONTENT_new() function was setting the content type as NID_pkcs7_encrypted by default: this was wrong since this should almost always be NID_pkcs7_data. Also modified the PKCS7_set_type() to handle the encrypted data type: this is a more sensible place to put it and it allows the PKCS#12 code to be tidied up that duplicated this functionality. [Steve Henson] *) Changed obj_dat.pl script so it takes its input and output files on the command line. This should avoid shell escape redirection problems under Win32. [Steve Henson] *) Initial support for certificate extension requests, these are included in things like Xenroll certificate requests. Included functions to allow extensions to be obtained and added. [Steve Henson] *) -crlf option to s_client and s_server for sending newlines as CRLF (as required by many protocols). [Bodo Moeller] Changes between 0.9.3a and 0.9.4 [09 Aug 1999] *) Install libRSAglue.a when OpenSSL is built with RSAref. [Ralf S. Engelschall] *) A few more ``#ifndef NO_FP_API / #endif'' pairs for consistency. [Andrija Antonijevic ] *) Fix -startdate and -enddate (which was missing) arguments to 'ca' program. [Steve Henson] *) New function DSA_dup_DH, which duplicates DSA parameters/keys as DH parameters/keys (q is lost during that conversion, but the resulting DH parameters contain its length). For 1024-bit p, DSA_generate_parameters followed by DSA_dup_DH is much faster than DH_generate_parameters (which creates parameters where p = 2*q + 1), and also the smaller q makes DH computations much more efficient (160-bit exponentiation instead of 1024-bit exponentiation); so this provides a convenient way to support DHE ciphersuites in SSL/TLS servers (see ssl/ssltest.c). It is of utter importance to use SSL_CTX_set_options(s_ctx, SSL_OP_SINGLE_DH_USE); or SSL_set_options(s_ctx, SSL_OP_SINGLE_DH_USE); when such DH parameters are used, because otherwise small subgroup attacks may become possible! [Bodo Moeller] *) Avoid memory leak in i2d_DHparams. [Bodo Moeller] *) Allow the -k option to be used more than once in the enc program: this allows the same encrypted message to be read by multiple recipients. [Steve Henson] *) New function OBJ_obj2txt(buf, buf_len, a, no_name), this converts an ASN1_OBJECT to a text string. If the "no_name" parameter is set then it will always use the numerical form of the OID, even if it has a short or long name. [Steve Henson] *) Added an extra RSA flag: RSA_FLAG_EXT_PKEY. Previously the rsa_mod_exp method only got called if p,q,dmp1,dmq1,iqmp components were present, otherwise bn_mod_exp was called. In the case of hardware keys for example no private key components need be present and it might store extra data in the RSA structure, which cannot be accessed from bn_mod_exp. By setting RSA_FLAG_EXT_PKEY rsa_mod_exp will always be called for private key operations. [Steve Henson] *) Added support for SPARC Linux. [Andy Polyakov] *) pem_password_cb function type incompatibly changed from typedef int pem_password_cb(char *buf, int size, int rwflag); to ....(char *buf, int size, int rwflag, void *userdata); so that applications can pass data to their callbacks: The PEM[_ASN1]_{read,write}... functions and macros now take an additional void * argument, which is just handed through whenever the password callback is called. [Damien Miller ; tiny changes by Bodo Moeller] New function SSL_CTX_set_default_passwd_cb_userdata. Compatibility note: As many C implementations push function arguments onto the stack in reverse order, the new library version is likely to interoperate with programs that have been compiled with the old pem_password_cb definition (PEM_whatever takes some data that happens to be on the stack as its last argument, and the callback just ignores this garbage); but there is no guarantee whatsoever that this will work. *) The -DPLATFORM="\"$(PLATFORM)\"" definition and the similar -DCFLAGS=... (both in crypto/Makefile.ssl for use by crypto/cversion.c) caused problems not only on Windows, but also on some Unix platforms. To avoid problematic command lines, these definitions are now in an auto-generated file crypto/buildinf.h (created by crypto/Makefile.ssl for standard "make" builds, by util/mk1mf.pl for "mk1mf" builds). [Bodo Moeller] *) MIPS III/IV assembler module is reimplemented. [Andy Polyakov] *) More DES library cleanups: remove references to srand/rand and delete an unused file. [Ulf Möller] *) Add support for the the free Netwide assembler (NASM) under Win32, since not many people have MASM (ml) and it can be hard to obtain. This is currently experimental but it seems to work OK and pass all the tests. Check out INSTALL.W32 for info. [Steve Henson] *) Fix memory leaks in s3_clnt.c: All non-anonymous SSL3/TLS1 connections without temporary keys kept an extra copy of the server key, and connections with temporary keys did not free everything in case of an error. [Bodo Moeller] *) New function RSA_check_key and new openssl rsa option -check for verifying the consistency of RSA keys. [Ulf Moeller, Bodo Moeller] *) Various changes to make Win32 compile work: 1. Casts to avoid "loss of data" warnings in p5_crpt2.c 2. Change unsigned int to int in b_dump.c to avoid "signed/unsigned comparison" warnings. 3. Add sk__sort to DEF file generator and do make update. [Steve Henson] *) Add a debugging option to PKCS#5 v2 key generation function: when you #define DEBUG_PKCS5V2 passwords, salts, iteration counts and derived keys are printed to stderr. [Steve Henson] *) Copy the flags in ASN1_STRING_dup(). [Roman E. Pavlov ] *) The x509 application mishandled signing requests containing DSA keys when the signing key was also DSA and the parameters didn't match. It was supposed to omit the parameters when they matched the signing key: the verifying software was then supposed to automatically use the CA's parameters if they were absent from the end user certificate. Omitting parameters is no longer recommended. The test was also the wrong way round! This was probably due to unusual behaviour in EVP_cmp_parameters() which returns 1 if the parameters match. This meant that parameters were omitted when they *didn't* match and the certificate was useless. Certificates signed with 'ca' didn't have this bug. [Steve Henson, reported by Doug Erickson ] *) Memory leak checking (-DCRYPTO_MDEBUG) had some problems. The interface is as follows: Applications can use CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON) aka MemCheck_start(), CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_OFF) aka MemCheck_stop(); "off" is now the default. The library internally uses CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE) aka MemCheck_off(), CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE) aka MemCheck_on() to disable memory-checking temporarily. Some inconsistent states that previously were possible (and were even the default) are now avoided. -DCRYPTO_MDEBUG_TIME is new and additionally stores the current time with each memory chunk allocated; this is occasionally more helpful than just having a counter. -DCRYPTO_MDEBUG_THREAD is also new and adds the thread ID. -DCRYPTO_MDEBUG_ALL enables all of the above, plus any future extensions. [Bodo Moeller] *) Introduce "mode" for SSL structures (with defaults in SSL_CTX), which largely parallels "options", but is for changing API behaviour, whereas "options" are about protocol behaviour. Initial "mode" flags are: SSL_MODE_ENABLE_PARTIAL_WRITE Allow SSL_write to report success when a single record has been written. SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER Don't insist that SSL_write retries use the same buffer location. (But all of the contents must be copied!) [Bodo Moeller] *) Bugfix: SSL_set_options ignored its parameter, only SSL_CTX_set_options worked. *) Fix problems with no-hmac etc. [Ulf Möller, pointed out by Brian Wellington ] *) New functions RSA_get_default_method(), RSA_set_method() and RSA_get_method(). These allows replacement of RSA_METHODs without having to mess around with the internals of an RSA structure. [Steve Henson] *) Fix memory leaks in DSA_do_sign and DSA_is_prime. Also really enable memory leak checks in openssl.c and in some test programs. [Chad C. Mulligan, Bodo Moeller] *) Fix a bug in d2i_ASN1_INTEGER() and i2d_ASN1_INTEGER() which can mess up the length of negative integers. This has now been simplified to just store the length when it is first determined and use it later, rather than trying to keep track of where data is copied and updating it to point to the end. [Steve Henson, reported by Brien Wheeler ] *) Add a new function PKCS7_signatureVerify. This allows the verification of a PKCS#7 signature but with the signing certificate passed to the function itself. This contrasts with PKCS7_dataVerify which assumes the certificate is present in the PKCS#7 structure. This isn't always the case: certificates can be omitted from a PKCS#7 structure and be distributed by "out of band" means (such as a certificate database). [Steve Henson] *) Complete the PEM_* macros with DECLARE_PEM versions to replace the function prototypes in pem.h, also change util/mkdef.pl to add the necessary function names. [Steve Henson] *) mk1mf.pl (used by Windows builds) did not properly read the options set by Configure in the top level Makefile, and Configure was not even able to write more than one option correctly. Fixed, now "no-idea no-rc5 -DCRYPTO_MDEBUG" etc. works as intended. [Bodo Moeller] *) New functions CONF_load_bio() and CONF_load_fp() to allow a config file to be loaded from a BIO or FILE pointer. The BIO version will for example allow memory BIOs to contain config info. [Steve Henson] *) New function "CRYPTO_num_locks" that returns CRYPTO_NUM_LOCKS. Whoever hopes to achieve shared-library compatibility across versions must use this, not the compile-time macro. (Exercise 0.9.4: Which is the minimum library version required by such programs?) Note: All this applies only to multi-threaded programs, others don't need locks. [Bodo Moeller] *) Add missing case to s3_clnt.c state machine -- one of the new SSL tests through a BIO pair triggered the default case, i.e. SSLerr(...,SSL_R_UNKNOWN_STATE). [Bodo Moeller] *) New "BIO pair" concept (crypto/bio/bss_bio.c) so that applications can use the SSL library even if none of the specific BIOs is appropriate. [Bodo Moeller] *) Fix a bug in i2d_DSAPublicKey() which meant it returned the wrong value for the encoded length. [Jeon KyoungHo ] *) Add initial documentation of the X509V3 functions. [Steve Henson] *) Add a new pair of functions PEM_write_PKCS8PrivateKey() and PEM_write_bio_PKCS8PrivateKey() that are equivalent to PEM_write_PrivateKey() and PEM_write_bio_PrivateKey() but use the more secure PKCS#8 private key format with a high iteration count. [Steve Henson] *) Fix determination of Perl interpreter: A perl or perl5 _directory_ in $PATH was also accepted as the interpreter. [Ralf S. Engelschall] *) Fix demos/sign/sign.c: well there wasn't anything strictly speaking wrong with it but it was very old and did things like calling PEM_ASN1_read() directly and used MD5 for the hash not to mention some unusual formatting. [Steve Henson] *) Fix demos/selfsign.c: it used obsolete and deleted functions, changed to use the new extension code. [Steve Henson] *) Implement the PEM_read/PEM_write functions in crypto/pem/pem_all.c with macros. This should make it easier to change their form, add extra arguments etc. Fix a few PEM prototypes which didn't have cipher as a constant. [Steve Henson] *) Add to configuration table a new entry that can specify an alternative name for unistd.h (for pre-POSIX systems); we need this for NeXTstep, according to Mark Crispin . [Bodo Moeller] #if 0 *) DES CBC did not update the IV. Weird. [Ben Laurie] #else des_cbc_encrypt does not update the IV, but des_ncbc_encrypt does. Changing the behaviour of the former might break existing programs -- where IV updating is needed, des_ncbc_encrypt can be used. #endif *) When bntest is run from "make test" it drives bc to check its calculations, as well as internally checking them. If an internal check fails, it needs to cause bc to give a non-zero result or make test carries on without noticing the failure. Fixed. [Ben Laurie] *) DES library cleanups. [Ulf Möller] *) Add support for PKCS#5 v2.0 PBE algorithms. This will permit PKCS#8 to be used with any cipher unlike PKCS#5 v1.5 which can at most handle 64 bit ciphers. NOTE: although the key derivation function has been verified against some published test vectors it has not been extensively tested yet. Added a -v2 "cipher" option to pkcs8 application to allow the use of v2.0. [Steve Henson] *) Instead of "mkdir -p", which is not fully portable, use new Perl script "util/mkdir-p.pl". [Bodo Moeller] *) Rewrite the way password based encryption (PBE) is handled. It used to assume that the ASN1 AlgorithmIdentifier parameter was a PBEParameter structure. This was true for the PKCS#5 v1.5 and PKCS#12 PBE algorithms but doesn't apply to PKCS#5 v2.0 where it can be something else. Now the 'parameter' field of the AlgorithmIdentifier is passed to the underlying key generation function so it must do its own ASN1 parsing. This has also changed the EVP_PBE_CipherInit() function which now has a 'parameter' argument instead of literal salt and iteration count values and the function EVP_PBE_ALGOR_CipherInit() has been deleted. [Steve Henson] *) Support for PKCS#5 v1.5 compatible password based encryption algorithms and PKCS#8 functionality. New 'pkcs8' application linked to openssl. Needed to change the PEM_STRING_EVP_PKEY value which was just "PRIVATE KEY" because this clashed with PKCS#8 unencrypted string. Since this value was just used as a "magic string" and not used directly its value doesn't matter. [Steve Henson] *) Introduce some semblance of const correctness to BN. Shame C doesn't support mutable. [Ben Laurie] *) "linux-sparc64" configuration (ultrapenguin). [Ray Miller ] "linux-sparc" configuration. [Christian Forster ] *) config now generates no-xxx options for missing ciphers. [Ulf Möller] *) Support the EBCDIC character set (work in progress). File ebcdic.c not yet included because it has a different license. [Martin Kraemer ] *) Support BS2000/OSD-POSIX. [Martin Kraemer ] *) Make callbacks for key generation use void * instead of char *. [Ben Laurie] *) Make S/MIME samples compile (not yet tested). [Ben Laurie] *) Additional typesafe stacks. [Ben Laurie] *) New configuration variants "bsdi-elf-gcc" (BSD/OS 4.x). [Bodo Moeller] Changes between 0.9.3 and 0.9.3a [29 May 1999] *) New configuration variant "sco5-gcc". *) Updated some demos. [Sean O Riordain, Wade Scholine] *) Add missing BIO_free at exit of pkcs12 application. [Wu Zhigang] *) Fix memory leak in conf.c. [Steve Henson] *) Updates for Win32 to assembler version of MD5. [Steve Henson] *) Set #! path to perl in apps/der_chop to where we found it instead of using a fixed path. [Bodo Moeller] *) SHA library changes for irix64-mips4-cc. [Andy Polyakov] *) Improvements for VMS support. [Richard Levitte] Changes between 0.9.2b and 0.9.3 [24 May 1999] *) Bignum library bug fix. IRIX 6 passes "make test" now! This also avoids the problems with SC4.2 and unpatched SC5. [Andy Polyakov ] *) New functions sk_num, sk_value and sk_set to replace the previous macros. These are required because of the typesafe stack would otherwise break existing code. If old code used a structure member which used to be STACK and is now STACK_OF (for example cert in a PKCS7_SIGNED structure) with sk_num or sk_value it would produce an error because the num, data members are not present in STACK_OF. Now it just produces a warning. sk_set replaces the old method of assigning a value to sk_value (e.g. sk_value(x, i) = y) which the library used in a few cases. Any code that does this will no longer work (and should use sk_set instead) but this could be regarded as a "questionable" behaviour anyway. [Steve Henson] *) Fix most of the other PKCS#7 bugs. The "experimental" code can now correctly handle encrypted S/MIME data. [Steve Henson] *) Change type of various DES function arguments from des_cblock (which means, in function argument declarations, pointer to char) to des_cblock * (meaning pointer to array with 8 char elements), which allows the compiler to do more typechecking; it was like that back in SSLeay, but with lots of ugly casts. Introduce new type const_des_cblock. [Bodo Moeller] *) Reorganise the PKCS#7 library and get rid of some of the more obvious problems: find RecipientInfo structure that matches recipient certificate and initialise the ASN1 structures properly based on passed cipher. [Steve Henson] *) Belatedly make the BN tests actually check the results. [Ben Laurie] *) Fix the encoding and decoding of negative ASN1 INTEGERS and conversion to and from BNs: it was completely broken. New compilation option NEG_PUBKEY_BUG to allow for some broken certificates that encode public key elements as negative integers. [Steve Henson] *) Reorganize and speed up MD5. [Andy Polyakov ] *) VMS support. [Richard Levitte ] *) New option -out to asn1parse to allow the parsed structure to be output to a file. This is most useful when combined with the -strparse option to examine the output of things like OCTET STRINGS. [Steve Henson] *) Make SSL library a little more fool-proof by not requiring any longer that SSL_set_{accept,connect}_state be called before SSL_{accept,connect} may be used (SSL_set_..._state is omitted in many applications because usually everything *appeared* to work as intended anyway -- now it really works as intended). [Bodo Moeller] *) Move openssl.cnf out of lib/. [Ulf Möller] *) Fix various things to let OpenSSL even pass ``egcc -pipe -O2 -Wall -Wshadow -Wpointer-arith -Wcast-align -Wmissing-prototypes -Wmissing-declarations -Wnested-externs -Winline'' with EGCS 1.1.2+ [Ralf S. Engelschall] *) Various fixes to the EVP and PKCS#7 code. It may now be able to handle PKCS#7 enveloped data properly. [Sebastian Akerman , modified by Steve] *) Create a duplicate of the SSL_CTX's CERT in SSL_new instead of copying pointers. The cert_st handling is changed by this in various ways (and thus what used to be known as ctx->default_cert is now called ctx->cert, since we don't resort to s->ctx->[default_]cert any longer when s->cert does not give us what we need). ssl_cert_instantiate becomes obsolete by this change. As soon as we've got the new code right (possibly it already is?), we have solved a couple of bugs of the earlier code where s->cert was used as if it could not have been shared with other SSL structures. Note that using the SSL API in certain dirty ways now will result in different behaviour than observed with earlier library versions: Changing settings for an SSL_CTX *ctx after having done s = SSL_new(ctx) does not influence s as it used to. In order to clean up things more thoroughly, inside SSL_SESSION we don't use CERT any longer, but a new structure SESS_CERT that holds per-session data (if available); currently, this is the peer's certificate chain and, for clients, the server's certificate and temporary key. CERT holds only those values that can have meaningful defaults in an SSL_CTX. [Bodo Moeller] *) New function X509V3_EXT_i2d() to create an X509_EXTENSION structure from the internal representation. Various PKCS#7 fixes: remove some evil casts and set the enc_dig_alg field properly based on the signing key type. [Steve Henson] *) Allow PKCS#12 password to be set from the command line or the environment. Let 'ca' get its config file name from the environment variables "OPENSSL_CONF" or "SSLEAY_CONF" (for consistency with 'req' and 'x509'). [Steve Henson] *) Allow certificate policies extension to use an IA5STRING for the organization field. This is contrary to the PKIX definition but VeriSign uses it and IE5 only recognises this form. Document 'x509' extension option. [Steve Henson] *) Add PEDANTIC compiler flag to allow compilation with gcc -pedantic, without disallowing inline assembler and the like for non-pedantic builds. [Ben Laurie] *) Support Borland C++ builder. [Janez Jere , modified by Ulf Möller] *) Support Mingw32. [Ulf Möller] *) SHA-1 cleanups and performance enhancements. [Andy Polyakov ] *) Sparc v8plus assembler for the bignum library. [Andy Polyakov ] *) Accept any -xxx and +xxx compiler options in Configure. [Ulf Möller] *) Update HPUX configuration. [Anonymous] *) Add missing sk__unshift() function to safestack.h [Ralf S. Engelschall] *) New function SSL_CTX_use_certificate_chain_file that sets the "extra_cert"s in addition to the certificate. (This makes sense only for "PEM" format files, as chains as a whole are not DER-encoded.) [Bodo Moeller] *) Support verify_depth from the SSL API. x509_vfy.c had what can be considered an off-by-one-error: Its depth (which was not part of the external interface) was actually counting the number of certificates in a chain; now it really counts the depth. [Bodo Moeller] *) Bugfix in crypto/x509/x509_cmp.c: The SSLerr macro was used instead of X509err, which often resulted in confusing error messages since the error codes are not globally unique (e.g. an alleged error in ssl3_accept when a certificate didn't match the private key). *) New function SSL_CTX_set_session_id_context that allows to set a default value (so that you don't need SSL_set_session_id_context for each connection using the SSL_CTX). [Bodo Moeller] *) OAEP decoding bug fix. [Ulf Möller] *) Support INSTALL_PREFIX for package builders, as proposed by David Harris. [Bodo Moeller] *) New Configure options "threads" and "no-threads". For systems where the proper compiler options are known (currently Solaris and Linux), "threads" is the default. [Bodo Moeller] *) New script util/mklink.pl as a faster substitute for util/mklink.sh. [Bodo Moeller] *) Install various scripts to $(OPENSSLDIR)/misc, not to $(INSTALLTOP)/bin -- they shouldn't clutter directories such as /usr/local/bin. [Bodo Moeller] *) "make linux-shared" to build shared libraries. [Niels Poppe ] *) New Configure option no- (rsa, idea, rc5, ...). [Ulf Möller] *) Add the PKCS#12 API documentation to openssl.txt. Preliminary support for extension adding in x509 utility. [Steve Henson] *) Remove NOPROTO sections and error code comments. [Ulf Möller] *) Partial rewrite of the DEF file generator to now parse the ANSI prototypes. [Steve Henson] *) New Configure options --prefix=DIR and --openssldir=DIR. [Ulf Möller] *) Complete rewrite of the error code script(s). It is all now handled by one script at the top level which handles error code gathering, header rewriting and C source file generation. It should be much better than the old method: it now uses a modified version of Ulf's parser to read the ANSI prototypes in all header files (thus the old K&R definitions aren't needed for error creation any more) and do a better job of translating function codes into names. The old 'ASN1 error code imbedded in a comment' is no longer necessary and it doesn't use .err files which have now been deleted. Also the error code call doesn't have to appear all on one line (which resulted in some large lines...). [Steve Henson] *) Change #include filenames from to . [Bodo Moeller] *) Change behaviour of ssl2_read when facing length-0 packets: Don't return 0 (which usually indicates a closed connection), but continue reading. [Bodo Moeller] *) Fix some race conditions. [Bodo Moeller] *) Add support for CRL distribution points extension. Add Certificate Policies and CRL distribution points documentation. [Steve Henson] *) Move the autogenerated header file parts to crypto/opensslconf.h. [Ulf Möller] *) Fix new 56-bit DES export ciphersuites: they were using 7 bytes instead of 8 of keying material. Merlin has also confirmed interop with this fix between OpenSSL and Baltimore C/SSL 2.0 and J/SSL 2.0. [Merlin Hughes ] *) Fix lots of warnings. [Richard Levitte ] *) In add_cert_dir() in crypto/x509/by_dir.c, break out of the loop if the directory spec didn't end with a LIST_SEPARATOR_CHAR. [Richard Levitte ] *) Fix problems with sizeof(long) == 8. [Andy Polyakov ] *) Change functions to ANSI C. [Ulf Möller] *) Fix typos in error codes. [Martin Kraemer , Ulf Möller] *) Remove defunct assembler files from Configure. [Ulf Möller] *) SPARC v8 assembler BIGNUM implementation. [Andy Polyakov ] *) Support for Certificate Policies extension: both print and set. Various additions to support the r2i method this uses. [Steve Henson] *) A lot of constification, and fix a bug in X509_NAME_oneline() that could return a const string when you are expecting an allocated buffer. [Ben Laurie] *) Add support for ASN1 types UTF8String and VISIBLESTRING, also the CHOICE types DirectoryString and DisplayText. [Steve Henson] *) Add code to allow r2i extensions to access the configuration database, add an LHASH database driver and add several ctx helper functions. [Steve Henson] *) Fix an evil bug in bn_expand2() which caused various BN functions to fail when they extended the size of a BIGNUM. [Steve Henson] *) Various utility functions to handle SXNet extension. Modify mkdef.pl to support typesafe stack. [Steve Henson] *) Fix typo in SSL_[gs]et_options(). [Nils Frostberg ] *) Delete various functions and files that belonged to the (now obsolete) old X509V3 handling code. [Steve Henson] *) New Configure option "rsaref". [Ulf Möller] *) Don't auto-generate pem.h. [Bodo Moeller] *) Introduce type-safe ASN.1 SETs. [Ben Laurie] *) Convert various additional casted stacks to type-safe STACK_OF() variants. [Ben Laurie, Ralf S. Engelschall, Steve Henson] *) Introduce type-safe STACKs. This will almost certainly break lots of code that links with OpenSSL (well at least cause lots of warnings), but fear not: the conversion is trivial, and it eliminates loads of evil casts. A few STACKed things have been converted already. Feel free to convert more. In the fullness of time, I'll do away with the STACK type altogether. [Ben Laurie] *) Add `openssl ca -revoke ' facility which revokes a certificate specified in by updating the entry in the index.txt file. This way one no longer has to edit the index.txt file manually for revoking a certificate. The -revoke option does the gory details now. [Massimiliano Pala , Ralf S. Engelschall] *) Fix `openssl crl -noout -text' combination where `-noout' killed the `-text' option at all and this way the `-noout -text' combination was inconsistent in `openssl crl' with the friends in `openssl x509|rsa|dsa'. [Ralf S. Engelschall] *) Make sure a corresponding plain text error message exists for the X509_V_ERR_CERT_REVOKED/23 error number which can occur when a verify callback function determined that a certificate was revoked. [Ralf S. Engelschall] *) Bugfix: In test/testenc, don't test "openssl " for ciphers that were excluded, e.g. by -DNO_IDEA. Also, test all available cipers including rc5, which was forgotten until now. In order to let the testing shell script know which algorithms are available, a new (up to now undocumented) command "openssl list-cipher-commands" is used. [Bodo Moeller] *) Bugfix: s_client occasionally would sleep in select() when it should have checked SSL_pending() first. [Bodo Moeller] *) New functions DSA_do_sign and DSA_do_verify to provide access to the raw DSA values prior to ASN.1 encoding. [Ulf Möller] *) Tweaks to Configure [Niels Poppe ] *) Add support for PKCS#5 v2.0 ASN1 PBES2 structures. No other support, yet... [Steve Henson] *) New variables $(RANLIB) and $(PERL) in the Makefiles. [Ulf Möller] *) New config option to avoid instructions that are illegal on the 80386. The default code is faster, but requires at least a 486. [Ulf Möller] *) Got rid of old SSL2_CLIENT_VERSION (inconsistently used) and SSL2_SERVER_VERSION (not used at all) macros, which are now the same as SSL2_VERSION anyway. [Bodo Moeller] *) New "-showcerts" option for s_client. [Bodo Moeller] *) Still more PKCS#12 integration. Add pkcs12 application to openssl application. Various cleanups and fixes. [Steve Henson] *) More PKCS#12 integration. Add new pkcs12 directory with Makefile.ssl and modify error routines to work internally. Add error codes and PBE init to library startup routines. [Steve Henson] *) Further PKCS#12 integration. Added password based encryption, PKCS#8 and packing functions to asn1 and evp. Changed function names and error codes along the way. [Steve Henson] *) PKCS12 integration: and so it begins... First of several patches to slowly integrate PKCS#12 functionality into OpenSSL. Add PKCS#12 objects to objects.h [Steve Henson] *) Add a new 'indent' option to some X509V3 extension code. Initial ASN1 and display support for Thawte strong extranet extension. [Steve Henson] *) Add LinuxPPC support. [Jeff Dubrule ] *) Get rid of redundant BN file bn_mulw.c, and rename bn_div64 to bn_div_words in alpha.s. [Hannes Reinecke and Ben Laurie] *) Make sure the RSA OAEP test is skipped under -DRSAref because OAEP isn't supported when OpenSSL is built with RSAref. [Ulf Moeller ] *) Move definitions of IS_SET/IS_SEQUENCE inside crypto/asn1/asn1.h so they no longer are missing under -DNOPROTO. [Soren S. Jorvang ] Changes between 0.9.1c and 0.9.2b [22 Mar 1999] *) Make SSL_get_peer_cert_chain() work in servers. Unfortunately, it still doesn't work when the session is reused. Coming soon! [Ben Laurie] *) Fix a security hole, that allows sessions to be reused in the wrong context thus bypassing client cert protection! All software that uses client certs and session caches in multiple contexts NEEDS PATCHING to allow session reuse! A fuller solution is in the works. [Ben Laurie, problem pointed out by Holger Reif, Bodo Moeller (and ???)] *) Some more source tree cleanups (removed obsolete files crypto/bf/asm/bf586.pl, test/test.txt and crypto/sha/asm/f.s; changed permission on "config" script to be executable) and a fix for the INSTALL document. [Ulf Moeller ] *) Remove some legacy and erroneous uses of malloc, free instead of Malloc, Free. [Lennart Bang , with minor changes by Steve] *) Make rsa_oaep_test return non-zero on error. [Ulf Moeller ] *) Add support for native Solaris shared libraries. Configure solaris-sparc-sc4-pic, make, then run shlib/solaris-sc4.sh. It'd be nice if someone would make that last step automatic. [Matthias Loepfe ] *) ctx_size was not built with the right compiler during "make links". Fixed. [Ben Laurie] *) Change the meaning of 'ALL' in the cipher list. It now means "everything except NULL ciphers". This means the default cipher list will no longer enable NULL ciphers. They need to be specifically enabled e.g. with the string "DEFAULT:eNULL". [Steve Henson] *) Fix to RSA private encryption routines: if p < q then it would occasionally produce an invalid result. This will only happen with externally generated keys because OpenSSL (and SSLeay) ensure p > q. [Steve Henson] *) Be less restrictive and allow also `perl util/perlpath.pl /path/to/bin/perl' in addition to `perl util/perlpath.pl /path/to/bin', because this way one can also use an interpreter named `perl5' (which is usually the name of Perl 5.xxx on platforms where an Perl 4.x is still installed as `perl'). [Matthias Loepfe ] *) Let util/clean-depend.pl work also with older Perl 5.00x versions. [Matthias Loepfe ] *) Fix Makefile.org so CC,CFLAG etc are passed to 'make links' add advapi32.lib to Win32 build and change the pem test comparision to fc.exe (thanks to Ulrich Kroener for the suggestion). Fix misplaced ASNI prototypes and declarations in evp.h and crypto/des/ede_cbcm_enc.c. [Steve Henson] *) DES quad checksum was broken on big-endian architectures. Fixed. [Ben Laurie] *) Comment out two functions in bio.h that aren't implemented. Fix up the Win32 test batch file so it (might) work again. The Win32 test batch file is horrible: I feel ill.... [Steve Henson] *) Move various #ifdefs around so NO_SYSLOG, NO_DIRENT etc are now selected in e_os.h. Audit of header files to check ANSI and non ANSI sections: 10 functions were absent from non ANSI section and not exported from Windows DLLs. Fixed up libeay.num for new functions. [Steve Henson] *) Make `openssl version' output lines consistent. [Ralf S. Engelschall] *) Fix Win32 symbol export lists for BIO functions: Added BIO_get_ex_new_index, BIO_get_ex_num, BIO_get_ex_data and BIO_set_ex_data to ms/libeay{16,32}.def. [Ralf S. Engelschall] *) Second round of fixing the OpenSSL perl/ stuff. It now at least compiled fine under Unix and passes some trivial tests I've now added. But the whole stuff is horribly incomplete, so a README.1ST with a disclaimer was added to make sure no one expects that this stuff really works in the OpenSSL 0.9.2 release. Additionally I've started to clean the XS sources up and fixed a few little bugs and inconsistencies in OpenSSL.{pm,xs} and openssl_bio.xs. [Ralf S. Engelschall] *) Fix the generation of two part addresses in perl. [Kenji Miyake , integrated by Ben Laurie] *) Add config entry for Linux on MIPS. [John Tobey ] *) Make links whenever Configure is run, unless we are on Windoze. [Ben Laurie] *) Permit extensions to be added to CRLs using crl_section in openssl.cnf. Currently only issuerAltName and AuthorityKeyIdentifier make any sense in CRLs. [Steve Henson] *) Add a useful kludge to allow package maintainers to specify compiler and other platforms details on the command line without having to patch the Configure script everytime: One now can use ``perl Configure :
'', i.e. platform ids are allowed to have details appended to them (seperated by colons). This is treated as there would be a static pre-configured entry in Configure's %table under key with value
and ``perl Configure '' is called. So, when you want to perform a quick test-compile under FreeBSD 3.1 with pgcc and without assembler stuff you can use ``perl Configure "FreeBSD-elf:pgcc:-O6:::"'' now, which overrides the FreeBSD-elf entry on-the-fly. [Ralf S. Engelschall] *) Disable new TLS1 ciphersuites by default: they aren't official yet. [Ben Laurie] *) Allow DSO flags like -fpic, -fPIC, -KPIC etc. to be specified on the `perl Configure ...' command line. This way one can compile OpenSSL libraries with Position Independent Code (PIC) which is needed for linking it into DSOs. [Ralf S. Engelschall] *) Remarkably, export ciphers were totally broken and no-one had noticed! Fixed. [Ben Laurie] *) Cleaned up the LICENSE document: The official contact for any license questions now is the OpenSSL core team under openssl-core@openssl.org. And add a paragraph about the dual-license situation to make sure people recognize that _BOTH_ the OpenSSL license _AND_ the SSLeay license apply to the OpenSSL toolkit. [Ralf S. Engelschall] *) General source tree makefile cleanups: Made `making xxx in yyy...' display consistent in the source tree and replaced `/bin/rm' by `rm'. Additonally cleaned up the `make links' target: Remove unnecessary semicolons, subsequent redundant removes, inline point.sh into mklink.sh to speed processing and no longer clutter the display with confusing stuff. Instead only the actually done links are displayed. [Ralf S. Engelschall] *) Permit null encryption ciphersuites, used for authentication only. It used to be necessary to set the preprocessor define SSL_ALLOW_ENULL to do this. It is now necessary to set SSL_FORBID_ENULL to prevent the use of null encryption. [Ben Laurie] *) Add a bunch of fixes to the PKCS#7 stuff. It used to sometimes reorder signed attributes when verifying signatures (this would break them), the detached data encoding was wrong and public keys obtained using X509_get_pubkey() weren't freed. [Steve Henson] *) Add text documentation for the BUFFER functions. Also added a work around to a Win95 console bug. This was triggered by the password read stuff: the last character typed gets carried over to the next fread(). If you were generating a new cert request using 'req' for example then the last character of the passphrase would be CR which would then enter the first field as blank. [Steve Henson] *) Added the new `Includes OpenSSL Cryptography Software' button as doc/openssl_button.{gif,html} which is similar in style to the old SSLeay button and can be used by applications based on OpenSSL to show the relationship to the OpenSSL project. [Ralf S. Engelschall] *) Remove confusing variables in function signatures in files ssl/ssl_lib.c and ssl/ssl.h. [Lennart Bong ] *) Don't install bss_file.c under PREFIX/include/ [Lennart Bong ] *) Get the Win32 compile working again. Modify mkdef.pl so it can handle functions that return function pointers and has support for NT specific stuff. Fix mk1mf.pl and VC-32.pl to support NT differences also. Various #ifdef WIN32 and WINNTs sprinkled about the place and some changes from unsigned to signed types: this was killing the Win32 compile. [Steve Henson] *) Add new certificate file to stack functions, SSL_add_dir_cert_subjects_to_stack() and SSL_add_file_cert_subjects_to_stack(). These largely supplant SSL_load_client_CA_file(), and can be used to add multiple certs easily to a stack (usually this is then handed to SSL_CTX_set_client_CA_list()). This means that Apache-SSL and similar packages don't have to mess around to add as many CAs as they want to the preferred list. [Ben Laurie] *) Experiment with doxygen documentation. Currently only partially applied to ssl/ssl_lib.c. See http://www.stack.nl/~dimitri/doxygen/index.html, and run doxygen with openssl.doxy as the configuration file. [Ben Laurie] *) Get rid of remaining C++-style comments which strict C compilers hate. [Ralf S. Engelschall, pointed out by Carlos Amengual] *) Changed BN_RECURSION in bn_mont.c to BN_RECURSION_MONT so it is not compiled in by default: it has problems with large keys. [Steve Henson] *) Add a bunch of SSL_xxx() functions for configuring the temporary RSA and DH private keys and/or callback functions which directly correspond to their SSL_CTX_xxx() counterparts but work on a per-connection basis. This is needed for applications which have to configure certificates on a per-connection basis (e.g. Apache+mod_ssl) instead of a per-context basis (e.g. s_server). For the RSA certificate situation is makes no difference, but for the DSA certificate situation this fixes the "no shared cipher" problem where the OpenSSL cipher selection procedure failed because the temporary keys were not overtaken from the context and the API provided no way to reconfigure them. The new functions now let applications reconfigure the stuff and they are in detail: SSL_need_tmp_RSA, SSL_set_tmp_rsa, SSL_set_tmp_dh, SSL_set_tmp_rsa_callback and SSL_set_tmp_dh_callback. Additionally a new non-public-API function ssl_cert_instantiate() is used as a helper function and also to reduce code redundancy inside ssl_rsa.c. [Ralf S. Engelschall] *) Move s_server -dcert and -dkey options out of the undocumented feature area because they are useful for the DSA situation and should be recognized by the users. [Ralf S. Engelschall] *) Fix the cipher decision scheme for export ciphers: the export bits are *not* within SSL_MKEY_MASK or SSL_AUTH_MASK, they are within SSL_EXP_MASK. So, the original variable has to be used instead of the already masked variable. [Richard Levitte ] *) Fix 'port' variable from `int' to `unsigned int' in crypto/bio/b_sock.c [Richard Levitte ] *) Change type of another md_len variable in pk7_doit.c:PKCS7_dataFinal() from `int' to `unsigned int' because it's a length and initialized by EVP_DigestFinal() which expects an `unsigned int *'. [Richard Levitte ] *) Don't hard-code path to Perl interpreter on shebang line of Configure script. Instead use the usual Shell->Perl transition trick. [Ralf S. Engelschall] *) Make `openssl x509 -noout -modulus' functional also for DSA certificates (in addition to RSA certificates) to match the behaviour of `openssl dsa -noout -modulus' as it's already the case for `openssl rsa -noout -modulus'. For RSA the -modulus is the real "modulus" while for DSA currently the public key is printed (a decision which was already done by `openssl dsa -modulus' in the past) which serves a similar purpose. Additionally the NO_RSA no longer completely removes the whole -modulus option; it now only avoids using the RSA stuff. Same applies to NO_DSA now, too. [Ralf S. Engelschall] *) Add Arne Ansper's reliable BIO - this is an encrypted, block-digested BIO. See the source (crypto/evp/bio_ok.c) for more info. [Arne Ansper ] *) Dump the old yucky req code that tried (and failed) to allow raw OIDs to be added. Now both 'req' and 'ca' can use new objects defined in the config file. [Steve Henson] *) Add cool BIO that does syslog (or event log on NT). [Arne Ansper , integrated by Ben Laurie] *) Add support for new TLS ciphersuites, TLS_RSA_EXPORT56_WITH_RC4_56_MD5, TLS_RSA_EXPORT56_WITH_RC2_CBC_56_MD5 and TLS_RSA_EXPORT56_WITH_DES_CBC_SHA, as specified in "56-bit Export Cipher Suites For TLS", draft-ietf-tls-56-bit-ciphersuites-00.txt. [Ben Laurie] *) Add preliminary config info for new extension code. [Steve Henson] *) Make RSA_NO_PADDING really use no padding. [Ulf Moeller ] *) Generate errors when private/public key check is done. [Ben Laurie] *) Overhaul for 'crl' utility. New function X509_CRL_print. Partial support for some CRL extensions and new objects added. [Steve Henson] *) Really fix the ASN1 IMPLICIT bug this time... Partial support for private key usage extension and fuller support for authority key id. [Steve Henson] *) Add OAEP encryption for the OpenSSL crypto library. OAEP is the improved padding method for RSA, which is recommended for new applications in PKCS #1 v2.0 (RFC 2437, October 1998). OAEP (Optimal Asymmetric Encryption Padding) has better theoretical foundations than the ad-hoc padding used in PKCS #1 v1.5. It is secure against Bleichbacher's attack on RSA. [Ulf Moeller , reformatted, corrected and integrated by Ben Laurie] *) Updates to the new SSL compression code [Eric A. Young, (from changes to C2Net SSLeay, integrated by Mark Cox)] *) Fix so that the version number in the master secret, when passed via RSA, checks that if TLS was proposed, but we roll back to SSLv3 (because the server will not accept higher), that the version number is 0x03,0x01, not 0x03,0x00 [Eric A. Young, (from changes to C2Net SSLeay, integrated by Mark Cox)] *) Run extensive memory leak checks on SSL apps. Fixed *lots* of memory leaks in ssl/ relating to new X509_get_pubkey() behaviour. Also fixes in apps/ and an unrelated leak in crypto/dsa/dsa_vrf.c [Steve Henson] *) Support for RAW extensions where an arbitrary extension can be created by including its DER encoding. See apps/openssl.cnf for an example. [Steve Henson] *) Make sure latest Perl versions don't interpret some generated C array code as Perl array code in the crypto/err/err_genc.pl script. [Lars Weber <3weber@informatik.uni-hamburg.de>] *) Modify ms/do_ms.bat to not generate assembly language makefiles since not many people have the assembler. Various Win32 compilation fixes and update to the INSTALL.W32 file with (hopefully) more accurate Win32 build instructions. [Steve Henson] *) Modify configure script 'Configure' to automatically create crypto/date.h file under Win32 and also build pem.h from pem.org. New script util/mkfiles.pl to create the MINFO file on environments that can't do a 'make files': perl util/mkfiles.pl >MINFO should work. [Steve Henson] *) Major rework of DES function declarations, in the pursuit of correctness and purity. As a result, many evil casts evaporated, and some weirdness, too. You may find this causes warnings in your code. Zapping your evil casts will probably fix them. Mostly. [Ben Laurie] *) Fix for a typo in asn1.h. Bug fix to object creation script obj_dat.pl. It considered a zero in an object definition to mean "end of object": none of the objects in objects.h have any zeros so it wasn't spotted. [Steve Henson, reported by Erwann ABALEA ] *) Add support for Triple DES Cipher Block Chaining with Output Feedback Masking (CBCM). In the absence of test vectors, the best I have been able to do is check that the decrypt undoes the encrypt, so far. Send me test vectors if you have them. [Ben Laurie] *) Correct calculation of key length for export ciphers (too much space was allocated for null ciphers). This has not been tested! [Ben Laurie] *) Modifications to the mkdef.pl for Win32 DEF file creation. The usage message is now correct (it understands "crypto" and "ssl" on its command line). There is also now an "update" option. This will update the util/ssleay.num and util/libeay.num files with any new functions. If you do a: perl util/mkdef.pl crypto ssl update it will update them. [Steve Henson] *) Overhauled the Perl interface (perl/*): - ported BN stuff to OpenSSL's different BN library - made the perl/ source tree CVS-aware - renamed the package from SSLeay to OpenSSL (the files still contain their history because I've copied them in the repository) - removed obsolete files (the test scripts will be replaced by better Test::Harness variants in the future) [Ralf S. Engelschall] *) First cut for a very conservative source tree cleanup: 1. merge various obsolete readme texts into doc/ssleay.txt where we collect the old documents and readme texts. 2. remove the first part of files where I'm already sure that we no longer need them because of three reasons: either they are just temporary files which were left by Eric or they are preserved original files where I've verified that the diff is also available in the CVS via "cvs diff -rSSLeay_0_8_1b" or they were renamed (as it was definitely the case for the crypto/md/ stuff). [Ralf S. Engelschall] *) More extension code. Incomplete support for subject and issuer alt name, issuer and authority key id. Change the i2v function parameters and add an extra 'crl' parameter in the X509V3_CTX structure: guess what that's for :-) Fix to ASN1 macro which messed up IMPLICIT tag and add f_enum.c which adds a2i, i2a for ENUMERATED. [Steve Henson] *) Preliminary support for ENUMERATED type. This is largely copied from the INTEGER code. [Steve Henson] *) Add new function, EVP_MD_CTX_copy() to replace frequent use of memcpy. [Eric A. Young, (from changes to C2Net SSLeay, integrated by Mark Cox)] *) Make sure `make rehash' target really finds the `openssl' program. [Ralf S. Engelschall, Matthias Loepfe ] *) Squeeze another 7% of speed out of MD5 assembler, at least on a P2. I'd like to hear about it if this slows down other processors. [Ben Laurie] *) Add CygWin32 platform information to Configure script. [Alan Batie ] *) Fixed ms/32all.bat script: `no_asm' -> `no-asm' [Rainer W. Gerling ] *) New program nseq to manipulate netscape certificate sequences [Steve Henson] *) Modify crl2pkcs7 so it supports multiple -certfile arguments. Fix a few typos. [Steve Henson] *) Fixes to BN code. Previously the default was to define BN_RECURSION but the BN code had some problems that would cause failures when doing certificate verification and some other functions. [Eric A. Young, (from changes to C2Net SSLeay, integrated by Mark Cox)] *) Add ASN1 and PEM code to support netscape certificate sequences. [Steve Henson] *) Add ASN1 and PEM code to support netscape certificate sequences. [Steve Henson] *) Add several PKIX and private extended key usage OIDs. [Steve Henson] *) Modify the 'ca' program to handle the new extension code. Modify openssl.cnf for new extension format, add comments. [Steve Henson] *) More X509 V3 changes. Fix typo in v3_bitstr.c. Add support to 'req' and add a sample to openssl.cnf so req -x509 now adds appropriate CA extensions. [Steve Henson] *) Continued X509 V3 changes. Add to other makefiles, integrate with the error code, add initial support to X509_print() and x509 application. [Steve Henson] *) Takes a deep breath and start addding X509 V3 extension support code. Add files in crypto/x509v3. Move original stuff to crypto/x509v3/old. All this stuff is currently isolated and isn't even compiled yet. [Steve Henson] *) Continuing patches for GeneralizedTime. Fix up certificate and CRL ASN1 to use ASN1_TIME and modify print routines to use ASN1_TIME_print. Removed the versions check from X509 routines when loading extensions: this allows certain broken certificates that don't set the version properly to be processed. [Steve Henson] *) Deal with irritating shit to do with dependencies, in YAAHW (Yet Another Ad Hoc Way) - Makefile.ssls now all contain local dependencies, which can still be regenerated with "make depend". [Ben Laurie] *) Spelling mistake in C version of CAST-128. [Ben Laurie, reported by Jeremy Hylton ] *) Changes to the error generation code. The perl script err-code.pl now reads in the old error codes and retains the old numbers, only adding new ones if necessary. It also only changes the .err files if new codes are added. The makefiles have been modified to only insert errors when needed (to avoid needlessly modifying header files). This is done by only inserting errors if the .err file is newer than the auto generated C file. To rebuild all the error codes from scratch (the old behaviour) either modify crypto/Makefile.ssl to pass the -regen flag to err_code.pl or delete all the .err files. [Steve Henson] *) CAST-128 was incorrectly implemented for short keys. The C version has been fixed, but is untested. The assembler versions are also fixed, but new assembler HAS NOT BEEN GENERATED FOR WIN32 - the Makefile needs fixing to regenerate it if needed. [Ben Laurie, reported (with fix for C version) by Jun-ichiro itojun Hagino ] *) File was opened incorrectly in randfile.c. [Ulf Möller ] *) Beginning of support for GeneralizedTime. d2i, i2d, check and print functions. Also ASN1_TIME suite which is a CHOICE of UTCTime or GeneralizedTime. ASN1_TIME is the proper type used in certificates et al: it's just almost always a UTCTime. Note this patch adds new error codes so do a "make errors" if there are problems. [Steve Henson] *) Correct Linux 1 recognition in config. [Ulf Möller ] *) Remove pointless MD5 hash when using DSA keys in ca. [Anonymous ] *) Generate an error if given an empty string as a cert directory. Also generate an error if handed NULL (previously returned 0 to indicate an error, but didn't set one). [Ben Laurie, reported by Anonymous ] *) Add prototypes to SSL methods. Make SSL_write's buffer const, at last. [Ben Laurie] *) Fix the dummy function BN_ref_mod_exp() in rsaref.c to have the correct parameters. This was causing a warning which killed off the Win32 compile. [Steve Henson] *) Remove C++ style comments from crypto/bn/bn_local.h. [Neil Costigan ] *) The function OBJ_txt2nid was broken. It was supposed to return a nid based on a text string, looking up short and long names and finally "dot" format. The "dot" format stuff didn't work. Added new function OBJ_txt2obj to do the same but return an ASN1_OBJECT and rewrote OBJ_txt2nid to use it. OBJ_txt2obj can also return objects even if the OID is not part of the table. [Steve Henson] *) Add prototypes to X509 lookup/verify methods, fixing a bug in X509_LOOKUP_by_alias(). [Ben Laurie] *) Sort openssl functions by name. [Ben Laurie] *) Get the gendsa program working (hopefully) and add it to app list. Remove encryption from sample DSA keys (in case anyone is interested the password was "1234"). [Steve Henson] *) Make _all_ *_free functions accept a NULL pointer. [Frans Heymans ] *) If a DH key is generated in s3_srvr.c, don't blow it by trying to use NULL pointers. [Anonymous ] *) s_server should send the CAfile as acceptable CAs, not its own cert. [Bodo Moeller <3moeller@informatik.uni-hamburg.de>] *) Don't blow it for numeric -newkey arguments to apps/req. [Bodo Moeller <3moeller@informatik.uni-hamburg.de>] *) Temp key "for export" tests were wrong in s3_srvr.c. [Anonymous ] *) Add prototype for temp key callback functions SSL_CTX_set_tmp_{rsa,dh}_callback(). [Ben Laurie] *) Make DH_free() tolerate being passed a NULL pointer (like RSA_free() and DSA_free()). Make X509_PUBKEY_set() check for errors in d2i_PublicKey(). [Steve Henson] *) X509_name_add_entry() freed the wrong thing after an error. [Arne Ansper ] *) rsa_eay.c would attempt to free a NULL context. [Arne Ansper ] *) BIO_s_socket() had a broken should_retry() on Windoze. [Arne Ansper ] *) BIO_f_buffer() didn't pass on BIO_CTRL_FLUSH. [Arne Ansper ] *) Make sure the already existing X509_STORE->depth variable is initialized in X509_STORE_new(), but document the fact that this variable is still unused in the certificate verification process. [Ralf S. Engelschall] *) Fix the various library and apps files to free up pkeys obtained from X509_PUBKEY_get() et al. Also allow x509.c to handle netscape extensions. [Steve Henson] *) Fix reference counting in X509_PUBKEY_get(). This makes demos/maurice/example2.c work, amongst others, probably. [Steve Henson and Ben Laurie] *) First cut of a cleanup for apps/. First the `ssleay' program is now named `openssl' and second, the shortcut symlinks for the `openssl ' are no longer created. This way we have a single and consistent command line interface `openssl ', similar to `cvs '. [Ralf S. Engelschall, Paul Sutton and Ben Laurie] *) ca.c: move test for DSA keys inside #ifndef NO_DSA. Make pubkey BIT STRING wrapper always have zero unused bits. [Steve Henson] *) Add CA.pl, perl version of CA.sh, add extended key usage OID. [Steve Henson] *) Make the top-level INSTALL documentation easier to understand. [Paul Sutton] *) Makefiles updated to exit if an error occurs in a sub-directory make (including if user presses ^C) [Paul Sutton] *) Make Montgomery context stuff explicit in RSA data structure. [Ben Laurie] *) Fix build order of pem and err to allow for generated pem.h. [Ben Laurie] *) Fix renumbering bug in X509_NAME_delete_entry(). [Ben Laurie] *) Enhanced the err-ins.pl script so it makes the error library number global and can add a library name. This is needed for external ASN1 and other error libraries. [Steve Henson] *) Fixed sk_insert which never worked properly. [Steve Henson] *) Fix ASN1 macros so they can handle indefinite length construted EXPLICIT tags. Some non standard certificates use these: they can now be read in. [Steve Henson] *) Merged the various old/obsolete SSLeay documentation files (doc/xxx.doc) into a single doc/ssleay.txt bundle. This way the information is still preserved but no longer messes up this directory. Now it's new room for the new set of documenation files. [Ralf S. Engelschall] *) SETs were incorrectly DER encoded. This was a major pain, because they shared code with SEQUENCEs, which aren't coded the same. This means that almost everything to do with SETs or SEQUENCEs has either changed name or number of arguments. [Ben Laurie, based on a partial fix by GP Jayan ] *) Fix test data to work with the above. [Ben Laurie] *) Fix the RSA header declarations that hid a bug I fixed in 0.9.0b but was already fixed by Eric for 0.9.1 it seems. [Ben Laurie - pointed out by Ulf Möller ] *) Autodetect FreeBSD3. [Ben Laurie] *) Fix various bugs in Configure. This affects the following platforms: nextstep ncr-scde unixware-2.0 unixware-2.0-pentium sco5-cc. [Ben Laurie] *) Eliminate generated files from CVS. Reorder tests to regenerate files before they are needed. [Ben Laurie] *) Generate Makefile.ssl from Makefile.org (to keep CVS happy). [Ben Laurie] Changes between 0.9.1b and 0.9.1c [23-Dec-1998] *) Added OPENSSL_VERSION_NUMBER to crypto/crypto.h and changed SSLeay to OpenSSL in version strings. [Ralf S. Engelschall] *) Some fixups to the top-level documents. [Paul Sutton] *) Fixed the nasty bug where rsaref.h was not found under compile-time because the symlink to include/ was missing. [Ralf S. Engelschall] *) Incorporated the popular no-RSA/DSA-only patches which allow to compile a RSA-free SSLeay. [Andrew Cooke / Interrader Ldt., Ralf S. Engelschall] *) Fixed nasty rehash problem under `make -f Makefile.ssl links' when "ssleay" is still not found. [Ralf S. Engelschall] *) Added more platforms to Configure: Cray T3E, HPUX 11, [Ralf S. Engelschall, Beckmann ] *) Updated the README file. [Ralf S. Engelschall] *) Added various .cvsignore files in the CVS repository subdirs to make a "cvs update" really silent. [Ralf S. Engelschall] *) Recompiled the error-definition header files and added missing symbols to the Win32 linker tables. [Ralf S. Engelschall] *) Cleaned up the top-level documents; o new files: CHANGES and LICENSE o merged VERSION, HISTORY* and README* files a CHANGES.SSLeay o merged COPYRIGHT into LICENSE o removed obsolete TODO file o renamed MICROSOFT to INSTALL.W32 [Ralf S. Engelschall] *) Removed dummy files from the 0.9.1b source tree: crypto/asn1/x crypto/bio/cd crypto/bio/fg crypto/bio/grep crypto/bio/vi crypto/bn/asm/......add.c crypto/bn/asm/a.out crypto/dsa/f crypto/md5/f crypto/pem/gmon.out crypto/perlasm/f crypto/pkcs7/build crypto/rsa/f crypto/sha/asm/f crypto/threads/f ms/zzz ssl/f ssl/f.mak test/f util/f.mak util/pl/f util/pl/f.mak crypto/bf/bf_locl.old apps/f [Ralf S. Engelschall] *) Added various platform portability fixes. [Mark J. Cox] *) The Genesis of the OpenSSL rpject: We start with the latest (unreleased) SSLeay version 0.9.1b which Eric A. Young and Tim J. Hudson created while they were working for C2Net until summer 1998. [The OpenSSL Project] Changes between 0.9.0b and 0.9.1b [not released] *) Updated a few CA certificates under certs/ [Eric A. Young] *) Changed some BIGNUM api stuff. [Eric A. Young] *) Various platform ports: OpenBSD, Ultrix, IRIX 64bit, NetBSD, DGUX x86, Linux Alpha, etc. [Eric A. Young] *) New COMP library [crypto/comp/] for SSL Record Layer Compression: RLE (dummy implemented) and ZLIB (really implemented when ZLIB is available). [Eric A. Young] *) Add -strparse option to asn1pars program which parses nested binary structures [Dr Stephen Henson ] *) Added "oid_file" to ssleay.cnf for "ca" and "req" programs. [Eric A. Young] *) DSA fix for "ca" program. [Eric A. Young] *) Added "-genkey" option to "dsaparam" program. [Eric A. Young] *) Added RIPE MD160 (rmd160) message digest. [Eric A. Young] *) Added -a (all) option to "ssleay version" command. [Eric A. Young] *) Added PLATFORM define which is the id given to Configure. [Eric A. Young] *) Added MemCheck_XXXX functions to crypto/mem.c for memory checking. [Eric A. Young] *) Extended the ASN.1 parser routines. [Eric A. Young] *) Extended BIO routines to support REUSEADDR, seek, tell, etc. [Eric A. Young] *) Added a BN_CTX to the BN library. [Eric A. Young] *) Fixed the weak key values in DES library [Eric A. Young] *) Changed API in EVP library for cipher aliases. [Eric A. Young] *) Added support for RC2/64bit cipher. [Eric A. Young] *) Converted the lhash library to the crypto/mem.c functions. [Eric A. Young] *) Added more recognized ASN.1 object ids. [Eric A. Young] *) Added more RSA padding checks for SSL/TLS. [Eric A. Young] *) Added BIO proxy/filter functionality. [Eric A. Young] *) Added extra_certs to SSL_CTX which can be used send extra CA certificates to the client in the CA cert chain sending process. It can be configured with SSL_CTX_add_extra_chain_cert(). [Eric A. Young] *) Now Fortezza is denied in the authentication phase because this is key exchange mechanism is not supported by SSLeay at all. [Eric A. Young] *) Additional PKCS1 checks. [Eric A. Young] *) Support the string "TLSv1" for all TLS v1 ciphers. [Eric A. Young] *) Added function SSL_get_ex_data_X509_STORE_CTX_idx() which gives the ex_data index of the SSL context in the X509_STORE_CTX ex_data. [Eric A. Young] *) Fixed a few memory leaks. [Eric A. Young] *) Fixed various code and comment typos. [Eric A. Young] *) A minor bug in ssl/s3_clnt.c where there would always be 4 0 bytes sent in the client random. [Edward Bishop ] Index: vendor-crypto/openssl/dist/Configure =================================================================== --- vendor-crypto/openssl/dist/Configure (revision 318896) +++ vendor-crypto/openssl/dist/Configure (revision 318897) @@ -1,2311 +1,2312 @@ : eval 'exec perl -S $0 ${1+"$@"}' if $running_under_some_shell; ## ## Configure -- OpenSSL source tree configuration script ## require 5.000; use strict; use File::Compare; # see INSTALL for instructions. my $usage="Usage: Configure [no- ...] [enable- ...] [experimental- ...] [-Dxxx] [-lxxx] [-Lxxx] [-fxxx] [-Kxxx] [no-hw-xxx|no-hw] [[no-]threads] [[no-]shared] [[no-]zlib|zlib-dynamic] [no-asm] [no-dso] [no-krb5] [sctp] [386] [--prefix=DIR] [--openssldir=OPENSSLDIR] [--with-xxx[=vvv]] [--test-sanity] os/compiler[:flags]\n"; # Options: # # --openssldir install OpenSSL in OPENSSLDIR (Default: DIR/ssl if the # --prefix option is given; /usr/local/ssl otherwise) # --prefix prefix for the OpenSSL include, lib and bin directories # (Default: the OPENSSLDIR directory) # # --install_prefix Additional prefix for package builders (empty by # default). This needn't be set in advance, you can # just as well use "make INSTALL_PREFIX=/whatever install". # # --with-krb5-dir Declare where Kerberos 5 lives. The libraries are expected # to live in the subdirectory lib/ and the header files in # include/. A value is required. # --with-krb5-lib Declare where the Kerberos 5 libraries live. A value is # required. # (Default: KRB5_DIR/lib) # --with-krb5-include Declare where the Kerberos 5 header files live. A # value is required. # (Default: KRB5_DIR/include) # --with-krb5-flavor Declare what flavor of Kerberos 5 is used. Currently # supported values are "MIT" and "Heimdal". A value is required. # # --test-sanity Make a number of sanity checks on the data in this file. # This is a debugging tool for OpenSSL developers. # # --cross-compile-prefix Add specified prefix to binutils components. # # no-hw-xxx do not compile support for specific crypto hardware. # Generic OpenSSL-style methods relating to this support # are always compiled but return NULL if the hardware # support isn't compiled. # no-hw do not compile support for any crypto hardware. # [no-]threads [don't] try to create a library that is suitable for # multithreaded applications (default is "threads" if we # know how to do it) # [no-]shared [don't] try to create shared libraries when supported. # no-asm do not use assembler # no-dso do not compile in any native shared-library methods. This # will ensure that all methods just return NULL. # no-krb5 do not compile in any KRB5 library or code. # [no-]zlib [don't] compile support for zlib compression. # zlib-dynamic Like "zlib", but the zlib library is expected to be a shared # library and will be loaded in run-time by the OpenSSL library. # sctp include SCTP support # enable-weak-ssl-ciphers # Enable EXPORT and LOW SSLv3 ciphers that are disabled by # default. Note, weak SSLv2 ciphers are unconditionally # disabled. # 386 generate 80386 code in assembly modules # no-sse2 disables IA-32 SSE2 code in assembly modules, the above # mentioned '386' option implies this one # no- build without specified algorithm (rsa, idea, rc5, ...) # - + compiler options are passed through # # DEBUG_SAFESTACK use type-safe stacks to enforce type-safety on stack items # provided to stack calls. Generates unique stack functions for # each possible stack type. # DES_PTR use pointer lookup vs arrays in the DES in crypto/des/des_locl.h # DES_RISC1 use different DES_ENCRYPT macro that helps reduce register # dependancies but needs to more registers, good for RISC CPU's # DES_RISC2 A different RISC variant. # DES_UNROLL unroll the inner DES loop, sometimes helps, somtimes hinders. # DES_INT use 'int' instead of 'long' for DES_LONG in crypto/des/des.h # This is used on the DEC Alpha where long is 8 bytes # and int is 4 # BN_LLONG use the type 'long long' in crypto/bn/bn.h # MD2_CHAR use 'char' instead of 'int' for MD2_INT in crypto/md2/md2.h # MD2_LONG use 'long' instead of 'int' for MD2_INT in crypto/md2/md2.h # IDEA_SHORT use 'short' instead of 'int' for IDEA_INT in crypto/idea/idea.h # IDEA_LONG use 'long' instead of 'int' for IDEA_INT in crypto/idea/idea.h # RC2_SHORT use 'short' instead of 'int' for RC2_INT in crypto/rc2/rc2.h # RC2_LONG use 'long' instead of 'int' for RC2_INT in crypto/rc2/rc2.h # RC4_CHAR use 'char' instead of 'int' for RC4_INT in crypto/rc4/rc4.h # RC4_LONG use 'long' instead of 'int' for RC4_INT in crypto/rc4/rc4.h # RC4_INDEX define RC4_INDEX in crypto/rc4/rc4_locl.h. This turns on # array lookups instead of pointer use. # RC4_CHUNK enables code that handles data aligned at long (natural CPU # word) boundary. # RC4_CHUNK_LL enables code that handles data aligned at long long boundary # (intended for 64-bit CPUs running 32-bit OS). # BF_PTR use 'pointer arithmatic' for Blowfish (unsafe on Alpha). # BF_PTR2 intel specific version (generic version is more efficient). # # Following are set automatically by this script # # MD5_ASM use some extra md5 assember, # SHA1_ASM use some extra sha1 assember, must define L_ENDIAN for x86 # RMD160_ASM use some extra ripemd160 assember, # SHA256_ASM sha256_block is implemented in assembler # SHA512_ASM sha512_block is implemented in assembler # AES_ASM ASE_[en|de]crypt is implemented in assembler # Minimum warning options... any contributions to OpenSSL should at least get # past these. -my $gcc_devteam_warn = "-Wall -pedantic -DPEDANTIC -Wno-long-long -Wsign-compare -Wmissing-prototypes -Wshadow -Wformat -Werror -DCRYPTO_MDEBUG_ALL -DCRYPTO_MDEBUG_ABORT -DREF_CHECK -DOPENSSL_NO_DEPRECATED"; +my $gcc_devteam_warn = "-Wall -pedantic -DPEDANTIC -Wno-long-long -Wsign-compare -Wmissing-prototypes -Wshadow -Wformat -Wundef -Werror -DCRYPTO_MDEBUG_ALL -DCRYPTO_MDEBUG_ABORT -DREF_CHECK -DOPENSSL_NO_DEPRECATED"; # TODO(openssl-team): fix problems and investigate if (at least) the following # warnings can also be enabled: # -Wconditional-uninitialized, -Wswitch-enum, -Wunused-macros, # -Wmissing-field-initializers, -Wmissing-variable-declarations, # -Wincompatible-pointer-types-discards-qualifiers, -Wcast-align, # -Wunreachable-code -Wunused-parameter -Wlanguage-extension-token # -Wextended-offsetof my $clang_disabled_warnings = "-Wno-unused-parameter -Wno-missing-field-initializers -Wno-language-extension-token -Wno-extended-offsetof"; # These are used in addition to $gcc_devteam_warn when the compiler is clang. # TODO(openssl-team): fix problems and investigate if (at least) the # following warnings can also be enabled: -Wconditional-uninitialized, # -Wswitch-enum, -Wunused-macros, -Wmissing-field-initializers, # -Wmissing-variable-declarations, # -Wincompatible-pointer-types-discards-qualifiers, -Wcast-align, # -Wunreachable-code -Wunused-parameter -Wlanguage-extension-token # -Wextended-offsetof my $clang_devteam_warn = "-Wno-unused-parameter -Wno-missing-field-initializers -Wno-language-extension-token -Wno-extended-offsetof -Qunused-arguments"; # Warn that "make depend" should be run? my $warn_make_depend = 0; my $strict_warnings = 0; my $x86_gcc_des="DES_PTR DES_RISC1 DES_UNROLL"; # MD2_CHAR slags pentium pros my $x86_gcc_opts="RC4_INDEX MD2_INT"; # MODIFY THESE PARAMETERS IF YOU ARE GOING TO USE THE 'util/speed.sh SCRIPT # Don't worry about these normally my $tcc="cc"; my $tflags="-fast -Xa"; my $tbn_mul=""; my $tlib="-lnsl -lsocket"; #$bits1="SIXTEEN_BIT "; #$bits2="THIRTY_TWO_BIT "; my $bits1="THIRTY_TWO_BIT "; my $bits2="SIXTY_FOUR_BIT "; my $x86_asm="x86cpuid.o:bn-586.o co-586.o x86-mont.o x86-gf2m.o::des-586.o crypt586.o:aes-586.o vpaes-x86.o aesni-x86.o:bf-586.o:md5-586.o:sha1-586.o sha256-586.o sha512-586.o:cast-586.o:rc4-586.o:rmd-586.o:rc5-586.o:wp_block.o wp-mmx.o:cmll-x86.o:ghash-x86.o:"; my $x86_elf_asm="$x86_asm:elf"; my $x86_64_asm="x86_64cpuid.o:x86_64-gcc.o x86_64-mont.o x86_64-mont5.o x86_64-gf2m.o rsaz_exp.o rsaz-x86_64.o rsaz-avx2.o:ecp_nistz256.o ecp_nistz256-x86_64.o::aes-x86_64.o vpaes-x86_64.o bsaes-x86_64.o aesni-x86_64.o aesni-sha1-x86_64.o aesni-sha256-x86_64.o aesni-mb-x86_64.o::md5-x86_64.o:sha1-x86_64.o sha256-x86_64.o sha512-x86_64.o sha1-mb-x86_64.o sha256-mb-x86_64.o::rc4-x86_64.o rc4-md5-x86_64.o:::wp-x86_64.o:cmll-x86_64.o cmll_misc.o:ghash-x86_64.o aesni-gcm-x86_64.o:"; my $ia64_asm="ia64cpuid.o:bn-ia64.o ia64-mont.o:::aes_core.o aes_cbc.o aes-ia64.o::md5-ia64.o:sha1-ia64.o sha256-ia64.o sha512-ia64.o::rc4-ia64.o rc4_skey.o:::::ghash-ia64.o::void"; my $sparcv9_asm="sparcv9cap.o sparccpuid.o:bn-sparcv9.o sparcv9-mont.o sparcv9a-mont.o vis3-mont.o sparct4-mont.o sparcv9-gf2m.o::des_enc-sparc.o fcrypt_b.o dest4-sparcv9.o:aes_core.o aes_cbc.o aes-sparcv9.o aest4-sparcv9.o::md5-sparcv9.o:sha1-sparcv9.o sha256-sparcv9.o sha512-sparcv9.o::::::camellia.o cmll_misc.o cmll_cbc.o cmllt4-sparcv9.o:ghash-sparcv9.o::void"; my $sparcv8_asm=":sparcv8.o::des_enc-sparc.o fcrypt_b.o:::::::::::::void"; my $alpha_asm="alphacpuid.o:bn_asm.o alpha-mont.o::::::sha1-alpha.o:::::::ghash-alpha.o::void"; my $mips64_asm=":bn-mips.o mips-mont.o:::aes_cbc.o aes-mips.o:::sha1-mips.o sha256-mips.o sha512-mips.o::::::::"; my $mips32_asm=$mips64_asm; $mips32_asm =~ s/\s*sha512\-mips\.o//; my $s390x_asm="s390xcap.o s390xcpuid.o:bn-s390x.o s390x-mont.o s390x-gf2m.o:::aes-s390x.o aes-ctr.o aes-xts.o:::sha1-s390x.o sha256-s390x.o sha512-s390x.o::rc4-s390x.o:::::ghash-s390x.o:"; my $armv4_asm="armcap.o armv4cpuid.o:bn_asm.o armv4-mont.o armv4-gf2m.o:::aes_cbc.o aes-armv4.o bsaes-armv7.o aesv8-armx.o:::sha1-armv4-large.o sha256-armv4.o sha512-armv4.o:::::::ghash-armv4.o ghashv8-armx.o::void"; my $aarch64_asm="armcap.o arm64cpuid.o mem_clr.o::::aes_core.o aes_cbc.o aesv8-armx.o:::sha1-armv8.o sha256-armv8.o sha512-armv8.o:::::::ghashv8-armx.o:"; my $parisc11_asm="pariscid.o:bn_asm.o parisc-mont.o:::aes_core.o aes_cbc.o aes-parisc.o:::sha1-parisc.o sha256-parisc.o sha512-parisc.o::rc4-parisc.o:::::ghash-parisc.o::32"; my $parisc20_asm="pariscid.o:pa-risc2W.o parisc-mont.o:::aes_core.o aes_cbc.o aes-parisc.o:::sha1-parisc.o sha256-parisc.o sha512-parisc.o::rc4-parisc.o:::::ghash-parisc.o::64"; my $ppc64_asm="ppccpuid.o ppccap.o:bn-ppc.o ppc-mont.o ppc64-mont.o:::aes_core.o aes_cbc.o aes-ppc.o vpaes-ppc.o aesp8-ppc.o:::sha1-ppc.o sha256-ppc.o sha512-ppc.o sha256p8-ppc.o sha512p8-ppc.o:::::::ghashp8-ppc.o:"; my $ppc32_asm=$ppc64_asm; my $no_asm="::::::::::::::::void"; # As for $BSDthreads. Idea is to maintain "collective" set of flags, # which would cover all BSD flavors. -pthread applies to them all, # but is treated differently. OpenBSD expands is as -D_POSIX_THREAD # -lc_r, which is sufficient. FreeBSD 4.x expands it as -lc_r, # which has to be accompanied by explicit -D_THREAD_SAFE and # sometimes -D_REENTRANT. FreeBSD 5.x expands it as -lc_r, which # seems to be sufficient? my $BSDthreads="-pthread -D_THREAD_SAFE -D_REENTRANT"; #config-string $cc : $cflags : $unistd : $thread_cflag : $sys_id : $lflags : $bn_ops : $cpuid_obj : $bn_obj : $ec_obj : $des_obj : $aes_obj : $bf_obj : $md5_obj : $sha1_obj : $cast_obj : $rc4_obj : $rmd160_obj : $rc5_obj : $wp_obj : $cmll_obj : $modes_obj : $engines_obj : $dso_scheme : $shared_target : $shared_cflag : $shared_ldflag : $shared_extension : $ranlib : $arflags : $multilib my %table=( # File 'TABLE' (created by 'make TABLE') contains the data from this list, # formatted for better readability. #"b", "${tcc}:${tflags}::${tlib}:${bits1}:${tbn_mul}::", #"bl-4c-2c", "${tcc}:${tflags}::${tlib}:${bits1}BN_LLONG RC4_CHAR MD2_CHAR:${tbn_mul}::", #"bl-4c-ri", "${tcc}:${tflags}::${tlib}:${bits1}BN_LLONG RC4_CHAR RC4_INDEX:${tbn_mul}::", #"b2-is-ri-dp", "${tcc}:${tflags}::${tlib}:${bits2}IDEA_SHORT RC4_INDEX DES_PTR:${tbn_mul}::", # Our development configs "purify", "purify gcc:-g -DPURIFY -Wall::(unknown)::-lsocket -lnsl::::", "debug", "gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG -DOPENSSL_NO_ASM -ggdb -g2 -Wformat -Wshadow -Wmissing-prototypes -Wmissing-declarations -Werror::(unknown)::-lefence::::", "debug-ben", "gcc:$gcc_devteam_warn -DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG -DDEBUG_SAFESTACK -O2 -pipe::(unknown):::::", "debug-ben-openbsd","gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG -DPEDANTIC -DDEBUG_SAFESTACK -DOPENSSL_OPENBSD_DEV_CRYPTO -DOPENSSL_NO_ASM -O2 -pedantic -Wall -Wshadow -Werror -pipe::(unknown)::::", "debug-ben-openbsd-debug","gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG -DPEDANTIC -DDEBUG_SAFESTACK -DOPENSSL_OPENBSD_DEV_CRYPTO -DOPENSSL_NO_ASM -g3 -O2 -pedantic -Wall -Wshadow -Werror -pipe::(unknown)::::", "debug-ben-debug", "gcc44:$gcc_devteam_warn -DBN_DEBUG -DCONF_DEBUG -DDEBUG_SAFESTACK -DDEBUG_UNUSED -g3 -O2 -pipe::(unknown)::::::", "debug-ben-debug-64", "gcc:$gcc_devteam_warn -Wno-error=overlength-strings -DBN_DEBUG -DCONF_DEBUG -DDEBUG_SAFESTACK -DDEBUG_UNUSED -g3 -O3 -pipe::${BSDthreads}:::SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:bsd-gcc-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "debug-ben-macos", "cc:$gcc_devteam_warn -arch i386 -DBN_DEBUG -DCONF_DEBUG -DDEBUG_SAFESTACK -DDEBUG_UNUSED -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -O3 -DL_ENDIAN -g3 -pipe::(unknown)::-Wl,-search_paths_first::::", "debug-ben-macos-gcc46", "gcc-mp-4.6:$gcc_devteam_warn -Wconversion -DBN_DEBUG -DCONF_DEBUG -DDEBUG_SAFESTACK -DDEBUG_UNUSED -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -O3 -DL_ENDIAN -g3 -pipe::(unknown)::::::", "debug-ben-darwin64","cc:$gcc_devteam_warn -g -Wno-language-extension-token -Wno-extended-offsetof -arch x86_64 -O3 -DL_ENDIAN -Wall::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL:".eval{my $asm=$x86_64_asm;$asm=~s/rc4\-[^:]+//;$asm}.":macosx:dlfcn:darwin-shared:-fPIC -fno-common:-arch x86_64 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib", "debug-ben-debug-64-clang", "clang:$gcc_devteam_warn -Wno-error=overlength-strings -Wno-error=extended-offsetof -Qunused-arguments -DBN_DEBUG -DCONF_DEBUG -DDEBUG_SAFESTACK -DDEBUG_UNUSED -g3 -O3 -pipe::${BSDthreads}:::SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:bsd-gcc-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "debug-ben-no-opt", "gcc: -Wall -Wmissing-prototypes -Wstrict-prototypes -Wmissing-declarations -DDEBUG_SAFESTACK -DCRYPTO_MDEBUG -Werror -DL_ENDIAN -DTERMIOS -Wall -g3::(unknown)::::::", "debug-ben-strict", "gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG -DCONST_STRICT -O2 -Wall -Wshadow -Werror -Wpointer-arith -Wcast-qual -Wwrite-strings -pipe::(unknown)::::::", "debug-rse","cc:-DTERMIOS -DL_ENDIAN -pipe -O -g -ggdb3 -Wall::(unknown):::BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}", "debug-bodo", "gcc:$gcc_devteam_warn -Wno-error=overlength-strings -DBN_DEBUG -DBN_DEBUG_RAND -DCONF_DEBUG -DBIO_PAIR_DEBUG -m64 -DL_ENDIAN -DTERMIO -g -DMD32_REG_T=int::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64", "debug-steve64", "gcc:$gcc_devteam_warn -m64 -DL_ENDIAN -DTERMIO -DCONF_DEBUG -DDEBUG_SAFESTACK -Wno-overlength-strings -g::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "debug-steve32", "gcc:$gcc_devteam_warn -m32 -DL_ENDIAN -DCONF_DEBUG -DDEBUG_SAFESTACK -Wno-overlength-strings -g -pipe::-D_REENTRANT::-rdynamic -ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:linux-shared:-fPIC:-m32:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "debug-steve-opt", "gcc:$gcc_devteam_warn -m64 -O3 -DL_ENDIAN -DTERMIO -DCONF_DEBUG -DDEBUG_SAFESTACK -g::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "debug-levitte-linux-elf","gcc:-DLEVITTE_DEBUG -DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DCRYPTO_MDEBUG -DL_ENDIAN -ggdb -g3 -Wall::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "debug-levitte-linux-noasm","gcc:-DLEVITTE_DEBUG -DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DCRYPTO_MDEBUG -DOPENSSL_NO_ASM -DL_ENDIAN -ggdb -g3 -Wall::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${no_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "debug-levitte-linux-elf-extreme","gcc:-DLEVITTE_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_DEBUG -DBN_DEBUG_RAND -DCRYPTO_MDEBUG -DENGINE_CONF_DEBUG -DL_ENDIAN -DPEDANTIC -ggdb -g3 -pedantic -ansi -Wall -W -Wundef -Wshadow -Wcast-align -Wstrict-prototypes -Wmissing-prototypes -Wno-long-long -Wundef -Wconversion -pipe::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "debug-levitte-linux-noasm-extreme","gcc:-DLEVITTE_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_DEBUG -DBN_DEBUG_RAND -DCRYPTO_MDEBUG -DENGINE_CONF_DEBUG -DOPENSSL_NO_ASM -DL_ENDIAN -DPEDANTIC -ggdb -g3 -pedantic -ansi -Wall -W -Wundef -Wshadow -Wcast-align -Wstrict-prototypes -Wmissing-prototypes -Wno-long-long -Wundef -Wconversion -pipe::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${no_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "debug-geoff32","gcc:-DBN_DEBUG -DBN_DEBUG_RAND -DBN_STRICT -DPURIFY -DOPENSSL_NO_DEPRECATED -DOPENSSL_NO_ASM -DOPENSSL_NO_INLINE_ASM -DL_ENDIAN -DTERMIO -DPEDANTIC -O1 -ggdb2 -Wall -Werror -Wundef -pedantic -Wshadow -Wpointer-arith -Wbad-function-cast -Wcast-align -Wsign-compare -Wmissing-prototypes -Wmissing-declarations -Wno-long-long::-D_REENTRANT::-ldl:BN_LLONG:${no_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "debug-geoff64","gcc:-DBN_DEBUG -DBN_DEBUG_RAND -DBN_STRICT -DPURIFY -DOPENSSL_NO_DEPRECATED -DOPENSSL_NO_ASM -DOPENSSL_NO_INLINE_ASM -DL_ENDIAN -DTERMIO -DPEDANTIC -O1 -ggdb2 -Wall -Werror -Wundef -pedantic -Wshadow -Wpointer-arith -Wbad-function-cast -Wcast-align -Wsign-compare -Wmissing-prototypes -Wmissing-declarations -Wno-long-long::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${no_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "debug-linux-pentium","gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG -DL_ENDIAN -g -mcpu=pentium -Wall::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn", "debug-linux-ppro","gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG -DL_ENDIAN -g -mcpu=pentiumpro -Wall::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn", "debug-linux-elf","gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG -DL_ENDIAN -g -march=i486 -Wall::-D_REENTRANT::-lefence -ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "debug-linux-elf-noefence","gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG -DL_ENDIAN -g -march=i486 -Wall::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "debug-linux-ia32-aes", "gcc:-DAES_EXPERIMENTAL -DL_ENDIAN -O3 -fomit-frame-pointer -Wall::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:x86cpuid.o:bn-586.o co-586.o x86-mont.o::des-586.o crypt586.o:aes_x86core.o aes_cbc.o aesni-x86.o:bf-586.o:md5-586.o:sha1-586.o sha256-586.o sha512-586.o:cast-586.o:rc4-586.o:rmd-586.o:rc5-586.o:wp_block.o wp-mmx.o::ghash-x86.o::elf:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "debug-linux-generic32","gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DCRYPTO_MDEBUG -g -Wall::-D_REENTRANT::-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${no_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "debug-linux-generic64","gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DCRYPTO_MDEBUG -DTERMIO -g -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${no_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "debug-linux-x86_64","gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DCRYPTO_MDEBUG -m64 -DL_ENDIAN -g -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64", "dist", "cc:-O::(unknown)::::::", # Basic configs that should work on any (32 and less bit) box "gcc", "gcc:-O3::(unknown):::BN_LLONG:::", "cc", "cc:-O::(unknown)::::::", ####VOS Configurations "vos-gcc","gcc:-O3 -Wall -DOPENSSL_SYSNAME_VOS -D_POSIX_C_SOURCE=200112L -D_BSD -D_VOS_EXTENDED_NAMES -DB_ENDIAN::(unknown):VOS:-Wl,-map:BN_LLONG:${no_asm}:::::.so:", "debug-vos-gcc","gcc:-O0 -g -Wall -DOPENSSL_SYSNAME_VOS -D_POSIX_C_SOURCE=200112L -D_BSD -D_VOS_EXTENDED_NAMES -DB_ENDIAN -DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DCRYPTO_MDEBUG::(unknown):VOS:-Wl,-map:BN_LLONG:${no_asm}:::::.so:", #### Solaris x86 with GNU C setups # -DOPENSSL_NO_INLINE_ASM switches off inline assembler. We have to do it # here because whenever GNU C instantiates an assembler template it # surrounds it with #APP #NO_APP comment pair which (at least Solaris # 7_x86) /usr/ccs/bin/as fails to assemble with "Illegal mnemonic" # error message. "solaris-x86-gcc","gcc:-O3 -fomit-frame-pointer -march=pentium -Wall -DL_ENDIAN -DOPENSSL_NO_INLINE_ASM::-D_REENTRANT::-lsocket -lnsl -ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:solaris-shared:-fPIC:-shared:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", # -shared -static-libgcc might appear controversial, but modules taken # from static libgcc do not have relocations and linking them into our # shared objects doesn't have any negative side-effects. On the contrary, # doing so makes it possible to use gcc shared build with Sun C. Given # that gcc generates faster code [thanks to inline assembler], I would # actually recommend to consider using gcc shared build even with vendor # compiler:-) # "solaris64-x86_64-gcc","gcc:-m64 -O3 -Wall -DL_ENDIAN::-D_REENTRANT::-lsocket -lnsl -ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:solaris-shared:-fPIC:-m64 -shared -static-libgcc:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/64", #### Solaris x86 with Sun C setups "solaris-x86-cc","cc:-fast -xarch=generic -O -Xa::-D_REENTRANT::-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_PTR DES_UNROLL BF_PTR:${no_asm}:dlfcn:solaris-shared:-KPIC:-G -dy -z text:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "solaris64-x86_64-cc","cc:-fast -xarch=amd64 -xstrconst -Xa -DL_ENDIAN::-D_REENTRANT::-lsocket -lnsl -ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:solaris-shared:-KPIC:-xarch=amd64 -G -dy -z text:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/64", #### SPARC Solaris with GNU C setups "solaris-sparcv7-gcc","gcc:-O3 -fomit-frame-pointer -Wall -DB_ENDIAN -DBN_DIV2W::-D_REENTRANT::-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${no_asm}:dlfcn:solaris-shared:-fPIC:-shared:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "solaris-sparcv8-gcc","gcc:-mcpu=v8 -O3 -fomit-frame-pointer -Wall -DB_ENDIAN -DBN_DIV2W::-D_REENTRANT::-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${sparcv8_asm}:dlfcn:solaris-shared:-fPIC:-shared:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", # -m32 should be safe to add as long as driver recognizes -mcpu=ultrasparc "solaris-sparcv9-gcc","gcc:-m32 -mcpu=ultrasparc -O3 -fomit-frame-pointer -Wall -DB_ENDIAN -DBN_DIV2W::-D_REENTRANT:ULTRASPARC:-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${sparcv9_asm}:dlfcn:solaris-shared:-fPIC:-shared:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "solaris64-sparcv9-gcc","gcc:-m64 -mcpu=ultrasparc -O3 -Wall -DB_ENDIAN::-D_REENTRANT:ULTRASPARC:-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_INT DES_PTR DES_RISC1 DES_UNROLL BF_PTR:${sparcv9_asm}:dlfcn:solaris-shared:-fPIC:-m64 -shared:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/64", #### "debug-solaris-sparcv8-gcc","gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG_ALL -O -g -mcpu=v8 -Wall -DB_ENDIAN::-D_REENTRANT::-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${sparcv8_asm}:dlfcn:solaris-shared:-fPIC:-shared:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "debug-solaris-sparcv9-gcc","gcc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG_ALL -DPEDANTIC -O -g -mcpu=ultrasparc -pedantic -ansi -Wall -Wshadow -Wno-long-long -D__EXTENSIONS__ -DB_ENDIAN -DBN_DIV2W::-D_REENTRANT:ULTRASPARC:-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${sparcv9_asm}:dlfcn:solaris-shared:-fPIC:-shared:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", #### SPARC Solaris with Sun C setups # SC4.0 doesn't pass 'make test', upgrade to SC5.0 or SC4.2. # SC4.2 is ok, better than gcc even on bn as long as you tell it -xarch=v8 # SC5.0 note: Compiler common patch 107357-01 or later is required! "solaris-sparcv7-cc","cc:-xO5 -xstrconst -xdepend -Xa -DB_ENDIAN -DBN_DIV2W::-D_REENTRANT::-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_PTR DES_RISC1 DES_UNROLL BF_PTR:${no_asm}:dlfcn:solaris-shared:-KPIC:-G -dy -z text:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "solaris-sparcv8-cc","cc:-xarch=v8 -xO5 -xstrconst -xdepend -Xa -DB_ENDIAN -DBN_DIV2W::-D_REENTRANT::-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_PTR DES_RISC1 DES_UNROLL BF_PTR:${sparcv8_asm}:dlfcn:solaris-shared:-KPIC:-G -dy -z text:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "solaris-sparcv9-cc","cc:-xtarget=ultra -xarch=v8plus -xO5 -xstrconst -xdepend -Xa -DB_ENDIAN -DBN_DIV2W::-D_REENTRANT:ULTRASPARC:-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK_LL DES_PTR DES_RISC1 DES_UNROLL BF_PTR:${sparcv9_asm}:dlfcn:solaris-shared:-KPIC:-G -dy -z text:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "solaris64-sparcv9-cc","cc:-xtarget=ultra -xarch=v9 -xO5 -xstrconst -xdepend -Xa -DB_ENDIAN::-D_REENTRANT:ULTRASPARC:-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_INT DES_PTR DES_RISC1 DES_UNROLL BF_PTR:${sparcv9_asm}:dlfcn:solaris-shared:-KPIC:-xarch=v9 -G -dy -z text:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/64", #### "debug-solaris-sparcv8-cc","cc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG_ALL -xarch=v8 -g -O -xstrconst -Xa -DB_ENDIAN -DBN_DIV2W::-D_REENTRANT::-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_PTR DES_RISC1 DES_UNROLL BF_PTR:${sparcv8_asm}:dlfcn:solaris-shared:-KPIC:-G -dy -z text:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "debug-solaris-sparcv9-cc","cc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG_ALL -xtarget=ultra -xarch=v8plus -g -O -xstrconst -Xa -DB_ENDIAN -DBN_DIV2W::-D_REENTRANT:ULTRASPARC:-lsocket -lnsl -ldl:BN_LLONG RC4_CHAR RC4_CHUNK_LL DES_PTR DES_RISC1 DES_UNROLL BF_PTR:${sparcv9_asm}:dlfcn:solaris-shared:-KPIC:-G -dy -z text:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", #### SunOS configs, assuming sparc for the gcc one. #"sunos-cc", "cc:-O4 -DNOPROTO -DNOCONST::(unknown):SUNOS::DES_UNROLL:${no_asm}::", "sunos-gcc","gcc:-O3 -mcpu=v8 -Dssize_t=int::(unknown):SUNOS::BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL DES_PTR DES_RISC1:${no_asm}::", #### IRIX 5.x configs # -mips2 flag is added by ./config when appropriate. "irix-gcc","gcc:-O3 -DB_ENDIAN::(unknown):::BN_LLONG MD2_CHAR RC4_INDEX RC4_CHAR RC4_CHUNK DES_UNROLL DES_RISC2 DES_PTR BF_PTR:${mips32_asm}:o32:dlfcn:irix-shared:::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "irix-cc", "cc:-O2 -use_readonly_const -DB_ENDIAN::(unknown):::BN_LLONG RC4_CHAR RC4_CHUNK DES_PTR DES_RISC2 DES_UNROLL BF_PTR:${mips32_asm}:o32:dlfcn:irix-shared:::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", #### IRIX 6.x configs # Only N32 and N64 ABIs are supported. If you need O32 ABI build, invoke # './Configure irix-cc -o32' manually. "irix-mips3-gcc","gcc:-mabi=n32 -O3 -DB_ENDIAN -DBN_DIV3W::-D_SGI_MP_SOURCE:::MD2_CHAR RC4_INDEX RC4_CHAR RC4_CHUNK_LL DES_UNROLL DES_RISC2 DES_PTR BF_PTR SIXTY_FOUR_BIT:${mips64_asm}:n32:dlfcn:irix-shared::-mabi=n32:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::32", "irix-mips3-cc", "cc:-n32 -mips3 -O2 -use_readonly_const -G0 -rdata_shared -DB_ENDIAN -DBN_DIV3W::-D_SGI_MP_SOURCE:::DES_PTR RC4_CHAR RC4_CHUNK_LL DES_RISC2 DES_UNROLL BF_PTR SIXTY_FOUR_BIT:${mips64_asm}:n32:dlfcn:irix-shared::-n32:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::32", # N64 ABI builds. "irix64-mips4-gcc","gcc:-mabi=64 -mips4 -O3 -DB_ENDIAN -DBN_DIV3W::-D_SGI_MP_SOURCE:::RC4_CHAR RC4_CHUNK DES_RISC2 DES_UNROLL SIXTY_FOUR_BIT_LONG:${mips64_asm}:64:dlfcn:irix-shared::-mabi=64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64", "irix64-mips4-cc", "cc:-64 -mips4 -O2 -use_readonly_const -G0 -rdata_shared -DB_ENDIAN -DBN_DIV3W::-D_SGI_MP_SOURCE:::RC4_CHAR RC4_CHUNK DES_RISC2 DES_UNROLL SIXTY_FOUR_BIT_LONG:${mips64_asm}:64:dlfcn:irix-shared::-64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64", #### Unified HP-UX ANSI C configs. # Special notes: # - Originally we were optimizing at +O4 level. It should be noted # that the only difference between +O3 and +O4 is global inter- # procedural analysis. As it has to be performed during the link # stage the compiler leaves behind certain pseudo-code in lib*.a # which might be release or even patch level specific. Generating # the machine code for and analyzing the *whole* program appears # to be *extremely* memory demanding while the performance gain is # actually questionable. The situation is intensified by the default # HP-UX data set size limit (infamous 'maxdsiz' tunable) of 64MB # which is way too low for +O4. In other words, doesn't +O3 make # more sense? # - Keep in mind that the HP compiler by default generates code # suitable for execution on the host you're currently compiling at. # If the toolkit is ment to be used on various PA-RISC processors # consider './config +DAportable'. # - +DD64 is chosen in favour of +DA2.0W because it's meant to be # compatible with *future* releases. # - If you run ./Configure hpux-parisc-[g]cc manually don't forget to # pass -D_REENTRANT on HP-UX 10 and later. # - -DMD32_XARRAY triggers workaround for compiler bug we ran into in # 32-bit message digests. (For the moment of this writing) HP C # doesn't seem to "digest" too many local variables (they make "him" # chew forever:-). For more details look-up MD32_XARRAY comment in # crypto/sha/sha_lcl.h. # # # Since there is mention of this in shlib/hpux10-cc.sh "hpux-parisc-cc-o4","cc:-Ae +O4 +ESlit -z -DB_ENDIAN -DBN_DIV2W -DMD32_XARRAY::-D_REENTRANT::-ldld:BN_LLONG DES_PTR DES_UNROLL DES_RISC1:${no_asm}:dl:hpux-shared:+Z:-b:.sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "hpux-parisc-gcc","gcc:-O3 -DB_ENDIAN -DBN_DIV2W::-D_REENTRANT::-Wl,+s -ldld:BN_LLONG DES_PTR DES_UNROLL DES_RISC1:${no_asm}:dl:hpux-shared:-fPIC:-shared:.sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "hpux-parisc1_1-gcc","gcc:-O3 -DB_ENDIAN -DBN_DIV2W::-D_REENTRANT::-Wl,+s -ldld:BN_LLONG DES_PTR DES_UNROLL DES_RISC1:${parisc11_asm}:dl:hpux-shared:-fPIC:-shared:.sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/pa1.1", "hpux-parisc2-gcc","gcc:-march=2.0 -O3 -DB_ENDIAN -D_REENTRANT::::-Wl,+s -ldld:SIXTY_FOUR_BIT RC4_CHAR RC4_CHUNK DES_PTR DES_UNROLL DES_RISC1:".eval{my $asm=$parisc20_asm;$asm=~s/2W\./2\./;$asm=~s/:64/:32/;$asm}.":dl:hpux-shared:-fPIC:-shared:.sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/pa20_32", "hpux64-parisc2-gcc","gcc:-O3 -DB_ENDIAN -D_REENTRANT::::-ldl:SIXTY_FOUR_BIT_LONG MD2_CHAR RC4_INDEX RC4_CHAR DES_UNROLL DES_RISC1 DES_INT::pa-risc2W.o:::::::::::::::void:dlfcn:hpux-shared:-fpic:-shared:.sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/pa20_64", # More attempts at unified 10.X and 11.X targets for HP C compiler. # # Chris Ruemmler # Kevin Steves "hpux-parisc-cc","cc:+O3 +Optrs_strongly_typed -Ae +ESlit -DB_ENDIAN -DBN_DIV2W -DMD32_XARRAY::-D_REENTRANT::-Wl,+s -ldld:MD2_CHAR RC4_INDEX RC4_CHAR DES_UNROLL DES_RISC1 DES_INT:${no_asm}:dl:hpux-shared:+Z:-b:.sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "hpux-parisc1_1-cc","cc:+DA1.1 +O3 +Optrs_strongly_typed -Ae +ESlit -DB_ENDIAN -DMD32_XARRAY::-D_REENTRANT::-Wl,+s -ldld:MD2_CHAR RC4_INDEX RC4_CHAR DES_UNROLL DES_RISC1 DES_INT:${parisc11_asm}:dl:hpux-shared:+Z:-b:.sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/pa1.1", "hpux-parisc2-cc","cc:+DA2.0 +DS2.0 +O3 +Optrs_strongly_typed -Ae +ESlit -DB_ENDIAN -DMD32_XARRAY -D_REENTRANT::::-Wl,+s -ldld:SIXTY_FOUR_BIT MD2_CHAR RC4_INDEX RC4_CHAR DES_UNROLL DES_RISC1 DES_INT:".eval{my $asm=$parisc20_asm;$asm=~s/2W\./2\./;$asm=~s/:64/:32/;$asm}.":dl:hpux-shared:+Z:-b:.sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/pa20_32", "hpux64-parisc2-cc","cc:+DD64 +O3 +Optrs_strongly_typed -Ae +ESlit -DB_ENDIAN -DMD32_XARRAY -D_REENTRANT::::-ldl:SIXTY_FOUR_BIT_LONG MD2_CHAR RC4_INDEX RC4_CHAR DES_UNROLL DES_RISC1 DES_INT:${parisc20_asm}:dlfcn:hpux-shared:+Z:+DD64 -b:.sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/pa20_64", # HP/UX IA-64 targets "hpux-ia64-cc","cc:-Ae +DD32 +O2 +Olit=all -z -DB_ENDIAN -D_REENTRANT::::-ldl:SIXTY_FOUR_BIT MD2_CHAR RC4_INDEX DES_UNROLL DES_RISC1 DES_INT:${ia64_asm}:dlfcn:hpux-shared:+Z:+DD32 -b:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/hpux32", # Frank Geurts has patiently assisted with # with debugging of the following config. "hpux64-ia64-cc","cc:-Ae +DD64 +O3 +Olit=all -z -DB_ENDIAN -D_REENTRANT::::-ldl:SIXTY_FOUR_BIT_LONG MD2_CHAR RC4_INDEX DES_UNROLL DES_RISC1 DES_INT:${ia64_asm}:dlfcn:hpux-shared:+Z:+DD64 -b:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/hpux64", # GCC builds... "hpux-ia64-gcc","gcc:-O3 -DB_ENDIAN -D_REENTRANT::::-ldl:SIXTY_FOUR_BIT MD2_CHAR RC4_INDEX DES_UNROLL DES_RISC1 DES_INT:${ia64_asm}:dlfcn:hpux-shared:-fpic:-shared:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/hpux32", "hpux64-ia64-gcc","gcc:-mlp64 -O3 -DB_ENDIAN -D_REENTRANT::::-ldl:SIXTY_FOUR_BIT_LONG MD2_CHAR RC4_INDEX DES_UNROLL DES_RISC1 DES_INT:${ia64_asm}:dlfcn:hpux-shared:-fpic:-mlp64 -shared:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/hpux64", # Legacy HPUX 9.X configs... "hpux-cc", "cc:-DB_ENDIAN -DBN_DIV2W -DMD32_XARRAY -Ae +ESlit +O2 -z::(unknown)::-Wl,+s -ldld:DES_PTR DES_UNROLL DES_RISC1:${no_asm}:dl:hpux-shared:+Z:-b:.sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "hpux-gcc", "gcc:-DB_ENDIAN -DBN_DIV2W -O3::(unknown)::-Wl,+s -ldld:DES_PTR DES_UNROLL DES_RISC1:${no_asm}:dl:hpux-shared:-fPIC:-shared:.sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", #### HP MPE/iX http://jazz.external.hp.com/src/openssl/ "MPE/iX-gcc", "gcc:-D_ENDIAN -DBN_DIV2W -O3 -D_POSIX_SOURCE -D_SOCKET_SOURCE -I/SYSLOG/PUB::(unknown):MPE:-L/SYSLOG/PUB -lsyslog -lsocket -lcurses:BN_LLONG DES_PTR DES_UNROLL DES_RISC1:::", # DEC Alpha OSF/1/Tru64 targets. # # "What's in a name? That which we call a rose # By any other word would smell as sweet." # # - William Shakespeare, "Romeo & Juliet", Act II, scene II. # # For gcc, the following gave a %50 speedup on a 164 over the 'DES_INT' version # "osf1-alpha-gcc", "gcc:-O3::(unknown):::SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_UNROLL DES_RISC1:${alpha_asm}:dlfcn:alpha-osf1-shared:::.so", "osf1-alpha-cc", "cc:-std1 -tune host -O4 -readonly_strings::(unknown):::SIXTY_FOUR_BIT_LONG RC4_CHUNK:${alpha_asm}:dlfcn:alpha-osf1-shared:::.so", "tru64-alpha-cc", "cc:-std1 -tune host -fast -readonly_strings::-pthread:::SIXTY_FOUR_BIT_LONG RC4_CHUNK:${alpha_asm}:dlfcn:alpha-osf1-shared::-msym:.so", #### #### Variety of LINUX:-) #### # *-generic* is endian-neutral target, but ./config is free to # throw in -D[BL]_ENDIAN, whichever appropriate... "linux-generic32","gcc:-O3 -fomit-frame-pointer -Wall::-D_REENTRANT::-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${no_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "linux-ppc", "gcc:-DB_ENDIAN -O3 -Wall::-D_REENTRANT::-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_RISC1 DES_UNROLL:${ppc32_asm}:linux32:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", ####################################################################### # Note that -march is not among compiler options in below linux-armv4 # target line. Not specifying one is intentional to give you choice to: # # a) rely on your compiler default by not specifying one; # b) specify your target platform explicitly for optimal performance, # e.g. -march=armv6 or -march=armv7-a; # c) build "universal" binary that targets *range* of platforms by # specifying minimum and maximum supported architecture; # # As for c) option. It actually makes no sense to specify maximum to be # less than ARMv7, because it's the least requirement for run-time # switch between platform-specific code paths. And without run-time # switch performance would be equivalent to one for minimum. Secondly, # there are some natural limitations that you'd have to accept and # respect. Most notably you can *not* build "universal" binary for # big-endian platform. This is because ARMv7 processor always picks # instructions in little-endian order. Another similar limitation is # that -mthumb can't "cross" -march=armv6t2 boundary, because that's # where it became Thumb-2. Well, this limitation is a bit artificial, # because it's not really impossible, but it's deemed too tricky to # support. And of course you have to be sure that your binutils are # actually up to the task of handling maximum target platform. With all # this in mind here is an example of how to configure "universal" build: # # ./Configure linux-armv4 -march=armv6 -D__ARM_MAX_ARCH__=8 # "linux-armv4", "gcc: -O3 -Wall::-D_REENTRANT::-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${armv4_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "linux-aarch64","gcc: -O3 -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${aarch64_asm}:linux64:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", # Configure script adds minimally required -march for assembly support, # if no -march was specified at command line. mips32 and mips64 below # refer to contemporary MIPS Architecture specifications, MIPS32 and # MIPS64, rather than to kernel bitness. "linux-mips32", "gcc:-mabi=32 -O3 -Wall -DBN_DIV3W::-D_REENTRANT::-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${mips32_asm}:o32:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "linux-mips64", "gcc:-mabi=n32 -O3 -Wall -DBN_DIV3W::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${mips64_asm}:n32:dlfcn:linux-shared:-fPIC:-mabi=n32:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::32", "linux64-mips64", "gcc:-mabi=64 -O3 -Wall -DBN_DIV3W::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${mips64_asm}:64:dlfcn:linux-shared:-fPIC:-mabi=64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64", #### IA-32 targets... "linux-ia32-icc", "icc:-DL_ENDIAN -O2::-D_REENTRANT::-ldl -no_cpprt:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:linux-shared:-KPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "linux-elf", "gcc:-DL_ENDIAN -O3 -fomit-frame-pointer -Wall::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "linux-aout", "gcc:-DL_ENDIAN -O3 -fomit-frame-pointer -march=i486 -Wall::(unknown):::BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_asm}:a.out", #### "linux-generic64","gcc:-O3 -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${no_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "linux-ppc64", "gcc:-m64 -DB_ENDIAN -O3 -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_RISC1 DES_UNROLL:${ppc64_asm}:linux64:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64", "linux-ppc64le","gcc:-m64 -DL_ENDIAN -O3 -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_RISC1 DES_UNROLL:$ppc64_asm:linux64le:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::", "linux-ia64", "gcc:-DL_ENDIAN -DTERMIO -O3 -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_UNROLL DES_INT:${ia64_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "linux-ia64-icc","icc:-DL_ENDIAN -O2 -Wall::-D_REENTRANT::-ldl -no_cpprt:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_RISC1 DES_INT:${ia64_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "linux-x86_64", "gcc:-m64 -DL_ENDIAN -O3 -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64", "linux-x86_64-clang", "clang: -m64 -DL_ENDIAN -O3 -Wall -Wextra $clang_disabled_warnings -Qunused-arguments::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64", "debug-linux-x86_64-clang", "clang: -DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DCRYPTO_MDEBUG -m64 -DL_ENDIAN -g -Wall -Wextra $clang_disabled_warnings -Qunused-arguments::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64", "linux-x86_64-icc", "icc:-DL_ENDIAN -O2::-D_REENTRANT::-ldl -no_cpprt:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64", "linux-x32", "gcc:-mx32 -DL_ENDIAN -O3 -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT RC4_CHUNK_LL DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:linux-shared:-fPIC:-mx32:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::x32", "linux64-s390x", "gcc:-m64 -DB_ENDIAN -O3 -Wall::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL:${s390x_asm}:64:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64", #### So called "highgprs" target for z/Architecture CPUs # "Highgprs" is kernel feature first implemented in Linux 2.6.32, see # /proc/cpuinfo. The idea is to preserve most significant bits of # general purpose registers not only upon 32-bit process context # switch, but even on asynchronous signal delivery to such process. # This makes it possible to deploy 64-bit instructions even in legacy # application context and achieve better [or should we say adequate] # performance. The build is binary compatible with linux-generic32, # and the idea is to be able to install the resulting libcrypto.so # alongside generic one, e.g. as /lib/highgprs/libcrypto.so.x.y, for # ldconfig and run-time linker to autodiscover. Unfortunately it # doesn't work just yet, because of couple of bugs in glibc # sysdeps/s390/dl-procinfo.c affecting ldconfig and ld.so.1... "linux32-s390x", "gcc:-m31 -Wa,-mzarch -DB_ENDIAN -O3 -Wall::-D_REENTRANT::-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL:".eval{my $asm=$s390x_asm;$asm=~s/bn\-s390x\.o/bn_asm.o/;$asm}.":31:dlfcn:linux-shared:-fPIC:-m31:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::/highgprs", #### SPARC Linux setups # Ray Miller has patiently # assisted with debugging of following two configs. "linux-sparcv8","gcc:-mcpu=v8 -DB_ENDIAN -O3 -fomit-frame-pointer -Wall -DBN_DIV2W::-D_REENTRANT::-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${sparcv8_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", # it's a real mess with -mcpu=ultrasparc option under Linux, but # -Wa,-Av8plus should do the trick no matter what. "linux-sparcv9","gcc:-m32 -mcpu=ultrasparc -DB_ENDIAN -O3 -fomit-frame-pointer -Wall -Wa,-Av8plus -DBN_DIV2W::-D_REENTRANT:ULTRASPARC:-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${sparcv9_asm}:dlfcn:linux-shared:-fPIC:-m32:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", # GCC 3.1 is a requirement "linux64-sparcv9","gcc:-m64 -mcpu=ultrasparc -DB_ENDIAN -O3 -fomit-frame-pointer -Wall::-D_REENTRANT:ULTRASPARC:-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_INT DES_PTR DES_RISC1 DES_UNROLL BF_PTR:${sparcv9_asm}:dlfcn:linux-shared:-fPIC:-m64:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):::64", #### Alpha Linux with GNU C and Compaq C setups # Special notes: # - linux-alpha+bwx-gcc is ment to be used from ./config only. If you # ought to run './Configure linux-alpha+bwx-gcc' manually, do # complement the command line with -mcpu=ev56, -mcpu=ev6 or whatever # which is appropriate. # - If you use ccc keep in mind that -fast implies -arch host and the # compiler is free to issue instructions which gonna make elder CPU # choke. If you wish to build "blended" toolkit, add -arch generic # *after* -fast and invoke './Configure linux-alpha-ccc' manually. # # # "linux-alpha-gcc","gcc:-O3 -DL_ENDIAN::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_RISC1 DES_UNROLL:${alpha_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "linux-alpha+bwx-gcc","gcc:-O3 -DL_ENDIAN::-D_REENTRANT::-ldl:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_RISC1 DES_UNROLL:${alpha_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "linux-alpha-ccc","ccc:-fast -readonly_strings -DL_ENDIAN::-D_REENTRANT:::SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_PTR DES_RISC1 DES_UNROLL:${alpha_asm}", "linux-alpha+bwx-ccc","ccc:-fast -readonly_strings -DL_ENDIAN::-D_REENTRANT:::SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_INT DES_PTR DES_RISC1 DES_UNROLL:${alpha_asm}", # Android: linux-* but without pointers to headers and libs. "android","gcc:-mandroid -I\$(ANDROID_DEV)/include -B\$(ANDROID_DEV)/lib -O3 -fomit-frame-pointer -Wall::-D_REENTRANT::-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${no_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "android-x86","gcc:-mandroid -I\$(ANDROID_DEV)/include -B\$(ANDROID_DEV)/lib -O3 -fomit-frame-pointer -Wall::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:".eval{my $asm=${x86_elf_asm};$asm=~s/:elf/:android/;$asm}.":dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "android-armv7","gcc:-march=armv7-a -mandroid -I\$(ANDROID_DEV)/include -B\$(ANDROID_DEV)/lib -O3 -fomit-frame-pointer -Wall::-D_REENTRANT::-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${armv4_asm}:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "android-mips","gcc:-mandroid -I\$(ANDROID_DEV)/include -B\$(ANDROID_DEV)/lib -O3 -Wall::-D_REENTRANT::-ldl:BN_LLONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL BF_PTR:${mips32_asm}:o32:dlfcn:linux-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", #### *BSD [do see comment about ${BSDthreads} above!] "BSD-generic32","gcc:-O3 -fomit-frame-pointer -Wall::${BSDthreads}:::BN_LLONG RC2_CHAR RC4_INDEX DES_INT DES_UNROLL:${no_asm}:dlfcn:bsd-gcc-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "BSD-x86", "gcc:-DL_ENDIAN -O3 -fomit-frame-pointer -Wall::${BSDthreads}:::BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_asm}:a.out:dlfcn:bsd-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "BSD-x86-elf", "gcc:-DL_ENDIAN -O3 -fomit-frame-pointer -Wall::${BSDthreads}:::BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:bsd-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "debug-BSD-x86-elf", "gcc:-DL_ENDIAN -O3 -Wall -g::${BSDthreads}:::BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:bsd-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "BSD-sparcv8", "gcc:-DB_ENDIAN -O3 -mcpu=v8 -Wall::${BSDthreads}:::BN_LLONG RC2_CHAR RC4_INDEX DES_INT DES_UNROLL:${sparcv8_asm}:dlfcn:bsd-gcc-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "BSD-generic64","gcc:-O3 -Wall::${BSDthreads}:::SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${no_asm}:dlfcn:bsd-gcc-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", # -DMD32_REG_T=int doesn't actually belong in sparc64 target, it # simply *happens* to work around a compiler bug in gcc 3.3.3, # triggered by RIPEMD160 code. "BSD-sparc64", "gcc:-DB_ENDIAN -O3 -DMD32_REG_T=int -Wall::${BSDthreads}:::BN_LLONG RC2_CHAR RC4_CHUNK DES_INT DES_PTR DES_RISC2 BF_PTR:${sparcv9_asm}:dlfcn:bsd-gcc-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "BSD-ia64", "gcc:-DL_ENDIAN -O3 -Wall::${BSDthreads}:::SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_UNROLL DES_INT:${ia64_asm}:dlfcn:bsd-gcc-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "BSD-x86_64", "cc:-DL_ENDIAN -O3 -Wall::${BSDthreads}:::SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:elf:dlfcn:bsd-gcc-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "bsdi-elf-gcc", "gcc:-DPERL5 -DL_ENDIAN -fomit-frame-pointer -O3 -march=i486 -Wall::(unknown)::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:bsd-gcc-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "nextstep", "cc:-O -Wall::(unknown):::BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:::", "nextstep3.3", "cc:-O3 -Wall::(unknown):::BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:::", # NCR MP-RAS UNIX ver 02.03.01 "ncr-scde","cc:-O6 -Xa -Hoff=BEHAVED -686 -Hwide -Hiw::(unknown)::-lsocket -lnsl -lc89:${x86_gcc_des} ${x86_gcc_opts}:::", # QNX "qnx4", "cc:-DL_ENDIAN -DTERMIO::(unknown):::${x86_gcc_des} ${x86_gcc_opts}:", "QNX6", "gcc:::::-lsocket::${no_asm}:dlfcn:bsd-gcc-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "QNX6-i386", "gcc:-DL_ENDIAN -O2 -Wall::::-lsocket:${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:bsd-gcc-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", # BeOS "beos-x86-r5", "gcc:-DL_ENDIAN -DTERMIOS -O3 -fomit-frame-pointer -mcpu=pentium -Wall::-D_REENTRANT:BEOS:-lbe -lnet:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:beos:beos-shared:-fPIC -DPIC:-shared:.so", "beos-x86-bone", "gcc:-DL_ENDIAN -DTERMIOS -O3 -fomit-frame-pointer -mcpu=pentium -Wall::-D_REENTRANT:BEOS:-lbe -lbind -lsocket:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:beos:beos-shared:-fPIC:-shared:.so", #### SCO/Caldera targets. # # Originally we had like unixware-*, unixware-*-pentium, unixware-*-p6, etc. # Now we only have blended unixware-* as it's the only one used by ./config. # If you want to optimize for particular microarchitecture, bypass ./config # and './Configure unixware-7 -Kpentium_pro' or whatever appropriate. # Note that not all targets include assembler support. Mostly because of # lack of motivation to support out-of-date platforms with out-of-date # compiler drivers and assemblers. Tim Rice has # patiently assisted to debug most of it. # # UnixWare 2.0x fails destest with -O. "unixware-2.0","cc:-DFILIO_H -DNO_STRINGS_H::-Kthread::-lsocket -lnsl -lresolv -lx:${x86_gcc_des} ${x86_gcc_opts}:::", "unixware-2.1","cc:-O -DFILIO_H::-Kthread::-lsocket -lnsl -lresolv -lx:${x86_gcc_des} ${x86_gcc_opts}:::", "unixware-7","cc:-O -DFILIO_H -Kalloca::-Kthread::-lsocket -lnsl:BN_LLONG MD2_CHAR RC4_INDEX ${x86_gcc_des}:${x86_elf_asm}-1:dlfcn:svr5-shared:-Kpic::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "unixware-7-gcc","gcc:-DL_ENDIAN -DFILIO_H -O3 -fomit-frame-pointer -march=pentium -Wall::-D_REENTRANT::-lsocket -lnsl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}-1:dlfcn:gnu-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", # SCO 5 - Ben Laurie says the -O breaks the SCO cc. "sco5-cc", "cc:-belf::(unknown)::-lsocket -lnsl:${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}-1:dlfcn:svr3-shared:-Kpic::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "sco5-gcc", "gcc:-O3 -fomit-frame-pointer::(unknown)::-lsocket -lnsl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}-1:dlfcn:svr3-shared:-fPIC::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", #### IBM's AIX. "aix3-cc", "cc:-O -DB_ENDIAN -qmaxmem=16384::(unknown):AIX::BN_LLONG RC4_CHAR:::", "aix-gcc", "gcc:-O -DB_ENDIAN::-pthread:AIX::BN_LLONG RC4_CHAR:${ppc32_asm}:aix32:dlfcn:aix-shared::-shared -Wl,-G:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)::-X32", "aix64-gcc","gcc:-maix64 -O -DB_ENDIAN::-pthread:AIX::SIXTY_FOUR_BIT_LONG RC4_CHAR:${ppc64_asm}:aix64:dlfcn:aix-shared::-maix64 -shared -Wl,-G:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)::-X64", # Below targets assume AIX 5. Idea is to effectively disregard $OBJECT_MODE # at build time. $OBJECT_MODE is respected at ./config stage! "aix-cc", "cc:-q32 -O -DB_ENDIAN -qmaxmem=16384 -qro -qroconst::-qthreaded -D_THREAD_SAFE:AIX::BN_LLONG RC4_CHAR:${ppc32_asm}:aix32:dlfcn:aix-shared::-q32 -G:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)::-X 32", "aix64-cc", "cc:-q64 -O -DB_ENDIAN -qmaxmem=16384 -qro -qroconst::-qthreaded -D_THREAD_SAFE:AIX::SIXTY_FOUR_BIT_LONG RC4_CHAR:${ppc64_asm}:aix64:dlfcn:aix-shared::-q64 -G:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)::-X 64", # # Cray T90 and similar (SDSC) # It's Big-endian, but the algorithms work properly when B_ENDIAN is NOT # defined. The T90 ints and longs are 8 bytes long, and apparently the # B_ENDIAN code assumes 4 byte ints. Fortunately, the non-B_ENDIAN and # non L_ENDIAN code aligns the bytes in each word correctly. # # The BIT_FIELD_LIMITS define is to avoid two fatal compiler errors: #'Taking the address of a bit field is not allowed. ' #'An expression with bit field exists as the operand of "sizeof" ' # (written by Wayne Schroeder ) # # j90 is considered the base machine type for unicos machines, # so this configuration is now called "cray-j90" ... "cray-j90", "cc: -DBIT_FIELD_LIMITS -DTERMIOS::(unknown):CRAY::SIXTY_FOUR_BIT_LONG DES_INT:::", # # Cray T3E (Research Center Juelich, beckman@acl.lanl.gov) # # The BIT_FIELD_LIMITS define was written for the C90 (it seems). I added # another use. Basically, the problem is that the T3E uses some bit fields # for some st_addr stuff, and then sizeof and address-of fails # I could not use the ams/alpha.o option because the Cray assembler, 'cam' # did not like it. "cray-t3e", "cc: -DBIT_FIELD_LIMITS -DTERMIOS::(unknown):CRAY::SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT:::", # DGUX, 88100. "dgux-R3-gcc", "gcc:-O3 -fomit-frame-pointer::(unknown):::RC4_INDEX DES_UNROLL:::", "dgux-R4-gcc", "gcc:-O3 -fomit-frame-pointer::(unknown)::-lnsl -lsocket:RC4_INDEX DES_UNROLL:::", "dgux-R4-x86-gcc", "gcc:-O3 -fomit-frame-pointer -DL_ENDIAN::(unknown)::-lnsl -lsocket:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}", # Sinix/ReliantUNIX RM400 # NOTE: The CDS++ Compiler up to V2.0Bsomething has the IRIX_CC_BUG optimizer problem. Better use -g */ "ReliantUNIX","cc:-KPIC -g -DTERMIOS -DB_ENDIAN::-Kthread:SNI:-lsocket -lnsl -lc -L/usr/ucblib -lucb:BN_LLONG DES_PTR DES_RISC2 DES_UNROLL BF_PTR:${no_asm}:dlfcn:reliantunix-shared:::.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", "SINIX","cc:-O::(unknown):SNI:-lsocket -lnsl -lc -L/usr/ucblib -lucb:RC4_INDEX RC4_CHAR:::", "SINIX-N","/usr/ucb/cc:-O2 -misaligned::(unknown)::-lucb:RC4_INDEX RC4_CHAR:::", # SIEMENS BS2000/OSD: an EBCDIC-based mainframe "BS2000-OSD","c89:-O -XLLML -XLLMK -XL -DB_ENDIAN -DCHARSET_EBCDIC::(unknown)::-lsocket -lnsl:THIRTY_TWO_BIT DES_PTR DES_UNROLL MD2_CHAR RC4_INDEX RC4_CHAR BF_PTR:::", # OS/390 Unix an EBCDIC-based Unix system on IBM mainframe # You need to compile using the c89.sh wrapper in the tools directory, because the # IBM compiler does not like the -L switch after any object modules. # "OS390-Unix","c89.sh:-O -DB_ENDIAN -DCHARSET_EBCDIC -DNO_SYS_PARAM_H -D_ALL_SOURCE::(unknown):::THIRTY_TWO_BIT DES_PTR DES_UNROLL MD2_CHAR RC4_INDEX RC4_CHAR BF_PTR:::", # Visual C targets # # Win64 targets, WIN64I denotes IA-64 and WIN64A - AMD64 "VC-WIN64I","cl:-W3 -Gs0 -Gy -nologo -DOPENSSL_SYSNAME_WIN32 -DWIN32_LEAN_AND_MEAN -DL_ENDIAN -DUNICODE -D_UNICODE -D_CRT_SECURE_NO_DEPRECATE:::WIN64I::SIXTY_FOUR_BIT RC4_CHUNK_LL DES_INT EXPORT_VAR_AS_FN:ia64cpuid.o:ia64.o ia64-mont.o:::aes_core.o aes_cbc.o aes-ia64.o::md5-ia64.o:sha1-ia64.o sha256-ia64.o sha512-ia64.o:::::::ghash-ia64.o::ias:win32", "VC-WIN64A","cl:-W3 -Gs0 -Gy -nologo -DOPENSSL_SYSNAME_WIN32 -DWIN32_LEAN_AND_MEAN -DL_ENDIAN -DUNICODE -D_UNICODE -D_CRT_SECURE_NO_DEPRECATE:::WIN64A::SIXTY_FOUR_BIT RC4_CHUNK_LL DES_INT EXPORT_VAR_AS_FN:".eval{my $asm=$x86_64_asm;$asm=~s/x86_64-gcc\.o/bn_asm.o/;$asm}.":auto:win32", "debug-VC-WIN64I","cl:-W3 -Gs0 -Gy -Zi -nologo -DOPENSSL_SYSNAME_WIN32 -DWIN32_LEAN_AND_MEAN -DL_ENDIAN -DUNICODE -D_UNICODE -D_CRT_SECURE_NO_DEPRECATE:::WIN64I::SIXTY_FOUR_BIT RC4_CHUNK_LL DES_INT EXPORT_VAR_AS_FN:ia64cpuid.o:ia64.o:::aes_core.o aes_cbc.o aes-ia64.o::md5-ia64.o:sha1-ia64.o sha256-ia64.o sha512-ia64.o:::::::ghash-ia64.o::ias:win32", "debug-VC-WIN64A","cl:-W3 -Gs0 -Gy -Zi -nologo -DOPENSSL_SYSNAME_WIN32 -DWIN32_LEAN_AND_MEAN -DL_ENDIAN -DUNICODE -D_UNICODE -D_CRT_SECURE_NO_DEPRECATE:::WIN64A::SIXTY_FOUR_BIT RC4_CHUNK_LL DES_INT EXPORT_VAR_AS_FN:".eval{my $asm=$x86_64_asm;$asm=~s/x86_64-gcc\.o/bn_asm.o/;$asm}.":auto:win32", # x86 Win32 target defaults to ANSI API, if you want UNICODE, complement # 'perl Configure VC-WIN32' with '-DUNICODE -D_UNICODE' "VC-WIN32","cl:-W3 -Gs0 -GF -Gy -nologo -DOPENSSL_SYSNAME_WIN32 -DWIN32_LEAN_AND_MEAN -DL_ENDIAN -D_CRT_SECURE_NO_DEPRECATE:::WIN32::BN_LLONG RC4_INDEX EXPORT_VAR_AS_FN ${x86_gcc_opts}:${x86_asm}:win32n:win32", # Unified CE target "debug-VC-WIN32","cl:-W3 -Gs0 -GF -Gy -Zi -nologo -DOPENSSL_SYSNAME_WIN32 -DWIN32_LEAN_AND_MEAN -DL_ENDIAN -D_CRT_SECURE_NO_DEPRECATE:::WIN32::BN_LLONG RC4_INDEX EXPORT_VAR_AS_FN ${x86_gcc_opts}:${x86_asm}:win32n:win32", "VC-CE","cl::::WINCE::BN_LLONG RC4_INDEX EXPORT_VAR_AS_FN ${x86_gcc_opts}:${no_asm}:win32", # Borland C++ 4.5 "BC-32","bcc32::::WIN32::BN_LLONG DES_PTR RC4_INDEX EXPORT_VAR_AS_FN:${no_asm}:win32", # MinGW "mingw", "gcc:-mno-cygwin -DL_ENDIAN -DWIN32_LEAN_AND_MEAN -fomit-frame-pointer -O3 -march=i486 -Wall::-D_MT:MINGW32:-lws2_32 -lgdi32 -lcrypt32:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts} EXPORT_VAR_AS_FN:${x86_asm}:coff:win32:cygwin-shared:-D_WINDLL -DOPENSSL_USE_APPLINK:-mno-cygwin:.dll.a", # As for OPENSSL_USE_APPLINK. Applink makes it possible to use .dll # compiled with one compiler with application compiled with another # compiler. It's possible to engage Applink support in mingw64 build, # but it's not done, because till mingw64 supports structured exception # handling, one can't seriously consider its binaries for using with # non-mingw64 run-time environment. And as mingw64 is always consistent # with itself, Applink is never engaged and can as well be omitted. "mingw64", "gcc:-mno-cygwin -DL_ENDIAN -O3 -Wall -DWIN32_LEAN_AND_MEAN -DUNICODE -D_UNICODE::-D_MT:MINGW64:-lws2_32 -lgdi32 -lcrypt32:SIXTY_FOUR_BIT RC4_CHUNK_LL DES_INT EXPORT_VAR_AS_FN:${x86_64_asm}:mingw64:win32:cygwin-shared:-D_WINDLL:-mno-cygwin:.dll.a", # UWIN "UWIN", "cc:-DTERMIOS -DL_ENDIAN -O -Wall:::UWIN::BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${no_asm}:win32", # Cygwin "Cygwin", "gcc:-DTERMIOS -DL_ENDIAN -fomit-frame-pointer -O3 -march=i486 -Wall:::CYGWIN::BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_asm}:coff:dlfcn:cygwin-shared:-D_WINDLL:-shared:.dll.a", "Cygwin-x86_64", "gcc:-DTERMIOS -DL_ENDIAN -O3 -Wall:::CYGWIN::SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:${x86_64_asm}:mingw64:dlfcn:cygwin-shared:-D_WINDLL:-shared:.dll.a", # NetWare from David Ward (dsward@novell.com) # requires either MetroWerks NLM development tools, or gcc / nlmconv # NetWare defaults socket bio to WinSock sockets. However, # the builds can be configured to use BSD sockets instead. # netware-clib => legacy CLib c-runtime support "netware-clib", "mwccnlm::::::${x86_gcc_opts}::", "netware-clib-bsdsock", "mwccnlm::::::${x86_gcc_opts}::", "netware-clib-gcc", "i586-netware-gcc:-nostdinc -I/ndk/nwsdk/include/nlm -I/ndk/ws295sdk/include -DL_ENDIAN -DNETWARE_CLIB -DOPENSSL_SYSNAME_NETWARE -O2 -Wall:::::${x86_gcc_opts}::", "netware-clib-bsdsock-gcc", "i586-netware-gcc:-nostdinc -I/ndk/nwsdk/include/nlm -DNETWARE_BSDSOCK -DNETDB_USE_INTERNET -DL_ENDIAN -DNETWARE_CLIB -DOPENSSL_SYSNAME_NETWARE -O2 -Wall:::::${x86_gcc_opts}::", # netware-libc => LibC/NKS support "netware-libc", "mwccnlm::::::BN_LLONG ${x86_gcc_opts}::", "netware-libc-bsdsock", "mwccnlm::::::BN_LLONG ${x86_gcc_opts}::", "netware-libc-gcc", "i586-netware-gcc:-nostdinc -I/ndk/libc/include -I/ndk/libc/include/winsock -DL_ENDIAN -DNETWARE_LIBC -DOPENSSL_SYSNAME_NETWARE -DTERMIO -O2 -Wall:::::BN_LLONG ${x86_gcc_opts}::", "netware-libc-bsdsock-gcc", "i586-netware-gcc:-nostdinc -I/ndk/libc/include -DNETWARE_BSDSOCK -DL_ENDIAN -DNETWARE_LIBC -DOPENSSL_SYSNAME_NETWARE -DTERMIO -O2 -Wall:::::BN_LLONG ${x86_gcc_opts}::", # DJGPP "DJGPP", "gcc:-I/dev/env/WATT_ROOT/inc -DTERMIO -DL_ENDIAN -fomit-frame-pointer -O2 -Wall:::MSDOS:-L/dev/env/WATT_ROOT/lib -lwatt:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_asm}:a.out:", # Ultrix from Bernhard Simon "ultrix-cc","cc:-std1 -O -Olimit 2500 -DL_ENDIAN::(unknown):::::::", "ultrix-gcc","gcc:-O3 -DL_ENDIAN::(unknown):::BN_LLONG::::", # K&R C is no longer supported; you need gcc on old Ultrix installations ##"ultrix","cc:-O2 -DNOPROTO -DNOCONST -DL_ENDIAN::(unknown):::::::", ##### MacOS X (a.k.a. Rhapsody or Darwin) setup "rhapsody-ppc-cc","cc:-O3 -DB_ENDIAN::(unknown):MACOSX_RHAPSODY::BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${no_asm}::", "darwin-ppc-cc","cc:-arch ppc -O3 -DB_ENDIAN -Wa,-force_cpusubtype_ALL::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${ppc32_asm}:osx32:dlfcn:darwin-shared:-fPIC -fno-common:-arch ppc -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib", "darwin64-ppc-cc","cc:-arch ppc64 -O3 -DB_ENDIAN::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${ppc64_asm}:osx64:dlfcn:darwin-shared:-fPIC -fno-common:-arch ppc64 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib", "darwin-i386-cc","cc:-arch i386 -O3 -fomit-frame-pointer -DL_ENDIAN::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:BN_LLONG RC4_INT RC4_CHUNK DES_UNROLL BF_PTR:".eval{my $asm=$x86_asm;$asm=~s/cast\-586\.o//;$asm}.":macosx:dlfcn:darwin-shared:-fPIC -fno-common:-arch i386 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib", "debug-darwin-i386-cc","cc:-arch i386 -g3 -DL_ENDIAN::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:BN_LLONG RC4_INT RC4_CHUNK DES_UNROLL BF_PTR:${x86_asm}:macosx:dlfcn:darwin-shared:-fPIC -fno-common:-arch i386 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib", "darwin64-x86_64-cc","cc:-arch x86_64 -O3 -DL_ENDIAN -Wall::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:".eval{my $asm=$x86_64_asm;$asm=~s/rc4\-[^:]+//;$asm}.":macosx:dlfcn:darwin-shared:-fPIC -fno-common:-arch x86_64 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib", "debug-darwin64-x86_64-cc","cc:-arch x86_64 -ggdb -g2 -O0 -DL_ENDIAN -Wall::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:".eval{my $asm=$x86_64_asm;$asm=~s/rc4\-[^:]+//;$asm}.":macosx:dlfcn:darwin-shared:-fPIC -fno-common:-arch x86_64 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib", "debug-darwin-ppc-cc","cc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DCRYPTO_MDEBUG -DB_ENDIAN -g -Wall -O::-D_REENTRANT:MACOSX::BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${ppc32_asm}:osx32:dlfcn:darwin-shared:-fPIC:-dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib", # iPhoneOS/iOS "iphoneos-cross","llvm-gcc:-O3 -isysroot \$(CROSS_TOP)/SDKs/\$(CROSS_SDK) -fomit-frame-pointer -fno-common::-D_REENTRANT:iOS:-Wl,-search_paths_first%:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${no_asm}:dlfcn:darwin-shared:-fPIC -fno-common:-dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib", ##### A/UX "aux3-gcc","gcc:-O2 -DTERMIO::(unknown):AUX:-lbsd:RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:::", ##### Sony NEWS-OS 4.x "newsos4-gcc","gcc:-O -DB_ENDIAN::(unknown):NEWS4:-lmld -liberty:BN_LLONG RC4_CHAR RC4_CHUNK DES_PTR DES_RISC1 DES_UNROLL BF_PTR::::", ##### GNU Hurd "hurd-x86", "gcc:-DL_ENDIAN -O3 -fomit-frame-pointer -march=i486 -Wall::-D_REENTRANT::-ldl:BN_LLONG ${x86_gcc_des} ${x86_gcc_opts}:${x86_elf_asm}:dlfcn:linux-shared:-fPIC", ##### OS/2 EMX "OS2-EMX", "gcc::::::::", ##### VxWorks for various targets "vxworks-ppc60x","ccppc:-D_REENTRANT -mrtp -mhard-float -mstrict-align -fno-implicit-fp -DPPC32_fp60x -O2 -fstrength-reduce -fno-builtin -fno-strict-aliasing -Wall -DCPU=PPC32 -DTOOL_FAMILY=gnu -DTOOL=gnu -I\$(WIND_BASE)/target/usr/h -I\$(WIND_BASE)/target/usr/h/wrn/coreip:::VXWORKS:-Wl,--defsym,__wrs_rtp_base=0xe0000000 -L \$(WIND_BASE)/target/usr/lib/ppc/PPC32/common:::::", "vxworks-ppcgen","ccppc:-D_REENTRANT -mrtp -msoft-float -mstrict-align -O1 -fno-builtin -fno-strict-aliasing -Wall -DCPU=PPC32 -DTOOL_FAMILY=gnu -DTOOL=gnu -I\$(WIND_BASE)/target/usr/h -I\$(WIND_BASE)/target/usr/h/wrn/coreip:::VXWORKS:-Wl,--defsym,__wrs_rtp_base=0xe0000000 -L \$(WIND_BASE)/target/usr/lib/ppc/PPC32/sfcommon:::::", "vxworks-ppc405","ccppc:-g -msoft-float -mlongcall -DCPU=PPC405 -I\$(WIND_BASE)/target/h:::VXWORKS:-r:::::", "vxworks-ppc750","ccppc:-ansi -nostdinc -DPPC750 -D_REENTRANT -fvolatile -fno-builtin -fno-for-scope -fsigned-char -Wall -msoft-float -mlongcall -DCPU=PPC604 -I\$(WIND_BASE)/target/h \$(DEBUG_FLAG):::VXWORKS:-r:::::", "vxworks-ppc750-debug","ccppc:-ansi -nostdinc -DPPC750 -D_REENTRANT -fvolatile -fno-builtin -fno-for-scope -fsigned-char -Wall -msoft-float -mlongcall -DCPU=PPC604 -I\$(WIND_BASE)/target/h -DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DBN_CTX_DEBUG -DCRYPTO_MDEBUG -DPEDANTIC -DDEBUG_SAFESTACK -DDEBUG -g:::VXWORKS:-r:::::", "vxworks-ppc860","ccppc:-nostdinc -msoft-float -DCPU=PPC860 -DNO_STRINGS_H -I\$(WIND_BASE)/target/h:::VXWORKS:-r:::::", "vxworks-simlinux","ccpentium:-B\$(WIND_BASE)/host/\$(WIND_HOST_TYPE)/lib/gcc-lib/ -D_VSB_CONFIG_FILE=\"\$(WIND_BASE)/target/lib/h/config/vsbConfig.h\" -DL_ENDIAN -DCPU=SIMLINUX -DTOOL_FAMILY=gnu -DTOOL=gnu -fno-builtin -fno-defer-pop -DNO_STRINGS_H -I\$(WIND_BASE)/target/h -I\$(WIND_BASE)/target/h/wrn/coreip -DOPENSSL_NO_HW_PADLOCK:::VXWORKS:-r::${no_asm}::::::ranlibpentium:", "vxworks-mips","ccmips:-mrtp -mips2 -O -G 0 -B\$(WIND_BASE)/host/\$(WIND_HOST_TYPE)/lib/gcc-lib/ -D_VSB_CONFIG_FILE=\"\$(WIND_BASE)/target/lib/h/config/vsbConfig.h\" -DCPU=MIPS32 -msoft-float -mno-branch-likely -DTOOL_FAMILY=gnu -DTOOL=gnu -fno-builtin -fno-defer-pop -DNO_STRINGS_H -I\$(WIND_BASE)/target/usr/h -I\$(WIND_BASE)/target/h/wrn/coreip::-D_REENTRANT:VXWORKS:-Wl,--defsym,__wrs_rtp_base=0xe0000000 -L \$(WIND_BASE)/target/usr/lib/mips/MIPSI32/sfcommon::${mips32_asm}:o32::::::ranlibmips:", ##### Compaq Non-Stop Kernel (Tandem) "tandem-c89","c89:-Ww -D__TANDEM -D_XOPEN_SOURCE -D_XOPEN_SOURCE_EXTENDED=1 -D_TANDEM_SOURCE -DB_ENDIAN::(unknown):::THIRTY_TWO_BIT:::", # uClinux "uClinux-dist","$ENV{'CC'}:\$(CFLAGS)::-D_REENTRANT::\$(LDFLAGS) \$(LDLIBS):BN_LLONG:${no_asm}:$ENV{'LIBSSL_dlfcn'}:linux-shared:-fPIC:-shared:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):$ENV{'RANLIB'}::", "uClinux-dist64","$ENV{'CC'}:\$(CFLAGS)::-D_REENTRANT::\$(LDFLAGS) \$(LDLIBS):SIXTY_FOUR_BIT_LONG:${no_asm}:$ENV{'LIBSSL_dlfcn'}:linux-shared:-fPIC:-shared:.so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR):$ENV{'RANLIB'}::", ); my @MK1MF_Builds=qw(VC-WIN64I VC-WIN64A debug-VC-WIN64I debug-VC-WIN64A VC-NT VC-CE VC-WIN32 debug-VC-WIN32 BC-32 netware-clib netware-clib-bsdsock netware-libc netware-libc-bsdsock); my $idx = 0; my $idx_cc = $idx++; my $idx_cflags = $idx++; my $idx_unistd = $idx++; my $idx_thread_cflag = $idx++; my $idx_sys_id = $idx++; my $idx_lflags = $idx++; my $idx_bn_ops = $idx++; my $idx_cpuid_obj = $idx++; my $idx_bn_obj = $idx++; my $idx_ec_obj = $idx++; my $idx_des_obj = $idx++; my $idx_aes_obj = $idx++; my $idx_bf_obj = $idx++; my $idx_md5_obj = $idx++; my $idx_sha1_obj = $idx++; my $idx_cast_obj = $idx++; my $idx_rc4_obj = $idx++; my $idx_rmd160_obj = $idx++; my $idx_rc5_obj = $idx++; my $idx_wp_obj = $idx++; my $idx_cmll_obj = $idx++; my $idx_modes_obj = $idx++; my $idx_engines_obj = $idx++; my $idx_perlasm_scheme = $idx++; my $idx_dso_scheme = $idx++; my $idx_shared_target = $idx++; my $idx_shared_cflag = $idx++; my $idx_shared_ldflag = $idx++; my $idx_shared_extension = $idx++; my $idx_ranlib = $idx++; my $idx_arflags = $idx++; my $idx_multilib = $idx++; my $prefix=""; my $libdir=""; my $openssldir=""; my $exe_ext=""; my $install_prefix= "$ENV{'INSTALL_PREFIX'}"; my $cross_compile_prefix=""; my $fipsdir="/usr/local/ssl/fips-2.0"; my $fipslibdir=""; my $baseaddr="0xFB00000"; my $no_threads=0; my $threads=0; my $no_shared=0; # but "no-shared" is default my $zlib=1; # but "no-zlib" is default my $no_krb5=0; # but "no-krb5" is implied unless "--with-krb5-..." is used my $no_rfc3779=1; # but "no-rfc3779" is default my $no_asm=0; my $no_dso=0; my $no_gmp=0; my @skip=(); my $Makefile="Makefile"; my $des_locl="crypto/des/des_locl.h"; my $des ="crypto/des/des.h"; my $bn ="crypto/bn/bn.h"; my $md2 ="crypto/md2/md2.h"; my $rc4 ="crypto/rc4/rc4.h"; my $rc4_locl="crypto/rc4/rc4_locl.h"; my $idea ="crypto/idea/idea.h"; my $rc2 ="crypto/rc2/rc2.h"; my $bf ="crypto/bf/bf_locl.h"; my $bn_asm ="bn_asm.o"; my $des_enc="des_enc.o fcrypt_b.o"; my $aes_enc="aes_core.o aes_cbc.o"; my $bf_enc ="bf_enc.o"; my $cast_enc="c_enc.o"; my $rc4_enc="rc4_enc.o rc4_skey.o"; my $rc5_enc="rc5_enc.o"; my $md5_obj=""; my $sha1_obj=""; my $rmd160_obj=""; my $cmll_enc="camellia.o cmll_misc.o cmll_cbc.o"; my $processor=""; my $default_ranlib; my $perl; my $fips=0; if (exists $ENV{FIPSDIR}) { $fipsdir = $ENV{FIPSDIR}; $fipsdir =~ s/\/$//; } # All of the following is disabled by default (RC5 was enabled before 0.9.8): my %disabled = ( # "what" => "comment" [or special keyword "experimental"] "ec_nistp_64_gcc_128" => "default", "gmp" => "default", "jpake" => "experimental", "libunbound" => "experimental", "md2" => "default", "rc5" => "default", "rfc3779" => "default", "sctp" => "default", "shared" => "default", "ssl-trace" => "default", "ssl2" => "default", "store" => "experimental", "unit-test" => "default", "weak-ssl-ciphers" => "default", "zlib" => "default", "zlib-dynamic" => "default" ); my @experimental = (); # This is what $depflags will look like with the above defaults # (we need this to see if we should advise the user to run "make depend"): my $default_depflags = " -DOPENSSL_NO_EC_NISTP_64_GCC_128 -DOPENSSL_NO_GMP -DOPENSSL_NO_JPAKE -DOPENSSL_NO_LIBUNBOUND -DOPENSSL_NO_MD2 -DOPENSSL_NO_RC5 -DOPENSSL_NO_RFC3779 -DOPENSSL_NO_SCTP -DOPENSSL_NO_SSL_TRACE -DOPENSSL_NO_SSL2 -DOPENSSL_NO_STORE -DOPENSSL_NO_UNIT_TEST -DOPENSSL_NO_WEAK_SSL_CIPHERS"; # Explicit "no-..." options will be collected in %disabled along with the defaults. # To remove something from %disabled, use "enable-foo" (unless it's experimental). # For symmetry, "disable-foo" is a synonym for "no-foo". # For features called "experimental" here, a more explicit "experimental-foo" is needed to enable. # We will collect such requests in @experimental. # To avoid accidental use of experimental features, applications will have to use -DOPENSSL_EXPERIMENTAL_FOO. my $no_sse2=0; &usage if ($#ARGV < 0); my $flags; my $depflags; my $openssl_experimental_defines; my $openssl_algorithm_defines; my $openssl_thread_defines; my $openssl_sys_defines=""; my $openssl_other_defines; my $libs; my $libkrb5=""; my $target; my $options; my $symlink; my $make_depend=0; my %withargs=(); my @argvcopy=@ARGV; my $argvstring=""; my $argv_unprocessed=1; while($argv_unprocessed) { $flags=""; $depflags=""; $openssl_experimental_defines=""; $openssl_algorithm_defines=""; $openssl_thread_defines=""; $openssl_sys_defines=""; $openssl_other_defines=""; $libs=""; $target=""; $options=""; $symlink=1; $argv_unprocessed=0; $argvstring=join(' ',@argvcopy); PROCESS_ARGS: foreach (@argvcopy) { s /^-no-/no-/; # some people just can't read the instructions # rewrite some options in "enable-..." form s /^-?-?shared$/enable-shared/; s /^sctp$/enable-sctp/; s /^threads$/enable-threads/; s /^zlib$/enable-zlib/; s /^zlib-dynamic$/enable-zlib-dynamic/; if (/^no-(.+)$/ || /^disable-(.+)$/) { if (!($disabled{$1} eq "experimental")) { if ($1 eq "ssl") { $disabled{"ssl2"} = "option(ssl)"; $disabled{"ssl3"} = "option(ssl)"; } elsif ($1 eq "tls") { $disabled{"tls1"} = "option(tls)" } elsif ($1 eq "ssl3-method") { $disabled{"ssl3-method"} = "option(ssl)"; $disabled{"ssl3"} = "option(ssl)"; } else { $disabled{$1} = "option"; } } } elsif (/^enable-(.+)$/ || /^experimental-(.+)$/) { my $algo = $1; if ($disabled{$algo} eq "experimental") { die "You are requesting an experimental feature; please say 'experimental-$algo' if you are sure\n" unless (/^experimental-/); push @experimental, $algo; } delete $disabled{$algo}; $threads = 1 if ($algo eq "threads"); } elsif (/^--test-sanity$/) { exit(&test_sanity()); } elsif (/^--strict-warnings/) { $strict_warnings = 1; } elsif (/^reconfigure/ || /^reconf/) { if (open(IN,"<$Makefile")) { while () { chomp; if (/^CONFIGURE_ARGS=(.*)/) { $argvstring=$1; @argvcopy=split(' ',$argvstring); die "Incorrect data to reconfigure, please do a normal configuration\n" if (grep(/^reconf/,@argvcopy)); print "Reconfiguring with: $argvstring\n"; $argv_unprocessed=1; close(IN); last PROCESS_ARGS; } } close(IN); } die "Insufficient data to reconfigure, please do a normal configuration\n"; } elsif (/^386$/) { $processor=386; } elsif (/^fips$/) { $fips=1; } elsif (/^rsaref$/) { # No RSAref support any more since it's not needed. # The check for the option is there so scripts aren't # broken } elsif (/^[-+]/) { if (/^--prefix=(.*)$/) { $prefix=$1; } elsif (/^--libdir=(.*)$/) { $libdir=$1; } elsif (/^--openssldir=(.*)$/) { $openssldir=$1; } elsif (/^--install.prefix=(.*)$/) { $install_prefix=$1; } elsif (/^--with-krb5-(dir|lib|include|flavor)=(.*)$/) { $withargs{"krb5-".$1}=$2; } elsif (/^--with-zlib-lib=(.*)$/) { $withargs{"zlib-lib"}=$1; } elsif (/^--with-zlib-include=(.*)$/) { $withargs{"zlib-include"}="-I$1"; } elsif (/^--with-fipsdir=(.*)$/) { $fipsdir="$1"; } elsif (/^--with-fipslibdir=(.*)$/) { $fipslibdir="$1"; } elsif (/^--with-baseaddr=(.*)$/) { $baseaddr="$1"; } elsif (/^--cross-compile-prefix=(.*)$/) { $cross_compile_prefix=$1; } elsif (/^-[lL](.*)$/ or /^-Wl,/) { $libs.=$_." "; } else # common if (/^[-+]/), just pass down... { $_ =~ s/%([0-9a-f]{1,2})/chr(hex($1))/gei; $flags.=$_." "; } } elsif ($_ =~ /^([^:]+):(.+)$/) { eval "\$table{\$1} = \"$2\""; # allow $xxx constructs in the string $target=$1; } else { die "target already defined - $target (offending arg: $_)\n" if ($target ne ""); $target=$_; } unless ($_ eq $target || /^no-/ || /^disable-/) { # "no-..." follows later after implied disactivations # have been derived. (Don't take this too seroiusly, # we really only write OPTIONS to the Makefile out of # nostalgia.) if ($options eq "") { $options = $_; } else { $options .= " ".$_; } } } } if ($processor eq "386") { $disabled{"sse2"} = "forced"; } if (!defined($withargs{"krb5-flavor"}) || $withargs{"krb5-flavor"} eq "") { $disabled{"krb5"} = "krb5-flavor not specified"; } if (!defined($disabled{"zlib-dynamic"})) { # "zlib-dynamic" was specifically enabled, so enable "zlib" delete $disabled{"zlib"}; } if (defined($disabled{"rijndael"})) { $disabled{"aes"} = "forced"; } if (defined($disabled{"des"})) { $disabled{"mdc2"} = "forced"; } if (defined($disabled{"ec"})) { $disabled{"ecdsa"} = "forced"; $disabled{"ecdh"} = "forced"; } # SSL 2.0 requires MD5 and RSA if (defined($disabled{"md5"}) || defined($disabled{"rsa"})) { $disabled{"ssl2"} = "forced"; } if ($fips && $fipslibdir eq "") { $fipslibdir = $fipsdir . "/lib/"; } # RSAX ENGINE sets default non-FIPS RSA method. if ($fips) { $disabled{"rsax"} = "forced"; } # SSL 3.0 and TLS requires MD5 and SHA and either RSA or DSA+DH if (defined($disabled{"md5"}) || defined($disabled{"sha"}) || (defined($disabled{"rsa"}) && (defined($disabled{"dsa"}) || defined($disabled{"dh"})))) { $disabled{"ssl3"} = "forced"; $disabled{"tls1"} = "forced"; } if (defined($disabled{"ec"}) || defined($disabled{"dsa"}) || defined($disabled{"dh"})) { $disabled{"gost"} = "forced"; } # SRP and HEARTBEATS require TLSEXT if (defined($disabled{"tlsext"})) { $disabled{"srp"} = "forced"; $disabled{"heartbeats"} = "forced"; } if ($target eq "TABLE") { foreach $target (sort keys %table) { print_table_entry($target); } exit 0; } if ($target eq "LIST") { foreach (sort keys %table) { print; print "\n"; } exit 0; } if ($target =~ m/^CygWin32(-.*)$/) { $target = "Cygwin".$1; } print "Configuring for $target\n"; &usage if (!defined($table{$target})); foreach (sort (keys %disabled)) { $options .= " no-$_"; printf " no-%-12s %-10s", $_, "[$disabled{$_}]"; if (/^dso$/) { $no_dso = 1; } elsif (/^threads$/) { $no_threads = 1; } elsif (/^shared$/) { $no_shared = 1; } elsif (/^zlib$/) { $zlib = 0; } elsif (/^static-engine$/) { } elsif (/^zlib-dynamic$/) { } elsif (/^symlinks$/) { $symlink = 0; } elsif (/^sse2$/) { $no_sse2 = 1; } else { my ($ALGO, $algo); ($ALGO = $algo = $_) =~ tr/[\-a-z]/[_A-Z]/; if (/^asm$/ || /^err$/ || /^hw$/ || /^hw-/) { $openssl_other_defines .= "#define OPENSSL_NO_$ALGO\n"; print " OPENSSL_NO_$ALGO"; if (/^err$/) { $flags .= "-DOPENSSL_NO_ERR "; } elsif (/^asm$/) { $no_asm = 1; } } else { $openssl_algorithm_defines .= "#define OPENSSL_NO_$ALGO\n"; print " OPENSSL_NO_$ALGO"; if (/^krb5$/) { $no_krb5 = 1; } else { push @skip, $algo; # fix-up crypto/directory name(s) @skip[$#skip]="whrlpool" if $algo eq "whirlpool"; print " (skip dir)"; $depflags .= " -DOPENSSL_NO_$ALGO"; } } } print "\n"; } my $exp_cflags = ""; foreach (sort @experimental) { my $ALGO; ($ALGO = $_) =~ tr/[a-z]/[A-Z]/; # opensslconf.h will set OPENSSL_NO_... unless OPENSSL_EXPERIMENTAL_... is defined $openssl_experimental_defines .= "#define OPENSSL_NO_$ALGO\n"; $exp_cflags .= " -DOPENSSL_EXPERIMENTAL_$ALGO"; } my $IsMK1MF=scalar grep /^$target$/,@MK1MF_Builds; $exe_ext=".exe" if ($target eq "Cygwin" || $target eq "DJGPP" || $target =~ /^mingw/); $exe_ext=".nlm" if ($target =~ /netware/); $exe_ext=".pm" if ($target =~ /vos/); $openssldir="/usr/local/ssl" if ($openssldir eq "" and $prefix eq ""); $prefix=$openssldir if $prefix eq ""; $default_ranlib= &which("ranlib") or $default_ranlib="true"; $perl=$ENV{'PERL'} or $perl=&which("perl5") or $perl=&which("perl") or $perl="perl"; my $make = $ENV{'MAKE'} || "make"; $cross_compile_prefix=$ENV{'CROSS_COMPILE'} if $cross_compile_prefix eq ""; chop $openssldir if $openssldir =~ /\/$/; chop $prefix if $prefix =~ /.\/$/; $openssldir=$prefix . "/ssl" if $openssldir eq ""; $openssldir=$prefix . "/" . $openssldir if $openssldir !~ /(^\/|^[a-zA-Z]:[\\\/])/; print "IsMK1MF=$IsMK1MF\n"; my @fields = split(/\s*:\s*/,$table{$target} . ":" x 30 , -1); my $cc = $fields[$idx_cc]; # Allow environment CC to override compiler... if($ENV{CC}) { $cc = $ENV{CC}; } my $cflags = $fields[$idx_cflags]; my $unistd = $fields[$idx_unistd]; my $thread_cflag = $fields[$idx_thread_cflag]; my $sys_id = $fields[$idx_sys_id]; my $lflags = $fields[$idx_lflags]; my $bn_ops = $fields[$idx_bn_ops]; my $cpuid_obj = $fields[$idx_cpuid_obj]; my $bn_obj = $fields[$idx_bn_obj]; my $ec_obj = $fields[$idx_ec_obj]; my $des_obj = $fields[$idx_des_obj]; my $aes_obj = $fields[$idx_aes_obj]; my $bf_obj = $fields[$idx_bf_obj]; my $md5_obj = $fields[$idx_md5_obj]; my $sha1_obj = $fields[$idx_sha1_obj]; my $cast_obj = $fields[$idx_cast_obj]; my $rc4_obj = $fields[$idx_rc4_obj]; my $rmd160_obj = $fields[$idx_rmd160_obj]; my $rc5_obj = $fields[$idx_rc5_obj]; my $wp_obj = $fields[$idx_wp_obj]; my $cmll_obj = $fields[$idx_cmll_obj]; my $modes_obj = $fields[$idx_modes_obj]; my $engines_obj = $fields[$idx_engines_obj]; my $perlasm_scheme = $fields[$idx_perlasm_scheme]; my $dso_scheme = $fields[$idx_dso_scheme]; my $shared_target = $fields[$idx_shared_target]; my $shared_cflag = $fields[$idx_shared_cflag]; my $shared_ldflag = $fields[$idx_shared_ldflag]; my $shared_extension = $fields[$idx_shared_extension]; my $ranlib = $ENV{'RANLIB'} || $fields[$idx_ranlib]; my $ar = $ENV{'AR'} || "ar"; my $arflags = $fields[$idx_arflags]; my $windres = $ENV{'RC'} || $ENV{'WINDRES'} || "windres"; my $multilib = $fields[$idx_multilib]; # if $prefix/lib$multilib is not an existing directory, then # assume that it's not searched by linker automatically, in # which case adding $multilib suffix causes more grief than # we're ready to tolerate, so don't... $multilib="" if !-d "$prefix/lib$multilib"; $libdir="lib$multilib" if $libdir eq ""; $cflags = "$cflags$exp_cflags"; # '%' in $lflags is used to split flags to "pre-" and post-flags my ($prelflags,$postlflags)=split('%',$lflags); if (defined($postlflags)) { $lflags=$postlflags; } else { $lflags=$prelflags; undef $prelflags; } if ($target =~ /^mingw/ && `$cc --target-help 2>&1` !~ m/\-mno\-cygwin/m) { $cflags =~ s/\-mno\-cygwin\s*//; $shared_ldflag =~ s/\-mno\-cygwin\s*//; } if ($target =~ /linux.*\-mips/ && !$no_asm && $flags !~ /\-m(ips|arch=)/) { # minimally required architecture flags for assembly modules $cflags="-mips2 $cflags" if ($target =~ /mips32/); $cflags="-mips3 $cflags" if ($target =~ /mips64/); } my $no_shared_warn=0; my $no_user_cflags=0; if ($flags ne "") { $cflags="$flags$cflags"; } else { $no_user_cflags=1; } # Kerberos settings. The flavor must be provided from outside, either through # the script "config" or manually. if (!$no_krb5) { my ($lresolv, $lpath, $lext); if ($withargs{"krb5-flavor"} =~ /^[Hh]eimdal$/) { die "Sorry, Heimdal is currently not supported\n"; } ##### HACK to force use of Heimdal. ##### WARNING: Since we don't really have adequate support for Heimdal, ##### using this will break the build. You'll have to make ##### changes to the source, and if you do, please send ##### patches to openssl-dev@openssl.org if ($withargs{"krb5-flavor"} =~ /^force-[Hh]eimdal$/) { warn "Heimdal isn't really supported. Your build WILL break\n"; warn "If you fix the problems, please send a patch to openssl-dev\@openssl.org\n"; $withargs{"krb5-dir"} = "/usr/heimdal" if $withargs{"krb5-dir"} eq ""; $withargs{"krb5-lib"} = "-L".$withargs{"krb5-dir"}. "/lib -lgssapi -lkrb5 -lcom_err" if $withargs{"krb5-lib"} eq "" && !$IsMK1MF; $cflags="-DKRB5_HEIMDAL $cflags"; } if ($withargs{"krb5-flavor"} =~ /^[Mm][Ii][Tt]/) { $withargs{"krb5-dir"} = "/usr/kerberos" if $withargs{"krb5-dir"} eq ""; $withargs{"krb5-lib"} = "-L".$withargs{"krb5-dir"}. "/lib -lgssapi_krb5 -lkrb5 -lcom_err -lk5crypto" if $withargs{"krb5-lib"} eq "" && !$IsMK1MF; $cflags="-DKRB5_MIT $cflags"; $withargs{"krb5-flavor"} =~ s/^[Mm][Ii][Tt][._-]*//; if ($withargs{"krb5-flavor"} =~ /^1[._-]*[01]/) { $cflags="-DKRB5_MIT_OLD11 $cflags"; } } LRESOLV: foreach $lpath ("/lib", "/usr/lib") { foreach $lext ("a", "so") { $lresolv = "$lpath/libresolv.$lext"; last LRESOLV if (-r "$lresolv"); $lresolv = ""; } } $withargs{"krb5-lib"} .= " -lresolv" if ("$lresolv" ne ""); $withargs{"krb5-include"} = "-I".$withargs{"krb5-dir"}."/include" if $withargs{"krb5-include"} eq "" && $withargs{"krb5-dir"} ne ""; } # The DSO code currently always implements all functions so that no # applications will have to worry about that from a compilation point # of view. However, the "method"s may return zero unless that platform # has support compiled in for them. Currently each method is enabled # by a define "DSO_" ... we translate the "dso_scheme" config # string entry into using the following logic; my $dso_cflags; if (!$no_dso && $dso_scheme ne "") { $dso_scheme =~ tr/[a-z]/[A-Z]/; if ($dso_scheme eq "DLFCN") { $dso_cflags = "-DDSO_DLFCN -DHAVE_DLFCN_H"; } elsif ($dso_scheme eq "DLFCN_NO_H") { $dso_cflags = "-DDSO_DLFCN"; } else { $dso_cflags = "-DDSO_$dso_scheme"; } $cflags = "$dso_cflags $cflags"; } my $thread_cflags; my $thread_defines; if ($thread_cflag ne "(unknown)" && !$no_threads) { # If we know how to do it, support threads by default. $threads = 1; } if ($thread_cflag eq "(unknown)" && $threads) { # If the user asked for "threads", [s]he is also expected to # provide any system-dependent compiler options that are # necessary. if ($no_user_cflags) { print "You asked for multi-threading support, but didn't\n"; print "provide any system-specific compiler options\n"; exit(1); } $thread_cflags="-DOPENSSL_THREADS $cflags" ; $thread_defines .= "#define OPENSSL_THREADS\n"; } else { $thread_cflags="-DOPENSSL_THREADS $thread_cflag $cflags"; $thread_defines .= "#define OPENSSL_THREADS\n"; # my $def; # foreach $def (split ' ',$thread_cflag) # { # if ($def =~ s/^-D// && $def !~ /^_/) # { # $thread_defines .= "#define $def\n"; # } # } } $lflags="$libs$lflags" if ($libs ne ""); if ($no_asm) { $cpuid_obj=$bn_obj=$ec_obj= $des_obj=$aes_obj=$bf_obj=$cast_obj=$rc4_obj=$rc5_obj=$cmll_obj= $modes_obj=$sha1_obj=$md5_obj=$rmd160_obj=$wp_obj=$engines_obj=""; } if (!$no_shared) { $cast_obj=""; # CAST assembler is not PIC } if ($threads) { $cflags=$thread_cflags; $openssl_thread_defines .= $thread_defines; } if ($zlib) { $cflags = "-DZLIB $cflags"; if (defined($disabled{"zlib-dynamic"})) { if (defined($withargs{"zlib-lib"})) { $lflags = "$lflags -L" . $withargs{"zlib-lib"} . " -lz"; } else { $lflags = "$lflags -lz"; } } else { $cflags = "-DZLIB_SHARED $cflags"; } } # You will find shlib_mark1 and shlib_mark2 explained in Makefile.org my $shared_mark = ""; if ($shared_target eq "") { $no_shared_warn = 1 if !$no_shared; $no_shared = 1; } if (!$no_shared) { if ($shared_cflag ne "") { $cflags = "$shared_cflag -DOPENSSL_PIC $cflags"; } } if (!$IsMK1MF) { # add {no-}static-engine to options to allow mkdef.pl to work without extra arguments if ($no_shared) { $openssl_other_defines.="#define OPENSSL_NO_DYNAMIC_ENGINE\n"; $options.=" static-engine"; } else { $openssl_other_defines.="#define OPENSSL_NO_STATIC_ENGINE\n"; $options.=" no-static-engine"; } } $cpuid_obj.=" uplink.o uplink-x86.o" if ($cflags =~ /\-DOPENSSL_USE_APPLINK/); # # Platform fix-ups # if ($target =~ /\-icc$/) # Intel C compiler { my $iccver=0; if (open(FD,"$cc -V 2>&1 |")) { while() { $iccver=$1 if (/Version ([0-9]+)\./); } close(FD); } if ($iccver>=8) { $cflags=~s/\-KPIC/-fPIC/; # Eliminate unnecessary dependency from libirc.a. This is # essential for shared library support, as otherwise # apps/openssl can end up in endless loop upon startup... $cflags.=" -Dmemcpy=__builtin_memcpy -Dmemset=__builtin_memset"; } if ($iccver>=9) { $lflags.=" -i-static"; $lflags=~s/\-no_cpprt/-no-cpprt/; } if ($iccver>=10) { $lflags=~s/\-i\-static/-static-intel/; } if ($iccver>=11) { $cflags.=" -no-intel-extensions"; # disable Cilk $lflags=~s/\-no\-cpprt/-no-cxxlib/; } } # Unlike other OSes (like Solaris, Linux, Tru64, IRIX) BSD run-time # linkers (tested OpenBSD, NetBSD and FreeBSD) "demand" RPATH set on # .so objects. Apparently application RPATH is not global and does # not apply to .so linked with other .so. Problem manifests itself # when libssl.so fails to load libcrypto.so. One can argue that we # should engrave this into Makefile.shared rules or into BSD-* config # lines above. Meanwhile let's try to be cautious and pass -rpath to # linker only when --prefix is not /usr. if ($target =~ /^BSD\-/) { $shared_ldflag.=" -Wl,-rpath,\$\$(LIBRPATH)" if ($prefix !~ m|^/usr[/]*$|); } if ($sys_id ne "") { #$cflags="-DOPENSSL_SYSNAME_$sys_id $cflags"; $openssl_sys_defines="#define OPENSSL_SYSNAME_$sys_id\n"; } if ($ranlib eq "") { $ranlib = $default_ranlib; } #my ($bn1)=split(/\s+/,$bn_obj); #$bn1 = "" unless defined $bn1; #$bn1=$bn_asm unless ($bn1 =~ /\.o$/); #$bn_obj="$bn1"; $cpuid_obj="" if ($processor eq "386"); $bn_obj = $bn_asm unless $bn_obj ne ""; # bn-586 is the only one implementing bn_*_part_words $cflags.=" -DOPENSSL_BN_ASM_PART_WORDS" if ($bn_obj =~ /bn-586/); $cflags.=" -DOPENSSL_IA32_SSE2" if (!$no_sse2 && $bn_obj =~ /86/); $cflags.=" -DOPENSSL_BN_ASM_MONT" if ($bn_obj =~ /-mont/); $cflags.=" -DOPENSSL_BN_ASM_MONT5" if ($bn_obj =~ /-mont5/); $cflags.=" -DOPENSSL_BN_ASM_GF2m" if ($bn_obj =~ /-gf2m/); if ($fips) { $openssl_other_defines.="#define OPENSSL_FIPS\n"; $cflags .= " -I\$(FIPSDIR)/include"; } $cpuid_obj="mem_clr.o" unless ($cpuid_obj =~ /\.o$/); $des_obj=$des_enc unless ($des_obj =~ /\.o$/); $bf_obj=$bf_enc unless ($bf_obj =~ /\.o$/); $cast_obj=$cast_enc unless ($cast_obj =~ /\.o$/); $rc5_obj=$rc5_enc unless ($rc5_obj =~ /\.o$/); if ($rc4_obj =~ /\.o$/) { $cflags.=" -DRC4_ASM"; } else { $rc4_obj=$rc4_enc; } if ($sha1_obj =~ /\.o$/) { # $sha1_obj=$sha1_enc; $cflags.=" -DSHA1_ASM" if ($sha1_obj =~ /sx86/ || $sha1_obj =~ /sha1/); $cflags.=" -DSHA256_ASM" if ($sha1_obj =~ /sha256/); $cflags.=" -DSHA512_ASM" if ($sha1_obj =~ /sha512/); if ($sha1_obj =~ /sse2/) { if ($no_sse2) { $sha1_obj =~ s/\S*sse2\S+//; } elsif ($cflags !~ /OPENSSL_IA32_SSE2/) { $cflags.=" -DOPENSSL_IA32_SSE2"; } } } if ($md5_obj =~ /\.o$/) { # $md5_obj=$md5_enc; $cflags.=" -DMD5_ASM"; } if ($rmd160_obj =~ /\.o$/) { # $rmd160_obj=$rmd160_enc; $cflags.=" -DRMD160_ASM"; } if ($aes_obj =~ /\.o$/) { $cflags.=" -DAES_ASM" if ($aes_obj =~ m/\baes\-/);; # aes-ctr.o is not a real file, only indication that assembler # module implements AES_ctr32_encrypt... $cflags.=" -DAES_CTR_ASM" if ($aes_obj =~ s/\s*aes\-ctr\.o//); # aes-xts.o indicates presense of AES_xts_[en|de]crypt... $cflags.=" -DAES_XTS_ASM" if ($aes_obj =~ s/\s*aes\-xts\.o//); $aes_obj =~ s/\s*(vpaes|aesni)\-x86\.o//g if ($no_sse2); $cflags.=" -DVPAES_ASM" if ($aes_obj =~ m/vpaes/); $cflags.=" -DBSAES_ASM" if ($aes_obj =~ m/bsaes/); } else { $aes_obj=$aes_enc; } $wp_obj="" if ($wp_obj =~ /mmx/ && $processor eq "386"); if ($wp_obj =~ /\.o$/ && !$disabled{"whirlpool"}) { $cflags.=" -DWHIRLPOOL_ASM"; } else { $wp_obj="wp_block.o"; } $cmll_obj=$cmll_enc unless ($cmll_obj =~ /.o$/); if ($modes_obj =~ /ghash\-/) { $cflags.=" -DGHASH_ASM"; } if ($ec_obj =~ /ecp_nistz256/) { $cflags.=" -DECP_NISTZ256_ASM"; } # "Stringify" the C flags string. This permits it to be made part of a string # and works as well on command lines. $cflags =~ s/([\\\"])/\\\1/g; my $version = "unknown"; my $version_num = "unknown"; my $major = "unknown"; my $minor = "unknown"; my $shlib_version_number = "unknown"; my $shlib_version_history = "unknown"; my $shlib_major = "unknown"; my $shlib_minor = "unknown"; open(IN,') { $version=$1 if /OPENSSL.VERSION.TEXT.*OpenSSL (\S+) /; $version_num=$1 if /OPENSSL.VERSION.NUMBER.*0x(\S+)/; $shlib_version_number=$1 if /SHLIB_VERSION_NUMBER *"([^"]+)"/; $shlib_version_history=$1 if /SHLIB_VERSION_HISTORY *"([^"]*)"/; } close(IN); if ($shlib_version_history ne "") { $shlib_version_history .= ":"; } if ($version =~ /(^[0-9]*)\.([0-9\.]*)/) { $major=$1; $minor=$2; } if ($shlib_version_number =~ /(^[0-9]*)\.([0-9\.]*)/) { $shlib_major=$1; $shlib_minor=$2; } my $ecc = $cc; $ecc = "clang" if `$cc --version 2>&1` =~ /clang/; if ($strict_warnings) { my $wopt; die "ERROR --strict-warnings requires gcc or clang" unless ($ecc =~ /gcc$/ or $ecc =~ /clang$/); foreach $wopt (split /\s+/, $gcc_devteam_warn) { $cflags .= " $wopt" unless ($cflags =~ /(^|\s)$wopt(\s|$)/) } if ($ecc eq "clang") { foreach $wopt (split /\s+/, $clang_devteam_warn) { $cflags .= " $wopt" unless ($cflags =~ /(^|\s)$wopt(\s|$)/) } } } open(IN,'$Makefile.new") || die "unable to create $Makefile.new:$!\n"; print OUT "### Generated automatically from Makefile.org by Configure.\n\n"; my $sdirs=0; while () { chomp; $sdirs = 1 if /^SDIRS=/; if ($sdirs) { my $dir; foreach $dir (@skip) { s/(\s)$dir /$1/; s/\s$dir$//; } } $sdirs = 0 unless /\\$/; s/engines // if (/^DIRS=/ && $disabled{"engine"}); s/ccgost// if (/^ENGDIRS=/ && $disabled{"gost"}); s/^VERSION=.*/VERSION=$version/; s/^MAJOR=.*/MAJOR=$major/; s/^MINOR=.*/MINOR=$minor/; s/^SHLIB_VERSION_NUMBER=.*/SHLIB_VERSION_NUMBER=$shlib_version_number/; s/^SHLIB_VERSION_HISTORY=.*/SHLIB_VERSION_HISTORY=$shlib_version_history/; s/^SHLIB_MAJOR=.*/SHLIB_MAJOR=$shlib_major/; s/^SHLIB_MINOR=.*/SHLIB_MINOR=$shlib_minor/; s/^SHLIB_EXT=.*/SHLIB_EXT=$shared_extension/; s/^INSTALLTOP=.*$/INSTALLTOP=$prefix/; s/^MULTILIB=.*$/MULTILIB=$multilib/; s/^OPENSSLDIR=.*$/OPENSSLDIR=$openssldir/; s/^LIBDIR=.*$/LIBDIR=$libdir/; s/^INSTALL_PREFIX=.*$/INSTALL_PREFIX=$install_prefix/; s/^PLATFORM=.*$/PLATFORM=$target/; s/^OPTIONS=.*$/OPTIONS=$options/; s/^CONFIGURE_ARGS=.*$/CONFIGURE_ARGS=$argvstring/; if ($cross_compile_prefix) { s/^CC=.*$/CROSS_COMPILE= $cross_compile_prefix\nCC= \$\(CROSS_COMPILE\)$cc/; s/^AR=\s*/AR= \$\(CROSS_COMPILE\)/; s/^NM=\s*/NM= \$\(CROSS_COMPILE\)/; s/^RANLIB=\s*/RANLIB= \$\(CROSS_COMPILE\)/; s/^RC=\s*/RC= \$\(CROSS_COMPILE\)/; s/^MAKEDEPPROG=.*$/MAKEDEPPROG= \$\(CROSS_COMPILE\)$cc/ if $cc eq "gcc"; } else { s/^CC=.*$/CC= $cc/; s/^AR=\s*ar/AR= $ar/; s/^RANLIB=.*/RANLIB= $ranlib/; s/^RC=.*/RC= $windres/; s/^MAKEDEPPROG=.*$/MAKEDEPPROG= $cc/ if $cc eq "gcc"; s/^MAKEDEPPROG=.*$/MAKEDEPPROG= $cc/ if $ecc eq "gcc" || $ecc eq "clang"; } s/^CFLAG=.*$/CFLAG= $cflags/; s/^DEPFLAG=.*$/DEPFLAG=$depflags/; s/^PEX_LIBS=.*$/PEX_LIBS= $prelflags/; s/^EX_LIBS=.*$/EX_LIBS= $lflags/; s/^EXE_EXT=.*$/EXE_EXT= $exe_ext/; s/^CPUID_OBJ=.*$/CPUID_OBJ= $cpuid_obj/; s/^BN_ASM=.*$/BN_ASM= $bn_obj/; s/^EC_ASM=.*$/EC_ASM= $ec_obj/; s/^DES_ENC=.*$/DES_ENC= $des_obj/; s/^AES_ENC=.*$/AES_ENC= $aes_obj/; s/^BF_ENC=.*$/BF_ENC= $bf_obj/; s/^CAST_ENC=.*$/CAST_ENC= $cast_obj/; s/^RC4_ENC=.*$/RC4_ENC= $rc4_obj/; s/^RC5_ENC=.*$/RC5_ENC= $rc5_obj/; s/^MD5_ASM_OBJ=.*$/MD5_ASM_OBJ= $md5_obj/; s/^SHA1_ASM_OBJ=.*$/SHA1_ASM_OBJ= $sha1_obj/; s/^RMD160_ASM_OBJ=.*$/RMD160_ASM_OBJ= $rmd160_obj/; s/^WP_ASM_OBJ=.*$/WP_ASM_OBJ= $wp_obj/; s/^CMLL_ENC=.*$/CMLL_ENC= $cmll_obj/; s/^MODES_ASM_OBJ.=*$/MODES_ASM_OBJ= $modes_obj/; s/^ENGINES_ASM_OBJ.=*$/ENGINES_ASM_OBJ= $engines_obj/; s/^PERLASM_SCHEME=.*$/PERLASM_SCHEME= $perlasm_scheme/; s/^PROCESSOR=.*/PROCESSOR= $processor/; s/^ARFLAGS=.*/ARFLAGS= $arflags/; s/^PERL=.*/PERL= $perl/; s/^KRB5_INCLUDES=.*/KRB5_INCLUDES=$withargs{"krb5-include"}/; s/^LIBKRB5=.*/LIBKRB5=$withargs{"krb5-lib"}/; s/^LIBZLIB=.*/LIBZLIB=$withargs{"zlib-lib"}/; s/^ZLIB_INCLUDE=.*/ZLIB_INCLUDE=$withargs{"zlib-include"}/; s/^FIPSDIR=.*/FIPSDIR=$fipsdir/; s/^FIPSLIBDIR=.*/FIPSLIBDIR=$fipslibdir/; s/^FIPSCANLIB=.*/FIPSCANLIB=libcrypto/ if $fips; s/^BASEADDR=.*/BASEADDR=$baseaddr/; s/^SHLIB_TARGET=.*/SHLIB_TARGET=$shared_target/; s/^SHLIB_MARK=.*/SHLIB_MARK=$shared_mark/; s/^SHARED_LIBS=.*/SHARED_LIBS=\$(SHARED_CRYPTO) \$(SHARED_SSL)/ if (!$no_shared); if ($shared_extension ne "" && $shared_extension =~ /^\.s([ol])\.[^\.]*$/) { my $sotmp = $1; s/^SHARED_LIBS_LINK_EXTS=.*/SHARED_LIBS_LINK_EXTS=.s$sotmp/; } elsif ($shared_extension ne "" && $shared_extension =~ /^\.[^\.]*\.dylib$/) { s/^SHARED_LIBS_LINK_EXTS=.*/SHARED_LIBS_LINK_EXTS=.dylib/; } elsif ($shared_extension ne "" && $shared_extension =~ /^\.s([ol])\.[^\.]*\.[^\.]*$/) { my $sotmp = $1; s/^SHARED_LIBS_LINK_EXTS=.*/SHARED_LIBS_LINK_EXTS=.s$sotmp.\$(SHLIB_MAJOR) .s$sotmp/; } elsif ($shared_extension ne "" && $shared_extension =~ /^\.[^\.]*\.[^\.]*\.dylib$/) { s/^SHARED_LIBS_LINK_EXTS=.*/SHARED_LIBS_LINK_EXTS=.\$(SHLIB_MAJOR).dylib .dylib/; } s/^SHARED_LDFLAGS=.*/SHARED_LDFLAGS=$shared_ldflag/; print OUT $_."\n"; } close(IN); close(OUT); if ((compare($Makefile, "$Makefile.new")) or file_newer('Configure', $Makefile) or file_newer('config', $Makefile) or file_newer('Makefile.org', $Makefile)) { rename($Makefile,"$Makefile.bak") || die "unable to rename $Makefile\n" if -e $Makefile; rename("$Makefile.new",$Makefile) || die "unable to rename $Makefile.new\n"; } else { unlink("$Makefile.new"); } print "CC =$cc\n"; print "CFLAG =$cflags\n"; print "EX_LIBS =$lflags\n"; print "CPUID_OBJ =$cpuid_obj\n"; print "BN_ASM =$bn_obj\n"; print "EC_ASM =$ec_obj\n"; print "DES_ENC =$des_obj\n"; print "AES_ENC =$aes_obj\n"; print "BF_ENC =$bf_obj\n"; print "CAST_ENC =$cast_obj\n"; print "RC4_ENC =$rc4_obj\n"; print "RC5_ENC =$rc5_obj\n"; print "MD5_OBJ_ASM =$md5_obj\n"; print "SHA1_OBJ_ASM =$sha1_obj\n"; print "RMD160_OBJ_ASM=$rmd160_obj\n"; print "CMLL_ENC =$cmll_obj\n"; print "MODES_OBJ =$modes_obj\n"; print "ENGINES_OBJ =$engines_obj\n"; print "PROCESSOR =$processor\n"; print "RANLIB =$ranlib\n"; print "ARFLAGS =$arflags\n"; print "PERL =$perl\n"; print "KRB5_INCLUDES =",$withargs{"krb5-include"},"\n" if $withargs{"krb5-include"} ne ""; my $des_ptr=0; my $des_risc1=0; my $des_risc2=0; my $des_unroll=0; my $bn_ll=0; my $def_int=2; my $rc4_int=$def_int; my $md2_int=$def_int; my $idea_int=$def_int; my $rc2_int=$def_int; my $rc4_idx=0; my $rc4_chunk=0; my $bf_ptr=0; my @type=("char","short","int","long"); my ($b64l,$b64,$b32,$b16,$b8)=(0,0,1,0,0); my $export_var_as_fn=0; my $des_int; foreach (sort split(/\s+/,$bn_ops)) { $des_ptr=1 if /DES_PTR/; $des_risc1=1 if /DES_RISC1/; $des_risc2=1 if /DES_RISC2/; $des_unroll=1 if /DES_UNROLL/; $des_int=1 if /DES_INT/; $bn_ll=1 if /BN_LLONG/; $rc4_int=0 if /RC4_CHAR/; $rc4_int=3 if /RC4_LONG/; $rc4_idx=1 if /RC4_INDEX/; $rc4_chunk=1 if /RC4_CHUNK/; $rc4_chunk=2 if /RC4_CHUNK_LL/; $md2_int=0 if /MD2_CHAR/; $md2_int=3 if /MD2_LONG/; $idea_int=1 if /IDEA_SHORT/; $idea_int=3 if /IDEA_LONG/; $rc2_int=1 if /RC2_SHORT/; $rc2_int=3 if /RC2_LONG/; $bf_ptr=1 if $_ eq "BF_PTR"; $bf_ptr=2 if $_ eq "BF_PTR2"; ($b64l,$b64,$b32,$b16,$b8)=(0,1,0,0,0) if /SIXTY_FOUR_BIT/; ($b64l,$b64,$b32,$b16,$b8)=(1,0,0,0,0) if /SIXTY_FOUR_BIT_LONG/; ($b64l,$b64,$b32,$b16,$b8)=(0,0,1,0,0) if /THIRTY_TWO_BIT/; ($b64l,$b64,$b32,$b16,$b8)=(0,0,0,1,0) if /SIXTEEN_BIT/; ($b64l,$b64,$b32,$b16,$b8)=(0,0,0,0,1) if /EIGHT_BIT/; $export_var_as_fn=1 if /EXPORT_VAR_AS_FN/; } open(IN,'crypto/opensslconf.h.new') || die "unable to create crypto/opensslconf.h.new:$!\n"; print OUT "/* opensslconf.h */\n"; print OUT "/* WARNING: Generated automatically from opensslconf.h.in by Configure. */\n\n"; print OUT "#ifdef __cplusplus\n"; print OUT "extern \"C\" {\n"; print OUT "#endif\n"; print OUT "/* OpenSSL was configured with the following options: */\n"; my $openssl_algorithm_defines_trans = $openssl_algorithm_defines; $openssl_experimental_defines =~ s/^\s*#\s*define\s+OPENSSL_NO_(.*)/#ifndef OPENSSL_EXPERIMENTAL_$1\n# ifndef OPENSSL_NO_$1\n# define OPENSSL_NO_$1\n# endif\n#endif/mg; $openssl_algorithm_defines_trans =~ s/^\s*#\s*define\s+OPENSSL_(.*)/# if defined(OPENSSL_$1) \&\& !defined($1)\n# define $1\n# endif/mg; $openssl_algorithm_defines =~ s/^\s*#\s*define\s+(.*)/#ifndef $1\n# define $1\n#endif/mg; $openssl_algorithm_defines = " /* no ciphers excluded */\n" if $openssl_algorithm_defines eq ""; $openssl_thread_defines =~ s/^\s*#\s*define\s+(.*)/#ifndef $1\n# define $1\n#endif/mg; $openssl_sys_defines =~ s/^\s*#\s*define\s+(.*)/#ifndef $1\n# define $1\n#endif/mg; $openssl_other_defines =~ s/^\s*#\s*define\s+(.*)/#ifndef $1\n# define $1\n#endif/mg; print OUT $openssl_sys_defines; print OUT "#ifndef OPENSSL_DOING_MAKEDEPEND\n\n"; print OUT $openssl_experimental_defines; print OUT "\n"; print OUT $openssl_algorithm_defines; print OUT "\n#endif /* OPENSSL_DOING_MAKEDEPEND */\n\n"; print OUT $openssl_thread_defines; print OUT $openssl_other_defines,"\n"; print OUT "/* The OPENSSL_NO_* macros are also defined as NO_* if the application\n"; print OUT " asks for it. This is a transient feature that is provided for those\n"; print OUT " who haven't had the time to do the appropriate changes in their\n"; print OUT " applications. */\n"; print OUT "#ifdef OPENSSL_ALGORITHM_DEFINES\n"; print OUT $openssl_algorithm_defines_trans; print OUT "#endif\n\n"; print OUT "#define OPENSSL_CPUID_OBJ\n\n" if ($cpuid_obj ne "mem_clr.o"); while () { if (/^#define\s+OPENSSLDIR/) { my $foo = $openssldir; $foo =~ s/\\/\\\\/g; print OUT "#define OPENSSLDIR \"$foo\"\n"; } elsif (/^#define\s+ENGINESDIR/) { my $foo = "$prefix/$libdir/engines"; $foo =~ s/\\/\\\\/g; print OUT "#define ENGINESDIR \"$foo\"\n"; } elsif (/^#((define)|(undef))\s+OPENSSL_EXPORT_VAR_AS_FUNCTION/) { printf OUT "#undef OPENSSL_EXPORT_VAR_AS_FUNCTION\n" if $export_var_as_fn; printf OUT "#%s OPENSSL_EXPORT_VAR_AS_FUNCTION\n", ($export_var_as_fn)?"define":"undef"; } elsif (/^#define\s+OPENSSL_UNISTD/) { $unistd = "" if $unistd eq ""; print OUT "#define OPENSSL_UNISTD $unistd\n"; } elsif (/^#((define)|(undef))\s+SIXTY_FOUR_BIT_LONG/) { printf OUT "#%s SIXTY_FOUR_BIT_LONG\n",($b64l)?"define":"undef"; } elsif (/^#((define)|(undef))\s+SIXTY_FOUR_BIT/) { printf OUT "#%s SIXTY_FOUR_BIT\n",($b64)?"define":"undef"; } elsif (/^#((define)|(undef))\s+THIRTY_TWO_BIT/) { printf OUT "#%s THIRTY_TWO_BIT\n",($b32)?"define":"undef"; } elsif (/^#((define)|(undef))\s+SIXTEEN_BIT/) { printf OUT "#%s SIXTEEN_BIT\n",($b16)?"define":"undef"; } elsif (/^#((define)|(undef))\s+EIGHT_BIT/) { printf OUT "#%s EIGHT_BIT\n",($b8)?"define":"undef"; } elsif (/^#((define)|(undef))\s+BN_LLONG\s*$/) { printf OUT "#%s BN_LLONG\n",($bn_ll)?"define":"undef"; } elsif (/^\#define\s+DES_LONG\s+.*/) { printf OUT "#define DES_LONG unsigned %s\n", ($des_int)?'int':'long'; } elsif (/^\#(define|undef)\s+DES_PTR/) { printf OUT "#%s DES_PTR\n",($des_ptr)?'define':'undef'; } elsif (/^\#(define|undef)\s+DES_RISC1/) { printf OUT "#%s DES_RISC1\n",($des_risc1)?'define':'undef'; } elsif (/^\#(define|undef)\s+DES_RISC2/) { printf OUT "#%s DES_RISC2\n",($des_risc2)?'define':'undef'; } elsif (/^\#(define|undef)\s+DES_UNROLL/) { printf OUT "#%s DES_UNROLL\n",($des_unroll)?'define':'undef'; } elsif (/^#define\s+RC4_INT\s/) { printf OUT "#define RC4_INT unsigned %s\n",$type[$rc4_int]; } elsif (/^#undef\s+RC4_CHUNK/) { printf OUT "#undef RC4_CHUNK\n" if $rc4_chunk==0; printf OUT "#define RC4_CHUNK unsigned long\n" if $rc4_chunk==1; printf OUT "#define RC4_CHUNK unsigned long long\n" if $rc4_chunk==2; } elsif (/^#((define)|(undef))\s+RC4_INDEX/) { printf OUT "#%s RC4_INDEX\n",($rc4_idx)?"define":"undef"; } elsif (/^#(define|undef)\s+I386_ONLY/) { printf OUT "#%s I386_ONLY\n", ($processor eq "386")? "define":"undef"; } elsif (/^#define\s+MD2_INT\s/) { printf OUT "#define MD2_INT unsigned %s\n",$type[$md2_int]; } elsif (/^#define\s+IDEA_INT\s/) {printf OUT "#define IDEA_INT unsigned %s\n",$type[$idea_int];} elsif (/^#define\s+RC2_INT\s/) {printf OUT "#define RC2_INT unsigned %s\n",$type[$rc2_int];} elsif (/^#(define|undef)\s+BF_PTR/) { printf OUT "#undef BF_PTR\n" if $bf_ptr == 0; printf OUT "#define BF_PTR\n" if $bf_ptr == 1; printf OUT "#define BF_PTR2\n" if $bf_ptr == 2; } else { print OUT $_; } } close(IN); print OUT "#ifdef __cplusplus\n"; print OUT "}\n"; print OUT "#endif\n"; close(OUT); if (compare("crypto/opensslconf.h.new","crypto/opensslconf.h")) { rename("crypto/opensslconf.h","crypto/opensslconf.h.bak") || die "unable to rename crypto/opensslconf.h\n" if -e "crypto/opensslconf.h"; rename("crypto/opensslconf.h.new","crypto/opensslconf.h") || die "unable to rename crypto/opensslconf.h.new\n"; } else { unlink("crypto/opensslconf.h.new"); } # Fix the date print "SIXTY_FOUR_BIT_LONG mode\n" if $b64l; print "SIXTY_FOUR_BIT mode\n" if $b64; print "THIRTY_TWO_BIT mode\n" if $b32; print "SIXTEEN_BIT mode\n" if $b16; print "EIGHT_BIT mode\n" if $b8; print "DES_PTR used\n" if $des_ptr; print "DES_RISC1 used\n" if $des_risc1; print "DES_RISC2 used\n" if $des_risc2; print "DES_UNROLL used\n" if $des_unroll; print "DES_INT used\n" if $des_int; print "BN_LLONG mode\n" if $bn_ll; print "RC4 uses u$type[$rc4_int]\n" if $rc4_int != $def_int; print "RC4_INDEX mode\n" if $rc4_idx; print "RC4_CHUNK is undefined\n" if $rc4_chunk==0; print "RC4_CHUNK is unsigned long\n" if $rc4_chunk==1; print "RC4_CHUNK is unsigned long long\n" if $rc4_chunk==2; print "MD2 uses u$type[$md2_int]\n" if $md2_int != $def_int; print "IDEA uses u$type[$idea_int]\n" if $idea_int != $def_int; print "RC2 uses u$type[$rc2_int]\n" if $rc2_int != $def_int; print "BF_PTR used\n" if $bf_ptr == 1; print "BF_PTR2 used\n" if $bf_ptr == 2; if($IsMK1MF) { open (OUT,">crypto/buildinf.h") || die "Can't open buildinf.h"; printf OUT <ms/version32.rc") || die "Can't open ms/version32.rc"; print OUT < LANGUAGE 0x09,0x01 1 VERSIONINFO FILEVERSION $v1,$v2,$v3,$v4 PRODUCTVERSION $v1,$v2,$v3,$v4 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x01L #else FILEFLAGS 0x00L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_DLL FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN // Required: VALUE "CompanyName", "The OpenSSL Project, http://www.openssl.org/\\0" VALUE "FileDescription", "OpenSSL Shared Library\\0" VALUE "FileVersion", "$version\\0" #if defined(CRYPTO) VALUE "InternalName", "libeay32\\0" VALUE "OriginalFilename", "libeay32.dll\\0" #elif defined(SSL) VALUE "InternalName", "ssleay32\\0" VALUE "OriginalFilename", "ssleay32.dll\\0" #endif VALUE "ProductName", "The OpenSSL Toolkit\\0" VALUE "ProductVersion", "$version\\0" // Optional: //VALUE "Comments", "\\0" VALUE "LegalCopyright", "Copyright © 1998-2005 The OpenSSL Project. Copyright © 1995-1998 Eric A. Young, Tim J. Hudson. All rights reserved.\\0" //VALUE "LegalTrademarks", "\\0" //VALUE "PrivateBuild", "\\0" //VALUE "SpecialBuild", "\\0" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 0x4b0 END END EOF close(OUT); } print < 78) { print STDERR "\n"; $k=length($i); } print STDERR $i . " "; } foreach $i (sort keys %table) { next if $i !~ /^debug/; $k += length($i) + 1; if ($k > 78) { print STDERR "\n"; $k=length($i); } print STDERR $i . " "; } print STDERR "\n\nNOTE: If in doubt, on Unix-ish systems use './config'.\n"; exit(1); } sub which { my($name)=@_; my $path; foreach $path (split /:/, $ENV{PATH}) { if (-f "$path/$name$exe_ext" and -x _) { return "$path/$name$exe_ext" unless ($name eq "perl" and system("$path/$name$exe_ext -e " . '\'exit($]<5.0);\'')); } } } sub dofile { my $f; my $p; my %m; my @a; my $k; my $ff; ($f,$p,%m)=@_; open(IN,"<$f.in") || open(IN,"<$f") || die "unable to open $f:$!\n"; @a=; close(IN); foreach $k (keys %m) { grep(/$k/ && ($_=sprintf($m{$k}."\n",$p)),@a); } open(OUT,">$f.new") || die "unable to open $f.new:$!\n"; print OUT @a; close(OUT); rename($f,"$f.bak") || die "unable to rename $f\n" if -e $f; rename("$f.new",$f) || die "unable to rename $f.new\n"; } sub print_table_entry { my $target = shift; my ($cc, $cflags, $unistd, $thread_cflag, $sys_id, $lflags, $bn_ops, $cpuid_obj, $bn_obj, $ec_obj, $des_obj, $aes_obj, $bf_obj, $md5_obj, $sha1_obj, $cast_obj, $rc4_obj, $rmd160_obj, $rc5_obj, $wp_obj, $cmll_obj, $modes_obj, $engines_obj, $perlasm_scheme, $dso_scheme, $shared_target, $shared_cflag, $shared_ldflag, $shared_extension, $ranlib, $arflags, $multilib)= split(/\s*:\s*/,$table{$target} . ":" x 30 , -1); print < (stat($file2))[9] } Index: vendor-crypto/openssl/dist/FREEBSD-Xlist =================================================================== --- vendor-crypto/openssl/dist/FREEBSD-Xlist (revision 318896) +++ vendor-crypto/openssl/dist/FREEBSD-Xlist (revision 318897) @@ -1,82 +1,84 @@ openssl-*/*.bak openssl-*/*.com openssl-*/*.doxy openssl-*/*.mak openssl-*/*.save openssl-*/*.spec openssl-*/*/*.bat openssl-*/*/*.com openssl-*/*/*.save openssl-*/*/*/*.bat openssl-*/*/*/*.com openssl-*/*/*/*.save openssl-*/Git* openssl-*/INSTALL.DJGPP openssl-*/INSTALL.MacOS openssl-*/INSTALL.NW openssl-*/INSTALL.OS2 openssl-*/INSTALL.VMS openssl-*/INSTALL.W32 openssl-*/INSTALL.W64 openssl-*/INSTALL.WCE openssl-*/MacOS openssl-*/Netware openssl-*/VMS openssl-*/apps/demoCA openssl-*/apps/demoSRP openssl-*/apps/md4.c openssl-*/apps/openssl-vms.cnf openssl-*/apps/vms_* openssl-*/apps/winrand.c openssl-*/bugs openssl-*/certs/demo openssl-*/crypto/*/*.cpp openssl-*/crypto/*/*/*.cpp openssl-*/crypto/*/asm/*-alpha.pl openssl-*/crypto/*/asm/alpha-*.pl openssl-*/crypto/LPdir_nyi.c openssl-*/crypto/LPdir_vms.c openssl-*/crypto/LPdir_win.c openssl-*/crypto/LPdir_win32.c openssl-*/crypto/LPdir_wince.c openssl-*/crypto/alphacpuid.pl openssl-*/crypto/bn/asm/vms.mar openssl-*/crypto/bn/vms-helper.c openssl-*/crypto/buildinf.h openssl-*/crypto/des/t openssl-*/crypto/des/times openssl-*/crypto/dso/dso_vms.c openssl-*/crypto/dso/dso_win.c openssl-*/crypto/dso/dso_win32.c openssl-*/crypto/dso/dso_wince.c openssl-*/crypto/err/openssl.ec openssl-*/crypto/openssl/demos openssl-*/crypto/rand/rand_nw.c openssl-*/crypto/rand/rand_os2.c openssl-*/crypto/rand/rand_vms.c openssl-*/crypto/rand/rand_win.c openssl-*/crypto/threads/solaris.sh openssl-*/demos +openssl-*/doc-nits openssl-*/engines/*.ec openssl-*/engines/*.opt openssl-*/engines/ccgost/e_gost_err.proto +openssl-*/fuzz openssl-*/include openssl-*/ms openssl-*/op openssl-*/os2 openssl-*/perl openssl-*/shlib/Makefile.hpux10-cc openssl-*/shlib/hpux10-cc.sh openssl-*/shlib/irix.sh openssl-*/shlib/sco5-shared-gcc.sh openssl-*/shlib/sco5-shared-installed openssl-*/shlib/sco5-shared.sh openssl-*/shlib/solaris-sc4.sh openssl-*/shlib/solaris.sh openssl-*/shlib/sun.sh openssl-*/shlib/svr5-shared-gcc.sh openssl-*/shlib/svr5-shared-installed openssl-*/shlib/svr5-shared.sh openssl-*/test openssl-*/times openssl-*/tools Index: vendor-crypto/openssl/dist/FREEBSD-upgrade =================================================================== --- vendor-crypto/openssl/dist/FREEBSD-upgrade (revision 318896) +++ vendor-crypto/openssl/dist/FREEBSD-upgrade (revision 318897) @@ -1,83 +1,83 @@ This contains various notes used to import a new OpenSSL version into the FreeBSD base system. It is not expected to be complete but just to contain some hints for imports. Note that this doesn't actually deal with getting OpenSSL to compile... XXX This file currently partly contain CVS and SVN instructions. First, read http://wiki.freebsd.org/SubversionPrimer/VendorImports # Xlist setenv XLIST /FreeBSD/work/openssl/svn-FREEBSD-files/FREEBSD-Xlist setenv FSVN "svn+ssh://repo.freebsd.org/base" -setenv OSSLVER 1.0.2j -# OSSLTAG format: v1_0_2j +setenv OSSLVER 1.0.2l +# OSSLTAG format: v1_0_2l ###setenv OSSLTAG v`echo ${OSSLVER} | tr . _` cd /FreeBSD/work/openssl/merge fetch http://www.openssl.org/source/openssl-${OSSLVER}.tar.gz \ http://www.openssl.org/source/openssl-${OSSLVER}.tar.gz.asc gpg --verify openssl-${OSSLVER}.tar.gz.asc openssl-${OSSLVER}.tar.gz svn co $FSVN/vendor-crypto/openssl/dist dist tar -x -X $XLIST -f openssl-${OSSLVER}.tar.gz cd dist svn list -R | egrep -v -e '/$' -e '^FREEBSD-(Xlist|upgrade)$' | sort >../old cd ../openssl-${OSSLVER} find . -type f -or -type l | cut -c 3- | sort >../new cd .. # See that files to remove makes sense comm -23 old new # See that files to add makes sense comm -13 old new tar -cf - -C openssl-${OSSLVER} . | tar -xf - -C dist cd dist comm -23 ../old ../new | xargs svn rm # Make sure to remove empty directories comm -13 ../old ../new | xargs svn --parents add svn stat svn ci svn cp ^/vendor-crypto/openssl/dist ^/vendor-crypto/openssl/$OSSLVER # Merge to head mkdir ../head cd ../head svn co $FSVN/head/crypto/openssl crypto/openssl svn merge ^/vendor-crypto/openssl/dist crypto/openssl # Resolve conflicts manually svn co $FSVN/head/secure/lib/libcrypto secure/lib/libcrypto svn co $FSVN/head/secure/lib/libssl secure/lib/libssl svn co $FSVN/head/secure/usr.bin/openssl secure/usr.bin/openssl cd secure/lib/libcrypto # Update version number and release date in Makefile.inc # Update all opensslconf-${MACHINE_CPUARCH}.h # Regen assembly files if necessary make -f Makefile.asm all mv *.[Ss] ${MACHINE_CPUARCH} make -f Makefile.asm clean # Regen manual pages make man-makefile-update && make man-update cd ../libssl make man-makefile-update && make man-update cd ../../usr.bin/openssl make man-makefile-update && make man-update cd ../../.. # Commit! svn ci crypto/openssl secure/lib/libcrypto secure/lib/libssl secure/usr.bin/openssl -- simon@, jkim@ $FreeBSD$ Index: vendor-crypto/openssl/dist/LICENSE =================================================================== --- vendor-crypto/openssl/dist/LICENSE (revision 318896) +++ vendor-crypto/openssl/dist/LICENSE (revision 318897) @@ -1,127 +1,127 @@ LICENSE ISSUES ============== - The OpenSSL toolkit stays under a dual license, i.e. both the conditions of + The OpenSSL toolkit stays under a double license, i.e. both the conditions of the OpenSSL License and the original SSLeay license apply to the toolkit. See below for the actual license texts. Actually both licenses are BSD-style Open Source licenses. In case of any license issues related to OpenSSL please contact openssl-core@openssl.org. OpenSSL License --------------- /* ==================================================================== - * Copyright (c) 1998-2016 The OpenSSL Project. All rights reserved. + * Copyright (c) 1998-2017 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ Original SSLeay License ----------------------- /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ Index: vendor-crypto/openssl/dist/Makefile =================================================================== --- vendor-crypto/openssl/dist/Makefile (revision 318896) +++ vendor-crypto/openssl/dist/Makefile (revision 318897) @@ -1,684 +1,692 @@ ### Generated automatically from Makefile.org by Configure. ## ## Makefile for OpenSSL ## -VERSION=1.0.2k +VERSION=1.0.2l MAJOR=1 MINOR=0.2 SHLIB_VERSION_NUMBER=1.0.0 SHLIB_VERSION_HISTORY= SHLIB_MAJOR=1 SHLIB_MINOR=0.0 SHLIB_EXT= PLATFORM=dist OPTIONS= no-ec_nistp_64_gcc_128 no-gmp no-jpake no-krb5 no-libunbound no-md2 no-rc5 no-rfc3779 no-sctp no-shared no-ssl-trace no-ssl2 no-store no-unit-test no-weak-ssl-ciphers no-zlib no-zlib-dynamic static-engine CONFIGURE_ARGS=dist SHLIB_TARGET= # HERE indicates where this Makefile lives. This can be used to indicate # where sub-Makefiles are expected to be. Currently has very limited usage, # and should probably not be bothered with at all. HERE=. # INSTALL_PREFIX is for package builders so that they can configure # for, say, /usr/ and yet have everything installed to /tmp/somedir/usr/. # Normally it is left empty. INSTALL_PREFIX= INSTALLTOP=/usr/local/ssl # Do not edit this manually. Use Configure --openssldir=DIR do change this! OPENSSLDIR=/usr/local/ssl # NO_IDEA - Define to build without the IDEA algorithm # NO_RC4 - Define to build without the RC4 algorithm # NO_RC2 - Define to build without the RC2 algorithm # THREADS - Define when building with threads, you will probably also need any # system defines as well, i.e. _REENTERANT for Solaris 2.[34] # TERMIO - Define the termio terminal subsystem, needed if sgtty is missing. # TERMIOS - Define the termios terminal subsystem, Silicon Graphics. # LONGCRYPT - Define to use HPUX 10.x's long password modification to crypt(3). # DEVRANDOM - Give this the value of the 'random device' if your OS supports # one. 32 bytes will be read from this when the random # number generator is initalised. # SSL_FORBID_ENULL - define if you want the server to be not able to use the # NULL encryption ciphers. # # LOCK_DEBUG - turns on lots of lock debug output :-) # REF_CHECK - turn on some xyz_free() assertions. # REF_PRINT - prints some stuff on structure free. # CRYPTO_MDEBUG - turns on my 'memory leak' detecting stuff # MFUNC - Make all Malloc/Free/Realloc calls call # CRYPTO_malloc/CRYPTO_free/CRYPTO_realloc which can be setup to # call application defined callbacks via CRYPTO_set_mem_functions() # MD5_ASM needs to be defined to use the x86 assembler for MD5 # SHA1_ASM needs to be defined to use the x86 assembler for SHA1 # RMD160_ASM needs to be defined to use the x86 assembler for RIPEMD160 # Do not define B_ENDIAN or L_ENDIAN if 'unsigned long' == 8. It must # equal 4. # PKCS1_CHECK - pkcs1 tests. CC= cc CFLAG= -O DEPFLAG= -DOPENSSL_NO_EC_NISTP_64_GCC_128 -DOPENSSL_NO_GMP -DOPENSSL_NO_JPAKE -DOPENSSL_NO_LIBUNBOUND -DOPENSSL_NO_MD2 -DOPENSSL_NO_RC5 -DOPENSSL_NO_RFC3779 -DOPENSSL_NO_SCTP -DOPENSSL_NO_SSL_TRACE -DOPENSSL_NO_SSL2 -DOPENSSL_NO_STORE -DOPENSSL_NO_UNIT_TEST -DOPENSSL_NO_WEAK_SSL_CIPHERS PEX_LIBS= EX_LIBS= EXE_EXT= ARFLAGS= AR= ar $(ARFLAGS) r RANLIB= /usr/bin/ranlib RC= windres NM= nm PERL= /usr/bin/perl TAR= tar TARFLAGS= --no-recursion MAKEDEPPROG=makedepend LIBDIR=lib # We let the C compiler driver to take care of .s files. This is done in # order to be excused from maintaining a separate set of architecture # dependent assembler flags. E.g. if you throw -mcpu=ultrasparc at SPARC # gcc, then the driver will automatically translate it to -xarch=v8plus # and pass it down to assembler. AS=$(CC) -c ASFLAG=$(CFLAG) # For x86 assembler: Set PROCESSOR to 386 if you want to support # the 80386. PROCESSOR= # CPUID module collects small commonly used assembler snippets CPUID_OBJ= mem_clr.o BN_ASM= bn_asm.o EC_ASM= DES_ENC= des_enc.o fcrypt_b.o AES_ENC= aes_core.o aes_cbc.o BF_ENC= bf_enc.o CAST_ENC= c_enc.o RC4_ENC= rc4_enc.o rc4_skey.o RC5_ENC= rc5_enc.o MD5_ASM_OBJ= SHA1_ASM_OBJ= RMD160_ASM_OBJ= WP_ASM_OBJ= wp_block.o CMLL_ENC= camellia.o cmll_misc.o cmll_cbc.o MODES_ASM_OBJ= ENGINES_ASM_OBJ= PERLASM_SCHEME= # KRB5 stuff KRB5_INCLUDES= LIBKRB5= # Zlib stuff ZLIB_INCLUDE= LIBZLIB= # TOP level FIPS install directory. FIPSDIR=/usr/local/ssl/fips-2.0 # This is the location of fipscanister.o and friends. # The FIPS module build will place it $(INSTALLTOP)/lib # but since $(INSTALLTOP) can only take the default value # when the module is built it will be in /usr/local/ssl/lib # $(INSTALLTOP) for this build may be different so hard # code the path. FIPSLIBDIR= # The location of the library which contains fipscanister.o # normally it will be libcrypto unless fipsdso is set in which # case it will be libfips. If not compiling in FIPS mode at all # this is empty making it a useful test for a FIPS compile. FIPSCANLIB= # Shared library base address. Currently only used on Windows. # BASEADDR=0xFB00000 DIRS= crypto ssl engines apps test tools ENGDIRS= ccgost SHLIBDIRS= crypto ssl # dirs in crypto to build SDIRS= \ objects \ md4 md5 sha mdc2 hmac ripemd whrlpool \ des aes rc2 rc4 idea bf cast camellia seed modes \ bn ec rsa dsa ecdsa dh ecdh dso engine \ buffer bio stack lhash rand err \ evp asn1 pem x509 x509v3 conf txt_db pkcs7 pkcs12 comp ocsp ui krb5 \ cms pqueue ts srp cmac # keep in mind that the above list is adjusted by ./Configure # according to no-xxx arguments... # tests to perform. "alltests" is a special word indicating that all tests # should be performed. TESTS = alltests MAKEFILE= Makefile MANDIR=$(OPENSSLDIR)/man MAN1=1 MAN3=3 MANSUFFIX= HTMLSUFFIX=html HTMLDIR=$(OPENSSLDIR)/html SHELL=/bin/sh TOP= . ONEDIRS=out tmp EDIRS= times doc bugs util include certs ms shlib mt demos perl sf dep VMS WDIRS= windows LIBS= libcrypto.a libssl.a SHARED_CRYPTO=libcrypto$(SHLIB_EXT) SHARED_SSL=libssl$(SHLIB_EXT) SHARED_LIBS= SHARED_LIBS_LINK_EXTS= SHARED_LDFLAGS= GENERAL= Makefile BASENAME= openssl NAME= $(BASENAME)-$(VERSION) TARFILE= ../$(NAME).tar EXHEADER= e_os2.h HEADER= e_os.h all: Makefile build_all # as we stick to -e, CLEARENV ensures that local variables in lower # Makefiles remain local and variable. $${VAR+VAR} is tribute to Korn # shell, which [annoyingly enough] terminates unset with error if VAR # is not present:-( TOP= && unset TOP is tribute to HP-UX /bin/sh, # which terminates unset with error if no variable was present:-( CLEARENV= TOP= && unset TOP $${LIB+LIB} $${LIBS+LIBS} \ $${INCLUDE+INCLUDE} $${INCLUDES+INCLUDES} \ $${DIR+DIR} $${DIRS+DIRS} $${SRC+SRC} \ $${LIBSRC+LIBSRC} $${LIBOBJ+LIBOBJ} $${ALL+ALL} \ $${EXHEADER+EXHEADER} $${HEADER+HEADER} \ $${GENERAL+GENERAL} $${CFLAGS+CFLAGS} \ $${ASFLAGS+ASFLAGS} $${AFLAGS+AFLAGS} \ $${LDCMD+LDCMD} $${LDFLAGS+LDFLAGS} $${SCRIPTS+SCRIPTS} \ $${SHAREDCMD+SHAREDCMD} $${SHAREDFLAGS+SHAREDFLAGS} \ $${SHARED_LIB+SHARED_LIB} $${LIBEXTRAS+LIBEXTRAS} \ $${APPS+APPS} # LC_ALL=C ensures that error [and other] messages are delivered in # same language for uniform treatment. BUILDENV= LC_ALL=C PLATFORM='$(PLATFORM)' PROCESSOR='$(PROCESSOR)'\ CC='$(CC)' CFLAG='$(CFLAG)' \ AS='$(CC)' ASFLAG='$(CFLAG) -c' \ AR='$(AR)' NM='$(NM)' RANLIB='$(RANLIB)' \ RC='$(RC)' \ CROSS_COMPILE='$(CROSS_COMPILE)' \ PERL='$(PERL)' ENGDIRS='$(ENGDIRS)' \ SDIRS='$(SDIRS)' LIBRPATH='$(INSTALLTOP)/$(LIBDIR)' \ INSTALL_PREFIX='$(INSTALL_PREFIX)' \ INSTALLTOP='$(INSTALLTOP)' OPENSSLDIR='$(OPENSSLDIR)' \ LIBDIR='$(LIBDIR)' \ MAKEDEPEND='$$$${TOP}/util/domd $$$${TOP} -MD $(MAKEDEPPROG)' \ DEPFLAG='-DOPENSSL_NO_DEPRECATED $(DEPFLAG)' \ MAKEDEPPROG='$(MAKEDEPPROG)' \ SHARED_LDFLAGS='$(SHARED_LDFLAGS)' \ KRB5_INCLUDES='$(KRB5_INCLUDES)' LIBKRB5='$(LIBKRB5)' \ ZLIB_INCLUDE='$(ZLIB_INCLUDE)' LIBZLIB='$(LIBZLIB)' \ EXE_EXT='$(EXE_EXT)' SHARED_LIBS='$(SHARED_LIBS)' \ SHLIB_EXT='$(SHLIB_EXT)' SHLIB_TARGET='$(SHLIB_TARGET)' \ PEX_LIBS='$(PEX_LIBS)' EX_LIBS='$(EX_LIBS)' \ CPUID_OBJ='$(CPUID_OBJ)' BN_ASM='$(BN_ASM)' \ EC_ASM='$(EC_ASM)' DES_ENC='$(DES_ENC)' \ AES_ENC='$(AES_ENC)' CMLL_ENC='$(CMLL_ENC)' \ BF_ENC='$(BF_ENC)' CAST_ENC='$(CAST_ENC)' \ RC4_ENC='$(RC4_ENC)' RC5_ENC='$(RC5_ENC)' \ SHA1_ASM_OBJ='$(SHA1_ASM_OBJ)' \ MD5_ASM_OBJ='$(MD5_ASM_OBJ)' \ RMD160_ASM_OBJ='$(RMD160_ASM_OBJ)' \ WP_ASM_OBJ='$(WP_ASM_OBJ)' \ MODES_ASM_OBJ='$(MODES_ASM_OBJ)' \ ENGINES_ASM_OBJ='$(ENGINES_ASM_OBJ)' \ PERLASM_SCHEME='$(PERLASM_SCHEME)' \ FIPSLIBDIR='${FIPSLIBDIR}' \ FIPSDIR='${FIPSDIR}' \ FIPSCANLIB="$${FIPSCANLIB:-$(FIPSCANLIB)}" \ THIS=$${THIS:-$@} MAKEFILE=Makefile MAKEOVERRIDES= # MAKEOVERRIDES= effectively "equalizes" GNU-ish and SysV-ish make flavors, # which in turn eliminates ambiguities in variable treatment with -e. # BUILD_CMD is a generic macro to build a given target in a given # subdirectory. The target must be given through the shell variable # `target' and the subdirectory to build in must be given through `dir'. # This macro shouldn't be used directly, use RECURSIVE_BUILD_CMD or # BUILD_ONE_CMD instead. # # BUILD_ONE_CMD is a macro to build a given target in a given # subdirectory if that subdirectory is part of $(DIRS). It requires # exactly the same shell variables as BUILD_CMD. # # RECURSIVE_BUILD_CMD is a macro to build a given target in all # subdirectories defined in $(DIRS). It requires that the target # is given through the shell variable `target'. BUILD_CMD= if [ -d "$$dir" ]; then \ ( cd $$dir && echo "making $$target in $$dir..." && \ $(CLEARENV) && $(MAKE) -e $(BUILDENV) TOP=.. DIR=$$dir $$target \ ) || exit 1; \ fi RECURSIVE_BUILD_CMD=for dir in $(DIRS); do $(BUILD_CMD); done BUILD_ONE_CMD=\ if expr " $(DIRS) " : ".* $$dir " >/dev/null 2>&1; then \ $(BUILD_CMD); \ fi reflect: @[ -n "$(THIS)" ] && $(CLEARENV) && $(MAKE) $(THIS) -e $(BUILDENV) sub_all: build_all build_all: build_libs build_apps build_tests build_tools build_libs: build_libcrypto build_libssl openssl.pc build_libcrypto: build_crypto build_engines libcrypto.pc build_libssl: build_ssl libssl.pc build_crypto: @dir=crypto; target=all; $(BUILD_ONE_CMD) build_ssl: build_crypto @dir=ssl; target=all; $(BUILD_ONE_CMD) build_engines: build_crypto @dir=engines; target=all; $(BUILD_ONE_CMD) build_apps: build_libs @dir=apps; target=all; $(BUILD_ONE_CMD) build_tests: build_libs @dir=test; target=all; $(BUILD_ONE_CMD) build_tools: build_libs @dir=tools; target=all; $(BUILD_ONE_CMD) all_testapps: build_libs build_testapps build_testapps: @dir=crypto; target=testapps; $(BUILD_ONE_CMD) fips_premain_dso$(EXE_EXT): libcrypto.a [ -z "$(FIPSCANLIB)" ] || $(CC) $(CFLAG) -Iinclude \ -DFINGERPRINT_PREMAIN_DSO_LOAD -o $@ \ $(FIPSLIBDIR)fips_premain.c $(FIPSLIBDIR)fipscanister.o \ libcrypto.a $(EX_LIBS) libcrypto$(SHLIB_EXT): libcrypto.a fips_premain_dso$(EXE_EXT) @if [ "$(SHLIB_TARGET)" != "" ]; then \ if [ "$(FIPSCANLIB)" = "libcrypto" ]; then \ FIPSLD_LIBCRYPTO=libcrypto.a ; \ FIPSLD_CC="$(CC)"; CC=$(FIPSDIR)/bin/fipsld; \ export CC FIPSLD_CC FIPSLD_LIBCRYPTO; \ fi; \ $(MAKE) -e SHLIBDIRS=crypto CC="$${CC:-$(CC)}" build-shared && \ (touch -c fips_premain_dso$(EXE_EXT) || :); \ else \ echo "There's no support for shared libraries on this platform" >&2; \ exit 1; \ fi libssl$(SHLIB_EXT): libcrypto$(SHLIB_EXT) libssl.a @if [ "$(SHLIB_TARGET)" != "" ]; then \ $(MAKE) SHLIBDIRS=ssl SHLIBDEPS='-lcrypto' build-shared; \ else \ echo "There's no support for shared libraries on this platform" >&2; \ exit 1; \ fi clean-shared: @set -e; for i in $(SHLIBDIRS); do \ if [ -n "$(SHARED_LIBS_LINK_EXTS)" ]; then \ tmp="$(SHARED_LIBS_LINK_EXTS)"; \ for j in $${tmp:-x}; do \ ( set -x; rm -f lib$$i$$j ); \ done; \ fi; \ ( set -x; rm -f lib$$i$(SHLIB_EXT) ); \ if expr "$(PLATFORM)" : "Cygwin" >/dev/null; then \ ( set -x; rm -f cyg$$i$(SHLIB_EXT) lib$$i$(SHLIB_EXT).a ); \ fi; \ done link-shared: @ set -e; for i in $(SHLIBDIRS); do \ $(MAKE) -f $(HERE)/Makefile.shared -e $(BUILDENV) \ LIBNAME=$$i LIBVERSION=$(SHLIB_MAJOR).$(SHLIB_MINOR) \ LIBCOMPATVERSIONS=";$(SHLIB_VERSION_HISTORY)" \ symlink.$(SHLIB_TARGET); \ libs="$$libs -l$$i"; \ done build-shared: do_$(SHLIB_TARGET) link-shared do_$(SHLIB_TARGET): @ set -e; libs='-L. $(SHLIBDEPS)'; for i in $(SHLIBDIRS); do \ if [ "$$i" = "ssl" -a -n "$(LIBKRB5)" ]; then \ libs="$(LIBKRB5) $$libs"; \ fi; \ $(CLEARENV) && $(MAKE) -f Makefile.shared -e $(BUILDENV) \ LIBNAME=$$i LIBVERSION=$(SHLIB_MAJOR).$(SHLIB_MINOR) \ LIBCOMPATVERSIONS=";$(SHLIB_VERSION_HISTORY)" \ LIBDEPS="$$libs $(EX_LIBS)" \ link_a.$(SHLIB_TARGET); \ libs="-l$$i $$libs"; \ done libcrypto.pc: Makefile @ ( echo 'prefix=$(INSTALLTOP)'; \ echo 'exec_prefix=$${prefix}'; \ echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \ echo 'includedir=$${prefix}/include'; \ echo 'enginesdir=$${libdir}/engines'; \ echo ''; \ echo 'Name: OpenSSL-libcrypto'; \ echo 'Description: OpenSSL cryptography library'; \ echo 'Version: '$(VERSION); \ echo 'Requires: '; \ echo 'Libs: -L$${libdir} -lcrypto'; \ echo 'Libs.private: $(EX_LIBS)'; \ echo 'Cflags: -I$${includedir} $(KRB5_INCLUDES)' ) > libcrypto.pc libssl.pc: Makefile @ ( echo 'prefix=$(INSTALLTOP)'; \ echo 'exec_prefix=$${prefix}'; \ echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \ echo 'includedir=$${prefix}/include'; \ echo ''; \ echo 'Name: OpenSSL-libssl'; \ echo 'Description: Secure Sockets Layer and cryptography libraries'; \ echo 'Version: '$(VERSION); \ echo 'Requires.private: libcrypto'; \ echo 'Libs: -L$${libdir} -lssl'; \ echo 'Libs.private: $(EX_LIBS)'; \ echo 'Cflags: -I$${includedir} $(KRB5_INCLUDES)' ) > libssl.pc openssl.pc: Makefile @ ( echo 'prefix=$(INSTALLTOP)'; \ echo 'exec_prefix=$${prefix}'; \ echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \ echo 'includedir=$${prefix}/include'; \ echo ''; \ echo 'Name: OpenSSL'; \ echo 'Description: Secure Sockets Layer and cryptography libraries and tools'; \ echo 'Version: '$(VERSION); \ echo 'Requires: libssl libcrypto' ) > openssl.pc Makefile: Makefile.org Configure config @echo "Makefile is older than Makefile.org, Configure or config." @echo "Reconfigure the source tree (via './config' or 'perl Configure'), please." @false libclean: rm -f *.map *.so *.so.* *.dylib *.dll engines/*.so engines/*.dll engines/*.dylib *.a engines/*.a */lib */*/lib clean: libclean rm -f shlib/*.o *.o core a.out fluff rehash.time testlog make.log cctest cctest.c @set -e; target=clean; $(RECURSIVE_BUILD_CMD) rm -f $(LIBS) rm -f openssl.pc libssl.pc libcrypto.pc rm -f speed.* .pure rm -f $(TARFILE) @set -e; for i in $(ONEDIRS) ;\ do \ rm -fr $$i/*; \ done + +distclean: clean + -$(RM) `find . -name .git -prune -o -type l -print` + $(RM) apps/CA.pl + $(RM) test/evptests.txt test/newkey.pem test/testkey.pem test/testreq.pem + $(RM) tools/c_rehash + $(RM) crypto/opensslconf.h + $(RM) Makefile Makefile.bak makefile.one: files $(PERL) util/mk1mf.pl >makefile.one; \ sh util/do_ms.sh files: $(PERL) $(TOP)/util/files.pl Makefile > $(TOP)/MINFO @set -e; target=files; $(RECURSIVE_BUILD_CMD) links: @$(PERL) $(TOP)/util/mkdir-p.pl include/openssl @$(PERL) $(TOP)/util/mklink.pl include/openssl $(EXHEADER) @set -e; target=links; $(RECURSIVE_BUILD_CMD) gentests: @(cd test && echo "generating dummy tests (if needed)..." && \ $(CLEARENV) && $(MAKE) -e $(BUILDENV) TESTS='$(TESTS)' OPENSSL_DEBUG_MEMORY=on generate ); dclean: rm -rf *.bak include/openssl certs/.0 @set -e; target=dclean; $(RECURSIVE_BUILD_CMD) rehash: rehash.time rehash.time: certs apps @if [ -z "$(CROSS_COMPILE)" ]; then \ (OPENSSL="`pwd`/util/opensslwrap.sh"; \ [ -x "apps/openssl.exe" ] && OPENSSL="apps/openssl.exe" || :; \ OPENSSL_DEBUG_MEMORY=on; \ export OPENSSL OPENSSL_DEBUG_MEMORY; \ $(PERL) tools/c_rehash certs/demo) && \ touch rehash.time; \ else :; fi test: tests tests: rehash @(cd test && echo "testing..." && \ $(CLEARENV) && $(MAKE) -e $(BUILDENV) TOP=.. TESTS='$(TESTS)' OPENSSL_DEBUG_MEMORY=on OPENSSL_CONF=../apps/openssl.cnf tests ); OPENSSL_CONF=apps/openssl.cnf util/opensslwrap.sh version -a report: @$(PERL) util/selftest.pl update: errors stacks util/libeay.num util/ssleay.num TABLE @set -e; target=update; $(RECURSIVE_BUILD_CMD) depend: @set -e; target=depend; $(RECURSIVE_BUILD_CMD) lint: @set -e; target=lint; $(RECURSIVE_BUILD_CMD) tags: rm -f TAGS find . -name '[^.]*.[ch]' | xargs etags -a errors: $(PERL) util/ck_errf.pl -strict */*.c */*/*.c $(PERL) util/mkerr.pl -recurse -write (cd engines; $(MAKE) PERL=$(PERL) errors) stacks: $(PERL) util/mkstack.pl -write util/libeay.num:: $(PERL) util/mkdef.pl crypto update util/ssleay.num:: $(PERL) util/mkdef.pl ssl update TABLE: Configure (echo 'Output of `Configure TABLE'"':"; \ $(PERL) Configure TABLE) > TABLE # Build distribution tar-file. As the list of files returned by "find" is # pretty long, on several platforms a "too many arguments" error or similar # would occur. Therefore the list of files is temporarily stored into a file # and read directly, requiring GNU-Tar. Call "make TAR=gtar dist" if the normal # tar does not support the --files-from option. TAR_COMMAND=$(TAR) $(TARFLAGS) --files-from $(TARFILE).list \ --owner 0 --group 0 \ --transform 's|^|$(NAME)/|' \ -cvf - $(TARFILE).list: find * \! -name STATUS \! -name TABLE \! -name '*.o' \! -name '*.a' \ \! -name '*.so' \! -name '*.so.*' \! -name 'openssl' \ \( \! -name '*test' -o -name bctest -o -name pod2mantest \) \ \! -name '.#*' \! -name '*~' \! -type l \ | sort > $(TARFILE).list tar: $(TARFILE).list find . -type d -print | xargs chmod 755 find . -type f -print | xargs chmod a+r find . -type f -perm -0100 -print | xargs chmod a+x $(TAR_COMMAND) | gzip --best > $(TARFILE).gz rm -f $(TARFILE).list ls -l $(TARFILE).gz tar-snap: $(TARFILE).list $(TAR_COMMAND) > $(TARFILE) rm -f $(TARFILE).list ls -l $(TARFILE) dist: $(PERL) Configure dist @$(MAKE) SDIRS='$(SDIRS)' clean @$(MAKE) TAR='$(TAR)' TARFLAGS='$(TARFLAGS)' $(DISTTARVARS) tar install: all install_docs install_sw install_sw: @$(PERL) $(TOP)/util/mkdir-p.pl $(INSTALL_PREFIX)$(INSTALLTOP)/bin \ $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR) \ $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/engines \ $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig \ $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl \ $(INSTALL_PREFIX)$(OPENSSLDIR)/misc \ $(INSTALL_PREFIX)$(OPENSSLDIR)/certs \ $(INSTALL_PREFIX)$(OPENSSLDIR)/private @set -e; headerlist="$(EXHEADER)"; for i in $$headerlist;\ do \ (cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i; \ chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i ); \ done; @set -e; target=install; $(RECURSIVE_BUILD_CMD) @set -e; liblist="$(LIBS)"; for i in $$liblist ;\ do \ if [ -f "$$i" ]; then \ ( echo installing $$i; \ cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \ $(RANLIB) $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \ chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \ mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i ); \ fi; \ done; @set -e; if [ -n "$(SHARED_LIBS)" ]; then \ tmp="$(SHARED_LIBS)"; \ for i in $${tmp:-x}; \ do \ if [ -f "$$i" -o -f "$$i.a" ]; then \ ( echo installing $$i; \ if expr "$(PLATFORM)" : "Cygwin" >/dev/null; then \ c=`echo $$i | sed 's/^lib\(.*\)\.dll\.a/cyg\1-$(SHLIB_VERSION_NUMBER).dll/'`; \ cp $$c $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$c.new; \ chmod 755 $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$c.new; \ mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$c.new $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$c; \ cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \ chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \ mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i; \ else \ cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \ chmod 555 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \ mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i; \ fi ); \ if expr $(PLATFORM) : 'mingw' > /dev/null; then \ ( case $$i in \ *crypto*) i=libeay32.dll;; \ *ssl*) i=ssleay32.dll;; \ esac; \ echo installing $$i; \ cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i.new; \ chmod 755 $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i.new; \ mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i.new $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i ); \ fi; \ fi; \ done; \ ( here="`pwd`"; \ cd $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR); \ $(MAKE) -f $$here/Makefile HERE="$$here" link-shared ); \ if [ "$(INSTALLTOP)" != "/usr" ]; then \ echo 'OpenSSL shared libraries have been installed in:'; \ echo ' $(INSTALLTOP)'; \ echo ''; \ sed -e '1,/^$$/d' doc/openssl-shared.txt; \ fi; \ fi cp libcrypto.pc $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/libcrypto.pc cp libssl.pc $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/libssl.pc cp openssl.pc $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/openssl.pc install_html_docs: here="`pwd`"; \ filecase=; \ case "$(PLATFORM)" in DJGPP|Cygwin*|mingw*|darwin*-*-cc) \ filecase=-i; \ esac; \ for subdir in apps crypto ssl; do \ mkdir -p $(INSTALL_PREFIX)$(HTMLDIR)/$$subdir; \ for i in doc/$$subdir/*.pod; do \ fn=`basename $$i .pod`; \ echo "installing html/$$fn.$(HTMLSUFFIX)"; \ cat $$i \ | sed -r 's/L<([^)]*)(\([0-9]\))?\|([^)]*)(\([0-9]\))?>/L<\1|\3>/g' \ | pod2html --podroot=doc --htmlroot=.. --podpath=apps:crypto:ssl \ | sed -r 's/ $(INSTALL_PREFIX)$(HTMLDIR)/$$subdir/$$fn.$(HTMLSUFFIX); \ $(PERL) util/extract-names.pl < $$i | \ grep -v $$filecase "^$$fn\$$" | \ (cd $(INSTALL_PREFIX)$(HTMLDIR)/$$subdir; \ while read n; do \ PLATFORM=$(PLATFORM) $$here/util/point.sh $$fn.$(HTMLSUFFIX) "$$n".$(HTMLSUFFIX); \ done); \ done; \ done install_docs: @$(PERL) $(TOP)/util/mkdir-p.pl \ $(INSTALL_PREFIX)$(MANDIR)/man1 \ $(INSTALL_PREFIX)$(MANDIR)/man3 \ $(INSTALL_PREFIX)$(MANDIR)/man5 \ $(INSTALL_PREFIX)$(MANDIR)/man7 @pod2man="`cd ./util; ./pod2mantest $(PERL)`"; \ here="`pwd`"; \ filecase=; \ case "$(PLATFORM)" in DJGPP|Cygwin*|mingw*|darwin*-*-cc) \ filecase=-i; \ esac; \ set -e; for i in doc/apps/*.pod; do \ fn=`basename $$i .pod`; \ sec=`$(PERL) util/extract-section.pl 1 < $$i`; \ echo "installing man$$sec/$$fn.$${sec}$(MANSUFFIX)"; \ (cd `$(PERL) util/dirname.pl $$i`; \ sh -c "$$pod2man \ --section=$$sec --center=OpenSSL \ --release=$(VERSION) `basename $$i`") \ > $(INSTALL_PREFIX)$(MANDIR)/man$$sec/$$fn.$${sec}$(MANSUFFIX); \ $(PERL) util/extract-names.pl < $$i | \ (grep -v $$filecase "^$$fn\$$"; true) | \ (grep -v "[ ]"; true) | \ (cd $(INSTALL_PREFIX)$(MANDIR)/man$$sec/; \ while read n; do \ PLATFORM=$(PLATFORM) $$here/util/point.sh $$fn.$${sec}$(MANSUFFIX) "$$n".$${sec}$(MANSUFFIX); \ done); \ done; \ set -e; for i in doc/crypto/*.pod doc/ssl/*.pod; do \ fn=`basename $$i .pod`; \ sec=`$(PERL) util/extract-section.pl 3 < $$i`; \ echo "installing man$$sec/$$fn.$${sec}$(MANSUFFIX)"; \ (cd `$(PERL) util/dirname.pl $$i`; \ sh -c "$$pod2man \ --section=$$sec --center=OpenSSL \ --release=$(VERSION) `basename $$i`") \ > $(INSTALL_PREFIX)$(MANDIR)/man$$sec/$$fn.$${sec}$(MANSUFFIX); \ $(PERL) util/extract-names.pl < $$i | \ (grep -v $$filecase "^$$fn\$$"; true) | \ (grep -v "[ ]"; true) | \ (cd $(INSTALL_PREFIX)$(MANDIR)/man$$sec/; \ while read n; do \ PLATFORM=$(PLATFORM) $$here/util/point.sh $$fn.$${sec}$(MANSUFFIX) "$$n".$${sec}$(MANSUFFIX); \ done); \ done # DO NOT DELETE THIS LINE -- make depend depends on it. Index: vendor-crypto/openssl/dist/Makefile.org =================================================================== --- vendor-crypto/openssl/dist/Makefile.org (revision 318896) +++ vendor-crypto/openssl/dist/Makefile.org (revision 318897) @@ -1,682 +1,690 @@ ## ## Makefile for OpenSSL ## VERSION= MAJOR= MINOR= SHLIB_VERSION_NUMBER= SHLIB_VERSION_HISTORY= SHLIB_MAJOR= SHLIB_MINOR= SHLIB_EXT= PLATFORM=dist OPTIONS= CONFIGURE_ARGS= SHLIB_TARGET= # HERE indicates where this Makefile lives. This can be used to indicate # where sub-Makefiles are expected to be. Currently has very limited usage, # and should probably not be bothered with at all. HERE=. # INSTALL_PREFIX is for package builders so that they can configure # for, say, /usr/ and yet have everything installed to /tmp/somedir/usr/. # Normally it is left empty. INSTALL_PREFIX= INSTALLTOP=/usr/local/ssl # Do not edit this manually. Use Configure --openssldir=DIR do change this! OPENSSLDIR=/usr/local/ssl # NO_IDEA - Define to build without the IDEA algorithm # NO_RC4 - Define to build without the RC4 algorithm # NO_RC2 - Define to build without the RC2 algorithm # THREADS - Define when building with threads, you will probably also need any # system defines as well, i.e. _REENTERANT for Solaris 2.[34] # TERMIO - Define the termio terminal subsystem, needed if sgtty is missing. # TERMIOS - Define the termios terminal subsystem, Silicon Graphics. # LONGCRYPT - Define to use HPUX 10.x's long password modification to crypt(3). # DEVRANDOM - Give this the value of the 'random device' if your OS supports # one. 32 bytes will be read from this when the random # number generator is initalised. # SSL_FORBID_ENULL - define if you want the server to be not able to use the # NULL encryption ciphers. # # LOCK_DEBUG - turns on lots of lock debug output :-) # REF_CHECK - turn on some xyz_free() assertions. # REF_PRINT - prints some stuff on structure free. # CRYPTO_MDEBUG - turns on my 'memory leak' detecting stuff # MFUNC - Make all Malloc/Free/Realloc calls call # CRYPTO_malloc/CRYPTO_free/CRYPTO_realloc which can be setup to # call application defined callbacks via CRYPTO_set_mem_functions() # MD5_ASM needs to be defined to use the x86 assembler for MD5 # SHA1_ASM needs to be defined to use the x86 assembler for SHA1 # RMD160_ASM needs to be defined to use the x86 assembler for RIPEMD160 # Do not define B_ENDIAN or L_ENDIAN if 'unsigned long' == 8. It must # equal 4. # PKCS1_CHECK - pkcs1 tests. CC= cc CFLAG= -O DEPFLAG= PEX_LIBS= EX_LIBS= EXE_EXT= ARFLAGS= AR=ar $(ARFLAGS) r RANLIB= ranlib RC= windres NM= nm PERL= perl TAR= tar TARFLAGS= --no-recursion MAKEDEPPROG=makedepend LIBDIR=lib # We let the C compiler driver to take care of .s files. This is done in # order to be excused from maintaining a separate set of architecture # dependent assembler flags. E.g. if you throw -mcpu=ultrasparc at SPARC # gcc, then the driver will automatically translate it to -xarch=v8plus # and pass it down to assembler. AS=$(CC) -c ASFLAG=$(CFLAG) # For x86 assembler: Set PROCESSOR to 386 if you want to support # the 80386. PROCESSOR= # CPUID module collects small commonly used assembler snippets CPUID_OBJ= BN_ASM= bn_asm.o EC_ASM= DES_ENC= des_enc.o fcrypt_b.o AES_ENC= aes_core.o aes_cbc.o BF_ENC= bf_enc.o CAST_ENC= c_enc.o RC4_ENC= rc4_enc.o RC5_ENC= rc5_enc.o MD5_ASM_OBJ= SHA1_ASM_OBJ= RMD160_ASM_OBJ= WP_ASM_OBJ= CMLL_ENC= MODES_ASM_OBJ= ENGINES_ASM_OBJ= PERLASM_SCHEME= # KRB5 stuff KRB5_INCLUDES= LIBKRB5= # Zlib stuff ZLIB_INCLUDE= LIBZLIB= # TOP level FIPS install directory. FIPSDIR= # This is the location of fipscanister.o and friends. # The FIPS module build will place it $(INSTALLTOP)/lib # but since $(INSTALLTOP) can only take the default value # when the module is built it will be in /usr/local/ssl/lib # $(INSTALLTOP) for this build may be different so hard # code the path. FIPSLIBDIR= # The location of the library which contains fipscanister.o # normally it will be libcrypto unless fipsdso is set in which # case it will be libfips. If not compiling in FIPS mode at all # this is empty making it a useful test for a FIPS compile. FIPSCANLIB= # Shared library base address. Currently only used on Windows. # BASEADDR= DIRS= crypto ssl engines apps test tools ENGDIRS= ccgost SHLIBDIRS= crypto ssl # dirs in crypto to build SDIRS= \ objects \ md2 md4 md5 sha mdc2 hmac ripemd whrlpool \ des aes rc2 rc4 rc5 idea bf cast camellia seed modes \ bn ec rsa dsa ecdsa dh ecdh dso engine \ buffer bio stack lhash rand err \ evp asn1 pem x509 x509v3 conf txt_db pkcs7 pkcs12 comp ocsp ui krb5 \ cms pqueue ts jpake srp store cmac # keep in mind that the above list is adjusted by ./Configure # according to no-xxx arguments... # tests to perform. "alltests" is a special word indicating that all tests # should be performed. TESTS = alltests MAKEFILE= Makefile MANDIR=$(OPENSSLDIR)/man MAN1=1 MAN3=3 MANSUFFIX= HTMLSUFFIX=html HTMLDIR=$(OPENSSLDIR)/html SHELL=/bin/sh TOP= . ONEDIRS=out tmp EDIRS= times doc bugs util include certs ms shlib mt demos perl sf dep VMS WDIRS= windows LIBS= libcrypto.a libssl.a SHARED_CRYPTO=libcrypto$(SHLIB_EXT) SHARED_SSL=libssl$(SHLIB_EXT) SHARED_LIBS= SHARED_LIBS_LINK_EXTS= SHARED_LDFLAGS= GENERAL= Makefile BASENAME= openssl NAME= $(BASENAME)-$(VERSION) TARFILE= ../$(NAME).tar EXHEADER= e_os2.h HEADER= e_os.h all: Makefile build_all # as we stick to -e, CLEARENV ensures that local variables in lower # Makefiles remain local and variable. $${VAR+VAR} is tribute to Korn # shell, which [annoyingly enough] terminates unset with error if VAR # is not present:-( TOP= && unset TOP is tribute to HP-UX /bin/sh, # which terminates unset with error if no variable was present:-( CLEARENV= TOP= && unset TOP $${LIB+LIB} $${LIBS+LIBS} \ $${INCLUDE+INCLUDE} $${INCLUDES+INCLUDES} \ $${DIR+DIR} $${DIRS+DIRS} $${SRC+SRC} \ $${LIBSRC+LIBSRC} $${LIBOBJ+LIBOBJ} $${ALL+ALL} \ $${EXHEADER+EXHEADER} $${HEADER+HEADER} \ $${GENERAL+GENERAL} $${CFLAGS+CFLAGS} \ $${ASFLAGS+ASFLAGS} $${AFLAGS+AFLAGS} \ $${LDCMD+LDCMD} $${LDFLAGS+LDFLAGS} $${SCRIPTS+SCRIPTS} \ $${SHAREDCMD+SHAREDCMD} $${SHAREDFLAGS+SHAREDFLAGS} \ $${SHARED_LIB+SHARED_LIB} $${LIBEXTRAS+LIBEXTRAS} \ $${APPS+APPS} # LC_ALL=C ensures that error [and other] messages are delivered in # same language for uniform treatment. BUILDENV= LC_ALL=C PLATFORM='$(PLATFORM)' PROCESSOR='$(PROCESSOR)'\ CC='$(CC)' CFLAG='$(CFLAG)' \ AS='$(CC)' ASFLAG='$(CFLAG) -c' \ AR='$(AR)' NM='$(NM)' RANLIB='$(RANLIB)' \ RC='$(RC)' \ CROSS_COMPILE='$(CROSS_COMPILE)' \ PERL='$(PERL)' ENGDIRS='$(ENGDIRS)' \ SDIRS='$(SDIRS)' LIBRPATH='$(INSTALLTOP)/$(LIBDIR)' \ INSTALL_PREFIX='$(INSTALL_PREFIX)' \ INSTALLTOP='$(INSTALLTOP)' OPENSSLDIR='$(OPENSSLDIR)' \ LIBDIR='$(LIBDIR)' \ MAKEDEPEND='$$$${TOP}/util/domd $$$${TOP} -MD $(MAKEDEPPROG)' \ DEPFLAG='-DOPENSSL_NO_DEPRECATED $(DEPFLAG)' \ MAKEDEPPROG='$(MAKEDEPPROG)' \ SHARED_LDFLAGS='$(SHARED_LDFLAGS)' \ KRB5_INCLUDES='$(KRB5_INCLUDES)' LIBKRB5='$(LIBKRB5)' \ ZLIB_INCLUDE='$(ZLIB_INCLUDE)' LIBZLIB='$(LIBZLIB)' \ EXE_EXT='$(EXE_EXT)' SHARED_LIBS='$(SHARED_LIBS)' \ SHLIB_EXT='$(SHLIB_EXT)' SHLIB_TARGET='$(SHLIB_TARGET)' \ PEX_LIBS='$(PEX_LIBS)' EX_LIBS='$(EX_LIBS)' \ CPUID_OBJ='$(CPUID_OBJ)' BN_ASM='$(BN_ASM)' \ EC_ASM='$(EC_ASM)' DES_ENC='$(DES_ENC)' \ AES_ENC='$(AES_ENC)' CMLL_ENC='$(CMLL_ENC)' \ BF_ENC='$(BF_ENC)' CAST_ENC='$(CAST_ENC)' \ RC4_ENC='$(RC4_ENC)' RC5_ENC='$(RC5_ENC)' \ SHA1_ASM_OBJ='$(SHA1_ASM_OBJ)' \ MD5_ASM_OBJ='$(MD5_ASM_OBJ)' \ RMD160_ASM_OBJ='$(RMD160_ASM_OBJ)' \ WP_ASM_OBJ='$(WP_ASM_OBJ)' \ MODES_ASM_OBJ='$(MODES_ASM_OBJ)' \ ENGINES_ASM_OBJ='$(ENGINES_ASM_OBJ)' \ PERLASM_SCHEME='$(PERLASM_SCHEME)' \ FIPSLIBDIR='${FIPSLIBDIR}' \ FIPSDIR='${FIPSDIR}' \ FIPSCANLIB="$${FIPSCANLIB:-$(FIPSCANLIB)}" \ THIS=$${THIS:-$@} MAKEFILE=Makefile MAKEOVERRIDES= # MAKEOVERRIDES= effectively "equalizes" GNU-ish and SysV-ish make flavors, # which in turn eliminates ambiguities in variable treatment with -e. # BUILD_CMD is a generic macro to build a given target in a given # subdirectory. The target must be given through the shell variable # `target' and the subdirectory to build in must be given through `dir'. # This macro shouldn't be used directly, use RECURSIVE_BUILD_CMD or # BUILD_ONE_CMD instead. # # BUILD_ONE_CMD is a macro to build a given target in a given # subdirectory if that subdirectory is part of $(DIRS). It requires # exactly the same shell variables as BUILD_CMD. # # RECURSIVE_BUILD_CMD is a macro to build a given target in all # subdirectories defined in $(DIRS). It requires that the target # is given through the shell variable `target'. BUILD_CMD= if [ -d "$$dir" ]; then \ ( cd $$dir && echo "making $$target in $$dir..." && \ $(CLEARENV) && $(MAKE) -e $(BUILDENV) TOP=.. DIR=$$dir $$target \ ) || exit 1; \ fi RECURSIVE_BUILD_CMD=for dir in $(DIRS); do $(BUILD_CMD); done BUILD_ONE_CMD=\ if expr " $(DIRS) " : ".* $$dir " >/dev/null 2>&1; then \ $(BUILD_CMD); \ fi reflect: @[ -n "$(THIS)" ] && $(CLEARENV) && $(MAKE) $(THIS) -e $(BUILDENV) sub_all: build_all build_all: build_libs build_apps build_tests build_tools build_libs: build_libcrypto build_libssl openssl.pc build_libcrypto: build_crypto build_engines libcrypto.pc build_libssl: build_ssl libssl.pc build_crypto: @dir=crypto; target=all; $(BUILD_ONE_CMD) build_ssl: build_crypto @dir=ssl; target=all; $(BUILD_ONE_CMD) build_engines: build_crypto @dir=engines; target=all; $(BUILD_ONE_CMD) build_apps: build_libs @dir=apps; target=all; $(BUILD_ONE_CMD) build_tests: build_libs @dir=test; target=all; $(BUILD_ONE_CMD) build_tools: build_libs @dir=tools; target=all; $(BUILD_ONE_CMD) all_testapps: build_libs build_testapps build_testapps: @dir=crypto; target=testapps; $(BUILD_ONE_CMD) fips_premain_dso$(EXE_EXT): libcrypto.a [ -z "$(FIPSCANLIB)" ] || $(CC) $(CFLAG) -Iinclude \ -DFINGERPRINT_PREMAIN_DSO_LOAD -o $@ \ $(FIPSLIBDIR)fips_premain.c $(FIPSLIBDIR)fipscanister.o \ libcrypto.a $(EX_LIBS) libcrypto$(SHLIB_EXT): libcrypto.a fips_premain_dso$(EXE_EXT) @if [ "$(SHLIB_TARGET)" != "" ]; then \ if [ "$(FIPSCANLIB)" = "libcrypto" ]; then \ FIPSLD_LIBCRYPTO=libcrypto.a ; \ FIPSLD_CC="$(CC)"; CC=$(FIPSDIR)/bin/fipsld; \ export CC FIPSLD_CC FIPSLD_LIBCRYPTO; \ fi; \ $(MAKE) -e SHLIBDIRS=crypto CC="$${CC:-$(CC)}" build-shared && \ (touch -c fips_premain_dso$(EXE_EXT) || :); \ else \ echo "There's no support for shared libraries on this platform" >&2; \ exit 1; \ fi libssl$(SHLIB_EXT): libcrypto$(SHLIB_EXT) libssl.a @if [ "$(SHLIB_TARGET)" != "" ]; then \ $(MAKE) SHLIBDIRS=ssl SHLIBDEPS='-lcrypto' build-shared; \ else \ echo "There's no support for shared libraries on this platform" >&2; \ exit 1; \ fi clean-shared: @set -e; for i in $(SHLIBDIRS); do \ if [ -n "$(SHARED_LIBS_LINK_EXTS)" ]; then \ tmp="$(SHARED_LIBS_LINK_EXTS)"; \ for j in $${tmp:-x}; do \ ( set -x; rm -f lib$$i$$j ); \ done; \ fi; \ ( set -x; rm -f lib$$i$(SHLIB_EXT) ); \ if expr "$(PLATFORM)" : "Cygwin" >/dev/null; then \ ( set -x; rm -f cyg$$i$(SHLIB_EXT) lib$$i$(SHLIB_EXT).a ); \ fi; \ done link-shared: @ set -e; for i in $(SHLIBDIRS); do \ $(MAKE) -f $(HERE)/Makefile.shared -e $(BUILDENV) \ LIBNAME=$$i LIBVERSION=$(SHLIB_MAJOR).$(SHLIB_MINOR) \ LIBCOMPATVERSIONS=";$(SHLIB_VERSION_HISTORY)" \ symlink.$(SHLIB_TARGET); \ libs="$$libs -l$$i"; \ done build-shared: do_$(SHLIB_TARGET) link-shared do_$(SHLIB_TARGET): @ set -e; libs='-L. $(SHLIBDEPS)'; for i in $(SHLIBDIRS); do \ if [ "$$i" = "ssl" -a -n "$(LIBKRB5)" ]; then \ libs="$(LIBKRB5) $$libs"; \ fi; \ $(CLEARENV) && $(MAKE) -f Makefile.shared -e $(BUILDENV) \ LIBNAME=$$i LIBVERSION=$(SHLIB_MAJOR).$(SHLIB_MINOR) \ LIBCOMPATVERSIONS=";$(SHLIB_VERSION_HISTORY)" \ LIBDEPS="$$libs $(EX_LIBS)" \ link_a.$(SHLIB_TARGET); \ libs="-l$$i $$libs"; \ done libcrypto.pc: Makefile @ ( echo 'prefix=$(INSTALLTOP)'; \ echo 'exec_prefix=$${prefix}'; \ echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \ echo 'includedir=$${prefix}/include'; \ echo 'enginesdir=$${libdir}/engines'; \ echo ''; \ echo 'Name: OpenSSL-libcrypto'; \ echo 'Description: OpenSSL cryptography library'; \ echo 'Version: '$(VERSION); \ echo 'Requires: '; \ echo 'Libs: -L$${libdir} -lcrypto'; \ echo 'Libs.private: $(EX_LIBS)'; \ echo 'Cflags: -I$${includedir} $(KRB5_INCLUDES)' ) > libcrypto.pc libssl.pc: Makefile @ ( echo 'prefix=$(INSTALLTOP)'; \ echo 'exec_prefix=$${prefix}'; \ echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \ echo 'includedir=$${prefix}/include'; \ echo ''; \ echo 'Name: OpenSSL-libssl'; \ echo 'Description: Secure Sockets Layer and cryptography libraries'; \ echo 'Version: '$(VERSION); \ echo 'Requires.private: libcrypto'; \ echo 'Libs: -L$${libdir} -lssl'; \ echo 'Libs.private: $(EX_LIBS)'; \ echo 'Cflags: -I$${includedir} $(KRB5_INCLUDES)' ) > libssl.pc openssl.pc: Makefile @ ( echo 'prefix=$(INSTALLTOP)'; \ echo 'exec_prefix=$${prefix}'; \ echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \ echo 'includedir=$${prefix}/include'; \ echo ''; \ echo 'Name: OpenSSL'; \ echo 'Description: Secure Sockets Layer and cryptography libraries and tools'; \ echo 'Version: '$(VERSION); \ echo 'Requires: libssl libcrypto' ) > openssl.pc Makefile: Makefile.org Configure config @echo "Makefile is older than Makefile.org, Configure or config." @echo "Reconfigure the source tree (via './config' or 'perl Configure'), please." @false libclean: rm -f *.map *.so *.so.* *.dylib *.dll engines/*.so engines/*.dll engines/*.dylib *.a engines/*.a */lib */*/lib clean: libclean rm -f shlib/*.o *.o core a.out fluff rehash.time testlog make.log cctest cctest.c @set -e; target=clean; $(RECURSIVE_BUILD_CMD) rm -f $(LIBS) rm -f openssl.pc libssl.pc libcrypto.pc rm -f speed.* .pure rm -f $(TARFILE) @set -e; for i in $(ONEDIRS) ;\ do \ rm -fr $$i/*; \ done +distclean: clean + -$(RM) `find . -name .git -prune -o -type l -print` + $(RM) apps/CA.pl + $(RM) test/evptests.txt test/newkey.pem test/testkey.pem test/testreq.pem + $(RM) tools/c_rehash + $(RM) crypto/opensslconf.h + $(RM) Makefile Makefile.bak + makefile.one: files $(PERL) util/mk1mf.pl >makefile.one; \ sh util/do_ms.sh files: $(PERL) $(TOP)/util/files.pl Makefile > $(TOP)/MINFO @set -e; target=files; $(RECURSIVE_BUILD_CMD) links: @$(PERL) $(TOP)/util/mkdir-p.pl include/openssl @$(PERL) $(TOP)/util/mklink.pl include/openssl $(EXHEADER) @set -e; target=links; $(RECURSIVE_BUILD_CMD) gentests: @(cd test && echo "generating dummy tests (if needed)..." && \ $(CLEARENV) && $(MAKE) -e $(BUILDENV) TESTS='$(TESTS)' OPENSSL_DEBUG_MEMORY=on generate ); dclean: rm -rf *.bak include/openssl certs/.0 @set -e; target=dclean; $(RECURSIVE_BUILD_CMD) rehash: rehash.time rehash.time: certs apps @if [ -z "$(CROSS_COMPILE)" ]; then \ (OPENSSL="`pwd`/util/opensslwrap.sh"; \ [ -x "apps/openssl.exe" ] && OPENSSL="apps/openssl.exe" || :; \ OPENSSL_DEBUG_MEMORY=on; \ export OPENSSL OPENSSL_DEBUG_MEMORY; \ $(PERL) tools/c_rehash certs/demo) && \ touch rehash.time; \ else :; fi test: tests tests: rehash @(cd test && echo "testing..." && \ $(CLEARENV) && $(MAKE) -e $(BUILDENV) TOP=.. TESTS='$(TESTS)' OPENSSL_DEBUG_MEMORY=on OPENSSL_CONF=../apps/openssl.cnf tests ); OPENSSL_CONF=apps/openssl.cnf util/opensslwrap.sh version -a report: @$(PERL) util/selftest.pl update: errors stacks util/libeay.num util/ssleay.num TABLE @set -e; target=update; $(RECURSIVE_BUILD_CMD) depend: @set -e; target=depend; $(RECURSIVE_BUILD_CMD) lint: @set -e; target=lint; $(RECURSIVE_BUILD_CMD) tags: rm -f TAGS find . -name '[^.]*.[ch]' | xargs etags -a errors: $(PERL) util/ck_errf.pl -strict */*.c */*/*.c $(PERL) util/mkerr.pl -recurse -write (cd engines; $(MAKE) PERL=$(PERL) errors) stacks: $(PERL) util/mkstack.pl -write util/libeay.num:: $(PERL) util/mkdef.pl crypto update util/ssleay.num:: $(PERL) util/mkdef.pl ssl update TABLE: Configure (echo 'Output of `Configure TABLE'"':"; \ $(PERL) Configure TABLE) > TABLE # Build distribution tar-file. As the list of files returned by "find" is # pretty long, on several platforms a "too many arguments" error or similar # would occur. Therefore the list of files is temporarily stored into a file # and read directly, requiring GNU-Tar. Call "make TAR=gtar dist" if the normal # tar does not support the --files-from option. TAR_COMMAND=$(TAR) $(TARFLAGS) --files-from $(TARFILE).list \ --owner 0 --group 0 \ --transform 's|^|$(NAME)/|' \ -cvf - $(TARFILE).list: find * \! -name STATUS \! -name TABLE \! -name '*.o' \! -name '*.a' \ \! -name '*.so' \! -name '*.so.*' \! -name 'openssl' \ \( \! -name '*test' -o -name bctest -o -name pod2mantest \) \ \! -name '.#*' \! -name '*~' \! -type l \ | sort > $(TARFILE).list tar: $(TARFILE).list find . -type d -print | xargs chmod 755 find . -type f -print | xargs chmod a+r find . -type f -perm -0100 -print | xargs chmod a+x $(TAR_COMMAND) | gzip --best > $(TARFILE).gz rm -f $(TARFILE).list ls -l $(TARFILE).gz tar-snap: $(TARFILE).list $(TAR_COMMAND) > $(TARFILE) rm -f $(TARFILE).list ls -l $(TARFILE) dist: $(PERL) Configure dist @$(MAKE) SDIRS='$(SDIRS)' clean @$(MAKE) TAR='$(TAR)' TARFLAGS='$(TARFLAGS)' $(DISTTARVARS) tar install: all install_docs install_sw install_sw: @$(PERL) $(TOP)/util/mkdir-p.pl $(INSTALL_PREFIX)$(INSTALLTOP)/bin \ $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR) \ $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/engines \ $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig \ $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl \ $(INSTALL_PREFIX)$(OPENSSLDIR)/misc \ $(INSTALL_PREFIX)$(OPENSSLDIR)/certs \ $(INSTALL_PREFIX)$(OPENSSLDIR)/private @set -e; headerlist="$(EXHEADER)"; for i in $$headerlist;\ do \ (cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i; \ chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i ); \ done; @set -e; target=install; $(RECURSIVE_BUILD_CMD) @set -e; liblist="$(LIBS)"; for i in $$liblist ;\ do \ if [ -f "$$i" ]; then \ ( echo installing $$i; \ cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \ $(RANLIB) $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \ chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \ mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i ); \ fi; \ done; @set -e; if [ -n "$(SHARED_LIBS)" ]; then \ tmp="$(SHARED_LIBS)"; \ for i in $${tmp:-x}; \ do \ if [ -f "$$i" -o -f "$$i.a" ]; then \ ( echo installing $$i; \ if expr "$(PLATFORM)" : "Cygwin" >/dev/null; then \ c=`echo $$i | sed 's/^lib\(.*\)\.dll\.a/cyg\1-$(SHLIB_VERSION_NUMBER).dll/'`; \ cp $$c $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$c.new; \ chmod 755 $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$c.new; \ mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$c.new $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$c; \ cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \ chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \ mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i; \ else \ cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \ chmod 555 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new; \ mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i.new $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/$$i; \ fi ); \ if expr $(PLATFORM) : 'mingw' > /dev/null; then \ ( case $$i in \ *crypto*) i=libeay32.dll;; \ *ssl*) i=ssleay32.dll;; \ esac; \ echo installing $$i; \ cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i.new; \ chmod 755 $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i.new; \ mv -f $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i.new $(INSTALL_PREFIX)$(INSTALLTOP)/bin/$$i ); \ fi; \ fi; \ done; \ ( here="`pwd`"; \ cd $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR); \ $(MAKE) -f $$here/Makefile HERE="$$here" link-shared ); \ if [ "$(INSTALLTOP)" != "/usr" ]; then \ echo 'OpenSSL shared libraries have been installed in:'; \ echo ' $(INSTALLTOP)'; \ echo ''; \ sed -e '1,/^$$/d' doc/openssl-shared.txt; \ fi; \ fi cp libcrypto.pc $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/libcrypto.pc cp libssl.pc $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/libssl.pc cp openssl.pc $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/openssl.pc install_html_docs: here="`pwd`"; \ filecase=; \ case "$(PLATFORM)" in DJGPP|Cygwin*|mingw*|darwin*-*-cc) \ filecase=-i; \ esac; \ for subdir in apps crypto ssl; do \ mkdir -p $(INSTALL_PREFIX)$(HTMLDIR)/$$subdir; \ for i in doc/$$subdir/*.pod; do \ fn=`basename $$i .pod`; \ echo "installing html/$$fn.$(HTMLSUFFIX)"; \ cat $$i \ | sed -r 's/L<([^)]*)(\([0-9]\))?\|([^)]*)(\([0-9]\))?>/L<\1|\3>/g' \ | pod2html --podroot=doc --htmlroot=.. --podpath=apps:crypto:ssl \ | sed -r 's/ $(INSTALL_PREFIX)$(HTMLDIR)/$$subdir/$$fn.$(HTMLSUFFIX); \ $(PERL) util/extract-names.pl < $$i | \ grep -v $$filecase "^$$fn\$$" | \ (cd $(INSTALL_PREFIX)$(HTMLDIR)/$$subdir; \ while read n; do \ PLATFORM=$(PLATFORM) $$here/util/point.sh $$fn.$(HTMLSUFFIX) "$$n".$(HTMLSUFFIX); \ done); \ done; \ done install_docs: @$(PERL) $(TOP)/util/mkdir-p.pl \ $(INSTALL_PREFIX)$(MANDIR)/man1 \ $(INSTALL_PREFIX)$(MANDIR)/man3 \ $(INSTALL_PREFIX)$(MANDIR)/man5 \ $(INSTALL_PREFIX)$(MANDIR)/man7 @pod2man="`cd ./util; ./pod2mantest $(PERL)`"; \ here="`pwd`"; \ filecase=; \ case "$(PLATFORM)" in DJGPP|Cygwin*|mingw*|darwin*-*-cc) \ filecase=-i; \ esac; \ set -e; for i in doc/apps/*.pod; do \ fn=`basename $$i .pod`; \ sec=`$(PERL) util/extract-section.pl 1 < $$i`; \ echo "installing man$$sec/$$fn.$${sec}$(MANSUFFIX)"; \ (cd `$(PERL) util/dirname.pl $$i`; \ sh -c "$$pod2man \ --section=$$sec --center=OpenSSL \ --release=$(VERSION) `basename $$i`") \ > $(INSTALL_PREFIX)$(MANDIR)/man$$sec/$$fn.$${sec}$(MANSUFFIX); \ $(PERL) util/extract-names.pl < $$i | \ (grep -v $$filecase "^$$fn\$$"; true) | \ (grep -v "[ ]"; true) | \ (cd $(INSTALL_PREFIX)$(MANDIR)/man$$sec/; \ while read n; do \ PLATFORM=$(PLATFORM) $$here/util/point.sh $$fn.$${sec}$(MANSUFFIX) "$$n".$${sec}$(MANSUFFIX); \ done); \ done; \ set -e; for i in doc/crypto/*.pod doc/ssl/*.pod; do \ fn=`basename $$i .pod`; \ sec=`$(PERL) util/extract-section.pl 3 < $$i`; \ echo "installing man$$sec/$$fn.$${sec}$(MANSUFFIX)"; \ (cd `$(PERL) util/dirname.pl $$i`; \ sh -c "$$pod2man \ --section=$$sec --center=OpenSSL \ --release=$(VERSION) `basename $$i`") \ > $(INSTALL_PREFIX)$(MANDIR)/man$$sec/$$fn.$${sec}$(MANSUFFIX); \ $(PERL) util/extract-names.pl < $$i | \ (grep -v $$filecase "^$$fn\$$"; true) | \ (grep -v "[ ]"; true) | \ (cd $(INSTALL_PREFIX)$(MANDIR)/man$$sec/; \ while read n; do \ PLATFORM=$(PLATFORM) $$here/util/point.sh $$fn.$${sec}$(MANSUFFIX) "$$n".$${sec}$(MANSUFFIX); \ done); \ done # DO NOT DELETE THIS LINE -- make depend depends on it. Index: vendor-crypto/openssl/dist/NEWS =================================================================== --- vendor-crypto/openssl/dist/NEWS (revision 318896) +++ vendor-crypto/openssl/dist/NEWS (revision 318897) @@ -1,799 +1,803 @@ NEWS ==== 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.0.2k and OpenSSL 1.0.2l [25 May 2017] + + o config now recognises 64-bit mingw and chooses mingw64 instead of mingw + Major changes between OpenSSL 1.0.2j and OpenSSL 1.0.2k [26 Jan 2017] o Truncated packet could crash via OOB read (CVE-2017-3731) o BN_mod_exp may produce incorrect results on x86_64 (CVE-2017-3732) o Montgomery multiplication may produce incorrect results (CVE-2016-7055) Major changes between OpenSSL 1.0.2i and OpenSSL 1.0.2j [26 Sep 2016] o Missing CRL sanity check (CVE-2016-7052) Major changes between OpenSSL 1.0.2h and OpenSSL 1.0.2i [22 Sep 2016] o OCSP Status Request extension unbounded memory growth (CVE-2016-6304) o SWEET32 Mitigation (CVE-2016-2183) o OOB write in MDC2_Update() (CVE-2016-6303) o Malformed SHA512 ticket DoS (CVE-2016-6302) o OOB write in BN_bn2dec() (CVE-2016-2182) o OOB read in TS_OBJ_print_bio() (CVE-2016-2180) o Pointer arithmetic undefined behaviour (CVE-2016-2177) o Constant time flag not preserved in DSA signing (CVE-2016-2178) o DTLS buffered message DoS (CVE-2016-2179) o DTLS replay protection DoS (CVE-2016-2181) o Certificate message OOB reads (CVE-2016-6306) Major changes between OpenSSL 1.0.2g and OpenSSL 1.0.2h [3 May 2016] o Prevent padding oracle in AES-NI CBC MAC check (CVE-2016-2107) o Fix EVP_EncodeUpdate overflow (CVE-2016-2105) o Fix EVP_EncryptUpdate overflow (CVE-2016-2106) o Prevent ASN.1 BIO excessive memory allocation (CVE-2016-2109) o EBCDIC overread (CVE-2016-2176) o Modify behavior of ALPN to invoke callback after SNI/servername callback, such that updates to the SSL_CTX affect ALPN. o Remove LOW from the DEFAULT cipher list. This removes singles DES from the default. o Only remove the SSLv2 methods with the no-ssl2-method option. Major changes between OpenSSL 1.0.2f and OpenSSL 1.0.2g [1 Mar 2016] o Disable weak ciphers in SSLv3 and up in default builds of OpenSSL. o Disable SSLv2 default build, default negotiation and weak ciphers (CVE-2016-0800) o Fix a double-free in DSA code (CVE-2016-0705) o Disable SRP fake user seed to address a server memory leak (CVE-2016-0798) o Fix BN_hex2bn/BN_dec2bn NULL pointer deref/heap corruption (CVE-2016-0797) o Fix memory issues in BIO_*printf functions (CVE-2016-0799) o Fix side channel attack on modular exponentiation (CVE-2016-0702) Major changes between OpenSSL 1.0.2e and OpenSSL 1.0.2f [28 Jan 2016] o DH small subgroups (CVE-2016-0701) o SSLv2 doesn't block disabled ciphers (CVE-2015-3197) Major changes between OpenSSL 1.0.2d and OpenSSL 1.0.2e [3 Dec 2015] o BN_mod_exp may produce incorrect results on x86_64 (CVE-2015-3193) o Certificate verify crash with missing PSS parameter (CVE-2015-3194) o X509_ATTRIBUTE memory leak (CVE-2015-3195) o Rewrite EVP_DecodeUpdate (base64 decoding) to fix several bugs o In DSA_generate_parameters_ex, if the provided seed is too short, return an error Major changes between OpenSSL 1.0.2c and OpenSSL 1.0.2d [9 Jul 2015] o Alternate chains certificate forgery (CVE-2015-1793) o Race condition handling PSK identify hint (CVE-2015-3196) Major changes between OpenSSL 1.0.2b and OpenSSL 1.0.2c [12 Jun 2015] o Fix HMAC ABI incompatibility Major changes between OpenSSL 1.0.2a and OpenSSL 1.0.2b [11 Jun 2015] o Malformed ECParameters causes infinite loop (CVE-2015-1788) o Exploitable out-of-bounds read in X509_cmp_time (CVE-2015-1789) o PKCS7 crash with missing EnvelopedContent (CVE-2015-1790) o CMS verify infinite loop with unknown hash function (CVE-2015-1792) o Race condition handling NewSessionTicket (CVE-2015-1791) Major changes between OpenSSL 1.0.2 and OpenSSL 1.0.2a [19 Mar 2015] o OpenSSL 1.0.2 ClientHello sigalgs DoS fix (CVE-2015-0291) o Multiblock corrupted pointer fix (CVE-2015-0290) o Segmentation fault in DTLSv1_listen fix (CVE-2015-0207) o Segmentation fault in ASN1_TYPE_cmp fix (CVE-2015-0286) o Segmentation fault for invalid PSS parameters fix (CVE-2015-0208) o ASN.1 structure reuse memory corruption fix (CVE-2015-0287) o PKCS7 NULL pointer dereferences fix (CVE-2015-0289) o DoS via reachable assert in SSLv2 servers fix (CVE-2015-0293) o Empty CKE with client auth and DHE fix (CVE-2015-1787) o Handshake with unseeded PRNG fix (CVE-2015-0285) o Use After Free following d2i_ECPrivatekey error fix (CVE-2015-0209) o X509_to_X509_REQ NULL pointer deref fix (CVE-2015-0288) o Removed the export ciphers from the DEFAULT ciphers Major changes between OpenSSL 1.0.1l and OpenSSL 1.0.2 [22 Jan 2015]: o Suite B support for TLS 1.2 and DTLS 1.2 o Support for DTLS 1.2 o TLS automatic EC curve selection. o API to set TLS supported signature algorithms and curves o SSL_CONF configuration API. o TLS Brainpool support. o ALPN support. o CMS support for RSA-PSS, RSA-OAEP, ECDH and X9.42 DH. Major changes between OpenSSL 1.0.1k and OpenSSL 1.0.1l [15 Jan 2015] o Build fixes for the Windows and OpenVMS platforms Major changes between OpenSSL 1.0.1j and OpenSSL 1.0.1k [8 Jan 2015] o Fix for CVE-2014-3571 o Fix for CVE-2015-0206 o Fix for CVE-2014-3569 o Fix for CVE-2014-3572 o Fix for CVE-2015-0204 o Fix for CVE-2015-0205 o Fix for CVE-2014-8275 o Fix for CVE-2014-3570 Major changes between OpenSSL 1.0.1i and OpenSSL 1.0.1j [15 Oct 2014] o Fix for CVE-2014-3513 o Fix for CVE-2014-3567 o Mitigation for CVE-2014-3566 (SSL protocol vulnerability) o Fix for CVE-2014-3568 Major changes between OpenSSL 1.0.1h and OpenSSL 1.0.1i [6 Aug 2014] o Fix for CVE-2014-3512 o Fix for CVE-2014-3511 o Fix for CVE-2014-3510 o Fix for CVE-2014-3507 o Fix for CVE-2014-3506 o Fix for CVE-2014-3505 o Fix for CVE-2014-3509 o Fix for CVE-2014-5139 o Fix for CVE-2014-3508 Major changes between OpenSSL 1.0.1g and OpenSSL 1.0.1h [5 Jun 2014] o Fix for CVE-2014-0224 o Fix for CVE-2014-0221 o Fix for CVE-2014-0198 o Fix for CVE-2014-0195 o Fix for CVE-2014-3470 o Fix for CVE-2010-5298 Major changes between OpenSSL 1.0.1f and OpenSSL 1.0.1g [7 Apr 2014] o Fix for CVE-2014-0160 o Add TLS padding extension workaround for broken servers. o Fix for CVE-2014-0076 Major changes between OpenSSL 1.0.1e and OpenSSL 1.0.1f [6 Jan 2014] o Don't include gmt_unix_time in TLS server and client random values o Fix for TLS record tampering bug CVE-2013-4353 o Fix for TLS version checking bug CVE-2013-6449 o Fix for DTLS retransmission bug CVE-2013-6450 Major changes between OpenSSL 1.0.1d and OpenSSL 1.0.1e [11 Feb 2013]: o Corrected fix for CVE-2013-0169 Major changes between OpenSSL 1.0.1c and OpenSSL 1.0.1d [4 Feb 2013]: o Fix renegotiation in TLS 1.1, 1.2 by using the correct TLS version. o Include the fips configuration module. o Fix OCSP bad key DoS attack CVE-2013-0166 o Fix for SSL/TLS/DTLS CBC plaintext recovery attack CVE-2013-0169 o Fix for TLS AESNI record handling flaw CVE-2012-2686 Major changes between OpenSSL 1.0.1b and OpenSSL 1.0.1c [10 May 2012]: o Fix TLS/DTLS record length checking bug CVE-2012-2333 o Don't attempt to use non-FIPS composite ciphers in FIPS mode. Major changes between OpenSSL 1.0.1a and OpenSSL 1.0.1b [26 Apr 2012]: o Fix compilation error on non-x86 platforms. o Make FIPS capable OpenSSL ciphers work in non-FIPS mode. o Fix SSL_OP_NO_TLSv1_1 clash with SSL_OP_ALL in OpenSSL 1.0.0 Major changes between OpenSSL 1.0.1 and OpenSSL 1.0.1a [19 Apr 2012]: o Fix for ASN1 overflow bug CVE-2012-2110 o Workarounds for some servers that hang on long client hellos. o Fix SEGV in AES code. Major changes between OpenSSL 1.0.0h and OpenSSL 1.0.1 [14 Mar 2012]: o TLS/DTLS heartbeat support. o SCTP support. o RFC 5705 TLS key material exporter. o RFC 5764 DTLS-SRTP negotiation. o Next Protocol Negotiation. o PSS signatures in certificates, requests and CRLs. o Support for password based recipient info for CMS. o Support TLS v1.2 and TLS v1.1. o Preliminary FIPS capability for unvalidated 2.0 FIPS module. o SRP support. Major changes between OpenSSL 1.0.0g and OpenSSL 1.0.0h [12 Mar 2012]: o Fix for CMS/PKCS#7 MMA CVE-2012-0884 o Corrected fix for CVE-2011-4619 o Various DTLS fixes. Major changes between OpenSSL 1.0.0f and OpenSSL 1.0.0g [18 Jan 2012]: o Fix for DTLS DoS issue CVE-2012-0050 Major changes between OpenSSL 1.0.0e and OpenSSL 1.0.0f [4 Jan 2012]: o Fix for DTLS plaintext recovery attack CVE-2011-4108 o Clear block padding bytes of SSL 3.0 records CVE-2011-4576 o Only allow one SGC handshake restart for SSL/TLS CVE-2011-4619 o Check parameters are not NULL in GOST ENGINE CVE-2012-0027 o Check for malformed RFC3779 data CVE-2011-4577 Major changes between OpenSSL 1.0.0d and OpenSSL 1.0.0e [6 Sep 2011]: o Fix for CRL vulnerability issue CVE-2011-3207 o Fix for ECDH crashes CVE-2011-3210 o Protection against EC timing attacks. o Support ECDH ciphersuites for certificates using SHA2 algorithms. o Various DTLS fixes. Major changes between OpenSSL 1.0.0c and OpenSSL 1.0.0d [8 Feb 2011]: o Fix for security issue CVE-2011-0014 Major changes between OpenSSL 1.0.0b and OpenSSL 1.0.0c [2 Dec 2010]: o Fix for security issue CVE-2010-4180 o Fix for CVE-2010-4252 o Fix mishandling of absent EC point format extension. o Fix various platform compilation issues. o Corrected fix for security issue CVE-2010-3864. Major changes between OpenSSL 1.0.0a and OpenSSL 1.0.0b [16 Nov 2010]: o Fix for security issue CVE-2010-3864. o Fix for CVE-2010-2939 o Fix WIN32 build system for GOST ENGINE. Major changes between OpenSSL 1.0.0 and OpenSSL 1.0.0a [1 Jun 2010]: o Fix for security issue CVE-2010-1633. o GOST MAC and CFB fixes. Major changes between OpenSSL 0.9.8n and OpenSSL 1.0.0 [29 Mar 2010]: o RFC3280 path validation: sufficient to process PKITS tests. o Integrated support for PVK files and keyblobs. o Change default private key format to PKCS#8. o CMS support: able to process all examples in RFC4134 o Streaming ASN1 encode support for PKCS#7 and CMS. o Multiple signer and signer add support for PKCS#7 and CMS. o ASN1 printing support. o Whirlpool hash algorithm added. o RFC3161 time stamp support. o New generalised public key API supporting ENGINE based algorithms. o New generalised public key API utilities. o New ENGINE supporting GOST algorithms. o SSL/TLS GOST ciphersuite support. o PKCS#7 and CMS GOST support. o RFC4279 PSK ciphersuite support. o Supported points format extension for ECC ciphersuites. o ecdsa-with-SHA224/256/384/512 signature types. o dsa-with-SHA224 and dsa-with-SHA256 signature types. o Opaque PRF Input TLS extension support. o Updated time routines to avoid OS limitations. Major changes between OpenSSL 0.9.8m and OpenSSL 0.9.8n [24 Mar 2010]: o CFB cipher definition fixes. o Fix security issues CVE-2010-0740 and CVE-2010-0433. Major changes between OpenSSL 0.9.8l and OpenSSL 0.9.8m [25 Feb 2010]: o Cipher definition fixes. o Workaround for slow RAND_poll() on some WIN32 versions. o Remove MD2 from algorithm tables. o SPKAC handling fixes. o Support for RFC5746 TLS renegotiation extension. o Compression memory leak fixed. o Compression session resumption fixed. o Ticket and SNI coexistence fixes. o Many fixes to DTLS handling. Major changes between OpenSSL 0.9.8k and OpenSSL 0.9.8l [5 Nov 2009]: o Temporary work around for CVE-2009-3555: disable renegotiation. Major changes between OpenSSL 0.9.8j and OpenSSL 0.9.8k [25 Mar 2009]: o Fix various build issues. o Fix security issues (CVE-2009-0590, CVE-2009-0591, CVE-2009-0789) Major changes between OpenSSL 0.9.8i and OpenSSL 0.9.8j [7 Jan 2009]: o Fix security issue (CVE-2008-5077) o Merge FIPS 140-2 branch code. Major changes between OpenSSL 0.9.8g and OpenSSL 0.9.8h [28 May 2008]: o CryptoAPI ENGINE support. o Various precautionary measures. o Fix for bugs affecting certificate request creation. o Support for local machine keyset attribute in PKCS#12 files. Major changes between OpenSSL 0.9.8f and OpenSSL 0.9.8g [19 Oct 2007]: o Backport of CMS functionality to 0.9.8. o Fixes for bugs introduced with 0.9.8f. Major changes between OpenSSL 0.9.8e and OpenSSL 0.9.8f [11 Oct 2007]: o Add gcc 4.2 support. o Add support for AES and SSE2 assembly lanugauge optimization for VC++ build. o Support for RFC4507bis and server name extensions if explicitly selected at compile time. o DTLS improvements. o RFC4507bis support. o TLS Extensions support. Major changes between OpenSSL 0.9.8d and OpenSSL 0.9.8e [23 Feb 2007]: o Various ciphersuite selection fixes. o RFC3779 support. Major changes between OpenSSL 0.9.8c and OpenSSL 0.9.8d [28 Sep 2006]: o Introduce limits to prevent malicious key DoS (CVE-2006-2940) o Fix security issues (CVE-2006-2937, CVE-2006-3737, CVE-2006-4343) o Changes to ciphersuite selection algorithm Major changes between OpenSSL 0.9.8b and OpenSSL 0.9.8c [5 Sep 2006]: o Fix Daniel Bleichenbacher forged signature attack, CVE-2006-4339 o New cipher Camellia Major changes between OpenSSL 0.9.8a and OpenSSL 0.9.8b [4 May 2006]: o Cipher string fixes. o Fixes for VC++ 2005. o Updated ECC cipher suite support. o New functions EVP_CIPHER_CTX_new() and EVP_CIPHER_CTX_free(). o Zlib compression usage fixes. o Built in dynamic engine compilation support on Win32. o Fixes auto dynamic engine loading in Win32. Major changes between OpenSSL 0.9.8 and OpenSSL 0.9.8a [11 Oct 2005]: o Fix potential SSL 2.0 rollback, CVE-2005-2969 o Extended Windows CE support Major changes between OpenSSL 0.9.7g and OpenSSL 0.9.8 [5 Jul 2005]: o Major work on the BIGNUM library for higher efficiency and to make operations more streamlined and less contradictory. This is the result of a major audit of the BIGNUM library. o Addition of BIGNUM functions for fields GF(2^m) and NIST curves, to support the Elliptic Crypto functions. o Major work on Elliptic Crypto; ECDH and ECDSA added, including the use through EVP, X509 and ENGINE. o New ASN.1 mini-compiler that's usable through the OpenSSL configuration file. o Added support for ASN.1 indefinite length constructed encoding. o New PKCS#12 'medium level' API to manipulate PKCS#12 files. o Complete rework of shared library construction and linking programs with shared or static libraries, through a separate Makefile.shared. o Rework of the passing of parameters from one Makefile to another. o Changed ENGINE framework to load dynamic engine modules automatically from specifically given directories. o New structure and ASN.1 functions for CertificatePair. o Changed the ZLIB compression method to be stateful. o Changed the key-generation and primality testing "progress" mechanism to take a structure that contains the ticker function and an argument. o New engine module: GMP (performs private key exponentiation). o New engine module: VIA PadLOck ACE extension in VIA C3 Nehemiah processors. o Added support for IPv6 addresses in certificate extensions. See RFC 1884, section 2.2. o Added support for certificate policy mappings, policy constraints and name constraints. o Added support for multi-valued AVAs in the OpenSSL configuration file. o Added support for multiple certificates with the same subject in the 'openssl ca' index file. o Make it possible to create self-signed certificates using 'openssl ca -selfsign'. o Make it possible to generate a serial number file with 'openssl ca -create_serial'. o New binary search functions with extended functionality. o New BUF functions. o New STORE structure and library to provide an interface to all sorts of data repositories. Supports storage of public and private keys, certificates, CRLs, numbers and arbitrary blobs. This library is unfortunately unfinished and unused withing OpenSSL. o New control functions for the error stack. o Changed the PKCS#7 library to support one-pass S/MIME processing. o Added the possibility to compile without old deprecated functionality with the OPENSSL_NO_DEPRECATED macro or the 'no-deprecated' argument to the config and Configure scripts. o Constification of all ASN.1 conversion functions, and other affected functions. o Improved platform support for PowerPC. o New FIPS 180-2 algorithms (SHA-224, -256, -384 and -512). o New X509_VERIFY_PARAM structure to support parametrisation of X.509 path validation. o Major overhaul of RC4 performance on Intel P4, IA-64 and AMD64. o Changed the Configure script to have some algorithms disabled by default. Those can be explicitely enabled with the new argument form 'enable-xxx'. o Change the default digest in 'openssl' commands from MD5 to SHA-1. o Added support for DTLS. o New BIGNUM blinding. o Added support for the RSA-PSS encryption scheme o Added support for the RSA X.931 padding. o Added support for BSD sockets on NetWare. o Added support for files larger than 2GB. o Added initial support for Win64. o Added alternate pkg-config files. Major changes between OpenSSL 0.9.7l and OpenSSL 0.9.7m [23 Feb 2007]: o FIPS 1.1.1 module linking. o Various ciphersuite selection fixes. Major changes between OpenSSL 0.9.7k and OpenSSL 0.9.7l [28 Sep 2006]: o Introduce limits to prevent malicious key DoS (CVE-2006-2940) o Fix security issues (CVE-2006-2937, CVE-2006-3737, CVE-2006-4343) Major changes between OpenSSL 0.9.7j and OpenSSL 0.9.7k [5 Sep 2006]: o Fix Daniel Bleichenbacher forged signature attack, CVE-2006-4339 Major changes between OpenSSL 0.9.7i and OpenSSL 0.9.7j [4 May 2006]: o Visual C++ 2005 fixes. o Update Windows build system for FIPS. Major changes between OpenSSL 0.9.7h and OpenSSL 0.9.7i [14 Oct 2005]: o Give EVP_MAX_MD_SIZE it's old value, except for a FIPS build. Major changes between OpenSSL 0.9.7g and OpenSSL 0.9.7h [11 Oct 2005]: o Fix SSL 2.0 Rollback, CVE-2005-2969 o Allow use of fixed-length exponent on DSA signing o Default fixed-window RSA, DSA, DH private-key operations Major changes between OpenSSL 0.9.7f and OpenSSL 0.9.7g [11 Apr 2005]: o More compilation issues fixed. o Adaptation to more modern Kerberos API. o Enhanced or corrected configuration for Solaris64, Mingw and Cygwin. o Enhanced x86_64 assembler BIGNUM module. o More constification. o Added processing of proxy certificates (RFC 3820). Major changes between OpenSSL 0.9.7e and OpenSSL 0.9.7f [22 Mar 2005]: o Several compilation issues fixed. o Many memory allocation failure checks added. o Improved comparison of X509 Name type. o Mandatory basic checks on certificates. o Performance improvements. Major changes between OpenSSL 0.9.7d and OpenSSL 0.9.7e [25 Oct 2004]: o Fix race condition in CRL checking code. o Fixes to PKCS#7 (S/MIME) code. Major changes between OpenSSL 0.9.7c and OpenSSL 0.9.7d [17 Mar 2004]: o Security: Fix Kerberos ciphersuite SSL/TLS handshaking bug o Security: Fix null-pointer assignment in do_change_cipher_spec() o Allow multiple active certificates with same subject in CA index o Multiple X509 verification fixes o Speed up HMAC and other operations Major changes between OpenSSL 0.9.7b and OpenSSL 0.9.7c [30 Sep 2003]: o Security: fix various ASN1 parsing bugs. o New -ignore_err option to OCSP utility. o Various interop and bug fixes in S/MIME code. o SSL/TLS protocol fix for unrequested client certificates. Major changes between OpenSSL 0.9.7a and OpenSSL 0.9.7b [10 Apr 2003]: o Security: counter the Klima-Pokorny-Rosa extension of Bleichbacher's attack o Security: make RSA blinding default. o Configuration: Irix fixes, AIX fixes, better mingw support. o Support for new platforms: linux-ia64-ecc. o Build: shared library support fixes. o ASN.1: treat domainComponent correctly. o Documentation: fixes and additions. Major changes between OpenSSL 0.9.7 and OpenSSL 0.9.7a [19 Feb 2003]: o Security: Important security related bugfixes. o Enhanced compatibility with MIT Kerberos. o Can be built without the ENGINE framework. o IA32 assembler enhancements. o Support for new platforms: FreeBSD/IA64 and FreeBSD/Sparc64. o Configuration: the no-err option now works properly. o SSL/TLS: now handles manual certificate chain building. o SSL/TLS: certain session ID malfunctions corrected. Major changes between OpenSSL 0.9.6 and OpenSSL 0.9.7 [30 Dec 2002]: o New library section OCSP. o Complete rewrite of ASN1 code. o CRL checking in verify code and openssl utility. o Extension copying in 'ca' utility. o Flexible display options in 'ca' utility. o Provisional support for international characters with UTF8. o Support for external crypto devices ('engine') is no longer a separate distribution. o New elliptic curve library section. o New AES (Rijndael) library section. o Support for new platforms: Windows CE, Tandem OSS, A/UX, AIX 64-bit, Linux x86_64, Linux 64-bit on Sparc v9 o Extended support for some platforms: VxWorks o Enhanced support for shared libraries. o Now only builds PIC code when shared library support is requested. o Support for pkg-config. o Lots of new manuals. o Makes symbolic links to or copies of manuals to cover all described functions. o Change DES API to clean up the namespace (some applications link also against libdes providing similar functions having the same name). Provide macros for backward compatibility (will be removed in the future). o Unify handling of cryptographic algorithms (software and engine) to be available via EVP routines for asymmetric and symmetric ciphers. o NCONF: new configuration handling routines. o Change API to use more 'const' modifiers to improve error checking and help optimizers. o Finally remove references to RSAref. o Reworked parts of the BIGNUM code. o Support for new engines: Broadcom ubsec, Accelerated Encryption Processing, IBM 4758. o A few new engines added in the demos area. o Extended and corrected OID (object identifier) table. o PRNG: query at more locations for a random device, automatic query for EGD style random sources at several locations. o SSL/TLS: allow optional cipher choice according to server's preference. o SSL/TLS: allow server to explicitly set new session ids. o SSL/TLS: support Kerberos cipher suites (RFC2712). Only supports MIT Kerberos for now. o SSL/TLS: allow more precise control of renegotiations and sessions. o SSL/TLS: add callback to retrieve SSL/TLS messages. o SSL/TLS: support AES cipher suites (RFC3268). Major changes between OpenSSL 0.9.6j and OpenSSL 0.9.6k [30 Sep 2003]: o Security: fix various ASN1 parsing bugs. o SSL/TLS protocol fix for unrequested client certificates. Major changes between OpenSSL 0.9.6i and OpenSSL 0.9.6j [10 Apr 2003]: o Security: counter the Klima-Pokorny-Rosa extension of Bleichbacher's attack o Security: make RSA blinding default. o Build: shared library support fixes. Major changes between OpenSSL 0.9.6h and OpenSSL 0.9.6i [19 Feb 2003]: o Important security related bugfixes. Major changes between OpenSSL 0.9.6g and OpenSSL 0.9.6h [5 Dec 2002]: o New configuration targets for Tandem OSS and A/UX. o New OIDs for Microsoft attributes. o Better handling of SSL session caching. o Better comparison of distinguished names. o Better handling of shared libraries in a mixed GNU/non-GNU environment. o Support assembler code with Borland C. o Fixes for length problems. o Fixes for uninitialised variables. o Fixes for memory leaks, some unusual crashes and some race conditions. o Fixes for smaller building problems. o Updates of manuals, FAQ and other instructive documents. Major changes between OpenSSL 0.9.6f and OpenSSL 0.9.6g [9 Aug 2002]: o Important building fixes on Unix. Major changes between OpenSSL 0.9.6e and OpenSSL 0.9.6f [8 Aug 2002]: o Various important bugfixes. Major changes between OpenSSL 0.9.6d and OpenSSL 0.9.6e [30 Jul 2002]: o Important security related bugfixes. o Various SSL/TLS library bugfixes. Major changes between OpenSSL 0.9.6c and OpenSSL 0.9.6d [9 May 2002]: o Various SSL/TLS library bugfixes. o Fix DH parameter generation for 'non-standard' generators. Major changes between OpenSSL 0.9.6b and OpenSSL 0.9.6c [21 Dec 2001]: o Various SSL/TLS library bugfixes. o BIGNUM library fixes. o RSA OAEP and random number generation fixes. o Object identifiers corrected and added. o Add assembler BN routines for IA64. o Add support for OS/390 Unix, UnixWare with gcc, OpenUNIX 8, MIPS Linux; shared library support for Irix, HP-UX. o Add crypto accelerator support for AEP, Baltimore SureWare, Broadcom and Cryptographic Appliance's keyserver [in 0.9.6c-engine release]. Major changes between OpenSSL 0.9.6a and OpenSSL 0.9.6b [9 Jul 2001]: o Security fix: PRNG improvements. o Security fix: RSA OAEP check. o Security fix: Reinsert and fix countermeasure to Bleichbacher's attack. o MIPS bug fix in BIGNUM. o Bug fix in "openssl enc". o Bug fix in X.509 printing routine. o Bug fix in DSA verification routine and DSA S/MIME verification. o Bug fix to make PRNG thread-safe. o Bug fix in RAND_file_name(). o Bug fix in compatibility mode trust settings. o Bug fix in blowfish EVP. o Increase default size for BIO buffering filter. o Compatibility fixes in some scripts. Major changes between OpenSSL 0.9.6 and OpenSSL 0.9.6a [5 Apr 2001]: o Security fix: change behavior of OpenSSL to avoid using environment variables when running as root. o Security fix: check the result of RSA-CRT to reduce the possibility of deducing the private key from an incorrectly calculated signature. o Security fix: prevent Bleichenbacher's DSA attack. o Security fix: Zero the premaster secret after deriving the master secret in DH ciphersuites. o Reimplement SSL_peek(), which had various problems. o Compatibility fix: the function des_encrypt() renamed to des_encrypt1() to avoid clashes with some Unixen libc. o Bug fixes for Win32, HP/UX and Irix. o Bug fixes in BIGNUM, SSL, PKCS#7, PKCS#12, X.509, CONF and memory checking routines. o Bug fixes for RSA operations in threaded environments. o Bug fixes in misc. openssl applications. o Remove a few potential memory leaks. o Add tighter checks of BIGNUM routines. o Shared library support has been reworked for generality. o More documentation. o New function BN_rand_range(). o Add "-rand" option to openssl s_client and s_server. Major changes between OpenSSL 0.9.5a and OpenSSL 0.9.6 [10 Oct 2000]: o Some documentation for BIO and SSL libraries. o Enhanced chain verification using key identifiers. o New sign and verify options to 'dgst' application. o Support for DER and PEM encoded messages in 'smime' application. o New 'rsautl' application, low level RSA utility. o MD4 now included. o Bugfix for SSL rollback padding check. o Support for external crypto devices [1]. o Enhanced EVP interface. [1] The support for external crypto devices is currently a separate distribution. See the file README.ENGINE. Major changes between OpenSSL 0.9.5 and OpenSSL 0.9.5a [1 Apr 2000]: o Bug fixes for Win32, SuSE Linux, NeXTSTEP and FreeBSD 2.2.8 o Shared library support for HPUX and Solaris-gcc o Support of Linux/IA64 o Assembler support for Mingw32 o New 'rand' application o New way to check for existence of algorithms from scripts Major changes between OpenSSL 0.9.4 and OpenSSL 0.9.5 [25 May 2000]: o S/MIME support in new 'smime' command o Documentation for the OpenSSL command line application o Automation of 'req' application o Fixes to make s_client, s_server work under Windows o Support for multiple fieldnames in SPKACs o New SPKAC command line utilty and associated library functions o Options to allow passwords to be obtained from various sources o New public key PEM format and options to handle it o Many other fixes and enhancements to command line utilities o Usable certificate chain verification o Certificate purpose checking o Certificate trust settings o Support of authority information access extension o Extensions in certificate requests o Simplified X509 name and attribute routines o Initial (incomplete) support for international character sets o New DH_METHOD, DSA_METHOD and enhanced RSA_METHOD o Read only memory BIOs and simplified creation function o TLS/SSL protocol bugfixes: Accept TLS 'client hello' in SSL 3.0 record; allow fragmentation and interleaving of handshake and other data o TLS/SSL code now "tolerates" MS SGC o Work around for Netscape client certificate hang bug o RSA_NULL option that removes RSA patent code but keeps other RSA functionality o Memory leak detection now allows applications to add extra information via a per-thread stack o PRNG robustness improved o EGD support o BIGNUM library bug fixes o Faster DSA parameter generation o Enhanced support for Alpha Linux o Experimental MacOS support Major changes between OpenSSL 0.9.3 and OpenSSL 0.9.4 [9 Aug 1999]: o Transparent support for PKCS#8 format private keys: these are used by several software packages and are more secure than the standard form o PKCS#5 v2.0 implementation o Password callbacks have a new void * argument for application data o Avoid various memory leaks o New pipe-like BIO that allows using the SSL library when actual I/O must be handled by the application (BIO pair) Major changes between OpenSSL 0.9.2b and OpenSSL 0.9.3 [24 May 1999]: o Lots of enhancements and cleanups to the Configuration mechanism o RSA OEAP related fixes o Added `openssl ca -revoke' option for revoking a certificate o Source cleanups: const correctness, type-safe stacks and ASN.1 SETs o Source tree cleanups: removed lots of obsolete files o Thawte SXNet, certificate policies and CRL distribution points extension support o Preliminary (experimental) S/MIME support o Support for ASN.1 UTF8String and VisibleString o Full integration of PKCS#12 code o Sparc assembler bignum implementation, optimized hash functions o Option to disable selected ciphers Major changes between OpenSSL 0.9.1c and OpenSSL 0.9.2b [22 Mar 1999]: o Fixed a security hole related to session resumption o Fixed RSA encryption routines for the p < q case o "ALL" in cipher lists now means "everything except NULL ciphers" o Support for Triple-DES CBCM cipher o Support of Optimal Asymmetric Encryption Padding (OAEP) for RSA o First support for new TLSv1 ciphers o Added a few new BIOs (syslog BIO, reliable BIO) o Extended support for DSA certificate/keys. o Extended support for Certificate Signing Requests (CSR) o Initial support for X.509v3 extensions o Extended support for compression inside the SSL record layer o Overhauled Win32 builds o Cleanups and fixes to the Big Number (BN) library o Support for ASN.1 GeneralizedTime o Splitted ASN.1 SETs from SEQUENCEs o ASN1 and PEM support for Netscape Certificate Sequences o Overhauled Perl interface o Lots of source tree cleanups. o Lots of memory leak fixes. o Lots of bug fixes. Major changes between SSLeay 0.9.0b and OpenSSL 0.9.1c [23 Dec 1998]: o Integration of the popular NO_RSA/NO_DSA patches o Initial support for compression inside the SSL record layer o Added BIO proxy and filtering functionality o Extended Big Number (BN) library o Added RIPE MD160 message digest o Addeed support for RC2/64bit cipher o Extended ASN.1 parser routines o Adjustations of the source tree for CVS o Support for various new platforms Index: vendor-crypto/openssl/dist/README =================================================================== --- vendor-crypto/openssl/dist/README (revision 318896) +++ vendor-crypto/openssl/dist/README (revision 318897) @@ -1,101 +1,101 @@ - OpenSSL 1.0.2k 26 Jan 2017 + OpenSSL 1.0.2l 25 May 2017 Copyright (c) 1998-2015 The OpenSSL Project Copyright (c) 1995-1998 Eric A. Young, Tim J. Hudson All rights reserved. DESCRIPTION ----------- The OpenSSL Project is a collaborative effort to develop a robust, commercial-grade, fully featured, and Open Source toolkit implementing the Secure Sockets Layer (SSLv3) and Transport Layer Security (TLS) protocols as well as a full-strength general purpose cryptograpic library. The project is managed by a worldwide community of volunteers that use the Internet to communicate, plan, and develop the OpenSSL toolkit and its related documentation. OpenSSL is descended from the SSLeay library developed by Eric A. Young and Tim J. Hudson. The OpenSSL toolkit is licensed under a dual-license (the OpenSSL license plus the SSLeay license), which means that you are free to get and use it for commercial and non-commercial purposes as long as you fulfill the conditions of both licenses. OVERVIEW -------- The OpenSSL toolkit includes: libssl.a: Provides the client and server-side implementations for SSLv3 and TLS. libcrypto.a: Provides general cryptographic and X.509 support needed by SSL/TLS but not logically part of it. openssl: A command line tool that can be used for: Creation of key parameters Creation of X.509 certificates, CSRs and CRLs Calculation of message digests Encryption and decryption SSL/TLS client and server tests Handling of S/MIME signed or encrypted mail And more... INSTALLATION ------------ See the appropriate file: INSTALL Linux, Unix, etc. INSTALL.DJGPP DOS platform with DJGPP INSTALL.NW Netware INSTALL.OS2 OS/2 INSTALL.VMS VMS INSTALL.W32 Windows (32bit) INSTALL.W64 Windows (64bit) INSTALL.WCE Windows CE SUPPORT ------- See the OpenSSL website www.openssl.org for details on how to obtain commercial technical support. If you have any problems with OpenSSL then please take the following steps first: - Download the latest version from the repository to see if the problem has already been addressed - Configure with no-asm - Remove compiler optimisation flags If you wish to report a bug then please include the following information and create an issue on GitHub: - On Unix systems: Self-test report generated by 'make report' - On other systems: OpenSSL version: output of 'openssl version -a' OS Name, Version, Hardware platform Compiler Details (name, version) - Application Details (name, version) - Problem Description (steps that will reproduce the problem, if known) - Stack Traceback (if the application dumps core) Just because something doesn't work the way you expect does not mean it is necessarily a bug in OpenSSL. HOW TO CONTRIBUTE TO OpenSSL ---------------------------- See CONTRIBUTING LEGALITIES ---------- A number of nations restrict the use or export of cryptography. If you are potentially subject to such restrictions you should seek competent professional legal advice before attempting to develop or distribute cryptographic code. Index: vendor-crypto/openssl/dist/apps/ca.c =================================================================== --- vendor-crypto/openssl/dist/apps/ca.c (revision 318896) +++ vendor-crypto/openssl/dist/apps/ca.c (revision 318897) @@ -1,2915 +1,2918 @@ /* apps/ca.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ /* The PPKI stuff has been donated by Jeff Barber */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef W_OK # ifdef OPENSSL_SYS_VMS # if defined(__DECC) # include # else # include # endif # elif !defined(OPENSSL_SYS_VXWORKS) && !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_NETWARE) # include # endif #endif #include "apps.h" #ifndef W_OK # define F_OK 0 # define X_OK 1 # define W_OK 2 # define R_OK 4 #endif #undef PROG #define PROG ca_main #define BASE_SECTION "ca" #define CONFIG_FILE "openssl.cnf" #define ENV_DEFAULT_CA "default_ca" #define STRING_MASK "string_mask" #define UTF8_IN "utf8" #define ENV_NEW_CERTS_DIR "new_certs_dir" #define ENV_CERTIFICATE "certificate" #define ENV_SERIAL "serial" #define ENV_CRLNUMBER "crlnumber" #define ENV_PRIVATE_KEY "private_key" #define ENV_DEFAULT_DAYS "default_days" #define ENV_DEFAULT_STARTDATE "default_startdate" #define ENV_DEFAULT_ENDDATE "default_enddate" #define ENV_DEFAULT_CRL_DAYS "default_crl_days" #define ENV_DEFAULT_CRL_HOURS "default_crl_hours" #define ENV_DEFAULT_MD "default_md" #define ENV_DEFAULT_EMAIL_DN "email_in_dn" #define ENV_PRESERVE "preserve" #define ENV_POLICY "policy" #define ENV_EXTENSIONS "x509_extensions" #define ENV_CRLEXT "crl_extensions" #define ENV_MSIE_HACK "msie_hack" #define ENV_NAMEOPT "name_opt" #define ENV_CERTOPT "cert_opt" #define ENV_EXTCOPY "copy_extensions" #define ENV_UNIQUE_SUBJECT "unique_subject" #define ENV_DATABASE "database" /* Additional revocation information types */ #define REV_NONE 0 /* No addditional information */ #define REV_CRL_REASON 1 /* Value is CRL reason code */ #define REV_HOLD 2 /* Value is hold instruction */ #define REV_KEY_COMPROMISE 3 /* Value is cert key compromise time */ #define REV_CA_COMPROMISE 4 /* Value is CA key compromise time */ static const char *ca_usage[] = { "usage: ca args\n", "\n", " -verbose - Talk alot while doing things\n", " -config file - A config file\n", " -name arg - The particular CA definition to use\n", " -gencrl - Generate a new CRL\n", " -crldays days - Days is when the next CRL is due\n", " -crlhours hours - Hours is when the next CRL is due\n", " -startdate YYMMDDHHMMSSZ - certificate validity notBefore\n", " -enddate YYMMDDHHMMSSZ - certificate validity notAfter (overrides -days)\n", " -days arg - number of days to certify the certificate for\n", " -md arg - md to use, one of md2, md5, sha or sha1\n", " -policy arg - The CA 'policy' to support\n", " -keyfile arg - private key file\n", " -keyform arg - private key file format (PEM or ENGINE)\n", " -key arg - key to decode the private key if it is encrypted\n", " -cert file - The CA certificate\n", " -selfsign - sign a certificate with the key associated with it\n", " -in file - The input PEM encoded certificate request(s)\n", " -out file - Where to put the output file(s)\n", " -outdir dir - Where to put output certificates\n", " -infiles .... - The last argument, requests to process\n", " -spkac file - File contains DN and signed public key and challenge\n", " -ss_cert file - File contains a self signed cert to sign\n", " -preserveDN - Don't re-order the DN\n", " -noemailDN - Don't add the EMAIL field into certificate' subject\n", " -batch - Don't ask questions\n", " -msie_hack - msie modifications to handle all those universal strings\n", " -revoke file - Revoke a certificate (given in file)\n", " -subj arg - Use arg instead of request's subject\n", " -utf8 - input characters are UTF8 (default ASCII)\n", " -multivalue-rdn - enable support for multivalued RDNs\n", " -extensions .. - Extension section (override value in config file)\n", " -extfile file - Configuration file with X509v3 extentions to add\n", " -crlexts .. - CRL extension section (override value in config file)\n", #ifndef OPENSSL_NO_ENGINE " -engine e - use engine e, possibly a hardware device.\n", #endif " -status serial - Shows certificate status given the serial number\n", " -updatedb - Updates db for expired certificates\n", NULL }; #ifdef EFENCE extern int EF_PROTECT_FREE; extern int EF_PROTECT_BELOW; extern int EF_ALIGNMENT; #endif static void lookup_fail(const char *name, const char *tag); static int certify(X509 **xret, char *infile, EVP_PKEY *pkey, X509 *x509, const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, char *subj, unsigned long chtype, int multirdn, int email_dn, char *startdate, char *enddate, long days, int batch, char *ext_sect, CONF *conf, int verbose, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, int selfsign); static int certify_cert(X509 **xret, char *infile, EVP_PKEY *pkey, X509 *x509, const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, char *subj, unsigned long chtype, int multirdn, int email_dn, char *startdate, char *enddate, long days, int batch, char *ext_sect, CONF *conf, int verbose, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, ENGINE *e); static int certify_spkac(X509 **xret, char *infile, EVP_PKEY *pkey, X509 *x509, const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, char *subj, unsigned long chtype, int multirdn, int email_dn, char *startdate, char *enddate, long days, char *ext_sect, CONF *conf, int verbose, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy); static void write_new_certificate(BIO *bp, X509 *x, int output_der, int notext); static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, char *subj, unsigned long chtype, int multirdn, int email_dn, char *startdate, char *enddate, long days, int batch, int verbose, X509_REQ *req, char *ext_sect, CONF *conf, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, int selfsign); static int do_revoke(X509 *x509, CA_DB *db, int ext, char *extval); static int get_certificate_status(const char *ser_status, CA_DB *db); static int do_updatedb(CA_DB *db); static int check_time_format(const char *str); char *make_revocation_str(int rev_type, char *rev_arg); int make_revoked(X509_REVOKED *rev, const char *str); int old_entry_print(BIO *bp, ASN1_OBJECT *obj, ASN1_STRING *str); static CONF *conf = NULL; static CONF *extconf = NULL; static char *section = NULL; static int preserve = 0; static int msie_hack = 0; int MAIN(int, char **); int MAIN(int argc, char **argv) { ENGINE *e = NULL; char *key = NULL, *passargin = NULL; int create_ser = 0; int free_key = 0; int total = 0; int total_done = 0; int badops = 0; int ret = 1; int email_dn = 1; int req = 0; int verbose = 0; int gencrl = 0; int dorevoke = 0; int doupdatedb = 0; long crldays = 0; long crlhours = 0; long crlsec = 0; long errorline = -1; char *configfile = NULL; char *md = NULL; char *policy = NULL; char *keyfile = NULL; char *certfile = NULL; int keyform = FORMAT_PEM; char *infile = NULL; char *spkac_file = NULL; char *ss_cert_file = NULL; char *ser_status = NULL; EVP_PKEY *pkey = NULL; int output_der = 0; char *outfile = NULL; char *outdir = NULL; char *serialfile = NULL; char *crlnumberfile = NULL; char *extensions = NULL; char *extfile = NULL; char *subj = NULL; unsigned long chtype = MBSTRING_ASC; int multirdn = 0; char *tmp_email_dn = NULL; char *crl_ext = NULL; int rev_type = REV_NONE; char *rev_arg = NULL; BIGNUM *serial = NULL; BIGNUM *crlnumber = NULL; char *startdate = NULL; char *enddate = NULL; long days = 0; int batch = 0; int notext = 0; unsigned long nameopt = 0, certopt = 0; int default_op = 1; int ext_copy = EXT_COPY_NONE; int selfsign = 0; X509 *x509 = NULL, *x509p = NULL; X509 *x = NULL; BIO *in = NULL, *out = NULL, *Sout = NULL, *Cout = NULL; char *dbfile = NULL; CA_DB *db = NULL; X509_CRL *crl = NULL; X509_REVOKED *r = NULL; ASN1_TIME *tmptm; ASN1_INTEGER *tmpser; char *f; const char *p; char *const *pp; int i, j; const EVP_MD *dgst = NULL; STACK_OF(CONF_VALUE) *attribs = NULL; STACK_OF(X509) *cert_sk = NULL; STACK_OF(OPENSSL_STRING) *sigopts = NULL; #undef BSIZE #define BSIZE 256 MS_STATIC char buf[3][BSIZE]; char *randfile = NULL; char *engine = NULL; char *tofree = NULL; DB_ATTR db_attr; #ifdef EFENCE EF_PROTECT_FREE = 1; EF_PROTECT_BELOW = 1; EF_ALIGNMENT = 0; #endif apps_startup(); conf = NULL; key = NULL; section = NULL; preserve = 0; msie_hack = 0; if (bio_err == NULL) if ((bio_err = BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT); argc--; argv++; while (argc >= 1) { if (strcmp(*argv, "-verbose") == 0) verbose = 1; else if (strcmp(*argv, "-config") == 0) { if (--argc < 1) goto bad; configfile = *(++argv); } else if (strcmp(*argv, "-name") == 0) { if (--argc < 1) goto bad; section = *(++argv); } else if (strcmp(*argv, "-subj") == 0) { if (--argc < 1) goto bad; subj = *(++argv); /* preserve=1; */ } else if (strcmp(*argv, "-utf8") == 0) chtype = MBSTRING_UTF8; else if (strcmp(*argv, "-create_serial") == 0) create_ser = 1; else if (strcmp(*argv, "-multivalue-rdn") == 0) multirdn = 1; else if (strcmp(*argv, "-startdate") == 0) { if (--argc < 1) goto bad; startdate = *(++argv); } else if (strcmp(*argv, "-enddate") == 0) { if (--argc < 1) goto bad; enddate = *(++argv); } else if (strcmp(*argv, "-days") == 0) { if (--argc < 1) goto bad; days = atoi(*(++argv)); } else if (strcmp(*argv, "-md") == 0) { if (--argc < 1) goto bad; md = *(++argv); } else if (strcmp(*argv, "-policy") == 0) { if (--argc < 1) goto bad; policy = *(++argv); } else if (strcmp(*argv, "-keyfile") == 0) { if (--argc < 1) goto bad; keyfile = *(++argv); } else if (strcmp(*argv, "-keyform") == 0) { if (--argc < 1) goto bad; keyform = str2fmt(*(++argv)); } else if (strcmp(*argv, "-passin") == 0) { if (--argc < 1) goto bad; passargin = *(++argv); } else if (strcmp(*argv, "-key") == 0) { if (--argc < 1) goto bad; key = *(++argv); } else if (strcmp(*argv, "-cert") == 0) { if (--argc < 1) goto bad; certfile = *(++argv); } else if (strcmp(*argv, "-selfsign") == 0) selfsign = 1; else if (strcmp(*argv, "-in") == 0) { if (--argc < 1) goto bad; infile = *(++argv); req = 1; } else if (strcmp(*argv, "-out") == 0) { if (--argc < 1) goto bad; outfile = *(++argv); } else if (strcmp(*argv, "-outdir") == 0) { if (--argc < 1) goto bad; outdir = *(++argv); } else if (strcmp(*argv, "-sigopt") == 0) { if (--argc < 1) goto bad; if (!sigopts) sigopts = sk_OPENSSL_STRING_new_null(); if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, *(++argv))) goto bad; } else if (strcmp(*argv, "-notext") == 0) notext = 1; else if (strcmp(*argv, "-batch") == 0) batch = 1; else if (strcmp(*argv, "-preserveDN") == 0) preserve = 1; else if (strcmp(*argv, "-noemailDN") == 0) email_dn = 0; else if (strcmp(*argv, "-gencrl") == 0) gencrl = 1; else if (strcmp(*argv, "-msie_hack") == 0) msie_hack = 1; else if (strcmp(*argv, "-crldays") == 0) { if (--argc < 1) goto bad; crldays = atol(*(++argv)); } else if (strcmp(*argv, "-crlhours") == 0) { if (--argc < 1) goto bad; crlhours = atol(*(++argv)); } else if (strcmp(*argv, "-crlsec") == 0) { if (--argc < 1) goto bad; crlsec = atol(*(++argv)); } else if (strcmp(*argv, "-infiles") == 0) { argc--; argv++; req = 1; break; } else if (strcmp(*argv, "-ss_cert") == 0) { if (--argc < 1) goto bad; ss_cert_file = *(++argv); req = 1; } else if (strcmp(*argv, "-spkac") == 0) { if (--argc < 1) goto bad; spkac_file = *(++argv); req = 1; } else if (strcmp(*argv, "-revoke") == 0) { if (--argc < 1) goto bad; infile = *(++argv); dorevoke = 1; } else if (strcmp(*argv, "-valid") == 0) { if (--argc < 1) goto bad; infile = *(++argv); dorevoke = 2; } else if (strcmp(*argv, "-extensions") == 0) { if (--argc < 1) goto bad; extensions = *(++argv); } else if (strcmp(*argv, "-extfile") == 0) { if (--argc < 1) goto bad; extfile = *(++argv); } else if (strcmp(*argv, "-status") == 0) { if (--argc < 1) goto bad; ser_status = *(++argv); } else if (strcmp(*argv, "-updatedb") == 0) { doupdatedb = 1; } else if (strcmp(*argv, "-crlexts") == 0) { if (--argc < 1) goto bad; crl_ext = *(++argv); } else if (strcmp(*argv, "-crl_reason") == 0) { if (--argc < 1) goto bad; rev_arg = *(++argv); rev_type = REV_CRL_REASON; } else if (strcmp(*argv, "-crl_hold") == 0) { if (--argc < 1) goto bad; rev_arg = *(++argv); rev_type = REV_HOLD; } else if (strcmp(*argv, "-crl_compromise") == 0) { if (--argc < 1) goto bad; rev_arg = *(++argv); rev_type = REV_KEY_COMPROMISE; } else if (strcmp(*argv, "-crl_CA_compromise") == 0) { if (--argc < 1) goto bad; rev_arg = *(++argv); rev_type = REV_CA_COMPROMISE; } #ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv, "-engine") == 0) { if (--argc < 1) goto bad; engine = *(++argv); } #endif else { bad: BIO_printf(bio_err, "unknown option %s\n", *argv); badops = 1; break; } argc--; argv++; } if (badops) { const char **pp2; for (pp2 = ca_usage; (*pp2 != NULL); pp2++) BIO_printf(bio_err, "%s", *pp2); goto err; } ERR_load_crypto_strings(); /*****************************************************************/ tofree = NULL; if (configfile == NULL) configfile = getenv("OPENSSL_CONF"); if (configfile == NULL) configfile = getenv("SSLEAY_CONF"); if (configfile == NULL) { const char *s = X509_get_default_cert_area(); size_t len; #ifdef OPENSSL_SYS_VMS len = strlen(s) + sizeof(CONFIG_FILE); tofree = OPENSSL_malloc(len); if (!tofree) { BIO_printf(bio_err, "Out of memory\n"); goto err; } strcpy(tofree, s); #else len = strlen(s) + sizeof(CONFIG_FILE) + 1; tofree = OPENSSL_malloc(len); if (!tofree) { BIO_printf(bio_err, "Out of memory\n"); goto err; } BUF_strlcpy(tofree, s, len); BUF_strlcat(tofree, "/", len); #endif BUF_strlcat(tofree, CONFIG_FILE, len); configfile = tofree; } BIO_printf(bio_err, "Using configuration from %s\n", configfile); conf = NCONF_new(NULL); if (NCONF_load(conf, configfile, &errorline) <= 0) { if (errorline <= 0) BIO_printf(bio_err, "error loading the config file '%s'\n", configfile); else BIO_printf(bio_err, "error on line %ld of config file '%s'\n", errorline, configfile); goto err; } if (tofree) { OPENSSL_free(tofree); tofree = NULL; } if (!load_config(bio_err, conf)) goto err; e = setup_engine(bio_err, engine, 0); /* Lets get the config section we are using */ if (section == NULL) { section = NCONF_get_string(conf, BASE_SECTION, ENV_DEFAULT_CA); if (section == NULL) { lookup_fail(BASE_SECTION, ENV_DEFAULT_CA); goto err; } } if (conf != NULL) { p = NCONF_get_string(conf, NULL, "oid_file"); if (p == NULL) ERR_clear_error(); if (p != NULL) { BIO *oid_bio; oid_bio = BIO_new_file(p, "r"); if (oid_bio == NULL) { /*- BIO_printf(bio_err,"problems opening %s for extra oid's\n",p); ERR_print_errors(bio_err); */ ERR_clear_error(); } else { OBJ_create_objects(oid_bio); BIO_free(oid_bio); } } if (!add_oid_section(bio_err, conf)) { ERR_print_errors(bio_err); goto err; } } randfile = NCONF_get_string(conf, BASE_SECTION, "RANDFILE"); if (randfile == NULL) ERR_clear_error(); app_RAND_load_file(randfile, bio_err, 0); f = NCONF_get_string(conf, section, STRING_MASK); if (!f) ERR_clear_error(); if (f && !ASN1_STRING_set_default_mask_asc(f)) { BIO_printf(bio_err, "Invalid global string mask setting %s\n", f); goto err; } if (chtype != MBSTRING_UTF8) { f = NCONF_get_string(conf, section, UTF8_IN); if (!f) ERR_clear_error(); else if (!strcmp(f, "yes")) chtype = MBSTRING_UTF8; } db_attr.unique_subject = 1; p = NCONF_get_string(conf, section, ENV_UNIQUE_SUBJECT); if (p) { #ifdef RL_DEBUG BIO_printf(bio_err, "DEBUG: unique_subject = \"%s\"\n", p); #endif db_attr.unique_subject = parse_yesno(p, 1); } else ERR_clear_error(); #ifdef RL_DEBUG if (!p) BIO_printf(bio_err, "DEBUG: unique_subject undefined\n"); #endif #ifdef RL_DEBUG BIO_printf(bio_err, "DEBUG: configured unique_subject is %d\n", db_attr.unique_subject); #endif in = BIO_new(BIO_s_file()); out = BIO_new(BIO_s_file()); Sout = BIO_new(BIO_s_file()); Cout = BIO_new(BIO_s_file()); if ((in == NULL) || (out == NULL) || (Sout == NULL) || (Cout == NULL)) { ERR_print_errors(bio_err); goto err; } /*****************************************************************/ /* report status of cert with serial number given on command line */ if (ser_status) { if ((dbfile = NCONF_get_string(conf, section, ENV_DATABASE)) == NULL) { lookup_fail(section, ENV_DATABASE); goto err; } db = load_index(dbfile, &db_attr); if (db == NULL) goto err; if (!index_index(db)) goto err; if (get_certificate_status(ser_status, db) != 1) BIO_printf(bio_err, "Error verifying serial %s!\n", ser_status); goto err; } /*****************************************************************/ /* we definitely need a private key, so let's get it */ if ((keyfile == NULL) && ((keyfile = NCONF_get_string(conf, section, ENV_PRIVATE_KEY)) == NULL)) { lookup_fail(section, ENV_PRIVATE_KEY); goto err; } if (!key) { free_key = 1; if (!app_passwd(bio_err, passargin, NULL, &key, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto err; } } pkey = load_key(bio_err, keyfile, keyform, 0, key, e, "CA private key"); if (key) OPENSSL_cleanse(key, strlen(key)); if (pkey == NULL) { /* load_key() has already printed an appropriate message */ goto err; } /*****************************************************************/ /* we need a certificate */ if (!selfsign || spkac_file || ss_cert_file || gencrl) { if ((certfile == NULL) && ((certfile = NCONF_get_string(conf, section, ENV_CERTIFICATE)) == NULL)) { lookup_fail(section, ENV_CERTIFICATE); goto err; } x509 = load_cert(bio_err, certfile, FORMAT_PEM, NULL, e, "CA certificate"); if (x509 == NULL) goto err; if (!X509_check_private_key(x509, pkey)) { BIO_printf(bio_err, "CA certificate and CA private key do not match\n"); goto err; } } if (!selfsign) x509p = x509; f = NCONF_get_string(conf, BASE_SECTION, ENV_PRESERVE); if (f == NULL) ERR_clear_error(); if ((f != NULL) && ((*f == 'y') || (*f == 'Y'))) preserve = 1; f = NCONF_get_string(conf, BASE_SECTION, ENV_MSIE_HACK); if (f == NULL) ERR_clear_error(); if ((f != NULL) && ((*f == 'y') || (*f == 'Y'))) msie_hack = 1; f = NCONF_get_string(conf, section, ENV_NAMEOPT); if (f) { if (!set_name_ex(&nameopt, f)) { BIO_printf(bio_err, "Invalid name options: \"%s\"\n", f); goto err; } default_op = 0; } else ERR_clear_error(); f = NCONF_get_string(conf, section, ENV_CERTOPT); if (f) { if (!set_cert_ex(&certopt, f)) { BIO_printf(bio_err, "Invalid certificate options: \"%s\"\n", f); goto err; } default_op = 0; } else ERR_clear_error(); f = NCONF_get_string(conf, section, ENV_EXTCOPY); if (f) { if (!set_ext_copy(&ext_copy, f)) { BIO_printf(bio_err, "Invalid extension copy option: \"%s\"\n", f); goto err; } } else ERR_clear_error(); /*****************************************************************/ /* lookup where to write new certificates */ if ((outdir == NULL) && (req)) { if ((outdir = NCONF_get_string(conf, section, ENV_NEW_CERTS_DIR)) == NULL) { BIO_printf(bio_err, "there needs to be defined a directory for new certificate to be placed in\n"); goto err; } #ifndef OPENSSL_SYS_VMS /* * outdir is a directory spec, but access() for VMS demands a * filename. In any case, stat(), below, will catch the problem if * outdir is not a directory spec, and the fopen() or open() will * catch an error if there is no write access. * * Presumably, this problem could also be solved by using the DEC C * routines to convert the directory syntax to Unixly, and give that * to access(). However, time's too short to do that just now. */ # ifndef _WIN32 if (access(outdir, R_OK | W_OK | X_OK) != 0) # else if (_access(outdir, R_OK | W_OK | X_OK) != 0) # endif { BIO_printf(bio_err, "I am unable to access the %s directory\n", outdir); perror(outdir); goto err; } if (app_isdir(outdir) <= 0) { BIO_printf(bio_err, "%s need to be a directory\n", outdir); perror(outdir); goto err; } #endif } /*****************************************************************/ /* we need to load the database file */ if ((dbfile = NCONF_get_string(conf, section, ENV_DATABASE)) == NULL) { lookup_fail(section, ENV_DATABASE); goto err; } db = load_index(dbfile, &db_attr); if (db == NULL) goto err; /* Lets check some fields */ for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { pp = sk_OPENSSL_PSTRING_value(db->db->data, i); if ((pp[DB_type][0] != DB_TYPE_REV) && (pp[DB_rev_date][0] != '\0')) { BIO_printf(bio_err, "entry %d: not revoked yet, but has a revocation date\n", i + 1); goto err; } if ((pp[DB_type][0] == DB_TYPE_REV) && !make_revoked(NULL, pp[DB_rev_date])) { BIO_printf(bio_err, " in entry %d\n", i + 1); goto err; } if (!check_time_format((char *)pp[DB_exp_date])) { BIO_printf(bio_err, "entry %d: invalid expiry date\n", i + 1); goto err; } p = pp[DB_serial]; j = strlen(p); if (*p == '-') { p++; j--; } if ((j & 1) || (j < 2)) { BIO_printf(bio_err, "entry %d: bad serial number length (%d)\n", i + 1, j); goto err; } while (*p) { if (!(((*p >= '0') && (*p <= '9')) || ((*p >= 'A') && (*p <= 'F')) || ((*p >= 'a') && (*p <= 'f')))) { BIO_printf(bio_err, "entry %d: bad serial number characters, char pos %ld, char is '%c'\n", i + 1, (long)(p - pp[DB_serial]), *p); goto err; } p++; } } if (verbose) { BIO_set_fp(out, stdout, BIO_NOCLOSE | BIO_FP_TEXT); /* cannot fail */ #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); out = BIO_push(tmpbio, out); } #endif TXT_DB_write(out, db->db); BIO_printf(bio_err, "%d entries loaded from the database\n", sk_OPENSSL_PSTRING_num(db->db->data)); BIO_printf(bio_err, "generating index\n"); } if (!index_index(db)) goto err; /*****************************************************************/ /* Update the db file for expired certificates */ if (doupdatedb) { if (verbose) BIO_printf(bio_err, "Updating %s ...\n", dbfile); i = do_updatedb(db); if (i == -1) { BIO_printf(bio_err, "Malloc failure\n"); goto err; } else if (i == 0) { if (verbose) BIO_printf(bio_err, "No entries found to mark expired\n"); } else { if (!save_index(dbfile, "new", db)) goto err; if (!rotate_index(dbfile, "new", "old")) goto err; if (verbose) BIO_printf(bio_err, "Done. %d entries marked as expired\n", i); } } /*****************************************************************/ /* Read extentions config file */ if (extfile) { extconf = NCONF_new(NULL); if (NCONF_load(extconf, extfile, &errorline) <= 0) { if (errorline <= 0) BIO_printf(bio_err, "ERROR: loading the config file '%s'\n", extfile); else BIO_printf(bio_err, "ERROR: on line %ld of config file '%s'\n", errorline, extfile); ret = 1; goto err; } if (verbose) BIO_printf(bio_err, "Successfully loaded extensions file %s\n", extfile); /* We can have sections in the ext file */ if (!extensions && !(extensions = NCONF_get_string(extconf, "default", "extensions"))) extensions = "default"; } /*****************************************************************/ if (req || gencrl) { if (outfile != NULL) { if (BIO_write_filename(Sout, outfile) <= 0) { perror(outfile); goto err; } } else { BIO_set_fp(Sout, stdout, BIO_NOCLOSE | BIO_FP_TEXT); #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); Sout = BIO_push(tmpbio, Sout); } #endif } } if ((md == NULL) && ((md = NCONF_get_string(conf, section, ENV_DEFAULT_MD)) == NULL)) { lookup_fail(section, ENV_DEFAULT_MD); goto err; } if (!strcmp(md, "default")) { int def_nid; if (EVP_PKEY_get_default_digest_nid(pkey, &def_nid) <= 0) { BIO_puts(bio_err, "no default digest\n"); goto err; } md = (char *)OBJ_nid2sn(def_nid); } if ((dgst = EVP_get_digestbyname(md)) == NULL) { BIO_printf(bio_err, "%s is an unsupported message digest type\n", md); goto err; } if (req) { if ((email_dn == 1) && ((tmp_email_dn = NCONF_get_string(conf, section, ENV_DEFAULT_EMAIL_DN)) != NULL)) { if (strcmp(tmp_email_dn, "no") == 0) email_dn = 0; } if (verbose) BIO_printf(bio_err, "message digest is %s\n", OBJ_nid2ln(dgst->type)); if ((policy == NULL) && ((policy = NCONF_get_string(conf, section, ENV_POLICY)) == NULL)) { lookup_fail(section, ENV_POLICY); goto err; } if (verbose) BIO_printf(bio_err, "policy is %s\n", policy); if ((serialfile = NCONF_get_string(conf, section, ENV_SERIAL)) == NULL) { lookup_fail(section, ENV_SERIAL); goto err; } if (!extconf) { /* * no '-extfile' option, so we look for extensions in the main * configuration file */ if (!extensions) { extensions = NCONF_get_string(conf, section, ENV_EXTENSIONS); if (!extensions) ERR_clear_error(); } if (extensions) { /* Check syntax of file */ X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); X509V3_set_nconf(&ctx, conf); if (!X509V3_EXT_add_nconf(conf, &ctx, extensions, NULL)) { BIO_printf(bio_err, "Error Loading extension section %s\n", extensions); ret = 1; goto err; } } } if (startdate == NULL) { startdate = NCONF_get_string(conf, section, ENV_DEFAULT_STARTDATE); if (startdate == NULL) ERR_clear_error(); } if (startdate && !ASN1_TIME_set_string(NULL, startdate)) { BIO_printf(bio_err, "start date is invalid, it should be YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ\n"); goto err; } if (startdate == NULL) startdate = "today"; if (enddate == NULL) { enddate = NCONF_get_string(conf, section, ENV_DEFAULT_ENDDATE); if (enddate == NULL) ERR_clear_error(); } if (enddate && !ASN1_TIME_set_string(NULL, enddate)) { BIO_printf(bio_err, "end date is invalid, it should be YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ\n"); goto err; } if (days == 0) { if (!NCONF_get_number(conf, section, ENV_DEFAULT_DAYS, &days)) days = 0; } if (!enddate && (days == 0)) { BIO_printf(bio_err, "cannot lookup how many days to certify for\n"); goto err; } if ((serial = load_serial(serialfile, create_ser, NULL)) == NULL) { BIO_printf(bio_err, "error while loading serial number\n"); goto err; } if (verbose) { if (BN_is_zero(serial)) BIO_printf(bio_err, "next serial number is 00\n"); else { if ((f = BN_bn2hex(serial)) == NULL) goto err; BIO_printf(bio_err, "next serial number is %s\n", f); OPENSSL_free(f); } } if ((attribs = NCONF_get_section(conf, policy)) == NULL) { BIO_printf(bio_err, "unable to find 'section' for %s\n", policy); goto err; } if ((cert_sk = sk_X509_new_null()) == NULL) { BIO_printf(bio_err, "Memory allocation failure\n"); goto err; } if (spkac_file != NULL) { total++; j = certify_spkac(&x, spkac_file, pkey, x509, dgst, sigopts, attribs, db, serial, subj, chtype, multirdn, email_dn, startdate, enddate, days, extensions, conf, verbose, certopt, nameopt, default_op, ext_copy); if (j < 0) goto err; if (j > 0) { total_done++; BIO_printf(bio_err, "\n"); if (!BN_add_word(serial, 1)) goto err; if (!sk_X509_push(cert_sk, x)) { BIO_printf(bio_err, "Memory allocation failure\n"); goto err; } if (outfile) { output_der = 1; batch = 1; } } } if (ss_cert_file != NULL) { total++; j = certify_cert(&x, ss_cert_file, pkey, x509, dgst, sigopts, attribs, db, serial, subj, chtype, multirdn, email_dn, startdate, enddate, days, batch, extensions, conf, verbose, certopt, nameopt, default_op, ext_copy, e); if (j < 0) goto err; if (j > 0) { total_done++; BIO_printf(bio_err, "\n"); if (!BN_add_word(serial, 1)) goto err; if (!sk_X509_push(cert_sk, x)) { BIO_printf(bio_err, "Memory allocation failure\n"); goto err; } } } if (infile != NULL) { total++; j = certify(&x, infile, pkey, x509p, dgst, sigopts, attribs, db, serial, subj, chtype, multirdn, email_dn, startdate, enddate, days, batch, extensions, conf, verbose, certopt, nameopt, default_op, ext_copy, selfsign); if (j < 0) goto err; if (j > 0) { total_done++; BIO_printf(bio_err, "\n"); if (!BN_add_word(serial, 1)) goto err; if (!sk_X509_push(cert_sk, x)) { BIO_printf(bio_err, "Memory allocation failure\n"); goto err; } } } for (i = 0; i < argc; i++) { total++; j = certify(&x, argv[i], pkey, x509p, dgst, sigopts, attribs, db, serial, subj, chtype, multirdn, email_dn, startdate, enddate, days, batch, extensions, conf, verbose, certopt, nameopt, default_op, ext_copy, selfsign); if (j < 0) goto err; if (j > 0) { total_done++; BIO_printf(bio_err, "\n"); if (!BN_add_word(serial, 1)) goto err; if (!sk_X509_push(cert_sk, x)) { BIO_printf(bio_err, "Memory allocation failure\n"); goto err; } } } /* * we have a stack of newly certified certificates and a data base * and serial number that need updating */ if (sk_X509_num(cert_sk) > 0) { if (!batch) { BIO_printf(bio_err, "\n%d out of %d certificate requests certified, commit? [y/n]", total_done, total); (void)BIO_flush(bio_err); buf[0][0] = '\0'; if (!fgets(buf[0], 10, stdin)) { BIO_printf(bio_err, "CERTIFICATION CANCELED: I/O error\n"); ret = 0; goto err; } if ((buf[0][0] != 'y') && (buf[0][0] != 'Y')) { BIO_printf(bio_err, "CERTIFICATION CANCELED\n"); ret = 0; goto err; } } BIO_printf(bio_err, "Write out database with %d new entries\n", sk_X509_num(cert_sk)); if (!save_serial(serialfile, "new", serial, NULL)) goto err; if (!save_index(dbfile, "new", db)) goto err; } if (verbose) BIO_printf(bio_err, "writing new certificates\n"); for (i = 0; i < sk_X509_num(cert_sk); i++) { int k; char *n; x = sk_X509_value(cert_sk, i); j = x->cert_info->serialNumber->length; p = (const char *)x->cert_info->serialNumber->data; if (strlen(outdir) >= (size_t)(j ? BSIZE - j * 2 - 6 : BSIZE - 8)) { BIO_printf(bio_err, "certificate file name too long\n"); goto err; } strcpy(buf[2], outdir); #ifndef OPENSSL_SYS_VMS BUF_strlcat(buf[2], "/", sizeof(buf[2])); #endif n = (char *)&(buf[2][strlen(buf[2])]); if (j > 0) { for (k = 0; k < j; k++) { if (n >= &(buf[2][sizeof(buf[2])])) break; BIO_snprintf(n, &buf[2][0] + sizeof(buf[2]) - n, "%02X", (unsigned char)*(p++)); n += 2; } } else { *(n++) = '0'; *(n++) = '0'; } *(n++) = '.'; *(n++) = 'p'; *(n++) = 'e'; *(n++) = 'm'; *n = '\0'; if (verbose) BIO_printf(bio_err, "writing %s\n", buf[2]); if (BIO_write_filename(Cout, buf[2]) <= 0) { perror(buf[2]); goto err; } write_new_certificate(Cout, x, 0, notext); write_new_certificate(Sout, x, output_der, notext); } if (sk_X509_num(cert_sk)) { /* Rename the database and the serial file */ if (!rotate_serial(serialfile, "new", "old")) goto err; if (!rotate_index(dbfile, "new", "old")) goto err; BIO_printf(bio_err, "Data Base Updated\n"); } } /*****************************************************************/ if (gencrl) { int crl_v2 = 0; if (!crl_ext) { crl_ext = NCONF_get_string(conf, section, ENV_CRLEXT); if (!crl_ext) ERR_clear_error(); } if (crl_ext) { /* Check syntax of file */ X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); X509V3_set_nconf(&ctx, conf); if (!X509V3_EXT_add_nconf(conf, &ctx, crl_ext, NULL)) { BIO_printf(bio_err, "Error Loading CRL extension section %s\n", crl_ext); ret = 1; goto err; } } if ((crlnumberfile = NCONF_get_string(conf, section, ENV_CRLNUMBER)) != NULL) if ((crlnumber = load_serial(crlnumberfile, 0, NULL)) == NULL) { BIO_printf(bio_err, "error while loading CRL number\n"); goto err; } if (!crldays && !crlhours && !crlsec) { if (!NCONF_get_number(conf, section, ENV_DEFAULT_CRL_DAYS, &crldays)) crldays = 0; if (!NCONF_get_number(conf, section, ENV_DEFAULT_CRL_HOURS, &crlhours)) crlhours = 0; ERR_clear_error(); } if ((crldays == 0) && (crlhours == 0) && (crlsec == 0)) { BIO_printf(bio_err, "cannot lookup how long until the next CRL is issued\n"); goto err; } if (verbose) BIO_printf(bio_err, "making CRL\n"); if ((crl = X509_CRL_new()) == NULL) goto err; if (!X509_CRL_set_issuer_name(crl, X509_get_subject_name(x509))) goto err; tmptm = ASN1_TIME_new(); if (!tmptm) goto err; X509_gmtime_adj(tmptm, 0); X509_CRL_set_lastUpdate(crl, tmptm); if (!X509_time_adj_ex(tmptm, crldays, crlhours * 60 * 60 + crlsec, NULL)) { BIO_puts(bio_err, "error setting CRL nextUpdate\n"); goto err; } X509_CRL_set_nextUpdate(crl, tmptm); ASN1_TIME_free(tmptm); for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { pp = sk_OPENSSL_PSTRING_value(db->db->data, i); if (pp[DB_type][0] == DB_TYPE_REV) { if ((r = X509_REVOKED_new()) == NULL) goto err; j = make_revoked(r, pp[DB_rev_date]); if (!j) goto err; if (j == 2) crl_v2 = 1; if (!BN_hex2bn(&serial, pp[DB_serial])) goto err; tmpser = BN_to_ASN1_INTEGER(serial, NULL); BN_free(serial); serial = NULL; if (!tmpser) goto err; X509_REVOKED_set_serialNumber(r, tmpser); ASN1_INTEGER_free(tmpser); X509_CRL_add0_revoked(crl, r); } } /* * sort the data so it will be written in serial number order */ X509_CRL_sort(crl); /* we now have a CRL */ if (verbose) BIO_printf(bio_err, "signing CRL\n"); /* Add any extensions asked for */ if (crl_ext || crlnumberfile != NULL) { X509V3_CTX crlctx; X509V3_set_ctx(&crlctx, x509, NULL, NULL, crl, 0); X509V3_set_nconf(&crlctx, conf); if (crl_ext) if (!X509V3_EXT_CRL_add_nconf(conf, &crlctx, crl_ext, crl)) goto err; if (crlnumberfile != NULL) { tmpser = BN_to_ASN1_INTEGER(crlnumber, NULL); if (!tmpser) goto err; X509_CRL_add1_ext_i2d(crl, NID_crl_number, tmpser, 0, 0); ASN1_INTEGER_free(tmpser); crl_v2 = 1; if (!BN_add_word(crlnumber, 1)) goto err; } } if (crl_ext || crl_v2) { if (!X509_CRL_set_version(crl, 1)) goto err; /* version 2 CRL */ } /* we have a CRL number that need updating */ if (crlnumberfile != NULL) if (!save_serial(crlnumberfile, "new", crlnumber, NULL)) goto err; if (crlnumber) { BN_free(crlnumber); crlnumber = NULL; } if (!do_X509_CRL_sign(bio_err, crl, pkey, dgst, sigopts)) goto err; PEM_write_bio_X509_CRL(Sout, crl); if (crlnumberfile != NULL) /* Rename the crlnumber file */ if (!rotate_serial(crlnumberfile, "new", "old")) goto err; } /*****************************************************************/ if (dorevoke) { if (infile == NULL) { BIO_printf(bio_err, "no input files\n"); goto err; } else { X509 *revcert; revcert = load_cert(bio_err, infile, FORMAT_PEM, NULL, e, infile); if (revcert == NULL) goto err; if (dorevoke == 2) rev_type = -1; j = do_revoke(revcert, db, rev_type, rev_arg); if (j <= 0) goto err; X509_free(revcert); if (!save_index(dbfile, "new", db)) goto err; if (!rotate_index(dbfile, "new", "old")) goto err; BIO_printf(bio_err, "Data Base Updated\n"); } } /*****************************************************************/ ret = 0; err: if (tofree) OPENSSL_free(tofree); BIO_free_all(Cout); BIO_free_all(Sout); BIO_free_all(out); BIO_free_all(in); if (cert_sk) sk_X509_pop_free(cert_sk, X509_free); if (ret) ERR_print_errors(bio_err); app_RAND_write_file(randfile, bio_err); if (free_key && key) OPENSSL_free(key); BN_free(serial); BN_free(crlnumber); free_index(db); if (sigopts) sk_OPENSSL_STRING_free(sigopts); EVP_PKEY_free(pkey); if (x509) X509_free(x509); X509_CRL_free(crl); NCONF_free(conf); NCONF_free(extconf); release_engine(e); OBJ_cleanup(); apps_shutdown(); OPENSSL_EXIT(ret); } static void lookup_fail(const char *name, const char *tag) { BIO_printf(bio_err, "variable lookup failed for %s::%s\n", name, tag); } static int certify(X509 **xret, char *infile, EVP_PKEY *pkey, X509 *x509, const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, char *subj, unsigned long chtype, int multirdn, int email_dn, char *startdate, char *enddate, long days, int batch, char *ext_sect, CONF *lconf, int verbose, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, int selfsign) { X509_REQ *req = NULL; BIO *in = NULL; EVP_PKEY *pktmp = NULL; int ok = -1, i; in = BIO_new(BIO_s_file()); if (BIO_read_filename(in, infile) <= 0) { perror(infile); goto err; } if ((req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL)) == NULL) { BIO_printf(bio_err, "Error reading certificate request in %s\n", infile); goto err; } if (verbose) X509_REQ_print(bio_err, req); BIO_printf(bio_err, "Check that the request matches the signature\n"); if (selfsign && !X509_REQ_check_private_key(req, pkey)) { BIO_printf(bio_err, "Certificate request and CA private key do not match\n"); ok = 0; goto err; } if ((pktmp = X509_REQ_get_pubkey(req)) == NULL) { BIO_printf(bio_err, "error unpacking public key\n"); goto err; } i = X509_REQ_verify(req, pktmp); EVP_PKEY_free(pktmp); if (i < 0) { ok = 0; BIO_printf(bio_err, "Signature verification problems....\n"); ERR_print_errors(bio_err); goto err; } if (i == 0) { ok = 0; BIO_printf(bio_err, "Signature did not match the certificate request\n"); ERR_print_errors(bio_err); goto err; } else BIO_printf(bio_err, "Signature ok\n"); ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial, subj, chtype, multirdn, email_dn, startdate, enddate, days, batch, verbose, req, ext_sect, lconf, certopt, nameopt, default_op, ext_copy, selfsign); err: if (req != NULL) X509_REQ_free(req); if (in != NULL) BIO_free(in); return (ok); } static int certify_cert(X509 **xret, char *infile, EVP_PKEY *pkey, X509 *x509, const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, char *subj, unsigned long chtype, int multirdn, int email_dn, char *startdate, char *enddate, long days, int batch, char *ext_sect, CONF *lconf, int verbose, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, ENGINE *e) { X509 *req = NULL; X509_REQ *rreq = NULL; EVP_PKEY *pktmp = NULL; int ok = -1, i; if ((req = load_cert(bio_err, infile, FORMAT_PEM, NULL, e, infile)) == NULL) goto err; if (verbose) X509_print(bio_err, req); BIO_printf(bio_err, "Check that the request matches the signature\n"); if ((pktmp = X509_get_pubkey(req)) == NULL) { BIO_printf(bio_err, "error unpacking public key\n"); goto err; } i = X509_verify(req, pktmp); EVP_PKEY_free(pktmp); if (i < 0) { ok = 0; BIO_printf(bio_err, "Signature verification problems....\n"); goto err; } if (i == 0) { ok = 0; BIO_printf(bio_err, "Signature did not match the certificate\n"); goto err; } else BIO_printf(bio_err, "Signature ok\n"); if ((rreq = X509_to_X509_REQ(req, NULL, EVP_md5())) == NULL) goto err; ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial, subj, chtype, multirdn, email_dn, startdate, enddate, days, batch, verbose, rreq, ext_sect, lconf, certopt, nameopt, default_op, ext_copy, 0); err: if (rreq != NULL) X509_REQ_free(rreq); if (req != NULL) X509_free(req); return (ok); } static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, char *subj, unsigned long chtype, int multirdn, int email_dn, char *startdate, char *enddate, long days, int batch, int verbose, X509_REQ *req, char *ext_sect, CONF *lconf, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, int selfsign) { X509_NAME *name = NULL, *CAname = NULL, *subject = NULL, *dn_subject = NULL; ASN1_UTCTIME *tm, *tmptm; ASN1_STRING *str, *str2; ASN1_OBJECT *obj; X509 *ret = NULL; X509_CINF *ci; X509_NAME_ENTRY *ne; X509_NAME_ENTRY *tne, *push; EVP_PKEY *pktmp; int ok = -1, i, j, last, nid; const char *p; CONF_VALUE *cv; OPENSSL_STRING row[DB_NUMBER]; OPENSSL_STRING *irow = NULL; OPENSSL_STRING *rrow = NULL; char buf[25]; tmptm = ASN1_UTCTIME_new(); if (tmptm == NULL) { BIO_printf(bio_err, "malloc error\n"); return (0); } for (i = 0; i < DB_NUMBER; i++) row[i] = NULL; if (subj) { X509_NAME *n = parse_name(subj, chtype, multirdn); if (!n) { ERR_print_errors(bio_err); goto err; } X509_REQ_set_subject_name(req, n); req->req_info->enc.modified = 1; X509_NAME_free(n); } if (default_op) BIO_printf(bio_err, "The Subject's Distinguished Name is as follows\n"); name = X509_REQ_get_subject_name(req); for (i = 0; i < X509_NAME_entry_count(name); i++) { ne = X509_NAME_get_entry(name, i); str = X509_NAME_ENTRY_get_data(ne); obj = X509_NAME_ENTRY_get_object(ne); if (msie_hack) { /* assume all type should be strings */ nid = OBJ_obj2nid(ne->object); if (str->type == V_ASN1_UNIVERSALSTRING) ASN1_UNIVERSALSTRING_to_string(str); if ((str->type == V_ASN1_IA5STRING) && (nid != NID_pkcs9_emailAddress)) str->type = V_ASN1_T61STRING; if ((nid == NID_pkcs9_emailAddress) && (str->type == V_ASN1_PRINTABLESTRING)) str->type = V_ASN1_IA5STRING; } /* If no EMAIL is wanted in the subject */ if ((OBJ_obj2nid(obj) == NID_pkcs9_emailAddress) && (!email_dn)) continue; /* check some things */ if ((OBJ_obj2nid(obj) == NID_pkcs9_emailAddress) && (str->type != V_ASN1_IA5STRING)) { BIO_printf(bio_err, "\nemailAddress type needs to be of type IA5STRING\n"); goto err; } if ((str->type != V_ASN1_BMPSTRING) && (str->type != V_ASN1_UTF8STRING)) { j = ASN1_PRINTABLE_type(str->data, str->length); if (((j == V_ASN1_T61STRING) && (str->type != V_ASN1_T61STRING)) || ((j == V_ASN1_IA5STRING) && (str->type == V_ASN1_PRINTABLESTRING))) { BIO_printf(bio_err, "\nThe string contains characters that are illegal for the ASN.1 type\n"); goto err; } } if (default_op) old_entry_print(bio_err, obj, str); } /* Ok, now we check the 'policy' stuff. */ if ((subject = X509_NAME_new()) == NULL) { BIO_printf(bio_err, "Memory allocation failure\n"); goto err; } /* take a copy of the issuer name before we mess with it. */ if (selfsign) CAname = X509_NAME_dup(name); else CAname = X509_NAME_dup(x509->cert_info->subject); if (CAname == NULL) goto err; str = str2 = NULL; for (i = 0; i < sk_CONF_VALUE_num(policy); i++) { cv = sk_CONF_VALUE_value(policy, i); /* get the object id */ if ((j = OBJ_txt2nid(cv->name)) == NID_undef) { BIO_printf(bio_err, "%s:unknown object type in 'policy' configuration\n", cv->name); goto err; } obj = OBJ_nid2obj(j); last = -1; for (;;) { /* lookup the object in the supplied name list */ j = X509_NAME_get_index_by_OBJ(name, obj, last); if (j < 0) { if (last != -1) break; tne = NULL; } else { tne = X509_NAME_get_entry(name, j); } last = j; /* depending on the 'policy', decide what to do. */ push = NULL; if (strcmp(cv->value, "optional") == 0) { if (tne != NULL) push = tne; } else if (strcmp(cv->value, "supplied") == 0) { if (tne == NULL) { BIO_printf(bio_err, "The %s field needed to be supplied and was missing\n", cv->name); goto err; } else push = tne; } else if (strcmp(cv->value, "match") == 0) { int last2; if (tne == NULL) { BIO_printf(bio_err, "The mandatory %s field was missing\n", cv->name); goto err; } last2 = -1; again2: j = X509_NAME_get_index_by_OBJ(CAname, obj, last2); if ((j < 0) && (last2 == -1)) { BIO_printf(bio_err, "The %s field does not exist in the CA certificate,\nthe 'policy' is misconfigured\n", cv->name); goto err; } if (j >= 0) { push = X509_NAME_get_entry(CAname, j); str = X509_NAME_ENTRY_get_data(tne); str2 = X509_NAME_ENTRY_get_data(push); last2 = j; if (ASN1_STRING_cmp(str, str2) != 0) goto again2; } if (j < 0) { BIO_printf(bio_err, "The %s field needed to be the same in the\nCA certificate (%s) and the request (%s)\n", cv->name, ((str2 == NULL) ? "NULL" : (char *)str2->data), ((str == NULL) ? "NULL" : (char *)str->data)); goto err; } } else { BIO_printf(bio_err, "%s:invalid type in 'policy' configuration\n", cv->value); goto err; } if (push != NULL) { if (!X509_NAME_add_entry(subject, push, -1, 0)) { if (push != NULL) X509_NAME_ENTRY_free(push); BIO_printf(bio_err, "Memory allocation failure\n"); goto err; } } if (j < 0) break; } } if (preserve) { X509_NAME_free(subject); /* subject=X509_NAME_dup(X509_REQ_get_subject_name(req)); */ subject = X509_NAME_dup(name); if (subject == NULL) goto err; } if (verbose) BIO_printf(bio_err, "The subject name appears to be ok, checking data base for clashes\n"); /* Build the correct Subject if no e-mail is wanted in the subject */ /* * and add it later on because of the method extensions are added * (altName) */ if (email_dn) dn_subject = subject; else { X509_NAME_ENTRY *tmpne; /* * Its best to dup the subject DN and then delete any email addresses * because this retains its structure. */ if (!(dn_subject = X509_NAME_dup(subject))) { BIO_printf(bio_err, "Memory allocation failure\n"); goto err; } while ((i = X509_NAME_get_index_by_NID(dn_subject, NID_pkcs9_emailAddress, -1)) >= 0) { tmpne = X509_NAME_get_entry(dn_subject, i); X509_NAME_delete_entry(dn_subject, i); X509_NAME_ENTRY_free(tmpne); } } if (BN_is_zero(serial)) row[DB_serial] = BUF_strdup("00"); else row[DB_serial] = BN_bn2hex(serial); if (row[DB_serial] == NULL) { BIO_printf(bio_err, "Memory allocation failure\n"); goto err; } if (db->attributes.unique_subject) { OPENSSL_STRING *crow = row; rrow = TXT_DB_get_by_index(db->db, DB_name, crow); if (rrow != NULL) { BIO_printf(bio_err, "ERROR:There is already a certificate for %s\n", row[DB_name]); } } if (rrow == NULL) { rrow = TXT_DB_get_by_index(db->db, DB_serial, row); if (rrow != NULL) { BIO_printf(bio_err, "ERROR:Serial number %s has already been issued,\n", row[DB_serial]); BIO_printf(bio_err, " check the database/serial_file for corruption\n"); } } if (rrow != NULL) { BIO_printf(bio_err, "The matching entry has the following details\n"); if (rrow[DB_type][0] == 'E') p = "Expired"; else if (rrow[DB_type][0] == 'R') p = "Revoked"; else if (rrow[DB_type][0] == 'V') p = "Valid"; else p = "\ninvalid type, Data base error\n"; BIO_printf(bio_err, "Type :%s\n", p);; if (rrow[DB_type][0] == 'R') { p = rrow[DB_exp_date]; if (p == NULL) p = "undef"; BIO_printf(bio_err, "Was revoked on:%s\n", p); } p = rrow[DB_exp_date]; if (p == NULL) p = "undef"; BIO_printf(bio_err, "Expires on :%s\n", p); p = rrow[DB_serial]; if (p == NULL) p = "undef"; BIO_printf(bio_err, "Serial Number :%s\n", p); p = rrow[DB_file]; if (p == NULL) p = "undef"; BIO_printf(bio_err, "File name :%s\n", p); p = rrow[DB_name]; if (p == NULL) p = "undef"; BIO_printf(bio_err, "Subject Name :%s\n", p); ok = -1; /* This is now a 'bad' error. */ goto err; } /* We are now totally happy, lets make and sign the certificate */ if (verbose) BIO_printf(bio_err, "Everything appears to be ok, creating and signing the certificate\n"); if ((ret = X509_new()) == NULL) goto err; ci = ret->cert_info; #ifdef X509_V3 /* Make it an X509 v3 certificate. */ if (!X509_set_version(ret, 2)) goto err; #endif if (BN_to_ASN1_INTEGER(serial, ci->serialNumber) == NULL) goto err; if (selfsign) { if (!X509_set_issuer_name(ret, subject)) goto err; } else { if (!X509_set_issuer_name(ret, X509_get_subject_name(x509))) goto err; } if (strcmp(startdate, "today") == 0) X509_gmtime_adj(X509_get_notBefore(ret), 0); else ASN1_TIME_set_string(X509_get_notBefore(ret), startdate); if (enddate == NULL) X509_time_adj_ex(X509_get_notAfter(ret), days, 0, NULL); else { int tdays; ASN1_TIME_set_string(X509_get_notAfter(ret), enddate); ASN1_TIME_diff(&tdays, NULL, NULL, X509_get_notAfter(ret)); days = tdays; } if (!X509_set_subject_name(ret, subject)) goto err; pktmp = X509_REQ_get_pubkey(req); i = X509_set_pubkey(ret, pktmp); EVP_PKEY_free(pktmp); if (!i) goto err; /* Lets add the extensions, if there are any */ if (ext_sect) { X509V3_CTX ctx; if (ci->version == NULL) if ((ci->version = ASN1_INTEGER_new()) == NULL) goto err; ASN1_INTEGER_set(ci->version, 2); /* version 3 certificate */ /* * Free the current entries if any, there should not be any I believe */ if (ci->extensions != NULL) sk_X509_EXTENSION_pop_free(ci->extensions, X509_EXTENSION_free); ci->extensions = NULL; /* Initialize the context structure */ if (selfsign) X509V3_set_ctx(&ctx, ret, ret, req, NULL, 0); else X509V3_set_ctx(&ctx, x509, ret, req, NULL, 0); if (extconf) { if (verbose) BIO_printf(bio_err, "Extra configuration file found\n"); /* Use the extconf configuration db LHASH */ X509V3_set_nconf(&ctx, extconf); /* Test the structure (needed?) */ /* X509V3_set_ctx_test(&ctx); */ /* Adds exts contained in the configuration file */ if (!X509V3_EXT_add_nconf(extconf, &ctx, ext_sect, ret)) { BIO_printf(bio_err, "ERROR: adding extensions in section %s\n", ext_sect); ERR_print_errors(bio_err); goto err; } if (verbose) BIO_printf(bio_err, "Successfully added extensions from file.\n"); } else if (ext_sect) { /* We found extensions to be set from config file */ X509V3_set_nconf(&ctx, lconf); if (!X509V3_EXT_add_nconf(lconf, &ctx, ext_sect, ret)) { BIO_printf(bio_err, "ERROR: adding extensions in section %s\n", ext_sect); ERR_print_errors(bio_err); goto err; } if (verbose) BIO_printf(bio_err, "Successfully added extensions from config\n"); } } /* Copy extensions from request (if any) */ if (!copy_extensions(ret, req, ext_copy)) { BIO_printf(bio_err, "ERROR: adding extensions from request\n"); ERR_print_errors(bio_err); goto err; } /* Set the right value for the noemailDN option */ if (email_dn == 0) { if (!X509_set_subject_name(ret, dn_subject)) goto err; } if (!default_op) { BIO_printf(bio_err, "Certificate Details:\n"); /* * Never print signature details because signature not present */ certopt |= X509_FLAG_NO_SIGDUMP | X509_FLAG_NO_SIGNAME; X509_print_ex(bio_err, ret, nameopt, certopt); } BIO_printf(bio_err, "Certificate is to be certified until "); ASN1_TIME_print(bio_err, X509_get_notAfter(ret)); if (days) BIO_printf(bio_err, " (%ld days)", days); BIO_printf(bio_err, "\n"); if (!batch) { BIO_printf(bio_err, "Sign the certificate? [y/n]:"); (void)BIO_flush(bio_err); buf[0] = '\0'; if (!fgets(buf, sizeof(buf) - 1, stdin)) { BIO_printf(bio_err, "CERTIFICATE WILL NOT BE CERTIFIED: I/O error\n"); ok = 0; goto err; } if (!((buf[0] == 'y') || (buf[0] == 'Y'))) { BIO_printf(bio_err, "CERTIFICATE WILL NOT BE CERTIFIED\n"); ok = 0; goto err; } } pktmp = X509_get_pubkey(ret); if (EVP_PKEY_missing_parameters(pktmp) && !EVP_PKEY_missing_parameters(pkey)) EVP_PKEY_copy_parameters(pktmp, pkey); EVP_PKEY_free(pktmp); if (!do_X509_sign(bio_err, ret, pkey, dgst, sigopts)) goto err; /* We now just add it to the database */ tm = X509_get_notAfter(ret); row[DB_type] = OPENSSL_malloc(2); row[DB_exp_date] = OPENSSL_malloc(tm->length + 1); row[DB_rev_date] = OPENSSL_malloc(1); row[DB_file] = OPENSSL_malloc(8); row[DB_name] = X509_NAME_oneline(X509_get_subject_name(ret), NULL, 0); if ((row[DB_type] == NULL) || (row[DB_exp_date] == NULL) || (row[DB_rev_date] == NULL) || (row[DB_file] == NULL) || (row[DB_name] == NULL)) { BIO_printf(bio_err, "Memory allocation failure\n"); goto err; } memcpy(row[DB_exp_date], tm->data, tm->length); row[DB_exp_date][tm->length] = '\0'; row[DB_rev_date][0] = '\0'; strcpy(row[DB_file], "unknown"); row[DB_type][0] = 'V'; row[DB_type][1] = '\0'; if ((irow = (char **)OPENSSL_malloc(sizeof(char *) * (DB_NUMBER + 1))) == NULL) { BIO_printf(bio_err, "Memory allocation failure\n"); goto err; } - for (i = 0; i < DB_NUMBER; i++) { + for (i = 0; i < DB_NUMBER; i++) irow[i] = row[i]; - row[i] = NULL; - } irow[DB_NUMBER] = NULL; if (!TXT_DB_insert(db->db, irow)) { BIO_printf(bio_err, "failed to update database\n"); BIO_printf(bio_err, "TXT_DB error number %ld\n", db->db->error); goto err; } + irow = NULL; ok = 1; err: - for (i = 0; i < DB_NUMBER; i++) - if (row[i] != NULL) + if (irow != NULL) { + for (i = 0; i < DB_NUMBER; i++) OPENSSL_free(row[i]); + OPENSSL_free(irow); + } if (CAname != NULL) X509_NAME_free(CAname); if (subject != NULL) X509_NAME_free(subject); if ((dn_subject != NULL) && !email_dn) X509_NAME_free(dn_subject); if (tmptm != NULL) ASN1_UTCTIME_free(tmptm); if (ok <= 0) { if (ret != NULL) X509_free(ret); ret = NULL; } else *xret = ret; return (ok); } static void write_new_certificate(BIO *bp, X509 *x, int output_der, int notext) { if (output_der) { (void)i2d_X509_bio(bp, x); return; } #if 0 /* ??? Not needed since X509_print prints all this stuff anyway */ f = X509_NAME_oneline(X509_get_issuer_name(x), buf, 256); BIO_printf(bp, "issuer :%s\n", f); f = X509_NAME_oneline(X509_get_subject_name(x), buf, 256); BIO_printf(bp, "subject:%s\n", f); BIO_puts(bp, "serial :"); i2a_ASN1_INTEGER(bp, x->cert_info->serialNumber); BIO_puts(bp, "\n\n"); #endif if (!notext) X509_print(bp, x); PEM_write_bio_X509(bp, x); } static int certify_spkac(X509 **xret, char *infile, EVP_PKEY *pkey, X509 *x509, const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, char *subj, unsigned long chtype, int multirdn, int email_dn, char *startdate, char *enddate, long days, char *ext_sect, CONF *lconf, int verbose, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy) { STACK_OF(CONF_VALUE) *sk = NULL; LHASH_OF(CONF_VALUE) *parms = NULL; X509_REQ *req = NULL; CONF_VALUE *cv = NULL; NETSCAPE_SPKI *spki = NULL; X509_REQ_INFO *ri; char *type, *buf; EVP_PKEY *pktmp = NULL; X509_NAME *n = NULL; X509_NAME_ENTRY *ne = NULL; int ok = -1, i, j; long errline; int nid; /* * Load input file into a hash table. (This is just an easy * way to read and parse the file, then put it into a convenient * STACK format). */ parms = CONF_load(NULL, infile, &errline); if (parms == NULL) { BIO_printf(bio_err, "error on line %ld of %s\n", errline, infile); ERR_print_errors(bio_err); goto err; } sk = CONF_get_section(parms, "default"); if (sk_CONF_VALUE_num(sk) == 0) { BIO_printf(bio_err, "no name/value pairs found in %s\n", infile); goto err; } /* * Now create a dummy X509 request structure. We don't actually * have an X509 request, but we have many of the components * (a public key, various DN components). The idea is that we * put these components into the right X509 request structure * and we can use the same code as if you had a real X509 request. */ req = X509_REQ_new(); if (req == NULL) { ERR_print_errors(bio_err); goto err; } /* * Build up the subject name set. */ ri = req->req_info; n = ri->subject; for (i = 0;; i++) { if (sk_CONF_VALUE_num(sk) <= i) break; cv = sk_CONF_VALUE_value(sk, i); type = cv->name; /* * Skip past any leading X. X: X, etc to allow for multiple instances */ for (buf = cv->name; *buf; buf++) if ((*buf == ':') || (*buf == ',') || (*buf == '.')) { buf++; if (*buf) type = buf; break; } buf = cv->value; if ((nid = OBJ_txt2nid(type)) == NID_undef) { if (strcmp(type, "SPKAC") == 0) { spki = NETSCAPE_SPKI_b64_decode(cv->value, -1); if (spki == NULL) { BIO_printf(bio_err, "unable to load Netscape SPKAC structure\n"); ERR_print_errors(bio_err); goto err; } } continue; } if (!X509_NAME_add_entry_by_NID(n, nid, chtype, (unsigned char *)buf, -1, -1, 0)) goto err; } if (spki == NULL) { BIO_printf(bio_err, "Netscape SPKAC structure not found in %s\n", infile); goto err; } /* * Now extract the key from the SPKI structure. */ BIO_printf(bio_err, "Check that the SPKAC request matches the signature\n"); if ((pktmp = NETSCAPE_SPKI_get_pubkey(spki)) == NULL) { BIO_printf(bio_err, "error unpacking SPKAC public key\n"); goto err; } j = NETSCAPE_SPKI_verify(spki, pktmp); if (j <= 0) { EVP_PKEY_free(pktmp); BIO_printf(bio_err, "signature verification failed on SPKAC public key\n"); goto err; } BIO_printf(bio_err, "Signature ok\n"); X509_REQ_set_pubkey(req, pktmp); EVP_PKEY_free(pktmp); ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial, subj, chtype, multirdn, email_dn, startdate, enddate, days, 1, verbose, req, ext_sect, lconf, certopt, nameopt, default_op, ext_copy, 0); err: if (req != NULL) X509_REQ_free(req); if (parms != NULL) CONF_free(parms); if (spki != NULL) NETSCAPE_SPKI_free(spki); if (ne != NULL) X509_NAME_ENTRY_free(ne); return (ok); } static int check_time_format(const char *str) { return ASN1_TIME_set_string(NULL, str); } static int do_revoke(X509 *x509, CA_DB *db, int type, char *value) { ASN1_UTCTIME *tm = NULL; char *row[DB_NUMBER], **rrow, **irow; char *rev_str = NULL; BIGNUM *bn = NULL; int ok = -1, i; for (i = 0; i < DB_NUMBER; i++) row[i] = NULL; row[DB_name] = X509_NAME_oneline(X509_get_subject_name(x509), NULL, 0); bn = ASN1_INTEGER_to_BN(X509_get_serialNumber(x509), NULL); if (!bn) goto err; if (BN_is_zero(bn)) row[DB_serial] = BUF_strdup("00"); else row[DB_serial] = BN_bn2hex(bn); BN_free(bn); if ((row[DB_name] == NULL) || (row[DB_serial] == NULL)) { BIO_printf(bio_err, "Memory allocation failure\n"); goto err; } /* * We have to lookup by serial number because name lookup skips revoked * certs */ rrow = TXT_DB_get_by_index(db->db, DB_serial, row); if (rrow == NULL) { BIO_printf(bio_err, "Adding Entry with serial number %s to DB for %s\n", row[DB_serial], row[DB_name]); /* We now just add it to the database */ row[DB_type] = (char *)OPENSSL_malloc(2); tm = X509_get_notAfter(x509); row[DB_exp_date] = (char *)OPENSSL_malloc(tm->length + 1); memcpy(row[DB_exp_date], tm->data, tm->length); row[DB_exp_date][tm->length] = '\0'; row[DB_rev_date] = NULL; /* row[DB_serial] done already */ row[DB_file] = (char *)OPENSSL_malloc(8); /* row[DB_name] done already */ if ((row[DB_type] == NULL) || (row[DB_exp_date] == NULL) || (row[DB_file] == NULL)) { BIO_printf(bio_err, "Memory allocation failure\n"); goto err; } BUF_strlcpy(row[DB_file], "unknown", 8); row[DB_type][0] = 'V'; row[DB_type][1] = '\0'; if ((irow = (char **)OPENSSL_malloc(sizeof(char *) * (DB_NUMBER + 1))) == NULL) { BIO_printf(bio_err, "Memory allocation failure\n"); goto err; } - for (i = 0; i < DB_NUMBER; i++) { + for (i = 0; i < DB_NUMBER; i++) irow[i] = row[i]; - row[i] = NULL; - } irow[DB_NUMBER] = NULL; if (!TXT_DB_insert(db->db, irow)) { BIO_printf(bio_err, "failed to update database\n"); BIO_printf(bio_err, "TXT_DB error number %ld\n", db->db->error); + OPENSSL_free(irow); goto err; } + + for (i = 0; i < DB_NUMBER; i++) + row[i] = NULL; /* Revoke Certificate */ if (type == -1) ok = 1; else ok = do_revoke(x509, db, type, value); goto err; } else if (index_name_cmp_noconst(row, rrow)) { BIO_printf(bio_err, "ERROR:name does not match %s\n", row[DB_name]); goto err; } else if (type == -1) { BIO_printf(bio_err, "ERROR:Already present, serial number %s\n", row[DB_serial]); goto err; } else if (rrow[DB_type][0] == 'R') { BIO_printf(bio_err, "ERROR:Already revoked, serial number %s\n", row[DB_serial]); goto err; } else { BIO_printf(bio_err, "Revoking Certificate %s.\n", rrow[DB_serial]); rev_str = make_revocation_str(type, value); if (!rev_str) { BIO_printf(bio_err, "Error in revocation arguments\n"); goto err; } rrow[DB_type][0] = 'R'; rrow[DB_type][1] = '\0'; rrow[DB_rev_date] = rev_str; } ok = 1; err: for (i = 0; i < DB_NUMBER; i++) { if (row[i] != NULL) OPENSSL_free(row[i]); } return (ok); } static int get_certificate_status(const char *serial, CA_DB *db) { char *row[DB_NUMBER], **rrow; int ok = -1, i; /* Free Resources */ for (i = 0; i < DB_NUMBER; i++) row[i] = NULL; /* Malloc needed char spaces */ row[DB_serial] = OPENSSL_malloc(strlen(serial) + 2); if (row[DB_serial] == NULL) { BIO_printf(bio_err, "Malloc failure\n"); goto err; } if (strlen(serial) % 2) { /* * Set the first char to 0 */ ; row[DB_serial][0] = '0'; /* Copy String from serial to row[DB_serial] */ memcpy(row[DB_serial] + 1, serial, strlen(serial)); row[DB_serial][strlen(serial) + 1] = '\0'; } else { /* Copy String from serial to row[DB_serial] */ memcpy(row[DB_serial], serial, strlen(serial)); row[DB_serial][strlen(serial)] = '\0'; } /* Make it Upper Case */ for (i = 0; row[DB_serial][i] != '\0'; i++) row[DB_serial][i] = toupper((unsigned char)row[DB_serial][i]); ok = 1; /* Search for the certificate */ rrow = TXT_DB_get_by_index(db->db, DB_serial, row); if (rrow == NULL) { BIO_printf(bio_err, "Serial %s not present in db.\n", row[DB_serial]); ok = -1; goto err; } else if (rrow[DB_type][0] == 'V') { BIO_printf(bio_err, "%s=Valid (%c)\n", row[DB_serial], rrow[DB_type][0]); goto err; } else if (rrow[DB_type][0] == 'R') { BIO_printf(bio_err, "%s=Revoked (%c)\n", row[DB_serial], rrow[DB_type][0]); goto err; } else if (rrow[DB_type][0] == 'E') { BIO_printf(bio_err, "%s=Expired (%c)\n", row[DB_serial], rrow[DB_type][0]); goto err; } else if (rrow[DB_type][0] == 'S') { BIO_printf(bio_err, "%s=Suspended (%c)\n", row[DB_serial], rrow[DB_type][0]); goto err; } else { BIO_printf(bio_err, "%s=Unknown (%c).\n", row[DB_serial], rrow[DB_type][0]); ok = -1; } err: for (i = 0; i < DB_NUMBER; i++) { if (row[i] != NULL) OPENSSL_free(row[i]); } return (ok); } static int do_updatedb(CA_DB *db) { ASN1_UTCTIME *a_tm = NULL; int i, cnt = 0; int db_y2k, a_y2k; /* flags = 1 if y >= 2000 */ char **rrow, *a_tm_s; a_tm = ASN1_UTCTIME_new(); if (a_tm == NULL) return -1; /* get actual time and make a string */ a_tm = X509_gmtime_adj(a_tm, 0); a_tm_s = (char *)OPENSSL_malloc(a_tm->length + 1); if (a_tm_s == NULL) { cnt = -1; goto err; } memcpy(a_tm_s, a_tm->data, a_tm->length); a_tm_s[a_tm->length] = '\0'; if (strncmp(a_tm_s, "49", 2) <= 0) a_y2k = 1; else a_y2k = 0; for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { rrow = sk_OPENSSL_PSTRING_value(db->db->data, i); if (rrow[DB_type][0] == 'V') { /* ignore entries that are not valid */ if (strncmp(rrow[DB_exp_date], "49", 2) <= 0) db_y2k = 1; else db_y2k = 0; if (db_y2k == a_y2k) { /* all on the same y2k side */ if (strcmp(rrow[DB_exp_date], a_tm_s) <= 0) { rrow[DB_type][0] = 'E'; rrow[DB_type][1] = '\0'; cnt++; BIO_printf(bio_err, "%s=Expired\n", rrow[DB_serial]); } } else if (db_y2k < a_y2k) { rrow[DB_type][0] = 'E'; rrow[DB_type][1] = '\0'; cnt++; BIO_printf(bio_err, "%s=Expired\n", rrow[DB_serial]); } } } err: ASN1_UTCTIME_free(a_tm); OPENSSL_free(a_tm_s); return (cnt); } static const char *crl_reasons[] = { /* CRL reason strings */ "unspecified", "keyCompromise", "CACompromise", "affiliationChanged", "superseded", "cessationOfOperation", "certificateHold", "removeFromCRL", /* Additional pseudo reasons */ "holdInstruction", "keyTime", "CAkeyTime" }; #define NUM_REASONS (sizeof(crl_reasons) / sizeof(char *)) /* * Given revocation information convert to a DB string. The format of the * string is: revtime[,reason,extra]. Where 'revtime' is the revocation time * (the current time). 'reason' is the optional CRL reason and 'extra' is any * additional argument */ char *make_revocation_str(int rev_type, char *rev_arg) { char *other = NULL, *str; const char *reason = NULL; ASN1_OBJECT *otmp; ASN1_UTCTIME *revtm = NULL; int i; switch (rev_type) { case REV_NONE: break; case REV_CRL_REASON: for (i = 0; i < 8; i++) { if (!strcasecmp(rev_arg, crl_reasons[i])) { reason = crl_reasons[i]; break; } } if (reason == NULL) { BIO_printf(bio_err, "Unknown CRL reason %s\n", rev_arg); return NULL; } break; case REV_HOLD: /* Argument is an OID */ otmp = OBJ_txt2obj(rev_arg, 0); ASN1_OBJECT_free(otmp); if (otmp == NULL) { BIO_printf(bio_err, "Invalid object identifier %s\n", rev_arg); return NULL; } reason = "holdInstruction"; other = rev_arg; break; case REV_KEY_COMPROMISE: case REV_CA_COMPROMISE: /* Argument is the key compromise time */ if (!ASN1_GENERALIZEDTIME_set_string(NULL, rev_arg)) { BIO_printf(bio_err, "Invalid time format %s. Need YYYYMMDDHHMMSSZ\n", rev_arg); return NULL; } other = rev_arg; if (rev_type == REV_KEY_COMPROMISE) reason = "keyTime"; else reason = "CAkeyTime"; break; } revtm = X509_gmtime_adj(NULL, 0); if (!revtm) return NULL; i = revtm->length + 1; if (reason) i += strlen(reason) + 1; if (other) i += strlen(other) + 1; str = OPENSSL_malloc(i); if (!str) return NULL; BUF_strlcpy(str, (char *)revtm->data, i); if (reason) { BUF_strlcat(str, ",", i); BUF_strlcat(str, reason, i); } if (other) { BUF_strlcat(str, ",", i); BUF_strlcat(str, other, i); } ASN1_UTCTIME_free(revtm); return str; } /*- * Convert revocation field to X509_REVOKED entry * return code: * 0 error * 1 OK * 2 OK and some extensions added (i.e. V2 CRL) */ int make_revoked(X509_REVOKED *rev, const char *str) { char *tmp = NULL; int reason_code = -1; int i, ret = 0; ASN1_OBJECT *hold = NULL; ASN1_GENERALIZEDTIME *comp_time = NULL; ASN1_ENUMERATED *rtmp = NULL; ASN1_TIME *revDate = NULL; i = unpack_revinfo(&revDate, &reason_code, &hold, &comp_time, str); if (i == 0) goto err; if (rev && !X509_REVOKED_set_revocationDate(rev, revDate)) goto err; if (rev && (reason_code != OCSP_REVOKED_STATUS_NOSTATUS)) { rtmp = ASN1_ENUMERATED_new(); if (!rtmp || !ASN1_ENUMERATED_set(rtmp, reason_code)) goto err; if (!X509_REVOKED_add1_ext_i2d(rev, NID_crl_reason, rtmp, 0, 0)) goto err; } if (rev && comp_time) { if (!X509_REVOKED_add1_ext_i2d (rev, NID_invalidity_date, comp_time, 0, 0)) goto err; } if (rev && hold) { if (!X509_REVOKED_add1_ext_i2d (rev, NID_hold_instruction_code, hold, 0, 0)) goto err; } if (reason_code != OCSP_REVOKED_STATUS_NOSTATUS) ret = 2; else ret = 1; err: if (tmp) OPENSSL_free(tmp); ASN1_OBJECT_free(hold); ASN1_GENERALIZEDTIME_free(comp_time); ASN1_ENUMERATED_free(rtmp); ASN1_TIME_free(revDate); return ret; } int old_entry_print(BIO *bp, ASN1_OBJECT *obj, ASN1_STRING *str) { char buf[25], *pbuf, *p; int j; j = i2a_ASN1_OBJECT(bp, obj); pbuf = buf; for (j = 22 - j; j > 0; j--) *(pbuf++) = ' '; *(pbuf++) = ':'; *(pbuf++) = '\0'; BIO_puts(bp, buf); if (str->type == V_ASN1_PRINTABLESTRING) BIO_printf(bp, "PRINTABLE:'"); else if (str->type == V_ASN1_T61STRING) BIO_printf(bp, "T61STRING:'"); else if (str->type == V_ASN1_IA5STRING) BIO_printf(bp, "IA5STRING:'"); else if (str->type == V_ASN1_UNIVERSALSTRING) BIO_printf(bp, "UNIVERSALSTRING:'"); else BIO_printf(bp, "ASN.1 %2d:'", str->type); p = (char *)str->data; for (j = str->length; j > 0; j--) { if ((*p >= ' ') && (*p <= '~')) BIO_printf(bp, "%c", *p); else if (*p & 0x80) BIO_printf(bp, "\\0x%02X", *p); else if ((unsigned char)*p == 0xf7) BIO_printf(bp, "^?"); else BIO_printf(bp, "^%c", *p + '@'); p++; } BIO_printf(bp, "'\n"); return 1; } int unpack_revinfo(ASN1_TIME **prevtm, int *preason, ASN1_OBJECT **phold, ASN1_GENERALIZEDTIME **pinvtm, const char *str) { char *tmp = NULL; char *rtime_str, *reason_str = NULL, *arg_str = NULL, *p; int reason_code = -1; int ret = 0; unsigned int i; ASN1_OBJECT *hold = NULL; ASN1_GENERALIZEDTIME *comp_time = NULL; tmp = BUF_strdup(str); if (!tmp) { BIO_printf(bio_err, "memory allocation failure\n"); goto err; } p = strchr(tmp, ','); rtime_str = tmp; if (p) { *p = '\0'; p++; reason_str = p; p = strchr(p, ','); if (p) { *p = '\0'; arg_str = p + 1; } } if (prevtm) { *prevtm = ASN1_UTCTIME_new(); if (!*prevtm) { BIO_printf(bio_err, "memory allocation failure\n"); goto err; } if (!ASN1_UTCTIME_set_string(*prevtm, rtime_str)) { BIO_printf(bio_err, "invalid revocation date %s\n", rtime_str); goto err; } } if (reason_str) { for (i = 0; i < NUM_REASONS; i++) { if (!strcasecmp(reason_str, crl_reasons[i])) { reason_code = i; break; } } if (reason_code == OCSP_REVOKED_STATUS_NOSTATUS) { BIO_printf(bio_err, "invalid reason code %s\n", reason_str); goto err; } if (reason_code == 7) reason_code = OCSP_REVOKED_STATUS_REMOVEFROMCRL; else if (reason_code == 8) { /* Hold instruction */ if (!arg_str) { BIO_printf(bio_err, "missing hold instruction\n"); goto err; } reason_code = OCSP_REVOKED_STATUS_CERTIFICATEHOLD; hold = OBJ_txt2obj(arg_str, 0); if (!hold) { BIO_printf(bio_err, "invalid object identifier %s\n", arg_str); goto err; } if (phold) *phold = hold; } else if ((reason_code == 9) || (reason_code == 10)) { if (!arg_str) { BIO_printf(bio_err, "missing compromised time\n"); goto err; } comp_time = ASN1_GENERALIZEDTIME_new(); if (!comp_time) { BIO_printf(bio_err, "memory allocation failure\n"); goto err; } if (!ASN1_GENERALIZEDTIME_set_string(comp_time, arg_str)) { BIO_printf(bio_err, "invalid compromised time %s\n", arg_str); goto err; } if (reason_code == 9) reason_code = OCSP_REVOKED_STATUS_KEYCOMPROMISE; else reason_code = OCSP_REVOKED_STATUS_CACOMPROMISE; } } if (preason) *preason = reason_code; if (pinvtm) *pinvtm = comp_time; else ASN1_GENERALIZEDTIME_free(comp_time); ret = 1; err: if (tmp) OPENSSL_free(tmp); if (!phold) ASN1_OBJECT_free(hold); if (!pinvtm) ASN1_GENERALIZEDTIME_free(comp_time); return ret; } Index: vendor-crypto/openssl/dist/apps/dhparam.c =================================================================== --- vendor-crypto/openssl/dist/apps/dhparam.c (revision 318896) +++ vendor-crypto/openssl/dist/apps/dhparam.c (revision 318897) @@ -1,544 +1,556 @@ /* apps/dhparam.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ /* ==================================================================== * Copyright (c) 1998-2000 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include /* for OPENSSL_NO_DH */ #ifndef OPENSSL_NO_DH # include # include # include # include # include "apps.h" # include # include # include # include # include # include # ifndef OPENSSL_NO_DSA # include # endif # undef PROG # define PROG dhparam_main # define DEFBITS 2048 /*- * -inform arg - input format - default PEM (DER or PEM) * -outform arg - output format - default PEM * -in arg - input file - default stdin * -out arg - output file - default stdout * -dsaparam - read or generate DSA parameters, convert to DH * -check - check the parameters are ok * -noout * -text * -C */ static int MS_CALLBACK dh_cb(int p, int n, BN_GENCB *cb); int MAIN(int, char **); int MAIN(int argc, char **argv) { DH *dh = NULL; int i, badops = 0, text = 0; # ifndef OPENSSL_NO_DSA int dsaparam = 0; # endif BIO *in = NULL, *out = NULL; int informat, outformat, check = 0, noout = 0, C = 0, ret = 1; char *infile, *outfile, *prog; char *inrand = NULL; char *engine = NULL; ENGINE *e = NULL; int num = 0, g = 0; apps_startup(); if (bio_err == NULL) if ((bio_err = BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT); if (!load_config(bio_err, NULL)) goto end; infile = NULL; outfile = NULL; informat = FORMAT_PEM; outformat = FORMAT_PEM; prog = argv[0]; argc--; argv++; while (argc >= 1) { if (strcmp(*argv, "-inform") == 0) { if (--argc < 1) goto bad; informat = str2fmt(*(++argv)); } else if (strcmp(*argv, "-outform") == 0) { if (--argc < 1) goto bad; outformat = str2fmt(*(++argv)); } else if (strcmp(*argv, "-in") == 0) { if (--argc < 1) goto bad; infile = *(++argv); } else if (strcmp(*argv, "-out") == 0) { if (--argc < 1) goto bad; outfile = *(++argv); } # ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv, "-engine") == 0) { if (--argc < 1) goto bad; engine = *(++argv); } # endif else if (strcmp(*argv, "-check") == 0) check = 1; else if (strcmp(*argv, "-text") == 0) text = 1; # ifndef OPENSSL_NO_DSA else if (strcmp(*argv, "-dsaparam") == 0) dsaparam = 1; # endif else if (strcmp(*argv, "-C") == 0) C = 1; else if (strcmp(*argv, "-noout") == 0) noout = 1; else if (strcmp(*argv, "-2") == 0) g = 2; else if (strcmp(*argv, "-5") == 0) g = 5; else if (strcmp(*argv, "-rand") == 0) { if (--argc < 1) goto bad; inrand = *(++argv); } else if (((sscanf(*argv, "%d", &num) == 0) || (num <= 0))) goto bad; argv++; argc--; } if (badops) { bad: BIO_printf(bio_err, "%s [options] [numbits]\n", prog); BIO_printf(bio_err, "where options are\n"); BIO_printf(bio_err, " -inform arg input format - one of DER PEM\n"); BIO_printf(bio_err, " -outform arg output format - one of DER PEM\n"); BIO_printf(bio_err, " -in arg input file\n"); BIO_printf(bio_err, " -out arg output file\n"); # ifndef OPENSSL_NO_DSA BIO_printf(bio_err, " -dsaparam read or generate DSA parameters, convert to DH\n"); # endif BIO_printf(bio_err, " -check check the DH parameters\n"); BIO_printf(bio_err, " -text print a text form of the DH parameters\n"); BIO_printf(bio_err, " -C Output C code\n"); BIO_printf(bio_err, " -2 generate parameters using 2 as the generator value\n"); BIO_printf(bio_err, " -5 generate parameters using 5 as the generator value\n"); BIO_printf(bio_err, " numbits number of bits in to generate (default 2048)\n"); # ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err, " -engine e use engine e, possibly a hardware device.\n"); # endif BIO_printf(bio_err, " -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR); BIO_printf(bio_err, " - load the file (or the files in the directory) into\n"); BIO_printf(bio_err, " the random number generator\n"); BIO_printf(bio_err, " -noout no output\n"); goto end; } ERR_load_crypto_strings(); e = setup_engine(bio_err, engine, 0); if (g && !num) num = DEFBITS; # ifndef OPENSSL_NO_DSA if (dsaparam) { if (g) { BIO_printf(bio_err, "generator may not be chosen for DSA parameters\n"); goto end; } } else # endif { /* DH parameters */ if (num && !g) g = 2; } if (num) { BN_GENCB cb; BN_GENCB_set(&cb, dh_cb, bio_err); if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL) { BIO_printf(bio_err, "warning, not much extra random data, consider using the -rand option\n"); } if (inrand != NULL) BIO_printf(bio_err, "%ld semi-random bytes loaded\n", app_RAND_load_files(inrand)); # ifndef OPENSSL_NO_DSA if (dsaparam) { DSA *dsa = DSA_new(); BIO_printf(bio_err, "Generating DSA parameters, %d bit long prime\n", num); if (!dsa || !DSA_generate_parameters_ex(dsa, num, NULL, 0, NULL, NULL, &cb)) { if (dsa) DSA_free(dsa); ERR_print_errors(bio_err); goto end; } dh = DSA_dup_DH(dsa); DSA_free(dsa); if (dh == NULL) { ERR_print_errors(bio_err); goto end; } } else # endif { dh = DH_new(); BIO_printf(bio_err, "Generating DH parameters, %d bit long safe prime, generator %d\n", num, g); BIO_printf(bio_err, "This is going to take a long time\n"); if (!dh || !DH_generate_parameters_ex(dh, num, g, &cb)) { ERR_print_errors(bio_err); goto end; } } app_RAND_write_file(NULL, bio_err); } else { in = BIO_new(BIO_s_file()); if (in == NULL) { ERR_print_errors(bio_err); goto end; } if (infile == NULL) BIO_set_fp(in, stdin, BIO_NOCLOSE); else { if (BIO_read_filename(in, infile) <= 0) { perror(infile); goto end; } } if (informat != FORMAT_ASN1 && informat != FORMAT_PEM) { BIO_printf(bio_err, "bad input format specified\n"); goto end; } # ifndef OPENSSL_NO_DSA if (dsaparam) { DSA *dsa; if (informat == FORMAT_ASN1) dsa = d2i_DSAparams_bio(in, NULL); else /* informat == FORMAT_PEM */ dsa = PEM_read_bio_DSAparams(in, NULL, NULL, NULL); if (dsa == NULL) { BIO_printf(bio_err, "unable to load DSA parameters\n"); ERR_print_errors(bio_err); goto end; } dh = DSA_dup_DH(dsa); DSA_free(dsa); if (dh == NULL) { ERR_print_errors(bio_err); goto end; } } else # endif { - if (informat == FORMAT_ASN1) + if (informat == FORMAT_ASN1) { + /* + * We have no PEM header to determine what type of DH params it + * is. We'll just try both. + */ dh = d2i_DHparams_bio(in, NULL); - else /* informat == FORMAT_PEM */ + /* BIO_reset() returns 0 for success for file BIOs only!!! */ + if (dh == NULL && BIO_reset(in) == 0) + dh = d2i_DHxparams_bio(in, NULL); + } else { + /* informat == FORMAT_PEM */ dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL); + } if (dh == NULL) { BIO_printf(bio_err, "unable to load DH parameters\n"); ERR_print_errors(bio_err); goto end; } } /* dh != NULL */ } out = BIO_new(BIO_s_file()); if (out == NULL) { ERR_print_errors(bio_err); goto end; } if (outfile == NULL) { BIO_set_fp(out, stdout, BIO_NOCLOSE); # ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); out = BIO_push(tmpbio, out); } # endif } else { if (BIO_write_filename(out, outfile) <= 0) { perror(outfile); goto end; } } if (text) { DHparams_print(out, dh); } if (check) { if (!DH_check(dh, &i)) { ERR_print_errors(bio_err); goto end; } if (i & DH_CHECK_P_NOT_PRIME) printf("p value is not prime\n"); if (i & DH_CHECK_P_NOT_SAFE_PRIME) printf("p value is not a safe prime\n"); if (i & DH_UNABLE_TO_CHECK_GENERATOR) printf("unable to check the generator value\n"); if (i & DH_NOT_SUITABLE_GENERATOR) printf("the g value is not a generator\n"); if (i == 0) printf("DH parameters appear to be ok.\n"); } if (C) { unsigned char *data; int len, l, bits; len = BN_num_bytes(dh->p); bits = BN_num_bits(dh->p); data = (unsigned char *)OPENSSL_malloc(len); if (data == NULL) { perror("OPENSSL_malloc"); goto end; } printf("#ifndef HEADER_DH_H\n" "#include \n" "#endif\n"); printf("DH *get_dh%d()\n\t{\n", bits); l = BN_bn2bin(dh->p, data); printf("\tstatic unsigned char dh%d_p[]={", bits); for (i = 0; i < l; i++) { if ((i % 12) == 0) printf("\n\t\t"); printf("0x%02X,", data[i]); } printf("\n\t\t};\n"); l = BN_bn2bin(dh->g, data); printf("\tstatic unsigned char dh%d_g[]={", bits); for (i = 0; i < l; i++) { if ((i % 12) == 0) printf("\n\t\t"); printf("0x%02X,", data[i]); } printf("\n\t\t};\n"); printf("\tDH *dh;\n\n"); printf("\tif ((dh=DH_new()) == NULL) return(NULL);\n"); printf("\tdh->p=BN_bin2bn(dh%d_p,sizeof(dh%d_p),NULL);\n", bits, bits); printf("\tdh->g=BN_bin2bn(dh%d_g,sizeof(dh%d_g),NULL);\n", bits, bits); printf("\tif ((dh->p == NULL) || (dh->g == NULL))\n"); printf("\t\t{ DH_free(dh); return(NULL); }\n"); if (dh->length) printf("\tdh->length = %ld;\n", dh->length); printf("\treturn(dh);\n\t}\n"); OPENSSL_free(data); } if (!noout) { - if (outformat == FORMAT_ASN1) - i = i2d_DHparams_bio(out, dh); - else if (outformat == FORMAT_PEM) { - if (dh->q) + if (outformat == FORMAT_ASN1) { + if (dh->q != NULL) + i = i2d_DHxparams_bio(out, dh); + else + i = i2d_DHparams_bio(out, dh); + } else if (outformat == FORMAT_PEM) { + if (dh->q != NULL) i = PEM_write_bio_DHxparams(out, dh); else i = PEM_write_bio_DHparams(out, dh); } else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } if (!i) { BIO_printf(bio_err, "unable to write DH parameters\n"); ERR_print_errors(bio_err); goto end; } } ret = 0; end: if (in != NULL) BIO_free(in); if (out != NULL) BIO_free_all(out); if (dh != NULL) DH_free(dh); release_engine(e); apps_shutdown(); OPENSSL_EXIT(ret); } /* dh_cb is identical to dsa_cb in apps/dsaparam.c */ static int MS_CALLBACK dh_cb(int p, int n, BN_GENCB *cb) { char c = '*'; if (p == 0) c = '.'; if (p == 1) c = '+'; if (p == 2) c = '*'; if (p == 3) c = '\n'; BIO_write(cb->arg, &c, 1); (void)BIO_flush(cb->arg); # ifdef LINT p = n; # endif return 1; } #else /* !OPENSSL_NO_DH */ # if PEDANTIC static void *dummy = &dummy; # endif #endif Index: vendor-crypto/openssl/dist/apps/enc.c =================================================================== --- vendor-crypto/openssl/dist/apps/enc.c (revision 318896) +++ vendor-crypto/openssl/dist/apps/enc.c (revision 318897) @@ -1,713 +1,728 @@ /* apps/enc.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include #include #include #include "apps.h" #include #include #include #include #include #include #include #ifndef OPENSSL_NO_COMP # include #endif #include int set_hex(char *in, unsigned char *out, int size); #undef SIZE #undef BSIZE #undef PROG #define SIZE (512) #define BSIZE (8*1024) #define PROG enc_main -static void show_ciphers(const OBJ_NAME *name, void *bio_) +struct doall_enc_ciphers { + BIO *bio; + int n; +}; + +static void show_ciphers(const OBJ_NAME *name, void *arg) { - BIO *bio = bio_; - static int n; + struct doall_enc_ciphers *dec = (struct doall_enc_ciphers *)arg; + const EVP_CIPHER *cipher; if (!islower((unsigned char)*name->name)) return; - BIO_printf(bio, "-%-25s", name->name); - if (++n == 3) { - BIO_printf(bio, "\n"); - n = 0; + /* Filter out ciphers that we cannot use */ + cipher = EVP_get_cipherbyname(name->name); + if (cipher == NULL || + (EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) != 0 || + EVP_CIPHER_mode(cipher) == EVP_CIPH_XTS_MODE) + return; + + BIO_printf(dec->bio, "-%-25s", name->name); + if (++dec->n == 3) { + BIO_printf(dec->bio, "\n"); + dec->n = 0; } else - BIO_printf(bio, " "); + BIO_printf(dec->bio, " "); } int MAIN(int, char **); int MAIN(int argc, char **argv) { static const char magic[] = "Salted__"; char mbuf[sizeof magic - 1]; char *strbuf = NULL; unsigned char *buff = NULL, *bufsize = NULL; int bsize = BSIZE, verbose = 0; int ret = 1, inl; int nopad = 0; unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH]; unsigned char salt[PKCS5_SALT_LEN]; char *str = NULL, *passarg = NULL, *pass = NULL; char *hkey = NULL, *hiv = NULL, *hsalt = NULL; char *md = NULL; int enc = 1, printkey = 0, i, base64 = 0; #ifdef ZLIB int do_zlib = 0; BIO *bzl = NULL; #endif int debug = 0, olb64 = 0, nosalt = 0; const EVP_CIPHER *cipher = NULL, *c; EVP_CIPHER_CTX *ctx = NULL; char *inf = NULL, *outf = NULL; BIO *in = NULL, *out = NULL, *b64 = NULL, *benc = NULL, *rbio = NULL, *wbio = NULL; #define PROG_NAME_SIZE 39 char pname[PROG_NAME_SIZE + 1]; char *engine = NULL; ENGINE *e = NULL; const EVP_MD *dgst = NULL; int non_fips_allow = 0; + struct doall_enc_ciphers dec; apps_startup(); if (bio_err == NULL) if ((bio_err = BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT); if (!load_config(bio_err, NULL)) goto end; /* first check the program name */ program_name(argv[0], pname, sizeof pname); if (strcmp(pname, "base64") == 0) base64 = 1; #ifdef ZLIB if (strcmp(pname, "zlib") == 0) do_zlib = 1; #endif cipher = EVP_get_cipherbyname(pname); #ifdef ZLIB if (!do_zlib && !base64 && (cipher == NULL) && (strcmp(pname, "enc") != 0)) #else if (!base64 && (cipher == NULL) && (strcmp(pname, "enc") != 0)) #endif { BIO_printf(bio_err, "%s is an unknown cipher\n", pname); goto bad; } argc--; argv++; while (argc >= 1) { if (strcmp(*argv, "-e") == 0) enc = 1; else if (strcmp(*argv, "-in") == 0) { if (--argc < 1) goto bad; inf = *(++argv); } else if (strcmp(*argv, "-out") == 0) { if (--argc < 1) goto bad; outf = *(++argv); } else if (strcmp(*argv, "-pass") == 0) { if (--argc < 1) goto bad; passarg = *(++argv); } #ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv, "-engine") == 0) { if (--argc < 1) goto bad; engine = *(++argv); } #endif else if (strcmp(*argv, "-d") == 0) enc = 0; else if (strcmp(*argv, "-p") == 0) printkey = 1; else if (strcmp(*argv, "-v") == 0) verbose = 1; else if (strcmp(*argv, "-nopad") == 0) nopad = 1; else if (strcmp(*argv, "-salt") == 0) nosalt = 0; else if (strcmp(*argv, "-nosalt") == 0) nosalt = 1; else if (strcmp(*argv, "-debug") == 0) debug = 1; else if (strcmp(*argv, "-P") == 0) printkey = 2; else if (strcmp(*argv, "-A") == 0) olb64 = 1; else if (strcmp(*argv, "-a") == 0) base64 = 1; else if (strcmp(*argv, "-base64") == 0) base64 = 1; #ifdef ZLIB else if (strcmp(*argv, "-z") == 0) do_zlib = 1; #endif else if (strcmp(*argv, "-bufsize") == 0) { if (--argc < 1) goto bad; bufsize = (unsigned char *)*(++argv); } else if (strcmp(*argv, "-k") == 0) { if (--argc < 1) goto bad; str = *(++argv); } else if (strcmp(*argv, "-kfile") == 0) { static char buf[128]; FILE *infile; char *file; if (--argc < 1) goto bad; file = *(++argv); infile = fopen(file, "r"); if (infile == NULL) { BIO_printf(bio_err, "unable to read key from '%s'\n", file); goto bad; } buf[0] = '\0'; if (!fgets(buf, sizeof buf, infile)) { BIO_printf(bio_err, "unable to read key from '%s'\n", file); goto bad; } fclose(infile); i = strlen(buf); if ((i > 0) && ((buf[i - 1] == '\n') || (buf[i - 1] == '\r'))) buf[--i] = '\0'; if ((i > 0) && ((buf[i - 1] == '\n') || (buf[i - 1] == '\r'))) buf[--i] = '\0'; if (i < 1) { BIO_printf(bio_err, "zero length password\n"); goto bad; } str = buf; } else if (strcmp(*argv, "-K") == 0) { if (--argc < 1) goto bad; hkey = *(++argv); } else if (strcmp(*argv, "-S") == 0) { if (--argc < 1) goto bad; hsalt = *(++argv); } else if (strcmp(*argv, "-iv") == 0) { if (--argc < 1) goto bad; hiv = *(++argv); } else if (strcmp(*argv, "-md") == 0) { if (--argc < 1) goto bad; md = *(++argv); } else if (strcmp(*argv, "-non-fips-allow") == 0) non_fips_allow = 1; else if ((argv[0][0] == '-') && ((c = EVP_get_cipherbyname(&(argv[0][1]))) != NULL)) { cipher = c; } else if (strcmp(*argv, "-none") == 0) cipher = NULL; else { BIO_printf(bio_err, "unknown option '%s'\n", *argv); bad: BIO_printf(bio_err, "options are\n"); BIO_printf(bio_err, "%-14s input file\n", "-in "); BIO_printf(bio_err, "%-14s output file\n", "-out "); BIO_printf(bio_err, "%-14s pass phrase source\n", "-pass "); BIO_printf(bio_err, "%-14s encrypt\n", "-e"); BIO_printf(bio_err, "%-14s decrypt\n", "-d"); BIO_printf(bio_err, "%-14s base64 encode/decode, depending on encryption flag\n", "-a/-base64"); BIO_printf(bio_err, "%-14s passphrase is the next argument\n", "-k"); BIO_printf(bio_err, "%-14s passphrase is the first line of the file argument\n", "-kfile"); BIO_printf(bio_err, "%-14s the next argument is the md to use to create a key\n", "-md"); BIO_printf(bio_err, "%-14s from a passphrase. One of md2, md5, sha or sha1\n", ""); BIO_printf(bio_err, "%-14s salt in hex is the next argument\n", "-S"); BIO_printf(bio_err, "%-14s key/iv in hex is the next argument\n", "-K/-iv"); BIO_printf(bio_err, "%-14s print the iv/key (then exit if -P)\n", "-[pP]"); BIO_printf(bio_err, "%-14s buffer size\n", "-bufsize "); BIO_printf(bio_err, "%-14s disable standard block padding\n", "-nopad"); #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err, "%-14s use engine e, possibly a hardware device.\n", "-engine e"); #endif BIO_printf(bio_err, "Cipher Types\n"); + dec.n = 0; + dec.bio = bio_err; OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH, - show_ciphers, bio_err); + show_ciphers, &dec); BIO_printf(bio_err, "\n"); goto end; } argc--; argv++; } e = setup_engine(bio_err, engine, 0); if (cipher && EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) { BIO_printf(bio_err, "AEAD ciphers not supported by the enc utility\n"); goto end; } if (cipher && (EVP_CIPHER_mode(cipher) == EVP_CIPH_XTS_MODE)) { BIO_printf(bio_err, "Ciphers in XTS mode are not supported by the enc utility\n"); goto end; } if (md && (dgst = EVP_get_digestbyname(md)) == NULL) { BIO_printf(bio_err, "%s is an unsupported message digest type\n", md); goto end; } if (dgst == NULL) { dgst = EVP_md5(); } if (bufsize != NULL) { unsigned long n; for (n = 0; *bufsize; bufsize++) { i = *bufsize; if ((i <= '9') && (i >= '0')) n = n * 10 + i - '0'; else if (i == 'k') { n *= 1024; bufsize++; break; } } if (*bufsize != '\0') { BIO_printf(bio_err, "invalid 'bufsize' specified.\n"); goto end; } /* It must be large enough for a base64 encoded line */ if (base64 && n < 80) n = 80; bsize = (int)n; if (verbose) BIO_printf(bio_err, "bufsize=%d\n", bsize); } strbuf = OPENSSL_malloc(SIZE); buff = (unsigned char *)OPENSSL_malloc(EVP_ENCODE_LENGTH(bsize)); if ((buff == NULL) || (strbuf == NULL)) { BIO_printf(bio_err, "OPENSSL_malloc failure %ld\n", (long)EVP_ENCODE_LENGTH(bsize)); goto end; } in = BIO_new(BIO_s_file()); out = BIO_new(BIO_s_file()); if ((in == NULL) || (out == NULL)) { ERR_print_errors(bio_err); goto end; } if (debug) { BIO_set_callback(in, BIO_debug_callback); BIO_set_callback(out, BIO_debug_callback); BIO_set_callback_arg(in, (char *)bio_err); BIO_set_callback_arg(out, (char *)bio_err); } if (inf == NULL) { #ifndef OPENSSL_NO_SETVBUF_IONBF if (bufsize != NULL) setvbuf(stdin, (char *)NULL, _IONBF, 0); #endif /* ndef OPENSSL_NO_SETVBUF_IONBF */ BIO_set_fp(in, stdin, BIO_NOCLOSE); } else { if (BIO_read_filename(in, inf) <= 0) { perror(inf); goto end; } } if (!str && passarg) { if (!app_passwd(bio_err, passarg, NULL, &pass, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } str = pass; } if ((str == NULL) && (cipher != NULL) && (hkey == NULL)) { for (;;) { char buf[200]; BIO_snprintf(buf, sizeof buf, "enter %s %s password:", OBJ_nid2ln(EVP_CIPHER_nid(cipher)), (enc) ? "encryption" : "decryption"); strbuf[0] = '\0'; i = EVP_read_pw_string((char *)strbuf, SIZE, buf, enc); if (i == 0) { if (strbuf[0] == '\0') { ret = 1; goto end; } str = strbuf; break; } if (i < 0) { BIO_printf(bio_err, "bad password read\n"); goto end; } } } if (outf == NULL) { BIO_set_fp(out, stdout, BIO_NOCLOSE); #ifndef OPENSSL_NO_SETVBUF_IONBF if (bufsize != NULL) setvbuf(stdout, (char *)NULL, _IONBF, 0); #endif /* ndef OPENSSL_NO_SETVBUF_IONBF */ #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); out = BIO_push(tmpbio, out); } #endif } else { if (BIO_write_filename(out, outf) <= 0) { perror(outf); goto end; } } rbio = in; wbio = out; #ifdef ZLIB if (do_zlib) { if ((bzl = BIO_new(BIO_f_zlib())) == NULL) goto end; if (enc) wbio = BIO_push(bzl, wbio); else rbio = BIO_push(bzl, rbio); } #endif if (base64) { if ((b64 = BIO_new(BIO_f_base64())) == NULL) goto end; if (debug) { BIO_set_callback(b64, BIO_debug_callback); BIO_set_callback_arg(b64, (char *)bio_err); } if (olb64) BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); if (enc) wbio = BIO_push(b64, wbio); else rbio = BIO_push(b64, rbio); } if (cipher != NULL) { /* * Note that str is NULL if a key was passed on the command line, so * we get no salt in that case. Is this a bug? */ if (str != NULL) { /* * Salt handling: if encrypting generate a salt and write to * output BIO. If decrypting read salt from input BIO. */ unsigned char *sptr; if (nosalt) sptr = NULL; else { if (enc) { if (hsalt) { if (!set_hex(hsalt, salt, sizeof salt)) { BIO_printf(bio_err, "invalid hex salt value\n"); goto end; } } else if (RAND_bytes(salt, sizeof salt) <= 0) goto end; /* * If -P option then don't bother writing */ if ((printkey != 2) && (BIO_write(wbio, magic, sizeof magic - 1) != sizeof magic - 1 || BIO_write(wbio, (char *)salt, sizeof salt) != sizeof salt)) { BIO_printf(bio_err, "error writing output file\n"); goto end; } } else if (BIO_read(rbio, mbuf, sizeof mbuf) != sizeof mbuf || BIO_read(rbio, (unsigned char *)salt, sizeof salt) != sizeof salt) { BIO_printf(bio_err, "error reading input file\n"); goto end; } else if (memcmp(mbuf, magic, sizeof magic - 1)) { BIO_printf(bio_err, "bad magic number\n"); goto end; } sptr = salt; } EVP_BytesToKey(cipher, dgst, sptr, (unsigned char *)str, strlen(str), 1, key, iv); /* * zero the complete buffer or the string passed from the command * line bug picked up by Larry J. Hughes Jr. */ if (str == strbuf) OPENSSL_cleanse(str, SIZE); else OPENSSL_cleanse(str, strlen(str)); } if (hiv != NULL) { int siz = EVP_CIPHER_iv_length(cipher); if (siz == 0) { BIO_printf(bio_err, "warning: iv not use by this cipher\n"); } else if (!set_hex(hiv, iv, sizeof iv)) { BIO_printf(bio_err, "invalid hex iv value\n"); goto end; } } if ((hiv == NULL) && (str == NULL) && EVP_CIPHER_iv_length(cipher) != 0) { /* * No IV was explicitly set and no IV was generated during * EVP_BytesToKey. Hence the IV is undefined, making correct * decryption impossible. */ BIO_printf(bio_err, "iv undefined\n"); goto end; } if ((hkey != NULL) && !set_hex(hkey, key, EVP_CIPHER_key_length(cipher))) { BIO_printf(bio_err, "invalid hex key value\n"); goto end; } if ((benc = BIO_new(BIO_f_cipher())) == NULL) goto end; /* * Since we may be changing parameters work on the encryption context * rather than calling BIO_set_cipher(). */ BIO_get_cipher_ctx(benc, &ctx); if (non_fips_allow) EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPH_FLAG_NON_FIPS_ALLOW); if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, enc)) { BIO_printf(bio_err, "Error setting cipher %s\n", EVP_CIPHER_name(cipher)); ERR_print_errors(bio_err); goto end; } if (nopad) EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, enc)) { BIO_printf(bio_err, "Error setting cipher %s\n", EVP_CIPHER_name(cipher)); ERR_print_errors(bio_err); goto end; } if (debug) { BIO_set_callback(benc, BIO_debug_callback); BIO_set_callback_arg(benc, (char *)bio_err); } if (printkey) { if (!nosalt) { printf("salt="); for (i = 0; i < (int)sizeof(salt); i++) printf("%02X", salt[i]); printf("\n"); } if (cipher->key_len > 0) { printf("key="); for (i = 0; i < cipher->key_len; i++) printf("%02X", key[i]); printf("\n"); } if (cipher->iv_len > 0) { printf("iv ="); for (i = 0; i < cipher->iv_len; i++) printf("%02X", iv[i]); printf("\n"); } if (printkey == 2) { ret = 0; goto end; } } } /* Only encrypt/decrypt as we write the file */ if (benc != NULL) wbio = BIO_push(benc, wbio); for (;;) { inl = BIO_read(rbio, (char *)buff, bsize); if (inl <= 0) break; if (BIO_write(wbio, (char *)buff, inl) != inl) { BIO_printf(bio_err, "error writing output file\n"); goto end; } } if (!BIO_flush(wbio)) { BIO_printf(bio_err, "bad decrypt\n"); goto end; } ret = 0; if (verbose) { BIO_printf(bio_err, "bytes read :%8ld\n", BIO_number_read(in)); BIO_printf(bio_err, "bytes written:%8ld\n", BIO_number_written(out)); } end: ERR_print_errors(bio_err); if (strbuf != NULL) OPENSSL_free(strbuf); if (buff != NULL) OPENSSL_free(buff); if (in != NULL) BIO_free(in); if (out != NULL) BIO_free_all(out); if (benc != NULL) BIO_free(benc); if (b64 != NULL) BIO_free(b64); #ifdef ZLIB if (bzl != NULL) BIO_free(bzl); #endif release_engine(e); if (pass) OPENSSL_free(pass); apps_shutdown(); OPENSSL_EXIT(ret); } int set_hex(char *in, unsigned char *out, int size) { int i, n; unsigned char j; n = strlen(in); if (n > (size * 2)) { BIO_printf(bio_err, "hex string is too long\n"); return (0); } memset(out, 0, size); for (i = 0; i < n; i++) { j = (unsigned char)*in; *(in++) = '\0'; if (j == 0) break; if ((j >= '0') && (j <= '9')) j -= '0'; else if ((j >= 'A') && (j <= 'F')) j = j - 'A' + 10; else if ((j >= 'a') && (j <= 'f')) j = j - 'a' + 10; else { BIO_printf(bio_err, "non-hex digit\n"); return (0); } if (i & 1) out[i / 2] |= j; else out[i / 2] = (j << 4); } return (1); } Index: vendor-crypto/openssl/dist/apps/engine.c =================================================================== --- vendor-crypto/openssl/dist/apps/engine.c (revision 318896) +++ vendor-crypto/openssl/dist/apps/engine.c (revision 318897) @@ -1,512 +1,515 @@ /* apps/engine.c */ /* * Written by Richard Levitte for the OpenSSL project * 2000. */ /* ==================================================================== * Copyright (c) 2000 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * licensing@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include #include #include #ifdef OPENSSL_NO_STDIO # define APPS_WIN16 #endif #include "apps.h" #include #ifndef OPENSSL_NO_ENGINE # include # include # undef PROG # define PROG engine_main static const char *engine_usage[] = { "usage: engine opts [engine ...]\n", " -v[v[v[v]]] - verbose mode, for each engine, list its 'control commands'\n", " -vv will additionally display each command's description\n", " -vvv will also add the input flags for each command\n", " -vvvv will also show internal input flags\n", " -c - for each engine, also list the capabilities\n", " -t[t] - for each engine, check that they are really available\n", " -tt will display error trace for unavailable engines\n", " -pre - runs command 'cmd' against the ENGINE before any attempts\n", " to load it (if -t is used)\n", " -post - runs command 'cmd' against the ENGINE after loading it\n", " (only used if -t is also provided)\n", " NB: -pre and -post will be applied to all ENGINEs supplied on the command\n", " line, or all supported ENGINEs if none are specified.\n", " Eg. '-pre \"SO_PATH:/lib/libdriver.so\"' calls command \"SO_PATH\" with\n", " argument \"/lib/libdriver.so\".\n", NULL }; static void identity(char *ptr) { return; } static int append_buf(char **buf, const char *s, int *size, int step) { if (*buf == NULL) { *size = step; *buf = OPENSSL_malloc(*size); if (*buf == NULL) return 0; **buf = '\0'; } if (strlen(*buf) + strlen(s) >= (unsigned int)*size) { + char *p = *buf; + *size += step; *buf = OPENSSL_realloc(*buf, *size); + if (*buf == NULL) { + OPENSSL_free(p); + return 0; + } } - - if (*buf == NULL) - return 0; if (**buf != '\0') BUF_strlcat(*buf, ", ", *size); BUF_strlcat(*buf, s, *size); return 1; } static int util_flags(BIO *bio_out, unsigned int flags, const char *indent) { int started = 0, err = 0; /* Indent before displaying input flags */ BIO_printf(bio_out, "%s%s(input flags): ", indent, indent); if (flags == 0) { BIO_printf(bio_out, "\n"); return 1; } /* * If the object is internal, mark it in a way that shows instead of * having it part of all the other flags, even if it really is. */ if (flags & ENGINE_CMD_FLAG_INTERNAL) { BIO_printf(bio_out, "[Internal] "); } if (flags & ENGINE_CMD_FLAG_NUMERIC) { BIO_printf(bio_out, "NUMERIC"); started = 1; } /* * Now we check that no combinations of the mutually exclusive NUMERIC, * STRING, and NO_INPUT flags have been used. Future flags that can be * OR'd together with these would need to added after these to preserve * the testing logic. */ if (flags & ENGINE_CMD_FLAG_STRING) { if (started) { BIO_printf(bio_out, "|"); err = 1; } BIO_printf(bio_out, "STRING"); started = 1; } if (flags & ENGINE_CMD_FLAG_NO_INPUT) { if (started) { BIO_printf(bio_out, "|"); err = 1; } BIO_printf(bio_out, "NO_INPUT"); started = 1; } /* Check for unknown flags */ flags = flags & ~ENGINE_CMD_FLAG_NUMERIC & ~ENGINE_CMD_FLAG_STRING & ~ENGINE_CMD_FLAG_NO_INPUT & ~ENGINE_CMD_FLAG_INTERNAL; if (flags) { if (started) BIO_printf(bio_out, "|"); BIO_printf(bio_out, "<0x%04X>", flags); } if (err) BIO_printf(bio_out, " "); BIO_printf(bio_out, "\n"); return 1; } static int util_verbose(ENGINE *e, int verbose, BIO *bio_out, const char *indent) { static const int line_wrap = 78; int num; int ret = 0; char *name = NULL; char *desc = NULL; int flags; int xpos = 0; STACK_OF(OPENSSL_STRING) *cmds = NULL; if (!ENGINE_ctrl(e, ENGINE_CTRL_HAS_CTRL_FUNCTION, 0, NULL, NULL) || ((num = ENGINE_ctrl(e, ENGINE_CTRL_GET_FIRST_CMD_TYPE, 0, NULL, NULL)) <= 0)) { # if 0 BIO_printf(bio_out, "%s\n", indent); # endif return 1; } cmds = sk_OPENSSL_STRING_new_null(); if (!cmds) goto err; do { int len; /* Get the command input flags */ if ((flags = ENGINE_ctrl(e, ENGINE_CTRL_GET_CMD_FLAGS, num, NULL, NULL)) < 0) goto err; if (!(flags & ENGINE_CMD_FLAG_INTERNAL) || verbose >= 4) { /* Get the command name */ if ((len = ENGINE_ctrl(e, ENGINE_CTRL_GET_NAME_LEN_FROM_CMD, num, NULL, NULL)) <= 0) goto err; if ((name = OPENSSL_malloc(len + 1)) == NULL) goto err; if (ENGINE_ctrl(e, ENGINE_CTRL_GET_NAME_FROM_CMD, num, name, NULL) <= 0) goto err; /* Get the command description */ if ((len = ENGINE_ctrl(e, ENGINE_CTRL_GET_DESC_LEN_FROM_CMD, num, NULL, NULL)) < 0) goto err; if (len > 0) { if ((desc = OPENSSL_malloc(len + 1)) == NULL) goto err; if (ENGINE_ctrl(e, ENGINE_CTRL_GET_DESC_FROM_CMD, num, desc, NULL) <= 0) goto err; } /* Now decide on the output */ if (xpos == 0) /* Do an indent */ xpos = BIO_puts(bio_out, indent); else /* Otherwise prepend a ", " */ xpos += BIO_printf(bio_out, ", "); if (verbose == 1) { /* * We're just listing names, comma-delimited */ if ((xpos > (int)strlen(indent)) && (xpos + (int)strlen(name) > line_wrap)) { BIO_printf(bio_out, "\n"); xpos = BIO_puts(bio_out, indent); } xpos += BIO_printf(bio_out, "%s", name); } else { /* We're listing names plus descriptions */ BIO_printf(bio_out, "%s: %s\n", name, (desc == NULL) ? "" : desc); /* ... and sometimes input flags */ if ((verbose >= 3) && !util_flags(bio_out, flags, indent)) goto err; xpos = 0; } } OPENSSL_free(name); name = NULL; if (desc) { OPENSSL_free(desc); desc = NULL; } /* Move to the next command */ num = ENGINE_ctrl(e, ENGINE_CTRL_GET_NEXT_CMD_TYPE, num, NULL, NULL); } while (num > 0); if (xpos > 0) BIO_printf(bio_out, "\n"); ret = 1; err: if (cmds) sk_OPENSSL_STRING_pop_free(cmds, identity); if (name) OPENSSL_free(name); if (desc) OPENSSL_free(desc); return ret; } static void util_do_cmds(ENGINE *e, STACK_OF(OPENSSL_STRING) *cmds, BIO *bio_out, const char *indent) { int loop, res, num = sk_OPENSSL_STRING_num(cmds); if (num < 0) { BIO_printf(bio_out, "[Error]: internal stack error\n"); return; } for (loop = 0; loop < num; loop++) { char buf[256]; const char *cmd, *arg; cmd = sk_OPENSSL_STRING_value(cmds, loop); res = 1; /* assume success */ /* Check if this command has no ":arg" */ if ((arg = strstr(cmd, ":")) == NULL) { if (!ENGINE_ctrl_cmd_string(e, cmd, NULL, 0)) res = 0; } else { if ((int)(arg - cmd) > 254) { BIO_printf(bio_out, "[Error]: command name too long\n"); return; } memcpy(buf, cmd, (int)(arg - cmd)); buf[arg - cmd] = '\0'; arg++; /* Move past the ":" */ /* Call the command with the argument */ if (!ENGINE_ctrl_cmd_string(e, buf, arg, 0)) res = 0; } if (res) BIO_printf(bio_out, "[Success]: %s\n", cmd); else { BIO_printf(bio_out, "[Failure]: %s\n", cmd); ERR_print_errors(bio_out); } } } int MAIN(int, char **); int MAIN(int argc, char **argv) { int ret = 1, i; const char **pp; int verbose = 0, list_cap = 0, test_avail = 0, test_avail_noise = 0; ENGINE *e; STACK_OF(OPENSSL_STRING) *engines = sk_OPENSSL_STRING_new_null(); STACK_OF(OPENSSL_STRING) *pre_cmds = sk_OPENSSL_STRING_new_null(); STACK_OF(OPENSSL_STRING) *post_cmds = sk_OPENSSL_STRING_new_null(); int badops = 1; BIO *bio_out = NULL; const char *indent = " "; apps_startup(); SSL_load_error_strings(); if (bio_err == NULL) bio_err = BIO_new_fp(stderr, BIO_NOCLOSE); if (!load_config(bio_err, NULL)) goto end; bio_out = BIO_new_fp(stdout, BIO_NOCLOSE); # ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); bio_out = BIO_push(tmpbio, bio_out); } # endif argc--; argv++; while (argc >= 1) { if (strncmp(*argv, "-v", 2) == 0) { if (strspn(*argv + 1, "v") < strlen(*argv + 1)) goto skip_arg_loop; if ((verbose = strlen(*argv + 1)) > 4) goto skip_arg_loop; } else if (strcmp(*argv, "-c") == 0) list_cap = 1; else if (strncmp(*argv, "-t", 2) == 0) { test_avail = 1; if (strspn(*argv + 1, "t") < strlen(*argv + 1)) goto skip_arg_loop; if ((test_avail_noise = strlen(*argv + 1) - 1) > 1) goto skip_arg_loop; } else if (strcmp(*argv, "-pre") == 0) { argc--; argv++; if (argc == 0) goto skip_arg_loop; sk_OPENSSL_STRING_push(pre_cmds, *argv); } else if (strcmp(*argv, "-post") == 0) { argc--; argv++; if (argc == 0) goto skip_arg_loop; sk_OPENSSL_STRING_push(post_cmds, *argv); } else if ((strncmp(*argv, "-h", 2) == 0) || (strcmp(*argv, "-?") == 0)) goto skip_arg_loop; else sk_OPENSSL_STRING_push(engines, *argv); argc--; argv++; } /* Looks like everything went OK */ badops = 0; skip_arg_loop: if (badops) { for (pp = engine_usage; (*pp != NULL); pp++) BIO_printf(bio_err, "%s", *pp); goto end; } if (sk_OPENSSL_STRING_num(engines) == 0) { for (e = ENGINE_get_first(); e != NULL; e = ENGINE_get_next(e)) { sk_OPENSSL_STRING_push(engines, (char *)ENGINE_get_id(e)); } } for (i = 0; i < sk_OPENSSL_STRING_num(engines); i++) { const char *id = sk_OPENSSL_STRING_value(engines, i); if ((e = ENGINE_by_id(id)) != NULL) { const char *name = ENGINE_get_name(e); /* * Do "id" first, then "name". Easier to auto-parse. */ BIO_printf(bio_out, "(%s) %s\n", id, name); util_do_cmds(e, pre_cmds, bio_out, indent); if (strcmp(ENGINE_get_id(e), id) != 0) { BIO_printf(bio_out, "Loaded: (%s) %s\n", ENGINE_get_id(e), ENGINE_get_name(e)); } if (list_cap) { int cap_size = 256; char *cap_buf = NULL; int k, n; const int *nids; ENGINE_CIPHERS_PTR fn_c; ENGINE_DIGESTS_PTR fn_d; ENGINE_PKEY_METHS_PTR fn_pk; if (ENGINE_get_RSA(e) != NULL && !append_buf(&cap_buf, "RSA", &cap_size, 256)) goto end; if (ENGINE_get_DSA(e) != NULL && !append_buf(&cap_buf, "DSA", &cap_size, 256)) goto end; if (ENGINE_get_DH(e) != NULL && !append_buf(&cap_buf, "DH", &cap_size, 256)) goto end; if (ENGINE_get_RAND(e) != NULL && !append_buf(&cap_buf, "RAND", &cap_size, 256)) goto end; fn_c = ENGINE_get_ciphers(e); if (!fn_c) goto skip_ciphers; n = fn_c(e, NULL, &nids, 0); for (k = 0; k < n; ++k) if (!append_buf(&cap_buf, OBJ_nid2sn(nids[k]), &cap_size, 256)) goto end; skip_ciphers: fn_d = ENGINE_get_digests(e); if (!fn_d) goto skip_digests; n = fn_d(e, NULL, &nids, 0); for (k = 0; k < n; ++k) if (!append_buf(&cap_buf, OBJ_nid2sn(nids[k]), &cap_size, 256)) goto end; skip_digests: fn_pk = ENGINE_get_pkey_meths(e); if (!fn_pk) goto skip_pmeths; n = fn_pk(e, NULL, &nids, 0); for (k = 0; k < n; ++k) if (!append_buf(&cap_buf, OBJ_nid2sn(nids[k]), &cap_size, 256)) goto end; skip_pmeths: if (cap_buf && (*cap_buf != '\0')) BIO_printf(bio_out, " [%s]\n", cap_buf); OPENSSL_free(cap_buf); } if (test_avail) { BIO_printf(bio_out, "%s", indent); if (ENGINE_init(e)) { BIO_printf(bio_out, "[ available ]\n"); util_do_cmds(e, post_cmds, bio_out, indent); ENGINE_finish(e); } else { BIO_printf(bio_out, "[ unavailable ]\n"); if (test_avail_noise) ERR_print_errors_fp(stdout); ERR_clear_error(); } } if ((verbose > 0) && !util_verbose(e, verbose, bio_out, indent)) goto end; ENGINE_free(e); } else ERR_print_errors(bio_err); } ret = 0; end: ERR_print_errors(bio_err); sk_OPENSSL_STRING_pop_free(engines, identity); sk_OPENSSL_STRING_pop_free(pre_cmds, identity); sk_OPENSSL_STRING_pop_free(post_cmds, identity); if (bio_out != NULL) BIO_free_all(bio_out); apps_shutdown(); OPENSSL_EXIT(ret); } #else # if PEDANTIC static void *dummy = &dummy; # endif #endif Index: vendor-crypto/openssl/dist/apps/pkeyutl.c =================================================================== --- vendor-crypto/openssl/dist/apps/pkeyutl.c (revision 318896) +++ vendor-crypto/openssl/dist/apps/pkeyutl.c (revision 318897) @@ -1,556 +1,558 @@ /* * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project * 2006. */ /* ==================================================================== * Copyright (c) 2006 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * licensing@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include "apps.h" #include #include #include #include #define KEY_PRIVKEY 1 #define KEY_PUBKEY 2 #define KEY_CERT 3 static void usage(void); #undef PROG #define PROG pkeyutl_main static EVP_PKEY_CTX *init_ctx(int *pkeysize, const char *keyfile, int keyform, int key_type, char *passargin, int pkey_op, ENGINE *e, int impl); static int setup_peer(BIO *err, EVP_PKEY_CTX *ctx, int peerform, const char *file, ENGINE* e); static int do_keyop(EVP_PKEY_CTX *ctx, int pkey_op, unsigned char *out, size_t *poutlen, unsigned char *in, size_t inlen); int MAIN(int argc, char **); int MAIN(int argc, char **argv) { BIO *in = NULL, *out = NULL; char *infile = NULL, *outfile = NULL, *sigfile = NULL; ENGINE *e = NULL; int pkey_op = EVP_PKEY_OP_SIGN, key_type = KEY_PRIVKEY; int keyform = FORMAT_PEM, peerform = FORMAT_PEM; char badarg = 0, rev = 0; char hexdump = 0, asn1parse = 0; EVP_PKEY_CTX *ctx = NULL; char *passargin = NULL; int keysize = -1; int engine_impl = 0; unsigned char *buf_in = NULL, *buf_out = NULL, *sig = NULL; size_t buf_outlen = 0; int buf_inlen = 0, siglen = -1; const char *inkey = NULL; const char *peerkey = NULL; STACK_OF(OPENSSL_STRING) *pkeyopts = NULL; int ret = 1, rv = -1; argc--; argv++; if (!bio_err) bio_err = BIO_new_fp(stderr, BIO_NOCLOSE); if (!load_config(bio_err, NULL)) goto end; ERR_load_crypto_strings(); OpenSSL_add_all_algorithms(); while (argc >= 1) { if (!strcmp(*argv, "-in")) { if (--argc < 1) badarg = 1; else infile = *(++argv); } else if (!strcmp(*argv, "-out")) { if (--argc < 1) badarg = 1; else outfile = *(++argv); } else if (!strcmp(*argv, "-sigfile")) { if (--argc < 1) badarg = 1; else sigfile = *(++argv); } else if (!strcmp(*argv, "-inkey")) { if (--argc < 1) badarg = 1; else inkey = *++argv; } else if (!strcmp(*argv, "-peerkey")) { if (--argc < 1) badarg = 1; else peerkey = *++argv; } else if (!strcmp(*argv, "-passin")) { if (--argc < 1) badarg = 1; else passargin = *(++argv); } else if (strcmp(*argv, "-peerform") == 0) { if (--argc < 1) badarg = 1; else peerform = str2fmt(*(++argv)); } else if (strcmp(*argv, "-keyform") == 0) { if (--argc < 1) badarg = 1; else keyform = str2fmt(*(++argv)); } #ifndef OPENSSL_NO_ENGINE else if (!strcmp(*argv, "-engine")) { if (--argc < 1) badarg = 1; else e = setup_engine(bio_err, *(++argv), 0); } else if (!strcmp(*argv, "-engine_impl")) { engine_impl = 1; } #endif else if (!strcmp(*argv, "-pubin")) key_type = KEY_PUBKEY; else if (!strcmp(*argv, "-certin")) key_type = KEY_CERT; else if (!strcmp(*argv, "-asn1parse")) asn1parse = 1; else if (!strcmp(*argv, "-hexdump")) hexdump = 1; else if (!strcmp(*argv, "-sign")) pkey_op = EVP_PKEY_OP_SIGN; else if (!strcmp(*argv, "-verify")) pkey_op = EVP_PKEY_OP_VERIFY; else if (!strcmp(*argv, "-verifyrecover")) pkey_op = EVP_PKEY_OP_VERIFYRECOVER; else if (!strcmp(*argv, "-encrypt")) pkey_op = EVP_PKEY_OP_ENCRYPT; else if (!strcmp(*argv, "-decrypt")) pkey_op = EVP_PKEY_OP_DECRYPT; else if (!strcmp(*argv, "-derive")) pkey_op = EVP_PKEY_OP_DERIVE; else if (!strcmp(*argv, "-rev")) rev = 1; else if (strcmp(*argv, "-pkeyopt") == 0) { if (--argc < 1) badarg = 1; else if ((pkeyopts == NULL && (pkeyopts = sk_OPENSSL_STRING_new_null()) == NULL) || sk_OPENSSL_STRING_push(pkeyopts, *++argv) == 0) { BIO_puts(bio_err, "out of memory\n"); goto end; } } else badarg = 1; if (badarg) { usage(); goto end; } argc--; argv++; } if (inkey == NULL || (peerkey != NULL && pkey_op != EVP_PKEY_OP_DERIVE)) { usage(); goto end; } ctx = init_ctx(&keysize, inkey, keyform, key_type, passargin, pkey_op, e, engine_impl); if (!ctx) { BIO_puts(bio_err, "Error initializing context\n"); ERR_print_errors(bio_err); goto end; } if (peerkey != NULL && !setup_peer(bio_err, ctx, peerform, peerkey, e)) { BIO_puts(bio_err, "Error setting up peer key\n"); ERR_print_errors(bio_err); goto end; } if (pkeyopts != NULL) { int num = sk_OPENSSL_STRING_num(pkeyopts); int i; for (i = 0; i < num; ++i) { const char *opt = sk_OPENSSL_STRING_value(pkeyopts, i); if (pkey_ctrl_string(ctx, opt) <= 0) { BIO_puts(bio_err, "parameter setting error\n"); ERR_print_errors(bio_err); goto end; } } } if (sigfile && (pkey_op != EVP_PKEY_OP_VERIFY)) { BIO_puts(bio_err, "Signature file specified for non verify\n"); goto end; } if (!sigfile && (pkey_op == EVP_PKEY_OP_VERIFY)) { BIO_puts(bio_err, "No signature file specified for verify\n"); goto end; } /* FIXME: seed PRNG only if needed */ app_RAND_load_file(NULL, bio_err, 0); if (pkey_op != EVP_PKEY_OP_DERIVE) { if (infile) { if (!(in = BIO_new_file(infile, "rb"))) { BIO_puts(bio_err, "Error Opening Input File\n"); ERR_print_errors(bio_err); goto end; } } else in = BIO_new_fp(stdin, BIO_NOCLOSE); } if (outfile) { if (!(out = BIO_new_file(outfile, "wb"))) { BIO_printf(bio_err, "Error Creating Output File\n"); ERR_print_errors(bio_err); goto end; } } else { out = BIO_new_fp(stdout, BIO_NOCLOSE); #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); out = BIO_push(tmpbio, out); } #endif } if (sigfile) { BIO *sigbio = BIO_new_file(sigfile, "rb"); if (!sigbio) { BIO_printf(bio_err, "Can't open signature file %s\n", sigfile); goto end; } siglen = bio_to_mem(&sig, keysize * 10, sigbio); BIO_free(sigbio); if (siglen < 0) { BIO_printf(bio_err, "Error reading signature data\n"); goto end; } } if (in) { /* Read the input data */ buf_inlen = bio_to_mem(&buf_in, keysize * 10, in); if (buf_inlen < 0) { BIO_printf(bio_err, "Error reading input Data\n"); exit(1); } if (rev) { size_t i; unsigned char ctmp; size_t l = (size_t)buf_inlen; for (i = 0; i < l / 2; i++) { ctmp = buf_in[i]; buf_in[i] = buf_in[l - 1 - i]; buf_in[l - 1 - i] = ctmp; } } } if (pkey_op == EVP_PKEY_OP_VERIFY) { rv = EVP_PKEY_verify(ctx, sig, (size_t)siglen, buf_in, (size_t)buf_inlen); if (rv == 0) BIO_puts(out, "Signature Verification Failure\n"); - else if (rv == 1) + else if (rv == 1) { BIO_puts(out, "Signature Verified Successfully\n"); + ret = 0; + } if (rv >= 0) goto end; } else { rv = do_keyop(ctx, pkey_op, NULL, (size_t *)&buf_outlen, buf_in, (size_t)buf_inlen); if (rv > 0 && buf_outlen != 0) { buf_out = OPENSSL_malloc(buf_outlen); if (!buf_out) rv = -1; else rv = do_keyop(ctx, pkey_op, buf_out, (size_t *)&buf_outlen, buf_in, (size_t)buf_inlen); } } if (rv <= 0) { BIO_printf(bio_err, "Public Key operation error\n"); ERR_print_errors(bio_err); goto end; } ret = 0; if (asn1parse) { if (!ASN1_parse_dump(out, buf_out, buf_outlen, 1, -1)) ERR_print_errors(bio_err); } else if (hexdump) BIO_dump(out, (char *)buf_out, buf_outlen); else BIO_write(out, buf_out, buf_outlen); end: if (ctx) EVP_PKEY_CTX_free(ctx); release_engine(e); BIO_free(in); BIO_free_all(out); if (buf_in != NULL) OPENSSL_free(buf_in); if (buf_out != NULL) OPENSSL_free(buf_out); if (sig != NULL) OPENSSL_free(sig); if (pkeyopts != NULL) sk_OPENSSL_STRING_free(pkeyopts); return ret; } static void usage() { BIO_printf(bio_err, "Usage: pkeyutl [options]\n"); BIO_printf(bio_err, "-in file input file\n"); BIO_printf(bio_err, "-out file output file\n"); BIO_printf(bio_err, "-sigfile file signature file (verify operation only)\n"); BIO_printf(bio_err, "-inkey file input key\n"); BIO_printf(bio_err, "-keyform arg private key format - default PEM\n"); BIO_printf(bio_err, "-pubin input is a public key\n"); BIO_printf(bio_err, "-certin input is a certificate carrying a public key\n"); BIO_printf(bio_err, "-pkeyopt X:Y public key options\n"); BIO_printf(bio_err, "-sign sign with private key\n"); BIO_printf(bio_err, "-verify verify with public key\n"); BIO_printf(bio_err, "-verifyrecover verify with public key, recover original data\n"); BIO_printf(bio_err, "-encrypt encrypt with public key\n"); BIO_printf(bio_err, "-decrypt decrypt with private key\n"); BIO_printf(bio_err, "-derive derive shared secret\n"); BIO_printf(bio_err, "-hexdump hex dump output\n"); #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err, "-engine e use engine e, maybe a hardware device, for loading keys.\n"); BIO_printf(bio_err, "-engine_impl also use engine given by -engine for crypto operations\n"); #endif BIO_printf(bio_err, "-passin arg pass phrase source\n"); } static EVP_PKEY_CTX *init_ctx(int *pkeysize, const char *keyfile, int keyform, int key_type, char *passargin, int pkey_op, ENGINE *e, int engine_impl) { EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; ENGINE *impl = NULL; char *passin = NULL; int rv = -1; X509 *x; if (((pkey_op == EVP_PKEY_OP_SIGN) || (pkey_op == EVP_PKEY_OP_DECRYPT) || (pkey_op == EVP_PKEY_OP_DERIVE)) && (key_type != KEY_PRIVKEY)) { BIO_printf(bio_err, "A private key is needed for this operation\n"); goto end; } if (!app_passwd(bio_err, passargin, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } switch (key_type) { case KEY_PRIVKEY: pkey = load_key(bio_err, keyfile, keyform, 0, passin, e, "Private Key"); break; case KEY_PUBKEY: pkey = load_pubkey(bio_err, keyfile, keyform, 0, NULL, e, "Public Key"); break; case KEY_CERT: x = load_cert(bio_err, keyfile, keyform, NULL, e, "Certificate"); if (x) { pkey = X509_get_pubkey(x); X509_free(x); } break; } *pkeysize = EVP_PKEY_size(pkey); if (!pkey) goto end; #ifndef OPENSSL_NO_ENGINE if (engine_impl) impl = e; #endif ctx = EVP_PKEY_CTX_new(pkey, impl); EVP_PKEY_free(pkey); if (!ctx) goto end; switch (pkey_op) { case EVP_PKEY_OP_SIGN: rv = EVP_PKEY_sign_init(ctx); break; case EVP_PKEY_OP_VERIFY: rv = EVP_PKEY_verify_init(ctx); break; case EVP_PKEY_OP_VERIFYRECOVER: rv = EVP_PKEY_verify_recover_init(ctx); break; case EVP_PKEY_OP_ENCRYPT: rv = EVP_PKEY_encrypt_init(ctx); break; case EVP_PKEY_OP_DECRYPT: rv = EVP_PKEY_decrypt_init(ctx); break; case EVP_PKEY_OP_DERIVE: rv = EVP_PKEY_derive_init(ctx); break; } if (rv <= 0) { EVP_PKEY_CTX_free(ctx); ctx = NULL; } end: if (passin) OPENSSL_free(passin); return ctx; } static int setup_peer(BIO *err, EVP_PKEY_CTX *ctx, int peerform, const char *file, ENGINE* e) { EVP_PKEY *peer = NULL; ENGINE* engine = NULL; int ret; if (peerform == FORMAT_ENGINE) engine = e; peer = load_pubkey(bio_err, file, peerform, 0, NULL, engine, "Peer Key"); if (!peer) { BIO_printf(bio_err, "Error reading peer key %s\n", file); ERR_print_errors(err); return 0; } ret = EVP_PKEY_derive_set_peer(ctx, peer); EVP_PKEY_free(peer); if (ret <= 0) ERR_print_errors(err); return ret; } static int do_keyop(EVP_PKEY_CTX *ctx, int pkey_op, unsigned char *out, size_t *poutlen, unsigned char *in, size_t inlen) { int rv = 0; switch (pkey_op) { case EVP_PKEY_OP_VERIFYRECOVER: rv = EVP_PKEY_verify_recover(ctx, out, poutlen, in, inlen); break; case EVP_PKEY_OP_SIGN: rv = EVP_PKEY_sign(ctx, out, poutlen, in, inlen); break; case EVP_PKEY_OP_ENCRYPT: rv = EVP_PKEY_encrypt(ctx, out, poutlen, in, inlen); break; case EVP_PKEY_OP_DECRYPT: rv = EVP_PKEY_decrypt(ctx, out, poutlen, in, inlen); break; case EVP_PKEY_OP_DERIVE: rv = EVP_PKEY_derive(ctx, out, poutlen); break; } return rv; } Index: vendor-crypto/openssl/dist/apps/prime.c =================================================================== --- vendor-crypto/openssl/dist/apps/prime.c (revision 318896) +++ vendor-crypto/openssl/dist/apps/prime.c (revision 318897) @@ -1,159 +1,162 @@ /* ==================================================================== * Copyright (c) 2004 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include #include "apps.h" #include #undef PROG #define PROG prime_main int MAIN(int, char **); int MAIN(int argc, char **argv) { int hex = 0; int checks = 20; int generate = 0; int bits = 0; int safe = 0; BIGNUM *bn = NULL; BIO *bio_out; apps_startup(); if (bio_err == NULL) if ((bio_err = BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT); --argc; ++argv; while (argc >= 1 && **argv == '-') { if (!strcmp(*argv, "-hex")) hex = 1; else if (!strcmp(*argv, "-generate")) generate = 1; else if (!strcmp(*argv, "-bits")) if (--argc < 1) goto bad; else bits = atoi(*++argv); else if (!strcmp(*argv, "-safe")) safe = 1; else if (!strcmp(*argv, "-checks")) if (--argc < 1) goto bad; else checks = atoi(*++argv); else { BIO_printf(bio_err, "Unknown option '%s'\n", *argv); goto bad; } --argc; ++argv; } if (argv[0] == NULL && !generate) { BIO_printf(bio_err, "No prime specified\n"); goto bad; } if ((bio_out = BIO_new(BIO_s_file())) != NULL) { BIO_set_fp(bio_out, stdout, BIO_NOCLOSE); #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); bio_out = BIO_push(tmpbio, bio_out); } #endif } if (generate) { char *s; if (!bits) { BIO_printf(bio_err, "Specifiy the number of bits.\n"); return 1; } bn = BN_new(); BN_generate_prime_ex(bn, bits, safe, NULL, NULL, NULL); s = hex ? BN_bn2hex(bn) : BN_bn2dec(bn); BIO_printf(bio_out, "%s\n", s); OPENSSL_free(s); } else { int r; if (hex) r = BN_hex2bn(&bn, argv[0]); else r = BN_dec2bn(&bn, argv[0]); if(!r) { BIO_printf(bio_err, "Failed to process value (%s)\n", argv[0]); goto end; } BN_print(bio_out, bn); BIO_printf(bio_out, " is %sprime\n", BN_is_prime_ex(bn, checks, NULL, NULL) ? "" : "not "); } end: BN_free(bn); BIO_free_all(bio_out); return 0; bad: BIO_printf(bio_err, "options are\n"); BIO_printf(bio_err, "%-14s hex\n", "-hex"); BIO_printf(bio_err, "%-14s number of checks\n", "-checks "); + BIO_printf(bio_err, "%-14s generate prime\n", "-generate"); + BIO_printf(bio_err, "%-14s number of bits\n", "-bits "); + BIO_printf(bio_err, "%-14s safe prime\n", "-safe"); return 1; } Index: vendor-crypto/openssl/dist/apps/progs.h =================================================================== --- vendor-crypto/openssl/dist/apps/progs.h (revision 318896) +++ vendor-crypto/openssl/dist/apps/progs.h (revision 318897) @@ -1,366 +1,366 @@ /* apps/progs.h */ /* automatically generated by progs.pl for openssl.c */ extern int verify_main(int argc, char *argv[]); extern int asn1parse_main(int argc, char *argv[]); extern int req_main(int argc, char *argv[]); extern int dgst_main(int argc, char *argv[]); extern int dh_main(int argc, char *argv[]); extern int dhparam_main(int argc, char *argv[]); extern int enc_main(int argc, char *argv[]); extern int passwd_main(int argc, char *argv[]); extern int gendh_main(int argc, char *argv[]); extern int errstr_main(int argc, char *argv[]); extern int ca_main(int argc, char *argv[]); extern int crl_main(int argc, char *argv[]); extern int rsa_main(int argc, char *argv[]); extern int rsautl_main(int argc, char *argv[]); extern int dsa_main(int argc, char *argv[]); extern int dsaparam_main(int argc, char *argv[]); extern int ec_main(int argc, char *argv[]); extern int ecparam_main(int argc, char *argv[]); extern int x509_main(int argc, char *argv[]); extern int genrsa_main(int argc, char *argv[]); extern int gendsa_main(int argc, char *argv[]); extern int genpkey_main(int argc, char *argv[]); extern int s_server_main(int argc, char *argv[]); extern int s_client_main(int argc, char *argv[]); extern int speed_main(int argc, char *argv[]); extern int s_time_main(int argc, char *argv[]); extern int version_main(int argc, char *argv[]); extern int pkcs7_main(int argc, char *argv[]); extern int cms_main(int argc, char *argv[]); extern int crl2pkcs7_main(int argc, char *argv[]); extern int sess_id_main(int argc, char *argv[]); extern int ciphers_main(int argc, char *argv[]); extern int nseq_main(int argc, char *argv[]); extern int pkcs12_main(int argc, char *argv[]); extern int pkcs8_main(int argc, char *argv[]); extern int pkey_main(int argc, char *argv[]); extern int pkeyparam_main(int argc, char *argv[]); extern int pkeyutl_main(int argc, char *argv[]); extern int spkac_main(int argc, char *argv[]); extern int smime_main(int argc, char *argv[]); extern int rand_main(int argc, char *argv[]); extern int engine_main(int argc, char *argv[]); extern int ocsp_main(int argc, char *argv[]); extern int prime_main(int argc, char *argv[]); extern int ts_main(int argc, char *argv[]); extern int srp_main(int argc, char *argv[]); #define FUNC_TYPE_GENERAL 1 #define FUNC_TYPE_MD 2 #define FUNC_TYPE_CIPHER 3 #define FUNC_TYPE_PKEY 4 #define FUNC_TYPE_MD_ALG 5 #define FUNC_TYPE_CIPHER_ALG 6 typedef struct { int type; const char *name; - int (*func) (int argc, char *argv[]); + int (*func)(int argc, char *argv[]); } FUNCTION; DECLARE_LHASH_OF(FUNCTION); FUNCTION functions[] = { {FUNC_TYPE_GENERAL, "verify", verify_main}, {FUNC_TYPE_GENERAL, "asn1parse", asn1parse_main}, {FUNC_TYPE_GENERAL, "req", req_main}, {FUNC_TYPE_GENERAL, "dgst", dgst_main}, #ifndef OPENSSL_NO_DH {FUNC_TYPE_GENERAL, "dh", dh_main}, #endif #ifndef OPENSSL_NO_DH {FUNC_TYPE_GENERAL, "dhparam", dhparam_main}, #endif {FUNC_TYPE_GENERAL, "enc", enc_main}, {FUNC_TYPE_GENERAL, "passwd", passwd_main}, #ifndef OPENSSL_NO_DH {FUNC_TYPE_GENERAL, "gendh", gendh_main}, #endif {FUNC_TYPE_GENERAL, "errstr", errstr_main}, {FUNC_TYPE_GENERAL, "ca", ca_main}, {FUNC_TYPE_GENERAL, "crl", crl_main}, #ifndef OPENSSL_NO_RSA {FUNC_TYPE_GENERAL, "rsa", rsa_main}, #endif #ifndef OPENSSL_NO_RSA {FUNC_TYPE_GENERAL, "rsautl", rsautl_main}, #endif #ifndef OPENSSL_NO_DSA {FUNC_TYPE_GENERAL, "dsa", dsa_main}, #endif #ifndef OPENSSL_NO_DSA {FUNC_TYPE_GENERAL, "dsaparam", dsaparam_main}, #endif #ifndef OPENSSL_NO_EC {FUNC_TYPE_GENERAL, "ec", ec_main}, #endif #ifndef OPENSSL_NO_EC {FUNC_TYPE_GENERAL, "ecparam", ecparam_main}, #endif {FUNC_TYPE_GENERAL, "x509", x509_main}, #ifndef OPENSSL_NO_RSA {FUNC_TYPE_GENERAL, "genrsa", genrsa_main}, #endif #ifndef OPENSSL_NO_DSA {FUNC_TYPE_GENERAL, "gendsa", gendsa_main}, #endif {FUNC_TYPE_GENERAL, "genpkey", genpkey_main}, #if !defined(OPENSSL_NO_SOCK) {FUNC_TYPE_GENERAL, "s_server", s_server_main}, #endif #if !defined(OPENSSL_NO_SOCK) {FUNC_TYPE_GENERAL, "s_client", s_client_main}, #endif #ifndef OPENSSL_NO_SPEED {FUNC_TYPE_GENERAL, "speed", speed_main}, #endif #if !defined(OPENSSL_NO_SOCK) {FUNC_TYPE_GENERAL, "s_time", s_time_main}, #endif {FUNC_TYPE_GENERAL, "version", version_main}, {FUNC_TYPE_GENERAL, "pkcs7", pkcs7_main}, #ifndef OPENSSL_NO_CMS {FUNC_TYPE_GENERAL, "cms", cms_main}, #endif {FUNC_TYPE_GENERAL, "crl2pkcs7", crl2pkcs7_main}, {FUNC_TYPE_GENERAL, "sess_id", sess_id_main}, #if !defined(OPENSSL_NO_SOCK) {FUNC_TYPE_GENERAL, "ciphers", ciphers_main}, #endif {FUNC_TYPE_GENERAL, "nseq", nseq_main}, #if !defined(OPENSSL_NO_DES) && !defined(OPENSSL_NO_SHA1) {FUNC_TYPE_GENERAL, "pkcs12", pkcs12_main}, #endif {FUNC_TYPE_GENERAL, "pkcs8", pkcs8_main}, {FUNC_TYPE_GENERAL, "pkey", pkey_main}, {FUNC_TYPE_GENERAL, "pkeyparam", pkeyparam_main}, {FUNC_TYPE_GENERAL, "pkeyutl", pkeyutl_main}, {FUNC_TYPE_GENERAL, "spkac", spkac_main}, {FUNC_TYPE_GENERAL, "smime", smime_main}, {FUNC_TYPE_GENERAL, "rand", rand_main}, #ifndef OPENSSL_NO_ENGINE {FUNC_TYPE_GENERAL, "engine", engine_main}, #endif #ifndef OPENSSL_NO_OCSP {FUNC_TYPE_GENERAL, "ocsp", ocsp_main}, #endif {FUNC_TYPE_GENERAL, "prime", prime_main}, {FUNC_TYPE_GENERAL, "ts", ts_main}, #ifndef OPENSSL_NO_SRP {FUNC_TYPE_GENERAL, "srp", srp_main}, #endif #ifndef OPENSSL_NO_MD2 {FUNC_TYPE_MD, "md2", dgst_main}, #endif #ifndef OPENSSL_NO_MD4 {FUNC_TYPE_MD, "md4", dgst_main}, #endif #ifndef OPENSSL_NO_MD5 {FUNC_TYPE_MD, "md5", dgst_main}, #endif #ifndef OPENSSL_NO_SHA {FUNC_TYPE_MD, "sha", dgst_main}, #endif #ifndef OPENSSL_NO_SHA1 {FUNC_TYPE_MD, "sha1", dgst_main}, #endif #ifndef OPENSSL_NO_MDC2 {FUNC_TYPE_MD, "mdc2", dgst_main}, #endif #ifndef OPENSSL_NO_RMD160 {FUNC_TYPE_MD, "rmd160", dgst_main}, #endif #ifndef OPENSSL_NO_AES {FUNC_TYPE_CIPHER, "aes-128-cbc", enc_main}, #endif #ifndef OPENSSL_NO_AES {FUNC_TYPE_CIPHER, "aes-128-ecb", enc_main}, #endif #ifndef OPENSSL_NO_AES {FUNC_TYPE_CIPHER, "aes-192-cbc", enc_main}, #endif #ifndef OPENSSL_NO_AES {FUNC_TYPE_CIPHER, "aes-192-ecb", enc_main}, #endif #ifndef OPENSSL_NO_AES {FUNC_TYPE_CIPHER, "aes-256-cbc", enc_main}, #endif #ifndef OPENSSL_NO_AES {FUNC_TYPE_CIPHER, "aes-256-ecb", enc_main}, #endif #ifndef OPENSSL_NO_CAMELLIA {FUNC_TYPE_CIPHER, "camellia-128-cbc", enc_main}, #endif #ifndef OPENSSL_NO_CAMELLIA {FUNC_TYPE_CIPHER, "camellia-128-ecb", enc_main}, #endif #ifndef OPENSSL_NO_CAMELLIA {FUNC_TYPE_CIPHER, "camellia-192-cbc", enc_main}, #endif #ifndef OPENSSL_NO_CAMELLIA {FUNC_TYPE_CIPHER, "camellia-192-ecb", enc_main}, #endif #ifndef OPENSSL_NO_CAMELLIA {FUNC_TYPE_CIPHER, "camellia-256-cbc", enc_main}, #endif #ifndef OPENSSL_NO_CAMELLIA {FUNC_TYPE_CIPHER, "camellia-256-ecb", enc_main}, #endif {FUNC_TYPE_CIPHER, "base64", enc_main}, #ifdef ZLIB {FUNC_TYPE_CIPHER, "zlib", enc_main}, #endif #ifndef OPENSSL_NO_DES {FUNC_TYPE_CIPHER, "des", enc_main}, #endif #ifndef OPENSSL_NO_DES {FUNC_TYPE_CIPHER, "des3", enc_main}, #endif #ifndef OPENSSL_NO_DES {FUNC_TYPE_CIPHER, "desx", enc_main}, #endif #ifndef OPENSSL_NO_IDEA {FUNC_TYPE_CIPHER, "idea", enc_main}, #endif #ifndef OPENSSL_NO_SEED {FUNC_TYPE_CIPHER, "seed", enc_main}, #endif #ifndef OPENSSL_NO_RC4 {FUNC_TYPE_CIPHER, "rc4", enc_main}, #endif #ifndef OPENSSL_NO_RC4 {FUNC_TYPE_CIPHER, "rc4-40", enc_main}, #endif #ifndef OPENSSL_NO_RC2 {FUNC_TYPE_CIPHER, "rc2", enc_main}, #endif #ifndef OPENSSL_NO_BF {FUNC_TYPE_CIPHER, "bf", enc_main}, #endif #ifndef OPENSSL_NO_CAST {FUNC_TYPE_CIPHER, "cast", enc_main}, #endif #ifndef OPENSSL_NO_RC5 {FUNC_TYPE_CIPHER, "rc5", enc_main}, #endif #ifndef OPENSSL_NO_DES {FUNC_TYPE_CIPHER, "des-ecb", enc_main}, #endif #ifndef OPENSSL_NO_DES {FUNC_TYPE_CIPHER, "des-ede", enc_main}, #endif #ifndef OPENSSL_NO_DES {FUNC_TYPE_CIPHER, "des-ede3", enc_main}, #endif #ifndef OPENSSL_NO_DES {FUNC_TYPE_CIPHER, "des-cbc", enc_main}, #endif #ifndef OPENSSL_NO_DES {FUNC_TYPE_CIPHER, "des-ede-cbc", enc_main}, #endif #ifndef OPENSSL_NO_DES {FUNC_TYPE_CIPHER, "des-ede3-cbc", enc_main}, #endif #ifndef OPENSSL_NO_DES {FUNC_TYPE_CIPHER, "des-cfb", enc_main}, #endif #ifndef OPENSSL_NO_DES {FUNC_TYPE_CIPHER, "des-ede-cfb", enc_main}, #endif #ifndef OPENSSL_NO_DES {FUNC_TYPE_CIPHER, "des-ede3-cfb", enc_main}, #endif #ifndef OPENSSL_NO_DES {FUNC_TYPE_CIPHER, "des-ofb", enc_main}, #endif #ifndef OPENSSL_NO_DES {FUNC_TYPE_CIPHER, "des-ede-ofb", enc_main}, #endif #ifndef OPENSSL_NO_DES {FUNC_TYPE_CIPHER, "des-ede3-ofb", enc_main}, #endif #ifndef OPENSSL_NO_IDEA {FUNC_TYPE_CIPHER, "idea-cbc", enc_main}, #endif #ifndef OPENSSL_NO_IDEA {FUNC_TYPE_CIPHER, "idea-ecb", enc_main}, #endif #ifndef OPENSSL_NO_IDEA {FUNC_TYPE_CIPHER, "idea-cfb", enc_main}, #endif #ifndef OPENSSL_NO_IDEA {FUNC_TYPE_CIPHER, "idea-ofb", enc_main}, #endif #ifndef OPENSSL_NO_SEED {FUNC_TYPE_CIPHER, "seed-cbc", enc_main}, #endif #ifndef OPENSSL_NO_SEED {FUNC_TYPE_CIPHER, "seed-ecb", enc_main}, #endif #ifndef OPENSSL_NO_SEED {FUNC_TYPE_CIPHER, "seed-cfb", enc_main}, #endif #ifndef OPENSSL_NO_SEED {FUNC_TYPE_CIPHER, "seed-ofb", enc_main}, #endif #ifndef OPENSSL_NO_RC2 {FUNC_TYPE_CIPHER, "rc2-cbc", enc_main}, #endif #ifndef OPENSSL_NO_RC2 {FUNC_TYPE_CIPHER, "rc2-ecb", enc_main}, #endif #ifndef OPENSSL_NO_RC2 {FUNC_TYPE_CIPHER, "rc2-cfb", enc_main}, #endif #ifndef OPENSSL_NO_RC2 {FUNC_TYPE_CIPHER, "rc2-ofb", enc_main}, #endif #ifndef OPENSSL_NO_RC2 {FUNC_TYPE_CIPHER, "rc2-64-cbc", enc_main}, #endif #ifndef OPENSSL_NO_RC2 {FUNC_TYPE_CIPHER, "rc2-40-cbc", enc_main}, #endif #ifndef OPENSSL_NO_BF {FUNC_TYPE_CIPHER, "bf-cbc", enc_main}, #endif #ifndef OPENSSL_NO_BF {FUNC_TYPE_CIPHER, "bf-ecb", enc_main}, #endif #ifndef OPENSSL_NO_BF {FUNC_TYPE_CIPHER, "bf-cfb", enc_main}, #endif #ifndef OPENSSL_NO_BF {FUNC_TYPE_CIPHER, "bf-ofb", enc_main}, #endif #ifndef OPENSSL_NO_CAST {FUNC_TYPE_CIPHER, "cast5-cbc", enc_main}, #endif #ifndef OPENSSL_NO_CAST {FUNC_TYPE_CIPHER, "cast5-ecb", enc_main}, #endif #ifndef OPENSSL_NO_CAST {FUNC_TYPE_CIPHER, "cast5-cfb", enc_main}, #endif #ifndef OPENSSL_NO_CAST {FUNC_TYPE_CIPHER, "cast5-ofb", enc_main}, #endif #ifndef OPENSSL_NO_CAST {FUNC_TYPE_CIPHER, "cast-cbc", enc_main}, #endif #ifndef OPENSSL_NO_RC5 {FUNC_TYPE_CIPHER, "rc5-cbc", enc_main}, #endif #ifndef OPENSSL_NO_RC5 {FUNC_TYPE_CIPHER, "rc5-ecb", enc_main}, #endif #ifndef OPENSSL_NO_RC5 {FUNC_TYPE_CIPHER, "rc5-cfb", enc_main}, #endif #ifndef OPENSSL_NO_RC5 {FUNC_TYPE_CIPHER, "rc5-ofb", enc_main}, #endif {0, NULL, NULL} }; Index: vendor-crypto/openssl/dist/apps/progs.pl =================================================================== --- vendor-crypto/openssl/dist/apps/progs.pl (revision 318896) +++ vendor-crypto/openssl/dist/apps/progs.pl (revision 318897) @@ -1,104 +1,104 @@ #!/usr/local/bin/perl print "/* apps/progs.h */\n"; print "/* automatically generated by progs.pl for openssl.c */\n\n"; grep(s/^asn1pars$/asn1parse/,@ARGV); foreach (@ARGV) - { printf "extern int %s_main(int argc,char *argv[]);\n",$_; } + { printf "extern int %s_main(int argc, char *argv[]);\n",$_; } print <<'EOF'; -#define FUNC_TYPE_GENERAL 1 -#define FUNC_TYPE_MD 2 -#define FUNC_TYPE_CIPHER 3 -#define FUNC_TYPE_PKEY 4 -#define FUNC_TYPE_MD_ALG 5 -#define FUNC_TYPE_CIPHER_ALG 6 +#define FUNC_TYPE_GENERAL 1 +#define FUNC_TYPE_MD 2 +#define FUNC_TYPE_CIPHER 3 +#define FUNC_TYPE_PKEY 4 +#define FUNC_TYPE_MD_ALG 5 +#define FUNC_TYPE_CIPHER_ALG 6 typedef struct { - int type; - const char *name; - int (*func)(int argc,char *argv[]); - } FUNCTION; + int type; + const char *name; + int (*func)(int argc, char *argv[]); +} FUNCTION; DECLARE_LHASH_OF(FUNCTION); FUNCTION functions[] = { EOF foreach (@ARGV) { push(@files,$_); - $str="\t{FUNC_TYPE_GENERAL,\"$_\",${_}_main},\n"; + $str=" {FUNC_TYPE_GENERAL, \"$_\", ${_}_main},\n"; if (($_ =~ /^s_/) || ($_ =~ /^ciphers$/)) { print "#if !defined(OPENSSL_NO_SOCK)\n${str}#endif\n"; } elsif ( ($_ =~ /^speed$/)) { print "#ifndef OPENSSL_NO_SPEED\n${str}#endif\n"; } elsif ( ($_ =~ /^engine$/)) { print "#ifndef OPENSSL_NO_ENGINE\n${str}#endif\n"; } elsif ( ($_ =~ /^rsa$/) || ($_ =~ /^genrsa$/) || ($_ =~ /^rsautl$/)) { print "#ifndef OPENSSL_NO_RSA\n${str}#endif\n"; } elsif ( ($_ =~ /^dsa$/) || ($_ =~ /^gendsa$/) || ($_ =~ /^dsaparam$/)) { print "#ifndef OPENSSL_NO_DSA\n${str}#endif\n"; } elsif ( ($_ =~ /^ec$/) || ($_ =~ /^ecparam$/)) { print "#ifndef OPENSSL_NO_EC\n${str}#endif\n";} elsif ( ($_ =~ /^dh$/) || ($_ =~ /^gendh$/) || ($_ =~ /^dhparam$/)) { print "#ifndef OPENSSL_NO_DH\n${str}#endif\n"; } elsif ( ($_ =~ /^pkcs12$/)) { print "#if !defined(OPENSSL_NO_DES) && !defined(OPENSSL_NO_SHA1)\n${str}#endif\n"; } elsif ( ($_ =~ /^cms$/)) { print "#ifndef OPENSSL_NO_CMS\n${str}#endif\n"; } elsif ( ($_ =~ /^ocsp$/)) { print "#ifndef OPENSSL_NO_OCSP\n${str}#endif\n"; } elsif ( ($_ =~ /^srp$/)) { print "#ifndef OPENSSL_NO_SRP\n${str}#endif\n"; } else { print $str; } } foreach ("md2","md4","md5","sha","sha1","mdc2","rmd160") { push(@files,$_); - printf "#ifndef OPENSSL_NO_".uc($_)."\n\t{FUNC_TYPE_MD,\"".$_."\",dgst_main},\n#endif\n"; + printf "#ifndef OPENSSL_NO_".uc($_)."\n {FUNC_TYPE_MD, \"".$_."\", dgst_main},\n#endif\n"; } foreach ( "aes-128-cbc", "aes-128-ecb", "aes-192-cbc", "aes-192-ecb", "aes-256-cbc", "aes-256-ecb", "camellia-128-cbc", "camellia-128-ecb", "camellia-192-cbc", "camellia-192-ecb", "camellia-256-cbc", "camellia-256-ecb", "base64", "zlib", "des", "des3", "desx", "idea", "seed", "rc4", "rc4-40", "rc2", "bf", "cast", "rc5", "des-ecb", "des-ede", "des-ede3", "des-cbc", "des-ede-cbc","des-ede3-cbc", "des-cfb", "des-ede-cfb","des-ede3-cfb", "des-ofb", "des-ede-ofb","des-ede3-ofb", "idea-cbc","idea-ecb", "idea-cfb", "idea-ofb", "seed-cbc","seed-ecb", "seed-cfb", "seed-ofb", "rc2-cbc", "rc2-ecb", "rc2-cfb","rc2-ofb", "rc2-64-cbc", "rc2-40-cbc", "bf-cbc", "bf-ecb", "bf-cfb", "bf-ofb", "cast5-cbc","cast5-ecb", "cast5-cfb","cast5-ofb", "cast-cbc", "rc5-cbc", "rc5-ecb", "rc5-cfb", "rc5-ofb") { push(@files,$_); - $t=sprintf("\t{FUNC_TYPE_CIPHER,\"%s\",enc_main},\n",$_); + $t=sprintf(" {FUNC_TYPE_CIPHER, \"%s\", enc_main},\n",$_); if ($_ =~ /des/) { $t="#ifndef OPENSSL_NO_DES\n${t}#endif\n"; } elsif ($_ =~ /aes/) { $t="#ifndef OPENSSL_NO_AES\n${t}#endif\n"; } elsif ($_ =~ /camellia/) { $t="#ifndef OPENSSL_NO_CAMELLIA\n${t}#endif\n"; } elsif ($_ =~ /idea/) { $t="#ifndef OPENSSL_NO_IDEA\n${t}#endif\n"; } elsif ($_ =~ /seed/) { $t="#ifndef OPENSSL_NO_SEED\n${t}#endif\n"; } elsif ($_ =~ /rc4/) { $t="#ifndef OPENSSL_NO_RC4\n${t}#endif\n"; } elsif ($_ =~ /rc2/) { $t="#ifndef OPENSSL_NO_RC2\n${t}#endif\n"; } elsif ($_ =~ /bf/) { $t="#ifndef OPENSSL_NO_BF\n${t}#endif\n"; } elsif ($_ =~ /cast/) { $t="#ifndef OPENSSL_NO_CAST\n${t}#endif\n"; } elsif ($_ =~ /rc5/) { $t="#ifndef OPENSSL_NO_RC5\n${t}#endif\n"; } elsif ($_ =~ /zlib/) { $t="#ifdef ZLIB\n${t}#endif\n"; } print $t; } -print "\t{0,NULL,NULL}\n\t};\n"; +print " {0, NULL, NULL}\n};\n"; Index: vendor-crypto/openssl/dist/apps/req.c =================================================================== --- vendor-crypto/openssl/dist/apps/req.c (revision 318896) +++ vendor-crypto/openssl/dist/apps/req.c (revision 318897) @@ -1,1729 +1,1731 @@ /* apps/req.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ /* * Until the key-gen callbacks are modified to use newer prototypes, we allow * deprecated functions for openssl-internal code */ #ifdef OPENSSL_NO_DEPRECATED # undef OPENSSL_NO_DEPRECATED #endif #include #include #include #include #ifdef OPENSSL_NO_STDIO # define APPS_WIN16 #endif #include "apps.h" #include #include #include #include #include #include #include #include #include #include #ifndef OPENSSL_NO_RSA # include #endif #ifndef OPENSSL_NO_DSA # include #endif #define SECTION "req" #define BITS "default_bits" #define KEYFILE "default_keyfile" #define PROMPT "prompt" #define DISTINGUISHED_NAME "distinguished_name" #define ATTRIBUTES "attributes" #define V3_EXTENSIONS "x509_extensions" #define REQ_EXTENSIONS "req_extensions" #define STRING_MASK "string_mask" #define UTF8_IN "utf8" #define DEFAULT_KEY_LENGTH 2048 #define MIN_KEY_LENGTH 512 #undef PROG #define PROG req_main /*- * -inform arg - input format - default PEM (DER or PEM) * -outform arg - output format - default PEM * -in arg - input file - default stdin * -out arg - output file - default stdout * -verify - check request signature * -noout - don't print stuff out. * -text - print out human readable text. * -nodes - no des encryption * -config file - Load configuration file. * -key file - make a request using key in file (or use it for verification). * -keyform arg - key file format. * -rand file(s) - load the file(s) into the PRNG. * -newkey - make a key and a request. * -modulus - print RSA modulus. * -pubkey - output Public Key. * -x509 - output a self signed X509 structure instead. * -asn1-kludge - output new certificate request in a format that some CA's * require. This format is wrong */ static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *dn, int mutlirdn, int attribs, unsigned long chtype); static int build_subject(X509_REQ *req, char *subj, unsigned long chtype, int multirdn); static int prompt_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk, char *dn_sect, STACK_OF(CONF_VALUE) *attr_sk, char *attr_sect, int attribs, unsigned long chtype); static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk, STACK_OF(CONF_VALUE) *attr, int attribs, unsigned long chtype); static int add_attribute_object(X509_REQ *req, char *text, const char *def, char *value, int nid, int n_min, int n_max, unsigned long chtype); static int add_DN_object(X509_NAME *n, char *text, const char *def, char *value, int nid, int n_min, int n_max, unsigned long chtype, int mval); static int genpkey_cb(EVP_PKEY_CTX *ctx); static int req_check_len(int len, int n_min, int n_max); static int check_end(const char *str, const char *end); static EVP_PKEY_CTX *set_keygen_ctx(BIO *err, const char *gstr, int *pkey_type, long *pkeylen, char **palgnam, ENGINE *keygen_engine); #ifndef MONOLITH static char *default_config_file = NULL; #endif static CONF *req_conf = NULL; static int batch = 0; int MAIN(int, char **); int MAIN(int argc, char **argv) { ENGINE *e = NULL, *gen_eng = NULL; unsigned long nmflag = 0, reqflag = 0; int ex = 1, x509 = 0, days = 30; X509 *x509ss = NULL; X509_REQ *req = NULL; EVP_PKEY_CTX *genctx = NULL; const char *keyalg = NULL; char *keyalgstr = NULL; STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL; EVP_PKEY *pkey = NULL; int i = 0, badops = 0, newreq = 0, verbose = 0, pkey_type = -1; long newkey = -1; BIO *in = NULL, *out = NULL; int informat, outformat, verify = 0, noout = 0, text = 0, keyform = FORMAT_PEM; int nodes = 0, kludge = 0, newhdr = 0, subject = 0, pubkey = 0; char *infile, *outfile, *prog, *keyfile = NULL, *template = NULL, *keyout = NULL; char *engine = NULL; char *extensions = NULL; char *req_exts = NULL; const EVP_CIPHER *cipher = NULL; ASN1_INTEGER *serial = NULL; int modulus = 0; char *inrand = NULL; char *passargin = NULL, *passargout = NULL; char *passin = NULL, *passout = NULL; char *p; char *subj = NULL; int multirdn = 0; const EVP_MD *md_alg = NULL, *digest = NULL; unsigned long chtype = MBSTRING_ASC; #ifndef MONOLITH char *to_free; long errline; #endif req_conf = NULL; #ifndef OPENSSL_NO_DES cipher = EVP_des_ede3_cbc(); #endif apps_startup(); if (bio_err == NULL) if ((bio_err = BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT); infile = NULL; outfile = NULL; informat = FORMAT_PEM; outformat = FORMAT_PEM; prog = argv[0]; argc--; argv++; while (argc >= 1) { if (strcmp(*argv, "-inform") == 0) { if (--argc < 1) goto bad; informat = str2fmt(*(++argv)); } else if (strcmp(*argv, "-outform") == 0) { if (--argc < 1) goto bad; outformat = str2fmt(*(++argv)); } #ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv, "-engine") == 0) { if (--argc < 1) goto bad; engine = *(++argv); } else if (strcmp(*argv, "-keygen_engine") == 0) { if (--argc < 1) goto bad; gen_eng = ENGINE_by_id(*(++argv)); if (gen_eng == NULL) { BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv); goto end; } } #endif else if (strcmp(*argv, "-key") == 0) { if (--argc < 1) goto bad; keyfile = *(++argv); } else if (strcmp(*argv, "-pubkey") == 0) { pubkey = 1; } else if (strcmp(*argv, "-new") == 0) { newreq = 1; } else if (strcmp(*argv, "-config") == 0) { if (--argc < 1) goto bad; template = *(++argv); } else if (strcmp(*argv, "-keyform") == 0) { if (--argc < 1) goto bad; keyform = str2fmt(*(++argv)); } else if (strcmp(*argv, "-in") == 0) { if (--argc < 1) goto bad; infile = *(++argv); } else if (strcmp(*argv, "-out") == 0) { if (--argc < 1) goto bad; outfile = *(++argv); } else if (strcmp(*argv, "-keyout") == 0) { if (--argc < 1) goto bad; keyout = *(++argv); } else if (strcmp(*argv, "-passin") == 0) { if (--argc < 1) goto bad; passargin = *(++argv); } else if (strcmp(*argv, "-passout") == 0) { if (--argc < 1) goto bad; passargout = *(++argv); } else if (strcmp(*argv, "-rand") == 0) { if (--argc < 1) goto bad; inrand = *(++argv); } else if (strcmp(*argv, "-newkey") == 0) { if (--argc < 1) goto bad; keyalg = *(++argv); newreq = 1; } else if (strcmp(*argv, "-pkeyopt") == 0) { if (--argc < 1) goto bad; if (!pkeyopts) pkeyopts = sk_OPENSSL_STRING_new_null(); if (!pkeyopts || !sk_OPENSSL_STRING_push(pkeyopts, *(++argv))) goto bad; } else if (strcmp(*argv, "-sigopt") == 0) { if (--argc < 1) goto bad; if (!sigopts) sigopts = sk_OPENSSL_STRING_new_null(); if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, *(++argv))) goto bad; } else if (strcmp(*argv, "-batch") == 0) batch = 1; else if (strcmp(*argv, "-newhdr") == 0) newhdr = 1; else if (strcmp(*argv, "-modulus") == 0) modulus = 1; else if (strcmp(*argv, "-verify") == 0) verify = 1; else if (strcmp(*argv, "-nodes") == 0) nodes = 1; else if (strcmp(*argv, "-noout") == 0) noout = 1; else if (strcmp(*argv, "-verbose") == 0) verbose = 1; else if (strcmp(*argv, "-utf8") == 0) chtype = MBSTRING_UTF8; else if (strcmp(*argv, "-nameopt") == 0) { if (--argc < 1) goto bad; if (!set_name_ex(&nmflag, *(++argv))) goto bad; } else if (strcmp(*argv, "-reqopt") == 0) { if (--argc < 1) goto bad; if (!set_cert_ex(&reqflag, *(++argv))) goto bad; } else if (strcmp(*argv, "-subject") == 0) subject = 1; else if (strcmp(*argv, "-text") == 0) text = 1; else if (strcmp(*argv, "-x509") == 0) { - newreq = 1; x509 = 1; } else if (strcmp(*argv, "-asn1-kludge") == 0) kludge = 1; else if (strcmp(*argv, "-no-asn1-kludge") == 0) kludge = 0; else if (strcmp(*argv, "-subj") == 0) { if (--argc < 1) goto bad; subj = *(++argv); } else if (strcmp(*argv, "-multivalue-rdn") == 0) multirdn = 1; else if (strcmp(*argv, "-days") == 0) { if (--argc < 1) goto bad; days = atoi(*(++argv)); if (days == 0) days = 30; } else if (strcmp(*argv, "-set_serial") == 0) { if (--argc < 1) goto bad; serial = s2i_ASN1_INTEGER(NULL, *(++argv)); if (!serial) goto bad; } else if (strcmp(*argv, "-extensions") == 0) { if (--argc < 1) goto bad; extensions = *(++argv); } else if (strcmp(*argv, "-reqexts") == 0) { if (--argc < 1) goto bad; req_exts = *(++argv); } else if ((md_alg = EVP_get_digestbyname(&((*argv)[1]))) != NULL) { /* ok */ digest = md_alg; } else { BIO_printf(bio_err, "unknown option %s\n", *argv); badops = 1; break; } argc--; argv++; } if (badops) { bad: BIO_printf(bio_err, "%s [options] outfile\n", prog); BIO_printf(bio_err, "where options are\n"); BIO_printf(bio_err, " -inform arg input format - DER or PEM\n"); BIO_printf(bio_err, " -outform arg output format - DER or PEM\n"); BIO_printf(bio_err, " -in arg input file\n"); BIO_printf(bio_err, " -out arg output file\n"); BIO_printf(bio_err, " -text text form of request\n"); BIO_printf(bio_err, " -pubkey output public key\n"); BIO_printf(bio_err, " -noout do not output REQ\n"); BIO_printf(bio_err, " -verify verify signature on REQ\n"); BIO_printf(bio_err, " -modulus RSA modulus\n"); BIO_printf(bio_err, " -nodes don't encrypt the output key\n"); #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err, " -engine e use engine e, possibly a hardware device\n"); #endif BIO_printf(bio_err, " -subject output the request's subject\n"); BIO_printf(bio_err, " -passin private key password source\n"); BIO_printf(bio_err, " -key file use the private key contained in file\n"); BIO_printf(bio_err, " -keyform arg key file format\n"); BIO_printf(bio_err, " -keyout arg file to send the key to\n"); BIO_printf(bio_err, " -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR); BIO_printf(bio_err, " load the file (or the files in the directory) into\n"); BIO_printf(bio_err, " the random number generator\n"); BIO_printf(bio_err, " -newkey rsa:bits generate a new RSA key of 'bits' in size\n"); BIO_printf(bio_err, " -newkey dsa:file generate a new DSA key, parameters taken from CA in 'file'\n"); #ifndef OPENSSL_NO_ECDSA BIO_printf(bio_err, " -newkey ec:file generate a new EC key, parameters taken from CA in 'file'\n"); #endif BIO_printf(bio_err, " -[digest] Digest to sign with (md5, sha1, md2, mdc2, md4)\n"); BIO_printf(bio_err, " -config file request template file.\n"); BIO_printf(bio_err, " -subj arg set or modify request subject\n"); BIO_printf(bio_err, " -multivalue-rdn enable support for multivalued RDNs\n"); BIO_printf(bio_err, " -new new request.\n"); BIO_printf(bio_err, " -batch do not ask anything during request generation\n"); BIO_printf(bio_err, " -x509 output a x509 structure instead of a cert. req.\n"); BIO_printf(bio_err, " -days number of days a certificate generated by -x509 is valid for.\n"); BIO_printf(bio_err, " -set_serial serial number to use for a certificate generated by -x509.\n"); BIO_printf(bio_err, " -newhdr output \"NEW\" in the header lines\n"); BIO_printf(bio_err, " -asn1-kludge Output the 'request' in a format that is wrong but some CA's\n"); BIO_printf(bio_err, " have been reported as requiring\n"); BIO_printf(bio_err, " -extensions .. specify certificate extension section (override value in config file)\n"); BIO_printf(bio_err, " -reqexts .. specify request extension section (override value in config file)\n"); BIO_printf(bio_err, " -utf8 input characters are UTF8 (default ASCII)\n"); BIO_printf(bio_err, " -nameopt arg - various certificate name options\n"); BIO_printf(bio_err, " -reqopt arg - various request text options\n\n"); goto end; } + if (x509 && infile == NULL) + newreq = 1; + ERR_load_crypto_strings(); if (!app_passwd(bio_err, passargin, passargout, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } #ifndef MONOLITH /* else this has happened in openssl.c * (global `config') */ /* Lets load up our environment a little */ p = getenv("OPENSSL_CONF"); if (p == NULL) p = getenv("SSLEAY_CONF"); if (p == NULL) p = to_free = make_config_name(); default_config_file = p; config = NCONF_new(NULL); i = NCONF_load(config, p, &errline); #endif if (template != NULL) { long errline = -1; if (verbose) BIO_printf(bio_err, "Using configuration from %s\n", template); req_conf = NCONF_new(NULL); i = NCONF_load(req_conf, template, &errline); if (i == 0) { BIO_printf(bio_err, "error on line %ld of %s\n", errline, template); goto end; } } else { req_conf = config; if (req_conf == NULL) { BIO_printf(bio_err, "Unable to load config info from %s\n", default_config_file); if (newreq) goto end; } else if (verbose) BIO_printf(bio_err, "Using configuration from %s\n", default_config_file); } if (req_conf != NULL) { if (!load_config(bio_err, req_conf)) goto end; p = NCONF_get_string(req_conf, NULL, "oid_file"); if (p == NULL) ERR_clear_error(); if (p != NULL) { BIO *oid_bio; oid_bio = BIO_new_file(p, "r"); if (oid_bio == NULL) { /*- BIO_printf(bio_err,"problems opening %s for extra oid's\n",p); ERR_print_errors(bio_err); */ } else { OBJ_create_objects(oid_bio); BIO_free(oid_bio); } } } if (!add_oid_section(bio_err, req_conf)) goto end; if (md_alg == NULL) { p = NCONF_get_string(req_conf, SECTION, "default_md"); if (p == NULL) ERR_clear_error(); if (p != NULL) { if ((md_alg = EVP_get_digestbyname(p)) != NULL) digest = md_alg; } } if (!extensions) { extensions = NCONF_get_string(req_conf, SECTION, V3_EXTENSIONS); if (!extensions) ERR_clear_error(); } if (extensions) { /* Check syntax of file */ X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); X509V3_set_nconf(&ctx, req_conf); if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) { BIO_printf(bio_err, "Error Loading extension section %s\n", extensions); goto end; } } if (!passin) { passin = NCONF_get_string(req_conf, SECTION, "input_password"); if (!passin) ERR_clear_error(); } if (!passout) { passout = NCONF_get_string(req_conf, SECTION, "output_password"); if (!passout) ERR_clear_error(); } p = NCONF_get_string(req_conf, SECTION, STRING_MASK); if (!p) ERR_clear_error(); if (p && !ASN1_STRING_set_default_mask_asc(p)) { BIO_printf(bio_err, "Invalid global string mask setting %s\n", p); goto end; } if (chtype != MBSTRING_UTF8) { p = NCONF_get_string(req_conf, SECTION, UTF8_IN); if (!p) ERR_clear_error(); else if (!strcmp(p, "yes")) chtype = MBSTRING_UTF8; } if (!req_exts) { req_exts = NCONF_get_string(req_conf, SECTION, REQ_EXTENSIONS); if (!req_exts) ERR_clear_error(); } if (req_exts) { /* Check syntax of file */ X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); X509V3_set_nconf(&ctx, req_conf); if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) { BIO_printf(bio_err, "Error Loading request extension section %s\n", req_exts); goto end; } } in = BIO_new(BIO_s_file()); out = BIO_new(BIO_s_file()); if ((in == NULL) || (out == NULL)) goto end; e = setup_engine(bio_err, engine, 0); if (keyfile != NULL) { pkey = load_key(bio_err, keyfile, keyform, 0, passin, e, "Private Key"); if (!pkey) { /* * load_key() has already printed an appropriate message */ goto end; } else { char *randfile = NCONF_get_string(req_conf, SECTION, "RANDFILE"); if (randfile == NULL) ERR_clear_error(); app_RAND_load_file(randfile, bio_err, 0); } } if (newreq && (pkey == NULL)) { char *randfile = NCONF_get_string(req_conf, SECTION, "RANDFILE"); if (randfile == NULL) ERR_clear_error(); app_RAND_load_file(randfile, bio_err, 0); if (inrand) app_RAND_load_files(inrand); if (!NCONF_get_number(req_conf, SECTION, BITS, &newkey)) { newkey = DEFAULT_KEY_LENGTH; } if (keyalg) { genctx = set_keygen_ctx(bio_err, keyalg, &pkey_type, &newkey, &keyalgstr, gen_eng); if (!genctx) goto end; } if (newkey < MIN_KEY_LENGTH && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) { BIO_printf(bio_err, "private key length is too short,\n"); BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n", MIN_KEY_LENGTH, newkey); goto end; } if (!genctx) { genctx = set_keygen_ctx(bio_err, NULL, &pkey_type, &newkey, &keyalgstr, gen_eng); if (!genctx) goto end; } if (pkeyopts) { char *genopt; for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) { genopt = sk_OPENSSL_STRING_value(pkeyopts, i); if (pkey_ctrl_string(genctx, genopt) <= 0) { BIO_printf(bio_err, "parameter error \"%s\"\n", genopt); ERR_print_errors(bio_err); goto end; } } } BIO_printf(bio_err, "Generating a %ld bit %s private key\n", newkey, keyalgstr); EVP_PKEY_CTX_set_cb(genctx, genpkey_cb); EVP_PKEY_CTX_set_app_data(genctx, bio_err); if (EVP_PKEY_keygen(genctx, &pkey) <= 0) { BIO_puts(bio_err, "Error Generating Key\n"); goto end; } EVP_PKEY_CTX_free(genctx); genctx = NULL; app_RAND_write_file(randfile, bio_err); if (keyout == NULL) { keyout = NCONF_get_string(req_conf, SECTION, KEYFILE); if (keyout == NULL) ERR_clear_error(); } if (keyout == NULL) { BIO_printf(bio_err, "writing new private key to stdout\n"); BIO_set_fp(out, stdout, BIO_NOCLOSE); #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); out = BIO_push(tmpbio, out); } #endif } else { BIO_printf(bio_err, "writing new private key to '%s'\n", keyout); if (BIO_write_filename(out, keyout) <= 0) { perror(keyout); goto end; } } p = NCONF_get_string(req_conf, SECTION, "encrypt_rsa_key"); if (p == NULL) { ERR_clear_error(); p = NCONF_get_string(req_conf, SECTION, "encrypt_key"); if (p == NULL) ERR_clear_error(); } if ((p != NULL) && (strcmp(p, "no") == 0)) cipher = NULL; if (nodes) cipher = NULL; i = 0; loop: if (!PEM_write_bio_PrivateKey(out, pkey, cipher, NULL, 0, NULL, passout)) { if ((ERR_GET_REASON(ERR_peek_error()) == PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) { ERR_clear_error(); i++; goto loop; } goto end; } BIO_printf(bio_err, "-----\n"); } if (!newreq) { /* * Since we are using a pre-existing certificate request, the kludge * 'format' info should not be changed. */ kludge = -1; if (infile == NULL) BIO_set_fp(in, stdin, BIO_NOCLOSE); else { if (BIO_read_filename(in, infile) <= 0) { perror(infile); goto end; } } if (informat == FORMAT_ASN1) req = d2i_X509_REQ_bio(in, NULL); else if (informat == FORMAT_PEM) req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL); else { BIO_printf(bio_err, "bad input format specified for X509 request\n"); goto end; } if (req == NULL) { BIO_printf(bio_err, "unable to load X509 request\n"); goto end; } } - if (newreq) { + if (newreq || x509) { if (pkey == NULL) { BIO_printf(bio_err, "you need to specify a private key\n"); goto end; } if (req == NULL) { req = X509_REQ_new(); if (req == NULL) { goto end; } i = make_REQ(req, pkey, subj, multirdn, !x509, chtype); subj = NULL; /* done processing '-subj' option */ if ((kludge > 0) && !sk_X509_ATTRIBUTE_num(req->req_info->attributes)) { sk_X509_ATTRIBUTE_free(req->req_info->attributes); req->req_info->attributes = NULL; } if (!i) { BIO_printf(bio_err, "problems making Certificate Request\n"); goto end; } } if (x509) { EVP_PKEY *tmppkey; X509V3_CTX ext_ctx; if ((x509ss = X509_new()) == NULL) goto end; /* Set version to V3 */ if (extensions && !X509_set_version(x509ss, 2)) goto end; if (serial) { if (!X509_set_serialNumber(x509ss, serial)) goto end; } else { if (!rand_serial(NULL, X509_get_serialNumber(x509ss))) goto end; } if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req))) goto end; if (!X509_gmtime_adj(X509_get_notBefore(x509ss), 0)) goto end; if (!X509_time_adj_ex(X509_get_notAfter(x509ss), days, 0, NULL)) goto end; if (!X509_set_subject_name (x509ss, X509_REQ_get_subject_name(req))) goto end; tmppkey = X509_REQ_get_pubkey(req); if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey)) goto end; EVP_PKEY_free(tmppkey); /* Set up V3 context struct */ X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0); X509V3_set_nconf(&ext_ctx, req_conf); /* Add extensions */ if (extensions && !X509V3_EXT_add_nconf(req_conf, &ext_ctx, extensions, x509ss)) { BIO_printf(bio_err, "Error Loading extension section %s\n", extensions); goto end; } i = do_X509_sign(bio_err, x509ss, pkey, digest, sigopts); if (!i) { ERR_print_errors(bio_err); goto end; } } else { X509V3_CTX ext_ctx; /* Set up V3 context struct */ X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0); X509V3_set_nconf(&ext_ctx, req_conf); /* Add extensions */ if (req_exts && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx, req_exts, req)) { BIO_printf(bio_err, "Error Loading extension section %s\n", req_exts); goto end; } i = do_X509_REQ_sign(bio_err, req, pkey, digest, sigopts); if (!i) { ERR_print_errors(bio_err); goto end; } } } if (subj && x509) { BIO_printf(bio_err, "Cannot modifiy certificate subject\n"); goto end; } if (subj && !x509) { if (verbose) { BIO_printf(bio_err, "Modifying Request's Subject\n"); print_name(bio_err, "old subject=", X509_REQ_get_subject_name(req), nmflag); } if (build_subject(req, subj, chtype, multirdn) == 0) { BIO_printf(bio_err, "ERROR: cannot modify subject\n"); ex = 1; goto end; } req->req_info->enc.modified = 1; if (verbose) { print_name(bio_err, "new subject=", X509_REQ_get_subject_name(req), nmflag); } } if (verify && !x509) { int tmp = 0; if (pkey == NULL) { pkey = X509_REQ_get_pubkey(req); tmp = 1; if (pkey == NULL) goto end; } i = X509_REQ_verify(req, pkey); if (tmp) { EVP_PKEY_free(pkey); pkey = NULL; } if (i < 0) { goto end; } else if (i == 0) { BIO_printf(bio_err, "verify failure\n"); ERR_print_errors(bio_err); } else /* if (i > 0) */ BIO_printf(bio_err, "verify OK\n"); } if (noout && !text && !modulus && !subject && !pubkey) { ex = 0; goto end; } if (outfile == NULL) { BIO_set_fp(out, stdout, BIO_NOCLOSE); #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); out = BIO_push(tmpbio, out); } #endif } else { if ((keyout != NULL) && (strcmp(outfile, keyout) == 0)) i = (int)BIO_append_filename(out, outfile); else i = (int)BIO_write_filename(out, outfile); if (!i) { perror(outfile); goto end; } } if (pubkey) { EVP_PKEY *tpubkey; tpubkey = X509_REQ_get_pubkey(req); if (tpubkey == NULL) { BIO_printf(bio_err, "Error getting public key\n"); ERR_print_errors(bio_err); goto end; } PEM_write_bio_PUBKEY(out, tpubkey); EVP_PKEY_free(tpubkey); } if (text) { if (x509) X509_print_ex(out, x509ss, nmflag, reqflag); else X509_REQ_print_ex(out, req, nmflag, reqflag); } if (subject) { if (x509) print_name(out, "subject=", X509_get_subject_name(x509ss), nmflag); else print_name(out, "subject=", X509_REQ_get_subject_name(req), nmflag); } if (modulus) { EVP_PKEY *tpubkey; if (x509) tpubkey = X509_get_pubkey(x509ss); else tpubkey = X509_REQ_get_pubkey(req); if (tpubkey == NULL) { fprintf(stdout, "Modulus=unavailable\n"); goto end; } fprintf(stdout, "Modulus="); #ifndef OPENSSL_NO_RSA if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA) BN_print(out, tpubkey->pkey.rsa->n); else #endif fprintf(stdout, "Wrong Algorithm type"); EVP_PKEY_free(tpubkey); fprintf(stdout, "\n"); } if (!noout && !x509) { if (outformat == FORMAT_ASN1) i = i2d_X509_REQ_bio(out, req); else if (outformat == FORMAT_PEM) { if (newhdr) i = PEM_write_bio_X509_REQ_NEW(out, req); else i = PEM_write_bio_X509_REQ(out, req); } else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } if (!i) { BIO_printf(bio_err, "unable to write X509 request\n"); goto end; } } if (!noout && x509 && (x509ss != NULL)) { if (outformat == FORMAT_ASN1) i = i2d_X509_bio(out, x509ss); else if (outformat == FORMAT_PEM) i = PEM_write_bio_X509(out, x509ss); else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } if (!i) { BIO_printf(bio_err, "unable to write X509 certificate\n"); goto end; } } ex = 0; end: #ifndef MONOLITH if (to_free) OPENSSL_free(to_free); #endif if (ex) { ERR_print_errors(bio_err); } if ((req_conf != NULL) && (req_conf != config)) NCONF_free(req_conf); BIO_free(in); BIO_free_all(out); EVP_PKEY_free(pkey); if (genctx) EVP_PKEY_CTX_free(genctx); if (pkeyopts) sk_OPENSSL_STRING_free(pkeyopts); if (sigopts) sk_OPENSSL_STRING_free(sigopts); #ifndef OPENSSL_NO_ENGINE if (gen_eng) ENGINE_free(gen_eng); #endif if (keyalgstr) OPENSSL_free(keyalgstr); X509_REQ_free(req); X509_free(x509ss); ASN1_INTEGER_free(serial); release_engine(e); if (passargin && passin) OPENSSL_free(passin); if (passargout && passout) OPENSSL_free(passout); OBJ_cleanup(); apps_shutdown(); OPENSSL_EXIT(ex); } static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn, int attribs, unsigned long chtype) { int ret = 0, i; char no_prompt = 0; STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL; char *tmp, *dn_sect, *attr_sect; tmp = NCONF_get_string(req_conf, SECTION, PROMPT); if (tmp == NULL) ERR_clear_error(); if ((tmp != NULL) && !strcmp(tmp, "no")) no_prompt = 1; dn_sect = NCONF_get_string(req_conf, SECTION, DISTINGUISHED_NAME); if (dn_sect == NULL) { BIO_printf(bio_err, "unable to find '%s' in config\n", DISTINGUISHED_NAME); goto err; } dn_sk = NCONF_get_section(req_conf, dn_sect); if (dn_sk == NULL) { BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect); goto err; } attr_sect = NCONF_get_string(req_conf, SECTION, ATTRIBUTES); if (attr_sect == NULL) { ERR_clear_error(); attr_sk = NULL; } else { attr_sk = NCONF_get_section(req_conf, attr_sect); if (attr_sk == NULL) { BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect); goto err; } } /* setup version number */ if (!X509_REQ_set_version(req, 0L)) goto err; /* version 1 */ if (no_prompt) i = auto_info(req, dn_sk, attr_sk, attribs, chtype); else { if (subj) i = build_subject(req, subj, chtype, multirdn); else i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs, chtype); } if (!i) goto err; if (!X509_REQ_set_pubkey(req, pkey)) goto err; ret = 1; err: return (ret); } /* * subject is expected to be in the format /type0=value0/type1=value1/type2=... * where characters may be escaped by \ */ static int build_subject(X509_REQ *req, char *subject, unsigned long chtype, int multirdn) { X509_NAME *n; if (!(n = parse_name(subject, chtype, multirdn))) return 0; if (!X509_REQ_set_subject_name(req, n)) { X509_NAME_free(n); return 0; } X509_NAME_free(n); return 1; } static int prompt_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk, char *dn_sect, STACK_OF(CONF_VALUE) *attr_sk, char *attr_sect, int attribs, unsigned long chtype) { int i; char *p, *q; char buf[100]; int nid, mval; long n_min, n_max; char *type, *value; const char *def; CONF_VALUE *v; X509_NAME *subj; subj = X509_REQ_get_subject_name(req); if (!batch) { BIO_printf(bio_err, "You are about to be asked to enter information that will be incorporated\n"); BIO_printf(bio_err, "into your certificate request.\n"); BIO_printf(bio_err, "What you are about to enter is what is called a Distinguished Name or a DN.\n"); BIO_printf(bio_err, "There are quite a few fields but you can leave some blank\n"); BIO_printf(bio_err, "For some fields there will be a default value,\n"); BIO_printf(bio_err, "If you enter '.', the field will be left blank.\n"); BIO_printf(bio_err, "-----\n"); } if (sk_CONF_VALUE_num(dn_sk)) { i = -1; start:for (;;) { i++; if (sk_CONF_VALUE_num(dn_sk) <= i) break; v = sk_CONF_VALUE_value(dn_sk, i); p = q = NULL; type = v->name; if (!check_end(type, "_min") || !check_end(type, "_max") || !check_end(type, "_default") || !check_end(type, "_value")) continue; /* * Skip past any leading X. X: X, etc to allow for multiple * instances */ for (p = v->name; *p; p++) if ((*p == ':') || (*p == ',') || (*p == '.')) { p++; if (*p) type = p; break; } if (*type == '+') { mval = -1; type++; } else mval = 0; /* If OBJ not recognised ignore it */ if ((nid = OBJ_txt2nid(type)) == NID_undef) goto start; if (BIO_snprintf(buf, sizeof buf, "%s_default", v->name) >= (int)sizeof(buf)) { BIO_printf(bio_err, "Name '%s' too long\n", v->name); return 0; } if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) { ERR_clear_error(); def = ""; } BIO_snprintf(buf, sizeof buf, "%s_value", v->name); if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) { ERR_clear_error(); value = NULL; } BIO_snprintf(buf, sizeof buf, "%s_min", v->name); if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) { ERR_clear_error(); n_min = -1; } BIO_snprintf(buf, sizeof buf, "%s_max", v->name); if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) { ERR_clear_error(); n_max = -1; } if (!add_DN_object(subj, v->value, def, value, nid, n_min, n_max, chtype, mval)) return 0; } if (X509_NAME_entry_count(subj) == 0) { BIO_printf(bio_err, "error, no objects specified in config file\n"); return 0; } if (attribs) { if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0) && (!batch)) { BIO_printf(bio_err, "\nPlease enter the following 'extra' attributes\n"); BIO_printf(bio_err, "to be sent with your certificate request\n"); } i = -1; start2: for (;;) { i++; if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i)) break; v = sk_CONF_VALUE_value(attr_sk, i); type = v->name; if ((nid = OBJ_txt2nid(type)) == NID_undef) goto start2; if (BIO_snprintf(buf, sizeof buf, "%s_default", type) >= (int)sizeof(buf)) { BIO_printf(bio_err, "Name '%s' too long\n", v->name); return 0; } if ((def = NCONF_get_string(req_conf, attr_sect, buf)) == NULL) { ERR_clear_error(); def = ""; } BIO_snprintf(buf, sizeof buf, "%s_value", type); if ((value = NCONF_get_string(req_conf, attr_sect, buf)) == NULL) { ERR_clear_error(); value = NULL; } BIO_snprintf(buf, sizeof buf, "%s_min", type); if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) { ERR_clear_error(); n_min = -1; } BIO_snprintf(buf, sizeof buf, "%s_max", type); if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) { ERR_clear_error(); n_max = -1; } if (!add_attribute_object(req, v->value, def, value, nid, n_min, n_max, chtype)) return 0; } } } else { BIO_printf(bio_err, "No template, please set one up.\n"); return 0; } return 1; } static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk, STACK_OF(CONF_VALUE) *attr_sk, int attribs, unsigned long chtype) { int i; char *p, *q; char *type; CONF_VALUE *v; X509_NAME *subj; subj = X509_REQ_get_subject_name(req); for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) { int mval; v = sk_CONF_VALUE_value(dn_sk, i); p = q = NULL; type = v->name; /* * Skip past any leading X. X: X, etc to allow for multiple instances */ for (p = v->name; *p; p++) #ifndef CHARSET_EBCDIC if ((*p == ':') || (*p == ',') || (*p == '.')) { #else if ((*p == os_toascii[':']) || (*p == os_toascii[',']) || (*p == os_toascii['.'])) { #endif p++; if (*p) type = p; break; } #ifndef CHARSET_EBCDIC if (*type == '+') { #else if (*type == os_toascii['+']) { #endif type++; mval = -1; } else mval = 0; if (!X509_NAME_add_entry_by_txt(subj, type, chtype, (unsigned char *)v->value, -1, -1, mval)) return 0; } if (!X509_NAME_entry_count(subj)) { BIO_printf(bio_err, "error, no objects specified in config file\n"); return 0; } if (attribs) { for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) { v = sk_CONF_VALUE_value(attr_sk, i); if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype, (unsigned char *)v->value, -1)) return 0; } } return 1; } static int add_DN_object(X509_NAME *n, char *text, const char *def, char *value, int nid, int n_min, int n_max, unsigned long chtype, int mval) { int i, ret = 0; MS_STATIC char buf[1024]; start: if (!batch) BIO_printf(bio_err, "%s [%s]:", text, def); (void)BIO_flush(bio_err); if (value != NULL) { BUF_strlcpy(buf, value, sizeof buf); BUF_strlcat(buf, "\n", sizeof buf); BIO_printf(bio_err, "%s\n", value); } else { buf[0] = '\0'; if (!batch) { if (!fgets(buf, sizeof buf, stdin)) return 0; } else { buf[0] = '\n'; buf[1] = '\0'; } } if (buf[0] == '\0') return (0); else if (buf[0] == '\n') { if ((def == NULL) || (def[0] == '\0')) return (1); BUF_strlcpy(buf, def, sizeof buf); BUF_strlcat(buf, "\n", sizeof buf); } else if ((buf[0] == '.') && (buf[1] == '\n')) return (1); i = strlen(buf); if (buf[i - 1] != '\n') { BIO_printf(bio_err, "weird input :-(\n"); return (0); } buf[--i] = '\0'; #ifdef CHARSET_EBCDIC ebcdic2ascii(buf, buf, i); #endif if (!req_check_len(i, n_min, n_max)) { if (batch || value) return 0; goto start; } if (!X509_NAME_add_entry_by_NID(n, nid, chtype, (unsigned char *)buf, -1, -1, mval)) goto err; ret = 1; err: return (ret); } static int add_attribute_object(X509_REQ *req, char *text, const char *def, char *value, int nid, int n_min, int n_max, unsigned long chtype) { int i; static char buf[1024]; start: if (!batch) BIO_printf(bio_err, "%s [%s]:", text, def); (void)BIO_flush(bio_err); if (value != NULL) { BUF_strlcpy(buf, value, sizeof buf); BUF_strlcat(buf, "\n", sizeof buf); BIO_printf(bio_err, "%s\n", value); } else { buf[0] = '\0'; if (!batch) { if (!fgets(buf, sizeof buf, stdin)) return 0; } else { buf[0] = '\n'; buf[1] = '\0'; } } if (buf[0] == '\0') return (0); else if (buf[0] == '\n') { if ((def == NULL) || (def[0] == '\0')) return (1); BUF_strlcpy(buf, def, sizeof buf); BUF_strlcat(buf, "\n", sizeof buf); } else if ((buf[0] == '.') && (buf[1] == '\n')) return (1); i = strlen(buf); if (buf[i - 1] != '\n') { BIO_printf(bio_err, "weird input :-(\n"); return (0); } buf[--i] = '\0'; #ifdef CHARSET_EBCDIC ebcdic2ascii(buf, buf, i); #endif if (!req_check_len(i, n_min, n_max)) { if (batch || value) return 0; goto start; } if (!X509_REQ_add1_attr_by_NID(req, nid, chtype, (unsigned char *)buf, -1)) { BIO_printf(bio_err, "Error adding attribute\n"); ERR_print_errors(bio_err); goto err; } return (1); err: return (0); } static int req_check_len(int len, int n_min, int n_max) { if ((n_min > 0) && (len < n_min)) { BIO_printf(bio_err, "string is too short, it needs to be at least %d bytes long\n", n_min); return (0); } if ((n_max >= 0) && (len > n_max)) { BIO_printf(bio_err, "string is too long, it needs to be less than %d bytes long\n", n_max); return (0); } return (1); } /* Check if the end of a string matches 'end' */ static int check_end(const char *str, const char *end) { int elen, slen; const char *tmp; elen = strlen(end); slen = strlen(str); if (elen > slen) return 1; tmp = str + slen - elen; return strcmp(tmp, end); } static EVP_PKEY_CTX *set_keygen_ctx(BIO *err, const char *gstr, int *pkey_type, long *pkeylen, char **palgnam, ENGINE *keygen_engine) { EVP_PKEY_CTX *gctx = NULL; EVP_PKEY *param = NULL; long keylen = -1; BIO *pbio = NULL; const char *paramfile = NULL; if (gstr == NULL) { *pkey_type = EVP_PKEY_RSA; keylen = *pkeylen; } else if (gstr[0] >= '0' && gstr[0] <= '9') { *pkey_type = EVP_PKEY_RSA; keylen = atol(gstr); *pkeylen = keylen; } else if (!strncmp(gstr, "param:", 6)) paramfile = gstr + 6; else { const char *p = strchr(gstr, ':'); int len; ENGINE *tmpeng; const EVP_PKEY_ASN1_METHOD *ameth; if (p) len = p - gstr; else len = strlen(gstr); /* * The lookup of a the string will cover all engines so keep a note * of the implementation. */ ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len); if (!ameth) { BIO_printf(err, "Unknown algorithm %.*s\n", len, gstr); return NULL; } EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth); #ifndef OPENSSL_NO_ENGINE if (tmpeng) ENGINE_finish(tmpeng); #endif if (*pkey_type == EVP_PKEY_RSA) { if (p) { keylen = atol(p + 1); *pkeylen = keylen; } else keylen = *pkeylen; } else if (p) paramfile = p + 1; } if (paramfile) { pbio = BIO_new_file(paramfile, "r"); if (!pbio) { BIO_printf(err, "Can't open parameter file %s\n", paramfile); return NULL; } param = PEM_read_bio_Parameters(pbio, NULL); if (!param) { X509 *x; (void)BIO_reset(pbio); x = PEM_read_bio_X509(pbio, NULL, NULL, NULL); if (x) { param = X509_get_pubkey(x); X509_free(x); } } BIO_free(pbio); if (!param) { BIO_printf(err, "Error reading parameter file %s\n", paramfile); return NULL; } if (*pkey_type == -1) *pkey_type = EVP_PKEY_id(param); else if (*pkey_type != EVP_PKEY_base_id(param)) { BIO_printf(err, "Key Type does not match parameters\n"); EVP_PKEY_free(param); return NULL; } } if (palgnam) { const EVP_PKEY_ASN1_METHOD *ameth; ENGINE *tmpeng; const char *anam; ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type); if (!ameth) { BIO_puts(err, "Internal error: can't find key algorithm\n"); return NULL; } EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth); *palgnam = BUF_strdup(anam); #ifndef OPENSSL_NO_ENGINE if (tmpeng) ENGINE_finish(tmpeng); #endif } if (param) { gctx = EVP_PKEY_CTX_new(param, keygen_engine); *pkeylen = EVP_PKEY_bits(param); EVP_PKEY_free(param); } else gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine); if (!gctx) { BIO_puts(err, "Error allocating keygen context\n"); ERR_print_errors(err); return NULL; } if (EVP_PKEY_keygen_init(gctx) <= 0) { BIO_puts(err, "Error initializing keygen context\n"); ERR_print_errors(err); return NULL; } #ifndef OPENSSL_NO_RSA if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) { if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) { BIO_puts(err, "Error setting RSA keysize\n"); ERR_print_errors(err); EVP_PKEY_CTX_free(gctx); return NULL; } } #endif return gctx; } static int genpkey_cb(EVP_PKEY_CTX *ctx) { char c = '*'; BIO *b = EVP_PKEY_CTX_get_app_data(ctx); int p; p = EVP_PKEY_CTX_get_keygen_info(ctx, 0); if (p == 0) c = '.'; if (p == 1) c = '+'; if (p == 2) c = '*'; if (p == 3) c = '\n'; BIO_write(b, &c, 1); (void)BIO_flush(b); #ifdef LINT p = n; #endif return 1; } static int do_sign_init(BIO *err, EVP_MD_CTX *ctx, EVP_PKEY *pkey, const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts) { EVP_PKEY_CTX *pkctx = NULL; int i; EVP_MD_CTX_init(ctx); if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey)) return 0; for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) { char *sigopt = sk_OPENSSL_STRING_value(sigopts, i); if (pkey_ctrl_string(pkctx, sigopt) <= 0) { BIO_printf(err, "parameter error \"%s\"\n", sigopt); ERR_print_errors(bio_err); return 0; } } return 1; } int do_X509_sign(BIO *err, X509 *x, EVP_PKEY *pkey, const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts) { int rv; EVP_MD_CTX mctx; EVP_MD_CTX_init(&mctx); rv = do_sign_init(err, &mctx, pkey, md, sigopts); if (rv > 0) rv = X509_sign_ctx(x, &mctx); EVP_MD_CTX_cleanup(&mctx); return rv > 0 ? 1 : 0; } int do_X509_REQ_sign(BIO *err, X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts) { int rv; EVP_MD_CTX mctx; EVP_MD_CTX_init(&mctx); rv = do_sign_init(err, &mctx, pkey, md, sigopts); if (rv > 0) rv = X509_REQ_sign_ctx(x, &mctx); EVP_MD_CTX_cleanup(&mctx); return rv > 0 ? 1 : 0; } int do_X509_CRL_sign(BIO *err, X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts) { int rv; EVP_MD_CTX mctx; EVP_MD_CTX_init(&mctx); rv = do_sign_init(err, &mctx, pkey, md, sigopts); if (rv > 0) rv = X509_CRL_sign_ctx(x, &mctx); EVP_MD_CTX_cleanup(&mctx); return rv > 0 ? 1 : 0; } Index: vendor-crypto/openssl/dist/apps/s_client.c =================================================================== --- vendor-crypto/openssl/dist/apps/s_client.c (revision 318896) +++ vendor-crypto/openssl/dist/apps/s_client.c (revision 318897) @@ -1,2360 +1,2361 @@ /* apps/s_client.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ /* ==================================================================== * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ /* ==================================================================== * Copyright 2005 Nokia. All rights reserved. * * The portions of the attached software ("Contribution") is developed by * Nokia Corporation and is licensed pursuant to the OpenSSL open source * license. * * The Contribution, originally written by Mika Kousa and Pasi Eronen of * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites * support (see RFC 4279) to OpenSSL. * * No patent licenses or other rights except those expressly stated in * the OpenSSL open source license shall be deemed granted or received * expressly, by implication, estoppel, or otherwise. * * No assurances are provided by Nokia that the Contribution does not * infringe the patent or other intellectual property rights of any third * party or that the license provides you with all the necessary rights * to make use of the Contribution. * * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR * OTHERWISE. */ #include #include #include #include #include #include #ifdef OPENSSL_NO_STDIO # define APPS_WIN16 #endif /* * With IPv6, it looks like Digital has mixed up the proper order of * recursive header file inclusion, resulting in the compiler complaining * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is * needed to have fileno() declared correctly... So let's define u_int */ #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT) # define __U_INT typedef unsigned int u_int; #endif #define USE_SOCKETS #include "apps.h" #include #include #include #include #include #include #include #ifndef OPENSSL_NO_SRP # include #endif #include "s_apps.h" #include "timeouts.h" #if (defined(OPENSSL_SYS_VMS) && __VMS_VER < 70000000) /* FIONBIO used as a switch to enable ioctl, and that isn't in VMS < 7.0 */ # undef FIONBIO #endif #if defined(OPENSSL_SYS_BEOS_R5) # include #endif #undef PROG #define PROG s_client_main /* * #define SSL_HOST_NAME "www.netscape.com" */ /* * #define SSL_HOST_NAME "193.118.187.102" */ #define SSL_HOST_NAME "localhost" /* no default cert. */ /* * #define TEST_CERT "client.pem" */ #undef BUFSIZZ #define BUFSIZZ 1024*8 extern int verify_depth; extern int verify_error; extern int verify_return_error; extern int verify_quiet; #ifdef FIONBIO static int c_nbio = 0; #endif static int c_Pause = 0; static int c_debug = 0; #ifndef OPENSSL_NO_TLSEXT static int c_tlsextdebug = 0; static int c_status_req = 0; #endif static int c_msg = 0; static int c_showcerts = 0; static char *keymatexportlabel = NULL; static int keymatexportlen = 20; static void sc_usage(void); static void print_stuff(BIO *berr, SSL *con, int full); #ifndef OPENSSL_NO_TLSEXT static int ocsp_resp_cb(SSL *s, void *arg); #endif static BIO *bio_c_out = NULL; static BIO *bio_c_msg = NULL; static int c_quiet = 0; static int c_ign_eof = 0; static int c_brief = 0; #ifndef OPENSSL_NO_PSK /* Default PSK identity and key */ static char *psk_identity = "Client_identity"; /* * char *psk_key=NULL; by default PSK is not used */ static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity, unsigned int max_identity_len, unsigned char *psk, unsigned int max_psk_len) { int ret; long key_len; unsigned char *key; if (c_debug) BIO_printf(bio_c_out, "psk_client_cb\n"); if (!hint) { /* no ServerKeyExchange message */ if (c_debug) BIO_printf(bio_c_out, "NULL received PSK identity hint, continuing anyway\n"); } else if (c_debug) BIO_printf(bio_c_out, "Received PSK identity hint '%s'\n", hint); /* * lookup PSK identity and PSK key based on the given identity hint here */ ret = BIO_snprintf(identity, max_identity_len, "%s", psk_identity); if (ret < 0 || (unsigned int)ret > max_identity_len) goto out_err; if (c_debug) BIO_printf(bio_c_out, "created identity '%s' len=%d\n", identity, ret); /* convert the PSK key to binary */ key = string_to_hex(psk_key, &key_len); if (key == NULL) { BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n", psk_key); return 0; } if ((unsigned long)key_len > (unsigned long)max_psk_len) { BIO_printf(bio_err, "psk buffer of callback is too small (%d) for key (%ld)\n", max_psk_len, key_len); OPENSSL_free(key); return 0; } memcpy(psk, key, key_len); OPENSSL_free(key); if (c_debug) BIO_printf(bio_c_out, "created PSK len=%ld\n", key_len); return key_len; out_err: if (c_debug) BIO_printf(bio_err, "Error in PSK client callback\n"); return 0; } #endif static void sc_usage(void) { BIO_printf(bio_err, "usage: s_client args\n"); BIO_printf(bio_err, "\n"); BIO_printf(bio_err, " -host host - use -connect instead\n"); BIO_printf(bio_err, " -port port - use -connect instead\n"); BIO_printf(bio_err, " -connect host:port - who to connect to (default is %s:%s)\n", SSL_HOST_NAME, PORT_STR); BIO_printf(bio_err, " -verify_hostname host - check peer certificate matches \"host\"\n"); BIO_printf(bio_err, " -verify_email email - check peer certificate matches \"email\"\n"); BIO_printf(bio_err, " -verify_ip ipaddr - check peer certificate matches \"ipaddr\"\n"); BIO_printf(bio_err, " -verify arg - turn on peer certificate verification\n"); BIO_printf(bio_err, " -verify_return_error - return verification errors\n"); BIO_printf(bio_err, " -cert arg - certificate file to use, PEM format assumed\n"); BIO_printf(bio_err, " -certform arg - certificate format (PEM or DER) PEM default\n"); BIO_printf(bio_err, " -key arg - Private key file to use, in cert file if\n"); BIO_printf(bio_err, " not specified but cert file is.\n"); BIO_printf(bio_err, " -keyform arg - key format (PEM or DER) PEM default\n"); BIO_printf(bio_err, " -pass arg - private key file pass phrase source\n"); BIO_printf(bio_err, " -CApath arg - PEM format directory of CA's\n"); BIO_printf(bio_err, " -CAfile arg - PEM format file of CA's\n"); BIO_printf(bio_err, " -no_alt_chains - only ever use the first certificate chain found\n"); BIO_printf(bio_err, " -reconnect - Drop and re-make the connection with the same Session-ID\n"); BIO_printf(bio_err, " -pause - sleep(1) after each read(2) and write(2) system call\n"); BIO_printf(bio_err, " -prexit - print session information even on connection failure\n"); BIO_printf(bio_err, " -showcerts - show all certificates in the chain\n"); BIO_printf(bio_err, " -debug - extra output\n"); #ifdef WATT32 BIO_printf(bio_err, " -wdebug - WATT-32 tcp debugging\n"); #endif BIO_printf(bio_err, " -msg - Show protocol messages\n"); BIO_printf(bio_err, " -nbio_test - more ssl protocol testing\n"); BIO_printf(bio_err, " -state - print the 'ssl' states\n"); #ifdef FIONBIO BIO_printf(bio_err, " -nbio - Run with non-blocking IO\n"); #endif BIO_printf(bio_err, " -crlf - convert LF from terminal into CRLF\n"); BIO_printf(bio_err, " -quiet - no s_client output\n"); BIO_printf(bio_err, " -ign_eof - ignore input eof (default when -quiet)\n"); BIO_printf(bio_err, " -no_ign_eof - don't ignore input eof\n"); #ifndef OPENSSL_NO_PSK BIO_printf(bio_err, " -psk_identity arg - PSK identity\n"); BIO_printf(bio_err, " -psk arg - PSK in hex (without 0x)\n"); # ifndef OPENSSL_NO_JPAKE BIO_printf(bio_err, " -jpake arg - JPAKE secret to use\n"); # endif #endif #ifndef OPENSSL_NO_SRP BIO_printf(bio_err, " -srpuser user - SRP authentification for 'user'\n"); BIO_printf(bio_err, " -srppass arg - password for 'user'\n"); BIO_printf(bio_err, " -srp_lateuser - SRP username into second ClientHello message\n"); BIO_printf(bio_err, " -srp_moregroups - Tolerate other than the known g N values.\n"); BIO_printf(bio_err, " -srp_strength int - minimal length in bits for N (default %d).\n", SRP_MINIMAL_N); #endif BIO_printf(bio_err, " -ssl2 - just use SSLv2\n"); #ifndef OPENSSL_NO_SSL3_METHOD BIO_printf(bio_err, " -ssl3 - just use SSLv3\n"); #endif BIO_printf(bio_err, " -tls1_2 - just use TLSv1.2\n"); BIO_printf(bio_err, " -tls1_1 - just use TLSv1.1\n"); BIO_printf(bio_err, " -tls1 - just use TLSv1\n"); BIO_printf(bio_err, " -dtls1 - just use DTLSv1\n"); BIO_printf(bio_err, " -fallback_scsv - send TLS_FALLBACK_SCSV\n"); BIO_printf(bio_err, " -mtu - set the link layer MTU\n"); BIO_printf(bio_err, " -no_tls1_2/-no_tls1_1/-no_tls1/-no_ssl3/-no_ssl2 - turn off that protocol\n"); BIO_printf(bio_err, " -bugs - Switch on all SSL implementation bug workarounds\n"); BIO_printf(bio_err, " -cipher - preferred cipher to use, use the 'openssl ciphers'\n"); BIO_printf(bio_err, " command to see what is available\n"); BIO_printf(bio_err, " -starttls prot - use the STARTTLS command before starting TLS\n"); BIO_printf(bio_err, " for those protocols that support it, where\n"); BIO_printf(bio_err, " 'prot' defines which one to assume. Currently,\n"); BIO_printf(bio_err, " only \"smtp\", \"pop3\", \"imap\", \"ftp\" and \"xmpp\"\n"); BIO_printf(bio_err, " are supported.\n"); #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err, " -engine id - Initialise and use the specified engine\n"); #endif BIO_printf(bio_err, " -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR); BIO_printf(bio_err, " -sess_out arg - file to write SSL session to\n"); BIO_printf(bio_err, " -sess_in arg - file to read SSL session from\n"); #ifndef OPENSSL_NO_TLSEXT BIO_printf(bio_err, " -servername host - Set TLS extension servername in ClientHello\n"); BIO_printf(bio_err, " -tlsextdebug - hex dump of all TLS extensions received\n"); BIO_printf(bio_err, " -status - request certificate status from server\n"); BIO_printf(bio_err, " -no_ticket - disable use of RFC4507bis session tickets\n"); BIO_printf(bio_err, " -serverinfo types - send empty ClientHello extensions (comma-separated numbers)\n"); BIO_printf(bio_err, " -curves arg - Elliptic curves to advertise (colon-separated list)\n"); BIO_printf(bio_err, " -sigalgs arg - Signature algorithms to support (colon-separated list)\n"); BIO_printf(bio_err, " -client_sigalgs arg - Signature algorithms to support for client\n"); BIO_printf(bio_err, " certificate authentication (colon-separated list)\n"); #endif #ifndef OPENSSL_NO_NEXTPROTONEG BIO_printf(bio_err, " -nextprotoneg arg - enable NPN extension, considering named protocols supported (comma-separated list)\n"); #endif BIO_printf(bio_err, " -alpn arg - enable ALPN extension, considering named protocols supported (comma-separated list)\n"); BIO_printf(bio_err, " -legacy_renegotiation - enable use of legacy renegotiation (dangerous)\n"); #ifndef OPENSSL_NO_SRTP BIO_printf(bio_err, " -use_srtp profiles - Offer SRTP key management with a colon-separated profile list\n"); #endif BIO_printf(bio_err, " -keymatexport label - Export keying material using label\n"); BIO_printf(bio_err, " -keymatexportlen len - Export len bytes of keying material (default 20)\n"); } #ifndef OPENSSL_NO_TLSEXT /* This is a context that we pass to callbacks */ typedef struct tlsextctx_st { BIO *biodebug; int ack; } tlsextctx; static int MS_CALLBACK ssl_servername_cb(SSL *s, int *ad, void *arg) { tlsextctx *p = (tlsextctx *) arg; const char *hn = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name); if (SSL_get_servername_type(s) != -1) p->ack = !SSL_session_reused(s) && hn != NULL; else BIO_printf(bio_err, "Can't use SSL_get_servername\n"); return SSL_TLSEXT_ERR_OK; } # ifndef OPENSSL_NO_SRP /* This is a context that we pass to all callbacks */ typedef struct srp_arg_st { char *srppassin; char *srplogin; int msg; /* copy from c_msg */ int debug; /* copy from c_debug */ int amp; /* allow more groups */ int strength /* minimal size for N */ ; } SRP_ARG; # define SRP_NUMBER_ITERATIONS_FOR_PRIME 64 static int srp_Verify_N_and_g(BIGNUM *N, BIGNUM *g) { BN_CTX *bn_ctx = BN_CTX_new(); BIGNUM *p = BN_new(); BIGNUM *r = BN_new(); int ret = g != NULL && N != NULL && bn_ctx != NULL && BN_is_odd(N) && BN_is_prime_ex(N, SRP_NUMBER_ITERATIONS_FOR_PRIME, bn_ctx, NULL) && p != NULL && BN_rshift1(p, N) && /* p = (N-1)/2 */ BN_is_prime_ex(p, SRP_NUMBER_ITERATIONS_FOR_PRIME, bn_ctx, NULL) && r != NULL && /* verify g^((N-1)/2) == -1 (mod N) */ BN_mod_exp(r, g, p, N, bn_ctx) && BN_add_word(r, 1) && BN_cmp(r, N) == 0; if (r) BN_free(r); if (p) BN_free(p); if (bn_ctx) BN_CTX_free(bn_ctx); return ret; } /*- * This callback is used here for two purposes: * - extended debugging * - making some primality tests for unknown groups * The callback is only called for a non default group. * * An application does not need the call back at all if * only the stanard groups are used. In real life situations, * client and server already share well known groups, * thus there is no need to verify them. * Furthermore, in case that a server actually proposes a group that * is not one of those defined in RFC 5054, it is more appropriate * to add the group to a static list and then compare since * primality tests are rather cpu consuming. */ static int MS_CALLBACK ssl_srp_verify_param_cb(SSL *s, void *arg) { SRP_ARG *srp_arg = (SRP_ARG *)arg; BIGNUM *N = NULL, *g = NULL; if (!(N = SSL_get_srp_N(s)) || !(g = SSL_get_srp_g(s))) return 0; if (srp_arg->debug || srp_arg->msg || srp_arg->amp == 1) { BIO_printf(bio_err, "SRP parameters:\n"); BIO_printf(bio_err, "\tN="); BN_print(bio_err, N); BIO_printf(bio_err, "\n\tg="); BN_print(bio_err, g); BIO_printf(bio_err, "\n"); } if (SRP_check_known_gN_param(g, N)) return 1; if (srp_arg->amp == 1) { if (srp_arg->debug) BIO_printf(bio_err, "SRP param N and g are not known params, going to check deeper.\n"); /* * The srp_moregroups is a real debugging feature. Implementors * should rather add the value to the known ones. The minimal size * has already been tested. */ if (BN_num_bits(g) <= BN_BITS && srp_Verify_N_and_g(N, g)) return 1; } BIO_printf(bio_err, "SRP param N and g rejected.\n"); return 0; } # define PWD_STRLEN 1024 static char *MS_CALLBACK ssl_give_srp_client_pwd_cb(SSL *s, void *arg) { SRP_ARG *srp_arg = (SRP_ARG *)arg; char *pass = (char *)OPENSSL_malloc(PWD_STRLEN + 1); PW_CB_DATA cb_tmp; int l; if (!pass) { BIO_printf(bio_err, "Malloc failure\n"); return NULL; } cb_tmp.password = (char *)srp_arg->srppassin; cb_tmp.prompt_info = "SRP user"; if ((l = password_callback(pass, PWD_STRLEN, 0, &cb_tmp)) < 0) { BIO_printf(bio_err, "Can't read Password\n"); OPENSSL_free(pass); return NULL; } *(pass + l) = '\0'; return pass; } # endif # ifndef OPENSSL_NO_SRTP char *srtp_profiles = NULL; # endif # ifndef OPENSSL_NO_NEXTPROTONEG /* This the context that we pass to next_proto_cb */ typedef struct tlsextnextprotoctx_st { unsigned char *data; unsigned short len; int status; } tlsextnextprotoctx; static tlsextnextprotoctx next_proto; static int next_proto_cb(SSL *s, unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg) { tlsextnextprotoctx *ctx = arg; if (!c_quiet) { /* We can assume that |in| is syntactically valid. */ unsigned i; BIO_printf(bio_c_out, "Protocols advertised by server: "); for (i = 0; i < inlen;) { if (i) BIO_write(bio_c_out, ", ", 2); BIO_write(bio_c_out, &in[i + 1], in[i]); i += in[i] + 1; } BIO_write(bio_c_out, "\n", 1); } ctx->status = SSL_select_next_proto(out, outlen, in, inlen, ctx->data, ctx->len); return SSL_TLSEXT_ERR_OK; } # endif /* ndef OPENSSL_NO_NEXTPROTONEG */ static int serverinfo_cli_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *arg) { char pem_name[100]; unsigned char ext_buf[4 + 65536]; /* Reconstruct the type/len fields prior to extension data */ ext_buf[0] = ext_type >> 8; ext_buf[1] = ext_type & 0xFF; ext_buf[2] = inlen >> 8; ext_buf[3] = inlen & 0xFF; memcpy(ext_buf + 4, in, inlen); BIO_snprintf(pem_name, sizeof(pem_name), "SERVERINFO FOR EXTENSION %d", ext_type); PEM_write_bio(bio_c_out, pem_name, "", ext_buf, 4 + inlen); return 1; } #endif enum { PROTO_OFF = 0, PROTO_SMTP, PROTO_POP3, PROTO_IMAP, PROTO_FTP, PROTO_XMPP }; int MAIN(int, char **); int MAIN(int argc, char **argv) { int build_chain = 0; SSL *con = NULL; #ifndef OPENSSL_NO_KRB5 KSSL_CTX *kctx; #endif int s, k, width, state = 0; char *cbuf = NULL, *sbuf = NULL, *mbuf = NULL; int cbuf_len, cbuf_off; int sbuf_len, sbuf_off; fd_set readfds, writefds; short port = PORT; int full_log = 1; char *host = SSL_HOST_NAME; char *cert_file = NULL, *key_file = NULL, *chain_file = NULL; int cert_format = FORMAT_PEM, key_format = FORMAT_PEM; char *passarg = NULL, *pass = NULL; X509 *cert = NULL; EVP_PKEY *key = NULL; STACK_OF(X509) *chain = NULL; char *CApath = NULL, *CAfile = NULL; char *chCApath = NULL, *chCAfile = NULL; char *vfyCApath = NULL, *vfyCAfile = NULL; int reconnect = 0, badop = 0, verify = SSL_VERIFY_NONE; int crlf = 0; int write_tty, read_tty, write_ssl, read_ssl, tty_on, ssl_pending; SSL_CTX *ctx = NULL; int ret = 1, in_init = 1, i, nbio_test = 0; int starttls_proto = PROTO_OFF; int prexit = 0; X509_VERIFY_PARAM *vpm = NULL; int badarg = 0; const SSL_METHOD *meth = NULL; int socket_type = SOCK_STREAM; BIO *sbio; char *inrand = NULL; int mbuf_len = 0; struct timeval timeout, *timeoutp; char *engine_id = NULL; ENGINE *e = NULL; #ifndef OPENSSL_NO_ENGINE char *ssl_client_engine_id = NULL; ENGINE *ssl_client_engine = NULL; #endif #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE) || defined(OPENSSL_SYS_BEOS_R5) struct timeval tv; # if defined(OPENSSL_SYS_BEOS_R5) int stdin_set = 0; # endif #endif #ifndef OPENSSL_NO_TLSEXT char *servername = NULL; tlsextctx tlsextcbp = { NULL, 0 }; # ifndef OPENSSL_NO_NEXTPROTONEG const char *next_proto_neg_in = NULL; # endif const char *alpn_in = NULL; # define MAX_SI_TYPES 100 unsigned short serverinfo_types[MAX_SI_TYPES]; int serverinfo_types_count = 0; #endif char *sess_in = NULL; char *sess_out = NULL; struct sockaddr peer; int peerlen = sizeof(peer); int fallback_scsv = 0; int enable_timeouts = 0; long socket_mtu = 0; #ifndef OPENSSL_NO_JPAKE static char *jpake_secret = NULL; # define no_jpake !jpake_secret #else # define no_jpake 1 #endif #ifndef OPENSSL_NO_SRP char *srppass = NULL; int srp_lateuser = 0; SRP_ARG srp_arg = { NULL, NULL, 0, 0, 0, 1024 }; #endif SSL_EXCERT *exc = NULL; SSL_CONF_CTX *cctx = NULL; STACK_OF(OPENSSL_STRING) *ssl_args = NULL; char *crl_file = NULL; int crl_format = FORMAT_PEM; int crl_download = 0; STACK_OF(X509_CRL) *crls = NULL; int prot_opt = 0, no_prot_opt = 0; meth = SSLv23_client_method(); apps_startup(); c_Pause = 0; c_quiet = 0; c_ign_eof = 0; c_debug = 0; c_msg = 0; c_showcerts = 0; if (bio_err == NULL) bio_err = BIO_new_fp(stderr, BIO_NOCLOSE); if (!load_config(bio_err, NULL)) goto end; cctx = SSL_CONF_CTX_new(); if (!cctx) goto end; SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT); SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CMDLINE); if (((cbuf = OPENSSL_malloc(BUFSIZZ)) == NULL) || ((sbuf = OPENSSL_malloc(BUFSIZZ)) == NULL) || ((mbuf = OPENSSL_malloc(BUFSIZZ)) == NULL)) { BIO_printf(bio_err, "out of memory\n"); goto end; } verify_depth = 0; verify_error = X509_V_OK; #ifdef FIONBIO c_nbio = 0; #endif argc--; argv++; while (argc >= 1) { if (strcmp(*argv, "-host") == 0) { if (--argc < 1) goto bad; host = *(++argv); } else if (strcmp(*argv, "-port") == 0) { if (--argc < 1) goto bad; port = atoi(*(++argv)); if (port == 0) goto bad; } else if (strcmp(*argv, "-connect") == 0) { if (--argc < 1) goto bad; if (!extract_host_port(*(++argv), &host, NULL, &port)) goto bad; } else if (strcmp(*argv, "-verify") == 0) { verify = SSL_VERIFY_PEER; if (--argc < 1) goto bad; verify_depth = atoi(*(++argv)); if (!c_quiet) BIO_printf(bio_err, "verify depth is %d\n", verify_depth); } else if (strcmp(*argv, "-cert") == 0) { if (--argc < 1) goto bad; cert_file = *(++argv); } else if (strcmp(*argv, "-CRL") == 0) { if (--argc < 1) goto bad; crl_file = *(++argv); } else if (strcmp(*argv, "-crl_download") == 0) crl_download = 1; else if (strcmp(*argv, "-sess_out") == 0) { if (--argc < 1) goto bad; sess_out = *(++argv); } else if (strcmp(*argv, "-sess_in") == 0) { if (--argc < 1) goto bad; sess_in = *(++argv); } else if (strcmp(*argv, "-certform") == 0) { if (--argc < 1) goto bad; cert_format = str2fmt(*(++argv)); } else if (strcmp(*argv, "-CRLform") == 0) { if (--argc < 1) goto bad; crl_format = str2fmt(*(++argv)); } else if (args_verify(&argv, &argc, &badarg, bio_err, &vpm)) { if (badarg) goto bad; continue; } else if (strcmp(*argv, "-verify_return_error") == 0) verify_return_error = 1; else if (strcmp(*argv, "-verify_quiet") == 0) verify_quiet = 1; else if (strcmp(*argv, "-brief") == 0) { c_brief = 1; verify_quiet = 1; c_quiet = 1; } else if (args_excert(&argv, &argc, &badarg, bio_err, &exc)) { if (badarg) goto bad; continue; } else if (args_ssl(&argv, &argc, cctx, &badarg, bio_err, &ssl_args, &no_prot_opt)) { if (badarg) goto bad; continue; } else if (strcmp(*argv, "-prexit") == 0) prexit = 1; else if (strcmp(*argv, "-crlf") == 0) crlf = 1; else if (strcmp(*argv, "-quiet") == 0) { c_quiet = 1; c_ign_eof = 1; } else if (strcmp(*argv, "-ign_eof") == 0) c_ign_eof = 1; else if (strcmp(*argv, "-no_ign_eof") == 0) c_ign_eof = 0; else if (strcmp(*argv, "-pause") == 0) c_Pause = 1; else if (strcmp(*argv, "-debug") == 0) c_debug = 1; #ifndef OPENSSL_NO_TLSEXT else if (strcmp(*argv, "-tlsextdebug") == 0) c_tlsextdebug = 1; else if (strcmp(*argv, "-status") == 0) c_status_req = 1; #endif #ifdef WATT32 else if (strcmp(*argv, "-wdebug") == 0) dbug_init(); #endif else if (strcmp(*argv, "-msg") == 0) c_msg = 1; else if (strcmp(*argv, "-msgfile") == 0) { if (--argc < 1) goto bad; bio_c_msg = BIO_new_file(*(++argv), "w"); } #ifndef OPENSSL_NO_SSL_TRACE else if (strcmp(*argv, "-trace") == 0) c_msg = 2; #endif else if (strcmp(*argv, "-showcerts") == 0) c_showcerts = 1; else if (strcmp(*argv, "-nbio_test") == 0) nbio_test = 1; else if (strcmp(*argv, "-state") == 0) state = 1; #ifndef OPENSSL_NO_PSK else if (strcmp(*argv, "-psk_identity") == 0) { if (--argc < 1) goto bad; psk_identity = *(++argv); } else if (strcmp(*argv, "-psk") == 0) { size_t j; if (--argc < 1) goto bad; psk_key = *(++argv); for (j = 0; j < strlen(psk_key); j++) { if (isxdigit((unsigned char)psk_key[j])) continue; BIO_printf(bio_err, "Not a hex number '%s'\n", *argv); goto bad; } } #endif #ifndef OPENSSL_NO_SRP else if (strcmp(*argv, "-srpuser") == 0) { if (--argc < 1) goto bad; srp_arg.srplogin = *(++argv); meth = TLSv1_client_method(); } else if (strcmp(*argv, "-srppass") == 0) { if (--argc < 1) goto bad; srppass = *(++argv); meth = TLSv1_client_method(); } else if (strcmp(*argv, "-srp_strength") == 0) { if (--argc < 1) goto bad; srp_arg.strength = atoi(*(++argv)); BIO_printf(bio_err, "SRP minimal length for N is %d\n", srp_arg.strength); meth = TLSv1_client_method(); } else if (strcmp(*argv, "-srp_lateuser") == 0) { srp_lateuser = 1; meth = TLSv1_client_method(); } else if (strcmp(*argv, "-srp_moregroups") == 0) { srp_arg.amp = 1; meth = TLSv1_client_method(); } #endif #ifndef OPENSSL_NO_SSL2 else if (strcmp(*argv, "-ssl2") == 0) { meth = SSLv2_client_method(); prot_opt++; } #endif #ifndef OPENSSL_NO_SSL3_METHOD else if (strcmp(*argv, "-ssl3") == 0) { meth = SSLv3_client_method(); prot_opt++; } #endif #ifndef OPENSSL_NO_TLS1 else if (strcmp(*argv, "-tls1_2") == 0) { meth = TLSv1_2_client_method(); prot_opt++; } else if (strcmp(*argv, "-tls1_1") == 0) { meth = TLSv1_1_client_method(); prot_opt++; } else if (strcmp(*argv, "-tls1") == 0) { meth = TLSv1_client_method(); prot_opt++; } #endif #ifndef OPENSSL_NO_DTLS1 else if (strcmp(*argv, "-dtls") == 0) { meth = DTLS_client_method(); socket_type = SOCK_DGRAM; prot_opt++; } else if (strcmp(*argv, "-dtls1") == 0) { meth = DTLSv1_client_method(); socket_type = SOCK_DGRAM; prot_opt++; } else if (strcmp(*argv, "-dtls1_2") == 0) { meth = DTLSv1_2_client_method(); socket_type = SOCK_DGRAM; prot_opt++; } else if (strcmp(*argv, "-timeout") == 0) enable_timeouts = 1; else if (strcmp(*argv, "-mtu") == 0) { if (--argc < 1) goto bad; socket_mtu = atol(*(++argv)); } #endif else if (strcmp(*argv, "-fallback_scsv") == 0) { fallback_scsv = 1; } else if (strcmp(*argv, "-keyform") == 0) { if (--argc < 1) goto bad; key_format = str2fmt(*(++argv)); } else if (strcmp(*argv, "-pass") == 0) { if (--argc < 1) goto bad; passarg = *(++argv); } else if (strcmp(*argv, "-cert_chain") == 0) { if (--argc < 1) goto bad; chain_file = *(++argv); } else if (strcmp(*argv, "-key") == 0) { if (--argc < 1) goto bad; key_file = *(++argv); } else if (strcmp(*argv, "-reconnect") == 0) { reconnect = 5; } else if (strcmp(*argv, "-CApath") == 0) { if (--argc < 1) goto bad; CApath = *(++argv); } else if (strcmp(*argv, "-chainCApath") == 0) { if (--argc < 1) goto bad; chCApath = *(++argv); } else if (strcmp(*argv, "-verifyCApath") == 0) { if (--argc < 1) goto bad; vfyCApath = *(++argv); } else if (strcmp(*argv, "-build_chain") == 0) build_chain = 1; else if (strcmp(*argv, "-CAfile") == 0) { if (--argc < 1) goto bad; CAfile = *(++argv); } else if (strcmp(*argv, "-chainCAfile") == 0) { if (--argc < 1) goto bad; chCAfile = *(++argv); } else if (strcmp(*argv, "-verifyCAfile") == 0) { if (--argc < 1) goto bad; vfyCAfile = *(++argv); } #ifndef OPENSSL_NO_TLSEXT # ifndef OPENSSL_NO_NEXTPROTONEG else if (strcmp(*argv, "-nextprotoneg") == 0) { if (--argc < 1) goto bad; next_proto_neg_in = *(++argv); } # endif else if (strcmp(*argv, "-alpn") == 0) { if (--argc < 1) goto bad; alpn_in = *(++argv); } else if (strcmp(*argv, "-serverinfo") == 0) { char *c; int start = 0; int len; if (--argc < 1) goto bad; c = *(++argv); serverinfo_types_count = 0; len = strlen(c); for (i = 0; i <= len; ++i) { if (i == len || c[i] == ',') { serverinfo_types[serverinfo_types_count] = atoi(c + start); serverinfo_types_count++; start = i + 1; } if (serverinfo_types_count == MAX_SI_TYPES) break; } } #endif #ifdef FIONBIO else if (strcmp(*argv, "-nbio") == 0) { c_nbio = 1; } #endif else if (strcmp(*argv, "-starttls") == 0) { if (--argc < 1) goto bad; ++argv; if (strcmp(*argv, "smtp") == 0) starttls_proto = PROTO_SMTP; else if (strcmp(*argv, "pop3") == 0) starttls_proto = PROTO_POP3; else if (strcmp(*argv, "imap") == 0) starttls_proto = PROTO_IMAP; else if (strcmp(*argv, "ftp") == 0) starttls_proto = PROTO_FTP; else if (strcmp(*argv, "xmpp") == 0) starttls_proto = PROTO_XMPP; else goto bad; } #ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv, "-engine") == 0) { if (--argc < 1) goto bad; engine_id = *(++argv); } else if (strcmp(*argv, "-ssl_client_engine") == 0) { if (--argc < 1) goto bad; ssl_client_engine_id = *(++argv); } #endif else if (strcmp(*argv, "-rand") == 0) { if (--argc < 1) goto bad; inrand = *(++argv); } #ifndef OPENSSL_NO_TLSEXT else if (strcmp(*argv, "-servername") == 0) { if (--argc < 1) goto bad; servername = *(++argv); /* meth=TLSv1_client_method(); */ } #endif #ifndef OPENSSL_NO_JPAKE else if (strcmp(*argv, "-jpake") == 0) { if (--argc < 1) goto bad; jpake_secret = *++argv; } #endif #ifndef OPENSSL_NO_SRTP else if (strcmp(*argv, "-use_srtp") == 0) { if (--argc < 1) goto bad; srtp_profiles = *(++argv); } #endif else if (strcmp(*argv, "-keymatexport") == 0) { if (--argc < 1) goto bad; keymatexportlabel = *(++argv); } else if (strcmp(*argv, "-keymatexportlen") == 0) { if (--argc < 1) goto bad; keymatexportlen = atoi(*(++argv)); if (keymatexportlen == 0) goto bad; } else { BIO_printf(bio_err, "unknown option %s\n", *argv); badop = 1; break; } argc--; argv++; } if (badop) { bad: sc_usage(); goto end; } #if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK) if (jpake_secret) { if (psk_key) { BIO_printf(bio_err, "Can't use JPAKE and PSK together\n"); goto end; } psk_identity = "JPAKE"; } #endif if (prot_opt > 1) { BIO_printf(bio_err, "Cannot supply multiple protocol flags\n"); goto end; } if (prot_opt == 1 && no_prot_opt) { BIO_printf(bio_err, "Cannot supply both a protocol flag and " "\"-no_\"\n"); goto end; } OpenSSL_add_ssl_algorithms(); SSL_load_error_strings(); #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) next_proto.status = -1; if (next_proto_neg_in) { next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in); if (next_proto.data == NULL) { BIO_printf(bio_err, "Error parsing -nextprotoneg argument\n"); goto end; } } else next_proto.data = NULL; #endif e = setup_engine(bio_err, engine_id, 1); #ifndef OPENSSL_NO_ENGINE if (ssl_client_engine_id) { ssl_client_engine = ENGINE_by_id(ssl_client_engine_id); if (!ssl_client_engine) { BIO_printf(bio_err, "Error getting client auth engine\n"); goto end; } } #endif if (!app_passwd(bio_err, passarg, NULL, &pass, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } if (key_file == NULL) key_file = cert_file; if (key_file) { key = load_key(bio_err, key_file, key_format, 0, pass, e, "client certificate private key file"); if (!key) { ERR_print_errors(bio_err); goto end; } } if (cert_file) { cert = load_cert(bio_err, cert_file, cert_format, NULL, e, "client certificate file"); if (!cert) { ERR_print_errors(bio_err); goto end; } } if (chain_file) { chain = load_certs(bio_err, chain_file, FORMAT_PEM, NULL, e, "client certificate chain"); if (!chain) goto end; } if (crl_file) { X509_CRL *crl; crl = load_crl(crl_file, crl_format); if (!crl) { BIO_puts(bio_err, "Error loading CRL\n"); ERR_print_errors(bio_err); goto end; } crls = sk_X509_CRL_new_null(); if (!crls || !sk_X509_CRL_push(crls, crl)) { BIO_puts(bio_err, "Error adding CRL\n"); ERR_print_errors(bio_err); X509_CRL_free(crl); goto end; } } if (!load_excert(&exc, bio_err)) goto end; if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL && !RAND_status()) { BIO_printf(bio_err, "warning, not much extra random data, consider using the -rand option\n"); } if (inrand != NULL) BIO_printf(bio_err, "%ld semi-random bytes loaded\n", app_RAND_load_files(inrand)); if (bio_c_out == NULL) { if (c_quiet && !c_debug) { bio_c_out = BIO_new(BIO_s_null()); if (c_msg && !bio_c_msg) bio_c_msg = BIO_new_fp(stdout, BIO_NOCLOSE); } else { if (bio_c_out == NULL) bio_c_out = BIO_new_fp(stdout, BIO_NOCLOSE); } } #ifndef OPENSSL_NO_SRP if (!app_passwd(bio_err, srppass, NULL, &srp_arg.srppassin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } #endif ctx = SSL_CTX_new(meth); if (ctx == NULL) { ERR_print_errors(bio_err); goto end; } if (vpm) SSL_CTX_set1_param(ctx, vpm); if (!args_ssl_call(ctx, bio_err, cctx, ssl_args, 1, no_jpake)) { ERR_print_errors(bio_err); goto end; } if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile, crls, crl_download)) { BIO_printf(bio_err, "Error loading store locations\n"); ERR_print_errors(bio_err); goto end; } #ifndef OPENSSL_NO_ENGINE if (ssl_client_engine) { if (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine)) { BIO_puts(bio_err, "Error setting client auth engine\n"); ERR_print_errors(bio_err); ENGINE_free(ssl_client_engine); goto end; } ENGINE_free(ssl_client_engine); } #endif #ifndef OPENSSL_NO_PSK # ifdef OPENSSL_NO_JPAKE if (psk_key != NULL) # else if (psk_key != NULL || jpake_secret) # endif { if (c_debug) BIO_printf(bio_c_out, "PSK key given or JPAKE in use, setting client callback\n"); SSL_CTX_set_psk_client_callback(ctx, psk_client_cb); } #endif #ifndef OPENSSL_NO_SRTP if (srtp_profiles != NULL) SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles); #endif if (exc) ssl_ctx_set_excert(ctx, exc); #if !defined(OPENSSL_NO_TLSEXT) # if !defined(OPENSSL_NO_NEXTPROTONEG) if (next_proto.data) SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &next_proto); # endif if (alpn_in) { unsigned short alpn_len; unsigned char *alpn = next_protos_parse(&alpn_len, alpn_in); if (alpn == NULL) { BIO_printf(bio_err, "Error parsing -alpn argument\n"); goto end; } SSL_CTX_set_alpn_protos(ctx, alpn, alpn_len); OPENSSL_free(alpn); } #endif #ifndef OPENSSL_NO_TLSEXT for (i = 0; i < serverinfo_types_count; i++) { SSL_CTX_add_client_custom_ext(ctx, serverinfo_types[i], NULL, NULL, NULL, serverinfo_cli_parse_cb, NULL); } #endif if (state) SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback); #if 0 else SSL_CTX_set_cipher_list(ctx, getenv("SSL_CIPHER")); #endif SSL_CTX_set_verify(ctx, verify, verify_callback); if ((CAfile || CApath) && !SSL_CTX_load_verify_locations(ctx, CAfile, CApath)) { ERR_print_errors(bio_err); } if (!SSL_CTX_set_default_verify_paths(ctx)) { ERR_print_errors(bio_err); } ssl_ctx_add_crls(ctx, crls, crl_download); if (!set_cert_key_stuff(ctx, cert, key, chain, build_chain)) goto end; #ifndef OPENSSL_NO_TLSEXT if (servername != NULL) { tlsextcbp.biodebug = bio_err; SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb); SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp); } # ifndef OPENSSL_NO_SRP if (srp_arg.srplogin) { if (!srp_lateuser && !SSL_CTX_set_srp_username(ctx, srp_arg.srplogin)) { BIO_printf(bio_err, "Unable to set SRP username\n"); goto end; } srp_arg.msg = c_msg; srp_arg.debug = c_debug; SSL_CTX_set_srp_cb_arg(ctx, &srp_arg); SSL_CTX_set_srp_client_pwd_callback(ctx, ssl_give_srp_client_pwd_cb); SSL_CTX_set_srp_strength(ctx, srp_arg.strength); if (c_msg || c_debug || srp_arg.amp == 0) SSL_CTX_set_srp_verify_param_callback(ctx, ssl_srp_verify_param_cb); } # endif #endif con = SSL_new(ctx); if (sess_in) { SSL_SESSION *sess; BIO *stmp = BIO_new_file(sess_in, "r"); if (!stmp) { BIO_printf(bio_err, "Can't open session file %s\n", sess_in); ERR_print_errors(bio_err); goto end; } sess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL); BIO_free(stmp); if (!sess) { BIO_printf(bio_err, "Can't open session file %s\n", sess_in); ERR_print_errors(bio_err); goto end; } SSL_set_session(con, sess); SSL_SESSION_free(sess); } if (fallback_scsv) SSL_set_mode(con, SSL_MODE_SEND_FALLBACK_SCSV); #ifndef OPENSSL_NO_TLSEXT if (servername != NULL) { if (!SSL_set_tlsext_host_name(con, servername)) { BIO_printf(bio_err, "Unable to set TLS servername extension.\n"); ERR_print_errors(bio_err); goto end; } } #endif #ifndef OPENSSL_NO_KRB5 if (con && (kctx = kssl_ctx_new()) != NULL) { SSL_set0_kssl_ctx(con, kctx); kssl_ctx_setstring(kctx, KSSL_SERVER, host); } #endif /* OPENSSL_NO_KRB5 */ /* SSL_set_cipher_list(con,"RC4-MD5"); */ #if 0 # ifdef TLSEXT_TYPE_opaque_prf_input SSL_set_tlsext_opaque_prf_input(con, "Test client", 11); # endif #endif re_start: if (init_client(&s, host, port, socket_type) == 0) { BIO_printf(bio_err, "connect:errno=%d\n", get_last_socket_error()); SHUTDOWN(s); goto end; } BIO_printf(bio_c_out, "CONNECTED(%08X)\n", s); #ifdef FIONBIO if (c_nbio) { unsigned long l = 1; BIO_printf(bio_c_out, "turning on non blocking io\n"); if (BIO_socket_ioctl(s, FIONBIO, &l) < 0) { ERR_print_errors(bio_err); goto end; } } #endif if (c_Pause & 0x01) SSL_set_debug(con, 1); if (socket_type == SOCK_DGRAM) { sbio = BIO_new_dgram(s, BIO_NOCLOSE); if (getsockname(s, &peer, (void *)&peerlen) < 0) { BIO_printf(bio_err, "getsockname:errno=%d\n", get_last_socket_error()); SHUTDOWN(s); goto end; } (void)BIO_ctrl_set_connected(sbio, 1, &peer); if (enable_timeouts) { timeout.tv_sec = 0; timeout.tv_usec = DGRAM_RCV_TIMEOUT; BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout); timeout.tv_sec = 0; timeout.tv_usec = DGRAM_SND_TIMEOUT; BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout); } if (socket_mtu) { if (socket_mtu < DTLS_get_link_min_mtu(con)) { BIO_printf(bio_err, "MTU too small. Must be at least %ld\n", DTLS_get_link_min_mtu(con)); BIO_free(sbio); goto shut; } SSL_set_options(con, SSL_OP_NO_QUERY_MTU); if (!DTLS_set_link_mtu(con, socket_mtu)) { BIO_printf(bio_err, "Failed to set MTU\n"); BIO_free(sbio); goto shut; } } else /* want to do MTU discovery */ BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL); } else sbio = BIO_new_socket(s, BIO_NOCLOSE); if (nbio_test) { BIO *test; test = BIO_new(BIO_f_nbio_test()); sbio = BIO_push(test, sbio); } if (c_debug) { SSL_set_debug(con, 1); BIO_set_callback(sbio, bio_dump_callback); BIO_set_callback_arg(sbio, (char *)bio_c_out); } if (c_msg) { #ifndef OPENSSL_NO_SSL_TRACE if (c_msg == 2) SSL_set_msg_callback(con, SSL_trace); else #endif SSL_set_msg_callback(con, msg_cb); SSL_set_msg_callback_arg(con, bio_c_msg ? bio_c_msg : bio_c_out); } #ifndef OPENSSL_NO_TLSEXT if (c_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_c_out); } if (c_status_req) { SSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp); SSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb); SSL_CTX_set_tlsext_status_arg(ctx, bio_c_out); # if 0 { STACK_OF(OCSP_RESPID) *ids = sk_OCSP_RESPID_new_null(); OCSP_RESPID *id = OCSP_RESPID_new(); id->value.byKey = ASN1_OCTET_STRING_new(); id->type = V_OCSP_RESPID_KEY; ASN1_STRING_set(id->value.byKey, "Hello World", -1); sk_OCSP_RESPID_push(ids, id); SSL_set_tlsext_status_ids(con, ids); } # endif } #endif #ifndef OPENSSL_NO_JPAKE if (jpake_secret) jpake_client_auth(bio_c_out, sbio, jpake_secret); #endif SSL_set_bio(con, sbio, sbio); SSL_set_connect_state(con); /* ok, lets connect */ if (fileno_stdin() > SSL_get_fd(con)) width = fileno_stdin() + 1; else width = SSL_get_fd(con) + 1; read_tty = 1; write_tty = 0; tty_on = 0; read_ssl = 1; write_ssl = 1; cbuf_len = 0; cbuf_off = 0; sbuf_len = 0; sbuf_off = 0; /* This is an ugly hack that does a lot of assumptions */ /* * We do have to handle multi-line responses which may come in a single * packet or not. We therefore have to use BIO_gets() which does need a * buffering BIO. So during the initial chitchat we do push a buffering * BIO into the chain that is removed again later on to not disturb the * rest of the s_client operation. */ if (starttls_proto == PROTO_SMTP) { int foundit = 0; BIO *fbio = BIO_new(BIO_f_buffer()); BIO_push(fbio, sbio); /* wait for multi-line response to end from SMTP */ do { mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ); } while (mbuf_len > 3 && mbuf[3] == '-'); /* STARTTLS command requires EHLO... */ BIO_printf(fbio, "EHLO openssl.client.net\r\n"); (void)BIO_flush(fbio); /* wait for multi-line response to end EHLO SMTP response */ do { mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ); if (strstr(mbuf, "STARTTLS")) foundit = 1; } while (mbuf_len > 3 && mbuf[3] == '-'); (void)BIO_flush(fbio); BIO_pop(fbio); BIO_free(fbio); if (!foundit) BIO_printf(bio_err, "didn't found starttls in server response," " try anyway...\n"); BIO_printf(sbio, "STARTTLS\r\n"); BIO_read(sbio, sbuf, BUFSIZZ); } else if (starttls_proto == PROTO_POP3) { BIO_read(sbio, mbuf, BUFSIZZ); BIO_printf(sbio, "STLS\r\n"); BIO_read(sbio, sbuf, BUFSIZZ); } else if (starttls_proto == PROTO_IMAP) { int foundit = 0; BIO *fbio = BIO_new(BIO_f_buffer()); BIO_push(fbio, sbio); BIO_gets(fbio, mbuf, BUFSIZZ); /* STARTTLS command requires CAPABILITY... */ BIO_printf(fbio, ". CAPABILITY\r\n"); (void)BIO_flush(fbio); /* wait for multi-line CAPABILITY response */ do { mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ); if (strstr(mbuf, "STARTTLS")) foundit = 1; } while (mbuf_len > 3 && mbuf[0] != '.'); (void)BIO_flush(fbio); BIO_pop(fbio); BIO_free(fbio); if (!foundit) BIO_printf(bio_err, "didn't found STARTTLS in server response," " try anyway...\n"); BIO_printf(sbio, ". STARTTLS\r\n"); BIO_read(sbio, sbuf, BUFSIZZ); } else if (starttls_proto == PROTO_FTP) { BIO *fbio = BIO_new(BIO_f_buffer()); BIO_push(fbio, sbio); /* wait for multi-line response to end from FTP */ do { mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ); } while (mbuf_len > 3 && mbuf[3] == '-'); (void)BIO_flush(fbio); BIO_pop(fbio); BIO_free(fbio); BIO_printf(sbio, "AUTH TLS\r\n"); BIO_read(sbio, sbuf, BUFSIZZ); } if (starttls_proto == PROTO_XMPP) { int seen = 0; BIO_printf(sbio, "", host); seen = BIO_read(sbio, mbuf, BUFSIZZ); mbuf[seen] = 0; while (!strstr (mbuf, "")) goto shut; seen = BIO_read(sbio, mbuf, BUFSIZZ); mbuf[seen] = 0; } BIO_printf(sbio, ""); seen = BIO_read(sbio, sbuf, BUFSIZZ); sbuf[seen] = 0; if (!strstr(sbuf, " 0) full_log--; if (starttls_proto) { BIO_printf(bio_err, "%s", mbuf); /* We don't need to know any more */ starttls_proto = PROTO_OFF; } if (reconnect) { reconnect--; BIO_printf(bio_c_out, "drop connection and then reconnect\n"); SSL_shutdown(con); SSL_set_connect_state(con); SHUTDOWN(SSL_get_fd(con)); goto re_start; } } } ssl_pending = read_ssl && SSL_pending(con); if (!ssl_pending) { #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_NETWARE) && !defined (OPENSSL_SYS_BEOS_R5) if (tty_on) { if (read_tty) openssl_fdset(fileno_stdin(), &readfds); #if !defined(OPENSSL_SYS_VMS) if (write_tty) openssl_fdset(fileno_stdout(), &writefds); #endif } if (read_ssl) openssl_fdset(SSL_get_fd(con), &readfds); if (write_ssl) openssl_fdset(SSL_get_fd(con), &writefds); #else if (!tty_on || !write_tty) { if (read_ssl) openssl_fdset(SSL_get_fd(con), &readfds); if (write_ssl) openssl_fdset(SSL_get_fd(con), &writefds); } #endif /*- printf("mode tty(%d %d%d) ssl(%d%d)\n", tty_on,read_tty,write_tty,read_ssl,write_ssl);*/ /* * Note: under VMS with SOCKETSHR the second parameter is * currently of type (int *) whereas under other systems it is * (void *) if you don't have a cast it will choke the compiler: * if you do have a cast then you can either go for (int *) or * (void *). */ #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) /* * Under Windows/DOS we make the assumption that we can always * write to the tty: therefore if we need to write to the tty we * just fall through. Otherwise we timeout the select every * second and see if there are any keypresses. Note: this is a * hack, in a proper Windows application we wouldn't do this. */ i = 0; if (!write_tty) { if (read_tty) { tv.tv_sec = 1; tv.tv_usec = 0; i = select(width, (void *)&readfds, (void *)&writefds, NULL, &tv); # if defined(OPENSSL_SYS_WINCE) || defined(OPENSSL_SYS_MSDOS) if (!i && (!_kbhit() || !read_tty)) continue; # else if (!i && (!((_kbhit()) || (WAIT_OBJECT_0 == WaitForSingleObject(GetStdHandle (STD_INPUT_HANDLE), 0))) || !read_tty)) continue; # endif } else i = select(width, (void *)&readfds, (void *)&writefds, NULL, timeoutp); } #elif defined(OPENSSL_SYS_NETWARE) if (!write_tty) { if (read_tty) { tv.tv_sec = 1; tv.tv_usec = 0; i = select(width, (void *)&readfds, (void *)&writefds, NULL, &tv); } else i = select(width, (void *)&readfds, (void *)&writefds, NULL, timeoutp); } #elif defined(OPENSSL_SYS_BEOS_R5) /* Under BeOS-R5 the situation is similar to DOS */ i = 0; stdin_set = 0; (void)fcntl(fileno_stdin(), F_SETFL, O_NONBLOCK); if (!write_tty) { if (read_tty) { tv.tv_sec = 1; tv.tv_usec = 0; i = select(width, (void *)&readfds, (void *)&writefds, NULL, &tv); if (read(fileno_stdin(), sbuf, 0) >= 0) stdin_set = 1; if (!i && (stdin_set != 1 || !read_tty)) continue; } else i = select(width, (void *)&readfds, (void *)&writefds, NULL, timeoutp); } (void)fcntl(fileno_stdin(), F_SETFL, 0); #else i = select(width, (void *)&readfds, (void *)&writefds, NULL, timeoutp); #endif if (i < 0) { BIO_printf(bio_err, "bad select %d\n", get_last_socket_error()); goto shut; /* goto end; */ } } if ((SSL_version(con) == DTLS1_VERSION) && DTLSv1_handle_timeout(con) > 0) { BIO_printf(bio_err, "TIMEOUT occured\n"); } if (!ssl_pending && FD_ISSET(SSL_get_fd(con), &writefds)) { k = SSL_write(con, &(cbuf[cbuf_off]), (unsigned int)cbuf_len); switch (SSL_get_error(con, k)) { case SSL_ERROR_NONE: cbuf_off += k; cbuf_len -= k; if (k <= 0) goto end; /* we have done a write(con,NULL,0); */ if (cbuf_len <= 0) { read_tty = 1; write_ssl = 0; } else { /* if (cbuf_len > 0) */ read_tty = 0; write_ssl = 1; } break; case SSL_ERROR_WANT_WRITE: BIO_printf(bio_c_out, "write W BLOCK\n"); write_ssl = 1; read_tty = 0; break; case SSL_ERROR_WANT_READ: BIO_printf(bio_c_out, "write R BLOCK\n"); write_tty = 0; read_ssl = 1; write_ssl = 0; break; case SSL_ERROR_WANT_X509_LOOKUP: BIO_printf(bio_c_out, "write X BLOCK\n"); break; case SSL_ERROR_ZERO_RETURN: if (cbuf_len != 0) { BIO_printf(bio_c_out, "shutdown\n"); ret = 0; goto shut; } else { read_tty = 1; write_ssl = 0; break; } case SSL_ERROR_SYSCALL: if ((k != 0) || (cbuf_len != 0)) { BIO_printf(bio_err, "write:errno=%d\n", get_last_socket_error()); goto shut; } else { read_tty = 1; write_ssl = 0; } break; case SSL_ERROR_SSL: ERR_print_errors(bio_err); goto shut; } } #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE) || defined(OPENSSL_SYS_BEOS_R5) || defined(OPENSSL_SYS_VMS) /* Assume Windows/DOS/BeOS can always write */ else if (!ssl_pending && write_tty) #else else if (!ssl_pending && FD_ISSET(fileno_stdout(), &writefds)) #endif { #ifdef CHARSET_EBCDIC ascii2ebcdic(&(sbuf[sbuf_off]), &(sbuf[sbuf_off]), sbuf_len); #endif i = raw_write_stdout(&(sbuf[sbuf_off]), sbuf_len); if (i <= 0) { BIO_printf(bio_c_out, "DONE\n"); ret = 0; goto shut; /* goto end; */ } sbuf_len -= i;; sbuf_off += i; if (sbuf_len <= 0) { read_ssl = 1; write_tty = 0; } } else if (ssl_pending || FD_ISSET(SSL_get_fd(con), &readfds)) { #ifdef RENEG { static int iiii; if (++iiii == 52) { SSL_renegotiate(con); iiii = 0; } } #endif #if 1 k = SSL_read(con, sbuf, 1024 /* BUFSIZZ */ ); #else /* Demo for pending and peek :-) */ k = SSL_read(con, sbuf, 16); { char zbuf[10240]; printf("read=%d pending=%d peek=%d\n", k, SSL_pending(con), SSL_peek(con, zbuf, 10240)); } #endif switch (SSL_get_error(con, k)) { case SSL_ERROR_NONE: if (k <= 0) goto end; sbuf_off = 0; sbuf_len = k; read_ssl = 0; write_tty = 1; break; case SSL_ERROR_WANT_WRITE: BIO_printf(bio_c_out, "read W BLOCK\n"); write_ssl = 1; read_tty = 0; break; case SSL_ERROR_WANT_READ: BIO_printf(bio_c_out, "read R BLOCK\n"); write_tty = 0; read_ssl = 1; if ((read_tty == 0) && (write_ssl == 0)) write_ssl = 1; break; case SSL_ERROR_WANT_X509_LOOKUP: BIO_printf(bio_c_out, "read X BLOCK\n"); break; case SSL_ERROR_SYSCALL: ret = get_last_socket_error(); if (c_brief) BIO_puts(bio_err, "CONNECTION CLOSED BY SERVER\n"); else BIO_printf(bio_err, "read:errno=%d\n", ret); goto shut; case SSL_ERROR_ZERO_RETURN: BIO_printf(bio_c_out, "closed\n"); ret = 0; goto shut; case SSL_ERROR_SSL: ERR_print_errors(bio_err); goto shut; /* break; */ } } #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) # if defined(OPENSSL_SYS_WINCE) || defined(OPENSSL_SYS_MSDOS) else if (_kbhit()) # else else if ((_kbhit()) || (WAIT_OBJECT_0 == WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 0))) # endif #elif defined (OPENSSL_SYS_NETWARE) else if (_kbhit()) #elif defined(OPENSSL_SYS_BEOS_R5) else if (stdin_set) #else else if (FD_ISSET(fileno_stdin(), &readfds)) #endif { if (crlf) { int j, lf_num; i = raw_read_stdin(cbuf, BUFSIZZ / 2); lf_num = 0; /* both loops are skipped when i <= 0 */ for (j = 0; j < i; j++) if (cbuf[j] == '\n') lf_num++; for (j = i - 1; j >= 0; j--) { cbuf[j + lf_num] = cbuf[j]; if (cbuf[j] == '\n') { lf_num--; i++; cbuf[j + lf_num] = '\r'; } } assert(lf_num == 0); } else i = raw_read_stdin(cbuf, BUFSIZZ); if ((!c_ign_eof) && ((i <= 0) || (cbuf[0] == 'Q'))) { BIO_printf(bio_err, "DONE\n"); ret = 0; goto shut; } if ((!c_ign_eof) && (cbuf[0] == 'R')) { BIO_printf(bio_err, "RENEGOTIATING\n"); SSL_renegotiate(con); cbuf_len = 0; } #ifndef OPENSSL_NO_HEARTBEATS else if ((!c_ign_eof) && (cbuf[0] == 'B')) { BIO_printf(bio_err, "HEARTBEATING\n"); SSL_heartbeat(con); cbuf_len = 0; } #endif else { cbuf_len = i; cbuf_off = 0; #ifdef CHARSET_EBCDIC ebcdic2ascii(cbuf, cbuf, i); #endif } write_ssl = 1; read_tty = 0; } } ret = 0; shut: if (in_init) print_stuff(bio_c_out, con, full_log); SSL_shutdown(con); SHUTDOWN(SSL_get_fd(con)); end: if (con != NULL) { if (prexit != 0) print_stuff(bio_c_out, con, 1); SSL_free(con); } #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) if (next_proto.data) OPENSSL_free(next_proto.data); #endif if (ctx != NULL) SSL_CTX_free(ctx); if (cert) X509_free(cert); if (crls) sk_X509_CRL_pop_free(crls, X509_CRL_free); if (key) EVP_PKEY_free(key); if (chain) sk_X509_pop_free(chain, X509_free); if (pass) OPENSSL_free(pass); #ifndef OPENSSL_NO_SRP OPENSSL_free(srp_arg.srppassin); #endif if (vpm) X509_VERIFY_PARAM_free(vpm); ssl_excert_free(exc); if (ssl_args) sk_OPENSSL_STRING_free(ssl_args); if (cctx) SSL_CONF_CTX_free(cctx); #ifndef OPENSSL_NO_JPAKE if (jpake_secret && psk_key) OPENSSL_free(psk_key); #endif if (cbuf != NULL) { OPENSSL_cleanse(cbuf, BUFSIZZ); OPENSSL_free(cbuf); } if (sbuf != NULL) { OPENSSL_cleanse(sbuf, BUFSIZZ); OPENSSL_free(sbuf); } if (mbuf != NULL) { OPENSSL_cleanse(mbuf, BUFSIZZ); OPENSSL_free(mbuf); } release_engine(e); if (bio_c_out != NULL) { BIO_free(bio_c_out); bio_c_out = NULL; } if (bio_c_msg != NULL) { BIO_free(bio_c_msg); bio_c_msg = NULL; } + SSL_COMP_free_compression_methods(); apps_shutdown(); OPENSSL_EXIT(ret); } static void print_stuff(BIO *bio, SSL *s, int full) { X509 *peer = NULL; char *p; static const char *space = " "; char buf[BUFSIZ]; STACK_OF(X509) *sk; STACK_OF(X509_NAME) *sk2; const SSL_CIPHER *c; X509_NAME *xn; int j, i; #ifndef OPENSSL_NO_COMP const COMP_METHOD *comp, *expansion; #endif unsigned char *exportedkeymat; if (full) { int got_a_chain = 0; sk = SSL_get_peer_cert_chain(s); if (sk != NULL) { got_a_chain = 1; /* we don't have it for SSL2 (yet) */ BIO_printf(bio, "---\nCertificate chain\n"); for (i = 0; i < sk_X509_num(sk); i++) { X509_NAME_oneline(X509_get_subject_name(sk_X509_value(sk, i)), buf, sizeof buf); BIO_printf(bio, "%2d s:%s\n", i, buf); X509_NAME_oneline(X509_get_issuer_name(sk_X509_value(sk, i)), buf, sizeof buf); BIO_printf(bio, " i:%s\n", buf); if (c_showcerts) PEM_write_bio_X509(bio, sk_X509_value(sk, i)); } } BIO_printf(bio, "---\n"); peer = SSL_get_peer_certificate(s); if (peer != NULL) { BIO_printf(bio, "Server certificate\n"); /* Redundant if we showed the whole chain */ if (!(c_showcerts && got_a_chain)) PEM_write_bio_X509(bio, peer); X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof buf); BIO_printf(bio, "subject=%s\n", buf); X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof buf); BIO_printf(bio, "issuer=%s\n", buf); } else BIO_printf(bio, "no peer certificate available\n"); sk2 = SSL_get_client_CA_list(s); if ((sk2 != NULL) && (sk_X509_NAME_num(sk2) > 0)) { BIO_printf(bio, "---\nAcceptable client certificate CA names\n"); for (i = 0; i < sk_X509_NAME_num(sk2); i++) { xn = sk_X509_NAME_value(sk2, i); X509_NAME_oneline(xn, buf, sizeof(buf)); BIO_write(bio, buf, strlen(buf)); BIO_write(bio, "\n", 1); } } else { BIO_printf(bio, "---\nNo client certificate CA names sent\n"); } p = SSL_get_shared_ciphers(s, buf, sizeof buf); if (p != NULL) { /* * This works only for SSL 2. In later protocol versions, the * client does not know what other ciphers (in addition to the * one to be used in the current connection) the server supports. */ BIO_printf(bio, "---\nCiphers common between both SSL endpoints:\n"); j = i = 0; while (*p) { if (*p == ':') { BIO_write(bio, space, 15 - j % 25); i++; j = 0; BIO_write(bio, ((i % 3) ? " " : "\n"), 1); } else { BIO_write(bio, p, 1); j++; } p++; } BIO_write(bio, "\n", 1); } ssl_print_sigalgs(bio, s); ssl_print_tmp_key(bio, s); BIO_printf(bio, "---\nSSL handshake has read %ld bytes and written %ld bytes\n", BIO_number_read(SSL_get_rbio(s)), BIO_number_written(SSL_get_wbio(s))); } BIO_printf(bio, (SSL_cache_hit(s) ? "---\nReused, " : "---\nNew, ")); c = SSL_get_current_cipher(s); BIO_printf(bio, "%s, Cipher is %s\n", SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c)); if (peer != NULL) { EVP_PKEY *pktmp; pktmp = X509_get_pubkey(peer); BIO_printf(bio, "Server public key is %d bit\n", EVP_PKEY_bits(pktmp)); EVP_PKEY_free(pktmp); } BIO_printf(bio, "Secure Renegotiation IS%s supported\n", SSL_get_secure_renegotiation_support(s) ? "" : " NOT"); #ifndef OPENSSL_NO_COMP comp = SSL_get_current_compression(s); expansion = SSL_get_current_expansion(s); BIO_printf(bio, "Compression: %s\n", comp ? SSL_COMP_get_name(comp) : "NONE"); BIO_printf(bio, "Expansion: %s\n", expansion ? SSL_COMP_get_name(expansion) : "NONE"); #endif #ifdef SSL_DEBUG { /* Print out local port of connection: useful for debugging */ int sock; struct sockaddr_in ladd; socklen_t ladd_size = sizeof(ladd); sock = SSL_get_fd(s); getsockname(sock, (struct sockaddr *)&ladd, &ladd_size); BIO_printf(bio_c_out, "LOCAL PORT is %u\n", ntohs(ladd.sin_port)); } #endif #if !defined(OPENSSL_NO_TLSEXT) # if !defined(OPENSSL_NO_NEXTPROTONEG) if (next_proto.status != -1) { const unsigned char *proto; unsigned int proto_len; SSL_get0_next_proto_negotiated(s, &proto, &proto_len); BIO_printf(bio, "Next protocol: (%d) ", next_proto.status); BIO_write(bio, proto, proto_len); BIO_write(bio, "\n", 1); } # endif { const unsigned char *proto; unsigned int proto_len; SSL_get0_alpn_selected(s, &proto, &proto_len); if (proto_len > 0) { BIO_printf(bio, "ALPN protocol: "); BIO_write(bio, proto, proto_len); BIO_write(bio, "\n", 1); } else BIO_printf(bio, "No ALPN negotiated\n"); } #endif #ifndef OPENSSL_NO_SRTP { SRTP_PROTECTION_PROFILE *srtp_profile = SSL_get_selected_srtp_profile(s); if (srtp_profile) BIO_printf(bio, "SRTP Extension negotiated, profile=%s\n", srtp_profile->name); } #endif SSL_SESSION_print(bio, SSL_get_session(s)); if (keymatexportlabel != NULL) { BIO_printf(bio, "Keying material exporter:\n"); BIO_printf(bio, " Label: '%s'\n", keymatexportlabel); BIO_printf(bio, " Length: %i bytes\n", keymatexportlen); exportedkeymat = OPENSSL_malloc(keymatexportlen); if (exportedkeymat != NULL) { if (!SSL_export_keying_material(s, exportedkeymat, keymatexportlen, keymatexportlabel, strlen(keymatexportlabel), NULL, 0, 0)) { BIO_printf(bio, " Error\n"); } else { BIO_printf(bio, " Keying material: "); for (i = 0; i < keymatexportlen; i++) BIO_printf(bio, "%02X", exportedkeymat[i]); BIO_printf(bio, "\n"); } OPENSSL_free(exportedkeymat); } } BIO_printf(bio, "---\n"); if (peer != NULL) X509_free(peer); /* flush, or debugging output gets mixed with http response */ (void)BIO_flush(bio); } #ifndef OPENSSL_NO_TLSEXT static int ocsp_resp_cb(SSL *s, void *arg) { const unsigned char *p; int len; OCSP_RESPONSE *rsp; len = SSL_get_tlsext_status_ocsp_resp(s, &p); BIO_puts(arg, "OCSP response: "); if (!p) { BIO_puts(arg, "no response sent\n"); return 1; } rsp = d2i_OCSP_RESPONSE(NULL, &p, len); if (!rsp) { BIO_puts(arg, "response parse error\n"); BIO_dump_indent(arg, (char *)p, len, 4); return 0; } BIO_puts(arg, "\n======================================\n"); OCSP_RESPONSE_print(arg, rsp, 0); BIO_puts(arg, "======================================\n"); OCSP_RESPONSE_free(rsp); return 1; } #endif Index: vendor-crypto/openssl/dist/apps/s_server.c =================================================================== --- vendor-crypto/openssl/dist/apps/s_server.c (revision 318896) +++ vendor-crypto/openssl/dist/apps/s_server.c (revision 318897) @@ -1,3518 +1,3519 @@ /* apps/s_server.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ /* ==================================================================== * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ /* ==================================================================== * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. * ECC cipher suite support in OpenSSL originally developed by * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. */ /* ==================================================================== * Copyright 2005 Nokia. All rights reserved. * * The portions of the attached software ("Contribution") is developed by * Nokia Corporation and is licensed pursuant to the OpenSSL open source * license. * * The Contribution, originally written by Mika Kousa and Pasi Eronen of * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites * support (see RFC 4279) to OpenSSL. * * No patent licenses or other rights except those expressly stated in * the OpenSSL open source license shall be deemed granted or received * expressly, by implication, estoppel, or otherwise. * * No assurances are provided by Nokia that the Contribution does not * infringe the patent or other intellectual property rights of any third * party or that the license provides you with all the necessary rights * to make use of the Contribution. * * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR * OTHERWISE. */ /* * Until the key-gen callbacks are modified to use newer prototypes, we allow * deprecated functions for openssl-internal code */ #ifdef OPENSSL_NO_DEPRECATED # undef OPENSSL_NO_DEPRECATED #endif #include #include #include #include #include #include #ifdef OPENSSL_NO_STDIO # define APPS_WIN16 #endif /* conflicts with winsock2 stuff on netware */ #if !defined(OPENSSL_SYS_NETWARE) # include #endif /* * With IPv6, it looks like Digital has mixed up the proper order of * recursive header file inclusion, resulting in the compiler complaining * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is * needed to have fileno() declared correctly... So let's define u_int */ #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT) # define __U_INT typedef unsigned int u_int; #endif #include #include #define USE_SOCKETS #include "apps.h" #include #include #include #include #include #include #ifndef OPENSSL_NO_DH # include #endif #ifndef OPENSSL_NO_RSA # include #endif #ifndef OPENSSL_NO_SRP # include #endif #include "s_apps.h" #include "timeouts.h" #if (defined(OPENSSL_SYS_VMS) && __VMS_VER < 70000000) /* FIONBIO used as a switch to enable ioctl, and that isn't in VMS < 7.0 */ # undef FIONBIO #endif #if defined(OPENSSL_SYS_BEOS_R5) # include #endif #ifndef OPENSSL_NO_RSA static RSA MS_CALLBACK *tmp_rsa_cb(SSL *s, int is_export, int keylength); #endif static int sv_body(char *hostname, int s, int stype, unsigned char *context); static int www_body(char *hostname, int s, int stype, unsigned char *context); static int rev_body(char *hostname, int s, int stype, unsigned char *context); static void close_accept_socket(void); static void sv_usage(void); static int init_ssl_connection(SSL *s); static void print_stats(BIO *bp, SSL_CTX *ctx); static int generate_session_id(const SSL *ssl, unsigned char *id, unsigned int *id_len); static void init_session_cache_ctx(SSL_CTX *sctx); static void free_sessions(void); #ifndef OPENSSL_NO_DH static DH *load_dh_param(const char *dhfile); static DH *get_dh2048(void); #endif #ifdef MONOLITH static void s_server_init(void); #endif #ifndef OPENSSL_NO_DH static unsigned char dh2048_p[] = { 0xF6,0x42,0x57,0xB7,0x08,0x7F,0x08,0x17,0x72,0xA2,0xBA,0xD6, 0xA9,0x42,0xF3,0x05,0xE8,0xF9,0x53,0x11,0x39,0x4F,0xB6,0xF1, 0x6E,0xB9,0x4B,0x38,0x20,0xDA,0x01,0xA7,0x56,0xA3,0x14,0xE9, 0x8F,0x40,0x55,0xF3,0xD0,0x07,0xC6,0xCB,0x43,0xA9,0x94,0xAD, 0xF7,0x4C,0x64,0x86,0x49,0xF8,0x0C,0x83,0xBD,0x65,0xE9,0x17, 0xD4,0xA1,0xD3,0x50,0xF8,0xF5,0x59,0x5F,0xDC,0x76,0x52,0x4F, 0x3D,0x3D,0x8D,0xDB,0xCE,0x99,0xE1,0x57,0x92,0x59,0xCD,0xFD, 0xB8,0xAE,0x74,0x4F,0xC5,0xFC,0x76,0xBC,0x83,0xC5,0x47,0x30, 0x61,0xCE,0x7C,0xC9,0x66,0xFF,0x15,0xF9,0xBB,0xFD,0x91,0x5E, 0xC7,0x01,0xAA,0xD3,0x5B,0x9E,0x8D,0xA0,0xA5,0x72,0x3A,0xD4, 0x1A,0xF0,0xBF,0x46,0x00,0x58,0x2B,0xE5,0xF4,0x88,0xFD,0x58, 0x4E,0x49,0xDB,0xCD,0x20,0xB4,0x9D,0xE4,0x91,0x07,0x36,0x6B, 0x33,0x6C,0x38,0x0D,0x45,0x1D,0x0F,0x7C,0x88,0xB3,0x1C,0x7C, 0x5B,0x2D,0x8E,0xF6,0xF3,0xC9,0x23,0xC0,0x43,0xF0,0xA5,0x5B, 0x18,0x8D,0x8E,0xBB,0x55,0x8C,0xB8,0x5D,0x38,0xD3,0x34,0xFD, 0x7C,0x17,0x57,0x43,0xA3,0x1D,0x18,0x6C,0xDE,0x33,0x21,0x2C, 0xB5,0x2A,0xFF,0x3C,0xE1,0xB1,0x29,0x40,0x18,0x11,0x8D,0x7C, 0x84,0xA7,0x0A,0x72,0xD6,0x86,0xC4,0x03,0x19,0xC8,0x07,0x29, 0x7A,0xCA,0x95,0x0C,0xD9,0x96,0x9F,0xAB,0xD0,0x0A,0x50,0x9B, 0x02,0x46,0xD3,0x08,0x3D,0x66,0xA4,0x5D,0x41,0x9F,0x9C,0x7C, 0xBD,0x89,0x4B,0x22,0x19,0x26,0xBA,0xAB,0xA2,0x5E,0xC3,0x55, 0xE9,0x32,0x0B,0x3B, }; static unsigned char dh2048_g[] = { 0x02, }; DH *get_dh2048() { DH *dh; if ((dh = DH_new()) == NULL) return NULL; dh->p=BN_bin2bn(dh2048_p, sizeof(dh2048_p), NULL); dh->g=BN_bin2bn(dh2048_g, sizeof(dh2048_g), NULL); if (dh->p == NULL || dh->g == NULL) { DH_free(dh); return NULL; } return dh; } #endif /* static int load_CA(SSL_CTX *ctx, char *file);*/ #undef BUFSIZZ #define BUFSIZZ 16*1024 static int bufsize = BUFSIZZ; static int accept_socket = -1; #define TEST_CERT "server.pem" #ifndef OPENSSL_NO_TLSEXT # define TEST_CERT2 "server2.pem" #endif #undef PROG #define PROG s_server_main extern int verify_depth, verify_return_error, verify_quiet; static int s_server_verify = SSL_VERIFY_NONE; static int s_server_session_id_context = 1; /* anything will do */ static const char *s_cert_file = TEST_CERT, *s_key_file = NULL, *s_chain_file = NULL; #ifndef OPENSSL_NO_TLSEXT static const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL; #endif static char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL; #ifdef FIONBIO static int s_nbio = 0; #endif static int s_nbio_test = 0; int s_crlf = 0; static SSL_CTX *ctx = NULL; #ifndef OPENSSL_NO_TLSEXT static SSL_CTX *ctx2 = NULL; #endif static int www = 0; static BIO *bio_s_out = NULL; static BIO *bio_s_msg = NULL; static int s_debug = 0; #ifndef OPENSSL_NO_TLSEXT static int s_tlsextdebug = 0; static int s_tlsextstatus = 0; static int cert_status_cb(SSL *s, void *arg); #endif static int no_resume_ephemeral = 0; static int s_msg = 0; static int s_quiet = 0; static int s_ign_eof = 0; static int s_brief = 0; static char *keymatexportlabel = NULL; static int keymatexportlen = 20; static int hack = 0; static char *engine_id = NULL; static const char *session_id_prefix = NULL; static int enable_timeouts = 0; static long socket_mtu; #ifndef OPENSSL_NO_DTLS1 static int cert_chain = 0; #endif #ifndef OPENSSL_NO_TLSEXT static BIO *serverinfo_in = NULL; static const char *s_serverinfo_file = NULL; #endif #ifndef OPENSSL_NO_PSK static char *psk_identity = "Client_identity"; char *psk_key = NULL; /* by default PSK is not used */ static unsigned int psk_server_cb(SSL *ssl, const char *identity, unsigned char *psk, unsigned int max_psk_len) { long key_len = 0; unsigned char *key; if (s_debug) BIO_printf(bio_s_out, "psk_server_cb\n"); if (!identity) { BIO_printf(bio_err, "Error: client did not send PSK identity\n"); goto out_err; } if (s_debug) BIO_printf(bio_s_out, "identity_len=%d identity=%s\n", (int)strlen(identity), identity); /* here we could lookup the given identity e.g. from a database */ if (strcmp(identity, psk_identity) != 0) { BIO_printf(bio_s_out, "PSK error: client identity not found" " (got '%s' expected '%s')\n", identity, psk_identity); goto out_err; } if (s_debug) BIO_printf(bio_s_out, "PSK client identity found\n"); /* convert the PSK key to binary */ key = string_to_hex(psk_key, &key_len); if (key == NULL) { BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n", psk_key); return 0; } if (key_len > (int)max_psk_len) { BIO_printf(bio_err, "psk buffer of callback is too small (%d) for key (%ld)\n", max_psk_len, key_len); OPENSSL_free(key); return 0; } memcpy(psk, key, key_len); OPENSSL_free(key); if (s_debug) BIO_printf(bio_s_out, "fetched PSK len=%ld\n", key_len); return key_len; out_err: if (s_debug) BIO_printf(bio_err, "Error in PSK server callback\n"); return 0; } #endif #ifndef OPENSSL_NO_SRP /* This is a context that we pass to callbacks */ typedef struct srpsrvparm_st { char *login; SRP_VBASE *vb; SRP_user_pwd *user; } srpsrvparm; /* * This callback pretends to require some asynchronous logic in order to * obtain a verifier. When the callback is called for a new connection we * return with a negative value. This will provoke the accept etc to return * with an LOOKUP_X509. The main logic of the reinvokes the suspended call * (which would normally occur after a worker has finished) and we set the * user parameters. */ static int MS_CALLBACK ssl_srp_server_param_cb(SSL *s, int *ad, void *arg) { srpsrvparm *p = (srpsrvparm *) arg; int ret = SSL3_AL_FATAL; if (p->login == NULL && p->user == NULL) { p->login = SSL_get_srp_username(s); BIO_printf(bio_err, "SRP username = \"%s\"\n", p->login); return (-1); } if (p->user == NULL) { BIO_printf(bio_err, "User %s doesn't exist\n", p->login); goto err; } if (SSL_set_srp_server_param (s, p->user->N, p->user->g, p->user->s, p->user->v, p->user->info) < 0) { *ad = SSL_AD_INTERNAL_ERROR; goto err; } BIO_printf(bio_err, "SRP parameters set: username = \"%s\" info=\"%s\" \n", p->login, p->user->info); ret = SSL_ERROR_NONE; err: SRP_user_pwd_free(p->user); p->user = NULL; p->login = NULL; return ret; } #endif #ifdef MONOLITH static void s_server_init(void) { accept_socket = -1; s_server_verify = SSL_VERIFY_NONE; s_dcert_file = NULL; s_dkey_file = NULL; s_dchain_file = NULL; s_cert_file = TEST_CERT; s_key_file = NULL; s_chain_file = NULL; # ifndef OPENSSL_NO_TLSEXT s_cert_file2 = TEST_CERT2; s_key_file2 = NULL; ctx2 = NULL; # endif # ifdef FIONBIO s_nbio = 0; # endif s_nbio_test = 0; ctx = NULL; www = 0; bio_s_out = NULL; s_debug = 0; s_msg = 0; s_quiet = 0; s_brief = 0; hack = 0; engine_id = NULL; } #endif static void sv_usage(void) { BIO_printf(bio_err, "usage: s_server [args ...]\n"); BIO_printf(bio_err, "\n"); BIO_printf(bio_err, " -accept arg - port to accept on (default is %d)\n", PORT); BIO_printf(bio_err, " -verify_hostname host - check peer certificate matches \"host\"\n"); BIO_printf(bio_err, " -verify_email email - check peer certificate matches \"email\"\n"); BIO_printf(bio_err, " -verify_ip ipaddr - check peer certificate matches \"ipaddr\"\n"); BIO_printf(bio_err, " -context arg - set session ID context\n"); BIO_printf(bio_err, " -verify arg - turn on peer certificate verification\n"); BIO_printf(bio_err, " -Verify arg - turn on peer certificate verification, must have a cert.\n"); BIO_printf(bio_err, " -verify_return_error - return verification errors\n"); BIO_printf(bio_err, " -cert arg - certificate file to use\n"); BIO_printf(bio_err, " (default is %s)\n", TEST_CERT); #ifndef OPENSSL_NO_TLSEXT BIO_printf(bio_err, " -serverinfo arg - PEM serverinfo file for certificate\n"); BIO_printf(bio_err, " -auth - send and receive RFC 5878 TLS auth extensions and supplemental data\n"); BIO_printf(bio_err, " -auth_require_reneg - Do not send TLS auth extensions until renegotiation\n"); #endif BIO_printf(bio_err, " -no_resumption_on_reneg - set SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION flag\n"); BIO_printf(bio_err, " -crl_check - check the peer certificate has not been revoked by its CA.\n" " The CRL(s) are appended to the certificate file\n"); BIO_printf(bio_err, " -crl_check_all - check the peer certificate has not been revoked by its CA\n" " or any other CRL in the CA chain. CRL(s) are appened to the\n" " the certificate file.\n"); BIO_printf(bio_err, " -certform arg - certificate format (PEM or DER) PEM default\n"); BIO_printf(bio_err, " -key arg - Private Key file to use, in cert file if\n"); BIO_printf(bio_err, " not specified (default is %s)\n", TEST_CERT); BIO_printf(bio_err, " -keyform arg - key format (PEM, DER or ENGINE) PEM default\n"); BIO_printf(bio_err, " -pass arg - private key file pass phrase source\n"); BIO_printf(bio_err, " -dcert arg - second certificate file to use (usually for DSA)\n"); BIO_printf(bio_err, " -dcertform x - second certificate format (PEM or DER) PEM default\n"); BIO_printf(bio_err, " -dkey arg - second private key file to use (usually for DSA)\n"); BIO_printf(bio_err, " -dkeyform arg - second key format (PEM, DER or ENGINE) PEM default\n"); BIO_printf(bio_err, " -dpass arg - second private key file pass phrase source\n"); BIO_printf(bio_err, " -dhparam arg - DH parameter file to use, in cert file if not specified\n"); BIO_printf(bio_err, " or a default set of parameters is used\n"); #ifndef OPENSSL_NO_ECDH BIO_printf(bio_err, " -named_curve arg - Elliptic curve name to use for ephemeral ECDH keys.\n" " Use \"openssl ecparam -list_curves\" for all names\n" " (default is nistp256).\n"); #endif #ifdef FIONBIO BIO_printf(bio_err, " -nbio - Run with non-blocking IO\n"); #endif BIO_printf(bio_err, " -nbio_test - test with the non-blocking test bio\n"); BIO_printf(bio_err, " -crlf - convert LF from terminal into CRLF\n"); BIO_printf(bio_err, " -debug - Print more output\n"); BIO_printf(bio_err, " -msg - Show protocol messages\n"); BIO_printf(bio_err, " -state - Print the SSL states\n"); BIO_printf(bio_err, " -CApath arg - PEM format directory of CA's\n"); BIO_printf(bio_err, " -CAfile arg - PEM format file of CA's\n"); BIO_printf(bio_err, " -no_alt_chains - only ever use the first certificate chain found\n"); BIO_printf(bio_err, " -nocert - Don't use any certificates (Anon-DH)\n"); BIO_printf(bio_err, " -cipher arg - play with 'openssl ciphers' to see what goes here\n"); BIO_printf(bio_err, " -serverpref - Use server's cipher preferences\n"); BIO_printf(bio_err, " -quiet - No server output\n"); BIO_printf(bio_err, " -no_tmp_rsa - Do not generate a tmp RSA key\n"); #ifndef OPENSSL_NO_PSK BIO_printf(bio_err, " -psk_hint arg - PSK identity hint to use\n"); BIO_printf(bio_err, " -psk arg - PSK in hex (without 0x)\n"); # ifndef OPENSSL_NO_JPAKE BIO_printf(bio_err, " -jpake arg - JPAKE secret to use\n"); # endif #endif #ifndef OPENSSL_NO_SRP BIO_printf(bio_err, " -srpvfile file - The verifier file for SRP\n"); BIO_printf(bio_err, " -srpuserseed string - A seed string for a default user salt.\n"); #endif BIO_printf(bio_err, " -ssl2 - Just talk SSLv2\n"); #ifndef OPENSSL_NO_SSL3_METHOD BIO_printf(bio_err, " -ssl3 - Just talk SSLv3\n"); #endif BIO_printf(bio_err, " -tls1_2 - Just talk TLSv1.2\n"); BIO_printf(bio_err, " -tls1_1 - Just talk TLSv1.1\n"); BIO_printf(bio_err, " -tls1 - Just talk TLSv1\n"); BIO_printf(bio_err, " -dtls1 - Just talk DTLSv1\n"); BIO_printf(bio_err, " -dtls1_2 - Just talk DTLSv1.2\n"); BIO_printf(bio_err, " -timeout - Enable timeouts\n"); BIO_printf(bio_err, " -mtu - Set link layer MTU\n"); BIO_printf(bio_err, " -chain - Read a certificate chain\n"); BIO_printf(bio_err, " -no_ssl2 - Just disable SSLv2\n"); BIO_printf(bio_err, " -no_ssl3 - Just disable SSLv3\n"); BIO_printf(bio_err, " -no_tls1 - Just disable TLSv1\n"); BIO_printf(bio_err, " -no_tls1_1 - Just disable TLSv1.1\n"); BIO_printf(bio_err, " -no_tls1_2 - Just disable TLSv1.2\n"); #ifndef OPENSSL_NO_DH BIO_printf(bio_err, " -no_dhe - Disable ephemeral DH\n"); #endif #ifndef OPENSSL_NO_ECDH BIO_printf(bio_err, " -no_ecdhe - Disable ephemeral ECDH\n"); #endif BIO_printf(bio_err, " -bugs - Turn on SSL bug compatibility\n"); BIO_printf(bio_err, " -hack - workaround for early Netscape code\n"); BIO_printf(bio_err, " -www - Respond to a 'GET /' with a status page\n"); BIO_printf(bio_err, " -WWW - Respond to a 'GET / HTTP/1.0' with file ./\n"); BIO_printf(bio_err, " -HTTP - Respond to a 'GET / HTTP/1.0' with file ./\n"); BIO_printf(bio_err, " with the assumption it contains a complete HTTP response.\n"); #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err, " -engine id - Initialise and use the specified engine\n"); #endif BIO_printf(bio_err, " -id_prefix arg - Generate SSL/TLS session IDs prefixed by 'arg'\n"); BIO_printf(bio_err, " -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR); #ifndef OPENSSL_NO_TLSEXT BIO_printf(bio_err, " -servername host - servername for HostName TLS extension\n"); BIO_printf(bio_err, " -servername_fatal - on mismatch send fatal alert (default warning alert)\n"); BIO_printf(bio_err, " -cert2 arg - certificate file to use for servername\n"); BIO_printf(bio_err, " (default is %s)\n", TEST_CERT2); BIO_printf(bio_err, " -key2 arg - Private Key file to use for servername, in cert file if\n"); BIO_printf(bio_err, " not specified (default is %s)\n", TEST_CERT2); BIO_printf(bio_err, " -tlsextdebug - hex dump of all TLS extensions received\n"); BIO_printf(bio_err, " -no_ticket - disable use of RFC4507bis session tickets\n"); BIO_printf(bio_err, " -legacy_renegotiation - enable use of legacy renegotiation (dangerous)\n"); BIO_printf(bio_err, " -sigalgs arg - Signature algorithms to support (colon-separated list)\n"); BIO_printf(bio_err, " -client_sigalgs arg - Signature algorithms to support for client \n"); BIO_printf(bio_err, " certificate authentication (colon-separated list)\n"); # ifndef OPENSSL_NO_NEXTPROTONEG BIO_printf(bio_err, " -nextprotoneg arg - set the advertised protocols for the NPN extension (comma-separated list)\n"); # endif # ifndef OPENSSL_NO_SRTP BIO_printf(bio_err, " -use_srtp profiles - Offer SRTP key management with a colon-separated profile list\n"); # endif BIO_printf(bio_err, " -alpn arg - set the advertised protocols for the ALPN extension (comma-separated list)\n"); #endif BIO_printf(bio_err, " -keymatexport label - Export keying material using label\n"); BIO_printf(bio_err, " -keymatexportlen len - Export len bytes of keying material (default 20)\n"); BIO_printf(bio_err, " -status - respond to certificate status requests\n"); BIO_printf(bio_err, " -status_verbose - enable status request verbose printout\n"); BIO_printf(bio_err, " -status_timeout n - status request responder timeout\n"); BIO_printf(bio_err, " -status_url URL - status request fallback URL\n"); } static int local_argc = 0; static char **local_argv; #ifdef CHARSET_EBCDIC static int ebcdic_new(BIO *bi); static int ebcdic_free(BIO *a); static int ebcdic_read(BIO *b, char *out, int outl); static int ebcdic_write(BIO *b, const char *in, int inl); static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr); static int ebcdic_gets(BIO *bp, char *buf, int size); static int ebcdic_puts(BIO *bp, const char *str); # define BIO_TYPE_EBCDIC_FILTER (18|0x0200) static BIO_METHOD methods_ebcdic = { BIO_TYPE_EBCDIC_FILTER, "EBCDIC/ASCII filter", ebcdic_write, ebcdic_read, ebcdic_puts, ebcdic_gets, ebcdic_ctrl, ebcdic_new, ebcdic_free, }; typedef struct { size_t alloced; char buff[1]; } EBCDIC_OUTBUFF; BIO_METHOD *BIO_f_ebcdic_filter() { return (&methods_ebcdic); } static int ebcdic_new(BIO *bi) { EBCDIC_OUTBUFF *wbuf; wbuf = (EBCDIC_OUTBUFF *) OPENSSL_malloc(sizeof(EBCDIC_OUTBUFF) + 1024); if (!wbuf) return 0; wbuf->alloced = 1024; wbuf->buff[0] = '\0'; bi->ptr = (char *)wbuf; bi->init = 1; bi->flags = 0; return (1); } static int ebcdic_free(BIO *a) { if (a == NULL) return (0); if (a->ptr != NULL) OPENSSL_free(a->ptr); a->ptr = NULL; a->init = 0; a->flags = 0; return (1); } static int ebcdic_read(BIO *b, char *out, int outl) { int ret = 0; if (out == NULL || outl == 0) return (0); if (b->next_bio == NULL) return (0); ret = BIO_read(b->next_bio, out, outl); if (ret > 0) ascii2ebcdic(out, out, ret); return (ret); } static int ebcdic_write(BIO *b, const char *in, int inl) { EBCDIC_OUTBUFF *wbuf; int ret = 0; int num; unsigned char n; if ((in == NULL) || (inl <= 0)) return (0); if (b->next_bio == NULL) return (0); wbuf = (EBCDIC_OUTBUFF *) b->ptr; if (inl > (num = wbuf->alloced)) { num = num + num; /* double the size */ if (num < inl) num = inl; wbuf = (EBCDIC_OUTBUFF *) OPENSSL_malloc(sizeof(EBCDIC_OUTBUFF) + num); if (!wbuf) return 0; OPENSSL_free(b->ptr); wbuf->alloced = num; wbuf->buff[0] = '\0'; b->ptr = (char *)wbuf; } ebcdic2ascii(wbuf->buff, in, inl); ret = BIO_write(b->next_bio, wbuf->buff, inl); return (ret); } static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr) { long ret; if (b->next_bio == NULL) return (0); switch (cmd) { case BIO_CTRL_DUP: ret = 0L; break; default: ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; } return (ret); } static int ebcdic_gets(BIO *bp, char *buf, int size) { int i, ret = 0; if (bp->next_bio == NULL) return (0); /* return(BIO_gets(bp->next_bio,buf,size));*/ for (i = 0; i < size - 1; ++i) { ret = ebcdic_read(bp, &buf[i], 1); if (ret <= 0) break; else if (buf[i] == '\n') { ++i; break; } } if (i < size) buf[i] = '\0'; return (ret < 0 && i == 0) ? ret : i; } static int ebcdic_puts(BIO *bp, const char *str) { if (bp->next_bio == NULL) return (0); return ebcdic_write(bp, str, strlen(str)); } #endif #ifndef OPENSSL_NO_TLSEXT /* This is a context that we pass to callbacks */ typedef struct tlsextctx_st { char *servername; BIO *biodebug; int extension_error; } tlsextctx; static int MS_CALLBACK ssl_servername_cb(SSL *s, int *ad, void *arg) { tlsextctx *p = (tlsextctx *) arg; const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name); if (servername && p->biodebug) BIO_printf(p->biodebug, "Hostname in TLS extension: \"%s\"\n", servername); if (!p->servername) return SSL_TLSEXT_ERR_NOACK; if (servername) { if (strcasecmp(servername, p->servername)) return p->extension_error; if (ctx2) { BIO_printf(p->biodebug, "Switching server context.\n"); SSL_set_SSL_CTX(s, ctx2); } } return SSL_TLSEXT_ERR_OK; } /* Structure passed to cert status callback */ typedef struct tlsextstatusctx_st { /* Default responder to use */ char *host, *path, *port; int use_ssl; int timeout; BIO *err; int verbose; } tlsextstatusctx; static tlsextstatusctx tlscstatp = { NULL, NULL, NULL, 0, -1, NULL, 0 }; /* * Certificate Status callback. This is called when a client includes a * certificate status request extension. This is a simplified version. It * examines certificates each time and makes one OCSP responder query for * each request. A full version would store details such as the OCSP * certificate IDs and minimise the number of OCSP responses by caching them * until they were considered "expired". */ static int cert_status_cb(SSL *s, void *arg) { tlsextstatusctx *srctx = arg; BIO *err = srctx->err; char *host, *port, *path; int use_ssl; unsigned char *rspder = NULL; int rspderlen; STACK_OF(OPENSSL_STRING) *aia = NULL; X509 *x = NULL; X509_STORE_CTX inctx; X509_OBJECT obj; OCSP_REQUEST *req = NULL; OCSP_RESPONSE *resp = NULL; OCSP_CERTID *id = NULL; STACK_OF(X509_EXTENSION) *exts; int ret = SSL_TLSEXT_ERR_NOACK; int i; # if 0 STACK_OF(OCSP_RESPID) *ids; SSL_get_tlsext_status_ids(s, &ids); BIO_printf(err, "cert_status: received %d ids\n", sk_OCSP_RESPID_num(ids)); # endif if (srctx->verbose) BIO_puts(err, "cert_status: callback called\n"); /* Build up OCSP query from server certificate */ x = SSL_get_certificate(s); aia = X509_get1_ocsp(x); if (aia) { if (!OCSP_parse_url(sk_OPENSSL_STRING_value(aia, 0), &host, &port, &path, &use_ssl)) { BIO_puts(err, "cert_status: can't parse AIA URL\n"); goto err; } if (srctx->verbose) BIO_printf(err, "cert_status: AIA URL: %s\n", sk_OPENSSL_STRING_value(aia, 0)); } else { if (!srctx->host) { BIO_puts(srctx->err, "cert_status: no AIA and no default responder URL\n"); goto done; } host = srctx->host; path = srctx->path; port = srctx->port; use_ssl = srctx->use_ssl; } if (!X509_STORE_CTX_init(&inctx, SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)), NULL, NULL)) goto err; if (X509_STORE_get_by_subject(&inctx, X509_LU_X509, X509_get_issuer_name(x), &obj) <= 0) { BIO_puts(err, "cert_status: Can't retrieve issuer certificate.\n"); X509_STORE_CTX_cleanup(&inctx); goto done; } req = OCSP_REQUEST_new(); if (!req) goto err; id = OCSP_cert_to_id(NULL, x, obj.data.x509); X509_free(obj.data.x509); X509_STORE_CTX_cleanup(&inctx); if (!id) goto err; if (!OCSP_request_add0_id(req, id)) goto err; id = NULL; /* Add any extensions to the request */ SSL_get_tlsext_status_exts(s, &exts); for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) { X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i); if (!OCSP_REQUEST_add_ext(req, ext, -1)) goto err; } resp = process_responder(err, req, host, path, port, use_ssl, NULL, srctx->timeout); if (!resp) { BIO_puts(err, "cert_status: error querying responder\n"); goto done; } rspderlen = i2d_OCSP_RESPONSE(resp, &rspder); if (rspderlen <= 0) goto err; SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen); if (srctx->verbose) { BIO_puts(err, "cert_status: ocsp response sent:\n"); OCSP_RESPONSE_print(err, resp, 2); } ret = SSL_TLSEXT_ERR_OK; done: if (ret != SSL_TLSEXT_ERR_OK) ERR_print_errors(err); if (aia) { OPENSSL_free(host); OPENSSL_free(path); OPENSSL_free(port); X509_email_free(aia); } if (id) OCSP_CERTID_free(id); if (req) OCSP_REQUEST_free(req); if (resp) OCSP_RESPONSE_free(resp); return ret; err: ret = SSL_TLSEXT_ERR_ALERT_FATAL; goto done; } # ifndef OPENSSL_NO_NEXTPROTONEG /* This is the context that we pass to next_proto_cb */ typedef struct tlsextnextprotoctx_st { unsigned char *data; unsigned int len; } tlsextnextprotoctx; static int next_proto_cb(SSL *s, const unsigned char **data, unsigned int *len, void *arg) { tlsextnextprotoctx *next_proto = arg; *data = next_proto->data; *len = next_proto->len; return SSL_TLSEXT_ERR_OK; } # endif /* ndef OPENSSL_NO_NEXTPROTONEG */ /* This the context that we pass to alpn_cb */ typedef struct tlsextalpnctx_st { unsigned char *data; unsigned short len; } tlsextalpnctx; static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg) { tlsextalpnctx *alpn_ctx = arg; if (!s_quiet) { /* We can assume that |in| is syntactically valid. */ unsigned i; BIO_printf(bio_s_out, "ALPN protocols advertised by the client: "); for (i = 0; i < inlen;) { if (i) BIO_write(bio_s_out, ", ", 2); BIO_write(bio_s_out, &in[i + 1], in[i]); i += in[i] + 1; } BIO_write(bio_s_out, "\n", 1); } if (SSL_select_next_proto ((unsigned char **)out, outlen, alpn_ctx->data, alpn_ctx->len, in, inlen) != OPENSSL_NPN_NEGOTIATED) { return SSL_TLSEXT_ERR_NOACK; } if (!s_quiet) { BIO_printf(bio_s_out, "ALPN protocols selected: "); BIO_write(bio_s_out, *out, *outlen); BIO_write(bio_s_out, "\n", 1); } return SSL_TLSEXT_ERR_OK; } #endif /* ndef OPENSSL_NO_TLSEXT */ int MAIN(int, char **); #ifndef OPENSSL_NO_JPAKE static char *jpake_secret = NULL; # define no_jpake !jpake_secret #else # define no_jpake 1 #endif #ifndef OPENSSL_NO_SRP static srpsrvparm srp_callback_parm; #endif #ifndef OPENSSL_NO_SRTP static char *srtp_profiles = NULL; #endif int MAIN(int argc, char *argv[]) { X509_VERIFY_PARAM *vpm = NULL; int badarg = 0; short port = PORT; char *CApath = NULL, *CAfile = NULL; char *chCApath = NULL, *chCAfile = NULL; char *vfyCApath = NULL, *vfyCAfile = NULL; unsigned char *context = NULL; char *dhfile = NULL; int badop = 0; int ret = 1; int build_chain = 0; int no_tmp_rsa = 0, no_dhe = 0, no_ecdhe = 0, nocert = 0; int state = 0; const SSL_METHOD *meth = NULL; int socket_type = SOCK_STREAM; ENGINE *e = NULL; char *inrand = NULL; int s_cert_format = FORMAT_PEM, s_key_format = FORMAT_PEM; char *passarg = NULL, *pass = NULL; char *dpassarg = NULL, *dpass = NULL; int s_dcert_format = FORMAT_PEM, s_dkey_format = FORMAT_PEM; X509 *s_cert = NULL, *s_dcert = NULL; STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL; EVP_PKEY *s_key = NULL, *s_dkey = NULL; int no_cache = 0, ext_cache = 0; int rev = 0, naccept = -1; #ifndef OPENSSL_NO_TLSEXT EVP_PKEY *s_key2 = NULL; X509 *s_cert2 = NULL; tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING }; # ifndef OPENSSL_NO_NEXTPROTONEG const char *next_proto_neg_in = NULL; tlsextnextprotoctx next_proto = { NULL, 0 }; # endif const char *alpn_in = NULL; tlsextalpnctx alpn_ctx = { NULL, 0 }; #endif #ifndef OPENSSL_NO_PSK /* by default do not send a PSK identity hint */ static char *psk_identity_hint = NULL; #endif #ifndef OPENSSL_NO_SRP char *srpuserseed = NULL; char *srp_verifier_file = NULL; #endif SSL_EXCERT *exc = NULL; SSL_CONF_CTX *cctx = NULL; STACK_OF(OPENSSL_STRING) *ssl_args = NULL; char *crl_file = NULL; int crl_format = FORMAT_PEM; int crl_download = 0; STACK_OF(X509_CRL) *crls = NULL; int prot_opt = 0, no_prot_opt = 0; meth = SSLv23_server_method(); local_argc = argc; local_argv = argv; apps_startup(); #ifdef MONOLITH s_server_init(); #endif if (bio_err == NULL) bio_err = BIO_new_fp(stderr, BIO_NOCLOSE); if (!load_config(bio_err, NULL)) goto end; cctx = SSL_CONF_CTX_new(); if (!cctx) goto end; SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_SERVER); SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CMDLINE); verify_depth = 0; #ifdef FIONBIO s_nbio = 0; #endif s_nbio_test = 0; argc--; argv++; while (argc >= 1) { if ((strcmp(*argv, "-port") == 0) || (strcmp(*argv, "-accept") == 0)) { if (--argc < 1) goto bad; if (!extract_port(*(++argv), &port)) goto bad; } else if (strcmp(*argv, "-naccept") == 0) { if (--argc < 1) goto bad; naccept = atol(*(++argv)); if (naccept <= 0) { BIO_printf(bio_err, "bad accept value %s\n", *argv); goto bad; } } else if (strcmp(*argv, "-verify") == 0) { s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE; if (--argc < 1) goto bad; verify_depth = atoi(*(++argv)); if (!s_quiet) BIO_printf(bio_err, "verify depth is %d\n", verify_depth); } else if (strcmp(*argv, "-Verify") == 0) { s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE; if (--argc < 1) goto bad; verify_depth = atoi(*(++argv)); if (!s_quiet) BIO_printf(bio_err, "verify depth is %d, must return a certificate\n", verify_depth); } else if (strcmp(*argv, "-context") == 0) { if (--argc < 1) goto bad; context = (unsigned char *)*(++argv); } else if (strcmp(*argv, "-cert") == 0) { if (--argc < 1) goto bad; s_cert_file = *(++argv); } else if (strcmp(*argv, "-CRL") == 0) { if (--argc < 1) goto bad; crl_file = *(++argv); } else if (strcmp(*argv, "-crl_download") == 0) crl_download = 1; #ifndef OPENSSL_NO_TLSEXT else if (strcmp(*argv, "-serverinfo") == 0) { if (--argc < 1) goto bad; s_serverinfo_file = *(++argv); } #endif else if (strcmp(*argv, "-certform") == 0) { if (--argc < 1) goto bad; s_cert_format = str2fmt(*(++argv)); } else if (strcmp(*argv, "-key") == 0) { if (--argc < 1) goto bad; s_key_file = *(++argv); } else if (strcmp(*argv, "-keyform") == 0) { if (--argc < 1) goto bad; s_key_format = str2fmt(*(++argv)); } else if (strcmp(*argv, "-pass") == 0) { if (--argc < 1) goto bad; passarg = *(++argv); } else if (strcmp(*argv, "-cert_chain") == 0) { if (--argc < 1) goto bad; s_chain_file = *(++argv); } else if (strcmp(*argv, "-dhparam") == 0) { if (--argc < 1) goto bad; dhfile = *(++argv); } else if (strcmp(*argv, "-dcertform") == 0) { if (--argc < 1) goto bad; s_dcert_format = str2fmt(*(++argv)); } else if (strcmp(*argv, "-dcert") == 0) { if (--argc < 1) goto bad; s_dcert_file = *(++argv); } else if (strcmp(*argv, "-dkeyform") == 0) { if (--argc < 1) goto bad; s_dkey_format = str2fmt(*(++argv)); } else if (strcmp(*argv, "-dpass") == 0) { if (--argc < 1) goto bad; dpassarg = *(++argv); } else if (strcmp(*argv, "-dkey") == 0) { if (--argc < 1) goto bad; s_dkey_file = *(++argv); } else if (strcmp(*argv, "-dcert_chain") == 0) { if (--argc < 1) goto bad; s_dchain_file = *(++argv); } else if (strcmp(*argv, "-nocert") == 0) { nocert = 1; } else if (strcmp(*argv, "-CApath") == 0) { if (--argc < 1) goto bad; CApath = *(++argv); } else if (strcmp(*argv, "-chainCApath") == 0) { if (--argc < 1) goto bad; chCApath = *(++argv); } else if (strcmp(*argv, "-verifyCApath") == 0) { if (--argc < 1) goto bad; vfyCApath = *(++argv); } else if (strcmp(*argv, "-no_cache") == 0) no_cache = 1; else if (strcmp(*argv, "-ext_cache") == 0) ext_cache = 1; else if (strcmp(*argv, "-CRLform") == 0) { if (--argc < 1) goto bad; crl_format = str2fmt(*(++argv)); } else if (args_verify(&argv, &argc, &badarg, bio_err, &vpm)) { if (badarg) goto bad; continue; } else if (args_excert(&argv, &argc, &badarg, bio_err, &exc)) { if (badarg) goto bad; continue; } else if (args_ssl(&argv, &argc, cctx, &badarg, bio_err, &ssl_args, &no_prot_opt)) { if (badarg) goto bad; continue; } else if (strcmp(*argv, "-verify_return_error") == 0) verify_return_error = 1; else if (strcmp(*argv, "-verify_quiet") == 0) verify_quiet = 1; else if (strcmp(*argv, "-build_chain") == 0) build_chain = 1; else if (strcmp(*argv, "-CAfile") == 0) { if (--argc < 1) goto bad; CAfile = *(++argv); } else if (strcmp(*argv, "-chainCAfile") == 0) { if (--argc < 1) goto bad; chCAfile = *(++argv); } else if (strcmp(*argv, "-verifyCAfile") == 0) { if (--argc < 1) goto bad; vfyCAfile = *(++argv); } #ifdef FIONBIO else if (strcmp(*argv, "-nbio") == 0) { s_nbio = 1; } #endif else if (strcmp(*argv, "-nbio_test") == 0) { #ifdef FIONBIO s_nbio = 1; #endif s_nbio_test = 1; } else if (strcmp(*argv, "-ign_eof") == 0) s_ign_eof = 1; else if (strcmp(*argv, "-no_ign_eof") == 0) s_ign_eof = 0; else if (strcmp(*argv, "-debug") == 0) { s_debug = 1; } #ifndef OPENSSL_NO_TLSEXT else if (strcmp(*argv, "-tlsextdebug") == 0) s_tlsextdebug = 1; else if (strcmp(*argv, "-status") == 0) s_tlsextstatus = 1; else if (strcmp(*argv, "-status_verbose") == 0) { s_tlsextstatus = 1; tlscstatp.verbose = 1; } else if (!strcmp(*argv, "-status_timeout")) { s_tlsextstatus = 1; if (--argc < 1) goto bad; tlscstatp.timeout = atoi(*(++argv)); } else if (!strcmp(*argv, "-status_url")) { s_tlsextstatus = 1; if (--argc < 1) goto bad; if (!OCSP_parse_url(*(++argv), &tlscstatp.host, &tlscstatp.port, &tlscstatp.path, &tlscstatp.use_ssl)) { BIO_printf(bio_err, "Error parsing URL\n"); goto bad; } } #endif else if (strcmp(*argv, "-msg") == 0) { s_msg = 1; } else if (strcmp(*argv, "-msgfile") == 0) { if (--argc < 1) goto bad; bio_s_msg = BIO_new_file(*(++argv), "w"); } #ifndef OPENSSL_NO_SSL_TRACE else if (strcmp(*argv, "-trace") == 0) { s_msg = 2; } #endif else if (strcmp(*argv, "-hack") == 0) { hack = 1; } else if (strcmp(*argv, "-state") == 0) { state = 1; } else if (strcmp(*argv, "-crlf") == 0) { s_crlf = 1; } else if (strcmp(*argv, "-quiet") == 0) { s_quiet = 1; } else if (strcmp(*argv, "-brief") == 0) { s_quiet = 1; s_brief = 1; verify_quiet = 1; } else if (strcmp(*argv, "-no_tmp_rsa") == 0) { no_tmp_rsa = 1; } else if (strcmp(*argv, "-no_dhe") == 0) { no_dhe = 1; } else if (strcmp(*argv, "-no_ecdhe") == 0) { no_ecdhe = 1; } else if (strcmp(*argv, "-no_resume_ephemeral") == 0) { no_resume_ephemeral = 1; } #ifndef OPENSSL_NO_PSK else if (strcmp(*argv, "-psk_hint") == 0) { if (--argc < 1) goto bad; psk_identity_hint = *(++argv); } else if (strcmp(*argv, "-psk") == 0) { size_t i; if (--argc < 1) goto bad; psk_key = *(++argv); for (i = 0; i < strlen(psk_key); i++) { if (isxdigit((unsigned char)psk_key[i])) continue; BIO_printf(bio_err, "Not a hex number '%s'\n", *argv); goto bad; } } #endif #ifndef OPENSSL_NO_SRP else if (strcmp(*argv, "-srpvfile") == 0) { if (--argc < 1) goto bad; srp_verifier_file = *(++argv); meth = TLSv1_server_method(); } else if (strcmp(*argv, "-srpuserseed") == 0) { if (--argc < 1) goto bad; srpuserseed = *(++argv); meth = TLSv1_server_method(); } #endif else if (strcmp(*argv, "-rev") == 0) { rev = 1; } else if (strcmp(*argv, "-www") == 0) { www = 1; } else if (strcmp(*argv, "-WWW") == 0) { www = 2; } else if (strcmp(*argv, "-HTTP") == 0) { www = 3; } #ifndef OPENSSL_NO_SSL2 else if (strcmp(*argv, "-ssl2") == 0) { no_ecdhe = 1; meth = SSLv2_server_method(); prot_opt++; } #endif #ifndef OPENSSL_NO_SSL3_METHOD else if (strcmp(*argv, "-ssl3") == 0) { meth = SSLv3_server_method(); prot_opt++; } #endif #ifndef OPENSSL_NO_TLS1 else if (strcmp(*argv, "-tls1") == 0) { meth = TLSv1_server_method(); prot_opt++; } else if (strcmp(*argv, "-tls1_1") == 0) { meth = TLSv1_1_server_method(); prot_opt++; } else if (strcmp(*argv, "-tls1_2") == 0) { meth = TLSv1_2_server_method(); prot_opt++; } #endif #ifndef OPENSSL_NO_DTLS1 else if (strcmp(*argv, "-dtls") == 0) { meth = DTLS_server_method(); socket_type = SOCK_DGRAM; prot_opt++; } else if (strcmp(*argv, "-dtls1") == 0) { meth = DTLSv1_server_method(); socket_type = SOCK_DGRAM; prot_opt++; } else if (strcmp(*argv, "-dtls1_2") == 0) { meth = DTLSv1_2_server_method(); socket_type = SOCK_DGRAM; prot_opt++; } else if (strcmp(*argv, "-timeout") == 0) enable_timeouts = 1; else if (strcmp(*argv, "-mtu") == 0) { if (--argc < 1) goto bad; socket_mtu = atol(*(++argv)); } else if (strcmp(*argv, "-chain") == 0) cert_chain = 1; #endif else if (strcmp(*argv, "-id_prefix") == 0) { if (--argc < 1) goto bad; session_id_prefix = *(++argv); } #ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv, "-engine") == 0) { if (--argc < 1) goto bad; engine_id = *(++argv); } #endif else if (strcmp(*argv, "-rand") == 0) { if (--argc < 1) goto bad; inrand = *(++argv); } #ifndef OPENSSL_NO_TLSEXT else if (strcmp(*argv, "-servername") == 0) { if (--argc < 1) goto bad; tlsextcbp.servername = *(++argv); } else if (strcmp(*argv, "-servername_fatal") == 0) { tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL; } else if (strcmp(*argv, "-cert2") == 0) { if (--argc < 1) goto bad; s_cert_file2 = *(++argv); } else if (strcmp(*argv, "-key2") == 0) { if (--argc < 1) goto bad; s_key_file2 = *(++argv); } # ifndef OPENSSL_NO_NEXTPROTONEG else if (strcmp(*argv, "-nextprotoneg") == 0) { if (--argc < 1) goto bad; next_proto_neg_in = *(++argv); } # endif else if (strcmp(*argv, "-alpn") == 0) { if (--argc < 1) goto bad; alpn_in = *(++argv); } #endif #if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK) else if (strcmp(*argv, "-jpake") == 0) { if (--argc < 1) goto bad; jpake_secret = *(++argv); } #endif #ifndef OPENSSL_NO_SRTP else if (strcmp(*argv, "-use_srtp") == 0) { if (--argc < 1) goto bad; srtp_profiles = *(++argv); } #endif else if (strcmp(*argv, "-keymatexport") == 0) { if (--argc < 1) goto bad; keymatexportlabel = *(++argv); } else if (strcmp(*argv, "-keymatexportlen") == 0) { if (--argc < 1) goto bad; keymatexportlen = atoi(*(++argv)); if (keymatexportlen == 0) goto bad; } else { BIO_printf(bio_err, "unknown option %s\n", *argv); badop = 1; break; } argc--; argv++; } if (badop) { bad: sv_usage(); goto end; } #ifndef OPENSSL_NO_DTLS1 if (www && socket_type == SOCK_DGRAM) { BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n"); goto end; } #endif #if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK) if (jpake_secret) { if (psk_key) { BIO_printf(bio_err, "Can't use JPAKE and PSK together\n"); goto end; } psk_identity = "JPAKE"; } #endif if (prot_opt > 1) { BIO_printf(bio_err, "Cannot supply multiple protocol flags\n"); goto end; } if (prot_opt == 1 && no_prot_opt) { BIO_printf(bio_err, "Cannot supply both a protocol flag and " "\"-no_\"\n"); goto end; } SSL_load_error_strings(); OpenSSL_add_ssl_algorithms(); e = setup_engine(bio_err, engine_id, 1); if (!app_passwd(bio_err, passarg, dpassarg, &pass, &dpass)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } if (s_key_file == NULL) s_key_file = s_cert_file; #ifndef OPENSSL_NO_TLSEXT if (s_key_file2 == NULL) s_key_file2 = s_cert_file2; #endif if (!load_excert(&exc, bio_err)) goto end; if (nocert == 0) { s_key = load_key(bio_err, s_key_file, s_key_format, 0, pass, e, "server certificate private key file"); if (!s_key) { ERR_print_errors(bio_err); goto end; } s_cert = load_cert(bio_err, s_cert_file, s_cert_format, NULL, e, "server certificate file"); if (!s_cert) { ERR_print_errors(bio_err); goto end; } if (s_chain_file) { s_chain = load_certs(bio_err, s_chain_file, FORMAT_PEM, NULL, e, "server certificate chain"); if (!s_chain) goto end; } #ifndef OPENSSL_NO_TLSEXT if (tlsextcbp.servername) { s_key2 = load_key(bio_err, s_key_file2, s_key_format, 0, pass, e, "second server certificate private key file"); if (!s_key2) { ERR_print_errors(bio_err); goto end; } s_cert2 = load_cert(bio_err, s_cert_file2, s_cert_format, NULL, e, "second server certificate file"); if (!s_cert2) { ERR_print_errors(bio_err); goto end; } } #endif /* OPENSSL_NO_TLSEXT */ } #if !defined(OPENSSL_NO_TLSEXT) # if !defined(OPENSSL_NO_NEXTPROTONEG) if (next_proto_neg_in) { unsigned short len; next_proto.data = next_protos_parse(&len, next_proto_neg_in); if (next_proto.data == NULL) goto end; next_proto.len = len; } else { next_proto.data = NULL; } # endif alpn_ctx.data = NULL; if (alpn_in) { unsigned short len; alpn_ctx.data = next_protos_parse(&len, alpn_in); if (alpn_ctx.data == NULL) goto end; alpn_ctx.len = len; } #endif if (crl_file) { X509_CRL *crl; crl = load_crl(crl_file, crl_format); if (!crl) { BIO_puts(bio_err, "Error loading CRL\n"); ERR_print_errors(bio_err); goto end; } crls = sk_X509_CRL_new_null(); if (!crls || !sk_X509_CRL_push(crls, crl)) { BIO_puts(bio_err, "Error adding CRL\n"); ERR_print_errors(bio_err); X509_CRL_free(crl); goto end; } } if (s_dcert_file) { if (s_dkey_file == NULL) s_dkey_file = s_dcert_file; s_dkey = load_key(bio_err, s_dkey_file, s_dkey_format, 0, dpass, e, "second certificate private key file"); if (!s_dkey) { ERR_print_errors(bio_err); goto end; } s_dcert = load_cert(bio_err, s_dcert_file, s_dcert_format, NULL, e, "second server certificate file"); if (!s_dcert) { ERR_print_errors(bio_err); goto end; } if (s_dchain_file) { s_dchain = load_certs(bio_err, s_dchain_file, FORMAT_PEM, NULL, e, "second server certificate chain"); if (!s_dchain) goto end; } } if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL && !RAND_status()) { BIO_printf(bio_err, "warning, not much extra random data, consider using the -rand option\n"); } if (inrand != NULL) BIO_printf(bio_err, "%ld semi-random bytes loaded\n", app_RAND_load_files(inrand)); if (bio_s_out == NULL) { if (s_quiet && !s_debug) { bio_s_out = BIO_new(BIO_s_null()); if (s_msg && !bio_s_msg) bio_s_msg = BIO_new_fp(stdout, BIO_NOCLOSE); } else { if (bio_s_out == NULL) bio_s_out = BIO_new_fp(stdout, BIO_NOCLOSE); } } #if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_ECDSA) if (nocert) #endif { s_cert_file = NULL; s_key_file = NULL; s_dcert_file = NULL; s_dkey_file = NULL; #ifndef OPENSSL_NO_TLSEXT s_cert_file2 = NULL; s_key_file2 = NULL; #endif } ctx = SSL_CTX_new(meth); if (ctx == NULL) { ERR_print_errors(bio_err); goto end; } if (session_id_prefix) { if (strlen(session_id_prefix) >= 32) BIO_printf(bio_err, "warning: id_prefix is too long, only one new session will be possible\n"); else if (strlen(session_id_prefix) >= 16) BIO_printf(bio_err, "warning: id_prefix is too long if you use SSLv2\n"); if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) { BIO_printf(bio_err, "error setting 'id_prefix'\n"); ERR_print_errors(bio_err); goto end; } BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix); } SSL_CTX_set_quiet_shutdown(ctx, 1); if (hack) SSL_CTX_set_options(ctx, SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG); if (exc) ssl_ctx_set_excert(ctx, exc); if (state) SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback); if (no_cache) SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF); else if (ext_cache) init_session_cache_ctx(ctx); else SSL_CTX_sess_set_cache_size(ctx, 128); #ifndef OPENSSL_NO_SRTP if (srtp_profiles != NULL) SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles); #endif #if 0 if (cipher == NULL) cipher = getenv("SSL_CIPHER"); #endif #if 0 if (s_cert_file == NULL) { BIO_printf(bio_err, "You must specify a certificate file for the server to use\n"); goto end; } #endif if ((!SSL_CTX_load_verify_locations(ctx, CAfile, CApath)) || (!SSL_CTX_set_default_verify_paths(ctx))) { /* BIO_printf(bio_err,"X509_load_verify_locations\n"); */ ERR_print_errors(bio_err); /* goto end; */ } if (vpm) SSL_CTX_set1_param(ctx, vpm); ssl_ctx_add_crls(ctx, crls, 0); if (!args_ssl_call(ctx, bio_err, cctx, ssl_args, no_ecdhe, no_jpake)) goto end; if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile, crls, crl_download)) { BIO_printf(bio_err, "Error loading store locations\n"); ERR_print_errors(bio_err); goto end; } #ifndef OPENSSL_NO_TLSEXT if (s_cert2) { ctx2 = SSL_CTX_new(meth); if (ctx2 == NULL) { ERR_print_errors(bio_err); goto end; } } if (ctx2) { BIO_printf(bio_s_out, "Setting secondary ctx parameters\n"); if (session_id_prefix) { if (strlen(session_id_prefix) >= 32) BIO_printf(bio_err, "warning: id_prefix is too long, only one new session will be possible\n"); else if (strlen(session_id_prefix) >= 16) BIO_printf(bio_err, "warning: id_prefix is too long if you use SSLv2\n"); if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) { BIO_printf(bio_err, "error setting 'id_prefix'\n"); ERR_print_errors(bio_err); goto end; } BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix); } SSL_CTX_set_quiet_shutdown(ctx2, 1); if (hack) SSL_CTX_set_options(ctx2, SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG); if (exc) ssl_ctx_set_excert(ctx2, exc); if (state) SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback); if (no_cache) SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF); else if (ext_cache) init_session_cache_ctx(ctx2); else SSL_CTX_sess_set_cache_size(ctx2, 128); if ((!SSL_CTX_load_verify_locations(ctx2, CAfile, CApath)) || (!SSL_CTX_set_default_verify_paths(ctx2))) { ERR_print_errors(bio_err); } if (vpm) SSL_CTX_set1_param(ctx2, vpm); ssl_ctx_add_crls(ctx2, crls, 0); if (!args_ssl_call(ctx2, bio_err, cctx, ssl_args, no_ecdhe, no_jpake)) goto end; } # ifndef OPENSSL_NO_NEXTPROTONEG if (next_proto.data) SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb, &next_proto); # endif if (alpn_ctx.data) SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx); #endif #ifndef OPENSSL_NO_DH if (!no_dhe) { DH *dh = NULL; if (dhfile) dh = load_dh_param(dhfile); else if (s_cert_file) dh = load_dh_param(s_cert_file); if (dh != NULL) { BIO_printf(bio_s_out, "Setting temp DH parameters\n"); } else { BIO_printf(bio_s_out, "Using default temp DH parameters\n"); dh = get_dh2048(); if (dh == NULL) { ERR_print_errors(bio_err); goto end; } } (void)BIO_flush(bio_s_out); SSL_CTX_set_tmp_dh(ctx, dh); # ifndef OPENSSL_NO_TLSEXT if (ctx2) { if (!dhfile) { DH *dh2 = load_dh_param(s_cert_file2); if (dh2 != NULL) { BIO_printf(bio_s_out, "Setting temp DH parameters\n"); (void)BIO_flush(bio_s_out); DH_free(dh); dh = dh2; } } SSL_CTX_set_tmp_dh(ctx2, dh); } # endif DH_free(dh); } #endif if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain)) goto end; #ifndef OPENSSL_NO_TLSEXT if (s_serverinfo_file != NULL && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) { ERR_print_errors(bio_err); goto end; } #endif #ifndef OPENSSL_NO_TLSEXT if (ctx2 && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain)) goto end; #endif if (s_dcert != NULL) { if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain)) goto end; } #ifndef OPENSSL_NO_RSA # if 1 if (!no_tmp_rsa) { SSL_CTX_set_tmp_rsa_callback(ctx, tmp_rsa_cb); # ifndef OPENSSL_NO_TLSEXT if (ctx2) SSL_CTX_set_tmp_rsa_callback(ctx2, tmp_rsa_cb); # endif } # else if (!no_tmp_rsa && SSL_CTX_need_tmp_RSA(ctx)) { RSA *rsa; BIO_printf(bio_s_out, "Generating temp (512 bit) RSA key..."); BIO_flush(bio_s_out); rsa = RSA_generate_key(512, RSA_F4, NULL); if (!SSL_CTX_set_tmp_rsa(ctx, rsa)) { ERR_print_errors(bio_err); goto end; } # ifndef OPENSSL_NO_TLSEXT if (ctx2) { if (!SSL_CTX_set_tmp_rsa(ctx2, rsa)) { ERR_print_errors(bio_err); goto end; } } # endif RSA_free(rsa); BIO_printf(bio_s_out, "\n"); } # endif #endif #ifndef OPENSSL_NO_PSK # ifdef OPENSSL_NO_JPAKE if (psk_key != NULL) # else if (psk_key != NULL || jpake_secret) # endif { if (s_debug) BIO_printf(bio_s_out, "PSK key given or JPAKE in use, setting server callback\n"); SSL_CTX_set_psk_server_callback(ctx, psk_server_cb); } if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) { BIO_printf(bio_err, "error setting PSK identity hint to context\n"); ERR_print_errors(bio_err); goto end; } #endif SSL_CTX_set_verify(ctx, s_server_verify, verify_callback); SSL_CTX_set_session_id_context(ctx, (void *)&s_server_session_id_context, sizeof s_server_session_id_context); /* Set DTLS cookie generation and verification callbacks */ SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback); SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback); #ifndef OPENSSL_NO_TLSEXT if (ctx2) { SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback); SSL_CTX_set_session_id_context(ctx2, (void *)&s_server_session_id_context, sizeof s_server_session_id_context); tlsextcbp.biodebug = bio_s_out; SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb); SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp); SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb); SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp); } #endif #ifndef OPENSSL_NO_SRP if (srp_verifier_file != NULL) { srp_callback_parm.vb = SRP_VBASE_new(srpuserseed); srp_callback_parm.user = NULL; srp_callback_parm.login = NULL; if ((ret = SRP_VBASE_init(srp_callback_parm.vb, srp_verifier_file)) != SRP_NO_ERROR) { BIO_printf(bio_err, "Cannot initialize SRP verifier file \"%s\":ret=%d\n", srp_verifier_file, ret); goto end; } SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_callback); SSL_CTX_set_srp_cb_arg(ctx, &srp_callback_parm); SSL_CTX_set_srp_username_callback(ctx, ssl_srp_server_param_cb); } else #endif if (CAfile != NULL) { SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile)); #ifndef OPENSSL_NO_TLSEXT if (ctx2) SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile)); #endif } BIO_printf(bio_s_out, "ACCEPT\n"); (void)BIO_flush(bio_s_out); if (rev) do_server(port, socket_type, &accept_socket, rev_body, context, naccept); else if (www) do_server(port, socket_type, &accept_socket, www_body, context, naccept); else do_server(port, socket_type, &accept_socket, sv_body, context, naccept); print_stats(bio_s_out, ctx); ret = 0; end: if (ctx != NULL) SSL_CTX_free(ctx); if (s_cert) X509_free(s_cert); if (crls) sk_X509_CRL_pop_free(crls, X509_CRL_free); if (s_dcert) X509_free(s_dcert); if (s_key) EVP_PKEY_free(s_key); if (s_dkey) EVP_PKEY_free(s_dkey); if (s_chain) sk_X509_pop_free(s_chain, X509_free); if (s_dchain) sk_X509_pop_free(s_dchain, X509_free); if (pass) OPENSSL_free(pass); if (dpass) OPENSSL_free(dpass); if (vpm) X509_VERIFY_PARAM_free(vpm); free_sessions(); #ifndef OPENSSL_NO_TLSEXT if (tlscstatp.host) OPENSSL_free(tlscstatp.host); if (tlscstatp.port) OPENSSL_free(tlscstatp.port); if (tlscstatp.path) OPENSSL_free(tlscstatp.path); if (ctx2 != NULL) SSL_CTX_free(ctx2); if (s_cert2) X509_free(s_cert2); if (s_key2) EVP_PKEY_free(s_key2); if (serverinfo_in != NULL) BIO_free(serverinfo_in); # ifndef OPENSSL_NO_NEXTPROTONEG if (next_proto.data) OPENSSL_free(next_proto.data); # endif if (alpn_ctx.data) OPENSSL_free(alpn_ctx.data); #endif ssl_excert_free(exc); if (ssl_args) sk_OPENSSL_STRING_free(ssl_args); if (cctx) SSL_CONF_CTX_free(cctx); #ifndef OPENSSL_NO_JPAKE if (jpake_secret && psk_key) OPENSSL_free(psk_key); #endif release_engine(e); if (bio_s_out != NULL) { BIO_free(bio_s_out); bio_s_out = NULL; } if (bio_s_msg != NULL) { BIO_free(bio_s_msg); bio_s_msg = NULL; } + SSL_COMP_free_compression_methods(); apps_shutdown(); OPENSSL_EXIT(ret); } static void print_stats(BIO *bio, SSL_CTX *ssl_ctx) { BIO_printf(bio, "%4ld items in the session cache\n", SSL_CTX_sess_number(ssl_ctx)); BIO_printf(bio, "%4ld client connects (SSL_connect())\n", SSL_CTX_sess_connect(ssl_ctx)); BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n", SSL_CTX_sess_connect_renegotiate(ssl_ctx)); BIO_printf(bio, "%4ld client connects that finished\n", SSL_CTX_sess_connect_good(ssl_ctx)); BIO_printf(bio, "%4ld server accepts (SSL_accept())\n", SSL_CTX_sess_accept(ssl_ctx)); BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n", SSL_CTX_sess_accept_renegotiate(ssl_ctx)); BIO_printf(bio, "%4ld server accepts that finished\n", SSL_CTX_sess_accept_good(ssl_ctx)); BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx)); BIO_printf(bio, "%4ld session cache misses\n", SSL_CTX_sess_misses(ssl_ctx)); BIO_printf(bio, "%4ld session cache timeouts\n", SSL_CTX_sess_timeouts(ssl_ctx)); BIO_printf(bio, "%4ld callback cache hits\n", SSL_CTX_sess_cb_hits(ssl_ctx)); BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n", SSL_CTX_sess_cache_full(ssl_ctx), SSL_CTX_sess_get_cache_size(ssl_ctx)); } static int sv_body(char *hostname, int s, int stype, unsigned char *context) { char *buf = NULL; fd_set readfds; int ret = 1, width; int k, i; unsigned long l; SSL *con = NULL; BIO *sbio; #ifndef OPENSSL_NO_KRB5 KSSL_CTX *kctx; #endif struct timeval timeout; #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE) || defined(OPENSSL_SYS_BEOS_R5) struct timeval tv; #else struct timeval *timeoutp; #endif if ((buf = OPENSSL_malloc(bufsize)) == NULL) { BIO_printf(bio_err, "out of memory\n"); goto err; } #ifdef FIONBIO if (s_nbio) { unsigned long sl = 1; if (!s_quiet) BIO_printf(bio_err, "turning on non blocking io\n"); if (BIO_socket_ioctl(s, FIONBIO, &sl) < 0) ERR_print_errors(bio_err); } #endif if (con == NULL) { con = SSL_new(ctx); #ifndef OPENSSL_NO_TLSEXT if (s_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_s_out); } if (s_tlsextstatus) { SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb); tlscstatp.err = bio_err; SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp); } #endif #ifndef OPENSSL_NO_KRB5 if ((kctx = kssl_ctx_new()) != NULL) { SSL_set0_kssl_ctx(con, kctx); kssl_ctx_setstring(kctx, KSSL_SERVICE, KRB5SVC); kssl_ctx_setstring(kctx, KSSL_KEYTAB, KRB5KEYTAB); } #endif /* OPENSSL_NO_KRB5 */ if (context) SSL_set_session_id_context(con, context, strlen((char *)context)); } SSL_clear(con); #if 0 # ifdef TLSEXT_TYPE_opaque_prf_input SSL_set_tlsext_opaque_prf_input(con, "Test server", 11); # endif #endif if (stype == SOCK_DGRAM) { sbio = BIO_new_dgram(s, BIO_NOCLOSE); if (enable_timeouts) { timeout.tv_sec = 0; timeout.tv_usec = DGRAM_RCV_TIMEOUT; BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout); timeout.tv_sec = 0; timeout.tv_usec = DGRAM_SND_TIMEOUT; BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout); } if (socket_mtu) { if (socket_mtu < DTLS_get_link_min_mtu(con)) { BIO_printf(bio_err, "MTU too small. Must be at least %ld\n", DTLS_get_link_min_mtu(con)); ret = -1; BIO_free(sbio); goto err; } SSL_set_options(con, SSL_OP_NO_QUERY_MTU); if (!DTLS_set_link_mtu(con, socket_mtu)) { BIO_printf(bio_err, "Failed to set MTU\n"); ret = -1; BIO_free(sbio); goto err; } } else /* want to do MTU discovery */ BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL); /* turn on cookie exchange */ SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE); } else sbio = BIO_new_socket(s, BIO_NOCLOSE); if (s_nbio_test) { BIO *test; test = BIO_new(BIO_f_nbio_test()); sbio = BIO_push(test, sbio); } #ifndef OPENSSL_NO_JPAKE if (jpake_secret) jpake_server_auth(bio_s_out, sbio, jpake_secret); #endif SSL_set_bio(con, sbio, sbio); SSL_set_accept_state(con); /* SSL_set_fd(con,s); */ if (s_debug) { SSL_set_debug(con, 1); BIO_set_callback(SSL_get_rbio(con), bio_dump_callback); BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out); } if (s_msg) { #ifndef OPENSSL_NO_SSL_TRACE if (s_msg == 2) SSL_set_msg_callback(con, SSL_trace); else #endif SSL_set_msg_callback(con, msg_cb); SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out); } #ifndef OPENSSL_NO_TLSEXT if (s_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_s_out); } #endif if (fileno_stdin() > s) width = fileno_stdin() + 1; else width = s + 1; for (;;) { int read_from_terminal; int read_from_sslcon; read_from_terminal = 0; read_from_sslcon = SSL_pending(con); if (!read_from_sslcon) { FD_ZERO(&readfds); #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_NETWARE) && !defined(OPENSSL_SYS_BEOS_R5) openssl_fdset(fileno_stdin(), &readfds); #endif openssl_fdset(s, &readfds); /* * Note: under VMS with SOCKETSHR the second parameter is * currently of type (int *) whereas under other systems it is * (void *) if you don't have a cast it will choke the compiler: * if you do have a cast then you can either go for (int *) or * (void *). */ #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE) /* * Under DOS (non-djgpp) and Windows we can't select on stdin: * only on sockets. As a workaround we timeout the select every * 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); if ((i < 0) || (!i && !_kbhit())) continue; if (_kbhit()) read_from_terminal = 1; #elif defined(OPENSSL_SYS_BEOS_R5) /* Under BeOS-R5 the situation is similar to DOS */ tv.tv_sec = 1; tv.tv_usec = 0; (void)fcntl(fileno_stdin(), F_SETFL, O_NONBLOCK); i = select(width, (void *)&readfds, NULL, NULL, &tv); if ((i < 0) || (!i && read(fileno_stdin(), buf, 0) < 0)) continue; if (read(fileno_stdin(), buf, 0) >= 0) read_from_terminal = 1; (void)fcntl(fileno_stdin(), F_SETFL, 0); #else if ((SSL_version(con) == DTLS1_VERSION) && 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) { BIO_printf(bio_err, "TIMEOUT occured\n"); } if (i <= 0) continue; if (FD_ISSET(fileno_stdin(), &readfds)) read_from_terminal = 1; #endif if (FD_ISSET(s, &readfds)) read_from_sslcon = 1; } if (read_from_terminal) { if (s_crlf) { int j, lf_num; i = raw_read_stdin(buf, bufsize / 2); lf_num = 0; /* both loops are skipped when i <= 0 */ for (j = 0; j < i; j++) if (buf[j] == '\n') lf_num++; for (j = i - 1; j >= 0; j--) { buf[j + lf_num] = buf[j]; if (buf[j] == '\n') { lf_num--; i++; buf[j + lf_num] = '\r'; } } assert(lf_num == 0); } else i = raw_read_stdin(buf, bufsize); if (!s_quiet && !s_brief) { if ((i <= 0) || (buf[0] == 'Q')) { BIO_printf(bio_s_out, "DONE\n"); SHUTDOWN(s); close_accept_socket(); ret = -11; goto err; } if ((i <= 0) || (buf[0] == 'q')) { BIO_printf(bio_s_out, "DONE\n"); if (SSL_version(con) != DTLS1_VERSION) SHUTDOWN(s); /* * close_accept_socket(); ret= -11; */ goto err; } #ifndef OPENSSL_NO_HEARTBEATS if ((buf[0] == 'B') && ((buf[1] == '\n') || (buf[1] == '\r'))) { BIO_printf(bio_err, "HEARTBEATING\n"); SSL_heartbeat(con); i = 0; continue; } #endif if ((buf[0] == 'r') && ((buf[1] == '\n') || (buf[1] == '\r'))) { SSL_renegotiate(con); i = SSL_do_handshake(con); printf("SSL_do_handshake -> %d\n", i); i = 0; /* 13; */ continue; /* * strcpy(buf,"server side RE-NEGOTIATE\n"); */ } if ((buf[0] == 'R') && ((buf[1] == '\n') || (buf[1] == '\r'))) { SSL_set_verify(con, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, NULL); SSL_renegotiate(con); i = SSL_do_handshake(con); printf("SSL_do_handshake -> %d\n", i); i = 0; /* 13; */ continue; /* * strcpy(buf,"server side RE-NEGOTIATE asking for client * cert\n"); */ } if (buf[0] == 'P') { static const char *str = "Lets print some clear text\n"; BIO_write(SSL_get_wbio(con), str, strlen(str)); } if (buf[0] == 'S') { print_stats(bio_s_out, SSL_get_SSL_CTX(con)); } } #ifdef CHARSET_EBCDIC ebcdic2ascii(buf, buf, i); #endif l = k = 0; for (;;) { /* should do a select for the write */ #ifdef RENEG { static count = 0; if (++count == 100) { count = 0; SSL_renegotiate(con); } } #endif k = SSL_write(con, &(buf[l]), (unsigned int)i); #ifndef OPENSSL_NO_SRP while (SSL_get_error(con, k) == SSL_ERROR_WANT_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP renego during write\n"); SRP_user_pwd_free(srp_callback_parm.user); srp_callback_parm.user = SRP_VBASE_get1_by_user(srp_callback_parm.vb, srp_callback_parm.login); if (srp_callback_parm.user) BIO_printf(bio_s_out, "LOOKUP done %s\n", srp_callback_parm.user->info); else BIO_printf(bio_s_out, "LOOKUP not successful\n"); k = SSL_write(con, &(buf[l]), (unsigned int)i); } #endif switch (SSL_get_error(con, k)) { case SSL_ERROR_NONE: break; case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_X509_LOOKUP: BIO_printf(bio_s_out, "Write BLOCK\n"); break; case SSL_ERROR_SYSCALL: case SSL_ERROR_SSL: BIO_printf(bio_s_out, "ERROR\n"); ERR_print_errors(bio_err); ret = 1; goto err; /* break; */ case SSL_ERROR_ZERO_RETURN: BIO_printf(bio_s_out, "DONE\n"); ret = 1; goto err; } if (k > 0) { l += k; i -= k; } if (i <= 0) break; } } if (read_from_sslcon) { if (!SSL_is_init_finished(con)) { i = init_ssl_connection(con); if (i < 0) { ret = 0; goto err; } else if (i == 0) { ret = 1; goto err; } } else { again: i = SSL_read(con, (char *)buf, bufsize); #ifndef OPENSSL_NO_SRP while (SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP renego during read\n"); SRP_user_pwd_free(srp_callback_parm.user); srp_callback_parm.user = SRP_VBASE_get1_by_user(srp_callback_parm.vb, srp_callback_parm.login); if (srp_callback_parm.user) BIO_printf(bio_s_out, "LOOKUP done %s\n", srp_callback_parm.user->info); else BIO_printf(bio_s_out, "LOOKUP not successful\n"); i = SSL_read(con, (char *)buf, bufsize); } #endif switch (SSL_get_error(con, i)) { case SSL_ERROR_NONE: #ifdef CHARSET_EBCDIC ascii2ebcdic(buf, buf, i); #endif raw_write_stdout(buf, (unsigned int)i); if (SSL_pending(con)) goto again; break; case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_READ: BIO_printf(bio_s_out, "Read BLOCK\n"); break; case SSL_ERROR_SYSCALL: case SSL_ERROR_SSL: BIO_printf(bio_s_out, "ERROR\n"); ERR_print_errors(bio_err); ret = 1; goto err; case SSL_ERROR_ZERO_RETURN: BIO_printf(bio_s_out, "DONE\n"); ret = 1; goto err; } } } } err: if (con != NULL) { BIO_printf(bio_s_out, "shutting down SSL\n"); #if 1 SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); #else SSL_shutdown(con); #endif SSL_free(con); } BIO_printf(bio_s_out, "CONNECTION CLOSED\n"); if (buf != NULL) { OPENSSL_cleanse(buf, bufsize); OPENSSL_free(buf); } if (ret >= 0) BIO_printf(bio_s_out, "ACCEPT\n"); return (ret); } static void close_accept_socket(void) { BIO_printf(bio_err, "shutdown accept socket\n"); if (accept_socket >= 0) { SHUTDOWN2(accept_socket); } } static int init_ssl_connection(SSL *con) { int i; const char *str; X509 *peer; long verify_error; MS_STATIC char buf[BUFSIZ]; #ifndef OPENSSL_NO_KRB5 char *client_princ; #endif #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) const unsigned char *next_proto_neg; unsigned next_proto_neg_len; #endif unsigned char *exportedkeymat; i = SSL_accept(con); #ifdef CERT_CB_TEST_RETRY { while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP && SSL_state(con) == SSL3_ST_SR_CLNT_HELLO_C) { fprintf(stderr, "LOOKUP from certificate callback during accept\n"); i = SSL_accept(con); } } #endif #ifndef OPENSSL_NO_SRP while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP during accept %s\n", srp_callback_parm.login); SRP_user_pwd_free(srp_callback_parm.user); srp_callback_parm.user = SRP_VBASE_get1_by_user(srp_callback_parm.vb, srp_callback_parm.login); if (srp_callback_parm.user) BIO_printf(bio_s_out, "LOOKUP done %s\n", srp_callback_parm.user->info); else BIO_printf(bio_s_out, "LOOKUP not successful\n"); i = SSL_accept(con); } #endif if (i <= 0) { if (BIO_sock_should_retry(i)) { BIO_printf(bio_s_out, "DELAY\n"); return (1); } BIO_printf(bio_err, "ERROR\n"); verify_error = SSL_get_verify_result(con); if (verify_error != X509_V_OK) { BIO_printf(bio_err, "verify error:%s\n", X509_verify_cert_error_string(verify_error)); } /* Always print any error messages */ ERR_print_errors(bio_err); return (0); } if (s_brief) print_ssl_summary(bio_err, con); PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con)); peer = SSL_get_peer_certificate(con); if (peer != NULL) { BIO_printf(bio_s_out, "Client certificate\n"); PEM_write_bio_X509(bio_s_out, peer); X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof buf); BIO_printf(bio_s_out, "subject=%s\n", buf); X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof buf); BIO_printf(bio_s_out, "issuer=%s\n", buf); X509_free(peer); } if (SSL_get_shared_ciphers(con, buf, sizeof buf) != NULL) BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf); str = SSL_CIPHER_get_name(SSL_get_current_cipher(con)); ssl_print_sigalgs(bio_s_out, con); #ifndef OPENSSL_NO_EC ssl_print_point_formats(bio_s_out, con); ssl_print_curves(bio_s_out, con, 0); #endif BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)"); #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len); if (next_proto_neg) { BIO_printf(bio_s_out, "NEXTPROTO is "); BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len); BIO_printf(bio_s_out, "\n"); } #endif #ifndef OPENSSL_NO_SRTP { SRTP_PROTECTION_PROFILE *srtp_profile = SSL_get_selected_srtp_profile(con); if (srtp_profile) BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n", srtp_profile->name); } #endif if (SSL_cache_hit(con)) BIO_printf(bio_s_out, "Reused session-id\n"); if (SSL_ctrl(con, SSL_CTRL_GET_FLAGS, 0, NULL) & TLS1_FLAGS_TLS_PADDING_BUG) BIO_printf(bio_s_out, "Peer has incorrect TLSv1 block padding\n"); #ifndef OPENSSL_NO_KRB5 client_princ = kssl_ctx_get0_client_princ(SSL_get0_kssl_ctx(con)); if (client_princ != NULL) { BIO_printf(bio_s_out, "Kerberos peer principal is %s\n", client_princ); } #endif /* OPENSSL_NO_KRB5 */ BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n", SSL_get_secure_renegotiation_support(con) ? "" : " NOT"); if (keymatexportlabel != NULL) { BIO_printf(bio_s_out, "Keying material exporter:\n"); BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel); BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen); exportedkeymat = OPENSSL_malloc(keymatexportlen); if (exportedkeymat != NULL) { if (!SSL_export_keying_material(con, exportedkeymat, keymatexportlen, keymatexportlabel, strlen(keymatexportlabel), NULL, 0, 0)) { BIO_printf(bio_s_out, " Error\n"); } else { BIO_printf(bio_s_out, " Keying material: "); for (i = 0; i < keymatexportlen; i++) BIO_printf(bio_s_out, "%02X", exportedkeymat[i]); BIO_printf(bio_s_out, "\n"); } OPENSSL_free(exportedkeymat); } } return (1); } #ifndef OPENSSL_NO_DH static DH *load_dh_param(const char *dhfile) { DH *ret = NULL; BIO *bio; if ((bio = BIO_new_file(dhfile, "r")) == NULL) goto err; ret = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); err: if (bio != NULL) BIO_free(bio); return (ret); } #endif #ifndef OPENSSL_NO_KRB5 char *client_princ; #endif #if 0 static int load_CA(SSL_CTX *ctx, char *file) { FILE *in; X509 *x = NULL; if ((in = fopen(file, "r")) == NULL) return (0); for (;;) { if (PEM_read_X509(in, &x, NULL) == NULL) break; SSL_CTX_add_client_CA(ctx, x); } if (x != NULL) X509_free(x); fclose(in); return (1); } #endif static int www_body(char *hostname, int s, int stype, unsigned char *context) { char *buf = NULL; int ret = 1; int i, j, k, dot; SSL *con; const SSL_CIPHER *c; BIO *io, *ssl_bio, *sbio; #ifndef OPENSSL_NO_KRB5 KSSL_CTX *kctx; #endif buf = OPENSSL_malloc(bufsize); if (buf == NULL) return (0); io = BIO_new(BIO_f_buffer()); ssl_bio = BIO_new(BIO_f_ssl()); if ((io == NULL) || (ssl_bio == NULL)) goto err; #ifdef FIONBIO if (s_nbio) { unsigned long sl = 1; if (!s_quiet) BIO_printf(bio_err, "turning on non blocking io\n"); if (BIO_socket_ioctl(s, FIONBIO, &sl) < 0) ERR_print_errors(bio_err); } #endif /* lets make the output buffer a reasonable size */ if (!BIO_set_write_buffer_size(io, bufsize)) goto err; if ((con = SSL_new(ctx)) == NULL) goto err; #ifndef OPENSSL_NO_TLSEXT if (s_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_s_out); } #endif #ifndef OPENSSL_NO_KRB5 if ((kctx = kssl_ctx_new()) != NULL) { kssl_ctx_setstring(kctx, KSSL_SERVICE, KRB5SVC); kssl_ctx_setstring(kctx, KSSL_KEYTAB, KRB5KEYTAB); } #endif /* OPENSSL_NO_KRB5 */ if (context) SSL_set_session_id_context(con, context, strlen((char *)context)); sbio = BIO_new_socket(s, BIO_NOCLOSE); if (s_nbio_test) { BIO *test; test = BIO_new(BIO_f_nbio_test()); sbio = BIO_push(test, sbio); } SSL_set_bio(con, sbio, sbio); SSL_set_accept_state(con); /* SSL_set_fd(con,s); */ BIO_set_ssl(ssl_bio, con, BIO_CLOSE); BIO_push(io, ssl_bio); #ifdef CHARSET_EBCDIC io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io); #endif if (s_debug) { SSL_set_debug(con, 1); BIO_set_callback(SSL_get_rbio(con), bio_dump_callback); BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out); } if (s_msg) { #ifndef OPENSSL_NO_SSL_TRACE if (s_msg == 2) SSL_set_msg_callback(con, SSL_trace); else #endif SSL_set_msg_callback(con, msg_cb); SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out); } for (;;) { if (hack) { i = SSL_accept(con); #ifndef OPENSSL_NO_SRP while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP during accept %s\n", srp_callback_parm.login); SRP_user_pwd_free(srp_callback_parm.user); srp_callback_parm.user = SRP_VBASE_get1_by_user(srp_callback_parm.vb, srp_callback_parm.login); if (srp_callback_parm.user) BIO_printf(bio_s_out, "LOOKUP done %s\n", srp_callback_parm.user->info); else BIO_printf(bio_s_out, "LOOKUP not successful\n"); i = SSL_accept(con); } #endif switch (SSL_get_error(con, i)) { case SSL_ERROR_NONE: break; case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_X509_LOOKUP: continue; case SSL_ERROR_SYSCALL: case SSL_ERROR_SSL: case SSL_ERROR_ZERO_RETURN: ret = 1; goto err; /* break; */ } SSL_renegotiate(con); SSL_write(con, NULL, 0); } i = BIO_gets(io, buf, bufsize - 1); if (i < 0) { /* error */ if (!BIO_should_retry(io)) { if (!s_quiet) ERR_print_errors(bio_err); goto err; } else { BIO_printf(bio_s_out, "read R BLOCK\n"); #ifndef OPENSSL_NO_SRP if (BIO_should_io_special(io) && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP renego during read\n"); SRP_user_pwd_free(srp_callback_parm.user); srp_callback_parm.user = SRP_VBASE_get1_by_user(srp_callback_parm.vb, srp_callback_parm.login); if (srp_callback_parm.user) BIO_printf(bio_s_out, "LOOKUP done %s\n", srp_callback_parm.user->info); else BIO_printf(bio_s_out, "LOOKUP not successful\n"); continue; } #endif #if defined(OPENSSL_SYS_NETWARE) delay(1000); #elif !defined(OPENSSL_SYS_MSDOS) && !defined(__DJGPP__) sleep(1); #endif continue; } } else if (i == 0) { /* end of input */ ret = 1; goto end; } /* else we have data */ if (((www == 1) && (strncmp("GET ", buf, 4) == 0)) || ((www == 2) && (strncmp("GET /stats ", buf, 11) == 0))) { char *p; X509 *peer; STACK_OF(SSL_CIPHER) *sk; static const char *space = " "; BIO_puts(io, "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n"); BIO_puts(io, "\n"); BIO_puts(io, "
\n");
 /*                      BIO_puts(io,SSLeay_version(SSLEAY_VERSION));*/
             BIO_puts(io, "\n");
             for (i = 0; i < local_argc; i++) {
                 BIO_puts(io, local_argv[i]);
                 BIO_write(io, " ", 1);
             }
             BIO_puts(io, "\n");
 
             BIO_printf(io,
                        "Secure Renegotiation IS%s supported\n",
                        SSL_get_secure_renegotiation_support(con) ?
                        "" : " NOT");
 
             /*
              * The following is evil and should not really be done
              */
             BIO_printf(io, "Ciphers supported in s_server binary\n");
             sk = SSL_get_ciphers(con);
             j = sk_SSL_CIPHER_num(sk);
             for (i = 0; i < j; i++) {
                 c = sk_SSL_CIPHER_value(sk, i);
                 BIO_printf(io, "%-11s:%-25s",
                            SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
                 if ((((i + 1) % 2) == 0) && (i + 1 != j))
                     BIO_puts(io, "\n");
             }
             BIO_puts(io, "\n");
             p = SSL_get_shared_ciphers(con, buf, bufsize);
             if (p != NULL) {
                 BIO_printf(io,
                            "---\nCiphers common between both SSL end points:\n");
                 j = i = 0;
                 while (*p) {
                     if (*p == ':') {
                         BIO_write(io, space, 26 - j);
                         i++;
                         j = 0;
                         BIO_write(io, ((i % 3) ? " " : "\n"), 1);
                     } else {
                         BIO_write(io, p, 1);
                         j++;
                     }
                     p++;
                 }
                 BIO_puts(io, "\n");
             }
             ssl_print_sigalgs(io, con);
 #ifndef OPENSSL_NO_EC
             ssl_print_curves(io, con, 0);
 #endif
             BIO_printf(io, (SSL_cache_hit(con)
                             ? "---\nReused, " : "---\nNew, "));
             c = SSL_get_current_cipher(con);
             BIO_printf(io, "%s, Cipher is %s\n",
                        SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
             SSL_SESSION_print(io, SSL_get_session(con));
             BIO_printf(io, "---\n");
             print_stats(io, SSL_get_SSL_CTX(con));
             BIO_printf(io, "---\n");
             peer = SSL_get_peer_certificate(con);
             if (peer != NULL) {
                 BIO_printf(io, "Client certificate\n");
                 X509_print(io, peer);
                 PEM_write_bio_X509(io, peer);
             } else
                 BIO_puts(io, "no client certificate available\n");
             BIO_puts(io, "\r\n\r\n");
             break;
         } else if ((www == 2 || www == 3)
                    && (strncmp("GET /", buf, 5) == 0)) {
             BIO *file;
             char *p, *e;
             static const char *text =
                 "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n";
 
             /* skip the '/' */
             p = &(buf[5]);
 
             dot = 1;
             for (e = p; *e != '\0'; e++) {
                 if (e[0] == ' ')
                     break;
 
                 switch (dot) {
                 case 1:
                     dot = (e[0] == '.') ? 2 : 0;
                     break;
                 case 2:
                     dot = (e[0] == '.') ? 3 : 0;
                     break;
                 case 3:
                     dot = (e[0] == '/') ? -1 : 0;
                     break;
                 }
                 if (dot == 0)
                     dot = (e[0] == '/') ? 1 : 0;
             }
             dot = (dot == 3) || (dot == -1); /* filename contains ".."
                                               * component */
 
             if (*e == '\0') {
                 BIO_puts(io, text);
                 BIO_printf(io, "'%s' is an invalid file name\r\n", p);
                 break;
             }
             *e = '\0';
 
             if (dot) {
                 BIO_puts(io, text);
                 BIO_printf(io, "'%s' contains '..' reference\r\n", p);
                 break;
             }
 
             if (*p == '/') {
                 BIO_puts(io, text);
                 BIO_printf(io, "'%s' is an invalid path\r\n", p);
                 break;
             }
 #if 0
             /* append if a directory lookup */
             if (e[-1] == '/')
                 strcat(p, "index.html");
 #endif
 
             /* if a directory, do the index thang */
             if (app_isdir(p) > 0) {
 #if 0                           /* must check buffer size */
                 strcat(p, "/index.html");
 #else
                 BIO_puts(io, text);
                 BIO_printf(io, "'%s' is a directory\r\n", p);
                 break;
 #endif
             }
 
             if ((file = BIO_new_file(p, "r")) == NULL) {
                 BIO_puts(io, text);
                 BIO_printf(io, "Error opening '%s'\r\n", p);
                 ERR_print_errors(io);
                 break;
             }
 
             if (!s_quiet)
                 BIO_printf(bio_err, "FILE:%s\n", p);
 
             if (www == 2) {
                 i = strlen(p);
                 if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) ||
                     ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) ||
                     ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0)))
                     BIO_puts(io,
                              "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n");
                 else
                     BIO_puts(io,
                              "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n");
             }
             /* send the file */
             for (;;) {
                 i = BIO_read(file, buf, bufsize);
                 if (i <= 0)
                     break;
 
 #ifdef RENEG
                 total_bytes += i;
                 fprintf(stderr, "%d\n", i);
                 if (total_bytes > 3 * 1024) {
                     total_bytes = 0;
                     fprintf(stderr, "RENEGOTIATE\n");
                     SSL_renegotiate(con);
                 }
 #endif
 
                 for (j = 0; j < i;) {
 #ifdef RENEG
                     {
                         static count = 0;
                         if (++count == 13) {
                             SSL_renegotiate(con);
                         }
                     }
 #endif
                     k = BIO_write(io, &(buf[j]), i - j);
                     if (k <= 0) {
                         if (!BIO_should_retry(io))
                             goto write_error;
                         else {
                             BIO_printf(bio_s_out, "rwrite W BLOCK\n");
                         }
                     } else {
                         j += k;
                     }
                 }
             }
  write_error:
             BIO_free(file);
             break;
         }
     }
 
     for (;;) {
         i = (int)BIO_flush(io);
         if (i <= 0) {
             if (!BIO_should_retry(io))
                 break;
         } else
             break;
     }
  end:
 #if 1
     /* make sure we re-use sessions */
     SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
 #else
     /* This kills performance */
     /*
      * SSL_shutdown(con); A shutdown gets sent in the BIO_free_all(io)
      * procession
      */
 #endif
 
  err:
 
     if (ret >= 0)
         BIO_printf(bio_s_out, "ACCEPT\n");
 
     if (buf != NULL)
         OPENSSL_free(buf);
     if (io != NULL)
         BIO_free_all(io);
 /*      if (ssl_bio != NULL) BIO_free(ssl_bio);*/
     return (ret);
 }
 
 static int rev_body(char *hostname, int s, int stype, unsigned char *context)
 {
     char *buf = NULL;
     int i;
     int ret = 1;
     SSL *con;
     BIO *io, *ssl_bio, *sbio;
 #ifndef OPENSSL_NO_KRB5
     KSSL_CTX *kctx;
 #endif
 
     buf = OPENSSL_malloc(bufsize);
     if (buf == NULL)
         return (0);
     io = BIO_new(BIO_f_buffer());
     ssl_bio = BIO_new(BIO_f_ssl());
     if ((io == NULL) || (ssl_bio == NULL))
         goto err;
 
     /* lets make the output buffer a reasonable size */
     if (!BIO_set_write_buffer_size(io, bufsize))
         goto err;
 
     if ((con = SSL_new(ctx)) == NULL)
         goto err;
 #ifndef OPENSSL_NO_TLSEXT
     if (s_tlsextdebug) {
         SSL_set_tlsext_debug_callback(con, tlsext_cb);
         SSL_set_tlsext_debug_arg(con, bio_s_out);
     }
 #endif
 #ifndef OPENSSL_NO_KRB5
     if ((kctx = kssl_ctx_new()) != NULL) {
         kssl_ctx_setstring(kctx, KSSL_SERVICE, KRB5SVC);
         kssl_ctx_setstring(kctx, KSSL_KEYTAB, KRB5KEYTAB);
     }
 #endif                          /* OPENSSL_NO_KRB5 */
     if (context)
         SSL_set_session_id_context(con, context, strlen((char *)context));
 
     sbio = BIO_new_socket(s, BIO_NOCLOSE);
     SSL_set_bio(con, sbio, sbio);
     SSL_set_accept_state(con);
 
     BIO_set_ssl(ssl_bio, con, BIO_CLOSE);
     BIO_push(io, ssl_bio);
 #ifdef CHARSET_EBCDIC
     io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io);
 #endif
 
     if (s_debug) {
         SSL_set_debug(con, 1);
         BIO_set_callback(SSL_get_rbio(con), bio_dump_callback);
         BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out);
     }
     if (s_msg) {
 #ifndef OPENSSL_NO_SSL_TRACE
         if (s_msg == 2)
             SSL_set_msg_callback(con, SSL_trace);
         else
 #endif
             SSL_set_msg_callback(con, msg_cb);
         SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out);
     }
 
     for (;;) {
         i = BIO_do_handshake(io);
         if (i > 0)
             break;
         if (!BIO_should_retry(io)) {
             BIO_puts(bio_err, "CONNECTION FAILURE\n");
             ERR_print_errors(bio_err);
             goto end;
         }
 #ifndef OPENSSL_NO_SRP
         if (BIO_should_io_special(io)
             && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
             BIO_printf(bio_s_out, "LOOKUP renego during accept\n");
             SRP_user_pwd_free(srp_callback_parm.user);
             srp_callback_parm.user =
                 SRP_VBASE_get1_by_user(srp_callback_parm.vb,
                                        srp_callback_parm.login);
             if (srp_callback_parm.user)
                 BIO_printf(bio_s_out, "LOOKUP done %s\n",
                            srp_callback_parm.user->info);
             else
                 BIO_printf(bio_s_out, "LOOKUP not successful\n");
             continue;
         }
 #endif
     }
     BIO_printf(bio_err, "CONNECTION ESTABLISHED\n");
     print_ssl_summary(bio_err, con);
 
     for (;;) {
         i = BIO_gets(io, buf, bufsize - 1);
         if (i < 0) {            /* error */
             if (!BIO_should_retry(io)) {
                 if (!s_quiet)
                     ERR_print_errors(bio_err);
                 goto err;
             } else {
                 BIO_printf(bio_s_out, "read R BLOCK\n");
 #ifndef OPENSSL_NO_SRP
                 if (BIO_should_io_special(io)
                     && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) {
                     BIO_printf(bio_s_out, "LOOKUP renego during read\n");
                     SRP_user_pwd_free(srp_callback_parm.user);
                     srp_callback_parm.user =
                         SRP_VBASE_get1_by_user(srp_callback_parm.vb,
                                                srp_callback_parm.login);
                     if (srp_callback_parm.user)
                         BIO_printf(bio_s_out, "LOOKUP done %s\n",
                                    srp_callback_parm.user->info);
                     else
                         BIO_printf(bio_s_out, "LOOKUP not successful\n");
                     continue;
                 }
 #endif
 #if defined(OPENSSL_SYS_NETWARE)
                 delay(1000);
 #elif !defined(OPENSSL_SYS_MSDOS) && !defined(__DJGPP__)
                 sleep(1);
 #endif
                 continue;
             }
         } else if (i == 0) {    /* end of input */
             ret = 1;
             BIO_printf(bio_err, "CONNECTION CLOSED\n");
             goto end;
         } else {
             char *p = buf + i - 1;
             while (i && (*p == '\n' || *p == '\r')) {
                 p--;
                 i--;
             }
             if (!s_ign_eof && i == 5 && !strncmp(buf, "CLOSE", 5)) {
                 ret = 1;
                 BIO_printf(bio_err, "CONNECTION CLOSED\n");
                 goto end;
             }
             BUF_reverse((unsigned char *)buf, NULL, i);
             buf[i] = '\n';
             BIO_write(io, buf, i + 1);
             for (;;) {
                 i = BIO_flush(io);
                 if (i > 0)
                     break;
                 if (!BIO_should_retry(io))
                     goto end;
             }
         }
     }
  end:
     /* make sure we re-use sessions */
     SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
 
  err:
 
     if (buf != NULL)
         OPENSSL_free(buf);
     if (io != NULL)
         BIO_free_all(io);
     return (ret);
 }
 
 #ifndef OPENSSL_NO_RSA
 static RSA MS_CALLBACK *tmp_rsa_cb(SSL *s, int is_export, int keylength)
 {
     BIGNUM *bn = NULL;
     static RSA *rsa_tmp = NULL;
 
     if (!rsa_tmp && ((bn = BN_new()) == NULL))
         BIO_printf(bio_err, "Allocation error in generating RSA key\n");
     if (!rsa_tmp && bn) {
         if (!s_quiet) {
             BIO_printf(bio_err, "Generating temp (%d bit) RSA key...",
                        keylength);
             (void)BIO_flush(bio_err);
         }
         if (!BN_set_word(bn, RSA_F4) || ((rsa_tmp = RSA_new()) == NULL) ||
             !RSA_generate_key_ex(rsa_tmp, keylength, bn, NULL)) {
             if (rsa_tmp)
                 RSA_free(rsa_tmp);
             rsa_tmp = NULL;
         }
         if (!s_quiet) {
             BIO_printf(bio_err, "\n");
             (void)BIO_flush(bio_err);
         }
         BN_free(bn);
     }
     return (rsa_tmp);
 }
 #endif
 
 #define MAX_SESSION_ID_ATTEMPTS 10
 static int generate_session_id(const SSL *ssl, unsigned char *id,
                                unsigned int *id_len)
 {
     unsigned int count = 0;
     do {
         if (RAND_bytes(id, *id_len) <= 0)
             return 0;
         /*
          * Prefix the session_id with the required prefix. NB: If our prefix
          * is too long, clip it - but there will be worse effects anyway, eg.
          * the server could only possibly create 1 session ID (ie. the
          * prefix!) so all future session negotiations will fail due to
          * conflicts.
          */
         memcpy(id, session_id_prefix,
                (strlen(session_id_prefix) < *id_len) ?
                strlen(session_id_prefix) : *id_len);
     }
     while (SSL_has_matching_session_id(ssl, id, *id_len) &&
            (++count < MAX_SESSION_ID_ATTEMPTS));
     if (count >= MAX_SESSION_ID_ATTEMPTS)
         return 0;
     return 1;
 }
 
 /*
  * By default s_server uses an in-memory cache which caches SSL_SESSION
  * structures without any serialisation. This hides some bugs which only
  * become apparent in deployed servers. By implementing a basic external
  * session cache some issues can be debugged using s_server.
  */
 
 typedef struct simple_ssl_session_st {
     unsigned char *id;
     unsigned int idlen;
     unsigned char *der;
     int derlen;
     struct simple_ssl_session_st *next;
 } simple_ssl_session;
 
 static simple_ssl_session *first = NULL;
 
 static int add_session(SSL *ssl, SSL_SESSION *session)
 {
     simple_ssl_session *sess;
     unsigned char *p;
 
     sess = OPENSSL_malloc(sizeof(simple_ssl_session));
     if (!sess) {
         BIO_printf(bio_err, "Out of memory adding session to external cache\n");
         return 0;
     }
 
     SSL_SESSION_get_id(session, &sess->idlen);
     sess->derlen = i2d_SSL_SESSION(session, NULL);
 
     sess->id = BUF_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen);
 
     sess->der = OPENSSL_malloc(sess->derlen);
     if (!sess->id || !sess->der) {
         BIO_printf(bio_err, "Out of memory adding session to external cache\n");
 
         if (sess->id)
             OPENSSL_free(sess->id);
         if (sess->der)
             OPENSSL_free(sess->der);
         OPENSSL_free(sess);
         return 0;
     }
     p = sess->der;
     i2d_SSL_SESSION(session, &p);
 
     sess->next = first;
     first = sess;
     BIO_printf(bio_err, "New session added to external cache\n");
     return 0;
 }
 
 static SSL_SESSION *get_session(SSL *ssl, unsigned char *id, int idlen,
                                 int *do_copy)
 {
     simple_ssl_session *sess;
     *do_copy = 0;
     for (sess = first; sess; sess = sess->next) {
         if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) {
             const unsigned char *p = sess->der;
             BIO_printf(bio_err, "Lookup session: cache hit\n");
             return d2i_SSL_SESSION(NULL, &p, sess->derlen);
         }
     }
     BIO_printf(bio_err, "Lookup session: cache miss\n");
     return NULL;
 }
 
 static void del_session(SSL_CTX *sctx, SSL_SESSION *session)
 {
     simple_ssl_session *sess, *prev = NULL;
     const unsigned char *id;
     unsigned int idlen;
     id = SSL_SESSION_get_id(session, &idlen);
     for (sess = first; sess; sess = sess->next) {
         if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) {
             if (prev)
                 prev->next = sess->next;
             else
                 first = sess->next;
             OPENSSL_free(sess->id);
             OPENSSL_free(sess->der);
             OPENSSL_free(sess);
             return;
         }
         prev = sess;
     }
 }
 
 static void init_session_cache_ctx(SSL_CTX *sctx)
 {
     SSL_CTX_set_session_cache_mode(sctx,
                                    SSL_SESS_CACHE_NO_INTERNAL |
                                    SSL_SESS_CACHE_SERVER);
     SSL_CTX_sess_set_new_cb(sctx, add_session);
     SSL_CTX_sess_set_get_cb(sctx, get_session);
     SSL_CTX_sess_set_remove_cb(sctx, del_session);
 }
 
 static void free_sessions(void)
 {
     simple_ssl_session *sess, *tsess;
     for (sess = first; sess;) {
         OPENSSL_free(sess->id);
         OPENSSL_free(sess->der);
         tsess = sess;
         sess = sess->next;
         OPENSSL_free(tsess);
     }
     first = NULL;
 }
Index: vendor-crypto/openssl/dist/apps/srp.c
===================================================================
--- vendor-crypto/openssl/dist/apps/srp.c	(revision 318896)
+++ vendor-crypto/openssl/dist/apps/srp.c	(revision 318897)
@@ -1,768 +1,766 @@
 /* apps/srp.c */
 /*
  * Written by Peter Sylvester (peter.sylvester@edelweb.fr) for the EdelKey
  * project and contributed to the OpenSSL project 2004.
  */
 /* ====================================================================
  * Copyright (c) 2004 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    licensing@OpenSSL.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 #include 
 
 #ifndef OPENSSL_NO_SRP
 # include 
 # include 
 # include 
 # include 
 # include 
 # include 
 # include 
 # include 
 # include 
 
 # include "apps.h"
 
 # undef PROG
 # define PROG srp_main
 
 # define BASE_SECTION    "srp"
 # define CONFIG_FILE "openssl.cnf"
 
 # define ENV_RANDFILE            "RANDFILE"
 
 # define ENV_DATABASE            "srpvfile"
 # define ENV_DEFAULT_SRP         "default_srp"
 
 static char *srp_usage[] = {
     "usage: srp [args] [user] \n",
     "\n",
     " -verbose        Talk alot while doing things\n",
     " -config file    A config file\n",
     " -name arg       The particular srp definition to use\n",
     " -srpvfile arg   The srp verifier file name\n",
     " -add            add an user and srp verifier\n",
     " -modify         modify the srp verifier of an existing user\n",
     " -delete         delete user from verifier file\n",
     " -list           list user\n",
     " -gn arg         g and N values to be used for new verifier\n",
     " -userinfo arg   additional info to be set for user\n",
     " -passin arg     input file pass phrase source\n",
     " -passout arg    output file pass phrase source\n",
 # ifndef OPENSSL_NO_ENGINE
     " -engine e         - use engine e, possibly a hardware device.\n",
 # endif
     NULL
 };
 
 # ifdef EFENCE
 extern int EF_PROTECT_FREE;
 extern int EF_PROTECT_BELOW;
 extern int EF_ALIGNMENT;
 # endif
 
 static CONF *conf = NULL;
 static char *section = NULL;
 
 # define VERBOSE if (verbose)
 # define VVERBOSE if (verbose>1)
 
 int MAIN(int, char **);
 
 static int get_index(CA_DB *db, char *id, char type)
 {
     char **pp;
     int i;
     if (id == NULL)
         return -1;
     if (type == DB_SRP_INDEX)
         for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
             pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
             if (pp[DB_srptype][0] == DB_SRP_INDEX
                 && !strcmp(id, pp[DB_srpid]))
                 return i;
     } else
         for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
             pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
 
             if (pp[DB_srptype][0] != DB_SRP_INDEX
                 && !strcmp(id, pp[DB_srpid]))
                 return i;
         }
 
     return -1;
 }
 
 static void print_entry(CA_DB *db, BIO *bio, int indx, int verbose, char *s)
 {
     if (indx >= 0 && verbose) {
         int j;
         char **pp = sk_OPENSSL_PSTRING_value(db->db->data, indx);
         BIO_printf(bio, "%s \"%s\"\n", s, pp[DB_srpid]);
         for (j = 0; j < DB_NUMBER; j++) {
             BIO_printf(bio_err, "  %d = \"%s\"\n", j, pp[j]);
         }
     }
 }
 
 static void print_index(CA_DB *db, BIO *bio, int indexindex, int verbose)
 {
     print_entry(db, bio, indexindex, verbose, "g N entry");
 }
 
 static void print_user(CA_DB *db, BIO *bio, int userindex, int verbose)
 {
     if (verbose > 0) {
         char **pp = sk_OPENSSL_PSTRING_value(db->db->data, userindex);
 
         if (pp[DB_srptype][0] != 'I') {
             print_entry(db, bio, userindex, verbose, "User entry");
             print_entry(db, bio, get_index(db, pp[DB_srpgN], 'I'), verbose,
                         "g N entry");
         }
 
     }
 }
 
 static int update_index(CA_DB *db, BIO *bio, char **row)
 {
     char **irow;
     int i;
 
     if ((irow =
          (char **)OPENSSL_malloc(sizeof(char *) * (DB_NUMBER + 1))) == NULL) {
         BIO_printf(bio_err, "Memory allocation failure\n");
         return 0;
     }
 
-    for (i = 0; i < DB_NUMBER; i++) {
+    for (i = 0; i < DB_NUMBER; i++)
         irow[i] = row[i];
-        row[i] = NULL;
-    }
     irow[DB_NUMBER] = NULL;
 
     if (!TXT_DB_insert(db->db, irow)) {
         BIO_printf(bio, "failed to update srpvfile\n");
         BIO_printf(bio, "TXT_DB error number %ld\n", db->db->error);
         OPENSSL_free(irow);
         return 0;
     }
     return 1;
 }
 
 static void lookup_fail(const char *name, char *tag)
 {
     BIO_printf(bio_err, "variable lookup failed for %s::%s\n", name, tag);
 }
 
 static char *srp_verify_user(const char *user, const char *srp_verifier,
                              char *srp_usersalt, const char *g, const char *N,
                              const char *passin, BIO *bio, int verbose)
 {
     char password[1024];
     PW_CB_DATA cb_tmp;
     char *verifier = NULL;
     char *gNid = NULL;
 
     cb_tmp.prompt_info = user;
     cb_tmp.password = passin;
 
     if (password_callback(password, 1024, 0, &cb_tmp) > 0) {
         VERBOSE BIO_printf(bio,
                            "Validating\n   user=\"%s\"\n srp_verifier=\"%s\"\n srp_usersalt=\"%s\"\n g=\"%s\"\n N=\"%s\"\n",
                            user, srp_verifier, srp_usersalt, g, N);
         BIO_printf(bio, "Pass %s\n", password);
 
         if (!
             (gNid =
              SRP_create_verifier(user, password, &srp_usersalt, &verifier, N,
                                  g))) {
             BIO_printf(bio, "Internal error validating SRP verifier\n");
         } else {
             if (strcmp(verifier, srp_verifier))
                 gNid = NULL;
             OPENSSL_free(verifier);
         }
     }
     return gNid;
 }
 
 static char *srp_create_user(char *user, char **srp_verifier,
                              char **srp_usersalt, char *g, char *N,
                              char *passout, BIO *bio, int verbose)
 {
     char password[1024];
     PW_CB_DATA cb_tmp;
     char *gNid = NULL;
     char *salt = NULL;
     cb_tmp.prompt_info = user;
     cb_tmp.password = passout;
 
     if (password_callback(password, 1024, 1, &cb_tmp) > 0) {
         VERBOSE BIO_printf(bio,
                            "Creating\n user=\"%s\"\n g=\"%s\"\n N=\"%s\"\n",
                            user, g, N);
         if (!
             (gNid =
              SRP_create_verifier(user, password, &salt, srp_verifier, N,
                                  g))) {
             BIO_printf(bio, "Internal error creating SRP verifier\n");
         } else
             *srp_usersalt = salt;
         VVERBOSE BIO_printf(bio, "gNid=%s salt =\"%s\"\n verifier =\"%s\"\n",
                             gNid, salt, *srp_verifier);
 
     }
     return gNid;
 }
 
 int MAIN(int argc, char **argv)
 {
     int add_user = 0;
     int list_user = 0;
     int delete_user = 0;
     int modify_user = 0;
     char *user = NULL;
 
     char *passargin = NULL, *passargout = NULL;
     char *passin = NULL, *passout = NULL;
     char *gN = NULL;
     int gNindex = -1;
     char **gNrow = NULL;
     int maxgN = -1;
 
     char *userinfo = NULL;
 
     int badops = 0;
     int ret = 1;
     int errors = 0;
     int verbose = 0;
     int doupdatedb = 0;
     char *configfile = NULL;
     char *dbfile = NULL;
     CA_DB *db = NULL;
     char **pp;
     int i;
     long errorline = -1;
     char *randfile = NULL;
     ENGINE *e = NULL;
     char *engine = NULL;
     char *tofree = NULL;
     DB_ATTR db_attr;
 
 # ifdef EFENCE
     EF_PROTECT_FREE = 1;
     EF_PROTECT_BELOW = 1;
     EF_ALIGNMENT = 0;
 # endif
 
     apps_startup();
 
     conf = NULL;
     section = NULL;
 
     if (bio_err == NULL)
         if ((bio_err = BIO_new(BIO_s_file())) != NULL)
             BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
 
     argc--;
     argv++;
     while (argc >= 1 && badops == 0) {
         if (strcmp(*argv, "-verbose") == 0)
             verbose++;
         else if (strcmp(*argv, "-config") == 0) {
             if (--argc < 1)
                 goto bad;
             configfile = *(++argv);
         } else if (strcmp(*argv, "-name") == 0) {
             if (--argc < 1)
                 goto bad;
             section = *(++argv);
         } else if (strcmp(*argv, "-srpvfile") == 0) {
             if (--argc < 1)
                 goto bad;
             dbfile = *(++argv);
         } else if (strcmp(*argv, "-add") == 0)
             add_user = 1;
         else if (strcmp(*argv, "-delete") == 0)
             delete_user = 1;
         else if (strcmp(*argv, "-modify") == 0)
             modify_user = 1;
         else if (strcmp(*argv, "-list") == 0)
             list_user = 1;
         else if (strcmp(*argv, "-gn") == 0) {
             if (--argc < 1)
                 goto bad;
             gN = *(++argv);
         } else if (strcmp(*argv, "-userinfo") == 0) {
             if (--argc < 1)
                 goto bad;
             userinfo = *(++argv);
         } else if (strcmp(*argv, "-passin") == 0) {
             if (--argc < 1)
                 goto bad;
             passargin = *(++argv);
         } else if (strcmp(*argv, "-passout") == 0) {
             if (--argc < 1)
                 goto bad;
             passargout = *(++argv);
         }
 # ifndef OPENSSL_NO_ENGINE
         else if (strcmp(*argv, "-engine") == 0) {
             if (--argc < 1)
                 goto bad;
             engine = *(++argv);
         }
 # endif
 
         else if (**argv == '-') {
  bad:
             BIO_printf(bio_err, "unknown option %s\n", *argv);
             badops = 1;
             break;
         } else
             break;
 
         argc--;
         argv++;
     }
 
     if (dbfile && configfile) {
         BIO_printf(bio_err,
                    "-dbfile and -configfile cannot be specified together.\n");
         badops = 1;
     }
     if (add_user + delete_user + modify_user + list_user != 1) {
         BIO_printf(bio_err,
                    "Exactly one of the options -add, -delete, -modify -list must be specified.\n");
         badops = 1;
     }
     if (delete_user + modify_user + delete_user == 1 && argc <= 0) {
         BIO_printf(bio_err,
                    "Need at least one user for options -add, -delete, -modify. \n");
         badops = 1;
     }
     if ((passin || passout) && argc != 1) {
         BIO_printf(bio_err,
                    "-passin, -passout arguments only valid with one user.\n");
         badops = 1;
     }
 
     if (badops) {
         for (pp = srp_usage; (*pp != NULL); pp++)
             BIO_printf(bio_err, "%s", *pp);
 
         BIO_printf(bio_err, " -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR,
                    LIST_SEPARATOR_CHAR);
         BIO_printf(bio_err,
                    "                 load the file (or the files in the directory) into\n");
         BIO_printf(bio_err, "                 the random number generator\n");
         goto err;
     }
 
     ERR_load_crypto_strings();
 
     e = setup_engine(bio_err, engine, 0);
 
     if (!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
         BIO_printf(bio_err, "Error getting passwords\n");
         goto err;
     }
 
     if (!dbfile) {
 
         /*****************************************************************/
         tofree = NULL;
         if (configfile == NULL)
             configfile = getenv("OPENSSL_CONF");
         if (configfile == NULL)
             configfile = getenv("SSLEAY_CONF");
         if (configfile == NULL) {
             const char *s = X509_get_default_cert_area();
             size_t len;
 
 # ifdef OPENSSL_SYS_VMS
             len = strlen(s) + sizeof(CONFIG_FILE);
             tofree = OPENSSL_malloc(len);
             if (!tofree) {
                 BIO_printf(bio_err, "Out of memory\n");
                 goto err;
             }
             strcpy(tofree, s);
 # else
             len = strlen(s) + sizeof(CONFIG_FILE) + 1;
             tofree = OPENSSL_malloc(len);
             if (!tofree) {
                 BIO_printf(bio_err, "Out of memory\n");
                 goto err;
             }
             BUF_strlcpy(tofree, s, len);
             BUF_strlcat(tofree, "/", len);
 # endif
             BUF_strlcat(tofree, CONFIG_FILE, len);
             configfile = tofree;
         }
 
         VERBOSE BIO_printf(bio_err, "Using configuration from %s\n",
                            configfile);
         conf = NCONF_new(NULL);
         if (NCONF_load(conf, configfile, &errorline) <= 0) {
             if (errorline <= 0)
                 BIO_printf(bio_err, "error loading the config file '%s'\n",
                            configfile);
             else
                 BIO_printf(bio_err, "error on line %ld of config file '%s'\n",
                            errorline, configfile);
             goto err;
         }
         if (tofree) {
             OPENSSL_free(tofree);
             tofree = NULL;
         }
 
         if (!load_config(bio_err, conf))
             goto err;
 
         /* Lets get the config section we are using */
         if (section == NULL) {
             VERBOSE BIO_printf(bio_err,
                                "trying to read " ENV_DEFAULT_SRP
                                " in \" BASE_SECTION \"\n");
 
             section = NCONF_get_string(conf, BASE_SECTION, ENV_DEFAULT_SRP);
             if (section == NULL) {
                 lookup_fail(BASE_SECTION, ENV_DEFAULT_SRP);
                 goto err;
             }
         }
 
         if (randfile == NULL && conf)
             randfile = NCONF_get_string(conf, BASE_SECTION, "RANDFILE");
 
         VERBOSE BIO_printf(bio_err,
                            "trying to read " ENV_DATABASE
                            " in section \"%s\"\n", section);
 
         if ((dbfile = NCONF_get_string(conf, section, ENV_DATABASE)) == NULL) {
             lookup_fail(section, ENV_DATABASE);
             goto err;
         }
 
     }
     if (randfile == NULL)
         ERR_clear_error();
     else
         app_RAND_load_file(randfile, bio_err, 0);
 
     VERBOSE BIO_printf(bio_err, "Trying to read SRP verifier file \"%s\"\n",
                        dbfile);
 
     db = load_index(dbfile, &db_attr);
     if (db == NULL)
         goto err;
 
     /* Lets check some fields */
     for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
         pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
 
         if (pp[DB_srptype][0] == DB_SRP_INDEX) {
             maxgN = i;
             if (gNindex < 0 && gN != NULL && !strcmp(gN, pp[DB_srpid]))
                 gNindex = i;
 
             print_index(db, bio_err, i, verbose > 1);
         }
     }
 
     VERBOSE BIO_printf(bio_err, "Database initialised\n");
 
     if (gNindex >= 0) {
         gNrow = sk_OPENSSL_PSTRING_value(db->db->data, gNindex);
         print_entry(db, bio_err, gNindex, verbose > 1, "Default g and N");
     } else if (maxgN > 0 && !SRP_get_default_gN(gN)) {
         BIO_printf(bio_err, "No g and N value for index \"%s\"\n", gN);
         goto err;
     } else {
         VERBOSE BIO_printf(bio_err, "Database has no g N information.\n");
         gNrow = NULL;
     }
 
     VVERBOSE BIO_printf(bio_err, "Starting user processing\n");
 
     if (argc > 0)
         user = *(argv++);
 
     while (list_user || user) {
         int userindex = -1;
         if (user)
             VVERBOSE BIO_printf(bio_err, "Processing user \"%s\"\n", user);
         if ((userindex = get_index(db, user, 'U')) >= 0) {
             print_user(db, bio_err, userindex, (verbose > 0) || list_user);
         }
 
         if (list_user) {
             if (user == NULL) {
                 BIO_printf(bio_err, "List all users\n");
 
                 for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
                     print_user(db, bio_err, i, 1);
                 }
                 list_user = 0;
             } else if (userindex < 0) {
                 BIO_printf(bio_err,
                            "user \"%s\" does not exist, ignored. t\n", user);
                 errors++;
             }
         } else if (add_user) {
             if (userindex >= 0) {
                 /* reactivation of a new user */
                 char **row =
                     sk_OPENSSL_PSTRING_value(db->db->data, userindex);
                 BIO_printf(bio_err, "user \"%s\" reactivated.\n", user);
                 row[DB_srptype][0] = 'V';
 
                 doupdatedb = 1;
             } else {
                 char *row[DB_NUMBER];
                 char *gNid;
                 row[DB_srpverifier] = NULL;
                 row[DB_srpsalt] = NULL;
                 row[DB_srpinfo] = NULL;
                 if (!
                     (gNid =
                      srp_create_user(user, &(row[DB_srpverifier]),
                                      &(row[DB_srpsalt]),
                                      gNrow ? gNrow[DB_srpsalt] : gN,
                                      gNrow ? gNrow[DB_srpverifier] : NULL,
                                      passout, bio_err, verbose))) {
                     BIO_printf(bio_err,
                                "Cannot create srp verifier for user \"%s\", operation abandoned .\n",
                                user);
                     errors++;
                     goto err;
                 }
                 row[DB_srpid] = BUF_strdup(user);
                 row[DB_srptype] = BUF_strdup("v");
                 row[DB_srpgN] = BUF_strdup(gNid);
 
                 if (!row[DB_srpid] || !row[DB_srpgN] || !row[DB_srptype]
                     || !row[DB_srpverifier] || !row[DB_srpsalt] || (userinfo
                                                                     &&
                                                                     (!(row
                                                                        [DB_srpinfo]
                                                                        =
                                                                        BUF_strdup
                                                                        (userinfo))))
                     || !update_index(db, bio_err, row)) {
                     if (row[DB_srpid])
                         OPENSSL_free(row[DB_srpid]);
                     if (row[DB_srpgN])
                         OPENSSL_free(row[DB_srpgN]);
                     if (row[DB_srpinfo])
                         OPENSSL_free(row[DB_srpinfo]);
                     if (row[DB_srptype])
                         OPENSSL_free(row[DB_srptype]);
                     if (row[DB_srpverifier])
                         OPENSSL_free(row[DB_srpverifier]);
                     if (row[DB_srpsalt])
                         OPENSSL_free(row[DB_srpsalt]);
                     goto err;
                 }
                 doupdatedb = 1;
             }
         } else if (modify_user) {
             if (userindex < 0) {
                 BIO_printf(bio_err,
                            "user \"%s\" does not exist, operation ignored.\n",
                            user);
                 errors++;
             } else {
 
                 char **row =
                     sk_OPENSSL_PSTRING_value(db->db->data, userindex);
                 char type = row[DB_srptype][0];
                 if (type == 'v') {
                     BIO_printf(bio_err,
                                "user \"%s\" already updated, operation ignored.\n",
                                user);
                     errors++;
                 } else {
                     char *gNid;
 
                     if (row[DB_srptype][0] == 'V') {
                         int user_gN;
                         char **irow = NULL;
                         VERBOSE BIO_printf(bio_err,
                                            "Verifying password for user \"%s\"\n",
                                            user);
                         if ((user_gN =
                              get_index(db, row[DB_srpgN], DB_SRP_INDEX)) >= 0)
                             irow =
                                 (char **)sk_OPENSSL_PSTRING_value(db->
                                                                   db->data,
                                                                   userindex);
 
                         if (!srp_verify_user
                             (user, row[DB_srpverifier], row[DB_srpsalt],
                              irow ? irow[DB_srpsalt] : row[DB_srpgN],
                              irow ? irow[DB_srpverifier] : NULL, passin,
                              bio_err, verbose)) {
                             BIO_printf(bio_err,
                                        "Invalid password for user \"%s\", operation abandoned.\n",
                                        user);
                             errors++;
                             goto err;
                         }
                     }
                     VERBOSE BIO_printf(bio_err,
                                        "Password for user \"%s\" ok.\n",
                                        user);
 
                     if (!
                         (gNid =
                          srp_create_user(user, &(row[DB_srpverifier]),
                                          &(row[DB_srpsalt]),
                                          gNrow ? gNrow[DB_srpsalt] : NULL,
                                          gNrow ? gNrow[DB_srpverifier] : NULL,
                                          passout, bio_err, verbose))) {
                         BIO_printf(bio_err,
                                    "Cannot create srp verifier for user \"%s\", operation abandoned.\n",
                                    user);
                         errors++;
                         goto err;
                     }
 
                     row[DB_srptype][0] = 'v';
                     row[DB_srpgN] = BUF_strdup(gNid);
 
                     if (!row[DB_srpid] || !row[DB_srpgN] || !row[DB_srptype]
                         || !row[DB_srpverifier] || !row[DB_srpsalt]
                         || (userinfo
                             && (!(row[DB_srpinfo] = BUF_strdup(userinfo)))))
                         goto err;
 
                     doupdatedb = 1;
                 }
             }
         } else if (delete_user) {
             if (userindex < 0) {
                 BIO_printf(bio_err,
                            "user \"%s\" does not exist, operation ignored. t\n",
                            user);
                 errors++;
             } else {
                 char **xpp =
                     sk_OPENSSL_PSTRING_value(db->db->data, userindex);
                 BIO_printf(bio_err, "user \"%s\" revoked. t\n", user);
 
                 xpp[DB_srptype][0] = 'R';
 
                 doupdatedb = 1;
             }
         }
         if (--argc > 0)
             user = *(argv++);
         else {
             user = NULL;
             list_user = 0;
         }
     }
 
     VERBOSE BIO_printf(bio_err, "User procession done.\n");
 
     if (doupdatedb) {
         /* Lets check some fields */
         for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
             pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
 
             if (pp[DB_srptype][0] == 'v') {
                 pp[DB_srptype][0] = 'V';
                 print_user(db, bio_err, i, verbose);
             }
         }
 
         VERBOSE BIO_printf(bio_err, "Trying to update srpvfile.\n");
         if (!save_index(dbfile, "new", db))
             goto err;
 
         VERBOSE BIO_printf(bio_err, "Temporary srpvfile created.\n");
         if (!rotate_index(dbfile, "new", "old"))
             goto err;
 
         VERBOSE BIO_printf(bio_err, "srpvfile updated.\n");
     }
 
     ret = (errors != 0);
  err:
     if (errors != 0)
         VERBOSE BIO_printf(bio_err, "User errors %d.\n", errors);
 
     VERBOSE BIO_printf(bio_err, "SRP terminating with code %d.\n", ret);
     if (tofree)
         OPENSSL_free(tofree);
     if (ret)
         ERR_print_errors(bio_err);
     if (randfile)
         app_RAND_write_file(randfile, bio_err);
     if (conf)
         NCONF_free(conf);
     if (db)
         free_index(db);
 
     release_engine(e);
     OBJ_cleanup();
     apps_shutdown();
     OPENSSL_EXIT(ret);
 }
 
 #else
 static void *dummy = &dummy;
 #endif
Index: vendor-crypto/openssl/dist/appveyor.yml
===================================================================
--- vendor-crypto/openssl/dist/appveyor.yml	(revision 318896)
+++ vendor-crypto/openssl/dist/appveyor.yml	(revision 318897)
@@ -1,60 +1,52 @@
 platform:
     - x86
     - x64
 
 environment:
     matrix:
         - VSVER: 9
         - VSVER: 10
         - VSVER: 11
         - VSVER: 12
         - VSVER: 14
 
 configuration:
     - plain
     - shared
 
 matrix:
     allow_failures:
         - platform: x64
           VSVER: 9
         - platform: x64
           VSVER: 10
         - platform: x64
           VSVER: 11
 
 before_build:
     - ps: >-
         If ($env:Platform -Match "x86") {
             $env:VCVARS_PLATFORM="x86"
             $env:TARGET="VC-WIN32"
             $env:DO="do_ms"
         } Else {
             $env:VCVARS_PLATFORM="amd64"
             $env:TARGET="VC-WIN64A"
             $env:DO="do_win64a"
         }
     - ps: >-
         If ($env:Configuration -Like "*shared*") {
             $env:MAK="ntdll.mak"
         } Else {
             $env:MAK="nt.mak"
         }
     - ps: $env:VSCOMNTOOLS=(Get-Content ("env:VS" + "$env:VSVER" + "0COMNTOOLS"))
     - call "%VSCOMNTOOLS%\..\..\VC\vcvarsall.bat" %VCVARS_PLATFORM%
     - perl Configure %TARGET% no-asm
     - call ms\%DO%
 
 build_script:
     - nmake /f ms\%MAK%
 
 test_script:
     - nmake /f ms\%MAK% test
-
-notifications:
-    - provider: Email
-      to:
-          - openssl-commits@openssl.org
-      on_build_success: false
-      on_build_failure: true
-      on_build_status_changed: true
Index: vendor-crypto/openssl/dist/config
===================================================================
--- vendor-crypto/openssl/dist/config	(revision 318896)
+++ vendor-crypto/openssl/dist/config	(revision 318897)
@@ -1,987 +1,996 @@
 #!/bin/sh
 #
 # OpenSSL config: determine the operating system and run ./Configure
 #
 # "config -h" for usage information.
 #
 #          this is a merge of minarch and GuessOS from the Apache Group.
 #          Originally written by Tim Hudson .
 
 # Original Apache Group comments on GuessOS
 
 # Simple OS/Platform guesser. Similar to config.guess but
 # much, much smaller. Since it was developed for use with
 # Apache, it follows under Apache's regular licensing
 # with one specific addition: Any changes or additions
 # to this script should be Emailed to the Apache
 # group (apache@apache.org) in general and to
 # Jim Jagielski (jim@jaguNET.com) in specific.
 #
 # Be as similar to the output of config.guess/config.sub
 # as possible.
 
 PREFIX=""
 SUFFIX=""
 TEST="false"
 EXE=""
 
 # pick up any command line args to config
 for i
 do
 case "$i" in 
 -d*) PREFIX="debug-";;
 -t*) TEST="true";;
 -h*) TEST="true"; cat </dev/null` || MACHINE="unknown"
 [ "$RELEASE" ] || RELEASE=`(uname -r) 2>/dev/null` || RELEASE="unknown"
 [ "$SYSTEM" ] || SYSTEM=`(uname -s) 2>/dev/null`  || SYSTEM="unknown"
 [ "$BUILD" ] || VERSION=`(uname -v) 2>/dev/null` || VERSION="unknown"
 
 
 # Now test for ISC and SCO, since it is has a braindamaged uname.
 #
 # We need to work around FreeBSD 1.1.5.1 
 (
 XREL=`uname -X 2>/dev/null | grep "^Release" | awk '{print $3}'`
 if [ "x$XREL" != "x" ]; then
     if [ -f /etc/kconfig ]; then
 	case "$XREL" in
 	    4.0|4.1)
 		    echo "${MACHINE}-whatever-isc4"; exit 0
 		;;
 	esac
     else
 	case "$XREL" in
 	    3.2v4.2)
 		echo "whatever-whatever-sco3"; exit 0
 		;;
 	    3.2v5.0*)
 		echo "whatever-whatever-sco5"; exit 0
 		;;
 	    4.2MP)
 		case "x${VERSION}" in
 		    x2.0*) echo "whatever-whatever-unixware20"; exit 0 ;;
 		    x2.1*) echo "whatever-whatever-unixware21"; exit 0 ;;
 		    x2*)   echo "whatever-whatever-unixware2";  exit 0 ;;
 		esac
 		;;
 	    4.2)
 		echo "whatever-whatever-unixware1"; exit 0
 		;;
 	    5*)
 		case "x${VERSION}" in
 		    # We hardcode i586 in place of ${MACHINE} for the
 		    # following reason. The catch is that even though Pentium
 		    # is minimum requirement for platforms in question,
 		    # ${MACHINE} gets always assigned to i386. Now, problem
 		    # with i386 is that it makes ./config pass 386 to
 		    # ./Configure, which in turn makes make generate
 		    # inefficient SHA-1 (for this moment) code.
 		    x[678]*)  echo "i586-sco-unixware7"; exit 0 ;;
 		esac
 		;;
 	esac
     fi
 fi
 # Now we simply scan though... In most cases, the SYSTEM info is enough
 #
 case "${SYSTEM}:${RELEASE}:${VERSION}:${MACHINE}" in
     MPE/iX:*)
 	MACHINE=`echo "$MACHINE" | sed -e 's/-/_/g'`
 	echo "parisc-hp-MPE/iX"; exit 0
 	;;
     A/UX:*)
 	echo "m68k-apple-aux3"; exit 0
 	;;
 
     AIX:[3-9]:4:*)
 	echo "${MACHINE}-ibm-aix"; exit 0
 	;;
 
     AIX:*:[5-9]:*)
 	echo "${MACHINE}-ibm-aix"; exit 0
 	;;
 
     AIX:*)
 	echo "${MACHINE}-ibm-aix3"; exit 0
 	;;
 
     BeOS:*:BePC)
     if [ -e /boot/develop/headers/be/bone ]; then
 		echo "beos-x86-bone"; exit 0
 	else
 		echo "beos-x86-r5"; exit 0
 	fi
 	;;
 
     dgux:*)
 	echo "${MACHINE}-dg-dgux"; exit 0
 	;;
 
     HI-UX:*)
 	echo "${MACHINE}-hi-hiux"; exit 0
 	;;
 
     HP-UX:*)
 	HPUXVER=`echo ${RELEASE}|sed -e 's/[^.]*.[0B]*//'`
 	case "$HPUXVER" in
 	    1[0-9].*)	# HPUX 10 and 11 targets are unified
 		echo "${MACHINE}-hp-hpux1x"; exit 0
 		;;
 	    *)
 		echo "${MACHINE}-hp-hpux"; exit 0
 		;;
 	esac
 	;;
 
     IRIX:5.*)
 	echo "mips2-sgi-irix"; exit 0
 	;;
 
     IRIX:6.*)
 	echo "mips3-sgi-irix"; exit 0
 	;;
 
     IRIX64:*)
 	echo "mips4-sgi-irix64"; exit 0
 	;;
 
     Linux:[2-9].*)
 	echo "${MACHINE}-whatever-linux2"; exit 0
 	;;
 
     Linux:1.*)
 	echo "${MACHINE}-whatever-linux1"; exit 0
 	;;
 
     GNU*)
 	echo "hurd-x86"; exit 0;
 	;;
 
     LynxOS:*)
 	echo "${MACHINE}-lynx-lynxos"; exit 0
 	;;
 
     BSD/OS:4.*)  # BSD/OS always says 386
 	echo "i486-whatever-bsdi4"; exit 0
 	;;
 
     BSD/386:*:*:*486*|BSD/OS:*:*:*:*486*)
         case `/sbin/sysctl -n hw.model` in
 	    Pentium*)
                 echo "i586-whatever-bsdi"; exit 0
                 ;;
             *)
                 echo "i386-whatever-bsdi"; exit 0
                 ;;
             esac;
 	;;
 
     BSD/386:*|BSD/OS:*)
 	echo "${MACHINE}-whatever-bsdi"; exit 0
 	;;
 
     FreeBSD:*:*:*386*)
         VERS=`echo ${RELEASE} | sed -e 's/[-(].*//'`
         MACH=`sysctl -n hw.model`
         ARCH='whatever'
         case ${MACH} in
            *386*       ) MACH="i386"     ;;
            *486*       ) MACH="i486"     ;;
            Pentium\ II*) MACH="i686"     ;;
            Pentium*    ) MACH="i586"     ;;
            *           ) MACH="$MACHINE" ;;
         esac
         case ${MACH} in
            i[0-9]86 ) ARCH="pc" ;;
         esac
         echo "${MACH}-${ARCH}-freebsd${VERS}"; exit 0
         ;;
 
     FreeBSD:*)
 	echo "${MACHINE}-whatever-freebsd"; exit 0
 	;;
 
     NetBSD:*:*:*386*)
         echo "`(/usr/sbin/sysctl -n hw.model || /sbin/sysctl -n hw.model) | sed 's,.*\(.\)86-class.*,i\186,'`-whatever-netbsd"; exit 0
 	;;
 
     NetBSD:*)
 	echo "${MACHINE}-whatever-netbsd"; exit 0
 	;;
 
     OpenBSD:*)
 	echo "${MACHINE}-whatever-openbsd"; exit 0
 	;;
 
     OpenUNIX:*)
 	echo "${MACHINE}-unknown-OpenUNIX${VERSION}"; exit 0
 	;;
 
     OSF1:*:*:*alpha*)
 	OSFMAJOR=`echo ${RELEASE}| sed -e 's/^V\([0-9]*\)\..*$/\1/'`
 	case "$OSFMAJOR" in
 	    4|5)
 		echo "${MACHINE}-dec-tru64"; exit 0
 		;;
 	    1|2|3)
 		echo "${MACHINE}-dec-osf"; exit 0
 		;;
 	    *)
 		echo "${MACHINE}-dec-osf"; exit 0
 		;;
 	esac
 	;;
 
     QNX:*)
 	case "$RELEASE" in
 	    4*)
 		echo "${MACHINE}-whatever-qnx4"
 		;;
 	    6*)
 		echo "${MACHINE}-whatever-qnx6"
 		;;
 	    *)
 		echo "${MACHINE}-whatever-qnx"
 		;;
 	esac
 	exit 0
 	;;
 
     Paragon*:*:*:*)
 	echo "i860-intel-osf1"; exit 0
 	;;
 
     Rhapsody:*)
 	echo "ppc-apple-rhapsody"; exit 0
 	;;
 
     Darwin:*)
 	case "$MACHINE" in
 	    Power*)
 		echo "ppc-apple-darwin${VERSION}"
 		;;
 	    *)
 		echo "i686-apple-darwin${VERSION}"
 		;;
 	esac
 	exit 0
 	;;
 
     SunOS:5.*)
 	echo "${MACHINE}-whatever-solaris2"; exit 0
 	;;
 
     SunOS:*)
 	echo "${MACHINE}-sun-sunos4"; exit 0
 	;;
 
     UNIX_System_V:4.*:*)
 	echo "${MACHINE}-whatever-sysv4"; exit 0
 	;;
 
     VOS:*:*:i786)
      echo "i386-stratus-vos"; exit 0
      ;;
 
     VOS:*:*:*)
      echo "hppa1.1-stratus-vos"; exit 0
      ;;
 
     *:4*:R4*:m88k)
 	echo "${MACHINE}-whatever-sysv4"; exit 0
 	;;
 
     DYNIX/ptx:4*:*)
 	echo "${MACHINE}-whatever-sysv4"; exit 0
 	;;
 
     *:4.0:3.0:3[34]?? | *:4.0:3.0:3[34]??,*)
 	echo "i486-ncr-sysv4"; exit 0
 	;;
 
     ULTRIX:*)
 	echo "${MACHINE}-unknown-ultrix"; exit 0
 	;;
 
     SINIX*|ReliantUNIX*)
 	echo "${MACHINE}-siemens-sysv4"; exit 0
 	;;
 
     POSIX-BC*)
 	echo "${MACHINE}-siemens-sysv4"; exit 0   # Here, $MACHINE == "BS2000"
 	;;
 
     machten:*)
        echo "${MACHINE}-tenon-${SYSTEM}"; exit 0;
        ;;
 
     library:*)
 	echo "${MACHINE}-ncr-sysv4"; exit 0
 	;;
 
     ConvexOS:*:11.0:*)
 	echo "${MACHINE}-v11-${SYSTEM}"; exit 0;
 	;;
 
     NEWS-OS:4.*)
 	echo "mips-sony-newsos4"; exit 0;
 	;;
 
+    # The following combinations are supported
+    # MINGW64* on x86_64 => mingw64
+    # MINGW32* on x86_64 => mingw
+    # MINGW32* on i?86 => mingw
+    #
+    # MINGW64* on i?86 isn't expected to work...
+    MINGW64*:*:*:x86_64)
+	echo "${MACHINE}-whatever-mingw64"; exit 0;
+	;;
     MINGW*)
 	echo "${MACHINE}-whatever-mingw"; exit 0;
 	;;
     CYGWIN*)
 	case "$RELEASE" in
 	    [bB]*|1.0|1.[12].*)
 		echo "${MACHINE}-whatever-cygwin_pre1.3"
 		;;
 	    *)
 		echo "${MACHINE}-whatever-cygwin"
 		;;
 	esac
 	exit 0
 	;;
 
     *"CRAY T3E")
        echo "t3e-cray-unicosmk"; exit 0;
        ;;
 
     *CRAY*)
        echo "j90-cray-unicos"; exit 0;
        ;;
 
     NONSTOP_KERNEL*)
        echo "nsr-tandem-nsk"; exit 0;
        ;;
 
     vxworks*)
        echo "${MACHINE}-whatever-vxworks"; exit 0;
        ;;
 esac
 
 #
 # Ugg. These are all we can determine by what we know about
 # the output of uname. Be more creative:
 #
 
 # Do the Apollo stuff first. Here, we just simply assume
 # that the existance of the /usr/apollo directory is proof
 # enough
 if [ -d /usr/apollo ]; then
     echo "whatever-apollo-whatever"
     exit 0
 fi
 
 # Now NeXT
 ISNEXT=`hostinfo 2>/dev/null`
 case "$ISNEXT" in
     *'NeXT Mach 3.3'*)
 	echo "whatever-next-nextstep3.3"; exit 0
 	;;
     *NeXT*)
 	echo "whatever-next-nextstep"; exit 0
 	;;
 esac
 
 # At this point we gone through all the one's
 # we know of: Punt
 
 echo "${MACHINE}-whatever-${SYSTEM}" 
 exit 0
 ) 2>/dev/null | (
 
 # ---------------------------------------------------------------------------
 # this is where the translation occurs into SSLeay terms
 # ---------------------------------------------------------------------------
 
 # Only set CC if not supplied already
 if [ -z "$CROSS_COMPILE$CC" ]; then
   GCCVER=`sh -c "gcc -dumpversion" 2>/dev/null`
   if [ "$GCCVER" != "" ]; then
     # then strip off whatever prefix egcs prepends the number with...
     # Hopefully, this will work for any future prefixes as well.
     GCCVER=`echo $GCCVER | LC_ALL=C sed 's/^[a-zA-Z]*\-//'`
     # Since gcc 3.1 gcc --version behaviour has changed.  gcc -dumpversion
     # does give us what we want though, so we use that.  We just just the
     # major and minor version numbers.
     # peak single digit before and after first dot, e.g. 2.95.1 gives 29
     GCCVER=`echo $GCCVER | sed 's/\([0-9]\)\.\([0-9]\).*/\1\2/'`
     CC=gcc
   else
     CC=cc
   fi
 fi
 GCCVER=${GCCVER:-0}
 if [ "$SYSTEM" = "HP-UX" ];then
   # By default gcc is a ILP32 compiler (with long long == 64).
   GCC_BITS="32"
   if [ $GCCVER -ge 30 ]; then
     # PA64 support only came in with gcc 3.0.x.
     # We check if the preprocessor symbol __LP64__ is defined...
     if echo "__LP64__" | gcc -v -E -x c - 2>/dev/null | grep "^__LP64__" 2>&1 > /dev/null; then
       : # __LP64__ has slipped through, it therefore is not defined
     else
       GCC_BITS="64"
     fi
   fi
 fi
 if [ "$SYSTEM" = "SunOS" ]; then
   if [ $GCCVER -ge 30 ]; then
     # 64-bit ABI isn't officially supported in gcc 3.0, but it appears
     # to be working, at the very least 'make test' passes...
     if gcc -v -E -x c /dev/null 2>&1 | grep __arch64__ > /dev/null; then
       GCC_ARCH="-m64"
     else
       GCC_ARCH="-m32"
     fi
   fi
   # check for WorkShop C, expected output is "cc: blah-blah C x.x"
   CCVER=`(cc -V 2>&1) 2>/dev/null | \
   	egrep -e '^cc: .* C [0-9]\.[0-9]' | \
 	sed 's/.* C \([0-9]\)\.\([0-9]\).*/\1\2/'`
   CCVER=${CCVER:-0}
   if [ $MACHINE != i86pc -a $CCVER -gt 40 ]; then
     CC=cc	# overrides gcc!!!
     if [ $CCVER -eq 50 ]; then
       echo "WARNING! Detected WorkShop C 5.0. Do make sure you have"
       echo "         patch #107357-01 or later applied."
       sleep 5
     fi
   fi
 fi
 
 if [ "${SYSTEM}-${MACHINE}" = "Linux-alpha" ]; then
   # check for Compaq C, expected output is "blah-blah C Vx.x"
   CCCVER=`(ccc -V 2>&1) 2>/dev/null | \
 	egrep -e '.* C V[0-9]\.[0-9]' | \
 	sed 's/.* C V\([0-9]\)\.\([0-9]\).*/\1\2/'`
   CCCVER=${CCCVER:-0}
   if [ $CCCVER -gt 60 ]; then
     CC=ccc	# overrides gcc!!! well, ccc outperforms inoticeably
 		# only on hash routines and des, otherwise gcc (2.95)
 		# keeps along rather tight...
   fi
 fi
 
 if [ "${SYSTEM}" = "AIX" ]; then	# favor vendor cc over gcc
     (cc) 2>&1 | grep -iv "not found" > /dev/null && CC=cc
 fi
 
 CCVER=${CCVER:-0}
 
 # read the output of the embedded GuessOS 
 read GUESSOS
 
 echo Operating system: $GUESSOS
 
 # now map the output into SSLeay terms ... really should hack into the
 # script above so we end up with values in vars but that would take
 # more time that I want to waste at the moment
 case "$GUESSOS" in
   uClinux*64*)
     OUT=uClinux-dist64
 	;;
   uClinux*)
     OUT=uClinux-dist
 	;;
   mips2-sgi-irix)
 	CPU=`(hinv -t cpu) 2>/dev/null | head -1 | sed 's/^CPU:[^R]*R\([0-9]*\).*/\1/'`
 	CPU=${CPU:-0}
 	if [ $CPU -ge 4000 ]; then
 		options="$options -mips2"
 	fi
 	OUT="irix-$CC"
 	;;
   mips3-sgi-irix)
 	#CPU=`(hinv -t cpu) 2>/dev/null | head -1 | sed 's/^CPU:[^R]*R\([0-9]*\).*/\1/'`
 	#CPU=${CPU:-0}
 	#if [ $CPU -ge 5000 ]; then
 	#	options="$options -mips4"
 	#else
 	#	options="$options -mips3"
 	#fi
 	OUT="irix-mips3-$CC"
 	;;
   mips4-sgi-irix64)
 	echo "WARNING! If you wish to build 64-bit library, then you have to"
 	echo "         invoke './Configure irix64-mips4-$CC' *manually*."
 	if [ "$TEST" = "false" -a -t 1 ]; then
 	  echo "         You have about 5 seconds to press Ctrl-C to abort."
 	  (trap "stty `stty -g`" 2 0; stty -icanon min 0 time 50; read waste) <&1
 	fi
         #CPU=`(hinv -t cpu) 2>/dev/null | head -1 | sed 's/^CPU:[^R]*R\([0-9]*\).*/\1/'`
         #CPU=${CPU:-0}
         #if [ $CPU -ge 5000 ]; then
         #        options="$options -mips4"
         #else
         #        options="$options -mips3"
         #fi
 	OUT="irix-mips3-$CC"
 	;;
   ppc-apple-rhapsody) OUT="rhapsody-ppc-cc" ;;
   ppc-apple-darwin*)
 	ISA64=`(sysctl -n hw.optional.64bitops) 2>/dev/null`
 	if [ "$ISA64" = "1" -a -z "$KERNEL_BITS" ]; then
 	    echo "WARNING! If you wish to build 64-bit library, then you have to"
 	    echo "         invoke './Configure darwin64-ppc-cc' *manually*."
 	    if [ "$TEST" = "false" -a -t 1 ]; then
 	      echo "         You have about 5 seconds to press Ctrl-C to abort."
 	      (trap "stty `stty -g`" 2 0; stty -icanon min 0 time 50; read waste) <&1
 	    fi
 	fi
 	if [ "$ISA64" = "1" -a "$KERNEL_BITS" = "64" ]; then
 	    OUT="darwin64-ppc-cc"
 	else
 	    OUT="darwin-ppc-cc"
 	fi ;;
   i?86-apple-darwin*)
 	ISA64=`(sysctl -n hw.optional.x86_64) 2>/dev/null`
 	if [ "$ISA64" = "1" -a -z "$KERNEL_BITS" ]; then
 	    echo "WARNING! If you wish to build 64-bit library, then you have to"
 	    echo "         invoke './Configure darwin64-x86_64-cc' *manually*."
 	    if [ "$TEST" = "false" -a -t 1 ]; then
 	      echo "         You have about 5 seconds to press Ctrl-C to abort."
 	      (trap "stty `stty -g`" 2 0; stty -icanon min 0 time 50; read waste) <&1
 	    fi
 	fi
 	if [ "$ISA64" = "1" -a "$KERNEL_BITS" = "64" ]; then
 	    OUT="darwin64-x86_64-cc"
 	else
 	    OUT="darwin-i386-cc"
 	fi ;;
   armv6+7-*-iphoneos)
 	options="$options -arch%20armv6 -arch%20armv7"
 	OUT="iphoneos-cross" ;;
   *-*-iphoneos)
 	options="$options -arch%20${MACHINE}"
 	OUT="iphoneos-cross" ;;
   alpha-*-linux2)
         ISA=`awk '/cpu model/{print$4;exit(0);}' /proc/cpuinfo`
 	case ${ISA:-generic} in
 	*[678])	OUT="linux-alpha+bwx-$CC" ;;
 	*)	OUT="linux-alpha-$CC" ;;
 	esac
 	if [ "$CC" = "gcc" ]; then
 	    case ${ISA:-generic} in
 	    EV5|EV45)		options="$options -mcpu=ev5";;
 	    EV56|PCA56)		options="$options -mcpu=ev56";;
 	    *)			options="$options -mcpu=ev6";;
 	    esac
 	fi
 	;;
   ppc64-*-linux2)
 	if [ -z "$KERNEL_BITS" ]; then
 	    echo "WARNING! If you wish to build 64-bit library, then you have to"
 	    echo "         invoke './Configure linux-ppc64' *manually*."
 	    if [ "$TEST" = "false" -a -t 1 ]; then
 		echo "         You have about 5 seconds to press Ctrl-C to abort."
 		(trap "stty `stty -g`" 2 0; stty -icanon min 0 time 50; read waste) <&1
 	    fi
 	fi
 	if [ "$KERNEL_BITS" = "64" ]; then
 	    OUT="linux-ppc64"
 	else
 	    OUT="linux-ppc"
 	    (echo "__LP64__" | gcc -E -x c - 2>/dev/null | grep "^__LP64__" 2>&1 > /dev/null) || options="$options -m32"
 	fi
 	;;
   ppc64le-*-linux2) OUT="linux-ppc64le" ;;
   ppc-*-linux2) OUT="linux-ppc" ;;
   mips64*-*-linux2)
 	echo "WARNING! If you wish to build 64-bit library, then you have to"
 	echo "         invoke './Configure linux64-mips64' *manually*."
 	if [ "$TEST" = "false" -a -t 1 ]; then
 	    echo "         You have about 5 seconds to press Ctrl-C to abort."
 	    (trap "stty `stty -g`" 2 0; stty -icanon min 0 time 50; read waste) <&1
 	fi
 	OUT="linux-mips64"
 	;;
   mips*-*-linux2) OUT="linux-mips32" ;;
   ppc60x-*-vxworks*) OUT="vxworks-ppc60x" ;;
   ppcgen-*-vxworks*) OUT="vxworks-ppcgen" ;;
   pentium-*-vxworks*) OUT="vxworks-pentium" ;;
   simlinux-*-vxworks*) OUT="vxworks-simlinux" ;;
   mips-*-vxworks*) OUT="vxworks-mips";;
   ia64-*-linux?) OUT="linux-ia64" ;;
   sparc64-*-linux2)
 	echo "WARNING! If you *know* that your GNU C supports 64-bit/V9 ABI"
 	echo "         and wish to build 64-bit library, then you have to"
 	echo "         invoke './Configure linux64-sparcv9' *manually*."
 	if [ "$TEST" = "false" -a -t 1 ]; then
 	  echo "          You have about 5 seconds to press Ctrl-C to abort."
 	  (trap "stty `stty -g`" 2 0; stty -icanon min 0 time 50; read waste) <&1
 	fi
 	OUT="linux-sparcv9" ;;
   sparc-*-linux2)
 	KARCH=`awk '/^type/{print$3;exit(0);}' /proc/cpuinfo`
 	case ${KARCH:-sun4} in
 	sun4u*)	OUT="linux-sparcv9" ;;
 	sun4m)	OUT="linux-sparcv8" ;;
 	sun4d)	OUT="linux-sparcv8" ;;
 	*)	OUT="linux-generic32"; options="$options -DB_ENDIAN" ;;
 	esac ;;
   parisc*-*-linux2)
 	# 64-bit builds under parisc64 linux are not supported and
 	# compiler is expected to generate 32-bit objects...
 	CPUARCH=`awk '/cpu family/{print substr($5,1,3); exit(0);}' /proc/cpuinfo`
 	CPUSCHEDULE=`awk '/^cpu.[ 	]*: PA/{print substr($3,3); exit(0);}' /proc/cpuinfo`
 
 	# ??TODO ??  Model transformations
 	# 0. CPU Architecture for the 1.1 processor has letter suffixes. We strip that off
 	#    assuming no further arch. identification will ever be used by GCC.
 	# 1. I'm most concerned about whether is a 7300LC is closer to a 7100 versus a 7100LC.
 	# 2. The variant 64-bit processors cause concern should GCC support explicit schedulers
 	#    for these chips in the future.
 	#         PA7300LC -> 7100LC (1.1)
 	#         PA8200   -> 8000   (2.0)
 	#         PA8500   -> 8000   (2.0)
 	#         PA8600   -> 8000   (2.0)
 
 	CPUSCHEDULE=`echo $CPUSCHEDULE|sed -e 's/7300LC/7100LC/' -e 's/8.00/8000/'`
 	# Finish Model transformations
 
 	options="$options -DB_ENDIAN -mschedule=$CPUSCHEDULE -march=$CPUARCH"
 	OUT="linux-generic32" ;;
   armv[1-3]*-*-linux2) OUT="linux-generic32" ;;
   armv[7-9]*-*-linux2) OUT="linux-armv4"; options="$options -march=armv7-a" ;;
   arm*-*-linux2) OUT="linux-armv4" ;;
   aarch64-*-linux2) OUT="linux-aarch64" ;;
   sh*b-*-linux2) OUT="linux-generic32"; options="$options -DB_ENDIAN" ;;
   sh*-*-linux2)  OUT="linux-generic32"; options="$options -DL_ENDIAN" ;;
   m68k*-*-linux2) OUT="linux-generic32"; options="$options -DB_ENDIAN" ;;
   s390-*-linux2) OUT="linux-generic32"; options="$options -DB_ENDIAN" ;;
   s390x-*-linux2)
 	# To be uncommented when glibc bug is fixed, see Configure...
 	#if egrep -e '^features.* highgprs' /proc/cpuinfo >/dev/null ; then
 	#  echo "WARNING! If you wish to build \"highgprs\" 32-bit library, then you"
 	#  echo "         have to invoke './Configure linux32-s390x' *manually*."
 	#  if [ "$TEST" = "false" -a -t -1 ]; then
 	#    echo "         You have about 5 seconds to press Ctrl-C to abort."
 	#    (trap "stty `stty -g`" 2 0; stty -icanon min 0 time 50; read waste) <&1
 	#  fi
 	#fi
 	OUT="linux64-s390x"
 	;;
   x86_64-*-linux?) OUT="linux-x86_64" ;;
   *86-*-linux2) OUT="linux-elf"
 	if [ "$GCCVER" -gt 28 ]; then
           if grep '^model.*Pentium' /proc/cpuinfo >/dev/null ; then
 	    options="$options -march=pentium"
           fi
           if grep '^model.*Pentium Pro' /proc/cpuinfo >/dev/null ; then
 	    options="$options -march=pentiumpro"
           fi
           if grep '^model.*K6' /proc/cpuinfo >/dev/null ; then
 	    options="$options -march=k6"
           fi
         fi ;;
   *-*-linux1) OUT="linux-aout" ;;
   *-*-linux2) OUT="linux-generic32" ;;
   sun4[uv]*-*-solaris2)
 	OUT="solaris-sparcv9-$CC"
 	ISA64=`(isalist) 2>/dev/null | grep sparcv9`
 	if [ "$ISA64" != "" -a "$KERNEL_BITS" = "" ]; then
 	    if [ "$CC" = "cc" -a $CCVER -ge 50 ]; then
 		echo "WARNING! If you wish to build 64-bit library, then you have to"
 		echo "         invoke './Configure solaris64-sparcv9-cc' *manually*."
 		if [ "$TEST" = "false" -a -t 1 ]; then
 		  echo "         You have about 5 seconds to press Ctrl-C to abort."
 		  (trap "stty `stty -g`" 2 0; stty -icanon min 0 time 50; read waste) <&1
 		fi
 	    elif [ "$CC" = "gcc" -a "$GCC_ARCH" = "-m64" ]; then
 		# $GCC_ARCH denotes default ABI chosen by compiler driver
 		# (first one found on the $PATH). I assume that user
 		# expects certain consistency with the rest of his builds
 		# and therefore switch over to 64-bit. 
 		OUT="solaris64-sparcv9-gcc"
 		echo "WARNING! If you wish to build 32-bit library, then you have to"
 		echo "         invoke './Configure solaris-sparcv9-gcc' *manually*."
 		if [ "$TEST" = "false" -a -t 1 ]; then
 		  echo "         You have about 5 seconds to press Ctrl-C to abort."
 		  (trap "stty `stty -g`" 2 0; stty -icanon min 0 time 50; read waste) <&1
 		fi
 	    elif [ "$GCC_ARCH" = "-m32" ]; then
 		echo "NOTICE! If you *know* that your GNU C supports 64-bit/V9 ABI"
 		echo "        and wish to build 64-bit library, then you have to"
 		echo "        invoke './Configure solaris64-sparcv9-gcc' *manually*."
 		if [ "$TEST" = "false" -a -t 1 ]; then
 		  echo "         You have about 5 seconds to press Ctrl-C to abort."
 		  (trap "stty `stty -g`" 2 0; stty -icanon min 0 time 50; read waste) <&1
 		fi
 	    fi
 	fi
 	if [ "$ISA64" != "" -a "$KERNEL_BITS" = "64" ]; then
 	    OUT="solaris64-sparcv9-$CC"
 	fi
 	;;
   sun4m-*-solaris2)	OUT="solaris-sparcv8-$CC" ;;
   sun4d-*-solaris2)	OUT="solaris-sparcv8-$CC" ;;
   sun4*-*-solaris2)	OUT="solaris-sparcv7-$CC" ;;
   *86*-*-solaris2)
 	ISA64=`(isalist) 2>/dev/null | grep amd64`
 	if [ "$ISA64" != "" -a ${KERNEL_BITS:-64} -eq 64 ]; then
 	    OUT="solaris64-x86_64-$CC"
 	else
 	    OUT="solaris-x86-$CC"
 	    if [ `uname -r | sed -e 's/5\.//'` -lt 10 ]; then
 		options="$options no-sse2"
 	    fi
 	fi
 	;;
   *-*-sunos4)		OUT="sunos-$CC" ;;
 
   *86*-*-bsdi4)		OUT="BSD-x86-elf"; options="$options no-sse2 -ldl" ;;
   alpha*-*-*bsd*)	OUT="BSD-generic64"; options="$options -DL_ENDIAN" ;;
   powerpc64-*-*bsd*)	OUT="BSD-generic64"; options="$options -DB_ENDIAN" ;;
   sparc64-*-*bsd*)	OUT="BSD-sparc64" ;;
   ia64-*-*bsd*)		OUT="BSD-ia64" ;;
   amd64-*-*bsd*)	OUT="BSD-x86_64" ;;
   *86*-*-*bsd*)		# mimic ld behaviour when it's looking for libc...
 			if [ -L /usr/lib/libc.so ]; then	# [Free|Net]BSD
 			    libc=/usr/lib/libc.so
 			else					# OpenBSD
 			    # ld searches for highest libc.so.* and so do we
 			    libc=`(ls /usr/lib/libc.so.* /lib/libc.so.* | tail -1) 2>/dev/null`
 			fi
 			case "`(file -L $libc) 2>/dev/null`" in
 			*ELF*)	OUT="BSD-x86-elf" ;;
 			*)	OUT="BSD-x86"; options="$options no-sse2" ;;
 			esac ;;
   *-*-*bsd*)		OUT="BSD-generic32" ;;
 
   *-*-osf)		OUT="osf1-alpha-cc" ;;
   *-*-tru64)		OUT="tru64-alpha-cc" ;;
   *-*-[Uu]nix[Ww]are7)
 	if [ "$CC" = "gcc" ]; then
 	  OUT="unixware-7-gcc" ; options="$options no-sse2"
 	else    
 	  OUT="unixware-7" ; options="$options no-sse2 -D__i386__"
 	fi
 	;;
   *-*-[Uu]nix[Ww]are20*) OUT="unixware-2.0"; options="$options no-sse2 no-sha512" ;;
   *-*-[Uu]nix[Ww]are21*) OUT="unixware-2.1"; options="$options no-sse2 no-sha512" ;;
   *-*-vos)
 	options="$options no-threads no-shared no-asm no-dso"
 	EXE=".pm"
 	OUT="vos-$CC" ;;
   BS2000-siemens-sysv4) OUT="BS2000-OSD" ;;
   RM*-siemens-sysv4) OUT="ReliantUNIX" ;;
   *-siemens-sysv4) OUT="SINIX" ;;
   *-hpux1*)
 	if [ $CC = "gcc" -a $GCC_BITS = "64" ]; then
 	    OUT="hpux64-parisc2-gcc"
 	fi
 	[ "$KERNEL_BITS" ] || KERNEL_BITS=`(getconf KERNEL_BITS) 2>/dev/null`
 	KERNEL_BITS=${KERNEL_BITS:-32}
 	CPU_VERSION=`(getconf CPU_VERSION) 2>/dev/null`
 	CPU_VERSION=${CPU_VERSION:-0}
 	# See  for further info on CPU_VERSION.
 	if   [ $CPU_VERSION -ge 768 ]; then	# IA-64 CPU
 	     if [ $KERNEL_BITS -eq 64 -a "$CC" = "cc" ]; then
 	        OUT="hpux64-ia64-cc"
              else
 	        OUT="hpux-ia64-cc"
              fi
 	elif [ $CPU_VERSION -ge 532 ]; then	# PA-RISC 2.x CPU
 	     OUT=${OUT:-"hpux-parisc2-${CC}"}
 	     if [ $KERNEL_BITS -eq 64 -a "$CC" = "cc" ]; then
 		echo "WARNING! If you wish to build 64-bit library then you have to"
 		echo "         invoke './Configure hpux64-parisc2-cc' *manually*."
 		if [ "$TEST" = "false" -a -t 1 ]; then
 		  echo "         You have about 5 seconds to press Ctrl-C to abort."
 		  (trap "stty `stty -g`" 2 0; stty -icanon min 0 time 50; read waste) <&1
 		fi
 	     fi
 	elif [ $CPU_VERSION -ge 528 ]; then	# PA-RISC 1.1+ CPU
 	     OUT="hpux-parisc-${CC}"
 	elif [ $CPU_VERSION -ge 523 ]; then	# PA-RISC 1.0 CPU
 	     OUT="hpux-parisc-${CC}"
 	else					# Motorola(?) CPU
 	     OUT="hpux-$CC"
 	fi
 	options="$options -D_REENTRANT" ;;
   *-hpux)	OUT="hpux-parisc-$CC" ;;
   *-aix)
 	[ "$KERNEL_BITS" ] || KERNEL_BITS=`(getconf KERNEL_BITMODE) 2>/dev/null`
 	KERNEL_BITS=${KERNEL_BITS:-32}
 	OBJECT_MODE=${OBJECT_MODE:-32}
 	if [ "$CC" = "gcc" ]; then
 	    OUT="aix-gcc"
           if [ $OBJECT_MODE -eq 64 ]; then
             echo 'Your $OBJECT_MODE was found to be set to 64'
             OUT="aix64-gcc"
           fi
 	elif [ $OBJECT_MODE -eq 64 ]; then
 	    echo 'Your $OBJECT_MODE was found to be set to 64' 
 	    OUT="aix64-cc"
 	else
 	    OUT="aix-cc"
 	    if [ $KERNEL_BITS -eq 64 ]; then
 		echo "WARNING! If you wish to build 64-bit kit, then you have to"
 		echo "         invoke './Configure aix64-cc' *manually*."
 		if [ "$TEST" = "false" -a -t 1 ]; then
 		    echo "         You have ~5 seconds to press Ctrl-C to abort."
 		    (trap "stty `stty -g`" 2 0; stty -icanon min 0 time 50; read waste) <&1
 		fi
 	    fi
 	fi
 	if (lsattr -E -O -l `lsdev -c processor|awk '{print$1;exit}'` | grep -i powerpc) >/dev/null 2>&1; then
 	    :	# this applies even to Power3 and later, as they return PowerPC_POWER[345]
 	else
 	    options="$options no-asm"
 	fi
 	;;
   # these are all covered by the catchall below
   # *-dgux) OUT="dgux" ;;
   mips-sony-newsos4) OUT="newsos4-gcc" ;;
   *-*-cygwin_pre1.3) OUT="Cygwin-pre1.3" ;;
   i[3456]86-*-cygwin) OUT="Cygwin" ;;
   *-*-cygwin) OUT="Cygwin-${MACHINE}" ;;
   t3e-cray-unicosmk) OUT="cray-t3e" ;;
   j90-cray-unicos) OUT="cray-j90" ;;
   nsr-tandem-nsk) OUT="tandem-c89" ;;
   beos-*) OUT="$GUESSOS" ;;
   x86pc-*-qnx6) OUT="QNX6-i386" ;;
   *-*-qnx6) OUT="QNX6" ;;
   x86-*-android|i?86-*-android) OUT="android-x86" ;;
   armv[7-9]*-*-android) OUT="android-armv7" ;;
   *) OUT=`echo $GUESSOS | awk -F- '{print $3}'`;;
 esac
 
 # NB: This atalla support has been superceded by the ENGINE support
 # That contains its own header and definitions anyway. Support can
 # be enabled or disabled on any supported platform without external
 # headers, eg. by adding the "hw-atalla" switch to ./config or
 # perl Configure
 #
 # See whether we can compile Atalla support
 #if [ -f /usr/include/atasi.h ]
 #then
 #  options="$options -DATALLA"
 #fi
 
 if expr "$options" : '.*no\-asm' > /dev/null; then :; else
   sh -c "$CROSS_COMPILE${CC:-gcc} -Wa,--help -c -o /tmp/null.$$.o -x assembler /dev/null && rm /tmp/null.$$.o" 2>&1 | \
   grep \\--noexecstack >/dev/null && \
   options="$options -Wa,--noexecstack"
 fi
 
 # gcc < 2.8 does not support -march=ultrasparc
 if [ "$OUT" = solaris-sparcv9-gcc -a $GCCVER -lt 28 ]
 then
   echo "WARNING! Falling down to 'solaris-sparcv8-gcc'."
   echo "         Upgrade to gcc-2.8 or later."
   sleep 5
   OUT=solaris-sparcv8-gcc
 fi
 if [ "$OUT" = "linux-sparcv9" -a $GCCVER -lt 28 ]
 then
   echo "WARNING! Falling down to 'linux-sparcv8'."
   echo "         Upgrade to gcc-2.8 or later."
   sleep 5
   OUT=linux-sparcv8
 fi
 
 case "$GUESSOS" in
   i386-*) options="$options 386" ;;
 esac
 
 for i in aes bf camellia cast des dh dsa ec hmac idea md2 md5 mdc2 rc2 rc4 rc5 ripemd rsa seed sha
 do
   if [ ! -d crypto/$i ]
   then
     options="$options no-$i"
   fi
 done
 
 # Discover Kerberos 5 (since it's still a prototype, we don't
 # do any guesses yet, that's why this section is commented away.
 #if [ -d /usr/kerberos ]; then
 #    krb5_dir=/usr/kerberos
 #    if [ \( -f $krb5_dir/lib/libgssapi_krb5.a -o -f $krb5_dir/lib/libgssapi_krb5.so* \)\
 #	-a \( -f $krb5_dir/lib/libkrb5.a -o -f $krb5_dir/lib/libkrb5.so* \)\
 #	-a \( -f $krb5_dir/lib/libcom_err.a -o -f $krb5_dir/lib/libcom_err.so* \)\
 #	-a \( -f $krb5_dir/lib/libk5crypto.a -o -f $krb5_dir/lib/libk5crypto.so* \)\
 #	-a \( -f $krb5_dir/include/krb5.h \) ]; then
 #	options="$options --with-krb5-flavor=MIT"
 #    fi
 #elif [ -d /usr/heimdal ]; then
 #    krb5_dir=/usr/heimdal
 #    if [ \( -f $krb5_dir/lib/libgssapi.a -o -f $krb5_dir/lib/libgssapi.so* \)\
 #	-a \( -f $krb5_dir/lib/libkrb5.a -o -f $krb5_dir/lib/libkrb5.so* \)\
 #	-a \( -f $krb5_dir/lib/libcom_err.a -o -f $krb5_dir/lib/libcom_err.so* \)\
 #	-a \( -f $krb5_dir/include/krb5.h \) ]; then
 #	options="$options --with-krb5-flavor=Heimdal"
 #    fi
 #fi
 
 if [ -z "$OUT" ]; then
   OUT="$CC"
 fi
 
 if [ ".$PERL" = . ] ; then
 	for i in . `echo $PATH | sed 's/:/ /g'`; do
 		if [ -f "$i/perl5$EXE" ] ; then
 			PERL="$i/perl5$EXE"
 			break;
 		fi;
 	done
 fi
 
 if [ ".$PERL" = . ] ; then
 	for i in . `echo $PATH | sed 's/:/ /g'`; do
 		if [ -f "$i/perl$EXE" ] ; then
 			if "$i/perl$EXE" -e 'exit($]<5.0)'; then
 				PERL="$i/perl$EXE"
 				break;
 			fi;
 		fi;
 	done
 fi
 
 if [ ".$PERL" = . ] ; then
 	echo "You need Perl 5."
 	exit 1
 fi
 
 # run Configure to check to see if we need to specify the 
 # compiler for the platform ... in which case we add it on
 # the end ... otherwise we leave it off
 
 $PERL ./Configure LIST | grep "$OUT-$CC" > /dev/null
 if [ $? = "0" ]; then
   OUT="$OUT-$CC"
 fi
 
 OUT="$PREFIX$OUT"
 
 $PERL ./Configure LIST | grep "$OUT" > /dev/null
 if [ $? = "0" ]; then
   echo Configuring for $OUT
 
   if [ "$TEST" = "true" ]; then
     echo $PERL ./Configure $OUT $options
   else
     $PERL ./Configure $OUT $options
   fi
 else
   echo "This system ($OUT) is not supported. See file INSTALL for details."
 fi
 )
Index: vendor-crypto/openssl/dist/crypto/aes/Makefile
===================================================================
--- vendor-crypto/openssl/dist/crypto/aes/Makefile	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/aes/Makefile	(revision 318897)
@@ -1,171 +1,171 @@
 #
 # crypto/aes/Makefile
 #
 
 DIR=	aes
 TOP=	../..
 CC=	cc
 CPP=	$(CC) -E
 INCLUDES=
 CFLAG=-g
 MAKEFILE=	Makefile
 AR=		ar r
 
 AES_ENC=aes_core.o aes_cbc.o
 
 CFLAGS= $(INCLUDES) $(CFLAG)
 ASFLAGS= $(INCLUDES) $(ASFLAG)
 AFLAGS= $(ASFLAGS)
 
 GENERAL=Makefile
 #TEST=aestest.c
 TEST=
 APPS=
 
 LIB=$(TOP)/libcrypto.a
 LIBSRC=aes_core.c aes_misc.c aes_ecb.c aes_cbc.c aes_cfb.c aes_ofb.c \
        aes_ctr.c aes_ige.c aes_wrap.c
 LIBOBJ=aes_misc.o aes_ecb.o aes_cfb.o aes_ofb.o aes_ctr.o aes_ige.o aes_wrap.o \
        $(AES_ENC)
 
 SRC= $(LIBSRC)
 
 EXHEADER= aes.h
 HEADER= aes_locl.h $(EXHEADER)
 
 ALL=    $(GENERAL) $(SRC) $(HEADER)
 
 top:
 	(cd ../..; $(MAKE) DIRS=crypto SDIRS=$(DIR) sub_all)
 
 all:	lib
 
 lib:	$(LIBOBJ)
 	$(AR) $(LIB) $(LIBOBJ)
 	$(RANLIB) $(LIB) || echo Never mind.
 	@touch lib
 
 aes-ia64.s: asm/aes-ia64.S
 	$(CC) $(CFLAGS) -E asm/aes-ia64.S > $@
 
 aes-586.s:	asm/aes-586.pl ../perlasm/x86asm.pl
 	$(PERL) asm/aes-586.pl $(PERLASM_SCHEME) $(CFLAGS) $(PROCESSOR) > $@
 vpaes-x86.s:	asm/vpaes-x86.pl ../perlasm/x86asm.pl
 	$(PERL) asm/vpaes-x86.pl $(PERLASM_SCHEME) $(CFLAGS) $(PROCESSOR) > $@
 aesni-x86.s:	asm/aesni-x86.pl ../perlasm/x86asm.pl
 	$(PERL) asm/aesni-x86.pl $(PERLASM_SCHEME) $(CFLAGS) $(PROCESSOR) > $@
 
 aes-x86_64.s: asm/aes-x86_64.pl
 	$(PERL) asm/aes-x86_64.pl $(PERLASM_SCHEME) > $@
 vpaes-x86_64.s:	asm/vpaes-x86_64.pl
 	$(PERL) asm/vpaes-x86_64.pl $(PERLASM_SCHEME) > $@
 bsaes-x86_64.s:	asm/bsaes-x86_64.pl
 	$(PERL) asm/bsaes-x86_64.pl $(PERLASM_SCHEME) > $@
 aesni-x86_64.s: asm/aesni-x86_64.pl
 	$(PERL) asm/aesni-x86_64.pl $(PERLASM_SCHEME) > $@
 aesni-sha1-x86_64.s:	asm/aesni-sha1-x86_64.pl
 	$(PERL) asm/aesni-sha1-x86_64.pl $(PERLASM_SCHEME) > $@
 aesni-sha256-x86_64.s:	asm/aesni-sha256-x86_64.pl
 	$(PERL) asm/aesni-sha256-x86_64.pl $(PERLASM_SCHEME) > $@
 aesni-mb-x86_64.s:	asm/aesni-mb-x86_64.pl
 	$(PERL) asm/aesni-mb-x86_64.pl $(PERLASM_SCHEME) > $@
 
 aes-sparcv9.s: asm/aes-sparcv9.pl
 	$(PERL) asm/aes-sparcv9.pl $(CFLAGS) > $@
 aest4-sparcv9.s: asm/aest4-sparcv9.pl ../perlasm/sparcv9_modes.pl
 	$(PERL) asm/aest4-sparcv9.pl $(CFLAGS) > $@
 
 aes-ppc.s:	asm/aes-ppc.pl
 	$(PERL) asm/aes-ppc.pl $(PERLASM_SCHEME) $@
 vpaes-ppc.s:	asm/vpaes-ppc.pl
 	$(PERL) asm/vpaes-ppc.pl $(PERLASM_SCHEME) $@
 aesp8-ppc.s:	asm/aesp8-ppc.pl
 	$(PERL) asm/aesp8-ppc.pl $(PERLASM_SCHEME) $@
 
 aes-parisc.s:	asm/aes-parisc.pl
 	$(PERL) asm/aes-parisc.pl $(PERLASM_SCHEME) $@
 
 aes-mips.S:	asm/aes-mips.pl
 	$(PERL) asm/aes-mips.pl $(PERLASM_SCHEME) $@
 
 aesv8-armx.S:	asm/aesv8-armx.pl
 	$(PERL) asm/aesv8-armx.pl $(PERLASM_SCHEME) $@
 aesv8-armx.o:	aesv8-armx.S
 
 # GNU make "catch all"
 aes-%.S:	asm/aes-%.pl;	$(PERL) $< $(PERLASM_SCHEME) > $@
 aes-armv4.o:	aes-armv4.S
 bsaes-%.S:	asm/bsaes-%.pl;	$(PERL) $< $(PERLASM_SCHEME) $@
 bsaes-armv7.o:	bsaes-armv7.S
 
 files:
 	$(PERL) $(TOP)/util/files.pl "AES_ENC=$(AES_ENC)" Makefile >> $(TOP)/MINFO
 
 links:
 	@$(PERL) $(TOP)/util/mklink.pl ../../include/openssl $(EXHEADER)
 	@$(PERL) $(TOP)/util/mklink.pl ../../test $(TEST)
 	@$(PERL) $(TOP)/util/mklink.pl ../../apps $(APPS)
 
 install:
 	@[ -n "$(INSTALLTOP)" ] # should be set by top Makefile...
 	@headerlist="$(EXHEADER)"; for i in $$headerlist ; \
 	do  \
 	(cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i; \
 	chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i ); \
 	done;
 
 tags:
 	ctags $(SRC)
 
 tests:
 
 lint:
 	lint -DLINT $(INCLUDES) $(SRC)>fluff
 
 update: depend
 
 depend:
 	@[ -n "$(MAKEDEPEND)" ] # should be set by upper Makefile...
 	$(MAKEDEPEND) -- $(CFLAG) $(INCLUDES) $(DEPFLAG) -- $(PROGS) $(LIBSRC)
 
 dclean:
 	$(PERL) -pe 'if (/^# DO NOT DELETE THIS LINE/) {print; exit(0);}' $(MAKEFILE) >Makefile.new
 	mv -f Makefile.new $(MAKEFILE)
 
 clean:
-	rm -f *.s *.o *.obj lib tags core .pure .nfs* *.old *.bak fluff
+	rm -f *.s *.S *.o *.obj lib tags core .pure .nfs* *.old *.bak fluff
 
 # DO NOT DELETE THIS LINE -- make depend depends on it.
 
 aes_cbc.o: ../../include/openssl/aes.h ../../include/openssl/modes.h
 aes_cbc.o: ../../include/openssl/opensslconf.h aes_cbc.c
 aes_cfb.o: ../../include/openssl/aes.h ../../include/openssl/modes.h
 aes_cfb.o: ../../include/openssl/opensslconf.h aes_cfb.c
 aes_core.o: ../../include/openssl/aes.h ../../include/openssl/e_os2.h
 aes_core.o: ../../include/openssl/opensslconf.h aes_core.c aes_locl.h
 aes_ctr.o: ../../include/openssl/aes.h ../../include/openssl/modes.h
 aes_ctr.o: ../../include/openssl/opensslconf.h aes_ctr.c
 aes_ecb.o: ../../include/openssl/aes.h ../../include/openssl/e_os2.h
 aes_ecb.o: ../../include/openssl/opensslconf.h aes_ecb.c aes_locl.h
 aes_ige.o: ../../e_os.h ../../include/openssl/aes.h ../../include/openssl/bio.h
 aes_ige.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 aes_ige.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 aes_ige.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 aes_ige.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 aes_ige.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 aes_ige.o: ../../include/openssl/symhacks.h ../cryptlib.h aes_ige.c aes_locl.h
 aes_misc.o: ../../include/openssl/aes.h ../../include/openssl/crypto.h
 aes_misc.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
 aes_misc.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 aes_misc.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 aes_misc.o: ../../include/openssl/symhacks.h aes_locl.h aes_misc.c
 aes_ofb.o: ../../include/openssl/aes.h ../../include/openssl/modes.h
 aes_ofb.o: ../../include/openssl/opensslconf.h aes_ofb.c
 aes_wrap.o: ../../e_os.h ../../include/openssl/aes.h
 aes_wrap.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h
 aes_wrap.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
 aes_wrap.o: ../../include/openssl/err.h ../../include/openssl/lhash.h
 aes_wrap.o: ../../include/openssl/modes.h ../../include/openssl/opensslconf.h
 aes_wrap.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 aes_wrap.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 aes_wrap.o: ../../include/openssl/symhacks.h ../cryptlib.h aes_wrap.c
Index: vendor-crypto/openssl/dist/crypto/aes/asm/aesni-sha1-x86_64.pl
===================================================================
--- vendor-crypto/openssl/dist/crypto/aes/asm/aesni-sha1-x86_64.pl	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/aes/asm/aesni-sha1-x86_64.pl	(revision 318897)
@@ -1,2057 +1,2058 @@
 #!/usr/bin/env perl
 #
 # ====================================================================
 # Written by Andy Polyakov  for the OpenSSL
 # project. The module is, however, dual licensed under OpenSSL and
 # CRYPTOGAMS licenses depending on where you obtain it. For further
 # details see http://www.openssl.org/~appro/cryptogams/.
 # ====================================================================
 #
 # June 2011
 #
 # This is AESNI-CBC+SHA1 "stitch" implementation. The idea, as spelled
 # in http://download.intel.com/design/intarch/papers/323686.pdf, is
 # that since AESNI-CBC encrypt exhibit *very* low instruction-level
 # parallelism, interleaving it with another algorithm would allow to
 # utilize processor resources better and achieve better performance.
 # SHA1 instruction sequences(*) are taken from sha1-x86_64.pl and
 # AESNI code is weaved into it. Below are performance numbers in
 # cycles per processed byte, less is better, for standalone AESNI-CBC
 # encrypt, sum of the latter and standalone SHA1, and "stitched"
 # subroutine:
 #
 #		AES-128-CBC	+SHA1		stitch      gain
 # Westmere	3.77[+5.3]	9.07		6.55	    +38%
 # Sandy Bridge	5.05[+5.0(6.1)]	10.06(11.15)	5.98(7.05)  +68%(+58%)
 # Ivy Bridge	5.05[+4.6]	9.65		5.54        +74%
 # Haswell	4.43[+3.6(4.2)]	8.00(8.58)	4.55(5.21)  +75%(+65%)
 # Bulldozer	5.77[+6.0]	11.72		6.37        +84%
 #
 #		AES-192-CBC
 # Westmere	4.51		9.81		6.80	    +44%
 # Sandy Bridge	6.05		11.06(12.15)	6.11(7.19)  +81%(+69%)
 # Ivy Bridge	6.05		10.65		6.07        +75%
 # Haswell	5.29		8.86(9.44)	5.32(5.32)  +67%(+77%)
 # Bulldozer	6.89		12.84		6.96        +84%
 #
 #		AES-256-CBC
 # Westmere	5.25		10.55		7.21	    +46%
 # Sandy Bridge	7.05		12.06(13.15)	7.12(7.72)  +69%(+70%)
 # Ivy Bridge	7.05		11.65		7.12        +64%
 # Haswell	6.19		9.76(10.34)	6.21(6.25)  +57%(+65%)
 # Bulldozer	8.00		13.95		8.25        +69%
 #
 # (*)	There are two code paths: SSSE3 and AVX. See sha1-568.pl for
 #	background information. Above numbers in parentheses are SSSE3
 #	results collected on AVX-capable CPU, i.e. apply on OSes that
 #	don't support AVX.
 #
 # Needless to mention that it makes no sense to implement "stitched"
 # *decrypt* subroutine. Because *both* AESNI-CBC decrypt and SHA1
 # fully utilize parallelism, so stitching would not give any gain
 # anyway. Well, there might be some, e.g. because of better cache
 # locality... For reference, here are performance results for
 # standalone AESNI-CBC decrypt:
 #
 #		AES-128-CBC	AES-192-CBC	AES-256-CBC
 # Westmere	1.25		1.50		1.75
 # Sandy Bridge	0.74		0.91		1.09
 # Ivy Bridge	0.74		0.90		1.11
 # Haswell	0.63		0.76		0.88
 # Bulldozer	0.70		0.85		0.99
 
 # And indeed:
 #
 #		AES-256-CBC	+SHA1		stitch      gain
 # Westmere	1.75		7.20		6.68        +7.8%
 # Sandy Bridge	1.09		6.09(7.22)	5.82(6.95)  +4.6%(+3.9%)
 # Ivy Bridge	1.11		5.70		5.45        +4.6%
 # Haswell	0.88		4.45(5.00)	4.39(4.69)  +1.4%(*)(+6.6%)
 # Bulldozer	0.99		6.95		5.95        +17%(**)
 #
 # (*)	Tiny improvement coefficient on Haswell is because we compare
 #	AVX1 stitch to sum with AVX2 SHA1.
 # (**)	Execution is fully dominated by integer code sequence and
 #	SIMD still hardly shows [in single-process benchmark;-]
 
 $flavour = shift;
 $output  = shift;
 if ($flavour =~ /\./) { $output = $flavour; undef $flavour; }
 
 $win64=0; $win64=1 if ($flavour =~ /[nm]asm|mingw64/ || $output =~ /\.asm$/);
 
 $0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1;
 ( $xlate="${dir}x86_64-xlate.pl" and -f $xlate ) or
 ( $xlate="${dir}../../perlasm/x86_64-xlate.pl" and -f $xlate) or
 die "can't locate x86_64-xlate.pl";
 
 $avx=1 if (`$ENV{CC} -Wa,-v -c -o /dev/null -x assembler /dev/null 2>&1`
 		=~ /GNU assembler version ([2-9]\.[0-9]+)/ &&
 	   $1>=2.19);
 $avx=1 if (!$avx && $win64 && ($flavour =~ /nasm/ || $ENV{ASM} =~ /nasm/) &&
 	   `nasm -v 2>&1` =~ /NASM version ([2-9]\.[0-9]+)/ &&
 	   $1>=2.09);
 $avx=1 if (!$avx && $win64 && ($flavour =~ /masm/ || $ENV{ASM} =~ /ml64/) &&
 	   `ml64 2>&1` =~ /Version ([0-9]+)\./ &&
 	   $1>=10);
 $avx=1 if (!$avx && `$ENV{CC} -v 2>&1` =~ /((?:^clang|LLVM) version|.*based on LLVM) ([3-9]\.[0-9]+)/ && $2>=3.0);
 
 $shaext=1;	### set to zero if compiling for 1.0.1
 
 $stitched_decrypt=0;
 
 open OUT,"| \"$^X\" $xlate $flavour $output";
 *STDOUT=*OUT;
 
 # void aesni_cbc_sha1_enc(const void *inp,
 #			void *out,
 #			size_t length,
 #			const AES_KEY *key,
 #			unsigned char *iv,
 #			SHA_CTX *ctx,
 #			const void *in0);
 
 $code.=<<___;
 .text
 .extern	OPENSSL_ia32cap_P
 
 .globl	aesni_cbc_sha1_enc
 .type	aesni_cbc_sha1_enc,\@abi-omnipotent
 .align	32
 aesni_cbc_sha1_enc:
 	# caller should check for SSSE3 and AES-NI bits
 	mov	OPENSSL_ia32cap_P+0(%rip),%r10d
 	mov	OPENSSL_ia32cap_P+4(%rip),%r11
 ___
 $code.=<<___ if ($shaext);
 	bt	\$61,%r11		# check SHA bit
 	jc	aesni_cbc_sha1_enc_shaext
 ___
 $code.=<<___ if ($avx);
 	and	\$`1<<28`,%r11d		# mask AVX bit
 	and	\$`1<<30`,%r10d		# mask "Intel CPU" bit
 	or	%r11d,%r10d
 	cmp	\$`1<<28|1<<30`,%r10d
 	je	aesni_cbc_sha1_enc_avx
 ___
 $code.=<<___;
 	jmp	aesni_cbc_sha1_enc_ssse3
 	ret
 .size	aesni_cbc_sha1_enc,.-aesni_cbc_sha1_enc
 ___
 
 my ($in0,$out,$len,$key,$ivp,$ctx,$inp)=("%rdi","%rsi","%rdx","%rcx","%r8","%r9","%r10");
 
 my $Xi=4;
 my @X=map("%xmm$_",(4..7,0..3));
 my @Tx=map("%xmm$_",(8..10));
 my @V=($A,$B,$C,$D,$E)=("%eax","%ebx","%ecx","%edx","%ebp");	# size optimization
 my @T=("%esi","%edi");
 my $j=0; my $jj=0; my $r=0; my $sn=0; my $rx=0;
 my $K_XX_XX="%r11";
 my ($rndkey0,$iv,$in)=map("%xmm$_",(11..13));			# for enc
 my @rndkey=("%xmm14","%xmm15");					# for enc
 my ($inout0,$inout1,$inout2,$inout3)=map("%xmm$_",(12..15));	# for dec
 
 if (1) {	# reassign for Atom Silvermont
     # The goal is to minimize amount of instructions with more than
     # 3 prefix bytes. Or in more practical terms to keep AES-NI *and*
     # SSSE3 instructions to upper half of the register bank.
     @X=map("%xmm$_",(8..11,4..7));
     @Tx=map("%xmm$_",(12,13,3));
     ($iv,$in,$rndkey0)=map("%xmm$_",(2,14,15));
     @rndkey=("%xmm0","%xmm1");
 }
 
 sub AUTOLOAD()		# thunk [simplified] 32-bit style perlasm
 { my $opcode = $AUTOLOAD; $opcode =~ s/.*:://;
   my $arg = pop;
     $arg = "\$$arg" if ($arg*1 eq $arg);
     $code .= "\t$opcode\t".join(',',$arg,reverse @_)."\n";
 }
 
 my $_rol=sub { &rol(@_) };
 my $_ror=sub { &ror(@_) };
 
 $code.=<<___;
 .type	aesni_cbc_sha1_enc_ssse3,\@function,6
 .align	32
 aesni_cbc_sha1_enc_ssse3:
 	mov	`($win64?56:8)`(%rsp),$inp	# load 7th argument
 	#shr	\$6,$len			# debugging artefact
 	#jz	.Lepilogue_ssse3		# debugging artefact
 	push	%rbx
 	push	%rbp
 	push	%r12
 	push	%r13
 	push	%r14
 	push	%r15
 	lea	`-104-($win64?10*16:0)`(%rsp),%rsp
 	#mov	$in0,$inp			# debugging artefact
 	#lea	64(%rsp),$ctx			# debugging artefact
 ___
 $code.=<<___ if ($win64);
 	movaps	%xmm6,96+0(%rsp)
 	movaps	%xmm7,96+16(%rsp)
 	movaps	%xmm8,96+32(%rsp)
 	movaps	%xmm9,96+48(%rsp)
 	movaps	%xmm10,96+64(%rsp)
 	movaps	%xmm11,96+80(%rsp)
 	movaps	%xmm12,96+96(%rsp)
 	movaps	%xmm13,96+112(%rsp)
 	movaps	%xmm14,96+128(%rsp)
 	movaps	%xmm15,96+144(%rsp)
 .Lprologue_ssse3:
 ___
 $code.=<<___;
 	mov	$in0,%r12			# reassign arguments
 	mov	$out,%r13
 	mov	$len,%r14
 	lea	112($key),%r15			# size optimization
 	movdqu	($ivp),$iv			# load IV
 	mov	$ivp,88(%rsp)			# save $ivp
 ___
 ($in0,$out,$len,$key)=map("%r$_",(12..15));	# reassign arguments
 my $rounds="${ivp}d";
 $code.=<<___;
 	shl	\$6,$len
 	sub	$in0,$out
 	mov	240-112($key),$rounds
 	add	$inp,$len		# end of input
 
 	lea	K_XX_XX(%rip),$K_XX_XX
 	mov	0($ctx),$A		# load context
 	mov	4($ctx),$B
 	mov	8($ctx),$C
 	mov	12($ctx),$D
 	mov	$B,@T[0]		# magic seed
 	mov	16($ctx),$E
 	mov	$C,@T[1]
 	xor	$D,@T[1]
 	and	@T[1],@T[0]
 
 	movdqa	64($K_XX_XX),@Tx[2]	# pbswap mask
 	movdqa	0($K_XX_XX),@Tx[1]	# K_00_19
 	movdqu	0($inp),@X[-4&7]	# load input to %xmm[0-3]
 	movdqu	16($inp),@X[-3&7]
 	movdqu	32($inp),@X[-2&7]
 	movdqu	48($inp),@X[-1&7]
 	pshufb	@Tx[2],@X[-4&7]		# byte swap
 	pshufb	@Tx[2],@X[-3&7]
 	pshufb	@Tx[2],@X[-2&7]
 	add	\$64,$inp
 	paddd	@Tx[1],@X[-4&7]		# add K_00_19
 	pshufb	@Tx[2],@X[-1&7]
 	paddd	@Tx[1],@X[-3&7]
 	paddd	@Tx[1],@X[-2&7]
 	movdqa	@X[-4&7],0(%rsp)	# X[]+K xfer to IALU
 	psubd	@Tx[1],@X[-4&7]		# restore X[]
 	movdqa	@X[-3&7],16(%rsp)
 	psubd	@Tx[1],@X[-3&7]
 	movdqa	@X[-2&7],32(%rsp)
 	psubd	@Tx[1],@X[-2&7]
 	movups	-112($key),$rndkey0	# $key[0]
 	movups	16-112($key),$rndkey[0]	# forward reference
 	jmp	.Loop_ssse3
 ___
 
 my $aesenc=sub {
   use integer;
   my ($n,$k)=($r/10,$r%10);
     if ($k==0) {
       $code.=<<___;
 	movups		`16*$n`($in0),$in		# load input
 	xorps		$rndkey0,$in
 ___
       $code.=<<___ if ($n);
 	movups		$iv,`16*($n-1)`($out,$in0)	# write output
 ___
       $code.=<<___;
 	xorps		$in,$iv
 	movups		`32+16*$k-112`($key),$rndkey[1]
 	aesenc		$rndkey[0],$iv
 ___
     } elsif ($k==9) {
       $sn++;
       $code.=<<___;
 	cmp		\$11,$rounds
 	jb		.Laesenclast$sn
 	movups		`32+16*($k+0)-112`($key),$rndkey[1]
 	aesenc		$rndkey[0],$iv
 	movups		`32+16*($k+1)-112`($key),$rndkey[0]
 	aesenc		$rndkey[1],$iv
 	je		.Laesenclast$sn
 	movups		`32+16*($k+2)-112`($key),$rndkey[1]
 	aesenc		$rndkey[0],$iv
 	movups		`32+16*($k+3)-112`($key),$rndkey[0]
 	aesenc		$rndkey[1],$iv
 .Laesenclast$sn:
 	aesenclast	$rndkey[0],$iv
 	movups		16-112($key),$rndkey[1]		# forward reference
 ___
     } else {
       $code.=<<___;
 	movups		`32+16*$k-112`($key),$rndkey[1]
 	aesenc		$rndkey[0],$iv
 ___
     }
     $r++;	unshift(@rndkey,pop(@rndkey));
 };
 
 sub Xupdate_ssse3_16_31()		# recall that $Xi starts wtih 4
 { use integer;
   my $body = shift;
   my @insns = (&$body,&$body,&$body,&$body);	# 40 instructions
   my ($a,$b,$c,$d,$e);
 
 	 eval(shift(@insns));		# ror
 	&pshufd	(@X[0],@X[-4&7],0xee);	# was &movdqa	(@X[0],@X[-3&7]);
 	 eval(shift(@insns));
 	&movdqa	(@Tx[0],@X[-1&7]);
 	  &paddd	(@Tx[1],@X[-1&7]);
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 
 	&punpcklqdq(@X[0],@X[-3&7]);	# compose "X[-14]" in "X[0]", was &palignr(@X[0],@X[-4&7],8);
 	 eval(shift(@insns));
 	 eval(shift(@insns));		# rol
 	 eval(shift(@insns));
 	&psrldq	(@Tx[0],4);		# "X[-3]", 3 dwords
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 
 	&pxor	(@X[0],@X[-4&7]);	# "X[0]"^="X[-16]"
 	 eval(shift(@insns));
 	 eval(shift(@insns));		# ror
 	&pxor	(@Tx[0],@X[-2&7]);	# "X[-3]"^"X[-8]"
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 
 	&pxor	(@X[0],@Tx[0]);		# "X[0]"^="X[-3]"^"X[-8]"
 	 eval(shift(@insns));
 	 eval(shift(@insns));		# rol
 	  &movdqa	(eval(16*(($Xi-1)&3))."(%rsp)",@Tx[1]);	# X[]+K xfer to IALU
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 
 	&movdqa	(@Tx[2],@X[0]);
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));		# ror
 	&movdqa	(@Tx[0],@X[0]);
 	 eval(shift(@insns));
 
 	&pslldq	(@Tx[2],12);		# "X[0]"<<96, extract one dword
 	&paddd	(@X[0],@X[0]);
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 
 	&psrld	(@Tx[0],31);
 	 eval(shift(@insns));
 	 eval(shift(@insns));		# rol
 	 eval(shift(@insns));
 	&movdqa	(@Tx[1],@Tx[2]);
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 
 	&psrld	(@Tx[2],30);
 	 eval(shift(@insns));
 	 eval(shift(@insns));		# ror
 	&por	(@X[0],@Tx[0]);		# "X[0]"<<<=1
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 
 	&pslld	(@Tx[1],2);
 	&pxor	(@X[0],@Tx[2]);
 	 eval(shift(@insns));
 	  &movdqa	(@Tx[2],eval(16*(($Xi)/5))."($K_XX_XX)");	# K_XX_XX
 	 eval(shift(@insns));		# rol
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 
 	&pxor	(@X[0],@Tx[1]);		# "X[0]"^=("X[0]">>96)<<<2
 	&pshufd (@Tx[1],@X[-1&7],0xee)	if ($Xi==7);	# was &movdqa	(@Tx[0],@X[-1&7]) in Xupdate_ssse3_32_79
 
 	 foreach (@insns) { eval; }	# remaining instructions [if any]
 
   $Xi++;	push(@X,shift(@X));	# "rotate" X[]
 		push(@Tx,shift(@Tx));
 }
 
 sub Xupdate_ssse3_32_79()
 { use integer;
   my $body = shift;
   my @insns = (&$body,&$body,&$body,&$body);	# 32 to 44 instructions
   my ($a,$b,$c,$d,$e);
 
 	 eval(shift(@insns))		if ($Xi==8);
 	&pxor	(@X[0],@X[-4&7]);	# "X[0]"="X[-32]"^"X[-16]"
 	 eval(shift(@insns))		if ($Xi==8);
 	 eval(shift(@insns));		# body_20_39
 	 eval(shift(@insns));
 	 eval(shift(@insns))		if (@insns[1] =~ /_ror/);
 	 eval(shift(@insns))		if (@insns[0] =~ /_ror/);
 	&punpcklqdq(@Tx[0],@X[-1&7]);	# compose "X[-6]", was &palignr(@Tx[0],@X[-2&7],8);
 	 eval(shift(@insns));
 	 eval(shift(@insns));		# rol
 
 	&pxor	(@X[0],@X[-7&7]);	# "X[0]"^="X[-28]"
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	if ($Xi%5) {
 	  &movdqa	(@Tx[2],@Tx[1]);# "perpetuate" K_XX_XX...
 	} else {			# ... or load next one
 	  &movdqa	(@Tx[2],eval(16*($Xi/5))."($K_XX_XX)");
 	}
 	 eval(shift(@insns));		# ror
 	  &paddd	(@Tx[1],@X[-1&7]);
 	 eval(shift(@insns));
 
 	&pxor	(@X[0],@Tx[0]);		# "X[0]"^="X[-6]"
 	 eval(shift(@insns));		# body_20_39
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));		# rol
 	 eval(shift(@insns))		if (@insns[0] =~ /_ror/);
 
 	&movdqa	(@Tx[0],@X[0]);
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	  &movdqa	(eval(16*(($Xi-1)&3))."(%rsp)",@Tx[1]);	# X[]+K xfer to IALU
 	 eval(shift(@insns));		# ror
 	 eval(shift(@insns));
 	 eval(shift(@insns));		# body_20_39
 
 	&pslld	(@X[0],2);
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	&psrld	(@Tx[0],30);
 	 eval(shift(@insns))		if (@insns[0] =~ /_rol/);# rol
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));		# ror
 
 	&por	(@X[0],@Tx[0]);		# "X[0]"<<<=2
 	 eval(shift(@insns));
 	 eval(shift(@insns));		# body_20_39
 	 eval(shift(@insns))		if (@insns[1] =~ /_rol/);
 	 eval(shift(@insns))		if (@insns[0] =~ /_rol/);
 	  &pshufd(@Tx[1],@X[-1&7],0xee)	if ($Xi<19);	# was &movdqa	(@Tx[1],@X[0])
 	 eval(shift(@insns));
 	 eval(shift(@insns));		# rol
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));		# rol
 	 eval(shift(@insns));
 
 	 foreach (@insns) { eval; }	# remaining instructions
 
   $Xi++;	push(@X,shift(@X));	# "rotate" X[]
 		push(@Tx,shift(@Tx));
 }
 
 sub Xuplast_ssse3_80()
 { use integer;
   my $body = shift;
   my @insns = (&$body,&$body,&$body,&$body);	# 32 instructions
   my ($a,$b,$c,$d,$e);
 
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	  &paddd	(@Tx[1],@X[-1&7]);
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 
 	  &movdqa	(eval(16*(($Xi-1)&3))."(%rsp)",@Tx[1]);	# X[]+K xfer IALU
 
 	 foreach (@insns) { eval; }		# remaining instructions
 
 	&cmp	($inp,$len);
 	&je	(shift);
 
 	unshift(@Tx,pop(@Tx));
 
 	&movdqa	(@Tx[2],"64($K_XX_XX)");	# pbswap mask
 	&movdqa	(@Tx[1],"0($K_XX_XX)");		# K_00_19
 	&movdqu	(@X[-4&7],"0($inp)");		# load input
 	&movdqu	(@X[-3&7],"16($inp)");
 	&movdqu	(@X[-2&7],"32($inp)");
 	&movdqu	(@X[-1&7],"48($inp)");
 	&pshufb	(@X[-4&7],@Tx[2]);		# byte swap
 	&add	($inp,64);
 
   $Xi=0;
 }
 
 sub Xloop_ssse3()
 { use integer;
   my $body = shift;
   my @insns = (&$body,&$body,&$body,&$body);	# 32 instructions
   my ($a,$b,$c,$d,$e);
 
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	&pshufb	(@X[($Xi-3)&7],@Tx[2]);
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	&paddd	(@X[($Xi-4)&7],@Tx[1]);
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	&movdqa	(eval(16*$Xi)."(%rsp)",@X[($Xi-4)&7]);	# X[]+K xfer to IALU
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	&psubd	(@X[($Xi-4)&7],@Tx[1]);
 
 	foreach (@insns) { eval; }
   $Xi++;
 }
 
 sub Xtail_ssse3()
 { use integer;
   my $body = shift;
   my @insns = (&$body,&$body,&$body,&$body);	# 32 instructions
   my ($a,$b,$c,$d,$e);
 
 	foreach (@insns) { eval; }
 }
 
 my @body_00_19 = (
 	'($a,$b,$c,$d,$e)=@V;'.
 	'&$_ror	($b,$j?7:2);',	# $b>>>2
 	'&xor	(@T[0],$d);',
 	'&mov	(@T[1],$a);',	# $b for next round
 
 	'&add	($e,eval(4*($j&15))."(%rsp)");',# X[]+K xfer
 	'&xor	($b,$c);',	# $c^$d for next round
 
 	'&$_rol	($a,5);',
 	'&add	($e,@T[0]);',
 	'&and	(@T[1],$b);',	# ($b&($c^$d)) for next round
 
 	'&xor	($b,$c);',	# restore $b
 	'&add	($e,$a);'	.'$j++; unshift(@V,pop(@V)); unshift(@T,pop(@T));'
 	);
 
 sub body_00_19 () {	# ((c^d)&b)^d
     # on start @T[0]=(c^d)&b
     return &body_20_39() if ($rx==19); $rx++;
 
     use integer;
     my ($k,$n);
     my @r=@body_00_19;
 
 	$n = scalar(@r);
 	$k = (($jj+1)*12/20)*20*$n/12;	# 12 aesencs per these 20 rounds
 	@r[$k%$n].='&$aesenc();'	if ($jj==$k/$n);
 	$jj++;
 
     return @r;
 }
 
 my @body_20_39 = (
 	'($a,$b,$c,$d,$e)=@V;'.
 	'&add	($e,eval(4*($j&15))."(%rsp)");',# X[]+K xfer
 	'&xor	(@T[0],$d)	if($j==19);'.
 	'&xor	(@T[0],$c)	if($j> 19);',	# ($b^$d^$c)
 	'&mov	(@T[1],$a);',	# $b for next round
 
 	'&$_rol	($a,5);',
 	'&add	($e,@T[0]);',
 	'&xor	(@T[1],$c)	if ($j< 79);',	# $b^$d for next round
 
 	'&$_ror	($b,7);',	# $b>>>2
 	'&add	($e,$a);'	.'$j++; unshift(@V,pop(@V)); unshift(@T,pop(@T));'
 	);
 
 sub body_20_39 () {	# b^d^c
     # on entry @T[0]=b^d
     return &body_40_59() if ($rx==39); $rx++;
 
     use integer;
     my ($k,$n);
     my @r=@body_20_39;
 
 	$n = scalar(@r);
 	$k = (($jj+1)*8/20)*20*$n/8;	# 8 aesencs per these 20 rounds
 	@r[$k%$n].='&$aesenc();'	if ($jj==$k/$n && $rx!=20);
 	$jj++;
 
     return @r;
 }
 
 my @body_40_59 = (
 	'($a,$b,$c,$d,$e)=@V;'.
 	'&add	($e,eval(4*($j&15))."(%rsp)");',# X[]+K xfer
 	'&and	(@T[0],$c)	if ($j>=40);',	# (b^c)&(c^d)
 	'&xor	($c,$d)		if ($j>=40);',	# restore $c
 
 	'&$_ror	($b,7);',	# $b>>>2
 	'&mov	(@T[1],$a);',	# $b for next round
 	'&xor	(@T[0],$c);',
 
 	'&$_rol	($a,5);',
 	'&add	($e,@T[0]);',
 	'&xor	(@T[1],$c)	if ($j==59);'.
 	'&xor	(@T[1],$b)	if ($j< 59);',	# b^c for next round
 
 	'&xor	($b,$c)		if ($j< 59);',	# c^d for next round
 	'&add	($e,$a);'	.'$j++; unshift(@V,pop(@V)); unshift(@T,pop(@T));'
 	);
 
 sub body_40_59 () {	# ((b^c)&(c^d))^c
     # on entry @T[0]=(b^c), (c^=d)
     $rx++;
 
     use integer;
     my ($k,$n);
     my @r=@body_40_59;
 
 	$n = scalar(@r);
 	$k=(($jj+1)*12/20)*20*$n/12;	# 12 aesencs per these 20 rounds
 	@r[$k%$n].='&$aesenc();'	if ($jj==$k/$n && $rx!=40);
 	$jj++;
 
     return @r;
 }
 $code.=<<___;
 .align	32
 .Loop_ssse3:
 ___
 	&Xupdate_ssse3_16_31(\&body_00_19);
 	&Xupdate_ssse3_16_31(\&body_00_19);
 	&Xupdate_ssse3_16_31(\&body_00_19);
 	&Xupdate_ssse3_16_31(\&body_00_19);
 	&Xupdate_ssse3_32_79(\&body_00_19);
 	&Xupdate_ssse3_32_79(\&body_20_39);
 	&Xupdate_ssse3_32_79(\&body_20_39);
 	&Xupdate_ssse3_32_79(\&body_20_39);
 	&Xupdate_ssse3_32_79(\&body_20_39);
 	&Xupdate_ssse3_32_79(\&body_20_39);
 	&Xupdate_ssse3_32_79(\&body_40_59);
 	&Xupdate_ssse3_32_79(\&body_40_59);
 	&Xupdate_ssse3_32_79(\&body_40_59);
 	&Xupdate_ssse3_32_79(\&body_40_59);
 	&Xupdate_ssse3_32_79(\&body_40_59);
 	&Xupdate_ssse3_32_79(\&body_20_39);
 	&Xuplast_ssse3_80(\&body_20_39,".Ldone_ssse3");	# can jump to "done"
 
 				$saved_j=$j; @saved_V=@V;
 				$saved_r=$r; @saved_rndkey=@rndkey;
 
 	&Xloop_ssse3(\&body_20_39);
 	&Xloop_ssse3(\&body_20_39);
 	&Xloop_ssse3(\&body_20_39);
 
 $code.=<<___;
 	movups	$iv,48($out,$in0)		# write output
 	lea	64($in0),$in0
 
 	add	0($ctx),$A			# update context
 	add	4($ctx),@T[0]
 	add	8($ctx),$C
 	add	12($ctx),$D
 	mov	$A,0($ctx)
 	add	16($ctx),$E
 	mov	@T[0],4($ctx)
 	mov	@T[0],$B			# magic seed
 	mov	$C,8($ctx)
 	mov	$C,@T[1]
 	mov	$D,12($ctx)
 	xor	$D,@T[1]
 	mov	$E,16($ctx)
 	and	@T[1],@T[0]
 	jmp	.Loop_ssse3
 
 .Ldone_ssse3:
 ___
 				$jj=$j=$saved_j; @V=@saved_V;
 				$r=$saved_r;     @rndkey=@saved_rndkey;
 
 	&Xtail_ssse3(\&body_20_39);
 	&Xtail_ssse3(\&body_20_39);
 	&Xtail_ssse3(\&body_20_39);
 
 $code.=<<___;
 	movups	$iv,48($out,$in0)		# write output
 	mov	88(%rsp),$ivp			# restore $ivp
 
 	add	0($ctx),$A			# update context
 	add	4($ctx),@T[0]
 	add	8($ctx),$C
 	mov	$A,0($ctx)
 	add	12($ctx),$D
 	mov	@T[0],4($ctx)
 	add	16($ctx),$E
 	mov	$C,8($ctx)
 	mov	$D,12($ctx)
 	mov	$E,16($ctx)
 	movups	$iv,($ivp)			# write IV
 ___
 $code.=<<___ if ($win64);
 	movaps	96+0(%rsp),%xmm6
 	movaps	96+16(%rsp),%xmm7
 	movaps	96+32(%rsp),%xmm8
 	movaps	96+48(%rsp),%xmm9
 	movaps	96+64(%rsp),%xmm10
 	movaps	96+80(%rsp),%xmm11
 	movaps	96+96(%rsp),%xmm12
 	movaps	96+112(%rsp),%xmm13
 	movaps	96+128(%rsp),%xmm14
 	movaps	96+144(%rsp),%xmm15
 ___
 $code.=<<___;
 	lea	`104+($win64?10*16:0)`(%rsp),%rsi
 	mov	0(%rsi),%r15
 	mov	8(%rsi),%r14
 	mov	16(%rsi),%r13
 	mov	24(%rsi),%r12
 	mov	32(%rsi),%rbp
 	mov	40(%rsi),%rbx
 	lea	48(%rsi),%rsp
 .Lepilogue_ssse3:
 	ret
 .size	aesni_cbc_sha1_enc_ssse3,.-aesni_cbc_sha1_enc_ssse3
 ___
 
 						if ($stitched_decrypt) {{{
 # reset
 ($in0,$out,$len,$key,$ivp,$ctx,$inp)=("%rdi","%rsi","%rdx","%rcx","%r8","%r9","%r10");
 $j=$jj=$r=$rx=0;
 $Xi=4;
 
 # reassign for Atom Silvermont (see above)
 ($inout0,$inout1,$inout2,$inout3,$rndkey0)=map("%xmm$_",(0..4));
 @X=map("%xmm$_",(8..13,6,7));
 @Tx=map("%xmm$_",(14,15,5));
 
 my @aes256_dec = (
 	'&movdqu($inout0,"0x00($in0)");',
 	'&movdqu($inout1,"0x10($in0)");	&pxor	($inout0,$rndkey0);',
 	'&movdqu($inout2,"0x20($in0)");	&pxor	($inout1,$rndkey0);',
 	'&movdqu($inout3,"0x30($in0)");	&pxor	($inout2,$rndkey0);',
 
 	'&pxor	($inout3,$rndkey0);	&movups	($rndkey0,"16-112($key)");',
 	'&movaps("64(%rsp)",@X[2]);',	# save IV, originally @X[3]
 	undef,undef
 	);
 for ($i=0;$i<13;$i++) {
     push (@aes256_dec,(
 	'&aesdec	($inout0,$rndkey0);',
 	'&aesdec	($inout1,$rndkey0);',
 	'&aesdec	($inout2,$rndkey0);',
 	'&aesdec	($inout3,$rndkey0);	&movups($rndkey0,"'.(16*($i+2)-112).'($key)");'
 	));
     push (@aes256_dec,(undef,undef))	if (($i>=3 && $i<=5) || $i>=11);
     push (@aes256_dec,(undef,undef))	if ($i==5);
 }
 push(@aes256_dec,(
 	'&aesdeclast	($inout0,$rndkey0);	&movups	(@X[0],"0x00($in0)");',
 	'&aesdeclast	($inout1,$rndkey0);	&movups	(@X[1],"0x10($in0)");',
 	'&aesdeclast	($inout2,$rndkey0);	&movups	(@X[2],"0x20($in0)");',
 	'&aesdeclast	($inout3,$rndkey0);	&movups	(@X[3],"0x30($in0)");',
 
 	'&xorps		($inout0,"64(%rsp)");	&movdqu	($rndkey0,"-112($key)");',
 	'&xorps		($inout1,@X[0]);	&movups	("0x00($out,$in0)",$inout0);',
 	'&xorps		($inout2,@X[1]);	&movups	("0x10($out,$in0)",$inout1);',
 	'&xorps		($inout3,@X[2]);	&movups	("0x20($out,$in0)",$inout2);',
 
 	'&movups	("0x30($out,$in0)",$inout3);'
 	));
 
 sub body_00_19_dec () {	# ((c^d)&b)^d
     # on start @T[0]=(c^d)&b
     return &body_20_39_dec() if ($rx==19);
 
     my @r=@body_00_19;
 
 	unshift (@r,@aes256_dec[$rx])	if (@aes256_dec[$rx]);
 	$rx++;
 
     return @r;
 }
 
 sub body_20_39_dec () {	# b^d^c
     # on entry @T[0]=b^d
     return &body_40_59_dec() if ($rx==39);
   
     my @r=@body_20_39;
 
 	unshift (@r,@aes256_dec[$rx])	if (@aes256_dec[$rx]);
 	$rx++;
 
     return @r;
 }
 
 sub body_40_59_dec () {	# ((b^c)&(c^d))^c
     # on entry @T[0]=(b^c), (c^=d)
 
     my @r=@body_40_59;
 
 	unshift (@r,@aes256_dec[$rx])	if (@aes256_dec[$rx]);
 	$rx++;
 
     return @r;
 }
 
 $code.=<<___;
 .globl	aesni256_cbc_sha1_dec
 .type	aesni256_cbc_sha1_dec,\@abi-omnipotent
 .align	32
 aesni256_cbc_sha1_dec:
 	# caller should check for SSSE3 and AES-NI bits
 	mov	OPENSSL_ia32cap_P+0(%rip),%r10d
 	mov	OPENSSL_ia32cap_P+4(%rip),%r11d
 ___
 $code.=<<___ if ($avx);
 	and	\$`1<<28`,%r11d		# mask AVX bit
 	and	\$`1<<30`,%r10d		# mask "Intel CPU" bit
 	or	%r11d,%r10d
 	cmp	\$`1<<28|1<<30`,%r10d
 	je	aesni256_cbc_sha1_dec_avx
 ___
 $code.=<<___;
 	jmp	aesni256_cbc_sha1_dec_ssse3
 	ret
 .size	aesni256_cbc_sha1_dec,.-aesni256_cbc_sha1_dec
 
 .type	aesni256_cbc_sha1_dec_ssse3,\@function,6
 .align	32
 aesni256_cbc_sha1_dec_ssse3:
 	mov	`($win64?56:8)`(%rsp),$inp	# load 7th argument
 	push	%rbx
 	push	%rbp
 	push	%r12
 	push	%r13
 	push	%r14
 	push	%r15
 	lea	`-104-($win64?10*16:0)`(%rsp),%rsp
 ___
 $code.=<<___ if ($win64);
 	movaps	%xmm6,96+0(%rsp)
 	movaps	%xmm7,96+16(%rsp)
 	movaps	%xmm8,96+32(%rsp)
 	movaps	%xmm9,96+48(%rsp)
 	movaps	%xmm10,96+64(%rsp)
 	movaps	%xmm11,96+80(%rsp)
 	movaps	%xmm12,96+96(%rsp)
 	movaps	%xmm13,96+112(%rsp)
 	movaps	%xmm14,96+128(%rsp)
 	movaps	%xmm15,96+144(%rsp)
 .Lprologue_dec_ssse3:
 ___
 $code.=<<___;
 	mov	$in0,%r12			# reassign arguments
 	mov	$out,%r13
 	mov	$len,%r14
 	lea	112($key),%r15			# size optimization
 	movdqu	($ivp),@X[3]			# load IV
 	#mov	$ivp,88(%rsp)			# save $ivp
 ___
 ($in0,$out,$len,$key)=map("%r$_",(12..15));	# reassign arguments
 $code.=<<___;
 	shl	\$6,$len
 	sub	$in0,$out
 	add	$inp,$len		# end of input
 
 	lea	K_XX_XX(%rip),$K_XX_XX
 	mov	0($ctx),$A		# load context
 	mov	4($ctx),$B
 	mov	8($ctx),$C
 	mov	12($ctx),$D
 	mov	$B,@T[0]		# magic seed
 	mov	16($ctx),$E
 	mov	$C,@T[1]
 	xor	$D,@T[1]
 	and	@T[1],@T[0]
 
 	movdqa	64($K_XX_XX),@Tx[2]	# pbswap mask
 	movdqa	0($K_XX_XX),@Tx[1]	# K_00_19
 	movdqu	0($inp),@X[-4&7]	# load input to %xmm[0-3]
 	movdqu	16($inp),@X[-3&7]
 	movdqu	32($inp),@X[-2&7]
 	movdqu	48($inp),@X[-1&7]
 	pshufb	@Tx[2],@X[-4&7]		# byte swap
 	add	\$64,$inp
 	pshufb	@Tx[2],@X[-3&7]
 	pshufb	@Tx[2],@X[-2&7]
 	pshufb	@Tx[2],@X[-1&7]
 	paddd	@Tx[1],@X[-4&7]		# add K_00_19
 	paddd	@Tx[1],@X[-3&7]
 	paddd	@Tx[1],@X[-2&7]
 	movdqa	@X[-4&7],0(%rsp)	# X[]+K xfer to IALU
 	psubd	@Tx[1],@X[-4&7]		# restore X[]
 	movdqa	@X[-3&7],16(%rsp)
 	psubd	@Tx[1],@X[-3&7]
 	movdqa	@X[-2&7],32(%rsp)
 	psubd	@Tx[1],@X[-2&7]
 	movdqu	-112($key),$rndkey0	# $key[0]
 	jmp	.Loop_dec_ssse3
 
 .align	32
 .Loop_dec_ssse3:
 ___
 	&Xupdate_ssse3_16_31(\&body_00_19_dec);
 	&Xupdate_ssse3_16_31(\&body_00_19_dec);
 	&Xupdate_ssse3_16_31(\&body_00_19_dec);
 	&Xupdate_ssse3_16_31(\&body_00_19_dec);
 	&Xupdate_ssse3_32_79(\&body_00_19_dec);
 	&Xupdate_ssse3_32_79(\&body_20_39_dec);
 	&Xupdate_ssse3_32_79(\&body_20_39_dec);
 	&Xupdate_ssse3_32_79(\&body_20_39_dec);
 	&Xupdate_ssse3_32_79(\&body_20_39_dec);
 	&Xupdate_ssse3_32_79(\&body_20_39_dec);
 	&Xupdate_ssse3_32_79(\&body_40_59_dec);
 	&Xupdate_ssse3_32_79(\&body_40_59_dec);
 	&Xupdate_ssse3_32_79(\&body_40_59_dec);
 	&Xupdate_ssse3_32_79(\&body_40_59_dec);
 	&Xupdate_ssse3_32_79(\&body_40_59_dec);
 	&Xupdate_ssse3_32_79(\&body_20_39_dec);
 	&Xuplast_ssse3_80(\&body_20_39_dec,".Ldone_dec_ssse3");	# can jump to "done"
 
 				$saved_j=$j;   @saved_V=@V;
 				$saved_rx=$rx;
 
 	&Xloop_ssse3(\&body_20_39_dec);
 	&Xloop_ssse3(\&body_20_39_dec);
 	&Xloop_ssse3(\&body_20_39_dec);
 
 	eval(@aes256_dec[-1]);			# last store
 $code.=<<___;
 	lea	64($in0),$in0
 
 	add	0($ctx),$A			# update context
 	add	4($ctx),@T[0]
 	add	8($ctx),$C
 	add	12($ctx),$D
 	mov	$A,0($ctx)
 	add	16($ctx),$E
 	mov	@T[0],4($ctx)
 	mov	@T[0],$B			# magic seed
 	mov	$C,8($ctx)
 	mov	$C,@T[1]
 	mov	$D,12($ctx)
 	xor	$D,@T[1]
 	mov	$E,16($ctx)
 	and	@T[1],@T[0]
 	jmp	.Loop_dec_ssse3
 
 .Ldone_dec_ssse3:
 ___
 				$jj=$j=$saved_j; @V=@saved_V;
 				$rx=$saved_rx;
 
 	&Xtail_ssse3(\&body_20_39_dec);
 	&Xtail_ssse3(\&body_20_39_dec);
 	&Xtail_ssse3(\&body_20_39_dec);
 
 	eval(@aes256_dec[-1]);			# last store
 $code.=<<___;
 	add	0($ctx),$A			# update context
 	add	4($ctx),@T[0]
 	add	8($ctx),$C
 	mov	$A,0($ctx)
 	add	12($ctx),$D
 	mov	@T[0],4($ctx)
 	add	16($ctx),$E
 	mov	$C,8($ctx)
 	mov	$D,12($ctx)
 	mov	$E,16($ctx)
 	movups	@X[3],($ivp)			# write IV
 ___
 $code.=<<___ if ($win64);
 	movaps	96+0(%rsp),%xmm6
 	movaps	96+16(%rsp),%xmm7
 	movaps	96+32(%rsp),%xmm8
 	movaps	96+48(%rsp),%xmm9
 	movaps	96+64(%rsp),%xmm10
 	movaps	96+80(%rsp),%xmm11
 	movaps	96+96(%rsp),%xmm12
 	movaps	96+112(%rsp),%xmm13
 	movaps	96+128(%rsp),%xmm14
 	movaps	96+144(%rsp),%xmm15
 ___
 $code.=<<___;
 	lea	`104+($win64?10*16:0)`(%rsp),%rsi
 	mov	0(%rsi),%r15
 	mov	8(%rsi),%r14
 	mov	16(%rsi),%r13
 	mov	24(%rsi),%r12
 	mov	32(%rsi),%rbp
 	mov	40(%rsi),%rbx
 	lea	48(%rsi),%rsp
 .Lepilogue_dec_ssse3:
 	ret
 .size	aesni256_cbc_sha1_dec_ssse3,.-aesni256_cbc_sha1_dec_ssse3
 ___
 						}}}
 $j=$jj=$r=$rx=0;
 
 if ($avx) {
 my ($in0,$out,$len,$key,$ivp,$ctx,$inp)=("%rdi","%rsi","%rdx","%rcx","%r8","%r9","%r10");
 
 my $Xi=4;
 my @X=map("%xmm$_",(4..7,0..3));
 my @Tx=map("%xmm$_",(8..10));
 my @V=($A,$B,$C,$D,$E)=("%eax","%ebx","%ecx","%edx","%ebp");	# size optimization
 my @T=("%esi","%edi");
 my ($rndkey0,$iv,$in)=map("%xmm$_",(11..13));
 my @rndkey=("%xmm14","%xmm15");
 my ($inout0,$inout1,$inout2,$inout3)=map("%xmm$_",(12..15));	# for dec
 my $Kx=@Tx[2];
 
 my $_rol=sub { &shld(@_[0],@_) };
 my $_ror=sub { &shrd(@_[0],@_) };
 
 $code.=<<___;
 .type	aesni_cbc_sha1_enc_avx,\@function,6
 .align	32
 aesni_cbc_sha1_enc_avx:
 	mov	`($win64?56:8)`(%rsp),$inp	# load 7th argument
 	#shr	\$6,$len			# debugging artefact
 	#jz	.Lepilogue_avx			# debugging artefact
 	push	%rbx
 	push	%rbp
 	push	%r12
 	push	%r13
 	push	%r14
 	push	%r15
 	lea	`-104-($win64?10*16:0)`(%rsp),%rsp
 	#mov	$in0,$inp			# debugging artefact
 	#lea	64(%rsp),$ctx			# debugging artefact
 ___
 $code.=<<___ if ($win64);
 	movaps	%xmm6,96+0(%rsp)
 	movaps	%xmm7,96+16(%rsp)
 	movaps	%xmm8,96+32(%rsp)
 	movaps	%xmm9,96+48(%rsp)
 	movaps	%xmm10,96+64(%rsp)
 	movaps	%xmm11,96+80(%rsp)
 	movaps	%xmm12,96+96(%rsp)
 	movaps	%xmm13,96+112(%rsp)
 	movaps	%xmm14,96+128(%rsp)
 	movaps	%xmm15,96+144(%rsp)
 .Lprologue_avx:
 ___
 $code.=<<___;
 	vzeroall
 	mov	$in0,%r12			# reassign arguments
 	mov	$out,%r13
 	mov	$len,%r14
 	lea	112($key),%r15			# size optimization
 	vmovdqu	($ivp),$iv			# load IV
 	mov	$ivp,88(%rsp)			# save $ivp
 ___
 ($in0,$out,$len,$key)=map("%r$_",(12..15));	# reassign arguments
 my $rounds="${ivp}d";
 $code.=<<___;
 	shl	\$6,$len
 	sub	$in0,$out
 	mov	240-112($key),$rounds
 	add	$inp,$len		# end of input
 
 	lea	K_XX_XX(%rip),$K_XX_XX
 	mov	0($ctx),$A		# load context
 	mov	4($ctx),$B
 	mov	8($ctx),$C
 	mov	12($ctx),$D
 	mov	$B,@T[0]		# magic seed
 	mov	16($ctx),$E
 	mov	$C,@T[1]
 	xor	$D,@T[1]
 	and	@T[1],@T[0]
 
 	vmovdqa	64($K_XX_XX),@X[2]	# pbswap mask
 	vmovdqa	0($K_XX_XX),$Kx		# K_00_19
 	vmovdqu	0($inp),@X[-4&7]	# load input to %xmm[0-3]
 	vmovdqu	16($inp),@X[-3&7]
 	vmovdqu	32($inp),@X[-2&7]
 	vmovdqu	48($inp),@X[-1&7]
 	vpshufb	@X[2],@X[-4&7],@X[-4&7]	# byte swap
 	add	\$64,$inp
 	vpshufb	@X[2],@X[-3&7],@X[-3&7]
 	vpshufb	@X[2],@X[-2&7],@X[-2&7]
 	vpshufb	@X[2],@X[-1&7],@X[-1&7]
 	vpaddd	$Kx,@X[-4&7],@X[0]	# add K_00_19
 	vpaddd	$Kx,@X[-3&7],@X[1]
 	vpaddd	$Kx,@X[-2&7],@X[2]
 	vmovdqa	@X[0],0(%rsp)		# X[]+K xfer to IALU
 	vmovdqa	@X[1],16(%rsp)
 	vmovdqa	@X[2],32(%rsp)
 	vmovups	-112($key),$rndkey[1]	# $key[0]
 	vmovups	16-112($key),$rndkey[0]	# forward reference
 	jmp	.Loop_avx
 ___
 
 my $aesenc=sub {
   use integer;
   my ($n,$k)=($r/10,$r%10);
     if ($k==0) {
       $code.=<<___;
 	vmovdqu		`16*$n`($in0),$in		# load input
 	vpxor		$rndkey[1],$in,$in
 ___
       $code.=<<___ if ($n);
 	vmovups		$iv,`16*($n-1)`($out,$in0)	# write output
 ___
       $code.=<<___;
 	vpxor		$in,$iv,$iv
 	vaesenc		$rndkey[0],$iv,$iv
 	vmovups		`32+16*$k-112`($key),$rndkey[1]
 ___
     } elsif ($k==9) {
       $sn++;
       $code.=<<___;
 	cmp		\$11,$rounds
 	jb		.Lvaesenclast$sn
 	vaesenc		$rndkey[0],$iv,$iv
 	vmovups		`32+16*($k+0)-112`($key),$rndkey[1]
 	vaesenc		$rndkey[1],$iv,$iv
 	vmovups		`32+16*($k+1)-112`($key),$rndkey[0]
 	je		.Lvaesenclast$sn
 	vaesenc		$rndkey[0],$iv,$iv
 	vmovups		`32+16*($k+2)-112`($key),$rndkey[1]
 	vaesenc		$rndkey[1],$iv,$iv
 	vmovups		`32+16*($k+3)-112`($key),$rndkey[0]
 .Lvaesenclast$sn:
 	vaesenclast	$rndkey[0],$iv,$iv
 	vmovups		-112($key),$rndkey[0]
 	vmovups		16-112($key),$rndkey[1]		# forward reference
 ___
     } else {
       $code.=<<___;
 	vaesenc		$rndkey[0],$iv,$iv
 	vmovups		`32+16*$k-112`($key),$rndkey[1]
 ___
     }
     $r++;	unshift(@rndkey,pop(@rndkey));
 };
 
 sub Xupdate_avx_16_31()		# recall that $Xi starts wtih 4
 { use integer;
   my $body = shift;
   my @insns = (&$body,&$body,&$body,&$body);	# 40 instructions
   my ($a,$b,$c,$d,$e);
 
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	&vpalignr(@X[0],@X[-3&7],@X[-4&7],8);	# compose "X[-14]" in "X[0]"
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 
 	  &vpaddd	(@Tx[1],$Kx,@X[-1&7]);
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	&vpsrldq(@Tx[0],@X[-1&7],4);		# "X[-3]", 3 dwords
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	&vpxor	(@X[0],@X[0],@X[-4&7]);		# "X[0]"^="X[-16]"
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 
 	&vpxor	(@Tx[0],@Tx[0],@X[-2&7]);	# "X[-3]"^"X[-8]"
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 
 	&vpxor	(@X[0],@X[0],@Tx[0]);		# "X[0]"^="X[-3]"^"X[-8]"
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	  &vmovdqa	(eval(16*(($Xi-1)&3))."(%rsp)",@Tx[1]);	# X[]+K xfer to IALU
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 
 	&vpsrld	(@Tx[0],@X[0],31);
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 
 	&vpslldq(@Tx[1],@X[0],12);		# "X[0]"<<96, extract one dword
 	&vpaddd	(@X[0],@X[0],@X[0]);
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 
 	&vpor	(@X[0],@X[0],@Tx[0]);		# "X[0]"<<<=1
 	&vpsrld	(@Tx[0],@Tx[1],30);
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 
 	&vpslld	(@Tx[1],@Tx[1],2);
 	&vpxor	(@X[0],@X[0],@Tx[0]);
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 
 	&vpxor	(@X[0],@X[0],@Tx[1]);		# "X[0]"^=("X[0]">>96)<<<2
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	  &vmovdqa	($Kx,eval(16*(($Xi)/5))."($K_XX_XX)")	if ($Xi%5==0);	# K_XX_XX
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 
 
 	 foreach (@insns) { eval; }	# remaining instructions [if any]
 
   $Xi++;	push(@X,shift(@X));	# "rotate" X[]
 }
 
 sub Xupdate_avx_32_79()
 { use integer;
   my $body = shift;
   my @insns = (&$body,&$body,&$body,&$body);	# 32 to 48 instructions
   my ($a,$b,$c,$d,$e);
 
 	&vpalignr(@Tx[0],@X[-1&7],@X[-2&7],8);	# compose "X[-6]"
 	&vpxor	(@X[0],@X[0],@X[-4&7]);		# "X[0]"="X[-32]"^"X[-16]"
 	 eval(shift(@insns));		# body_20_39
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));		# rol
 
 	&vpxor	(@X[0],@X[0],@X[-7&7]);		# "X[0]"^="X[-28]"
 	 eval(shift(@insns));
 	 eval(shift(@insns))	if (@insns[0] !~ /&ro[rl]/);
 	  &vpaddd	(@Tx[1],$Kx,@X[-1&7]);
 	  &vmovdqa	($Kx,eval(16*($Xi/5))."($K_XX_XX)")	if ($Xi%5==0);
 	 eval(shift(@insns));		# ror
 	 eval(shift(@insns));
 
 	&vpxor	(@X[0],@X[0],@Tx[0]);		# "X[0]"^="X[-6]"
 	 eval(shift(@insns));		# body_20_39
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));		# rol
 
 	&vpsrld	(@Tx[0],@X[0],30);
 	  &vmovdqa	(eval(16*(($Xi-1)&3))."(%rsp)",@Tx[1]);	# X[]+K xfer to IALU
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));		# ror
 	 eval(shift(@insns));
 
 	&vpslld	(@X[0],@X[0],2);
 	 eval(shift(@insns));		# body_20_39
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));		# rol
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));		# ror
 	 eval(shift(@insns));
 
 	&vpor	(@X[0],@X[0],@Tx[0]);		# "X[0]"<<<=2
 	 eval(shift(@insns));		# body_20_39
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));		# rol
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));		# rol
 	 eval(shift(@insns));
 
 	 foreach (@insns) { eval; }	# remaining instructions
 
   $Xi++;	push(@X,shift(@X));	# "rotate" X[]
 }
 
 sub Xuplast_avx_80()
 { use integer;
   my $body = shift;
   my @insns = (&$body,&$body,&$body,&$body);	# 32 instructions
   my ($a,$b,$c,$d,$e);
 
 	 eval(shift(@insns));
 	  &vpaddd	(@Tx[1],$Kx,@X[-1&7]);
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 
 	  &vmovdqa	(eval(16*(($Xi-1)&3))."(%rsp)",@Tx[1]);	# X[]+K xfer IALU
 
 	 foreach (@insns) { eval; }		# remaining instructions
 
 	&cmp	($inp,$len);
 	&je	(shift);
 
 	&vmovdqa(@Tx[1],"64($K_XX_XX)");	# pbswap mask
 	&vmovdqa($Kx,"0($K_XX_XX)");		# K_00_19
 	&vmovdqu(@X[-4&7],"0($inp)");		# load input
 	&vmovdqu(@X[-3&7],"16($inp)");
 	&vmovdqu(@X[-2&7],"32($inp)");
 	&vmovdqu(@X[-1&7],"48($inp)");
 	&vpshufb(@X[-4&7],@X[-4&7],@Tx[1]);	# byte swap
 	&add	($inp,64);
 
   $Xi=0;
 }
 
 sub Xloop_avx()
 { use integer;
   my $body = shift;
   my @insns = (&$body,&$body,&$body,&$body);	# 32 instructions
   my ($a,$b,$c,$d,$e);
 
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	&vpshufb(@X[($Xi-3)&7],@X[($Xi-3)&7],@Tx[1]);
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	&vpaddd	(@Tx[0],@X[($Xi-4)&7],$Kx);
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 	&vmovdqa(eval(16*$Xi)."(%rsp)",@Tx[0]);	# X[]+K xfer to IALU
 	 eval(shift(@insns));
 	 eval(shift(@insns));
 
 	foreach (@insns) { eval; }
   $Xi++;
 }
 
 sub Xtail_avx()
 { use integer;
   my $body = shift;
   my @insns = (&$body,&$body,&$body,&$body);	# 32 instructions
   my ($a,$b,$c,$d,$e);
 
 	foreach (@insns) { eval; }
 }
 
 $code.=<<___;
 .align	32
 .Loop_avx:
 ___
 	&Xupdate_avx_16_31(\&body_00_19);
 	&Xupdate_avx_16_31(\&body_00_19);
 	&Xupdate_avx_16_31(\&body_00_19);
 	&Xupdate_avx_16_31(\&body_00_19);
 	&Xupdate_avx_32_79(\&body_00_19);
 	&Xupdate_avx_32_79(\&body_20_39);
 	&Xupdate_avx_32_79(\&body_20_39);
 	&Xupdate_avx_32_79(\&body_20_39);
 	&Xupdate_avx_32_79(\&body_20_39);
 	&Xupdate_avx_32_79(\&body_20_39);
 	&Xupdate_avx_32_79(\&body_40_59);
 	&Xupdate_avx_32_79(\&body_40_59);
 	&Xupdate_avx_32_79(\&body_40_59);
 	&Xupdate_avx_32_79(\&body_40_59);
 	&Xupdate_avx_32_79(\&body_40_59);
 	&Xupdate_avx_32_79(\&body_20_39);
 	&Xuplast_avx_80(\&body_20_39,".Ldone_avx");	# can jump to "done"
 
 				$saved_j=$j; @saved_V=@V;
 				$saved_r=$r; @saved_rndkey=@rndkey;
 
 	&Xloop_avx(\&body_20_39);
 	&Xloop_avx(\&body_20_39);
 	&Xloop_avx(\&body_20_39);
 
 $code.=<<___;
 	vmovups	$iv,48($out,$in0)		# write output
 	lea	64($in0),$in0
 
 	add	0($ctx),$A			# update context
 	add	4($ctx),@T[0]
 	add	8($ctx),$C
 	add	12($ctx),$D
 	mov	$A,0($ctx)
 	add	16($ctx),$E
 	mov	@T[0],4($ctx)
 	mov	@T[0],$B			# magic seed
 	mov	$C,8($ctx)
 	mov	$C,@T[1]
 	mov	$D,12($ctx)
 	xor	$D,@T[1]
 	mov	$E,16($ctx)
 	and	@T[1],@T[0]
 	jmp	.Loop_avx
 
 .Ldone_avx:
 ___
 				$jj=$j=$saved_j; @V=@saved_V;
 				$r=$saved_r;     @rndkey=@saved_rndkey;
 
 	&Xtail_avx(\&body_20_39);
 	&Xtail_avx(\&body_20_39);
 	&Xtail_avx(\&body_20_39);
 
 $code.=<<___;
 	vmovups	$iv,48($out,$in0)		# write output
 	mov	88(%rsp),$ivp			# restore $ivp
 
 	add	0($ctx),$A			# update context
 	add	4($ctx),@T[0]
 	add	8($ctx),$C
 	mov	$A,0($ctx)
 	add	12($ctx),$D
 	mov	@T[0],4($ctx)
 	add	16($ctx),$E
 	mov	$C,8($ctx)
 	mov	$D,12($ctx)
 	mov	$E,16($ctx)
 	vmovups	$iv,($ivp)			# write IV
 	vzeroall
 ___
 $code.=<<___ if ($win64);
 	movaps	96+0(%rsp),%xmm6
 	movaps	96+16(%rsp),%xmm7
 	movaps	96+32(%rsp),%xmm8
 	movaps	96+48(%rsp),%xmm9
 	movaps	96+64(%rsp),%xmm10
 	movaps	96+80(%rsp),%xmm11
 	movaps	96+96(%rsp),%xmm12
 	movaps	96+112(%rsp),%xmm13
 	movaps	96+128(%rsp),%xmm14
 	movaps	96+144(%rsp),%xmm15
 ___
 $code.=<<___;
 	lea	`104+($win64?10*16:0)`(%rsp),%rsi
 	mov	0(%rsi),%r15
 	mov	8(%rsi),%r14
 	mov	16(%rsi),%r13
 	mov	24(%rsi),%r12
 	mov	32(%rsi),%rbp
 	mov	40(%rsi),%rbx
 	lea	48(%rsi),%rsp
 .Lepilogue_avx:
 	ret
 .size	aesni_cbc_sha1_enc_avx,.-aesni_cbc_sha1_enc_avx
 ___
 
 						if ($stitched_decrypt) {{{
 # reset
 ($in0,$out,$len,$key,$ivp,$ctx,$inp)=("%rdi","%rsi","%rdx","%rcx","%r8","%r9","%r10");
 
 $j=$jj=$r=$rx=0;
 $Xi=4;
 
 @aes256_dec = (
 	'&vpxor	($inout0,$rndkey0,"0x00($in0)");',
 	'&vpxor	($inout1,$rndkey0,"0x10($in0)");',
 	'&vpxor	($inout2,$rndkey0,"0x20($in0)");',
 	'&vpxor	($inout3,$rndkey0,"0x30($in0)");',
 
 	'&vmovups($rndkey0,"16-112($key)");',
 	'&vmovups("64(%rsp)",@X[2]);',		# save IV, originally @X[3]
 	undef,undef
 	);
 for ($i=0;$i<13;$i++) {
     push (@aes256_dec,(
 	'&vaesdec	($inout0,$inout0,$rndkey0);',
 	'&vaesdec	($inout1,$inout1,$rndkey0);',
 	'&vaesdec	($inout2,$inout2,$rndkey0);',
 	'&vaesdec	($inout3,$inout3,$rndkey0);	&vmovups($rndkey0,"'.(16*($i+2)-112).'($key)");'
 	));
     push (@aes256_dec,(undef,undef))	if (($i>=3 && $i<=5) || $i>=11);
     push (@aes256_dec,(undef,undef))	if ($i==5);
 }
 push(@aes256_dec,(
 	'&vaesdeclast	($inout0,$inout0,$rndkey0);	&vmovups(@X[0],"0x00($in0)");',
 	'&vaesdeclast	($inout1,$inout1,$rndkey0);	&vmovups(@X[1],"0x10($in0)");',
 	'&vaesdeclast	($inout2,$inout2,$rndkey0);	&vmovups(@X[2],"0x20($in0)");',
 	'&vaesdeclast	($inout3,$inout3,$rndkey0);	&vmovups(@X[3],"0x30($in0)");',
 
 	'&vxorps	($inout0,$inout0,"64(%rsp)");	&vmovdqu($rndkey0,"-112($key)");',
 	'&vxorps	($inout1,$inout1,@X[0]);	&vmovups("0x00($out,$in0)",$inout0);',
 	'&vxorps	($inout2,$inout2,@X[1]);	&vmovups("0x10($out,$in0)",$inout1);',
 	'&vxorps	($inout3,$inout3,@X[2]);	&vmovups("0x20($out,$in0)",$inout2);',
 
 	'&vmovups	("0x30($out,$in0)",$inout3);'
 	));
 
 $code.=<<___;
 .type	aesni256_cbc_sha1_dec_avx,\@function,6
 .align	32
 aesni256_cbc_sha1_dec_avx:
 	mov	`($win64?56:8)`(%rsp),$inp	# load 7th argument
 	push	%rbx
 	push	%rbp
 	push	%r12
 	push	%r13
 	push	%r14
 	push	%r15
 	lea	`-104-($win64?10*16:0)`(%rsp),%rsp
 ___
 $code.=<<___ if ($win64);
 	movaps	%xmm6,96+0(%rsp)
 	movaps	%xmm7,96+16(%rsp)
 	movaps	%xmm8,96+32(%rsp)
 	movaps	%xmm9,96+48(%rsp)
 	movaps	%xmm10,96+64(%rsp)
 	movaps	%xmm11,96+80(%rsp)
 	movaps	%xmm12,96+96(%rsp)
 	movaps	%xmm13,96+112(%rsp)
 	movaps	%xmm14,96+128(%rsp)
 	movaps	%xmm15,96+144(%rsp)
 .Lprologue_dec_avx:
 ___
 $code.=<<___;
 	vzeroall
 	mov	$in0,%r12			# reassign arguments
 	mov	$out,%r13
 	mov	$len,%r14
 	lea	112($key),%r15			# size optimization
 	vmovdqu	($ivp),@X[3]			# load IV
 ___
 ($in0,$out,$len,$key)=map("%r$_",(12..15));	# reassign arguments
 $code.=<<___;
 	shl	\$6,$len
 	sub	$in0,$out
 	add	$inp,$len		# end of input
 
 	lea	K_XX_XX(%rip),$K_XX_XX
 	mov	0($ctx),$A		# load context
 	mov	4($ctx),$B
 	mov	8($ctx),$C
 	mov	12($ctx),$D
 	mov	$B,@T[0]		# magic seed
 	mov	16($ctx),$E
 	mov	$C,@T[1]
 	xor	$D,@T[1]
 	and	@T[1],@T[0]
 
 	vmovdqa	64($K_XX_XX),@X[2]	# pbswap mask
 	vmovdqa	0($K_XX_XX),$Kx		# K_00_19
 	vmovdqu	0($inp),@X[-4&7]	# load input to %xmm[0-3]
 	vmovdqu	16($inp),@X[-3&7]
 	vmovdqu	32($inp),@X[-2&7]
 	vmovdqu	48($inp),@X[-1&7]
 	vpshufb	@X[2],@X[-4&7],@X[-4&7]	# byte swap
 	add	\$64,$inp
 	vpshufb	@X[2],@X[-3&7],@X[-3&7]
 	vpshufb	@X[2],@X[-2&7],@X[-2&7]
 	vpshufb	@X[2],@X[-1&7],@X[-1&7]
 	vpaddd	$Kx,@X[-4&7],@X[0]	# add K_00_19
 	vpaddd	$Kx,@X[-3&7],@X[1]
 	vpaddd	$Kx,@X[-2&7],@X[2]
 	vmovdqa	@X[0],0(%rsp)		# X[]+K xfer to IALU
 	vmovdqa	@X[1],16(%rsp)
 	vmovdqa	@X[2],32(%rsp)
 	vmovups	-112($key),$rndkey0	# $key[0]
 	jmp	.Loop_dec_avx
 
 .align	32
 .Loop_dec_avx:
 ___
 	&Xupdate_avx_16_31(\&body_00_19_dec);
 	&Xupdate_avx_16_31(\&body_00_19_dec);
 	&Xupdate_avx_16_31(\&body_00_19_dec);
 	&Xupdate_avx_16_31(\&body_00_19_dec);
 	&Xupdate_avx_32_79(\&body_00_19_dec);
 	&Xupdate_avx_32_79(\&body_20_39_dec);
 	&Xupdate_avx_32_79(\&body_20_39_dec);
 	&Xupdate_avx_32_79(\&body_20_39_dec);
 	&Xupdate_avx_32_79(\&body_20_39_dec);
 	&Xupdate_avx_32_79(\&body_20_39_dec);
 	&Xupdate_avx_32_79(\&body_40_59_dec);
 	&Xupdate_avx_32_79(\&body_40_59_dec);
 	&Xupdate_avx_32_79(\&body_40_59_dec);
 	&Xupdate_avx_32_79(\&body_40_59_dec);
 	&Xupdate_avx_32_79(\&body_40_59_dec);
 	&Xupdate_avx_32_79(\&body_20_39_dec);
 	&Xuplast_avx_80(\&body_20_39_dec,".Ldone_dec_avx");	# can jump to "done"
 
 				$saved_j=$j; @saved_V=@V;
 				$saved_rx=$rx;
 
 	&Xloop_avx(\&body_20_39_dec);
 	&Xloop_avx(\&body_20_39_dec);
 	&Xloop_avx(\&body_20_39_dec);
 
 	eval(@aes256_dec[-1]);			# last store
 $code.=<<___;
 	lea	64($in0),$in0
 
 	add	0($ctx),$A			# update context
 	add	4($ctx),@T[0]
 	add	8($ctx),$C
 	add	12($ctx),$D
 	mov	$A,0($ctx)
 	add	16($ctx),$E
 	mov	@T[0],4($ctx)
 	mov	@T[0],$B			# magic seed
 	mov	$C,8($ctx)
 	mov	$C,@T[1]
 	mov	$D,12($ctx)
 	xor	$D,@T[1]
 	mov	$E,16($ctx)
 	and	@T[1],@T[0]
 	jmp	.Loop_dec_avx
 
 .Ldone_dec_avx:
 ___
 				$jj=$j=$saved_j; @V=@saved_V;
 				$rx=$saved_rx;
 
 	&Xtail_avx(\&body_20_39_dec);
 	&Xtail_avx(\&body_20_39_dec);
 	&Xtail_avx(\&body_20_39_dec);
 
 	eval(@aes256_dec[-1]);			# last store
 $code.=<<___;
 
 	add	0($ctx),$A			# update context
 	add	4($ctx),@T[0]
 	add	8($ctx),$C
 	mov	$A,0($ctx)
 	add	12($ctx),$D
 	mov	@T[0],4($ctx)
 	add	16($ctx),$E
 	mov	$C,8($ctx)
 	mov	$D,12($ctx)
 	mov	$E,16($ctx)
 	vmovups	@X[3],($ivp)			# write IV
 	vzeroall
 ___
 $code.=<<___ if ($win64);
 	movaps	96+0(%rsp),%xmm6
 	movaps	96+16(%rsp),%xmm7
 	movaps	96+32(%rsp),%xmm8
 	movaps	96+48(%rsp),%xmm9
 	movaps	96+64(%rsp),%xmm10
 	movaps	96+80(%rsp),%xmm11
 	movaps	96+96(%rsp),%xmm12
 	movaps	96+112(%rsp),%xmm13
 	movaps	96+128(%rsp),%xmm14
 	movaps	96+144(%rsp),%xmm15
 ___
 $code.=<<___;
 	lea	`104+($win64?10*16:0)`(%rsp),%rsi
 	mov	0(%rsi),%r15
 	mov	8(%rsi),%r14
 	mov	16(%rsi),%r13
 	mov	24(%rsi),%r12
 	mov	32(%rsi),%rbp
 	mov	40(%rsi),%rbx
 	lea	48(%rsi),%rsp
 .Lepilogue_dec_avx:
 	ret
 .size	aesni256_cbc_sha1_dec_avx,.-aesni256_cbc_sha1_dec_avx
 ___
 						}}}
 }
 $code.=<<___;
 .align	64
 K_XX_XX:
 .long	0x5a827999,0x5a827999,0x5a827999,0x5a827999	# K_00_19
 .long	0x6ed9eba1,0x6ed9eba1,0x6ed9eba1,0x6ed9eba1	# K_20_39
 .long	0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc	# K_40_59
 .long	0xca62c1d6,0xca62c1d6,0xca62c1d6,0xca62c1d6	# K_60_79
 .long	0x00010203,0x04050607,0x08090a0b,0x0c0d0e0f	# pbswap mask
 .byte	0xf,0xe,0xd,0xc,0xb,0xa,0x9,0x8,0x7,0x6,0x5,0x4,0x3,0x2,0x1,0x0
 
 .asciz	"AESNI-CBC+SHA1 stitch for x86_64, CRYPTOGAMS by "
 .align	64
 ___
 						if ($shaext) {{{
 ($in0,$out,$len,$key,$ivp,$ctx,$inp)=("%rdi","%rsi","%rdx","%rcx","%r8","%r9","%r10");
 
 $rounds="%r11d";
 
 ($iv,$in,$rndkey0)=map("%xmm$_",(2,14,15));
 @rndkey=("%xmm0","%xmm1");
 $r=0;
 
 my ($BSWAP,$ABCD,$E,$E_,$ABCD_SAVE,$E_SAVE)=map("%xmm$_",(7..12));
 my @MSG=map("%xmm$_",(3..6));
 
 $code.=<<___;
 .type	aesni_cbc_sha1_enc_shaext,\@function,6
 .align	32
 aesni_cbc_sha1_enc_shaext:
 	mov	`($win64?56:8)`(%rsp),$inp	# load 7th argument
 ___
 $code.=<<___ if ($win64);
 	lea	`-8-10*16`(%rsp),%rsp
 	movaps	%xmm6,-8-10*16(%rax)
 	movaps	%xmm7,-8-9*16(%rax)
 	movaps	%xmm8,-8-8*16(%rax)
 	movaps	%xmm9,-8-7*16(%rax)
 	movaps	%xmm10,-8-6*16(%rax)
 	movaps	%xmm11,-8-5*16(%rax)
 	movaps	%xmm12,-8-4*16(%rax)
 	movaps	%xmm13,-8-3*16(%rax)
 	movaps	%xmm14,-8-2*16(%rax)
 	movaps	%xmm15,-8-1*16(%rax)
 .Lprologue_shaext:
 ___
 $code.=<<___;
 	movdqu	($ctx),$ABCD
 	movd	16($ctx),$E
 	movdqa	K_XX_XX+0x50(%rip),$BSWAP	# byte-n-word swap
 
 	mov	240($key),$rounds
 	sub	$in0,$out
 	movups	($key),$rndkey0			# $key[0]
+	movups	($ivp),$iv			# load IV
 	movups	16($key),$rndkey[0]		# forward reference
 	lea	112($key),$key			# size optimization
 
 	pshufd	\$0b00011011,$ABCD,$ABCD	# flip word order
 	pshufd	\$0b00011011,$E,$E		# flip word order
 	jmp	.Loop_shaext
 
 .align	16
 .Loop_shaext:
 ___
 	&$aesenc();
 $code.=<<___;
 	movdqu		($inp),@MSG[0]
 	movdqa		$E,$E_SAVE		# offload $E
 	pshufb		$BSWAP,@MSG[0]
 	movdqu		0x10($inp),@MSG[1]
 	movdqa		$ABCD,$ABCD_SAVE	# offload $ABCD
 ___
 	&$aesenc();
 $code.=<<___;
 	pshufb		$BSWAP,@MSG[1]
 
 	paddd		@MSG[0],$E
 	movdqu		0x20($inp),@MSG[2]
 	lea		0x40($inp),$inp
 	pxor		$E_SAVE,@MSG[0]		# black magic
 ___
 	&$aesenc();
 $code.=<<___;
 	pxor		$E_SAVE,@MSG[0]		# black magic
 	movdqa		$ABCD,$E_
 	pshufb		$BSWAP,@MSG[2]
 	sha1rnds4	\$0,$E,$ABCD		# 0-3
 	sha1nexte	@MSG[1],$E_
 ___
 	&$aesenc();
 $code.=<<___;
 	sha1msg1	@MSG[1],@MSG[0]
 	movdqu		-0x10($inp),@MSG[3]
 	movdqa		$ABCD,$E
 	pshufb		$BSWAP,@MSG[3]
 ___
 	&$aesenc();
 $code.=<<___;
 	sha1rnds4	\$0,$E_,$ABCD		# 4-7
 	sha1nexte	@MSG[2],$E
 	pxor		@MSG[2],@MSG[0]
 	sha1msg1	@MSG[2],@MSG[1]
 ___
 	&$aesenc();
 
 for($i=2;$i<20-4;$i++) {
 $code.=<<___;
 	movdqa		$ABCD,$E_
 	sha1rnds4	\$`int($i/5)`,$E,$ABCD	# 8-11
 	sha1nexte	@MSG[3],$E_
 ___
 	&$aesenc();
 $code.=<<___;
 	sha1msg2	@MSG[3],@MSG[0]
 	pxor		@MSG[3],@MSG[1]
 	sha1msg1	@MSG[3],@MSG[2]
 ___
 	($E,$E_)=($E_,$E);
 	push(@MSG,shift(@MSG));
 
 	&$aesenc();
 }
 $code.=<<___;
 	movdqa		$ABCD,$E_
 	sha1rnds4	\$3,$E,$ABCD		# 64-67
 	sha1nexte	@MSG[3],$E_
 	sha1msg2	@MSG[3],@MSG[0]
 	pxor		@MSG[3],@MSG[1]
 ___
 	&$aesenc();
 $code.=<<___;
 	movdqa		$ABCD,$E
 	sha1rnds4	\$3,$E_,$ABCD		# 68-71
 	sha1nexte	@MSG[0],$E
 	sha1msg2	@MSG[0],@MSG[1]
 ___
 	&$aesenc();
 $code.=<<___;
 	movdqa		$E_SAVE,@MSG[0]
 	movdqa		$ABCD,$E_
 	sha1rnds4	\$3,$E,$ABCD		# 72-75
 	sha1nexte	@MSG[1],$E_
 ___
 	&$aesenc();
 $code.=<<___;
 	movdqa		$ABCD,$E
 	sha1rnds4	\$3,$E_,$ABCD		# 76-79
 	sha1nexte	$MSG[0],$E
 ___
 	while($r<40)	{ &$aesenc(); }		# remaining aesenc's
 $code.=<<___;
 	dec		$len
 
 	paddd		$ABCD_SAVE,$ABCD
 	movups		$iv,48($out,$in0)	# write output
 	lea		64($in0),$in0
 	jnz		.Loop_shaext
 
 	pshufd	\$0b00011011,$ABCD,$ABCD
 	pshufd	\$0b00011011,$E,$E
 	movups	$iv,($ivp)			# write IV
 	movdqu	$ABCD,($ctx)
 	movd	$E,16($ctx)
 ___
 $code.=<<___ if ($win64);
 	movaps	-8-10*16(%rax),%xmm6
 	movaps	-8-9*16(%rax),%xmm7
 	movaps	-8-8*16(%rax),%xmm8
 	movaps	-8-7*16(%rax),%xmm9
 	movaps	-8-6*16(%rax),%xmm10
 	movaps	-8-5*16(%rax),%xmm11
 	movaps	-8-4*16(%rax),%xmm12
 	movaps	-8-3*16(%rax),%xmm13
 	movaps	-8-2*16(%rax),%xmm14
 	movaps	-8-1*16(%rax),%xmm15
 	mov	%rax,%rsp
 .Lepilogue_shaext:
 ___
 $code.=<<___;
 	ret
 .size	aesni_cbc_sha1_enc_shaext,.-aesni_cbc_sha1_enc_shaext
 ___
 						}}}
 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
 #		CONTEXT *context,DISPATCHER_CONTEXT *disp)
 if ($win64) {
 $rec="%rcx";
 $frame="%rdx";
 $context="%r8";
 $disp="%r9";
 
 $code.=<<___;
 .extern	__imp_RtlVirtualUnwind
 .type	ssse3_handler,\@abi-omnipotent
 .align	16
 ssse3_handler:
 	push	%rsi
 	push	%rdi
 	push	%rbx
 	push	%rbp
 	push	%r12
 	push	%r13
 	push	%r14
 	push	%r15
 	pushfq
 	sub	\$64,%rsp
 
 	mov	120($context),%rax	# pull context->Rax
 	mov	248($context),%rbx	# pull context->Rip
 
 	mov	8($disp),%rsi		# disp->ImageBase
 	mov	56($disp),%r11		# disp->HandlerData
 
 	mov	0(%r11),%r10d		# HandlerData[0]
 	lea	(%rsi,%r10),%r10	# prologue label
 	cmp	%r10,%rbx		# context->RipRsp
 
 	mov	4(%r11),%r10d		# HandlerData[1]
 	lea	(%rsi,%r10),%r10	# epilogue label
 	cmp	%r10,%rbx		# context->Rip>=epilogue label
 	jae	.Lcommon_seh_tail
 ___
 $code.=<<___ if ($shaext);
 	lea	aesni_cbc_sha1_enc_shaext(%rip),%r10
 	cmp	%r10,%rbx
 	jb	.Lseh_no_shaext
 
 	lea	(%rax),%rsi
 	lea	512($context),%rdi	# &context.Xmm6
 	mov	\$20,%ecx
 	.long	0xa548f3fc		# cld; rep movsq
 	lea	168(%rax),%rax		# adjust stack pointer
 	jmp	.Lcommon_seh_tail
 .Lseh_no_shaext:
 ___
 $code.=<<___;
 	lea	96(%rax),%rsi
 	lea	512($context),%rdi	# &context.Xmm6
 	mov	\$20,%ecx
 	.long	0xa548f3fc		# cld; rep movsq
 	lea	`104+10*16`(%rax),%rax	# adjust stack pointer
 
 	mov	0(%rax),%r15
 	mov	8(%rax),%r14
 	mov	16(%rax),%r13
 	mov	24(%rax),%r12
 	mov	32(%rax),%rbp
 	mov	40(%rax),%rbx
 	lea	48(%rax),%rax
 	mov	%rbx,144($context)	# restore context->Rbx
 	mov	%rbp,160($context)	# restore context->Rbp
 	mov	%r12,216($context)	# restore context->R12
 	mov	%r13,224($context)	# restore context->R13
 	mov	%r14,232($context)	# restore context->R14
 	mov	%r15,240($context)	# restore context->R15
 
 .Lcommon_seh_tail:
 	mov	8(%rax),%rdi
 	mov	16(%rax),%rsi
 	mov	%rax,152($context)	# restore context->Rsp
 	mov	%rsi,168($context)	# restore context->Rsi
 	mov	%rdi,176($context)	# restore context->Rdi
 
 	mov	40($disp),%rdi		# disp->ContextRecord
 	mov	$context,%rsi		# context
 	mov	\$154,%ecx		# sizeof(CONTEXT)
 	.long	0xa548f3fc		# cld; rep movsq
 
 	mov	$disp,%rsi
 	xor	%rcx,%rcx		# arg1, UNW_FLAG_NHANDLER
 	mov	8(%rsi),%rdx		# arg2, disp->ImageBase
 	mov	0(%rsi),%r8		# arg3, disp->ControlPc
 	mov	16(%rsi),%r9		# arg4, disp->FunctionEntry
 	mov	40(%rsi),%r10		# disp->ContextRecord
 	lea	56(%rsi),%r11		# &disp->HandlerData
 	lea	24(%rsi),%r12		# &disp->EstablisherFrame
 	mov	%r10,32(%rsp)		# arg5
 	mov	%r11,40(%rsp)		# arg6
 	mov	%r12,48(%rsp)		# arg7
 	mov	%rcx,56(%rsp)		# arg8, (NULL)
 	call	*__imp_RtlVirtualUnwind(%rip)
 
 	mov	\$1,%eax		# ExceptionContinueSearch
 	add	\$64,%rsp
 	popfq
 	pop	%r15
 	pop	%r14
 	pop	%r13
 	pop	%r12
 	pop	%rbp
 	pop	%rbx
 	pop	%rdi
 	pop	%rsi
 	ret
 .size	ssse3_handler,.-ssse3_handler
 
 .section	.pdata
 .align	4
 	.rva	.LSEH_begin_aesni_cbc_sha1_enc_ssse3
 	.rva	.LSEH_end_aesni_cbc_sha1_enc_ssse3
 	.rva	.LSEH_info_aesni_cbc_sha1_enc_ssse3
 ___
 $code.=<<___ if ($avx);
 	.rva	.LSEH_begin_aesni_cbc_sha1_enc_avx
 	.rva	.LSEH_end_aesni_cbc_sha1_enc_avx
 	.rva	.LSEH_info_aesni_cbc_sha1_enc_avx
 ___
 $code.=<<___ if ($shaext);
 	.rva	.LSEH_begin_aesni_cbc_sha1_enc_shaext
 	.rva	.LSEH_end_aesni_cbc_sha1_enc_shaext
 	.rva	.LSEH_info_aesni_cbc_sha1_enc_shaext
 ___
 $code.=<<___;
 .section	.xdata
 .align	8
 .LSEH_info_aesni_cbc_sha1_enc_ssse3:
 	.byte	9,0,0,0
 	.rva	ssse3_handler
 	.rva	.Lprologue_ssse3,.Lepilogue_ssse3	# HandlerData[]
 ___
 $code.=<<___ if ($avx);
 .LSEH_info_aesni_cbc_sha1_enc_avx:
 	.byte	9,0,0,0
 	.rva	ssse3_handler
 	.rva	.Lprologue_avx,.Lepilogue_avx		# HandlerData[]
 ___
 $code.=<<___ if ($shaext);
 .LSEH_info_aesni_cbc_sha1_enc_shaext:
 	.byte	9,0,0,0
 	.rva	ssse3_handler
 	.rva	.Lprologue_shaext,.Lepilogue_shaext	# HandlerData[]
 ___
 }
 
 ####################################################################
 sub rex {
   local *opcode=shift;
   my ($dst,$src)=@_;
   my $rex=0;
 
     $rex|=0x04			if($dst>=8);
     $rex|=0x01			if($src>=8);
     unshift @opcode,$rex|0x40	if($rex);
 }
 
 sub sha1rnds4 {
     if (@_[0] =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
       my @opcode=(0x0f,0x3a,0xcc);
 	rex(\@opcode,$3,$2);
 	push @opcode,0xc0|($2&7)|(($3&7)<<3);		# ModR/M
 	my $c=$1;
 	push @opcode,$c=~/^0/?oct($c):$c;
 	return ".byte\t".join(',',@opcode);
     } else {
 	return "sha1rnds4\t".@_[0];
     }
 }
 
 sub sha1op38 {
     my $instr = shift;
     my %opcodelet = (
 		"sha1nexte" => 0xc8,
   		"sha1msg1"  => 0xc9,
 		"sha1msg2"  => 0xca	);
 
     if (defined($opcodelet{$instr}) && @_[0] =~ /%xmm([0-9]+),\s*%xmm([0-9]+)/) {
       my @opcode=(0x0f,0x38);
 	rex(\@opcode,$2,$1);
 	push @opcode,$opcodelet{$instr};
 	push @opcode,0xc0|($1&7)|(($2&7)<<3);		# ModR/M
 	return ".byte\t".join(',',@opcode);
     } else {
 	return $instr."\t".@_[0];
     }
 }
 
 sub aesni {
   my $line=shift;
   my @opcode=(0x0f,0x38);
 
     if ($line=~/(aes[a-z]+)\s+%xmm([0-9]+),\s*%xmm([0-9]+)/) {
 	my %opcodelet = (
 		"aesenc" => 0xdc,	"aesenclast" => 0xdd,
 		"aesdec" => 0xde,	"aesdeclast" => 0xdf
 	);
 	return undef if (!defined($opcodelet{$1}));
 	rex(\@opcode,$3,$2);
 	push @opcode,$opcodelet{$1},0xc0|($2&7)|(($3&7)<<3);	# ModR/M
 	unshift @opcode,0x66;
 	return ".byte\t".join(',',@opcode);
     }
     return $line;
 }
 
 foreach (split("\n",$code)) {
         s/\`([^\`]*)\`/eval $1/geo;
 
 	s/\b(sha1rnds4)\s+(.*)/sha1rnds4($2)/geo		or
 	s/\b(sha1[^\s]*)\s+(.*)/sha1op38($1,$2)/geo		or
 	s/\b(aes.*%xmm[0-9]+).*$/aesni($1)/geo;
 
 	print $_,"\n";
 }
 close STDOUT;
Index: vendor-crypto/openssl/dist/crypto/aes/asm/aesni-sha256-x86_64.pl
===================================================================
--- vendor-crypto/openssl/dist/crypto/aes/asm/aesni-sha256-x86_64.pl	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/aes/asm/aesni-sha256-x86_64.pl	(revision 318897)
@@ -1,1705 +1,1706 @@
 #!/usr/bin/env perl
 #
 # ====================================================================
 # Written by Andy Polyakov  for the OpenSSL
 # project. The module is, however, dual licensed under OpenSSL and
 # CRYPTOGAMS licenses depending on where you obtain it. For further
 # details see http://www.openssl.org/~appro/cryptogams/.
 # ====================================================================
 #
 # January 2013
 #
 # This is AESNI-CBC+SHA256 stitch implementation. The idea, as spelled
 # in http://download.intel.com/design/intarch/papers/323686.pdf, is
 # that since AESNI-CBC encrypt exhibit *very* low instruction-level
 # parallelism, interleaving it with another algorithm would allow to
 # utilize processor resources better and achieve better performance.
 # SHA256 instruction sequences(*) are taken from sha512-x86_64.pl and
 # AESNI code is weaved into it. As SHA256 dominates execution time,
 # stitch performance does not depend on AES key length. Below are
 # performance numbers in cycles per processed byte, less is better,
 # for standalone AESNI-CBC encrypt, standalone SHA256, and stitched
 # subroutine:
 #
 #		 AES-128/-192/-256+SHA256	this(**)gain
 # Sandy Bridge	    5.05/6.05/7.05+11.6		13.0	+28%/36%/43%
 # Ivy Bridge	    5.05/6.05/7.05+10.3		11.6	+32%/41%/50%
 # Haswell	    4.43/5.29/6.19+7.80		8.79	+39%/49%/59%
 # Bulldozer	    5.77/6.89/8.00+13.7		13.7	+42%/50%/58%
 #
 # (*)	there are XOP, AVX1 and AVX2 code pathes, meaning that
 #	Westmere is omitted from loop, this is because gain was not
 #	estimated high enough to justify the effort;
 # (**)	these are EVP-free results, results obtained with 'speed
 #	-evp aes-256-cbc-hmac-sha256' will vary by percent or two;
 
 $flavour = shift;
 $output  = shift;
 if ($flavour =~ /\./) { $output = $flavour; undef $flavour; }
 
 $win64=0; $win64=1 if ($flavour =~ /[nm]asm|mingw64/ || $output =~ /\.asm$/);
 
 $0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1;
 ( $xlate="${dir}x86_64-xlate.pl" and -f $xlate ) or
 ( $xlate="${dir}../../perlasm/x86_64-xlate.pl" and -f $xlate) or
 die "can't locate x86_64-xlate.pl";
 
 if (`$ENV{CC} -Wa,-v -c -o /dev/null -x assembler /dev/null 2>&1`
 		=~ /GNU assembler version ([2-9]\.[0-9]+)/) {
 	$avx = ($1>=2.19) + ($1>=2.22);
 }
 
 if (!$avx && $win64 && ($flavour =~ /nasm/ || $ENV{ASM} =~ /nasm/) &&
 	   `nasm -v 2>&1` =~ /NASM version ([2-9]\.[0-9]+)/) {
 	$avx = ($1>=2.09) + ($1>=2.10);
 }
 
 if (!$avx && $win64 && ($flavour =~ /masm/ || $ENV{ASM} =~ /ml64/) &&
 	   `ml64 2>&1` =~ /Version ([0-9]+)\./) {
 	$avx = ($1>=10) + ($1>=12);
 }
 
 if (!$avx && `$ENV{CC} -v 2>&1` =~ /((?:^clang|LLVM) version|.*based on LLVM) ([3-9]\.[0-9]+)/) {
 	$avx = ($2>=3.0) + ($2>3.0);
 }
 
 $shaext=$avx;	### set to zero if compiling for 1.0.1
 $avx=1		if (!$shaext && $avx);
 
 open OUT,"| \"$^X\" $xlate $flavour $output";
 *STDOUT=*OUT;
 
 $func="aesni_cbc_sha256_enc";
 $TABLE="K256";
 $SZ=4;
 @ROT=($A,$B,$C,$D,$E,$F,$G,$H)=("%eax","%ebx","%ecx","%edx",
 				"%r8d","%r9d","%r10d","%r11d");
 ($T1,$a0,$a1,$a2,$a3)=("%r12d","%r13d","%r14d","%r15d","%esi");
 @Sigma0=( 2,13,22);
 @Sigma1=( 6,11,25);
 @sigma0=( 7,18, 3);
 @sigma1=(17,19,10);
 $rounds=64;
 
 ########################################################################
 # void aesni_cbc_sha256_enc(const void *inp,
 #			void *out,
 #			size_t length,
 #			const AES_KEY *key,
 #			unsigned char *iv,
 #			SHA256_CTX *ctx,
 #			const void *in0);
 ($inp,  $out,  $len,  $key,  $ivp, $ctx, $in0) =
 ("%rdi","%rsi","%rdx","%rcx","%r8","%r9","%r10");
 
 $Tbl="%rbp";
 
 $_inp="16*$SZ+0*8(%rsp)";
 $_out="16*$SZ+1*8(%rsp)";
 $_end="16*$SZ+2*8(%rsp)";
 $_key="16*$SZ+3*8(%rsp)";
 $_ivp="16*$SZ+4*8(%rsp)";
 $_ctx="16*$SZ+5*8(%rsp)";
 $_in0="16*$SZ+6*8(%rsp)";
 $_rsp="16*$SZ+7*8(%rsp)";
 $framesz=16*$SZ+8*8;
 
 $code=<<___;
 .text
 
 .extern	OPENSSL_ia32cap_P
 .globl	$func
 .type	$func,\@abi-omnipotent
 .align	16
 $func:
 ___
 						if ($avx) {
 $code.=<<___;
 	lea	OPENSSL_ia32cap_P(%rip),%r11
 	mov	\$1,%eax
 	cmp	\$0,`$win64?"%rcx":"%rdi"`
 	je	.Lprobe
 	mov	0(%r11),%eax
 	mov	4(%r11),%r10
 ___
 $code.=<<___ if ($shaext);
 	bt	\$61,%r10			# check for SHA
 	jc	${func}_shaext
 ___
 $code.=<<___;
 	mov	%r10,%r11
 	shr	\$32,%r11
 
 	test	\$`1<<11`,%r10d			# check for XOP
 	jnz	${func}_xop
 ___
 $code.=<<___ if ($avx>1);
 	and	\$`1<<8|1<<5|1<<3`,%r11d	# check for BMI2+AVX2+BMI1
 	cmp	\$`1<<8|1<<5|1<<3`,%r11d
 	je	${func}_avx2
 ___
 $code.=<<___;
 	and	\$`1<<28`,%r10d			# check for AVX
 	jnz	${func}_avx
 	ud2
 ___
 						}
 $code.=<<___;
 	xor	%eax,%eax
 	cmp	\$0,`$win64?"%rcx":"%rdi"`
 	je	.Lprobe
 	ud2
 .Lprobe:
 	ret
 .size	$func,.-$func
 
 .align	64
 .type	$TABLE,\@object
 $TABLE:
 	.long	0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5
 	.long	0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5
 	.long	0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5
 	.long	0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5
 	.long	0xd807aa98,0x12835b01,0x243185be,0x550c7dc3
 	.long	0xd807aa98,0x12835b01,0x243185be,0x550c7dc3
 	.long	0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174
 	.long	0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174
 	.long	0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc
 	.long	0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc
 	.long	0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da
 	.long	0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da
 	.long	0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7
 	.long	0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7
 	.long	0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967
 	.long	0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967
 	.long	0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13
 	.long	0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13
 	.long	0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85
 	.long	0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85
 	.long	0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3
 	.long	0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3
 	.long	0xd192e819,0xd6990624,0xf40e3585,0x106aa070
 	.long	0xd192e819,0xd6990624,0xf40e3585,0x106aa070
 	.long	0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5
 	.long	0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5
 	.long	0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3
 	.long	0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3
 	.long	0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208
 	.long	0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208
 	.long	0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2
 	.long	0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2
 
 	.long	0x00010203,0x04050607,0x08090a0b,0x0c0d0e0f
 	.long	0x00010203,0x04050607,0x08090a0b,0x0c0d0e0f
 	.long	0,0,0,0,   0,0,0,0,   -1,-1,-1,-1
 	.long	0,0,0,0,   0,0,0,0
 	.asciz	"AESNI-CBC+SHA256 stitch for x86_64, CRYPTOGAMS by "
 .align	64
 ___
 
 ######################################################################
 # SIMD code paths
 #
 {{{
 ($iv,$inout,$roundkey,$temp,
  $mask10,$mask12,$mask14,$offload)=map("%xmm$_",(8..15));
 
 $aesni_cbc_idx=0;
 @aesni_cbc_block = (
 ##	&vmovdqu	($roundkey,"0x00-0x80($inp)");'
 ##	&vmovdqu	($inout,($inp));
 ##	&mov		($_inp,$inp);
 
 	'&vpxor		($inout,$inout,$roundkey);'.
 	' &vmovdqu	($roundkey,"0x10-0x80($inp)");',
 
 	'&vpxor		($inout,$inout,$iv);',
 
 	'&vaesenc	($inout,$inout,$roundkey);'.
 	' &vmovdqu	($roundkey,"0x20-0x80($inp)");',
 
 	'&vaesenc	($inout,$inout,$roundkey);'.
 	' &vmovdqu	($roundkey,"0x30-0x80($inp)");',
 
 	'&vaesenc	($inout,$inout,$roundkey);'.
 	' &vmovdqu	($roundkey,"0x40-0x80($inp)");',
 
 	'&vaesenc	($inout,$inout,$roundkey);'.
 	' &vmovdqu	($roundkey,"0x50-0x80($inp)");',
 
 	'&vaesenc	($inout,$inout,$roundkey);'.
 	' &vmovdqu	($roundkey,"0x60-0x80($inp)");',
 
 	'&vaesenc	($inout,$inout,$roundkey);'.
 	' &vmovdqu	($roundkey,"0x70-0x80($inp)");',
 
 	'&vaesenc	($inout,$inout,$roundkey);'.
 	' &vmovdqu	($roundkey,"0x80-0x80($inp)");',
 
 	'&vaesenc	($inout,$inout,$roundkey);'.
 	' &vmovdqu	($roundkey,"0x90-0x80($inp)");',
 
 	'&vaesenc	($inout,$inout,$roundkey);'.
 	' &vmovdqu	($roundkey,"0xa0-0x80($inp)");',
 
 	'&vaesenclast	($temp,$inout,$roundkey);'.
 	' &vaesenc	($inout,$inout,$roundkey);'.
 	' &vmovdqu	($roundkey,"0xb0-0x80($inp)");',
 
 	'&vpand		($iv,$temp,$mask10);'.
 	' &vaesenc	($inout,$inout,$roundkey);'.
 	' &vmovdqu	($roundkey,"0xc0-0x80($inp)");',
 
 	'&vaesenclast	($temp,$inout,$roundkey);'.
 	' &vaesenc	($inout,$inout,$roundkey);'.
 	' &vmovdqu	($roundkey,"0xd0-0x80($inp)");',
 
 	'&vpand		($temp,$temp,$mask12);'.
 	' &vaesenc	($inout,$inout,$roundkey);'.
 	 '&vmovdqu	($roundkey,"0xe0-0x80($inp)");',
 
 	'&vpor		($iv,$iv,$temp);'.
 	' &vaesenclast	($temp,$inout,$roundkey);'.
 	' &vmovdqu	($roundkey,"0x00-0x80($inp)");'
 
 ##	&mov		($inp,$_inp);
 ##	&mov		($out,$_out);
 ##	&vpand		($temp,$temp,$mask14);
 ##	&vpor		($iv,$iv,$temp);
 ##	&vmovdqu	($iv,($out,$inp);
 ##	&lea		(inp,16($inp));
 );
 
 my $a4=$T1;
 my ($a,$b,$c,$d,$e,$f,$g,$h);
 
 sub AUTOLOAD()		# thunk [simplified] 32-bit style perlasm
 { my $opcode = $AUTOLOAD; $opcode =~ s/.*:://;
   my $arg = pop;
     $arg = "\$$arg" if ($arg*1 eq $arg);
     $code .= "\t$opcode\t".join(',',$arg,reverse @_)."\n";
 }
 
 sub body_00_15 () {
 	(
 	'($a,$b,$c,$d,$e,$f,$g,$h)=@ROT;'.
 
 	'&ror	($a0,$Sigma1[2]-$Sigma1[1])',
 	'&mov	($a,$a1)',
 	'&mov	($a4,$f)',
 
 	'&xor	($a0,$e)',
 	'&ror	($a1,$Sigma0[2]-$Sigma0[1])',
 	'&xor	($a4,$g)',			# f^g
 
 	'&ror	($a0,$Sigma1[1]-$Sigma1[0])',
 	'&xor	($a1,$a)',
 	'&and	($a4,$e)',			# (f^g)&e
 
 	@aesni_cbc_block[$aesni_cbc_idx++].
 	'&xor	($a0,$e)',
 	'&add	($h,$SZ*($i&15)."(%rsp)")',	# h+=X[i]+K[i]
 	'&mov	($a2,$a)',
 
 	'&ror	($a1,$Sigma0[1]-$Sigma0[0])',
 	'&xor	($a4,$g)',			# Ch(e,f,g)=((f^g)&e)^g
 	'&xor	($a2,$b)',			# a^b, b^c in next round
 
 	'&ror	($a0,$Sigma1[0])',		# Sigma1(e)
 	'&add	($h,$a4)',			# h+=Ch(e,f,g)
 	'&and	($a3,$a2)',			# (b^c)&(a^b)
 
 	'&xor	($a1,$a)',
 	'&add	($h,$a0)',			# h+=Sigma1(e)
 	'&xor	($a3,$b)',			# Maj(a,b,c)=Ch(a^b,c,b)
 
 	'&add	($d,$h)',			# d+=h
 	'&ror	($a1,$Sigma0[0])',		# Sigma0(a)
 	'&add	($h,$a3)',			# h+=Maj(a,b,c)
 
 	'&mov	($a0,$d)',
 	'&add	($a1,$h);'.			# h+=Sigma0(a)
 	'($a2,$a3) = ($a3,$a2); unshift(@ROT,pop(@ROT)); $i++;'
 	);
 }
 
 if ($avx) {{
 ######################################################################
 # XOP code path
 #
 $code.=<<___;
 .type	${func}_xop,\@function,6
 .align	64
 ${func}_xop:
 .Lxop_shortcut:
 	mov	`($win64?56:8)`(%rsp),$in0	# load 7th parameter
 	push	%rbx
 	push	%rbp
 	push	%r12
 	push	%r13
 	push	%r14
 	push	%r15
 	mov	%rsp,%r11		# copy %rsp
 	sub	\$`$framesz+$win64*16*10`,%rsp
 	and	\$-64,%rsp		# align stack frame
 
 	shl	\$6,$len
 	sub	$inp,$out		# re-bias
 	sub	$inp,$in0
 	add	$inp,$len		# end of input
 
 	#mov	$inp,$_inp		# saved later
 	mov	$out,$_out
 	mov	$len,$_end
 	#mov	$key,$_key		# remains resident in $inp register
 	mov	$ivp,$_ivp
 	mov	$ctx,$_ctx
 	mov	$in0,$_in0
 	mov	%r11,$_rsp
 ___
 $code.=<<___ if ($win64);
 	movaps	%xmm6,`$framesz+16*0`(%rsp)
 	movaps	%xmm7,`$framesz+16*1`(%rsp)
 	movaps	%xmm8,`$framesz+16*2`(%rsp)
 	movaps	%xmm9,`$framesz+16*3`(%rsp)
 	movaps	%xmm10,`$framesz+16*4`(%rsp)
 	movaps	%xmm11,`$framesz+16*5`(%rsp)
 	movaps	%xmm12,`$framesz+16*6`(%rsp)
 	movaps	%xmm13,`$framesz+16*7`(%rsp)
 	movaps	%xmm14,`$framesz+16*8`(%rsp)
 	movaps	%xmm15,`$framesz+16*9`(%rsp)
 ___
 $code.=<<___;
 .Lprologue_xop:
 	vzeroall
 
 	mov	$inp,%r12		# borrow $a4
 	lea	0x80($key),$inp		# size optimization, reassign
 	lea	$TABLE+`$SZ*2*$rounds+32`(%rip),%r13	# borrow $a0
 	mov	0xf0-0x80($inp),%r14d	# rounds, borrow $a1
 	mov	$ctx,%r15		# borrow $a2
 	mov	$in0,%rsi		# borrow $a3
 	vmovdqu	($ivp),$iv		# load IV
 	sub	\$9,%r14
 
 	mov	$SZ*0(%r15),$A
 	mov	$SZ*1(%r15),$B
 	mov	$SZ*2(%r15),$C
 	mov	$SZ*3(%r15),$D
 	mov	$SZ*4(%r15),$E
 	mov	$SZ*5(%r15),$F
 	mov	$SZ*6(%r15),$G
 	mov	$SZ*7(%r15),$H
 
 	vmovdqa	0x00(%r13,%r14,8),$mask14
 	vmovdqa	0x10(%r13,%r14,8),$mask12
 	vmovdqa	0x20(%r13,%r14,8),$mask10
 	vmovdqu	0x00-0x80($inp),$roundkey
 	jmp	.Lloop_xop
 ___
 					if ($SZ==4) {	# SHA256
     my @X = map("%xmm$_",(0..3));
     my ($t0,$t1,$t2,$t3) = map("%xmm$_",(4..7));
 
 $code.=<<___;
 .align	16
 .Lloop_xop:
 	vmovdqa	$TABLE+`$SZ*2*$rounds`(%rip),$t3
 	vmovdqu	0x00(%rsi,%r12),@X[0]
 	vmovdqu	0x10(%rsi,%r12),@X[1]
 	vmovdqu	0x20(%rsi,%r12),@X[2]
 	vmovdqu	0x30(%rsi,%r12),@X[3]
 	vpshufb	$t3,@X[0],@X[0]
 	lea	$TABLE(%rip),$Tbl
 	vpshufb	$t3,@X[1],@X[1]
 	vpshufb	$t3,@X[2],@X[2]
 	vpaddd	0x00($Tbl),@X[0],$t0
 	vpshufb	$t3,@X[3],@X[3]
 	vpaddd	0x20($Tbl),@X[1],$t1
 	vpaddd	0x40($Tbl),@X[2],$t2
 	vpaddd	0x60($Tbl),@X[3],$t3
 	vmovdqa	$t0,0x00(%rsp)
 	mov	$A,$a1
 	vmovdqa	$t1,0x10(%rsp)
 	mov	$B,$a3
 	vmovdqa	$t2,0x20(%rsp)
 	xor	$C,$a3			# magic
 	vmovdqa	$t3,0x30(%rsp)
 	mov	$E,$a0
 	jmp	.Lxop_00_47
 
 .align	16
 .Lxop_00_47:
 	sub	\$-16*2*$SZ,$Tbl	# size optimization
 	vmovdqu	(%r12),$inout		# $a4
 	mov	%r12,$_inp		# $a4
 ___
 sub XOP_256_00_47 () {
 my $j = shift;
 my $body = shift;
 my @X = @_;
 my @insns = (&$body,&$body,&$body,&$body);	# 104 instructions
 
 	&vpalignr	($t0,@X[1],@X[0],$SZ);	# X[1..4]
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	 &vpalignr	($t3,@X[3],@X[2],$SZ);	# X[9..12]
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	&vprotd		($t1,$t0,8*$SZ-$sigma0[1]);
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	&vpsrld		($t0,$t0,$sigma0[2]);
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	 &vpaddd	(@X[0],@X[0],$t3);	# X[0..3] += X[9..12]
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	&vprotd		($t2,$t1,$sigma0[1]-$sigma0[0]);
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	&vpxor		($t0,$t0,$t1);
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	 &vprotd	($t3,@X[3],8*$SZ-$sigma1[1]);
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	&vpxor		($t0,$t0,$t2);		# sigma0(X[1..4])
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	 &vpsrld	($t2,@X[3],$sigma1[2]);
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	&vpaddd		(@X[0],@X[0],$t0);	# X[0..3] += sigma0(X[1..4])
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	 &vprotd	($t1,$t3,$sigma1[1]-$sigma1[0]);
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	 &vpxor		($t3,$t3,$t2);
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	 &vpxor		($t3,$t3,$t1);		# sigma1(X[14..15])
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	&vpsrldq	($t3,$t3,8);
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	&vpaddd		(@X[0],@X[0],$t3);	# X[0..1] += sigma1(X[14..15])
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	 &vprotd	($t3,@X[0],8*$SZ-$sigma1[1]);
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	 &vpsrld	($t2,@X[0],$sigma1[2]);
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	 &vprotd	($t1,$t3,$sigma1[1]-$sigma1[0]);
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	 &vpxor		($t3,$t3,$t2);
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	 &vpxor		($t3,$t3,$t1);		# sigma1(X[16..17])
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	&vpslldq	($t3,$t3,8);		# 22 instructions
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	&vpaddd		(@X[0],@X[0],$t3);	# X[2..3] += sigma1(X[16..17])
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	  eval(shift(@insns));
 	&vpaddd		($t2,@X[0],16*2*$j."($Tbl)");
 	  foreach (@insns) { eval; }		# remaining instructions
 	&vmovdqa	(16*$j."(%rsp)",$t2);
 }
 
     $aesni_cbc_idx=0;
     for ($i=0,$j=0; $j<4; $j++) {
 	&XOP_256_00_47($j,\&body_00_15,@X);
 	push(@X,shift(@X));			# rotate(@X)
     }
     	&mov		("%r12",$_inp);		# borrow $a4
 	&vpand		($temp,$temp,$mask14);
 	&mov		("%r15",$_out);		# borrow $a2
 	&vpor		($iv,$iv,$temp);
 	&vmovdqu	("(%r15,%r12)",$iv);	# write output
 	&lea		("%r12","16(%r12)");	# inp++
 
 	&cmpb	($SZ-1+16*2*$SZ."($Tbl)",0);
 	&jne	(".Lxop_00_47");
 
 	&vmovdqu	($inout,"(%r12)");
 	&mov		($_inp,"%r12");
 
     $aesni_cbc_idx=0;
     for ($i=0; $i<16; ) {
 	foreach(body_00_15()) { eval; }
     }
 					}
 $code.=<<___;
 	mov	$_inp,%r12		# borrow $a4
 	mov	$_out,%r13		# borrow $a0
 	mov	$_ctx,%r15		# borrow $a2
 	mov	$_in0,%rsi		# borrow $a3
 
 	vpand	$mask14,$temp,$temp
 	mov	$a1,$A
 	vpor	$temp,$iv,$iv
 	vmovdqu	$iv,(%r13,%r12)		# write output
 	lea	16(%r12),%r12		# inp++
 
 	add	$SZ*0(%r15),$A
 	add	$SZ*1(%r15),$B
 	add	$SZ*2(%r15),$C
 	add	$SZ*3(%r15),$D
 	add	$SZ*4(%r15),$E
 	add	$SZ*5(%r15),$F
 	add	$SZ*6(%r15),$G
 	add	$SZ*7(%r15),$H
 
 	cmp	$_end,%r12
 
 	mov	$A,$SZ*0(%r15)
 	mov	$B,$SZ*1(%r15)
 	mov	$C,$SZ*2(%r15)
 	mov	$D,$SZ*3(%r15)
 	mov	$E,$SZ*4(%r15)
 	mov	$F,$SZ*5(%r15)
 	mov	$G,$SZ*6(%r15)
 	mov	$H,$SZ*7(%r15)
 
 	jb	.Lloop_xop
 
 	mov	$_ivp,$ivp
 	mov	$_rsp,%rsi
 	vmovdqu	$iv,($ivp)		# output IV
 	vzeroall
 ___
 $code.=<<___ if ($win64);
 	movaps	`$framesz+16*0`(%rsp),%xmm6
 	movaps	`$framesz+16*1`(%rsp),%xmm7
 	movaps	`$framesz+16*2`(%rsp),%xmm8
 	movaps	`$framesz+16*3`(%rsp),%xmm9
 	movaps	`$framesz+16*4`(%rsp),%xmm10
 	movaps	`$framesz+16*5`(%rsp),%xmm11
 	movaps	`$framesz+16*6`(%rsp),%xmm12
 	movaps	`$framesz+16*7`(%rsp),%xmm13
 	movaps	`$framesz+16*8`(%rsp),%xmm14
 	movaps	`$framesz+16*9`(%rsp),%xmm15
 ___
 $code.=<<___;
 	mov	(%rsi),%r15
 	mov	8(%rsi),%r14
 	mov	16(%rsi),%r13
 	mov	24(%rsi),%r12
 	mov	32(%rsi),%rbp
 	mov	40(%rsi),%rbx
 	lea	48(%rsi),%rsp
 .Lepilogue_xop:
 	ret
 .size	${func}_xop,.-${func}_xop
 ___
 ######################################################################
 # AVX+shrd code path
 #
 local *ror = sub { &shrd(@_[0],@_) };
 
 $code.=<<___;
 .type	${func}_avx,\@function,6
 .align	64
 ${func}_avx:
 .Lavx_shortcut:
 	mov	`($win64?56:8)`(%rsp),$in0	# load 7th parameter
 	push	%rbx
 	push	%rbp
 	push	%r12
 	push	%r13
 	push	%r14
 	push	%r15
 	mov	%rsp,%r11		# copy %rsp
 	sub	\$`$framesz+$win64*16*10`,%rsp
 	and	\$-64,%rsp		# align stack frame
 
 	shl	\$6,$len
 	sub	$inp,$out		# re-bias
 	sub	$inp,$in0
 	add	$inp,$len		# end of input
 
 	#mov	$inp,$_inp		# saved later
 	mov	$out,$_out
 	mov	$len,$_end
 	#mov	$key,$_key		# remains resident in $inp register
 	mov	$ivp,$_ivp
 	mov	$ctx,$_ctx
 	mov	$in0,$_in0
 	mov	%r11,$_rsp
 ___
 $code.=<<___ if ($win64);
 	movaps	%xmm6,`$framesz+16*0`(%rsp)
 	movaps	%xmm7,`$framesz+16*1`(%rsp)
 	movaps	%xmm8,`$framesz+16*2`(%rsp)
 	movaps	%xmm9,`$framesz+16*3`(%rsp)
 	movaps	%xmm10,`$framesz+16*4`(%rsp)
 	movaps	%xmm11,`$framesz+16*5`(%rsp)
 	movaps	%xmm12,`$framesz+16*6`(%rsp)
 	movaps	%xmm13,`$framesz+16*7`(%rsp)
 	movaps	%xmm14,`$framesz+16*8`(%rsp)
 	movaps	%xmm15,`$framesz+16*9`(%rsp)
 ___
 $code.=<<___;
 .Lprologue_avx:
 	vzeroall
 
 	mov	$inp,%r12		# borrow $a4
 	lea	0x80($key),$inp		# size optimization, reassign
 	lea	$TABLE+`$SZ*2*$rounds+32`(%rip),%r13	# borrow $a0
 	mov	0xf0-0x80($inp),%r14d	# rounds, borrow $a1
 	mov	$ctx,%r15		# borrow $a2
 	mov	$in0,%rsi		# borrow $a3
 	vmovdqu	($ivp),$iv		# load IV
 	sub	\$9,%r14
 
 	mov	$SZ*0(%r15),$A
 	mov	$SZ*1(%r15),$B
 	mov	$SZ*2(%r15),$C
 	mov	$SZ*3(%r15),$D
 	mov	$SZ*4(%r15),$E
 	mov	$SZ*5(%r15),$F
 	mov	$SZ*6(%r15),$G
 	mov	$SZ*7(%r15),$H
 
 	vmovdqa	0x00(%r13,%r14,8),$mask14
 	vmovdqa	0x10(%r13,%r14,8),$mask12
 	vmovdqa	0x20(%r13,%r14,8),$mask10
 	vmovdqu	0x00-0x80($inp),$roundkey
 ___
 					if ($SZ==4) {	# SHA256
     my @X = map("%xmm$_",(0..3));
     my ($t0,$t1,$t2,$t3) = map("%xmm$_",(4..7));
 
 $code.=<<___;
 	jmp	.Lloop_avx
 .align	16
 .Lloop_avx:
 	vmovdqa	$TABLE+`$SZ*2*$rounds`(%rip),$t3
 	vmovdqu	0x00(%rsi,%r12),@X[0]
 	vmovdqu	0x10(%rsi,%r12),@X[1]
 	vmovdqu	0x20(%rsi,%r12),@X[2]
 	vmovdqu	0x30(%rsi,%r12),@X[3]
 	vpshufb	$t3,@X[0],@X[0]
 	lea	$TABLE(%rip),$Tbl
 	vpshufb	$t3,@X[1],@X[1]
 	vpshufb	$t3,@X[2],@X[2]
 	vpaddd	0x00($Tbl),@X[0],$t0
 	vpshufb	$t3,@X[3],@X[3]
 	vpaddd	0x20($Tbl),@X[1],$t1
 	vpaddd	0x40($Tbl),@X[2],$t2
 	vpaddd	0x60($Tbl),@X[3],$t3
 	vmovdqa	$t0,0x00(%rsp)
 	mov	$A,$a1
 	vmovdqa	$t1,0x10(%rsp)
 	mov	$B,$a3
 	vmovdqa	$t2,0x20(%rsp)
 	xor	$C,$a3			# magic
 	vmovdqa	$t3,0x30(%rsp)
 	mov	$E,$a0
 	jmp	.Lavx_00_47
 
 .align	16
 .Lavx_00_47:
 	sub	\$-16*2*$SZ,$Tbl	# size optimization
 	vmovdqu	(%r12),$inout		# $a4
 	mov	%r12,$_inp		# $a4
 ___
 sub Xupdate_256_AVX () {
 	(
 	'&vpalignr	($t0,@X[1],@X[0],$SZ)',	# X[1..4]
 	 '&vpalignr	($t3,@X[3],@X[2],$SZ)',	# X[9..12]
 	'&vpsrld	($t2,$t0,$sigma0[0]);',
 	 '&vpaddd	(@X[0],@X[0],$t3)',	# X[0..3] += X[9..12]
 	'&vpsrld	($t3,$t0,$sigma0[2])',
 	'&vpslld	($t1,$t0,8*$SZ-$sigma0[1]);',
 	'&vpxor		($t0,$t3,$t2)',
 	 '&vpshufd	($t3,@X[3],0b11111010)',# X[14..15]
 	'&vpsrld	($t2,$t2,$sigma0[1]-$sigma0[0]);',
 	'&vpxor		($t0,$t0,$t1)',
 	'&vpslld	($t1,$t1,$sigma0[1]-$sigma0[0]);',
 	'&vpxor		($t0,$t0,$t2)',
 	 '&vpsrld	($t2,$t3,$sigma1[2]);',
 	'&vpxor		($t0,$t0,$t1)',		# sigma0(X[1..4])
 	 '&vpsrlq	($t3,$t3,$sigma1[0]);',
 	'&vpaddd	(@X[0],@X[0],$t0)',	# X[0..3] += sigma0(X[1..4])
 	 '&vpxor	($t2,$t2,$t3);',
 	 '&vpsrlq	($t3,$t3,$sigma1[1]-$sigma1[0])',
 	 '&vpxor	($t2,$t2,$t3)',		# sigma1(X[14..15])
 	 '&vpshufd	($t2,$t2,0b10000100)',
 	 '&vpsrldq	($t2,$t2,8)',
 	'&vpaddd	(@X[0],@X[0],$t2)',	# X[0..1] += sigma1(X[14..15])
 	 '&vpshufd	($t3,@X[0],0b01010000)',# X[16..17]
 	 '&vpsrld	($t2,$t3,$sigma1[2])',
 	 '&vpsrlq	($t3,$t3,$sigma1[0])',
 	 '&vpxor	($t2,$t2,$t3);',
 	 '&vpsrlq	($t3,$t3,$sigma1[1]-$sigma1[0])',
 	 '&vpxor	($t2,$t2,$t3)',
 	 '&vpshufd	($t2,$t2,0b11101000)',
 	 '&vpslldq	($t2,$t2,8)',
 	'&vpaddd	(@X[0],@X[0],$t2)'	# X[2..3] += sigma1(X[16..17])
 	);
 }
 
 sub AVX_256_00_47 () {
 my $j = shift;
 my $body = shift;
 my @X = @_;
 my @insns = (&$body,&$body,&$body,&$body);	# 104 instructions
 
 	foreach (Xupdate_256_AVX()) {		# 29 instructions
 	    eval;
 	    eval(shift(@insns));
 	    eval(shift(@insns));
 	    eval(shift(@insns));
 	}
 	&vpaddd		($t2,@X[0],16*2*$j."($Tbl)");
 	  foreach (@insns) { eval; }		# remaining instructions
 	&vmovdqa	(16*$j."(%rsp)",$t2);
 }
 
     $aesni_cbc_idx=0;
     for ($i=0,$j=0; $j<4; $j++) {
 	&AVX_256_00_47($j,\&body_00_15,@X);
 	push(@X,shift(@X));			# rotate(@X)
     }
     	&mov		("%r12",$_inp);		# borrow $a4
 	&vpand		($temp,$temp,$mask14);
 	&mov		("%r15",$_out);		# borrow $a2
 	&vpor		($iv,$iv,$temp);
 	&vmovdqu	("(%r15,%r12)",$iv);	# write output
 	&lea		("%r12","16(%r12)");	# inp++
 
 	&cmpb	($SZ-1+16*2*$SZ."($Tbl)",0);
 	&jne	(".Lavx_00_47");
 
 	&vmovdqu	($inout,"(%r12)");
 	&mov		($_inp,"%r12");
 
     $aesni_cbc_idx=0;
     for ($i=0; $i<16; ) {
 	foreach(body_00_15()) { eval; }
     }
 
 					}
 $code.=<<___;
 	mov	$_inp,%r12		# borrow $a4
 	mov	$_out,%r13		# borrow $a0
 	mov	$_ctx,%r15		# borrow $a2
 	mov	$_in0,%rsi		# borrow $a3
 
 	vpand	$mask14,$temp,$temp
 	mov	$a1,$A
 	vpor	$temp,$iv,$iv
 	vmovdqu	$iv,(%r13,%r12)		# write output
 	lea	16(%r12),%r12		# inp++
 
 	add	$SZ*0(%r15),$A
 	add	$SZ*1(%r15),$B
 	add	$SZ*2(%r15),$C
 	add	$SZ*3(%r15),$D
 	add	$SZ*4(%r15),$E
 	add	$SZ*5(%r15),$F
 	add	$SZ*6(%r15),$G
 	add	$SZ*7(%r15),$H
 
 	cmp	$_end,%r12
 
 	mov	$A,$SZ*0(%r15)
 	mov	$B,$SZ*1(%r15)
 	mov	$C,$SZ*2(%r15)
 	mov	$D,$SZ*3(%r15)
 	mov	$E,$SZ*4(%r15)
 	mov	$F,$SZ*5(%r15)
 	mov	$G,$SZ*6(%r15)
 	mov	$H,$SZ*7(%r15)
 	jb	.Lloop_avx
 
 	mov	$_ivp,$ivp
 	mov	$_rsp,%rsi
 	vmovdqu	$iv,($ivp)		# output IV
 	vzeroall
 ___
 $code.=<<___ if ($win64);
 	movaps	`$framesz+16*0`(%rsp),%xmm6
 	movaps	`$framesz+16*1`(%rsp),%xmm7
 	movaps	`$framesz+16*2`(%rsp),%xmm8
 	movaps	`$framesz+16*3`(%rsp),%xmm9
 	movaps	`$framesz+16*4`(%rsp),%xmm10
 	movaps	`$framesz+16*5`(%rsp),%xmm11
 	movaps	`$framesz+16*6`(%rsp),%xmm12
 	movaps	`$framesz+16*7`(%rsp),%xmm13
 	movaps	`$framesz+16*8`(%rsp),%xmm14
 	movaps	`$framesz+16*9`(%rsp),%xmm15
 ___
 $code.=<<___;
 	mov	(%rsi),%r15
 	mov	8(%rsi),%r14
 	mov	16(%rsi),%r13
 	mov	24(%rsi),%r12
 	mov	32(%rsi),%rbp
 	mov	40(%rsi),%rbx
 	lea	48(%rsi),%rsp
 .Lepilogue_avx:
 	ret
 .size	${func}_avx,.-${func}_avx
 ___
 
 if ($avx>1) {{
 ######################################################################
 # AVX2+BMI code path
 #
 my $a5=$SZ==4?"%esi":"%rsi";	# zap $inp 
 my $PUSH8=8*2*$SZ;
 use integer;
 
 sub bodyx_00_15 () {
 	# at start $a1 should be zero, $a3 - $b^$c and $a4 copy of $f
 	(
 	'($a,$b,$c,$d,$e,$f,$g,$h)=@ROT;'.
 
 	'&add	($h,(32*($i/(16/$SZ))+$SZ*($i%(16/$SZ)))%$PUSH8.$base)',    # h+=X[i]+K[i]
 	'&and	($a4,$e)',		# f&e
 	'&rorx	($a0,$e,$Sigma1[2])',
 	'&rorx	($a2,$e,$Sigma1[1])',
 
 	'&lea	($a,"($a,$a1)")',	# h+=Sigma0(a) from the past
 	'&lea	($h,"($h,$a4)")',
 	'&andn	($a4,$e,$g)',		# ~e&g
 	'&xor	($a0,$a2)',
 
 	'&rorx	($a1,$e,$Sigma1[0])',
 	'&lea	($h,"($h,$a4)")',	# h+=Ch(e,f,g)=(e&f)+(~e&g)
 	'&xor	($a0,$a1)',		# Sigma1(e)
 	'&mov	($a2,$a)',
 
 	'&rorx	($a4,$a,$Sigma0[2])',
 	'&lea	($h,"($h,$a0)")',	# h+=Sigma1(e)
 	'&xor	($a2,$b)',		# a^b, b^c in next round
 	'&rorx	($a1,$a,$Sigma0[1])',
 
 	'&rorx	($a0,$a,$Sigma0[0])',
 	'&lea	($d,"($d,$h)")',	# d+=h
 	'&and	($a3,$a2)',		# (b^c)&(a^b)
 	@aesni_cbc_block[$aesni_cbc_idx++].
 	'&xor	($a1,$a4)',
 
 	'&xor	($a3,$b)',		# Maj(a,b,c)=Ch(a^b,c,b)
 	'&xor	($a1,$a0)',		# Sigma0(a)
 	'&lea	($h,"($h,$a3)");'.	# h+=Maj(a,b,c)
 	'&mov	($a4,$e)',		# copy of f in future
 
 	'($a2,$a3) = ($a3,$a2); unshift(@ROT,pop(@ROT)); $i++;'
 	);
 	# and at the finish one has to $a+=$a1
 }
 
 $code.=<<___;
 .type	${func}_avx2,\@function,6
 .align	64
 ${func}_avx2:
 .Lavx2_shortcut:
 	mov	`($win64?56:8)`(%rsp),$in0	# load 7th parameter
 	push	%rbx
 	push	%rbp
 	push	%r12
 	push	%r13
 	push	%r14
 	push	%r15
 	mov	%rsp,%r11		# copy %rsp
 	sub	\$`2*$SZ*$rounds+8*8+$win64*16*10`,%rsp
 	and	\$-256*$SZ,%rsp		# align stack frame
 	add	\$`2*$SZ*($rounds-8)`,%rsp
 
 	shl	\$6,$len
 	sub	$inp,$out		# re-bias
 	sub	$inp,$in0
 	add	$inp,$len		# end of input
 
 	#mov	$inp,$_inp		# saved later
 	#mov	$out,$_out		# kept in $offload
 	mov	$len,$_end
 	#mov	$key,$_key		# remains resident in $inp register
 	mov	$ivp,$_ivp
 	mov	$ctx,$_ctx
 	mov	$in0,$_in0
 	mov	%r11,$_rsp
 ___
 $code.=<<___ if ($win64);
 	movaps	%xmm6,`$framesz+16*0`(%rsp)
 	movaps	%xmm7,`$framesz+16*1`(%rsp)
 	movaps	%xmm8,`$framesz+16*2`(%rsp)
 	movaps	%xmm9,`$framesz+16*3`(%rsp)
 	movaps	%xmm10,`$framesz+16*4`(%rsp)
 	movaps	%xmm11,`$framesz+16*5`(%rsp)
 	movaps	%xmm12,`$framesz+16*6`(%rsp)
 	movaps	%xmm13,`$framesz+16*7`(%rsp)
 	movaps	%xmm14,`$framesz+16*8`(%rsp)
 	movaps	%xmm15,`$framesz+16*9`(%rsp)
 ___
 $code.=<<___;
 .Lprologue_avx2:
 	vzeroall
 
 	mov	$inp,%r13		# borrow $a0
 	vpinsrq	\$1,$out,$offload,$offload
 	lea	0x80($key),$inp		# size optimization, reassign
 	lea	$TABLE+`$SZ*2*$rounds+32`(%rip),%r12	# borrow $a4
 	mov	0xf0-0x80($inp),%r14d	# rounds, borrow $a1
 	mov	$ctx,%r15		# borrow $a2
 	mov	$in0,%rsi		# borrow $a3
 	vmovdqu	($ivp),$iv		# load IV
 	lea	-9(%r14),%r14
 
 	vmovdqa	0x00(%r12,%r14,8),$mask14
 	vmovdqa	0x10(%r12,%r14,8),$mask12
 	vmovdqa	0x20(%r12,%r14,8),$mask10
 
 	sub	\$-16*$SZ,%r13		# inp++, size optimization
 	mov	$SZ*0(%r15),$A
 	lea	(%rsi,%r13),%r12	# borrow $a0
 	mov	$SZ*1(%r15),$B
 	cmp	$len,%r13		# $_end
 	mov	$SZ*2(%r15),$C
 	cmove	%rsp,%r12		# next block or random data
 	mov	$SZ*3(%r15),$D
 	mov	$SZ*4(%r15),$E
 	mov	$SZ*5(%r15),$F
 	mov	$SZ*6(%r15),$G
 	mov	$SZ*7(%r15),$H
 	vmovdqu	0x00-0x80($inp),$roundkey
 ___
 					if ($SZ==4) {	# SHA256
     my @X = map("%ymm$_",(0..3));
     my ($t0,$t1,$t2,$t3) = map("%ymm$_",(4..7));
 
 $code.=<<___;
 	jmp	.Loop_avx2
 .align	16
 .Loop_avx2:
 	vmovdqa	$TABLE+`$SZ*2*$rounds`(%rip),$t3
 	vmovdqu	-16*$SZ+0(%rsi,%r13),%xmm0
 	vmovdqu	-16*$SZ+16(%rsi,%r13),%xmm1
 	vmovdqu	-16*$SZ+32(%rsi,%r13),%xmm2
 	vmovdqu	-16*$SZ+48(%rsi,%r13),%xmm3
 
 	vinserti128	\$1,(%r12),@X[0],@X[0]
 	vinserti128	\$1,16(%r12),@X[1],@X[1]
 	 vpshufb	$t3,@X[0],@X[0]
 	vinserti128	\$1,32(%r12),@X[2],@X[2]
 	 vpshufb	$t3,@X[1],@X[1]
 	vinserti128	\$1,48(%r12),@X[3],@X[3]
 
 	lea	$TABLE(%rip),$Tbl
 	vpshufb	$t3,@X[2],@X[2]
 	lea	-16*$SZ(%r13),%r13
 	vpaddd	0x00($Tbl),@X[0],$t0
 	vpshufb	$t3,@X[3],@X[3]
 	vpaddd	0x20($Tbl),@X[1],$t1
 	vpaddd	0x40($Tbl),@X[2],$t2
 	vpaddd	0x60($Tbl),@X[3],$t3
 	vmovdqa	$t0,0x00(%rsp)
 	xor	$a1,$a1
 	vmovdqa	$t1,0x20(%rsp)
 	lea	-$PUSH8(%rsp),%rsp
 	mov	$B,$a3
 	vmovdqa	$t2,0x00(%rsp)
 	xor	$C,$a3			# magic
 	vmovdqa	$t3,0x20(%rsp)
 	mov	$F,$a4
 	sub	\$-16*2*$SZ,$Tbl	# size optimization
 	jmp	.Lavx2_00_47
 
 .align	16
 .Lavx2_00_47:
 	vmovdqu	(%r13),$inout
 	vpinsrq	\$0,%r13,$offload,$offload
 ___
 
 sub AVX2_256_00_47 () {
 my $j = shift;
 my $body = shift;
 my @X = @_;
 my @insns = (&$body,&$body,&$body,&$body);	# 96 instructions
 my $base = "+2*$PUSH8(%rsp)";
 
 	&lea	("%rsp","-$PUSH8(%rsp)")	if (($j%2)==0);
 	foreach (Xupdate_256_AVX()) {		# 29 instructions
 	    eval;
 	    eval(shift(@insns));
 	    eval(shift(@insns));
 	    eval(shift(@insns));
 	}
 	&vpaddd		($t2,@X[0],16*2*$j."($Tbl)");
 	  foreach (@insns) { eval; }		# remaining instructions
 	&vmovdqa	((32*$j)%$PUSH8."(%rsp)",$t2);
 }
     $aesni_cbc_idx=0;
     for ($i=0,$j=0; $j<4; $j++) {
 	&AVX2_256_00_47($j,\&bodyx_00_15,@X);
 	push(@X,shift(@X));			# rotate(@X)
     }
 	&vmovq		("%r13",$offload);	# borrow $a0
 	&vpextrq	("%r15",$offload,1);	# borrow $a2
 	&vpand		($temp,$temp,$mask14);
 	&vpor		($iv,$iv,$temp);
 	&vmovdqu	("(%r15,%r13)",$iv);	# write output
 	&lea		("%r13","16(%r13)");	# inp++
 
 	&lea	($Tbl,16*2*$SZ."($Tbl)");
 	&cmpb	(($SZ-1)."($Tbl)",0);
 	&jne	(".Lavx2_00_47");
 
 	&vmovdqu	($inout,"(%r13)");
 	&vpinsrq	($offload,$offload,"%r13",0);
 
     $aesni_cbc_idx=0;
     for ($i=0; $i<16; ) {
 	my $base=$i<8?"+$PUSH8(%rsp)":"(%rsp)";
 	foreach(bodyx_00_15()) { eval; }
     }
 					}
 $code.=<<___;
 	vpextrq	\$1,$offload,%r12		# $_out, borrow $a4
 	vmovq	$offload,%r13			# $_inp, borrow $a0
 	mov	`2*$SZ*$rounds+5*8`(%rsp),%r15	# $_ctx, borrow $a2
 	add	$a1,$A
 	lea	`2*$SZ*($rounds-8)`(%rsp),$Tbl
 
 	vpand	$mask14,$temp,$temp
 	vpor	$temp,$iv,$iv
 	vmovdqu	$iv,(%r12,%r13)			# write output
 	lea	16(%r13),%r13
 
 	add	$SZ*0(%r15),$A
 	add	$SZ*1(%r15),$B
 	add	$SZ*2(%r15),$C
 	add	$SZ*3(%r15),$D
 	add	$SZ*4(%r15),$E
 	add	$SZ*5(%r15),$F
 	add	$SZ*6(%r15),$G
 	add	$SZ*7(%r15),$H
 
 	mov	$A,$SZ*0(%r15)
 	mov	$B,$SZ*1(%r15)
 	mov	$C,$SZ*2(%r15)
 	mov	$D,$SZ*3(%r15)
 	mov	$E,$SZ*4(%r15)
 	mov	$F,$SZ*5(%r15)
 	mov	$G,$SZ*6(%r15)
 	mov	$H,$SZ*7(%r15)
 
 	cmp	`$PUSH8+2*8`($Tbl),%r13		# $_end
 	je	.Ldone_avx2
 
 	xor	$a1,$a1
 	mov	$B,$a3
 	mov	$F,$a4
 	xor	$C,$a3			# magic
 	jmp	.Lower_avx2
 .align	16
 .Lower_avx2:
 	vmovdqu	(%r13),$inout
 	vpinsrq	\$0,%r13,$offload,$offload
 ___
     $aesni_cbc_idx=0;
     for ($i=0; $i<16; ) {
 	my $base="+16($Tbl)";
 	foreach(bodyx_00_15()) { eval; }
 	&lea	($Tbl,"-$PUSH8($Tbl)")	if ($i==8);
     }
 $code.=<<___;
 	vmovq	$offload,%r13			# borrow $a0
 	vpextrq	\$1,$offload,%r15		# borrow $a2
 	vpand	$mask14,$temp,$temp
 	vpor	$temp,$iv,$iv
 	lea	-$PUSH8($Tbl),$Tbl
 	vmovdqu	$iv,(%r15,%r13)			# write output
 	lea	16(%r13),%r13			# inp++
 	cmp	%rsp,$Tbl
 	jae	.Lower_avx2
 
 	mov	`2*$SZ*$rounds+5*8`(%rsp),%r15	# $_ctx, borrow $a2
 	lea	16*$SZ(%r13),%r13
 	mov	`2*$SZ*$rounds+6*8`(%rsp),%rsi	# $_in0, borrow $a3
 	add	$a1,$A
 	lea	`2*$SZ*($rounds-8)`(%rsp),%rsp
 
 	add	$SZ*0(%r15),$A
 	add	$SZ*1(%r15),$B
 	add	$SZ*2(%r15),$C
 	add	$SZ*3(%r15),$D
 	add	$SZ*4(%r15),$E
 	add	$SZ*5(%r15),$F
 	add	$SZ*6(%r15),$G
 	lea	(%rsi,%r13),%r12
 	add	$SZ*7(%r15),$H
 
 	cmp	$_end,%r13
 
 	mov	$A,$SZ*0(%r15)
 	cmove	%rsp,%r12		# next block or stale data
 	mov	$B,$SZ*1(%r15)
 	mov	$C,$SZ*2(%r15)
 	mov	$D,$SZ*3(%r15)
 	mov	$E,$SZ*4(%r15)
 	mov	$F,$SZ*5(%r15)
 	mov	$G,$SZ*6(%r15)
 	mov	$H,$SZ*7(%r15)
 
 	jbe	.Loop_avx2
 	lea	(%rsp),$Tbl
 
 .Ldone_avx2:
 	lea	($Tbl),%rsp
 	mov	$_ivp,$ivp
 	mov	$_rsp,%rsi
 	vmovdqu	$iv,($ivp)		# output IV
 	vzeroall
 ___
 $code.=<<___ if ($win64);
 	movaps	`$framesz+16*0`(%rsp),%xmm6
 	movaps	`$framesz+16*1`(%rsp),%xmm7
 	movaps	`$framesz+16*2`(%rsp),%xmm8
 	movaps	`$framesz+16*3`(%rsp),%xmm9
 	movaps	`$framesz+16*4`(%rsp),%xmm10
 	movaps	`$framesz+16*5`(%rsp),%xmm11
 	movaps	`$framesz+16*6`(%rsp),%xmm12
 	movaps	`$framesz+16*7`(%rsp),%xmm13
 	movaps	`$framesz+16*8`(%rsp),%xmm14
 	movaps	`$framesz+16*9`(%rsp),%xmm15
 ___
 $code.=<<___;
 	mov	(%rsi),%r15
 	mov	8(%rsi),%r14
 	mov	16(%rsi),%r13
 	mov	24(%rsi),%r12
 	mov	32(%rsi),%rbp
 	mov	40(%rsi),%rbx
 	lea	48(%rsi),%rsp
 .Lepilogue_avx2:
 	ret
 .size	${func}_avx2,.-${func}_avx2
 ___
 }}
 }}
 {{
 my ($in0,$out,$len,$key,$ivp,$ctx,$inp)=("%rdi","%rsi","%rdx","%rcx","%r8","%r9","%r10");
 
 my ($rounds,$Tbl)=("%r11d","%rbx");
 
 my ($iv,$in,$rndkey0)=map("%xmm$_",(6,14,15));
 my @rndkey=("%xmm4","%xmm5");
 my $r=0;
 my $sn=0;
 
 my ($Wi,$ABEF,$CDGH,$TMP,$BSWAP,$ABEF_SAVE,$CDGH_SAVE)=map("%xmm$_",(0..3,7..9));
 my @MSG=map("%xmm$_",(10..13));
 
 my $aesenc=sub {
   use integer;
   my ($n,$k)=($r/10,$r%10);
     if ($k==0) {
       $code.=<<___;
 	movups		`16*$n`($in0),$in		# load input
 	xorps		$rndkey0,$in
 ___
       $code.=<<___ if ($n);
 	movups		$iv,`16*($n-1)`($out,$in0)	# write output
 ___
       $code.=<<___;
 	xorps		$in,$iv
 	movups		`32+16*$k-112`($key),$rndkey[1]
 	aesenc		$rndkey[0],$iv
 ___
     } elsif ($k==9) {
       $sn++;
       $code.=<<___;
 	cmp		\$11,$rounds
 	jb		.Laesenclast$sn
 	movups		`32+16*($k+0)-112`($key),$rndkey[1]
 	aesenc		$rndkey[0],$iv
 	movups		`32+16*($k+1)-112`($key),$rndkey[0]
 	aesenc		$rndkey[1],$iv
 	je		.Laesenclast$sn
 	movups		`32+16*($k+2)-112`($key),$rndkey[1]
 	aesenc		$rndkey[0],$iv
 	movups		`32+16*($k+3)-112`($key),$rndkey[0]
 	aesenc		$rndkey[1],$iv
 .Laesenclast$sn:
 	aesenclast	$rndkey[0],$iv
 	movups		16-112($key),$rndkey[1]		# forward reference
 	nop
 ___
     } else {
       $code.=<<___;
 	movups		`32+16*$k-112`($key),$rndkey[1]
 	aesenc		$rndkey[0],$iv
 ___
     }
     $r++;	unshift(@rndkey,pop(@rndkey));
 };
 
 if ($shaext) {
 my $Tbl="%rax";
 
 $code.=<<___;
 .type	${func}_shaext,\@function,6
 .align	32
 ${func}_shaext:
 	mov	`($win64?56:8)`(%rsp),$inp	# load 7th argument
 ___
 $code.=<<___ if ($win64);
 	lea	`-8-10*16`(%rsp),%rsp
 	movaps	%xmm6,-8-10*16(%rax)
 	movaps	%xmm7,-8-9*16(%rax)
 	movaps	%xmm8,-8-8*16(%rax)
 	movaps	%xmm9,-8-7*16(%rax)
 	movaps	%xmm10,-8-6*16(%rax)
 	movaps	%xmm11,-8-5*16(%rax)
 	movaps	%xmm12,-8-4*16(%rax)
 	movaps	%xmm13,-8-3*16(%rax)
 	movaps	%xmm14,-8-2*16(%rax)
 	movaps	%xmm15,-8-1*16(%rax)
 .Lprologue_shaext:
 ___
 $code.=<<___;
 	lea		K256+0x80(%rip),$Tbl
 	movdqu		($ctx),$ABEF		# DCBA
 	movdqu		16($ctx),$CDGH		# HGFE
 	movdqa		0x200-0x80($Tbl),$TMP	# byte swap mask
 
 	mov		240($key),$rounds
 	sub		$in0,$out
 	movups		($key),$rndkey0		# $key[0]
+	movups		($ivp),$iv		# load IV
 	movups		16($key),$rndkey[0]	# forward reference
 	lea		112($key),$key		# size optimization
 
 	pshufd		\$0x1b,$ABEF,$Wi	# ABCD
 	pshufd		\$0xb1,$ABEF,$ABEF	# CDAB
 	pshufd		\$0x1b,$CDGH,$CDGH	# EFGH
 	movdqa		$TMP,$BSWAP		# offload
 	palignr		\$8,$CDGH,$ABEF		# ABEF
 	punpcklqdq	$Wi,$CDGH		# CDGH
 
 	jmp	.Loop_shaext
 
 .align	16
 .Loop_shaext:
 	movdqu		($inp),@MSG[0]
 	movdqu		0x10($inp),@MSG[1]
 	movdqu		0x20($inp),@MSG[2]
 	pshufb		$TMP,@MSG[0]
 	movdqu		0x30($inp),@MSG[3]
 
 	movdqa		0*32-0x80($Tbl),$Wi
 	paddd		@MSG[0],$Wi
 	pshufb		$TMP,@MSG[1]
 	movdqa		$CDGH,$CDGH_SAVE	# offload
 	movdqa		$ABEF,$ABEF_SAVE	# offload
 ___
 	&$aesenc();
 $code.=<<___;
 	sha256rnds2	$ABEF,$CDGH		# 0-3
 	pshufd		\$0x0e,$Wi,$Wi
 ___
 	&$aesenc();
 $code.=<<___;
 	sha256rnds2	$CDGH,$ABEF
 
 	movdqa		1*32-0x80($Tbl),$Wi
 	paddd		@MSG[1],$Wi
 	pshufb		$TMP,@MSG[2]
 	lea		0x40($inp),$inp
 ___
 	&$aesenc();
 $code.=<<___;
 	sha256rnds2	$ABEF,$CDGH		# 4-7
 	pshufd		\$0x0e,$Wi,$Wi
 ___
 	&$aesenc();
 $code.=<<___;
 	sha256rnds2	$CDGH,$ABEF
 
 	movdqa		2*32-0x80($Tbl),$Wi
 	paddd		@MSG[2],$Wi
 	pshufb		$TMP,@MSG[3]
 	sha256msg1	@MSG[1],@MSG[0]
 ___
 	&$aesenc();
 $code.=<<___;
 	sha256rnds2	$ABEF,$CDGH		# 8-11
 	pshufd		\$0x0e,$Wi,$Wi
 	movdqa		@MSG[3],$TMP
 	palignr		\$4,@MSG[2],$TMP
 	paddd		$TMP,@MSG[0]
 ___
 	&$aesenc();
 $code.=<<___;
 	sha256rnds2	$CDGH,$ABEF
 
 	movdqa		3*32-0x80($Tbl),$Wi
 	paddd		@MSG[3],$Wi
 	sha256msg2	@MSG[3],@MSG[0]
 	sha256msg1	@MSG[2],@MSG[1]
 ___
 	&$aesenc();
 $code.=<<___;
 	sha256rnds2	$ABEF,$CDGH		# 12-15
 	pshufd		\$0x0e,$Wi,$Wi
 ___
 	&$aesenc();
 $code.=<<___;
 	movdqa		@MSG[0],$TMP
 	palignr		\$4,@MSG[3],$TMP
 	paddd		$TMP,@MSG[1]
 	sha256rnds2	$CDGH,$ABEF
 ___
 for($i=4;$i<16-3;$i++) {
 	&$aesenc()	if (($r%10)==0);
 $code.=<<___;
 	movdqa		$i*32-0x80($Tbl),$Wi
 	paddd		@MSG[0],$Wi
 	sha256msg2	@MSG[0],@MSG[1]
 	sha256msg1	@MSG[3],@MSG[2]
 ___
 	&$aesenc();
 $code.=<<___;
 	sha256rnds2	$ABEF,$CDGH		# 16-19...
 	pshufd		\$0x0e,$Wi,$Wi
 	movdqa		@MSG[1],$TMP
 	palignr		\$4,@MSG[0],$TMP
 	paddd		$TMP,@MSG[2]
 ___
 	&$aesenc();
 	&$aesenc()	if ($r==19);
 $code.=<<___;
 	sha256rnds2	$CDGH,$ABEF
 ___
 	push(@MSG,shift(@MSG));
 }
 $code.=<<___;
 	movdqa		13*32-0x80($Tbl),$Wi
 	paddd		@MSG[0],$Wi
 	sha256msg2	@MSG[0],@MSG[1]
 	sha256msg1	@MSG[3],@MSG[2]
 ___
 	&$aesenc();
 $code.=<<___;
 	sha256rnds2	$ABEF,$CDGH		# 52-55
 	pshufd		\$0x0e,$Wi,$Wi
 	movdqa		@MSG[1],$TMP
 	palignr		\$4,@MSG[0],$TMP
 	paddd		$TMP,@MSG[2]
 ___
 	&$aesenc();
 	&$aesenc();
 $code.=<<___;
 	sha256rnds2	$CDGH,$ABEF
 
 	movdqa		14*32-0x80($Tbl),$Wi
 	paddd		@MSG[1],$Wi
 	sha256msg2	@MSG[1],@MSG[2]
 	movdqa		$BSWAP,$TMP
 ___
 	&$aesenc();
 $code.=<<___;
 	sha256rnds2	$ABEF,$CDGH		# 56-59
 	pshufd		\$0x0e,$Wi,$Wi
 ___
 	&$aesenc();
 $code.=<<___;
 	sha256rnds2	$CDGH,$ABEF
 
 	movdqa		15*32-0x80($Tbl),$Wi
 	paddd		@MSG[2],$Wi
 ___
 	&$aesenc();
 	&$aesenc();
 $code.=<<___;
 	sha256rnds2	$ABEF,$CDGH		# 60-63
 	pshufd		\$0x0e,$Wi,$Wi
 ___
 	&$aesenc();
 $code.=<<___;
 	sha256rnds2	$CDGH,$ABEF
 	#pxor		$CDGH,$rndkey0		# black magic
 ___
 	while ($r<40)	{ &$aesenc(); }		# remaining aesenc's
 $code.=<<___;
 	#xorps		$CDGH,$rndkey0		# black magic
 	paddd		$CDGH_SAVE,$CDGH
 	paddd		$ABEF_SAVE,$ABEF
 
 	dec		$len
 	movups		$iv,48($out,$in0)	# write output
 	lea		64($in0),$in0
 	jnz		.Loop_shaext
 
 	pshufd		\$0xb1,$CDGH,$CDGH	# DCHG
 	pshufd		\$0x1b,$ABEF,$TMP	# FEBA
 	pshufd		\$0xb1,$ABEF,$ABEF	# BAFE
 	punpckhqdq	$CDGH,$ABEF		# DCBA
 	palignr		\$8,$TMP,$CDGH		# HGFE
 
 	movups		$iv,($ivp)		# write IV
 	movdqu		$ABEF,($ctx)
 	movdqu		$CDGH,16($ctx)
 ___
 $code.=<<___ if ($win64);
 	movaps	0*16(%rsp),%xmm6
 	movaps	1*16(%rsp),%xmm7
 	movaps	2*16(%rsp),%xmm8
 	movaps	3*16(%rsp),%xmm9
 	movaps	4*16(%rsp),%xmm10
 	movaps	5*16(%rsp),%xmm11
 	movaps	6*16(%rsp),%xmm12
 	movaps	7*16(%rsp),%xmm13
 	movaps	8*16(%rsp),%xmm14
 	movaps	9*16(%rsp),%xmm15
 	lea	8+10*16(%rsp),%rsp
 .Lepilogue_shaext:
 ___
 $code.=<<___;
 	ret
 .size	${func}_shaext,.-${func}_shaext
 ___
 }
 }}}}}
 
 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
 #		CONTEXT *context,DISPATCHER_CONTEXT *disp)
 if ($win64 && $avx) {
 $rec="%rcx";
 $frame="%rdx";
 $context="%r8";
 $disp="%r9";
 
 $code.=<<___;
 .extern	__imp_RtlVirtualUnwind
 .type	se_handler,\@abi-omnipotent
 .align	16
 se_handler:
 	push	%rsi
 	push	%rdi
 	push	%rbx
 	push	%rbp
 	push	%r12
 	push	%r13
 	push	%r14
 	push	%r15
 	pushfq
 	sub	\$64,%rsp
 
 	mov	120($context),%rax	# pull context->Rax
 	mov	248($context),%rbx	# pull context->Rip
 
 	mov	8($disp),%rsi		# disp->ImageBase
 	mov	56($disp),%r11		# disp->HanderlData
 
 	mov	0(%r11),%r10d		# HandlerData[0]
 	lea	(%rsi,%r10),%r10	# prologue label
 	cmp	%r10,%rbx		# context->RipRsp
 
 	mov	4(%r11),%r10d		# HandlerData[1]
 	lea	(%rsi,%r10),%r10	# epilogue label
 	cmp	%r10,%rbx		# context->Rip>=epilogue label
 	jae	.Lin_prologue
 ___
 $code.=<<___ if ($shaext);
 	lea	aesni_cbc_sha256_enc_shaext(%rip),%r10
 	cmp	%r10,%rbx
 	jb	.Lnot_in_shaext
 
 	lea	(%rax),%rsi
 	lea	512($context),%rdi	# &context.Xmm6
 	mov	\$20,%ecx
 	.long	0xa548f3fc		# cld; rep movsq
 	lea	168(%rax),%rax		# adjust stack pointer
 	jmp	.Lin_prologue
 .Lnot_in_shaext:
 ___
 $code.=<<___ if ($avx>1);
 	lea	.Lavx2_shortcut(%rip),%r10
 	cmp	%r10,%rbx		# context->RipRbx
 	mov	%rbp,160($context)	# restore context->Rbp
 	mov	%r12,216($context)	# restore context->R12
 	mov	%r13,224($context)	# restore context->R13
 	mov	%r14,232($context)	# restore context->R14
 	mov	%r15,240($context)	# restore context->R15
 
 	lea	16*$SZ+8*8(%rsi),%rsi	# Xmm6- save area
 	lea	512($context),%rdi	# &context.Xmm6
 	mov	\$20,%ecx
 	.long	0xa548f3fc		# cld; rep movsq
 
 .Lin_prologue:
 	mov	8(%rax),%rdi
 	mov	16(%rax),%rsi
 	mov	%rax,152($context)	# restore context->Rsp
 	mov	%rsi,168($context)	# restore context->Rsi
 	mov	%rdi,176($context)	# restore context->Rdi
 
 	mov	40($disp),%rdi		# disp->ContextRecord
 	mov	$context,%rsi		# context
 	mov	\$154,%ecx		# sizeof(CONTEXT)
 	.long	0xa548f3fc		# cld; rep movsq
 
 	mov	$disp,%rsi
 	xor	%rcx,%rcx		# arg1, UNW_FLAG_NHANDLER
 	mov	8(%rsi),%rdx		# arg2, disp->ImageBase
 	mov	0(%rsi),%r8		# arg3, disp->ControlPc
 	mov	16(%rsi),%r9		# arg4, disp->FunctionEntry
 	mov	40(%rsi),%r10		# disp->ContextRecord
 	lea	56(%rsi),%r11		# &disp->HandlerData
 	lea	24(%rsi),%r12		# &disp->EstablisherFrame
 	mov	%r10,32(%rsp)		# arg5
 	mov	%r11,40(%rsp)		# arg6
 	mov	%r12,48(%rsp)		# arg7
 	mov	%rcx,56(%rsp)		# arg8, (NULL)
 	call	*__imp_RtlVirtualUnwind(%rip)
 
 	mov	\$1,%eax		# ExceptionContinueSearch
 	add	\$64,%rsp
 	popfq
 	pop	%r15
 	pop	%r14
 	pop	%r13
 	pop	%r12
 	pop	%rbp
 	pop	%rbx
 	pop	%rdi
 	pop	%rsi
 	ret
 .size	se_handler,.-se_handler
 
 .section	.pdata
 	.rva	.LSEH_begin_${func}_xop
 	.rva	.LSEH_end_${func}_xop
 	.rva	.LSEH_info_${func}_xop
 
 	.rva	.LSEH_begin_${func}_avx
 	.rva	.LSEH_end_${func}_avx
 	.rva	.LSEH_info_${func}_avx
 ___
 $code.=<<___ if ($avx>1);
 	.rva	.LSEH_begin_${func}_avx2
 	.rva	.LSEH_end_${func}_avx2
 	.rva	.LSEH_info_${func}_avx2
 ___
 $code.=<<___ if ($shaext);
 	.rva	.LSEH_begin_${func}_shaext
 	.rva	.LSEH_end_${func}_shaext
 	.rva	.LSEH_info_${func}_shaext
 ___
 $code.=<<___;
 .section	.xdata
 .align	8
 .LSEH_info_${func}_xop:
 	.byte	9,0,0,0
 	.rva	se_handler
 	.rva	.Lprologue_xop,.Lepilogue_xop		# HandlerData[]
 
 .LSEH_info_${func}_avx:
 	.byte	9,0,0,0
 	.rva	se_handler
 	.rva	.Lprologue_avx,.Lepilogue_avx		# HandlerData[]
 ___
 $code.=<<___ if ($avx>1);
 .LSEH_info_${func}_avx2:
 	.byte	9,0,0,0
 	.rva	se_handler
 	.rva	.Lprologue_avx2,.Lepilogue_avx2		# HandlerData[]
 ___
 $code.=<<___ if ($shaext);
 .LSEH_info_${func}_shaext:
 	.byte	9,0,0,0
 	.rva	se_handler
 	.rva	.Lprologue_shaext,.Lepilogue_shaext	# HandlerData[]
 ___
 }
 
 ####################################################################
 sub rex {
   local *opcode=shift;
   my ($dst,$src)=@_;
   my $rex=0;
 
     $rex|=0x04			if($dst>=8);
     $rex|=0x01			if($src>=8);
     unshift @opcode,$rex|0x40	if($rex);
 }
 
 {
   my %opcodelet = (
 		"sha256rnds2" => 0xcb,
   		"sha256msg1"  => 0xcc,
 		"sha256msg2"  => 0xcd	);
 
   sub sha256op38 {
     my $instr = shift;
 
     if (defined($opcodelet{$instr}) && @_[0] =~ /%xmm([0-9]+),\s*%xmm([0-9]+)/) {
       my @opcode=(0x0f,0x38);
 	rex(\@opcode,$2,$1);
 	push @opcode,$opcodelet{$instr};
 	push @opcode,0xc0|($1&7)|(($2&7)<<3);		# ModR/M
 	return ".byte\t".join(',',@opcode);
     } else {
 	return $instr."\t".@_[0];
     }
   }
 }
 
 $code =~ s/\`([^\`]*)\`/eval $1/gem;
 $code =~ s/\b(sha256[^\s]*)\s+(.*)/sha256op38($1,$2)/gem;
 print $code;
 close STDOUT;
Index: vendor-crypto/openssl/dist/crypto/aes/asm/bsaes-armv7.pl
===================================================================
--- vendor-crypto/openssl/dist/crypto/aes/asm/bsaes-armv7.pl	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/aes/asm/bsaes-armv7.pl	(revision 318897)
@@ -1,2451 +1,2451 @@
 #!/usr/bin/env perl
 
 # ====================================================================
 # Written by Andy Polyakov  for the OpenSSL
 # project. The module is, however, dual licensed under OpenSSL and
 # CRYPTOGAMS licenses depending on where you obtain it. For further
 # details see http://www.openssl.org/~appro/cryptogams/.
 #
 # Specific modes and adaptation for Linux kernel by Ard Biesheuvel
 # . Permission to use under GPL terms is
 # granted.
 # ====================================================================
 
 # Bit-sliced AES for ARM NEON
 #
 # February 2012.
 #
 # This implementation is direct adaptation of bsaes-x86_64 module for
 # ARM NEON. Except that this module is endian-neutral [in sense that
 # it can be compiled for either endianness] by courtesy of vld1.8's
 # neutrality. Initial version doesn't implement interface to OpenSSL,
 # only low-level primitives and unsupported entry points, just enough
 # to collect performance results, which for Cortex-A8 core are:
 #
 # encrypt	19.5 cycles per byte processed with 128-bit key
 # decrypt	22.1 cycles per byte processed with 128-bit key
 # key conv.	440  cycles per 128-bit key/0.18 of 8x block
 #
 # Snapdragon S4 encrypts byte in 17.6 cycles and decrypts in 19.7,
 # which is [much] worse than anticipated (for further details see
 # http://www.openssl.org/~appro/Snapdragon-S4.html).
 #
 # Cortex-A15 manages in 14.2/16.1 cycles [when integer-only code
 # manages in 20.0 cycles].
 #
 # When comparing to x86_64 results keep in mind that NEON unit is
 # [mostly] single-issue and thus can't [fully] benefit from
 # instruction-level parallelism. And when comparing to aes-armv4
 # results keep in mind key schedule conversion overhead (see
 # bsaes-x86_64.pl for further details)...
 #
 #						
 
 # April-August 2013
 #
 # Add CBC, CTR and XTS subroutines, adapt for kernel use.
 #
 #					
 
 while (($output=shift) && ($output!~/^\w[\w\-]*\.\w+$/)) {}
 open STDOUT,">$output";
 
 my ($inp,$out,$len,$key)=("r0","r1","r2","r3");
 my @XMM=map("q$_",(0..15));
 
 {
 my ($key,$rounds,$const)=("r4","r5","r6");
 
 sub Dlo()   { shift=~m|q([1]?[0-9])|?"d".($1*2):"";     }
 sub Dhi()   { shift=~m|q([1]?[0-9])|?"d".($1*2+1):"";   }
 
 sub Sbox {
 # input in  lsb > [b0, b1, b2, b3, b4, b5, b6, b7] < msb
 # output in lsb > [b0, b1, b4, b6, b3, b7, b2, b5] < msb
 my @b=@_[0..7];
 my @t=@_[8..11];
 my @s=@_[12..15];
 	&InBasisChange	(@b);
 	&Inv_GF256	(@b[6,5,0,3,7,1,4,2],@t,@s);
 	&OutBasisChange	(@b[7,1,4,2,6,5,0,3]);
 }
 
 sub InBasisChange {
 # input in  lsb > [b0, b1, b2, b3, b4, b5, b6, b7] < msb
 # output in lsb > [b6, b5, b0, b3, b7, b1, b4, b2] < msb 
 my @b=@_[0..7];
 $code.=<<___;
 	veor	@b[2], @b[2], @b[1]
 	veor	@b[5], @b[5], @b[6]
 	veor	@b[3], @b[3], @b[0]
 	veor	@b[6], @b[6], @b[2]
 	veor	@b[5], @b[5], @b[0]
 
 	veor	@b[6], @b[6], @b[3]
 	veor	@b[3], @b[3], @b[7]
 	veor	@b[7], @b[7], @b[5]
 	veor	@b[3], @b[3], @b[4]
 	veor	@b[4], @b[4], @b[5]
 
 	veor	@b[2], @b[2], @b[7]
 	veor	@b[3], @b[3], @b[1]
 	veor	@b[1], @b[1], @b[5]
 ___
 }
 
 sub OutBasisChange {
 # input in  lsb > [b0, b1, b2, b3, b4, b5, b6, b7] < msb
 # output in lsb > [b6, b1, b2, b4, b7, b0, b3, b5] < msb
 my @b=@_[0..7];
 $code.=<<___;
 	veor	@b[0], @b[0], @b[6]
 	veor	@b[1], @b[1], @b[4]
 	veor	@b[4], @b[4], @b[6]
 	veor	@b[2], @b[2], @b[0]
 	veor	@b[6], @b[6], @b[1]
 
 	veor	@b[1], @b[1], @b[5]
 	veor	@b[5], @b[5], @b[3]
 	veor	@b[3], @b[3], @b[7]
 	veor	@b[7], @b[7], @b[5]
 	veor	@b[2], @b[2], @b[5]
 
 	veor	@b[4], @b[4], @b[7]
 ___
 }
 
 sub InvSbox {
 # input in lsb 	> [b0, b1, b2, b3, b4, b5, b6, b7] < msb
 # output in lsb	> [b0, b1, b6, b4, b2, b7, b3, b5] < msb
 my @b=@_[0..7];
 my @t=@_[8..11];
 my @s=@_[12..15];
 	&InvInBasisChange	(@b);
 	&Inv_GF256		(@b[5,1,2,6,3,7,0,4],@t,@s);
 	&InvOutBasisChange	(@b[3,7,0,4,5,1,2,6]);
 }
 
 sub InvInBasisChange {		# OutBasisChange in reverse (with twist)
 my @b=@_[5,1,2,6,3,7,0,4];
 $code.=<<___
 	 veor	@b[1], @b[1], @b[7]
 	veor	@b[4], @b[4], @b[7]
 
 	veor	@b[7], @b[7], @b[5]
 	 veor	@b[1], @b[1], @b[3]
 	veor	@b[2], @b[2], @b[5]
 	veor	@b[3], @b[3], @b[7]
 
 	veor	@b[6], @b[6], @b[1]
 	veor	@b[2], @b[2], @b[0]
 	 veor	@b[5], @b[5], @b[3]
 	veor	@b[4], @b[4], @b[6]
 	veor	@b[0], @b[0], @b[6]
 	veor	@b[1], @b[1], @b[4]
 ___
 }
 
 sub InvOutBasisChange {		# InBasisChange in reverse
 my @b=@_[2,5,7,3,6,1,0,4];
 $code.=<<___;
 	veor	@b[1], @b[1], @b[5]
 	veor	@b[2], @b[2], @b[7]
 
 	veor	@b[3], @b[3], @b[1]
 	veor	@b[4], @b[4], @b[5]
 	veor	@b[7], @b[7], @b[5]
 	veor	@b[3], @b[3], @b[4]
 	 veor 	@b[5], @b[5], @b[0]
 	veor	@b[3], @b[3], @b[7]
 	 veor	@b[6], @b[6], @b[2]
 	 veor	@b[2], @b[2], @b[1]
 	veor	@b[6], @b[6], @b[3]
 
 	veor	@b[3], @b[3], @b[0]
 	veor	@b[5], @b[5], @b[6]
 ___
 }
 
 sub Mul_GF4 {
 #;*************************************************************
 #;* Mul_GF4: Input x0-x1,y0-y1 Output x0-x1 Temp t0 (8) *
 #;*************************************************************
 my ($x0,$x1,$y0,$y1,$t0,$t1)=@_;
 $code.=<<___;
 	veor 	$t0, $y0, $y1
 	vand	$t0, $t0, $x0
 	veor	$x0, $x0, $x1
 	vand	$t1, $x1, $y0
 	vand	$x0, $x0, $y1
 	veor	$x1, $t1, $t0
 	veor	$x0, $x0, $t1
 ___
 }
 
 sub Mul_GF4_N {				# not used, see next subroutine
 # multiply and scale by N
 my ($x0,$x1,$y0,$y1,$t0)=@_;
 $code.=<<___;
 	veor	$t0, $y0, $y1
 	vand	$t0, $t0, $x0
 	veor	$x0, $x0, $x1
 	vand	$x1, $x1, $y0
 	vand	$x0, $x0, $y1
 	veor	$x1, $x1, $x0
 	veor	$x0, $x0, $t0
 ___
 }
 
 sub Mul_GF4_N_GF4 {
 # interleaved Mul_GF4_N and Mul_GF4
 my ($x0,$x1,$y0,$y1,$t0,
     $x2,$x3,$y2,$y3,$t1)=@_;
 $code.=<<___;
 	veor	$t0, $y0, $y1
 	 veor 	$t1, $y2, $y3
 	vand	$t0, $t0, $x0
 	 vand	$t1, $t1, $x2
 	veor	$x0, $x0, $x1
 	 veor	$x2, $x2, $x3
 	vand	$x1, $x1, $y0
 	 vand	$x3, $x3, $y2
 	vand	$x0, $x0, $y1
 	 vand	$x2, $x2, $y3
 	veor	$x1, $x1, $x0
 	 veor	$x2, $x2, $x3
 	veor	$x0, $x0, $t0
 	 veor	$x3, $x3, $t1
 ___
 }
 sub Mul_GF16_2 {
 my @x=@_[0..7];
 my @y=@_[8..11];
 my @t=@_[12..15];
 $code.=<<___;
 	veor	@t[0], @x[0], @x[2]
 	veor	@t[1], @x[1], @x[3]
 ___
 	&Mul_GF4  	(@x[0], @x[1], @y[0], @y[1], @t[2..3]);
 $code.=<<___;
 	veor	@y[0], @y[0], @y[2]
 	veor	@y[1], @y[1], @y[3]
 ___
 	Mul_GF4_N_GF4	(@t[0], @t[1], @y[0], @y[1], @t[3],
 			 @x[2], @x[3], @y[2], @y[3], @t[2]);
 $code.=<<___;
 	veor	@x[0], @x[0], @t[0]
 	veor	@x[2], @x[2], @t[0]
 	veor	@x[1], @x[1], @t[1]
 	veor	@x[3], @x[3], @t[1]
 
 	veor	@t[0], @x[4], @x[6]
 	veor	@t[1], @x[5], @x[7]
 ___
 	&Mul_GF4_N_GF4	(@t[0], @t[1], @y[0], @y[1], @t[3],
 			 @x[6], @x[7], @y[2], @y[3], @t[2]);
 $code.=<<___;
 	veor	@y[0], @y[0], @y[2]
 	veor	@y[1], @y[1], @y[3]
 ___
 	&Mul_GF4  	(@x[4], @x[5], @y[0], @y[1], @t[2..3]);
 $code.=<<___;
 	veor	@x[4], @x[4], @t[0]
 	veor	@x[6], @x[6], @t[0]
 	veor	@x[5], @x[5], @t[1]
 	veor	@x[7], @x[7], @t[1]
 ___
 }
 sub Inv_GF256 {
 #;********************************************************************
 #;* Inv_GF256: Input x0-x7 Output x0-x7 Temp t0-t3,s0-s3 (144)       *
 #;********************************************************************
 my @x=@_[0..7];
 my @t=@_[8..11];
 my @s=@_[12..15];
 # direct optimizations from hardware
 $code.=<<___;
 	veor	@t[3], @x[4], @x[6]
 	veor	@t[2], @x[5], @x[7]
 	veor	@t[1], @x[1], @x[3]
 	veor	@s[1], @x[7], @x[6]
 	 vmov	@t[0], @t[2]
 	veor	@s[0], @x[0], @x[2]
 
 	vorr	@t[2], @t[2], @t[1]
 	veor	@s[3], @t[3], @t[0]
 	vand	@s[2], @t[3], @s[0]
 	vorr	@t[3], @t[3], @s[0]
 	veor	@s[0], @s[0], @t[1]
 	vand	@t[0], @t[0], @t[1]
 	veor	@t[1], @x[3], @x[2]
 	vand	@s[3], @s[3], @s[0]
 	vand	@s[1], @s[1], @t[1]
 	veor	@t[1], @x[4], @x[5]
 	veor	@s[0], @x[1], @x[0]
 	veor	@t[3], @t[3], @s[1]
 	veor	@t[2], @t[2], @s[1]
 	vand	@s[1], @t[1], @s[0]
 	vorr	@t[1], @t[1], @s[0]
 	veor	@t[3], @t[3], @s[3]
 	veor	@t[0], @t[0], @s[1]
 	veor	@t[2], @t[2], @s[2]
 	veor	@t[1], @t[1], @s[3]
 	veor	@t[0], @t[0], @s[2]
 	vand	@s[0], @x[7], @x[3]
 	veor	@t[1], @t[1], @s[2]
 	vand	@s[1], @x[6], @x[2]
 	vand	@s[2], @x[5], @x[1]
 	vorr	@s[3], @x[4], @x[0]
 	veor	@t[3], @t[3], @s[0]
 	veor	@t[1], @t[1], @s[2]
 	veor	@t[0], @t[0], @s[3]
 	veor	@t[2], @t[2], @s[1]
 
 	@ Inv_GF16 \t0, \t1, \t2, \t3, \s0, \s1, \s2, \s3
 
 	@ new smaller inversion
 
 	vand	@s[2], @t[3], @t[1]
 	vmov	@s[0], @t[0]
 
 	veor	@s[1], @t[2], @s[2]
 	veor	@s[3], @t[0], @s[2]
 	veor	@s[2], @t[0], @s[2]	@ @s[2]=@s[3]
 
 	vbsl	@s[1], @t[1], @t[0]
 	vbsl	@s[3], @t[3], @t[2]
 	veor	@t[3], @t[3], @t[2]
 
 	vbsl	@s[0], @s[1], @s[2]
 	vbsl	@t[0], @s[2], @s[1]
 
 	vand	@s[2], @s[0], @s[3]
 	veor	@t[1], @t[1], @t[0]
 
 	veor	@s[2], @s[2], @t[3]
 ___
 # output in s3, s2, s1, t1
 
 # Mul_GF16_2 \x0, \x1, \x2, \x3, \x4, \x5, \x6, \x7, \t2, \t3, \t0, \t1, \s0, \s1, \s2, \s3
 
 # Mul_GF16_2 \x0, \x1, \x2, \x3, \x4, \x5, \x6, \x7, \s3, \s2, \s1, \t1, \s0, \t0, \t2, \t3
 	&Mul_GF16_2(@x,@s[3,2,1],@t[1],@s[0],@t[0,2,3]);
 
 ### output msb > [x3,x2,x1,x0,x7,x6,x5,x4] < lsb
 }
 
 # AES linear components
 
 sub ShiftRows {
 my @x=@_[0..7];
 my @t=@_[8..11];
 my $mask=pop;
 $code.=<<___;
 	vldmia	$key!, {@t[0]-@t[3]}
 	veor	@t[0], @t[0], @x[0]
 	veor	@t[1], @t[1], @x[1]
 	vtbl.8	`&Dlo(@x[0])`, {@t[0]}, `&Dlo($mask)`
 	vtbl.8	`&Dhi(@x[0])`, {@t[0]}, `&Dhi($mask)`
 	vldmia	$key!, {@t[0]}
 	veor	@t[2], @t[2], @x[2]
 	vtbl.8	`&Dlo(@x[1])`, {@t[1]}, `&Dlo($mask)`
 	vtbl.8	`&Dhi(@x[1])`, {@t[1]}, `&Dhi($mask)`
 	vldmia	$key!, {@t[1]}
 	veor	@t[3], @t[3], @x[3]
 	vtbl.8	`&Dlo(@x[2])`, {@t[2]}, `&Dlo($mask)`
 	vtbl.8	`&Dhi(@x[2])`, {@t[2]}, `&Dhi($mask)`
 	vldmia	$key!, {@t[2]}
 	vtbl.8	`&Dlo(@x[3])`, {@t[3]}, `&Dlo($mask)`
 	vtbl.8	`&Dhi(@x[3])`, {@t[3]}, `&Dhi($mask)`
 	vldmia	$key!, {@t[3]}
 	veor	@t[0], @t[0], @x[4]
 	veor	@t[1], @t[1], @x[5]
 	vtbl.8	`&Dlo(@x[4])`, {@t[0]}, `&Dlo($mask)`
 	vtbl.8	`&Dhi(@x[4])`, {@t[0]}, `&Dhi($mask)`
 	veor	@t[2], @t[2], @x[6]
 	vtbl.8	`&Dlo(@x[5])`, {@t[1]}, `&Dlo($mask)`
 	vtbl.8	`&Dhi(@x[5])`, {@t[1]}, `&Dhi($mask)`
 	veor	@t[3], @t[3], @x[7]
 	vtbl.8	`&Dlo(@x[6])`, {@t[2]}, `&Dlo($mask)`
 	vtbl.8	`&Dhi(@x[6])`, {@t[2]}, `&Dhi($mask)`
 	vtbl.8	`&Dlo(@x[7])`, {@t[3]}, `&Dlo($mask)`
 	vtbl.8	`&Dhi(@x[7])`, {@t[3]}, `&Dhi($mask)`
 ___
 }
 
 sub MixColumns {
 # modified to emit output in order suitable for feeding back to aesenc[last]
 my @x=@_[0..7];
 my @t=@_[8..15];
 my $inv=@_[16];	# optional
 $code.=<<___;
 	vext.8	@t[0], @x[0], @x[0], #12	@ x0 <<< 32
 	vext.8	@t[1], @x[1], @x[1], #12
 	 veor	@x[0], @x[0], @t[0]		@ x0 ^ (x0 <<< 32)
 	vext.8	@t[2], @x[2], @x[2], #12
 	 veor	@x[1], @x[1], @t[1]
 	vext.8	@t[3], @x[3], @x[3], #12
 	 veor	@x[2], @x[2], @t[2]
 	vext.8	@t[4], @x[4], @x[4], #12
 	 veor	@x[3], @x[3], @t[3]
 	vext.8	@t[5], @x[5], @x[5], #12
 	 veor	@x[4], @x[4], @t[4]
 	vext.8	@t[6], @x[6], @x[6], #12
 	 veor	@x[5], @x[5], @t[5]
 	vext.8	@t[7], @x[7], @x[7], #12
 	 veor	@x[6], @x[6], @t[6]
 
 	veor	@t[1], @t[1], @x[0]
 	 veor	@x[7], @x[7], @t[7]
 	 vext.8	@x[0], @x[0], @x[0], #8		@ (x0 ^ (x0 <<< 32)) <<< 64)
 	veor	@t[2], @t[2], @x[1]
 	veor	@t[0], @t[0], @x[7]
 	veor	@t[1], @t[1], @x[7]
 	 vext.8	@x[1], @x[1], @x[1], #8
 	veor	@t[5], @t[5], @x[4]
 	 veor	@x[0], @x[0], @t[0]
 	veor	@t[6], @t[6], @x[5]
 	 veor	@x[1], @x[1], @t[1]
 	 vext.8	@t[0], @x[4], @x[4], #8
 	veor	@t[4], @t[4], @x[3]
 	 vext.8	@t[1], @x[5], @x[5], #8
 	veor	@t[7], @t[7], @x[6]
 	 vext.8	@x[4], @x[3], @x[3], #8
 	veor	@t[3], @t[3], @x[2]
 	 vext.8	@x[5], @x[7], @x[7], #8
 	veor	@t[4], @t[4], @x[7]
 	 vext.8	@x[3], @x[6], @x[6], #8
 	veor	@t[3], @t[3], @x[7]
 	 vext.8	@x[6], @x[2], @x[2], #8
 	veor	@x[7], @t[1], @t[5]
 ___
 $code.=<<___ if (!$inv);
 	veor	@x[2], @t[0], @t[4]
 	veor	@x[4], @x[4], @t[3]
 	veor	@x[5], @x[5], @t[7]
 	veor	@x[3], @x[3], @t[6]
 	 @ vmov	@x[2], @t[0]
 	veor	@x[6], @x[6], @t[2]
 	 @ vmov	@x[7], @t[1]
 ___
 $code.=<<___ if ($inv);
 	veor	@t[3], @t[3], @x[4]
 	veor	@x[5], @x[5], @t[7]
 	veor	@x[2], @x[3], @t[6]
 	veor	@x[3], @t[0], @t[4]
 	veor	@x[4], @x[6], @t[2]
 	vmov	@x[6], @t[3]
 	 @ vmov	@x[7], @t[1]
 ___
 }
 
 sub InvMixColumns_orig {
 my @x=@_[0..7];
 my @t=@_[8..15];
 
 $code.=<<___;
 	@ multiplication by 0x0e
 	vext.8	@t[7], @x[7], @x[7], #12
 	vmov	@t[2], @x[2]
 	veor	@x[2], @x[2], @x[5]		@ 2 5
 	veor	@x[7], @x[7], @x[5]		@ 7 5
 	vext.8	@t[0], @x[0], @x[0], #12
 	vmov	@t[5], @x[5]
 	veor	@x[5], @x[5], @x[0]		@ 5 0		[1]
 	veor	@x[0], @x[0], @x[1]		@ 0 1
 	vext.8	@t[1], @x[1], @x[1], #12
 	veor	@x[1], @x[1], @x[2]		@ 1 25
 	veor	@x[0], @x[0], @x[6]		@ 01 6		[2]
 	vext.8	@t[3], @x[3], @x[3], #12
 	veor	@x[1], @x[1], @x[3]		@ 125 3		[4]
 	veor	@x[2], @x[2], @x[0]		@ 25 016	[3]
 	veor	@x[3], @x[3], @x[7]		@ 3 75
 	veor	@x[7], @x[7], @x[6]		@ 75 6		[0]
 	vext.8	@t[6], @x[6], @x[6], #12
 	vmov	@t[4], @x[4]
 	veor	@x[6], @x[6], @x[4]		@ 6 4
 	veor	@x[4], @x[4], @x[3]		@ 4 375		[6]
 	veor	@x[3], @x[3], @x[7]		@ 375 756=36
 	veor	@x[6], @x[6], @t[5]		@ 64 5		[7]
 	veor	@x[3], @x[3], @t[2]		@ 36 2
 	vext.8	@t[5], @t[5], @t[5], #12
 	veor	@x[3], @x[3], @t[4]		@ 362 4		[5]
 ___
 					my @y = @x[7,5,0,2,1,3,4,6];
 $code.=<<___;
 	@ multiplication by 0x0b
 	veor	@y[1], @y[1], @y[0]
 	veor	@y[0], @y[0], @t[0]
 	vext.8	@t[2], @t[2], @t[2], #12
 	veor	@y[1], @y[1], @t[1]
 	veor	@y[0], @y[0], @t[5]
 	vext.8	@t[4], @t[4], @t[4], #12
 	veor	@y[1], @y[1], @t[6]
 	veor	@y[0], @y[0], @t[7]
 	veor	@t[7], @t[7], @t[6]		@ clobber t[7]
 
 	veor	@y[3], @y[3], @t[0]
 	 veor	@y[1], @y[1], @y[0]
 	vext.8	@t[0], @t[0], @t[0], #12
 	veor	@y[2], @y[2], @t[1]
 	veor	@y[4], @y[4], @t[1]
 	vext.8	@t[1], @t[1], @t[1], #12
 	veor	@y[2], @y[2], @t[2]
 	veor	@y[3], @y[3], @t[2]
 	veor	@y[5], @y[5], @t[2]
 	veor	@y[2], @y[2], @t[7]
 	vext.8	@t[2], @t[2], @t[2], #12
 	veor	@y[3], @y[3], @t[3]
 	veor	@y[6], @y[6], @t[3]
 	veor	@y[4], @y[4], @t[3]
 	veor	@y[7], @y[7], @t[4]
 	vext.8	@t[3], @t[3], @t[3], #12
 	veor	@y[5], @y[5], @t[4]
 	veor	@y[7], @y[7], @t[7]
 	veor	@t[7], @t[7], @t[5]		@ clobber t[7] even more
 	veor	@y[3], @y[3], @t[5]
 	veor	@y[4], @y[4], @t[4]
 
 	veor	@y[5], @y[5], @t[7]
 	vext.8	@t[4], @t[4], @t[4], #12
 	veor	@y[6], @y[6], @t[7]
 	veor	@y[4], @y[4], @t[7]
 
 	veor	@t[7], @t[7], @t[5]
 	vext.8	@t[5], @t[5], @t[5], #12
 
 	@ multiplication by 0x0d
 	veor	@y[4], @y[4], @y[7]
 	 veor	@t[7], @t[7], @t[6]		@ restore t[7]
 	veor	@y[7], @y[7], @t[4]
 	vext.8	@t[6], @t[6], @t[6], #12
 	veor	@y[2], @y[2], @t[0]
 	veor	@y[7], @y[7], @t[5]
 	vext.8	@t[7], @t[7], @t[7], #12
 	veor	@y[2], @y[2], @t[2]
 
 	veor	@y[3], @y[3], @y[1]
 	veor	@y[1], @y[1], @t[1]
 	veor	@y[0], @y[0], @t[0]
 	veor	@y[3], @y[3], @t[0]
 	veor	@y[1], @y[1], @t[5]
 	veor	@y[0], @y[0], @t[5]
 	vext.8	@t[0], @t[0], @t[0], #12
 	veor	@y[1], @y[1], @t[7]
 	veor	@y[0], @y[0], @t[6]
 	veor	@y[3], @y[3], @y[1]
 	veor	@y[4], @y[4], @t[1]
 	vext.8	@t[1], @t[1], @t[1], #12
 
 	veor	@y[7], @y[7], @t[7]
 	veor	@y[4], @y[4], @t[2]
 	veor	@y[5], @y[5], @t[2]
 	veor	@y[2], @y[2], @t[6]
 	veor	@t[6], @t[6], @t[3]		@ clobber t[6]
 	vext.8	@t[2], @t[2], @t[2], #12
 	veor	@y[4], @y[4], @y[7]
 	veor	@y[3], @y[3], @t[6]
 
 	veor	@y[6], @y[6], @t[6]
 	veor	@y[5], @y[5], @t[5]
 	vext.8	@t[5], @t[5], @t[5], #12
 	veor	@y[6], @y[6], @t[4]
 	vext.8	@t[4], @t[4], @t[4], #12
 	veor	@y[5], @y[5], @t[6]
 	veor	@y[6], @y[6], @t[7]
 	vext.8	@t[7], @t[7], @t[7], #12
 	veor	@t[6], @t[6], @t[3]		@ restore t[6]
 	vext.8	@t[3], @t[3], @t[3], #12
 
 	@ multiplication by 0x09
 	veor	@y[4], @y[4], @y[1]
 	veor	@t[1], @t[1], @y[1]		@ t[1]=y[1]
 	veor	@t[0], @t[0], @t[5]		@ clobber t[0]
 	vext.8	@t[6], @t[6], @t[6], #12
 	veor	@t[1], @t[1], @t[5]
 	veor	@y[3], @y[3], @t[0]
 	veor	@t[0], @t[0], @y[0]		@ t[0]=y[0]
 	veor	@t[1], @t[1], @t[6]
 	veor	@t[6], @t[6], @t[7]		@ clobber t[6]
 	veor	@y[4], @y[4], @t[1]
 	veor	@y[7], @y[7], @t[4]
 	veor	@y[6], @y[6], @t[3]
 	veor	@y[5], @y[5], @t[2]
 	veor	@t[4], @t[4], @y[4]		@ t[4]=y[4]
 	veor	@t[3], @t[3], @y[3]		@ t[3]=y[3]
 	veor	@t[5], @t[5], @y[5]		@ t[5]=y[5]
 	veor	@t[2], @t[2], @y[2]		@ t[2]=y[2]
 	veor	@t[3], @t[3], @t[7]
 	veor	@XMM[5], @t[5], @t[6]
 	veor	@XMM[6], @t[6], @y[6]		@ t[6]=y[6]
 	veor	@XMM[2], @t[2], @t[6]
 	veor	@XMM[7], @t[7], @y[7]		@ t[7]=y[7]
 
 	vmov	@XMM[0], @t[0]
 	vmov	@XMM[1], @t[1]
 	@ vmov	@XMM[2], @t[2]
 	vmov	@XMM[3], @t[3]
 	vmov	@XMM[4], @t[4]
 	@ vmov	@XMM[5], @t[5]
 	@ vmov	@XMM[6], @t[6]
 	@ vmov	@XMM[7], @t[7]
 ___
 }
 
 sub InvMixColumns {
 my @x=@_[0..7];
 my @t=@_[8..15];
 
 # Thanks to Jussi Kivilinna for providing pointer to
 #
 # | 0e 0b 0d 09 |   | 02 03 01 01 |   | 05 00 04 00 |
 # | 09 0e 0b 0d | = | 01 02 03 01 | x | 00 05 00 04 |
 # | 0d 09 0e 0b |   | 01 01 02 03 |   | 04 00 05 00 |
 # | 0b 0d 09 0e |   | 03 01 01 02 |   | 00 04 00 05 |
 
 $code.=<<___;
 	@ multiplication by 0x05-0x00-0x04-0x00
 	vext.8	@t[0], @x[0], @x[0], #8
 	vext.8	@t[6], @x[6], @x[6], #8
 	vext.8	@t[7], @x[7], @x[7], #8
 	veor	@t[0], @t[0], @x[0]
 	vext.8	@t[1], @x[1], @x[1], #8
 	veor	@t[6], @t[6], @x[6]
 	vext.8	@t[2], @x[2], @x[2], #8
 	veor	@t[7], @t[7], @x[7]
 	vext.8	@t[3], @x[3], @x[3], #8
 	veor	@t[1], @t[1], @x[1]
 	vext.8	@t[4], @x[4], @x[4], #8
 	veor	@t[2], @t[2], @x[2]
 	vext.8	@t[5], @x[5], @x[5], #8
 	veor	@t[3], @t[3], @x[3]
 	veor	@t[4], @t[4], @x[4]
 	veor	@t[5], @t[5], @x[5]
 
 	 veor	@x[0], @x[0], @t[6]
 	 veor	@x[1], @x[1], @t[6]
 	 veor	@x[2], @x[2], @t[0]
 	 veor	@x[4], @x[4], @t[2]
 	 veor	@x[3], @x[3], @t[1]
 	 veor	@x[1], @x[1], @t[7]
 	 veor	@x[2], @x[2], @t[7]
 	 veor	@x[4], @x[4], @t[6]
 	 veor	@x[5], @x[5], @t[3]
 	 veor	@x[3], @x[3], @t[6]
 	 veor	@x[6], @x[6], @t[4]
 	 veor	@x[4], @x[4], @t[7]
 	 veor	@x[5], @x[5], @t[7]
 	 veor	@x[7], @x[7], @t[5]
 ___
 	&MixColumns	(@x,@t,1);	# flipped 2<->3 and 4<->6
 }
 
 sub swapmove {
 my ($a,$b,$n,$mask,$t)=@_;
 $code.=<<___;
 	vshr.u64	$t, $b, #$n
 	veor		$t, $t, $a
 	vand		$t, $t, $mask
 	veor		$a, $a, $t
 	vshl.u64	$t, $t, #$n
 	veor		$b, $b, $t
 ___
 }
 sub swapmove2x {
 my ($a0,$b0,$a1,$b1,$n,$mask,$t0,$t1)=@_;
 $code.=<<___;
 	vshr.u64	$t0, $b0, #$n
 	 vshr.u64	$t1, $b1, #$n
 	veor		$t0, $t0, $a0
 	 veor		$t1, $t1, $a1
 	vand		$t0, $t0, $mask
 	 vand		$t1, $t1, $mask
 	veor		$a0, $a0, $t0
 	vshl.u64	$t0, $t0, #$n
 	 veor		$a1, $a1, $t1
 	 vshl.u64	$t1, $t1, #$n
 	veor		$b0, $b0, $t0
 	 veor		$b1, $b1, $t1
 ___
 }
 
 sub bitslice {
 my @x=reverse(@_[0..7]);
 my ($t0,$t1,$t2,$t3)=@_[8..11];
 $code.=<<___;
 	vmov.i8	$t0,#0x55			@ compose .LBS0
 	vmov.i8	$t1,#0x33			@ compose .LBS1
 ___
 	&swapmove2x(@x[0,1,2,3],1,$t0,$t2,$t3);
 	&swapmove2x(@x[4,5,6,7],1,$t0,$t2,$t3);
 $code.=<<___;
 	vmov.i8	$t0,#0x0f			@ compose .LBS2
 ___
 	&swapmove2x(@x[0,2,1,3],2,$t1,$t2,$t3);
 	&swapmove2x(@x[4,6,5,7],2,$t1,$t2,$t3);
 
 	&swapmove2x(@x[0,4,1,5],4,$t0,$t2,$t3);
 	&swapmove2x(@x[2,6,3,7],4,$t0,$t2,$t3);
 }
 
 $code.=<<___;
 #ifndef __KERNEL__
 # include "arm_arch.h"
 
 # define VFP_ABI_PUSH	vstmdb	sp!,{d8-d15}
 # define VFP_ABI_POP	vldmia	sp!,{d8-d15}
 # define VFP_ABI_FRAME	0x40
 #else
 # define VFP_ABI_PUSH
 # define VFP_ABI_POP
 # define VFP_ABI_FRAME	0
 # define BSAES_ASM_EXTENDED_KEY
 # define XTS_CHAIN_TWEAK
 # define __ARM_ARCH__ __LINUX_ARM_ARCH__
 # define __ARM_MAX_ARCH__ __LINUX_ARM_ARCH__
 #endif
 
 #ifdef __thumb__
 # define adrl adr
 #endif
 
 #if __ARM_MAX_ARCH__>=7
 .arch	armv7-a
 .fpu	neon
 
 .text
 .syntax	unified 	@ ARMv7-capable assembler is expected to handle this
 #ifdef __thumb2__
 .thumb
 #else
 .code   32
 #endif
 
 .type	_bsaes_decrypt8,%function
 .align	4
 _bsaes_decrypt8:
 	adr	$const,_bsaes_decrypt8
 	vldmia	$key!, {@XMM[9]}		@ round 0 key
 	add	$const,$const,#.LM0ISR-_bsaes_decrypt8
 
 	vldmia	$const!, {@XMM[8]}		@ .LM0ISR
 	veor	@XMM[10], @XMM[0], @XMM[9]	@ xor with round0 key
 	veor	@XMM[11], @XMM[1], @XMM[9]
 	 vtbl.8	`&Dlo(@XMM[0])`, {@XMM[10]}, `&Dlo(@XMM[8])`
 	 vtbl.8	`&Dhi(@XMM[0])`, {@XMM[10]}, `&Dhi(@XMM[8])`
 	veor	@XMM[12], @XMM[2], @XMM[9]
 	 vtbl.8	`&Dlo(@XMM[1])`, {@XMM[11]}, `&Dlo(@XMM[8])`
 	 vtbl.8	`&Dhi(@XMM[1])`, {@XMM[11]}, `&Dhi(@XMM[8])`
 	veor	@XMM[13], @XMM[3], @XMM[9]
 	 vtbl.8	`&Dlo(@XMM[2])`, {@XMM[12]}, `&Dlo(@XMM[8])`
 	 vtbl.8	`&Dhi(@XMM[2])`, {@XMM[12]}, `&Dhi(@XMM[8])`
 	veor	@XMM[14], @XMM[4], @XMM[9]
 	 vtbl.8	`&Dlo(@XMM[3])`, {@XMM[13]}, `&Dlo(@XMM[8])`
 	 vtbl.8	`&Dhi(@XMM[3])`, {@XMM[13]}, `&Dhi(@XMM[8])`
 	veor	@XMM[15], @XMM[5], @XMM[9]
 	 vtbl.8	`&Dlo(@XMM[4])`, {@XMM[14]}, `&Dlo(@XMM[8])`
 	 vtbl.8	`&Dhi(@XMM[4])`, {@XMM[14]}, `&Dhi(@XMM[8])`
 	veor	@XMM[10], @XMM[6], @XMM[9]
 	 vtbl.8	`&Dlo(@XMM[5])`, {@XMM[15]}, `&Dlo(@XMM[8])`
 	 vtbl.8	`&Dhi(@XMM[5])`, {@XMM[15]}, `&Dhi(@XMM[8])`
 	veor	@XMM[11], @XMM[7], @XMM[9]
 	 vtbl.8	`&Dlo(@XMM[6])`, {@XMM[10]}, `&Dlo(@XMM[8])`
 	 vtbl.8	`&Dhi(@XMM[6])`, {@XMM[10]}, `&Dhi(@XMM[8])`
 	 vtbl.8	`&Dlo(@XMM[7])`, {@XMM[11]}, `&Dlo(@XMM[8])`
 	 vtbl.8	`&Dhi(@XMM[7])`, {@XMM[11]}, `&Dhi(@XMM[8])`
 ___
 	&bitslice	(@XMM[0..7, 8..11]);
 $code.=<<___;
 	sub	$rounds,$rounds,#1
 	b	.Ldec_sbox
 .align	4
 .Ldec_loop:
 ___
 	&ShiftRows	(@XMM[0..7, 8..12]);
 $code.=".Ldec_sbox:\n";
 	&InvSbox	(@XMM[0..7, 8..15]);
 $code.=<<___;
 	subs	$rounds,$rounds,#1
 	bcc	.Ldec_done
 ___
 	&InvMixColumns	(@XMM[0,1,6,4,2,7,3,5, 8..15]);
 $code.=<<___;
 	vldmia	$const, {@XMM[12]}		@ .LISR
 	ite	eq				@ Thumb2 thing, sanity check in ARM
 	addeq	$const,$const,#0x10
 	bne	.Ldec_loop
 	vldmia	$const, {@XMM[12]}		@ .LISRM0
 	b	.Ldec_loop
 .align	4
 .Ldec_done:
 ___
 	&bitslice	(@XMM[0,1,6,4,2,7,3,5, 8..11]);
 $code.=<<___;
 	vldmia	$key, {@XMM[8]}			@ last round key
 	veor	@XMM[6], @XMM[6], @XMM[8]
 	veor	@XMM[4], @XMM[4], @XMM[8]
 	veor	@XMM[2], @XMM[2], @XMM[8]
 	veor	@XMM[7], @XMM[7], @XMM[8]
 	veor	@XMM[3], @XMM[3], @XMM[8]
 	veor	@XMM[5], @XMM[5], @XMM[8]
 	veor	@XMM[0], @XMM[0], @XMM[8]
 	veor	@XMM[1], @XMM[1], @XMM[8]
 	bx	lr
 .size	_bsaes_decrypt8,.-_bsaes_decrypt8
 
 .type	_bsaes_const,%object
 .align	6
 _bsaes_const:
 .LM0ISR:	@ InvShiftRows constants
 	.quad	0x0a0e0206070b0f03, 0x0004080c0d010509
 .LISR:
 	.quad	0x0504070602010003, 0x0f0e0d0c080b0a09
 .LISRM0:
 	.quad	0x01040b0e0205080f, 0x0306090c00070a0d
 .LM0SR:		@ ShiftRows constants
 	.quad	0x0a0e02060f03070b, 0x0004080c05090d01
 .LSR:
 	.quad	0x0504070600030201, 0x0f0e0d0c0a09080b
 .LSRM0:
 	.quad	0x0304090e00050a0f, 0x01060b0c0207080d
 .LM0:
 	.quad	0x02060a0e03070b0f, 0x0004080c0105090d
 .LREVM0SR:
 	.quad	0x090d01050c000408, 0x03070b0f060a0e02
 .asciz	"Bit-sliced AES for NEON, CRYPTOGAMS by "
 .align	6
 .size	_bsaes_const,.-_bsaes_const
 
 .type	_bsaes_encrypt8,%function
 .align	4
 _bsaes_encrypt8:
 	adr	$const,_bsaes_encrypt8
 	vldmia	$key!, {@XMM[9]}		@ round 0 key
 	sub	$const,$const,#_bsaes_encrypt8-.LM0SR
 
 	vldmia	$const!, {@XMM[8]}		@ .LM0SR
 _bsaes_encrypt8_alt:
 	veor	@XMM[10], @XMM[0], @XMM[9]	@ xor with round0 key
 	veor	@XMM[11], @XMM[1], @XMM[9]
 	 vtbl.8	`&Dlo(@XMM[0])`, {@XMM[10]}, `&Dlo(@XMM[8])`
 	 vtbl.8	`&Dhi(@XMM[0])`, {@XMM[10]}, `&Dhi(@XMM[8])`
 	veor	@XMM[12], @XMM[2], @XMM[9]
 	 vtbl.8	`&Dlo(@XMM[1])`, {@XMM[11]}, `&Dlo(@XMM[8])`
 	 vtbl.8	`&Dhi(@XMM[1])`, {@XMM[11]}, `&Dhi(@XMM[8])`
 	veor	@XMM[13], @XMM[3], @XMM[9]
 	 vtbl.8	`&Dlo(@XMM[2])`, {@XMM[12]}, `&Dlo(@XMM[8])`
 	 vtbl.8	`&Dhi(@XMM[2])`, {@XMM[12]}, `&Dhi(@XMM[8])`
 	veor	@XMM[14], @XMM[4], @XMM[9]
 	 vtbl.8	`&Dlo(@XMM[3])`, {@XMM[13]}, `&Dlo(@XMM[8])`
 	 vtbl.8	`&Dhi(@XMM[3])`, {@XMM[13]}, `&Dhi(@XMM[8])`
 	veor	@XMM[15], @XMM[5], @XMM[9]
 	 vtbl.8	`&Dlo(@XMM[4])`, {@XMM[14]}, `&Dlo(@XMM[8])`
 	 vtbl.8	`&Dhi(@XMM[4])`, {@XMM[14]}, `&Dhi(@XMM[8])`
 	veor	@XMM[10], @XMM[6], @XMM[9]
 	 vtbl.8	`&Dlo(@XMM[5])`, {@XMM[15]}, `&Dlo(@XMM[8])`
 	 vtbl.8	`&Dhi(@XMM[5])`, {@XMM[15]}, `&Dhi(@XMM[8])`
 	veor	@XMM[11], @XMM[7], @XMM[9]
 	 vtbl.8	`&Dlo(@XMM[6])`, {@XMM[10]}, `&Dlo(@XMM[8])`
 	 vtbl.8	`&Dhi(@XMM[6])`, {@XMM[10]}, `&Dhi(@XMM[8])`
 	 vtbl.8	`&Dlo(@XMM[7])`, {@XMM[11]}, `&Dlo(@XMM[8])`
 	 vtbl.8	`&Dhi(@XMM[7])`, {@XMM[11]}, `&Dhi(@XMM[8])`
 _bsaes_encrypt8_bitslice:
 ___
 	&bitslice	(@XMM[0..7, 8..11]);
 $code.=<<___;
 	sub	$rounds,$rounds,#1
 	b	.Lenc_sbox
 .align	4
 .Lenc_loop:
 ___
 	&ShiftRows	(@XMM[0..7, 8..12]);
 $code.=".Lenc_sbox:\n";
 	&Sbox		(@XMM[0..7, 8..15]);
 $code.=<<___;
 	subs	$rounds,$rounds,#1
 	bcc	.Lenc_done
 ___
 	&MixColumns	(@XMM[0,1,4,6,3,7,2,5, 8..15]);
 $code.=<<___;
 	vldmia	$const, {@XMM[12]}		@ .LSR
 	ite	eq				@ Thumb2 thing, samity check in ARM
 	addeq	$const,$const,#0x10
 	bne	.Lenc_loop
 	vldmia	$const, {@XMM[12]}		@ .LSRM0
 	b	.Lenc_loop
 .align	4
 .Lenc_done:
 ___
 	# output in lsb > [t0, t1, t4, t6, t3, t7, t2, t5] < msb
 	&bitslice	(@XMM[0,1,4,6,3,7,2,5, 8..11]);
 $code.=<<___;
 	vldmia	$key, {@XMM[8]}			@ last round key
 	veor	@XMM[4], @XMM[4], @XMM[8]
 	veor	@XMM[6], @XMM[6], @XMM[8]
 	veor	@XMM[3], @XMM[3], @XMM[8]
 	veor	@XMM[7], @XMM[7], @XMM[8]
 	veor	@XMM[2], @XMM[2], @XMM[8]
 	veor	@XMM[5], @XMM[5], @XMM[8]
 	veor	@XMM[0], @XMM[0], @XMM[8]
 	veor	@XMM[1], @XMM[1], @XMM[8]
 	bx	lr
 .size	_bsaes_encrypt8,.-_bsaes_encrypt8
 ___
 }
 {
 my ($out,$inp,$rounds,$const)=("r12","r4","r5","r6");
 
 sub bitslice_key {
 my @x=reverse(@_[0..7]);
 my ($bs0,$bs1,$bs2,$t2,$t3)=@_[8..12];
 
 	&swapmove	(@x[0,1],1,$bs0,$t2,$t3);
 $code.=<<___;
 	@ &swapmove(@x[2,3],1,$t0,$t2,$t3);
 	vmov	@x[2], @x[0]
 	vmov	@x[3], @x[1]
 ___
 	#&swapmove2x(@x[4,5,6,7],1,$t0,$t2,$t3);
 
 	&swapmove2x	(@x[0,2,1,3],2,$bs1,$t2,$t3);
 $code.=<<___;
 	@ &swapmove2x(@x[4,6,5,7],2,$t1,$t2,$t3);
 	vmov	@x[4], @x[0]
 	vmov	@x[6], @x[2]
 	vmov	@x[5], @x[1]
 	vmov	@x[7], @x[3]
 ___
 	&swapmove2x	(@x[0,4,1,5],4,$bs2,$t2,$t3);
 	&swapmove2x	(@x[2,6,3,7],4,$bs2,$t2,$t3);
 }
 
 $code.=<<___;
 .type	_bsaes_key_convert,%function
 .align	4
 _bsaes_key_convert:
 	adr	$const,_bsaes_key_convert
 	vld1.8	{@XMM[7]},  [$inp]!		@ load round 0 key
 	sub	$const,$const,#_bsaes_key_convert-.LM0
 	vld1.8	{@XMM[15]}, [$inp]!		@ load round 1 key
 
 	vmov.i8	@XMM[8],  #0x01			@ bit masks
 	vmov.i8	@XMM[9],  #0x02
 	vmov.i8	@XMM[10], #0x04
 	vmov.i8	@XMM[11], #0x08
 	vmov.i8	@XMM[12], #0x10
 	vmov.i8	@XMM[13], #0x20
 	vldmia	$const, {@XMM[14]}		@ .LM0
 
 #ifdef __ARMEL__
 	vrev32.8	@XMM[7],  @XMM[7]
 	vrev32.8	@XMM[15], @XMM[15]
 #endif
 	sub	$rounds,$rounds,#1
 	vstmia	$out!, {@XMM[7]}		@ save round 0 key
 	b	.Lkey_loop
 
 .align	4
 .Lkey_loop:
 	vtbl.8	`&Dlo(@XMM[7])`,{@XMM[15]},`&Dlo(@XMM[14])`
 	vtbl.8	`&Dhi(@XMM[7])`,{@XMM[15]},`&Dhi(@XMM[14])`
 	vmov.i8	@XMM[6],  #0x40
 	vmov.i8	@XMM[15], #0x80
 
 	vtst.8	@XMM[0], @XMM[7], @XMM[8]
 	vtst.8	@XMM[1], @XMM[7], @XMM[9]
 	vtst.8	@XMM[2], @XMM[7], @XMM[10]
 	vtst.8	@XMM[3], @XMM[7], @XMM[11]
 	vtst.8	@XMM[4], @XMM[7], @XMM[12]
 	vtst.8	@XMM[5], @XMM[7], @XMM[13]
 	vtst.8	@XMM[6], @XMM[7], @XMM[6]
 	vtst.8	@XMM[7], @XMM[7], @XMM[15]
 	vld1.8	{@XMM[15]}, [$inp]!		@ load next round key
 	vmvn	@XMM[0], @XMM[0]		@ "pnot"
 	vmvn	@XMM[1], @XMM[1]
 	vmvn	@XMM[5], @XMM[5]
 	vmvn	@XMM[6], @XMM[6]
 #ifdef __ARMEL__
 	vrev32.8	@XMM[15], @XMM[15]
 #endif
 	subs	$rounds,$rounds,#1
 	vstmia	$out!,{@XMM[0]-@XMM[7]}		@ write bit-sliced round key
 	bne	.Lkey_loop
 
 	vmov.i8	@XMM[7],#0x63			@ compose .L63
 	@ don't save last round key
 	bx	lr
 .size	_bsaes_key_convert,.-_bsaes_key_convert
 ___
 }
 
 if (0) {		# following four functions are unsupported interface
 			# used for benchmarking...
 $code.=<<___;
 .globl	bsaes_enc_key_convert
 .type	bsaes_enc_key_convert,%function
 .align	4
 bsaes_enc_key_convert:
 	stmdb	sp!,{r4-r6,lr}
 	vstmdb	sp!,{d8-d15}		@ ABI specification says so
 
 	ldr	r5,[$inp,#240]			@ pass rounds
 	mov	r4,$inp				@ pass key
 	mov	r12,$out			@ pass key schedule
 	bl	_bsaes_key_convert
 	veor	@XMM[7],@XMM[7],@XMM[15]	@ fix up last round key
 	vstmia	r12, {@XMM[7]}			@ save last round key
 
 	vldmia	sp!,{d8-d15}
 	ldmia	sp!,{r4-r6,pc}
 .size	bsaes_enc_key_convert,.-bsaes_enc_key_convert
 
 .globl	bsaes_encrypt_128
 .type	bsaes_encrypt_128,%function
 .align	4
 bsaes_encrypt_128:
 	stmdb	sp!,{r4-r6,lr}
 	vstmdb	sp!,{d8-d15}		@ ABI specification says so
 .Lenc128_loop:
 	vld1.8	{@XMM[0]-@XMM[1]}, [$inp]!	@ load input
 	vld1.8	{@XMM[2]-@XMM[3]}, [$inp]!
 	mov	r4,$key				@ pass the key
 	vld1.8	{@XMM[4]-@XMM[5]}, [$inp]!
 	mov	r5,#10				@ pass rounds
 	vld1.8	{@XMM[6]-@XMM[7]}, [$inp]!
 
 	bl	_bsaes_encrypt8
 
 	vst1.8	{@XMM[0]-@XMM[1]}, [$out]!	@ write output
 	vst1.8	{@XMM[4]}, [$out]!
 	vst1.8	{@XMM[6]}, [$out]!
 	vst1.8	{@XMM[3]}, [$out]!
 	vst1.8	{@XMM[7]}, [$out]!
 	vst1.8	{@XMM[2]}, [$out]!
 	subs	$len,$len,#0x80
 	vst1.8	{@XMM[5]}, [$out]!
 	bhi	.Lenc128_loop
 
 	vldmia	sp!,{d8-d15}
 	ldmia	sp!,{r4-r6,pc}
 .size	bsaes_encrypt_128,.-bsaes_encrypt_128
 
 .globl	bsaes_dec_key_convert
 .type	bsaes_dec_key_convert,%function
 .align	4
 bsaes_dec_key_convert:
 	stmdb	sp!,{r4-r6,lr}
 	vstmdb	sp!,{d8-d15}		@ ABI specification says so
 
 	ldr	r5,[$inp,#240]			@ pass rounds
 	mov	r4,$inp				@ pass key
 	mov	r12,$out			@ pass key schedule
 	bl	_bsaes_key_convert
 	vldmia	$out, {@XMM[6]}
 	vstmia	r12,  {@XMM[15]}		@ save last round key
 	veor	@XMM[7], @XMM[7], @XMM[6]	@ fix up round 0 key
 	vstmia	$out, {@XMM[7]}
 
 	vldmia	sp!,{d8-d15}
 	ldmia	sp!,{r4-r6,pc}
 .size	bsaes_dec_key_convert,.-bsaes_dec_key_convert
 
 .globl	bsaes_decrypt_128
 .type	bsaes_decrypt_128,%function
 .align	4
 bsaes_decrypt_128:
 	stmdb	sp!,{r4-r6,lr}
 	vstmdb	sp!,{d8-d15}		@ ABI specification says so
 .Ldec128_loop:
 	vld1.8	{@XMM[0]-@XMM[1]}, [$inp]!	@ load input
 	vld1.8	{@XMM[2]-@XMM[3]}, [$inp]!
 	mov	r4,$key				@ pass the key
 	vld1.8	{@XMM[4]-@XMM[5]}, [$inp]!
 	mov	r5,#10				@ pass rounds
 	vld1.8	{@XMM[6]-@XMM[7]}, [$inp]!
 
 	bl	_bsaes_decrypt8
 
 	vst1.8	{@XMM[0]-@XMM[1]}, [$out]!	@ write output
 	vst1.8	{@XMM[6]}, [$out]!
 	vst1.8	{@XMM[4]}, [$out]!
 	vst1.8	{@XMM[2]}, [$out]!
 	vst1.8	{@XMM[7]}, [$out]!
 	vst1.8	{@XMM[3]}, [$out]!
 	subs	$len,$len,#0x80
 	vst1.8	{@XMM[5]}, [$out]!
 	bhi	.Ldec128_loop
 
 	vldmia	sp!,{d8-d15}
 	ldmia	sp!,{r4-r6,pc}
 .size	bsaes_decrypt_128,.-bsaes_decrypt_128
 ___
 }
 {
 my ($inp,$out,$len,$key, $ivp,$fp,$rounds)=map("r$_",(0..3,8..10));
 my ($keysched)=("sp");
 
 $code.=<<___;
 .extern AES_cbc_encrypt
 .extern AES_decrypt
 
 .global	bsaes_cbc_encrypt
 .type	bsaes_cbc_encrypt,%function
 .align	5
 bsaes_cbc_encrypt:
 #ifndef	__KERNEL__
 	cmp	$len, #128
 #ifndef	__thumb__
 	blo	AES_cbc_encrypt
 #else
 	bhs	1f
 	b	AES_cbc_encrypt
 1:
 #endif
 #endif
 
 	@ it is up to the caller to make sure we are called with enc == 0
 
 	mov	ip, sp
 	stmdb	sp!, {r4-r10, lr}
 	VFP_ABI_PUSH
 	ldr	$ivp, [ip]			@ IV is 1st arg on the stack
 	mov	$len, $len, lsr#4		@ len in 16 byte blocks
 	sub	sp, #0x10			@ scratch space to carry over the IV
 	mov	$fp, sp				@ save sp
 
 	ldr	$rounds, [$key, #240]		@ get # of rounds
 #ifndef	BSAES_ASM_EXTENDED_KEY
 	@ allocate the key schedule on the stack
 	sub	r12, sp, $rounds, lsl#7		@ 128 bytes per inner round key
 	add	r12, #`128-32`			@ sifze of bit-slices key schedule
 
 	@ populate the key schedule
 	mov	r4, $key			@ pass key
 	mov	r5, $rounds			@ pass # of rounds
 	mov	sp, r12				@ sp is $keysched
 	bl	_bsaes_key_convert
 	vldmia	$keysched, {@XMM[6]}
 	vstmia	r12,  {@XMM[15]}		@ save last round key
 	veor	@XMM[7], @XMM[7], @XMM[6]	@ fix up round 0 key
 	vstmia	$keysched, {@XMM[7]}
 #else
 	ldr	r12, [$key, #244]
 	eors	r12, #1
 	beq	0f
 
 	@ populate the key schedule
 	str	r12, [$key, #244]
 	mov	r4, $key			@ pass key
 	mov	r5, $rounds			@ pass # of rounds
 	add	r12, $key, #248			@ pass key schedule
 	bl	_bsaes_key_convert
 	add	r4, $key, #248
 	vldmia	r4, {@XMM[6]}
 	vstmia	r12, {@XMM[15]}			@ save last round key
 	veor	@XMM[7], @XMM[7], @XMM[6]	@ fix up round 0 key
 	vstmia	r4, {@XMM[7]}
 
 .align	2
 0:
 #endif
 
 	vld1.8	{@XMM[15]}, [$ivp]		@ load IV
 	b	.Lcbc_dec_loop
 
 .align	4
 .Lcbc_dec_loop:
 	subs	$len, $len, #0x8
 	bmi	.Lcbc_dec_loop_finish
 
 	vld1.8	{@XMM[0]-@XMM[1]}, [$inp]!	@ load input
 	vld1.8	{@XMM[2]-@XMM[3]}, [$inp]!
 #ifndef	BSAES_ASM_EXTENDED_KEY
 	mov	r4, $keysched			@ pass the key
 #else
 	add	r4, $key, #248
 #endif
 	vld1.8	{@XMM[4]-@XMM[5]}, [$inp]!
 	mov	r5, $rounds
 	vld1.8	{@XMM[6]-@XMM[7]}, [$inp]
 	sub	$inp, $inp, #0x60
 	vstmia	$fp, {@XMM[15]}			@ put aside IV
 
 	bl	_bsaes_decrypt8
 
 	vldmia	$fp, {@XMM[14]}			@ reload IV
 	vld1.8	{@XMM[8]-@XMM[9]}, [$inp]!	@ reload input
 	veor	@XMM[0], @XMM[0], @XMM[14]	@ ^= IV
 	vld1.8	{@XMM[10]-@XMM[11]}, [$inp]!
 	veor	@XMM[1], @XMM[1], @XMM[8]
 	veor	@XMM[6], @XMM[6], @XMM[9]
 	vld1.8	{@XMM[12]-@XMM[13]}, [$inp]!
 	veor	@XMM[4], @XMM[4], @XMM[10]
 	veor	@XMM[2], @XMM[2], @XMM[11]
 	vld1.8	{@XMM[14]-@XMM[15]}, [$inp]!
 	veor	@XMM[7], @XMM[7], @XMM[12]
 	vst1.8	{@XMM[0]-@XMM[1]}, [$out]!	@ write output
 	veor	@XMM[3], @XMM[3], @XMM[13]
 	vst1.8	{@XMM[6]}, [$out]!
 	veor	@XMM[5], @XMM[5], @XMM[14]
 	vst1.8	{@XMM[4]}, [$out]!
 	vst1.8	{@XMM[2]}, [$out]!
 	vst1.8	{@XMM[7]}, [$out]!
 	vst1.8	{@XMM[3]}, [$out]!
 	vst1.8	{@XMM[5]}, [$out]!
 
 	b	.Lcbc_dec_loop
 
 .Lcbc_dec_loop_finish:
 	adds	$len, $len, #8
 	beq	.Lcbc_dec_done
 
 	vld1.8	{@XMM[0]}, [$inp]!		@ load input
 	cmp	$len, #2
 	blo	.Lcbc_dec_one
 	vld1.8	{@XMM[1]}, [$inp]!
 #ifndef	BSAES_ASM_EXTENDED_KEY
 	mov	r4, $keysched			@ pass the key
 #else
 	add	r4, $key, #248
 #endif
 	mov	r5, $rounds
 	vstmia	$fp, {@XMM[15]}			@ put aside IV
 	beq	.Lcbc_dec_two
 	vld1.8	{@XMM[2]}, [$inp]!
 	cmp	$len, #4
 	blo	.Lcbc_dec_three
 	vld1.8	{@XMM[3]}, [$inp]!
 	beq	.Lcbc_dec_four
 	vld1.8	{@XMM[4]}, [$inp]!
 	cmp	$len, #6
 	blo	.Lcbc_dec_five
 	vld1.8	{@XMM[5]}, [$inp]!
 	beq	.Lcbc_dec_six
 	vld1.8	{@XMM[6]}, [$inp]!
 	sub	$inp, $inp, #0x70
 
 	bl	_bsaes_decrypt8
 
 	vldmia	$fp, {@XMM[14]}			@ reload IV
 	vld1.8	{@XMM[8]-@XMM[9]}, [$inp]!	@ reload input
 	veor	@XMM[0], @XMM[0], @XMM[14]	@ ^= IV
 	vld1.8	{@XMM[10]-@XMM[11]}, [$inp]!
 	veor	@XMM[1], @XMM[1], @XMM[8]
 	veor	@XMM[6], @XMM[6], @XMM[9]
 	vld1.8	{@XMM[12]-@XMM[13]}, [$inp]!
 	veor	@XMM[4], @XMM[4], @XMM[10]
 	veor	@XMM[2], @XMM[2], @XMM[11]
 	vld1.8	{@XMM[15]}, [$inp]!
 	veor	@XMM[7], @XMM[7], @XMM[12]
 	vst1.8	{@XMM[0]-@XMM[1]}, [$out]!	@ write output
 	veor	@XMM[3], @XMM[3], @XMM[13]
 	vst1.8	{@XMM[6]}, [$out]!
 	vst1.8	{@XMM[4]}, [$out]!
 	vst1.8	{@XMM[2]}, [$out]!
 	vst1.8	{@XMM[7]}, [$out]!
 	vst1.8	{@XMM[3]}, [$out]!
 	b	.Lcbc_dec_done
 .align	4
 .Lcbc_dec_six:
 	sub	$inp, $inp, #0x60
 	bl	_bsaes_decrypt8
 	vldmia	$fp,{@XMM[14]}			@ reload IV
 	vld1.8	{@XMM[8]-@XMM[9]}, [$inp]!	@ reload input
 	veor	@XMM[0], @XMM[0], @XMM[14]	@ ^= IV
 	vld1.8	{@XMM[10]-@XMM[11]}, [$inp]!
 	veor	@XMM[1], @XMM[1], @XMM[8]
 	veor	@XMM[6], @XMM[6], @XMM[9]
 	vld1.8	{@XMM[12]}, [$inp]!
 	veor	@XMM[4], @XMM[4], @XMM[10]
 	veor	@XMM[2], @XMM[2], @XMM[11]
 	vld1.8	{@XMM[15]}, [$inp]!
 	veor	@XMM[7], @XMM[7], @XMM[12]
 	vst1.8	{@XMM[0]-@XMM[1]}, [$out]!	@ write output
 	vst1.8	{@XMM[6]}, [$out]!
 	vst1.8	{@XMM[4]}, [$out]!
 	vst1.8	{@XMM[2]}, [$out]!
 	vst1.8	{@XMM[7]}, [$out]!
 	b	.Lcbc_dec_done
 .align	4
 .Lcbc_dec_five:
 	sub	$inp, $inp, #0x50
 	bl	_bsaes_decrypt8
 	vldmia	$fp, {@XMM[14]}			@ reload IV
 	vld1.8	{@XMM[8]-@XMM[9]}, [$inp]!	@ reload input
 	veor	@XMM[0], @XMM[0], @XMM[14]	@ ^= IV
 	vld1.8	{@XMM[10]-@XMM[11]}, [$inp]!
 	veor	@XMM[1], @XMM[1], @XMM[8]
 	veor	@XMM[6], @XMM[6], @XMM[9]
 	vld1.8	{@XMM[15]}, [$inp]!
 	veor	@XMM[4], @XMM[4], @XMM[10]
 	vst1.8	{@XMM[0]-@XMM[1]}, [$out]!	@ write output
 	veor	@XMM[2], @XMM[2], @XMM[11]
 	vst1.8	{@XMM[6]}, [$out]!
 	vst1.8	{@XMM[4]}, [$out]!
 	vst1.8	{@XMM[2]}, [$out]!
 	b	.Lcbc_dec_done
 .align	4
 .Lcbc_dec_four:
 	sub	$inp, $inp, #0x40
 	bl	_bsaes_decrypt8
 	vldmia	$fp, {@XMM[14]}			@ reload IV
 	vld1.8	{@XMM[8]-@XMM[9]}, [$inp]!	@ reload input
 	veor	@XMM[0], @XMM[0], @XMM[14]	@ ^= IV
 	vld1.8	{@XMM[10]}, [$inp]!
 	veor	@XMM[1], @XMM[1], @XMM[8]
 	veor	@XMM[6], @XMM[6], @XMM[9]
 	vld1.8	{@XMM[15]}, [$inp]!
 	veor	@XMM[4], @XMM[4], @XMM[10]
 	vst1.8	{@XMM[0]-@XMM[1]}, [$out]!	@ write output
 	vst1.8	{@XMM[6]}, [$out]!
 	vst1.8	{@XMM[4]}, [$out]!
 	b	.Lcbc_dec_done
 .align	4
 .Lcbc_dec_three:
 	sub	$inp, $inp, #0x30
 	bl	_bsaes_decrypt8
 	vldmia	$fp, {@XMM[14]}			@ reload IV
 	vld1.8	{@XMM[8]-@XMM[9]}, [$inp]!	@ reload input
 	veor	@XMM[0], @XMM[0], @XMM[14]	@ ^= IV
 	vld1.8	{@XMM[15]}, [$inp]!
 	veor	@XMM[1], @XMM[1], @XMM[8]
 	veor	@XMM[6], @XMM[6], @XMM[9]
 	vst1.8	{@XMM[0]-@XMM[1]}, [$out]!	@ write output
 	vst1.8	{@XMM[6]}, [$out]!
 	b	.Lcbc_dec_done
 .align	4
 .Lcbc_dec_two:
 	sub	$inp, $inp, #0x20
 	bl	_bsaes_decrypt8
 	vldmia	$fp, {@XMM[14]}			@ reload IV
 	vld1.8	{@XMM[8]}, [$inp]!		@ reload input
 	veor	@XMM[0], @XMM[0], @XMM[14]	@ ^= IV
 	vld1.8	{@XMM[15]}, [$inp]!		@ reload input
 	veor	@XMM[1], @XMM[1], @XMM[8]
 	vst1.8	{@XMM[0]-@XMM[1]}, [$out]!	@ write output
 	b	.Lcbc_dec_done
 .align	4
 .Lcbc_dec_one:
 	sub	$inp, $inp, #0x10
 	mov	$rounds, $out			@ save original out pointer
 	mov	$out, $fp			@ use the iv scratch space as out buffer
 	mov	r2, $key
 	vmov	@XMM[4],@XMM[15]		@ just in case ensure that IV
 	vmov	@XMM[5],@XMM[0]			@ and input are preserved
 	bl	AES_decrypt
-	vld1.8	{@XMM[0]}, [$fp,:64]		@ load result
+	vld1.8	{@XMM[0]}, [$fp]		@ load result
 	veor	@XMM[0], @XMM[0], @XMM[4]	@ ^= IV
 	vmov	@XMM[15], @XMM[5]		@ @XMM[5] holds input
 	vst1.8	{@XMM[0]}, [$rounds]		@ write output
 
 .Lcbc_dec_done:
 #ifndef	BSAES_ASM_EXTENDED_KEY
 	vmov.i32	q0, #0
 	vmov.i32	q1, #0
 .Lcbc_dec_bzero:				@ wipe key schedule [if any]
 	vstmia		$keysched!, {q0-q1}
 	cmp		$keysched, $fp
 	bne		.Lcbc_dec_bzero
 #endif
 
 	mov	sp, $fp
 	add	sp, #0x10			@ add sp,$fp,#0x10 is no good for thumb
 	vst1.8	{@XMM[15]}, [$ivp]		@ return IV
 	VFP_ABI_POP
 	ldmia	sp!, {r4-r10, pc}
 .size	bsaes_cbc_encrypt,.-bsaes_cbc_encrypt
 ___
 }
 {
 my ($inp,$out,$len,$key, $ctr,$fp,$rounds)=(map("r$_",(0..3,8..10)));
 my $const = "r6";	# shared with _bsaes_encrypt8_alt
 my $keysched = "sp";
 
 $code.=<<___;
 .extern	AES_encrypt
 .global	bsaes_ctr32_encrypt_blocks
 .type	bsaes_ctr32_encrypt_blocks,%function
 .align	5
 bsaes_ctr32_encrypt_blocks:
 	cmp	$len, #8			@ use plain AES for
 	blo	.Lctr_enc_short			@ small sizes
 
 	mov	ip, sp
 	stmdb	sp!, {r4-r10, lr}
 	VFP_ABI_PUSH
 	ldr	$ctr, [ip]			@ ctr is 1st arg on the stack
 	sub	sp, sp, #0x10			@ scratch space to carry over the ctr
 	mov	$fp, sp				@ save sp
 
 	ldr	$rounds, [$key, #240]		@ get # of rounds
 #ifndef	BSAES_ASM_EXTENDED_KEY
 	@ allocate the key schedule on the stack
 	sub	r12, sp, $rounds, lsl#7		@ 128 bytes per inner round key
 	add	r12, #`128-32`			@ size of bit-sliced key schedule
 
 	@ populate the key schedule
 	mov	r4, $key			@ pass key
 	mov	r5, $rounds			@ pass # of rounds
 	mov	sp, r12				@ sp is $keysched
 	bl	_bsaes_key_convert
 	veor	@XMM[7],@XMM[7],@XMM[15]	@ fix up last round key
 	vstmia	r12, {@XMM[7]}			@ save last round key
 
 	vld1.8	{@XMM[0]}, [$ctr]		@ load counter
 	add	$ctr, $const, #.LREVM0SR-.LM0	@ borrow $ctr
 	vldmia	$keysched, {@XMM[4]}		@ load round0 key
 #else
 	ldr	r12, [$key, #244]
 	eors	r12, #1
 	beq	0f
 
 	@ populate the key schedule
 	str	r12, [$key, #244]
 	mov	r4, $key			@ pass key
 	mov	r5, $rounds			@ pass # of rounds
 	add	r12, $key, #248			@ pass key schedule
 	bl	_bsaes_key_convert
 	veor	@XMM[7],@XMM[7],@XMM[15]	@ fix up last round key
 	vstmia	r12, {@XMM[7]}			@ save last round key
 
 .align	2
 0:	add	r12, $key, #248
 	vld1.8	{@XMM[0]}, [$ctr]		@ load counter
 	adrl	$ctr, .LREVM0SR			@ borrow $ctr
 	vldmia	r12, {@XMM[4]}			@ load round0 key
 	sub	sp, #0x10			@ place for adjusted round0 key
 #endif
 
 	vmov.i32	@XMM[8],#1		@ compose 1<<96
 	veor		@XMM[9],@XMM[9],@XMM[9]
 	vrev32.8	@XMM[0],@XMM[0]
 	vext.8		@XMM[8],@XMM[9],@XMM[8],#4
 	vrev32.8	@XMM[4],@XMM[4]
 	vadd.u32	@XMM[9],@XMM[8],@XMM[8]	@ compose 2<<96
 	vstmia	$keysched, {@XMM[4]}		@ save adjusted round0 key
 	b	.Lctr_enc_loop
 
 .align	4
 .Lctr_enc_loop:
 	vadd.u32	@XMM[10], @XMM[8], @XMM[9]	@ compose 3<<96
 	vadd.u32	@XMM[1], @XMM[0], @XMM[8]	@ +1
 	vadd.u32	@XMM[2], @XMM[0], @XMM[9]	@ +2
 	vadd.u32	@XMM[3], @XMM[0], @XMM[10]	@ +3
 	vadd.u32	@XMM[4], @XMM[1], @XMM[10]
 	vadd.u32	@XMM[5], @XMM[2], @XMM[10]
 	vadd.u32	@XMM[6], @XMM[3], @XMM[10]
 	vadd.u32	@XMM[7], @XMM[4], @XMM[10]
 	vadd.u32	@XMM[10], @XMM[5], @XMM[10]	@ next counter
 
 	@ Borrow prologue from _bsaes_encrypt8 to use the opportunity
 	@ to flip byte order in 32-bit counter
 
 	vldmia		$keysched, {@XMM[9]}		@ load round0 key
 #ifndef	BSAES_ASM_EXTENDED_KEY
 	add		r4, $keysched, #0x10		@ pass next round key
 #else
 	add		r4, $key, #`248+16`
 #endif
 	vldmia		$ctr, {@XMM[8]}			@ .LREVM0SR
 	mov		r5, $rounds			@ pass rounds
 	vstmia		$fp, {@XMM[10]}			@ save next counter
 	sub		$const, $ctr, #.LREVM0SR-.LSR	@ pass constants
 
 	bl		_bsaes_encrypt8_alt
 
 	subs		$len, $len, #8
 	blo		.Lctr_enc_loop_done
 
 	vld1.8		{@XMM[8]-@XMM[9]}, [$inp]!	@ load input
 	vld1.8		{@XMM[10]-@XMM[11]}, [$inp]!
 	veor		@XMM[0], @XMM[8]
 	veor		@XMM[1], @XMM[9]
 	vld1.8		{@XMM[12]-@XMM[13]}, [$inp]!
 	veor		@XMM[4], @XMM[10]
 	veor		@XMM[6], @XMM[11]
 	vld1.8		{@XMM[14]-@XMM[15]}, [$inp]!
 	veor		@XMM[3], @XMM[12]
 	vst1.8		{@XMM[0]-@XMM[1]}, [$out]!	@ write output
 	veor		@XMM[7], @XMM[13]
 	veor		@XMM[2], @XMM[14]
 	vst1.8		{@XMM[4]}, [$out]!
 	veor		@XMM[5], @XMM[15]
 	vst1.8		{@XMM[6]}, [$out]!
 	vmov.i32	@XMM[8], #1			@ compose 1<<96
 	vst1.8		{@XMM[3]}, [$out]!
 	veor		@XMM[9], @XMM[9], @XMM[9]
 	vst1.8		{@XMM[7]}, [$out]!
 	vext.8		@XMM[8], @XMM[9], @XMM[8], #4
 	vst1.8		{@XMM[2]}, [$out]!
 	vadd.u32	@XMM[9],@XMM[8],@XMM[8]		@ compose 2<<96
 	vst1.8		{@XMM[5]}, [$out]!
 	vldmia		$fp, {@XMM[0]}			@ load counter
 
 	bne		.Lctr_enc_loop
 	b		.Lctr_enc_done
 
 .align	4
 .Lctr_enc_loop_done:
 	add		$len, $len, #8
 	vld1.8		{@XMM[8]}, [$inp]!	@ load input
 	veor		@XMM[0], @XMM[8]
 	vst1.8		{@XMM[0]}, [$out]!	@ write output
 	cmp		$len, #2
 	blo		.Lctr_enc_done
 	vld1.8		{@XMM[9]}, [$inp]!
 	veor		@XMM[1], @XMM[9]
 	vst1.8		{@XMM[1]}, [$out]!
 	beq		.Lctr_enc_done
 	vld1.8		{@XMM[10]}, [$inp]!
 	veor		@XMM[4], @XMM[10]
 	vst1.8		{@XMM[4]}, [$out]!
 	cmp		$len, #4
 	blo		.Lctr_enc_done
 	vld1.8		{@XMM[11]}, [$inp]!
 	veor		@XMM[6], @XMM[11]
 	vst1.8		{@XMM[6]}, [$out]!
 	beq		.Lctr_enc_done
 	vld1.8		{@XMM[12]}, [$inp]!
 	veor		@XMM[3], @XMM[12]
 	vst1.8		{@XMM[3]}, [$out]!
 	cmp		$len, #6
 	blo		.Lctr_enc_done
 	vld1.8		{@XMM[13]}, [$inp]!
 	veor		@XMM[7], @XMM[13]
 	vst1.8		{@XMM[7]}, [$out]!
 	beq		.Lctr_enc_done
 	vld1.8		{@XMM[14]}, [$inp]
 	veor		@XMM[2], @XMM[14]
 	vst1.8		{@XMM[2]}, [$out]!
 
 .Lctr_enc_done:
 	vmov.i32	q0, #0
 	vmov.i32	q1, #0
 #ifndef	BSAES_ASM_EXTENDED_KEY
 .Lctr_enc_bzero:			@ wipe key schedule [if any]
 	vstmia		$keysched!, {q0-q1}
 	cmp		$keysched, $fp
 	bne		.Lctr_enc_bzero
 #else
 	vstmia		$keysched, {q0-q1}
 #endif
 
 	mov	sp, $fp
 	add	sp, #0x10		@ add sp,$fp,#0x10 is no good for thumb
 	VFP_ABI_POP
 	ldmia	sp!, {r4-r10, pc}	@ return
 
 .align	4
 .Lctr_enc_short:
 	ldr	ip, [sp]		@ ctr pointer is passed on stack
 	stmdb	sp!, {r4-r8, lr}
 
 	mov	r4, $inp		@ copy arguments
 	mov	r5, $out
 	mov	r6, $len
 	mov	r7, $key
 	ldr	r8, [ip, #12]		@ load counter LSW
 	vld1.8	{@XMM[1]}, [ip]		@ load whole counter value
 #ifdef __ARMEL__
 	rev	r8, r8
 #endif
 	sub	sp, sp, #0x10
 	vst1.8	{@XMM[1]}, [sp,:64]	@ copy counter value
 	sub	sp, sp, #0x10
 
 .Lctr_enc_short_loop:
 	add	r0, sp, #0x10		@ input counter value
 	mov	r1, sp			@ output on the stack
 	mov	r2, r7			@ key
 
 	bl	AES_encrypt
 
 	vld1.8	{@XMM[0]}, [r4]!	@ load input
 	vld1.8	{@XMM[1]}, [sp,:64]	@ load encrypted counter
 	add	r8, r8, #1
 #ifdef __ARMEL__
 	rev	r0, r8
 	str	r0, [sp, #0x1c]		@ next counter value
 #else
 	str	r8, [sp, #0x1c]		@ next counter value
 #endif
 	veor	@XMM[0],@XMM[0],@XMM[1]
 	vst1.8	{@XMM[0]}, [r5]!	@ store output
 	subs	r6, r6, #1
 	bne	.Lctr_enc_short_loop
 
 	vmov.i32	q0, #0
 	vmov.i32	q1, #0
 	vstmia		sp!, {q0-q1}
 
 	ldmia	sp!, {r4-r8, pc}
 .size	bsaes_ctr32_encrypt_blocks,.-bsaes_ctr32_encrypt_blocks
 ___
 }
 {
 ######################################################################
 # void bsaes_xts_[en|de]crypt(const char *inp,char *out,size_t len,
 #	const AES_KEY *key1, const AES_KEY *key2,
 #	const unsigned char iv[16]);
 #
 my ($inp,$out,$len,$key,$rounds,$magic,$fp)=(map("r$_",(7..10,1..3)));
 my $const="r6";		# returned by _bsaes_key_convert
 my $twmask=@XMM[5];
 my @T=@XMM[6..7];
 
 $code.=<<___;
 .globl	bsaes_xts_encrypt
 .type	bsaes_xts_encrypt,%function
 .align	4
 bsaes_xts_encrypt:
 	mov	ip, sp
 	stmdb	sp!, {r4-r10, lr}		@ 0x20
 	VFP_ABI_PUSH
 	mov	r6, sp				@ future $fp
 
 	mov	$inp, r0
 	mov	$out, r1
 	mov	$len, r2
 	mov	$key, r3
 
 	sub	r0, sp, #0x10			@ 0x10
 	bic	r0, #0xf			@ align at 16 bytes
 	mov	sp, r0
 
 #ifdef	XTS_CHAIN_TWEAK
 	ldr	r0, [ip]			@ pointer to input tweak
 #else
 	@ generate initial tweak
 	ldr	r0, [ip, #4]			@ iv[]
 	mov	r1, sp
 	ldr	r2, [ip, #0]			@ key2
 	bl	AES_encrypt
 	mov	r0,sp				@ pointer to initial tweak
 #endif
 
 	ldr	$rounds, [$key, #240]		@ get # of rounds
 	mov	$fp, r6
 #ifndef	BSAES_ASM_EXTENDED_KEY
 	@ allocate the key schedule on the stack
 	sub	r12, sp, $rounds, lsl#7		@ 128 bytes per inner round key
 	@ add	r12, #`128-32`			@ size of bit-sliced key schedule
 	sub	r12, #`32+16`			@ place for tweak[9]
 
 	@ populate the key schedule
 	mov	r4, $key			@ pass key
 	mov	r5, $rounds			@ pass # of rounds
 	mov	sp, r12
 	add	r12, #0x90			@ pass key schedule
 	bl	_bsaes_key_convert
 	veor	@XMM[7], @XMM[7], @XMM[15]	@ fix up last round key
 	vstmia	r12, {@XMM[7]}			@ save last round key
 #else
 	ldr	r12, [$key, #244]
 	eors	r12, #1
 	beq	0f
 
 	str	r12, [$key, #244]
 	mov	r4, $key			@ pass key
 	mov	r5, $rounds			@ pass # of rounds
 	add	r12, $key, #248			@ pass key schedule
 	bl	_bsaes_key_convert
 	veor	@XMM[7], @XMM[7], @XMM[15]	@ fix up last round key
 	vstmia	r12, {@XMM[7]}
 
 .align	2
 0:	sub	sp, #0x90			@ place for tweak[9]
 #endif
 
 	vld1.8	{@XMM[8]}, [r0]			@ initial tweak
 	adr	$magic, .Lxts_magic
 
 	subs	$len, #0x80
 	blo	.Lxts_enc_short
 	b	.Lxts_enc_loop
 
 .align	4
 .Lxts_enc_loop:
 	vldmia		$magic, {$twmask}	@ load XTS magic
 	vshr.s64	@T[0], @XMM[8], #63
 	mov		r0, sp
 	vand		@T[0], @T[0], $twmask
 ___
 for($i=9;$i<16;$i++) {
 $code.=<<___;
 	vadd.u64	@XMM[$i], @XMM[$i-1], @XMM[$i-1]
 	vst1.64		{@XMM[$i-1]}, [r0,:128]!
 	vswp		`&Dhi("@T[0]")`,`&Dlo("@T[0]")`
 	vshr.s64	@T[1], @XMM[$i], #63
 	veor		@XMM[$i], @XMM[$i], @T[0]
 	vand		@T[1], @T[1], $twmask
 ___
 	@T=reverse(@T);
 
 $code.=<<___ if ($i>=10);
 	vld1.8		{@XMM[$i-10]}, [$inp]!
 ___
 $code.=<<___ if ($i>=11);
 	veor		@XMM[$i-11], @XMM[$i-11], @XMM[$i-3]
 ___
 }
 $code.=<<___;
 	vadd.u64	@XMM[8], @XMM[15], @XMM[15]
 	vst1.64		{@XMM[15]}, [r0,:128]!
 	vswp		`&Dhi("@T[0]")`,`&Dlo("@T[0]")`
 	veor		@XMM[8], @XMM[8], @T[0]
 	vst1.64		{@XMM[8]}, [r0,:128]		@ next round tweak
 
 	vld1.8		{@XMM[6]-@XMM[7]}, [$inp]!
 	veor		@XMM[5], @XMM[5], @XMM[13]
 #ifndef	BSAES_ASM_EXTENDED_KEY
 	add		r4, sp, #0x90			@ pass key schedule
 #else
 	add		r4, $key, #248			@ pass key schedule
 #endif
 	veor		@XMM[6], @XMM[6], @XMM[14]
 	mov		r5, $rounds			@ pass rounds
 	veor		@XMM[7], @XMM[7], @XMM[15]
 	mov		r0, sp
 
 	bl		_bsaes_encrypt8
 
 	vld1.64		{@XMM[ 8]-@XMM[ 9]}, [r0,:128]!
 	vld1.64		{@XMM[10]-@XMM[11]}, [r0,:128]!
 	veor		@XMM[0], @XMM[0], @XMM[ 8]
 	vld1.64		{@XMM[12]-@XMM[13]}, [r0,:128]!
 	veor		@XMM[1], @XMM[1], @XMM[ 9]
 	veor		@XMM[8], @XMM[4], @XMM[10]
 	vst1.8		{@XMM[0]-@XMM[1]}, [$out]!
 	veor		@XMM[9], @XMM[6], @XMM[11]
 	vld1.64		{@XMM[14]-@XMM[15]}, [r0,:128]!
 	veor		@XMM[10], @XMM[3], @XMM[12]
 	vst1.8		{@XMM[8]-@XMM[9]}, [$out]!
 	veor		@XMM[11], @XMM[7], @XMM[13]
 	veor		@XMM[12], @XMM[2], @XMM[14]
 	vst1.8		{@XMM[10]-@XMM[11]}, [$out]!
 	veor		@XMM[13], @XMM[5], @XMM[15]
 	vst1.8		{@XMM[12]-@XMM[13]}, [$out]!
 
 	vld1.64		{@XMM[8]}, [r0,:128]		@ next round tweak
 
 	subs		$len, #0x80
 	bpl		.Lxts_enc_loop
 
 .Lxts_enc_short:
 	adds		$len, #0x70
 	bmi		.Lxts_enc_done
 
 	vldmia		$magic, {$twmask}	@ load XTS magic
 	vshr.s64	@T[0], @XMM[8], #63
 	mov		r0, sp
 	vand		@T[0], @T[0], $twmask
 ___
 for($i=9;$i<16;$i++) {
 $code.=<<___;
 	vadd.u64	@XMM[$i], @XMM[$i-1], @XMM[$i-1]
 	vst1.64		{@XMM[$i-1]}, [r0,:128]!
 	vswp		`&Dhi("@T[0]")`,`&Dlo("@T[0]")`
 	vshr.s64	@T[1], @XMM[$i], #63
 	veor		@XMM[$i], @XMM[$i], @T[0]
 	vand		@T[1], @T[1], $twmask
 ___
 	@T=reverse(@T);
 
 $code.=<<___ if ($i>=10);
 	vld1.8		{@XMM[$i-10]}, [$inp]!
 	subs		$len, #0x10
 	bmi		.Lxts_enc_`$i-9`
 ___
 $code.=<<___ if ($i>=11);
 	veor		@XMM[$i-11], @XMM[$i-11], @XMM[$i-3]
 ___
 }
 $code.=<<___;
 	sub		$len, #0x10
 	vst1.64		{@XMM[15]}, [r0,:128]		@ next round tweak
 
 	vld1.8		{@XMM[6]}, [$inp]!
 	veor		@XMM[5], @XMM[5], @XMM[13]
 #ifndef	BSAES_ASM_EXTENDED_KEY
 	add		r4, sp, #0x90			@ pass key schedule
 #else
 	add		r4, $key, #248			@ pass key schedule
 #endif
 	veor		@XMM[6], @XMM[6], @XMM[14]
 	mov		r5, $rounds			@ pass rounds
 	mov		r0, sp
 
 	bl		_bsaes_encrypt8
 
 	vld1.64		{@XMM[ 8]-@XMM[ 9]}, [r0,:128]!
 	vld1.64		{@XMM[10]-@XMM[11]}, [r0,:128]!
 	veor		@XMM[0], @XMM[0], @XMM[ 8]
 	vld1.64		{@XMM[12]-@XMM[13]}, [r0,:128]!
 	veor		@XMM[1], @XMM[1], @XMM[ 9]
 	veor		@XMM[8], @XMM[4], @XMM[10]
 	vst1.8		{@XMM[0]-@XMM[1]}, [$out]!
 	veor		@XMM[9], @XMM[6], @XMM[11]
 	vld1.64		{@XMM[14]}, [r0,:128]!
 	veor		@XMM[10], @XMM[3], @XMM[12]
 	vst1.8		{@XMM[8]-@XMM[9]}, [$out]!
 	veor		@XMM[11], @XMM[7], @XMM[13]
 	veor		@XMM[12], @XMM[2], @XMM[14]
 	vst1.8		{@XMM[10]-@XMM[11]}, [$out]!
 	vst1.8		{@XMM[12]}, [$out]!
 
 	vld1.64		{@XMM[8]}, [r0,:128]		@ next round tweak
 	b		.Lxts_enc_done
 .align	4
 .Lxts_enc_6:
 	veor		@XMM[4], @XMM[4], @XMM[12]
 #ifndef	BSAES_ASM_EXTENDED_KEY
 	add		r4, sp, #0x90			@ pass key schedule
 #else
 	add		r4, $key, #248			@ pass key schedule
 #endif
 	veor		@XMM[5], @XMM[5], @XMM[13]
 	mov		r5, $rounds			@ pass rounds
 	mov		r0, sp
 
 	bl		_bsaes_encrypt8
 
 	vld1.64		{@XMM[ 8]-@XMM[ 9]}, [r0,:128]!
 	vld1.64		{@XMM[10]-@XMM[11]}, [r0,:128]!
 	veor		@XMM[0], @XMM[0], @XMM[ 8]
 	vld1.64		{@XMM[12]-@XMM[13]}, [r0,:128]!
 	veor		@XMM[1], @XMM[1], @XMM[ 9]
 	veor		@XMM[8], @XMM[4], @XMM[10]
 	vst1.8		{@XMM[0]-@XMM[1]}, [$out]!
 	veor		@XMM[9], @XMM[6], @XMM[11]
 	veor		@XMM[10], @XMM[3], @XMM[12]
 	vst1.8		{@XMM[8]-@XMM[9]}, [$out]!
 	veor		@XMM[11], @XMM[7], @XMM[13]
 	vst1.8		{@XMM[10]-@XMM[11]}, [$out]!
 
 	vld1.64		{@XMM[8]}, [r0,:128]		@ next round tweak
 	b		.Lxts_enc_done
 
 @ put this in range for both ARM and Thumb mode adr instructions
 .align	5
 .Lxts_magic:
 	.quad	1, 0x87
 
 .align	5
 .Lxts_enc_5:
 	veor		@XMM[3], @XMM[3], @XMM[11]
 #ifndef	BSAES_ASM_EXTENDED_KEY
 	add		r4, sp, #0x90			@ pass key schedule
 #else
 	add		r4, $key, #248			@ pass key schedule
 #endif
 	veor		@XMM[4], @XMM[4], @XMM[12]
 	mov		r5, $rounds			@ pass rounds
 	mov		r0, sp
 
 	bl		_bsaes_encrypt8
 
 	vld1.64		{@XMM[ 8]-@XMM[ 9]}, [r0,:128]!
 	vld1.64		{@XMM[10]-@XMM[11]}, [r0,:128]!
 	veor		@XMM[0], @XMM[0], @XMM[ 8]
 	vld1.64		{@XMM[12]}, [r0,:128]!
 	veor		@XMM[1], @XMM[1], @XMM[ 9]
 	veor		@XMM[8], @XMM[4], @XMM[10]
 	vst1.8		{@XMM[0]-@XMM[1]}, [$out]!
 	veor		@XMM[9], @XMM[6], @XMM[11]
 	veor		@XMM[10], @XMM[3], @XMM[12]
 	vst1.8		{@XMM[8]-@XMM[9]}, [$out]!
 	vst1.8		{@XMM[10]}, [$out]!
 
 	vld1.64		{@XMM[8]}, [r0,:128]		@ next round tweak
 	b		.Lxts_enc_done
 .align	4
 .Lxts_enc_4:
 	veor		@XMM[2], @XMM[2], @XMM[10]
 #ifndef	BSAES_ASM_EXTENDED_KEY
 	add		r4, sp, #0x90			@ pass key schedule
 #else
 	add		r4, $key, #248			@ pass key schedule
 #endif
 	veor		@XMM[3], @XMM[3], @XMM[11]
 	mov		r5, $rounds			@ pass rounds
 	mov		r0, sp
 
 	bl		_bsaes_encrypt8
 
 	vld1.64		{@XMM[ 8]-@XMM[ 9]}, [r0,:128]!
 	vld1.64		{@XMM[10]-@XMM[11]}, [r0,:128]!
 	veor		@XMM[0], @XMM[0], @XMM[ 8]
 	veor		@XMM[1], @XMM[1], @XMM[ 9]
 	veor		@XMM[8], @XMM[4], @XMM[10]
 	vst1.8		{@XMM[0]-@XMM[1]}, [$out]!
 	veor		@XMM[9], @XMM[6], @XMM[11]
 	vst1.8		{@XMM[8]-@XMM[9]}, [$out]!
 
 	vld1.64		{@XMM[8]}, [r0,:128]		@ next round tweak
 	b		.Lxts_enc_done
 .align	4
 .Lxts_enc_3:
 	veor		@XMM[1], @XMM[1], @XMM[9]
 #ifndef	BSAES_ASM_EXTENDED_KEY
 	add		r4, sp, #0x90			@ pass key schedule
 #else
 	add		r4, $key, #248			@ pass key schedule
 #endif
 	veor		@XMM[2], @XMM[2], @XMM[10]
 	mov		r5, $rounds			@ pass rounds
 	mov		r0, sp
 
 	bl		_bsaes_encrypt8
 
 	vld1.64		{@XMM[8]-@XMM[9]}, [r0,:128]!
 	vld1.64		{@XMM[10]}, [r0,:128]!
 	veor		@XMM[0], @XMM[0], @XMM[ 8]
 	veor		@XMM[1], @XMM[1], @XMM[ 9]
 	veor		@XMM[8], @XMM[4], @XMM[10]
 	vst1.8		{@XMM[0]-@XMM[1]}, [$out]!
 	vst1.8		{@XMM[8]}, [$out]!
 
 	vld1.64		{@XMM[8]}, [r0,:128]		@ next round tweak
 	b		.Lxts_enc_done
 .align	4
 .Lxts_enc_2:
 	veor		@XMM[0], @XMM[0], @XMM[8]
 #ifndef	BSAES_ASM_EXTENDED_KEY
 	add		r4, sp, #0x90			@ pass key schedule
 #else
 	add		r4, $key, #248			@ pass key schedule
 #endif
 	veor		@XMM[1], @XMM[1], @XMM[9]
 	mov		r5, $rounds			@ pass rounds
 	mov		r0, sp
 
 	bl		_bsaes_encrypt8
 
 	vld1.64		{@XMM[8]-@XMM[9]}, [r0,:128]!
 	veor		@XMM[0], @XMM[0], @XMM[ 8]
 	veor		@XMM[1], @XMM[1], @XMM[ 9]
 	vst1.8		{@XMM[0]-@XMM[1]}, [$out]!
 
 	vld1.64		{@XMM[8]}, [r0,:128]		@ next round tweak
 	b		.Lxts_enc_done
 .align	4
 .Lxts_enc_1:
 	mov		r0, sp
 	veor		@XMM[0], @XMM[0], @XMM[8]
 	mov		r1, sp
 	vst1.8		{@XMM[0]}, [sp,:128]
 	mov		r2, $key
 	mov		r4, $fp				@ preserve fp
 
 	bl		AES_encrypt
 
 	vld1.8		{@XMM[0]}, [sp,:128]
 	veor		@XMM[0], @XMM[0], @XMM[8]
 	vst1.8		{@XMM[0]}, [$out]!
 	mov		$fp, r4
 
 	vmov		@XMM[8], @XMM[9]		@ next round tweak
 
 .Lxts_enc_done:
 #ifndef	XTS_CHAIN_TWEAK
 	adds		$len, #0x10
 	beq		.Lxts_enc_ret
 	sub		r6, $out, #0x10
 
 .Lxts_enc_steal:
 	ldrb		r0, [$inp], #1
 	ldrb		r1, [$out, #-0x10]
 	strb		r0, [$out, #-0x10]
 	strb		r1, [$out], #1
 
 	subs		$len, #1
 	bhi		.Lxts_enc_steal
 
 	vld1.8		{@XMM[0]}, [r6]
 	mov		r0, sp
 	veor		@XMM[0], @XMM[0], @XMM[8]
 	mov		r1, sp
 	vst1.8		{@XMM[0]}, [sp,:128]
 	mov		r2, $key
 	mov		r4, $fp			@ preserve fp
 
 	bl		AES_encrypt
 
 	vld1.8		{@XMM[0]}, [sp,:128]
 	veor		@XMM[0], @XMM[0], @XMM[8]
 	vst1.8		{@XMM[0]}, [r6]
 	mov		$fp, r4
 #endif
 
 .Lxts_enc_ret:
 	bic		r0, $fp, #0xf
 	vmov.i32	q0, #0
 	vmov.i32	q1, #0
 #ifdef	XTS_CHAIN_TWEAK
 	ldr		r1, [$fp, #0x20+VFP_ABI_FRAME]	@ chain tweak
 #endif
 .Lxts_enc_bzero:				@ wipe key schedule [if any]
 	vstmia		sp!, {q0-q1}
 	cmp		sp, r0
 	bne		.Lxts_enc_bzero
 
 	mov		sp, $fp
 #ifdef	XTS_CHAIN_TWEAK
 	vst1.8		{@XMM[8]}, [r1]
 #endif
 	VFP_ABI_POP
 	ldmia		sp!, {r4-r10, pc}	@ return
 
 .size	bsaes_xts_encrypt,.-bsaes_xts_encrypt
 
 .globl	bsaes_xts_decrypt
 .type	bsaes_xts_decrypt,%function
 .align	4
 bsaes_xts_decrypt:
 	mov	ip, sp
 	stmdb	sp!, {r4-r10, lr}		@ 0x20
 	VFP_ABI_PUSH
 	mov	r6, sp				@ future $fp
 
 	mov	$inp, r0
 	mov	$out, r1
 	mov	$len, r2
 	mov	$key, r3
 
 	sub	r0, sp, #0x10			@ 0x10
 	bic	r0, #0xf			@ align at 16 bytes
 	mov	sp, r0
 
 #ifdef	XTS_CHAIN_TWEAK
 	ldr	r0, [ip]			@ pointer to input tweak
 #else
 	@ generate initial tweak
 	ldr	r0, [ip, #4]			@ iv[]
 	mov	r1, sp
 	ldr	r2, [ip, #0]			@ key2
 	bl	AES_encrypt
 	mov	r0, sp				@ pointer to initial tweak
 #endif
 
 	ldr	$rounds, [$key, #240]		@ get # of rounds
 	mov	$fp, r6
 #ifndef	BSAES_ASM_EXTENDED_KEY
 	@ allocate the key schedule on the stack
 	sub	r12, sp, $rounds, lsl#7		@ 128 bytes per inner round key
 	@ add	r12, #`128-32`			@ size of bit-sliced key schedule
 	sub	r12, #`32+16`			@ place for tweak[9]
 
 	@ populate the key schedule
 	mov	r4, $key			@ pass key
 	mov	r5, $rounds			@ pass # of rounds
 	mov	sp, r12
 	add	r12, #0x90			@ pass key schedule
 	bl	_bsaes_key_convert
 	add	r4, sp, #0x90
 	vldmia	r4, {@XMM[6]}
 	vstmia	r12,  {@XMM[15]}		@ save last round key
 	veor	@XMM[7], @XMM[7], @XMM[6]	@ fix up round 0 key
 	vstmia	r4, {@XMM[7]}
 #else
 	ldr	r12, [$key, #244]
 	eors	r12, #1
 	beq	0f
 
 	str	r12, [$key, #244]
 	mov	r4, $key			@ pass key
 	mov	r5, $rounds			@ pass # of rounds
 	add	r12, $key, #248			@ pass key schedule
 	bl	_bsaes_key_convert
 	add	r4, $key, #248
 	vldmia	r4, {@XMM[6]}
 	vstmia	r12,  {@XMM[15]}		@ save last round key
 	veor	@XMM[7], @XMM[7], @XMM[6]	@ fix up round 0 key
 	vstmia	r4, {@XMM[7]}
 
 .align	2
 0:	sub	sp, #0x90			@ place for tweak[9]
 #endif
 	vld1.8	{@XMM[8]}, [r0]			@ initial tweak
 	adr	$magic, .Lxts_magic
 
 	tst	$len, #0xf			@ if not multiple of 16
 	it	ne				@ Thumb2 thing, sanity check in ARM
 	subne	$len, #0x10			@ subtract another 16 bytes
 	subs	$len, #0x80
 
 	blo	.Lxts_dec_short
 	b	.Lxts_dec_loop
 
 .align	4
 .Lxts_dec_loop:
 	vldmia		$magic, {$twmask}	@ load XTS magic
 	vshr.s64	@T[0], @XMM[8], #63
 	mov		r0, sp
 	vand		@T[0], @T[0], $twmask
 ___
 for($i=9;$i<16;$i++) {
 $code.=<<___;
 	vadd.u64	@XMM[$i], @XMM[$i-1], @XMM[$i-1]
 	vst1.64		{@XMM[$i-1]}, [r0,:128]!
 	vswp		`&Dhi("@T[0]")`,`&Dlo("@T[0]")`
 	vshr.s64	@T[1], @XMM[$i], #63
 	veor		@XMM[$i], @XMM[$i], @T[0]
 	vand		@T[1], @T[1], $twmask
 ___
 	@T=reverse(@T);
 
 $code.=<<___ if ($i>=10);
 	vld1.8		{@XMM[$i-10]}, [$inp]!
 ___
 $code.=<<___ if ($i>=11);
 	veor		@XMM[$i-11], @XMM[$i-11], @XMM[$i-3]
 ___
 }
 $code.=<<___;
 	vadd.u64	@XMM[8], @XMM[15], @XMM[15]
 	vst1.64		{@XMM[15]}, [r0,:128]!
 	vswp		`&Dhi("@T[0]")`,`&Dlo("@T[0]")`
 	veor		@XMM[8], @XMM[8], @T[0]
 	vst1.64		{@XMM[8]}, [r0,:128]		@ next round tweak
 
 	vld1.8		{@XMM[6]-@XMM[7]}, [$inp]!
 	veor		@XMM[5], @XMM[5], @XMM[13]
 #ifndef	BSAES_ASM_EXTENDED_KEY
 	add		r4, sp, #0x90			@ pass key schedule
 #else
 	add		r4, $key, #248			@ pass key schedule
 #endif
 	veor		@XMM[6], @XMM[6], @XMM[14]
 	mov		r5, $rounds			@ pass rounds
 	veor		@XMM[7], @XMM[7], @XMM[15]
 	mov		r0, sp
 
 	bl		_bsaes_decrypt8
 
 	vld1.64		{@XMM[ 8]-@XMM[ 9]}, [r0,:128]!
 	vld1.64		{@XMM[10]-@XMM[11]}, [r0,:128]!
 	veor		@XMM[0], @XMM[0], @XMM[ 8]
 	vld1.64		{@XMM[12]-@XMM[13]}, [r0,:128]!
 	veor		@XMM[1], @XMM[1], @XMM[ 9]
 	veor		@XMM[8], @XMM[6], @XMM[10]
 	vst1.8		{@XMM[0]-@XMM[1]}, [$out]!
 	veor		@XMM[9], @XMM[4], @XMM[11]
 	vld1.64		{@XMM[14]-@XMM[15]}, [r0,:128]!
 	veor		@XMM[10], @XMM[2], @XMM[12]
 	vst1.8		{@XMM[8]-@XMM[9]}, [$out]!
 	veor		@XMM[11], @XMM[7], @XMM[13]
 	veor		@XMM[12], @XMM[3], @XMM[14]
 	vst1.8		{@XMM[10]-@XMM[11]}, [$out]!
 	veor		@XMM[13], @XMM[5], @XMM[15]
 	vst1.8		{@XMM[12]-@XMM[13]}, [$out]!
 
 	vld1.64		{@XMM[8]}, [r0,:128]		@ next round tweak
 
 	subs		$len, #0x80
 	bpl		.Lxts_dec_loop
 
 .Lxts_dec_short:
 	adds		$len, #0x70
 	bmi		.Lxts_dec_done
 
 	vldmia		$magic, {$twmask}	@ load XTS magic
 	vshr.s64	@T[0], @XMM[8], #63
 	mov		r0, sp
 	vand		@T[0], @T[0], $twmask
 ___
 for($i=9;$i<16;$i++) {
 $code.=<<___;
 	vadd.u64	@XMM[$i], @XMM[$i-1], @XMM[$i-1]
 	vst1.64		{@XMM[$i-1]}, [r0,:128]!
 	vswp		`&Dhi("@T[0]")`,`&Dlo("@T[0]")`
 	vshr.s64	@T[1], @XMM[$i], #63
 	veor		@XMM[$i], @XMM[$i], @T[0]
 	vand		@T[1], @T[1], $twmask
 ___
 	@T=reverse(@T);
 
 $code.=<<___ if ($i>=10);
 	vld1.8		{@XMM[$i-10]}, [$inp]!
 	subs		$len, #0x10
 	bmi		.Lxts_dec_`$i-9`
 ___
 $code.=<<___ if ($i>=11);
 	veor		@XMM[$i-11], @XMM[$i-11], @XMM[$i-3]
 ___
 }
 $code.=<<___;
 	sub		$len, #0x10
 	vst1.64		{@XMM[15]}, [r0,:128]		@ next round tweak
 
 	vld1.8		{@XMM[6]}, [$inp]!
 	veor		@XMM[5], @XMM[5], @XMM[13]
 #ifndef	BSAES_ASM_EXTENDED_KEY
 	add		r4, sp, #0x90			@ pass key schedule
 #else
 	add		r4, $key, #248			@ pass key schedule
 #endif
 	veor		@XMM[6], @XMM[6], @XMM[14]
 	mov		r5, $rounds			@ pass rounds
 	mov		r0, sp
 
 	bl		_bsaes_decrypt8
 
 	vld1.64		{@XMM[ 8]-@XMM[ 9]}, [r0,:128]!
 	vld1.64		{@XMM[10]-@XMM[11]}, [r0,:128]!
 	veor		@XMM[0], @XMM[0], @XMM[ 8]
 	vld1.64		{@XMM[12]-@XMM[13]}, [r0,:128]!
 	veor		@XMM[1], @XMM[1], @XMM[ 9]
 	veor		@XMM[8], @XMM[6], @XMM[10]
 	vst1.8		{@XMM[0]-@XMM[1]}, [$out]!
 	veor		@XMM[9], @XMM[4], @XMM[11]
 	vld1.64		{@XMM[14]}, [r0,:128]!
 	veor		@XMM[10], @XMM[2], @XMM[12]
 	vst1.8		{@XMM[8]-@XMM[9]}, [$out]!
 	veor		@XMM[11], @XMM[7], @XMM[13]
 	veor		@XMM[12], @XMM[3], @XMM[14]
 	vst1.8		{@XMM[10]-@XMM[11]}, [$out]!
 	vst1.8		{@XMM[12]}, [$out]!
 
 	vld1.64		{@XMM[8]}, [r0,:128]		@ next round tweak
 	b		.Lxts_dec_done
 .align	4
 .Lxts_dec_6:
 	vst1.64		{@XMM[14]}, [r0,:128]		@ next round tweak
 
 	veor		@XMM[4], @XMM[4], @XMM[12]
 #ifndef	BSAES_ASM_EXTENDED_KEY
 	add		r4, sp, #0x90			@ pass key schedule
 #else
 	add		r4, $key, #248			@ pass key schedule
 #endif
 	veor		@XMM[5], @XMM[5], @XMM[13]
 	mov		r5, $rounds			@ pass rounds
 	mov		r0, sp
 
 	bl		_bsaes_decrypt8
 
 	vld1.64		{@XMM[ 8]-@XMM[ 9]}, [r0,:128]!
 	vld1.64		{@XMM[10]-@XMM[11]}, [r0,:128]!
 	veor		@XMM[0], @XMM[0], @XMM[ 8]
 	vld1.64		{@XMM[12]-@XMM[13]}, [r0,:128]!
 	veor		@XMM[1], @XMM[1], @XMM[ 9]
 	veor		@XMM[8], @XMM[6], @XMM[10]
 	vst1.8		{@XMM[0]-@XMM[1]}, [$out]!
 	veor		@XMM[9], @XMM[4], @XMM[11]
 	veor		@XMM[10], @XMM[2], @XMM[12]
 	vst1.8		{@XMM[8]-@XMM[9]}, [$out]!
 	veor		@XMM[11], @XMM[7], @XMM[13]
 	vst1.8		{@XMM[10]-@XMM[11]}, [$out]!
 
 	vld1.64		{@XMM[8]}, [r0,:128]		@ next round tweak
 	b		.Lxts_dec_done
 .align	4
 .Lxts_dec_5:
 	veor		@XMM[3], @XMM[3], @XMM[11]
 #ifndef	BSAES_ASM_EXTENDED_KEY
 	add		r4, sp, #0x90			@ pass key schedule
 #else
 	add		r4, $key, #248			@ pass key schedule
 #endif
 	veor		@XMM[4], @XMM[4], @XMM[12]
 	mov		r5, $rounds			@ pass rounds
 	mov		r0, sp
 
 	bl		_bsaes_decrypt8
 
 	vld1.64		{@XMM[ 8]-@XMM[ 9]}, [r0,:128]!
 	vld1.64		{@XMM[10]-@XMM[11]}, [r0,:128]!
 	veor		@XMM[0], @XMM[0], @XMM[ 8]
 	vld1.64		{@XMM[12]}, [r0,:128]!
 	veor		@XMM[1], @XMM[1], @XMM[ 9]
 	veor		@XMM[8], @XMM[6], @XMM[10]
 	vst1.8		{@XMM[0]-@XMM[1]}, [$out]!
 	veor		@XMM[9], @XMM[4], @XMM[11]
 	veor		@XMM[10], @XMM[2], @XMM[12]
 	vst1.8		{@XMM[8]-@XMM[9]}, [$out]!
 	vst1.8		{@XMM[10]}, [$out]!
 
 	vld1.64		{@XMM[8]}, [r0,:128]		@ next round tweak
 	b		.Lxts_dec_done
 .align	4
 .Lxts_dec_4:
 	veor		@XMM[2], @XMM[2], @XMM[10]
 #ifndef	BSAES_ASM_EXTENDED_KEY
 	add		r4, sp, #0x90			@ pass key schedule
 #else
 	add		r4, $key, #248			@ pass key schedule
 #endif
 	veor		@XMM[3], @XMM[3], @XMM[11]
 	mov		r5, $rounds			@ pass rounds
 	mov		r0, sp
 
 	bl		_bsaes_decrypt8
 
 	vld1.64		{@XMM[ 8]-@XMM[ 9]}, [r0,:128]!
 	vld1.64		{@XMM[10]-@XMM[11]}, [r0,:128]!
 	veor		@XMM[0], @XMM[0], @XMM[ 8]
 	veor		@XMM[1], @XMM[1], @XMM[ 9]
 	veor		@XMM[8], @XMM[6], @XMM[10]
 	vst1.8		{@XMM[0]-@XMM[1]}, [$out]!
 	veor		@XMM[9], @XMM[4], @XMM[11]
 	vst1.8		{@XMM[8]-@XMM[9]}, [$out]!
 
 	vld1.64		{@XMM[8]}, [r0,:128]		@ next round tweak
 	b		.Lxts_dec_done
 .align	4
 .Lxts_dec_3:
 	veor		@XMM[1], @XMM[1], @XMM[9]
 #ifndef	BSAES_ASM_EXTENDED_KEY
 	add		r4, sp, #0x90			@ pass key schedule
 #else
 	add		r4, $key, #248			@ pass key schedule
 #endif
 	veor		@XMM[2], @XMM[2], @XMM[10]
 	mov		r5, $rounds			@ pass rounds
 	mov		r0, sp
 
 	bl		_bsaes_decrypt8
 
 	vld1.64		{@XMM[8]-@XMM[9]}, [r0,:128]!
 	vld1.64		{@XMM[10]}, [r0,:128]!
 	veor		@XMM[0], @XMM[0], @XMM[ 8]
 	veor		@XMM[1], @XMM[1], @XMM[ 9]
 	veor		@XMM[8], @XMM[6], @XMM[10]
 	vst1.8		{@XMM[0]-@XMM[1]}, [$out]!
 	vst1.8		{@XMM[8]}, [$out]!
 
 	vld1.64		{@XMM[8]}, [r0,:128]		@ next round tweak
 	b		.Lxts_dec_done
 .align	4
 .Lxts_dec_2:
 	veor		@XMM[0], @XMM[0], @XMM[8]
 #ifndef	BSAES_ASM_EXTENDED_KEY
 	add		r4, sp, #0x90			@ pass key schedule
 #else
 	add		r4, $key, #248			@ pass key schedule
 #endif
 	veor		@XMM[1], @XMM[1], @XMM[9]
 	mov		r5, $rounds			@ pass rounds
 	mov		r0, sp
 
 	bl		_bsaes_decrypt8
 
 	vld1.64		{@XMM[8]-@XMM[9]}, [r0,:128]!
 	veor		@XMM[0], @XMM[0], @XMM[ 8]
 	veor		@XMM[1], @XMM[1], @XMM[ 9]
 	vst1.8		{@XMM[0]-@XMM[1]}, [$out]!
 
 	vld1.64		{@XMM[8]}, [r0,:128]		@ next round tweak
 	b		.Lxts_dec_done
 .align	4
 .Lxts_dec_1:
 	mov		r0, sp
 	veor		@XMM[0], @XMM[0], @XMM[8]
 	mov		r1, sp
 	vst1.8		{@XMM[0]}, [sp,:128]
 	mov		r5, $magic			@ preserve magic
 	mov		r2, $key
 	mov		r4, $fp				@ preserve fp
 
 	bl		AES_decrypt
 
 	vld1.8		{@XMM[0]}, [sp,:128]
 	veor		@XMM[0], @XMM[0], @XMM[8]
 	vst1.8		{@XMM[0]}, [$out]!
 	mov		$fp, r4
 	mov		$magic, r5
 
 	vmov		@XMM[8], @XMM[9]		@ next round tweak
 
 .Lxts_dec_done:
 #ifndef	XTS_CHAIN_TWEAK
 	adds		$len, #0x10
 	beq		.Lxts_dec_ret
 
 	@ calculate one round of extra tweak for the stolen ciphertext
 	vldmia		$magic, {$twmask}
 	vshr.s64	@XMM[6], @XMM[8], #63
 	vand		@XMM[6], @XMM[6], $twmask
 	vadd.u64	@XMM[9], @XMM[8], @XMM[8]
 	vswp		`&Dhi("@XMM[6]")`,`&Dlo("@XMM[6]")`
 	veor		@XMM[9], @XMM[9], @XMM[6]
 
 	@ perform the final decryption with the last tweak value
 	vld1.8		{@XMM[0]}, [$inp]!
 	mov		r0, sp
 	veor		@XMM[0], @XMM[0], @XMM[9]
 	mov		r1, sp
 	vst1.8		{@XMM[0]}, [sp,:128]
 	mov		r2, $key
 	mov		r4, $fp			@ preserve fp
 
 	bl		AES_decrypt
 
 	vld1.8		{@XMM[0]}, [sp,:128]
 	veor		@XMM[0], @XMM[0], @XMM[9]
 	vst1.8		{@XMM[0]}, [$out]
 
 	mov		r6, $out
 .Lxts_dec_steal:
 	ldrb		r1, [$out]
 	ldrb		r0, [$inp], #1
 	strb		r1, [$out, #0x10]
 	strb		r0, [$out], #1
 
 	subs		$len, #1
 	bhi		.Lxts_dec_steal
 
 	vld1.8		{@XMM[0]}, [r6]
 	mov		r0, sp
 	veor		@XMM[0], @XMM[8]
 	mov		r1, sp
 	vst1.8		{@XMM[0]}, [sp,:128]
 	mov		r2, $key
 
 	bl		AES_decrypt
 
 	vld1.8		{@XMM[0]}, [sp,:128]
 	veor		@XMM[0], @XMM[0], @XMM[8]
 	vst1.8		{@XMM[0]}, [r6]
 	mov		$fp, r4
 #endif
 
 .Lxts_dec_ret:
 	bic		r0, $fp, #0xf
 	vmov.i32	q0, #0
 	vmov.i32	q1, #0
 #ifdef	XTS_CHAIN_TWEAK
 	ldr		r1, [$fp, #0x20+VFP_ABI_FRAME]	@ chain tweak
 #endif
 .Lxts_dec_bzero:				@ wipe key schedule [if any]
 	vstmia		sp!, {q0-q1}
 	cmp		sp, r0
 	bne		.Lxts_dec_bzero
 
 	mov		sp, $fp
 #ifdef	XTS_CHAIN_TWEAK
 	vst1.8		{@XMM[8]}, [r1]
 #endif
 	VFP_ABI_POP
 	ldmia		sp!, {r4-r10, pc}	@ return
 
 .size	bsaes_xts_decrypt,.-bsaes_xts_decrypt
 ___
 }
 $code.=<<___;
 #endif
 ___
 
 $code =~ s/\`([^\`]*)\`/eval($1)/gem;
 
 open SELF,$0;
 while() {
 	next if (/^#!/);
         last if (!s/^#/@/ and !/^$/);
         print;
 }
 close SELF;
 
 print $code;
 
 close STDOUT;
Index: vendor-crypto/openssl/dist/crypto/asn1/a_bitstr.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/asn1/a_bitstr.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/asn1/a_bitstr.c	(revision 318897)
@@ -1,262 +1,263 @@
 /* crypto/asn1/a_bitstr.c */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 
 #include 
 #include "cryptlib.h"
 #include 
 
 int ASN1_BIT_STRING_set(ASN1_BIT_STRING *x, unsigned char *d, int len)
 {
     return M_ASN1_BIT_STRING_set(x, d, len);
 }
 
 int i2c_ASN1_BIT_STRING(ASN1_BIT_STRING *a, unsigned char **pp)
 {
     int ret, j, bits, len;
     unsigned char *p, *d;
 
     if (a == NULL)
         return (0);
 
     len = a->length;
 
     if (len > 0) {
         if (a->flags & ASN1_STRING_FLAG_BITS_LEFT) {
             bits = (int)a->flags & 0x07;
         } else {
             for (; len > 0; len--) {
                 if (a->data[len - 1])
                     break;
             }
             j = a->data[len - 1];
             if (j & 0x01)
                 bits = 0;
             else if (j & 0x02)
                 bits = 1;
             else if (j & 0x04)
                 bits = 2;
             else if (j & 0x08)
                 bits = 3;
             else if (j & 0x10)
                 bits = 4;
             else if (j & 0x20)
                 bits = 5;
             else if (j & 0x40)
                 bits = 6;
             else if (j & 0x80)
                 bits = 7;
             else
                 bits = 0;       /* should not happen */
         }
     } else
         bits = 0;
 
     ret = 1 + len;
     if (pp == NULL)
         return (ret);
 
     p = *pp;
 
     *(p++) = (unsigned char)bits;
     d = a->data;
-    memcpy(p, d, len);
-    p += len;
-    if (len > 0)
+    if (len > 0) {
+        memcpy(p, d, len);
+        p += len;
         p[-1] &= (0xff << bits);
+    }
     *pp = p;
     return (ret);
 }
 
 ASN1_BIT_STRING *c2i_ASN1_BIT_STRING(ASN1_BIT_STRING **a,
                                      const unsigned char **pp, long len)
 {
     ASN1_BIT_STRING *ret = NULL;
     const unsigned char *p;
     unsigned char *s;
     int i;
 
     if (len < 1) {
         i = ASN1_R_STRING_TOO_SHORT;
         goto err;
     }
 
     if ((a == NULL) || ((*a) == NULL)) {
         if ((ret = M_ASN1_BIT_STRING_new()) == NULL)
             return (NULL);
     } else
         ret = (*a);
 
     p = *pp;
     i = *(p++);
     if (i > 7) {
         i = ASN1_R_INVALID_BIT_STRING_BITS_LEFT;
         goto err;
     }
     /*
      * We do this to preserve the settings.  If we modify the settings, via
      * the _set_bit function, we will recalculate on output
      */
     ret->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07); /* clear */
     ret->flags |= (ASN1_STRING_FLAG_BITS_LEFT | i); /* set */
 
     if (len-- > 1) {            /* using one because of the bits left byte */
         s = (unsigned char *)OPENSSL_malloc((int)len);
         if (s == NULL) {
             i = ERR_R_MALLOC_FAILURE;
             goto err;
         }
         memcpy(s, p, (int)len);
         s[len - 1] &= (0xff << i);
         p += len;
     } else
         s = NULL;
 
     ret->length = (int)len;
     if (ret->data != NULL)
         OPENSSL_free(ret->data);
     ret->data = s;
     ret->type = V_ASN1_BIT_STRING;
     if (a != NULL)
         (*a) = ret;
     *pp = p;
     return (ret);
  err:
     ASN1err(ASN1_F_C2I_ASN1_BIT_STRING, i);
     if ((ret != NULL) && ((a == NULL) || (*a != ret)))
         M_ASN1_BIT_STRING_free(ret);
     return (NULL);
 }
 
 /*
  * These next 2 functions from Goetz Babin-Ebell 
  */
 int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *a, int n, int value)
 {
     int w, v, iv;
     unsigned char *c;
 
     w = n / 8;
     v = 1 << (7 - (n & 0x07));
     iv = ~v;
     if (!value)
         v = 0;
 
     if (a == NULL)
         return 0;
 
     a->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07); /* clear, set on write */
 
     if ((a->length < (w + 1)) || (a->data == NULL)) {
         if (!value)
             return (1);         /* Don't need to set */
         if (a->data == NULL)
             c = (unsigned char *)OPENSSL_malloc(w + 1);
         else
             c = (unsigned char *)OPENSSL_realloc_clean(a->data,
                                                        a->length, w + 1);
         if (c == NULL) {
             ASN1err(ASN1_F_ASN1_BIT_STRING_SET_BIT, ERR_R_MALLOC_FAILURE);
             return 0;
         }
         if (w + 1 - a->length > 0)
             memset(c + a->length, 0, w + 1 - a->length);
         a->data = c;
         a->length = w + 1;
     }
     a->data[w] = ((a->data[w]) & iv) | v;
     while ((a->length > 0) && (a->data[a->length - 1] == 0))
         a->length--;
     return (1);
 }
 
 int ASN1_BIT_STRING_get_bit(ASN1_BIT_STRING *a, int n)
 {
     int w, v;
 
     w = n / 8;
     v = 1 << (7 - (n & 0x07));
     if ((a == NULL) || (a->length < (w + 1)) || (a->data == NULL))
         return (0);
     return ((a->data[w] & v) != 0);
 }
 
 /*
  * Checks if the given bit string contains only bits specified by
  * the flags vector. Returns 0 if there is at least one bit set in 'a'
  * which is not specified in 'flags', 1 otherwise.
  * 'len' is the length of 'flags'.
  */
 int ASN1_BIT_STRING_check(ASN1_BIT_STRING *a,
                           unsigned char *flags, int flags_len)
 {
     int i, ok;
     /* Check if there is one bit set at all. */
     if (!a || !a->data)
         return 1;
 
     /*
      * Check each byte of the internal representation of the bit string.
      */
     ok = 1;
     for (i = 0; i < a->length && ok; ++i) {
         unsigned char mask = i < flags_len ? ~flags[i] : 0xff;
         /* We are done if there is an unneeded bit set. */
         ok = (a->data[i] & mask) == 0;
     }
     return ok;
 }
Index: vendor-crypto/openssl/dist/crypto/asn1/a_digest.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/asn1/a_digest.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/asn1/a_digest.c	(revision 318897)
@@ -1,111 +1,115 @@
 /* crypto/asn1/a_digest.c */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 
 #include 
 #include 
 
 #include "cryptlib.h"
 
 #ifndef NO_SYS_TYPES_H
 # include 
 #endif
 
 #include 
 #include 
 #include 
 #include 
 
 #ifndef NO_ASN1_OLD
 
 int ASN1_digest(i2d_of_void *i2d, const EVP_MD *type, char *data,
                 unsigned char *md, unsigned int *len)
 {
     int i;
     unsigned char *str, *p;
 
     i = i2d(data, NULL);
     if ((str = (unsigned char *)OPENSSL_malloc(i)) == NULL) {
         ASN1err(ASN1_F_ASN1_DIGEST, ERR_R_MALLOC_FAILURE);
         return (0);
     }
     p = str;
     i2d(data, &p);
 
-    if (!EVP_Digest(str, i, md, len, type, NULL))
+    if (!EVP_Digest(str, i, md, len, type, NULL)) {
+        OPENSSL_free(str);
         return 0;
+    }
     OPENSSL_free(str);
     return (1);
 }
 
 #endif
 
 int ASN1_item_digest(const ASN1_ITEM *it, const EVP_MD *type, void *asn,
                      unsigned char *md, unsigned int *len)
 {
     int i;
     unsigned char *str = NULL;
 
     i = ASN1_item_i2d(asn, &str, it);
     if (!str)
         return (0);
 
-    if (!EVP_Digest(str, i, md, len, type, NULL))
+    if (!EVP_Digest(str, i, md, len, type, NULL)) {
+        OPENSSL_free(str);
         return 0;
+    }
     OPENSSL_free(str);
     return (1);
 }
Index: vendor-crypto/openssl/dist/crypto/asn1/a_gentm.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/asn1/a_gentm.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/asn1/a_gentm.c	(revision 318897)
@@ -1,312 +1,312 @@
 /* crypto/asn1/a_gentm.c */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 
 /*
  * GENERALIZEDTIME implementation, written by Steve Henson. Based on UTCTIME
  */
 
 #include 
 #include 
 #include "cryptlib.h"
 #include "o_time.h"
 #include 
 #include "asn1_locl.h"
 
 #if 0
 
 int i2d_ASN1_GENERALIZEDTIME(ASN1_GENERALIZEDTIME *a, unsigned char **pp)
 {
 # ifdef CHARSET_EBCDIC
     /* KLUDGE! We convert to ascii before writing DER */
     int len;
     char tmp[24];
     ASN1_STRING tmpstr = *(ASN1_STRING *)a;
 
     len = tmpstr.length;
     ebcdic2ascii(tmp, tmpstr.data, (len >= sizeof tmp) ? sizeof tmp : len);
     tmpstr.data = tmp;
 
     a = (ASN1_GENERALIZEDTIME *)&tmpstr;
 # endif
     return (i2d_ASN1_bytes((ASN1_STRING *)a, pp,
                            V_ASN1_GENERALIZEDTIME, V_ASN1_UNIVERSAL));
 }
 
 ASN1_GENERALIZEDTIME *d2i_ASN1_GENERALIZEDTIME(ASN1_GENERALIZEDTIME **a,
                                                unsigned char **pp,
                                                long length)
 {
     ASN1_GENERALIZEDTIME *ret = NULL;
 
     ret =
         (ASN1_GENERALIZEDTIME *)d2i_ASN1_bytes((ASN1_STRING **)a, pp, length,
                                                V_ASN1_GENERALIZEDTIME,
                                                V_ASN1_UNIVERSAL);
     if (ret == NULL) {
         ASN1err(ASN1_F_D2I_ASN1_GENERALIZEDTIME, ERR_R_NESTED_ASN1_ERROR);
         return (NULL);
     }
 # ifdef CHARSET_EBCDIC
     ascii2ebcdic(ret->data, ret->data, ret->length);
 # endif
     if (!ASN1_GENERALIZEDTIME_check(ret)) {
         ASN1err(ASN1_F_D2I_ASN1_GENERALIZEDTIME, ASN1_R_INVALID_TIME_FORMAT);
         goto err;
     }
 
     return (ret);
  err:
     if ((ret != NULL) && ((a == NULL) || (*a != ret)))
         M_ASN1_GENERALIZEDTIME_free(ret);
     return (NULL);
 }
 
 #endif
 
 int asn1_generalizedtime_to_tm(struct tm *tm, const ASN1_GENERALIZEDTIME *d)
 {
     static const int min[9] = { 0, 0, 1, 1, 0, 0, 0, 0, 0 };
     static const int max[9] = { 99, 99, 12, 31, 23, 59, 59, 12, 59 };
     char *a;
     int n, i, l, o;
 
     if (d->type != V_ASN1_GENERALIZEDTIME)
         return (0);
     l = d->length;
     a = (char *)d->data;
     o = 0;
     /*
      * GENERALIZEDTIME is similar to UTCTIME except the year is represented
      * as YYYY. This stuff treats everything as a two digit field so make
      * first two fields 00 to 99
      */
     if (l < 13)
         goto err;
     for (i = 0; i < 7; i++) {
         if ((i == 6) && ((a[o] == 'Z') || (a[o] == '+') || (a[o] == '-'))) {
             i++;
             if (tm)
                 tm->tm_sec = 0;
             break;
         }
         if ((a[o] < '0') || (a[o] > '9'))
             goto err;
         n = a[o] - '0';
         if (++o > l)
             goto err;
 
         if ((a[o] < '0') || (a[o] > '9'))
             goto err;
         n = (n * 10) + a[o] - '0';
         if (++o > l)
             goto err;
 
         if ((n < min[i]) || (n > max[i]))
             goto err;
         if (tm) {
             switch (i) {
             case 0:
                 tm->tm_year = n * 100 - 1900;
                 break;
             case 1:
                 tm->tm_year += n;
                 break;
             case 2:
                 tm->tm_mon = n - 1;
                 break;
             case 3:
                 tm->tm_mday = n;
                 break;
             case 4:
                 tm->tm_hour = n;
                 break;
             case 5:
                 tm->tm_min = n;
                 break;
             case 6:
                 tm->tm_sec = n;
                 break;
             }
         }
     }
     /*
      * Optional fractional seconds: decimal point followed by one or more
      * digits.
      */
     if (a[o] == '.') {
         if (++o > l)
             goto err;
         i = o;
         while ((a[o] >= '0') && (a[o] <= '9') && (o <= l))
             o++;
         /* Must have at least one digit after decimal point */
         if (i == o)
             goto err;
     }
 
     if (a[o] == 'Z')
         o++;
     else if ((a[o] == '+') || (a[o] == '-')) {
-        int offsign = a[o] == '-' ? -1 : 1, offset = 0;
+        int offsign = a[o] == '-' ? 1 : -1, offset = 0;
         o++;
         if (o + 4 > l)
             goto err;
         for (i = 7; i < 9; i++) {
             if ((a[o] < '0') || (a[o] > '9'))
                 goto err;
             n = a[o] - '0';
             o++;
             if ((a[o] < '0') || (a[o] > '9'))
                 goto err;
             n = (n * 10) + a[o] - '0';
             if ((n < min[i]) || (n > max[i]))
                 goto err;
             if (tm) {
                 if (i == 7)
                     offset = n * 3600;
                 else if (i == 8)
                     offset += n * 60;
             }
             o++;
         }
         if (offset && !OPENSSL_gmtime_adj(tm, 0, offset * offsign))
             return 0;
     } else if (a[o]) {
         /* Missing time zone information. */
         goto err;
     }
     return (o == l);
  err:
     return (0);
 }
 
 int ASN1_GENERALIZEDTIME_check(const ASN1_GENERALIZEDTIME *d)
 {
     return asn1_generalizedtime_to_tm(NULL, d);
 }
 
 int ASN1_GENERALIZEDTIME_set_string(ASN1_GENERALIZEDTIME *s, const char *str)
 {
     ASN1_GENERALIZEDTIME t;
 
     t.type = V_ASN1_GENERALIZEDTIME;
     t.length = strlen(str);
     t.data = (unsigned char *)str;
     if (ASN1_GENERALIZEDTIME_check(&t)) {
         if (s != NULL) {
             if (!ASN1_STRING_set((ASN1_STRING *)s,
                                  (unsigned char *)str, t.length))
                 return 0;
             s->type = V_ASN1_GENERALIZEDTIME;
         }
         return (1);
     } else
         return (0);
 }
 
 ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_set(ASN1_GENERALIZEDTIME *s,
                                                time_t t)
 {
     return ASN1_GENERALIZEDTIME_adj(s, t, 0, 0);
 }
 
 ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_adj(ASN1_GENERALIZEDTIME *s,
                                                time_t t, int offset_day,
                                                long offset_sec)
 {
     char *p;
     struct tm *ts;
     struct tm data;
     size_t len = 20;
 
     if (s == NULL)
         s = M_ASN1_GENERALIZEDTIME_new();
     if (s == NULL)
         return (NULL);
 
     ts = OPENSSL_gmtime(&t, &data);
     if (ts == NULL)
         return (NULL);
 
     if (offset_day || offset_sec) {
         if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec))
             return NULL;
     }
 
     p = (char *)s->data;
     if ((p == NULL) || ((size_t)s->length < len)) {
         p = OPENSSL_malloc(len);
         if (p == NULL) {
             ASN1err(ASN1_F_ASN1_GENERALIZEDTIME_ADJ, ERR_R_MALLOC_FAILURE);
             return (NULL);
         }
         if (s->data != NULL)
             OPENSSL_free(s->data);
         s->data = (unsigned char *)p;
     }
 
     BIO_snprintf(p, len, "%04d%02d%02d%02d%02d%02dZ", ts->tm_year + 1900,
                  ts->tm_mon + 1, ts->tm_mday, ts->tm_hour, ts->tm_min,
                  ts->tm_sec);
     s->length = strlen(p);
     s->type = V_ASN1_GENERALIZEDTIME;
 #ifdef CHARSET_EBCDIC_not
     ebcdic2ascii(s->data, s->data, s->length);
 #endif
     return (s);
 }
Index: vendor-crypto/openssl/dist/crypto/asn1/a_strnid.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/asn1/a_strnid.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/asn1/a_strnid.c	(revision 318897)
@@ -1,314 +1,315 @@
 /* a_strnid.c */
 /*
  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
  * 1999.
  */
 /* ====================================================================
  * Copyright (c) 1999 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    licensing@OpenSSL.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #include 
 #include 
 #include "cryptlib.h"
 #include 
 #include 
 
 static STACK_OF(ASN1_STRING_TABLE) *stable = NULL;
 static void st_free(ASN1_STRING_TABLE *tbl);
 static int sk_table_cmp(const ASN1_STRING_TABLE *const *a,
                         const ASN1_STRING_TABLE *const *b);
 
 /*
  * This is the global mask for the mbstring functions: this is use to mask
  * out certain types (such as BMPString and UTF8String) because certain
  * software (e.g. Netscape) has problems with them.
  */
 
 static unsigned long global_mask = B_ASN1_UTF8STRING;
 
 void ASN1_STRING_set_default_mask(unsigned long mask)
 {
     global_mask = mask;
 }
 
 unsigned long ASN1_STRING_get_default_mask(void)
 {
     return global_mask;
 }
 
 /*-
  * This function sets the default to various "flavours" of configuration.
  * based on an ASCII string. Currently this is:
  * MASK:XXXX : a numerical mask value.
  * nobmp : Don't use BMPStrings (just Printable, T61).
  * pkix : PKIX recommendation in RFC2459.
  * utf8only : only use UTF8Strings (RFC2459 recommendation for 2004).
  * default:   the default value, Printable, T61, BMP.
  */
 
 int ASN1_STRING_set_default_mask_asc(const char *p)
 {
     unsigned long mask;
     char *end;
     if (!strncmp(p, "MASK:", 5)) {
         if (!p[5])
             return 0;
         mask = strtoul(p + 5, &end, 0);
         if (*end)
             return 0;
     } else if (!strcmp(p, "nombstr"))
         mask = ~((unsigned long)(B_ASN1_BMPSTRING | B_ASN1_UTF8STRING));
     else if (!strcmp(p, "pkix"))
         mask = ~((unsigned long)B_ASN1_T61STRING);
     else if (!strcmp(p, "utf8only"))
         mask = B_ASN1_UTF8STRING;
     else if (!strcmp(p, "default"))
         mask = 0xFFFFFFFFL;
     else
         return 0;
     ASN1_STRING_set_default_mask(mask);
     return 1;
 }
 
 /*
  * The following function generates an ASN1_STRING based on limits in a
  * table. Frequently the types and length of an ASN1_STRING are restricted by
  * a corresponding OID. For example certificates and certificate requests.
  */
 
 ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out,
                                     const unsigned char *in, int inlen,
                                     int inform, int nid)
 {
     ASN1_STRING_TABLE *tbl;
     ASN1_STRING *str = NULL;
     unsigned long mask;
     int ret;
     if (!out)
         out = &str;
     tbl = ASN1_STRING_TABLE_get(nid);
     if (tbl) {
         mask = tbl->mask;
         if (!(tbl->flags & STABLE_NO_MASK))
             mask &= global_mask;
         ret = ASN1_mbstring_ncopy(out, in, inlen, inform, mask,
                                   tbl->minsize, tbl->maxsize);
     } else
         ret =
             ASN1_mbstring_copy(out, in, inlen, inform,
                                DIRSTRING_TYPE & global_mask);
     if (ret <= 0)
         return NULL;
     return *out;
 }
 
 /*
  * Now the tables and helper functions for the string table:
  */
 
 /* size limits: this stuff is taken straight from RFC3280 */
 
 #define ub_name                         32768
 #define ub_common_name                  64
 #define ub_locality_name                128
 #define ub_state_name                   128
 #define ub_organization_name            64
 #define ub_organization_unit_name       64
 #define ub_title                        64
 #define ub_email_address                128
 #define ub_serial_number                64
 
 /* This table must be kept in NID order */
 
 static const ASN1_STRING_TABLE tbl_standard[] = {
     {NID_commonName, 1, ub_common_name, DIRSTRING_TYPE, 0},
     {NID_countryName, 2, 2, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK},
     {NID_localityName, 1, ub_locality_name, DIRSTRING_TYPE, 0},
     {NID_stateOrProvinceName, 1, ub_state_name, DIRSTRING_TYPE, 0},
     {NID_organizationName, 1, ub_organization_name, DIRSTRING_TYPE, 0},
     {NID_organizationalUnitName, 1, ub_organization_unit_name, DIRSTRING_TYPE,
      0},
     {NID_pkcs9_emailAddress, 1, ub_email_address, B_ASN1_IA5STRING,
      STABLE_NO_MASK},
     {NID_pkcs9_unstructuredName, 1, -1, PKCS9STRING_TYPE, 0},
     {NID_pkcs9_challengePassword, 1, -1, PKCS9STRING_TYPE, 0},
     {NID_pkcs9_unstructuredAddress, 1, -1, DIRSTRING_TYPE, 0},
     {NID_givenName, 1, ub_name, DIRSTRING_TYPE, 0},
     {NID_surname, 1, ub_name, DIRSTRING_TYPE, 0},
     {NID_initials, 1, ub_name, DIRSTRING_TYPE, 0},
     {NID_serialNumber, 1, ub_serial_number, B_ASN1_PRINTABLESTRING,
      STABLE_NO_MASK},
     {NID_friendlyName, -1, -1, B_ASN1_BMPSTRING, STABLE_NO_MASK},
     {NID_name, 1, ub_name, DIRSTRING_TYPE, 0},
     {NID_dnQualifier, -1, -1, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK},
     {NID_domainComponent, 1, -1, B_ASN1_IA5STRING, STABLE_NO_MASK},
-    {NID_ms_csp_name, -1, -1, B_ASN1_BMPSTRING, STABLE_NO_MASK}
+    {NID_ms_csp_name, -1, -1, B_ASN1_BMPSTRING, STABLE_NO_MASK},
+    {NID_jurisdictionCountryName, 2, 2, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK}
 };
 
 static int sk_table_cmp(const ASN1_STRING_TABLE *const *a,
                         const ASN1_STRING_TABLE *const *b)
 {
     return (*a)->nid - (*b)->nid;
 }
 
 DECLARE_OBJ_BSEARCH_CMP_FN(ASN1_STRING_TABLE, ASN1_STRING_TABLE, table);
 
 static int table_cmp(const ASN1_STRING_TABLE *a, const ASN1_STRING_TABLE *b)
 {
     return a->nid - b->nid;
 }
 
 IMPLEMENT_OBJ_BSEARCH_CMP_FN(ASN1_STRING_TABLE, ASN1_STRING_TABLE, table);
 
 ASN1_STRING_TABLE *ASN1_STRING_TABLE_get(int nid)
 {
     int idx;
     ASN1_STRING_TABLE *ttmp;
     ASN1_STRING_TABLE fnd;
     fnd.nid = nid;
     ttmp = OBJ_bsearch_table(&fnd, tbl_standard,
                              sizeof(tbl_standard) /
                              sizeof(ASN1_STRING_TABLE));
     if (ttmp)
         return ttmp;
     if (!stable)
         return NULL;
     idx = sk_ASN1_STRING_TABLE_find(stable, &fnd);
     if (idx < 0)
         return NULL;
     return sk_ASN1_STRING_TABLE_value(stable, idx);
 }
 
 int ASN1_STRING_TABLE_add(int nid,
                           long minsize, long maxsize, unsigned long mask,
                           unsigned long flags)
 {
     ASN1_STRING_TABLE *tmp;
     char new_nid = 0;
     flags &= ~STABLE_FLAGS_MALLOC;
     if (!stable)
         stable = sk_ASN1_STRING_TABLE_new(sk_table_cmp);
     if (!stable) {
         ASN1err(ASN1_F_ASN1_STRING_TABLE_ADD, ERR_R_MALLOC_FAILURE);
         return 0;
     }
     if (!(tmp = ASN1_STRING_TABLE_get(nid))) {
         tmp = OPENSSL_malloc(sizeof(ASN1_STRING_TABLE));
         if (!tmp) {
             ASN1err(ASN1_F_ASN1_STRING_TABLE_ADD, ERR_R_MALLOC_FAILURE);
             return 0;
         }
         tmp->flags = flags | STABLE_FLAGS_MALLOC;
         tmp->nid = nid;
         tmp->minsize = tmp->maxsize = -1;
         new_nid = 1;
     } else
         tmp->flags = (tmp->flags & STABLE_FLAGS_MALLOC) | flags;
     if (minsize != -1)
         tmp->minsize = minsize;
     if (maxsize != -1)
         tmp->maxsize = maxsize;
     tmp->mask = mask;
     if (new_nid)
         sk_ASN1_STRING_TABLE_push(stable, tmp);
     return 1;
 }
 
 void ASN1_STRING_TABLE_cleanup(void)
 {
     STACK_OF(ASN1_STRING_TABLE) *tmp;
     tmp = stable;
     if (!tmp)
         return;
     stable = NULL;
     sk_ASN1_STRING_TABLE_pop_free(tmp, st_free);
 }
 
 static void st_free(ASN1_STRING_TABLE *tbl)
 {
     if (tbl->flags & STABLE_FLAGS_MALLOC)
         OPENSSL_free(tbl);
 }
 
 
 IMPLEMENT_STACK_OF(ASN1_STRING_TABLE)
 
 #ifdef STRING_TABLE_TEST
 
 main()
 {
     ASN1_STRING_TABLE *tmp;
     int i, last_nid = -1;
 
     for (tmp = tbl_standard, i = 0;
          i < sizeof(tbl_standard) / sizeof(ASN1_STRING_TABLE); i++, tmp++) {
         if (tmp->nid < last_nid) {
             last_nid = 0;
             break;
         }
         last_nid = tmp->nid;
     }
 
     if (last_nid != 0) {
         printf("Table order OK\n");
         exit(0);
     }
 
     for (tmp = tbl_standard, i = 0;
          i < sizeof(tbl_standard) / sizeof(ASN1_STRING_TABLE); i++, tmp++)
         printf("Index %d, NID %d, Name=%s\n", i, tmp->nid,
                OBJ_nid2ln(tmp->nid));
 
 }
 
 #endif
Index: vendor-crypto/openssl/dist/crypto/asn1/a_time.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/asn1/a_time.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/asn1/a_time.c	(revision 318897)
@@ -1,228 +1,236 @@
 /* crypto/asn1/a_time.c */
 /* ====================================================================
  * Copyright (c) 1999 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    licensing@OpenSSL.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 /*-
  * This is an implementation of the ASN1 Time structure which is:
  *    Time ::= CHOICE {
  *      utcTime        UTCTime,
  *      generalTime    GeneralizedTime }
  * written by Steve Henson.
  */
 
 #include 
 #include 
 #include "cryptlib.h"
 #include "o_time.h"
 #include 
 #include "asn1_locl.h"
 
 IMPLEMENT_ASN1_MSTRING(ASN1_TIME, B_ASN1_TIME)
 
 IMPLEMENT_ASN1_FUNCTIONS(ASN1_TIME)
 
 #if 0
 int i2d_ASN1_TIME(ASN1_TIME *a, unsigned char **pp)
 {
 # ifdef CHARSET_EBCDIC
     /* KLUDGE! We convert to ascii before writing DER */
     char tmp[24];
     ASN1_STRING tmpstr;
 
     if (a->type == V_ASN1_UTCTIME || a->type == V_ASN1_GENERALIZEDTIME) {
         int len;
 
         tmpstr = *(ASN1_STRING *)a;
         len = tmpstr.length;
         ebcdic2ascii(tmp, tmpstr.data,
                      (len >= sizeof tmp) ? sizeof tmp : len);
         tmpstr.data = tmp;
         a = (ASN1_GENERALIZEDTIME *)&tmpstr;
     }
 # endif
     if (a->type == V_ASN1_UTCTIME || a->type == V_ASN1_GENERALIZEDTIME)
         return (i2d_ASN1_bytes((ASN1_STRING *)a, pp,
                                a->type, V_ASN1_UNIVERSAL));
     ASN1err(ASN1_F_I2D_ASN1_TIME, ASN1_R_EXPECTING_A_TIME);
     return -1;
 }
 #endif
 
 ASN1_TIME *ASN1_TIME_set(ASN1_TIME *s, time_t t)
 {
     return ASN1_TIME_adj(s, t, 0, 0);
 }
 
 ASN1_TIME *ASN1_TIME_adj(ASN1_TIME *s, time_t t,
                          int offset_day, long offset_sec)
 {
     struct tm *ts;
     struct tm data;
 
     ts = OPENSSL_gmtime(&t, &data);
     if (ts == NULL) {
         ASN1err(ASN1_F_ASN1_TIME_ADJ, ASN1_R_ERROR_GETTING_TIME);
         return NULL;
     }
     if (offset_day || offset_sec) {
         if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec))
             return NULL;
     }
     if ((ts->tm_year >= 50) && (ts->tm_year < 150))
         return ASN1_UTCTIME_adj(s, t, offset_day, offset_sec);
     return ASN1_GENERALIZEDTIME_adj(s, t, offset_day, offset_sec);
 }
 
 int ASN1_TIME_check(ASN1_TIME *t)
 {
     if (t->type == V_ASN1_GENERALIZEDTIME)
         return ASN1_GENERALIZEDTIME_check(t);
     else if (t->type == V_ASN1_UTCTIME)
         return ASN1_UTCTIME_check(t);
     return 0;
 }
 
 /* Convert an ASN1_TIME structure to GeneralizedTime */
 ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(ASN1_TIME *t,
                                                    ASN1_GENERALIZEDTIME **out)
 {
-    ASN1_GENERALIZEDTIME *ret;
+    ASN1_GENERALIZEDTIME *ret = NULL;
     char *str;
     int newlen;
 
     if (!ASN1_TIME_check(t))
         return NULL;
 
     if (!out || !*out) {
         if (!(ret = ASN1_GENERALIZEDTIME_new()))
-            return NULL;
-        if (out)
-            *out = ret;
-    } else
+            goto err;
+    } else {
         ret = *out;
+    }
 
     /* If already GeneralizedTime just copy across */
     if (t->type == V_ASN1_GENERALIZEDTIME) {
         if (!ASN1_STRING_set(ret, t->data, t->length))
-            return NULL;
-        return ret;
+            goto err;
+        goto done;
     }
 
     /* grow the string */
     if (!ASN1_STRING_set(ret, NULL, t->length + 2))
-        return NULL;
+        goto err;
     /* ASN1_STRING_set() allocated 'len + 1' bytes. */
     newlen = t->length + 2 + 1;
     str = (char *)ret->data;
     /* Work out the century and prepend */
     if (t->data[0] >= '5')
         BUF_strlcpy(str, "19", newlen);
     else
         BUF_strlcpy(str, "20", newlen);
 
     BUF_strlcat(str, (char *)t->data, newlen);
 
-    return ret;
+ done:
+   if (out != NULL && *out == NULL)
+       *out = ret;
+   return ret;
+
+ err:
+    if (out == NULL || *out != ret)
+        ASN1_GENERALIZEDTIME_free(ret);
+    return NULL;
 }
+
 
 int ASN1_TIME_set_string(ASN1_TIME *s, const char *str)
 {
     ASN1_TIME t;
 
     t.length = strlen(str);
     t.data = (unsigned char *)str;
     t.flags = 0;
 
     t.type = V_ASN1_UTCTIME;
 
     if (!ASN1_TIME_check(&t)) {
         t.type = V_ASN1_GENERALIZEDTIME;
         if (!ASN1_TIME_check(&t))
             return 0;
     }
 
     if (s && !ASN1_STRING_copy((ASN1_STRING *)s, (ASN1_STRING *)&t))
         return 0;
 
     return 1;
 }
 
 static int asn1_time_to_tm(struct tm *tm, const ASN1_TIME *t)
 {
     if (t == NULL) {
         time_t now_t;
         time(&now_t);
         if (OPENSSL_gmtime(&now_t, tm))
             return 1;
         return 0;
     }
 
     if (t->type == V_ASN1_UTCTIME)
         return asn1_utctime_to_tm(tm, t);
     else if (t->type == V_ASN1_GENERALIZEDTIME)
         return asn1_generalizedtime_to_tm(tm, t);
 
     return 0;
 }
 
 int ASN1_TIME_diff(int *pday, int *psec,
                    const ASN1_TIME *from, const ASN1_TIME *to)
 {
     struct tm tm_from, tm_to;
     if (!asn1_time_to_tm(&tm_from, from))
         return 0;
     if (!asn1_time_to_tm(&tm_to, to))
         return 0;
     return OPENSSL_gmtime_diff(pday, psec, &tm_from, &tm_to);
 }
Index: vendor-crypto/openssl/dist/crypto/asn1/a_utctm.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/asn1/a_utctm.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/asn1/a_utctm.c	(revision 318897)
@@ -1,352 +1,352 @@
 /* crypto/asn1/a_utctm.c */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 
 #include 
 #include 
 #include "cryptlib.h"
 #include "o_time.h"
 #include 
 #include "asn1_locl.h"
 
 #if 0
 int i2d_ASN1_UTCTIME(ASN1_UTCTIME *a, unsigned char **pp)
 {
 # ifndef CHARSET_EBCDIC
     return (i2d_ASN1_bytes((ASN1_STRING *)a, pp,
                            V_ASN1_UTCTIME, V_ASN1_UNIVERSAL));
 # else
     /* KLUDGE! We convert to ascii before writing DER */
     int len;
     char tmp[24];
     ASN1_STRING x = *(ASN1_STRING *)a;
 
     len = x.length;
     ebcdic2ascii(tmp, x.data, (len >= sizeof tmp) ? sizeof tmp : len);
     x.data = tmp;
     return i2d_ASN1_bytes(&x, pp, V_ASN1_UTCTIME, V_ASN1_UNIVERSAL);
 # endif
 }
 
 ASN1_UTCTIME *d2i_ASN1_UTCTIME(ASN1_UTCTIME **a, unsigned char **pp,
                                long length)
 {
     ASN1_UTCTIME *ret = NULL;
 
     ret = (ASN1_UTCTIME *)d2i_ASN1_bytes((ASN1_STRING **)a, pp, length,
                                          V_ASN1_UTCTIME, V_ASN1_UNIVERSAL);
     if (ret == NULL) {
         ASN1err(ASN1_F_D2I_ASN1_UTCTIME, ERR_R_NESTED_ASN1_ERROR);
         return (NULL);
     }
 # ifdef CHARSET_EBCDIC
     ascii2ebcdic(ret->data, ret->data, ret->length);
 # endif
     if (!ASN1_UTCTIME_check(ret)) {
         ASN1err(ASN1_F_D2I_ASN1_UTCTIME, ASN1_R_INVALID_TIME_FORMAT);
         goto err;
     }
 
     return (ret);
  err:
     if ((ret != NULL) && ((a == NULL) || (*a != ret)))
         M_ASN1_UTCTIME_free(ret);
     return (NULL);
 }
 
 #endif
 
 int asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d)
 {
     static const int min[8] = { 0, 1, 1, 0, 0, 0, 0, 0 };
     static const int max[8] = { 99, 12, 31, 23, 59, 59, 12, 59 };
     char *a;
     int n, i, l, o;
 
     if (d->type != V_ASN1_UTCTIME)
         return (0);
     l = d->length;
     a = (char *)d->data;
     o = 0;
 
     if (l < 11)
         goto err;
     for (i = 0; i < 6; i++) {
         if ((i == 5) && ((a[o] == 'Z') || (a[o] == '+') || (a[o] == '-'))) {
             i++;
             if (tm)
                 tm->tm_sec = 0;
             break;
         }
         if ((a[o] < '0') || (a[o] > '9'))
             goto err;
         n = a[o] - '0';
         if (++o > l)
             goto err;
 
         if ((a[o] < '0') || (a[o] > '9'))
             goto err;
         n = (n * 10) + a[o] - '0';
         if (++o > l)
             goto err;
 
         if ((n < min[i]) || (n > max[i]))
             goto err;
         if (tm) {
             switch (i) {
             case 0:
                 tm->tm_year = n < 50 ? n + 100 : n;
                 break;
             case 1:
                 tm->tm_mon = n - 1;
                 break;
             case 2:
                 tm->tm_mday = n;
                 break;
             case 3:
                 tm->tm_hour = n;
                 break;
             case 4:
                 tm->tm_min = n;
                 break;
             case 5:
                 tm->tm_sec = n;
                 break;
             }
         }
     }
     if (a[o] == 'Z')
         o++;
     else if ((a[o] == '+') || (a[o] == '-')) {
-        int offsign = a[o] == '-' ? -1 : 1, offset = 0;
+        int offsign = a[o] == '-' ? 1 : -1, offset = 0;
         o++;
         if (o + 4 > l)
             goto err;
         for (i = 6; i < 8; i++) {
             if ((a[o] < '0') || (a[o] > '9'))
                 goto err;
             n = a[o] - '0';
             o++;
             if ((a[o] < '0') || (a[o] > '9'))
                 goto err;
             n = (n * 10) + a[o] - '0';
             if ((n < min[i]) || (n > max[i]))
                 goto err;
             if (tm) {
                 if (i == 6)
                     offset = n * 3600;
                 else if (i == 7)
                     offset += n * 60;
             }
             o++;
         }
         if (offset && !OPENSSL_gmtime_adj(tm, 0, offset * offsign))
             return 0;
     }
     return o == l;
  err:
     return 0;
 }
 
 int ASN1_UTCTIME_check(const ASN1_UTCTIME *d)
 {
     return asn1_utctime_to_tm(NULL, d);
 }
 
 int ASN1_UTCTIME_set_string(ASN1_UTCTIME *s, const char *str)
 {
     ASN1_UTCTIME t;
 
     t.type = V_ASN1_UTCTIME;
     t.length = strlen(str);
     t.data = (unsigned char *)str;
     if (ASN1_UTCTIME_check(&t)) {
         if (s != NULL) {
             if (!ASN1_STRING_set((ASN1_STRING *)s,
                                  (unsigned char *)str, t.length))
                 return 0;
             s->type = V_ASN1_UTCTIME;
         }
         return (1);
     } else
         return (0);
 }
 
 ASN1_UTCTIME *ASN1_UTCTIME_set(ASN1_UTCTIME *s, time_t t)
 {
     return ASN1_UTCTIME_adj(s, t, 0, 0);
 }
 
 ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, time_t t,
                                int offset_day, long offset_sec)
 {
     char *p;
     struct tm *ts;
     struct tm data;
     size_t len = 20;
     int free_s = 0;
 
     if (s == NULL) {
         free_s = 1;
         s = M_ASN1_UTCTIME_new();
     }
     if (s == NULL)
         goto err;
 
     ts = OPENSSL_gmtime(&t, &data);
     if (ts == NULL)
         goto err;
 
     if (offset_day || offset_sec) {
         if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec))
             goto err;
     }
 
     if ((ts->tm_year < 50) || (ts->tm_year >= 150))
         goto err;
 
     p = (char *)s->data;
     if ((p == NULL) || ((size_t)s->length < len)) {
         p = OPENSSL_malloc(len);
         if (p == NULL) {
             ASN1err(ASN1_F_ASN1_UTCTIME_ADJ, ERR_R_MALLOC_FAILURE);
             goto err;
         }
         if (s->data != NULL)
             OPENSSL_free(s->data);
         s->data = (unsigned char *)p;
     }
 
     BIO_snprintf(p, len, "%02d%02d%02d%02d%02d%02dZ", ts->tm_year % 100,
                  ts->tm_mon + 1, ts->tm_mday, ts->tm_hour, ts->tm_min,
                  ts->tm_sec);
     s->length = strlen(p);
     s->type = V_ASN1_UTCTIME;
 #ifdef CHARSET_EBCDIC_not
     ebcdic2ascii(s->data, s->data, s->length);
 #endif
     return (s);
  err:
     if (free_s && s)
         M_ASN1_UTCTIME_free(s);
     return NULL;
 }
 
 int ASN1_UTCTIME_cmp_time_t(const ASN1_UTCTIME *s, time_t t)
 {
     struct tm stm, ttm;
     int day, sec;
 
     if (!asn1_utctime_to_tm(&stm, s))
         return -2;
 
     if (!OPENSSL_gmtime(&t, &ttm))
         return -2;
 
     if (!OPENSSL_gmtime_diff(&day, &sec, &ttm, &stm))
         return -2;
 
     if (day > 0)
         return 1;
     if (day < 0)
         return -1;
     if (sec > 0)
         return 1;
     if (sec < 0)
         return -1;
     return 0;
 }
 
 #if 0
 time_t ASN1_UTCTIME_get(const ASN1_UTCTIME *s)
 {
     struct tm tm;
     int offset;
 
     memset(&tm, '\0', sizeof tm);
 
 # define g2(p) (((p)[0]-'0')*10+(p)[1]-'0')
     tm.tm_year = g2(s->data);
     if (tm.tm_year < 50)
         tm.tm_year += 100;
     tm.tm_mon = g2(s->data + 2) - 1;
     tm.tm_mday = g2(s->data + 4);
     tm.tm_hour = g2(s->data + 6);
     tm.tm_min = g2(s->data + 8);
     tm.tm_sec = g2(s->data + 10);
     if (s->data[12] == 'Z')
         offset = 0;
     else {
         offset = g2(s->data + 13) * 60 + g2(s->data + 15);
         if (s->data[12] == '-')
             offset = -offset;
     }
 # undef g2
 
     /*
      * FIXME: mktime assumes the current timezone
      * instead of UTC, and unless we rewrite OpenSSL
      * in Lisp we cannot locally change the timezone
      * without possibly interfering with other parts
      * of the program. timegm, which uses UTC, is
      * non-standard.
      * Also time_t is inappropriate for general
      * UTC times because it may a 32 bit type.
      */
     return mktime(&tm) - offset * 60;
 }
 #endif
Index: vendor-crypto/openssl/dist/crypto/asn1/f_enum.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/asn1/f_enum.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/asn1/f_enum.c	(revision 318897)
@@ -1,203 +1,203 @@
 /* crypto/asn1/f_enum.c */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 
 #include 
 #include "cryptlib.h"
 #include 
 #include 
 
 /* Based on a_int.c: equivalent ENUMERATED functions */
 
 int i2a_ASN1_ENUMERATED(BIO *bp, ASN1_ENUMERATED *a)
 {
     int i, n = 0;
     static const char *h = "0123456789ABCDEF";
     char buf[2];
 
     if (a == NULL)
         return (0);
 
     if (a->length == 0) {
         if (BIO_write(bp, "00", 2) != 2)
             goto err;
         n = 2;
     } else {
         for (i = 0; i < a->length; i++) {
             if ((i != 0) && (i % 35 == 0)) {
                 if (BIO_write(bp, "\\\n", 2) != 2)
                     goto err;
                 n += 2;
             }
             buf[0] = h[((unsigned char)a->data[i] >> 4) & 0x0f];
             buf[1] = h[((unsigned char)a->data[i]) & 0x0f];
             if (BIO_write(bp, buf, 2) != 2)
                 goto err;
             n += 2;
         }
     }
     return (n);
  err:
     return (-1);
 }
 
 int a2i_ASN1_ENUMERATED(BIO *bp, ASN1_ENUMERATED *bs, char *buf, int size)
 {
     int ret = 0;
     int i, j, k, m, n, again, bufsize;
     unsigned char *s = NULL, *sp;
     unsigned char *bufp;
     int num = 0, slen = 0, first = 1;
 
     bs->type = V_ASN1_ENUMERATED;
 
     bufsize = BIO_gets(bp, buf, size);
     for (;;) {
         if (bufsize < 1)
             goto err_sl;
         i = bufsize;
         if (buf[i - 1] == '\n')
             buf[--i] = '\0';
         if (i == 0)
             goto err_sl;
         if (buf[i - 1] == '\r')
             buf[--i] = '\0';
         if (i == 0)
             goto err_sl;
         again = (buf[i - 1] == '\\');
 
         for (j = 0; j < i; j++) {
             if (!(((buf[j] >= '0') && (buf[j] <= '9')) ||
                   ((buf[j] >= 'a') && (buf[j] <= 'f')) ||
                   ((buf[j] >= 'A') && (buf[j] <= 'F')))) {
                 i = j;
                 break;
             }
         }
         buf[i] = '\0';
         /*
          * We have now cleared all the crap off the end of the line
          */
         if (i < 2)
             goto err_sl;
 
         bufp = (unsigned char *)buf;
         if (first) {
             first = 0;
-            if ((bufp[0] == '0') && (buf[1] == '0')) {
+            if ((bufp[0] == '0') && (bufp[1] == '0')) {
                 bufp += 2;
                 i -= 2;
             }
         }
         k = 0;
         i -= again;
         if (i % 2 != 0) {
             ASN1err(ASN1_F_A2I_ASN1_ENUMERATED, ASN1_R_ODD_NUMBER_OF_CHARS);
             goto err;
         }
         i /= 2;
         if (num + i > slen) {
             if (s == NULL)
                 sp = (unsigned char *)OPENSSL_malloc((unsigned int)num +
                                                      i * 2);
             else
                 sp = (unsigned char *)OPENSSL_realloc(s,
                                                       (unsigned int)num +
                                                       i * 2);
             if (sp == NULL) {
                 ASN1err(ASN1_F_A2I_ASN1_ENUMERATED, ERR_R_MALLOC_FAILURE);
                 goto err;
             }
             s = sp;
             slen = num + i * 2;
         }
         for (j = 0; j < i; j++, k += 2) {
             for (n = 0; n < 2; n++) {
                 m = bufp[k + n];
                 if ((m >= '0') && (m <= '9'))
                     m -= '0';
                 else if ((m >= 'a') && (m <= 'f'))
                     m = m - 'a' + 10;
                 else if ((m >= 'A') && (m <= 'F'))
                     m = m - 'A' + 10;
                 else {
                     ASN1err(ASN1_F_A2I_ASN1_ENUMERATED,
                             ASN1_R_NON_HEX_CHARACTERS);
                     goto err;
                 }
                 s[num + j] <<= 4;
                 s[num + j] |= m;
             }
         }
         num += i;
         if (again)
             bufsize = BIO_gets(bp, buf, size);
         else
             break;
     }
     bs->length = num;
     bs->data = s;
     ret = 1;
  err:
     if (0) {
  err_sl:
         ASN1err(ASN1_F_A2I_ASN1_ENUMERATED, ASN1_R_SHORT_LINE);
     }
     if (ret != 1)
         OPENSSL_free(s);
     return (ret);
 }
Index: vendor-crypto/openssl/dist/crypto/asn1/f_int.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/asn1/f_int.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/asn1/f_int.c	(revision 318897)
@@ -1,215 +1,215 @@
 /* crypto/asn1/f_int.c */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 
 #include 
 #include "cryptlib.h"
 #include 
 #include 
 
 int i2a_ASN1_INTEGER(BIO *bp, ASN1_INTEGER *a)
 {
     int i, n = 0;
     static const char *h = "0123456789ABCDEF";
     char buf[2];
 
     if (a == NULL)
         return (0);
 
     if (a->type & V_ASN1_NEG) {
         if (BIO_write(bp, "-", 1) != 1)
             goto err;
         n = 1;
     }
 
     if (a->length == 0) {
         if (BIO_write(bp, "00", 2) != 2)
             goto err;
         n += 2;
     } else {
         for (i = 0; i < a->length; i++) {
             if ((i != 0) && (i % 35 == 0)) {
                 if (BIO_write(bp, "\\\n", 2) != 2)
                     goto err;
                 n += 2;
             }
             buf[0] = h[((unsigned char)a->data[i] >> 4) & 0x0f];
             buf[1] = h[((unsigned char)a->data[i]) & 0x0f];
             if (BIO_write(bp, buf, 2) != 2)
                 goto err;
             n += 2;
         }
     }
     return (n);
  err:
     return (-1);
 }
 
 int a2i_ASN1_INTEGER(BIO *bp, ASN1_INTEGER *bs, char *buf, int size)
 {
     int ret = 0;
     int i, j, k, m, n, again, bufsize;
     unsigned char *s = NULL, *sp;
     unsigned char *bufp;
     int num = 0, slen = 0, first = 1;
 
     bs->type = V_ASN1_INTEGER;
 
     bufsize = BIO_gets(bp, buf, size);
     for (;;) {
         if (bufsize < 1)
             goto err_sl;
         i = bufsize;
         if (buf[i - 1] == '\n')
             buf[--i] = '\0';
         if (i == 0)
             goto err_sl;
         if (buf[i - 1] == '\r')
             buf[--i] = '\0';
         if (i == 0)
             goto err_sl;
         again = (buf[i - 1] == '\\');
 
         for (j = 0; j < i; j++) {
 #ifndef CHARSET_EBCDIC
             if (!(((buf[j] >= '0') && (buf[j] <= '9')) ||
                   ((buf[j] >= 'a') && (buf[j] <= 'f')) ||
                   ((buf[j] >= 'A') && (buf[j] <= 'F'))))
 #else
             /*
              * This #ifdef is not strictly necessary, since the characters
              * A...F a...f 0...9 are contiguous (yes, even in EBCDIC - but
              * not the whole alphabet). Nevertheless, isxdigit() is faster.
              */
             if (!isxdigit(buf[j]))
 #endif
             {
                 i = j;
                 break;
             }
         }
         buf[i] = '\0';
         /*
          * We have now cleared all the crap off the end of the line
          */
         if (i < 2)
             goto err_sl;
 
         bufp = (unsigned char *)buf;
         if (first) {
             first = 0;
-            if ((bufp[0] == '0') && (buf[1] == '0')) {
+            if ((bufp[0] == '0') && (bufp[1] == '0')) {
                 bufp += 2;
                 i -= 2;
             }
         }
         k = 0;
         i -= again;
         if (i % 2 != 0) {
             ASN1err(ASN1_F_A2I_ASN1_INTEGER, ASN1_R_ODD_NUMBER_OF_CHARS);
             goto err;
         }
         i /= 2;
         if (num + i > slen) {
             if (s == NULL)
                 sp = (unsigned char *)OPENSSL_malloc((unsigned int)num +
                                                      i * 2);
             else
                 sp = OPENSSL_realloc_clean(s, slen, num + i * 2);
             if (sp == NULL) {
                 ASN1err(ASN1_F_A2I_ASN1_INTEGER, ERR_R_MALLOC_FAILURE);
                 goto err;
             }
             s = sp;
             slen = num + i * 2;
         }
         for (j = 0; j < i; j++, k += 2) {
             for (n = 0; n < 2; n++) {
                 m = bufp[k + n];
                 if ((m >= '0') && (m <= '9'))
                     m -= '0';
                 else if ((m >= 'a') && (m <= 'f'))
                     m = m - 'a' + 10;
                 else if ((m >= 'A') && (m <= 'F'))
                     m = m - 'A' + 10;
                 else {
                     ASN1err(ASN1_F_A2I_ASN1_INTEGER,
                             ASN1_R_NON_HEX_CHARACTERS);
                     goto err;
                 }
                 s[num + j] <<= 4;
                 s[num + j] |= m;
             }
         }
         num += i;
         if (again)
             bufsize = BIO_gets(bp, buf, size);
         else
             break;
     }
     bs->length = num;
     bs->data = s;
     ret = 1;
  err:
     if (0) {
  err_sl:
         ASN1err(ASN1_F_A2I_ASN1_INTEGER, ASN1_R_SHORT_LINE);
     }
     if (ret != 1)
         OPENSSL_free(s);
     return (ret);
 }
Index: vendor-crypto/openssl/dist/crypto/asn1/tasn_dec.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/asn1/tasn_dec.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/asn1/tasn_dec.c	(revision 318897)
@@ -1,1229 +1,1230 @@
 /* tasn_dec.c */
 /*
  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
  * 2000.
  */
 /* ====================================================================
  * Copyright (c) 2000-2005 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    licensing@OpenSSL.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #include 
 #include 
 #include 
 #include 
 #include 
 #include 
 #include 
 
 static int asn1_check_eoc(const unsigned char **in, long len);
 static int asn1_find_end(const unsigned char **in, long len, char inf);
 
 static int asn1_collect(BUF_MEM *buf, const unsigned char **in, long len,
                         char inf, int tag, int aclass, int depth);
 
 static int collect_data(BUF_MEM *buf, const unsigned char **p, long plen);
 
 static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass,
                            char *inf, char *cst,
                            const unsigned char **in, long len,
                            int exptag, int expclass, char opt, ASN1_TLC *ctx);
 
 static int asn1_template_ex_d2i(ASN1_VALUE **pval,
                                 const unsigned char **in, long len,
                                 const ASN1_TEMPLATE *tt, char opt,
                                 ASN1_TLC *ctx);
 static int asn1_template_noexp_d2i(ASN1_VALUE **val,
                                    const unsigned char **in, long len,
                                    const ASN1_TEMPLATE *tt, char opt,
                                    ASN1_TLC *ctx);
 static int asn1_d2i_ex_primitive(ASN1_VALUE **pval,
                                  const unsigned char **in, long len,
                                  const ASN1_ITEM *it,
                                  int tag, int aclass, char opt,
                                  ASN1_TLC *ctx);
 
 /* Table to convert tags to bit values, used for MSTRING type */
 static const unsigned long tag2bit[32] = {
     /* tags  0 -  3 */
     0, 0, 0, B_ASN1_BIT_STRING,
     /* tags  4- 7 */
     B_ASN1_OCTET_STRING, 0, 0, B_ASN1_UNKNOWN,
     /* tags  8-11 */
     B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN,
     /* tags 12-15 */
     B_ASN1_UTF8STRING, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN,
     /* tags 16-19 */
     B_ASN1_SEQUENCE, 0, B_ASN1_NUMERICSTRING, B_ASN1_PRINTABLESTRING,
     /* tags 20-22 */
     B_ASN1_T61STRING, B_ASN1_VIDEOTEXSTRING, B_ASN1_IA5STRING,
     /* tags 23-24 */
     B_ASN1_UTCTIME, B_ASN1_GENERALIZEDTIME,
     /* tags 25-27 */
     B_ASN1_GRAPHICSTRING, B_ASN1_ISO64STRING, B_ASN1_GENERALSTRING,
     /* tags 28-31 */
     B_ASN1_UNIVERSALSTRING, B_ASN1_UNKNOWN, B_ASN1_BMPSTRING, B_ASN1_UNKNOWN,
 };
 
 unsigned long ASN1_tag2bit(int tag)
 {
     if ((tag < 0) || (tag > 30))
         return 0;
     return tag2bit[tag];
 }
 
 /* Macro to initialize and invalidate the cache */
 
 #define asn1_tlc_clear(c)       if (c) (c)->valid = 0
 /* Version to avoid compiler warning about 'c' always non-NULL */
 #define asn1_tlc_clear_nc(c)    (c)->valid = 0
 
 /*
  * Decode an ASN1 item, this currently behaves just like a standard 'd2i'
  * function. 'in' points to a buffer to read the data from, in future we
  * will have more advanced versions that can input data a piece at a time and
  * this will simply be a special case.
  */
 
 ASN1_VALUE *ASN1_item_d2i(ASN1_VALUE **pval,
                           const unsigned char **in, long len,
                           const ASN1_ITEM *it)
 {
     ASN1_TLC c;
     ASN1_VALUE *ptmpval = NULL;
     if (!pval)
         pval = &ptmpval;
     asn1_tlc_clear_nc(&c);
     if (ASN1_item_ex_d2i(pval, in, len, it, -1, 0, 0, &c) > 0)
         return *pval;
     return NULL;
 }
 
 int ASN1_template_d2i(ASN1_VALUE **pval,
                       const unsigned char **in, long len,
                       const ASN1_TEMPLATE *tt)
 {
     ASN1_TLC c;
     asn1_tlc_clear_nc(&c);
     return asn1_template_ex_d2i(pval, in, len, tt, 0, &c);
 }
 
 /*
  * Decode an item, taking care of IMPLICIT tagging, if any. If 'opt' set and
  * tag mismatch return -1 to handle OPTIONAL
  */
 
 int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
                      const ASN1_ITEM *it,
                      int tag, int aclass, char opt, ASN1_TLC *ctx)
 {
     const ASN1_TEMPLATE *tt, *errtt = NULL;
     const ASN1_COMPAT_FUNCS *cf;
     const ASN1_EXTERN_FUNCS *ef;
     const ASN1_AUX *aux = it->funcs;
     ASN1_aux_cb *asn1_cb;
     const unsigned char *p = NULL, *q;
     unsigned char *wp = NULL;   /* BIG FAT WARNING! BREAKS CONST WHERE USED */
     unsigned char imphack = 0, oclass;
     char seq_eoc, seq_nolen, cst, isopt;
     long tmplen;
     int i;
     int otag;
     int ret = 0;
     ASN1_VALUE **pchptr, *ptmpval;
     int combine = aclass & ASN1_TFLG_COMBINE;
     aclass &= ~ASN1_TFLG_COMBINE;
     if (!pval)
         return 0;
     if (aux && aux->asn1_cb)
         asn1_cb = aux->asn1_cb;
     else
         asn1_cb = 0;
 
     switch (it->itype) {
     case ASN1_ITYPE_PRIMITIVE:
         if (it->templates) {
             /*
              * tagging or OPTIONAL is currently illegal on an item template
              * because the flags can't get passed down. In practice this
              * isn't a problem: we include the relevant flags from the item
              * template in the template itself.
              */
             if ((tag != -1) || opt) {
                 ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
                         ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE);
                 goto err;
             }
             return asn1_template_ex_d2i(pval, in, len,
                                         it->templates, opt, ctx);
         }
         return asn1_d2i_ex_primitive(pval, in, len, it,
                                      tag, aclass, opt, ctx);
         break;
 
     case ASN1_ITYPE_MSTRING:
         p = *in;
         /* Just read in tag and class */
         ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, NULL,
                               &p, len, -1, 0, 1, ctx);
         if (!ret) {
             ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
             goto err;
         }
 
         /* Must be UNIVERSAL class */
         if (oclass != V_ASN1_UNIVERSAL) {
             /* If OPTIONAL, assume this is OK */
             if (opt)
                 return -1;
             ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_NOT_UNIVERSAL);
             goto err;
         }
         /* Check tag matches bit map */
         if (!(ASN1_tag2bit(otag) & it->utype)) {
             /* If OPTIONAL, assume this is OK */
             if (opt)
                 return -1;
             ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_WRONG_TAG);
             goto err;
         }
         return asn1_d2i_ex_primitive(pval, in, len, it, otag, 0, 0, ctx);
 
     case ASN1_ITYPE_EXTERN:
         /* Use new style d2i */
         ef = it->funcs;
         return ef->asn1_ex_d2i(pval, in, len, it, tag, aclass, opt, ctx);
 
     case ASN1_ITYPE_COMPAT:
         /* we must resort to old style evil hackery */
         cf = it->funcs;
 
         /* If OPTIONAL see if it is there */
         if (opt) {
             int exptag;
             p = *in;
             if (tag == -1)
                 exptag = it->utype;
             else
                 exptag = tag;
             /*
              * Don't care about anything other than presence of expected tag
              */
 
             ret = asn1_check_tlen(NULL, NULL, NULL, NULL, NULL,
                                   &p, len, exptag, aclass, 1, ctx);
             if (!ret) {
                 ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
                 goto err;
             }
             if (ret == -1)
                 return -1;
         }
 
         /*
          * This is the old style evil hack IMPLICIT handling: since the
          * underlying code is expecting a tag and class other than the one
          * present we change the buffer temporarily then change it back
          * afterwards. This doesn't and never did work for tags > 30. Yes
          * this is *horrible* but it is only needed for old style d2i which
          * will hopefully not be around for much longer. FIXME: should copy
          * the buffer then modify it so the input buffer can be const: we
          * should *always* copy because the old style d2i might modify the
          * buffer.
          */
 
         if (tag != -1) {
             wp = *(unsigned char **)in;
             imphack = *wp;
             if (p == NULL) {
                 ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
                 goto err;
             }
             *wp = (unsigned char)((*p & V_ASN1_CONSTRUCTED)
                                   | it->utype);
         }
 
         ptmpval = cf->asn1_d2i(pval, in, len);
 
         if (tag != -1)
             *wp = imphack;
 
         if (ptmpval)
             return 1;
 
         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
         goto err;
 
     case ASN1_ITYPE_CHOICE:
         if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))
             goto auxerr;
         if (*pval) {
             /* Free up and zero CHOICE value if initialised */
             i = asn1_get_choice_selector(pval, it);
             if ((i >= 0) && (i < it->tcount)) {
                 tt = it->templates + i;
                 pchptr = asn1_get_field_ptr(pval, tt);
                 ASN1_template_free(pchptr, tt);
                 asn1_set_choice_selector(pval, -1, it);
             }
         } else if (!ASN1_item_ex_new(pval, it)) {
             ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
             goto err;
         }
         /* CHOICE type, try each possibility in turn */
         p = *in;
         for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
             pchptr = asn1_get_field_ptr(pval, tt);
             /*
              * We mark field as OPTIONAL so its absence can be recognised.
              */
             ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, ctx);
             /* If field not present, try the next one */
             if (ret == -1)
                 continue;
             /* If positive return, read OK, break loop */
             if (ret > 0)
                 break;
             /* Otherwise must be an ASN1 parsing error */
             errtt = tt;
             ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
             goto err;
         }
 
         /* Did we fall off the end without reading anything? */
         if (i == it->tcount) {
             /* If OPTIONAL, this is OK */
             if (opt) {
                 /* Free and zero it */
                 ASN1_item_ex_free(pval, it);
                 return -1;
             }
             ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_NO_MATCHING_CHOICE_TYPE);
             goto err;
         }
 
         asn1_set_choice_selector(pval, i, it);
         if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL))
             goto auxerr;
         *in = p;
         return 1;
 
     case ASN1_ITYPE_NDEF_SEQUENCE:
     case ASN1_ITYPE_SEQUENCE:
         p = *in;
         tmplen = len;
 
         /* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */
         if (tag == -1) {
             tag = V_ASN1_SEQUENCE;
             aclass = V_ASN1_UNIVERSAL;
         }
         /* Get SEQUENCE length and update len, p */
         ret = asn1_check_tlen(&len, NULL, NULL, &seq_eoc, &cst,
                               &p, len, tag, aclass, opt, ctx);
         if (!ret) {
             ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
             goto err;
         } else if (ret == -1)
             return -1;
         if (aux && (aux->flags & ASN1_AFLG_BROKEN)) {
             len = tmplen - (p - *in);
             seq_nolen = 1;
         }
         /* If indefinite we don't do a length check */
         else
             seq_nolen = seq_eoc;
         if (!cst) {
             ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_NOT_CONSTRUCTED);
             goto err;
         }
 
         if (!*pval && !ASN1_item_ex_new(pval, it)) {
             ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
             goto err;
         }
 
         if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))
             goto auxerr;
 
         /* Free up and zero any ADB found */
         for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
             if (tt->flags & ASN1_TFLG_ADB_MASK) {
                 const ASN1_TEMPLATE *seqtt;
                 ASN1_VALUE **pseqval;
                 seqtt = asn1_do_adb(pval, tt, 0);
                 if (seqtt == NULL)
                     continue;
                 pseqval = asn1_get_field_ptr(pval, seqtt);
                 ASN1_template_free(pseqval, seqtt);
             }
         }
 
         /* Get each field entry */
         for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
             const ASN1_TEMPLATE *seqtt;
             ASN1_VALUE **pseqval;
             seqtt = asn1_do_adb(pval, tt, 1);
             if (seqtt == NULL)
                 goto err;
             pseqval = asn1_get_field_ptr(pval, seqtt);
             /* Have we ran out of data? */
             if (!len)
                 break;
             q = p;
             if (asn1_check_eoc(&p, len)) {
                 if (!seq_eoc) {
                     ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_UNEXPECTED_EOC);
                     goto err;
                 }
                 len -= p - q;
                 seq_eoc = 0;
                 q = p;
                 break;
             }
             /*
              * This determines the OPTIONAL flag value. The field cannot be
              * omitted if it is the last of a SEQUENCE and there is still
              * data to be read. This isn't strictly necessary but it
              * increases efficiency in some cases.
              */
             if (i == (it->tcount - 1))
                 isopt = 0;
             else
                 isopt = (char)(seqtt->flags & ASN1_TFLG_OPTIONAL);
             /*
              * attempt to read in field, allowing each to be OPTIONAL
              */
 
             ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, ctx);
             if (!ret) {
                 errtt = seqtt;
                 goto err;
             } else if (ret == -1) {
                 /*
                  * OPTIONAL component absent. Free and zero the field.
                  */
                 ASN1_template_free(pseqval, seqtt);
                 continue;
             }
             /* Update length */
             len -= p - q;
         }
 
         /* Check for EOC if expecting one */
         if (seq_eoc && !asn1_check_eoc(&p, len)) {
             ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MISSING_EOC);
             goto err;
         }
         /* Check all data read */
         if (!seq_nolen && len) {
             ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_LENGTH_MISMATCH);
             goto err;
         }
 
         /*
          * If we get here we've got no more data in the SEQUENCE, however we
          * may not have read all fields so check all remaining are OPTIONAL
          * and clear any that are.
          */
         for (; i < it->tcount; tt++, i++) {
             const ASN1_TEMPLATE *seqtt;
             seqtt = asn1_do_adb(pval, tt, 1);
             if (seqtt == NULL)
                 goto err;
             if (seqtt->flags & ASN1_TFLG_OPTIONAL) {
                 ASN1_VALUE **pseqval;
                 pseqval = asn1_get_field_ptr(pval, seqtt);
                 ASN1_template_free(pseqval, seqtt);
             } else {
                 errtt = seqtt;
                 ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_FIELD_MISSING);
                 goto err;
             }
         }
         /* Save encoding */
         if (!asn1_enc_save(pval, *in, p - *in, it))
             goto auxerr;
         if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL))
             goto auxerr;
         *in = p;
         return 1;
 
     default:
         return 0;
     }
  auxerr:
     ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_AUX_ERROR);
  err:
     if (combine == 0)
         ASN1_item_ex_free(pval, it);
     if (errtt)
         ERR_add_error_data(4, "Field=", errtt->field_name,
                            ", Type=", it->sname);
     else
         ERR_add_error_data(2, "Type=", it->sname);
     return 0;
 }
 
 /*
  * Templates are handled with two separate functions. One handles any
  * EXPLICIT tag and the other handles the rest.
  */
 
 static int asn1_template_ex_d2i(ASN1_VALUE **val,
                                 const unsigned char **in, long inlen,
                                 const ASN1_TEMPLATE *tt, char opt,
                                 ASN1_TLC *ctx)
 {
     int flags, aclass;
     int ret;
     long len;
     const unsigned char *p, *q;
     char exp_eoc;
     if (!val)
         return 0;
     flags = tt->flags;
     aclass = flags & ASN1_TFLG_TAG_CLASS;
 
     p = *in;
 
     /* Check if EXPLICIT tag expected */
     if (flags & ASN1_TFLG_EXPTAG) {
         char cst;
         /*
          * Need to work out amount of data available to the inner content and
          * where it starts: so read in EXPLICIT header to get the info.
          */
         ret = asn1_check_tlen(&len, NULL, NULL, &exp_eoc, &cst,
                               &p, inlen, tt->tag, aclass, opt, ctx);
         q = p;
         if (!ret) {
             ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
             return 0;
         } else if (ret == -1)
             return -1;
         if (!cst) {
             ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I,
                     ASN1_R_EXPLICIT_TAG_NOT_CONSTRUCTED);
             return 0;
         }
         /* We've found the field so it can't be OPTIONAL now */
         ret = asn1_template_noexp_d2i(val, &p, len, tt, 0, ctx);
         if (!ret) {
             ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
             return 0;
         }
         /* We read the field in OK so update length */
         len -= p - q;
         if (exp_eoc) {
             /* If NDEF we must have an EOC here */
             if (!asn1_check_eoc(&p, len)) {
                 ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I, ASN1_R_MISSING_EOC);
                 goto err;
             }
         } else {
             /*
              * Otherwise we must hit the EXPLICIT tag end or its an error
              */
             if (len) {
                 ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I,
                         ASN1_R_EXPLICIT_LENGTH_MISMATCH);
                 goto err;
             }
         }
     } else
         return asn1_template_noexp_d2i(val, in, inlen, tt, opt, ctx);
 
     *in = p;
     return 1;
 
  err:
     ASN1_template_free(val, tt);
     return 0;
 }
 
 static int asn1_template_noexp_d2i(ASN1_VALUE **val,
                                    const unsigned char **in, long len,
                                    const ASN1_TEMPLATE *tt, char opt,
                                    ASN1_TLC *ctx)
 {
     int flags, aclass;
     int ret;
     const unsigned char *p, *q;
     if (!val)
         return 0;
     flags = tt->flags;
     aclass = flags & ASN1_TFLG_TAG_CLASS;
 
     p = *in;
     q = p;
 
     if (flags & ASN1_TFLG_SK_MASK) {
         /* SET OF, SEQUENCE OF */
         int sktag, skaclass;
         char sk_eoc;
         /* First work out expected inner tag value */
         if (flags & ASN1_TFLG_IMPTAG) {
             sktag = tt->tag;
             skaclass = aclass;
         } else {
             skaclass = V_ASN1_UNIVERSAL;
             if (flags & ASN1_TFLG_SET_OF)
                 sktag = V_ASN1_SET;
             else
                 sktag = V_ASN1_SEQUENCE;
         }
         /* Get the tag */
         ret = asn1_check_tlen(&len, NULL, NULL, &sk_eoc, NULL,
                               &p, len, sktag, skaclass, opt, ctx);
         if (!ret) {
             ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_NESTED_ASN1_ERROR);
             return 0;
         } else if (ret == -1)
             return -1;
         if (!*val)
             *val = (ASN1_VALUE *)sk_new_null();
         else {
             /*
              * We've got a valid STACK: free up any items present
              */
             STACK_OF(ASN1_VALUE) *sktmp = (STACK_OF(ASN1_VALUE) *)*val;
             ASN1_VALUE *vtmp;
             while (sk_ASN1_VALUE_num(sktmp) > 0) {
                 vtmp = sk_ASN1_VALUE_pop(sktmp);
                 ASN1_item_ex_free(&vtmp, ASN1_ITEM_ptr(tt->item));
             }
         }
 
         if (!*val) {
             ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_MALLOC_FAILURE);
             goto err;
         }
 
         /* Read as many items as we can */
         while (len > 0) {
             ASN1_VALUE *skfield;
             q = p;
             /* See if EOC found */
             if (asn1_check_eoc(&p, len)) {
                 if (!sk_eoc) {
                     ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I,
                             ASN1_R_UNEXPECTED_EOC);
                     goto err;
                 }
                 len -= p - q;
                 sk_eoc = 0;
                 break;
             }
             skfield = NULL;
             if (!ASN1_item_ex_d2i(&skfield, &p, len,
                                   ASN1_ITEM_ptr(tt->item), -1, 0, 0, ctx)) {
                 ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I,
                         ERR_R_NESTED_ASN1_ERROR);
                 goto err;
             }
             len -= p - q;
             if (!sk_ASN1_VALUE_push((STACK_OF(ASN1_VALUE) *)*val, skfield)) {
+                ASN1_item_ex_free(&skfield, ASN1_ITEM_ptr(tt->item));
                 ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_MALLOC_FAILURE);
                 goto err;
             }
         }
         if (sk_eoc) {
             ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ASN1_R_MISSING_EOC);
             goto err;
         }
     } else if (flags & ASN1_TFLG_IMPTAG) {
         /* IMPLICIT tagging */
         ret = ASN1_item_ex_d2i(val, &p, len,
                                ASN1_ITEM_ptr(tt->item), tt->tag, aclass, opt,
                                ctx);
         if (!ret) {
             ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_NESTED_ASN1_ERROR);
             goto err;
         } else if (ret == -1)
             return -1;
     } else {
         /* Nothing special */
         ret = ASN1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item),
                                -1, tt->flags & ASN1_TFLG_COMBINE, opt, ctx);
         if (!ret) {
             ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_NESTED_ASN1_ERROR);
             goto err;
         } else if (ret == -1)
             return -1;
     }
 
     *in = p;
     return 1;
 
  err:
     ASN1_template_free(val, tt);
     return 0;
 }
 
 static int asn1_d2i_ex_primitive(ASN1_VALUE **pval,
                                  const unsigned char **in, long inlen,
                                  const ASN1_ITEM *it,
                                  int tag, int aclass, char opt, ASN1_TLC *ctx)
 {
     int ret = 0, utype;
     long plen;
     char cst, inf, free_cont = 0;
     const unsigned char *p;
     BUF_MEM buf = { 0, NULL, 0 };
     const unsigned char *cont = NULL;
     long len;
     if (!pval) {
         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_ILLEGAL_NULL);
         return 0;               /* Should never happen */
     }
 
     if (it->itype == ASN1_ITYPE_MSTRING) {
         utype = tag;
         tag = -1;
     } else
         utype = it->utype;
 
     if (utype == V_ASN1_ANY) {
         /* If type is ANY need to figure out type from tag */
         unsigned char oclass;
         if (tag >= 0) {
             ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_ILLEGAL_TAGGED_ANY);
             return 0;
         }
         if (opt) {
             ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE,
                     ASN1_R_ILLEGAL_OPTIONAL_ANY);
             return 0;
         }
         p = *in;
         ret = asn1_check_tlen(NULL, &utype, &oclass, NULL, NULL,
                               &p, inlen, -1, 0, 0, ctx);
         if (!ret) {
             ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_NESTED_ASN1_ERROR);
             return 0;
         }
         if (oclass != V_ASN1_UNIVERSAL)
             utype = V_ASN1_OTHER;
     }
     if (tag == -1) {
         tag = utype;
         aclass = V_ASN1_UNIVERSAL;
     }
     p = *in;
     /* Check header */
     ret = asn1_check_tlen(&plen, NULL, NULL, &inf, &cst,
                           &p, inlen, tag, aclass, opt, ctx);
     if (!ret) {
         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_NESTED_ASN1_ERROR);
         return 0;
     } else if (ret == -1)
         return -1;
     ret = 0;
     /* SEQUENCE, SET and "OTHER" are left in encoded form */
     if ((utype == V_ASN1_SEQUENCE)
         || (utype == V_ASN1_SET) || (utype == V_ASN1_OTHER)) {
         /*
          * Clear context cache for type OTHER because the auto clear when we
          * have a exact match wont work
          */
         if (utype == V_ASN1_OTHER) {
             asn1_tlc_clear(ctx);
         }
         /* SEQUENCE and SET must be constructed */
         else if (!cst) {
             ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE,
                     ASN1_R_TYPE_NOT_CONSTRUCTED);
             return 0;
         }
 
         cont = *in;
         /* If indefinite length constructed find the real end */
         if (inf) {
             if (!asn1_find_end(&p, plen, inf))
                 goto err;
             len = p - cont;
         } else {
             len = p - cont + plen;
             p += plen;
         }
     } else if (cst) {
         if (utype == V_ASN1_NULL || utype == V_ASN1_BOOLEAN
             || utype == V_ASN1_OBJECT || utype == V_ASN1_INTEGER
             || utype == V_ASN1_ENUMERATED) {
             ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_TYPE_NOT_PRIMITIVE);
             return 0;
         }
 
         /* Free any returned 'buf' content */
         free_cont = 1;
         /*
          * Should really check the internal tags are correct but some things
          * may get this wrong. The relevant specs say that constructed string
          * types should be OCTET STRINGs internally irrespective of the type.
          * So instead just check for UNIVERSAL class and ignore the tag.
          */
         if (!asn1_collect(&buf, &p, plen, inf, -1, V_ASN1_UNIVERSAL, 0)) {
             goto err;
         }
         len = buf.length;
         /* Append a final null to string */
         if (!BUF_MEM_grow_clean(&buf, len + 1)) {
             ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_MALLOC_FAILURE);
             goto err;
         }
         buf.data[len] = 0;
         cont = (const unsigned char *)buf.data;
     } else {
         cont = p;
         len = plen;
         p += plen;
     }
 
     /* We now have content length and type: translate into a structure */
     /* asn1_ex_c2i may reuse allocated buffer, and so sets free_cont to 0 */
     if (!asn1_ex_c2i(pval, cont, len, utype, &free_cont, it))
         goto err;
 
     *in = p;
     ret = 1;
  err:
     if (free_cont && buf.data)
         OPENSSL_free(buf.data);
     return ret;
 }
 
 /* Translate ASN1 content octets into a structure */
 
 int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
                 int utype, char *free_cont, const ASN1_ITEM *it)
 {
     ASN1_VALUE **opval = NULL;
     ASN1_STRING *stmp;
     ASN1_TYPE *typ = NULL;
     int ret = 0;
     const ASN1_PRIMITIVE_FUNCS *pf;
     ASN1_INTEGER **tint;
     pf = it->funcs;
 
     if (pf && pf->prim_c2i)
         return pf->prim_c2i(pval, cont, len, utype, free_cont, it);
     /* If ANY type clear type and set pointer to internal value */
     if (it->utype == V_ASN1_ANY) {
         if (!*pval) {
             typ = ASN1_TYPE_new();
             if (typ == NULL)
                 goto err;
             *pval = (ASN1_VALUE *)typ;
         } else
             typ = (ASN1_TYPE *)*pval;
 
         if (utype != typ->type)
             ASN1_TYPE_set(typ, utype, NULL);
         opval = pval;
         pval = &typ->value.asn1_value;
     }
     switch (utype) {
     case V_ASN1_OBJECT:
         if (!c2i_ASN1_OBJECT((ASN1_OBJECT **)pval, &cont, len))
             goto err;
         break;
 
     case V_ASN1_NULL:
         if (len) {
             ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_NULL_IS_WRONG_LENGTH);
             goto err;
         }
         *pval = (ASN1_VALUE *)1;
         break;
 
     case V_ASN1_BOOLEAN:
         if (len != 1) {
             ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_BOOLEAN_IS_WRONG_LENGTH);
             goto err;
         } else {
             ASN1_BOOLEAN *tbool;
             tbool = (ASN1_BOOLEAN *)pval;
             *tbool = *cont;
         }
         break;
 
     case V_ASN1_BIT_STRING:
         if (!c2i_ASN1_BIT_STRING((ASN1_BIT_STRING **)pval, &cont, len))
             goto err;
         break;
 
     case V_ASN1_INTEGER:
     case V_ASN1_ENUMERATED:
         tint = (ASN1_INTEGER **)pval;
         if (!c2i_ASN1_INTEGER(tint, &cont, len))
             goto err;
         /* Fixup type to match the expected form */
         (*tint)->type = utype | ((*tint)->type & V_ASN1_NEG);
         break;
 
     case V_ASN1_OCTET_STRING:
     case V_ASN1_NUMERICSTRING:
     case V_ASN1_PRINTABLESTRING:
     case V_ASN1_T61STRING:
     case V_ASN1_VIDEOTEXSTRING:
     case V_ASN1_IA5STRING:
     case V_ASN1_UTCTIME:
     case V_ASN1_GENERALIZEDTIME:
     case V_ASN1_GRAPHICSTRING:
     case V_ASN1_VISIBLESTRING:
     case V_ASN1_GENERALSTRING:
     case V_ASN1_UNIVERSALSTRING:
     case V_ASN1_BMPSTRING:
     case V_ASN1_UTF8STRING:
     case V_ASN1_OTHER:
     case V_ASN1_SET:
     case V_ASN1_SEQUENCE:
     default:
         if (utype == V_ASN1_BMPSTRING && (len & 1)) {
             ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_BMPSTRING_IS_WRONG_LENGTH);
             goto err;
         }
         if (utype == V_ASN1_UNIVERSALSTRING && (len & 3)) {
             ASN1err(ASN1_F_ASN1_EX_C2I,
                     ASN1_R_UNIVERSALSTRING_IS_WRONG_LENGTH);
             goto err;
         }
         /* All based on ASN1_STRING and handled the same */
         if (!*pval) {
             stmp = ASN1_STRING_type_new(utype);
             if (!stmp) {
                 ASN1err(ASN1_F_ASN1_EX_C2I, ERR_R_MALLOC_FAILURE);
                 goto err;
             }
             *pval = (ASN1_VALUE *)stmp;
         } else {
             stmp = (ASN1_STRING *)*pval;
             stmp->type = utype;
         }
         /* If we've already allocated a buffer use it */
         if (*free_cont) {
             if (stmp->data)
                 OPENSSL_free(stmp->data);
             stmp->data = (unsigned char *)cont; /* UGLY CAST! RL */
             stmp->length = len;
             *free_cont = 0;
         } else {
             if (!ASN1_STRING_set(stmp, cont, len)) {
                 ASN1err(ASN1_F_ASN1_EX_C2I, ERR_R_MALLOC_FAILURE);
                 ASN1_STRING_free(stmp);
                 *pval = NULL;
                 goto err;
             }
         }
         break;
     }
     /* If ASN1_ANY and NULL type fix up value */
     if (typ && (utype == V_ASN1_NULL))
         typ->value.ptr = NULL;
 
     ret = 1;
  err:
     if (!ret) {
         ASN1_TYPE_free(typ);
         if (opval)
             *opval = NULL;
     }
     return ret;
 }
 
 /*
  * This function finds the end of an ASN1 structure when passed its maximum
  * length, whether it is indefinite length and a pointer to the content. This
  * is more efficient than calling asn1_collect because it does not recurse on
  * each indefinite length header.
  */
 
 static int asn1_find_end(const unsigned char **in, long len, char inf)
 {
     int expected_eoc;
     long plen;
     const unsigned char *p = *in, *q;
     /* If not indefinite length constructed just add length */
     if (inf == 0) {
         *in += len;
         return 1;
     }
     expected_eoc = 1;
     /*
      * Indefinite length constructed form. Find the end when enough EOCs are
      * found. If more indefinite length constructed headers are encountered
      * increment the expected eoc count otherwise just skip to the end of the
      * data.
      */
     while (len > 0) {
         if (asn1_check_eoc(&p, len)) {
             expected_eoc--;
             if (expected_eoc == 0)
                 break;
             len -= 2;
             continue;
         }
         q = p;
         /* Just read in a header: only care about the length */
         if (!asn1_check_tlen(&plen, NULL, NULL, &inf, NULL, &p, len,
                              -1, 0, 0, NULL)) {
             ASN1err(ASN1_F_ASN1_FIND_END, ERR_R_NESTED_ASN1_ERROR);
             return 0;
         }
         if (inf)
             expected_eoc++;
         else
             p += plen;
         len -= p - q;
     }
     if (expected_eoc) {
         ASN1err(ASN1_F_ASN1_FIND_END, ASN1_R_MISSING_EOC);
         return 0;
     }
     *in = p;
     return 1;
 }
 
 /*
  * This function collects the asn1 data from a constructred string type into
  * a buffer. The values of 'in' and 'len' should refer to the contents of the
  * constructed type and 'inf' should be set if it is indefinite length.
  */
 
 #ifndef ASN1_MAX_STRING_NEST
 /*
  * This determines how many levels of recursion are permitted in ASN1 string
  * types. If it is not limited stack overflows can occur. If set to zero no
  * recursion is allowed at all. Although zero should be adequate examples
  * exist that require a value of 1. So 5 should be more than enough.
  */
 # define ASN1_MAX_STRING_NEST 5
 #endif
 
 static int asn1_collect(BUF_MEM *buf, const unsigned char **in, long len,
                         char inf, int tag, int aclass, int depth)
 {
     const unsigned char *p, *q;
     long plen;
     char cst, ininf;
     p = *in;
     inf &= 1;
     /*
      * If no buffer and not indefinite length constructed just pass over the
      * encoded data
      */
     if (!buf && !inf) {
         *in += len;
         return 1;
     }
     while (len > 0) {
         q = p;
         /* Check for EOC */
         if (asn1_check_eoc(&p, len)) {
             /*
              * EOC is illegal outside indefinite length constructed form
              */
             if (!inf) {
                 ASN1err(ASN1_F_ASN1_COLLECT, ASN1_R_UNEXPECTED_EOC);
                 return 0;
             }
             inf = 0;
             break;
         }
 
         if (!asn1_check_tlen(&plen, NULL, NULL, &ininf, &cst, &p,
                              len, tag, aclass, 0, NULL)) {
             ASN1err(ASN1_F_ASN1_COLLECT, ERR_R_NESTED_ASN1_ERROR);
             return 0;
         }
 
         /* If indefinite length constructed update max length */
         if (cst) {
             if (depth >= ASN1_MAX_STRING_NEST) {
                 ASN1err(ASN1_F_ASN1_COLLECT, ASN1_R_NESTED_ASN1_STRING);
                 return 0;
             }
             if (!asn1_collect(buf, &p, plen, ininf, tag, aclass, depth + 1))
                 return 0;
         } else if (plen && !collect_data(buf, &p, plen))
             return 0;
         len -= p - q;
     }
     if (inf) {
         ASN1err(ASN1_F_ASN1_COLLECT, ASN1_R_MISSING_EOC);
         return 0;
     }
     *in = p;
     return 1;
 }
 
 static int collect_data(BUF_MEM *buf, const unsigned char **p, long plen)
 {
     int len;
     if (buf) {
         len = buf->length;
         if (!BUF_MEM_grow_clean(buf, len + plen)) {
             ASN1err(ASN1_F_COLLECT_DATA, ERR_R_MALLOC_FAILURE);
             return 0;
         }
         memcpy(buf->data + len, *p, plen);
     }
     *p += plen;
     return 1;
 }
 
 /* Check for ASN1 EOC and swallow it if found */
 
 static int asn1_check_eoc(const unsigned char **in, long len)
 {
     const unsigned char *p;
     if (len < 2)
         return 0;
     p = *in;
     if (!p[0] && !p[1]) {
         *in += 2;
         return 1;
     }
     return 0;
 }
 
 /*
  * Check an ASN1 tag and length: a bit like ASN1_get_object but it sets the
  * length for indefinite length constructed form, we don't know the exact
  * length but we can set an upper bound to the amount of data available minus
  * the header length just read.
  */
 
 static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass,
                            char *inf, char *cst,
                            const unsigned char **in, long len,
                            int exptag, int expclass, char opt, ASN1_TLC *ctx)
 {
     int i;
     int ptag, pclass;
     long plen;
     const unsigned char *p, *q;
     p = *in;
     q = p;
 
     if (ctx && ctx->valid) {
         i = ctx->ret;
         plen = ctx->plen;
         pclass = ctx->pclass;
         ptag = ctx->ptag;
         p += ctx->hdrlen;
     } else {
         i = ASN1_get_object(&p, &plen, &ptag, &pclass, len);
         if (ctx) {
             ctx->ret = i;
             ctx->plen = plen;
             ctx->pclass = pclass;
             ctx->ptag = ptag;
             ctx->hdrlen = p - q;
             ctx->valid = 1;
             /*
              * If definite length, and no error, length + header can't exceed
              * total amount of data available.
              */
             if (!(i & 0x81) && ((plen + ctx->hdrlen) > len)) {
                 ASN1err(ASN1_F_ASN1_CHECK_TLEN, ASN1_R_TOO_LONG);
                 asn1_tlc_clear(ctx);
                 return 0;
             }
         }
     }
 
     if (i & 0x80) {
         ASN1err(ASN1_F_ASN1_CHECK_TLEN, ASN1_R_BAD_OBJECT_HEADER);
         asn1_tlc_clear(ctx);
         return 0;
     }
     if (exptag >= 0) {
         if ((exptag != ptag) || (expclass != pclass)) {
             /*
              * If type is OPTIONAL, not an error: indicate missing type.
              */
             if (opt)
                 return -1;
             asn1_tlc_clear(ctx);
             ASN1err(ASN1_F_ASN1_CHECK_TLEN, ASN1_R_WRONG_TAG);
             return 0;
         }
         /*
          * We have a tag and class match: assume we are going to do something
          * with it
          */
         asn1_tlc_clear(ctx);
     }
 
     if (i & 1)
         plen = len - (p - q);
 
     if (inf)
         *inf = i & 1;
 
     if (cst)
         *cst = i & V_ASN1_CONSTRUCTED;
 
     if (olen)
         *olen = plen;
 
     if (oclass)
         *oclass = pclass;
 
     if (otag)
         *otag = ptag;
 
     *in = p;
     return 1;
 }
Index: vendor-crypto/openssl/dist/crypto/asn1/tasn_new.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/asn1/tasn_new.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/asn1/tasn_new.c	(revision 318897)
@@ -1,381 +1,384 @@
 /* tasn_new.c */
 /*
  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
  * 2000.
  */
 /* ====================================================================
  * Copyright (c) 2000-2004 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    licensing@OpenSSL.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #include 
 #include 
 #include 
 #include 
 #include 
 #include 
 
 static int asn1_item_ex_combine_new(ASN1_VALUE **pval, const ASN1_ITEM *it,
                                     int combine);
 static void asn1_item_clear(ASN1_VALUE **pval, const ASN1_ITEM *it);
 static void asn1_template_clear(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt);
 static void asn1_primitive_clear(ASN1_VALUE **pval, const ASN1_ITEM *it);
 
 ASN1_VALUE *ASN1_item_new(const ASN1_ITEM *it)
 {
     ASN1_VALUE *ret = NULL;
     if (ASN1_item_ex_new(&ret, it) > 0)
         return ret;
     return NULL;
 }
 
 /* Allocate an ASN1 structure */
 
 int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it)
 {
     return asn1_item_ex_combine_new(pval, it, 0);
 }
 
 static int asn1_item_ex_combine_new(ASN1_VALUE **pval, const ASN1_ITEM *it,
                                     int combine)
 {
     const ASN1_TEMPLATE *tt = NULL;
     const ASN1_COMPAT_FUNCS *cf;
     const ASN1_EXTERN_FUNCS *ef;
     const ASN1_AUX *aux = it->funcs;
     ASN1_aux_cb *asn1_cb;
     ASN1_VALUE **pseqval;
     int i;
     if (aux && aux->asn1_cb)
         asn1_cb = aux->asn1_cb;
     else
         asn1_cb = 0;
 
 #ifdef CRYPTO_MDEBUG
     if (it->sname)
         CRYPTO_push_info(it->sname);
 #endif
 
     switch (it->itype) {
 
     case ASN1_ITYPE_EXTERN:
         ef = it->funcs;
         if (ef && ef->asn1_ex_new) {
             if (!ef->asn1_ex_new(pval, it))
                 goto memerr;
         }
         break;
 
     case ASN1_ITYPE_COMPAT:
         cf = it->funcs;
         if (cf && cf->asn1_new) {
             *pval = cf->asn1_new();
             if (!*pval)
                 goto memerr;
         }
         break;
 
     case ASN1_ITYPE_PRIMITIVE:
         if (it->templates) {
             if (!ASN1_template_new(pval, it->templates))
                 goto memerr;
         } else if (!ASN1_primitive_new(pval, it))
             goto memerr;
         break;
 
     case ASN1_ITYPE_MSTRING:
         if (!ASN1_primitive_new(pval, it))
             goto memerr;
         break;
 
     case ASN1_ITYPE_CHOICE:
         if (asn1_cb) {
             i = asn1_cb(ASN1_OP_NEW_PRE, pval, it, NULL);
             if (!i)
                 goto auxerr;
             if (i == 2) {
 #ifdef CRYPTO_MDEBUG
                 if (it->sname)
                     CRYPTO_pop_info();
 #endif
                 return 1;
             }
         }
         if (!combine) {
             *pval = OPENSSL_malloc(it->size);
             if (!*pval)
                 goto memerr;
             memset(*pval, 0, it->size);
         }
         asn1_set_choice_selector(pval, -1, it);
         if (asn1_cb && !asn1_cb(ASN1_OP_NEW_POST, pval, it, NULL))
-            goto auxerr;
+            goto auxerr2;
         break;
 
     case ASN1_ITYPE_NDEF_SEQUENCE:
     case ASN1_ITYPE_SEQUENCE:
         if (asn1_cb) {
             i = asn1_cb(ASN1_OP_NEW_PRE, pval, it, NULL);
             if (!i)
                 goto auxerr;
             if (i == 2) {
 #ifdef CRYPTO_MDEBUG
                 if (it->sname)
                     CRYPTO_pop_info();
 #endif
                 return 1;
             }
         }
         if (!combine) {
             *pval = OPENSSL_malloc(it->size);
             if (!*pval)
                 goto memerr;
             memset(*pval, 0, it->size);
             asn1_do_lock(pval, 0, it);
             asn1_enc_init(pval, it);
         }
         for (i = 0, tt = it->templates; i < it->tcount; tt++, i++) {
             pseqval = asn1_get_field_ptr(pval, tt);
             if (!ASN1_template_new(pseqval, tt))
-                goto memerr;
+                goto memerr2;
         }
         if (asn1_cb && !asn1_cb(ASN1_OP_NEW_POST, pval, it, NULL))
-            goto auxerr;
+            goto auxerr2;
         break;
     }
 #ifdef CRYPTO_MDEBUG
     if (it->sname)
         CRYPTO_pop_info();
 #endif
     return 1;
 
+ memerr2:
+    ASN1_item_ex_free(pval, it);
  memerr:
     ASN1err(ASN1_F_ASN1_ITEM_EX_COMBINE_NEW, ERR_R_MALLOC_FAILURE);
 #ifdef CRYPTO_MDEBUG
     if (it->sname)
         CRYPTO_pop_info();
 #endif
     return 0;
 
+ auxerr2:
+    ASN1_item_ex_free(pval, it);
  auxerr:
     ASN1err(ASN1_F_ASN1_ITEM_EX_COMBINE_NEW, ASN1_R_AUX_ERROR);
-    ASN1_item_ex_free(pval, it);
 #ifdef CRYPTO_MDEBUG
     if (it->sname)
         CRYPTO_pop_info();
 #endif
     return 0;
 
 }
 
 static void asn1_item_clear(ASN1_VALUE **pval, const ASN1_ITEM *it)
 {
     const ASN1_EXTERN_FUNCS *ef;
 
     switch (it->itype) {
 
     case ASN1_ITYPE_EXTERN:
         ef = it->funcs;
         if (ef && ef->asn1_ex_clear)
             ef->asn1_ex_clear(pval, it);
         else
             *pval = NULL;
         break;
 
     case ASN1_ITYPE_PRIMITIVE:
         if (it->templates)
             asn1_template_clear(pval, it->templates);
         else
             asn1_primitive_clear(pval, it);
         break;
 
     case ASN1_ITYPE_MSTRING:
         asn1_primitive_clear(pval, it);
         break;
 
     case ASN1_ITYPE_COMPAT:
     case ASN1_ITYPE_CHOICE:
     case ASN1_ITYPE_SEQUENCE:
     case ASN1_ITYPE_NDEF_SEQUENCE:
         *pval = NULL;
         break;
     }
 }
 
 int ASN1_template_new(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt)
 {
     const ASN1_ITEM *it = ASN1_ITEM_ptr(tt->item);
     int ret;
     if (tt->flags & ASN1_TFLG_OPTIONAL) {
         asn1_template_clear(pval, tt);
         return 1;
     }
     /* If ANY DEFINED BY nothing to do */
 
     if (tt->flags & ASN1_TFLG_ADB_MASK) {
         *pval = NULL;
         return 1;
     }
 #ifdef CRYPTO_MDEBUG
     if (tt->field_name)
         CRYPTO_push_info(tt->field_name);
 #endif
     /* If SET OF or SEQUENCE OF, its a STACK */
     if (tt->flags & ASN1_TFLG_SK_MASK) {
         STACK_OF(ASN1_VALUE) *skval;
         skval = sk_ASN1_VALUE_new_null();
         if (!skval) {
             ASN1err(ASN1_F_ASN1_TEMPLATE_NEW, ERR_R_MALLOC_FAILURE);
             ret = 0;
             goto done;
         }
         *pval = (ASN1_VALUE *)skval;
         ret = 1;
         goto done;
     }
     /* Otherwise pass it back to the item routine */
     ret = asn1_item_ex_combine_new(pval, it, tt->flags & ASN1_TFLG_COMBINE);
  done:
 #ifdef CRYPTO_MDEBUG
     if (it->sname)
         CRYPTO_pop_info();
 #endif
     return ret;
 }
 
 static void asn1_template_clear(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt)
 {
     /* If ADB or STACK just NULL the field */
     if (tt->flags & (ASN1_TFLG_ADB_MASK | ASN1_TFLG_SK_MASK))
         *pval = NULL;
     else
         asn1_item_clear(pval, ASN1_ITEM_ptr(tt->item));
 }
 
 /*
  * NB: could probably combine most of the real XXX_new() behaviour and junk
  * all the old functions.
  */
 
 int ASN1_primitive_new(ASN1_VALUE **pval, const ASN1_ITEM *it)
 {
     ASN1_TYPE *typ;
     ASN1_STRING *str;
     int utype;
 
     if (!it)
         return 0;
 
     if (it->funcs) {
         const ASN1_PRIMITIVE_FUNCS *pf = it->funcs;
         if (pf->prim_new)
             return pf->prim_new(pval, it);
     }
 
     if (it->itype == ASN1_ITYPE_MSTRING)
         utype = -1;
     else
         utype = it->utype;
     switch (utype) {
     case V_ASN1_OBJECT:
         *pval = (ASN1_VALUE *)OBJ_nid2obj(NID_undef);
         return 1;
 
     case V_ASN1_BOOLEAN:
         *(ASN1_BOOLEAN *)pval = it->size;
         return 1;
 
     case V_ASN1_NULL:
         *pval = (ASN1_VALUE *)1;
         return 1;
 
     case V_ASN1_ANY:
         typ = OPENSSL_malloc(sizeof(ASN1_TYPE));
         if (!typ)
             return 0;
         typ->value.ptr = NULL;
         typ->type = -1;
         *pval = (ASN1_VALUE *)typ;
         break;
 
     default:
         str = ASN1_STRING_type_new(utype);
         if (it->itype == ASN1_ITYPE_MSTRING && str)
             str->flags |= ASN1_STRING_FLAG_MSTRING;
         *pval = (ASN1_VALUE *)str;
         break;
     }
     if (*pval)
         return 1;
     return 0;
 }
 
 static void asn1_primitive_clear(ASN1_VALUE **pval, const ASN1_ITEM *it)
 {
     int utype;
     if (it && it->funcs) {
         const ASN1_PRIMITIVE_FUNCS *pf = it->funcs;
         if (pf->prim_clear)
             pf->prim_clear(pval, it);
         else
             *pval = NULL;
         return;
     }
     if (!it || (it->itype == ASN1_ITYPE_MSTRING))
         utype = -1;
     else
         utype = it->utype;
     if (utype == V_ASN1_BOOLEAN)
         *(ASN1_BOOLEAN *)pval = it->size;
     else
         *pval = NULL;
 }
Index: vendor-crypto/openssl/dist/crypto/asn1/x_long.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/asn1/x_long.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/asn1/x_long.c	(revision 318897)
@@ -1,196 +1,218 @@
 /* x_long.c */
 /*
  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
  * 2000.
  */
 /* ====================================================================
  * Copyright (c) 2000 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    licensing@OpenSSL.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #include 
 #include "cryptlib.h"
 #include 
 #include 
 
 /*
  * Custom primitive type for long handling. This converts between an
  * ASN1_INTEGER and a long directly.
  */
 
 static int long_new(ASN1_VALUE **pval, const ASN1_ITEM *it);
 static void long_free(ASN1_VALUE **pval, const ASN1_ITEM *it);
 
 static int long_i2c(ASN1_VALUE **pval, unsigned char *cont, int *putype,
                     const ASN1_ITEM *it);
 static int long_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
                     int utype, char *free_cont, const ASN1_ITEM *it);
 static int long_print(BIO *out, ASN1_VALUE **pval, const ASN1_ITEM *it,
                       int indent, const ASN1_PCTX *pctx);
 
 static ASN1_PRIMITIVE_FUNCS long_pf = {
     NULL, 0,
     long_new,
     long_free,
     long_free,                  /* Clear should set to initial value */
     long_c2i,
     long_i2c,
     long_print
 };
 
 ASN1_ITEM_start(LONG)
         ASN1_ITYPE_PRIMITIVE, V_ASN1_INTEGER, NULL, 0, &long_pf, ASN1_LONG_UNDEF, "LONG"
 ASN1_ITEM_end(LONG)
 
 ASN1_ITEM_start(ZLONG)
         ASN1_ITYPE_PRIMITIVE, V_ASN1_INTEGER, NULL, 0, &long_pf, 0, "ZLONG"
 ASN1_ITEM_end(ZLONG)
 
 static int long_new(ASN1_VALUE **pval, const ASN1_ITEM *it)
 {
     *(long *)pval = it->size;
     return 1;
 }
 
 static void long_free(ASN1_VALUE **pval, const ASN1_ITEM *it)
 {
     *(long *)pval = it->size;
 }
 
 static int long_i2c(ASN1_VALUE **pval, unsigned char *cont, int *putype,
                     const ASN1_ITEM *it)
 {
     long ltmp;
     unsigned long utmp;
     int clen, pad, i;
     /* this exists to bypass broken gcc optimization */
     char *cp = (char *)pval;
 
     /* use memcpy, because we may not be long aligned */
     memcpy(<mp, cp, sizeof(long));
 
     if (ltmp == it->size)
         return -1;
     /*
      * Convert the long to positive: we subtract one if negative so we can
      * cleanly handle the padding if only the MSB of the leading octet is
      * set.
      */
     if (ltmp < 0)
-        utmp = -ltmp - 1;
+        utmp = 0 - (unsigned long)ltmp - 1;
     else
         utmp = ltmp;
     clen = BN_num_bits_word(utmp);
     /* If MSB of leading octet set we need to pad */
     if (!(clen & 0x7))
         pad = 1;
     else
         pad = 0;
 
     /* Convert number of bits to number of octets */
     clen = (clen + 7) >> 3;
 
     if (cont) {
         if (pad)
             *cont++ = (ltmp < 0) ? 0xff : 0;
         for (i = clen - 1; i >= 0; i--) {
             cont[i] = (unsigned char)(utmp & 0xff);
             if (ltmp < 0)
                 cont[i] ^= 0xff;
             utmp >>= 8;
         }
     }
     return clen + pad;
 }
 
 static int long_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
                     int utype, char *free_cont, const ASN1_ITEM *it)
 {
-    int neg, i;
+    int neg = -1, i;
     long ltmp;
     unsigned long utmp = 0;
     char *cp = (char *)pval;
+
+    if (len) {
+        /*
+         * Check possible pad byte.  Worst case, we're skipping past actual
+         * content, but since that's only with 0x00 and 0xff and we set neg
+         * accordingly, the result will be correct in the end anyway.
+         */
+        switch (cont[0]) {
+        case 0xff:
+            cont++;
+            len--;
+            neg = 1;
+            break;
+        case 0:
+            cont++;
+            len--;
+            neg = 0;
+            break;
+        }
+    }
     if (len > (int)sizeof(long)) {
         ASN1err(ASN1_F_LONG_C2I, ASN1_R_INTEGER_TOO_LARGE_FOR_LONG);
         return 0;
     }
-    /* Is it negative? */
-    if (len && (cont[0] & 0x80))
-        neg = 1;
-    else
-        neg = 0;
+    if (neg == -1) {
+        /* Is it negative? */
+        if (len && (cont[0] & 0x80))
+            neg = 1;
+        else
+            neg = 0;
+    }
     utmp = 0;
     for (i = 0; i < len; i++) {
         utmp <<= 8;
         if (neg)
             utmp |= cont[i] ^ 0xff;
         else
             utmp |= cont[i];
     }
     ltmp = (long)utmp;
     if (neg) {
-        ltmp++;
         ltmp = -ltmp;
+        ltmp--;
     }
     if (ltmp == it->size) {
         ASN1err(ASN1_F_LONG_C2I, ASN1_R_INTEGER_TOO_LARGE_FOR_LONG);
         return 0;
     }
     memcpy(cp, <mp, sizeof(long));
     return 1;
 }
 
 static int long_print(BIO *out, ASN1_VALUE **pval, const ASN1_ITEM *it,
                       int indent, const ASN1_PCTX *pctx)
 {
     return BIO_printf(out, "%ld\n", *(long *)pval);
 }
Index: vendor-crypto/openssl/dist/crypto/asn1/x_name.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/asn1/x_name.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/asn1/x_name.c	(revision 318897)
@@ -1,536 +1,543 @@
 /* crypto/asn1/x_name.c */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 
 #include 
 #include 
 #include "cryptlib.h"
 #include 
 #include 
 #include "asn1_locl.h"
 
 typedef STACK_OF(X509_NAME_ENTRY) STACK_OF_X509_NAME_ENTRY;
 DECLARE_STACK_OF(STACK_OF_X509_NAME_ENTRY)
 
 /*
  * Maximum length of X509_NAME: much larger than anything we should
  * ever see in practice.
  */
 
 #define X509_NAME_MAX (1024 * 1024)
 
 static int x509_name_ex_d2i(ASN1_VALUE **val,
                             const unsigned char **in, long len,
                             const ASN1_ITEM *it,
                             int tag, int aclass, char opt, ASN1_TLC *ctx);
 
 static int x509_name_ex_i2d(ASN1_VALUE **val, unsigned char **out,
                             const ASN1_ITEM *it, int tag, int aclass);
 static int x509_name_ex_new(ASN1_VALUE **val, const ASN1_ITEM *it);
 static void x509_name_ex_free(ASN1_VALUE **val, const ASN1_ITEM *it);
 
 static int x509_name_encode(X509_NAME *a);
 static int x509_name_canon(X509_NAME *a);
 static int asn1_string_canon(ASN1_STRING *out, ASN1_STRING *in);
 static int i2d_name_canon(STACK_OF(STACK_OF_X509_NAME_ENTRY) * intname,
                           unsigned char **in);
 
 static int x509_name_ex_print(BIO *out, ASN1_VALUE **pval,
                               int indent,
                               const char *fname, const ASN1_PCTX *pctx);
 
 ASN1_SEQUENCE(X509_NAME_ENTRY) = {
         ASN1_SIMPLE(X509_NAME_ENTRY, object, ASN1_OBJECT),
         ASN1_SIMPLE(X509_NAME_ENTRY, value, ASN1_PRINTABLE)
 } ASN1_SEQUENCE_END(X509_NAME_ENTRY)
 
 IMPLEMENT_ASN1_FUNCTIONS(X509_NAME_ENTRY)
 IMPLEMENT_ASN1_DUP_FUNCTION(X509_NAME_ENTRY)
 
 /*
  * For the "Name" type we need a SEQUENCE OF { SET OF X509_NAME_ENTRY } so
  * declare two template wrappers for this
  */
 
 ASN1_ITEM_TEMPLATE(X509_NAME_ENTRIES) =
         ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SET_OF, 0, RDNS, X509_NAME_ENTRY)
 ASN1_ITEM_TEMPLATE_END(X509_NAME_ENTRIES)
 
 ASN1_ITEM_TEMPLATE(X509_NAME_INTERNAL) =
         ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, Name, X509_NAME_ENTRIES)
 ASN1_ITEM_TEMPLATE_END(X509_NAME_INTERNAL)
 
 /*
  * Normally that's where it would end: we'd have two nested STACK structures
  * representing the ASN1. Unfortunately X509_NAME uses a completely different
  * form and caches encodings so we have to process the internal form and
  * convert to the external form.
  */
 
 const ASN1_EXTERN_FUNCS x509_name_ff = {
     NULL,
     x509_name_ex_new,
     x509_name_ex_free,
     0,                          /* Default clear behaviour is OK */
     x509_name_ex_d2i,
     x509_name_ex_i2d,
     x509_name_ex_print
 };
 
 IMPLEMENT_EXTERN_ASN1(X509_NAME, V_ASN1_SEQUENCE, x509_name_ff)
 
 IMPLEMENT_ASN1_FUNCTIONS(X509_NAME)
 
 IMPLEMENT_ASN1_DUP_FUNCTION(X509_NAME)
 
 static int x509_name_ex_new(ASN1_VALUE **val, const ASN1_ITEM *it)
 {
     X509_NAME *ret = NULL;
     ret = OPENSSL_malloc(sizeof(X509_NAME));
     if (!ret)
         goto memerr;
     if ((ret->entries = sk_X509_NAME_ENTRY_new_null()) == NULL)
         goto memerr;
     if ((ret->bytes = BUF_MEM_new()) == NULL)
         goto memerr;
     ret->canon_enc = NULL;
     ret->canon_enclen = 0;
     ret->modified = 1;
     *val = (ASN1_VALUE *)ret;
     return 1;
 
  memerr:
     ASN1err(ASN1_F_X509_NAME_EX_NEW, ERR_R_MALLOC_FAILURE);
     if (ret) {
         if (ret->entries)
             sk_X509_NAME_ENTRY_free(ret->entries);
         OPENSSL_free(ret);
     }
     return 0;
 }
 
 static void x509_name_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it)
 {
     X509_NAME *a;
     if (!pval || !*pval)
         return;
     a = (X509_NAME *)*pval;
 
     BUF_MEM_free(a->bytes);
     sk_X509_NAME_ENTRY_pop_free(a->entries, X509_NAME_ENTRY_free);
     if (a->canon_enc)
         OPENSSL_free(a->canon_enc);
     OPENSSL_free(a);
     *pval = NULL;
 }
 
+static void local_sk_X509_NAME_ENTRY_free(STACK_OF(X509_NAME_ENTRY) *ne)
+{
+    sk_X509_NAME_ENTRY_free(ne);
+}
+
+static void local_sk_X509_NAME_ENTRY_pop_free(STACK_OF(X509_NAME_ENTRY) *ne)
+{
+    sk_X509_NAME_ENTRY_pop_free(ne, X509_NAME_ENTRY_free);
+}
+
 static int x509_name_ex_d2i(ASN1_VALUE **val,
                             const unsigned char **in, long len,
                             const ASN1_ITEM *it, int tag, int aclass,
                             char opt, ASN1_TLC *ctx)
 {
     const unsigned char *p = *in, *q;
     union {
         STACK_OF(STACK_OF_X509_NAME_ENTRY) *s;
         ASN1_VALUE *a;
     } intname = {
         NULL
     };
     union {
         X509_NAME *x;
         ASN1_VALUE *a;
     } nm = {
         NULL
     };
     int i, j, ret;
     STACK_OF(X509_NAME_ENTRY) *entries;
     X509_NAME_ENTRY *entry;
     if (len > X509_NAME_MAX)
         len = X509_NAME_MAX;
     q = p;
 
     /* Get internal representation of Name */
     ret = ASN1_item_ex_d2i(&intname.a,
                            &p, len, ASN1_ITEM_rptr(X509_NAME_INTERNAL),
                            tag, aclass, opt, ctx);
 
     if (ret <= 0)
         return ret;
 
     if (*val)
         x509_name_ex_free(val, NULL);
     if (!x509_name_ex_new(&nm.a, NULL))
         goto err;
     /* We've decoded it: now cache encoding */
     if (!BUF_MEM_grow(nm.x->bytes, p - q))
         goto err;
     memcpy(nm.x->bytes->data, q, p - q);
 
     /* Convert internal representation to X509_NAME structure */
     for (i = 0; i < sk_STACK_OF_X509_NAME_ENTRY_num(intname.s); i++) {
         entries = sk_STACK_OF_X509_NAME_ENTRY_value(intname.s, i);
         for (j = 0; j < sk_X509_NAME_ENTRY_num(entries); j++) {
             entry = sk_X509_NAME_ENTRY_value(entries, j);
             entry->set = i;
             if (!sk_X509_NAME_ENTRY_push(nm.x->entries, entry))
                 goto err;
+            sk_X509_NAME_ENTRY_set(entries, j, NULL);
         }
-        sk_X509_NAME_ENTRY_free(entries);
     }
-    sk_STACK_OF_X509_NAME_ENTRY_free(intname.s);
     ret = x509_name_canon(nm.x);
     if (!ret)
         goto err;
+    sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname.s,
+                                         local_sk_X509_NAME_ENTRY_free);
     nm.x->modified = 0;
     *val = nm.a;
     *in = p;
     return ret;
  err:
     if (nm.x != NULL)
         X509_NAME_free(nm.x);
+    sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname.s,
+                                         local_sk_X509_NAME_ENTRY_pop_free);
     ASN1err(ASN1_F_X509_NAME_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
     return 0;
 }
 
 static int x509_name_ex_i2d(ASN1_VALUE **val, unsigned char **out,
                             const ASN1_ITEM *it, int tag, int aclass)
 {
     int ret;
     X509_NAME *a = (X509_NAME *)*val;
     if (a->modified) {
         ret = x509_name_encode(a);
         if (ret < 0)
             return ret;
         ret = x509_name_canon(a);
         if (ret < 0)
             return ret;
     }
     ret = a->bytes->length;
     if (out != NULL) {
         memcpy(*out, a->bytes->data, ret);
         *out += ret;
     }
     return ret;
 }
 
-static void local_sk_X509_NAME_ENTRY_free(STACK_OF(X509_NAME_ENTRY) *ne)
-{
-    sk_X509_NAME_ENTRY_free(ne);
-}
-
-static void local_sk_X509_NAME_ENTRY_pop_free(STACK_OF(X509_NAME_ENTRY) *ne)
-{
-    sk_X509_NAME_ENTRY_pop_free(ne, X509_NAME_ENTRY_free);
-}
-
 static int x509_name_encode(X509_NAME *a)
 {
     union {
         STACK_OF(STACK_OF_X509_NAME_ENTRY) *s;
         ASN1_VALUE *a;
     } intname = {
         NULL
     };
     int len;
     unsigned char *p;
     STACK_OF(X509_NAME_ENTRY) *entries = NULL;
     X509_NAME_ENTRY *entry;
     int i, set = -1;
     intname.s = sk_STACK_OF_X509_NAME_ENTRY_new_null();
     if (!intname.s)
         goto memerr;
     for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) {
         entry = sk_X509_NAME_ENTRY_value(a->entries, i);
         if (entry->set != set) {
             entries = sk_X509_NAME_ENTRY_new_null();
             if (!entries)
                 goto memerr;
-            if (!sk_STACK_OF_X509_NAME_ENTRY_push(intname.s, entries))
+            if (!sk_STACK_OF_X509_NAME_ENTRY_push(intname.s, entries)) {
+                sk_X509_NAME_ENTRY_free(entries);
                 goto memerr;
+            }
             set = entry->set;
         }
         if (!sk_X509_NAME_ENTRY_push(entries, entry))
             goto memerr;
     }
     len = ASN1_item_ex_i2d(&intname.a, NULL,
                            ASN1_ITEM_rptr(X509_NAME_INTERNAL), -1, -1);
     if (!BUF_MEM_grow(a->bytes, len))
         goto memerr;
     p = (unsigned char *)a->bytes->data;
     ASN1_item_ex_i2d(&intname.a,
                      &p, ASN1_ITEM_rptr(X509_NAME_INTERNAL), -1, -1);
     sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname.s,
                                          local_sk_X509_NAME_ENTRY_free);
     a->modified = 0;
     return len;
  memerr:
     sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname.s,
                                          local_sk_X509_NAME_ENTRY_free);
     ASN1err(ASN1_F_X509_NAME_ENCODE, ERR_R_MALLOC_FAILURE);
     return -1;
 }
 
 static int x509_name_ex_print(BIO *out, ASN1_VALUE **pval,
                               int indent,
                               const char *fname, const ASN1_PCTX *pctx)
 {
     if (X509_NAME_print_ex(out, (X509_NAME *)*pval,
                            indent, pctx->nm_flags) <= 0)
         return 0;
     return 2;
 }
 
 /*
  * This function generates the canonical encoding of the Name structure. In
  * it all strings are converted to UTF8, leading, trailing and multiple
  * spaces collapsed, converted to lower case and the leading SEQUENCE header
  * removed. In future we could also normalize the UTF8 too. By doing this
  * comparison of Name structures can be rapidly perfomed by just using
  * memcmp() of the canonical encoding. By omitting the leading SEQUENCE name
  * constraints of type dirName can also be checked with a simple memcmp().
  */
 
 static int x509_name_canon(X509_NAME *a)
 {
     unsigned char *p;
     STACK_OF(STACK_OF_X509_NAME_ENTRY) *intname = NULL;
     STACK_OF(X509_NAME_ENTRY) *entries = NULL;
     X509_NAME_ENTRY *entry, *tmpentry = NULL;
     int i, set = -1, ret = 0;
 
     if (a->canon_enc) {
         OPENSSL_free(a->canon_enc);
         a->canon_enc = NULL;
     }
     /* Special case: empty X509_NAME => null encoding */
     if (sk_X509_NAME_ENTRY_num(a->entries) == 0) {
         a->canon_enclen = 0;
         return 1;
     }
     intname = sk_STACK_OF_X509_NAME_ENTRY_new_null();
     if (!intname)
         goto err;
     for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) {
         entry = sk_X509_NAME_ENTRY_value(a->entries, i);
         if (entry->set != set) {
             entries = sk_X509_NAME_ENTRY_new_null();
             if (!entries)
                 goto err;
-            if (!sk_STACK_OF_X509_NAME_ENTRY_push(intname, entries))
+            if (!sk_STACK_OF_X509_NAME_ENTRY_push(intname, entries)) {
+                sk_X509_NAME_ENTRY_free(entries);
                 goto err;
+            }
             set = entry->set;
         }
         tmpentry = X509_NAME_ENTRY_new();
         if (!tmpentry)
             goto err;
         tmpentry->object = OBJ_dup(entry->object);
         if (!asn1_string_canon(tmpentry->value, entry->value))
             goto err;
         if (!sk_X509_NAME_ENTRY_push(entries, tmpentry))
             goto err;
         tmpentry = NULL;
     }
 
     /* Finally generate encoding */
 
     a->canon_enclen = i2d_name_canon(intname, NULL);
 
     p = OPENSSL_malloc(a->canon_enclen);
 
     if (!p)
         goto err;
 
     a->canon_enc = p;
 
     i2d_name_canon(intname, &p);
 
     ret = 1;
 
  err:
 
     if (tmpentry)
         X509_NAME_ENTRY_free(tmpentry);
     if (intname)
         sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname,
                                              local_sk_X509_NAME_ENTRY_pop_free);
     return ret;
 }
 
 /* Bitmap of all the types of string that will be canonicalized. */
 
 #define ASN1_MASK_CANON \
         (B_ASN1_UTF8STRING | B_ASN1_BMPSTRING | B_ASN1_UNIVERSALSTRING \
         | B_ASN1_PRINTABLESTRING | B_ASN1_T61STRING | B_ASN1_IA5STRING \
         | B_ASN1_VISIBLESTRING)
 
 static int asn1_string_canon(ASN1_STRING *out, ASN1_STRING *in)
 {
     unsigned char *to, *from;
     int len, i;
 
     /* If type not in bitmask just copy string across */
     if (!(ASN1_tag2bit(in->type) & ASN1_MASK_CANON)) {
         if (!ASN1_STRING_copy(out, in))
             return 0;
         return 1;
     }
 
     out->type = V_ASN1_UTF8STRING;
     out->length = ASN1_STRING_to_UTF8(&out->data, in);
     if (out->length == -1)
         return 0;
 
     to = out->data;
     from = to;
 
     len = out->length;
 
     /*
      * Convert string in place to canonical form. Ultimately we may need to
      * handle a wider range of characters but for now ignore anything with
      * MSB set and rely on the isspace() and tolower() functions.
      */
 
     /* Ignore leading spaces */
     while ((len > 0) && !(*from & 0x80) && isspace(*from)) {
         from++;
         len--;
     }
 
     to = from + len - 1;
 
     /* Ignore trailing spaces */
     while ((len > 0) && !(*to & 0x80) && isspace(*to)) {
         to--;
         len--;
     }
 
     to = out->data;
 
     i = 0;
     while (i < len) {
         /* If MSB set just copy across */
         if (*from & 0x80) {
             *to++ = *from++;
             i++;
         }
         /* Collapse multiple spaces */
         else if (isspace(*from)) {
             /* Copy one space across */
             *to++ = ' ';
             /*
              * Ignore subsequent spaces. Note: don't need to check len here
              * because we know the last character is a non-space so we can't
              * overflow.
              */
             do {
                 from++;
                 i++;
             }
             while (!(*from & 0x80) && isspace(*from));
         } else {
             *to++ = tolower(*from);
             from++;
             i++;
         }
     }
 
     out->length = to - out->data;
 
     return 1;
 
 }
 
 static int i2d_name_canon(STACK_OF(STACK_OF_X509_NAME_ENTRY) * _intname,
                           unsigned char **in)
 {
     int i, len, ltmp;
     ASN1_VALUE *v;
     STACK_OF(ASN1_VALUE) *intname = (STACK_OF(ASN1_VALUE) *)_intname;
 
     len = 0;
     for (i = 0; i < sk_ASN1_VALUE_num(intname); i++) {
         v = sk_ASN1_VALUE_value(intname, i);
         ltmp = ASN1_item_ex_i2d(&v, in,
                                 ASN1_ITEM_rptr(X509_NAME_ENTRIES), -1, -1);
         if (ltmp < 0)
             return ltmp;
         len += ltmp;
     }
     return len;
 }
 
 int X509_NAME_set(X509_NAME **xn, X509_NAME *name)
 {
     X509_NAME *in;
 
     if (!xn || !name)
         return (0);
 
     if (*xn != name) {
         in = X509_NAME_dup(name);
         if (in != NULL) {
             X509_NAME_free(*xn);
             *xn = in;
         }
     }
     return (*xn != NULL);
 }
 
 IMPLEMENT_STACK_OF(X509_NAME_ENTRY)
 
 IMPLEMENT_ASN1_SET_OF(X509_NAME_ENTRY)
Index: vendor-crypto/openssl/dist/crypto/bio/b_print.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/bio/b_print.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/bio/b_print.c	(revision 318897)
@@ -1,869 +1,869 @@
 /* crypto/bio/b_print.c */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 
 /* disable assert() unless BIO_DEBUG has been defined */
 #ifndef BIO_DEBUG
 # ifndef NDEBUG
 #  define NDEBUG
 # endif
 #endif
 
 /*
  * Stolen from tjh's ssl/ssl_trc.c stuff.
  */
 
 #include 
 #include 
 #include 
 #include 
 #include 
 #include "cryptlib.h"
 #ifndef NO_SYS_TYPES_H
 # include 
 #endif
 #include          /* To get BN_LLONG properly defined */
 #include 
 
 #if defined(BN_LLONG) || defined(SIXTY_FOUR_BIT)
 # ifndef HAVE_LONG_LONG
 #  define HAVE_LONG_LONG 1
 # endif
 #endif
 
 /***************************************************************************/
 
 /*
  * Copyright Patrick Powell 1995
  * This code is based on code written by Patrick Powell 
  * It may be used for any purpose as long as this notice remains intact
  * on all source code distributions.
  */
 
 /*-
  * This code contains numerious changes and enhancements which were
  * made by lots of contributors over the last years to Patrick Powell's
  * original code:
  *
  * o Patrick Powell       (1995)
  * o Brandon Long           (1996, for Mutt)
  * o Thomas Roessler         (1998, for Mutt)
  * o Michael Elkins             (1998, for Mutt)
  * o Andrew Tridgell         (1998, for Samba)
  * o Luke Mewburn            (1999, for LukemFTP)
  * o Ralf S. Engelschall  (1999, for Pth)
  * o ...                                       (for OpenSSL)
  */
 
 #ifdef HAVE_LONG_DOUBLE
 # define LDOUBLE long double
 #else
 # define LDOUBLE double
 #endif
 
 #ifdef HAVE_LONG_LONG
 # if defined(_WIN32) && !defined(__GNUC__)
 #  define LLONG __int64
 # else
 #  define LLONG long long
 # endif
 #else
 # define LLONG long
 #endif
 
 static int fmtstr(char **, char **, size_t *, size_t *,
                   const char *, int, int, int);
 static int fmtint(char **, char **, size_t *, size_t *,
                   LLONG, int, int, int, int);
 static int fmtfp(char **, char **, size_t *, size_t *,
                  LDOUBLE, int, int, int);
 static int doapr_outch(char **, char **, size_t *, size_t *, int);
 static int _dopr(char **sbuffer, char **buffer,
                  size_t *maxlen, size_t *retlen, int *truncated,
                  const char *format, va_list args);
 
 /* format read states */
 #define DP_S_DEFAULT    0
 #define DP_S_FLAGS      1
 #define DP_S_MIN        2
 #define DP_S_DOT        3
 #define DP_S_MAX        4
 #define DP_S_MOD        5
 #define DP_S_CONV       6
 #define DP_S_DONE       7
 
 /* format flags - Bits */
 #define DP_F_MINUS      (1 << 0)
 #define DP_F_PLUS       (1 << 1)
 #define DP_F_SPACE      (1 << 2)
 #define DP_F_NUM        (1 << 3)
 #define DP_F_ZERO       (1 << 4)
 #define DP_F_UP         (1 << 5)
 #define DP_F_UNSIGNED   (1 << 6)
 
 /* conversion flags */
 #define DP_C_SHORT      1
 #define DP_C_LONG       2
 #define DP_C_LDOUBLE    3
 #define DP_C_LLONG      4
 
 /* some handy macros */
 #define char_to_int(p) (p - '0')
 #define OSSL_MAX(p,q) ((p >= q) ? p : q)
 
 static int
 _dopr(char **sbuffer,
       char **buffer,
       size_t *maxlen,
       size_t *retlen, int *truncated, const char *format, va_list args)
 {
     char ch;
     LLONG value;
     LDOUBLE fvalue;
     char *strvalue;
     int min;
     int max;
     int state;
     int flags;
     int cflags;
     size_t currlen;
 
     state = DP_S_DEFAULT;
     flags = currlen = cflags = min = 0;
     max = -1;
     ch = *format++;
 
     while (state != DP_S_DONE) {
         if (ch == '\0' || (buffer == NULL && currlen >= *maxlen))
             state = DP_S_DONE;
 
         switch (state) {
         case DP_S_DEFAULT:
             if (ch == '%')
                 state = DP_S_FLAGS;
             else
                 if(!doapr_outch(sbuffer, buffer, &currlen, maxlen, ch))
                     return 0;
             ch = *format++;
             break;
         case DP_S_FLAGS:
             switch (ch) {
             case '-':
                 flags |= DP_F_MINUS;
                 ch = *format++;
                 break;
             case '+':
                 flags |= DP_F_PLUS;
                 ch = *format++;
                 break;
             case ' ':
                 flags |= DP_F_SPACE;
                 ch = *format++;
                 break;
             case '#':
                 flags |= DP_F_NUM;
                 ch = *format++;
                 break;
             case '0':
                 flags |= DP_F_ZERO;
                 ch = *format++;
                 break;
             default:
                 state = DP_S_MIN;
                 break;
             }
             break;
         case DP_S_MIN:
             if (isdigit((unsigned char)ch)) {
                 min = 10 * min + char_to_int(ch);
                 ch = *format++;
             } else if (ch == '*') {
                 min = va_arg(args, int);
                 ch = *format++;
                 state = DP_S_DOT;
             } else
                 state = DP_S_DOT;
             break;
         case DP_S_DOT:
             if (ch == '.') {
                 state = DP_S_MAX;
                 ch = *format++;
             } else
                 state = DP_S_MOD;
             break;
         case DP_S_MAX:
             if (isdigit((unsigned char)ch)) {
                 if (max < 0)
                     max = 0;
                 max = 10 * max + char_to_int(ch);
                 ch = *format++;
             } else if (ch == '*') {
                 max = va_arg(args, int);
                 ch = *format++;
                 state = DP_S_MOD;
             } else
                 state = DP_S_MOD;
             break;
         case DP_S_MOD:
             switch (ch) {
             case 'h':
                 cflags = DP_C_SHORT;
                 ch = *format++;
                 break;
             case 'l':
                 if (*format == 'l') {
                     cflags = DP_C_LLONG;
                     format++;
                 } else
                     cflags = DP_C_LONG;
                 ch = *format++;
                 break;
             case 'q':
                 cflags = DP_C_LLONG;
                 ch = *format++;
                 break;
             case 'L':
                 cflags = DP_C_LDOUBLE;
                 ch = *format++;
                 break;
             default:
                 break;
             }
             state = DP_S_CONV;
             break;
         case DP_S_CONV:
             switch (ch) {
             case 'd':
             case 'i':
                 switch (cflags) {
                 case DP_C_SHORT:
                     value = (short int)va_arg(args, int);
                     break;
                 case DP_C_LONG:
                     value = va_arg(args, long int);
                     break;
                 case DP_C_LLONG:
                     value = va_arg(args, LLONG);
                     break;
                 default:
                     value = va_arg(args, int);
                     break;
                 }
                 if (!fmtint(sbuffer, buffer, &currlen, maxlen, value, 10, min,
                             max, flags))
                     return 0;
                 break;
             case 'X':
                 flags |= DP_F_UP;
                 /* FALLTHROUGH */
             case 'x':
             case 'o':
             case 'u':
                 flags |= DP_F_UNSIGNED;
                 switch (cflags) {
                 case DP_C_SHORT:
                     value = (unsigned short int)va_arg(args, unsigned int);
                     break;
                 case DP_C_LONG:
                     value = (LLONG) va_arg(args, unsigned long int);
                     break;
                 case DP_C_LLONG:
                     value = va_arg(args, unsigned LLONG);
                     break;
                 default:
                     value = (LLONG) va_arg(args, unsigned int);
                     break;
                 }
                 if (!fmtint(sbuffer, buffer, &currlen, maxlen, value,
                             ch == 'o' ? 8 : (ch == 'u' ? 10 : 16),
                             min, max, flags))
                     return 0;
                 break;
             case 'f':
                 if (cflags == DP_C_LDOUBLE)
                     fvalue = va_arg(args, LDOUBLE);
                 else
                     fvalue = va_arg(args, double);
                 if (!fmtfp(sbuffer, buffer, &currlen, maxlen, fvalue, min, max,
                            flags))
                     return 0;
                 break;
             case 'E':
                 flags |= DP_F_UP;
             case 'e':
                 if (cflags == DP_C_LDOUBLE)
                     fvalue = va_arg(args, LDOUBLE);
                 else
                     fvalue = va_arg(args, double);
                 break;
             case 'G':
                 flags |= DP_F_UP;
             case 'g':
                 if (cflags == DP_C_LDOUBLE)
                     fvalue = va_arg(args, LDOUBLE);
                 else
                     fvalue = va_arg(args, double);
                 break;
             case 'c':
                 if(!doapr_outch(sbuffer, buffer, &currlen, maxlen,
                             va_arg(args, int)))
                     return 0;
                 break;
             case 's':
                 strvalue = va_arg(args, char *);
                 if (max < 0) {
                     if (buffer)
                         max = INT_MAX;
                     else
                         max = *maxlen;
                 }
                 if (!fmtstr(sbuffer, buffer, &currlen, maxlen, strvalue,
                             flags, min, max))
                     return 0;
                 break;
             case 'p':
                 value = (long)va_arg(args, void *);
                 if (!fmtint(sbuffer, buffer, &currlen, maxlen,
                             value, 16, min, max, flags | DP_F_NUM))
                     return 0;
                 break;
             case 'n':          /* XXX */
                 if (cflags == DP_C_SHORT) {
                     short int *num;
                     num = va_arg(args, short int *);
                     *num = currlen;
                 } else if (cflags == DP_C_LONG) { /* XXX */
                     long int *num;
                     num = va_arg(args, long int *);
                     *num = (long int)currlen;
                 } else if (cflags == DP_C_LLONG) { /* XXX */
                     LLONG *num;
                     num = va_arg(args, LLONG *);
                     *num = (LLONG) currlen;
                 } else {
                     int *num;
                     num = va_arg(args, int *);
                     *num = currlen;
                 }
                 break;
             case '%':
                 if(!doapr_outch(sbuffer, buffer, &currlen, maxlen, ch))
                     return 0;
                 break;
             case 'w':
                 /* not supported yet, treat as next char */
                 ch = *format++;
                 break;
             default:
                 /* unknown, skip */
                 break;
             }
             ch = *format++;
             state = DP_S_DEFAULT;
             flags = cflags = min = 0;
             max = -1;
             break;
         case DP_S_DONE:
             break;
         default:
             break;
         }
     }
     /*
      * We have to truncate if there is no dynamic buffer and we have filled the
      * static buffer.
      */
     if (buffer == NULL) {
         *truncated = (currlen > *maxlen - 1);
         if (*truncated)
             currlen = *maxlen - 1;
     }
     if(!doapr_outch(sbuffer, buffer, &currlen, maxlen, '\0'))
         return 0;
     *retlen = currlen - 1;
     return 1;
 }
 
 static int
 fmtstr(char **sbuffer,
        char **buffer,
        size_t *currlen,
        size_t *maxlen, const char *value, int flags, int min, int max)
 {
     int padlen;
     size_t strln;
     int cnt = 0;
 
     if (value == 0)
         value = "";
 
     strln = strlen(value);
     if (strln > INT_MAX)
         strln = INT_MAX;
 
     padlen = min - strln;
     if (min < 0 || padlen < 0)
         padlen = 0;
     if (flags & DP_F_MINUS)
         padlen = -padlen;
 
     while ((padlen > 0) && (cnt < max)) {
         if(!doapr_outch(sbuffer, buffer, currlen, maxlen, ' '))
             return 0;
         --padlen;
         ++cnt;
     }
     while (*value && (cnt < max)) {
         if(!doapr_outch(sbuffer, buffer, currlen, maxlen, *value++))
             return 0;
         ++cnt;
     }
     while ((padlen < 0) && (cnt < max)) {
         if(!doapr_outch(sbuffer, buffer, currlen, maxlen, ' '))
             return 0;
         ++padlen;
         ++cnt;
     }
     return 1;
 }
 
 static int
 fmtint(char **sbuffer,
        char **buffer,
        size_t *currlen,
        size_t *maxlen, LLONG value, int base, int min, int max, int flags)
 {
     int signvalue = 0;
     const char *prefix = "";
     unsigned LLONG uvalue;
     char convert[DECIMAL_SIZE(value) + 3];
     int place = 0;
     int spadlen = 0;
     int zpadlen = 0;
     int caps = 0;
 
     if (max < 0)
         max = 0;
     uvalue = value;
     if (!(flags & DP_F_UNSIGNED)) {
         if (value < 0) {
             signvalue = '-';
-            uvalue = -value;
+            uvalue = -(unsigned LLONG)value;
         } else if (flags & DP_F_PLUS)
             signvalue = '+';
         else if (flags & DP_F_SPACE)
             signvalue = ' ';
     }
     if (flags & DP_F_NUM) {
         if (base == 8)
             prefix = "0";
         if (base == 16)
             prefix = "0x";
     }
     if (flags & DP_F_UP)
         caps = 1;
     do {
         convert[place++] = (caps ? "0123456789ABCDEF" : "0123456789abcdef")
             [uvalue % (unsigned)base];
         uvalue = (uvalue / (unsigned)base);
     } while (uvalue && (place < (int)sizeof(convert)));
     if (place == sizeof(convert))
         place--;
     convert[place] = 0;
 
     zpadlen = max - place;
     spadlen =
         min - OSSL_MAX(max, place) - (signvalue ? 1 : 0) - strlen(prefix);
     if (zpadlen < 0)
         zpadlen = 0;
     if (spadlen < 0)
         spadlen = 0;
     if (flags & DP_F_ZERO) {
         zpadlen = OSSL_MAX(zpadlen, spadlen);
         spadlen = 0;
     }
     if (flags & DP_F_MINUS)
         spadlen = -spadlen;
 
     /* spaces */
     while (spadlen > 0) {
         if(!doapr_outch(sbuffer, buffer, currlen, maxlen, ' '))
             return 0;
         --spadlen;
     }
 
     /* sign */
     if (signvalue)
         if(!doapr_outch(sbuffer, buffer, currlen, maxlen, signvalue))
             return 0;
 
     /* prefix */
     while (*prefix) {
         if(!doapr_outch(sbuffer, buffer, currlen, maxlen, *prefix))
             return 0;
         prefix++;
     }
 
     /* zeros */
     if (zpadlen > 0) {
         while (zpadlen > 0) {
             if(!doapr_outch(sbuffer, buffer, currlen, maxlen, '0'))
                 return 0;
             --zpadlen;
         }
     }
     /* digits */
     while (place > 0) {
         if (!doapr_outch(sbuffer, buffer, currlen, maxlen, convert[--place]))
             return 0;
     }
 
     /* left justified spaces */
     while (spadlen < 0) {
         if (!doapr_outch(sbuffer, buffer, currlen, maxlen, ' '))
             return 0;
         ++spadlen;
     }
     return 1;
 }
 
 static LDOUBLE abs_val(LDOUBLE value)
 {
     LDOUBLE result = value;
     if (value < 0)
         result = -value;
     return result;
 }
 
 static LDOUBLE pow_10(int in_exp)
 {
     LDOUBLE result = 1;
     while (in_exp) {
         result *= 10;
         in_exp--;
     }
     return result;
 }
 
 static long roundv(LDOUBLE value)
 {
     long intpart;
     intpart = (long)value;
     value = value - intpart;
     if (value >= 0.5)
         intpart++;
     return intpart;
 }
 
 static int
 fmtfp(char **sbuffer,
       char **buffer,
       size_t *currlen,
       size_t *maxlen, LDOUBLE fvalue, int min, int max, int flags)
 {
     int signvalue = 0;
     LDOUBLE ufvalue;
     char iconvert[20];
     char fconvert[20];
     int iplace = 0;
     int fplace = 0;
     int padlen = 0;
     int zpadlen = 0;
     long intpart;
     long fracpart;
     long max10;
 
     if (max < 0)
         max = 6;
     ufvalue = abs_val(fvalue);
     if (fvalue < 0)
         signvalue = '-';
     else if (flags & DP_F_PLUS)
         signvalue = '+';
     else if (flags & DP_F_SPACE)
         signvalue = ' ';
 
     intpart = (long)ufvalue;
 
     /*
      * sorry, we only support 9 digits past the decimal because of our
      * conversion method
      */
     if (max > 9)
         max = 9;
 
     /*
      * we "cheat" by converting the fractional part to integer by multiplying
      * by a factor of 10
      */
     max10 = roundv(pow_10(max));
     fracpart = roundv(pow_10(max) * (ufvalue - intpart));
 
     if (fracpart >= max10) {
         intpart++;
         fracpart -= max10;
     }
 
     /* convert integer part */
     do {
         iconvert[iplace++] = "0123456789"[intpart % 10];
         intpart = (intpart / 10);
     } while (intpart && (iplace < (int)sizeof(iconvert)));
     if (iplace == sizeof iconvert)
         iplace--;
     iconvert[iplace] = 0;
 
     /* convert fractional part */
     do {
         fconvert[fplace++] = "0123456789"[fracpart % 10];
         fracpart = (fracpart / 10);
     } while (fplace < max);
     if (fplace == sizeof fconvert)
         fplace--;
     fconvert[fplace] = 0;
 
     /* -1 for decimal point, another -1 if we are printing a sign */
     padlen = min - iplace - max - 1 - ((signvalue) ? 1 : 0);
     zpadlen = max - fplace;
     if (zpadlen < 0)
         zpadlen = 0;
     if (padlen < 0)
         padlen = 0;
     if (flags & DP_F_MINUS)
         padlen = -padlen;
 
     if ((flags & DP_F_ZERO) && (padlen > 0)) {
         if (signvalue) {
             if (!doapr_outch(sbuffer, buffer, currlen, maxlen, signvalue))
                 return 0;
             --padlen;
             signvalue = 0;
         }
         while (padlen > 0) {
             if (!doapr_outch(sbuffer, buffer, currlen, maxlen, '0'))
                 return 0;
             --padlen;
         }
     }
     while (padlen > 0) {
         if (!doapr_outch(sbuffer, buffer, currlen, maxlen, ' '))
             return 0;
         --padlen;
     }
     if (signvalue && !doapr_outch(sbuffer, buffer, currlen, maxlen, signvalue))
         return 0;
 
     while (iplace > 0) {
         if (!doapr_outch(sbuffer, buffer, currlen, maxlen, iconvert[--iplace]))
             return 0;
     }
 
     /*
      * Decimal point. This should probably use locale to find the correct
      * char to print out.
      */
     if (max > 0 || (flags & DP_F_NUM)) {
         if (!doapr_outch(sbuffer, buffer, currlen, maxlen, '.'))
             return 0;
 
         while (fplace > 0) {
             if(!doapr_outch(sbuffer, buffer, currlen, maxlen,
                             fconvert[--fplace]))
                 return 0;
         }
     }
     while (zpadlen > 0) {
         if (!doapr_outch(sbuffer, buffer, currlen, maxlen, '0'))
             return 0;
         --zpadlen;
     }
 
     while (padlen < 0) {
         if (!doapr_outch(sbuffer, buffer, currlen, maxlen, ' '))
             return 0;
         ++padlen;
     }
     return 1;
 }
 
 #define BUFFER_INC  1024
 
 static int
 doapr_outch(char **sbuffer,
             char **buffer, size_t *currlen, size_t *maxlen, int c)
 {
     /* If we haven't at least one buffer, someone has doe a big booboo */
     assert(*sbuffer != NULL || buffer != NULL);
 
     /* |currlen| must always be <= |*maxlen| */
     assert(*currlen <= *maxlen);
 
     if (buffer && *currlen == *maxlen) {
         if (*maxlen > INT_MAX - BUFFER_INC)
             return 0;
 
         *maxlen += BUFFER_INC;
         if (*buffer == NULL) {
             *buffer = OPENSSL_malloc(*maxlen);
             if (*buffer == NULL)
                 return 0;
             if (*currlen > 0) {
                 assert(*sbuffer != NULL);
                 memcpy(*buffer, *sbuffer, *currlen);
             }
             *sbuffer = NULL;
         } else {
             char *tmpbuf;
             tmpbuf = OPENSSL_realloc(*buffer, *maxlen);
             if (tmpbuf == NULL)
                 return 0;
             *buffer = tmpbuf;
         }
     }
 
     if (*currlen < *maxlen) {
         if (*sbuffer)
             (*sbuffer)[(*currlen)++] = (char)c;
         else
             (*buffer)[(*currlen)++] = (char)c;
     }
 
     return 1;
 }
 
 /***************************************************************************/
 
 int BIO_printf(BIO *bio, const char *format, ...)
 {
     va_list args;
     int ret;
 
     va_start(args, format);
 
     ret = BIO_vprintf(bio, format, args);
 
     va_end(args);
     return (ret);
 }
 
 int BIO_vprintf(BIO *bio, const char *format, va_list args)
 {
     int ret;
     size_t retlen;
     char hugebuf[1024 * 2];     /* Was previously 10k, which is unreasonable
                                  * in small-stack environments, like threads
                                  * or DOS programs. */
     char *hugebufp = hugebuf;
     size_t hugebufsize = sizeof(hugebuf);
     char *dynbuf = NULL;
     int ignored;
 
     dynbuf = NULL;
     CRYPTO_push_info("doapr()");
     if (!_dopr(&hugebufp, &dynbuf, &hugebufsize, &retlen, &ignored, format,
                 args)) {
         OPENSSL_free(dynbuf);
         return -1;
     }
     if (dynbuf) {
         ret = BIO_write(bio, dynbuf, (int)retlen);
         OPENSSL_free(dynbuf);
     } else {
         ret = BIO_write(bio, hugebuf, (int)retlen);
     }
     CRYPTO_pop_info();
     return (ret);
 }
 
 /*
  * As snprintf is not available everywhere, we provide our own
  * implementation. This function has nothing to do with BIOs, but it's
  * closely related to BIO_printf, and we need *some* name prefix ... (XXX the
  * function should be renamed, but to what?)
  */
 int BIO_snprintf(char *buf, size_t n, const char *format, ...)
 {
     va_list args;
     int ret;
 
     va_start(args, format);
 
     ret = BIO_vsnprintf(buf, n, format, args);
 
     va_end(args);
     return (ret);
 }
 
 int BIO_vsnprintf(char *buf, size_t n, const char *format, va_list args)
 {
     size_t retlen;
     int truncated;
 
     if(!_dopr(&buf, NULL, &n, &retlen, &truncated, format, args))
         return -1;
 
     if (truncated)
         /*
          * In case of truncation, return -1 like traditional snprintf.
          * (Current drafts for ISO/IEC 9899 say snprintf should return the
          * number of characters that would have been written, had the buffer
          * been large enough.)
          */
         return -1;
     else
         return (retlen <= INT_MAX) ? (int)retlen : -1;
 }
Index: vendor-crypto/openssl/dist/crypto/bio/bio_cb.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/bio/bio_cb.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/bio/bio_cb.c	(revision 318897)
@@ -1,145 +1,148 @@
 /* crypto/bio/bio_cb.c */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 
 #include 
 #include 
 #include 
 #include "cryptlib.h"
 #include 
 #include 
 
 long MS_CALLBACK BIO_debug_callback(BIO *bio, int cmd, const char *argp,
                                     int argi, long argl, long ret)
 {
     BIO *b;
     MS_STATIC char buf[256];
     char *p;
     long r = 1;
     int len;
     size_t p_maxlen;
 
     if (BIO_CB_RETURN & cmd)
         r = ret;
 
     len = BIO_snprintf(buf,sizeof buf,"BIO[%p]: ",(void *)bio);
 
+    /* Ignore errors and continue printing the other information. */
+    if (len < 0)
+        len = 0;
     p = buf + len;
     p_maxlen = sizeof(buf) - len;
 
     switch (cmd) {
     case BIO_CB_FREE:
         BIO_snprintf(p, p_maxlen, "Free - %s\n", bio->method->name);
         break;
     case BIO_CB_READ:
         if (bio->method->type & BIO_TYPE_DESCRIPTOR)
             BIO_snprintf(p, p_maxlen, "read(%d,%lu) - %s fd=%d\n",
                          bio->num, (unsigned long)argi,
                          bio->method->name, bio->num);
         else
             BIO_snprintf(p, p_maxlen, "read(%d,%lu) - %s\n",
                          bio->num, (unsigned long)argi, bio->method->name);
         break;
     case BIO_CB_WRITE:
         if (bio->method->type & BIO_TYPE_DESCRIPTOR)
             BIO_snprintf(p, p_maxlen, "write(%d,%lu) - %s fd=%d\n",
                          bio->num, (unsigned long)argi,
                          bio->method->name, bio->num);
         else
             BIO_snprintf(p, p_maxlen, "write(%d,%lu) - %s\n",
                          bio->num, (unsigned long)argi, bio->method->name);
         break;
     case BIO_CB_PUTS:
         BIO_snprintf(p, p_maxlen, "puts() - %s\n", bio->method->name);
         break;
     case BIO_CB_GETS:
         BIO_snprintf(p, p_maxlen, "gets(%lu) - %s\n", (unsigned long)argi,
                      bio->method->name);
         break;
     case BIO_CB_CTRL:
         BIO_snprintf(p, p_maxlen, "ctrl(%lu) - %s\n", (unsigned long)argi,
                      bio->method->name);
         break;
     case BIO_CB_RETURN | BIO_CB_READ:
         BIO_snprintf(p, p_maxlen, "read return %ld\n", ret);
         break;
     case BIO_CB_RETURN | BIO_CB_WRITE:
         BIO_snprintf(p, p_maxlen, "write return %ld\n", ret);
         break;
     case BIO_CB_RETURN | BIO_CB_GETS:
         BIO_snprintf(p, p_maxlen, "gets return %ld\n", ret);
         break;
     case BIO_CB_RETURN | BIO_CB_PUTS:
         BIO_snprintf(p, p_maxlen, "puts return %ld\n", ret);
         break;
     case BIO_CB_RETURN | BIO_CB_CTRL:
         BIO_snprintf(p, p_maxlen, "ctrl return %ld\n", ret);
         break;
     default:
         BIO_snprintf(p, p_maxlen, "bio callback - unknown type (%d)\n", cmd);
         break;
     }
 
     b = (BIO *)bio->cb_arg;
     if (b != NULL)
         BIO_write(b, buf, strlen(buf));
 #if !defined(OPENSSL_NO_STDIO) && !defined(OPENSSL_SYS_WIN16)
     else
         fputs(buf, stderr);
 #endif
     return (r);
 }
Index: vendor-crypto/openssl/dist/crypto/bio/bss_file.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/bio/bss_file.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/bio/bss_file.c	(revision 318897)
@@ -1,476 +1,484 @@
 /* crypto/bio/bss_file.c */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 
 /*-
  * 03-Dec-1997  rdenny@dc3.com  Fix bug preventing use of stdin/stdout
  *              with binary data (e.g. asn1parse -inform DER < xxx) under
  *              Windows
  */
 
 #ifndef HEADER_BSS_FILE_C
 # define HEADER_BSS_FILE_C
 
 # if defined(__linux) || defined(__sun) || defined(__hpux)
 /*
  * Following definition aliases fopen to fopen64 on above mentioned
  * platforms. This makes it possible to open and sequentially access files
  * larger than 2GB from 32-bit application. It does not allow to traverse
  * them beyond 2GB with fseek/ftell, but on the other hand *no* 32-bit
  * platform permits that, not with fseek/ftell. Not to mention that breaking
  * 2GB limit for seeking would require surgery to *our* API. But sequential
  * access suffices for practical cases when you can run into large files,
  * such as fingerprinting, so we can let API alone. For reference, the list
  * of 32-bit platforms which allow for sequential access of large files
  * without extra "magic" comprise *BSD, Darwin, IRIX...
  */
 #  ifndef _FILE_OFFSET_BITS
 #   define _FILE_OFFSET_BITS 64
 #  endif
 # endif
 
 # include 
 # include 
 # include "cryptlib.h"
 # include "bio_lcl.h"
 # include 
 
 # if defined(OPENSSL_SYS_NETWARE) && defined(NETWARE_CLIB)
 #  include 
 # endif
 
 # if !defined(OPENSSL_NO_STDIO)
 
 static int MS_CALLBACK file_write(BIO *h, const char *buf, int num);
 static int MS_CALLBACK file_read(BIO *h, char *buf, int size);
 static int MS_CALLBACK file_puts(BIO *h, const char *str);
 static int MS_CALLBACK file_gets(BIO *h, char *str, int size);
 static long MS_CALLBACK file_ctrl(BIO *h, int cmd, long arg1, void *arg2);
 static int MS_CALLBACK file_new(BIO *h);
 static int MS_CALLBACK file_free(BIO *data);
 static BIO_METHOD methods_filep = {
     BIO_TYPE_FILE,
     "FILE pointer",
     file_write,
     file_read,
     file_puts,
     file_gets,
     file_ctrl,
     file_new,
     file_free,
     NULL,
 };
 
 static FILE *file_fopen(const char *filename, const char *mode)
 {
     FILE *file = NULL;
 
 #  if defined(_WIN32) && defined(CP_UTF8)
     int sz, len_0 = (int)strlen(filename) + 1;
     DWORD flags;
 
     /*
      * Basically there are three cases to cover: a) filename is
      * pure ASCII string; b) actual UTF-8 encoded string and
      * c) locale-ized string, i.e. one containing 8-bit
      * characters that are meaningful in current system locale.
      * If filename is pure ASCII or real UTF-8 encoded string,
      * MultiByteToWideChar succeeds and _wfopen works. If
      * filename is locale-ized string, chances are that
      * MultiByteToWideChar fails reporting
      * ERROR_NO_UNICODE_TRANSLATION, in which case we fall
      * back to fopen...
      */
     if ((sz = MultiByteToWideChar(CP_UTF8, (flags = MB_ERR_INVALID_CHARS),
                                   filename, len_0, NULL, 0)) > 0 ||
         (GetLastError() == ERROR_INVALID_FLAGS &&
          (sz = MultiByteToWideChar(CP_UTF8, (flags = 0),
                                    filename, len_0, NULL, 0)) > 0)
         ) {
         WCHAR wmode[8];
         WCHAR *wfilename = _alloca(sz * sizeof(WCHAR));
 
         if (MultiByteToWideChar(CP_UTF8, flags,
                                 filename, len_0, wfilename, sz) &&
             MultiByteToWideChar(CP_UTF8, 0, mode, strlen(mode) + 1,
                                 wmode, sizeof(wmode) / sizeof(wmode[0])) &&
             (file = _wfopen(wfilename, wmode)) == NULL &&
             (errno == ENOENT || errno == EBADF)
             ) {
             /*
              * UTF-8 decode succeeded, but no file, filename
              * could still have been locale-ized...
              */
             file = fopen(filename, mode);
         }
     } else if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION) {
         file = fopen(filename, mode);
     }
 #  else
     file = fopen(filename, mode);
 #  endif
     return (file);
 }
 
 BIO *BIO_new_file(const char *filename, const char *mode)
 {
     BIO  *ret;
     FILE *file = file_fopen(filename, mode);
 
     if (file == NULL) {
         SYSerr(SYS_F_FOPEN, get_last_sys_error());
         ERR_add_error_data(5, "fopen('", filename, "','", mode, "')");
         if (errno == ENOENT
 # ifdef ENXIO
             || errno == ENXIO
 # endif
             )
             BIOerr(BIO_F_BIO_NEW_FILE, BIO_R_NO_SUCH_FILE);
         else
             BIOerr(BIO_F_BIO_NEW_FILE, ERR_R_SYS_LIB);
         return (NULL);
     }
     if ((ret = BIO_new(BIO_s_file())) == NULL) {
         fclose(file);
         return (NULL);
     }
 
     BIO_clear_flags(ret, BIO_FLAGS_UPLINK); /* we did fopen -> we disengage
                                              * UPLINK */
     BIO_set_fp(ret, file, BIO_CLOSE);
     return (ret);
 }
 
 BIO *BIO_new_fp(FILE *stream, int close_flag)
 {
     BIO *ret;
 
     if ((ret = BIO_new(BIO_s_file())) == NULL)
         return (NULL);
 
     BIO_set_flags(ret, BIO_FLAGS_UPLINK); /* redundant, left for
                                            * documentation puposes */
     BIO_set_fp(ret, stream, close_flag);
     return (ret);
 }
 
 BIO_METHOD *BIO_s_file(void)
 {
     return (&methods_filep);
 }
 
 static int MS_CALLBACK file_new(BIO *bi)
 {
     bi->init = 0;
     bi->num = 0;
     bi->ptr = NULL;
     bi->flags = BIO_FLAGS_UPLINK; /* default to UPLINK */
     return (1);
 }
 
 static int MS_CALLBACK file_free(BIO *a)
 {
     if (a == NULL)
         return (0);
     if (a->shutdown) {
         if ((a->init) && (a->ptr != NULL)) {
             if (a->flags & BIO_FLAGS_UPLINK)
                 UP_fclose(a->ptr);
             else
                 fclose(a->ptr);
             a->ptr = NULL;
             a->flags = BIO_FLAGS_UPLINK;
         }
         a->init = 0;
     }
     return (1);
 }
 
 static int MS_CALLBACK file_read(BIO *b, char *out, int outl)
 {
     int ret = 0;
 
     if (b->init && (out != NULL)) {
         if (b->flags & BIO_FLAGS_UPLINK)
             ret = UP_fread(out, 1, (int)outl, b->ptr);
         else
             ret = fread(out, 1, (int)outl, (FILE *)b->ptr);
         if (ret == 0
             && (b->flags & BIO_FLAGS_UPLINK) ? UP_ferror((FILE *)b->ptr) :
-            ferror((FILE *)b->ptr)) {
+                                               ferror((FILE *)b->ptr)) {
             SYSerr(SYS_F_FREAD, get_last_sys_error());
             BIOerr(BIO_F_FILE_READ, ERR_R_SYS_LIB);
             ret = -1;
         }
     }
     return (ret);
 }
 
 static int MS_CALLBACK file_write(BIO *b, const char *in, int inl)
 {
     int ret = 0;
 
     if (b->init && (in != NULL)) {
         if (b->flags & BIO_FLAGS_UPLINK)
             ret = UP_fwrite(in, (int)inl, 1, b->ptr);
         else
             ret = fwrite(in, (int)inl, 1, (FILE *)b->ptr);
         if (ret)
             ret = inl;
         /* ret=fwrite(in,1,(int)inl,(FILE *)b->ptr); */
         /*
          * according to Tim Hudson , the commented out
          * version above can cause 'inl' write calls under some stupid stdio
          * implementations (VMS)
          */
     }
     return (ret);
 }
 
 static long MS_CALLBACK file_ctrl(BIO *b, int cmd, long num, void *ptr)
 {
     long ret = 1;
     FILE *fp = (FILE *)b->ptr;
     FILE **fpp;
     char p[4];
+    int st;
 
     switch (cmd) {
     case BIO_C_FILE_SEEK:
     case BIO_CTRL_RESET:
         if (b->flags & BIO_FLAGS_UPLINK)
             ret = (long)UP_fseek(b->ptr, num, 0);
         else
             ret = (long)fseek(fp, num, 0);
         break;
     case BIO_CTRL_EOF:
         if (b->flags & BIO_FLAGS_UPLINK)
             ret = (long)UP_feof(fp);
         else
             ret = (long)feof(fp);
         break;
     case BIO_C_FILE_TELL:
     case BIO_CTRL_INFO:
         if (b->flags & BIO_FLAGS_UPLINK)
             ret = UP_ftell(b->ptr);
         else
             ret = ftell(fp);
         break;
     case BIO_C_SET_FILE_PTR:
         file_free(b);
         b->shutdown = (int)num & BIO_CLOSE;
         b->ptr = ptr;
         b->init = 1;
 #  if BIO_FLAGS_UPLINK!=0
 #   if defined(__MINGW32__) && defined(__MSVCRT__) && !defined(_IOB_ENTRIES)
 #    define _IOB_ENTRIES 20
 #   endif
-#   if defined(_IOB_ENTRIES)
         /* Safety net to catch purely internal BIO_set_fp calls */
+#   if defined(_MSC_VER) && _MSC_VER>=1900
+        if (ptr == stdin || ptr == stdout || ptr == stderr)
+            BIO_clear_flags(b, BIO_FLAGS_UPLINK);
+#   elif defined(_IOB_ENTRIES)
         if ((size_t)ptr >= (size_t)stdin &&
             (size_t)ptr < (size_t)(stdin + _IOB_ENTRIES))
             BIO_clear_flags(b, BIO_FLAGS_UPLINK);
 #   endif
 #  endif
 #  ifdef UP_fsetmod
         if (b->flags & BIO_FLAGS_UPLINK)
             UP_fsetmod(b->ptr, (char)((num & BIO_FP_TEXT) ? 't' : 'b'));
         else
 #  endif
         {
 #  if defined(OPENSSL_SYS_WINDOWS)
             int fd = _fileno((FILE *)ptr);
             if (num & BIO_FP_TEXT)
                 _setmode(fd, _O_TEXT);
             else
                 _setmode(fd, _O_BINARY);
 #  elif defined(OPENSSL_SYS_NETWARE) && defined(NETWARE_CLIB)
             int fd = fileno((FILE *)ptr);
             /* Under CLib there are differences in file modes */
             if (num & BIO_FP_TEXT)
                 setmode(fd, O_TEXT);
             else
                 setmode(fd, O_BINARY);
 #  elif defined(OPENSSL_SYS_MSDOS)
             int fd = fileno((FILE *)ptr);
             /* Set correct text/binary mode */
             if (num & BIO_FP_TEXT)
                 _setmode(fd, _O_TEXT);
             /* Dangerous to set stdin/stdout to raw (unless redirected) */
             else {
                 if (fd == STDIN_FILENO || fd == STDOUT_FILENO) {
                     if (isatty(fd) <= 0)
                         _setmode(fd, _O_BINARY);
                 } else
                     _setmode(fd, _O_BINARY);
             }
 #  elif defined(OPENSSL_SYS_OS2) || defined(OPENSSL_SYS_WIN32_CYGWIN)
             int fd = fileno((FILE *)ptr);
             if (num & BIO_FP_TEXT)
                 setmode(fd, O_TEXT);
             else
                 setmode(fd, O_BINARY);
 #  endif
         }
         break;
     case BIO_C_SET_FILENAME:
         file_free(b);
         b->shutdown = (int)num & BIO_CLOSE;
         if (num & BIO_FP_APPEND) {
             if (num & BIO_FP_READ)
                 BUF_strlcpy(p, "a+", sizeof p);
             else
                 BUF_strlcpy(p, "a", sizeof p);
         } else if ((num & BIO_FP_READ) && (num & BIO_FP_WRITE))
             BUF_strlcpy(p, "r+", sizeof p);
         else if (num & BIO_FP_WRITE)
             BUF_strlcpy(p, "w", sizeof p);
         else if (num & BIO_FP_READ)
             BUF_strlcpy(p, "r", sizeof p);
         else {
             BIOerr(BIO_F_FILE_CTRL, BIO_R_BAD_FOPEN_MODE);
             ret = 0;
             break;
         }
 #  if defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_OS2) || defined(OPENSSL_SYS_WIN32_CYGWIN)
         if (!(num & BIO_FP_TEXT))
             strcat(p, "b");
         else
             strcat(p, "t");
 #  endif
 #  if defined(OPENSSL_SYS_NETWARE)
         if (!(num & BIO_FP_TEXT))
             strcat(p, "b");
         else
             strcat(p, "t");
 #  endif
         fp = file_fopen(ptr, p);
         if (fp == NULL) {
             SYSerr(SYS_F_FOPEN, get_last_sys_error());
             ERR_add_error_data(5, "fopen('", ptr, "','", p, "')");
             BIOerr(BIO_F_FILE_CTRL, ERR_R_SYS_LIB);
             ret = 0;
             break;
         }
         b->ptr = fp;
         b->init = 1;
         BIO_clear_flags(b, BIO_FLAGS_UPLINK); /* we did fopen -> we disengage
                                                * UPLINK */
         break;
     case BIO_C_GET_FILE_PTR:
         /* the ptr parameter is actually a FILE ** in this case. */
         if (ptr != NULL) {
             fpp = (FILE **)ptr;
             *fpp = (FILE *)b->ptr;
         }
         break;
     case BIO_CTRL_GET_CLOSE:
         ret = (long)b->shutdown;
         break;
     case BIO_CTRL_SET_CLOSE:
         b->shutdown = (int)num;
         break;
     case BIO_CTRL_FLUSH:
-        if (b->flags & BIO_FLAGS_UPLINK)
-            UP_fflush(b->ptr);
-        else
-            fflush((FILE *)b->ptr);
+        st = b->flags & BIO_FLAGS_UPLINK
+                ? UP_fflush(b->ptr) : fflush((FILE *)b->ptr);
+        if (st == EOF) {
+            SYSerr(SYS_F_FFLUSH, get_last_sys_error());
+            ERR_add_error_data(1, "fflush()");
+            BIOerr(BIO_F_FILE_CTRL, ERR_R_SYS_LIB);
+            ret = 0;
+        }
         break;
     case BIO_CTRL_DUP:
         ret = 1;
         break;
 
     case BIO_CTRL_WPENDING:
     case BIO_CTRL_PENDING:
     case BIO_CTRL_PUSH:
     case BIO_CTRL_POP:
     default:
         ret = 0;
         break;
     }
     return (ret);
 }
 
 static int MS_CALLBACK file_gets(BIO *bp, char *buf, int size)
 {
     int ret = 0;
 
     buf[0] = '\0';
     if (bp->flags & BIO_FLAGS_UPLINK) {
         if (!UP_fgets(buf, size, bp->ptr))
             goto err;
     } else {
         if (!fgets(buf, size, (FILE *)bp->ptr))
             goto err;
     }
     if (buf[0] != '\0')
         ret = strlen(buf);
  err:
     return (ret);
 }
 
 static int MS_CALLBACK file_puts(BIO *bp, const char *str)
 {
     int n, ret;
 
     n = strlen(str);
     ret = file_write(bp, str, n);
     return (ret);
 }
 
 # endif                         /* OPENSSL_NO_STDIO */
 
 #endif                          /* HEADER_BSS_FILE_C */
Index: vendor-crypto/openssl/dist/crypto/bn/Makefile
===================================================================
--- vendor-crypto/openssl/dist/crypto/bn/Makefile	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/bn/Makefile	(revision 318897)
@@ -1,389 +1,389 @@
 #
 # OpenSSL/crypto/bn/Makefile
 #
 
 DIR=	bn
 TOP=	../..
 CC=	cc
 CPP=    $(CC) -E
 INCLUDES= -I.. -I$(TOP) -I../../include
 CFLAG=-g
 MAKEFILE=	Makefile
 AR=		ar r
 
 BN_ASM=		bn_asm.o
 
 CFLAGS= $(INCLUDES) $(CFLAG)
 ASFLAGS= $(INCLUDES) $(ASFLAG)
 AFLAGS= $(ASFLAGS)
 
 GENERAL=Makefile
 TEST=bntest.c exptest.c
 APPS=
 
 LIB=$(TOP)/libcrypto.a
 LIBSRC=	bn_add.c bn_div.c bn_exp.c bn_lib.c bn_ctx.c bn_mul.c bn_mod.c \
 	bn_print.c bn_rand.c bn_shift.c bn_word.c bn_blind.c \
 	bn_kron.c bn_sqrt.c bn_gcd.c bn_prime.c bn_err.c bn_sqr.c bn_asm.c \
 	bn_recp.c bn_mont.c bn_mpi.c bn_exp2.c bn_gf2m.c bn_nist.c \
 	bn_depr.c bn_const.c bn_x931p.c
 
 LIBOBJ=	bn_add.o bn_div.o bn_exp.o bn_lib.o bn_ctx.o bn_mul.o bn_mod.o \
 	bn_print.o bn_rand.o bn_shift.o bn_word.o bn_blind.o \
 	bn_kron.o bn_sqrt.o bn_gcd.o bn_prime.o bn_err.o bn_sqr.o $(BN_ASM) \
 	bn_recp.o bn_mont.o bn_mpi.o bn_exp2.o bn_gf2m.o bn_nist.o \
 	bn_depr.o bn_const.o bn_x931p.o
 
 SRC= $(LIBSRC)
 
 EXHEADER= bn.h
 HEADER=	bn_lcl.h bn_prime.h $(EXHEADER)
 
 ALL=    $(GENERAL) $(SRC) $(HEADER)
 
 top:
 	(cd ../..; $(MAKE) DIRS=crypto SDIRS=$(DIR) sub_all)
 
 all:	lib
 
 bn_prime.h: bn_prime.pl
 	$(PERL) bn_prime.pl >bn_prime.h
 
 divtest: divtest.c ../../libcrypto.a
 	cc -I../../include divtest.c -o divtest ../../libcrypto.a
 
 bnbug: bnbug.c ../../libcrypto.a top
 	cc -g -I../../include bnbug.c -o bnbug ../../libcrypto.a
 
 lib:	$(LIBOBJ)
 	$(AR) $(LIB) $(LIBOBJ)
 	$(RANLIB) $(LIB) || echo Never mind.
 	@touch lib
 
 bn-586.s:	asm/bn-586.pl ../perlasm/x86asm.pl
 	$(PERL) asm/bn-586.pl $(PERLASM_SCHEME) $(CFLAGS) $(PROCESSOR) > $@
 co-586.s:	asm/co-586.pl ../perlasm/x86asm.pl
 	$(PERL) asm/co-586.pl $(PERLASM_SCHEME) $(CFLAGS) $(PROCESSOR) > $@
 x86-mont.s:	asm/x86-mont.pl ../perlasm/x86asm.pl
 	$(PERL) asm/x86-mont.pl $(PERLASM_SCHEME) $(CFLAGS) $(PROCESSOR) > $@
 x86-gf2m.s:	asm/x86-gf2m.pl ../perlasm/x86asm.pl
 	$(PERL) asm/x86-gf2m.pl $(PERLASM_SCHEME) $(CFLAGS) $(PROCESSOR) > $@
 
 sparcv8.o:	asm/sparcv8.S
 	$(CC) $(CFLAGS) -c asm/sparcv8.S
 bn-sparcv9.o:	asm/sparcv8plus.S
 	$(CC) $(CFLAGS) -c -o $@ asm/sparcv8plus.S
 sparcv9a-mont.s:	asm/sparcv9a-mont.pl
 	$(PERL) asm/sparcv9a-mont.pl $(CFLAGS) > $@
 sparcv9-mont.s:		asm/sparcv9-mont.pl
 	$(PERL) asm/sparcv9-mont.pl $(CFLAGS) > $@
 vis3-mont.s:		asm/vis3-mont.pl
 	$(PERL) asm/vis3-mont.pl $(CFLAGS) > $@
 sparct4-mont.S:	asm/sparct4-mont.pl
 	$(PERL) asm/sparct4-mont.pl $(CFLAGS) > $@
 sparcv9-gf2m.S:	asm/sparcv9-gf2m.pl
 	$(PERL) asm/sparcv9-gf2m.pl $(CFLAGS) > $@
 
 bn-mips3.o:	asm/mips3.s
 	@if [ "$(CC)" = "gcc" ]; then \
 		ABI=`expr "$(CFLAGS)" : ".*-mabi=\([n3264]*\)"` && \
 		as -$$ABI -O -o $@ asm/mips3.s; \
 	else	$(CC) -c $(CFLAGS) -o $@ asm/mips3.s; fi
 
 bn-mips.s:	asm/mips.pl
 	$(PERL) asm/mips.pl $(PERLASM_SCHEME) $@
 mips-mont.s:	asm/mips-mont.pl
 	$(PERL)	asm/mips-mont.pl $(PERLASM_SCHEME) $@
 
 bn-s390x.o:	asm/s390x.S
 	$(CC) $(CFLAGS) -c -o $@ asm/s390x.S
 s390x-gf2m.s:	asm/s390x-gf2m.pl
 	$(PERL) asm/s390x-gf2m.pl $(PERLASM_SCHEME) $@
 
 x86_64-gcc.o:	asm/x86_64-gcc.c
 	$(CC) $(CFLAGS) -c -o $@ asm/x86_64-gcc.c
 x86_64-mont.s:	asm/x86_64-mont.pl
 	$(PERL) asm/x86_64-mont.pl $(PERLASM_SCHEME) > $@
 x86_64-mont5.s:	asm/x86_64-mont5.pl
 	$(PERL) asm/x86_64-mont5.pl $(PERLASM_SCHEME) > $@
 x86_64-gf2m.s:	asm/x86_64-gf2m.pl
 	$(PERL) asm/x86_64-gf2m.pl $(PERLASM_SCHEME) > $@
 rsaz-x86_64.s:	asm/rsaz-x86_64.pl
 	$(PERL) asm/rsaz-x86_64.pl $(PERLASM_SCHEME) > $@
 rsaz-avx2.s:	asm/rsaz-avx2.pl 
 	$(PERL) asm/rsaz-avx2.pl $(PERLASM_SCHEME) > $@
 
 bn-ia64.s:	asm/ia64.S
 	$(CC) $(CFLAGS) -E asm/ia64.S > $@
 ia64-mont.s:	asm/ia64-mont.pl
 	$(PERL) asm/ia64-mont.pl $@ $(CFLAGS)
 
 # GNU assembler fails to compile PA-RISC2 modules, insist on calling
 # vendor assembler...
 pa-risc2W.o: asm/pa-risc2W.s
 	/usr/ccs/bin/as -o pa-risc2W.o asm/pa-risc2W.s
 pa-risc2.o: asm/pa-risc2.s
 	/usr/ccs/bin/as -o pa-risc2.o asm/pa-risc2.s
 parisc-mont.s:	asm/parisc-mont.pl
 	$(PERL) asm/parisc-mont.pl $(PERLASM_SCHEME) $@
 
 # ppc - AIX, Linux, MacOS X...
 bn-ppc.s:	asm/ppc.pl;	$(PERL) asm/ppc.pl $(PERLASM_SCHEME) $@
 ppc-mont.s:	asm/ppc-mont.pl;$(PERL) asm/ppc-mont.pl $(PERLASM_SCHEME) $@
 ppc64-mont.s:	asm/ppc64-mont.pl;$(PERL) asm/ppc64-mont.pl $(PERLASM_SCHEME) $@
 
 alpha-mont.s:	asm/alpha-mont.pl
 	(preproc=$$$$.$@.S; trap "rm $$preproc" INT; \
 	$(PERL) asm/alpha-mont.pl > $$preproc && \
 	$(CC) -E -P $$preproc > $@ && rm $$preproc)
 
 # GNU make "catch all"
 %-mont.S:	asm/%-mont.pl;	$(PERL) $< $(PERLASM_SCHEME) $@
 %-gf2m.S:	asm/%-gf2m.pl;	$(PERL) $< $(PERLASM_SCHEME) $@
 
 armv4-mont.o:	armv4-mont.S
 armv4-gf2m.o:	armv4-gf2m.S
 
 files:
 	$(PERL) $(TOP)/util/files.pl Makefile >> $(TOP)/MINFO
 
 links:
 	@$(PERL) $(TOP)/util/mklink.pl ../../include/openssl $(EXHEADER)
 	@$(PERL) $(TOP)/util/mklink.pl ../../test $(TEST)
 	@$(PERL) $(TOP)/util/mklink.pl ../../apps $(APPS)
 
 install:
 	@[ -n "$(INSTALLTOP)" ] # should be set by top Makefile...
 	@headerlist="$(EXHEADER)"; for i in $$headerlist ; \
 	do  \
 	(cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i; \
 	chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i ); \
 	done;
 
 exptest:
 	rm -f exptest
 	gcc -I../../include -g2 -ggdb -o exptest exptest.c ../../libcrypto.a
 
 div:
 	rm -f a.out
 	gcc -I.. -g div.c ../../libcrypto.a
 
 tags:
 	ctags $(SRC)
 
 tests:
 
 lint:
 	lint -DLINT $(INCLUDES) $(SRC)>fluff
 
 update: bn_prime.h depend
 
 depend:
 	@[ -n "$(MAKEDEPEND)" ] # should be set by upper Makefile...
 	$(MAKEDEPEND) -- $(CFLAG) $(INCLUDES) $(DEPFLAG) -- $(PROGS) $(LIBSRC)
 
 dclean:
 	$(PERL) -pe 'if (/^# DO NOT DELETE THIS LINE/) {print; exit(0);}' $(MAKEFILE) >Makefile.new
 	mv -f Makefile.new $(MAKEFILE)
 
 clean:
-	rm -f *.s *.o *.obj lib tags core .pure .nfs* *.old *.bak fluff
+	rm -f *.s *.S *.o *.obj lib tags core .pure .nfs* *.old *.bak fluff
 
 # DO NOT DELETE THIS LINE -- make depend depends on it.
 
 bn_add.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_add.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_add.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_add.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_add.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_add.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_add.o: ../../include/openssl/symhacks.h ../cryptlib.h bn_add.c bn_lcl.h
 bn_asm.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_asm.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_asm.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_asm.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_asm.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_asm.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_asm.o: ../../include/openssl/symhacks.h ../cryptlib.h bn_asm.c bn_lcl.h
 bn_blind.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_blind.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_blind.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_blind.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_blind.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_blind.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_blind.o: ../../include/openssl/symhacks.h ../cryptlib.h bn_blind.c bn_lcl.h
 bn_const.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
 bn_const.o: ../../include/openssl/opensslconf.h
 bn_const.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_const.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_const.o: ../../include/openssl/symhacks.h bn.h bn_const.c
 bn_ctx.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_ctx.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_ctx.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_ctx.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_ctx.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_ctx.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_ctx.o: ../../include/openssl/symhacks.h ../cryptlib.h bn_ctx.c bn_lcl.h
 bn_depr.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_depr.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_depr.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_depr.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_depr.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_depr.o: ../../include/openssl/rand.h ../../include/openssl/safestack.h
 bn_depr.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 bn_depr.o: ../cryptlib.h bn_depr.c bn_lcl.h
 bn_div.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_div.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_div.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_div.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_div.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_div.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_div.o: ../../include/openssl/symhacks.h ../cryptlib.h bn_div.c bn_lcl.h
 bn_err.o: ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_err.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
 bn_err.o: ../../include/openssl/err.h ../../include/openssl/lhash.h
 bn_err.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h
 bn_err.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h
 bn_err.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 bn_err.o: bn_err.c
 bn_exp.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_exp.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_exp.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_exp.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_exp.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_exp.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_exp.o: ../../include/openssl/symhacks.h ../constant_time_locl.h
 bn_exp.o: ../cryptlib.h bn_exp.c bn_lcl.h rsaz_exp.h
 bn_exp2.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_exp2.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_exp2.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_exp2.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_exp2.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_exp2.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_exp2.o: ../../include/openssl/symhacks.h ../cryptlib.h bn_exp2.c bn_lcl.h
 bn_gcd.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_gcd.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_gcd.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_gcd.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_gcd.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_gcd.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_gcd.o: ../../include/openssl/symhacks.h ../cryptlib.h bn_gcd.c bn_lcl.h
 bn_gf2m.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_gf2m.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_gf2m.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_gf2m.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_gf2m.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_gf2m.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_gf2m.o: ../../include/openssl/symhacks.h ../cryptlib.h bn_gf2m.c bn_lcl.h
 bn_kron.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_kron.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_kron.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_kron.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_kron.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_kron.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_kron.o: ../../include/openssl/symhacks.h ../cryptlib.h bn_kron.c bn_lcl.h
 bn_lib.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_lib.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_lib.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_lib.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_lib.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_lib.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_lib.o: ../../include/openssl/symhacks.h ../cryptlib.h bn_lcl.h bn_lib.c
 bn_mod.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_mod.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_mod.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_mod.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_mod.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_mod.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_mod.o: ../../include/openssl/symhacks.h ../cryptlib.h bn_lcl.h bn_mod.c
 bn_mont.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_mont.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_mont.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_mont.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_mont.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_mont.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_mont.o: ../../include/openssl/symhacks.h ../cryptlib.h bn_lcl.h bn_mont.c
 bn_mpi.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_mpi.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_mpi.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_mpi.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_mpi.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_mpi.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_mpi.o: ../../include/openssl/symhacks.h ../cryptlib.h bn_lcl.h bn_mpi.c
 bn_mul.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_mul.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_mul.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_mul.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_mul.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_mul.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_mul.o: ../../include/openssl/symhacks.h ../cryptlib.h bn_lcl.h bn_mul.c
 bn_nist.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_nist.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_nist.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_nist.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_nist.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_nist.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_nist.o: ../../include/openssl/symhacks.h ../cryptlib.h bn_lcl.h bn_nist.c
 bn_prime.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_prime.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_prime.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_prime.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_prime.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_prime.o: ../../include/openssl/rand.h ../../include/openssl/safestack.h
 bn_prime.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 bn_prime.o: ../cryptlib.h bn_lcl.h bn_prime.c bn_prime.h
 bn_print.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_print.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_print.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_print.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_print.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_print.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_print.o: ../../include/openssl/symhacks.h ../cryptlib.h bn_lcl.h bn_print.c
 bn_rand.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_rand.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_rand.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_rand.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_rand.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_rand.o: ../../include/openssl/rand.h ../../include/openssl/safestack.h
 bn_rand.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 bn_rand.o: ../cryptlib.h bn_lcl.h bn_rand.c
 bn_recp.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_recp.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_recp.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_recp.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_recp.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_recp.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_recp.o: ../../include/openssl/symhacks.h ../cryptlib.h bn_lcl.h bn_recp.c
 bn_shift.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_shift.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_shift.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_shift.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_shift.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_shift.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_shift.o: ../../include/openssl/symhacks.h ../cryptlib.h bn_lcl.h bn_shift.c
 bn_sqr.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_sqr.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_sqr.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_sqr.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_sqr.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_sqr.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_sqr.o: ../../include/openssl/symhacks.h ../cryptlib.h bn_lcl.h bn_sqr.c
 bn_sqrt.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_sqrt.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_sqrt.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_sqrt.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_sqrt.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_sqrt.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_sqrt.o: ../../include/openssl/symhacks.h ../cryptlib.h bn_lcl.h bn_sqrt.c
 bn_word.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h
 bn_word.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 bn_word.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 bn_word.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 bn_word.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_word.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_word.o: ../../include/openssl/symhacks.h ../cryptlib.h bn_lcl.h bn_word.c
 bn_x931p.o: ../../include/openssl/bn.h ../../include/openssl/crypto.h
 bn_x931p.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
 bn_x931p.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 bn_x931p.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 bn_x931p.o: ../../include/openssl/symhacks.h bn_x931p.c
Index: vendor-crypto/openssl/dist/crypto/bn/asm/sparcv9-mont.pl
===================================================================
--- vendor-crypto/openssl/dist/crypto/bn/asm/sparcv9-mont.pl	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/bn/asm/sparcv9-mont.pl	(revision 318897)
@@ -1,606 +1,609 @@
 #!/usr/bin/env perl
 
 # ====================================================================
 # Written by Andy Polyakov  for the OpenSSL
 # project. The module is, however, dual licensed under OpenSSL and
 # CRYPTOGAMS licenses depending on where you obtain it. For further
 # details see http://www.openssl.org/~appro/cryptogams/.
 # ====================================================================
 
 # December 2005
 #
 # Pure SPARCv9/8+ and IALU-only bn_mul_mont implementation. The reasons
 # for undertaken effort are multiple. First of all, UltraSPARC is not
 # the whole SPARCv9 universe and other VIS-free implementations deserve
 # optimized code as much. Secondly, newly introduced UltraSPARC T1,
 # a.k.a. Niagara, has shared FPU and concurrent FPU-intensive pathes,
 # such as sparcv9a-mont, will simply sink it. Yes, T1 is equipped with
 # several integrated RSA/DSA accelerator circuits accessible through
 # kernel driver [only(*)], but having decent user-land software
 # implementation is important too. Finally, reasons like desire to
 # experiment with dedicated squaring procedure. Yes, this module
 # implements one, because it was easiest to draft it in SPARCv9
 # instructions...
 
 # (*)	Engine accessing the driver in question is on my TODO list.
 #	For reference, acceleator is estimated to give 6 to 10 times
 #	improvement on single-threaded RSA sign. It should be noted
 #	that 6-10x improvement coefficient does not actually mean
 #	something extraordinary in terms of absolute [single-threaded]
 #	performance, as SPARCv9 instruction set is by all means least
 #	suitable for high performance crypto among other 64 bit
 #	platforms. 6-10x factor simply places T1 in same performance
 #	domain as say AMD64 and IA-64. Improvement of RSA verify don't
 #	appear impressive at all, but it's the sign operation which is
 #	far more critical/interesting.
 
 # You might notice that inner loops are modulo-scheduled:-) This has
 # essentially negligible impact on UltraSPARC performance, it's
 # Fujitsu SPARC64 V users who should notice and hopefully appreciate
 # the advantage... Currently this module surpasses sparcv9a-mont.pl
 # by ~20% on UltraSPARC-III and later cores, but recall that sparcv9a
 # module still have hidden potential [see TODO list there], which is
 # estimated to be larger than 20%...
 
 # int bn_mul_mont(
 $rp="%i0";	# BN_ULONG *rp,
 $ap="%i1";	# const BN_ULONG *ap,
 $bp="%i2";	# const BN_ULONG *bp,
 $np="%i3";	# const BN_ULONG *np,
 $n0="%i4";	# const BN_ULONG *n0,
 $num="%i5";	# int num);
 
 $bits=32;
 for (@ARGV)	{ $bits=64 if (/\-m64/ || /\-xarch\=v9/); }
 if ($bits==64)	{ $bias=2047; $frame=192; }
 else		{ $bias=0;    $frame=128; }
 
 $car0="%o0";
 $car1="%o1";
 $car2="%o2";	# 1 bit
 $acc0="%o3";
 $acc1="%o4";
 $mask="%g1";	# 32 bits, what a waste...
 $tmp0="%g4";
 $tmp1="%g5";
 
 $i="%l0";
 $j="%l1";
 $mul0="%l2";
 $mul1="%l3";
 $tp="%l4";
 $apj="%l5";
 $npj="%l6";
 $tpj="%l7";
 
 $fname="bn_mul_mont_int";
 
 $code=<<___;
 .section	".text",#alloc,#execinstr
 
 .global	$fname
 .align	32
 $fname:
 	cmp	%o5,4			! 128 bits minimum
 	bge,pt	%icc,.Lenter
 	sethi	%hi(0xffffffff),$mask
 	retl
 	clr	%o0
 .align	32
 .Lenter:
 	save	%sp,-$frame,%sp
 	sll	$num,2,$num		! num*=4
 	or	$mask,%lo(0xffffffff),$mask
 	ld	[$n0],$n0
 	cmp	$ap,$bp
 	and	$num,$mask,$num
 	ld	[$bp],$mul0		! bp[0]
 	nop
 
 	add	%sp,$bias,%o7		! real top of stack
 	ld	[$ap],$car0		! ap[0] ! redundant in squaring context
 	sub	%o7,$num,%o7
 	ld	[$ap+4],$apj		! ap[1]
 	and	%o7,-1024,%o7
 	ld	[$np],$car1		! np[0]
 	sub	%o7,$bias,%sp		! alloca
 	ld	[$np+4],$npj		! np[1]
 	be,pt	`$bits==32?"%icc":"%xcc"`,.Lbn_sqr_mont
 	mov	12,$j
 
 	mulx	$car0,$mul0,$car0	! ap[0]*bp[0]
 	mulx	$apj,$mul0,$tmp0	!prologue! ap[1]*bp[0]
 	and	$car0,$mask,$acc0
 	add	%sp,$bias+$frame,$tp
 	ld	[$ap+8],$apj		!prologue!
 
 	mulx	$n0,$acc0,$mul1		! "t[0]"*n0
 	and	$mul1,$mask,$mul1
 
 	mulx	$car1,$mul1,$car1	! np[0]*"t[0]"*n0
 	mulx	$npj,$mul1,$acc1	!prologue! np[1]*"t[0]"*n0
 	srlx	$car0,32,$car0
 	add	$acc0,$car1,$car1
 	ld	[$np+8],$npj		!prologue!
 	srlx	$car1,32,$car1
 	mov	$tmp0,$acc0		!prologue!
 
 .L1st:
 	mulx	$apj,$mul0,$tmp0
 	mulx	$npj,$mul1,$tmp1
 	add	$acc0,$car0,$car0
 	ld	[$ap+$j],$apj		! ap[j]
 	and	$car0,$mask,$acc0
 	add	$acc1,$car1,$car1
 	ld	[$np+$j],$npj		! np[j]
 	srlx	$car0,32,$car0
 	add	$acc0,$car1,$car1
 	add	$j,4,$j			! j++
 	mov	$tmp0,$acc0
 	st	$car1,[$tp]
 	cmp	$j,$num
 	mov	$tmp1,$acc1
 	srlx	$car1,32,$car1
 	bl	%icc,.L1st
 	add	$tp,4,$tp		! tp++
 !.L1st
 
 	mulx	$apj,$mul0,$tmp0	!epilogue!
 	mulx	$npj,$mul1,$tmp1
 	add	$acc0,$car0,$car0
 	and	$car0,$mask,$acc0
 	add	$acc1,$car1,$car1
 	srlx	$car0,32,$car0
 	add	$acc0,$car1,$car1
 	st	$car1,[$tp]
 	srlx	$car1,32,$car1
 
 	add	$tmp0,$car0,$car0
 	and	$car0,$mask,$acc0
 	add	$tmp1,$car1,$car1
 	srlx	$car0,32,$car0
 	add	$acc0,$car1,$car1
 	st	$car1,[$tp+4]
 	srlx	$car1,32,$car1
 
 	add	$car0,$car1,$car1
 	st	$car1,[$tp+8]
 	srlx	$car1,32,$car2
 
 	mov	4,$i			! i++
 	ld	[$bp+4],$mul0		! bp[1]
 .Louter:
 	add	%sp,$bias+$frame,$tp
 	ld	[$ap],$car0		! ap[0]
 	ld	[$ap+4],$apj		! ap[1]
 	ld	[$np],$car1		! np[0]
 	ld	[$np+4],$npj		! np[1]
 	ld	[$tp],$tmp1		! tp[0]
 	ld	[$tp+4],$tpj		! tp[1]
 	mov	12,$j
 
 	mulx	$car0,$mul0,$car0
 	mulx	$apj,$mul0,$tmp0	!prologue!
 	add	$tmp1,$car0,$car0
 	ld	[$ap+8],$apj		!prologue!
 	and	$car0,$mask,$acc0
 
 	mulx	$n0,$acc0,$mul1
 	and	$mul1,$mask,$mul1
 
 	mulx	$car1,$mul1,$car1
 	mulx	$npj,$mul1,$acc1	!prologue!
 	srlx	$car0,32,$car0
 	add	$acc0,$car1,$car1
 	ld	[$np+8],$npj		!prologue!
 	srlx	$car1,32,$car1
 	mov	$tmp0,$acc0		!prologue!
 
 .Linner:
 	mulx	$apj,$mul0,$tmp0
 	mulx	$npj,$mul1,$tmp1
 	add	$tpj,$car0,$car0
 	ld	[$ap+$j],$apj		! ap[j]
 	add	$acc0,$car0,$car0
 	add	$acc1,$car1,$car1
 	ld	[$np+$j],$npj		! np[j]
 	and	$car0,$mask,$acc0
 	ld	[$tp+8],$tpj		! tp[j]
 	srlx	$car0,32,$car0
 	add	$acc0,$car1,$car1
 	add	$j,4,$j			! j++
 	mov	$tmp0,$acc0
 	st	$car1,[$tp]		! tp[j-1]
 	srlx	$car1,32,$car1
 	mov	$tmp1,$acc1
 	cmp	$j,$num
 	bl	%icc,.Linner
 	add	$tp,4,$tp		! tp++
 !.Linner
 
 	mulx	$apj,$mul0,$tmp0	!epilogue!
 	mulx	$npj,$mul1,$tmp1
 	add	$tpj,$car0,$car0
 	add	$acc0,$car0,$car0
 	ld	[$tp+8],$tpj		! tp[j]
 	and	$car0,$mask,$acc0
 	add	$acc1,$car1,$car1
 	srlx	$car0,32,$car0
 	add	$acc0,$car1,$car1
 	st	$car1,[$tp]		! tp[j-1]
 	srlx	$car1,32,$car1
 
 	add	$tpj,$car0,$car0
 	add	$tmp0,$car0,$car0
 	and	$car0,$mask,$acc0
 	add	$tmp1,$car1,$car1
 	add	$acc0,$car1,$car1
 	st	$car1,[$tp+4]		! tp[j-1]
 	srlx	$car0,32,$car0
 	add	$i,4,$i			! i++
 	srlx	$car1,32,$car1
 
 	add	$car0,$car1,$car1
 	cmp	$i,$num
 	add	$car2,$car1,$car1
 	st	$car1,[$tp+8]
 
 	srlx	$car1,32,$car2
 	bl,a	%icc,.Louter
 	ld	[$bp+$i],$mul0		! bp[i]
 !.Louter
 
 	add	$tp,12,$tp
 
 .Ltail:
 	add	$np,$num,$np
 	add	$rp,$num,$rp
 	mov	$tp,$ap
 	sub	%g0,$num,%o7		! k=-num
 	ba	.Lsub
 	subcc	%g0,%g0,%g0		! clear %icc.c
 .align	16
 .Lsub:
 	ld	[$tp+%o7],%o0
 	ld	[$np+%o7],%o1
 	subccc	%o0,%o1,%o1		! tp[j]-np[j]
 	add	$rp,%o7,$i
 	add	%o7,4,%o7
 	brnz	%o7,.Lsub
 	st	%o1,[$i]
 	subc	$car2,0,$car2		! handle upmost overflow bit
 	and	$tp,$car2,$ap
 	andn	$rp,$car2,$np
 	or	$ap,$np,$ap
 	sub	%g0,$num,%o7
 
 .Lcopy:
 	ld	[$ap+%o7],%o0		! copy or in-place refresh
 	st	%g0,[$tp+%o7]		! zap tp
 	st	%o0,[$rp+%o7]
 	add	%o7,4,%o7
 	brnz	%o7,.Lcopy
 	nop
 	mov	1,%i0
 	ret
 	restore
 ___
 
 ########
 ######## .Lbn_sqr_mont gives up to 20% *overall* improvement over
 ######## code without following dedicated squaring procedure.
 ########
-$sbit="%i2";		# re-use $bp!
+$sbit="%o5";
 
 $code.=<<___;
 .align	32
 .Lbn_sqr_mont:
 	mulx	$mul0,$mul0,$car0		! ap[0]*ap[0]
 	mulx	$apj,$mul0,$tmp0		!prologue!
 	and	$car0,$mask,$acc0
 	add	%sp,$bias+$frame,$tp
 	ld	[$ap+8],$apj			!prologue!
 
 	mulx	$n0,$acc0,$mul1			! "t[0]"*n0
 	srlx	$car0,32,$car0
 	and	$mul1,$mask,$mul1
 
 	mulx	$car1,$mul1,$car1		! np[0]*"t[0]"*n0
 	mulx	$npj,$mul1,$acc1		!prologue!
 	and	$car0,1,$sbit
 	ld	[$np+8],$npj			!prologue!
 	srlx	$car0,1,$car0
 	add	$acc0,$car1,$car1
 	srlx	$car1,32,$car1
 	mov	$tmp0,$acc0			!prologue!
 
 .Lsqr_1st:
 	mulx	$apj,$mul0,$tmp0
 	mulx	$npj,$mul1,$tmp1
 	add	$acc0,$car0,$car0		! ap[j]*a0+c0
 	add	$acc1,$car1,$car1
 	ld	[$ap+$j],$apj			! ap[j]
 	and	$car0,$mask,$acc0
 	ld	[$np+$j],$npj			! np[j]
 	srlx	$car0,32,$car0
 	add	$acc0,$acc0,$acc0
 	or	$sbit,$acc0,$acc0
 	mov	$tmp1,$acc1
 	srlx	$acc0,32,$sbit
 	add	$j,4,$j				! j++
 	and	$acc0,$mask,$acc0
 	cmp	$j,$num
 	add	$acc0,$car1,$car1
 	st	$car1,[$tp]
 	mov	$tmp0,$acc0
 	srlx	$car1,32,$car1
 	bl	%icc,.Lsqr_1st
 	add	$tp,4,$tp			! tp++
 !.Lsqr_1st
 
 	mulx	$apj,$mul0,$tmp0		! epilogue
 	mulx	$npj,$mul1,$tmp1
 	add	$acc0,$car0,$car0		! ap[j]*a0+c0
 	add	$acc1,$car1,$car1
 	and	$car0,$mask,$acc0
 	srlx	$car0,32,$car0
 	add	$acc0,$acc0,$acc0
 	or	$sbit,$acc0,$acc0
 	srlx	$acc0,32,$sbit
 	and	$acc0,$mask,$acc0
 	add	$acc0,$car1,$car1
 	st	$car1,[$tp]
 	srlx	$car1,32,$car1
 
 	add	$tmp0,$car0,$car0		! ap[j]*a0+c0
 	add	$tmp1,$car1,$car1
 	and	$car0,$mask,$acc0
 	srlx	$car0,32,$car0
 	add	$acc0,$acc0,$acc0
 	or	$sbit,$acc0,$acc0
 	srlx	$acc0,32,$sbit
 	and	$acc0,$mask,$acc0
 	add	$acc0,$car1,$car1
 	st	$car1,[$tp+4]
 	srlx	$car1,32,$car1
 
 	add	$car0,$car0,$car0
 	or	$sbit,$car0,$car0
 	add	$car0,$car1,$car1
 	st	$car1,[$tp+8]
 	srlx	$car1,32,$car2
 
 	ld	[%sp+$bias+$frame],$tmp0	! tp[0]
 	ld	[%sp+$bias+$frame+4],$tmp1	! tp[1]
 	ld	[%sp+$bias+$frame+8],$tpj	! tp[2]
 	ld	[$ap+4],$mul0			! ap[1]
 	ld	[$ap+8],$apj			! ap[2]
 	ld	[$np],$car1			! np[0]
 	ld	[$np+4],$npj			! np[1]
 	mulx	$n0,$tmp0,$mul1
 
 	mulx	$mul0,$mul0,$car0
 	and	$mul1,$mask,$mul1
 
 	mulx	$car1,$mul1,$car1
 	mulx	$npj,$mul1,$acc1
 	add	$tmp0,$car1,$car1
 	and	$car0,$mask,$acc0
 	ld	[$np+8],$npj			! np[2]
 	srlx	$car1,32,$car1
 	add	$tmp1,$car1,$car1
 	srlx	$car0,32,$car0
 	add	$acc0,$car1,$car1
 	and	$car0,1,$sbit
 	add	$acc1,$car1,$car1
 	srlx	$car0,1,$car0
 	mov	12,$j
 	st	$car1,[%sp+$bias+$frame]	! tp[0]=
 	srlx	$car1,32,$car1
 	add	%sp,$bias+$frame+4,$tp
 
 .Lsqr_2nd:
 	mulx	$apj,$mul0,$acc0
 	mulx	$npj,$mul1,$acc1
 	add	$acc0,$car0,$car0
-	add	$tpj,$car1,$car1
+	add	$tpj,$sbit,$sbit
 	ld	[$ap+$j],$apj			! ap[j]
 	and	$car0,$mask,$acc0
 	ld	[$np+$j],$npj			! np[j]
 	srlx	$car0,32,$car0
 	add	$acc1,$car1,$car1
 	ld	[$tp+8],$tpj			! tp[j]
 	add	$acc0,$acc0,$acc0
 	add	$j,4,$j				! j++
-	or	$sbit,$acc0,$acc0
+	add	$sbit,$acc0,$acc0
 	srlx	$acc0,32,$sbit
 	and	$acc0,$mask,$acc0
 	cmp	$j,$num
 	add	$acc0,$car1,$car1
 	st	$car1,[$tp]			! tp[j-1]
 	srlx	$car1,32,$car1
 	bl	%icc,.Lsqr_2nd
 	add	$tp,4,$tp			! tp++
 !.Lsqr_2nd
 
 	mulx	$apj,$mul0,$acc0
 	mulx	$npj,$mul1,$acc1
 	add	$acc0,$car0,$car0
-	add	$tpj,$car1,$car1
+	add	$tpj,$sbit,$sbit
 	and	$car0,$mask,$acc0
 	srlx	$car0,32,$car0
 	add	$acc1,$car1,$car1
 	add	$acc0,$acc0,$acc0
-	or	$sbit,$acc0,$acc0
+	add	$sbit,$acc0,$acc0
 	srlx	$acc0,32,$sbit
 	and	$acc0,$mask,$acc0
 	add	$acc0,$car1,$car1
 	st	$car1,[$tp]			! tp[j-1]
 	srlx	$car1,32,$car1
 
 	add	$car0,$car0,$car0
-	or	$sbit,$car0,$car0
+	add	$sbit,$car0,$car0
 	add	$car0,$car1,$car1
 	add	$car2,$car1,$car1
 	st	$car1,[$tp+4]
 	srlx	$car1,32,$car2
 
 	ld	[%sp+$bias+$frame],$tmp1	! tp[0]
 	ld	[%sp+$bias+$frame+4],$tpj	! tp[1]
 	ld	[$ap+8],$mul0			! ap[2]
 	ld	[$np],$car1			! np[0]
 	ld	[$np+4],$npj			! np[1]
 	mulx	$n0,$tmp1,$mul1
 	and	$mul1,$mask,$mul1
 	mov	8,$i
 
 	mulx	$mul0,$mul0,$car0
 	mulx	$car1,$mul1,$car1
 	and	$car0,$mask,$acc0
 	add	$tmp1,$car1,$car1
 	srlx	$car0,32,$car0
 	add	%sp,$bias+$frame,$tp
 	srlx	$car1,32,$car1
 	and	$car0,1,$sbit
 	srlx	$car0,1,$car0
 	mov	4,$j
 
 .Lsqr_outer:
 .Lsqr_inner1:
 	mulx	$npj,$mul1,$acc1
 	add	$tpj,$car1,$car1
 	add	$j,4,$j
 	ld	[$tp+8],$tpj
 	cmp	$j,$i
 	add	$acc1,$car1,$car1
 	ld	[$np+$j],$npj
 	st	$car1,[$tp]
 	srlx	$car1,32,$car1
 	bl	%icc,.Lsqr_inner1
 	add	$tp,4,$tp
 !.Lsqr_inner1
 
 	add	$j,4,$j
 	ld	[$ap+$j],$apj			! ap[j]
 	mulx	$npj,$mul1,$acc1
 	add	$tpj,$car1,$car1
 	ld	[$np+$j],$npj			! np[j]
 	add	$acc0,$car1,$car1
 	ld	[$tp+8],$tpj			! tp[j]
 	add	$acc1,$car1,$car1
 	st	$car1,[$tp]
 	srlx	$car1,32,$car1
 
 	add	$j,4,$j
 	cmp	$j,$num
 	be,pn	%icc,.Lsqr_no_inner2
 	add	$tp,4,$tp
 
 .Lsqr_inner2:
 	mulx	$apj,$mul0,$acc0
 	mulx	$npj,$mul1,$acc1
-	add	$tpj,$car1,$car1
+	add	$tpj,$sbit,$sbit
 	add	$acc0,$car0,$car0
 	ld	[$ap+$j],$apj			! ap[j]
 	and	$car0,$mask,$acc0
 	ld	[$np+$j],$npj			! np[j]
 	srlx	$car0,32,$car0
 	add	$acc0,$acc0,$acc0
 	ld	[$tp+8],$tpj			! tp[j]
-	or	$sbit,$acc0,$acc0
+	add	$sbit,$acc0,$acc0
 	add	$j,4,$j				! j++
 	srlx	$acc0,32,$sbit
 	and	$acc0,$mask,$acc0
 	cmp	$j,$num
 	add	$acc0,$car1,$car1
 	add	$acc1,$car1,$car1
 	st	$car1,[$tp]			! tp[j-1]
 	srlx	$car1,32,$car1
 	bl	%icc,.Lsqr_inner2
 	add	$tp,4,$tp			! tp++
 
 .Lsqr_no_inner2:
 	mulx	$apj,$mul0,$acc0
 	mulx	$npj,$mul1,$acc1
-	add	$tpj,$car1,$car1
+	add	$tpj,$sbit,$sbit
 	add	$acc0,$car0,$car0
 	and	$car0,$mask,$acc0
 	srlx	$car0,32,$car0
 	add	$acc0,$acc0,$acc0
-	or	$sbit,$acc0,$acc0
+	add	$sbit,$acc0,$acc0
 	srlx	$acc0,32,$sbit
 	and	$acc0,$mask,$acc0
 	add	$acc0,$car1,$car1
 	add	$acc1,$car1,$car1
 	st	$car1,[$tp]			! tp[j-1]
 	srlx	$car1,32,$car1
 
 	add	$car0,$car0,$car0
-	or	$sbit,$car0,$car0
+	add	$sbit,$car0,$car0
 	add	$car0,$car1,$car1
 	add	$car2,$car1,$car1
 	st	$car1,[$tp+4]
 	srlx	$car1,32,$car2
 
 	add	$i,4,$i				! i++
 	ld	[%sp+$bias+$frame],$tmp1	! tp[0]
 	ld	[%sp+$bias+$frame+4],$tpj	! tp[1]
 	ld	[$ap+$i],$mul0			! ap[j]
 	ld	[$np],$car1			! np[0]
 	ld	[$np+4],$npj			! np[1]
 	mulx	$n0,$tmp1,$mul1
 	and	$mul1,$mask,$mul1
 	add	$i,4,$tmp0
 
 	mulx	$mul0,$mul0,$car0
 	mulx	$car1,$mul1,$car1
 	and	$car0,$mask,$acc0
 	add	$tmp1,$car1,$car1
 	srlx	$car0,32,$car0
 	add	%sp,$bias+$frame,$tp
 	srlx	$car1,32,$car1
 	and	$car0,1,$sbit
 	srlx	$car0,1,$car0
 
 	cmp	$tmp0,$num			! i"
 .align	32
 ___
 $code =~ s/\`([^\`]*)\`/eval($1)/gem;
 print $code;
 close STDOUT;
Index: vendor-crypto/openssl/dist/crypto/bn/bn_prime.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/bn/bn_prime.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/bn/bn_prime.c	(revision 318897)
@@ -1,516 +1,504 @@
 /* crypto/bn/bn_prime.c */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 /* ====================================================================
  * Copyright (c) 1998-2001 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    openssl-core@openssl.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #include 
 #include 
 #include "cryptlib.h"
 #include "bn_lcl.h"
 #include 
 
 /*
  * NB: these functions have been "upgraded", the deprecated versions (which
  * are compatibility wrappers using these functions) are in bn_depr.c. -
  * Geoff
  */
 
 /*
  * The quick sieve algorithm approach to weeding out primes is Philip
  * Zimmermann's, as implemented in PGP.  I have had a read of his comments
  * and implemented my own version.
  */
 #include "bn_prime.h"
 
 static int witness(BIGNUM *w, const BIGNUM *a, const BIGNUM *a1,
                    const BIGNUM *a1_odd, int k, BN_CTX *ctx,
                    BN_MONT_CTX *mont);
 static int probable_prime(BIGNUM *rnd, int bits);
 static int probable_prime_dh(BIGNUM *rnd, int bits,
                              const BIGNUM *add, const BIGNUM *rem,
                              BN_CTX *ctx);
 static int probable_prime_dh_safe(BIGNUM *rnd, int bits, const BIGNUM *add,
                                   const BIGNUM *rem, BN_CTX *ctx);
 
 int BN_GENCB_call(BN_GENCB *cb, int a, int b)
 {
     /* No callback means continue */
     if (!cb)
         return 1;
     switch (cb->ver) {
     case 1:
         /* Deprecated-style callbacks */
         if (!cb->cb.cb_1)
             return 1;
         cb->cb.cb_1(a, b, cb->arg);
         return 1;
     case 2:
         /* New-style callbacks */
         return cb->cb.cb_2(a, b, cb);
     default:
         break;
     }
     /* Unrecognised callback type */
     return 0;
 }
 
 int BN_generate_prime_ex(BIGNUM *ret, int bits, int safe,
                          const BIGNUM *add, const BIGNUM *rem, BN_GENCB *cb)
 {
     BIGNUM *t;
     int found = 0;
     int i, j, c1 = 0;
     BN_CTX *ctx;
     int checks = BN_prime_checks_for_size(bits);
 
     ctx = BN_CTX_new();
     if (ctx == NULL)
         goto err;
     BN_CTX_start(ctx);
     t = BN_CTX_get(ctx);
     if (!t)
         goto err;
  loop:
     /* make a random number and set the top and bottom bits */
     if (add == NULL) {
         if (!probable_prime(ret, bits))
             goto err;
     } else {
         if (safe) {
             if (!probable_prime_dh_safe(ret, bits, add, rem, ctx))
                 goto err;
         } else {
             if (!probable_prime_dh(ret, bits, add, rem, ctx))
                 goto err;
         }
     }
     /* if (BN_mod_word(ret,(BN_ULONG)3) == 1) goto loop; */
     if (!BN_GENCB_call(cb, 0, c1++))
         /* aborted */
         goto err;
 
     if (!safe) {
         i = BN_is_prime_fasttest_ex(ret, checks, ctx, 0, cb);
         if (i == -1)
             goto err;
         if (i == 0)
             goto loop;
     } else {
         /*
          * for "safe prime" generation, check that (p-1)/2 is prime. Since a
          * prime is odd, We just need to divide by 2
          */
         if (!BN_rshift1(t, ret))
             goto err;
 
         for (i = 0; i < checks; i++) {
             j = BN_is_prime_fasttest_ex(ret, 1, ctx, 0, cb);
             if (j == -1)
                 goto err;
             if (j == 0)
                 goto loop;
 
             j = BN_is_prime_fasttest_ex(t, 1, ctx, 0, cb);
             if (j == -1)
                 goto err;
             if (j == 0)
                 goto loop;
 
             if (!BN_GENCB_call(cb, 2, c1 - 1))
                 goto err;
             /* We have a safe prime test pass */
         }
     }
     /* we have a prime :-) */
     found = 1;
  err:
     if (ctx != NULL) {
         BN_CTX_end(ctx);
         BN_CTX_free(ctx);
     }
     bn_check_top(ret);
     return found;
 }
 
 int BN_is_prime_ex(const BIGNUM *a, int checks, BN_CTX *ctx_passed,
                    BN_GENCB *cb)
 {
     return BN_is_prime_fasttest_ex(a, checks, ctx_passed, 0, cb);
 }
 
 int BN_is_prime_fasttest_ex(const BIGNUM *a, int checks, BN_CTX *ctx_passed,
                             int do_trial_division, BN_GENCB *cb)
 {
     int i, j, ret = -1;
     int k;
     BN_CTX *ctx = NULL;
     BIGNUM *A1, *A1_odd, *check; /* taken from ctx */
     BN_MONT_CTX *mont = NULL;
-    const BIGNUM *A = NULL;
 
     if (BN_cmp(a, BN_value_one()) <= 0)
         return 0;
 
     if (checks == BN_prime_checks)
         checks = BN_prime_checks_for_size(BN_num_bits(a));
 
     /* first look for small factors */
     if (!BN_is_odd(a))
         /* a is even => a is prime if and only if a == 2 */
         return BN_is_word(a, 2);
     if (do_trial_division) {
         for (i = 1; i < NUMPRIMES; i++)
             if (BN_mod_word(a, primes[i]) == 0)
                 return 0;
         if (!BN_GENCB_call(cb, 1, -1))
             goto err;
     }
 
     if (ctx_passed != NULL)
         ctx = ctx_passed;
     else if ((ctx = BN_CTX_new()) == NULL)
         goto err;
     BN_CTX_start(ctx);
 
-    /* A := abs(a) */
-    if (a->neg) {
-        BIGNUM *t;
-        if ((t = BN_CTX_get(ctx)) == NULL)
-            goto err;
-        if (BN_copy(t, a) == NULL)
-            goto err;
-        t->neg = 0;
-        A = t;
-    } else
-        A = a;
     A1 = BN_CTX_get(ctx);
     A1_odd = BN_CTX_get(ctx);
     check = BN_CTX_get(ctx);
     if (check == NULL)
         goto err;
 
-    /* compute A1 := A - 1 */
-    if (!BN_copy(A1, A))
+    /* compute A1 := a - 1 */
+    if (!BN_copy(A1, a))
         goto err;
     if (!BN_sub_word(A1, 1))
         goto err;
     if (BN_is_zero(A1)) {
         ret = 0;
         goto err;
     }
 
     /* write  A1  as  A1_odd * 2^k */
     k = 1;
     while (!BN_is_bit_set(A1, k))
         k++;
     if (!BN_rshift(A1_odd, A1, k))
         goto err;
 
-    /* Montgomery setup for computations mod A */
+    /* Montgomery setup for computations mod a */
     mont = BN_MONT_CTX_new();
     if (mont == NULL)
         goto err;
-    if (!BN_MONT_CTX_set(mont, A, ctx))
+    if (!BN_MONT_CTX_set(mont, a, ctx))
         goto err;
 
     for (i = 0; i < checks; i++) {
         if (!BN_pseudo_rand_range(check, A1))
             goto err;
         if (!BN_add_word(check, 1))
             goto err;
-        /* now 1 <= check < A */
+        /* now 1 <= check < a */
 
-        j = witness(check, A, A1, A1_odd, k, ctx, mont);
+        j = witness(check, a, A1, A1_odd, k, ctx, mont);
         if (j == -1)
             goto err;
         if (j) {
             ret = 0;
             goto err;
         }
         if (!BN_GENCB_call(cb, 1, i))
             goto err;
     }
     ret = 1;
  err:
     if (ctx != NULL) {
         BN_CTX_end(ctx);
         if (ctx_passed == NULL)
             BN_CTX_free(ctx);
     }
     if (mont != NULL)
         BN_MONT_CTX_free(mont);
 
     return (ret);
 }
 
 static int witness(BIGNUM *w, const BIGNUM *a, const BIGNUM *a1,
                    const BIGNUM *a1_odd, int k, BN_CTX *ctx,
                    BN_MONT_CTX *mont)
 {
     if (!BN_mod_exp_mont(w, w, a1_odd, a, ctx, mont)) /* w := w^a1_odd mod a */
         return -1;
     if (BN_is_one(w))
         return 0;               /* probably prime */
     if (BN_cmp(w, a1) == 0)
         return 0;               /* w == -1 (mod a), 'a' is probably prime */
     while (--k) {
         if (!BN_mod_mul(w, w, w, a, ctx)) /* w := w^2 mod a */
             return -1;
         if (BN_is_one(w))
             return 1;           /* 'a' is composite, otherwise a previous 'w'
                                  * would have been == -1 (mod 'a') */
         if (BN_cmp(w, a1) == 0)
             return 0;           /* w == -1 (mod a), 'a' is probably prime */
     }
     /*
      * If we get here, 'w' is the (a-1)/2-th power of the original 'w', and
      * it is neither -1 nor +1 -- so 'a' cannot be prime
      */
     bn_check_top(w);
     return 1;
 }
 
 static int probable_prime(BIGNUM *rnd, int bits)
 {
     int i;
     prime_t mods[NUMPRIMES];
     BN_ULONG delta, maxdelta;
 
  again:
     if (!BN_rand(rnd, bits, 1, 1))
         return (0);
     /* we now have a random number 'rand' to test. */
     for (i = 1; i < NUMPRIMES; i++)
         mods[i] = (prime_t) BN_mod_word(rnd, (BN_ULONG)primes[i]);
     maxdelta = BN_MASK2 - primes[NUMPRIMES - 1];
     delta = 0;
  loop:for (i = 1; i < NUMPRIMES; i++) {
         /*
          * check that rnd is not a prime and also that gcd(rnd-1,primes) == 1
          * (except for 2)
          */
         if (((mods[i] + delta) % primes[i]) <= 1) {
             delta += 2;
             if (delta > maxdelta)
                 goto again;
             goto loop;
         }
     }
     if (!BN_add_word(rnd, delta))
         return (0);
     bn_check_top(rnd);
     return (1);
 }
 
 static int probable_prime_dh(BIGNUM *rnd, int bits,
                              const BIGNUM *add, const BIGNUM *rem,
                              BN_CTX *ctx)
 {
     int i, ret = 0;
     BIGNUM *t1;
 
     BN_CTX_start(ctx);
     if ((t1 = BN_CTX_get(ctx)) == NULL)
         goto err;
 
     if (!BN_rand(rnd, bits, 0, 1))
         goto err;
 
     /* we need ((rnd-rem) % add) == 0 */
 
     if (!BN_mod(t1, rnd, add, ctx))
         goto err;
     if (!BN_sub(rnd, rnd, t1))
         goto err;
     if (rem == NULL) {
         if (!BN_add_word(rnd, 1))
             goto err;
     } else {
         if (!BN_add(rnd, rnd, rem))
             goto err;
     }
 
     /* we now have a random number 'rand' to test. */
 
  loop:for (i = 1; i < NUMPRIMES; i++) {
         /* check that rnd is a prime */
         if (BN_mod_word(rnd, (BN_ULONG)primes[i]) <= 1) {
             if (!BN_add(rnd, rnd, add))
                 goto err;
             goto loop;
         }
     }
     ret = 1;
  err:
     BN_CTX_end(ctx);
     bn_check_top(rnd);
     return (ret);
 }
 
 static int probable_prime_dh_safe(BIGNUM *p, int bits, const BIGNUM *padd,
                                   const BIGNUM *rem, BN_CTX *ctx)
 {
     int i, ret = 0;
     BIGNUM *t1, *qadd, *q;
 
     bits--;
     BN_CTX_start(ctx);
     t1 = BN_CTX_get(ctx);
     q = BN_CTX_get(ctx);
     qadd = BN_CTX_get(ctx);
     if (qadd == NULL)
         goto err;
 
     if (!BN_rshift1(qadd, padd))
         goto err;
 
     if (!BN_rand(q, bits, 0, 1))
         goto err;
 
     /* we need ((rnd-rem) % add) == 0 */
     if (!BN_mod(t1, q, qadd, ctx))
         goto err;
     if (!BN_sub(q, q, t1))
         goto err;
     if (rem == NULL) {
         if (!BN_add_word(q, 1))
             goto err;
     } else {
         if (!BN_rshift1(t1, rem))
             goto err;
         if (!BN_add(q, q, t1))
             goto err;
     }
 
     /* we now have a random number 'rand' to test. */
     if (!BN_lshift1(p, q))
         goto err;
     if (!BN_add_word(p, 1))
         goto err;
 
  loop:for (i = 1; i < NUMPRIMES; i++) {
         /* check that p and q are prime */
         /*
          * check that for p and q gcd(p-1,primes) == 1 (except for 2)
          */
         if ((BN_mod_word(p, (BN_ULONG)primes[i]) == 0) ||
             (BN_mod_word(q, (BN_ULONG)primes[i]) == 0)) {
             if (!BN_add(p, p, padd))
                 goto err;
             if (!BN_add(q, q, qadd))
                 goto err;
             goto loop;
         }
     }
     ret = 1;
  err:
     BN_CTX_end(ctx);
     bn_check_top(p);
     return (ret);
 }
Index: vendor-crypto/openssl/dist/crypto/bn/bn_prime.h
===================================================================
--- vendor-crypto/openssl/dist/crypto/bn/bn_prime.h	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/bn/bn_prime.h	(revision 318897)
@@ -1,326 +1,326 @@
 /* Auto generated by bn_prime.pl */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 
 #ifndef EIGHT_BIT
 # define NUMPRIMES 2048
 typedef unsigned short prime_t;
 #else
 # define NUMPRIMES 54
 typedef unsigned char prime_t;
 #endif
 static const prime_t primes[NUMPRIMES] = {
-    2, 3, 5, 7, 11, 13, 17, 19,
-    23, 29, 31, 37, 41, 43, 47, 53,
-    59, 61, 67, 71, 73, 79, 83, 89,
-    97, 101, 103, 107, 109, 113, 127, 131,
-    137, 139, 149, 151, 157, 163, 167, 173,
-    179, 181, 191, 193, 197, 199, 211, 223,
-    227, 229, 233, 239, 241, 251,
+         2,     3,     5,     7,    11,    13,    17,    19,
+        23,    29,    31,    37,    41,    43,    47,    53,
+        59,    61,    67,    71,    73,    79,    83,    89,
+        97,   101,   103,   107,   109,   113,   127,   131,
+       137,   139,   149,   151,   157,   163,   167,   173,
+       179,   181,   191,   193,   197,   199,   211,   223,
+       227,   229,   233,   239,   241,   251,
 #ifndef EIGHT_BIT
-    257, 263,
-    269, 271, 277, 281, 283, 293, 307, 311,
-    313, 317, 331, 337, 347, 349, 353, 359,
-    367, 373, 379, 383, 389, 397, 401, 409,
-    419, 421, 431, 433, 439, 443, 449, 457,
-    461, 463, 467, 479, 487, 491, 499, 503,
-    509, 521, 523, 541, 547, 557, 563, 569,
-    571, 577, 587, 593, 599, 601, 607, 613,
-    617, 619, 631, 641, 643, 647, 653, 659,
-    661, 673, 677, 683, 691, 701, 709, 719,
-    727, 733, 739, 743, 751, 757, 761, 769,
-    773, 787, 797, 809, 811, 821, 823, 827,
-    829, 839, 853, 857, 859, 863, 877, 881,
-    883, 887, 907, 911, 919, 929, 937, 941,
-    947, 953, 967, 971, 977, 983, 991, 997,
-    1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049,
-    1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097,
-    1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163,
-    1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223,
-    1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283,
-    1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321,
-    1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423,
-    1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459,
-    1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511,
-    1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571,
-    1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619,
-    1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693,
-    1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747,
-    1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811,
-    1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877,
-    1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949,
-    1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003,
-    2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069,
-    2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129,
-    2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203,
-    2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267,
-    2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311,
-    2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377,
-    2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423,
-    2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503,
-    2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579,
-    2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657,
-    2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693,
-    2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741,
-    2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801,
-    2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861,
-    2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939,
-    2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011,
-    3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079,
-    3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167,
-    3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221,
-    3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301,
-    3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347,
-    3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413,
-    3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491,
-    3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541,
-    3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607,
-    3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671,
-    3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727,
-    3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797,
-    3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863,
-    3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923,
-    3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003,
-    4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057,
-    4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129,
-    4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211,
-    4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259,
-    4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337,
-    4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409,
-    4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481,
-    4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547,
-    4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621,
-    4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673,
-    4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751,
-    4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813,
-    4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909,
-    4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967,
-    4969, 4973, 4987, 4993, 4999, 5003, 5009, 5011,
-    5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087,
-    5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167,
-    5171, 5179, 5189, 5197, 5209, 5227, 5231, 5233,
-    5237, 5261, 5273, 5279, 5281, 5297, 5303, 5309,
-    5323, 5333, 5347, 5351, 5381, 5387, 5393, 5399,
-    5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443,
-    5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507,
-    5519, 5521, 5527, 5531, 5557, 5563, 5569, 5573,
-    5581, 5591, 5623, 5639, 5641, 5647, 5651, 5653,
-    5657, 5659, 5669, 5683, 5689, 5693, 5701, 5711,
-    5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791,
-    5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849,
-    5851, 5857, 5861, 5867, 5869, 5879, 5881, 5897,
-    5903, 5923, 5927, 5939, 5953, 5981, 5987, 6007,
-    6011, 6029, 6037, 6043, 6047, 6053, 6067, 6073,
-    6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133,
-    6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211,
-    6217, 6221, 6229, 6247, 6257, 6263, 6269, 6271,
-    6277, 6287, 6299, 6301, 6311, 6317, 6323, 6329,
-    6337, 6343, 6353, 6359, 6361, 6367, 6373, 6379,
-    6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473,
-    6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563,
-    6569, 6571, 6577, 6581, 6599, 6607, 6619, 6637,
-    6653, 6659, 6661, 6673, 6679, 6689, 6691, 6701,
-    6703, 6709, 6719, 6733, 6737, 6761, 6763, 6779,
-    6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833,
-    6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907,
-    6911, 6917, 6947, 6949, 6959, 6961, 6967, 6971,
-    6977, 6983, 6991, 6997, 7001, 7013, 7019, 7027,
-    7039, 7043, 7057, 7069, 7079, 7103, 7109, 7121,
-    7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207,
-    7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253,
-    7283, 7297, 7307, 7309, 7321, 7331, 7333, 7349,
-    7351, 7369, 7393, 7411, 7417, 7433, 7451, 7457,
-    7459, 7477, 7481, 7487, 7489, 7499, 7507, 7517,
-    7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561,
-    7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621,
-    7639, 7643, 7649, 7669, 7673, 7681, 7687, 7691,
-    7699, 7703, 7717, 7723, 7727, 7741, 7753, 7757,
-    7759, 7789, 7793, 7817, 7823, 7829, 7841, 7853,
-    7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919,
-    7927, 7933, 7937, 7949, 7951, 7963, 7993, 8009,
-    8011, 8017, 8039, 8053, 8059, 8069, 8081, 8087,
-    8089, 8093, 8101, 8111, 8117, 8123, 8147, 8161,
-    8167, 8171, 8179, 8191, 8209, 8219, 8221, 8231,
-    8233, 8237, 8243, 8263, 8269, 8273, 8287, 8291,
-    8293, 8297, 8311, 8317, 8329, 8353, 8363, 8369,
-    8377, 8387, 8389, 8419, 8423, 8429, 8431, 8443,
-    8447, 8461, 8467, 8501, 8513, 8521, 8527, 8537,
-    8539, 8543, 8563, 8573, 8581, 8597, 8599, 8609,
-    8623, 8627, 8629, 8641, 8647, 8663, 8669, 8677,
-    8681, 8689, 8693, 8699, 8707, 8713, 8719, 8731,
-    8737, 8741, 8747, 8753, 8761, 8779, 8783, 8803,
-    8807, 8819, 8821, 8831, 8837, 8839, 8849, 8861,
-    8863, 8867, 8887, 8893, 8923, 8929, 8933, 8941,
-    8951, 8963, 8969, 8971, 8999, 9001, 9007, 9011,
-    9013, 9029, 9041, 9043, 9049, 9059, 9067, 9091,
-    9103, 9109, 9127, 9133, 9137, 9151, 9157, 9161,
-    9173, 9181, 9187, 9199, 9203, 9209, 9221, 9227,
-    9239, 9241, 9257, 9277, 9281, 9283, 9293, 9311,
-    9319, 9323, 9337, 9341, 9343, 9349, 9371, 9377,
-    9391, 9397, 9403, 9413, 9419, 9421, 9431, 9433,
-    9437, 9439, 9461, 9463, 9467, 9473, 9479, 9491,
-    9497, 9511, 9521, 9533, 9539, 9547, 9551, 9587,
-    9601, 9613, 9619, 9623, 9629, 9631, 9643, 9649,
-    9661, 9677, 9679, 9689, 9697, 9719, 9721, 9733,
-    9739, 9743, 9749, 9767, 9769, 9781, 9787, 9791,
-    9803, 9811, 9817, 9829, 9833, 9839, 9851, 9857,
-    9859, 9871, 9883, 9887, 9901, 9907, 9923, 9929,
-    9931, 9941, 9949, 9967, 9973, 10007, 10009, 10037,
-    10039, 10061, 10067, 10069, 10079, 10091, 10093, 10099,
-    10103, 10111, 10133, 10139, 10141, 10151, 10159, 10163,
-    10169, 10177, 10181, 10193, 10211, 10223, 10243, 10247,
-    10253, 10259, 10267, 10271, 10273, 10289, 10301, 10303,
-    10313, 10321, 10331, 10333, 10337, 10343, 10357, 10369,
-    10391, 10399, 10427, 10429, 10433, 10453, 10457, 10459,
-    10463, 10477, 10487, 10499, 10501, 10513, 10529, 10531,
-    10559, 10567, 10589, 10597, 10601, 10607, 10613, 10627,
-    10631, 10639, 10651, 10657, 10663, 10667, 10687, 10691,
-    10709, 10711, 10723, 10729, 10733, 10739, 10753, 10771,
-    10781, 10789, 10799, 10831, 10837, 10847, 10853, 10859,
-    10861, 10867, 10883, 10889, 10891, 10903, 10909, 10937,
-    10939, 10949, 10957, 10973, 10979, 10987, 10993, 11003,
-    11027, 11047, 11057, 11059, 11069, 11071, 11083, 11087,
-    11093, 11113, 11117, 11119, 11131, 11149, 11159, 11161,
-    11171, 11173, 11177, 11197, 11213, 11239, 11243, 11251,
-    11257, 11261, 11273, 11279, 11287, 11299, 11311, 11317,
-    11321, 11329, 11351, 11353, 11369, 11383, 11393, 11399,
-    11411, 11423, 11437, 11443, 11447, 11467, 11471, 11483,
-    11489, 11491, 11497, 11503, 11519, 11527, 11549, 11551,
-    11579, 11587, 11593, 11597, 11617, 11621, 11633, 11657,
-    11677, 11681, 11689, 11699, 11701, 11717, 11719, 11731,
-    11743, 11777, 11779, 11783, 11789, 11801, 11807, 11813,
-    11821, 11827, 11831, 11833, 11839, 11863, 11867, 11887,
-    11897, 11903, 11909, 11923, 11927, 11933, 11939, 11941,
-    11953, 11959, 11969, 11971, 11981, 11987, 12007, 12011,
-    12037, 12041, 12043, 12049, 12071, 12073, 12097, 12101,
-    12107, 12109, 12113, 12119, 12143, 12149, 12157, 12161,
-    12163, 12197, 12203, 12211, 12227, 12239, 12241, 12251,
-    12253, 12263, 12269, 12277, 12281, 12289, 12301, 12323,
-    12329, 12343, 12347, 12373, 12377, 12379, 12391, 12401,
-    12409, 12413, 12421, 12433, 12437, 12451, 12457, 12473,
-    12479, 12487, 12491, 12497, 12503, 12511, 12517, 12527,
-    12539, 12541, 12547, 12553, 12569, 12577, 12583, 12589,
-    12601, 12611, 12613, 12619, 12637, 12641, 12647, 12653,
-    12659, 12671, 12689, 12697, 12703, 12713, 12721, 12739,
-    12743, 12757, 12763, 12781, 12791, 12799, 12809, 12821,
-    12823, 12829, 12841, 12853, 12889, 12893, 12899, 12907,
-    12911, 12917, 12919, 12923, 12941, 12953, 12959, 12967,
-    12973, 12979, 12983, 13001, 13003, 13007, 13009, 13033,
-    13037, 13043, 13049, 13063, 13093, 13099, 13103, 13109,
-    13121, 13127, 13147, 13151, 13159, 13163, 13171, 13177,
-    13183, 13187, 13217, 13219, 13229, 13241, 13249, 13259,
-    13267, 13291, 13297, 13309, 13313, 13327, 13331, 13337,
-    13339, 13367, 13381, 13397, 13399, 13411, 13417, 13421,
-    13441, 13451, 13457, 13463, 13469, 13477, 13487, 13499,
-    13513, 13523, 13537, 13553, 13567, 13577, 13591, 13597,
-    13613, 13619, 13627, 13633, 13649, 13669, 13679, 13681,
-    13687, 13691, 13693, 13697, 13709, 13711, 13721, 13723,
-    13729, 13751, 13757, 13759, 13763, 13781, 13789, 13799,
-    13807, 13829, 13831, 13841, 13859, 13873, 13877, 13879,
-    13883, 13901, 13903, 13907, 13913, 13921, 13931, 13933,
-    13963, 13967, 13997, 13999, 14009, 14011, 14029, 14033,
-    14051, 14057, 14071, 14081, 14083, 14087, 14107, 14143,
-    14149, 14153, 14159, 14173, 14177, 14197, 14207, 14221,
-    14243, 14249, 14251, 14281, 14293, 14303, 14321, 14323,
-    14327, 14341, 14347, 14369, 14387, 14389, 14401, 14407,
-    14411, 14419, 14423, 14431, 14437, 14447, 14449, 14461,
-    14479, 14489, 14503, 14519, 14533, 14537, 14543, 14549,
-    14551, 14557, 14561, 14563, 14591, 14593, 14621, 14627,
-    14629, 14633, 14639, 14653, 14657, 14669, 14683, 14699,
-    14713, 14717, 14723, 14731, 14737, 14741, 14747, 14753,
-    14759, 14767, 14771, 14779, 14783, 14797, 14813, 14821,
-    14827, 14831, 14843, 14851, 14867, 14869, 14879, 14887,
-    14891, 14897, 14923, 14929, 14939, 14947, 14951, 14957,
-    14969, 14983, 15013, 15017, 15031, 15053, 15061, 15073,
-    15077, 15083, 15091, 15101, 15107, 15121, 15131, 15137,
-    15139, 15149, 15161, 15173, 15187, 15193, 15199, 15217,
-    15227, 15233, 15241, 15259, 15263, 15269, 15271, 15277,
-    15287, 15289, 15299, 15307, 15313, 15319, 15329, 15331,
-    15349, 15359, 15361, 15373, 15377, 15383, 15391, 15401,
-    15413, 15427, 15439, 15443, 15451, 15461, 15467, 15473,
-    15493, 15497, 15511, 15527, 15541, 15551, 15559, 15569,
-    15581, 15583, 15601, 15607, 15619, 15629, 15641, 15643,
-    15647, 15649, 15661, 15667, 15671, 15679, 15683, 15727,
-    15731, 15733, 15737, 15739, 15749, 15761, 15767, 15773,
-    15787, 15791, 15797, 15803, 15809, 15817, 15823, 15859,
-    15877, 15881, 15887, 15889, 15901, 15907, 15913, 15919,
-    15923, 15937, 15959, 15971, 15973, 15991, 16001, 16007,
-    16033, 16057, 16061, 16063, 16067, 16069, 16073, 16087,
-    16091, 16097, 16103, 16111, 16127, 16139, 16141, 16183,
-    16187, 16189, 16193, 16217, 16223, 16229, 16231, 16249,
-    16253, 16267, 16273, 16301, 16319, 16333, 16339, 16349,
-    16361, 16363, 16369, 16381, 16411, 16417, 16421, 16427,
-    16433, 16447, 16451, 16453, 16477, 16481, 16487, 16493,
-    16519, 16529, 16547, 16553, 16561, 16567, 16573, 16603,
-    16607, 16619, 16631, 16633, 16649, 16651, 16657, 16661,
-    16673, 16691, 16693, 16699, 16703, 16729, 16741, 16747,
-    16759, 16763, 16787, 16811, 16823, 16829, 16831, 16843,
-    16871, 16879, 16883, 16889, 16901, 16903, 16921, 16927,
-    16931, 16937, 16943, 16963, 16979, 16981, 16987, 16993,
-    17011, 17021, 17027, 17029, 17033, 17041, 17047, 17053,
-    17077, 17093, 17099, 17107, 17117, 17123, 17137, 17159,
-    17167, 17183, 17189, 17191, 17203, 17207, 17209, 17231,
-    17239, 17257, 17291, 17293, 17299, 17317, 17321, 17327,
-    17333, 17341, 17351, 17359, 17377, 17383, 17387, 17389,
-    17393, 17401, 17417, 17419, 17431, 17443, 17449, 17467,
-    17471, 17477, 17483, 17489, 17491, 17497, 17509, 17519,
-    17539, 17551, 17569, 17573, 17579, 17581, 17597, 17599,
-    17609, 17623, 17627, 17657, 17659, 17669, 17681, 17683,
-    17707, 17713, 17729, 17737, 17747, 17749, 17761, 17783,
-    17789, 17791, 17807, 17827, 17837, 17839, 17851, 17863,
+       257,   263,
+       269,   271,   277,   281,   283,   293,   307,   311,
+       313,   317,   331,   337,   347,   349,   353,   359,
+       367,   373,   379,   383,   389,   397,   401,   409,
+       419,   421,   431,   433,   439,   443,   449,   457,
+       461,   463,   467,   479,   487,   491,   499,   503,
+       509,   521,   523,   541,   547,   557,   563,   569,
+       571,   577,   587,   593,   599,   601,   607,   613,
+       617,   619,   631,   641,   643,   647,   653,   659,
+       661,   673,   677,   683,   691,   701,   709,   719,
+       727,   733,   739,   743,   751,   757,   761,   769,
+       773,   787,   797,   809,   811,   821,   823,   827,
+       829,   839,   853,   857,   859,   863,   877,   881,
+       883,   887,   907,   911,   919,   929,   937,   941,
+       947,   953,   967,   971,   977,   983,   991,   997,
+      1009,  1013,  1019,  1021,  1031,  1033,  1039,  1049,
+      1051,  1061,  1063,  1069,  1087,  1091,  1093,  1097,
+      1103,  1109,  1117,  1123,  1129,  1151,  1153,  1163,
+      1171,  1181,  1187,  1193,  1201,  1213,  1217,  1223,
+      1229,  1231,  1237,  1249,  1259,  1277,  1279,  1283,
+      1289,  1291,  1297,  1301,  1303,  1307,  1319,  1321,
+      1327,  1361,  1367,  1373,  1381,  1399,  1409,  1423,
+      1427,  1429,  1433,  1439,  1447,  1451,  1453,  1459,
+      1471,  1481,  1483,  1487,  1489,  1493,  1499,  1511,
+      1523,  1531,  1543,  1549,  1553,  1559,  1567,  1571,
+      1579,  1583,  1597,  1601,  1607,  1609,  1613,  1619,
+      1621,  1627,  1637,  1657,  1663,  1667,  1669,  1693,
+      1697,  1699,  1709,  1721,  1723,  1733,  1741,  1747,
+      1753,  1759,  1777,  1783,  1787,  1789,  1801,  1811,
+      1823,  1831,  1847,  1861,  1867,  1871,  1873,  1877,
+      1879,  1889,  1901,  1907,  1913,  1931,  1933,  1949,
+      1951,  1973,  1979,  1987,  1993,  1997,  1999,  2003,
+      2011,  2017,  2027,  2029,  2039,  2053,  2063,  2069,
+      2081,  2083,  2087,  2089,  2099,  2111,  2113,  2129,
+      2131,  2137,  2141,  2143,  2153,  2161,  2179,  2203,
+      2207,  2213,  2221,  2237,  2239,  2243,  2251,  2267,
+      2269,  2273,  2281,  2287,  2293,  2297,  2309,  2311,
+      2333,  2339,  2341,  2347,  2351,  2357,  2371,  2377,
+      2381,  2383,  2389,  2393,  2399,  2411,  2417,  2423,
+      2437,  2441,  2447,  2459,  2467,  2473,  2477,  2503,
+      2521,  2531,  2539,  2543,  2549,  2551,  2557,  2579,
+      2591,  2593,  2609,  2617,  2621,  2633,  2647,  2657,
+      2659,  2663,  2671,  2677,  2683,  2687,  2689,  2693,
+      2699,  2707,  2711,  2713,  2719,  2729,  2731,  2741,
+      2749,  2753,  2767,  2777,  2789,  2791,  2797,  2801,
+      2803,  2819,  2833,  2837,  2843,  2851,  2857,  2861,
+      2879,  2887,  2897,  2903,  2909,  2917,  2927,  2939,
+      2953,  2957,  2963,  2969,  2971,  2999,  3001,  3011,
+      3019,  3023,  3037,  3041,  3049,  3061,  3067,  3079,
+      3083,  3089,  3109,  3119,  3121,  3137,  3163,  3167,
+      3169,  3181,  3187,  3191,  3203,  3209,  3217,  3221,
+      3229,  3251,  3253,  3257,  3259,  3271,  3299,  3301,
+      3307,  3313,  3319,  3323,  3329,  3331,  3343,  3347,
+      3359,  3361,  3371,  3373,  3389,  3391,  3407,  3413,
+      3433,  3449,  3457,  3461,  3463,  3467,  3469,  3491,
+      3499,  3511,  3517,  3527,  3529,  3533,  3539,  3541,
+      3547,  3557,  3559,  3571,  3581,  3583,  3593,  3607,
+      3613,  3617,  3623,  3631,  3637,  3643,  3659,  3671,
+      3673,  3677,  3691,  3697,  3701,  3709,  3719,  3727,
+      3733,  3739,  3761,  3767,  3769,  3779,  3793,  3797,
+      3803,  3821,  3823,  3833,  3847,  3851,  3853,  3863,
+      3877,  3881,  3889,  3907,  3911,  3917,  3919,  3923,
+      3929,  3931,  3943,  3947,  3967,  3989,  4001,  4003,
+      4007,  4013,  4019,  4021,  4027,  4049,  4051,  4057,
+      4073,  4079,  4091,  4093,  4099,  4111,  4127,  4129,
+      4133,  4139,  4153,  4157,  4159,  4177,  4201,  4211,
+      4217,  4219,  4229,  4231,  4241,  4243,  4253,  4259,
+      4261,  4271,  4273,  4283,  4289,  4297,  4327,  4337,
+      4339,  4349,  4357,  4363,  4373,  4391,  4397,  4409,
+      4421,  4423,  4441,  4447,  4451,  4457,  4463,  4481,
+      4483,  4493,  4507,  4513,  4517,  4519,  4523,  4547,
+      4549,  4561,  4567,  4583,  4591,  4597,  4603,  4621,
+      4637,  4639,  4643,  4649,  4651,  4657,  4663,  4673,
+      4679,  4691,  4703,  4721,  4723,  4729,  4733,  4751,
+      4759,  4783,  4787,  4789,  4793,  4799,  4801,  4813,
+      4817,  4831,  4861,  4871,  4877,  4889,  4903,  4909,
+      4919,  4931,  4933,  4937,  4943,  4951,  4957,  4967,
+      4969,  4973,  4987,  4993,  4999,  5003,  5009,  5011,
+      5021,  5023,  5039,  5051,  5059,  5077,  5081,  5087,
+      5099,  5101,  5107,  5113,  5119,  5147,  5153,  5167,
+      5171,  5179,  5189,  5197,  5209,  5227,  5231,  5233,
+      5237,  5261,  5273,  5279,  5281,  5297,  5303,  5309,
+      5323,  5333,  5347,  5351,  5381,  5387,  5393,  5399,
+      5407,  5413,  5417,  5419,  5431,  5437,  5441,  5443,
+      5449,  5471,  5477,  5479,  5483,  5501,  5503,  5507,
+      5519,  5521,  5527,  5531,  5557,  5563,  5569,  5573,
+      5581,  5591,  5623,  5639,  5641,  5647,  5651,  5653,
+      5657,  5659,  5669,  5683,  5689,  5693,  5701,  5711,
+      5717,  5737,  5741,  5743,  5749,  5779,  5783,  5791,
+      5801,  5807,  5813,  5821,  5827,  5839,  5843,  5849,
+      5851,  5857,  5861,  5867,  5869,  5879,  5881,  5897,
+      5903,  5923,  5927,  5939,  5953,  5981,  5987,  6007,
+      6011,  6029,  6037,  6043,  6047,  6053,  6067,  6073,
+      6079,  6089,  6091,  6101,  6113,  6121,  6131,  6133,
+      6143,  6151,  6163,  6173,  6197,  6199,  6203,  6211,
+      6217,  6221,  6229,  6247,  6257,  6263,  6269,  6271,
+      6277,  6287,  6299,  6301,  6311,  6317,  6323,  6329,
+      6337,  6343,  6353,  6359,  6361,  6367,  6373,  6379,
+      6389,  6397,  6421,  6427,  6449,  6451,  6469,  6473,
+      6481,  6491,  6521,  6529,  6547,  6551,  6553,  6563,
+      6569,  6571,  6577,  6581,  6599,  6607,  6619,  6637,
+      6653,  6659,  6661,  6673,  6679,  6689,  6691,  6701,
+      6703,  6709,  6719,  6733,  6737,  6761,  6763,  6779,
+      6781,  6791,  6793,  6803,  6823,  6827,  6829,  6833,
+      6841,  6857,  6863,  6869,  6871,  6883,  6899,  6907,
+      6911,  6917,  6947,  6949,  6959,  6961,  6967,  6971,
+      6977,  6983,  6991,  6997,  7001,  7013,  7019,  7027,
+      7039,  7043,  7057,  7069,  7079,  7103,  7109,  7121,
+      7127,  7129,  7151,  7159,  7177,  7187,  7193,  7207,
+      7211,  7213,  7219,  7229,  7237,  7243,  7247,  7253,
+      7283,  7297,  7307,  7309,  7321,  7331,  7333,  7349,
+      7351,  7369,  7393,  7411,  7417,  7433,  7451,  7457,
+      7459,  7477,  7481,  7487,  7489,  7499,  7507,  7517,
+      7523,  7529,  7537,  7541,  7547,  7549,  7559,  7561,
+      7573,  7577,  7583,  7589,  7591,  7603,  7607,  7621,
+      7639,  7643,  7649,  7669,  7673,  7681,  7687,  7691,
+      7699,  7703,  7717,  7723,  7727,  7741,  7753,  7757,
+      7759,  7789,  7793,  7817,  7823,  7829,  7841,  7853,
+      7867,  7873,  7877,  7879,  7883,  7901,  7907,  7919,
+      7927,  7933,  7937,  7949,  7951,  7963,  7993,  8009,
+      8011,  8017,  8039,  8053,  8059,  8069,  8081,  8087,
+      8089,  8093,  8101,  8111,  8117,  8123,  8147,  8161,
+      8167,  8171,  8179,  8191,  8209,  8219,  8221,  8231,
+      8233,  8237,  8243,  8263,  8269,  8273,  8287,  8291,
+      8293,  8297,  8311,  8317,  8329,  8353,  8363,  8369,
+      8377,  8387,  8389,  8419,  8423,  8429,  8431,  8443,
+      8447,  8461,  8467,  8501,  8513,  8521,  8527,  8537,
+      8539,  8543,  8563,  8573,  8581,  8597,  8599,  8609,
+      8623,  8627,  8629,  8641,  8647,  8663,  8669,  8677,
+      8681,  8689,  8693,  8699,  8707,  8713,  8719,  8731,
+      8737,  8741,  8747,  8753,  8761,  8779,  8783,  8803,
+      8807,  8819,  8821,  8831,  8837,  8839,  8849,  8861,
+      8863,  8867,  8887,  8893,  8923,  8929,  8933,  8941,
+      8951,  8963,  8969,  8971,  8999,  9001,  9007,  9011,
+      9013,  9029,  9041,  9043,  9049,  9059,  9067,  9091,
+      9103,  9109,  9127,  9133,  9137,  9151,  9157,  9161,
+      9173,  9181,  9187,  9199,  9203,  9209,  9221,  9227,
+      9239,  9241,  9257,  9277,  9281,  9283,  9293,  9311,
+      9319,  9323,  9337,  9341,  9343,  9349,  9371,  9377,
+      9391,  9397,  9403,  9413,  9419,  9421,  9431,  9433,
+      9437,  9439,  9461,  9463,  9467,  9473,  9479,  9491,
+      9497,  9511,  9521,  9533,  9539,  9547,  9551,  9587,
+      9601,  9613,  9619,  9623,  9629,  9631,  9643,  9649,
+      9661,  9677,  9679,  9689,  9697,  9719,  9721,  9733,
+      9739,  9743,  9749,  9767,  9769,  9781,  9787,  9791,
+      9803,  9811,  9817,  9829,  9833,  9839,  9851,  9857,
+      9859,  9871,  9883,  9887,  9901,  9907,  9923,  9929,
+      9931,  9941,  9949,  9967,  9973, 10007, 10009, 10037,
+     10039, 10061, 10067, 10069, 10079, 10091, 10093, 10099,
+     10103, 10111, 10133, 10139, 10141, 10151, 10159, 10163,
+     10169, 10177, 10181, 10193, 10211, 10223, 10243, 10247,
+     10253, 10259, 10267, 10271, 10273, 10289, 10301, 10303,
+     10313, 10321, 10331, 10333, 10337, 10343, 10357, 10369,
+     10391, 10399, 10427, 10429, 10433, 10453, 10457, 10459,
+     10463, 10477, 10487, 10499, 10501, 10513, 10529, 10531,
+     10559, 10567, 10589, 10597, 10601, 10607, 10613, 10627,
+     10631, 10639, 10651, 10657, 10663, 10667, 10687, 10691,
+     10709, 10711, 10723, 10729, 10733, 10739, 10753, 10771,
+     10781, 10789, 10799, 10831, 10837, 10847, 10853, 10859,
+     10861, 10867, 10883, 10889, 10891, 10903, 10909, 10937,
+     10939, 10949, 10957, 10973, 10979, 10987, 10993, 11003,
+     11027, 11047, 11057, 11059, 11069, 11071, 11083, 11087,
+     11093, 11113, 11117, 11119, 11131, 11149, 11159, 11161,
+     11171, 11173, 11177, 11197, 11213, 11239, 11243, 11251,
+     11257, 11261, 11273, 11279, 11287, 11299, 11311, 11317,
+     11321, 11329, 11351, 11353, 11369, 11383, 11393, 11399,
+     11411, 11423, 11437, 11443, 11447, 11467, 11471, 11483,
+     11489, 11491, 11497, 11503, 11519, 11527, 11549, 11551,
+     11579, 11587, 11593, 11597, 11617, 11621, 11633, 11657,
+     11677, 11681, 11689, 11699, 11701, 11717, 11719, 11731,
+     11743, 11777, 11779, 11783, 11789, 11801, 11807, 11813,
+     11821, 11827, 11831, 11833, 11839, 11863, 11867, 11887,
+     11897, 11903, 11909, 11923, 11927, 11933, 11939, 11941,
+     11953, 11959, 11969, 11971, 11981, 11987, 12007, 12011,
+     12037, 12041, 12043, 12049, 12071, 12073, 12097, 12101,
+     12107, 12109, 12113, 12119, 12143, 12149, 12157, 12161,
+     12163, 12197, 12203, 12211, 12227, 12239, 12241, 12251,
+     12253, 12263, 12269, 12277, 12281, 12289, 12301, 12323,
+     12329, 12343, 12347, 12373, 12377, 12379, 12391, 12401,
+     12409, 12413, 12421, 12433, 12437, 12451, 12457, 12473,
+     12479, 12487, 12491, 12497, 12503, 12511, 12517, 12527,
+     12539, 12541, 12547, 12553, 12569, 12577, 12583, 12589,
+     12601, 12611, 12613, 12619, 12637, 12641, 12647, 12653,
+     12659, 12671, 12689, 12697, 12703, 12713, 12721, 12739,
+     12743, 12757, 12763, 12781, 12791, 12799, 12809, 12821,
+     12823, 12829, 12841, 12853, 12889, 12893, 12899, 12907,
+     12911, 12917, 12919, 12923, 12941, 12953, 12959, 12967,
+     12973, 12979, 12983, 13001, 13003, 13007, 13009, 13033,
+     13037, 13043, 13049, 13063, 13093, 13099, 13103, 13109,
+     13121, 13127, 13147, 13151, 13159, 13163, 13171, 13177,
+     13183, 13187, 13217, 13219, 13229, 13241, 13249, 13259,
+     13267, 13291, 13297, 13309, 13313, 13327, 13331, 13337,
+     13339, 13367, 13381, 13397, 13399, 13411, 13417, 13421,
+     13441, 13451, 13457, 13463, 13469, 13477, 13487, 13499,
+     13513, 13523, 13537, 13553, 13567, 13577, 13591, 13597,
+     13613, 13619, 13627, 13633, 13649, 13669, 13679, 13681,
+     13687, 13691, 13693, 13697, 13709, 13711, 13721, 13723,
+     13729, 13751, 13757, 13759, 13763, 13781, 13789, 13799,
+     13807, 13829, 13831, 13841, 13859, 13873, 13877, 13879,
+     13883, 13901, 13903, 13907, 13913, 13921, 13931, 13933,
+     13963, 13967, 13997, 13999, 14009, 14011, 14029, 14033,
+     14051, 14057, 14071, 14081, 14083, 14087, 14107, 14143,
+     14149, 14153, 14159, 14173, 14177, 14197, 14207, 14221,
+     14243, 14249, 14251, 14281, 14293, 14303, 14321, 14323,
+     14327, 14341, 14347, 14369, 14387, 14389, 14401, 14407,
+     14411, 14419, 14423, 14431, 14437, 14447, 14449, 14461,
+     14479, 14489, 14503, 14519, 14533, 14537, 14543, 14549,
+     14551, 14557, 14561, 14563, 14591, 14593, 14621, 14627,
+     14629, 14633, 14639, 14653, 14657, 14669, 14683, 14699,
+     14713, 14717, 14723, 14731, 14737, 14741, 14747, 14753,
+     14759, 14767, 14771, 14779, 14783, 14797, 14813, 14821,
+     14827, 14831, 14843, 14851, 14867, 14869, 14879, 14887,
+     14891, 14897, 14923, 14929, 14939, 14947, 14951, 14957,
+     14969, 14983, 15013, 15017, 15031, 15053, 15061, 15073,
+     15077, 15083, 15091, 15101, 15107, 15121, 15131, 15137,
+     15139, 15149, 15161, 15173, 15187, 15193, 15199, 15217,
+     15227, 15233, 15241, 15259, 15263, 15269, 15271, 15277,
+     15287, 15289, 15299, 15307, 15313, 15319, 15329, 15331,
+     15349, 15359, 15361, 15373, 15377, 15383, 15391, 15401,
+     15413, 15427, 15439, 15443, 15451, 15461, 15467, 15473,
+     15493, 15497, 15511, 15527, 15541, 15551, 15559, 15569,
+     15581, 15583, 15601, 15607, 15619, 15629, 15641, 15643,
+     15647, 15649, 15661, 15667, 15671, 15679, 15683, 15727,
+     15731, 15733, 15737, 15739, 15749, 15761, 15767, 15773,
+     15787, 15791, 15797, 15803, 15809, 15817, 15823, 15859,
+     15877, 15881, 15887, 15889, 15901, 15907, 15913, 15919,
+     15923, 15937, 15959, 15971, 15973, 15991, 16001, 16007,
+     16033, 16057, 16061, 16063, 16067, 16069, 16073, 16087,
+     16091, 16097, 16103, 16111, 16127, 16139, 16141, 16183,
+     16187, 16189, 16193, 16217, 16223, 16229, 16231, 16249,
+     16253, 16267, 16273, 16301, 16319, 16333, 16339, 16349,
+     16361, 16363, 16369, 16381, 16411, 16417, 16421, 16427,
+     16433, 16447, 16451, 16453, 16477, 16481, 16487, 16493,
+     16519, 16529, 16547, 16553, 16561, 16567, 16573, 16603,
+     16607, 16619, 16631, 16633, 16649, 16651, 16657, 16661,
+     16673, 16691, 16693, 16699, 16703, 16729, 16741, 16747,
+     16759, 16763, 16787, 16811, 16823, 16829, 16831, 16843,
+     16871, 16879, 16883, 16889, 16901, 16903, 16921, 16927,
+     16931, 16937, 16943, 16963, 16979, 16981, 16987, 16993,
+     17011, 17021, 17027, 17029, 17033, 17041, 17047, 17053,
+     17077, 17093, 17099, 17107, 17117, 17123, 17137, 17159,
+     17167, 17183, 17189, 17191, 17203, 17207, 17209, 17231,
+     17239, 17257, 17291, 17293, 17299, 17317, 17321, 17327,
+     17333, 17341, 17351, 17359, 17377, 17383, 17387, 17389,
+     17393, 17401, 17417, 17419, 17431, 17443, 17449, 17467,
+     17471, 17477, 17483, 17489, 17491, 17497, 17509, 17519,
+     17539, 17551, 17569, 17573, 17579, 17581, 17597, 17599,
+     17609, 17623, 17627, 17657, 17659, 17669, 17681, 17683,
+     17707, 17713, 17729, 17737, 17747, 17749, 17761, 17783,
+     17789, 17791, 17807, 17827, 17837, 17839, 17851, 17863,
 #endif
 };
Index: vendor-crypto/openssl/dist/crypto/bn/bn_prime.pl
===================================================================
--- vendor-crypto/openssl/dist/crypto/bn/bn_prime.pl	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/bn/bn_prime.pl	(revision 318897)
@@ -1,119 +1,119 @@
 #!/usr/local/bin/perl
 # bn_prime.pl
 
 $num=2048;
 $num=$ARGV[0] if ($#ARGV >= 0);
 
 push(@primes,2);
 $p=1;
 loop: while ($#primes < $num-1)
 	{
 	$p+=2;
 	$s=int(sqrt($p));
 
 	for ($i=0; defined($primes[$i]) && $primes[$i]<=$s; $i++)
 		{
 		next loop if (($p%$primes[$i]) == 0);
 		}
 	push(@primes,$p);
 	}
 
 # print <<"EOF";
 # /* Auto generated by bn_prime.pl */
 # /* Copyright (C) 1995-1997 Eric Young (eay\@mincom.oz.au).
 #  * All rights reserved.
 #  * Copyright remains Eric Young's, and as such any Copyright notices in
 #  * the code are not to be removed.
 #  * See the COPYRIGHT file in the SSLeay distribution for more details.
 #  */
-# 
+#
 # EOF
 
 print <<\EOF;
 /* Auto generated by bn_prime.pl */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
- * 
+ *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
- * 
+ *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
- * 
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
- * 4. If you include any Windows specific code (or a derivative thereof) from 
+ * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
- * 
+ *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
- * 
+ *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 
 EOF
 
 for ($i=0; $i <= $#primes; $i++)
 	{
 	if ($primes[$i] > 256)
 		{
 		$eight=$i;
 		last;
 		}
 	}
 
 printf "#ifndef EIGHT_BIT\n";
-printf "#define NUMPRIMES %d\n",$num;
+printf "# define NUMPRIMES %d\n",$num;
 printf "typedef unsigned short prime_t;\n";
 printf "#else\n";
-printf "#define NUMPRIMES %d\n",$eight;
+printf "# define NUMPRIMES %d\n",$eight;
 printf "typedef unsigned char prime_t;\n";
 printf "#endif\n";
-print "static const prime_t primes[NUMPRIMES]=\n\t{\n\t";
+print "static const prime_t primes[NUMPRIMES] = {";
 $init=0;
 for ($i=0; $i <= $#primes; $i++)
 	{
-	printf "\n#ifndef EIGHT_BIT\n\t" if ($primes[$i] > 256) && !($init++);
-	printf("\n\t") if (($i%8) == 0) && ($i != 0);
-	printf("%4d,",$primes[$i]);
+	printf "\n#ifndef EIGHT_BIT\n    " if ($primes[$i] > 256) && !($init++);
+	printf("\n    ") if ($i%8) == 0;
+	printf(" %5d,",$primes[$i]);
 	}
-print "\n#endif\n\t};\n";
+print "\n#endif\n};\n";
 
 
Index: vendor-crypto/openssl/dist/crypto/bn/bn_print.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/bn/bn_print.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/bn/bn_print.c	(revision 318897)
@@ -1,404 +1,402 @@
 /* crypto/bn/bn_print.c */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 
 #include 
 #include 
 #include 
 #include "cryptlib.h"
 #include 
 #include "bn_lcl.h"
 
 static const char Hex[] = "0123456789ABCDEF";
 
 /* Must 'OPENSSL_free' the returned data */
 char *BN_bn2hex(const BIGNUM *a)
 {
     int i, j, v, z = 0;
     char *buf;
     char *p;
 
     if (BN_is_zero(a))
         return OPENSSL_strdup("0");
     buf = OPENSSL_malloc(a->top * BN_BYTES * 2 + 2);
     if (buf == NULL) {
         BNerr(BN_F_BN_BN2HEX, ERR_R_MALLOC_FAILURE);
         goto err;
     }
     p = buf;
     if (a->neg)
         *(p++) = '-';
-    if (BN_is_zero(a))
-        *(p++) = '0';
     for (i = a->top - 1; i >= 0; i--) {
         for (j = BN_BITS2 - 8; j >= 0; j -= 8) {
             /* strip leading zeros */
             v = ((int)(a->d[i] >> (long)j)) & 0xff;
             if (z || (v != 0)) {
                 *(p++) = Hex[v >> 4];
                 *(p++) = Hex[v & 0x0f];
                 z = 1;
             }
         }
     }
     *p = '\0';
  err:
     return (buf);
 }
 
 /* Must 'OPENSSL_free' the returned data */
 char *BN_bn2dec(const BIGNUM *a)
 {
     int i = 0, num, ok = 0;
     char *buf = NULL;
     char *p;
     BIGNUM *t = NULL;
     BN_ULONG *bn_data = NULL, *lp;
     int bn_data_num;
 
     /*-
      * get an upper bound for the length of the decimal integer
      * num <= (BN_num_bits(a) + 1) * log(2)
      *     <= 3 * BN_num_bits(a) * 0.1001 + log(2) + 1     (rounding error)
      *     <= BN_num_bits(a)/10 + BN_num_bits/1000 + 1 + 1
      */
     i = BN_num_bits(a) * 3;
     num = (i / 10 + i / 1000 + 1) + 1;
     bn_data_num = num / BN_DEC_NUM + 1;
     bn_data = OPENSSL_malloc(bn_data_num * sizeof(BN_ULONG));
     buf = OPENSSL_malloc(num + 3);
     if ((buf == NULL) || (bn_data == NULL)) {
         BNerr(BN_F_BN_BN2DEC, ERR_R_MALLOC_FAILURE);
         goto err;
     }
     if ((t = BN_dup(a)) == NULL)
         goto err;
 
 #define BUF_REMAIN (num+3 - (size_t)(p - buf))
     p = buf;
     lp = bn_data;
     if (BN_is_zero(t)) {
         *(p++) = '0';
         *(p++) = '\0';
     } else {
         if (BN_is_negative(t))
             *p++ = '-';
 
         while (!BN_is_zero(t)) {
             if (lp - bn_data >= bn_data_num)
                 goto err;
             *lp = BN_div_word(t, BN_DEC_CONV);
             if (*lp == (BN_ULONG)-1)
                 goto err;
             lp++;
         }
         lp--;
         /*
          * We now have a series of blocks, BN_DEC_NUM chars in length, where
          * the last one needs truncation. The blocks need to be reversed in
          * order.
          */
         BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT1, *lp);
         while (*p)
             p++;
         while (lp != bn_data) {
             lp--;
             BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT2, *lp);
             while (*p)
                 p++;
         }
     }
     ok = 1;
  err:
     if (bn_data != NULL)
         OPENSSL_free(bn_data);
     if (t != NULL)
         BN_free(t);
     if (!ok && buf) {
         OPENSSL_free(buf);
         buf = NULL;
     }
 
     return (buf);
 }
 
 int BN_hex2bn(BIGNUM **bn, const char *a)
 {
     BIGNUM *ret = NULL;
     BN_ULONG l = 0;
     int neg = 0, h, m, i, j, k, c;
     int num;
 
     if ((a == NULL) || (*a == '\0'))
         return (0);
 
     if (*a == '-') {
         neg = 1;
         a++;
     }
 
     for (i = 0; i <= (INT_MAX/4) && isxdigit((unsigned char)a[i]); i++)
         continue;
 
     if (i > INT_MAX/4)
         goto err;
 
     num = i + neg;
     if (bn == NULL)
         return (num);
 
     /* a is the start of the hex digits, and it is 'i' long */
     if (*bn == NULL) {
         if ((ret = BN_new()) == NULL)
             return (0);
     } else {
         ret = *bn;
         BN_zero(ret);
     }
 
     /* i is the number of hex digits */
     if (bn_expand(ret, i * 4) == NULL)
         goto err;
 
     j = i;                      /* least significant 'hex' */
     m = 0;
     h = 0;
     while (j > 0) {
         m = ((BN_BYTES * 2) <= j) ? (BN_BYTES * 2) : j;
         l = 0;
         for (;;) {
             c = a[j - m];
             if ((c >= '0') && (c <= '9'))
                 k = c - '0';
             else if ((c >= 'a') && (c <= 'f'))
                 k = c - 'a' + 10;
             else if ((c >= 'A') && (c <= 'F'))
                 k = c - 'A' + 10;
             else
                 k = 0;          /* paranoia */
             l = (l << 4) | k;
 
             if (--m <= 0) {
                 ret->d[h++] = l;
                 break;
             }
         }
         j -= (BN_BYTES * 2);
     }
     ret->top = h;
     bn_correct_top(ret);
 
     *bn = ret;
     bn_check_top(ret);
     /* Don't set the negative flag if it's zero. */
     if (ret->top != 0)
         ret->neg = neg;
     return (num);
  err:
     if (*bn == NULL)
         BN_free(ret);
     return (0);
 }
 
 int BN_dec2bn(BIGNUM **bn, const char *a)
 {
     BIGNUM *ret = NULL;
     BN_ULONG l = 0;
     int neg = 0, i, j;
     int num;
 
     if ((a == NULL) || (*a == '\0'))
         return (0);
     if (*a == '-') {
         neg = 1;
         a++;
     }
 
     for (i = 0; i <= (INT_MAX/4) && isdigit((unsigned char)a[i]); i++)
         continue;
 
     if (i > INT_MAX/4)
         goto err;
 
     num = i + neg;
     if (bn == NULL)
         return (num);
 
     /*
      * a is the start of the digits, and it is 'i' long. We chop it into
      * BN_DEC_NUM digits at a time
      */
     if (*bn == NULL) {
         if ((ret = BN_new()) == NULL)
             return (0);
     } else {
         ret = *bn;
         BN_zero(ret);
     }
 
     /* i is the number of digits, a bit of an over expand */
     if (bn_expand(ret, i * 4) == NULL)
         goto err;
 
     j = BN_DEC_NUM - (i % BN_DEC_NUM);
     if (j == BN_DEC_NUM)
         j = 0;
     l = 0;
     while (--i >= 0) {
         l *= 10;
         l += *a - '0';
         a++;
         if (++j == BN_DEC_NUM) {
             BN_mul_word(ret, BN_DEC_CONV);
             BN_add_word(ret, l);
             l = 0;
             j = 0;
         }
     }
 
     bn_correct_top(ret);
     *bn = ret;
     bn_check_top(ret);
     /* Don't set the negative flag if it's zero. */
     if (ret->top != 0)
         ret->neg = neg;
     return (num);
  err:
     if (*bn == NULL)
         BN_free(ret);
     return (0);
 }
 
 int BN_asc2bn(BIGNUM **bn, const char *a)
 {
     const char *p = a;
 
     if (*p == '-')
         p++;
 
     if (p[0] == '0' && (p[1] == 'X' || p[1] == 'x')) {
         if (!BN_hex2bn(bn, p + 2))
             return 0;
     } else {
         if (!BN_dec2bn(bn, p))
             return 0;
     }
     /* Don't set the negative flag if it's zero. */
     if (*a == '-' && (*bn)->top != 0)
         (*bn)->neg = 1;
     return 1;
 }
 
 #ifndef OPENSSL_NO_BIO
 # ifndef OPENSSL_NO_FP_API
 int BN_print_fp(FILE *fp, const BIGNUM *a)
 {
     BIO *b;
     int ret;
 
     if ((b = BIO_new(BIO_s_file())) == NULL)
         return (0);
     BIO_set_fp(b, fp, BIO_NOCLOSE);
     ret = BN_print(b, a);
     BIO_free(b);
     return (ret);
 }
 # endif
 
 int BN_print(BIO *bp, const BIGNUM *a)
 {
     int i, j, v, z = 0;
     int ret = 0;
 
     if ((a->neg) && (BIO_write(bp, "-", 1) != 1))
         goto end;
     if (BN_is_zero(a) && (BIO_write(bp, "0", 1) != 1))
         goto end;
     for (i = a->top - 1; i >= 0; i--) {
         for (j = BN_BITS2 - 4; j >= 0; j -= 4) {
             /* strip leading zeros */
             v = ((int)(a->d[i] >> (long)j)) & 0x0f;
             if (z || (v != 0)) {
                 if (BIO_write(bp, &(Hex[v]), 1) != 1)
                     goto end;
                 z = 1;
             }
         }
     }
     ret = 1;
  end:
     return (ret);
 }
 #endif
 
 char *BN_options(void)
 {
     static int init = 0;
     static char data[16];
 
     if (!init) {
         init++;
 #ifdef BN_LLONG
         BIO_snprintf(data, sizeof data, "bn(%d,%d)",
                      (int)sizeof(BN_ULLONG) * 8, (int)sizeof(BN_ULONG) * 8);
 #else
         BIO_snprintf(data, sizeof data, "bn(%d,%d)",
                      (int)sizeof(BN_ULONG) * 8, (int)sizeof(BN_ULONG) * 8);
 #endif
     }
     return (data);
 }
Index: vendor-crypto/openssl/dist/crypto/comp/c_rle.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/comp/c_rle.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/comp/c_rle.c	(revision 318897)
@@ -1,62 +1,63 @@
 #include 
 #include 
 #include 
 #include 
 #include 
 
 static int rle_compress_block(COMP_CTX *ctx, unsigned char *out,
                               unsigned int olen, unsigned char *in,
                               unsigned int ilen);
 static int rle_expand_block(COMP_CTX *ctx, unsigned char *out,
                             unsigned int olen, unsigned char *in,
                             unsigned int ilen);
 
 static COMP_METHOD rle_method = {
     NID_rle_compression,
     LN_rle_compression,
     NULL,
     NULL,
     rle_compress_block,
     rle_expand_block,
     NULL,
     NULL,
 };
 
 COMP_METHOD *COMP_rle(void)
 {
     return (&rle_method);
 }
 
 static int rle_compress_block(COMP_CTX *ctx, unsigned char *out,
                               unsigned int olen, unsigned char *in,
                               unsigned int ilen)
 {
-    /* int i; */
+    if (ilen == 0)
+        return 0;
 
-    if (ilen == 0 || olen < (ilen - 1)) {
-        /* ZZZZZZZZZZZZZZZZZZZZZZ */
-        return (-1);
-    }
+    if (olen <= ilen)
+        return -1;
 
     *(out++) = 0;
     memcpy(out, in, ilen);
     return (ilen + 1);
 }
 
 static int rle_expand_block(COMP_CTX *ctx, unsigned char *out,
                             unsigned int olen, unsigned char *in,
                             unsigned int ilen)
 {
     int i;
 
-    if (olen < (ilen - 1)) {
-        /* ZZZZZZZZZZZZZZZZZZZZZZ */
-        return (-1);
-    }
+    if (ilen == 0)
+        return 0;
 
+    if (olen < (ilen - 1))
+        return -1;
+
     i = *(in++);
-    if (i == 0) {
-        memcpy(out, in, ilen - 1);
-    }
+    if (i != 0)
+        return -1;
+
+    memcpy(out, in, ilen - 1);
     return (ilen - 1);
 }
Index: vendor-crypto/openssl/dist/crypto/conf/conf.h
===================================================================
--- vendor-crypto/openssl/dist/crypto/conf/conf.h	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/conf/conf.h	(revision 318897)
@@ -1,267 +1,268 @@
 /* crypto/conf/conf.h */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 
 #ifndef  HEADER_CONF_H
 # define HEADER_CONF_H
 
 # include 
 # include 
 # include 
 # include 
 # include 
 
 # include 
 
 #ifdef  __cplusplus
 extern "C" {
 #endif
 
 typedef struct {
     char *section;
     char *name;
     char *value;
 } CONF_VALUE;
 
 DECLARE_STACK_OF(CONF_VALUE)
 DECLARE_LHASH_OF(CONF_VALUE);
 
 struct conf_st;
 struct conf_method_st;
 typedef struct conf_method_st CONF_METHOD;
 
 struct conf_method_st {
     const char *name;
     CONF *(*create) (CONF_METHOD *meth);
     int (*init) (CONF *conf);
     int (*destroy) (CONF *conf);
     int (*destroy_data) (CONF *conf);
     int (*load_bio) (CONF *conf, BIO *bp, long *eline);
     int (*dump) (const CONF *conf, BIO *bp);
     int (*is_number) (const CONF *conf, char c);
     int (*to_int) (const CONF *conf, char c);
     int (*load) (CONF *conf, const char *name, long *eline);
 };
 
 /* Module definitions */
 
 typedef struct conf_imodule_st CONF_IMODULE;
 typedef struct conf_module_st CONF_MODULE;
 
 DECLARE_STACK_OF(CONF_MODULE)
 DECLARE_STACK_OF(CONF_IMODULE)
 
 /* DSO module function typedefs */
 typedef int conf_init_func (CONF_IMODULE *md, const CONF *cnf);
 typedef void conf_finish_func (CONF_IMODULE *md);
 
 # define CONF_MFLAGS_IGNORE_ERRORS       0x1
 # define CONF_MFLAGS_IGNORE_RETURN_CODES 0x2
 # define CONF_MFLAGS_SILENT              0x4
 # define CONF_MFLAGS_NO_DSO              0x8
 # define CONF_MFLAGS_IGNORE_MISSING_FILE 0x10
 # define CONF_MFLAGS_DEFAULT_SECTION     0x20
 
 int CONF_set_default_method(CONF_METHOD *meth);
 void CONF_set_nconf(CONF *conf, LHASH_OF(CONF_VALUE) *hash);
 LHASH_OF(CONF_VALUE) *CONF_load(LHASH_OF(CONF_VALUE) *conf, const char *file,
                                 long *eline);
 # ifndef OPENSSL_NO_FP_API
 LHASH_OF(CONF_VALUE) *CONF_load_fp(LHASH_OF(CONF_VALUE) *conf, FILE *fp,
                                    long *eline);
 # endif
 LHASH_OF(CONF_VALUE) *CONF_load_bio(LHASH_OF(CONF_VALUE) *conf, BIO *bp,
                                     long *eline);
 STACK_OF(CONF_VALUE) *CONF_get_section(LHASH_OF(CONF_VALUE) *conf,
                                        const char *section);
 char *CONF_get_string(LHASH_OF(CONF_VALUE) *conf, const char *group,
                       const char *name);
 long CONF_get_number(LHASH_OF(CONF_VALUE) *conf, const char *group,
                      const char *name);
 void CONF_free(LHASH_OF(CONF_VALUE) *conf);
 int CONF_dump_fp(LHASH_OF(CONF_VALUE) *conf, FILE *out);
 int CONF_dump_bio(LHASH_OF(CONF_VALUE) *conf, BIO *out);
 
 void OPENSSL_config(const char *config_name);
 void OPENSSL_no_config(void);
 
 /*
  * New conf code.  The semantics are different from the functions above. If
  * that wasn't the case, the above functions would have been replaced
  */
 
 struct conf_st {
     CONF_METHOD *meth;
     void *meth_data;
     LHASH_OF(CONF_VALUE) *data;
 };
 
 CONF *NCONF_new(CONF_METHOD *meth);
 CONF_METHOD *NCONF_default(void);
 CONF_METHOD *NCONF_WIN32(void);
 # if 0                          /* Just to give you an idea of what I have in
                                  * mind */
 CONF_METHOD *NCONF_XML(void);
 # endif
 void NCONF_free(CONF *conf);
 void NCONF_free_data(CONF *conf);
 
 int NCONF_load(CONF *conf, const char *file, long *eline);
 # ifndef OPENSSL_NO_FP_API
 int NCONF_load_fp(CONF *conf, FILE *fp, long *eline);
 # endif
 int NCONF_load_bio(CONF *conf, BIO *bp, long *eline);
 STACK_OF(CONF_VALUE) *NCONF_get_section(const CONF *conf,
                                         const char *section);
 char *NCONF_get_string(const CONF *conf, const char *group, const char *name);
 int NCONF_get_number_e(const CONF *conf, const char *group, const char *name,
                        long *result);
 int NCONF_dump_fp(const CONF *conf, FILE *out);
 int NCONF_dump_bio(const CONF *conf, BIO *out);
 
 # if 0                          /* The following function has no error
                                  * checking, and should therefore be avoided */
 long NCONF_get_number(CONF *conf, char *group, char *name);
 # else
 #  define NCONF_get_number(c,g,n,r) NCONF_get_number_e(c,g,n,r)
 # endif
 
 /* Module functions */
 
 int CONF_modules_load(const CONF *cnf, const char *appname,
                       unsigned long flags);
 int CONF_modules_load_file(const char *filename, const char *appname,
                            unsigned long flags);
 void CONF_modules_unload(int all);
 void CONF_modules_finish(void);
 void CONF_modules_free(void);
 int CONF_module_add(const char *name, conf_init_func *ifunc,
                     conf_finish_func *ffunc);
 
 const char *CONF_imodule_get_name(const CONF_IMODULE *md);
 const char *CONF_imodule_get_value(const CONF_IMODULE *md);
 void *CONF_imodule_get_usr_data(const CONF_IMODULE *md);
 void CONF_imodule_set_usr_data(CONF_IMODULE *md, void *usr_data);
 CONF_MODULE *CONF_imodule_get_module(const CONF_IMODULE *md);
 unsigned long CONF_imodule_get_flags(const CONF_IMODULE *md);
 void CONF_imodule_set_flags(CONF_IMODULE *md, unsigned long flags);
 void *CONF_module_get_usr_data(CONF_MODULE *pmod);
 void CONF_module_set_usr_data(CONF_MODULE *pmod, void *usr_data);
 
 char *CONF_get1_default_config_file(void);
 
 int CONF_parse_list(const char *list, int sep, int nospc,
                     int (*list_cb) (const char *elem, int len, void *usr),
                     void *arg);
 
 void OPENSSL_load_builtin_modules(void);
 
 /* BEGIN ERROR CODES */
 /*
  * The following lines are auto generated by the script mkerr.pl. Any changes
  * made after this point may be overwritten when the script is next run.
  */
 void ERR_load_CONF_strings(void);
 
 /* Error codes for the CONF functions. */
 
 /* Function codes. */
 # define CONF_F_CONF_DUMP_FP                              104
 # define CONF_F_CONF_LOAD                                 100
 # define CONF_F_CONF_LOAD_BIO                             102
 # define CONF_F_CONF_LOAD_FP                              103
 # define CONF_F_CONF_MODULES_LOAD                         116
 # define CONF_F_CONF_PARSE_LIST                           119
 # define CONF_F_DEF_LOAD                                  120
 # define CONF_F_DEF_LOAD_BIO                              121
 # define CONF_F_MODULE_INIT                               115
 # define CONF_F_MODULE_LOAD_DSO                           117
 # define CONF_F_MODULE_RUN                                118
 # define CONF_F_NCONF_DUMP_BIO                            105
 # define CONF_F_NCONF_DUMP_FP                             106
 # define CONF_F_NCONF_GET_NUMBER                          107
 # define CONF_F_NCONF_GET_NUMBER_E                        112
 # define CONF_F_NCONF_GET_SECTION                         108
 # define CONF_F_NCONF_GET_STRING                          109
 # define CONF_F_NCONF_LOAD                                113
 # define CONF_F_NCONF_LOAD_BIO                            110
 # define CONF_F_NCONF_LOAD_FP                             114
 # define CONF_F_NCONF_NEW                                 111
 # define CONF_F_STR_COPY                                  101
 
 /* Reason codes. */
 # define CONF_R_ERROR_LOADING_DSO                         110
 # define CONF_R_LIST_CANNOT_BE_NULL                       115
 # define CONF_R_MISSING_CLOSE_SQUARE_BRACKET              100
 # define CONF_R_MISSING_EQUAL_SIGN                        101
 # define CONF_R_MISSING_FINISH_FUNCTION                   111
 # define CONF_R_MISSING_INIT_FUNCTION                     112
 # define CONF_R_MODULE_INITIALIZATION_ERROR               109
 # define CONF_R_NO_CLOSE_BRACE                            102
 # define CONF_R_NO_CONF                                   105
 # define CONF_R_NO_CONF_OR_ENVIRONMENT_VARIABLE           106
 # define CONF_R_NO_SECTION                                107
 # define CONF_R_NO_SUCH_FILE                              114
 # define CONF_R_NO_VALUE                                  108
 # define CONF_R_UNABLE_TO_CREATE_NEW_SECTION              103
 # define CONF_R_UNKNOWN_MODULE_NAME                       113
+# define CONF_R_VARIABLE_EXPANSION_TOO_LONG               116
 # define CONF_R_VARIABLE_HAS_NO_VALUE                     104
 
 #ifdef  __cplusplus
 }
 #endif
 #endif
Index: vendor-crypto/openssl/dist/crypto/conf/conf_def.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/conf/conf_def.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/conf/conf_def.c	(revision 318897)
@@ -1,706 +1,718 @@
 /* crypto/conf/conf.c */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 
 /* Part of the code in here was originally in conf.c, which is now removed */
 
 #include 
 #include 
 #include "cryptlib.h"
 #include 
 #include 
 #include 
 #include 
 #include "conf_def.h"
 #include 
 #include 
 
+/*
+ * The maximum length we can grow a value to after variable expansion. 64k
+ * should be more than enough for all reasonable uses.
+ */
+#define MAX_CONF_VALUE_LENGTH       65536
+
 static char *eat_ws(CONF *conf, char *p);
 static char *eat_alpha_numeric(CONF *conf, char *p);
 static void clear_comments(CONF *conf, char *p);
 static int str_copy(CONF *conf, char *section, char **to, char *from);
 static char *scan_quote(CONF *conf, char *p);
 static char *scan_dquote(CONF *conf, char *p);
 #define scan_esc(conf,p)        (((IS_EOF((conf),(p)[1]))?((p)+1):((p)+2)))
 
 static CONF *def_create(CONF_METHOD *meth);
 static int def_init_default(CONF *conf);
 static int def_init_WIN32(CONF *conf);
 static int def_destroy(CONF *conf);
 static int def_destroy_data(CONF *conf);
 static int def_load(CONF *conf, const char *name, long *eline);
 static int def_load_bio(CONF *conf, BIO *bp, long *eline);
 static int def_dump(const CONF *conf, BIO *bp);
 static int def_is_number(const CONF *conf, char c);
 static int def_to_int(const CONF *conf, char c);
 
 const char CONF_def_version[] = "CONF_def" OPENSSL_VERSION_PTEXT;
 
 static CONF_METHOD default_method = {
     "OpenSSL default",
     def_create,
     def_init_default,
     def_destroy,
     def_destroy_data,
     def_load_bio,
     def_dump,
     def_is_number,
     def_to_int,
     def_load
 };
 
 static CONF_METHOD WIN32_method = {
     "WIN32",
     def_create,
     def_init_WIN32,
     def_destroy,
     def_destroy_data,
     def_load_bio,
     def_dump,
     def_is_number,
     def_to_int,
     def_load
 };
 
 CONF_METHOD *NCONF_default()
 {
     return &default_method;
 }
 
 CONF_METHOD *NCONF_WIN32()
 {
     return &WIN32_method;
 }
 
 static CONF *def_create(CONF_METHOD *meth)
 {
     CONF *ret;
 
     ret = OPENSSL_malloc(sizeof(CONF) + sizeof(unsigned short *));
     if (ret)
         if (meth->init(ret) == 0) {
             OPENSSL_free(ret);
             ret = NULL;
         }
     return ret;
 }
 
 static int def_init_default(CONF *conf)
 {
     if (conf == NULL)
         return 0;
 
     conf->meth = &default_method;
     conf->meth_data = CONF_type_default;
     conf->data = NULL;
 
     return 1;
 }
 
 static int def_init_WIN32(CONF *conf)
 {
     if (conf == NULL)
         return 0;
 
     conf->meth = &WIN32_method;
     conf->meth_data = (void *)CONF_type_win32;
     conf->data = NULL;
 
     return 1;
 }
 
 static int def_destroy(CONF *conf)
 {
     if (def_destroy_data(conf)) {
         OPENSSL_free(conf);
         return 1;
     }
     return 0;
 }
 
 static int def_destroy_data(CONF *conf)
 {
     if (conf == NULL)
         return 0;
     _CONF_free_data(conf);
     return 1;
 }
 
 static int def_load(CONF *conf, const char *name, long *line)
 {
     int ret;
     BIO *in = NULL;
 
 #ifdef OPENSSL_SYS_VMS
     in = BIO_new_file(name, "r");
 #else
     in = BIO_new_file(name, "rb");
 #endif
     if (in == NULL) {
         if (ERR_GET_REASON(ERR_peek_last_error()) == BIO_R_NO_SUCH_FILE)
             CONFerr(CONF_F_DEF_LOAD, CONF_R_NO_SUCH_FILE);
         else
             CONFerr(CONF_F_DEF_LOAD, ERR_R_SYS_LIB);
         return 0;
     }
 
     ret = def_load_bio(conf, in, line);
     BIO_free(in);
 
     return ret;
 }
 
 static int def_load_bio(CONF *conf, BIO *in, long *line)
 {
 /* The macro BUFSIZE conflicts with a system macro in VxWorks */
 #define CONFBUFSIZE     512
     int bufnum = 0, i, ii;
     BUF_MEM *buff = NULL;
     char *s, *p, *end;
     int again;
     long eline = 0;
     char btmp[DECIMAL_SIZE(eline) + 1];
     CONF_VALUE *v = NULL, *tv;
     CONF_VALUE *sv = NULL;
     char *section = NULL, *buf;
     char *start, *psection, *pname;
     void *h = (void *)(conf->data);
 
     if ((buff = BUF_MEM_new()) == NULL) {
         CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_BUF_LIB);
         goto err;
     }
 
     section = BUF_strdup("default");
     if (section == NULL) {
         CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_MALLOC_FAILURE);
         goto err;
     }
 
     if (_CONF_new_data(conf) == 0) {
         CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_MALLOC_FAILURE);
         goto err;
     }
 
     sv = _CONF_new_section(conf, section);
     if (sv == NULL) {
         CONFerr(CONF_F_DEF_LOAD_BIO, CONF_R_UNABLE_TO_CREATE_NEW_SECTION);
         goto err;
     }
 
     bufnum = 0;
     again = 0;
     for (;;) {
         if (!BUF_MEM_grow(buff, bufnum + CONFBUFSIZE)) {
             CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_BUF_LIB);
             goto err;
         }
         p = &(buff->data[bufnum]);
         *p = '\0';
         BIO_gets(in, p, CONFBUFSIZE - 1);
         p[CONFBUFSIZE - 1] = '\0';
         ii = i = strlen(p);
         if (i == 0 && !again)
             break;
         again = 0;
         while (i > 0) {
             if ((p[i - 1] != '\r') && (p[i - 1] != '\n'))
                 break;
             else
                 i--;
         }
         /*
          * we removed some trailing stuff so there is a new line on the end.
          */
         if (ii && i == ii)
             again = 1;          /* long line */
         else {
             p[i] = '\0';
             eline++;            /* another input line */
         }
 
         /* we now have a line with trailing \r\n removed */
 
         /* i is the number of bytes */
         bufnum += i;
 
         v = NULL;
         /* check for line continuation */
         if (bufnum >= 1) {
             /*
              * If we have bytes and the last char '\\' and second last char
              * is not '\\'
              */
             p = &(buff->data[bufnum - 1]);
             if (IS_ESC(conf, p[0]) && ((bufnum <= 1) || !IS_ESC(conf, p[-1]))) {
                 bufnum--;
                 again = 1;
             }
         }
         if (again)
             continue;
         bufnum = 0;
         buf = buff->data;
 
         clear_comments(conf, buf);
         s = eat_ws(conf, buf);
         if (IS_EOF(conf, *s))
             continue;           /* blank line */
         if (*s == '[') {
             char *ss;
 
             s++;
             start = eat_ws(conf, s);
             ss = start;
  again:
             end = eat_alpha_numeric(conf, ss);
             p = eat_ws(conf, end);
             if (*p != ']') {
                 if (*p != '\0' && ss != p) {
                     ss = p;
                     goto again;
                 }
                 CONFerr(CONF_F_DEF_LOAD_BIO,
                         CONF_R_MISSING_CLOSE_SQUARE_BRACKET);
                 goto err;
             }
             *end = '\0';
             if (!str_copy(conf, NULL, §ion, start))
                 goto err;
             if ((sv = _CONF_get_section(conf, section)) == NULL)
                 sv = _CONF_new_section(conf, section);
             if (sv == NULL) {
                 CONFerr(CONF_F_DEF_LOAD_BIO,
                         CONF_R_UNABLE_TO_CREATE_NEW_SECTION);
                 goto err;
             }
             continue;
         } else {
             pname = s;
             psection = NULL;
             end = eat_alpha_numeric(conf, s);
             if ((end[0] == ':') && (end[1] == ':')) {
                 *end = '\0';
                 end += 2;
                 psection = pname;
                 pname = end;
                 end = eat_alpha_numeric(conf, end);
             }
             p = eat_ws(conf, end);
             if (*p != '=') {
                 CONFerr(CONF_F_DEF_LOAD_BIO, CONF_R_MISSING_EQUAL_SIGN);
                 goto err;
             }
             *end = '\0';
             p++;
             start = eat_ws(conf, p);
             while (!IS_EOF(conf, *p))
                 p++;
             p--;
             while ((p != start) && (IS_WS(conf, *p)))
                 p--;
             p++;
             *p = '\0';
 
             if (!(v = (CONF_VALUE *)OPENSSL_malloc(sizeof(CONF_VALUE)))) {
                 CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_MALLOC_FAILURE);
                 goto err;
             }
             if (psection == NULL)
                 psection = section;
             v->name = (char *)OPENSSL_malloc(strlen(pname) + 1);
             v->value = NULL;
             if (v->name == NULL) {
                 CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_MALLOC_FAILURE);
                 goto err;
             }
             BUF_strlcpy(v->name, pname, strlen(pname) + 1);
             if (!str_copy(conf, psection, &(v->value), start))
                 goto err;
 
             if (strcmp(psection, section) != 0) {
                 if ((tv = _CONF_get_section(conf, psection))
                     == NULL)
                     tv = _CONF_new_section(conf, psection);
                 if (tv == NULL) {
                     CONFerr(CONF_F_DEF_LOAD_BIO,
                             CONF_R_UNABLE_TO_CREATE_NEW_SECTION);
                     goto err;
                 }
             } else
                 tv = sv;
 #if 1
             if (_CONF_add_string(conf, tv, v) == 0) {
                 CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_MALLOC_FAILURE);
                 goto err;
             }
 #else
             v->section = tv->section;
             if (!sk_CONF_VALUE_push(ts, v)) {
                 CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_MALLOC_FAILURE);
                 goto err;
             }
             vv = (CONF_VALUE *)lh_insert(conf->data, v);
             if (vv != NULL) {
                 sk_CONF_VALUE_delete_ptr(ts, vv);
                 OPENSSL_free(vv->name);
                 OPENSSL_free(vv->value);
                 OPENSSL_free(vv);
             }
 #endif
             v = NULL;
         }
     }
     if (buff != NULL)
         BUF_MEM_free(buff);
     if (section != NULL)
         OPENSSL_free(section);
     return (1);
  err:
     if (buff != NULL)
         BUF_MEM_free(buff);
     if (section != NULL)
         OPENSSL_free(section);
     if (line != NULL)
         *line = eline;
     BIO_snprintf(btmp, sizeof btmp, "%ld", eline);
     ERR_add_error_data(2, "line ", btmp);
     if ((h != conf->data) && (conf->data != NULL)) {
         CONF_free(conf->data);
         conf->data = NULL;
     }
     if (v != NULL) {
         if (v->name != NULL)
             OPENSSL_free(v->name);
         if (v->value != NULL)
             OPENSSL_free(v->value);
         if (v != NULL)
             OPENSSL_free(v);
     }
     return (0);
 }
 
 static void clear_comments(CONF *conf, char *p)
 {
     for (;;) {
         if (IS_FCOMMENT(conf, *p)) {
             *p = '\0';
             return;
         }
         if (!IS_WS(conf, *p)) {
             break;
         }
         p++;
     }
 
     for (;;) {
         if (IS_COMMENT(conf, *p)) {
             *p = '\0';
             return;
         }
         if (IS_DQUOTE(conf, *p)) {
             p = scan_dquote(conf, p);
             continue;
         }
         if (IS_QUOTE(conf, *p)) {
             p = scan_quote(conf, p);
             continue;
         }
         if (IS_ESC(conf, *p)) {
             p = scan_esc(conf, p);
             continue;
         }
         if (IS_EOF(conf, *p))
             return;
         else
             p++;
     }
 }
 
 static int str_copy(CONF *conf, char *section, char **pto, char *from)
 {
     int q, r, rr = 0, to = 0, len = 0;
     char *s, *e, *rp, *p, *rrp, *np, *cp, v;
     BUF_MEM *buf;
 
     if ((buf = BUF_MEM_new()) == NULL)
         return (0);
 
     len = strlen(from) + 1;
     if (!BUF_MEM_grow(buf, len))
         goto err;
 
     for (;;) {
         if (IS_QUOTE(conf, *from)) {
             q = *from;
             from++;
             while (!IS_EOF(conf, *from) && (*from != q)) {
                 if (IS_ESC(conf, *from)) {
                     from++;
                     if (IS_EOF(conf, *from))
                         break;
                 }
                 buf->data[to++] = *(from++);
             }
             if (*from == q)
                 from++;
         } else if (IS_DQUOTE(conf, *from)) {
             q = *from;
             from++;
             while (!IS_EOF(conf, *from)) {
                 if (*from == q) {
                     if (*(from + 1) == q) {
                         from++;
                     } else {
                         break;
                     }
                 }
                 buf->data[to++] = *(from++);
             }
             if (*from == q)
                 from++;
         } else if (IS_ESC(conf, *from)) {
             from++;
             v = *(from++);
             if (IS_EOF(conf, v))
                 break;
             else if (v == 'r')
                 v = '\r';
             else if (v == 'n')
                 v = '\n';
             else if (v == 'b')
                 v = '\b';
             else if (v == 't')
                 v = '\t';
             buf->data[to++] = v;
         } else if (IS_EOF(conf, *from))
             break;
         else if (*from == '$') {
+            size_t newsize;
+
             /* try to expand it */
             rrp = NULL;
             s = &(from[1]);
             if (*s == '{')
                 q = '}';
             else if (*s == '(')
                 q = ')';
             else
                 q = 0;
 
             if (q)
                 s++;
             cp = section;
             e = np = s;
             while (IS_ALPHA_NUMERIC(conf, *e))
                 e++;
             if ((e[0] == ':') && (e[1] == ':')) {
                 cp = np;
                 rrp = e;
                 rr = *e;
                 *rrp = '\0';
                 e += 2;
                 np = e;
                 while (IS_ALPHA_NUMERIC(conf, *e))
                     e++;
             }
             r = *e;
             *e = '\0';
             rp = e;
             if (q) {
                 if (r != q) {
                     CONFerr(CONF_F_STR_COPY, CONF_R_NO_CLOSE_BRACE);
                     goto err;
                 }
                 e++;
             }
             /*-
              * So at this point we have
              * np which is the start of the name string which is
              *   '\0' terminated.
              * cp which is the start of the section string which is
              *   '\0' terminated.
              * e is the 'next point after'.
              * r and rr are the chars replaced by the '\0'
              * rp and rrp is where 'r' and 'rr' came from.
              */
             p = _CONF_get_string(conf, cp, np);
             if (rrp != NULL)
                 *rrp = rr;
             *rp = r;
             if (p == NULL) {
                 CONFerr(CONF_F_STR_COPY, CONF_R_VARIABLE_HAS_NO_VALUE);
                 goto err;
             }
-            if (!BUF_MEM_grow_clean(buf,
-                        (strlen(p) + buf->length - (e - from)))) {
+            newsize = strlen(p) + buf->length - (e - from);
+            if (newsize > MAX_CONF_VALUE_LENGTH) {
+                CONFerr(CONF_F_STR_COPY, CONF_R_VARIABLE_EXPANSION_TOO_LONG);
+                goto err;
+            }
+            if (!BUF_MEM_grow_clean(buf, newsize)) {
                 CONFerr(CONF_F_STR_COPY, ERR_R_MALLOC_FAILURE);
                 goto err;
             }
             while (*p)
                 buf->data[to++] = *(p++);
 
             /*
              * Since we change the pointer 'from', we also have to change the
              * perceived length of the string it points at.  /RL
              */
             len -= e - from;
             from = e;
 
             /*
              * In case there were no braces or parenthesis around the
              * variable reference, we have to put back the character that was
              * replaced with a '\0'.  /RL
              */
             *rp = r;
         } else
             buf->data[to++] = *(from++);
     }
     buf->data[to] = '\0';
     if (*pto != NULL)
         OPENSSL_free(*pto);
     *pto = buf->data;
     OPENSSL_free(buf);
     return (1);
  err:
     if (buf != NULL)
         BUF_MEM_free(buf);
     return (0);
 }
 
 static char *eat_ws(CONF *conf, char *p)
 {
     while (IS_WS(conf, *p) && (!IS_EOF(conf, *p)))
         p++;
     return (p);
 }
 
 static char *eat_alpha_numeric(CONF *conf, char *p)
 {
     for (;;) {
         if (IS_ESC(conf, *p)) {
             p = scan_esc(conf, p);
             continue;
         }
         if (!IS_ALPHA_NUMERIC_PUNCT(conf, *p))
             return (p);
         p++;
     }
 }
 
 static char *scan_quote(CONF *conf, char *p)
 {
     int q = *p;
 
     p++;
     while (!(IS_EOF(conf, *p)) && (*p != q)) {
         if (IS_ESC(conf, *p)) {
             p++;
             if (IS_EOF(conf, *p))
                 return (p);
         }
         p++;
     }
     if (*p == q)
         p++;
     return (p);
 }
 
 static char *scan_dquote(CONF *conf, char *p)
 {
     int q = *p;
 
     p++;
     while (!(IS_EOF(conf, *p))) {
         if (*p == q) {
             if (*(p + 1) == q) {
                 p++;
             } else {
                 break;
             }
         }
         p++;
     }
     if (*p == q)
         p++;
     return (p);
 }
 
 static void dump_value_doall_arg(CONF_VALUE *a, BIO *out)
 {
     if (a->name)
         BIO_printf(out, "[%s] %s=%s\n", a->section, a->name, a->value);
     else
         BIO_printf(out, "[[%s]]\n", a->section);
 }
 
 static IMPLEMENT_LHASH_DOALL_ARG_FN(dump_value, CONF_VALUE, BIO)
 
 static int def_dump(const CONF *conf, BIO *out)
 {
     lh_CONF_VALUE_doall_arg(conf->data, LHASH_DOALL_ARG_FN(dump_value),
                             BIO, out);
     return 1;
 }
 
 static int def_is_number(const CONF *conf, char c)
 {
     return IS_NUMBER(conf, c);
 }
 
 static int def_to_int(const CONF *conf, char c)
 {
     return c - '0';
 }
Index: vendor-crypto/openssl/dist/crypto/conf/conf_err.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/conf/conf_err.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/conf/conf_err.c	(revision 318897)
@@ -1,133 +1,135 @@
 /* crypto/conf/conf_err.c */
 /* ====================================================================
  * Copyright (c) 1999-2007 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    openssl-core@OpenSSL.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 /*
  * NOTE: this file was auto generated by the mkerr.pl script: any changes
  * made to it will be overwritten when the script next updates this file,
  * only reason strings will be preserved.
  */
 
 #include 
 #include 
 #include 
 
 /* BEGIN ERROR CODES */
 #ifndef OPENSSL_NO_ERR
 
 # define ERR_FUNC(func) ERR_PACK(ERR_LIB_CONF,func,0)
 # define ERR_REASON(reason) ERR_PACK(ERR_LIB_CONF,0,reason)
 
 static ERR_STRING_DATA CONF_str_functs[] = {
     {ERR_FUNC(CONF_F_CONF_DUMP_FP), "CONF_dump_fp"},
     {ERR_FUNC(CONF_F_CONF_LOAD), "CONF_load"},
     {ERR_FUNC(CONF_F_CONF_LOAD_BIO), "CONF_load_bio"},
     {ERR_FUNC(CONF_F_CONF_LOAD_FP), "CONF_load_fp"},
     {ERR_FUNC(CONF_F_CONF_MODULES_LOAD), "CONF_modules_load"},
     {ERR_FUNC(CONF_F_CONF_PARSE_LIST), "CONF_parse_list"},
     {ERR_FUNC(CONF_F_DEF_LOAD), "DEF_LOAD"},
     {ERR_FUNC(CONF_F_DEF_LOAD_BIO), "DEF_LOAD_BIO"},
     {ERR_FUNC(CONF_F_MODULE_INIT), "MODULE_INIT"},
     {ERR_FUNC(CONF_F_MODULE_LOAD_DSO), "MODULE_LOAD_DSO"},
     {ERR_FUNC(CONF_F_MODULE_RUN), "MODULE_RUN"},
     {ERR_FUNC(CONF_F_NCONF_DUMP_BIO), "NCONF_dump_bio"},
     {ERR_FUNC(CONF_F_NCONF_DUMP_FP), "NCONF_dump_fp"},
     {ERR_FUNC(CONF_F_NCONF_GET_NUMBER), "NCONF_get_number"},
     {ERR_FUNC(CONF_F_NCONF_GET_NUMBER_E), "NCONF_get_number_e"},
     {ERR_FUNC(CONF_F_NCONF_GET_SECTION), "NCONF_get_section"},
     {ERR_FUNC(CONF_F_NCONF_GET_STRING), "NCONF_get_string"},
     {ERR_FUNC(CONF_F_NCONF_LOAD), "NCONF_load"},
     {ERR_FUNC(CONF_F_NCONF_LOAD_BIO), "NCONF_load_bio"},
     {ERR_FUNC(CONF_F_NCONF_LOAD_FP), "NCONF_load_fp"},
     {ERR_FUNC(CONF_F_NCONF_NEW), "NCONF_new"},
     {ERR_FUNC(CONF_F_STR_COPY), "STR_COPY"},
     {0, NULL}
 };
 
 static ERR_STRING_DATA CONF_str_reasons[] = {
     {ERR_REASON(CONF_R_ERROR_LOADING_DSO), "error loading dso"},
     {ERR_REASON(CONF_R_LIST_CANNOT_BE_NULL), "list cannot be null"},
     {ERR_REASON(CONF_R_MISSING_CLOSE_SQUARE_BRACKET),
      "missing close square bracket"},
     {ERR_REASON(CONF_R_MISSING_EQUAL_SIGN), "missing equal sign"},
     {ERR_REASON(CONF_R_MISSING_FINISH_FUNCTION), "missing finish function"},
     {ERR_REASON(CONF_R_MISSING_INIT_FUNCTION), "missing init function"},
     {ERR_REASON(CONF_R_MODULE_INITIALIZATION_ERROR),
      "module initialization error"},
     {ERR_REASON(CONF_R_NO_CLOSE_BRACE), "no close brace"},
     {ERR_REASON(CONF_R_NO_CONF), "no conf"},
     {ERR_REASON(CONF_R_NO_CONF_OR_ENVIRONMENT_VARIABLE),
      "no conf or environment variable"},
     {ERR_REASON(CONF_R_NO_SECTION), "no section"},
     {ERR_REASON(CONF_R_NO_SUCH_FILE), "no such file"},
     {ERR_REASON(CONF_R_NO_VALUE), "no value"},
     {ERR_REASON(CONF_R_UNABLE_TO_CREATE_NEW_SECTION),
      "unable to create new section"},
     {ERR_REASON(CONF_R_UNKNOWN_MODULE_NAME), "unknown module name"},
+    {ERR_REASON(CONF_R_VARIABLE_EXPANSION_TOO_LONG),
+     "variable expansion too long"},
     {ERR_REASON(CONF_R_VARIABLE_HAS_NO_VALUE), "variable has no value"},
     {0, NULL}
 };
 
 #endif
 
 void ERR_load_CONF_strings(void)
 {
 #ifndef OPENSSL_NO_ERR
 
     if (ERR_func_error_string(CONF_str_functs[0].error) == NULL) {
         ERR_load_strings(0, CONF_str_functs);
         ERR_load_strings(0, CONF_str_reasons);
     }
 #endif
 }
Index: vendor-crypto/openssl/dist/crypto/des/Makefile
===================================================================
--- vendor-crypto/openssl/dist/crypto/des/Makefile	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/des/Makefile	(revision 318897)
@@ -1,283 +1,283 @@
 #
 # OpenSSL/crypto/des/Makefile
 #
 
 DIR=	des
 TOP=	../..
 CC=	cc
 CPP=	$(CC) -E
 INCLUDES=-I$(TOP) -I../../include
 CFLAG=-g
 MAKEFILE=	Makefile
 AR=		ar r
 RANLIB=		ranlib
 DES_ENC=	des_enc.o fcrypt_b.o
 
 CFLAGS= $(INCLUDES) $(CFLAG)
 ASFLAGS= $(INCLUDES) $(ASFLAG)
 AFLAGS= $(ASFLAGS)
 
 GENERAL=Makefile
 TEST=destest.c
 APPS=
 
 LIB=$(TOP)/libcrypto.a
 LIBSRC=	cbc_cksm.c cbc_enc.c  cfb64enc.c cfb_enc.c  \
 	ecb3_enc.c ecb_enc.c  enc_read.c enc_writ.c \
 	fcrypt.c ofb64enc.c ofb_enc.c  pcbc_enc.c \
 	qud_cksm.c rand_key.c rpc_enc.c  set_key.c  \
 	des_enc.c fcrypt_b.c \
 	xcbc_enc.c \
 	str2key.c  cfb64ede.c ofb64ede.c ede_cbcm_enc.c des_old.c des_old2.c \
 	read2pwd.c
 
 LIBOBJ= set_key.o  ecb_enc.o  cbc_enc.o \
 	ecb3_enc.o cfb64enc.o cfb64ede.o cfb_enc.o  ofb64ede.o \
 	enc_read.o enc_writ.o ofb64enc.o \
 	ofb_enc.o  str2key.o  pcbc_enc.o qud_cksm.o rand_key.o \
 	${DES_ENC} \
 	fcrypt.o xcbc_enc.o rpc_enc.o  cbc_cksm.o \
 	ede_cbcm_enc.o des_old.o des_old2.o read2pwd.o
 
 SRC= $(LIBSRC)
 
 EXHEADER= des.h des_old.h
 HEADER=	des_locl.h rpc_des.h spr.h des_ver.h $(EXHEADER)
 
 ALL=    $(GENERAL) $(SRC) $(HEADER)
 
 top:
 	(cd ../..; $(MAKE) DIRS=crypto SDIRS=$(DIR) sub_all)
 
 all:	lib
 
 lib:	$(LIBOBJ)
 	$(AR) $(LIB) $(LIBOBJ)
 	$(RANLIB) $(LIB) || echo Never mind.
 	@touch lib
 
 des: des.o cbc3_enc.o lib
 	$(CC) $(CFLAGS) -o des des.o cbc3_enc.o $(LIB)
 
 des_enc-sparc.S:	asm/des_enc.m4
 	m4 -B 8192 asm/des_enc.m4 > des_enc-sparc.S
 dest4-sparcv9.s:	asm/dest4-sparcv9.pl
 	$(PERL) asm/dest4-sparcv9.pl $(CFLAGS) > $@
 
 des-586.s:	asm/des-586.pl ../perlasm/x86asm.pl ../perlasm/cbc.pl
 	$(PERL) asm/des-586.pl $(PERLASM_SCHEME) $(CFLAGS) > $@
 crypt586.s:	asm/crypt586.pl ../perlasm/x86asm.pl ../perlasm/cbc.pl
 	$(PERL) asm/crypt586.pl $(PERLASM_SCHEME) $(CFLAGS) > $@
 
 files:
 	$(PERL) $(TOP)/util/files.pl Makefile >> $(TOP)/MINFO
 
 links:
 	@$(PERL) $(TOP)/util/mklink.pl ../../include/openssl $(EXHEADER)
 	@$(PERL) $(TOP)/util/mklink.pl ../../test $(TEST)
 	@$(PERL) $(TOP)/util/mklink.pl ../../apps $(APPS)
 
 # We need to use force because 'install' matches 'INSTALL' on case
 # insensitive systems
 FRC.install:
 install: FRC.install
 	@[ -n "$(INSTALLTOP)" ] # should be set by top Makefile...
 	@headerlist="$(EXHEADER)"; for i in $$headerlist ; \
 	do  \
 	(cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i; \
 	chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i ); \
 	done;
 
 tags:
 	ctags $(SRC)
 
 tests:
 
 lint:
 	lint -DLINT $(INCLUDES) $(SRC)>fluff
 
 update: depend
 
 depend:
 	@[ -n "$(MAKEDEPEND)" ] # should be set by upper Makefile...
 	$(MAKEDEPEND) -- $(CFLAG) $(INCLUDES) $(DEPFLAG) -- $(PROGS) $(LIBSRC)
 
 dclean:
 	$(PERL) -pe 'if (/^# DO NOT DELETE THIS LINE/) {print; exit(0);}' $(MAKEFILE) >Makefile.new
 	mv -f Makefile.new $(MAKEFILE)
 
 clean:
-	rm -f *.s *.o *.obj des lib tags core .pure .nfs* *.old *.bak fluff
+	rm -f *.s *.S *.o *.obj des lib tags core .pure .nfs* *.old *.bak fluff
 
 # DO NOT DELETE THIS LINE -- make depend depends on it.
 
 cbc_cksm.o: ../../include/openssl/des.h ../../include/openssl/des_old.h
 cbc_cksm.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
 cbc_cksm.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h
 cbc_cksm.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 cbc_cksm.o: ../../include/openssl/ui.h ../../include/openssl/ui_compat.h
 cbc_cksm.o: cbc_cksm.c des_locl.h
 cbc_enc.o: ../../include/openssl/des.h ../../include/openssl/des_old.h
 cbc_enc.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
 cbc_enc.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h
 cbc_enc.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 cbc_enc.o: ../../include/openssl/ui.h ../../include/openssl/ui_compat.h
 cbc_enc.o: cbc_enc.c des_locl.h ncbc_enc.c
 cfb64ede.o: ../../e_os.h ../../include/openssl/des.h
 cfb64ede.o: ../../include/openssl/des_old.h ../../include/openssl/e_os2.h
 cfb64ede.o: ../../include/openssl/opensslconf.h
 cfb64ede.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h
 cfb64ede.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 cfb64ede.o: ../../include/openssl/ui.h ../../include/openssl/ui_compat.h
 cfb64ede.o: cfb64ede.c des_locl.h
 cfb64enc.o: ../../include/openssl/des.h ../../include/openssl/des_old.h
 cfb64enc.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
 cfb64enc.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h
 cfb64enc.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 cfb64enc.o: ../../include/openssl/ui.h ../../include/openssl/ui_compat.h
 cfb64enc.o: cfb64enc.c des_locl.h
 cfb_enc.o: ../../e_os.h ../../include/openssl/des.h
 cfb_enc.o: ../../include/openssl/des_old.h ../../include/openssl/e_os2.h
 cfb_enc.o: ../../include/openssl/opensslconf.h ../../include/openssl/ossl_typ.h
 cfb_enc.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 cfb_enc.o: ../../include/openssl/symhacks.h ../../include/openssl/ui.h
 cfb_enc.o: ../../include/openssl/ui_compat.h cfb_enc.c des_locl.h
 des_enc.o: ../../include/openssl/des.h ../../include/openssl/des_old.h
 des_enc.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
 des_enc.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h
 des_enc.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 des_enc.o: ../../include/openssl/ui.h ../../include/openssl/ui_compat.h
 des_enc.o: des_enc.c des_locl.h ncbc_enc.c spr.h
 des_old.o: ../../include/openssl/des.h ../../include/openssl/des_old.h
 des_old.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
 des_old.o: ../../include/openssl/ossl_typ.h ../../include/openssl/rand.h
 des_old.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 des_old.o: ../../include/openssl/symhacks.h ../../include/openssl/ui.h
 des_old.o: ../../include/openssl/ui_compat.h des_old.c
 des_old2.o: ../../include/openssl/des.h ../../include/openssl/des_old.h
 des_old2.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
 des_old2.o: ../../include/openssl/ossl_typ.h ../../include/openssl/rand.h
 des_old2.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 des_old2.o: ../../include/openssl/symhacks.h ../../include/openssl/ui.h
 des_old2.o: ../../include/openssl/ui_compat.h des_old2.c
 ecb3_enc.o: ../../include/openssl/des.h ../../include/openssl/des_old.h
 ecb3_enc.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
 ecb3_enc.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h
 ecb3_enc.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 ecb3_enc.o: ../../include/openssl/ui.h ../../include/openssl/ui_compat.h
 ecb3_enc.o: des_locl.h ecb3_enc.c
 ecb_enc.o: ../../include/openssl/bio.h ../../include/openssl/crypto.h
 ecb_enc.o: ../../include/openssl/des.h ../../include/openssl/des_old.h
 ecb_enc.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
 ecb_enc.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 ecb_enc.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 ecb_enc.o: ../../include/openssl/symhacks.h ../../include/openssl/ui.h
 ecb_enc.o: ../../include/openssl/ui_compat.h des_locl.h des_ver.h ecb_enc.c
 ede_cbcm_enc.o: ../../include/openssl/des.h ../../include/openssl/des_old.h
 ede_cbcm_enc.o: ../../include/openssl/e_os2.h
 ede_cbcm_enc.o: ../../include/openssl/opensslconf.h
 ede_cbcm_enc.o: ../../include/openssl/ossl_typ.h
 ede_cbcm_enc.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 ede_cbcm_enc.o: ../../include/openssl/symhacks.h ../../include/openssl/ui.h
 ede_cbcm_enc.o: ../../include/openssl/ui_compat.h des_locl.h ede_cbcm_enc.c
 enc_read.o: ../../e_os.h ../../include/openssl/bio.h
 enc_read.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 enc_read.o: ../../include/openssl/des.h ../../include/openssl/des_old.h
 enc_read.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 enc_read.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 enc_read.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 enc_read.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 enc_read.o: ../../include/openssl/symhacks.h ../../include/openssl/ui.h
 enc_read.o: ../../include/openssl/ui_compat.h ../cryptlib.h des_locl.h
 enc_read.o: enc_read.c
 enc_writ.o: ../../e_os.h ../../include/openssl/bio.h
 enc_writ.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 enc_writ.o: ../../include/openssl/des.h ../../include/openssl/des_old.h
 enc_writ.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 enc_writ.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 enc_writ.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 enc_writ.o: ../../include/openssl/rand.h ../../include/openssl/safestack.h
 enc_writ.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 enc_writ.o: ../../include/openssl/ui.h ../../include/openssl/ui_compat.h
 enc_writ.o: ../cryptlib.h des_locl.h enc_writ.c
 fcrypt.o: ../../include/openssl/des.h ../../include/openssl/des_old.h
 fcrypt.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
 fcrypt.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h
 fcrypt.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 fcrypt.o: ../../include/openssl/ui.h ../../include/openssl/ui_compat.h
 fcrypt.o: des_locl.h fcrypt.c
 fcrypt_b.o: ../../include/openssl/des.h ../../include/openssl/des_old.h
 fcrypt_b.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
 fcrypt_b.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h
 fcrypt_b.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 fcrypt_b.o: ../../include/openssl/ui.h ../../include/openssl/ui_compat.h
 fcrypt_b.o: des_locl.h fcrypt_b.c
 ofb64ede.o: ../../include/openssl/des.h ../../include/openssl/des_old.h
 ofb64ede.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
 ofb64ede.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h
 ofb64ede.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 ofb64ede.o: ../../include/openssl/ui.h ../../include/openssl/ui_compat.h
 ofb64ede.o: des_locl.h ofb64ede.c
 ofb64enc.o: ../../include/openssl/des.h ../../include/openssl/des_old.h
 ofb64enc.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
 ofb64enc.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h
 ofb64enc.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 ofb64enc.o: ../../include/openssl/ui.h ../../include/openssl/ui_compat.h
 ofb64enc.o: des_locl.h ofb64enc.c
 ofb_enc.o: ../../include/openssl/des.h ../../include/openssl/des_old.h
 ofb_enc.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
 ofb_enc.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h
 ofb_enc.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 ofb_enc.o: ../../include/openssl/ui.h ../../include/openssl/ui_compat.h
 ofb_enc.o: des_locl.h ofb_enc.c
 pcbc_enc.o: ../../include/openssl/des.h ../../include/openssl/des_old.h
 pcbc_enc.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
 pcbc_enc.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h
 pcbc_enc.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 pcbc_enc.o: ../../include/openssl/ui.h ../../include/openssl/ui_compat.h
 pcbc_enc.o: des_locl.h pcbc_enc.c
 qud_cksm.o: ../../include/openssl/des.h ../../include/openssl/des_old.h
 qud_cksm.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
 qud_cksm.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h
 qud_cksm.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 qud_cksm.o: ../../include/openssl/ui.h ../../include/openssl/ui_compat.h
 qud_cksm.o: des_locl.h qud_cksm.c
 rand_key.o: ../../include/openssl/des.h ../../include/openssl/des_old.h
 rand_key.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
 rand_key.o: ../../include/openssl/ossl_typ.h ../../include/openssl/rand.h
 rand_key.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 rand_key.o: ../../include/openssl/symhacks.h ../../include/openssl/ui.h
 rand_key.o: ../../include/openssl/ui_compat.h rand_key.c
 read2pwd.o: ../../include/openssl/crypto.h ../../include/openssl/des.h
 read2pwd.o: ../../include/openssl/des_old.h ../../include/openssl/e_os2.h
 read2pwd.o: ../../include/openssl/opensslconf.h
 read2pwd.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 read2pwd.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 read2pwd.o: ../../include/openssl/symhacks.h ../../include/openssl/ui.h
 read2pwd.o: ../../include/openssl/ui_compat.h read2pwd.c
 rpc_enc.o: ../../include/openssl/des.h ../../include/openssl/des_old.h
 rpc_enc.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
 rpc_enc.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h
 rpc_enc.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 rpc_enc.o: ../../include/openssl/ui.h ../../include/openssl/ui_compat.h
 rpc_enc.o: des_locl.h des_ver.h rpc_des.h rpc_enc.c
 set_key.o: ../../include/openssl/crypto.h ../../include/openssl/des.h
 set_key.o: ../../include/openssl/des_old.h ../../include/openssl/e_os2.h
 set_key.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h
 set_key.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h
 set_key.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 set_key.o: ../../include/openssl/ui.h ../../include/openssl/ui_compat.h
 set_key.o: des_locl.h set_key.c
 str2key.o: ../../include/openssl/crypto.h ../../include/openssl/des.h
 str2key.o: ../../include/openssl/des_old.h ../../include/openssl/e_os2.h
 str2key.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h
 str2key.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h
 str2key.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 str2key.o: ../../include/openssl/ui.h ../../include/openssl/ui_compat.h
 str2key.o: des_locl.h str2key.c
 xcbc_enc.o: ../../include/openssl/des.h ../../include/openssl/des_old.h
 xcbc_enc.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h
 xcbc_enc.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h
 xcbc_enc.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 xcbc_enc.o: ../../include/openssl/ui.h ../../include/openssl/ui_compat.h
 xcbc_enc.o: des_locl.h xcbc_enc.c
Index: vendor-crypto/openssl/dist/crypto/des/set_key.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/des/set_key.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/des/set_key.c	(revision 318897)
@@ -1,447 +1,447 @@
 /* crypto/des/set_key.c */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 
 /*-
  * set_key.c v 1.4 eay 24/9/91
  * 1.4 Speed up by 400% :-)
  * 1.3 added register declarations.
  * 1.2 unrolled make_key_sched a bit more
  * 1.1 added norm_expand_bits
  * 1.0 First working version
  */
 #include 
 #include "des_locl.h"
 
 OPENSSL_IMPLEMENT_GLOBAL(int, DES_check_key, 0)
                                                     /*
                                                      * defaults to false
                                                      */
 static const unsigned char odd_parity[256] = {
     1, 1, 2, 2, 4, 4, 7, 7, 8, 8, 11, 11, 13, 13, 14, 14,
     16, 16, 19, 19, 21, 21, 22, 22, 25, 25, 26, 26, 28, 28, 31, 31,
     32, 32, 35, 35, 37, 37, 38, 38, 41, 41, 42, 42, 44, 44, 47, 47,
     49, 49, 50, 50, 52, 52, 55, 55, 56, 56, 59, 59, 61, 61, 62, 62,
     64, 64, 67, 67, 69, 69, 70, 70, 73, 73, 74, 74, 76, 76, 79, 79,
     81, 81, 82, 82, 84, 84, 87, 87, 88, 88, 91, 91, 93, 93, 94, 94,
     97, 97, 98, 98, 100, 100, 103, 103, 104, 104, 107, 107, 109, 109, 110,
     110,
     112, 112, 115, 115, 117, 117, 118, 118, 121, 121, 122, 122, 124, 124, 127,
     127,
     128, 128, 131, 131, 133, 133, 134, 134, 137, 137, 138, 138, 140, 140, 143,
     143,
     145, 145, 146, 146, 148, 148, 151, 151, 152, 152, 155, 155, 157, 157, 158,
     158,
     161, 161, 162, 162, 164, 164, 167, 167, 168, 168, 171, 171, 173, 173, 174,
     174,
     176, 176, 179, 179, 181, 181, 182, 182, 185, 185, 186, 186, 188, 188, 191,
     191,
     193, 193, 194, 194, 196, 196, 199, 199, 200, 200, 203, 203, 205, 205, 206,
     206,
     208, 208, 211, 211, 213, 213, 214, 214, 217, 217, 218, 218, 220, 220, 223,
     223,
     224, 224, 227, 227, 229, 229, 230, 230, 233, 233, 234, 234, 236, 236, 239,
     239,
     241, 241, 242, 242, 244, 244, 247, 247, 248, 248, 251, 251, 253, 253, 254,
     254
 };
 
 void DES_set_odd_parity(DES_cblock *key)
 {
     unsigned int i;
 
     for (i = 0; i < DES_KEY_SZ; i++)
         (*key)[i] = odd_parity[(*key)[i]];
 }
 
 int DES_check_key_parity(const_DES_cblock *key)
 {
     unsigned int i;
 
     for (i = 0; i < DES_KEY_SZ; i++) {
         if ((*key)[i] != odd_parity[(*key)[i]])
             return (0);
     }
     return (1);
 }
 
 /*-
- * Weak and semi week keys as take from
+ * Weak and semi weak keys as taken from
  * %A D.W. Davies
  * %A W.L. Price
  * %T Security for Computer Networks
  * %I John Wiley & Sons
  * %D 1984
  * Many thanks to smb@ulysses.att.com (Steven Bellovin) for the reference
  * (and actual cblock values).
  */
 #define NUM_WEAK_KEY    16
 static const DES_cblock weak_keys[NUM_WEAK_KEY] = {
     /* weak keys */
     {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01},
     {0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE},
     {0x1F, 0x1F, 0x1F, 0x1F, 0x0E, 0x0E, 0x0E, 0x0E},
     {0xE0, 0xE0, 0xE0, 0xE0, 0xF1, 0xF1, 0xF1, 0xF1},
     /* semi-weak keys */
     {0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE},
     {0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01},
     {0x1F, 0xE0, 0x1F, 0xE0, 0x0E, 0xF1, 0x0E, 0xF1},
     {0xE0, 0x1F, 0xE0, 0x1F, 0xF1, 0x0E, 0xF1, 0x0E},
     {0x01, 0xE0, 0x01, 0xE0, 0x01, 0xF1, 0x01, 0xF1},
     {0xE0, 0x01, 0xE0, 0x01, 0xF1, 0x01, 0xF1, 0x01},
     {0x1F, 0xFE, 0x1F, 0xFE, 0x0E, 0xFE, 0x0E, 0xFE},
     {0xFE, 0x1F, 0xFE, 0x1F, 0xFE, 0x0E, 0xFE, 0x0E},
     {0x01, 0x1F, 0x01, 0x1F, 0x01, 0x0E, 0x01, 0x0E},
     {0x1F, 0x01, 0x1F, 0x01, 0x0E, 0x01, 0x0E, 0x01},
     {0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1, 0xFE},
     {0xFE, 0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1}
 };
 
 int DES_is_weak_key(const_DES_cblock *key)
 {
     int i;
 
     for (i = 0; i < NUM_WEAK_KEY; i++)
         /*
          * Added == 0 to comparison, I obviously don't run this section very
          * often :-(, thanks to engineering@MorningStar.Com for the fix eay
          * 93/06/29 Another problem, I was comparing only the first 4 bytes,
          * 97/03/18
          */
         if (memcmp(weak_keys[i], key, sizeof(DES_cblock)) == 0)
             return (1);
     return (0);
 }
 
 /*-
  * NOW DEFINED IN des_local.h
  * See ecb_encrypt.c for a pseudo description of these macros.
  * #define PERM_OP(a,b,t,n,m) ((t)=((((a)>>(n))^(b))&(m)),\
  *      (b)^=(t),\
  *      (a)=((a)^((t)<<(n))))
  */
 
 #define HPERM_OP(a,t,n,m) ((t)=((((a)<<(16-(n)))^(a))&(m)),\
         (a)=(a)^(t)^(t>>(16-(n))))
 
 static const DES_LONG des_skb[8][64] = {
     {
      /* for C bits (numbered as per FIPS 46) 1 2 3 4 5 6 */
      0x00000000L, 0x00000010L, 0x20000000L, 0x20000010L,
      0x00010000L, 0x00010010L, 0x20010000L, 0x20010010L,
      0x00000800L, 0x00000810L, 0x20000800L, 0x20000810L,
      0x00010800L, 0x00010810L, 0x20010800L, 0x20010810L,
      0x00000020L, 0x00000030L, 0x20000020L, 0x20000030L,
      0x00010020L, 0x00010030L, 0x20010020L, 0x20010030L,
      0x00000820L, 0x00000830L, 0x20000820L, 0x20000830L,
      0x00010820L, 0x00010830L, 0x20010820L, 0x20010830L,
      0x00080000L, 0x00080010L, 0x20080000L, 0x20080010L,
      0x00090000L, 0x00090010L, 0x20090000L, 0x20090010L,
      0x00080800L, 0x00080810L, 0x20080800L, 0x20080810L,
      0x00090800L, 0x00090810L, 0x20090800L, 0x20090810L,
      0x00080020L, 0x00080030L, 0x20080020L, 0x20080030L,
      0x00090020L, 0x00090030L, 0x20090020L, 0x20090030L,
      0x00080820L, 0x00080830L, 0x20080820L, 0x20080830L,
      0x00090820L, 0x00090830L, 0x20090820L, 0x20090830L,
      },
     {
      /* for C bits (numbered as per FIPS 46) 7 8 10 11 12 13 */
      0x00000000L, 0x02000000L, 0x00002000L, 0x02002000L,
      0x00200000L, 0x02200000L, 0x00202000L, 0x02202000L,
      0x00000004L, 0x02000004L, 0x00002004L, 0x02002004L,
      0x00200004L, 0x02200004L, 0x00202004L, 0x02202004L,
      0x00000400L, 0x02000400L, 0x00002400L, 0x02002400L,
      0x00200400L, 0x02200400L, 0x00202400L, 0x02202400L,
      0x00000404L, 0x02000404L, 0x00002404L, 0x02002404L,
      0x00200404L, 0x02200404L, 0x00202404L, 0x02202404L,
      0x10000000L, 0x12000000L, 0x10002000L, 0x12002000L,
      0x10200000L, 0x12200000L, 0x10202000L, 0x12202000L,
      0x10000004L, 0x12000004L, 0x10002004L, 0x12002004L,
      0x10200004L, 0x12200004L, 0x10202004L, 0x12202004L,
      0x10000400L, 0x12000400L, 0x10002400L, 0x12002400L,
      0x10200400L, 0x12200400L, 0x10202400L, 0x12202400L,
      0x10000404L, 0x12000404L, 0x10002404L, 0x12002404L,
      0x10200404L, 0x12200404L, 0x10202404L, 0x12202404L,
      },
     {
      /* for C bits (numbered as per FIPS 46) 14 15 16 17 19 20 */
      0x00000000L, 0x00000001L, 0x00040000L, 0x00040001L,
      0x01000000L, 0x01000001L, 0x01040000L, 0x01040001L,
      0x00000002L, 0x00000003L, 0x00040002L, 0x00040003L,
      0x01000002L, 0x01000003L, 0x01040002L, 0x01040003L,
      0x00000200L, 0x00000201L, 0x00040200L, 0x00040201L,
      0x01000200L, 0x01000201L, 0x01040200L, 0x01040201L,
      0x00000202L, 0x00000203L, 0x00040202L, 0x00040203L,
      0x01000202L, 0x01000203L, 0x01040202L, 0x01040203L,
      0x08000000L, 0x08000001L, 0x08040000L, 0x08040001L,
      0x09000000L, 0x09000001L, 0x09040000L, 0x09040001L,
      0x08000002L, 0x08000003L, 0x08040002L, 0x08040003L,
      0x09000002L, 0x09000003L, 0x09040002L, 0x09040003L,
      0x08000200L, 0x08000201L, 0x08040200L, 0x08040201L,
      0x09000200L, 0x09000201L, 0x09040200L, 0x09040201L,
      0x08000202L, 0x08000203L, 0x08040202L, 0x08040203L,
      0x09000202L, 0x09000203L, 0x09040202L, 0x09040203L,
      },
     {
      /* for C bits (numbered as per FIPS 46) 21 23 24 26 27 28 */
      0x00000000L, 0x00100000L, 0x00000100L, 0x00100100L,
      0x00000008L, 0x00100008L, 0x00000108L, 0x00100108L,
      0x00001000L, 0x00101000L, 0x00001100L, 0x00101100L,
      0x00001008L, 0x00101008L, 0x00001108L, 0x00101108L,
      0x04000000L, 0x04100000L, 0x04000100L, 0x04100100L,
      0x04000008L, 0x04100008L, 0x04000108L, 0x04100108L,
      0x04001000L, 0x04101000L, 0x04001100L, 0x04101100L,
      0x04001008L, 0x04101008L, 0x04001108L, 0x04101108L,
      0x00020000L, 0x00120000L, 0x00020100L, 0x00120100L,
      0x00020008L, 0x00120008L, 0x00020108L, 0x00120108L,
      0x00021000L, 0x00121000L, 0x00021100L, 0x00121100L,
      0x00021008L, 0x00121008L, 0x00021108L, 0x00121108L,
      0x04020000L, 0x04120000L, 0x04020100L, 0x04120100L,
      0x04020008L, 0x04120008L, 0x04020108L, 0x04120108L,
      0x04021000L, 0x04121000L, 0x04021100L, 0x04121100L,
      0x04021008L, 0x04121008L, 0x04021108L, 0x04121108L,
      },
     {
      /* for D bits (numbered as per FIPS 46) 1 2 3 4 5 6 */
      0x00000000L, 0x10000000L, 0x00010000L, 0x10010000L,
      0x00000004L, 0x10000004L, 0x00010004L, 0x10010004L,
      0x20000000L, 0x30000000L, 0x20010000L, 0x30010000L,
      0x20000004L, 0x30000004L, 0x20010004L, 0x30010004L,
      0x00100000L, 0x10100000L, 0x00110000L, 0x10110000L,
      0x00100004L, 0x10100004L, 0x00110004L, 0x10110004L,
      0x20100000L, 0x30100000L, 0x20110000L, 0x30110000L,
      0x20100004L, 0x30100004L, 0x20110004L, 0x30110004L,
      0x00001000L, 0x10001000L, 0x00011000L, 0x10011000L,
      0x00001004L, 0x10001004L, 0x00011004L, 0x10011004L,
      0x20001000L, 0x30001000L, 0x20011000L, 0x30011000L,
      0x20001004L, 0x30001004L, 0x20011004L, 0x30011004L,
      0x00101000L, 0x10101000L, 0x00111000L, 0x10111000L,
      0x00101004L, 0x10101004L, 0x00111004L, 0x10111004L,
      0x20101000L, 0x30101000L, 0x20111000L, 0x30111000L,
      0x20101004L, 0x30101004L, 0x20111004L, 0x30111004L,
      },
     {
      /* for D bits (numbered as per FIPS 46) 8 9 11 12 13 14 */
      0x00000000L, 0x08000000L, 0x00000008L, 0x08000008L,
      0x00000400L, 0x08000400L, 0x00000408L, 0x08000408L,
      0x00020000L, 0x08020000L, 0x00020008L, 0x08020008L,
      0x00020400L, 0x08020400L, 0x00020408L, 0x08020408L,
      0x00000001L, 0x08000001L, 0x00000009L, 0x08000009L,
      0x00000401L, 0x08000401L, 0x00000409L, 0x08000409L,
      0x00020001L, 0x08020001L, 0x00020009L, 0x08020009L,
      0x00020401L, 0x08020401L, 0x00020409L, 0x08020409L,
      0x02000000L, 0x0A000000L, 0x02000008L, 0x0A000008L,
      0x02000400L, 0x0A000400L, 0x02000408L, 0x0A000408L,
      0x02020000L, 0x0A020000L, 0x02020008L, 0x0A020008L,
      0x02020400L, 0x0A020400L, 0x02020408L, 0x0A020408L,
      0x02000001L, 0x0A000001L, 0x02000009L, 0x0A000009L,
      0x02000401L, 0x0A000401L, 0x02000409L, 0x0A000409L,
      0x02020001L, 0x0A020001L, 0x02020009L, 0x0A020009L,
      0x02020401L, 0x0A020401L, 0x02020409L, 0x0A020409L,
      },
     {
      /* for D bits (numbered as per FIPS 46) 16 17 18 19 20 21 */
      0x00000000L, 0x00000100L, 0x00080000L, 0x00080100L,
      0x01000000L, 0x01000100L, 0x01080000L, 0x01080100L,
      0x00000010L, 0x00000110L, 0x00080010L, 0x00080110L,
      0x01000010L, 0x01000110L, 0x01080010L, 0x01080110L,
      0x00200000L, 0x00200100L, 0x00280000L, 0x00280100L,
      0x01200000L, 0x01200100L, 0x01280000L, 0x01280100L,
      0x00200010L, 0x00200110L, 0x00280010L, 0x00280110L,
      0x01200010L, 0x01200110L, 0x01280010L, 0x01280110L,
      0x00000200L, 0x00000300L, 0x00080200L, 0x00080300L,
      0x01000200L, 0x01000300L, 0x01080200L, 0x01080300L,
      0x00000210L, 0x00000310L, 0x00080210L, 0x00080310L,
      0x01000210L, 0x01000310L, 0x01080210L, 0x01080310L,
      0x00200200L, 0x00200300L, 0x00280200L, 0x00280300L,
      0x01200200L, 0x01200300L, 0x01280200L, 0x01280300L,
      0x00200210L, 0x00200310L, 0x00280210L, 0x00280310L,
      0x01200210L, 0x01200310L, 0x01280210L, 0x01280310L,
      },
     {
      /* for D bits (numbered as per FIPS 46) 22 23 24 25 27 28 */
      0x00000000L, 0x04000000L, 0x00040000L, 0x04040000L,
      0x00000002L, 0x04000002L, 0x00040002L, 0x04040002L,
      0x00002000L, 0x04002000L, 0x00042000L, 0x04042000L,
      0x00002002L, 0x04002002L, 0x00042002L, 0x04042002L,
      0x00000020L, 0x04000020L, 0x00040020L, 0x04040020L,
      0x00000022L, 0x04000022L, 0x00040022L, 0x04040022L,
      0x00002020L, 0x04002020L, 0x00042020L, 0x04042020L,
      0x00002022L, 0x04002022L, 0x00042022L, 0x04042022L,
      0x00000800L, 0x04000800L, 0x00040800L, 0x04040800L,
      0x00000802L, 0x04000802L, 0x00040802L, 0x04040802L,
      0x00002800L, 0x04002800L, 0x00042800L, 0x04042800L,
      0x00002802L, 0x04002802L, 0x00042802L, 0x04042802L,
      0x00000820L, 0x04000820L, 0x00040820L, 0x04040820L,
      0x00000822L, 0x04000822L, 0x00040822L, 0x04040822L,
      0x00002820L, 0x04002820L, 0x00042820L, 0x04042820L,
      0x00002822L, 0x04002822L, 0x00042822L, 0x04042822L,
      }
 };
 
 int DES_set_key(const_DES_cblock *key, DES_key_schedule *schedule)
 {
     if (DES_check_key) {
         return DES_set_key_checked(key, schedule);
     } else {
         DES_set_key_unchecked(key, schedule);
         return 0;
     }
 }
 
 /*-
  * return 0 if key parity is odd (correct),
  * return -1 if key parity error,
  * return -2 if illegal weak key.
  */
 int DES_set_key_checked(const_DES_cblock *key, DES_key_schedule *schedule)
 {
     if (!DES_check_key_parity(key))
         return (-1);
     if (DES_is_weak_key(key))
         return (-2);
     DES_set_key_unchecked(key, schedule);
     return 0;
 }
 
 void DES_set_key_unchecked(const_DES_cblock *key, DES_key_schedule *schedule)
 #ifdef OPENSSL_FIPS
 {
     fips_cipher_abort(DES);
     private_DES_set_key_unchecked(key, schedule);
 }
 
 void private_DES_set_key_unchecked(const_DES_cblock *key,
                                    DES_key_schedule *schedule)
 #endif
 {
     static const int shifts2[16] =
         { 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0 };
     register DES_LONG c, d, t, s, t2;
     register const unsigned char *in;
     register DES_LONG *k;
     register int i;
 
 #ifdef OPENBSD_DEV_CRYPTO
     memcpy(schedule->key, key, sizeof schedule->key);
     schedule->session = NULL;
 #endif
     k = &schedule->ks->deslong[0];
     in = &(*key)[0];
 
     c2l(in, c);
     c2l(in, d);
 
     /*
      * do PC1 in 47 simple operations :-) Thanks to John Fletcher
      * (john_fletcher@lccmail.ocf.llnl.gov) for the inspiration. :-)
      */
     PERM_OP(d, c, t, 4, 0x0f0f0f0fL);
     HPERM_OP(c, t, -2, 0xcccc0000L);
     HPERM_OP(d, t, -2, 0xcccc0000L);
     PERM_OP(d, c, t, 1, 0x55555555L);
     PERM_OP(c, d, t, 8, 0x00ff00ffL);
     PERM_OP(d, c, t, 1, 0x55555555L);
     d = (((d & 0x000000ffL) << 16L) | (d & 0x0000ff00L) |
          ((d & 0x00ff0000L) >> 16L) | ((c & 0xf0000000L) >> 4L));
     c &= 0x0fffffffL;
 
     for (i = 0; i < ITERATIONS; i++) {
         if (shifts2[i]) {
             c = ((c >> 2L) | (c << 26L));
             d = ((d >> 2L) | (d << 26L));
         } else {
             c = ((c >> 1L) | (c << 27L));
             d = ((d >> 1L) | (d << 27L));
         }
         c &= 0x0fffffffL;
         d &= 0x0fffffffL;
         /*
          * could be a few less shifts but I am to lazy at this point in time
          * to investigate
          */
         s = des_skb[0][(c) & 0x3f] |
             des_skb[1][((c >> 6L) & 0x03) | ((c >> 7L) & 0x3c)] |
             des_skb[2][((c >> 13L) & 0x0f) | ((c >> 14L) & 0x30)] |
             des_skb[3][((c >> 20L) & 0x01) | ((c >> 21L) & 0x06) |
                        ((c >> 22L) & 0x38)];
         t = des_skb[4][(d) & 0x3f] |
             des_skb[5][((d >> 7L) & 0x03) | ((d >> 8L) & 0x3c)] |
             des_skb[6][(d >> 15L) & 0x3f] |
             des_skb[7][((d >> 21L) & 0x0f) | ((d >> 22L) & 0x30)];
 
         /* table contained 0213 4657 */
         t2 = ((t << 16L) | (s & 0x0000ffffL)) & 0xffffffffL;
         *(k++) = ROTATE(t2, 30) & 0xffffffffL;
 
         t2 = ((s >> 16L) | (t & 0xffff0000L));
         *(k++) = ROTATE(t2, 26) & 0xffffffffL;
     }
 }
 
 int DES_key_sched(const_DES_cblock *key, DES_key_schedule *schedule)
 {
     return (DES_set_key(key, schedule));
 }
 
 /*-
 #undef des_fixup_key_parity
 void des_fixup_key_parity(des_cblock *key)
         {
         des_set_odd_parity(key);
         }
 */
Index: vendor-crypto/openssl/dist/crypto/dh/dh.h
===================================================================
--- vendor-crypto/openssl/dist/crypto/dh/dh.h	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/dh/dh.h	(revision 318897)
@@ -1,393 +1,410 @@
 /* crypto/dh/dh.h */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 
 #ifndef HEADER_DH_H
 # define HEADER_DH_H
 
 # include 
 
 # ifdef OPENSSL_NO_DH
 #  error DH is disabled.
 # endif
 
 # ifndef OPENSSL_NO_BIO
 #  include 
 # endif
 # include 
 # ifndef OPENSSL_NO_DEPRECATED
 #  include 
 # endif
 
 # ifndef OPENSSL_DH_MAX_MODULUS_BITS
 #  define OPENSSL_DH_MAX_MODULUS_BITS    10000
 # endif
 
 # define DH_FLAG_CACHE_MONT_P     0x01
 
 /*
  * new with 0.9.7h; the built-in DH
  * implementation now uses constant time
  * modular exponentiation for secret exponents
  * by default. This flag causes the
  * faster variable sliding window method to
  * be used for all exponents.
  */
 # define DH_FLAG_NO_EXP_CONSTTIME 0x02
 
 /*
  * If this flag is set the DH method is FIPS compliant and can be used in
  * FIPS mode. This is set in the validated module method. If an application
  * sets this flag in its own methods it is its reposibility to ensure the
  * result is compliant.
  */
 
 # define DH_FLAG_FIPS_METHOD                     0x0400
 
 /*
  * If this flag is set the operations normally disabled in FIPS mode are
  * permitted it is then the applications responsibility to ensure that the
  * usage is compliant.
  */
 
 # define DH_FLAG_NON_FIPS_ALLOW                  0x0400
 
 #ifdef  __cplusplus
 extern "C" {
 #endif
 
 /* Already defined in ossl_typ.h */
 /* typedef struct dh_st DH; */
 /* typedef struct dh_method DH_METHOD; */
 
 struct dh_method {
     const char *name;
     /* Methods here */
     int (*generate_key) (DH *dh);
     int (*compute_key) (unsigned char *key, const BIGNUM *pub_key, DH *dh);
     /* Can be null */
     int (*bn_mod_exp) (const DH *dh, BIGNUM *r, const BIGNUM *a,
                        const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
                        BN_MONT_CTX *m_ctx);
     int (*init) (DH *dh);
     int (*finish) (DH *dh);
     int flags;
     char *app_data;
     /* If this is non-NULL, it will be used to generate parameters */
     int (*generate_params) (DH *dh, int prime_len, int generator,
                             BN_GENCB *cb);
 };
 
 struct dh_st {
     /*
      * This first argument is used to pick up errors when a DH is passed
      * instead of a EVP_PKEY
      */
     int pad;
     int version;
     BIGNUM *p;
     BIGNUM *g;
     long length;                /* optional */
     BIGNUM *pub_key;            /* g^x % p */
     BIGNUM *priv_key;           /* x */
     int flags;
     BN_MONT_CTX *method_mont_p;
     /* Place holders if we want to do X9.42 DH */
     BIGNUM *q;
     BIGNUM *j;
     unsigned char *seed;
     int seedlen;
     BIGNUM *counter;
     int references;
     CRYPTO_EX_DATA ex_data;
     const DH_METHOD *meth;
     ENGINE *engine;
 };
 
 # define DH_GENERATOR_2          2
 /* #define DH_GENERATOR_3       3 */
 # define DH_GENERATOR_5          5
 
 /* DH_check error codes */
 # define DH_CHECK_P_NOT_PRIME            0x01
 # define DH_CHECK_P_NOT_SAFE_PRIME       0x02
 # define DH_UNABLE_TO_CHECK_GENERATOR    0x04
 # define DH_NOT_SUITABLE_GENERATOR       0x08
 # define DH_CHECK_Q_NOT_PRIME            0x10
 # define DH_CHECK_INVALID_Q_VALUE        0x20
 # define DH_CHECK_INVALID_J_VALUE        0x40
 
 /* DH_check_pub_key error codes */
 # define DH_CHECK_PUBKEY_TOO_SMALL       0x01
 # define DH_CHECK_PUBKEY_TOO_LARGE       0x02
 # define DH_CHECK_PUBKEY_INVALID         0x04
 
 /*
  * primes p where (p-1)/2 is prime too are called "safe"; we define this for
  * backward compatibility:
  */
 # define DH_CHECK_P_NOT_STRONG_PRIME     DH_CHECK_P_NOT_SAFE_PRIME
 
-# define d2i_DHparams_fp(fp,x) (DH *)ASN1_d2i_fp((char *(*)())DH_new, \
-                (char *(*)())d2i_DHparams,(fp),(unsigned char **)(x))
-# define i2d_DHparams_fp(fp,x) ASN1_i2d_fp(i2d_DHparams,(fp), \
-                (unsigned char *)(x))
-# define d2i_DHparams_bio(bp,x) ASN1_d2i_bio_of(DH,DH_new,d2i_DHparams,bp,x)
-# define i2d_DHparams_bio(bp,x) ASN1_i2d_bio_of_const(DH,i2d_DHparams,bp,x)
+# define d2i_DHparams_fp(fp,x) \
+    (DH *)ASN1_d2i_fp((char *(*)())DH_new, \
+                      (char *(*)())d2i_DHparams, \
+                      (fp), \
+                      (unsigned char **)(x))
+# define i2d_DHparams_fp(fp,x) \
+    ASN1_i2d_fp(i2d_DHparams,(fp), (unsigned char *)(x))
+# define d2i_DHparams_bio(bp,x) \
+    ASN1_d2i_bio_of(DH, DH_new, d2i_DHparams, bp, x)
+# define i2d_DHparams_bio(bp,x) \
+    ASN1_i2d_bio_of_const(DH,i2d_DHparams,bp,x)
+
+# define d2i_DHxparams_fp(fp,x) \
+    (DH *)ASN1_d2i_fp((char *(*)())DH_new, \
+                      (char *(*)())d2i_DHxparams, \
+                      (fp), \
+                      (unsigned char **)(x))
+# define i2d_DHxparams_fp(fp,x) \
+    ASN1_i2d_fp(i2d_DHxparams,(fp), (unsigned char *)(x))
+# define d2i_DHxparams_bio(bp,x) \
+    ASN1_d2i_bio_of(DH, DH_new, d2i_DHxparams, bp, x)
+# define i2d_DHxparams_bio(bp,x) \
+    ASN1_i2d_bio_of_const(DH, i2d_DHxparams, bp, x)
 
 DH *DHparams_dup(DH *);
 
 const DH_METHOD *DH_OpenSSL(void);
 
 void DH_set_default_method(const DH_METHOD *meth);
 const DH_METHOD *DH_get_default_method(void);
 int DH_set_method(DH *dh, const DH_METHOD *meth);
 DH *DH_new_method(ENGINE *engine);
 
 DH *DH_new(void);
 void DH_free(DH *dh);
 int DH_up_ref(DH *dh);
 int DH_size(const DH *dh);
 int DH_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
                         CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func);
 int DH_set_ex_data(DH *d, int idx, void *arg);
 void *DH_get_ex_data(DH *d, int idx);
 
 /* Deprecated version */
 # ifndef OPENSSL_NO_DEPRECATED
 DH *DH_generate_parameters(int prime_len, int generator,
                            void (*callback) (int, int, void *), void *cb_arg);
 # endif                         /* !defined(OPENSSL_NO_DEPRECATED) */
 
 /* New version */
 int DH_generate_parameters_ex(DH *dh, int prime_len, int generator,
                               BN_GENCB *cb);
 
 int DH_check(const DH *dh, int *codes);
 int DH_check_pub_key(const DH *dh, const BIGNUM *pub_key, int *codes);
 int DH_generate_key(DH *dh);
 int DH_compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh);
 int DH_compute_key_padded(unsigned char *key, const BIGNUM *pub_key, DH *dh);
 DH *d2i_DHparams(DH **a, const unsigned char **pp, long length);
 int i2d_DHparams(const DH *a, unsigned char **pp);
 DH *d2i_DHxparams(DH **a, const unsigned char **pp, long length);
 int i2d_DHxparams(const DH *a, unsigned char **pp);
 # ifndef OPENSSL_NO_FP_API
 int DHparams_print_fp(FILE *fp, const DH *x);
 # endif
 # ifndef OPENSSL_NO_BIO
 int DHparams_print(BIO *bp, const DH *x);
 # else
 int DHparams_print(char *bp, const DH *x);
 # endif
 
 /* RFC 5114 parameters */
 DH *DH_get_1024_160(void);
 DH *DH_get_2048_224(void);
 DH *DH_get_2048_256(void);
 
 /* RFC2631 KDF */
 int DH_KDF_X9_42(unsigned char *out, size_t outlen,
                  const unsigned char *Z, size_t Zlen,
                  ASN1_OBJECT *key_oid,
                  const unsigned char *ukm, size_t ukmlen, const EVP_MD *md);
 
 # define EVP_PKEY_CTX_set_dh_paramgen_prime_len(ctx, len) \
         EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_PARAMGEN, \
                         EVP_PKEY_CTRL_DH_PARAMGEN_PRIME_LEN, len, NULL)
 
 # define EVP_PKEY_CTX_set_dh_paramgen_subprime_len(ctx, len) \
         EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_PARAMGEN, \
                         EVP_PKEY_CTRL_DH_PARAMGEN_SUBPRIME_LEN, len, NULL)
 
 # define EVP_PKEY_CTX_set_dh_paramgen_type(ctx, typ) \
         EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_PARAMGEN, \
                         EVP_PKEY_CTRL_DH_PARAMGEN_TYPE, typ, NULL)
 
 # define EVP_PKEY_CTX_set_dh_paramgen_generator(ctx, gen) \
         EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_PARAMGEN, \
                         EVP_PKEY_CTRL_DH_PARAMGEN_GENERATOR, gen, NULL)
 
 # define EVP_PKEY_CTX_set_dh_rfc5114(ctx, gen) \
         EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, EVP_PKEY_OP_PARAMGEN, \
                         EVP_PKEY_CTRL_DH_RFC5114, gen, NULL)
 
 # define EVP_PKEY_CTX_set_dhx_rfc5114(ctx, gen) \
         EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, EVP_PKEY_OP_PARAMGEN, \
                         EVP_PKEY_CTRL_DH_RFC5114, gen, NULL)
 
 # define EVP_PKEY_CTX_set_dh_kdf_type(ctx, kdf) \
         EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
                                 EVP_PKEY_OP_DERIVE, \
                                 EVP_PKEY_CTRL_DH_KDF_TYPE, kdf, NULL)
 
 # define EVP_PKEY_CTX_get_dh_kdf_type(ctx) \
         EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
                                 EVP_PKEY_OP_DERIVE, \
                                 EVP_PKEY_CTRL_DH_KDF_TYPE, -2, NULL)
 
 # define EVP_PKEY_CTX_set0_dh_kdf_oid(ctx, oid) \
         EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
                                 EVP_PKEY_OP_DERIVE, \
                                 EVP_PKEY_CTRL_DH_KDF_OID, 0, (void *)oid)
 
 # define EVP_PKEY_CTX_get0_dh_kdf_oid(ctx, poid) \
         EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
                                 EVP_PKEY_OP_DERIVE, \
                                 EVP_PKEY_CTRL_GET_DH_KDF_OID, 0, (void *)poid)
 
 # define EVP_PKEY_CTX_set_dh_kdf_md(ctx, md) \
         EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
                                 EVP_PKEY_OP_DERIVE, \
                                 EVP_PKEY_CTRL_DH_KDF_MD, 0, (void *)md)
 
 # define EVP_PKEY_CTX_get_dh_kdf_md(ctx, pmd) \
         EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
                                 EVP_PKEY_OP_DERIVE, \
                                 EVP_PKEY_CTRL_GET_DH_KDF_MD, 0, (void *)pmd)
 
 # define EVP_PKEY_CTX_set_dh_kdf_outlen(ctx, len) \
         EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
                                 EVP_PKEY_OP_DERIVE, \
                                 EVP_PKEY_CTRL_DH_KDF_OUTLEN, len, NULL)
 
 # define EVP_PKEY_CTX_get_dh_kdf_outlen(ctx, plen) \
         EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
                                 EVP_PKEY_OP_DERIVE, \
                         EVP_PKEY_CTRL_GET_DH_KDF_OUTLEN, 0, (void *)plen)
 
 # define EVP_PKEY_CTX_set0_dh_kdf_ukm(ctx, p, plen) \
         EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
                                 EVP_PKEY_OP_DERIVE, \
                                 EVP_PKEY_CTRL_DH_KDF_UKM, plen, (void *)p)
 
 # define EVP_PKEY_CTX_get0_dh_kdf_ukm(ctx, p) \
         EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \
                                 EVP_PKEY_OP_DERIVE, \
                                 EVP_PKEY_CTRL_GET_DH_KDF_UKM, 0, (void *)p)
 
 # define EVP_PKEY_CTRL_DH_PARAMGEN_PRIME_LEN     (EVP_PKEY_ALG_CTRL + 1)
 # define EVP_PKEY_CTRL_DH_PARAMGEN_GENERATOR     (EVP_PKEY_ALG_CTRL + 2)
 # define EVP_PKEY_CTRL_DH_RFC5114                (EVP_PKEY_ALG_CTRL + 3)
 # define EVP_PKEY_CTRL_DH_PARAMGEN_SUBPRIME_LEN  (EVP_PKEY_ALG_CTRL + 4)
 # define EVP_PKEY_CTRL_DH_PARAMGEN_TYPE          (EVP_PKEY_ALG_CTRL + 5)
 # define EVP_PKEY_CTRL_DH_KDF_TYPE               (EVP_PKEY_ALG_CTRL + 6)
 # define EVP_PKEY_CTRL_DH_KDF_MD                 (EVP_PKEY_ALG_CTRL + 7)
 # define EVP_PKEY_CTRL_GET_DH_KDF_MD             (EVP_PKEY_ALG_CTRL + 8)
 # define EVP_PKEY_CTRL_DH_KDF_OUTLEN             (EVP_PKEY_ALG_CTRL + 9)
 # define EVP_PKEY_CTRL_GET_DH_KDF_OUTLEN         (EVP_PKEY_ALG_CTRL + 10)
 # define EVP_PKEY_CTRL_DH_KDF_UKM                (EVP_PKEY_ALG_CTRL + 11)
 # define EVP_PKEY_CTRL_GET_DH_KDF_UKM            (EVP_PKEY_ALG_CTRL + 12)
 # define EVP_PKEY_CTRL_DH_KDF_OID                (EVP_PKEY_ALG_CTRL + 13)
 # define EVP_PKEY_CTRL_GET_DH_KDF_OID            (EVP_PKEY_ALG_CTRL + 14)
 
 /* KDF types */
 # define EVP_PKEY_DH_KDF_NONE                            1
 # define EVP_PKEY_DH_KDF_X9_42                           2
 
 /* BEGIN ERROR CODES */
 /*
  * The following lines are auto generated by the script mkerr.pl. Any changes
  * made after this point may be overwritten when the script is next run.
  */
 void ERR_load_DH_strings(void);
 
 /* Error codes for the DH functions. */
 
 /* Function codes. */
 # define DH_F_COMPUTE_KEY                                 102
 # define DH_F_DHPARAMS_PRINT_FP                           101
 # define DH_F_DH_BUILTIN_GENPARAMS                        106
 # define DH_F_DH_CMS_DECRYPT                              117
 # define DH_F_DH_CMS_SET_PEERKEY                          118
 # define DH_F_DH_CMS_SET_SHARED_INFO                      119
 # define DH_F_DH_COMPUTE_KEY                              114
 # define DH_F_DH_GENERATE_KEY                             115
 # define DH_F_DH_GENERATE_PARAMETERS_EX                   116
 # define DH_F_DH_NEW_METHOD                               105
 # define DH_F_DH_PARAM_DECODE                             107
 # define DH_F_DH_PRIV_DECODE                              110
 # define DH_F_DH_PRIV_ENCODE                              111
 # define DH_F_DH_PUB_DECODE                               108
 # define DH_F_DH_PUB_ENCODE                               109
 # define DH_F_DO_DH_PRINT                                 100
 # define DH_F_GENERATE_KEY                                103
 # define DH_F_GENERATE_PARAMETERS                         104
 # define DH_F_PKEY_DH_DERIVE                              112
 # define DH_F_PKEY_DH_KEYGEN                              113
 
 /* Reason codes. */
 # define DH_R_BAD_GENERATOR                               101
 # define DH_R_BN_DECODE_ERROR                             109
 # define DH_R_BN_ERROR                                    106
 # define DH_R_DECODE_ERROR                                104
 # define DH_R_INVALID_PUBKEY                              102
 # define DH_R_KDF_PARAMETER_ERROR                         112
 # define DH_R_KEYS_NOT_SET                                108
 # define DH_R_KEY_SIZE_TOO_SMALL                          110
 # define DH_R_MODULUS_TOO_LARGE                           103
 # define DH_R_NON_FIPS_METHOD                             111
 # define DH_R_NO_PARAMETERS_SET                           107
 # define DH_R_NO_PRIVATE_VALUE                            100
 # define DH_R_PARAMETER_ENCODING_ERROR                    105
 # define DH_R_PEER_KEY_ERROR                              113
 # define DH_R_SHARED_INFO_ERROR                           114
 
 #ifdef  __cplusplus
 }
 #endif
 #endif
Index: vendor-crypto/openssl/dist/crypto/ec/ec_ameth.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/ec/ec_ameth.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/ec/ec_ameth.c	(revision 318897)
@@ -1,965 +1,967 @@
 /*
  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
  * 2006.
  */
 /* ====================================================================
  * Copyright (c) 2006 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    licensing@OpenSSL.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #include 
 #include "cryptlib.h"
 #include 
 #include 
 #include 
 #ifndef OPENSSL_NO_CMS
 # include 
 #endif
 #include 
 #include "asn1_locl.h"
 #include "ec_lcl.h"
 
 #ifndef OPENSSL_NO_CMS
 static int ecdh_cms_decrypt(CMS_RecipientInfo *ri);
 static int ecdh_cms_encrypt(CMS_RecipientInfo *ri);
 #endif
 
 static int eckey_param2type(int *pptype, void **ppval, EC_KEY *ec_key)
 {
     const EC_GROUP *group;
     int nid;
     if (ec_key == NULL || (group = EC_KEY_get0_group(ec_key)) == NULL) {
         ECerr(EC_F_ECKEY_PARAM2TYPE, EC_R_MISSING_PARAMETERS);
         return 0;
     }
     if (EC_GROUP_get_asn1_flag(group)
         && (nid = EC_GROUP_get_curve_name(group)))
         /* we have a 'named curve' => just set the OID */
     {
         *ppval = OBJ_nid2obj(nid);
         *pptype = V_ASN1_OBJECT;
     } else {                    /* explicit parameters */
 
         ASN1_STRING *pstr = NULL;
         pstr = ASN1_STRING_new();
         if (!pstr)
             return 0;
         pstr->length = i2d_ECParameters(ec_key, &pstr->data);
         if (pstr->length <= 0) {
             ASN1_STRING_free(pstr);
             ECerr(EC_F_ECKEY_PARAM2TYPE, ERR_R_EC_LIB);
             return 0;
         }
         *ppval = pstr;
         *pptype = V_ASN1_SEQUENCE;
     }
     return 1;
 }
 
 static int eckey_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey)
 {
     EC_KEY *ec_key = pkey->pkey.ec;
     void *pval = NULL;
     int ptype;
     unsigned char *penc = NULL, *p;
     int penclen;
 
     if (!eckey_param2type(&ptype, &pval, ec_key)) {
         ECerr(EC_F_ECKEY_PUB_ENCODE, ERR_R_EC_LIB);
         return 0;
     }
     penclen = i2o_ECPublicKey(ec_key, NULL);
     if (penclen <= 0)
         goto err;
     penc = OPENSSL_malloc(penclen);
     if (!penc)
         goto err;
     p = penc;
     penclen = i2o_ECPublicKey(ec_key, &p);
     if (penclen <= 0)
         goto err;
     if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(EVP_PKEY_EC),
                                ptype, pval, penc, penclen))
         return 1;
  err:
     if (ptype == V_ASN1_OBJECT)
         ASN1_OBJECT_free(pval);
     else
         ASN1_STRING_free(pval);
     if (penc)
         OPENSSL_free(penc);
     return 0;
 }
 
 static EC_KEY *eckey_type2param(int ptype, void *pval)
 {
     EC_KEY *eckey = NULL;
     if (ptype == V_ASN1_SEQUENCE) {
         ASN1_STRING *pstr = pval;
         const unsigned char *pm = NULL;
         int pmlen;
         pm = pstr->data;
         pmlen = pstr->length;
         if (!(eckey = d2i_ECParameters(NULL, &pm, pmlen))) {
             ECerr(EC_F_ECKEY_TYPE2PARAM, EC_R_DECODE_ERROR);
             goto ecerr;
         }
     } else if (ptype == V_ASN1_OBJECT) {
         ASN1_OBJECT *poid = pval;
         EC_GROUP *group;
 
         /*
          * type == V_ASN1_OBJECT => the parameters are given by an asn1 OID
          */
         if ((eckey = EC_KEY_new()) == NULL) {
             ECerr(EC_F_ECKEY_TYPE2PARAM, ERR_R_MALLOC_FAILURE);
             goto ecerr;
         }
         group = EC_GROUP_new_by_curve_name(OBJ_obj2nid(poid));
         if (group == NULL)
             goto ecerr;
         EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE);
         if (EC_KEY_set_group(eckey, group) == 0)
             goto ecerr;
         EC_GROUP_free(group);
     } else {
         ECerr(EC_F_ECKEY_TYPE2PARAM, EC_R_DECODE_ERROR);
         goto ecerr;
     }
 
     return eckey;
 
  ecerr:
     if (eckey)
         EC_KEY_free(eckey);
     return NULL;
 }
 
 static int eckey_pub_decode(EVP_PKEY *pkey, X509_PUBKEY *pubkey)
 {
     const unsigned char *p = NULL;
     void *pval;
     int ptype, pklen;
     EC_KEY *eckey = NULL;
     X509_ALGOR *palg;
 
     if (!X509_PUBKEY_get0_param(NULL, &p, &pklen, &palg, pubkey))
         return 0;
     X509_ALGOR_get0(NULL, &ptype, &pval, palg);
 
     eckey = eckey_type2param(ptype, pval);
 
     if (!eckey) {
         ECerr(EC_F_ECKEY_PUB_DECODE, ERR_R_EC_LIB);
         return 0;
     }
 
     /* We have parameters now set public key */
     if (!o2i_ECPublicKey(&eckey, &p, pklen)) {
         ECerr(EC_F_ECKEY_PUB_DECODE, EC_R_DECODE_ERROR);
         goto ecerr;
     }
 
     EVP_PKEY_assign_EC_KEY(pkey, eckey);
     return 1;
 
  ecerr:
     if (eckey)
         EC_KEY_free(eckey);
     return 0;
 }
 
 static int eckey_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b)
 {
     int r;
     const EC_GROUP *group = EC_KEY_get0_group(b->pkey.ec);
     const EC_POINT *pa = EC_KEY_get0_public_key(a->pkey.ec),
         *pb = EC_KEY_get0_public_key(b->pkey.ec);
     if (group == NULL || pa == NULL || pb == NULL)
         return -2;
     r = EC_POINT_cmp(group, pa, pb, NULL);
     if (r == 0)
         return 1;
     if (r == 1)
         return 0;
     return -2;
 }
 
 static int eckey_priv_decode(EVP_PKEY *pkey, PKCS8_PRIV_KEY_INFO *p8)
 {
     const unsigned char *p = NULL;
     void *pval;
     int ptype, pklen;
     EC_KEY *eckey = NULL;
     X509_ALGOR *palg;
 
     if (!PKCS8_pkey_get0(NULL, &p, &pklen, &palg, p8))
         return 0;
     X509_ALGOR_get0(NULL, &ptype, &pval, palg);
 
     eckey = eckey_type2param(ptype, pval);
 
     if (!eckey)
         goto ecliberr;
 
     /* We have parameters now set private key */
     if (!d2i_ECPrivateKey(&eckey, &p, pklen)) {
         ECerr(EC_F_ECKEY_PRIV_DECODE, EC_R_DECODE_ERROR);
         goto ecerr;
     }
 
     /* calculate public key (if necessary) */
     if (EC_KEY_get0_public_key(eckey) == NULL) {
         const BIGNUM *priv_key;
         const EC_GROUP *group;
         EC_POINT *pub_key;
         /*
          * the public key was not included in the SEC1 private key =>
          * calculate the public key
          */
         group = EC_KEY_get0_group(eckey);
         pub_key = EC_POINT_new(group);
         if (pub_key == NULL) {
             ECerr(EC_F_ECKEY_PRIV_DECODE, ERR_R_EC_LIB);
             goto ecliberr;
         }
         if (!EC_POINT_copy(pub_key, EC_GROUP_get0_generator(group))) {
             EC_POINT_free(pub_key);
             ECerr(EC_F_ECKEY_PRIV_DECODE, ERR_R_EC_LIB);
             goto ecliberr;
         }
         priv_key = EC_KEY_get0_private_key(eckey);
         if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, NULL)) {
             EC_POINT_free(pub_key);
             ECerr(EC_F_ECKEY_PRIV_DECODE, ERR_R_EC_LIB);
             goto ecliberr;
         }
         if (EC_KEY_set_public_key(eckey, pub_key) == 0) {
             EC_POINT_free(pub_key);
             ECerr(EC_F_ECKEY_PRIV_DECODE, ERR_R_EC_LIB);
             goto ecliberr;
         }
         EC_POINT_free(pub_key);
     }
 
     EVP_PKEY_assign_EC_KEY(pkey, eckey);
     return 1;
 
  ecliberr:
     ECerr(EC_F_ECKEY_PRIV_DECODE, ERR_R_EC_LIB);
  ecerr:
     if (eckey)
         EC_KEY_free(eckey);
     return 0;
 }
 
 static int eckey_priv_encode(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pkey)
 {
     EC_KEY ec_key = *(pkey->pkey.ec);
     unsigned char *ep, *p;
     int eplen, ptype;
     void *pval;
     unsigned int old_flags;
 
     if (!eckey_param2type(&ptype, &pval, &ec_key)) {
         ECerr(EC_F_ECKEY_PRIV_ENCODE, EC_R_DECODE_ERROR);
         return 0;
     }
 
     /* set the private key */
 
     /*
      * do not include the parameters in the SEC1 private key see PKCS#11
      * 12.11
      */
     old_flags = EC_KEY_get_enc_flags(&ec_key);
     EC_KEY_set_enc_flags(&ec_key, old_flags | EC_PKEY_NO_PARAMETERS);
 
     eplen = i2d_ECPrivateKey(&ec_key, NULL);
     if (!eplen) {
         ECerr(EC_F_ECKEY_PRIV_ENCODE, ERR_R_EC_LIB);
         return 0;
     }
     ep = (unsigned char *)OPENSSL_malloc(eplen);
     if (!ep) {
         ECerr(EC_F_ECKEY_PRIV_ENCODE, ERR_R_MALLOC_FAILURE);
         return 0;
     }
     p = ep;
     if (!i2d_ECPrivateKey(&ec_key, &p)) {
         OPENSSL_free(ep);
         ECerr(EC_F_ECKEY_PRIV_ENCODE, ERR_R_EC_LIB);
         return 0;
     }
 
     if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(NID_X9_62_id_ecPublicKey), 0,
-                         ptype, pval, ep, eplen))
+                         ptype, pval, ep, eplen)) {
+        OPENSSL_free(ep);
         return 0;
+    }
 
     return 1;
 }
 
 static int int_ec_size(const EVP_PKEY *pkey)
 {
     return ECDSA_size(pkey->pkey.ec);
 }
 
 static int ec_bits(const EVP_PKEY *pkey)
 {
     BIGNUM *order = BN_new();
     const EC_GROUP *group;
     int ret;
 
     if (!order) {
         ERR_clear_error();
         return 0;
     }
     group = EC_KEY_get0_group(pkey->pkey.ec);
     if (!EC_GROUP_get_order(group, order, NULL)) {
         ERR_clear_error();
         return 0;
     }
 
     ret = BN_num_bits(order);
     BN_free(order);
     return ret;
 }
 
 static int ec_missing_parameters(const EVP_PKEY *pkey)
 {
     if (pkey->pkey.ec == NULL || EC_KEY_get0_group(pkey->pkey.ec) == NULL)
         return 1;
     return 0;
 }
 
 static int ec_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from)
 {
     EC_GROUP *group = EC_GROUP_dup(EC_KEY_get0_group(from->pkey.ec));
     if (group == NULL)
         return 0;
     if (EC_KEY_set_group(to->pkey.ec, group) == 0)
         return 0;
     EC_GROUP_free(group);
     return 1;
 }
 
 static int ec_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b)
 {
     const EC_GROUP *group_a = EC_KEY_get0_group(a->pkey.ec),
         *group_b = EC_KEY_get0_group(b->pkey.ec);
     if (group_a == NULL || group_b == NULL)
         return -2;
     if (EC_GROUP_cmp(group_a, group_b, NULL))
         return 0;
     else
         return 1;
 }
 
 static void int_ec_free(EVP_PKEY *pkey)
 {
     EC_KEY_free(pkey->pkey.ec);
 }
 
 static int do_EC_KEY_print(BIO *bp, const EC_KEY *x, int off, int ktype)
 {
     unsigned char *buffer = NULL;
     const char *ecstr;
     size_t buf_len = 0, i;
     int ret = 0, reason = ERR_R_BIO_LIB;
     BIGNUM *pub_key = NULL, *order = NULL;
     BN_CTX *ctx = NULL;
     const EC_GROUP *group;
     const EC_POINT *public_key;
     const BIGNUM *priv_key;
 
     if (x == NULL || (group = EC_KEY_get0_group(x)) == NULL) {
         reason = ERR_R_PASSED_NULL_PARAMETER;
         goto err;
     }
 
     ctx = BN_CTX_new();
     if (ctx == NULL) {
         reason = ERR_R_MALLOC_FAILURE;
         goto err;
     }
 
     if (ktype > 0) {
         public_key = EC_KEY_get0_public_key(x);
         if (public_key != NULL) {
             if ((pub_key = EC_POINT_point2bn(group, public_key,
                                              EC_KEY_get_conv_form(x), NULL,
                                              ctx)) == NULL) {
                 reason = ERR_R_EC_LIB;
                 goto err;
             }
             buf_len = (size_t)BN_num_bytes(pub_key);
         }
     }
 
     if (ktype == 2) {
         priv_key = EC_KEY_get0_private_key(x);
         if (priv_key && (i = (size_t)BN_num_bytes(priv_key)) > buf_len)
             buf_len = i;
     } else
         priv_key = NULL;
 
     if (ktype > 0) {
         buf_len += 10;
         if ((buffer = OPENSSL_malloc(buf_len)) == NULL) {
             reason = ERR_R_MALLOC_FAILURE;
             goto err;
         }
     }
     if (ktype == 2)
         ecstr = "Private-Key";
     else if (ktype == 1)
         ecstr = "Public-Key";
     else
         ecstr = "ECDSA-Parameters";
 
     if (!BIO_indent(bp, off, 128))
         goto err;
     if ((order = BN_new()) == NULL)
         goto err;
     if (!EC_GROUP_get_order(group, order, NULL))
         goto err;
     if (BIO_printf(bp, "%s: (%d bit)\n", ecstr, BN_num_bits(order)) <= 0)
         goto err;
 
     if ((priv_key != NULL) && !ASN1_bn_print(bp, "priv:", priv_key,
                                              buffer, off))
         goto err;
     if ((pub_key != NULL) && !ASN1_bn_print(bp, "pub: ", pub_key,
                                             buffer, off))
         goto err;
     if (!ECPKParameters_print(bp, group, off))
         goto err;
     ret = 1;
  err:
     if (!ret)
         ECerr(EC_F_DO_EC_KEY_PRINT, reason);
     if (pub_key)
         BN_free(pub_key);
     if (order)
         BN_free(order);
     if (ctx)
         BN_CTX_free(ctx);
     if (buffer != NULL)
         OPENSSL_free(buffer);
     return (ret);
 }
 
 static int eckey_param_decode(EVP_PKEY *pkey,
                               const unsigned char **pder, int derlen)
 {
     EC_KEY *eckey;
     if (!(eckey = d2i_ECParameters(NULL, pder, derlen))) {
         ECerr(EC_F_ECKEY_PARAM_DECODE, ERR_R_EC_LIB);
         return 0;
     }
     EVP_PKEY_assign_EC_KEY(pkey, eckey);
     return 1;
 }
 
 static int eckey_param_encode(const EVP_PKEY *pkey, unsigned char **pder)
 {
     return i2d_ECParameters(pkey->pkey.ec, pder);
 }
 
 static int eckey_param_print(BIO *bp, const EVP_PKEY *pkey, int indent,
                              ASN1_PCTX *ctx)
 {
     return do_EC_KEY_print(bp, pkey->pkey.ec, indent, 0);
 }
 
 static int eckey_pub_print(BIO *bp, const EVP_PKEY *pkey, int indent,
                            ASN1_PCTX *ctx)
 {
     return do_EC_KEY_print(bp, pkey->pkey.ec, indent, 1);
 }
 
 static int eckey_priv_print(BIO *bp, const EVP_PKEY *pkey, int indent,
                             ASN1_PCTX *ctx)
 {
     return do_EC_KEY_print(bp, pkey->pkey.ec, indent, 2);
 }
 
 static int old_ec_priv_decode(EVP_PKEY *pkey,
                               const unsigned char **pder, int derlen)
 {
     EC_KEY *ec;
     if (!(ec = d2i_ECPrivateKey(NULL, pder, derlen))) {
         ECerr(EC_F_OLD_EC_PRIV_DECODE, EC_R_DECODE_ERROR);
         return 0;
     }
     EVP_PKEY_assign_EC_KEY(pkey, ec);
     return 1;
 }
 
 static int old_ec_priv_encode(const EVP_PKEY *pkey, unsigned char **pder)
 {
     return i2d_ECPrivateKey(pkey->pkey.ec, pder);
 }
 
 static int ec_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2)
 {
     switch (op) {
     case ASN1_PKEY_CTRL_PKCS7_SIGN:
         if (arg1 == 0) {
             int snid, hnid;
             X509_ALGOR *alg1, *alg2;
             PKCS7_SIGNER_INFO_get0_algs(arg2, NULL, &alg1, &alg2);
             if (alg1 == NULL || alg1->algorithm == NULL)
                 return -1;
             hnid = OBJ_obj2nid(alg1->algorithm);
             if (hnid == NID_undef)
                 return -1;
             if (!OBJ_find_sigid_by_algs(&snid, hnid, EVP_PKEY_id(pkey)))
                 return -1;
             X509_ALGOR_set0(alg2, OBJ_nid2obj(snid), V_ASN1_UNDEF, 0);
         }
         return 1;
 #ifndef OPENSSL_NO_CMS
     case ASN1_PKEY_CTRL_CMS_SIGN:
         if (arg1 == 0) {
             int snid, hnid;
             X509_ALGOR *alg1, *alg2;
             CMS_SignerInfo_get0_algs(arg2, NULL, NULL, &alg1, &alg2);
             if (alg1 == NULL || alg1->algorithm == NULL)
                 return -1;
             hnid = OBJ_obj2nid(alg1->algorithm);
             if (hnid == NID_undef)
                 return -1;
             if (!OBJ_find_sigid_by_algs(&snid, hnid, EVP_PKEY_id(pkey)))
                 return -1;
             X509_ALGOR_set0(alg2, OBJ_nid2obj(snid), V_ASN1_UNDEF, 0);
         }
         return 1;
 
     case ASN1_PKEY_CTRL_CMS_ENVELOPE:
         if (arg1 == 1)
             return ecdh_cms_decrypt(arg2);
         else if (arg1 == 0)
             return ecdh_cms_encrypt(arg2);
         return -2;
 
     case ASN1_PKEY_CTRL_CMS_RI_TYPE:
         *(int *)arg2 = CMS_RECIPINFO_AGREE;
         return 1;
 #endif
 
     case ASN1_PKEY_CTRL_DEFAULT_MD_NID:
         *(int *)arg2 = NID_sha256;
         return 2;
 
     default:
         return -2;
 
     }
 
 }
 
 const EVP_PKEY_ASN1_METHOD eckey_asn1_meth = {
     EVP_PKEY_EC,
     EVP_PKEY_EC,
     0,
     "EC",
     "OpenSSL EC algorithm",
 
     eckey_pub_decode,
     eckey_pub_encode,
     eckey_pub_cmp,
     eckey_pub_print,
 
     eckey_priv_decode,
     eckey_priv_encode,
     eckey_priv_print,
 
     int_ec_size,
     ec_bits,
 
     eckey_param_decode,
     eckey_param_encode,
     ec_missing_parameters,
     ec_copy_parameters,
     ec_cmp_parameters,
     eckey_param_print,
     0,
 
     int_ec_free,
     ec_pkey_ctrl,
     old_ec_priv_decode,
     old_ec_priv_encode
 };
 
 #ifndef OPENSSL_NO_CMS
 
 static int ecdh_cms_set_peerkey(EVP_PKEY_CTX *pctx,
                                 X509_ALGOR *alg, ASN1_BIT_STRING *pubkey)
 {
     ASN1_OBJECT *aoid;
     int atype;
     void *aval;
     int rv = 0;
     EVP_PKEY *pkpeer = NULL;
     EC_KEY *ecpeer = NULL;
     const unsigned char *p;
     int plen;
     X509_ALGOR_get0(&aoid, &atype, &aval, alg);
     if (OBJ_obj2nid(aoid) != NID_X9_62_id_ecPublicKey)
         goto err;
     /* If absent parameters get group from main key */
     if (atype == V_ASN1_UNDEF || atype == V_ASN1_NULL) {
         const EC_GROUP *grp;
         EVP_PKEY *pk;
         pk = EVP_PKEY_CTX_get0_pkey(pctx);
         if (!pk)
             goto err;
         grp = EC_KEY_get0_group(pk->pkey.ec);
         ecpeer = EC_KEY_new();
         if (!ecpeer)
             goto err;
         if (!EC_KEY_set_group(ecpeer, grp))
             goto err;
     } else {
         ecpeer = eckey_type2param(atype, aval);
         if (!ecpeer)
             goto err;
     }
     /* We have parameters now set public key */
     plen = ASN1_STRING_length(pubkey);
     p = ASN1_STRING_data(pubkey);
     if (!p || !plen)
         goto err;
     if (!o2i_ECPublicKey(&ecpeer, &p, plen))
         goto err;
     pkpeer = EVP_PKEY_new();
     if (!pkpeer)
         goto err;
     EVP_PKEY_set1_EC_KEY(pkpeer, ecpeer);
     if (EVP_PKEY_derive_set_peer(pctx, pkpeer) > 0)
         rv = 1;
  err:
     if (ecpeer)
         EC_KEY_free(ecpeer);
     if (pkpeer)
         EVP_PKEY_free(pkpeer);
     return rv;
 }
 
 /* Set KDF parameters based on KDF NID */
 static int ecdh_cms_set_kdf_param(EVP_PKEY_CTX *pctx, int eckdf_nid)
 {
     int kdf_nid, kdfmd_nid, cofactor;
     const EVP_MD *kdf_md;
     if (eckdf_nid == NID_undef)
         return 0;
 
     /* Lookup KDF type, cofactor mode and digest */
     if (!OBJ_find_sigid_algs(eckdf_nid, &kdfmd_nid, &kdf_nid))
         return 0;
 
     if (kdf_nid == NID_dh_std_kdf)
         cofactor = 0;
     else if (kdf_nid == NID_dh_cofactor_kdf)
         cofactor = 1;
     else
         return 0;
 
     if (EVP_PKEY_CTX_set_ecdh_cofactor_mode(pctx, cofactor) <= 0)
         return 0;
 
     if (EVP_PKEY_CTX_set_ecdh_kdf_type(pctx, EVP_PKEY_ECDH_KDF_X9_62) <= 0)
         return 0;
 
     kdf_md = EVP_get_digestbynid(kdfmd_nid);
     if (!kdf_md)
         return 0;
 
     if (EVP_PKEY_CTX_set_ecdh_kdf_md(pctx, kdf_md) <= 0)
         return 0;
     return 1;
 }
 
 static int ecdh_cms_set_shared_info(EVP_PKEY_CTX *pctx, CMS_RecipientInfo *ri)
 {
     int rv = 0;
 
     X509_ALGOR *alg, *kekalg = NULL;
     ASN1_OCTET_STRING *ukm;
     const unsigned char *p;
     unsigned char *der = NULL;
     int plen, keylen;
     const EVP_CIPHER *kekcipher;
     EVP_CIPHER_CTX *kekctx;
 
     if (!CMS_RecipientInfo_kari_get0_alg(ri, &alg, &ukm))
         return 0;
 
     if (!ecdh_cms_set_kdf_param(pctx, OBJ_obj2nid(alg->algorithm))) {
         ECerr(EC_F_ECDH_CMS_SET_SHARED_INFO, EC_R_KDF_PARAMETER_ERROR);
         return 0;
     }
 
     if (alg->parameter->type != V_ASN1_SEQUENCE)
         return 0;
 
     p = alg->parameter->value.sequence->data;
     plen = alg->parameter->value.sequence->length;
     kekalg = d2i_X509_ALGOR(NULL, &p, plen);
     if (!kekalg)
         goto err;
     kekctx = CMS_RecipientInfo_kari_get0_ctx(ri);
     if (!kekctx)
         goto err;
     kekcipher = EVP_get_cipherbyobj(kekalg->algorithm);
     if (!kekcipher || EVP_CIPHER_mode(kekcipher) != EVP_CIPH_WRAP_MODE)
         goto err;
     if (!EVP_EncryptInit_ex(kekctx, kekcipher, NULL, NULL, NULL))
         goto err;
     if (EVP_CIPHER_asn1_to_param(kekctx, kekalg->parameter) <= 0)
         goto err;
 
     keylen = EVP_CIPHER_CTX_key_length(kekctx);
     if (EVP_PKEY_CTX_set_ecdh_kdf_outlen(pctx, keylen) <= 0)
         goto err;
 
     plen = CMS_SharedInfo_encode(&der, kekalg, ukm, keylen);
 
     if (!plen)
         goto err;
 
     if (EVP_PKEY_CTX_set0_ecdh_kdf_ukm(pctx, der, plen) <= 0)
         goto err;
     der = NULL;
 
     rv = 1;
  err:
     if (kekalg)
         X509_ALGOR_free(kekalg);
     if (der)
         OPENSSL_free(der);
     return rv;
 }
 
 static int ecdh_cms_decrypt(CMS_RecipientInfo *ri)
 {
     EVP_PKEY_CTX *pctx;
     pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
     if (!pctx)
         return 0;
     /* See if we need to set peer key */
     if (!EVP_PKEY_CTX_get0_peerkey(pctx)) {
         X509_ALGOR *alg;
         ASN1_BIT_STRING *pubkey;
         if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &alg, &pubkey,
                                                  NULL, NULL, NULL))
             return 0;
         if (!alg || !pubkey)
             return 0;
         if (!ecdh_cms_set_peerkey(pctx, alg, pubkey)) {
             ECerr(EC_F_ECDH_CMS_DECRYPT, EC_R_PEER_KEY_ERROR);
             return 0;
         }
     }
     /* Set ECDH derivation parameters and initialise unwrap context */
     if (!ecdh_cms_set_shared_info(pctx, ri)) {
         ECerr(EC_F_ECDH_CMS_DECRYPT, EC_R_SHARED_INFO_ERROR);
         return 0;
     }
     return 1;
 }
 
 static int ecdh_cms_encrypt(CMS_RecipientInfo *ri)
 {
     EVP_PKEY_CTX *pctx;
     EVP_PKEY *pkey;
     EVP_CIPHER_CTX *ctx;
     int keylen;
     X509_ALGOR *talg, *wrap_alg = NULL;
     ASN1_OBJECT *aoid;
     ASN1_BIT_STRING *pubkey;
     ASN1_STRING *wrap_str;
     ASN1_OCTET_STRING *ukm;
     unsigned char *penc = NULL;
     int penclen;
     int rv = 0;
     int ecdh_nid, kdf_type, kdf_nid, wrap_nid;
     const EVP_MD *kdf_md;
     pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
     if (!pctx)
         return 0;
     /* Get ephemeral key */
     pkey = EVP_PKEY_CTX_get0_pkey(pctx);
     if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &talg, &pubkey,
                                              NULL, NULL, NULL))
         goto err;
     X509_ALGOR_get0(&aoid, NULL, NULL, talg);
     /* Is everything uninitialised? */
     if (aoid == OBJ_nid2obj(NID_undef)) {
 
         EC_KEY *eckey = pkey->pkey.ec;
         /* Set the key */
         unsigned char *p;
 
         penclen = i2o_ECPublicKey(eckey, NULL);
         if (penclen <= 0)
             goto err;
         penc = OPENSSL_malloc(penclen);
         if (!penc)
             goto err;
         p = penc;
         penclen = i2o_ECPublicKey(eckey, &p);
         if (penclen <= 0)
             goto err;
         ASN1_STRING_set0(pubkey, penc, penclen);
         pubkey->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07);
         pubkey->flags |= ASN1_STRING_FLAG_BITS_LEFT;
 
         penc = NULL;
         X509_ALGOR_set0(talg, OBJ_nid2obj(NID_X9_62_id_ecPublicKey),
                         V_ASN1_UNDEF, NULL);
     }
 
     /* See if custom paraneters set */
     kdf_type = EVP_PKEY_CTX_get_ecdh_kdf_type(pctx);
     if (kdf_type <= 0)
         goto err;
     if (!EVP_PKEY_CTX_get_ecdh_kdf_md(pctx, &kdf_md))
         goto err;
     ecdh_nid = EVP_PKEY_CTX_get_ecdh_cofactor_mode(pctx);
     if (ecdh_nid < 0)
         goto err;
     else if (ecdh_nid == 0)
         ecdh_nid = NID_dh_std_kdf;
     else if (ecdh_nid == 1)
         ecdh_nid = NID_dh_cofactor_kdf;
 
     if (kdf_type == EVP_PKEY_ECDH_KDF_NONE) {
         kdf_type = EVP_PKEY_ECDH_KDF_X9_62;
         if (EVP_PKEY_CTX_set_ecdh_kdf_type(pctx, kdf_type) <= 0)
             goto err;
     } else
         /* Uknown KDF */
         goto err;
     if (kdf_md == NULL) {
         /* Fixme later for better MD */
         kdf_md = EVP_sha1();
         if (EVP_PKEY_CTX_set_ecdh_kdf_md(pctx, kdf_md) <= 0)
             goto err;
     }
 
     if (!CMS_RecipientInfo_kari_get0_alg(ri, &talg, &ukm))
         goto err;
 
     /* Lookup NID for KDF+cofactor+digest */
 
     if (!OBJ_find_sigid_by_algs(&kdf_nid, EVP_MD_type(kdf_md), ecdh_nid))
         goto err;
     /* Get wrap NID */
     ctx = CMS_RecipientInfo_kari_get0_ctx(ri);
     wrap_nid = EVP_CIPHER_CTX_type(ctx);
     keylen = EVP_CIPHER_CTX_key_length(ctx);
 
     /* Package wrap algorithm in an AlgorithmIdentifier */
 
     wrap_alg = X509_ALGOR_new();
     if (!wrap_alg)
         goto err;
     wrap_alg->algorithm = OBJ_nid2obj(wrap_nid);
     wrap_alg->parameter = ASN1_TYPE_new();
     if (!wrap_alg->parameter)
         goto err;
     if (EVP_CIPHER_param_to_asn1(ctx, wrap_alg->parameter) <= 0)
         goto err;
     if (ASN1_TYPE_get(wrap_alg->parameter) == NID_undef) {
         ASN1_TYPE_free(wrap_alg->parameter);
         wrap_alg->parameter = NULL;
     }
 
     if (EVP_PKEY_CTX_set_ecdh_kdf_outlen(pctx, keylen) <= 0)
         goto err;
 
     penclen = CMS_SharedInfo_encode(&penc, wrap_alg, ukm, keylen);
 
     if (!penclen)
         goto err;
 
     if (EVP_PKEY_CTX_set0_ecdh_kdf_ukm(pctx, penc, penclen) <= 0)
         goto err;
     penc = NULL;
 
     /*
      * Now need to wrap encoding of wrap AlgorithmIdentifier into parameter
      * of another AlgorithmIdentifier.
      */
     penclen = i2d_X509_ALGOR(wrap_alg, &penc);
     if (!penc || !penclen)
         goto err;
     wrap_str = ASN1_STRING_new();
     if (!wrap_str)
         goto err;
     ASN1_STRING_set0(wrap_str, penc, penclen);
     penc = NULL;
     X509_ALGOR_set0(talg, OBJ_nid2obj(kdf_nid), V_ASN1_SEQUENCE, wrap_str);
 
     rv = 1;
 
  err:
     if (penc)
         OPENSSL_free(penc);
     if (wrap_alg)
         X509_ALGOR_free(wrap_alg);
     return rv;
 }
 
 #endif
Index: vendor-crypto/openssl/dist/crypto/ec/ec_asn1.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/ec/ec_asn1.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/ec/ec_asn1.c	(revision 318897)
@@ -1,1326 +1,1331 @@
 /* crypto/ec/ec_asn1.c */
 /*
  * Written by Nils Larsch for the OpenSSL project.
  */
 /* ====================================================================
  * Copyright (c) 2000-2003 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    licensing@OpenSSL.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #include 
 #include "ec_lcl.h"
 #include 
 #include 
 #include 
 
+#define OSSL_NELEM(x)    (sizeof(x)/sizeof(x[0]))
+
 int EC_GROUP_get_basis_type(const EC_GROUP *group)
 {
-    int i = 0;
+    int i;
 
     if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
         NID_X9_62_characteristic_two_field)
         /* everything else is currently not supported */
         return 0;
 
-    while (group->poly[i] != 0)
-        i++;
+    /* Find the last non-zero element of group->poly[] */
+    for (i = 0;
+         i < (int)OSSL_NELEM(group->poly) && group->poly[i] != 0;
+         i++)
+        continue;
 
     if (i == 4)
         return NID_X9_62_ppBasis;
     else if (i == 2)
         return NID_X9_62_tpBasis;
     else
         /* everything else is currently not supported */
         return 0;
 }
 
 #ifndef OPENSSL_NO_EC2M
 int EC_GROUP_get_trinomial_basis(const EC_GROUP *group, unsigned int *k)
 {
     if (group == NULL)
         return 0;
 
     if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
         NID_X9_62_characteristic_two_field
         || !((group->poly[0] != 0) && (group->poly[1] != 0)
              && (group->poly[2] == 0))) {
         ECerr(EC_F_EC_GROUP_GET_TRINOMIAL_BASIS,
               ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
         return 0;
     }
 
     if (k)
         *k = group->poly[1];
 
     return 1;
 }
 
 int EC_GROUP_get_pentanomial_basis(const EC_GROUP *group, unsigned int *k1,
                                    unsigned int *k2, unsigned int *k3)
 {
     if (group == NULL)
         return 0;
 
     if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) !=
         NID_X9_62_characteristic_two_field
         || !((group->poly[0] != 0) && (group->poly[1] != 0)
              && (group->poly[2] != 0) && (group->poly[3] != 0)
              && (group->poly[4] == 0))) {
         ECerr(EC_F_EC_GROUP_GET_PENTANOMIAL_BASIS,
               ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
         return 0;
     }
 
     if (k1)
         *k1 = group->poly[3];
     if (k2)
         *k2 = group->poly[2];
     if (k3)
         *k3 = group->poly[1];
 
     return 1;
 }
 #endif
 
 /* some structures needed for the asn1 encoding */
 typedef struct x9_62_pentanomial_st {
     long k1;
     long k2;
     long k3;
 } X9_62_PENTANOMIAL;
 
 typedef struct x9_62_characteristic_two_st {
     long m;
     ASN1_OBJECT *type;
     union {
         char *ptr;
         /* NID_X9_62_onBasis */
         ASN1_NULL *onBasis;
         /* NID_X9_62_tpBasis */
         ASN1_INTEGER *tpBasis;
         /* NID_X9_62_ppBasis */
         X9_62_PENTANOMIAL *ppBasis;
         /* anything else */
         ASN1_TYPE *other;
     } p;
 } X9_62_CHARACTERISTIC_TWO;
 
 typedef struct x9_62_fieldid_st {
     ASN1_OBJECT *fieldType;
     union {
         char *ptr;
         /* NID_X9_62_prime_field */
         ASN1_INTEGER *prime;
         /* NID_X9_62_characteristic_two_field */
         X9_62_CHARACTERISTIC_TWO *char_two;
         /* anything else */
         ASN1_TYPE *other;
     } p;
 } X9_62_FIELDID;
 
 typedef struct x9_62_curve_st {
     ASN1_OCTET_STRING *a;
     ASN1_OCTET_STRING *b;
     ASN1_BIT_STRING *seed;
 } X9_62_CURVE;
 
 typedef struct ec_parameters_st {
     long version;
     X9_62_FIELDID *fieldID;
     X9_62_CURVE *curve;
     ASN1_OCTET_STRING *base;
     ASN1_INTEGER *order;
     ASN1_INTEGER *cofactor;
 } ECPARAMETERS;
 
 struct ecpk_parameters_st {
     int type;
     union {
         ASN1_OBJECT *named_curve;
         ECPARAMETERS *parameters;
         ASN1_NULL *implicitlyCA;
     } value;
 } /* ECPKPARAMETERS */ ;
 
 /* SEC1 ECPrivateKey */
 typedef struct ec_privatekey_st {
     long version;
     ASN1_OCTET_STRING *privateKey;
     ECPKPARAMETERS *parameters;
     ASN1_BIT_STRING *publicKey;
 } EC_PRIVATEKEY;
 
 /* the OpenSSL ASN.1 definitions */
 ASN1_SEQUENCE(X9_62_PENTANOMIAL) = {
         ASN1_SIMPLE(X9_62_PENTANOMIAL, k1, LONG),
         ASN1_SIMPLE(X9_62_PENTANOMIAL, k2, LONG),
         ASN1_SIMPLE(X9_62_PENTANOMIAL, k3, LONG)
 } ASN1_SEQUENCE_END(X9_62_PENTANOMIAL)
 
 DECLARE_ASN1_ALLOC_FUNCTIONS(X9_62_PENTANOMIAL)
 IMPLEMENT_ASN1_ALLOC_FUNCTIONS(X9_62_PENTANOMIAL)
 
 ASN1_ADB_TEMPLATE(char_two_def) = ASN1_SIMPLE(X9_62_CHARACTERISTIC_TWO, p.other, ASN1_ANY);
 
 ASN1_ADB(X9_62_CHARACTERISTIC_TWO) = {
         ADB_ENTRY(NID_X9_62_onBasis, ASN1_SIMPLE(X9_62_CHARACTERISTIC_TWO, p.onBasis, ASN1_NULL)),
         ADB_ENTRY(NID_X9_62_tpBasis, ASN1_SIMPLE(X9_62_CHARACTERISTIC_TWO, p.tpBasis, ASN1_INTEGER)),
         ADB_ENTRY(NID_X9_62_ppBasis, ASN1_SIMPLE(X9_62_CHARACTERISTIC_TWO, p.ppBasis, X9_62_PENTANOMIAL))
 } ASN1_ADB_END(X9_62_CHARACTERISTIC_TWO, 0, type, 0, &char_two_def_tt, NULL);
 
 ASN1_SEQUENCE(X9_62_CHARACTERISTIC_TWO) = {
         ASN1_SIMPLE(X9_62_CHARACTERISTIC_TWO, m, LONG),
         ASN1_SIMPLE(X9_62_CHARACTERISTIC_TWO, type, ASN1_OBJECT),
         ASN1_ADB_OBJECT(X9_62_CHARACTERISTIC_TWO)
 } ASN1_SEQUENCE_END(X9_62_CHARACTERISTIC_TWO)
 
 DECLARE_ASN1_ALLOC_FUNCTIONS(X9_62_CHARACTERISTIC_TWO)
 IMPLEMENT_ASN1_ALLOC_FUNCTIONS(X9_62_CHARACTERISTIC_TWO)
 
 ASN1_ADB_TEMPLATE(fieldID_def) = ASN1_SIMPLE(X9_62_FIELDID, p.other, ASN1_ANY);
 
 ASN1_ADB(X9_62_FIELDID) = {
         ADB_ENTRY(NID_X9_62_prime_field, ASN1_SIMPLE(X9_62_FIELDID, p.prime, ASN1_INTEGER)),
         ADB_ENTRY(NID_X9_62_characteristic_two_field, ASN1_SIMPLE(X9_62_FIELDID, p.char_two, X9_62_CHARACTERISTIC_TWO))
 } ASN1_ADB_END(X9_62_FIELDID, 0, fieldType, 0, &fieldID_def_tt, NULL);
 
 ASN1_SEQUENCE(X9_62_FIELDID) = {
         ASN1_SIMPLE(X9_62_FIELDID, fieldType, ASN1_OBJECT),
         ASN1_ADB_OBJECT(X9_62_FIELDID)
 } ASN1_SEQUENCE_END(X9_62_FIELDID)
 
 ASN1_SEQUENCE(X9_62_CURVE) = {
         ASN1_SIMPLE(X9_62_CURVE, a, ASN1_OCTET_STRING),
         ASN1_SIMPLE(X9_62_CURVE, b, ASN1_OCTET_STRING),
         ASN1_OPT(X9_62_CURVE, seed, ASN1_BIT_STRING)
 } ASN1_SEQUENCE_END(X9_62_CURVE)
 
 ASN1_SEQUENCE(ECPARAMETERS) = {
         ASN1_SIMPLE(ECPARAMETERS, version, LONG),
         ASN1_SIMPLE(ECPARAMETERS, fieldID, X9_62_FIELDID),
         ASN1_SIMPLE(ECPARAMETERS, curve, X9_62_CURVE),
         ASN1_SIMPLE(ECPARAMETERS, base, ASN1_OCTET_STRING),
         ASN1_SIMPLE(ECPARAMETERS, order, ASN1_INTEGER),
         ASN1_OPT(ECPARAMETERS, cofactor, ASN1_INTEGER)
 } ASN1_SEQUENCE_END(ECPARAMETERS)
 
 DECLARE_ASN1_ALLOC_FUNCTIONS(ECPARAMETERS)
 IMPLEMENT_ASN1_ALLOC_FUNCTIONS(ECPARAMETERS)
 
 ASN1_CHOICE(ECPKPARAMETERS) = {
         ASN1_SIMPLE(ECPKPARAMETERS, value.named_curve, ASN1_OBJECT),
         ASN1_SIMPLE(ECPKPARAMETERS, value.parameters, ECPARAMETERS),
         ASN1_SIMPLE(ECPKPARAMETERS, value.implicitlyCA, ASN1_NULL)
 } ASN1_CHOICE_END(ECPKPARAMETERS)
 
 DECLARE_ASN1_FUNCTIONS_const(ECPKPARAMETERS)
 DECLARE_ASN1_ENCODE_FUNCTIONS_const(ECPKPARAMETERS, ECPKPARAMETERS)
 IMPLEMENT_ASN1_FUNCTIONS_const(ECPKPARAMETERS)
 
 ASN1_SEQUENCE(EC_PRIVATEKEY) = {
         ASN1_SIMPLE(EC_PRIVATEKEY, version, LONG),
         ASN1_SIMPLE(EC_PRIVATEKEY, privateKey, ASN1_OCTET_STRING),
         ASN1_EXP_OPT(EC_PRIVATEKEY, parameters, ECPKPARAMETERS, 0),
         ASN1_EXP_OPT(EC_PRIVATEKEY, publicKey, ASN1_BIT_STRING, 1)
 } ASN1_SEQUENCE_END(EC_PRIVATEKEY)
 
 DECLARE_ASN1_FUNCTIONS_const(EC_PRIVATEKEY)
 DECLARE_ASN1_ENCODE_FUNCTIONS_const(EC_PRIVATEKEY, EC_PRIVATEKEY)
 IMPLEMENT_ASN1_FUNCTIONS_const(EC_PRIVATEKEY)
 
 /* some declarations of internal function */
 
 /* ec_asn1_group2field() sets the values in a X9_62_FIELDID object */
 static int ec_asn1_group2fieldid(const EC_GROUP *, X9_62_FIELDID *);
 /* ec_asn1_group2curve() sets the values in a X9_62_CURVE object */
 static int ec_asn1_group2curve(const EC_GROUP *, X9_62_CURVE *);
 /*
  * ec_asn1_parameters2group() creates a EC_GROUP object from a ECPARAMETERS
  * object
  */
 static EC_GROUP *ec_asn1_parameters2group(const ECPARAMETERS *);
 /*
  * ec_asn1_group2parameters() creates a ECPARAMETERS object from a EC_GROUP
  * object
  */
 static ECPARAMETERS *ec_asn1_group2parameters(const EC_GROUP *,
                                               ECPARAMETERS *);
 /*
  * ec_asn1_pkparameters2group() creates a EC_GROUP object from a
  * ECPKPARAMETERS object
  */
 static EC_GROUP *ec_asn1_pkparameters2group(const ECPKPARAMETERS *);
 /*
  * ec_asn1_group2pkparameters() creates a ECPKPARAMETERS object from a
  * EC_GROUP object
  */
 static ECPKPARAMETERS *ec_asn1_group2pkparameters(const EC_GROUP *,
                                                   ECPKPARAMETERS *);
 
 /* the function definitions */
 
 static int ec_asn1_group2fieldid(const EC_GROUP *group, X9_62_FIELDID *field)
 {
     int ok = 0, nid;
     BIGNUM *tmp = NULL;
 
     if (group == NULL || field == NULL)
         return 0;
 
     /* clear the old values (if necessary) */
     if (field->fieldType != NULL)
         ASN1_OBJECT_free(field->fieldType);
     if (field->p.other != NULL)
         ASN1_TYPE_free(field->p.other);
 
     nid = EC_METHOD_get_field_type(EC_GROUP_method_of(group));
     /* set OID for the field */
     if ((field->fieldType = OBJ_nid2obj(nid)) == NULL) {
         ECerr(EC_F_EC_ASN1_GROUP2FIELDID, ERR_R_OBJ_LIB);
         goto err;
     }
 
     if (nid == NID_X9_62_prime_field) {
         if ((tmp = BN_new()) == NULL) {
             ECerr(EC_F_EC_ASN1_GROUP2FIELDID, ERR_R_MALLOC_FAILURE);
             goto err;
         }
         /* the parameters are specified by the prime number p */
         if (!EC_GROUP_get_curve_GFp(group, tmp, NULL, NULL, NULL)) {
             ECerr(EC_F_EC_ASN1_GROUP2FIELDID, ERR_R_EC_LIB);
             goto err;
         }
         /* set the prime number */
         field->p.prime = BN_to_ASN1_INTEGER(tmp, NULL);
         if (field->p.prime == NULL) {
             ECerr(EC_F_EC_ASN1_GROUP2FIELDID, ERR_R_ASN1_LIB);
             goto err;
         }
     } else                      /* nid == NID_X9_62_characteristic_two_field */
 #ifdef OPENSSL_NO_EC2M
     {
         ECerr(EC_F_EC_ASN1_GROUP2FIELDID, EC_R_GF2M_NOT_SUPPORTED);
         goto err;
     }
 #else
     {
         int field_type;
         X9_62_CHARACTERISTIC_TWO *char_two;
 
         field->p.char_two = X9_62_CHARACTERISTIC_TWO_new();
         char_two = field->p.char_two;
 
         if (char_two == NULL) {
             ECerr(EC_F_EC_ASN1_GROUP2FIELDID, ERR_R_MALLOC_FAILURE);
             goto err;
         }
 
         char_two->m = (long)EC_GROUP_get_degree(group);
 
         field_type = EC_GROUP_get_basis_type(group);
 
         if (field_type == 0) {
             ECerr(EC_F_EC_ASN1_GROUP2FIELDID, ERR_R_EC_LIB);
             goto err;
         }
         /* set base type OID */
         if ((char_two->type = OBJ_nid2obj(field_type)) == NULL) {
             ECerr(EC_F_EC_ASN1_GROUP2FIELDID, ERR_R_OBJ_LIB);
             goto err;
         }
 
         if (field_type == NID_X9_62_tpBasis) {
             unsigned int k;
 
             if (!EC_GROUP_get_trinomial_basis(group, &k))
                 goto err;
 
             char_two->p.tpBasis = ASN1_INTEGER_new();
             if (!char_two->p.tpBasis) {
                 ECerr(EC_F_EC_ASN1_GROUP2FIELDID, ERR_R_MALLOC_FAILURE);
                 goto err;
             }
             if (!ASN1_INTEGER_set(char_two->p.tpBasis, (long)k)) {
                 ECerr(EC_F_EC_ASN1_GROUP2FIELDID, ERR_R_ASN1_LIB);
                 goto err;
             }
         } else if (field_type == NID_X9_62_ppBasis) {
             unsigned int k1, k2, k3;
 
             if (!EC_GROUP_get_pentanomial_basis(group, &k1, &k2, &k3))
                 goto err;
 
             char_two->p.ppBasis = X9_62_PENTANOMIAL_new();
             if (!char_two->p.ppBasis) {
                 ECerr(EC_F_EC_ASN1_GROUP2FIELDID, ERR_R_MALLOC_FAILURE);
                 goto err;
             }
 
             /* set k? values */
             char_two->p.ppBasis->k1 = (long)k1;
             char_two->p.ppBasis->k2 = (long)k2;
             char_two->p.ppBasis->k3 = (long)k3;
         } else {                /* field_type == NID_X9_62_onBasis */
 
             /* for ONB the parameters are (asn1) NULL */
             char_two->p.onBasis = ASN1_NULL_new();
             if (!char_two->p.onBasis) {
                 ECerr(EC_F_EC_ASN1_GROUP2FIELDID, ERR_R_MALLOC_FAILURE);
                 goto err;
             }
         }
     }
 #endif
 
     ok = 1;
 
  err:if (tmp)
         BN_free(tmp);
     return (ok);
 }
 
 static int ec_asn1_group2curve(const EC_GROUP *group, X9_62_CURVE *curve)
 {
     int ok = 0, nid;
     BIGNUM *tmp_1 = NULL, *tmp_2 = NULL;
     unsigned char *buffer_1 = NULL, *buffer_2 = NULL,
         *a_buf = NULL, *b_buf = NULL;
     size_t len_1, len_2;
     unsigned char char_zero = 0;
 
     if (!group || !curve || !curve->a || !curve->b)
         return 0;
 
     if ((tmp_1 = BN_new()) == NULL || (tmp_2 = BN_new()) == NULL) {
         ECerr(EC_F_EC_ASN1_GROUP2CURVE, ERR_R_MALLOC_FAILURE);
         goto err;
     }
 
     nid = EC_METHOD_get_field_type(EC_GROUP_method_of(group));
 
     /* get a and b */
     if (nid == NID_X9_62_prime_field) {
         if (!EC_GROUP_get_curve_GFp(group, NULL, tmp_1, tmp_2, NULL)) {
             ECerr(EC_F_EC_ASN1_GROUP2CURVE, ERR_R_EC_LIB);
             goto err;
         }
     }
 #ifndef OPENSSL_NO_EC2M
     else {                      /* nid == NID_X9_62_characteristic_two_field */
 
         if (!EC_GROUP_get_curve_GF2m(group, NULL, tmp_1, tmp_2, NULL)) {
             ECerr(EC_F_EC_ASN1_GROUP2CURVE, ERR_R_EC_LIB);
             goto err;
         }
     }
 #endif
     len_1 = (size_t)BN_num_bytes(tmp_1);
     len_2 = (size_t)BN_num_bytes(tmp_2);
 
     if (len_1 == 0) {
         /* len_1 == 0 => a == 0 */
         a_buf = &char_zero;
         len_1 = 1;
     } else {
         if ((buffer_1 = OPENSSL_malloc(len_1)) == NULL) {
             ECerr(EC_F_EC_ASN1_GROUP2CURVE, ERR_R_MALLOC_FAILURE);
             goto err;
         }
         if ((len_1 = BN_bn2bin(tmp_1, buffer_1)) == 0) {
             ECerr(EC_F_EC_ASN1_GROUP2CURVE, ERR_R_BN_LIB);
             goto err;
         }
         a_buf = buffer_1;
     }
 
     if (len_2 == 0) {
         /* len_2 == 0 => b == 0 */
         b_buf = &char_zero;
         len_2 = 1;
     } else {
         if ((buffer_2 = OPENSSL_malloc(len_2)) == NULL) {
             ECerr(EC_F_EC_ASN1_GROUP2CURVE, ERR_R_MALLOC_FAILURE);
             goto err;
         }
         if ((len_2 = BN_bn2bin(tmp_2, buffer_2)) == 0) {
             ECerr(EC_F_EC_ASN1_GROUP2CURVE, ERR_R_BN_LIB);
             goto err;
         }
         b_buf = buffer_2;
     }
 
     /* set a and b */
     if (!M_ASN1_OCTET_STRING_set(curve->a, a_buf, len_1) ||
         !M_ASN1_OCTET_STRING_set(curve->b, b_buf, len_2)) {
         ECerr(EC_F_EC_ASN1_GROUP2CURVE, ERR_R_ASN1_LIB);
         goto err;
     }
 
     /* set the seed (optional) */
     if (group->seed) {
         if (!curve->seed)
             if ((curve->seed = ASN1_BIT_STRING_new()) == NULL) {
                 ECerr(EC_F_EC_ASN1_GROUP2CURVE, ERR_R_MALLOC_FAILURE);
                 goto err;
             }
         curve->seed->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07);
         curve->seed->flags |= ASN1_STRING_FLAG_BITS_LEFT;
         if (!ASN1_BIT_STRING_set(curve->seed, group->seed,
                                  (int)group->seed_len)) {
             ECerr(EC_F_EC_ASN1_GROUP2CURVE, ERR_R_ASN1_LIB);
             goto err;
         }
     } else {
         if (curve->seed) {
             ASN1_BIT_STRING_free(curve->seed);
             curve->seed = NULL;
         }
     }
 
     ok = 1;
 
  err:if (buffer_1)
         OPENSSL_free(buffer_1);
     if (buffer_2)
         OPENSSL_free(buffer_2);
     if (tmp_1)
         BN_free(tmp_1);
     if (tmp_2)
         BN_free(tmp_2);
     return (ok);
 }
 
 static ECPARAMETERS *ec_asn1_group2parameters(const EC_GROUP *group,
                                               ECPARAMETERS *param)
 {
     int ok = 0;
     size_t len = 0;
     ECPARAMETERS *ret = NULL;
     BIGNUM *tmp = NULL;
     unsigned char *buffer = NULL;
     const EC_POINT *point = NULL;
     point_conversion_form_t form;
 
     if ((tmp = BN_new()) == NULL) {
         ECerr(EC_F_EC_ASN1_GROUP2PARAMETERS, ERR_R_MALLOC_FAILURE);
         goto err;
     }
 
     if (param == NULL) {
         if ((ret = ECPARAMETERS_new()) == NULL) {
             ECerr(EC_F_EC_ASN1_GROUP2PARAMETERS, ERR_R_MALLOC_FAILURE);
             goto err;
         }
     } else
         ret = param;
 
     /* set the version (always one) */
     ret->version = (long)0x1;
 
     /* set the fieldID */
     if (!ec_asn1_group2fieldid(group, ret->fieldID)) {
         ECerr(EC_F_EC_ASN1_GROUP2PARAMETERS, ERR_R_EC_LIB);
         goto err;
     }
 
     /* set the curve */
     if (!ec_asn1_group2curve(group, ret->curve)) {
         ECerr(EC_F_EC_ASN1_GROUP2PARAMETERS, ERR_R_EC_LIB);
         goto err;
     }
 
     /* set the base point */
     if ((point = EC_GROUP_get0_generator(group)) == NULL) {
         ECerr(EC_F_EC_ASN1_GROUP2PARAMETERS, EC_R_UNDEFINED_GENERATOR);
         goto err;
     }
 
     form = EC_GROUP_get_point_conversion_form(group);
 
     len = EC_POINT_point2oct(group, point, form, NULL, len, NULL);
     if (len == 0) {
         ECerr(EC_F_EC_ASN1_GROUP2PARAMETERS, ERR_R_EC_LIB);
         goto err;
     }
     if ((buffer = OPENSSL_malloc(len)) == NULL) {
         ECerr(EC_F_EC_ASN1_GROUP2PARAMETERS, ERR_R_MALLOC_FAILURE);
         goto err;
     }
     if (!EC_POINT_point2oct(group, point, form, buffer, len, NULL)) {
         ECerr(EC_F_EC_ASN1_GROUP2PARAMETERS, ERR_R_EC_LIB);
         goto err;
     }
     if (ret->base == NULL && (ret->base = ASN1_OCTET_STRING_new()) == NULL) {
         ECerr(EC_F_EC_ASN1_GROUP2PARAMETERS, ERR_R_MALLOC_FAILURE);
         goto err;
     }
     if (!ASN1_OCTET_STRING_set(ret->base, buffer, len)) {
         ECerr(EC_F_EC_ASN1_GROUP2PARAMETERS, ERR_R_ASN1_LIB);
         goto err;
     }
 
     /* set the order */
     if (!EC_GROUP_get_order(group, tmp, NULL)) {
         ECerr(EC_F_EC_ASN1_GROUP2PARAMETERS, ERR_R_EC_LIB);
         goto err;
     }
     ret->order = BN_to_ASN1_INTEGER(tmp, ret->order);
     if (ret->order == NULL) {
         ECerr(EC_F_EC_ASN1_GROUP2PARAMETERS, ERR_R_ASN1_LIB);
         goto err;
     }
 
     /* set the cofactor (optional) */
     if (EC_GROUP_get_cofactor(group, tmp, NULL)) {
         ret->cofactor = BN_to_ASN1_INTEGER(tmp, ret->cofactor);
         if (ret->cofactor == NULL) {
             ECerr(EC_F_EC_ASN1_GROUP2PARAMETERS, ERR_R_ASN1_LIB);
             goto err;
         }
     }
 
     ok = 1;
 
  err:if (!ok) {
         if (ret && !param)
             ECPARAMETERS_free(ret);
         ret = NULL;
     }
     if (tmp)
         BN_free(tmp);
     if (buffer)
         OPENSSL_free(buffer);
     return (ret);
 }
 
 ECPKPARAMETERS *ec_asn1_group2pkparameters(const EC_GROUP *group,
                                            ECPKPARAMETERS *params)
 {
     int ok = 1, tmp;
     ECPKPARAMETERS *ret = params;
 
     if (ret == NULL) {
         if ((ret = ECPKPARAMETERS_new()) == NULL) {
             ECerr(EC_F_EC_ASN1_GROUP2PKPARAMETERS, ERR_R_MALLOC_FAILURE);
             return NULL;
         }
     } else {
         if (ret->type == 0 && ret->value.named_curve)
             ASN1_OBJECT_free(ret->value.named_curve);
         else if (ret->type == 1 && ret->value.parameters)
             ECPARAMETERS_free(ret->value.parameters);
     }
 
     if (EC_GROUP_get_asn1_flag(group)) {
         /*
          * use the asn1 OID to describe the the elliptic curve parameters
          */
         tmp = EC_GROUP_get_curve_name(group);
         if (tmp) {
             ret->type = 0;
             if ((ret->value.named_curve = OBJ_nid2obj(tmp)) == NULL)
                 ok = 0;
         } else
             /* we don't kmow the nid => ERROR */
             ok = 0;
     } else {
         /* use the ECPARAMETERS structure */
         ret->type = 1;
         if ((ret->value.parameters =
              ec_asn1_group2parameters(group, NULL)) == NULL)
             ok = 0;
     }
 
     if (!ok) {
         ECPKPARAMETERS_free(ret);
         return NULL;
     }
     return ret;
 }
 
 static EC_GROUP *ec_asn1_parameters2group(const ECPARAMETERS *params)
 {
     int ok = 0, tmp;
     EC_GROUP *ret = NULL;
     BIGNUM *p = NULL, *a = NULL, *b = NULL;
     EC_POINT *point = NULL;
     long field_bits;
 
     if (!params->fieldID || !params->fieldID->fieldType ||
         !params->fieldID->p.ptr) {
         ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, EC_R_ASN1_ERROR);
         goto err;
     }
 
     /* now extract the curve parameters a and b */
     if (!params->curve || !params->curve->a ||
         !params->curve->a->data || !params->curve->b ||
         !params->curve->b->data) {
         ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, EC_R_ASN1_ERROR);
         goto err;
     }
     a = BN_bin2bn(params->curve->a->data, params->curve->a->length, NULL);
     if (a == NULL) {
         ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, ERR_R_BN_LIB);
         goto err;
     }
     b = BN_bin2bn(params->curve->b->data, params->curve->b->length, NULL);
     if (b == NULL) {
         ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, ERR_R_BN_LIB);
         goto err;
     }
 
     /* get the field parameters */
     tmp = OBJ_obj2nid(params->fieldID->fieldType);
     if (tmp == NID_X9_62_characteristic_two_field)
 #ifdef OPENSSL_NO_EC2M
     {
         ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, EC_R_GF2M_NOT_SUPPORTED);
         goto err;
     }
 #else
     {
         X9_62_CHARACTERISTIC_TWO *char_two;
 
         char_two = params->fieldID->p.char_two;
 
         field_bits = char_two->m;
         if (field_bits > OPENSSL_ECC_MAX_FIELD_BITS) {
             ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, EC_R_FIELD_TOO_LARGE);
             goto err;
         }
 
         if ((p = BN_new()) == NULL) {
             ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, ERR_R_MALLOC_FAILURE);
             goto err;
         }
 
         /* get the base type */
         tmp = OBJ_obj2nid(char_two->type);
 
         if (tmp == NID_X9_62_tpBasis) {
             long tmp_long;
 
             if (!char_two->p.tpBasis) {
                 ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, EC_R_ASN1_ERROR);
                 goto err;
             }
 
             tmp_long = ASN1_INTEGER_get(char_two->p.tpBasis);
 
             if (!(char_two->m > tmp_long && tmp_long > 0)) {
                 ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP,
                       EC_R_INVALID_TRINOMIAL_BASIS);
                 goto err;
             }
 
             /* create the polynomial */
             if (!BN_set_bit(p, (int)char_two->m))
                 goto err;
             if (!BN_set_bit(p, (int)tmp_long))
                 goto err;
             if (!BN_set_bit(p, 0))
                 goto err;
         } else if (tmp == NID_X9_62_ppBasis) {
             X9_62_PENTANOMIAL *penta;
 
             penta = char_two->p.ppBasis;
             if (!penta) {
                 ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, EC_R_ASN1_ERROR);
                 goto err;
             }
 
             if (!
                 (char_two->m > penta->k3 && penta->k3 > penta->k2
                  && penta->k2 > penta->k1 && penta->k1 > 0)) {
                 ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP,
                       EC_R_INVALID_PENTANOMIAL_BASIS);
                 goto err;
             }
 
             /* create the polynomial */
             if (!BN_set_bit(p, (int)char_two->m))
                 goto err;
             if (!BN_set_bit(p, (int)penta->k1))
                 goto err;
             if (!BN_set_bit(p, (int)penta->k2))
                 goto err;
             if (!BN_set_bit(p, (int)penta->k3))
                 goto err;
             if (!BN_set_bit(p, 0))
                 goto err;
         } else if (tmp == NID_X9_62_onBasis) {
             ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, EC_R_NOT_IMPLEMENTED);
             goto err;
         } else {                /* error */
 
             ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, EC_R_ASN1_ERROR);
             goto err;
         }
 
         /* create the EC_GROUP structure */
         ret = EC_GROUP_new_curve_GF2m(p, a, b, NULL);
     }
 #endif
     else if (tmp == NID_X9_62_prime_field) {
         /* we have a curve over a prime field */
         /* extract the prime number */
         if (!params->fieldID->p.prime) {
             ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, EC_R_ASN1_ERROR);
             goto err;
         }
         p = ASN1_INTEGER_to_BN(params->fieldID->p.prime, NULL);
         if (p == NULL) {
             ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, ERR_R_ASN1_LIB);
             goto err;
         }
 
         if (BN_is_negative(p) || BN_is_zero(p)) {
             ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, EC_R_INVALID_FIELD);
             goto err;
         }
 
         field_bits = BN_num_bits(p);
         if (field_bits > OPENSSL_ECC_MAX_FIELD_BITS) {
             ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, EC_R_FIELD_TOO_LARGE);
             goto err;
         }
 
         /* create the EC_GROUP structure */
         ret = EC_GROUP_new_curve_GFp(p, a, b, NULL);
     } else {
         ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, EC_R_INVALID_FIELD);
         goto err;
     }
 
     if (ret == NULL) {
         ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, ERR_R_EC_LIB);
         goto err;
     }
 
     /* extract seed (optional) */
     if (params->curve->seed != NULL) {
         if (ret->seed != NULL)
             OPENSSL_free(ret->seed);
         if (!(ret->seed = OPENSSL_malloc(params->curve->seed->length))) {
             ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, ERR_R_MALLOC_FAILURE);
             goto err;
         }
         memcpy(ret->seed, params->curve->seed->data,
                params->curve->seed->length);
         ret->seed_len = params->curve->seed->length;
     }
 
     if (!params->order || !params->base || !params->base->data) {
         ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, EC_R_ASN1_ERROR);
         goto err;
     }
 
     if ((point = EC_POINT_new(ret)) == NULL)
         goto err;
 
     /* set the point conversion form */
     EC_GROUP_set_point_conversion_form(ret, (point_conversion_form_t)
                                        (params->base->data[0] & ~0x01));
 
     /* extract the ec point */
     if (!EC_POINT_oct2point(ret, point, params->base->data,
                             params->base->length, NULL)) {
         ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, ERR_R_EC_LIB);
         goto err;
     }
 
     /* extract the order */
     if ((a = ASN1_INTEGER_to_BN(params->order, a)) == NULL) {
         ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, ERR_R_ASN1_LIB);
         goto err;
     }
     if (BN_is_negative(a) || BN_is_zero(a)) {
         ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, EC_R_INVALID_GROUP_ORDER);
         goto err;
     }
     if (BN_num_bits(a) > (int)field_bits + 1) { /* Hasse bound */
         ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, EC_R_INVALID_GROUP_ORDER);
         goto err;
     }
 
     /* extract the cofactor (optional) */
     if (params->cofactor == NULL) {
         if (b) {
             BN_free(b);
             b = NULL;
         }
     } else if ((b = ASN1_INTEGER_to_BN(params->cofactor, b)) == NULL) {
         ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, ERR_R_ASN1_LIB);
         goto err;
     }
     /* set the generator, order and cofactor (if present) */
     if (!EC_GROUP_set_generator(ret, point, a, b)) {
         ECerr(EC_F_EC_ASN1_PARAMETERS2GROUP, ERR_R_EC_LIB);
         goto err;
     }
 
     ok = 1;
 
  err:if (!ok) {
         if (ret)
             EC_GROUP_clear_free(ret);
         ret = NULL;
     }
 
     if (p)
         BN_free(p);
     if (a)
         BN_free(a);
     if (b)
         BN_free(b);
     if (point)
         EC_POINT_free(point);
     return (ret);
 }
 
 EC_GROUP *ec_asn1_pkparameters2group(const ECPKPARAMETERS *params)
 {
     EC_GROUP *ret = NULL;
     int tmp = 0;
 
     if (params == NULL) {
         ECerr(EC_F_EC_ASN1_PKPARAMETERS2GROUP, EC_R_MISSING_PARAMETERS);
         return NULL;
     }
 
     if (params->type == 0) {    /* the curve is given by an OID */
         tmp = OBJ_obj2nid(params->value.named_curve);
         if ((ret = EC_GROUP_new_by_curve_name(tmp)) == NULL) {
             ECerr(EC_F_EC_ASN1_PKPARAMETERS2GROUP,
                   EC_R_EC_GROUP_NEW_BY_NAME_FAILURE);
             return NULL;
         }
         EC_GROUP_set_asn1_flag(ret, OPENSSL_EC_NAMED_CURVE);
     } else if (params->type == 1) { /* the parameters are given by a
                                      * ECPARAMETERS structure */
         ret = ec_asn1_parameters2group(params->value.parameters);
         if (!ret) {
             ECerr(EC_F_EC_ASN1_PKPARAMETERS2GROUP, ERR_R_EC_LIB);
             return NULL;
         }
         EC_GROUP_set_asn1_flag(ret, 0x0);
     } else if (params->type == 2) { /* implicitlyCA */
         return NULL;
     } else {
         ECerr(EC_F_EC_ASN1_PKPARAMETERS2GROUP, EC_R_ASN1_ERROR);
         return NULL;
     }
 
     return ret;
 }
 
 /* EC_GROUP <-> DER encoding of ECPKPARAMETERS */
 
 EC_GROUP *d2i_ECPKParameters(EC_GROUP **a, const unsigned char **in, long len)
 {
     EC_GROUP *group = NULL;
     ECPKPARAMETERS *params = NULL;
     const unsigned char *p = *in;
 
     if ((params = d2i_ECPKPARAMETERS(NULL, &p, len)) == NULL) {
         ECerr(EC_F_D2I_ECPKPARAMETERS, EC_R_D2I_ECPKPARAMETERS_FAILURE);
         ECPKPARAMETERS_free(params);
         return NULL;
     }
 
     if ((group = ec_asn1_pkparameters2group(params)) == NULL) {
         ECerr(EC_F_D2I_ECPKPARAMETERS, EC_R_PKPARAMETERS2GROUP_FAILURE);
         ECPKPARAMETERS_free(params);
         return NULL;
     }
 
     if (a && *a)
         EC_GROUP_clear_free(*a);
     if (a)
         *a = group;
 
     ECPKPARAMETERS_free(params);
     *in = p;
     return (group);
 }
 
 int i2d_ECPKParameters(const EC_GROUP *a, unsigned char **out)
 {
     int ret = 0;
     ECPKPARAMETERS *tmp = ec_asn1_group2pkparameters(a, NULL);
     if (tmp == NULL) {
         ECerr(EC_F_I2D_ECPKPARAMETERS, EC_R_GROUP2PKPARAMETERS_FAILURE);
         return 0;
     }
     if ((ret = i2d_ECPKPARAMETERS(tmp, out)) == 0) {
         ECerr(EC_F_I2D_ECPKPARAMETERS, EC_R_I2D_ECPKPARAMETERS_FAILURE);
         ECPKPARAMETERS_free(tmp);
         return 0;
     }
     ECPKPARAMETERS_free(tmp);
     return (ret);
 }
 
 /* some EC_KEY functions */
 
 EC_KEY *d2i_ECPrivateKey(EC_KEY **a, const unsigned char **in, long len)
 {
     int ok = 0;
     EC_KEY *ret = NULL;
     EC_PRIVATEKEY *priv_key = NULL;
     const unsigned char *p = *in;
 
     if ((priv_key = d2i_EC_PRIVATEKEY(NULL, &p, len)) == NULL) {
         ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_EC_LIB);
         return NULL;
     }
 
     if (a == NULL || *a == NULL) {
         if ((ret = EC_KEY_new()) == NULL) {
             ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_MALLOC_FAILURE);
             goto err;
         }
     } else
         ret = *a;
 
     if (priv_key->parameters) {
         if (ret->group)
             EC_GROUP_clear_free(ret->group);
         ret->group = ec_asn1_pkparameters2group(priv_key->parameters);
     }
 
     if (ret->group == NULL) {
         ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_EC_LIB);
         goto err;
     }
 
     ret->version = priv_key->version;
 
     if (priv_key->privateKey) {
         ret->priv_key = BN_bin2bn(M_ASN1_STRING_data(priv_key->privateKey),
                                   M_ASN1_STRING_length(priv_key->privateKey),
                                   ret->priv_key);
         if (ret->priv_key == NULL) {
             ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_BN_LIB);
             goto err;
         }
     } else {
         ECerr(EC_F_D2I_ECPRIVATEKEY, EC_R_MISSING_PRIVATE_KEY);
         goto err;
     }
 
     if (ret->pub_key)
         EC_POINT_clear_free(ret->pub_key);
     ret->pub_key = EC_POINT_new(ret->group);
     if (ret->pub_key == NULL) {
         ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_EC_LIB);
         goto err;
     }
 
     if (priv_key->publicKey) {
         const unsigned char *pub_oct;
         int pub_oct_len;
 
         pub_oct = M_ASN1_STRING_data(priv_key->publicKey);
         pub_oct_len = M_ASN1_STRING_length(priv_key->publicKey);
         /*
          * The first byte - point conversion form - must be present.
          */
         if (pub_oct_len <= 0) {
             ECerr(EC_F_D2I_ECPRIVATEKEY, EC_R_BUFFER_TOO_SMALL);
             goto err;
         }
         /* Save the point conversion form. */
         ret->conv_form = (point_conversion_form_t) (pub_oct[0] & ~0x01);
         if (!EC_POINT_oct2point(ret->group, ret->pub_key,
                                 pub_oct, (size_t)(pub_oct_len), NULL)) {
             ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_EC_LIB);
             goto err;
         }
     } else {
         if (!EC_POINT_mul
             (ret->group, ret->pub_key, ret->priv_key, NULL, NULL, NULL)) {
             ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_EC_LIB);
             goto err;
         }
         /* Remember the original private-key-only encoding. */
         ret->enc_flag |= EC_PKEY_NO_PUBKEY;
     }
 
     if (a)
         *a = ret;
     *in = p;
     ok = 1;
  err:
     if (!ok) {
         if (ret && (a == NULL || *a != ret))
             EC_KEY_free(ret);
         ret = NULL;
     }
 
     if (priv_key)
         EC_PRIVATEKEY_free(priv_key);
 
     return (ret);
 }
 
 int i2d_ECPrivateKey(EC_KEY *a, unsigned char **out)
 {
     int ret = 0, ok = 0;
     unsigned char *buffer = NULL;
     size_t buf_len = 0, tmp_len, bn_len;
     EC_PRIVATEKEY *priv_key = NULL;
 
     if (a == NULL || a->group == NULL || a->priv_key == NULL ||
         (!(a->enc_flag & EC_PKEY_NO_PUBKEY) && a->pub_key == NULL)) {
         ECerr(EC_F_I2D_ECPRIVATEKEY, ERR_R_PASSED_NULL_PARAMETER);
         goto err;
     }
 
     if ((priv_key = EC_PRIVATEKEY_new()) == NULL) {
         ECerr(EC_F_I2D_ECPRIVATEKEY, ERR_R_MALLOC_FAILURE);
         goto err;
     }
 
     priv_key->version = a->version;
 
     bn_len = (size_t)BN_num_bytes(a->priv_key);
 
     /* Octetstring may need leading zeros if BN is to short */
 
     buf_len = (EC_GROUP_get_degree(a->group) + 7) / 8;
 
     if (bn_len > buf_len) {
         ECerr(EC_F_I2D_ECPRIVATEKEY, EC_R_BUFFER_TOO_SMALL);
         goto err;
     }
 
     buffer = OPENSSL_malloc(buf_len);
     if (buffer == NULL) {
         ECerr(EC_F_I2D_ECPRIVATEKEY, ERR_R_MALLOC_FAILURE);
         goto err;
     }
 
     if (!BN_bn2bin(a->priv_key, buffer + buf_len - bn_len)) {
         ECerr(EC_F_I2D_ECPRIVATEKEY, ERR_R_BN_LIB);
         goto err;
     }
 
     if (buf_len - bn_len > 0) {
         memset(buffer, 0, buf_len - bn_len);
     }
 
     if (!M_ASN1_OCTET_STRING_set(priv_key->privateKey, buffer, buf_len)) {
         ECerr(EC_F_I2D_ECPRIVATEKEY, ERR_R_ASN1_LIB);
         goto err;
     }
 
     if (!(a->enc_flag & EC_PKEY_NO_PARAMETERS)) {
         if ((priv_key->parameters =
              ec_asn1_group2pkparameters(a->group,
                                         priv_key->parameters)) == NULL) {
             ECerr(EC_F_I2D_ECPRIVATEKEY, ERR_R_EC_LIB);
             goto err;
         }
     }
 
     if (!(a->enc_flag & EC_PKEY_NO_PUBKEY)) {
         priv_key->publicKey = M_ASN1_BIT_STRING_new();
         if (priv_key->publicKey == NULL) {
             ECerr(EC_F_I2D_ECPRIVATEKEY, ERR_R_MALLOC_FAILURE);
             goto err;
         }
 
         tmp_len = EC_POINT_point2oct(a->group, a->pub_key,
                                      a->conv_form, NULL, 0, NULL);
 
         if (tmp_len > buf_len) {
             unsigned char *tmp_buffer = OPENSSL_realloc(buffer, tmp_len);
             if (!tmp_buffer) {
                 ECerr(EC_F_I2D_ECPRIVATEKEY, ERR_R_MALLOC_FAILURE);
                 goto err;
             }
             buffer = tmp_buffer;
             buf_len = tmp_len;
         }
 
         if (!EC_POINT_point2oct(a->group, a->pub_key,
                                 a->conv_form, buffer, buf_len, NULL)) {
             ECerr(EC_F_I2D_ECPRIVATEKEY, ERR_R_EC_LIB);
             goto err;
         }
 
         priv_key->publicKey->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07);
         priv_key->publicKey->flags |= ASN1_STRING_FLAG_BITS_LEFT;
         if (!M_ASN1_BIT_STRING_set(priv_key->publicKey, buffer, buf_len)) {
             ECerr(EC_F_I2D_ECPRIVATEKEY, ERR_R_ASN1_LIB);
             goto err;
         }
     }
 
     if ((ret = i2d_EC_PRIVATEKEY(priv_key, out)) == 0) {
         ECerr(EC_F_I2D_ECPRIVATEKEY, ERR_R_EC_LIB);
         goto err;
     }
     ok = 1;
  err:
     if (buffer)
         OPENSSL_free(buffer);
     if (priv_key)
         EC_PRIVATEKEY_free(priv_key);
     return (ok ? ret : 0);
 }
 
 int i2d_ECParameters(EC_KEY *a, unsigned char **out)
 {
     if (a == NULL) {
         ECerr(EC_F_I2D_ECPARAMETERS, ERR_R_PASSED_NULL_PARAMETER);
         return 0;
     }
     return i2d_ECPKParameters(a->group, out);
 }
 
 EC_KEY *d2i_ECParameters(EC_KEY **a, const unsigned char **in, long len)
 {
     EC_KEY *ret;
 
     if (in == NULL || *in == NULL) {
         ECerr(EC_F_D2I_ECPARAMETERS, ERR_R_PASSED_NULL_PARAMETER);
         return NULL;
     }
 
     if (a == NULL || *a == NULL) {
         if ((ret = EC_KEY_new()) == NULL) {
             ECerr(EC_F_D2I_ECPARAMETERS, ERR_R_MALLOC_FAILURE);
             return NULL;
         }
     } else
         ret = *a;
 
     if (!d2i_ECPKParameters(&ret->group, in, len)) {
         ECerr(EC_F_D2I_ECPARAMETERS, ERR_R_EC_LIB);
         if (a == NULL || *a != ret)
              EC_KEY_free(ret);
         return NULL;
     }
 
     if (a)
         *a = ret;
 
     return ret;
 }
 
 EC_KEY *o2i_ECPublicKey(EC_KEY **a, const unsigned char **in, long len)
 {
     EC_KEY *ret = NULL;
 
     if (a == NULL || (*a) == NULL || (*a)->group == NULL) {
         /*
          * sorry, but a EC_GROUP-structur is necessary to set the public key
          */
         ECerr(EC_F_O2I_ECPUBLICKEY, ERR_R_PASSED_NULL_PARAMETER);
         return 0;
     }
     ret = *a;
     if (ret->pub_key == NULL &&
         (ret->pub_key = EC_POINT_new(ret->group)) == NULL) {
         ECerr(EC_F_O2I_ECPUBLICKEY, ERR_R_MALLOC_FAILURE);
         return 0;
     }
     if (!EC_POINT_oct2point(ret->group, ret->pub_key, *in, len, NULL)) {
         ECerr(EC_F_O2I_ECPUBLICKEY, ERR_R_EC_LIB);
         return 0;
     }
     /* save the point conversion form */
     ret->conv_form = (point_conversion_form_t) (*in[0] & ~0x01);
     *in += len;
     return ret;
 }
 
 int i2o_ECPublicKey(EC_KEY *a, unsigned char **out)
 {
     size_t buf_len = 0;
     int new_buffer = 0;
 
     if (a == NULL) {
         ECerr(EC_F_I2O_ECPUBLICKEY, ERR_R_PASSED_NULL_PARAMETER);
         return 0;
     }
 
     buf_len = EC_POINT_point2oct(a->group, a->pub_key,
                                  a->conv_form, NULL, 0, NULL);
 
     if (out == NULL || buf_len == 0)
         /* out == NULL => just return the length of the octet string */
         return buf_len;
 
     if (*out == NULL) {
         if ((*out = OPENSSL_malloc(buf_len)) == NULL) {
             ECerr(EC_F_I2O_ECPUBLICKEY, ERR_R_MALLOC_FAILURE);
             return 0;
         }
         new_buffer = 1;
     }
     if (!EC_POINT_point2oct(a->group, a->pub_key, a->conv_form,
                             *out, buf_len, NULL)) {
         ECerr(EC_F_I2O_ECPUBLICKEY, ERR_R_EC_LIB);
         if (new_buffer) {
             OPENSSL_free(*out);
             *out = NULL;
         }
         return 0;
     }
     if (!new_buffer)
         *out += buf_len;
     return buf_len;
 }
Index: vendor-crypto/openssl/dist/crypto/ec/ec_mult.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/ec/ec_mult.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/ec/ec_mult.c	(revision 318897)
@@ -1,913 +1,917 @@
 /* crypto/ec/ec_mult.c */
 /*
  * Originally written by Bodo Moeller and Nils Larsch for the OpenSSL project.
  */
 /* ====================================================================
  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    openssl-core@openssl.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 /* ====================================================================
  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
  * Portions of this software developed by SUN MICROSYSTEMS, INC.,
  * and contributed to the OpenSSL project.
  */
 
 #include 
 
 #include 
 
 #include "ec_lcl.h"
 
 /*
- * This file implements the wNAF-based interleaving multi-exponentation method
- * ();
- * for multiplication with precomputation, we use wNAF splitting
- * ().
+ * This file implements the wNAF-based interleaving multi-exponentiation method
+ * Formerly at:
+ *   http://www.informatik.tu-darmstadt.de/TI/Mitarbeiter/moeller.html#multiexp
+ * You might now find it here:
+ *   http://link.springer.com/chapter/10.1007%2F3-540-45537-X_13
+ *   http://www.bmoeller.de/pdf/TI-01-08.multiexp.pdf
+ * For multiplication with precomputation, we use wNAF splitting, formerly at:
+ *   http://www.informatik.tu-darmstadt.de/TI/Mitarbeiter/moeller.html#fastexp
  */
 
 /* structure for precomputed multiples of the generator */
 typedef struct ec_pre_comp_st {
     const EC_GROUP *group;      /* parent EC_GROUP object */
     size_t blocksize;           /* block size for wNAF splitting */
     size_t numblocks;           /* max. number of blocks for which we have
                                  * precomputation */
     size_t w;                   /* window size */
     EC_POINT **points;          /* array with pre-calculated multiples of
                                  * generator: 'num' pointers to EC_POINT
                                  * objects followed by a NULL */
     size_t num;                 /* numblocks * 2^(w-1) */
     int references;
 } EC_PRE_COMP;
 
 /* functions to manage EC_PRE_COMP within the EC_GROUP extra_data framework */
 static void *ec_pre_comp_dup(void *);
 static void ec_pre_comp_free(void *);
 static void ec_pre_comp_clear_free(void *);
 
 static EC_PRE_COMP *ec_pre_comp_new(const EC_GROUP *group)
 {
     EC_PRE_COMP *ret = NULL;
 
     if (!group)
         return NULL;
 
     ret = (EC_PRE_COMP *)OPENSSL_malloc(sizeof(EC_PRE_COMP));
     if (!ret) {
         ECerr(EC_F_EC_PRE_COMP_NEW, ERR_R_MALLOC_FAILURE);
         return ret;
     }
     ret->group = group;
     ret->blocksize = 8;         /* default */
     ret->numblocks = 0;
     ret->w = 4;                 /* default */
     ret->points = NULL;
     ret->num = 0;
     ret->references = 1;
     return ret;
 }
 
 static void *ec_pre_comp_dup(void *src_)
 {
     EC_PRE_COMP *src = src_;
 
     /* no need to actually copy, these objects never change! */
 
     CRYPTO_add(&src->references, 1, CRYPTO_LOCK_EC_PRE_COMP);
 
     return src_;
 }
 
 static void ec_pre_comp_free(void *pre_)
 {
     int i;
     EC_PRE_COMP *pre = pre_;
 
     if (!pre)
         return;
 
     i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP);
     if (i > 0)
         return;
 
     if (pre->points) {
         EC_POINT **p;
 
         for (p = pre->points; *p != NULL; p++)
             EC_POINT_free(*p);
         OPENSSL_free(pre->points);
     }
     OPENSSL_free(pre);
 }
 
 static void ec_pre_comp_clear_free(void *pre_)
 {
     int i;
     EC_PRE_COMP *pre = pre_;
 
     if (!pre)
         return;
 
     i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP);
     if (i > 0)
         return;
 
     if (pre->points) {
         EC_POINT **p;
 
         for (p = pre->points; *p != NULL; p++) {
             EC_POINT_clear_free(*p);
             OPENSSL_cleanse(p, sizeof *p);
         }
         OPENSSL_free(pre->points);
     }
     OPENSSL_cleanse(pre, sizeof *pre);
     OPENSSL_free(pre);
 }
 
 /*-
  * Determine the modified width-(w+1) Non-Adjacent Form (wNAF) of 'scalar'.
  * This is an array  r[]  of values that are either zero or odd with an
  * absolute value less than  2^w  satisfying
  *     scalar = \sum_j r[j]*2^j
  * where at most one of any  w+1  consecutive digits is non-zero
  * with the exception that the most significant digit may be only
  * w-1 zeros away from that next non-zero digit.
  */
 static signed char *compute_wNAF(const BIGNUM *scalar, int w, size_t *ret_len)
 {
     int window_val;
     int ok = 0;
     signed char *r = NULL;
     int sign = 1;
     int bit, next_bit, mask;
     size_t len = 0, j;
 
     if (BN_is_zero(scalar)) {
         r = OPENSSL_malloc(1);
         if (!r) {
             ECerr(EC_F_COMPUTE_WNAF, ERR_R_MALLOC_FAILURE);
             goto err;
         }
         r[0] = 0;
         *ret_len = 1;
         return r;
     }
 
     if (w <= 0 || w > 7) {      /* 'signed char' can represent integers with
                                  * absolute values less than 2^7 */
         ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
         goto err;
     }
     bit = 1 << w;               /* at most 128 */
     next_bit = bit << 1;        /* at most 256 */
     mask = next_bit - 1;        /* at most 255 */
 
     if (BN_is_negative(scalar)) {
         sign = -1;
     }
 
     if (scalar->d == NULL || scalar->top == 0) {
         ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
         goto err;
     }
 
     len = BN_num_bits(scalar);
     r = OPENSSL_malloc(len + 1); /* modified wNAF may be one digit longer
                                   * than binary representation (*ret_len will
                                   * be set to the actual length, i.e. at most
                                   * BN_num_bits(scalar) + 1) */
     if (r == NULL) {
         ECerr(EC_F_COMPUTE_WNAF, ERR_R_MALLOC_FAILURE);
         goto err;
     }
     window_val = scalar->d[0] & mask;
     j = 0;
     while ((window_val != 0) || (j + w + 1 < len)) { /* if j+w+1 >= len,
                                                       * window_val will not
                                                       * increase */
         int digit = 0;
 
         /* 0 <= window_val <= 2^(w+1) */
 
         if (window_val & 1) {
             /* 0 < window_val < 2^(w+1) */
 
             if (window_val & bit) {
                 digit = window_val - next_bit; /* -2^w < digit < 0 */
 
 #if 1                           /* modified wNAF */
                 if (j + w + 1 >= len) {
                     /*
                      * special case for generating modified wNAFs: no new
                      * bits will be added into window_val, so using a
                      * positive digit here will decrease the total length of
                      * the representation
                      */
 
                     digit = window_val & (mask >> 1); /* 0 < digit < 2^w */
                 }
 #endif
             } else {
                 digit = window_val; /* 0 < digit < 2^w */
             }
 
             if (digit <= -bit || digit >= bit || !(digit & 1)) {
                 ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
                 goto err;
             }
 
             window_val -= digit;
 
             /*
              * now window_val is 0 or 2^(w+1) in standard wNAF generation;
              * for modified window NAFs, it may also be 2^w
              */
             if (window_val != 0 && window_val != next_bit
                 && window_val != bit) {
                 ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
                 goto err;
             }
         }
 
         r[j++] = sign * digit;
 
         window_val >>= 1;
         window_val += bit * BN_is_bit_set(scalar, j + w);
 
         if (window_val > next_bit) {
             ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
             goto err;
         }
     }
 
     if (j > len + 1) {
         ECerr(EC_F_COMPUTE_WNAF, ERR_R_INTERNAL_ERROR);
         goto err;
     }
     len = j;
     ok = 1;
 
  err:
     if (!ok) {
         OPENSSL_free(r);
         r = NULL;
     }
     if (ok)
         *ret_len = len;
     return r;
 }
 
 /*
  * TODO: table should be optimised for the wNAF-based implementation,
  * sometimes smaller windows will give better performance (thus the
  * boundaries should be increased)
  */
 #define EC_window_bits_for_scalar_size(b) \
                 ((size_t) \
                  ((b) >= 2000 ? 6 : \
                   (b) >=  800 ? 5 : \
                   (b) >=  300 ? 4 : \
                   (b) >=   70 ? 3 : \
                   (b) >=   20 ? 2 : \
                   1))
 
 /*-
  * Compute
  *      \sum scalars[i]*points[i],
  * also including
  *      scalar*generator
  * in the addition if scalar != NULL
  */
 int ec_wNAF_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar,
                 size_t num, const EC_POINT *points[], const BIGNUM *scalars[],
                 BN_CTX *ctx)
 {
     BN_CTX *new_ctx = NULL;
     const EC_POINT *generator = NULL;
     EC_POINT *tmp = NULL;
     size_t totalnum;
     size_t blocksize = 0, numblocks = 0; /* for wNAF splitting */
     size_t pre_points_per_block = 0;
     size_t i, j;
     int k;
     int r_is_inverted = 0;
     int r_is_at_infinity = 1;
     size_t *wsize = NULL;       /* individual window sizes */
     signed char **wNAF = NULL;  /* individual wNAFs */
     size_t *wNAF_len = NULL;
     size_t max_len = 0;
     size_t num_val;
     EC_POINT **val = NULL;      /* precomputation */
     EC_POINT **v;
     EC_POINT ***val_sub = NULL; /* pointers to sub-arrays of 'val' or
                                  * 'pre_comp->points' */
     const EC_PRE_COMP *pre_comp = NULL;
     int num_scalar = 0;         /* flag: will be set to 1 if 'scalar' must be
                                  * treated like other scalars, i.e.
                                  * precomputation is not available */
     int ret = 0;
 
     if (group->meth != r->meth) {
         ECerr(EC_F_EC_WNAF_MUL, EC_R_INCOMPATIBLE_OBJECTS);
         return 0;
     }
 
     if ((scalar == NULL) && (num == 0)) {
         return EC_POINT_set_to_infinity(group, r);
     }
 
     for (i = 0; i < num; i++) {
         if (group->meth != points[i]->meth) {
             ECerr(EC_F_EC_WNAF_MUL, EC_R_INCOMPATIBLE_OBJECTS);
             return 0;
         }
     }
 
     if (ctx == NULL) {
         ctx = new_ctx = BN_CTX_new();
         if (ctx == NULL)
             goto err;
     }
 
     if (scalar != NULL) {
         generator = EC_GROUP_get0_generator(group);
         if (generator == NULL) {
             ECerr(EC_F_EC_WNAF_MUL, EC_R_UNDEFINED_GENERATOR);
             goto err;
         }
 
         /* look if we can use precomputed multiples of generator */
 
         pre_comp =
             EC_EX_DATA_get_data(group->extra_data, ec_pre_comp_dup,
                                 ec_pre_comp_free, ec_pre_comp_clear_free);
 
         if (pre_comp && pre_comp->numblocks
             && (EC_POINT_cmp(group, generator, pre_comp->points[0], ctx) ==
                 0)) {
             blocksize = pre_comp->blocksize;
 
             /*
              * determine maximum number of blocks that wNAF splitting may
              * yield (NB: maximum wNAF length is bit length plus one)
              */
             numblocks = (BN_num_bits(scalar) / blocksize) + 1;
 
             /*
              * we cannot use more blocks than we have precomputation for
              */
             if (numblocks > pre_comp->numblocks)
                 numblocks = pre_comp->numblocks;
 
             pre_points_per_block = (size_t)1 << (pre_comp->w - 1);
 
             /* check that pre_comp looks sane */
             if (pre_comp->num != (pre_comp->numblocks * pre_points_per_block)) {
                 ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
                 goto err;
             }
         } else {
             /* can't use precomputation */
             pre_comp = NULL;
             numblocks = 1;
             num_scalar = 1;     /* treat 'scalar' like 'num'-th element of
                                  * 'scalars' */
         }
     }
 
     totalnum = num + numblocks;
 
     wsize = OPENSSL_malloc(totalnum * sizeof wsize[0]);
     wNAF_len = OPENSSL_malloc(totalnum * sizeof wNAF_len[0]);
     wNAF = OPENSSL_malloc((totalnum + 1) * sizeof wNAF[0]); /* includes space
                                                              * for pivot */
     val_sub = OPENSSL_malloc(totalnum * sizeof val_sub[0]);
 
     /* Ensure wNAF is initialised in case we end up going to err */
     if (wNAF)
         wNAF[0] = NULL;         /* preliminary pivot */
 
     if (!wsize || !wNAF_len || !wNAF || !val_sub) {
         ECerr(EC_F_EC_WNAF_MUL, ERR_R_MALLOC_FAILURE);
         goto err;
     }
 
     /*
      * num_val will be the total number of temporarily precomputed points
      */
     num_val = 0;
 
     for (i = 0; i < num + num_scalar; i++) {
         size_t bits;
 
         bits = i < num ? BN_num_bits(scalars[i]) : BN_num_bits(scalar);
         wsize[i] = EC_window_bits_for_scalar_size(bits);
         num_val += (size_t)1 << (wsize[i] - 1);
         wNAF[i + 1] = NULL;     /* make sure we always have a pivot */
         wNAF[i] =
             compute_wNAF((i < num ? scalars[i] : scalar), wsize[i],
                          &wNAF_len[i]);
         if (wNAF[i] == NULL)
             goto err;
         if (wNAF_len[i] > max_len)
             max_len = wNAF_len[i];
     }
 
     if (numblocks) {
         /* we go here iff scalar != NULL */
 
         if (pre_comp == NULL) {
             if (num_scalar != 1) {
                 ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
                 goto err;
             }
             /* we have already generated a wNAF for 'scalar' */
         } else {
             signed char *tmp_wNAF = NULL;
             size_t tmp_len = 0;
 
             if (num_scalar != 0) {
                 ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
                 goto err;
             }
 
             /*
              * use the window size for which we have precomputation
              */
             wsize[num] = pre_comp->w;
             tmp_wNAF = compute_wNAF(scalar, wsize[num], &tmp_len);
             if (!tmp_wNAF)
                 goto err;
 
             if (tmp_len <= max_len) {
                 /*
                  * One of the other wNAFs is at least as long as the wNAF
                  * belonging to the generator, so wNAF splitting will not buy
                  * us anything.
                  */
 
                 numblocks = 1;
                 totalnum = num + 1; /* don't use wNAF splitting */
                 wNAF[num] = tmp_wNAF;
                 wNAF[num + 1] = NULL;
                 wNAF_len[num] = tmp_len;
                 if (tmp_len > max_len)
                     max_len = tmp_len;
                 /*
                  * pre_comp->points starts with the points that we need here:
                  */
                 val_sub[num] = pre_comp->points;
             } else {
                 /*
                  * don't include tmp_wNAF directly into wNAF array - use wNAF
                  * splitting and include the blocks
                  */
 
                 signed char *pp;
                 EC_POINT **tmp_points;
 
                 if (tmp_len < numblocks * blocksize) {
                     /*
                      * possibly we can do with fewer blocks than estimated
                      */
                     numblocks = (tmp_len + blocksize - 1) / blocksize;
                     if (numblocks > pre_comp->numblocks) {
                         ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
                         goto err;
                     }
                     totalnum = num + numblocks;
                 }
 
                 /* split wNAF in 'numblocks' parts */
                 pp = tmp_wNAF;
                 tmp_points = pre_comp->points;
 
                 for (i = num; i < totalnum; i++) {
                     if (i < totalnum - 1) {
                         wNAF_len[i] = blocksize;
                         if (tmp_len < blocksize) {
                             ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
                             goto err;
                         }
                         tmp_len -= blocksize;
                     } else
                         /*
                          * last block gets whatever is left (this could be
                          * more or less than 'blocksize'!)
                          */
                         wNAF_len[i] = tmp_len;
 
                     wNAF[i + 1] = NULL;
                     wNAF[i] = OPENSSL_malloc(wNAF_len[i]);
                     if (wNAF[i] == NULL) {
                         ECerr(EC_F_EC_WNAF_MUL, ERR_R_MALLOC_FAILURE);
                         OPENSSL_free(tmp_wNAF);
                         goto err;
                     }
                     memcpy(wNAF[i], pp, wNAF_len[i]);
                     if (wNAF_len[i] > max_len)
                         max_len = wNAF_len[i];
 
                     if (*tmp_points == NULL) {
                         ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
                         OPENSSL_free(tmp_wNAF);
                         goto err;
                     }
                     val_sub[i] = tmp_points;
                     tmp_points += pre_points_per_block;
                     pp += blocksize;
                 }
                 OPENSSL_free(tmp_wNAF);
             }
         }
     }
 
     /*
      * All points we precompute now go into a single array 'val'.
      * 'val_sub[i]' is a pointer to the subarray for the i-th point, or to a
      * subarray of 'pre_comp->points' if we already have precomputation.
      */
     val = OPENSSL_malloc((num_val + 1) * sizeof val[0]);
     if (val == NULL) {
         ECerr(EC_F_EC_WNAF_MUL, ERR_R_MALLOC_FAILURE);
         goto err;
     }
     val[num_val] = NULL;        /* pivot element */
 
     /* allocate points for precomputation */
     v = val;
     for (i = 0; i < num + num_scalar; i++) {
         val_sub[i] = v;
         for (j = 0; j < ((size_t)1 << (wsize[i] - 1)); j++) {
             *v = EC_POINT_new(group);
             if (*v == NULL)
                 goto err;
             v++;
         }
     }
     if (!(v == val + num_val)) {
         ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
         goto err;
     }
 
     if (!(tmp = EC_POINT_new(group)))
         goto err;
 
     /*-
      * prepare precomputed values:
      *    val_sub[i][0] :=     points[i]
      *    val_sub[i][1] := 3 * points[i]
      *    val_sub[i][2] := 5 * points[i]
      *    ...
      */
     for (i = 0; i < num + num_scalar; i++) {
         if (i < num) {
             if (!EC_POINT_copy(val_sub[i][0], points[i]))
                 goto err;
         } else {
             if (!EC_POINT_copy(val_sub[i][0], generator))
                 goto err;
         }
 
         if (wsize[i] > 1) {
             if (!EC_POINT_dbl(group, tmp, val_sub[i][0], ctx))
                 goto err;
             for (j = 1; j < ((size_t)1 << (wsize[i] - 1)); j++) {
                 if (!EC_POINT_add
                     (group, val_sub[i][j], val_sub[i][j - 1], tmp, ctx))
                     goto err;
             }
         }
     }
 
 #if 1                           /* optional; EC_window_bits_for_scalar_size
                                  * assumes we do this step */
     if (!EC_POINTs_make_affine(group, num_val, val, ctx))
         goto err;
 #endif
 
     r_is_at_infinity = 1;
 
     for (k = max_len - 1; k >= 0; k--) {
         if (!r_is_at_infinity) {
             if (!EC_POINT_dbl(group, r, r, ctx))
                 goto err;
         }
 
         for (i = 0; i < totalnum; i++) {
             if (wNAF_len[i] > (size_t)k) {
                 int digit = wNAF[i][k];
                 int is_neg;
 
                 if (digit) {
                     is_neg = digit < 0;
 
                     if (is_neg)
                         digit = -digit;
 
                     if (is_neg != r_is_inverted) {
                         if (!r_is_at_infinity) {
                             if (!EC_POINT_invert(group, r, ctx))
                                 goto err;
                         }
                         r_is_inverted = !r_is_inverted;
                     }
 
                     /* digit > 0 */
 
                     if (r_is_at_infinity) {
                         if (!EC_POINT_copy(r, val_sub[i][digit >> 1]))
                             goto err;
                         r_is_at_infinity = 0;
                     } else {
                         if (!EC_POINT_add
                             (group, r, r, val_sub[i][digit >> 1], ctx))
                             goto err;
                     }
                 }
             }
         }
     }
 
     if (r_is_at_infinity) {
         if (!EC_POINT_set_to_infinity(group, r))
             goto err;
     } else {
         if (r_is_inverted)
             if (!EC_POINT_invert(group, r, ctx))
                 goto err;
     }
 
     ret = 1;
 
  err:
     if (new_ctx != NULL)
         BN_CTX_free(new_ctx);
     if (tmp != NULL)
         EC_POINT_free(tmp);
     if (wsize != NULL)
         OPENSSL_free(wsize);
     if (wNAF_len != NULL)
         OPENSSL_free(wNAF_len);
     if (wNAF != NULL) {
         signed char **w;
 
         for (w = wNAF; *w != NULL; w++)
             OPENSSL_free(*w);
 
         OPENSSL_free(wNAF);
     }
     if (val != NULL) {
         for (v = val; *v != NULL; v++)
             EC_POINT_clear_free(*v);
 
         OPENSSL_free(val);
     }
     if (val_sub != NULL) {
         OPENSSL_free(val_sub);
     }
     return ret;
 }
 
 /*-
  * ec_wNAF_precompute_mult()
  * creates an EC_PRE_COMP object with preprecomputed multiples of the generator
  * for use with wNAF splitting as implemented in ec_wNAF_mul().
  *
  * 'pre_comp->points' is an array of multiples of the generator
  * of the following form:
  * points[0] =     generator;
  * points[1] = 3 * generator;
  * ...
  * points[2^(w-1)-1] =     (2^(w-1)-1) * generator;
  * points[2^(w-1)]   =     2^blocksize * generator;
  * points[2^(w-1)+1] = 3 * 2^blocksize * generator;
  * ...
  * points[2^(w-1)*(numblocks-1)-1] = (2^(w-1)) *  2^(blocksize*(numblocks-2)) * generator
  * points[2^(w-1)*(numblocks-1)]   =              2^(blocksize*(numblocks-1)) * generator
  * ...
  * points[2^(w-1)*numblocks-1]     = (2^(w-1)) *  2^(blocksize*(numblocks-1)) * generator
  * points[2^(w-1)*numblocks]       = NULL
  */
 int ec_wNAF_precompute_mult(EC_GROUP *group, BN_CTX *ctx)
 {
     const EC_POINT *generator;
     EC_POINT *tmp_point = NULL, *base = NULL, **var;
     BN_CTX *new_ctx = NULL;
     BIGNUM *order;
     size_t i, bits, w, pre_points_per_block, blocksize, numblocks, num;
     EC_POINT **points = NULL;
     EC_PRE_COMP *pre_comp;
     int ret = 0;
 
     /* if there is an old EC_PRE_COMP object, throw it away */
     EC_EX_DATA_free_data(&group->extra_data, ec_pre_comp_dup,
                          ec_pre_comp_free, ec_pre_comp_clear_free);
 
     if ((pre_comp = ec_pre_comp_new(group)) == NULL)
         return 0;
 
     generator = EC_GROUP_get0_generator(group);
     if (generator == NULL) {
         ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, EC_R_UNDEFINED_GENERATOR);
         goto err;
     }
 
     if (ctx == NULL) {
         ctx = new_ctx = BN_CTX_new();
         if (ctx == NULL)
             goto err;
     }
 
     BN_CTX_start(ctx);
     order = BN_CTX_get(ctx);
     if (order == NULL)
         goto err;
 
     if (!EC_GROUP_get_order(group, order, ctx))
         goto err;
     if (BN_is_zero(order)) {
         ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, EC_R_UNKNOWN_ORDER);
         goto err;
     }
 
     bits = BN_num_bits(order);
     /*
      * The following parameters mean we precompute (approximately) one point
      * per bit. TBD: The combination 8, 4 is perfect for 160 bits; for other
      * bit lengths, other parameter combinations might provide better
      * efficiency.
      */
     blocksize = 8;
     w = 4;
     if (EC_window_bits_for_scalar_size(bits) > w) {
         /* let's not make the window too small ... */
         w = EC_window_bits_for_scalar_size(bits);
     }
 
     numblocks = (bits + blocksize - 1) / blocksize; /* max. number of blocks
                                                      * to use for wNAF
                                                      * splitting */
 
     pre_points_per_block = (size_t)1 << (w - 1);
     num = pre_points_per_block * numblocks; /* number of points to compute
                                              * and store */
 
     points = OPENSSL_malloc(sizeof(EC_POINT *) * (num + 1));
     if (!points) {
         ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, ERR_R_MALLOC_FAILURE);
         goto err;
     }
 
     var = points;
     var[num] = NULL;            /* pivot */
     for (i = 0; i < num; i++) {
         if ((var[i] = EC_POINT_new(group)) == NULL) {
             ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, ERR_R_MALLOC_FAILURE);
             goto err;
         }
     }
 
     if (!(tmp_point = EC_POINT_new(group)) || !(base = EC_POINT_new(group))) {
         ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, ERR_R_MALLOC_FAILURE);
         goto err;
     }
 
     if (!EC_POINT_copy(base, generator))
         goto err;
 
     /* do the precomputation */
     for (i = 0; i < numblocks; i++) {
         size_t j;
 
         if (!EC_POINT_dbl(group, tmp_point, base, ctx))
             goto err;
 
         if (!EC_POINT_copy(*var++, base))
             goto err;
 
         for (j = 1; j < pre_points_per_block; j++, var++) {
             /*
              * calculate odd multiples of the current base point
              */
             if (!EC_POINT_add(group, *var, tmp_point, *(var - 1), ctx))
                 goto err;
         }
 
         if (i < numblocks - 1) {
             /*
              * get the next base (multiply current one by 2^blocksize)
              */
             size_t k;
 
             if (blocksize <= 2) {
                 ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, ERR_R_INTERNAL_ERROR);
                 goto err;
             }
 
             if (!EC_POINT_dbl(group, base, tmp_point, ctx))
                 goto err;
             for (k = 2; k < blocksize; k++) {
                 if (!EC_POINT_dbl(group, base, base, ctx))
                     goto err;
             }
         }
     }
 
     if (!EC_POINTs_make_affine(group, num, points, ctx))
         goto err;
 
     pre_comp->group = group;
     pre_comp->blocksize = blocksize;
     pre_comp->numblocks = numblocks;
     pre_comp->w = w;
     pre_comp->points = points;
     points = NULL;
     pre_comp->num = num;
 
     if (!EC_EX_DATA_set_data(&group->extra_data, pre_comp,
                              ec_pre_comp_dup, ec_pre_comp_free,
                              ec_pre_comp_clear_free))
         goto err;
     pre_comp = NULL;
 
     ret = 1;
  err:
     if (ctx != NULL)
         BN_CTX_end(ctx);
     if (new_ctx != NULL)
         BN_CTX_free(new_ctx);
     if (pre_comp)
         ec_pre_comp_free(pre_comp);
     if (points) {
         EC_POINT **p;
 
         for (p = points; *p != NULL; p++)
             EC_POINT_free(*p);
         OPENSSL_free(points);
     }
     if (tmp_point)
         EC_POINT_free(tmp_point);
     if (base)
         EC_POINT_free(base);
     return ret;
 }
 
 int ec_wNAF_have_precompute_mult(const EC_GROUP *group)
 {
     if (EC_EX_DATA_get_data
         (group->extra_data, ec_pre_comp_dup, ec_pre_comp_free,
          ec_pre_comp_clear_free) != NULL)
         return 1;
     else
         return 0;
 }
Index: vendor-crypto/openssl/dist/crypto/ec/eck_prn.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/ec/eck_prn.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/ec/eck_prn.c	(revision 318897)
@@ -1,377 +1,377 @@
 /* crypto/ec/eck_prn.c */
 /*
  * Written by Nils Larsch for the OpenSSL project.
  */
 /* ====================================================================
  * Copyright (c) 1998-2005 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    openssl-core@openssl.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 /* ====================================================================
  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
  * Portions originally developed by SUN MICROSYSTEMS, INC., and
  * contributed to the OpenSSL project.
  */
 
 #include 
 #include "cryptlib.h"
 #include 
 #include 
 #include 
 
 #ifndef OPENSSL_NO_FP_API
 int ECPKParameters_print_fp(FILE *fp, const EC_GROUP *x, int off)
 {
     BIO *b;
     int ret;
 
     if ((b = BIO_new(BIO_s_file())) == NULL) {
         ECerr(EC_F_ECPKPARAMETERS_PRINT_FP, ERR_R_BUF_LIB);
         return (0);
     }
     BIO_set_fp(b, fp, BIO_NOCLOSE);
     ret = ECPKParameters_print(b, x, off);
     BIO_free(b);
     return (ret);
 }
 
 int EC_KEY_print_fp(FILE *fp, const EC_KEY *x, int off)
 {
     BIO *b;
     int ret;
 
     if ((b = BIO_new(BIO_s_file())) == NULL) {
         ECerr(EC_F_EC_KEY_PRINT_FP, ERR_R_BIO_LIB);
         return (0);
     }
     BIO_set_fp(b, fp, BIO_NOCLOSE);
     ret = EC_KEY_print(b, x, off);
     BIO_free(b);
     return (ret);
 }
 
 int ECParameters_print_fp(FILE *fp, const EC_KEY *x)
 {
     BIO *b;
     int ret;
 
     if ((b = BIO_new(BIO_s_file())) == NULL) {
         ECerr(EC_F_ECPARAMETERS_PRINT_FP, ERR_R_BIO_LIB);
         return (0);
     }
     BIO_set_fp(b, fp, BIO_NOCLOSE);
     ret = ECParameters_print(b, x);
     BIO_free(b);
     return (ret);
 }
 #endif
 
 int EC_KEY_print(BIO *bp, const EC_KEY *x, int off)
 {
     EVP_PKEY *pk;
     int ret;
     pk = EVP_PKEY_new();
     if (!pk || !EVP_PKEY_set1_EC_KEY(pk, (EC_KEY *)x))
         return 0;
     ret = EVP_PKEY_print_private(bp, pk, off, NULL);
     EVP_PKEY_free(pk);
     return ret;
 }
 
 int ECParameters_print(BIO *bp, const EC_KEY *x)
 {
     EVP_PKEY *pk;
     int ret;
     pk = EVP_PKEY_new();
     if (!pk || !EVP_PKEY_set1_EC_KEY(pk, (EC_KEY *)x))
         return 0;
     ret = EVP_PKEY_print_params(bp, pk, 4, NULL);
     EVP_PKEY_free(pk);
     return ret;
 }
 
 static int print_bin(BIO *fp, const char *str, const unsigned char *num,
                      size_t len, int off);
 
 int ECPKParameters_print(BIO *bp, const EC_GROUP *x, int off)
 {
     unsigned char *buffer = NULL;
     size_t buf_len = 0, i;
     int ret = 0, reason = ERR_R_BIO_LIB;
     BN_CTX *ctx = NULL;
     const EC_POINT *point = NULL;
     BIGNUM *p = NULL, *a = NULL, *b = NULL, *gen = NULL,
         *order = NULL, *cofactor = NULL;
     const unsigned char *seed;
     size_t seed_len = 0;
 
     static const char *gen_compressed = "Generator (compressed):";
     static const char *gen_uncompressed = "Generator (uncompressed):";
     static const char *gen_hybrid = "Generator (hybrid):";
 
     if (!x) {
         reason = ERR_R_PASSED_NULL_PARAMETER;
         goto err;
     }
 
     ctx = BN_CTX_new();
     if (ctx == NULL) {
         reason = ERR_R_MALLOC_FAILURE;
         goto err;
     }
 
     if (EC_GROUP_get_asn1_flag(x)) {
         /* the curve parameter are given by an asn1 OID */
         int nid;
         const char *nname;
 
         if (!BIO_indent(bp, off, 128))
             goto err;
 
         nid = EC_GROUP_get_curve_name(x);
         if (nid == 0)
             goto err;
 
         if (BIO_printf(bp, "ASN1 OID: %s", OBJ_nid2sn(nid)) <= 0)
             goto err;
         if (BIO_printf(bp, "\n") <= 0)
             goto err;
         nname = EC_curve_nid2nist(nid);
         if (nname) {
             if (!BIO_indent(bp, off, 128))
                 goto err;
             if (BIO_printf(bp, "NIST CURVE: %s\n", nname) <= 0)
                 goto err;
         }
     } else {
         /* explicit parameters */
         int is_char_two = 0;
         point_conversion_form_t form;
         int tmp_nid = EC_METHOD_get_field_type(EC_GROUP_method_of(x));
 
         if (tmp_nid == NID_X9_62_characteristic_two_field)
             is_char_two = 1;
 
         if ((p = BN_new()) == NULL || (a = BN_new()) == NULL ||
             (b = BN_new()) == NULL || (order = BN_new()) == NULL ||
             (cofactor = BN_new()) == NULL) {
             reason = ERR_R_MALLOC_FAILURE;
             goto err;
         }
 #ifndef OPENSSL_NO_EC2M
         if (is_char_two) {
             if (!EC_GROUP_get_curve_GF2m(x, p, a, b, ctx)) {
                 reason = ERR_R_EC_LIB;
                 goto err;
             }
         } else                  /* prime field */
 #endif
         {
             if (!EC_GROUP_get_curve_GFp(x, p, a, b, ctx)) {
                 reason = ERR_R_EC_LIB;
                 goto err;
             }
         }
 
         if ((point = EC_GROUP_get0_generator(x)) == NULL) {
             reason = ERR_R_EC_LIB;
             goto err;
         }
         if (!EC_GROUP_get_order(x, order, NULL) ||
             !EC_GROUP_get_cofactor(x, cofactor, NULL)) {
             reason = ERR_R_EC_LIB;
             goto err;
         }
 
         form = EC_GROUP_get_point_conversion_form(x);
 
         if ((gen = EC_POINT_point2bn(x, point, form, NULL, ctx)) == NULL) {
             reason = ERR_R_EC_LIB;
             goto err;
         }
 
         buf_len = (size_t)BN_num_bytes(p);
         if (buf_len < (i = (size_t)BN_num_bytes(a)))
             buf_len = i;
         if (buf_len < (i = (size_t)BN_num_bytes(b)))
             buf_len = i;
         if (buf_len < (i = (size_t)BN_num_bytes(gen)))
             buf_len = i;
         if (buf_len < (i = (size_t)BN_num_bytes(order)))
             buf_len = i;
         if (buf_len < (i = (size_t)BN_num_bytes(cofactor)))
             buf_len = i;
 
         if ((seed = EC_GROUP_get0_seed(x)) != NULL)
             seed_len = EC_GROUP_get_seed_len(x);
 
         buf_len += 10;
         if ((buffer = OPENSSL_malloc(buf_len)) == NULL) {
             reason = ERR_R_MALLOC_FAILURE;
             goto err;
         }
 
         if (!BIO_indent(bp, off, 128))
             goto err;
 
         /* print the 'short name' of the field type */
         if (BIO_printf(bp, "Field Type: %s\n", OBJ_nid2sn(tmp_nid))
             <= 0)
             goto err;
 
         if (is_char_two) {
             /* print the 'short name' of the base type OID */
             int basis_type = EC_GROUP_get_basis_type(x);
             if (basis_type == 0)
                 goto err;
 
             if (!BIO_indent(bp, off, 128))
                 goto err;
 
             if (BIO_printf(bp, "Basis Type: %s\n",
                            OBJ_nid2sn(basis_type)) <= 0)
                 goto err;
 
             /* print the polynomial */
             if ((p != NULL) && !ASN1_bn_print(bp, "Polynomial:", p, buffer,
                                               off))
                 goto err;
         } else {
             if ((p != NULL) && !ASN1_bn_print(bp, "Prime:", p, buffer, off))
                 goto err;
         }
         if ((a != NULL) && !ASN1_bn_print(bp, "A:   ", a, buffer, off))
             goto err;
         if ((b != NULL) && !ASN1_bn_print(bp, "B:   ", b, buffer, off))
             goto err;
         if (form == POINT_CONVERSION_COMPRESSED) {
             if ((gen != NULL) && !ASN1_bn_print(bp, gen_compressed, gen,
                                                 buffer, off))
                 goto err;
         } else if (form == POINT_CONVERSION_UNCOMPRESSED) {
             if ((gen != NULL) && !ASN1_bn_print(bp, gen_uncompressed, gen,
                                                 buffer, off))
                 goto err;
         } else {                /* form == POINT_CONVERSION_HYBRID */
 
             if ((gen != NULL) && !ASN1_bn_print(bp, gen_hybrid, gen,
                                                 buffer, off))
                 goto err;
         }
         if ((order != NULL) && !ASN1_bn_print(bp, "Order: ", order,
                                               buffer, off))
             goto err;
         if ((cofactor != NULL) && !ASN1_bn_print(bp, "Cofactor: ", cofactor,
                                                  buffer, off))
             goto err;
         if (seed && !print_bin(bp, "Seed:", seed, seed_len, off))
             goto err;
     }
     ret = 1;
  err:
     if (!ret)
         ECerr(EC_F_ECPKPARAMETERS_PRINT, reason);
     if (p)
         BN_free(p);
     if (a)
         BN_free(a);
     if (b)
         BN_free(b);
     if (gen)
         BN_free(gen);
     if (order)
         BN_free(order);
     if (cofactor)
         BN_free(cofactor);
     if (ctx)
         BN_CTX_free(ctx);
     if (buffer != NULL)
         OPENSSL_free(buffer);
     return (ret);
 }
 
 static int print_bin(BIO *fp, const char *name, const unsigned char *buf,
                      size_t len, int off)
 {
     size_t i;
-    char str[128];
+    char str[128 + 1 + 4];
 
     if (buf == NULL)
         return 1;
     if (off > 0) {
         if (off > 128)
             off = 128;
         memset(str, ' ', off);
         if (BIO_write(fp, str, off) <= 0)
             return 0;
     } else {
         off = 0;
     }
 
     if (BIO_printf(fp, "%s", name) <= 0)
         return 0;
 
     for (i = 0; i < len; i++) {
         if ((i % 15) == 0) {
             str[0] = '\n';
             memset(&(str[1]), ' ', off + 4);
             if (BIO_write(fp, str, off + 1 + 4) <= 0)
                 return 0;
         }
         if (BIO_printf(fp, "%02x%s", buf[i], ((i + 1) == len) ? "" : ":") <=
             0)
             return 0;
     }
     if (BIO_write(fp, "\n", 1) <= 0)
         return 0;
 
     return 1;
 }
Index: vendor-crypto/openssl/dist/crypto/engine/eng_cryptodev.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/engine/eng_cryptodev.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/engine/eng_cryptodev.c	(revision 318897)
@@ -1,1548 +1,1549 @@
 /*
  * Copyright (c) 2002 Bob Beck 
  * Copyright (c) 2002 Theo de Raadt
  * Copyright (c) 2002 Markus Friedl
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  *
  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
  */
 
 #include 
 #include 
 #include 
 #include 
 #include 
 
 #if (defined(__unix__) || defined(unix)) && !defined(USG) && \
         (defined(OpenBSD) || defined(__FreeBSD__))
 # include 
 # if (OpenBSD >= 200112) || ((__FreeBSD_version >= 470101 && __FreeBSD_version < 500000) || __FreeBSD_version >= 500041)
 #  define HAVE_CRYPTODEV
 # endif
 # if (OpenBSD >= 200110)
 #  define HAVE_SYSLOG_R
 # endif
 #endif
 
 #ifndef HAVE_CRYPTODEV
 
 void ENGINE_load_cryptodev(void)
 {
     /* This is a NOP on platforms without /dev/crypto */
     return;
 }
 
 #else
 
 # include 
 # include 
 # include 
 # include 
 # include 
 # include 
 # include 
 # include 
 # include 
 # include 
 # include 
 # include 
 # include 
 # include 
 # include 
 
 struct dev_crypto_state {
     struct session_op d_sess;
     int d_fd;
 # ifdef USE_CRYPTODEV_DIGESTS
     char dummy_mac_key[HASH_MAX_LEN];
     unsigned char digest_res[HASH_MAX_LEN];
     char *mac_data;
     int mac_len;
 # endif
 };
 
 static u_int32_t cryptodev_asymfeat = 0;
 
 static int get_asym_dev_crypto(void);
 static int open_dev_crypto(void);
 static int get_dev_crypto(void);
 static int get_cryptodev_ciphers(const int **cnids);
 # ifdef USE_CRYPTODEV_DIGESTS
 static int get_cryptodev_digests(const int **cnids);
 # endif
 static int cryptodev_usable_ciphers(const int **nids);
 static int cryptodev_usable_digests(const int **nids);
 static int cryptodev_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                             const unsigned char *in, size_t inl);
 static int cryptodev_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
                               const unsigned char *iv, int enc);
 static int cryptodev_cleanup(EVP_CIPHER_CTX *ctx);
 static int cryptodev_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
                                     const int **nids, int nid);
 static int cryptodev_engine_digests(ENGINE *e, const EVP_MD **digest,
                                     const int **nids, int nid);
 static int bn2crparam(const BIGNUM *a, struct crparam *crp);
 static int crparam2bn(struct crparam *crp, BIGNUM *a);
 static void zapparams(struct crypt_kop *kop);
 static int cryptodev_asym(struct crypt_kop *kop, int rlen, BIGNUM *r,
                           int slen, BIGNUM *s);
 
 static int cryptodev_bn_mod_exp(BIGNUM *r, const BIGNUM *a,
                                 const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
                                 BN_MONT_CTX *m_ctx);
 static int cryptodev_rsa_nocrt_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa,
                                        BN_CTX *ctx);
 static int cryptodev_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa,
                                  BN_CTX *ctx);
 static int cryptodev_dsa_bn_mod_exp(DSA *dsa, BIGNUM *r, BIGNUM *a,
                                     const BIGNUM *p, const BIGNUM *m,
                                     BN_CTX *ctx, BN_MONT_CTX *m_ctx);
 static int cryptodev_dsa_dsa_mod_exp(DSA *dsa, BIGNUM *t1, BIGNUM *g,
                                      BIGNUM *u1, BIGNUM *pub_key, BIGNUM *u2,
                                      BIGNUM *p, BN_CTX *ctx,
                                      BN_MONT_CTX *mont);
 static DSA_SIG *cryptodev_dsa_do_sign(const unsigned char *dgst, int dlen,
                                       DSA *dsa);
 static int cryptodev_dsa_verify(const unsigned char *dgst, int dgst_len,
                                 DSA_SIG *sig, DSA *dsa);
 static int cryptodev_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a,
                                 const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
                                 BN_MONT_CTX *m_ctx);
 static int cryptodev_dh_compute_key(unsigned char *key, const BIGNUM *pub_key,
                                     DH *dh);
 static int cryptodev_ctrl(ENGINE *e, int cmd, long i, void *p,
                           void (*f) (void));
 void ENGINE_load_cryptodev(void);
 
 static const ENGINE_CMD_DEFN cryptodev_defns[] = {
     {0, NULL, NULL, 0}
 };
 
 static struct {
     int id;
     int nid;
     int ivmax;
     int keylen;
 } ciphers[] = {
     {
         CRYPTO_ARC4, NID_rc4, 0, 16,
     },
     {
         CRYPTO_DES_CBC, NID_des_cbc, 8, 8,
     },
     {
         CRYPTO_3DES_CBC, NID_des_ede3_cbc, 8, 24,
     },
     {
         CRYPTO_AES_CBC, NID_aes_128_cbc, 16, 16,
     },
     {
         CRYPTO_AES_CBC, NID_aes_192_cbc, 16, 24,
     },
     {
         CRYPTO_AES_CBC, NID_aes_256_cbc, 16, 32,
     },
 # ifdef CRYPTO_AES_CTR
     {
         CRYPTO_AES_CTR, NID_aes_128_ctr, 14, 16,
     },
     {
         CRYPTO_AES_CTR, NID_aes_192_ctr, 14, 24,
     },
     {
         CRYPTO_AES_CTR, NID_aes_256_ctr, 14, 32,
     },
 # endif
     {
         CRYPTO_BLF_CBC, NID_bf_cbc, 8, 16,
     },
     {
         CRYPTO_CAST_CBC, NID_cast5_cbc, 8, 16,
     },
     {
         CRYPTO_SKIPJACK_CBC, NID_undef, 0, 0,
     },
     {
         0, NID_undef, 0, 0,
     },
 };
 
 # ifdef USE_CRYPTODEV_DIGESTS
 static struct {
     int id;
     int nid;
     int keylen;
 } digests[] = {
     {
         CRYPTO_MD5_HMAC, NID_hmacWithMD5, 16
     },
     {
         CRYPTO_SHA1_HMAC, NID_hmacWithSHA1, 20
     },
     {
         CRYPTO_RIPEMD160_HMAC, NID_ripemd160, 16
         /* ? */
     },
     {
         CRYPTO_MD5_KPDK, NID_undef, 0
     },
     {
         CRYPTO_SHA1_KPDK, NID_undef, 0
     },
     {
         CRYPTO_MD5, NID_md5, 16
     },
     {
         CRYPTO_SHA1, NID_sha1, 20
     },
     {
         0, NID_undef, 0
     },
 };
 # endif
 
 /*
  * Return a fd if /dev/crypto seems usable, 0 otherwise.
  */
 static int open_dev_crypto(void)
 {
     static int fd = -1;
 
     if (fd == -1) {
         if ((fd = open("/dev/crypto", O_RDWR, 0)) == -1)
             return (-1);
         /* close on exec */
         if (fcntl(fd, F_SETFD, 1) == -1) {
             close(fd);
             fd = -1;
             return (-1);
         }
     }
     return (fd);
 }
 
 static int get_dev_crypto(void)
 {
     int fd, retfd;
 
     if ((fd = open_dev_crypto()) == -1)
         return (-1);
 # ifndef CRIOGET_NOT_NEEDED
     if (ioctl(fd, CRIOGET, &retfd) == -1)
         return (-1);
 
     /* close on exec */
     if (fcntl(retfd, F_SETFD, 1) == -1) {
         close(retfd);
         return (-1);
     }
 # else
     retfd = fd;
 # endif
     return (retfd);
 }
 
 static void put_dev_crypto(int fd)
 {
 # ifndef CRIOGET_NOT_NEEDED
     close(fd);
 # endif
 }
 
 /* Caching version for asym operations */
 static int get_asym_dev_crypto(void)
 {
     static int fd = -1;
 
     if (fd == -1)
         fd = get_dev_crypto();
     return fd;
 }
 
 /*
  * Find out what ciphers /dev/crypto will let us have a session for.
  * XXX note, that some of these openssl doesn't deal with yet!
  * returning them here is harmless, as long as we return NULL
  * when asked for a handler in the cryptodev_engine_ciphers routine
  */
 static int get_cryptodev_ciphers(const int **cnids)
 {
     static int nids[CRYPTO_ALGORITHM_MAX];
     struct session_op sess;
     int fd, i, count = 0;
 
     if ((fd = get_dev_crypto()) < 0) {
         *cnids = NULL;
         return (0);
     }
     memset(&sess, 0, sizeof(sess));
     sess.key = (caddr_t) "123456789abcdefghijklmno";
 
     for (i = 0; ciphers[i].id && count < CRYPTO_ALGORITHM_MAX; i++) {
         if (ciphers[i].nid == NID_undef)
             continue;
         sess.cipher = ciphers[i].id;
         sess.keylen = ciphers[i].keylen;
         sess.mac = 0;
         if (ioctl(fd, CIOCGSESSION, &sess) != -1 &&
             ioctl(fd, CIOCFSESSION, &sess.ses) != -1)
             nids[count++] = ciphers[i].nid;
     }
     put_dev_crypto(fd);
 
     if (count > 0)
         *cnids = nids;
     else
         *cnids = NULL;
     return (count);
 }
 
 # ifdef USE_CRYPTODEV_DIGESTS
 /*
  * Find out what digests /dev/crypto will let us have a session for.
  * XXX note, that some of these openssl doesn't deal with yet!
  * returning them here is harmless, as long as we return NULL
  * when asked for a handler in the cryptodev_engine_digests routine
  */
 static int get_cryptodev_digests(const int **cnids)
 {
     static int nids[CRYPTO_ALGORITHM_MAX];
     struct session_op sess;
     int fd, i, count = 0;
 
     if ((fd = get_dev_crypto()) < 0) {
         *cnids = NULL;
         return (0);
     }
     memset(&sess, 0, sizeof(sess));
     sess.mackey = (caddr_t) "123456789abcdefghijklmno";
     for (i = 0; digests[i].id && count < CRYPTO_ALGORITHM_MAX; i++) {
         if (digests[i].nid == NID_undef)
             continue;
         sess.mac = digests[i].id;
         sess.mackeylen = digests[i].keylen;
         sess.cipher = 0;
         if (ioctl(fd, CIOCGSESSION, &sess) != -1 &&
             ioctl(fd, CIOCFSESSION, &sess.ses) != -1)
             nids[count++] = digests[i].nid;
     }
     put_dev_crypto(fd);
 
     if (count > 0)
         *cnids = nids;
     else
         *cnids = NULL;
     return (count);
 }
 # endif                         /* 0 */
 
 /*
  * Find the useable ciphers|digests from dev/crypto - this is the first
  * thing called by the engine init crud which determines what it
  * can use for ciphers from this engine. We want to return
  * only what we can do, anythine else is handled by software.
  *
  * If we can't initialize the device to do anything useful for
  * any reason, we want to return a NULL array, and 0 length,
  * which forces everything to be done is software. By putting
  * the initalization of the device in here, we ensure we can
  * use this engine as the default, and if for whatever reason
  * /dev/crypto won't do what we want it will just be done in
  * software
  *
  * This can (should) be greatly expanded to perhaps take into
  * account speed of the device, and what we want to do.
  * (although the disabling of particular alg's could be controlled
  * by the device driver with sysctl's.) - this is where we
  * want most of the decisions made about what we actually want
  * to use from /dev/crypto.
  */
 static int cryptodev_usable_ciphers(const int **nids)
 {
     return (get_cryptodev_ciphers(nids));
 }
 
 static int cryptodev_usable_digests(const int **nids)
 {
 # ifdef USE_CRYPTODEV_DIGESTS
     return (get_cryptodev_digests(nids));
 # else
     /*
      * XXXX just disable all digests for now, because it sucks.
      * we need a better way to decide this - i.e. I may not
      * want digests on slow cards like hifn on fast machines,
      * but might want them on slow or loaded machines, etc.
      * will also want them when using crypto cards that don't
      * suck moose gonads - would be nice to be able to decide something
      * as reasonable default without having hackery that's card dependent.
      * of course, the default should probably be just do everything,
      * with perhaps a sysctl to turn algoritms off (or have them off
      * by default) on cards that generally suck like the hifn.
      */
     *nids = NULL;
     return (0);
 # endif
 }
 
 static int
 cryptodev_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                  const unsigned char *in, size_t inl)
 {
     struct crypt_op cryp;
     struct dev_crypto_state *state = ctx->cipher_data;
     struct session_op *sess = &state->d_sess;
     const void *iiv;
     unsigned char save_iv[EVP_MAX_IV_LENGTH];
 
     if (state->d_fd < 0)
         return (0);
     if (!inl)
         return (1);
     if ((inl % ctx->cipher->block_size) != 0)
         return (0);
 
     memset(&cryp, 0, sizeof(cryp));
 
     cryp.ses = sess->ses;
     cryp.flags = 0;
     cryp.len = inl;
     cryp.src = (caddr_t) in;
     cryp.dst = (caddr_t) out;
     cryp.mac = 0;
 
     cryp.op = ctx->encrypt ? COP_ENCRYPT : COP_DECRYPT;
 
     if (ctx->cipher->iv_len) {
         cryp.iv = (caddr_t) ctx->iv;
         if (!ctx->encrypt) {
             iiv = in + inl - ctx->cipher->iv_len;
             memcpy(save_iv, iiv, ctx->cipher->iv_len);
         }
     } else
         cryp.iv = NULL;
 
     if (ioctl(state->d_fd, CIOCCRYPT, &cryp) == -1) {
         /*
          * XXX need better errror handling this can fail for a number of
          * different reasons.
          */
         return (0);
     }
 
     if (ctx->cipher->iv_len) {
         if (ctx->encrypt)
             iiv = out + inl - ctx->cipher->iv_len;
         else
             iiv = save_iv;
         memcpy(ctx->iv, iiv, ctx->cipher->iv_len);
     }
     return (1);
 }
 
 static int
 cryptodev_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
                    const unsigned char *iv, int enc)
 {
     struct dev_crypto_state *state = ctx->cipher_data;
     struct session_op *sess = &state->d_sess;
     int cipher = -1, i;
 
     for (i = 0; ciphers[i].id; i++)
         if (ctx->cipher->nid == ciphers[i].nid &&
             ctx->cipher->iv_len <= ciphers[i].ivmax &&
             ctx->key_len == ciphers[i].keylen) {
             cipher = ciphers[i].id;
             break;
         }
 
     if (!ciphers[i].id) {
         state->d_fd = -1;
         return (0);
     }
 
     memset(sess, 0, sizeof(struct session_op));
 
     if ((state->d_fd = get_dev_crypto()) < 0)
         return (0);
 
     sess->key = (caddr_t) key;
     sess->keylen = ctx->key_len;
     sess->cipher = cipher;
 
     if (ioctl(state->d_fd, CIOCGSESSION, sess) == -1) {
         put_dev_crypto(state->d_fd);
         state->d_fd = -1;
         return (0);
     }
     return (1);
 }
 
 /*
  * free anything we allocated earlier when initting a
  * session, and close the session.
  */
 static int cryptodev_cleanup(EVP_CIPHER_CTX *ctx)
 {
     int ret = 0;
     struct dev_crypto_state *state = ctx->cipher_data;
     struct session_op *sess = &state->d_sess;
 
     if (state->d_fd < 0)
         return (0);
 
     /*
      * XXX if this ioctl fails, someting's wrong. the invoker may have called
      * us with a bogus ctx, or we could have a device that for whatever
      * reason just doesn't want to play ball - it's not clear what's right
      * here - should this be an error? should it just increase a counter,
      * hmm. For right now, we return 0 - I don't believe that to be "right".
      * we could call the gorpy openssl lib error handlers that print messages
      * to users of the library. hmm..
      */
 
     if (ioctl(state->d_fd, CIOCFSESSION, &sess->ses) == -1) {
         ret = 0;
     } else {
         ret = 1;
     }
     put_dev_crypto(state->d_fd);
     state->d_fd = -1;
 
     return (ret);
 }
 
 /*
  * libcrypto EVP stuff - this is how we get wired to EVP so the engine
  * gets called when libcrypto requests a cipher NID.
  */
 
 /* RC4 */
 const EVP_CIPHER cryptodev_rc4 = {
     NID_rc4,
     1, 16, 0,
     EVP_CIPH_VARIABLE_LENGTH,
     cryptodev_init_key,
     cryptodev_cipher,
     cryptodev_cleanup,
     sizeof(struct dev_crypto_state),
     NULL,
     NULL,
     NULL
 };
 
 /* DES CBC EVP */
 const EVP_CIPHER cryptodev_des_cbc = {
     NID_des_cbc,
     8, 8, 8,
     EVP_CIPH_CBC_MODE,
     cryptodev_init_key,
     cryptodev_cipher,
     cryptodev_cleanup,
     sizeof(struct dev_crypto_state),
     EVP_CIPHER_set_asn1_iv,
     EVP_CIPHER_get_asn1_iv,
     NULL
 };
 
 /* 3DES CBC EVP */
 const EVP_CIPHER cryptodev_3des_cbc = {
     NID_des_ede3_cbc,
     8, 24, 8,
     EVP_CIPH_CBC_MODE,
     cryptodev_init_key,
     cryptodev_cipher,
     cryptodev_cleanup,
     sizeof(struct dev_crypto_state),
     EVP_CIPHER_set_asn1_iv,
     EVP_CIPHER_get_asn1_iv,
     NULL
 };
 
 const EVP_CIPHER cryptodev_bf_cbc = {
     NID_bf_cbc,
     8, 16, 8,
     EVP_CIPH_CBC_MODE,
     cryptodev_init_key,
     cryptodev_cipher,
     cryptodev_cleanup,
     sizeof(struct dev_crypto_state),
     EVP_CIPHER_set_asn1_iv,
     EVP_CIPHER_get_asn1_iv,
     NULL
 };
 
 const EVP_CIPHER cryptodev_cast_cbc = {
     NID_cast5_cbc,
     8, 16, 8,
     EVP_CIPH_CBC_MODE,
     cryptodev_init_key,
     cryptodev_cipher,
     cryptodev_cleanup,
     sizeof(struct dev_crypto_state),
     EVP_CIPHER_set_asn1_iv,
     EVP_CIPHER_get_asn1_iv,
     NULL
 };
 
 const EVP_CIPHER cryptodev_aes_cbc = {
     NID_aes_128_cbc,
     16, 16, 16,
     EVP_CIPH_CBC_MODE,
     cryptodev_init_key,
     cryptodev_cipher,
     cryptodev_cleanup,
     sizeof(struct dev_crypto_state),
     EVP_CIPHER_set_asn1_iv,
     EVP_CIPHER_get_asn1_iv,
     NULL
 };
 
 const EVP_CIPHER cryptodev_aes_192_cbc = {
     NID_aes_192_cbc,
     16, 24, 16,
     EVP_CIPH_CBC_MODE,
     cryptodev_init_key,
     cryptodev_cipher,
     cryptodev_cleanup,
     sizeof(struct dev_crypto_state),
     EVP_CIPHER_set_asn1_iv,
     EVP_CIPHER_get_asn1_iv,
     NULL
 };
 
 const EVP_CIPHER cryptodev_aes_256_cbc = {
     NID_aes_256_cbc,
     16, 32, 16,
     EVP_CIPH_CBC_MODE,
     cryptodev_init_key,
     cryptodev_cipher,
     cryptodev_cleanup,
     sizeof(struct dev_crypto_state),
     EVP_CIPHER_set_asn1_iv,
     EVP_CIPHER_get_asn1_iv,
     NULL
 };
 
 # ifdef CRYPTO_AES_CTR
 const EVP_CIPHER cryptodev_aes_ctr = {
     NID_aes_128_ctr,
     16, 16, 14,
     EVP_CIPH_CTR_MODE,
     cryptodev_init_key,
     cryptodev_cipher,
     cryptodev_cleanup,
     sizeof(struct dev_crypto_state),
     EVP_CIPHER_set_asn1_iv,
     EVP_CIPHER_get_asn1_iv,
     NULL
 };
 
 const EVP_CIPHER cryptodev_aes_ctr_192 = {
     NID_aes_192_ctr,
     16, 24, 14,
     EVP_CIPH_CTR_MODE,
     cryptodev_init_key,
     cryptodev_cipher,
     cryptodev_cleanup,
     sizeof(struct dev_crypto_state),
     EVP_CIPHER_set_asn1_iv,
     EVP_CIPHER_get_asn1_iv,
     NULL
 };
 
 const EVP_CIPHER cryptodev_aes_ctr_256 = {
     NID_aes_256_ctr,
     16, 32, 14,
     EVP_CIPH_CTR_MODE,
     cryptodev_init_key,
     cryptodev_cipher,
     cryptodev_cleanup,
     sizeof(struct dev_crypto_state),
     EVP_CIPHER_set_asn1_iv,
     EVP_CIPHER_get_asn1_iv,
     NULL
 };
 # endif
 /*
  * Registered by the ENGINE when used to find out how to deal with
  * a particular NID in the ENGINE. this says what we'll do at the
  * top level - note, that list is restricted by what we answer with
  */
 static int
 cryptodev_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher,
                          const int **nids, int nid)
 {
     if (!cipher)
         return (cryptodev_usable_ciphers(nids));
 
     switch (nid) {
     case NID_rc4:
         *cipher = &cryptodev_rc4;
         break;
     case NID_des_ede3_cbc:
         *cipher = &cryptodev_3des_cbc;
         break;
     case NID_des_cbc:
         *cipher = &cryptodev_des_cbc;
         break;
     case NID_bf_cbc:
         *cipher = &cryptodev_bf_cbc;
         break;
     case NID_cast5_cbc:
         *cipher = &cryptodev_cast_cbc;
         break;
     case NID_aes_128_cbc:
         *cipher = &cryptodev_aes_cbc;
         break;
     case NID_aes_192_cbc:
         *cipher = &cryptodev_aes_192_cbc;
         break;
     case NID_aes_256_cbc:
         *cipher = &cryptodev_aes_256_cbc;
         break;
 # ifdef CRYPTO_AES_CTR
     case NID_aes_128_ctr:
         *cipher = &cryptodev_aes_ctr;
         break;
     case NID_aes_192_ctr:
         *cipher = &cryptodev_aes_ctr_192;
         break;
     case NID_aes_256_ctr:
         *cipher = &cryptodev_aes_ctr_256;
         break;
 # endif
     default:
         *cipher = NULL;
         break;
     }
     return (*cipher != NULL);
 }
 
 # ifdef USE_CRYPTODEV_DIGESTS
 
 /* convert digest type to cryptodev */
 static int digest_nid_to_cryptodev(int nid)
 {
     int i;
 
     for (i = 0; digests[i].id; i++)
         if (digests[i].nid == nid)
             return (digests[i].id);
     return (0);
 }
 
 static int digest_key_length(int nid)
 {
     int i;
 
     for (i = 0; digests[i].id; i++)
         if (digests[i].nid == nid)
             return digests[i].keylen;
     return (0);
 }
 
 static int cryptodev_digest_init(EVP_MD_CTX *ctx)
 {
     struct dev_crypto_state *state = ctx->md_data;
     struct session_op *sess = &state->d_sess;
     int digest;
 
     if ((digest = digest_nid_to_cryptodev(ctx->digest->type)) == NID_undef) {
         printf("cryptodev_digest_init: Can't get digest \n");
         return (0);
     }
 
     memset(state, 0, sizeof(struct dev_crypto_state));
 
     if ((state->d_fd = get_dev_crypto()) < 0) {
         printf("cryptodev_digest_init: Can't get Dev \n");
         return (0);
     }
 
     sess->mackey = state->dummy_mac_key;
     sess->mackeylen = digest_key_length(ctx->digest->type);
     sess->mac = digest;
 
     if (ioctl(state->d_fd, CIOCGSESSION, sess) < 0) {
         put_dev_crypto(state->d_fd);
         state->d_fd = -1;
         printf("cryptodev_digest_init: Open session failed\n");
         return (0);
     }
 
     return (1);
 }
 
 static int cryptodev_digest_update(EVP_MD_CTX *ctx, const void *data,
                                    size_t count)
 {
     struct crypt_op cryp;
     struct dev_crypto_state *state = ctx->md_data;
     struct session_op *sess = &state->d_sess;
 
     if (!data || state->d_fd < 0) {
         printf("cryptodev_digest_update: illegal inputs \n");
         return (0);
     }
 
     if (!count) {
         return (0);
     }
 
     if (!(ctx->flags & EVP_MD_CTX_FLAG_ONESHOT)) {
         /* if application doesn't support one buffer */
-        state->mac_data =
+        char *mac_data =
             OPENSSL_realloc(state->mac_data, state->mac_len + count);
 
-        if (!state->mac_data) {
+        if (mac_data == NULL) {
             printf("cryptodev_digest_update: realloc failed\n");
             return (0);
         }
 
+        state->mac_data = mac_data;
         memcpy(state->mac_data + state->mac_len, data, count);
         state->mac_len += count;
 
         return (1);
     }
 
     memset(&cryp, 0, sizeof(cryp));
 
     cryp.ses = sess->ses;
     cryp.flags = 0;
     cryp.len = count;
     cryp.src = (caddr_t) data;
     cryp.dst = NULL;
     cryp.mac = (caddr_t) state->digest_res;
     if (ioctl(state->d_fd, CIOCCRYPT, &cryp) < 0) {
         printf("cryptodev_digest_update: digest failed\n");
         return (0);
     }
     return (1);
 }
 
 static int cryptodev_digest_final(EVP_MD_CTX *ctx, unsigned char *md)
 {
     struct crypt_op cryp;
     struct dev_crypto_state *state = ctx->md_data;
     struct session_op *sess = &state->d_sess;
 
     int ret = 1;
 
     if (!md || state->d_fd < 0) {
         printf("cryptodev_digest_final: illegal input\n");
         return (0);
     }
 
     if (!(ctx->flags & EVP_MD_CTX_FLAG_ONESHOT)) {
         /* if application doesn't support one buffer */
         memset(&cryp, 0, sizeof(cryp));
         cryp.ses = sess->ses;
         cryp.flags = 0;
         cryp.len = state->mac_len;
         cryp.src = state->mac_data;
         cryp.dst = NULL;
         cryp.mac = (caddr_t) md;
         if (ioctl(state->d_fd, CIOCCRYPT, &cryp) < 0) {
             printf("cryptodev_digest_final: digest failed\n");
             return (0);
         }
 
         return 1;
     }
 
     memcpy(md, state->digest_res, ctx->digest->md_size);
 
     return (ret);
 }
 
 static int cryptodev_digest_cleanup(EVP_MD_CTX *ctx)
 {
     int ret = 1;
     struct dev_crypto_state *state = ctx->md_data;
     struct session_op *sess = &state->d_sess;
 
     if (state == NULL)
         return 0;
 
     if (state->d_fd < 0) {
         printf("cryptodev_digest_cleanup: illegal input\n");
         return (0);
     }
 
     if (state->mac_data) {
         OPENSSL_free(state->mac_data);
         state->mac_data = NULL;
         state->mac_len = 0;
     }
 
     if (ioctl(state->d_fd, CIOCFSESSION, &sess->ses) < 0) {
         printf("cryptodev_digest_cleanup: failed to close session\n");
         ret = 0;
     } else {
         ret = 1;
     }
     put_dev_crypto(state->d_fd);
     state->d_fd = -1;
 
     return (ret);
 }
 
 static int cryptodev_digest_copy(EVP_MD_CTX *to, const EVP_MD_CTX *from)
 {
     struct dev_crypto_state *fstate = from->md_data;
     struct dev_crypto_state *dstate = to->md_data;
     struct session_op *sess;
     int digest;
 
     if (dstate == NULL || fstate == NULL)
         return 1;
 
     memcpy(dstate, fstate, sizeof(struct dev_crypto_state));
 
     sess = &dstate->d_sess;
 
     digest = digest_nid_to_cryptodev(to->digest->type);
 
     sess->mackey = dstate->dummy_mac_key;
     sess->mackeylen = digest_key_length(to->digest->type);
     sess->mac = digest;
 
     dstate->d_fd = get_dev_crypto();
 
     if (ioctl(dstate->d_fd, CIOCGSESSION, sess) < 0) {
         put_dev_crypto(dstate->d_fd);
         dstate->d_fd = -1;
         printf("cryptodev_digest_init: Open session failed\n");
         return (0);
     }
 
     dstate->mac_len = fstate->mac_len;
     if (fstate->mac_len != 0) {
         if (fstate->mac_data != NULL) {
             dstate->mac_data = OPENSSL_malloc(fstate->mac_len);
             if (dstate->mac_data == NULL) {
                 printf("cryptodev_digest_init: malloc failed\n");
                 return 0;
             }
             memcpy(dstate->mac_data, fstate->mac_data, fstate->mac_len);
         }
     }
 
     return 1;
 }
 
 const EVP_MD cryptodev_sha1 = {
     NID_sha1,
     NID_undef,
     SHA_DIGEST_LENGTH,
     EVP_MD_FLAG_ONESHOT,
     cryptodev_digest_init,
     cryptodev_digest_update,
     cryptodev_digest_final,
     cryptodev_digest_copy,
     cryptodev_digest_cleanup,
     EVP_PKEY_NULL_method,
     SHA_CBLOCK,
     sizeof(struct dev_crypto_state),
 };
 
 const EVP_MD cryptodev_md5 = {
     NID_md5,
     NID_undef,
     16 /* MD5_DIGEST_LENGTH */ ,
     EVP_MD_FLAG_ONESHOT,
     cryptodev_digest_init,
     cryptodev_digest_update,
     cryptodev_digest_final,
     cryptodev_digest_copy,
     cryptodev_digest_cleanup,
     EVP_PKEY_NULL_method,
     64 /* MD5_CBLOCK */ ,
     sizeof(struct dev_crypto_state),
 };
 
 # endif                         /* USE_CRYPTODEV_DIGESTS */
 
 static int
 cryptodev_engine_digests(ENGINE *e, const EVP_MD **digest,
                          const int **nids, int nid)
 {
     if (!digest)
         return (cryptodev_usable_digests(nids));
 
     switch (nid) {
 # ifdef USE_CRYPTODEV_DIGESTS
     case NID_md5:
         *digest = &cryptodev_md5;
         break;
     case NID_sha1:
         *digest = &cryptodev_sha1;
         break;
     default:
 # endif                         /* USE_CRYPTODEV_DIGESTS */
         *digest = NULL;
         break;
     }
     return (*digest != NULL);
 }
 
 /*
  * Convert a BIGNUM to the representation that /dev/crypto needs.
  * Upon completion of use, the caller is responsible for freeing
  * crp->crp_p.
  */
 static int bn2crparam(const BIGNUM *a, struct crparam *crp)
 {
     int i, j, k;
     ssize_t bytes, bits;
     u_char *b;
 
     crp->crp_p = NULL;
     crp->crp_nbits = 0;
 
     bits = BN_num_bits(a);
     bytes = (bits + 7) / 8;
 
     b = malloc(bytes);
     if (b == NULL)
         return (1);
     memset(b, 0, bytes);
 
     crp->crp_p = (caddr_t) b;
     crp->crp_nbits = bits;
 
     for (i = 0, j = 0; i < a->top; i++) {
         for (k = 0; k < BN_BITS2 / 8; k++) {
             if ((j + k) >= bytes)
                 return (0);
             b[j + k] = a->d[i] >> (k * 8);
         }
         j += BN_BITS2 / 8;
     }
     return (0);
 }
 
 /* Convert a /dev/crypto parameter to a BIGNUM */
 static int crparam2bn(struct crparam *crp, BIGNUM *a)
 {
     u_int8_t *pd;
     int i, bytes;
 
     bytes = (crp->crp_nbits + 7) / 8;
 
     if (bytes == 0)
         return (-1);
 
     if ((pd = (u_int8_t *) malloc(bytes)) == NULL)
         return (-1);
 
     for (i = 0; i < bytes; i++)
         pd[i] = crp->crp_p[bytes - i - 1];
 
     BN_bin2bn(pd, bytes, a);
     free(pd);
 
     return (0);
 }
 
 static void zapparams(struct crypt_kop *kop)
 {
     int i;
 
     for (i = 0; i < kop->crk_iparams + kop->crk_oparams; i++) {
         OPENSSL_free(kop->crk_param[i].crp_p);
         kop->crk_param[i].crp_p = NULL;
         kop->crk_param[i].crp_nbits = 0;
     }
 }
 
 static int
 cryptodev_asym(struct crypt_kop *kop, int rlen, BIGNUM *r, int slen,
                BIGNUM *s)
 {
     int fd, ret = -1;
 
     if ((fd = get_asym_dev_crypto()) < 0)
         return ret;
 
     if (r) {
         kop->crk_param[kop->crk_iparams].crp_p = OPENSSL_malloc(rlen);
         if (kop->crk_param[kop->crk_iparams].crp_p == NULL)
             return ret;
         memset(kop->crk_param[kop->crk_iparams].crp_p, 0, (size_t)rlen);
         kop->crk_param[kop->crk_iparams].crp_nbits = rlen * 8;
         kop->crk_oparams++;
     }
     if (s) {
         kop->crk_param[kop->crk_iparams + 1].crp_p = OPENSSL_malloc(slen);
         /* No need to free the kop->crk_iparams parameter if it was allocated,
          * callers of this routine have to free allocated parameters through
          * zapparams both in case of success and failure
          */
         if (kop->crk_param[kop->crk_iparams+1].crp_p == NULL)
             return ret;
         memset(kop->crk_param[kop->crk_iparams + 1].crp_p, 0, (size_t)slen);
         kop->crk_param[kop->crk_iparams + 1].crp_nbits = slen * 8;
         kop->crk_oparams++;
     }
 
     if (ioctl(fd, CIOCKEY, kop) == 0) {
         if (r)
             crparam2bn(&kop->crk_param[kop->crk_iparams], r);
         if (s)
             crparam2bn(&kop->crk_param[kop->crk_iparams + 1], s);
         ret = 0;
     }
 
     return ret;
 }
 
 static int
 cryptodev_bn_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
                      const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
 {
     struct crypt_kop kop;
     int ret = 1;
 
     /*
      * Currently, we know we can do mod exp iff we can do any asymmetric
      * operations at all.
      */
     if (cryptodev_asymfeat == 0) {
         ret = BN_mod_exp(r, a, p, m, ctx);
         return (ret);
     }
 
     memset(&kop, 0, sizeof kop);
     kop.crk_op = CRK_MOD_EXP;
 
     /* inputs: a^p % m */
     if (bn2crparam(a, &kop.crk_param[0]))
         goto err;
     if (bn2crparam(p, &kop.crk_param[1]))
         goto err;
     if (bn2crparam(m, &kop.crk_param[2]))
         goto err;
     kop.crk_iparams = 3;
 
     if (cryptodev_asym(&kop, BN_num_bytes(m), r, 0, NULL)) {
         const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
         printf("OCF asym process failed, Running in software\n");
         ret = meth->bn_mod_exp(r, a, p, m, ctx, in_mont);
 
     } else if (ECANCELED == kop.crk_status) {
         const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
         printf("OCF hardware operation cancelled. Running in Software\n");
         ret = meth->bn_mod_exp(r, a, p, m, ctx, in_mont);
     }
     /* else cryptodev operation worked ok ==> ret = 1 */
 
  err:
     zapparams(&kop);
     return (ret);
 }
 
 static int
 cryptodev_rsa_nocrt_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa,
                             BN_CTX *ctx)
 {
     int r;
     ctx = BN_CTX_new();
     r = cryptodev_bn_mod_exp(r0, I, rsa->d, rsa->n, ctx, NULL);
     BN_CTX_free(ctx);
     return (r);
 }
 
 static int
 cryptodev_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
 {
     struct crypt_kop kop;
     int ret = 1;
 
     if (!rsa->p || !rsa->q || !rsa->dmp1 || !rsa->dmq1 || !rsa->iqmp) {
         /* XXX 0 means failure?? */
         return (0);
     }
 
     memset(&kop, 0, sizeof kop);
     kop.crk_op = CRK_MOD_EXP_CRT;
     /* inputs: rsa->p rsa->q I rsa->dmp1 rsa->dmq1 rsa->iqmp */
     if (bn2crparam(rsa->p, &kop.crk_param[0]))
         goto err;
     if (bn2crparam(rsa->q, &kop.crk_param[1]))
         goto err;
     if (bn2crparam(I, &kop.crk_param[2]))
         goto err;
     if (bn2crparam(rsa->dmp1, &kop.crk_param[3]))
         goto err;
     if (bn2crparam(rsa->dmq1, &kop.crk_param[4]))
         goto err;
     if (bn2crparam(rsa->iqmp, &kop.crk_param[5]))
         goto err;
     kop.crk_iparams = 6;
 
     if (cryptodev_asym(&kop, BN_num_bytes(rsa->n), r0, 0, NULL)) {
         const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
         printf("OCF asym process failed, running in Software\n");
         ret = (*meth->rsa_mod_exp) (r0, I, rsa, ctx);
 
     } else if (ECANCELED == kop.crk_status) {
         const RSA_METHOD *meth = RSA_PKCS1_SSLeay();
         printf("OCF hardware operation cancelled. Running in Software\n");
         ret = (*meth->rsa_mod_exp) (r0, I, rsa, ctx);
     }
     /* else cryptodev operation worked ok ==> ret = 1 */
 
  err:
     zapparams(&kop);
     return (ret);
 }
 
 static RSA_METHOD cryptodev_rsa = {
     "cryptodev RSA method",
     NULL,                       /* rsa_pub_enc */
     NULL,                       /* rsa_pub_dec */
     NULL,                       /* rsa_priv_enc */
     NULL,                       /* rsa_priv_dec */
     NULL,
     NULL,
     NULL,                       /* init */
     NULL,                       /* finish */
     0,                          /* flags */
     NULL,                       /* app_data */
     NULL,                       /* rsa_sign */
     NULL                        /* rsa_verify */
 };
 
 static int
 cryptodev_dsa_bn_mod_exp(DSA *dsa, BIGNUM *r, BIGNUM *a, const BIGNUM *p,
                          const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx)
 {
     return (cryptodev_bn_mod_exp(r, a, p, m, ctx, m_ctx));
 }
 
 static int
 cryptodev_dsa_dsa_mod_exp(DSA *dsa, BIGNUM *t1, BIGNUM *g,
                           BIGNUM *u1, BIGNUM *pub_key, BIGNUM *u2, BIGNUM *p,
                           BN_CTX *ctx, BN_MONT_CTX *mont)
 {
     BIGNUM t2;
     int ret = 0;
 
     BN_init(&t2);
 
     /* v = ( g^u1 * y^u2 mod p ) mod q */
     /* let t1 = g ^ u1 mod p */
     ret = 0;
 
     if (!dsa->meth->bn_mod_exp(dsa, t1, dsa->g, u1, dsa->p, ctx, mont))
         goto err;
 
     /* let t2 = y ^ u2 mod p */
     if (!dsa->meth->bn_mod_exp(dsa, &t2, dsa->pub_key, u2, dsa->p, ctx, mont))
         goto err;
     /* let u1 = t1 * t2 mod p */
     if (!BN_mod_mul(u1, t1, &t2, dsa->p, ctx))
         goto err;
 
     BN_copy(t1, u1);
 
     ret = 1;
  err:
     BN_free(&t2);
     return (ret);
 }
 
 static DSA_SIG *cryptodev_dsa_do_sign(const unsigned char *dgst, int dlen,
                                       DSA *dsa)
 {
     struct crypt_kop kop;
     BIGNUM *r = NULL, *s = NULL;
     DSA_SIG *dsaret = NULL;
 
     if ((r = BN_new()) == NULL)
         goto err;
     if ((s = BN_new()) == NULL) {
         BN_free(r);
         goto err;
     }
 
     memset(&kop, 0, sizeof kop);
     kop.crk_op = CRK_DSA_SIGN;
 
     /* inputs: dgst dsa->p dsa->q dsa->g dsa->priv_key */
     kop.crk_param[0].crp_p = (caddr_t) dgst;
     kop.crk_param[0].crp_nbits = dlen * 8;
     if (bn2crparam(dsa->p, &kop.crk_param[1]))
         goto err;
     if (bn2crparam(dsa->q, &kop.crk_param[2]))
         goto err;
     if (bn2crparam(dsa->g, &kop.crk_param[3]))
         goto err;
     if (bn2crparam(dsa->priv_key, &kop.crk_param[4]))
         goto err;
     kop.crk_iparams = 5;
 
     if (cryptodev_asym(&kop, BN_num_bytes(dsa->q), r,
                        BN_num_bytes(dsa->q), s) == 0) {
         dsaret = DSA_SIG_new();
         if (dsaret == NULL)
             goto err;
         dsaret->r = r;
         dsaret->s = s;
         r = s = NULL;
     } else {
         const DSA_METHOD *meth = DSA_OpenSSL();
         dsaret = (meth->dsa_do_sign) (dgst, dlen, dsa);
     }
  err:
     BN_free(r);
     BN_free(s);
     kop.crk_param[0].crp_p = NULL;
     zapparams(&kop);
     return (dsaret);
 }
 
 static int
 cryptodev_dsa_verify(const unsigned char *dgst, int dlen,
                      DSA_SIG *sig, DSA *dsa)
 {
     struct crypt_kop kop;
     int dsaret = 1;
 
     memset(&kop, 0, sizeof kop);
     kop.crk_op = CRK_DSA_VERIFY;
 
     /* inputs: dgst dsa->p dsa->q dsa->g dsa->pub_key sig->r sig->s */
     kop.crk_param[0].crp_p = (caddr_t) dgst;
     kop.crk_param[0].crp_nbits = dlen * 8;
     if (bn2crparam(dsa->p, &kop.crk_param[1]))
         goto err;
     if (bn2crparam(dsa->q, &kop.crk_param[2]))
         goto err;
     if (bn2crparam(dsa->g, &kop.crk_param[3]))
         goto err;
     if (bn2crparam(dsa->pub_key, &kop.crk_param[4]))
         goto err;
     if (bn2crparam(sig->r, &kop.crk_param[5]))
         goto err;
     if (bn2crparam(sig->s, &kop.crk_param[6]))
         goto err;
     kop.crk_iparams = 7;
 
     if (cryptodev_asym(&kop, 0, NULL, 0, NULL) == 0) {
         /*
          * OCF success value is 0, if not zero, change dsaret to fail
          */
         if (0 != kop.crk_status)
             dsaret = 0;
     } else {
         const DSA_METHOD *meth = DSA_OpenSSL();
 
         dsaret = (meth->dsa_do_verify) (dgst, dlen, sig, dsa);
     }
  err:
     kop.crk_param[0].crp_p = NULL;
     zapparams(&kop);
     return (dsaret);
 }
 
 static DSA_METHOD cryptodev_dsa = {
     "cryptodev DSA method",
     NULL,
     NULL,                       /* dsa_sign_setup */
     NULL,
     NULL,                       /* dsa_mod_exp */
     NULL,
     NULL,                       /* init */
     NULL,                       /* finish */
     0,                          /* flags */
     NULL                        /* app_data */
 };
 
 static int
 cryptodev_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a,
                      const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx,
                      BN_MONT_CTX *m_ctx)
 {
     return (cryptodev_bn_mod_exp(r, a, p, m, ctx, m_ctx));
 }
 
 static int
 cryptodev_dh_compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh)
 {
     struct crypt_kop kop;
     int dhret = 1;
     int fd, keylen;
 
     if ((fd = get_asym_dev_crypto()) < 0) {
         const DH_METHOD *meth = DH_OpenSSL();
 
         return ((meth->compute_key) (key, pub_key, dh));
     }
 
     keylen = BN_num_bits(dh->p);
 
     memset(&kop, 0, sizeof kop);
     kop.crk_op = CRK_DH_COMPUTE_KEY;
 
     /* inputs: dh->priv_key pub_key dh->p key */
     if (bn2crparam(dh->priv_key, &kop.crk_param[0]))
         goto err;
     if (bn2crparam(pub_key, &kop.crk_param[1]))
         goto err;
     if (bn2crparam(dh->p, &kop.crk_param[2]))
         goto err;
     kop.crk_iparams = 3;
 
     kop.crk_param[3].crp_p = (caddr_t) key;
     kop.crk_param[3].crp_nbits = keylen * 8;
     kop.crk_oparams = 1;
 
     if (ioctl(fd, CIOCKEY, &kop) == -1) {
         const DH_METHOD *meth = DH_OpenSSL();
 
         dhret = (meth->compute_key) (key, pub_key, dh);
     }
  err:
     kop.crk_param[3].crp_p = NULL;
     zapparams(&kop);
     return (dhret);
 }
 
 static DH_METHOD cryptodev_dh = {
     "cryptodev DH method",
     NULL,                       /* cryptodev_dh_generate_key */
     NULL,
     NULL,
     NULL,
     NULL,
     0,                          /* flags */
     NULL                        /* app_data */
 };
 
 /*
  * ctrl right now is just a wrapper that doesn't do much
  * but I expect we'll want some options soon.
  */
 static int
 cryptodev_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void))
 {
 # ifdef HAVE_SYSLOG_R
     struct syslog_data sd = SYSLOG_DATA_INIT;
 # endif
 
     switch (cmd) {
     default:
 # ifdef HAVE_SYSLOG_R
         syslog_r(LOG_ERR, &sd, "cryptodev_ctrl: unknown command %d", cmd);
 # else
         syslog(LOG_ERR, "cryptodev_ctrl: unknown command %d", cmd);
 # endif
         break;
     }
     return (1);
 }
 
 void ENGINE_load_cryptodev(void)
 {
     ENGINE *engine = ENGINE_new();
     int fd;
 
     if (engine == NULL)
         return;
     if ((fd = get_dev_crypto()) < 0) {
         ENGINE_free(engine);
         return;
     }
 
     /*
      * find out what asymmetric crypto algorithms we support
      */
     if (ioctl(fd, CIOCASYMFEAT, &cryptodev_asymfeat) == -1) {
         put_dev_crypto(fd);
         ENGINE_free(engine);
         return;
     }
     put_dev_crypto(fd);
 
     if (!ENGINE_set_id(engine, "cryptodev") ||
         !ENGINE_set_name(engine, "BSD cryptodev engine") ||
         !ENGINE_set_ciphers(engine, cryptodev_engine_ciphers) ||
         !ENGINE_set_digests(engine, cryptodev_engine_digests) ||
         !ENGINE_set_ctrl_function(engine, cryptodev_ctrl) ||
         !ENGINE_set_cmd_defns(engine, cryptodev_defns)) {
         ENGINE_free(engine);
         return;
     }
 
     if (ENGINE_set_RSA(engine, &cryptodev_rsa)) {
         const RSA_METHOD *rsa_meth = RSA_PKCS1_SSLeay();
 
         cryptodev_rsa.bn_mod_exp = rsa_meth->bn_mod_exp;
         cryptodev_rsa.rsa_mod_exp = rsa_meth->rsa_mod_exp;
         cryptodev_rsa.rsa_pub_enc = rsa_meth->rsa_pub_enc;
         cryptodev_rsa.rsa_pub_dec = rsa_meth->rsa_pub_dec;
         cryptodev_rsa.rsa_priv_enc = rsa_meth->rsa_priv_enc;
         cryptodev_rsa.rsa_priv_dec = rsa_meth->rsa_priv_dec;
         if (cryptodev_asymfeat & CRF_MOD_EXP) {
             cryptodev_rsa.bn_mod_exp = cryptodev_bn_mod_exp;
             if (cryptodev_asymfeat & CRF_MOD_EXP_CRT)
                 cryptodev_rsa.rsa_mod_exp = cryptodev_rsa_mod_exp;
             else
                 cryptodev_rsa.rsa_mod_exp = cryptodev_rsa_nocrt_mod_exp;
         }
     }
 
     if (ENGINE_set_DSA(engine, &cryptodev_dsa)) {
         const DSA_METHOD *meth = DSA_OpenSSL();
 
         memcpy(&cryptodev_dsa, meth, sizeof(DSA_METHOD));
         if (cryptodev_asymfeat & CRF_DSA_SIGN)
             cryptodev_dsa.dsa_do_sign = cryptodev_dsa_do_sign;
         if (cryptodev_asymfeat & CRF_MOD_EXP) {
             cryptodev_dsa.bn_mod_exp = cryptodev_dsa_bn_mod_exp;
             cryptodev_dsa.dsa_mod_exp = cryptodev_dsa_dsa_mod_exp;
         }
         if (cryptodev_asymfeat & CRF_DSA_VERIFY)
             cryptodev_dsa.dsa_do_verify = cryptodev_dsa_verify;
     }
 
     if (ENGINE_set_DH(engine, &cryptodev_dh)) {
         const DH_METHOD *dh_meth = DH_OpenSSL();
 
         cryptodev_dh.generate_key = dh_meth->generate_key;
         cryptodev_dh.compute_key = dh_meth->compute_key;
         cryptodev_dh.bn_mod_exp = dh_meth->bn_mod_exp;
         if (cryptodev_asymfeat & CRF_MOD_EXP) {
             cryptodev_dh.bn_mod_exp = cryptodev_mod_exp_dh;
             if (cryptodev_asymfeat & CRF_DH_COMPUTE_KEY)
                 cryptodev_dh.compute_key = cryptodev_dh_compute_key;
         }
     }
 
     ENGINE_add(engine);
     ENGINE_free(engine);
     ERR_clear_error();
 }
 
 #endif                          /* HAVE_CRYPTODEV */
Index: vendor-crypto/openssl/dist/crypto/err/err.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/err/err.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/err/err.c	(revision 318897)
@@ -1,1148 +1,1149 @@
 /* crypto/err/err.c */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 /* ====================================================================
  * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    openssl-core@openssl.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #include 
 #include 
 #include 
 #include "cryptlib.h"
 #include 
 #include 
 #include 
 #include 
 #include 
 
 DECLARE_LHASH_OF(ERR_STRING_DATA);
 DECLARE_LHASH_OF(ERR_STATE);
 
 static void err_load_strings(int lib, ERR_STRING_DATA *str);
 
 static void ERR_STATE_free(ERR_STATE *s);
 #ifndef OPENSSL_NO_ERR
 static ERR_STRING_DATA ERR_str_libraries[] = {
     {ERR_PACK(ERR_LIB_NONE, 0, 0), "unknown library"},
     {ERR_PACK(ERR_LIB_SYS, 0, 0), "system library"},
     {ERR_PACK(ERR_LIB_BN, 0, 0), "bignum routines"},
     {ERR_PACK(ERR_LIB_RSA, 0, 0), "rsa routines"},
     {ERR_PACK(ERR_LIB_DH, 0, 0), "Diffie-Hellman routines"},
     {ERR_PACK(ERR_LIB_EVP, 0, 0), "digital envelope routines"},
     {ERR_PACK(ERR_LIB_BUF, 0, 0), "memory buffer routines"},
     {ERR_PACK(ERR_LIB_OBJ, 0, 0), "object identifier routines"},
     {ERR_PACK(ERR_LIB_PEM, 0, 0), "PEM routines"},
     {ERR_PACK(ERR_LIB_DSA, 0, 0), "dsa routines"},
     {ERR_PACK(ERR_LIB_X509, 0, 0), "x509 certificate routines"},
     {ERR_PACK(ERR_LIB_ASN1, 0, 0), "asn1 encoding routines"},
     {ERR_PACK(ERR_LIB_CONF, 0, 0), "configuration file routines"},
     {ERR_PACK(ERR_LIB_CRYPTO, 0, 0), "common libcrypto routines"},
     {ERR_PACK(ERR_LIB_EC, 0, 0), "elliptic curve routines"},
     {ERR_PACK(ERR_LIB_SSL, 0, 0), "SSL routines"},
     {ERR_PACK(ERR_LIB_BIO, 0, 0), "BIO routines"},
     {ERR_PACK(ERR_LIB_PKCS7, 0, 0), "PKCS7 routines"},
     {ERR_PACK(ERR_LIB_X509V3, 0, 0), "X509 V3 routines"},
     {ERR_PACK(ERR_LIB_PKCS12, 0, 0), "PKCS12 routines"},
     {ERR_PACK(ERR_LIB_RAND, 0, 0), "random number generator"},
     {ERR_PACK(ERR_LIB_DSO, 0, 0), "DSO support routines"},
     {ERR_PACK(ERR_LIB_TS, 0, 0), "time stamp routines"},
     {ERR_PACK(ERR_LIB_ENGINE, 0, 0), "engine routines"},
     {ERR_PACK(ERR_LIB_OCSP, 0, 0), "OCSP routines"},
     {ERR_PACK(ERR_LIB_FIPS, 0, 0), "FIPS routines"},
     {ERR_PACK(ERR_LIB_CMS, 0, 0), "CMS routines"},
     {ERR_PACK(ERR_LIB_HMAC, 0, 0), "HMAC routines"},
     {0, NULL},
 };
 
 static ERR_STRING_DATA ERR_str_functs[] = {
     {ERR_PACK(0, SYS_F_FOPEN, 0), "fopen"},
     {ERR_PACK(0, SYS_F_CONNECT, 0), "connect"},
     {ERR_PACK(0, SYS_F_GETSERVBYNAME, 0), "getservbyname"},
     {ERR_PACK(0, SYS_F_SOCKET, 0), "socket"},
     {ERR_PACK(0, SYS_F_IOCTLSOCKET, 0), "ioctlsocket"},
     {ERR_PACK(0, SYS_F_BIND, 0), "bind"},
     {ERR_PACK(0, SYS_F_LISTEN, 0), "listen"},
     {ERR_PACK(0, SYS_F_ACCEPT, 0), "accept"},
 # ifdef OPENSSL_SYS_WINDOWS
     {ERR_PACK(0, SYS_F_WSASTARTUP, 0), "WSAstartup"},
 # endif
     {ERR_PACK(0, SYS_F_OPENDIR, 0), "opendir"},
     {ERR_PACK(0, SYS_F_FREAD, 0), "fread"},
+    {ERR_PACK(0, SYS_F_FFLUSH, 0), "fflush"},
     {0, NULL},
 };
 
 static ERR_STRING_DATA ERR_str_reasons[] = {
     {ERR_R_SYS_LIB, "system lib"},
     {ERR_R_BN_LIB, "BN lib"},
     {ERR_R_RSA_LIB, "RSA lib"},
     {ERR_R_DH_LIB, "DH lib"},
     {ERR_R_EVP_LIB, "EVP lib"},
     {ERR_R_BUF_LIB, "BUF lib"},
     {ERR_R_OBJ_LIB, "OBJ lib"},
     {ERR_R_PEM_LIB, "PEM lib"},
     {ERR_R_DSA_LIB, "DSA lib"},
     {ERR_R_X509_LIB, "X509 lib"},
     {ERR_R_ASN1_LIB, "ASN1 lib"},
     {ERR_R_CONF_LIB, "CONF lib"},
     {ERR_R_CRYPTO_LIB, "CRYPTO lib"},
     {ERR_R_EC_LIB, "EC lib"},
     {ERR_R_SSL_LIB, "SSL lib"},
     {ERR_R_BIO_LIB, "BIO lib"},
     {ERR_R_PKCS7_LIB, "PKCS7 lib"},
     {ERR_R_X509V3_LIB, "X509V3 lib"},
     {ERR_R_PKCS12_LIB, "PKCS12 lib"},
     {ERR_R_RAND_LIB, "RAND lib"},
     {ERR_R_DSO_LIB, "DSO lib"},
     {ERR_R_ENGINE_LIB, "ENGINE lib"},
     {ERR_R_OCSP_LIB, "OCSP lib"},
     {ERR_R_TS_LIB, "TS lib"},
 
     {ERR_R_NESTED_ASN1_ERROR, "nested asn1 error"},
     {ERR_R_BAD_ASN1_OBJECT_HEADER, "bad asn1 object header"},
     {ERR_R_BAD_GET_ASN1_OBJECT_CALL, "bad get asn1 object call"},
     {ERR_R_EXPECTING_AN_ASN1_SEQUENCE, "expecting an asn1 sequence"},
     {ERR_R_ASN1_LENGTH_MISMATCH, "asn1 length mismatch"},
     {ERR_R_MISSING_ASN1_EOS, "missing asn1 eos"},
 
     {ERR_R_FATAL, "fatal"},
     {ERR_R_MALLOC_FAILURE, "malloc failure"},
     {ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED,
      "called a function you should not call"},
     {ERR_R_PASSED_NULL_PARAMETER, "passed a null parameter"},
     {ERR_R_INTERNAL_ERROR, "internal error"},
     {ERR_R_DISABLED, "called a function that was disabled at compile-time"},
 
     {0, NULL},
 };
 #endif
 
 /* Define the predeclared (but externally opaque) "ERR_FNS" type */
 struct st_ERR_FNS {
     /* Works on the "error_hash" string table */
     LHASH_OF(ERR_STRING_DATA) *(*cb_err_get) (int create);
     void (*cb_err_del) (void);
     ERR_STRING_DATA *(*cb_err_get_item) (const ERR_STRING_DATA *);
     ERR_STRING_DATA *(*cb_err_set_item) (ERR_STRING_DATA *);
     ERR_STRING_DATA *(*cb_err_del_item) (ERR_STRING_DATA *);
     /* Works on the "thread_hash" error-state table */
     LHASH_OF(ERR_STATE) *(*cb_thread_get) (int create);
     void (*cb_thread_release) (LHASH_OF(ERR_STATE) **hash);
     ERR_STATE *(*cb_thread_get_item) (const ERR_STATE *);
     ERR_STATE *(*cb_thread_set_item) (ERR_STATE *);
     void (*cb_thread_del_item) (const ERR_STATE *);
     /* Returns the next available error "library" numbers */
     int (*cb_get_next_lib) (void);
 };
 
 /* Predeclarations of the "err_defaults" functions */
 static LHASH_OF(ERR_STRING_DATA) *int_err_get(int create);
 static void int_err_del(void);
 static ERR_STRING_DATA *int_err_get_item(const ERR_STRING_DATA *);
 static ERR_STRING_DATA *int_err_set_item(ERR_STRING_DATA *);
 static ERR_STRING_DATA *int_err_del_item(ERR_STRING_DATA *);
 static LHASH_OF(ERR_STATE) *int_thread_get(int create);
 static void int_thread_release(LHASH_OF(ERR_STATE) **hash);
 static ERR_STATE *int_thread_get_item(const ERR_STATE *);
 static ERR_STATE *int_thread_set_item(ERR_STATE *);
 static void int_thread_del_item(const ERR_STATE *);
 static int int_err_get_next_lib(void);
 /* The static ERR_FNS table using these defaults functions */
 static const ERR_FNS err_defaults = {
     int_err_get,
     int_err_del,
     int_err_get_item,
     int_err_set_item,
     int_err_del_item,
     int_thread_get,
     int_thread_release,
     int_thread_get_item,
     int_thread_set_item,
     int_thread_del_item,
     int_err_get_next_lib
 };
 
 /* The replacable table of ERR_FNS functions we use at run-time */
 static const ERR_FNS *err_fns = NULL;
 
 /* Eg. rather than using "err_get()", use "ERRFN(err_get)()". */
 #define ERRFN(a) err_fns->cb_##a
 
 /*
  * The internal state used by "err_defaults" - as such, the setting, reading,
  * creating, and deleting of this data should only be permitted via the
  * "err_defaults" functions. This way, a linked module can completely defer
  * all ERR state operation (together with requisite locking) to the
  * implementations and state in the loading application.
  */
 static LHASH_OF(ERR_STRING_DATA) *int_error_hash = NULL;
 static LHASH_OF(ERR_STATE) *int_thread_hash = NULL;
 static int int_thread_hash_references = 0;
 static int int_err_library_number = ERR_LIB_USER;
 
 /*
  * Internal function that checks whether "err_fns" is set and if not, sets it
  * to the defaults.
  */
 static void err_fns_check(void)
 {
     if (err_fns)
         return;
 
     CRYPTO_w_lock(CRYPTO_LOCK_ERR);
     if (!err_fns)
         err_fns = &err_defaults;
     CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
 }
 
 /* API functions to get or set the underlying ERR functions. */
 
 const ERR_FNS *ERR_get_implementation(void)
 {
     err_fns_check();
     return err_fns;
 }
 
 int ERR_set_implementation(const ERR_FNS *fns)
 {
     int ret = 0;
 
     CRYPTO_w_lock(CRYPTO_LOCK_ERR);
     /*
      * It's too late if 'err_fns' is non-NULL. BTW: not much point setting an
      * error is there?!
      */
     if (!err_fns) {
         err_fns = fns;
         ret = 1;
     }
     CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
     return ret;
 }
 
 /*
  * These are the callbacks provided to "lh_new()" when creating the LHASH
  * tables internal to the "err_defaults" implementation.
  */
 
 static unsigned long get_error_values(int inc, int top, const char **file,
                                       int *line, const char **data,
                                       int *flags);
 
 /* The internal functions used in the "err_defaults" implementation */
 
 static unsigned long err_string_data_hash(const ERR_STRING_DATA *a)
 {
     unsigned long ret, l;
 
     l = a->error;
     ret = l ^ ERR_GET_LIB(l) ^ ERR_GET_FUNC(l);
     return (ret ^ ret % 19 * 13);
 }
 
 static IMPLEMENT_LHASH_HASH_FN(err_string_data, ERR_STRING_DATA)
 
 static int err_string_data_cmp(const ERR_STRING_DATA *a,
                                const ERR_STRING_DATA *b)
 {
     return (int)(a->error - b->error);
 }
 
 static IMPLEMENT_LHASH_COMP_FN(err_string_data, ERR_STRING_DATA)
 
 static LHASH_OF(ERR_STRING_DATA) *int_err_get(int create)
 {
     LHASH_OF(ERR_STRING_DATA) *ret = NULL;
 
     CRYPTO_w_lock(CRYPTO_LOCK_ERR);
     if (!int_error_hash && create) {
         CRYPTO_push_info("int_err_get (err.c)");
         int_error_hash = lh_ERR_STRING_DATA_new();
         CRYPTO_pop_info();
     }
     if (int_error_hash)
         ret = int_error_hash;
     CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
 
     return ret;
 }
 
 static void int_err_del(void)
 {
     CRYPTO_w_lock(CRYPTO_LOCK_ERR);
     if (int_error_hash) {
         lh_ERR_STRING_DATA_free(int_error_hash);
         int_error_hash = NULL;
     }
     CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
 }
 
 static ERR_STRING_DATA *int_err_get_item(const ERR_STRING_DATA *d)
 {
     ERR_STRING_DATA *p;
     LHASH_OF(ERR_STRING_DATA) *hash;
 
     err_fns_check();
     hash = ERRFN(err_get) (0);
     if (!hash)
         return NULL;
 
     CRYPTO_r_lock(CRYPTO_LOCK_ERR);
     p = lh_ERR_STRING_DATA_retrieve(hash, d);
     CRYPTO_r_unlock(CRYPTO_LOCK_ERR);
 
     return p;
 }
 
 static ERR_STRING_DATA *int_err_set_item(ERR_STRING_DATA *d)
 {
     ERR_STRING_DATA *p;
     LHASH_OF(ERR_STRING_DATA) *hash;
 
     err_fns_check();
     hash = ERRFN(err_get) (1);
     if (!hash)
         return NULL;
 
     CRYPTO_w_lock(CRYPTO_LOCK_ERR);
     p = lh_ERR_STRING_DATA_insert(hash, d);
     CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
 
     return p;
 }
 
 static ERR_STRING_DATA *int_err_del_item(ERR_STRING_DATA *d)
 {
     ERR_STRING_DATA *p;
     LHASH_OF(ERR_STRING_DATA) *hash;
 
     err_fns_check();
     hash = ERRFN(err_get) (0);
     if (!hash)
         return NULL;
 
     CRYPTO_w_lock(CRYPTO_LOCK_ERR);
     p = lh_ERR_STRING_DATA_delete(hash, d);
     CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
 
     return p;
 }
 
 static unsigned long err_state_hash(const ERR_STATE *a)
 {
     return CRYPTO_THREADID_hash(&a->tid) * 13;
 }
 
 static IMPLEMENT_LHASH_HASH_FN(err_state, ERR_STATE)
 
 static int err_state_cmp(const ERR_STATE *a, const ERR_STATE *b)
 {
     return CRYPTO_THREADID_cmp(&a->tid, &b->tid);
 }
 
 static IMPLEMENT_LHASH_COMP_FN(err_state, ERR_STATE)
 
 static LHASH_OF(ERR_STATE) *int_thread_get(int create)
 {
     LHASH_OF(ERR_STATE) *ret = NULL;
 
     CRYPTO_w_lock(CRYPTO_LOCK_ERR);
     if (!int_thread_hash && create) {
         CRYPTO_push_info("int_thread_get (err.c)");
         int_thread_hash = lh_ERR_STATE_new();
         CRYPTO_pop_info();
     }
     if (int_thread_hash) {
         int_thread_hash_references++;
         ret = int_thread_hash;
     }
     CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
     return ret;
 }
 
 static void int_thread_release(LHASH_OF(ERR_STATE) **hash)
 {
     int i;
 
     if (hash == NULL || *hash == NULL)
         return;
 
     i = CRYPTO_add(&int_thread_hash_references, -1, CRYPTO_LOCK_ERR);
 
 #ifdef REF_PRINT
     fprintf(stderr, "%4d:%s\n", int_thread_hash_references, "ERR");
 #endif
     if (i > 0)
         return;
 #ifdef REF_CHECK
     if (i < 0) {
         fprintf(stderr, "int_thread_release, bad reference count\n");
         abort();                /* ok */
     }
 #endif
     *hash = NULL;
 }
 
 static ERR_STATE *int_thread_get_item(const ERR_STATE *d)
 {
     ERR_STATE *p;
     LHASH_OF(ERR_STATE) *hash;
 
     err_fns_check();
     hash = ERRFN(thread_get) (0);
     if (!hash)
         return NULL;
 
     CRYPTO_r_lock(CRYPTO_LOCK_ERR);
     p = lh_ERR_STATE_retrieve(hash, d);
     CRYPTO_r_unlock(CRYPTO_LOCK_ERR);
 
     ERRFN(thread_release) (&hash);
     return p;
 }
 
 static ERR_STATE *int_thread_set_item(ERR_STATE *d)
 {
     ERR_STATE *p;
     LHASH_OF(ERR_STATE) *hash;
 
     err_fns_check();
     hash = ERRFN(thread_get) (1);
     if (!hash)
         return NULL;
 
     CRYPTO_w_lock(CRYPTO_LOCK_ERR);
     p = lh_ERR_STATE_insert(hash, d);
     CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
 
     ERRFN(thread_release) (&hash);
     return p;
 }
 
 static void int_thread_del_item(const ERR_STATE *d)
 {
     ERR_STATE *p;
     LHASH_OF(ERR_STATE) *hash;
 
     err_fns_check();
     hash = ERRFN(thread_get) (0);
     if (!hash)
         return;
 
     CRYPTO_w_lock(CRYPTO_LOCK_ERR);
     p = lh_ERR_STATE_delete(hash, d);
     /* make sure we don't leak memory */
     if (int_thread_hash_references == 1
         && int_thread_hash && lh_ERR_STATE_num_items(int_thread_hash) == 0) {
         lh_ERR_STATE_free(int_thread_hash);
         int_thread_hash = NULL;
     }
     CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
 
     ERRFN(thread_release) (&hash);
     if (p)
         ERR_STATE_free(p);
 }
 
 static int int_err_get_next_lib(void)
 {
     int ret;
 
     CRYPTO_w_lock(CRYPTO_LOCK_ERR);
     ret = int_err_library_number++;
     CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
 
     return ret;
 }
 
 #ifndef OPENSSL_NO_ERR
 # define NUM_SYS_STR_REASONS 127
 # define LEN_SYS_STR_REASON 32
 
 static ERR_STRING_DATA SYS_str_reasons[NUM_SYS_STR_REASONS + 1];
 /*
  * SYS_str_reasons is filled with copies of strerror() results at
  * initialization. 'errno' values up to 127 should cover all usual errors,
  * others will be displayed numerically by ERR_error_string. It is crucial
  * that we have something for each reason code that occurs in
  * ERR_str_reasons, or bogus reason strings will be returned for SYSerr(),
  * which always gets an errno value and never one of those 'standard' reason
  * codes.
  */
 
 static void build_SYS_str_reasons(void)
 {
     /* OPENSSL_malloc cannot be used here, use static storage instead */
     static char strerror_tab[NUM_SYS_STR_REASONS][LEN_SYS_STR_REASON];
     int i;
     static int init = 1;
 
     CRYPTO_r_lock(CRYPTO_LOCK_ERR);
     if (!init) {
         CRYPTO_r_unlock(CRYPTO_LOCK_ERR);
         return;
     }
 
     CRYPTO_r_unlock(CRYPTO_LOCK_ERR);
     CRYPTO_w_lock(CRYPTO_LOCK_ERR);
     if (!init) {
         CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
         return;
     }
 
     for (i = 1; i <= NUM_SYS_STR_REASONS; i++) {
         ERR_STRING_DATA *str = &SYS_str_reasons[i - 1];
 
         str->error = (unsigned long)i;
         if (str->string == NULL) {
             char (*dest)[LEN_SYS_STR_REASON] = &(strerror_tab[i - 1]);
             char *src = strerror(i);
             if (src != NULL) {
                 strncpy(*dest, src, sizeof *dest);
                 (*dest)[sizeof *dest - 1] = '\0';
                 str->string = *dest;
             }
         }
         if (str->string == NULL)
             str->string = "unknown";
     }
 
     /*
      * Now we still have SYS_str_reasons[NUM_SYS_STR_REASONS] = {0, NULL}, as
      * required by ERR_load_strings.
      */
 
     init = 0;
 
     CRYPTO_w_unlock(CRYPTO_LOCK_ERR);
 }
 #endif
 
 #define err_clear_data(p,i) \
         do { \
         if (((p)->err_data[i] != NULL) && \
                 (p)->err_data_flags[i] & ERR_TXT_MALLOCED) \
                 {  \
                 OPENSSL_free((p)->err_data[i]); \
                 (p)->err_data[i]=NULL; \
                 } \
         (p)->err_data_flags[i]=0; \
         } while(0)
 
 #define err_clear(p,i) \
         do { \
         (p)->err_flags[i]=0; \
         (p)->err_buffer[i]=0; \
         err_clear_data(p,i); \
         (p)->err_file[i]=NULL; \
         (p)->err_line[i]= -1; \
         } while(0)
 
 static void ERR_STATE_free(ERR_STATE *s)
 {
     int i;
 
     if (s == NULL)
         return;
 
     for (i = 0; i < ERR_NUM_ERRORS; i++) {
         err_clear_data(s, i);
     }
     OPENSSL_free(s);
 }
 
 void ERR_load_ERR_strings(void)
 {
     err_fns_check();
 #ifndef OPENSSL_NO_ERR
     err_load_strings(0, ERR_str_libraries);
     err_load_strings(0, ERR_str_reasons);
     err_load_strings(ERR_LIB_SYS, ERR_str_functs);
     build_SYS_str_reasons();
     err_load_strings(ERR_LIB_SYS, SYS_str_reasons);
 #endif
 }
 
 static void err_load_strings(int lib, ERR_STRING_DATA *str)
 {
     while (str->error) {
         if (lib)
             str->error |= ERR_PACK(lib, 0, 0);
         ERRFN(err_set_item) (str);
         str++;
     }
 }
 
 void ERR_load_strings(int lib, ERR_STRING_DATA *str)
 {
     ERR_load_ERR_strings();
     err_load_strings(lib, str);
 }
 
 void ERR_unload_strings(int lib, ERR_STRING_DATA *str)
 {
     while (str->error) {
         if (lib)
             str->error |= ERR_PACK(lib, 0, 0);
         ERRFN(err_del_item) (str);
         str++;
     }
 }
 
 void ERR_free_strings(void)
 {
     err_fns_check();
     ERRFN(err_del) ();
 }
 
 /********************************************************/
 
 void ERR_put_error(int lib, int func, int reason, const char *file, int line)
 {
     ERR_STATE *es;
 
 #ifdef _OSD_POSIX
     /*
      * In the BS2000-OSD POSIX subsystem, the compiler generates path names
      * in the form "*POSIX(/etc/passwd)". This dirty hack strips them to
      * something sensible. @@@ We shouldn't modify a const string, though.
      */
     if (strncmp(file, "*POSIX(", sizeof("*POSIX(") - 1) == 0) {
         char *end;
 
         /* Skip the "*POSIX(" prefix */
         file += sizeof("*POSIX(") - 1;
         end = &file[strlen(file) - 1];
         if (*end == ')')
             *end = '\0';
         /* Optional: use the basename of the path only. */
         if ((end = strrchr(file, '/')) != NULL)
             file = &end[1];
     }
 #endif
     es = ERR_get_state();
 
     es->top = (es->top + 1) % ERR_NUM_ERRORS;
     if (es->top == es->bottom)
         es->bottom = (es->bottom + 1) % ERR_NUM_ERRORS;
     es->err_flags[es->top] = 0;
     es->err_buffer[es->top] = ERR_PACK(lib, func, reason);
     es->err_file[es->top] = file;
     es->err_line[es->top] = line;
     err_clear_data(es, es->top);
 }
 
 void ERR_clear_error(void)
 {
     int i;
     ERR_STATE *es;
 
     es = ERR_get_state();
 
     for (i = 0; i < ERR_NUM_ERRORS; i++) {
         err_clear(es, i);
     }
     es->top = es->bottom = 0;
 }
 
 unsigned long ERR_get_error(void)
 {
     return (get_error_values(1, 0, NULL, NULL, NULL, NULL));
 }
 
 unsigned long ERR_get_error_line(const char **file, int *line)
 {
     return (get_error_values(1, 0, file, line, NULL, NULL));
 }
 
 unsigned long ERR_get_error_line_data(const char **file, int *line,
                                       const char **data, int *flags)
 {
     return (get_error_values(1, 0, file, line, data, flags));
 }
 
 unsigned long ERR_peek_error(void)
 {
     return (get_error_values(0, 0, NULL, NULL, NULL, NULL));
 }
 
 unsigned long ERR_peek_error_line(const char **file, int *line)
 {
     return (get_error_values(0, 0, file, line, NULL, NULL));
 }
 
 unsigned long ERR_peek_error_line_data(const char **file, int *line,
                                        const char **data, int *flags)
 {
     return (get_error_values(0, 0, file, line, data, flags));
 }
 
 unsigned long ERR_peek_last_error(void)
 {
     return (get_error_values(0, 1, NULL, NULL, NULL, NULL));
 }
 
 unsigned long ERR_peek_last_error_line(const char **file, int *line)
 {
     return (get_error_values(0, 1, file, line, NULL, NULL));
 }
 
 unsigned long ERR_peek_last_error_line_data(const char **file, int *line,
                                             const char **data, int *flags)
 {
     return (get_error_values(0, 1, file, line, data, flags));
 }
 
 static unsigned long get_error_values(int inc, int top, const char **file,
                                       int *line, const char **data,
                                       int *flags)
 {
     int i = 0;
     ERR_STATE *es;
     unsigned long ret;
 
     es = ERR_get_state();
 
     if (inc && top) {
         if (file)
             *file = "";
         if (line)
             *line = 0;
         if (data)
             *data = "";
         if (flags)
             *flags = 0;
 
         return ERR_R_INTERNAL_ERROR;
     }
 
     if (es->bottom == es->top)
         return 0;
     if (top)
         i = es->top;            /* last error */
     else
         i = (es->bottom + 1) % ERR_NUM_ERRORS; /* first error */
 
     ret = es->err_buffer[i];
     if (inc) {
         es->bottom = i;
         es->err_buffer[i] = 0;
     }
 
     if ((file != NULL) && (line != NULL)) {
         if (es->err_file[i] == NULL) {
             *file = "NA";
             if (line != NULL)
                 *line = 0;
         } else {
             *file = es->err_file[i];
             if (line != NULL)
                 *line = es->err_line[i];
         }
     }
 
     if (data == NULL) {
         if (inc) {
             err_clear_data(es, i);
         }
     } else {
         if (es->err_data[i] == NULL) {
             *data = "";
             if (flags != NULL)
                 *flags = 0;
         } else {
             *data = es->err_data[i];
             if (flags != NULL)
                 *flags = es->err_data_flags[i];
         }
     }
     return ret;
 }
 
 void ERR_error_string_n(unsigned long e, char *buf, size_t len)
 {
     char lsbuf[64], fsbuf[64], rsbuf[64];
     const char *ls, *fs, *rs;
     unsigned long l, f, r;
 
     if (len == 0)
         return;
 
     l = ERR_GET_LIB(e);
     f = ERR_GET_FUNC(e);
     r = ERR_GET_REASON(e);
 
     ls = ERR_lib_error_string(e);
     fs = ERR_func_error_string(e);
     rs = ERR_reason_error_string(e);
 
     if (ls == NULL)
         BIO_snprintf(lsbuf, sizeof(lsbuf), "lib(%lu)", l);
     if (fs == NULL)
         BIO_snprintf(fsbuf, sizeof(fsbuf), "func(%lu)", f);
     if (rs == NULL)
         BIO_snprintf(rsbuf, sizeof(rsbuf), "reason(%lu)", r);
 
     BIO_snprintf(buf, len, "error:%08lX:%s:%s:%s", e, ls ? ls : lsbuf,
                  fs ? fs : fsbuf, rs ? rs : rsbuf);
     if (strlen(buf) == len - 1) {
         /*
          * output may be truncated; make sure we always have 5
          * colon-separated fields, i.e. 4 colons ...
          */
 #define NUM_COLONS 4
         if (len > NUM_COLONS) { /* ... if possible */
             int i;
             char *s = buf;
 
             for (i = 0; i < NUM_COLONS; i++) {
                 char *colon = strchr(s, ':');
                 if (colon == NULL || colon > &buf[len - 1] - NUM_COLONS + i) {
                     /*
                      * set colon no. i at last possible position (buf[len-1]
                      * is the terminating 0)
                      */
                     colon = &buf[len - 1] - NUM_COLONS + i;
                     *colon = ':';
                 }
                 s = colon + 1;
             }
         }
     }
 }
 
 /* BAD for multi-threading: uses a local buffer if ret == NULL */
 /*
  * ERR_error_string_n should be used instead for ret != NULL as
  * ERR_error_string cannot know how large the buffer is
  */
 char *ERR_error_string(unsigned long e, char *ret)
 {
     static char buf[256];
 
     if (ret == NULL)
         ret = buf;
     ERR_error_string_n(e, ret, 256);
 
     return ret;
 }
 
 LHASH_OF(ERR_STRING_DATA) *ERR_get_string_table(void)
 {
     err_fns_check();
     return ERRFN(err_get) (0);
 }
 
 LHASH_OF(ERR_STATE) *ERR_get_err_state_table(void)
 {
     err_fns_check();
     return ERRFN(thread_get) (0);
 }
 
 void ERR_release_err_state_table(LHASH_OF(ERR_STATE) **hash)
 {
     err_fns_check();
     ERRFN(thread_release) (hash);
 }
 
 const char *ERR_lib_error_string(unsigned long e)
 {
     ERR_STRING_DATA d, *p;
     unsigned long l;
 
     err_fns_check();
     l = ERR_GET_LIB(e);
     d.error = ERR_PACK(l, 0, 0);
     p = ERRFN(err_get_item) (&d);
     return ((p == NULL) ? NULL : p->string);
 }
 
 const char *ERR_func_error_string(unsigned long e)
 {
     ERR_STRING_DATA d, *p;
     unsigned long l, f;
 
     err_fns_check();
     l = ERR_GET_LIB(e);
     f = ERR_GET_FUNC(e);
     d.error = ERR_PACK(l, f, 0);
     p = ERRFN(err_get_item) (&d);
     return ((p == NULL) ? NULL : p->string);
 }
 
 const char *ERR_reason_error_string(unsigned long e)
 {
     ERR_STRING_DATA d, *p = NULL;
     unsigned long l, r;
 
     err_fns_check();
     l = ERR_GET_LIB(e);
     r = ERR_GET_REASON(e);
     d.error = ERR_PACK(l, 0, r);
     p = ERRFN(err_get_item) (&d);
     if (!p) {
         d.error = ERR_PACK(0, 0, r);
         p = ERRFN(err_get_item) (&d);
     }
     return ((p == NULL) ? NULL : p->string);
 }
 
 void ERR_remove_thread_state(const CRYPTO_THREADID *id)
 {
     ERR_STATE tmp;
 
     if (id)
         CRYPTO_THREADID_cpy(&tmp.tid, id);
     else
         CRYPTO_THREADID_current(&tmp.tid);
     err_fns_check();
     /*
      * thread_del_item automatically destroys the LHASH if the number of
      * items reaches zero.
      */
     ERRFN(thread_del_item) (&tmp);
 }
 
 #ifndef OPENSSL_NO_DEPRECATED
 void ERR_remove_state(unsigned long pid)
 {
     ERR_remove_thread_state(NULL);
 }
 #endif
 
 ERR_STATE *ERR_get_state(void)
 {
     static ERR_STATE fallback;
     ERR_STATE *ret, tmp, *tmpp = NULL;
     int i;
     CRYPTO_THREADID tid;
 
     err_fns_check();
     CRYPTO_THREADID_current(&tid);
     CRYPTO_THREADID_cpy(&tmp.tid, &tid);
     ret = ERRFN(thread_get_item) (&tmp);
 
     /* ret == the error state, if NULL, make a new one */
     if (ret == NULL) {
         ret = (ERR_STATE *)OPENSSL_malloc(sizeof(ERR_STATE));
         if (ret == NULL)
             return (&fallback);
         CRYPTO_THREADID_cpy(&ret->tid, &tid);
         ret->top = 0;
         ret->bottom = 0;
         for (i = 0; i < ERR_NUM_ERRORS; i++) {
             ret->err_data[i] = NULL;
             ret->err_data_flags[i] = 0;
         }
         tmpp = ERRFN(thread_set_item) (ret);
         /* To check if insertion failed, do a get. */
         if (ERRFN(thread_get_item) (ret) != ret) {
             ERR_STATE_free(ret); /* could not insert it */
             return (&fallback);
         }
         /*
          * If a race occured in this function and we came second, tmpp is the
          * first one that we just replaced.
          */
         if (tmpp)
             ERR_STATE_free(tmpp);
     }
     return ret;
 }
 
 int ERR_get_next_error_library(void)
 {
     err_fns_check();
     return ERRFN(get_next_lib) ();
 }
 
 void ERR_set_error_data(char *data, int flags)
 {
     ERR_STATE *es;
     int i;
 
     es = ERR_get_state();
 
     i = es->top;
     if (i == 0)
         i = ERR_NUM_ERRORS - 1;
 
     err_clear_data(es, i);
     es->err_data[i] = data;
     es->err_data_flags[i] = flags;
 }
 
 void ERR_add_error_data(int num, ...)
 {
     va_list args;
     va_start(args, num);
     ERR_add_error_vdata(num, args);
     va_end(args);
 }
 
 void ERR_add_error_vdata(int num, va_list args)
 {
     int i, n, s;
     char *str, *p, *a;
 
     s = 80;
     str = OPENSSL_malloc(s + 1);
     if (str == NULL)
         return;
     str[0] = '\0';
 
     n = 0;
     for (i = 0; i < num; i++) {
         a = va_arg(args, char *);
         /* ignore NULLs, thanks to Bob Beck  */
         if (a != NULL) {
             n += strlen(a);
             if (n > s) {
                 s = n + 20;
                 p = OPENSSL_realloc(str, s + 1);
                 if (p == NULL) {
                     OPENSSL_free(str);
                     return;
                 } else
                     str = p;
             }
             BUF_strlcat(str, a, (size_t)s + 1);
         }
     }
     ERR_set_error_data(str, ERR_TXT_MALLOCED | ERR_TXT_STRING);
 }
 
 int ERR_set_mark(void)
 {
     ERR_STATE *es;
 
     es = ERR_get_state();
 
     if (es->bottom == es->top)
         return 0;
     es->err_flags[es->top] |= ERR_FLAG_MARK;
     return 1;
 }
 
 int ERR_pop_to_mark(void)
 {
     ERR_STATE *es;
 
     es = ERR_get_state();
 
     while (es->bottom != es->top
            && (es->err_flags[es->top] & ERR_FLAG_MARK) == 0) {
         err_clear(es, es->top);
         es->top -= 1;
         if (es->top == -1)
             es->top = ERR_NUM_ERRORS - 1;
     }
 
     if (es->bottom == es->top)
         return 0;
     es->err_flags[es->top] &= ~ERR_FLAG_MARK;
     return 1;
 }
Index: vendor-crypto/openssl/dist/crypto/err/err.h
===================================================================
--- vendor-crypto/openssl/dist/crypto/err/err.h	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/err/err.h	(revision 318897)
@@ -1,389 +1,390 @@
 /* crypto/err/err.h */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 /* ====================================================================
  * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    openssl-core@openssl.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #ifndef HEADER_ERR_H
 # define HEADER_ERR_H
 
 # include 
 
 # ifndef OPENSSL_NO_FP_API
 #  include 
 #  include 
 # endif
 
 # include 
 # ifndef OPENSSL_NO_BIO
 #  include 
 # endif
 # ifndef OPENSSL_NO_LHASH
 #  include 
 # endif
 
 #ifdef  __cplusplus
 extern "C" {
 #endif
 
 # ifndef OPENSSL_NO_ERR
 #  define ERR_PUT_error(a,b,c,d,e)        ERR_put_error(a,b,c,d,e)
 # else
 #  define ERR_PUT_error(a,b,c,d,e)        ERR_put_error(a,b,c,NULL,0)
 # endif
 
 # include 
 
 # define ERR_TXT_MALLOCED        0x01
 # define ERR_TXT_STRING          0x02
 
 # define ERR_FLAG_MARK           0x01
 
 # define ERR_NUM_ERRORS  16
 typedef struct err_state_st {
     CRYPTO_THREADID tid;
     int err_flags[ERR_NUM_ERRORS];
     unsigned long err_buffer[ERR_NUM_ERRORS];
     char *err_data[ERR_NUM_ERRORS];
     int err_data_flags[ERR_NUM_ERRORS];
     const char *err_file[ERR_NUM_ERRORS];
     int err_line[ERR_NUM_ERRORS];
     int top, bottom;
 } ERR_STATE;
 
 /* library */
 # define ERR_LIB_NONE            1
 # define ERR_LIB_SYS             2
 # define ERR_LIB_BN              3
 # define ERR_LIB_RSA             4
 # define ERR_LIB_DH              5
 # define ERR_LIB_EVP             6
 # define ERR_LIB_BUF             7
 # define ERR_LIB_OBJ             8
 # define ERR_LIB_PEM             9
 # define ERR_LIB_DSA             10
 # define ERR_LIB_X509            11
 /* #define ERR_LIB_METH         12 */
 # define ERR_LIB_ASN1            13
 # define ERR_LIB_CONF            14
 # define ERR_LIB_CRYPTO          15
 # define ERR_LIB_EC              16
 # define ERR_LIB_SSL             20
 /* #define ERR_LIB_SSL23        21 */
 /* #define ERR_LIB_SSL2         22 */
 /* #define ERR_LIB_SSL3         23 */
 /* #define ERR_LIB_RSAREF       30 */
 /* #define ERR_LIB_PROXY        31 */
 # define ERR_LIB_BIO             32
 # define ERR_LIB_PKCS7           33
 # define ERR_LIB_X509V3          34
 # define ERR_LIB_PKCS12          35
 # define ERR_LIB_RAND            36
 # define ERR_LIB_DSO             37
 # define ERR_LIB_ENGINE          38
 # define ERR_LIB_OCSP            39
 # define ERR_LIB_UI              40
 # define ERR_LIB_COMP            41
 # define ERR_LIB_ECDSA           42
 # define ERR_LIB_ECDH            43
 # define ERR_LIB_STORE           44
 # define ERR_LIB_FIPS            45
 # define ERR_LIB_CMS             46
 # define ERR_LIB_TS              47
 # define ERR_LIB_HMAC            48
 # define ERR_LIB_JPAKE           49
 
 # define ERR_LIB_USER            128
 
 # define SYSerr(f,r)  ERR_PUT_error(ERR_LIB_SYS,(f),(r),__FILE__,__LINE__)
 # define BNerr(f,r)   ERR_PUT_error(ERR_LIB_BN,(f),(r),__FILE__,__LINE__)
 # define RSAerr(f,r)  ERR_PUT_error(ERR_LIB_RSA,(f),(r),__FILE__,__LINE__)
 # define DHerr(f,r)   ERR_PUT_error(ERR_LIB_DH,(f),(r),__FILE__,__LINE__)
 # define EVPerr(f,r)  ERR_PUT_error(ERR_LIB_EVP,(f),(r),__FILE__,__LINE__)
 # define BUFerr(f,r)  ERR_PUT_error(ERR_LIB_BUF,(f),(r),__FILE__,__LINE__)
 # define OBJerr(f,r)  ERR_PUT_error(ERR_LIB_OBJ,(f),(r),__FILE__,__LINE__)
 # define PEMerr(f,r)  ERR_PUT_error(ERR_LIB_PEM,(f),(r),__FILE__,__LINE__)
 # define DSAerr(f,r)  ERR_PUT_error(ERR_LIB_DSA,(f),(r),__FILE__,__LINE__)
 # define X509err(f,r) ERR_PUT_error(ERR_LIB_X509,(f),(r),__FILE__,__LINE__)
 # define ASN1err(f,r) ERR_PUT_error(ERR_LIB_ASN1,(f),(r),__FILE__,__LINE__)
 # define CONFerr(f,r) ERR_PUT_error(ERR_LIB_CONF,(f),(r),__FILE__,__LINE__)
 # define CRYPTOerr(f,r) ERR_PUT_error(ERR_LIB_CRYPTO,(f),(r),__FILE__,__LINE__)
 # define ECerr(f,r)   ERR_PUT_error(ERR_LIB_EC,(f),(r),__FILE__,__LINE__)
 # define SSLerr(f,r)  ERR_PUT_error(ERR_LIB_SSL,(f),(r),__FILE__,__LINE__)
 # define BIOerr(f,r)  ERR_PUT_error(ERR_LIB_BIO,(f),(r),__FILE__,__LINE__)
 # define PKCS7err(f,r) ERR_PUT_error(ERR_LIB_PKCS7,(f),(r),__FILE__,__LINE__)
 # define X509V3err(f,r) ERR_PUT_error(ERR_LIB_X509V3,(f),(r),__FILE__,__LINE__)
 # define PKCS12err(f,r) ERR_PUT_error(ERR_LIB_PKCS12,(f),(r),__FILE__,__LINE__)
 # define RANDerr(f,r) ERR_PUT_error(ERR_LIB_RAND,(f),(r),__FILE__,__LINE__)
 # define DSOerr(f,r) ERR_PUT_error(ERR_LIB_DSO,(f),(r),__FILE__,__LINE__)
 # define ENGINEerr(f,r) ERR_PUT_error(ERR_LIB_ENGINE,(f),(r),__FILE__,__LINE__)
 # define OCSPerr(f,r) ERR_PUT_error(ERR_LIB_OCSP,(f),(r),__FILE__,__LINE__)
 # define UIerr(f,r) ERR_PUT_error(ERR_LIB_UI,(f),(r),__FILE__,__LINE__)
 # define COMPerr(f,r) ERR_PUT_error(ERR_LIB_COMP,(f),(r),__FILE__,__LINE__)
 # define ECDSAerr(f,r)  ERR_PUT_error(ERR_LIB_ECDSA,(f),(r),__FILE__,__LINE__)
 # define ECDHerr(f,r)  ERR_PUT_error(ERR_LIB_ECDH,(f),(r),__FILE__,__LINE__)
 # define STOREerr(f,r) ERR_PUT_error(ERR_LIB_STORE,(f),(r),__FILE__,__LINE__)
 # define FIPSerr(f,r) ERR_PUT_error(ERR_LIB_FIPS,(f),(r),__FILE__,__LINE__)
 # define CMSerr(f,r) ERR_PUT_error(ERR_LIB_CMS,(f),(r),__FILE__,__LINE__)
 # define TSerr(f,r) ERR_PUT_error(ERR_LIB_TS,(f),(r),__FILE__,__LINE__)
 # define HMACerr(f,r) ERR_PUT_error(ERR_LIB_HMAC,(f),(r),__FILE__,__LINE__)
 # define JPAKEerr(f,r) ERR_PUT_error(ERR_LIB_JPAKE,(f),(r),__FILE__,__LINE__)
 
 /*
  * Borland C seems too stupid to be able to shift and do longs in the
  * pre-processor :-(
  */
 # define ERR_PACK(l,f,r)         (((((unsigned long)l)&0xffL)*0x1000000)| \
                                 ((((unsigned long)f)&0xfffL)*0x1000)| \
                                 ((((unsigned long)r)&0xfffL)))
 # define ERR_GET_LIB(l)          (int)((((unsigned long)l)>>24L)&0xffL)
 # define ERR_GET_FUNC(l)         (int)((((unsigned long)l)>>12L)&0xfffL)
 # define ERR_GET_REASON(l)       (int)((l)&0xfffL)
 # define ERR_FATAL_ERROR(l)      (int)((l)&ERR_R_FATAL)
 
 /* OS functions */
 # define SYS_F_FOPEN             1
 # define SYS_F_CONNECT           2
 # define SYS_F_GETSERVBYNAME     3
 # define SYS_F_SOCKET            4
 # define SYS_F_IOCTLSOCKET       5
 # define SYS_F_BIND              6
 # define SYS_F_LISTEN            7
 # define SYS_F_ACCEPT            8
 # define SYS_F_WSASTARTUP        9/* Winsock stuff */
 # define SYS_F_OPENDIR           10
 # define SYS_F_FREAD             11
+# define SYS_F_FFLUSH            18
 
 /* reasons */
 # define ERR_R_SYS_LIB   ERR_LIB_SYS/* 2 */
 # define ERR_R_BN_LIB    ERR_LIB_BN/* 3 */
 # define ERR_R_RSA_LIB   ERR_LIB_RSA/* 4 */
 # define ERR_R_DH_LIB    ERR_LIB_DH/* 5 */
 # define ERR_R_EVP_LIB   ERR_LIB_EVP/* 6 */
 # define ERR_R_BUF_LIB   ERR_LIB_BUF/* 7 */
 # define ERR_R_OBJ_LIB   ERR_LIB_OBJ/* 8 */
 # define ERR_R_PEM_LIB   ERR_LIB_PEM/* 9 */
 # define ERR_R_DSA_LIB   ERR_LIB_DSA/* 10 */
 # define ERR_R_X509_LIB  ERR_LIB_X509/* 11 */
 # define ERR_R_ASN1_LIB  ERR_LIB_ASN1/* 13 */
 # define ERR_R_CONF_LIB  ERR_LIB_CONF/* 14 */
 # define ERR_R_CRYPTO_LIB ERR_LIB_CRYPTO/* 15 */
 # define ERR_R_EC_LIB    ERR_LIB_EC/* 16 */
 # define ERR_R_SSL_LIB   ERR_LIB_SSL/* 20 */
 # define ERR_R_BIO_LIB   ERR_LIB_BIO/* 32 */
 # define ERR_R_PKCS7_LIB ERR_LIB_PKCS7/* 33 */
 # define ERR_R_X509V3_LIB ERR_LIB_X509V3/* 34 */
 # define ERR_R_PKCS12_LIB ERR_LIB_PKCS12/* 35 */
 # define ERR_R_RAND_LIB  ERR_LIB_RAND/* 36 */
 # define ERR_R_DSO_LIB   ERR_LIB_DSO/* 37 */
 # define ERR_R_ENGINE_LIB ERR_LIB_ENGINE/* 38 */
 # define ERR_R_OCSP_LIB  ERR_LIB_OCSP/* 39 */
 # define ERR_R_UI_LIB    ERR_LIB_UI/* 40 */
 # define ERR_R_COMP_LIB  ERR_LIB_COMP/* 41 */
 # define ERR_R_ECDSA_LIB ERR_LIB_ECDSA/* 42 */
 # define ERR_R_ECDH_LIB  ERR_LIB_ECDH/* 43 */
 # define ERR_R_STORE_LIB ERR_LIB_STORE/* 44 */
 # define ERR_R_TS_LIB    ERR_LIB_TS/* 45 */
 
 # define ERR_R_NESTED_ASN1_ERROR                 58
 # define ERR_R_BAD_ASN1_OBJECT_HEADER            59
 # define ERR_R_BAD_GET_ASN1_OBJECT_CALL          60
 # define ERR_R_EXPECTING_AN_ASN1_SEQUENCE        61
 # define ERR_R_ASN1_LENGTH_MISMATCH              62
 # define ERR_R_MISSING_ASN1_EOS                  63
 
 /* fatal error */
 # define ERR_R_FATAL                             64
 # define ERR_R_MALLOC_FAILURE                    (1|ERR_R_FATAL)
 # define ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED       (2|ERR_R_FATAL)
 # define ERR_R_PASSED_NULL_PARAMETER             (3|ERR_R_FATAL)
 # define ERR_R_INTERNAL_ERROR                    (4|ERR_R_FATAL)
 # define ERR_R_DISABLED                          (5|ERR_R_FATAL)
 
 /*
  * 99 is the maximum possible ERR_R_... code, higher values are reserved for
  * the individual libraries
  */
 
 typedef struct ERR_string_data_st {
     unsigned long error;
     const char *string;
 } ERR_STRING_DATA;
 
 void ERR_put_error(int lib, int func, int reason, const char *file, int line);
 void ERR_set_error_data(char *data, int flags);
 
 unsigned long ERR_get_error(void);
 unsigned long ERR_get_error_line(const char **file, int *line);
 unsigned long ERR_get_error_line_data(const char **file, int *line,
                                       const char **data, int *flags);
 unsigned long ERR_peek_error(void);
 unsigned long ERR_peek_error_line(const char **file, int *line);
 unsigned long ERR_peek_error_line_data(const char **file, int *line,
                                        const char **data, int *flags);
 unsigned long ERR_peek_last_error(void);
 unsigned long ERR_peek_last_error_line(const char **file, int *line);
 unsigned long ERR_peek_last_error_line_data(const char **file, int *line,
                                             const char **data, int *flags);
 void ERR_clear_error(void);
 char *ERR_error_string(unsigned long e, char *buf);
 void ERR_error_string_n(unsigned long e, char *buf, size_t len);
 const char *ERR_lib_error_string(unsigned long e);
 const char *ERR_func_error_string(unsigned long e);
 const char *ERR_reason_error_string(unsigned long e);
 void ERR_print_errors_cb(int (*cb) (const char *str, size_t len, void *u),
                          void *u);
 # ifndef OPENSSL_NO_FP_API
 void ERR_print_errors_fp(FILE *fp);
 # endif
 # ifndef OPENSSL_NO_BIO
 void ERR_print_errors(BIO *bp);
 # endif
 void ERR_add_error_data(int num, ...);
 void ERR_add_error_vdata(int num, va_list args);
 void ERR_load_strings(int lib, ERR_STRING_DATA str[]);
 void ERR_unload_strings(int lib, ERR_STRING_DATA str[]);
 void ERR_load_ERR_strings(void);
 void ERR_load_crypto_strings(void);
 void ERR_free_strings(void);
 
 void ERR_remove_thread_state(const CRYPTO_THREADID *tid);
 # ifndef OPENSSL_NO_DEPRECATED
 void ERR_remove_state(unsigned long pid); /* if zero we look it up */
 # endif
 ERR_STATE *ERR_get_state(void);
 
 # ifndef OPENSSL_NO_LHASH
 LHASH_OF(ERR_STRING_DATA) *ERR_get_string_table(void);
 LHASH_OF(ERR_STATE) *ERR_get_err_state_table(void);
 void ERR_release_err_state_table(LHASH_OF(ERR_STATE) **hash);
 # endif
 
 int ERR_get_next_error_library(void);
 
 int ERR_set_mark(void);
 int ERR_pop_to_mark(void);
 
 /* Already defined in ossl_typ.h */
 /* typedef struct st_ERR_FNS ERR_FNS; */
 /*
  * An application can use this function and provide the return value to
  * loaded modules that should use the application's ERR state/functionality
  */
 const ERR_FNS *ERR_get_implementation(void);
 /*
  * A loaded module should call this function prior to any ERR operations
  * using the application's "ERR_FNS".
  */
 int ERR_set_implementation(const ERR_FNS *fns);
 
 #ifdef  __cplusplus
 }
 #endif
 
 #endif
Index: vendor-crypto/openssl/dist/crypto/evp/e_aes.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/evp/e_aes.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/evp/e_aes.c	(revision 318897)
@@ -1,2024 +1,2031 @@
 /* ====================================================================
  * Copyright (c) 2001-2011 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    openssl-core@openssl.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  */
 
 #include 
 #ifndef OPENSSL_NO_AES
 #include 
 # include 
 # include 
 # include 
 # include 
 # include 
 # include "evp_locl.h"
 # include "modes_lcl.h"
 # include 
 
 # undef EVP_CIPH_FLAG_FIPS
 # define EVP_CIPH_FLAG_FIPS 0
 
 typedef struct {
     union {
         double align;
         AES_KEY ks;
     } ks;
     block128_f block;
     union {
         cbc128_f cbc;
         ctr128_f ctr;
     } stream;
 } EVP_AES_KEY;
 
 typedef struct {
     union {
         double align;
         AES_KEY ks;
     } ks;                       /* AES key schedule to use */
     int key_set;                /* Set if key initialised */
     int iv_set;                 /* Set if an iv is set */
     GCM128_CONTEXT gcm;
     unsigned char *iv;          /* Temporary IV store */
     int ivlen;                  /* IV length */
     int taglen;
     int iv_gen;                 /* It is OK to generate IVs */
     int tls_aad_len;            /* TLS AAD length */
     ctr128_f ctr;
 } EVP_AES_GCM_CTX;
 
 typedef struct {
     union {
         double align;
         AES_KEY ks;
     } ks1, ks2;                 /* AES key schedules to use */
     XTS128_CONTEXT xts;
     void (*stream) (const unsigned char *in,
                     unsigned char *out, size_t length,
                     const AES_KEY *key1, const AES_KEY *key2,
                     const unsigned char iv[16]);
 } EVP_AES_XTS_CTX;
 
 typedef struct {
     union {
         double align;
         AES_KEY ks;
     } ks;                       /* AES key schedule to use */
     int key_set;                /* Set if key initialised */
     int iv_set;                 /* Set if an iv is set */
     int tag_set;                /* Set if tag is valid */
     int len_set;                /* Set if message length set */
     int L, M;                   /* L and M parameters from RFC3610 */
     CCM128_CONTEXT ccm;
     ccm128_f str;
 } EVP_AES_CCM_CTX;
 
 # define MAXBITCHUNK     ((size_t)1<<(sizeof(size_t)*8-4))
 
 # ifdef VPAES_ASM
 int vpaes_set_encrypt_key(const unsigned char *userKey, int bits,
                           AES_KEY *key);
 int vpaes_set_decrypt_key(const unsigned char *userKey, int bits,
                           AES_KEY *key);
 
 void vpaes_encrypt(const unsigned char *in, unsigned char *out,
                    const AES_KEY *key);
 void vpaes_decrypt(const unsigned char *in, unsigned char *out,
                    const AES_KEY *key);
 
 void vpaes_cbc_encrypt(const unsigned char *in,
                        unsigned char *out,
                        size_t length,
                        const AES_KEY *key, unsigned char *ivec, int enc);
 # endif
 # ifdef BSAES_ASM
 void bsaes_cbc_encrypt(const unsigned char *in, unsigned char *out,
                        size_t length, const AES_KEY *key,
                        unsigned char ivec[16], int enc);
 void bsaes_ctr32_encrypt_blocks(const unsigned char *in, unsigned char *out,
                                 size_t len, const AES_KEY *key,
                                 const unsigned char ivec[16]);
 void bsaes_xts_encrypt(const unsigned char *inp, unsigned char *out,
                        size_t len, const AES_KEY *key1,
                        const AES_KEY *key2, const unsigned char iv[16]);
 void bsaes_xts_decrypt(const unsigned char *inp, unsigned char *out,
                        size_t len, const AES_KEY *key1,
                        const AES_KEY *key2, const unsigned char iv[16]);
 # endif
 # ifdef AES_CTR_ASM
 void AES_ctr32_encrypt(const unsigned char *in, unsigned char *out,
                        size_t blocks, const AES_KEY *key,
                        const unsigned char ivec[AES_BLOCK_SIZE]);
 # endif
 # ifdef AES_XTS_ASM
 void AES_xts_encrypt(const unsigned char *inp, unsigned char *out, size_t len,
                      const AES_KEY *key1, const AES_KEY *key2,
                      const unsigned char iv[16]);
 void AES_xts_decrypt(const unsigned char *inp, unsigned char *out, size_t len,
                      const AES_KEY *key1, const AES_KEY *key2,
                      const unsigned char iv[16]);
 # endif
 
 # if     defined(OPENSSL_CPUID_OBJ) && (defined(__powerpc__) || defined(__ppc__) || defined(_ARCH_PPC))
 #  include "ppc_arch.h"
 #  ifdef VPAES_ASM
 #   define VPAES_CAPABLE (OPENSSL_ppccap_P & PPC_ALTIVEC)
 #  endif
 #  define HWAES_CAPABLE  (OPENSSL_ppccap_P & PPC_CRYPTO207)
 #  define HWAES_set_encrypt_key aes_p8_set_encrypt_key
 #  define HWAES_set_decrypt_key aes_p8_set_decrypt_key
 #  define HWAES_encrypt aes_p8_encrypt
 #  define HWAES_decrypt aes_p8_decrypt
 #  define HWAES_cbc_encrypt aes_p8_cbc_encrypt
 #  define HWAES_ctr32_encrypt_blocks aes_p8_ctr32_encrypt_blocks
 # endif
 
 # if     defined(AES_ASM) && !defined(I386_ONLY) &&      (  \
         ((defined(__i386)       || defined(__i386__)    || \
           defined(_M_IX86)) && defined(OPENSSL_IA32_SSE2))|| \
         defined(__x86_64)       || defined(__x86_64__)  || \
         defined(_M_AMD64)       || defined(_M_X64)      || \
         defined(__INTEL__)                              )
 
 extern unsigned int OPENSSL_ia32cap_P[];
 
 #  ifdef VPAES_ASM
 #   define VPAES_CAPABLE   (OPENSSL_ia32cap_P[1]&(1<<(41-32)))
 #  endif
 #  ifdef BSAES_ASM
 #   define BSAES_CAPABLE   (OPENSSL_ia32cap_P[1]&(1<<(41-32)))
 #  endif
 /*
  * AES-NI section
  */
 #  define AESNI_CAPABLE   (OPENSSL_ia32cap_P[1]&(1<<(57-32)))
 
 int aesni_set_encrypt_key(const unsigned char *userKey, int bits,
                           AES_KEY *key);
 int aesni_set_decrypt_key(const unsigned char *userKey, int bits,
                           AES_KEY *key);
 
 void aesni_encrypt(const unsigned char *in, unsigned char *out,
                    const AES_KEY *key);
 void aesni_decrypt(const unsigned char *in, unsigned char *out,
                    const AES_KEY *key);
 
 void aesni_ecb_encrypt(const unsigned char *in,
                        unsigned char *out,
                        size_t length, const AES_KEY *key, int enc);
 void aesni_cbc_encrypt(const unsigned char *in,
                        unsigned char *out,
                        size_t length,
                        const AES_KEY *key, unsigned char *ivec, int enc);
 
 void aesni_ctr32_encrypt_blocks(const unsigned char *in,
                                 unsigned char *out,
                                 size_t blocks,
                                 const void *key, const unsigned char *ivec);
 
 void aesni_xts_encrypt(const unsigned char *in,
                        unsigned char *out,
                        size_t length,
                        const AES_KEY *key1, const AES_KEY *key2,
                        const unsigned char iv[16]);
 
 void aesni_xts_decrypt(const unsigned char *in,
                        unsigned char *out,
                        size_t length,
                        const AES_KEY *key1, const AES_KEY *key2,
                        const unsigned char iv[16]);
 
 void aesni_ccm64_encrypt_blocks(const unsigned char *in,
                                 unsigned char *out,
                                 size_t blocks,
                                 const void *key,
                                 const unsigned char ivec[16],
                                 unsigned char cmac[16]);
 
 void aesni_ccm64_decrypt_blocks(const unsigned char *in,
                                 unsigned char *out,
                                 size_t blocks,
                                 const void *key,
                                 const unsigned char ivec[16],
                                 unsigned char cmac[16]);
 
 #  if defined(__x86_64) || defined(__x86_64__) || defined(_M_AMD64) || defined(_M_X64)
 size_t aesni_gcm_encrypt(const unsigned char *in,
                          unsigned char *out,
                          size_t len,
                          const void *key, unsigned char ivec[16], u64 *Xi);
 #   define AES_gcm_encrypt aesni_gcm_encrypt
 size_t aesni_gcm_decrypt(const unsigned char *in,
                          unsigned char *out,
                          size_t len,
                          const void *key, unsigned char ivec[16], u64 *Xi);
 #   define AES_gcm_decrypt aesni_gcm_decrypt
 void gcm_ghash_avx(u64 Xi[2], const u128 Htable[16], const u8 *in,
                    size_t len);
 #   define AES_GCM_ASM(gctx)       (gctx->ctr==aesni_ctr32_encrypt_blocks && \
                                  gctx->gcm.ghash==gcm_ghash_avx)
 #   define AES_GCM_ASM2(gctx)      (gctx->gcm.block==(block128_f)aesni_encrypt && \
                                  gctx->gcm.ghash==gcm_ghash_avx)
 #   undef AES_GCM_ASM2          /* minor size optimization */
 #  endif
 
 static int aesni_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
                           const unsigned char *iv, int enc)
 {
     int ret, mode;
     EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
 
     mode = ctx->cipher->flags & EVP_CIPH_MODE;
     if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE)
         && !enc) {
         ret = aesni_set_decrypt_key(key, ctx->key_len * 8, ctx->cipher_data);
         dat->block = (block128_f) aesni_decrypt;
         dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
             (cbc128_f) aesni_cbc_encrypt : NULL;
     } else {
         ret = aesni_set_encrypt_key(key, ctx->key_len * 8, ctx->cipher_data);
         dat->block = (block128_f) aesni_encrypt;
         if (mode == EVP_CIPH_CBC_MODE)
             dat->stream.cbc = (cbc128_f) aesni_cbc_encrypt;
         else if (mode == EVP_CIPH_CTR_MODE)
             dat->stream.ctr = (ctr128_f) aesni_ctr32_encrypt_blocks;
         else
             dat->stream.cbc = NULL;
     }
 
     if (ret < 0) {
         EVPerr(EVP_F_AESNI_INIT_KEY, EVP_R_AES_KEY_SETUP_FAILED);
         return 0;
     }
 
     return 1;
 }
 
 static int aesni_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                             const unsigned char *in, size_t len)
 {
     aesni_cbc_encrypt(in, out, len, ctx->cipher_data, ctx->iv, ctx->encrypt);
 
     return 1;
 }
 
 static int aesni_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                             const unsigned char *in, size_t len)
 {
     size_t bl = ctx->cipher->block_size;
 
     if (len < bl)
         return 1;
 
     aesni_ecb_encrypt(in, out, len, ctx->cipher_data, ctx->encrypt);
 
     return 1;
 }
 
 #  define aesni_ofb_cipher aes_ofb_cipher
 static int aesni_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                             const unsigned char *in, size_t len);
 
 #  define aesni_cfb_cipher aes_cfb_cipher
 static int aesni_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                             const unsigned char *in, size_t len);
 
 #  define aesni_cfb8_cipher aes_cfb8_cipher
 static int aesni_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                              const unsigned char *in, size_t len);
 
 #  define aesni_cfb1_cipher aes_cfb1_cipher
 static int aesni_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                              const unsigned char *in, size_t len);
 
 #  define aesni_ctr_cipher aes_ctr_cipher
 static int aesni_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                             const unsigned char *in, size_t len);
 
 static int aesni_gcm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
                               const unsigned char *iv, int enc)
 {
     EVP_AES_GCM_CTX *gctx = ctx->cipher_data;
     if (!iv && !key)
         return 1;
     if (key) {
         aesni_set_encrypt_key(key, ctx->key_len * 8, &gctx->ks.ks);
         CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks, (block128_f) aesni_encrypt);
         gctx->ctr = (ctr128_f) aesni_ctr32_encrypt_blocks;
         /*
          * If we have an iv can set it directly, otherwise use saved IV.
          */
         if (iv == NULL && gctx->iv_set)
             iv = gctx->iv;
         if (iv) {
             CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen);
             gctx->iv_set = 1;
         }
         gctx->key_set = 1;
     } else {
         /* If key set use IV, otherwise copy */
         if (gctx->key_set)
             CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen);
         else
             memcpy(gctx->iv, iv, gctx->ivlen);
         gctx->iv_set = 1;
         gctx->iv_gen = 0;
     }
     return 1;
 }
 
 #  define aesni_gcm_cipher aes_gcm_cipher
 static int aesni_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                             const unsigned char *in, size_t len);
 
 static int aesni_xts_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
                               const unsigned char *iv, int enc)
 {
     EVP_AES_XTS_CTX *xctx = ctx->cipher_data;
     if (!iv && !key)
         return 1;
 
     if (key) {
         /* key_len is two AES keys */
         if (enc) {
             aesni_set_encrypt_key(key, ctx->key_len * 4, &xctx->ks1.ks);
             xctx->xts.block1 = (block128_f) aesni_encrypt;
             xctx->stream = aesni_xts_encrypt;
         } else {
             aesni_set_decrypt_key(key, ctx->key_len * 4, &xctx->ks1.ks);
             xctx->xts.block1 = (block128_f) aesni_decrypt;
             xctx->stream = aesni_xts_decrypt;
         }
 
         aesni_set_encrypt_key(key + ctx->key_len / 2,
                               ctx->key_len * 4, &xctx->ks2.ks);
         xctx->xts.block2 = (block128_f) aesni_encrypt;
 
         xctx->xts.key1 = &xctx->ks1;
     }
 
     if (iv) {
         xctx->xts.key2 = &xctx->ks2;
         memcpy(ctx->iv, iv, 16);
     }
 
     return 1;
 }
 
 #  define aesni_xts_cipher aes_xts_cipher
 static int aesni_xts_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                             const unsigned char *in, size_t len);
 
 static int aesni_ccm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
                               const unsigned char *iv, int enc)
 {
     EVP_AES_CCM_CTX *cctx = ctx->cipher_data;
     if (!iv && !key)
         return 1;
     if (key) {
         aesni_set_encrypt_key(key, ctx->key_len * 8, &cctx->ks.ks);
         CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L,
                            &cctx->ks, (block128_f) aesni_encrypt);
         cctx->str = enc ? (ccm128_f) aesni_ccm64_encrypt_blocks :
             (ccm128_f) aesni_ccm64_decrypt_blocks;
         cctx->key_set = 1;
     }
     if (iv) {
         memcpy(ctx->iv, iv, 15 - cctx->L);
         cctx->iv_set = 1;
     }
     return 1;
 }
 
 #  define aesni_ccm_cipher aes_ccm_cipher
 static int aesni_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                             const unsigned char *in, size_t len);
 
 #  define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \
 static const EVP_CIPHER aesni_##keylen##_##mode = { \
         nid##_##keylen##_##nmode,blocksize,keylen/8,ivlen, \
         flags|EVP_CIPH_##MODE##_MODE,   \
         aesni_init_key,                 \
         aesni_##mode##_cipher,          \
         NULL,                           \
         sizeof(EVP_AES_KEY),            \
         NULL,NULL,NULL,NULL }; \
 static const EVP_CIPHER aes_##keylen##_##mode = { \
         nid##_##keylen##_##nmode,blocksize,     \
         keylen/8,ivlen, \
         flags|EVP_CIPH_##MODE##_MODE,   \
         aes_init_key,                   \
         aes_##mode##_cipher,            \
         NULL,                           \
         sizeof(EVP_AES_KEY),            \
         NULL,NULL,NULL,NULL }; \
 const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \
 { return AESNI_CAPABLE?&aesni_##keylen##_##mode:&aes_##keylen##_##mode; }
 
 #  define BLOCK_CIPHER_custom(nid,keylen,blocksize,ivlen,mode,MODE,flags) \
 static const EVP_CIPHER aesni_##keylen##_##mode = { \
         nid##_##keylen##_##mode,blocksize, \
         (EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE?2:1)*keylen/8, ivlen, \
         flags|EVP_CIPH_##MODE##_MODE,   \
         aesni_##mode##_init_key,        \
         aesni_##mode##_cipher,          \
         aes_##mode##_cleanup,           \
         sizeof(EVP_AES_##MODE##_CTX),   \
         NULL,NULL,aes_##mode##_ctrl,NULL }; \
 static const EVP_CIPHER aes_##keylen##_##mode = { \
         nid##_##keylen##_##mode,blocksize, \
         (EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE?2:1)*keylen/8, ivlen, \
         flags|EVP_CIPH_##MODE##_MODE,   \
         aes_##mode##_init_key,          \
         aes_##mode##_cipher,            \
         aes_##mode##_cleanup,           \
         sizeof(EVP_AES_##MODE##_CTX),   \
         NULL,NULL,aes_##mode##_ctrl,NULL }; \
 const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \
 { return AESNI_CAPABLE?&aesni_##keylen##_##mode:&aes_##keylen##_##mode; }
 
 # elif   defined(AES_ASM) && (defined(__sparc) || defined(__sparc__))
 
 #  include "sparc_arch.h"
 
 extern unsigned int OPENSSL_sparcv9cap_P[];
 
 #  define SPARC_AES_CAPABLE       (OPENSSL_sparcv9cap_P[1] & CFR_AES)
 
 void aes_t4_set_encrypt_key(const unsigned char *key, int bits, AES_KEY *ks);
 void aes_t4_set_decrypt_key(const unsigned char *key, int bits, AES_KEY *ks);
 void aes_t4_encrypt(const unsigned char *in, unsigned char *out,
                     const AES_KEY *key);
 void aes_t4_decrypt(const unsigned char *in, unsigned char *out,
                     const AES_KEY *key);
 /*
  * Key-length specific subroutines were chosen for following reason.
  * Each SPARC T4 core can execute up to 8 threads which share core's
  * resources. Loading as much key material to registers allows to
  * minimize references to shared memory interface, as well as amount
  * of instructions in inner loops [much needed on T4]. But then having
  * non-key-length specific routines would require conditional branches
  * either in inner loops or on subroutines' entries. Former is hardly
  * acceptable, while latter means code size increase to size occupied
  * by multiple key-length specfic subroutines, so why fight?
  */
 void aes128_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
                            size_t len, const AES_KEY *key,
                            unsigned char *ivec);
 void aes128_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
                            size_t len, const AES_KEY *key,
                            unsigned char *ivec);
 void aes192_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
                            size_t len, const AES_KEY *key,
                            unsigned char *ivec);
 void aes192_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
                            size_t len, const AES_KEY *key,
                            unsigned char *ivec);
 void aes256_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
                            size_t len, const AES_KEY *key,
                            unsigned char *ivec);
 void aes256_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
                            size_t len, const AES_KEY *key,
                            unsigned char *ivec);
 void aes128_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out,
                              size_t blocks, const AES_KEY *key,
                              unsigned char *ivec);
 void aes192_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out,
                              size_t blocks, const AES_KEY *key,
                              unsigned char *ivec);
 void aes256_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out,
                              size_t blocks, const AES_KEY *key,
                              unsigned char *ivec);
 void aes128_t4_xts_encrypt(const unsigned char *in, unsigned char *out,
                            size_t blocks, const AES_KEY *key1,
                            const AES_KEY *key2, const unsigned char *ivec);
 void aes128_t4_xts_decrypt(const unsigned char *in, unsigned char *out,
                            size_t blocks, const AES_KEY *key1,
                            const AES_KEY *key2, const unsigned char *ivec);
 void aes256_t4_xts_encrypt(const unsigned char *in, unsigned char *out,
                            size_t blocks, const AES_KEY *key1,
                            const AES_KEY *key2, const unsigned char *ivec);
 void aes256_t4_xts_decrypt(const unsigned char *in, unsigned char *out,
                            size_t blocks, const AES_KEY *key1,
                            const AES_KEY *key2, const unsigned char *ivec);
 
 static int aes_t4_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
                            const unsigned char *iv, int enc)
 {
     int ret, mode, bits;
     EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
 
     mode = ctx->cipher->flags & EVP_CIPH_MODE;
     bits = ctx->key_len * 8;
     if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE)
         && !enc) {
         ret = 0;
         aes_t4_set_decrypt_key(key, bits, ctx->cipher_data);
         dat->block = (block128_f) aes_t4_decrypt;
         switch (bits) {
         case 128:
             dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
                 (cbc128_f) aes128_t4_cbc_decrypt : NULL;
             break;
         case 192:
             dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
                 (cbc128_f) aes192_t4_cbc_decrypt : NULL;
             break;
         case 256:
             dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
                 (cbc128_f) aes256_t4_cbc_decrypt : NULL;
             break;
         default:
             ret = -1;
         }
     } else {
         ret = 0;
         aes_t4_set_encrypt_key(key, bits, ctx->cipher_data);
         dat->block = (block128_f) aes_t4_encrypt;
         switch (bits) {
         case 128:
             if (mode == EVP_CIPH_CBC_MODE)
                 dat->stream.cbc = (cbc128_f) aes128_t4_cbc_encrypt;
             else if (mode == EVP_CIPH_CTR_MODE)
                 dat->stream.ctr = (ctr128_f) aes128_t4_ctr32_encrypt;
             else
                 dat->stream.cbc = NULL;
             break;
         case 192:
             if (mode == EVP_CIPH_CBC_MODE)
                 dat->stream.cbc = (cbc128_f) aes192_t4_cbc_encrypt;
             else if (mode == EVP_CIPH_CTR_MODE)
                 dat->stream.ctr = (ctr128_f) aes192_t4_ctr32_encrypt;
             else
                 dat->stream.cbc = NULL;
             break;
         case 256:
             if (mode == EVP_CIPH_CBC_MODE)
                 dat->stream.cbc = (cbc128_f) aes256_t4_cbc_encrypt;
             else if (mode == EVP_CIPH_CTR_MODE)
                 dat->stream.ctr = (ctr128_f) aes256_t4_ctr32_encrypt;
             else
                 dat->stream.cbc = NULL;
             break;
         default:
             ret = -1;
         }
     }
 
     if (ret < 0) {
         EVPerr(EVP_F_AES_T4_INIT_KEY, EVP_R_AES_KEY_SETUP_FAILED);
         return 0;
     }
 
     return 1;
 }
 
 #  define aes_t4_cbc_cipher aes_cbc_cipher
 static int aes_t4_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                              const unsigned char *in, size_t len);
 
 #  define aes_t4_ecb_cipher aes_ecb_cipher
 static int aes_t4_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                              const unsigned char *in, size_t len);
 
 #  define aes_t4_ofb_cipher aes_ofb_cipher
 static int aes_t4_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                              const unsigned char *in, size_t len);
 
 #  define aes_t4_cfb_cipher aes_cfb_cipher
 static int aes_t4_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                              const unsigned char *in, size_t len);
 
 #  define aes_t4_cfb8_cipher aes_cfb8_cipher
 static int aes_t4_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                               const unsigned char *in, size_t len);
 
 #  define aes_t4_cfb1_cipher aes_cfb1_cipher
 static int aes_t4_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                               const unsigned char *in, size_t len);
 
 #  define aes_t4_ctr_cipher aes_ctr_cipher
 static int aes_t4_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                              const unsigned char *in, size_t len);
 
 static int aes_t4_gcm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
                                const unsigned char *iv, int enc)
 {
     EVP_AES_GCM_CTX *gctx = ctx->cipher_data;
     if (!iv && !key)
         return 1;
     if (key) {
         int bits = ctx->key_len * 8;
         aes_t4_set_encrypt_key(key, bits, &gctx->ks.ks);
         CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks,
                            (block128_f) aes_t4_encrypt);
         switch (bits) {
         case 128:
             gctx->ctr = (ctr128_f) aes128_t4_ctr32_encrypt;
             break;
         case 192:
             gctx->ctr = (ctr128_f) aes192_t4_ctr32_encrypt;
             break;
         case 256:
             gctx->ctr = (ctr128_f) aes256_t4_ctr32_encrypt;
             break;
         default:
             return 0;
         }
         /*
          * If we have an iv can set it directly, otherwise use saved IV.
          */
         if (iv == NULL && gctx->iv_set)
             iv = gctx->iv;
         if (iv) {
             CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen);
             gctx->iv_set = 1;
         }
         gctx->key_set = 1;
     } else {
         /* If key set use IV, otherwise copy */
         if (gctx->key_set)
             CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen);
         else
             memcpy(gctx->iv, iv, gctx->ivlen);
         gctx->iv_set = 1;
         gctx->iv_gen = 0;
     }
     return 1;
 }
 
 #  define aes_t4_gcm_cipher aes_gcm_cipher
 static int aes_t4_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                              const unsigned char *in, size_t len);
 
 static int aes_t4_xts_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
                                const unsigned char *iv, int enc)
 {
     EVP_AES_XTS_CTX *xctx = ctx->cipher_data;
     if (!iv && !key)
         return 1;
 
     if (key) {
         int bits = ctx->key_len * 4;
         xctx->stream = NULL;
         /* key_len is two AES keys */
         if (enc) {
             aes_t4_set_encrypt_key(key, bits, &xctx->ks1.ks);
             xctx->xts.block1 = (block128_f) aes_t4_encrypt;
             switch (bits) {
             case 128:
                 xctx->stream = aes128_t4_xts_encrypt;
                 break;
 #  if 0                         /* not yet */
             case 192:
                 xctx->stream = aes192_t4_xts_encrypt;
                 break;
 #  endif
             case 256:
                 xctx->stream = aes256_t4_xts_encrypt;
                 break;
             default:
                 return 0;
             }
         } else {
             aes_t4_set_decrypt_key(key, ctx->key_len * 4, &xctx->ks1.ks);
             xctx->xts.block1 = (block128_f) aes_t4_decrypt;
             switch (bits) {
             case 128:
                 xctx->stream = aes128_t4_xts_decrypt;
                 break;
 #  if 0                         /* not yet */
             case 192:
                 xctx->stream = aes192_t4_xts_decrypt;
                 break;
 #  endif
             case 256:
                 xctx->stream = aes256_t4_xts_decrypt;
                 break;
             default:
                 return 0;
             }
         }
 
         aes_t4_set_encrypt_key(key + ctx->key_len / 2,
                                ctx->key_len * 4, &xctx->ks2.ks);
         xctx->xts.block2 = (block128_f) aes_t4_encrypt;
 
         xctx->xts.key1 = &xctx->ks1;
     }
 
     if (iv) {
         xctx->xts.key2 = &xctx->ks2;
         memcpy(ctx->iv, iv, 16);
     }
 
     return 1;
 }
 
 #  define aes_t4_xts_cipher aes_xts_cipher
 static int aes_t4_xts_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                              const unsigned char *in, size_t len);
 
 static int aes_t4_ccm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
                                const unsigned char *iv, int enc)
 {
     EVP_AES_CCM_CTX *cctx = ctx->cipher_data;
     if (!iv && !key)
         return 1;
     if (key) {
         int bits = ctx->key_len * 8;
         aes_t4_set_encrypt_key(key, bits, &cctx->ks.ks);
         CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L,
                            &cctx->ks, (block128_f) aes_t4_encrypt);
 #  if 0                         /* not yet */
         switch (bits) {
         case 128:
             cctx->str = enc ? (ccm128_f) aes128_t4_ccm64_encrypt :
                 (ccm128_f) ae128_t4_ccm64_decrypt;
             break;
         case 192:
             cctx->str = enc ? (ccm128_f) aes192_t4_ccm64_encrypt :
                 (ccm128_f) ae192_t4_ccm64_decrypt;
             break;
         case 256:
             cctx->str = enc ? (ccm128_f) aes256_t4_ccm64_encrypt :
                 (ccm128_f) ae256_t4_ccm64_decrypt;
             break;
         default:
             return 0;
         }
 #  else
         cctx->str = NULL;
 #  endif
         cctx->key_set = 1;
     }
     if (iv) {
         memcpy(ctx->iv, iv, 15 - cctx->L);
         cctx->iv_set = 1;
     }
     return 1;
 }
 
 #  define aes_t4_ccm_cipher aes_ccm_cipher
 static int aes_t4_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                              const unsigned char *in, size_t len);
 
 #  define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \
 static const EVP_CIPHER aes_t4_##keylen##_##mode = { \
         nid##_##keylen##_##nmode,blocksize,keylen/8,ivlen, \
         flags|EVP_CIPH_##MODE##_MODE,   \
         aes_t4_init_key,                \
         aes_t4_##mode##_cipher,         \
         NULL,                           \
         sizeof(EVP_AES_KEY),            \
         NULL,NULL,NULL,NULL }; \
 static const EVP_CIPHER aes_##keylen##_##mode = { \
         nid##_##keylen##_##nmode,blocksize,     \
         keylen/8,ivlen, \
         flags|EVP_CIPH_##MODE##_MODE,   \
         aes_init_key,                   \
         aes_##mode##_cipher,            \
         NULL,                           \
         sizeof(EVP_AES_KEY),            \
         NULL,NULL,NULL,NULL }; \
 const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \
 { return SPARC_AES_CAPABLE?&aes_t4_##keylen##_##mode:&aes_##keylen##_##mode; }
 
 #  define BLOCK_CIPHER_custom(nid,keylen,blocksize,ivlen,mode,MODE,flags) \
 static const EVP_CIPHER aes_t4_##keylen##_##mode = { \
         nid##_##keylen##_##mode,blocksize, \
         (EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE?2:1)*keylen/8, ivlen, \
         flags|EVP_CIPH_##MODE##_MODE,   \
         aes_t4_##mode##_init_key,       \
         aes_t4_##mode##_cipher,         \
         aes_##mode##_cleanup,           \
         sizeof(EVP_AES_##MODE##_CTX),   \
         NULL,NULL,aes_##mode##_ctrl,NULL }; \
 static const EVP_CIPHER aes_##keylen##_##mode = { \
         nid##_##keylen##_##mode,blocksize, \
         (EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE?2:1)*keylen/8, ivlen, \
         flags|EVP_CIPH_##MODE##_MODE,   \
         aes_##mode##_init_key,          \
         aes_##mode##_cipher,            \
         aes_##mode##_cleanup,           \
         sizeof(EVP_AES_##MODE##_CTX),   \
         NULL,NULL,aes_##mode##_ctrl,NULL }; \
 const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \
 { return SPARC_AES_CAPABLE?&aes_t4_##keylen##_##mode:&aes_##keylen##_##mode; }
 
 # else
 
 #  define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \
 static const EVP_CIPHER aes_##keylen##_##mode = { \
         nid##_##keylen##_##nmode,blocksize,keylen/8,ivlen, \
         flags|EVP_CIPH_##MODE##_MODE,   \
         aes_init_key,                   \
         aes_##mode##_cipher,            \
         NULL,                           \
         sizeof(EVP_AES_KEY),            \
         NULL,NULL,NULL,NULL }; \
 const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \
 { return &aes_##keylen##_##mode; }
 
 #  define BLOCK_CIPHER_custom(nid,keylen,blocksize,ivlen,mode,MODE,flags) \
 static const EVP_CIPHER aes_##keylen##_##mode = { \
         nid##_##keylen##_##mode,blocksize, \
         (EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE?2:1)*keylen/8, ivlen, \
         flags|EVP_CIPH_##MODE##_MODE,   \
         aes_##mode##_init_key,          \
         aes_##mode##_cipher,            \
         aes_##mode##_cleanup,           \
         sizeof(EVP_AES_##MODE##_CTX),   \
         NULL,NULL,aes_##mode##_ctrl,NULL }; \
 const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \
 { return &aes_##keylen##_##mode; }
 # endif
 
 # if defined(OPENSSL_CPUID_OBJ) && (defined(__arm__) || defined(__arm) || defined(__aarch64__))
 #  include "arm_arch.h"
 #  if __ARM_MAX_ARCH__>=7
 #   if defined(BSAES_ASM)
 #    define BSAES_CAPABLE (OPENSSL_armcap_P & ARMV7_NEON)
 #   endif
 #   define HWAES_CAPABLE (OPENSSL_armcap_P & ARMV8_AES)
 #   define HWAES_set_encrypt_key aes_v8_set_encrypt_key
 #   define HWAES_set_decrypt_key aes_v8_set_decrypt_key
 #   define HWAES_encrypt aes_v8_encrypt
 #   define HWAES_decrypt aes_v8_decrypt
 #   define HWAES_cbc_encrypt aes_v8_cbc_encrypt
 #   define HWAES_ctr32_encrypt_blocks aes_v8_ctr32_encrypt_blocks
 #  endif
 # endif
 
 # if defined(HWAES_CAPABLE)
 int HWAES_set_encrypt_key(const unsigned char *userKey, const int bits,
                           AES_KEY *key);
 int HWAES_set_decrypt_key(const unsigned char *userKey, const int bits,
                           AES_KEY *key);
 void HWAES_encrypt(const unsigned char *in, unsigned char *out,
                    const AES_KEY *key);
 void HWAES_decrypt(const unsigned char *in, unsigned char *out,
                    const AES_KEY *key);
 void HWAES_cbc_encrypt(const unsigned char *in, unsigned char *out,
                        size_t length, const AES_KEY *key,
                        unsigned char *ivec, const int enc);
 void HWAES_ctr32_encrypt_blocks(const unsigned char *in, unsigned char *out,
                                 size_t len, const AES_KEY *key,
                                 const unsigned char ivec[16]);
 # endif
 
 # define BLOCK_CIPHER_generic_pack(nid,keylen,flags)             \
         BLOCK_CIPHER_generic(nid,keylen,16,16,cbc,cbc,CBC,flags|EVP_CIPH_FLAG_DEFAULT_ASN1)     \
         BLOCK_CIPHER_generic(nid,keylen,16,0,ecb,ecb,ECB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1)      \
         BLOCK_CIPHER_generic(nid,keylen,1,16,ofb128,ofb,OFB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1)   \
         BLOCK_CIPHER_generic(nid,keylen,1,16,cfb128,cfb,CFB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1)   \
         BLOCK_CIPHER_generic(nid,keylen,1,16,cfb1,cfb1,CFB,flags)       \
         BLOCK_CIPHER_generic(nid,keylen,1,16,cfb8,cfb8,CFB,flags)       \
         BLOCK_CIPHER_generic(nid,keylen,1,16,ctr,ctr,CTR,flags)
 
 static int aes_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
                         const unsigned char *iv, int enc)
 {
     int ret, mode;
     EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
 
     mode = ctx->cipher->flags & EVP_CIPH_MODE;
     if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE)
         && !enc)
 # ifdef HWAES_CAPABLE
         if (HWAES_CAPABLE) {
             ret = HWAES_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
             dat->block = (block128_f) HWAES_decrypt;
             dat->stream.cbc = NULL;
 #  ifdef HWAES_cbc_encrypt
             if (mode == EVP_CIPH_CBC_MODE)
                 dat->stream.cbc = (cbc128_f) HWAES_cbc_encrypt;
 #  endif
         } else
 # endif
 # ifdef BSAES_CAPABLE
         if (BSAES_CAPABLE && mode == EVP_CIPH_CBC_MODE) {
             ret = AES_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
             dat->block = (block128_f) AES_decrypt;
             dat->stream.cbc = (cbc128_f) bsaes_cbc_encrypt;
         } else
 # endif
 # ifdef VPAES_CAPABLE
         if (VPAES_CAPABLE) {
             ret = vpaes_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
             dat->block = (block128_f) vpaes_decrypt;
             dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
                 (cbc128_f) vpaes_cbc_encrypt : NULL;
         } else
 # endif
         {
             ret = AES_set_decrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
             dat->block = (block128_f) AES_decrypt;
             dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
                 (cbc128_f) AES_cbc_encrypt : NULL;
     } else
 # ifdef HWAES_CAPABLE
     if (HWAES_CAPABLE) {
         ret = HWAES_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
         dat->block = (block128_f) HWAES_encrypt;
         dat->stream.cbc = NULL;
 #  ifdef HWAES_cbc_encrypt
         if (mode == EVP_CIPH_CBC_MODE)
             dat->stream.cbc = (cbc128_f) HWAES_cbc_encrypt;
         else
 #  endif
 #  ifdef HWAES_ctr32_encrypt_blocks
         if (mode == EVP_CIPH_CTR_MODE)
             dat->stream.ctr = (ctr128_f) HWAES_ctr32_encrypt_blocks;
         else
 #  endif
             (void)0;            /* terminate potentially open 'else' */
     } else
 # endif
 # ifdef BSAES_CAPABLE
     if (BSAES_CAPABLE && mode == EVP_CIPH_CTR_MODE) {
         ret = AES_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
         dat->block = (block128_f) AES_encrypt;
         dat->stream.ctr = (ctr128_f) bsaes_ctr32_encrypt_blocks;
     } else
 # endif
 # ifdef VPAES_CAPABLE
     if (VPAES_CAPABLE) {
         ret = vpaes_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
         dat->block = (block128_f) vpaes_encrypt;
         dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
             (cbc128_f) vpaes_cbc_encrypt : NULL;
     } else
 # endif
     {
         ret = AES_set_encrypt_key(key, ctx->key_len * 8, &dat->ks.ks);
         dat->block = (block128_f) AES_encrypt;
         dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ?
             (cbc128_f) AES_cbc_encrypt : NULL;
 # ifdef AES_CTR_ASM
         if (mode == EVP_CIPH_CTR_MODE)
             dat->stream.ctr = (ctr128_f) AES_ctr32_encrypt;
 # endif
     }
 
     if (ret < 0) {
         EVPerr(EVP_F_AES_INIT_KEY, EVP_R_AES_KEY_SETUP_FAILED);
         return 0;
     }
 
     return 1;
 }
 
 static int aes_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                           const unsigned char *in, size_t len)
 {
     EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
 
     if (dat->stream.cbc)
         (*dat->stream.cbc) (in, out, len, &dat->ks, ctx->iv, ctx->encrypt);
     else if (ctx->encrypt)
         CRYPTO_cbc128_encrypt(in, out, len, &dat->ks, ctx->iv, dat->block);
     else
         CRYPTO_cbc128_decrypt(in, out, len, &dat->ks, ctx->iv, dat->block);
 
     return 1;
 }
 
 static int aes_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                           const unsigned char *in, size_t len)
 {
     size_t bl = ctx->cipher->block_size;
     size_t i;
     EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
 
     if (len < bl)
         return 1;
 
     for (i = 0, len -= bl; i <= len; i += bl)
         (*dat->block) (in + i, out + i, &dat->ks);
 
     return 1;
 }
 
 static int aes_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                           const unsigned char *in, size_t len)
 {
     EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
 
     CRYPTO_ofb128_encrypt(in, out, len, &dat->ks,
                           ctx->iv, &ctx->num, dat->block);
     return 1;
 }
 
 static int aes_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                           const unsigned char *in, size_t len)
 {
     EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
 
     CRYPTO_cfb128_encrypt(in, out, len, &dat->ks,
                           ctx->iv, &ctx->num, ctx->encrypt, dat->block);
     return 1;
 }
 
 static int aes_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                            const unsigned char *in, size_t len)
 {
     EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
 
     CRYPTO_cfb128_8_encrypt(in, out, len, &dat->ks,
                             ctx->iv, &ctx->num, ctx->encrypt, dat->block);
     return 1;
 }
 
 static int aes_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                            const unsigned char *in, size_t len)
 {
     EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
 
     if (ctx->flags & EVP_CIPH_FLAG_LENGTH_BITS) {
         CRYPTO_cfb128_1_encrypt(in, out, len, &dat->ks,
                                 ctx->iv, &ctx->num, ctx->encrypt, dat->block);
         return 1;
     }
 
     while (len >= MAXBITCHUNK) {
         CRYPTO_cfb128_1_encrypt(in, out, MAXBITCHUNK * 8, &dat->ks,
                                 ctx->iv, &ctx->num, ctx->encrypt, dat->block);
         len -= MAXBITCHUNK;
     }
     if (len)
         CRYPTO_cfb128_1_encrypt(in, out, len * 8, &dat->ks,
                                 ctx->iv, &ctx->num, ctx->encrypt, dat->block);
 
     return 1;
 }
 
 static int aes_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                           const unsigned char *in, size_t len)
 {
     unsigned int num = ctx->num;
     EVP_AES_KEY *dat = (EVP_AES_KEY *) ctx->cipher_data;
 
     if (dat->stream.ctr)
         CRYPTO_ctr128_encrypt_ctr32(in, out, len, &dat->ks,
                                     ctx->iv, ctx->buf, &num, dat->stream.ctr);
     else
         CRYPTO_ctr128_encrypt(in, out, len, &dat->ks,
                               ctx->iv, ctx->buf, &num, dat->block);
     ctx->num = (size_t)num;
     return 1;
 }
 
 BLOCK_CIPHER_generic_pack(NID_aes, 128, EVP_CIPH_FLAG_FIPS)
     BLOCK_CIPHER_generic_pack(NID_aes, 192, EVP_CIPH_FLAG_FIPS)
     BLOCK_CIPHER_generic_pack(NID_aes, 256, EVP_CIPH_FLAG_FIPS)
 
 static int aes_gcm_cleanup(EVP_CIPHER_CTX *c)
 {
     EVP_AES_GCM_CTX *gctx = c->cipher_data;
+    if (gctx == NULL)
+        return 0;
     OPENSSL_cleanse(&gctx->gcm, sizeof(gctx->gcm));
     if (gctx->iv != c->iv)
         OPENSSL_free(gctx->iv);
     return 1;
 }
 
 /* increment counter (64-bit int) by 1 */
 static void ctr64_inc(unsigned char *counter)
 {
     int n = 8;
     unsigned char c;
 
     do {
         --n;
         c = counter[n];
         ++c;
         counter[n] = c;
         if (c)
             return;
     } while (n);
 }
 
 static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)
 {
     EVP_AES_GCM_CTX *gctx = c->cipher_data;
     switch (type) {
     case EVP_CTRL_INIT:
         gctx->key_set = 0;
         gctx->iv_set = 0;
         gctx->ivlen = c->cipher->iv_len;
         gctx->iv = c->iv;
         gctx->taglen = -1;
         gctx->iv_gen = 0;
         gctx->tls_aad_len = -1;
         return 1;
 
     case EVP_CTRL_GCM_SET_IVLEN:
         if (arg <= 0)
             return 0;
         /* Allocate memory for IV if needed */
         if ((arg > EVP_MAX_IV_LENGTH) && (arg > gctx->ivlen)) {
             if (gctx->iv != c->iv)
                 OPENSSL_free(gctx->iv);
             gctx->iv = OPENSSL_malloc(arg);
             if (!gctx->iv)
                 return 0;
         }
         gctx->ivlen = arg;
         return 1;
 
     case EVP_CTRL_GCM_SET_TAG:
         if (arg <= 0 || arg > 16 || c->encrypt)
             return 0;
         memcpy(c->buf, ptr, arg);
         gctx->taglen = arg;
         return 1;
 
     case EVP_CTRL_GCM_GET_TAG:
         if (arg <= 0 || arg > 16 || !c->encrypt || gctx->taglen < 0)
             return 0;
         memcpy(ptr, c->buf, arg);
         return 1;
 
     case EVP_CTRL_GCM_SET_IV_FIXED:
         /* Special case: -1 length restores whole IV */
         if (arg == -1) {
             memcpy(gctx->iv, ptr, gctx->ivlen);
             gctx->iv_gen = 1;
             return 1;
         }
         /*
          * Fixed field must be at least 4 bytes and invocation field at least
          * 8.
          */
         if ((arg < 4) || (gctx->ivlen - arg) < 8)
             return 0;
         if (arg)
             memcpy(gctx->iv, ptr, arg);
         if (c->encrypt && RAND_bytes(gctx->iv + arg, gctx->ivlen - arg) <= 0)
             return 0;
         gctx->iv_gen = 1;
         return 1;
 
     case EVP_CTRL_GCM_IV_GEN:
         if (gctx->iv_gen == 0 || gctx->key_set == 0)
             return 0;
         CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen);
         if (arg <= 0 || arg > gctx->ivlen)
             arg = gctx->ivlen;
         memcpy(ptr, gctx->iv + gctx->ivlen - arg, arg);
         /*
          * Invocation field will be at least 8 bytes in size and so no need
          * to check wrap around or increment more than last 8 bytes.
          */
         ctr64_inc(gctx->iv + gctx->ivlen - 8);
         gctx->iv_set = 1;
         return 1;
 
     case EVP_CTRL_GCM_SET_IV_INV:
         if (gctx->iv_gen == 0 || gctx->key_set == 0 || c->encrypt)
             return 0;
         memcpy(gctx->iv + gctx->ivlen - arg, ptr, arg);
         CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen);
         gctx->iv_set = 1;
         return 1;
 
     case EVP_CTRL_AEAD_TLS1_AAD:
         /* Save the AAD for later use */
         if (arg != EVP_AEAD_TLS1_AAD_LEN)
             return 0;
         memcpy(c->buf, ptr, arg);
         gctx->tls_aad_len = arg;
         {
             unsigned int len = c->buf[arg - 2] << 8 | c->buf[arg - 1];
             /* Correct length for explicit IV */
+            if (len < EVP_GCM_TLS_EXPLICIT_IV_LEN)
+                return 0;
             len -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
             /* If decrypting correct for tag too */
-            if (!c->encrypt)
+            if (!c->encrypt) {
+                if (len < EVP_GCM_TLS_TAG_LEN)
+                    return 0;
                 len -= EVP_GCM_TLS_TAG_LEN;
+            }
             c->buf[arg - 2] = len >> 8;
             c->buf[arg - 1] = len & 0xff;
         }
         /* Extra padding: tag appended to record */
         return EVP_GCM_TLS_TAG_LEN;
 
     case EVP_CTRL_COPY:
         {
             EVP_CIPHER_CTX *out = ptr;
             EVP_AES_GCM_CTX *gctx_out = out->cipher_data;
             if (gctx->gcm.key) {
                 if (gctx->gcm.key != &gctx->ks)
                     return 0;
                 gctx_out->gcm.key = &gctx_out->ks;
             }
             if (gctx->iv == c->iv)
                 gctx_out->iv = out->iv;
             else {
                 gctx_out->iv = OPENSSL_malloc(gctx->ivlen);
                 if (!gctx_out->iv)
                     return 0;
                 memcpy(gctx_out->iv, gctx->iv, gctx->ivlen);
             }
             return 1;
         }
 
     default:
         return -1;
 
     }
 }
 
 static int aes_gcm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
                             const unsigned char *iv, int enc)
 {
     EVP_AES_GCM_CTX *gctx = ctx->cipher_data;
     if (!iv && !key)
         return 1;
     if (key) {
         do {
 # ifdef HWAES_CAPABLE
             if (HWAES_CAPABLE) {
                 HWAES_set_encrypt_key(key, ctx->key_len * 8, &gctx->ks.ks);
                 CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks,
                                    (block128_f) HWAES_encrypt);
 #  ifdef HWAES_ctr32_encrypt_blocks
                 gctx->ctr = (ctr128_f) HWAES_ctr32_encrypt_blocks;
 #  else
                 gctx->ctr = NULL;
 #  endif
                 break;
             } else
 # endif
 # ifdef BSAES_CAPABLE
             if (BSAES_CAPABLE) {
                 AES_set_encrypt_key(key, ctx->key_len * 8, &gctx->ks.ks);
                 CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks,
                                    (block128_f) AES_encrypt);
                 gctx->ctr = (ctr128_f) bsaes_ctr32_encrypt_blocks;
                 break;
             } else
 # endif
 # ifdef VPAES_CAPABLE
             if (VPAES_CAPABLE) {
                 vpaes_set_encrypt_key(key, ctx->key_len * 8, &gctx->ks.ks);
                 CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks,
                                    (block128_f) vpaes_encrypt);
                 gctx->ctr = NULL;
                 break;
             } else
 # endif
                 (void)0;        /* terminate potentially open 'else' */
 
             AES_set_encrypt_key(key, ctx->key_len * 8, &gctx->ks.ks);
             CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks,
                                (block128_f) AES_encrypt);
 # ifdef AES_CTR_ASM
             gctx->ctr = (ctr128_f) AES_ctr32_encrypt;
 # else
             gctx->ctr = NULL;
 # endif
         } while (0);
 
         /*
          * If we have an iv can set it directly, otherwise use saved IV.
          */
         if (iv == NULL && gctx->iv_set)
             iv = gctx->iv;
         if (iv) {
             CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen);
             gctx->iv_set = 1;
         }
         gctx->key_set = 1;
     } else {
         /* If key set use IV, otherwise copy */
         if (gctx->key_set)
             CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen);
         else
             memcpy(gctx->iv, iv, gctx->ivlen);
         gctx->iv_set = 1;
         gctx->iv_gen = 0;
     }
     return 1;
 }
 
 /*
  * Handle TLS GCM packet format. This consists of the last portion of the IV
  * followed by the payload and finally the tag. On encrypt generate IV,
  * encrypt payload and write the tag. On verify retrieve IV, decrypt payload
  * and verify tag.
  */
 
 static int aes_gcm_tls_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                               const unsigned char *in, size_t len)
 {
     EVP_AES_GCM_CTX *gctx = ctx->cipher_data;
     int rv = -1;
     /* Encrypt/decrypt must be performed in place */
     if (out != in
         || len < (EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN))
         return -1;
     /*
      * Set IV from start of buffer or generate IV and write to start of
      * buffer.
      */
     if (EVP_CIPHER_CTX_ctrl(ctx, ctx->encrypt ?
                             EVP_CTRL_GCM_IV_GEN : EVP_CTRL_GCM_SET_IV_INV,
                             EVP_GCM_TLS_EXPLICIT_IV_LEN, out) <= 0)
         goto err;
     /* Use saved AAD */
     if (CRYPTO_gcm128_aad(&gctx->gcm, ctx->buf, gctx->tls_aad_len))
         goto err;
     /* Fix buffer and length to point to payload */
     in += EVP_GCM_TLS_EXPLICIT_IV_LEN;
     out += EVP_GCM_TLS_EXPLICIT_IV_LEN;
     len -= EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN;
     if (ctx->encrypt) {
         /* Encrypt payload */
         if (gctx->ctr) {
             size_t bulk = 0;
 # if defined(AES_GCM_ASM)
             if (len >= 32 && AES_GCM_ASM(gctx)) {
                 if (CRYPTO_gcm128_encrypt(&gctx->gcm, NULL, NULL, 0))
                     return -1;
 
                 bulk = AES_gcm_encrypt(in, out, len,
                                        gctx->gcm.key,
                                        gctx->gcm.Yi.c, gctx->gcm.Xi.u);
                 gctx->gcm.len.u[1] += bulk;
             }
 # endif
             if (CRYPTO_gcm128_encrypt_ctr32(&gctx->gcm,
                                             in + bulk,
                                             out + bulk,
                                             len - bulk, gctx->ctr))
                 goto err;
         } else {
             size_t bulk = 0;
 # if defined(AES_GCM_ASM2)
             if (len >= 32 && AES_GCM_ASM2(gctx)) {
                 if (CRYPTO_gcm128_encrypt(&gctx->gcm, NULL, NULL, 0))
                     return -1;
 
                 bulk = AES_gcm_encrypt(in, out, len,
                                        gctx->gcm.key,
                                        gctx->gcm.Yi.c, gctx->gcm.Xi.u);
                 gctx->gcm.len.u[1] += bulk;
             }
 # endif
             if (CRYPTO_gcm128_encrypt(&gctx->gcm,
                                       in + bulk, out + bulk, len - bulk))
                 goto err;
         }
         out += len;
         /* Finally write tag */
         CRYPTO_gcm128_tag(&gctx->gcm, out, EVP_GCM_TLS_TAG_LEN);
         rv = len + EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN;
     } else {
         /* Decrypt */
         if (gctx->ctr) {
             size_t bulk = 0;
 # if defined(AES_GCM_ASM)
             if (len >= 16 && AES_GCM_ASM(gctx)) {
                 if (CRYPTO_gcm128_decrypt(&gctx->gcm, NULL, NULL, 0))
                     return -1;
 
                 bulk = AES_gcm_decrypt(in, out, len,
                                        gctx->gcm.key,
                                        gctx->gcm.Yi.c, gctx->gcm.Xi.u);
                 gctx->gcm.len.u[1] += bulk;
             }
 # endif
             if (CRYPTO_gcm128_decrypt_ctr32(&gctx->gcm,
                                             in + bulk,
                                             out + bulk,
                                             len - bulk, gctx->ctr))
                 goto err;
         } else {
             size_t bulk = 0;
 # if defined(AES_GCM_ASM2)
             if (len >= 16 && AES_GCM_ASM2(gctx)) {
                 if (CRYPTO_gcm128_decrypt(&gctx->gcm, NULL, NULL, 0))
                     return -1;
 
                 bulk = AES_gcm_decrypt(in, out, len,
                                        gctx->gcm.key,
                                        gctx->gcm.Yi.c, gctx->gcm.Xi.u);
                 gctx->gcm.len.u[1] += bulk;
             }
 # endif
             if (CRYPTO_gcm128_decrypt(&gctx->gcm,
                                       in + bulk, out + bulk, len - bulk))
                 goto err;
         }
         /* Retrieve tag */
         CRYPTO_gcm128_tag(&gctx->gcm, ctx->buf, EVP_GCM_TLS_TAG_LEN);
         /* If tag mismatch wipe buffer */
         if (CRYPTO_memcmp(ctx->buf, in + len, EVP_GCM_TLS_TAG_LEN)) {
             OPENSSL_cleanse(out, len);
             goto err;
         }
         rv = len;
     }
 
  err:
     gctx->iv_set = 0;
     gctx->tls_aad_len = -1;
     return rv;
 }
 
 static int aes_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                           const unsigned char *in, size_t len)
 {
     EVP_AES_GCM_CTX *gctx = ctx->cipher_data;
     /* If not set up, return error */
     if (!gctx->key_set)
         return -1;
 
     if (gctx->tls_aad_len >= 0)
         return aes_gcm_tls_cipher(ctx, out, in, len);
 
     if (!gctx->iv_set)
         return -1;
     if (in) {
         if (out == NULL) {
             if (CRYPTO_gcm128_aad(&gctx->gcm, in, len))
                 return -1;
         } else if (ctx->encrypt) {
             if (gctx->ctr) {
                 size_t bulk = 0;
 # if defined(AES_GCM_ASM)
                 if (len >= 32 && AES_GCM_ASM(gctx)) {
                     size_t res = (16 - gctx->gcm.mres) % 16;
 
                     if (CRYPTO_gcm128_encrypt(&gctx->gcm, in, out, res))
                         return -1;
 
                     bulk = AES_gcm_encrypt(in + res,
                                            out + res, len - res,
                                            gctx->gcm.key, gctx->gcm.Yi.c,
                                            gctx->gcm.Xi.u);
                     gctx->gcm.len.u[1] += bulk;
                     bulk += res;
                 }
 # endif
                 if (CRYPTO_gcm128_encrypt_ctr32(&gctx->gcm,
                                                 in + bulk,
                                                 out + bulk,
                                                 len - bulk, gctx->ctr))
                     return -1;
             } else {
                 size_t bulk = 0;
 # if defined(AES_GCM_ASM2)
                 if (len >= 32 && AES_GCM_ASM2(gctx)) {
                     size_t res = (16 - gctx->gcm.mres) % 16;
 
                     if (CRYPTO_gcm128_encrypt(&gctx->gcm, in, out, res))
                         return -1;
 
                     bulk = AES_gcm_encrypt(in + res,
                                            out + res, len - res,
                                            gctx->gcm.key, gctx->gcm.Yi.c,
                                            gctx->gcm.Xi.u);
                     gctx->gcm.len.u[1] += bulk;
                     bulk += res;
                 }
 # endif
                 if (CRYPTO_gcm128_encrypt(&gctx->gcm,
                                           in + bulk, out + bulk, len - bulk))
                     return -1;
             }
         } else {
             if (gctx->ctr) {
                 size_t bulk = 0;
 # if defined(AES_GCM_ASM)
                 if (len >= 16 && AES_GCM_ASM(gctx)) {
                     size_t res = (16 - gctx->gcm.mres) % 16;
 
                     if (CRYPTO_gcm128_decrypt(&gctx->gcm, in, out, res))
                         return -1;
 
                     bulk = AES_gcm_decrypt(in + res,
                                            out + res, len - res,
                                            gctx->gcm.key,
                                            gctx->gcm.Yi.c, gctx->gcm.Xi.u);
                     gctx->gcm.len.u[1] += bulk;
                     bulk += res;
                 }
 # endif
                 if (CRYPTO_gcm128_decrypt_ctr32(&gctx->gcm,
                                                 in + bulk,
                                                 out + bulk,
                                                 len - bulk, gctx->ctr))
                     return -1;
             } else {
                 size_t bulk = 0;
 # if defined(AES_GCM_ASM2)
                 if (len >= 16 && AES_GCM_ASM2(gctx)) {
                     size_t res = (16 - gctx->gcm.mres) % 16;
 
                     if (CRYPTO_gcm128_decrypt(&gctx->gcm, in, out, res))
                         return -1;
 
                     bulk = AES_gcm_decrypt(in + res,
                                            out + res, len - res,
                                            gctx->gcm.key,
                                            gctx->gcm.Yi.c, gctx->gcm.Xi.u);
                     gctx->gcm.len.u[1] += bulk;
                     bulk += res;
                 }
 # endif
                 if (CRYPTO_gcm128_decrypt(&gctx->gcm,
                                           in + bulk, out + bulk, len - bulk))
                     return -1;
             }
         }
         return len;
     } else {
         if (!ctx->encrypt) {
             if (gctx->taglen < 0)
                 return -1;
             if (CRYPTO_gcm128_finish(&gctx->gcm, ctx->buf, gctx->taglen) != 0)
                 return -1;
             gctx->iv_set = 0;
             return 0;
         }
         CRYPTO_gcm128_tag(&gctx->gcm, ctx->buf, 16);
         gctx->taglen = 16;
         /* Don't reuse the IV */
         gctx->iv_set = 0;
         return 0;
     }
 
 }
 
 # define CUSTOM_FLAGS    (EVP_CIPH_FLAG_DEFAULT_ASN1 \
                 | EVP_CIPH_CUSTOM_IV | EVP_CIPH_FLAG_CUSTOM_CIPHER \
                 | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CTRL_INIT \
                 | EVP_CIPH_CUSTOM_COPY)
 
 BLOCK_CIPHER_custom(NID_aes, 128, 1, 12, gcm, GCM,
                     EVP_CIPH_FLAG_FIPS | EVP_CIPH_FLAG_AEAD_CIPHER |
                     CUSTOM_FLAGS)
     BLOCK_CIPHER_custom(NID_aes, 192, 1, 12, gcm, GCM,
                     EVP_CIPH_FLAG_FIPS | EVP_CIPH_FLAG_AEAD_CIPHER |
                     CUSTOM_FLAGS)
     BLOCK_CIPHER_custom(NID_aes, 256, 1, 12, gcm, GCM,
                     EVP_CIPH_FLAG_FIPS | EVP_CIPH_FLAG_AEAD_CIPHER |
                     CUSTOM_FLAGS)
 
 static int aes_xts_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)
 {
     EVP_AES_XTS_CTX *xctx = c->cipher_data;
     if (type == EVP_CTRL_COPY) {
         EVP_CIPHER_CTX *out = ptr;
         EVP_AES_XTS_CTX *xctx_out = out->cipher_data;
         if (xctx->xts.key1) {
             if (xctx->xts.key1 != &xctx->ks1)
                 return 0;
             xctx_out->xts.key1 = &xctx_out->ks1;
         }
         if (xctx->xts.key2) {
             if (xctx->xts.key2 != &xctx->ks2)
                 return 0;
             xctx_out->xts.key2 = &xctx_out->ks2;
         }
         return 1;
     } else if (type != EVP_CTRL_INIT)
         return -1;
     /* key1 and key2 are used as an indicator both key and IV are set */
     xctx->xts.key1 = NULL;
     xctx->xts.key2 = NULL;
     return 1;
 }
 
 static int aes_xts_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
                             const unsigned char *iv, int enc)
 {
     EVP_AES_XTS_CTX *xctx = ctx->cipher_data;
     if (!iv && !key)
         return 1;
 
     if (key)
         do {
 # ifdef AES_XTS_ASM
             xctx->stream = enc ? AES_xts_encrypt : AES_xts_decrypt;
 # else
             xctx->stream = NULL;
 # endif
             /* key_len is two AES keys */
 # ifdef HWAES_CAPABLE
             if (HWAES_CAPABLE) {
                 if (enc) {
                     HWAES_set_encrypt_key(key, ctx->key_len * 4,
                                           &xctx->ks1.ks);
                     xctx->xts.block1 = (block128_f) HWAES_encrypt;
                 } else {
                     HWAES_set_decrypt_key(key, ctx->key_len * 4,
                                           &xctx->ks1.ks);
                     xctx->xts.block1 = (block128_f) HWAES_decrypt;
                 }
 
                 HWAES_set_encrypt_key(key + ctx->key_len / 2,
                                       ctx->key_len * 4, &xctx->ks2.ks);
                 xctx->xts.block2 = (block128_f) HWAES_encrypt;
 
                 xctx->xts.key1 = &xctx->ks1;
                 break;
             } else
 # endif
 # ifdef BSAES_CAPABLE
             if (BSAES_CAPABLE)
                 xctx->stream = enc ? bsaes_xts_encrypt : bsaes_xts_decrypt;
             else
 # endif
 # ifdef VPAES_CAPABLE
             if (VPAES_CAPABLE) {
                 if (enc) {
                     vpaes_set_encrypt_key(key, ctx->key_len * 4,
                                           &xctx->ks1.ks);
                     xctx->xts.block1 = (block128_f) vpaes_encrypt;
                 } else {
                     vpaes_set_decrypt_key(key, ctx->key_len * 4,
                                           &xctx->ks1.ks);
                     xctx->xts.block1 = (block128_f) vpaes_decrypt;
                 }
 
                 vpaes_set_encrypt_key(key + ctx->key_len / 2,
                                       ctx->key_len * 4, &xctx->ks2.ks);
                 xctx->xts.block2 = (block128_f) vpaes_encrypt;
 
                 xctx->xts.key1 = &xctx->ks1;
                 break;
             } else
 # endif
                 (void)0;        /* terminate potentially open 'else' */
 
             if (enc) {
                 AES_set_encrypt_key(key, ctx->key_len * 4, &xctx->ks1.ks);
                 xctx->xts.block1 = (block128_f) AES_encrypt;
             } else {
                 AES_set_decrypt_key(key, ctx->key_len * 4, &xctx->ks1.ks);
                 xctx->xts.block1 = (block128_f) AES_decrypt;
             }
 
             AES_set_encrypt_key(key + ctx->key_len / 2,
                                 ctx->key_len * 4, &xctx->ks2.ks);
             xctx->xts.block2 = (block128_f) AES_encrypt;
 
             xctx->xts.key1 = &xctx->ks1;
         } while (0);
 
     if (iv) {
         xctx->xts.key2 = &xctx->ks2;
         memcpy(ctx->iv, iv, 16);
     }
 
     return 1;
 }
 
 static int aes_xts_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                           const unsigned char *in, size_t len)
 {
     EVP_AES_XTS_CTX *xctx = ctx->cipher_data;
     if (!xctx->xts.key1 || !xctx->xts.key2)
         return 0;
     if (!out || !in || len < AES_BLOCK_SIZE)
         return 0;
     if (xctx->stream)
         (*xctx->stream) (in, out, len,
                          xctx->xts.key1, xctx->xts.key2, ctx->iv);
     else if (CRYPTO_xts128_encrypt(&xctx->xts, ctx->iv, in, out, len,
                                    ctx->encrypt))
         return 0;
     return 1;
 }
 
 # define aes_xts_cleanup NULL
 
 # define XTS_FLAGS       (EVP_CIPH_FLAG_DEFAULT_ASN1 | EVP_CIPH_CUSTOM_IV \
                          | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CTRL_INIT \
                          | EVP_CIPH_CUSTOM_COPY)
 
 BLOCK_CIPHER_custom(NID_aes, 128, 1, 16, xts, XTS,
                     EVP_CIPH_FLAG_FIPS | XTS_FLAGS)
     BLOCK_CIPHER_custom(NID_aes, 256, 1, 16, xts, XTS,
                     EVP_CIPH_FLAG_FIPS | XTS_FLAGS)
 
 static int aes_ccm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)
 {
     EVP_AES_CCM_CTX *cctx = c->cipher_data;
     switch (type) {
     case EVP_CTRL_INIT:
         cctx->key_set = 0;
         cctx->iv_set = 0;
         cctx->L = 8;
         cctx->M = 12;
         cctx->tag_set = 0;
         cctx->len_set = 0;
         return 1;
 
     case EVP_CTRL_CCM_SET_IVLEN:
         arg = 15 - arg;
     case EVP_CTRL_CCM_SET_L:
         if (arg < 2 || arg > 8)
             return 0;
         cctx->L = arg;
         return 1;
 
     case EVP_CTRL_CCM_SET_TAG:
         if ((arg & 1) || arg < 4 || arg > 16)
             return 0;
         if (c->encrypt && ptr)
             return 0;
         if (ptr) {
             cctx->tag_set = 1;
             memcpy(c->buf, ptr, arg);
         }
         cctx->M = arg;
         return 1;
 
     case EVP_CTRL_CCM_GET_TAG:
         if (!c->encrypt || !cctx->tag_set)
             return 0;
         if (!CRYPTO_ccm128_tag(&cctx->ccm, ptr, (size_t)arg))
             return 0;
         cctx->tag_set = 0;
         cctx->iv_set = 0;
         cctx->len_set = 0;
         return 1;
 
     case EVP_CTRL_COPY:
         {
             EVP_CIPHER_CTX *out = ptr;
             EVP_AES_CCM_CTX *cctx_out = out->cipher_data;
             if (cctx->ccm.key) {
                 if (cctx->ccm.key != &cctx->ks)
                     return 0;
                 cctx_out->ccm.key = &cctx_out->ks;
             }
             return 1;
         }
 
     default:
         return -1;
 
     }
 }
 
 static int aes_ccm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
                             const unsigned char *iv, int enc)
 {
     EVP_AES_CCM_CTX *cctx = ctx->cipher_data;
     if (!iv && !key)
         return 1;
     if (key)
         do {
 # ifdef HWAES_CAPABLE
             if (HWAES_CAPABLE) {
                 HWAES_set_encrypt_key(key, ctx->key_len * 8, &cctx->ks.ks);
 
                 CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L,
                                    &cctx->ks, (block128_f) HWAES_encrypt);
                 cctx->str = NULL;
                 cctx->key_set = 1;
                 break;
             } else
 # endif
 # ifdef VPAES_CAPABLE
             if (VPAES_CAPABLE) {
                 vpaes_set_encrypt_key(key, ctx->key_len * 8, &cctx->ks.ks);
                 CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L,
                                    &cctx->ks, (block128_f) vpaes_encrypt);
                 cctx->str = NULL;
                 cctx->key_set = 1;
                 break;
             }
 # endif
             AES_set_encrypt_key(key, ctx->key_len * 8, &cctx->ks.ks);
             CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L,
                                &cctx->ks, (block128_f) AES_encrypt);
             cctx->str = NULL;
             cctx->key_set = 1;
         } while (0);
     if (iv) {
         memcpy(ctx->iv, iv, 15 - cctx->L);
         cctx->iv_set = 1;
     }
     return 1;
 }
 
 static int aes_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                           const unsigned char *in, size_t len)
 {
     EVP_AES_CCM_CTX *cctx = ctx->cipher_data;
     CCM128_CONTEXT *ccm = &cctx->ccm;
     /* If not set up, return error */
     if (!cctx->iv_set && !cctx->key_set)
         return -1;
     if (!ctx->encrypt && !cctx->tag_set)
         return -1;
     if (!out) {
         if (!in) {
             if (CRYPTO_ccm128_setiv(ccm, ctx->iv, 15 - cctx->L, len))
                 return -1;
             cctx->len_set = 1;
             return len;
         }
         /* If have AAD need message length */
         if (!cctx->len_set && len)
             return -1;
         CRYPTO_ccm128_aad(ccm, in, len);
         return len;
     }
     /* EVP_*Final() doesn't return any data */
     if (!in)
         return 0;
     /* If not set length yet do it */
     if (!cctx->len_set) {
         if (CRYPTO_ccm128_setiv(ccm, ctx->iv, 15 - cctx->L, len))
             return -1;
         cctx->len_set = 1;
     }
     if (ctx->encrypt) {
         if (cctx->str ? CRYPTO_ccm128_encrypt_ccm64(ccm, in, out, len,
                                                     cctx->str) :
             CRYPTO_ccm128_encrypt(ccm, in, out, len))
             return -1;
         cctx->tag_set = 1;
         return len;
     } else {
         int rv = -1;
         if (cctx->str ? !CRYPTO_ccm128_decrypt_ccm64(ccm, in, out, len,
                                                      cctx->str) :
             !CRYPTO_ccm128_decrypt(ccm, in, out, len)) {
             unsigned char tag[16];
             if (CRYPTO_ccm128_tag(ccm, tag, cctx->M)) {
                 if (!CRYPTO_memcmp(tag, ctx->buf, cctx->M))
                     rv = len;
             }
         }
         if (rv == -1)
             OPENSSL_cleanse(out, len);
         cctx->iv_set = 0;
         cctx->tag_set = 0;
         cctx->len_set = 0;
         return rv;
     }
 
 }
 
 # define aes_ccm_cleanup NULL
 
 BLOCK_CIPHER_custom(NID_aes, 128, 1, 12, ccm, CCM,
                     EVP_CIPH_FLAG_FIPS | CUSTOM_FLAGS)
     BLOCK_CIPHER_custom(NID_aes, 192, 1, 12, ccm, CCM,
                     EVP_CIPH_FLAG_FIPS | CUSTOM_FLAGS)
     BLOCK_CIPHER_custom(NID_aes, 256, 1, 12, ccm, CCM,
                     EVP_CIPH_FLAG_FIPS | CUSTOM_FLAGS)
 #endif
 typedef struct {
     union {
         double align;
         AES_KEY ks;
     } ks;
     /* Indicates if IV has been set */
     unsigned char *iv;
 } EVP_AES_WRAP_CTX;
 
 static int aes_wrap_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
                              const unsigned char *iv, int enc)
 {
     EVP_AES_WRAP_CTX *wctx = ctx->cipher_data;
     if (!iv && !key)
         return 1;
     if (key) {
         if (ctx->encrypt)
             AES_set_encrypt_key(key, ctx->key_len * 8, &wctx->ks.ks);
         else
             AES_set_decrypt_key(key, ctx->key_len * 8, &wctx->ks.ks);
         if (!iv)
             wctx->iv = NULL;
     }
     if (iv) {
         memcpy(ctx->iv, iv, 8);
         wctx->iv = ctx->iv;
     }
     return 1;
 }
 
 static int aes_wrap_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                            const unsigned char *in, size_t inlen)
 {
     EVP_AES_WRAP_CTX *wctx = ctx->cipher_data;
     size_t rv;
     if (!in)
         return 0;
     if (inlen % 8)
         return -1;
     if (ctx->encrypt && inlen < 8)
         return -1;
     if (!ctx->encrypt && inlen < 16)
         return -1;
     if (!out) {
         if (ctx->encrypt)
             return inlen + 8;
         else
             return inlen - 8;
     }
     if (ctx->encrypt)
         rv = CRYPTO_128_wrap(&wctx->ks.ks, wctx->iv, out, in, inlen,
                              (block128_f) AES_encrypt);
     else
         rv = CRYPTO_128_unwrap(&wctx->ks.ks, wctx->iv, out, in, inlen,
                                (block128_f) AES_decrypt);
     return rv ? (int)rv : -1;
 }
 
 #define WRAP_FLAGS      (EVP_CIPH_WRAP_MODE \
                 | EVP_CIPH_CUSTOM_IV | EVP_CIPH_FLAG_CUSTOM_CIPHER \
                 | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_FLAG_DEFAULT_ASN1)
 
 static const EVP_CIPHER aes_128_wrap = {
     NID_id_aes128_wrap,
     8, 16, 8, WRAP_FLAGS,
     aes_wrap_init_key, aes_wrap_cipher,
     NULL,
     sizeof(EVP_AES_WRAP_CTX),
     NULL, NULL, NULL, NULL
 };
 
 const EVP_CIPHER *EVP_aes_128_wrap(void)
 {
     return &aes_128_wrap;
 }
 
 static const EVP_CIPHER aes_192_wrap = {
     NID_id_aes192_wrap,
     8, 24, 8, WRAP_FLAGS,
     aes_wrap_init_key, aes_wrap_cipher,
     NULL,
     sizeof(EVP_AES_WRAP_CTX),
     NULL, NULL, NULL, NULL
 };
 
 const EVP_CIPHER *EVP_aes_192_wrap(void)
 {
     return &aes_192_wrap;
 }
 
 static const EVP_CIPHER aes_256_wrap = {
     NID_id_aes256_wrap,
     8, 32, 8, WRAP_FLAGS,
     aes_wrap_init_key, aes_wrap_cipher,
     NULL,
     sizeof(EVP_AES_WRAP_CTX),
     NULL, NULL, NULL, NULL
 };
 
 const EVP_CIPHER *EVP_aes_256_wrap(void)
 {
     return &aes_256_wrap;
 }
Index: vendor-crypto/openssl/dist/crypto/evp/e_aes_cbc_hmac_sha1.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/evp/e_aes_cbc_hmac_sha1.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/evp/e_aes_cbc_hmac_sha1.c	(revision 318897)
@@ -1,1008 +1,1010 @@
 /* ====================================================================
  * Copyright (c) 2011-2013 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    licensing@OpenSSL.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  */
 
 #include 
 
 #include 
 #include 
 
 #if !defined(OPENSSL_NO_AES) && !defined(OPENSSL_NO_SHA1)
 
 # include 
 # include 
 # include 
 # include 
 # include 
 # include "modes_lcl.h"
 # include "constant_time_locl.h"
 
 # ifndef EVP_CIPH_FLAG_AEAD_CIPHER
 #  define EVP_CIPH_FLAG_AEAD_CIPHER       0x200000
 #  define EVP_CTRL_AEAD_TLS1_AAD          0x16
 #  define EVP_CTRL_AEAD_SET_MAC_KEY       0x17
 # endif
 
 # if !defined(EVP_CIPH_FLAG_DEFAULT_ASN1)
 #  define EVP_CIPH_FLAG_DEFAULT_ASN1 0
 # endif
 
 # if !defined(EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK)
 #  define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
 # endif
 
 # define TLS1_1_VERSION 0x0302
 
 typedef struct {
     AES_KEY ks;
     SHA_CTX head, tail, md;
     size_t payload_length;      /* AAD length in decrypt case */
     union {
         unsigned int tls_ver;
         unsigned char tls_aad[16]; /* 13 used */
     } aux;
 } EVP_AES_HMAC_SHA1;
 
 # define NO_PAYLOAD_LENGTH       ((size_t)-1)
 
 # if     defined(AES_ASM) &&     ( \
         defined(__x86_64)       || defined(__x86_64__)  || \
         defined(_M_AMD64)       || defined(_M_X64)      || \
         defined(__INTEL__)      )
 
 extern unsigned int OPENSSL_ia32cap_P[];
 #  define AESNI_CAPABLE   (1<<(57-32))
 
 int aesni_set_encrypt_key(const unsigned char *userKey, int bits,
                           AES_KEY *key);
 int aesni_set_decrypt_key(const unsigned char *userKey, int bits,
                           AES_KEY *key);
 
 void aesni_cbc_encrypt(const unsigned char *in,
                        unsigned char *out,
                        size_t length,
                        const AES_KEY *key, unsigned char *ivec, int enc);
 
 void aesni_cbc_sha1_enc(const void *inp, void *out, size_t blocks,
                         const AES_KEY *key, unsigned char iv[16],
                         SHA_CTX *ctx, const void *in0);
 
 void aesni256_cbc_sha1_dec(const void *inp, void *out, size_t blocks,
                            const AES_KEY *key, unsigned char iv[16],
                            SHA_CTX *ctx, const void *in0);
 
 #  define data(ctx) ((EVP_AES_HMAC_SHA1 *)(ctx)->cipher_data)
 
 static int aesni_cbc_hmac_sha1_init_key(EVP_CIPHER_CTX *ctx,
                                         const unsigned char *inkey,
                                         const unsigned char *iv, int enc)
 {
     EVP_AES_HMAC_SHA1 *key = data(ctx);
     int ret;
 
     if (enc)
         ret = aesni_set_encrypt_key(inkey, ctx->key_len * 8, &key->ks);
     else
         ret = aesni_set_decrypt_key(inkey, ctx->key_len * 8, &key->ks);
 
     SHA1_Init(&key->head);      /* handy when benchmarking */
     key->tail = key->head;
     key->md = key->head;
 
     key->payload_length = NO_PAYLOAD_LENGTH;
 
     return ret < 0 ? 0 : 1;
 }
 
 #  define STITCHED_CALL
 #  undef  STITCHED_DECRYPT_CALL
 
 #  if !defined(STITCHED_CALL)
 #   define aes_off 0
 #  endif
 
 void sha1_block_data_order(void *c, const void *p, size_t len);
 
 static void sha1_update(SHA_CTX *c, const void *data, size_t len)
 {
     const unsigned char *ptr = data;
     size_t res;
 
     if ((res = c->num)) {
         res = SHA_CBLOCK - res;
         if (len < res)
             res = len;
         SHA1_Update(c, ptr, res);
         ptr += res;
         len -= res;
     }
 
     res = len % SHA_CBLOCK;
     len -= res;
 
     if (len) {
         sha1_block_data_order(c, ptr, len / SHA_CBLOCK);
 
         ptr += len;
         c->Nh += len >> 29;
         c->Nl += len <<= 3;
         if (c->Nl < (unsigned int)len)
             c->Nh++;
     }
 
     if (res)
         SHA1_Update(c, ptr, res);
 }
 
 #  ifdef SHA1_Update
 #   undef SHA1_Update
 #  endif
 #  define SHA1_Update sha1_update
 
 #  if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
 
 typedef struct {
     unsigned int A[8], B[8], C[8], D[8], E[8];
 } SHA1_MB_CTX;
 typedef struct {
     const unsigned char *ptr;
     int blocks;
 } HASH_DESC;
 
 void sha1_multi_block(SHA1_MB_CTX *, const HASH_DESC *, int);
 
 typedef struct {
     const unsigned char *inp;
     unsigned char *out;
     int blocks;
     u64 iv[2];
 } CIPH_DESC;
 
 void aesni_multi_cbc_encrypt(CIPH_DESC *, void *, int);
 
 static size_t tls1_1_multi_block_encrypt(EVP_AES_HMAC_SHA1 *key,
                                          unsigned char *out,
                                          const unsigned char *inp,
                                          size_t inp_len, int n4x)
 {                               /* n4x is 1 or 2 */
     HASH_DESC hash_d[8], edges[8];
     CIPH_DESC ciph_d[8];
     unsigned char storage[sizeof(SHA1_MB_CTX) + 32];
     union {
         u64 q[16];
         u32 d[32];
         u8 c[128];
     } blocks[8];
     SHA1_MB_CTX *ctx;
     unsigned int frag, last, packlen, i, x4 = 4 * n4x, minblocks, processed =
         0;
     size_t ret = 0;
     u8 *IVs;
 #   if defined(BSWAP8)
     u64 seqnum;
 #   endif
 
     /* ask for IVs in bulk */
     if (RAND_bytes((IVs = blocks[0].c), 16 * x4) <= 0)
         return 0;
 
     ctx = (SHA1_MB_CTX *) (storage + 32 - ((size_t)storage % 32)); /* align */
 
     frag = (unsigned int)inp_len >> (1 + n4x);
     last = (unsigned int)inp_len + frag - (frag << (1 + n4x));
     if (last > frag && ((last + 13 + 9) % 64) < (x4 - 1)) {
         frag++;
         last -= x4 - 1;
     }
 
     packlen = 5 + 16 + ((frag + 20 + 16) & -16);
 
     /* populate descriptors with pointers and IVs */
     hash_d[0].ptr = inp;
     ciph_d[0].inp = inp;
     /* 5+16 is place for header and explicit IV */
     ciph_d[0].out = out + 5 + 16;
     memcpy(ciph_d[0].out - 16, IVs, 16);
     memcpy(ciph_d[0].iv, IVs, 16);
     IVs += 16;
 
     for (i = 1; i < x4; i++) {
         ciph_d[i].inp = hash_d[i].ptr = hash_d[i - 1].ptr + frag;
         ciph_d[i].out = ciph_d[i - 1].out + packlen;
         memcpy(ciph_d[i].out - 16, IVs, 16);
         memcpy(ciph_d[i].iv, IVs, 16);
         IVs += 16;
     }
 
 #   if defined(BSWAP8)
     memcpy(blocks[0].c, key->md.data, 8);
     seqnum = BSWAP8(blocks[0].q[0]);
 #   endif
     for (i = 0; i < x4; i++) {
         unsigned int len = (i == (x4 - 1) ? last : frag);
 #   if !defined(BSWAP8)
         unsigned int carry, j;
 #   endif
 
         ctx->A[i] = key->md.h0;
         ctx->B[i] = key->md.h1;
         ctx->C[i] = key->md.h2;
         ctx->D[i] = key->md.h3;
         ctx->E[i] = key->md.h4;
 
         /* fix seqnum */
 #   if defined(BSWAP8)
         blocks[i].q[0] = BSWAP8(seqnum + i);
 #   else
         for (carry = i, j = 8; j--;) {
             blocks[i].c[j] = ((u8 *)key->md.data)[j] + carry;
             carry = (blocks[i].c[j] - carry) >> (sizeof(carry) * 8 - 1);
         }
 #   endif
         blocks[i].c[8] = ((u8 *)key->md.data)[8];
         blocks[i].c[9] = ((u8 *)key->md.data)[9];
         blocks[i].c[10] = ((u8 *)key->md.data)[10];
         /* fix length */
         blocks[i].c[11] = (u8)(len >> 8);
         blocks[i].c[12] = (u8)(len);
 
         memcpy(blocks[i].c + 13, hash_d[i].ptr, 64 - 13);
         hash_d[i].ptr += 64 - 13;
         hash_d[i].blocks = (len - (64 - 13)) / 64;
 
         edges[i].ptr = blocks[i].c;
         edges[i].blocks = 1;
     }
 
     /* hash 13-byte headers and first 64-13 bytes of inputs */
     sha1_multi_block(ctx, edges, n4x);
     /* hash bulk inputs */
 #   define MAXCHUNKSIZE    2048
 #   if     MAXCHUNKSIZE%64
 #    error  "MAXCHUNKSIZE is not divisible by 64"
 #   elif   MAXCHUNKSIZE
     /*
      * goal is to minimize pressure on L1 cache by moving in shorter steps,
      * so that hashed data is still in the cache by the time we encrypt it
      */
     minblocks = ((frag <= last ? frag : last) - (64 - 13)) / 64;
     if (minblocks > MAXCHUNKSIZE / 64) {
         for (i = 0; i < x4; i++) {
             edges[i].ptr = hash_d[i].ptr;
             edges[i].blocks = MAXCHUNKSIZE / 64;
             ciph_d[i].blocks = MAXCHUNKSIZE / 16;
         }
         do {
             sha1_multi_block(ctx, edges, n4x);
             aesni_multi_cbc_encrypt(ciph_d, &key->ks, n4x);
 
             for (i = 0; i < x4; i++) {
                 edges[i].ptr = hash_d[i].ptr += MAXCHUNKSIZE;
                 hash_d[i].blocks -= MAXCHUNKSIZE / 64;
                 edges[i].blocks = MAXCHUNKSIZE / 64;
                 ciph_d[i].inp += MAXCHUNKSIZE;
                 ciph_d[i].out += MAXCHUNKSIZE;
                 ciph_d[i].blocks = MAXCHUNKSIZE / 16;
                 memcpy(ciph_d[i].iv, ciph_d[i].out - 16, 16);
             }
             processed += MAXCHUNKSIZE;
             minblocks -= MAXCHUNKSIZE / 64;
         } while (minblocks > MAXCHUNKSIZE / 64);
     }
 #   endif
 #   undef  MAXCHUNKSIZE
     sha1_multi_block(ctx, hash_d, n4x);
 
     memset(blocks, 0, sizeof(blocks));
     for (i = 0; i < x4; i++) {
         unsigned int len = (i == (x4 - 1) ? last : frag),
             off = hash_d[i].blocks * 64;
         const unsigned char *ptr = hash_d[i].ptr + off;
 
         off = (len - processed) - (64 - 13) - off; /* remainder actually */
         memcpy(blocks[i].c, ptr, off);
         blocks[i].c[off] = 0x80;
         len += 64 + 13;         /* 64 is HMAC header */
         len *= 8;               /* convert to bits */
         if (off < (64 - 8)) {
 #   ifdef BSWAP4
             blocks[i].d[15] = BSWAP4(len);
 #   else
             PUTU32(blocks[i].c + 60, len);
 #   endif
             edges[i].blocks = 1;
         } else {
 #   ifdef BSWAP4
             blocks[i].d[31] = BSWAP4(len);
 #   else
             PUTU32(blocks[i].c + 124, len);
 #   endif
             edges[i].blocks = 2;
         }
         edges[i].ptr = blocks[i].c;
     }
 
     /* hash input tails and finalize */
     sha1_multi_block(ctx, edges, n4x);
 
     memset(blocks, 0, sizeof(blocks));
     for (i = 0; i < x4; i++) {
 #   ifdef BSWAP4
         blocks[i].d[0] = BSWAP4(ctx->A[i]);
         ctx->A[i] = key->tail.h0;
         blocks[i].d[1] = BSWAP4(ctx->B[i]);
         ctx->B[i] = key->tail.h1;
         blocks[i].d[2] = BSWAP4(ctx->C[i]);
         ctx->C[i] = key->tail.h2;
         blocks[i].d[3] = BSWAP4(ctx->D[i]);
         ctx->D[i] = key->tail.h3;
         blocks[i].d[4] = BSWAP4(ctx->E[i]);
         ctx->E[i] = key->tail.h4;
         blocks[i].c[20] = 0x80;
         blocks[i].d[15] = BSWAP4((64 + 20) * 8);
 #   else
         PUTU32(blocks[i].c + 0, ctx->A[i]);
         ctx->A[i] = key->tail.h0;
         PUTU32(blocks[i].c + 4, ctx->B[i]);
         ctx->B[i] = key->tail.h1;
         PUTU32(blocks[i].c + 8, ctx->C[i]);
         ctx->C[i] = key->tail.h2;
         PUTU32(blocks[i].c + 12, ctx->D[i]);
         ctx->D[i] = key->tail.h3;
         PUTU32(blocks[i].c + 16, ctx->E[i]);
         ctx->E[i] = key->tail.h4;
         blocks[i].c[20] = 0x80;
         PUTU32(blocks[i].c + 60, (64 + 20) * 8);
 #   endif
         edges[i].ptr = blocks[i].c;
         edges[i].blocks = 1;
     }
 
     /* finalize MACs */
     sha1_multi_block(ctx, edges, n4x);
 
     for (i = 0; i < x4; i++) {
         unsigned int len = (i == (x4 - 1) ? last : frag), pad, j;
         unsigned char *out0 = out;
 
         memcpy(ciph_d[i].out, ciph_d[i].inp, len - processed);
         ciph_d[i].inp = ciph_d[i].out;
 
         out += 5 + 16 + len;
 
         /* write MAC */
         PUTU32(out + 0, ctx->A[i]);
         PUTU32(out + 4, ctx->B[i]);
         PUTU32(out + 8, ctx->C[i]);
         PUTU32(out + 12, ctx->D[i]);
         PUTU32(out + 16, ctx->E[i]);
         out += 20;
         len += 20;
 
         /* pad */
         pad = 15 - len % 16;
         for (j = 0; j <= pad; j++)
             *(out++) = pad;
         len += pad + 1;
 
         ciph_d[i].blocks = (len - processed) / 16;
         len += 16;              /* account for explicit iv */
 
         /* arrange header */
         out0[0] = ((u8 *)key->md.data)[8];
         out0[1] = ((u8 *)key->md.data)[9];
         out0[2] = ((u8 *)key->md.data)[10];
         out0[3] = (u8)(len >> 8);
         out0[4] = (u8)(len);
 
         ret += len + 5;
         inp += frag;
     }
 
     aesni_multi_cbc_encrypt(ciph_d, &key->ks, n4x);
 
     OPENSSL_cleanse(blocks, sizeof(blocks));
     OPENSSL_cleanse(ctx, sizeof(*ctx));
 
     return ret;
 }
 #  endif
 
 static int aesni_cbc_hmac_sha1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                                       const unsigned char *in, size_t len)
 {
     EVP_AES_HMAC_SHA1 *key = data(ctx);
     unsigned int l;
     size_t plen = key->payload_length, iv = 0, /* explicit IV in TLS 1.1 and
                                                 * later */
         sha_off = 0;
 #  if defined(STITCHED_CALL)
     size_t aes_off = 0, blocks;
 
     sha_off = SHA_CBLOCK - key->md.num;
 #  endif
 
     key->payload_length = NO_PAYLOAD_LENGTH;
 
     if (len % AES_BLOCK_SIZE)
         return 0;
 
     if (ctx->encrypt) {
         if (plen == NO_PAYLOAD_LENGTH)
             plen = len;
         else if (len !=
                  ((plen + SHA_DIGEST_LENGTH +
                    AES_BLOCK_SIZE) & -AES_BLOCK_SIZE))
             return 0;
         else if (key->aux.tls_ver >= TLS1_1_VERSION)
             iv = AES_BLOCK_SIZE;
 
 #  if defined(STITCHED_CALL)
         if (plen > (sha_off + iv)
             && (blocks = (plen - (sha_off + iv)) / SHA_CBLOCK)) {
             SHA1_Update(&key->md, in + iv, sha_off);
 
             aesni_cbc_sha1_enc(in, out, blocks, &key->ks,
                                ctx->iv, &key->md, in + iv + sha_off);
             blocks *= SHA_CBLOCK;
             aes_off += blocks;
             sha_off += blocks;
             key->md.Nh += blocks >> 29;
             key->md.Nl += blocks <<= 3;
             if (key->md.Nl < (unsigned int)blocks)
                 key->md.Nh++;
         } else {
             sha_off = 0;
         }
 #  endif
         sha_off += iv;
         SHA1_Update(&key->md, in + sha_off, plen - sha_off);
 
         if (plen != len) {      /* "TLS" mode of operation */
             if (in != out)
                 memcpy(out + aes_off, in + aes_off, plen - aes_off);
 
             /* calculate HMAC and append it to payload */
             SHA1_Final(out + plen, &key->md);
             key->md = key->tail;
             SHA1_Update(&key->md, out + plen, SHA_DIGEST_LENGTH);
             SHA1_Final(out + plen, &key->md);
 
             /* pad the payload|hmac */
             plen += SHA_DIGEST_LENGTH;
             for (l = len - plen - 1; plen < len; plen++)
                 out[plen] = l;
             /* encrypt HMAC|padding at once */
             aesni_cbc_encrypt(out + aes_off, out + aes_off, len - aes_off,
                               &key->ks, ctx->iv, 1);
         } else {
             aesni_cbc_encrypt(in + aes_off, out + aes_off, len - aes_off,
                               &key->ks, ctx->iv, 1);
         }
     } else {
         union {
             unsigned int u[SHA_DIGEST_LENGTH / sizeof(unsigned int)];
             unsigned char c[32 + SHA_DIGEST_LENGTH];
         } mac, *pmac;
 
         /* arrange cache line alignment */
         pmac = (void *)(((size_t)mac.c + 31) & ((size_t)0 - 32));
 
         if (plen != NO_PAYLOAD_LENGTH) { /* "TLS" mode of operation */
             size_t inp_len, mask, j, i;
             unsigned int res, maxpad, pad, bitlen;
             int ret = 1;
             union {
                 unsigned int u[SHA_LBLOCK];
                 unsigned char c[SHA_CBLOCK];
             } *data = (void *)key->md.data;
 #  if defined(STITCHED_DECRYPT_CALL)
             unsigned char tail_iv[AES_BLOCK_SIZE];
             int stitch = 0;
 #  endif
 
             if ((key->aux.tls_aad[plen - 4] << 8 | key->aux.tls_aad[plen - 3])
                 >= TLS1_1_VERSION) {
                 if (len < (AES_BLOCK_SIZE + SHA_DIGEST_LENGTH + 1))
                     return 0;
 
                 /* omit explicit iv */
                 memcpy(ctx->iv, in, AES_BLOCK_SIZE);
                 in += AES_BLOCK_SIZE;
                 out += AES_BLOCK_SIZE;
                 len -= AES_BLOCK_SIZE;
             } else if (len < (SHA_DIGEST_LENGTH + 1))
                 return 0;
 
 #  if defined(STITCHED_DECRYPT_CALL)
             if (len >= 1024 && ctx->key_len == 32) {
                 /* decrypt last block */
                 memcpy(tail_iv, in + len - 2 * AES_BLOCK_SIZE,
                        AES_BLOCK_SIZE);
                 aesni_cbc_encrypt(in + len - AES_BLOCK_SIZE,
                                   out + len - AES_BLOCK_SIZE, AES_BLOCK_SIZE,
                                   &key->ks, tail_iv, 0);
                 stitch = 1;
             } else
 #  endif
                 /* decrypt HMAC|padding at once */
                 aesni_cbc_encrypt(in, out, len, &key->ks, ctx->iv, 0);
 
             /* figure out payload length */
             pad = out[len - 1];
             maxpad = len - (SHA_DIGEST_LENGTH + 1);
             maxpad |= (255 - maxpad) >> (sizeof(maxpad) * 8 - 8);
             maxpad &= 255;
 
             ret &= constant_time_ge(maxpad, pad);
 
             inp_len = len - (SHA_DIGEST_LENGTH + pad + 1);
             mask = (0 - ((inp_len - len) >> (sizeof(inp_len) * 8 - 1)));
             inp_len &= mask;
             ret &= (int)mask;
 
             key->aux.tls_aad[plen - 2] = inp_len >> 8;
             key->aux.tls_aad[plen - 1] = inp_len;
 
             /* calculate HMAC */
             key->md = key->head;
             SHA1_Update(&key->md, key->aux.tls_aad, plen);
 
 #  if defined(STITCHED_DECRYPT_CALL)
             if (stitch) {
                 blocks = (len - (256 + 32 + SHA_CBLOCK)) / SHA_CBLOCK;
                 aes_off = len - AES_BLOCK_SIZE - blocks * SHA_CBLOCK;
                 sha_off = SHA_CBLOCK - plen;
 
                 aesni_cbc_encrypt(in, out, aes_off, &key->ks, ctx->iv, 0);
 
                 SHA1_Update(&key->md, out, sha_off);
                 aesni256_cbc_sha1_dec(in + aes_off,
                                       out + aes_off, blocks, &key->ks,
                                       ctx->iv, &key->md, out + sha_off);
 
                 sha_off += blocks *= SHA_CBLOCK;
                 out += sha_off;
                 len -= sha_off;
                 inp_len -= sha_off;
 
                 key->md.Nl += (blocks << 3); /* at most 18 bits */
                 memcpy(ctx->iv, tail_iv, AES_BLOCK_SIZE);
             }
 #  endif
 
 #  if 1
             len -= SHA_DIGEST_LENGTH; /* amend mac */
             if (len >= (256 + SHA_CBLOCK)) {
                 j = (len - (256 + SHA_CBLOCK)) & (0 - SHA_CBLOCK);
                 j += SHA_CBLOCK - key->md.num;
                 SHA1_Update(&key->md, out, j);
                 out += j;
                 len -= j;
                 inp_len -= j;
             }
 
             /* but pretend as if we hashed padded payload */
             bitlen = key->md.Nl + (inp_len << 3); /* at most 18 bits */
 #   ifdef BSWAP4
             bitlen = BSWAP4(bitlen);
 #   else
             mac.c[0] = 0;
             mac.c[1] = (unsigned char)(bitlen >> 16);
             mac.c[2] = (unsigned char)(bitlen >> 8);
             mac.c[3] = (unsigned char)bitlen;
             bitlen = mac.u[0];
 #   endif
 
             pmac->u[0] = 0;
             pmac->u[1] = 0;
             pmac->u[2] = 0;
             pmac->u[3] = 0;
             pmac->u[4] = 0;
 
             for (res = key->md.num, j = 0; j < len; j++) {
                 size_t c = out[j];
                 mask = (j - inp_len) >> (sizeof(j) * 8 - 8);
                 c &= mask;
                 c |= 0x80 & ~mask & ~((inp_len - j) >> (sizeof(j) * 8 - 8));
                 data->c[res++] = (unsigned char)c;
 
                 if (res != SHA_CBLOCK)
                     continue;
 
                 /* j is not incremented yet */
                 mask = 0 - ((inp_len + 7 - j) >> (sizeof(j) * 8 - 1));
                 data->u[SHA_LBLOCK - 1] |= bitlen & mask;
                 sha1_block_data_order(&key->md, data, 1);
                 mask &= 0 - ((j - inp_len - 72) >> (sizeof(j) * 8 - 1));
                 pmac->u[0] |= key->md.h0 & mask;
                 pmac->u[1] |= key->md.h1 & mask;
                 pmac->u[2] |= key->md.h2 & mask;
                 pmac->u[3] |= key->md.h3 & mask;
                 pmac->u[4] |= key->md.h4 & mask;
                 res = 0;
             }
 
             for (i = res; i < SHA_CBLOCK; i++, j++)
                 data->c[i] = 0;
 
             if (res > SHA_CBLOCK - 8) {
                 mask = 0 - ((inp_len + 8 - j) >> (sizeof(j) * 8 - 1));
                 data->u[SHA_LBLOCK - 1] |= bitlen & mask;
                 sha1_block_data_order(&key->md, data, 1);
                 mask &= 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1));
                 pmac->u[0] |= key->md.h0 & mask;
                 pmac->u[1] |= key->md.h1 & mask;
                 pmac->u[2] |= key->md.h2 & mask;
                 pmac->u[3] |= key->md.h3 & mask;
                 pmac->u[4] |= key->md.h4 & mask;
 
                 memset(data, 0, SHA_CBLOCK);
                 j += 64;
             }
             data->u[SHA_LBLOCK - 1] = bitlen;
             sha1_block_data_order(&key->md, data, 1);
             mask = 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1));
             pmac->u[0] |= key->md.h0 & mask;
             pmac->u[1] |= key->md.h1 & mask;
             pmac->u[2] |= key->md.h2 & mask;
             pmac->u[3] |= key->md.h3 & mask;
             pmac->u[4] |= key->md.h4 & mask;
 
 #   ifdef BSWAP4
             pmac->u[0] = BSWAP4(pmac->u[0]);
             pmac->u[1] = BSWAP4(pmac->u[1]);
             pmac->u[2] = BSWAP4(pmac->u[2]);
             pmac->u[3] = BSWAP4(pmac->u[3]);
             pmac->u[4] = BSWAP4(pmac->u[4]);
 #   else
             for (i = 0; i < 5; i++) {
                 res = pmac->u[i];
                 pmac->c[4 * i + 0] = (unsigned char)(res >> 24);
                 pmac->c[4 * i + 1] = (unsigned char)(res >> 16);
                 pmac->c[4 * i + 2] = (unsigned char)(res >> 8);
                 pmac->c[4 * i + 3] = (unsigned char)res;
             }
 #   endif
             len += SHA_DIGEST_LENGTH;
 #  else
             SHA1_Update(&key->md, out, inp_len);
             res = key->md.num;
             SHA1_Final(pmac->c, &key->md);
 
             {
                 unsigned int inp_blocks, pad_blocks;
 
                 /* but pretend as if we hashed padded payload */
                 inp_blocks =
                     1 + ((SHA_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1));
                 res += (unsigned int)(len - inp_len);
                 pad_blocks = res / SHA_CBLOCK;
                 res %= SHA_CBLOCK;
                 pad_blocks +=
                     1 + ((SHA_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1));
                 for (; inp_blocks < pad_blocks; inp_blocks++)
                     sha1_block_data_order(&key->md, data, 1);
             }
 #  endif
             key->md = key->tail;
             SHA1_Update(&key->md, pmac->c, SHA_DIGEST_LENGTH);
             SHA1_Final(pmac->c, &key->md);
 
             /* verify HMAC */
             out += inp_len;
             len -= inp_len;
 #  if 1
             {
                 unsigned char *p = out + len - 1 - maxpad - SHA_DIGEST_LENGTH;
                 size_t off = out - p;
                 unsigned int c, cmask;
 
                 maxpad += SHA_DIGEST_LENGTH;
                 for (res = 0, i = 0, j = 0; j < maxpad; j++) {
                     c = p[j];
                     cmask =
                         ((int)(j - off - SHA_DIGEST_LENGTH)) >> (sizeof(int) *
                                                                  8 - 1);
                     res |= (c ^ pad) & ~cmask; /* ... and padding */
                     cmask &= ((int)(off - 1 - j)) >> (sizeof(int) * 8 - 1);
                     res |= (c ^ pmac->c[i]) & cmask;
                     i += 1 & cmask;
                 }
                 maxpad -= SHA_DIGEST_LENGTH;
 
                 res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1));
                 ret &= (int)~res;
             }
 #  else
             for (res = 0, i = 0; i < SHA_DIGEST_LENGTH; i++)
                 res |= out[i] ^ pmac->c[i];
             res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1));
             ret &= (int)~res;
 
             /* verify padding */
             pad = (pad & ~res) | (maxpad & res);
             out = out + len - 1 - pad;
             for (res = 0, i = 0; i < pad; i++)
                 res |= out[i] ^ pad;
 
             res = (0 - res) >> (sizeof(res) * 8 - 1);
             ret &= (int)~res;
 #  endif
             return ret;
         } else {
 #  if defined(STITCHED_DECRYPT_CALL)
             if (len >= 1024 && ctx->key_len == 32) {
                 if (sha_off %= SHA_CBLOCK)
                     blocks = (len - 3 * SHA_CBLOCK) / SHA_CBLOCK;
                 else
                     blocks = (len - 2 * SHA_CBLOCK) / SHA_CBLOCK;
                 aes_off = len - blocks * SHA_CBLOCK;
 
                 aesni_cbc_encrypt(in, out, aes_off, &key->ks, ctx->iv, 0);
                 SHA1_Update(&key->md, out, sha_off);
                 aesni256_cbc_sha1_dec(in + aes_off,
                                       out + aes_off, blocks, &key->ks,
                                       ctx->iv, &key->md, out + sha_off);
 
                 sha_off += blocks *= SHA_CBLOCK;
                 out += sha_off;
                 len -= sha_off;
 
                 key->md.Nh += blocks >> 29;
                 key->md.Nl += blocks <<= 3;
                 if (key->md.Nl < (unsigned int)blocks)
                     key->md.Nh++;
             } else
 #  endif
                 /* decrypt HMAC|padding at once */
                 aesni_cbc_encrypt(in, out, len, &key->ks, ctx->iv, 0);
 
             SHA1_Update(&key->md, out, len);
         }
     }
 
     return 1;
 }
 
 static int aesni_cbc_hmac_sha1_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg,
                                     void *ptr)
 {
     EVP_AES_HMAC_SHA1 *key = data(ctx);
 
     switch (type) {
     case EVP_CTRL_AEAD_SET_MAC_KEY:
         {
             unsigned int i;
             unsigned char hmac_key[64];
 
             memset(hmac_key, 0, sizeof(hmac_key));
 
             if (arg > (int)sizeof(hmac_key)) {
                 SHA1_Init(&key->head);
                 SHA1_Update(&key->head, ptr, arg);
                 SHA1_Final(hmac_key, &key->head);
             } else {
                 memcpy(hmac_key, ptr, arg);
             }
 
             for (i = 0; i < sizeof(hmac_key); i++)
                 hmac_key[i] ^= 0x36; /* ipad */
             SHA1_Init(&key->head);
             SHA1_Update(&key->head, hmac_key, sizeof(hmac_key));
 
             for (i = 0; i < sizeof(hmac_key); i++)
                 hmac_key[i] ^= 0x36 ^ 0x5c; /* opad */
             SHA1_Init(&key->tail);
             SHA1_Update(&key->tail, hmac_key, sizeof(hmac_key));
 
             OPENSSL_cleanse(hmac_key, sizeof(hmac_key));
 
             return 1;
         }
     case EVP_CTRL_AEAD_TLS1_AAD:
         {
             unsigned char *p = ptr;
             unsigned int len;
 
             if (arg != EVP_AEAD_TLS1_AAD_LEN)
                 return -1;
  
             len = p[arg - 2] << 8 | p[arg - 1];
 
             if (ctx->encrypt) {
                 key->payload_length = len;
                 if ((key->aux.tls_ver =
                      p[arg - 4] << 8 | p[arg - 3]) >= TLS1_1_VERSION) {
+                    if (len < AES_BLOCK_SIZE)
+                        return 0;
                     len -= AES_BLOCK_SIZE;
                     p[arg - 2] = len >> 8;
                     p[arg - 1] = len;
                 }
                 key->md = key->head;
                 SHA1_Update(&key->md, p, arg);
 
                 return (int)(((len + SHA_DIGEST_LENGTH +
                                AES_BLOCK_SIZE) & -AES_BLOCK_SIZE)
                              - len);
             } else {
                 memcpy(key->aux.tls_aad, ptr, arg);
                 key->payload_length = arg;
 
                 return SHA_DIGEST_LENGTH;
             }
         }
 #  if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
     case EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE:
         return (int)(5 + 16 + ((arg + 20 + 16) & -16));
     case EVP_CTRL_TLS1_1_MULTIBLOCK_AAD:
         {
             EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *param =
                 (EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *) ptr;
             unsigned int n4x = 1, x4;
             unsigned int frag, last, packlen, inp_len;
 
             if (arg < (int)sizeof(EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM))
                 return -1;
 
             inp_len = param->inp[11] << 8 | param->inp[12];
 
             if (ctx->encrypt) {
                 if ((param->inp[9] << 8 | param->inp[10]) < TLS1_1_VERSION)
                     return -1;
 
                 if (inp_len) {
                     if (inp_len < 4096)
                         return 0; /* too short */
 
                     if (inp_len >= 8192 && OPENSSL_ia32cap_P[2] & (1 << 5))
                         n4x = 2; /* AVX2 */
                 } else if ((n4x = param->interleave / 4) && n4x <= 2)
                     inp_len = param->len;
                 else
                     return -1;
 
                 key->md = key->head;
                 SHA1_Update(&key->md, param->inp, 13);
 
                 x4 = 4 * n4x;
                 n4x += 1;
 
                 frag = inp_len >> n4x;
                 last = inp_len + frag - (frag << n4x);
                 if (last > frag && ((last + 13 + 9) % 64 < (x4 - 1))) {
                     frag++;
                     last -= x4 - 1;
                 }
 
                 packlen = 5 + 16 + ((frag + 20 + 16) & -16);
                 packlen = (packlen << n4x) - packlen;
                 packlen += 5 + 16 + ((last + 20 + 16) & -16);
 
                 param->interleave = x4;
 
                 return (int)packlen;
             } else
                 return -1;      /* not yet */
         }
     case EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT:
         {
             EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *param =
                 (EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *) ptr;
 
             return (int)tls1_1_multi_block_encrypt(key, param->out,
                                                    param->inp, param->len,
                                                    param->interleave / 4);
         }
     case EVP_CTRL_TLS1_1_MULTIBLOCK_DECRYPT:
 #  endif
     default:
         return -1;
     }
 }
 
 static EVP_CIPHER aesni_128_cbc_hmac_sha1_cipher = {
 #  ifdef NID_aes_128_cbc_hmac_sha1
     NID_aes_128_cbc_hmac_sha1,
 #  else
     NID_undef,
 #  endif
     16, 16, 16,
     EVP_CIPH_CBC_MODE | EVP_CIPH_FLAG_DEFAULT_ASN1 |
         EVP_CIPH_FLAG_AEAD_CIPHER | EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK,
     aesni_cbc_hmac_sha1_init_key,
     aesni_cbc_hmac_sha1_cipher,
     NULL,
     sizeof(EVP_AES_HMAC_SHA1),
     EVP_CIPH_FLAG_DEFAULT_ASN1 ? NULL : EVP_CIPHER_set_asn1_iv,
     EVP_CIPH_FLAG_DEFAULT_ASN1 ? NULL : EVP_CIPHER_get_asn1_iv,
     aesni_cbc_hmac_sha1_ctrl,
     NULL
 };
 
 static EVP_CIPHER aesni_256_cbc_hmac_sha1_cipher = {
 #  ifdef NID_aes_256_cbc_hmac_sha1
     NID_aes_256_cbc_hmac_sha1,
 #  else
     NID_undef,
 #  endif
     16, 32, 16,
     EVP_CIPH_CBC_MODE | EVP_CIPH_FLAG_DEFAULT_ASN1 |
         EVP_CIPH_FLAG_AEAD_CIPHER | EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK,
     aesni_cbc_hmac_sha1_init_key,
     aesni_cbc_hmac_sha1_cipher,
     NULL,
     sizeof(EVP_AES_HMAC_SHA1),
     EVP_CIPH_FLAG_DEFAULT_ASN1 ? NULL : EVP_CIPHER_set_asn1_iv,
     EVP_CIPH_FLAG_DEFAULT_ASN1 ? NULL : EVP_CIPHER_get_asn1_iv,
     aesni_cbc_hmac_sha1_ctrl,
     NULL
 };
 
 const EVP_CIPHER *EVP_aes_128_cbc_hmac_sha1(void)
 {
     return (OPENSSL_ia32cap_P[1] & AESNI_CAPABLE ?
             &aesni_128_cbc_hmac_sha1_cipher : NULL);
 }
 
 const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha1(void)
 {
     return (OPENSSL_ia32cap_P[1] & AESNI_CAPABLE ?
             &aesni_256_cbc_hmac_sha1_cipher : NULL);
 }
 # else
 const EVP_CIPHER *EVP_aes_128_cbc_hmac_sha1(void)
 {
     return NULL;
 }
 
 const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha1(void)
 {
     return NULL;
 }
 # endif
 #endif
Index: vendor-crypto/openssl/dist/crypto/evp/e_aes_cbc_hmac_sha256.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/evp/e_aes_cbc_hmac_sha256.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/evp/e_aes_cbc_hmac_sha256.c	(revision 318897)
@@ -1,985 +1,989 @@
 /* ====================================================================
  * Copyright (c) 2011-2013 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    licensing@OpenSSL.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  */
 
 #include 
 
 #include 
 #include 
 
 #if !defined(OPENSSL_NO_AES) && !defined(OPENSSL_NO_SHA256)
 
 # include 
 # include 
 # include 
 # include 
 # include 
 # include "modes_lcl.h"
 # include "constant_time_locl.h"
 
 # ifndef EVP_CIPH_FLAG_AEAD_CIPHER
 #  define EVP_CIPH_FLAG_AEAD_CIPHER       0x200000
 #  define EVP_CTRL_AEAD_TLS1_AAD          0x16
 #  define EVP_CTRL_AEAD_SET_MAC_KEY       0x17
 # endif
 
 # if !defined(EVP_CIPH_FLAG_DEFAULT_ASN1)
 #  define EVP_CIPH_FLAG_DEFAULT_ASN1 0
 # endif
 
 # if !defined(EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK)
 #  define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
 # endif
 
 # define TLS1_1_VERSION 0x0302
 
 typedef struct {
     AES_KEY ks;
     SHA256_CTX head, tail, md;
     size_t payload_length;      /* AAD length in decrypt case */
     union {
         unsigned int tls_ver;
         unsigned char tls_aad[16]; /* 13 used */
     } aux;
 } EVP_AES_HMAC_SHA256;
 
 # define NO_PAYLOAD_LENGTH       ((size_t)-1)
 
 # if     defined(AES_ASM) &&     ( \
         defined(__x86_64)       || defined(__x86_64__)  || \
         defined(_M_AMD64)       || defined(_M_X64)      || \
         defined(__INTEL__)      )
 
 extern unsigned int OPENSSL_ia32cap_P[];
 #  define AESNI_CAPABLE   (1<<(57-32))
 
 int aesni_set_encrypt_key(const unsigned char *userKey, int bits,
                           AES_KEY *key);
 int aesni_set_decrypt_key(const unsigned char *userKey, int bits,
                           AES_KEY *key);
 
 void aesni_cbc_encrypt(const unsigned char *in,
                        unsigned char *out,
                        size_t length,
                        const AES_KEY *key, unsigned char *ivec, int enc);
 
 int aesni_cbc_sha256_enc(const void *inp, void *out, size_t blocks,
                          const AES_KEY *key, unsigned char iv[16],
                          SHA256_CTX *ctx, const void *in0);
 
 #  define data(ctx) ((EVP_AES_HMAC_SHA256 *)(ctx)->cipher_data)
 
 static int aesni_cbc_hmac_sha256_init_key(EVP_CIPHER_CTX *ctx,
                                           const unsigned char *inkey,
                                           const unsigned char *iv, int enc)
 {
     EVP_AES_HMAC_SHA256 *key = data(ctx);
     int ret;
 
     if (enc)
         memset(&key->ks, 0, sizeof(key->ks.rd_key)),
             ret = aesni_set_encrypt_key(inkey, ctx->key_len * 8, &key->ks);
     else
         ret = aesni_set_decrypt_key(inkey, ctx->key_len * 8, &key->ks);
 
     SHA256_Init(&key->head);    /* handy when benchmarking */
     key->tail = key->head;
     key->md = key->head;
 
     key->payload_length = NO_PAYLOAD_LENGTH;
 
     return ret < 0 ? 0 : 1;
 }
 
 #  define STITCHED_CALL
 
 #  if !defined(STITCHED_CALL)
 #   define aes_off 0
 #  endif
 
 void sha256_block_data_order(void *c, const void *p, size_t len);
 
 static void sha256_update(SHA256_CTX *c, const void *data, size_t len)
 {
     const unsigned char *ptr = data;
     size_t res;
 
     if ((res = c->num)) {
         res = SHA256_CBLOCK - res;
         if (len < res)
             res = len;
         SHA256_Update(c, ptr, res);
         ptr += res;
         len -= res;
     }
 
     res = len % SHA256_CBLOCK;
     len -= res;
 
     if (len) {
         sha256_block_data_order(c, ptr, len / SHA256_CBLOCK);
 
         ptr += len;
         c->Nh += len >> 29;
         c->Nl += len <<= 3;
         if (c->Nl < (unsigned int)len)
             c->Nh++;
     }
 
     if (res)
         SHA256_Update(c, ptr, res);
 }
 
 #  ifdef SHA256_Update
 #   undef SHA256_Update
 #  endif
 #  define SHA256_Update sha256_update
 
 #  if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
 
 typedef struct {
     unsigned int A[8], B[8], C[8], D[8], E[8], F[8], G[8], H[8];
 } SHA256_MB_CTX;
 typedef struct {
     const unsigned char *ptr;
     int blocks;
 } HASH_DESC;
 
 void sha256_multi_block(SHA256_MB_CTX *, const HASH_DESC *, int);
 
 typedef struct {
     const unsigned char *inp;
     unsigned char *out;
     int blocks;
     u64 iv[2];
 } CIPH_DESC;
 
 void aesni_multi_cbc_encrypt(CIPH_DESC *, void *, int);
 
 static size_t tls1_1_multi_block_encrypt(EVP_AES_HMAC_SHA256 *key,
                                          unsigned char *out,
                                          const unsigned char *inp,
                                          size_t inp_len, int n4x)
 {                               /* n4x is 1 or 2 */
     HASH_DESC hash_d[8], edges[8];
     CIPH_DESC ciph_d[8];
     unsigned char storage[sizeof(SHA256_MB_CTX) + 32];
     union {
         u64 q[16];
         u32 d[32];
         u8 c[128];
     } blocks[8];
     SHA256_MB_CTX *ctx;
     unsigned int frag, last, packlen, i, x4 = 4 * n4x, minblocks, processed =
         0;
     size_t ret = 0;
     u8 *IVs;
 #   if defined(BSWAP8)
     u64 seqnum;
 #   endif
 
     /* ask for IVs in bulk */
     if (RAND_bytes((IVs = blocks[0].c), 16 * x4) <= 0)
         return 0;
 
     /* align */
     ctx = (SHA256_MB_CTX *) (storage + 32 - ((size_t)storage % 32));
 
     frag = (unsigned int)inp_len >> (1 + n4x);
     last = (unsigned int)inp_len + frag - (frag << (1 + n4x));
     if (last > frag && ((last + 13 + 9) % 64) < (x4 - 1)) {
         frag++;
         last -= x4 - 1;
     }
 
     packlen = 5 + 16 + ((frag + 32 + 16) & -16);
 
     /* populate descriptors with pointers and IVs */
     hash_d[0].ptr = inp;
     ciph_d[0].inp = inp;
     /* 5+16 is place for header and explicit IV */
     ciph_d[0].out = out + 5 + 16;
     memcpy(ciph_d[0].out - 16, IVs, 16);
     memcpy(ciph_d[0].iv, IVs, 16);
     IVs += 16;
 
     for (i = 1; i < x4; i++) {
         ciph_d[i].inp = hash_d[i].ptr = hash_d[i - 1].ptr + frag;
         ciph_d[i].out = ciph_d[i - 1].out + packlen;
         memcpy(ciph_d[i].out - 16, IVs, 16);
         memcpy(ciph_d[i].iv, IVs, 16);
         IVs += 16;
     }
 
 #   if defined(BSWAP8)
     memcpy(blocks[0].c, key->md.data, 8);
     seqnum = BSWAP8(blocks[0].q[0]);
 #   endif
     for (i = 0; i < x4; i++) {
         unsigned int len = (i == (x4 - 1) ? last : frag);
 #   if !defined(BSWAP8)
         unsigned int carry, j;
 #   endif
 
         ctx->A[i] = key->md.h[0];
         ctx->B[i] = key->md.h[1];
         ctx->C[i] = key->md.h[2];
         ctx->D[i] = key->md.h[3];
         ctx->E[i] = key->md.h[4];
         ctx->F[i] = key->md.h[5];
         ctx->G[i] = key->md.h[6];
         ctx->H[i] = key->md.h[7];
 
         /* fix seqnum */
 #   if defined(BSWAP8)
         blocks[i].q[0] = BSWAP8(seqnum + i);
 #   else
         for (carry = i, j = 8; j--;) {
             blocks[i].c[j] = ((u8 *)key->md.data)[j] + carry;
             carry = (blocks[i].c[j] - carry) >> (sizeof(carry) * 8 - 1);
         }
 #   endif
         blocks[i].c[8] = ((u8 *)key->md.data)[8];
         blocks[i].c[9] = ((u8 *)key->md.data)[9];
         blocks[i].c[10] = ((u8 *)key->md.data)[10];
         /* fix length */
         blocks[i].c[11] = (u8)(len >> 8);
         blocks[i].c[12] = (u8)(len);
 
         memcpy(blocks[i].c + 13, hash_d[i].ptr, 64 - 13);
         hash_d[i].ptr += 64 - 13;
         hash_d[i].blocks = (len - (64 - 13)) / 64;
 
         edges[i].ptr = blocks[i].c;
         edges[i].blocks = 1;
     }
 
     /* hash 13-byte headers and first 64-13 bytes of inputs */
     sha256_multi_block(ctx, edges, n4x);
     /* hash bulk inputs */
 #   define MAXCHUNKSIZE    2048
 #   if     MAXCHUNKSIZE%64
 #    error  "MAXCHUNKSIZE is not divisible by 64"
 #   elif   MAXCHUNKSIZE
     /*
      * goal is to minimize pressure on L1 cache by moving in shorter steps,
      * so that hashed data is still in the cache by the time we encrypt it
      */
     minblocks = ((frag <= last ? frag : last) - (64 - 13)) / 64;
     if (minblocks > MAXCHUNKSIZE / 64) {
         for (i = 0; i < x4; i++) {
             edges[i].ptr = hash_d[i].ptr;
             edges[i].blocks = MAXCHUNKSIZE / 64;
             ciph_d[i].blocks = MAXCHUNKSIZE / 16;
         }
         do {
             sha256_multi_block(ctx, edges, n4x);
             aesni_multi_cbc_encrypt(ciph_d, &key->ks, n4x);
 
             for (i = 0; i < x4; i++) {
                 edges[i].ptr = hash_d[i].ptr += MAXCHUNKSIZE;
                 hash_d[i].blocks -= MAXCHUNKSIZE / 64;
                 edges[i].blocks = MAXCHUNKSIZE / 64;
                 ciph_d[i].inp += MAXCHUNKSIZE;
                 ciph_d[i].out += MAXCHUNKSIZE;
                 ciph_d[i].blocks = MAXCHUNKSIZE / 16;
                 memcpy(ciph_d[i].iv, ciph_d[i].out - 16, 16);
             }
             processed += MAXCHUNKSIZE;
             minblocks -= MAXCHUNKSIZE / 64;
         } while (minblocks > MAXCHUNKSIZE / 64);
     }
 #   endif
 #   undef  MAXCHUNKSIZE
     sha256_multi_block(ctx, hash_d, n4x);
 
     memset(blocks, 0, sizeof(blocks));
     for (i = 0; i < x4; i++) {
         unsigned int len = (i == (x4 - 1) ? last : frag),
             off = hash_d[i].blocks * 64;
         const unsigned char *ptr = hash_d[i].ptr + off;
 
         off = (len - processed) - (64 - 13) - off; /* remainder actually */
         memcpy(blocks[i].c, ptr, off);
         blocks[i].c[off] = 0x80;
         len += 64 + 13;         /* 64 is HMAC header */
         len *= 8;               /* convert to bits */
         if (off < (64 - 8)) {
 #   ifdef BSWAP4
             blocks[i].d[15] = BSWAP4(len);
 #   else
             PUTU32(blocks[i].c + 60, len);
 #   endif
             edges[i].blocks = 1;
         } else {
 #   ifdef BSWAP4
             blocks[i].d[31] = BSWAP4(len);
 #   else
             PUTU32(blocks[i].c + 124, len);
 #   endif
             edges[i].blocks = 2;
         }
         edges[i].ptr = blocks[i].c;
     }
 
     /* hash input tails and finalize */
     sha256_multi_block(ctx, edges, n4x);
 
     memset(blocks, 0, sizeof(blocks));
     for (i = 0; i < x4; i++) {
 #   ifdef BSWAP4
         blocks[i].d[0] = BSWAP4(ctx->A[i]);
         ctx->A[i] = key->tail.h[0];
         blocks[i].d[1] = BSWAP4(ctx->B[i]);
         ctx->B[i] = key->tail.h[1];
         blocks[i].d[2] = BSWAP4(ctx->C[i]);
         ctx->C[i] = key->tail.h[2];
         blocks[i].d[3] = BSWAP4(ctx->D[i]);
         ctx->D[i] = key->tail.h[3];
         blocks[i].d[4] = BSWAP4(ctx->E[i]);
         ctx->E[i] = key->tail.h[4];
         blocks[i].d[5] = BSWAP4(ctx->F[i]);
         ctx->F[i] = key->tail.h[5];
         blocks[i].d[6] = BSWAP4(ctx->G[i]);
         ctx->G[i] = key->tail.h[6];
         blocks[i].d[7] = BSWAP4(ctx->H[i]);
         ctx->H[i] = key->tail.h[7];
         blocks[i].c[32] = 0x80;
         blocks[i].d[15] = BSWAP4((64 + 32) * 8);
 #   else
         PUTU32(blocks[i].c + 0, ctx->A[i]);
         ctx->A[i] = key->tail.h[0];
         PUTU32(blocks[i].c + 4, ctx->B[i]);
         ctx->B[i] = key->tail.h[1];
         PUTU32(blocks[i].c + 8, ctx->C[i]);
         ctx->C[i] = key->tail.h[2];
         PUTU32(blocks[i].c + 12, ctx->D[i]);
         ctx->D[i] = key->tail.h[3];
         PUTU32(blocks[i].c + 16, ctx->E[i]);
         ctx->E[i] = key->tail.h[4];
         PUTU32(blocks[i].c + 20, ctx->F[i]);
         ctx->F[i] = key->tail.h[5];
         PUTU32(blocks[i].c + 24, ctx->G[i]);
         ctx->G[i] = key->tail.h[6];
         PUTU32(blocks[i].c + 28, ctx->H[i]);
         ctx->H[i] = key->tail.h[7];
         blocks[i].c[32] = 0x80;
         PUTU32(blocks[i].c + 60, (64 + 32) * 8);
 #   endif
         edges[i].ptr = blocks[i].c;
         edges[i].blocks = 1;
     }
 
     /* finalize MACs */
     sha256_multi_block(ctx, edges, n4x);
 
     for (i = 0; i < x4; i++) {
         unsigned int len = (i == (x4 - 1) ? last : frag), pad, j;
         unsigned char *out0 = out;
 
         memcpy(ciph_d[i].out, ciph_d[i].inp, len - processed);
         ciph_d[i].inp = ciph_d[i].out;
 
         out += 5 + 16 + len;
 
         /* write MAC */
         PUTU32(out + 0, ctx->A[i]);
         PUTU32(out + 4, ctx->B[i]);
         PUTU32(out + 8, ctx->C[i]);
         PUTU32(out + 12, ctx->D[i]);
         PUTU32(out + 16, ctx->E[i]);
         PUTU32(out + 20, ctx->F[i]);
         PUTU32(out + 24, ctx->G[i]);
         PUTU32(out + 28, ctx->H[i]);
         out += 32;
         len += 32;
 
         /* pad */
         pad = 15 - len % 16;
         for (j = 0; j <= pad; j++)
             *(out++) = pad;
         len += pad + 1;
 
         ciph_d[i].blocks = (len - processed) / 16;
         len += 16;              /* account for explicit iv */
 
         /* arrange header */
         out0[0] = ((u8 *)key->md.data)[8];
         out0[1] = ((u8 *)key->md.data)[9];
         out0[2] = ((u8 *)key->md.data)[10];
         out0[3] = (u8)(len >> 8);
         out0[4] = (u8)(len);
 
         ret += len + 5;
         inp += frag;
     }
 
     aesni_multi_cbc_encrypt(ciph_d, &key->ks, n4x);
 
     OPENSSL_cleanse(blocks, sizeof(blocks));
     OPENSSL_cleanse(ctx, sizeof(*ctx));
 
     return ret;
 }
 #  endif
 
 static int aesni_cbc_hmac_sha256_cipher(EVP_CIPHER_CTX *ctx,
                                         unsigned char *out,
                                         const unsigned char *in, size_t len)
 {
     EVP_AES_HMAC_SHA256 *key = data(ctx);
     unsigned int l;
     size_t plen = key->payload_length, iv = 0, /* explicit IV in TLS 1.1 and
                                                 * later */
         sha_off = 0;
 #  if defined(STITCHED_CALL)
     size_t aes_off = 0, blocks;
 
     sha_off = SHA256_CBLOCK - key->md.num;
 #  endif
 
     key->payload_length = NO_PAYLOAD_LENGTH;
 
     if (len % AES_BLOCK_SIZE)
         return 0;
 
     if (ctx->encrypt) {
         if (plen == NO_PAYLOAD_LENGTH)
             plen = len;
         else if (len !=
                  ((plen + SHA256_DIGEST_LENGTH +
                    AES_BLOCK_SIZE) & -AES_BLOCK_SIZE))
             return 0;
         else if (key->aux.tls_ver >= TLS1_1_VERSION)
             iv = AES_BLOCK_SIZE;
 
 #  if defined(STITCHED_CALL)
         /*
          * Assembly stitch handles AVX-capable processors, but its
          * performance is not optimal on AMD Jaguar, ~40% worse, for
          * unknown reasons. Incidentally processor in question supports
          * AVX, but not AMD-specific XOP extension, which can be used
          * to identify it and avoid stitch invocation. So that after we
          * establish that current CPU supports AVX, we even see if it's
          * either even XOP-capable Bulldozer-based or GenuineIntel one.
          */
         if (OPENSSL_ia32cap_P[1] & (1 << (60 - 32)) && /* AVX? */
             ((OPENSSL_ia32cap_P[1] & (1 << (43 - 32))) /* XOP? */
              | (OPENSSL_ia32cap_P[0] & (1<<30))) &&    /* "Intel CPU"? */
             plen > (sha_off + iv) &&
             (blocks = (plen - (sha_off + iv)) / SHA256_CBLOCK)) {
             SHA256_Update(&key->md, in + iv, sha_off);
 
             (void)aesni_cbc_sha256_enc(in, out, blocks, &key->ks,
                                        ctx->iv, &key->md, in + iv + sha_off);
             blocks *= SHA256_CBLOCK;
             aes_off += blocks;
             sha_off += blocks;
             key->md.Nh += blocks >> 29;
             key->md.Nl += blocks <<= 3;
             if (key->md.Nl < (unsigned int)blocks)
                 key->md.Nh++;
         } else {
             sha_off = 0;
         }
 #  endif
         sha_off += iv;
         SHA256_Update(&key->md, in + sha_off, plen - sha_off);
 
         if (plen != len) {      /* "TLS" mode of operation */
             if (in != out)
                 memcpy(out + aes_off, in + aes_off, plen - aes_off);
 
             /* calculate HMAC and append it to payload */
             SHA256_Final(out + plen, &key->md);
             key->md = key->tail;
             SHA256_Update(&key->md, out + plen, SHA256_DIGEST_LENGTH);
             SHA256_Final(out + plen, &key->md);
 
             /* pad the payload|hmac */
             plen += SHA256_DIGEST_LENGTH;
             for (l = len - plen - 1; plen < len; plen++)
                 out[plen] = l;
             /* encrypt HMAC|padding at once */
             aesni_cbc_encrypt(out + aes_off, out + aes_off, len - aes_off,
                               &key->ks, ctx->iv, 1);
         } else {
             aesni_cbc_encrypt(in + aes_off, out + aes_off, len - aes_off,
                               &key->ks, ctx->iv, 1);
         }
     } else {
         union {
             unsigned int u[SHA256_DIGEST_LENGTH / sizeof(unsigned int)];
             unsigned char c[64 + SHA256_DIGEST_LENGTH];
         } mac, *pmac;
 
         /* arrange cache line alignment */
         pmac = (void *)(((size_t)mac.c + 63) & ((size_t)0 - 64));
 
         /* decrypt HMAC|padding at once */
         aesni_cbc_encrypt(in, out, len, &key->ks, ctx->iv, 0);
 
         if (plen != NO_PAYLOAD_LENGTH) { /* "TLS" mode of operation */
             size_t inp_len, mask, j, i;
             unsigned int res, maxpad, pad, bitlen;
             int ret = 1;
             union {
                 unsigned int u[SHA_LBLOCK];
                 unsigned char c[SHA256_CBLOCK];
             } *data = (void *)key->md.data;
 
             if ((key->aux.tls_aad[plen - 4] << 8 | key->aux.tls_aad[plen - 3])
                 >= TLS1_1_VERSION)
                 iv = AES_BLOCK_SIZE;
 
             if (len < (iv + SHA256_DIGEST_LENGTH + 1))
                 return 0;
 
             /* omit explicit iv */
             out += iv;
             len -= iv;
 
             /* figure out payload length */
             pad = out[len - 1];
             maxpad = len - (SHA256_DIGEST_LENGTH + 1);
             maxpad |= (255 - maxpad) >> (sizeof(maxpad) * 8 - 8);
             maxpad &= 255;
 
             ret &= constant_time_ge(maxpad, pad);
 
             inp_len = len - (SHA256_DIGEST_LENGTH + pad + 1);
             mask = (0 - ((inp_len - len) >> (sizeof(inp_len) * 8 - 1)));
             inp_len &= mask;
             ret &= (int)mask;
 
             key->aux.tls_aad[plen - 2] = inp_len >> 8;
             key->aux.tls_aad[plen - 1] = inp_len;
 
             /* calculate HMAC */
             key->md = key->head;
             SHA256_Update(&key->md, key->aux.tls_aad, plen);
 
 #  if 1
             len -= SHA256_DIGEST_LENGTH; /* amend mac */
             if (len >= (256 + SHA256_CBLOCK)) {
                 j = (len - (256 + SHA256_CBLOCK)) & (0 - SHA256_CBLOCK);
                 j += SHA256_CBLOCK - key->md.num;
                 SHA256_Update(&key->md, out, j);
                 out += j;
                 len -= j;
                 inp_len -= j;
             }
 
             /* but pretend as if we hashed padded payload */
             bitlen = key->md.Nl + (inp_len << 3); /* at most 18 bits */
 #   ifdef BSWAP4
             bitlen = BSWAP4(bitlen);
 #   else
             mac.c[0] = 0;
             mac.c[1] = (unsigned char)(bitlen >> 16);
             mac.c[2] = (unsigned char)(bitlen >> 8);
             mac.c[3] = (unsigned char)bitlen;
             bitlen = mac.u[0];
 #   endif
 
             pmac->u[0] = 0;
             pmac->u[1] = 0;
             pmac->u[2] = 0;
             pmac->u[3] = 0;
             pmac->u[4] = 0;
             pmac->u[5] = 0;
             pmac->u[6] = 0;
             pmac->u[7] = 0;
 
             for (res = key->md.num, j = 0; j < len; j++) {
                 size_t c = out[j];
                 mask = (j - inp_len) >> (sizeof(j) * 8 - 8);
                 c &= mask;
                 c |= 0x80 & ~mask & ~((inp_len - j) >> (sizeof(j) * 8 - 8));
                 data->c[res++] = (unsigned char)c;
 
                 if (res != SHA256_CBLOCK)
                     continue;
 
                 /* j is not incremented yet */
                 mask = 0 - ((inp_len + 7 - j) >> (sizeof(j) * 8 - 1));
                 data->u[SHA_LBLOCK - 1] |= bitlen & mask;
                 sha256_block_data_order(&key->md, data, 1);
                 mask &= 0 - ((j - inp_len - 72) >> (sizeof(j) * 8 - 1));
                 pmac->u[0] |= key->md.h[0] & mask;
                 pmac->u[1] |= key->md.h[1] & mask;
                 pmac->u[2] |= key->md.h[2] & mask;
                 pmac->u[3] |= key->md.h[3] & mask;
                 pmac->u[4] |= key->md.h[4] & mask;
                 pmac->u[5] |= key->md.h[5] & mask;
                 pmac->u[6] |= key->md.h[6] & mask;
                 pmac->u[7] |= key->md.h[7] & mask;
                 res = 0;
             }
 
             for (i = res; i < SHA256_CBLOCK; i++, j++)
                 data->c[i] = 0;
 
             if (res > SHA256_CBLOCK - 8) {
                 mask = 0 - ((inp_len + 8 - j) >> (sizeof(j) * 8 - 1));
                 data->u[SHA_LBLOCK - 1] |= bitlen & mask;
                 sha256_block_data_order(&key->md, data, 1);
                 mask &= 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1));
                 pmac->u[0] |= key->md.h[0] & mask;
                 pmac->u[1] |= key->md.h[1] & mask;
                 pmac->u[2] |= key->md.h[2] & mask;
                 pmac->u[3] |= key->md.h[3] & mask;
                 pmac->u[4] |= key->md.h[4] & mask;
                 pmac->u[5] |= key->md.h[5] & mask;
                 pmac->u[6] |= key->md.h[6] & mask;
                 pmac->u[7] |= key->md.h[7] & mask;
 
                 memset(data, 0, SHA256_CBLOCK);
                 j += 64;
             }
             data->u[SHA_LBLOCK - 1] = bitlen;
             sha256_block_data_order(&key->md, data, 1);
             mask = 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1));
             pmac->u[0] |= key->md.h[0] & mask;
             pmac->u[1] |= key->md.h[1] & mask;
             pmac->u[2] |= key->md.h[2] & mask;
             pmac->u[3] |= key->md.h[3] & mask;
             pmac->u[4] |= key->md.h[4] & mask;
             pmac->u[5] |= key->md.h[5] & mask;
             pmac->u[6] |= key->md.h[6] & mask;
             pmac->u[7] |= key->md.h[7] & mask;
 
 #   ifdef BSWAP4
             pmac->u[0] = BSWAP4(pmac->u[0]);
             pmac->u[1] = BSWAP4(pmac->u[1]);
             pmac->u[2] = BSWAP4(pmac->u[2]);
             pmac->u[3] = BSWAP4(pmac->u[3]);
             pmac->u[4] = BSWAP4(pmac->u[4]);
             pmac->u[5] = BSWAP4(pmac->u[5]);
             pmac->u[6] = BSWAP4(pmac->u[6]);
             pmac->u[7] = BSWAP4(pmac->u[7]);
 #   else
             for (i = 0; i < 8; i++) {
                 res = pmac->u[i];
                 pmac->c[4 * i + 0] = (unsigned char)(res >> 24);
                 pmac->c[4 * i + 1] = (unsigned char)(res >> 16);
                 pmac->c[4 * i + 2] = (unsigned char)(res >> 8);
                 pmac->c[4 * i + 3] = (unsigned char)res;
             }
 #   endif
             len += SHA256_DIGEST_LENGTH;
 #  else
             SHA256_Update(&key->md, out, inp_len);
             res = key->md.num;
             SHA256_Final(pmac->c, &key->md);
 
             {
                 unsigned int inp_blocks, pad_blocks;
 
                 /* but pretend as if we hashed padded payload */
                 inp_blocks =
                     1 + ((SHA256_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1));
                 res += (unsigned int)(len - inp_len);
                 pad_blocks = res / SHA256_CBLOCK;
                 res %= SHA256_CBLOCK;
                 pad_blocks +=
                     1 + ((SHA256_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1));
                 for (; inp_blocks < pad_blocks; inp_blocks++)
                     sha1_block_data_order(&key->md, data, 1);
             }
 #  endif
             key->md = key->tail;
             SHA256_Update(&key->md, pmac->c, SHA256_DIGEST_LENGTH);
             SHA256_Final(pmac->c, &key->md);
 
             /* verify HMAC */
             out += inp_len;
             len -= inp_len;
 #  if 1
             {
                 unsigned char *p =
                     out + len - 1 - maxpad - SHA256_DIGEST_LENGTH;
                 size_t off = out - p;
                 unsigned int c, cmask;
 
                 maxpad += SHA256_DIGEST_LENGTH;
                 for (res = 0, i = 0, j = 0; j < maxpad; j++) {
                     c = p[j];
                     cmask =
                         ((int)(j - off - SHA256_DIGEST_LENGTH)) >>
                         (sizeof(int) * 8 - 1);
                     res |= (c ^ pad) & ~cmask; /* ... and padding */
                     cmask &= ((int)(off - 1 - j)) >> (sizeof(int) * 8 - 1);
                     res |= (c ^ pmac->c[i]) & cmask;
                     i += 1 & cmask;
                 }
                 maxpad -= SHA256_DIGEST_LENGTH;
 
                 res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1));
                 ret &= (int)~res;
             }
 #  else
             for (res = 0, i = 0; i < SHA256_DIGEST_LENGTH; i++)
                 res |= out[i] ^ pmac->c[i];
             res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1));
             ret &= (int)~res;
 
             /* verify padding */
             pad = (pad & ~res) | (maxpad & res);
             out = out + len - 1 - pad;
             for (res = 0, i = 0; i < pad; i++)
                 res |= out[i] ^ pad;
 
             res = (0 - res) >> (sizeof(res) * 8 - 1);
             ret &= (int)~res;
 #  endif
             return ret;
         } else {
             SHA256_Update(&key->md, out, len);
         }
     }
 
     return 1;
 }
 
 static int aesni_cbc_hmac_sha256_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg,
                                       void *ptr)
 {
     EVP_AES_HMAC_SHA256 *key = data(ctx);
 
     switch (type) {
     case EVP_CTRL_AEAD_SET_MAC_KEY:
         {
             unsigned int i;
             unsigned char hmac_key[64];
 
             memset(hmac_key, 0, sizeof(hmac_key));
 
             if (arg > (int)sizeof(hmac_key)) {
                 SHA256_Init(&key->head);
                 SHA256_Update(&key->head, ptr, arg);
                 SHA256_Final(hmac_key, &key->head);
             } else {
                 memcpy(hmac_key, ptr, arg);
             }
 
             for (i = 0; i < sizeof(hmac_key); i++)
                 hmac_key[i] ^= 0x36; /* ipad */
             SHA256_Init(&key->head);
             SHA256_Update(&key->head, hmac_key, sizeof(hmac_key));
 
             for (i = 0; i < sizeof(hmac_key); i++)
                 hmac_key[i] ^= 0x36 ^ 0x5c; /* opad */
             SHA256_Init(&key->tail);
             SHA256_Update(&key->tail, hmac_key, sizeof(hmac_key));
 
             OPENSSL_cleanse(hmac_key, sizeof(hmac_key));
 
             return 1;
         }
     case EVP_CTRL_AEAD_TLS1_AAD:
         {
             unsigned char *p = ptr;
-            unsigned int len = p[arg - 2] << 8 | p[arg - 1];
+            unsigned int len;
 
             if (arg != EVP_AEAD_TLS1_AAD_LEN)
                 return -1;
 
+            len = p[arg - 2] << 8 | p[arg - 1];
+
             if (ctx->encrypt) {
                 key->payload_length = len;
                 if ((key->aux.tls_ver =
                      p[arg - 4] << 8 | p[arg - 3]) >= TLS1_1_VERSION) {
+                    if (len < AES_BLOCK_SIZE)
+                        return 0;
                     len -= AES_BLOCK_SIZE;
                     p[arg - 2] = len >> 8;
                     p[arg - 1] = len;
                 }
                 key->md = key->head;
                 SHA256_Update(&key->md, p, arg);
 
                 return (int)(((len + SHA256_DIGEST_LENGTH +
                                AES_BLOCK_SIZE) & -AES_BLOCK_SIZE)
                              - len);
             } else {
                 memcpy(key->aux.tls_aad, ptr, arg);
                 key->payload_length = arg;
 
                 return SHA256_DIGEST_LENGTH;
             }
         }
 #  if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
     case EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE:
         return (int)(5 + 16 + ((arg + 32 + 16) & -16));
     case EVP_CTRL_TLS1_1_MULTIBLOCK_AAD:
         {
             EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *param =
                 (EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *) ptr;
             unsigned int n4x = 1, x4;
             unsigned int frag, last, packlen, inp_len;
 
             if (arg < (int)sizeof(EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM))
                 return -1;
 
             inp_len = param->inp[11] << 8 | param->inp[12];
 
             if (ctx->encrypt) {
                 if ((param->inp[9] << 8 | param->inp[10]) < TLS1_1_VERSION)
                     return -1;
 
                 if (inp_len) {
                     if (inp_len < 4096)
                         return 0; /* too short */
 
                     if (inp_len >= 8192 && OPENSSL_ia32cap_P[2] & (1 << 5))
                         n4x = 2; /* AVX2 */
                 } else if ((n4x = param->interleave / 4) && n4x <= 2)
                     inp_len = param->len;
                 else
                     return -1;
 
                 key->md = key->head;
                 SHA256_Update(&key->md, param->inp, 13);
 
                 x4 = 4 * n4x;
                 n4x += 1;
 
                 frag = inp_len >> n4x;
                 last = inp_len + frag - (frag << n4x);
                 if (last > frag && ((last + 13 + 9) % 64 < (x4 - 1))) {
                     frag++;
                     last -= x4 - 1;
                 }
 
                 packlen = 5 + 16 + ((frag + 32 + 16) & -16);
                 packlen = (packlen << n4x) - packlen;
                 packlen += 5 + 16 + ((last + 32 + 16) & -16);
 
                 param->interleave = x4;
 
                 return (int)packlen;
             } else
                 return -1;      /* not yet */
         }
     case EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT:
         {
             EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *param =
                 (EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *) ptr;
 
             return (int)tls1_1_multi_block_encrypt(key, param->out,
                                                    param->inp, param->len,
                                                    param->interleave / 4);
         }
     case EVP_CTRL_TLS1_1_MULTIBLOCK_DECRYPT:
 #  endif
     default:
         return -1;
     }
 }
 
 static EVP_CIPHER aesni_128_cbc_hmac_sha256_cipher = {
 #  ifdef NID_aes_128_cbc_hmac_sha256
     NID_aes_128_cbc_hmac_sha256,
 #  else
     NID_undef,
 #  endif
     16, 16, 16,
     EVP_CIPH_CBC_MODE | EVP_CIPH_FLAG_DEFAULT_ASN1 |
         EVP_CIPH_FLAG_AEAD_CIPHER | EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK,
     aesni_cbc_hmac_sha256_init_key,
     aesni_cbc_hmac_sha256_cipher,
     NULL,
     sizeof(EVP_AES_HMAC_SHA256),
     EVP_CIPH_FLAG_DEFAULT_ASN1 ? NULL : EVP_CIPHER_set_asn1_iv,
     EVP_CIPH_FLAG_DEFAULT_ASN1 ? NULL : EVP_CIPHER_get_asn1_iv,
     aesni_cbc_hmac_sha256_ctrl,
     NULL
 };
 
 static EVP_CIPHER aesni_256_cbc_hmac_sha256_cipher = {
 #  ifdef NID_aes_256_cbc_hmac_sha256
     NID_aes_256_cbc_hmac_sha256,
 #  else
     NID_undef,
 #  endif
     16, 32, 16,
     EVP_CIPH_CBC_MODE | EVP_CIPH_FLAG_DEFAULT_ASN1 |
         EVP_CIPH_FLAG_AEAD_CIPHER | EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK,
     aesni_cbc_hmac_sha256_init_key,
     aesni_cbc_hmac_sha256_cipher,
     NULL,
     sizeof(EVP_AES_HMAC_SHA256),
     EVP_CIPH_FLAG_DEFAULT_ASN1 ? NULL : EVP_CIPHER_set_asn1_iv,
     EVP_CIPH_FLAG_DEFAULT_ASN1 ? NULL : EVP_CIPHER_get_asn1_iv,
     aesni_cbc_hmac_sha256_ctrl,
     NULL
 };
 
 const EVP_CIPHER *EVP_aes_128_cbc_hmac_sha256(void)
 {
     return ((OPENSSL_ia32cap_P[1] & AESNI_CAPABLE) &&
             aesni_cbc_sha256_enc(NULL, NULL, 0, NULL, NULL, NULL, NULL) ?
             &aesni_128_cbc_hmac_sha256_cipher : NULL);
 }
 
 const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha256(void)
 {
     return ((OPENSSL_ia32cap_P[1] & AESNI_CAPABLE) &&
             aesni_cbc_sha256_enc(NULL, NULL, 0, NULL, NULL, NULL, NULL) ?
             &aesni_256_cbc_hmac_sha256_cipher : NULL);
 }
 # else
 const EVP_CIPHER *EVP_aes_128_cbc_hmac_sha256(void)
 {
     return NULL;
 }
 
 const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha256(void)
 {
     return NULL;
 }
 # endif
 #endif
Index: vendor-crypto/openssl/dist/crypto/evp/e_des3.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/evp/e_des3.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/evp/e_des3.c	(revision 318897)
@@ -1,495 +1,497 @@
 /* crypto/evp/e_des3.c */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 
 #include 
 #include "cryptlib.h"
 #ifndef OPENSSL_NO_DES
 # include 
 # include 
 # include "evp_locl.h"
 # include 
 # include 
 
 /* Block use of implementations in FIPS mode */
 # undef EVP_CIPH_FLAG_FIPS
 # define EVP_CIPH_FLAG_FIPS      0
 
 typedef struct {
     union {
         double align;
         DES_key_schedule ks[3];
     } ks;
     union {
         void (*cbc) (const void *, void *, size_t,
                      const DES_key_schedule *, unsigned char *);
     } stream;
 } DES_EDE_KEY;
 # define ks1 ks.ks[0]
 # define ks2 ks.ks[1]
 # define ks3 ks.ks[2]
 
 # if defined(AES_ASM) && (defined(__sparc) || defined(__sparc__))
 /* ---------^^^ this is not a typo, just a way to detect that
  * assembler support was in general requested... */
 #  include "sparc_arch.h"
 
 extern unsigned int OPENSSL_sparcv9cap_P[];
 
 #  define SPARC_DES_CAPABLE       (OPENSSL_sparcv9cap_P[1] & CFR_DES)
 
 void des_t4_key_expand(const void *key, DES_key_schedule *ks);
 void des_t4_ede3_cbc_encrypt(const void *inp, void *out, size_t len,
                              const DES_key_schedule ks[3], unsigned char iv[8]);
 void des_t4_ede3_cbc_decrypt(const void *inp, void *out, size_t len,
                              const DES_key_schedule ks[3], unsigned char iv[8]);
 # endif
 
 static int des_ede_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
                             const unsigned char *iv, int enc);
 
 static int des_ede3_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
                              const unsigned char *iv, int enc);
 
 static int des3_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr);
 
 # define data(ctx) ((DES_EDE_KEY *)(ctx)->cipher_data)
 
 /*
  * Because of various casts and different args can't use
  * IMPLEMENT_BLOCK_CIPHER
  */
 
 static int des_ede_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                               const unsigned char *in, size_t inl)
 {
     BLOCK_CIPHER_ecb_loop()
         DES_ecb3_encrypt((const_DES_cblock *)(in + i),
                          (DES_cblock *)(out + i),
                          &data(ctx)->ks1, &data(ctx)->ks2,
                          &data(ctx)->ks3, ctx->encrypt);
     return 1;
 }
 
 static int des_ede_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                               const unsigned char *in, size_t inl)
 {
     while (inl >= EVP_MAXCHUNK) {
         DES_ede3_ofb64_encrypt(in, out, (long)EVP_MAXCHUNK,
                                &data(ctx)->ks1, &data(ctx)->ks2,
                                &data(ctx)->ks3, (DES_cblock *)ctx->iv,
                                &ctx->num);
         inl -= EVP_MAXCHUNK;
         in += EVP_MAXCHUNK;
         out += EVP_MAXCHUNK;
     }
     if (inl)
         DES_ede3_ofb64_encrypt(in, out, (long)inl,
                                &data(ctx)->ks1, &data(ctx)->ks2,
                                &data(ctx)->ks3, (DES_cblock *)ctx->iv,
                                &ctx->num);
 
     return 1;
 }
 
 static int des_ede_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                               const unsigned char *in, size_t inl)
 {
     DES_EDE_KEY *dat = data(ctx);
 
 # ifdef KSSL_DEBUG
     {
         int i;
         fprintf(stderr, "des_ede_cbc_cipher(ctx=%p, buflen=%d)\n", ctx,
                 ctx->buf_len);
         fprintf(stderr, "\t iv= ");
         for (i = 0; i < 8; i++)
             fprintf(stderr, "%02X", ctx->iv[i]);
         fprintf(stderr, "\n");
     }
 # endif                         /* KSSL_DEBUG */
     if (dat->stream.cbc) {
         (*dat->stream.cbc) (in, out, inl, dat->ks.ks, ctx->iv);
         return 1;
     }
 
     while (inl >= EVP_MAXCHUNK) {
         DES_ede3_cbc_encrypt(in, out, (long)EVP_MAXCHUNK,
                              &dat->ks1, &dat->ks2, &dat->ks3,
                              (DES_cblock *)ctx->iv, ctx->encrypt);
         inl -= EVP_MAXCHUNK;
         in += EVP_MAXCHUNK;
         out += EVP_MAXCHUNK;
     }
     if (inl)
         DES_ede3_cbc_encrypt(in, out, (long)inl,
                              &dat->ks1, &dat->ks2, &dat->ks3,
                              (DES_cblock *)ctx->iv, ctx->encrypt);
     return 1;
 }
 
 static int des_ede_cfb64_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                                 const unsigned char *in, size_t inl)
 {
     while (inl >= EVP_MAXCHUNK) {
         DES_ede3_cfb64_encrypt(in, out, (long)EVP_MAXCHUNK,
                                &data(ctx)->ks1, &data(ctx)->ks2,
                                &data(ctx)->ks3, (DES_cblock *)ctx->iv,
                                &ctx->num, ctx->encrypt);
         inl -= EVP_MAXCHUNK;
         in += EVP_MAXCHUNK;
         out += EVP_MAXCHUNK;
     }
     if (inl)
         DES_ede3_cfb64_encrypt(in, out, (long)inl,
                                &data(ctx)->ks1, &data(ctx)->ks2,
                                &data(ctx)->ks3, (DES_cblock *)ctx->iv,
                                &ctx->num, ctx->encrypt);
     return 1;
 }
 
 /*
  * Although we have a CFB-r implementation for 3-DES, it doesn't pack the
  * right way, so wrap it here
  */
 static int des_ede3_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                                 const unsigned char *in, size_t inl)
 {
     size_t n;
     unsigned char c[1], d[1];
 
+    if (!EVP_CIPHER_CTX_test_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS))
+            inl *= 8;
     for (n = 0; n < inl; ++n) {
         c[0] = (in[n / 8] & (1 << (7 - n % 8))) ? 0x80 : 0;
         DES_ede3_cfb_encrypt(c, d, 1, 1,
                              &data(ctx)->ks1, &data(ctx)->ks2,
                              &data(ctx)->ks3, (DES_cblock *)ctx->iv,
                              ctx->encrypt);
         out[n / 8] = (out[n / 8] & ~(0x80 >> (unsigned int)(n % 8)))
             | ((d[0] & 0x80) >> (unsigned int)(n % 8));
     }
 
     return 1;
 }
 
 static int des_ede3_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                                 const unsigned char *in, size_t inl)
 {
     while (inl >= EVP_MAXCHUNK) {
         DES_ede3_cfb_encrypt(in, out, 8, (long)EVP_MAXCHUNK,
                              &data(ctx)->ks1, &data(ctx)->ks2,
                              &data(ctx)->ks3, (DES_cblock *)ctx->iv,
                              ctx->encrypt);
         inl -= EVP_MAXCHUNK;
         in += EVP_MAXCHUNK;
         out += EVP_MAXCHUNK;
     }
     if (inl)
         DES_ede3_cfb_encrypt(in, out, 8, (long)inl,
                              &data(ctx)->ks1, &data(ctx)->ks2,
                              &data(ctx)->ks3, (DES_cblock *)ctx->iv,
                              ctx->encrypt);
     return 1;
 }
 
 BLOCK_CIPHER_defs(des_ede, DES_EDE_KEY, NID_des_ede, 8, 16, 8, 64,
                   EVP_CIPH_RAND_KEY | EVP_CIPH_FLAG_DEFAULT_ASN1,
                   des_ede_init_key, NULL, NULL, NULL, des3_ctrl)
 # define des_ede3_cfb64_cipher des_ede_cfb64_cipher
 # define des_ede3_ofb_cipher des_ede_ofb_cipher
 # define des_ede3_cbc_cipher des_ede_cbc_cipher
 # define des_ede3_ecb_cipher des_ede_ecb_cipher
     BLOCK_CIPHER_defs(des_ede3, DES_EDE_KEY, NID_des_ede3, 8, 24, 8, 64,
                   EVP_CIPH_RAND_KEY | EVP_CIPH_FLAG_FIPS |
                   EVP_CIPH_FLAG_DEFAULT_ASN1, des_ede3_init_key, NULL, NULL, NULL,
                   des3_ctrl)
 
     BLOCK_CIPHER_def_cfb(des_ede3, DES_EDE_KEY, NID_des_ede3, 24, 8, 1,
                      EVP_CIPH_RAND_KEY | EVP_CIPH_FLAG_FIPS |
                      EVP_CIPH_FLAG_DEFAULT_ASN1, des_ede3_init_key, NULL, NULL,
                      NULL, des3_ctrl)
 
     BLOCK_CIPHER_def_cfb(des_ede3, DES_EDE_KEY, NID_des_ede3, 24, 8, 8,
                      EVP_CIPH_RAND_KEY | EVP_CIPH_FLAG_FIPS |
                      EVP_CIPH_FLAG_DEFAULT_ASN1, des_ede3_init_key, NULL, NULL,
                      NULL, des3_ctrl)
 
 static int des_ede_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
                             const unsigned char *iv, int enc)
 {
     DES_cblock *deskey = (DES_cblock *)key;
     DES_EDE_KEY *dat = data(ctx);
 
     dat->stream.cbc = NULL;
 # if defined(SPARC_DES_CAPABLE)
     if (SPARC_DES_CAPABLE) {
         int mode = ctx->cipher->flags & EVP_CIPH_MODE;
 
         if (mode == EVP_CIPH_CBC_MODE) {
             des_t4_key_expand(&deskey[0], &dat->ks1);
             des_t4_key_expand(&deskey[1], &dat->ks2);
             memcpy(&dat->ks3, &dat->ks1, sizeof(dat->ks1));
             dat->stream.cbc = enc ? des_t4_ede3_cbc_encrypt :
                 des_t4_ede3_cbc_decrypt;
             return 1;
         }
     }
 # endif
 # ifdef EVP_CHECK_DES_KEY
     if (DES_set_key_checked(&deskey[0], &dat->ks1)
         || DES_set_key_checked(&deskey[1], &dat->ks2))
         return 0;
 # else
     DES_set_key_unchecked(&deskey[0], &dat->ks1);
     DES_set_key_unchecked(&deskey[1], &dat->ks2);
 # endif
     memcpy(&dat->ks3, &dat->ks1, sizeof(dat->ks1));
     return 1;
 }
 
 static int des_ede3_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key,
                              const unsigned char *iv, int enc)
 {
     DES_cblock *deskey = (DES_cblock *)key;
     DES_EDE_KEY *dat = data(ctx);
 
 # ifdef KSSL_DEBUG
     {
         int i;
         fprintf(stderr, "des_ede3_init_key(ctx=%p)\n", ctx);
         fprintf(stderr, "\tKEY= ");
         for (i = 0; i < 24; i++)
             fprintf(stderr, "%02X", key[i]);
         fprintf(stderr, "\n");
         if (iv) {
             fprintf(stderr, "\t IV= ");
             for (i = 0; i < 8; i++)
                 fprintf(stderr, "%02X", iv[i]);
             fprintf(stderr, "\n");
         }
     }
 # endif                         /* KSSL_DEBUG */
 
     dat->stream.cbc = NULL;
 # if defined(SPARC_DES_CAPABLE)
     if (SPARC_DES_CAPABLE) {
         int mode = ctx->cipher->flags & EVP_CIPH_MODE;
 
         if (mode == EVP_CIPH_CBC_MODE) {
             des_t4_key_expand(&deskey[0], &dat->ks1);
             des_t4_key_expand(&deskey[1], &dat->ks2);
             des_t4_key_expand(&deskey[2], &dat->ks3);
             dat->stream.cbc = enc ? des_t4_ede3_cbc_encrypt :
                 des_t4_ede3_cbc_decrypt;
             return 1;
         }
     }
 # endif
 # ifdef EVP_CHECK_DES_KEY
     if (DES_set_key_checked(&deskey[0], &dat->ks1)
         || DES_set_key_checked(&deskey[1], &dat->ks2)
         || DES_set_key_checked(&deskey[2], &dat->ks3))
         return 0;
 # else
     DES_set_key_unchecked(&deskey[0], &dat->ks1);
     DES_set_key_unchecked(&deskey[1], &dat->ks2);
     DES_set_key_unchecked(&deskey[2], &dat->ks3);
 # endif
     return 1;
 }
 
 static int des3_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)
 {
 
     DES_cblock *deskey = ptr;
 
     switch (type) {
     case EVP_CTRL_RAND_KEY:
         if (RAND_bytes(ptr, c->key_len) <= 0)
             return 0;
         DES_set_odd_parity(deskey);
         if (c->key_len >= 16)
             DES_set_odd_parity(deskey + 1);
         if (c->key_len >= 24)
             DES_set_odd_parity(deskey + 2);
         return 1;
 
     default:
         return -1;
     }
 }
 
 const EVP_CIPHER *EVP_des_ede(void)
 {
     return &des_ede_ecb;
 }
 
 const EVP_CIPHER *EVP_des_ede3(void)
 {
     return &des_ede3_ecb;
 }
 
 # ifndef OPENSSL_NO_SHA
 
 #  include 
 
 static const unsigned char wrap_iv[8] =
     { 0x4a, 0xdd, 0xa2, 0x2c, 0x79, 0xe8, 0x21, 0x05 };
 
 static int des_ede3_unwrap(EVP_CIPHER_CTX *ctx, unsigned char *out,
                            const unsigned char *in, size_t inl)
 {
     unsigned char icv[8], iv[8], sha1tmp[SHA_DIGEST_LENGTH];
     int rv = -1;
     if (inl < 24)
         return -1;
     if (out == NULL)
         return inl - 16;
     memcpy(ctx->iv, wrap_iv, 8);
     /* Decrypt first block which will end up as icv */
     des_ede_cbc_cipher(ctx, icv, in, 8);
     /* Decrypt central blocks */
     /*
      * If decrypting in place move whole output along a block so the next
      * des_ede_cbc_cipher is in place.
      */
     if (out == in) {
         memmove(out, out + 8, inl - 8);
         in -= 8;
     }
     des_ede_cbc_cipher(ctx, out, in + 8, inl - 16);
     /* Decrypt final block which will be IV */
     des_ede_cbc_cipher(ctx, iv, in + inl - 8, 8);
     /* Reverse order of everything */
     BUF_reverse(icv, NULL, 8);
     BUF_reverse(out, NULL, inl - 16);
     BUF_reverse(ctx->iv, iv, 8);
     /* Decrypt again using new IV */
     des_ede_cbc_cipher(ctx, out, out, inl - 16);
     des_ede_cbc_cipher(ctx, icv, icv, 8);
     /* Work out SHA1 hash of first portion */
     SHA1(out, inl - 16, sha1tmp);
 
     if (!CRYPTO_memcmp(sha1tmp, icv, 8))
         rv = inl - 16;
     OPENSSL_cleanse(icv, 8);
     OPENSSL_cleanse(sha1tmp, SHA_DIGEST_LENGTH);
     OPENSSL_cleanse(iv, 8);
     OPENSSL_cleanse(ctx->iv, 8);
     if (rv == -1)
         OPENSSL_cleanse(out, inl - 16);
 
     return rv;
 }
 
 static int des_ede3_wrap(EVP_CIPHER_CTX *ctx, unsigned char *out,
                          const unsigned char *in, size_t inl)
 {
     unsigned char sha1tmp[SHA_DIGEST_LENGTH];
     if (out == NULL)
         return inl + 16;
     /* Copy input to output buffer + 8 so we have space for IV */
     memmove(out + 8, in, inl);
     /* Work out ICV */
     SHA1(in, inl, sha1tmp);
     memcpy(out + inl + 8, sha1tmp, 8);
     OPENSSL_cleanse(sha1tmp, SHA_DIGEST_LENGTH);
     /* Generate random IV */
     if (RAND_bytes(ctx->iv, 8) <= 0)
         return -1;
     memcpy(out, ctx->iv, 8);
     /* Encrypt everything after IV in place */
     des_ede_cbc_cipher(ctx, out + 8, out + 8, inl + 8);
     BUF_reverse(out, NULL, inl + 16);
     memcpy(ctx->iv, wrap_iv, 8);
     des_ede_cbc_cipher(ctx, out, out, inl + 16);
     return inl + 16;
 }
 
 static int des_ede3_wrap_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out,
                                 const unsigned char *in, size_t inl)
 {
     /*
      * Sanity check input length: we typically only wrap keys so EVP_MAXCHUNK
      * is more than will ever be needed. Also input length must be a multiple
      * of 8 bits.
      */
     if (inl >= EVP_MAXCHUNK || inl % 8)
         return -1;
     if (ctx->encrypt)
         return des_ede3_wrap(ctx, out, in, inl);
     else
         return des_ede3_unwrap(ctx, out, in, inl);
 }
 
 static const EVP_CIPHER des3_wrap = {
     NID_id_smime_alg_CMS3DESwrap,
     8, 24, 0,
     EVP_CIPH_WRAP_MODE | EVP_CIPH_CUSTOM_IV | EVP_CIPH_FLAG_CUSTOM_CIPHER
         | EVP_CIPH_FLAG_DEFAULT_ASN1,
     des_ede3_init_key, des_ede3_wrap_cipher,
     NULL,
     sizeof(DES_EDE_KEY),
     NULL, NULL, NULL, NULL
 };
 
 const EVP_CIPHER *EVP_des_ede3_wrap(void)
 {
     return &des3_wrap;
 }
 
 # endif
 #endif
Index: vendor-crypto/openssl/dist/crypto/evp/evp_enc.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/evp/evp_enc.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/evp/evp_enc.c	(revision 318897)
@@ -1,666 +1,673 @@
 /* crypto/evp/evp_enc.c */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 
 #include 
 #include "cryptlib.h"
 #include 
 #include 
 #include 
 #ifndef OPENSSL_NO_ENGINE
 # include 
 #endif
 #ifdef OPENSSL_FIPS
 # include 
 #endif
 #include "evp_locl.h"
 
 #ifdef OPENSSL_FIPS
 # define M_do_cipher(ctx, out, in, inl) FIPS_cipher(ctx, out, in, inl)
 #else
 # define M_do_cipher(ctx, out, in, inl) ctx->cipher->do_cipher(ctx, out, in, inl)
 #endif
 
 const char EVP_version[] = "EVP" OPENSSL_VERSION_PTEXT;
 
 void EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *ctx)
 {
     memset(ctx, 0, sizeof(EVP_CIPHER_CTX));
     /* ctx->cipher=NULL; */
 }
 
 EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void)
 {
     EVP_CIPHER_CTX *ctx = OPENSSL_malloc(sizeof *ctx);
     if (ctx)
         EVP_CIPHER_CTX_init(ctx);
     return ctx;
 }
 
 int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
                    const unsigned char *key, const unsigned char *iv, int enc)
 {
     if (cipher)
         EVP_CIPHER_CTX_init(ctx);
     return EVP_CipherInit_ex(ctx, cipher, NULL, key, iv, enc);
 }
 
 int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
                       ENGINE *impl, const unsigned char *key,
                       const unsigned char *iv, int enc)
 {
     if (enc == -1)
         enc = ctx->encrypt;
     else {
         if (enc)
             enc = 1;
         ctx->encrypt = enc;
     }
 #ifndef OPENSSL_NO_ENGINE
     /*
      * Whether it's nice or not, "Inits" can be used on "Final"'d contexts so
      * this context may already have an ENGINE! Try to avoid releasing the
      * previous handle, re-querying for an ENGINE, and having a
      * reinitialisation, when it may all be unecessary.
      */
     if (ctx->engine && ctx->cipher && (!cipher ||
                                        (cipher
                                         && (cipher->nid ==
                                             ctx->cipher->nid))))
         goto skip_to_init;
 #endif
     if (cipher) {
         /*
          * Ensure a context left lying around from last time is cleared (the
          * previous check attempted to avoid this if the same ENGINE and
          * EVP_CIPHER could be used).
          */
         if (ctx->cipher) {
             unsigned long flags = ctx->flags;
             EVP_CIPHER_CTX_cleanup(ctx);
             /* Restore encrypt and flags */
             ctx->encrypt = enc;
             ctx->flags = flags;
         }
 #ifndef OPENSSL_NO_ENGINE
         if (impl) {
             if (!ENGINE_init(impl)) {
                 EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
                 return 0;
             }
         } else
             /* Ask if an ENGINE is reserved for this job */
             impl = ENGINE_get_cipher_engine(cipher->nid);
         if (impl) {
             /* There's an ENGINE for this job ... (apparently) */
             const EVP_CIPHER *c = ENGINE_get_cipher(impl, cipher->nid);
             if (!c) {
                 /*
                  * One positive side-effect of US's export control history,
                  * is that we should at least be able to avoid using US
                  * mispellings of "initialisation"?
                  */
                 EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
                 return 0;
             }
             /* We'll use the ENGINE's private cipher definition */
             cipher = c;
             /*
              * Store the ENGINE functional reference so we know 'cipher' came
              * from an ENGINE and we need to release it when done.
              */
             ctx->engine = impl;
         } else
             ctx->engine = NULL;
 #endif
 
 #ifdef OPENSSL_FIPS
         if (FIPS_mode()) {
             const EVP_CIPHER *fcipher = NULL;
             if (cipher)
                 fcipher = evp_get_fips_cipher(cipher);
             if (fcipher)
                 cipher = fcipher;
             return FIPS_cipherinit(ctx, cipher, key, iv, enc);
         }
 #endif
         ctx->cipher = cipher;
         if (ctx->cipher->ctx_size) {
             ctx->cipher_data = OPENSSL_malloc(ctx->cipher->ctx_size);
             if (!ctx->cipher_data) {
+                ctx->cipher = NULL;
                 EVPerr(EVP_F_EVP_CIPHERINIT_EX, ERR_R_MALLOC_FAILURE);
                 return 0;
             }
         } else {
             ctx->cipher_data = NULL;
         }
         ctx->key_len = cipher->key_len;
         /* Preserve wrap enable flag, zero everything else */
         ctx->flags &= EVP_CIPHER_CTX_FLAG_WRAP_ALLOW;
         if (ctx->cipher->flags & EVP_CIPH_CTRL_INIT) {
             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, NULL)) {
+                ctx->cipher = NULL;
                 EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
                 return 0;
             }
         }
     } else if (!ctx->cipher) {
         EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_NO_CIPHER_SET);
         return 0;
     }
 #ifndef OPENSSL_NO_ENGINE
  skip_to_init:
 #endif
 #ifdef OPENSSL_FIPS
     if (FIPS_mode())
         return FIPS_cipherinit(ctx, cipher, key, iv, enc);
 #endif
     /* we assume block size is a power of 2 in *cryptUpdate */
     OPENSSL_assert(ctx->cipher->block_size == 1
                    || ctx->cipher->block_size == 8
                    || ctx->cipher->block_size == 16);
 
     if (!(ctx->flags & EVP_CIPHER_CTX_FLAG_WRAP_ALLOW)
         && EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_WRAP_MODE) {
         EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_WRAP_MODE_NOT_ALLOWED);
         return 0;
     }
 
     if (!(EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_CUSTOM_IV)) {
         switch (EVP_CIPHER_CTX_mode(ctx)) {
 
         case EVP_CIPH_STREAM_CIPHER:
         case EVP_CIPH_ECB_MODE:
             break;
 
         case EVP_CIPH_CFB_MODE:
         case EVP_CIPH_OFB_MODE:
 
             ctx->num = 0;
             /* fall-through */
 
         case EVP_CIPH_CBC_MODE:
 
             OPENSSL_assert(EVP_CIPHER_CTX_iv_length(ctx) <=
                            (int)sizeof(ctx->iv));
             if (iv)
                 memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx));
             memcpy(ctx->iv, ctx->oiv, EVP_CIPHER_CTX_iv_length(ctx));
             break;
 
         case EVP_CIPH_CTR_MODE:
             ctx->num = 0;
             /* Don't reuse IV for CTR mode */
             if (iv)
                 memcpy(ctx->iv, iv, EVP_CIPHER_CTX_iv_length(ctx));
             break;
 
         default:
             return 0;
             break;
         }
     }
 
     if (key || (ctx->cipher->flags & EVP_CIPH_ALWAYS_CALL_INIT)) {
         if (!ctx->cipher->init(ctx, key, iv, enc))
             return 0;
     }
     ctx->buf_len = 0;
     ctx->final_used = 0;
     ctx->block_mask = ctx->cipher->block_size - 1;
     return 1;
 }
 
 int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
                      const unsigned char *in, int inl)
 {
     if (ctx->encrypt)
         return EVP_EncryptUpdate(ctx, out, outl, in, inl);
     else
         return EVP_DecryptUpdate(ctx, out, outl, in, inl);
 }
 
 int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
 {
     if (ctx->encrypt)
         return EVP_EncryptFinal_ex(ctx, out, outl);
     else
         return EVP_DecryptFinal_ex(ctx, out, outl);
 }
 
 int EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
 {
     if (ctx->encrypt)
         return EVP_EncryptFinal(ctx, out, outl);
     else
         return EVP_DecryptFinal(ctx, out, outl);
 }
 
 int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
                     const unsigned char *key, const unsigned char *iv)
 {
     return EVP_CipherInit(ctx, cipher, key, iv, 1);
 }
 
 int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
                        ENGINE *impl, const unsigned char *key,
                        const unsigned char *iv)
 {
     return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 1);
 }
 
 int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
                     const unsigned char *key, const unsigned char *iv)
 {
     return EVP_CipherInit(ctx, cipher, key, iv, 0);
 }
 
 int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
                        ENGINE *impl, const unsigned char *key,
                        const unsigned char *iv)
 {
     return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 0);
 }
 
 int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
                       const unsigned char *in, int inl)
 {
     int i, j, bl;
 
     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
         i = M_do_cipher(ctx, out, in, inl);
         if (i < 0)
             return 0;
         else
             *outl = i;
         return 1;
     }
 
     if (inl <= 0) {
         *outl = 0;
         return inl == 0;
     }
 
     if (ctx->buf_len == 0 && (inl & (ctx->block_mask)) == 0) {
         if (M_do_cipher(ctx, out, in, inl)) {
             *outl = inl;
             return 1;
         } else {
             *outl = 0;
             return 0;
         }
     }
     i = ctx->buf_len;
     bl = ctx->cipher->block_size;
     OPENSSL_assert(bl <= (int)sizeof(ctx->buf));
     if (i != 0) {
         if (bl - i > inl) {
             memcpy(&(ctx->buf[i]), in, inl);
             ctx->buf_len += inl;
             *outl = 0;
             return 1;
         } else {
             j = bl - i;
             memcpy(&(ctx->buf[i]), in, j);
             if (!M_do_cipher(ctx, out, ctx->buf, bl))
                 return 0;
             inl -= j;
             in += j;
             out += bl;
             *outl = bl;
         }
     } else
         *outl = 0;
     i = inl & (bl - 1);
     inl -= i;
     if (inl > 0) {
         if (!M_do_cipher(ctx, out, in, inl))
             return 0;
         *outl += inl;
     }
 
     if (i != 0)
         memcpy(ctx->buf, &(in[inl]), i);
     ctx->buf_len = i;
     return 1;
 }
 
 int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
 {
     int ret;
     ret = EVP_EncryptFinal_ex(ctx, out, outl);
     return ret;
 }
 
 int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
 {
     int n, ret;
     unsigned int i, b, bl;
 
     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
         ret = M_do_cipher(ctx, out, NULL, 0);
         if (ret < 0)
             return 0;
         else
             *outl = ret;
         return 1;
     }
 
     b = ctx->cipher->block_size;
     OPENSSL_assert(b <= sizeof ctx->buf);
     if (b == 1) {
         *outl = 0;
         return 1;
     }
     bl = ctx->buf_len;
     if (ctx->flags & EVP_CIPH_NO_PADDING) {
         if (bl) {
             EVPerr(EVP_F_EVP_ENCRYPTFINAL_EX,
                    EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
             return 0;
         }
         *outl = 0;
         return 1;
     }
 
     n = b - bl;
     for (i = bl; i < b; i++)
         ctx->buf[i] = n;
     ret = M_do_cipher(ctx, out, ctx->buf, b);
 
     if (ret)
         *outl = b;
 
     return ret;
 }
 
 int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
                       const unsigned char *in, int inl)
 {
     int fix_len;
     unsigned int b;
 
     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
         fix_len = M_do_cipher(ctx, out, in, inl);
         if (fix_len < 0) {
             *outl = 0;
             return 0;
         } else
             *outl = fix_len;
         return 1;
     }
 
     if (inl <= 0) {
         *outl = 0;
         return inl == 0;
     }
 
     if (ctx->flags & EVP_CIPH_NO_PADDING)
         return EVP_EncryptUpdate(ctx, out, outl, in, inl);
 
     b = ctx->cipher->block_size;
     OPENSSL_assert(b <= sizeof ctx->final);
 
     if (ctx->final_used) {
         memcpy(out, ctx->final, b);
         out += b;
         fix_len = 1;
     } else
         fix_len = 0;
 
     if (!EVP_EncryptUpdate(ctx, out, outl, in, inl))
         return 0;
 
     /*
      * if we have 'decrypted' a multiple of block size, make sure we have a
      * copy of this last block
      */
     if (b > 1 && !ctx->buf_len) {
         *outl -= b;
         ctx->final_used = 1;
         memcpy(ctx->final, &out[*outl], b);
     } else
         ctx->final_used = 0;
 
     if (fix_len)
         *outl += b;
 
     return 1;
 }
 
 int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
 {
     int ret;
     ret = EVP_DecryptFinal_ex(ctx, out, outl);
     return ret;
 }
 
 int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
 {
     int i, n;
     unsigned int b;
     *outl = 0;
 
     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
         i = M_do_cipher(ctx, out, NULL, 0);
         if (i < 0)
             return 0;
         else
             *outl = i;
         return 1;
     }
 
     b = ctx->cipher->block_size;
     if (ctx->flags & EVP_CIPH_NO_PADDING) {
         if (ctx->buf_len) {
             EVPerr(EVP_F_EVP_DECRYPTFINAL_EX,
                    EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
             return 0;
         }
         *outl = 0;
         return 1;
     }
     if (b > 1) {
         if (ctx->buf_len || !ctx->final_used) {
             EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_WRONG_FINAL_BLOCK_LENGTH);
             return (0);
         }
         OPENSSL_assert(b <= sizeof ctx->final);
 
         /*
          * The following assumes that the ciphertext has been authenticated.
          * Otherwise it provides a padding oracle.
          */
         n = ctx->final[b - 1];
         if (n == 0 || n > (int)b) {
             EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_BAD_DECRYPT);
             return (0);
         }
         for (i = 0; i < n; i++) {
             if (ctx->final[--b] != n) {
                 EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_BAD_DECRYPT);
                 return (0);
             }
         }
         n = ctx->cipher->block_size - n;
         for (i = 0; i < n; i++)
             out[i] = ctx->final[i];
         *outl = n;
     } else
         *outl = 0;
     return (1);
 }
 
 void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx)
 {
     if (ctx) {
         EVP_CIPHER_CTX_cleanup(ctx);
         OPENSSL_free(ctx);
     }
 }
 
 int EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *c)
 {
 #ifndef OPENSSL_FIPS
     if (c->cipher != NULL) {
         if (c->cipher->cleanup && !c->cipher->cleanup(c))
             return 0;
         /* Cleanse cipher context data */
         if (c->cipher_data)
             OPENSSL_cleanse(c->cipher_data, c->cipher->ctx_size);
     }
     if (c->cipher_data)
         OPENSSL_free(c->cipher_data);
 #endif
 #ifndef OPENSSL_NO_ENGINE
     if (c->engine)
         /*
          * The EVP_CIPHER we used belongs to an ENGINE, release the
          * functional reference we held for this reason.
          */
         ENGINE_finish(c->engine);
 #endif
 #ifdef OPENSSL_FIPS
     FIPS_cipher_ctx_cleanup(c);
 #endif
     memset(c, 0, sizeof(EVP_CIPHER_CTX));
     return 1;
 }
 
 int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *c, int keylen)
 {
     if (c->cipher->flags & EVP_CIPH_CUSTOM_KEY_LENGTH)
         return EVP_CIPHER_CTX_ctrl(c, EVP_CTRL_SET_KEY_LENGTH, keylen, NULL);
     if (c->key_len == keylen)
         return 1;
     if ((keylen > 0) && (c->cipher->flags & EVP_CIPH_VARIABLE_LENGTH)) {
         c->key_len = keylen;
         return 1;
     }
     EVPerr(EVP_F_EVP_CIPHER_CTX_SET_KEY_LENGTH, EVP_R_INVALID_KEY_LENGTH);
     return 0;
 }
 
 int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *ctx, int pad)
 {
     if (pad)
         ctx->flags &= ~EVP_CIPH_NO_PADDING;
     else
         ctx->flags |= EVP_CIPH_NO_PADDING;
     return 1;
 }
 
 int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
 {
     int ret;
     if (!ctx->cipher) {
         EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_NO_CIPHER_SET);
         return 0;
     }
 
     if (!ctx->cipher->ctrl) {
         EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_CTRL_NOT_IMPLEMENTED);
         return 0;
     }
 
     ret = ctx->cipher->ctrl(ctx, type, arg, ptr);
     if (ret == -1) {
         EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL,
                EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED);
         return 0;
     }
     return ret;
 }
 
 int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key)
 {
     if (ctx->cipher->flags & EVP_CIPH_RAND_KEY)
         return EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_RAND_KEY, 0, key);
     if (RAND_bytes(key, ctx->key_len) <= 0)
         return 0;
     return 1;
 }
 
 int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in)
 {
     if ((in == NULL) || (in->cipher == NULL)) {
         EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_INPUT_NOT_INITIALIZED);
         return 0;
     }
 #ifndef OPENSSL_NO_ENGINE
     /* Make sure it's safe to copy a cipher context using an ENGINE */
     if (in->engine && !ENGINE_init(in->engine)) {
         EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, ERR_R_ENGINE_LIB);
         return 0;
     }
 #endif
 
     EVP_CIPHER_CTX_cleanup(out);
     memcpy(out, in, sizeof *out);
 
     if (in->cipher_data && in->cipher->ctx_size) {
         out->cipher_data = OPENSSL_malloc(in->cipher->ctx_size);
         if (!out->cipher_data) {
+            out->cipher = NULL;
             EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, ERR_R_MALLOC_FAILURE);
             return 0;
         }
         memcpy(out->cipher_data, in->cipher_data, in->cipher->ctx_size);
     }
 
     if (in->cipher->flags & EVP_CIPH_CUSTOM_COPY)
-        return in->cipher->ctrl((EVP_CIPHER_CTX *)in, EVP_CTRL_COPY, 0, out);
+        if (!in->cipher->ctrl((EVP_CIPHER_CTX *)in, EVP_CTRL_COPY, 0, out)) {
+            out->cipher = NULL;
+            EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_INITIALIZATION_ERROR);
+            return 0;
+        }
     return 1;
 }
Index: vendor-crypto/openssl/dist/crypto/evp/pmeth_lib.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/evp/pmeth_lib.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/evp/pmeth_lib.c	(revision 318897)
@@ -1,589 +1,591 @@
 /* pmeth_lib.c */
 /*
  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
  * 2006.
  */
 /* ====================================================================
  * Copyright (c) 2006 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    licensing@OpenSSL.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #include 
 #include 
 #include "cryptlib.h"
 #include 
 #include 
 #ifndef OPENSSL_NO_ENGINE
 # include 
 #endif
 #include "asn1_locl.h"
 #include "evp_locl.h"
 
 typedef int sk_cmp_fn_type(const char *const *a, const char *const *b);
 
 DECLARE_STACK_OF(EVP_PKEY_METHOD)
 STACK_OF(EVP_PKEY_METHOD) *app_pkey_methods = NULL;
 
 extern const EVP_PKEY_METHOD rsa_pkey_meth, dh_pkey_meth, dsa_pkey_meth;
 extern const EVP_PKEY_METHOD ec_pkey_meth, hmac_pkey_meth, cmac_pkey_meth;
 extern const EVP_PKEY_METHOD dhx_pkey_meth;
 
 static const EVP_PKEY_METHOD *standard_methods[] = {
 #ifndef OPENSSL_NO_RSA
     &rsa_pkey_meth,
 #endif
 #ifndef OPENSSL_NO_DH
     &dh_pkey_meth,
 #endif
 #ifndef OPENSSL_NO_DSA
     &dsa_pkey_meth,
 #endif
 #ifndef OPENSSL_NO_EC
     &ec_pkey_meth,
 #endif
     &hmac_pkey_meth,
 #ifndef OPENSSL_NO_CMAC
     &cmac_pkey_meth,
 #endif
 #ifndef OPENSSL_NO_DH
     &dhx_pkey_meth
 #endif
 };
 
 DECLARE_OBJ_BSEARCH_CMP_FN(const EVP_PKEY_METHOD *, const EVP_PKEY_METHOD *,
                            pmeth);
 
 static int pmeth_cmp(const EVP_PKEY_METHOD *const *a,
                      const EVP_PKEY_METHOD *const *b)
 {
     return ((*a)->pkey_id - (*b)->pkey_id);
 }
 
 IMPLEMENT_OBJ_BSEARCH_CMP_FN(const EVP_PKEY_METHOD *, const EVP_PKEY_METHOD *,
                              pmeth);
 
 const EVP_PKEY_METHOD *EVP_PKEY_meth_find(int type)
 {
     EVP_PKEY_METHOD tmp;
     const EVP_PKEY_METHOD *t = &tmp, **ret;
     tmp.pkey_id = type;
     if (app_pkey_methods) {
         int idx;
         idx = sk_EVP_PKEY_METHOD_find(app_pkey_methods, &tmp);
         if (idx >= 0)
             return sk_EVP_PKEY_METHOD_value(app_pkey_methods, idx);
     }
     ret = OBJ_bsearch_pmeth(&t, standard_methods,
                             sizeof(standard_methods) /
                             sizeof(EVP_PKEY_METHOD *));
     if (!ret || !*ret)
         return NULL;
     return *ret;
 }
 
 static EVP_PKEY_CTX *int_ctx_new(EVP_PKEY *pkey, ENGINE *e, int id)
 {
     EVP_PKEY_CTX *ret;
     const EVP_PKEY_METHOD *pmeth;
     if (id == -1) {
         if (!pkey || !pkey->ameth)
             return NULL;
         id = pkey->ameth->pkey_id;
     }
 #ifndef OPENSSL_NO_ENGINE
     if (pkey && pkey->engine)
         e = pkey->engine;
     /* Try to find an ENGINE which implements this method */
     if (e) {
         if (!ENGINE_init(e)) {
             EVPerr(EVP_F_INT_CTX_NEW, ERR_R_ENGINE_LIB);
             return NULL;
         }
     } else
         e = ENGINE_get_pkey_meth_engine(id);
 
     /*
      * If an ENGINE handled this method look it up. Othewise use internal
      * tables.
      */
 
     if (e)
         pmeth = ENGINE_get_pkey_meth(e, id);
     else
 #endif
         pmeth = EVP_PKEY_meth_find(id);
 
     if (pmeth == NULL) {
         EVPerr(EVP_F_INT_CTX_NEW, EVP_R_UNSUPPORTED_ALGORITHM);
         return NULL;
     }
 
     ret = OPENSSL_malloc(sizeof(EVP_PKEY_CTX));
     if (!ret) {
 #ifndef OPENSSL_NO_ENGINE
         if (e)
             ENGINE_finish(e);
 #endif
         EVPerr(EVP_F_INT_CTX_NEW, ERR_R_MALLOC_FAILURE);
         return NULL;
     }
     ret->engine = e;
     ret->pmeth = pmeth;
     ret->operation = EVP_PKEY_OP_UNDEFINED;
     ret->pkey = pkey;
     ret->peerkey = NULL;
     ret->pkey_gencb = 0;
     if (pkey)
         CRYPTO_add(&pkey->references, 1, CRYPTO_LOCK_EVP_PKEY);
     ret->data = NULL;
 
     if (pmeth->init) {
         if (pmeth->init(ret) <= 0) {
+            ret->pmeth = NULL;
             EVP_PKEY_CTX_free(ret);
             return NULL;
         }
     }
 
     return ret;
 }
 
 EVP_PKEY_METHOD *EVP_PKEY_meth_new(int id, int flags)
 {
     EVP_PKEY_METHOD *pmeth;
 
     pmeth = OPENSSL_malloc(sizeof(EVP_PKEY_METHOD));
     if (!pmeth)
         return NULL;
 
     memset(pmeth, 0, sizeof(EVP_PKEY_METHOD));
 
     pmeth->pkey_id = id;
     pmeth->flags = flags | EVP_PKEY_FLAG_DYNAMIC;
     return pmeth;
 }
 
 void EVP_PKEY_meth_get0_info(int *ppkey_id, int *pflags,
                              const EVP_PKEY_METHOD *meth)
 {
     if (ppkey_id)
         *ppkey_id = meth->pkey_id;
     if (pflags)
         *pflags = meth->flags;
 }
 
 void EVP_PKEY_meth_copy(EVP_PKEY_METHOD *dst, const EVP_PKEY_METHOD *src)
 {
 
     dst->init = src->init;
     dst->copy = src->copy;
     dst->cleanup = src->cleanup;
 
     dst->paramgen_init = src->paramgen_init;
     dst->paramgen = src->paramgen;
 
     dst->keygen_init = src->keygen_init;
     dst->keygen = src->keygen;
 
     dst->sign_init = src->sign_init;
     dst->sign = src->sign;
 
     dst->verify_init = src->verify_init;
     dst->verify = src->verify;
 
     dst->verify_recover_init = src->verify_recover_init;
     dst->verify_recover = src->verify_recover;
 
     dst->signctx_init = src->signctx_init;
     dst->signctx = src->signctx;
 
     dst->verifyctx_init = src->verifyctx_init;
     dst->verifyctx = src->verifyctx;
 
     dst->encrypt_init = src->encrypt_init;
     dst->encrypt = src->encrypt;
 
     dst->decrypt_init = src->decrypt_init;
     dst->decrypt = src->decrypt;
 
     dst->derive_init = src->derive_init;
     dst->derive = src->derive;
 
     dst->ctrl = src->ctrl;
     dst->ctrl_str = src->ctrl_str;
 }
 
 void EVP_PKEY_meth_free(EVP_PKEY_METHOD *pmeth)
 {
     if (pmeth && (pmeth->flags & EVP_PKEY_FLAG_DYNAMIC))
         OPENSSL_free(pmeth);
 }
 
 EVP_PKEY_CTX *EVP_PKEY_CTX_new(EVP_PKEY *pkey, ENGINE *e)
 {
     return int_ctx_new(pkey, e, -1);
 }
 
 EVP_PKEY_CTX *EVP_PKEY_CTX_new_id(int id, ENGINE *e)
 {
     return int_ctx_new(NULL, e, id);
 }
 
 EVP_PKEY_CTX *EVP_PKEY_CTX_dup(EVP_PKEY_CTX *pctx)
 {
     EVP_PKEY_CTX *rctx;
     if (!pctx->pmeth || !pctx->pmeth->copy)
         return NULL;
 #ifndef OPENSSL_NO_ENGINE
     /* Make sure it's safe to copy a pkey context using an ENGINE */
     if (pctx->engine && !ENGINE_init(pctx->engine)) {
         EVPerr(EVP_F_EVP_PKEY_CTX_DUP, ERR_R_ENGINE_LIB);
         return 0;
     }
 #endif
     rctx = OPENSSL_malloc(sizeof(EVP_PKEY_CTX));
     if (!rctx)
         return NULL;
 
     rctx->pmeth = pctx->pmeth;
 #ifndef OPENSSL_NO_ENGINE
     rctx->engine = pctx->engine;
 #endif
 
     if (pctx->pkey)
         CRYPTO_add(&pctx->pkey->references, 1, CRYPTO_LOCK_EVP_PKEY);
 
     rctx->pkey = pctx->pkey;
 
     if (pctx->peerkey)
         CRYPTO_add(&pctx->peerkey->references, 1, CRYPTO_LOCK_EVP_PKEY);
 
     rctx->peerkey = pctx->peerkey;
 
     rctx->data = NULL;
     rctx->app_data = NULL;
     rctx->operation = pctx->operation;
 
     if (pctx->pmeth->copy(rctx, pctx) > 0)
         return rctx;
 
+    rctx->pmeth = NULL;
     EVP_PKEY_CTX_free(rctx);
     return NULL;
 
 }
 
 int EVP_PKEY_meth_add0(const EVP_PKEY_METHOD *pmeth)
 {
     if (app_pkey_methods == NULL) {
         app_pkey_methods = sk_EVP_PKEY_METHOD_new(pmeth_cmp);
         if (!app_pkey_methods)
             return 0;
     }
     if (!sk_EVP_PKEY_METHOD_push(app_pkey_methods, pmeth))
         return 0;
     sk_EVP_PKEY_METHOD_sort(app_pkey_methods);
     return 1;
 }
 
 void EVP_PKEY_CTX_free(EVP_PKEY_CTX *ctx)
 {
     if (ctx == NULL)
         return;
     if (ctx->pmeth && ctx->pmeth->cleanup)
         ctx->pmeth->cleanup(ctx);
     if (ctx->pkey)
         EVP_PKEY_free(ctx->pkey);
     if (ctx->peerkey)
         EVP_PKEY_free(ctx->peerkey);
 #ifndef OPENSSL_NO_ENGINE
     if (ctx->engine)
         /*
          * The EVP_PKEY_CTX we used belongs to an ENGINE, release the
          * functional reference we held for this reason.
          */
         ENGINE_finish(ctx->engine);
 #endif
     OPENSSL_free(ctx);
 }
 
 int EVP_PKEY_CTX_ctrl(EVP_PKEY_CTX *ctx, int keytype, int optype,
                       int cmd, int p1, void *p2)
 {
     int ret;
     if (!ctx || !ctx->pmeth || !ctx->pmeth->ctrl) {
         EVPerr(EVP_F_EVP_PKEY_CTX_CTRL, EVP_R_COMMAND_NOT_SUPPORTED);
         return -2;
     }
     if ((keytype != -1) && (ctx->pmeth->pkey_id != keytype))
         return -1;
 
     if (ctx->operation == EVP_PKEY_OP_UNDEFINED) {
         EVPerr(EVP_F_EVP_PKEY_CTX_CTRL, EVP_R_NO_OPERATION_SET);
         return -1;
     }
 
     if ((optype != -1) && !(ctx->operation & optype)) {
         EVPerr(EVP_F_EVP_PKEY_CTX_CTRL, EVP_R_INVALID_OPERATION);
         return -1;
     }
 
     ret = ctx->pmeth->ctrl(ctx, cmd, p1, p2);
 
     if (ret == -2)
         EVPerr(EVP_F_EVP_PKEY_CTX_CTRL, EVP_R_COMMAND_NOT_SUPPORTED);
 
     return ret;
 
 }
 
 int EVP_PKEY_CTX_ctrl_str(EVP_PKEY_CTX *ctx,
                           const char *name, const char *value)
 {
     if (!ctx || !ctx->pmeth || !ctx->pmeth->ctrl_str) {
         EVPerr(EVP_F_EVP_PKEY_CTX_CTRL_STR, EVP_R_COMMAND_NOT_SUPPORTED);
         return -2;
     }
     if (!strcmp(name, "digest")) {
         const EVP_MD *md;
         if (!value || !(md = EVP_get_digestbyname(value))) {
             EVPerr(EVP_F_EVP_PKEY_CTX_CTRL_STR, EVP_R_INVALID_DIGEST);
             return 0;
         }
         return EVP_PKEY_CTX_set_signature_md(ctx, md);
     }
     return ctx->pmeth->ctrl_str(ctx, name, value);
 }
 
 int EVP_PKEY_CTX_get_operation(EVP_PKEY_CTX *ctx)
 {
     return ctx->operation;
 }
 
 void EVP_PKEY_CTX_set0_keygen_info(EVP_PKEY_CTX *ctx, int *dat, int datlen)
 {
     ctx->keygen_info = dat;
     ctx->keygen_info_count = datlen;
 }
 
 void EVP_PKEY_CTX_set_data(EVP_PKEY_CTX *ctx, void *data)
 {
     ctx->data = data;
 }
 
 void *EVP_PKEY_CTX_get_data(EVP_PKEY_CTX *ctx)
 {
     return ctx->data;
 }
 
 EVP_PKEY *EVP_PKEY_CTX_get0_pkey(EVP_PKEY_CTX *ctx)
 {
     return ctx->pkey;
 }
 
 EVP_PKEY *EVP_PKEY_CTX_get0_peerkey(EVP_PKEY_CTX *ctx)
 {
     return ctx->peerkey;
 }
 
 void EVP_PKEY_CTX_set_app_data(EVP_PKEY_CTX *ctx, void *data)
 {
     ctx->app_data = data;
 }
 
 void *EVP_PKEY_CTX_get_app_data(EVP_PKEY_CTX *ctx)
 {
     return ctx->app_data;
 }
 
 void EVP_PKEY_meth_set_init(EVP_PKEY_METHOD *pmeth,
                             int (*init) (EVP_PKEY_CTX *ctx))
 {
     pmeth->init = init;
 }
 
 void EVP_PKEY_meth_set_copy(EVP_PKEY_METHOD *pmeth,
                             int (*copy) (EVP_PKEY_CTX *dst,
                                          EVP_PKEY_CTX *src))
 {
     pmeth->copy = copy;
 }
 
 void EVP_PKEY_meth_set_cleanup(EVP_PKEY_METHOD *pmeth,
                                void (*cleanup) (EVP_PKEY_CTX *ctx))
 {
     pmeth->cleanup = cleanup;
 }
 
 void EVP_PKEY_meth_set_paramgen(EVP_PKEY_METHOD *pmeth,
                                 int (*paramgen_init) (EVP_PKEY_CTX *ctx),
                                 int (*paramgen) (EVP_PKEY_CTX *ctx,
                                                  EVP_PKEY *pkey))
 {
     pmeth->paramgen_init = paramgen_init;
     pmeth->paramgen = paramgen;
 }
 
 void EVP_PKEY_meth_set_keygen(EVP_PKEY_METHOD *pmeth,
                               int (*keygen_init) (EVP_PKEY_CTX *ctx),
                               int (*keygen) (EVP_PKEY_CTX *ctx,
                                              EVP_PKEY *pkey))
 {
     pmeth->keygen_init = keygen_init;
     pmeth->keygen = keygen;
 }
 
 void EVP_PKEY_meth_set_sign(EVP_PKEY_METHOD *pmeth,
                             int (*sign_init) (EVP_PKEY_CTX *ctx),
                             int (*sign) (EVP_PKEY_CTX *ctx,
                                          unsigned char *sig, size_t *siglen,
                                          const unsigned char *tbs,
                                          size_t tbslen))
 {
     pmeth->sign_init = sign_init;
     pmeth->sign = sign;
 }
 
 void EVP_PKEY_meth_set_verify(EVP_PKEY_METHOD *pmeth,
                               int (*verify_init) (EVP_PKEY_CTX *ctx),
                               int (*verify) (EVP_PKEY_CTX *ctx,
                                              const unsigned char *sig,
                                              size_t siglen,
                                              const unsigned char *tbs,
                                              size_t tbslen))
 {
     pmeth->verify_init = verify_init;
     pmeth->verify = verify;
 }
 
 void EVP_PKEY_meth_set_verify_recover(EVP_PKEY_METHOD *pmeth,
                                       int (*verify_recover_init) (EVP_PKEY_CTX
                                                                   *ctx),
                                       int (*verify_recover) (EVP_PKEY_CTX
                                                              *ctx,
                                                              unsigned char
                                                              *sig,
                                                              size_t *siglen,
                                                              const unsigned
                                                              char *tbs,
                                                              size_t tbslen))
 {
     pmeth->verify_recover_init = verify_recover_init;
     pmeth->verify_recover = verify_recover;
 }
 
 void EVP_PKEY_meth_set_signctx(EVP_PKEY_METHOD *pmeth,
                                int (*signctx_init) (EVP_PKEY_CTX *ctx,
                                                     EVP_MD_CTX *mctx),
                                int (*signctx) (EVP_PKEY_CTX *ctx,
                                                unsigned char *sig,
                                                size_t *siglen,
                                                EVP_MD_CTX *mctx))
 {
     pmeth->signctx_init = signctx_init;
     pmeth->signctx = signctx;
 }
 
 void EVP_PKEY_meth_set_verifyctx(EVP_PKEY_METHOD *pmeth,
                                  int (*verifyctx_init) (EVP_PKEY_CTX *ctx,
                                                         EVP_MD_CTX *mctx),
                                  int (*verifyctx) (EVP_PKEY_CTX *ctx,
                                                    const unsigned char *sig,
                                                    int siglen,
                                                    EVP_MD_CTX *mctx))
 {
     pmeth->verifyctx_init = verifyctx_init;
     pmeth->verifyctx = verifyctx;
 }
 
 void EVP_PKEY_meth_set_encrypt(EVP_PKEY_METHOD *pmeth,
                                int (*encrypt_init) (EVP_PKEY_CTX *ctx),
                                int (*encryptfn) (EVP_PKEY_CTX *ctx,
                                                  unsigned char *out,
                                                  size_t *outlen,
                                                  const unsigned char *in,
                                                  size_t inlen))
 {
     pmeth->encrypt_init = encrypt_init;
     pmeth->encrypt = encryptfn;
 }
 
 void EVP_PKEY_meth_set_decrypt(EVP_PKEY_METHOD *pmeth,
                                int (*decrypt_init) (EVP_PKEY_CTX *ctx),
                                int (*decrypt) (EVP_PKEY_CTX *ctx,
                                                unsigned char *out,
                                                size_t *outlen,
                                                const unsigned char *in,
                                                size_t inlen))
 {
     pmeth->decrypt_init = decrypt_init;
     pmeth->decrypt = decrypt;
 }
 
 void EVP_PKEY_meth_set_derive(EVP_PKEY_METHOD *pmeth,
                               int (*derive_init) (EVP_PKEY_CTX *ctx),
                               int (*derive) (EVP_PKEY_CTX *ctx,
                                              unsigned char *key,
                                              size_t *keylen))
 {
     pmeth->derive_init = derive_init;
     pmeth->derive = derive;
 }
 
 void EVP_PKEY_meth_set_ctrl(EVP_PKEY_METHOD *pmeth,
                             int (*ctrl) (EVP_PKEY_CTX *ctx, int type, int p1,
                                          void *p2),
                             int (*ctrl_str) (EVP_PKEY_CTX *ctx,
                                              const char *type,
                                              const char *value))
 {
     pmeth->ctrl = ctrl;
     pmeth->ctrl_str = ctrl_str;
 }
Index: vendor-crypto/openssl/dist/crypto/ex_data.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/ex_data.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/ex_data.c	(revision 318897)
@@ -1,646 +1,653 @@
 /* crypto/ex_data.c */
 
 /*
  * Overhaul notes;
  *
  * This code is now *mostly* thread-safe. It is now easier to understand in what
  * ways it is safe and in what ways it is not, which is an improvement. Firstly,
  * all per-class stacks and index-counters for ex_data are stored in the same
  * global LHASH table (keyed by class). This hash table uses locking for all
  * access with the exception of CRYPTO_cleanup_all_ex_data(), which must only be
  * called when no other threads can possibly race against it (even if it was
  * locked, the race would mean it's possible the hash table might have been
  * recreated after the cleanup). As classes can only be added to the hash table,
  * and within each class, the stack of methods can only be incremented, the
  * locking mechanics are simpler than they would otherwise be. For example, the
  * new/dup/free ex_data functions will lock the hash table, copy the method
  * pointers it needs from the relevant class, then unlock the hash table before
  * actually applying those method pointers to the task of the new/dup/free
  * operations. As they can't be removed from the method-stack, only
  * supplemented, there's no race conditions associated with using them outside
  * the lock. The get/set_ex_data functions are not locked because they do not
  * involve this global state at all - they operate directly with a previously
  * obtained per-class method index and a particular "ex_data" variable. These
  * variables are usually instantiated per-context (eg. each RSA structure has
  * one) so locking on read/write access to that variable can be locked locally
  * if required (eg. using the "RSA" lock to synchronise access to a
  * per-RSA-structure ex_data variable if required).
  * [Geoff]
  */
 
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 /* ====================================================================
  * Copyright (c) 1998-2001 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    openssl-core@openssl.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #include "cryptlib.h"
 #include 
 
 /* What an "implementation of ex_data functionality" looks like */
 struct st_CRYPTO_EX_DATA_IMPL {
         /*********************/
     /* GLOBAL OPERATIONS */
     /* Return a new class index */
     int (*cb_new_class) (void);
     /* Cleanup all state used by the implementation */
     void (*cb_cleanup) (void);
         /************************/
     /* PER-CLASS OPERATIONS */
     /* Get a new method index within a class */
     int (*cb_get_new_index) (int class_index, long argl, void *argp,
                              CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func,
                              CRYPTO_EX_free *free_func);
     /* Initialise a new CRYPTO_EX_DATA of a given class */
     int (*cb_new_ex_data) (int class_index, void *obj, CRYPTO_EX_DATA *ad);
     /* Duplicate a CRYPTO_EX_DATA of a given class onto a copy */
     int (*cb_dup_ex_data) (int class_index, CRYPTO_EX_DATA *to,
                            CRYPTO_EX_DATA *from);
     /* Cleanup a CRYPTO_EX_DATA of a given class */
     void (*cb_free_ex_data) (int class_index, void *obj, CRYPTO_EX_DATA *ad);
 };
 
 /* The implementation we use at run-time */
 static const CRYPTO_EX_DATA_IMPL *impl = NULL;
 
 /*
  * To call "impl" functions, use this macro rather than referring to 'impl'
  * directly, eg. EX_IMPL(get_new_index)(...);
  */
 #define EX_IMPL(a) impl->cb_##a
 
 /* Predeclare the "default" ex_data implementation */
 static int int_new_class(void);
 static void int_cleanup(void);
 static int int_get_new_index(int class_index, long argl, void *argp,
                              CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func,
                              CRYPTO_EX_free *free_func);
 static int int_new_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad);
 static int int_dup_ex_data(int class_index, CRYPTO_EX_DATA *to,
                            CRYPTO_EX_DATA *from);
 static void int_free_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad);
 static CRYPTO_EX_DATA_IMPL impl_default = {
     int_new_class,
     int_cleanup,
     int_get_new_index,
     int_new_ex_data,
     int_dup_ex_data,
     int_free_ex_data
 };
 
 /*
  * Internal function that checks whether "impl" is set and if not, sets it to
  * the default.
  */
 static void impl_check(void)
 {
     CRYPTO_w_lock(CRYPTO_LOCK_EX_DATA);
     if (!impl)
         impl = &impl_default;
     CRYPTO_w_unlock(CRYPTO_LOCK_EX_DATA);
 }
 
 /*
  * A macro wrapper for impl_check that first uses a non-locked test before
  * invoking the function (which checks again inside a lock).
  */
 #define IMPL_CHECK if(!impl) impl_check();
 
 /* API functions to get/set the "ex_data" implementation */
 const CRYPTO_EX_DATA_IMPL *CRYPTO_get_ex_data_implementation(void)
 {
     IMPL_CHECK return impl;
 }
 
 int CRYPTO_set_ex_data_implementation(const CRYPTO_EX_DATA_IMPL *i)
 {
     int toret = 0;
     CRYPTO_w_lock(CRYPTO_LOCK_EX_DATA);
     if (!impl) {
         impl = i;
         toret = 1;
     }
     CRYPTO_w_unlock(CRYPTO_LOCK_EX_DATA);
     return toret;
 }
 
 /****************************************************************************/
 /*
  * Interal (default) implementation of "ex_data" support. API functions are
  * further down.
  */
 
 /*
  * The type that represents what each "class" used to implement locally. A
  * STACK of CRYPTO_EX_DATA_FUNCS plus a index-counter. The 'class_index' is
  * the global value representing the class that is used to distinguish these
  * items.
  */
 typedef struct st_ex_class_item {
     int class_index;
     STACK_OF(CRYPTO_EX_DATA_FUNCS) *meth;
     int meth_num;
 } EX_CLASS_ITEM;
 
 /* When assigning new class indexes, this is our counter */
 static int ex_class = CRYPTO_EX_INDEX_USER;
 
 /* The global hash table of EX_CLASS_ITEM items */
 DECLARE_LHASH_OF(EX_CLASS_ITEM);
 static LHASH_OF(EX_CLASS_ITEM) *ex_data = NULL;
 
 /* The callbacks required in the "ex_data" hash table */
 static unsigned long ex_class_item_hash(const EX_CLASS_ITEM *a)
 {
     return a->class_index;
 }
 
 static IMPLEMENT_LHASH_HASH_FN(ex_class_item, EX_CLASS_ITEM)
 
 static int ex_class_item_cmp(const EX_CLASS_ITEM *a, const EX_CLASS_ITEM *b)
 {
     return a->class_index - b->class_index;
 }
 
 static IMPLEMENT_LHASH_COMP_FN(ex_class_item, EX_CLASS_ITEM)
 
 /*
  * Internal functions used by the "impl_default" implementation to access the
  * state
  */
 static int ex_data_check(void)
 {
     int toret = 1;
     CRYPTO_w_lock(CRYPTO_LOCK_EX_DATA);
     if (!ex_data && (ex_data = lh_EX_CLASS_ITEM_new()) == NULL)
         toret = 0;
     CRYPTO_w_unlock(CRYPTO_LOCK_EX_DATA);
     return toret;
 }
 
 /*
  * This macros helps reduce the locking from repeated checks because the
  * ex_data_check() function checks ex_data again inside a lock.
  */
 #define EX_DATA_CHECK(iffail) if(!ex_data && !ex_data_check()) {iffail}
 
 /* This "inner" callback is used by the callback function that follows it */
 static void def_cleanup_util_cb(CRYPTO_EX_DATA_FUNCS *funcs)
 {
     OPENSSL_free(funcs);
 }
 
 /*
  * This callback is used in lh_doall to destroy all EX_CLASS_ITEM values from
  * "ex_data" prior to the ex_data hash table being itself destroyed. Doesn't
  * do any locking.
  */
 static void def_cleanup_cb(void *a_void)
 {
     EX_CLASS_ITEM *item = (EX_CLASS_ITEM *)a_void;
     sk_CRYPTO_EX_DATA_FUNCS_pop_free(item->meth, def_cleanup_util_cb);
     OPENSSL_free(item);
 }
 
 /*
  * Return the EX_CLASS_ITEM from the "ex_data" hash table that corresponds to
  * a given class. Handles locking.
  */
 static EX_CLASS_ITEM *def_get_class(int class_index)
 {
     EX_CLASS_ITEM d, *p, *gen;
     EX_DATA_CHECK(return NULL;)
         d.class_index = class_index;
     CRYPTO_w_lock(CRYPTO_LOCK_EX_DATA);
     p = lh_EX_CLASS_ITEM_retrieve(ex_data, &d);
     if (!p) {
         gen = OPENSSL_malloc(sizeof(EX_CLASS_ITEM));
         if (gen) {
             gen->class_index = class_index;
             gen->meth_num = 0;
             gen->meth = sk_CRYPTO_EX_DATA_FUNCS_new_null();
             if (!gen->meth)
                 OPENSSL_free(gen);
             else {
                 /*
                  * Because we're inside the ex_data lock, the return value
                  * from the insert will be NULL
                  */
                 (void)lh_EX_CLASS_ITEM_insert(ex_data, gen);
-                p = gen;
+                p = lh_EX_CLASS_ITEM_retrieve(ex_data, &d);
+                if (p != gen) {
+                    sk_CRYPTO_EX_DATA_FUNCS_free(gen->meth);
+                    OPENSSL_free(gen);
+                }
             }
         }
     }
     CRYPTO_w_unlock(CRYPTO_LOCK_EX_DATA);
     if (!p)
         CRYPTOerr(CRYPTO_F_DEF_GET_CLASS, ERR_R_MALLOC_FAILURE);
     return p;
 }
 
 /*
  * Add a new method to the given EX_CLASS_ITEM and return the corresponding
  * index (or -1 for error). Handles locking.
  */
 static int def_add_index(EX_CLASS_ITEM *item, long argl, void *argp,
                          CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func,
                          CRYPTO_EX_free *free_func)
 {
     int toret = -1;
     CRYPTO_EX_DATA_FUNCS *a =
         (CRYPTO_EX_DATA_FUNCS *)OPENSSL_malloc(sizeof(CRYPTO_EX_DATA_FUNCS));
     if (!a) {
         CRYPTOerr(CRYPTO_F_DEF_ADD_INDEX, ERR_R_MALLOC_FAILURE);
         return -1;
     }
     a->argl = argl;
     a->argp = argp;
     a->new_func = new_func;
     a->dup_func = dup_func;
     a->free_func = free_func;
     CRYPTO_w_lock(CRYPTO_LOCK_EX_DATA);
     while (sk_CRYPTO_EX_DATA_FUNCS_num(item->meth) <= item->meth_num) {
         if (!sk_CRYPTO_EX_DATA_FUNCS_push(item->meth, NULL)) {
             CRYPTOerr(CRYPTO_F_DEF_ADD_INDEX, ERR_R_MALLOC_FAILURE);
             OPENSSL_free(a);
             goto err;
         }
     }
     toret = item->meth_num++;
     (void)sk_CRYPTO_EX_DATA_FUNCS_set(item->meth, toret, a);
  err:
     CRYPTO_w_unlock(CRYPTO_LOCK_EX_DATA);
     return toret;
 }
 
 /**************************************************************/
 /* The functions in the default CRYPTO_EX_DATA_IMPL structure */
 
 static int int_new_class(void)
 {
     int toret;
     CRYPTO_w_lock(CRYPTO_LOCK_EX_DATA);
     toret = ex_class++;
     CRYPTO_w_unlock(CRYPTO_LOCK_EX_DATA);
     return toret;
 }
 
 static void int_cleanup(void)
 {
     EX_DATA_CHECK(return;)
         lh_EX_CLASS_ITEM_doall(ex_data, def_cleanup_cb);
     lh_EX_CLASS_ITEM_free(ex_data);
     ex_data = NULL;
     impl = NULL;
 }
 
 static int int_get_new_index(int class_index, long argl, void *argp,
                              CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func,
                              CRYPTO_EX_free *free_func)
 {
     EX_CLASS_ITEM *item = def_get_class(class_index);
     if (!item)
         return -1;
     return def_add_index(item, argl, argp, new_func, dup_func, free_func);
 }
 
 /*
  * Thread-safe by copying a class's array of "CRYPTO_EX_DATA_FUNCS" entries
  * in the lock, then using them outside the lock. NB: Thread-safety only
  * applies to the global "ex_data" state (ie. class definitions), not
  * thread-safe on 'ad' itself.
  */
 static int int_new_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad)
 {
     int mx, i;
     void *ptr;
     CRYPTO_EX_DATA_FUNCS **storage = NULL;
     EX_CLASS_ITEM *item = def_get_class(class_index);
     if (!item)
         /* error is already set */
         return 0;
     ad->sk = NULL;
     CRYPTO_r_lock(CRYPTO_LOCK_EX_DATA);
     mx = sk_CRYPTO_EX_DATA_FUNCS_num(item->meth);
     if (mx > 0) {
         storage = OPENSSL_malloc(mx * sizeof(CRYPTO_EX_DATA_FUNCS *));
         if (!storage)
             goto skip;
         for (i = 0; i < mx; i++)
             storage[i] = sk_CRYPTO_EX_DATA_FUNCS_value(item->meth, i);
     }
  skip:
     CRYPTO_r_unlock(CRYPTO_LOCK_EX_DATA);
     if ((mx > 0) && !storage) {
         CRYPTOerr(CRYPTO_F_INT_NEW_EX_DATA, ERR_R_MALLOC_FAILURE);
         return 0;
     }
     for (i = 0; i < mx; i++) {
         if (storage[i] && storage[i]->new_func) {
             ptr = CRYPTO_get_ex_data(ad, i);
             storage[i]->new_func(obj, ptr, ad, i,
                                  storage[i]->argl, storage[i]->argp);
         }
     }
     if (storage)
         OPENSSL_free(storage);
     return 1;
 }
 
 /* Same thread-safety notes as for "int_new_ex_data" */
 static int int_dup_ex_data(int class_index, CRYPTO_EX_DATA *to,
                            CRYPTO_EX_DATA *from)
 {
     int mx, j, i;
-    char *ptr;
+    void *ptr;
     CRYPTO_EX_DATA_FUNCS **storage = NULL;
     EX_CLASS_ITEM *item;
     if (!from->sk)
         /* 'to' should be "blank" which *is* just like 'from' */
         return 1;
     if ((item = def_get_class(class_index)) == NULL)
         return 0;
     CRYPTO_r_lock(CRYPTO_LOCK_EX_DATA);
     mx = sk_CRYPTO_EX_DATA_FUNCS_num(item->meth);
     j = sk_void_num(from->sk);
     if (j < mx)
         mx = j;
     if (mx > 0) {
+        if (!CRYPTO_set_ex_data(to, mx - 1, NULL))
+            goto skip;
         storage = OPENSSL_malloc(mx * sizeof(CRYPTO_EX_DATA_FUNCS *));
         if (!storage)
             goto skip;
         for (i = 0; i < mx; i++)
             storage[i] = sk_CRYPTO_EX_DATA_FUNCS_value(item->meth, i);
     }
  skip:
     CRYPTO_r_unlock(CRYPTO_LOCK_EX_DATA);
     if ((mx > 0) && !storage) {
         CRYPTOerr(CRYPTO_F_INT_DUP_EX_DATA, ERR_R_MALLOC_FAILURE);
         return 0;
     }
     for (i = 0; i < mx; i++) {
         ptr = CRYPTO_get_ex_data(from, i);
         if (storage[i] && storage[i]->dup_func)
             storage[i]->dup_func(to, from, &ptr, i,
                                  storage[i]->argl, storage[i]->argp);
         CRYPTO_set_ex_data(to, i, ptr);
     }
     if (storage)
         OPENSSL_free(storage);
     return 1;
 }
 
 /* Same thread-safety notes as for "int_new_ex_data" */
 static void int_free_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad)
 {
     int mx, i;
     EX_CLASS_ITEM *item;
     void *ptr;
+    CRYPTO_EX_DATA_FUNCS *f;
     CRYPTO_EX_DATA_FUNCS **storage = NULL;
     if (ex_data == NULL)
-        return;
+        goto err;
     if ((item = def_get_class(class_index)) == NULL)
-        return;
+        goto err;
     CRYPTO_r_lock(CRYPTO_LOCK_EX_DATA);
     mx = sk_CRYPTO_EX_DATA_FUNCS_num(item->meth);
     if (mx > 0) {
         storage = OPENSSL_malloc(mx * sizeof(CRYPTO_EX_DATA_FUNCS *));
         if (!storage)
             goto skip;
         for (i = 0; i < mx; i++)
             storage[i] = sk_CRYPTO_EX_DATA_FUNCS_value(item->meth, i);
     }
  skip:
     CRYPTO_r_unlock(CRYPTO_LOCK_EX_DATA);
-    if ((mx > 0) && !storage) {
-        CRYPTOerr(CRYPTO_F_INT_FREE_EX_DATA, ERR_R_MALLOC_FAILURE);
-        return;
-    }
     for (i = 0; i < mx; i++) {
-        if (storage[i] && storage[i]->free_func) {
+        if (storage != NULL)
+            f = storage[i];
+        else {
+            CRYPTO_r_lock(CRYPTO_LOCK_EX_DATA);
+            f = sk_CRYPTO_EX_DATA_FUNCS_value(item->meth, i);
+            CRYPTO_r_unlock(CRYPTO_LOCK_EX_DATA);
+        }
+        if (f != NULL && f->free_func != NULL) {
             ptr = CRYPTO_get_ex_data(ad, i);
-            storage[i]->free_func(obj, ptr, ad, i,
-                                  storage[i]->argl, storage[i]->argp);
+            f->free_func(obj, ptr, ad, i, f->argl, f->argp);
         }
     }
-    if (storage)
-        OPENSSL_free(storage);
-    if (ad->sk) {
-        sk_void_free(ad->sk);
-        ad->sk = NULL;
-    }
+    OPENSSL_free(storage);
+ err:
+    sk_void_free(ad->sk);
+    ad->sk = NULL;
 }
 
 /********************************************************************/
 /*
  * API functions that defer all "state" operations to the "ex_data"
  * implementation we have set.
  */
 
 /*
  * Obtain an index for a new class (not the same as getting a new index
  * within an existing class - this is actually getting a new *class*)
  */
 int CRYPTO_ex_data_new_class(void)
 {
     IMPL_CHECK return EX_IMPL(new_class) ();
 }
 
 /*
  * Release all "ex_data" state to prevent memory leaks. This can't be made
  * thread-safe without overhauling a lot of stuff, and shouldn't really be
  * called under potential race-conditions anyway (it's for program shutdown
  * after all).
  */
 void CRYPTO_cleanup_all_ex_data(void)
 {
     IMPL_CHECK EX_IMPL(cleanup) ();
 }
 
 /* Inside an existing class, get/register a new index. */
 int CRYPTO_get_ex_new_index(int class_index, long argl, void *argp,
                             CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func,
                             CRYPTO_EX_free *free_func)
 {
     int ret = -1;
 
     IMPL_CHECK
         ret = EX_IMPL(get_new_index) (class_index,
                                       argl, argp, new_func, dup_func,
                                       free_func);
     return ret;
 }
 
 /*
  * Initialise a new CRYPTO_EX_DATA for use in a particular class - including
  * calling new() callbacks for each index in the class used by this variable
  */
 int CRYPTO_new_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad)
 {
     IMPL_CHECK return EX_IMPL(new_ex_data) (class_index, obj, ad);
 }
 
 /*
  * Duplicate a CRYPTO_EX_DATA variable - including calling dup() callbacks
  * for each index in the class used by this variable
  */
 int CRYPTO_dup_ex_data(int class_index, CRYPTO_EX_DATA *to,
                        CRYPTO_EX_DATA *from)
 {
     IMPL_CHECK return EX_IMPL(dup_ex_data) (class_index, to, from);
 }
 
 /*
  * Cleanup a CRYPTO_EX_DATA variable - including calling free() callbacks for
  * each index in the class used by this variable
  */
 void CRYPTO_free_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad)
 {
     IMPL_CHECK EX_IMPL(free_ex_data) (class_index, obj, ad);
 }
 
 /*
  * For a given CRYPTO_EX_DATA variable, set the value corresponding to a
  * particular index in the class used by this variable
  */
 int CRYPTO_set_ex_data(CRYPTO_EX_DATA *ad, int idx, void *val)
 {
     int i;
 
     if (ad->sk == NULL) {
         if ((ad->sk = sk_void_new_null()) == NULL) {
             CRYPTOerr(CRYPTO_F_CRYPTO_SET_EX_DATA, ERR_R_MALLOC_FAILURE);
             return (0);
         }
     }
     i = sk_void_num(ad->sk);
 
     while (i <= idx) {
         if (!sk_void_push(ad->sk, NULL)) {
             CRYPTOerr(CRYPTO_F_CRYPTO_SET_EX_DATA, ERR_R_MALLOC_FAILURE);
             return (0);
         }
         i++;
     }
     sk_void_set(ad->sk, idx, val);
     return (1);
 }
 
 /*
  * For a given CRYPTO_EX_DATA_ variable, get the value corresponding to a
  * particular index in the class used by this variable
  */
 void *CRYPTO_get_ex_data(const CRYPTO_EX_DATA *ad, int idx)
 {
     if (ad->sk == NULL)
         return (0);
     else if (idx >= sk_void_num(ad->sk))
         return (0);
     else
         return (sk_void_value(ad->sk, idx));
 }
 
 IMPLEMENT_STACK_OF(CRYPTO_EX_DATA_FUNCS)
Index: vendor-crypto/openssl/dist/crypto/hmac/hm_pmeth.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/hmac/hm_pmeth.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/hmac/hm_pmeth.c	(revision 318897)
@@ -1,262 +1,265 @@
 /*
  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
  * 2007.
  */
 /* ====================================================================
  * Copyright (c) 2007 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    licensing@OpenSSL.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #include 
 #include "cryptlib.h"
 #include 
 #include 
 #include 
 #include 
 #include "evp_locl.h"
 
 /* HMAC pkey context structure */
 
 typedef struct {
     const EVP_MD *md;           /* MD for HMAC use */
     ASN1_OCTET_STRING ktmp;     /* Temp storage for key */
     HMAC_CTX ctx;
 } HMAC_PKEY_CTX;
 
 static int pkey_hmac_init(EVP_PKEY_CTX *ctx)
 {
     HMAC_PKEY_CTX *hctx;
     hctx = OPENSSL_malloc(sizeof(HMAC_PKEY_CTX));
     if (!hctx)
         return 0;
     hctx->md = NULL;
     hctx->ktmp.data = NULL;
     hctx->ktmp.length = 0;
     hctx->ktmp.flags = 0;
     hctx->ktmp.type = V_ASN1_OCTET_STRING;
     HMAC_CTX_init(&hctx->ctx);
 
     ctx->data = hctx;
     ctx->keygen_info_count = 0;
 
     return 1;
 }
 
 static int pkey_hmac_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src)
 {
     HMAC_PKEY_CTX *sctx, *dctx;
     if (!pkey_hmac_init(dst))
         return 0;
     sctx = src->data;
     dctx = dst->data;
     dctx->md = sctx->md;
-    HMAC_CTX_init(&dctx->ctx);
     if (!HMAC_CTX_copy(&dctx->ctx, &sctx->ctx))
-        return 0;
-    if (sctx->ktmp.data) {
+        goto err;
+    if (sctx->ktmp.data != NULL) {
         if (!ASN1_OCTET_STRING_set(&dctx->ktmp,
                                    sctx->ktmp.data, sctx->ktmp.length))
-            return 0;
+            goto err;
     }
     return 1;
+ err:
+    HMAC_CTX_cleanup(&dctx->ctx);
+    OPENSSL_free(dctx);
+    return 0;
 }
 
 static void pkey_hmac_cleanup(EVP_PKEY_CTX *ctx)
 {
     HMAC_PKEY_CTX *hctx = ctx->data;
     HMAC_CTX_cleanup(&hctx->ctx);
     if (hctx->ktmp.data) {
         if (hctx->ktmp.length)
             OPENSSL_cleanse(hctx->ktmp.data, hctx->ktmp.length);
         OPENSSL_free(hctx->ktmp.data);
         hctx->ktmp.data = NULL;
     }
     OPENSSL_free(hctx);
 }
 
 static int pkey_hmac_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)
 {
     ASN1_OCTET_STRING *hkey = NULL;
     HMAC_PKEY_CTX *hctx = ctx->data;
     if (!hctx->ktmp.data)
         return 0;
     hkey = ASN1_OCTET_STRING_dup(&hctx->ktmp);
     if (!hkey)
         return 0;
     EVP_PKEY_assign(pkey, EVP_PKEY_HMAC, hkey);
 
     return 1;
 }
 
 static int int_update(EVP_MD_CTX *ctx, const void *data, size_t count)
 {
     HMAC_PKEY_CTX *hctx = ctx->pctx->data;
     if (!HMAC_Update(&hctx->ctx, data, count))
         return 0;
     return 1;
 }
 
 static int hmac_signctx_init(EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx)
 {
     HMAC_PKEY_CTX *hctx = ctx->data;
     HMAC_CTX_set_flags(&hctx->ctx, mctx->flags & ~EVP_MD_CTX_FLAG_NO_INIT);
     EVP_MD_CTX_set_flags(mctx, EVP_MD_CTX_FLAG_NO_INIT);
     mctx->update = int_update;
     return 1;
 }
 
 static int hmac_signctx(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen,
                         EVP_MD_CTX *mctx)
 {
     unsigned int hlen;
     HMAC_PKEY_CTX *hctx = ctx->data;
     int l = EVP_MD_CTX_size(mctx);
 
     if (l < 0)
         return 0;
     *siglen = l;
     if (!sig)
         return 1;
 
     if (!HMAC_Final(&hctx->ctx, sig, &hlen))
         return 0;
     *siglen = (size_t)hlen;
     return 1;
 }
 
 static int pkey_hmac_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2)
 {
     HMAC_PKEY_CTX *hctx = ctx->data;
     ASN1_OCTET_STRING *key;
     switch (type) {
 
     case EVP_PKEY_CTRL_SET_MAC_KEY:
         if ((!p2 && p1 > 0) || (p1 < -1))
             return 0;
         if (!ASN1_OCTET_STRING_set(&hctx->ktmp, p2, p1))
             return 0;
         break;
 
     case EVP_PKEY_CTRL_MD:
         hctx->md = p2;
         break;
 
     case EVP_PKEY_CTRL_DIGESTINIT:
         key = (ASN1_OCTET_STRING *)ctx->pkey->pkey.ptr;
         if (!HMAC_Init_ex(&hctx->ctx, key->data, key->length, hctx->md,
                           ctx->engine))
             return 0;
         break;
 
     default:
         return -2;
 
     }
     return 1;
 }
 
 static int pkey_hmac_ctrl_str(EVP_PKEY_CTX *ctx,
                               const char *type, const char *value)
 {
     if (!value) {
         return 0;
     }
     if (!strcmp(type, "key")) {
         void *p = (void *)value;
         return pkey_hmac_ctrl(ctx, EVP_PKEY_CTRL_SET_MAC_KEY, -1, p);
     }
     if (!strcmp(type, "hexkey")) {
         unsigned char *key;
         int r;
         long keylen;
         key = string_to_hex(value, &keylen);
         if (!key)
             return 0;
         r = pkey_hmac_ctrl(ctx, EVP_PKEY_CTRL_SET_MAC_KEY, keylen, key);
         OPENSSL_free(key);
         return r;
     }
     return -2;
 }
 
 const EVP_PKEY_METHOD hmac_pkey_meth = {
     EVP_PKEY_HMAC,
     0,
     pkey_hmac_init,
     pkey_hmac_copy,
     pkey_hmac_cleanup,
 
     0, 0,
 
     0,
     pkey_hmac_keygen,
 
     0, 0,
 
     0, 0,
 
     0, 0,
 
     hmac_signctx_init,
     hmac_signctx,
 
     0, 0,
 
     0, 0,
 
     0, 0,
 
     0, 0,
 
     pkey_hmac_ctrl,
     pkey_hmac_ctrl_str
 };
Index: vendor-crypto/openssl/dist/crypto/md5/Makefile
===================================================================
--- vendor-crypto/openssl/dist/crypto/md5/Makefile	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/md5/Makefile	(revision 318897)
@@ -1,107 +1,107 @@
 #
 # OpenSSL/crypto/md5/Makefile
 #
 
 DIR=    md5
 TOP=    ../..
 CC=     cc
 CPP=    $(CC) -E
 INCLUDES=-I.. -I$(TOP) -I../../include
 CFLAG=-g
 MAKEFILE=       Makefile
 AR=             ar r
 
 MD5_ASM_OBJ=
 
 CFLAGS= $(INCLUDES) $(CFLAG)
 ASFLAGS= $(INCLUDES) $(ASFLAG)
 AFLAGS= $(ASFLAGS)
 
 GENERAL=Makefile
 TEST=md5test.c
 APPS=
 
 LIB=$(TOP)/libcrypto.a
 LIBSRC=md5_dgst.c md5_one.c
 LIBOBJ=md5_dgst.o md5_one.o $(MD5_ASM_OBJ)
 
 SRC= $(LIBSRC)
 
 EXHEADER= md5.h
 HEADER= md5_locl.h $(EXHEADER)
 
 ALL=    $(GENERAL) $(SRC) $(HEADER)
 
 top:
 	(cd ../..; $(MAKE) DIRS=crypto SDIRS=$(DIR) sub_all)
 
 all:    lib
 
 lib:    $(LIBOBJ)
 	$(AR) $(LIB) $(LIBOBJ)
 	$(RANLIB) $(LIB) || echo Never mind.
 	@touch lib
 
 md5-586.s:	asm/md5-586.pl ../perlasm/x86asm.pl
 	$(PERL) asm/md5-586.pl $(PERLASM_SCHEME) $(CFLAGS) > $@
 
 md5-x86_64.s:	asm/md5-x86_64.pl
 	$(PERL) asm/md5-x86_64.pl $(PERLASM_SCHEME) > $@
 
 md5-ia64.s: asm/md5-ia64.S
 	$(CC) $(CFLAGS) -E asm/md5-ia64.S | \
 	$(PERL) -ne 's/;\s+/;\n/g; print;' > $@
 
 md5-sparcv9.S:	asm/md5-sparcv9.pl
 	$(PERL) asm/md5-sparcv9.pl $@ $(CFLAGS)
 
 files:
 	$(PERL) $(TOP)/util/files.pl Makefile >> $(TOP)/MINFO
 
 links:
 	@$(PERL) $(TOP)/util/mklink.pl ../../include/openssl $(EXHEADER)
 	@$(PERL) $(TOP)/util/mklink.pl ../../test $(TEST)
 	@$(PERL) $(TOP)/util/mklink.pl ../../apps $(APPS)
 
 install:
 	@[ -n "$(INSTALLTOP)" ] # should be set by top Makefile...
 	@headerlist="$(EXHEADER)"; for i in $$headerlist ; \
 	do  \
 	(cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i; \
 	chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i ); \
 	done;
 
 tags:
 	ctags $(SRC)
 
 tests:
 
 lint:
 	lint -DLINT $(INCLUDES) $(SRC)>fluff
 
 update: depend
 
 depend:
 	@[ -n "$(MAKEDEPEND)" ] # should be set by upper Makefile...
 	$(MAKEDEPEND) -- $(CFLAG) $(INCLUDES) $(DEPFLAG) -- $(PROGS) $(LIBSRC)
 
 dclean:
 	$(PERL) -pe 'if (/^# DO NOT DELETE THIS LINE/) {print; exit(0);}' $(MAKEFILE) >Makefile.new
 	mv -f Makefile.new $(MAKEFILE)
 
 clean:
-	rm -f *.s *.o *.obj lib tags core .pure .nfs* *.old *.bak fluff
+	rm -f *.s *.S *.o *.obj lib tags core .pure .nfs* *.old *.bak fluff
 
 # DO NOT DELETE THIS LINE -- make depend depends on it.
 
 md5_dgst.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
 md5_dgst.o: ../../include/openssl/md5.h ../../include/openssl/opensslconf.h
 md5_dgst.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 md5_dgst.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 md5_dgst.o: ../../include/openssl/symhacks.h ../md32_common.h md5_dgst.c
 md5_dgst.o: md5_locl.h
 md5_one.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
 md5_one.o: ../../include/openssl/md5.h ../../include/openssl/opensslconf.h
 md5_one.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 md5_one.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 md5_one.o: ../../include/openssl/symhacks.h md5_one.c
Index: vendor-crypto/openssl/dist/crypto/mem.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/mem.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/mem.c	(revision 318897)
@@ -1,458 +1,458 @@
 /* crypto/mem.c */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 
 #include 
 #include 
 #include 
 #include "cryptlib.h"
 
 static int allow_customize = 1; /* we provide flexible functions for */
 static int allow_customize_debug = 1; /* exchanging memory-related functions
                                        * at run-time, but this must be done
                                        * before any blocks are actually
                                        * allocated; or we'll run into huge
                                        * problems when malloc/free pairs
                                        * don't match etc. */
 
 /*
  * the following pointers may be changed as long as 'allow_customize' is set
  */
 
 static void *(*malloc_func) (size_t) = malloc;
 static void *default_malloc_ex(size_t num, const char *file, int line)
 {
     return malloc_func(num);
 }
 
 static void *(*malloc_ex_func) (size_t, const char *file, int line)
     = default_malloc_ex;
 
 #ifdef OPENSSL_SYS_VMS
 # if __INITIAL_POINTER_SIZE == 64
 #  define realloc _realloc64
 # elif __INITIAL_POINTER_SIZE == 32
 #  define realloc _realloc32
 # endif
 #endif
 
 static void *(*realloc_func) (void *, size_t) = realloc;
 static void *default_realloc_ex(void *str, size_t num,
                                 const char *file, int line)
 {
     return realloc_func(str, num);
 }
 
 static void *(*realloc_ex_func) (void *, size_t, const char *file, int line)
     = default_realloc_ex;
 
 #ifdef OPENSSL_SYS_VMS
    static void (*free_func) (__void_ptr64) = free;
 #else
    static void (*free_func) (void *) = free;
 #endif
 
 static void *(*malloc_locked_func) (size_t) = malloc;
 static void *default_malloc_locked_ex(size_t num, const char *file, int line)
 {
     return malloc_locked_func(num);
 }
 
 static void *(*malloc_locked_ex_func) (size_t, const char *file, int line)
     = default_malloc_locked_ex;
 
 #ifdef OPENSSL_SYS_VMS
    static void (*free_locked_func) (__void_ptr64) = free;
 #else
    static void (*free_locked_func) (void *) = free;
 #endif
 
 /* may be changed as long as 'allow_customize_debug' is set */
 /* XXX use correct function pointer types */
 #ifdef CRYPTO_MDEBUG
 /* use default functions from mem_dbg.c */
 static void (*malloc_debug_func) (void *, int, const char *, int, int)
     = CRYPTO_dbg_malloc;
 static void (*realloc_debug_func) (void *, void *, int, const char *, int,
                                    int)
     = CRYPTO_dbg_realloc;
 static void (*free_debug_func) (void *, int) = CRYPTO_dbg_free;
 static void (*set_debug_options_func) (long) = CRYPTO_dbg_set_options;
 static long (*get_debug_options_func) (void) = CRYPTO_dbg_get_options;
 #else
 /*
  * applications can use CRYPTO_malloc_debug_init() to select above case at
  * run-time
  */
 static void (*malloc_debug_func) (void *, int, const char *, int, int) = NULL;
 static void (*realloc_debug_func) (void *, void *, int, const char *, int,
                                    int)
     = NULL;
 static void (*free_debug_func) (void *, int) = NULL;
 static void (*set_debug_options_func) (long) = NULL;
 static long (*get_debug_options_func) (void) = NULL;
 #endif
 
 int CRYPTO_set_mem_functions(void *(*m) (size_t), void *(*r) (void *, size_t),
                              void (*f) (void *))
 {
-    /* Dummy call just to ensure OPENSSL_init() gets linked in */
-    OPENSSL_init();
     if (!allow_customize)
         return 0;
     if ((m == 0) || (r == 0) || (f == 0))
         return 0;
+    /* Dummy call just to ensure OPENSSL_init() gets linked in */
+    OPENSSL_init();
     malloc_func = m;
     malloc_ex_func = default_malloc_ex;
     realloc_func = r;
     realloc_ex_func = default_realloc_ex;
     free_func = f;
     malloc_locked_func = m;
     malloc_locked_ex_func = default_malloc_locked_ex;
     free_locked_func = f;
     return 1;
 }
 
 int CRYPTO_set_mem_ex_functions(void *(*m) (size_t, const char *, int),
                                 void *(*r) (void *, size_t, const char *,
                                             int), void (*f) (void *))
 {
     if (!allow_customize)
         return 0;
     if ((m == 0) || (r == 0) || (f == 0))
         return 0;
     malloc_func = 0;
     malloc_ex_func = m;
     realloc_func = 0;
     realloc_ex_func = r;
     free_func = f;
     malloc_locked_func = 0;
     malloc_locked_ex_func = m;
     free_locked_func = f;
     return 1;
 }
 
 int CRYPTO_set_locked_mem_functions(void *(*m) (size_t), void (*f) (void *))
 {
     if (!allow_customize)
         return 0;
     if ((m == NULL) || (f == NULL))
         return 0;
     malloc_locked_func = m;
     malloc_locked_ex_func = default_malloc_locked_ex;
     free_locked_func = f;
     return 1;
 }
 
 int CRYPTO_set_locked_mem_ex_functions(void *(*m) (size_t, const char *, int),
                                        void (*f) (void *))
 {
     if (!allow_customize)
         return 0;
     if ((m == NULL) || (f == NULL))
         return 0;
     malloc_locked_func = 0;
     malloc_locked_ex_func = m;
     free_func = f;
     return 1;
 }
 
 int CRYPTO_set_mem_debug_functions(void (*m)
                                     (void *, int, const char *, int, int),
                                    void (*r) (void *, void *, int,
                                               const char *, int, int),
                                    void (*f) (void *, int), void (*so) (long),
                                    long (*go) (void))
 {
     if (!allow_customize_debug)
         return 0;
     OPENSSL_init();
     malloc_debug_func = m;
     realloc_debug_func = r;
     free_debug_func = f;
     set_debug_options_func = so;
     get_debug_options_func = go;
     return 1;
 }
 
 void CRYPTO_get_mem_functions(void *(**m) (size_t),
                               void *(**r) (void *, size_t),
                               void (**f) (void *))
 {
     if (m != NULL)
         *m = (malloc_ex_func == default_malloc_ex) ? malloc_func : 0;
     if (r != NULL)
         *r = (realloc_ex_func == default_realloc_ex) ? realloc_func : 0;
     if (f != NULL)
         *f = free_func;
 }
 
 void CRYPTO_get_mem_ex_functions(void *(**m) (size_t, const char *, int),
                                  void *(**r) (void *, size_t, const char *,
                                               int), void (**f) (void *))
 {
     if (m != NULL)
         *m = (malloc_ex_func != default_malloc_ex) ? malloc_ex_func : 0;
     if (r != NULL)
         *r = (realloc_ex_func != default_realloc_ex) ? realloc_ex_func : 0;
     if (f != NULL)
         *f = free_func;
 }
 
 void CRYPTO_get_locked_mem_functions(void *(**m) (size_t),
                                      void (**f) (void *))
 {
     if (m != NULL)
         *m = (malloc_locked_ex_func == default_malloc_locked_ex) ?
             malloc_locked_func : 0;
     if (f != NULL)
         *f = free_locked_func;
 }
 
 void CRYPTO_get_locked_mem_ex_functions(void
                                         *(**m) (size_t, const char *, int),
                                         void (**f) (void *))
 {
     if (m != NULL)
         *m = (malloc_locked_ex_func != default_malloc_locked_ex) ?
             malloc_locked_ex_func : 0;
     if (f != NULL)
         *f = free_locked_func;
 }
 
 void CRYPTO_get_mem_debug_functions(void (**m)
                                      (void *, int, const char *, int, int),
                                     void (**r) (void *, void *, int,
                                                 const char *, int, int),
                                     void (**f) (void *, int),
                                     void (**so) (long), long (**go) (void))
 {
     if (m != NULL)
         *m = malloc_debug_func;
     if (r != NULL)
         *r = realloc_debug_func;
     if (f != NULL)
         *f = free_debug_func;
     if (so != NULL)
         *so = set_debug_options_func;
     if (go != NULL)
         *go = get_debug_options_func;
 }
 
 void *CRYPTO_malloc_locked(int num, const char *file, int line)
 {
     void *ret = NULL;
 
     if (num <= 0)
         return NULL;
 
     if (allow_customize)
         allow_customize = 0;
     if (malloc_debug_func != NULL) {
         if (allow_customize_debug)
             allow_customize_debug = 0;
         malloc_debug_func(NULL, num, file, line, 0);
     }
     ret = malloc_locked_ex_func(num, file, line);
 #ifdef LEVITTE_DEBUG_MEM
     fprintf(stderr, "LEVITTE_DEBUG_MEM:         > 0x%p (%d)\n", ret, num);
 #endif
     if (malloc_debug_func != NULL)
         malloc_debug_func(ret, num, file, line, 1);
 
     return ret;
 }
 
 void CRYPTO_free_locked(void *str)
 {
     if (free_debug_func != NULL)
         free_debug_func(str, 0);
 #ifdef LEVITTE_DEBUG_MEM
     fprintf(stderr, "LEVITTE_DEBUG_MEM:         < 0x%p\n", str);
 #endif
     free_locked_func(str);
     if (free_debug_func != NULL)
         free_debug_func(NULL, 1);
 }
 
 void *CRYPTO_malloc(int num, const char *file, int line)
 {
     void *ret = NULL;
 
     if (num <= 0)
         return NULL;
 
     if (allow_customize)
         allow_customize = 0;
     if (malloc_debug_func != NULL) {
         if (allow_customize_debug)
             allow_customize_debug = 0;
         malloc_debug_func(NULL, num, file, line, 0);
     }
     ret = malloc_ex_func(num, file, line);
 #ifdef LEVITTE_DEBUG_MEM
     fprintf(stderr, "LEVITTE_DEBUG_MEM:         > 0x%p (%d)\n", ret, num);
 #endif
     if (malloc_debug_func != NULL)
         malloc_debug_func(ret, num, file, line, 1);
 
     return ret;
 }
 
 char *CRYPTO_strdup(const char *str, const char *file, int line)
 {
     char *ret = CRYPTO_malloc(strlen(str) + 1, file, line);
 
     if (ret == NULL)
         return NULL;
 
     strcpy(ret, str);
     return ret;
 }
 
 void *CRYPTO_realloc(void *str, int num, const char *file, int line)
 {
     void *ret = NULL;
 
     if (str == NULL)
         return CRYPTO_malloc(num, file, line);
 
     if (num <= 0)
         return NULL;
 
     if (realloc_debug_func != NULL)
         realloc_debug_func(str, NULL, num, file, line, 0);
     ret = realloc_ex_func(str, num, file, line);
 #ifdef LEVITTE_DEBUG_MEM
     fprintf(stderr, "LEVITTE_DEBUG_MEM:         | 0x%p -> 0x%p (%d)\n", str,
             ret, num);
 #endif
     if (realloc_debug_func != NULL)
         realloc_debug_func(str, ret, num, file, line, 1);
 
     return ret;
 }
 
 void *CRYPTO_realloc_clean(void *str, int old_len, int num, const char *file,
                            int line)
 {
     void *ret = NULL;
 
     if (str == NULL)
         return CRYPTO_malloc(num, file, line);
 
     if (num <= 0)
         return NULL;
 
     /*
      * We don't support shrinking the buffer. Note the memcpy that copies
      * |old_len| bytes to the new buffer, below.
      */
     if (num < old_len)
         return NULL;
 
     if (realloc_debug_func != NULL)
         realloc_debug_func(str, NULL, num, file, line, 0);
     ret = malloc_ex_func(num, file, line);
     if (ret) {
         memcpy(ret, str, old_len);
         OPENSSL_cleanse(str, old_len);
         free_func(str);
     }
 #ifdef LEVITTE_DEBUG_MEM
     fprintf(stderr,
             "LEVITTE_DEBUG_MEM:         | 0x%p -> 0x%p (%d)\n",
             str, ret, num);
 #endif
     if (realloc_debug_func != NULL)
         realloc_debug_func(str, ret, num, file, line, 1);
 
     return ret;
 }
 
 void CRYPTO_free(void *str)
 {
     if (free_debug_func != NULL)
         free_debug_func(str, 0);
 #ifdef LEVITTE_DEBUG_MEM
     fprintf(stderr, "LEVITTE_DEBUG_MEM:         < 0x%p\n", str);
 #endif
     free_func(str);
     if (free_debug_func != NULL)
         free_debug_func(NULL, 1);
 }
 
 void *CRYPTO_remalloc(void *a, int num, const char *file, int line)
 {
     if (a != NULL)
         OPENSSL_free(a);
     a = (char *)OPENSSL_malloc(num);
     return (a);
 }
 
 void CRYPTO_set_mem_debug_options(long bits)
 {
     if (set_debug_options_func != NULL)
         set_debug_options_func(bits);
 }
 
 long CRYPTO_get_mem_debug_options(void)
 {
     if (get_debug_options_func != NULL)
         return get_debug_options_func();
     return 0;
 }
Index: vendor-crypto/openssl/dist/crypto/modes/Makefile
===================================================================
--- vendor-crypto/openssl/dist/crypto/modes/Makefile	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/modes/Makefile	(revision 318897)
@@ -1,160 +1,160 @@
 #
 # OpenSSL/crypto/modes/Makefile
 #
 
 DIR=	modes
 TOP=	../..
 CC=	cc
 INCLUDES= -I.. -I$(TOP) -I../../include
 CFLAG=-g
 MAKEFILE=	Makefile
 AR=		ar r
 
 MODES_ASM_OBJ=
 
 CFLAGS= $(INCLUDES) $(CFLAG)
 ASFLAGS= $(INCLUDES) $(ASFLAG)
 AFLAGS= $(ASFLAGS)
 
 GENERAL=Makefile
 TEST=
 APPS=
 
 LIB=$(TOP)/libcrypto.a
 LIBSRC= cbc128.c ctr128.c cts128.c cfb128.c ofb128.c gcm128.c \
 	ccm128.c xts128.c wrap128.c
 LIBOBJ= cbc128.o ctr128.o cts128.o cfb128.o ofb128.o gcm128.o \
 	ccm128.o xts128.o wrap128.o $(MODES_ASM_OBJ)
 
 SRC= $(LIBSRC)
 
 #EXHEADER= store.h str_compat.h
 EXHEADER= modes.h
 HEADER=	modes_lcl.h $(EXHEADER)
 
 ALL=    $(GENERAL) $(SRC) $(HEADER)
 
 top:
 	(cd ../..; $(MAKE) DIRS=crypto SDIRS=$(DIR) sub_all)
 
 all:	lib
 
 lib:	$(LIBOBJ)
 	$(AR) $(LIB) $(LIBOBJ)
 	$(RANLIB) $(LIB) || echo Never mind.
 	@touch lib
 
 ghash-ia64.s:	asm/ghash-ia64.pl
 	$(PERL) asm/ghash-ia64.pl $@ $(CFLAGS)
 ghash-x86.s:	asm/ghash-x86.pl
 	$(PERL) asm/ghash-x86.pl $(PERLASM_SCHEME) $(CFLAGS) $(PROCESSOR) > $@
 ghash-x86_64.s:	asm/ghash-x86_64.pl
 	$(PERL) asm/ghash-x86_64.pl $(PERLASM_SCHEME) > $@
 aesni-gcm-x86_64.s:	asm/aesni-gcm-x86_64.pl
 	$(PERL) asm/aesni-gcm-x86_64.pl $(PERLASM_SCHEME) > $@
 ghash-sparcv9.s:	asm/ghash-sparcv9.pl
 	$(PERL) asm/ghash-sparcv9.pl $@ $(CFLAGS)
 ghash-alpha.s:	asm/ghash-alpha.pl
 	(preproc=$$$$.$@.S; trap "rm $$preproc" INT; \
 	$(PERL) asm/ghash-alpha.pl > $$preproc && \
 	$(CC) -E -P $$preproc > $@ && rm $$preproc)
 ghash-parisc.s:	asm/ghash-parisc.pl
 	$(PERL) asm/ghash-parisc.pl $(PERLASM_SCHEME) $@
 ghashv8-armx.S:	asm/ghashv8-armx.pl
 	$(PERL) asm/ghashv8-armx.pl $(PERLASM_SCHEME) $@
 ghashp8-ppc.s:	asm/ghashp8-ppc.pl
 	$(PERL) asm/ghashp8-ppc.pl $(PERLASM_SCHEME) $@
 
 # GNU make "catch all"
 ghash-%.S:	asm/ghash-%.pl;	$(PERL) $< $(PERLASM_SCHEME) $@
 
 ghash-armv4.o:	ghash-armv4.S
 ghashv8-armx.o:	ghashv8-armx.S
 
 files:
 	$(PERL) $(TOP)/util/files.pl Makefile >> $(TOP)/MINFO
 
 links:
 	@$(PERL) $(TOP)/util/mklink.pl ../../include/openssl $(EXHEADER)
 	@$(PERL) $(TOP)/util/mklink.pl ../../test $(TEST)
 	@$(PERL) $(TOP)/util/mklink.pl ../../apps $(APPS)
 
 install:
 	@[ -n "$(INSTALLTOP)" ] # should be set by top Makefile...
 	@headerlist="$(EXHEADER)"; for i in $$headerlist; \
 	do  \
 	(cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i; \
 	chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i ); \
 	done;
 
 tags:
 	ctags $(SRC)
 
 tests:
 
 lint:
 	lint -DLINT $(INCLUDES) $(SRC)>fluff
 
 update: depend
 
 depend:
 	@[ -n "$(MAKEDEPEND)" ] # should be set by upper Makefile...
 	$(MAKEDEPEND) -- $(CFLAG) $(INCLUDES) $(DEPFLAG) -- $(PROGS) $(LIBSRC)
 
 dclean:
 	$(PERL) -pe 'if (/^# DO NOT DELETE THIS LINE/) {print; exit(0);}' $(MAKEFILE) >Makefile.new
 	mv -f Makefile.new $(MAKEFILE)
 
 clean:
-	rm -f *.s *.o */*.o *.obj lib tags core .pure .nfs* *.old *.bak fluff
+	rm -f *.s *.S *.o */*.o *.obj lib tags core .pure .nfs* *.old *.bak fluff
 
 # DO NOT DELETE THIS LINE -- make depend depends on it.
 
 cbc128.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
 cbc128.o: ../../include/openssl/modes.h ../../include/openssl/opensslconf.h
 cbc128.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 cbc128.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 cbc128.o: ../../include/openssl/symhacks.h cbc128.c modes_lcl.h
 ccm128.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
 ccm128.o: ../../include/openssl/modes.h ../../include/openssl/opensslconf.h
 ccm128.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 ccm128.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 ccm128.o: ../../include/openssl/symhacks.h ccm128.c modes_lcl.h
 cfb128.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
 cfb128.o: ../../include/openssl/modes.h ../../include/openssl/opensslconf.h
 cfb128.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 cfb128.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 cfb128.o: ../../include/openssl/symhacks.h cfb128.c modes_lcl.h
 ctr128.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
 ctr128.o: ../../include/openssl/modes.h ../../include/openssl/opensslconf.h
 ctr128.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 ctr128.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 ctr128.o: ../../include/openssl/symhacks.h ctr128.c modes_lcl.h
 cts128.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
 cts128.o: ../../include/openssl/modes.h ../../include/openssl/opensslconf.h
 cts128.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 cts128.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 cts128.o: ../../include/openssl/symhacks.h cts128.c modes_lcl.h
 gcm128.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
 gcm128.o: ../../include/openssl/modes.h ../../include/openssl/opensslconf.h
 gcm128.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 gcm128.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 gcm128.o: ../../include/openssl/symhacks.h gcm128.c modes_lcl.h
 ofb128.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
 ofb128.o: ../../include/openssl/modes.h ../../include/openssl/opensslconf.h
 ofb128.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 ofb128.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 ofb128.o: ../../include/openssl/symhacks.h modes_lcl.h ofb128.c
 wrap128.o: ../../e_os.h ../../include/openssl/bio.h
 wrap128.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 wrap128.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 wrap128.o: ../../include/openssl/lhash.h ../../include/openssl/modes.h
 wrap128.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h
 wrap128.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h
 wrap128.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 wrap128.o: ../cryptlib.h wrap128.c
 xts128.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
 xts128.o: ../../include/openssl/modes.h ../../include/openssl/opensslconf.h
 xts128.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 xts128.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 xts128.o: ../../include/openssl/symhacks.h modes_lcl.h xts128.c
Index: vendor-crypto/openssl/dist/crypto/o_dir.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/o_dir.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/o_dir.c	(revision 318897)
@@ -1,86 +1,87 @@
 /* crypto/o_dir.c */
 /*
  * Written by Richard Levitte (richard@levitte.org) for the OpenSSL project
  * 2004.
  */
 /* ====================================================================
  * Copyright (c) 2004 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    openssl-core@openssl.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #include 
 #include 
 
 /*
  * The routines really come from the Levitte Programming, so to make life
  * simple, let's just use the raw files and hack the symbols to fit our
  * namespace.
  */
 #define LP_DIR_CTX OPENSSL_DIR_CTX
 #define LP_dir_context_st OPENSSL_dir_context_st
 #define LP_find_file OPENSSL_DIR_read
 #define LP_find_file_end OPENSSL_DIR_end
 
 #include "o_dir.h"
 
 #define LPDIR_H
-#if defined OPENSSL_SYS_UNIX || defined DJGPP
+#if defined OPENSSL_SYS_UNIX || defined DJGPP \
+    || (defined __VMS_VER && __VMS_VER >= 70000000)
 # include "LPdir_unix.c"
 #elif defined OPENSSL_SYS_VMS
 # include "LPdir_vms.c"
 #elif defined OPENSSL_SYS_WIN32
 # include "LPdir_win32.c"
 #elif defined OPENSSL_SYS_WINCE
 # include "LPdir_wince.c"
 #else
 # include "LPdir_nyi.c"
 #endif
Index: vendor-crypto/openssl/dist/crypto/o_time.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/o_time.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/o_time.c	(revision 318897)
@@ -1,477 +1,474 @@
 /* crypto/o_time.c */
 /*
  * Written by Richard Levitte (richard@levitte.org) for the OpenSSL project
  * 2001.
  */
 /*
  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
  * 2008.
  */
 /* ====================================================================
  * Copyright (c) 2001 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    licensing@OpenSSL.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #include 
 #include 
 #include "o_time.h"
 
 #ifdef OPENSSL_SYS_VMS
 # if __CRTL_VER >= 70000000 && \
      (defined _POSIX_C_SOURCE || !defined _ANSI_C_SOURCE)
 #  define VMS_GMTIME_OK
 # endif
 # ifndef VMS_GMTIME_OK
 #  include 
 #  include 
 #  include 
 #  include 
 #  include 
 #  include 
 # endif                         /* ndef VMS_GMTIME_OK */
 
 
 /*
  * Needed to pick up the correct definitions and declarations in some of the
  * DEC C Header Files (*.H).
  */
 # define __NEW_STARLET 1
 
 # if (defined(__alpha) || defined(__ia64))
 #  include 
 # else
 
 /* VAX */
 typedef struct _ile3 {          /* Copied from ILEDEF.H for Alpha   */
 #  pragma __nomember_alignment
     unsigned short int ile3$w_length;        /* Length of buffer in bytes */
     unsigned short int ile3$w_code;          /* Item code value */
     void *ile3$ps_bufaddr;                   /* Buffer address */
     unsigned short int *ile3$ps_retlen_addr; /* Address of word for returned length */
 } ILE3;
 # endif   /* alpha || ia64    */
 #endif    /* OPENSSL_SYS_VMS  */
 
 struct tm *OPENSSL_gmtime(const time_t *timer, struct tm *result)
 {
     struct tm *ts = NULL;
 
 #if defined(OPENSSL_THREADS) && !defined(OPENSSL_SYS_WIN32) && !defined(OPENSSL_SYS_OS2) && (!defined(OPENSSL_SYS_VMS) || defined(gmtime_r)) && !defined(OPENSSL_SYS_MACOSX) && !defined(OPENSSL_SYS_SUNOS)
-    /*
-     * should return &data, but doesn't on some systems, so we don't even
-     * look at the return value
-     */
-    gmtime_r(timer, result);
+    if (gmtime_r(timer, result) == NULL)
+        return NULL;
     ts = result;
 #elif !defined(OPENSSL_SYS_VMS) || defined(VMS_GMTIME_OK)
     ts = gmtime(timer);
     if (ts == NULL)
         return NULL;
 
     memcpy(result, ts, sizeof(struct tm));
     ts = result;
 #endif
 #if defined( OPENSSL_SYS_VMS) && !defined( VMS_GMTIME_OK)
     if (ts == NULL) {
         static $DESCRIPTOR(tabnam, "LNM$DCL_LOGICAL");
         static $DESCRIPTOR(lognam, "SYS$TIMEZONE_DIFFERENTIAL");
         char logvalue[256];
         unsigned int reslen = 0;
 # if __INITIAL_POINTER_SIZE == 64
         ILEB_64 itemlist[2], *pitem;
 # else
         ILE3 itemlist[2], *pitem;
 # endif
         int status;
         time_t t;
 
 
         /*
          * Setup an itemlist for the call to $TRNLNM - Translate Logical Name.
          */
         pitem = itemlist;
 
 # if __INITIAL_POINTER_SIZE == 64
         pitem->ileb_64$w_mbo = 1;
         pitem->ileb_64$w_code = LNM$_STRING;
         pitem->ileb_64$l_mbmo = -1;
         pitem->ileb_64$q_length = sizeof (logvalue);
         pitem->ileb_64$pq_bufaddr = logvalue;
         pitem->ileb_64$pq_retlen_addr = (unsigned __int64 *) &reslen;
         pitem++;
         /* Last item of the item list is null terminated */
         pitem->ileb_64$q_length = pitem->ileb_64$w_code = 0;
 # else
         pitem->ile3$w_length = sizeof (logvalue);
         pitem->ile3$w_code = LNM$_STRING;
         pitem->ile3$ps_bufaddr = logvalue;
         pitem->ile3$ps_retlen_addr = (unsigned short int *) &reslen;
         pitem++;
         /* Last item of the item list is null terminated */
         pitem->ile3$w_length = pitem->ile3$w_code = 0;
 # endif
 
 
         /* Get the value for SYS$TIMEZONE_DIFFERENTIAL */
         status = sys$trnlnm(0, &tabnam, &lognam, 0, itemlist);
         if (!(status & 1))
             return NULL;
         logvalue[reslen] = '\0';
 
         t = *timer;
 
         /* The following is extracted from the DEC C header time.h */
         /*
          **  Beginning in OpenVMS Version 7.0 mktime, time, ctime, strftime
          **  have two implementations.  One implementation is provided
          **  for compatibility and deals with time in terms of local time,
          **  the other __utc_* deals with time in terms of UTC.
          */
         /*
          * We use the same conditions as in said time.h to check if we should
          * assume that t contains local time (and should therefore be
          * adjusted) or UTC (and should therefore be left untouched).
          */
 # if __CRTL_VER < 70000000 || defined _VMS_V6_SOURCE
         /* Get the numerical value of the equivalence string */
         status = atoi(logvalue);
 
         /* and use it to move time to GMT */
         t -= status;
 # endif
 
         /* then convert the result to the time structure */
 
         /*
          * Since there was no gmtime_r() to do this stuff for us, we have to
          * do it the hard way.
          */
         {
             /*-
              * The VMS epoch is the astronomical Smithsonian date,
                if I remember correctly, which is November 17, 1858.
                Furthermore, time is measure in thenths of microseconds
                and stored in quadwords (64 bit integers).  unix_epoch
                below is January 1st 1970 expressed as a VMS time.  The
                following code was used to get this number:
 
                #include 
                #include 
                #include 
                #include 
 
                main()
                {
                  unsigned long systime[2];
                  unsigned short epoch_values[7] =
                    { 1970, 1, 1, 0, 0, 0, 0 };
 
                  lib$cvt_vectim(epoch_values, systime);
 
                  printf("%u %u", systime[0], systime[1]);
                }
             */
             unsigned long unix_epoch[2] = { 1273708544, 8164711 };
             unsigned long deltatime[2];
             unsigned long systime[2];
             struct vms_vectime {
                 short year, month, day, hour, minute, second, centi_second;
             } time_values;
             long operation;
 
             /*
              * Turn the number of seconds since January 1st 1970 to an
              * internal delta time. Note that lib$cvt_to_internal_time() will
              * assume that t is signed, and will therefore break on 32-bit
              * systems some time in 2038.
              */
             operation = LIB$K_DELTA_SECONDS;
             status = lib$cvt_to_internal_time(&operation, &t, deltatime);
 
             /*
              * Add the delta time with the Unix epoch and we have the current
              * UTC time in internal format
              */
             status = lib$add_times(unix_epoch, deltatime, systime);
 
             /* Turn the internal time into a time vector */
             status = sys$numtim(&time_values, systime);
 
             /* Fill in the struct tm with the result */
             result->tm_sec = time_values.second;
             result->tm_min = time_values.minute;
             result->tm_hour = time_values.hour;
             result->tm_mday = time_values.day;
             result->tm_mon = time_values.month - 1;
             result->tm_year = time_values.year - 1900;
 
             operation = LIB$K_DAY_OF_WEEK;
             status = lib$cvt_from_internal_time(&operation,
                                                 &result->tm_wday, systime);
             result->tm_wday %= 7;
 
             operation = LIB$K_DAY_OF_YEAR;
             status = lib$cvt_from_internal_time(&operation,
                                                 &result->tm_yday, systime);
             result->tm_yday--;
 
             result->tm_isdst = 0; /* There's no way to know... */
 
             ts = result;
         }
     }
 #endif
     return ts;
 }
 
 /*
  * Take a tm structure and add an offset to it. This avoids any OS issues
  * with restricted date types and overflows which cause the year 2038
  * problem.
  */
 
 #define SECS_PER_DAY (24 * 60 * 60)
 
 static long date_to_julian(int y, int m, int d);
 static void julian_to_date(long jd, int *y, int *m, int *d);
 static int julian_adj(const struct tm *tm, int off_day, long offset_sec,
                       long *pday, int *psec);
 
 int OPENSSL_gmtime_adj(struct tm *tm, int off_day, long offset_sec)
 {
     int time_sec, time_year, time_month, time_day;
     long time_jd;
 
     /* Convert time and offset into julian day and seconds */
     if (!julian_adj(tm, off_day, offset_sec, &time_jd, &time_sec))
         return 0;
 
     /* Convert Julian day back to date */
 
     julian_to_date(time_jd, &time_year, &time_month, &time_day);
 
     if (time_year < 1900 || time_year > 9999)
         return 0;
 
     /* Update tm structure */
 
     tm->tm_year = time_year - 1900;
     tm->tm_mon = time_month - 1;
     tm->tm_mday = time_day;
 
     tm->tm_hour = time_sec / 3600;
     tm->tm_min = (time_sec / 60) % 60;
     tm->tm_sec = time_sec % 60;
 
     return 1;
 
 }
 
 int OPENSSL_gmtime_diff(int *pday, int *psec,
                         const struct tm *from, const struct tm *to)
 {
     int from_sec, to_sec, diff_sec;
     long from_jd, to_jd, diff_day;
     if (!julian_adj(from, 0, 0, &from_jd, &from_sec))
         return 0;
     if (!julian_adj(to, 0, 0, &to_jd, &to_sec))
         return 0;
     diff_day = to_jd - from_jd;
     diff_sec = to_sec - from_sec;
     /* Adjust differences so both positive or both negative */
     if (diff_day > 0 && diff_sec < 0) {
         diff_day--;
         diff_sec += SECS_PER_DAY;
     }
     if (diff_day < 0 && diff_sec > 0) {
         diff_day++;
         diff_sec -= SECS_PER_DAY;
     }
 
     if (pday)
         *pday = (int)diff_day;
     if (psec)
         *psec = diff_sec;
 
     return 1;
 
 }
 
 /* Convert tm structure and offset into julian day and seconds */
 static int julian_adj(const struct tm *tm, int off_day, long offset_sec,
                       long *pday, int *psec)
 {
     int offset_hms, offset_day;
     long time_jd;
     int time_year, time_month, time_day;
     /* split offset into days and day seconds */
     offset_day = offset_sec / SECS_PER_DAY;
     /* Avoid sign issues with % operator */
     offset_hms = offset_sec - (offset_day * SECS_PER_DAY);
     offset_day += off_day;
     /* Add current time seconds to offset */
     offset_hms += tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
     /* Adjust day seconds if overflow */
     if (offset_hms >= SECS_PER_DAY) {
         offset_day++;
         offset_hms -= SECS_PER_DAY;
     } else if (offset_hms < 0) {
         offset_day--;
         offset_hms += SECS_PER_DAY;
     }
 
     /*
      * Convert date of time structure into a Julian day number.
      */
 
     time_year = tm->tm_year + 1900;
     time_month = tm->tm_mon + 1;
     time_day = tm->tm_mday;
 
     time_jd = date_to_julian(time_year, time_month, time_day);
 
     /* Work out Julian day of new date */
     time_jd += offset_day;
 
     if (time_jd < 0)
         return 0;
 
     *pday = time_jd;
     *psec = offset_hms;
     return 1;
 }
 
 /*
  * Convert date to and from julian day Uses Fliegel & Van Flandern algorithm
  */
 static long date_to_julian(int y, int m, int d)
 {
     return (1461 * (y + 4800 + (m - 14) / 12)) / 4 +
         (367 * (m - 2 - 12 * ((m - 14) / 12))) / 12 -
         (3 * ((y + 4900 + (m - 14) / 12) / 100)) / 4 + d - 32075;
 }
 
 static void julian_to_date(long jd, int *y, int *m, int *d)
 {
     long L = jd + 68569;
     long n = (4 * L) / 146097;
     long i, j;
 
     L = L - (146097 * n + 3) / 4;
     i = (4000 * (L + 1)) / 1461001;
     L = L - (1461 * i) / 4 + 31;
     j = (80 * L) / 2447;
     *d = L - (2447 * j) / 80;
     L = j / 11;
     *m = j + 2 - (12 * L);
     *y = 100 * (n - 49) + i + L;
 }
 
 #ifdef OPENSSL_TIME_TEST
 
 # include 
 
 /*
  * Time checking test code. Check times are identical for a wide range of
  * offsets. This should be run on a machine with 64 bit time_t or it will
  * trigger the very errors the routines fix.
  */
 
 int main(int argc, char **argv)
 {
     long offset;
     for (offset = 0; offset < 1000000; offset++) {
         check_time(offset);
         check_time(-offset);
         check_time(offset * 1000);
         check_time(-offset * 1000);
     }
 }
 
 int check_time(long offset)
 {
     struct tm tm1, tm2, o1;
     int off_day, off_sec;
     long toffset;
     time_t t1, t2;
     time(&t1);
     t2 = t1 + offset;
     OPENSSL_gmtime(&t2, &tm2);
     OPENSSL_gmtime(&t1, &tm1);
     o1 = tm1;
     OPENSSL_gmtime_adj(&tm1, 0, offset);
     if ((tm1.tm_year != tm2.tm_year) ||
         (tm1.tm_mon != tm2.tm_mon) ||
         (tm1.tm_mday != tm2.tm_mday) ||
         (tm1.tm_hour != tm2.tm_hour) ||
         (tm1.tm_min != tm2.tm_min) || (tm1.tm_sec != tm2.tm_sec)) {
         fprintf(stderr, "TIME ERROR!!\n");
         fprintf(stderr, "Time1: %d/%d/%d, %d:%02d:%02d\n",
                 tm2.tm_mday, tm2.tm_mon + 1, tm2.tm_year + 1900,
                 tm2.tm_hour, tm2.tm_min, tm2.tm_sec);
         fprintf(stderr, "Time2: %d/%d/%d, %d:%02d:%02d\n",
                 tm1.tm_mday, tm1.tm_mon + 1, tm1.tm_year + 1900,
                 tm1.tm_hour, tm1.tm_min, tm1.tm_sec);
         return 0;
     }
     OPENSSL_gmtime_diff(&o1, &tm1, &off_day, &off_sec);
     toffset = (long)off_day *SECS_PER_DAY + off_sec;
     if (offset != toffset) {
         fprintf(stderr, "TIME OFFSET ERROR!!\n");
         fprintf(stderr, "Expected %ld, Got %ld (%d:%d)\n",
                 offset, toffset, off_day, off_sec);
         return 0;
     }
     return 1;
 }
 
 #endif
Index: vendor-crypto/openssl/dist/crypto/opensslv.h
===================================================================
--- vendor-crypto/openssl/dist/crypto/opensslv.h	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/opensslv.h	(revision 318897)
@@ -1,97 +1,97 @@
 #ifndef HEADER_OPENSSLV_H
 # define HEADER_OPENSSLV_H
 
 #ifdef  __cplusplus
 extern "C" {
 #endif
 
 /*-
  * Numeric release version identifier:
  * MNNFFPPS: major minor fix patch status
  * The status nibble has one of the values 0 for development, 1 to e for betas
  * 1 to 14, and f for release.  The patch level is exactly that.
  * For example:
  * 0.9.3-dev      0x00903000
  * 0.9.3-beta1    0x00903001
  * 0.9.3-beta2-dev 0x00903002
  * 0.9.3-beta2    0x00903002 (same as ...beta2-dev)
  * 0.9.3          0x0090300f
  * 0.9.3a         0x0090301f
  * 0.9.4          0x0090400f
  * 1.2.3z         0x102031af
  *
  * For continuity reasons (because 0.9.5 is already out, and is coded
  * 0x00905100), between 0.9.5 and 0.9.6 the coding of the patch level
  * part is slightly different, by setting the highest bit.  This means
  * that 0.9.5a looks like this: 0x0090581f.  At 0.9.6, we can start
  * with 0x0090600S...
  *
  * (Prior to 0.9.3-dev a different scheme was used: 0.9.2b is 0x0922.)
  * (Prior to 0.9.5a beta1, a different scheme was used: MMNNFFRBB for
  *  major minor fix final patch/beta)
  */
-# define OPENSSL_VERSION_NUMBER  0x100020bfL
+# define OPENSSL_VERSION_NUMBER  0x100020cfL
 # ifdef OPENSSL_FIPS
-#  define OPENSSL_VERSION_TEXT    "OpenSSL 1.0.2k-fips  26 Jan 2017"
+#  define OPENSSL_VERSION_TEXT    "OpenSSL 1.0.2l-fips  25 May 2017"
 # else
-#  define OPENSSL_VERSION_TEXT    "OpenSSL 1.0.2k  26 Jan 2017"
+#  define OPENSSL_VERSION_TEXT    "OpenSSL 1.0.2l  25 May 2017"
 # endif
 # define OPENSSL_VERSION_PTEXT   " part of " OPENSSL_VERSION_TEXT
 
 /*-
  * The macros below are to be used for shared library (.so, .dll, ...)
  * versioning.  That kind of versioning works a bit differently between
  * operating systems.  The most usual scheme is to set a major and a minor
  * number, and have the runtime loader check that the major number is equal
  * to what it was at application link time, while the minor number has to
  * be greater or equal to what it was at application link time.  With this
  * scheme, the version number is usually part of the file name, like this:
  *
  *      libcrypto.so.0.9
  *
  * Some unixen also make a softlink with the major verson number only:
  *
  *      libcrypto.so.0
  *
  * On Tru64 and IRIX 6.x it works a little bit differently.  There, the
  * shared library version is stored in the file, and is actually a series
  * of versions, separated by colons.  The rightmost version present in the
  * library when linking an application is stored in the application to be
  * matched at run time.  When the application is run, a check is done to
  * see if the library version stored in the application matches any of the
  * versions in the version string of the library itself.
  * This version string can be constructed in any way, depending on what
  * kind of matching is desired.  However, to implement the same scheme as
  * the one used in the other unixen, all compatible versions, from lowest
  * to highest, should be part of the string.  Consecutive builds would
  * give the following versions strings:
  *
  *      3.0
  *      3.0:3.1
  *      3.0:3.1:3.2
  *      4.0
  *      4.0:4.1
  *
  * Notice how version 4 is completely incompatible with version, and
  * therefore give the breach you can see.
  *
  * There may be other schemes as well that I haven't yet discovered.
  *
  * So, here's the way it works here: first of all, the library version
  * number doesn't need at all to match the overall OpenSSL version.
  * However, it's nice and more understandable if it actually does.
  * The current library version is stored in the macro SHLIB_VERSION_NUMBER,
  * which is just a piece of text in the format "M.m.e" (Major, minor, edit).
  * For the sake of Tru64, IRIX, and any other OS that behaves in similar ways,
  * we need to keep a history of version numbers, which is done in the
  * macro SHLIB_VERSION_HISTORY.  The numbers are separated by colons and
  * should only keep the versions that are binary compatible with the current.
  */
 # define SHLIB_VERSION_HISTORY ""
 # define SHLIB_VERSION_NUMBER "1.0.0"
 
 
 #ifdef  __cplusplus
 }
 #endif
 #endif                          /* HEADER_OPENSSLV_H */
Index: vendor-crypto/openssl/dist/crypto/perlasm/x86_64-xlate.pl
===================================================================
--- vendor-crypto/openssl/dist/crypto/perlasm/x86_64-xlate.pl	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/perlasm/x86_64-xlate.pl	(revision 318897)
@@ -1,1158 +1,1159 @@
 #!/usr/bin/env perl
 
 # Ascetic x86_64 AT&T to MASM/NASM assembler translator by .
 #
 # Why AT&T to MASM and not vice versa? Several reasons. Because AT&T
 # format is way easier to parse. Because it's simpler to "gear" from
 # Unix ABI to Windows one [see cross-reference "card" at the end of
 # file]. Because Linux targets were available first...
 #
 # In addition the script also "distills" code suitable for GNU
 # assembler, so that it can be compiled with more rigid assemblers,
 # such as Solaris /usr/ccs/bin/as.
 #
 # This translator is not designed to convert *arbitrary* assembler
 # code from AT&T format to MASM one. It's designed to convert just
 # enough to provide for dual-ABI OpenSSL modules development...
 # There *are* limitations and you might have to modify your assembler
 # code or this script to achieve the desired result...
 #
 # Currently recognized limitations:
 #
 # - can't use multiple ops per line;
 #
 # Dual-ABI styling rules.
 #
 # 1. Adhere to Unix register and stack layout [see cross-reference
 #    ABI "card" at the end for explanation].
 # 2. Forget about "red zone," stick to more traditional blended
 #    stack frame allocation. If volatile storage is actually required
 #    that is. If not, just leave the stack as is.
 # 3. Functions tagged with ".type name,@function" get crafted with
 #    unified Win64 prologue and epilogue automatically. If you want
 #    to take care of ABI differences yourself, tag functions as
 #    ".type name,@abi-omnipotent" instead.
 # 4. To optimize the Win64 prologue you can specify number of input
 #    arguments as ".type name,@function,N." Keep in mind that if N is
 #    larger than 6, then you *have to* write "abi-omnipotent" code,
 #    because >6 cases can't be addressed with unified prologue.
 # 5. Name local labels as .L*, do *not* use dynamic labels such as 1:
 #    (sorry about latter).
 # 6. Don't use [or hand-code with .byte] "rep ret." "ret" mnemonic is
 #    required to identify the spots, where to inject Win64 epilogue!
 #    But on the pros, it's then prefixed with rep automatically:-)
 # 7. Stick to explicit ip-relative addressing. If you have to use
 #    GOTPCREL addressing, stick to mov symbol@GOTPCREL(%rip),%r??.
 #    Both are recognized and translated to proper Win64 addressing
 #    modes. To support legacy code a synthetic directive, .picmeup,
 #    is implemented. It puts address of the *next* instruction into
 #    target register, e.g.:
 #
 #		.picmeup	%rax
 #		lea		.Label-.(%rax),%rax
 #
 # 8. In order to provide for structured exception handling unified
 #    Win64 prologue copies %rsp value to %rax. For further details
 #    see SEH paragraph at the end.
 # 9. .init segment is allowed to contain calls to functions only.
 # a. If function accepts more than 4 arguments *and* >4th argument
 #    is declared as non 64-bit value, do clear its upper part.
 
 my $flavour = shift;
 my $output  = shift;
 if ($flavour =~ /\./) { $output = $flavour; undef $flavour; }
 
 open STDOUT,">$output" || die "can't open $output: $!"
 	if (defined($output));
 
 my $gas=1;	$gas=0 if ($output =~ /\.asm$/);
 my $elf=1;	$elf=0 if (!$gas);
 my $win64=0;
 my $prefix="";
 my $decor=".L";
 
 my $masmref=8 + 50727*2**-32;	# 8.00.50727 shipped with VS2005
 my $masm=0;
 my $PTR=" PTR";
 
 my $nasmref=2.03;
 my $nasm=0;
 
 if    ($flavour eq "mingw64")	{ $gas=1; $elf=0; $win64=1;
 				  $prefix=`echo __USER_LABEL_PREFIX__ | $ENV{CC} -E -P -`;
 				  chomp($prefix);
 				}
 elsif ($flavour eq "macosx")	{ $gas=1; $elf=0; $prefix="_"; $decor="L\$"; }
 elsif ($flavour eq "masm")	{ $gas=0; $elf=0; $masm=$masmref; $win64=1; $decor="\$L\$"; }
 elsif ($flavour eq "nasm")	{ $gas=0; $elf=0; $nasm=$nasmref; $win64=1; $decor="\$L\$"; $PTR=""; }
 elsif (!$gas)
 {   if ($ENV{ASM} =~ m/nasm/ && `nasm -v` =~ m/version ([0-9]+)\.([0-9]+)/i)
     {	$nasm = $1 + $2*0.01; $PTR="";  }
     elsif (`ml64 2>&1` =~ m/Version ([0-9]+)\.([0-9]+)(\.([0-9]+))?/)
     {	$masm = $1 + $2*2**-16 + $4*2**-32;   }
     die "no assembler found on %PATH" if (!($nasm || $masm));
     $win64=1;
     $elf=0;
     $decor="\$L\$";
 }
 
 my $current_segment;
 my $current_function;
 my %globals;
 
 { package opcode;	# pick up opcodes
     sub re {
 	my	$self = shift;	# single instance in enough...
 	local	*line = shift;
 	undef	$ret;
 
 	if ($line =~ /^([a-z][a-z0-9]*)/i) {
 	    $self->{op} = $1;
 	    $ret = $self;
 	    $line = substr($line,@+[0]); $line =~ s/^\s+//;
 
 	    undef $self->{sz};
 	    if ($self->{op} =~ /^(movz)x?([bw]).*/) {	# movz is pain...
 		$self->{op} = $1;
 		$self->{sz} = $2;
 	    } elsif ($self->{op} =~ /call|jmp/) {
 		$self->{sz} = "";
 	    } elsif ($self->{op} =~ /^p/ && $' !~ /^(ush|op|insrw)/) { # SSEn
 		$self->{sz} = "";
 	    } elsif ($self->{op} =~ /^v/) { # VEX
 		$self->{sz} = "";
 	    } elsif ($self->{op} =~ /mov[dq]/ && $line =~ /%xmm/) {
 		$self->{sz} = "";
 	    } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])$/) {
 		$self->{op} = $1;
 		$self->{sz} = $2;
 	    }
 	}
 	$ret;
     }
     sub size {
 	my $self = shift;
 	my $sz   = shift;
 	$self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
 	$self->{sz};
     }
     sub out {
 	my $self = shift;
 	if ($gas) {
 	    if ($self->{op} eq "movz") {	# movz is pain...
 		sprintf "%s%s%s",$self->{op},$self->{sz},shift;
 	    } elsif ($self->{op} =~ /^set/) { 
 		"$self->{op}";
 	    } elsif ($self->{op} eq "ret") {
 		my $epilogue = "";
 		if ($win64 && $current_function->{abi} eq "svr4") {
 		    $epilogue = "movq	8(%rsp),%rdi\n\t" .
 				"movq	16(%rsp),%rsi\n\t";
 		}
 	    	$epilogue . ".byte	0xf3,0xc3";
 	    } elsif ($self->{op} eq "call" && !$elf && $current_segment eq ".init") {
 		".p2align\t3\n\t.quad";
 	    } else {
 		"$self->{op}$self->{sz}";
 	    }
 	} else {
 	    $self->{op} =~ s/^movz/movzx/;
 	    if ($self->{op} eq "ret") {
 		$self->{op} = "";
 		if ($win64 && $current_function->{abi} eq "svr4") {
 		    $self->{op} = "mov	rdi,QWORD${PTR}[8+rsp]\t;WIN64 epilogue\n\t".
 				  "mov	rsi,QWORD${PTR}[16+rsp]\n\t";
 	    	}
 		$self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
 	    } elsif ($self->{op} =~ /^(pop|push)f/) {
 		$self->{op} .= $self->{sz};
 	    } elsif ($self->{op} eq "call" && $current_segment eq ".CRT\$XCU") {
 		$self->{op} = "\tDQ";
 	    } 
 	    $self->{op};
 	}
     }
     sub mnemonic {
 	my $self=shift;
 	my $op=shift;
 	$self->{op}=$op if (defined($op));
 	$self->{op};
     }
 }
 { package const;	# pick up constants, which start with $
     sub re {
 	my	$self = shift;	# single instance in enough...
 	local	*line = shift;
 	undef	$ret;
 
 	if ($line =~ /^\$([^,]+)/) {
 	    $self->{value} = $1;
 	    $ret = $self;
 	    $line = substr($line,@+[0]); $line =~ s/^\s+//;
 	}
 	$ret;
     }
     sub out {
     	my $self = shift;
 
 	$self->{value} =~ s/\b(0b[0-1]+)/oct($1)/eig;
 	if ($gas) {
 	    # Solaris /usr/ccs/bin/as can't handle multiplications
 	    # in $self->{value}
 	    my $value = $self->{value};
 	    $value =~ s/(?{value} = $value;
 	    }
 	    sprintf "\$%s",$self->{value};
 	} else {
-	    $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig if ($masm);
-	    sprintf "%s",$self->{value};
+	    my $value = $self->{value};
+	    $value =~ s/0x([0-9a-f]+)/0$1h/ig if ($masm);
+	    sprintf "%s",$value;
 	}
     }
 }
 { package ea;		# pick up effective addresses: expr(%reg,%reg,scale)
     sub re {
 	my	$self = shift;	# single instance in enough...
 	local	*line = shift;
 	undef	$ret;
 
 	# optional * ---vvv--- appears in indirect jmp/call
 	if ($line =~ /^(\*?)([^\(,]*)\(([%\w,]+)\)/) {
 	    $self->{asterisk} = $1;
 	    $self->{label} = $2;
 	    ($self->{base},$self->{index},$self->{scale})=split(/,/,$3);
 	    $self->{scale} = 1 if (!defined($self->{scale}));
 	    $ret = $self;
 	    $line = substr($line,@+[0]); $line =~ s/^\s+//;
 
 	    if ($win64 && $self->{label} =~ s/\@GOTPCREL//) {
 		die if (opcode->mnemonic() ne "mov");
 		opcode->mnemonic("lea");
 	    }
 	    $self->{base}  =~ s/^%//;
 	    $self->{index} =~ s/^%// if (defined($self->{index}));
 	}
 	$ret;
     }
     sub size {}
     sub out {
     	my $self = shift;
 	my $sz = shift;
 
 	$self->{label} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
 	$self->{label} =~ s/\.L/$decor/g;
 
 	# Silently convert all EAs to 64-bit. This is required for
 	# elder GNU assembler and results in more compact code,
 	# *but* most importantly AES module depends on this feature!
 	$self->{index} =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
 	$self->{base}  =~ s/^[er](.?[0-9xpi])[d]?$/r\1/;
 
 	# Solaris /usr/ccs/bin/as can't handle multiplications
 	# in $self->{label}...
 	use integer;
 	$self->{label} =~ s/(?{label} =~ s/\b([0-9]+\s*[\*\/\%]\s*[0-9]+)\b/eval($1)/eg;
 
 	# Some assemblers insist on signed presentation of 32-bit
 	# offsets, but sign extension is a tricky business in perl...
 	if ((1<<31)<<1) {
 	    $self->{label} =~ s/\b([0-9]+)\b/$1<<32>>32/eg;
 	} else {
 	    $self->{label} =~ s/\b([0-9]+)\b/$1>>0/eg;
 	}
 
 	if (!$self->{label} && $self->{index} && $self->{scale}==1 &&
 	    $self->{base} =~ /(rbp|r13)/) {
 		$self->{base} = $self->{index}; $self->{index} = $1;
 	}
 
 	if ($gas) {
 	    $self->{label} =~ s/^___imp_/__imp__/   if ($flavour eq "mingw64");
 
 	    if (defined($self->{index})) {
 		sprintf "%s%s(%s,%%%s,%d)",$self->{asterisk},
 					$self->{label},
 					$self->{base}?"%$self->{base}":"",
 					$self->{index},$self->{scale};
 	    } else {
 		sprintf "%s%s(%%%s)",	$self->{asterisk},$self->{label},$self->{base};
 	    }
 	} else {
 	    %szmap = (	b=>"BYTE$PTR",  w=>"WORD$PTR",
 			l=>"DWORD$PTR", d=>"DWORD$PTR",
 	    		q=>"QWORD$PTR", o=>"OWORD$PTR",
 			x=>"XMMWORD$PTR", y=>"YMMWORD$PTR", z=>"ZMMWORD$PTR" );
 
 	    $self->{label} =~ s/\./\$/g;
 	    $self->{label} =~ s/(?{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
 
 	    ($self->{asterisk})					&& ($sz="q") ||
 	    (opcode->mnemonic() =~ /^v?mov([qd])$/)		&& ($sz=$1)  ||
 	    (opcode->mnemonic() =~ /^v?pinsr([qdwb])$/)		&& ($sz=$1)  ||
 	    (opcode->mnemonic() =~ /^vpbroadcast([qdwb])$/)	&& ($sz=$1)  ||
 	    (opcode->mnemonic() =~ /^vinsert[fi]128$/)		&& ($sz="x");
 
 	    if (defined($self->{index})) {
 		sprintf "%s[%s%s*%d%s]",$szmap{$sz},
 					$self->{label}?"$self->{label}+":"",
 					$self->{index},$self->{scale},
 					$self->{base}?"+$self->{base}":"";
 	    } elsif ($self->{base} eq "rip") {
 		sprintf "%s[%s]",$szmap{$sz},$self->{label};
 	    } else {
 		sprintf "%s[%s%s]",$szmap{$sz},
 					$self->{label}?"$self->{label}+":"",
 					$self->{base};
 	    }
 	}
     }
 }
 { package register;	# pick up registers, which start with %.
     sub re {
 	my	$class = shift;	# muliple instances...
 	my	$self = {};
 	local	*line = shift;
 	undef	$ret;
 
 	# optional * ---vvv--- appears in indirect jmp/call
 	if ($line =~ /^(\*?)%(\w+)/) {
 	    bless $self,$class;
 	    $self->{asterisk} = $1;
 	    $self->{value} = $2;
 	    $ret = $self;
 	    $line = substr($line,@+[0]); $line =~ s/^\s+//;
 	}
 	$ret;
     }
     sub size {
 	my	$self = shift;
 	undef	$ret;
 
 	if    ($self->{value} =~ /^r[\d]+b$/i)	{ $ret="b"; }
 	elsif ($self->{value} =~ /^r[\d]+w$/i)	{ $ret="w"; }
 	elsif ($self->{value} =~ /^r[\d]+d$/i)	{ $ret="l"; }
 	elsif ($self->{value} =~ /^r[\w]+$/i)	{ $ret="q"; }
 	elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
 	elsif ($self->{value} =~ /^[\w]{2}l$/i)	{ $ret="b"; }
 	elsif ($self->{value} =~ /^[\w]{2}$/i)	{ $ret="w"; }
 	elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
 
 	$ret;
     }
     sub out {
     	my $self = shift;
 	if ($gas)	{ sprintf "%s%%%s",$self->{asterisk},$self->{value}; }
 	else		{ $self->{value}; }
     }
 }
 { package label;	# pick up labels, which end with :
     sub re {
 	my	$self = shift;	# single instance is enough...
 	local	*line = shift;
 	undef	$ret;
 
 	if ($line =~ /(^[\.\w]+)\:/) {
 	    $self->{value} = $1;
 	    $ret = $self;
 	    $line = substr($line,@+[0]); $line =~ s/^\s+//;
 
 	    $self->{value} =~ s/^\.L/$decor/;
 	}
 	$ret;
     }
     sub out {
 	my $self = shift;
 
 	if ($gas) {
 	    my $func = ($globals{$self->{value}} or $self->{value}) . ":";
 	    if ($win64	&&
 			$current_function->{name} eq $self->{value} &&
 			$current_function->{abi} eq "svr4") {
 		$func .= "\n";
 		$func .= "	movq	%rdi,8(%rsp)\n";
 		$func .= "	movq	%rsi,16(%rsp)\n";
 		$func .= "	movq	%rsp,%rax\n";
 		$func .= "${decor}SEH_begin_$current_function->{name}:\n";
 		my $narg = $current_function->{narg};
 		$narg=6 if (!defined($narg));
 		$func .= "	movq	%rcx,%rdi\n" if ($narg>0);
 		$func .= "	movq	%rdx,%rsi\n" if ($narg>1);
 		$func .= "	movq	%r8,%rdx\n"  if ($narg>2);
 		$func .= "	movq	%r9,%rcx\n"  if ($narg>3);
 		$func .= "	movq	40(%rsp),%r8\n" if ($narg>4);
 		$func .= "	movq	48(%rsp),%r9\n" if ($narg>5);
 	    }
 	    $func;
 	} elsif ($self->{value} ne "$current_function->{name}") {
 	    $self->{value} .= ":" if ($masm && $ret!~m/^\$/);
 	    $self->{value} . ":";
 	} elsif ($win64 && $current_function->{abi} eq "svr4") {
 	    my $func =	"$current_function->{name}" .
 			($nasm ? ":" : "\tPROC $current_function->{scope}") .
 			"\n";
 	    $func .= "	mov	QWORD${PTR}[8+rsp],rdi\t;WIN64 prologue\n";
 	    $func .= "	mov	QWORD${PTR}[16+rsp],rsi\n";
 	    $func .= "	mov	rax,rsp\n";
 	    $func .= "${decor}SEH_begin_$current_function->{name}:";
 	    $func .= ":" if ($masm);
 	    $func .= "\n";
 	    my $narg = $current_function->{narg};
 	    $narg=6 if (!defined($narg));
 	    $func .= "	mov	rdi,rcx\n" if ($narg>0);
 	    $func .= "	mov	rsi,rdx\n" if ($narg>1);
 	    $func .= "	mov	rdx,r8\n"  if ($narg>2);
 	    $func .= "	mov	rcx,r9\n"  if ($narg>3);
 	    $func .= "	mov	r8,QWORD${PTR}[40+rsp]\n" if ($narg>4);
 	    $func .= "	mov	r9,QWORD${PTR}[48+rsp]\n" if ($narg>5);
 	    $func .= "\n";
 	} else {
 	   "$current_function->{name}".
 			($nasm ? ":" : "\tPROC $current_function->{scope}");
 	}
     }
 }
-{ package expr;		# pick up expressioins
+{ package expr;		# pick up expressions
     sub re {
 	my	$self = shift;	# single instance is enough...
 	local	*line = shift;
 	undef	$ret;
 
 	if ($line =~ /(^[^,]+)/) {
 	    $self->{value} = $1;
 	    $ret = $self;
 	    $line = substr($line,@+[0]); $line =~ s/^\s+//;
 
 	    $self->{value} =~ s/\@PLT// if (!$elf);
 	    $self->{value} =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
 	    $self->{value} =~ s/\.L/$decor/g;
 	}
 	$ret;
     }
     sub out {
 	my $self = shift;
 	if ($nasm && opcode->mnemonic()=~m/^j(?![re]cxz)/) {
 	    "NEAR ".$self->{value};
 	} else {
 	    $self->{value};
 	}
     }
 }
 { package directive;	# pick up directives, which start with .
     sub re {
 	my	$self = shift;	# single instance is enough...
 	local	*line = shift;
 	undef	$ret;
 	my	$dir;
 	my	%opcode =	# lea 2f-1f(%rip),%dst; 1: nop; 2:
 		(	"%rax"=>0x01058d48,	"%rcx"=>0x010d8d48,
 			"%rdx"=>0x01158d48,	"%rbx"=>0x011d8d48,
 			"%rsp"=>0x01258d48,	"%rbp"=>0x012d8d48,
 			"%rsi"=>0x01358d48,	"%rdi"=>0x013d8d48,
 			"%r8" =>0x01058d4c,	"%r9" =>0x010d8d4c,
 			"%r10"=>0x01158d4c,	"%r11"=>0x011d8d4c,
 			"%r12"=>0x01258d4c,	"%r13"=>0x012d8d4c,
 			"%r14"=>0x01358d4c,	"%r15"=>0x013d8d4c	);
 
 	if ($line =~ /^\s*(\.\w+)/) {
 	    $dir = $1;
 	    $ret = $self;
 	    undef $self->{value};
 	    $line = substr($line,@+[0]); $line =~ s/^\s+//;
 
 	    SWITCH: for ($dir) {
 		/\.picmeup/ && do { if ($line =~ /(%r[\w]+)/i) {
 			    		$dir="\t.long";
 					$line=sprintf "0x%x,0x90000000",$opcode{$1};
 				    }
 				    last;
 				  };
 		/\.global|\.globl|\.extern/
 			    && do { $globals{$line} = $prefix . $line;
 				    $line = $globals{$line} if ($prefix);
 				    last;
 				  };
 		/\.type/    && do { ($sym,$type,$narg) = split(',',$line);
 				    if ($type eq "\@function") {
 					undef $current_function;
 					$current_function->{name} = $sym;
 					$current_function->{abi}  = "svr4";
 					$current_function->{narg} = $narg;
 					$current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
 				    } elsif ($type eq "\@abi-omnipotent") {
 					undef $current_function;
 					$current_function->{name} = $sym;
 					$current_function->{scope} = defined($globals{$sym})?"PUBLIC":"PRIVATE";
 				    }
 				    $line =~ s/\@abi\-omnipotent/\@function/;
 				    $line =~ s/\@function.*/\@function/;
 				    last;
 				  };
 		/\.asciz/   && do { if ($line =~ /^"(.*)"$/) {
 					$dir  = ".byte";
 					$line = join(",",unpack("C*",$1),0);
 				    }
 				    last;
 				  };
 		/\.rva|\.long|\.quad/
 			    && do { $line =~ s/([_a-z][_a-z0-9]*)/$globals{$1} or $1/gei;
 				    $line =~ s/\.L/$decor/g;
 				    last;
 				  };
 	    }
 
 	    if ($gas) {
 		$self->{value} = $dir . "\t" . $line;
 
 		if ($dir =~ /\.extern/) {
 		    $self->{value} = ""; # swallow extern
 		} elsif (!$elf && $dir =~ /\.type/) {
 		    $self->{value} = "";
 		    $self->{value} = ".def\t" . ($globals{$1} or $1) . ";\t" .
 				(defined($globals{$1})?".scl 2;":".scl 3;") .
 				"\t.type 32;\t.endef"
 				if ($win64 && $line =~ /([^,]+),\@function/);
 		} elsif (!$elf && $dir =~ /\.size/) {
 		    $self->{value} = "";
 		    if (defined($current_function)) {
 			$self->{value} .= "${decor}SEH_end_$current_function->{name}:"
 				if ($win64 && $current_function->{abi} eq "svr4");
 			undef $current_function;
 		    }
 		} elsif (!$elf && $dir =~ /\.align/) {
 		    $self->{value} = ".p2align\t" . (log($line)/log(2));
 		} elsif ($dir eq ".section") {
 		    $current_segment=$line;
 		    if (!$elf && $current_segment eq ".init") {
 			if	($flavour eq "macosx")	{ $self->{value} = ".mod_init_func"; }
 			elsif	($flavour eq "mingw64")	{ $self->{value} = ".section\t.ctors"; }
 		    }
 		} elsif ($dir =~ /\.(text|data)/) {
 		    $current_segment=".$1";
 		} elsif ($dir =~ /\.hidden/) {
 		    if    ($flavour eq "macosx")  { $self->{value} = ".private_extern\t$prefix$line"; }
 		    elsif ($flavour eq "mingw64") { $self->{value} = ""; }
 		} elsif ($dir =~ /\.comm/) {
 		    $self->{value} = "$dir\t$prefix$line";
 		    $self->{value} =~ s|,([0-9]+),([0-9]+)$|",$1,".log($2)/log(2)|e if ($flavour eq "macosx");
 		}
 		$line = "";
 		return $self;
 	    }
 
 	    # non-gas case or nasm/masm
 	    SWITCH: for ($dir) {
 		/\.text/    && do { my $v=undef;
 				    if ($nasm) {
 					$v="section	.text code align=64\n";
 				    } else {
 					$v="$current_segment\tENDS\n" if ($current_segment);
 					$current_segment = ".text\$";
 					$v.="$current_segment\tSEGMENT ";
 					$v.=$masm>=$masmref ? "ALIGN(256)" : "PAGE";
 					$v.=" 'CODE'";
 				    }
 				    $self->{value} = $v;
 				    last;
 				  };
 		/\.data/    && do { my $v=undef;
 				    if ($nasm) {
 					$v="section	.data data align=8\n";
 				    } else {
 					$v="$current_segment\tENDS\n" if ($current_segment);
 					$current_segment = "_DATA";
 					$v.="$current_segment\tSEGMENT";
 				    }
 				    $self->{value} = $v;
 				    last;
 				  };
 		/\.section/ && do { my $v=undef;
 				    $line =~ s/([^,]*).*/$1/;
 				    $line = ".CRT\$XCU" if ($line eq ".init");
 				    if ($nasm) {
 					$v="section	$line";
 					if ($line=~/\.([px])data/) {
 					    $v.=" rdata align=";
 					    $v.=$1 eq "p"? 4 : 8;
 					} elsif ($line=~/\.CRT\$/i) {
 					    $v.=" rdata align=8";
 					}
 				    } else {
 					$v="$current_segment\tENDS\n" if ($current_segment);
 					$v.="$line\tSEGMENT";
 					if ($line=~/\.([px])data/) {
 					    $v.=" READONLY";
 					    $v.=" ALIGN(".($1 eq "p" ? 4 : 8).")" if ($masm>=$masmref);
 					} elsif ($line=~/\.CRT\$/i) {
 					    $v.=" READONLY ";
 					    $v.=$masm>=$masmref ? "ALIGN(8)" : "DWORD";
 					}
 				    }
 				    $current_segment = $line;
 				    $self->{value} = $v;
 				    last;
 				  };
 		/\.extern/  && do { $self->{value}  = "EXTERN\t".$line;
 				    $self->{value} .= ":NEAR" if ($masm);
 				    last;
 				  };
 		/\.globl|.global/
 			    && do { $self->{value}  = $masm?"PUBLIC":"global";
 				    $self->{value} .= "\t".$line;
 				    last;
 				  };
 		/\.size/    && do { if (defined($current_function)) {
 					undef $self->{value};
 					if ($current_function->{abi} eq "svr4") {
 					    $self->{value}="${decor}SEH_end_$current_function->{name}:";
 					    $self->{value}.=":\n" if($masm);
 					}
 					$self->{value}.="$current_function->{name}\tENDP" if($masm && $current_function->{name});
 					undef $current_function;
 				    }
 				    last;
 				  };
 		/\.align/   && do { $self->{value} = "ALIGN\t".$line; last; };
 		/\.(value|long|rva|quad)/
 			    && do { my $sz  = substr($1,0,1);
 				    my @arr = split(/,\s*/,$line);
 				    my $last = pop(@arr);
 				    my $conv = sub  {	my $var=shift;
 							$var=~s/^(0b[0-1]+)/oct($1)/eig;
 							$var=~s/^0x([0-9a-f]+)/0$1h/ig if ($masm);
 							if ($sz eq "D" && ($current_segment=~/.[px]data/ || $dir eq ".rva"))
 							{ $var=~s/([_a-z\$\@][_a-z0-9\$\@]*)/$nasm?"$1 wrt ..imagebase":"imagerel $1"/egi; }
 							$var;
 						    };  
 
 				    $sz =~ tr/bvlrq/BWDDQ/;
 				    $self->{value} = "\tD$sz\t";
 				    for (@arr) { $self->{value} .= &$conv($_).","; }
 				    $self->{value} .= &$conv($last);
 				    last;
 				  };
 		/\.byte/    && do { my @str=split(/,\s*/,$line);
 				    map(s/(0b[0-1]+)/oct($1)/eig,@str);
 				    map(s/0x([0-9a-f]+)/0$1h/ig,@str) if ($masm);	
 				    while ($#str>15) {
 					$self->{value}.="DB\t"
 						.join(",",@str[0..15])."\n";
 					foreach (0..15) { shift @str; }
 				    }
 				    $self->{value}.="DB\t"
 						.join(",",@str) if (@str);
 				    last;
 				  };
 		/\.comm/    && do { my @str=split(/,\s*/,$line);
 				    my $v=undef;
 				    if ($nasm) {
 					$v.="common	$prefix@str[0] @str[1]";
 				    } else {
 					$v="$current_segment\tENDS\n" if ($current_segment);
 					$current_segment = "_DATA";
 					$v.="$current_segment\tSEGMENT\n";
 					$v.="COMM	@str[0]:DWORD:".@str[1]/4;
 				    }
 				    $self->{value} = $v;
 				    last;
 				  };
 	    }
 	    $line = "";
 	}
 
 	$ret;
     }
     sub out {
 	my $self = shift;
 	$self->{value};
     }
 }
 
 sub rex {
  local *opcode=shift;
  my ($dst,$src,$rex)=@_;
 
    $rex|=0x04 if($dst>=8);
    $rex|=0x01 if($src>=8);
    push @opcode,($rex|0x40) if ($rex);
 }
 
 # older gas and ml64 don't handle SSE>2 instructions
 my %regrm = (	"%eax"=>0, "%ecx"=>1, "%edx"=>2, "%ebx"=>3,
 		"%esp"=>4, "%ebp"=>5, "%esi"=>6, "%edi"=>7	);
 
 my $movq = sub {	# elderly gas can't handle inter-register movq
   my $arg = shift;
   my @opcode=(0x66);
     if ($arg =~ /%xmm([0-9]+),\s*%r(\w+)/) {
 	my ($src,$dst)=($1,$2);
 	if ($dst !~ /[0-9]+/)	{ $dst = $regrm{"%e$dst"}; }
 	rex(\@opcode,$src,$dst,0x8);
 	push @opcode,0x0f,0x7e;
 	push @opcode,0xc0|(($src&7)<<3)|($dst&7);	# ModR/M
 	@opcode;
     } elsif ($arg =~ /%r(\w+),\s*%xmm([0-9]+)/) {
 	my ($src,$dst)=($2,$1);
 	if ($dst !~ /[0-9]+/)	{ $dst = $regrm{"%e$dst"}; }
 	rex(\@opcode,$src,$dst,0x8);
 	push @opcode,0x0f,0x6e;
 	push @opcode,0xc0|(($src&7)<<3)|($dst&7);	# ModR/M
 	@opcode;
     } else {
 	();
     }
 };
 
 my $pextrd = sub {
     if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*(%\w+)/) {
       my @opcode=(0x66);
 	$imm=$1;
 	$src=$2;
 	$dst=$3;
 	if ($dst =~ /%r([0-9]+)d/)	{ $dst = $1; }
 	elsif ($dst =~ /%e/)		{ $dst = $regrm{$dst}; }
 	rex(\@opcode,$src,$dst);
 	push @opcode,0x0f,0x3a,0x16;
 	push @opcode,0xc0|(($src&7)<<3)|($dst&7);	# ModR/M
 	push @opcode,$imm;
 	@opcode;
     } else {
 	();
     }
 };
 
 my $pinsrd = sub {
     if (shift =~ /\$([0-9]+),\s*(%\w+),\s*%xmm([0-9]+)/) {
       my @opcode=(0x66);
 	$imm=$1;
 	$src=$2;
 	$dst=$3;
 	if ($src =~ /%r([0-9]+)/)	{ $src = $1; }
 	elsif ($src =~ /%e/)		{ $src = $regrm{$src}; }
 	rex(\@opcode,$dst,$src);
 	push @opcode,0x0f,0x3a,0x22;
 	push @opcode,0xc0|(($dst&7)<<3)|($src&7);	# ModR/M
 	push @opcode,$imm;
 	@opcode;
     } else {
 	();
     }
 };
 
 my $pshufb = sub {
     if (shift =~ /%xmm([0-9]+),\s*%xmm([0-9]+)/) {
       my @opcode=(0x66);
 	rex(\@opcode,$2,$1);
 	push @opcode,0x0f,0x38,0x00;
 	push @opcode,0xc0|($1&7)|(($2&7)<<3);		# ModR/M
 	@opcode;
     } else {
 	();
     }
 };
 
 my $palignr = sub {
     if (shift =~ /\$([0-9]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
       my @opcode=(0x66);
 	rex(\@opcode,$3,$2);
 	push @opcode,0x0f,0x3a,0x0f;
 	push @opcode,0xc0|($2&7)|(($3&7)<<3);		# ModR/M
 	push @opcode,$1;
 	@opcode;
     } else {
 	();
     }
 };
 
 my $pclmulqdq = sub {
     if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
       my @opcode=(0x66);
 	rex(\@opcode,$3,$2);
 	push @opcode,0x0f,0x3a,0x44;
 	push @opcode,0xc0|($2&7)|(($3&7)<<3);		# ModR/M
 	my $c=$1;
 	push @opcode,$c=~/^0/?oct($c):$c;
 	@opcode;
     } else {
 	();
     }
 };
 
 my $rdrand = sub {
     if (shift =~ /%[er](\w+)/) {
       my @opcode=();
       my $dst=$1;
 	if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
 	rex(\@opcode,0,$1,8);
 	push @opcode,0x0f,0xc7,0xf0|($dst&7);
 	@opcode;
     } else {
 	();
     }
 };
 
 my $rdseed = sub {
     if (shift =~ /%[er](\w+)/) {
       my @opcode=();
       my $dst=$1;
 	if ($dst !~ /[0-9]+/) { $dst = $regrm{"%e$dst"}; }
 	rex(\@opcode,0,$1,8);
 	push @opcode,0x0f,0xc7,0xf8|($dst&7);
 	@opcode;
     } else {
 	();
     }
 };
 
 sub rxb {
  local *opcode=shift;
  my ($dst,$src1,$src2,$rxb)=@_;
 
    $rxb|=0x7<<5;
    $rxb&=~(0x04<<5) if($dst>=8);
    $rxb&=~(0x01<<5) if($src1>=8);
    $rxb&=~(0x02<<5) if($src2>=8);
    push @opcode,$rxb;
 }
 
 my $vprotd = sub {
     if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
       my @opcode=(0x8f);
 	rxb(\@opcode,$3,$2,-1,0x08);
 	push @opcode,0x78,0xc2;
 	push @opcode,0xc0|($2&7)|(($3&7)<<3);		# ModR/M
 	my $c=$1;
 	push @opcode,$c=~/^0/?oct($c):$c;
 	@opcode;
     } else {
 	();
     }
 };
 
 my $vprotq = sub {
     if (shift =~ /\$([x0-9a-f]+),\s*%xmm([0-9]+),\s*%xmm([0-9]+)/) {
       my @opcode=(0x8f);
 	rxb(\@opcode,$3,$2,-1,0x08);
 	push @opcode,0x78,0xc3;
 	push @opcode,0xc0|($2&7)|(($3&7)<<3);		# ModR/M
 	my $c=$1;
 	push @opcode,$c=~/^0/?oct($c):$c;
 	@opcode;
     } else {
 	();
     }
 };
 
 if ($nasm) {
     print <<___;
 default	rel
 %define XMMWORD
 %define YMMWORD
 %define ZMMWORD
 ___
 } elsif ($masm) {
     print <<___;
 OPTION	DOTNAME
 ___
 }
 while($line=<>) {
 
     chomp($line);
 
     $line =~ s|[#!].*$||;	# get rid of asm-style comments...
     $line =~ s|/\*.*\*/||;	# ... and C-style comments...
     $line =~ s|^\s+||;		# ... and skip white spaces in beginning
     $line =~ s|\s+$||;		# ... and at the end
 
     undef $label;
     undef $opcode;
     undef @args;
 
     if ($label=label->re(\$line))	{ print $label->out(); }
 
     if (directive->re(\$line)) {
 	printf "%s",directive->out();
     } elsif ($opcode=opcode->re(\$line)) {
 	my $asm = eval("\$".$opcode->mnemonic());
 	undef @bytes;
 	
 	if ((ref($asm) eq 'CODE') && scalar(@bytes=&$asm($line))) {
 	    print $gas?".byte\t":"DB\t",join(',',@bytes),"\n";
 	    next;
 	}
 
 	ARGUMENT: while (1) {
 	my $arg;
 
 	if ($arg=register->re(\$line))	{ opcode->size($arg->size()); }
 	elsif ($arg=const->re(\$line))	{ }
 	elsif ($arg=ea->re(\$line))	{ }
 	elsif ($arg=expr->re(\$line))	{ }
 	else				{ last ARGUMENT; }
 
 	push @args,$arg;
 
 	last ARGUMENT if ($line !~ /^,/);
 
 	$line =~ s/^,\s*//;
 	} # ARGUMENT:
 
 	if ($#args>=0) {
 	    my $insn;
 	    my $sz=opcode->size();
 
 	    if ($gas) {
 		$insn = $opcode->out($#args>=1?$args[$#args]->size():$sz);
 		@args = map($_->out($sz),@args);
 		printf "\t%s\t%s",$insn,join(",",@args);
 	    } else {
 		$insn = $opcode->out();
 		foreach (@args) {
 		    my $arg = $_->out();
 		    # $insn.=$sz compensates for movq, pinsrw, ...
 		    if ($arg =~ /^xmm[0-9]+$/) { $insn.=$sz; $sz="x" if(!$sz); last; }
 		    if ($arg =~ /^ymm[0-9]+$/) { $insn.=$sz; $sz="y" if(!$sz); last; }
 		    if ($arg =~ /^zmm[0-9]+$/) { $insn.=$sz; $sz="z" if(!$sz); last; }
 		    if ($arg =~ /^mm[0-9]+$/)  { $insn.=$sz; $sz="q" if(!$sz); last; }
 		}
 		@args = reverse(@args);
 		undef $sz if ($nasm && $opcode->mnemonic() eq "lea");
 		printf "\t%s\t%s",$insn,join(",",map($_->out($sz),@args));
 	    }
 	} else {
 	    printf "\t%s",$opcode->out();
 	}
     }
 
     print $line,"\n";
 }
 
 print "\n$current_segment\tENDS\n"	if ($current_segment && $masm);
 print "END\n"				if ($masm);
 
 close STDOUT;
 
 #################################################
 # Cross-reference x86_64 ABI "card"
 #
 # 		Unix		Win64
 # %rax		*		*
 # %rbx		-		-
 # %rcx		#4		#1
 # %rdx		#3		#2
 # %rsi		#2		-
 # %rdi		#1		-
 # %rbp		-		-
 # %rsp		-		-
 # %r8		#5		#3
 # %r9		#6		#4
 # %r10		*		*
 # %r11		*		*
 # %r12		-		-
 # %r13		-		-
 # %r14		-		-
 # %r15		-		-
 # 
 # (*)	volatile register
 # (-)	preserved by callee
 # (#)	Nth argument, volatile
 #
 # In Unix terms top of stack is argument transfer area for arguments
 # which could not be accomodated in registers. Or in other words 7th
 # [integer] argument resides at 8(%rsp) upon function entry point.
 # 128 bytes above %rsp constitute a "red zone" which is not touched
 # by signal handlers and can be used as temporal storage without
 # allocating a frame.
 #
 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
 # which belongs to/can be overwritten by callee. N is the number of
 # arguments passed to callee, *but* not less than 4! This means that
 # upon function entry point 5th argument resides at 40(%rsp), as well
 # as that 32 bytes from 8(%rsp) can always be used as temporal
 # storage [without allocating a frame]. One can actually argue that
 # one can assume a "red zone" above stack pointer under Win64 as well.
 # Point is that at apparently no occasion Windows kernel would alter
 # the area above user stack pointer in true asynchronous manner...
 #
 # All the above means that if assembler programmer adheres to Unix
-# register and stack layout, but disregards the "red zone" existense,
+# register and stack layout, but disregards the "red zone" existence,
 # it's possible to use following prologue and epilogue to "gear" from
 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
 #
 # omnipotent_function:
 # ifdef WIN64
 #	movq	%rdi,8(%rsp)
 #	movq	%rsi,16(%rsp)
 #	movq	%rcx,%rdi	; if 1st argument is actually present
 #	movq	%rdx,%rsi	; if 2nd argument is actually ...
 #	movq	%r8,%rdx	; if 3rd argument is ...
 #	movq	%r9,%rcx	; if 4th argument ...
 #	movq	40(%rsp),%r8	; if 5th ...
 #	movq	48(%rsp),%r9	; if 6th ...
 # endif
 #	...
 # ifdef WIN64
 #	movq	8(%rsp),%rdi
 #	movq	16(%rsp),%rsi
 # endif
 #	ret
 #
 #################################################
 # Win64 SEH, Structured Exception Handling.
 #
 # Unlike on Unix systems(*) lack of Win64 stack unwinding information
 # has undesired side-effect at run-time: if an exception is raised in
 # assembler subroutine such as those in question (basically we're
 # referring to segmentation violations caused by malformed input
 # parameters), the application is briskly terminated without invoking
 # any exception handlers, most notably without generating memory dump
 # or any user notification whatsoever. This poses a problem. It's
 # possible to address it by registering custom language-specific
 # handler that would restore processor context to the state at
 # subroutine entry point and return "exception is not handled, keep
 # unwinding" code. Writing such handler can be a challenge... But it's
 # doable, though requires certain coding convention. Consider following
 # snippet:
 #
 # .type	function,@function
 # function:
 #	movq	%rsp,%rax	# copy rsp to volatile register
 #	pushq	%r15		# save non-volatile registers
 #	pushq	%rbx
 #	pushq	%rbp
 #	movq	%rsp,%r11
 #	subq	%rdi,%r11	# prepare [variable] stack frame
 #	andq	$-64,%r11
 #	movq	%rax,0(%r11)	# check for exceptions
 #	movq	%r11,%rsp	# allocate [variable] stack frame
 #	movq	%rax,0(%rsp)	# save original rsp value
 # magic_point:
 #	...
 #	movq	0(%rsp),%rcx	# pull original rsp value
 #	movq	-24(%rcx),%rbp	# restore non-volatile registers
 #	movq	-16(%rcx),%rbx
 #	movq	-8(%rcx),%r15
 #	movq	%rcx,%rsp	# restore original rsp
 #	ret
 # .size function,.-function
 #
 # The key is that up to magic_point copy of original rsp value remains
 # in chosen volatile register and no non-volatile register, except for
 # rsp, is modified. While past magic_point rsp remains constant till
 # the very end of the function. In this case custom language-specific
 # exception handler would look like this:
 #
 # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
 #		CONTEXT *context,DISPATCHER_CONTEXT *disp)
 # {	ULONG64 *rsp = (ULONG64 *)context->Rax;
 #	if (context->Rip >= magic_point)
 #	{   rsp = ((ULONG64 **)context->Rsp)[0];
 #	    context->Rbp = rsp[-3];
 #	    context->Rbx = rsp[-2];
 #	    context->R15 = rsp[-1];
 #	}
 #	context->Rsp = (ULONG64)rsp;
 #	context->Rdi = rsp[1];
 #	context->Rsi = rsp[2];
 #
 #	memcpy (disp->ContextRecord,context,sizeof(CONTEXT));
 #	RtlVirtualUnwind(UNW_FLAG_NHANDLER,disp->ImageBase,
 #		dips->ControlPc,disp->FunctionEntry,disp->ContextRecord,
 #		&disp->HandlerData,&disp->EstablisherFrame,NULL);
 #	return ExceptionContinueSearch;
 # }
 #
 # It's appropriate to implement this handler in assembler, directly in
 # function's module. In order to do that one has to know members'
 # offsets in CONTEXT and DISPATCHER_CONTEXT structures and some constant
 # values. Here they are:
 #
 #	CONTEXT.Rax				120
 #	CONTEXT.Rcx				128
 #	CONTEXT.Rdx				136
 #	CONTEXT.Rbx				144
 #	CONTEXT.Rsp				152
 #	CONTEXT.Rbp				160
 #	CONTEXT.Rsi				168
 #	CONTEXT.Rdi				176
 #	CONTEXT.R8				184
 #	CONTEXT.R9				192
 #	CONTEXT.R10				200
 #	CONTEXT.R11				208
 #	CONTEXT.R12				216
 #	CONTEXT.R13				224
 #	CONTEXT.R14				232
 #	CONTEXT.R15				240
 #	CONTEXT.Rip				248
 #	CONTEXT.Xmm6				512
 #	sizeof(CONTEXT)				1232
 #	DISPATCHER_CONTEXT.ControlPc		0
 #	DISPATCHER_CONTEXT.ImageBase		8
 #	DISPATCHER_CONTEXT.FunctionEntry	16
 #	DISPATCHER_CONTEXT.EstablisherFrame	24
 #	DISPATCHER_CONTEXT.TargetIp		32
 #	DISPATCHER_CONTEXT.ContextRecord	40
 #	DISPATCHER_CONTEXT.LanguageHandler	48
 #	DISPATCHER_CONTEXT.HandlerData		56
 #	UNW_FLAG_NHANDLER			0
 #	ExceptionContinueSearch			1
 #
 # In order to tie the handler to the function one has to compose
 # couple of structures: one for .xdata segment and one for .pdata.
 #
 # UNWIND_INFO structure for .xdata segment would be
 #
 # function_unwind_info:
 #	.byte	9,0,0,0
 #	.rva	handler
 #
 # This structure designates exception handler for a function with
 # zero-length prologue, no stack frame or frame register.
 #
 # To facilitate composing of .pdata structures, auto-generated "gear"
 # prologue copies rsp value to rax and denotes next instruction with
 # .LSEH_begin_{function_name} label. This essentially defines the SEH
 # styling rule mentioned in the beginning. Position of this label is
 # chosen in such manner that possible exceptions raised in the "gear"
 # prologue would be accounted to caller and unwound from latter's frame.
 # End of function is marked with respective .LSEH_end_{function_name}
 # label. To summarize, .pdata segment would contain
 #
 #	.rva	.LSEH_begin_function
 #	.rva	.LSEH_end_function
 #	.rva	function_unwind_info
 #
 # Reference to functon_unwind_info from .xdata segment is the anchor.
 # In case you wonder why references are 32-bit .rvas and not 64-bit
 # .quads. References put into these two segments are required to be
 # *relative* to the base address of the current binary module, a.k.a.
 # image base. No Win64 module, be it .exe or .dll, can be larger than
 # 2GB and thus such relative references can be and are accommodated in
 # 32 bits.
 #
 # Having reviewed the example function code, one can argue that "movq
 # %rsp,%rax" above is redundant. It is not! Keep in mind that on Unix
 # rax would contain an undefined value. If this "offends" you, use
 # another register and refrain from modifying rax till magic_point is
 # reached, i.e. as if it was a non-volatile register. If more registers
 # are required prior [variable] frame setup is completed, note that
 # nobody says that you can have only one "magic point." You can
 # "liberate" non-volatile registers by denoting last stack off-load
 # instruction and reflecting it in finer grade unwind logic in handler.
 # After all, isn't it why it's called *language-specific* handler...
 #
 # Attentive reader can notice that exceptions would be mishandled in
 # auto-generated "gear" epilogue. Well, exception effectively can't
 # occur there, because if memory area used by it was subject to
 # segmentation violation, then it would be raised upon call to the
 # function (and as already mentioned be accounted to caller, which is
 # not a problem). If you're still not comfortable, then define tail
 # "magic point" just prior ret instruction and have handler treat it...
 #
 # (*)	Note that we're talking about run-time, not debug-time. Lack of
 #	unwind information makes debugging hard on both Windows and
 #	Unix. "Unlike" referes to the fact that on Unix signal handler
 #	will always be invoked, core dumped and appropriate exit code
 #	returned to parent (for user notification).
Index: vendor-crypto/openssl/dist/crypto/pkcs12/p12_mutl.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/pkcs12/p12_mutl.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/pkcs12/p12_mutl.c	(revision 318897)
@@ -1,195 +1,198 @@
 /* p12_mutl.c */
 /*
  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
  * 1999.
  */
 /* ====================================================================
  * Copyright (c) 1999 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    licensing@OpenSSL.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #ifndef OPENSSL_NO_HMAC
 # include 
 # include "cryptlib.h"
 # include 
 # include 
 # include 
 # include 
 
 /* Generate a MAC */
 int PKCS12_gen_mac(PKCS12 *p12, const char *pass, int passlen,
                    unsigned char *mac, unsigned int *maclen)
 {
     const EVP_MD *md_type;
     HMAC_CTX hmac;
     unsigned char key[EVP_MAX_MD_SIZE], *salt;
     int saltlen, iter;
     int md_size;
 
     if (!PKCS7_type_is_data(p12->authsafes)) {
         PKCS12err(PKCS12_F_PKCS12_GEN_MAC, PKCS12_R_CONTENT_TYPE_NOT_DATA);
         return 0;
     }
 
     salt = p12->mac->salt->data;
     saltlen = p12->mac->salt->length;
     if (!p12->mac->iter)
         iter = 1;
     else
         iter = ASN1_INTEGER_get(p12->mac->iter);
     if (!(md_type = EVP_get_digestbyobj(p12->mac->dinfo->algor->algorithm))) {
         PKCS12err(PKCS12_F_PKCS12_GEN_MAC, PKCS12_R_UNKNOWN_DIGEST_ALGORITHM);
         return 0;
     }
     md_size = EVP_MD_size(md_type);
     if (md_size < 0)
         return 0;
     if (!PKCS12_key_gen(pass, passlen, salt, saltlen, PKCS12_MAC_ID, iter,
                         md_size, key, md_type)) {
         PKCS12err(PKCS12_F_PKCS12_GEN_MAC, PKCS12_R_KEY_GEN_ERROR);
         return 0;
     }
     HMAC_CTX_init(&hmac);
     if (!HMAC_Init_ex(&hmac, key, md_size, md_type, NULL)
         || !HMAC_Update(&hmac, p12->authsafes->d.data->data,
                         p12->authsafes->d.data->length)
         || !HMAC_Final(&hmac, mac, maclen)) {
         HMAC_CTX_cleanup(&hmac);
         return 0;
     }
     HMAC_CTX_cleanup(&hmac);
     return 1;
 }
 
 /* Verify the mac */
 int PKCS12_verify_mac(PKCS12 *p12, const char *pass, int passlen)
 {
     unsigned char mac[EVP_MAX_MD_SIZE];
     unsigned int maclen;
     if (p12->mac == NULL) {
         PKCS12err(PKCS12_F_PKCS12_VERIFY_MAC, PKCS12_R_MAC_ABSENT);
         return 0;
     }
     if (!PKCS12_gen_mac(p12, pass, passlen, mac, &maclen)) {
         PKCS12err(PKCS12_F_PKCS12_VERIFY_MAC, PKCS12_R_MAC_GENERATION_ERROR);
         return 0;
     }
     if ((maclen != (unsigned int)p12->mac->dinfo->digest->length)
         || CRYPTO_memcmp(mac, p12->mac->dinfo->digest->data, maclen))
         return 0;
     return 1;
 }
 
 /* Set a mac */
 
 int PKCS12_set_mac(PKCS12 *p12, const char *pass, int passlen,
                    unsigned char *salt, int saltlen, int iter,
                    const EVP_MD *md_type)
 {
     unsigned char mac[EVP_MAX_MD_SIZE];
     unsigned int maclen;
 
     if (!md_type)
         md_type = EVP_sha1();
     if (PKCS12_setup_mac(p12, iter, salt, saltlen, md_type) == PKCS12_ERROR) {
         PKCS12err(PKCS12_F_PKCS12_SET_MAC, PKCS12_R_MAC_SETUP_ERROR);
         return 0;
     }
     if (!PKCS12_gen_mac(p12, pass, passlen, mac, &maclen)) {
         PKCS12err(PKCS12_F_PKCS12_SET_MAC, PKCS12_R_MAC_GENERATION_ERROR);
         return 0;
     }
     if (!(M_ASN1_OCTET_STRING_set(p12->mac->dinfo->digest, mac, maclen))) {
         PKCS12err(PKCS12_F_PKCS12_SET_MAC, PKCS12_R_MAC_STRING_SET_ERROR);
         return 0;
     }
     return 1;
 }
 
 /* Set up a mac structure */
 int PKCS12_setup_mac(PKCS12 *p12, int iter, unsigned char *salt, int saltlen,
                      const EVP_MD *md_type)
 {
-    if (!(p12->mac = PKCS12_MAC_DATA_new()))
+    PKCS12_MAC_DATA_free(p12->mac);
+    p12->mac = NULL;
+
+    if ((p12->mac = PKCS12_MAC_DATA_new()) == NULL)
         return PKCS12_ERROR;
     if (iter > 1) {
         if (!(p12->mac->iter = M_ASN1_INTEGER_new())) {
             PKCS12err(PKCS12_F_PKCS12_SETUP_MAC, ERR_R_MALLOC_FAILURE);
             return 0;
         }
         if (!ASN1_INTEGER_set(p12->mac->iter, iter)) {
             PKCS12err(PKCS12_F_PKCS12_SETUP_MAC, ERR_R_MALLOC_FAILURE);
             return 0;
         }
     }
     if (!saltlen)
         saltlen = PKCS12_SALT_LEN;
     if ((p12->mac->salt->data = OPENSSL_malloc(saltlen)) == NULL) {
         PKCS12err(PKCS12_F_PKCS12_SETUP_MAC, ERR_R_MALLOC_FAILURE);
         return 0;
     }
     p12->mac->salt->length = saltlen;
     if (!salt) {
         if (RAND_bytes(p12->mac->salt->data, saltlen) <= 0)
             return 0;
     } else
         memcpy(p12->mac->salt->data, salt, saltlen);
     p12->mac->dinfo->algor->algorithm = OBJ_nid2obj(EVP_MD_type(md_type));
     if (!(p12->mac->dinfo->algor->parameter = ASN1_TYPE_new())) {
         PKCS12err(PKCS12_F_PKCS12_SETUP_MAC, ERR_R_MALLOC_FAILURE);
         return 0;
     }
     p12->mac->dinfo->algor->parameter->type = V_ASN1_NULL;
 
     return 1;
 }
 #endif
Index: vendor-crypto/openssl/dist/crypto/ppccap.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/ppccap.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/ppccap.c	(revision 318897)
@@ -1,159 +1,183 @@
 #include 
 #include 
 #include 
 #include 
 #include 
 #include 
 #if defined(__linux) || defined(_AIX)
 # include 
 #endif
+#if defined(__APPLE__) && defined(__MACH__)
+# include 
+# include 
+#endif
 #include 
 #include 
 
 #include "ppc_arch.h"
 
 unsigned int OPENSSL_ppccap_P = 0;
 
 static sigset_t all_masked;
 
 #ifdef OPENSSL_BN_ASM_MONT
 int bn_mul_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp,
                 const BN_ULONG *np, const BN_ULONG *n0, int num)
 {
     int bn_mul_mont_fpu64(BN_ULONG *rp, const BN_ULONG *ap,
                           const BN_ULONG *bp, const BN_ULONG *np,
                           const BN_ULONG *n0, int num);
     int bn_mul_mont_int(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp,
                         const BN_ULONG *np, const BN_ULONG *n0, int num);
 
     if (sizeof(size_t) == 4) {
 # if 1 || (defined(__APPLE__) && defined(__MACH__))
         if (num >= 8 && (num & 3) == 0 && (OPENSSL_ppccap_P & PPC_FPU64))
             return bn_mul_mont_fpu64(rp, ap, bp, np, n0, num);
 # else
         /*
          * boundary of 32 was experimentally determined on Linux 2.6.22,
          * might have to be adjusted on AIX...
          */
         if (num >= 32 && (num & 3) == 0 && (OPENSSL_ppccap_P & PPC_FPU64)) {
             sigset_t oset;
             int ret;
 
             sigprocmask(SIG_SETMASK, &all_masked, &oset);
             ret = bn_mul_mont_fpu64(rp, ap, bp, np, n0, num);
             sigprocmask(SIG_SETMASK, &oset, NULL);
 
             return ret;
         }
 # endif
     } else if ((OPENSSL_ppccap_P & PPC_FPU64))
         /*
          * this is a "must" on POWER6, but run-time detection is not
          * implemented yet...
          */
         return bn_mul_mont_fpu64(rp, ap, bp, np, n0, num);
 
     return bn_mul_mont_int(rp, ap, bp, np, n0, num);
 }
 #endif
 
 void sha256_block_p8(void *ctx, const void *inp, size_t len);
 void sha256_block_ppc(void *ctx, const void *inp, size_t len);
 void sha256_block_data_order(void *ctx, const void *inp, size_t len)
 {
     OPENSSL_ppccap_P & PPC_CRYPTO207 ? sha256_block_p8(ctx, inp, len) :
         sha256_block_ppc(ctx, inp, len);
 }
 
 void sha512_block_p8(void *ctx, const void *inp, size_t len);
 void sha512_block_ppc(void *ctx, const void *inp, size_t len);
 void sha512_block_data_order(void *ctx, const void *inp, size_t len)
 {
     OPENSSL_ppccap_P & PPC_CRYPTO207 ? sha512_block_p8(ctx, inp, len) :
         sha512_block_ppc(ctx, inp, len);
 }
 
 static sigjmp_buf ill_jmp;
 static void ill_handler(int sig)
 {
     siglongjmp(ill_jmp, sig);
 }
 
 void OPENSSL_ppc64_probe(void);
 void OPENSSL_altivec_probe(void);
 void OPENSSL_crypto207_probe(void);
 
 void OPENSSL_cpuid_setup(void)
 {
     char *e;
     struct sigaction ill_oact, ill_act;
     sigset_t oset;
     static int trigger = 0;
 
     if (trigger)
         return;
     trigger = 1;
 
     sigfillset(&all_masked);
     sigdelset(&all_masked, SIGILL);
     sigdelset(&all_masked, SIGTRAP);
 #ifdef SIGEMT
     sigdelset(&all_masked, SIGEMT);
 #endif
     sigdelset(&all_masked, SIGFPE);
     sigdelset(&all_masked, SIGBUS);
     sigdelset(&all_masked, SIGSEGV);
 
     if ((e = getenv("OPENSSL_ppccap"))) {
         OPENSSL_ppccap_P = strtoul(e, NULL, 0);
         return;
     }
 
     OPENSSL_ppccap_P = 0;
 
 #if defined(_AIX)
     if (sizeof(size_t) == 4) {
         struct utsname uts;
 # if defined(_SC_AIX_KERNEL_BITMODE)
         if (sysconf(_SC_AIX_KERNEL_BITMODE) != 64)
             return;
 # endif
         if (uname(&uts) != 0 || atoi(uts.version) < 6)
             return;
+    }
+#endif
+
+#if defined(__APPLE__) && defined(__MACH__)
+    {
+        int val;
+        size_t len = sizeof(val);
+
+        if (sysctlbyname("hw.optional.64bitops", &val, &len, NULL, 0) == 0) {
+            if (val)
+                OPENSSL_ppccap_P |= PPC_FPU64;
+        }
+
+        len = sizeof(val);
+        if (sysctlbyname("hw.optional.altivec", &val, &len, NULL, 0) == 0) {
+            if (val)
+                OPENSSL_ppccap_P |= PPC_ALTIVEC;
+        }
+
+        return;
     }
 #endif
 
     memset(&ill_act, 0, sizeof(ill_act));
     ill_act.sa_handler = ill_handler;
     ill_act.sa_mask = all_masked;
 
     sigprocmask(SIG_SETMASK, &ill_act.sa_mask, &oset);
     sigaction(SIGILL, &ill_act, &ill_oact);
 
     if (sizeof(size_t) == 4) {
 #ifdef __linux
         struct utsname uts;
         if (uname(&uts) == 0 && strcmp(uts.machine, "ppc64") == 0)
 #endif
             if (sigsetjmp(ill_jmp, 1) == 0) {
                 OPENSSL_ppc64_probe();
                 OPENSSL_ppccap_P |= PPC_FPU64;
             }
     } else {
         /*
          * Wanted code detecting POWER6 CPU and setting PPC_FPU64
          */
     }
 
     if (sigsetjmp(ill_jmp, 1) == 0) {
         OPENSSL_altivec_probe();
         OPENSSL_ppccap_P |= PPC_ALTIVEC;
         if (sigsetjmp(ill_jmp, 1) == 0) {
             OPENSSL_crypto207_probe();
             OPENSSL_ppccap_P |= PPC_CRYPTO207;
         }
     }
 
     sigaction(SIGILL, &ill_oact, NULL);
     sigprocmask(SIG_SETMASK, &oset, NULL);
 }
Index: vendor-crypto/openssl/dist/crypto/rand/md_rand.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/rand/md_rand.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/rand/md_rand.c	(revision 318897)
@@ -1,592 +1,616 @@
 /* crypto/rand/md_rand.c */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 /* ====================================================================
  * Copyright (c) 1998-2001 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    openssl-core@openssl.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #define OPENSSL_FIPSEVP
 
 #ifdef MD_RAND_DEBUG
 # ifndef NDEBUG
 #  define NDEBUG
 # endif
 #endif
 
 #include 
 #include 
 #include 
 
 #include "e_os.h"
 
 #include 
 #include 
 #include "rand_lcl.h"
 
 #include 
 
 #ifdef BN_DEBUG
 # define PREDICT
 #endif
 
 /* #define PREDICT      1 */
 
 #define STATE_SIZE      1023
 static size_t state_num = 0, state_index = 0;
 static unsigned char state[STATE_SIZE + MD_DIGEST_LENGTH];
 static unsigned char md[MD_DIGEST_LENGTH];
 static long md_count[2] = { 0, 0 };
 
 static double entropy = 0;
 static int initialized = 0;
 
 static unsigned int crypto_lock_rand = 0; /* may be set only when a thread
                                            * holds CRYPTO_LOCK_RAND (to
                                            * prevent double locking) */
 /* access to lockin_thread is synchronized by CRYPTO_LOCK_RAND2 */
 /* valid iff crypto_lock_rand is set */
 static CRYPTO_THREADID locking_threadid;
 
 #ifdef PREDICT
 int rand_predictable = 0;
 #endif
 
 const char RAND_version[] = "RAND" OPENSSL_VERSION_PTEXT;
 
 static void ssleay_rand_cleanup(void);
 static void ssleay_rand_seed(const void *buf, int num);
 static void ssleay_rand_add(const void *buf, int num, double add_entropy);
 static int ssleay_rand_nopseudo_bytes(unsigned char *buf, int num);
 static int ssleay_rand_pseudo_bytes(unsigned char *buf, int num);
 static int ssleay_rand_status(void);
 
 RAND_METHOD rand_ssleay_meth = {
     ssleay_rand_seed,
     ssleay_rand_nopseudo_bytes,
     ssleay_rand_cleanup,
     ssleay_rand_add,
     ssleay_rand_pseudo_bytes,
     ssleay_rand_status
 };
 
 RAND_METHOD *RAND_SSLeay(void)
 {
     return (&rand_ssleay_meth);
 }
 
 static void ssleay_rand_cleanup(void)
 {
     OPENSSL_cleanse(state, sizeof(state));
     state_num = 0;
     state_index = 0;
     OPENSSL_cleanse(md, MD_DIGEST_LENGTH);
     md_count[0] = 0;
     md_count[1] = 0;
     entropy = 0;
     initialized = 0;
 }
 
 static void ssleay_rand_add(const void *buf, int num, double add)
 {
     int i, j, k, st_idx;
     long md_c[2];
     unsigned char local_md[MD_DIGEST_LENGTH];
     EVP_MD_CTX m;
     int do_not_lock;
 
     if (!num)
         return;
 
     /*
      * (Based on the rand(3) manpage)
      *
      * The input is chopped up into units of 20 bytes (or less for
      * the last block).  Each of these blocks is run through the hash
      * function as follows:  The data passed to the hash function
      * is the current 'md', the same number of bytes from the 'state'
      * (the location determined by in incremented looping index) as
      * the current 'block', the new key data 'block', and 'count'
      * (which is incremented after each use).
      * The result of this is kept in 'md' and also xored into the
      * 'state' at the same locations that were used as input into the
      * hash function.
      */
 
     /* check if we already have the lock */
     if (crypto_lock_rand) {
         CRYPTO_THREADID cur;
         CRYPTO_THREADID_current(&cur);
         CRYPTO_r_lock(CRYPTO_LOCK_RAND2);
         do_not_lock = !CRYPTO_THREADID_cmp(&locking_threadid, &cur);
         CRYPTO_r_unlock(CRYPTO_LOCK_RAND2);
     } else
         do_not_lock = 0;
 
     if (!do_not_lock)
         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
     st_idx = state_index;
 
     /*
      * use our own copies of the counters so that even if a concurrent thread
      * seeds with exactly the same data and uses the same subarray there's
      * _some_ difference
      */
     md_c[0] = md_count[0];
     md_c[1] = md_count[1];
 
     memcpy(local_md, md, sizeof md);
 
     /* state_index <= state_num <= STATE_SIZE */
     state_index += num;
     if (state_index >= STATE_SIZE) {
         state_index %= STATE_SIZE;
         state_num = STATE_SIZE;
     } else if (state_num < STATE_SIZE) {
         if (state_index > state_num)
             state_num = state_index;
     }
     /* state_index <= state_num <= STATE_SIZE */
 
     /*
      * state[st_idx], ..., state[(st_idx + num - 1) % STATE_SIZE] are what we
      * will use now, but other threads may use them as well
      */
 
     md_count[1] += (num / MD_DIGEST_LENGTH) + (num % MD_DIGEST_LENGTH > 0);
 
     if (!do_not_lock)
         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
 
     EVP_MD_CTX_init(&m);
     for (i = 0; i < num; i += MD_DIGEST_LENGTH) {
         j = (num - i);
         j = (j > MD_DIGEST_LENGTH) ? MD_DIGEST_LENGTH : j;
 
-        MD_Init(&m);
-        MD_Update(&m, local_md, MD_DIGEST_LENGTH);
+        if (!MD_Init(&m) ||
+            !MD_Update(&m, local_md, MD_DIGEST_LENGTH))
+            goto err;
         k = (st_idx + j) - STATE_SIZE;
         if (k > 0) {
-            MD_Update(&m, &(state[st_idx]), j - k);
-            MD_Update(&m, &(state[0]), k);
+            if (!MD_Update(&m, &(state[st_idx]), j - k) ||
+                !MD_Update(&m, &(state[0]), k))
+                goto err;
         } else
-            MD_Update(&m, &(state[st_idx]), j);
+            if (!MD_Update(&m, &(state[st_idx]), j))
+                goto err;
 
         /* DO NOT REMOVE THE FOLLOWING CALL TO MD_Update()! */
-        MD_Update(&m, buf, j);
+        if (!MD_Update(&m, buf, j))
+            goto err;
         /*
          * We know that line may cause programs such as purify and valgrind
          * to complain about use of uninitialized data.  The problem is not,
          * it's with the caller.  Removing that line will make sure you get
          * really bad randomness and thereby other problems such as very
          * insecure keys.
          */
 
-        MD_Update(&m, (unsigned char *)&(md_c[0]), sizeof(md_c));
-        MD_Final(&m, local_md);
+        if (!MD_Update(&m, (unsigned char *)&(md_c[0]), sizeof(md_c)) ||
+            !MD_Final(&m, local_md))
+            goto err;
         md_c[1]++;
 
         buf = (const char *)buf + j;
 
         for (k = 0; k < j; k++) {
             /*
              * Parallel threads may interfere with this, but always each byte
              * of the new state is the XOR of some previous value of its and
              * local_md (itermediate values may be lost). Alway using locking
              * could hurt performance more than necessary given that
              * conflicts occur only when the total seeding is longer than the
              * random state.
              */
             state[st_idx++] ^= local_md[k];
             if (st_idx >= STATE_SIZE)
                 st_idx = 0;
         }
     }
-    EVP_MD_CTX_cleanup(&m);
 
     if (!do_not_lock)
         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
     /*
      * Don't just copy back local_md into md -- this could mean that other
      * thread's seeding remains without effect (except for the incremented
      * counter).  By XORing it we keep at least as much entropy as fits into
      * md.
      */
     for (k = 0; k < (int)sizeof(md); k++) {
         md[k] ^= local_md[k];
     }
     if (entropy < ENTROPY_NEEDED) /* stop counting when we have enough */
         entropy += add;
     if (!do_not_lock)
         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
 
 #if !defined(OPENSSL_THREADS) && !defined(OPENSSL_SYS_WIN32)
     assert(md_c[1] == md_count[1]);
 #endif
+
+ err:
+    EVP_MD_CTX_cleanup(&m);
 }
 
 static void ssleay_rand_seed(const void *buf, int num)
 {
     ssleay_rand_add(buf, num, (double)num);
 }
 
 int ssleay_rand_bytes(unsigned char *buf, int num, int pseudo, int lock)
 {
     static volatile int stirred_pool = 0;
     int i, j, k;
     size_t num_ceil, st_idx, st_num;
     int ok;
     long md_c[2];
     unsigned char local_md[MD_DIGEST_LENGTH];
     EVP_MD_CTX m;
 #ifndef GETPID_IS_MEANINGLESS
     pid_t curr_pid = getpid();
 #endif
     int do_stir_pool = 0;
 
 #ifdef PREDICT
     if (rand_predictable) {
         static unsigned char val = 0;
 
         for (i = 0; i < num; i++)
             buf[i] = val++;
         return (1);
     }
 #endif
 
     if (num <= 0)
         return 1;
 
     EVP_MD_CTX_init(&m);
     /* round upwards to multiple of MD_DIGEST_LENGTH/2 */
     num_ceil =
         (1 + (num - 1) / (MD_DIGEST_LENGTH / 2)) * (MD_DIGEST_LENGTH / 2);
 
     /*
      * (Based on the rand(3) manpage:)
      *
      * For each group of 10 bytes (or less), we do the following:
      *
      * Input into the hash function the local 'md' (which is initialized from
      * the global 'md' before any bytes are generated), the bytes that are to
      * be overwritten by the random bytes, and bytes from the 'state'
      * (incrementing looping index). From this digest output (which is kept
      * in 'md'), the top (up to) 10 bytes are returned to the caller and the
      * bottom 10 bytes are xored into the 'state'.
      *
      * Finally, after we have finished 'num' random bytes for the
      * caller, 'count' (which is incremented) and the local and global 'md'
      * are fed into the hash function and the results are kept in the
      * global 'md'.
      */
     if (lock)
         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
 
     /* prevent ssleay_rand_bytes() from trying to obtain the lock again */
     CRYPTO_w_lock(CRYPTO_LOCK_RAND2);
     CRYPTO_THREADID_current(&locking_threadid);
     CRYPTO_w_unlock(CRYPTO_LOCK_RAND2);
     crypto_lock_rand = 1;
 
     if (!initialized) {
         RAND_poll();
         initialized = 1;
     }
 
     if (!stirred_pool)
         do_stir_pool = 1;
 
     ok = (entropy >= ENTROPY_NEEDED);
     if (!ok) {
         /*
          * If the PRNG state is not yet unpredictable, then seeing the PRNG
          * output may help attackers to determine the new state; thus we have
          * to decrease the entropy estimate. Once we've had enough initial
          * seeding we don't bother to adjust the entropy count, though,
          * because we're not ambitious to provide *information-theoretic*
          * randomness. NOTE: This approach fails if the program forks before
          * we have enough entropy. Entropy should be collected in a separate
          * input pool and be transferred to the output pool only when the
          * entropy limit has been reached.
          */
         entropy -= num;
         if (entropy < 0)
             entropy = 0;
     }
 
     if (do_stir_pool) {
         /*
          * In the output function only half of 'md' remains secret, so we
          * better make sure that the required entropy gets 'evenly
          * distributed' through 'state', our randomness pool. The input
          * function (ssleay_rand_add) chains all of 'md', which makes it more
          * suitable for this purpose.
          */
 
         int n = STATE_SIZE;     /* so that the complete pool gets accessed */
         while (n > 0) {
 #if MD_DIGEST_LENGTH > 20
 # error "Please adjust DUMMY_SEED."
 #endif
 #define DUMMY_SEED "...................." /* at least MD_DIGEST_LENGTH */
             /*
              * Note that the seed does not matter, it's just that
              * ssleay_rand_add expects to have something to hash.
              */
             ssleay_rand_add(DUMMY_SEED, MD_DIGEST_LENGTH, 0.0);
             n -= MD_DIGEST_LENGTH;
         }
         if (ok)
             stirred_pool = 1;
     }
 
     st_idx = state_index;
     st_num = state_num;
     md_c[0] = md_count[0];
     md_c[1] = md_count[1];
     memcpy(local_md, md, sizeof md);
 
     state_index += num_ceil;
     if (state_index > state_num)
         state_index %= state_num;
 
     /*
      * state[st_idx], ..., state[(st_idx + num_ceil - 1) % st_num] are now
      * ours (but other threads may use them too)
      */
 
     md_count[0] += 1;
 
     /* before unlocking, we must clear 'crypto_lock_rand' */
     crypto_lock_rand = 0;
     if (lock)
         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
 
     while (num > 0) {
         /* num_ceil -= MD_DIGEST_LENGTH/2 */
         j = (num >= MD_DIGEST_LENGTH / 2) ? MD_DIGEST_LENGTH / 2 : num;
         num -= j;
-        MD_Init(&m);
+        if (!MD_Init(&m))
+           goto err;
 #ifndef GETPID_IS_MEANINGLESS
         if (curr_pid) {         /* just in the first iteration to save time */
-            MD_Update(&m, (unsigned char *)&curr_pid, sizeof curr_pid);
+            if (!MD_Update(&m, (unsigned char *)&curr_pid, sizeof curr_pid))
+                goto err;
             curr_pid = 0;
         }
 #endif
-        MD_Update(&m, local_md, MD_DIGEST_LENGTH);
-        MD_Update(&m, (unsigned char *)&(md_c[0]), sizeof(md_c));
+        if (!MD_Update(&m, local_md, MD_DIGEST_LENGTH) ||
+            !MD_Update(&m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
+            goto err;
 
 #ifndef PURIFY                  /* purify complains */
         /*
          * The following line uses the supplied buffer as a small source of
          * entropy: since this buffer is often uninitialised it may cause
          * programs such as purify or valgrind to complain. So for those
          * builds it is not used: the removal of such a small source of
          * entropy has negligible impact on security.
          */
-        MD_Update(&m, buf, j);
+        if (!MD_Update(&m, buf, j))
+            goto err;
 #endif
 
         k = (st_idx + MD_DIGEST_LENGTH / 2) - st_num;
         if (k > 0) {
-            MD_Update(&m, &(state[st_idx]), MD_DIGEST_LENGTH / 2 - k);
-            MD_Update(&m, &(state[0]), k);
-        } else
-            MD_Update(&m, &(state[st_idx]), MD_DIGEST_LENGTH / 2);
-        MD_Final(&m, local_md);
+            if (!MD_Update(&m, &(state[st_idx]), MD_DIGEST_LENGTH / 2 - k) ||
+                !MD_Update(&m, &(state[0]), k))
+                goto err;
+        } else {
+            if (!MD_Update(&m, &(state[st_idx]), MD_DIGEST_LENGTH / 2))
+                goto err;
+        }
+        if (!MD_Final(&m, local_md))
+            goto err;
 
         for (i = 0; i < MD_DIGEST_LENGTH / 2; i++) {
             /* may compete with other threads */
             state[st_idx++] ^= local_md[i];
             if (st_idx >= st_num)
                 st_idx = 0;
             if (i < j)
                 *(buf++) = local_md[i + MD_DIGEST_LENGTH / 2];
         }
     }
 
-    MD_Init(&m);
-    MD_Update(&m, (unsigned char *)&(md_c[0]), sizeof(md_c));
-    MD_Update(&m, local_md, MD_DIGEST_LENGTH);
+    if (!MD_Init(&m) ||
+        !MD_Update(&m, (unsigned char *)&(md_c[0]), sizeof(md_c)) ||
+        !MD_Update(&m, local_md, MD_DIGEST_LENGTH))
+        goto err;
     if (lock)
         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
-    MD_Update(&m, md, MD_DIGEST_LENGTH);
-    MD_Final(&m, md);
+    if (!MD_Update(&m, md, MD_DIGEST_LENGTH) ||
+        !MD_Final(&m, md)) {
+        if (lock)
+            CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
+        goto err;
+    }
     if (lock)
         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
 
     EVP_MD_CTX_cleanup(&m);
     if (ok)
         return (1);
     else if (pseudo)
         return 0;
     else {
         RANDerr(RAND_F_SSLEAY_RAND_BYTES, RAND_R_PRNG_NOT_SEEDED);
         ERR_add_error_data(1, "You need to read the OpenSSL FAQ, "
                            "http://www.openssl.org/support/faq.html");
         return (0);
     }
+
+ err:
+    EVP_MD_CTX_cleanup(&m);
+    return (0);
 }
 
 static int ssleay_rand_nopseudo_bytes(unsigned char *buf, int num)
 {
     return ssleay_rand_bytes(buf, num, 0, 1);
 }
 
 /*
  * pseudo-random bytes that are guaranteed to be unique but not unpredictable
  */
 static int ssleay_rand_pseudo_bytes(unsigned char *buf, int num)
 {
     return ssleay_rand_bytes(buf, num, 1, 1);
 }
 
 static int ssleay_rand_status(void)
 {
     CRYPTO_THREADID cur;
     int ret;
     int do_not_lock;
 
     CRYPTO_THREADID_current(&cur);
     /*
      * check if we already have the lock (could happen if a RAND_poll()
      * implementation calls RAND_status())
      */
     if (crypto_lock_rand) {
         CRYPTO_r_lock(CRYPTO_LOCK_RAND2);
         do_not_lock = !CRYPTO_THREADID_cmp(&locking_threadid, &cur);
         CRYPTO_r_unlock(CRYPTO_LOCK_RAND2);
     } else
         do_not_lock = 0;
 
     if (!do_not_lock) {
         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
 
         /*
          * prevent ssleay_rand_bytes() from trying to obtain the lock again
          */
         CRYPTO_w_lock(CRYPTO_LOCK_RAND2);
         CRYPTO_THREADID_cpy(&locking_threadid, &cur);
         CRYPTO_w_unlock(CRYPTO_LOCK_RAND2);
         crypto_lock_rand = 1;
     }
 
     if (!initialized) {
         RAND_poll();
         initialized = 1;
     }
 
     ret = entropy >= ENTROPY_NEEDED;
 
     if (!do_not_lock) {
         /* before unlocking, we must clear 'crypto_lock_rand' */
         crypto_lock_rand = 0;
 
         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
     }
 
     return ret;
 }
Index: vendor-crypto/openssl/dist/crypto/rc4/Makefile
===================================================================
--- vendor-crypto/openssl/dist/crypto/rc4/Makefile	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/rc4/Makefile	(revision 318897)
@@ -1,127 +1,127 @@
 #
 # OpenSSL/crypto/rc4/Makefile
 #
 
 DIR=	rc4
 TOP=	../..
 CC=	cc
 CPP=    $(CC) -E
 INCLUDES=
 CFLAG=-g
 AR=		ar r
 
 RC4_ENC=rc4_enc.o rc4_skey.o
 
 CFLAGS= $(INCLUDES) $(CFLAG)
 ASFLAGS= $(INCLUDES) $(ASFLAG)
 AFLAGS= $(ASFLAGS)
 
 GENERAL=Makefile
 TEST=rc4test.c
 APPS=
 
 LIB=$(TOP)/libcrypto.a
 LIBSRC=rc4_skey.c rc4_enc.c rc4_utl.c
 LIBOBJ=$(RC4_ENC) rc4_utl.o
 
 SRC= $(LIBSRC)
 
 EXHEADER= rc4.h
 HEADER=	$(EXHEADER) rc4_locl.h
 
 ALL=    $(GENERAL) $(SRC) $(HEADER)
 
 top:
 	(cd ../..; $(MAKE) DIRS=crypto SDIRS=$(DIR) sub_all)
 
 all:	lib
 
 lib:	$(LIBOBJ)
 	$(AR) $(LIB) $(LIBOBJ)
 	$(RANLIB) $(LIB) || echo Never mind.
 	@touch lib
 
 rc4-586.s:	asm/rc4-586.pl ../perlasm/x86asm.pl
 	$(PERL) asm/rc4-586.pl $(PERLASM_SCHEME) $(CFLAGS) $(PROCESSOR) > $@
 
 rc4-x86_64.s: asm/rc4-x86_64.pl
 	$(PERL) asm/rc4-x86_64.pl $(PERLASM_SCHEME) > $@
 rc4-md5-x86_64.s:	asm/rc4-md5-x86_64.pl
 	$(PERL) asm/rc4-md5-x86_64.pl $(PERLASM_SCHEME) > $@
 
 rc4-ia64.S: asm/rc4-ia64.pl
 	$(PERL) asm/rc4-ia64.pl $(CFLAGS) > $@
 
 rc4-parisc.s:	asm/rc4-parisc.pl
 	$(PERL) asm/rc4-parisc.pl $(PERLASM_SCHEME) $@
 
 rc4-ia64.s: rc4-ia64.S
 	@case `awk '/^#define RC4_INT/{print$$NF}' $(TOP)/include/openssl/opensslconf.h` in \
 	int)	set -x; $(CC) $(CFLAGS) -DSZ=4 -E rc4-ia64.S > $@ ;; \
 	char)	set -x; $(CC) $(CFLAGS) -DSZ=1 -E rc4-ia64.S > $@ ;; \
 	*)	exit 1 ;; \
 	esac
 
 # GNU make "catch all"
 rc4-%.s:	asm/rc4-%.pl;	$(PERL) $< $(PERLASM_SCHEME) $@
 
 files:
 	$(PERL) $(TOP)/util/files.pl "RC4_ENC=$(RC4_ENC)" Makefile >> $(TOP)/MINFO
 
 links:
 	@$(PERL) $(TOP)/util/mklink.pl ../../include/openssl $(EXHEADER)
 	@$(PERL) $(TOP)/util/mklink.pl ../../test $(TEST)
 	@$(PERL) $(TOP)/util/mklink.pl ../../apps $(APPS)
 
 install:
 	@[ -n "$(INSTALLTOP)" ] # should be set by top Makefile...
 	@headerlist="$(EXHEADER)"; for i in $$headerlist ; \
 	do  \
 	(cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i; \
 	chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i ); \
 	done;
 
 tags:
 	ctags $(SRC)
 
 tests:
 
 lint:
 	lint -DLINT $(INCLUDES) $(SRC)>fluff
 
 update: depend
 
 depend:
 	@[ -n "$(MAKEDEPEND)" ] # should be set by upper Makefile...
 	$(MAKEDEPEND) -- $(CFLAG) $(INCLUDES) $(DEPFLAG) -- $(PROGS) $(LIBSRC)
 
 dclean:
 	$(PERL) -pe 'if (/^# DO NOT DELETE THIS LINE/) {print; exit(0);}' $(MAKEFILE) >Makefile.new
 	mv -f Makefile.new $(MAKEFILE)
 
 clean:
-	rm -f *.s *.o *.obj lib tags core .pure .nfs* *.old *.bak fluff
+	rm -f *.s *.S *.o *.obj lib tags core .pure .nfs* *.old *.bak fluff
 
 # DO NOT DELETE THIS LINE -- make depend depends on it.
 
 rc4_enc.o: ../../e_os.h ../../include/openssl/bio.h
 rc4_enc.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 rc4_enc.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 rc4_enc.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 rc4_enc.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 rc4_enc.o: ../../include/openssl/rc4.h ../../include/openssl/safestack.h
 rc4_enc.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 rc4_enc.o: ../cryptlib.h rc4_enc.c rc4_locl.h
 rc4_skey.o: ../../e_os.h ../../include/openssl/bio.h
 rc4_skey.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 rc4_skey.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 rc4_skey.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 rc4_skey.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 rc4_skey.o: ../../include/openssl/rc4.h ../../include/openssl/safestack.h
 rc4_skey.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 rc4_skey.o: ../cryptlib.h rc4_locl.h rc4_skey.c
 rc4_utl.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
 rc4_utl.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h
 rc4_utl.o: ../../include/openssl/ossl_typ.h ../../include/openssl/rc4.h
 rc4_utl.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h
 rc4_utl.o: ../../include/openssl/symhacks.h rc4_utl.c
Index: vendor-crypto/openssl/dist/crypto/rsa/rsa_pmeth.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/rsa/rsa_pmeth.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/rsa/rsa_pmeth.c	(revision 318897)
@@ -1,790 +1,785 @@
 /* crypto/rsa/rsa_pmeth.c */
 /*
  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
  * 2006.
  */
 /* ====================================================================
  * Copyright (c) 2006 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    licensing@OpenSSL.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #include 
 #include "cryptlib.h"
 #include 
 #include 
 #include 
 #include 
 #include 
 #include 
 #ifndef OPENSSL_NO_CMS
 # include 
 #endif
 #ifdef OPENSSL_FIPS
 # include 
 #endif
 #include "evp_locl.h"
 #include "rsa_locl.h"
 
 /* RSA pkey context structure */
 
 typedef struct {
     /* Key gen parameters */
     int nbits;
     BIGNUM *pub_exp;
     /* Keygen callback info */
     int gentmp[2];
     /* RSA padding mode */
     int pad_mode;
     /* message digest */
     const EVP_MD *md;
     /* message digest for MGF1 */
     const EVP_MD *mgf1md;
     /* PSS salt length */
     int saltlen;
     /* Temp buffer */
     unsigned char *tbuf;
     /* OAEP label */
     unsigned char *oaep_label;
     size_t oaep_labellen;
 } RSA_PKEY_CTX;
 
 static int pkey_rsa_init(EVP_PKEY_CTX *ctx)
 {
     RSA_PKEY_CTX *rctx;
     rctx = OPENSSL_malloc(sizeof(RSA_PKEY_CTX));
     if (!rctx)
         return 0;
     rctx->nbits = 1024;
     rctx->pub_exp = NULL;
     rctx->pad_mode = RSA_PKCS1_PADDING;
     rctx->md = NULL;
     rctx->mgf1md = NULL;
     rctx->tbuf = NULL;
 
     rctx->saltlen = -2;
 
     rctx->oaep_label = NULL;
     rctx->oaep_labellen = 0;
 
     ctx->data = rctx;
     ctx->keygen_info = rctx->gentmp;
     ctx->keygen_info_count = 2;
 
     return 1;
 }
 
 static int pkey_rsa_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src)
 {
     RSA_PKEY_CTX *dctx, *sctx;
     if (!pkey_rsa_init(dst))
         return 0;
     sctx = src->data;
     dctx = dst->data;
     dctx->nbits = sctx->nbits;
     if (sctx->pub_exp) {
         dctx->pub_exp = BN_dup(sctx->pub_exp);
         if (!dctx->pub_exp)
             return 0;
     }
     dctx->pad_mode = sctx->pad_mode;
     dctx->md = sctx->md;
     dctx->mgf1md = sctx->mgf1md;
     if (sctx->oaep_label) {
         if (dctx->oaep_label)
             OPENSSL_free(dctx->oaep_label);
         dctx->oaep_label = BUF_memdup(sctx->oaep_label, sctx->oaep_labellen);
         if (!dctx->oaep_label)
             return 0;
         dctx->oaep_labellen = sctx->oaep_labellen;
     }
     return 1;
 }
 
 static int setup_tbuf(RSA_PKEY_CTX *ctx, EVP_PKEY_CTX *pk)
 {
     if (ctx->tbuf)
         return 1;
     ctx->tbuf = OPENSSL_malloc(EVP_PKEY_size(pk->pkey));
     if (!ctx->tbuf)
         return 0;
     return 1;
 }
 
 static void pkey_rsa_cleanup(EVP_PKEY_CTX *ctx)
 {
     RSA_PKEY_CTX *rctx = ctx->data;
     if (rctx) {
         if (rctx->pub_exp)
             BN_free(rctx->pub_exp);
         if (rctx->tbuf)
             OPENSSL_free(rctx->tbuf);
         if (rctx->oaep_label)
             OPENSSL_free(rctx->oaep_label);
         OPENSSL_free(rctx);
     }
 }
 
 #ifdef OPENSSL_FIPS
 /*
  * FIP checker. Return value indicates status of context parameters: 1 :
  * redirect to FIPS. 0 : don't redirect to FIPS. -1 : illegal operation in
  * FIPS mode.
  */
 
 static int pkey_fips_check_ctx(EVP_PKEY_CTX *ctx)
 {
     RSA_PKEY_CTX *rctx = ctx->data;
     RSA *rsa = ctx->pkey->pkey.rsa;
     int rv = -1;
     if (!FIPS_mode())
         return 0;
     if (rsa->flags & RSA_FLAG_NON_FIPS_ALLOW)
         rv = 0;
     if (!(rsa->meth->flags & RSA_FLAG_FIPS_METHOD) && rv)
         return -1;
     if (rctx->md) {
         const EVP_MD *fmd;
         fmd = FIPS_get_digestbynid(EVP_MD_type(rctx->md));
         if (!fmd || !(fmd->flags & EVP_MD_FLAG_FIPS))
             return rv;
     }
     if (rctx->mgf1md && !(rctx->mgf1md->flags & EVP_MD_FLAG_FIPS)) {
         const EVP_MD *fmd;
         fmd = FIPS_get_digestbynid(EVP_MD_type(rctx->mgf1md));
         if (!fmd || !(fmd->flags & EVP_MD_FLAG_FIPS))
             return rv;
     }
     return 1;
 }
 #endif
 
 static int pkey_rsa_sign(EVP_PKEY_CTX *ctx, unsigned char *sig,
                          size_t *siglen, const unsigned char *tbs,
                          size_t tbslen)
 {
     int ret;
     RSA_PKEY_CTX *rctx = ctx->data;
     RSA *rsa = ctx->pkey->pkey.rsa;
 
 #ifdef OPENSSL_FIPS
     ret = pkey_fips_check_ctx(ctx);
     if (ret < 0) {
         RSAerr(RSA_F_PKEY_RSA_SIGN, RSA_R_OPERATION_NOT_ALLOWED_IN_FIPS_MODE);
         return -1;
     }
 #endif
 
     if (rctx->md) {
         if (tbslen != (size_t)EVP_MD_size(rctx->md)) {
             RSAerr(RSA_F_PKEY_RSA_SIGN, RSA_R_INVALID_DIGEST_LENGTH);
             return -1;
         }
 #ifdef OPENSSL_FIPS
         if (ret > 0) {
             unsigned int slen;
             ret = FIPS_rsa_sign_digest(rsa, tbs, tbslen, rctx->md,
                                        rctx->pad_mode,
                                        rctx->saltlen,
                                        rctx->mgf1md, sig, &slen);
             if (ret > 0)
                 *siglen = slen;
             else
                 *siglen = 0;
             return ret;
         }
 #endif
 
         if (EVP_MD_type(rctx->md) == NID_mdc2) {
             unsigned int sltmp;
             if (rctx->pad_mode != RSA_PKCS1_PADDING)
                 return -1;
             ret = RSA_sign_ASN1_OCTET_STRING(NID_mdc2,
                                              tbs, tbslen, sig, &sltmp, rsa);
 
             if (ret <= 0)
                 return ret;
             ret = sltmp;
         } else if (rctx->pad_mode == RSA_X931_PADDING) {
             if ((size_t)EVP_PKEY_size(ctx->pkey) < tbslen + 1) {
                 RSAerr(RSA_F_PKEY_RSA_SIGN, RSA_R_KEY_SIZE_TOO_SMALL);
                 return -1;
             }
             if (!setup_tbuf(rctx, ctx)) {
                 RSAerr(RSA_F_PKEY_RSA_SIGN, ERR_R_MALLOC_FAILURE);
                 return -1;
             }
             memcpy(rctx->tbuf, tbs, tbslen);
             rctx->tbuf[tbslen] = RSA_X931_hash_id(EVP_MD_type(rctx->md));
             ret = RSA_private_encrypt(tbslen + 1, rctx->tbuf,
                                       sig, rsa, RSA_X931_PADDING);
         } else if (rctx->pad_mode == RSA_PKCS1_PADDING) {
             unsigned int sltmp;
             ret = RSA_sign(EVP_MD_type(rctx->md),
                            tbs, tbslen, sig, &sltmp, rsa);
             if (ret <= 0)
                 return ret;
             ret = sltmp;
         } else if (rctx->pad_mode == RSA_PKCS1_PSS_PADDING) {
             if (!setup_tbuf(rctx, ctx))
                 return -1;
             if (!RSA_padding_add_PKCS1_PSS_mgf1(rsa,
                                                 rctx->tbuf, tbs,
                                                 rctx->md, rctx->mgf1md,
                                                 rctx->saltlen))
                 return -1;
             ret = RSA_private_encrypt(RSA_size(rsa), rctx->tbuf,
                                       sig, rsa, RSA_NO_PADDING);
         } else
             return -1;
     } else
         ret = RSA_private_encrypt(tbslen, tbs, sig, ctx->pkey->pkey.rsa,
                                   rctx->pad_mode);
     if (ret < 0)
         return ret;
     *siglen = ret;
     return 1;
 }
 
 static int pkey_rsa_verifyrecover(EVP_PKEY_CTX *ctx,
                                   unsigned char *rout, size_t *routlen,
                                   const unsigned char *sig, size_t siglen)
 {
     int ret;
     RSA_PKEY_CTX *rctx = ctx->data;
 
     if (rctx->md) {
         if (rctx->pad_mode == RSA_X931_PADDING) {
             if (!setup_tbuf(rctx, ctx))
                 return -1;
             ret = RSA_public_decrypt(siglen, sig,
                                      rctx->tbuf, ctx->pkey->pkey.rsa,
                                      RSA_X931_PADDING);
             if (ret < 1)
                 return 0;
             ret--;
             if (rctx->tbuf[ret] != RSA_X931_hash_id(EVP_MD_type(rctx->md))) {
                 RSAerr(RSA_F_PKEY_RSA_VERIFYRECOVER,
                        RSA_R_ALGORITHM_MISMATCH);
                 return 0;
             }
             if (ret != EVP_MD_size(rctx->md)) {
                 RSAerr(RSA_F_PKEY_RSA_VERIFYRECOVER,
                        RSA_R_INVALID_DIGEST_LENGTH);
                 return 0;
             }
             if (rout)
                 memcpy(rout, rctx->tbuf, ret);
         } else if (rctx->pad_mode == RSA_PKCS1_PADDING) {
             size_t sltmp;
             ret = int_rsa_verify(EVP_MD_type(rctx->md),
                                  NULL, 0, rout, &sltmp,
                                  sig, siglen, ctx->pkey->pkey.rsa);
             if (ret <= 0)
                 return 0;
             ret = sltmp;
         } else
             return -1;
     } else
         ret = RSA_public_decrypt(siglen, sig, rout, ctx->pkey->pkey.rsa,
                                  rctx->pad_mode);
     if (ret < 0)
         return ret;
     *routlen = ret;
     return 1;
 }
 
 static int pkey_rsa_verify(EVP_PKEY_CTX *ctx,
                            const unsigned char *sig, size_t siglen,
                            const unsigned char *tbs, size_t tbslen)
 {
     RSA_PKEY_CTX *rctx = ctx->data;
     RSA *rsa = ctx->pkey->pkey.rsa;
     size_t rslen;
 #ifdef OPENSSL_FIPS
     int rv;
     rv = pkey_fips_check_ctx(ctx);
     if (rv < 0) {
         RSAerr(RSA_F_PKEY_RSA_VERIFY,
                RSA_R_OPERATION_NOT_ALLOWED_IN_FIPS_MODE);
         return -1;
     }
 #endif
     if (rctx->md) {
 #ifdef OPENSSL_FIPS
         if (rv > 0) {
             return FIPS_rsa_verify_digest(rsa,
                                           tbs, tbslen,
                                           rctx->md,
                                           rctx->pad_mode,
                                           rctx->saltlen,
                                           rctx->mgf1md, sig, siglen);
 
         }
 #endif
         if (rctx->pad_mode == RSA_PKCS1_PADDING)
             return RSA_verify(EVP_MD_type(rctx->md), tbs, tbslen,
                               sig, siglen, rsa);
         if (tbslen != (size_t)EVP_MD_size(rctx->md)) {
             RSAerr(RSA_F_PKEY_RSA_VERIFY, RSA_R_INVALID_DIGEST_LENGTH);
             return -1;
         }
         if (rctx->pad_mode == RSA_X931_PADDING) {
             if (pkey_rsa_verifyrecover(ctx, NULL, &rslen, sig, siglen) <= 0)
                 return 0;
         } else if (rctx->pad_mode == RSA_PKCS1_PSS_PADDING) {
             int ret;
             if (!setup_tbuf(rctx, ctx))
                 return -1;
             ret = RSA_public_decrypt(siglen, sig, rctx->tbuf,
                                      rsa, RSA_NO_PADDING);
             if (ret <= 0)
                 return 0;
             ret = RSA_verify_PKCS1_PSS_mgf1(rsa, tbs,
                                             rctx->md, rctx->mgf1md,
                                             rctx->tbuf, rctx->saltlen);
             if (ret <= 0)
                 return 0;
             return 1;
         } else
             return -1;
     } else {
         if (!setup_tbuf(rctx, ctx))
             return -1;
         rslen = RSA_public_decrypt(siglen, sig, rctx->tbuf,
                                    rsa, rctx->pad_mode);
         if (rslen == 0)
             return 0;
     }
 
     if ((rslen != tbslen) || memcmp(tbs, rctx->tbuf, rslen))
         return 0;
 
     return 1;
 
 }
 
 static int pkey_rsa_encrypt(EVP_PKEY_CTX *ctx,
                             unsigned char *out, size_t *outlen,
                             const unsigned char *in, size_t inlen)
 {
     int ret;
     RSA_PKEY_CTX *rctx = ctx->data;
     if (rctx->pad_mode == RSA_PKCS1_OAEP_PADDING) {
         int klen = RSA_size(ctx->pkey->pkey.rsa);
         if (!setup_tbuf(rctx, ctx))
             return -1;
         if (!RSA_padding_add_PKCS1_OAEP_mgf1(rctx->tbuf, klen,
                                              in, inlen,
                                              rctx->oaep_label,
                                              rctx->oaep_labellen,
                                              rctx->md, rctx->mgf1md))
             return -1;
         ret = RSA_public_encrypt(klen, rctx->tbuf, out,
                                  ctx->pkey->pkey.rsa, RSA_NO_PADDING);
     } else
         ret = RSA_public_encrypt(inlen, in, out, ctx->pkey->pkey.rsa,
                                  rctx->pad_mode);
     if (ret < 0)
         return ret;
     *outlen = ret;
     return 1;
 }
 
 static int pkey_rsa_decrypt(EVP_PKEY_CTX *ctx,
                             unsigned char *out, size_t *outlen,
                             const unsigned char *in, size_t inlen)
 {
     int ret;
     RSA_PKEY_CTX *rctx = ctx->data;
     if (rctx->pad_mode == RSA_PKCS1_OAEP_PADDING) {
-        int i;
         if (!setup_tbuf(rctx, ctx))
             return -1;
         ret = RSA_private_decrypt(inlen, in, rctx->tbuf,
                                   ctx->pkey->pkey.rsa, RSA_NO_PADDING);
         if (ret <= 0)
             return ret;
-        for (i = 0; i < ret; i++) {
-            if (rctx->tbuf[i])
-                break;
-        }
-        ret = RSA_padding_check_PKCS1_OAEP_mgf1(out, ret, rctx->tbuf + i,
-                                                ret - i, ret,
+        ret = RSA_padding_check_PKCS1_OAEP_mgf1(out, ret, rctx->tbuf,
+                                                ret, ret,
                                                 rctx->oaep_label,
                                                 rctx->oaep_labellen,
                                                 rctx->md, rctx->mgf1md);
     } else
         ret = RSA_private_decrypt(inlen, in, out, ctx->pkey->pkey.rsa,
                                   rctx->pad_mode);
     if (ret < 0)
         return ret;
     *outlen = ret;
     return 1;
 }
 
 static int check_padding_md(const EVP_MD *md, int padding)
 {
     if (!md)
         return 1;
 
     if (padding == RSA_NO_PADDING) {
         RSAerr(RSA_F_CHECK_PADDING_MD, RSA_R_INVALID_PADDING_MODE);
         return 0;
     }
 
     if (padding == RSA_X931_PADDING) {
         if (RSA_X931_hash_id(EVP_MD_type(md)) == -1) {
             RSAerr(RSA_F_CHECK_PADDING_MD, RSA_R_INVALID_X931_DIGEST);
             return 0;
         }
         return 1;
     }
 
     return 1;
 }
 
 static int pkey_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2)
 {
     RSA_PKEY_CTX *rctx = ctx->data;
     switch (type) {
     case EVP_PKEY_CTRL_RSA_PADDING:
         if ((p1 >= RSA_PKCS1_PADDING) && (p1 <= RSA_PKCS1_PSS_PADDING)) {
             if (!check_padding_md(rctx->md, p1))
                 return 0;
             if (p1 == RSA_PKCS1_PSS_PADDING) {
                 if (!(ctx->operation &
                       (EVP_PKEY_OP_SIGN | EVP_PKEY_OP_VERIFY)))
                     goto bad_pad;
                 if (!rctx->md)
                     rctx->md = EVP_sha1();
             }
             if (p1 == RSA_PKCS1_OAEP_PADDING) {
                 if (!(ctx->operation & EVP_PKEY_OP_TYPE_CRYPT))
                     goto bad_pad;
                 if (!rctx->md)
                     rctx->md = EVP_sha1();
             }
             rctx->pad_mode = p1;
             return 1;
         }
  bad_pad:
         RSAerr(RSA_F_PKEY_RSA_CTRL,
                RSA_R_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE);
         return -2;
 
     case EVP_PKEY_CTRL_GET_RSA_PADDING:
         *(int *)p2 = rctx->pad_mode;
         return 1;
 
     case EVP_PKEY_CTRL_RSA_PSS_SALTLEN:
     case EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN:
         if (rctx->pad_mode != RSA_PKCS1_PSS_PADDING) {
             RSAerr(RSA_F_PKEY_RSA_CTRL, RSA_R_INVALID_PSS_SALTLEN);
             return -2;
         }
         if (type == EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN)
             *(int *)p2 = rctx->saltlen;
         else {
             if (p1 < -2)
                 return -2;
             rctx->saltlen = p1;
         }
         return 1;
 
     case EVP_PKEY_CTRL_RSA_KEYGEN_BITS:
         if (p1 < 256) {
             RSAerr(RSA_F_PKEY_RSA_CTRL, RSA_R_INVALID_KEYBITS);
             return -2;
         }
         rctx->nbits = p1;
         return 1;
 
     case EVP_PKEY_CTRL_RSA_KEYGEN_PUBEXP:
         if (p2 == NULL || !BN_is_odd((BIGNUM *)p2) || BN_is_one((BIGNUM *)p2)) {
             RSAerr(RSA_F_PKEY_RSA_CTRL, RSA_R_BAD_E_VALUE);
             return -2;
         }
         BN_free(rctx->pub_exp);
         rctx->pub_exp = p2;
         return 1;
 
     case EVP_PKEY_CTRL_RSA_OAEP_MD:
     case EVP_PKEY_CTRL_GET_RSA_OAEP_MD:
         if (rctx->pad_mode != RSA_PKCS1_OAEP_PADDING) {
             RSAerr(RSA_F_PKEY_RSA_CTRL, RSA_R_INVALID_PADDING_MODE);
             return -2;
         }
         if (type == EVP_PKEY_CTRL_GET_RSA_OAEP_MD)
             *(const EVP_MD **)p2 = rctx->md;
         else
             rctx->md = p2;
         return 1;
 
     case EVP_PKEY_CTRL_MD:
         if (!check_padding_md(p2, rctx->pad_mode))
             return 0;
         rctx->md = p2;
         return 1;
 
     case EVP_PKEY_CTRL_GET_MD:
         *(const EVP_MD **)p2 = rctx->md;
         return 1;
 
     case EVP_PKEY_CTRL_RSA_MGF1_MD:
     case EVP_PKEY_CTRL_GET_RSA_MGF1_MD:
         if (rctx->pad_mode != RSA_PKCS1_PSS_PADDING
             && rctx->pad_mode != RSA_PKCS1_OAEP_PADDING) {
             RSAerr(RSA_F_PKEY_RSA_CTRL, RSA_R_INVALID_MGF1_MD);
             return -2;
         }
         if (type == EVP_PKEY_CTRL_GET_RSA_MGF1_MD) {
             if (rctx->mgf1md)
                 *(const EVP_MD **)p2 = rctx->mgf1md;
             else
                 *(const EVP_MD **)p2 = rctx->md;
         } else
             rctx->mgf1md = p2;
         return 1;
 
     case EVP_PKEY_CTRL_RSA_OAEP_LABEL:
         if (rctx->pad_mode != RSA_PKCS1_OAEP_PADDING) {
             RSAerr(RSA_F_PKEY_RSA_CTRL, RSA_R_INVALID_PADDING_MODE);
             return -2;
         }
         if (rctx->oaep_label)
             OPENSSL_free(rctx->oaep_label);
         if (p2 && p1 > 0) {
             rctx->oaep_label = p2;
             rctx->oaep_labellen = p1;
         } else {
             rctx->oaep_label = NULL;
             rctx->oaep_labellen = 0;
         }
         return 1;
 
     case EVP_PKEY_CTRL_GET_RSA_OAEP_LABEL:
         if (rctx->pad_mode != RSA_PKCS1_OAEP_PADDING) {
             RSAerr(RSA_F_PKEY_RSA_CTRL, RSA_R_INVALID_PADDING_MODE);
             return -2;
         }
         *(unsigned char **)p2 = rctx->oaep_label;
         return rctx->oaep_labellen;
 
     case EVP_PKEY_CTRL_DIGESTINIT:
     case EVP_PKEY_CTRL_PKCS7_ENCRYPT:
     case EVP_PKEY_CTRL_PKCS7_DECRYPT:
     case EVP_PKEY_CTRL_PKCS7_SIGN:
         return 1;
 #ifndef OPENSSL_NO_CMS
     case EVP_PKEY_CTRL_CMS_DECRYPT:
     case EVP_PKEY_CTRL_CMS_ENCRYPT:
     case EVP_PKEY_CTRL_CMS_SIGN:
         return 1;
 #endif
     case EVP_PKEY_CTRL_PEER_KEY:
         RSAerr(RSA_F_PKEY_RSA_CTRL,
                RSA_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
         return -2;
 
     default:
         return -2;
 
     }
 }
 
 static int pkey_rsa_ctrl_str(EVP_PKEY_CTX *ctx,
                              const char *type, const char *value)
 {
     if (!value) {
         RSAerr(RSA_F_PKEY_RSA_CTRL_STR, RSA_R_VALUE_MISSING);
         return 0;
     }
     if (!strcmp(type, "rsa_padding_mode")) {
         int pm;
         if (!strcmp(value, "pkcs1"))
             pm = RSA_PKCS1_PADDING;
         else if (!strcmp(value, "sslv23"))
             pm = RSA_SSLV23_PADDING;
         else if (!strcmp(value, "none"))
             pm = RSA_NO_PADDING;
         else if (!strcmp(value, "oeap"))
             pm = RSA_PKCS1_OAEP_PADDING;
         else if (!strcmp(value, "oaep"))
             pm = RSA_PKCS1_OAEP_PADDING;
         else if (!strcmp(value, "x931"))
             pm = RSA_X931_PADDING;
         else if (!strcmp(value, "pss"))
             pm = RSA_PKCS1_PSS_PADDING;
         else {
             RSAerr(RSA_F_PKEY_RSA_CTRL_STR, RSA_R_UNKNOWN_PADDING_TYPE);
             return -2;
         }
         return EVP_PKEY_CTX_set_rsa_padding(ctx, pm);
     }
 
     if (!strcmp(type, "rsa_pss_saltlen")) {
         int saltlen;
         saltlen = atoi(value);
         return EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx, saltlen);
     }
 
     if (!strcmp(type, "rsa_keygen_bits")) {
         int nbits;
         nbits = atoi(value);
         return EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, nbits);
     }
 
     if (!strcmp(type, "rsa_keygen_pubexp")) {
         int ret;
         BIGNUM *pubexp = NULL;
         if (!BN_asc2bn(&pubexp, value))
             return 0;
         ret = EVP_PKEY_CTX_set_rsa_keygen_pubexp(ctx, pubexp);
         if (ret <= 0)
             BN_free(pubexp);
         return ret;
     }
 
     if (!strcmp(type, "rsa_mgf1_md")) {
         const EVP_MD *md;
         if (!(md = EVP_get_digestbyname(value))) {
             RSAerr(RSA_F_PKEY_RSA_CTRL_STR, RSA_R_INVALID_DIGEST);
             return 0;
         }
         return EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, md);
     }
 
     if (!strcmp(type, "rsa_oaep_md")) {
         const EVP_MD *md;
         if (!(md = EVP_get_digestbyname(value))) {
             RSAerr(RSA_F_PKEY_RSA_CTRL_STR, RSA_R_INVALID_DIGEST);
             return 0;
         }
         return EVP_PKEY_CTX_set_rsa_oaep_md(ctx, md);
     }
     if (!strcmp(type, "rsa_oaep_label")) {
         unsigned char *lab;
         long lablen;
         int ret;
         lab = string_to_hex(value, &lablen);
         if (!lab)
             return 0;
         ret = EVP_PKEY_CTX_set0_rsa_oaep_label(ctx, lab, lablen);
         if (ret <= 0)
             OPENSSL_free(lab);
         return ret;
     }
 
     return -2;
 }
 
 static int pkey_rsa_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)
 {
     RSA *rsa = NULL;
     RSA_PKEY_CTX *rctx = ctx->data;
     BN_GENCB *pcb, cb;
     int ret;
     if (!rctx->pub_exp) {
         rctx->pub_exp = BN_new();
         if (!rctx->pub_exp || !BN_set_word(rctx->pub_exp, RSA_F4))
             return 0;
     }
     rsa = RSA_new();
     if (!rsa)
         return 0;
     if (ctx->pkey_gencb) {
         pcb = &cb;
         evp_pkey_set_cb_translate(pcb, ctx);
     } else
         pcb = NULL;
     ret = RSA_generate_key_ex(rsa, rctx->nbits, rctx->pub_exp, pcb);
     if (ret > 0)
         EVP_PKEY_assign_RSA(pkey, rsa);
     else
         RSA_free(rsa);
     return ret;
 }
 
 const EVP_PKEY_METHOD rsa_pkey_meth = {
     EVP_PKEY_RSA,
     EVP_PKEY_FLAG_AUTOARGLEN,
     pkey_rsa_init,
     pkey_rsa_copy,
     pkey_rsa_cleanup,
 
     0, 0,
 
     0,
     pkey_rsa_keygen,
 
     0,
     pkey_rsa_sign,
 
     0,
     pkey_rsa_verify,
 
     0,
     pkey_rsa_verifyrecover,
 
     0, 0, 0, 0,
 
     0,
     pkey_rsa_encrypt,
 
     0,
     pkey_rsa_decrypt,
 
     0, 0,
 
     pkey_rsa_ctrl,
     pkey_rsa_ctrl_str
 };
Index: vendor-crypto/openssl/dist/crypto/rsa/rsa_pss.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/rsa/rsa_pss.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/rsa/rsa_pss.c	(revision 318897)
@@ -1,290 +1,299 @@
 /* rsa_pss.c */
 /*
  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
  * 2005.
  */
 /* ====================================================================
  * Copyright (c) 2005 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    licensing@OpenSSL.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #include 
 #include "cryptlib.h"
 #include 
 #include 
 #include 
 #include 
 #include 
 
 static const unsigned char zeroes[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
 
 #if defined(_MSC_VER) && defined(_ARM_)
 # pragma optimize("g", off)
 #endif
 
 int RSA_verify_PKCS1_PSS(RSA *rsa, const unsigned char *mHash,
                          const EVP_MD *Hash, const unsigned char *EM,
                          int sLen)
 {
     return RSA_verify_PKCS1_PSS_mgf1(rsa, mHash, Hash, NULL, EM, sLen);
 }
 
 int RSA_verify_PKCS1_PSS_mgf1(RSA *rsa, const unsigned char *mHash,
                               const EVP_MD *Hash, const EVP_MD *mgf1Hash,
                               const unsigned char *EM, int sLen)
 {
     int i;
     int ret = 0;
     int hLen, maskedDBLen, MSBits, emLen;
     const unsigned char *H;
     unsigned char *DB = NULL;
     EVP_MD_CTX ctx;
     unsigned char H_[EVP_MAX_MD_SIZE];
     EVP_MD_CTX_init(&ctx);
 
     if (mgf1Hash == NULL)
         mgf1Hash = Hash;
 
     hLen = EVP_MD_size(Hash);
     if (hLen < 0)
         goto err;
     /*-
      * Negative sLen has special meanings:
      *      -1      sLen == hLen
      *      -2      salt length is autorecovered from signature
      *      -N      reserved
      */
     if (sLen == -1)
         sLen = hLen;
     else if (sLen == -2)
         sLen = -2;
     else if (sLen < -2) {
         RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_SLEN_CHECK_FAILED);
         goto err;
     }
 
     MSBits = (BN_num_bits(rsa->n) - 1) & 0x7;
     emLen = RSA_size(rsa);
     if (EM[0] & (0xFF << MSBits)) {
         RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_FIRST_OCTET_INVALID);
         goto err;
     }
     if (MSBits == 0) {
         EM++;
         emLen--;
     }
-    if (emLen < (hLen + sLen + 2)) { /* sLen can be small negative */
+    if (emLen < hLen + 2) {
         RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_DATA_TOO_LARGE);
         goto err;
     }
+    if (sLen > emLen - hLen - 2) { /* sLen can be small negative */
+        RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_DATA_TOO_LARGE);
+        goto err;
+    }
     if (EM[emLen - 1] != 0xbc) {
         RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_LAST_OCTET_INVALID);
         goto err;
     }
     maskedDBLen = emLen - hLen - 1;
     H = EM + maskedDBLen;
     DB = OPENSSL_malloc(maskedDBLen);
     if (!DB) {
         RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, ERR_R_MALLOC_FAILURE);
         goto err;
     }
     if (PKCS1_MGF1(DB, maskedDBLen, H, hLen, mgf1Hash) < 0)
         goto err;
     for (i = 0; i < maskedDBLen; i++)
         DB[i] ^= EM[i];
     if (MSBits)
         DB[0] &= 0xFF >> (8 - MSBits);
     for (i = 0; DB[i] == 0 && i < (maskedDBLen - 1); i++) ;
     if (DB[i++] != 0x1) {
         RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_SLEN_RECOVERY_FAILED);
         goto err;
     }
     if (sLen >= 0 && (maskedDBLen - i) != sLen) {
         RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_SLEN_CHECK_FAILED);
         goto err;
     }
     if (!EVP_DigestInit_ex(&ctx, Hash, NULL)
         || !EVP_DigestUpdate(&ctx, zeroes, sizeof zeroes)
         || !EVP_DigestUpdate(&ctx, mHash, hLen))
         goto err;
     if (maskedDBLen - i) {
         if (!EVP_DigestUpdate(&ctx, DB + i, maskedDBLen - i))
             goto err;
     }
     if (!EVP_DigestFinal_ex(&ctx, H_, NULL))
         goto err;
     if (memcmp(H_, H, hLen)) {
         RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_BAD_SIGNATURE);
         ret = 0;
     } else
         ret = 1;
 
  err:
     if (DB)
         OPENSSL_free(DB);
     EVP_MD_CTX_cleanup(&ctx);
 
     return ret;
 
 }
 
 int RSA_padding_add_PKCS1_PSS(RSA *rsa, unsigned char *EM,
                               const unsigned char *mHash,
                               const EVP_MD *Hash, int sLen)
 {
     return RSA_padding_add_PKCS1_PSS_mgf1(rsa, EM, mHash, Hash, NULL, sLen);
 }
 
 int RSA_padding_add_PKCS1_PSS_mgf1(RSA *rsa, unsigned char *EM,
                                    const unsigned char *mHash,
                                    const EVP_MD *Hash, const EVP_MD *mgf1Hash,
                                    int sLen)
 {
     int i;
     int ret = 0;
     int hLen, maskedDBLen, MSBits, emLen;
     unsigned char *H, *salt = NULL, *p;
     EVP_MD_CTX ctx;
 
     if (mgf1Hash == NULL)
         mgf1Hash = Hash;
 
     hLen = EVP_MD_size(Hash);
     if (hLen < 0)
         goto err;
     /*-
      * Negative sLen has special meanings:
      *      -1      sLen == hLen
      *      -2      salt length is maximized
      *      -N      reserved
      */
     if (sLen == -1)
         sLen = hLen;
     else if (sLen == -2)
         sLen = -2;
     else if (sLen < -2) {
         RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1, RSA_R_SLEN_CHECK_FAILED);
         goto err;
     }
 
     MSBits = (BN_num_bits(rsa->n) - 1) & 0x7;
     emLen = RSA_size(rsa);
     if (MSBits == 0) {
         *EM++ = 0;
         emLen--;
     }
+    if (emLen < hLen + 2) {
+        RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1,
+               RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
+        goto err;
+    }
     if (sLen == -2) {
         sLen = emLen - hLen - 2;
-    } else if (emLen < (hLen + sLen + 2)) {
+    } else if (sLen > emLen - hLen - 2) {
         RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1,
                RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
         goto err;
     }
     if (sLen > 0) {
         salt = OPENSSL_malloc(sLen);
         if (!salt) {
             RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1,
                    ERR_R_MALLOC_FAILURE);
             goto err;
         }
         if (RAND_bytes(salt, sLen) <= 0)
             goto err;
     }
     maskedDBLen = emLen - hLen - 1;
     H = EM + maskedDBLen;
     EVP_MD_CTX_init(&ctx);
     if (!EVP_DigestInit_ex(&ctx, Hash, NULL)
         || !EVP_DigestUpdate(&ctx, zeroes, sizeof zeroes)
         || !EVP_DigestUpdate(&ctx, mHash, hLen))
         goto err;
     if (sLen && !EVP_DigestUpdate(&ctx, salt, sLen))
         goto err;
     if (!EVP_DigestFinal_ex(&ctx, H, NULL))
         goto err;
     EVP_MD_CTX_cleanup(&ctx);
 
     /* Generate dbMask in place then perform XOR on it */
     if (PKCS1_MGF1(EM, maskedDBLen, H, hLen, mgf1Hash))
         goto err;
 
     p = EM;
 
     /*
      * Initial PS XORs with all zeroes which is a NOP so just update pointer.
      * Note from a test above this value is guaranteed to be non-negative.
      */
     p += emLen - sLen - hLen - 2;
     *p++ ^= 0x1;
     if (sLen > 0) {
         for (i = 0; i < sLen; i++)
             *p++ ^= salt[i];
     }
     if (MSBits)
         EM[0] &= 0xFF >> (8 - MSBits);
 
     /* H is already in place so just set final 0xbc */
 
     EM[emLen - 1] = 0xbc;
 
     ret = 1;
 
  err:
     if (salt)
         OPENSSL_free(salt);
 
     return ret;
 
 }
 
 #if defined(_MSC_VER)
 # pragma optimize("",on)
 #endif
Index: vendor-crypto/openssl/dist/crypto/sha/Makefile
===================================================================
--- vendor-crypto/openssl/dist/crypto/sha/Makefile	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/sha/Makefile	(revision 318897)
@@ -1,177 +1,177 @@
 #
 # OpenSSL/crypto/sha/Makefile
 #
 
 DIR=    sha
 TOP=    ../..
 CC=     cc
 CPP=    $(CC) -E
 INCLUDES=
 CFLAG=-g
 MAKEFILE=       Makefile
 AR=             ar r
 
 SHA1_ASM_OBJ=
 
 CFLAGS= $(INCLUDES) $(CFLAG)
 ASFLAGS= $(INCLUDES) $(ASFLAG)
 AFLAGS= $(ASFLAGS)
 
 GENERAL=Makefile
 TEST=shatest.c sha1test.c sha256t.c sha512t.c
 APPS=
 
 LIB=$(TOP)/libcrypto.a
 LIBSRC=sha_dgst.c sha1dgst.c sha_one.c sha1_one.c sha256.c sha512.c
 LIBOBJ=sha_dgst.o sha1dgst.o sha_one.o sha1_one.o sha256.o sha512.o $(SHA1_ASM_OBJ)
 
 SRC= $(LIBSRC)
 
 EXHEADER= sha.h
 HEADER= sha_locl.h $(EXHEADER)
 
 ALL=    $(GENERAL) $(SRC) $(HEADER)
 
 top:
 	(cd ../..; $(MAKE) DIRS=crypto SDIRS=$(DIR) sub_all)
 
 all:    lib
 
 lib:    $(LIBOBJ)
 	$(AR) $(LIB) $(LIBOBJ)
 	$(RANLIB) $(LIB) || echo Never mind.
 	@touch lib
 
 sha1-586.s:	asm/sha1-586.pl ../perlasm/x86asm.pl
 	$(PERL) asm/sha1-586.pl $(PERLASM_SCHEME) $(CFLAGS) $(PROCESSOR) > $@
 sha256-586.s:	asm/sha256-586.pl ../perlasm/x86asm.pl
 	$(PERL) asm/sha256-586.pl $(PERLASM_SCHEME) $(CFLAGS) $(PROCESSOR) > $@
 sha512-586.s:	asm/sha512-586.pl ../perlasm/x86asm.pl
 	$(PERL) asm/sha512-586.pl $(PERLASM_SCHEME) $(CFLAGS) $(PROCESSOR) > $@
 
 sha1-ia64.s:   asm/sha1-ia64.pl
 	(cd asm; $(PERL) sha1-ia64.pl ../$@ $(CFLAGS))
 sha256-ia64.s: asm/sha512-ia64.pl
 	(cd asm; $(PERL) sha512-ia64.pl ../$@ $(CFLAGS))
 sha512-ia64.s: asm/sha512-ia64.pl
 	(cd asm; $(PERL) sha512-ia64.pl ../$@ $(CFLAGS))
 
 sha256-armv4.S: asm/sha256-armv4.pl
 	$(PERL) $< $(PERLASM_SCHEME) $@
 
 sha1-alpha.s:	asm/sha1-alpha.pl
 	(preproc=$$$$.$@.S; trap "rm $$preproc" INT; \
 	$(PERL) asm/sha1-alpha.pl > $$preproc && \
 	$(CC) -E -P $$preproc > $@ && rm $$preproc)
 
 # Solaris make has to be explicitly told
 sha1-x86_64.s:	asm/sha1-x86_64.pl;	$(PERL) asm/sha1-x86_64.pl $(PERLASM_SCHEME) > $@
 sha1-mb-x86_64.s:	asm/sha1-mb-x86_64.pl;	$(PERL) asm/sha1-mb-x86_64.pl $(PERLASM_SCHEME) > $@
 sha256-x86_64.s:asm/sha512-x86_64.pl;	$(PERL) asm/sha512-x86_64.pl $(PERLASM_SCHEME) $@
 sha256-mb-x86_64.s:	asm/sha256-mb-x86_64.pl;	$(PERL) asm/sha256-mb-x86_64.pl $(PERLASM_SCHEME) > $@
 sha512-x86_64.s:asm/sha512-x86_64.pl;	$(PERL) asm/sha512-x86_64.pl $(PERLASM_SCHEME) $@
 sha1-sparcv9.S:	asm/sha1-sparcv9.pl;	$(PERL) asm/sha1-sparcv9.pl $@ $(CFLAGS)
 sha256-sparcv9.S:asm/sha512-sparcv9.pl;	$(PERL) asm/sha512-sparcv9.pl $@ $(CFLAGS)
 sha512-sparcv9.S:asm/sha512-sparcv9.pl;	$(PERL) asm/sha512-sparcv9.pl $@ $(CFLAGS)
 
 sha1-ppc.s:	asm/sha1-ppc.pl;	$(PERL) asm/sha1-ppc.pl $(PERLASM_SCHEME) $@
 sha256-ppc.s:	asm/sha512-ppc.pl;	$(PERL) asm/sha512-ppc.pl $(PERLASM_SCHEME) $@
 sha512-ppc.s:	asm/sha512-ppc.pl;	$(PERL) asm/sha512-ppc.pl $(PERLASM_SCHEME) $@
 sha256p8-ppc.s:	asm/sha512p8-ppc.pl;	$(PERL) asm/sha512p8-ppc.pl $(PERLASM_SCHEME) $@
 sha512p8-ppc.s:	asm/sha512p8-ppc.pl;	$(PERL) asm/sha512p8-ppc.pl $(PERLASM_SCHEME) $@
 
 sha1-parisc.s:	asm/sha1-parisc.pl;	$(PERL) asm/sha1-parisc.pl $(PERLASM_SCHEME) $@
 sha256-parisc.s:asm/sha512-parisc.pl;	$(PERL) asm/sha512-parisc.pl $(PERLASM_SCHEME) $@
 sha512-parisc.s:asm/sha512-parisc.pl;	$(PERL) asm/sha512-parisc.pl $(PERLASM_SCHEME) $@
 
 sha1-mips.S:	asm/sha1-mips.pl;	$(PERL) asm/sha1-mips.pl $(PERLASM_SCHEME) $@
 sha256-mips.S:	asm/sha512-mips.pl;	$(PERL) asm/sha512-mips.pl $(PERLASM_SCHEME) $@
 sha512-mips.S:	asm/sha512-mips.pl;	$(PERL) asm/sha512-mips.pl $(PERLASM_SCHEME) $@
 
 # GNU make "catch all"
 sha1-%.S:	asm/sha1-%.pl;		$(PERL) $< $(PERLASM_SCHEME) $@
 sha256-%.S:	asm/sha512-%.pl;	$(PERL) $< $(PERLASM_SCHEME) $@
 sha512-%.S:	asm/sha512-%.pl;	$(PERL) $< $(PERLASM_SCHEME) $@
 
 sha1-armv4-large.o:	sha1-armv4-large.S
 sha256-armv4.o:		sha256-armv4.S
 sha512-armv4.o:		sha512-armv4.S
 sha1-armv8.o:		sha1-armv8.S
 sha256-armv8.o:		sha256-armv8.S
 sha512-armv8.o:		sha512-armv8.S
 
 files:
 	$(PERL) $(TOP)/util/files.pl Makefile >> $(TOP)/MINFO
 
 links:
 	@$(PERL) $(TOP)/util/mklink.pl ../../include/openssl $(EXHEADER)
 	@$(PERL) $(TOP)/util/mklink.pl ../../test $(TEST)
 	@$(PERL) $(TOP)/util/mklink.pl ../../apps $(APPS)
 
 install:
 	@[ -n "$(INSTALLTOP)" ] # should be set by top Makefile...
 	@headerlist="$(EXHEADER)"; for i in $$headerlist ; \
 	do  \
 	(cp $$i $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i; \
 	chmod 644 $(INSTALL_PREFIX)$(INSTALLTOP)/include/openssl/$$i ); \
 	done;
 
 tags:
 	ctags $(SRC)
 
 tests:
 
 lint:
 	lint -DLINT $(INCLUDES) $(SRC)>fluff
 
 update: depend
 
 depend:
 	@[ -n "$(MAKEDEPEND)" ] # should be set by upper Makefile...
 	$(MAKEDEPEND) -- $(CFLAG) $(INCLUDES) $(DEPFLAG) -- $(PROGS) $(LIBSRC)
 
 dclean:
 	$(PERL) -pe 'if (/^# DO NOT DELETE THIS LINE/) {print; exit(0);}' $(MAKEFILE) >Makefile.new
 	mv -f Makefile.new $(MAKEFILE)
 
 clean:
-	rm -f *.s *.o *.obj lib tags core .pure .nfs* *.old *.bak fluff
+	rm -f *.s *.S *.o *.obj lib tags core .pure .nfs* *.old *.bak fluff
 
 # DO NOT DELETE THIS LINE -- make depend depends on it.
 
 sha1_one.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
 sha1_one.o: ../../include/openssl/opensslconf.h
 sha1_one.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 sha1_one.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h
 sha1_one.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 sha1_one.o: sha1_one.c
 sha1dgst.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
 sha1dgst.o: ../../include/openssl/opensslconf.h
 sha1dgst.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 sha1dgst.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h
 sha1dgst.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 sha1dgst.o: ../md32_common.h sha1dgst.c sha_locl.h
 sha256.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
 sha256.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h
 sha256.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h
 sha256.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
 sha256.o: ../../include/openssl/symhacks.h ../md32_common.h sha256.c
 sha512.o: ../../e_os.h ../../include/openssl/bio.h
 sha512.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h
 sha512.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h
 sha512.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h
 sha512.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 sha512.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h
 sha512.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 sha512.o: ../cryptlib.h sha512.c
 sha_dgst.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
 sha_dgst.o: ../../include/openssl/opensslconf.h
 sha_dgst.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h
 sha_dgst.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h
 sha_dgst.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h
 sha_dgst.o: ../md32_common.h sha_dgst.c sha_locl.h
 sha_one.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h
 sha_one.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h
 sha_one.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h
 sha_one.o: ../../include/openssl/sha.h ../../include/openssl/stack.h
 sha_one.o: ../../include/openssl/symhacks.h sha_one.c
Index: vendor-crypto/openssl/dist/crypto/srp/srp_vfy.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/srp/srp_vfy.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/srp/srp_vfy.c	(revision 318897)
@@ -1,724 +1,727 @@
 /* crypto/srp/srp_vfy.c */
 /*
  * Written by Christophe Renou (christophe.renou@edelweb.fr) with the
  * precious help of Peter Sylvester (peter.sylvester@edelweb.fr) for the
  * EdelKey project and contributed to the OpenSSL project 2004.
  */
 /* ====================================================================
  * Copyright (c) 2004 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    licensing@OpenSSL.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 #ifndef OPENSSL_NO_SRP
 # include "cryptlib.h"
 # include "srp_lcl.h"
 # include 
 # include 
 # include 
 # include 
 # include 
 
 # define SRP_RANDOM_SALT_LEN 20
 # define MAX_LEN 2500
 
 static char b64table[] =
     "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz./";
 
 /*
  * the following two conversion routines have been inspired by code from
  * Stanford
  */
 
 /*
  * Convert a base64 string into raw byte array representation.
  */
 static int t_fromb64(unsigned char *a, size_t alen, const char *src)
 {
     char *loc;
     int i, j;
     int size;
 
+    if (alen == 0 || alen > INT_MAX)
+        return -1;
+
     while (*src && (*src == ' ' || *src == '\t' || *src == '\n'))
         ++src;
     size = strlen(src);
-    if (alen > INT_MAX || size > (int)alen)
+    if (size < 0 || size >= (int)alen)
         return -1;
 
     i = 0;
     while (i < size) {
         loc = strchr(b64table, src[i]);
         if (loc == (char *)0)
             break;
         else
             a[i] = loc - b64table;
         ++i;
     }
     /* if nothing valid to process we have a zero length response */
     if (i == 0)
         return 0;
     size = i;
     i = size - 1;
     j = size;
     while (1) {
         a[j] = a[i];
         if (--i < 0)
             break;
         a[j] |= (a[i] & 3) << 6;
         --j;
         a[j] = (unsigned char)((a[i] & 0x3c) >> 2);
         if (--i < 0)
             break;
         a[j] |= (a[i] & 0xf) << 4;
         --j;
         a[j] = (unsigned char)((a[i] & 0x30) >> 4);
         if (--i < 0)
             break;
         a[j] |= (a[i] << 2);
 
         a[--j] = 0;
         if (--i < 0)
             break;
     }
-    while (a[j] == 0 && j <= size)
+    while (j <= size && a[j] == 0)
         ++j;
     i = 0;
     while (j <= size)
         a[i++] = a[j++];
     return i;
 }
 
 /*
  * Convert a raw byte string into a null-terminated base64 ASCII string.
  */
 static char *t_tob64(char *dst, const unsigned char *src, int size)
 {
     int c, pos = size % 3;
     unsigned char b0 = 0, b1 = 0, b2 = 0, notleading = 0;
     char *olddst = dst;
 
     switch (pos) {
     case 1:
         b2 = src[0];
         break;
     case 2:
         b1 = src[0];
         b2 = src[1];
         break;
     }
 
     while (1) {
         c = (b0 & 0xfc) >> 2;
         if (notleading || c != 0) {
             *dst++ = b64table[c];
             notleading = 1;
         }
         c = ((b0 & 3) << 4) | ((b1 & 0xf0) >> 4);
         if (notleading || c != 0) {
             *dst++ = b64table[c];
             notleading = 1;
         }
         c = ((b1 & 0xf) << 2) | ((b2 & 0xc0) >> 6);
         if (notleading || c != 0) {
             *dst++ = b64table[c];
             notleading = 1;
         }
         c = b2 & 0x3f;
         if (notleading || c != 0) {
             *dst++ = b64table[c];
             notleading = 1;
         }
         if (pos >= size)
             break;
         else {
             b0 = src[pos++];
             b1 = src[pos++];
             b2 = src[pos++];
         }
     }
 
     *dst++ = '\0';
     return olddst;
 }
 
 void SRP_user_pwd_free(SRP_user_pwd *user_pwd)
 {
     if (user_pwd == NULL)
         return;
     BN_free(user_pwd->s);
     BN_clear_free(user_pwd->v);
     OPENSSL_free(user_pwd->id);
     OPENSSL_free(user_pwd->info);
     OPENSSL_free(user_pwd);
 }
 
 static SRP_user_pwd *SRP_user_pwd_new()
 {
     SRP_user_pwd *ret = OPENSSL_malloc(sizeof(SRP_user_pwd));
     if (ret == NULL)
         return NULL;
     ret->N = NULL;
     ret->g = NULL;
     ret->s = NULL;
     ret->v = NULL;
     ret->id = NULL;
     ret->info = NULL;
     return ret;
 }
 
 static void SRP_user_pwd_set_gN(SRP_user_pwd *vinfo, const BIGNUM *g,
                                 const BIGNUM *N)
 {
     vinfo->N = N;
     vinfo->g = g;
 }
 
 static int SRP_user_pwd_set_ids(SRP_user_pwd *vinfo, const char *id,
                                 const char *info)
 {
     if (id != NULL && NULL == (vinfo->id = BUF_strdup(id)))
         return 0;
     return (info == NULL || NULL != (vinfo->info = BUF_strdup(info)));
 }
 
 static int SRP_user_pwd_set_sv(SRP_user_pwd *vinfo, const char *s,
                                const char *v)
 {
     unsigned char tmp[MAX_LEN];
     int len;
 
     vinfo->v = NULL;
     vinfo->s = NULL;
 
     len = t_fromb64(tmp, sizeof(tmp), v);
     if (len < 0)
         return 0;
     if (NULL == (vinfo->v = BN_bin2bn(tmp, len, NULL)))
         return 0;
     len = t_fromb64(tmp, sizeof(tmp), s);
     if (len < 0)
         goto err;
     vinfo->s = BN_bin2bn(tmp, len, NULL);
     if (vinfo->s == NULL)
         goto err;
     return 1;
  err:
     BN_free(vinfo->v);
     vinfo->v = NULL;
     return 0;
 }
 
 static int SRP_user_pwd_set_sv_BN(SRP_user_pwd *vinfo, BIGNUM *s, BIGNUM *v)
 {
     vinfo->v = v;
     vinfo->s = s;
     return (vinfo->s != NULL && vinfo->v != NULL);
 }
 
 static SRP_user_pwd *srp_user_pwd_dup(SRP_user_pwd *src)
 {
     SRP_user_pwd *ret;
 
     if (src == NULL)
         return NULL;
     if ((ret = SRP_user_pwd_new()) == NULL)
         return NULL;
 
     SRP_user_pwd_set_gN(ret, src->g, src->N);
     if (!SRP_user_pwd_set_ids(ret, src->id, src->info)
         || !SRP_user_pwd_set_sv_BN(ret, BN_dup(src->s), BN_dup(src->v))) {
             SRP_user_pwd_free(ret);
             return NULL;
     }
     return ret;
 }
 
 SRP_VBASE *SRP_VBASE_new(char *seed_key)
 {
     SRP_VBASE *vb = (SRP_VBASE *)OPENSSL_malloc(sizeof(SRP_VBASE));
 
     if (vb == NULL)
         return NULL;
     if (!(vb->users_pwd = sk_SRP_user_pwd_new_null()) ||
         !(vb->gN_cache = sk_SRP_gN_cache_new_null())) {
         OPENSSL_free(vb);
         return NULL;
     }
     vb->default_g = NULL;
     vb->default_N = NULL;
     vb->seed_key = NULL;
     if ((seed_key != NULL) && (vb->seed_key = BUF_strdup(seed_key)) == NULL) {
         sk_SRP_user_pwd_free(vb->users_pwd);
         sk_SRP_gN_cache_free(vb->gN_cache);
         OPENSSL_free(vb);
         return NULL;
     }
     return vb;
 }
 
 int SRP_VBASE_free(SRP_VBASE *vb)
 {
     sk_SRP_user_pwd_pop_free(vb->users_pwd, SRP_user_pwd_free);
     sk_SRP_gN_cache_free(vb->gN_cache);
     OPENSSL_free(vb->seed_key);
     OPENSSL_free(vb);
     return 0;
 }
 
 static SRP_gN_cache *SRP_gN_new_init(const char *ch)
 {
     unsigned char tmp[MAX_LEN];
     int len;
 
     SRP_gN_cache *newgN =
         (SRP_gN_cache *)OPENSSL_malloc(sizeof(SRP_gN_cache));
     if (newgN == NULL)
         return NULL;
 
     len = t_fromb64(tmp, sizeof(tmp), ch);
     if (len < 0)
         goto err;
 
     if ((newgN->b64_bn = BUF_strdup(ch)) == NULL)
         goto err;
 
     if ((newgN->bn = BN_bin2bn(tmp, len, NULL)))
         return newgN;
 
     OPENSSL_free(newgN->b64_bn);
  err:
     OPENSSL_free(newgN);
     return NULL;
 }
 
 static void SRP_gN_free(SRP_gN_cache *gN_cache)
 {
     if (gN_cache == NULL)
         return;
     OPENSSL_free(gN_cache->b64_bn);
     BN_free(gN_cache->bn);
     OPENSSL_free(gN_cache);
 }
 
 static SRP_gN *SRP_get_gN_by_id(const char *id, STACK_OF(SRP_gN) *gN_tab)
 {
     int i;
 
     SRP_gN *gN;
     if (gN_tab != NULL)
         for (i = 0; i < sk_SRP_gN_num(gN_tab); i++) {
             gN = sk_SRP_gN_value(gN_tab, i);
             if (gN && (id == NULL || strcmp(gN->id, id) == 0))
                 return gN;
         }
 
     return SRP_get_default_gN(id);
 }
 
 static BIGNUM *SRP_gN_place_bn(STACK_OF(SRP_gN_cache) *gN_cache, char *ch)
 {
     int i;
     if (gN_cache == NULL)
         return NULL;
 
     /* search if we have already one... */
     for (i = 0; i < sk_SRP_gN_cache_num(gN_cache); i++) {
         SRP_gN_cache *cache = sk_SRP_gN_cache_value(gN_cache, i);
         if (strcmp(cache->b64_bn, ch) == 0)
             return cache->bn;
     }
     {                           /* it is the first time that we find it */
         SRP_gN_cache *newgN = SRP_gN_new_init(ch);
         if (newgN) {
             if (sk_SRP_gN_cache_insert(gN_cache, newgN, 0) > 0)
                 return newgN->bn;
             SRP_gN_free(newgN);
         }
     }
     return NULL;
 }
 
 /*
  * this function parses verifier file. Format is:
  * string(index):base64(N):base64(g):0
  * string(username):base64(v):base64(salt):int(index)
  */
 
 int SRP_VBASE_init(SRP_VBASE *vb, char *verifier_file)
 {
     int error_code;
     STACK_OF(SRP_gN) *SRP_gN_tab = sk_SRP_gN_new_null();
     char *last_index = NULL;
     int i;
     char **pp;
 
     SRP_gN *gN = NULL;
     SRP_user_pwd *user_pwd = NULL;
 
     TXT_DB *tmpdb = NULL;
     BIO *in = BIO_new(BIO_s_file());
 
     error_code = SRP_ERR_OPEN_FILE;
 
     if (in == NULL || BIO_read_filename(in, verifier_file) <= 0)
         goto err;
 
     error_code = SRP_ERR_VBASE_INCOMPLETE_FILE;
 
     if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
         goto err;
 
     error_code = SRP_ERR_MEMORY;
 
     if (vb->seed_key) {
         last_index = SRP_get_default_gN(NULL)->id;
     }
     for (i = 0; i < sk_OPENSSL_PSTRING_num(tmpdb->data); i++) {
         pp = sk_OPENSSL_PSTRING_value(tmpdb->data, i);
         if (pp[DB_srptype][0] == DB_SRP_INDEX) {
             /*
              * we add this couple in the internal Stack
              */
 
             if ((gN = (SRP_gN *) OPENSSL_malloc(sizeof(SRP_gN))) == NULL)
                 goto err;
 
             if (!(gN->id = BUF_strdup(pp[DB_srpid]))
                 || !(gN->N =
                      SRP_gN_place_bn(vb->gN_cache, pp[DB_srpverifier]))
                 || !(gN->g = SRP_gN_place_bn(vb->gN_cache, pp[DB_srpsalt]))
                 || sk_SRP_gN_insert(SRP_gN_tab, gN, 0) == 0)
                 goto err;
 
             gN = NULL;
 
             if (vb->seed_key != NULL) {
                 last_index = pp[DB_srpid];
             }
         } else if (pp[DB_srptype][0] == DB_SRP_VALID) {
             /* it is a user .... */
             SRP_gN *lgN;
             if ((lgN = SRP_get_gN_by_id(pp[DB_srpgN], SRP_gN_tab)) != NULL) {
                 error_code = SRP_ERR_MEMORY;
                 if ((user_pwd = SRP_user_pwd_new()) == NULL)
                     goto err;
 
                 SRP_user_pwd_set_gN(user_pwd, lgN->g, lgN->N);
                 if (!SRP_user_pwd_set_ids
                     (user_pwd, pp[DB_srpid], pp[DB_srpinfo]))
                     goto err;
 
                 error_code = SRP_ERR_VBASE_BN_LIB;
                 if (!SRP_user_pwd_set_sv
                     (user_pwd, pp[DB_srpsalt], pp[DB_srpverifier]))
                     goto err;
 
                 if (sk_SRP_user_pwd_insert(vb->users_pwd, user_pwd, 0) == 0)
                     goto err;
                 user_pwd = NULL; /* abandon responsability */
             }
         }
     }
 
     if (last_index != NULL) {
         /* this means that we want to simulate a default user */
 
         if (((gN = SRP_get_gN_by_id(last_index, SRP_gN_tab)) == NULL)) {
             error_code = SRP_ERR_VBASE_BN_LIB;
             goto err;
         }
         vb->default_g = gN->g;
         vb->default_N = gN->N;
         gN = NULL;
     }
     error_code = SRP_NO_ERROR;
 
  err:
     /*
      * there may be still some leaks to fix, if this fails, the application
      * terminates most likely
      */
 
     if (gN != NULL) {
         OPENSSL_free(gN->id);
         OPENSSL_free(gN);
     }
 
     SRP_user_pwd_free(user_pwd);
 
     if (tmpdb)
         TXT_DB_free(tmpdb);
     if (in)
         BIO_free_all(in);
 
     sk_SRP_gN_free(SRP_gN_tab);
 
     return error_code;
 
 }
 
 static SRP_user_pwd *find_user(SRP_VBASE *vb, char *username)
 {
     int i;
     SRP_user_pwd *user;
 
     if (vb == NULL)
         return NULL;
 
     for (i = 0; i < sk_SRP_user_pwd_num(vb->users_pwd); i++) {
         user = sk_SRP_user_pwd_value(vb->users_pwd, i);
         if (strcmp(user->id, username) == 0)
             return user;
     }
 
     return NULL;
 }
 
 /*
  * This method ignores the configured seed and fails for an unknown user.
  * Ownership of the returned pointer is not released to the caller.
  * In other words, caller must not free the result.
  */
 SRP_user_pwd *SRP_VBASE_get_by_user(SRP_VBASE *vb, char *username)
 {
     return find_user(vb, username);
 }
 
 /*
  * Ownership of the returned pointer is released to the caller.
  * In other words, caller must free the result once done.
  */
 SRP_user_pwd *SRP_VBASE_get1_by_user(SRP_VBASE *vb, char *username)
 {
     SRP_user_pwd *user;
     unsigned char digv[SHA_DIGEST_LENGTH];
     unsigned char digs[SHA_DIGEST_LENGTH];
     EVP_MD_CTX ctxt;
 
     if (vb == NULL)
         return NULL;
 
     if ((user = find_user(vb, username)) != NULL)
         return srp_user_pwd_dup(user);
 
     if ((vb->seed_key == NULL) ||
         (vb->default_g == NULL) || (vb->default_N == NULL))
         return NULL;
 
 /* if the user is unknown we set parameters as well if we have a seed_key */
 
     if ((user = SRP_user_pwd_new()) == NULL)
         return NULL;
 
     SRP_user_pwd_set_gN(user, vb->default_g, vb->default_N);
 
     if (!SRP_user_pwd_set_ids(user, username, NULL))
         goto err;
 
     if (RAND_bytes(digv, SHA_DIGEST_LENGTH) <= 0)
         goto err;
     EVP_MD_CTX_init(&ctxt);
     EVP_DigestInit_ex(&ctxt, EVP_sha1(), NULL);
     EVP_DigestUpdate(&ctxt, vb->seed_key, strlen(vb->seed_key));
     EVP_DigestUpdate(&ctxt, username, strlen(username));
     EVP_DigestFinal_ex(&ctxt, digs, NULL);
     EVP_MD_CTX_cleanup(&ctxt);
     if (SRP_user_pwd_set_sv_BN
         (user, BN_bin2bn(digs, SHA_DIGEST_LENGTH, NULL),
          BN_bin2bn(digv, SHA_DIGEST_LENGTH, NULL)))
         return user;
 
  err:SRP_user_pwd_free(user);
     return NULL;
 }
 
 /*
  * create a verifier (*salt,*verifier,g and N are in base64)
  */
 char *SRP_create_verifier(const char *user, const char *pass, char **salt,
                           char **verifier, const char *N, const char *g)
 {
     int len;
     char *result = NULL, *vf = NULL;
     BIGNUM *N_bn = NULL, *g_bn = NULL, *s = NULL, *v = NULL;
     unsigned char tmp[MAX_LEN];
     unsigned char tmp2[MAX_LEN];
     char *defgNid = NULL;
     int vfsize = 0;
 
     if ((user == NULL) ||
         (pass == NULL) || (salt == NULL) || (verifier == NULL))
         goto err;
 
     if (N) {
         if (!(len = t_fromb64(tmp, sizeof(tmp), N)))
             goto err;
         N_bn = BN_bin2bn(tmp, len, NULL);
         if (!(len = t_fromb64(tmp, sizeof(tmp), g)))
             goto err;
         g_bn = BN_bin2bn(tmp, len, NULL);
         defgNid = "*";
     } else {
         SRP_gN *gN = SRP_get_gN_by_id(g, NULL);
         if (gN == NULL)
             goto err;
         N_bn = gN->N;
         g_bn = gN->g;
         defgNid = gN->id;
     }
 
     if (*salt == NULL) {
         if (RAND_bytes(tmp2, SRP_RANDOM_SALT_LEN) <= 0)
             goto err;
 
         s = BN_bin2bn(tmp2, SRP_RANDOM_SALT_LEN, NULL);
     } else {
         if (!(len = t_fromb64(tmp2, sizeof(tmp2), *salt)))
             goto err;
         s = BN_bin2bn(tmp2, len, NULL);
     }
 
     if (!SRP_create_verifier_BN(user, pass, &s, &v, N_bn, g_bn))
         goto err;
 
     BN_bn2bin(v, tmp);
     vfsize = BN_num_bytes(v) * 2;
     if (((vf = OPENSSL_malloc(vfsize)) == NULL))
         goto err;
     t_tob64(vf, tmp, BN_num_bytes(v));
 
     if (*salt == NULL) {
         char *tmp_salt;
 
         if ((tmp_salt = OPENSSL_malloc(SRP_RANDOM_SALT_LEN * 2)) == NULL) {
             goto err;
         }
         t_tob64(tmp_salt, tmp2, SRP_RANDOM_SALT_LEN);
         *salt = tmp_salt;
     }
 
     *verifier = vf;
     vf = NULL;
     result = defgNid;
 
  err:
     if (N) {
         BN_free(N_bn);
         BN_free(g_bn);
     }
     if (vf != NULL)
         OPENSSL_cleanse(vf, vfsize);
     OPENSSL_free(vf);
     BN_clear_free(s);
     BN_clear_free(v);
     return result;
 }
 
 /*
  * create a verifier (*salt,*verifier,g and N are BIGNUMs). If *salt != NULL
  * then the provided salt will be used. On successful exit *verifier will point
  * to a newly allocated BIGNUM containing the verifier and (if a salt was not
  * provided) *salt will be populated with a newly allocated BIGNUM containing a
  * random salt.
  * The caller is responsible for freeing the allocated *salt and *verifier
  * BIGNUMS.
  */
 int SRP_create_verifier_BN(const char *user, const char *pass, BIGNUM **salt,
                            BIGNUM **verifier, BIGNUM *N, BIGNUM *g)
 {
     int result = 0;
     BIGNUM *x = NULL;
     BN_CTX *bn_ctx = BN_CTX_new();
     unsigned char tmp2[MAX_LEN];
     BIGNUM *salttmp = NULL;
 
     if ((user == NULL) ||
         (pass == NULL) ||
         (salt == NULL) ||
         (verifier == NULL) || (N == NULL) || (g == NULL) || (bn_ctx == NULL))
         goto err;
 
     srp_bn_print(N);
     srp_bn_print(g);
 
     if (*salt == NULL) {
         if (RAND_bytes(tmp2, SRP_RANDOM_SALT_LEN) <= 0)
             goto err;
 
         salttmp = BN_bin2bn(tmp2, SRP_RANDOM_SALT_LEN, NULL);
     } else {
         salttmp = *salt;
     }
 
     x = SRP_Calc_x(salttmp, user, pass);
 
     *verifier = BN_new();
     if (*verifier == NULL)
         goto err;
 
     if (!BN_mod_exp(*verifier, g, x, N, bn_ctx)) {
         BN_clear_free(*verifier);
         goto err;
     }
 
     srp_bn_print(*verifier);
 
     result = 1;
     *salt = salttmp;
 
  err:
     if (*salt != salttmp)
         BN_clear_free(salttmp);
     BN_clear_free(x);
     BN_CTX_free(bn_ctx);
     return result;
 }
 
 #endif
Index: vendor-crypto/openssl/dist/crypto/txt_db/txt_db.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/txt_db/txt_db.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/txt_db/txt_db.c	(revision 318897)
@@ -1,381 +1,397 @@
 /* crypto/txt_db/txt_db.c */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 
 #include 
 #include 
 #include 
 #include "cryptlib.h"
 #include 
 #include 
 
 #undef BUFSIZE
 #define BUFSIZE 512
 
 const char TXT_DB_version[] = "TXT_DB" OPENSSL_VERSION_PTEXT;
 
 TXT_DB *TXT_DB_read(BIO *in, int num)
 {
     TXT_DB *ret = NULL;
     int er = 1;
     int esc = 0;
     long ln = 0;
     int i, add, n;
     int size = BUFSIZE;
     int offset = 0;
     char *p, *f;
     OPENSSL_STRING *pp;
     BUF_MEM *buf = NULL;
 
     if ((buf = BUF_MEM_new()) == NULL)
         goto err;
     if (!BUF_MEM_grow(buf, size))
         goto err;
 
     if ((ret = OPENSSL_malloc(sizeof(TXT_DB))) == NULL)
         goto err;
     ret->num_fields = num;
     ret->index = NULL;
     ret->qual = NULL;
     if ((ret->data = sk_OPENSSL_PSTRING_new_null()) == NULL)
         goto err;
     if ((ret->index = OPENSSL_malloc(sizeof(*ret->index) * num)) == NULL)
         goto err;
     if ((ret->qual = OPENSSL_malloc(sizeof(*(ret->qual)) * num)) == NULL)
         goto err;
     for (i = 0; i < num; i++) {
         ret->index[i] = NULL;
         ret->qual[i] = NULL;
     }
 
     add = (num + 1) * sizeof(char *);
     buf->data[size - 1] = '\0';
     offset = 0;
     for (;;) {
         if (offset != 0) {
             size += BUFSIZE;
             if (!BUF_MEM_grow_clean(buf, size))
                 goto err;
         }
         buf->data[offset] = '\0';
         BIO_gets(in, &(buf->data[offset]), size - offset);
         ln++;
         if (buf->data[offset] == '\0')
             break;
         if ((offset == 0) && (buf->data[0] == '#'))
             continue;
         i = strlen(&(buf->data[offset]));
         offset += i;
         if (buf->data[offset - 1] != '\n')
             continue;
         else {
             buf->data[offset - 1] = '\0'; /* blat the '\n' */
             if (!(p = OPENSSL_malloc(add + offset)))
                 goto err;
             offset = 0;
         }
         pp = (char **)p;
         p += add;
         n = 0;
         pp[n++] = p;
         i = 0;
         f = buf->data;
 
         esc = 0;
         for (;;) {
             if (*f == '\0')
                 break;
             if (*f == '\t') {
                 if (esc)
                     p--;
                 else {
                     *(p++) = '\0';
                     f++;
                     if (n >= num)
                         break;
                     pp[n++] = p;
                     continue;
                 }
             }
             esc = (*f == '\\');
             *(p++) = *(f++);
         }
         *(p++) = '\0';
         if ((n != num) || (*f != '\0')) {
 #if !defined(OPENSSL_NO_STDIO) && !defined(OPENSSL_SYS_WIN16) /* temporary
                                                                * fix :-( */
             fprintf(stderr,
                     "wrong number of fields on line %ld (looking for field %d, got %d, '%s' left)\n",
                     ln, num, n, f);
 #endif
+            OPENSSL_free(pp);
             er = 2;
             goto err;
         }
         pp[n] = p;
         if (!sk_OPENSSL_PSTRING_push(ret->data, pp)) {
 #if !defined(OPENSSL_NO_STDIO) && !defined(OPENSSL_SYS_WIN16) /* temporary
                                                                * fix :-( */
             fprintf(stderr, "failure in sk_push\n");
 #endif
+            OPENSSL_free(pp);
             er = 2;
             goto err;
         }
     }
     er = 0;
  err:
     BUF_MEM_free(buf);
     if (er) {
 #if !defined(OPENSSL_NO_STDIO) && !defined(OPENSSL_SYS_WIN16)
         if (er == 1)
             fprintf(stderr, "OPENSSL_malloc failure\n");
 #endif
         if (ret != NULL) {
             if (ret->data != NULL)
                 sk_OPENSSL_PSTRING_free(ret->data);
             if (ret->index != NULL)
                 OPENSSL_free(ret->index);
             if (ret->qual != NULL)
                 OPENSSL_free(ret->qual);
             if (ret != NULL)
                 OPENSSL_free(ret);
         }
         return (NULL);
     } else
         return (ret);
 }
 
 OPENSSL_STRING *TXT_DB_get_by_index(TXT_DB *db, int idx,
                                     OPENSSL_STRING *value)
 {
     OPENSSL_STRING *ret;
     LHASH_OF(OPENSSL_STRING) *lh;
 
     if (idx >= db->num_fields) {
         db->error = DB_ERROR_INDEX_OUT_OF_RANGE;
         return (NULL);
     }
     lh = db->index[idx];
     if (lh == NULL) {
         db->error = DB_ERROR_NO_INDEX;
         return (NULL);
     }
     ret = lh_OPENSSL_STRING_retrieve(lh, value);
     db->error = DB_ERROR_OK;
     return (ret);
 }
 
 int TXT_DB_create_index(TXT_DB *db, int field, int (*qual) (OPENSSL_STRING *),
                         LHASH_HASH_FN_TYPE hash, LHASH_COMP_FN_TYPE cmp)
 {
     LHASH_OF(OPENSSL_STRING) *idx;
-    OPENSSL_STRING *r;
+    OPENSSL_STRING *r, *k;
     int i, n;
 
     if (field >= db->num_fields) {
         db->error = DB_ERROR_INDEX_OUT_OF_RANGE;
         return (0);
     }
     /* FIXME: we lose type checking at this point */
     if ((idx = (LHASH_OF(OPENSSL_STRING) *)lh_new(hash, cmp)) == NULL) {
         db->error = DB_ERROR_MALLOC;
         return (0);
     }
     n = sk_OPENSSL_PSTRING_num(db->data);
     for (i = 0; i < n; i++) {
         r = sk_OPENSSL_PSTRING_value(db->data, i);
         if ((qual != NULL) && (qual(r) == 0))
             continue;
-        if ((r = lh_OPENSSL_STRING_insert(idx, r)) != NULL) {
+        if ((k = lh_OPENSSL_STRING_insert(idx, r)) != NULL) {
             db->error = DB_ERROR_INDEX_CLASH;
-            db->arg1 = sk_OPENSSL_PSTRING_find(db->data, r);
+            db->arg1 = sk_OPENSSL_PSTRING_find(db->data, k);
             db->arg2 = i;
             lh_OPENSSL_STRING_free(idx);
             return (0);
         }
+        if (lh_OPENSSL_STRING_retrieve(idx, r) == NULL) {
+            db->error = DB_ERROR_MALLOC;
+            lh_OPENSSL_STRING_free(idx);
+            return (0);
+        }
     }
     if (db->index[field] != NULL)
         lh_OPENSSL_STRING_free(db->index[field]);
     db->index[field] = idx;
     db->qual[field] = qual;
     return (1);
 }
 
 long TXT_DB_write(BIO *out, TXT_DB *db)
 {
     long i, j, n, nn, l, tot = 0;
     char *p, **pp, *f;
     BUF_MEM *buf = NULL;
     long ret = -1;
 
     if ((buf = BUF_MEM_new()) == NULL)
         goto err;
     n = sk_OPENSSL_PSTRING_num(db->data);
     nn = db->num_fields;
     for (i = 0; i < n; i++) {
         pp = sk_OPENSSL_PSTRING_value(db->data, i);
 
         l = 0;
         for (j = 0; j < nn; j++) {
             if (pp[j] != NULL)
                 l += strlen(pp[j]);
         }
         if (!BUF_MEM_grow_clean(buf, (int)(l * 2 + nn)))
             goto err;
 
         p = buf->data;
         for (j = 0; j < nn; j++) {
             f = pp[j];
             if (f != NULL)
                 for (;;) {
                     if (*f == '\0')
                         break;
                     if (*f == '\t')
                         *(p++) = '\\';
                     *(p++) = *(f++);
                 }
             *(p++) = '\t';
         }
         p[-1] = '\n';
         j = p - buf->data;
         if (BIO_write(out, buf->data, (int)j) != j)
             goto err;
         tot += j;
     }
     ret = tot;
  err:
     if (buf != NULL)
         BUF_MEM_free(buf);
     return (ret);
 }
 
 int TXT_DB_insert(TXT_DB *db, OPENSSL_STRING *row)
 {
     int i;
     OPENSSL_STRING *r;
 
     for (i = 0; i < db->num_fields; i++) {
         if (db->index[i] != NULL) {
             if ((db->qual[i] != NULL) && (db->qual[i] (row) == 0))
                 continue;
             r = lh_OPENSSL_STRING_retrieve(db->index[i], row);
             if (r != NULL) {
                 db->error = DB_ERROR_INDEX_CLASH;
                 db->arg1 = i;
                 db->arg_row = r;
                 goto err;
             }
         }
     }
-    /* We have passed the index checks, now just append and insert */
-    if (!sk_OPENSSL_PSTRING_push(db->data, row)) {
-        db->error = DB_ERROR_MALLOC;
-        goto err;
-    }
 
     for (i = 0; i < db->num_fields; i++) {
         if (db->index[i] != NULL) {
             if ((db->qual[i] != NULL) && (db->qual[i] (row) == 0))
                 continue;
             (void)lh_OPENSSL_STRING_insert(db->index[i], row);
+            if (lh_OPENSSL_STRING_retrieve(db->index[i], row) == NULL)
+                goto err1;
         }
     }
+    if (!sk_OPENSSL_PSTRING_push(db->data, row))
+        goto err1;
     return (1);
+
+ err1:
+    db->error = DB_ERROR_MALLOC;
+    while (i-- > 0) {
+        if (db->index[i] != NULL) {
+            if ((db->qual[i] != NULL) && (db->qual[i] (row) == 0))
+                continue;
+            (void)lh_OPENSSL_STRING_delete(db->index[i], row);
+        }
+    }
  err:
     return (0);
 }
 
 void TXT_DB_free(TXT_DB *db)
 {
     int i, n;
     char **p, *max;
 
     if (db == NULL)
         return;
 
     if (db->index != NULL) {
         for (i = db->num_fields - 1; i >= 0; i--)
             if (db->index[i] != NULL)
                 lh_OPENSSL_STRING_free(db->index[i]);
         OPENSSL_free(db->index);
     }
     if (db->qual != NULL)
         OPENSSL_free(db->qual);
     if (db->data != NULL) {
         for (i = sk_OPENSSL_PSTRING_num(db->data) - 1; i >= 0; i--) {
             /*
              * check if any 'fields' have been allocated from outside of the
              * initial block
              */
             p = sk_OPENSSL_PSTRING_value(db->data, i);
             max = p[db->num_fields]; /* last address */
             if (max == NULL) {  /* new row */
                 for (n = 0; n < db->num_fields; n++)
                     if (p[n] != NULL)
                         OPENSSL_free(p[n]);
             } else {
                 for (n = 0; n < db->num_fields; n++) {
                     if (((p[n] < (char *)p) || (p[n] > max))
                         && (p[n] != NULL))
                         OPENSSL_free(p[n]);
                 }
             }
             OPENSSL_free(sk_OPENSSL_PSTRING_value(db->data, i));
         }
         sk_OPENSSL_PSTRING_free(db->data);
     }
     OPENSSL_free(db);
 }
Index: vendor-crypto/openssl/dist/crypto/ui/ui_lib.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/ui/ui_lib.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/ui/ui_lib.c	(revision 318897)
@@ -1,878 +1,877 @@
 /* crypto/ui/ui_lib.c */
 /*
  * Written by Richard Levitte (richard@levitte.org) for the OpenSSL project
  * 2001.
  */
 /* ====================================================================
  * Copyright (c) 2001 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    openssl-core@openssl.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #include 
 #include "cryptlib.h"
 #include 
 #include 
 #include 
 #include 
 #include "ui_locl.h"
 
 IMPLEMENT_STACK_OF(UI_STRING_ST)
 
 static const UI_METHOD *default_UI_meth = NULL;
 
 UI *UI_new(void)
 {
     return (UI_new_method(NULL));
 }
 
 UI *UI_new_method(const UI_METHOD *method)
 {
     UI *ret;
 
     ret = (UI *)OPENSSL_malloc(sizeof(UI));
     if (ret == NULL) {
         UIerr(UI_F_UI_NEW_METHOD, ERR_R_MALLOC_FAILURE);
         return NULL;
     }
     if (method == NULL)
         ret->meth = UI_get_default_method();
     else
         ret->meth = method;
 
     ret->strings = NULL;
     ret->user_data = NULL;
     ret->flags = 0;
     CRYPTO_new_ex_data(CRYPTO_EX_INDEX_UI, ret, &ret->ex_data);
     return ret;
 }
 
 static void free_string(UI_STRING *uis)
 {
     if (uis->flags & OUT_STRING_FREEABLE) {
         OPENSSL_free((char *)uis->out_string);
         switch (uis->type) {
         case UIT_BOOLEAN:
             OPENSSL_free((char *)uis->_.boolean_data.action_desc);
             OPENSSL_free((char *)uis->_.boolean_data.ok_chars);
             OPENSSL_free((char *)uis->_.boolean_data.cancel_chars);
             break;
         default:
             break;
         }
     }
     OPENSSL_free(uis);
 }
 
 void UI_free(UI *ui)
 {
     if (ui == NULL)
         return;
     sk_UI_STRING_pop_free(ui->strings, free_string);
     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_UI, ui, &ui->ex_data);
     OPENSSL_free(ui);
 }
 
 static int allocate_string_stack(UI *ui)
 {
     if (ui->strings == NULL) {
         ui->strings = sk_UI_STRING_new_null();
         if (ui->strings == NULL) {
             return -1;
         }
     }
     return 0;
 }
 
 static UI_STRING *general_allocate_prompt(UI *ui, const char *prompt,
                                           int prompt_freeable,
                                           enum UI_string_types type,
                                           int input_flags, char *result_buf)
 {
     UI_STRING *ret = NULL;
 
     if (prompt == NULL) {
         UIerr(UI_F_GENERAL_ALLOCATE_PROMPT, ERR_R_PASSED_NULL_PARAMETER);
     } else if ((type == UIT_PROMPT || type == UIT_VERIFY
                 || type == UIT_BOOLEAN) && result_buf == NULL) {
         UIerr(UI_F_GENERAL_ALLOCATE_PROMPT, UI_R_NO_RESULT_BUFFER);
     } else if ((ret = (UI_STRING *)OPENSSL_malloc(sizeof(UI_STRING)))) {
         ret->out_string = prompt;
         ret->flags = prompt_freeable ? OUT_STRING_FREEABLE : 0;
         ret->input_flags = input_flags;
         ret->type = type;
         ret->result_buf = result_buf;
     }
     return ret;
 }
 
 static int general_allocate_string(UI *ui, const char *prompt,
                                    int prompt_freeable,
                                    enum UI_string_types type, int input_flags,
                                    char *result_buf, int minsize, int maxsize,
                                    const char *test_buf)
 {
     int ret = -1;
     UI_STRING *s = general_allocate_prompt(ui, prompt, prompt_freeable,
                                            type, input_flags, result_buf);
 
     if (s != NULL) {
         if (allocate_string_stack(ui) >= 0) {
             s->_.string_data.result_minsize = minsize;
             s->_.string_data.result_maxsize = maxsize;
             s->_.string_data.test_buf = test_buf;
             ret = sk_UI_STRING_push(ui->strings, s);
             /* sk_push() returns 0 on error.  Let's addapt that */
             if (ret <= 0)
                 ret--;
         } else
             free_string(s);
     }
     return ret;
 }
 
 static int general_allocate_boolean(UI *ui,
                                     const char *prompt,
                                     const char *action_desc,
                                     const char *ok_chars,
                                     const char *cancel_chars,
                                     int prompt_freeable,
                                     enum UI_string_types type,
                                     int input_flags, char *result_buf)
 {
     int ret = -1;
     UI_STRING *s;
     const char *p;
 
     if (ok_chars == NULL) {
         UIerr(UI_F_GENERAL_ALLOCATE_BOOLEAN, ERR_R_PASSED_NULL_PARAMETER);
     } else if (cancel_chars == NULL) {
         UIerr(UI_F_GENERAL_ALLOCATE_BOOLEAN, ERR_R_PASSED_NULL_PARAMETER);
     } else {
         for (p = ok_chars; *p != '\0'; p++) {
             if (strchr(cancel_chars, *p) != NULL) {
                 UIerr(UI_F_GENERAL_ALLOCATE_BOOLEAN,
                       UI_R_COMMON_OK_AND_CANCEL_CHARACTERS);
             }
         }
 
         s = general_allocate_prompt(ui, prompt, prompt_freeable,
                                     type, input_flags, result_buf);
 
         if (s != NULL) {
             if (allocate_string_stack(ui) >= 0) {
                 s->_.boolean_data.action_desc = action_desc;
                 s->_.boolean_data.ok_chars = ok_chars;
                 s->_.boolean_data.cancel_chars = cancel_chars;
                 ret = sk_UI_STRING_push(ui->strings, s);
                 /*
                  * sk_push() returns 0 on error. Let's addapt that
                  */
                 if (ret <= 0)
                     ret--;
             } else
                 free_string(s);
         }
     }
     return ret;
 }
 
 /*
  * Returns the index to the place in the stack or -1 for error.  Uses a
  * direct reference to the prompt.
  */
 int UI_add_input_string(UI *ui, const char *prompt, int flags,
                         char *result_buf, int minsize, int maxsize)
 {
     return general_allocate_string(ui, prompt, 0,
                                    UIT_PROMPT, flags, result_buf, minsize,
                                    maxsize, NULL);
 }
 
 /* Same as UI_add_input_string(), excepts it takes a copy of the prompt */
 int UI_dup_input_string(UI *ui, const char *prompt, int flags,
                         char *result_buf, int minsize, int maxsize)
 {
     char *prompt_copy = NULL;
 
     if (prompt != NULL) {
         prompt_copy = BUF_strdup(prompt);
         if (prompt_copy == NULL) {
             UIerr(UI_F_UI_DUP_INPUT_STRING, ERR_R_MALLOC_FAILURE);
             return 0;
         }
     }
 
     return general_allocate_string(ui, prompt_copy, 1,
                                    UIT_PROMPT, flags, result_buf, minsize,
                                    maxsize, NULL);
 }
 
 int UI_add_verify_string(UI *ui, const char *prompt, int flags,
                          char *result_buf, int minsize, int maxsize,
                          const char *test_buf)
 {
     return general_allocate_string(ui, prompt, 0,
                                    UIT_VERIFY, flags, result_buf, minsize,
                                    maxsize, test_buf);
 }
 
 int UI_dup_verify_string(UI *ui, const char *prompt, int flags,
                          char *result_buf, int minsize, int maxsize,
                          const char *test_buf)
 {
     char *prompt_copy = NULL;
 
     if (prompt != NULL) {
         prompt_copy = BUF_strdup(prompt);
         if (prompt_copy == NULL) {
             UIerr(UI_F_UI_DUP_VERIFY_STRING, ERR_R_MALLOC_FAILURE);
             return -1;
         }
     }
 
     return general_allocate_string(ui, prompt_copy, 1,
                                    UIT_VERIFY, flags, result_buf, minsize,
                                    maxsize, test_buf);
 }
 
 int UI_add_input_boolean(UI *ui, const char *prompt, const char *action_desc,
                          const char *ok_chars, const char *cancel_chars,
                          int flags, char *result_buf)
 {
     return general_allocate_boolean(ui, prompt, action_desc,
                                     ok_chars, cancel_chars, 0, UIT_BOOLEAN,
                                     flags, result_buf);
 }
 
 int UI_dup_input_boolean(UI *ui, const char *prompt, const char *action_desc,
                          const char *ok_chars, const char *cancel_chars,
                          int flags, char *result_buf)
 {
     char *prompt_copy = NULL;
     char *action_desc_copy = NULL;
     char *ok_chars_copy = NULL;
     char *cancel_chars_copy = NULL;
 
     if (prompt != NULL) {
         prompt_copy = BUF_strdup(prompt);
         if (prompt_copy == NULL) {
             UIerr(UI_F_UI_DUP_INPUT_BOOLEAN, ERR_R_MALLOC_FAILURE);
             goto err;
         }
     }
 
     if (action_desc != NULL) {
         action_desc_copy = BUF_strdup(action_desc);
         if (action_desc_copy == NULL) {
             UIerr(UI_F_UI_DUP_INPUT_BOOLEAN, ERR_R_MALLOC_FAILURE);
             goto err;
         }
     }
 
     if (ok_chars != NULL) {
         ok_chars_copy = BUF_strdup(ok_chars);
         if (ok_chars_copy == NULL) {
             UIerr(UI_F_UI_DUP_INPUT_BOOLEAN, ERR_R_MALLOC_FAILURE);
             goto err;
         }
     }
 
     if (cancel_chars != NULL) {
         cancel_chars_copy = BUF_strdup(cancel_chars);
         if (cancel_chars_copy == NULL) {
             UIerr(UI_F_UI_DUP_INPUT_BOOLEAN, ERR_R_MALLOC_FAILURE);
             goto err;
         }
     }
 
     return general_allocate_boolean(ui, prompt_copy, action_desc_copy,
                                     ok_chars_copy, cancel_chars_copy, 1,
                                     UIT_BOOLEAN, flags, result_buf);
  err:
     if (prompt_copy)
         OPENSSL_free(prompt_copy);
     if (action_desc_copy)
         OPENSSL_free(action_desc_copy);
     if (ok_chars_copy)
         OPENSSL_free(ok_chars_copy);
     if (cancel_chars_copy)
         OPENSSL_free(cancel_chars_copy);
     return -1;
 }
 
 int UI_add_info_string(UI *ui, const char *text)
 {
     return general_allocate_string(ui, text, 0, UIT_INFO, 0, NULL, 0, 0,
                                    NULL);
 }
 
 int UI_dup_info_string(UI *ui, const char *text)
 {
     char *text_copy = NULL;
 
     if (text != NULL) {
         text_copy = BUF_strdup(text);
         if (text_copy == NULL) {
             UIerr(UI_F_UI_DUP_INFO_STRING, ERR_R_MALLOC_FAILURE);
             return -1;
         }
     }
 
     return general_allocate_string(ui, text_copy, 1, UIT_INFO, 0, NULL,
                                    0, 0, NULL);
 }
 
 int UI_add_error_string(UI *ui, const char *text)
 {
     return general_allocate_string(ui, text, 0, UIT_ERROR, 0, NULL, 0, 0,
                                    NULL);
 }
 
 int UI_dup_error_string(UI *ui, const char *text)
 {
     char *text_copy = NULL;
 
     if (text != NULL) {
         text_copy = BUF_strdup(text);
         if (text_copy == NULL) {
             UIerr(UI_F_UI_DUP_ERROR_STRING, ERR_R_MALLOC_FAILURE);
             return -1;
         }
     }
     return general_allocate_string(ui, text_copy, 1, UIT_ERROR, 0, NULL,
                                    0, 0, NULL);
 }
 
 char *UI_construct_prompt(UI *ui, const char *object_desc,
                           const char *object_name)
 {
     char *prompt = NULL;
 
     if (ui->meth->ui_construct_prompt != NULL)
         prompt = ui->meth->ui_construct_prompt(ui, object_desc, object_name);
     else {
         char prompt1[] = "Enter ";
         char prompt2[] = " for ";
         char prompt3[] = ":";
         int len = 0;
 
         if (object_desc == NULL)
             return NULL;
         len = sizeof(prompt1) - 1 + strlen(object_desc);
         if (object_name != NULL)
             len += sizeof(prompt2) - 1 + strlen(object_name);
         len += sizeof(prompt3) - 1;
 
         prompt = (char *)OPENSSL_malloc(len + 1);
         if (prompt == NULL)
             return NULL;
         BUF_strlcpy(prompt, prompt1, len + 1);
         BUF_strlcat(prompt, object_desc, len + 1);
         if (object_name != NULL) {
             BUF_strlcat(prompt, prompt2, len + 1);
             BUF_strlcat(prompt, object_name, len + 1);
         }
         BUF_strlcat(prompt, prompt3, len + 1);
     }
     return prompt;
 }
 
 void *UI_add_user_data(UI *ui, void *user_data)
 {
     void *old_data = ui->user_data;
     ui->user_data = user_data;
     return old_data;
 }
 
 void *UI_get0_user_data(UI *ui)
 {
     return ui->user_data;
 }
 
 const char *UI_get0_result(UI *ui, int i)
 {
     if (i < 0) {
         UIerr(UI_F_UI_GET0_RESULT, UI_R_INDEX_TOO_SMALL);
         return NULL;
     }
     if (i >= sk_UI_STRING_num(ui->strings)) {
         UIerr(UI_F_UI_GET0_RESULT, UI_R_INDEX_TOO_LARGE);
         return NULL;
     }
     return UI_get0_result_string(sk_UI_STRING_value(ui->strings, i));
 }
 
 static int print_error(const char *str, size_t len, UI *ui)
 {
     UI_STRING uis;
 
     memset(&uis, 0, sizeof(uis));
     uis.type = UIT_ERROR;
     uis.out_string = str;
 
     if (ui->meth->ui_write_string != NULL
         && ui->meth->ui_write_string(ui, &uis) <= 0)
         return -1;
     return 0;
 }
 
 int UI_process(UI *ui)
 {
     int i, ok = 0;
 
     if (ui->meth->ui_open_session != NULL
         && ui->meth->ui_open_session(ui) <= 0) {
         ok = -1;
         goto err;
     }
 
     if (ui->flags & UI_FLAG_PRINT_ERRORS)
         ERR_print_errors_cb((int (*)(const char *, size_t, void *))
                             print_error, (void *)ui);
 
     for (i = 0; i < sk_UI_STRING_num(ui->strings); i++) {
         if (ui->meth->ui_write_string != NULL
             && (ui->meth->ui_write_string(ui,
                                           sk_UI_STRING_value(ui->strings, i))
                 <= 0))
         {
             ok = -1;
             goto err;
         }
     }
 
     if (ui->meth->ui_flush != NULL)
         switch (ui->meth->ui_flush(ui)) {
         case -1:               /* Interrupt/Cancel/something... */
             ok = -2;
             goto err;
         case 0:                /* Errors */
             ok = -1;
             goto err;
         default:               /* Success */
             ok = 0;
             break;
         }
 
     for (i = 0; i < sk_UI_STRING_num(ui->strings); i++) {
         if (ui->meth->ui_read_string != NULL) {
             switch (ui->meth->ui_read_string(ui,
                                              sk_UI_STRING_value(ui->strings,
                                                                 i))) {
             case -1:           /* Interrupt/Cancel/something... */
                 ok = -2;
                 goto err;
             case 0:            /* Errors */
                 ok = -1;
                 goto err;
             default:           /* Success */
                 ok = 0;
                 break;
             }
         }
     }
  err:
     if (ui->meth->ui_close_session != NULL
         && ui->meth->ui_close_session(ui) <= 0)
         return -1;
     return ok;
 }
 
 int UI_ctrl(UI *ui, int cmd, long i, void *p, void (*f) (void))
 {
     if (ui == NULL) {
         UIerr(UI_F_UI_CTRL, ERR_R_PASSED_NULL_PARAMETER);
         return -1;
     }
     switch (cmd) {
     case UI_CTRL_PRINT_ERRORS:
         {
             int save_flag = ! !(ui->flags & UI_FLAG_PRINT_ERRORS);
             if (i)
                 ui->flags |= UI_FLAG_PRINT_ERRORS;
             else
                 ui->flags &= ~UI_FLAG_PRINT_ERRORS;
             return save_flag;
         }
     case UI_CTRL_IS_REDOABLE:
         return ! !(ui->flags & UI_FLAG_REDOABLE);
     default:
         break;
     }
     UIerr(UI_F_UI_CTRL, UI_R_UNKNOWN_CONTROL_COMMAND);
     return -1;
 }
 
 int UI_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
                         CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func)
 {
     return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_UI, argl, argp,
                                    new_func, dup_func, free_func);
 }
 
 int UI_set_ex_data(UI *r, int idx, void *arg)
 {
     return (CRYPTO_set_ex_data(&r->ex_data, idx, arg));
 }
 
 void *UI_get_ex_data(UI *r, int idx)
 {
     return (CRYPTO_get_ex_data(&r->ex_data, idx));
 }
 
 void UI_set_default_method(const UI_METHOD *meth)
 {
     default_UI_meth = meth;
 }
 
 const UI_METHOD *UI_get_default_method(void)
 {
     if (default_UI_meth == NULL) {
         default_UI_meth = UI_OpenSSL();
     }
     return default_UI_meth;
 }
 
 const UI_METHOD *UI_get_method(UI *ui)
 {
     return ui->meth;
 }
 
 const UI_METHOD *UI_set_method(UI *ui, const UI_METHOD *meth)
 {
     ui->meth = meth;
     return ui->meth;
 }
 
 UI_METHOD *UI_create_method(char *name)
 {
     UI_METHOD *ui_method = (UI_METHOD *)OPENSSL_malloc(sizeof(UI_METHOD));
 
     if (ui_method) {
         memset(ui_method, 0, sizeof(*ui_method));
         ui_method->name = BUF_strdup(name);
     }
     return ui_method;
 }
 
 /*
  * BIG FSCKING WARNING!!!! If you use this on a statically allocated method
  * (that is, it hasn't been allocated using UI_create_method(), you deserve
  * anything Murphy can throw at you and more! You have been warned.
  */
 void UI_destroy_method(UI_METHOD *ui_method)
 {
     OPENSSL_free(ui_method->name);
     ui_method->name = NULL;
     OPENSSL_free(ui_method);
 }
 
 int UI_method_set_opener(UI_METHOD *method, int (*opener) (UI *ui))
 {
     if (method != NULL) {
         method->ui_open_session = opener;
         return 0;
     }
     return -1;
 }
 
 int UI_method_set_writer(UI_METHOD *method,
                          int (*writer) (UI *ui, UI_STRING *uis))
 {
     if (method != NULL) {
         method->ui_write_string = writer;
         return 0;
     }
     return -1;
 }
 
 int UI_method_set_flusher(UI_METHOD *method, int (*flusher) (UI *ui))
 {
     if (method != NULL) {
         method->ui_flush = flusher;
         return 0;
     }
     return -1;
 }
 
 int UI_method_set_reader(UI_METHOD *method,
                          int (*reader) (UI *ui, UI_STRING *uis))
 {
     if (method != NULL) {
         method->ui_read_string = reader;
         return 0;
     }
     return -1;
 }
 
 int UI_method_set_closer(UI_METHOD *method, int (*closer) (UI *ui))
 {
     if (method != NULL) {
         method->ui_close_session = closer;
         return 0;
     }
     return -1;
 }
 
 int UI_method_set_prompt_constructor(UI_METHOD *method,
                                      char *(*prompt_constructor) (UI *ui,
                                                                   const char
                                                                   *object_desc,
                                                                   const char
                                                                   *object_name))
 {
     if (method != NULL) {
         method->ui_construct_prompt = prompt_constructor;
         return 0;
     }
     return -1;
 }
 
 int (*UI_method_get_opener(UI_METHOD *method)) (UI *)
 {
     if (method != NULL)
         return method->ui_open_session;
     return NULL;
 }
 
 int (*UI_method_get_writer(UI_METHOD *method)) (UI *, UI_STRING *)
 {
     if (method != NULL)
         return method->ui_write_string;
     return NULL;
 }
 
 int (*UI_method_get_flusher(UI_METHOD *method)) (UI *)
 {
     if (method != NULL)
         return method->ui_flush;
     return NULL;
 }
 
 int (*UI_method_get_reader(UI_METHOD *method)) (UI *, UI_STRING *)
 {
     if (method != NULL)
         return method->ui_read_string;
     return NULL;
 }
 
 int (*UI_method_get_closer(UI_METHOD *method)) (UI *)
 {
     if (method != NULL)
         return method->ui_close_session;
     return NULL;
 }
 
 char *(*UI_method_get_prompt_constructor(UI_METHOD *method)) (UI *,
                                                               const char *,
                                                               const char *)
 {
     if (method != NULL)
         return method->ui_construct_prompt;
     return NULL;
 }
 
 enum UI_string_types UI_get_string_type(UI_STRING *uis)
 {
     if (!uis)
         return UIT_NONE;
     return uis->type;
 }
 
 int UI_get_input_flags(UI_STRING *uis)
 {
     if (!uis)
         return 0;
     return uis->input_flags;
 }
 
 const char *UI_get0_output_string(UI_STRING *uis)
 {
     if (!uis)
         return NULL;
     return uis->out_string;
 }
 
 const char *UI_get0_action_string(UI_STRING *uis)
 {
     if (!uis)
         return NULL;
     switch (uis->type) {
-    case UIT_PROMPT:
     case UIT_BOOLEAN:
         return uis->_.boolean_data.action_desc;
     default:
         return NULL;
     }
 }
 
 const char *UI_get0_result_string(UI_STRING *uis)
 {
     if (!uis)
         return NULL;
     switch (uis->type) {
     case UIT_PROMPT:
     case UIT_VERIFY:
         return uis->result_buf;
     default:
         return NULL;
     }
 }
 
 const char *UI_get0_test_string(UI_STRING *uis)
 {
     if (!uis)
         return NULL;
     switch (uis->type) {
     case UIT_VERIFY:
         return uis->_.string_data.test_buf;
     default:
         return NULL;
     }
 }
 
 int UI_get_result_minsize(UI_STRING *uis)
 {
     if (!uis)
         return -1;
     switch (uis->type) {
     case UIT_PROMPT:
     case UIT_VERIFY:
         return uis->_.string_data.result_minsize;
     default:
         return -1;
     }
 }
 
 int UI_get_result_maxsize(UI_STRING *uis)
 {
     if (!uis)
         return -1;
     switch (uis->type) {
     case UIT_PROMPT:
     case UIT_VERIFY:
         return uis->_.string_data.result_maxsize;
     default:
         return -1;
     }
 }
 
 int UI_set_result(UI *ui, UI_STRING *uis, const char *result)
 {
     int l = strlen(result);
 
     ui->flags &= ~UI_FLAG_REDOABLE;
 
     if (!uis)
         return -1;
     switch (uis->type) {
     case UIT_PROMPT:
     case UIT_VERIFY:
         {
             char number1[DECIMAL_SIZE(uis->_.string_data.result_minsize) + 1];
             char number2[DECIMAL_SIZE(uis->_.string_data.result_maxsize) + 1];
 
             BIO_snprintf(number1, sizeof(number1), "%d",
                          uis->_.string_data.result_minsize);
             BIO_snprintf(number2, sizeof(number2), "%d",
                          uis->_.string_data.result_maxsize);
 
             if (l < uis->_.string_data.result_minsize) {
                 ui->flags |= UI_FLAG_REDOABLE;
                 UIerr(UI_F_UI_SET_RESULT, UI_R_RESULT_TOO_SMALL);
                 ERR_add_error_data(5, "You must type in ",
                                    number1, " to ", number2, " characters");
                 return -1;
             }
             if (l > uis->_.string_data.result_maxsize) {
                 ui->flags |= UI_FLAG_REDOABLE;
                 UIerr(UI_F_UI_SET_RESULT, UI_R_RESULT_TOO_LARGE);
                 ERR_add_error_data(5, "You must type in ",
                                    number1, " to ", number2, " characters");
                 return -1;
             }
         }
 
         if (!uis->result_buf) {
             UIerr(UI_F_UI_SET_RESULT, UI_R_NO_RESULT_BUFFER);
             return -1;
         }
 
         BUF_strlcpy(uis->result_buf, result,
                     uis->_.string_data.result_maxsize + 1);
         break;
     case UIT_BOOLEAN:
         {
             const char *p;
 
             if (!uis->result_buf) {
                 UIerr(UI_F_UI_SET_RESULT, UI_R_NO_RESULT_BUFFER);
                 return -1;
             }
 
             uis->result_buf[0] = '\0';
             for (p = result; *p; p++) {
                 if (strchr(uis->_.boolean_data.ok_chars, *p)) {
                     uis->result_buf[0] = uis->_.boolean_data.ok_chars[0];
                     break;
                 }
                 if (strchr(uis->_.boolean_data.cancel_chars, *p)) {
                     uis->result_buf[0] = uis->_.boolean_data.cancel_chars[0];
                     break;
                 }
             }
         }
     default:
         break;
     }
     return 0;
 }
Index: vendor-crypto/openssl/dist/crypto/x509/x509_lu.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/x509/x509_lu.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/x509/x509_lu.c	(revision 318897)
@@ -1,710 +1,727 @@
 /* crypto/x509/x509_lu.c */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
  * This package is an SSL implementation written
  * by Eric Young (eay@cryptsoft.com).
  * The implementation was written so as to conform with Netscapes SSL.
  *
  * This library is free for commercial and non-commercial use as long as
  * the following conditions are aheared to.  The following conditions
  * apply to all code found in this distribution, be it the RC4, RSA,
  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
  * included with this distribution is covered by the same copyright terms
  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  *
  * Copyright remains Eric Young's, and as such any Copyright notices in
  * the code are not to be removed.
  * If this package is used in a product, Eric Young should be given attribution
  * as the author of the parts of the library used.
  * This can be in the form of a textual message at program startup or
  * in documentation (online or textual) provided with the package.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  * 3. All advertising materials mentioning features or use of this software
  *    must display the following acknowledgement:
  *    "This product includes cryptographic software written by
  *     Eric Young (eay@cryptsoft.com)"
  *    The word 'cryptographic' can be left out if the rouines from the library
  *    being used are not cryptographic related :-).
  * 4. If you include any Windows specific code (or a derivative thereof) from
  *    the apps directory (application code) you must include an acknowledgement:
  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  *
  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
  * The licence and distribution terms for any publically available version or
  * derivative of this code cannot be changed.  i.e. this code cannot simply be
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
 
 #include 
 #include "cryptlib.h"
 #include 
 #include 
 #include 
 
 X509_LOOKUP *X509_LOOKUP_new(X509_LOOKUP_METHOD *method)
 {
     X509_LOOKUP *ret;
 
     ret = (X509_LOOKUP *)OPENSSL_malloc(sizeof(X509_LOOKUP));
     if (ret == NULL)
         return NULL;
 
     ret->init = 0;
     ret->skip = 0;
     ret->method = method;
     ret->method_data = NULL;
     ret->store_ctx = NULL;
     if ((method->new_item != NULL) && !method->new_item(ret)) {
         OPENSSL_free(ret);
         return NULL;
     }
     return ret;
 }
 
 void X509_LOOKUP_free(X509_LOOKUP *ctx)
 {
     if (ctx == NULL)
         return;
     if ((ctx->method != NULL) && (ctx->method->free != NULL))
         (*ctx->method->free) (ctx);
     OPENSSL_free(ctx);
 }
 
 int X509_LOOKUP_init(X509_LOOKUP *ctx)
 {
     if (ctx->method == NULL)
         return 0;
     if (ctx->method->init != NULL)
         return ctx->method->init(ctx);
     else
         return 1;
 }
 
 int X509_LOOKUP_shutdown(X509_LOOKUP *ctx)
 {
     if (ctx->method == NULL)
         return 0;
     if (ctx->method->shutdown != NULL)
         return ctx->method->shutdown(ctx);
     else
         return 1;
 }
 
 int X509_LOOKUP_ctrl(X509_LOOKUP *ctx, int cmd, const char *argc, long argl,
                      char **ret)
 {
     if (ctx->method == NULL)
         return -1;
     if (ctx->method->ctrl != NULL)
         return ctx->method->ctrl(ctx, cmd, argc, argl, ret);
     else
         return 1;
 }
 
 int X509_LOOKUP_by_subject(X509_LOOKUP *ctx, int type, X509_NAME *name,
                            X509_OBJECT *ret)
 {
     if ((ctx->method == NULL) || (ctx->method->get_by_subject == NULL))
         return X509_LU_FAIL;
     if (ctx->skip)
         return 0;
     return ctx->method->get_by_subject(ctx, type, name, ret);
 }
 
 int X509_LOOKUP_by_issuer_serial(X509_LOOKUP *ctx, int type, X509_NAME *name,
                                  ASN1_INTEGER *serial, X509_OBJECT *ret)
 {
     if ((ctx->method == NULL) || (ctx->method->get_by_issuer_serial == NULL))
         return X509_LU_FAIL;
     return ctx->method->get_by_issuer_serial(ctx, type, name, serial, ret);
 }
 
 int X509_LOOKUP_by_fingerprint(X509_LOOKUP *ctx, int type,
                                unsigned char *bytes, int len,
                                X509_OBJECT *ret)
 {
     if ((ctx->method == NULL) || (ctx->method->get_by_fingerprint == NULL))
         return X509_LU_FAIL;
     return ctx->method->get_by_fingerprint(ctx, type, bytes, len, ret);
 }
 
 int X509_LOOKUP_by_alias(X509_LOOKUP *ctx, int type, char *str, int len,
                          X509_OBJECT *ret)
 {
     if ((ctx->method == NULL) || (ctx->method->get_by_alias == NULL))
         return X509_LU_FAIL;
     return ctx->method->get_by_alias(ctx, type, str, len, ret);
 }
 
 static int x509_object_cmp(const X509_OBJECT *const *a,
                            const X509_OBJECT *const *b)
 {
     int ret;
 
     ret = ((*a)->type - (*b)->type);
     if (ret)
         return ret;
     switch ((*a)->type) {
     case X509_LU_X509:
         ret = X509_subject_name_cmp((*a)->data.x509, (*b)->data.x509);
         break;
     case X509_LU_CRL:
         ret = X509_CRL_cmp((*a)->data.crl, (*b)->data.crl);
         break;
     default:
         /* abort(); */
         return 0;
     }
     return ret;
 }
 
 X509_STORE *X509_STORE_new(void)
 {
     X509_STORE *ret;
 
     if ((ret = (X509_STORE *)OPENSSL_malloc(sizeof(X509_STORE))) == NULL)
         return NULL;
-    ret->objs = sk_X509_OBJECT_new(x509_object_cmp);
+    if ((ret->objs = sk_X509_OBJECT_new(x509_object_cmp)) == NULL)
+        goto err0;
     ret->cache = 1;
-    ret->get_cert_methods = sk_X509_LOOKUP_new_null();
+    if ((ret->get_cert_methods = sk_X509_LOOKUP_new_null()) == NULL)
+        goto err1;
     ret->verify = 0;
     ret->verify_cb = 0;
 
     if ((ret->param = X509_VERIFY_PARAM_new()) == NULL)
-        return NULL;
+        goto err2;
 
     ret->get_issuer = 0;
     ret->check_issued = 0;
     ret->check_revocation = 0;
     ret->get_crl = 0;
     ret->check_crl = 0;
     ret->cert_crl = 0;
     ret->lookup_certs = 0;
     ret->lookup_crls = 0;
     ret->cleanup = 0;
 
-    if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE, ret, &ret->ex_data)) {
-        sk_X509_OBJECT_free(ret->objs);
-        OPENSSL_free(ret);
-        return NULL;
-    }
+    if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE, ret, &ret->ex_data))
+       goto err3;
 
     ret->references = 1;
     return ret;
+
+ err3:
+    X509_VERIFY_PARAM_free(ret->param);
+ err2:
+    sk_X509_LOOKUP_free(ret->get_cert_methods);
+ err1:
+    sk_X509_OBJECT_free(ret->objs);
+ err0:
+    OPENSSL_free(ret);
+    return NULL;
 }
 
 static void cleanup(X509_OBJECT *a)
 {
     if (!a)
         return;
     if (a->type == X509_LU_X509) {
         X509_free(a->data.x509);
     } else if (a->type == X509_LU_CRL) {
         X509_CRL_free(a->data.crl);
     } else {
         /* abort(); */
     }
 
     OPENSSL_free(a);
 }
 
 void X509_STORE_free(X509_STORE *vfy)
 {
     int i;
     STACK_OF(X509_LOOKUP) *sk;
     X509_LOOKUP *lu;
 
     if (vfy == NULL)
         return;
 
     i = CRYPTO_add(&vfy->references, -1, CRYPTO_LOCK_X509_STORE);
 #ifdef REF_PRINT
     REF_PRINT("X509_STORE", vfy);
 #endif
     if (i > 0)
         return;
 #ifdef REF_CHECK
     if (i < 0) {
         fprintf(stderr, "X509_STORE_free, bad reference count\n");
         abort();                /* ok */
     }
 #endif
 
     sk = vfy->get_cert_methods;
     for (i = 0; i < sk_X509_LOOKUP_num(sk); i++) {
         lu = sk_X509_LOOKUP_value(sk, i);
         X509_LOOKUP_shutdown(lu);
         X509_LOOKUP_free(lu);
     }
     sk_X509_LOOKUP_free(sk);
     sk_X509_OBJECT_pop_free(vfy->objs, cleanup);
 
     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509_STORE, vfy, &vfy->ex_data);
     if (vfy->param)
         X509_VERIFY_PARAM_free(vfy->param);
     OPENSSL_free(vfy);
 }
 
 X509_LOOKUP *X509_STORE_add_lookup(X509_STORE *v, X509_LOOKUP_METHOD *m)
 {
     int i;
     STACK_OF(X509_LOOKUP) *sk;
     X509_LOOKUP *lu;
 
     sk = v->get_cert_methods;
     for (i = 0; i < sk_X509_LOOKUP_num(sk); i++) {
         lu = sk_X509_LOOKUP_value(sk, i);
         if (m == lu->method) {
             return lu;
         }
     }
     /* a new one */
     lu = X509_LOOKUP_new(m);
     if (lu == NULL)
         return NULL;
     else {
         lu->store_ctx = v;
         if (sk_X509_LOOKUP_push(v->get_cert_methods, lu))
             return lu;
         else {
             X509_LOOKUP_free(lu);
             return NULL;
         }
     }
 }
 
 int X509_STORE_get_by_subject(X509_STORE_CTX *vs, int type, X509_NAME *name,
                               X509_OBJECT *ret)
 {
     X509_STORE *ctx = vs->ctx;
     X509_LOOKUP *lu;
     X509_OBJECT stmp, *tmp;
     int i, j;
 
     CRYPTO_w_lock(CRYPTO_LOCK_X509_STORE);
     tmp = X509_OBJECT_retrieve_by_subject(ctx->objs, type, name);
     CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
 
     if (tmp == NULL || type == X509_LU_CRL) {
         for (i = vs->current_method;
              i < sk_X509_LOOKUP_num(ctx->get_cert_methods); i++) {
             lu = sk_X509_LOOKUP_value(ctx->get_cert_methods, i);
             j = X509_LOOKUP_by_subject(lu, type, name, &stmp);
             if (j < 0) {
                 vs->current_method = j;
                 return j;
             } else if (j) {
                 tmp = &stmp;
                 break;
             }
         }
         vs->current_method = 0;
         if (tmp == NULL)
             return 0;
     }
 
 /*- if (ret->data.ptr != NULL)
             X509_OBJECT_free_contents(ret); */
 
     ret->type = tmp->type;
     ret->data.ptr = tmp->data.ptr;
 
     X509_OBJECT_up_ref_count(ret);
 
     return 1;
 }
 
 int X509_STORE_add_cert(X509_STORE *ctx, X509 *x)
 {
     X509_OBJECT *obj;
     int ret = 1;
 
     if (x == NULL)
         return 0;
     obj = (X509_OBJECT *)OPENSSL_malloc(sizeof(X509_OBJECT));
     if (obj == NULL) {
         X509err(X509_F_X509_STORE_ADD_CERT, ERR_R_MALLOC_FAILURE);
         return 0;
     }
     obj->type = X509_LU_X509;
     obj->data.x509 = x;
 
     CRYPTO_w_lock(CRYPTO_LOCK_X509_STORE);
 
     X509_OBJECT_up_ref_count(obj);
 
     if (X509_OBJECT_retrieve_match(ctx->objs, obj)) {
         X509_OBJECT_free_contents(obj);
         OPENSSL_free(obj);
         X509err(X509_F_X509_STORE_ADD_CERT,
                 X509_R_CERT_ALREADY_IN_HASH_TABLE);
         ret = 0;
-    } else
-        sk_X509_OBJECT_push(ctx->objs, obj);
+    } else if (!sk_X509_OBJECT_push(ctx->objs, obj)) {
+        X509_OBJECT_free_contents(obj);
+        OPENSSL_free(obj);
+        X509err(X509_F_X509_STORE_ADD_CERT, ERR_R_MALLOC_FAILURE);
+        ret = 0;
+    }
 
     CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
 
     return ret;
 }
 
 int X509_STORE_add_crl(X509_STORE *ctx, X509_CRL *x)
 {
     X509_OBJECT *obj;
     int ret = 1;
 
     if (x == NULL)
         return 0;
     obj = (X509_OBJECT *)OPENSSL_malloc(sizeof(X509_OBJECT));
     if (obj == NULL) {
         X509err(X509_F_X509_STORE_ADD_CRL, ERR_R_MALLOC_FAILURE);
         return 0;
     }
     obj->type = X509_LU_CRL;
     obj->data.crl = x;
 
     CRYPTO_w_lock(CRYPTO_LOCK_X509_STORE);
 
     X509_OBJECT_up_ref_count(obj);
 
     if (X509_OBJECT_retrieve_match(ctx->objs, obj)) {
         X509_OBJECT_free_contents(obj);
         OPENSSL_free(obj);
         X509err(X509_F_X509_STORE_ADD_CRL, X509_R_CERT_ALREADY_IN_HASH_TABLE);
         ret = 0;
-    } else
-        sk_X509_OBJECT_push(ctx->objs, obj);
+    } else if (!sk_X509_OBJECT_push(ctx->objs, obj)) {
+        X509_OBJECT_free_contents(obj);
+        OPENSSL_free(obj);
+        X509err(X509_F_X509_STORE_ADD_CRL, ERR_R_MALLOC_FAILURE);
+        ret = 0;
+    }
 
     CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
 
     return ret;
 }
 
 void X509_OBJECT_up_ref_count(X509_OBJECT *a)
 {
     switch (a->type) {
     case X509_LU_X509:
         CRYPTO_add(&a->data.x509->references, 1, CRYPTO_LOCK_X509);
         break;
     case X509_LU_CRL:
         CRYPTO_add(&a->data.crl->references, 1, CRYPTO_LOCK_X509_CRL);
         break;
     }
 }
 
 void X509_OBJECT_free_contents(X509_OBJECT *a)
 {
     switch (a->type) {
     case X509_LU_X509:
         X509_free(a->data.x509);
         break;
     case X509_LU_CRL:
         X509_CRL_free(a->data.crl);
         break;
     }
 }
 
 static int x509_object_idx_cnt(STACK_OF(X509_OBJECT) *h, int type,
                                X509_NAME *name, int *pnmatch)
 {
     X509_OBJECT stmp;
     X509 x509_s;
     X509_CINF cinf_s;
     X509_CRL crl_s;
     X509_CRL_INFO crl_info_s;
     int idx;
 
     stmp.type = type;
     switch (type) {
     case X509_LU_X509:
         stmp.data.x509 = &x509_s;
         x509_s.cert_info = &cinf_s;
         cinf_s.subject = name;
         break;
     case X509_LU_CRL:
         stmp.data.crl = &crl_s;
         crl_s.crl = &crl_info_s;
         crl_info_s.issuer = name;
         break;
     default:
         /* abort(); */
         return -1;
     }
 
     idx = sk_X509_OBJECT_find(h, &stmp);
     if (idx >= 0 && pnmatch) {
         int tidx;
         const X509_OBJECT *tobj, *pstmp;
         *pnmatch = 1;
         pstmp = &stmp;
         for (tidx = idx + 1; tidx < sk_X509_OBJECT_num(h); tidx++) {
             tobj = sk_X509_OBJECT_value(h, tidx);
             if (x509_object_cmp(&tobj, &pstmp))
                 break;
             (*pnmatch)++;
         }
     }
     return idx;
 }
 
 int X509_OBJECT_idx_by_subject(STACK_OF(X509_OBJECT) *h, int type,
                                X509_NAME *name)
 {
     return x509_object_idx_cnt(h, type, name, NULL);
 }
 
 X509_OBJECT *X509_OBJECT_retrieve_by_subject(STACK_OF(X509_OBJECT) *h,
                                              int type, X509_NAME *name)
 {
     int idx;
     idx = X509_OBJECT_idx_by_subject(h, type, name);
     if (idx == -1)
         return NULL;
     return sk_X509_OBJECT_value(h, idx);
 }
 
 STACK_OF(X509) *X509_STORE_get1_certs(X509_STORE_CTX *ctx, X509_NAME *nm)
 {
     int i, idx, cnt;
     STACK_OF(X509) *sk;
     X509 *x;
     X509_OBJECT *obj;
     sk = sk_X509_new_null();
     CRYPTO_w_lock(CRYPTO_LOCK_X509_STORE);
     idx = x509_object_idx_cnt(ctx->ctx->objs, X509_LU_X509, nm, &cnt);
     if (idx < 0) {
         /*
          * Nothing found in cache: do lookup to possibly add new objects to
          * cache
          */
         X509_OBJECT xobj;
         CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
         if (!X509_STORE_get_by_subject(ctx, X509_LU_X509, nm, &xobj)) {
             sk_X509_free(sk);
             return NULL;
         }
         X509_OBJECT_free_contents(&xobj);
         CRYPTO_w_lock(CRYPTO_LOCK_X509_STORE);
         idx = x509_object_idx_cnt(ctx->ctx->objs, X509_LU_X509, nm, &cnt);
         if (idx < 0) {
             CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
             sk_X509_free(sk);
             return NULL;
         }
     }
     for (i = 0; i < cnt; i++, idx++) {
         obj = sk_X509_OBJECT_value(ctx->ctx->objs, idx);
         x = obj->data.x509;
         CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
         if (!sk_X509_push(sk, x)) {
             CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
             X509_free(x);
             sk_X509_pop_free(sk, X509_free);
             return NULL;
         }
     }
     CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
     return sk;
 
 }
 
 STACK_OF(X509_CRL) *X509_STORE_get1_crls(X509_STORE_CTX *ctx, X509_NAME *nm)
 {
     int i, idx, cnt;
     STACK_OF(X509_CRL) *sk;
     X509_CRL *x;
     X509_OBJECT *obj, xobj;
     sk = sk_X509_CRL_new_null();
     CRYPTO_w_lock(CRYPTO_LOCK_X509_STORE);
 
     /*
      * Always do lookup to possibly add new CRLs to cache
      */
     CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
     if (!X509_STORE_get_by_subject(ctx, X509_LU_CRL, nm, &xobj)) {
         sk_X509_CRL_free(sk);
         return NULL;
     }
     X509_OBJECT_free_contents(&xobj);
     CRYPTO_w_lock(CRYPTO_LOCK_X509_STORE);
     idx = x509_object_idx_cnt(ctx->ctx->objs, X509_LU_CRL, nm, &cnt);
     if (idx < 0) {
         CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
         sk_X509_CRL_free(sk);
         return NULL;
     }
 
     for (i = 0; i < cnt; i++, idx++) {
         obj = sk_X509_OBJECT_value(ctx->ctx->objs, idx);
         x = obj->data.crl;
         CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509_CRL);
         if (!sk_X509_CRL_push(sk, x)) {
             CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
             X509_CRL_free(x);
             sk_X509_CRL_pop_free(sk, X509_CRL_free);
             return NULL;
         }
     }
     CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
     return sk;
 }
 
 X509_OBJECT *X509_OBJECT_retrieve_match(STACK_OF(X509_OBJECT) *h,
                                         X509_OBJECT *x)
 {
     int idx, i;
     X509_OBJECT *obj;
     idx = sk_X509_OBJECT_find(h, x);
     if (idx == -1)
         return NULL;
     if ((x->type != X509_LU_X509) && (x->type != X509_LU_CRL))
         return sk_X509_OBJECT_value(h, idx);
     for (i = idx; i < sk_X509_OBJECT_num(h); i++) {
         obj = sk_X509_OBJECT_value(h, i);
         if (x509_object_cmp
             ((const X509_OBJECT **)&obj, (const X509_OBJECT **)&x))
             return NULL;
         if (x->type == X509_LU_X509) {
             if (!X509_cmp(obj->data.x509, x->data.x509))
                 return obj;
         } else if (x->type == X509_LU_CRL) {
             if (!X509_CRL_match(obj->data.crl, x->data.crl))
                 return obj;
         } else
             return obj;
     }
     return NULL;
 }
 
 /*-
  * Try to get issuer certificate from store. Due to limitations
  * of the API this can only retrieve a single certificate matching
  * a given subject name. However it will fill the cache with all
  * matching certificates, so we can examine the cache for all
  * matches.
  *
  * Return values are:
  *  1 lookup successful.
  *  0 certificate not found.
  * -1 some other error.
  */
 int X509_STORE_CTX_get1_issuer(X509 **issuer, X509_STORE_CTX *ctx, X509 *x)
 {
     X509_NAME *xn;
     X509_OBJECT obj, *pobj;
     int i, ok, idx, ret;
     xn = X509_get_issuer_name(x);
     ok = X509_STORE_get_by_subject(ctx, X509_LU_X509, xn, &obj);
     if (ok != X509_LU_X509) {
         if (ok == X509_LU_RETRY) {
             X509_OBJECT_free_contents(&obj);
             X509err(X509_F_X509_STORE_CTX_GET1_ISSUER, X509_R_SHOULD_RETRY);
             return -1;
         } else if (ok != X509_LU_FAIL) {
             X509_OBJECT_free_contents(&obj);
             /* not good :-(, break anyway */
             return -1;
         }
         return 0;
     }
     /* If certificate matches all OK */
     if (ctx->check_issued(ctx, x, obj.data.x509)) {
         *issuer = obj.data.x509;
         return 1;
     }
     X509_OBJECT_free_contents(&obj);
 
     /* Else find index of first cert accepted by 'check_issued' */
     ret = 0;
     CRYPTO_w_lock(CRYPTO_LOCK_X509_STORE);
     idx = X509_OBJECT_idx_by_subject(ctx->ctx->objs, X509_LU_X509, xn);
     if (idx != -1) {            /* should be true as we've had at least one
                                  * match */
         /* Look through all matching certs for suitable issuer */
         for (i = idx; i < sk_X509_OBJECT_num(ctx->ctx->objs); i++) {
             pobj = sk_X509_OBJECT_value(ctx->ctx->objs, i);
             /* See if we've run past the matches */
             if (pobj->type != X509_LU_X509)
                 break;
             if (X509_NAME_cmp(xn, X509_get_subject_name(pobj->data.x509)))
                 break;
             if (ctx->check_issued(ctx, x, pobj->data.x509)) {
                 *issuer = pobj->data.x509;
                 X509_OBJECT_up_ref_count(pobj);
                 ret = 1;
                 break;
             }
         }
     }
     CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
     return ret;
 }
 
 int X509_STORE_set_flags(X509_STORE *ctx, unsigned long flags)
 {
     return X509_VERIFY_PARAM_set_flags(ctx->param, flags);
 }
 
 int X509_STORE_set_depth(X509_STORE *ctx, int depth)
 {
     X509_VERIFY_PARAM_set_depth(ctx->param, depth);
     return 1;
 }
 
 int X509_STORE_set_purpose(X509_STORE *ctx, int purpose)
 {
     return X509_VERIFY_PARAM_set_purpose(ctx->param, purpose);
 }
 
 int X509_STORE_set_trust(X509_STORE *ctx, int trust)
 {
     return X509_VERIFY_PARAM_set_trust(ctx->param, trust);
 }
 
 int X509_STORE_set1_param(X509_STORE *ctx, X509_VERIFY_PARAM *param)
 {
     return X509_VERIFY_PARAM_set1(ctx->param, param);
 }
 
 void X509_STORE_set_verify_cb(X509_STORE *ctx,
                               int (*verify_cb) (int, X509_STORE_CTX *))
 {
     ctx->verify_cb = verify_cb;
 }
 
 void X509_STORE_set_lookup_crls_cb(X509_STORE *ctx,
                                    STACK_OF(X509_CRL) *(*cb) (X509_STORE_CTX
                                                               *ctx,
                                                               X509_NAME *nm))
 {
     ctx->lookup_crls = cb;
 }
 
 X509_STORE *X509_STORE_CTX_get0_store(X509_STORE_CTX *ctx)
 {
     return ctx->ctx;
 }
 
 IMPLEMENT_STACK_OF(X509_LOOKUP)
 
 IMPLEMENT_STACK_OF(X509_OBJECT)
Index: vendor-crypto/openssl/dist/crypto/x509v3/v3_alt.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/x509v3/v3_alt.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/x509v3/v3_alt.c	(revision 318897)
@@ -1,611 +1,621 @@
 /* v3_alt.c */
 /*
  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
  * project.
  */
 /* ====================================================================
  * Copyright (c) 1999-2003 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    licensing@OpenSSL.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #include 
 #include "cryptlib.h"
 #include 
 #include 
 
 static GENERAL_NAMES *v2i_subject_alt(X509V3_EXT_METHOD *method,
                                       X509V3_CTX *ctx,
                                       STACK_OF(CONF_VALUE) *nval);
 static GENERAL_NAMES *v2i_issuer_alt(X509V3_EXT_METHOD *method,
                                      X509V3_CTX *ctx,
                                      STACK_OF(CONF_VALUE) *nval);
 static int copy_email(X509V3_CTX *ctx, GENERAL_NAMES *gens, int move_p);
 static int copy_issuer(X509V3_CTX *ctx, GENERAL_NAMES *gens);
 static int do_othername(GENERAL_NAME *gen, char *value, X509V3_CTX *ctx);
 static int do_dirname(GENERAL_NAME *gen, char *value, X509V3_CTX *ctx);
 
 const X509V3_EXT_METHOD v3_alt[] = {
     {NID_subject_alt_name, 0, ASN1_ITEM_ref(GENERAL_NAMES),
      0, 0, 0, 0,
      0, 0,
      (X509V3_EXT_I2V) i2v_GENERAL_NAMES,
      (X509V3_EXT_V2I)v2i_subject_alt,
      NULL, NULL, NULL},
 
     {NID_issuer_alt_name, 0, ASN1_ITEM_ref(GENERAL_NAMES),
      0, 0, 0, 0,
      0, 0,
      (X509V3_EXT_I2V) i2v_GENERAL_NAMES,
      (X509V3_EXT_V2I)v2i_issuer_alt,
      NULL, NULL, NULL},
 
     {NID_certificate_issuer, 0, ASN1_ITEM_ref(GENERAL_NAMES),
      0, 0, 0, 0,
      0, 0,
      (X509V3_EXT_I2V) i2v_GENERAL_NAMES,
      NULL, NULL, NULL, NULL},
 };
 
 STACK_OF(CONF_VALUE) *i2v_GENERAL_NAMES(X509V3_EXT_METHOD *method,
                                         GENERAL_NAMES *gens,
                                         STACK_OF(CONF_VALUE) *ret)
 {
     int i;
     GENERAL_NAME *gen;
     for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
         gen = sk_GENERAL_NAME_value(gens, i);
         ret = i2v_GENERAL_NAME(method, gen, ret);
     }
     if (!ret)
         return sk_CONF_VALUE_new_null();
     return ret;
 }
 
 STACK_OF(CONF_VALUE) *i2v_GENERAL_NAME(X509V3_EXT_METHOD *method,
                                        GENERAL_NAME *gen,
                                        STACK_OF(CONF_VALUE) *ret)
 {
     unsigned char *p;
     char oline[256], htmp[5];
     int i;
     switch (gen->type) {
     case GEN_OTHERNAME:
-        X509V3_add_value("othername", "", &ret);
+        if (!X509V3_add_value("othername", "", &ret))
+            return NULL;
         break;
 
     case GEN_X400:
-        X509V3_add_value("X400Name", "", &ret);
+        if (!X509V3_add_value("X400Name", "", &ret))
+            return NULL;
         break;
 
     case GEN_EDIPARTY:
-        X509V3_add_value("EdiPartyName", "", &ret);
+        if (!X509V3_add_value("EdiPartyName", "", &ret))
+            return NULL;
         break;
 
     case GEN_EMAIL:
-        X509V3_add_value_uchar("email", gen->d.ia5->data, &ret);
+        if (!X509V3_add_value_uchar("email", gen->d.ia5->data, &ret))
+            return NULL;
         break;
 
     case GEN_DNS:
-        X509V3_add_value_uchar("DNS", gen->d.ia5->data, &ret);
+        if (!X509V3_add_value_uchar("DNS", gen->d.ia5->data, &ret))
+            return NULL;
         break;
 
     case GEN_URI:
-        X509V3_add_value_uchar("URI", gen->d.ia5->data, &ret);
+        if (!X509V3_add_value_uchar("URI", gen->d.ia5->data, &ret))
+            return NULL;
         break;
 
     case GEN_DIRNAME:
-        X509_NAME_oneline(gen->d.dirn, oline, 256);
-        X509V3_add_value("DirName", oline, &ret);
+        if (X509_NAME_oneline(gen->d.dirn, oline, 256) == NULL
+                || !X509V3_add_value("DirName", oline, &ret))
+            return NULL;
         break;
 
     case GEN_IPADD:
         p = gen->d.ip->data;
         if (gen->d.ip->length == 4)
             BIO_snprintf(oline, sizeof oline,
                          "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
         else if (gen->d.ip->length == 16) {
             oline[0] = 0;
             for (i = 0; i < 8; i++) {
                 BIO_snprintf(htmp, sizeof htmp, "%X", p[0] << 8 | p[1]);
                 p += 2;
                 strcat(oline, htmp);
                 if (i != 7)
                     strcat(oline, ":");
             }
         } else {
-            X509V3_add_value("IP Address", "", &ret);
+            if (!X509V3_add_value("IP Address", "", &ret))
+                return NULL;
             break;
         }
-        X509V3_add_value("IP Address", oline, &ret);
+        if (!X509V3_add_value("IP Address", oline, &ret))
+            return NULL;
         break;
 
     case GEN_RID:
         i2t_ASN1_OBJECT(oline, 256, gen->d.rid);
-        X509V3_add_value("Registered ID", oline, &ret);
+        if (!X509V3_add_value("Registered ID", oline, &ret))
+            return NULL;
         break;
     }
     return ret;
 }
 
 int GENERAL_NAME_print(BIO *out, GENERAL_NAME *gen)
 {
     unsigned char *p;
     int i;
     switch (gen->type) {
     case GEN_OTHERNAME:
         BIO_printf(out, "othername:");
         break;
 
     case GEN_X400:
         BIO_printf(out, "X400Name:");
         break;
 
     case GEN_EDIPARTY:
         /* Maybe fix this: it is supported now */
         BIO_printf(out, "EdiPartyName:");
         break;
 
     case GEN_EMAIL:
         BIO_printf(out, "email:%s", gen->d.ia5->data);
         break;
 
     case GEN_DNS:
         BIO_printf(out, "DNS:%s", gen->d.ia5->data);
         break;
 
     case GEN_URI:
         BIO_printf(out, "URI:%s", gen->d.ia5->data);
         break;
 
     case GEN_DIRNAME:
         BIO_printf(out, "DirName: ");
         X509_NAME_print_ex(out, gen->d.dirn, 0, XN_FLAG_ONELINE);
         break;
 
     case GEN_IPADD:
         p = gen->d.ip->data;
         if (gen->d.ip->length == 4)
             BIO_printf(out, "IP Address:%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
         else if (gen->d.ip->length == 16) {
             BIO_printf(out, "IP Address");
             for (i = 0; i < 8; i++) {
                 BIO_printf(out, ":%X", p[0] << 8 | p[1]);
                 p += 2;
             }
             BIO_puts(out, "\n");
         } else {
             BIO_printf(out, "IP Address:");
             break;
         }
         break;
 
     case GEN_RID:
         BIO_printf(out, "Registered ID");
         i2a_ASN1_OBJECT(out, gen->d.rid);
         break;
     }
     return 1;
 }
 
 static GENERAL_NAMES *v2i_issuer_alt(X509V3_EXT_METHOD *method,
                                      X509V3_CTX *ctx,
                                      STACK_OF(CONF_VALUE) *nval)
 {
     GENERAL_NAMES *gens = NULL;
     CONF_VALUE *cnf;
     int i;
     if (!(gens = sk_GENERAL_NAME_new_null())) {
         X509V3err(X509V3_F_V2I_ISSUER_ALT, ERR_R_MALLOC_FAILURE);
         return NULL;
     }
     for (i = 0; i < sk_CONF_VALUE_num(nval); i++) {
         cnf = sk_CONF_VALUE_value(nval, i);
         if (!name_cmp(cnf->name, "issuer") && cnf->value &&
             !strcmp(cnf->value, "copy")) {
             if (!copy_issuer(ctx, gens))
                 goto err;
         } else {
             GENERAL_NAME *gen;
             if (!(gen = v2i_GENERAL_NAME(method, ctx, cnf)))
                 goto err;
             sk_GENERAL_NAME_push(gens, gen);
         }
     }
     return gens;
  err:
     sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
     return NULL;
 }
 
 /* Append subject altname of issuer to issuer alt name of subject */
 
 static int copy_issuer(X509V3_CTX *ctx, GENERAL_NAMES *gens)
 {
     GENERAL_NAMES *ialt;
     GENERAL_NAME *gen;
     X509_EXTENSION *ext;
     int i;
     if (ctx && (ctx->flags == CTX_TEST))
         return 1;
     if (!ctx || !ctx->issuer_cert) {
         X509V3err(X509V3_F_COPY_ISSUER, X509V3_R_NO_ISSUER_DETAILS);
         goto err;
     }
     i = X509_get_ext_by_NID(ctx->issuer_cert, NID_subject_alt_name, -1);
     if (i < 0)
         return 1;
     if (!(ext = X509_get_ext(ctx->issuer_cert, i)) ||
         !(ialt = X509V3_EXT_d2i(ext))) {
         X509V3err(X509V3_F_COPY_ISSUER, X509V3_R_ISSUER_DECODE_ERROR);
         goto err;
     }
 
     for (i = 0; i < sk_GENERAL_NAME_num(ialt); i++) {
         gen = sk_GENERAL_NAME_value(ialt, i);
         if (!sk_GENERAL_NAME_push(gens, gen)) {
             X509V3err(X509V3_F_COPY_ISSUER, ERR_R_MALLOC_FAILURE);
             goto err;
         }
     }
     sk_GENERAL_NAME_free(ialt);
 
     return 1;
 
  err:
     return 0;
 
 }
 
 static GENERAL_NAMES *v2i_subject_alt(X509V3_EXT_METHOD *method,
                                       X509V3_CTX *ctx,
                                       STACK_OF(CONF_VALUE) *nval)
 {
     GENERAL_NAMES *gens = NULL;
     CONF_VALUE *cnf;
     int i;
     if (!(gens = sk_GENERAL_NAME_new_null())) {
         X509V3err(X509V3_F_V2I_SUBJECT_ALT, ERR_R_MALLOC_FAILURE);
         return NULL;
     }
     for (i = 0; i < sk_CONF_VALUE_num(nval); i++) {
         cnf = sk_CONF_VALUE_value(nval, i);
         if (!name_cmp(cnf->name, "email") && cnf->value &&
             !strcmp(cnf->value, "copy")) {
             if (!copy_email(ctx, gens, 0))
                 goto err;
         } else if (!name_cmp(cnf->name, "email") && cnf->value &&
                    !strcmp(cnf->value, "move")) {
             if (!copy_email(ctx, gens, 1))
                 goto err;
         } else {
             GENERAL_NAME *gen;
             if (!(gen = v2i_GENERAL_NAME(method, ctx, cnf)))
                 goto err;
             sk_GENERAL_NAME_push(gens, gen);
         }
     }
     return gens;
  err:
     sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
     return NULL;
 }
 
 /*
  * Copy any email addresses in a certificate or request to GENERAL_NAMES
  */
 
 static int copy_email(X509V3_CTX *ctx, GENERAL_NAMES *gens, int move_p)
 {
     X509_NAME *nm;
     ASN1_IA5STRING *email = NULL;
     X509_NAME_ENTRY *ne;
     GENERAL_NAME *gen = NULL;
     int i;
     if (ctx != NULL && ctx->flags == CTX_TEST)
         return 1;
     if (!ctx || (!ctx->subject_cert && !ctx->subject_req)) {
         X509V3err(X509V3_F_COPY_EMAIL, X509V3_R_NO_SUBJECT_DETAILS);
         goto err;
     }
     /* Find the subject name */
     if (ctx->subject_cert)
         nm = X509_get_subject_name(ctx->subject_cert);
     else
         nm = X509_REQ_get_subject_name(ctx->subject_req);
 
     /* Now add any email address(es) to STACK */
     i = -1;
     while ((i = X509_NAME_get_index_by_NID(nm,
                                            NID_pkcs9_emailAddress, i)) >= 0) {
         ne = X509_NAME_get_entry(nm, i);
         email = M_ASN1_IA5STRING_dup(X509_NAME_ENTRY_get_data(ne));
         if (move_p) {
             X509_NAME_delete_entry(nm, i);
             X509_NAME_ENTRY_free(ne);
             i--;
         }
         if (!email || !(gen = GENERAL_NAME_new())) {
             X509V3err(X509V3_F_COPY_EMAIL, ERR_R_MALLOC_FAILURE);
             goto err;
         }
         gen->d.ia5 = email;
         email = NULL;
         gen->type = GEN_EMAIL;
         if (!sk_GENERAL_NAME_push(gens, gen)) {
             X509V3err(X509V3_F_COPY_EMAIL, ERR_R_MALLOC_FAILURE);
             goto err;
         }
         gen = NULL;
     }
 
     return 1;
 
  err:
     GENERAL_NAME_free(gen);
     M_ASN1_IA5STRING_free(email);
     return 0;
 
 }
 
 GENERAL_NAMES *v2i_GENERAL_NAMES(const X509V3_EXT_METHOD *method,
                                  X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval)
 {
     GENERAL_NAME *gen;
     GENERAL_NAMES *gens = NULL;
     CONF_VALUE *cnf;
     int i;
     if (!(gens = sk_GENERAL_NAME_new_null())) {
         X509V3err(X509V3_F_V2I_GENERAL_NAMES, ERR_R_MALLOC_FAILURE);
         return NULL;
     }
     for (i = 0; i < sk_CONF_VALUE_num(nval); i++) {
         cnf = sk_CONF_VALUE_value(nval, i);
         if (!(gen = v2i_GENERAL_NAME(method, ctx, cnf)))
             goto err;
         sk_GENERAL_NAME_push(gens, gen);
     }
     return gens;
  err:
     sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
     return NULL;
 }
 
 GENERAL_NAME *v2i_GENERAL_NAME(const X509V3_EXT_METHOD *method,
                                X509V3_CTX *ctx, CONF_VALUE *cnf)
 {
     return v2i_GENERAL_NAME_ex(NULL, method, ctx, cnf, 0);
 }
 
 GENERAL_NAME *a2i_GENERAL_NAME(GENERAL_NAME *out,
                                const X509V3_EXT_METHOD *method,
                                X509V3_CTX *ctx, int gen_type, char *value,
                                int is_nc)
 {
     char is_string = 0;
     GENERAL_NAME *gen = NULL;
 
     if (!value) {
         X509V3err(X509V3_F_A2I_GENERAL_NAME, X509V3_R_MISSING_VALUE);
         return NULL;
     }
 
     if (out)
         gen = out;
     else {
         gen = GENERAL_NAME_new();
         if (gen == NULL) {
             X509V3err(X509V3_F_A2I_GENERAL_NAME, ERR_R_MALLOC_FAILURE);
             return NULL;
         }
     }
 
     switch (gen_type) {
     case GEN_URI:
     case GEN_EMAIL:
     case GEN_DNS:
         is_string = 1;
         break;
 
     case GEN_RID:
         {
             ASN1_OBJECT *obj;
             if (!(obj = OBJ_txt2obj(value, 0))) {
                 X509V3err(X509V3_F_A2I_GENERAL_NAME, X509V3_R_BAD_OBJECT);
                 ERR_add_error_data(2, "value=", value);
                 goto err;
             }
             gen->d.rid = obj;
         }
         break;
 
     case GEN_IPADD:
         if (is_nc)
             gen->d.ip = a2i_IPADDRESS_NC(value);
         else
             gen->d.ip = a2i_IPADDRESS(value);
         if (gen->d.ip == NULL) {
             X509V3err(X509V3_F_A2I_GENERAL_NAME, X509V3_R_BAD_IP_ADDRESS);
             ERR_add_error_data(2, "value=", value);
             goto err;
         }
         break;
 
     case GEN_DIRNAME:
         if (!do_dirname(gen, value, ctx)) {
             X509V3err(X509V3_F_A2I_GENERAL_NAME, X509V3_R_DIRNAME_ERROR);
             goto err;
         }
         break;
 
     case GEN_OTHERNAME:
         if (!do_othername(gen, value, ctx)) {
             X509V3err(X509V3_F_A2I_GENERAL_NAME, X509V3_R_OTHERNAME_ERROR);
             goto err;
         }
         break;
     default:
         X509V3err(X509V3_F_A2I_GENERAL_NAME, X509V3_R_UNSUPPORTED_TYPE);
         goto err;
     }
 
     if (is_string) {
         if (!(gen->d.ia5 = M_ASN1_IA5STRING_new()) ||
             !ASN1_STRING_set(gen->d.ia5, (unsigned char *)value,
                              strlen(value))) {
             X509V3err(X509V3_F_A2I_GENERAL_NAME, ERR_R_MALLOC_FAILURE);
             goto err;
         }
     }
 
     gen->type = gen_type;
 
     return gen;
 
  err:
     if (!out)
         GENERAL_NAME_free(gen);
     return NULL;
 }
 
 GENERAL_NAME *v2i_GENERAL_NAME_ex(GENERAL_NAME *out,
                                   const X509V3_EXT_METHOD *method,
                                   X509V3_CTX *ctx, CONF_VALUE *cnf, int is_nc)
 {
     int type;
 
     char *name, *value;
 
     name = cnf->name;
     value = cnf->value;
 
     if (!value) {
         X509V3err(X509V3_F_V2I_GENERAL_NAME_EX, X509V3_R_MISSING_VALUE);
         return NULL;
     }
 
     if (!name_cmp(name, "email"))
         type = GEN_EMAIL;
     else if (!name_cmp(name, "URI"))
         type = GEN_URI;
     else if (!name_cmp(name, "DNS"))
         type = GEN_DNS;
     else if (!name_cmp(name, "RID"))
         type = GEN_RID;
     else if (!name_cmp(name, "IP"))
         type = GEN_IPADD;
     else if (!name_cmp(name, "dirName"))
         type = GEN_DIRNAME;
     else if (!name_cmp(name, "otherName"))
         type = GEN_OTHERNAME;
     else {
         X509V3err(X509V3_F_V2I_GENERAL_NAME_EX, X509V3_R_UNSUPPORTED_OPTION);
         ERR_add_error_data(2, "name=", name);
         return NULL;
     }
 
     return a2i_GENERAL_NAME(out, method, ctx, type, value, is_nc);
 
 }
 
 static int do_othername(GENERAL_NAME *gen, char *value, X509V3_CTX *ctx)
 {
     char *objtmp = NULL, *p;
     int objlen;
     if (!(p = strchr(value, ';')))
         return 0;
     if (!(gen->d.otherName = OTHERNAME_new()))
         return 0;
     /*
      * Free this up because we will overwrite it. no need to free type_id
      * because it is static
      */
     ASN1_TYPE_free(gen->d.otherName->value);
     if (!(gen->d.otherName->value = ASN1_generate_v3(p + 1, ctx)))
         return 0;
     objlen = p - value;
     objtmp = OPENSSL_malloc(objlen + 1);
     if (objtmp == NULL)
         return 0;
     strncpy(objtmp, value, objlen);
     objtmp[objlen] = 0;
     gen->d.otherName->type_id = OBJ_txt2obj(objtmp, 0);
     OPENSSL_free(objtmp);
     if (!gen->d.otherName->type_id)
         return 0;
     return 1;
 }
 
 static int do_dirname(GENERAL_NAME *gen, char *value, X509V3_CTX *ctx)
 {
     int ret = 0;
     STACK_OF(CONF_VALUE) *sk = NULL;
     X509_NAME *nm = NULL;
     if (!(nm = X509_NAME_new()))
         goto err;
     sk = X509V3_get_section(ctx, value);
     if (!sk) {
         X509V3err(X509V3_F_DO_DIRNAME, X509V3_R_SECTION_NOT_FOUND);
         ERR_add_error_data(2, "section=", value);
         goto err;
     }
     /* FIXME: should allow other character types... */
     ret = X509V3_NAME_from_section(nm, sk, MBSTRING_ASC);
     if (!ret)
         goto err;
     gen->d.dirn = nm;
 
 err:
     if (ret == 0)
         X509_NAME_free(nm);
     X509V3_section_free(ctx, sk);
     return ret;
 }
Index: vendor-crypto/openssl/dist/crypto/x509v3/v3_cpols.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/x509v3/v3_cpols.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/x509v3/v3_cpols.c	(revision 318897)
@@ -1,491 +1,497 @@
 /* v3_cpols.c */
 /*
  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
  * 1999.
  */
 /* ====================================================================
  * Copyright (c) 1999-2004 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    licensing@OpenSSL.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #include 
 #include "cryptlib.h"
 #include 
 #include 
 #include 
 #include 
 
 #include "pcy_int.h"
 
 /* Certificate policies extension support: this one is a bit complex... */
 
 static int i2r_certpol(X509V3_EXT_METHOD *method, STACK_OF(POLICYINFO) *pol,
                        BIO *out, int indent);
 static STACK_OF(POLICYINFO) *r2i_certpol(X509V3_EXT_METHOD *method,
                                          X509V3_CTX *ctx, char *value);
 static void print_qualifiers(BIO *out, STACK_OF(POLICYQUALINFO) *quals,
                              int indent);
 static void print_notice(BIO *out, USERNOTICE *notice, int indent);
 static POLICYINFO *policy_section(X509V3_CTX *ctx,
                                   STACK_OF(CONF_VALUE) *polstrs, int ia5org);
 static POLICYQUALINFO *notice_section(X509V3_CTX *ctx,
                                       STACK_OF(CONF_VALUE) *unot, int ia5org);
 static int nref_nos(STACK_OF(ASN1_INTEGER) *nnums, STACK_OF(CONF_VALUE) *nos);
 
 const X509V3_EXT_METHOD v3_cpols = {
     NID_certificate_policies, 0, ASN1_ITEM_ref(CERTIFICATEPOLICIES),
     0, 0, 0, 0,
     0, 0,
     0, 0,
     (X509V3_EXT_I2R)i2r_certpol,
     (X509V3_EXT_R2I)r2i_certpol,
     NULL
 };
 
 ASN1_ITEM_TEMPLATE(CERTIFICATEPOLICIES) =
         ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, CERTIFICATEPOLICIES, POLICYINFO)
 ASN1_ITEM_TEMPLATE_END(CERTIFICATEPOLICIES)
 
 IMPLEMENT_ASN1_FUNCTIONS(CERTIFICATEPOLICIES)
 
 ASN1_SEQUENCE(POLICYINFO) = {
         ASN1_SIMPLE(POLICYINFO, policyid, ASN1_OBJECT),
         ASN1_SEQUENCE_OF_OPT(POLICYINFO, qualifiers, POLICYQUALINFO)
 } ASN1_SEQUENCE_END(POLICYINFO)
 
 IMPLEMENT_ASN1_FUNCTIONS(POLICYINFO)
 
 ASN1_ADB_TEMPLATE(policydefault) = ASN1_SIMPLE(POLICYQUALINFO, d.other, ASN1_ANY);
 
 ASN1_ADB(POLICYQUALINFO) = {
         ADB_ENTRY(NID_id_qt_cps, ASN1_SIMPLE(POLICYQUALINFO, d.cpsuri, ASN1_IA5STRING)),
         ADB_ENTRY(NID_id_qt_unotice, ASN1_SIMPLE(POLICYQUALINFO, d.usernotice, USERNOTICE))
 } ASN1_ADB_END(POLICYQUALINFO, 0, pqualid, 0, &policydefault_tt, NULL);
 
 ASN1_SEQUENCE(POLICYQUALINFO) = {
         ASN1_SIMPLE(POLICYQUALINFO, pqualid, ASN1_OBJECT),
         ASN1_ADB_OBJECT(POLICYQUALINFO)
 } ASN1_SEQUENCE_END(POLICYQUALINFO)
 
 IMPLEMENT_ASN1_FUNCTIONS(POLICYQUALINFO)
 
 ASN1_SEQUENCE(USERNOTICE) = {
         ASN1_OPT(USERNOTICE, noticeref, NOTICEREF),
         ASN1_OPT(USERNOTICE, exptext, DISPLAYTEXT)
 } ASN1_SEQUENCE_END(USERNOTICE)
 
 IMPLEMENT_ASN1_FUNCTIONS(USERNOTICE)
 
 ASN1_SEQUENCE(NOTICEREF) = {
         ASN1_SIMPLE(NOTICEREF, organization, DISPLAYTEXT),
         ASN1_SEQUENCE_OF(NOTICEREF, noticenos, ASN1_INTEGER)
 } ASN1_SEQUENCE_END(NOTICEREF)
 
 IMPLEMENT_ASN1_FUNCTIONS(NOTICEREF)
 
 static STACK_OF(POLICYINFO) *r2i_certpol(X509V3_EXT_METHOD *method,
                                          X509V3_CTX *ctx, char *value)
 {
     STACK_OF(POLICYINFO) *pols = NULL;
     char *pstr;
     POLICYINFO *pol;
     ASN1_OBJECT *pobj;
     STACK_OF(CONF_VALUE) *vals;
     CONF_VALUE *cnf;
     int i, ia5org;
     pols = sk_POLICYINFO_new_null();
     if (pols == NULL) {
         X509V3err(X509V3_F_R2I_CERTPOL, ERR_R_MALLOC_FAILURE);
         return NULL;
     }
     vals = X509V3_parse_list(value);
     if (vals == NULL) {
         X509V3err(X509V3_F_R2I_CERTPOL, ERR_R_X509V3_LIB);
         goto err;
     }
     ia5org = 0;
     for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
         cnf = sk_CONF_VALUE_value(vals, i);
         if (cnf->value || !cnf->name) {
             X509V3err(X509V3_F_R2I_CERTPOL,
                       X509V3_R_INVALID_POLICY_IDENTIFIER);
             X509V3_conf_err(cnf);
             goto err;
         }
         pstr = cnf->name;
         if (!strcmp(pstr, "ia5org")) {
             ia5org = 1;
             continue;
         } else if (*pstr == '@') {
             STACK_OF(CONF_VALUE) *polsect;
             polsect = X509V3_get_section(ctx, pstr + 1);
             if (!polsect) {
                 X509V3err(X509V3_F_R2I_CERTPOL, X509V3_R_INVALID_SECTION);
 
                 X509V3_conf_err(cnf);
                 goto err;
             }
             pol = policy_section(ctx, polsect, ia5org);
             X509V3_section_free(ctx, polsect);
             if (!pol)
                 goto err;
         } else {
             if (!(pobj = OBJ_txt2obj(cnf->name, 0))) {
                 X509V3err(X509V3_F_R2I_CERTPOL,
                           X509V3_R_INVALID_OBJECT_IDENTIFIER);
                 X509V3_conf_err(cnf);
                 goto err;
             }
             pol = POLICYINFO_new();
             if (pol == NULL) {
                 X509V3err(X509V3_F_R2I_CERTPOL, ERR_R_MALLOC_FAILURE);
                 goto err;
             }
             pol->policyid = pobj;
         }
         if (!sk_POLICYINFO_push(pols, pol)) {
             POLICYINFO_free(pol);
             X509V3err(X509V3_F_R2I_CERTPOL, ERR_R_MALLOC_FAILURE);
             goto err;
         }
     }
     sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
     return pols;
  err:
     sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
     sk_POLICYINFO_pop_free(pols, POLICYINFO_free);
     return NULL;
 }
 
 static POLICYINFO *policy_section(X509V3_CTX *ctx,
                                   STACK_OF(CONF_VALUE) *polstrs, int ia5org)
 {
     int i;
     CONF_VALUE *cnf;
     POLICYINFO *pol;
     POLICYQUALINFO *qual;
     if (!(pol = POLICYINFO_new()))
         goto merr;
     for (i = 0; i < sk_CONF_VALUE_num(polstrs); i++) {
         cnf = sk_CONF_VALUE_value(polstrs, i);
         if (!strcmp(cnf->name, "policyIdentifier")) {
             ASN1_OBJECT *pobj;
             if (!(pobj = OBJ_txt2obj(cnf->value, 0))) {
                 X509V3err(X509V3_F_POLICY_SECTION,
                           X509V3_R_INVALID_OBJECT_IDENTIFIER);
                 X509V3_conf_err(cnf);
                 goto err;
             }
             pol->policyid = pobj;
 
         } else if (!name_cmp(cnf->name, "CPS")) {
             if (!pol->qualifiers)
                 pol->qualifiers = sk_POLICYQUALINFO_new_null();
             if (!(qual = POLICYQUALINFO_new()))
                 goto merr;
             if (!sk_POLICYQUALINFO_push(pol->qualifiers, qual))
                 goto merr;
             if (!(qual->pqualid = OBJ_nid2obj(NID_id_qt_cps))) {
                 X509V3err(X509V3_F_POLICY_SECTION, ERR_R_INTERNAL_ERROR);
                 goto err;
             }
             if (!(qual->d.cpsuri = M_ASN1_IA5STRING_new()))
                 goto merr;
             if (!ASN1_STRING_set(qual->d.cpsuri, cnf->value,
                                  strlen(cnf->value)))
                 goto merr;
         } else if (!name_cmp(cnf->name, "userNotice")) {
             STACK_OF(CONF_VALUE) *unot;
             if (*cnf->value != '@') {
                 X509V3err(X509V3_F_POLICY_SECTION,
                           X509V3_R_EXPECTED_A_SECTION_NAME);
                 X509V3_conf_err(cnf);
                 goto err;
             }
             unot = X509V3_get_section(ctx, cnf->value + 1);
             if (!unot) {
                 X509V3err(X509V3_F_POLICY_SECTION, X509V3_R_INVALID_SECTION);
 
                 X509V3_conf_err(cnf);
                 goto err;
             }
             qual = notice_section(ctx, unot, ia5org);
             X509V3_section_free(ctx, unot);
             if (!qual)
                 goto err;
             if (!pol->qualifiers)
                 pol->qualifiers = sk_POLICYQUALINFO_new_null();
             if (!sk_POLICYQUALINFO_push(pol->qualifiers, qual))
                 goto merr;
         } else {
             X509V3err(X509V3_F_POLICY_SECTION, X509V3_R_INVALID_OPTION);
 
             X509V3_conf_err(cnf);
             goto err;
         }
     }
     if (!pol->policyid) {
         X509V3err(X509V3_F_POLICY_SECTION, X509V3_R_NO_POLICY_IDENTIFIER);
         goto err;
     }
 
     return pol;
 
  merr:
     X509V3err(X509V3_F_POLICY_SECTION, ERR_R_MALLOC_FAILURE);
 
  err:
     POLICYINFO_free(pol);
     return NULL;
 
 }
 
 static POLICYQUALINFO *notice_section(X509V3_CTX *ctx,
                                       STACK_OF(CONF_VALUE) *unot, int ia5org)
 {
     int i, ret;
     CONF_VALUE *cnf;
     USERNOTICE *not;
     POLICYQUALINFO *qual;
     if (!(qual = POLICYQUALINFO_new()))
         goto merr;
     if (!(qual->pqualid = OBJ_nid2obj(NID_id_qt_unotice))) {
         X509V3err(X509V3_F_NOTICE_SECTION, ERR_R_INTERNAL_ERROR);
         goto err;
     }
     if (!(not = USERNOTICE_new()))
         goto merr;
     qual->d.usernotice = not;
     for (i = 0; i < sk_CONF_VALUE_num(unot); i++) {
         cnf = sk_CONF_VALUE_value(unot, i);
         if (!strcmp(cnf->name, "explicitText")) {
             if (!(not->exptext = M_ASN1_VISIBLESTRING_new()))
                 goto merr;
             if (!ASN1_STRING_set(not->exptext, cnf->value,
                                  strlen(cnf->value)))
                 goto merr;
         } else if (!strcmp(cnf->name, "organization")) {
             NOTICEREF *nref;
             if (!not->noticeref) {
                 if (!(nref = NOTICEREF_new()))
                     goto merr;
                 not->noticeref = nref;
             } else
                 nref = not->noticeref;
             if (ia5org)
                 nref->organization->type = V_ASN1_IA5STRING;
             else
                 nref->organization->type = V_ASN1_VISIBLESTRING;
             if (!ASN1_STRING_set(nref->organization, cnf->value,
                                  strlen(cnf->value)))
                 goto merr;
         } else if (!strcmp(cnf->name, "noticeNumbers")) {
             NOTICEREF *nref;
             STACK_OF(CONF_VALUE) *nos;
             if (!not->noticeref) {
                 if (!(nref = NOTICEREF_new()))
                     goto merr;
                 not->noticeref = nref;
             } else
                 nref = not->noticeref;
             nos = X509V3_parse_list(cnf->value);
             if (!nos || !sk_CONF_VALUE_num(nos)) {
                 X509V3err(X509V3_F_NOTICE_SECTION, X509V3_R_INVALID_NUMBERS);
                 X509V3_conf_err(cnf);
                 goto err;
             }
             ret = nref_nos(nref->noticenos, nos);
             sk_CONF_VALUE_pop_free(nos, X509V3_conf_free);
             if (!ret)
                 goto err;
         } else {
             X509V3err(X509V3_F_NOTICE_SECTION, X509V3_R_INVALID_OPTION);
             X509V3_conf_err(cnf);
             goto err;
         }
     }
 
     if (not->noticeref &&
         (!not->noticeref->noticenos || !not->noticeref->organization)) {
         X509V3err(X509V3_F_NOTICE_SECTION,
                   X509V3_R_NEED_ORGANIZATION_AND_NUMBERS);
         goto err;
     }
 
     return qual;
 
  merr:
     X509V3err(X509V3_F_NOTICE_SECTION, ERR_R_MALLOC_FAILURE);
 
  err:
     POLICYQUALINFO_free(qual);
     return NULL;
 }
 
 static int nref_nos(STACK_OF(ASN1_INTEGER) *nnums, STACK_OF(CONF_VALUE) *nos)
 {
     CONF_VALUE *cnf;
     ASN1_INTEGER *aint;
 
     int i;
 
     for (i = 0; i < sk_CONF_VALUE_num(nos); i++) {
         cnf = sk_CONF_VALUE_value(nos, i);
         if (!(aint = s2i_ASN1_INTEGER(NULL, cnf->name))) {
             X509V3err(X509V3_F_NREF_NOS, X509V3_R_INVALID_NUMBER);
             goto err;
         }
         if (!sk_ASN1_INTEGER_push(nnums, aint))
             goto merr;
     }
     return 1;
 
  merr:
+    ASN1_INTEGER_free(aint);
     X509V3err(X509V3_F_NREF_NOS, ERR_R_MALLOC_FAILURE);
 
  err:
-    sk_ASN1_INTEGER_pop_free(nnums, ASN1_STRING_free);
     return 0;
 }
 
 static int i2r_certpol(X509V3_EXT_METHOD *method, STACK_OF(POLICYINFO) *pol,
                        BIO *out, int indent)
 {
     int i;
     POLICYINFO *pinfo;
     /* First print out the policy OIDs */
     for (i = 0; i < sk_POLICYINFO_num(pol); i++) {
         pinfo = sk_POLICYINFO_value(pol, i);
         BIO_printf(out, "%*sPolicy: ", indent, "");
         i2a_ASN1_OBJECT(out, pinfo->policyid);
         BIO_puts(out, "\n");
         if (pinfo->qualifiers)
             print_qualifiers(out, pinfo->qualifiers, indent + 2);
     }
     return 1;
 }
 
 static void print_qualifiers(BIO *out, STACK_OF(POLICYQUALINFO) *quals,
                              int indent)
 {
     POLICYQUALINFO *qualinfo;
     int i;
     for (i = 0; i < sk_POLICYQUALINFO_num(quals); i++) {
         qualinfo = sk_POLICYQUALINFO_value(quals, i);
         switch (OBJ_obj2nid(qualinfo->pqualid)) {
         case NID_id_qt_cps:
             BIO_printf(out, "%*sCPS: %s\n", indent, "",
                        qualinfo->d.cpsuri->data);
             break;
 
         case NID_id_qt_unotice:
             BIO_printf(out, "%*sUser Notice:\n", indent, "");
             print_notice(out, qualinfo->d.usernotice, indent + 2);
             break;
 
         default:
             BIO_printf(out, "%*sUnknown Qualifier: ", indent + 2, "");
 
             i2a_ASN1_OBJECT(out, qualinfo->pqualid);
             BIO_puts(out, "\n");
             break;
         }
     }
 }
 
 static void print_notice(BIO *out, USERNOTICE *notice, int indent)
 {
     int i;
     if (notice->noticeref) {
         NOTICEREF *ref;
         ref = notice->noticeref;
         BIO_printf(out, "%*sOrganization: %s\n", indent, "",
                    ref->organization->data);
         BIO_printf(out, "%*sNumber%s: ", indent, "",
                    sk_ASN1_INTEGER_num(ref->noticenos) > 1 ? "s" : "");
         for (i = 0; i < sk_ASN1_INTEGER_num(ref->noticenos); i++) {
             ASN1_INTEGER *num;
             char *tmp;
             num = sk_ASN1_INTEGER_value(ref->noticenos, i);
             if (i)
                 BIO_puts(out, ", ");
-            tmp = i2s_ASN1_INTEGER(NULL, num);
-            BIO_puts(out, tmp);
-            OPENSSL_free(tmp);
+            if (num == NULL)
+                BIO_puts(out, "(null)");
+            else {
+                tmp = i2s_ASN1_INTEGER(NULL, num);
+                if (tmp == NULL)
+                    return;
+                BIO_puts(out, tmp);
+                OPENSSL_free(tmp);
+            }
         }
         BIO_puts(out, "\n");
     }
     if (notice->exptext)
         BIO_printf(out, "%*sExplicit Text: %s\n", indent, "",
                    notice->exptext->data);
 }
 
 void X509_POLICY_NODE_print(BIO *out, X509_POLICY_NODE *node, int indent)
 {
     const X509_POLICY_DATA *dat = node->data;
 
     BIO_printf(out, "%*sPolicy: ", indent, "");
 
     i2a_ASN1_OBJECT(out, dat->valid_policy);
     BIO_puts(out, "\n");
     BIO_printf(out, "%*s%s\n", indent + 2, "",
                node_data_critical(dat) ? "Critical" : "Non Critical");
     if (dat->qualifier_set)
         print_qualifiers(out, dat->qualifier_set, indent + 2);
     else
         BIO_printf(out, "%*sNo Qualifiers\n", indent + 2, "");
 }
 
 
 IMPLEMENT_STACK_OF(X509_POLICY_NODE)
 
 IMPLEMENT_STACK_OF(X509_POLICY_DATA)
Index: vendor-crypto/openssl/dist/crypto/x509v3/v3_info.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/x509v3/v3_info.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/x509v3/v3_info.c	(revision 318897)
@@ -1,210 +1,217 @@
 /* v3_info.c */
 /*
  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
  * 1999.
  */
 /* ====================================================================
  * Copyright (c) 1999 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    licensing@OpenSSL.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #include 
 #include "cryptlib.h"
 #include 
 #include 
 #include 
 #include 
 
 static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_INFO_ACCESS(X509V3_EXT_METHOD
                                                        *method, AUTHORITY_INFO_ACCESS
                                                        *ainfo, STACK_OF(CONF_VALUE)
                                                        *ret);
 static AUTHORITY_INFO_ACCESS *v2i_AUTHORITY_INFO_ACCESS(X509V3_EXT_METHOD
                                                         *method,
                                                         X509V3_CTX *ctx,
                                                         STACK_OF(CONF_VALUE)
                                                         *nval);
 
 const X509V3_EXT_METHOD v3_info = { NID_info_access, X509V3_EXT_MULTILINE,
     ASN1_ITEM_ref(AUTHORITY_INFO_ACCESS),
     0, 0, 0, 0,
     0, 0,
     (X509V3_EXT_I2V) i2v_AUTHORITY_INFO_ACCESS,
     (X509V3_EXT_V2I)v2i_AUTHORITY_INFO_ACCESS,
     0, 0,
     NULL
 };
 
 const X509V3_EXT_METHOD v3_sinfo = { NID_sinfo_access, X509V3_EXT_MULTILINE,
     ASN1_ITEM_ref(AUTHORITY_INFO_ACCESS),
     0, 0, 0, 0,
     0, 0,
     (X509V3_EXT_I2V) i2v_AUTHORITY_INFO_ACCESS,
     (X509V3_EXT_V2I)v2i_AUTHORITY_INFO_ACCESS,
     0, 0,
     NULL
 };
 
 ASN1_SEQUENCE(ACCESS_DESCRIPTION) = {
         ASN1_SIMPLE(ACCESS_DESCRIPTION, method, ASN1_OBJECT),
         ASN1_SIMPLE(ACCESS_DESCRIPTION, location, GENERAL_NAME)
 } ASN1_SEQUENCE_END(ACCESS_DESCRIPTION)
 
 IMPLEMENT_ASN1_FUNCTIONS(ACCESS_DESCRIPTION)
 
 ASN1_ITEM_TEMPLATE(AUTHORITY_INFO_ACCESS) =
         ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, GeneralNames, ACCESS_DESCRIPTION)
 ASN1_ITEM_TEMPLATE_END(AUTHORITY_INFO_ACCESS)
 
 IMPLEMENT_ASN1_FUNCTIONS(AUTHORITY_INFO_ACCESS)
 
-static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_INFO_ACCESS(X509V3_EXT_METHOD
-                                                       *method, AUTHORITY_INFO_ACCESS
-                                                       *ainfo, STACK_OF(CONF_VALUE)
-                                                       *ret)
+static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_INFO_ACCESS(
+    X509V3_EXT_METHOD *method, AUTHORITY_INFO_ACCESS *ainfo,
+    STACK_OF(CONF_VALUE) *ret)
 {
     ACCESS_DESCRIPTION *desc;
     int i, nlen;
     char objtmp[80], *ntmp;
     CONF_VALUE *vtmp;
+    STACK_OF(CONF_VALUE) *tret = ret;
+
     for (i = 0; i < sk_ACCESS_DESCRIPTION_num(ainfo); i++) {
+        STACK_OF(CONF_VALUE) *tmp;
+
         desc = sk_ACCESS_DESCRIPTION_value(ainfo, i);
-        ret = i2v_GENERAL_NAME(method, desc->location, ret);
-        if (!ret)
-            break;
-        vtmp = sk_CONF_VALUE_value(ret, i);
+        tmp = i2v_GENERAL_NAME(method, desc->location, tret);
+        if (tmp == NULL)
+            goto err;
+        tret = tmp;
+        vtmp = sk_CONF_VALUE_value(tret, i);
         i2t_ASN1_OBJECT(objtmp, sizeof objtmp, desc->method);
         nlen = strlen(objtmp) + strlen(vtmp->name) + 5;
         ntmp = OPENSSL_malloc(nlen);
-        if (!ntmp) {
-            X509V3err(X509V3_F_I2V_AUTHORITY_INFO_ACCESS,
-                      ERR_R_MALLOC_FAILURE);
-            return NULL;
-        }
+        if (ntmp == NULL)
+            goto err;
         BUF_strlcpy(ntmp, objtmp, nlen);
         BUF_strlcat(ntmp, " - ", nlen);
         BUF_strlcat(ntmp, vtmp->name, nlen);
         OPENSSL_free(vtmp->name);
         vtmp->name = ntmp;
 
     }
-    if (!ret)
+    if (ret == NULL && tret == NULL)
         return sk_CONF_VALUE_new_null();
-    return ret;
+
+    return tret;
+ err:
+    X509V3err(X509V3_F_I2V_AUTHORITY_INFO_ACCESS, ERR_R_MALLOC_FAILURE);
+    if (ret == NULL && tret != NULL)
+        sk_CONF_VALUE_pop_free(tret, X509V3_conf_free);
+    return NULL;
 }
 
 static AUTHORITY_INFO_ACCESS *v2i_AUTHORITY_INFO_ACCESS(X509V3_EXT_METHOD
                                                         *method,
                                                         X509V3_CTX *ctx,
                                                         STACK_OF(CONF_VALUE)
                                                         *nval)
 {
     AUTHORITY_INFO_ACCESS *ainfo = NULL;
     CONF_VALUE *cnf, ctmp;
     ACCESS_DESCRIPTION *acc;
     int i, objlen;
     char *objtmp, *ptmp;
     if (!(ainfo = sk_ACCESS_DESCRIPTION_new_null())) {
         X509V3err(X509V3_F_V2I_AUTHORITY_INFO_ACCESS, ERR_R_MALLOC_FAILURE);
         return NULL;
     }
     for (i = 0; i < sk_CONF_VALUE_num(nval); i++) {
         cnf = sk_CONF_VALUE_value(nval, i);
         if (!(acc = ACCESS_DESCRIPTION_new())
             || !sk_ACCESS_DESCRIPTION_push(ainfo, acc)) {
             X509V3err(X509V3_F_V2I_AUTHORITY_INFO_ACCESS,
                       ERR_R_MALLOC_FAILURE);
             goto err;
         }
         ptmp = strchr(cnf->name, ';');
         if (!ptmp) {
             X509V3err(X509V3_F_V2I_AUTHORITY_INFO_ACCESS,
                       X509V3_R_INVALID_SYNTAX);
             goto err;
         }
         objlen = ptmp - cnf->name;
         ctmp.name = ptmp + 1;
         ctmp.value = cnf->value;
         if (!v2i_GENERAL_NAME_ex(acc->location, method, ctx, &ctmp, 0))
             goto err;
         if (!(objtmp = OPENSSL_malloc(objlen + 1))) {
             X509V3err(X509V3_F_V2I_AUTHORITY_INFO_ACCESS,
                       ERR_R_MALLOC_FAILURE);
             goto err;
         }
         strncpy(objtmp, cnf->name, objlen);
         objtmp[objlen] = 0;
         acc->method = OBJ_txt2obj(objtmp, 0);
         if (!acc->method) {
             X509V3err(X509V3_F_V2I_AUTHORITY_INFO_ACCESS,
                       X509V3_R_BAD_OBJECT);
             ERR_add_error_data(2, "value=", objtmp);
             OPENSSL_free(objtmp);
             goto err;
         }
         OPENSSL_free(objtmp);
 
     }
     return ainfo;
  err:
     sk_ACCESS_DESCRIPTION_pop_free(ainfo, ACCESS_DESCRIPTION_free);
     return NULL;
 }
 
 int i2a_ACCESS_DESCRIPTION(BIO *bp, ACCESS_DESCRIPTION *a)
 {
     i2a_ASN1_OBJECT(bp, a->method);
 #ifdef UNDEF
     i2a_GENERAL_NAME(bp, a->location);
 #endif
     return 2;
 }
Index: vendor-crypto/openssl/dist/crypto/x509v3/v3_purp.c
===================================================================
--- vendor-crypto/openssl/dist/crypto/x509v3/v3_purp.c	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/x509v3/v3_purp.c	(revision 318897)
@@ -1,852 +1,853 @@
 /* v3_purp.c */
 /*
  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
  * 2001.
  */
 /* ====================================================================
  * Copyright (c) 1999-2004 The OpenSSL Project.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in
  *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * 3. All advertising materials mentioning features or use of this
  *    software must display the following acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  *
  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  *    endorse or promote products derived from this software without
  *    prior written permission. For written permission, please contact
  *    licensing@OpenSSL.org.
  *
  * 5. Products derived from this software may not be called "OpenSSL"
  *    nor may "OpenSSL" appear in their names without prior written
  *    permission of the OpenSSL Project.
  *
  * 6. Redistributions of any form whatsoever must retain the following
  *    acknowledgment:
  *    "This product includes software developed by the OpenSSL Project
  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  *
  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  * ====================================================================
  *
  * This product includes cryptographic software written by Eric Young
  * (eay@cryptsoft.com).  This product includes software written by Tim
  * Hudson (tjh@cryptsoft.com).
  *
  */
 
 #include 
 #include "cryptlib.h"
 #include 
 #include 
 
 static void x509v3_cache_extensions(X509 *x);
 
 static int check_ssl_ca(const X509 *x);
 static int check_purpose_ssl_client(const X509_PURPOSE *xp, const X509 *x,
                                     int ca);
 static int check_purpose_ssl_server(const X509_PURPOSE *xp, const X509 *x,
                                     int ca);
 static int check_purpose_ns_ssl_server(const X509_PURPOSE *xp, const X509 *x,
                                        int ca);
 static int purpose_smime(const X509 *x, int ca);
 static int check_purpose_smime_sign(const X509_PURPOSE *xp, const X509 *x,
                                     int ca);
 static int check_purpose_smime_encrypt(const X509_PURPOSE *xp, const X509 *x,
                                        int ca);
 static int check_purpose_crl_sign(const X509_PURPOSE *xp, const X509 *x,
                                   int ca);
 static int check_purpose_timestamp_sign(const X509_PURPOSE *xp, const X509 *x,
                                         int ca);
 static int no_check(const X509_PURPOSE *xp, const X509 *x, int ca);
 static int ocsp_helper(const X509_PURPOSE *xp, const X509 *x, int ca);
 
 static int xp_cmp(const X509_PURPOSE *const *a, const X509_PURPOSE *const *b);
 static void xptable_free(X509_PURPOSE *p);
 
 static X509_PURPOSE xstandard[] = {
     {X509_PURPOSE_SSL_CLIENT, X509_TRUST_SSL_CLIENT, 0,
      check_purpose_ssl_client, "SSL client", "sslclient", NULL},
     {X509_PURPOSE_SSL_SERVER, X509_TRUST_SSL_SERVER, 0,
      check_purpose_ssl_server, "SSL server", "sslserver", NULL},
     {X509_PURPOSE_NS_SSL_SERVER, X509_TRUST_SSL_SERVER, 0,
      check_purpose_ns_ssl_server, "Netscape SSL server", "nssslserver", NULL},
     {X509_PURPOSE_SMIME_SIGN, X509_TRUST_EMAIL, 0, check_purpose_smime_sign,
      "S/MIME signing", "smimesign", NULL},
     {X509_PURPOSE_SMIME_ENCRYPT, X509_TRUST_EMAIL, 0,
      check_purpose_smime_encrypt, "S/MIME encryption", "smimeencrypt", NULL},
     {X509_PURPOSE_CRL_SIGN, X509_TRUST_COMPAT, 0, check_purpose_crl_sign,
      "CRL signing", "crlsign", NULL},
     {X509_PURPOSE_ANY, X509_TRUST_DEFAULT, 0, no_check, "Any Purpose", "any",
      NULL},
     {X509_PURPOSE_OCSP_HELPER, X509_TRUST_COMPAT, 0, ocsp_helper,
      "OCSP helper", "ocsphelper", NULL},
     {X509_PURPOSE_TIMESTAMP_SIGN, X509_TRUST_TSA, 0,
      check_purpose_timestamp_sign, "Time Stamp signing", "timestampsign",
      NULL},
 };
 
 #define X509_PURPOSE_COUNT (sizeof(xstandard)/sizeof(X509_PURPOSE))
 
 IMPLEMENT_STACK_OF(X509_PURPOSE)
 
 static STACK_OF(X509_PURPOSE) *xptable = NULL;
 
 static int xp_cmp(const X509_PURPOSE *const *a, const X509_PURPOSE *const *b)
 {
     return (*a)->purpose - (*b)->purpose;
 }
 
 /*
  * As much as I'd like to make X509_check_purpose use a "const" X509* I
  * really can't because it does recalculate hashes and do other non-const
  * things.
  */
 int X509_check_purpose(X509 *x, int id, int ca)
 {
     int idx;
     const X509_PURPOSE *pt;
     if (!(x->ex_flags & EXFLAG_SET)) {
         CRYPTO_w_lock(CRYPTO_LOCK_X509);
         x509v3_cache_extensions(x);
         CRYPTO_w_unlock(CRYPTO_LOCK_X509);
     }
     if (id == -1)
         return 1;
     idx = X509_PURPOSE_get_by_id(id);
     if (idx == -1)
         return -1;
     pt = X509_PURPOSE_get0(idx);
     return pt->check_purpose(pt, x, ca);
 }
 
 int X509_PURPOSE_set(int *p, int purpose)
 {
     if (X509_PURPOSE_get_by_id(purpose) == -1) {
         X509V3err(X509V3_F_X509_PURPOSE_SET, X509V3_R_INVALID_PURPOSE);
         return 0;
     }
     *p = purpose;
     return 1;
 }
 
 int X509_PURPOSE_get_count(void)
 {
     if (!xptable)
         return X509_PURPOSE_COUNT;
     return sk_X509_PURPOSE_num(xptable) + X509_PURPOSE_COUNT;
 }
 
 X509_PURPOSE *X509_PURPOSE_get0(int idx)
 {
     if (idx < 0)
         return NULL;
     if (idx < (int)X509_PURPOSE_COUNT)
         return xstandard + idx;
     return sk_X509_PURPOSE_value(xptable, idx - X509_PURPOSE_COUNT);
 }
 
 int X509_PURPOSE_get_by_sname(char *sname)
 {
     int i;
     X509_PURPOSE *xptmp;
     for (i = 0; i < X509_PURPOSE_get_count(); i++) {
         xptmp = X509_PURPOSE_get0(i);
         if (!strcmp(xptmp->sname, sname))
             return i;
     }
     return -1;
 }
 
 int X509_PURPOSE_get_by_id(int purpose)
 {
     X509_PURPOSE tmp;
     int idx;
     if ((purpose >= X509_PURPOSE_MIN) && (purpose <= X509_PURPOSE_MAX))
         return purpose - X509_PURPOSE_MIN;
     tmp.purpose = purpose;
     if (!xptable)
         return -1;
     idx = sk_X509_PURPOSE_find(xptable, &tmp);
     if (idx == -1)
         return -1;
     return idx + X509_PURPOSE_COUNT;
 }
 
 int X509_PURPOSE_add(int id, int trust, int flags,
                      int (*ck) (const X509_PURPOSE *, const X509 *, int),
                      char *name, char *sname, void *arg)
 {
     int idx;
     X509_PURPOSE *ptmp;
     /*
      * This is set according to what we change: application can't set it
      */
     flags &= ~X509_PURPOSE_DYNAMIC;
     /* This will always be set for application modified trust entries */
     flags |= X509_PURPOSE_DYNAMIC_NAME;
     /* Get existing entry if any */
     idx = X509_PURPOSE_get_by_id(id);
     /* Need a new entry */
     if (idx == -1) {
         if (!(ptmp = OPENSSL_malloc(sizeof(X509_PURPOSE)))) {
             X509V3err(X509V3_F_X509_PURPOSE_ADD, ERR_R_MALLOC_FAILURE);
             return 0;
         }
         ptmp->flags = X509_PURPOSE_DYNAMIC;
     } else
         ptmp = X509_PURPOSE_get0(idx);
 
     /* OPENSSL_free existing name if dynamic */
     if (ptmp->flags & X509_PURPOSE_DYNAMIC_NAME) {
         OPENSSL_free(ptmp->name);
         OPENSSL_free(ptmp->sname);
     }
     /* dup supplied name */
     ptmp->name = BUF_strdup(name);
     ptmp->sname = BUF_strdup(sname);
     if (!ptmp->name || !ptmp->sname) {
         X509V3err(X509V3_F_X509_PURPOSE_ADD, ERR_R_MALLOC_FAILURE);
         return 0;
     }
     /* Keep the dynamic flag of existing entry */
     ptmp->flags &= X509_PURPOSE_DYNAMIC;
     /* Set all other flags */
     ptmp->flags |= flags;
 
     ptmp->purpose = id;
     ptmp->trust = trust;
     ptmp->check_purpose = ck;
     ptmp->usr_data = arg;
 
     /* If its a new entry manage the dynamic table */
     if (idx == -1) {
         if (!xptable && !(xptable = sk_X509_PURPOSE_new(xp_cmp))) {
             X509V3err(X509V3_F_X509_PURPOSE_ADD, ERR_R_MALLOC_FAILURE);
             return 0;
         }
         if (!sk_X509_PURPOSE_push(xptable, ptmp)) {
             X509V3err(X509V3_F_X509_PURPOSE_ADD, ERR_R_MALLOC_FAILURE);
             return 0;
         }
     }
     return 1;
 }
 
 static void xptable_free(X509_PURPOSE *p)
 {
     if (!p)
         return;
     if (p->flags & X509_PURPOSE_DYNAMIC) {
         if (p->flags & X509_PURPOSE_DYNAMIC_NAME) {
             OPENSSL_free(p->name);
             OPENSSL_free(p->sname);
         }
         OPENSSL_free(p);
     }
 }
 
 void X509_PURPOSE_cleanup(void)
 {
     unsigned int i;
     sk_X509_PURPOSE_pop_free(xptable, xptable_free);
     for (i = 0; i < X509_PURPOSE_COUNT; i++)
         xptable_free(xstandard + i);
     xptable = NULL;
 }
 
 int X509_PURPOSE_get_id(X509_PURPOSE *xp)
 {
     return xp->purpose;
 }
 
 char *X509_PURPOSE_get0_name(X509_PURPOSE *xp)
 {
     return xp->name;
 }
 
 char *X509_PURPOSE_get0_sname(X509_PURPOSE *xp)
 {
     return xp->sname;
 }
 
 int X509_PURPOSE_get_trust(X509_PURPOSE *xp)
 {
     return xp->trust;
 }
 
 static int nid_cmp(const int *a, const int *b)
 {
     return *a - *b;
 }
 
 DECLARE_OBJ_BSEARCH_CMP_FN(int, int, nid);
 IMPLEMENT_OBJ_BSEARCH_CMP_FN(int, int, nid);
 
 int X509_supported_extension(X509_EXTENSION *ex)
 {
     /*
      * This table is a list of the NIDs of supported extensions: that is
      * those which are used by the verify process. If an extension is
      * critical and doesn't appear in this list then the verify process will
      * normally reject the certificate. The list must be kept in numerical
      * order because it will be searched using bsearch.
      */
 
     static const int supported_nids[] = {
         NID_netscape_cert_type, /* 71 */
         NID_key_usage,          /* 83 */
         NID_subject_alt_name,   /* 85 */
         NID_basic_constraints,  /* 87 */
         NID_certificate_policies, /* 89 */
+        NID_crl_distribution_points, /* 103 */
         NID_ext_key_usage,      /* 126 */
 #ifndef OPENSSL_NO_RFC3779
         NID_sbgp_ipAddrBlock,   /* 290 */
         NID_sbgp_autonomousSysNum, /* 291 */
 #endif
         NID_policy_constraints, /* 401 */
         NID_proxyCertInfo,      /* 663 */
         NID_name_constraints,   /* 666 */
         NID_policy_mappings,    /* 747 */
         NID_inhibit_any_policy  /* 748 */
     };
 
     int ex_nid = OBJ_obj2nid(X509_EXTENSION_get_object(ex));
 
     if (ex_nid == NID_undef)
         return 0;
 
     if (OBJ_bsearch_nid(&ex_nid, supported_nids,
                         sizeof(supported_nids) / sizeof(int)))
         return 1;
     return 0;
 }
 
 static void setup_dp(X509 *x, DIST_POINT *dp)
 {
     X509_NAME *iname = NULL;
     int i;
     if (dp->reasons) {
         if (dp->reasons->length > 0)
             dp->dp_reasons = dp->reasons->data[0];
         if (dp->reasons->length > 1)
             dp->dp_reasons |= (dp->reasons->data[1] << 8);
         dp->dp_reasons &= CRLDP_ALL_REASONS;
     } else
         dp->dp_reasons = CRLDP_ALL_REASONS;
     if (!dp->distpoint || (dp->distpoint->type != 1))
         return;
     for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
         GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
         if (gen->type == GEN_DIRNAME) {
             iname = gen->d.directoryName;
             break;
         }
     }
     if (!iname)
         iname = X509_get_issuer_name(x);
 
     DIST_POINT_set_dpname(dp->distpoint, iname);
 
 }
 
 static void setup_crldp(X509 *x)
 {
     int i;
     x->crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
     for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++)
         setup_dp(x, sk_DIST_POINT_value(x->crldp, i));
 }
 
 #define V1_ROOT (EXFLAG_V1|EXFLAG_SS)
 #define ku_reject(x, usage) \
         (((x)->ex_flags & EXFLAG_KUSAGE) && !((x)->ex_kusage & (usage)))
 #define xku_reject(x, usage) \
         (((x)->ex_flags & EXFLAG_XKUSAGE) && !((x)->ex_xkusage & (usage)))
 #define ns_reject(x, usage) \
         (((x)->ex_flags & EXFLAG_NSCERT) && !((x)->ex_nscert & (usage)))
 
 static void x509v3_cache_extensions(X509 *x)
 {
     BASIC_CONSTRAINTS *bs;
     PROXY_CERT_INFO_EXTENSION *pci;
     ASN1_BIT_STRING *usage;
     ASN1_BIT_STRING *ns;
     EXTENDED_KEY_USAGE *extusage;
     X509_EXTENSION *ex;
 
     int i;
     if (x->ex_flags & EXFLAG_SET)
         return;
 #ifndef OPENSSL_NO_SHA
     X509_digest(x, EVP_sha1(), x->sha1_hash, NULL);
 #endif
     /* V1 should mean no extensions ... */
     if (!X509_get_version(x))
         x->ex_flags |= EXFLAG_V1;
     /* Handle basic constraints */
     if ((bs = X509_get_ext_d2i(x, NID_basic_constraints, NULL, NULL))) {
         if (bs->ca)
             x->ex_flags |= EXFLAG_CA;
         if (bs->pathlen) {
             if ((bs->pathlen->type == V_ASN1_NEG_INTEGER)
                 || !bs->ca) {
                 x->ex_flags |= EXFLAG_INVALID;
                 x->ex_pathlen = 0;
             } else
                 x->ex_pathlen = ASN1_INTEGER_get(bs->pathlen);
         } else
             x->ex_pathlen = -1;
         BASIC_CONSTRAINTS_free(bs);
         x->ex_flags |= EXFLAG_BCONS;
     }
     /* Handle proxy certificates */
     if ((pci = X509_get_ext_d2i(x, NID_proxyCertInfo, NULL, NULL))) {
         if (x->ex_flags & EXFLAG_CA
             || X509_get_ext_by_NID(x, NID_subject_alt_name, -1) >= 0
             || X509_get_ext_by_NID(x, NID_issuer_alt_name, -1) >= 0) {
             x->ex_flags |= EXFLAG_INVALID;
         }
         if (pci->pcPathLengthConstraint) {
             x->ex_pcpathlen = ASN1_INTEGER_get(pci->pcPathLengthConstraint);
         } else
             x->ex_pcpathlen = -1;
         PROXY_CERT_INFO_EXTENSION_free(pci);
         x->ex_flags |= EXFLAG_PROXY;
     }
     /* Handle key usage */
     if ((usage = X509_get_ext_d2i(x, NID_key_usage, NULL, NULL))) {
         if (usage->length > 0) {
             x->ex_kusage = usage->data[0];
             if (usage->length > 1)
                 x->ex_kusage |= usage->data[1] << 8;
         } else
             x->ex_kusage = 0;
         x->ex_flags |= EXFLAG_KUSAGE;
         ASN1_BIT_STRING_free(usage);
     }
     x->ex_xkusage = 0;
     if ((extusage = X509_get_ext_d2i(x, NID_ext_key_usage, NULL, NULL))) {
         x->ex_flags |= EXFLAG_XKUSAGE;
         for (i = 0; i < sk_ASN1_OBJECT_num(extusage); i++) {
             switch (OBJ_obj2nid(sk_ASN1_OBJECT_value(extusage, i))) {
             case NID_server_auth:
                 x->ex_xkusage |= XKU_SSL_SERVER;
                 break;
 
             case NID_client_auth:
                 x->ex_xkusage |= XKU_SSL_CLIENT;
                 break;
 
             case NID_email_protect:
                 x->ex_xkusage |= XKU_SMIME;
                 break;
 
             case NID_code_sign:
                 x->ex_xkusage |= XKU_CODE_SIGN;
                 break;
 
             case NID_ms_sgc:
             case NID_ns_sgc:
                 x->ex_xkusage |= XKU_SGC;
                 break;
 
             case NID_OCSP_sign:
                 x->ex_xkusage |= XKU_OCSP_SIGN;
                 break;
 
             case NID_time_stamp:
                 x->ex_xkusage |= XKU_TIMESTAMP;
                 break;
 
             case NID_dvcs:
                 x->ex_xkusage |= XKU_DVCS;
                 break;
 
             case NID_anyExtendedKeyUsage:
                 x->ex_xkusage |= XKU_ANYEKU;
                 break;
             }
         }
         sk_ASN1_OBJECT_pop_free(extusage, ASN1_OBJECT_free);
     }
 
     if ((ns = X509_get_ext_d2i(x, NID_netscape_cert_type, NULL, NULL))) {
         if (ns->length > 0)
             x->ex_nscert = ns->data[0];
         else
             x->ex_nscert = 0;
         x->ex_flags |= EXFLAG_NSCERT;
         ASN1_BIT_STRING_free(ns);
     }
     x->skid = X509_get_ext_d2i(x, NID_subject_key_identifier, NULL, NULL);
     x->akid = X509_get_ext_d2i(x, NID_authority_key_identifier, NULL, NULL);
     /* Does subject name match issuer ? */
     if (!X509_NAME_cmp(X509_get_subject_name(x), X509_get_issuer_name(x))) {
         x->ex_flags |= EXFLAG_SI;
         /* If SKID matches AKID also indicate self signed */
         if (X509_check_akid(x, x->akid) == X509_V_OK &&
             !ku_reject(x, KU_KEY_CERT_SIGN))
             x->ex_flags |= EXFLAG_SS;
     }
     x->altname = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
     x->nc = X509_get_ext_d2i(x, NID_name_constraints, &i, NULL);
     if (!x->nc && (i != -1))
         x->ex_flags |= EXFLAG_INVALID;
     setup_crldp(x);
 
 #ifndef OPENSSL_NO_RFC3779
     x->rfc3779_addr = X509_get_ext_d2i(x, NID_sbgp_ipAddrBlock, NULL, NULL);
     x->rfc3779_asid = X509_get_ext_d2i(x, NID_sbgp_autonomousSysNum,
                                        NULL, NULL);
 #endif
     for (i = 0; i < X509_get_ext_count(x); i++) {
         ex = X509_get_ext(x, i);
         if (OBJ_obj2nid(X509_EXTENSION_get_object(ex))
             == NID_freshest_crl)
             x->ex_flags |= EXFLAG_FRESHEST;
         if (!X509_EXTENSION_get_critical(ex))
             continue;
         if (!X509_supported_extension(ex)) {
             x->ex_flags |= EXFLAG_CRITICAL;
             break;
         }
     }
     x->ex_flags |= EXFLAG_SET;
 }
 
 /*-
  * CA checks common to all purposes
  * return codes:
  * 0 not a CA
  * 1 is a CA
  * 2 basicConstraints absent so "maybe" a CA
  * 3 basicConstraints absent but self signed V1.
  * 4 basicConstraints absent but keyUsage present and keyCertSign asserted.
  */
 
 static int check_ca(const X509 *x)
 {
     /* keyUsage if present should allow cert signing */
     if (ku_reject(x, KU_KEY_CERT_SIGN))
         return 0;
     if (x->ex_flags & EXFLAG_BCONS) {
         if (x->ex_flags & EXFLAG_CA)
             return 1;
         /* If basicConstraints says not a CA then say so */
         else
             return 0;
     } else {
         /* we support V1 roots for...  uh, I don't really know why. */
         if ((x->ex_flags & V1_ROOT) == V1_ROOT)
             return 3;
         /*
          * If key usage present it must have certSign so tolerate it
          */
         else if (x->ex_flags & EXFLAG_KUSAGE)
             return 4;
         /* Older certificates could have Netscape-specific CA types */
         else if (x->ex_flags & EXFLAG_NSCERT && x->ex_nscert & NS_ANY_CA)
             return 5;
         /* can this still be regarded a CA certificate?  I doubt it */
         return 0;
     }
 }
 
 int X509_check_ca(X509 *x)
 {
     if (!(x->ex_flags & EXFLAG_SET)) {
         CRYPTO_w_lock(CRYPTO_LOCK_X509);
         x509v3_cache_extensions(x);
         CRYPTO_w_unlock(CRYPTO_LOCK_X509);
     }
 
     return check_ca(x);
 }
 
 /* Check SSL CA: common checks for SSL client and server */
 static int check_ssl_ca(const X509 *x)
 {
     int ca_ret;
     ca_ret = check_ca(x);
     if (!ca_ret)
         return 0;
     /* check nsCertType if present */
     if (ca_ret != 5 || x->ex_nscert & NS_SSL_CA)
         return ca_ret;
     else
         return 0;
 }
 
 static int check_purpose_ssl_client(const X509_PURPOSE *xp, const X509 *x,
                                     int ca)
 {
     if (xku_reject(x, XKU_SSL_CLIENT))
         return 0;
     if (ca)
         return check_ssl_ca(x);
     /* We need to do digital signatures or key agreement */
     if (ku_reject(x, KU_DIGITAL_SIGNATURE | KU_KEY_AGREEMENT))
         return 0;
     /* nsCertType if present should allow SSL client use */
     if (ns_reject(x, NS_SSL_CLIENT))
         return 0;
     return 1;
 }
 
 /*
  * Key usage needed for TLS/SSL server: digital signature, encipherment or
  * key agreement. The ssl code can check this more thoroughly for individual
  * key types.
  */
 #define KU_TLS \
         KU_DIGITAL_SIGNATURE|KU_KEY_ENCIPHERMENT|KU_KEY_AGREEMENT
 
 static int check_purpose_ssl_server(const X509_PURPOSE *xp, const X509 *x,
                                     int ca)
 {
     if (xku_reject(x, XKU_SSL_SERVER | XKU_SGC))
         return 0;
     if (ca)
         return check_ssl_ca(x);
 
     if (ns_reject(x, NS_SSL_SERVER))
         return 0;
     if (ku_reject(x, KU_TLS))
         return 0;
 
     return 1;
 
 }
 
 static int check_purpose_ns_ssl_server(const X509_PURPOSE *xp, const X509 *x,
                                        int ca)
 {
     int ret;
     ret = check_purpose_ssl_server(xp, x, ca);
     if (!ret || ca)
         return ret;
     /* We need to encipher or Netscape complains */
     if (ku_reject(x, KU_KEY_ENCIPHERMENT))
         return 0;
     return ret;
 }
 
 /* common S/MIME checks */
 static int purpose_smime(const X509 *x, int ca)
 {
     if (xku_reject(x, XKU_SMIME))
         return 0;
     if (ca) {
         int ca_ret;
         ca_ret = check_ca(x);
         if (!ca_ret)
             return 0;
         /* check nsCertType if present */
         if (ca_ret != 5 || x->ex_nscert & NS_SMIME_CA)
             return ca_ret;
         else
             return 0;
     }
     if (x->ex_flags & EXFLAG_NSCERT) {
         if (x->ex_nscert & NS_SMIME)
             return 1;
         /* Workaround for some buggy certificates */
         if (x->ex_nscert & NS_SSL_CLIENT)
             return 2;
         return 0;
     }
     return 1;
 }
 
 static int check_purpose_smime_sign(const X509_PURPOSE *xp, const X509 *x,
                                     int ca)
 {
     int ret;
     ret = purpose_smime(x, ca);
     if (!ret || ca)
         return ret;
     if (ku_reject(x, KU_DIGITAL_SIGNATURE | KU_NON_REPUDIATION))
         return 0;
     return ret;
 }
 
 static int check_purpose_smime_encrypt(const X509_PURPOSE *xp, const X509 *x,
                                        int ca)
 {
     int ret;
     ret = purpose_smime(x, ca);
     if (!ret || ca)
         return ret;
     if (ku_reject(x, KU_KEY_ENCIPHERMENT))
         return 0;
     return ret;
 }
 
 static int check_purpose_crl_sign(const X509_PURPOSE *xp, const X509 *x,
                                   int ca)
 {
     if (ca) {
         int ca_ret;
         if ((ca_ret = check_ca(x)) != 2)
             return ca_ret;
         else
             return 0;
     }
     if (ku_reject(x, KU_CRL_SIGN))
         return 0;
     return 1;
 }
 
 /*
  * OCSP helper: this is *not* a full OCSP check. It just checks that each CA
  * is valid. Additional checks must be made on the chain.
  */
 
 static int ocsp_helper(const X509_PURPOSE *xp, const X509 *x, int ca)
 {
     /*
      * Must be a valid CA.  Should we really support the "I don't know" value
      * (2)?
      */
     if (ca)
         return check_ca(x);
     /* leaf certificate is checked in OCSP_verify() */
     return 1;
 }
 
 static int check_purpose_timestamp_sign(const X509_PURPOSE *xp, const X509 *x,
                                         int ca)
 {
     int i_ext;
 
     /* If ca is true we must return if this is a valid CA certificate. */
     if (ca)
         return check_ca(x);
 
     /*
      * Check the optional key usage field:
      * if Key Usage is present, it must be one of digitalSignature
      * and/or nonRepudiation (other values are not consistent and shall
      * be rejected).
      */
     if ((x->ex_flags & EXFLAG_KUSAGE)
         && ((x->ex_kusage & ~(KU_NON_REPUDIATION | KU_DIGITAL_SIGNATURE)) ||
             !(x->ex_kusage & (KU_NON_REPUDIATION | KU_DIGITAL_SIGNATURE))))
         return 0;
 
     /* Only time stamp key usage is permitted and it's required. */
     if (!(x->ex_flags & EXFLAG_XKUSAGE) || x->ex_xkusage != XKU_TIMESTAMP)
         return 0;
 
     /* Extended Key Usage MUST be critical */
     i_ext = X509_get_ext_by_NID((X509 *)x, NID_ext_key_usage, -1);
     if (i_ext >= 0) {
         X509_EXTENSION *ext = X509_get_ext((X509 *)x, i_ext);
         if (!X509_EXTENSION_get_critical(ext))
             return 0;
     }
 
     return 1;
 }
 
 static int no_check(const X509_PURPOSE *xp, const X509 *x, int ca)
 {
     return 1;
 }
 
 /*-
  * Various checks to see if one certificate issued the second.
  * This can be used to prune a set of possible issuer certificates
  * which have been looked up using some simple method such as by
  * subject name.
  * These are:
  * 1. Check issuer_name(subject) == subject_name(issuer)
  * 2. If akid(subject) exists check it matches issuer
  * 3. If key_usage(issuer) exists check it supports certificate signing
  * returns 0 for OK, positive for reason for mismatch, reasons match
  * codes for X509_verify_cert()
  */
 
 int X509_check_issued(X509 *issuer, X509 *subject)
 {
     if (X509_NAME_cmp(X509_get_subject_name(issuer),
                       X509_get_issuer_name(subject)))
         return X509_V_ERR_SUBJECT_ISSUER_MISMATCH;
     x509v3_cache_extensions(issuer);
     x509v3_cache_extensions(subject);
 
     if (subject->akid) {
         int ret = X509_check_akid(issuer, subject->akid);
         if (ret != X509_V_OK)
             return ret;
     }
 
     if (subject->ex_flags & EXFLAG_PROXY) {
         if (ku_reject(issuer, KU_DIGITAL_SIGNATURE))
             return X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE;
     } else if (ku_reject(issuer, KU_KEY_CERT_SIGN))
         return X509_V_ERR_KEYUSAGE_NO_CERTSIGN;
     return X509_V_OK;
 }
 
 int X509_check_akid(X509 *issuer, AUTHORITY_KEYID *akid)
 {
 
     if (!akid)
         return X509_V_OK;
 
     /* Check key ids (if present) */
     if (akid->keyid && issuer->skid &&
         ASN1_OCTET_STRING_cmp(akid->keyid, issuer->skid))
         return X509_V_ERR_AKID_SKID_MISMATCH;
     /* Check serial number */
     if (akid->serial &&
         ASN1_INTEGER_cmp(X509_get_serialNumber(issuer), akid->serial))
         return X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
     /* Check issuer name */
     if (akid->issuer) {
         /*
          * Ugh, for some peculiar reason AKID includes SEQUENCE OF
          * GeneralName. So look for a DirName. There may be more than one but
          * we only take any notice of the first.
          */
         GENERAL_NAMES *gens;
         GENERAL_NAME *gen;
         X509_NAME *nm = NULL;
         int i;
         gens = akid->issuer;
         for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
             gen = sk_GENERAL_NAME_value(gens, i);
             if (gen->type == GEN_DIRNAME) {
                 nm = gen->d.dirn;
                 break;
             }
         }
         if (nm && X509_NAME_cmp(nm, X509_get_issuer_name(issuer)))
             return X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
     }
     return X509_V_OK;
 }
Index: vendor-crypto/openssl/dist/crypto/x86_64cpuid.pl
===================================================================
--- vendor-crypto/openssl/dist/crypto/x86_64cpuid.pl	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/x86_64cpuid.pl	(revision 318897)
@@ -1,309 +1,310 @@
 #!/usr/bin/env perl
 
 $flavour = shift;
 $output  = shift;
 if ($flavour =~ /\./) { $output = $flavour; undef $flavour; }
 
 $win64=0; $win64=1 if ($flavour =~ /[nm]asm|mingw64/ || $output =~ /\.asm$/);
 
 $0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1;
 ( $xlate="${dir}x86_64-xlate.pl" and -f $xlate ) or
 ( $xlate="${dir}perlasm/x86_64-xlate.pl" and -f $xlate) or
 die "can't locate x86_64-xlate.pl";
 
 open OUT,"| \"$^X\" $xlate $flavour $output";
 *STDOUT=*OUT;
 
 ($arg1,$arg2,$arg3,$arg4)=$win64?("%rcx","%rdx","%r8", "%r9") :	# Win64 order
 				 ("%rdi","%rsi","%rdx","%rcx");	# Unix order
 
 print<<___;
 .extern		OPENSSL_cpuid_setup
 .hidden		OPENSSL_cpuid_setup
 .section	.init
 	call	OPENSSL_cpuid_setup
 
 .hidden	OPENSSL_ia32cap_P
 .comm	OPENSSL_ia32cap_P,16,4
 
 .text
 
 .globl	OPENSSL_atomic_add
 .type	OPENSSL_atomic_add,\@abi-omnipotent
 .align	16
 OPENSSL_atomic_add:
 	movl	($arg1),%eax
 .Lspin:	leaq	($arg2,%rax),%r8
 	.byte	0xf0		# lock
 	cmpxchgl	%r8d,($arg1)
 	jne	.Lspin
 	movl	%r8d,%eax
 	.byte	0x48,0x98	# cltq/cdqe
 	ret
 .size	OPENSSL_atomic_add,.-OPENSSL_atomic_add
 
 .globl	OPENSSL_rdtsc
 .type	OPENSSL_rdtsc,\@abi-omnipotent
 .align	16
 OPENSSL_rdtsc:
 	rdtsc
 	shl	\$32,%rdx
 	or	%rdx,%rax
 	ret
 .size	OPENSSL_rdtsc,.-OPENSSL_rdtsc
 
 .globl	OPENSSL_ia32_cpuid
 .type	OPENSSL_ia32_cpuid,\@function,1
 .align	16
 OPENSSL_ia32_cpuid:
 	mov	%rbx,%r8		# save %rbx
 
 	xor	%eax,%eax
-	mov	%eax,8(%rdi)		# clear 3rd word
+	mov	%eax,8(%rdi)		# clear extended feature flags
 	cpuid
 	mov	%eax,%r11d		# max value for standard query level
 
 	xor	%eax,%eax
 	cmp	\$0x756e6547,%ebx	# "Genu"
 	setne	%al
 	mov	%eax,%r9d
 	cmp	\$0x49656e69,%edx	# "ineI"
 	setne	%al
 	or	%eax,%r9d
 	cmp	\$0x6c65746e,%ecx	# "ntel"
 	setne	%al
 	or	%eax,%r9d		# 0 indicates Intel CPU
 	jz	.Lintel
 
 	cmp	\$0x68747541,%ebx	# "Auth"
 	setne	%al
 	mov	%eax,%r10d
 	cmp	\$0x69746E65,%edx	# "enti"
 	setne	%al
 	or	%eax,%r10d
 	cmp	\$0x444D4163,%ecx	# "cAMD"
 	setne	%al
 	or	%eax,%r10d		# 0 indicates AMD CPU
 	jnz	.Lintel
 
 	# AMD specific
 	mov	\$0x80000000,%eax
 	cpuid
 	cmp	\$0x80000001,%eax
 	jb	.Lintel
 	mov	%eax,%r10d
 	mov	\$0x80000001,%eax
 	cpuid
 	or	%ecx,%r9d
 	and	\$0x00000801,%r9d	# isolate AMD XOP bit, 1<<11
 
 	cmp	\$0x80000008,%r10d
 	jb	.Lintel
 
 	mov	\$0x80000008,%eax
 	cpuid
 	movzb	%cl,%r10		# number of cores - 1
 	inc	%r10			# number of cores
 
 	mov	\$1,%eax
 	cpuid
 	bt	\$28,%edx		# test hyper-threading bit
 	jnc	.Lgeneric
 	shr	\$16,%ebx		# number of logical processors
 	cmp	%r10b,%bl
 	ja	.Lgeneric
 	and	\$0xefffffff,%edx	# ~(1<<28)
 	jmp	.Lgeneric
 
 .Lintel:
 	cmp	\$4,%r11d
 	mov	\$-1,%r10d
 	jb	.Lnocacheinfo
 
 	mov	\$4,%eax
 	mov	\$0,%ecx		# query L1D
 	cpuid
 	mov	%eax,%r10d
 	shr	\$14,%r10d
 	and	\$0xfff,%r10d		# number of cores -1 per L1D
 
-	cmp	\$7,%r11d
-	jb	.Lnocacheinfo
-
-	mov	\$7,%eax
-	xor	%ecx,%ecx
-	cpuid
-	mov	%ebx,8(%rdi)
-
 .Lnocacheinfo:
 	mov	\$1,%eax
 	cpuid
 	and	\$0xbfefffff,%edx	# force reserved bits to 0
 	cmp	\$0,%r9d
 	jne	.Lnotintel
 	or	\$0x40000000,%edx	# set reserved bit#30 on Intel CPUs
 	and	\$15,%ah
 	cmp	\$15,%ah		# examine Family ID
 	jne	.Lnotintel
 	or	\$0x00100000,%edx	# set reserved bit#20 to engage RC4_CHAR
 .Lnotintel:
 	bt	\$28,%edx		# test hyper-threading bit
 	jnc	.Lgeneric
 	and	\$0xefffffff,%edx	# ~(1<<28)
 	cmp	\$0,%r10d
 	je	.Lgeneric
 
 	or	\$0x10000000,%edx	# 1<<28
 	shr	\$16,%ebx
 	cmp	\$1,%bl			# see if cache is shared
 	ja	.Lgeneric
 	and	\$0xefffffff,%edx	# ~(1<<28)
 .Lgeneric:
 	and	\$0x00000800,%r9d	# isolate AMD XOP flag
 	and	\$0xfffff7ff,%ecx
 	or	%ecx,%r9d		# merge AMD XOP flag
 
 	mov	%edx,%r10d		# %r9d:%r10d is copy of %ecx:%edx
+
+	cmp	\$7,%r11d
+	jb	.Lno_extended_info
+	mov	\$7,%eax
+	xor	%ecx,%ecx
+	cpuid
+	mov	%ebx,8(%rdi)		# save extended feature flags
+.Lno_extended_info:
+
 	bt	\$27,%r9d		# check OSXSAVE bit
 	jnc	.Lclear_avx
 	xor	%ecx,%ecx		# XCR0
 	.byte	0x0f,0x01,0xd0		# xgetbv
 	and	\$6,%eax		# isolate XMM and YMM state support
 	cmp	\$6,%eax
 	je	.Ldone
 .Lclear_avx:
 	mov	\$0xefffe7ff,%eax	# ~(1<<28|1<<12|1<<11)
 	and	%eax,%r9d		# clear AVX, FMA and AMD XOP bits
 	andl	\$0xffffffdf,8(%rdi)	# cleax AVX2, ~(1<<5)
 .Ldone:
 	shl	\$32,%r9
 	mov	%r10d,%eax
 	mov	%r8,%rbx		# restore %rbx
 	or	%r9,%rax
 	ret
 .size	OPENSSL_ia32_cpuid,.-OPENSSL_ia32_cpuid
 
 .globl  OPENSSL_cleanse
 .type   OPENSSL_cleanse,\@abi-omnipotent
 .align  16
 OPENSSL_cleanse:
 	xor	%rax,%rax
 	cmp	\$15,$arg2
 	jae	.Lot
 	cmp	\$0,$arg2
 	je	.Lret
 .Little:
 	mov	%al,($arg1)
 	sub	\$1,$arg2
 	lea	1($arg1),$arg1
 	jnz	.Little
 .Lret:
 	ret
 .align	16
 .Lot:
 	test	\$7,$arg1
 	jz	.Laligned
 	mov	%al,($arg1)
 	lea	-1($arg2),$arg2
 	lea	1($arg1),$arg1
 	jmp	.Lot
 .Laligned:
 	mov	%rax,($arg1)
 	lea	-8($arg2),$arg2
 	test	\$-8,$arg2
 	lea	8($arg1),$arg1
 	jnz	.Laligned
 	cmp	\$0,$arg2
 	jne	.Little
 	ret
 .size	OPENSSL_cleanse,.-OPENSSL_cleanse
 ___
 
 print<<___ if (!$win64);
 .globl	OPENSSL_wipe_cpu
 .type	OPENSSL_wipe_cpu,\@abi-omnipotent
 .align	16
 OPENSSL_wipe_cpu:
 	pxor	%xmm0,%xmm0
 	pxor	%xmm1,%xmm1
 	pxor	%xmm2,%xmm2
 	pxor	%xmm3,%xmm3
 	pxor	%xmm4,%xmm4
 	pxor	%xmm5,%xmm5
 	pxor	%xmm6,%xmm6
 	pxor	%xmm7,%xmm7
 	pxor	%xmm8,%xmm8
 	pxor	%xmm9,%xmm9
 	pxor	%xmm10,%xmm10
 	pxor	%xmm11,%xmm11
 	pxor	%xmm12,%xmm12
 	pxor	%xmm13,%xmm13
 	pxor	%xmm14,%xmm14
 	pxor	%xmm15,%xmm15
 	xorq	%rcx,%rcx
 	xorq	%rdx,%rdx
 	xorq	%rsi,%rsi
 	xorq	%rdi,%rdi
 	xorq	%r8,%r8
 	xorq	%r9,%r9
 	xorq	%r10,%r10
 	xorq	%r11,%r11
 	leaq	8(%rsp),%rax
 	ret
 .size	OPENSSL_wipe_cpu,.-OPENSSL_wipe_cpu
 ___
 print<<___ if ($win64);
 .globl	OPENSSL_wipe_cpu
 .type	OPENSSL_wipe_cpu,\@abi-omnipotent
 .align	16
 OPENSSL_wipe_cpu:
 	pxor	%xmm0,%xmm0
 	pxor	%xmm1,%xmm1
 	pxor	%xmm2,%xmm2
 	pxor	%xmm3,%xmm3
 	pxor	%xmm4,%xmm4
 	pxor	%xmm5,%xmm5
 	xorq	%rcx,%rcx
 	xorq	%rdx,%rdx
 	xorq	%r8,%r8
 	xorq	%r9,%r9
 	xorq	%r10,%r10
 	xorq	%r11,%r11
 	leaq	8(%rsp),%rax
 	ret
 .size	OPENSSL_wipe_cpu,.-OPENSSL_wipe_cpu
 ___
 
 print<<___;
 .globl	OPENSSL_ia32_rdrand
 .type	OPENSSL_ia32_rdrand,\@abi-omnipotent
 .align	16
 OPENSSL_ia32_rdrand:
 	mov	\$8,%ecx
 .Loop_rdrand:
 	rdrand	%rax
 	jc	.Lbreak_rdrand
 	loop	.Loop_rdrand
 .Lbreak_rdrand:
 	cmp	\$0,%rax
 	cmove	%rcx,%rax
 	ret
 .size	OPENSSL_ia32_rdrand,.-OPENSSL_ia32_rdrand
 
 .globl	OPENSSL_ia32_rdseed
 .type	OPENSSL_ia32_rdseed,\@abi-omnipotent
 .align	16
 OPENSSL_ia32_rdseed:
 	mov	\$8,%ecx
 .Loop_rdseed:
 	rdseed	%rax
 	jc	.Lbreak_rdseed
 	loop	.Loop_rdseed
 .Lbreak_rdseed:
 	cmp	\$0,%rax
 	cmove	%rcx,%rax
 	ret
 .size	OPENSSL_ia32_rdseed,.-OPENSSL_ia32_rdseed
 ___
 
 close STDOUT;	# flush
Index: vendor-crypto/openssl/dist/crypto/x86cpuid.pl
===================================================================
--- vendor-crypto/openssl/dist/crypto/x86cpuid.pl	(revision 318896)
+++ vendor-crypto/openssl/dist/crypto/x86cpuid.pl	(revision 318897)
@@ -1,387 +1,385 @@
 #!/usr/bin/env perl
 
 $0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1;
 push(@INC, "${dir}perlasm", "perlasm");
 require "x86asm.pl";
 
 &asm_init($ARGV[0],"x86cpuid");
 
 for (@ARGV) { $sse2=1 if (/-DOPENSSL_IA32_SSE2/); }
 
 &function_begin("OPENSSL_ia32_cpuid");
 	&xor	("edx","edx");
 	&pushf	();
 	&pop	("eax");
 	&mov	("ecx","eax");
 	&xor	("eax",1<<21);
 	&push	("eax");
 	&popf	();
 	&pushf	();
 	&pop	("eax");
 	&xor	("ecx","eax");
 	&xor	("eax","eax");
+	&mov	("esi",&wparam(0));
+	&mov	(&DWP(8,"esi"),"eax");	# clear extended feature flags
 	&bt	("ecx",21);
 	&jnc	(&label("nocpuid"));
-	&mov	("esi",&wparam(0));
-	&mov	(&DWP(8,"esi"),"eax");	# clear 3rd word
 	&cpuid	();
 	&mov	("edi","eax");		# max value for standard query level
 
 	&xor	("eax","eax");
 	&cmp	("ebx",0x756e6547);	# "Genu"
 	&setne	(&LB("eax"));
 	&mov	("ebp","eax");
 	&cmp	("edx",0x49656e69);	# "ineI"
 	&setne	(&LB("eax"));
 	&or	("ebp","eax");
 	&cmp	("ecx",0x6c65746e);	# "ntel"
 	&setne	(&LB("eax"));
 	&or	("ebp","eax");		# 0 indicates Intel CPU
 	&jz	(&label("intel"));
 
 	&cmp	("ebx",0x68747541);	# "Auth"
 	&setne	(&LB("eax"));
 	&mov	("esi","eax");
 	&cmp	("edx",0x69746E65);	# "enti"
 	&setne	(&LB("eax"));
 	&or	("esi","eax");
 	&cmp	("ecx",0x444D4163);	# "cAMD"
 	&setne	(&LB("eax"));
 	&or	("esi","eax");		# 0 indicates AMD CPU
 	&jnz	(&label("intel"));
 
 	# AMD specific
 	&mov	("eax",0x80000000);
 	&cpuid	();
 	&cmp	("eax",0x80000001);
 	&jb	(&label("intel"));
 	&mov	("esi","eax");
 	&mov	("eax",0x80000001);
 	&cpuid	();
 	&or	("ebp","ecx");
 	&and	("ebp",1<<11|1);	# isolate XOP bit
 	&cmp	("esi",0x80000008);
 	&jb	(&label("intel"));
 
 	&mov	("eax",0x80000008);
 	&cpuid	();
 	&movz	("esi",&LB("ecx"));	# number of cores - 1
 	&inc	("esi");		# number of cores
 
 	&mov	("eax",1);
 	&xor	("ecx","ecx");
 	&cpuid	();
 	&bt	("edx",28);
 	&jnc	(&label("generic"));
 	&shr	("ebx",16);
 	&and	("ebx",0xff);
 	&cmp	("ebx","esi");
 	&ja	(&label("generic"));
 	&and	("edx",0xefffffff);	# clear hyper-threading bit
 	&jmp	(&label("generic"));
 	
 &set_label("intel");
-	&cmp	("edi",7);
-	&jb	(&label("cacheinfo"));
-
-	&mov	("esi",&wparam(0));
-	&mov	("eax",7);
-	&xor	("ecx","ecx");
-	&cpuid	();
-	&mov	(&DWP(8,"esi"),"ebx");
-
-&set_label("cacheinfo");
 	&cmp	("edi",4);
-	&mov	("edi",-1);
+	&mov	("esi",-1);
 	&jb	(&label("nocacheinfo"));
 
 	&mov	("eax",4);
 	&mov	("ecx",0);		# query L1D
 	&cpuid	();
-	&mov	("edi","eax");
-	&shr	("edi",14);
-	&and	("edi",0xfff);		# number of cores -1 per L1D
+	&mov	("esi","eax");
+	&shr	("esi",14);
+	&and	("esi",0xfff);		# number of cores -1 per L1D
 
 &set_label("nocacheinfo");
 	&mov	("eax",1);
 	&xor	("ecx","ecx");
 	&cpuid	();
 	&and	("edx",0xbfefffff);	# force reserved bits #20, #30 to 0
 	&cmp	("ebp",0);
 	&jne	(&label("notintel"));
 	&or	("edx",1<<30);		# set reserved bit#30 on Intel CPUs
 	&and	(&HB("eax"),15);	# familiy ID
 	&cmp	(&HB("eax"),15);	# P4?
 	&jne	(&label("notintel"));
 	&or	("edx",1<<20);		# set reserved bit#20 to engage RC4_CHAR
 &set_label("notintel");
 	&bt	("edx",28);		# test hyper-threading bit
 	&jnc	(&label("generic"));
 	&and	("edx",0xefffffff);
-	&cmp	("edi",0);
+	&cmp	("esi",0);
 	&je	(&label("generic"));
 
 	&or	("edx",0x10000000);
 	&shr	("ebx",16);
 	&cmp	(&LB("ebx"),1);
 	&ja	(&label("generic"));
 	&and	("edx",0xefffffff);	# clear hyper-threading bit if not
 
 &set_label("generic");
 	&and	("ebp",1<<11);		# isolate AMD XOP flag
 	&and	("ecx",0xfffff7ff);	# force 11th bit to 0
-	&mov	("esi","edx");
+	&mov	("esi","edx");		# %ebp:%esi is copy of %ecx:%edx
 	&or	("ebp","ecx");		# merge AMD XOP flag
 
-	&bt	("ecx",27);		# check OSXSAVE bit
+	&cmp	("edi",7);
+	&mov	("edi",&wparam(0));
+	&jb	(&label("no_extended_info"));
+	&mov	("eax",7);
+	&xor	("ecx","ecx");
+	&cpuid	();
+	&mov	(&DWP(8,"edi"),"ebx");	# save extended feature flag
+&set_label("no_extended_info");
+
+	&bt	("ebp",27);		# check OSXSAVE bit
 	&jnc	(&label("clear_avx"));
 	&xor	("ecx","ecx");
 	&data_byte(0x0f,0x01,0xd0);	# xgetbv
 	&and	("eax",6);
 	&cmp	("eax",6);
 	&je	(&label("done"));
 	&cmp	("eax",2);
 	&je	(&label("clear_avx"));
 &set_label("clear_xmm");
 	&and	("ebp",0xfdfffffd);	# clear AESNI and PCLMULQDQ bits
 	&and	("esi",0xfeffffff);	# clear FXSR
 &set_label("clear_avx");
 	&and	("ebp",0xefffe7ff);	# clear AVX, FMA and AMD XOP bits
-	&mov	("edi",&wparam(0));
 	&and	(&DWP(8,"edi"),0xffffffdf);	# clear AVX2
 &set_label("done");
 	&mov	("eax","esi");
 	&mov	("edx","ebp");
 &set_label("nocpuid");
 &function_end("OPENSSL_ia32_cpuid");
 
 &external_label("OPENSSL_ia32cap_P");
 
 &function_begin_B("OPENSSL_rdtsc","EXTRN\t_OPENSSL_ia32cap_P:DWORD");
 	&xor	("eax","eax");
 	&xor	("edx","edx");
 	&picmeup("ecx","OPENSSL_ia32cap_P");
 	&bt	(&DWP(0,"ecx"),4);
 	&jnc	(&label("notsc"));
 	&rdtsc	();
 &set_label("notsc");
 	&ret	();
 &function_end_B("OPENSSL_rdtsc");
 
 # This works in Ring 0 only [read DJGPP+MS-DOS+privileged DPMI host],
 # but it's safe to call it on any [supported] 32-bit platform...
 # Just check for [non-]zero return value...
 &function_begin_B("OPENSSL_instrument_halt","EXTRN\t_OPENSSL_ia32cap_P:DWORD");
 	&picmeup("ecx","OPENSSL_ia32cap_P");
 	&bt	(&DWP(0,"ecx"),4);
 	&jnc	(&label("nohalt"));	# no TSC
 
 	&data_word(0x9058900e);		# push %cs; pop %eax
 	&and	("eax",3);
 	&jnz	(&label("nohalt"));	# not enough privileges
 
 	&pushf	();
 	&pop	("eax");
 	&bt	("eax",9);
 	&jnc	(&label("nohalt"));	# interrupts are disabled
 
 	&rdtsc	();
 	&push	("edx");
 	&push	("eax");
 	&halt	();
 	&rdtsc	();
 
 	&sub	("eax",&DWP(0,"esp"));
 	&sbb	("edx",&DWP(4,"esp"));
 	&add	("esp",8);
 	&ret	();
 
 &set_label("nohalt");
 	&xor	("eax","eax");
 	&xor	("edx","edx");
 	&ret	();
 &function_end_B("OPENSSL_instrument_halt");
 
 # Essentially there is only one use for this function. Under DJGPP:
 #
 #	#include 
 #	...
 #	i=OPENSSL_far_spin(_dos_ds,0x46c);
 #	...
 # to obtain the number of spins till closest timer interrupt.
 
 &function_begin_B("OPENSSL_far_spin");
 	&pushf	();
 	&pop	("eax");
 	&bt	("eax",9);
 	&jnc	(&label("nospin"));	# interrupts are disabled
 
 	&mov	("eax",&DWP(4,"esp"));
 	&mov	("ecx",&DWP(8,"esp"));
 	&data_word (0x90d88e1e);	# push %ds, mov %eax,%ds
 	&xor	("eax","eax");
 	&mov	("edx",&DWP(0,"ecx"));
 	&jmp	(&label("spin"));
 
 	&align	(16);
 &set_label("spin");
 	&inc	("eax");
 	&cmp	("edx",&DWP(0,"ecx"));
 	&je	(&label("spin"));
 
 	&data_word (0x1f909090);	# pop	%ds
 	&ret	();
 
 &set_label("nospin");
 	&xor	("eax","eax");
 	&xor	("edx","edx");
 	&ret	();
 &function_end_B("OPENSSL_far_spin");
 
 &function_begin_B("OPENSSL_wipe_cpu","EXTRN\t_OPENSSL_ia32cap_P:DWORD");
 	&xor	("eax","eax");
 	&xor	("edx","edx");
 	&picmeup("ecx","OPENSSL_ia32cap_P");
 	&mov	("ecx",&DWP(0,"ecx"));
 	&bt	(&DWP(0,"ecx"),1);
 	&jnc	(&label("no_x87"));
 	if ($sse2) {
 		&and	("ecx",1<<26|1<<24);	# check SSE2 and FXSR bits
 		&cmp	("ecx",1<<26|1<<24);
 		&jne	(&label("no_sse2"));
 		&pxor	("xmm0","xmm0");
 		&pxor	("xmm1","xmm1");
 		&pxor	("xmm2","xmm2");
 		&pxor	("xmm3","xmm3");
 		&pxor	("xmm4","xmm4");
 		&pxor	("xmm5","xmm5");
 		&pxor	("xmm6","xmm6");
 		&pxor	("xmm7","xmm7");
 	&set_label("no_sse2");
 	}
 	# just a bunch of fldz to zap the fp/mm bank followed by finit...
 	&data_word(0xeed9eed9,0xeed9eed9,0xeed9eed9,0xeed9eed9,0x90e3db9b);
 &set_label("no_x87");
 	&lea	("eax",&DWP(4,"esp"));
 	&ret	();
 &function_end_B("OPENSSL_wipe_cpu");
 
 &function_begin_B("OPENSSL_atomic_add");
 	&mov	("edx",&DWP(4,"esp"));	# fetch the pointer, 1st arg
 	&mov	("ecx",&DWP(8,"esp"));	# fetch the increment, 2nd arg
 	&push	("ebx");
 	&nop	();
 	&mov	("eax",&DWP(0,"edx"));
 &set_label("spin");
 	&lea	("ebx",&DWP(0,"eax","ecx"));
 	&nop	();
 	&data_word(0x1ab10ff0);	# lock;	cmpxchg	%ebx,(%edx)	# %eax is envolved and is always reloaded
 	&jne	(&label("spin"));
 	&mov	("eax","ebx");	# OpenSSL expects the new value
 	&pop	("ebx");
 	&ret	();
 &function_end_B("OPENSSL_atomic_add");
 
 # This function can become handy under Win32 in situations when
 # we don't know which calling convention, __stdcall or __cdecl(*),
 # indirect callee is using. In C it can be deployed as
 #
 #ifdef OPENSSL_CPUID_OBJ
 #	type OPENSSL_indirect_call(void *f,...);
 #	...
 #	OPENSSL_indirect_call(func,[up to $max arguments]);
 #endif
 #
 # (*)	it's designed to work even for __fastcall if number of
 #	arguments is 1 or 2!
 &function_begin_B("OPENSSL_indirect_call");
 	{
 	my ($max,$i)=(7,);	# $max has to be chosen as 4*n-1
 				# in order to preserve eventual
 				# stack alignment
 	&push	("ebp");
 	&mov	("ebp","esp");
 	&sub	("esp",$max*4);
 	&mov	("ecx",&DWP(12,"ebp"));
 	&mov	(&DWP(0,"esp"),"ecx");
 	&mov	("edx",&DWP(16,"ebp"));
 	&mov	(&DWP(4,"esp"),"edx");
 	for($i=2;$i<$max;$i++)
 		{
 		# Some copies will be redundant/bogus...
 		&mov	("eax",&DWP(12+$i*4,"ebp"));
 		&mov	(&DWP(0+$i*4,"esp"),"eax");
 		}
 	&call_ptr	(&DWP(8,"ebp"));# make the call...
 	&mov	("esp","ebp");	# ... and just restore the stack pointer
 				# without paying attention to what we called,
 				# (__cdecl *func) or (__stdcall *one).
 	&pop	("ebp");
 	&ret	();
 	}
 &function_end_B("OPENSSL_indirect_call");
 
 &function_begin_B("OPENSSL_cleanse");
 	&mov	("edx",&wparam(0));
 	&mov	("ecx",&wparam(1));
 	&xor	("eax","eax");
 	&cmp	("ecx",7);
 	&jae	(&label("lot"));
 	&cmp	("ecx",0);
 	&je	(&label("ret"));
 &set_label("little");
 	&mov	(&BP(0,"edx"),"al");
 	&sub	("ecx",1);
 	&lea	("edx",&DWP(1,"edx"));
 	&jnz	(&label("little"));
 &set_label("ret");
 	&ret	();
 
 &set_label("lot",16);
 	&test	("edx",3);
 	&jz	(&label("aligned"));
 	&mov	(&BP(0,"edx"),"al");
 	&lea	("ecx",&DWP(-1,"ecx"));
 	&lea	("edx",&DWP(1,"edx"));
 	&jmp	(&label("lot"));
 &set_label("aligned");
 	&mov	(&DWP(0,"edx"),"eax");
 	&lea	("ecx",&DWP(-4,"ecx"));
 	&test	("ecx",-4);
 	&lea	("edx",&DWP(4,"edx"));
 	&jnz	(&label("aligned"));
 	&cmp	("ecx",0);
 	&jne	(&label("little"));
 	&ret	();
 &function_end_B("OPENSSL_cleanse");
 
 &function_begin_B("OPENSSL_ia32_rdrand");
 	&mov	("ecx",8);
 &set_label("loop");
 	&rdrand	("eax");
 	&jc	(&label("break"));
 	&loop	(&label("loop"));
 &set_label("break");
 	&cmp	("eax",0);
 	&cmove	("eax","ecx");
 	&ret	();
 &function_end_B("OPENSSL_ia32_rdrand");
 
 &function_begin_B("OPENSSL_ia32_rdseed");
 	&mov	("ecx",8);
 &set_label("loop");
 	&rdseed	("eax");
 	&jc	(&label("break"));
 	&loop	(&label("loop"));
 &set_label("break");
 	&cmp	("eax",0);
 	&cmove	("eax","ecx");
 	&ret	();
 &function_end_B("OPENSSL_ia32_rdseed");
 
 &initseg("OPENSSL_cpuid_setup");
 
 &hidden("OPENSSL_cpuid_setup");
 &hidden("OPENSSL_ia32cap_P");
 
 &asm_finish();
Index: vendor-crypto/openssl/dist/doc/apps/ciphers.pod
===================================================================
--- vendor-crypto/openssl/dist/doc/apps/ciphers.pod	(revision 318896)
+++ vendor-crypto/openssl/dist/doc/apps/ciphers.pod	(revision 318897)
@@ -1,645 +1,646 @@
 =pod
 
 =head1 NAME
 
 ciphers - SSL cipher display and cipher list tool.
 
 =head1 SYNOPSIS
 
 B B
 [B<-v>]
 [B<-V>]
 [B<-ssl2>]
 [B<-ssl3>]
 [B<-tls1>]
 [B]
 
 =head1 DESCRIPTION
 
 The B command converts textual OpenSSL cipher lists into ordered
 SSL cipher preference lists. It can be used as a test tool to determine
 the appropriate cipherlist.
 
 =head1 COMMAND OPTIONS
 
 =over 4
 
 =item B<-v>
 
 Verbose option. List ciphers with a complete description of
 protocol version (SSLv2 or SSLv3; the latter includes TLS), key exchange,
 authentication, encryption and mac algorithms used along with any key size
 restrictions and whether the algorithm is classed as an "export" cipher.
 Note that without the B<-v> option, ciphers may seem to appear twice
 in a cipher list; this is when similar ciphers are available for
 SSL v2 and for SSL v3/TLS v1.
 
 =item B<-V>
 
 Like B<-v>, but include cipher suite codes in output (hex format).
 
 =item B<-ssl3>, B<-tls1>
 
 This lists ciphers compatible with any of SSLv3, TLSv1, TLSv1.1 or TLSv1.2.
 
 =item B<-ssl2>
 
 Only include SSLv2 ciphers.
 
 =item B<-h>, B<-?>
 
 Print a brief usage message.
 
 =item B
 
 A cipher list to convert to a cipher preference list. If it is not included
 then the default cipher list will be used. The format is described below.
 
 =back
 
 =head1 CIPHER LIST FORMAT
 
 The cipher list consists of one or more I separated by colons.
 Commas or spaces are also acceptable separators but colons are normally used.
 
 The actual cipher string can take several different forms.
 
 It can consist of a single cipher suite such as B.
 
 It can represent a list of cipher suites containing a certain algorithm, or
 cipher suites of a certain type. For example B represents all ciphers
 suites using the digest algorithm SHA1 and B represents all SSL v3
 algorithms.
 
 Lists of cipher suites can be combined in a single cipher string using the
 B<+> character. This is used as a logical B operation. For example
 B represents all cipher suites containing the SHA1 B the DES
 algorithms.
 
 Each cipher string can be optionally preceded by the characters B,
 B<-> or B<+>.
 
 If B is used then the ciphers are permanently deleted from the list.
 The ciphers deleted can never reappear in the list even if they are
 explicitly stated.
 
 If B<-> is used then the ciphers are deleted from the list, but some or
 all of the ciphers can be added again by later options.
 
 If B<+> is used then the ciphers are moved to the end of the list. This
 option doesn't add any new ciphers it just moves matching existing ones.
 
 If none of these characters is present then the string is just interpreted
 as a list of ciphers to be appended to the current preference list. If the
 list includes any ciphers already present they will be ignored: that is they
 will not moved to the end of the list.
 
 Additionally the cipher string B<@STRENGTH> can be used at any point to sort
 the current cipher list in order of encryption algorithm key length.
 
 =head1 CIPHER STRINGS
 
 The following is a list of all permitted cipher strings and their meanings.
 
 =over 4
 
 =item B
 
 The default cipher list.
 This is determined at compile time and is normally
 B.
 When used, this must be the first cipherstring specified.
 
 =item B
 
 the ciphers included in B, but not enabled by default. Currently
 this is B and B. Note that this rule does not cover B,
 which is not included by B (use B if necessary).
 
 =item B
 
 all cipher suites except the B ciphers which must be explicitly enabled;
 as of OpenSSL, the B cipher suites are reasonably ordered by default
 
 =item B
 
 the cipher suites not enabled by B, currently being B.
 
 =item B
 
 "high" encryption cipher suites. This currently means those with key lengths larger
 than 128 bits, and some cipher suites with 128-bit keys.
 
 =item B
 
 "medium" encryption cipher suites, currently some of those using 128 bit encryption.
 
 =item B
 
 Low strength encryption cipher suites, currently those using 64 or 56 bit
 encryption algorithms but excluding export cipher suites.
 As of OpenSSL 1.0.2g, these are disabled in default builds.
 
 =item B, B
 
 Export strength encryption algorithms. Including 40 and 56 bits algorithms.
 As of OpenSSL 1.0.2g, these are disabled in default builds.
 
 =item B
 
 40-bit export encryption algorithms
 As of OpenSSL 1.0.2g, these are disabled in default builds.
 
 =item B
 
 56-bit export encryption algorithms. In OpenSSL 0.9.8c and later the set of
 56 bit export ciphers is empty unless OpenSSL has been explicitly configured
 with support for experimental ciphers.
 As of OpenSSL 1.0.2g, these are disabled in default builds.
 
 =item B, B
 
 The "NULL" ciphers that is those offering no encryption. Because these offer no
 encryption at all and are a security risk they are not enabled via either the
 B or B cipher strings.
 Be careful when building cipherlists out of lower-level primitives such as
 B or B as these do overlap with the B ciphers.
 When in doubt, include B in your cipherlist.
 
 =item B
 
 The cipher suites offering no authentication. This is currently the anonymous
 DH algorithms and anonymous ECDH algorithms. These cipher suites are vulnerable
 to a "man in the middle" attack and so their use is normally discouraged.
 These are excluded from the B ciphers, but included in the B
 ciphers.
 Be careful when building cipherlists out of lower-level primitives such as
 B or B as these do overlap with the B ciphers.
 When in doubt, include B in your cipherlist.
 
 =item B, B
 
-cipher suites using RSA key exchange.
+cipher suites using RSA key exchange or authentication. B is an alias for
+B.
 
 =item B, B, B
 
 cipher suites using DH key agreement and DH certificates signed by CAs with RSA
 and DSS keys or either respectively.
 
 =item B, B
 
 cipher suites using ephemeral DH key agreement, including anonymous cipher
 suites.
 
 =item B, B
 
 cipher suites using authenticated ephemeral DH key agreement.
 
 =item B
 
 anonymous DH cipher suites, note that this does not include anonymous Elliptic
 Curve DH (ECDH) cipher suites.
 
 =item B
 
 cipher suites using DH, including anonymous DH, ephemeral DH and fixed DH.
 
 =item B, B, B
 
 cipher suites using fixed ECDH key agreement signed by CAs with RSA and ECDSA
 keys or either respectively.
 
 =item B, B
 
 cipher suites using ephemeral ECDH key agreement, including anonymous
 cipher suites.
 
 =item B, B
 
 cipher suites using authenticated ephemeral ECDH key agreement.
 
 =item B
 
 anonymous Elliptic Curve Diffie Hellman cipher suites.
 
 =item B
 
 cipher suites using ECDH key exchange, including anonymous, ephemeral and
 fixed ECDH.
 
 =item B
 
 cipher suites using RSA authentication, i.e. the certificates carry RSA keys.
 
 =item B, B
 
 cipher suites using DSS authentication, i.e. the certificates carry DSS keys.
 
 =item B
 
 cipher suites effectively using DH authentication, i.e. the certificates carry
 DH keys.
 
 =item B
 
 cipher suites effectively using ECDH authentication, i.e. the certificates
 carry ECDH keys.
 
 =item B, B
 
 cipher suites using ECDSA authentication, i.e. the certificates carry ECDSA
 keys.
 
 =item B, B, B, B
 
 ciphers suites using FORTEZZA key exchange, authentication, encryption or all
 FORTEZZA algorithms. Not implemented.
 
 =item B, B, B, B
 
 TLS v1.2, TLS v1.0, SSL v3.0 or SSL v2.0 cipher suites respectively. Note:
 there are no ciphersuites specific to TLS v1.1.
 
 =item B, B, B
 
 cipher suites using 128 bit AES, 256 bit AES or either 128 or 256 bit AES.
 
 =item B
 
 AES in Galois Counter Mode (GCM): these ciphersuites are only supported
 in TLS v1.2.
 
 =item B, B, B
 
 cipher suites using 128 bit CAMELLIA, 256 bit CAMELLIA or either 128 or 256 bit
 CAMELLIA.
 
 =item B<3DES>
 
 cipher suites using triple DES.
 
 =item B
 
 cipher suites using DES (not triple DES).
 
 =item B
 
 cipher suites using RC4.
 
 =item B
 
 cipher suites using RC2.
 
 =item B
 
 cipher suites using IDEA.
 
 =item B
 
 cipher suites using SEED.
 
 =item B
 
 cipher suites using MD5.
 
 =item B, B
 
 cipher suites using SHA1.
 
 =item B, B
 
 ciphersuites using SHA256 or SHA384.
 
 =item B 
 
 cipher suites using GOST R 34.10 (either 2001 or 94) for authenticaction
 (needs an engine supporting GOST algorithms). 
 
 =item B
 
 cipher suites using GOST R 34.10-2001 authentication.
 
 =item B
 
 cipher suites using GOST R 34.10-94 authentication (note that R 34.10-94
 standard has been expired so use GOST R 34.10-2001)
 
 =item B
 
 cipher suites, using VKO 34.10 key exchange, specified in the RFC 4357.
 
 =item B
 
 cipher suites, using HMAC based on GOST R 34.11-94.
 
 =item B
 
 cipher suites using GOST 28147-89 MAC B HMAC.
 
 =item B
 
 cipher suites using pre-shared keys (PSK).
 
 =item B, B, B
 
 enables suite B mode operation using 128 (permitting 192 bit mode by peer)
 128 bit (not permitting 192 bit by peer) or 192 bit level of security
 respectively. If used these cipherstrings should appear first in the cipher
 list and anything after them is ignored. Setting Suite B mode has additional
 consequences required to comply with RFC6460. In particular the supported
 signature algorithms is reduced to support only ECDSA and SHA256 or SHA384,
 only the elliptic curves P-256 and P-384 can be used and only the two suite B
 compliant ciphersuites (ECDHE-ECDSA-AES128-GCM-SHA256 and
 ECDHE-ECDSA-AES256-GCM-SHA384) are permissible.
 
 =back
 
 =head1 CIPHER SUITE NAMES
 
 The following lists give the SSL or TLS cipher suites names from the
 relevant specification and their OpenSSL equivalents. It should be noted,
 that several cipher suite names do not include the authentication used,
 e.g. DES-CBC3-SHA. In these cases, RSA authentication is used.
 
 =head2 SSL v3.0 cipher suites.
 
  SSL_RSA_WITH_NULL_MD5                   NULL-MD5
  SSL_RSA_WITH_NULL_SHA                   NULL-SHA
  SSL_RSA_EXPORT_WITH_RC4_40_MD5          EXP-RC4-MD5
  SSL_RSA_WITH_RC4_128_MD5                RC4-MD5
  SSL_RSA_WITH_RC4_128_SHA                RC4-SHA
  SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5      EXP-RC2-CBC-MD5
  SSL_RSA_WITH_IDEA_CBC_SHA               IDEA-CBC-SHA
  SSL_RSA_EXPORT_WITH_DES40_CBC_SHA       EXP-DES-CBC-SHA
  SSL_RSA_WITH_DES_CBC_SHA                DES-CBC-SHA
  SSL_RSA_WITH_3DES_EDE_CBC_SHA           DES-CBC3-SHA
 
  SSL_DH_DSS_WITH_DES_CBC_SHA             DH-DSS-DES-CBC-SHA
  SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA        DH-DSS-DES-CBC3-SHA
  SSL_DH_RSA_WITH_DES_CBC_SHA             DH-RSA-DES-CBC-SHA
  SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA        DH-RSA-DES-CBC3-SHA
  SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA   EXP-EDH-DSS-DES-CBC-SHA
  SSL_DHE_DSS_WITH_DES_CBC_SHA            EDH-DSS-CBC-SHA
  SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA       EDH-DSS-DES-CBC3-SHA
  SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA   EXP-EDH-RSA-DES-CBC-SHA
  SSL_DHE_RSA_WITH_DES_CBC_SHA            EDH-RSA-DES-CBC-SHA
  SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA       EDH-RSA-DES-CBC3-SHA
 
  SSL_DH_anon_EXPORT_WITH_RC4_40_MD5      EXP-ADH-RC4-MD5
  SSL_DH_anon_WITH_RC4_128_MD5            ADH-RC4-MD5
  SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA   EXP-ADH-DES-CBC-SHA
  SSL_DH_anon_WITH_DES_CBC_SHA            ADH-DES-CBC-SHA
  SSL_DH_anon_WITH_3DES_EDE_CBC_SHA       ADH-DES-CBC3-SHA
 
  SSL_FORTEZZA_KEA_WITH_NULL_SHA          Not implemented.
  SSL_FORTEZZA_KEA_WITH_FORTEZZA_CBC_SHA  Not implemented.
  SSL_FORTEZZA_KEA_WITH_RC4_128_SHA       Not implemented.
 
 =head2 TLS v1.0 cipher suites.
 
  TLS_RSA_WITH_NULL_MD5                   NULL-MD5
  TLS_RSA_WITH_NULL_SHA                   NULL-SHA
  TLS_RSA_EXPORT_WITH_RC4_40_MD5          EXP-RC4-MD5
  TLS_RSA_WITH_RC4_128_MD5                RC4-MD5
  TLS_RSA_WITH_RC4_128_SHA                RC4-SHA
  TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5      EXP-RC2-CBC-MD5
  TLS_RSA_WITH_IDEA_CBC_SHA               IDEA-CBC-SHA
  TLS_RSA_EXPORT_WITH_DES40_CBC_SHA       EXP-DES-CBC-SHA
  TLS_RSA_WITH_DES_CBC_SHA                DES-CBC-SHA
  TLS_RSA_WITH_3DES_EDE_CBC_SHA           DES-CBC3-SHA
 
  TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA    Not implemented.
  TLS_DH_DSS_WITH_DES_CBC_SHA             Not implemented.
  TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA        Not implemented.
  TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA    Not implemented.
  TLS_DH_RSA_WITH_DES_CBC_SHA             Not implemented.
  TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA        Not implemented.
  TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA   EXP-EDH-DSS-DES-CBC-SHA
  TLS_DHE_DSS_WITH_DES_CBC_SHA            EDH-DSS-CBC-SHA
  TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA       EDH-DSS-DES-CBC3-SHA
  TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA   EXP-EDH-RSA-DES-CBC-SHA
  TLS_DHE_RSA_WITH_DES_CBC_SHA            EDH-RSA-DES-CBC-SHA
  TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA       EDH-RSA-DES-CBC3-SHA
 
  TLS_DH_anon_EXPORT_WITH_RC4_40_MD5      EXP-ADH-RC4-MD5
  TLS_DH_anon_WITH_RC4_128_MD5            ADH-RC4-MD5
  TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA   EXP-ADH-DES-CBC-SHA
  TLS_DH_anon_WITH_DES_CBC_SHA            ADH-DES-CBC-SHA
  TLS_DH_anon_WITH_3DES_EDE_CBC_SHA       ADH-DES-CBC3-SHA
 
 =head2 AES ciphersuites from RFC3268, extending TLS v1.0
 
  TLS_RSA_WITH_AES_128_CBC_SHA            AES128-SHA
  TLS_RSA_WITH_AES_256_CBC_SHA            AES256-SHA
 
  TLS_DH_DSS_WITH_AES_128_CBC_SHA         DH-DSS-AES128-SHA
  TLS_DH_DSS_WITH_AES_256_CBC_SHA         DH-DSS-AES256-SHA
  TLS_DH_RSA_WITH_AES_128_CBC_SHA         DH-RSA-AES128-SHA
  TLS_DH_RSA_WITH_AES_256_CBC_SHA         DH-RSA-AES256-SHA
 
  TLS_DHE_DSS_WITH_AES_128_CBC_SHA        DHE-DSS-AES128-SHA
  TLS_DHE_DSS_WITH_AES_256_CBC_SHA        DHE-DSS-AES256-SHA
  TLS_DHE_RSA_WITH_AES_128_CBC_SHA        DHE-RSA-AES128-SHA
  TLS_DHE_RSA_WITH_AES_256_CBC_SHA        DHE-RSA-AES256-SHA
 
  TLS_DH_anon_WITH_AES_128_CBC_SHA        ADH-AES128-SHA
  TLS_DH_anon_WITH_AES_256_CBC_SHA        ADH-AES256-SHA
 
 =head2 Camellia ciphersuites from RFC4132, extending TLS v1.0
 
  TLS_RSA_WITH_CAMELLIA_128_CBC_SHA      CAMELLIA128-SHA
  TLS_RSA_WITH_CAMELLIA_256_CBC_SHA      CAMELLIA256-SHA
 
  TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA   DH-DSS-CAMELLIA128-SHA
  TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA   DH-DSS-CAMELLIA256-SHA
  TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA   DH-RSA-CAMELLIA128-SHA
  TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA   DH-RSA-CAMELLIA256-SHA
 
  TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA  DHE-DSS-CAMELLIA128-SHA
  TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA  DHE-DSS-CAMELLIA256-SHA
  TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA  DHE-RSA-CAMELLIA128-SHA
  TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA  DHE-RSA-CAMELLIA256-SHA
 
  TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA  ADH-CAMELLIA128-SHA
  TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA  ADH-CAMELLIA256-SHA
 
 =head2 SEED ciphersuites from RFC4162, extending TLS v1.0
 
  TLS_RSA_WITH_SEED_CBC_SHA              SEED-SHA
 
  TLS_DH_DSS_WITH_SEED_CBC_SHA           DH-DSS-SEED-SHA
  TLS_DH_RSA_WITH_SEED_CBC_SHA           DH-RSA-SEED-SHA
 
  TLS_DHE_DSS_WITH_SEED_CBC_SHA          DHE-DSS-SEED-SHA
  TLS_DHE_RSA_WITH_SEED_CBC_SHA          DHE-RSA-SEED-SHA
 
  TLS_DH_anon_WITH_SEED_CBC_SHA          ADH-SEED-SHA
 
 =head2 GOST ciphersuites from draft-chudov-cryptopro-cptls, extending TLS v1.0
 
 Note: these ciphers require an engine which including GOST cryptographic
 algorithms, such as the B engine, included in the OpenSSL distribution.
 
  TLS_GOSTR341094_WITH_28147_CNT_IMIT GOST94-GOST89-GOST89
  TLS_GOSTR341001_WITH_28147_CNT_IMIT GOST2001-GOST89-GOST89
  TLS_GOSTR341094_WITH_NULL_GOSTR3411 GOST94-NULL-GOST94
  TLS_GOSTR341001_WITH_NULL_GOSTR3411 GOST2001-NULL-GOST94
 
 =head2 Additional Export 1024 and other cipher suites
 
 Note: these ciphers can also be used in SSL v3.
 
  TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA     EXP1024-DES-CBC-SHA
  TLS_RSA_EXPORT1024_WITH_RC4_56_SHA      EXP1024-RC4-SHA
  TLS_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA EXP1024-DHE-DSS-DES-CBC-SHA
  TLS_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA  EXP1024-DHE-DSS-RC4-SHA
  TLS_DHE_DSS_WITH_RC4_128_SHA            DHE-DSS-RC4-SHA
 
 =head2 Elliptic curve cipher suites.
 
  TLS_ECDH_RSA_WITH_NULL_SHA              ECDH-RSA-NULL-SHA
  TLS_ECDH_RSA_WITH_RC4_128_SHA           ECDH-RSA-RC4-SHA
  TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA      ECDH-RSA-DES-CBC3-SHA
  TLS_ECDH_RSA_WITH_AES_128_CBC_SHA       ECDH-RSA-AES128-SHA
  TLS_ECDH_RSA_WITH_AES_256_CBC_SHA       ECDH-RSA-AES256-SHA
 
  TLS_ECDH_ECDSA_WITH_NULL_SHA            ECDH-ECDSA-NULL-SHA
  TLS_ECDH_ECDSA_WITH_RC4_128_SHA         ECDH-ECDSA-RC4-SHA
  TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA    ECDH-ECDSA-DES-CBC3-SHA
  TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA     ECDH-ECDSA-AES128-SHA
  TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA     ECDH-ECDSA-AES256-SHA
 
  TLS_ECDHE_RSA_WITH_NULL_SHA             ECDHE-RSA-NULL-SHA
  TLS_ECDHE_RSA_WITH_RC4_128_SHA          ECDHE-RSA-RC4-SHA
  TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA     ECDHE-RSA-DES-CBC3-SHA
  TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA      ECDHE-RSA-AES128-SHA
  TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA      ECDHE-RSA-AES256-SHA
 
  TLS_ECDHE_ECDSA_WITH_NULL_SHA           ECDHE-ECDSA-NULL-SHA
  TLS_ECDHE_ECDSA_WITH_RC4_128_SHA        ECDHE-ECDSA-RC4-SHA
  TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA   ECDHE-ECDSA-DES-CBC3-SHA
  TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA    ECDHE-ECDSA-AES128-SHA
  TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA    ECDHE-ECDSA-AES256-SHA
 
  TLS_ECDH_anon_WITH_NULL_SHA             AECDH-NULL-SHA
  TLS_ECDH_anon_WITH_RC4_128_SHA          AECDH-RC4-SHA
  TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA     AECDH-DES-CBC3-SHA
  TLS_ECDH_anon_WITH_AES_128_CBC_SHA      AECDH-AES128-SHA
  TLS_ECDH_anon_WITH_AES_256_CBC_SHA      AECDH-AES256-SHA
 
 =head2 TLS v1.2 cipher suites
 
  TLS_RSA_WITH_NULL_SHA256                  NULL-SHA256
 
  TLS_RSA_WITH_AES_128_CBC_SHA256           AES128-SHA256
  TLS_RSA_WITH_AES_256_CBC_SHA256           AES256-SHA256
  TLS_RSA_WITH_AES_128_GCM_SHA256           AES128-GCM-SHA256
  TLS_RSA_WITH_AES_256_GCM_SHA384           AES256-GCM-SHA384
 
  TLS_DH_RSA_WITH_AES_128_CBC_SHA256        DH-RSA-AES128-SHA256
  TLS_DH_RSA_WITH_AES_256_CBC_SHA256        DH-RSA-AES256-SHA256
  TLS_DH_RSA_WITH_AES_128_GCM_SHA256        DH-RSA-AES128-GCM-SHA256
  TLS_DH_RSA_WITH_AES_256_GCM_SHA384        DH-RSA-AES256-GCM-SHA384
 
  TLS_DH_DSS_WITH_AES_128_CBC_SHA256        DH-DSS-AES128-SHA256
  TLS_DH_DSS_WITH_AES_256_CBC_SHA256        DH-DSS-AES256-SHA256
  TLS_DH_DSS_WITH_AES_128_GCM_SHA256        DH-DSS-AES128-GCM-SHA256
  TLS_DH_DSS_WITH_AES_256_GCM_SHA384        DH-DSS-AES256-GCM-SHA384
 
  TLS_DHE_RSA_WITH_AES_128_CBC_SHA256       DHE-RSA-AES128-SHA256
  TLS_DHE_RSA_WITH_AES_256_CBC_SHA256       DHE-RSA-AES256-SHA256
  TLS_DHE_RSA_WITH_AES_128_GCM_SHA256       DHE-RSA-AES128-GCM-SHA256
  TLS_DHE_RSA_WITH_AES_256_GCM_SHA384       DHE-RSA-AES256-GCM-SHA384
 
  TLS_DHE_DSS_WITH_AES_128_CBC_SHA256       DHE-DSS-AES128-SHA256
  TLS_DHE_DSS_WITH_AES_256_CBC_SHA256       DHE-DSS-AES256-SHA256
  TLS_DHE_DSS_WITH_AES_128_GCM_SHA256       DHE-DSS-AES128-GCM-SHA256
  TLS_DHE_DSS_WITH_AES_256_GCM_SHA384       DHE-DSS-AES256-GCM-SHA384
 
  TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256      ECDH-RSA-AES128-SHA256
  TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384      ECDH-RSA-AES256-SHA384
  TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256      ECDH-RSA-AES128-GCM-SHA256
  TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384      ECDH-RSA-AES256-GCM-SHA384
 
  TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256    ECDH-ECDSA-AES128-SHA256
  TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384    ECDH-ECDSA-AES256-SHA384
  TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256    ECDH-ECDSA-AES128-GCM-SHA256
  TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384    ECDH-ECDSA-AES256-GCM-SHA384
 
  TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256     ECDHE-RSA-AES128-SHA256
  TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384     ECDHE-RSA-AES256-SHA384
  TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256     ECDHE-RSA-AES128-GCM-SHA256
  TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384     ECDHE-RSA-AES256-GCM-SHA384
 
  TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256   ECDHE-ECDSA-AES128-SHA256
  TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384   ECDHE-ECDSA-AES256-SHA384
  TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256   ECDHE-ECDSA-AES128-GCM-SHA256
  TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384   ECDHE-ECDSA-AES256-GCM-SHA384
 
  TLS_DH_anon_WITH_AES_128_CBC_SHA256       ADH-AES128-SHA256
  TLS_DH_anon_WITH_AES_256_CBC_SHA256       ADH-AES256-SHA256
  TLS_DH_anon_WITH_AES_128_GCM_SHA256       ADH-AES128-GCM-SHA256
  TLS_DH_anon_WITH_AES_256_GCM_SHA384       ADH-AES256-GCM-SHA384
 
 =head2 Pre shared keying (PSK) cipheruites
 
  TLS_PSK_WITH_RC4_128_SHA                  PSK-RC4-SHA
  TLS_PSK_WITH_3DES_EDE_CBC_SHA             PSK-3DES-EDE-CBC-SHA
  TLS_PSK_WITH_AES_128_CBC_SHA              PSK-AES128-CBC-SHA
  TLS_PSK_WITH_AES_256_CBC_SHA              PSK-AES256-CBC-SHA
 
 =head2 Deprecated SSL v2.0 cipher suites.
 
  SSL_CK_RC4_128_WITH_MD5                 RC4-MD5
  SSL_CK_RC4_128_EXPORT40_WITH_MD5        Not implemented.
  SSL_CK_RC2_128_CBC_WITH_MD5             RC2-CBC-MD5
  SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5    Not implemented.
  SSL_CK_IDEA_128_CBC_WITH_MD5            IDEA-CBC-MD5
  SSL_CK_DES_64_CBC_WITH_MD5              Not implemented.
  SSL_CK_DES_192_EDE3_CBC_WITH_MD5        DES-CBC3-MD5
 
 =head1 NOTES
 
 Some compiled versions of OpenSSL may not include all the ciphers
 listed here because some ciphers were excluded at compile time.
 
 =head1 EXAMPLES
 
 Verbose listing of all OpenSSL ciphers including NULL ciphers:
 
  openssl ciphers -v 'ALL:eNULL'
 
 Include all ciphers except NULL and anonymous DH then sort by
 strength:
 
  openssl ciphers -v 'ALL:!ADH:@STRENGTH'
 
 Include all ciphers except ones with no encryption (eNULL) or no
 authentication (aNULL):
 
  openssl ciphers -v 'ALL:!aNULL'
 
 Include only 3DES ciphers and then place RSA ciphers last:
 
  openssl ciphers -v '3DES:+RSA'
 
 Include all RC4 ciphers but leave out those without authentication:
 
  openssl ciphers -v 'RC4:!COMPLEMENTOFDEFAULT'
 
 Include all chiphers with RSA authentication but leave out ciphers without
 encryption.
 
  openssl ciphers -v 'RSA:!COMPLEMENTOFALL'
 
 =head1 SEE ALSO
 
 L, L, L
 
 =head1 HISTORY
 
 The B and B selection options
 for cipherlist strings were added in OpenSSL 0.9.7.
 The B<-V> option for the B command was added in OpenSSL 1.0.0.
 
 =cut
Index: vendor-crypto/openssl/dist/doc/apps/config.pod
===================================================================
--- vendor-crypto/openssl/dist/doc/apps/config.pod	(revision 318896)
+++ vendor-crypto/openssl/dist/doc/apps/config.pod	(revision 318897)
@@ -1,350 +1,351 @@
 
 =pod
 
 =for comment openssl_manual_section:5
 
 =head1 NAME
 
 config - OpenSSL CONF library configuration files
 
 =head1 DESCRIPTION
 
 The OpenSSL CONF library can be used to read configuration files.
 It is used for the OpenSSL master configuration file B
 and in a few other places like B files and certificate extension
 files for the B utility. OpenSSL applications can also use the
 CONF library for their own purposes.
 
 A configuration file is divided into a number of sections. Each section
 starts with a line B<[ section_name ]> and ends when a new section is
 started or end of file is reached. A section name can consist of
 alphanumeric characters and underscores.
 
 The first section of a configuration file is special and is referred
 to as the B section this is usually unnamed and is from the
 start of file until the first named section. When a name is being looked up
 it is first looked up in a named section (if any) and then the
 default section.
 
 The environment is mapped onto a section called B.
 
 Comments can be included by preceding them with the B<#> character
 
 Each section in a configuration file consists of a number of name and
 value pairs of the form B
 
 The B string can contain any alphanumeric characters as well as
 a few punctuation symbols such as B<.> B<,> B<;> and B<_>.
 
 The B string consists of the string following the B<=> character
 until end of line with any leading and trailing white space removed.
 
 The value string undergoes variable expansion. This can be done by
 including the form B<$var> or B<${var}>: this will substitute the value
 of the named variable in the current section. It is also possible to
 substitute a value from another section using the syntax B<$section::name>
 or B<${section::name}>. By using the form B<$ENV::name> environment
 variables can be substituted. It is also possible to assign values to
 environment variables by using the name B, this will work
 if the program looks up environment variables using the B library
-instead of calling B directly.
+instead of calling B directly. The value string must not exceed 64k in
+length after variable expansion. Otherwise an error will occur.
 
 It is possible to escape certain characters by using any kind of quote
 or the B<\> character. By making the last character of a line a B<\>
 a B string can be spread across multiple lines. In addition
 the sequences B<\n>, B<\r>, B<\b> and B<\t> are recognized.
 
 =head1 OPENSSL LIBRARY CONFIGURATION
 
 In OpenSSL 0.9.7 and later applications can automatically configure certain
 aspects of OpenSSL using the master OpenSSL configuration file, or optionally
 an alternative configuration file. The B utility includes this
 functionality: any sub command uses the master OpenSSL configuration file
 unless an option is used in the sub command to use an alternative configuration
 file.
 
 To enable library configuration the default section needs to contain an 
 appropriate line which points to the main configuration section. The default
 name is B which is used by the B utility. Other
 applications may use an alternative name such as B.
 
 The configuration section should consist of a set of name value pairs which
 contain specific module configuration information. The B represents
 the name of the I the meaning of the B is 
 module specific: it may, for example, represent a further configuration
 section containing configuration module specific information. E.g.
 
  openssl_conf = openssl_init
 
  [openssl_init]
 
  oid_section = new_oids
  engines = engine_section
 
  [new_oids]
 
  ... new oids here ...
 
  [engine_section]
 
  ... engine stuff here ...
 
 The features of each configuration module are described below.
 
 =head2 ASN1 OBJECT CONFIGURATION MODULE
 
 This module has the name B. The value of this variable points
 to a section containing name value pairs of OIDs: the name is the OID short
 and long name, the value is the numerical form of the OID. Although some of
 the B utility sub commands already have their own ASN1 OBJECT section
 functionality not all do. By using the ASN1 OBJECT configuration module
 B the B utility sub commands can see the new objects as well
 as any compliant applications. For example:
 
  [new_oids]
  
  some_new_oid = 1.2.3.4
  some_other_oid = 1.2.3.5
 
 In OpenSSL 0.9.8 it is also possible to set the value to the long name followed
 by a comma and the numerical OID form. For example:
 
  shortName = some object long name, 1.2.3.4
 
 =head2 ENGINE CONFIGURATION MODULE
 
 This ENGINE configuration module has the name B. The value of this
 variable points to a section containing further ENGINE configuration
 information.
 
 The section pointed to by B is a table of engine names (though see
 B below) and further sections containing configuration information
 specific to each ENGINE.
 
 Each ENGINE specific section is used to set default algorithms, load
 dynamic, perform initialization and send ctrls. The actual operation performed
 depends on the I name which is the name of the name value pair. The
 currently supported commands are listed below.
 
 For example:
 
  [engine_section]
 
  # Configure ENGINE named "foo"
  foo = foo_section
  # Configure ENGINE named "bar"
  bar = bar_section
 
  [foo_section]
  ... foo ENGINE specific commands ...
 
  [bar_section]
  ... "bar" ENGINE specific commands ...
 
 The command B is used to give the ENGINE name. If used this 
 command must be first. For example:
 
  [engine_section]
  # This would normally handle an ENGINE named "foo"
  foo = foo_section
 
  [foo_section]
  # Override default name and use "myfoo" instead.
  engine_id = myfoo
 
 The command B loads and adds an ENGINE from the given path. It
 is equivalent to sending the ctrls B with the path argument followed
 by B with value 2 and B to the dynamic ENGINE. If this is
 not the required behaviour then alternative ctrls can be sent directly
 to the dynamic ENGINE using ctrl commands.
 
 The command B determines whether to initialize the ENGINE. If the value
 is B<0> the ENGINE will not be initialized, if B<1> and attempt it made to
 initialized the ENGINE immediately. If the B command is not present
 then an attempt will be made to initialize the ENGINE after all commands in
 its section have been processed.
 
 The command B sets the default algorithms an ENGINE will
 supply using the functions B
 
 If the name matches none of the above command names it is assumed to be a
 ctrl command which is sent to the ENGINE. The value of the command is the 
 argument to the ctrl command. If the value is the string B then no
 value is sent to the command.
 
 For example:
 
 
  [engine_section]
 
  # Configure ENGINE named "foo"
  foo = foo_section
 
  [foo_section]
  # Load engine from DSO
  dynamic_path = /some/path/fooengine.so
  # A foo specific ctrl.
  some_ctrl = some_value
  # Another ctrl that doesn't take a value.
  other_ctrl = EMPTY
  # Supply all default algorithms
  default_algorithms = ALL
 
 =head2 EVP CONFIGURATION MODULE
 
 This modules has the name B which points to a section containing
 algorithm commands.
 
 Currently the only algorithm command supported is B whose
 value should be a boolean string such as B or B. If the value is
 B this attempt to enter FIPS mode. If the call fails or the library is
 not FIPS capable then an error occurs.
 
 For example:
 
  alg_section = evp_settings
 
  [evp_settings]
 
  fips_mode = on
 
 
 =head1 NOTES
 
 If a configuration file attempts to expand a variable that doesn't exist
 then an error is flagged and the file will not load. This can happen
 if an attempt is made to expand an environment variable that doesn't
 exist. For example in a previous version of OpenSSL the default OpenSSL
 master configuration file used the value of B which may not be
 defined on non Unix systems and would cause an error.
 
 This can be worked around by including a B section to provide
 a default value: then if the environment lookup fails the default value
 will be used instead. For this to work properly the default value must
 be defined earlier in the configuration file than the expansion. See
 the B section for an example of how to do this.
 
 If the same variable exists in the same section then all but the last
 value will be silently ignored. In certain circumstances such as with
 DNs the same field may occur multiple times. This is usually worked
 around by ignoring any characters before an initial B<.> e.g.
 
  1.OU="My first OU"
  2.OU="My Second OU"
 
 =head1 EXAMPLES
 
 Here is a sample configuration file using some of the features
 mentioned above.
 
  # This is the default section.
  
  HOME=/temp
  RANDFILE= ${ENV::HOME}/.rnd
  configdir=$ENV::HOME/config
 
  [ section_one ]
 
  # We are now in section one.
 
  # Quotes permit leading and trailing whitespace
  any = " any variable name "
 
  other = A string that can \
  cover several lines \
  by including \\ characters
 
  message = Hello World\n
 
  [ section_two ]
 
  greeting = $section_one::message
 
 This next example shows how to expand environment variables safely.
 
 Suppose you want a variable called B to refer to a
 temporary filename. The directory it is placed in can determined by
 the the B or B environment variables but they may not be
 set to any value at all. If you just include the environment variable
 names and the variable doesn't exist then this will cause an error when
 an attempt is made to load the configuration file. By making use of the
 default section both values can be looked up with B taking 
 priority and B used if neither is defined:
 
  TMP=/tmp
  # The above value is used if TMP isn't in the environment
  TEMP=$ENV::TMP
  # The above value is used if TEMP isn't in the environment
  tmpfile=${ENV::TEMP}/tmp.filename
 
 Simple OpenSSL library configuration example to enter FIPS mode:
 
  # Default appname: should match "appname" parameter (if any)
  # supplied to CONF_modules_load_file et al.
  openssl_conf = openssl_conf_section
 
  [openssl_conf_section]
  # Configuration module list
  alg_section = evp_sect
 
  [evp_sect]
  # Set to "yes" to enter FIPS mode if supported
  fips_mode = yes
 
 Note: in the above example you will get an error in non FIPS capable versions
 of OpenSSL.
 
 More complex OpenSSL library configuration. Add OID and don't enter FIPS mode:
 
  # Default appname: should match "appname" parameter (if any)
  # supplied to CONF_modules_load_file et al.
  openssl_conf = openssl_conf_section
 
  [openssl_conf_section]
  # Configuration module list
  alg_section = evp_sect
  oid_section = new_oids
 
  [evp_sect]
  # This will have no effect as FIPS mode is off by default.
  # Set to "yes" to enter FIPS mode, if supported
  fips_mode = no
 
  [new_oids]
  # New OID, just short name
  newoid1 = 1.2.3.4.1
  # New OID shortname and long name
  newoid2 = New OID 2 long name, 1.2.3.4.2
 
 The above examples can be used with with any application supporting library
 configuration if "openssl_conf" is modified to match the appropriate "appname".
 
 For example if the second sample file above is saved to "example.cnf" then
 the command line:
 
  OPENSSL_CONF=example.cnf openssl asn1parse -genstr OID:1.2.3.4.1
 
 will output:
 
     0:d=0  hl=2 l=   4 prim: OBJECT            :newoid1
 
 showing that the OID "newoid1" has been added as "1.2.3.4.1".
 
 =head1 BUGS
 
 Currently there is no way to include characters using the octal B<\nnn>
 form. Strings are all null terminated so nulls cannot form part of
 the value.
 
 The escaping isn't quite right: if you want to use sequences like B<\n>
 you can't use any quote escaping on the same line.
 
 Files are loaded in a single pass. This means that an variable expansion
 will only work if the variables referenced are defined earlier in the
 file.
 
 =head1 SEE ALSO
 
 L, L, L
 
 =cut
Index: vendor-crypto/openssl/dist/doc/apps/genrsa.pod
===================================================================
--- vendor-crypto/openssl/dist/doc/apps/genrsa.pod	(revision 318896)
+++ vendor-crypto/openssl/dist/doc/apps/genrsa.pod	(revision 318897)
@@ -1,102 +1,118 @@
 =pod
 
 =head1 NAME
 
 genrsa - generate an RSA private key
 
 =head1 SYNOPSIS
 
 B B
+[B<-help>]
 [B<-out filename>]
 [B<-passout arg>]
 [B<-aes128>]
 [B<-aes192>]
 [B<-aes256>]
+[B<-aria128>]
+[B<-aria192>]
+[B<-aria256>]
 [B<-camellia128>]
 [B<-camellia192>]
 [B<-camellia256>]
 [B<-des>]
 [B<-des3>]
 [B<-idea>]
 [B<-f4>]
 [B<-3>]
 [B<-rand file(s)>]
 [B<-engine id>]
 [B]
 
 =head1 DESCRIPTION
 
 The B command generates an RSA private key.
 
 =head1 OPTIONS
 
 =over 4
 
+=item B<-help>
+
+Print out a usage message.
+
 =item B<-out filename>
 
-the output filename. If this argument is not specified then standard output is
-used.  
+Output the key to the specified file. If this argument is not specified then
+standard output is used.
 
 =item B<-passout arg>
 
 the output file password source. For more information about the format of B
-see the B section in L.
+see the B section in L.
 
-=item B<-aes128|-aes192|-aes256|-camellia128|-camellia192|-camellia256|-des|-des3|-idea>
+=item B<-aes128|-aes192|-aes256|-aria128|-aria192|-aria256|-camellia128|-camellia192|-camellia256|-des|-des3|-idea>
 
 These options encrypt the private key with specified
 cipher before outputting it. If none of these options is
 specified no encryption is used. If encryption is used a pass phrase is prompted
 for if it is not supplied via the B<-passout> argument.
 
 =item B<-F4|-3>
 
 the public exponent to use, either 65537 or 3. The default is 65537.
 
 =item B<-rand file(s)>
 
 a file or files containing random data used to seed the random number
-generator, or an EGD socket (see L).
-Multiple files can be specified separated by a OS-dependent character.
+generator, or an EGD socket (see L).
+Multiple files can be specified separated by an OS-dependent character.
 The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for
 all others.
 
 =item B<-engine id>
 
 specifying an engine (by its unique B string) will cause B
 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.
 
 =item B
 
 the size of the private key to generate in bits. This must be the last option
-specified. The default is 512.
+specified. The default is 2048.
 
 =back
 
 =head1 NOTES
 
 RSA private key generation essentially involves the generation of two prime
 numbers. When generating a private key various symbols will be output to
 indicate the progress of the generation. A B<.> represents each number which
 has passed an initial sieve test, B<+> means a number has passed a single
 round of the Miller-Rabin primality test. A newline means that the number has
 passed all the prime tests (the actual number depends on the key size).
 
 Because key generation is a random process the time taken to generate a key
 may vary somewhat.
 
 =head1 BUGS
 
 A quirk of the prime generation algorithm is that it cannot generate small
 primes. Therefore the number of bits should not be less that 64. For typical
 private keys this will not matter because for security reasons they will
 be much larger (typically 1024 bits).
 
 =head1 SEE ALSO
 
-L
+L
 
-=cut
+=head1 COPYRIGHT
 
+Copyright 2000-2017 The OpenSSL Project Authors. All Rights Reserved.
+
+Licensed under the OpenSSL license (the "License").  You may not use
+this file except in compliance with the License.  You can obtain a copy
+in the file LICENSE in the source distribution or at
+L.
+
+=cut
Index: vendor-crypto/openssl/dist/doc/apps/req.pod
===================================================================
--- vendor-crypto/openssl/dist/doc/apps/req.pod	(revision 318896)
+++ vendor-crypto/openssl/dist/doc/apps/req.pod	(revision 318897)
@@ -1,680 +1,683 @@
 
 =pod
 
 =head1 NAME
 
 req - PKCS#10 certificate request and certificate generating utility.
 
 =head1 SYNOPSIS
 
 B B
 [B<-inform PEM|DER>]
 [B<-outform PEM|DER>]
 [B<-in filename>]
 [B<-passin arg>]
 [B<-out filename>]
 [B<-passout arg>]
 [B<-text>]
 [B<-pubkey>]
 [B<-noout>]
 [B<-verify>]
 [B<-modulus>]
 [B<-new>]
 [B<-rand file(s)>]
 [B<-newkey rsa:bits>]
 [B<-newkey alg:file>]
 [B<-nodes>]
 [B<-key filename>]
 [B<-keyform PEM|DER>]
 [B<-keyout filename>]
 [B<-keygen_engine id>]
 [B<-[digest]>]
 [B<-config filename>]
 [B<-multivalue-rdn>]
 [B<-x509>]
 [B<-days n>]
 [B<-set_serial n>]
 [B<-asn1-kludge>]
 [B<-no-asn1-kludge>]
 [B<-newhdr>]
 [B<-extensions section>]
 [B<-reqexts section>]
 [B<-utf8>]
 [B<-nameopt>]
 [B<-reqopt>]
 [B<-subject>]
 [B<-subj arg>]
 [B<-batch>]
 [B<-verbose>]
 [B<-engine id>]
 
 =head1 DESCRIPTION
 
 The B command primarily creates and processes certificate requests
 in PKCS#10 format. It can additionally create self signed certificates
 for use as root CAs for example.
 
 =head1 COMMAND OPTIONS
 
 =over 4
 
 =item B<-inform DER|PEM>
 
 This specifies the input format. The B option uses an ASN1 DER encoded
 form compatible with the PKCS#10. The B form is the default format: it
 consists of the B format base64 encoded with additional header and
 footer lines.
 
 =item B<-outform DER|PEM>
 
 This specifies the output format, the options have the same meaning as the 
 B<-inform> option.
 
 =item B<-in filename>
 
 This specifies the input filename to read a request from or standard input
 if this option is not specified. A request is only read if the creation
 options (B<-new> and B<-newkey>) are not specified.
 
 =item B<-passin arg>
 
 the input file password source. For more information about the format of B
 see the B section in L.
 
 =item B<-out filename>
 
 This specifies the output filename to write to or standard output by
 default.
 
 =item B<-passout arg>
 
 the output file password source. For more information about the format of B
 see the B section in L.
 
 =item B<-text>
 
 prints out the certificate request in text form.
 
 =item B<-subject>
 
 prints out the request subject (or certificate subject if B<-x509> is
 specified)
 
 =item B<-pubkey>
 
 outputs the public key.
 
 =item B<-noout>
 
 this option prevents output of the encoded version of the request.
 
 =item B<-modulus>
 
 this option prints out the value of the modulus of the public key
 contained in the request.
 
 =item B<-verify>
 
 verifies the signature on the request.
 
 =item B<-new>
 
 this option generates a new certificate request. It will prompt
 the user for the relevant field values. The actual fields
 prompted for and their maximum and minimum sizes are specified
 in the configuration file and any requested extensions.
 
 If the B<-key> option is not used it will generate a new RSA private
 key using information specified in the configuration file.
 
 =item B<-subj arg>
 
 Replaces subject field of input request with specified data and outputs
 modified request. The arg must be formatted as
 I,
 characters may be escaped by \ (backslash), no spaces are skipped.
 
 =item B<-rand file(s)>
 
 a file or files containing random data used to seed the random number
 generator, or an EGD socket (see L).
 Multiple files can be specified separated by a OS-dependent character.
 The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for
 all others.
 
 =item B<-newkey arg>
 
 this option creates a new certificate request and a new private
 key. The argument takes one of several forms. B, where
 B is the number of bits, generates an RSA key B
 in size. If B is omitted, i.e. B<-newkey rsa> specified,
 the default key size, specified in the configuration file is used.
 
 All other algorithms support the B<-newkey alg:file> form, where file may be
 an algorithm parameter file, created by the B command
 or and X.509 certificate for a key with approriate algorithm.
 
 B generates a key using the parameter file or certificate B,
 the algorithm is determined by the parameters. B use algorithm
 B and parameter file B: the two algorithms must match or an
 error occurs. B just uses algorithm B, and parameters,
 if neccessary should be specified via B<-pkeyopt> parameter.
 
 B generates a DSA key using the parameters
 in the file B. B generates EC key (usable both with
 ECDSA or ECDH algorithms), B generates GOST R
 34.10-2001 key (requires B engine configured in the configuration
 file). If just B is specified a parameter set should be
 specified by B<-pkeyopt paramset:X>
 
 
 =item B<-pkeyopt opt:value>
 
 set the public key algorithm option B to B. The precise set of
 options supported depends on the public key algorithm used and its
 implementation. See B in the B manual page
 for more details.
 
 =item B<-key filename>
 
 This specifies the file to read the private key from. It also
 accepts PKCS#8 format private keys for PEM format files.
 
 =item B<-keyform PEM|DER>
 
 the format of the private key file specified in the B<-key>
 argument. PEM is the default.
 
 =item B<-keyout filename>
 
 this gives the filename to write the newly created private key to.
 If this option is not specified then the filename present in the
 configuration file is used.
 
 =item B<-nodes>
 
 if this option is specified then if a private key is created it
 will not be encrypted.
 
 =item B<-[digest]>
 
 this specifies the message digest to sign the request with (such as
 B<-md5>, B<-sha1>). This overrides the digest algorithm specified in
 the configuration file.
 
 Some public key algorithms may override this choice. For instance, DSA
 signatures always use SHA1, GOST R 34.10 signatures always use
 GOST R 34.11-94 (B<-md_gost94>).
 
 =item B<-config filename>
 
 this allows an alternative configuration file to be specified,
 this overrides the compile time filename or any specified in
 the B environment variable.
 
 =item B<-subj arg>
 
 sets subject name for new request or supersedes the subject name
 when processing a request.
 The arg must be formatted as I,
 characters may be escaped by \ (backslash), no spaces are skipped.
 
 =item B<-multivalue-rdn>
 
 this option causes the -subj argument to be interpreted with full
 support for multivalued RDNs. Example:
 
 I
 
 If -multi-rdn is not used then the UID value is I<123456+CN=John Doe>.
 
 =item B<-x509>
 
 this option outputs a self signed certificate instead of a certificate
 request. This is typically used to generate a test certificate or
 a self signed root CA. The extensions added to the certificate
 (if any) are specified in the configuration file. Unless specified
 using the B option, a large random number will be used for
 the serial number.
 
+If existing request is specified with the B<-in> option, it is converted
+to the self signed certificate otherwise new request is created.
+
 =item B<-days n>
 
 when the B<-x509> option is being used this specifies the number of
 days to certify the certificate for. The default is 30 days.
 
 =item B<-set_serial n>
 
 serial number to use when outputting a self signed certificate. This
 may be specified as a decimal value or a hex value if preceded by B<0x>.
 It is possible to use negative serial numbers but this is not recommended.
 
 =item B<-extensions section>
 
 =item B<-reqexts section>
 
 these options specify alternative sections to include certificate
 extensions (if the B<-x509> option is present) or certificate
 request extensions. This allows several different sections to
 be used in the same configuration file to specify requests for
 a variety of purposes.
 
 =item B<-utf8>
 
 this option causes field values to be interpreted as UTF8 strings, by 
 default they are interpreted as ASCII. This means that the field
 values, whether prompted from a terminal or obtained from a
 configuration file, must be valid UTF8 strings.
 
 =item B<-nameopt option>
 
 option which determines how the subject or issuer names are displayed. The
 B