Index: vendor-crypto/openssl/dist/CHANGES =================================================================== --- vendor-crypto/openssl/dist/CHANGES (revision 325325) +++ vendor-crypto/openssl/dist/CHANGES (revision 325326) @@ -1,11450 +1,11488 @@ OpenSSL CHANGES _______________ + This is a high-level summary of the most important changes. + For a full list of changes, see the git commit log; for example, + https://github.com/openssl/openssl/commits/ and pick the appropriate + release branch. + + Changes between 1.0.2l and 1.0.2m [2 Nov 2017] + + *) bn_sqrx8x_internal carry bug 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. + + This only affects processors that support the BMI1, BMI2 and ADX extensions + like Intel Broadwell (5th generation) and later or AMD Ryzen. + + This issue was reported to OpenSSL by the OSS-Fuzz project. + (CVE-2017-3736) + [Andy Polyakov] + + *) Malformed X.509 IPAddressFamily could cause OOB read + + If an X.509 certificate has a malformed IPAddressFamily extension, + OpenSSL could do a one-byte buffer overread. The most likely result + would be an erroneous display of the certificate in text format. + + This issue was reported to OpenSSL by the OSS-Fuzz project. + (CVE-2017-3735) + [Rich Salz] + 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/FREEBSD-upgrade =================================================================== --- vendor-crypto/openssl/dist/FREEBSD-upgrade (revision 325325) +++ vendor-crypto/openssl/dist/FREEBSD-upgrade (revision 325326) @@ -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.2l -# OSSLTAG format: v1_0_2l +setenv OSSLVER 1.0.2m +# OSSLTAG format: v1_0_2m ###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/INSTALL =================================================================== --- vendor-crypto/openssl/dist/INSTALL (revision 325325) +++ vendor-crypto/openssl/dist/INSTALL (revision 325326) @@ -1,367 +1,365 @@ INSTALLATION ON THE UNIX PLATFORM --------------------------------- [Installation on DOS (with djgpp), Windows, OpenVMS, MacOS (before MacOS X) and NetWare is described in INSTALL.DJGPP, INSTALL.W32, INSTALL.VMS, INSTALL.MacOS and INSTALL.NW. This document describes installation on operating systems in the Unix family.] To install OpenSSL, you will need: * make * Perl 5 * an ANSI C compiler * a development environment in form of development libraries and C header files * a supported Unix operating system Quick Start ----------- If you want to just get on with it, do: $ ./config $ make $ make test $ make install [If any of these steps fails, see section Installation in Detail below.] This will build and install OpenSSL in the default location, which is (for historical reasons) /usr/local/ssl. If you want to install it anywhere else, run config like this: $ ./config --prefix=/usr/local --openssldir=/usr/local/openssl Configuration Options --------------------- There are several options to ./config (or ./Configure) to customize the build: --prefix=DIR Install in DIR/bin, DIR/lib, DIR/include/openssl. Configuration files used by OpenSSL will be in DIR/ssl or the directory specified by --openssldir. --openssldir=DIR Directory for OpenSSL files. If no prefix is specified, the library files and binaries are also installed there. no-threads Don't try to build with support for multi-threaded applications. threads Build with support for multi-threaded applications. This will usually require additional system-dependent options! See "Note on multi-threading" below. no-zlib Don't try to build with support for zlib compression and decompression. zlib Build with support for zlib compression/decompression. zlib-dynamic Like "zlib", but has OpenSSL load the zlib library dynamically when needed. This is only supported on systems where loading of shared libraries is supported. This is the default choice. no-shared Don't try to create shared libraries. shared In addition to the usual static libraries, create shared libraries on platforms where it's supported. See "Note on shared libraries" below. no-asm Do not use assembler code. 386 In 32-bit x86 builds, when generating assembly modules, use the 80386 instruction set only (the default x86 code is more efficient, but requires at least a 486). Note: This doesn't affect code generated by compiler, you're likely to complement configuration command line with suitable compiler-specific option. no-sse2 Exclude SSE2 code paths from 32-bit x86 assembly modules. Normally SSE2 extension is detected at run-time, but the decision whether or not the machine code will be executed is taken solely on CPU capability vector. This means that if you happen to run OS kernel which does not support SSE2 extension on Intel P4 processor, then your application might be exposed to "illegal instruction" exception. There might be a way to enable support in kernel, e.g. FreeBSD kernel can be compiled with CPU_ENABLE_SSE, and there is a way to disengage SSE2 code paths upon application start-up, but if you aim for wider "audience" running such kernel, consider no-sse2. Both the 386 and no-asm options imply no-sse2. no- Build without the specified cipher (bf, cast, des, dh, dsa, hmac, md2, md5, mdc2, rc2, rc4, rc5, rsa, sha). The crypto/ directory can be removed after running "make depend". -Dxxx, -lxxx, -Lxxx, -fxxx, -mXXX, -Kxxx These system specific options will be passed through to the compiler to allow you to define preprocessor symbols, specify additional libraries, library directories or other compiler options. It might be worth noting that some compilers generate code specifically for processor the compiler currently executes on. This is not necessarily what you might have in mind, since it might be unsuitable for execution on other, typically older, processor. Consult your compiler documentation. -DHAVE_CRYPTODEV Enable the BSD cryptodev engine even if we are not using BSD. Useful if you are running ocf-linux or something similar. Once enabled you can also enable the use of cryptodev digests, which is usually slower unless you have large amounts data. Use -DUSE_CRYPTODEV_DIGESTS to force it. Installation in Detail ---------------------- 1a. Configure OpenSSL for your operation system automatically: $ ./config [options] This guesses at your operating system (and compiler, if necessary) and configures OpenSSL based on this guess. Run ./config -t to see if it guessed correctly. If you want to use a different compiler, you are cross-compiling for another platform, or the ./config guess was wrong for other reasons, go to step 1b. Otherwise go to step 2. On some systems, you can include debugging information as follows: $ ./config -d [options] 1b. Configure OpenSSL for your operating system manually OpenSSL knows about a range of different operating system, hardware and compiler combinations. To see the ones it knows about, run $ ./Configure Pick a suitable name from the list that matches your system. For most operating systems there is a choice between using "cc" or "gcc". When you have identified your system (and if necessary compiler) use this name as the argument to ./Configure. For example, a "linux-elf" user would run: $ ./Configure linux-elf [options] If your system is not available, you will have to edit the Configure program and add the correct configuration for your system. The generic configurations "cc" or "gcc" should usually work on 32 bit systems. Configure creates the file Makefile.ssl from Makefile.org and defines various macros in crypto/opensslconf.h (generated from crypto/opensslconf.h.in). 2. Build OpenSSL by running: $ make This will build the OpenSSL libraries (libcrypto.a and libssl.a) and the OpenSSL binary ("openssl"). The libraries will be built in the top-level directory, and the binary will be in the "apps" directory. If the build fails, look at the output. There may be reasons for the failure that aren't problems in OpenSSL itself (like missing standard headers). If you are having problems you can get help by sending an email to the openssl-users email list (see https://www.openssl.org/community/mailinglists.html for details). If it is a bug with OpenSSL itself, please open an issue on GitHub, at https://github.com/openssl/openssl/issues. Please review the existing ones first; maybe the bug was already reported or has already been fixed. (If you encounter assembler error messages, try the "no-asm" configuration option as an immediate fix.) Compiling parts of OpenSSL with gcc and others with the system compiler will result in unresolved symbols on some systems. 3. After a successful build, the libraries should be tested. Run: $ make test If a test fails, look at the output. There may be reasons for the failure that isn't a problem in OpenSSL itself (like a missing or malfunctioning bc). If it is a problem with OpenSSL itself, try removing any compiler optimization flags from the CFLAG line - in Makefile.ssl and run "make clean; make". Please send a bug - report to , including the output of - "make report" in order to be added to the request tracker at - http://www.openssl.org/support/rt.html. + in Makefile.ssl and run "make clean; make". To report a bug please open an + issue on GitHub, at https://github.com/openssl/openssl/issues. 4. If everything tests ok, install OpenSSL with $ make install This will create the installation directory (if it does not exist) and then the following subdirectories: certs Initially empty, this is the default location for certificate files. man/man1 Manual pages for the 'openssl' command line tool man/man3 Manual pages for the libraries (very incomplete) misc Various scripts. private Initially empty, this is the default location for private key files. If you didn't choose a different installation prefix, the following additional subdirectories will be created: bin Contains the openssl binary and a few other utility programs. include/openssl Contains the header files needed if you want to compile programs with libcrypto or libssl. lib Contains the OpenSSL library files themselves. Use "make install_sw" to install the software without documentation, and "install_docs_html" to install HTML renditions of the manual pages. Package builders who want to configure the library for standard locations, but have the package installed somewhere else so that it can easily be packaged, can use $ make INSTALL_PREFIX=/tmp/package-root install (or specify "--install_prefix=/tmp/package-root" as a configure option). The specified prefix will be prepended to all installation target filenames. NOTE: The header files used to reside directly in the include directory, but have now been moved to include/openssl so that OpenSSL can co-exist with other libraries which use some of the same filenames. This means that applications that use OpenSSL should now use C preprocessor directives of the form #include instead of "#include ", which was used with library versions up to OpenSSL 0.9.2b. If you install a new version of OpenSSL over an old library version, you should delete the old header files in the include directory. Compatibility issues: * COMPILING existing applications To compile an application that uses old filenames -- e.g. "#include " --, it will usually be enough to find the CFLAGS definition in the application's Makefile and add a C option such as -I/usr/local/ssl/include/openssl to it. But don't delete the existing -I option that points to the ..../include directory! Otherwise, OpenSSL header files could not #include each other. * WRITING applications To write an application that is able to handle both the new and the old directory layout, so that it can still be compiled with library versions up to OpenSSL 0.9.2b without bothering the user, you can proceed as follows: - Always use the new filename of OpenSSL header files, e.g. #include . - Create a directory "incl" that contains only a symbolic link named "openssl", which points to the "include" directory of OpenSSL. For example, your application's Makefile might contain the following rule, if OPENSSLDIR is a pathname (absolute or relative) of the directory where OpenSSL resides: incl/openssl: -mkdir incl cd $(OPENSSLDIR) # Check whether the directory really exists -ln -s `cd $(OPENSSLDIR); pwd`/include incl/openssl You will have to add "incl/openssl" to the dependencies of those C files that include some OpenSSL header file. - Add "-Iincl" to your CFLAGS. With these additions, the OpenSSL header files will be available under both name variants if an old library version is used: Your application can reach them under names like , while the header files still are able to #include each other with names of the form . Note on multi-threading ----------------------- For some systems, the OpenSSL Configure script knows what compiler options are needed to generate a library that is suitable for multi-threaded applications. On these systems, support for multi-threading is enabled by default; use the "no-threads" option to disable (this should never be necessary). On other systems, to enable support for multi-threading, you will have to specify at least two options: "threads", and a system-dependent option. (The latter is "-D_REENTRANT" on various systems.) The default in this case, obviously, is not to include support for multi-threading (but you can still use "no-threads" to suppress an annoying warning message from the Configure script.) Note on shared libraries ------------------------ Shared libraries have certain caveats. Binary backward compatibility can't be guaranteed before OpenSSL version 1.0. The only reason to use them would be to conserve memory on systems where several programs are using OpenSSL. For some systems, the OpenSSL Configure script knows what is needed to build shared libraries for libcrypto and libssl. On these systems, the shared libraries are currently not created by default, but giving the option "shared" will get them created. This method supports Makefile targets for shared library creation, like linux-shared. Those targets can currently be used on their own just as well, but this is expected to change in future versions of OpenSSL. Note on random number generation -------------------------------- Availability of cryptographically secure random numbers is required for secret key generation. OpenSSL provides several options to seed the internal PRNG. If not properly seeded, the internal PRNG will refuse to deliver random bytes and a "PRNG not seeded error" will occur. On systems without /dev/urandom (or similar) device, it may be necessary to install additional support software to obtain random seed. Please check out the manual pages for RAND_add(), RAND_bytes(), RAND_egd(), and the FAQ for more information. Note on support for multiple builds ----------------------------------- OpenSSL is usually built in its source tree. Unfortunately, this doesn't support building for multiple platforms from the same source tree very well. It is however possible to build in a separate tree through the use of lots of symbolic links, which should be prepared like this: 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` rm -f $F; ln -s $OPENSSL_SOURCE/$F $F echo $F '->' $OPENSSL_SOURCE/$F done make -f Makefile.org clean OPENSSL_SOURCE is an environment variable that contains the absolute (this is important!) path to the OpenSSL source tree. Also, operations like 'make update' should still be made in the source tree. Index: vendor-crypto/openssl/dist/Makefile =================================================================== --- vendor-crypto/openssl/dist/Makefile (revision 325325) +++ vendor-crypto/openssl/dist/Makefile (revision 325326) @@ -1,692 +1,692 @@ ### Generated automatically from Makefile.org by Configure. ## ## Makefile for OpenSSL ## -VERSION=1.0.2l +VERSION=1.0.2m 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/NEWS =================================================================== --- vendor-crypto/openssl/dist/NEWS (revision 325325) +++ vendor-crypto/openssl/dist/NEWS (revision 325326) @@ -1,803 +1,808 @@ 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.2l and OpenSSL 1.0.2m [2 Nov 2017] + + o bn_sqrx8x_internal carry bug on x86_64 (CVE-2017-3736) + o Malformed X.509 IPAddressFamily could cause OOB read (CVE-2017-3735) + 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 325325) +++ vendor-crypto/openssl/dist/README (revision 325326) @@ -1,101 +1,101 @@ - OpenSSL 1.0.2l 25 May 2017 + OpenSSL 1.0.2m 2 Nov 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 325325) +++ vendor-crypto/openssl/dist/apps/ca.c (revision 325326) @@ -1,2918 +1,2923 @@ /* 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; + } + + { + STACK_OF(X509_EXTENSION) *exts = ci->extensions; + + if (exts != NULL && sk_X509_EXTENSION_num(exts) > 0) + /* Make it an X509 v3 certificate. */ + if (!X509_set_version(ret, 2)) + 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++) irow[i] = row[i]; 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: 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++) irow[i] = row[i]; 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/s_client.c =================================================================== --- vendor-crypto/openssl/dist/apps/s_client.c (revision 325325) +++ vendor-crypto/openssl/dist/apps/s_client.c (revision 325326) @@ -1,2361 +1,2363 @@ /* 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); + if (seen <= 0) + goto shut; 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 325325) +++ vendor-crypto/openssl/dist/apps/s_server.c (revision 325326) @@ -1,3519 +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");
+            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/speed.c =================================================================== --- vendor-crypto/openssl/dist/apps/speed.c (revision 325325) +++ vendor-crypto/openssl/dist/apps/speed.c (revision 325326) @@ -1,2878 +1,2880 @@ /* apps/speed.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 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. * * Portions of the attached software ("Contribution") are developed by * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project. * * The Contribution is licensed pursuant to the OpenSSL open source * license provided above. * * The ECDH and ECDSA speed test software is originally written by * Sumit Gupta of Sun Microsystems Laboratories. * */ /* most of this code has been pilfered from my libdes speed.c program */ #ifndef OPENSSL_NO_SPEED # undef SECONDS # define SECONDS 3 # define RSA_SECONDS 10 # define DSA_SECONDS 10 # define ECDSA_SECONDS 10 # define ECDH_SECONDS 10 /* 11-Sep-92 Andrew Daviel Support for Silicon Graphics IRIX added */ /* 06-Apr-92 Luke Brennan Support for VMS and add extra signal calls */ # undef PROG # define PROG speed_main # include # include # include # include # include "apps.h" # ifdef OPENSSL_NO_STDIO # define APPS_WIN16 # endif # include # include # include # include # include # if !defined(OPENSSL_SYS_MSDOS) # include OPENSSL_UNISTD # endif # ifndef OPENSSL_SYS_NETWARE # include # endif # if defined(_WIN32) || defined(__CYGWIN__) # include # if defined(__CYGWIN__) && !defined(_WIN32) /* * should define _WIN32, which normally is mutually exclusive * with __CYGWIN__, but if it didn't... */ # define _WIN32 /* this is done because Cygwin alarm() fails sometimes. */ # endif # endif # include # ifndef OPENSSL_NO_DES # include # endif # ifndef OPENSSL_NO_AES # include # endif # ifndef OPENSSL_NO_CAMELLIA # include # endif # ifndef OPENSSL_NO_MD2 # include # endif # ifndef OPENSSL_NO_MDC2 # include # endif # ifndef OPENSSL_NO_MD4 # include # endif # ifndef OPENSSL_NO_MD5 # include # endif # ifndef OPENSSL_NO_HMAC # include # endif # include # ifndef OPENSSL_NO_SHA # include # endif # ifndef OPENSSL_NO_RIPEMD # include # endif # ifndef OPENSSL_NO_WHIRLPOOL # include # endif # ifndef OPENSSL_NO_RC4 # include # endif # ifndef OPENSSL_NO_RC5 # include # endif # ifndef OPENSSL_NO_RC2 # include # endif # ifndef OPENSSL_NO_IDEA # include # endif # ifndef OPENSSL_NO_SEED # include # endif # ifndef OPENSSL_NO_BF # include # endif # ifndef OPENSSL_NO_CAST # include # endif # ifndef OPENSSL_NO_RSA # include # include "./testrsa.h" # endif # include # ifndef OPENSSL_NO_DSA # include # include "./testdsa.h" # endif # ifndef OPENSSL_NO_ECDSA # include # endif # ifndef OPENSSL_NO_ECDH # include # endif # include # ifdef OPENSSL_FIPS # ifdef OPENSSL_DOING_MAKEDEPEND # undef AES_set_encrypt_key # undef AES_set_decrypt_key # undef DES_set_key_unchecked # endif # define BF_set_key private_BF_set_key # define CAST_set_key private_CAST_set_key # define idea_set_encrypt_key private_idea_set_encrypt_key # define SEED_set_key private_SEED_set_key # define RC2_set_key private_RC2_set_key # define RC4_set_key private_RC4_set_key # define DES_set_key_unchecked private_DES_set_key_unchecked # define AES_set_encrypt_key private_AES_set_encrypt_key # define AES_set_decrypt_key private_AES_set_decrypt_key # define Camellia_set_key private_Camellia_set_key # endif # ifndef HAVE_FORK # if defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MACINTOSH_CLASSIC) || defined(OPENSSL_SYS_OS2) || defined(OPENSSL_SYS_NETWARE) # define HAVE_FORK 0 # else # define HAVE_FORK 1 # endif # endif # if HAVE_FORK # undef NO_FORK # else # define NO_FORK # endif # undef BUFSIZE # define BUFSIZE ((long)1024*8+1) static volatile int run = 0; static int mr = 0; static int usertime = 1; static double Time_F(int s); static void print_message(const char *s, long num, int length); static void pkey_print_message(const char *str, const char *str2, long num, int bits, int sec); static void print_result(int alg, int run_no, int count, double time_used); # ifndef NO_FORK static int do_multi(int multi); # endif # define ALGOR_NUM 30 # define SIZE_NUM 5 # define RSA_NUM 4 # define DSA_NUM 3 # define EC_NUM 16 # define MAX_ECDH_SIZE 256 static const char *names[ALGOR_NUM] = { "md2", "mdc2", "md4", "md5", "hmac(md5)", "sha1", "rmd160", "rc4", "des cbc", "des ede3", "idea cbc", "seed cbc", "rc2 cbc", "rc5-32/12 cbc", "blowfish cbc", "cast cbc", "aes-128 cbc", "aes-192 cbc", "aes-256 cbc", "camellia-128 cbc", "camellia-192 cbc", "camellia-256 cbc", "evp", "sha256", "sha512", "whirlpool", "aes-128 ige", "aes-192 ige", "aes-256 ige", "ghash" }; static double results[ALGOR_NUM][SIZE_NUM]; static int lengths[SIZE_NUM] = { 16, 64, 256, 1024, 8 * 1024 }; # ifndef OPENSSL_NO_RSA static double rsa_results[RSA_NUM][2]; # endif # ifndef OPENSSL_NO_DSA static double dsa_results[DSA_NUM][2]; # endif # ifndef OPENSSL_NO_ECDSA static double ecdsa_results[EC_NUM][2]; # endif # ifndef OPENSSL_NO_ECDH static double ecdh_results[EC_NUM][1]; # endif # if defined(OPENSSL_NO_DSA) && !(defined(OPENSSL_NO_ECDSA) && defined(OPENSSL_NO_ECDH)) static const char rnd_seed[] = "string to make the random number generator think it has entropy"; static int rnd_fake = 0; # endif # ifdef SIGALRM # if defined(__STDC__) || defined(sgi) || defined(_AIX) # define SIGRETTYPE void # else # define SIGRETTYPE int # endif static SIGRETTYPE sig_done(int sig); static SIGRETTYPE sig_done(int sig) { signal(SIGALRM, sig_done); run = 0; # ifdef LINT sig = sig; # endif } # endif # define START 0 # define STOP 1 # if defined(_WIN32) # if !defined(SIGALRM) # define SIGALRM # endif -static unsigned int lapse, schlock; +static volatile unsigned int lapse; +static volatile unsigned int schlock; static void alarm_win32(unsigned int secs) { lapse = secs * 1000; } # define alarm alarm_win32 static DWORD WINAPI sleepy(VOID * arg) { schlock = 1; Sleep(lapse); run = 0; return 0; } static double Time_F(int s) { if (s == START) { HANDLE thr; schlock = 0; thr = CreateThread(NULL, 4096, sleepy, NULL, 0, NULL); if (thr == NULL) { DWORD ret = GetLastError(); BIO_printf(bio_err, "unable to CreateThread (%d)", ret); ExitProcess(ret); } CloseHandle(thr); /* detach the thread */ while (!schlock) Sleep(0); /* scheduler spinlock */ } return app_tminterval(s, usertime); } # else static double Time_F(int s) { return app_tminterval(s, usertime); } # endif # ifndef OPENSSL_NO_ECDH static const int KDF1_SHA1_len = 20; static void *KDF1_SHA1(const void *in, size_t inlen, void *out, size_t *outlen) { # ifndef OPENSSL_NO_SHA if (*outlen < SHA_DIGEST_LENGTH) return NULL; else *outlen = SHA_DIGEST_LENGTH; return SHA1(in, inlen, out); # else return NULL; # endif /* OPENSSL_NO_SHA */ } # endif /* OPENSSL_NO_ECDH */ static void multiblock_speed(const EVP_CIPHER *evp_cipher); int MAIN(int, char **); int MAIN(int argc, char **argv) { ENGINE *e = NULL; unsigned char *buf = NULL, *buf2 = NULL; int mret = 1; long count = 0, save_count = 0; int i, j, k; # if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA) long rsa_count; # endif # ifndef OPENSSL_NO_RSA unsigned rsa_num; # endif unsigned char md[EVP_MAX_MD_SIZE]; # ifndef OPENSSL_NO_MD2 unsigned char md2[MD2_DIGEST_LENGTH]; # endif # ifndef OPENSSL_NO_MDC2 unsigned char mdc2[MDC2_DIGEST_LENGTH]; # endif # ifndef OPENSSL_NO_MD4 unsigned char md4[MD4_DIGEST_LENGTH]; # endif # ifndef OPENSSL_NO_MD5 unsigned char md5[MD5_DIGEST_LENGTH]; unsigned char hmac[MD5_DIGEST_LENGTH]; # endif # ifndef OPENSSL_NO_SHA unsigned char sha[SHA_DIGEST_LENGTH]; # ifndef OPENSSL_NO_SHA256 unsigned char sha256[SHA256_DIGEST_LENGTH]; # endif # ifndef OPENSSL_NO_SHA512 unsigned char sha512[SHA512_DIGEST_LENGTH]; # endif # endif # ifndef OPENSSL_NO_WHIRLPOOL unsigned char whirlpool[WHIRLPOOL_DIGEST_LENGTH]; # endif # ifndef OPENSSL_NO_RIPEMD unsigned char rmd160[RIPEMD160_DIGEST_LENGTH]; # endif # ifndef OPENSSL_NO_RC4 RC4_KEY rc4_ks; # endif # ifndef OPENSSL_NO_RC5 RC5_32_KEY rc5_ks; # endif # ifndef OPENSSL_NO_RC2 RC2_KEY rc2_ks; # endif # ifndef OPENSSL_NO_IDEA IDEA_KEY_SCHEDULE idea_ks; # endif # ifndef OPENSSL_NO_SEED SEED_KEY_SCHEDULE seed_ks; # endif # ifndef OPENSSL_NO_BF BF_KEY bf_ks; # endif # ifndef OPENSSL_NO_CAST CAST_KEY cast_ks; # endif static const unsigned char key16[16] = { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12 }; # ifndef OPENSSL_NO_AES static const unsigned char key24[24] = { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34 }; static const unsigned char key32[32] = { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56 }; # endif # ifndef OPENSSL_NO_CAMELLIA static const unsigned char ckey24[24] = { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34 }; static const unsigned char ckey32[32] = { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56 }; # endif # ifndef OPENSSL_NO_AES # define MAX_BLOCK_SIZE 128 # else # define MAX_BLOCK_SIZE 64 # endif unsigned char DES_iv[8]; unsigned char iv[2 * MAX_BLOCK_SIZE / 8]; # ifndef OPENSSL_NO_DES static DES_cblock key = { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0 }; static DES_cblock key2 = { 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12 }; static DES_cblock key3 = { 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34 }; DES_key_schedule sch; DES_key_schedule sch2; DES_key_schedule sch3; # endif # ifndef OPENSSL_NO_AES AES_KEY aes_ks1, aes_ks2, aes_ks3; # endif # ifndef OPENSSL_NO_CAMELLIA CAMELLIA_KEY camellia_ks1, camellia_ks2, camellia_ks3; # endif # define D_MD2 0 # define D_MDC2 1 # define D_MD4 2 # define D_MD5 3 # define D_HMAC 4 # define D_SHA1 5 # define D_RMD160 6 # define D_RC4 7 # define D_CBC_DES 8 # define D_EDE3_DES 9 # define D_CBC_IDEA 10 # define D_CBC_SEED 11 # define D_CBC_RC2 12 # define D_CBC_RC5 13 # define D_CBC_BF 14 # define D_CBC_CAST 15 # define D_CBC_128_AES 16 # define D_CBC_192_AES 17 # define D_CBC_256_AES 18 # define D_CBC_128_CML 19 # define D_CBC_192_CML 20 # define D_CBC_256_CML 21 # define D_EVP 22 # define D_SHA256 23 # define D_SHA512 24 # define D_WHIRLPOOL 25 # define D_IGE_128_AES 26 # define D_IGE_192_AES 27 # define D_IGE_256_AES 28 # define D_GHASH 29 double d = 0.0; long c[ALGOR_NUM][SIZE_NUM]; # define R_DSA_512 0 # define R_DSA_1024 1 # define R_DSA_2048 2 # define R_RSA_512 0 # define R_RSA_1024 1 # define R_RSA_2048 2 # define R_RSA_4096 3 # define R_EC_P160 0 # define R_EC_P192 1 # define R_EC_P224 2 # define R_EC_P256 3 # define R_EC_P384 4 # define R_EC_P521 5 # define R_EC_K163 6 # define R_EC_K233 7 # define R_EC_K283 8 # define R_EC_K409 9 # define R_EC_K571 10 # define R_EC_B163 11 # define R_EC_B233 12 # define R_EC_B283 13 # define R_EC_B409 14 # define R_EC_B571 15 # ifndef OPENSSL_NO_RSA RSA *rsa_key[RSA_NUM]; long rsa_c[RSA_NUM][2]; static unsigned int rsa_bits[RSA_NUM] = { 512, 1024, 2048, 4096 }; static unsigned char *rsa_data[RSA_NUM] = { test512, test1024, test2048, test4096 }; static int rsa_data_length[RSA_NUM] = { sizeof(test512), sizeof(test1024), sizeof(test2048), sizeof(test4096) }; # endif # ifndef OPENSSL_NO_DSA DSA *dsa_key[DSA_NUM]; long dsa_c[DSA_NUM][2]; static unsigned int dsa_bits[DSA_NUM] = { 512, 1024, 2048 }; # endif # ifndef OPENSSL_NO_EC /* * We only test over the following curves as they are representative, To * add tests over more curves, simply add the curve NID and curve name to * the following arrays and increase the EC_NUM value accordingly. */ static unsigned int test_curves[EC_NUM] = { /* Prime Curves */ NID_secp160r1, NID_X9_62_prime192v1, NID_secp224r1, NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, /* Binary Curves */ NID_sect163k1, NID_sect233k1, NID_sect283k1, NID_sect409k1, NID_sect571k1, NID_sect163r2, NID_sect233r1, NID_sect283r1, NID_sect409r1, NID_sect571r1 }; static const char *test_curves_names[EC_NUM] = { /* Prime Curves */ "secp160r1", "nistp192", "nistp224", "nistp256", "nistp384", "nistp521", /* Binary Curves */ "nistk163", "nistk233", "nistk283", "nistk409", "nistk571", "nistb163", "nistb233", "nistb283", "nistb409", "nistb571" }; static int test_curves_bits[EC_NUM] = { 160, 192, 224, 256, 384, 521, 163, 233, 283, 409, 571, 163, 233, 283, 409, 571 }; # endif # ifndef OPENSSL_NO_ECDSA unsigned char ecdsasig[256]; unsigned int ecdsasiglen; EC_KEY *ecdsa[EC_NUM]; long ecdsa_c[EC_NUM][2]; # endif # ifndef OPENSSL_NO_ECDH EC_KEY *ecdh_a[EC_NUM], *ecdh_b[EC_NUM]; unsigned char secret_a[MAX_ECDH_SIZE], secret_b[MAX_ECDH_SIZE]; int secret_size_a, secret_size_b; int ecdh_checks = 0; int secret_idx = 0; long ecdh_c[EC_NUM][2]; # endif int rsa_doit[RSA_NUM]; int dsa_doit[DSA_NUM]; # ifndef OPENSSL_NO_ECDSA int ecdsa_doit[EC_NUM]; # endif # ifndef OPENSSL_NO_ECDH int ecdh_doit[EC_NUM]; # endif int doit[ALGOR_NUM]; int pr_header = 0; const EVP_CIPHER *evp_cipher = NULL; const EVP_MD *evp_md = NULL; int decrypt = 0; # ifndef NO_FORK int multi = 0; # endif int multiblock = 0; # ifndef TIMES usertime = -1; # endif apps_startup(); memset(results, 0, sizeof(results)); # ifndef OPENSSL_NO_DSA memset(dsa_key, 0, sizeof(dsa_key)); # endif # ifndef OPENSSL_NO_ECDSA for (i = 0; i < EC_NUM; i++) ecdsa[i] = NULL; # endif # ifndef OPENSSL_NO_ECDH for (i = 0; i < EC_NUM; i++) { ecdh_a[i] = NULL; ecdh_b[i] = NULL; } # endif # ifndef OPENSSL_NO_RSA for (i = 0; i < RSA_NUM; i++) rsa_key[i] = NULL; # endif 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; if ((buf = (unsigned char *)OPENSSL_malloc((int)BUFSIZE)) == NULL) { BIO_printf(bio_err, "out of memory\n"); goto end; } if ((buf2 = (unsigned char *)OPENSSL_malloc((int)BUFSIZE)) == NULL) { BIO_printf(bio_err, "out of memory\n"); goto end; } memset(c, 0, sizeof(c)); memset(DES_iv, 0, sizeof(DES_iv)); memset(iv, 0, sizeof(iv)); for (i = 0; i < ALGOR_NUM; i++) doit[i] = 0; for (i = 0; i < RSA_NUM; i++) rsa_doit[i] = 0; for (i = 0; i < DSA_NUM; i++) dsa_doit[i] = 0; # ifndef OPENSSL_NO_ECDSA for (i = 0; i < EC_NUM; i++) ecdsa_doit[i] = 0; # endif # ifndef OPENSSL_NO_ECDH for (i = 0; i < EC_NUM; i++) ecdh_doit[i] = 0; # endif j = 0; argc--; argv++; while (argc) { if ((argc > 0) && (strcmp(*argv, "-elapsed") == 0)) { usertime = 0; j--; /* Otherwise, -elapsed gets confused with an * algorithm. */ } else if ((argc > 0) && (strcmp(*argv, "-evp") == 0)) { argc--; argv++; if (argc == 0) { BIO_printf(bio_err, "no EVP given\n"); goto end; } + evp_md = NULL; evp_cipher = EVP_get_cipherbyname(*argv); if (!evp_cipher) { evp_md = EVP_get_digestbyname(*argv); } if (!evp_cipher && !evp_md) { BIO_printf(bio_err, "%s is an unknown cipher or digest\n", *argv); goto end; } doit[D_EVP] = 1; } else if (argc > 0 && !strcmp(*argv, "-decrypt")) { decrypt = 1; j--; /* Otherwise, -elapsed gets confused with an * algorithm. */ } # ifndef OPENSSL_NO_ENGINE else if ((argc > 0) && (strcmp(*argv, "-engine") == 0)) { argc--; argv++; if (argc == 0) { BIO_printf(bio_err, "no engine given\n"); goto end; } e = setup_engine(bio_err, *argv, 0); /* * j will be increased again further down. We just don't want * speed to confuse an engine with an algorithm, especially when * none is given (which means all of them should be run) */ j--; } # endif # ifndef NO_FORK else if ((argc > 0) && (strcmp(*argv, "-multi") == 0)) { argc--; argv++; if (argc == 0) { BIO_printf(bio_err, "no multi count given\n"); goto end; } multi = atoi(argv[0]); if (multi <= 0) { BIO_printf(bio_err, "bad multi count\n"); goto end; } j--; /* Otherwise, -mr gets confused with an * algorithm. */ } # endif else if (argc > 0 && !strcmp(*argv, "-mr")) { mr = 1; j--; /* Otherwise, -mr gets confused with an * algorithm. */ } else if (argc > 0 && !strcmp(*argv, "-mb")) { multiblock = 1; j--; } else # ifndef OPENSSL_NO_MD2 if (strcmp(*argv, "md2") == 0) doit[D_MD2] = 1; else # endif # ifndef OPENSSL_NO_MDC2 if (strcmp(*argv, "mdc2") == 0) doit[D_MDC2] = 1; else # endif # ifndef OPENSSL_NO_MD4 if (strcmp(*argv, "md4") == 0) doit[D_MD4] = 1; else # endif # ifndef OPENSSL_NO_MD5 if (strcmp(*argv, "md5") == 0) doit[D_MD5] = 1; else # endif # ifndef OPENSSL_NO_MD5 if (strcmp(*argv, "hmac") == 0) doit[D_HMAC] = 1; else # endif # ifndef OPENSSL_NO_SHA if (strcmp(*argv, "sha1") == 0) doit[D_SHA1] = 1; else if (strcmp(*argv, "sha") == 0) doit[D_SHA1] = 1, doit[D_SHA256] = 1, doit[D_SHA512] = 1; else # ifndef OPENSSL_NO_SHA256 if (strcmp(*argv, "sha256") == 0) doit[D_SHA256] = 1; else # endif # ifndef OPENSSL_NO_SHA512 if (strcmp(*argv, "sha512") == 0) doit[D_SHA512] = 1; else # endif # endif # ifndef OPENSSL_NO_WHIRLPOOL if (strcmp(*argv, "whirlpool") == 0) doit[D_WHIRLPOOL] = 1; else # endif # ifndef OPENSSL_NO_RIPEMD if (strcmp(*argv, "ripemd") == 0) doit[D_RMD160] = 1; else if (strcmp(*argv, "rmd160") == 0) doit[D_RMD160] = 1; else if (strcmp(*argv, "ripemd160") == 0) doit[D_RMD160] = 1; else # endif # ifndef OPENSSL_NO_RC4 if (strcmp(*argv, "rc4") == 0) doit[D_RC4] = 1; else # endif # ifndef OPENSSL_NO_DES if (strcmp(*argv, "des-cbc") == 0) doit[D_CBC_DES] = 1; else if (strcmp(*argv, "des-ede3") == 0) doit[D_EDE3_DES] = 1; else # endif # ifndef OPENSSL_NO_AES if (strcmp(*argv, "aes-128-cbc") == 0) doit[D_CBC_128_AES] = 1; else if (strcmp(*argv, "aes-192-cbc") == 0) doit[D_CBC_192_AES] = 1; else if (strcmp(*argv, "aes-256-cbc") == 0) doit[D_CBC_256_AES] = 1; else if (strcmp(*argv, "aes-128-ige") == 0) doit[D_IGE_128_AES] = 1; else if (strcmp(*argv, "aes-192-ige") == 0) doit[D_IGE_192_AES] = 1; else if (strcmp(*argv, "aes-256-ige") == 0) doit[D_IGE_256_AES] = 1; else # endif # ifndef OPENSSL_NO_CAMELLIA if (strcmp(*argv, "camellia-128-cbc") == 0) doit[D_CBC_128_CML] = 1; else if (strcmp(*argv, "camellia-192-cbc") == 0) doit[D_CBC_192_CML] = 1; else if (strcmp(*argv, "camellia-256-cbc") == 0) doit[D_CBC_256_CML] = 1; else # endif # ifndef OPENSSL_NO_RSA # if 0 /* was: #ifdef RSAref */ if (strcmp(*argv, "rsaref") == 0) { RSA_set_default_openssl_method(RSA_PKCS1_RSAref()); j--; } else # endif # ifndef RSA_NULL if (strcmp(*argv, "openssl") == 0) { RSA_set_default_method(RSA_PKCS1_SSLeay()); j--; } else # endif # endif /* !OPENSSL_NO_RSA */ if (strcmp(*argv, "dsa512") == 0) dsa_doit[R_DSA_512] = 2; else if (strcmp(*argv, "dsa1024") == 0) dsa_doit[R_DSA_1024] = 2; else if (strcmp(*argv, "dsa2048") == 0) dsa_doit[R_DSA_2048] = 2; else if (strcmp(*argv, "rsa512") == 0) rsa_doit[R_RSA_512] = 2; else if (strcmp(*argv, "rsa1024") == 0) rsa_doit[R_RSA_1024] = 2; else if (strcmp(*argv, "rsa2048") == 0) rsa_doit[R_RSA_2048] = 2; else if (strcmp(*argv, "rsa4096") == 0) rsa_doit[R_RSA_4096] = 2; else # ifndef OPENSSL_NO_RC2 if (strcmp(*argv, "rc2-cbc") == 0) doit[D_CBC_RC2] = 1; else if (strcmp(*argv, "rc2") == 0) doit[D_CBC_RC2] = 1; else # endif # ifndef OPENSSL_NO_RC5 if (strcmp(*argv, "rc5-cbc") == 0) doit[D_CBC_RC5] = 1; else if (strcmp(*argv, "rc5") == 0) doit[D_CBC_RC5] = 1; else # endif # ifndef OPENSSL_NO_IDEA if (strcmp(*argv, "idea-cbc") == 0) doit[D_CBC_IDEA] = 1; else if (strcmp(*argv, "idea") == 0) doit[D_CBC_IDEA] = 1; else # endif # ifndef OPENSSL_NO_SEED if (strcmp(*argv, "seed-cbc") == 0) doit[D_CBC_SEED] = 1; else if (strcmp(*argv, "seed") == 0) doit[D_CBC_SEED] = 1; else # endif # ifndef OPENSSL_NO_BF if (strcmp(*argv, "bf-cbc") == 0) doit[D_CBC_BF] = 1; else if (strcmp(*argv, "blowfish") == 0) doit[D_CBC_BF] = 1; else if (strcmp(*argv, "bf") == 0) doit[D_CBC_BF] = 1; else # endif # ifndef OPENSSL_NO_CAST if (strcmp(*argv, "cast-cbc") == 0) doit[D_CBC_CAST] = 1; else if (strcmp(*argv, "cast") == 0) doit[D_CBC_CAST] = 1; else if (strcmp(*argv, "cast5") == 0) doit[D_CBC_CAST] = 1; else # endif # ifndef OPENSSL_NO_DES if (strcmp(*argv, "des") == 0) { doit[D_CBC_DES] = 1; doit[D_EDE3_DES] = 1; } else # endif # ifndef OPENSSL_NO_AES if (strcmp(*argv, "aes") == 0) { doit[D_CBC_128_AES] = 1; doit[D_CBC_192_AES] = 1; doit[D_CBC_256_AES] = 1; } else if (strcmp(*argv, "ghash") == 0) { doit[D_GHASH] = 1; } else # endif # ifndef OPENSSL_NO_CAMELLIA if (strcmp(*argv, "camellia") == 0) { doit[D_CBC_128_CML] = 1; doit[D_CBC_192_CML] = 1; doit[D_CBC_256_CML] = 1; } else # endif # ifndef OPENSSL_NO_RSA if (strcmp(*argv, "rsa") == 0) { rsa_doit[R_RSA_512] = 1; rsa_doit[R_RSA_1024] = 1; rsa_doit[R_RSA_2048] = 1; rsa_doit[R_RSA_4096] = 1; } else # endif # ifndef OPENSSL_NO_DSA if (strcmp(*argv, "dsa") == 0) { dsa_doit[R_DSA_512] = 1; dsa_doit[R_DSA_1024] = 1; dsa_doit[R_DSA_2048] = 1; } else # endif # ifndef OPENSSL_NO_ECDSA if (strcmp(*argv, "ecdsap160") == 0) ecdsa_doit[R_EC_P160] = 2; else if (strcmp(*argv, "ecdsap192") == 0) ecdsa_doit[R_EC_P192] = 2; else if (strcmp(*argv, "ecdsap224") == 0) ecdsa_doit[R_EC_P224] = 2; else if (strcmp(*argv, "ecdsap256") == 0) ecdsa_doit[R_EC_P256] = 2; else if (strcmp(*argv, "ecdsap384") == 0) ecdsa_doit[R_EC_P384] = 2; else if (strcmp(*argv, "ecdsap521") == 0) ecdsa_doit[R_EC_P521] = 2; else if (strcmp(*argv, "ecdsak163") == 0) ecdsa_doit[R_EC_K163] = 2; else if (strcmp(*argv, "ecdsak233") == 0) ecdsa_doit[R_EC_K233] = 2; else if (strcmp(*argv, "ecdsak283") == 0) ecdsa_doit[R_EC_K283] = 2; else if (strcmp(*argv, "ecdsak409") == 0) ecdsa_doit[R_EC_K409] = 2; else if (strcmp(*argv, "ecdsak571") == 0) ecdsa_doit[R_EC_K571] = 2; else if (strcmp(*argv, "ecdsab163") == 0) ecdsa_doit[R_EC_B163] = 2; else if (strcmp(*argv, "ecdsab233") == 0) ecdsa_doit[R_EC_B233] = 2; else if (strcmp(*argv, "ecdsab283") == 0) ecdsa_doit[R_EC_B283] = 2; else if (strcmp(*argv, "ecdsab409") == 0) ecdsa_doit[R_EC_B409] = 2; else if (strcmp(*argv, "ecdsab571") == 0) ecdsa_doit[R_EC_B571] = 2; else if (strcmp(*argv, "ecdsa") == 0) { for (i = 0; i < EC_NUM; i++) ecdsa_doit[i] = 1; } else # endif # ifndef OPENSSL_NO_ECDH if (strcmp(*argv, "ecdhp160") == 0) ecdh_doit[R_EC_P160] = 2; else if (strcmp(*argv, "ecdhp192") == 0) ecdh_doit[R_EC_P192] = 2; else if (strcmp(*argv, "ecdhp224") == 0) ecdh_doit[R_EC_P224] = 2; else if (strcmp(*argv, "ecdhp256") == 0) ecdh_doit[R_EC_P256] = 2; else if (strcmp(*argv, "ecdhp384") == 0) ecdh_doit[R_EC_P384] = 2; else if (strcmp(*argv, "ecdhp521") == 0) ecdh_doit[R_EC_P521] = 2; else if (strcmp(*argv, "ecdhk163") == 0) ecdh_doit[R_EC_K163] = 2; else if (strcmp(*argv, "ecdhk233") == 0) ecdh_doit[R_EC_K233] = 2; else if (strcmp(*argv, "ecdhk283") == 0) ecdh_doit[R_EC_K283] = 2; else if (strcmp(*argv, "ecdhk409") == 0) ecdh_doit[R_EC_K409] = 2; else if (strcmp(*argv, "ecdhk571") == 0) ecdh_doit[R_EC_K571] = 2; else if (strcmp(*argv, "ecdhb163") == 0) ecdh_doit[R_EC_B163] = 2; else if (strcmp(*argv, "ecdhb233") == 0) ecdh_doit[R_EC_B233] = 2; else if (strcmp(*argv, "ecdhb283") == 0) ecdh_doit[R_EC_B283] = 2; else if (strcmp(*argv, "ecdhb409") == 0) ecdh_doit[R_EC_B409] = 2; else if (strcmp(*argv, "ecdhb571") == 0) ecdh_doit[R_EC_B571] = 2; else if (strcmp(*argv, "ecdh") == 0) { for (i = 0; i < EC_NUM; i++) ecdh_doit[i] = 1; } else # endif { BIO_printf(bio_err, "Error: bad option or value\n"); BIO_printf(bio_err, "\n"); BIO_printf(bio_err, "Available values:\n"); # ifndef OPENSSL_NO_MD2 BIO_printf(bio_err, "md2 "); # endif # ifndef OPENSSL_NO_MDC2 BIO_printf(bio_err, "mdc2 "); # endif # ifndef OPENSSL_NO_MD4 BIO_printf(bio_err, "md4 "); # endif # ifndef OPENSSL_NO_MD5 BIO_printf(bio_err, "md5 "); # ifndef OPENSSL_NO_HMAC BIO_printf(bio_err, "hmac "); # endif # endif # ifndef OPENSSL_NO_SHA1 BIO_printf(bio_err, "sha1 "); # endif # ifndef OPENSSL_NO_SHA256 BIO_printf(bio_err, "sha256 "); # endif # ifndef OPENSSL_NO_SHA512 BIO_printf(bio_err, "sha512 "); # endif # ifndef OPENSSL_NO_WHIRLPOOL BIO_printf(bio_err, "whirlpool"); # endif # ifndef OPENSSL_NO_RIPEMD160 BIO_printf(bio_err, "rmd160"); # endif # if !defined(OPENSSL_NO_MD2) || !defined(OPENSSL_NO_MDC2) || \ !defined(OPENSSL_NO_MD4) || !defined(OPENSSL_NO_MD5) || \ !defined(OPENSSL_NO_SHA1) || !defined(OPENSSL_NO_RIPEMD160) || \ !defined(OPENSSL_NO_WHIRLPOOL) BIO_printf(bio_err, "\n"); # endif # ifndef OPENSSL_NO_IDEA BIO_printf(bio_err, "idea-cbc "); # endif # ifndef OPENSSL_NO_SEED BIO_printf(bio_err, "seed-cbc "); # endif # ifndef OPENSSL_NO_RC2 BIO_printf(bio_err, "rc2-cbc "); # endif # ifndef OPENSSL_NO_RC5 BIO_printf(bio_err, "rc5-cbc "); # endif # ifndef OPENSSL_NO_BF BIO_printf(bio_err, "bf-cbc"); # endif # if !defined(OPENSSL_NO_IDEA) || !defined(OPENSSL_NO_SEED) || !defined(OPENSSL_NO_RC2) || \ !defined(OPENSSL_NO_BF) || !defined(OPENSSL_NO_RC5) BIO_printf(bio_err, "\n"); # endif # ifndef OPENSSL_NO_DES BIO_printf(bio_err, "des-cbc des-ede3 "); # endif # ifndef OPENSSL_NO_AES BIO_printf(bio_err, "aes-128-cbc aes-192-cbc aes-256-cbc "); BIO_printf(bio_err, "aes-128-ige aes-192-ige aes-256-ige "); # endif # ifndef OPENSSL_NO_CAMELLIA BIO_printf(bio_err, "\n"); BIO_printf(bio_err, "camellia-128-cbc camellia-192-cbc camellia-256-cbc "); # endif # ifndef OPENSSL_NO_RC4 BIO_printf(bio_err, "rc4"); # endif BIO_printf(bio_err, "\n"); # ifndef OPENSSL_NO_RSA BIO_printf(bio_err, "rsa512 rsa1024 rsa2048 rsa4096\n"); # endif # ifndef OPENSSL_NO_DSA BIO_printf(bio_err, "dsa512 dsa1024 dsa2048\n"); # endif # ifndef OPENSSL_NO_ECDSA BIO_printf(bio_err, "ecdsap160 ecdsap192 ecdsap224 " "ecdsap256 ecdsap384 ecdsap521\n"); BIO_printf(bio_err, "ecdsak163 ecdsak233 ecdsak283 ecdsak409 ecdsak571\n"); BIO_printf(bio_err, "ecdsab163 ecdsab233 ecdsab283 ecdsab409 ecdsab571\n"); BIO_printf(bio_err, "ecdsa\n"); # endif # ifndef OPENSSL_NO_ECDH BIO_printf(bio_err, "ecdhp160 ecdhp192 ecdhp224 " "ecdhp256 ecdhp384 ecdhp521\n"); BIO_printf(bio_err, "ecdhk163 ecdhk233 ecdhk283 ecdhk409 ecdhk571\n"); BIO_printf(bio_err, "ecdhb163 ecdhb233 ecdhb283 ecdhb409 ecdhb571\n"); BIO_printf(bio_err, "ecdh\n"); # endif # ifndef OPENSSL_NO_IDEA BIO_printf(bio_err, "idea "); # endif # ifndef OPENSSL_NO_SEED BIO_printf(bio_err, "seed "); # endif # ifndef OPENSSL_NO_RC2 BIO_printf(bio_err, "rc2 "); # endif # ifndef OPENSSL_NO_DES BIO_printf(bio_err, "des "); # endif # ifndef OPENSSL_NO_AES BIO_printf(bio_err, "aes "); # endif # ifndef OPENSSL_NO_CAMELLIA BIO_printf(bio_err, "camellia "); # endif # ifndef OPENSSL_NO_RSA BIO_printf(bio_err, "rsa "); # endif # ifndef OPENSSL_NO_BF BIO_printf(bio_err, "blowfish"); # endif # if !defined(OPENSSL_NO_IDEA) || !defined(OPENSSL_NO_SEED) || \ !defined(OPENSSL_NO_RC2) || !defined(OPENSSL_NO_DES) || \ !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_BF) || \ !defined(OPENSSL_NO_AES) || !defined(OPENSSL_NO_CAMELLIA) BIO_printf(bio_err, "\n"); # endif BIO_printf(bio_err, "\n"); BIO_printf(bio_err, "Available options:\n"); # if defined(TIMES) || defined(USE_TOD) BIO_printf(bio_err, "-elapsed " "measure time in real time instead of CPU user time.\n"); # endif # ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err, "-engine e " "use engine e, possibly a hardware device.\n"); # endif BIO_printf(bio_err, "-evp e " "use EVP e.\n"); BIO_printf(bio_err, "-decrypt " "time decryption instead of encryption (only EVP).\n"); BIO_printf(bio_err, "-mr " "produce machine readable output.\n"); # ifndef NO_FORK BIO_printf(bio_err, "-multi n " "run n benchmarks in parallel.\n"); # endif goto end; } argc--; argv++; j++; } # ifndef NO_FORK if (multi && do_multi(multi)) goto show_res; # endif if (j == 0) { for (i = 0; i < ALGOR_NUM; i++) { if (i != D_EVP) doit[i] = 1; } for (i = 0; i < RSA_NUM; i++) rsa_doit[i] = 1; for (i = 0; i < DSA_NUM; i++) dsa_doit[i] = 1; # ifndef OPENSSL_NO_ECDSA for (i = 0; i < EC_NUM; i++) ecdsa_doit[i] = 1; # endif # ifndef OPENSSL_NO_ECDH for (i = 0; i < EC_NUM; i++) ecdh_doit[i] = 1; # endif } for (i = 0; i < ALGOR_NUM; i++) if (doit[i]) pr_header++; if (usertime == 0 && !mr) BIO_printf(bio_err, "You have chosen to measure elapsed time " "instead of user CPU time.\n"); # ifndef OPENSSL_NO_RSA for (i = 0; i < RSA_NUM; i++) { const unsigned char *p; p = rsa_data[i]; rsa_key[i] = d2i_RSAPrivateKey(NULL, &p, rsa_data_length[i]); if (rsa_key[i] == NULL) { BIO_printf(bio_err, "internal error loading RSA key number %d\n", i); goto end; } # if 0 else { BIO_printf(bio_err, mr ? "+RK:%d:" : "Loaded RSA key, %d bit modulus and e= 0x", BN_num_bits(rsa_key[i]->n)); BN_print(bio_err, rsa_key[i]->e); BIO_printf(bio_err, "\n"); } # endif } # endif # ifndef OPENSSL_NO_DSA dsa_key[0] = get_dsa512(); dsa_key[1] = get_dsa1024(); dsa_key[2] = get_dsa2048(); # endif # ifndef OPENSSL_NO_DES DES_set_key_unchecked(&key, &sch); DES_set_key_unchecked(&key2, &sch2); DES_set_key_unchecked(&key3, &sch3); # endif # ifndef OPENSSL_NO_AES AES_set_encrypt_key(key16, 128, &aes_ks1); AES_set_encrypt_key(key24, 192, &aes_ks2); AES_set_encrypt_key(key32, 256, &aes_ks3); # endif # ifndef OPENSSL_NO_CAMELLIA Camellia_set_key(key16, 128, &camellia_ks1); Camellia_set_key(ckey24, 192, &camellia_ks2); Camellia_set_key(ckey32, 256, &camellia_ks3); # endif # ifndef OPENSSL_NO_IDEA idea_set_encrypt_key(key16, &idea_ks); # endif # ifndef OPENSSL_NO_SEED SEED_set_key(key16, &seed_ks); # endif # ifndef OPENSSL_NO_RC4 RC4_set_key(&rc4_ks, 16, key16); # endif # ifndef OPENSSL_NO_RC2 RC2_set_key(&rc2_ks, 16, key16, 128); # endif # ifndef OPENSSL_NO_RC5 RC5_32_set_key(&rc5_ks, 16, key16, 12); # endif # ifndef OPENSSL_NO_BF BF_set_key(&bf_ks, 16, key16); # endif # ifndef OPENSSL_NO_CAST CAST_set_key(&cast_ks, 16, key16); # endif # ifndef OPENSSL_NO_RSA memset(rsa_c, 0, sizeof(rsa_c)); # endif # ifndef SIGALRM # ifndef OPENSSL_NO_DES BIO_printf(bio_err, "First we calculate the approximate speed ...\n"); count = 10; do { long it; count *= 2; Time_F(START); for (it = count; it; it--) DES_ecb_encrypt((DES_cblock *)buf, (DES_cblock *)buf, &sch, DES_ENCRYPT); d = Time_F(STOP); } while (d < 3); save_count = count; c[D_MD2][0] = count / 10; c[D_MDC2][0] = count / 10; c[D_MD4][0] = count; c[D_MD5][0] = count; c[D_HMAC][0] = count; c[D_SHA1][0] = count; c[D_RMD160][0] = count; c[D_RC4][0] = count * 5; c[D_CBC_DES][0] = count; c[D_EDE3_DES][0] = count / 3; c[D_CBC_IDEA][0] = count; c[D_CBC_SEED][0] = count; c[D_CBC_RC2][0] = count; c[D_CBC_RC5][0] = count; c[D_CBC_BF][0] = count; c[D_CBC_CAST][0] = count; c[D_CBC_128_AES][0] = count; c[D_CBC_192_AES][0] = count; c[D_CBC_256_AES][0] = count; c[D_CBC_128_CML][0] = count; c[D_CBC_192_CML][0] = count; c[D_CBC_256_CML][0] = count; c[D_SHA256][0] = count; c[D_SHA512][0] = count; c[D_WHIRLPOOL][0] = count; c[D_IGE_128_AES][0] = count; c[D_IGE_192_AES][0] = count; c[D_IGE_256_AES][0] = count; c[D_GHASH][0] = count; for (i = 1; i < SIZE_NUM; i++) { c[D_MD2][i] = c[D_MD2][0] * 4 * lengths[0] / lengths[i]; c[D_MDC2][i] = c[D_MDC2][0] * 4 * lengths[0] / lengths[i]; c[D_MD4][i] = c[D_MD4][0] * 4 * lengths[0] / lengths[i]; c[D_MD5][i] = c[D_MD5][0] * 4 * lengths[0] / lengths[i]; c[D_HMAC][i] = c[D_HMAC][0] * 4 * lengths[0] / lengths[i]; c[D_SHA1][i] = c[D_SHA1][0] * 4 * lengths[0] / lengths[i]; c[D_RMD160][i] = c[D_RMD160][0] * 4 * lengths[0] / lengths[i]; c[D_SHA256][i] = c[D_SHA256][0] * 4 * lengths[0] / lengths[i]; c[D_SHA512][i] = c[D_SHA512][0] * 4 * lengths[0] / lengths[i]; c[D_WHIRLPOOL][i] = c[D_WHIRLPOOL][0] * 4 * lengths[0] / lengths[i]; } for (i = 1; i < SIZE_NUM; i++) { long l0, l1; l0 = (long)lengths[i - 1]; l1 = (long)lengths[i]; c[D_RC4][i] = c[D_RC4][i - 1] * l0 / l1; c[D_CBC_DES][i] = c[D_CBC_DES][i - 1] * l0 / l1; c[D_EDE3_DES][i] = c[D_EDE3_DES][i - 1] * l0 / l1; c[D_CBC_IDEA][i] = c[D_CBC_IDEA][i - 1] * l0 / l1; c[D_CBC_SEED][i] = c[D_CBC_SEED][i - 1] * l0 / l1; c[D_CBC_RC2][i] = c[D_CBC_RC2][i - 1] * l0 / l1; c[D_CBC_RC5][i] = c[D_CBC_RC5][i - 1] * l0 / l1; c[D_CBC_BF][i] = c[D_CBC_BF][i - 1] * l0 / l1; c[D_CBC_CAST][i] = c[D_CBC_CAST][i - 1] * l0 / l1; c[D_CBC_128_AES][i] = c[D_CBC_128_AES][i - 1] * l0 / l1; c[D_CBC_192_AES][i] = c[D_CBC_192_AES][i - 1] * l0 / l1; c[D_CBC_256_AES][i] = c[D_CBC_256_AES][i - 1] * l0 / l1; c[D_CBC_128_CML][i] = c[D_CBC_128_CML][i - 1] * l0 / l1; c[D_CBC_192_CML][i] = c[D_CBC_192_CML][i - 1] * l0 / l1; c[D_CBC_256_CML][i] = c[D_CBC_256_CML][i - 1] * l0 / l1; c[D_IGE_128_AES][i] = c[D_IGE_128_AES][i - 1] * l0 / l1; c[D_IGE_192_AES][i] = c[D_IGE_192_AES][i - 1] * l0 / l1; c[D_IGE_256_AES][i] = c[D_IGE_256_AES][i - 1] * l0 / l1; } # ifndef OPENSSL_NO_RSA rsa_c[R_RSA_512][0] = count / 2000; rsa_c[R_RSA_512][1] = count / 400; for (i = 1; i < RSA_NUM; i++) { rsa_c[i][0] = rsa_c[i - 1][0] / 8; rsa_c[i][1] = rsa_c[i - 1][1] / 4; if ((rsa_doit[i] <= 1) && (rsa_c[i][0] == 0)) rsa_doit[i] = 0; else { if (rsa_c[i][0] == 0) { rsa_c[i][0] = 1; rsa_c[i][1] = 20; } } } # endif # ifndef OPENSSL_NO_DSA dsa_c[R_DSA_512][0] = count / 1000; dsa_c[R_DSA_512][1] = count / 1000 / 2; for (i = 1; i < DSA_NUM; i++) { dsa_c[i][0] = dsa_c[i - 1][0] / 4; dsa_c[i][1] = dsa_c[i - 1][1] / 4; if ((dsa_doit[i] <= 1) && (dsa_c[i][0] == 0)) dsa_doit[i] = 0; else { if (dsa_c[i] == 0) { dsa_c[i][0] = 1; dsa_c[i][1] = 1; } } } # endif # ifndef OPENSSL_NO_ECDSA ecdsa_c[R_EC_P160][0] = count / 1000; ecdsa_c[R_EC_P160][1] = count / 1000 / 2; for (i = R_EC_P192; i <= R_EC_P521; i++) { ecdsa_c[i][0] = ecdsa_c[i - 1][0] / 2; ecdsa_c[i][1] = ecdsa_c[i - 1][1] / 2; if ((ecdsa_doit[i] <= 1) && (ecdsa_c[i][0] == 0)) ecdsa_doit[i] = 0; else { if (ecdsa_c[i] == 0) { ecdsa_c[i][0] = 1; ecdsa_c[i][1] = 1; } } } ecdsa_c[R_EC_K163][0] = count / 1000; ecdsa_c[R_EC_K163][1] = count / 1000 / 2; for (i = R_EC_K233; i <= R_EC_K571; i++) { ecdsa_c[i][0] = ecdsa_c[i - 1][0] / 2; ecdsa_c[i][1] = ecdsa_c[i - 1][1] / 2; if ((ecdsa_doit[i] <= 1) && (ecdsa_c[i][0] == 0)) ecdsa_doit[i] = 0; else { if (ecdsa_c[i] == 0) { ecdsa_c[i][0] = 1; ecdsa_c[i][1] = 1; } } } ecdsa_c[R_EC_B163][0] = count / 1000; ecdsa_c[R_EC_B163][1] = count / 1000 / 2; for (i = R_EC_B233; i <= R_EC_B571; i++) { ecdsa_c[i][0] = ecdsa_c[i - 1][0] / 2; ecdsa_c[i][1] = ecdsa_c[i - 1][1] / 2; if ((ecdsa_doit[i] <= 1) && (ecdsa_c[i][0] == 0)) ecdsa_doit[i] = 0; else { if (ecdsa_c[i] == 0) { ecdsa_c[i][0] = 1; ecdsa_c[i][1] = 1; } } } # endif # ifndef OPENSSL_NO_ECDH ecdh_c[R_EC_P160][0] = count / 1000; ecdh_c[R_EC_P160][1] = count / 1000; for (i = R_EC_P192; i <= R_EC_P521; i++) { ecdh_c[i][0] = ecdh_c[i - 1][0] / 2; ecdh_c[i][1] = ecdh_c[i - 1][1] / 2; if ((ecdh_doit[i] <= 1) && (ecdh_c[i][0] == 0)) ecdh_doit[i] = 0; else { if (ecdh_c[i] == 0) { ecdh_c[i][0] = 1; ecdh_c[i][1] = 1; } } } ecdh_c[R_EC_K163][0] = count / 1000; ecdh_c[R_EC_K163][1] = count / 1000; for (i = R_EC_K233; i <= R_EC_K571; i++) { ecdh_c[i][0] = ecdh_c[i - 1][0] / 2; ecdh_c[i][1] = ecdh_c[i - 1][1] / 2; if ((ecdh_doit[i] <= 1) && (ecdh_c[i][0] == 0)) ecdh_doit[i] = 0; else { if (ecdh_c[i] == 0) { ecdh_c[i][0] = 1; ecdh_c[i][1] = 1; } } } ecdh_c[R_EC_B163][0] = count / 1000; ecdh_c[R_EC_B163][1] = count / 1000; for (i = R_EC_B233; i <= R_EC_B571; i++) { ecdh_c[i][0] = ecdh_c[i - 1][0] / 2; ecdh_c[i][1] = ecdh_c[i - 1][1] / 2; if ((ecdh_doit[i] <= 1) && (ecdh_c[i][0] == 0)) ecdh_doit[i] = 0; else { if (ecdh_c[i] == 0) { ecdh_c[i][0] = 1; ecdh_c[i][1] = 1; } } } # endif # define COND(d) (count < (d)) # define COUNT(d) (d) # else /* not worth fixing */ # error "You cannot disable DES on systems without SIGALRM." # endif /* OPENSSL_NO_DES */ # else # define COND(c) (run && count<0x7fffffff) # define COUNT(d) (count) # ifndef _WIN32 signal(SIGALRM, sig_done); # endif # endif /* SIGALRM */ # ifndef OPENSSL_NO_MD2 if (doit[D_MD2]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_MD2], c[D_MD2][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_MD2][j]); count++) EVP_Digest(buf, (unsigned long)lengths[j], &(md2[0]), NULL, EVP_md2(), NULL); d = Time_F(STOP); print_result(D_MD2, j, count, d); } } # endif # ifndef OPENSSL_NO_MDC2 if (doit[D_MDC2]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_MDC2], c[D_MDC2][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_MDC2][j]); count++) EVP_Digest(buf, (unsigned long)lengths[j], &(mdc2[0]), NULL, EVP_mdc2(), NULL); d = Time_F(STOP); print_result(D_MDC2, j, count, d); } } # endif # ifndef OPENSSL_NO_MD4 if (doit[D_MD4]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_MD4], c[D_MD4][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_MD4][j]); count++) EVP_Digest(&(buf[0]), (unsigned long)lengths[j], &(md4[0]), NULL, EVP_md4(), NULL); d = Time_F(STOP); print_result(D_MD4, j, count, d); } } # endif # ifndef OPENSSL_NO_MD5 if (doit[D_MD5]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_MD5], c[D_MD5][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_MD5][j]); count++) EVP_Digest(&(buf[0]), (unsigned long)lengths[j], &(md5[0]), NULL, EVP_get_digestbyname("md5"), NULL); d = Time_F(STOP); print_result(D_MD5, j, count, d); } } # endif # if !defined(OPENSSL_NO_MD5) && !defined(OPENSSL_NO_HMAC) if (doit[D_HMAC]) { HMAC_CTX hctx; HMAC_CTX_init(&hctx); HMAC_Init_ex(&hctx, (unsigned char *)"This is a key...", 16, EVP_md5(), NULL); for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_HMAC], c[D_HMAC][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_HMAC][j]); count++) { HMAC_Init_ex(&hctx, NULL, 0, NULL, NULL); HMAC_Update(&hctx, buf, lengths[j]); HMAC_Final(&hctx, &(hmac[0]), NULL); } d = Time_F(STOP); print_result(D_HMAC, j, count, d); } HMAC_CTX_cleanup(&hctx); } # endif # ifndef OPENSSL_NO_SHA if (doit[D_SHA1]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_SHA1], c[D_SHA1][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_SHA1][j]); count++) EVP_Digest(buf, (unsigned long)lengths[j], &(sha[0]), NULL, EVP_sha1(), NULL); d = Time_F(STOP); print_result(D_SHA1, j, count, d); } } # ifndef OPENSSL_NO_SHA256 if (doit[D_SHA256]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_SHA256], c[D_SHA256][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_SHA256][j]); count++) SHA256(buf, lengths[j], sha256); d = Time_F(STOP); print_result(D_SHA256, j, count, d); } } # endif # ifndef OPENSSL_NO_SHA512 if (doit[D_SHA512]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_SHA512], c[D_SHA512][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_SHA512][j]); count++) SHA512(buf, lengths[j], sha512); d = Time_F(STOP); print_result(D_SHA512, j, count, d); } } # endif # endif # ifndef OPENSSL_NO_WHIRLPOOL if (doit[D_WHIRLPOOL]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_WHIRLPOOL], c[D_WHIRLPOOL][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_WHIRLPOOL][j]); count++) WHIRLPOOL(buf, lengths[j], whirlpool); d = Time_F(STOP); print_result(D_WHIRLPOOL, j, count, d); } } # endif # ifndef OPENSSL_NO_RIPEMD if (doit[D_RMD160]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_RMD160], c[D_RMD160][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_RMD160][j]); count++) EVP_Digest(buf, (unsigned long)lengths[j], &(rmd160[0]), NULL, EVP_ripemd160(), NULL); d = Time_F(STOP); print_result(D_RMD160, j, count, d); } } # endif # ifndef OPENSSL_NO_RC4 if (doit[D_RC4]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_RC4], c[D_RC4][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_RC4][j]); count++) RC4(&rc4_ks, (unsigned int)lengths[j], buf, buf); d = Time_F(STOP); print_result(D_RC4, j, count, d); } } # endif # ifndef OPENSSL_NO_DES if (doit[D_CBC_DES]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_CBC_DES], c[D_CBC_DES][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_CBC_DES][j]); count++) DES_ncbc_encrypt(buf, buf, lengths[j], &sch, &DES_iv, DES_ENCRYPT); d = Time_F(STOP); print_result(D_CBC_DES, j, count, d); } } if (doit[D_EDE3_DES]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_EDE3_DES], c[D_EDE3_DES][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_EDE3_DES][j]); count++) DES_ede3_cbc_encrypt(buf, buf, lengths[j], &sch, &sch2, &sch3, &DES_iv, DES_ENCRYPT); d = Time_F(STOP); print_result(D_EDE3_DES, j, count, d); } } # endif # ifndef OPENSSL_NO_AES if (doit[D_CBC_128_AES]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_CBC_128_AES], c[D_CBC_128_AES][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_CBC_128_AES][j]); count++) AES_cbc_encrypt(buf, buf, (unsigned long)lengths[j], &aes_ks1, iv, AES_ENCRYPT); d = Time_F(STOP); print_result(D_CBC_128_AES, j, count, d); } } if (doit[D_CBC_192_AES]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_CBC_192_AES], c[D_CBC_192_AES][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_CBC_192_AES][j]); count++) AES_cbc_encrypt(buf, buf, (unsigned long)lengths[j], &aes_ks2, iv, AES_ENCRYPT); d = Time_F(STOP); print_result(D_CBC_192_AES, j, count, d); } } if (doit[D_CBC_256_AES]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_CBC_256_AES], c[D_CBC_256_AES][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_CBC_256_AES][j]); count++) AES_cbc_encrypt(buf, buf, (unsigned long)lengths[j], &aes_ks3, iv, AES_ENCRYPT); d = Time_F(STOP); print_result(D_CBC_256_AES, j, count, d); } } if (doit[D_IGE_128_AES]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_IGE_128_AES], c[D_IGE_128_AES][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_IGE_128_AES][j]); count++) AES_ige_encrypt(buf, buf2, (unsigned long)lengths[j], &aes_ks1, iv, AES_ENCRYPT); d = Time_F(STOP); print_result(D_IGE_128_AES, j, count, d); } } if (doit[D_IGE_192_AES]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_IGE_192_AES], c[D_IGE_192_AES][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_IGE_192_AES][j]); count++) AES_ige_encrypt(buf, buf2, (unsigned long)lengths[j], &aes_ks2, iv, AES_ENCRYPT); d = Time_F(STOP); print_result(D_IGE_192_AES, j, count, d); } } if (doit[D_IGE_256_AES]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_IGE_256_AES], c[D_IGE_256_AES][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_IGE_256_AES][j]); count++) AES_ige_encrypt(buf, buf2, (unsigned long)lengths[j], &aes_ks3, iv, AES_ENCRYPT); d = Time_F(STOP); print_result(D_IGE_256_AES, j, count, d); } } if (doit[D_GHASH]) { GCM128_CONTEXT *ctx = CRYPTO_gcm128_new(&aes_ks1, (block128_f) AES_encrypt); CRYPTO_gcm128_setiv(ctx, (unsigned char *)"0123456789ab", 12); for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_GHASH], c[D_GHASH][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_GHASH][j]); count++) CRYPTO_gcm128_aad(ctx, buf, lengths[j]); d = Time_F(STOP); print_result(D_GHASH, j, count, d); } CRYPTO_gcm128_release(ctx); } # endif # ifndef OPENSSL_NO_CAMELLIA if (doit[D_CBC_128_CML]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_CBC_128_CML], c[D_CBC_128_CML][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_CBC_128_CML][j]); count++) Camellia_cbc_encrypt(buf, buf, (unsigned long)lengths[j], &camellia_ks1, iv, CAMELLIA_ENCRYPT); d = Time_F(STOP); print_result(D_CBC_128_CML, j, count, d); } } if (doit[D_CBC_192_CML]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_CBC_192_CML], c[D_CBC_192_CML][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_CBC_192_CML][j]); count++) Camellia_cbc_encrypt(buf, buf, (unsigned long)lengths[j], &camellia_ks2, iv, CAMELLIA_ENCRYPT); d = Time_F(STOP); print_result(D_CBC_192_CML, j, count, d); } } if (doit[D_CBC_256_CML]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_CBC_256_CML], c[D_CBC_256_CML][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_CBC_256_CML][j]); count++) Camellia_cbc_encrypt(buf, buf, (unsigned long)lengths[j], &camellia_ks3, iv, CAMELLIA_ENCRYPT); d = Time_F(STOP); print_result(D_CBC_256_CML, j, count, d); } } # endif # ifndef OPENSSL_NO_IDEA if (doit[D_CBC_IDEA]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_CBC_IDEA], c[D_CBC_IDEA][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_CBC_IDEA][j]); count++) idea_cbc_encrypt(buf, buf, (unsigned long)lengths[j], &idea_ks, iv, IDEA_ENCRYPT); d = Time_F(STOP); print_result(D_CBC_IDEA, j, count, d); } } # endif # ifndef OPENSSL_NO_SEED if (doit[D_CBC_SEED]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_CBC_SEED], c[D_CBC_SEED][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_CBC_SEED][j]); count++) SEED_cbc_encrypt(buf, buf, (unsigned long)lengths[j], &seed_ks, iv, 1); d = Time_F(STOP); print_result(D_CBC_SEED, j, count, d); } } # endif # ifndef OPENSSL_NO_RC2 if (doit[D_CBC_RC2]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_CBC_RC2], c[D_CBC_RC2][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_CBC_RC2][j]); count++) RC2_cbc_encrypt(buf, buf, (unsigned long)lengths[j], &rc2_ks, iv, RC2_ENCRYPT); d = Time_F(STOP); print_result(D_CBC_RC2, j, count, d); } } # endif # ifndef OPENSSL_NO_RC5 if (doit[D_CBC_RC5]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_CBC_RC5], c[D_CBC_RC5][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_CBC_RC5][j]); count++) RC5_32_cbc_encrypt(buf, buf, (unsigned long)lengths[j], &rc5_ks, iv, RC5_ENCRYPT); d = Time_F(STOP); print_result(D_CBC_RC5, j, count, d); } } # endif # ifndef OPENSSL_NO_BF if (doit[D_CBC_BF]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_CBC_BF], c[D_CBC_BF][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_CBC_BF][j]); count++) BF_cbc_encrypt(buf, buf, (unsigned long)lengths[j], &bf_ks, iv, BF_ENCRYPT); d = Time_F(STOP); print_result(D_CBC_BF, j, count, d); } } # endif # ifndef OPENSSL_NO_CAST if (doit[D_CBC_CAST]) { for (j = 0; j < SIZE_NUM; j++) { print_message(names[D_CBC_CAST], c[D_CBC_CAST][j], lengths[j]); Time_F(START); for (count = 0, run = 1; COND(c[D_CBC_CAST][j]); count++) CAST_cbc_encrypt(buf, buf, (unsigned long)lengths[j], &cast_ks, iv, CAST_ENCRYPT); d = Time_F(STOP); print_result(D_CBC_CAST, j, count, d); } } # endif if (doit[D_EVP]) { # ifdef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK if (multiblock && evp_cipher) { if (! (EVP_CIPHER_flags(evp_cipher) & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK)) { fprintf(stderr, "%s is not multi-block capable\n", OBJ_nid2ln(evp_cipher->nid)); goto end; } multiblock_speed(evp_cipher); mret = 0; goto end; } # endif for (j = 0; j < SIZE_NUM; j++) { if (evp_cipher) { EVP_CIPHER_CTX ctx; int outl; names[D_EVP] = OBJ_nid2ln(evp_cipher->nid); /* * -O3 -fschedule-insns messes up an optimization here! * names[D_EVP] somehow becomes NULL */ print_message(names[D_EVP], save_count, lengths[j]); EVP_CIPHER_CTX_init(&ctx); if (decrypt) EVP_DecryptInit_ex(&ctx, evp_cipher, NULL, key16, iv); else EVP_EncryptInit_ex(&ctx, evp_cipher, NULL, key16, iv); EVP_CIPHER_CTX_set_padding(&ctx, 0); Time_F(START); if (decrypt) for (count = 0, run = 1; COND(save_count * 4 * lengths[0] / lengths[j]); count++) EVP_DecryptUpdate(&ctx, buf, &outl, buf, lengths[j]); else for (count = 0, run = 1; COND(save_count * 4 * lengths[0] / lengths[j]); count++) EVP_EncryptUpdate(&ctx, buf, &outl, buf, lengths[j]); if (decrypt) EVP_DecryptFinal_ex(&ctx, buf, &outl); else EVP_EncryptFinal_ex(&ctx, buf, &outl); d = Time_F(STOP); EVP_CIPHER_CTX_cleanup(&ctx); } if (evp_md) { names[D_EVP] = OBJ_nid2ln(evp_md->type); print_message(names[D_EVP], save_count, lengths[j]); Time_F(START); for (count = 0, run = 1; COND(save_count * 4 * lengths[0] / lengths[j]); count++) EVP_Digest(buf, lengths[j], &(md[0]), NULL, evp_md, NULL); d = Time_F(STOP); } print_result(D_EVP, j, count, d); } } RAND_pseudo_bytes(buf, 36); # ifndef OPENSSL_NO_RSA for (j = 0; j < RSA_NUM; j++) { int ret; if (!rsa_doit[j]) continue; ret = RSA_sign(NID_md5_sha1, buf, 36, buf2, &rsa_num, rsa_key[j]); if (ret == 0) { BIO_printf(bio_err, "RSA sign failure. No RSA sign will be done.\n"); ERR_print_errors(bio_err); rsa_count = 1; } else { pkey_print_message("private", "rsa", rsa_c[j][0], rsa_bits[j], RSA_SECONDS); /* RSA_blinding_on(rsa_key[j],NULL); */ Time_F(START); for (count = 0, run = 1; COND(rsa_c[j][0]); count++) { ret = RSA_sign(NID_md5_sha1, buf, 36, buf2, &rsa_num, rsa_key[j]); if (ret == 0) { BIO_printf(bio_err, "RSA sign failure\n"); ERR_print_errors(bio_err); count = 1; break; } } d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R1:%ld:%d:%.2f\n" : "%ld %d bit private RSA's in %.2fs\n", count, rsa_bits[j], d); rsa_results[j][0] = d / (double)count; rsa_count = count; } # if 1 ret = RSA_verify(NID_md5_sha1, buf, 36, buf2, rsa_num, rsa_key[j]); if (ret <= 0) { BIO_printf(bio_err, "RSA verify failure. No RSA verify will be done.\n"); ERR_print_errors(bio_err); rsa_doit[j] = 0; } else { pkey_print_message("public", "rsa", rsa_c[j][1], rsa_bits[j], RSA_SECONDS); Time_F(START); for (count = 0, run = 1; COND(rsa_c[j][1]); count++) { ret = RSA_verify(NID_md5_sha1, buf, 36, buf2, rsa_num, rsa_key[j]); if (ret <= 0) { BIO_printf(bio_err, "RSA verify failure\n"); ERR_print_errors(bio_err); count = 1; break; } } d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R2:%ld:%d:%.2f\n" : "%ld %d bit public RSA's in %.2fs\n", count, rsa_bits[j], d); rsa_results[j][1] = d / (double)count; } # endif if (rsa_count <= 1) { /* if longer than 10s, don't do any more */ for (j++; j < RSA_NUM; j++) rsa_doit[j] = 0; } } # endif RAND_pseudo_bytes(buf, 20); # ifndef OPENSSL_NO_DSA if (RAND_status() != 1) { RAND_seed(rnd_seed, sizeof rnd_seed); rnd_fake = 1; } for (j = 0; j < DSA_NUM; j++) { unsigned int kk; int ret; if (!dsa_doit[j]) continue; /* DSA_generate_key(dsa_key[j]); */ /* DSA_sign_setup(dsa_key[j],NULL); */ ret = DSA_sign(EVP_PKEY_DSA, buf, 20, buf2, &kk, dsa_key[j]); if (ret == 0) { BIO_printf(bio_err, "DSA sign failure. No DSA sign will be done.\n"); ERR_print_errors(bio_err); rsa_count = 1; } else { pkey_print_message("sign", "dsa", dsa_c[j][0], dsa_bits[j], DSA_SECONDS); Time_F(START); for (count = 0, run = 1; COND(dsa_c[j][0]); count++) { ret = DSA_sign(EVP_PKEY_DSA, buf, 20, buf2, &kk, dsa_key[j]); if (ret == 0) { BIO_printf(bio_err, "DSA sign failure\n"); ERR_print_errors(bio_err); count = 1; break; } } d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R3:%ld:%d:%.2f\n" : "%ld %d bit DSA signs in %.2fs\n", count, dsa_bits[j], d); dsa_results[j][0] = d / (double)count; rsa_count = count; } ret = DSA_verify(EVP_PKEY_DSA, buf, 20, buf2, kk, dsa_key[j]); if (ret <= 0) { BIO_printf(bio_err, "DSA verify failure. No DSA verify will be done.\n"); ERR_print_errors(bio_err); dsa_doit[j] = 0; } else { pkey_print_message("verify", "dsa", dsa_c[j][1], dsa_bits[j], DSA_SECONDS); Time_F(START); for (count = 0, run = 1; COND(dsa_c[j][1]); count++) { ret = DSA_verify(EVP_PKEY_DSA, buf, 20, buf2, kk, dsa_key[j]); if (ret <= 0) { BIO_printf(bio_err, "DSA verify failure\n"); ERR_print_errors(bio_err); count = 1; break; } } d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R4:%ld:%d:%.2f\n" : "%ld %d bit DSA verify in %.2fs\n", count, dsa_bits[j], d); dsa_results[j][1] = d / (double)count; } if (rsa_count <= 1) { /* if longer than 10s, don't do any more */ for (j++; j < DSA_NUM; j++) dsa_doit[j] = 0; } } if (rnd_fake) RAND_cleanup(); # endif # ifndef OPENSSL_NO_ECDSA if (RAND_status() != 1) { RAND_seed(rnd_seed, sizeof rnd_seed); rnd_fake = 1; } for (j = 0; j < EC_NUM; j++) { int ret; if (!ecdsa_doit[j]) continue; /* Ignore Curve */ ecdsa[j] = EC_KEY_new_by_curve_name(test_curves[j]); if (ecdsa[j] == NULL) { BIO_printf(bio_err, "ECDSA failure.\n"); ERR_print_errors(bio_err); rsa_count = 1; } else { # if 1 EC_KEY_precompute_mult(ecdsa[j], NULL); # endif /* Perform ECDSA signature test */ EC_KEY_generate_key(ecdsa[j]); ret = ECDSA_sign(0, buf, 20, ecdsasig, &ecdsasiglen, ecdsa[j]); if (ret == 0) { BIO_printf(bio_err, "ECDSA sign failure. No ECDSA sign will be done.\n"); ERR_print_errors(bio_err); rsa_count = 1; } else { pkey_print_message("sign", "ecdsa", ecdsa_c[j][0], test_curves_bits[j], ECDSA_SECONDS); Time_F(START); for (count = 0, run = 1; COND(ecdsa_c[j][0]); count++) { ret = ECDSA_sign(0, buf, 20, ecdsasig, &ecdsasiglen, ecdsa[j]); if (ret == 0) { BIO_printf(bio_err, "ECDSA sign failure\n"); ERR_print_errors(bio_err); count = 1; break; } } d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R5:%ld:%d:%.2f\n" : "%ld %d bit ECDSA signs in %.2fs \n", count, test_curves_bits[j], d); ecdsa_results[j][0] = d / (double)count; rsa_count = count; } /* Perform ECDSA verification test */ ret = ECDSA_verify(0, buf, 20, ecdsasig, ecdsasiglen, ecdsa[j]); if (ret != 1) { BIO_printf(bio_err, "ECDSA verify failure. No ECDSA verify will be done.\n"); ERR_print_errors(bio_err); ecdsa_doit[j] = 0; } else { pkey_print_message("verify", "ecdsa", ecdsa_c[j][1], test_curves_bits[j], ECDSA_SECONDS); Time_F(START); for (count = 0, run = 1; COND(ecdsa_c[j][1]); count++) { ret = ECDSA_verify(0, buf, 20, ecdsasig, ecdsasiglen, ecdsa[j]); if (ret != 1) { BIO_printf(bio_err, "ECDSA verify failure\n"); ERR_print_errors(bio_err); count = 1; break; } } d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R6:%ld:%d:%.2f\n" : "%ld %d bit ECDSA verify in %.2fs\n", count, test_curves_bits[j], d); ecdsa_results[j][1] = d / (double)count; } if (rsa_count <= 1) { /* if longer than 10s, don't do any more */ for (j++; j < EC_NUM; j++) ecdsa_doit[j] = 0; } } } if (rnd_fake) RAND_cleanup(); # endif # ifndef OPENSSL_NO_ECDH if (RAND_status() != 1) { RAND_seed(rnd_seed, sizeof rnd_seed); rnd_fake = 1; } for (j = 0; j < EC_NUM; j++) { if (!ecdh_doit[j]) continue; ecdh_a[j] = EC_KEY_new_by_curve_name(test_curves[j]); ecdh_b[j] = EC_KEY_new_by_curve_name(test_curves[j]); if ((ecdh_a[j] == NULL) || (ecdh_b[j] == NULL)) { BIO_printf(bio_err, "ECDH failure.\n"); ERR_print_errors(bio_err); rsa_count = 1; } else { /* generate two ECDH key pairs */ if (!EC_KEY_generate_key(ecdh_a[j]) || !EC_KEY_generate_key(ecdh_b[j])) { BIO_printf(bio_err, "ECDH key generation failure.\n"); ERR_print_errors(bio_err); rsa_count = 1; } else { /* * If field size is not more than 24 octets, then use SHA-1 * hash of result; otherwise, use result (see section 4.8 of * draft-ietf-tls-ecc-03.txt). */ int field_size, outlen; void *(*kdf) (const void *in, size_t inlen, void *out, size_t *xoutlen); field_size = EC_GROUP_get_degree(EC_KEY_get0_group(ecdh_a[j])); if (field_size <= 24 * 8) { outlen = KDF1_SHA1_len; kdf = KDF1_SHA1; } else { outlen = (field_size + 7) / 8; kdf = NULL; } secret_size_a = ECDH_compute_key(secret_a, outlen, EC_KEY_get0_public_key(ecdh_b[j]), ecdh_a[j], kdf); secret_size_b = ECDH_compute_key(secret_b, outlen, EC_KEY_get0_public_key(ecdh_a[j]), ecdh_b[j], kdf); if (secret_size_a != secret_size_b) ecdh_checks = 0; else ecdh_checks = 1; for (secret_idx = 0; (secret_idx < secret_size_a) && (ecdh_checks == 1); secret_idx++) { if (secret_a[secret_idx] != secret_b[secret_idx]) ecdh_checks = 0; } if (ecdh_checks == 0) { BIO_printf(bio_err, "ECDH computations don't match.\n"); ERR_print_errors(bio_err); rsa_count = 1; } pkey_print_message("", "ecdh", ecdh_c[j][0], test_curves_bits[j], ECDH_SECONDS); Time_F(START); for (count = 0, run = 1; COND(ecdh_c[j][0]); count++) { ECDH_compute_key(secret_a, outlen, EC_KEY_get0_public_key(ecdh_b[j]), ecdh_a[j], kdf); } d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R7:%ld:%d:%.2f\n" : "%ld %d-bit ECDH ops in %.2fs\n", count, test_curves_bits[j], d); ecdh_results[j][0] = d / (double)count; rsa_count = count; } } if (rsa_count <= 1) { /* if longer than 10s, don't do any more */ for (j++; j < EC_NUM; j++) ecdh_doit[j] = 0; } } if (rnd_fake) RAND_cleanup(); # endif # ifndef NO_FORK show_res: # endif if (!mr) { fprintf(stdout, "%s\n", SSLeay_version(SSLEAY_VERSION)); fprintf(stdout, "%s\n", SSLeay_version(SSLEAY_BUILT_ON)); printf("options:"); printf("%s ", BN_options()); # ifndef OPENSSL_NO_MD2 printf("%s ", MD2_options()); # endif # ifndef OPENSSL_NO_RC4 printf("%s ", RC4_options()); # endif # ifndef OPENSSL_NO_DES printf("%s ", DES_options()); # endif # ifndef OPENSSL_NO_AES printf("%s ", AES_options()); # endif # ifndef OPENSSL_NO_IDEA printf("%s ", idea_options()); # endif # ifndef OPENSSL_NO_BF printf("%s ", BF_options()); # endif fprintf(stdout, "\n%s\n", SSLeay_version(SSLEAY_CFLAGS)); } if (pr_header) { if (mr) fprintf(stdout, "+H"); else { fprintf(stdout, "The 'numbers' are in 1000s of bytes per second processed.\n"); fprintf(stdout, "type "); } for (j = 0; j < SIZE_NUM; j++) fprintf(stdout, mr ? ":%d" : "%7d bytes", lengths[j]); fprintf(stdout, "\n"); } for (k = 0; k < ALGOR_NUM; k++) { if (!doit[k]) continue; if (mr) fprintf(stdout, "+F:%d:%s", k, names[k]); else fprintf(stdout, "%-13s", names[k]); for (j = 0; j < SIZE_NUM; j++) { if (results[k][j] > 10000 && !mr) fprintf(stdout, " %11.2fk", results[k][j] / 1e3); else fprintf(stdout, mr ? ":%.2f" : " %11.2f ", results[k][j]); } fprintf(stdout, "\n"); } # ifndef OPENSSL_NO_RSA j = 1; for (k = 0; k < RSA_NUM; k++) { if (!rsa_doit[k]) continue; if (j && !mr) { printf("%18ssign verify sign/s verify/s\n", " "); j = 0; } if (mr) fprintf(stdout, "+F2:%u:%u:%f:%f\n", k, rsa_bits[k], rsa_results[k][0], rsa_results[k][1]); else fprintf(stdout, "rsa %4u bits %8.6fs %8.6fs %8.1f %8.1f\n", rsa_bits[k], rsa_results[k][0], rsa_results[k][1], 1.0 / rsa_results[k][0], 1.0 / rsa_results[k][1]); } # endif # ifndef OPENSSL_NO_DSA j = 1; for (k = 0; k < DSA_NUM; k++) { if (!dsa_doit[k]) continue; if (j && !mr) { printf("%18ssign verify sign/s verify/s\n", " "); j = 0; } if (mr) fprintf(stdout, "+F3:%u:%u:%f:%f\n", k, dsa_bits[k], dsa_results[k][0], dsa_results[k][1]); else fprintf(stdout, "dsa %4u bits %8.6fs %8.6fs %8.1f %8.1f\n", dsa_bits[k], dsa_results[k][0], dsa_results[k][1], 1.0 / dsa_results[k][0], 1.0 / dsa_results[k][1]); } # endif # ifndef OPENSSL_NO_ECDSA j = 1; for (k = 0; k < EC_NUM; k++) { if (!ecdsa_doit[k]) continue; if (j && !mr) { printf("%30ssign verify sign/s verify/s\n", " "); j = 0; } if (mr) fprintf(stdout, "+F4:%u:%u:%f:%f\n", k, test_curves_bits[k], ecdsa_results[k][0], ecdsa_results[k][1]); else fprintf(stdout, "%4u bit ecdsa (%s) %8.4fs %8.4fs %8.1f %8.1f\n", test_curves_bits[k], test_curves_names[k], ecdsa_results[k][0], ecdsa_results[k][1], 1.0 / ecdsa_results[k][0], 1.0 / ecdsa_results[k][1]); } # endif # ifndef OPENSSL_NO_ECDH j = 1; for (k = 0; k < EC_NUM; k++) { if (!ecdh_doit[k]) continue; if (j && !mr) { printf("%30sop op/s\n", " "); j = 0; } if (mr) fprintf(stdout, "+F5:%u:%u:%f:%f\n", k, test_curves_bits[k], ecdh_results[k][0], 1.0 / ecdh_results[k][0]); else fprintf(stdout, "%4u bit ecdh (%s) %8.4fs %8.1f\n", test_curves_bits[k], test_curves_names[k], ecdh_results[k][0], 1.0 / ecdh_results[k][0]); } # endif mret = 0; end: ERR_print_errors(bio_err); if (buf != NULL) OPENSSL_free(buf); if (buf2 != NULL) OPENSSL_free(buf2); # ifndef OPENSSL_NO_RSA for (i = 0; i < RSA_NUM; i++) if (rsa_key[i] != NULL) RSA_free(rsa_key[i]); # endif # ifndef OPENSSL_NO_DSA for (i = 0; i < DSA_NUM; i++) if (dsa_key[i] != NULL) DSA_free(dsa_key[i]); # endif # ifndef OPENSSL_NO_ECDSA for (i = 0; i < EC_NUM; i++) if (ecdsa[i] != NULL) EC_KEY_free(ecdsa[i]); # endif # ifndef OPENSSL_NO_ECDH for (i = 0; i < EC_NUM; i++) { if (ecdh_a[i] != NULL) EC_KEY_free(ecdh_a[i]); if (ecdh_b[i] != NULL) EC_KEY_free(ecdh_b[i]); } # endif release_engine(e); apps_shutdown(); OPENSSL_EXIT(mret); } static void print_message(const char *s, long num, int length) { # ifdef SIGALRM BIO_printf(bio_err, mr ? "+DT:%s:%d:%d\n" : "Doing %s for %ds on %d size blocks: ", s, SECONDS, length); (void)BIO_flush(bio_err); alarm(SECONDS); # else BIO_printf(bio_err, mr ? "+DN:%s:%ld:%d\n" : "Doing %s %ld times on %d size blocks: ", s, num, length); (void)BIO_flush(bio_err); # endif # ifdef LINT num = num; # endif } static void pkey_print_message(const char *str, const char *str2, long num, int bits, int tm) { # ifdef SIGALRM BIO_printf(bio_err, mr ? "+DTP:%d:%s:%s:%d\n" : "Doing %d bit %s %s's for %ds: ", bits, str, str2, tm); (void)BIO_flush(bio_err); alarm(tm); # else BIO_printf(bio_err, mr ? "+DNP:%ld:%d:%s:%s\n" : "Doing %ld %d bit %s %s's: ", num, bits, str, str2); (void)BIO_flush(bio_err); # endif # ifdef LINT num = num; # endif } static void print_result(int alg, int run_no, int count, double time_used) { BIO_printf(bio_err, mr ? "+R:%d:%s:%f\n" : "%d %s's in %.2fs\n", count, names[alg], time_used); results[alg][run_no] = ((double)count) / time_used * lengths[run_no]; } # ifndef NO_FORK static char *sstrsep(char **string, const char *delim) { char isdelim[256]; char *token = *string; if (**string == 0) return NULL; memset(isdelim, 0, sizeof isdelim); isdelim[0] = 1; while (*delim) { isdelim[(unsigned char)(*delim)] = 1; delim++; } while (!isdelim[(unsigned char)(**string)]) { (*string)++; } if (**string) { **string = 0; (*string)++; } return token; } static int do_multi(int multi) { int n; int fd[2]; int *fds; static char sep[] = ":"; fds = malloc(multi * sizeof *fds); if (fds == NULL) { fprintf(stderr, "Out of memory in speed (do_multi)\n"); exit(1); } for (n = 0; n < multi; ++n) { if (pipe(fd) == -1) { fprintf(stderr, "pipe failure\n"); exit(1); } fflush(stdout); fflush(stderr); if (fork()) { close(fd[1]); fds[n] = fd[0]; } else { close(fd[0]); close(1); if (dup(fd[1]) == -1) { fprintf(stderr, "dup failed\n"); exit(1); } close(fd[1]); mr = 1; usertime = 0; free(fds); return 0; } printf("Forked child %d\n", n); } /* for now, assume the pipe is long enough to take all the output */ for (n = 0; n < multi; ++n) { FILE *f; char buf[1024]; char *p; f = fdopen(fds[n], "r"); while (fgets(buf, sizeof buf, f)) { p = strchr(buf, '\n'); if (p) *p = '\0'; if (buf[0] != '+') { fprintf(stderr, "Don't understand line '%s' from child %d\n", buf, n); continue; } printf("Got: %s from %d\n", buf, n); if (!strncmp(buf, "+F:", 3)) { int alg; int j; p = buf + 3; alg = atoi(sstrsep(&p, sep)); sstrsep(&p, sep); for (j = 0; j < SIZE_NUM; ++j) results[alg][j] += atof(sstrsep(&p, sep)); } else if (!strncmp(buf, "+F2:", 4)) { int k; double d; p = buf + 4; k = atoi(sstrsep(&p, sep)); sstrsep(&p, sep); d = atof(sstrsep(&p, sep)); if (n) rsa_results[k][0] = 1 / (1 / rsa_results[k][0] + 1 / d); else rsa_results[k][0] = d; d = atof(sstrsep(&p, sep)); if (n) rsa_results[k][1] = 1 / (1 / rsa_results[k][1] + 1 / d); else rsa_results[k][1] = d; } # ifndef OPENSSL_NO_DSA else if (!strncmp(buf, "+F3:", 4)) { int k; double d; p = buf + 4; k = atoi(sstrsep(&p, sep)); sstrsep(&p, sep); d = atof(sstrsep(&p, sep)); if (n) dsa_results[k][0] = 1 / (1 / dsa_results[k][0] + 1 / d); else dsa_results[k][0] = d; d = atof(sstrsep(&p, sep)); if (n) dsa_results[k][1] = 1 / (1 / dsa_results[k][1] + 1 / d); else dsa_results[k][1] = d; } # endif # ifndef OPENSSL_NO_ECDSA else if (!strncmp(buf, "+F4:", 4)) { int k; double d; p = buf + 4; k = atoi(sstrsep(&p, sep)); sstrsep(&p, sep); d = atof(sstrsep(&p, sep)); if (n) ecdsa_results[k][0] = 1 / (1 / ecdsa_results[k][0] + 1 / d); else ecdsa_results[k][0] = d; d = atof(sstrsep(&p, sep)); if (n) ecdsa_results[k][1] = 1 / (1 / ecdsa_results[k][1] + 1 / d); else ecdsa_results[k][1] = d; } # endif # ifndef OPENSSL_NO_ECDH else if (!strncmp(buf, "+F5:", 4)) { int k; double d; p = buf + 4; k = atoi(sstrsep(&p, sep)); sstrsep(&p, sep); d = atof(sstrsep(&p, sep)); if (n) ecdh_results[k][0] = 1 / (1 / ecdh_results[k][0] + 1 / d); else ecdh_results[k][0] = d; } # endif else if (!strncmp(buf, "+H:", 3)) { } else fprintf(stderr, "Unknown type '%s' from child %d\n", buf, n); } fclose(f); } free(fds); return 1; } # endif static void multiblock_speed(const EVP_CIPHER *evp_cipher) { static int mblengths[] = { 8 * 1024, 2 * 8 * 1024, 4 * 8 * 1024, 8 * 8 * 1024, 8 * 16 * 1024 }; int j, count, num = sizeof(lengths) / sizeof(lengths[0]); const char *alg_name; unsigned char *inp, *out, no_key[32], no_iv[16]; EVP_CIPHER_CTX ctx; double d = 0.0; inp = OPENSSL_malloc(mblengths[num - 1]); out = OPENSSL_malloc(mblengths[num - 1] + 1024); if (!inp || !out) { BIO_printf(bio_err,"Out of memory\n"); goto end; } EVP_CIPHER_CTX_init(&ctx); EVP_EncryptInit_ex(&ctx, evp_cipher, NULL, no_key, no_iv); EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_AEAD_SET_MAC_KEY, sizeof(no_key), no_key); alg_name = OBJ_nid2ln(evp_cipher->nid); for (j = 0; j < num; j++) { print_message(alg_name, 0, mblengths[j]); Time_F(START); for (count = 0, run = 1; run && count < 0x7fffffff; count++) { unsigned char aad[EVP_AEAD_TLS1_AAD_LEN]; EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param; size_t len = mblengths[j]; int packlen; memset(aad, 0, 8); /* avoid uninitialized values */ aad[8] = 23; /* SSL3_RT_APPLICATION_DATA */ aad[9] = 3; /* version */ aad[10] = 2; aad[11] = 0; /* length */ aad[12] = 0; mb_param.out = NULL; mb_param.inp = aad; mb_param.len = len; mb_param.interleave = 8; packlen = EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_AAD, sizeof(mb_param), &mb_param); if (packlen > 0) { mb_param.out = out; mb_param.inp = inp; mb_param.len = len; EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT, sizeof(mb_param), &mb_param); } else { int pad; RAND_bytes(out, 16); len += 16; aad[11] = len >> 8; aad[12] = len; pad = EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_AEAD_TLS1_AAD, EVP_AEAD_TLS1_AAD_LEN, aad); EVP_Cipher(&ctx, out, inp, len + pad); } } d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R:%d:%s:%f\n" : "%d %s's in %.2fs\n", count, "evp", d); results[D_EVP][j] = ((double)count) / d * mblengths[j]; } if (mr) { fprintf(stdout, "+H"); for (j = 0; j < num; j++) fprintf(stdout, ":%d", mblengths[j]); fprintf(stdout, "\n"); fprintf(stdout, "+F:%d:%s", D_EVP, alg_name); for (j = 0; j < num; j++) fprintf(stdout, ":%.2f", results[D_EVP][j]); fprintf(stdout, "\n"); } else { fprintf(stdout, "The 'numbers' are in 1000s of bytes per second processed.\n"); fprintf(stdout, "type "); for (j = 0; j < num; j++) fprintf(stdout, "%7d bytes", mblengths[j]); fprintf(stdout, "\n"); fprintf(stdout, "%-24s", alg_name); for (j = 0; j < num; j++) { if (results[D_EVP][j] > 10000) fprintf(stdout, " %11.2fk", results[D_EVP][j] / 1e3); else fprintf(stdout, " %11.2f ", results[D_EVP][j]); } fprintf(stdout, "\n"); } end: if (inp) OPENSSL_free(inp); if (out) OPENSSL_free(out); } #endif Index: vendor-crypto/openssl/dist/apps/spkac.c =================================================================== --- vendor-crypto/openssl/dist/apps/spkac.c (revision 325325) +++ vendor-crypto/openssl/dist/apps/spkac.c (revision 325326) @@ -1,309 +1,312 @@ /* apps/spkac.c */ /* * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project * 1999. Based on an original idea by Massimiliano Pala (madwolf@openca.org). */ /* ==================================================================== - * Copyright (c) 1999 The OpenSSL Project. All rights reserved. + * Copyright (c) 1999-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 * 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 "apps.h" #include #include #include #include #include #include #include #undef PROG #define PROG spkac_main /*- * -in arg - input file - default stdin * -out arg - output file - default stdout */ int MAIN(int, char **); int MAIN(int argc, char **argv) { ENGINE *e = NULL; int i, badops = 0, ret = 1; BIO *in = NULL, *out = NULL; int verify = 0, noout = 0, pubkey = 0; char *infile = NULL, *outfile = NULL, *prog; char *passargin = NULL, *passin = NULL; const char *spkac = "SPKAC", *spksect = "default"; char *spkstr = NULL; char *challenge = NULL, *keyfile = NULL; CONF *conf = NULL; NETSCAPE_SPKI *spki = NULL; EVP_PKEY *pkey = NULL; char *engine = NULL; apps_startup(); if (!bio_err) bio_err = BIO_new_fp(stderr, BIO_NOCLOSE); if (!load_config(bio_err, NULL)) goto end; prog = argv[0]; argc--; argv++; while (argc >= 1) { 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, "-passin") == 0) { if (--argc < 1) goto bad; passargin = *(++argv); } else if (strcmp(*argv, "-key") == 0) { if (--argc < 1) goto bad; keyfile = *(++argv); } else if (strcmp(*argv, "-challenge") == 0) { if (--argc < 1) goto bad; challenge = *(++argv); } else if (strcmp(*argv, "-spkac") == 0) { if (--argc < 1) goto bad; spkac = *(++argv); } else if (strcmp(*argv, "-spksect") == 0) { if (--argc < 1) goto bad; spksect = *(++argv); } #ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv, "-engine") == 0) { if (--argc < 1) goto bad; engine = *(++argv); } #endif else if (strcmp(*argv, "-noout") == 0) noout = 1; else if (strcmp(*argv, "-pubkey") == 0) pubkey = 1; else if (strcmp(*argv, "-verify") == 0) verify = 1; else badops = 1; argc--; argv++; } if (badops) { bad: BIO_printf(bio_err, "%s [options]\n", prog); BIO_printf(bio_err, "where options are\n"); BIO_printf(bio_err, " -in arg input file\n"); BIO_printf(bio_err, " -out arg output file\n"); BIO_printf(bio_err, " -key arg create SPKAC using private key\n"); BIO_printf(bio_err, " -passin arg input file pass phrase source\n"); BIO_printf(bio_err, " -challenge arg challenge string\n"); BIO_printf(bio_err, " -spkac arg alternative SPKAC name\n"); BIO_printf(bio_err, " -noout don't print SPKAC\n"); BIO_printf(bio_err, " -pubkey output public key\n"); BIO_printf(bio_err, " -verify verify SPKAC signature\n"); #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err, " -engine e use engine e, possibly a hardware device.\n"); #endif goto end; } ERR_load_crypto_strings(); if (!app_passwd(bio_err, passargin, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } e = setup_engine(bio_err, engine, 0); - if (keyfile) { + if (keyfile != NULL) { pkey = load_key(bio_err, strcmp(keyfile, "-") ? keyfile : NULL, FORMAT_PEM, 1, passin, e, "private key"); - if (!pkey) { + if (pkey == NULL) goto end; - } spki = NETSCAPE_SPKI_new(); - if (challenge) + if (spki == NULL) + goto end; + if (challenge != NULL) ASN1_STRING_set(spki->spkac->challenge, challenge, (int)strlen(challenge)); NETSCAPE_SPKI_set_pubkey(spki, pkey); NETSCAPE_SPKI_sign(spki, pkey, EVP_md5()); spkstr = NETSCAPE_SPKI_b64_encode(spki); + if (spkstr == NULL) + goto end; if (outfile) out = BIO_new_file(outfile, "w"); 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 (!out) { BIO_printf(bio_err, "Error opening output file\n"); ERR_print_errors(bio_err); goto end; } BIO_printf(out, "SPKAC=%s\n", spkstr); OPENSSL_free(spkstr); ret = 0; goto end; } if (infile) in = BIO_new_file(infile, "r"); else in = BIO_new_fp(stdin, BIO_NOCLOSE); if (!in) { BIO_printf(bio_err, "Error opening input file\n"); ERR_print_errors(bio_err); goto end; } conf = NCONF_new(NULL); i = NCONF_load_bio(conf, in, NULL); if (!i) { BIO_printf(bio_err, "Error parsing config file\n"); ERR_print_errors(bio_err); goto end; } spkstr = NCONF_get_string(conf, spksect, spkac); if (!spkstr) { BIO_printf(bio_err, "Can't find SPKAC called \"%s\"\n", spkac); ERR_print_errors(bio_err); goto end; } spki = NETSCAPE_SPKI_b64_decode(spkstr, -1); - if (!spki) { + if (spki == NULL) { BIO_printf(bio_err, "Error loading SPKAC\n"); ERR_print_errors(bio_err); goto end; } if (outfile) out = BIO_new_file(outfile, "w"); 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 (!out) { BIO_printf(bio_err, "Error opening output file\n"); ERR_print_errors(bio_err); goto end; } if (!noout) NETSCAPE_SPKI_print(out, spki); pkey = NETSCAPE_SPKI_get_pubkey(spki); if (verify) { i = NETSCAPE_SPKI_verify(spki, pkey); - if (i > 0) + if (i > 0) { BIO_printf(bio_err, "Signature OK\n"); - else { + } else { BIO_printf(bio_err, "Signature Failure\n"); ERR_print_errors(bio_err); goto end; } } if (pubkey) PEM_write_bio_PUBKEY(out, pkey); ret = 0; end: NCONF_free(conf); NETSCAPE_SPKI_free(spki); BIO_free(in); BIO_free_all(out); EVP_PKEY_free(pkey); release_engine(e); if (passin) OPENSSL_free(passin); apps_shutdown(); OPENSSL_EXIT(ret); } Index: vendor-crypto/openssl/dist/apps/srp.c =================================================================== --- vendor-crypto/openssl/dist/apps/srp.c (revision 325325) +++ vendor-crypto/openssl/dist/apps/srp.c (revision 325326) @@ -1,766 +1,774 @@ /* 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) + 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 + } + } 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) { + irow = (char **)OPENSSL_malloc(sizeof(char *) * (DB_NUMBER + 1)); + if (irow == NULL) { BIO_printf(bio_err, "Memory allocation failure\n"); return 0; } for (i = 0; i < DB_NUMBER; i++) irow[i] = row[i]; 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]; + char password[1025]; PW_CB_DATA cb_tmp; char *verifier = NULL; char *gNid = NULL; + int len; cb_tmp.prompt_info = user; cb_tmp.password = passin; - if (password_callback(password, 1024, 0, &cb_tmp) > 0) { + len = password_callback(password, sizeof(password)-1, 0, &cb_tmp); + if (len > 0) { + password[len] = 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); + VVERBOSE BIO_printf(bio, "Pass %s\n", password); - if (! - (gNid = - SRP_create_verifier(user, password, &srp_usersalt, &verifier, N, - g))) { + 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); } + OPENSSL_cleanse(password, len); } 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]; + char password[1025]; PW_CB_DATA cb_tmp; char *gNid = NULL; char *salt = NULL; + int len; cb_tmp.prompt_info = user; cb_tmp.password = passout; - if (password_callback(password, 1024, 1, &cb_tmp) > 0) { + len = password_callback(password, sizeof(password)-1, 1, &cb_tmp); + if (len > 0) { + password[len] = 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))) { + if (!(gNid = SRP_create_verifier(user, password, &salt, + srp_verifier, N, g))) { BIO_printf(bio, "Internal error creating SRP verifier\n"); - } else + } else { *srp_usersalt = salt; + } + OPENSSL_cleanse(password, len); 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) + if (strcmp(*argv, "-verbose") == 0) { verbose++; - else if (strcmp(*argv, "-config") == 0) { + } 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) + } else if (strcmp(*argv, "-add") == 0) { add_user = 1; - else if (strcmp(*argv, "-delete") == 0) + } else if (strcmp(*argv, "-delete") == 0) { delete_user = 1; - else if (strcmp(*argv, "-modify") == 0) + } else if (strcmp(*argv, "-modify") == 0) { modify_user = 1; - else if (strcmp(*argv, "-list") == 0) + } else if (strcmp(*argv, "-list") == 0) { list_user = 1; - else if (strcmp(*argv, "-gn") == 0) { + } 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 + } 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) { + if ((passargin || passargout) && 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) + if (--argc > 0) { user = *(argv++); - else { + } 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/apps/tsget =================================================================== --- vendor-crypto/openssl/dist/apps/tsget (revision 325325) +++ vendor-crypto/openssl/dist/apps/tsget (revision 325326) @@ -1,196 +1,195 @@ #!/usr/bin/perl -w # Written by Zoltan Glozik . # Copyright (c) 2002 The OpenTSA Project. All rights reserved. $::version = '$Id: tsget,v 1.1.2.2 2009/09/07 17:57:02 steve Exp $'; use strict; use IO::Handle; use Getopt::Std; use File::Basename; use WWW::Curl::Easy; use vars qw(%options); # Callback for reading the body. sub read_body { my ($maxlength, $state) = @_; my $return_data = ""; my $data_len = length ${$state->{data}}; if ($state->{bytes} < $data_len) { $data_len = $data_len - $state->{bytes}; $data_len = $maxlength if $data_len > $maxlength; $return_data = substr ${$state->{data}}, $state->{bytes}, $data_len; $state->{bytes} += $data_len; } return $return_data; } # Callback for writing the body into a variable. sub write_body { my ($data, $pointer) = @_; ${$pointer} .= $data; return length($data); } # Initialise a new Curl object. sub create_curl { my $url = shift; # Create Curl object. my $curl = WWW::Curl::Easy::new(); # Error-handling related options. $curl->setopt(CURLOPT_VERBOSE, 1) if $options{d}; $curl->setopt(CURLOPT_FAILONERROR, 1); $curl->setopt(CURLOPT_USERAGENT, "OpenTSA tsget.pl/" . (split / /, $::version)[2]); # Options for POST method. $curl->setopt(CURLOPT_UPLOAD, 1); $curl->setopt(CURLOPT_CUSTOMREQUEST, "POST"); $curl->setopt(CURLOPT_HTTPHEADER, ["Content-Type: application/timestamp-query", "Accept: application/timestamp-reply,application/timestamp-response"]); $curl->setopt(CURLOPT_READFUNCTION, \&read_body); $curl->setopt(CURLOPT_HEADERFUNCTION, sub { return length($_[0]); }); # Options for getting the result. $curl->setopt(CURLOPT_WRITEFUNCTION, \&write_body); # SSL related options. $curl->setopt(CURLOPT_SSLKEYTYPE, "PEM"); $curl->setopt(CURLOPT_SSL_VERIFYPEER, 1); # Verify server's certificate. $curl->setopt(CURLOPT_SSL_VERIFYHOST, 2); # Check server's CN. $curl->setopt(CURLOPT_SSLKEY, $options{k}) if defined($options{k}); $curl->setopt(CURLOPT_SSLKEYPASSWD, $options{p}) if defined($options{p}); $curl->setopt(CURLOPT_SSLCERT, $options{c}) if defined($options{c}); $curl->setopt(CURLOPT_CAINFO, $options{C}) if defined($options{C}); $curl->setopt(CURLOPT_CAPATH, $options{P}) if defined($options{P}); $curl->setopt(CURLOPT_RANDOM_FILE, $options{r}) if defined($options{r}); $curl->setopt(CURLOPT_EGDSOCKET, $options{g}) if defined($options{g}); # Setting destination. $curl->setopt(CURLOPT_URL, $url); return $curl; } # Send a request and returns the body back. sub get_timestamp { my $curl = shift; my $body = shift; my $ts_body; local $::error_buf; # Error-handling related options. $curl->setopt(CURLOPT_ERRORBUFFER, "::error_buf"); # Options for POST method. $curl->setopt(CURLOPT_INFILE, {data => $body, bytes => 0}); $curl->setopt(CURLOPT_INFILESIZE, length(${$body})); # Options for getting the result. $curl->setopt(CURLOPT_FILE, \$ts_body); # Send the request... my $error_code = $curl->perform(); my $error_string; if ($error_code != 0) { my $http_code = $curl->getinfo(CURLINFO_HTTP_CODE); $error_string = "could not get timestamp"; $error_string .= ", http code: $http_code" unless $http_code == 0; $error_string .= ", curl code: $error_code"; $error_string .= " ($::error_buf)" if defined($::error_buf); } else { my $ct = $curl->getinfo(CURLINFO_CONTENT_TYPE); if (lc($ct) ne "application/timestamp-reply" && lc($ct) ne "application/timestamp-response") { $error_string = "unexpected content type returned: $ct"; } } return ($ts_body, $error_string); } # Print usage information and exists. sub usage { print STDERR "usage: $0 -h [-e ] [-o ] "; print STDERR "[-v] [-d] [-k ] [-p ] "; print STDERR "[-c ] [-C ] [-P ] "; print STDERR "[-r ] [-g ] []...\n"; exit 1; } # ---------------------------------------------------------------------- # Main program # ---------------------------------------------------------------------- # Getting command-line options (default comes from TSGET environment variable). my $getopt_arg = "h:e:o:vdk:p:c:C:P:r:g:"; if (exists $ENV{TSGET}) { my @old_argv = @ARGV; @ARGV = split /\s+/, $ENV{TSGET}; getopts($getopt_arg, \%options) or usage; @ARGV = @old_argv; } getopts($getopt_arg, \%options) or usage; # Checking argument consistency. if (!exists($options{h}) || (@ARGV == 0 && !exists($options{o})) || (@ARGV > 1 && exists($options{o}))) { print STDERR "Inconsistent command line options.\n"; usage; } # Setting defaults. @ARGV = ("-") unless @ARGV != 0; $options{e} = ".tsr" unless defined($options{e}); # Processing requests. my $curl = create_curl $options{h}; undef $/; # For reading whole files. REQUEST: foreach (@ARGV) { my $input = $_; my ($base, $path) = fileparse($input, '\.[^.]*'); my $output_base = $base . $options{e}; my $output = defined($options{o}) ? $options{o} : $path . $output_base; STDERR->printflush("$input: ") if $options{v}; # Read request. my $body; if ($input eq "-") { # Read the request from STDIN; $body = ; } else { # Read the request from file. open INPUT, "<" . $input or warn("$input: could not open input file: $!\n"), next REQUEST; $body = ; close INPUT or warn("$input: could not close input file: $!\n"), next REQUEST; } # Send request. STDERR->printflush("sending request") if $options{v}; my ($ts_body, $error) = get_timestamp $curl, \$body; if (defined($error)) { die "$input: fatal error: $error\n"; } STDERR->printflush(", reply received") if $options{v}; # Write response. if ($output eq "-") { # Write to STDOUT. print $ts_body; } else { # Write to file. open OUTPUT, ">", $output or warn("$output: could not open output file: $!\n"), next REQUEST; print OUTPUT $ts_body; close OUTPUT or warn("$output: could not close output file: $!\n"), next REQUEST; } STDERR->printflush(", $output written.\n") if $options{v}; } $curl->cleanup(); -WWW::Curl::Easy::global_cleanup(); Index: vendor-crypto/openssl/dist/crypto/asn1/Makefile =================================================================== --- vendor-crypto/openssl/dist/crypto/asn1/Makefile (revision 325325) +++ vendor-crypto/openssl/dist/crypto/asn1/Makefile (revision 325326) @@ -1,933 +1,933 @@ # # OpenSSL/crypto/asn1/Makefile # DIR= asn1 TOP= ../.. CC= cc INCLUDES= -I.. -I$(TOP) -I../../include CFLAG=-g MAKEFILE= Makefile AR= ar r CFLAGS= $(INCLUDES) $(CFLAG) GENERAL=Makefile README TEST= APPS= LIB=$(TOP)/libcrypto.a LIBSRC= a_object.c a_bitstr.c a_utctm.c a_gentm.c a_time.c a_int.c a_octet.c \ a_print.c a_type.c a_set.c a_dup.c a_d2i_fp.c a_i2d_fp.c \ a_enum.c a_utf8.c a_sign.c a_digest.c a_verify.c a_mbstr.c a_strex.c \ x_algor.c x_val.c x_pubkey.c x_sig.c x_req.c x_attrib.c x_bignum.c \ x_long.c x_name.c x_x509.c x_x509a.c x_crl.c x_info.c x_spki.c nsseq.c \ x_nx509.c d2i_pu.c d2i_pr.c i2d_pu.c i2d_pr.c\ t_req.c t_x509.c t_x509a.c t_crl.c t_pkey.c t_spki.c t_bitst.c \ tasn_new.c tasn_fre.c tasn_enc.c tasn_dec.c tasn_utl.c tasn_typ.c \ tasn_prn.c ameth_lib.c \ f_int.c f_string.c n_pkey.c \ f_enum.c x_pkey.c a_bool.c x_exten.c bio_asn1.c bio_ndef.c asn_mime.c \ asn1_gen.c asn1_par.c asn1_lib.c asn1_err.c a_bytes.c a_strnid.c \ evp_asn1.c asn_pack.c p5_pbe.c p5_pbev2.c p8_pkey.c asn_moid.c LIBOBJ= a_object.o a_bitstr.o a_utctm.o a_gentm.o a_time.o a_int.o a_octet.o \ a_print.o a_type.o a_set.o a_dup.o a_d2i_fp.o a_i2d_fp.o \ a_enum.o a_utf8.o a_sign.o a_digest.o a_verify.o a_mbstr.o a_strex.o \ x_algor.o x_val.o x_pubkey.o x_sig.o x_req.o x_attrib.o x_bignum.o \ x_long.o x_name.o x_x509.o x_x509a.o x_crl.o x_info.o x_spki.o nsseq.o \ x_nx509.o d2i_pu.o d2i_pr.o i2d_pu.o i2d_pr.o \ t_req.o t_x509.o t_x509a.o t_crl.o t_pkey.o t_spki.o t_bitst.o \ tasn_new.o tasn_fre.o tasn_enc.o tasn_dec.o tasn_utl.o tasn_typ.o \ tasn_prn.o ameth_lib.o \ f_int.o f_string.o n_pkey.o \ f_enum.o x_pkey.o a_bool.o x_exten.o bio_asn1.o bio_ndef.o asn_mime.o \ asn1_gen.o asn1_par.o asn1_lib.o asn1_err.o a_bytes.o a_strnid.o \ evp_asn1.o asn_pack.o p5_pbe.o p5_pbev2.o p8_pkey.o asn_moid.o SRC= $(LIBSRC) EXHEADER= asn1.h asn1_mac.h asn1t.h HEADER= $(EXHEADER) asn1_locl.h ALL= $(GENERAL) $(SRC) $(HEADER) top: (cd ../..; $(MAKE) DIRS=crypto SDIRS=$(DIR) sub_all) test: test.c cc -g -I../../include -c test.c cc -g -I../../include -o test test.o -L../.. -lcrypto pk: pk.c cc -g -I../../include -c pk.c cc -g -I../../include -o pk pk.o -L../.. -lcrypto all: lib lib: $(LIBOBJ) $(AR) $(LIB) $(LIBOBJ) $(RANLIB) $(LIB) || echo Never mind. @touch lib 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 top 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 *.o *.obj lib tags core .pure .nfs* *.old *.bak fluff # DO NOT DELETE THIS LINE -- make depend depends on it. a_bitstr.o: ../../e_os.h ../../include/openssl/asn1.h a_bitstr.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h a_bitstr.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h a_bitstr.o: ../../include/openssl/err.h ../../include/openssl/lhash.h a_bitstr.o: ../../include/openssl/opensslconf.h a_bitstr.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h a_bitstr.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h a_bitstr.o: ../../include/openssl/symhacks.h ../cryptlib.h a_bitstr.c a_bool.o: ../../e_os.h ../../include/openssl/asn1.h a_bool.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h a_bool.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h a_bool.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h a_bool.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h a_bool.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h a_bool.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h a_bool.o: ../../include/openssl/symhacks.h ../cryptlib.h a_bool.c a_bytes.o: ../../e_os.h ../../include/openssl/asn1.h a_bytes.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h a_bytes.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h a_bytes.o: ../../include/openssl/err.h ../../include/openssl/lhash.h a_bytes.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h a_bytes.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h a_bytes.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h a_bytes.o: ../cryptlib.h a_bytes.c a_d2i_fp.o: ../../e_os.h ../../include/openssl/asn1.h a_d2i_fp.o: ../../include/openssl/asn1_mac.h ../../include/openssl/bio.h a_d2i_fp.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h a_d2i_fp.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h a_d2i_fp.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h a_d2i_fp.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h a_d2i_fp.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h a_d2i_fp.o: ../../include/openssl/symhacks.h ../cryptlib.h a_d2i_fp.c a_digest.o: ../../e_os.h ../../include/openssl/asn1.h a_digest.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h a_digest.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h a_digest.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h a_digest.o: ../../include/openssl/ecdsa.h ../../include/openssl/err.h a_digest.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h a_digest.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h a_digest.o: ../../include/openssl/opensslconf.h a_digest.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h a_digest.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h a_digest.o: ../../include/openssl/sha.h ../../include/openssl/stack.h a_digest.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h a_digest.o: ../../include/openssl/x509_vfy.h ../cryptlib.h a_digest.c a_dup.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h a_dup.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h a_dup.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h a_dup.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h a_dup.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h a_dup.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h a_dup.o: ../../include/openssl/symhacks.h ../cryptlib.h a_dup.c a_enum.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h a_enum.o: ../../include/openssl/bn.h ../../include/openssl/buffer.h a_enum.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h a_enum.o: ../../include/openssl/err.h ../../include/openssl/lhash.h a_enum.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h a_enum.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h a_enum.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h a_enum.o: ../cryptlib.h a_enum.c a_gentm.o: ../../e_os.h ../../include/openssl/asn1.h a_gentm.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h a_gentm.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h a_gentm.o: ../../include/openssl/err.h ../../include/openssl/lhash.h a_gentm.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h a_gentm.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h a_gentm.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h a_gentm.o: ../cryptlib.h ../o_time.h a_gentm.c asn1_locl.h a_i2d_fp.o: ../../e_os.h ../../include/openssl/asn1.h a_i2d_fp.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h a_i2d_fp.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h a_i2d_fp.o: ../../include/openssl/err.h ../../include/openssl/lhash.h a_i2d_fp.o: ../../include/openssl/opensslconf.h a_i2d_fp.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h a_i2d_fp.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h a_i2d_fp.o: ../../include/openssl/symhacks.h ../cryptlib.h a_i2d_fp.c a_int.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h a_int.o: ../../include/openssl/bn.h ../../include/openssl/buffer.h a_int.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h a_int.o: ../../include/openssl/err.h ../../include/openssl/lhash.h a_int.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h a_int.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h a_int.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h a_int.o: ../cryptlib.h a_int.c a_mbstr.o: ../../e_os.h ../../include/openssl/asn1.h a_mbstr.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h a_mbstr.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h a_mbstr.o: ../../include/openssl/err.h ../../include/openssl/lhash.h a_mbstr.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h a_mbstr.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h a_mbstr.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h a_mbstr.o: ../cryptlib.h a_mbstr.c a_object.o: ../../e_os.h ../../include/openssl/asn1.h a_object.o: ../../include/openssl/bio.h ../../include/openssl/bn.h a_object.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h a_object.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h a_object.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h a_object.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h a_object.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h a_object.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h a_object.o: ../../include/openssl/symhacks.h ../cryptlib.h a_object.c a_octet.o: ../../e_os.h ../../include/openssl/asn1.h a_octet.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h a_octet.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h a_octet.o: ../../include/openssl/err.h ../../include/openssl/lhash.h a_octet.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h a_octet.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h a_octet.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h a_octet.o: ../cryptlib.h a_octet.c a_print.o: ../../e_os.h ../../include/openssl/asn1.h a_print.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h a_print.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h a_print.o: ../../include/openssl/err.h ../../include/openssl/lhash.h a_print.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h a_print.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h a_print.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h a_print.o: ../cryptlib.h a_print.c a_set.o: ../../e_os.h ../../include/openssl/asn1.h a_set.o: ../../include/openssl/asn1_mac.h ../../include/openssl/bio.h a_set.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h a_set.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h a_set.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h a_set.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h a_set.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h a_set.o: ../../include/openssl/symhacks.h ../cryptlib.h a_set.c a_sign.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h a_sign.o: ../../include/openssl/bn.h ../../include/openssl/buffer.h a_sign.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h a_sign.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h a_sign.o: ../../include/openssl/ecdsa.h ../../include/openssl/err.h a_sign.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h a_sign.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h a_sign.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h a_sign.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h a_sign.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h a_sign.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h a_sign.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h a_sign.o: ../cryptlib.h a_sign.c asn1_locl.h a_strex.o: ../../e_os.h ../../include/openssl/asn1.h a_strex.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h a_strex.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h a_strex.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h a_strex.o: ../../include/openssl/ecdsa.h ../../include/openssl/err.h a_strex.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h a_strex.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h a_strex.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h a_strex.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h a_strex.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h a_strex.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h a_strex.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h a_strex.o: ../cryptlib.h a_strex.c charmap.h a_strnid.o: ../../e_os.h ../../include/openssl/asn1.h a_strnid.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h a_strnid.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h a_strnid.o: ../../include/openssl/err.h ../../include/openssl/lhash.h a_strnid.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h a_strnid.o: ../../include/openssl/opensslconf.h a_strnid.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h a_strnid.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h a_strnid.o: ../../include/openssl/symhacks.h ../cryptlib.h a_strnid.c a_time.o: ../../e_os.h ../../include/openssl/asn1.h a_time.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h a_time.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h a_time.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h a_time.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h a_time.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h a_time.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h a_time.o: ../../include/openssl/symhacks.h ../cryptlib.h ../o_time.h a_time.c a_time.o: asn1_locl.h a_type.o: ../../e_os.h ../../include/openssl/asn1.h a_type.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h a_type.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h a_type.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h a_type.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h a_type.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h a_type.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h a_type.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h a_type.o: ../../include/openssl/symhacks.h ../cryptlib.h a_type.c a_utctm.o: ../../e_os.h ../../include/openssl/asn1.h a_utctm.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h a_utctm.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h a_utctm.o: ../../include/openssl/err.h ../../include/openssl/lhash.h a_utctm.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h a_utctm.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h a_utctm.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h a_utctm.o: ../cryptlib.h ../o_time.h a_utctm.c asn1_locl.h a_utf8.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h a_utf8.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h a_utf8.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h a_utf8.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h a_utf8.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h a_utf8.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h a_utf8.o: ../../include/openssl/symhacks.h ../cryptlib.h a_utf8.c a_verify.o: ../../e_os.h ../../include/openssl/asn1.h a_verify.o: ../../include/openssl/bio.h ../../include/openssl/bn.h a_verify.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h a_verify.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h a_verify.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h a_verify.o: ../../include/openssl/err.h ../../include/openssl/evp.h a_verify.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h a_verify.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h a_verify.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h a_verify.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h a_verify.o: ../../include/openssl/sha.h ../../include/openssl/stack.h a_verify.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h a_verify.o: ../../include/openssl/x509_vfy.h ../cryptlib.h a_verify.c a_verify.o: asn1_locl.h ameth_lib.o: ../../e_os.h ../../include/openssl/asn1.h ameth_lib.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h ameth_lib.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h ameth_lib.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h ameth_lib.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h ameth_lib.o: ../../include/openssl/engine.h ../../include/openssl/err.h ameth_lib.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h ameth_lib.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h ameth_lib.o: ../../include/openssl/opensslconf.h ameth_lib.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h ameth_lib.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h ameth_lib.o: ../../include/openssl/sha.h ../../include/openssl/stack.h ameth_lib.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h ameth_lib.o: ../../include/openssl/x509_vfy.h ../cryptlib.h ameth_lib.c ameth_lib.o: asn1_locl.h asn1_err.o: ../../include/openssl/asn1.h ../../include/openssl/bio.h asn1_err.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h asn1_err.o: ../../include/openssl/err.h ../../include/openssl/lhash.h asn1_err.o: ../../include/openssl/opensslconf.h asn1_err.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h asn1_err.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h asn1_err.o: ../../include/openssl/symhacks.h asn1_err.c asn1_gen.o: ../../e_os.h ../../include/openssl/asn1.h asn1_gen.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h asn1_gen.o: ../../include/openssl/conf.h ../../include/openssl/crypto.h asn1_gen.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h asn1_gen.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h asn1_gen.o: ../../include/openssl/err.h ../../include/openssl/evp.h asn1_gen.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h asn1_gen.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h asn1_gen.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h asn1_gen.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h asn1_gen.o: ../../include/openssl/sha.h ../../include/openssl/stack.h asn1_gen.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h asn1_gen.o: ../../include/openssl/x509_vfy.h ../../include/openssl/x509v3.h asn1_gen.o: ../cryptlib.h asn1_gen.c asn1_lib.o: ../../e_os.h ../../include/openssl/asn1.h asn1_lib.o: ../../include/openssl/asn1_mac.h ../../include/openssl/bio.h asn1_lib.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h asn1_lib.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h asn1_lib.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h asn1_lib.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h asn1_lib.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h asn1_lib.o: ../../include/openssl/symhacks.h ../cryptlib.h asn1_lib.c asn1_par.o: ../../e_os.h ../../include/openssl/asn1.h asn1_par.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h asn1_par.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h asn1_par.o: ../../include/openssl/err.h ../../include/openssl/lhash.h asn1_par.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h asn1_par.o: ../../include/openssl/opensslconf.h asn1_par.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h asn1_par.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h asn1_par.o: ../../include/openssl/symhacks.h ../cryptlib.h asn1_par.c asn_mime.o: ../../e_os.h ../../include/openssl/asn1.h asn_mime.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h asn_mime.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h asn_mime.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h asn_mime.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h asn_mime.o: ../../include/openssl/err.h ../../include/openssl/evp.h asn_mime.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h asn_mime.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h asn_mime.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h asn_mime.o: ../../include/openssl/pkcs7.h ../../include/openssl/rand.h asn_mime.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h asn_mime.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h asn_mime.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h asn_mime.o: ../cryptlib.h asn1_locl.h asn_mime.c asn_moid.o: ../../e_os.h ../../include/openssl/asn1.h asn_moid.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h asn_moid.o: ../../include/openssl/conf.h ../../include/openssl/crypto.h asn_moid.o: ../../include/openssl/dso.h ../../include/openssl/e_os2.h asn_moid.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h asn_moid.o: ../../include/openssl/ecdsa.h ../../include/openssl/err.h asn_moid.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h asn_moid.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h asn_moid.o: ../../include/openssl/opensslconf.h asn_moid.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h asn_moid.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h asn_moid.o: ../../include/openssl/sha.h ../../include/openssl/stack.h asn_moid.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h asn_moid.o: ../../include/openssl/x509_vfy.h ../cryptlib.h asn_moid.c asn_pack.o: ../../e_os.h ../../include/openssl/asn1.h asn_pack.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h asn_pack.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h asn_pack.o: ../../include/openssl/err.h ../../include/openssl/lhash.h asn_pack.o: ../../include/openssl/opensslconf.h asn_pack.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h asn_pack.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h asn_pack.o: ../../include/openssl/symhacks.h ../cryptlib.h asn_pack.c bio_asn1.o: ../../include/openssl/asn1.h ../../include/openssl/bio.h bio_asn1.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h bio_asn1.o: ../../include/openssl/opensslconf.h bio_asn1.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h bio_asn1.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h bio_asn1.o: ../../include/openssl/symhacks.h bio_asn1.c bio_ndef.o: ../../include/openssl/asn1.h ../../include/openssl/asn1t.h bio_ndef.o: ../../include/openssl/bio.h ../../include/openssl/crypto.h bio_ndef.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h bio_ndef.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h bio_ndef.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h bio_ndef.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h bio_ndef.o: ../../include/openssl/symhacks.h bio_ndef.c d2i_pr.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h d2i_pr.o: ../../include/openssl/bn.h ../../include/openssl/buffer.h d2i_pr.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h d2i_pr.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h d2i_pr.o: ../../include/openssl/ecdsa.h ../../include/openssl/engine.h d2i_pr.o: ../../include/openssl/err.h ../../include/openssl/evp.h d2i_pr.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h d2i_pr.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h d2i_pr.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h d2i_pr.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h d2i_pr.o: ../../include/openssl/sha.h ../../include/openssl/stack.h d2i_pr.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h d2i_pr.o: ../../include/openssl/x509_vfy.h ../cryptlib.h asn1_locl.h d2i_pr.c d2i_pu.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h d2i_pu.o: ../../include/openssl/bn.h ../../include/openssl/buffer.h d2i_pu.o: ../../include/openssl/crypto.h ../../include/openssl/dsa.h d2i_pu.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h d2i_pu.o: ../../include/openssl/err.h ../../include/openssl/evp.h d2i_pu.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h d2i_pu.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h d2i_pu.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h d2i_pu.o: ../../include/openssl/rsa.h ../../include/openssl/safestack.h d2i_pu.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h d2i_pu.o: ../cryptlib.h d2i_pu.c evp_asn1.o: ../../e_os.h ../../include/openssl/asn1.h evp_asn1.o: ../../include/openssl/asn1_mac.h ../../include/openssl/bio.h evp_asn1.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h evp_asn1.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h evp_asn1.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h evp_asn1.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h evp_asn1.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h evp_asn1.o: ../../include/openssl/symhacks.h ../cryptlib.h evp_asn1.c f_enum.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h f_enum.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h f_enum.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h f_enum.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h f_enum.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h f_enum.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h f_enum.o: ../../include/openssl/symhacks.h ../cryptlib.h f_enum.c f_int.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h f_int.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h f_int.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h f_int.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h f_int.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h f_int.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h f_int.o: ../../include/openssl/symhacks.h ../cryptlib.h f_int.c f_string.o: ../../e_os.h ../../include/openssl/asn1.h f_string.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h f_string.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h f_string.o: ../../include/openssl/err.h ../../include/openssl/lhash.h f_string.o: ../../include/openssl/opensslconf.h f_string.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h f_string.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h f_string.o: ../../include/openssl/symhacks.h ../cryptlib.h f_string.c i2d_pr.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h i2d_pr.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h i2d_pr.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h i2d_pr.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h i2d_pr.o: ../../include/openssl/err.h ../../include/openssl/evp.h i2d_pr.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h i2d_pr.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h i2d_pr.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h i2d_pr.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h i2d_pr.o: ../../include/openssl/sha.h ../../include/openssl/stack.h i2d_pr.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h i2d_pr.o: ../../include/openssl/x509_vfy.h ../cryptlib.h asn1_locl.h i2d_pr.c i2d_pu.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h i2d_pu.o: ../../include/openssl/bn.h ../../include/openssl/buffer.h i2d_pu.o: ../../include/openssl/crypto.h ../../include/openssl/dsa.h i2d_pu.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h i2d_pu.o: ../../include/openssl/err.h ../../include/openssl/evp.h i2d_pu.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h i2d_pu.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h i2d_pu.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h i2d_pu.o: ../../include/openssl/rsa.h ../../include/openssl/safestack.h i2d_pu.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h i2d_pu.o: ../cryptlib.h i2d_pu.c n_pkey.o: ../../e_os.h ../../include/openssl/asn1.h n_pkey.o: ../../include/openssl/asn1_mac.h ../../include/openssl/asn1t.h n_pkey.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h n_pkey.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h n_pkey.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h n_pkey.o: ../../include/openssl/ecdsa.h ../../include/openssl/err.h n_pkey.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h n_pkey.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h n_pkey.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h n_pkey.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h n_pkey.o: ../../include/openssl/rsa.h ../../include/openssl/safestack.h n_pkey.o: ../../include/openssl/sha.h ../../include/openssl/stack.h n_pkey.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h n_pkey.o: ../../include/openssl/x509_vfy.h ../cryptlib.h n_pkey.c nsseq.o: ../../include/openssl/asn1.h ../../include/openssl/asn1t.h nsseq.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h nsseq.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h nsseq.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h nsseq.o: ../../include/openssl/ecdsa.h ../../include/openssl/evp.h nsseq.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h nsseq.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h nsseq.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h nsseq.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h nsseq.o: ../../include/openssl/sha.h ../../include/openssl/stack.h nsseq.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h nsseq.o: ../../include/openssl/x509_vfy.h nsseq.c p5_pbe.o: ../../e_os.h ../../include/openssl/asn1.h p5_pbe.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h p5_pbe.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h p5_pbe.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h p5_pbe.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h p5_pbe.o: ../../include/openssl/err.h ../../include/openssl/evp.h p5_pbe.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h p5_pbe.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h p5_pbe.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h p5_pbe.o: ../../include/openssl/pkcs7.h ../../include/openssl/rand.h p5_pbe.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h p5_pbe.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h p5_pbe.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h p5_pbe.o: ../cryptlib.h p5_pbe.c p5_pbev2.o: ../../e_os.h ../../include/openssl/asn1.h p5_pbev2.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h p5_pbev2.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h p5_pbev2.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h p5_pbev2.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h p5_pbev2.o: ../../include/openssl/err.h ../../include/openssl/evp.h p5_pbev2.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h p5_pbev2.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h p5_pbev2.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h p5_pbev2.o: ../../include/openssl/pkcs7.h ../../include/openssl/rand.h p5_pbev2.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h p5_pbev2.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h p5_pbev2.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h p5_pbev2.o: ../cryptlib.h p5_pbev2.c p8_pkey.o: ../../e_os.h ../../include/openssl/asn1.h p8_pkey.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h p8_pkey.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h p8_pkey.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h p8_pkey.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h p8_pkey.o: ../../include/openssl/err.h ../../include/openssl/evp.h p8_pkey.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h p8_pkey.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h p8_pkey.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h p8_pkey.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h p8_pkey.o: ../../include/openssl/sha.h ../../include/openssl/stack.h p8_pkey.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h p8_pkey.o: ../../include/openssl/x509_vfy.h ../cryptlib.h p8_pkey.c t_bitst.o: ../../e_os.h ../../include/openssl/asn1.h t_bitst.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h t_bitst.o: ../../include/openssl/conf.h ../../include/openssl/crypto.h t_bitst.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h t_bitst.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h t_bitst.o: ../../include/openssl/err.h ../../include/openssl/evp.h t_bitst.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h t_bitst.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h t_bitst.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h t_bitst.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h t_bitst.o: ../../include/openssl/sha.h ../../include/openssl/stack.h t_bitst.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h t_bitst.o: ../../include/openssl/x509_vfy.h ../../include/openssl/x509v3.h t_bitst.o: ../cryptlib.h t_bitst.c t_crl.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h t_crl.o: ../../include/openssl/bn.h ../../include/openssl/buffer.h t_crl.o: ../../include/openssl/conf.h ../../include/openssl/crypto.h t_crl.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h t_crl.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h t_crl.o: ../../include/openssl/err.h ../../include/openssl/evp.h t_crl.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h t_crl.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h t_crl.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h t_crl.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h t_crl.o: ../../include/openssl/sha.h ../../include/openssl/stack.h t_crl.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h t_crl.o: ../../include/openssl/x509_vfy.h ../../include/openssl/x509v3.h t_crl.o: ../cryptlib.h t_crl.c t_pkey.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h t_pkey.o: ../../include/openssl/bn.h ../../include/openssl/buffer.h t_pkey.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h t_pkey.o: ../../include/openssl/err.h ../../include/openssl/lhash.h t_pkey.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h t_pkey.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h t_pkey.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h t_pkey.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h t_pkey.o: ../cryptlib.h t_pkey.c t_req.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h t_req.o: ../../include/openssl/bn.h ../../include/openssl/buffer.h t_req.o: ../../include/openssl/conf.h ../../include/openssl/crypto.h t_req.o: ../../include/openssl/dsa.h ../../include/openssl/e_os2.h t_req.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h t_req.o: ../../include/openssl/ecdsa.h ../../include/openssl/err.h t_req.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h t_req.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h t_req.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h t_req.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h t_req.o: ../../include/openssl/rsa.h ../../include/openssl/safestack.h t_req.o: ../../include/openssl/sha.h ../../include/openssl/stack.h t_req.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h t_req.o: ../../include/openssl/x509_vfy.h ../../include/openssl/x509v3.h t_req.o: ../cryptlib.h t_req.c t_spki.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h t_spki.o: ../../include/openssl/bn.h ../../include/openssl/buffer.h t_spki.o: ../../include/openssl/crypto.h ../../include/openssl/dsa.h t_spki.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h t_spki.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h t_spki.o: ../../include/openssl/err.h ../../include/openssl/evp.h t_spki.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h t_spki.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h t_spki.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h t_spki.o: ../../include/openssl/pkcs7.h ../../include/openssl/rsa.h t_spki.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h t_spki.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h t_spki.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h t_spki.o: ../cryptlib.h t_spki.c t_x509.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h t_x509.o: ../../include/openssl/bn.h ../../include/openssl/buffer.h t_x509.o: ../../include/openssl/conf.h ../../include/openssl/crypto.h t_x509.o: ../../include/openssl/dsa.h ../../include/openssl/e_os2.h t_x509.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h t_x509.o: ../../include/openssl/ecdsa.h ../../include/openssl/err.h t_x509.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h t_x509.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h t_x509.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h t_x509.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h t_x509.o: ../../include/openssl/rsa.h ../../include/openssl/safestack.h t_x509.o: ../../include/openssl/sha.h ../../include/openssl/stack.h t_x509.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h t_x509.o: ../../include/openssl/x509_vfy.h ../../include/openssl/x509v3.h t_x509.o: ../cryptlib.h asn1_locl.h t_x509.c t_x509a.o: ../../e_os.h ../../include/openssl/asn1.h t_x509a.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h t_x509a.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h t_x509a.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h t_x509a.o: ../../include/openssl/ecdsa.h ../../include/openssl/err.h t_x509a.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h t_x509a.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h t_x509a.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h t_x509a.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h t_x509a.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h t_x509a.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h t_x509a.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h t_x509a.o: ../cryptlib.h t_x509a.c tasn_dec.o: ../../include/openssl/asn1.h ../../include/openssl/asn1t.h tasn_dec.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h tasn_dec.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h tasn_dec.o: ../../include/openssl/err.h ../../include/openssl/lhash.h tasn_dec.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h tasn_dec.o: ../../include/openssl/opensslconf.h tasn_dec.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h tasn_dec.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h tasn_dec.o: ../../include/openssl/symhacks.h tasn_dec.c tasn_enc.o: ../../e_os.h ../../include/openssl/asn1.h tasn_enc.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h tasn_enc.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h tasn_enc.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h tasn_enc.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h tasn_enc.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h tasn_enc.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h tasn_enc.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h tasn_enc.o: ../../include/openssl/symhacks.h ../cryptlib.h tasn_enc.c tasn_fre.o: ../../include/openssl/asn1.h ../../include/openssl/asn1t.h tasn_fre.o: ../../include/openssl/bio.h ../../include/openssl/crypto.h tasn_fre.o: ../../include/openssl/e_os2.h ../../include/openssl/obj_mac.h tasn_fre.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h tasn_fre.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h tasn_fre.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h -tasn_fre.o: ../../include/openssl/symhacks.h tasn_fre.c +tasn_fre.o: ../../include/openssl/symhacks.h asn1_int.h tasn_fre.c tasn_new.o: ../../include/openssl/asn1.h ../../include/openssl/asn1t.h tasn_new.o: ../../include/openssl/bio.h ../../include/openssl/crypto.h tasn_new.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h tasn_new.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h tasn_new.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h tasn_new.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h tasn_new.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h -tasn_new.o: ../../include/openssl/symhacks.h tasn_new.c +tasn_new.o: ../../include/openssl/symhacks.h asn1_int.h tasn_new.c tasn_prn.o: ../../e_os.h ../../include/openssl/asn1.h tasn_prn.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h tasn_prn.o: ../../include/openssl/buffer.h ../../include/openssl/conf.h tasn_prn.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h tasn_prn.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h tasn_prn.o: ../../include/openssl/ecdsa.h ../../include/openssl/err.h tasn_prn.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h tasn_prn.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h tasn_prn.o: ../../include/openssl/opensslconf.h tasn_prn.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h tasn_prn.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h tasn_prn.o: ../../include/openssl/sha.h ../../include/openssl/stack.h tasn_prn.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h tasn_prn.o: ../../include/openssl/x509_vfy.h ../../include/openssl/x509v3.h tasn_prn.o: ../cryptlib.h asn1_locl.h tasn_prn.c tasn_typ.o: ../../include/openssl/asn1.h ../../include/openssl/asn1t.h tasn_typ.o: ../../include/openssl/bio.h ../../include/openssl/crypto.h tasn_typ.o: ../../include/openssl/e_os2.h ../../include/openssl/opensslconf.h tasn_typ.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h tasn_typ.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h tasn_typ.o: ../../include/openssl/symhacks.h tasn_typ.c tasn_utl.o: ../../include/openssl/asn1.h ../../include/openssl/asn1t.h tasn_utl.o: ../../include/openssl/bio.h ../../include/openssl/crypto.h tasn_utl.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h tasn_utl.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h tasn_utl.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h tasn_utl.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h tasn_utl.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h tasn_utl.o: ../../include/openssl/symhacks.h tasn_utl.c x_algor.o: ../../include/openssl/asn1.h ../../include/openssl/asn1t.h x_algor.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h x_algor.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h x_algor.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h x_algor.o: ../../include/openssl/ecdsa.h ../../include/openssl/evp.h x_algor.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h x_algor.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h x_algor.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h x_algor.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h x_algor.o: ../../include/openssl/sha.h ../../include/openssl/stack.h x_algor.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h x_algor.o: ../../include/openssl/x509_vfy.h x_algor.c x_attrib.o: ../../e_os.h ../../include/openssl/asn1.h x_attrib.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h x_attrib.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h x_attrib.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h x_attrib.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h x_attrib.o: ../../include/openssl/err.h ../../include/openssl/evp.h x_attrib.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h x_attrib.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h x_attrib.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h x_attrib.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h x_attrib.o: ../../include/openssl/sha.h ../../include/openssl/stack.h x_attrib.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h x_attrib.o: ../../include/openssl/x509_vfy.h ../cryptlib.h x_attrib.c x_bignum.o: ../../e_os.h ../../include/openssl/asn1.h x_bignum.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h x_bignum.o: ../../include/openssl/bn.h ../../include/openssl/buffer.h x_bignum.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h x_bignum.o: ../../include/openssl/err.h ../../include/openssl/lhash.h x_bignum.o: ../../include/openssl/opensslconf.h x_bignum.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h x_bignum.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h x_bignum.o: ../../include/openssl/symhacks.h ../cryptlib.h x_bignum.c x_crl.o: ../../e_os.h ../../include/openssl/asn1.h x_crl.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h x_crl.o: ../../include/openssl/buffer.h ../../include/openssl/conf.h x_crl.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h x_crl.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h x_crl.o: ../../include/openssl/ecdsa.h ../../include/openssl/err.h x_crl.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h x_crl.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h x_crl.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h x_crl.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h x_crl.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h x_crl.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h x_crl.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h x_crl.o: ../../include/openssl/x509v3.h ../cryptlib.h asn1_locl.h x_crl.c x_exten.o: ../../include/openssl/asn1.h ../../include/openssl/asn1t.h x_exten.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h x_exten.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h x_exten.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h x_exten.o: ../../include/openssl/ecdsa.h ../../include/openssl/evp.h x_exten.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h x_exten.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h x_exten.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h x_exten.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h x_exten.o: ../../include/openssl/sha.h ../../include/openssl/stack.h x_exten.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h x_exten.o: ../../include/openssl/x509_vfy.h x_exten.c x_info.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h x_info.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h x_info.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h x_info.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h x_info.o: ../../include/openssl/err.h ../../include/openssl/evp.h x_info.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h x_info.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h x_info.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h x_info.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h x_info.o: ../../include/openssl/sha.h ../../include/openssl/stack.h x_info.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h x_info.o: ../../include/openssl/x509_vfy.h ../cryptlib.h x_info.c x_long.o: ../../e_os.h ../../include/openssl/asn1.h x_long.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h x_long.o: ../../include/openssl/bn.h ../../include/openssl/buffer.h x_long.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h x_long.o: ../../include/openssl/err.h ../../include/openssl/lhash.h x_long.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h x_long.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h x_long.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h x_long.o: ../cryptlib.h x_long.c x_name.o: ../../e_os.h ../../include/openssl/asn1.h x_name.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h x_name.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h x_name.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h x_name.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h x_name.o: ../../include/openssl/err.h ../../include/openssl/evp.h x_name.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h x_name.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h x_name.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h x_name.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h x_name.o: ../../include/openssl/sha.h ../../include/openssl/stack.h x_name.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h x_name.o: ../../include/openssl/x509_vfy.h ../cryptlib.h asn1_locl.h x_name.c x_nx509.o: ../../include/openssl/asn1.h ../../include/openssl/asn1t.h x_nx509.o: ../../include/openssl/bio.h ../../include/openssl/buffer.h x_nx509.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h x_nx509.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h x_nx509.o: ../../include/openssl/ecdsa.h ../../include/openssl/evp.h x_nx509.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h x_nx509.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h x_nx509.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h x_nx509.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h x_nx509.o: ../../include/openssl/sha.h ../../include/openssl/stack.h x_nx509.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h x_nx509.o: ../../include/openssl/x509_vfy.h x_nx509.c x_pkey.o: ../../e_os.h ../../include/openssl/asn1.h x_pkey.o: ../../include/openssl/asn1_mac.h ../../include/openssl/bio.h x_pkey.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h x_pkey.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h x_pkey.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h x_pkey.o: ../../include/openssl/err.h ../../include/openssl/evp.h x_pkey.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h x_pkey.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h x_pkey.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h x_pkey.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h x_pkey.o: ../../include/openssl/sha.h ../../include/openssl/stack.h x_pkey.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h x_pkey.o: ../../include/openssl/x509_vfy.h ../cryptlib.h x_pkey.c x_pubkey.o: ../../e_os.h ../../include/openssl/asn1.h x_pubkey.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h x_pubkey.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h x_pubkey.o: ../../include/openssl/dsa.h ../../include/openssl/e_os2.h x_pubkey.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h x_pubkey.o: ../../include/openssl/ecdsa.h ../../include/openssl/err.h x_pubkey.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h x_pubkey.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h x_pubkey.o: ../../include/openssl/opensslconf.h x_pubkey.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h x_pubkey.o: ../../include/openssl/pkcs7.h ../../include/openssl/rsa.h x_pubkey.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h x_pubkey.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h x_pubkey.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h x_pubkey.o: ../cryptlib.h asn1_locl.h x_pubkey.c x_req.o: ../../e_os.h ../../include/openssl/asn1.h x_req.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h x_req.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h x_req.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h x_req.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h x_req.o: ../../include/openssl/err.h ../../include/openssl/evp.h x_req.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h x_req.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h x_req.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h x_req.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h x_req.o: ../../include/openssl/sha.h ../../include/openssl/stack.h x_req.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h x_req.o: ../../include/openssl/x509_vfy.h ../cryptlib.h x_req.c x_sig.o: ../../e_os.h ../../include/openssl/asn1.h x_sig.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h x_sig.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h x_sig.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h x_sig.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h x_sig.o: ../../include/openssl/err.h ../../include/openssl/evp.h x_sig.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h x_sig.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h x_sig.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h x_sig.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h x_sig.o: ../../include/openssl/sha.h ../../include/openssl/stack.h x_sig.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h x_sig.o: ../../include/openssl/x509_vfy.h ../cryptlib.h x_sig.c x_spki.o: ../../e_os.h ../../include/openssl/asn1.h x_spki.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h x_spki.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h x_spki.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h x_spki.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h x_spki.o: ../../include/openssl/err.h ../../include/openssl/evp.h x_spki.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h x_spki.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h x_spki.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h x_spki.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h x_spki.o: ../../include/openssl/sha.h ../../include/openssl/stack.h x_spki.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h x_spki.o: ../../include/openssl/x509_vfy.h ../cryptlib.h x_spki.c x_val.o: ../../e_os.h ../../include/openssl/asn1.h x_val.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h x_val.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h x_val.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h x_val.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h x_val.o: ../../include/openssl/err.h ../../include/openssl/evp.h x_val.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h x_val.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h x_val.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h x_val.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h x_val.o: ../../include/openssl/sha.h ../../include/openssl/stack.h x_val.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h x_val.o: ../../include/openssl/x509_vfy.h ../cryptlib.h x_val.c x_x509.o: ../../e_os.h ../../include/openssl/asn1.h x_x509.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h x_x509.o: ../../include/openssl/buffer.h ../../include/openssl/conf.h x_x509.o: ../../include/openssl/crypto.h ../../include/openssl/e_os2.h x_x509.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h x_x509.o: ../../include/openssl/ecdsa.h ../../include/openssl/err.h x_x509.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h x_x509.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h x_x509.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h x_x509.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h x_x509.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h x_x509.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h x_x509.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h x_x509.o: ../../include/openssl/x509v3.h ../cryptlib.h x_x509.c x_x509a.o: ../../e_os.h ../../include/openssl/asn1.h x_x509a.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h x_x509a.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h x_x509a.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h x_x509a.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h x_x509a.o: ../../include/openssl/err.h ../../include/openssl/evp.h x_x509a.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h x_x509a.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h x_x509a.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h x_x509a.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h x_x509a.o: ../../include/openssl/sha.h ../../include/openssl/stack.h x_x509a.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h x_x509a.o: ../../include/openssl/x509_vfy.h ../cryptlib.h x_x509a.c Index: vendor-crypto/openssl/dist/crypto/asn1/a_bitstr.c =================================================================== --- vendor-crypto/openssl/dist/crypto/asn1/a_bitstr.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/asn1/a_bitstr.c (revision 325326) @@ -1,263 +1,269 @@ /* 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 #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; 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 (len > INT_MAX) { + i = ASN1_R_STRING_TOO_LONG; 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/asn1_int.h =================================================================== --- vendor-crypto/openssl/dist/crypto/asn1/asn1_int.h (nonexistent) +++ vendor-crypto/openssl/dist/crypto/asn1/asn1_int.h (revision 325326) @@ -0,0 +1,63 @@ +/* asn1t.h */ +/* + * 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). + * + */ + +/* Internal ASN1 template structures and functions: not for application use */ + +void asn1_item_combine_free(ASN1_VALUE **pval, const ASN1_ITEM *it, + int combine); Property changes on: vendor-crypto/openssl/dist/crypto/asn1/asn1_int.h ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: vendor-crypto/openssl/dist/crypto/asn1/tasn_fre.c =================================================================== --- vendor-crypto/openssl/dist/crypto/asn1/tasn_fre.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/asn1/tasn_fre.c (revision 325326) @@ -1,249 +1,246 @@ /* tasn_fre.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 #include #include +#include "asn1_int.h" -static void asn1_item_combine_free(ASN1_VALUE **pval, const ASN1_ITEM *it, - int combine); - /* Free up an ASN1 structure */ void ASN1_item_free(ASN1_VALUE *val, const ASN1_ITEM *it) { asn1_item_combine_free(&val, it, 0); } void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it) { asn1_item_combine_free(pval, it, 0); } -static void asn1_item_combine_free(ASN1_VALUE **pval, const ASN1_ITEM *it, - int combine) +void asn1_item_combine_free(ASN1_VALUE **pval, const ASN1_ITEM *it, int combine) { const ASN1_TEMPLATE *tt = NULL, *seqtt; const ASN1_EXTERN_FUNCS *ef; const ASN1_COMPAT_FUNCS *cf; const ASN1_AUX *aux = it->funcs; ASN1_aux_cb *asn1_cb; int i; if (!pval) return; if ((it->itype != ASN1_ITYPE_PRIMITIVE) && !*pval) return; if (aux && aux->asn1_cb) asn1_cb = aux->asn1_cb; else asn1_cb = 0; switch (it->itype) { case ASN1_ITYPE_PRIMITIVE: if (it->templates) ASN1_template_free(pval, it->templates); else ASN1_primitive_free(pval, it); break; case ASN1_ITYPE_MSTRING: ASN1_primitive_free(pval, it); break; case ASN1_ITYPE_CHOICE: if (asn1_cb) { i = asn1_cb(ASN1_OP_FREE_PRE, pval, it, NULL); if (i == 2) return; } i = asn1_get_choice_selector(pval, it); if ((i >= 0) && (i < it->tcount)) { ASN1_VALUE **pchval; tt = it->templates + i; pchval = asn1_get_field_ptr(pval, tt); ASN1_template_free(pchval, tt); } if (asn1_cb) asn1_cb(ASN1_OP_FREE_POST, pval, it, NULL); if (!combine) { OPENSSL_free(*pval); *pval = NULL; } break; case ASN1_ITYPE_COMPAT: cf = it->funcs; if (cf && cf->asn1_free) cf->asn1_free(*pval); break; case ASN1_ITYPE_EXTERN: ef = it->funcs; if (ef && ef->asn1_ex_free) ef->asn1_ex_free(pval, it); break; case ASN1_ITYPE_NDEF_SEQUENCE: case ASN1_ITYPE_SEQUENCE: if (asn1_do_lock(pval, -1, it) > 0) return; if (asn1_cb) { i = asn1_cb(ASN1_OP_FREE_PRE, pval, it, NULL); if (i == 2) return; } asn1_enc_free(pval, it); /* * If we free up as normal we will invalidate any ANY DEFINED BY * field and we wont be able to determine the type of the field it * defines. So free up in reverse order. */ tt = it->templates + it->tcount - 1; for (i = 0; i < it->tcount; tt--, i++) { ASN1_VALUE **pseqval; seqtt = asn1_do_adb(pval, tt, 0); if (!seqtt) continue; pseqval = asn1_get_field_ptr(pval, seqtt); ASN1_template_free(pseqval, seqtt); } if (asn1_cb) asn1_cb(ASN1_OP_FREE_POST, pval, it, NULL); if (!combine) { OPENSSL_free(*pval); *pval = NULL; } break; } } void ASN1_template_free(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt) { int i; if (tt->flags & ASN1_TFLG_SK_MASK) { STACK_OF(ASN1_VALUE) *sk = (STACK_OF(ASN1_VALUE) *)*pval; for (i = 0; i < sk_ASN1_VALUE_num(sk); i++) { ASN1_VALUE *vtmp; vtmp = sk_ASN1_VALUE_value(sk, i); asn1_item_combine_free(&vtmp, ASN1_ITEM_ptr(tt->item), 0); } sk_ASN1_VALUE_free(sk); *pval = NULL; } else asn1_item_combine_free(pval, ASN1_ITEM_ptr(tt->item), tt->flags & ASN1_TFLG_COMBINE); } void ASN1_primitive_free(ASN1_VALUE **pval, const ASN1_ITEM *it) { int utype; if (it) { const ASN1_PRIMITIVE_FUNCS *pf; pf = it->funcs; if (pf && pf->prim_free) { pf->prim_free(pval, it); return; } } /* Special case: if 'it' is NULL free contents of ASN1_TYPE */ if (!it) { ASN1_TYPE *typ = (ASN1_TYPE *)*pval; utype = typ->type; pval = &typ->value.asn1_value; if (!*pval) return; } else if (it->itype == ASN1_ITYPE_MSTRING) { utype = -1; if (!*pval) return; } else { utype = it->utype; if ((utype != V_ASN1_BOOLEAN) && !*pval) return; } switch (utype) { case V_ASN1_OBJECT: ASN1_OBJECT_free((ASN1_OBJECT *)*pval); break; case V_ASN1_BOOLEAN: if (it) *(ASN1_BOOLEAN *)pval = it->size; else *(ASN1_BOOLEAN *)pval = -1; return; case V_ASN1_NULL: break; case V_ASN1_ANY: ASN1_primitive_free(pval, NULL); OPENSSL_free(*pval); break; default: ASN1_STRING_free((ASN1_STRING *)*pval); *pval = NULL; break; } *pval = NULL; } Index: vendor-crypto/openssl/dist/crypto/asn1/tasn_new.c =================================================================== --- vendor-crypto/openssl/dist/crypto/asn1/tasn_new.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/asn1/tasn_new.c (revision 325326) @@ -1,384 +1,385 @@ /* 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 +#include "asn1_int.h" 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 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 memerr2; } if (asn1_cb && !asn1_cb(ASN1_OP_NEW_POST, pval, it, NULL)) goto auxerr2; break; } #ifdef CRYPTO_MDEBUG if (it->sname) CRYPTO_pop_info(); #endif return 1; memerr2: - ASN1_item_ex_free(pval, it); + asn1_item_combine_free(pval, it, combine); 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); + asn1_item_combine_free(pval, it, combine); auxerr: ASN1err(ASN1_F_ASN1_ITEM_EX_COMBINE_NEW, ASN1_R_AUX_ERROR); #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_name.c =================================================================== --- vendor-crypto/openssl/dist/crypto/asn1/x_name.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/asn1/x_name.c (revision 325326) @@ -1,543 +1,535 @@ /* 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); } } 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 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)) { 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)) { 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); + if ((name = X509_NAME_dup(name)) == NULL) + return 0; + X509_NAME_free(*xn); + *xn = name; + return 1; } IMPLEMENT_STACK_OF(X509_NAME_ENTRY) IMPLEMENT_ASN1_SET_OF(X509_NAME_ENTRY) Index: vendor-crypto/openssl/dist/crypto/asn1/x_pkey.c =================================================================== --- vendor-crypto/openssl/dist/crypto/asn1/x_pkey.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/asn1/x_pkey.c (revision 325326) @@ -1,153 +1,164 @@ /* crypto/asn1/x_pkey.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 #include /* need to implement */ int i2d_X509_PKEY(X509_PKEY *a, unsigned char **pp) { return (0); } X509_PKEY *d2i_X509_PKEY(X509_PKEY **a, const unsigned char **pp, long length) { int i; M_ASN1_D2I_vars(a, X509_PKEY *, X509_PKEY_new); M_ASN1_D2I_Init(); M_ASN1_D2I_start_sequence(); M_ASN1_D2I_get_x(X509_ALGOR, ret->enc_algor, d2i_X509_ALGOR); M_ASN1_D2I_get_x(ASN1_OCTET_STRING, ret->enc_pkey, d2i_ASN1_OCTET_STRING); ret->cipher.cipher = EVP_get_cipherbyname(OBJ_nid2ln (OBJ_obj2nid(ret->enc_algor->algorithm))); if (ret->cipher.cipher == NULL) { c.error = ASN1_R_UNSUPPORTED_CIPHER; c.line = __LINE__; goto err; } if (ret->enc_algor->parameter->type == V_ASN1_OCTET_STRING) { i = ret->enc_algor->parameter->value.octet_string->length; if (i > EVP_MAX_IV_LENGTH) { c.error = ASN1_R_IV_TOO_LARGE; c.line = __LINE__; goto err; } memcpy(ret->cipher.iv, ret->enc_algor->parameter->value.octet_string->data, i); } else memset(ret->cipher.iv, 0, EVP_MAX_IV_LENGTH); M_ASN1_D2I_Finish(a, X509_PKEY_free, ASN1_F_D2I_X509_PKEY); } X509_PKEY *X509_PKEY_new(void) { X509_PKEY *ret = NULL; ASN1_CTX c; - M_ASN1_New_Malloc(ret, X509_PKEY); + ret = OPENSSL_malloc(sizeof(X509_PKEY)); + if (ret == NULL) { + c.line = __LINE__; + goto err; + } ret->version = 0; - M_ASN1_New(ret->enc_algor, X509_ALGOR_new); - M_ASN1_New(ret->enc_pkey, M_ASN1_OCTET_STRING_new); + ret->enc_algor = X509_ALGOR_new(); + ret->enc_pkey = M_ASN1_OCTET_STRING_new(); ret->dec_pkey = NULL; ret->key_length = 0; ret->key_data = NULL; ret->key_free = 0; ret->cipher.cipher = NULL; memset(ret->cipher.iv, 0, EVP_MAX_IV_LENGTH); ret->references = 1; - return (ret); - M_ASN1_New_Error(ASN1_F_X509_PKEY_NEW); + if (ret->enc_algor == NULL || ret->enc_pkey == NULL) { + c.line = __LINE__; + goto err; + } + return ret; +err: + X509_PKEY_free(ret); + ASN1_MAC_H_err(ASN1_F_X509_PKEY_NEW, ERR_R_MALLOC_FAILURE, c.line); + return NULL; } void X509_PKEY_free(X509_PKEY *x) { int i; if (x == NULL) return; i = CRYPTO_add(&x->references, -1, CRYPTO_LOCK_X509_PKEY); #ifdef REF_PRINT REF_PRINT("X509_PKEY", x); #endif if (i > 0) return; #ifdef REF_CHECK if (i < 0) { fprintf(stderr, "X509_PKEY_free, bad reference count\n"); abort(); } #endif if (x->enc_algor != NULL) X509_ALGOR_free(x->enc_algor); if (x->enc_pkey != NULL) M_ASN1_OCTET_STRING_free(x->enc_pkey); if (x->dec_pkey != NULL) EVP_PKEY_free(x->dec_pkey); if ((x->key_data != NULL) && (x->key_free)) OPENSSL_free(x->key_data); OPENSSL_free(x); } Index: vendor-crypto/openssl/dist/crypto/bn/asm/x86_64-mont5.pl =================================================================== --- vendor-crypto/openssl/dist/crypto/bn/asm/x86_64-mont5.pl (revision 325325) +++ vendor-crypto/openssl/dist/crypto/bn/asm/x86_64-mont5.pl (revision 325326) @@ -1,3818 +1,3826 @@ #!/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/. # ==================================================================== # August 2011. # # Companion to x86_64-mont.pl that optimizes cache-timing attack # countermeasures. The subroutines are produced by replacing bp[i] # references in their x86_64-mont.pl counterparts with cache-neutral # references to powers table computed in BN_mod_exp_mont_consttime. # In addition subroutine that scatters elements of the powers table # is implemented, so that scatter-/gathering can be tuned without # bn_exp.c modifications. # August 2013. # # Add MULX/AD*X code paths and additional interfaces to optimize for # branch prediction unit. For input lengths that are multiples of 8 # the np argument is not just modulus value, but one interleaved # with 0. This is to optimize post-condition... $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; if (`$ENV{CC} -Wa,-v -c -o /dev/null -x assembler /dev/null 2>&1` =~ /GNU assembler version ([2-9]\.[0-9]+)/) { $addx = ($1>=2.23); } if (!$addx && $win64 && ($flavour =~ /nasm/ || $ENV{ASM} =~ /nasm/) && `nasm -v 2>&1` =~ /NASM version ([2-9]\.[0-9]+)/) { $addx = ($1>=2.10); } if (!$addx && $win64 && ($flavour =~ /masm/ || $ENV{ASM} =~ /ml64/) && `ml64 2>&1` =~ /Version ([0-9]+)\./) { $addx = ($1>=12); } if (!$addx && `$ENV{CC} -v 2>&1` =~ /((?:^clang|LLVM) version|.*based on LLVM) ([3-9])\.([0-9]+)/) { my $ver = $2 + $3/100.0; # 3.1->3.01, 3.10->3.10 $addx = ($ver>=3.03); } # int bn_mul_mont_gather5( $rp="%rdi"; # BN_ULONG *rp, $ap="%rsi"; # const BN_ULONG *ap, $bp="%rdx"; # const BN_ULONG *bp, $np="%rcx"; # const BN_ULONG *np, $n0="%r8"; # const BN_ULONG *n0, $num="%r9"; # int num, # int idx); # 0 to 2^5-1, "index" in $bp holding # pre-computed powers of a', interlaced # in such manner that b[0] is $bp[idx], # b[1] is [2^5+idx], etc. $lo0="%r10"; $hi0="%r11"; $hi1="%r13"; $i="%r14"; $j="%r15"; $m0="%rbx"; $m1="%rbp"; $code=<<___; .text .extern OPENSSL_ia32cap_P .globl bn_mul_mont_gather5 .type bn_mul_mont_gather5,\@function,6 .align 64 bn_mul_mont_gather5: mov ${num}d,${num}d mov %rsp,%rax test \$7,${num}d jnz .Lmul_enter ___ $code.=<<___ if ($addx); mov OPENSSL_ia32cap_P+8(%rip),%r11d ___ $code.=<<___; jmp .Lmul4x_enter .align 16 .Lmul_enter: movd `($win64?56:8)`(%rsp),%xmm5 # load 7th argument push %rbx push %rbp push %r12 push %r13 push %r14 push %r15 neg $num mov %rsp,%r11 lea -280(%rsp,$num,8),%r10 # future alloca(8*(num+2)+256+8) neg $num # restore $num and \$-1024,%r10 # minimize TLB usage # Some OSes, *cough*-dows, insist on stack being "wired" to # physical memory in strictly sequential manner, i.e. if stack # allocation spans two pages, then reference to farmost one can # be punishable by SEGV. But page walking can do good even on # other OSes, because it guarantees that villain thread hits # the guard page before it can make damage to innocent one... sub %r10,%r11 and \$-4096,%r11 lea (%r10,%r11),%rsp mov (%rsp),%r11 cmp %r10,%rsp ja .Lmul_page_walk jmp .Lmul_page_walk_done .Lmul_page_walk: lea -4096(%rsp),%rsp mov (%rsp),%r11 cmp %r10,%rsp ja .Lmul_page_walk .Lmul_page_walk_done: lea .Linc(%rip),%r10 mov %rax,8(%rsp,$num,8) # tp[num+1]=%rsp .Lmul_body: lea 128($bp),%r12 # reassign $bp (+size optimization) ___ $bp="%r12"; $STRIDE=2**5*8; # 5 is "window size" $N=$STRIDE/4; # should match cache line size $code.=<<___; movdqa 0(%r10),%xmm0 # 00000001000000010000000000000000 movdqa 16(%r10),%xmm1 # 00000002000000020000000200000002 lea 24-112(%rsp,$num,8),%r10# place the mask after tp[num+3] (+ICache optimization) and \$-16,%r10 pshufd \$0,%xmm5,%xmm5 # broadcast index movdqa %xmm1,%xmm4 movdqa %xmm1,%xmm2 ___ ######################################################################## # calculate mask by comparing 0..31 to index and save result to stack # $code.=<<___; paddd %xmm0,%xmm1 pcmpeqd %xmm5,%xmm0 # compare to 1,0 .byte 0x67 movdqa %xmm4,%xmm3 ___ for($k=0;$k<$STRIDE/16-4;$k+=4) { $code.=<<___; paddd %xmm1,%xmm2 pcmpeqd %xmm5,%xmm1 # compare to 3,2 movdqa %xmm0,`16*($k+0)+112`(%r10) movdqa %xmm4,%xmm0 paddd %xmm2,%xmm3 pcmpeqd %xmm5,%xmm2 # compare to 5,4 movdqa %xmm1,`16*($k+1)+112`(%r10) movdqa %xmm4,%xmm1 paddd %xmm3,%xmm0 pcmpeqd %xmm5,%xmm3 # compare to 7,6 movdqa %xmm2,`16*($k+2)+112`(%r10) movdqa %xmm4,%xmm2 paddd %xmm0,%xmm1 pcmpeqd %xmm5,%xmm0 movdqa %xmm3,`16*($k+3)+112`(%r10) movdqa %xmm4,%xmm3 ___ } $code.=<<___; # last iteration can be optimized paddd %xmm1,%xmm2 pcmpeqd %xmm5,%xmm1 movdqa %xmm0,`16*($k+0)+112`(%r10) paddd %xmm2,%xmm3 .byte 0x67 pcmpeqd %xmm5,%xmm2 movdqa %xmm1,`16*($k+1)+112`(%r10) pcmpeqd %xmm5,%xmm3 movdqa %xmm2,`16*($k+2)+112`(%r10) pand `16*($k+0)-128`($bp),%xmm0 # while it's still in register pand `16*($k+1)-128`($bp),%xmm1 pand `16*($k+2)-128`($bp),%xmm2 movdqa %xmm3,`16*($k+3)+112`(%r10) pand `16*($k+3)-128`($bp),%xmm3 por %xmm2,%xmm0 por %xmm3,%xmm1 ___ for($k=0;$k<$STRIDE/16-4;$k+=4) { $code.=<<___; movdqa `16*($k+0)-128`($bp),%xmm4 movdqa `16*($k+1)-128`($bp),%xmm5 movdqa `16*($k+2)-128`($bp),%xmm2 pand `16*($k+0)+112`(%r10),%xmm4 movdqa `16*($k+3)-128`($bp),%xmm3 pand `16*($k+1)+112`(%r10),%xmm5 por %xmm4,%xmm0 pand `16*($k+2)+112`(%r10),%xmm2 por %xmm5,%xmm1 pand `16*($k+3)+112`(%r10),%xmm3 por %xmm2,%xmm0 por %xmm3,%xmm1 ___ } $code.=<<___; por %xmm1,%xmm0 pshufd \$0x4e,%xmm0,%xmm1 por %xmm1,%xmm0 lea $STRIDE($bp),$bp movq %xmm0,$m0 # m0=bp[0] mov ($n0),$n0 # pull n0[0] value mov ($ap),%rax xor $i,$i # i=0 xor $j,$j # j=0 mov $n0,$m1 mulq $m0 # ap[0]*bp[0] mov %rax,$lo0 mov ($np),%rax imulq $lo0,$m1 # "tp[0]"*n0 mov %rdx,$hi0 mulq $m1 # np[0]*m1 add %rax,$lo0 # discarded mov 8($ap),%rax adc \$0,%rdx mov %rdx,$hi1 lea 1($j),$j # j++ jmp .L1st_enter .align 16 .L1st: add %rax,$hi1 mov ($ap,$j,8),%rax adc \$0,%rdx add $hi0,$hi1 # np[j]*m1+ap[j]*bp[0] mov $lo0,$hi0 adc \$0,%rdx mov $hi1,-16(%rsp,$j,8) # tp[j-1] mov %rdx,$hi1 .L1st_enter: mulq $m0 # ap[j]*bp[0] add %rax,$hi0 mov ($np,$j,8),%rax adc \$0,%rdx lea 1($j),$j # j++ mov %rdx,$lo0 mulq $m1 # np[j]*m1 cmp $num,$j jne .L1st # note that upon exit $j==$num, so # they can be used interchangeably add %rax,$hi1 adc \$0,%rdx add $hi0,$hi1 # np[j]*m1+ap[j]*bp[0] adc \$0,%rdx mov $hi1,-16(%rsp,$num,8) # tp[num-1] mov %rdx,$hi1 mov $lo0,$hi0 xor %rdx,%rdx add $hi0,$hi1 adc \$0,%rdx mov $hi1,-8(%rsp,$num,8) mov %rdx,(%rsp,$num,8) # store upmost overflow bit lea 1($i),$i # i++ jmp .Louter .align 16 .Louter: lea 24+128(%rsp,$num,8),%rdx # where 256-byte mask is (+size optimization) and \$-16,%rdx pxor %xmm4,%xmm4 pxor %xmm5,%xmm5 ___ for($k=0;$k<$STRIDE/16;$k+=4) { $code.=<<___; movdqa `16*($k+0)-128`($bp),%xmm0 movdqa `16*($k+1)-128`($bp),%xmm1 movdqa `16*($k+2)-128`($bp),%xmm2 movdqa `16*($k+3)-128`($bp),%xmm3 pand `16*($k+0)-128`(%rdx),%xmm0 pand `16*($k+1)-128`(%rdx),%xmm1 por %xmm0,%xmm4 pand `16*($k+2)-128`(%rdx),%xmm2 por %xmm1,%xmm5 pand `16*($k+3)-128`(%rdx),%xmm3 por %xmm2,%xmm4 por %xmm3,%xmm5 ___ } $code.=<<___; por %xmm5,%xmm4 pshufd \$0x4e,%xmm4,%xmm0 por %xmm4,%xmm0 lea $STRIDE($bp),$bp mov ($ap),%rax # ap[0] movq %xmm0,$m0 # m0=bp[i] xor $j,$j # j=0 mov $n0,$m1 mov (%rsp),$lo0 mulq $m0 # ap[0]*bp[i] add %rax,$lo0 # ap[0]*bp[i]+tp[0] mov ($np),%rax adc \$0,%rdx imulq $lo0,$m1 # tp[0]*n0 mov %rdx,$hi0 mulq $m1 # np[0]*m1 add %rax,$lo0 # discarded mov 8($ap),%rax adc \$0,%rdx mov 8(%rsp),$lo0 # tp[1] mov %rdx,$hi1 lea 1($j),$j # j++ jmp .Linner_enter .align 16 .Linner: add %rax,$hi1 mov ($ap,$j,8),%rax adc \$0,%rdx add $lo0,$hi1 # np[j]*m1+ap[j]*bp[i]+tp[j] mov (%rsp,$j,8),$lo0 adc \$0,%rdx mov $hi1,-16(%rsp,$j,8) # tp[j-1] mov %rdx,$hi1 .Linner_enter: mulq $m0 # ap[j]*bp[i] add %rax,$hi0 mov ($np,$j,8),%rax adc \$0,%rdx add $hi0,$lo0 # ap[j]*bp[i]+tp[j] mov %rdx,$hi0 adc \$0,$hi0 lea 1($j),$j # j++ mulq $m1 # np[j]*m1 cmp $num,$j jne .Linner # note that upon exit $j==$num, so # they can be used interchangeably add %rax,$hi1 adc \$0,%rdx add $lo0,$hi1 # np[j]*m1+ap[j]*bp[i]+tp[j] mov (%rsp,$num,8),$lo0 adc \$0,%rdx mov $hi1,-16(%rsp,$num,8) # tp[num-1] mov %rdx,$hi1 xor %rdx,%rdx add $hi0,$hi1 adc \$0,%rdx add $lo0,$hi1 # pull upmost overflow bit adc \$0,%rdx mov $hi1,-8(%rsp,$num,8) mov %rdx,(%rsp,$num,8) # store upmost overflow bit lea 1($i),$i # i++ cmp $num,$i jb .Louter xor $i,$i # i=0 and clear CF! mov (%rsp),%rax # tp[0] lea (%rsp),$ap # borrow ap for tp mov $num,$j # j=num jmp .Lsub .align 16 .Lsub: sbb ($np,$i,8),%rax mov %rax,($rp,$i,8) # rp[i]=tp[i]-np[i] mov 8($ap,$i,8),%rax # tp[i+1] lea 1($i),$i # i++ dec $j # doesnn't affect CF! jnz .Lsub sbb \$0,%rax # handle upmost overflow bit xor $i,$i and %rax,$ap not %rax mov $rp,$np and %rax,$np mov $num,$j # j=num or $np,$ap # ap=borrow?tp:rp .align 16 .Lcopy: # copy or in-place refresh mov ($ap,$i,8),%rax mov $i,(%rsp,$i,8) # zap temporary vector mov %rax,($rp,$i,8) # rp[i]=tp[i] lea 1($i),$i sub \$1,$j jnz .Lcopy mov 8(%rsp,$num,8),%rsi # restore %rsp mov \$1,%rax mov -48(%rsi),%r15 mov -40(%rsi),%r14 mov -32(%rsi),%r13 mov -24(%rsi),%r12 mov -16(%rsi),%rbp mov -8(%rsi),%rbx lea (%rsi),%rsp .Lmul_epilogue: ret .size bn_mul_mont_gather5,.-bn_mul_mont_gather5 ___ {{{ my @A=("%r10","%r11"); my @N=("%r13","%rdi"); $code.=<<___; .type bn_mul4x_mont_gather5,\@function,6 .align 32 bn_mul4x_mont_gather5: .byte 0x67 mov %rsp,%rax .Lmul4x_enter: ___ $code.=<<___ if ($addx); and \$0x80108,%r11d cmp \$0x80108,%r11d # check for AD*X+BMI2+BMI1 je .Lmulx4x_enter ___ $code.=<<___; push %rbx push %rbp push %r12 push %r13 push %r14 push %r15 .Lmul4x_prologue: .byte 0x67 shl \$3,${num}d # convert $num to bytes lea ($num,$num,2),%r10 # 3*$num in bytes neg $num # -$num ############################################################## # Ensure that stack frame doesn't alias with $rptr+3*$num # modulo 4096, which covers ret[num], am[num] and n[num] # (see bn_exp.c). This is done to allow memory disambiguation # logic do its magic. [Extra [num] is allocated in order # to align with bn_power5's frame, which is cleansed after # completing exponentiation. Extra 256 bytes is for power mask # calculated from 7th argument, the index.] # lea -320(%rsp,$num,2),%r11 mov %rsp,%rbp sub $rp,%r11 and \$4095,%r11 cmp %r11,%r10 jb .Lmul4xsp_alt sub %r11,%rbp # align with $rp lea -320(%rbp,$num,2),%rbp # future alloca(frame+2*num*8+256) jmp .Lmul4xsp_done .align 32 .Lmul4xsp_alt: lea 4096-320(,$num,2),%r10 lea -320(%rbp,$num,2),%rbp # future alloca(frame+2*num*8+256) sub %r10,%r11 mov \$0,%r10 cmovc %r10,%r11 sub %r11,%rbp .Lmul4xsp_done: and \$-64,%rbp mov %rsp,%r11 sub %rbp,%r11 and \$-4096,%r11 lea (%rbp,%r11),%rsp mov (%rsp),%r10 cmp %rbp,%rsp ja .Lmul4x_page_walk jmp .Lmul4x_page_walk_done .Lmul4x_page_walk: lea -4096(%rsp),%rsp mov (%rsp),%r10 cmp %rbp,%rsp ja .Lmul4x_page_walk .Lmul4x_page_walk_done: neg $num mov %rax,40(%rsp) .Lmul4x_body: call mul4x_internal mov 40(%rsp),%rsi # restore %rsp mov \$1,%rax mov -48(%rsi),%r15 mov -40(%rsi),%r14 mov -32(%rsi),%r13 mov -24(%rsi),%r12 mov -16(%rsi),%rbp mov -8(%rsi),%rbx lea (%rsi),%rsp .Lmul4x_epilogue: ret .size bn_mul4x_mont_gather5,.-bn_mul4x_mont_gather5 .type mul4x_internal,\@abi-omnipotent .align 32 mul4x_internal: shl \$5,$num # $num was in bytes movd `($win64?56:8)`(%rax),%xmm5 # load 7th argument, index lea .Linc(%rip),%rax lea 128(%rdx,$num),%r13 # end of powers table (+size optimization) shr \$5,$num # restore $num ___ $bp="%r12"; $STRIDE=2**5*8; # 5 is "window size" $N=$STRIDE/4; # should match cache line size $tp=$i; $code.=<<___; movdqa 0(%rax),%xmm0 # 00000001000000010000000000000000 movdqa 16(%rax),%xmm1 # 00000002000000020000000200000002 lea 88-112(%rsp,$num),%r10 # place the mask after tp[num+1] (+ICache optimization) lea 128(%rdx),$bp # size optimization pshufd \$0,%xmm5,%xmm5 # broadcast index movdqa %xmm1,%xmm4 .byte 0x67,0x67 movdqa %xmm1,%xmm2 ___ ######################################################################## # calculate mask by comparing 0..31 to index and save result to stack # $code.=<<___; paddd %xmm0,%xmm1 pcmpeqd %xmm5,%xmm0 # compare to 1,0 .byte 0x67 movdqa %xmm4,%xmm3 ___ for($i=0;$i<$STRIDE/16-4;$i+=4) { $code.=<<___; paddd %xmm1,%xmm2 pcmpeqd %xmm5,%xmm1 # compare to 3,2 movdqa %xmm0,`16*($i+0)+112`(%r10) movdqa %xmm4,%xmm0 paddd %xmm2,%xmm3 pcmpeqd %xmm5,%xmm2 # compare to 5,4 movdqa %xmm1,`16*($i+1)+112`(%r10) movdqa %xmm4,%xmm1 paddd %xmm3,%xmm0 pcmpeqd %xmm5,%xmm3 # compare to 7,6 movdqa %xmm2,`16*($i+2)+112`(%r10) movdqa %xmm4,%xmm2 paddd %xmm0,%xmm1 pcmpeqd %xmm5,%xmm0 movdqa %xmm3,`16*($i+3)+112`(%r10) movdqa %xmm4,%xmm3 ___ } $code.=<<___; # last iteration can be optimized paddd %xmm1,%xmm2 pcmpeqd %xmm5,%xmm1 movdqa %xmm0,`16*($i+0)+112`(%r10) paddd %xmm2,%xmm3 .byte 0x67 pcmpeqd %xmm5,%xmm2 movdqa %xmm1,`16*($i+1)+112`(%r10) pcmpeqd %xmm5,%xmm3 movdqa %xmm2,`16*($i+2)+112`(%r10) pand `16*($i+0)-128`($bp),%xmm0 # while it's still in register pand `16*($i+1)-128`($bp),%xmm1 pand `16*($i+2)-128`($bp),%xmm2 movdqa %xmm3,`16*($i+3)+112`(%r10) pand `16*($i+3)-128`($bp),%xmm3 por %xmm2,%xmm0 por %xmm3,%xmm1 ___ for($i=0;$i<$STRIDE/16-4;$i+=4) { $code.=<<___; movdqa `16*($i+0)-128`($bp),%xmm4 movdqa `16*($i+1)-128`($bp),%xmm5 movdqa `16*($i+2)-128`($bp),%xmm2 pand `16*($i+0)+112`(%r10),%xmm4 movdqa `16*($i+3)-128`($bp),%xmm3 pand `16*($i+1)+112`(%r10),%xmm5 por %xmm4,%xmm0 pand `16*($i+2)+112`(%r10),%xmm2 por %xmm5,%xmm1 pand `16*($i+3)+112`(%r10),%xmm3 por %xmm2,%xmm0 por %xmm3,%xmm1 ___ } $code.=<<___; por %xmm1,%xmm0 pshufd \$0x4e,%xmm0,%xmm1 por %xmm1,%xmm0 lea $STRIDE($bp),$bp movq %xmm0,$m0 # m0=bp[0] mov %r13,16+8(%rsp) # save end of b[num] mov $rp, 56+8(%rsp) # save $rp mov ($n0),$n0 # pull n0[0] value mov ($ap),%rax lea ($ap,$num),$ap # end of a[num] neg $num mov $n0,$m1 mulq $m0 # ap[0]*bp[0] mov %rax,$A[0] mov ($np),%rax imulq $A[0],$m1 # "tp[0]"*n0 lea 64+8(%rsp),$tp mov %rdx,$A[1] mulq $m1 # np[0]*m1 add %rax,$A[0] # discarded mov 8($ap,$num),%rax adc \$0,%rdx mov %rdx,$N[1] mulq $m0 add %rax,$A[1] mov 8*1($np),%rax adc \$0,%rdx mov %rdx,$A[0] mulq $m1 add %rax,$N[1] mov 16($ap,$num),%rax adc \$0,%rdx add $A[1],$N[1] lea 4*8($num),$j # j=4 lea 8*4($np),$np adc \$0,%rdx mov $N[1],($tp) mov %rdx,$N[0] jmp .L1st4x .align 32 .L1st4x: mulq $m0 # ap[j]*bp[0] add %rax,$A[0] mov -8*2($np),%rax lea 32($tp),$tp adc \$0,%rdx mov %rdx,$A[1] mulq $m1 # np[j]*m1 add %rax,$N[0] mov -8($ap,$j),%rax adc \$0,%rdx add $A[0],$N[0] # np[j]*m1+ap[j]*bp[0] adc \$0,%rdx mov $N[0],-24($tp) # tp[j-1] mov %rdx,$N[1] mulq $m0 # ap[j]*bp[0] add %rax,$A[1] mov -8*1($np),%rax adc \$0,%rdx mov %rdx,$A[0] mulq $m1 # np[j]*m1 add %rax,$N[1] mov ($ap,$j),%rax adc \$0,%rdx add $A[1],$N[1] # np[j]*m1+ap[j]*bp[0] adc \$0,%rdx mov $N[1],-16($tp) # tp[j-1] mov %rdx,$N[0] mulq $m0 # ap[j]*bp[0] add %rax,$A[0] mov 8*0($np),%rax adc \$0,%rdx mov %rdx,$A[1] mulq $m1 # np[j]*m1 add %rax,$N[0] mov 8($ap,$j),%rax adc \$0,%rdx add $A[0],$N[0] # np[j]*m1+ap[j]*bp[0] adc \$0,%rdx mov $N[0],-8($tp) # tp[j-1] mov %rdx,$N[1] mulq $m0 # ap[j]*bp[0] add %rax,$A[1] mov 8*1($np),%rax adc \$0,%rdx mov %rdx,$A[0] mulq $m1 # np[j]*m1 add %rax,$N[1] mov 16($ap,$j),%rax adc \$0,%rdx add $A[1],$N[1] # np[j]*m1+ap[j]*bp[0] lea 8*4($np),$np adc \$0,%rdx mov $N[1],($tp) # tp[j-1] mov %rdx,$N[0] add \$32,$j # j+=4 jnz .L1st4x mulq $m0 # ap[j]*bp[0] add %rax,$A[0] mov -8*2($np),%rax lea 32($tp),$tp adc \$0,%rdx mov %rdx,$A[1] mulq $m1 # np[j]*m1 add %rax,$N[0] mov -8($ap),%rax adc \$0,%rdx add $A[0],$N[0] # np[j]*m1+ap[j]*bp[0] adc \$0,%rdx mov $N[0],-24($tp) # tp[j-1] mov %rdx,$N[1] mulq $m0 # ap[j]*bp[0] add %rax,$A[1] mov -8*1($np),%rax adc \$0,%rdx mov %rdx,$A[0] mulq $m1 # np[j]*m1 add %rax,$N[1] mov ($ap,$num),%rax # ap[0] adc \$0,%rdx add $A[1],$N[1] # np[j]*m1+ap[j]*bp[0] adc \$0,%rdx mov $N[1],-16($tp) # tp[j-1] mov %rdx,$N[0] lea ($np,$num),$np # rewind $np xor $N[1],$N[1] add $A[0],$N[0] adc \$0,$N[1] mov $N[0],-8($tp) jmp .Louter4x .align 32 .Louter4x: lea 16+128($tp),%rdx # where 256-byte mask is (+size optimization) pxor %xmm4,%xmm4 pxor %xmm5,%xmm5 ___ for($i=0;$i<$STRIDE/16;$i+=4) { $code.=<<___; movdqa `16*($i+0)-128`($bp),%xmm0 movdqa `16*($i+1)-128`($bp),%xmm1 movdqa `16*($i+2)-128`($bp),%xmm2 movdqa `16*($i+3)-128`($bp),%xmm3 pand `16*($i+0)-128`(%rdx),%xmm0 pand `16*($i+1)-128`(%rdx),%xmm1 por %xmm0,%xmm4 pand `16*($i+2)-128`(%rdx),%xmm2 por %xmm1,%xmm5 pand `16*($i+3)-128`(%rdx),%xmm3 por %xmm2,%xmm4 por %xmm3,%xmm5 ___ } $code.=<<___; por %xmm5,%xmm4 pshufd \$0x4e,%xmm4,%xmm0 por %xmm4,%xmm0 lea $STRIDE($bp),$bp movq %xmm0,$m0 # m0=bp[i] mov ($tp,$num),$A[0] mov $n0,$m1 mulq $m0 # ap[0]*bp[i] add %rax,$A[0] # ap[0]*bp[i]+tp[0] mov ($np),%rax adc \$0,%rdx imulq $A[0],$m1 # tp[0]*n0 mov %rdx,$A[1] mov $N[1],($tp) # store upmost overflow bit lea ($tp,$num),$tp # rewind $tp mulq $m1 # np[0]*m1 add %rax,$A[0] # "$N[0]", discarded mov 8($ap,$num),%rax adc \$0,%rdx mov %rdx,$N[1] mulq $m0 # ap[j]*bp[i] add %rax,$A[1] mov 8*1($np),%rax adc \$0,%rdx add 8($tp),$A[1] # +tp[1] adc \$0,%rdx mov %rdx,$A[0] mulq $m1 # np[j]*m1 add %rax,$N[1] mov 16($ap,$num),%rax adc \$0,%rdx add $A[1],$N[1] # np[j]*m1+ap[j]*bp[i]+tp[j] lea 4*8($num),$j # j=4 lea 8*4($np),$np adc \$0,%rdx mov %rdx,$N[0] jmp .Linner4x .align 32 .Linner4x: mulq $m0 # ap[j]*bp[i] add %rax,$A[0] mov -8*2($np),%rax adc \$0,%rdx add 16($tp),$A[0] # ap[j]*bp[i]+tp[j] lea 32($tp),$tp adc \$0,%rdx mov %rdx,$A[1] mulq $m1 # np[j]*m1 add %rax,$N[0] mov -8($ap,$j),%rax adc \$0,%rdx add $A[0],$N[0] adc \$0,%rdx mov $N[1],-32($tp) # tp[j-1] mov %rdx,$N[1] mulq $m0 # ap[j]*bp[i] add %rax,$A[1] mov -8*1($np),%rax adc \$0,%rdx add -8($tp),$A[1] adc \$0,%rdx mov %rdx,$A[0] mulq $m1 # np[j]*m1 add %rax,$N[1] mov ($ap,$j),%rax adc \$0,%rdx add $A[1],$N[1] adc \$0,%rdx mov $N[0],-24($tp) # tp[j-1] mov %rdx,$N[0] mulq $m0 # ap[j]*bp[i] add %rax,$A[0] mov 8*0($np),%rax adc \$0,%rdx add ($tp),$A[0] # ap[j]*bp[i]+tp[j] adc \$0,%rdx mov %rdx,$A[1] mulq $m1 # np[j]*m1 add %rax,$N[0] mov 8($ap,$j),%rax adc \$0,%rdx add $A[0],$N[0] adc \$0,%rdx mov $N[1],-16($tp) # tp[j-1] mov %rdx,$N[1] mulq $m0 # ap[j]*bp[i] add %rax,$A[1] mov 8*1($np),%rax adc \$0,%rdx add 8($tp),$A[1] adc \$0,%rdx mov %rdx,$A[0] mulq $m1 # np[j]*m1 add %rax,$N[1] mov 16($ap,$j),%rax adc \$0,%rdx add $A[1],$N[1] lea 8*4($np),$np adc \$0,%rdx mov $N[0],-8($tp) # tp[j-1] mov %rdx,$N[0] add \$32,$j # j+=4 jnz .Linner4x mulq $m0 # ap[j]*bp[i] add %rax,$A[0] mov -8*2($np),%rax adc \$0,%rdx add 16($tp),$A[0] # ap[j]*bp[i]+tp[j] lea 32($tp),$tp adc \$0,%rdx mov %rdx,$A[1] mulq $m1 # np[j]*m1 add %rax,$N[0] mov -8($ap),%rax adc \$0,%rdx add $A[0],$N[0] adc \$0,%rdx mov $N[1],-32($tp) # tp[j-1] mov %rdx,$N[1] mulq $m0 # ap[j]*bp[i] add %rax,$A[1] mov $m1,%rax mov -8*1($np),$m1 adc \$0,%rdx add -8($tp),$A[1] adc \$0,%rdx mov %rdx,$A[0] mulq $m1 # np[j]*m1 add %rax,$N[1] mov ($ap,$num),%rax # ap[0] adc \$0,%rdx add $A[1],$N[1] adc \$0,%rdx mov $N[0],-24($tp) # tp[j-1] mov %rdx,$N[0] mov $N[1],-16($tp) # tp[j-1] lea ($np,$num),$np # rewind $np xor $N[1],$N[1] add $A[0],$N[0] adc \$0,$N[1] add ($tp),$N[0] # pull upmost overflow bit adc \$0,$N[1] # upmost overflow bit mov $N[0],-8($tp) cmp 16+8(%rsp),$bp jb .Louter4x ___ if (1) { $code.=<<___; xor %rax,%rax sub $N[0],$m1 # compare top-most words adc $j,$j # $j is zero or $j,$N[1] sub $N[1],%rax # %rax=-$N[1] lea ($tp,$num),%rbx # tptr in .sqr4x_sub mov ($np),%r12 lea ($np),%rbp # nptr in .sqr4x_sub mov %r9,%rcx sar \$3+2,%rcx mov 56+8(%rsp),%rdi # rptr in .sqr4x_sub dec %r12 # so that after 'not' we get -n[0] xor %r10,%r10 mov 8*1(%rbp),%r13 mov 8*2(%rbp),%r14 mov 8*3(%rbp),%r15 jmp .Lsqr4x_sub_entry ___ } else { my @ri=("%rax",$bp,$m0,$m1); my $rp="%rdx"; $code.=<<___ xor \$1,$N[1] lea ($tp,$num),$tp # rewind $tp sar \$5,$num # cf=0 lea ($np,$N[1],8),$np mov 56+8(%rsp),$rp # restore $rp jmp .Lsub4x .align 32 .Lsub4x: .byte 0x66 mov 8*0($tp),@ri[0] mov 8*1($tp),@ri[1] .byte 0x66 sbb 16*0($np),@ri[0] mov 8*2($tp),@ri[2] sbb 16*1($np),@ri[1] mov 3*8($tp),@ri[3] lea 4*8($tp),$tp sbb 16*2($np),@ri[2] mov @ri[0],8*0($rp) sbb 16*3($np),@ri[3] lea 16*4($np),$np mov @ri[1],8*1($rp) mov @ri[2],8*2($rp) mov @ri[3],8*3($rp) lea 8*4($rp),$rp inc $num jnz .Lsub4x ret ___ } $code.=<<___; .size mul4x_internal,.-mul4x_internal ___ }}} {{{ ###################################################################### # void bn_power5( my $rptr="%rdi"; # BN_ULONG *rptr, my $aptr="%rsi"; # const BN_ULONG *aptr, my $bptr="%rdx"; # const void *table, my $nptr="%rcx"; # const BN_ULONG *nptr, my $n0 ="%r8"; # const BN_ULONG *n0); my $num ="%r9"; # int num, has to be divisible by 8 # int pwr my ($i,$j,$tptr)=("%rbp","%rcx",$rptr); my @A0=("%r10","%r11"); my @A1=("%r12","%r13"); my ($a0,$a1,$ai)=("%r14","%r15","%rbx"); $code.=<<___; .globl bn_power5 .type bn_power5,\@function,6 .align 32 bn_power5: mov %rsp,%rax ___ $code.=<<___ if ($addx); mov OPENSSL_ia32cap_P+8(%rip),%r11d and \$0x80108,%r11d cmp \$0x80108,%r11d # check for AD*X+BMI2+BMI1 je .Lpowerx5_enter ___ $code.=<<___; push %rbx push %rbp push %r12 push %r13 push %r14 push %r15 .Lpower5_prologue: shl \$3,${num}d # convert $num to bytes lea ($num,$num,2),%r10d # 3*$num neg $num mov ($n0),$n0 # *n0 ############################################################## # Ensure that stack frame doesn't alias with $rptr+3*$num # modulo 4096, which covers ret[num], am[num] and n[num] # (see bn_exp.c). This is done to allow memory disambiguation # logic do its magic. [Extra 256 bytes is for power mask # calculated from 7th argument, the index.] # lea -320(%rsp,$num,2),%r11 mov %rsp,%rbp sub $rptr,%r11 and \$4095,%r11 cmp %r11,%r10 jb .Lpwr_sp_alt sub %r11,%rbp # align with $aptr lea -320(%rbp,$num,2),%rbp # future alloca(frame+2*num*8+256) jmp .Lpwr_sp_done .align 32 .Lpwr_sp_alt: lea 4096-320(,$num,2),%r10 lea -320(%rbp,$num,2),%rbp # future alloca(frame+2*num*8+256) sub %r10,%r11 mov \$0,%r10 cmovc %r10,%r11 sub %r11,%rbp .Lpwr_sp_done: and \$-64,%rbp mov %rsp,%r11 sub %rbp,%r11 and \$-4096,%r11 lea (%rbp,%r11),%rsp mov (%rsp),%r10 cmp %rbp,%rsp ja .Lpwr_page_walk jmp .Lpwr_page_walk_done .Lpwr_page_walk: lea -4096(%rsp),%rsp mov (%rsp),%r10 cmp %rbp,%rsp ja .Lpwr_page_walk .Lpwr_page_walk_done: mov $num,%r10 neg $num ############################################################## # Stack layout # # +0 saved $num, used in reduction section # +8 &t[2*$num], used in reduction section # +32 saved *n0 # +40 saved %rsp # +48 t[2*$num] # mov $n0, 32(%rsp) mov %rax, 40(%rsp) # save original %rsp .Lpower5_body: movq $rptr,%xmm1 # save $rptr, used in sqr8x movq $nptr,%xmm2 # save $nptr movq %r10, %xmm3 # -$num, used in sqr8x movq $bptr,%xmm4 call __bn_sqr8x_internal call __bn_post4x_internal call __bn_sqr8x_internal call __bn_post4x_internal call __bn_sqr8x_internal call __bn_post4x_internal call __bn_sqr8x_internal call __bn_post4x_internal call __bn_sqr8x_internal call __bn_post4x_internal movq %xmm2,$nptr movq %xmm4,$bptr mov $aptr,$rptr mov 40(%rsp),%rax lea 32(%rsp),$n0 call mul4x_internal mov 40(%rsp),%rsi # restore %rsp mov \$1,%rax mov -48(%rsi),%r15 mov -40(%rsi),%r14 mov -32(%rsi),%r13 mov -24(%rsi),%r12 mov -16(%rsi),%rbp mov -8(%rsi),%rbx lea (%rsi),%rsp .Lpower5_epilogue: ret .size bn_power5,.-bn_power5 .globl bn_sqr8x_internal .hidden bn_sqr8x_internal .type bn_sqr8x_internal,\@abi-omnipotent .align 32 bn_sqr8x_internal: __bn_sqr8x_internal: ############################################################## # Squaring part: # # a) multiply-n-add everything but a[i]*a[i]; # b) shift result of a) by 1 to the left and accumulate # a[i]*a[i] products; # ############################################################## # a[1]a[0] # a[2]a[0] # a[3]a[0] # a[2]a[1] # a[4]a[0] # a[3]a[1] # a[5]a[0] # a[4]a[1] # a[3]a[2] # a[6]a[0] # a[5]a[1] # a[4]a[2] # a[7]a[0] # a[6]a[1] # a[5]a[2] # a[4]a[3] # a[7]a[1] # a[6]a[2] # a[5]a[3] # a[7]a[2] # a[6]a[3] # a[5]a[4] # a[7]a[3] # a[6]a[4] # a[7]a[4] # a[6]a[5] # a[7]a[5] # a[7]a[6] # a[1]a[0] # a[2]a[0] # a[3]a[0] # a[4]a[0] # a[5]a[0] # a[6]a[0] # a[7]a[0] # a[2]a[1] # a[3]a[1] # a[4]a[1] # a[5]a[1] # a[6]a[1] # a[7]a[1] # a[3]a[2] # a[4]a[2] # a[5]a[2] # a[6]a[2] # a[7]a[2] # a[4]a[3] # a[5]a[3] # a[6]a[3] # a[7]a[3] # a[5]a[4] # a[6]a[4] # a[7]a[4] # a[6]a[5] # a[7]a[5] # a[7]a[6] # a[0]a[0] # a[1]a[1] # a[2]a[2] # a[3]a[3] # a[4]a[4] # a[5]a[5] # a[6]a[6] # a[7]a[7] lea 32(%r10),$i # $i=-($num-32) lea ($aptr,$num),$aptr # end of a[] buffer, ($aptr,$i)=&ap[2] mov $num,$j # $j=$num # comments apply to $num==8 case mov -32($aptr,$i),$a0 # a[0] lea 48+8(%rsp,$num,2),$tptr # end of tp[] buffer, &tp[2*$num] mov -24($aptr,$i),%rax # a[1] lea -32($tptr,$i),$tptr # end of tp[] window, &tp[2*$num-"$i"] mov -16($aptr,$i),$ai # a[2] mov %rax,$a1 mul $a0 # a[1]*a[0] mov %rax,$A0[0] # a[1]*a[0] mov $ai,%rax # a[2] mov %rdx,$A0[1] mov $A0[0],-24($tptr,$i) # t[1] mul $a0 # a[2]*a[0] add %rax,$A0[1] mov $ai,%rax adc \$0,%rdx mov $A0[1],-16($tptr,$i) # t[2] mov %rdx,$A0[0] mov -8($aptr,$i),$ai # a[3] mul $a1 # a[2]*a[1] mov %rax,$A1[0] # a[2]*a[1]+t[3] mov $ai,%rax mov %rdx,$A1[1] lea ($i),$j mul $a0 # a[3]*a[0] add %rax,$A0[0] # a[3]*a[0]+a[2]*a[1]+t[3] mov $ai,%rax mov %rdx,$A0[1] adc \$0,$A0[1] add $A1[0],$A0[0] adc \$0,$A0[1] mov $A0[0],-8($tptr,$j) # t[3] jmp .Lsqr4x_1st .align 32 .Lsqr4x_1st: mov ($aptr,$j),$ai # a[4] mul $a1 # a[3]*a[1] add %rax,$A1[1] # a[3]*a[1]+t[4] mov $ai,%rax mov %rdx,$A1[0] adc \$0,$A1[0] mul $a0 # a[4]*a[0] add %rax,$A0[1] # a[4]*a[0]+a[3]*a[1]+t[4] mov $ai,%rax # a[3] mov 8($aptr,$j),$ai # a[5] mov %rdx,$A0[0] adc \$0,$A0[0] add $A1[1],$A0[1] adc \$0,$A0[0] mul $a1 # a[4]*a[3] add %rax,$A1[0] # a[4]*a[3]+t[5] mov $ai,%rax mov $A0[1],($tptr,$j) # t[4] mov %rdx,$A1[1] adc \$0,$A1[1] mul $a0 # a[5]*a[2] add %rax,$A0[0] # a[5]*a[2]+a[4]*a[3]+t[5] mov $ai,%rax mov 16($aptr,$j),$ai # a[6] mov %rdx,$A0[1] adc \$0,$A0[1] add $A1[0],$A0[0] adc \$0,$A0[1] mul $a1 # a[5]*a[3] add %rax,$A1[1] # a[5]*a[3]+t[6] mov $ai,%rax mov $A0[0],8($tptr,$j) # t[5] mov %rdx,$A1[0] adc \$0,$A1[0] mul $a0 # a[6]*a[2] add %rax,$A0[1] # a[6]*a[2]+a[5]*a[3]+t[6] mov $ai,%rax # a[3] mov 24($aptr,$j),$ai # a[7] mov %rdx,$A0[0] adc \$0,$A0[0] add $A1[1],$A0[1] adc \$0,$A0[0] mul $a1 # a[6]*a[5] add %rax,$A1[0] # a[6]*a[5]+t[7] mov $ai,%rax mov $A0[1],16($tptr,$j) # t[6] mov %rdx,$A1[1] adc \$0,$A1[1] lea 32($j),$j mul $a0 # a[7]*a[4] add %rax,$A0[0] # a[7]*a[4]+a[6]*a[5]+t[6] mov $ai,%rax mov %rdx,$A0[1] adc \$0,$A0[1] add $A1[0],$A0[0] adc \$0,$A0[1] mov $A0[0],-8($tptr,$j) # t[7] cmp \$0,$j jne .Lsqr4x_1st mul $a1 # a[7]*a[5] add %rax,$A1[1] lea 16($i),$i adc \$0,%rdx add $A0[1],$A1[1] adc \$0,%rdx mov $A1[1],($tptr) # t[8] mov %rdx,$A1[0] mov %rdx,8($tptr) # t[9] jmp .Lsqr4x_outer .align 32 .Lsqr4x_outer: # comments apply to $num==6 case mov -32($aptr,$i),$a0 # a[0] lea 48+8(%rsp,$num,2),$tptr # end of tp[] buffer, &tp[2*$num] mov -24($aptr,$i),%rax # a[1] lea -32($tptr,$i),$tptr # end of tp[] window, &tp[2*$num-"$i"] mov -16($aptr,$i),$ai # a[2] mov %rax,$a1 mul $a0 # a[1]*a[0] mov -24($tptr,$i),$A0[0] # t[1] add %rax,$A0[0] # a[1]*a[0]+t[1] mov $ai,%rax # a[2] adc \$0,%rdx mov $A0[0],-24($tptr,$i) # t[1] mov %rdx,$A0[1] mul $a0 # a[2]*a[0] add %rax,$A0[1] mov $ai,%rax adc \$0,%rdx add -16($tptr,$i),$A0[1] # a[2]*a[0]+t[2] mov %rdx,$A0[0] adc \$0,$A0[0] mov $A0[1],-16($tptr,$i) # t[2] xor $A1[0],$A1[0] mov -8($aptr,$i),$ai # a[3] mul $a1 # a[2]*a[1] add %rax,$A1[0] # a[2]*a[1]+t[3] mov $ai,%rax adc \$0,%rdx add -8($tptr,$i),$A1[0] mov %rdx,$A1[1] adc \$0,$A1[1] mul $a0 # a[3]*a[0] add %rax,$A0[0] # a[3]*a[0]+a[2]*a[1]+t[3] mov $ai,%rax adc \$0,%rdx add $A1[0],$A0[0] mov %rdx,$A0[1] adc \$0,$A0[1] mov $A0[0],-8($tptr,$i) # t[3] lea ($i),$j jmp .Lsqr4x_inner .align 32 .Lsqr4x_inner: mov ($aptr,$j),$ai # a[4] mul $a1 # a[3]*a[1] add %rax,$A1[1] # a[3]*a[1]+t[4] mov $ai,%rax mov %rdx,$A1[0] adc \$0,$A1[0] add ($tptr,$j),$A1[1] adc \$0,$A1[0] .byte 0x67 mul $a0 # a[4]*a[0] add %rax,$A0[1] # a[4]*a[0]+a[3]*a[1]+t[4] mov $ai,%rax # a[3] mov 8($aptr,$j),$ai # a[5] mov %rdx,$A0[0] adc \$0,$A0[0] add $A1[1],$A0[1] adc \$0,$A0[0] mul $a1 # a[4]*a[3] add %rax,$A1[0] # a[4]*a[3]+t[5] mov $A0[1],($tptr,$j) # t[4] mov $ai,%rax mov %rdx,$A1[1] adc \$0,$A1[1] add 8($tptr,$j),$A1[0] lea 16($j),$j # j++ adc \$0,$A1[1] mul $a0 # a[5]*a[2] add %rax,$A0[0] # a[5]*a[2]+a[4]*a[3]+t[5] mov $ai,%rax adc \$0,%rdx add $A1[0],$A0[0] mov %rdx,$A0[1] adc \$0,$A0[1] mov $A0[0],-8($tptr,$j) # t[5], "preloaded t[1]" below cmp \$0,$j jne .Lsqr4x_inner .byte 0x67 mul $a1 # a[5]*a[3] add %rax,$A1[1] adc \$0,%rdx add $A0[1],$A1[1] adc \$0,%rdx mov $A1[1],($tptr) # t[6], "preloaded t[2]" below mov %rdx,$A1[0] mov %rdx,8($tptr) # t[7], "preloaded t[3]" below add \$16,$i jnz .Lsqr4x_outer # comments apply to $num==4 case mov -32($aptr),$a0 # a[0] lea 48+8(%rsp,$num,2),$tptr # end of tp[] buffer, &tp[2*$num] mov -24($aptr),%rax # a[1] lea -32($tptr,$i),$tptr # end of tp[] window, &tp[2*$num-"$i"] mov -16($aptr),$ai # a[2] mov %rax,$a1 mul $a0 # a[1]*a[0] add %rax,$A0[0] # a[1]*a[0]+t[1], preloaded t[1] mov $ai,%rax # a[2] mov %rdx,$A0[1] adc \$0,$A0[1] mul $a0 # a[2]*a[0] add %rax,$A0[1] mov $ai,%rax mov $A0[0],-24($tptr) # t[1] mov %rdx,$A0[0] adc \$0,$A0[0] add $A1[1],$A0[1] # a[2]*a[0]+t[2], preloaded t[2] mov -8($aptr),$ai # a[3] adc \$0,$A0[0] mul $a1 # a[2]*a[1] add %rax,$A1[0] # a[2]*a[1]+t[3], preloaded t[3] mov $ai,%rax mov $A0[1],-16($tptr) # t[2] mov %rdx,$A1[1] adc \$0,$A1[1] mul $a0 # a[3]*a[0] add %rax,$A0[0] # a[3]*a[0]+a[2]*a[1]+t[3] mov $ai,%rax mov %rdx,$A0[1] adc \$0,$A0[1] add $A1[0],$A0[0] adc \$0,$A0[1] mov $A0[0],-8($tptr) # t[3] mul $a1 # a[3]*a[1] add %rax,$A1[1] mov -16($aptr),%rax # a[2] adc \$0,%rdx add $A0[1],$A1[1] adc \$0,%rdx mov $A1[1],($tptr) # t[4] mov %rdx,$A1[0] mov %rdx,8($tptr) # t[5] mul $ai # a[2]*a[3] ___ { my ($shift,$carry)=($a0,$a1); my @S=(@A1,$ai,$n0); $code.=<<___; add \$16,$i xor $shift,$shift sub $num,$i # $i=16-$num xor $carry,$carry add $A1[0],%rax # t[5] adc \$0,%rdx mov %rax,8($tptr) # t[5] mov %rdx,16($tptr) # t[6] mov $carry,24($tptr) # t[7] mov -16($aptr,$i),%rax # a[0] lea 48+8(%rsp),$tptr xor $A0[0],$A0[0] # t[0] mov 8($tptr),$A0[1] # t[1] lea ($shift,$A0[0],2),$S[0] # t[2*i]<<1 | shift shr \$63,$A0[0] lea ($j,$A0[1],2),$S[1] # t[2*i+1]<<1 | shr \$63,$A0[1] or $A0[0],$S[1] # | t[2*i]>>63 mov 16($tptr),$A0[0] # t[2*i+2] # prefetch mov $A0[1],$shift # shift=t[2*i+1]>>63 mul %rax # a[i]*a[i] neg $carry # mov $carry,cf mov 24($tptr),$A0[1] # t[2*i+2+1] # prefetch adc %rax,$S[0] mov -8($aptr,$i),%rax # a[i+1] # prefetch mov $S[0],($tptr) adc %rdx,$S[1] lea ($shift,$A0[0],2),$S[2] # t[2*i]<<1 | shift mov $S[1],8($tptr) sbb $carry,$carry # mov cf,$carry shr \$63,$A0[0] lea ($j,$A0[1],2),$S[3] # t[2*i+1]<<1 | shr \$63,$A0[1] or $A0[0],$S[3] # | t[2*i]>>63 mov 32($tptr),$A0[0] # t[2*i+2] # prefetch mov $A0[1],$shift # shift=t[2*i+1]>>63 mul %rax # a[i]*a[i] neg $carry # mov $carry,cf mov 40($tptr),$A0[1] # t[2*i+2+1] # prefetch adc %rax,$S[2] mov 0($aptr,$i),%rax # a[i+1] # prefetch mov $S[2],16($tptr) adc %rdx,$S[3] lea 16($i),$i mov $S[3],24($tptr) sbb $carry,$carry # mov cf,$carry lea 64($tptr),$tptr jmp .Lsqr4x_shift_n_add .align 32 .Lsqr4x_shift_n_add: lea ($shift,$A0[0],2),$S[0] # t[2*i]<<1 | shift shr \$63,$A0[0] lea ($j,$A0[1],2),$S[1] # t[2*i+1]<<1 | shr \$63,$A0[1] or $A0[0],$S[1] # | t[2*i]>>63 mov -16($tptr),$A0[0] # t[2*i+2] # prefetch mov $A0[1],$shift # shift=t[2*i+1]>>63 mul %rax # a[i]*a[i] neg $carry # mov $carry,cf mov -8($tptr),$A0[1] # t[2*i+2+1] # prefetch adc %rax,$S[0] mov -8($aptr,$i),%rax # a[i+1] # prefetch mov $S[0],-32($tptr) adc %rdx,$S[1] lea ($shift,$A0[0],2),$S[2] # t[2*i]<<1 | shift mov $S[1],-24($tptr) sbb $carry,$carry # mov cf,$carry shr \$63,$A0[0] lea ($j,$A0[1],2),$S[3] # t[2*i+1]<<1 | shr \$63,$A0[1] or $A0[0],$S[3] # | t[2*i]>>63 mov 0($tptr),$A0[0] # t[2*i+2] # prefetch mov $A0[1],$shift # shift=t[2*i+1]>>63 mul %rax # a[i]*a[i] neg $carry # mov $carry,cf mov 8($tptr),$A0[1] # t[2*i+2+1] # prefetch adc %rax,$S[2] mov 0($aptr,$i),%rax # a[i+1] # prefetch mov $S[2],-16($tptr) adc %rdx,$S[3] lea ($shift,$A0[0],2),$S[0] # t[2*i]<<1 | shift mov $S[3],-8($tptr) sbb $carry,$carry # mov cf,$carry shr \$63,$A0[0] lea ($j,$A0[1],2),$S[1] # t[2*i+1]<<1 | shr \$63,$A0[1] or $A0[0],$S[1] # | t[2*i]>>63 mov 16($tptr),$A0[0] # t[2*i+2] # prefetch mov $A0[1],$shift # shift=t[2*i+1]>>63 mul %rax # a[i]*a[i] neg $carry # mov $carry,cf mov 24($tptr),$A0[1] # t[2*i+2+1] # prefetch adc %rax,$S[0] mov 8($aptr,$i),%rax # a[i+1] # prefetch mov $S[0],0($tptr) adc %rdx,$S[1] lea ($shift,$A0[0],2),$S[2] # t[2*i]<<1 | shift mov $S[1],8($tptr) sbb $carry,$carry # mov cf,$carry shr \$63,$A0[0] lea ($j,$A0[1],2),$S[3] # t[2*i+1]<<1 | shr \$63,$A0[1] or $A0[0],$S[3] # | t[2*i]>>63 mov 32($tptr),$A0[0] # t[2*i+2] # prefetch mov $A0[1],$shift # shift=t[2*i+1]>>63 mul %rax # a[i]*a[i] neg $carry # mov $carry,cf mov 40($tptr),$A0[1] # t[2*i+2+1] # prefetch adc %rax,$S[2] mov 16($aptr,$i),%rax # a[i+1] # prefetch mov $S[2],16($tptr) adc %rdx,$S[3] mov $S[3],24($tptr) sbb $carry,$carry # mov cf,$carry lea 64($tptr),$tptr add \$32,$i jnz .Lsqr4x_shift_n_add lea ($shift,$A0[0],2),$S[0] # t[2*i]<<1 | shift .byte 0x67 shr \$63,$A0[0] lea ($j,$A0[1],2),$S[1] # t[2*i+1]<<1 | shr \$63,$A0[1] or $A0[0],$S[1] # | t[2*i]>>63 mov -16($tptr),$A0[0] # t[2*i+2] # prefetch mov $A0[1],$shift # shift=t[2*i+1]>>63 mul %rax # a[i]*a[i] neg $carry # mov $carry,cf mov -8($tptr),$A0[1] # t[2*i+2+1] # prefetch adc %rax,$S[0] mov -8($aptr),%rax # a[i+1] # prefetch mov $S[0],-32($tptr) adc %rdx,$S[1] lea ($shift,$A0[0],2),$S[2] # t[2*i]<<1|shift mov $S[1],-24($tptr) sbb $carry,$carry # mov cf,$carry shr \$63,$A0[0] lea ($j,$A0[1],2),$S[3] # t[2*i+1]<<1 | shr \$63,$A0[1] or $A0[0],$S[3] # | t[2*i]>>63 mul %rax # a[i]*a[i] neg $carry # mov $carry,cf adc %rax,$S[2] adc %rdx,$S[3] mov $S[2],-16($tptr) mov $S[3],-8($tptr) ___ } ###################################################################### # Montgomery reduction part, "word-by-word" algorithm. # # This new path is inspired by multiple submissions from Intel, by # Shay Gueron, Vlad Krasnov, Erdinc Ozturk, James Guilford, # Vinodh Gopal... { my ($nptr,$tptr,$carry,$m0)=("%rbp","%rdi","%rsi","%rbx"); $code.=<<___; movq %xmm2,$nptr __bn_sqr8x_reduction: xor %rax,%rax lea ($nptr,$num),%rcx # end of n[] lea 48+8(%rsp,$num,2),%rdx # end of t[] buffer mov %rcx,0+8(%rsp) lea 48+8(%rsp,$num),$tptr # end of initial t[] window mov %rdx,8+8(%rsp) neg $num jmp .L8x_reduction_loop .align 32 .L8x_reduction_loop: lea ($tptr,$num),$tptr # start of current t[] window .byte 0x66 mov 8*0($tptr),$m0 mov 8*1($tptr),%r9 mov 8*2($tptr),%r10 mov 8*3($tptr),%r11 mov 8*4($tptr),%r12 mov 8*5($tptr),%r13 mov 8*6($tptr),%r14 mov 8*7($tptr),%r15 mov %rax,(%rdx) # store top-most carry bit lea 8*8($tptr),$tptr .byte 0x67 mov $m0,%r8 imulq 32+8(%rsp),$m0 # n0*a[0] mov 8*0($nptr),%rax # n[0] mov \$8,%ecx jmp .L8x_reduce .align 32 .L8x_reduce: mulq $m0 mov 8*1($nptr),%rax # n[1] neg %r8 mov %rdx,%r8 adc \$0,%r8 mulq $m0 add %rax,%r9 mov 8*2($nptr),%rax adc \$0,%rdx add %r9,%r8 mov $m0,48-8+8(%rsp,%rcx,8) # put aside n0*a[i] mov %rdx,%r9 adc \$0,%r9 mulq $m0 add %rax,%r10 mov 8*3($nptr),%rax adc \$0,%rdx add %r10,%r9 mov 32+8(%rsp),$carry # pull n0, borrow $carry mov %rdx,%r10 adc \$0,%r10 mulq $m0 add %rax,%r11 mov 8*4($nptr),%rax adc \$0,%rdx imulq %r8,$carry # modulo-scheduled add %r11,%r10 mov %rdx,%r11 adc \$0,%r11 mulq $m0 add %rax,%r12 mov 8*5($nptr),%rax adc \$0,%rdx add %r12,%r11 mov %rdx,%r12 adc \$0,%r12 mulq $m0 add %rax,%r13 mov 8*6($nptr),%rax adc \$0,%rdx add %r13,%r12 mov %rdx,%r13 adc \$0,%r13 mulq $m0 add %rax,%r14 mov 8*7($nptr),%rax adc \$0,%rdx add %r14,%r13 mov %rdx,%r14 adc \$0,%r14 mulq $m0 mov $carry,$m0 # n0*a[i] add %rax,%r15 mov 8*0($nptr),%rax # n[0] adc \$0,%rdx add %r15,%r14 mov %rdx,%r15 adc \$0,%r15 dec %ecx jnz .L8x_reduce lea 8*8($nptr),$nptr xor %rax,%rax mov 8+8(%rsp),%rdx # pull end of t[] cmp 0+8(%rsp),$nptr # end of n[]? jae .L8x_no_tail .byte 0x66 add 8*0($tptr),%r8 adc 8*1($tptr),%r9 adc 8*2($tptr),%r10 adc 8*3($tptr),%r11 adc 8*4($tptr),%r12 adc 8*5($tptr),%r13 adc 8*6($tptr),%r14 adc 8*7($tptr),%r15 sbb $carry,$carry # top carry mov 48+56+8(%rsp),$m0 # pull n0*a[0] mov \$8,%ecx mov 8*0($nptr),%rax jmp .L8x_tail .align 32 .L8x_tail: mulq $m0 add %rax,%r8 mov 8*1($nptr),%rax mov %r8,($tptr) # save result mov %rdx,%r8 adc \$0,%r8 mulq $m0 add %rax,%r9 mov 8*2($nptr),%rax adc \$0,%rdx add %r9,%r8 lea 8($tptr),$tptr # $tptr++ mov %rdx,%r9 adc \$0,%r9 mulq $m0 add %rax,%r10 mov 8*3($nptr),%rax adc \$0,%rdx add %r10,%r9 mov %rdx,%r10 adc \$0,%r10 mulq $m0 add %rax,%r11 mov 8*4($nptr),%rax adc \$0,%rdx add %r11,%r10 mov %rdx,%r11 adc \$0,%r11 mulq $m0 add %rax,%r12 mov 8*5($nptr),%rax adc \$0,%rdx add %r12,%r11 mov %rdx,%r12 adc \$0,%r12 mulq $m0 add %rax,%r13 mov 8*6($nptr),%rax adc \$0,%rdx add %r13,%r12 mov %rdx,%r13 adc \$0,%r13 mulq $m0 add %rax,%r14 mov 8*7($nptr),%rax adc \$0,%rdx add %r14,%r13 mov %rdx,%r14 adc \$0,%r14 mulq $m0 mov 48-16+8(%rsp,%rcx,8),$m0# pull n0*a[i] add %rax,%r15 adc \$0,%rdx add %r15,%r14 mov 8*0($nptr),%rax # pull n[0] mov %rdx,%r15 adc \$0,%r15 dec %ecx jnz .L8x_tail lea 8*8($nptr),$nptr mov 8+8(%rsp),%rdx # pull end of t[] cmp 0+8(%rsp),$nptr # end of n[]? jae .L8x_tail_done # break out of loop mov 48+56+8(%rsp),$m0 # pull n0*a[0] neg $carry mov 8*0($nptr),%rax # pull n[0] adc 8*0($tptr),%r8 adc 8*1($tptr),%r9 adc 8*2($tptr),%r10 adc 8*3($tptr),%r11 adc 8*4($tptr),%r12 adc 8*5($tptr),%r13 adc 8*6($tptr),%r14 adc 8*7($tptr),%r15 sbb $carry,$carry # top carry mov \$8,%ecx jmp .L8x_tail .align 32 .L8x_tail_done: xor %rax,%rax add (%rdx),%r8 # can this overflow? adc \$0,%r9 adc \$0,%r10 adc \$0,%r11 adc \$0,%r12 adc \$0,%r13 adc \$0,%r14 adc \$0,%r15 adc \$0,%rax neg $carry .L8x_no_tail: adc 8*0($tptr),%r8 adc 8*1($tptr),%r9 adc 8*2($tptr),%r10 adc 8*3($tptr),%r11 adc 8*4($tptr),%r12 adc 8*5($tptr),%r13 adc 8*6($tptr),%r14 adc 8*7($tptr),%r15 adc \$0,%rax # top-most carry mov -8($nptr),%rcx # np[num-1] xor $carry,$carry movq %xmm2,$nptr # restore $nptr mov %r8,8*0($tptr) # store top 512 bits mov %r9,8*1($tptr) movq %xmm3,$num # $num is %r9, can't be moved upwards mov %r10,8*2($tptr) mov %r11,8*3($tptr) mov %r12,8*4($tptr) mov %r13,8*5($tptr) mov %r14,8*6($tptr) mov %r15,8*7($tptr) lea 8*8($tptr),$tptr cmp %rdx,$tptr # end of t[]? jb .L8x_reduction_loop ret .size bn_sqr8x_internal,.-bn_sqr8x_internal ___ } ############################################################## # Post-condition, 4x unrolled # { my ($tptr,$nptr)=("%rbx","%rbp"); $code.=<<___; .type __bn_post4x_internal,\@abi-omnipotent .align 32 __bn_post4x_internal: mov 8*0($nptr),%r12 lea (%rdi,$num),$tptr # %rdi was $tptr above mov $num,%rcx movq %xmm1,$rptr # restore $rptr neg %rax movq %xmm1,$aptr # prepare for back-to-back call sar \$3+2,%rcx dec %r12 # so that after 'not' we get -n[0] xor %r10,%r10 mov 8*1($nptr),%r13 mov 8*2($nptr),%r14 mov 8*3($nptr),%r15 jmp .Lsqr4x_sub_entry .align 16 .Lsqr4x_sub: mov 8*0($nptr),%r12 mov 8*1($nptr),%r13 mov 8*2($nptr),%r14 mov 8*3($nptr),%r15 .Lsqr4x_sub_entry: lea 8*4($nptr),$nptr not %r12 not %r13 not %r14 not %r15 and %rax,%r12 and %rax,%r13 and %rax,%r14 and %rax,%r15 neg %r10 # mov %r10,%cf adc 8*0($tptr),%r12 adc 8*1($tptr),%r13 adc 8*2($tptr),%r14 adc 8*3($tptr),%r15 mov %r12,8*0($rptr) lea 8*4($tptr),$tptr mov %r13,8*1($rptr) sbb %r10,%r10 # mov %cf,%r10 mov %r14,8*2($rptr) mov %r15,8*3($rptr) lea 8*4($rptr),$rptr inc %rcx # pass %cf jnz .Lsqr4x_sub mov $num,%r10 # prepare for back-to-back call neg $num # restore $num ret .size __bn_post4x_internal,.-__bn_post4x_internal ___ } { $code.=<<___; .globl bn_from_montgomery .type bn_from_montgomery,\@abi-omnipotent .align 32 bn_from_montgomery: testl \$7,`($win64?"48(%rsp)":"%r9d")` jz bn_from_mont8x xor %eax,%eax ret .size bn_from_montgomery,.-bn_from_montgomery .type bn_from_mont8x,\@function,6 .align 32 bn_from_mont8x: .byte 0x67 mov %rsp,%rax push %rbx push %rbp push %r12 push %r13 push %r14 push %r15 .Lfrom_prologue: shl \$3,${num}d # convert $num to bytes lea ($num,$num,2),%r10 # 3*$num in bytes neg $num mov ($n0),$n0 # *n0 ############################################################## # Ensure that stack frame doesn't alias with $rptr+3*$num # modulo 4096, which covers ret[num], am[num] and n[num] # (see bn_exp.c). The stack is allocated to aligned with # bn_power5's frame, and as bn_from_montgomery happens to be # last operation, we use the opportunity to cleanse it. # lea -320(%rsp,$num,2),%r11 mov %rsp,%rbp sub $rptr,%r11 and \$4095,%r11 cmp %r11,%r10 jb .Lfrom_sp_alt sub %r11,%rbp # align with $aptr lea -320(%rbp,$num,2),%rbp # future alloca(frame+2*$num*8+256) jmp .Lfrom_sp_done .align 32 .Lfrom_sp_alt: lea 4096-320(,$num,2),%r10 lea -320(%rbp,$num,2),%rbp # future alloca(frame+2*$num*8+256) sub %r10,%r11 mov \$0,%r10 cmovc %r10,%r11 sub %r11,%rbp .Lfrom_sp_done: and \$-64,%rbp mov %rsp,%r11 sub %rbp,%r11 and \$-4096,%r11 lea (%rbp,%r11),%rsp mov (%rsp),%r10 cmp %rbp,%rsp ja .Lfrom_page_walk jmp .Lfrom_page_walk_done .Lfrom_page_walk: lea -4096(%rsp),%rsp mov (%rsp),%r10 cmp %rbp,%rsp ja .Lfrom_page_walk .Lfrom_page_walk_done: mov $num,%r10 neg $num ############################################################## # Stack layout # # +0 saved $num, used in reduction section # +8 &t[2*$num], used in reduction section # +32 saved *n0 # +40 saved %rsp # +48 t[2*$num] # mov $n0, 32(%rsp) mov %rax, 40(%rsp) # save original %rsp .Lfrom_body: mov $num,%r11 lea 48(%rsp),%rax pxor %xmm0,%xmm0 jmp .Lmul_by_1 .align 32 .Lmul_by_1: movdqu ($aptr),%xmm1 movdqu 16($aptr),%xmm2 movdqu 32($aptr),%xmm3 movdqa %xmm0,(%rax,$num) movdqu 48($aptr),%xmm4 movdqa %xmm0,16(%rax,$num) .byte 0x48,0x8d,0xb6,0x40,0x00,0x00,0x00 # lea 64($aptr),$aptr movdqa %xmm1,(%rax) movdqa %xmm0,32(%rax,$num) movdqa %xmm2,16(%rax) movdqa %xmm0,48(%rax,$num) movdqa %xmm3,32(%rax) movdqa %xmm4,48(%rax) lea 64(%rax),%rax sub \$64,%r11 jnz .Lmul_by_1 movq $rptr,%xmm1 movq $nptr,%xmm2 .byte 0x67 mov $nptr,%rbp movq %r10, %xmm3 # -num ___ $code.=<<___ if ($addx); mov OPENSSL_ia32cap_P+8(%rip),%r11d and \$0x80108,%r11d cmp \$0x80108,%r11d # check for AD*X+BMI2+BMI1 jne .Lfrom_mont_nox lea (%rax,$num),$rptr call __bn_sqrx8x_reduction call __bn_postx4x_internal pxor %xmm0,%xmm0 lea 48(%rsp),%rax mov 40(%rsp),%rsi # restore %rsp jmp .Lfrom_mont_zero .align 32 .Lfrom_mont_nox: ___ $code.=<<___; call __bn_sqr8x_reduction call __bn_post4x_internal pxor %xmm0,%xmm0 lea 48(%rsp),%rax mov 40(%rsp),%rsi # restore %rsp jmp .Lfrom_mont_zero .align 32 .Lfrom_mont_zero: movdqa %xmm0,16*0(%rax) movdqa %xmm0,16*1(%rax) movdqa %xmm0,16*2(%rax) movdqa %xmm0,16*3(%rax) lea 16*4(%rax),%rax sub \$32,$num jnz .Lfrom_mont_zero mov \$1,%rax mov -48(%rsi),%r15 mov -40(%rsi),%r14 mov -32(%rsi),%r13 mov -24(%rsi),%r12 mov -16(%rsi),%rbp mov -8(%rsi),%rbx lea (%rsi),%rsp .Lfrom_epilogue: ret .size bn_from_mont8x,.-bn_from_mont8x ___ } }}} if ($addx) {{{ my $bp="%rdx"; # restore original value $code.=<<___; .type bn_mulx4x_mont_gather5,\@function,6 .align 32 bn_mulx4x_mont_gather5: mov %rsp,%rax .Lmulx4x_enter: push %rbx push %rbp push %r12 push %r13 push %r14 push %r15 .Lmulx4x_prologue: shl \$3,${num}d # convert $num to bytes lea ($num,$num,2),%r10 # 3*$num in bytes neg $num # -$num mov ($n0),$n0 # *n0 ############################################################## # Ensure that stack frame doesn't alias with $rptr+3*$num # modulo 4096, which covers ret[num], am[num] and n[num] # (see bn_exp.c). This is done to allow memory disambiguation # logic do its magic. [Extra [num] is allocated in order # to align with bn_power5's frame, which is cleansed after # completing exponentiation. Extra 256 bytes is for power mask # calculated from 7th argument, the index.] # lea -320(%rsp,$num,2),%r11 mov %rsp,%rbp sub $rp,%r11 and \$4095,%r11 cmp %r11,%r10 jb .Lmulx4xsp_alt sub %r11,%rbp # align with $aptr lea -320(%rbp,$num,2),%rbp # future alloca(frame+2*$num*8+256) jmp .Lmulx4xsp_done .Lmulx4xsp_alt: lea 4096-320(,$num,2),%r10 lea -320(%rbp,$num,2),%rbp # future alloca(frame+2*$num*8+256) sub %r10,%r11 mov \$0,%r10 cmovc %r10,%r11 sub %r11,%rbp .Lmulx4xsp_done: and \$-64,%rbp # ensure alignment mov %rsp,%r11 sub %rbp,%r11 and \$-4096,%r11 lea (%rbp,%r11),%rsp mov (%rsp),%r10 cmp %rbp,%rsp ja .Lmulx4x_page_walk jmp .Lmulx4x_page_walk_done .Lmulx4x_page_walk: lea -4096(%rsp),%rsp mov (%rsp),%r10 cmp %rbp,%rsp ja .Lmulx4x_page_walk .Lmulx4x_page_walk_done: ############################################################## # Stack layout # +0 -num # +8 off-loaded &b[i] # +16 end of b[num] # +24 inner counter # +32 saved n0 # +40 saved %rsp # +48 # +56 saved rp # +64 tmp[num+1] # mov $n0, 32(%rsp) # save *n0 mov %rax,40(%rsp) # save original %rsp .Lmulx4x_body: call mulx4x_internal mov 40(%rsp),%rsi # restore %rsp mov \$1,%rax mov -48(%rsi),%r15 mov -40(%rsi),%r14 mov -32(%rsi),%r13 mov -24(%rsi),%r12 mov -16(%rsi),%rbp mov -8(%rsi),%rbx lea (%rsi),%rsp .Lmulx4x_epilogue: ret .size bn_mulx4x_mont_gather5,.-bn_mulx4x_mont_gather5 .type mulx4x_internal,\@abi-omnipotent .align 32 mulx4x_internal: mov $num,8(%rsp) # save -$num (it was in bytes) mov $num,%r10 neg $num # restore $num shl \$5,$num neg %r10 # restore $num lea 128($bp,$num),%r13 # end of powers table (+size optimization) shr \$5+5,$num movd `($win64?56:8)`(%rax),%xmm5 # load 7th argument sub \$1,$num lea .Linc(%rip),%rax mov %r13,16+8(%rsp) # end of b[num] mov $num,24+8(%rsp) # inner counter mov $rp, 56+8(%rsp) # save $rp ___ my ($aptr, $bptr, $nptr, $tptr, $mi, $bi, $zero, $num)= ("%rsi","%rdi","%rcx","%rbx","%r8","%r9","%rbp","%rax"); my $rptr=$bptr; my $STRIDE=2**5*8; # 5 is "window size" my $N=$STRIDE/4; # should match cache line size $code.=<<___; movdqa 0(%rax),%xmm0 # 00000001000000010000000000000000 movdqa 16(%rax),%xmm1 # 00000002000000020000000200000002 lea 88-112(%rsp,%r10),%r10 # place the mask after tp[num+1] (+ICache optimizaton) lea 128($bp),$bptr # size optimization pshufd \$0,%xmm5,%xmm5 # broadcast index movdqa %xmm1,%xmm4 .byte 0x67 movdqa %xmm1,%xmm2 ___ ######################################################################## # calculate mask by comparing 0..31 to index and save result to stack # $code.=<<___; .byte 0x67 paddd %xmm0,%xmm1 pcmpeqd %xmm5,%xmm0 # compare to 1,0 movdqa %xmm4,%xmm3 ___ for($i=0;$i<$STRIDE/16-4;$i+=4) { $code.=<<___; paddd %xmm1,%xmm2 pcmpeqd %xmm5,%xmm1 # compare to 3,2 movdqa %xmm0,`16*($i+0)+112`(%r10) movdqa %xmm4,%xmm0 paddd %xmm2,%xmm3 pcmpeqd %xmm5,%xmm2 # compare to 5,4 movdqa %xmm1,`16*($i+1)+112`(%r10) movdqa %xmm4,%xmm1 paddd %xmm3,%xmm0 pcmpeqd %xmm5,%xmm3 # compare to 7,6 movdqa %xmm2,`16*($i+2)+112`(%r10) movdqa %xmm4,%xmm2 paddd %xmm0,%xmm1 pcmpeqd %xmm5,%xmm0 movdqa %xmm3,`16*($i+3)+112`(%r10) movdqa %xmm4,%xmm3 ___ } $code.=<<___; # last iteration can be optimized .byte 0x67 paddd %xmm1,%xmm2 pcmpeqd %xmm5,%xmm1 movdqa %xmm0,`16*($i+0)+112`(%r10) paddd %xmm2,%xmm3 pcmpeqd %xmm5,%xmm2 movdqa %xmm1,`16*($i+1)+112`(%r10) pcmpeqd %xmm5,%xmm3 movdqa %xmm2,`16*($i+2)+112`(%r10) pand `16*($i+0)-128`($bptr),%xmm0 # while it's still in register pand `16*($i+1)-128`($bptr),%xmm1 pand `16*($i+2)-128`($bptr),%xmm2 movdqa %xmm3,`16*($i+3)+112`(%r10) pand `16*($i+3)-128`($bptr),%xmm3 por %xmm2,%xmm0 por %xmm3,%xmm1 ___ for($i=0;$i<$STRIDE/16-4;$i+=4) { $code.=<<___; movdqa `16*($i+0)-128`($bptr),%xmm4 movdqa `16*($i+1)-128`($bptr),%xmm5 movdqa `16*($i+2)-128`($bptr),%xmm2 pand `16*($i+0)+112`(%r10),%xmm4 movdqa `16*($i+3)-128`($bptr),%xmm3 pand `16*($i+1)+112`(%r10),%xmm5 por %xmm4,%xmm0 pand `16*($i+2)+112`(%r10),%xmm2 por %xmm5,%xmm1 pand `16*($i+3)+112`(%r10),%xmm3 por %xmm2,%xmm0 por %xmm3,%xmm1 ___ } $code.=<<___; pxor %xmm1,%xmm0 pshufd \$0x4e,%xmm0,%xmm1 por %xmm1,%xmm0 lea $STRIDE($bptr),$bptr movq %xmm0,%rdx # bp[0] lea 64+8*4+8(%rsp),$tptr mov %rdx,$bi mulx 0*8($aptr),$mi,%rax # a[0]*b[0] mulx 1*8($aptr),%r11,%r12 # a[1]*b[0] add %rax,%r11 mulx 2*8($aptr),%rax,%r13 # ... adc %rax,%r12 adc \$0,%r13 mulx 3*8($aptr),%rax,%r14 mov $mi,%r15 imulq 32+8(%rsp),$mi # "t[0]"*n0 xor $zero,$zero # cf=0, of=0 mov $mi,%rdx mov $bptr,8+8(%rsp) # off-load &b[i] lea 4*8($aptr),$aptr adcx %rax,%r13 adcx $zero,%r14 # cf=0 mulx 0*8($nptr),%rax,%r10 adcx %rax,%r15 # discarded adox %r11,%r10 mulx 1*8($nptr),%rax,%r11 adcx %rax,%r10 adox %r12,%r11 mulx 2*8($nptr),%rax,%r12 mov 24+8(%rsp),$bptr # counter value mov %r10,-8*4($tptr) adcx %rax,%r11 adox %r13,%r12 mulx 3*8($nptr),%rax,%r15 mov $bi,%rdx mov %r11,-8*3($tptr) adcx %rax,%r12 adox $zero,%r15 # of=0 lea 4*8($nptr),$nptr mov %r12,-8*2($tptr) jmp .Lmulx4x_1st .align 32 .Lmulx4x_1st: adcx $zero,%r15 # cf=0, modulo-scheduled mulx 0*8($aptr),%r10,%rax # a[4]*b[0] adcx %r14,%r10 mulx 1*8($aptr),%r11,%r14 # a[5]*b[0] adcx %rax,%r11 mulx 2*8($aptr),%r12,%rax # ... adcx %r14,%r12 mulx 3*8($aptr),%r13,%r14 .byte 0x67,0x67 mov $mi,%rdx adcx %rax,%r13 adcx $zero,%r14 # cf=0 lea 4*8($aptr),$aptr lea 4*8($tptr),$tptr adox %r15,%r10 mulx 0*8($nptr),%rax,%r15 adcx %rax,%r10 adox %r15,%r11 mulx 1*8($nptr),%rax,%r15 adcx %rax,%r11 adox %r15,%r12 mulx 2*8($nptr),%rax,%r15 mov %r10,-5*8($tptr) adcx %rax,%r12 mov %r11,-4*8($tptr) adox %r15,%r13 mulx 3*8($nptr),%rax,%r15 mov $bi,%rdx mov %r12,-3*8($tptr) adcx %rax,%r13 adox $zero,%r15 lea 4*8($nptr),$nptr mov %r13,-2*8($tptr) dec $bptr # of=0, pass cf jnz .Lmulx4x_1st mov 8(%rsp),$num # load -num adc $zero,%r15 # modulo-scheduled lea ($aptr,$num),$aptr # rewind $aptr add %r15,%r14 mov 8+8(%rsp),$bptr # re-load &b[i] adc $zero,$zero # top-most carry mov %r14,-1*8($tptr) jmp .Lmulx4x_outer .align 32 .Lmulx4x_outer: lea 16-256($tptr),%r10 # where 256-byte mask is (+density control) pxor %xmm4,%xmm4 .byte 0x67,0x67 pxor %xmm5,%xmm5 ___ for($i=0;$i<$STRIDE/16;$i+=4) { $code.=<<___; movdqa `16*($i+0)-128`($bptr),%xmm0 movdqa `16*($i+1)-128`($bptr),%xmm1 movdqa `16*($i+2)-128`($bptr),%xmm2 pand `16*($i+0)+256`(%r10),%xmm0 movdqa `16*($i+3)-128`($bptr),%xmm3 pand `16*($i+1)+256`(%r10),%xmm1 por %xmm0,%xmm4 pand `16*($i+2)+256`(%r10),%xmm2 por %xmm1,%xmm5 pand `16*($i+3)+256`(%r10),%xmm3 por %xmm2,%xmm4 por %xmm3,%xmm5 ___ } $code.=<<___; por %xmm5,%xmm4 pshufd \$0x4e,%xmm4,%xmm0 por %xmm4,%xmm0 lea $STRIDE($bptr),$bptr movq %xmm0,%rdx # m0=bp[i] mov $zero,($tptr) # save top-most carry lea 4*8($tptr,$num),$tptr # rewind $tptr mulx 0*8($aptr),$mi,%r11 # a[0]*b[i] xor $zero,$zero # cf=0, of=0 mov %rdx,$bi mulx 1*8($aptr),%r14,%r12 # a[1]*b[i] adox -4*8($tptr),$mi # +t[0] adcx %r14,%r11 mulx 2*8($aptr),%r15,%r13 # ... adox -3*8($tptr),%r11 adcx %r15,%r12 mulx 3*8($aptr),%rdx,%r14 adox -2*8($tptr),%r12 adcx %rdx,%r13 lea ($nptr,$num),$nptr # rewind $nptr lea 4*8($aptr),$aptr adox -1*8($tptr),%r13 adcx $zero,%r14 adox $zero,%r14 mov $mi,%r15 imulq 32+8(%rsp),$mi # "t[0]"*n0 mov $mi,%rdx xor $zero,$zero # cf=0, of=0 mov $bptr,8+8(%rsp) # off-load &b[i] mulx 0*8($nptr),%rax,%r10 adcx %rax,%r15 # discarded adox %r11,%r10 mulx 1*8($nptr),%rax,%r11 adcx %rax,%r10 adox %r12,%r11 mulx 2*8($nptr),%rax,%r12 adcx %rax,%r11 adox %r13,%r12 mulx 3*8($nptr),%rax,%r15 mov $bi,%rdx mov 24+8(%rsp),$bptr # counter value mov %r10,-8*4($tptr) adcx %rax,%r12 mov %r11,-8*3($tptr) adox $zero,%r15 # of=0 mov %r12,-8*2($tptr) lea 4*8($nptr),$nptr jmp .Lmulx4x_inner .align 32 .Lmulx4x_inner: mulx 0*8($aptr),%r10,%rax # a[4]*b[i] adcx $zero,%r15 # cf=0, modulo-scheduled adox %r14,%r10 mulx 1*8($aptr),%r11,%r14 # a[5]*b[i] adcx 0*8($tptr),%r10 adox %rax,%r11 mulx 2*8($aptr),%r12,%rax # ... adcx 1*8($tptr),%r11 adox %r14,%r12 mulx 3*8($aptr),%r13,%r14 mov $mi,%rdx adcx 2*8($tptr),%r12 adox %rax,%r13 adcx 3*8($tptr),%r13 adox $zero,%r14 # of=0 lea 4*8($aptr),$aptr lea 4*8($tptr),$tptr adcx $zero,%r14 # cf=0 adox %r15,%r10 mulx 0*8($nptr),%rax,%r15 adcx %rax,%r10 adox %r15,%r11 mulx 1*8($nptr),%rax,%r15 adcx %rax,%r11 adox %r15,%r12 mulx 2*8($nptr),%rax,%r15 mov %r10,-5*8($tptr) adcx %rax,%r12 adox %r15,%r13 mov %r11,-4*8($tptr) mulx 3*8($nptr),%rax,%r15 mov $bi,%rdx lea 4*8($nptr),$nptr mov %r12,-3*8($tptr) adcx %rax,%r13 adox $zero,%r15 mov %r13,-2*8($tptr) dec $bptr # of=0, pass cf jnz .Lmulx4x_inner mov 0+8(%rsp),$num # load -num adc $zero,%r15 # modulo-scheduled sub 0*8($tptr),$bptr # pull top-most carry to %cf mov 8+8(%rsp),$bptr # re-load &b[i] mov 16+8(%rsp),%r10 adc %r15,%r14 lea ($aptr,$num),$aptr # rewind $aptr adc $zero,$zero # top-most carry mov %r14,-1*8($tptr) cmp %r10,$bptr jb .Lmulx4x_outer mov -8($nptr),%r10 mov $zero,%r8 mov ($nptr,$num),%r12 lea ($nptr,$num),%rbp # rewind $nptr mov $num,%rcx lea ($tptr,$num),%rdi # rewind $tptr xor %eax,%eax xor %r15,%r15 sub %r14,%r10 # compare top-most words adc %r15,%r15 or %r15,%r8 sar \$3+2,%rcx sub %r8,%rax # %rax=-%r8 mov 56+8(%rsp),%rdx # restore rp dec %r12 # so that after 'not' we get -n[0] mov 8*1(%rbp),%r13 xor %r8,%r8 mov 8*2(%rbp),%r14 mov 8*3(%rbp),%r15 jmp .Lsqrx4x_sub_entry # common post-condition .size mulx4x_internal,.-mulx4x_internal ___ } { ###################################################################### # void bn_power5( my $rptr="%rdi"; # BN_ULONG *rptr, my $aptr="%rsi"; # const BN_ULONG *aptr, my $bptr="%rdx"; # const void *table, my $nptr="%rcx"; # const BN_ULONG *nptr, my $n0 ="%r8"; # const BN_ULONG *n0); my $num ="%r9"; # int num, has to be divisible by 8 # int pwr); my ($i,$j,$tptr)=("%rbp","%rcx",$rptr); my @A0=("%r10","%r11"); my @A1=("%r12","%r13"); my ($a0,$a1,$ai)=("%r14","%r15","%rbx"); $code.=<<___; .type bn_powerx5,\@function,6 .align 32 bn_powerx5: mov %rsp,%rax .Lpowerx5_enter: push %rbx push %rbp push %r12 push %r13 push %r14 push %r15 .Lpowerx5_prologue: shl \$3,${num}d # convert $num to bytes lea ($num,$num,2),%r10 # 3*$num in bytes neg $num mov ($n0),$n0 # *n0 ############################################################## # Ensure that stack frame doesn't alias with $rptr+3*$num # modulo 4096, which covers ret[num], am[num] and n[num] # (see bn_exp.c). This is done to allow memory disambiguation # logic do its magic. [Extra 256 bytes is for power mask # calculated from 7th argument, the index.] # lea -320(%rsp,$num,2),%r11 mov %rsp,%rbp sub $rptr,%r11 and \$4095,%r11 cmp %r11,%r10 jb .Lpwrx_sp_alt sub %r11,%rbp # align with $aptr lea -320(%rbp,$num,2),%rbp # future alloca(frame+2*$num*8+256) jmp .Lpwrx_sp_done .align 32 .Lpwrx_sp_alt: lea 4096-320(,$num,2),%r10 lea -320(%rbp,$num,2),%rbp # alloca(frame+2*$num*8+256) sub %r10,%r11 mov \$0,%r10 cmovc %r10,%r11 sub %r11,%rbp .Lpwrx_sp_done: and \$-64,%rbp mov %rsp,%r11 sub %rbp,%r11 and \$-4096,%r11 lea (%rbp,%r11),%rsp mov (%rsp),%r10 cmp %rbp,%rsp ja .Lpwrx_page_walk jmp .Lpwrx_page_walk_done .Lpwrx_page_walk: lea -4096(%rsp),%rsp mov (%rsp),%r10 cmp %rbp,%rsp ja .Lpwrx_page_walk .Lpwrx_page_walk_done: mov $num,%r10 neg $num ############################################################## # Stack layout # # +0 saved $num, used in reduction section # +8 &t[2*$num], used in reduction section # +16 intermediate carry bit # +24 top-most carry bit, used in reduction section # +32 saved *n0 # +40 saved %rsp # +48 t[2*$num] # pxor %xmm0,%xmm0 movq $rptr,%xmm1 # save $rptr movq $nptr,%xmm2 # save $nptr movq %r10, %xmm3 # -$num movq $bptr,%xmm4 mov $n0, 32(%rsp) mov %rax, 40(%rsp) # save original %rsp .Lpowerx5_body: call __bn_sqrx8x_internal call __bn_postx4x_internal call __bn_sqrx8x_internal call __bn_postx4x_internal call __bn_sqrx8x_internal call __bn_postx4x_internal call __bn_sqrx8x_internal call __bn_postx4x_internal call __bn_sqrx8x_internal call __bn_postx4x_internal mov %r10,$num # -num mov $aptr,$rptr movq %xmm2,$nptr movq %xmm4,$bptr mov 40(%rsp),%rax call mulx4x_internal mov 40(%rsp),%rsi # restore %rsp mov \$1,%rax mov -48(%rsi),%r15 mov -40(%rsi),%r14 mov -32(%rsi),%r13 mov -24(%rsi),%r12 mov -16(%rsi),%rbp mov -8(%rsi),%rbx lea (%rsi),%rsp .Lpowerx5_epilogue: ret .size bn_powerx5,.-bn_powerx5 .globl bn_sqrx8x_internal .hidden bn_sqrx8x_internal .type bn_sqrx8x_internal,\@abi-omnipotent .align 32 bn_sqrx8x_internal: __bn_sqrx8x_internal: ################################################################## # Squaring part: # # a) multiply-n-add everything but a[i]*a[i]; # b) shift result of a) by 1 to the left and accumulate # a[i]*a[i] products; # ################################################################## # a[7]a[7]a[6]a[6]a[5]a[5]a[4]a[4]a[3]a[3]a[2]a[2]a[1]a[1]a[0]a[0] # a[1]a[0] # a[2]a[0] # a[3]a[0] # a[2]a[1] # a[3]a[1] # a[3]a[2] # # a[4]a[0] # a[5]a[0] # a[6]a[0] # a[7]a[0] # a[4]a[1] # a[5]a[1] # a[6]a[1] # a[7]a[1] # a[4]a[2] # a[5]a[2] # a[6]a[2] # a[7]a[2] # a[4]a[3] # a[5]a[3] # a[6]a[3] # a[7]a[3] # # a[5]a[4] # a[6]a[4] # a[7]a[4] # a[6]a[5] # a[7]a[5] # a[7]a[6] # a[7]a[7]a[6]a[6]a[5]a[5]a[4]a[4]a[3]a[3]a[2]a[2]a[1]a[1]a[0]a[0] ___ { my ($zero,$carry)=("%rbp","%rcx"); my $aaptr=$zero; $code.=<<___; lea 48+8(%rsp),$tptr lea ($aptr,$num),$aaptr mov $num,0+8(%rsp) # save $num mov $aaptr,8+8(%rsp) # save end of $aptr jmp .Lsqr8x_zero_start .align 32 .byte 0x66,0x66,0x66,0x2e,0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00 .Lsqrx8x_zero: .byte 0x3e movdqa %xmm0,0*8($tptr) movdqa %xmm0,2*8($tptr) movdqa %xmm0,4*8($tptr) movdqa %xmm0,6*8($tptr) .Lsqr8x_zero_start: # aligned at 32 movdqa %xmm0,8*8($tptr) movdqa %xmm0,10*8($tptr) movdqa %xmm0,12*8($tptr) movdqa %xmm0,14*8($tptr) lea 16*8($tptr),$tptr sub \$64,$num jnz .Lsqrx8x_zero mov 0*8($aptr),%rdx # a[0], modulo-scheduled #xor %r9,%r9 # t[1], ex-$num, zero already xor %r10,%r10 xor %r11,%r11 xor %r12,%r12 xor %r13,%r13 xor %r14,%r14 xor %r15,%r15 lea 48+8(%rsp),$tptr xor $zero,$zero # cf=0, cf=0 jmp .Lsqrx8x_outer_loop .align 32 .Lsqrx8x_outer_loop: mulx 1*8($aptr),%r8,%rax # a[1]*a[0] adcx %r9,%r8 # a[1]*a[0]+=t[1] adox %rax,%r10 mulx 2*8($aptr),%r9,%rax # a[2]*a[0] adcx %r10,%r9 adox %rax,%r11 .byte 0xc4,0xe2,0xab,0xf6,0x86,0x18,0x00,0x00,0x00 # mulx 3*8($aptr),%r10,%rax # ... adcx %r11,%r10 adox %rax,%r12 .byte 0xc4,0xe2,0xa3,0xf6,0x86,0x20,0x00,0x00,0x00 # mulx 4*8($aptr),%r11,%rax adcx %r12,%r11 adox %rax,%r13 mulx 5*8($aptr),%r12,%rax adcx %r13,%r12 adox %rax,%r14 mulx 6*8($aptr),%r13,%rax adcx %r14,%r13 adox %r15,%rax mulx 7*8($aptr),%r14,%r15 mov 1*8($aptr),%rdx # a[1] adcx %rax,%r14 adox $zero,%r15 adc 8*8($tptr),%r15 mov %r8,1*8($tptr) # t[1] mov %r9,2*8($tptr) # t[2] sbb $carry,$carry # mov %cf,$carry xor $zero,$zero # cf=0, of=0 mulx 2*8($aptr),%r8,%rbx # a[2]*a[1] mulx 3*8($aptr),%r9,%rax # a[3]*a[1] adcx %r10,%r8 adox %rbx,%r9 mulx 4*8($aptr),%r10,%rbx # ... adcx %r11,%r9 adox %rax,%r10 .byte 0xc4,0xe2,0xa3,0xf6,0x86,0x28,0x00,0x00,0x00 # mulx 5*8($aptr),%r11,%rax adcx %r12,%r10 adox %rbx,%r11 .byte 0xc4,0xe2,0x9b,0xf6,0x9e,0x30,0x00,0x00,0x00 # mulx 6*8($aptr),%r12,%rbx adcx %r13,%r11 adox %r14,%r12 .byte 0xc4,0x62,0x93,0xf6,0xb6,0x38,0x00,0x00,0x00 # mulx 7*8($aptr),%r13,%r14 mov 2*8($aptr),%rdx # a[2] adcx %rax,%r12 adox %rbx,%r13 adcx %r15,%r13 adox $zero,%r14 # of=0 adcx $zero,%r14 # cf=0 mov %r8,3*8($tptr) # t[3] mov %r9,4*8($tptr) # t[4] mulx 3*8($aptr),%r8,%rbx # a[3]*a[2] mulx 4*8($aptr),%r9,%rax # a[4]*a[2] adcx %r10,%r8 adox %rbx,%r9 mulx 5*8($aptr),%r10,%rbx # ... adcx %r11,%r9 adox %rax,%r10 .byte 0xc4,0xe2,0xa3,0xf6,0x86,0x30,0x00,0x00,0x00 # mulx 6*8($aptr),%r11,%rax adcx %r12,%r10 adox %r13,%r11 .byte 0xc4,0x62,0x9b,0xf6,0xae,0x38,0x00,0x00,0x00 # mulx 7*8($aptr),%r12,%r13 .byte 0x3e mov 3*8($aptr),%rdx # a[3] adcx %rbx,%r11 adox %rax,%r12 adcx %r14,%r12 mov %r8,5*8($tptr) # t[5] mov %r9,6*8($tptr) # t[6] mulx 4*8($aptr),%r8,%rax # a[4]*a[3] adox $zero,%r13 # of=0 adcx $zero,%r13 # cf=0 mulx 5*8($aptr),%r9,%rbx # a[5]*a[3] adcx %r10,%r8 adox %rax,%r9 mulx 6*8($aptr),%r10,%rax # ... adcx %r11,%r9 adox %r12,%r10 mulx 7*8($aptr),%r11,%r12 mov 4*8($aptr),%rdx # a[4] mov 5*8($aptr),%r14 # a[5] adcx %rbx,%r10 adox %rax,%r11 mov 6*8($aptr),%r15 # a[6] adcx %r13,%r11 adox $zero,%r12 # of=0 adcx $zero,%r12 # cf=0 mov %r8,7*8($tptr) # t[7] mov %r9,8*8($tptr) # t[8] mulx %r14,%r9,%rax # a[5]*a[4] mov 7*8($aptr),%r8 # a[7] adcx %r10,%r9 mulx %r15,%r10,%rbx # a[6]*a[4] adox %rax,%r10 adcx %r11,%r10 mulx %r8,%r11,%rax # a[7]*a[4] mov %r14,%rdx # a[5] adox %rbx,%r11 adcx %r12,%r11 #adox $zero,%rax # of=0 adcx $zero,%rax # cf=0 mulx %r15,%r14,%rbx # a[6]*a[5] mulx %r8,%r12,%r13 # a[7]*a[5] mov %r15,%rdx # a[6] lea 8*8($aptr),$aptr adcx %r14,%r11 adox %rbx,%r12 adcx %rax,%r12 adox $zero,%r13 .byte 0x67,0x67 mulx %r8,%r8,%r14 # a[7]*a[6] adcx %r8,%r13 adcx $zero,%r14 cmp 8+8(%rsp),$aptr je .Lsqrx8x_outer_break neg $carry # mov $carry,%cf mov \$-8,%rcx mov $zero,%r15 mov 8*8($tptr),%r8 adcx 9*8($tptr),%r9 # +=t[9] adcx 10*8($tptr),%r10 # ... adcx 11*8($tptr),%r11 adc 12*8($tptr),%r12 adc 13*8($tptr),%r13 adc 14*8($tptr),%r14 adc 15*8($tptr),%r15 lea ($aptr),$aaptr lea 2*64($tptr),$tptr sbb %rax,%rax # mov %cf,$carry mov -64($aptr),%rdx # a[0] mov %rax,16+8(%rsp) # offload $carry mov $tptr,24+8(%rsp) #lea 8*8($tptr),$tptr # see 2*8*8($tptr) above xor %eax,%eax # cf=0, of=0 jmp .Lsqrx8x_loop .align 32 .Lsqrx8x_loop: mov %r8,%rbx mulx 0*8($aaptr),%rax,%r8 # a[8]*a[i] adcx %rax,%rbx # +=t[8] adox %r9,%r8 mulx 1*8($aaptr),%rax,%r9 # ... adcx %rax,%r8 adox %r10,%r9 mulx 2*8($aaptr),%rax,%r10 adcx %rax,%r9 adox %r11,%r10 mulx 3*8($aaptr),%rax,%r11 adcx %rax,%r10 adox %r12,%r11 .byte 0xc4,0x62,0xfb,0xf6,0xa5,0x20,0x00,0x00,0x00 # mulx 4*8($aaptr),%rax,%r12 adcx %rax,%r11 adox %r13,%r12 mulx 5*8($aaptr),%rax,%r13 adcx %rax,%r12 adox %r14,%r13 mulx 6*8($aaptr),%rax,%r14 mov %rbx,($tptr,%rcx,8) # store t[8+i] mov \$0,%ebx adcx %rax,%r13 adox %r15,%r14 .byte 0xc4,0x62,0xfb,0xf6,0xbd,0x38,0x00,0x00,0x00 # mulx 7*8($aaptr),%rax,%r15 mov 8($aptr,%rcx,8),%rdx # a[i] adcx %rax,%r14 adox %rbx,%r15 # %rbx is 0, of=0 adcx %rbx,%r15 # cf=0 .byte 0x67 inc %rcx # of=0 jnz .Lsqrx8x_loop lea 8*8($aaptr),$aaptr mov \$-8,%rcx cmp 8+8(%rsp),$aaptr # done? je .Lsqrx8x_break sub 16+8(%rsp),%rbx # mov 16(%rsp),%cf .byte 0x66 mov -64($aptr),%rdx adcx 0*8($tptr),%r8 adcx 1*8($tptr),%r9 adc 2*8($tptr),%r10 adc 3*8($tptr),%r11 adc 4*8($tptr),%r12 adc 5*8($tptr),%r13 adc 6*8($tptr),%r14 adc 7*8($tptr),%r15 lea 8*8($tptr),$tptr .byte 0x67 sbb %rax,%rax # mov %cf,%rax xor %ebx,%ebx # cf=0, of=0 mov %rax,16+8(%rsp) # offload carry jmp .Lsqrx8x_loop .align 32 .Lsqrx8x_break: - sub 16+8(%rsp),%r8 # consume last carry + xor $zero,$zero + sub 16+8(%rsp),%rbx # mov 16(%rsp),%cf + adcx $zero,%r8 mov 24+8(%rsp),$carry # initial $tptr, borrow $carry + adcx $zero,%r9 mov 0*8($aptr),%rdx # a[8], modulo-scheduled - xor %ebp,%ebp # xor $zero,$zero + adc \$0,%r10 mov %r8,0*8($tptr) + adc \$0,%r11 + adc \$0,%r12 + adc \$0,%r13 + adc \$0,%r14 + adc \$0,%r15 cmp $carry,$tptr # cf=0, of=0 je .Lsqrx8x_outer_loop mov %r9,1*8($tptr) mov 1*8($carry),%r9 mov %r10,2*8($tptr) mov 2*8($carry),%r10 mov %r11,3*8($tptr) mov 3*8($carry),%r11 mov %r12,4*8($tptr) mov 4*8($carry),%r12 mov %r13,5*8($tptr) mov 5*8($carry),%r13 mov %r14,6*8($tptr) mov 6*8($carry),%r14 mov %r15,7*8($tptr) mov 7*8($carry),%r15 mov $carry,$tptr jmp .Lsqrx8x_outer_loop .align 32 .Lsqrx8x_outer_break: mov %r9,9*8($tptr) # t[9] movq %xmm3,%rcx # -$num mov %r10,10*8($tptr) # ... mov %r11,11*8($tptr) mov %r12,12*8($tptr) mov %r13,13*8($tptr) mov %r14,14*8($tptr) ___ } { my $i="%rcx"; $code.=<<___; lea 48+8(%rsp),$tptr mov ($aptr,$i),%rdx # a[0] mov 8($tptr),$A0[1] # t[1] xor $A0[0],$A0[0] # t[0], of=0, cf=0 mov 0+8(%rsp),$num # restore $num adox $A0[1],$A0[1] mov 16($tptr),$A1[0] # t[2] # prefetch mov 24($tptr),$A1[1] # t[3] # prefetch #jmp .Lsqrx4x_shift_n_add # happens to be aligned .align 32 .Lsqrx4x_shift_n_add: mulx %rdx,%rax,%rbx adox $A1[0],$A1[0] adcx $A0[0],%rax .byte 0x48,0x8b,0x94,0x0e,0x08,0x00,0x00,0x00 # mov 8($aptr,$i),%rdx # a[i+1] # prefetch .byte 0x4c,0x8b,0x97,0x20,0x00,0x00,0x00 # mov 32($tptr),$A0[0] # t[2*i+4] # prefetch adox $A1[1],$A1[1] adcx $A0[1],%rbx mov 40($tptr),$A0[1] # t[2*i+4+1] # prefetch mov %rax,0($tptr) mov %rbx,8($tptr) mulx %rdx,%rax,%rbx adox $A0[0],$A0[0] adcx $A1[0],%rax mov 16($aptr,$i),%rdx # a[i+2] # prefetch mov 48($tptr),$A1[0] # t[2*i+6] # prefetch adox $A0[1],$A0[1] adcx $A1[1],%rbx mov 56($tptr),$A1[1] # t[2*i+6+1] # prefetch mov %rax,16($tptr) mov %rbx,24($tptr) mulx %rdx,%rax,%rbx adox $A1[0],$A1[0] adcx $A0[0],%rax mov 24($aptr,$i),%rdx # a[i+3] # prefetch lea 32($i),$i mov 64($tptr),$A0[0] # t[2*i+8] # prefetch adox $A1[1],$A1[1] adcx $A0[1],%rbx mov 72($tptr),$A0[1] # t[2*i+8+1] # prefetch mov %rax,32($tptr) mov %rbx,40($tptr) mulx %rdx,%rax,%rbx adox $A0[0],$A0[0] adcx $A1[0],%rax jrcxz .Lsqrx4x_shift_n_add_break .byte 0x48,0x8b,0x94,0x0e,0x00,0x00,0x00,0x00 # mov 0($aptr,$i),%rdx # a[i+4] # prefetch adox $A0[1],$A0[1] adcx $A1[1],%rbx mov 80($tptr),$A1[0] # t[2*i+10] # prefetch mov 88($tptr),$A1[1] # t[2*i+10+1] # prefetch mov %rax,48($tptr) mov %rbx,56($tptr) lea 64($tptr),$tptr nop jmp .Lsqrx4x_shift_n_add .align 32 .Lsqrx4x_shift_n_add_break: adcx $A1[1],%rbx mov %rax,48($tptr) mov %rbx,56($tptr) lea 64($tptr),$tptr # end of t[] buffer ___ } ###################################################################### # Montgomery reduction part, "word-by-word" algorithm. # # This new path is inspired by multiple submissions from Intel, by # Shay Gueron, Vlad Krasnov, Erdinc Ozturk, James Guilford, # Vinodh Gopal... { my ($nptr,$carry,$m0)=("%rbp","%rsi","%rdx"); $code.=<<___; movq %xmm2,$nptr __bn_sqrx8x_reduction: xor %eax,%eax # initial top-most carry bit mov 32+8(%rsp),%rbx # n0 mov 48+8(%rsp),%rdx # "%r8", 8*0($tptr) lea -8*8($nptr,$num),%rcx # end of n[] #lea 48+8(%rsp,$num,2),$tptr # end of t[] buffer mov %rcx, 0+8(%rsp) # save end of n[] mov $tptr,8+8(%rsp) # save end of t[] lea 48+8(%rsp),$tptr # initial t[] window jmp .Lsqrx8x_reduction_loop .align 32 .Lsqrx8x_reduction_loop: mov 8*1($tptr),%r9 mov 8*2($tptr),%r10 mov 8*3($tptr),%r11 mov 8*4($tptr),%r12 mov %rdx,%r8 imulq %rbx,%rdx # n0*a[i] mov 8*5($tptr),%r13 mov 8*6($tptr),%r14 mov 8*7($tptr),%r15 mov %rax,24+8(%rsp) # store top-most carry bit lea 8*8($tptr),$tptr xor $carry,$carry # cf=0,of=0 mov \$-8,%rcx jmp .Lsqrx8x_reduce .align 32 .Lsqrx8x_reduce: mov %r8, %rbx mulx 8*0($nptr),%rax,%r8 # n[0] adcx %rbx,%rax # discarded adox %r9,%r8 mulx 8*1($nptr),%rbx,%r9 # n[1] adcx %rbx,%r8 adox %r10,%r9 mulx 8*2($nptr),%rbx,%r10 adcx %rbx,%r9 adox %r11,%r10 mulx 8*3($nptr),%rbx,%r11 adcx %rbx,%r10 adox %r12,%r11 .byte 0xc4,0x62,0xe3,0xf6,0xa5,0x20,0x00,0x00,0x00 # mulx 8*4($nptr),%rbx,%r12 mov %rdx,%rax mov %r8,%rdx adcx %rbx,%r11 adox %r13,%r12 mulx 32+8(%rsp),%rbx,%rdx # %rdx discarded mov %rax,%rdx mov %rax,64+48+8(%rsp,%rcx,8) # put aside n0*a[i] mulx 8*5($nptr),%rax,%r13 adcx %rax,%r12 adox %r14,%r13 mulx 8*6($nptr),%rax,%r14 adcx %rax,%r13 adox %r15,%r14 mulx 8*7($nptr),%rax,%r15 mov %rbx,%rdx adcx %rax,%r14 adox $carry,%r15 # $carry is 0 adcx $carry,%r15 # cf=0 .byte 0x67,0x67,0x67 inc %rcx # of=0 jnz .Lsqrx8x_reduce mov $carry,%rax # xor %rax,%rax cmp 0+8(%rsp),$nptr # end of n[]? jae .Lsqrx8x_no_tail mov 48+8(%rsp),%rdx # pull n0*a[0] add 8*0($tptr),%r8 lea 8*8($nptr),$nptr mov \$-8,%rcx adcx 8*1($tptr),%r9 adcx 8*2($tptr),%r10 adc 8*3($tptr),%r11 adc 8*4($tptr),%r12 adc 8*5($tptr),%r13 adc 8*6($tptr),%r14 adc 8*7($tptr),%r15 lea 8*8($tptr),$tptr sbb %rax,%rax # top carry xor $carry,$carry # of=0, cf=0 mov %rax,16+8(%rsp) jmp .Lsqrx8x_tail .align 32 .Lsqrx8x_tail: mov %r8,%rbx mulx 8*0($nptr),%rax,%r8 adcx %rax,%rbx adox %r9,%r8 mulx 8*1($nptr),%rax,%r9 adcx %rax,%r8 adox %r10,%r9 mulx 8*2($nptr),%rax,%r10 adcx %rax,%r9 adox %r11,%r10 mulx 8*3($nptr),%rax,%r11 adcx %rax,%r10 adox %r12,%r11 .byte 0xc4,0x62,0xfb,0xf6,0xa5,0x20,0x00,0x00,0x00 # mulx 8*4($nptr),%rax,%r12 adcx %rax,%r11 adox %r13,%r12 mulx 8*5($nptr),%rax,%r13 adcx %rax,%r12 adox %r14,%r13 mulx 8*6($nptr),%rax,%r14 adcx %rax,%r13 adox %r15,%r14 mulx 8*7($nptr),%rax,%r15 mov 72+48+8(%rsp,%rcx,8),%rdx # pull n0*a[i] adcx %rax,%r14 adox $carry,%r15 mov %rbx,($tptr,%rcx,8) # save result mov %r8,%rbx adcx $carry,%r15 # cf=0 inc %rcx # of=0 jnz .Lsqrx8x_tail cmp 0+8(%rsp),$nptr # end of n[]? jae .Lsqrx8x_tail_done # break out of loop sub 16+8(%rsp),$carry # mov 16(%rsp),%cf mov 48+8(%rsp),%rdx # pull n0*a[0] lea 8*8($nptr),$nptr adc 8*0($tptr),%r8 adc 8*1($tptr),%r9 adc 8*2($tptr),%r10 adc 8*3($tptr),%r11 adc 8*4($tptr),%r12 adc 8*5($tptr),%r13 adc 8*6($tptr),%r14 adc 8*7($tptr),%r15 lea 8*8($tptr),$tptr sbb %rax,%rax sub \$8,%rcx # mov \$-8,%rcx xor $carry,$carry # of=0, cf=0 mov %rax,16+8(%rsp) jmp .Lsqrx8x_tail .align 32 .Lsqrx8x_tail_done: xor %rax,%rax add 24+8(%rsp),%r8 # can this overflow? adc \$0,%r9 adc \$0,%r10 adc \$0,%r11 adc \$0,%r12 adc \$0,%r13 adc \$0,%r14 adc \$0,%r15 adc \$0,%rax sub 16+8(%rsp),$carry # mov 16(%rsp),%cf .Lsqrx8x_no_tail: # %cf is 0 if jumped here adc 8*0($tptr),%r8 movq %xmm3,%rcx adc 8*1($tptr),%r9 mov 8*7($nptr),$carry movq %xmm2,$nptr # restore $nptr adc 8*2($tptr),%r10 adc 8*3($tptr),%r11 adc 8*4($tptr),%r12 adc 8*5($tptr),%r13 adc 8*6($tptr),%r14 adc 8*7($tptr),%r15 adc \$0,%rax # top-most carry mov 32+8(%rsp),%rbx # n0 mov 8*8($tptr,%rcx),%rdx # modulo-scheduled "%r8" mov %r8,8*0($tptr) # store top 512 bits lea 8*8($tptr),%r8 # borrow %r8 mov %r9,8*1($tptr) mov %r10,8*2($tptr) mov %r11,8*3($tptr) mov %r12,8*4($tptr) mov %r13,8*5($tptr) mov %r14,8*6($tptr) mov %r15,8*7($tptr) lea 8*8($tptr,%rcx),$tptr # start of current t[] window cmp 8+8(%rsp),%r8 # end of t[]? jb .Lsqrx8x_reduction_loop ret .size bn_sqrx8x_internal,.-bn_sqrx8x_internal ___ } ############################################################## # Post-condition, 4x unrolled # { my ($rptr,$nptr)=("%rdx","%rbp"); $code.=<<___; .align 32 __bn_postx4x_internal: mov 8*0($nptr),%r12 mov %rcx,%r10 # -$num mov %rcx,%r9 # -$num neg %rax sar \$3+2,%rcx #lea 48+8(%rsp,%r9),$tptr movq %xmm1,$rptr # restore $rptr movq %xmm1,$aptr # prepare for back-to-back call dec %r12 # so that after 'not' we get -n[0] mov 8*1($nptr),%r13 xor %r8,%r8 mov 8*2($nptr),%r14 mov 8*3($nptr),%r15 jmp .Lsqrx4x_sub_entry .align 16 .Lsqrx4x_sub: mov 8*0($nptr),%r12 mov 8*1($nptr),%r13 mov 8*2($nptr),%r14 mov 8*3($nptr),%r15 .Lsqrx4x_sub_entry: andn %rax,%r12,%r12 lea 8*4($nptr),$nptr andn %rax,%r13,%r13 andn %rax,%r14,%r14 andn %rax,%r15,%r15 neg %r8 # mov %r8,%cf adc 8*0($tptr),%r12 adc 8*1($tptr),%r13 adc 8*2($tptr),%r14 adc 8*3($tptr),%r15 mov %r12,8*0($rptr) lea 8*4($tptr),$tptr mov %r13,8*1($rptr) sbb %r8,%r8 # mov %cf,%r8 mov %r14,8*2($rptr) mov %r15,8*3($rptr) lea 8*4($rptr),$rptr inc %rcx jnz .Lsqrx4x_sub neg %r9 # restore $num ret .size __bn_postx4x_internal,.-__bn_postx4x_internal ___ } }}} { my ($inp,$num,$tbl,$idx)=$win64?("%rcx","%edx","%r8", "%r9d") : # Win64 order ("%rdi","%esi","%rdx","%ecx"); # Unix order my $out=$inp; my $STRIDE=2**5*8; my $N=$STRIDE/4; $code.=<<___; .globl bn_get_bits5 .type bn_get_bits5,\@abi-omnipotent .align 16 bn_get_bits5: lea 0($inp),%r10 lea 1($inp),%r11 mov $num,%ecx shr \$4,$num and \$15,%ecx lea -8(%ecx),%eax cmp \$11,%ecx cmova %r11,%r10 cmova %eax,%ecx movzw (%r10,$num,2),%eax shrl %cl,%eax and \$31,%eax ret .size bn_get_bits5,.-bn_get_bits5 .globl bn_scatter5 .type bn_scatter5,\@abi-omnipotent .align 16 bn_scatter5: cmp \$0, $num jz .Lscatter_epilogue lea ($tbl,$idx,8),$tbl .Lscatter: mov ($inp),%rax lea 8($inp),$inp mov %rax,($tbl) lea 32*8($tbl),$tbl sub \$1,$num jnz .Lscatter .Lscatter_epilogue: ret .size bn_scatter5,.-bn_scatter5 .globl bn_gather5 .type bn_gather5,\@abi-omnipotent .align 32 bn_gather5: .LSEH_begin_bn_gather5: # Win64 thing, but harmless in other cases # I can't trust assembler to use specific encoding:-( .byte 0x4c,0x8d,0x14,0x24 #lea (%rsp),%r10 .byte 0x48,0x81,0xec,0x08,0x01,0x00,0x00 #sub $0x108,%rsp lea .Linc(%rip),%rax and \$-16,%rsp # shouldn't be formally required movd $idx,%xmm5 movdqa 0(%rax),%xmm0 # 00000001000000010000000000000000 movdqa 16(%rax),%xmm1 # 00000002000000020000000200000002 lea 128($tbl),%r11 # size optimization lea 128(%rsp),%rax # size optimization pshufd \$0,%xmm5,%xmm5 # broadcast $idx movdqa %xmm1,%xmm4 movdqa %xmm1,%xmm2 ___ ######################################################################## # calculate mask by comparing 0..31 to $idx and save result to stack # for($i=0;$i<$STRIDE/16;$i+=4) { $code.=<<___; paddd %xmm0,%xmm1 pcmpeqd %xmm5,%xmm0 # compare to 1,0 ___ $code.=<<___ if ($i); movdqa %xmm3,`16*($i-1)-128`(%rax) ___ $code.=<<___; movdqa %xmm4,%xmm3 paddd %xmm1,%xmm2 pcmpeqd %xmm5,%xmm1 # compare to 3,2 movdqa %xmm0,`16*($i+0)-128`(%rax) movdqa %xmm4,%xmm0 paddd %xmm2,%xmm3 pcmpeqd %xmm5,%xmm2 # compare to 5,4 movdqa %xmm1,`16*($i+1)-128`(%rax) movdqa %xmm4,%xmm1 paddd %xmm3,%xmm0 pcmpeqd %xmm5,%xmm3 # compare to 7,6 movdqa %xmm2,`16*($i+2)-128`(%rax) movdqa %xmm4,%xmm2 ___ } $code.=<<___; movdqa %xmm3,`16*($i-1)-128`(%rax) jmp .Lgather .align 32 .Lgather: pxor %xmm4,%xmm4 pxor %xmm5,%xmm5 ___ for($i=0;$i<$STRIDE/16;$i+=4) { $code.=<<___; movdqa `16*($i+0)-128`(%r11),%xmm0 movdqa `16*($i+1)-128`(%r11),%xmm1 movdqa `16*($i+2)-128`(%r11),%xmm2 pand `16*($i+0)-128`(%rax),%xmm0 movdqa `16*($i+3)-128`(%r11),%xmm3 pand `16*($i+1)-128`(%rax),%xmm1 por %xmm0,%xmm4 pand `16*($i+2)-128`(%rax),%xmm2 por %xmm1,%xmm5 pand `16*($i+3)-128`(%rax),%xmm3 por %xmm2,%xmm4 por %xmm3,%xmm5 ___ } $code.=<<___; por %xmm5,%xmm4 lea $STRIDE(%r11),%r11 pshufd \$0x4e,%xmm4,%xmm0 por %xmm4,%xmm0 movq %xmm0,($out) # m0=bp[0] lea 8($out),$out sub \$1,$num jnz .Lgather lea (%r10),%rsp ret .LSEH_end_bn_gather5: .size bn_gather5,.-bn_gather5 ___ } $code.=<<___; .align 64 .Linc: .long 0,0, 1,1 .long 2,2, 2,2 .asciz "Montgomery Multiplication with scatter/gather for x86_64, CRYPTOGAMS by " ___ # 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 mul_handler,\@abi-omnipotent .align 16 mul_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 # end of prologue label cmp %r10,%rbx # context->RipRip>=epilogue label jb .Lcommon_pop_regs mov 152($context),%rax # pull context->Rsp mov 8(%r11),%r10d # HandlerData[2] lea (%rsi,%r10),%r10 # epilogue label cmp %r10,%rbx # context->Rip>=epilogue label jae .Lcommon_seh_tail lea .Lmul_epilogue(%rip),%r10 cmp %r10,%rbx ja .Lbody_40 mov 192($context),%r10 # pull $num mov 8(%rax,%r10,8),%rax # pull saved stack pointer jmp .Lcommon_pop_regs .Lbody_40: mov 40(%rax),%rax # pull saved stack pointer .Lcommon_pop_regs: mov -8(%rax),%rbx mov -16(%rax),%rbp mov -24(%rax),%r12 mov -32(%rax),%r13 mov -40(%rax),%r14 mov -48(%rax),%r15 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 mul_handler,.-mul_handler .section .pdata .align 4 .rva .LSEH_begin_bn_mul_mont_gather5 .rva .LSEH_end_bn_mul_mont_gather5 .rva .LSEH_info_bn_mul_mont_gather5 .rva .LSEH_begin_bn_mul4x_mont_gather5 .rva .LSEH_end_bn_mul4x_mont_gather5 .rva .LSEH_info_bn_mul4x_mont_gather5 .rva .LSEH_begin_bn_power5 .rva .LSEH_end_bn_power5 .rva .LSEH_info_bn_power5 .rva .LSEH_begin_bn_from_mont8x .rva .LSEH_end_bn_from_mont8x .rva .LSEH_info_bn_from_mont8x ___ $code.=<<___ if ($addx); .rva .LSEH_begin_bn_mulx4x_mont_gather5 .rva .LSEH_end_bn_mulx4x_mont_gather5 .rva .LSEH_info_bn_mulx4x_mont_gather5 .rva .LSEH_begin_bn_powerx5 .rva .LSEH_end_bn_powerx5 .rva .LSEH_info_bn_powerx5 ___ $code.=<<___; .rva .LSEH_begin_bn_gather5 .rva .LSEH_end_bn_gather5 .rva .LSEH_info_bn_gather5 .section .xdata .align 8 .LSEH_info_bn_mul_mont_gather5: .byte 9,0,0,0 .rva mul_handler .rva .Lmul_body,.Lmul_body,.Lmul_epilogue # HandlerData[] .align 8 .LSEH_info_bn_mul4x_mont_gather5: .byte 9,0,0,0 .rva mul_handler .rva .Lmul4x_prologue,.Lmul4x_body,.Lmul4x_epilogue # HandlerData[] .align 8 .LSEH_info_bn_power5: .byte 9,0,0,0 .rva mul_handler .rva .Lpower5_prologue,.Lpower5_body,.Lpower5_epilogue # HandlerData[] .align 8 .LSEH_info_bn_from_mont8x: .byte 9,0,0,0 .rva mul_handler .rva .Lfrom_prologue,.Lfrom_body,.Lfrom_epilogue # HandlerData[] ___ $code.=<<___ if ($addx); .align 8 .LSEH_info_bn_mulx4x_mont_gather5: .byte 9,0,0,0 .rva mul_handler .rva .Lmulx4x_prologue,.Lmulx4x_body,.Lmulx4x_epilogue # HandlerData[] .align 8 .LSEH_info_bn_powerx5: .byte 9,0,0,0 .rva mul_handler .rva .Lpowerx5_prologue,.Lpowerx5_body,.Lpowerx5_epilogue # HandlerData[] ___ $code.=<<___; .align 8 .LSEH_info_bn_gather5: .byte 0x01,0x0b,0x03,0x0a .byte 0x0b,0x01,0x21,0x00 # sub rsp,0x108 .byte 0x04,0xa3,0x00,0x00 # lea r10,(rsp) .align 8 ___ } $code =~ s/\`([^\`]*)\`/eval($1)/gem; print $code; close STDOUT; Index: vendor-crypto/openssl/dist/crypto/bn/bn_exp.c =================================================================== --- vendor-crypto/openssl/dist/crypto/bn/bn_exp.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/bn/bn_exp.c (revision 325326) @@ -1,1458 +1,1468 @@ /* crypto/bn/bn_exp.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-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). * */ #include "cryptlib.h" #include "constant_time_locl.h" #include "bn_lcl.h" #include #ifdef _WIN32 # include # ifndef alloca # define alloca _alloca # endif #elif defined(__GNUC__) # ifndef alloca # define alloca(s) __builtin_alloca((s)) # endif #elif defined(__sun) # include #endif #include "rsaz_exp.h" #undef SPARC_T4_MONT #if defined(OPENSSL_BN_ASM_MONT) && (defined(__sparc__) || defined(__sparc)) # include "sparc_arch.h" extern unsigned int OPENSSL_sparcv9cap_P[]; # define SPARC_T4_MONT #endif /* maximum precomputation table size for *variable* sliding windows */ #define TABLE_SIZE 32 /* this one works - simple but works */ int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { int i, bits, ret = 0; BIGNUM *v, *rr; - if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) { + if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0 + || BN_get_flags(a, BN_FLG_CONSTTIME) != 0) { /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */ BNerr(BN_F_BN_EXP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return -1; } BN_CTX_start(ctx); if ((r == a) || (r == p)) rr = BN_CTX_get(ctx); else rr = r; v = BN_CTX_get(ctx); if (rr == NULL || v == NULL) goto err; if (BN_copy(v, a) == NULL) goto err; bits = BN_num_bits(p); if (BN_is_odd(p)) { if (BN_copy(rr, a) == NULL) goto err; } else { if (!BN_one(rr)) goto err; } for (i = 1; i < bits; i++) { if (!BN_sqr(v, v, ctx)) goto err; if (BN_is_bit_set(p, i)) { if (!BN_mul(rr, rr, v, ctx)) goto err; } } if (r != rr && BN_copy(r, rr) == NULL) goto err; ret = 1; err: BN_CTX_end(ctx); bn_check_top(r); return (ret); } int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx) { int ret; bn_check_top(a); bn_check_top(p); bn_check_top(m); /*- * For even modulus m = 2^k*m_odd, it might make sense to compute * a^p mod m_odd and a^p mod 2^k separately (with Montgomery * exponentiation for the odd part), using appropriate exponent * reductions, and combine the results using the CRT. * * For now, we use Montgomery only if the modulus is odd; otherwise, * exponentiation using the reciprocal-based quick remaindering * algorithm is used. * * (Timing obtained with expspeed.c [computations a^p mod m * where a, p, m are of the same length: 256, 512, 1024, 2048, * 4096, 8192 bits], compared to the running time of the * standard algorithm: * * BN_mod_exp_mont 33 .. 40 % [AMD K6-2, Linux, debug configuration] * 55 .. 77 % [UltraSparc processor, but * debug-solaris-sparcv8-gcc conf.] * * BN_mod_exp_recp 50 .. 70 % [AMD K6-2, Linux, debug configuration] * 62 .. 118 % [UltraSparc, debug-solaris-sparcv8-gcc] * * On the Sparc, BN_mod_exp_recp was faster than BN_mod_exp_mont * at 2048 and more bits, but at 512 and 1024 bits, it was * slower even than the standard algorithm! * * "Real" timings [linux-elf, solaris-sparcv9-gcc configurations] * should be obtained when the new Montgomery reduction code * has been integrated into OpenSSL.) */ #define MONT_MUL_MOD #define MONT_EXP_WORD #define RECP_MUL_MOD #ifdef MONT_MUL_MOD /* * I have finally been able to take out this pre-condition of the top bit * being set. It was caused by an error in BN_div with negatives. There * was also another problem when for a^b%m a >= m. eay 07-May-97 */ /* if ((m->d[m->top-1]&BN_TBIT) && BN_is_odd(m)) */ if (BN_is_odd(m)) { # ifdef MONT_EXP_WORD if (a->top == 1 && !a->neg - && (BN_get_flags(p, BN_FLG_CONSTTIME) == 0)) { + && (BN_get_flags(p, BN_FLG_CONSTTIME) == 0) + && (BN_get_flags(a, BN_FLG_CONSTTIME) == 0) + && (BN_get_flags(m, BN_FLG_CONSTTIME) == 0)) { BN_ULONG A = a->d[0]; ret = BN_mod_exp_mont_word(r, A, p, m, ctx, NULL); } else # endif ret = BN_mod_exp_mont(r, a, p, m, ctx, NULL); } else #endif #ifdef RECP_MUL_MOD { ret = BN_mod_exp_recp(r, a, p, m, ctx); } #else { ret = BN_mod_exp_simple(r, a, p, m, ctx); } #endif bn_check_top(r); return (ret); } int BN_mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx) { int i, j, bits, ret = 0, wstart, wend, window, wvalue; int start = 1; BIGNUM *aa; /* Table of variables obtained from 'ctx' */ BIGNUM *val[TABLE_SIZE]; BN_RECP_CTX recp; - if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) { + if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0 + || BN_get_flags(a, BN_FLG_CONSTTIME) != 0 + || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) { /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */ BNerr(BN_F_BN_MOD_EXP_RECP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return -1; } bits = BN_num_bits(p); if (bits == 0) { /* x**0 mod 1 is still zero. */ if (BN_is_one(m)) { ret = 1; BN_zero(r); } else { ret = BN_one(r); } return ret; } BN_CTX_start(ctx); aa = BN_CTX_get(ctx); val[0] = BN_CTX_get(ctx); if (!aa || !val[0]) goto err; BN_RECP_CTX_init(&recp); if (m->neg) { /* ignore sign of 'm' */ if (!BN_copy(aa, m)) goto err; aa->neg = 0; if (BN_RECP_CTX_set(&recp, aa, ctx) <= 0) goto err; } else { if (BN_RECP_CTX_set(&recp, m, ctx) <= 0) goto err; } if (!BN_nnmod(val[0], a, m, ctx)) goto err; /* 1 */ if (BN_is_zero(val[0])) { BN_zero(r); ret = 1; goto err; } window = BN_window_bits_for_exponent_size(bits); if (window > 1) { if (!BN_mod_mul_reciprocal(aa, val[0], val[0], &recp, ctx)) goto err; /* 2 */ j = 1 << (window - 1); for (i = 1; i < j; i++) { if (((val[i] = BN_CTX_get(ctx)) == NULL) || !BN_mod_mul_reciprocal(val[i], val[i - 1], aa, &recp, ctx)) goto err; } } start = 1; /* This is used to avoid multiplication etc * when there is only the value '1' in the * buffer. */ wvalue = 0; /* The 'value' of the window */ wstart = bits - 1; /* The top bit of the window */ wend = 0; /* The bottom bit of the window */ if (!BN_one(r)) goto err; for (;;) { if (BN_is_bit_set(p, wstart) == 0) { if (!start) if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx)) goto err; if (wstart == 0) break; wstart--; continue; } /* * We now have wstart on a 'set' bit, we now need to work out how bit * a window to do. To do this we need to scan forward until the last * set bit before the end of the window */ j = wstart; wvalue = 1; wend = 0; for (i = 1; i < window; i++) { if (wstart - i < 0) break; if (BN_is_bit_set(p, wstart - i)) { wvalue <<= (i - wend); wvalue |= 1; wend = i; } } /* wend is the size of the current window */ j = wend + 1; /* add the 'bytes above' */ if (!start) for (i = 0; i < j; i++) { if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx)) goto err; } /* wvalue will be an odd number < 2^window */ if (!BN_mod_mul_reciprocal(r, r, val[wvalue >> 1], &recp, ctx)) goto err; /* move the 'window' down further */ wstart -= wend + 1; wvalue = 0; start = 0; if (wstart < 0) break; } ret = 1; err: BN_CTX_end(ctx); BN_RECP_CTX_free(&recp); bn_check_top(r); return (ret); } int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont) { int i, j, bits, ret = 0, wstart, wend, window, wvalue; int start = 1; BIGNUM *d, *r; const BIGNUM *aa; /* Table of variables obtained from 'ctx' */ BIGNUM *val[TABLE_SIZE]; BN_MONT_CTX *mont = NULL; - if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) { + if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0 + || BN_get_flags(a, BN_FLG_CONSTTIME) != 0 + || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) { return BN_mod_exp_mont_consttime(rr, a, p, m, ctx, in_mont); } bn_check_top(a); bn_check_top(p); bn_check_top(m); if (!BN_is_odd(m)) { BNerr(BN_F_BN_MOD_EXP_MONT, BN_R_CALLED_WITH_EVEN_MODULUS); return (0); } bits = BN_num_bits(p); if (bits == 0) { /* x**0 mod 1 is still zero. */ if (BN_is_one(m)) { ret = 1; BN_zero(rr); } else { ret = BN_one(rr); } return ret; } BN_CTX_start(ctx); d = BN_CTX_get(ctx); r = BN_CTX_get(ctx); val[0] = BN_CTX_get(ctx); if (!d || !r || !val[0]) goto err; /* * If this is not done, things will break in the montgomery part */ if (in_mont != NULL) mont = in_mont; else { if ((mont = BN_MONT_CTX_new()) == NULL) goto err; if (!BN_MONT_CTX_set(mont, m, ctx)) goto err; } if (a->neg || BN_ucmp(a, m) >= 0) { if (!BN_nnmod(val[0], a, m, ctx)) goto err; aa = val[0]; } else aa = a; if (BN_is_zero(aa)) { BN_zero(rr); ret = 1; goto err; } if (!BN_to_montgomery(val[0], aa, mont, ctx)) goto err; /* 1 */ window = BN_window_bits_for_exponent_size(bits); if (window > 1) { if (!BN_mod_mul_montgomery(d, val[0], val[0], mont, ctx)) goto err; /* 2 */ j = 1 << (window - 1); for (i = 1; i < j; i++) { if (((val[i] = BN_CTX_get(ctx)) == NULL) || !BN_mod_mul_montgomery(val[i], val[i - 1], d, mont, ctx)) goto err; } } start = 1; /* This is used to avoid multiplication etc * when there is only the value '1' in the * buffer. */ wvalue = 0; /* The 'value' of the window */ wstart = bits - 1; /* The top bit of the window */ wend = 0; /* The bottom bit of the window */ #if 1 /* by Shay Gueron's suggestion */ j = m->top; /* borrow j */ if (m->d[j - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) { if (bn_wexpand(r, j) == NULL) goto err; /* 2^(top*BN_BITS2) - m */ r->d[0] = (0 - m->d[0]) & BN_MASK2; for (i = 1; i < j; i++) r->d[i] = (~m->d[i]) & BN_MASK2; r->top = j; /* * Upper words will be zero if the corresponding words of 'm' were * 0xfff[...], so decrement r->top accordingly. */ bn_correct_top(r); } else #endif if (!BN_to_montgomery(r, BN_value_one(), mont, ctx)) goto err; for (;;) { if (BN_is_bit_set(p, wstart) == 0) { if (!start) { if (!BN_mod_mul_montgomery(r, r, r, mont, ctx)) goto err; } if (wstart == 0) break; wstart--; continue; } /* * We now have wstart on a 'set' bit, we now need to work out how bit * a window to do. To do this we need to scan forward until the last * set bit before the end of the window */ j = wstart; wvalue = 1; wend = 0; for (i = 1; i < window; i++) { if (wstart - i < 0) break; if (BN_is_bit_set(p, wstart - i)) { wvalue <<= (i - wend); wvalue |= 1; wend = i; } } /* wend is the size of the current window */ j = wend + 1; /* add the 'bytes above' */ if (!start) for (i = 0; i < j; i++) { if (!BN_mod_mul_montgomery(r, r, r, mont, ctx)) goto err; } /* wvalue will be an odd number < 2^window */ if (!BN_mod_mul_montgomery(r, r, val[wvalue >> 1], mont, ctx)) goto err; /* move the 'window' down further */ wstart -= wend + 1; wvalue = 0; start = 0; if (wstart < 0) break; } #if defined(SPARC_T4_MONT) if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) { j = mont->N.top; /* borrow j */ val[0]->d[0] = 1; /* borrow val[0] */ for (i = 1; i < j; i++) val[0]->d[i] = 0; val[0]->top = j; if (!BN_mod_mul_montgomery(rr, r, val[0], mont, ctx)) goto err; } else #endif if (!BN_from_montgomery(rr, r, mont, ctx)) goto err; ret = 1; err: if ((in_mont == NULL) && (mont != NULL)) BN_MONT_CTX_free(mont); BN_CTX_end(ctx); bn_check_top(rr); return (ret); } #if defined(SPARC_T4_MONT) static BN_ULONG bn_get_bits(const BIGNUM *a, int bitpos) { BN_ULONG ret = 0; int wordpos; wordpos = bitpos / BN_BITS2; bitpos %= BN_BITS2; if (wordpos >= 0 && wordpos < a->top) { ret = a->d[wordpos] & BN_MASK2; if (bitpos) { ret >>= bitpos; if (++wordpos < a->top) ret |= a->d[wordpos] << (BN_BITS2 - bitpos); } } return ret & BN_MASK2; } #endif /* * BN_mod_exp_mont_consttime() stores the precomputed powers in a specific * layout so that accessing any of these table values shows the same access * pattern as far as cache lines are concerned. The following functions are * used to transfer a BIGNUM from/to that table. */ static int MOD_EXP_CTIME_COPY_TO_PREBUF(const BIGNUM *b, int top, unsigned char *buf, int idx, int window) { int i, j; int width = 1 << window; BN_ULONG *table = (BN_ULONG *)buf; if (top > b->top) top = b->top; /* this works because 'buf' is explicitly * zeroed */ for (i = 0, j = idx; i < top; i++, j += width) { table[j] = b->d[i]; } return 1; } static int MOD_EXP_CTIME_COPY_FROM_PREBUF(BIGNUM *b, int top, unsigned char *buf, int idx, int window) { int i, j; int width = 1 << window; volatile BN_ULONG *table = (volatile BN_ULONG *)buf; if (bn_wexpand(b, top) == NULL) return 0; if (window <= 3) { for (i = 0; i < top; i++, table += width) { BN_ULONG acc = 0; for (j = 0; j < width; j++) { acc |= table[j] & ((BN_ULONG)0 - (constant_time_eq_int(j,idx)&1)); } b->d[i] = acc; } } else { int xstride = 1 << (window - 2); BN_ULONG y0, y1, y2, y3; i = idx >> (window - 2); /* equivalent of idx / xstride */ idx &= xstride - 1; /* equivalent of idx % xstride */ y0 = (BN_ULONG)0 - (constant_time_eq_int(i,0)&1); y1 = (BN_ULONG)0 - (constant_time_eq_int(i,1)&1); y2 = (BN_ULONG)0 - (constant_time_eq_int(i,2)&1); y3 = (BN_ULONG)0 - (constant_time_eq_int(i,3)&1); for (i = 0; i < top; i++, table += width) { BN_ULONG acc = 0; for (j = 0; j < xstride; j++) { acc |= ( (table[j + 0 * xstride] & y0) | (table[j + 1 * xstride] & y1) | (table[j + 2 * xstride] & y2) | (table[j + 3 * xstride] & y3) ) & ((BN_ULONG)0 - (constant_time_eq_int(j,idx)&1)); } b->d[i] = acc; } } b->top = top; bn_correct_top(b); return 1; } /* * Given a pointer value, compute the next address that is a cache line * multiple. */ #define MOD_EXP_CTIME_ALIGN(x_) \ ((unsigned char*)(x_) + (MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH - (((size_t)(x_)) & (MOD_EXP_CTIME_MIN_CACHE_LINE_MASK)))) /* * This variant of BN_mod_exp_mont() uses fixed windows and the special * precomputation memory layout to limit data-dependency to a minimum to * protect secret exponents (cf. the hyper-threading timing attacks pointed * out by Colin Percival, * http://www.daemonology.net/hyperthreading-considered-harmful/) */ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont) { int i, bits, ret = 0, window, wvalue; int top; BN_MONT_CTX *mont = NULL; int numPowers; unsigned char *powerbufFree = NULL; int powerbufLen = 0; unsigned char *powerbuf = NULL; BIGNUM tmp, am; #if defined(SPARC_T4_MONT) unsigned int t4 = 0; #endif bn_check_top(a); bn_check_top(p); bn_check_top(m); if (!BN_is_odd(m)) { BNerr(BN_F_BN_MOD_EXP_MONT_CONSTTIME, BN_R_CALLED_WITH_EVEN_MODULUS); return (0); } top = m->top; bits = BN_num_bits(p); if (bits == 0) { /* x**0 mod 1 is still zero. */ if (BN_is_one(m)) { ret = 1; BN_zero(rr); } else { ret = BN_one(rr); } return ret; } BN_CTX_start(ctx); /* * Allocate a montgomery context if it was not supplied by the caller. If * this is not done, things will break in the montgomery part. */ if (in_mont != NULL) mont = in_mont; else { if ((mont = BN_MONT_CTX_new()) == NULL) goto err; if (!BN_MONT_CTX_set(mont, m, ctx)) goto err; } #ifdef RSAZ_ENABLED /* * If the size of the operands allow it, perform the optimized * RSAZ exponentiation. For further information see * crypto/bn/rsaz_exp.c and accompanying assembly modules. */ if ((16 == a->top) && (16 == p->top) && (BN_num_bits(m) == 1024) && rsaz_avx2_eligible()) { if (NULL == bn_wexpand(rr, 16)) goto err; RSAZ_1024_mod_exp_avx2(rr->d, a->d, p->d, m->d, mont->RR.d, mont->n0[0]); rr->top = 16; rr->neg = 0; bn_correct_top(rr); ret = 1; goto err; } else if ((8 == a->top) && (8 == p->top) && (BN_num_bits(m) == 512)) { if (NULL == bn_wexpand(rr, 8)) goto err; RSAZ_512_mod_exp(rr->d, a->d, p->d, m->d, mont->n0[0], mont->RR.d); rr->top = 8; rr->neg = 0; bn_correct_top(rr); ret = 1; goto err; } #endif /* Get the window size to use with size of p. */ window = BN_window_bits_for_ctime_exponent_size(bits); #if defined(SPARC_T4_MONT) if (window >= 5 && (top & 15) == 0 && top <= 64 && (OPENSSL_sparcv9cap_P[1] & (CFR_MONTMUL | CFR_MONTSQR)) == (CFR_MONTMUL | CFR_MONTSQR) && (t4 = OPENSSL_sparcv9cap_P[0])) window = 5; else #endif #if defined(OPENSSL_BN_ASM_MONT5) if (window >= 5) { window = 5; /* ~5% improvement for RSA2048 sign, and even * for RSA4096 */ /* reserve space for mont->N.d[] copy */ powerbufLen += top * sizeof(mont->N.d[0]); } #endif (void)0; /* * Allocate a buffer large enough to hold all of the pre-computed powers * of am, am itself and tmp. */ numPowers = 1 << window; powerbufLen += sizeof(m->d[0]) * (top * numPowers + ((2 * top) > numPowers ? (2 * top) : numPowers)); #ifdef alloca if (powerbufLen < 3072) powerbufFree = alloca(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH); else #endif if ((powerbufFree = (unsigned char *)OPENSSL_malloc(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH)) == NULL) goto err; powerbuf = MOD_EXP_CTIME_ALIGN(powerbufFree); memset(powerbuf, 0, powerbufLen); #ifdef alloca if (powerbufLen < 3072) powerbufFree = NULL; #endif /* lay down tmp and am right after powers table */ tmp.d = (BN_ULONG *)(powerbuf + sizeof(m->d[0]) * top * numPowers); am.d = tmp.d + top; tmp.top = am.top = 0; tmp.dmax = am.dmax = top; tmp.neg = am.neg = 0; tmp.flags = am.flags = BN_FLG_STATIC_DATA; /* prepare a^0 in Montgomery domain */ #if 1 /* by Shay Gueron's suggestion */ if (m->d[top - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) { /* 2^(top*BN_BITS2) - m */ tmp.d[0] = (0 - m->d[0]) & BN_MASK2; for (i = 1; i < top; i++) tmp.d[i] = (~m->d[i]) & BN_MASK2; tmp.top = top; } else #endif if (!BN_to_montgomery(&tmp, BN_value_one(), mont, ctx)) goto err; /* prepare a^1 in Montgomery domain */ if (a->neg || BN_ucmp(a, m) >= 0) { if (!BN_mod(&am, a, m, ctx)) goto err; if (!BN_to_montgomery(&am, &am, mont, ctx)) goto err; } else if (!BN_to_montgomery(&am, a, mont, ctx)) goto err; #if defined(SPARC_T4_MONT) if (t4) { typedef int (*bn_pwr5_mont_f) (BN_ULONG *tp, const BN_ULONG *np, const BN_ULONG *n0, const void *table, int power, int bits); int bn_pwr5_mont_t4_8(BN_ULONG *tp, const BN_ULONG *np, const BN_ULONG *n0, const void *table, int power, int bits); int bn_pwr5_mont_t4_16(BN_ULONG *tp, const BN_ULONG *np, const BN_ULONG *n0, const void *table, int power, int bits); int bn_pwr5_mont_t4_24(BN_ULONG *tp, const BN_ULONG *np, const BN_ULONG *n0, const void *table, int power, int bits); int bn_pwr5_mont_t4_32(BN_ULONG *tp, const BN_ULONG *np, const BN_ULONG *n0, const void *table, int power, int bits); static const bn_pwr5_mont_f pwr5_funcs[4] = { bn_pwr5_mont_t4_8, bn_pwr5_mont_t4_16, bn_pwr5_mont_t4_24, bn_pwr5_mont_t4_32 }; bn_pwr5_mont_f pwr5_worker = pwr5_funcs[top / 16 - 1]; typedef int (*bn_mul_mont_f) (BN_ULONG *rp, const BN_ULONG *ap, const void *bp, const BN_ULONG *np, const BN_ULONG *n0); int bn_mul_mont_t4_8(BN_ULONG *rp, const BN_ULONG *ap, const void *bp, const BN_ULONG *np, const BN_ULONG *n0); int bn_mul_mont_t4_16(BN_ULONG *rp, const BN_ULONG *ap, const void *bp, const BN_ULONG *np, const BN_ULONG *n0); int bn_mul_mont_t4_24(BN_ULONG *rp, const BN_ULONG *ap, const void *bp, const BN_ULONG *np, const BN_ULONG *n0); int bn_mul_mont_t4_32(BN_ULONG *rp, const BN_ULONG *ap, const void *bp, const BN_ULONG *np, const BN_ULONG *n0); static const bn_mul_mont_f mul_funcs[4] = { bn_mul_mont_t4_8, bn_mul_mont_t4_16, bn_mul_mont_t4_24, bn_mul_mont_t4_32 }; bn_mul_mont_f mul_worker = mul_funcs[top / 16 - 1]; void bn_mul_mont_vis3(BN_ULONG *rp, const BN_ULONG *ap, const void *bp, const BN_ULONG *np, const BN_ULONG *n0, int num); void bn_mul_mont_t4(BN_ULONG *rp, const BN_ULONG *ap, const void *bp, const BN_ULONG *np, const BN_ULONG *n0, int num); void bn_mul_mont_gather5_t4(BN_ULONG *rp, const BN_ULONG *ap, const void *table, const BN_ULONG *np, const BN_ULONG *n0, int num, int power); void bn_flip_n_scatter5_t4(const BN_ULONG *inp, size_t num, void *table, size_t power); void bn_gather5_t4(BN_ULONG *out, size_t num, void *table, size_t power); void bn_flip_t4(BN_ULONG *dst, BN_ULONG *src, size_t num); BN_ULONG *np = mont->N.d, *n0 = mont->n0; int stride = 5 * (6 - (top / 16 - 1)); /* multiple of 5, but less * than 32 */ /* * BN_to_montgomery can contaminate words above .top [in * BN_DEBUG[_DEBUG] build]... */ for (i = am.top; i < top; i++) am.d[i] = 0; for (i = tmp.top; i < top; i++) tmp.d[i] = 0; bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 0); bn_flip_n_scatter5_t4(am.d, top, powerbuf, 1); if (!(*mul_worker) (tmp.d, am.d, am.d, np, n0) && !(*mul_worker) (tmp.d, am.d, am.d, np, n0)) bn_mul_mont_vis3(tmp.d, am.d, am.d, np, n0, top); bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 2); for (i = 3; i < 32; i++) { /* Calculate a^i = a^(i-1) * a */ if (!(*mul_worker) (tmp.d, tmp.d, am.d, np, n0) && !(*mul_worker) (tmp.d, tmp.d, am.d, np, n0)) bn_mul_mont_vis3(tmp.d, tmp.d, am.d, np, n0, top); bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, i); } /* switch to 64-bit domain */ np = alloca(top * sizeof(BN_ULONG)); top /= 2; bn_flip_t4(np, mont->N.d, top); bits--; for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--) wvalue = (wvalue << 1) + BN_is_bit_set(p, bits); bn_gather5_t4(tmp.d, top, powerbuf, wvalue); /* * Scan the exponent one window at a time starting from the most * significant bits. */ while (bits >= 0) { if (bits < stride) stride = bits + 1; bits -= stride; wvalue = bn_get_bits(p, bits + 1); if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride)) continue; /* retry once and fall back */ if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride)) continue; bits += stride - 5; wvalue >>= stride - 5; wvalue &= 31; bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont_gather5_t4(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue); } bn_flip_t4(tmp.d, tmp.d, top); top *= 2; /* back to 32-bit domain */ tmp.top = top; bn_correct_top(&tmp); OPENSSL_cleanse(np, top * sizeof(BN_ULONG)); } else #endif #if defined(OPENSSL_BN_ASM_MONT5) if (window == 5 && top > 1) { /* * This optimization uses ideas from http://eprint.iacr.org/2011/239, * specifically optimization of cache-timing attack countermeasures * and pre-computation optimization. */ /* * Dedicated window==4 case improves 512-bit RSA sign by ~15%, but as * 512-bit RSA is hardly relevant, we omit it to spare size... */ void bn_mul_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap, const void *table, const BN_ULONG *np, const BN_ULONG *n0, int num, int power); void bn_scatter5(const BN_ULONG *inp, size_t num, void *table, size_t power); void bn_gather5(BN_ULONG *out, size_t num, void *table, size_t power); void bn_power5(BN_ULONG *rp, const BN_ULONG *ap, const void *table, const BN_ULONG *np, const BN_ULONG *n0, int num, int power); int bn_get_bits5(const BN_ULONG *ap, int off); int bn_from_montgomery(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *not_used, const BN_ULONG *np, const BN_ULONG *n0, int num); BN_ULONG *n0 = mont->n0, *np; /* * BN_to_montgomery can contaminate words above .top [in * BN_DEBUG[_DEBUG] build]... */ for (i = am.top; i < top; i++) am.d[i] = 0; for (i = tmp.top; i < top; i++) tmp.d[i] = 0; /* * copy mont->N.d[] to improve cache locality */ for (np = am.d + top, i = 0; i < top; i++) np[i] = mont->N.d[i]; bn_scatter5(tmp.d, top, powerbuf, 0); bn_scatter5(am.d, am.top, powerbuf, 1); bn_mul_mont(tmp.d, am.d, am.d, np, n0, top); bn_scatter5(tmp.d, top, powerbuf, 2); # if 0 for (i = 3; i < 32; i++) { /* Calculate a^i = a^(i-1) * a */ bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1); bn_scatter5(tmp.d, top, powerbuf, i); } # else /* same as above, but uses squaring for 1/2 of operations */ for (i = 4; i < 32; i *= 2) { bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_scatter5(tmp.d, top, powerbuf, i); } for (i = 3; i < 8; i += 2) { int j; bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1); bn_scatter5(tmp.d, top, powerbuf, i); for (j = 2 * i; j < 32; j *= 2) { bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_scatter5(tmp.d, top, powerbuf, j); } } for (; i < 16; i += 2) { bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1); bn_scatter5(tmp.d, top, powerbuf, i); bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_scatter5(tmp.d, top, powerbuf, 2 * i); } for (; i < 32; i += 2) { bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1); bn_scatter5(tmp.d, top, powerbuf, i); } # endif bits--; for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--) wvalue = (wvalue << 1) + BN_is_bit_set(p, bits); bn_gather5(tmp.d, top, powerbuf, wvalue); /* * Scan the exponent one window at a time starting from the most * significant bits. */ if (top & 7) while (bits >= 0) { for (wvalue = 0, i = 0; i < 5; i++, bits--) wvalue = (wvalue << 1) + BN_is_bit_set(p, bits); bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); bn_mul_mont_gather5(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue); } else { while (bits >= 0) { wvalue = bn_get_bits5(p->d, bits - 4); bits -= 5; bn_power5(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue); } } ret = bn_from_montgomery(tmp.d, tmp.d, NULL, np, n0, top); tmp.top = top; bn_correct_top(&tmp); if (ret) { if (!BN_copy(rr, &tmp)) ret = 0; goto err; /* non-zero ret means it's not error */ } } else #endif { if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 0, window)) goto err; if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&am, top, powerbuf, 1, window)) goto err; /* * If the window size is greater than 1, then calculate * val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1) (even * powers could instead be computed as (a^(i/2))^2 to use the slight * performance advantage of sqr over mul). */ if (window > 1) { if (!BN_mod_mul_montgomery(&tmp, &am, &am, mont, ctx)) goto err; if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 2, window)) goto err; for (i = 3; i < numPowers; i++) { /* Calculate a^i = a^(i-1) * a */ if (!BN_mod_mul_montgomery(&tmp, &am, &tmp, mont, ctx)) goto err; if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, i, window)) goto err; } } bits--; for (wvalue = 0, i = bits % window; i >= 0; i--, bits--) wvalue = (wvalue << 1) + BN_is_bit_set(p, bits); if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&tmp, top, powerbuf, wvalue, window)) goto err; /* * Scan the exponent one window at a time starting from the most * significant bits. */ while (bits >= 0) { wvalue = 0; /* The 'value' of the window */ /* Scan the window, squaring the result as we go */ for (i = 0; i < window; i++, bits--) { if (!BN_mod_mul_montgomery(&tmp, &tmp, &tmp, mont, ctx)) goto err; wvalue = (wvalue << 1) + BN_is_bit_set(p, bits); } /* * Fetch the appropriate pre-computed value from the pre-buf */ if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&am, top, powerbuf, wvalue, window)) goto err; /* Multiply the result into the intermediate result */ if (!BN_mod_mul_montgomery(&tmp, &tmp, &am, mont, ctx)) goto err; } } /* Convert the final result from montgomery to standard format */ #if defined(SPARC_T4_MONT) if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) { am.d[0] = 1; /* borrow am */ for (i = 1; i < top; i++) am.d[i] = 0; if (!BN_mod_mul_montgomery(rr, &tmp, &am, mont, ctx)) goto err; } else #endif if (!BN_from_montgomery(rr, &tmp, mont, ctx)) goto err; ret = 1; err: if ((in_mont == NULL) && (mont != NULL)) BN_MONT_CTX_free(mont); if (powerbuf != NULL) { OPENSSL_cleanse(powerbuf, powerbufLen); if (powerbufFree) OPENSSL_free(powerbufFree); } BN_CTX_end(ctx); return (ret); } int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont) { BN_MONT_CTX *mont = NULL; int b, bits, ret = 0; int r_is_one; BN_ULONG w, next_w; BIGNUM *d, *r, *t; BIGNUM *swap_tmp; #define BN_MOD_MUL_WORD(r, w, m) \ (BN_mul_word(r, (w)) && \ (/* BN_ucmp(r, (m)) < 0 ? 1 :*/ \ (BN_mod(t, r, m, ctx) && (swap_tmp = r, r = t, t = swap_tmp, 1)))) /* * BN_MOD_MUL_WORD is only used with 'w' large, so the BN_ucmp test is * probably more overhead than always using BN_mod (which uses BN_copy if * a similar test returns true). */ /* * We can use BN_mod and do not need BN_nnmod because our accumulator is * never negative (the result of BN_mod does not depend on the sign of * the modulus). */ #define BN_TO_MONTGOMERY_WORD(r, w, mont) \ (BN_set_word(r, (w)) && BN_to_montgomery(r, r, (mont), ctx)) - if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) { + if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0 + || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) { /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */ BNerr(BN_F_BN_MOD_EXP_MONT_WORD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return -1; } bn_check_top(p); bn_check_top(m); if (!BN_is_odd(m)) { BNerr(BN_F_BN_MOD_EXP_MONT_WORD, BN_R_CALLED_WITH_EVEN_MODULUS); return (0); } if (m->top == 1) a %= m->d[0]; /* make sure that 'a' is reduced */ bits = BN_num_bits(p); if (bits == 0) { /* x**0 mod 1 is still zero. */ if (BN_is_one(m)) { ret = 1; BN_zero(rr); } else { ret = BN_one(rr); } return ret; } if (a == 0) { BN_zero(rr); ret = 1; return ret; } BN_CTX_start(ctx); d = BN_CTX_get(ctx); r = BN_CTX_get(ctx); t = BN_CTX_get(ctx); if (d == NULL || r == NULL || t == NULL) goto err; if (in_mont != NULL) mont = in_mont; else { if ((mont = BN_MONT_CTX_new()) == NULL) goto err; if (!BN_MONT_CTX_set(mont, m, ctx)) goto err; } r_is_one = 1; /* except for Montgomery factor */ /* bits-1 >= 0 */ /* The result is accumulated in the product r*w. */ w = a; /* bit 'bits-1' of 'p' is always set */ for (b = bits - 2; b >= 0; b--) { /* First, square r*w. */ next_w = w * w; if ((next_w / w) != w) { /* overflow */ if (r_is_one) { if (!BN_TO_MONTGOMERY_WORD(r, w, mont)) goto err; r_is_one = 0; } else { if (!BN_MOD_MUL_WORD(r, w, m)) goto err; } next_w = 1; } w = next_w; if (!r_is_one) { if (!BN_mod_mul_montgomery(r, r, r, mont, ctx)) goto err; } /* Second, multiply r*w by 'a' if exponent bit is set. */ if (BN_is_bit_set(p, b)) { next_w = w * a; if ((next_w / a) != w) { /* overflow */ if (r_is_one) { if (!BN_TO_MONTGOMERY_WORD(r, w, mont)) goto err; r_is_one = 0; } else { if (!BN_MOD_MUL_WORD(r, w, m)) goto err; } next_w = a; } w = next_w; } } /* Finally, set r:=r*w. */ if (w != 1) { if (r_is_one) { if (!BN_TO_MONTGOMERY_WORD(r, w, mont)) goto err; r_is_one = 0; } else { if (!BN_MOD_MUL_WORD(r, w, m)) goto err; } } if (r_is_one) { /* can happen only if a == 1 */ if (!BN_one(rr)) goto err; } else { if (!BN_from_montgomery(rr, r, mont, ctx)) goto err; } ret = 1; err: if ((in_mont == NULL) && (mont != NULL)) BN_MONT_CTX_free(mont); BN_CTX_end(ctx); bn_check_top(rr); return (ret); } /* The old fallback, simple version :-) */ int BN_mod_exp_simple(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx) { int i, j, bits, ret = 0, wstart, wend, window, wvalue; int start = 1; BIGNUM *d; /* Table of variables obtained from 'ctx' */ BIGNUM *val[TABLE_SIZE]; - if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) { + if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0 + || BN_get_flags(a, BN_FLG_CONSTTIME) != 0 + || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) { /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */ BNerr(BN_F_BN_MOD_EXP_SIMPLE, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return -1; } bits = BN_num_bits(p); if (bits == 0) { /* x**0 mod 1 is still zero. */ if (BN_is_one(m)) { ret = 1; BN_zero(r); } else { ret = BN_one(r); } return ret; } BN_CTX_start(ctx); d = BN_CTX_get(ctx); val[0] = BN_CTX_get(ctx); if (!d || !val[0]) goto err; if (!BN_nnmod(val[0], a, m, ctx)) goto err; /* 1 */ if (BN_is_zero(val[0])) { BN_zero(r); ret = 1; goto err; } window = BN_window_bits_for_exponent_size(bits); if (window > 1) { if (!BN_mod_mul(d, val[0], val[0], m, ctx)) goto err; /* 2 */ j = 1 << (window - 1); for (i = 1; i < j; i++) { if (((val[i] = BN_CTX_get(ctx)) == NULL) || !BN_mod_mul(val[i], val[i - 1], d, m, ctx)) goto err; } } start = 1; /* This is used to avoid multiplication etc * when there is only the value '1' in the * buffer. */ wvalue = 0; /* The 'value' of the window */ wstart = bits - 1; /* The top bit of the window */ wend = 0; /* The bottom bit of the window */ if (!BN_one(r)) goto err; for (;;) { if (BN_is_bit_set(p, wstart) == 0) { if (!start) if (!BN_mod_mul(r, r, r, m, ctx)) goto err; if (wstart == 0) break; wstart--; continue; } /* * We now have wstart on a 'set' bit, we now need to work out how bit * a window to do. To do this we need to scan forward until the last * set bit before the end of the window */ j = wstart; wvalue = 1; wend = 0; for (i = 1; i < window; i++) { if (wstart - i < 0) break; if (BN_is_bit_set(p, wstart - i)) { wvalue <<= (i - wend); wvalue |= 1; wend = i; } } /* wend is the size of the current window */ j = wend + 1; /* add the 'bytes above' */ if (!start) for (i = 0; i < j; i++) { if (!BN_mod_mul(r, r, r, m, ctx)) goto err; } /* wvalue will be an odd number < 2^window */ if (!BN_mod_mul(r, r, val[wvalue >> 1], m, ctx)) goto err; /* move the 'window' down further */ wstart -= wend + 1; wvalue = 0; start = 0; if (wstart < 0) break; } ret = 1; err: BN_CTX_end(ctx); bn_check_top(r); return (ret); } Index: vendor-crypto/openssl/dist/crypto/bn/bn_lib.c =================================================================== --- vendor-crypto/openssl/dist/crypto/bn/bn_lib.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/bn/bn_lib.c (revision 325326) @@ -1,916 +1,919 @@ /* crypto/bn/bn_lib.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.] */ #ifndef BN_DEBUG # undef NDEBUG /* avoid conflicting definitions */ # define NDEBUG #endif #include #include #include #include "cryptlib.h" #include "bn_lcl.h" const char BN_version[] = "Big Number" OPENSSL_VERSION_PTEXT; /* This stuff appears to be completely unused, so is deprecated */ #ifndef OPENSSL_NO_DEPRECATED /*- * For a 32 bit machine * 2 - 4 == 128 * 3 - 8 == 256 * 4 - 16 == 512 * 5 - 32 == 1024 * 6 - 64 == 2048 * 7 - 128 == 4096 * 8 - 256 == 8192 */ static int bn_limit_bits = 0; static int bn_limit_num = 8; /* (1<= 0) { if (mult > (int)(sizeof(int) * 8) - 1) mult = sizeof(int) * 8 - 1; bn_limit_bits = mult; bn_limit_num = 1 << mult; } if (high >= 0) { if (high > (int)(sizeof(int) * 8) - 1) high = sizeof(int) * 8 - 1; bn_limit_bits_high = high; bn_limit_num_high = 1 << high; } if (low >= 0) { if (low > (int)(sizeof(int) * 8) - 1) low = sizeof(int) * 8 - 1; bn_limit_bits_low = low; bn_limit_num_low = 1 << low; } if (mont >= 0) { if (mont > (int)(sizeof(int) * 8) - 1) mont = sizeof(int) * 8 - 1; bn_limit_bits_mont = mont; bn_limit_num_mont = 1 << mont; } } int BN_get_params(int which) { if (which == 0) return (bn_limit_bits); else if (which == 1) return (bn_limit_bits_high); else if (which == 2) return (bn_limit_bits_low); else if (which == 3) return (bn_limit_bits_mont); else return (0); } #endif const BIGNUM *BN_value_one(void) { static const BN_ULONG data_one = 1L; static const BIGNUM const_one = { (BN_ULONG *)&data_one, 1, 1, 0, BN_FLG_STATIC_DATA }; return (&const_one); } int BN_num_bits_word(BN_ULONG l) { static const unsigned char bits[256] = { 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, }; #if defined(SIXTY_FOUR_BIT_LONG) if (l & 0xffffffff00000000L) { if (l & 0xffff000000000000L) { if (l & 0xff00000000000000L) { return (bits[(int)(l >> 56)] + 56); } else return (bits[(int)(l >> 48)] + 48); } else { if (l & 0x0000ff0000000000L) { return (bits[(int)(l >> 40)] + 40); } else return (bits[(int)(l >> 32)] + 32); } } else #else # ifdef SIXTY_FOUR_BIT if (l & 0xffffffff00000000LL) { if (l & 0xffff000000000000LL) { if (l & 0xff00000000000000LL) { return (bits[(int)(l >> 56)] + 56); } else return (bits[(int)(l >> 48)] + 48); } else { if (l & 0x0000ff0000000000LL) { return (bits[(int)(l >> 40)] + 40); } else return (bits[(int)(l >> 32)] + 32); } } else # endif #endif { #if defined(THIRTY_TWO_BIT) || defined(SIXTY_FOUR_BIT) || defined(SIXTY_FOUR_BIT_LONG) if (l & 0xffff0000L) { if (l & 0xff000000L) return (bits[(int)(l >> 24L)] + 24); else return (bits[(int)(l >> 16L)] + 16); } else #endif { #if defined(THIRTY_TWO_BIT) || defined(SIXTY_FOUR_BIT) || defined(SIXTY_FOUR_BIT_LONG) if (l & 0xff00L) return (bits[(int)(l >> 8)] + 8); else #endif return (bits[(int)(l)]); } } } int BN_num_bits(const BIGNUM *a) { int i = a->top - 1; bn_check_top(a); if (BN_is_zero(a)) return 0; return ((i * BN_BITS2) + BN_num_bits_word(a->d[i])); } void BN_clear_free(BIGNUM *a) { int i; if (a == NULL) return; bn_check_top(a); if (a->d != NULL) { OPENSSL_cleanse(a->d, a->dmax * sizeof(a->d[0])); if (!(BN_get_flags(a, BN_FLG_STATIC_DATA))) OPENSSL_free(a->d); } i = BN_get_flags(a, BN_FLG_MALLOCED); OPENSSL_cleanse(a, sizeof(BIGNUM)); if (i) OPENSSL_free(a); } void BN_free(BIGNUM *a) { if (a == NULL) return; bn_check_top(a); if ((a->d != NULL) && !(BN_get_flags(a, BN_FLG_STATIC_DATA))) OPENSSL_free(a->d); if (a->flags & BN_FLG_MALLOCED) OPENSSL_free(a); else { #ifndef OPENSSL_NO_DEPRECATED a->flags |= BN_FLG_FREE; #endif a->d = NULL; } } void BN_init(BIGNUM *a) { memset(a, 0, sizeof(BIGNUM)); bn_check_top(a); } BIGNUM *BN_new(void) { BIGNUM *ret; if ((ret = (BIGNUM *)OPENSSL_malloc(sizeof(BIGNUM))) == NULL) { BNerr(BN_F_BN_NEW, ERR_R_MALLOC_FAILURE); return (NULL); } ret->flags = BN_FLG_MALLOCED; ret->top = 0; ret->neg = 0; ret->dmax = 0; ret->d = NULL; bn_check_top(ret); return (ret); } /* This is used both by bn_expand2() and bn_dup_expand() */ /* The caller MUST check that words > b->dmax before calling this */ static BN_ULONG *bn_expand_internal(const BIGNUM *b, int words) { BN_ULONG *A, *a = NULL; const BN_ULONG *B; int i; bn_check_top(b); if (words > (INT_MAX / (4 * BN_BITS2))) { BNerr(BN_F_BN_EXPAND_INTERNAL, BN_R_BIGNUM_TOO_LONG); return NULL; } if (BN_get_flags(b, BN_FLG_STATIC_DATA)) { BNerr(BN_F_BN_EXPAND_INTERNAL, BN_R_EXPAND_ON_STATIC_BIGNUM_DATA); return (NULL); } a = A = (BN_ULONG *)OPENSSL_malloc(sizeof(BN_ULONG) * words); if (A == NULL) { BNerr(BN_F_BN_EXPAND_INTERNAL, ERR_R_MALLOC_FAILURE); return (NULL); } #ifdef PURIFY /* * Valgrind complains in BN_consttime_swap because we process the whole * array even if it's not initialised yet. This doesn't matter in that * function - what's important is constant time operation (we're not * actually going to use the data) */ memset(a, 0, sizeof(BN_ULONG) * words); #endif #if 1 B = b->d; /* Check if the previous number needs to be copied */ if (B != NULL) { for (i = b->top >> 2; i > 0; i--, A += 4, B += 4) { /* * The fact that the loop is unrolled * 4-wise is a tribute to Intel. It's * the one that doesn't have enough * registers to accomodate more data. * I'd unroll it 8-wise otherwise:-) * * */ BN_ULONG a0, a1, a2, a3; a0 = B[0]; a1 = B[1]; a2 = B[2]; a3 = B[3]; A[0] = a0; A[1] = a1; A[2] = a2; A[3] = a3; } /* * workaround for ultrix cc: without 'case 0', the optimizer does * the switch table by doing a=top&3; a--; goto jump_table[a]; * which fails for top== 0 */ switch (b->top & 3) { case 3: A[2] = B[2]; case 2: A[1] = B[1]; case 1: A[0] = B[0]; case 0: ; } } #else memset(A, 0, sizeof(BN_ULONG) * words); memcpy(A, b->d, sizeof(b->d[0]) * b->top); #endif return (a); } /* * This is an internal function that can be used instead of bn_expand2() when * there is a need to copy BIGNUMs instead of only expanding the data part, * while still expanding them. Especially useful when needing to expand * BIGNUMs that are declared 'const' and should therefore not be changed. The * reason to use this instead of a BN_dup() followed by a bn_expand2() is * memory allocation overhead. A BN_dup() followed by a bn_expand2() will * allocate new memory for the BIGNUM data twice, and free it once, while * bn_dup_expand() makes sure allocation is made only once. */ #ifndef OPENSSL_NO_DEPRECATED BIGNUM *bn_dup_expand(const BIGNUM *b, int words) { BIGNUM *r = NULL; bn_check_top(b); /* * This function does not work if words <= b->dmax && top < words because * BN_dup() does not preserve 'dmax'! (But bn_dup_expand() is not used * anywhere yet.) */ if (words > b->dmax) { BN_ULONG *a = bn_expand_internal(b, words); if (a) { r = BN_new(); if (r) { r->top = b->top; r->dmax = words; r->neg = b->neg; r->d = a; } else { /* r == NULL, BN_new failure */ OPENSSL_free(a); } } /* * If a == NULL, there was an error in allocation in * bn_expand_internal(), and NULL should be returned */ } else { r = BN_dup(b); } bn_check_top(r); return r; } #endif /* * This is an internal function that should not be used in applications. It * ensures that 'b' has enough room for a 'words' word number and initialises * any unused part of b->d with leading zeros. It is mostly used by the * various BIGNUM routines. If there is an error, NULL is returned. If not, * 'b' is returned. */ BIGNUM *bn_expand2(BIGNUM *b, int words) { bn_check_top(b); if (words > b->dmax) { BN_ULONG *a = bn_expand_internal(b, words); if (!a) return NULL; if (b->d) OPENSSL_free(b->d); b->d = a; b->dmax = words; } /* None of this should be necessary because of what b->top means! */ #if 0 /* * NB: bn_wexpand() calls this only if the BIGNUM really has to grow */ if (b->top < b->dmax) { int i; BN_ULONG *A = &(b->d[b->top]); for (i = (b->dmax - b->top) >> 3; i > 0; i--, A += 8) { A[0] = 0; A[1] = 0; A[2] = 0; A[3] = 0; A[4] = 0; A[5] = 0; A[6] = 0; A[7] = 0; } for (i = (b->dmax - b->top) & 7; i > 0; i--, A++) A[0] = 0; assert(A == &(b->d[b->dmax])); } #endif bn_check_top(b); return b; } BIGNUM *BN_dup(const BIGNUM *a) { BIGNUM *t; if (a == NULL) return NULL; bn_check_top(a); t = BN_new(); if (t == NULL) return NULL; if (!BN_copy(t, a)) { BN_free(t); return NULL; } bn_check_top(t); return t; } BIGNUM *BN_copy(BIGNUM *a, const BIGNUM *b) { int i; BN_ULONG *A; const BN_ULONG *B; bn_check_top(b); if (a == b) return (a); if (bn_wexpand(a, b->top) == NULL) return (NULL); #if 1 A = a->d; B = b->d; for (i = b->top >> 2; i > 0; i--, A += 4, B += 4) { BN_ULONG a0, a1, a2, a3; a0 = B[0]; a1 = B[1]; a2 = B[2]; a3 = B[3]; A[0] = a0; A[1] = a1; A[2] = a2; A[3] = a3; } /* ultrix cc workaround, see comments in bn_expand_internal */ switch (b->top & 3) { case 3: A[2] = B[2]; case 2: A[1] = B[1]; case 1: A[0] = B[0]; case 0:; } #else memcpy(a->d, b->d, sizeof(b->d[0]) * b->top); #endif + if (BN_get_flags(b, BN_FLG_CONSTTIME) != 0) + BN_set_flags(a, BN_FLG_CONSTTIME); + a->top = b->top; a->neg = b->neg; bn_check_top(a); return (a); } void BN_swap(BIGNUM *a, BIGNUM *b) { int flags_old_a, flags_old_b; BN_ULONG *tmp_d; int tmp_top, tmp_dmax, tmp_neg; bn_check_top(a); bn_check_top(b); flags_old_a = a->flags; flags_old_b = b->flags; tmp_d = a->d; tmp_top = a->top; tmp_dmax = a->dmax; tmp_neg = a->neg; a->d = b->d; a->top = b->top; a->dmax = b->dmax; a->neg = b->neg; b->d = tmp_d; b->top = tmp_top; b->dmax = tmp_dmax; b->neg = tmp_neg; a->flags = (flags_old_a & BN_FLG_MALLOCED) | (flags_old_b & BN_FLG_STATIC_DATA); b->flags = (flags_old_b & BN_FLG_MALLOCED) | (flags_old_a & BN_FLG_STATIC_DATA); bn_check_top(a); bn_check_top(b); } void BN_clear(BIGNUM *a) { bn_check_top(a); if (a->d != NULL) OPENSSL_cleanse(a->d, a->dmax * sizeof(a->d[0])); a->top = 0; a->neg = 0; } BN_ULONG BN_get_word(const BIGNUM *a) { if (a->top > 1) return BN_MASK2; else if (a->top == 1) return a->d[0]; /* a->top == 0 */ return 0; } int BN_set_word(BIGNUM *a, BN_ULONG w) { bn_check_top(a); if (bn_expand(a, (int)sizeof(BN_ULONG) * 8) == NULL) return (0); a->neg = 0; a->d[0] = w; a->top = (w ? 1 : 0); bn_check_top(a); return (1); } BIGNUM *BN_bin2bn(const unsigned char *s, int len, BIGNUM *ret) { unsigned int i, m; unsigned int n; BN_ULONG l; BIGNUM *bn = NULL; if (ret == NULL) ret = bn = BN_new(); if (ret == NULL) return (NULL); bn_check_top(ret); l = 0; n = len; if (n == 0) { ret->top = 0; return (ret); } i = ((n - 1) / BN_BYTES) + 1; m = ((n - 1) % (BN_BYTES)); if (bn_wexpand(ret, (int)i) == NULL) { if (bn) BN_free(bn); return NULL; } ret->top = i; ret->neg = 0; while (n--) { l = (l << 8L) | *(s++); if (m-- == 0) { ret->d[--i] = l; l = 0; m = BN_BYTES - 1; } } /* * need to call this due to clear byte at top if avoiding having the top * bit set (-ve number) */ bn_correct_top(ret); return (ret); } /* ignore negative */ int BN_bn2bin(const BIGNUM *a, unsigned char *to) { int n, i; BN_ULONG l; bn_check_top(a); n = i = BN_num_bytes(a); while (i--) { l = a->d[i / BN_BYTES]; *(to++) = (unsigned char)(l >> (8 * (i % BN_BYTES))) & 0xff; } return (n); } int BN_ucmp(const BIGNUM *a, const BIGNUM *b) { int i; BN_ULONG t1, t2, *ap, *bp; bn_check_top(a); bn_check_top(b); i = a->top - b->top; if (i != 0) return (i); ap = a->d; bp = b->d; for (i = a->top - 1; i >= 0; i--) { t1 = ap[i]; t2 = bp[i]; if (t1 != t2) return ((t1 > t2) ? 1 : -1); } return (0); } int BN_cmp(const BIGNUM *a, const BIGNUM *b) { int i; int gt, lt; BN_ULONG t1, t2; if ((a == NULL) || (b == NULL)) { if (a != NULL) return (-1); else if (b != NULL) return (1); else return (0); } bn_check_top(a); bn_check_top(b); if (a->neg != b->neg) { if (a->neg) return (-1); else return (1); } if (a->neg == 0) { gt = 1; lt = -1; } else { gt = -1; lt = 1; } if (a->top > b->top) return (gt); if (a->top < b->top) return (lt); for (i = a->top - 1; i >= 0; i--) { t1 = a->d[i]; t2 = b->d[i]; if (t1 > t2) return (gt); if (t1 < t2) return (lt); } return (0); } int BN_set_bit(BIGNUM *a, int n) { int i, j, k; if (n < 0) return 0; i = n / BN_BITS2; j = n % BN_BITS2; if (a->top <= i) { if (bn_wexpand(a, i + 1) == NULL) return (0); for (k = a->top; k < i + 1; k++) a->d[k] = 0; a->top = i + 1; } a->d[i] |= (((BN_ULONG)1) << j); bn_check_top(a); return (1); } int BN_clear_bit(BIGNUM *a, int n) { int i, j; bn_check_top(a); if (n < 0) return 0; i = n / BN_BITS2; j = n % BN_BITS2; if (a->top <= i) return (0); a->d[i] &= (~(((BN_ULONG)1) << j)); bn_correct_top(a); return (1); } int BN_is_bit_set(const BIGNUM *a, int n) { int i, j; bn_check_top(a); if (n < 0) return 0; i = n / BN_BITS2; j = n % BN_BITS2; if (a->top <= i) return 0; return (int)(((a->d[i]) >> j) & ((BN_ULONG)1)); } int BN_mask_bits(BIGNUM *a, int n) { int b, w; bn_check_top(a); if (n < 0) return 0; w = n / BN_BITS2; b = n % BN_BITS2; if (w >= a->top) return 0; if (b == 0) a->top = w; else { a->top = w + 1; a->d[w] &= ~(BN_MASK2 << b); } bn_correct_top(a); return (1); } void BN_set_negative(BIGNUM *a, int b) { if (b && !BN_is_zero(a)) a->neg = 1; else a->neg = 0; } int bn_cmp_words(const BN_ULONG *a, const BN_ULONG *b, int n) { int i; BN_ULONG aa, bb; aa = a[n - 1]; bb = b[n - 1]; if (aa != bb) return ((aa > bb) ? 1 : -1); for (i = n - 2; i >= 0; i--) { aa = a[i]; bb = b[i]; if (aa != bb) return ((aa > bb) ? 1 : -1); } return (0); } /* * Here follows a specialised variants of bn_cmp_words(). It has the * property of performing the operation on arrays of different sizes. The * sizes of those arrays is expressed through cl, which is the common length * ( basicall, min(len(a),len(b)) ), and dl, which is the delta between the * two lengths, calculated as len(a)-len(b). All lengths are the number of * BN_ULONGs... */ int bn_cmp_part_words(const BN_ULONG *a, const BN_ULONG *b, int cl, int dl) { int n, i; n = cl - 1; if (dl < 0) { for (i = dl; i < 0; i++) { if (b[n - i] != 0) return -1; /* a < b */ } } if (dl > 0) { for (i = dl; i > 0; i--) { if (a[n + i] != 0) return 1; /* a > b */ } } return bn_cmp_words(a, b, cl); } /* * Constant-time conditional swap of a and b. * a and b are swapped if condition is not 0. The code assumes that at most one bit of condition is set. * nwords is the number of words to swap. The code assumes that at least nwords are allocated in both a and b, * and that no more than nwords are used by either a or b. * a and b cannot be the same number */ void BN_consttime_swap(BN_ULONG condition, BIGNUM *a, BIGNUM *b, int nwords) { BN_ULONG t; int i; bn_wcheck_size(a, nwords); bn_wcheck_size(b, nwords); assert(a != b); assert((condition & (condition - 1)) == 0); assert(sizeof(BN_ULONG) >= sizeof(int)); condition = ((condition - 1) >> (BN_BITS2 - 1)) - 1; t = (a->top ^ b->top) & condition; a->top ^= t; b->top ^= t; #define BN_CONSTTIME_SWAP(ind) \ do { \ t = (a->d[ind] ^ b->d[ind]) & condition; \ a->d[ind] ^= t; \ b->d[ind] ^= t; \ } while (0) switch (nwords) { default: for (i = 10; i < nwords; i++) BN_CONSTTIME_SWAP(i); /* Fallthrough */ case 10: BN_CONSTTIME_SWAP(9); /* Fallthrough */ case 9: BN_CONSTTIME_SWAP(8); /* Fallthrough */ case 8: BN_CONSTTIME_SWAP(7); /* Fallthrough */ case 7: BN_CONSTTIME_SWAP(6); /* Fallthrough */ case 6: BN_CONSTTIME_SWAP(5); /* Fallthrough */ case 5: BN_CONSTTIME_SWAP(4); /* Fallthrough */ case 4: BN_CONSTTIME_SWAP(3); /* Fallthrough */ case 3: BN_CONSTTIME_SWAP(2); /* Fallthrough */ case 2: BN_CONSTTIME_SWAP(1); /* Fallthrough */ case 1: BN_CONSTTIME_SWAP(0); } #undef BN_CONSTTIME_SWAP } Index: vendor-crypto/openssl/dist/crypto/bn/bn_mont.c =================================================================== --- vendor-crypto/openssl/dist/crypto/bn/bn_mont.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/bn/bn_mont.c (revision 325326) @@ -1,558 +1,561 @@ /* crypto/bn/bn_mont.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). * */ /* * Details about Montgomery multiplication algorithms can be found at * http://security.ece.orst.edu/publications.html, e.g. * http://security.ece.orst.edu/koc/papers/j37acmon.pdf and * sections 3.8 and 4.2 in http://security.ece.orst.edu/koc/papers/r01rsasw.pdf */ #include #include "cryptlib.h" #include "bn_lcl.h" #define MONT_WORD /* use the faster word-based algorithm */ #ifdef MONT_WORD static int BN_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont); #endif int BN_mod_mul_montgomery(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_MONT_CTX *mont, BN_CTX *ctx) { BIGNUM *tmp; int ret = 0; #if defined(OPENSSL_BN_ASM_MONT) && defined(MONT_WORD) int num = mont->N.top; if (num > 1 && a->top == num && b->top == num) { if (bn_wexpand(r, num) == NULL) return (0); if (bn_mul_mont(r->d, a->d, b->d, mont->N.d, mont->n0, num)) { r->neg = a->neg ^ b->neg; r->top = num; bn_correct_top(r); return (1); } } #endif BN_CTX_start(ctx); tmp = BN_CTX_get(ctx); if (tmp == NULL) goto err; bn_check_top(tmp); if (a == b) { if (!BN_sqr(tmp, a, ctx)) goto err; } else { if (!BN_mul(tmp, a, b, ctx)) goto err; } /* reduce from aRR to aR */ #ifdef MONT_WORD if (!BN_from_montgomery_word(r, tmp, mont)) goto err; #else if (!BN_from_montgomery(r, tmp, mont, ctx)) goto err; #endif bn_check_top(r); ret = 1; err: BN_CTX_end(ctx); return (ret); } #ifdef MONT_WORD static int BN_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont) { BIGNUM *n; BN_ULONG *ap, *np, *rp, n0, v, carry; int nl, max, i; n = &(mont->N); nl = n->top; if (nl == 0) { ret->top = 0; return (1); } max = (2 * nl); /* carry is stored separately */ if (bn_wexpand(r, max) == NULL) return (0); r->neg ^= n->neg; np = n->d; rp = r->d; /* clear the top words of T */ # if 1 for (i = r->top; i < max; i++) /* memset? XXX */ rp[i] = 0; # else memset(&(rp[r->top]), 0, (max - r->top) * sizeof(BN_ULONG)); # endif r->top = max; n0 = mont->n0[0]; # ifdef BN_COUNT fprintf(stderr, "word BN_from_montgomery_word %d * %d\n", nl, nl); # endif for (carry = 0, i = 0; i < nl; i++, rp++) { # ifdef __TANDEM { long long t1; long long t2; long long t3; t1 = rp[0] * (n0 & 0177777); t2 = 037777600000l; t2 = n0 & t2; t3 = rp[0] & 0177777; t2 = (t3 * t2) & BN_MASK2; t1 = t1 + t2; v = bn_mul_add_words(rp, np, nl, (BN_ULONG)t1); } # else v = bn_mul_add_words(rp, np, nl, (rp[0] * n0) & BN_MASK2); # endif v = (v + carry + rp[nl]) & BN_MASK2; carry |= (v != rp[nl]); carry &= (v <= rp[nl]); rp[nl] = v; } if (bn_wexpand(ret, nl) == NULL) return (0); ret->top = nl; ret->neg = r->neg; rp = ret->d; ap = &(r->d[nl]); # define BRANCH_FREE 1 # if BRANCH_FREE { BN_ULONG *nrp; size_t m; v = bn_sub_words(rp, ap, np, nl) - carry; /* * if subtraction result is real, then trick unconditional memcpy * below to perform in-place "refresh" instead of actual copy. */ m = (0 - (size_t)v); nrp = (BN_ULONG *)(((PTR_SIZE_INT) rp & ~m) | ((PTR_SIZE_INT) ap & m)); for (i = 0, nl -= 4; i < nl; i += 4) { BN_ULONG t1, t2, t3, t4; t1 = nrp[i + 0]; t2 = nrp[i + 1]; t3 = nrp[i + 2]; ap[i + 0] = 0; t4 = nrp[i + 3]; ap[i + 1] = 0; rp[i + 0] = t1; ap[i + 2] = 0; rp[i + 1] = t2; ap[i + 3] = 0; rp[i + 2] = t3; rp[i + 3] = t4; } for (nl += 4; i < nl; i++) rp[i] = nrp[i], ap[i] = 0; } # else if (bn_sub_words(rp, ap, np, nl) - carry) memcpy(rp, ap, nl * sizeof(BN_ULONG)); # endif bn_correct_top(r); bn_correct_top(ret); bn_check_top(ret); return (1); } #endif /* MONT_WORD */ int BN_from_montgomery(BIGNUM *ret, const BIGNUM *a, BN_MONT_CTX *mont, BN_CTX *ctx) { int retn = 0; #ifdef MONT_WORD BIGNUM *t; BN_CTX_start(ctx); if ((t = BN_CTX_get(ctx)) && BN_copy(t, a)) retn = BN_from_montgomery_word(ret, t, mont); BN_CTX_end(ctx); #else /* !MONT_WORD */ BIGNUM *t1, *t2; BN_CTX_start(ctx); t1 = BN_CTX_get(ctx); t2 = BN_CTX_get(ctx); if (t1 == NULL || t2 == NULL) goto err; if (!BN_copy(t1, a)) goto err; BN_mask_bits(t1, mont->ri); if (!BN_mul(t2, t1, &mont->Ni, ctx)) goto err; BN_mask_bits(t2, mont->ri); if (!BN_mul(t1, t2, &mont->N, ctx)) goto err; if (!BN_add(t2, a, t1)) goto err; if (!BN_rshift(ret, t2, mont->ri)) goto err; if (BN_ucmp(ret, &(mont->N)) >= 0) { if (!BN_usub(ret, ret, &(mont->N))) goto err; } retn = 1; bn_check_top(ret); err: BN_CTX_end(ctx); #endif /* MONT_WORD */ return (retn); } BN_MONT_CTX *BN_MONT_CTX_new(void) { BN_MONT_CTX *ret; if ((ret = (BN_MONT_CTX *)OPENSSL_malloc(sizeof(BN_MONT_CTX))) == NULL) return (NULL); BN_MONT_CTX_init(ret); ret->flags = BN_FLG_MALLOCED; return (ret); } void BN_MONT_CTX_init(BN_MONT_CTX *ctx) { ctx->ri = 0; BN_init(&(ctx->RR)); BN_init(&(ctx->N)); BN_init(&(ctx->Ni)); ctx->n0[0] = ctx->n0[1] = 0; ctx->flags = 0; } void BN_MONT_CTX_free(BN_MONT_CTX *mont) { if (mont == NULL) return; BN_clear_free(&(mont->RR)); BN_clear_free(&(mont->N)); BN_clear_free(&(mont->Ni)); if (mont->flags & BN_FLG_MALLOCED) OPENSSL_free(mont); } int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *mod, BN_CTX *ctx) { int ret = 0; BIGNUM *Ri, *R; if (BN_is_zero(mod)) return 0; BN_CTX_start(ctx); if ((Ri = BN_CTX_get(ctx)) == NULL) goto err; R = &(mont->RR); /* grab RR as a temp */ if (!BN_copy(&(mont->N), mod)) goto err; /* Set N */ mont->N.neg = 0; #ifdef MONT_WORD { BIGNUM tmod; BN_ULONG buf[2]; BN_init(&tmod); tmod.d = buf; tmod.dmax = 2; tmod.neg = 0; + if (BN_get_flags(mod, BN_FLG_CONSTTIME) != 0) + BN_set_flags(&tmod, BN_FLG_CONSTTIME); + mont->ri = (BN_num_bits(mod) + (BN_BITS2 - 1)) / BN_BITS2 * BN_BITS2; # if defined(OPENSSL_BN_ASM_MONT) && (BN_BITS2<=32) /* * Only certain BN_BITS2<=32 platforms actually make use of n0[1], * and we could use the #else case (with a shorter R value) for the * others. However, currently only the assembler files do know which * is which. */ BN_zero(R); if (!(BN_set_bit(R, 2 * BN_BITS2))) goto err; tmod.top = 0; if ((buf[0] = mod->d[0])) tmod.top = 1; if ((buf[1] = mod->top > 1 ? mod->d[1] : 0)) tmod.top = 2; if ((BN_mod_inverse(Ri, R, &tmod, ctx)) == NULL) goto err; if (!BN_lshift(Ri, Ri, 2 * BN_BITS2)) goto err; /* R*Ri */ if (!BN_is_zero(Ri)) { if (!BN_sub_word(Ri, 1)) goto err; } else { /* if N mod word size == 1 */ if (bn_expand(Ri, (int)sizeof(BN_ULONG) * 2) == NULL) goto err; /* Ri-- (mod double word size) */ Ri->neg = 0; Ri->d[0] = BN_MASK2; Ri->d[1] = BN_MASK2; Ri->top = 2; } if (!BN_div(Ri, NULL, Ri, &tmod, ctx)) goto err; /* * Ni = (R*Ri-1)/N, keep only couple of least significant words: */ mont->n0[0] = (Ri->top > 0) ? Ri->d[0] : 0; mont->n0[1] = (Ri->top > 1) ? Ri->d[1] : 0; # else BN_zero(R); if (!(BN_set_bit(R, BN_BITS2))) goto err; /* R */ buf[0] = mod->d[0]; /* tmod = N mod word size */ buf[1] = 0; tmod.top = buf[0] != 0 ? 1 : 0; /* Ri = R^-1 mod N */ if ((BN_mod_inverse(Ri, R, &tmod, ctx)) == NULL) goto err; if (!BN_lshift(Ri, Ri, BN_BITS2)) goto err; /* R*Ri */ if (!BN_is_zero(Ri)) { if (!BN_sub_word(Ri, 1)) goto err; } else { /* if N mod word size == 1 */ if (!BN_set_word(Ri, BN_MASK2)) goto err; /* Ri-- (mod word size) */ } if (!BN_div(Ri, NULL, Ri, &tmod, ctx)) goto err; /* * Ni = (R*Ri-1)/N, keep only least significant word: */ mont->n0[0] = (Ri->top > 0) ? Ri->d[0] : 0; mont->n0[1] = 0; # endif } #else /* !MONT_WORD */ { /* bignum version */ mont->ri = BN_num_bits(&mont->N); BN_zero(R); if (!BN_set_bit(R, mont->ri)) goto err; /* R = 2^ri */ /* Ri = R^-1 mod N */ if ((BN_mod_inverse(Ri, R, &mont->N, ctx)) == NULL) goto err; if (!BN_lshift(Ri, Ri, mont->ri)) goto err; /* R*Ri */ if (!BN_sub_word(Ri, 1)) goto err; /* * Ni = (R*Ri-1) / N */ if (!BN_div(&(mont->Ni), NULL, Ri, &mont->N, ctx)) goto err; } #endif /* setup RR for conversions */ BN_zero(&(mont->RR)); if (!BN_set_bit(&(mont->RR), mont->ri * 2)) goto err; if (!BN_mod(&(mont->RR), &(mont->RR), &(mont->N), ctx)) goto err; ret = 1; err: BN_CTX_end(ctx); return ret; } BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, BN_MONT_CTX *from) { if (to == from) return (to); if (!BN_copy(&(to->RR), &(from->RR))) return NULL; if (!BN_copy(&(to->N), &(from->N))) return NULL; if (!BN_copy(&(to->Ni), &(from->Ni))) return NULL; to->ri = from->ri; to->n0[0] = from->n0[0]; to->n0[1] = from->n0[1]; return (to); } BN_MONT_CTX *BN_MONT_CTX_set_locked(BN_MONT_CTX **pmont, int lock, const BIGNUM *mod, BN_CTX *ctx) { BN_MONT_CTX *ret; CRYPTO_r_lock(lock); ret = *pmont; CRYPTO_r_unlock(lock); if (ret) return ret; /* * We don't want to serialise globally while doing our lazy-init math in * BN_MONT_CTX_set. That punishes threads that are doing independent * things. Instead, punish the case where more than one thread tries to * lazy-init the same 'pmont', by having each do the lazy-init math work * independently and only use the one from the thread that wins the race * (the losers throw away the work they've done). */ ret = BN_MONT_CTX_new(); if (!ret) return NULL; if (!BN_MONT_CTX_set(ret, mod, ctx)) { BN_MONT_CTX_free(ret); return NULL; } /* The locked compare-and-set, after the local work is done. */ CRYPTO_w_lock(lock); if (*pmont) { BN_MONT_CTX_free(ret); ret = *pmont; } else *pmont = ret; CRYPTO_w_unlock(lock); return ret; } Index: vendor-crypto/openssl/dist/crypto/bn/bn_mul.c =================================================================== --- vendor-crypto/openssl/dist/crypto/bn/bn_mul.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/bn/bn_mul.c (revision 325326) @@ -1,1165 +1,1125 @@ /* crypto/bn/bn_mul.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.] */ #ifndef BN_DEBUG # undef NDEBUG /* avoid conflicting definitions */ # define NDEBUG #endif #include #include #include "cryptlib.h" #include "bn_lcl.h" #if defined(OPENSSL_NO_ASM) || !defined(OPENSSL_BN_ASM_PART_WORDS) /* * Here follows specialised variants of bn_add_words() and bn_sub_words(). * They have the property performing operations on arrays of different sizes. * The sizes of those arrays is expressed through cl, which is the common * length ( basicall, min(len(a),len(b)) ), and dl, which is the delta * between the two lengths, calculated as len(a)-len(b). All lengths are the * number of BN_ULONGs... For the operations that require a result array as * parameter, it must have the length cl+abs(dl). These functions should * probably end up in bn_asm.c as soon as there are assembler counterparts * for the systems that use assembler files. */ BN_ULONG bn_sub_part_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, int cl, int dl) { BN_ULONG c, t; assert(cl >= 0); c = bn_sub_words(r, a, b, cl); if (dl == 0) return c; r += cl; a += cl; b += cl; if (dl < 0) { # ifdef BN_COUNT fprintf(stderr, " bn_sub_part_words %d + %d (dl < 0, c = %d)\n", cl, dl, c); # endif for (;;) { t = b[0]; r[0] = (0 - t - c) & BN_MASK2; if (t != 0) c = 1; if (++dl >= 0) break; t = b[1]; r[1] = (0 - t - c) & BN_MASK2; if (t != 0) c = 1; if (++dl >= 0) break; t = b[2]; r[2] = (0 - t - c) & BN_MASK2; if (t != 0) c = 1; if (++dl >= 0) break; t = b[3]; r[3] = (0 - t - c) & BN_MASK2; if (t != 0) c = 1; if (++dl >= 0) break; b += 4; r += 4; } } else { int save_dl = dl; # ifdef BN_COUNT fprintf(stderr, " bn_sub_part_words %d + %d (dl > 0, c = %d)\n", cl, dl, c); # endif while (c) { t = a[0]; r[0] = (t - c) & BN_MASK2; if (t != 0) c = 0; if (--dl <= 0) break; t = a[1]; r[1] = (t - c) & BN_MASK2; if (t != 0) c = 0; if (--dl <= 0) break; t = a[2]; r[2] = (t - c) & BN_MASK2; if (t != 0) c = 0; if (--dl <= 0) break; t = a[3]; r[3] = (t - c) & BN_MASK2; if (t != 0) c = 0; if (--dl <= 0) break; save_dl = dl; a += 4; r += 4; } if (dl > 0) { # ifdef BN_COUNT fprintf(stderr, " bn_sub_part_words %d + %d (dl > 0, c == 0)\n", cl, dl); # endif if (save_dl > dl) { switch (save_dl - dl) { case 1: r[1] = a[1]; if (--dl <= 0) break; case 2: r[2] = a[2]; if (--dl <= 0) break; case 3: r[3] = a[3]; if (--dl <= 0) break; } a += 4; r += 4; } } if (dl > 0) { # ifdef BN_COUNT fprintf(stderr, " bn_sub_part_words %d + %d (dl > 0, copy)\n", cl, dl); # endif for (;;) { r[0] = a[0]; if (--dl <= 0) break; r[1] = a[1]; if (--dl <= 0) break; r[2] = a[2]; if (--dl <= 0) break; r[3] = a[3]; if (--dl <= 0) break; a += 4; r += 4; } } } return c; } #endif BN_ULONG bn_add_part_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, int cl, int dl) { BN_ULONG c, l, t; assert(cl >= 0); c = bn_add_words(r, a, b, cl); if (dl == 0) return c; r += cl; a += cl; b += cl; if (dl < 0) { int save_dl = dl; #ifdef BN_COUNT fprintf(stderr, " bn_add_part_words %d + %d (dl < 0, c = %d)\n", cl, dl, c); #endif while (c) { l = (c + b[0]) & BN_MASK2; c = (l < c); r[0] = l; if (++dl >= 0) break; l = (c + b[1]) & BN_MASK2; c = (l < c); r[1] = l; if (++dl >= 0) break; l = (c + b[2]) & BN_MASK2; c = (l < c); r[2] = l; if (++dl >= 0) break; l = (c + b[3]) & BN_MASK2; c = (l < c); r[3] = l; if (++dl >= 0) break; save_dl = dl; b += 4; r += 4; } if (dl < 0) { #ifdef BN_COUNT fprintf(stderr, " bn_add_part_words %d + %d (dl < 0, c == 0)\n", cl, dl); #endif if (save_dl < dl) { switch (dl - save_dl) { case 1: r[1] = b[1]; if (++dl >= 0) break; case 2: r[2] = b[2]; if (++dl >= 0) break; case 3: r[3] = b[3]; if (++dl >= 0) break; } b += 4; r += 4; } } if (dl < 0) { #ifdef BN_COUNT fprintf(stderr, " bn_add_part_words %d + %d (dl < 0, copy)\n", cl, dl); #endif for (;;) { r[0] = b[0]; if (++dl >= 0) break; r[1] = b[1]; if (++dl >= 0) break; r[2] = b[2]; if (++dl >= 0) break; r[3] = b[3]; if (++dl >= 0) break; b += 4; r += 4; } } } else { int save_dl = dl; #ifdef BN_COUNT fprintf(stderr, " bn_add_part_words %d + %d (dl > 0)\n", cl, dl); #endif while (c) { t = (a[0] + c) & BN_MASK2; c = (t < c); r[0] = t; if (--dl <= 0) break; t = (a[1] + c) & BN_MASK2; c = (t < c); r[1] = t; if (--dl <= 0) break; t = (a[2] + c) & BN_MASK2; c = (t < c); r[2] = t; if (--dl <= 0) break; t = (a[3] + c) & BN_MASK2; c = (t < c); r[3] = t; if (--dl <= 0) break; save_dl = dl; a += 4; r += 4; } #ifdef BN_COUNT fprintf(stderr, " bn_add_part_words %d + %d (dl > 0, c == 0)\n", cl, dl); #endif if (dl > 0) { if (save_dl > dl) { switch (save_dl - dl) { case 1: r[1] = a[1]; if (--dl <= 0) break; case 2: r[2] = a[2]; if (--dl <= 0) break; case 3: r[3] = a[3]; if (--dl <= 0) break; } a += 4; r += 4; } } if (dl > 0) { #ifdef BN_COUNT fprintf(stderr, " bn_add_part_words %d + %d (dl > 0, copy)\n", cl, dl); #endif for (;;) { r[0] = a[0]; if (--dl <= 0) break; r[1] = a[1]; if (--dl <= 0) break; r[2] = a[2]; if (--dl <= 0) break; r[3] = a[3]; if (--dl <= 0) break; a += 4; r += 4; } } } return c; } #ifdef BN_RECURSION /* * Karatsuba recursive multiplication algorithm (cf. Knuth, The Art of * Computer Programming, Vol. 2) */ /*- * r is 2*n2 words in size, * a and b are both n2 words in size. * n2 must be a power of 2. * We multiply and return the result. * t must be 2*n2 words in size * We calculate * a[0]*b[0] * a[0]*b[0]+a[1]*b[1]+(a[0]-a[1])*(b[1]-b[0]) * a[1]*b[1] */ /* dnX may not be positive, but n2/2+dnX has to be */ void bn_mul_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n2, int dna, int dnb, BN_ULONG *t) { int n = n2 / 2, c1, c2; int tna = n + dna, tnb = n + dnb; unsigned int neg, zero; BN_ULONG ln, lo, *p; # ifdef BN_COUNT fprintf(stderr, " bn_mul_recursive %d%+d * %d%+d\n", n2, dna, n2, dnb); # endif # ifdef BN_MUL_COMBA # if 0 if (n2 == 4) { bn_mul_comba4(r, a, b); return; } # endif /* * Only call bn_mul_comba 8 if n2 == 8 and the two arrays are complete * [steve] */ if (n2 == 8 && dna == 0 && dnb == 0) { bn_mul_comba8(r, a, b); return; } # endif /* BN_MUL_COMBA */ /* Else do normal multiply */ if (n2 < BN_MUL_RECURSIVE_SIZE_NORMAL) { bn_mul_normal(r, a, n2 + dna, b, n2 + dnb); if ((dna + dnb) < 0) memset(&r[2 * n2 + dna + dnb], 0, sizeof(BN_ULONG) * -(dna + dnb)); return; } /* r=(a[0]-a[1])*(b[1]-b[0]) */ c1 = bn_cmp_part_words(a, &(a[n]), tna, n - tna); c2 = bn_cmp_part_words(&(b[n]), b, tnb, tnb - n); zero = neg = 0; switch (c1 * 3 + c2) { case -4: bn_sub_part_words(t, &(a[n]), a, tna, tna - n); /* - */ bn_sub_part_words(&(t[n]), b, &(b[n]), tnb, n - tnb); /* - */ break; case -3: zero = 1; break; case -2: bn_sub_part_words(t, &(a[n]), a, tna, tna - n); /* - */ bn_sub_part_words(&(t[n]), &(b[n]), b, tnb, tnb - n); /* + */ neg = 1; break; case -1: case 0: case 1: zero = 1; break; case 2: bn_sub_part_words(t, a, &(a[n]), tna, n - tna); /* + */ bn_sub_part_words(&(t[n]), b, &(b[n]), tnb, n - tnb); /* - */ neg = 1; break; case 3: zero = 1; break; case 4: bn_sub_part_words(t, a, &(a[n]), tna, n - tna); bn_sub_part_words(&(t[n]), &(b[n]), b, tnb, tnb - n); break; } # ifdef BN_MUL_COMBA if (n == 4 && dna == 0 && dnb == 0) { /* XXX: bn_mul_comba4 could take * extra args to do this well */ if (!zero) bn_mul_comba4(&(t[n2]), t, &(t[n])); else memset(&(t[n2]), 0, 8 * sizeof(BN_ULONG)); bn_mul_comba4(r, a, b); bn_mul_comba4(&(r[n2]), &(a[n]), &(b[n])); } else if (n == 8 && dna == 0 && dnb == 0) { /* XXX: bn_mul_comba8 could * take extra args to do * this well */ if (!zero) bn_mul_comba8(&(t[n2]), t, &(t[n])); else memset(&(t[n2]), 0, 16 * sizeof(BN_ULONG)); bn_mul_comba8(r, a, b); bn_mul_comba8(&(r[n2]), &(a[n]), &(b[n])); } else # endif /* BN_MUL_COMBA */ { p = &(t[n2 * 2]); if (!zero) bn_mul_recursive(&(t[n2]), t, &(t[n]), n, 0, 0, p); else memset(&(t[n2]), 0, n2 * sizeof(BN_ULONG)); bn_mul_recursive(r, a, b, n, 0, 0, p); bn_mul_recursive(&(r[n2]), &(a[n]), &(b[n]), n, dna, dnb, p); } /*- * t[32] holds (a[0]-a[1])*(b[1]-b[0]), c1 is the sign * r[10] holds (a[0]*b[0]) * r[32] holds (b[1]*b[1]) */ c1 = (int)(bn_add_words(t, r, &(r[n2]), n2)); if (neg) { /* if t[32] is negative */ c1 -= (int)(bn_sub_words(&(t[n2]), t, &(t[n2]), n2)); } else { /* Might have a carry */ c1 += (int)(bn_add_words(&(t[n2]), &(t[n2]), t, n2)); } /*- * t[32] holds (a[0]-a[1])*(b[1]-b[0])+(a[0]*b[0])+(a[1]*b[1]) * r[10] holds (a[0]*b[0]) * r[32] holds (b[1]*b[1]) * c1 holds the carry bits */ c1 += (int)(bn_add_words(&(r[n]), &(r[n]), &(t[n2]), n2)); if (c1) { p = &(r[n + n2]); lo = *p; ln = (lo + c1) & BN_MASK2; *p = ln; /* * The overflow will stop before we over write words we should not * overwrite */ if (ln < (BN_ULONG)c1) { do { p++; lo = *p; ln = (lo + 1) & BN_MASK2; *p = ln; } while (ln == 0); } } } /* * n+tn is the word length t needs to be n*4 is size, as does r */ /* tnX may not be negative but less than n */ void bn_mul_part_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n, int tna, int tnb, BN_ULONG *t) { int i, j, n2 = n * 2; int c1, c2, neg; BN_ULONG ln, lo, *p; # ifdef BN_COUNT fprintf(stderr, " bn_mul_part_recursive (%d%+d) * (%d%+d)\n", n, tna, n, tnb); # endif if (n < 8) { bn_mul_normal(r, a, n + tna, b, n + tnb); return; } /* r=(a[0]-a[1])*(b[1]-b[0]) */ c1 = bn_cmp_part_words(a, &(a[n]), tna, n - tna); c2 = bn_cmp_part_words(&(b[n]), b, tnb, tnb - n); neg = 0; switch (c1 * 3 + c2) { case -4: bn_sub_part_words(t, &(a[n]), a, tna, tna - n); /* - */ bn_sub_part_words(&(t[n]), b, &(b[n]), tnb, n - tnb); /* - */ break; case -3: /* break; */ case -2: bn_sub_part_words(t, &(a[n]), a, tna, tna - n); /* - */ bn_sub_part_words(&(t[n]), &(b[n]), b, tnb, tnb - n); /* + */ neg = 1; break; case -1: case 0: case 1: /* break; */ case 2: bn_sub_part_words(t, a, &(a[n]), tna, n - tna); /* + */ bn_sub_part_words(&(t[n]), b, &(b[n]), tnb, n - tnb); /* - */ neg = 1; break; case 3: /* break; */ case 4: bn_sub_part_words(t, a, &(a[n]), tna, n - tna); bn_sub_part_words(&(t[n]), &(b[n]), b, tnb, tnb - n); break; } /* * The zero case isn't yet implemented here. The speedup would probably * be negligible. */ # if 0 if (n == 4) { bn_mul_comba4(&(t[n2]), t, &(t[n])); bn_mul_comba4(r, a, b); bn_mul_normal(&(r[n2]), &(a[n]), tn, &(b[n]), tn); memset(&(r[n2 + tn * 2]), 0, sizeof(BN_ULONG) * (n2 - tn * 2)); } else # endif if (n == 8) { bn_mul_comba8(&(t[n2]), t, &(t[n])); bn_mul_comba8(r, a, b); bn_mul_normal(&(r[n2]), &(a[n]), tna, &(b[n]), tnb); memset(&(r[n2 + tna + tnb]), 0, sizeof(BN_ULONG) * (n2 - tna - tnb)); } else { p = &(t[n2 * 2]); bn_mul_recursive(&(t[n2]), t, &(t[n]), n, 0, 0, p); bn_mul_recursive(r, a, b, n, 0, 0, p); i = n / 2; /* * If there is only a bottom half to the number, just do it */ if (tna > tnb) j = tna - i; else j = tnb - i; if (j == 0) { bn_mul_recursive(&(r[n2]), &(a[n]), &(b[n]), i, tna - i, tnb - i, p); memset(&(r[n2 + i * 2]), 0, sizeof(BN_ULONG) * (n2 - i * 2)); } else if (j > 0) { /* eg, n == 16, i == 8 and tn == 11 */ bn_mul_part_recursive(&(r[n2]), &(a[n]), &(b[n]), i, tna - i, tnb - i, p); memset(&(r[n2 + tna + tnb]), 0, sizeof(BN_ULONG) * (n2 - tna - tnb)); } else { /* (j < 0) eg, n == 16, i == 8 and tn == 5 */ memset(&(r[n2]), 0, sizeof(BN_ULONG) * n2); if (tna < BN_MUL_RECURSIVE_SIZE_NORMAL && tnb < BN_MUL_RECURSIVE_SIZE_NORMAL) { bn_mul_normal(&(r[n2]), &(a[n]), tna, &(b[n]), tnb); } else { for (;;) { i /= 2; /* * these simplified conditions work exclusively because * difference between tna and tnb is 1 or 0 */ if (i < tna || i < tnb) { bn_mul_part_recursive(&(r[n2]), &(a[n]), &(b[n]), i, tna - i, tnb - i, p); break; } else if (i == tna || i == tnb) { bn_mul_recursive(&(r[n2]), &(a[n]), &(b[n]), i, tna - i, tnb - i, p); break; } } } } } /*- * t[32] holds (a[0]-a[1])*(b[1]-b[0]), c1 is the sign * r[10] holds (a[0]*b[0]) * r[32] holds (b[1]*b[1]) */ c1 = (int)(bn_add_words(t, r, &(r[n2]), n2)); if (neg) { /* if t[32] is negative */ c1 -= (int)(bn_sub_words(&(t[n2]), t, &(t[n2]), n2)); } else { /* Might have a carry */ c1 += (int)(bn_add_words(&(t[n2]), &(t[n2]), t, n2)); } /*- * t[32] holds (a[0]-a[1])*(b[1]-b[0])+(a[0]*b[0])+(a[1]*b[1]) * r[10] holds (a[0]*b[0]) * r[32] holds (b[1]*b[1]) * c1 holds the carry bits */ c1 += (int)(bn_add_words(&(r[n]), &(r[n]), &(t[n2]), n2)); if (c1) { p = &(r[n + n2]); lo = *p; ln = (lo + c1) & BN_MASK2; *p = ln; /* * The overflow will stop before we over write words we should not * overwrite */ if (ln < (BN_ULONG)c1) { do { p++; lo = *p; ln = (lo + 1) & BN_MASK2; *p = ln; } while (ln == 0); } } } /*- * a and b must be the same size, which is n2. * r needs to be n2 words and t needs to be n2*2 */ void bn_mul_low_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n2, BN_ULONG *t) { int n = n2 / 2; # ifdef BN_COUNT fprintf(stderr, " bn_mul_low_recursive %d * %d\n", n2, n2); # endif bn_mul_recursive(r, a, b, n, 0, 0, &(t[0])); if (n >= BN_MUL_LOW_RECURSIVE_SIZE_NORMAL) { bn_mul_low_recursive(&(t[0]), &(a[0]), &(b[n]), n, &(t[n2])); bn_add_words(&(r[n]), &(r[n]), &(t[0]), n); bn_mul_low_recursive(&(t[0]), &(a[n]), &(b[0]), n, &(t[n2])); bn_add_words(&(r[n]), &(r[n]), &(t[0]), n); } else { bn_mul_low_normal(&(t[0]), &(a[0]), &(b[n]), n); bn_mul_low_normal(&(t[n]), &(a[n]), &(b[0]), n); bn_add_words(&(r[n]), &(r[n]), &(t[0]), n); bn_add_words(&(r[n]), &(r[n]), &(t[n]), n); } } /*- * a and b must be the same size, which is n2. * r needs to be n2 words and t needs to be n2*2 * l is the low words of the output. * t needs to be n2*3 */ void bn_mul_high(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, BN_ULONG *l, int n2, BN_ULONG *t) { int i, n; int c1, c2; int neg, oneg, zero; BN_ULONG ll, lc, *lp, *mp; # ifdef BN_COUNT fprintf(stderr, " bn_mul_high %d * %d\n", n2, n2); # endif n = n2 / 2; /* Calculate (al-ah)*(bh-bl) */ neg = zero = 0; c1 = bn_cmp_words(&(a[0]), &(a[n]), n); c2 = bn_cmp_words(&(b[n]), &(b[0]), n); switch (c1 * 3 + c2) { case -4: bn_sub_words(&(r[0]), &(a[n]), &(a[0]), n); bn_sub_words(&(r[n]), &(b[0]), &(b[n]), n); break; case -3: zero = 1; break; case -2: bn_sub_words(&(r[0]), &(a[n]), &(a[0]), n); bn_sub_words(&(r[n]), &(b[n]), &(b[0]), n); neg = 1; break; case -1: case 0: case 1: zero = 1; break; case 2: bn_sub_words(&(r[0]), &(a[0]), &(a[n]), n); bn_sub_words(&(r[n]), &(b[0]), &(b[n]), n); neg = 1; break; case 3: zero = 1; break; case 4: bn_sub_words(&(r[0]), &(a[0]), &(a[n]), n); bn_sub_words(&(r[n]), &(b[n]), &(b[0]), n); break; } oneg = neg; /* t[10] = (a[0]-a[1])*(b[1]-b[0]) */ /* r[10] = (a[1]*b[1]) */ # ifdef BN_MUL_COMBA if (n == 8) { bn_mul_comba8(&(t[0]), &(r[0]), &(r[n])); bn_mul_comba8(r, &(a[n]), &(b[n])); } else # endif { bn_mul_recursive(&(t[0]), &(r[0]), &(r[n]), n, 0, 0, &(t[n2])); bn_mul_recursive(r, &(a[n]), &(b[n]), n, 0, 0, &(t[n2])); } /*- * s0 == low(al*bl) * s1 == low(ah*bh)+low((al-ah)*(bh-bl))+low(al*bl)+high(al*bl) * We know s0 and s1 so the only unknown is high(al*bl) * high(al*bl) == s1 - low(ah*bh+s0+(al-ah)*(bh-bl)) * high(al*bl) == s1 - (r[0]+l[0]+t[0]) */ if (l != NULL) { lp = &(t[n2 + n]); c1 = (int)(bn_add_words(lp, &(r[0]), &(l[0]), n)); } else { c1 = 0; lp = &(r[0]); } if (neg) neg = (int)(bn_sub_words(&(t[n2]), lp, &(t[0]), n)); else { bn_add_words(&(t[n2]), lp, &(t[0]), n); neg = 0; } if (l != NULL) { bn_sub_words(&(t[n2 + n]), &(l[n]), &(t[n2]), n); } else { lp = &(t[n2 + n]); mp = &(t[n2]); for (i = 0; i < n; i++) lp[i] = ((~mp[i]) + 1) & BN_MASK2; } /*- * s[0] = low(al*bl) * t[3] = high(al*bl) * t[10] = (a[0]-a[1])*(b[1]-b[0]) neg is the sign * r[10] = (a[1]*b[1]) */ /*- * R[10] = al*bl * R[21] = al*bl + ah*bh + (a[0]-a[1])*(b[1]-b[0]) * R[32] = ah*bh */ /*- * R[1]=t[3]+l[0]+r[0](+-)t[0] (have carry/borrow) * R[2]=r[0]+t[3]+r[1](+-)t[1] (have carry/borrow) * R[3]=r[1]+(carry/borrow) */ if (l != NULL) { lp = &(t[n2]); c1 = (int)(bn_add_words(lp, &(t[n2 + n]), &(l[0]), n)); } else { lp = &(t[n2 + n]); c1 = 0; } c1 += (int)(bn_add_words(&(t[n2]), lp, &(r[0]), n)); if (oneg) c1 -= (int)(bn_sub_words(&(t[n2]), &(t[n2]), &(t[0]), n)); else c1 += (int)(bn_add_words(&(t[n2]), &(t[n2]), &(t[0]), n)); c2 = (int)(bn_add_words(&(r[0]), &(r[0]), &(t[n2 + n]), n)); c2 += (int)(bn_add_words(&(r[0]), &(r[0]), &(r[n]), n)); if (oneg) c2 -= (int)(bn_sub_words(&(r[0]), &(r[0]), &(t[n]), n)); else c2 += (int)(bn_add_words(&(r[0]), &(r[0]), &(t[n]), n)); if (c1 != 0) { /* Add starting at r[0], could be +ve or -ve */ i = 0; if (c1 > 0) { lc = c1; do { ll = (r[i] + lc) & BN_MASK2; r[i++] = ll; lc = (lc > ll); } while (lc); } else { lc = -c1; do { ll = r[i]; r[i++] = (ll - lc) & BN_MASK2; lc = (lc > ll); } while (lc); } } if (c2 != 0) { /* Add starting at r[1] */ i = n; if (c2 > 0) { lc = c2; do { ll = (r[i] + lc) & BN_MASK2; r[i++] = ll; lc = (lc > ll); } while (lc); } else { lc = -c2; do { ll = r[i]; r[i++] = (ll - lc) & BN_MASK2; lc = (lc > ll); } while (lc); } } } #endif /* BN_RECURSION */ int BN_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { int ret = 0; int top, al, bl; BIGNUM *rr; #if defined(BN_MUL_COMBA) || defined(BN_RECURSION) int i; #endif #ifdef BN_RECURSION BIGNUM *t = NULL; int j = 0, k; #endif #ifdef BN_COUNT fprintf(stderr, "BN_mul %d * %d\n", a->top, b->top); #endif bn_check_top(a); bn_check_top(b); bn_check_top(r); al = a->top; bl = b->top; if ((al == 0) || (bl == 0)) { BN_zero(r); return (1); } top = al + bl; BN_CTX_start(ctx); if ((r == a) || (r == b)) { if ((rr = BN_CTX_get(ctx)) == NULL) goto err; } else rr = r; rr->neg = a->neg ^ b->neg; #if defined(BN_MUL_COMBA) || defined(BN_RECURSION) i = al - bl; #endif #ifdef BN_MUL_COMBA if (i == 0) { # if 0 if (al == 4) { if (bn_wexpand(rr, 8) == NULL) goto err; rr->top = 8; bn_mul_comba4(rr->d, a->d, b->d); goto end; } # endif if (al == 8) { if (bn_wexpand(rr, 16) == NULL) goto err; rr->top = 16; bn_mul_comba8(rr->d, a->d, b->d); goto end; } } #endif /* BN_MUL_COMBA */ #ifdef BN_RECURSION if ((al >= BN_MULL_SIZE_NORMAL) && (bl >= BN_MULL_SIZE_NORMAL)) { if (i >= -1 && i <= 1) { /* * Find out the power of two lower or equal to the longest of the * two numbers */ if (i >= 0) { j = BN_num_bits_word((BN_ULONG)al); } if (i == -1) { j = BN_num_bits_word((BN_ULONG)bl); } j = 1 << (j - 1); assert(j <= al || j <= bl); k = j + j; t = BN_CTX_get(ctx); if (t == NULL) goto err; if (al > j || bl > j) { if (bn_wexpand(t, k * 4) == NULL) goto err; if (bn_wexpand(rr, k * 4) == NULL) goto err; bn_mul_part_recursive(rr->d, a->d, b->d, j, al - j, bl - j, t->d); } else { /* al <= j || bl <= j */ if (bn_wexpand(t, k * 2) == NULL) goto err; if (bn_wexpand(rr, k * 2) == NULL) goto err; bn_mul_recursive(rr->d, a->d, b->d, j, al - j, bl - j, t->d); } rr->top = top; goto end; } -# if 0 - if (i == 1 && !BN_get_flags(b, BN_FLG_STATIC_DATA)) { - BIGNUM *tmp_bn = (BIGNUM *)b; - if (bn_wexpand(tmp_bn, al) == NULL) - goto err; - tmp_bn->d[bl] = 0; - bl++; - i--; - } else if (i == -1 && !BN_get_flags(a, BN_FLG_STATIC_DATA)) { - BIGNUM *tmp_bn = (BIGNUM *)a; - if (bn_wexpand(tmp_bn, bl) == NULL) - goto err; - tmp_bn->d[al] = 0; - al++; - i++; - } - if (i == 0) { - /* symmetric and > 4 */ - /* 16 or larger */ - j = BN_num_bits_word((BN_ULONG)al); - j = 1 << (j - 1); - k = j + j; - t = BN_CTX_get(ctx); - if (al == j) { /* exact multiple */ - if (bn_wexpand(t, k * 2) == NULL) - goto err; - if (bn_wexpand(rr, k * 2) == NULL) - goto err; - bn_mul_recursive(rr->d, a->d, b->d, al, t->d); - } else { - if (bn_wexpand(t, k * 4) == NULL) - goto err; - if (bn_wexpand(rr, k * 4) == NULL) - goto err; - bn_mul_part_recursive(rr->d, a->d, b->d, al - j, j, t->d); - } - rr->top = top; - goto end; - } -# endif } #endif /* BN_RECURSION */ if (bn_wexpand(rr, top) == NULL) goto err; rr->top = top; bn_mul_normal(rr->d, a->d, al, b->d, bl); #if defined(BN_MUL_COMBA) || defined(BN_RECURSION) end: #endif bn_correct_top(rr); if (r != rr && BN_copy(r, rr) == NULL) goto err; ret = 1; err: bn_check_top(r); BN_CTX_end(ctx); return (ret); } void bn_mul_normal(BN_ULONG *r, BN_ULONG *a, int na, BN_ULONG *b, int nb) { BN_ULONG *rr; #ifdef BN_COUNT fprintf(stderr, " bn_mul_normal %d * %d\n", na, nb); #endif if (na < nb) { int itmp; BN_ULONG *ltmp; itmp = na; na = nb; nb = itmp; ltmp = a; a = b; b = ltmp; } rr = &(r[na]); if (nb <= 0) { (void)bn_mul_words(r, a, na, 0); return; } else rr[0] = bn_mul_words(r, a, na, b[0]); for (;;) { if (--nb <= 0) return; rr[1] = bn_mul_add_words(&(r[1]), a, na, b[1]); if (--nb <= 0) return; rr[2] = bn_mul_add_words(&(r[2]), a, na, b[2]); if (--nb <= 0) return; rr[3] = bn_mul_add_words(&(r[3]), a, na, b[3]); if (--nb <= 0) return; rr[4] = bn_mul_add_words(&(r[4]), a, na, b[4]); rr += 4; r += 4; b += 4; } } void bn_mul_low_normal(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n) { #ifdef BN_COUNT fprintf(stderr, " bn_mul_low_normal %d * %d\n", n, n); #endif bn_mul_words(r, a, n, b[0]); for (;;) { if (--n <= 0) return; bn_mul_add_words(&(r[1]), a, n, b[1]); if (--n <= 0) return; bn_mul_add_words(&(r[2]), a, n, b[2]); if (--n <= 0) return; bn_mul_add_words(&(r[3]), a, n, b[3]); if (--n <= 0) return; bn_mul_add_words(&(r[4]), a, n, b[4]); r += 4; b += 4; } } Index: vendor-crypto/openssl/dist/crypto/bn/bn_x931p.c =================================================================== --- vendor-crypto/openssl/dist/crypto/bn/bn_x931p.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/bn/bn_x931p.c (revision 325326) @@ -1,277 +1,281 @@ /* bn_x931p.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 /* X9.31 routines for prime derivation */ /* * X9.31 prime derivation. This is used to generate the primes pi (p1, p2, * q1, q2) from a parameter Xpi by checking successive odd integers. */ static int bn_x931_derive_pi(BIGNUM *pi, const BIGNUM *Xpi, BN_CTX *ctx, BN_GENCB *cb) { int i = 0; if (!BN_copy(pi, Xpi)) return 0; if (!BN_is_odd(pi) && !BN_add_word(pi, 1)) return 0; for (;;) { i++; BN_GENCB_call(cb, 0, i); /* NB 27 MR is specificed in X9.31 */ if (BN_is_prime_fasttest_ex(pi, 27, ctx, 1, cb)) break; if (!BN_add_word(pi, 2)) return 0; } BN_GENCB_call(cb, 2, i); return 1; } /* * This is the main X9.31 prime derivation function. From parameters Xp1, Xp2 * and Xp derive the prime p. If the parameters p1 or p2 are not NULL they * will be returned too: this is needed for testing. */ int BN_X931_derive_prime_ex(BIGNUM *p, BIGNUM *p1, BIGNUM *p2, const BIGNUM *Xp, const BIGNUM *Xp1, const BIGNUM *Xp2, const BIGNUM *e, BN_CTX *ctx, BN_GENCB *cb) { int ret = 0; BIGNUM *t, *p1p2, *pm1; /* Only even e supported */ if (!BN_is_odd(e)) return 0; BN_CTX_start(ctx); if (!p1) p1 = BN_CTX_get(ctx); if (!p2) p2 = BN_CTX_get(ctx); t = BN_CTX_get(ctx); p1p2 = BN_CTX_get(ctx); pm1 = BN_CTX_get(ctx); if (!bn_x931_derive_pi(p1, Xp1, ctx, cb)) goto err; if (!bn_x931_derive_pi(p2, Xp2, ctx, cb)) goto err; if (!BN_mul(p1p2, p1, p2, ctx)) goto err; /* First set p to value of Rp */ if (!BN_mod_inverse(p, p2, p1, ctx)) goto err; if (!BN_mul(p, p, p2, ctx)) goto err; if (!BN_mod_inverse(t, p1, p2, ctx)) goto err; if (!BN_mul(t, t, p1, ctx)) goto err; if (!BN_sub(p, p, t)) goto err; if (p->neg && !BN_add(p, p, p1p2)) goto err; /* p now equals Rp */ if (!BN_mod_sub(p, p, Xp, p1p2, ctx)) goto err; if (!BN_add(p, p, Xp)) goto err; /* p now equals Yp0 */ for (;;) { int i = 1; BN_GENCB_call(cb, 0, i++); if (!BN_copy(pm1, p)) goto err; if (!BN_sub_word(pm1, 1)) goto err; if (!BN_gcd(t, pm1, e, ctx)) goto err; if (BN_is_one(t) /* * X9.31 specifies 8 MR and 1 Lucas test or any prime test * offering similar or better guarantees 50 MR is considerably * better. */ && BN_is_prime_fasttest_ex(p, 50, ctx, 1, cb)) break; if (!BN_add(p, p, p1p2)) goto err; } BN_GENCB_call(cb, 3, 0); ret = 1; err: BN_CTX_end(ctx); return ret; } /* * Generate pair of paramters Xp, Xq for X9.31 prime generation. Note: nbits * paramter is sum of number of bits in both. */ int BN_X931_generate_Xpq(BIGNUM *Xp, BIGNUM *Xq, int nbits, BN_CTX *ctx) { BIGNUM *t; int i; /* * Number of bits for each prime is of the form 512+128s for s = 0, 1, * ... */ if ((nbits < 1024) || (nbits & 0xff)) return 0; nbits >>= 1; /* * The random value Xp must be between sqrt(2) * 2^(nbits-1) and 2^nbits * - 1. By setting the top two bits we ensure that the lower bound is * exceeded. */ if (!BN_rand(Xp, nbits, 1, 0)) goto err; BN_CTX_start(ctx); t = BN_CTX_get(ctx); + if (t == NULL) + goto err; for (i = 0; i < 1000; i++) { if (!BN_rand(Xq, nbits, 1, 0)) goto err; /* Check that |Xp - Xq| > 2^(nbits - 100) */ BN_sub(t, Xp, Xq); if (BN_num_bits(t) > (nbits - 100)) break; } BN_CTX_end(ctx); if (i < 1000) return 1; return 0; err: BN_CTX_end(ctx); return 0; } /* * Generate primes using X9.31 algorithm. Of the values p, p1, p2, Xp1 and * Xp2 only 'p' needs to be non-NULL. If any of the others are not NULL the * relevant parameter will be stored in it. Due to the fact that |Xp - Xq| > * 2^(nbits - 100) must be satisfied Xp and Xq are generated using the * previous function and supplied as input. */ int BN_X931_generate_prime_ex(BIGNUM *p, BIGNUM *p1, BIGNUM *p2, BIGNUM *Xp1, BIGNUM *Xp2, const BIGNUM *Xp, const BIGNUM *e, BN_CTX *ctx, BN_GENCB *cb) { int ret = 0; BN_CTX_start(ctx); - if (!Xp1) + if (Xp1 == NULL) Xp1 = BN_CTX_get(ctx); - if (!Xp2) + if (Xp2 == NULL) Xp2 = BN_CTX_get(ctx); + if (Xp1 == NULL || Xp2 == NULL) + goto error; if (!BN_rand(Xp1, 101, 0, 0)) goto error; if (!BN_rand(Xp2, 101, 0, 0)) goto error; if (!BN_X931_derive_prime_ex(p, p1, p2, Xp, Xp1, Xp2, e, ctx, cb)) goto error; ret = 1; error: BN_CTX_end(ctx); return ret; } Index: vendor-crypto/openssl/dist/crypto/cryptlib.c =================================================================== --- vendor-crypto/openssl/dist/crypto/cryptlib.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/cryptlib.c (revision 325326) @@ -1,1030 +1,1037 @@ /* crypto/cryptlib.c */ /* ==================================================================== * 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 (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 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. * ECDH support in OpenSSL originally developed by * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. */ #include "cryptlib.h" #include #if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN16) static double SSLeay_MSVC5_hack = 0.0; /* and for VC1.5 */ #endif DECLARE_STACK_OF(CRYPTO_dynlock) /* real #defines in crypto.h, keep these upto date */ static const char *const lock_names[CRYPTO_NUM_LOCKS] = { "<>", "err", "ex_data", "x509", "x509_info", "x509_pkey", "x509_crl", "x509_req", "dsa", "rsa", "evp_pkey", "x509_store", "ssl_ctx", "ssl_cert", "ssl_session", "ssl_sess_cert", "ssl", "ssl_method", "rand", "rand2", "debug_malloc", "BIO", "gethostbyname", "getservbyname", "readdir", "RSA_blinding", "dh", "debug_malloc2", "dso", "dynlock", "engine", "ui", "ecdsa", "ec", "ecdh", "bn", "ec_pre_comp", "store", "comp", "fips", "fips2", #if CRYPTO_NUM_LOCKS != 41 # error "Inconsistency between crypto.h and cryptlib.c" #endif }; /* * This is for applications to allocate new type names in the non-dynamic * array of lock names. These are numbered with positive numbers. */ static STACK_OF(OPENSSL_STRING) *app_locks = NULL; /* * For applications that want a more dynamic way of handling threads, the * following stack is used. These are externally numbered with negative * numbers. */ static STACK_OF(CRYPTO_dynlock) *dyn_locks = NULL; static void (MS_FAR *locking_callback) (int mode, int type, const char *file, int line) = 0; static int (MS_FAR *add_lock_callback) (int *pointer, int amount, int type, const char *file, int line) = 0; #ifndef OPENSSL_NO_DEPRECATED static unsigned long (MS_FAR *id_callback) (void) = 0; #endif static void (MS_FAR *threadid_callback) (CRYPTO_THREADID *) = 0; static struct CRYPTO_dynlock_value *(MS_FAR *dynlock_create_callback) (const char *file, int line) = 0; static void (MS_FAR *dynlock_lock_callback) (int mode, struct CRYPTO_dynlock_value *l, const char *file, int line) = 0; static void (MS_FAR *dynlock_destroy_callback) (struct CRYPTO_dynlock_value *l, const char *file, int line) = 0; int CRYPTO_get_new_lockid(char *name) { char *str; int i; #if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN16) /* * A hack to make Visual C++ 5.0 work correctly when linking as a DLL * using /MT. Without this, the application cannot use any floating point * printf's. It also seems to be needed for Visual C 1.5 (win16) */ SSLeay_MSVC5_hack = (double)name[0] * (double)name[1]; #endif if ((app_locks == NULL) && ((app_locks = sk_OPENSSL_STRING_new_null()) == NULL)) { CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_LOCKID, ERR_R_MALLOC_FAILURE); return (0); } if ((str = BUF_strdup(name)) == NULL) { CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_LOCKID, ERR_R_MALLOC_FAILURE); return (0); } i = sk_OPENSSL_STRING_push(app_locks, str); if (!i) OPENSSL_free(str); else i += CRYPTO_NUM_LOCKS; /* gap of one :-) */ return (i); } int CRYPTO_num_locks(void) { return CRYPTO_NUM_LOCKS; } int CRYPTO_get_new_dynlockid(void) { int i = 0; CRYPTO_dynlock *pointer = NULL; if (dynlock_create_callback == NULL) { CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID, CRYPTO_R_NO_DYNLOCK_CREATE_CALLBACK); return (0); } CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK); if ((dyn_locks == NULL) && ((dyn_locks = sk_CRYPTO_dynlock_new_null()) == NULL)) { CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK); CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID, ERR_R_MALLOC_FAILURE); return (0); } CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK); pointer = (CRYPTO_dynlock *) OPENSSL_malloc(sizeof(CRYPTO_dynlock)); if (pointer == NULL) { CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID, ERR_R_MALLOC_FAILURE); return (0); } pointer->references = 1; pointer->data = dynlock_create_callback(__FILE__, __LINE__); if (pointer->data == NULL) { OPENSSL_free(pointer); CRYPTOerr(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID, ERR_R_MALLOC_FAILURE); return (0); } CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK); /* First, try to find an existing empty slot */ i = sk_CRYPTO_dynlock_find(dyn_locks, NULL); /* If there was none, push, thereby creating a new one */ if (i == -1) /* * Since sk_push() returns the number of items on the stack, not the * location of the pushed item, we need to transform the returned * number into a position, by decreasing it. */ i = sk_CRYPTO_dynlock_push(dyn_locks, pointer) - 1; else /* * If we found a place with a NULL pointer, put our pointer in it. */ (void)sk_CRYPTO_dynlock_set(dyn_locks, i, pointer); CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK); if (i == -1) { dynlock_destroy_callback(pointer->data, __FILE__, __LINE__); OPENSSL_free(pointer); } else i += 1; /* to avoid 0 */ return -i; } void CRYPTO_destroy_dynlockid(int i) { CRYPTO_dynlock *pointer = NULL; if (i) i = -i - 1; if (dynlock_destroy_callback == NULL) return; CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK); if (dyn_locks == NULL || i >= sk_CRYPTO_dynlock_num(dyn_locks)) { CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK); return; } pointer = sk_CRYPTO_dynlock_value(dyn_locks, i); if (pointer != NULL) { --pointer->references; #ifdef REF_CHECK if (pointer->references < 0) { fprintf(stderr, "CRYPTO_destroy_dynlockid, bad reference count\n"); abort(); } else #endif if (pointer->references <= 0) { (void)sk_CRYPTO_dynlock_set(dyn_locks, i, NULL); } else pointer = NULL; } CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK); if (pointer) { dynlock_destroy_callback(pointer->data, __FILE__, __LINE__); OPENSSL_free(pointer); } } struct CRYPTO_dynlock_value *CRYPTO_get_dynlock_value(int i) { CRYPTO_dynlock *pointer = NULL; if (i) i = -i - 1; CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK); if (dyn_locks != NULL && i < sk_CRYPTO_dynlock_num(dyn_locks)) pointer = sk_CRYPTO_dynlock_value(dyn_locks, i); if (pointer) pointer->references++; CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK); if (pointer) return pointer->data; return NULL; } struct CRYPTO_dynlock_value *(*CRYPTO_get_dynlock_create_callback(void)) (const char *file, int line) { return (dynlock_create_callback); } void (*CRYPTO_get_dynlock_lock_callback(void)) (int mode, struct CRYPTO_dynlock_value *l, const char *file, int line) { return (dynlock_lock_callback); } void (*CRYPTO_get_dynlock_destroy_callback(void)) (struct CRYPTO_dynlock_value *l, const char *file, int line) { return (dynlock_destroy_callback); } void CRYPTO_set_dynlock_create_callback(struct CRYPTO_dynlock_value *(*func) (const char *file, int line)) { dynlock_create_callback = func; } void CRYPTO_set_dynlock_lock_callback(void (*func) (int mode, struct CRYPTO_dynlock_value *l, const char *file, int line)) { dynlock_lock_callback = func; } void CRYPTO_set_dynlock_destroy_callback(void (*func) (struct CRYPTO_dynlock_value *l, const char *file, int line)) { dynlock_destroy_callback = func; } void (*CRYPTO_get_locking_callback(void)) (int mode, int type, const char *file, int line) { return (locking_callback); } int (*CRYPTO_get_add_lock_callback(void)) (int *num, int mount, int type, const char *file, int line) { return (add_lock_callback); } void CRYPTO_set_locking_callback(void (*func) (int mode, int type, const char *file, int line)) { /* * Calling this here ensures initialisation before any threads are * started. */ OPENSSL_init(); locking_callback = func; } void CRYPTO_set_add_lock_callback(int (*func) (int *num, int mount, int type, const char *file, int line)) { add_lock_callback = func; } /* * the memset() here and in set_pointer() seem overkill, but for the sake of * CRYPTO_THREADID_cmp() this avoids any platform silliness that might cause * two "equal" THREADID structs to not be memcmp()-identical. */ void CRYPTO_THREADID_set_numeric(CRYPTO_THREADID *id, unsigned long val) { memset(id, 0, sizeof(*id)); id->val = val; } static const unsigned char hash_coeffs[] = { 3, 5, 7, 11, 13, 17, 19, 23 }; void CRYPTO_THREADID_set_pointer(CRYPTO_THREADID *id, void *ptr) { unsigned char *dest = (void *)&id->val; unsigned int accum = 0; unsigned char dnum = sizeof(id->val); memset(id, 0, sizeof(*id)); id->ptr = ptr; if (sizeof(id->val) >= sizeof(id->ptr)) { /* * 'ptr' can be embedded in 'val' without loss of uniqueness */ id->val = (unsigned long)id->ptr; return; } /* * hash ptr ==> val. Each byte of 'val' gets the mod-256 total of a * linear function over the bytes in 'ptr', the co-efficients of which * are a sequence of low-primes (hash_coeffs is an 8-element cycle) - the * starting prime for the sequence varies for each byte of 'val' (unique * polynomials unless pointers are >64-bit). For added spice, the totals * accumulate rather than restarting from zero, and the index of the * 'val' byte is added each time (position dependence). If I was a * black-belt, I'd scan big-endian pointers in reverse to give low-order * bits more play, but this isn't crypto and I'd prefer nobody mistake it * as such. Plus I'm lazy. */ while (dnum--) { const unsigned char *src = (void *)&id->ptr; unsigned char snum = sizeof(id->ptr); while (snum--) accum += *(src++) * hash_coeffs[(snum + dnum) & 7]; accum += dnum; *(dest++) = accum & 255; } } +#ifdef OPENSSL_FIPS +extern int FIPS_crypto_threadid_set_callback(void (*func) (CRYPTO_THREADID *)); +#endif + int CRYPTO_THREADID_set_callback(void (*func) (CRYPTO_THREADID *)) { if (threadid_callback) return 0; threadid_callback = func; +#ifdef OPENSSL_FIPS + FIPS_crypto_threadid_set_callback(func); +#endif return 1; } void (*CRYPTO_THREADID_get_callback(void)) (CRYPTO_THREADID *) { return threadid_callback; } void CRYPTO_THREADID_current(CRYPTO_THREADID *id) { if (threadid_callback) { threadid_callback(id); return; } #ifndef OPENSSL_NO_DEPRECATED /* If the deprecated callback was set, fall back to that */ if (id_callback) { CRYPTO_THREADID_set_numeric(id, id_callback()); return; } #endif /* Else pick a backup */ #ifdef OPENSSL_SYS_WIN16 CRYPTO_THREADID_set_numeric(id, (unsigned long)GetCurrentTask()); #elif defined(OPENSSL_SYS_WIN32) CRYPTO_THREADID_set_numeric(id, (unsigned long)GetCurrentThreadId()); #elif defined(OPENSSL_SYS_BEOS) CRYPTO_THREADID_set_numeric(id, (unsigned long)find_thread(NULL)); #else /* For everything else, default to using the address of 'errno' */ CRYPTO_THREADID_set_pointer(id, (void *)&errno); #endif } int CRYPTO_THREADID_cmp(const CRYPTO_THREADID *a, const CRYPTO_THREADID *b) { return memcmp(a, b, sizeof(*a)); } void CRYPTO_THREADID_cpy(CRYPTO_THREADID *dest, const CRYPTO_THREADID *src) { memcpy(dest, src, sizeof(*src)); } unsigned long CRYPTO_THREADID_hash(const CRYPTO_THREADID *id) { return id->val; } #ifndef OPENSSL_NO_DEPRECATED unsigned long (*CRYPTO_get_id_callback(void)) (void) { return (id_callback); } void CRYPTO_set_id_callback(unsigned long (*func) (void)) { id_callback = func; } unsigned long CRYPTO_thread_id(void) { unsigned long ret = 0; if (id_callback == NULL) { # ifdef OPENSSL_SYS_WIN16 ret = (unsigned long)GetCurrentTask(); # elif defined(OPENSSL_SYS_WIN32) ret = (unsigned long)GetCurrentThreadId(); # elif defined(GETPID_IS_MEANINGLESS) ret = 1L; # elif defined(OPENSSL_SYS_BEOS) ret = (unsigned long)find_thread(NULL); # else ret = (unsigned long)getpid(); # endif } else ret = id_callback(); return (ret); } #endif void CRYPTO_lock(int mode, int type, const char *file, int line) { #ifdef LOCK_DEBUG { CRYPTO_THREADID id; char *rw_text, *operation_text; if (mode & CRYPTO_LOCK) operation_text = "lock "; else if (mode & CRYPTO_UNLOCK) operation_text = "unlock"; else operation_text = "ERROR "; if (mode & CRYPTO_READ) rw_text = "r"; else if (mode & CRYPTO_WRITE) rw_text = "w"; else rw_text = "ERROR"; CRYPTO_THREADID_current(&id); fprintf(stderr, "lock:%08lx:(%s)%s %-18s %s:%d\n", CRYPTO_THREADID_hash(&id), rw_text, operation_text, CRYPTO_get_lock_name(type), file, line); } #endif if (type < 0) { if (dynlock_lock_callback != NULL) { struct CRYPTO_dynlock_value *pointer = CRYPTO_get_dynlock_value(type); OPENSSL_assert(pointer != NULL); dynlock_lock_callback(mode, pointer, file, line); CRYPTO_destroy_dynlockid(type); } } else if (locking_callback != NULL) locking_callback(mode, type, file, line); } int CRYPTO_add_lock(int *pointer, int amount, int type, const char *file, int line) { int ret = 0; if (add_lock_callback != NULL) { #ifdef LOCK_DEBUG int before = *pointer; #endif ret = add_lock_callback(pointer, amount, type, file, line); #ifdef LOCK_DEBUG { CRYPTO_THREADID id; CRYPTO_THREADID_current(&id); fprintf(stderr, "ladd:%08lx:%2d+%2d->%2d %-18s %s:%d\n", CRYPTO_THREADID_hash(&id), before, amount, ret, CRYPTO_get_lock_name(type), file, line); } #endif } else { CRYPTO_lock(CRYPTO_LOCK | CRYPTO_WRITE, type, file, line); ret = *pointer + amount; #ifdef LOCK_DEBUG { CRYPTO_THREADID id; CRYPTO_THREADID_current(&id); fprintf(stderr, "ladd:%08lx:%2d+%2d->%2d %-18s %s:%d\n", CRYPTO_THREADID_hash(&id), *pointer, amount, ret, CRYPTO_get_lock_name(type), file, line); } #endif *pointer = ret; CRYPTO_lock(CRYPTO_UNLOCK | CRYPTO_WRITE, type, file, line); } return (ret); } const char *CRYPTO_get_lock_name(int type) { if (type < 0) return ("dynamic"); else if (type < CRYPTO_NUM_LOCKS) return (lock_names[type]); else if (type - CRYPTO_NUM_LOCKS > sk_OPENSSL_STRING_num(app_locks)) return ("ERROR"); else return (sk_OPENSSL_STRING_value(app_locks, type - CRYPTO_NUM_LOCKS)); } #if defined(__i386) || defined(__i386__) || defined(_M_IX86) || \ defined(__INTEL__) || \ defined(__x86_64) || defined(__x86_64__) || \ defined(_M_AMD64) || defined(_M_X64) extern unsigned int OPENSSL_ia32cap_P[4]; unsigned long *OPENSSL_ia32cap_loc(void) { if (sizeof(long) == 4) /* * If 32-bit application pulls address of OPENSSL_ia32cap_P[0] * clear second element to maintain the illusion that vector * is 32-bit. */ OPENSSL_ia32cap_P[1] = 0; OPENSSL_ia32cap_P[2] = 0; return (unsigned long *)OPENSSL_ia32cap_P; } # if defined(OPENSSL_CPUID_OBJ) && !defined(OPENSSL_NO_ASM) && !defined(I386_ONLY) # define OPENSSL_CPUID_SETUP # if defined(_WIN32) typedef unsigned __int64 IA32CAP; # else typedef unsigned long long IA32CAP; # endif void OPENSSL_cpuid_setup(void) { static int trigger = 0; IA32CAP OPENSSL_ia32_cpuid(unsigned int *); IA32CAP vec; char *env; if (trigger) return; trigger = 1; if ((env = getenv("OPENSSL_ia32cap"))) { int off = (env[0] == '~') ? 1 : 0; # if defined(_WIN32) if (!sscanf(env + off, "%I64i", &vec)) vec = strtoul(env + off, NULL, 0); # else if (!sscanf(env + off, "%lli", (long long *)&vec)) vec = strtoul(env + off, NULL, 0); # endif if (off) vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P) & ~vec; else if (env[0] == ':') vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P); OPENSSL_ia32cap_P[2] = 0; if ((env = strchr(env, ':'))) { unsigned int vecx; env++; off = (env[0] == '~') ? 1 : 0; vecx = strtoul(env + off, NULL, 0); if (off) OPENSSL_ia32cap_P[2] &= ~vecx; else OPENSSL_ia32cap_P[2] = vecx; } } else vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P); /* * |(1<<10) sets a reserved bit to signal that variable * was initialized already... This is to avoid interference * with cpuid snippets in ELF .init segment. */ OPENSSL_ia32cap_P[0] = (unsigned int)vec | (1 << 10); OPENSSL_ia32cap_P[1] = (unsigned int)(vec >> 32); } # else unsigned int OPENSSL_ia32cap_P[4]; # endif #else unsigned long *OPENSSL_ia32cap_loc(void) { return NULL; } #endif int OPENSSL_NONPIC_relocated = 0; #if !defined(OPENSSL_CPUID_SETUP) && !defined(OPENSSL_CPUID_OBJ) void OPENSSL_cpuid_setup(void) { } #endif #if (defined(_WIN32) || defined(__CYGWIN__)) && defined(_WINDLL) # ifdef __CYGWIN__ /* pick DLL_[PROCESS|THREAD]_[ATTACH|DETACH] definitions */ # include /* * this has side-effect of _WIN32 getting defined, which otherwise is * mutually exclusive with __CYGWIN__... */ # endif /* * All we really need to do is remove the 'error' state when a thread * detaches */ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH: OPENSSL_cpuid_setup(); # if defined(_WIN32_WINNT) { IMAGE_DOS_HEADER *dos_header = (IMAGE_DOS_HEADER *) hinstDLL; IMAGE_NT_HEADERS *nt_headers; if (dos_header->e_magic == IMAGE_DOS_SIGNATURE) { nt_headers = (IMAGE_NT_HEADERS *) ((char *)dos_header + dos_header->e_lfanew); if (nt_headers->Signature == IMAGE_NT_SIGNATURE && hinstDLL != (HINSTANCE) (nt_headers->OptionalHeader.ImageBase)) OPENSSL_NONPIC_relocated = 1; } } # endif break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: break; } return (TRUE); } #endif #if defined(_WIN32) && !defined(__CYGWIN__) # include # include # ifdef __WATCOMC__ # if defined(_UNICODE) || defined(__UNICODE__) # define _vsntprintf _vsnwprintf # else # define _vsntprintf _vsnprintf # endif # endif # ifdef _MSC_VER # define alloca _alloca # endif # if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333 int OPENSSL_isservice(void) { HWINSTA h; DWORD len; WCHAR *name; static union { void *p; int (*f) (void); } _OPENSSL_isservice = { NULL }; if (_OPENSSL_isservice.p == NULL) { HANDLE h = GetModuleHandle(NULL); if (h != NULL) _OPENSSL_isservice.p = GetProcAddress(h, "_OPENSSL_isservice"); if (_OPENSSL_isservice.p == NULL) _OPENSSL_isservice.p = (void *)-1; } if (_OPENSSL_isservice.p != (void *)-1) return (*_OPENSSL_isservice.f) (); h = GetProcessWindowStation(); if (h == NULL) return -1; if (GetUserObjectInformationW(h, UOI_NAME, NULL, 0, &len) || GetLastError() != ERROR_INSUFFICIENT_BUFFER) return -1; if (len > 512) return -1; /* paranoia */ len++, len &= ~1; /* paranoia */ name = (WCHAR *)alloca(len + sizeof(WCHAR)); if (!GetUserObjectInformationW(h, UOI_NAME, name, len, &len)) return -1; len++, len &= ~1; /* paranoia */ name[len / sizeof(WCHAR)] = L'\0'; /* paranoia */ # if 1 /* * This doesn't cover "interactive" services [working with real * WinSta0's] nor programs started non-interactively by Task Scheduler * [those are working with SAWinSta]. */ if (wcsstr(name, L"Service-0x")) return 1; # else /* This covers all non-interactive programs such as services. */ if (!wcsstr(name, L"WinSta0")) return 1; # endif else return 0; } # else int OPENSSL_isservice(void) { return 0; } # endif void OPENSSL_showfatal(const char *fmta, ...) { va_list ap; TCHAR buf[256]; const TCHAR *fmt; # ifdef STD_ERROR_HANDLE /* what a dirty trick! */ HANDLE h; if ((h = GetStdHandle(STD_ERROR_HANDLE)) != NULL && GetFileType(h) != FILE_TYPE_UNKNOWN) { /* must be console application */ int len; DWORD out; va_start(ap, fmta); len = _vsnprintf((char *)buf, sizeof(buf), fmta, ap); WriteFile(h, buf, len < 0 ? sizeof(buf) : (DWORD) len, &out, NULL); va_end(ap); return; } # endif if (sizeof(TCHAR) == sizeof(char)) fmt = (const TCHAR *)fmta; else do { int keepgoing; size_t len_0 = strlen(fmta) + 1, i; WCHAR *fmtw; fmtw = (WCHAR *)alloca(len_0 * sizeof(WCHAR)); if (fmtw == NULL) { fmt = (const TCHAR *)L"no stack?"; break; } # ifndef OPENSSL_NO_MULTIBYTE if (!MultiByteToWideChar(CP_ACP, 0, fmta, len_0, fmtw, len_0)) # endif for (i = 0; i < len_0; i++) fmtw[i] = (WCHAR)fmta[i]; for (i = 0; i < len_0; i++) { if (fmtw[i] == L'%') do { keepgoing = 0; switch (fmtw[i + 1]) { case L'0': case L'1': case L'2': case L'3': case L'4': case L'5': case L'6': case L'7': case L'8': case L'9': case L'.': case L'*': case L'-': i++; keepgoing = 1; break; case L's': fmtw[i + 1] = L'S'; break; case L'S': fmtw[i + 1] = L's'; break; case L'c': fmtw[i + 1] = L'C'; break; case L'C': fmtw[i + 1] = L'c'; break; } } while (keepgoing); } fmt = (const TCHAR *)fmtw; } while (0); va_start(ap, fmta); _vsntprintf(buf, sizeof(buf) / sizeof(TCHAR) - 1, fmt, ap); buf[sizeof(buf) / sizeof(TCHAR) - 1] = _T('\0'); va_end(ap); # if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333 /* this -------------v--- guards NT-specific calls */ if (check_winnt() && OPENSSL_isservice() > 0) { HANDLE hEventLog = RegisterEventSource(NULL, _T("OpenSSL")); if (hEventLog != NULL) { const TCHAR *pmsg = buf; if (!ReportEvent(hEventLog, EVENTLOG_ERROR_TYPE, 0, 0, NULL, 1, 0, &pmsg, NULL)) { #if defined(DEBUG) /* * We are in a situation where we tried to report a critical * error and this failed for some reason. As a last resort, * in debug builds, send output to the debugger or any other * tool like DebugView which can monitor the output. */ OutputDebugString(pmsg); #endif } (void)DeregisterEventSource(hEventLog); } } else # endif MessageBox(NULL, buf, _T("OpenSSL: FATAL"), MB_OK | MB_ICONERROR); } #else void OPENSSL_showfatal(const char *fmta, ...) { va_list ap; va_start(ap, fmta); vfprintf(stderr, fmta, ap); va_end(ap); } int OPENSSL_isservice(void) { return 0; } #endif void OpenSSLDie(const char *file, int line, const char *assertion) { OPENSSL_showfatal ("%s(%d): OpenSSL internal error, assertion failed: %s\n", file, line, assertion); #if !defined(_WIN32) || defined(__CYGWIN__) abort(); #else /* * Win32 abort() customarily shows a dialog, but we just did that... */ # if !defined(_WIN32_WCE) raise(SIGABRT); # endif _exit(3); #endif } void *OPENSSL_stderr(void) { return stderr; } int CRYPTO_memcmp(const volatile void *in_a, const volatile void *in_b, size_t len) { size_t i; const volatile unsigned char *a = in_a; const volatile unsigned char *b = in_b; unsigned char x = 0; for (i = 0; i < len; i++) x |= a[i] ^ b[i]; return x; } Index: vendor-crypto/openssl/dist/crypto/dh/Makefile =================================================================== --- vendor-crypto/openssl/dist/crypto/dh/Makefile (revision 325325) +++ vendor-crypto/openssl/dist/crypto/dh/Makefile (revision 325326) @@ -1,204 +1,204 @@ # # OpenSSL/crypto/dh/Makefile # DIR= dh TOP= ../.. CC= cc INCLUDES= -I.. -I$(TOP) -I../../include CFLAG=-g MAKEFILE= Makefile AR= ar r CFLAGS= $(INCLUDES) $(CFLAG) GENERAL=Makefile TEST= dhtest.c APPS= LIB=$(TOP)/libcrypto.a LIBSRC= dh_asn1.c dh_gen.c dh_key.c dh_lib.c dh_check.c dh_err.c dh_depr.c \ dh_ameth.c dh_pmeth.c dh_prn.c dh_rfc5114.c dh_kdf.c LIBOBJ= dh_asn1.o dh_gen.o dh_key.o dh_lib.o dh_check.o dh_err.o dh_depr.o \ dh_ameth.o dh_pmeth.o dh_prn.o dh_rfc5114.o dh_kdf.o SRC= $(LIBSRC) EXHEADER= dh.h HEADER= $(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 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 *.o */*.o *.obj lib tags core .pure .nfs* *.old *.bak fluff # DO NOT DELETE THIS LINE -- make depend depends on it. dh_ameth.o: ../../e_os.h ../../include/openssl/asn1.h dh_ameth.o: ../../include/openssl/bio.h ../../include/openssl/bn.h dh_ameth.o: ../../include/openssl/buffer.h ../../include/openssl/cms.h dh_ameth.o: ../../include/openssl/crypto.h ../../include/openssl/dh.h dh_ameth.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h dh_ameth.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h dh_ameth.o: ../../include/openssl/err.h ../../include/openssl/evp.h dh_ameth.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h dh_ameth.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h dh_ameth.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h dh_ameth.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h dh_ameth.o: ../../include/openssl/sha.h ../../include/openssl/stack.h dh_ameth.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h dh_ameth.o: ../../include/openssl/x509_vfy.h ../asn1/asn1_locl.h ../cryptlib.h dh_ameth.o: dh_ameth.c dh_asn1.o: ../../e_os.h ../../include/openssl/asn1.h dh_asn1.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h dh_asn1.o: ../../include/openssl/bn.h ../../include/openssl/buffer.h dh_asn1.o: ../../include/openssl/crypto.h ../../include/openssl/dh.h dh_asn1.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h dh_asn1.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h dh_asn1.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h dh_asn1.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h dh_asn1.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h dh_asn1.o: ../../include/openssl/symhacks.h ../cryptlib.h dh_asn1.c dh_check.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h dh_check.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h dh_check.o: ../../include/openssl/dh.h ../../include/openssl/e_os2.h dh_check.o: ../../include/openssl/err.h ../../include/openssl/lhash.h dh_check.o: ../../include/openssl/opensslconf.h dh_check.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h dh_check.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h dh_check.o: ../../include/openssl/symhacks.h ../cryptlib.h dh_check.c dh_depr.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h dh_depr.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h dh_depr.o: ../../include/openssl/dh.h ../../include/openssl/e_os2.h dh_depr.o: ../../include/openssl/err.h ../../include/openssl/lhash.h dh_depr.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h dh_depr.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h dh_depr.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h dh_depr.o: ../cryptlib.h dh_depr.c dh_err.o: ../../include/openssl/bio.h ../../include/openssl/crypto.h dh_err.o: ../../include/openssl/dh.h ../../include/openssl/e_os2.h dh_err.o: ../../include/openssl/err.h ../../include/openssl/lhash.h dh_err.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h dh_err.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h dh_err.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h dh_err.o: dh_err.c dh_gen.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h dh_gen.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h dh_gen.o: ../../include/openssl/dh.h ../../include/openssl/e_os2.h dh_gen.o: ../../include/openssl/err.h ../../include/openssl/lhash.h dh_gen.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h dh_gen.o: ../../include/openssl/ossl_typ.h ../../include/openssl/safestack.h dh_gen.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h dh_gen.o: ../cryptlib.h dh_gen.c -dh_kdf.o: ../../include/openssl/asn1.h ../../include/openssl/bio.h +dh_kdf.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h dh_kdf.o: ../../include/openssl/buffer.h ../../include/openssl/cms.h dh_kdf.o: ../../include/openssl/crypto.h ../../include/openssl/dh.h dh_kdf.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h dh_kdf.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h dh_kdf.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h dh_kdf.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h dh_kdf.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h dh_kdf.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h dh_kdf.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h dh_kdf.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h dh_kdf.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h dh_kdf.o: dh_kdf.c dh_key.o: ../../e_os.h ../../include/openssl/bio.h ../../include/openssl/bn.h dh_key.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h dh_key.o: ../../include/openssl/dh.h ../../include/openssl/e_os2.h dh_key.o: ../../include/openssl/err.h ../../include/openssl/lhash.h dh_key.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h dh_key.o: ../../include/openssl/ossl_typ.h ../../include/openssl/rand.h dh_key.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h dh_key.o: ../../include/openssl/symhacks.h ../cryptlib.h dh_key.c dh_lib.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h dh_lib.o: ../../include/openssl/bn.h ../../include/openssl/buffer.h dh_lib.o: ../../include/openssl/crypto.h ../../include/openssl/dh.h dh_lib.o: ../../include/openssl/e_os2.h ../../include/openssl/ec.h dh_lib.o: ../../include/openssl/ecdh.h ../../include/openssl/ecdsa.h dh_lib.o: ../../include/openssl/engine.h ../../include/openssl/err.h dh_lib.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h dh_lib.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h dh_lib.o: ../../include/openssl/opensslconf.h ../../include/openssl/opensslv.h dh_lib.o: ../../include/openssl/ossl_typ.h ../../include/openssl/pkcs7.h dh_lib.o: ../../include/openssl/safestack.h ../../include/openssl/sha.h dh_lib.o: ../../include/openssl/stack.h ../../include/openssl/symhacks.h dh_lib.o: ../../include/openssl/x509.h ../../include/openssl/x509_vfy.h dh_lib.o: ../cryptlib.h dh_lib.c dh_pmeth.o: ../../e_os.h ../../include/openssl/asn1.h dh_pmeth.o: ../../include/openssl/asn1t.h ../../include/openssl/bio.h dh_pmeth.o: ../../include/openssl/bn.h ../../include/openssl/buffer.h dh_pmeth.o: ../../include/openssl/crypto.h ../../include/openssl/dh.h dh_pmeth.o: ../../include/openssl/dsa.h ../../include/openssl/e_os2.h dh_pmeth.o: ../../include/openssl/ec.h ../../include/openssl/ecdh.h dh_pmeth.o: ../../include/openssl/ecdsa.h ../../include/openssl/err.h dh_pmeth.o: ../../include/openssl/evp.h ../../include/openssl/lhash.h dh_pmeth.o: ../../include/openssl/obj_mac.h ../../include/openssl/objects.h dh_pmeth.o: ../../include/openssl/opensslconf.h dh_pmeth.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h dh_pmeth.o: ../../include/openssl/pkcs7.h ../../include/openssl/safestack.h dh_pmeth.o: ../../include/openssl/sha.h ../../include/openssl/stack.h dh_pmeth.o: ../../include/openssl/symhacks.h ../../include/openssl/x509.h dh_pmeth.o: ../../include/openssl/x509_vfy.h ../cryptlib.h ../evp/evp_locl.h dh_pmeth.o: dh_pmeth.c dh_prn.o: ../../e_os.h ../../include/openssl/asn1.h ../../include/openssl/bio.h dh_prn.o: ../../include/openssl/buffer.h ../../include/openssl/crypto.h dh_prn.o: ../../include/openssl/dh.h ../../include/openssl/e_os2.h dh_prn.o: ../../include/openssl/err.h ../../include/openssl/evp.h dh_prn.o: ../../include/openssl/lhash.h ../../include/openssl/obj_mac.h dh_prn.o: ../../include/openssl/objects.h ../../include/openssl/opensslconf.h dh_prn.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h dh_prn.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h dh_prn.o: ../../include/openssl/symhacks.h ../cryptlib.h dh_prn.c dh_rfc5114.o: ../../e_os.h ../../include/openssl/bio.h dh_rfc5114.o: ../../include/openssl/bn.h ../../include/openssl/buffer.h dh_rfc5114.o: ../../include/openssl/crypto.h ../../include/openssl/dh.h dh_rfc5114.o: ../../include/openssl/e_os2.h ../../include/openssl/err.h dh_rfc5114.o: ../../include/openssl/lhash.h ../../include/openssl/opensslconf.h dh_rfc5114.o: ../../include/openssl/opensslv.h ../../include/openssl/ossl_typ.h dh_rfc5114.o: ../../include/openssl/safestack.h ../../include/openssl/stack.h dh_rfc5114.o: ../../include/openssl/symhacks.h ../cryptlib.h dh_rfc5114.c Index: vendor-crypto/openssl/dist/crypto/dh/dh.h =================================================================== --- vendor-crypto/openssl/dist/crypto/dh/dh.h (revision 325325) +++ vendor-crypto/openssl/dist/crypto/dh/dh.h (revision 325326) @@ -1,410 +1,412 @@ /* 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_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); +# ifndef OPENSSL_NO_CMS /* 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); +# endif # 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/dh/dh_kdf.c =================================================================== --- vendor-crypto/openssl/dist/crypto/dh/dh_kdf.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/dh/dh_kdf.c (revision 325326) @@ -1,187 +1,191 @@ /* crypto/dh/dh_kdf.c */ /* * Written by Stephen Henson for the OpenSSL project. */ /* ==================================================================== * Copyright (c) 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 * 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_CMS #include #include #include #include #include /* Key derivation from X9.42/RFC2631 */ #define DH_KDF_MAX (1L << 30) /* Skip past an ASN1 structure: for OBJECT skip content octets too */ static int skip_asn1(unsigned char **pp, long *plen, int exptag) { const unsigned char *q = *pp; int i, tag, xclass; long tmplen; i = ASN1_get_object(&q, &tmplen, &tag, &xclass, *plen); if (i & 0x80) return 0; if (tag != exptag || xclass != V_ASN1_UNIVERSAL) return 0; if (tag == V_ASN1_OBJECT) q += tmplen; *plen -= q - *pp; *pp = (unsigned char *)q; return 1; } /* * Encode the DH shared info structure, return an offset to the counter value * so we can update the structure without reencoding it. */ static int dh_sharedinfo_encode(unsigned char **pder, unsigned char **pctr, ASN1_OBJECT *key_oid, size_t outlen, const unsigned char *ukm, size_t ukmlen) { unsigned char *p; int derlen; long tlen; /* "magic" value to check offset is sane */ static unsigned char ctr[4] = { 0xF3, 0x17, 0x22, 0x53 }; X509_ALGOR atmp; ASN1_OCTET_STRING ctr_oct, ukm_oct, *pukm_oct; ASN1_TYPE ctr_atype; if (ukmlen > DH_KDF_MAX || outlen > DH_KDF_MAX) return 0; ctr_oct.data = ctr; ctr_oct.length = 4; ctr_oct.flags = 0; ctr_oct.type = V_ASN1_OCTET_STRING; ctr_atype.type = V_ASN1_OCTET_STRING; ctr_atype.value.octet_string = &ctr_oct; atmp.algorithm = key_oid; atmp.parameter = &ctr_atype; if (ukm) { ukm_oct.type = V_ASN1_OCTET_STRING; ukm_oct.flags = 0; ukm_oct.data = (unsigned char *)ukm; ukm_oct.length = ukmlen; pukm_oct = &ukm_oct; } else pukm_oct = NULL; derlen = CMS_SharedInfo_encode(pder, &atmp, pukm_oct, outlen); if (derlen <= 0) return 0; p = *pder; tlen = derlen; if (!skip_asn1(&p, &tlen, V_ASN1_SEQUENCE)) return 0; if (!skip_asn1(&p, &tlen, V_ASN1_SEQUENCE)) return 0; if (!skip_asn1(&p, &tlen, V_ASN1_OBJECT)) return 0; if (!skip_asn1(&p, &tlen, V_ASN1_OCTET_STRING)) return 0; if (CRYPTO_memcmp(p, ctr, 4)) return 0; *pctr = p; return derlen; } 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) { EVP_MD_CTX mctx; int rv = 0; unsigned int i; size_t mdlen; unsigned char *der = NULL, *ctr; int derlen; if (Zlen > DH_KDF_MAX) return 0; mdlen = EVP_MD_size(md); EVP_MD_CTX_init(&mctx); derlen = dh_sharedinfo_encode(&der, &ctr, key_oid, outlen, ukm, ukmlen); if (derlen == 0) goto err; for (i = 1;; i++) { unsigned char mtmp[EVP_MAX_MD_SIZE]; EVP_DigestInit_ex(&mctx, md, NULL); if (!EVP_DigestUpdate(&mctx, Z, Zlen)) goto err; ctr[3] = i & 0xFF; ctr[2] = (i >> 8) & 0xFF; ctr[1] = (i >> 16) & 0xFF; ctr[0] = (i >> 24) & 0xFF; if (!EVP_DigestUpdate(&mctx, der, derlen)) goto err; if (outlen >= mdlen) { if (!EVP_DigestFinal(&mctx, out, NULL)) goto err; outlen -= mdlen; if (outlen == 0) break; out += mdlen; } else { if (!EVP_DigestFinal(&mctx, mtmp, NULL)) goto err; memcpy(out, mtmp, outlen); OPENSSL_cleanse(mtmp, mdlen); break; } } rv = 1; err: if (der) OPENSSL_free(der); EVP_MD_CTX_cleanup(&mctx); return rv; } +#endif Index: vendor-crypto/openssl/dist/crypto/dh/dh_pmeth.c =================================================================== --- vendor-crypto/openssl/dist/crypto/dh/dh_pmeth.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/dh/dh_pmeth.c (revision 325326) @@ -1,551 +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 #include "cryptlib.h" #include #include #include #include #include #ifndef OPENSSL_NO_DSA # include #endif #include #include "evp_locl.h" /* DH pkey context structure */ typedef struct { /* Parameter gen parameters */ int prime_len; int generator; int use_dsa; int subprime_len; /* message digest used for parameter generation */ const EVP_MD *md; int rfc5114_param; /* Keygen callback info */ int gentmp[2]; /* KDF (if any) to use for DH */ char kdf_type; /* OID to use for KDF */ ASN1_OBJECT *kdf_oid; /* Message digest to use for key derivation */ const EVP_MD *kdf_md; /* User key material */ unsigned char *kdf_ukm; size_t kdf_ukmlen; /* KDF output length */ size_t kdf_outlen; } DH_PKEY_CTX; static int pkey_dh_init(EVP_PKEY_CTX *ctx) { DH_PKEY_CTX *dctx; dctx = OPENSSL_malloc(sizeof(DH_PKEY_CTX)); if (!dctx) return 0; dctx->prime_len = 1024; dctx->subprime_len = -1; dctx->generator = 2; dctx->use_dsa = 0; dctx->md = NULL; dctx->rfc5114_param = 0; dctx->kdf_type = EVP_PKEY_DH_KDF_NONE; dctx->kdf_oid = NULL; dctx->kdf_md = NULL; dctx->kdf_ukm = NULL; dctx->kdf_ukmlen = 0; dctx->kdf_outlen = 0; ctx->data = dctx; ctx->keygen_info = dctx->gentmp; ctx->keygen_info_count = 2; return 1; } static int pkey_dh_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { DH_PKEY_CTX *dctx, *sctx; if (!pkey_dh_init(dst)) return 0; sctx = src->data; dctx = dst->data; dctx->prime_len = sctx->prime_len; dctx->subprime_len = sctx->subprime_len; dctx->generator = sctx->generator; dctx->use_dsa = sctx->use_dsa; dctx->md = sctx->md; dctx->rfc5114_param = sctx->rfc5114_param; dctx->kdf_type = sctx->kdf_type; dctx->kdf_oid = OBJ_dup(sctx->kdf_oid); if (!dctx->kdf_oid) return 0; dctx->kdf_md = sctx->kdf_md; if (dctx->kdf_ukm) { dctx->kdf_ukm = BUF_memdup(sctx->kdf_ukm, sctx->kdf_ukmlen); dctx->kdf_ukmlen = sctx->kdf_ukmlen; } dctx->kdf_outlen = sctx->kdf_outlen; return 1; } static void pkey_dh_cleanup(EVP_PKEY_CTX *ctx) { DH_PKEY_CTX *dctx = ctx->data; if (dctx) { if (dctx->kdf_ukm) OPENSSL_free(dctx->kdf_ukm); if (dctx->kdf_oid) ASN1_OBJECT_free(dctx->kdf_oid); OPENSSL_free(dctx); } } static int pkey_dh_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { DH_PKEY_CTX *dctx = ctx->data; switch (type) { case EVP_PKEY_CTRL_DH_PARAMGEN_PRIME_LEN: if (p1 < 256) return -2; dctx->prime_len = p1; return 1; case EVP_PKEY_CTRL_DH_PARAMGEN_SUBPRIME_LEN: if (dctx->use_dsa == 0) return -2; dctx->subprime_len = p1; return 1; case EVP_PKEY_CTRL_DH_PARAMGEN_GENERATOR: if (dctx->use_dsa) return -2; dctx->generator = p1; return 1; case EVP_PKEY_CTRL_DH_PARAMGEN_TYPE: #ifdef OPENSSL_NO_DSA if (p1 != 0) return -2; #else if (p1 < 0 || p1 > 2) return -2; #endif dctx->use_dsa = p1; return 1; case EVP_PKEY_CTRL_DH_RFC5114: if (p1 < 1 || p1 > 3) return -2; dctx->rfc5114_param = p1; return 1; case EVP_PKEY_CTRL_PEER_KEY: /* Default behaviour is OK */ return 1; case EVP_PKEY_CTRL_DH_KDF_TYPE: if (p1 == -2) return dctx->kdf_type; +#ifdef OPENSSL_NO_CMS + if (p1 != EVP_PKEY_DH_KDF_NONE) +#else if (p1 != EVP_PKEY_DH_KDF_NONE && p1 != EVP_PKEY_DH_KDF_X9_42) +#endif return -2; dctx->kdf_type = p1; return 1; case EVP_PKEY_CTRL_DH_KDF_MD: dctx->kdf_md = p2; return 1; case EVP_PKEY_CTRL_GET_DH_KDF_MD: *(const EVP_MD **)p2 = dctx->kdf_md; return 1; case EVP_PKEY_CTRL_DH_KDF_OUTLEN: if (p1 <= 0) return -2; dctx->kdf_outlen = (size_t)p1; return 1; case EVP_PKEY_CTRL_GET_DH_KDF_OUTLEN: *(int *)p2 = dctx->kdf_outlen; return 1; case EVP_PKEY_CTRL_DH_KDF_UKM: if (dctx->kdf_ukm) OPENSSL_free(dctx->kdf_ukm); dctx->kdf_ukm = p2; if (p2) dctx->kdf_ukmlen = p1; else dctx->kdf_ukmlen = 0; return 1; case EVP_PKEY_CTRL_GET_DH_KDF_UKM: *(unsigned char **)p2 = dctx->kdf_ukm; return dctx->kdf_ukmlen; case EVP_PKEY_CTRL_DH_KDF_OID: if (dctx->kdf_oid) ASN1_OBJECT_free(dctx->kdf_oid); dctx->kdf_oid = p2; return 1; case EVP_PKEY_CTRL_GET_DH_KDF_OID: *(ASN1_OBJECT **)p2 = dctx->kdf_oid; return 1; default: return -2; } } static int pkey_dh_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, const char *value) { if (!strcmp(type, "dh_paramgen_prime_len")) { int len; len = atoi(value); return EVP_PKEY_CTX_set_dh_paramgen_prime_len(ctx, len); } if (!strcmp(type, "dh_rfc5114")) { DH_PKEY_CTX *dctx = ctx->data; int len; len = atoi(value); if (len < 0 || len > 3) return -2; dctx->rfc5114_param = len; return 1; } if (!strcmp(type, "dh_paramgen_generator")) { int len; len = atoi(value); return EVP_PKEY_CTX_set_dh_paramgen_generator(ctx, len); } if (!strcmp(type, "dh_paramgen_subprime_len")) { int len; len = atoi(value); return EVP_PKEY_CTX_set_dh_paramgen_subprime_len(ctx, len); } if (!strcmp(type, "dh_paramgen_type")) { int typ; typ = atoi(value); return EVP_PKEY_CTX_set_dh_paramgen_type(ctx, typ); } return -2; } #ifndef OPENSSL_NO_DSA extern int dsa_builtin_paramgen(DSA *ret, size_t bits, size_t qbits, const EVP_MD *evpmd, const unsigned char *seed_in, size_t seed_len, unsigned char *seed_out, int *counter_ret, unsigned long *h_ret, BN_GENCB *cb); extern int dsa_builtin_paramgen2(DSA *ret, size_t L, size_t N, const EVP_MD *evpmd, const unsigned char *seed_in, size_t seed_len, int idx, unsigned char *seed_out, int *counter_ret, unsigned long *h_ret, BN_GENCB *cb); static DSA *dsa_dh_generate(DH_PKEY_CTX *dctx, BN_GENCB *pcb) { DSA *ret; int rv = 0; int prime_len = dctx->prime_len; int subprime_len = dctx->subprime_len; const EVP_MD *md = dctx->md; if (dctx->use_dsa > 2) return NULL; ret = DSA_new(); if (!ret) return NULL; if (subprime_len == -1) { if (prime_len >= 2048) subprime_len = 256; else subprime_len = 160; } if (md == NULL) { if (prime_len >= 2048) md = EVP_sha256(); else md = EVP_sha1(); } if (dctx->use_dsa == 1) rv = dsa_builtin_paramgen(ret, prime_len, subprime_len, md, NULL, 0, NULL, NULL, NULL, pcb); else if (dctx->use_dsa == 2) rv = dsa_builtin_paramgen2(ret, prime_len, subprime_len, md, NULL, 0, -1, NULL, NULL, NULL, pcb); if (rv <= 0) { DSA_free(ret); return NULL; } return ret; } #endif static int pkey_dh_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { DH *dh = NULL; DH_PKEY_CTX *dctx = ctx->data; BN_GENCB *pcb, cb; int ret; if (dctx->rfc5114_param) { switch (dctx->rfc5114_param) { case 1: dh = DH_get_1024_160(); break; case 2: dh = DH_get_2048_224(); break; case 3: dh = DH_get_2048_256(); break; default: return -2; } EVP_PKEY_assign(pkey, EVP_PKEY_DHX, dh); return 1; } if (ctx->pkey_gencb) { pcb = &cb; evp_pkey_set_cb_translate(pcb, ctx); } else pcb = NULL; #ifndef OPENSSL_NO_DSA if (dctx->use_dsa) { DSA *dsa_dh; dsa_dh = dsa_dh_generate(dctx, pcb); if (!dsa_dh) return 0; dh = DSA_dup_DH(dsa_dh); DSA_free(dsa_dh); if (!dh) return 0; EVP_PKEY_assign(pkey, EVP_PKEY_DHX, dh); return 1; } #endif dh = DH_new(); if (!dh) return 0; ret = DH_generate_parameters_ex(dh, dctx->prime_len, dctx->generator, pcb); if (ret) EVP_PKEY_assign_DH(pkey, dh); else DH_free(dh); return ret; } static int pkey_dh_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { DH *dh = NULL; if (ctx->pkey == NULL) { DHerr(DH_F_PKEY_DH_KEYGEN, DH_R_NO_PARAMETERS_SET); return 0; } dh = DH_new(); if (!dh) return 0; EVP_PKEY_assign(pkey, ctx->pmeth->pkey_id, dh); /* Note: if error return, pkey is freed by parent routine */ if (!EVP_PKEY_copy_parameters(pkey, ctx->pkey)) return 0; return DH_generate_key(pkey->pkey.dh); } static int pkey_dh_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen) { int ret; DH *dh; DH_PKEY_CTX *dctx = ctx->data; BIGNUM *dhpub; if (!ctx->pkey || !ctx->peerkey) { DHerr(DH_F_PKEY_DH_DERIVE, DH_R_KEYS_NOT_SET); return 0; } dh = ctx->pkey->pkey.dh; dhpub = ctx->peerkey->pkey.dh->pub_key; if (dctx->kdf_type == EVP_PKEY_DH_KDF_NONE) { if (key == NULL) { *keylen = DH_size(dh); return 1; } ret = DH_compute_key(key, dhpub, dh); if (ret < 0) return ret; *keylen = ret; return 1; - } else if (dctx->kdf_type == EVP_PKEY_DH_KDF_X9_42) { + } +#ifndef OPENSSL_NO_CMS + else if (dctx->kdf_type == EVP_PKEY_DH_KDF_X9_42) { unsigned char *Z = NULL; size_t Zlen = 0; if (!dctx->kdf_outlen || !dctx->kdf_oid) return 0; if (key == NULL) { *keylen = dctx->kdf_outlen; return 1; } if (*keylen != dctx->kdf_outlen) return 0; ret = 0; Zlen = DH_size(dh); Z = OPENSSL_malloc(Zlen); if (!Z) { goto err; } if (DH_compute_key_padded(Z, dhpub, dh) <= 0) goto err; if (!DH_KDF_X9_42(key, *keylen, Z, Zlen, dctx->kdf_oid, dctx->kdf_ukm, dctx->kdf_ukmlen, dctx->kdf_md)) goto err; *keylen = dctx->kdf_outlen; ret = 1; err: if (Z) { OPENSSL_cleanse(Z, Zlen); OPENSSL_free(Z); } return ret; } +#endif return 1; } const EVP_PKEY_METHOD dh_pkey_meth = { EVP_PKEY_DH, 0, pkey_dh_init, pkey_dh_copy, pkey_dh_cleanup, 0, pkey_dh_paramgen, 0, pkey_dh_keygen, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, pkey_dh_derive, pkey_dh_ctrl, pkey_dh_ctrl_str }; const EVP_PKEY_METHOD dhx_pkey_meth = { EVP_PKEY_DHX, 0, pkey_dh_init, pkey_dh_copy, pkey_dh_cleanup, 0, pkey_dh_paramgen, 0, pkey_dh_keygen, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, pkey_dh_derive, pkey_dh_ctrl, pkey_dh_ctrl_str }; Index: vendor-crypto/openssl/dist/crypto/dsa/dsa_ameth.c =================================================================== --- vendor-crypto/openssl/dist/crypto/dsa/dsa_ameth.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/dsa/dsa_ameth.c (revision 325326) @@ -1,678 +1,679 @@ /* * 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 #ifndef OPENSSL_NO_CMS # include #endif #include "asn1_locl.h" static int dsa_pub_decode(EVP_PKEY *pkey, X509_PUBKEY *pubkey) { const unsigned char *p, *pm; int pklen, pmlen; int ptype; void *pval; ASN1_STRING *pstr; X509_ALGOR *palg; ASN1_INTEGER *public_key = NULL; DSA *dsa = NULL; if (!X509_PUBKEY_get0_param(NULL, &p, &pklen, &palg, pubkey)) return 0; X509_ALGOR_get0(NULL, &ptype, &pval, palg); if (ptype == V_ASN1_SEQUENCE) { pstr = pval; pm = pstr->data; pmlen = pstr->length; if (!(dsa = d2i_DSAparams(NULL, &pm, pmlen))) { DSAerr(DSA_F_DSA_PUB_DECODE, DSA_R_DECODE_ERROR); goto err; } } else if ((ptype == V_ASN1_NULL) || (ptype == V_ASN1_UNDEF)) { if (!(dsa = DSA_new())) { DSAerr(DSA_F_DSA_PUB_DECODE, ERR_R_MALLOC_FAILURE); goto err; } } else { DSAerr(DSA_F_DSA_PUB_DECODE, DSA_R_PARAMETER_ENCODING_ERROR); goto err; } if (!(public_key = d2i_ASN1_INTEGER(NULL, &p, pklen))) { DSAerr(DSA_F_DSA_PUB_DECODE, DSA_R_DECODE_ERROR); goto err; } if (!(dsa->pub_key = ASN1_INTEGER_to_BN(public_key, NULL))) { DSAerr(DSA_F_DSA_PUB_DECODE, DSA_R_BN_DECODE_ERROR); goto err; } ASN1_INTEGER_free(public_key); EVP_PKEY_assign_DSA(pkey, dsa); return 1; err: if (public_key) ASN1_INTEGER_free(public_key); if (dsa) DSA_free(dsa); return 0; } static int dsa_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey) { DSA *dsa; int ptype; unsigned char *penc = NULL; int penclen; ASN1_STRING *str = NULL; dsa = pkey->pkey.dsa; if (pkey->save_parameters && dsa->p && dsa->q && dsa->g) { str = ASN1_STRING_new(); if (!str) { DSAerr(DSA_F_DSA_PUB_ENCODE, ERR_R_MALLOC_FAILURE); goto err; } str->length = i2d_DSAparams(dsa, &str->data); if (str->length <= 0) { DSAerr(DSA_F_DSA_PUB_ENCODE, ERR_R_MALLOC_FAILURE); goto err; } ptype = V_ASN1_SEQUENCE; } else ptype = V_ASN1_UNDEF; dsa->write_params = 0; penclen = i2d_DSAPublicKey(dsa, &penc); if (penclen <= 0) { DSAerr(DSA_F_DSA_PUB_ENCODE, ERR_R_MALLOC_FAILURE); goto err; } if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(EVP_PKEY_DSA), ptype, str, penc, penclen)) return 1; err: if (penc) OPENSSL_free(penc); if (str) ASN1_STRING_free(str); return 0; } /* * In PKCS#8 DSA: you just get a private key integer and parameters in the * AlgorithmIdentifier the pubkey must be recalculated. */ static int dsa_priv_decode(EVP_PKEY *pkey, PKCS8_PRIV_KEY_INFO *p8) { const unsigned char *p, *pm; int pklen, pmlen; int ptype; void *pval; ASN1_STRING *pstr; X509_ALGOR *palg; ASN1_INTEGER *privkey = NULL; BN_CTX *ctx = NULL; STACK_OF(ASN1_TYPE) *ndsa = NULL; DSA *dsa = NULL; int ret = 0; if (!PKCS8_pkey_get0(NULL, &p, &pklen, &palg, p8)) return 0; X509_ALGOR_get0(NULL, &ptype, &pval, palg); /* Check for broken DSA PKCS#8, UGH! */ if (*p == (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)) { ASN1_TYPE *t1, *t2; if (!(ndsa = d2i_ASN1_SEQUENCE_ANY(NULL, &p, pklen))) goto decerr; if (sk_ASN1_TYPE_num(ndsa) != 2) goto decerr; /*- * Handle Two broken types: * SEQUENCE {parameters, priv_key} * SEQUENCE {pub_key, priv_key} */ t1 = sk_ASN1_TYPE_value(ndsa, 0); t2 = sk_ASN1_TYPE_value(ndsa, 1); if (t1->type == V_ASN1_SEQUENCE) { p8->broken = PKCS8_EMBEDDED_PARAM; pval = t1->value.ptr; } else if (ptype == V_ASN1_SEQUENCE) p8->broken = PKCS8_NS_DB; else goto decerr; if (t2->type != V_ASN1_INTEGER) goto decerr; privkey = t2->value.integer; } else { const unsigned char *q = p; if (!(privkey = d2i_ASN1_INTEGER(NULL, &p, pklen))) goto decerr; if (privkey->type == V_ASN1_NEG_INTEGER) { p8->broken = PKCS8_NEG_PRIVKEY; ASN1_STRING_clear_free(privkey); if (!(privkey = d2i_ASN1_UINTEGER(NULL, &q, pklen))) goto decerr; } if (ptype != V_ASN1_SEQUENCE) goto decerr; } pstr = pval; pm = pstr->data; pmlen = pstr->length; if (!(dsa = d2i_DSAparams(NULL, &pm, pmlen))) goto decerr; /* We have parameters now set private key */ if (!(dsa->priv_key = ASN1_INTEGER_to_BN(privkey, NULL))) { DSAerr(DSA_F_DSA_PRIV_DECODE, DSA_R_BN_ERROR); goto dsaerr; } /* Calculate public key */ if (!(dsa->pub_key = BN_new())) { DSAerr(DSA_F_DSA_PRIV_DECODE, ERR_R_MALLOC_FAILURE); goto dsaerr; } if (!(ctx = BN_CTX_new())) { DSAerr(DSA_F_DSA_PRIV_DECODE, ERR_R_MALLOC_FAILURE); goto dsaerr; } + BN_set_flags(dsa->priv_key, BN_FLG_CONSTTIME); if (!BN_mod_exp(dsa->pub_key, dsa->g, dsa->priv_key, dsa->p, ctx)) { DSAerr(DSA_F_DSA_PRIV_DECODE, DSA_R_BN_ERROR); goto dsaerr; } EVP_PKEY_assign_DSA(pkey, dsa); ret = 1; goto done; decerr: DSAerr(DSA_F_DSA_PRIV_DECODE, DSA_R_DECODE_ERROR); dsaerr: DSA_free(dsa); done: BN_CTX_free(ctx); if (ndsa) sk_ASN1_TYPE_pop_free(ndsa, ASN1_TYPE_free); else ASN1_STRING_clear_free(privkey); return ret; } static int dsa_priv_encode(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pkey) { ASN1_STRING *params = NULL; ASN1_INTEGER *prkey = NULL; unsigned char *dp = NULL; int dplen; if (!pkey->pkey.dsa || !pkey->pkey.dsa->priv_key) { DSAerr(DSA_F_DSA_PRIV_ENCODE, DSA_R_MISSING_PARAMETERS); goto err; } params = ASN1_STRING_new(); if (!params) { DSAerr(DSA_F_DSA_PRIV_ENCODE, ERR_R_MALLOC_FAILURE); goto err; } params->length = i2d_DSAparams(pkey->pkey.dsa, ¶ms->data); if (params->length <= 0) { DSAerr(DSA_F_DSA_PRIV_ENCODE, ERR_R_MALLOC_FAILURE); goto err; } params->type = V_ASN1_SEQUENCE; /* Get private key into integer */ prkey = BN_to_ASN1_INTEGER(pkey->pkey.dsa->priv_key, NULL); if (!prkey) { DSAerr(DSA_F_DSA_PRIV_ENCODE, DSA_R_BN_ERROR); goto err; } dplen = i2d_ASN1_INTEGER(prkey, &dp); ASN1_STRING_clear_free(prkey); prkey = NULL; if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(NID_dsa), 0, V_ASN1_SEQUENCE, params, dp, dplen)) goto err; return 1; err: if (dp != NULL) OPENSSL_free(dp); if (params != NULL) ASN1_STRING_free(params); if (prkey != NULL) ASN1_STRING_clear_free(prkey); return 0; } static int int_dsa_size(const EVP_PKEY *pkey) { return (DSA_size(pkey->pkey.dsa)); } static int dsa_bits(const EVP_PKEY *pkey) { return BN_num_bits(pkey->pkey.dsa->p); } static int dsa_missing_parameters(const EVP_PKEY *pkey) { DSA *dsa; dsa = pkey->pkey.dsa; if (dsa == NULL || dsa->p == NULL || dsa->q == NULL || dsa->g == NULL) return 1; return 0; } static int dsa_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from) { BIGNUM *a; if ((a = BN_dup(from->pkey.dsa->p)) == NULL) return 0; if (to->pkey.dsa->p != NULL) BN_free(to->pkey.dsa->p); to->pkey.dsa->p = a; if ((a = BN_dup(from->pkey.dsa->q)) == NULL) return 0; if (to->pkey.dsa->q != NULL) BN_free(to->pkey.dsa->q); to->pkey.dsa->q = a; if ((a = BN_dup(from->pkey.dsa->g)) == NULL) return 0; if (to->pkey.dsa->g != NULL) BN_free(to->pkey.dsa->g); to->pkey.dsa->g = a; return 1; } static int dsa_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b) { if (BN_cmp(a->pkey.dsa->p, b->pkey.dsa->p) || BN_cmp(a->pkey.dsa->q, b->pkey.dsa->q) || BN_cmp(a->pkey.dsa->g, b->pkey.dsa->g)) return 0; else return 1; } static int dsa_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b) { if (BN_cmp(b->pkey.dsa->pub_key, a->pkey.dsa->pub_key) != 0) return 0; else return 1; } static void int_dsa_free(EVP_PKEY *pkey) { DSA_free(pkey->pkey.dsa); } static void update_buflen(const BIGNUM *b, size_t *pbuflen) { size_t i; if (!b) return; if (*pbuflen < (i = (size_t)BN_num_bytes(b))) *pbuflen = i; } static int do_dsa_print(BIO *bp, const DSA *x, int off, int ptype) { unsigned char *m = NULL; int ret = 0; size_t buf_len = 0; const char *ktype = NULL; const BIGNUM *priv_key, *pub_key; if (ptype == 2) priv_key = x->priv_key; else priv_key = NULL; if (ptype > 0) pub_key = x->pub_key; else pub_key = NULL; if (ptype == 2) ktype = "Private-Key"; else if (ptype == 1) ktype = "Public-Key"; else ktype = "DSA-Parameters"; update_buflen(x->p, &buf_len); update_buflen(x->q, &buf_len); update_buflen(x->g, &buf_len); update_buflen(priv_key, &buf_len); update_buflen(pub_key, &buf_len); m = (unsigned char *)OPENSSL_malloc(buf_len + 10); if (m == NULL) { DSAerr(DSA_F_DO_DSA_PRINT, ERR_R_MALLOC_FAILURE); goto err; } if (priv_key) { if (!BIO_indent(bp, off, 128)) goto err; if (BIO_printf(bp, "%s: (%d bit)\n", ktype, BN_num_bits(x->p)) <= 0) goto err; } if (!ASN1_bn_print(bp, "priv:", priv_key, m, off)) goto err; if (!ASN1_bn_print(bp, "pub: ", pub_key, m, off)) goto err; if (!ASN1_bn_print(bp, "P: ", x->p, m, off)) goto err; if (!ASN1_bn_print(bp, "Q: ", x->q, m, off)) goto err; if (!ASN1_bn_print(bp, "G: ", x->g, m, off)) goto err; ret = 1; err: if (m != NULL) OPENSSL_free(m); return (ret); } static int dsa_param_decode(EVP_PKEY *pkey, const unsigned char **pder, int derlen) { DSA *dsa; if (!(dsa = d2i_DSAparams(NULL, pder, derlen))) { DSAerr(DSA_F_DSA_PARAM_DECODE, ERR_R_DSA_LIB); return 0; } EVP_PKEY_assign_DSA(pkey, dsa); return 1; } static int dsa_param_encode(const EVP_PKEY *pkey, unsigned char **pder) { return i2d_DSAparams(pkey->pkey.dsa, pder); } static int dsa_param_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return do_dsa_print(bp, pkey->pkey.dsa, indent, 0); } static int dsa_pub_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return do_dsa_print(bp, pkey->pkey.dsa, indent, 1); } static int dsa_priv_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return do_dsa_print(bp, pkey->pkey.dsa, indent, 2); } static int old_dsa_priv_decode(EVP_PKEY *pkey, const unsigned char **pder, int derlen) { DSA *dsa; if (!(dsa = d2i_DSAPrivateKey(NULL, pder, derlen))) { DSAerr(DSA_F_OLD_DSA_PRIV_DECODE, ERR_R_DSA_LIB); return 0; } EVP_PKEY_assign_DSA(pkey, dsa); return 1; } static int old_dsa_priv_encode(const EVP_PKEY *pkey, unsigned char **pder) { return i2d_DSAPrivateKey(pkey->pkey.dsa, pder); } static int dsa_sig_print(BIO *bp, const X509_ALGOR *sigalg, const ASN1_STRING *sig, int indent, ASN1_PCTX *pctx) { DSA_SIG *dsa_sig; const unsigned char *p; if (!sig) { if (BIO_puts(bp, "\n") <= 0) return 0; else return 1; } p = sig->data; dsa_sig = d2i_DSA_SIG(NULL, &p, sig->length); if (dsa_sig) { int rv = 0; size_t buf_len = 0; unsigned char *m = NULL; update_buflen(dsa_sig->r, &buf_len); update_buflen(dsa_sig->s, &buf_len); m = OPENSSL_malloc(buf_len + 10); if (m == NULL) { DSAerr(DSA_F_DSA_SIG_PRINT, ERR_R_MALLOC_FAILURE); goto err; } if (BIO_write(bp, "\n", 1) != 1) goto err; if (!ASN1_bn_print(bp, "r: ", dsa_sig->r, m, indent)) goto err; if (!ASN1_bn_print(bp, "s: ", dsa_sig->s, m, indent)) goto err; rv = 1; err: if (m) OPENSSL_free(m); DSA_SIG_free(dsa_sig); return rv; } return X509_signature_dump(bp, sig, indent); } static int dsa_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_RI_TYPE: *(int *)arg2 = CMS_RECIPINFO_NONE; return 1; #endif case ASN1_PKEY_CTRL_DEFAULT_MD_NID: *(int *)arg2 = NID_sha256; return 2; default: return -2; } } /* NB these are sorted in pkey_id order, lowest first */ const EVP_PKEY_ASN1_METHOD dsa_asn1_meths[] = { { EVP_PKEY_DSA2, EVP_PKEY_DSA, ASN1_PKEY_ALIAS}, { EVP_PKEY_DSA1, EVP_PKEY_DSA, ASN1_PKEY_ALIAS}, { EVP_PKEY_DSA4, EVP_PKEY_DSA, ASN1_PKEY_ALIAS}, { EVP_PKEY_DSA3, EVP_PKEY_DSA, ASN1_PKEY_ALIAS}, { EVP_PKEY_DSA, EVP_PKEY_DSA, 0, "DSA", "OpenSSL DSA method", dsa_pub_decode, dsa_pub_encode, dsa_pub_cmp, dsa_pub_print, dsa_priv_decode, dsa_priv_encode, dsa_priv_print, int_dsa_size, dsa_bits, dsa_param_decode, dsa_param_encode, dsa_missing_parameters, dsa_copy_parameters, dsa_cmp_parameters, dsa_param_print, dsa_sig_print, int_dsa_free, dsa_pkey_ctrl, old_dsa_priv_decode, old_dsa_priv_encode} }; Index: vendor-crypto/openssl/dist/crypto/dsa/dsa_gen.c =================================================================== --- vendor-crypto/openssl/dist/crypto/dsa/dsa_gen.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/dsa/dsa_gen.c (revision 325326) @@ -1,751 +1,753 @@ /* crypto/dsa/dsa_gen.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.] */ #undef GENUINE_DSA #ifdef GENUINE_DSA /* * Parameter generation follows the original release of FIPS PUB 186, * Appendix 2.2 (i.e. use SHA as defined in FIPS PUB 180) */ # define HASH EVP_sha() #else /* * Parameter generation follows the updated Appendix 2.2 for FIPS PUB 186, * also Appendix 2.2 of FIPS PUB 186-1 (i.e. use SHA as defined in FIPS PUB * 180-1) */ # define HASH EVP_sha1() #endif #include /* To see if OPENSSL_NO_SHA is defined */ #ifndef OPENSSL_NO_SHA # include # include "cryptlib.h" # include # include # include # include # include "dsa_locl.h" # ifdef OPENSSL_FIPS /* Workaround bug in prototype */ # define fips_dsa_builtin_paramgen2 fips_dsa_paramgen_bad # include # endif int DSA_generate_parameters_ex(DSA *ret, int bits, const unsigned char *seed_in, int seed_len, int *counter_ret, unsigned long *h_ret, BN_GENCB *cb) { # ifdef OPENSSL_FIPS if (FIPS_mode() && !(ret->meth->flags & DSA_FLAG_FIPS_METHOD) && !(ret->flags & DSA_FLAG_NON_FIPS_ALLOW)) { DSAerr(DSA_F_DSA_GENERATE_PARAMETERS_EX, DSA_R_NON_FIPS_DSA_METHOD); return 0; } # endif if (ret->meth->dsa_paramgen) return ret->meth->dsa_paramgen(ret, bits, seed_in, seed_len, counter_ret, h_ret, cb); # ifdef OPENSSL_FIPS else if (FIPS_mode()) { return FIPS_dsa_generate_parameters_ex(ret, bits, seed_in, seed_len, counter_ret, h_ret, cb); } # endif else { const EVP_MD *evpmd = bits >= 2048 ? EVP_sha256() : EVP_sha1(); size_t qbits = EVP_MD_size(evpmd) * 8; return dsa_builtin_paramgen(ret, bits, qbits, evpmd, seed_in, seed_len, NULL, counter_ret, h_ret, cb); } } int dsa_builtin_paramgen(DSA *ret, size_t bits, size_t qbits, const EVP_MD *evpmd, const unsigned char *seed_in, size_t seed_len, unsigned char *seed_out, int *counter_ret, unsigned long *h_ret, BN_GENCB *cb) { int ok = 0; unsigned char seed[SHA256_DIGEST_LENGTH]; unsigned char md[SHA256_DIGEST_LENGTH]; unsigned char buf[SHA256_DIGEST_LENGTH], buf2[SHA256_DIGEST_LENGTH]; BIGNUM *r0, *W, *X, *c, *test; BIGNUM *g = NULL, *q = NULL, *p = NULL; BN_MONT_CTX *mont = NULL; int i, k, n = 0, m = 0, qsize = qbits >> 3; int counter = 0; int r = 0; BN_CTX *ctx = NULL; unsigned int h = 2; if (qsize != SHA_DIGEST_LENGTH && qsize != SHA224_DIGEST_LENGTH && qsize != SHA256_DIGEST_LENGTH) /* invalid q size */ return 0; if (evpmd == NULL) /* use SHA1 as default */ evpmd = EVP_sha1(); if (bits < 512) bits = 512; bits = (bits + 63) / 64 * 64; /* * NB: seed_len == 0 is special case: copy generated seed to seed_in if * it is not NULL. */ if (seed_len && (seed_len < (size_t)qsize)) seed_in = NULL; /* seed buffer too small -- ignore */ if (seed_len > (size_t)qsize) seed_len = qsize; /* App. 2.2 of FIPS PUB 186 allows larger * SEED, but our internal buffers are * restricted to 160 bits */ if (seed_in != NULL) memcpy(seed, seed_in, seed_len); if ((mont = BN_MONT_CTX_new()) == NULL) goto err; if ((ctx = BN_CTX_new()) == NULL) goto err; BN_CTX_start(ctx); r0 = BN_CTX_get(ctx); g = BN_CTX_get(ctx); W = BN_CTX_get(ctx); q = BN_CTX_get(ctx); X = BN_CTX_get(ctx); c = BN_CTX_get(ctx); p = BN_CTX_get(ctx); test = BN_CTX_get(ctx); if (test == NULL) goto err; if (!BN_lshift(test, BN_value_one(), bits - 1)) goto err; for (;;) { for (;;) { /* find q */ int seed_is_random; /* step 1 */ if (!BN_GENCB_call(cb, 0, m++)) goto err; if (!seed_len || !seed_in) { if (RAND_bytes(seed, qsize) <= 0) goto err; seed_is_random = 1; } else { seed_is_random = 0; seed_len = 0; /* use random seed if 'seed_in' turns out to * be bad */ } memcpy(buf, seed, qsize); memcpy(buf2, seed, qsize); /* precompute "SEED + 1" for step 7: */ for (i = qsize - 1; i >= 0; i--) { buf[i]++; if (buf[i] != 0) break; } /* step 2 */ if (!EVP_Digest(seed, qsize, md, NULL, evpmd, NULL)) goto err; if (!EVP_Digest(buf, qsize, buf2, NULL, evpmd, NULL)) goto err; for (i = 0; i < qsize; i++) md[i] ^= buf2[i]; /* step 3 */ md[0] |= 0x80; md[qsize - 1] |= 0x01; if (!BN_bin2bn(md, qsize, q)) goto err; /* step 4 */ r = BN_is_prime_fasttest_ex(q, DSS_prime_checks, ctx, seed_is_random, cb); if (r > 0) break; if (r != 0) goto err; /* do a callback call */ /* step 5 */ } if (!BN_GENCB_call(cb, 2, 0)) goto err; if (!BN_GENCB_call(cb, 3, 0)) goto err; /* step 6 */ counter = 0; /* "offset = 2" */ n = (bits - 1) / 160; for (;;) { if ((counter != 0) && !BN_GENCB_call(cb, 0, counter)) goto err; /* step 7 */ BN_zero(W); /* now 'buf' contains "SEED + offset - 1" */ for (k = 0; k <= n; k++) { /* * obtain "SEED + offset + k" by incrementing: */ for (i = qsize - 1; i >= 0; i--) { buf[i]++; if (buf[i] != 0) break; } if (!EVP_Digest(buf, qsize, md, NULL, evpmd, NULL)) goto err; /* step 8 */ if (!BN_bin2bn(md, qsize, r0)) goto err; if (!BN_lshift(r0, r0, (qsize << 3) * k)) goto err; if (!BN_add(W, W, r0)) goto err; } /* more of step 8 */ if (!BN_mask_bits(W, bits - 1)) goto err; if (!BN_copy(X, W)) goto err; if (!BN_add(X, X, test)) goto err; /* step 9 */ if (!BN_lshift1(r0, q)) goto err; if (!BN_mod(c, X, r0, ctx)) goto err; if (!BN_sub(r0, c, BN_value_one())) goto err; if (!BN_sub(p, X, r0)) goto err; /* step 10 */ if (BN_cmp(p, test) >= 0) { /* step 11 */ r = BN_is_prime_fasttest_ex(p, DSS_prime_checks, ctx, 1, cb); if (r > 0) goto end; /* found it */ if (r != 0) goto err; } /* step 13 */ counter++; /* "offset = offset + n + 1" */ /* step 14 */ if (counter >= 4096) break; } } end: if (!BN_GENCB_call(cb, 2, 1)) goto err; /* We now need to generate g */ /* Set r0=(p-1)/q */ if (!BN_sub(test, p, BN_value_one())) goto err; if (!BN_div(r0, NULL, test, q, ctx)) goto err; if (!BN_set_word(test, h)) goto err; if (!BN_MONT_CTX_set(mont, p, ctx)) goto err; for (;;) { /* g=test^r0%p */ if (!BN_mod_exp_mont(g, test, r0, p, ctx, mont)) goto err; if (!BN_is_one(g)) break; if (!BN_add(test, test, BN_value_one())) goto err; h++; } if (!BN_GENCB_call(cb, 3, 1)) goto err; ok = 1; err: if (ok) { if (ret->p) BN_free(ret->p); if (ret->q) BN_free(ret->q); if (ret->g) BN_free(ret->g); ret->p = BN_dup(p); ret->q = BN_dup(q); ret->g = BN_dup(g); if (ret->p == NULL || ret->q == NULL || ret->g == NULL) { ok = 0; goto err; } if (counter_ret != NULL) *counter_ret = counter; if (h_ret != NULL) *h_ret = h; if (seed_out) memcpy(seed_out, seed, qsize); } if (ctx) { BN_CTX_end(ctx); BN_CTX_free(ctx); } if (mont != NULL) BN_MONT_CTX_free(mont); return ok; } # ifdef OPENSSL_FIPS # undef fips_dsa_builtin_paramgen2 extern int fips_dsa_builtin_paramgen2(DSA *ret, size_t L, size_t N, const EVP_MD *evpmd, const unsigned char *seed_in, size_t seed_len, int idx, unsigned char *seed_out, int *counter_ret, unsigned long *h_ret, BN_GENCB *cb); # endif /* * This is a parameter generation algorithm for the DSA2 algorithm as * described in FIPS 186-3. */ int dsa_builtin_paramgen2(DSA *ret, size_t L, size_t N, const EVP_MD *evpmd, const unsigned char *seed_in, size_t seed_len, int idx, unsigned char *seed_out, int *counter_ret, unsigned long *h_ret, BN_GENCB *cb) { int ok = -1; unsigned char *seed = NULL, *seed_tmp = NULL; unsigned char md[EVP_MAX_MD_SIZE]; int mdsize; BIGNUM *r0, *W, *X, *c, *test; BIGNUM *g = NULL, *q = NULL, *p = NULL; BN_MONT_CTX *mont = NULL; int i, k, n = 0, m = 0, qsize = N >> 3; int counter = 0; int r = 0; BN_CTX *ctx = NULL; EVP_MD_CTX mctx; unsigned int h = 2; # ifdef OPENSSL_FIPS if (FIPS_mode()) return fips_dsa_builtin_paramgen2(ret, L, N, evpmd, seed_in, seed_len, idx, seed_out, counter_ret, h_ret, cb); # endif EVP_MD_CTX_init(&mctx); if (evpmd == NULL) { if (N == 160) evpmd = EVP_sha1(); else if (N == 224) evpmd = EVP_sha224(); else evpmd = EVP_sha256(); } mdsize = EVP_MD_size(evpmd); /* If unverificable g generation only don't need seed */ if (!ret->p || !ret->q || idx >= 0) { if (seed_len == 0) seed_len = mdsize; seed = OPENSSL_malloc(seed_len); if (seed_out) seed_tmp = seed_out; else seed_tmp = OPENSSL_malloc(seed_len); if (!seed || !seed_tmp) goto err; if (seed_in) memcpy(seed, seed_in, seed_len); } if ((ctx = BN_CTX_new()) == NULL) goto err; if ((mont = BN_MONT_CTX_new()) == NULL) goto err; BN_CTX_start(ctx); r0 = BN_CTX_get(ctx); g = BN_CTX_get(ctx); W = BN_CTX_get(ctx); X = BN_CTX_get(ctx); c = BN_CTX_get(ctx); test = BN_CTX_get(ctx); /* if p, q already supplied generate g only */ if (ret->p && ret->q) { p = ret->p; q = ret->q; if (idx >= 0) memcpy(seed_tmp, seed, seed_len); goto g_only; } else { p = BN_CTX_get(ctx); q = BN_CTX_get(ctx); + if (q == NULL) + goto err; } if (!BN_lshift(test, BN_value_one(), L - 1)) goto err; for (;;) { for (;;) { /* find q */ unsigned char *pmd; /* step 1 */ if (!BN_GENCB_call(cb, 0, m++)) goto err; if (!seed_in) { if (RAND_bytes(seed, seed_len) <= 0) goto err; } /* step 2 */ if (!EVP_Digest(seed, seed_len, md, NULL, evpmd, NULL)) goto err; /* Take least significant bits of md */ if (mdsize > qsize) pmd = md + mdsize - qsize; else pmd = md; if (mdsize < qsize) memset(md + mdsize, 0, qsize - mdsize); /* step 3 */ pmd[0] |= 0x80; pmd[qsize - 1] |= 0x01; if (!BN_bin2bn(pmd, qsize, q)) goto err; /* step 4 */ r = BN_is_prime_fasttest_ex(q, DSS_prime_checks, ctx, seed_in ? 1 : 0, cb); if (r > 0) break; if (r != 0) goto err; /* Provided seed didn't produce a prime: error */ if (seed_in) { ok = 0; DSAerr(DSA_F_DSA_BUILTIN_PARAMGEN2, DSA_R_Q_NOT_PRIME); goto err; } /* do a callback call */ /* step 5 */ } /* Copy seed to seed_out before we mess with it */ if (seed_out) memcpy(seed_out, seed, seed_len); if (!BN_GENCB_call(cb, 2, 0)) goto err; if (!BN_GENCB_call(cb, 3, 0)) goto err; /* step 6 */ counter = 0; /* "offset = 1" */ n = (L - 1) / (mdsize << 3); for (;;) { if ((counter != 0) && !BN_GENCB_call(cb, 0, counter)) goto err; /* step 7 */ BN_zero(W); /* now 'buf' contains "SEED + offset - 1" */ for (k = 0; k <= n; k++) { /* * obtain "SEED + offset + k" by incrementing: */ for (i = seed_len - 1; i >= 0; i--) { seed[i]++; if (seed[i] != 0) break; } if (!EVP_Digest(seed, seed_len, md, NULL, evpmd, NULL)) goto err; /* step 8 */ if (!BN_bin2bn(md, mdsize, r0)) goto err; if (!BN_lshift(r0, r0, (mdsize << 3) * k)) goto err; if (!BN_add(W, W, r0)) goto err; } /* more of step 8 */ if (!BN_mask_bits(W, L - 1)) goto err; if (!BN_copy(X, W)) goto err; if (!BN_add(X, X, test)) goto err; /* step 9 */ if (!BN_lshift1(r0, q)) goto err; if (!BN_mod(c, X, r0, ctx)) goto err; if (!BN_sub(r0, c, BN_value_one())) goto err; if (!BN_sub(p, X, r0)) goto err; /* step 10 */ if (BN_cmp(p, test) >= 0) { /* step 11 */ r = BN_is_prime_fasttest_ex(p, DSS_prime_checks, ctx, 1, cb); if (r > 0) goto end; /* found it */ if (r != 0) goto err; } /* step 13 */ counter++; /* "offset = offset + n + 1" */ /* step 14 */ if (counter >= (int)(4 * L)) break; } if (seed_in) { ok = 0; DSAerr(DSA_F_DSA_BUILTIN_PARAMGEN2, DSA_R_INVALID_PARAMETERS); goto err; } } end: if (!BN_GENCB_call(cb, 2, 1)) goto err; g_only: /* We now need to generate g */ /* Set r0=(p-1)/q */ if (!BN_sub(test, p, BN_value_one())) goto err; if (!BN_div(r0, NULL, test, q, ctx)) goto err; if (idx < 0) { if (!BN_set_word(test, h)) goto err; } else h = 1; if (!BN_MONT_CTX_set(mont, p, ctx)) goto err; for (;;) { static const unsigned char ggen[4] = { 0x67, 0x67, 0x65, 0x6e }; if (idx >= 0) { md[0] = idx & 0xff; md[1] = (h >> 8) & 0xff; md[2] = h & 0xff; if (!EVP_DigestInit_ex(&mctx, evpmd, NULL)) goto err; if (!EVP_DigestUpdate(&mctx, seed_tmp, seed_len)) goto err; if (!EVP_DigestUpdate(&mctx, ggen, sizeof(ggen))) goto err; if (!EVP_DigestUpdate(&mctx, md, 3)) goto err; if (!EVP_DigestFinal_ex(&mctx, md, NULL)) goto err; if (!BN_bin2bn(md, mdsize, test)) goto err; } /* g=test^r0%p */ if (!BN_mod_exp_mont(g, test, r0, p, ctx, mont)) goto err; if (!BN_is_one(g)) break; if (idx < 0 && !BN_add(test, test, BN_value_one())) goto err; h++; if (idx >= 0 && h > 0xffff) goto err; } if (!BN_GENCB_call(cb, 3, 1)) goto err; ok = 1; err: if (ok == 1) { if (p != ret->p) { if (ret->p) BN_free(ret->p); ret->p = BN_dup(p); } if (q != ret->q) { if (ret->q) BN_free(ret->q); ret->q = BN_dup(q); } if (ret->g) BN_free(ret->g); ret->g = BN_dup(g); if (ret->p == NULL || ret->q == NULL || ret->g == NULL) { ok = -1; goto err; } if (counter_ret != NULL) *counter_ret = counter; if (h_ret != NULL) *h_ret = h; } if (seed) OPENSSL_free(seed); if (seed_out != seed_tmp) OPENSSL_free(seed_tmp); if (ctx) { BN_CTX_end(ctx); BN_CTX_free(ctx); } if (mont != NULL) BN_MONT_CTX_free(mont); EVP_MD_CTX_cleanup(&mctx); return ok; } int dsa_paramgen_check_g(DSA *dsa) { BN_CTX *ctx; BIGNUM *tmp; BN_MONT_CTX *mont = NULL; int rv = -1; ctx = BN_CTX_new(); if (!ctx) return -1; BN_CTX_start(ctx); if (BN_cmp(dsa->g, BN_value_one()) <= 0) return 0; if (BN_cmp(dsa->g, dsa->p) >= 0) return 0; tmp = BN_CTX_get(ctx); if (!tmp) goto err; if ((mont = BN_MONT_CTX_new()) == NULL) goto err; if (!BN_MONT_CTX_set(mont, dsa->p, ctx)) goto err; /* Work out g^q mod p */ if (!BN_mod_exp_mont(tmp, dsa->g, dsa->q, dsa->p, ctx, mont)) goto err; if (!BN_cmp(tmp, BN_value_one())) rv = 1; else rv = 0; err: BN_CTX_end(ctx); if (mont) BN_MONT_CTX_free(mont); BN_CTX_free(ctx); return rv; } #endif Index: vendor-crypto/openssl/dist/crypto/dsa/dsa_ossl.c =================================================================== --- vendor-crypto/openssl/dist/crypto/dsa/dsa_ossl.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/dsa/dsa_ossl.c (revision 325326) @@ -1,427 +1,439 @@ /* crypto/dsa/dsa_ossl.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.] */ /* Original version from Steven Schoch */ #include #include "cryptlib.h" #include #include #include #include #include static DSA_SIG *dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa); static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp); static int dsa_do_verify(const unsigned char *dgst, int dgst_len, DSA_SIG *sig, DSA *dsa); static int dsa_init(DSA *dsa); static int dsa_finish(DSA *dsa); static DSA_METHOD openssl_dsa_meth = { "OpenSSL DSA method", dsa_do_sign, dsa_sign_setup, dsa_do_verify, NULL, /* dsa_mod_exp, */ NULL, /* dsa_bn_mod_exp, */ dsa_init, dsa_finish, 0, NULL, NULL, NULL }; /*- * These macro wrappers replace attempts to use the dsa_mod_exp() and * bn_mod_exp() handlers in the DSA_METHOD structure. We avoid the problem of * having a the macro work as an expression by bundling an "err_instr". So; * * if (!dsa->meth->bn_mod_exp(dsa, r,dsa->g,&k,dsa->p,ctx, * dsa->method_mont_p)) goto err; * * can be replaced by; * * DSA_BN_MOD_EXP(goto err, dsa, r, dsa->g, &k, dsa->p, ctx, * dsa->method_mont_p); */ #define DSA_MOD_EXP(err_instr,dsa,rr,a1,p1,a2,p2,m,ctx,in_mont) \ do { \ int _tmp_res53; \ if ((dsa)->meth->dsa_mod_exp) \ _tmp_res53 = (dsa)->meth->dsa_mod_exp((dsa), (rr), (a1), (p1), \ (a2), (p2), (m), (ctx), (in_mont)); \ else \ _tmp_res53 = BN_mod_exp2_mont((rr), (a1), (p1), (a2), (p2), \ (m), (ctx), (in_mont)); \ if (!_tmp_res53) err_instr; \ } while(0) #define DSA_BN_MOD_EXP(err_instr,dsa,r,a,p,m,ctx,m_ctx) \ do { \ int _tmp_res53; \ if ((dsa)->meth->bn_mod_exp) \ _tmp_res53 = (dsa)->meth->bn_mod_exp((dsa), (r), (a), (p), \ (m), (ctx), (m_ctx)); \ else \ _tmp_res53 = BN_mod_exp_mont((r), (a), (p), (m), (ctx), (m_ctx)); \ if (!_tmp_res53) err_instr; \ } while(0) const DSA_METHOD *DSA_OpenSSL(void) { return &openssl_dsa_meth; } static DSA_SIG *dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa) { BIGNUM *kinv = NULL, *r = NULL, *s = NULL; BIGNUM m; BIGNUM xr; BN_CTX *ctx = NULL; int reason = ERR_R_BN_LIB; DSA_SIG *ret = NULL; int noredo = 0; BN_init(&m); BN_init(&xr); if (!dsa->p || !dsa->q || !dsa->g) { reason = DSA_R_MISSING_PARAMETERS; goto err; } s = BN_new(); if (s == NULL) goto err; ctx = BN_CTX_new(); if (ctx == NULL) goto err; redo: if ((dsa->kinv == NULL) || (dsa->r == NULL)) { if (!DSA_sign_setup(dsa, ctx, &kinv, &r)) goto err; } else { kinv = dsa->kinv; dsa->kinv = NULL; r = dsa->r; dsa->r = NULL; noredo = 1; } if (dlen > BN_num_bytes(dsa->q)) /* * if the digest length is greater than the size of q use the * BN_num_bits(dsa->q) leftmost bits of the digest, see fips 186-3, * 4.2 */ dlen = BN_num_bytes(dsa->q); if (BN_bin2bn(dgst, dlen, &m) == NULL) goto err; /* Compute s = inv(k) (m + xr) mod q */ if (!BN_mod_mul(&xr, dsa->priv_key, r, dsa->q, ctx)) goto err; /* s = xr */ if (!BN_add(s, &xr, &m)) goto err; /* s = m + xr */ if (BN_cmp(s, dsa->q) > 0) if (!BN_sub(s, s, dsa->q)) goto err; if (!BN_mod_mul(s, s, kinv, dsa->q, ctx)) goto err; /* * Redo if r or s is zero as required by FIPS 186-3: this is very * unlikely. */ if (BN_is_zero(r) || BN_is_zero(s)) { if (noredo) { reason = DSA_R_NEED_NEW_SETUP_VALUES; goto err; } goto redo; } ret = DSA_SIG_new(); if (ret == NULL) goto err; ret->r = r; ret->s = s; err: if (ret == NULL) { DSAerr(DSA_F_DSA_DO_SIGN, reason); BN_free(r); BN_free(s); } if (ctx != NULL) BN_CTX_free(ctx); BN_clear_free(&m); BN_clear_free(&xr); if (kinv != NULL) /* dsa->kinv is NULL now if we used it */ BN_clear_free(kinv); return (ret); } static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp) { BN_CTX *ctx; BIGNUM k, kq, *K, *kinv = NULL, *r = NULL; + BIGNUM l, m; int ret = 0; + int q_bits; if (!dsa->p || !dsa->q || !dsa->g) { DSAerr(DSA_F_DSA_SIGN_SETUP, DSA_R_MISSING_PARAMETERS); return 0; } BN_init(&k); BN_init(&kq); + BN_init(&l); + BN_init(&m); if (ctx_in == NULL) { if ((ctx = BN_CTX_new()) == NULL) goto err; } else ctx = ctx_in; if ((r = BN_new()) == NULL) goto err; + /* Preallocate space */ + q_bits = BN_num_bits(dsa->q); + if (!BN_set_bit(&k, q_bits) + || !BN_set_bit(&l, q_bits) + || !BN_set_bit(&m, q_bits)) + goto err; + /* Get random k */ do if (!BN_rand_range(&k, dsa->q)) goto err; while (BN_is_zero(&k)); if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) { BN_set_flags(&k, BN_FLG_CONSTTIME); } if (dsa->flags & DSA_FLAG_CACHE_MONT_P) { if (!BN_MONT_CTX_set_locked(&dsa->method_mont_p, CRYPTO_LOCK_DSA, dsa->p, ctx)) goto err; } /* Compute r = (g^k mod p) mod q */ if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) { - if (!BN_copy(&kq, &k)) - goto err; - - BN_set_flags(&kq, BN_FLG_CONSTTIME); - /* * We do not want timing information to leak the length of k, so we - * compute g^k using an equivalent exponent of fixed length. (This - * is a kludge that we need because the BN_mod_exp_mont() does not - * let us specify the desired timing behaviour.) + * compute G^k using an equivalent scalar of fixed bit-length. + * + * We unconditionally perform both of these additions to prevent a + * small timing information leakage. We then choose the sum that is + * one bit longer than the modulus. + * + * TODO: revisit the BN_copy aiming for a memory access agnostic + * conditional copy. */ - - if (!BN_add(&kq, &kq, dsa->q)) + if (!BN_add(&l, &k, dsa->q) + || !BN_add(&m, &l, dsa->q) + || !BN_copy(&kq, BN_num_bits(&l) > q_bits ? &l : &m)) goto err; - if (BN_num_bits(&kq) <= BN_num_bits(dsa->q)) { - if (!BN_add(&kq, &kq, dsa->q)) - goto err; - } + BN_set_flags(&kq, BN_FLG_CONSTTIME); + K = &kq; } else { K = &k; } DSA_BN_MOD_EXP(goto err, dsa, r, dsa->g, K, dsa->p, ctx, dsa->method_mont_p); if (!BN_mod(r, r, dsa->q, ctx)) goto err; /* Compute part of 's = inv(k) (m + xr) mod q' */ if ((kinv = BN_mod_inverse(NULL, &k, dsa->q, ctx)) == NULL) goto err; if (*kinvp != NULL) BN_clear_free(*kinvp); *kinvp = kinv; kinv = NULL; if (*rp != NULL) BN_clear_free(*rp); *rp = r; ret = 1; err: if (!ret) { DSAerr(DSA_F_DSA_SIGN_SETUP, ERR_R_BN_LIB); if (r != NULL) BN_clear_free(r); } if (ctx_in == NULL) BN_CTX_free(ctx); BN_clear_free(&k); BN_clear_free(&kq); - return (ret); + BN_clear_free(&l); + BN_clear_free(&m); + return ret; } static int dsa_do_verify(const unsigned char *dgst, int dgst_len, DSA_SIG *sig, DSA *dsa) { BN_CTX *ctx; BIGNUM u1, u2, t1; BN_MONT_CTX *mont = NULL; int ret = -1, i; if (!dsa->p || !dsa->q || !dsa->g) { DSAerr(DSA_F_DSA_DO_VERIFY, DSA_R_MISSING_PARAMETERS); return -1; } i = BN_num_bits(dsa->q); /* fips 186-3 allows only different sizes for q */ if (i != 160 && i != 224 && i != 256) { DSAerr(DSA_F_DSA_DO_VERIFY, DSA_R_BAD_Q_VALUE); return -1; } if (BN_num_bits(dsa->p) > OPENSSL_DSA_MAX_MODULUS_BITS) { DSAerr(DSA_F_DSA_DO_VERIFY, DSA_R_MODULUS_TOO_LARGE); return -1; } BN_init(&u1); BN_init(&u2); BN_init(&t1); if ((ctx = BN_CTX_new()) == NULL) goto err; if (BN_is_zero(sig->r) || BN_is_negative(sig->r) || BN_ucmp(sig->r, dsa->q) >= 0) { ret = 0; goto err; } if (BN_is_zero(sig->s) || BN_is_negative(sig->s) || BN_ucmp(sig->s, dsa->q) >= 0) { ret = 0; goto err; } /* * Calculate W = inv(S) mod Q save W in u2 */ if ((BN_mod_inverse(&u2, sig->s, dsa->q, ctx)) == NULL) goto err; /* save M in u1 */ if (dgst_len > (i >> 3)) /* * if the digest length is greater than the size of q use the * BN_num_bits(dsa->q) leftmost bits of the digest, see fips 186-3, * 4.2 */ dgst_len = (i >> 3); if (BN_bin2bn(dgst, dgst_len, &u1) == NULL) goto err; /* u1 = M * w mod q */ if (!BN_mod_mul(&u1, &u1, &u2, dsa->q, ctx)) goto err; /* u2 = r * w mod q */ if (!BN_mod_mul(&u2, sig->r, &u2, dsa->q, ctx)) goto err; if (dsa->flags & DSA_FLAG_CACHE_MONT_P) { mont = BN_MONT_CTX_set_locked(&dsa->method_mont_p, CRYPTO_LOCK_DSA, dsa->p, ctx); if (!mont) goto err; } DSA_MOD_EXP(goto err, dsa, &t1, dsa->g, &u1, dsa->pub_key, &u2, dsa->p, ctx, mont); /* BN_copy(&u1,&t1); */ /* let u1 = u1 mod q */ if (!BN_mod(&u1, &t1, dsa->q, ctx)) goto err; /* * V is now in u1. If the signature is correct, it will be equal to R. */ ret = (BN_ucmp(&u1, sig->r) == 0); err: if (ret < 0) DSAerr(DSA_F_DSA_DO_VERIFY, ERR_R_BN_LIB); if (ctx != NULL) BN_CTX_free(ctx); BN_free(&u1); BN_free(&u2); BN_free(&t1); return (ret); } static int dsa_init(DSA *dsa) { dsa->flags |= DSA_FLAG_CACHE_MONT_P; return (1); } static int dsa_finish(DSA *dsa) { if (dsa->method_mont_p) BN_MONT_CTX_free(dsa->method_mont_p); return (1); } Index: vendor-crypto/openssl/dist/crypto/ec/asm/ecp_nistz256-x86_64.pl =================================================================== --- vendor-crypto/openssl/dist/crypto/ec/asm/ecp_nistz256-x86_64.pl (revision 325325) +++ vendor-crypto/openssl/dist/crypto/ec/asm/ecp_nistz256-x86_64.pl (revision 325326) @@ -1,3007 +1,3003 @@ #!/usr/bin/env perl ############################################################################## # # # Copyright 2014 Intel Corporation # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################## # # # Developers and authors: # # Shay Gueron (1, 2), and Vlad Krasnov (1) # # (1) Intel Corporation, Israel Development Center # # (2) University of Haifa # # Reference: # # S.Gueron and V.Krasnov, "Fast Prime Field Elliptic Curve Cryptography with# # 256 Bit Primes" # # # ############################################################################## # Further optimization by : # # this/original with/without -DECP_NISTZ256_ASM(*) # Opteron +12-49% +110-150% # Bulldozer +14-45% +175-210% # P4 +18-46% n/a :-( # Westmere +12-34% +80-87% # Sandy Bridge +9-35% +110-120% # Ivy Bridge +9-35% +110-125% # Haswell +8-37% +140-160% # Broadwell +18-58% +145-210% # Atom +15-50% +130-180% # VIA Nano +43-160% +300-480% # # (*) "without -DECP_NISTZ256_ASM" refers to build with # "enable-ec_nistp_64_gcc_128"; # # Ranges denote minimum and maximum improvement coefficients depending # on benchmark. Lower coefficients are for ECDSA sign, relatively fastest # server-side operation. Keep in mind that +100% means 2x improvement. $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; 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); $addx = ($1>=2.23); } if (!$addx && $win64 && ($flavour =~ /nasm/ || $ENV{ASM} =~ /nasm/) && `nasm -v 2>&1` =~ /NASM version ([2-9]\.[0-9]+)/) { $avx = ($1>=2.09) + ($1>=2.10); $addx = ($1>=2.10); } if (!$addx && $win64 && ($flavour =~ /masm/ || $ENV{ASM} =~ /ml64/) && `ml64 2>&1` =~ /Version ([0-9]+)\./) { $avx = ($1>=10) + ($1>=11); $addx = ($1>=12); } if (!$addx && `$ENV{CC} -v 2>&1` =~ /((?:^clang|LLVM) version|.*based on LLVM) ([3-9])\.([0-9]+)/) { my $ver = $2 + $3/100.0; # 3.1->3.01, 3.10->3.10 $avx = ($ver>=3.0) + ($ver>=3.01); $addx = ($ver>=3.03); } $code.=<<___; .text .extern OPENSSL_ia32cap_P # The polynomial .align 64 .Lpoly: .quad 0xffffffffffffffff, 0x00000000ffffffff, 0x0000000000000000, 0xffffffff00000001 # 2^512 mod P precomputed for NIST P256 polynomial .LRR: .quad 0x0000000000000003, 0xfffffffbffffffff, 0xfffffffffffffffe, 0x00000004fffffffd .LOne: .long 1,1,1,1,1,1,1,1 .LTwo: .long 2,2,2,2,2,2,2,2 .LThree: .long 3,3,3,3,3,3,3,3 .LONE_mont: .quad 0x0000000000000001, 0xffffffff00000000, 0xffffffffffffffff, 0x00000000fffffffe ___ { ################################################################################ # void ecp_nistz256_mul_by_2(uint64_t res[4], uint64_t a[4]); my ($a0,$a1,$a2,$a3)=map("%r$_",(8..11)); my ($t0,$t1,$t2,$t3,$t4)=("%rax","%rdx","%rcx","%r12","%r13"); my ($r_ptr,$a_ptr,$b_ptr)=("%rdi","%rsi","%rdx"); $code.=<<___; .globl ecp_nistz256_mul_by_2 .type ecp_nistz256_mul_by_2,\@function,2 .align 64 ecp_nistz256_mul_by_2: push %r12 push %r13 mov 8*0($a_ptr), $a0 xor $t4,$t4 mov 8*1($a_ptr), $a1 add $a0, $a0 # a0:a3+a0:a3 mov 8*2($a_ptr), $a2 adc $a1, $a1 mov 8*3($a_ptr), $a3 lea .Lpoly(%rip), $a_ptr mov $a0, $t0 adc $a2, $a2 adc $a3, $a3 mov $a1, $t1 adc \$0, $t4 sub 8*0($a_ptr), $a0 mov $a2, $t2 sbb 8*1($a_ptr), $a1 sbb 8*2($a_ptr), $a2 mov $a3, $t3 sbb 8*3($a_ptr), $a3 sbb \$0, $t4 cmovc $t0, $a0 cmovc $t1, $a1 mov $a0, 8*0($r_ptr) cmovc $t2, $a2 mov $a1, 8*1($r_ptr) cmovc $t3, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) pop %r13 pop %r12 ret .size ecp_nistz256_mul_by_2,.-ecp_nistz256_mul_by_2 ################################################################################ # void ecp_nistz256_div_by_2(uint64_t res[4], uint64_t a[4]); .globl ecp_nistz256_div_by_2 .type ecp_nistz256_div_by_2,\@function,2 .align 32 ecp_nistz256_div_by_2: push %r12 push %r13 mov 8*0($a_ptr), $a0 mov 8*1($a_ptr), $a1 mov 8*2($a_ptr), $a2 mov $a0, $t0 mov 8*3($a_ptr), $a3 lea .Lpoly(%rip), $a_ptr mov $a1, $t1 xor $t4, $t4 add 8*0($a_ptr), $a0 mov $a2, $t2 adc 8*1($a_ptr), $a1 adc 8*2($a_ptr), $a2 mov $a3, $t3 adc 8*3($a_ptr), $a3 adc \$0, $t4 xor $a_ptr, $a_ptr # borrow $a_ptr test \$1, $t0 cmovz $t0, $a0 cmovz $t1, $a1 cmovz $t2, $a2 cmovz $t3, $a3 cmovz $a_ptr, $t4 mov $a1, $t0 # a0:a3>>1 shr \$1, $a0 shl \$63, $t0 mov $a2, $t1 shr \$1, $a1 or $t0, $a0 shl \$63, $t1 mov $a3, $t2 shr \$1, $a2 or $t1, $a1 shl \$63, $t2 shr \$1, $a3 shl \$63, $t4 or $t2, $a2 or $t4, $a3 mov $a0, 8*0($r_ptr) mov $a1, 8*1($r_ptr) mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) pop %r13 pop %r12 ret .size ecp_nistz256_div_by_2,.-ecp_nistz256_div_by_2 ################################################################################ # void ecp_nistz256_mul_by_3(uint64_t res[4], uint64_t a[4]); .globl ecp_nistz256_mul_by_3 .type ecp_nistz256_mul_by_3,\@function,2 .align 32 ecp_nistz256_mul_by_3: push %r12 push %r13 mov 8*0($a_ptr), $a0 xor $t4, $t4 mov 8*1($a_ptr), $a1 add $a0, $a0 # a0:a3+a0:a3 mov 8*2($a_ptr), $a2 adc $a1, $a1 mov 8*3($a_ptr), $a3 mov $a0, $t0 adc $a2, $a2 adc $a3, $a3 mov $a1, $t1 adc \$0, $t4 sub \$-1, $a0 mov $a2, $t2 sbb .Lpoly+8*1(%rip), $a1 sbb \$0, $a2 mov $a3, $t3 sbb .Lpoly+8*3(%rip), $a3 sbb \$0, $t4 cmovc $t0, $a0 cmovc $t1, $a1 cmovc $t2, $a2 cmovc $t3, $a3 xor $t4, $t4 add 8*0($a_ptr), $a0 # a0:a3+=a_ptr[0:3] adc 8*1($a_ptr), $a1 mov $a0, $t0 adc 8*2($a_ptr), $a2 adc 8*3($a_ptr), $a3 mov $a1, $t1 adc \$0, $t4 sub \$-1, $a0 mov $a2, $t2 sbb .Lpoly+8*1(%rip), $a1 sbb \$0, $a2 mov $a3, $t3 sbb .Lpoly+8*3(%rip), $a3 sbb \$0, $t4 cmovc $t0, $a0 cmovc $t1, $a1 mov $a0, 8*0($r_ptr) cmovc $t2, $a2 mov $a1, 8*1($r_ptr) cmovc $t3, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) pop %r13 pop %r12 ret .size ecp_nistz256_mul_by_3,.-ecp_nistz256_mul_by_3 ################################################################################ # void ecp_nistz256_add(uint64_t res[4], uint64_t a[4], uint64_t b[4]); .globl ecp_nistz256_add .type ecp_nistz256_add,\@function,3 .align 32 ecp_nistz256_add: push %r12 push %r13 mov 8*0($a_ptr), $a0 xor $t4, $t4 mov 8*1($a_ptr), $a1 mov 8*2($a_ptr), $a2 mov 8*3($a_ptr), $a3 lea .Lpoly(%rip), $a_ptr add 8*0($b_ptr), $a0 adc 8*1($b_ptr), $a1 mov $a0, $t0 adc 8*2($b_ptr), $a2 adc 8*3($b_ptr), $a3 mov $a1, $t1 adc \$0, $t4 sub 8*0($a_ptr), $a0 mov $a2, $t2 sbb 8*1($a_ptr), $a1 sbb 8*2($a_ptr), $a2 mov $a3, $t3 sbb 8*3($a_ptr), $a3 sbb \$0, $t4 cmovc $t0, $a0 cmovc $t1, $a1 mov $a0, 8*0($r_ptr) cmovc $t2, $a2 mov $a1, 8*1($r_ptr) cmovc $t3, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) pop %r13 pop %r12 ret .size ecp_nistz256_add,.-ecp_nistz256_add ################################################################################ # void ecp_nistz256_sub(uint64_t res[4], uint64_t a[4], uint64_t b[4]); .globl ecp_nistz256_sub .type ecp_nistz256_sub,\@function,3 .align 32 ecp_nistz256_sub: push %r12 push %r13 mov 8*0($a_ptr), $a0 xor $t4, $t4 mov 8*1($a_ptr), $a1 mov 8*2($a_ptr), $a2 mov 8*3($a_ptr), $a3 lea .Lpoly(%rip), $a_ptr sub 8*0($b_ptr), $a0 sbb 8*1($b_ptr), $a1 mov $a0, $t0 sbb 8*2($b_ptr), $a2 sbb 8*3($b_ptr), $a3 mov $a1, $t1 sbb \$0, $t4 add 8*0($a_ptr), $a0 mov $a2, $t2 adc 8*1($a_ptr), $a1 adc 8*2($a_ptr), $a2 mov $a3, $t3 adc 8*3($a_ptr), $a3 test $t4, $t4 cmovz $t0, $a0 cmovz $t1, $a1 mov $a0, 8*0($r_ptr) cmovz $t2, $a2 mov $a1, 8*1($r_ptr) cmovz $t3, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) pop %r13 pop %r12 ret .size ecp_nistz256_sub,.-ecp_nistz256_sub ################################################################################ # void ecp_nistz256_neg(uint64_t res[4], uint64_t a[4]); .globl ecp_nistz256_neg .type ecp_nistz256_neg,\@function,2 .align 32 ecp_nistz256_neg: push %r12 push %r13 xor $a0, $a0 xor $a1, $a1 xor $a2, $a2 xor $a3, $a3 xor $t4, $t4 sub 8*0($a_ptr), $a0 sbb 8*1($a_ptr), $a1 sbb 8*2($a_ptr), $a2 mov $a0, $t0 sbb 8*3($a_ptr), $a3 lea .Lpoly(%rip), $a_ptr mov $a1, $t1 sbb \$0, $t4 add 8*0($a_ptr), $a0 mov $a2, $t2 adc 8*1($a_ptr), $a1 adc 8*2($a_ptr), $a2 mov $a3, $t3 adc 8*3($a_ptr), $a3 test $t4, $t4 cmovz $t0, $a0 cmovz $t1, $a1 mov $a0, 8*0($r_ptr) cmovz $t2, $a2 mov $a1, 8*1($r_ptr) cmovz $t3, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) pop %r13 pop %r12 ret .size ecp_nistz256_neg,.-ecp_nistz256_neg ___ } { my ($r_ptr,$a_ptr,$b_org,$b_ptr)=("%rdi","%rsi","%rdx","%rbx"); my ($acc0,$acc1,$acc2,$acc3,$acc4,$acc5,$acc6,$acc7)=map("%r$_",(8..15)); my ($t0,$t1,$t2,$t3,$t4)=("%rcx","%rbp","%rbx","%rdx","%rax"); my ($poly1,$poly3)=($acc6,$acc7); $code.=<<___; ################################################################################ # void ecp_nistz256_to_mont( # uint64_t res[4], # uint64_t in[4]); .globl ecp_nistz256_to_mont .type ecp_nistz256_to_mont,\@function,2 .align 32 ecp_nistz256_to_mont: ___ $code.=<<___ if ($addx); mov \$0x80100, %ecx and OPENSSL_ia32cap_P+8(%rip), %ecx ___ $code.=<<___; lea .LRR(%rip), $b_org jmp .Lmul_mont .size ecp_nistz256_to_mont,.-ecp_nistz256_to_mont ################################################################################ # void ecp_nistz256_mul_mont( # uint64_t res[4], # uint64_t a[4], # uint64_t b[4]); .globl ecp_nistz256_mul_mont .type ecp_nistz256_mul_mont,\@function,3 .align 32 ecp_nistz256_mul_mont: ___ $code.=<<___ if ($addx); mov \$0x80100, %ecx and OPENSSL_ia32cap_P+8(%rip), %ecx ___ $code.=<<___; .Lmul_mont: push %rbp push %rbx push %r12 push %r13 push %r14 push %r15 ___ $code.=<<___ if ($addx); cmp \$0x80100, %ecx je .Lmul_montx ___ $code.=<<___; mov $b_org, $b_ptr mov 8*0($b_org), %rax mov 8*0($a_ptr), $acc1 mov 8*1($a_ptr), $acc2 mov 8*2($a_ptr), $acc3 mov 8*3($a_ptr), $acc4 call __ecp_nistz256_mul_montq ___ $code.=<<___ if ($addx); jmp .Lmul_mont_done .align 32 .Lmul_montx: mov $b_org, $b_ptr mov 8*0($b_org), %rdx mov 8*0($a_ptr), $acc1 mov 8*1($a_ptr), $acc2 mov 8*2($a_ptr), $acc3 mov 8*3($a_ptr), $acc4 lea -128($a_ptr), $a_ptr # control u-op density call __ecp_nistz256_mul_montx ___ $code.=<<___; .Lmul_mont_done: pop %r15 pop %r14 pop %r13 pop %r12 pop %rbx pop %rbp ret .size ecp_nistz256_mul_mont,.-ecp_nistz256_mul_mont .type __ecp_nistz256_mul_montq,\@abi-omnipotent .align 32 __ecp_nistz256_mul_montq: ######################################################################## # Multiply a by b[0] mov %rax, $t1 mulq $acc1 mov .Lpoly+8*1(%rip),$poly1 mov %rax, $acc0 mov $t1, %rax mov %rdx, $acc1 mulq $acc2 mov .Lpoly+8*3(%rip),$poly3 add %rax, $acc1 mov $t1, %rax adc \$0, %rdx mov %rdx, $acc2 mulq $acc3 add %rax, $acc2 mov $t1, %rax adc \$0, %rdx mov %rdx, $acc3 mulq $acc4 add %rax, $acc3 mov $acc0, %rax adc \$0, %rdx xor $acc5, $acc5 mov %rdx, $acc4 ######################################################################## # First reduction step # Basically now we want to multiply acc[0] by p256, # and add the result to the acc. # Due to the special form of p256 we do some optimizations # # acc[0] x p256[0..1] = acc[0] x 2^96 - acc[0] # then we add acc[0] and get acc[0] x 2^96 mov $acc0, $t1 shl \$32, $acc0 mulq $poly3 shr \$32, $t1 add $acc0, $acc1 # +=acc[0]<<96 adc $t1, $acc2 adc %rax, $acc3 mov 8*1($b_ptr), %rax adc %rdx, $acc4 adc \$0, $acc5 xor $acc0, $acc0 ######################################################################## # Multiply by b[1] mov %rax, $t1 mulq 8*0($a_ptr) add %rax, $acc1 mov $t1, %rax adc \$0, %rdx mov %rdx, $t0 mulq 8*1($a_ptr) add $t0, $acc2 adc \$0, %rdx add %rax, $acc2 mov $t1, %rax adc \$0, %rdx mov %rdx, $t0 mulq 8*2($a_ptr) add $t0, $acc3 adc \$0, %rdx add %rax, $acc3 mov $t1, %rax adc \$0, %rdx mov %rdx, $t0 mulq 8*3($a_ptr) add $t0, $acc4 adc \$0, %rdx add %rax, $acc4 mov $acc1, %rax adc %rdx, $acc5 adc \$0, $acc0 ######################################################################## # Second reduction step mov $acc1, $t1 shl \$32, $acc1 mulq $poly3 shr \$32, $t1 add $acc1, $acc2 adc $t1, $acc3 adc %rax, $acc4 mov 8*2($b_ptr), %rax adc %rdx, $acc5 adc \$0, $acc0 xor $acc1, $acc1 ######################################################################## # Multiply by b[2] mov %rax, $t1 mulq 8*0($a_ptr) add %rax, $acc2 mov $t1, %rax adc \$0, %rdx mov %rdx, $t0 mulq 8*1($a_ptr) add $t0, $acc3 adc \$0, %rdx add %rax, $acc3 mov $t1, %rax adc \$0, %rdx mov %rdx, $t0 mulq 8*2($a_ptr) add $t0, $acc4 adc \$0, %rdx add %rax, $acc4 mov $t1, %rax adc \$0, %rdx mov %rdx, $t0 mulq 8*3($a_ptr) add $t0, $acc5 adc \$0, %rdx add %rax, $acc5 mov $acc2, %rax adc %rdx, $acc0 adc \$0, $acc1 ######################################################################## # Third reduction step mov $acc2, $t1 shl \$32, $acc2 mulq $poly3 shr \$32, $t1 add $acc2, $acc3 adc $t1, $acc4 adc %rax, $acc5 mov 8*3($b_ptr), %rax adc %rdx, $acc0 adc \$0, $acc1 xor $acc2, $acc2 ######################################################################## # Multiply by b[3] mov %rax, $t1 mulq 8*0($a_ptr) add %rax, $acc3 mov $t1, %rax adc \$0, %rdx mov %rdx, $t0 mulq 8*1($a_ptr) add $t0, $acc4 adc \$0, %rdx add %rax, $acc4 mov $t1, %rax adc \$0, %rdx mov %rdx, $t0 mulq 8*2($a_ptr) add $t0, $acc5 adc \$0, %rdx add %rax, $acc5 mov $t1, %rax adc \$0, %rdx mov %rdx, $t0 mulq 8*3($a_ptr) add $t0, $acc0 adc \$0, %rdx add %rax, $acc0 mov $acc3, %rax adc %rdx, $acc1 adc \$0, $acc2 ######################################################################## # Final reduction step mov $acc3, $t1 shl \$32, $acc3 mulq $poly3 shr \$32, $t1 add $acc3, $acc4 adc $t1, $acc5 mov $acc4, $t0 adc %rax, $acc0 adc %rdx, $acc1 mov $acc5, $t1 adc \$0, $acc2 ######################################################################## # Branch-less conditional subtraction of P sub \$-1, $acc4 # .Lpoly[0] mov $acc0, $t2 sbb $poly1, $acc5 # .Lpoly[1] sbb \$0, $acc0 # .Lpoly[2] mov $acc1, $t3 sbb $poly3, $acc1 # .Lpoly[3] sbb \$0, $acc2 cmovc $t0, $acc4 cmovc $t1, $acc5 mov $acc4, 8*0($r_ptr) cmovc $t2, $acc0 mov $acc5, 8*1($r_ptr) cmovc $t3, $acc1 mov $acc0, 8*2($r_ptr) mov $acc1, 8*3($r_ptr) ret .size __ecp_nistz256_mul_montq,.-__ecp_nistz256_mul_montq ################################################################################ # void ecp_nistz256_sqr_mont( # uint64_t res[4], # uint64_t a[4]); # we optimize the square according to S.Gueron and V.Krasnov, # "Speeding up Big-Number Squaring" .globl ecp_nistz256_sqr_mont .type ecp_nistz256_sqr_mont,\@function,2 .align 32 ecp_nistz256_sqr_mont: ___ $code.=<<___ if ($addx); mov \$0x80100, %ecx and OPENSSL_ia32cap_P+8(%rip), %ecx ___ $code.=<<___; push %rbp push %rbx push %r12 push %r13 push %r14 push %r15 ___ $code.=<<___ if ($addx); cmp \$0x80100, %ecx je .Lsqr_montx ___ $code.=<<___; mov 8*0($a_ptr), %rax mov 8*1($a_ptr), $acc6 mov 8*2($a_ptr), $acc7 mov 8*3($a_ptr), $acc0 call __ecp_nistz256_sqr_montq ___ $code.=<<___ if ($addx); jmp .Lsqr_mont_done .align 32 .Lsqr_montx: mov 8*0($a_ptr), %rdx mov 8*1($a_ptr), $acc6 mov 8*2($a_ptr), $acc7 mov 8*3($a_ptr), $acc0 lea -128($a_ptr), $a_ptr # control u-op density call __ecp_nistz256_sqr_montx ___ $code.=<<___; .Lsqr_mont_done: pop %r15 pop %r14 pop %r13 pop %r12 pop %rbx pop %rbp ret .size ecp_nistz256_sqr_mont,.-ecp_nistz256_sqr_mont .type __ecp_nistz256_sqr_montq,\@abi-omnipotent .align 32 __ecp_nistz256_sqr_montq: mov %rax, $acc5 mulq $acc6 # a[1]*a[0] mov %rax, $acc1 mov $acc7, %rax mov %rdx, $acc2 mulq $acc5 # a[0]*a[2] add %rax, $acc2 mov $acc0, %rax adc \$0, %rdx mov %rdx, $acc3 mulq $acc5 # a[0]*a[3] add %rax, $acc3 mov $acc7, %rax adc \$0, %rdx mov %rdx, $acc4 ################################# mulq $acc6 # a[1]*a[2] add %rax, $acc3 mov $acc0, %rax adc \$0, %rdx mov %rdx, $t1 mulq $acc6 # a[1]*a[3] add %rax, $acc4 mov $acc0, %rax adc \$0, %rdx add $t1, $acc4 mov %rdx, $acc5 adc \$0, $acc5 ################################# mulq $acc7 # a[2]*a[3] xor $acc7, $acc7 add %rax, $acc5 mov 8*0($a_ptr), %rax mov %rdx, $acc6 adc \$0, $acc6 add $acc1, $acc1 # acc1:6<<1 adc $acc2, $acc2 adc $acc3, $acc3 adc $acc4, $acc4 adc $acc5, $acc5 adc $acc6, $acc6 adc \$0, $acc7 mulq %rax mov %rax, $acc0 mov 8*1($a_ptr), %rax mov %rdx, $t0 mulq %rax add $t0, $acc1 adc %rax, $acc2 mov 8*2($a_ptr), %rax adc \$0, %rdx mov %rdx, $t0 mulq %rax add $t0, $acc3 adc %rax, $acc4 mov 8*3($a_ptr), %rax adc \$0, %rdx mov %rdx, $t0 mulq %rax add $t0, $acc5 adc %rax, $acc6 mov $acc0, %rax adc %rdx, $acc7 mov .Lpoly+8*1(%rip), $a_ptr mov .Lpoly+8*3(%rip), $t1 ########################################## # Now the reduction # First iteration mov $acc0, $t0 shl \$32, $acc0 mulq $t1 shr \$32, $t0 add $acc0, $acc1 # +=acc[0]<<96 adc $t0, $acc2 adc %rax, $acc3 mov $acc1, %rax adc \$0, %rdx ########################################## # Second iteration mov $acc1, $t0 shl \$32, $acc1 mov %rdx, $acc0 mulq $t1 shr \$32, $t0 add $acc1, $acc2 adc $t0, $acc3 adc %rax, $acc0 mov $acc2, %rax adc \$0, %rdx ########################################## # Third iteration mov $acc2, $t0 shl \$32, $acc2 mov %rdx, $acc1 mulq $t1 shr \$32, $t0 add $acc2, $acc3 adc $t0, $acc0 adc %rax, $acc1 mov $acc3, %rax adc \$0, %rdx ########################################### # Last iteration mov $acc3, $t0 shl \$32, $acc3 mov %rdx, $acc2 mulq $t1 shr \$32, $t0 add $acc3, $acc0 adc $t0, $acc1 adc %rax, $acc2 adc \$0, %rdx xor $acc3, $acc3 ############################################ # Add the rest of the acc add $acc0, $acc4 adc $acc1, $acc5 mov $acc4, $acc0 adc $acc2, $acc6 adc %rdx, $acc7 mov $acc5, $acc1 adc \$0, $acc3 sub \$-1, $acc4 # .Lpoly[0] mov $acc6, $acc2 sbb $a_ptr, $acc5 # .Lpoly[1] sbb \$0, $acc6 # .Lpoly[2] mov $acc7, $t0 sbb $t1, $acc7 # .Lpoly[3] sbb \$0, $acc3 cmovc $acc0, $acc4 cmovc $acc1, $acc5 mov $acc4, 8*0($r_ptr) cmovc $acc2, $acc6 mov $acc5, 8*1($r_ptr) cmovc $t0, $acc7 mov $acc6, 8*2($r_ptr) mov $acc7, 8*3($r_ptr) ret .size __ecp_nistz256_sqr_montq,.-__ecp_nistz256_sqr_montq ___ if ($addx) { $code.=<<___; .type __ecp_nistz256_mul_montx,\@abi-omnipotent .align 32 __ecp_nistz256_mul_montx: ######################################################################## # Multiply by b[0] mulx $acc1, $acc0, $acc1 mulx $acc2, $t0, $acc2 mov \$32, $poly1 xor $acc5, $acc5 # cf=0 mulx $acc3, $t1, $acc3 mov .Lpoly+8*3(%rip), $poly3 adc $t0, $acc1 mulx $acc4, $t0, $acc4 mov $acc0, %rdx adc $t1, $acc2 shlx $poly1,$acc0,$t1 adc $t0, $acc3 shrx $poly1,$acc0,$t0 adc \$0, $acc4 ######################################################################## # First reduction step add $t1, $acc1 adc $t0, $acc2 mulx $poly3, $t0, $t1 mov 8*1($b_ptr), %rdx adc $t0, $acc3 adc $t1, $acc4 adc \$0, $acc5 xor $acc0, $acc0 # $acc0=0,cf=0,of=0 ######################################################################## # Multiply by b[1] mulx 8*0+128($a_ptr), $t0, $t1 adcx $t0, $acc1 adox $t1, $acc2 mulx 8*1+128($a_ptr), $t0, $t1 adcx $t0, $acc2 adox $t1, $acc3 mulx 8*2+128($a_ptr), $t0, $t1 adcx $t0, $acc3 adox $t1, $acc4 mulx 8*3+128($a_ptr), $t0, $t1 mov $acc1, %rdx adcx $t0, $acc4 shlx $poly1, $acc1, $t0 adox $t1, $acc5 shrx $poly1, $acc1, $t1 adcx $acc0, $acc5 adox $acc0, $acc0 adc \$0, $acc0 ######################################################################## # Second reduction step add $t0, $acc2 adc $t1, $acc3 mulx $poly3, $t0, $t1 mov 8*2($b_ptr), %rdx adc $t0, $acc4 adc $t1, $acc5 adc \$0, $acc0 xor $acc1 ,$acc1 # $acc1=0,cf=0,of=0 ######################################################################## # Multiply by b[2] mulx 8*0+128($a_ptr), $t0, $t1 adcx $t0, $acc2 adox $t1, $acc3 mulx 8*1+128($a_ptr), $t0, $t1 adcx $t0, $acc3 adox $t1, $acc4 mulx 8*2+128($a_ptr), $t0, $t1 adcx $t0, $acc4 adox $t1, $acc5 mulx 8*3+128($a_ptr), $t0, $t1 mov $acc2, %rdx adcx $t0, $acc5 shlx $poly1, $acc2, $t0 adox $t1, $acc0 shrx $poly1, $acc2, $t1 adcx $acc1, $acc0 adox $acc1, $acc1 adc \$0, $acc1 ######################################################################## # Third reduction step add $t0, $acc3 adc $t1, $acc4 mulx $poly3, $t0, $t1 mov 8*3($b_ptr), %rdx adc $t0, $acc5 adc $t1, $acc0 adc \$0, $acc1 xor $acc2, $acc2 # $acc2=0,cf=0,of=0 ######################################################################## # Multiply by b[3] mulx 8*0+128($a_ptr), $t0, $t1 adcx $t0, $acc3 adox $t1, $acc4 mulx 8*1+128($a_ptr), $t0, $t1 adcx $t0, $acc4 adox $t1, $acc5 mulx 8*2+128($a_ptr), $t0, $t1 adcx $t0, $acc5 adox $t1, $acc0 mulx 8*3+128($a_ptr), $t0, $t1 mov $acc3, %rdx adcx $t0, $acc0 shlx $poly1, $acc3, $t0 adox $t1, $acc1 shrx $poly1, $acc3, $t1 adcx $acc2, $acc1 adox $acc2, $acc2 adc \$0, $acc2 ######################################################################## # Fourth reduction step add $t0, $acc4 adc $t1, $acc5 mulx $poly3, $t0, $t1 mov $acc4, $t2 mov .Lpoly+8*1(%rip), $poly1 adc $t0, $acc0 mov $acc5, $t3 adc $t1, $acc1 adc \$0, $acc2 ######################################################################## # Branch-less conditional subtraction of P xor %eax, %eax mov $acc0, $t0 sbb \$-1, $acc4 # .Lpoly[0] sbb $poly1, $acc5 # .Lpoly[1] sbb \$0, $acc0 # .Lpoly[2] mov $acc1, $t1 sbb $poly3, $acc1 # .Lpoly[3] sbb \$0, $acc2 cmovc $t2, $acc4 cmovc $t3, $acc5 mov $acc4, 8*0($r_ptr) cmovc $t0, $acc0 mov $acc5, 8*1($r_ptr) cmovc $t1, $acc1 mov $acc0, 8*2($r_ptr) mov $acc1, 8*3($r_ptr) ret .size __ecp_nistz256_mul_montx,.-__ecp_nistz256_mul_montx .type __ecp_nistz256_sqr_montx,\@abi-omnipotent .align 32 __ecp_nistz256_sqr_montx: mulx $acc6, $acc1, $acc2 # a[0]*a[1] mulx $acc7, $t0, $acc3 # a[0]*a[2] xor %eax, %eax adc $t0, $acc2 mulx $acc0, $t1, $acc4 # a[0]*a[3] mov $acc6, %rdx adc $t1, $acc3 adc \$0, $acc4 xor $acc5, $acc5 # $acc5=0,cf=0,of=0 ################################# mulx $acc7, $t0, $t1 # a[1]*a[2] adcx $t0, $acc3 adox $t1, $acc4 mulx $acc0, $t0, $t1 # a[1]*a[3] mov $acc7, %rdx adcx $t0, $acc4 adox $t1, $acc5 adc \$0, $acc5 ################################# mulx $acc0, $t0, $acc6 # a[2]*a[3] mov 8*0+128($a_ptr), %rdx xor $acc7, $acc7 # $acc7=0,cf=0,of=0 adcx $acc1, $acc1 # acc1:6<<1 adox $t0, $acc5 adcx $acc2, $acc2 adox $acc7, $acc6 # of=0 mulx %rdx, $acc0, $t1 mov 8*1+128($a_ptr), %rdx adcx $acc3, $acc3 adox $t1, $acc1 adcx $acc4, $acc4 mulx %rdx, $t0, $t4 mov 8*2+128($a_ptr), %rdx adcx $acc5, $acc5 adox $t0, $acc2 adcx $acc6, $acc6 .byte 0x67 mulx %rdx, $t0, $t1 mov 8*3+128($a_ptr), %rdx adox $t4, $acc3 adcx $acc7, $acc7 adox $t0, $acc4 mov \$32, $a_ptr adox $t1, $acc5 .byte 0x67,0x67 mulx %rdx, $t0, $t4 - mov $acc0, %rdx + mov .Lpoly+8*3(%rip), %rdx adox $t0, $acc6 shlx $a_ptr, $acc0, $t0 adox $t4, $acc7 shrx $a_ptr, $acc0, $t4 - mov .Lpoly+8*3(%rip), $t1 + mov %rdx,$t1 # reduction step 1 add $t0, $acc1 adc $t4, $acc2 - mulx $t1, $t0, $acc0 - mov $acc1, %rdx + mulx $acc0, $t0, $acc0 adc $t0, $acc3 shlx $a_ptr, $acc1, $t0 adc \$0, $acc0 shrx $a_ptr, $acc1, $t4 # reduction step 2 add $t0, $acc2 adc $t4, $acc3 - mulx $t1, $t0, $acc1 - mov $acc2, %rdx + mulx $acc1, $t0, $acc1 adc $t0, $acc0 shlx $a_ptr, $acc2, $t0 adc \$0, $acc1 shrx $a_ptr, $acc2, $t4 # reduction step 3 add $t0, $acc3 adc $t4, $acc0 - mulx $t1, $t0, $acc2 - mov $acc3, %rdx + mulx $acc2, $t0, $acc2 adc $t0, $acc1 shlx $a_ptr, $acc3, $t0 adc \$0, $acc2 shrx $a_ptr, $acc3, $t4 # reduction step 4 add $t0, $acc0 adc $t4, $acc1 - mulx $t1, $t0, $acc3 + mulx $acc3, $t0, $acc3 adc $t0, $acc2 adc \$0, $acc3 - xor $t3, $t3 # cf=0 - adc $acc0, $acc4 # accumulate upper half + xor $t3, $t3 + add $acc0, $acc4 # accumulate upper half mov .Lpoly+8*1(%rip), $a_ptr adc $acc1, $acc5 mov $acc4, $acc0 adc $acc2, $acc6 adc $acc3, $acc7 mov $acc5, $acc1 adc \$0, $t3 - xor %eax, %eax # cf=0 - sbb \$-1, $acc4 # .Lpoly[0] + sub \$-1, $acc4 # .Lpoly[0] mov $acc6, $acc2 sbb $a_ptr, $acc5 # .Lpoly[1] sbb \$0, $acc6 # .Lpoly[2] mov $acc7, $acc3 sbb $t1, $acc7 # .Lpoly[3] sbb \$0, $t3 cmovc $acc0, $acc4 cmovc $acc1, $acc5 mov $acc4, 8*0($r_ptr) cmovc $acc2, $acc6 mov $acc5, 8*1($r_ptr) cmovc $acc3, $acc7 mov $acc6, 8*2($r_ptr) mov $acc7, 8*3($r_ptr) ret .size __ecp_nistz256_sqr_montx,.-__ecp_nistz256_sqr_montx ___ } } { my ($r_ptr,$in_ptr)=("%rdi","%rsi"); my ($acc0,$acc1,$acc2,$acc3)=map("%r$_",(8..11)); my ($t0,$t1,$t2)=("%rcx","%r12","%r13"); $code.=<<___; ################################################################################ # void ecp_nistz256_from_mont( # uint64_t res[4], # uint64_t in[4]); # This one performs Montgomery multiplication by 1, so we only need the reduction .globl ecp_nistz256_from_mont .type ecp_nistz256_from_mont,\@function,2 .align 32 ecp_nistz256_from_mont: push %r12 push %r13 mov 8*0($in_ptr), %rax mov .Lpoly+8*3(%rip), $t2 mov 8*1($in_ptr), $acc1 mov 8*2($in_ptr), $acc2 mov 8*3($in_ptr), $acc3 mov %rax, $acc0 mov .Lpoly+8*1(%rip), $t1 ######################################### # First iteration mov %rax, $t0 shl \$32, $acc0 mulq $t2 shr \$32, $t0 add $acc0, $acc1 adc $t0, $acc2 adc %rax, $acc3 mov $acc1, %rax adc \$0, %rdx ######################################### # Second iteration mov $acc1, $t0 shl \$32, $acc1 mov %rdx, $acc0 mulq $t2 shr \$32, $t0 add $acc1, $acc2 adc $t0, $acc3 adc %rax, $acc0 mov $acc2, %rax adc \$0, %rdx ########################################## # Third iteration mov $acc2, $t0 shl \$32, $acc2 mov %rdx, $acc1 mulq $t2 shr \$32, $t0 add $acc2, $acc3 adc $t0, $acc0 adc %rax, $acc1 mov $acc3, %rax adc \$0, %rdx ########################################### # Last iteration mov $acc3, $t0 shl \$32, $acc3 mov %rdx, $acc2 mulq $t2 shr \$32, $t0 add $acc3, $acc0 adc $t0, $acc1 mov $acc0, $t0 adc %rax, $acc2 mov $acc1, $in_ptr adc \$0, %rdx ########################################### # Branch-less conditional subtraction sub \$-1, $acc0 mov $acc2, %rax sbb $t1, $acc1 sbb \$0, $acc2 mov %rdx, $acc3 sbb $t2, %rdx sbb $t2, $t2 cmovnz $t0, $acc0 cmovnz $in_ptr, $acc1 mov $acc0, 8*0($r_ptr) cmovnz %rax, $acc2 mov $acc1, 8*1($r_ptr) cmovz %rdx, $acc3 mov $acc2, 8*2($r_ptr) mov $acc3, 8*3($r_ptr) pop %r13 pop %r12 ret .size ecp_nistz256_from_mont,.-ecp_nistz256_from_mont ___ } { my ($val,$in_t,$index)=$win64?("%rcx","%rdx","%r8d"):("%rdi","%rsi","%edx"); my ($ONE,$INDEX,$Ra,$Rb,$Rc,$Rd,$Re,$Rf)=map("%xmm$_",(0..7)); my ($M0,$T0a,$T0b,$T0c,$T0d,$T0e,$T0f,$TMP0)=map("%xmm$_",(8..15)); my ($M1,$T2a,$T2b,$TMP2,$M2,$T2a,$T2b,$TMP2)=map("%xmm$_",(8..15)); $code.=<<___; ################################################################################ # void ecp_nistz256_select_w5(uint64_t *val, uint64_t *in_t, int index); .globl ecp_nistz256_select_w5 .type ecp_nistz256_select_w5,\@abi-omnipotent .align 32 ecp_nistz256_select_w5: ___ $code.=<<___ if ($avx>1); mov OPENSSL_ia32cap_P+8(%rip), %eax test \$`1<<5`, %eax jnz .Lavx2_select_w5 ___ $code.=<<___ if ($win64); lea -0x88(%rsp), %rax .LSEH_begin_ecp_nistz256_select_w5: .byte 0x48,0x8d,0x60,0xe0 #lea -0x20(%rax), %rsp .byte 0x0f,0x29,0x70,0xe0 #movaps %xmm6, -0x20(%rax) .byte 0x0f,0x29,0x78,0xf0 #movaps %xmm7, -0x10(%rax) .byte 0x44,0x0f,0x29,0x00 #movaps %xmm8, 0(%rax) .byte 0x44,0x0f,0x29,0x48,0x10 #movaps %xmm9, 0x10(%rax) .byte 0x44,0x0f,0x29,0x50,0x20 #movaps %xmm10, 0x20(%rax) .byte 0x44,0x0f,0x29,0x58,0x30 #movaps %xmm11, 0x30(%rax) .byte 0x44,0x0f,0x29,0x60,0x40 #movaps %xmm12, 0x40(%rax) .byte 0x44,0x0f,0x29,0x68,0x50 #movaps %xmm13, 0x50(%rax) .byte 0x44,0x0f,0x29,0x70,0x60 #movaps %xmm14, 0x60(%rax) .byte 0x44,0x0f,0x29,0x78,0x70 #movaps %xmm15, 0x70(%rax) ___ $code.=<<___; movdqa .LOne(%rip), $ONE movd $index, $INDEX pxor $Ra, $Ra pxor $Rb, $Rb pxor $Rc, $Rc pxor $Rd, $Rd pxor $Re, $Re pxor $Rf, $Rf movdqa $ONE, $M0 pshufd \$0, $INDEX, $INDEX mov \$16, %rax .Lselect_loop_sse_w5: movdqa $M0, $TMP0 paddd $ONE, $M0 pcmpeqd $INDEX, $TMP0 movdqa 16*0($in_t), $T0a movdqa 16*1($in_t), $T0b movdqa 16*2($in_t), $T0c movdqa 16*3($in_t), $T0d movdqa 16*4($in_t), $T0e movdqa 16*5($in_t), $T0f lea 16*6($in_t), $in_t pand $TMP0, $T0a pand $TMP0, $T0b por $T0a, $Ra pand $TMP0, $T0c por $T0b, $Rb pand $TMP0, $T0d por $T0c, $Rc pand $TMP0, $T0e por $T0d, $Rd pand $TMP0, $T0f por $T0e, $Re por $T0f, $Rf dec %rax jnz .Lselect_loop_sse_w5 movdqu $Ra, 16*0($val) movdqu $Rb, 16*1($val) movdqu $Rc, 16*2($val) movdqu $Rd, 16*3($val) movdqu $Re, 16*4($val) movdqu $Rf, 16*5($val) ___ $code.=<<___ if ($win64); movaps (%rsp), %xmm6 movaps 0x10(%rsp), %xmm7 movaps 0x20(%rsp), %xmm8 movaps 0x30(%rsp), %xmm9 movaps 0x40(%rsp), %xmm10 movaps 0x50(%rsp), %xmm11 movaps 0x60(%rsp), %xmm12 movaps 0x70(%rsp), %xmm13 movaps 0x80(%rsp), %xmm14 movaps 0x90(%rsp), %xmm15 lea 0xa8(%rsp), %rsp .LSEH_end_ecp_nistz256_select_w5: ___ $code.=<<___; ret .size ecp_nistz256_select_w5,.-ecp_nistz256_select_w5 ################################################################################ # void ecp_nistz256_select_w7(uint64_t *val, uint64_t *in_t, int index); .globl ecp_nistz256_select_w7 .type ecp_nistz256_select_w7,\@abi-omnipotent .align 32 ecp_nistz256_select_w7: ___ $code.=<<___ if ($avx>1); mov OPENSSL_ia32cap_P+8(%rip), %eax test \$`1<<5`, %eax jnz .Lavx2_select_w7 ___ $code.=<<___ if ($win64); lea -0x88(%rsp), %rax .LSEH_begin_ecp_nistz256_select_w7: .byte 0x48,0x8d,0x60,0xe0 #lea -0x20(%rax), %rsp .byte 0x0f,0x29,0x70,0xe0 #movaps %xmm6, -0x20(%rax) .byte 0x0f,0x29,0x78,0xf0 #movaps %xmm7, -0x10(%rax) .byte 0x44,0x0f,0x29,0x00 #movaps %xmm8, 0(%rax) .byte 0x44,0x0f,0x29,0x48,0x10 #movaps %xmm9, 0x10(%rax) .byte 0x44,0x0f,0x29,0x50,0x20 #movaps %xmm10, 0x20(%rax) .byte 0x44,0x0f,0x29,0x58,0x30 #movaps %xmm11, 0x30(%rax) .byte 0x44,0x0f,0x29,0x60,0x40 #movaps %xmm12, 0x40(%rax) .byte 0x44,0x0f,0x29,0x68,0x50 #movaps %xmm13, 0x50(%rax) .byte 0x44,0x0f,0x29,0x70,0x60 #movaps %xmm14, 0x60(%rax) .byte 0x44,0x0f,0x29,0x78,0x70 #movaps %xmm15, 0x70(%rax) ___ $code.=<<___; movdqa .LOne(%rip), $M0 movd $index, $INDEX pxor $Ra, $Ra pxor $Rb, $Rb pxor $Rc, $Rc pxor $Rd, $Rd movdqa $M0, $ONE pshufd \$0, $INDEX, $INDEX mov \$64, %rax .Lselect_loop_sse_w7: movdqa $M0, $TMP0 paddd $ONE, $M0 movdqa 16*0($in_t), $T0a movdqa 16*1($in_t), $T0b pcmpeqd $INDEX, $TMP0 movdqa 16*2($in_t), $T0c movdqa 16*3($in_t), $T0d lea 16*4($in_t), $in_t pand $TMP0, $T0a pand $TMP0, $T0b por $T0a, $Ra pand $TMP0, $T0c por $T0b, $Rb pand $TMP0, $T0d por $T0c, $Rc prefetcht0 255($in_t) por $T0d, $Rd dec %rax jnz .Lselect_loop_sse_w7 movdqu $Ra, 16*0($val) movdqu $Rb, 16*1($val) movdqu $Rc, 16*2($val) movdqu $Rd, 16*3($val) ___ $code.=<<___ if ($win64); movaps (%rsp), %xmm6 movaps 0x10(%rsp), %xmm7 movaps 0x20(%rsp), %xmm8 movaps 0x30(%rsp), %xmm9 movaps 0x40(%rsp), %xmm10 movaps 0x50(%rsp), %xmm11 movaps 0x60(%rsp), %xmm12 movaps 0x70(%rsp), %xmm13 movaps 0x80(%rsp), %xmm14 movaps 0x90(%rsp), %xmm15 lea 0xa8(%rsp), %rsp .LSEH_end_ecp_nistz256_select_w7: ___ $code.=<<___; ret .size ecp_nistz256_select_w7,.-ecp_nistz256_select_w7 ___ } if ($avx>1) { my ($val,$in_t,$index)=$win64?("%rcx","%rdx","%r8d"):("%rdi","%rsi","%edx"); my ($TWO,$INDEX,$Ra,$Rb,$Rc)=map("%ymm$_",(0..4)); my ($M0,$T0a,$T0b,$T0c,$TMP0)=map("%ymm$_",(5..9)); my ($M1,$T1a,$T1b,$T1c,$TMP1)=map("%ymm$_",(10..14)); $code.=<<___; ################################################################################ # void ecp_nistz256_avx2_select_w5(uint64_t *val, uint64_t *in_t, int index); .type ecp_nistz256_avx2_select_w5,\@abi-omnipotent .align 32 ecp_nistz256_avx2_select_w5: .Lavx2_select_w5: vzeroupper ___ $code.=<<___ if ($win64); lea -0x88(%rsp), %rax .LSEH_begin_ecp_nistz256_avx2_select_w5: .byte 0x48,0x8d,0x60,0xe0 #lea -0x20(%rax), %rsp .byte 0xc5,0xf8,0x29,0x70,0xe0 #vmovaps %xmm6, -0x20(%rax) .byte 0xc5,0xf8,0x29,0x78,0xf0 #vmovaps %xmm7, -0x10(%rax) .byte 0xc5,0x78,0x29,0x40,0x00 #vmovaps %xmm8, 8(%rax) .byte 0xc5,0x78,0x29,0x48,0x10 #vmovaps %xmm9, 0x10(%rax) .byte 0xc5,0x78,0x29,0x50,0x20 #vmovaps %xmm10, 0x20(%rax) .byte 0xc5,0x78,0x29,0x58,0x30 #vmovaps %xmm11, 0x30(%rax) .byte 0xc5,0x78,0x29,0x60,0x40 #vmovaps %xmm12, 0x40(%rax) .byte 0xc5,0x78,0x29,0x68,0x50 #vmovaps %xmm13, 0x50(%rax) .byte 0xc5,0x78,0x29,0x70,0x60 #vmovaps %xmm14, 0x60(%rax) .byte 0xc5,0x78,0x29,0x78,0x70 #vmovaps %xmm15, 0x70(%rax) ___ $code.=<<___; vmovdqa .LTwo(%rip), $TWO vpxor $Ra, $Ra, $Ra vpxor $Rb, $Rb, $Rb vpxor $Rc, $Rc, $Rc vmovdqa .LOne(%rip), $M0 vmovdqa .LTwo(%rip), $M1 vmovd $index, %xmm1 vpermd $INDEX, $Ra, $INDEX mov \$8, %rax .Lselect_loop_avx2_w5: vmovdqa 32*0($in_t), $T0a vmovdqa 32*1($in_t), $T0b vmovdqa 32*2($in_t), $T0c vmovdqa 32*3($in_t), $T1a vmovdqa 32*4($in_t), $T1b vmovdqa 32*5($in_t), $T1c vpcmpeqd $INDEX, $M0, $TMP0 vpcmpeqd $INDEX, $M1, $TMP1 vpaddd $TWO, $M0, $M0 vpaddd $TWO, $M1, $M1 lea 32*6($in_t), $in_t vpand $TMP0, $T0a, $T0a vpand $TMP0, $T0b, $T0b vpand $TMP0, $T0c, $T0c vpand $TMP1, $T1a, $T1a vpand $TMP1, $T1b, $T1b vpand $TMP1, $T1c, $T1c vpxor $T0a, $Ra, $Ra vpxor $T0b, $Rb, $Rb vpxor $T0c, $Rc, $Rc vpxor $T1a, $Ra, $Ra vpxor $T1b, $Rb, $Rb vpxor $T1c, $Rc, $Rc dec %rax jnz .Lselect_loop_avx2_w5 vmovdqu $Ra, 32*0($val) vmovdqu $Rb, 32*1($val) vmovdqu $Rc, 32*2($val) vzeroupper ___ $code.=<<___ if ($win64); movaps (%rsp), %xmm6 movaps 0x10(%rsp), %xmm7 movaps 0x20(%rsp), %xmm8 movaps 0x30(%rsp), %xmm9 movaps 0x40(%rsp), %xmm10 movaps 0x50(%rsp), %xmm11 movaps 0x60(%rsp), %xmm12 movaps 0x70(%rsp), %xmm13 movaps 0x80(%rsp), %xmm14 movaps 0x90(%rsp), %xmm15 lea 0xa8(%rsp), %rsp .LSEH_end_ecp_nistz256_avx2_select_w5: ___ $code.=<<___; ret .size ecp_nistz256_avx2_select_w5,.-ecp_nistz256_avx2_select_w5 ___ } if ($avx>1) { my ($val,$in_t,$index)=$win64?("%rcx","%rdx","%r8d"):("%rdi","%rsi","%edx"); my ($THREE,$INDEX,$Ra,$Rb)=map("%ymm$_",(0..3)); my ($M0,$T0a,$T0b,$TMP0)=map("%ymm$_",(4..7)); my ($M1,$T1a,$T1b,$TMP1)=map("%ymm$_",(8..11)); my ($M2,$T2a,$T2b,$TMP2)=map("%ymm$_",(12..15)); $code.=<<___; ################################################################################ # void ecp_nistz256_avx2_select_w7(uint64_t *val, uint64_t *in_t, int index); .globl ecp_nistz256_avx2_select_w7 .type ecp_nistz256_avx2_select_w7,\@abi-omnipotent .align 32 ecp_nistz256_avx2_select_w7: .Lavx2_select_w7: vzeroupper ___ $code.=<<___ if ($win64); lea -0x88(%rsp), %rax .LSEH_begin_ecp_nistz256_avx2_select_w7: .byte 0x48,0x8d,0x60,0xe0 #lea -0x20(%rax), %rsp .byte 0xc5,0xf8,0x29,0x70,0xe0 #vmovaps %xmm6, -0x20(%rax) .byte 0xc5,0xf8,0x29,0x78,0xf0 #vmovaps %xmm7, -0x10(%rax) .byte 0xc5,0x78,0x29,0x40,0x00 #vmovaps %xmm8, 8(%rax) .byte 0xc5,0x78,0x29,0x48,0x10 #vmovaps %xmm9, 0x10(%rax) .byte 0xc5,0x78,0x29,0x50,0x20 #vmovaps %xmm10, 0x20(%rax) .byte 0xc5,0x78,0x29,0x58,0x30 #vmovaps %xmm11, 0x30(%rax) .byte 0xc5,0x78,0x29,0x60,0x40 #vmovaps %xmm12, 0x40(%rax) .byte 0xc5,0x78,0x29,0x68,0x50 #vmovaps %xmm13, 0x50(%rax) .byte 0xc5,0x78,0x29,0x70,0x60 #vmovaps %xmm14, 0x60(%rax) .byte 0xc5,0x78,0x29,0x78,0x70 #vmovaps %xmm15, 0x70(%rax) ___ $code.=<<___; vmovdqa .LThree(%rip), $THREE vpxor $Ra, $Ra, $Ra vpxor $Rb, $Rb, $Rb vmovdqa .LOne(%rip), $M0 vmovdqa .LTwo(%rip), $M1 vmovdqa .LThree(%rip), $M2 vmovd $index, %xmm1 vpermd $INDEX, $Ra, $INDEX # Skip index = 0, because it is implicitly the point at infinity mov \$21, %rax .Lselect_loop_avx2_w7: vmovdqa 32*0($in_t), $T0a vmovdqa 32*1($in_t), $T0b vmovdqa 32*2($in_t), $T1a vmovdqa 32*3($in_t), $T1b vmovdqa 32*4($in_t), $T2a vmovdqa 32*5($in_t), $T2b vpcmpeqd $INDEX, $M0, $TMP0 vpcmpeqd $INDEX, $M1, $TMP1 vpcmpeqd $INDEX, $M2, $TMP2 vpaddd $THREE, $M0, $M0 vpaddd $THREE, $M1, $M1 vpaddd $THREE, $M2, $M2 lea 32*6($in_t), $in_t vpand $TMP0, $T0a, $T0a vpand $TMP0, $T0b, $T0b vpand $TMP1, $T1a, $T1a vpand $TMP1, $T1b, $T1b vpand $TMP2, $T2a, $T2a vpand $TMP2, $T2b, $T2b vpxor $T0a, $Ra, $Ra vpxor $T0b, $Rb, $Rb vpxor $T1a, $Ra, $Ra vpxor $T1b, $Rb, $Rb vpxor $T2a, $Ra, $Ra vpxor $T2b, $Rb, $Rb dec %rax jnz .Lselect_loop_avx2_w7 vmovdqa 32*0($in_t), $T0a vmovdqa 32*1($in_t), $T0b vpcmpeqd $INDEX, $M0, $TMP0 vpand $TMP0, $T0a, $T0a vpand $TMP0, $T0b, $T0b vpxor $T0a, $Ra, $Ra vpxor $T0b, $Rb, $Rb vmovdqu $Ra, 32*0($val) vmovdqu $Rb, 32*1($val) vzeroupper ___ $code.=<<___ if ($win64); movaps (%rsp), %xmm6 movaps 0x10(%rsp), %xmm7 movaps 0x20(%rsp), %xmm8 movaps 0x30(%rsp), %xmm9 movaps 0x40(%rsp), %xmm10 movaps 0x50(%rsp), %xmm11 movaps 0x60(%rsp), %xmm12 movaps 0x70(%rsp), %xmm13 movaps 0x80(%rsp), %xmm14 movaps 0x90(%rsp), %xmm15 lea 0xa8(%rsp), %rsp .LSEH_end_ecp_nistz256_avx2_select_w7: ___ $code.=<<___; ret .size ecp_nistz256_avx2_select_w7,.-ecp_nistz256_avx2_select_w7 ___ } else { $code.=<<___; .globl ecp_nistz256_avx2_select_w7 .type ecp_nistz256_avx2_select_w7,\@function,3 .align 32 ecp_nistz256_avx2_select_w7: .byte 0x0f,0x0b # ud2 ret .size ecp_nistz256_avx2_select_w7,.-ecp_nistz256_avx2_select_w7 ___ } {{{ ######################################################################## # This block implements higher level point_double, point_add and # point_add_affine. The key to performance in this case is to allow # out-of-order execution logic to overlap computations from next step # with tail processing from current step. By using tailored calling # sequence we minimize inter-step overhead to give processor better # shot at overlapping operations... # # You will notice that input data is copied to stack. Trouble is that # there are no registers to spare for holding original pointers and # reloading them, pointers, would create undesired dependencies on # effective addresses calculation paths. In other words it's too done # to favour out-of-order execution logic. # my ($r_ptr,$a_ptr,$b_org,$b_ptr)=("%rdi","%rsi","%rdx","%rbx"); my ($acc0,$acc1,$acc2,$acc3,$acc4,$acc5,$acc6,$acc7)=map("%r$_",(8..15)); my ($t0,$t1,$t2,$t3,$t4)=("%rax","%rbp","%rcx",$acc4,$acc4); my ($poly1,$poly3)=($acc6,$acc7); sub load_for_mul () { my ($a,$b,$src0) = @_; my $bias = $src0 eq "%rax" ? 0 : -128; " mov $b, $src0 lea $b, $b_ptr mov 8*0+$a, $acc1 mov 8*1+$a, $acc2 lea $bias+$a, $a_ptr mov 8*2+$a, $acc3 mov 8*3+$a, $acc4" } sub load_for_sqr () { my ($a,$src0) = @_; my $bias = $src0 eq "%rax" ? 0 : -128; " mov 8*0+$a, $src0 mov 8*1+$a, $acc6 lea $bias+$a, $a_ptr mov 8*2+$a, $acc7 mov 8*3+$a, $acc0" } { ######################################################################## # operate in 4-5-0-1 "name space" that matches multiplication output # my ($a0,$a1,$a2,$a3,$t3,$t4)=($acc4,$acc5,$acc0,$acc1,$acc2,$acc3); $code.=<<___; .type __ecp_nistz256_add_toq,\@abi-omnipotent .align 32 __ecp_nistz256_add_toq: xor $t4,$t4 add 8*0($b_ptr), $a0 adc 8*1($b_ptr), $a1 mov $a0, $t0 adc 8*2($b_ptr), $a2 adc 8*3($b_ptr), $a3 mov $a1, $t1 adc \$0, $t4 sub \$-1, $a0 mov $a2, $t2 sbb $poly1, $a1 sbb \$0, $a2 mov $a3, $t3 sbb $poly3, $a3 sbb \$0, $t4 cmovc $t0, $a0 cmovc $t1, $a1 mov $a0, 8*0($r_ptr) cmovc $t2, $a2 mov $a1, 8*1($r_ptr) cmovc $t3, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) ret .size __ecp_nistz256_add_toq,.-__ecp_nistz256_add_toq .type __ecp_nistz256_sub_fromq,\@abi-omnipotent .align 32 __ecp_nistz256_sub_fromq: sub 8*0($b_ptr), $a0 sbb 8*1($b_ptr), $a1 mov $a0, $t0 sbb 8*2($b_ptr), $a2 sbb 8*3($b_ptr), $a3 mov $a1, $t1 sbb $t4, $t4 add \$-1, $a0 mov $a2, $t2 adc $poly1, $a1 adc \$0, $a2 mov $a3, $t3 adc $poly3, $a3 test $t4, $t4 cmovz $t0, $a0 cmovz $t1, $a1 mov $a0, 8*0($r_ptr) cmovz $t2, $a2 mov $a1, 8*1($r_ptr) cmovz $t3, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) ret .size __ecp_nistz256_sub_fromq,.-__ecp_nistz256_sub_fromq .type __ecp_nistz256_subq,\@abi-omnipotent .align 32 __ecp_nistz256_subq: sub $a0, $t0 sbb $a1, $t1 mov $t0, $a0 sbb $a2, $t2 sbb $a3, $t3 mov $t1, $a1 sbb $t4, $t4 add \$-1, $t0 mov $t2, $a2 adc $poly1, $t1 adc \$0, $t2 mov $t3, $a3 adc $poly3, $t3 test $t4, $t4 cmovnz $t0, $a0 cmovnz $t1, $a1 cmovnz $t2, $a2 cmovnz $t3, $a3 ret .size __ecp_nistz256_subq,.-__ecp_nistz256_subq .type __ecp_nistz256_mul_by_2q,\@abi-omnipotent .align 32 __ecp_nistz256_mul_by_2q: xor $t4, $t4 add $a0, $a0 # a0:a3+a0:a3 adc $a1, $a1 mov $a0, $t0 adc $a2, $a2 adc $a3, $a3 mov $a1, $t1 adc \$0, $t4 sub \$-1, $a0 mov $a2, $t2 sbb $poly1, $a1 sbb \$0, $a2 mov $a3, $t3 sbb $poly3, $a3 sbb \$0, $t4 cmovc $t0, $a0 cmovc $t1, $a1 mov $a0, 8*0($r_ptr) cmovc $t2, $a2 mov $a1, 8*1($r_ptr) cmovc $t3, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) ret .size __ecp_nistz256_mul_by_2q,.-__ecp_nistz256_mul_by_2q ___ } sub gen_double () { my $x = shift; my ($src0,$sfx,$bias); my ($S,$M,$Zsqr,$in_x,$tmp0)=map(32*$_,(0..4)); if ($x ne "x") { $src0 = "%rax"; $sfx = ""; $bias = 0; $code.=<<___; .globl ecp_nistz256_point_double .type ecp_nistz256_point_double,\@function,2 .align 32 ecp_nistz256_point_double: ___ $code.=<<___ if ($addx); mov \$0x80100, %ecx and OPENSSL_ia32cap_P+8(%rip), %ecx cmp \$0x80100, %ecx je .Lpoint_doublex ___ } else { $src0 = "%rdx"; $sfx = "x"; $bias = 128; $code.=<<___; .type ecp_nistz256_point_doublex,\@function,2 .align 32 ecp_nistz256_point_doublex: .Lpoint_doublex: ___ } $code.=<<___; push %rbp push %rbx push %r12 push %r13 push %r14 push %r15 sub \$32*5+8, %rsp .Lpoint_double_shortcut$x: movdqu 0x00($a_ptr), %xmm0 # copy *(P256_POINT *)$a_ptr.x mov $a_ptr, $b_ptr # backup copy movdqu 0x10($a_ptr), %xmm1 mov 0x20+8*0($a_ptr), $acc4 # load in_y in "5-4-0-1" order mov 0x20+8*1($a_ptr), $acc5 mov 0x20+8*2($a_ptr), $acc0 mov 0x20+8*3($a_ptr), $acc1 mov .Lpoly+8*1(%rip), $poly1 mov .Lpoly+8*3(%rip), $poly3 movdqa %xmm0, $in_x(%rsp) movdqa %xmm1, $in_x+0x10(%rsp) lea 0x20($r_ptr), $acc2 lea 0x40($r_ptr), $acc3 movq $r_ptr, %xmm0 movq $acc2, %xmm1 movq $acc3, %xmm2 lea $S(%rsp), $r_ptr call __ecp_nistz256_mul_by_2$x # p256_mul_by_2(S, in_y); mov 0x40+8*0($a_ptr), $src0 mov 0x40+8*1($a_ptr), $acc6 mov 0x40+8*2($a_ptr), $acc7 mov 0x40+8*3($a_ptr), $acc0 lea 0x40-$bias($a_ptr), $a_ptr lea $Zsqr(%rsp), $r_ptr call __ecp_nistz256_sqr_mont$x # p256_sqr_mont(Zsqr, in_z); `&load_for_sqr("$S(%rsp)", "$src0")` lea $S(%rsp), $r_ptr call __ecp_nistz256_sqr_mont$x # p256_sqr_mont(S, S); mov 0x20($b_ptr), $src0 # $b_ptr is still valid mov 0x40+8*0($b_ptr), $acc1 mov 0x40+8*1($b_ptr), $acc2 mov 0x40+8*2($b_ptr), $acc3 mov 0x40+8*3($b_ptr), $acc4 lea 0x40-$bias($b_ptr), $a_ptr lea 0x20($b_ptr), $b_ptr movq %xmm2, $r_ptr call __ecp_nistz256_mul_mont$x # p256_mul_mont(res_z, in_z, in_y); call __ecp_nistz256_mul_by_2$x # p256_mul_by_2(res_z, res_z); mov $in_x+8*0(%rsp), $acc4 # "5-4-0-1" order mov $in_x+8*1(%rsp), $acc5 lea $Zsqr(%rsp), $b_ptr mov $in_x+8*2(%rsp), $acc0 mov $in_x+8*3(%rsp), $acc1 lea $M(%rsp), $r_ptr call __ecp_nistz256_add_to$x # p256_add(M, in_x, Zsqr); mov $in_x+8*0(%rsp), $acc4 # "5-4-0-1" order mov $in_x+8*1(%rsp), $acc5 lea $Zsqr(%rsp), $b_ptr mov $in_x+8*2(%rsp), $acc0 mov $in_x+8*3(%rsp), $acc1 lea $Zsqr(%rsp), $r_ptr call __ecp_nistz256_sub_from$x # p256_sub(Zsqr, in_x, Zsqr); `&load_for_sqr("$S(%rsp)", "$src0")` movq %xmm1, $r_ptr call __ecp_nistz256_sqr_mont$x # p256_sqr_mont(res_y, S); ___ { ######## ecp_nistz256_div_by_2(res_y, res_y); ########################## # operate in 4-5-6-7 "name space" that matches squaring output # my ($poly1,$poly3)=($a_ptr,$t1); my ($a0,$a1,$a2,$a3,$t3,$t4,$t1)=($acc4,$acc5,$acc6,$acc7,$acc0,$acc1,$acc2); $code.=<<___; xor $t4, $t4 mov $a0, $t0 add \$-1, $a0 mov $a1, $t1 adc $poly1, $a1 mov $a2, $t2 adc \$0, $a2 mov $a3, $t3 adc $poly3, $a3 adc \$0, $t4 xor $a_ptr, $a_ptr # borrow $a_ptr test \$1, $t0 cmovz $t0, $a0 cmovz $t1, $a1 cmovz $t2, $a2 cmovz $t3, $a3 cmovz $a_ptr, $t4 mov $a1, $t0 # a0:a3>>1 shr \$1, $a0 shl \$63, $t0 mov $a2, $t1 shr \$1, $a1 or $t0, $a0 shl \$63, $t1 mov $a3, $t2 shr \$1, $a2 or $t1, $a1 shl \$63, $t2 mov $a0, 8*0($r_ptr) shr \$1, $a3 mov $a1, 8*1($r_ptr) shl \$63, $t4 or $t2, $a2 or $t4, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) ___ } $code.=<<___; `&load_for_mul("$M(%rsp)", "$Zsqr(%rsp)", "$src0")` lea $M(%rsp), $r_ptr call __ecp_nistz256_mul_mont$x # p256_mul_mont(M, M, Zsqr); lea $tmp0(%rsp), $r_ptr call __ecp_nistz256_mul_by_2$x lea $M(%rsp), $b_ptr lea $M(%rsp), $r_ptr call __ecp_nistz256_add_to$x # p256_mul_by_3(M, M); `&load_for_mul("$S(%rsp)", "$in_x(%rsp)", "$src0")` lea $S(%rsp), $r_ptr call __ecp_nistz256_mul_mont$x # p256_mul_mont(S, S, in_x); lea $tmp0(%rsp), $r_ptr call __ecp_nistz256_mul_by_2$x # p256_mul_by_2(tmp0, S); `&load_for_sqr("$M(%rsp)", "$src0")` movq %xmm0, $r_ptr call __ecp_nistz256_sqr_mont$x # p256_sqr_mont(res_x, M); lea $tmp0(%rsp), $b_ptr mov $acc6, $acc0 # harmonize sqr output and sub input mov $acc7, $acc1 mov $a_ptr, $poly1 mov $t1, $poly3 call __ecp_nistz256_sub_from$x # p256_sub(res_x, res_x, tmp0); mov $S+8*0(%rsp), $t0 mov $S+8*1(%rsp), $t1 mov $S+8*2(%rsp), $t2 mov $S+8*3(%rsp), $acc2 # "4-5-0-1" order lea $S(%rsp), $r_ptr call __ecp_nistz256_sub$x # p256_sub(S, S, res_x); mov $M(%rsp), $src0 lea $M(%rsp), $b_ptr mov $acc4, $acc6 # harmonize sub output and mul input xor %ecx, %ecx mov $acc4, $S+8*0(%rsp) # have to save:-( mov $acc5, $acc2 mov $acc5, $S+8*1(%rsp) cmovz $acc0, $acc3 mov $acc0, $S+8*2(%rsp) lea $S-$bias(%rsp), $a_ptr cmovz $acc1, $acc4 mov $acc1, $S+8*3(%rsp) mov $acc6, $acc1 lea $S(%rsp), $r_ptr call __ecp_nistz256_mul_mont$x # p256_mul_mont(S, S, M); movq %xmm1, $b_ptr movq %xmm1, $r_ptr call __ecp_nistz256_sub_from$x # p256_sub(res_y, S, res_y); add \$32*5+8, %rsp pop %r15 pop %r14 pop %r13 pop %r12 pop %rbx pop %rbp ret .size ecp_nistz256_point_double$sfx,.-ecp_nistz256_point_double$sfx ___ } &gen_double("q"); sub gen_add () { my $x = shift; my ($src0,$sfx,$bias); my ($H,$Hsqr,$R,$Rsqr,$Hcub, $U1,$U2,$S1,$S2, $res_x,$res_y,$res_z, $in1_x,$in1_y,$in1_z, $in2_x,$in2_y,$in2_z)=map(32*$_,(0..17)); my ($Z1sqr, $Z2sqr) = ($Hsqr, $Rsqr); if ($x ne "x") { $src0 = "%rax"; $sfx = ""; $bias = 0; $code.=<<___; .globl ecp_nistz256_point_add .type ecp_nistz256_point_add,\@function,3 .align 32 ecp_nistz256_point_add: ___ $code.=<<___ if ($addx); mov \$0x80100, %ecx and OPENSSL_ia32cap_P+8(%rip), %ecx cmp \$0x80100, %ecx je .Lpoint_addx ___ } else { $src0 = "%rdx"; $sfx = "x"; $bias = 128; $code.=<<___; .type ecp_nistz256_point_addx,\@function,3 .align 32 ecp_nistz256_point_addx: .Lpoint_addx: ___ } $code.=<<___; push %rbp push %rbx push %r12 push %r13 push %r14 push %r15 sub \$32*18+8, %rsp movdqu 0x00($a_ptr), %xmm0 # copy *(P256_POINT *)$a_ptr movdqu 0x10($a_ptr), %xmm1 movdqu 0x20($a_ptr), %xmm2 movdqu 0x30($a_ptr), %xmm3 movdqu 0x40($a_ptr), %xmm4 movdqu 0x50($a_ptr), %xmm5 mov $a_ptr, $b_ptr # reassign mov $b_org, $a_ptr # reassign movdqa %xmm0, $in1_x(%rsp) movdqa %xmm1, $in1_x+0x10(%rsp) movdqa %xmm2, $in1_y(%rsp) movdqa %xmm3, $in1_y+0x10(%rsp) movdqa %xmm4, $in1_z(%rsp) movdqa %xmm5, $in1_z+0x10(%rsp) por %xmm4, %xmm5 movdqu 0x00($a_ptr), %xmm0 # copy *(P256_POINT *)$b_ptr pshufd \$0xb1, %xmm5, %xmm3 movdqu 0x10($a_ptr), %xmm1 movdqu 0x20($a_ptr), %xmm2 por %xmm3, %xmm5 movdqu 0x30($a_ptr), %xmm3 mov 0x40+8*0($a_ptr), $src0 # load original in2_z mov 0x40+8*1($a_ptr), $acc6 mov 0x40+8*2($a_ptr), $acc7 mov 0x40+8*3($a_ptr), $acc0 movdqa %xmm0, $in2_x(%rsp) pshufd \$0x1e, %xmm5, %xmm4 movdqa %xmm1, $in2_x+0x10(%rsp) movdqu 0x40($a_ptr),%xmm0 # in2_z again movdqu 0x50($a_ptr),%xmm1 movdqa %xmm2, $in2_y(%rsp) movdqa %xmm3, $in2_y+0x10(%rsp) por %xmm4, %xmm5 pxor %xmm4, %xmm4 por %xmm0, %xmm1 movq $r_ptr, %xmm0 # save $r_ptr lea 0x40-$bias($a_ptr), $a_ptr # $a_ptr is still valid mov $src0, $in2_z+8*0(%rsp) # make in2_z copy mov $acc6, $in2_z+8*1(%rsp) mov $acc7, $in2_z+8*2(%rsp) mov $acc0, $in2_z+8*3(%rsp) lea $Z2sqr(%rsp), $r_ptr # Z2^2 call __ecp_nistz256_sqr_mont$x # p256_sqr_mont(Z2sqr, in2_z); pcmpeqd %xmm4, %xmm5 pshufd \$0xb1, %xmm1, %xmm4 por %xmm1, %xmm4 pshufd \$0, %xmm5, %xmm5 # in1infty pshufd \$0x1e, %xmm4, %xmm3 por %xmm3, %xmm4 pxor %xmm3, %xmm3 pcmpeqd %xmm3, %xmm4 pshufd \$0, %xmm4, %xmm4 # in2infty mov 0x40+8*0($b_ptr), $src0 # load original in1_z mov 0x40+8*1($b_ptr), $acc6 mov 0x40+8*2($b_ptr), $acc7 mov 0x40+8*3($b_ptr), $acc0 movq $b_ptr, %xmm1 lea 0x40-$bias($b_ptr), $a_ptr lea $Z1sqr(%rsp), $r_ptr # Z1^2 call __ecp_nistz256_sqr_mont$x # p256_sqr_mont(Z1sqr, in1_z); `&load_for_mul("$Z2sqr(%rsp)", "$in2_z(%rsp)", "$src0")` lea $S1(%rsp), $r_ptr # S1 = Z2^3 call __ecp_nistz256_mul_mont$x # p256_mul_mont(S1, Z2sqr, in2_z); `&load_for_mul("$Z1sqr(%rsp)", "$in1_z(%rsp)", "$src0")` lea $S2(%rsp), $r_ptr # S2 = Z1^3 call __ecp_nistz256_mul_mont$x # p256_mul_mont(S2, Z1sqr, in1_z); `&load_for_mul("$S1(%rsp)", "$in1_y(%rsp)", "$src0")` lea $S1(%rsp), $r_ptr # S1 = Y1*Z2^3 call __ecp_nistz256_mul_mont$x # p256_mul_mont(S1, S1, in1_y); `&load_for_mul("$S2(%rsp)", "$in2_y(%rsp)", "$src0")` lea $S2(%rsp), $r_ptr # S2 = Y2*Z1^3 call __ecp_nistz256_mul_mont$x # p256_mul_mont(S2, S2, in2_y); lea $S1(%rsp), $b_ptr lea $R(%rsp), $r_ptr # R = S2 - S1 call __ecp_nistz256_sub_from$x # p256_sub(R, S2, S1); or $acc5, $acc4 # see if result is zero movdqa %xmm4, %xmm2 or $acc0, $acc4 or $acc1, $acc4 por %xmm5, %xmm2 # in1infty || in2infty movq $acc4, %xmm3 `&load_for_mul("$Z2sqr(%rsp)", "$in1_x(%rsp)", "$src0")` lea $U1(%rsp), $r_ptr # U1 = X1*Z2^2 call __ecp_nistz256_mul_mont$x # p256_mul_mont(U1, in1_x, Z2sqr); `&load_for_mul("$Z1sqr(%rsp)", "$in2_x(%rsp)", "$src0")` lea $U2(%rsp), $r_ptr # U2 = X2*Z1^2 call __ecp_nistz256_mul_mont$x # p256_mul_mont(U2, in2_x, Z1sqr); lea $U1(%rsp), $b_ptr lea $H(%rsp), $r_ptr # H = U2 - U1 call __ecp_nistz256_sub_from$x # p256_sub(H, U2, U1); or $acc5, $acc4 # see if result is zero or $acc0, $acc4 or $acc1, $acc4 .byte 0x3e # predict taken jnz .Ladd_proceed$x # is_equal(U1,U2)? movq %xmm2, $acc0 movq %xmm3, $acc1 test $acc0, $acc0 jnz .Ladd_proceed$x # (in1infty || in2infty)? test $acc1, $acc1 jz .Ladd_double$x # is_equal(S1,S2)? movq %xmm0, $r_ptr # restore $r_ptr pxor %xmm0, %xmm0 movdqu %xmm0, 0x00($r_ptr) movdqu %xmm0, 0x10($r_ptr) movdqu %xmm0, 0x20($r_ptr) movdqu %xmm0, 0x30($r_ptr) movdqu %xmm0, 0x40($r_ptr) movdqu %xmm0, 0x50($r_ptr) jmp .Ladd_done$x .align 32 .Ladd_double$x: movq %xmm1, $a_ptr # restore $a_ptr movq %xmm0, $r_ptr # restore $r_ptr add \$`32*(18-5)`, %rsp # difference in frame sizes jmp .Lpoint_double_shortcut$x .align 32 .Ladd_proceed$x: `&load_for_sqr("$R(%rsp)", "$src0")` lea $Rsqr(%rsp), $r_ptr # R^2 call __ecp_nistz256_sqr_mont$x # p256_sqr_mont(Rsqr, R); `&load_for_mul("$H(%rsp)", "$in1_z(%rsp)", "$src0")` lea $res_z(%rsp), $r_ptr # Z3 = H*Z1*Z2 call __ecp_nistz256_mul_mont$x # p256_mul_mont(res_z, H, in1_z); `&load_for_sqr("$H(%rsp)", "$src0")` lea $Hsqr(%rsp), $r_ptr # H^2 call __ecp_nistz256_sqr_mont$x # p256_sqr_mont(Hsqr, H); `&load_for_mul("$res_z(%rsp)", "$in2_z(%rsp)", "$src0")` lea $res_z(%rsp), $r_ptr # Z3 = H*Z1*Z2 call __ecp_nistz256_mul_mont$x # p256_mul_mont(res_z, res_z, in2_z); `&load_for_mul("$Hsqr(%rsp)", "$H(%rsp)", "$src0")` lea $Hcub(%rsp), $r_ptr # H^3 call __ecp_nistz256_mul_mont$x # p256_mul_mont(Hcub, Hsqr, H); `&load_for_mul("$Hsqr(%rsp)", "$U1(%rsp)", "$src0")` lea $U2(%rsp), $r_ptr # U1*H^2 call __ecp_nistz256_mul_mont$x # p256_mul_mont(U2, U1, Hsqr); ___ { ####################################################################### # operate in 4-5-0-1 "name space" that matches multiplication output # my ($acc0,$acc1,$acc2,$acc3,$t3,$t4)=($acc4,$acc5,$acc0,$acc1,$acc2,$acc3); my ($poly1, $poly3)=($acc6,$acc7); $code.=<<___; #lea $U2(%rsp), $a_ptr #lea $Hsqr(%rsp), $r_ptr # 2*U1*H^2 #call __ecp_nistz256_mul_by_2 # ecp_nistz256_mul_by_2(Hsqr, U2); xor $t4, $t4 add $acc0, $acc0 # a0:a3+a0:a3 lea $Rsqr(%rsp), $a_ptr adc $acc1, $acc1 mov $acc0, $t0 adc $acc2, $acc2 adc $acc3, $acc3 mov $acc1, $t1 adc \$0, $t4 sub \$-1, $acc0 mov $acc2, $t2 sbb $poly1, $acc1 sbb \$0, $acc2 mov $acc3, $t3 sbb $poly3, $acc3 sbb \$0, $t4 cmovc $t0, $acc0 mov 8*0($a_ptr), $t0 cmovc $t1, $acc1 mov 8*1($a_ptr), $t1 cmovc $t2, $acc2 mov 8*2($a_ptr), $t2 cmovc $t3, $acc3 mov 8*3($a_ptr), $t3 call __ecp_nistz256_sub$x # p256_sub(res_x, Rsqr, Hsqr); lea $Hcub(%rsp), $b_ptr lea $res_x(%rsp), $r_ptr call __ecp_nistz256_sub_from$x # p256_sub(res_x, res_x, Hcub); mov $U2+8*0(%rsp), $t0 mov $U2+8*1(%rsp), $t1 mov $U2+8*2(%rsp), $t2 mov $U2+8*3(%rsp), $t3 lea $res_y(%rsp), $r_ptr call __ecp_nistz256_sub$x # p256_sub(res_y, U2, res_x); mov $acc0, 8*0($r_ptr) # save the result, as mov $acc1, 8*1($r_ptr) # __ecp_nistz256_sub doesn't mov $acc2, 8*2($r_ptr) mov $acc3, 8*3($r_ptr) ___ } $code.=<<___; `&load_for_mul("$S1(%rsp)", "$Hcub(%rsp)", "$src0")` lea $S2(%rsp), $r_ptr call __ecp_nistz256_mul_mont$x # p256_mul_mont(S2, S1, Hcub); `&load_for_mul("$R(%rsp)", "$res_y(%rsp)", "$src0")` lea $res_y(%rsp), $r_ptr call __ecp_nistz256_mul_mont$x # p256_mul_mont(res_y, R, res_y); lea $S2(%rsp), $b_ptr lea $res_y(%rsp), $r_ptr call __ecp_nistz256_sub_from$x # p256_sub(res_y, res_y, S2); movq %xmm0, $r_ptr # restore $r_ptr movdqa %xmm5, %xmm0 # copy_conditional(res_z, in2_z, in1infty); movdqa %xmm5, %xmm1 pandn $res_z(%rsp), %xmm0 movdqa %xmm5, %xmm2 pandn $res_z+0x10(%rsp), %xmm1 movdqa %xmm5, %xmm3 pand $in2_z(%rsp), %xmm2 pand $in2_z+0x10(%rsp), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqa %xmm4, %xmm0 # copy_conditional(res_z, in1_z, in2infty); movdqa %xmm4, %xmm1 pandn %xmm2, %xmm0 movdqa %xmm4, %xmm2 pandn %xmm3, %xmm1 movdqa %xmm4, %xmm3 pand $in1_z(%rsp), %xmm2 pand $in1_z+0x10(%rsp), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqu %xmm2, 0x40($r_ptr) movdqu %xmm3, 0x50($r_ptr) movdqa %xmm5, %xmm0 # copy_conditional(res_x, in2_x, in1infty); movdqa %xmm5, %xmm1 pandn $res_x(%rsp), %xmm0 movdqa %xmm5, %xmm2 pandn $res_x+0x10(%rsp), %xmm1 movdqa %xmm5, %xmm3 pand $in2_x(%rsp), %xmm2 pand $in2_x+0x10(%rsp), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqa %xmm4, %xmm0 # copy_conditional(res_x, in1_x, in2infty); movdqa %xmm4, %xmm1 pandn %xmm2, %xmm0 movdqa %xmm4, %xmm2 pandn %xmm3, %xmm1 movdqa %xmm4, %xmm3 pand $in1_x(%rsp), %xmm2 pand $in1_x+0x10(%rsp), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqu %xmm2, 0x00($r_ptr) movdqu %xmm3, 0x10($r_ptr) movdqa %xmm5, %xmm0 # copy_conditional(res_y, in2_y, in1infty); movdqa %xmm5, %xmm1 pandn $res_y(%rsp), %xmm0 movdqa %xmm5, %xmm2 pandn $res_y+0x10(%rsp), %xmm1 movdqa %xmm5, %xmm3 pand $in2_y(%rsp), %xmm2 pand $in2_y+0x10(%rsp), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqa %xmm4, %xmm0 # copy_conditional(res_y, in1_y, in2infty); movdqa %xmm4, %xmm1 pandn %xmm2, %xmm0 movdqa %xmm4, %xmm2 pandn %xmm3, %xmm1 movdqa %xmm4, %xmm3 pand $in1_y(%rsp), %xmm2 pand $in1_y+0x10(%rsp), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqu %xmm2, 0x20($r_ptr) movdqu %xmm3, 0x30($r_ptr) .Ladd_done$x: add \$32*18+8, %rsp pop %r15 pop %r14 pop %r13 pop %r12 pop %rbx pop %rbp ret .size ecp_nistz256_point_add$sfx,.-ecp_nistz256_point_add$sfx ___ } &gen_add("q"); sub gen_add_affine () { my $x = shift; my ($src0,$sfx,$bias); my ($U2,$S2,$H,$R,$Hsqr,$Hcub,$Rsqr, $res_x,$res_y,$res_z, $in1_x,$in1_y,$in1_z, $in2_x,$in2_y)=map(32*$_,(0..14)); my $Z1sqr = $S2; if ($x ne "x") { $src0 = "%rax"; $sfx = ""; $bias = 0; $code.=<<___; .globl ecp_nistz256_point_add_affine .type ecp_nistz256_point_add_affine,\@function,3 .align 32 ecp_nistz256_point_add_affine: ___ $code.=<<___ if ($addx); mov \$0x80100, %ecx and OPENSSL_ia32cap_P+8(%rip), %ecx cmp \$0x80100, %ecx je .Lpoint_add_affinex ___ } else { $src0 = "%rdx"; $sfx = "x"; $bias = 128; $code.=<<___; .type ecp_nistz256_point_add_affinex,\@function,3 .align 32 ecp_nistz256_point_add_affinex: .Lpoint_add_affinex: ___ } $code.=<<___; push %rbp push %rbx push %r12 push %r13 push %r14 push %r15 sub \$32*15+8, %rsp movdqu 0x00($a_ptr), %xmm0 # copy *(P256_POINT *)$a_ptr mov $b_org, $b_ptr # reassign movdqu 0x10($a_ptr), %xmm1 movdqu 0x20($a_ptr), %xmm2 movdqu 0x30($a_ptr), %xmm3 movdqu 0x40($a_ptr), %xmm4 movdqu 0x50($a_ptr), %xmm5 mov 0x40+8*0($a_ptr), $src0 # load original in1_z mov 0x40+8*1($a_ptr), $acc6 mov 0x40+8*2($a_ptr), $acc7 mov 0x40+8*3($a_ptr), $acc0 movdqa %xmm0, $in1_x(%rsp) movdqa %xmm1, $in1_x+0x10(%rsp) movdqa %xmm2, $in1_y(%rsp) movdqa %xmm3, $in1_y+0x10(%rsp) movdqa %xmm4, $in1_z(%rsp) movdqa %xmm5, $in1_z+0x10(%rsp) por %xmm4, %xmm5 movdqu 0x00($b_ptr), %xmm0 # copy *(P256_POINT_AFFINE *)$b_ptr pshufd \$0xb1, %xmm5, %xmm3 movdqu 0x10($b_ptr), %xmm1 movdqu 0x20($b_ptr), %xmm2 por %xmm3, %xmm5 movdqu 0x30($b_ptr), %xmm3 movdqa %xmm0, $in2_x(%rsp) pshufd \$0x1e, %xmm5, %xmm4 movdqa %xmm1, $in2_x+0x10(%rsp) por %xmm0, %xmm1 movq $r_ptr, %xmm0 # save $r_ptr movdqa %xmm2, $in2_y(%rsp) movdqa %xmm3, $in2_y+0x10(%rsp) por %xmm2, %xmm3 por %xmm4, %xmm5 pxor %xmm4, %xmm4 por %xmm1, %xmm3 lea 0x40-$bias($a_ptr), $a_ptr # $a_ptr is still valid lea $Z1sqr(%rsp), $r_ptr # Z1^2 call __ecp_nistz256_sqr_mont$x # p256_sqr_mont(Z1sqr, in1_z); pcmpeqd %xmm4, %xmm5 pshufd \$0xb1, %xmm3, %xmm4 mov 0x00($b_ptr), $src0 # $b_ptr is still valid #lea 0x00($b_ptr), $b_ptr mov $acc4, $acc1 # harmonize sqr output and mul input por %xmm3, %xmm4 pshufd \$0, %xmm5, %xmm5 # in1infty pshufd \$0x1e, %xmm4, %xmm3 mov $acc5, $acc2 por %xmm3, %xmm4 pxor %xmm3, %xmm3 mov $acc6, $acc3 pcmpeqd %xmm3, %xmm4 pshufd \$0, %xmm4, %xmm4 # in2infty lea $Z1sqr-$bias(%rsp), $a_ptr mov $acc7, $acc4 lea $U2(%rsp), $r_ptr # U2 = X2*Z1^2 call __ecp_nistz256_mul_mont$x # p256_mul_mont(U2, Z1sqr, in2_x); lea $in1_x(%rsp), $b_ptr lea $H(%rsp), $r_ptr # H = U2 - U1 call __ecp_nistz256_sub_from$x # p256_sub(H, U2, in1_x); `&load_for_mul("$Z1sqr(%rsp)", "$in1_z(%rsp)", "$src0")` lea $S2(%rsp), $r_ptr # S2 = Z1^3 call __ecp_nistz256_mul_mont$x # p256_mul_mont(S2, Z1sqr, in1_z); `&load_for_mul("$H(%rsp)", "$in1_z(%rsp)", "$src0")` lea $res_z(%rsp), $r_ptr # Z3 = H*Z1*Z2 call __ecp_nistz256_mul_mont$x # p256_mul_mont(res_z, H, in1_z); `&load_for_mul("$S2(%rsp)", "$in2_y(%rsp)", "$src0")` lea $S2(%rsp), $r_ptr # S2 = Y2*Z1^3 call __ecp_nistz256_mul_mont$x # p256_mul_mont(S2, S2, in2_y); lea $in1_y(%rsp), $b_ptr lea $R(%rsp), $r_ptr # R = S2 - S1 call __ecp_nistz256_sub_from$x # p256_sub(R, S2, in1_y); `&load_for_sqr("$H(%rsp)", "$src0")` lea $Hsqr(%rsp), $r_ptr # H^2 call __ecp_nistz256_sqr_mont$x # p256_sqr_mont(Hsqr, H); `&load_for_sqr("$R(%rsp)", "$src0")` lea $Rsqr(%rsp), $r_ptr # R^2 call __ecp_nistz256_sqr_mont$x # p256_sqr_mont(Rsqr, R); `&load_for_mul("$H(%rsp)", "$Hsqr(%rsp)", "$src0")` lea $Hcub(%rsp), $r_ptr # H^3 call __ecp_nistz256_mul_mont$x # p256_mul_mont(Hcub, Hsqr, H); `&load_for_mul("$Hsqr(%rsp)", "$in1_x(%rsp)", "$src0")` lea $U2(%rsp), $r_ptr # U1*H^2 call __ecp_nistz256_mul_mont$x # p256_mul_mont(U2, in1_x, Hsqr); ___ { ####################################################################### # operate in 4-5-0-1 "name space" that matches multiplication output # my ($acc0,$acc1,$acc2,$acc3,$t3,$t4)=($acc4,$acc5,$acc0,$acc1,$acc2,$acc3); my ($poly1, $poly3)=($acc6,$acc7); $code.=<<___; #lea $U2(%rsp), $a_ptr #lea $Hsqr(%rsp), $r_ptr # 2*U1*H^2 #call __ecp_nistz256_mul_by_2 # ecp_nistz256_mul_by_2(Hsqr, U2); xor $t4, $t4 add $acc0, $acc0 # a0:a3+a0:a3 lea $Rsqr(%rsp), $a_ptr adc $acc1, $acc1 mov $acc0, $t0 adc $acc2, $acc2 adc $acc3, $acc3 mov $acc1, $t1 adc \$0, $t4 sub \$-1, $acc0 mov $acc2, $t2 sbb $poly1, $acc1 sbb \$0, $acc2 mov $acc3, $t3 sbb $poly3, $acc3 sbb \$0, $t4 cmovc $t0, $acc0 mov 8*0($a_ptr), $t0 cmovc $t1, $acc1 mov 8*1($a_ptr), $t1 cmovc $t2, $acc2 mov 8*2($a_ptr), $t2 cmovc $t3, $acc3 mov 8*3($a_ptr), $t3 call __ecp_nistz256_sub$x # p256_sub(res_x, Rsqr, Hsqr); lea $Hcub(%rsp), $b_ptr lea $res_x(%rsp), $r_ptr call __ecp_nistz256_sub_from$x # p256_sub(res_x, res_x, Hcub); mov $U2+8*0(%rsp), $t0 mov $U2+8*1(%rsp), $t1 mov $U2+8*2(%rsp), $t2 mov $U2+8*3(%rsp), $t3 lea $H(%rsp), $r_ptr call __ecp_nistz256_sub$x # p256_sub(H, U2, res_x); mov $acc0, 8*0($r_ptr) # save the result, as mov $acc1, 8*1($r_ptr) # __ecp_nistz256_sub doesn't mov $acc2, 8*2($r_ptr) mov $acc3, 8*3($r_ptr) ___ } $code.=<<___; `&load_for_mul("$Hcub(%rsp)", "$in1_y(%rsp)", "$src0")` lea $S2(%rsp), $r_ptr call __ecp_nistz256_mul_mont$x # p256_mul_mont(S2, Hcub, in1_y); `&load_for_mul("$H(%rsp)", "$R(%rsp)", "$src0")` lea $H(%rsp), $r_ptr call __ecp_nistz256_mul_mont$x # p256_mul_mont(H, H, R); lea $S2(%rsp), $b_ptr lea $res_y(%rsp), $r_ptr call __ecp_nistz256_sub_from$x # p256_sub(res_y, H, S2); movq %xmm0, $r_ptr # restore $r_ptr movdqa %xmm5, %xmm0 # copy_conditional(res_z, ONE, in1infty); movdqa %xmm5, %xmm1 pandn $res_z(%rsp), %xmm0 movdqa %xmm5, %xmm2 pandn $res_z+0x10(%rsp), %xmm1 movdqa %xmm5, %xmm3 pand .LONE_mont(%rip), %xmm2 pand .LONE_mont+0x10(%rip), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqa %xmm4, %xmm0 # copy_conditional(res_z, in1_z, in2infty); movdqa %xmm4, %xmm1 pandn %xmm2, %xmm0 movdqa %xmm4, %xmm2 pandn %xmm3, %xmm1 movdqa %xmm4, %xmm3 pand $in1_z(%rsp), %xmm2 pand $in1_z+0x10(%rsp), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqu %xmm2, 0x40($r_ptr) movdqu %xmm3, 0x50($r_ptr) movdqa %xmm5, %xmm0 # copy_conditional(res_x, in2_x, in1infty); movdqa %xmm5, %xmm1 pandn $res_x(%rsp), %xmm0 movdqa %xmm5, %xmm2 pandn $res_x+0x10(%rsp), %xmm1 movdqa %xmm5, %xmm3 pand $in2_x(%rsp), %xmm2 pand $in2_x+0x10(%rsp), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqa %xmm4, %xmm0 # copy_conditional(res_x, in1_x, in2infty); movdqa %xmm4, %xmm1 pandn %xmm2, %xmm0 movdqa %xmm4, %xmm2 pandn %xmm3, %xmm1 movdqa %xmm4, %xmm3 pand $in1_x(%rsp), %xmm2 pand $in1_x+0x10(%rsp), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqu %xmm2, 0x00($r_ptr) movdqu %xmm3, 0x10($r_ptr) movdqa %xmm5, %xmm0 # copy_conditional(res_y, in2_y, in1infty); movdqa %xmm5, %xmm1 pandn $res_y(%rsp), %xmm0 movdqa %xmm5, %xmm2 pandn $res_y+0x10(%rsp), %xmm1 movdqa %xmm5, %xmm3 pand $in2_y(%rsp), %xmm2 pand $in2_y+0x10(%rsp), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqa %xmm4, %xmm0 # copy_conditional(res_y, in1_y, in2infty); movdqa %xmm4, %xmm1 pandn %xmm2, %xmm0 movdqa %xmm4, %xmm2 pandn %xmm3, %xmm1 movdqa %xmm4, %xmm3 pand $in1_y(%rsp), %xmm2 pand $in1_y+0x10(%rsp), %xmm3 por %xmm0, %xmm2 por %xmm1, %xmm3 movdqu %xmm2, 0x20($r_ptr) movdqu %xmm3, 0x30($r_ptr) add \$32*15+8, %rsp pop %r15 pop %r14 pop %r13 pop %r12 pop %rbx pop %rbp ret .size ecp_nistz256_point_add_affine$sfx,.-ecp_nistz256_point_add_affine$sfx ___ } &gen_add_affine("q"); ######################################################################## # AD*X magic # if ($addx) { { ######################################################################## # operate in 4-5-0-1 "name space" that matches multiplication output # my ($a0,$a1,$a2,$a3,$t3,$t4)=($acc4,$acc5,$acc0,$acc1,$acc2,$acc3); $code.=<<___; .type __ecp_nistz256_add_tox,\@abi-omnipotent .align 32 __ecp_nistz256_add_tox: xor $t4, $t4 adc 8*0($b_ptr), $a0 adc 8*1($b_ptr), $a1 mov $a0, $t0 adc 8*2($b_ptr), $a2 adc 8*3($b_ptr), $a3 mov $a1, $t1 adc \$0, $t4 xor $t3, $t3 sbb \$-1, $a0 mov $a2, $t2 sbb $poly1, $a1 sbb \$0, $a2 mov $a3, $t3 sbb $poly3, $a3 sbb \$0, $t4 cmovc $t0, $a0 cmovc $t1, $a1 mov $a0, 8*0($r_ptr) cmovc $t2, $a2 mov $a1, 8*1($r_ptr) cmovc $t3, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) ret .size __ecp_nistz256_add_tox,.-__ecp_nistz256_add_tox .type __ecp_nistz256_sub_fromx,\@abi-omnipotent .align 32 __ecp_nistz256_sub_fromx: xor $t4, $t4 sbb 8*0($b_ptr), $a0 sbb 8*1($b_ptr), $a1 mov $a0, $t0 sbb 8*2($b_ptr), $a2 sbb 8*3($b_ptr), $a3 mov $a1, $t1 sbb \$0, $t4 xor $t3, $t3 adc \$-1, $a0 mov $a2, $t2 adc $poly1, $a1 adc \$0, $a2 mov $a3, $t3 adc $poly3, $a3 bt \$0, $t4 cmovnc $t0, $a0 cmovnc $t1, $a1 mov $a0, 8*0($r_ptr) cmovnc $t2, $a2 mov $a1, 8*1($r_ptr) cmovnc $t3, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) ret .size __ecp_nistz256_sub_fromx,.-__ecp_nistz256_sub_fromx .type __ecp_nistz256_subx,\@abi-omnipotent .align 32 __ecp_nistz256_subx: xor $t4, $t4 sbb $a0, $t0 sbb $a1, $t1 mov $t0, $a0 sbb $a2, $t2 sbb $a3, $t3 mov $t1, $a1 sbb \$0, $t4 xor $a3 ,$a3 adc \$-1, $t0 mov $t2, $a2 adc $poly1, $t1 adc \$0, $t2 mov $t3, $a3 adc $poly3, $t3 bt \$0, $t4 cmovc $t0, $a0 cmovc $t1, $a1 cmovc $t2, $a2 cmovc $t3, $a3 ret .size __ecp_nistz256_subx,.-__ecp_nistz256_subx .type __ecp_nistz256_mul_by_2x,\@abi-omnipotent .align 32 __ecp_nistz256_mul_by_2x: xor $t4, $t4 adc $a0, $a0 # a0:a3+a0:a3 adc $a1, $a1 mov $a0, $t0 adc $a2, $a2 adc $a3, $a3 mov $a1, $t1 adc \$0, $t4 xor $t3, $t3 sbb \$-1, $a0 mov $a2, $t2 sbb $poly1, $a1 sbb \$0, $a2 mov $a3, $t3 sbb $poly3, $a3 sbb \$0, $t4 cmovc $t0, $a0 cmovc $t1, $a1 mov $a0, 8*0($r_ptr) cmovc $t2, $a2 mov $a1, 8*1($r_ptr) cmovc $t3, $a3 mov $a2, 8*2($r_ptr) mov $a3, 8*3($r_ptr) ret .size __ecp_nistz256_mul_by_2x,.-__ecp_nistz256_mul_by_2x ___ } &gen_double("x"); &gen_add("x"); &gen_add_affine("x"); } }}} $code =~ s/\`([^\`]*)\`/eval $1/gem; print $code; close STDOUT; Index: vendor-crypto/openssl/dist/crypto/ec/ecp_mont.c =================================================================== --- vendor-crypto/openssl/dist/crypto/ec/ecp_mont.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/ec/ecp_mont.c (revision 325326) @@ -1,308 +1,310 @@ /* crypto/ec/ecp_mont.c */ /* * Originally written by Bodo Moeller for the OpenSSL project. */ /* ==================================================================== * 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). * */ /* ==================================================================== * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. * Portions of this software developed by SUN MICROSYSTEMS, INC., * and contributed to the OpenSSL project. */ #include #ifdef OPENSSL_FIPS # include #endif #include "ec_lcl.h" const EC_METHOD *EC_GFp_mont_method(void) { static const EC_METHOD ret = { EC_FLAGS_DEFAULT_OCT, NID_X9_62_prime_field, ec_GFp_mont_group_init, ec_GFp_mont_group_finish, ec_GFp_mont_group_clear_finish, ec_GFp_mont_group_copy, ec_GFp_mont_group_set_curve, ec_GFp_simple_group_get_curve, ec_GFp_simple_group_get_degree, ec_GFp_simple_group_check_discriminant, ec_GFp_simple_point_init, ec_GFp_simple_point_finish, ec_GFp_simple_point_clear_finish, ec_GFp_simple_point_copy, ec_GFp_simple_point_set_to_infinity, ec_GFp_simple_set_Jprojective_coordinates_GFp, ec_GFp_simple_get_Jprojective_coordinates_GFp, ec_GFp_simple_point_set_affine_coordinates, ec_GFp_simple_point_get_affine_coordinates, 0, 0, 0, ec_GFp_simple_add, ec_GFp_simple_dbl, ec_GFp_simple_invert, ec_GFp_simple_is_at_infinity, ec_GFp_simple_is_on_curve, ec_GFp_simple_cmp, ec_GFp_simple_make_affine, ec_GFp_simple_points_make_affine, 0 /* mul */ , 0 /* precompute_mult */ , 0 /* have_precompute_mult */ , ec_GFp_mont_field_mul, ec_GFp_mont_field_sqr, 0 /* field_div */ , ec_GFp_mont_field_encode, ec_GFp_mont_field_decode, ec_GFp_mont_field_set_to_one }; #ifdef OPENSSL_FIPS if (FIPS_mode()) return fips_ec_gfp_mont_method(); #endif return &ret; } int ec_GFp_mont_group_init(EC_GROUP *group) { int ok; ok = ec_GFp_simple_group_init(group); group->field_data1 = NULL; group->field_data2 = NULL; return ok; } void ec_GFp_mont_group_finish(EC_GROUP *group) { if (group->field_data1 != NULL) { BN_MONT_CTX_free(group->field_data1); group->field_data1 = NULL; } if (group->field_data2 != NULL) { BN_free(group->field_data2); group->field_data2 = NULL; } ec_GFp_simple_group_finish(group); } void ec_GFp_mont_group_clear_finish(EC_GROUP *group) { if (group->field_data1 != NULL) { BN_MONT_CTX_free(group->field_data1); group->field_data1 = NULL; } if (group->field_data2 != NULL) { BN_clear_free(group->field_data2); group->field_data2 = NULL; } ec_GFp_simple_group_clear_finish(group); } int ec_GFp_mont_group_copy(EC_GROUP *dest, const EC_GROUP *src) { if (dest->field_data1 != NULL) { BN_MONT_CTX_free(dest->field_data1); dest->field_data1 = NULL; } if (dest->field_data2 != NULL) { BN_clear_free(dest->field_data2); dest->field_data2 = NULL; } if (!ec_GFp_simple_group_copy(dest, src)) return 0; if (src->field_data1 != NULL) { dest->field_data1 = BN_MONT_CTX_new(); if (dest->field_data1 == NULL) return 0; if (!BN_MONT_CTX_copy(dest->field_data1, src->field_data1)) goto err; } if (src->field_data2 != NULL) { dest->field_data2 = BN_dup(src->field_data2); if (dest->field_data2 == NULL) goto err; } return 1; err: if (dest->field_data1 != NULL) { BN_MONT_CTX_free(dest->field_data1); dest->field_data1 = NULL; } return 0; } int ec_GFp_mont_group_set_curve(EC_GROUP *group, const BIGNUM *p, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { BN_CTX *new_ctx = NULL; BN_MONT_CTX *mont = NULL; BIGNUM *one = NULL; int ret = 0; if (group->field_data1 != NULL) { BN_MONT_CTX_free(group->field_data1); group->field_data1 = NULL; } if (group->field_data2 != NULL) { BN_free(group->field_data2); group->field_data2 = NULL; } if (ctx == NULL) { ctx = new_ctx = BN_CTX_new(); if (ctx == NULL) return 0; } mont = BN_MONT_CTX_new(); if (mont == NULL) goto err; if (!BN_MONT_CTX_set(mont, p, ctx)) { ECerr(EC_F_EC_GFP_MONT_GROUP_SET_CURVE, ERR_R_BN_LIB); goto err; } one = BN_new(); if (one == NULL) goto err; if (!BN_to_montgomery(one, BN_value_one(), mont, ctx)) goto err; group->field_data1 = mont; mont = NULL; group->field_data2 = one; one = NULL; ret = ec_GFp_simple_group_set_curve(group, p, a, b, ctx); if (!ret) { BN_MONT_CTX_free(group->field_data1); group->field_data1 = NULL; BN_free(group->field_data2); group->field_data2 = NULL; } err: if (new_ctx != NULL) BN_CTX_free(new_ctx); if (mont != NULL) BN_MONT_CTX_free(mont); + if (one != NULL) + BN_free(one); return ret; } int ec_GFp_mont_field_mul(const EC_GROUP *group, BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { if (group->field_data1 == NULL) { ECerr(EC_F_EC_GFP_MONT_FIELD_MUL, EC_R_NOT_INITIALIZED); return 0; } return BN_mod_mul_montgomery(r, a, b, group->field_data1, ctx); } int ec_GFp_mont_field_sqr(const EC_GROUP *group, BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) { if (group->field_data1 == NULL) { ECerr(EC_F_EC_GFP_MONT_FIELD_SQR, EC_R_NOT_INITIALIZED); return 0; } return BN_mod_mul_montgomery(r, a, a, group->field_data1, ctx); } int ec_GFp_mont_field_encode(const EC_GROUP *group, BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) { if (group->field_data1 == NULL) { ECerr(EC_F_EC_GFP_MONT_FIELD_ENCODE, EC_R_NOT_INITIALIZED); return 0; } return BN_to_montgomery(r, a, (BN_MONT_CTX *)group->field_data1, ctx); } int ec_GFp_mont_field_decode(const EC_GROUP *group, BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) { if (group->field_data1 == NULL) { ECerr(EC_F_EC_GFP_MONT_FIELD_DECODE, EC_R_NOT_INITIALIZED); return 0; } return BN_from_montgomery(r, a, group->field_data1, ctx); } int ec_GFp_mont_field_set_to_one(const EC_GROUP *group, BIGNUM *r, BN_CTX *ctx) { if (group->field_data2 == NULL) { ECerr(EC_F_EC_GFP_MONT_FIELD_SET_TO_ONE, EC_R_NOT_INITIALIZED); return 0; } if (!BN_copy(r, group->field_data2)) return 0; return 1; } Index: vendor-crypto/openssl/dist/crypto/ec/ecp_nistp224.c =================================================================== --- vendor-crypto/openssl/dist/crypto/ec/ecp_nistp224.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/ec/ecp_nistp224.c (revision 325326) @@ -1,1769 +1,1768 @@ /* crypto/ec/ecp_nistp224.c */ /* * Written by Emilia Kasper (Google) for the OpenSSL project. */ /* Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * A 64-bit implementation of the NIST P-224 elliptic curve point multiplication * * Inspired by Daniel J. Bernstein's public domain nistp224 implementation * and Adam Langley's public domain 64-bit C implementation of curve25519 */ #include #ifndef OPENSSL_NO_EC_NISTP_64_GCC_128 # ifndef OPENSSL_SYS_VMS # include # else # include # endif # include # include # include "ec_lcl.h" # if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) /* even with gcc, the typedef won't work for 32-bit platforms */ typedef __uint128_t uint128_t; /* nonstandard; implemented by gcc on 64-bit * platforms */ # else # error "Need GCC 3.1 or later to define type uint128_t" # endif typedef uint8_t u8; typedef uint64_t u64; typedef int64_t s64; /******************************************************************************/ /*- * INTERNAL REPRESENTATION OF FIELD ELEMENTS * * Field elements are represented as a_0 + 2^56*a_1 + 2^112*a_2 + 2^168*a_3 * using 64-bit coefficients called 'limbs', * and sometimes (for multiplication results) as * b_0 + 2^56*b_1 + 2^112*b_2 + 2^168*b_3 + 2^224*b_4 + 2^280*b_5 + 2^336*b_6 * using 128-bit coefficients called 'widelimbs'. * A 4-limb representation is an 'felem'; * a 7-widelimb representation is a 'widefelem'. * Even within felems, bits of adjacent limbs overlap, and we don't always * reduce the representations: we ensure that inputs to each felem * multiplication satisfy a_i < 2^60, so outputs satisfy b_i < 4*2^60*2^60, * and fit into a 128-bit word without overflow. The coefficients are then * again partially reduced to obtain an felem satisfying a_i < 2^57. * We only reduce to the unique minimal representation at the end of the * computation. */ typedef uint64_t limb; typedef uint128_t widelimb; typedef limb felem[4]; typedef widelimb widefelem[7]; /* * Field element represented as a byte arrary. 28*8 = 224 bits is also the * group order size for the elliptic curve, and we also use this type for * scalars for point multiplication. */ typedef u8 felem_bytearray[28]; static const felem_bytearray nistp224_curve_params[5] = { {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, /* p */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}, {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, /* a */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE}, {0xB4, 0x05, 0x0A, 0x85, 0x0C, 0x04, 0xB3, 0xAB, 0xF5, 0x41, /* b */ 0x32, 0x56, 0x50, 0x44, 0xB0, 0xB7, 0xD7, 0xBF, 0xD8, 0xBA, 0x27, 0x0B, 0x39, 0x43, 0x23, 0x55, 0xFF, 0xB4}, {0xB7, 0x0E, 0x0C, 0xBD, 0x6B, 0xB4, 0xBF, 0x7F, 0x32, 0x13, /* x */ 0x90, 0xB9, 0x4A, 0x03, 0xC1, 0xD3, 0x56, 0xC2, 0x11, 0x22, 0x34, 0x32, 0x80, 0xD6, 0x11, 0x5C, 0x1D, 0x21}, {0xbd, 0x37, 0x63, 0x88, 0xb5, 0xf7, 0x23, 0xfb, 0x4c, 0x22, /* y */ 0xdf, 0xe6, 0xcd, 0x43, 0x75, 0xa0, 0x5a, 0x07, 0x47, 0x64, 0x44, 0xd5, 0x81, 0x99, 0x85, 0x00, 0x7e, 0x34} }; /*- * Precomputed multiples of the standard generator * Points are given in coordinates (X, Y, Z) where Z normally is 1 * (0 for the point at infinity). * For each field element, slice a_0 is word 0, etc. * * The table has 2 * 16 elements, starting with the following: * index | bits | point * ------+---------+------------------------------ * 0 | 0 0 0 0 | 0G * 1 | 0 0 0 1 | 1G * 2 | 0 0 1 0 | 2^56G * 3 | 0 0 1 1 | (2^56 + 1)G * 4 | 0 1 0 0 | 2^112G * 5 | 0 1 0 1 | (2^112 + 1)G * 6 | 0 1 1 0 | (2^112 + 2^56)G * 7 | 0 1 1 1 | (2^112 + 2^56 + 1)G * 8 | 1 0 0 0 | 2^168G * 9 | 1 0 0 1 | (2^168 + 1)G * 10 | 1 0 1 0 | (2^168 + 2^56)G * 11 | 1 0 1 1 | (2^168 + 2^56 + 1)G * 12 | 1 1 0 0 | (2^168 + 2^112)G * 13 | 1 1 0 1 | (2^168 + 2^112 + 1)G * 14 | 1 1 1 0 | (2^168 + 2^112 + 2^56)G * 15 | 1 1 1 1 | (2^168 + 2^112 + 2^56 + 1)G * followed by a copy of this with each element multiplied by 2^28. * * The reason for this is so that we can clock bits into four different * locations when doing simple scalar multiplies against the base point, * and then another four locations using the second 16 elements. */ static const felem gmul[2][16][3] = { {{{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}, {{0x3280d6115c1d21, 0xc1d356c2112234, 0x7f321390b94a03, 0xb70e0cbd6bb4bf}, {0xd5819985007e34, 0x75a05a07476444, 0xfb4c22dfe6cd43, 0xbd376388b5f723}, {1, 0, 0, 0}}, {{0xfd9675666ebbe9, 0xbca7664d40ce5e, 0x2242df8d8a2a43, 0x1f49bbb0f99bc5}, {0x29e0b892dc9c43, 0xece8608436e662, 0xdc858f185310d0, 0x9812dd4eb8d321}, {1, 0, 0, 0}}, {{0x6d3e678d5d8eb8, 0x559eed1cb362f1, 0x16e9a3bbce8a3f, 0xeedcccd8c2a748}, {0xf19f90ed50266d, 0xabf2b4bf65f9df, 0x313865468fafec, 0x5cb379ba910a17}, {1, 0, 0, 0}}, {{0x0641966cab26e3, 0x91fb2991fab0a0, 0xefec27a4e13a0b, 0x0499aa8a5f8ebe}, {0x7510407766af5d, 0x84d929610d5450, 0x81d77aae82f706, 0x6916f6d4338c5b}, {1, 0, 0, 0}}, {{0xea95ac3b1f15c6, 0x086000905e82d4, 0xdd323ae4d1c8b1, 0x932b56be7685a3}, {0x9ef93dea25dbbf, 0x41665960f390f0, 0xfdec76dbe2a8a7, 0x523e80f019062a}, {1, 0, 0, 0}}, {{0x822fdd26732c73, 0xa01c83531b5d0f, 0x363f37347c1ba4, 0xc391b45c84725c}, {0xbbd5e1b2d6ad24, 0xddfbcde19dfaec, 0xc393da7e222a7f, 0x1efb7890ede244}, {1, 0, 0, 0}}, {{0x4c9e90ca217da1, 0xd11beca79159bb, 0xff8d33c2c98b7c, 0x2610b39409f849}, {0x44d1352ac64da0, 0xcdbb7b2c46b4fb, 0x966c079b753c89, 0xfe67e4e820b112}, {1, 0, 0, 0}}, {{0xe28cae2df5312d, 0xc71b61d16f5c6e, 0x79b7619a3e7c4c, 0x05c73240899b47}, {0x9f7f6382c73e3a, 0x18615165c56bda, 0x641fab2116fd56, 0x72855882b08394}, {1, 0, 0, 0}}, {{0x0469182f161c09, 0x74a98ca8d00fb5, 0xb89da93489a3e0, 0x41c98768fb0c1d}, {0xe5ea05fb32da81, 0x3dce9ffbca6855, 0x1cfe2d3fbf59e6, 0x0e5e03408738a7}, {1, 0, 0, 0}}, {{0xdab22b2333e87f, 0x4430137a5dd2f6, 0xe03ab9f738beb8, 0xcb0c5d0dc34f24}, {0x764a7df0c8fda5, 0x185ba5c3fa2044, 0x9281d688bcbe50, 0xc40331df893881}, {1, 0, 0, 0}}, {{0xb89530796f0f60, 0xade92bd26909a3, 0x1a0c83fb4884da, 0x1765bf22a5a984}, {0x772a9ee75db09e, 0x23bc6c67cec16f, 0x4c1edba8b14e2f, 0xe2a215d9611369}, {1, 0, 0, 0}}, {{0x571e509fb5efb3, 0xade88696410552, 0xc8ae85fada74fe, 0x6c7e4be83bbde3}, {0xff9f51160f4652, 0xb47ce2495a6539, 0xa2946c53b582f4, 0x286d2db3ee9a60}, {1, 0, 0, 0}}, {{0x40bbd5081a44af, 0x0995183b13926c, 0xbcefba6f47f6d0, 0x215619e9cc0057}, {0x8bc94d3b0df45e, 0xf11c54a3694f6f, 0x8631b93cdfe8b5, 0xe7e3f4b0982db9}, {1, 0, 0, 0}}, {{0xb17048ab3e1c7b, 0xac38f36ff8a1d8, 0x1c29819435d2c6, 0xc813132f4c07e9}, {0x2891425503b11f, 0x08781030579fea, 0xf5426ba5cc9674, 0x1e28ebf18562bc}, {1, 0, 0, 0}}, {{0x9f31997cc864eb, 0x06cd91d28b5e4c, 0xff17036691a973, 0xf1aef351497c58}, {0xdd1f2d600564ff, 0xdead073b1402db, 0x74a684435bd693, 0xeea7471f962558}, {1, 0, 0, 0}}}, {{{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}, {{0x9665266dddf554, 0x9613d78b60ef2d, 0xce27a34cdba417, 0xd35ab74d6afc31}, {0x85ccdd22deb15e, 0x2137e5783a6aab, 0xa141cffd8c93c6, 0x355a1830e90f2d}, {1, 0, 0, 0}}, {{0x1a494eadaade65, 0xd6da4da77fe53c, 0xe7992996abec86, 0x65c3553c6090e3}, {0xfa610b1fb09346, 0xf1c6540b8a4aaf, 0xc51a13ccd3cbab, 0x02995b1b18c28a}, {1, 0, 0, 0}}, {{0x7874568e7295ef, 0x86b419fbe38d04, 0xdc0690a7550d9a, 0xd3966a44beac33}, {0x2b7280ec29132f, 0xbeaa3b6a032df3, 0xdc7dd88ae41200, 0xd25e2513e3a100}, {1, 0, 0, 0}}, {{0x924857eb2efafd, 0xac2bce41223190, 0x8edaa1445553fc, 0x825800fd3562d5}, {0x8d79148ea96621, 0x23a01c3dd9ed8d, 0xaf8b219f9416b5, 0xd8db0cc277daea}, {1, 0, 0, 0}}, {{0x76a9c3b1a700f0, 0xe9acd29bc7e691, 0x69212d1a6b0327, 0x6322e97fe154be}, {0x469fc5465d62aa, 0x8d41ed18883b05, 0x1f8eae66c52b88, 0xe4fcbe9325be51}, {1, 0, 0, 0}}, {{0x825fdf583cac16, 0x020b857c7b023a, 0x683c17744b0165, 0x14ffd0a2daf2f1}, {0x323b36184218f9, 0x4944ec4e3b47d4, 0xc15b3080841acf, 0x0bced4b01a28bb}, {1, 0, 0, 0}}, {{0x92ac22230df5c4, 0x52f33b4063eda8, 0xcb3f19870c0c93, 0x40064f2ba65233}, {0xfe16f0924f8992, 0x012da25af5b517, 0x1a57bb24f723a6, 0x06f8bc76760def}, {1, 0, 0, 0}}, {{0x4a7084f7817cb9, 0xbcab0738ee9a78, 0x3ec11e11d9c326, 0xdc0fe90e0f1aae}, {0xcf639ea5f98390, 0x5c350aa22ffb74, 0x9afae98a4047b7, 0x956ec2d617fc45}, {1, 0, 0, 0}}, {{0x4306d648c1be6a, 0x9247cd8bc9a462, 0xf5595e377d2f2e, 0xbd1c3caff1a52e}, {0x045e14472409d0, 0x29f3e17078f773, 0x745a602b2d4f7d, 0x191837685cdfbb}, {1, 0, 0, 0}}, {{0x5b6ee254a8cb79, 0x4953433f5e7026, 0xe21faeb1d1def4, 0xc4c225785c09de}, {0x307ce7bba1e518, 0x31b125b1036db8, 0x47e91868839e8f, 0xc765866e33b9f3}, {1, 0, 0, 0}}, {{0x3bfece24f96906, 0x4794da641e5093, 0xde5df64f95db26, 0x297ecd89714b05}, {0x701bd3ebb2c3aa, 0x7073b4f53cb1d5, 0x13c5665658af16, 0x9895089d66fe58}, {1, 0, 0, 0}}, {{0x0fef05f78c4790, 0x2d773633b05d2e, 0x94229c3a951c94, 0xbbbd70df4911bb}, {0xb2c6963d2c1168, 0x105f47a72b0d73, 0x9fdf6111614080, 0x7b7e94b39e67b0}, {1, 0, 0, 0}}, {{0xad1a7d6efbe2b3, 0xf012482c0da69d, 0x6b3bdf12438345, 0x40d7558d7aa4d9}, {0x8a09fffb5c6d3d, 0x9a356e5d9ffd38, 0x5973f15f4f9b1c, 0xdcd5f59f63c3ea}, {1, 0, 0, 0}}, {{0xacf39f4c5ca7ab, 0x4c8071cc5fd737, 0xc64e3602cd1184, 0x0acd4644c9abba}, {0x6c011a36d8bf6e, 0xfecd87ba24e32a, 0x19f6f56574fad8, 0x050b204ced9405}, {1, 0, 0, 0}}, {{0xed4f1cae7d9a96, 0x5ceef7ad94c40a, 0x778e4a3bf3ef9b, 0x7405783dc3b55e}, {0x32477c61b6e8c6, 0xb46a97570f018b, 0x91176d0a7e95d1, 0x3df90fbc4c7d0e}, {1, 0, 0, 0}}} }; /* Precomputation for the group generator. */ typedef struct { felem g_pre_comp[2][16][3]; int references; } NISTP224_PRE_COMP; const EC_METHOD *EC_GFp_nistp224_method(void) { static const EC_METHOD ret = { EC_FLAGS_DEFAULT_OCT, NID_X9_62_prime_field, ec_GFp_nistp224_group_init, ec_GFp_simple_group_finish, ec_GFp_simple_group_clear_finish, ec_GFp_nist_group_copy, ec_GFp_nistp224_group_set_curve, ec_GFp_simple_group_get_curve, ec_GFp_simple_group_get_degree, ec_GFp_simple_group_check_discriminant, ec_GFp_simple_point_init, ec_GFp_simple_point_finish, ec_GFp_simple_point_clear_finish, ec_GFp_simple_point_copy, ec_GFp_simple_point_set_to_infinity, ec_GFp_simple_set_Jprojective_coordinates_GFp, ec_GFp_simple_get_Jprojective_coordinates_GFp, ec_GFp_simple_point_set_affine_coordinates, ec_GFp_nistp224_point_get_affine_coordinates, 0 /* point_set_compressed_coordinates */ , 0 /* point2oct */ , 0 /* oct2point */ , ec_GFp_simple_add, ec_GFp_simple_dbl, ec_GFp_simple_invert, ec_GFp_simple_is_at_infinity, ec_GFp_simple_is_on_curve, ec_GFp_simple_cmp, ec_GFp_simple_make_affine, ec_GFp_simple_points_make_affine, ec_GFp_nistp224_points_mul, ec_GFp_nistp224_precompute_mult, ec_GFp_nistp224_have_precompute_mult, ec_GFp_nist_field_mul, ec_GFp_nist_field_sqr, 0 /* field_div */ , 0 /* field_encode */ , 0 /* field_decode */ , 0 /* field_set_to_one */ }; return &ret; } /* * Helper functions to convert field elements to/from internal representation */ static void bin28_to_felem(felem out, const u8 in[28]) { out[0] = *((const uint64_t *)(in)) & 0x00ffffffffffffff; out[1] = (*((const uint64_t *)(in + 7))) & 0x00ffffffffffffff; out[2] = (*((const uint64_t *)(in + 14))) & 0x00ffffffffffffff; out[3] = (*((const uint64_t *)(in+20))) >> 8; } static void felem_to_bin28(u8 out[28], const felem in) { unsigned i; for (i = 0; i < 7; ++i) { out[i] = in[0] >> (8 * i); out[i + 7] = in[1] >> (8 * i); out[i + 14] = in[2] >> (8 * i); out[i + 21] = in[3] >> (8 * i); } } /* To preserve endianness when using BN_bn2bin and BN_bin2bn */ static void flip_endian(u8 *out, const u8 *in, unsigned len) { unsigned i; for (i = 0; i < len; ++i) out[i] = in[len - 1 - i]; } /* From OpenSSL BIGNUM to internal representation */ static int BN_to_felem(felem out, const BIGNUM *bn) { felem_bytearray b_in; felem_bytearray b_out; unsigned num_bytes; /* BN_bn2bin eats leading zeroes */ memset(b_out, 0, sizeof b_out); num_bytes = BN_num_bytes(bn); if (num_bytes > sizeof b_out) { ECerr(EC_F_BN_TO_FELEM, EC_R_BIGNUM_OUT_OF_RANGE); return 0; } if (BN_is_negative(bn)) { ECerr(EC_F_BN_TO_FELEM, EC_R_BIGNUM_OUT_OF_RANGE); return 0; } num_bytes = BN_bn2bin(bn, b_in); flip_endian(b_out, b_in, num_bytes); bin28_to_felem(out, b_out); return 1; } /* From internal representation to OpenSSL BIGNUM */ static BIGNUM *felem_to_BN(BIGNUM *out, const felem in) { felem_bytearray b_in, b_out; felem_to_bin28(b_in, in); flip_endian(b_out, b_in, sizeof b_out); return BN_bin2bn(b_out, sizeof b_out, out); } /******************************************************************************/ /*- * FIELD OPERATIONS * * Field operations, using the internal representation of field elements. * NB! These operations are specific to our point multiplication and cannot be * expected to be correct in general - e.g., multiplication with a large scalar * will cause an overflow. * */ static void felem_one(felem out) { out[0] = 1; out[1] = 0; out[2] = 0; out[3] = 0; } static void felem_assign(felem out, const felem in) { out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; out[3] = in[3]; } /* Sum two field elements: out += in */ static void felem_sum(felem out, const felem in) { out[0] += in[0]; out[1] += in[1]; out[2] += in[2]; out[3] += in[3]; } /* Get negative value: out = -in */ /* Assumes in[i] < 2^57 */ static void felem_neg(felem out, const felem in) { static const limb two58p2 = (((limb) 1) << 58) + (((limb) 1) << 2); static const limb two58m2 = (((limb) 1) << 58) - (((limb) 1) << 2); static const limb two58m42m2 = (((limb) 1) << 58) - (((limb) 1) << 42) - (((limb) 1) << 2); /* Set to 0 mod 2^224-2^96+1 to ensure out > in */ out[0] = two58p2 - in[0]; out[1] = two58m42m2 - in[1]; out[2] = two58m2 - in[2]; out[3] = two58m2 - in[3]; } /* Subtract field elements: out -= in */ /* Assumes in[i] < 2^57 */ static void felem_diff(felem out, const felem in) { static const limb two58p2 = (((limb) 1) << 58) + (((limb) 1) << 2); static const limb two58m2 = (((limb) 1) << 58) - (((limb) 1) << 2); static const limb two58m42m2 = (((limb) 1) << 58) - (((limb) 1) << 42) - (((limb) 1) << 2); /* Add 0 mod 2^224-2^96+1 to ensure out > in */ out[0] += two58p2; out[1] += two58m42m2; out[2] += two58m2; out[3] += two58m2; out[0] -= in[0]; out[1] -= in[1]; out[2] -= in[2]; out[3] -= in[3]; } /* Subtract in unreduced 128-bit mode: out -= in */ /* Assumes in[i] < 2^119 */ static void widefelem_diff(widefelem out, const widefelem in) { static const widelimb two120 = ((widelimb) 1) << 120; static const widelimb two120m64 = (((widelimb) 1) << 120) - (((widelimb) 1) << 64); static const widelimb two120m104m64 = (((widelimb) 1) << 120) - (((widelimb) 1) << 104) - (((widelimb) 1) << 64); /* Add 0 mod 2^224-2^96+1 to ensure out > in */ out[0] += two120; out[1] += two120m64; out[2] += two120m64; out[3] += two120; out[4] += two120m104m64; out[5] += two120m64; out[6] += two120m64; out[0] -= in[0]; out[1] -= in[1]; out[2] -= in[2]; out[3] -= in[3]; out[4] -= in[4]; out[5] -= in[5]; out[6] -= in[6]; } /* Subtract in mixed mode: out128 -= in64 */ /* in[i] < 2^63 */ static void felem_diff_128_64(widefelem out, const felem in) { static const widelimb two64p8 = (((widelimb) 1) << 64) + (((widelimb) 1) << 8); static const widelimb two64m8 = (((widelimb) 1) << 64) - (((widelimb) 1) << 8); static const widelimb two64m48m8 = (((widelimb) 1) << 64) - (((widelimb) 1) << 48) - (((widelimb) 1) << 8); /* Add 0 mod 2^224-2^96+1 to ensure out > in */ out[0] += two64p8; out[1] += two64m48m8; out[2] += two64m8; out[3] += two64m8; out[0] -= in[0]; out[1] -= in[1]; out[2] -= in[2]; out[3] -= in[3]; } /* * Multiply a field element by a scalar: out = out * scalar The scalars we * actually use are small, so results fit without overflow */ static void felem_scalar(felem out, const limb scalar) { out[0] *= scalar; out[1] *= scalar; out[2] *= scalar; out[3] *= scalar; } /* * Multiply an unreduced field element by a scalar: out = out * scalar The * scalars we actually use are small, so results fit without overflow */ static void widefelem_scalar(widefelem out, const widelimb scalar) { out[0] *= scalar; out[1] *= scalar; out[2] *= scalar; out[3] *= scalar; out[4] *= scalar; out[5] *= scalar; out[6] *= scalar; } /* Square a field element: out = in^2 */ static void felem_square(widefelem out, const felem in) { limb tmp0, tmp1, tmp2; tmp0 = 2 * in[0]; tmp1 = 2 * in[1]; tmp2 = 2 * in[2]; out[0] = ((widelimb) in[0]) * in[0]; out[1] = ((widelimb) in[0]) * tmp1; out[2] = ((widelimb) in[0]) * tmp2 + ((widelimb) in[1]) * in[1]; out[3] = ((widelimb) in[3]) * tmp0 + ((widelimb) in[1]) * tmp2; out[4] = ((widelimb) in[3]) * tmp1 + ((widelimb) in[2]) * in[2]; out[5] = ((widelimb) in[3]) * tmp2; out[6] = ((widelimb) in[3]) * in[3]; } /* Multiply two field elements: out = in1 * in2 */ static void felem_mul(widefelem out, const felem in1, const felem in2) { out[0] = ((widelimb) in1[0]) * in2[0]; out[1] = ((widelimb) in1[0]) * in2[1] + ((widelimb) in1[1]) * in2[0]; out[2] = ((widelimb) in1[0]) * in2[2] + ((widelimb) in1[1]) * in2[1] + ((widelimb) in1[2]) * in2[0]; out[3] = ((widelimb) in1[0]) * in2[3] + ((widelimb) in1[1]) * in2[2] + ((widelimb) in1[2]) * in2[1] + ((widelimb) in1[3]) * in2[0]; out[4] = ((widelimb) in1[1]) * in2[3] + ((widelimb) in1[2]) * in2[2] + ((widelimb) in1[3]) * in2[1]; out[5] = ((widelimb) in1[2]) * in2[3] + ((widelimb) in1[3]) * in2[2]; out[6] = ((widelimb) in1[3]) * in2[3]; } /*- * Reduce seven 128-bit coefficients to four 64-bit coefficients. * Requires in[i] < 2^126, * ensures out[0] < 2^56, out[1] < 2^56, out[2] < 2^56, out[3] <= 2^56 + 2^16 */ static void felem_reduce(felem out, const widefelem in) { static const widelimb two127p15 = (((widelimb) 1) << 127) + (((widelimb) 1) << 15); static const widelimb two127m71 = (((widelimb) 1) << 127) - (((widelimb) 1) << 71); static const widelimb two127m71m55 = (((widelimb) 1) << 127) - (((widelimb) 1) << 71) - (((widelimb) 1) << 55); widelimb output[5]; /* Add 0 mod 2^224-2^96+1 to ensure all differences are positive */ output[0] = in[0] + two127p15; output[1] = in[1] + two127m71m55; output[2] = in[2] + two127m71; output[3] = in[3]; output[4] = in[4]; /* Eliminate in[4], in[5], in[6] */ output[4] += in[6] >> 16; output[3] += (in[6] & 0xffff) << 40; output[2] -= in[6]; output[3] += in[5] >> 16; output[2] += (in[5] & 0xffff) << 40; output[1] -= in[5]; output[2] += output[4] >> 16; output[1] += (output[4] & 0xffff) << 40; output[0] -= output[4]; /* Carry 2 -> 3 -> 4 */ output[3] += output[2] >> 56; output[2] &= 0x00ffffffffffffff; output[4] = output[3] >> 56; output[3] &= 0x00ffffffffffffff; /* Now output[2] < 2^56, output[3] < 2^56, output[4] < 2^72 */ /* Eliminate output[4] */ output[2] += output[4] >> 16; /* output[2] < 2^56 + 2^56 = 2^57 */ output[1] += (output[4] & 0xffff) << 40; output[0] -= output[4]; /* Carry 0 -> 1 -> 2 -> 3 */ output[1] += output[0] >> 56; out[0] = output[0] & 0x00ffffffffffffff; output[2] += output[1] >> 56; /* output[2] < 2^57 + 2^72 */ out[1] = output[1] & 0x00ffffffffffffff; output[3] += output[2] >> 56; /* output[3] <= 2^56 + 2^16 */ out[2] = output[2] & 0x00ffffffffffffff; /*- * out[0] < 2^56, out[1] < 2^56, out[2] < 2^56, * out[3] <= 2^56 + 2^16 (due to final carry), * so out < 2*p */ out[3] = output[3]; } static void felem_square_reduce(felem out, const felem in) { widefelem tmp; felem_square(tmp, in); felem_reduce(out, tmp); } static void felem_mul_reduce(felem out, const felem in1, const felem in2) { widefelem tmp; felem_mul(tmp, in1, in2); felem_reduce(out, tmp); } /* * Reduce to unique minimal representation. Requires 0 <= in < 2*p (always * call felem_reduce first) */ static void felem_contract(felem out, const felem in) { static const int64_t two56 = ((limb) 1) << 56; /* 0 <= in < 2*p, p = 2^224 - 2^96 + 1 */ /* if in > p , reduce in = in - 2^224 + 2^96 - 1 */ int64_t tmp[4], a; tmp[0] = in[0]; tmp[1] = in[1]; tmp[2] = in[2]; tmp[3] = in[3]; /* Case 1: a = 1 iff in >= 2^224 */ a = (in[3] >> 56); tmp[0] -= a; tmp[1] += a << 40; tmp[3] &= 0x00ffffffffffffff; /* * Case 2: a = 0 iff p <= in < 2^224, i.e., the high 128 bits are all 1 * and the lower part is non-zero */ a = ((in[3] & in[2] & (in[1] | 0x000000ffffffffff)) + 1) | (((int64_t) (in[0] + (in[1] & 0x000000ffffffffff)) - 1) >> 63); a &= 0x00ffffffffffffff; /* turn a into an all-one mask (if a = 0) or an all-zero mask */ a = (a - 1) >> 63; /* subtract 2^224 - 2^96 + 1 if a is all-one */ tmp[3] &= a ^ 0xffffffffffffffff; tmp[2] &= a ^ 0xffffffffffffffff; tmp[1] &= (a ^ 0xffffffffffffffff) | 0x000000ffffffffff; tmp[0] -= 1 & a; /* * eliminate negative coefficients: if tmp[0] is negative, tmp[1] must be * non-zero, so we only need one step */ a = tmp[0] >> 63; tmp[0] += two56 & a; tmp[1] -= 1 & a; /* carry 1 -> 2 -> 3 */ tmp[2] += tmp[1] >> 56; tmp[1] &= 0x00ffffffffffffff; tmp[3] += tmp[2] >> 56; tmp[2] &= 0x00ffffffffffffff; /* Now 0 <= out < p */ out[0] = tmp[0]; out[1] = tmp[1]; out[2] = tmp[2]; out[3] = tmp[3]; } /* * Zero-check: returns 1 if input is 0, and 0 otherwise. We know that field * elements are reduced to in < 2^225, so we only need to check three cases: * 0, 2^224 - 2^96 + 1, and 2^225 - 2^97 + 2 */ static limb felem_is_zero(const felem in) { limb zero, two224m96p1, two225m97p2; zero = in[0] | in[1] | in[2] | in[3]; zero = (((int64_t) (zero) - 1) >> 63) & 1; two224m96p1 = (in[0] ^ 1) | (in[1] ^ 0x00ffff0000000000) | (in[2] ^ 0x00ffffffffffffff) | (in[3] ^ 0x00ffffffffffffff); two224m96p1 = (((int64_t) (two224m96p1) - 1) >> 63) & 1; two225m97p2 = (in[0] ^ 2) | (in[1] ^ 0x00fffe0000000000) | (in[2] ^ 0x00ffffffffffffff) | (in[3] ^ 0x01ffffffffffffff); two225m97p2 = (((int64_t) (two225m97p2) - 1) >> 63) & 1; return (zero | two224m96p1 | two225m97p2); } -static limb felem_is_zero_int(const felem in) +static int felem_is_zero_int(const void *in) { return (int)(felem_is_zero(in) & ((limb) 1)); } /* Invert a field element */ /* Computation chain copied from djb's code */ static void felem_inv(felem out, const felem in) { felem ftmp, ftmp2, ftmp3, ftmp4; widefelem tmp; unsigned i; felem_square(tmp, in); felem_reduce(ftmp, tmp); /* 2 */ felem_mul(tmp, in, ftmp); felem_reduce(ftmp, tmp); /* 2^2 - 1 */ felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); /* 2^3 - 2 */ felem_mul(tmp, in, ftmp); felem_reduce(ftmp, tmp); /* 2^3 - 1 */ felem_square(tmp, ftmp); felem_reduce(ftmp2, tmp); /* 2^4 - 2 */ felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); /* 2^5 - 4 */ felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); /* 2^6 - 8 */ felem_mul(tmp, ftmp2, ftmp); felem_reduce(ftmp, tmp); /* 2^6 - 1 */ felem_square(tmp, ftmp); felem_reduce(ftmp2, tmp); /* 2^7 - 2 */ for (i = 0; i < 5; ++i) { /* 2^12 - 2^6 */ felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); } felem_mul(tmp, ftmp2, ftmp); felem_reduce(ftmp2, tmp); /* 2^12 - 1 */ felem_square(tmp, ftmp2); felem_reduce(ftmp3, tmp); /* 2^13 - 2 */ for (i = 0; i < 11; ++i) { /* 2^24 - 2^12 */ felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); } felem_mul(tmp, ftmp3, ftmp2); felem_reduce(ftmp2, tmp); /* 2^24 - 1 */ felem_square(tmp, ftmp2); felem_reduce(ftmp3, tmp); /* 2^25 - 2 */ for (i = 0; i < 23; ++i) { /* 2^48 - 2^24 */ felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); } felem_mul(tmp, ftmp3, ftmp2); felem_reduce(ftmp3, tmp); /* 2^48 - 1 */ felem_square(tmp, ftmp3); felem_reduce(ftmp4, tmp); /* 2^49 - 2 */ for (i = 0; i < 47; ++i) { /* 2^96 - 2^48 */ felem_square(tmp, ftmp4); felem_reduce(ftmp4, tmp); } felem_mul(tmp, ftmp3, ftmp4); felem_reduce(ftmp3, tmp); /* 2^96 - 1 */ felem_square(tmp, ftmp3); felem_reduce(ftmp4, tmp); /* 2^97 - 2 */ for (i = 0; i < 23; ++i) { /* 2^120 - 2^24 */ felem_square(tmp, ftmp4); felem_reduce(ftmp4, tmp); } felem_mul(tmp, ftmp2, ftmp4); felem_reduce(ftmp2, tmp); /* 2^120 - 1 */ for (i = 0; i < 6; ++i) { /* 2^126 - 2^6 */ felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); } felem_mul(tmp, ftmp2, ftmp); felem_reduce(ftmp, tmp); /* 2^126 - 1 */ felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); /* 2^127 - 2 */ felem_mul(tmp, ftmp, in); felem_reduce(ftmp, tmp); /* 2^127 - 1 */ for (i = 0; i < 97; ++i) { /* 2^224 - 2^97 */ felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); } felem_mul(tmp, ftmp, ftmp3); felem_reduce(out, tmp); /* 2^224 - 2^96 - 1 */ } /* * Copy in constant time: if icopy == 1, copy in to out, if icopy == 0, copy * out to itself. */ static void copy_conditional(felem out, const felem in, limb icopy) { unsigned i; /* * icopy is a (64-bit) 0 or 1, so copy is either all-zero or all-one */ const limb copy = -icopy; for (i = 0; i < 4; ++i) { const limb tmp = copy & (in[i] ^ out[i]); out[i] ^= tmp; } } /******************************************************************************/ /*- * ELLIPTIC CURVE POINT OPERATIONS * * Points are represented in Jacobian projective coordinates: * (X, Y, Z) corresponds to the affine point (X/Z^2, Y/Z^3), * or to the point at infinity if Z == 0. * */ /*- * Double an elliptic curve point: * (X', Y', Z') = 2 * (X, Y, Z), where * X' = (3 * (X - Z^2) * (X + Z^2))^2 - 8 * X * Y^2 * Y' = 3 * (X - Z^2) * (X + Z^2) * (4 * X * Y^2 - X') - 8 * Y^2 * Z' = (Y + Z)^2 - Y^2 - Z^2 = 2 * Y * Z * Outputs can equal corresponding inputs, i.e., x_out == x_in is allowed, * while x_out == y_in is not (maybe this works, but it's not tested). */ static void point_double(felem x_out, felem y_out, felem z_out, const felem x_in, const felem y_in, const felem z_in) { widefelem tmp, tmp2; felem delta, gamma, beta, alpha, ftmp, ftmp2; felem_assign(ftmp, x_in); felem_assign(ftmp2, x_in); /* delta = z^2 */ felem_square(tmp, z_in); felem_reduce(delta, tmp); /* gamma = y^2 */ felem_square(tmp, y_in); felem_reduce(gamma, tmp); /* beta = x*gamma */ felem_mul(tmp, x_in, gamma); felem_reduce(beta, tmp); /* alpha = 3*(x-delta)*(x+delta) */ felem_diff(ftmp, delta); /* ftmp[i] < 2^57 + 2^58 + 2 < 2^59 */ felem_sum(ftmp2, delta); /* ftmp2[i] < 2^57 + 2^57 = 2^58 */ felem_scalar(ftmp2, 3); /* ftmp2[i] < 3 * 2^58 < 2^60 */ felem_mul(tmp, ftmp, ftmp2); /* tmp[i] < 2^60 * 2^59 * 4 = 2^121 */ felem_reduce(alpha, tmp); /* x' = alpha^2 - 8*beta */ felem_square(tmp, alpha); /* tmp[i] < 4 * 2^57 * 2^57 = 2^116 */ felem_assign(ftmp, beta); felem_scalar(ftmp, 8); /* ftmp[i] < 8 * 2^57 = 2^60 */ felem_diff_128_64(tmp, ftmp); /* tmp[i] < 2^116 + 2^64 + 8 < 2^117 */ felem_reduce(x_out, tmp); /* z' = (y + z)^2 - gamma - delta */ felem_sum(delta, gamma); /* delta[i] < 2^57 + 2^57 = 2^58 */ felem_assign(ftmp, y_in); felem_sum(ftmp, z_in); /* ftmp[i] < 2^57 + 2^57 = 2^58 */ felem_square(tmp, ftmp); /* tmp[i] < 4 * 2^58 * 2^58 = 2^118 */ felem_diff_128_64(tmp, delta); /* tmp[i] < 2^118 + 2^64 + 8 < 2^119 */ felem_reduce(z_out, tmp); /* y' = alpha*(4*beta - x') - 8*gamma^2 */ felem_scalar(beta, 4); /* beta[i] < 4 * 2^57 = 2^59 */ felem_diff(beta, x_out); /* beta[i] < 2^59 + 2^58 + 2 < 2^60 */ felem_mul(tmp, alpha, beta); /* tmp[i] < 4 * 2^57 * 2^60 = 2^119 */ felem_square(tmp2, gamma); /* tmp2[i] < 4 * 2^57 * 2^57 = 2^116 */ widefelem_scalar(tmp2, 8); /* tmp2[i] < 8 * 2^116 = 2^119 */ widefelem_diff(tmp, tmp2); /* tmp[i] < 2^119 + 2^120 < 2^121 */ felem_reduce(y_out, tmp); } /*- * Add two elliptic curve points: * (X_1, Y_1, Z_1) + (X_2, Y_2, Z_2) = (X_3, Y_3, Z_3), where * X_3 = (Z_1^3 * Y_2 - Z_2^3 * Y_1)^2 - (Z_1^2 * X_2 - Z_2^2 * X_1)^3 - * 2 * Z_2^2 * X_1 * (Z_1^2 * X_2 - Z_2^2 * X_1)^2 * Y_3 = (Z_1^3 * Y_2 - Z_2^3 * Y_1) * (Z_2^2 * X_1 * (Z_1^2 * X_2 - Z_2^2 * X_1)^2 - X_3) - * Z_2^3 * Y_1 * (Z_1^2 * X_2 - Z_2^2 * X_1)^3 * Z_3 = (Z_1^2 * X_2 - Z_2^2 * X_1) * (Z_1 * Z_2) * * This runs faster if 'mixed' is set, which requires Z_2 = 1 or Z_2 = 0. */ /* * This function is not entirely constant-time: it includes a branch for * checking whether the two input points are equal, (while not equal to the * point at infinity). This case never happens during single point * multiplication, so there is no timing leak for ECDH or ECDSA signing. */ static void point_add(felem x3, felem y3, felem z3, const felem x1, const felem y1, const felem z1, const int mixed, const felem x2, const felem y2, const felem z2) { felem ftmp, ftmp2, ftmp3, ftmp4, ftmp5, x_out, y_out, z_out; widefelem tmp, tmp2; limb z1_is_zero, z2_is_zero, x_equal, y_equal; if (!mixed) { /* ftmp2 = z2^2 */ felem_square(tmp, z2); felem_reduce(ftmp2, tmp); /* ftmp4 = z2^3 */ felem_mul(tmp, ftmp2, z2); felem_reduce(ftmp4, tmp); /* ftmp4 = z2^3*y1 */ felem_mul(tmp2, ftmp4, y1); felem_reduce(ftmp4, tmp2); /* ftmp2 = z2^2*x1 */ felem_mul(tmp2, ftmp2, x1); felem_reduce(ftmp2, tmp2); } else { /* * We'll assume z2 = 1 (special case z2 = 0 is handled later) */ /* ftmp4 = z2^3*y1 */ felem_assign(ftmp4, y1); /* ftmp2 = z2^2*x1 */ felem_assign(ftmp2, x1); } /* ftmp = z1^2 */ felem_square(tmp, z1); felem_reduce(ftmp, tmp); /* ftmp3 = z1^3 */ felem_mul(tmp, ftmp, z1); felem_reduce(ftmp3, tmp); /* tmp = z1^3*y2 */ felem_mul(tmp, ftmp3, y2); /* tmp[i] < 4 * 2^57 * 2^57 = 2^116 */ /* ftmp3 = z1^3*y2 - z2^3*y1 */ felem_diff_128_64(tmp, ftmp4); /* tmp[i] < 2^116 + 2^64 + 8 < 2^117 */ felem_reduce(ftmp3, tmp); /* tmp = z1^2*x2 */ felem_mul(tmp, ftmp, x2); /* tmp[i] < 4 * 2^57 * 2^57 = 2^116 */ /* ftmp = z1^2*x2 - z2^2*x1 */ felem_diff_128_64(tmp, ftmp2); /* tmp[i] < 2^116 + 2^64 + 8 < 2^117 */ felem_reduce(ftmp, tmp); /* * the formulae are incorrect if the points are equal so we check for * this and do doubling if this happens */ x_equal = felem_is_zero(ftmp); y_equal = felem_is_zero(ftmp3); z1_is_zero = felem_is_zero(z1); z2_is_zero = felem_is_zero(z2); /* In affine coordinates, (X_1, Y_1) == (X_2, Y_2) */ if (x_equal && y_equal && !z1_is_zero && !z2_is_zero) { point_double(x3, y3, z3, x1, y1, z1); return; } /* ftmp5 = z1*z2 */ if (!mixed) { felem_mul(tmp, z1, z2); felem_reduce(ftmp5, tmp); } else { /* special case z2 = 0 is handled later */ felem_assign(ftmp5, z1); } /* z_out = (z1^2*x2 - z2^2*x1)*(z1*z2) */ felem_mul(tmp, ftmp, ftmp5); felem_reduce(z_out, tmp); /* ftmp = (z1^2*x2 - z2^2*x1)^2 */ felem_assign(ftmp5, ftmp); felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); /* ftmp5 = (z1^2*x2 - z2^2*x1)^3 */ felem_mul(tmp, ftmp, ftmp5); felem_reduce(ftmp5, tmp); /* ftmp2 = z2^2*x1*(z1^2*x2 - z2^2*x1)^2 */ felem_mul(tmp, ftmp2, ftmp); felem_reduce(ftmp2, tmp); /* tmp = z2^3*y1*(z1^2*x2 - z2^2*x1)^3 */ felem_mul(tmp, ftmp4, ftmp5); /* tmp[i] < 4 * 2^57 * 2^57 = 2^116 */ /* tmp2 = (z1^3*y2 - z2^3*y1)^2 */ felem_square(tmp2, ftmp3); /* tmp2[i] < 4 * 2^57 * 2^57 < 2^116 */ /* tmp2 = (z1^3*y2 - z2^3*y1)^2 - (z1^2*x2 - z2^2*x1)^3 */ felem_diff_128_64(tmp2, ftmp5); /* tmp2[i] < 2^116 + 2^64 + 8 < 2^117 */ /* ftmp5 = 2*z2^2*x1*(z1^2*x2 - z2^2*x1)^2 */ felem_assign(ftmp5, ftmp2); felem_scalar(ftmp5, 2); /* ftmp5[i] < 2 * 2^57 = 2^58 */ /*- * x_out = (z1^3*y2 - z2^3*y1)^2 - (z1^2*x2 - z2^2*x1)^3 - * 2*z2^2*x1*(z1^2*x2 - z2^2*x1)^2 */ felem_diff_128_64(tmp2, ftmp5); /* tmp2[i] < 2^117 + 2^64 + 8 < 2^118 */ felem_reduce(x_out, tmp2); /* ftmp2 = z2^2*x1*(z1^2*x2 - z2^2*x1)^2 - x_out */ felem_diff(ftmp2, x_out); /* ftmp2[i] < 2^57 + 2^58 + 2 < 2^59 */ /* * tmp2 = (z1^3*y2 - z2^3*y1)*(z2^2*x1*(z1^2*x2 - z2^2*x1)^2 - x_out) */ felem_mul(tmp2, ftmp3, ftmp2); /* tmp2[i] < 4 * 2^57 * 2^59 = 2^118 */ /*- * y_out = (z1^3*y2 - z2^3*y1)*(z2^2*x1*(z1^2*x2 - z2^2*x1)^2 - x_out) - * z2^3*y1*(z1^2*x2 - z2^2*x1)^3 */ widefelem_diff(tmp2, tmp); /* tmp2[i] < 2^118 + 2^120 < 2^121 */ felem_reduce(y_out, tmp2); /* * the result (x_out, y_out, z_out) is incorrect if one of the inputs is * the point at infinity, so we need to check for this separately */ /* * if point 1 is at infinity, copy point 2 to output, and vice versa */ copy_conditional(x_out, x2, z1_is_zero); copy_conditional(x_out, x1, z2_is_zero); copy_conditional(y_out, y2, z1_is_zero); copy_conditional(y_out, y1, z2_is_zero); copy_conditional(z_out, z2, z1_is_zero); copy_conditional(z_out, z1, z2_is_zero); felem_assign(x3, x_out); felem_assign(y3, y_out); felem_assign(z3, z_out); } /* * select_point selects the |idx|th point from a precomputation table and * copies it to out. * The pre_comp array argument should be size of |size| argument */ static void select_point(const u64 idx, unsigned int size, const felem pre_comp[][3], felem out[3]) { unsigned i, j; limb *outlimbs = &out[0][0]; memset(outlimbs, 0, 3 * sizeof(felem)); for (i = 0; i < size; i++) { const limb *inlimbs = &pre_comp[i][0][0]; u64 mask = i ^ idx; mask |= mask >> 4; mask |= mask >> 2; mask |= mask >> 1; mask &= 1; mask--; for (j = 0; j < 4 * 3; j++) outlimbs[j] |= inlimbs[j] & mask; } } /* get_bit returns the |i|th bit in |in| */ static char get_bit(const felem_bytearray in, unsigned i) { if (i >= 224) return 0; return (in[i >> 3] >> (i & 7)) & 1; } /* * Interleaved point multiplication using precomputed point multiples: The * small point multiples 0*P, 1*P, ..., 16*P are in pre_comp[], the scalars * in scalars[]. If g_scalar is non-NULL, we also add this multiple of the * generator, using certain (large) precomputed multiples in g_pre_comp. * Output point (X, Y, Z) is stored in x_out, y_out, z_out */ static void batch_mul(felem x_out, felem y_out, felem z_out, const felem_bytearray scalars[], const unsigned num_points, const u8 *g_scalar, const int mixed, const felem pre_comp[][17][3], const felem g_pre_comp[2][16][3]) { int i, skip; unsigned num; unsigned gen_mul = (g_scalar != NULL); felem nq[3], tmp[4]; u64 bits; u8 sign, digit; /* set nq to the point at infinity */ memset(nq, 0, 3 * sizeof(felem)); /* * Loop over all scalars msb-to-lsb, interleaving additions of multiples * of the generator (two in each of the last 28 rounds) and additions of * other points multiples (every 5th round). */ skip = 1; /* save two point operations in the first * round */ for (i = (num_points ? 220 : 27); i >= 0; --i) { /* double */ if (!skip) point_double(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2]); /* add multiples of the generator */ if (gen_mul && (i <= 27)) { /* first, look 28 bits upwards */ bits = get_bit(g_scalar, i + 196) << 3; bits |= get_bit(g_scalar, i + 140) << 2; bits |= get_bit(g_scalar, i + 84) << 1; bits |= get_bit(g_scalar, i + 28); /* select the point to add, in constant time */ select_point(bits, 16, g_pre_comp[1], tmp); if (!skip) { /* value 1 below is argument for "mixed" */ point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1, tmp[0], tmp[1], tmp[2]); } else { memcpy(nq, tmp, 3 * sizeof(felem)); skip = 0; } /* second, look at the current position */ bits = get_bit(g_scalar, i + 168) << 3; bits |= get_bit(g_scalar, i + 112) << 2; bits |= get_bit(g_scalar, i + 56) << 1; bits |= get_bit(g_scalar, i); /* select the point to add, in constant time */ select_point(bits, 16, g_pre_comp[0], tmp); point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1 /* mixed */ , tmp[0], tmp[1], tmp[2]); } /* do other additions every 5 doublings */ if (num_points && (i % 5 == 0)) { /* loop over all scalars */ for (num = 0; num < num_points; ++num) { bits = get_bit(scalars[num], i + 4) << 5; bits |= get_bit(scalars[num], i + 3) << 4; bits |= get_bit(scalars[num], i + 2) << 3; bits |= get_bit(scalars[num], i + 1) << 2; bits |= get_bit(scalars[num], i) << 1; bits |= get_bit(scalars[num], i - 1); ec_GFp_nistp_recode_scalar_bits(&sign, &digit, bits); /* select the point to add or subtract */ select_point(digit, 17, pre_comp[num], tmp); felem_neg(tmp[3], tmp[1]); /* (X, -Y, Z) is the negative * point */ copy_conditional(tmp[1], tmp[3], sign); if (!skip) { point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], mixed, tmp[0], tmp[1], tmp[2]); } else { memcpy(nq, tmp, 3 * sizeof(felem)); skip = 0; } } } } felem_assign(x_out, nq[0]); felem_assign(y_out, nq[1]); felem_assign(z_out, nq[2]); } /******************************************************************************/ /* * FUNCTIONS TO MANAGE PRECOMPUTATION */ static NISTP224_PRE_COMP *nistp224_pre_comp_new() { NISTP224_PRE_COMP *ret = NULL; ret = (NISTP224_PRE_COMP *) OPENSSL_malloc(sizeof *ret); if (!ret) { ECerr(EC_F_NISTP224_PRE_COMP_NEW, ERR_R_MALLOC_FAILURE); return ret; } memset(ret->g_pre_comp, 0, sizeof(ret->g_pre_comp)); ret->references = 1; return ret; } static void *nistp224_pre_comp_dup(void *src_) { NISTP224_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 nistp224_pre_comp_free(void *pre_) { int i; NISTP224_PRE_COMP *pre = pre_; if (!pre) return; i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP); if (i > 0) return; OPENSSL_free(pre); } static void nistp224_pre_comp_clear_free(void *pre_) { int i; NISTP224_PRE_COMP *pre = pre_; if (!pre) return; i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP); if (i > 0) return; OPENSSL_cleanse(pre, sizeof *pre); OPENSSL_free(pre); } /******************************************************************************/ /* * OPENSSL EC_METHOD FUNCTIONS */ int ec_GFp_nistp224_group_init(EC_GROUP *group) { int ret; ret = ec_GFp_simple_group_init(group); group->a_is_minus3 = 1; return ret; } int ec_GFp_nistp224_group_set_curve(EC_GROUP *group, const BIGNUM *p, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { int ret = 0; BN_CTX *new_ctx = NULL; BIGNUM *curve_p, *curve_a, *curve_b; if (ctx == NULL) if ((ctx = new_ctx = BN_CTX_new()) == NULL) return 0; BN_CTX_start(ctx); if (((curve_p = BN_CTX_get(ctx)) == NULL) || ((curve_a = BN_CTX_get(ctx)) == NULL) || ((curve_b = BN_CTX_get(ctx)) == NULL)) goto err; BN_bin2bn(nistp224_curve_params[0], sizeof(felem_bytearray), curve_p); BN_bin2bn(nistp224_curve_params[1], sizeof(felem_bytearray), curve_a); BN_bin2bn(nistp224_curve_params[2], sizeof(felem_bytearray), curve_b); if ((BN_cmp(curve_p, p)) || (BN_cmp(curve_a, a)) || (BN_cmp(curve_b, b))) { ECerr(EC_F_EC_GFP_NISTP224_GROUP_SET_CURVE, EC_R_WRONG_CURVE_PARAMETERS); goto err; } group->field_mod_func = BN_nist_mod_224; ret = ec_GFp_simple_group_set_curve(group, p, a, b, ctx); err: BN_CTX_end(ctx); if (new_ctx != NULL) BN_CTX_free(new_ctx); return ret; } /* * Takes the Jacobian coordinates (X, Y, Z) of a point and returns (X', Y') = * (X/Z^2, Y/Z^3) */ int ec_GFp_nistp224_point_get_affine_coordinates(const EC_GROUP *group, const EC_POINT *point, BIGNUM *x, BIGNUM *y, BN_CTX *ctx) { felem z1, z2, x_in, y_in, x_out, y_out; widefelem tmp; if (EC_POINT_is_at_infinity(group, point)) { ECerr(EC_F_EC_GFP_NISTP224_POINT_GET_AFFINE_COORDINATES, EC_R_POINT_AT_INFINITY); return 0; } if ((!BN_to_felem(x_in, &point->X)) || (!BN_to_felem(y_in, &point->Y)) || (!BN_to_felem(z1, &point->Z))) return 0; felem_inv(z2, z1); felem_square(tmp, z2); felem_reduce(z1, tmp); felem_mul(tmp, x_in, z1); felem_reduce(x_in, tmp); felem_contract(x_out, x_in); if (x != NULL) { if (!felem_to_BN(x, x_out)) { ECerr(EC_F_EC_GFP_NISTP224_POINT_GET_AFFINE_COORDINATES, ERR_R_BN_LIB); return 0; } } felem_mul(tmp, z1, z2); felem_reduce(z1, tmp); felem_mul(tmp, y_in, z1); felem_reduce(y_in, tmp); felem_contract(y_out, y_in); if (y != NULL) { if (!felem_to_BN(y, y_out)) { ECerr(EC_F_EC_GFP_NISTP224_POINT_GET_AFFINE_COORDINATES, ERR_R_BN_LIB); return 0; } } return 1; } static void make_points_affine(size_t num, felem points[ /* num */ ][3], felem tmp_felems[ /* num+1 */ ]) { /* * Runs in constant time, unless an input is the point at infinity (which * normally shouldn't happen). */ ec_GFp_nistp_points_make_affine_internal(num, points, sizeof(felem), tmp_felems, (void (*)(void *))felem_one, - (int (*)(const void *)) felem_is_zero_int, (void (*)(void *, const void *)) felem_assign, (void (*)(void *, const void *)) felem_square_reduce, (void (*) (void *, const void *, const void *)) felem_mul_reduce, (void (*)(void *, const void *)) felem_inv, (void (*)(void *, const void *)) felem_contract); } /* * Computes scalar*generator + \sum scalars[i]*points[i], ignoring NULL * values Result is stored in r (r can equal one of the inputs). */ int ec_GFp_nistp224_points_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar, size_t num, const EC_POINT *points[], const BIGNUM *scalars[], BN_CTX *ctx) { int ret = 0; int j; unsigned i; int mixed = 0; BN_CTX *new_ctx = NULL; BIGNUM *x, *y, *z, *tmp_scalar; felem_bytearray g_secret; felem_bytearray *secrets = NULL; felem(*pre_comp)[17][3] = NULL; felem *tmp_felems = NULL; felem_bytearray tmp; unsigned num_bytes; int have_pre_comp = 0; size_t num_points = num; felem x_in, y_in, z_in, x_out, y_out, z_out; NISTP224_PRE_COMP *pre = NULL; const felem(*g_pre_comp)[16][3] = NULL; EC_POINT *generator = NULL; const EC_POINT *p = NULL; const BIGNUM *p_scalar = NULL; if (ctx == NULL) if ((ctx = new_ctx = BN_CTX_new()) == NULL) return 0; BN_CTX_start(ctx); if (((x = BN_CTX_get(ctx)) == NULL) || ((y = BN_CTX_get(ctx)) == NULL) || ((z = BN_CTX_get(ctx)) == NULL) || ((tmp_scalar = BN_CTX_get(ctx)) == NULL)) goto err; if (scalar != NULL) { pre = EC_EX_DATA_get_data(group->extra_data, nistp224_pre_comp_dup, nistp224_pre_comp_free, nistp224_pre_comp_clear_free); if (pre) /* we have precomputation, try to use it */ g_pre_comp = (const felem(*)[16][3])pre->g_pre_comp; else /* try to use the standard precomputation */ g_pre_comp = &gmul[0]; generator = EC_POINT_new(group); if (generator == NULL) goto err; /* get the generator from precomputation */ if (!felem_to_BN(x, g_pre_comp[0][1][0]) || !felem_to_BN(y, g_pre_comp[0][1][1]) || !felem_to_BN(z, g_pre_comp[0][1][2])) { ECerr(EC_F_EC_GFP_NISTP224_POINTS_MUL, ERR_R_BN_LIB); goto err; } if (!EC_POINT_set_Jprojective_coordinates_GFp(group, generator, x, y, z, ctx)) goto err; if (0 == EC_POINT_cmp(group, generator, group->generator, ctx)) /* precomputation matches generator */ have_pre_comp = 1; else /* * we don't have valid precomputation: treat the generator as a * random point */ num_points = num_points + 1; } if (num_points > 0) { if (num_points >= 3) { /* * unless we precompute multiples for just one or two points, * converting those into affine form is time well spent */ mixed = 1; } secrets = OPENSSL_malloc(num_points * sizeof(felem_bytearray)); pre_comp = OPENSSL_malloc(num_points * 17 * 3 * sizeof(felem)); if (mixed) tmp_felems = OPENSSL_malloc((num_points * 17 + 1) * sizeof(felem)); if ((secrets == NULL) || (pre_comp == NULL) || (mixed && (tmp_felems == NULL))) { ECerr(EC_F_EC_GFP_NISTP224_POINTS_MUL, ERR_R_MALLOC_FAILURE); goto err; } /* * we treat NULL scalars as 0, and NULL points as points at infinity, * i.e., they contribute nothing to the linear combination */ memset(secrets, 0, num_points * sizeof(felem_bytearray)); memset(pre_comp, 0, num_points * 17 * 3 * sizeof(felem)); for (i = 0; i < num_points; ++i) { if (i == num) /* the generator */ { p = EC_GROUP_get0_generator(group); p_scalar = scalar; } else /* the i^th point */ { p = points[i]; p_scalar = scalars[i]; } if ((p_scalar != NULL) && (p != NULL)) { /* reduce scalar to 0 <= scalar < 2^224 */ if ((BN_num_bits(p_scalar) > 224) || (BN_is_negative(p_scalar))) { /* * this is an unusual input, and we don't guarantee * constant-timeness */ if (!BN_nnmod(tmp_scalar, p_scalar, &group->order, ctx)) { ECerr(EC_F_EC_GFP_NISTP224_POINTS_MUL, ERR_R_BN_LIB); goto err; } num_bytes = BN_bn2bin(tmp_scalar, tmp); } else num_bytes = BN_bn2bin(p_scalar, tmp); flip_endian(secrets[i], tmp, num_bytes); /* precompute multiples */ if ((!BN_to_felem(x_out, &p->X)) || (!BN_to_felem(y_out, &p->Y)) || (!BN_to_felem(z_out, &p->Z))) goto err; felem_assign(pre_comp[i][1][0], x_out); felem_assign(pre_comp[i][1][1], y_out); felem_assign(pre_comp[i][1][2], z_out); for (j = 2; j <= 16; ++j) { if (j & 1) { point_add(pre_comp[i][j][0], pre_comp[i][j][1], pre_comp[i][j][2], pre_comp[i][1][0], pre_comp[i][1][1], pre_comp[i][1][2], 0, pre_comp[i][j - 1][0], pre_comp[i][j - 1][1], pre_comp[i][j - 1][2]); } else { point_double(pre_comp[i][j][0], pre_comp[i][j][1], pre_comp[i][j][2], pre_comp[i][j / 2][0], pre_comp[i][j / 2][1], pre_comp[i][j / 2][2]); } } } } if (mixed) make_points_affine(num_points * 17, pre_comp[0], tmp_felems); } /* the scalar for the generator */ if ((scalar != NULL) && (have_pre_comp)) { memset(g_secret, 0, sizeof g_secret); /* reduce scalar to 0 <= scalar < 2^224 */ if ((BN_num_bits(scalar) > 224) || (BN_is_negative(scalar))) { /* * this is an unusual input, and we don't guarantee * constant-timeness */ if (!BN_nnmod(tmp_scalar, scalar, &group->order, ctx)) { ECerr(EC_F_EC_GFP_NISTP224_POINTS_MUL, ERR_R_BN_LIB); goto err; } num_bytes = BN_bn2bin(tmp_scalar, tmp); } else num_bytes = BN_bn2bin(scalar, tmp); flip_endian(g_secret, tmp, num_bytes); /* do the multiplication with generator precomputation */ batch_mul(x_out, y_out, z_out, (const felem_bytearray(*))secrets, num_points, g_secret, mixed, (const felem(*)[17][3])pre_comp, g_pre_comp); } else /* do the multiplication without generator precomputation */ batch_mul(x_out, y_out, z_out, (const felem_bytearray(*))secrets, num_points, NULL, mixed, (const felem(*)[17][3])pre_comp, NULL); /* reduce the output to its unique minimal representation */ felem_contract(x_in, x_out); felem_contract(y_in, y_out); felem_contract(z_in, z_out); if ((!felem_to_BN(x, x_in)) || (!felem_to_BN(y, y_in)) || (!felem_to_BN(z, z_in))) { ECerr(EC_F_EC_GFP_NISTP224_POINTS_MUL, ERR_R_BN_LIB); goto err; } ret = EC_POINT_set_Jprojective_coordinates_GFp(group, r, x, y, z, ctx); err: BN_CTX_end(ctx); if (generator != NULL) EC_POINT_free(generator); if (new_ctx != NULL) BN_CTX_free(new_ctx); if (secrets != NULL) OPENSSL_free(secrets); if (pre_comp != NULL) OPENSSL_free(pre_comp); if (tmp_felems != NULL) OPENSSL_free(tmp_felems); return ret; } int ec_GFp_nistp224_precompute_mult(EC_GROUP *group, BN_CTX *ctx) { int ret = 0; NISTP224_PRE_COMP *pre = NULL; int i, j; BN_CTX *new_ctx = NULL; BIGNUM *x, *y; EC_POINT *generator = NULL; felem tmp_felems[32]; /* throw away old precomputation */ EC_EX_DATA_free_data(&group->extra_data, nistp224_pre_comp_dup, nistp224_pre_comp_free, nistp224_pre_comp_clear_free); if (ctx == NULL) if ((ctx = new_ctx = BN_CTX_new()) == NULL) return 0; BN_CTX_start(ctx); if (((x = BN_CTX_get(ctx)) == NULL) || ((y = BN_CTX_get(ctx)) == NULL)) goto err; /* get the generator */ if (group->generator == NULL) goto err; generator = EC_POINT_new(group); if (generator == NULL) goto err; BN_bin2bn(nistp224_curve_params[3], sizeof(felem_bytearray), x); BN_bin2bn(nistp224_curve_params[4], sizeof(felem_bytearray), y); if (!EC_POINT_set_affine_coordinates_GFp(group, generator, x, y, ctx)) goto err; if ((pre = nistp224_pre_comp_new()) == NULL) goto err; /* * if the generator is the standard one, use built-in precomputation */ if (0 == EC_POINT_cmp(group, generator, group->generator, ctx)) { memcpy(pre->g_pre_comp, gmul, sizeof(pre->g_pre_comp)); goto done; } if ((!BN_to_felem(pre->g_pre_comp[0][1][0], &group->generator->X)) || (!BN_to_felem(pre->g_pre_comp[0][1][1], &group->generator->Y)) || (!BN_to_felem(pre->g_pre_comp[0][1][2], &group->generator->Z))) goto err; /* * compute 2^56*G, 2^112*G, 2^168*G for the first table, 2^28*G, 2^84*G, * 2^140*G, 2^196*G for the second one */ for (i = 1; i <= 8; i <<= 1) { point_double(pre->g_pre_comp[1][i][0], pre->g_pre_comp[1][i][1], pre->g_pre_comp[1][i][2], pre->g_pre_comp[0][i][0], pre->g_pre_comp[0][i][1], pre->g_pre_comp[0][i][2]); for (j = 0; j < 27; ++j) { point_double(pre->g_pre_comp[1][i][0], pre->g_pre_comp[1][i][1], pre->g_pre_comp[1][i][2], pre->g_pre_comp[1][i][0], pre->g_pre_comp[1][i][1], pre->g_pre_comp[1][i][2]); } if (i == 8) break; point_double(pre->g_pre_comp[0][2 * i][0], pre->g_pre_comp[0][2 * i][1], pre->g_pre_comp[0][2 * i][2], pre->g_pre_comp[1][i][0], pre->g_pre_comp[1][i][1], pre->g_pre_comp[1][i][2]); for (j = 0; j < 27; ++j) { point_double(pre->g_pre_comp[0][2 * i][0], pre->g_pre_comp[0][2 * i][1], pre->g_pre_comp[0][2 * i][2], pre->g_pre_comp[0][2 * i][0], pre->g_pre_comp[0][2 * i][1], pre->g_pre_comp[0][2 * i][2]); } } for (i = 0; i < 2; i++) { /* g_pre_comp[i][0] is the point at infinity */ memset(pre->g_pre_comp[i][0], 0, sizeof(pre->g_pre_comp[i][0])); /* the remaining multiples */ /* 2^56*G + 2^112*G resp. 2^84*G + 2^140*G */ point_add(pre->g_pre_comp[i][6][0], pre->g_pre_comp[i][6][1], pre->g_pre_comp[i][6][2], pre->g_pre_comp[i][4][0], pre->g_pre_comp[i][4][1], pre->g_pre_comp[i][4][2], 0, pre->g_pre_comp[i][2][0], pre->g_pre_comp[i][2][1], pre->g_pre_comp[i][2][2]); /* 2^56*G + 2^168*G resp. 2^84*G + 2^196*G */ point_add(pre->g_pre_comp[i][10][0], pre->g_pre_comp[i][10][1], pre->g_pre_comp[i][10][2], pre->g_pre_comp[i][8][0], pre->g_pre_comp[i][8][1], pre->g_pre_comp[i][8][2], 0, pre->g_pre_comp[i][2][0], pre->g_pre_comp[i][2][1], pre->g_pre_comp[i][2][2]); /* 2^112*G + 2^168*G resp. 2^140*G + 2^196*G */ point_add(pre->g_pre_comp[i][12][0], pre->g_pre_comp[i][12][1], pre->g_pre_comp[i][12][2], pre->g_pre_comp[i][8][0], pre->g_pre_comp[i][8][1], pre->g_pre_comp[i][8][2], 0, pre->g_pre_comp[i][4][0], pre->g_pre_comp[i][4][1], pre->g_pre_comp[i][4][2]); /* * 2^56*G + 2^112*G + 2^168*G resp. 2^84*G + 2^140*G + 2^196*G */ point_add(pre->g_pre_comp[i][14][0], pre->g_pre_comp[i][14][1], pre->g_pre_comp[i][14][2], pre->g_pre_comp[i][12][0], pre->g_pre_comp[i][12][1], pre->g_pre_comp[i][12][2], 0, pre->g_pre_comp[i][2][0], pre->g_pre_comp[i][2][1], pre->g_pre_comp[i][2][2]); for (j = 1; j < 8; ++j) { /* odd multiples: add G resp. 2^28*G */ point_add(pre->g_pre_comp[i][2 * j + 1][0], pre->g_pre_comp[i][2 * j + 1][1], pre->g_pre_comp[i][2 * j + 1][2], pre->g_pre_comp[i][2 * j][0], pre->g_pre_comp[i][2 * j][1], pre->g_pre_comp[i][2 * j][2], 0, pre->g_pre_comp[i][1][0], pre->g_pre_comp[i][1][1], pre->g_pre_comp[i][1][2]); } } make_points_affine(31, &(pre->g_pre_comp[0][1]), tmp_felems); done: if (!EC_EX_DATA_set_data(&group->extra_data, pre, nistp224_pre_comp_dup, nistp224_pre_comp_free, nistp224_pre_comp_clear_free)) goto err; ret = 1; pre = NULL; err: BN_CTX_end(ctx); if (generator != NULL) EC_POINT_free(generator); if (new_ctx != NULL) BN_CTX_free(new_ctx); if (pre) nistp224_pre_comp_free(pre); return ret; } int ec_GFp_nistp224_have_precompute_mult(const EC_GROUP *group) { if (EC_EX_DATA_get_data(group->extra_data, nistp224_pre_comp_dup, nistp224_pre_comp_free, nistp224_pre_comp_clear_free) != NULL) return 1; else return 0; } #else static void *dummy = &dummy; #endif Index: vendor-crypto/openssl/dist/crypto/ec/ecp_nistp256.c =================================================================== --- vendor-crypto/openssl/dist/crypto/ec/ecp_nistp256.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/ec/ecp_nistp256.c (revision 325326) @@ -1,2369 +1,2368 @@ /* crypto/ec/ecp_nistp256.c */ /* * Written by Adam Langley (Google) for the OpenSSL project */ /* Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * A 64-bit implementation of the NIST P-256 elliptic curve point multiplication * * OpenSSL integration was taken from Emilia Kasper's work in ecp_nistp224.c. * Otherwise based on Emilia's P224 work, which was inspired by my curve25519 * work which got its smarts from Daniel J. Bernstein's work on the same. */ #include #ifndef OPENSSL_NO_EC_NISTP_64_GCC_128 # ifndef OPENSSL_SYS_VMS # include # else # include # endif # include # include # include "ec_lcl.h" # if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) /* even with gcc, the typedef won't work for 32-bit platforms */ typedef __uint128_t uint128_t; /* nonstandard; implemented by gcc on 64-bit * platforms */ typedef __int128_t int128_t; # else # error "Need GCC 3.1 or later to define type uint128_t" # endif typedef uint8_t u8; typedef uint32_t u32; typedef uint64_t u64; typedef int64_t s64; /* * The underlying field. P256 operates over GF(2^256-2^224+2^192+2^96-1). We * can serialise an element of this field into 32 bytes. We call this an * felem_bytearray. */ typedef u8 felem_bytearray[32]; /* * These are the parameters of P256, taken from FIPS 186-3, page 86. These * values are big-endian. */ static const felem_bytearray nistp256_curve_params[5] = { {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, /* p */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, /* a = -3 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc}, /* b */ {0x5a, 0xc6, 0x35, 0xd8, 0xaa, 0x3a, 0x93, 0xe7, 0xb3, 0xeb, 0xbd, 0x55, 0x76, 0x98, 0x86, 0xbc, 0x65, 0x1d, 0x06, 0xb0, 0xcc, 0x53, 0xb0, 0xf6, 0x3b, 0xce, 0x3c, 0x3e, 0x27, 0xd2, 0x60, 0x4b}, {0x6b, 0x17, 0xd1, 0xf2, 0xe1, 0x2c, 0x42, 0x47, /* x */ 0xf8, 0xbc, 0xe6, 0xe5, 0x63, 0xa4, 0x40, 0xf2, 0x77, 0x03, 0x7d, 0x81, 0x2d, 0xeb, 0x33, 0xa0, 0xf4, 0xa1, 0x39, 0x45, 0xd8, 0x98, 0xc2, 0x96}, {0x4f, 0xe3, 0x42, 0xe2, 0xfe, 0x1a, 0x7f, 0x9b, /* y */ 0x8e, 0xe7, 0xeb, 0x4a, 0x7c, 0x0f, 0x9e, 0x16, 0x2b, 0xce, 0x33, 0x57, 0x6b, 0x31, 0x5e, 0xce, 0xcb, 0xb6, 0x40, 0x68, 0x37, 0xbf, 0x51, 0xf5} }; /*- * The representation of field elements. * ------------------------------------ * * We represent field elements with either four 128-bit values, eight 128-bit * values, or four 64-bit values. The field element represented is: * v[0]*2^0 + v[1]*2^64 + v[2]*2^128 + v[3]*2^192 (mod p) * or: * v[0]*2^0 + v[1]*2^64 + v[2]*2^128 + ... + v[8]*2^512 (mod p) * * 128-bit values are called 'limbs'. Since the limbs are spaced only 64 bits * apart, but are 128-bits wide, the most significant bits of each limb overlap * with the least significant bits of the next. * * A field element with four limbs is an 'felem'. One with eight limbs is a * 'longfelem' * * A field element with four, 64-bit values is called a 'smallfelem'. Small * values are used as intermediate values before multiplication. */ # define NLIMBS 4 typedef uint128_t limb; typedef limb felem[NLIMBS]; typedef limb longfelem[NLIMBS * 2]; typedef u64 smallfelem[NLIMBS]; /* This is the value of the prime as four 64-bit words, little-endian. */ static const u64 kPrime[4] = { 0xfffffffffffffffful, 0xffffffff, 0, 0xffffffff00000001ul }; static const u64 bottom63bits = 0x7ffffffffffffffful; /* * bin32_to_felem takes a little-endian byte array and converts it into felem * form. This assumes that the CPU is little-endian. */ static void bin32_to_felem(felem out, const u8 in[32]) { out[0] = *((u64 *)&in[0]); out[1] = *((u64 *)&in[8]); out[2] = *((u64 *)&in[16]); out[3] = *((u64 *)&in[24]); } /* * smallfelem_to_bin32 takes a smallfelem and serialises into a little * endian, 32 byte array. This assumes that the CPU is little-endian. */ static void smallfelem_to_bin32(u8 out[32], const smallfelem in) { *((u64 *)&out[0]) = in[0]; *((u64 *)&out[8]) = in[1]; *((u64 *)&out[16]) = in[2]; *((u64 *)&out[24]) = in[3]; } /* To preserve endianness when using BN_bn2bin and BN_bin2bn */ static void flip_endian(u8 *out, const u8 *in, unsigned len) { unsigned i; for (i = 0; i < len; ++i) out[i] = in[len - 1 - i]; } /* BN_to_felem converts an OpenSSL BIGNUM into an felem */ static int BN_to_felem(felem out, const BIGNUM *bn) { felem_bytearray b_in; felem_bytearray b_out; unsigned num_bytes; /* BN_bn2bin eats leading zeroes */ memset(b_out, 0, sizeof b_out); num_bytes = BN_num_bytes(bn); if (num_bytes > sizeof b_out) { ECerr(EC_F_BN_TO_FELEM, EC_R_BIGNUM_OUT_OF_RANGE); return 0; } if (BN_is_negative(bn)) { ECerr(EC_F_BN_TO_FELEM, EC_R_BIGNUM_OUT_OF_RANGE); return 0; } num_bytes = BN_bn2bin(bn, b_in); flip_endian(b_out, b_in, num_bytes); bin32_to_felem(out, b_out); return 1; } /* felem_to_BN converts an felem into an OpenSSL BIGNUM */ static BIGNUM *smallfelem_to_BN(BIGNUM *out, const smallfelem in) { felem_bytearray b_in, b_out; smallfelem_to_bin32(b_in, in); flip_endian(b_out, b_in, sizeof b_out); return BN_bin2bn(b_out, sizeof b_out, out); } /*- * Field operations * ---------------- */ static void smallfelem_one(smallfelem out) { out[0] = 1; out[1] = 0; out[2] = 0; out[3] = 0; } static void smallfelem_assign(smallfelem out, const smallfelem in) { out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; out[3] = in[3]; } static void felem_assign(felem out, const felem in) { out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; out[3] = in[3]; } /* felem_sum sets out = out + in. */ static void felem_sum(felem out, const felem in) { out[0] += in[0]; out[1] += in[1]; out[2] += in[2]; out[3] += in[3]; } /* felem_small_sum sets out = out + in. */ static void felem_small_sum(felem out, const smallfelem in) { out[0] += in[0]; out[1] += in[1]; out[2] += in[2]; out[3] += in[3]; } /* felem_scalar sets out = out * scalar */ static void felem_scalar(felem out, const u64 scalar) { out[0] *= scalar; out[1] *= scalar; out[2] *= scalar; out[3] *= scalar; } /* longfelem_scalar sets out = out * scalar */ static void longfelem_scalar(longfelem out, const u64 scalar) { out[0] *= scalar; out[1] *= scalar; out[2] *= scalar; out[3] *= scalar; out[4] *= scalar; out[5] *= scalar; out[6] *= scalar; out[7] *= scalar; } # define two105m41m9 (((limb)1) << 105) - (((limb)1) << 41) - (((limb)1) << 9) # define two105 (((limb)1) << 105) # define two105m41p9 (((limb)1) << 105) - (((limb)1) << 41) + (((limb)1) << 9) /* zero105 is 0 mod p */ static const felem zero105 = { two105m41m9, two105, two105m41p9, two105m41p9 }; /*- * smallfelem_neg sets |out| to |-small| * On exit: * out[i] < out[i] + 2^105 */ static void smallfelem_neg(felem out, const smallfelem small) { /* In order to prevent underflow, we subtract from 0 mod p. */ out[0] = zero105[0] - small[0]; out[1] = zero105[1] - small[1]; out[2] = zero105[2] - small[2]; out[3] = zero105[3] - small[3]; } /*- * felem_diff subtracts |in| from |out| * On entry: * in[i] < 2^104 * On exit: * out[i] < out[i] + 2^105 */ static void felem_diff(felem out, const felem in) { /* * In order to prevent underflow, we add 0 mod p before subtracting. */ out[0] += zero105[0]; out[1] += zero105[1]; out[2] += zero105[2]; out[3] += zero105[3]; out[0] -= in[0]; out[1] -= in[1]; out[2] -= in[2]; out[3] -= in[3]; } # define two107m43m11 (((limb)1) << 107) - (((limb)1) << 43) - (((limb)1) << 11) # define two107 (((limb)1) << 107) # define two107m43p11 (((limb)1) << 107) - (((limb)1) << 43) + (((limb)1) << 11) /* zero107 is 0 mod p */ static const felem zero107 = { two107m43m11, two107, two107m43p11, two107m43p11 }; /*- * An alternative felem_diff for larger inputs |in| * felem_diff_zero107 subtracts |in| from |out| * On entry: * in[i] < 2^106 * On exit: * out[i] < out[i] + 2^107 */ static void felem_diff_zero107(felem out, const felem in) { /* * In order to prevent underflow, we add 0 mod p before subtracting. */ out[0] += zero107[0]; out[1] += zero107[1]; out[2] += zero107[2]; out[3] += zero107[3]; out[0] -= in[0]; out[1] -= in[1]; out[2] -= in[2]; out[3] -= in[3]; } /*- * longfelem_diff subtracts |in| from |out| * On entry: * in[i] < 7*2^67 * On exit: * out[i] < out[i] + 2^70 + 2^40 */ static void longfelem_diff(longfelem out, const longfelem in) { static const limb two70m8p6 = (((limb) 1) << 70) - (((limb) 1) << 8) + (((limb) 1) << 6); static const limb two70p40 = (((limb) 1) << 70) + (((limb) 1) << 40); static const limb two70 = (((limb) 1) << 70); static const limb two70m40m38p6 = (((limb) 1) << 70) - (((limb) 1) << 40) - (((limb) 1) << 38) + (((limb) 1) << 6); static const limb two70m6 = (((limb) 1) << 70) - (((limb) 1) << 6); /* add 0 mod p to avoid underflow */ out[0] += two70m8p6; out[1] += two70p40; out[2] += two70; out[3] += two70m40m38p6; out[4] += two70m6; out[5] += two70m6; out[6] += two70m6; out[7] += two70m6; /* in[i] < 7*2^67 < 2^70 - 2^40 - 2^38 + 2^6 */ out[0] -= in[0]; out[1] -= in[1]; out[2] -= in[2]; out[3] -= in[3]; out[4] -= in[4]; out[5] -= in[5]; out[6] -= in[6]; out[7] -= in[7]; } # define two64m0 (((limb)1) << 64) - 1 # define two110p32m0 (((limb)1) << 110) + (((limb)1) << 32) - 1 # define two64m46 (((limb)1) << 64) - (((limb)1) << 46) # define two64m32 (((limb)1) << 64) - (((limb)1) << 32) /* zero110 is 0 mod p */ static const felem zero110 = { two64m0, two110p32m0, two64m46, two64m32 }; /*- * felem_shrink converts an felem into a smallfelem. The result isn't quite * minimal as the value may be greater than p. * * On entry: * in[i] < 2^109 * On exit: * out[i] < 2^64 */ static void felem_shrink(smallfelem out, const felem in) { felem tmp; u64 a, b, mask; s64 high, low; static const u64 kPrime3Test = 0x7fffffff00000001ul; /* 2^63 - 2^32 + 1 */ /* Carry 2->3 */ tmp[3] = zero110[3] + in[3] + ((u64)(in[2] >> 64)); /* tmp[3] < 2^110 */ tmp[2] = zero110[2] + (u64)in[2]; tmp[0] = zero110[0] + in[0]; tmp[1] = zero110[1] + in[1]; /* tmp[0] < 2**110, tmp[1] < 2^111, tmp[2] < 2**65 */ /* * We perform two partial reductions where we eliminate the high-word of * tmp[3]. We don't update the other words till the end. */ a = tmp[3] >> 64; /* a < 2^46 */ tmp[3] = (u64)tmp[3]; tmp[3] -= a; tmp[3] += ((limb) a) << 32; /* tmp[3] < 2^79 */ b = a; a = tmp[3] >> 64; /* a < 2^15 */ b += a; /* b < 2^46 + 2^15 < 2^47 */ tmp[3] = (u64)tmp[3]; tmp[3] -= a; tmp[3] += ((limb) a) << 32; /* tmp[3] < 2^64 + 2^47 */ /* * This adjusts the other two words to complete the two partial * reductions. */ tmp[0] += b; tmp[1] -= (((limb) b) << 32); /* * In order to make space in tmp[3] for the carry from 2 -> 3, we * conditionally subtract kPrime if tmp[3] is large enough. */ high = tmp[3] >> 64; /* As tmp[3] < 2^65, high is either 1 or 0 */ high <<= 63; high >>= 63; /*- * high is: * all ones if the high word of tmp[3] is 1 * all zeros if the high word of tmp[3] if 0 */ low = tmp[3]; mask = low >> 63; /*- * mask is: * all ones if the MSB of low is 1 * all zeros if the MSB of low if 0 */ low &= bottom63bits; low -= kPrime3Test; /* if low was greater than kPrime3Test then the MSB is zero */ low = ~low; low >>= 63; /*- * low is: * all ones if low was > kPrime3Test * all zeros if low was <= kPrime3Test */ mask = (mask & low) | high; tmp[0] -= mask & kPrime[0]; tmp[1] -= mask & kPrime[1]; /* kPrime[2] is zero, so omitted */ tmp[3] -= mask & kPrime[3]; /* tmp[3] < 2**64 - 2**32 + 1 */ tmp[1] += ((u64)(tmp[0] >> 64)); tmp[0] = (u64)tmp[0]; tmp[2] += ((u64)(tmp[1] >> 64)); tmp[1] = (u64)tmp[1]; tmp[3] += ((u64)(tmp[2] >> 64)); tmp[2] = (u64)tmp[2]; /* tmp[i] < 2^64 */ out[0] = tmp[0]; out[1] = tmp[1]; out[2] = tmp[2]; out[3] = tmp[3]; } /* smallfelem_expand converts a smallfelem to an felem */ static void smallfelem_expand(felem out, const smallfelem in) { out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; out[3] = in[3]; } /*- * smallfelem_square sets |out| = |small|^2 * On entry: * small[i] < 2^64 * On exit: * out[i] < 7 * 2^64 < 2^67 */ static void smallfelem_square(longfelem out, const smallfelem small) { limb a; u64 high, low; a = ((uint128_t) small[0]) * small[0]; low = a; high = a >> 64; out[0] = low; out[1] = high; a = ((uint128_t) small[0]) * small[1]; low = a; high = a >> 64; out[1] += low; out[1] += low; out[2] = high; a = ((uint128_t) small[0]) * small[2]; low = a; high = a >> 64; out[2] += low; out[2] *= 2; out[3] = high; a = ((uint128_t) small[0]) * small[3]; low = a; high = a >> 64; out[3] += low; out[4] = high; a = ((uint128_t) small[1]) * small[2]; low = a; high = a >> 64; out[3] += low; out[3] *= 2; out[4] += high; a = ((uint128_t) small[1]) * small[1]; low = a; high = a >> 64; out[2] += low; out[3] += high; a = ((uint128_t) small[1]) * small[3]; low = a; high = a >> 64; out[4] += low; out[4] *= 2; out[5] = high; a = ((uint128_t) small[2]) * small[3]; low = a; high = a >> 64; out[5] += low; out[5] *= 2; out[6] = high; out[6] += high; a = ((uint128_t) small[2]) * small[2]; low = a; high = a >> 64; out[4] += low; out[5] += high; a = ((uint128_t) small[3]) * small[3]; low = a; high = a >> 64; out[6] += low; out[7] = high; } /*- * felem_square sets |out| = |in|^2 * On entry: * in[i] < 2^109 * On exit: * out[i] < 7 * 2^64 < 2^67 */ static void felem_square(longfelem out, const felem in) { u64 small[4]; felem_shrink(small, in); smallfelem_square(out, small); } /*- * smallfelem_mul sets |out| = |small1| * |small2| * On entry: * small1[i] < 2^64 * small2[i] < 2^64 * On exit: * out[i] < 7 * 2^64 < 2^67 */ static void smallfelem_mul(longfelem out, const smallfelem small1, const smallfelem small2) { limb a; u64 high, low; a = ((uint128_t) small1[0]) * small2[0]; low = a; high = a >> 64; out[0] = low; out[1] = high; a = ((uint128_t) small1[0]) * small2[1]; low = a; high = a >> 64; out[1] += low; out[2] = high; a = ((uint128_t) small1[1]) * small2[0]; low = a; high = a >> 64; out[1] += low; out[2] += high; a = ((uint128_t) small1[0]) * small2[2]; low = a; high = a >> 64; out[2] += low; out[3] = high; a = ((uint128_t) small1[1]) * small2[1]; low = a; high = a >> 64; out[2] += low; out[3] += high; a = ((uint128_t) small1[2]) * small2[0]; low = a; high = a >> 64; out[2] += low; out[3] += high; a = ((uint128_t) small1[0]) * small2[3]; low = a; high = a >> 64; out[3] += low; out[4] = high; a = ((uint128_t) small1[1]) * small2[2]; low = a; high = a >> 64; out[3] += low; out[4] += high; a = ((uint128_t) small1[2]) * small2[1]; low = a; high = a >> 64; out[3] += low; out[4] += high; a = ((uint128_t) small1[3]) * small2[0]; low = a; high = a >> 64; out[3] += low; out[4] += high; a = ((uint128_t) small1[1]) * small2[3]; low = a; high = a >> 64; out[4] += low; out[5] = high; a = ((uint128_t) small1[2]) * small2[2]; low = a; high = a >> 64; out[4] += low; out[5] += high; a = ((uint128_t) small1[3]) * small2[1]; low = a; high = a >> 64; out[4] += low; out[5] += high; a = ((uint128_t) small1[2]) * small2[3]; low = a; high = a >> 64; out[5] += low; out[6] = high; a = ((uint128_t) small1[3]) * small2[2]; low = a; high = a >> 64; out[5] += low; out[6] += high; a = ((uint128_t) small1[3]) * small2[3]; low = a; high = a >> 64; out[6] += low; out[7] = high; } /*- * felem_mul sets |out| = |in1| * |in2| * On entry: * in1[i] < 2^109 * in2[i] < 2^109 * On exit: * out[i] < 7 * 2^64 < 2^67 */ static void felem_mul(longfelem out, const felem in1, const felem in2) { smallfelem small1, small2; felem_shrink(small1, in1); felem_shrink(small2, in2); smallfelem_mul(out, small1, small2); } /*- * felem_small_mul sets |out| = |small1| * |in2| * On entry: * small1[i] < 2^64 * in2[i] < 2^109 * On exit: * out[i] < 7 * 2^64 < 2^67 */ static void felem_small_mul(longfelem out, const smallfelem small1, const felem in2) { smallfelem small2; felem_shrink(small2, in2); smallfelem_mul(out, small1, small2); } # define two100m36m4 (((limb)1) << 100) - (((limb)1) << 36) - (((limb)1) << 4) # define two100 (((limb)1) << 100) # define two100m36p4 (((limb)1) << 100) - (((limb)1) << 36) + (((limb)1) << 4) /* zero100 is 0 mod p */ static const felem zero100 = { two100m36m4, two100, two100m36p4, two100m36p4 }; /*- * Internal function for the different flavours of felem_reduce. * felem_reduce_ reduces the higher coefficients in[4]-in[7]. * On entry: * out[0] >= in[6] + 2^32*in[6] + in[7] + 2^32*in[7] * out[1] >= in[7] + 2^32*in[4] * out[2] >= in[5] + 2^32*in[5] * out[3] >= in[4] + 2^32*in[5] + 2^32*in[6] * On exit: * out[0] <= out[0] + in[4] + 2^32*in[5] * out[1] <= out[1] + in[5] + 2^33*in[6] * out[2] <= out[2] + in[7] + 2*in[6] + 2^33*in[7] * out[3] <= out[3] + 2^32*in[4] + 3*in[7] */ static void felem_reduce_(felem out, const longfelem in) { int128_t c; /* combine common terms from below */ c = in[4] + (in[5] << 32); out[0] += c; out[3] -= c; c = in[5] - in[7]; out[1] += c; out[2] -= c; /* the remaining terms */ /* 256: [(0,1),(96,-1),(192,-1),(224,1)] */ out[1] -= (in[4] << 32); out[3] += (in[4] << 32); /* 320: [(32,1),(64,1),(128,-1),(160,-1),(224,-1)] */ out[2] -= (in[5] << 32); /* 384: [(0,-1),(32,-1),(96,2),(128,2),(224,-1)] */ out[0] -= in[6]; out[0] -= (in[6] << 32); out[1] += (in[6] << 33); out[2] += (in[6] * 2); out[3] -= (in[6] << 32); /* 448: [(0,-1),(32,-1),(64,-1),(128,1),(160,2),(192,3)] */ out[0] -= in[7]; out[0] -= (in[7] << 32); out[2] += (in[7] << 33); out[3] += (in[7] * 3); } /*- * felem_reduce converts a longfelem into an felem. * To be called directly after felem_square or felem_mul. * On entry: * in[0] < 2^64, in[1] < 3*2^64, in[2] < 5*2^64, in[3] < 7*2^64 * in[4] < 7*2^64, in[5] < 5*2^64, in[6] < 3*2^64, in[7] < 2*64 * On exit: * out[i] < 2^101 */ static void felem_reduce(felem out, const longfelem in) { out[0] = zero100[0] + in[0]; out[1] = zero100[1] + in[1]; out[2] = zero100[2] + in[2]; out[3] = zero100[3] + in[3]; felem_reduce_(out, in); /*- * out[0] > 2^100 - 2^36 - 2^4 - 3*2^64 - 3*2^96 - 2^64 - 2^96 > 0 * out[1] > 2^100 - 2^64 - 7*2^96 > 0 * out[2] > 2^100 - 2^36 + 2^4 - 5*2^64 - 5*2^96 > 0 * out[3] > 2^100 - 2^36 + 2^4 - 7*2^64 - 5*2^96 - 3*2^96 > 0 * * out[0] < 2^100 + 2^64 + 7*2^64 + 5*2^96 < 2^101 * out[1] < 2^100 + 3*2^64 + 5*2^64 + 3*2^97 < 2^101 * out[2] < 2^100 + 5*2^64 + 2^64 + 3*2^65 + 2^97 < 2^101 * out[3] < 2^100 + 7*2^64 + 7*2^96 + 3*2^64 < 2^101 */ } /*- * felem_reduce_zero105 converts a larger longfelem into an felem. * On entry: * in[0] < 2^71 * On exit: * out[i] < 2^106 */ static void felem_reduce_zero105(felem out, const longfelem in) { out[0] = zero105[0] + in[0]; out[1] = zero105[1] + in[1]; out[2] = zero105[2] + in[2]; out[3] = zero105[3] + in[3]; felem_reduce_(out, in); /*- * out[0] > 2^105 - 2^41 - 2^9 - 2^71 - 2^103 - 2^71 - 2^103 > 0 * out[1] > 2^105 - 2^71 - 2^103 > 0 * out[2] > 2^105 - 2^41 + 2^9 - 2^71 - 2^103 > 0 * out[3] > 2^105 - 2^41 + 2^9 - 2^71 - 2^103 - 2^103 > 0 * * out[0] < 2^105 + 2^71 + 2^71 + 2^103 < 2^106 * out[1] < 2^105 + 2^71 + 2^71 + 2^103 < 2^106 * out[2] < 2^105 + 2^71 + 2^71 + 2^71 + 2^103 < 2^106 * out[3] < 2^105 + 2^71 + 2^103 + 2^71 < 2^106 */ } /* * subtract_u64 sets *result = *result - v and *carry to one if the * subtraction underflowed. */ static void subtract_u64(u64 *result, u64 *carry, u64 v) { uint128_t r = *result; r -= v; *carry = (r >> 64) & 1; *result = (u64)r; } /* * felem_contract converts |in| to its unique, minimal representation. On * entry: in[i] < 2^109 */ static void felem_contract(smallfelem out, const felem in) { unsigned i; u64 all_equal_so_far = 0, result = 0, carry; felem_shrink(out, in); /* small is minimal except that the value might be > p */ all_equal_so_far--; /* * We are doing a constant time test if out >= kPrime. We need to compare * each u64, from most-significant to least significant. For each one, if * all words so far have been equal (m is all ones) then a non-equal * result is the answer. Otherwise we continue. */ for (i = 3; i < 4; i--) { u64 equal; uint128_t a = ((uint128_t) kPrime[i]) - out[i]; /* * if out[i] > kPrime[i] then a will underflow and the high 64-bits * will all be set. */ result |= all_equal_so_far & ((u64)(a >> 64)); /* * if kPrime[i] == out[i] then |equal| will be all zeros and the * decrement will make it all ones. */ equal = kPrime[i] ^ out[i]; equal--; equal &= equal << 32; equal &= equal << 16; equal &= equal << 8; equal &= equal << 4; equal &= equal << 2; equal &= equal << 1; equal = ((s64) equal) >> 63; all_equal_so_far &= equal; } /* * if all_equal_so_far is still all ones then the two values are equal * and so out >= kPrime is true. */ result |= all_equal_so_far; /* if out >= kPrime then we subtract kPrime. */ subtract_u64(&out[0], &carry, result & kPrime[0]); subtract_u64(&out[1], &carry, carry); subtract_u64(&out[2], &carry, carry); subtract_u64(&out[3], &carry, carry); subtract_u64(&out[1], &carry, result & kPrime[1]); subtract_u64(&out[2], &carry, carry); subtract_u64(&out[3], &carry, carry); subtract_u64(&out[2], &carry, result & kPrime[2]); subtract_u64(&out[3], &carry, carry); subtract_u64(&out[3], &carry, result & kPrime[3]); } static void smallfelem_square_contract(smallfelem out, const smallfelem in) { longfelem longtmp; felem tmp; smallfelem_square(longtmp, in); felem_reduce(tmp, longtmp); felem_contract(out, tmp); } static void smallfelem_mul_contract(smallfelem out, const smallfelem in1, const smallfelem in2) { longfelem longtmp; felem tmp; smallfelem_mul(longtmp, in1, in2); felem_reduce(tmp, longtmp); felem_contract(out, tmp); } /*- * felem_is_zero returns a limb with all bits set if |in| == 0 (mod p) and 0 * otherwise. * On entry: * small[i] < 2^64 */ static limb smallfelem_is_zero(const smallfelem small) { limb result; u64 is_p; u64 is_zero = small[0] | small[1] | small[2] | small[3]; is_zero--; is_zero &= is_zero << 32; is_zero &= is_zero << 16; is_zero &= is_zero << 8; is_zero &= is_zero << 4; is_zero &= is_zero << 2; is_zero &= is_zero << 1; is_zero = ((s64) is_zero) >> 63; is_p = (small[0] ^ kPrime[0]) | (small[1] ^ kPrime[1]) | (small[2] ^ kPrime[2]) | (small[3] ^ kPrime[3]); is_p--; is_p &= is_p << 32; is_p &= is_p << 16; is_p &= is_p << 8; is_p &= is_p << 4; is_p &= is_p << 2; is_p &= is_p << 1; is_p = ((s64) is_p) >> 63; is_zero |= is_p; result = is_zero; result |= ((limb) is_zero) << 64; return result; } -static int smallfelem_is_zero_int(const smallfelem small) +static int smallfelem_is_zero_int(const void *small) { return (int)(smallfelem_is_zero(small) & ((limb) 1)); } /*- * felem_inv calculates |out| = |in|^{-1} * * Based on Fermat's Little Theorem: * a^p = a (mod p) * a^{p-1} = 1 (mod p) * a^{p-2} = a^{-1} (mod p) */ static void felem_inv(felem out, const felem in) { felem ftmp, ftmp2; /* each e_I will hold |in|^{2^I - 1} */ felem e2, e4, e8, e16, e32, e64; longfelem tmp; unsigned i; felem_square(tmp, in); felem_reduce(ftmp, tmp); /* 2^1 */ felem_mul(tmp, in, ftmp); felem_reduce(ftmp, tmp); /* 2^2 - 2^0 */ felem_assign(e2, ftmp); felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); /* 2^3 - 2^1 */ felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); /* 2^4 - 2^2 */ felem_mul(tmp, ftmp, e2); felem_reduce(ftmp, tmp); /* 2^4 - 2^0 */ felem_assign(e4, ftmp); felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); /* 2^5 - 2^1 */ felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); /* 2^6 - 2^2 */ felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); /* 2^7 - 2^3 */ felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); /* 2^8 - 2^4 */ felem_mul(tmp, ftmp, e4); felem_reduce(ftmp, tmp); /* 2^8 - 2^0 */ felem_assign(e8, ftmp); for (i = 0; i < 8; i++) { felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); } /* 2^16 - 2^8 */ felem_mul(tmp, ftmp, e8); felem_reduce(ftmp, tmp); /* 2^16 - 2^0 */ felem_assign(e16, ftmp); for (i = 0; i < 16; i++) { felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); } /* 2^32 - 2^16 */ felem_mul(tmp, ftmp, e16); felem_reduce(ftmp, tmp); /* 2^32 - 2^0 */ felem_assign(e32, ftmp); for (i = 0; i < 32; i++) { felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); } /* 2^64 - 2^32 */ felem_assign(e64, ftmp); felem_mul(tmp, ftmp, in); felem_reduce(ftmp, tmp); /* 2^64 - 2^32 + 2^0 */ for (i = 0; i < 192; i++) { felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); } /* 2^256 - 2^224 + 2^192 */ felem_mul(tmp, e64, e32); felem_reduce(ftmp2, tmp); /* 2^64 - 2^0 */ for (i = 0; i < 16; i++) { felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); } /* 2^80 - 2^16 */ felem_mul(tmp, ftmp2, e16); felem_reduce(ftmp2, tmp); /* 2^80 - 2^0 */ for (i = 0; i < 8; i++) { felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); } /* 2^88 - 2^8 */ felem_mul(tmp, ftmp2, e8); felem_reduce(ftmp2, tmp); /* 2^88 - 2^0 */ for (i = 0; i < 4; i++) { felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); } /* 2^92 - 2^4 */ felem_mul(tmp, ftmp2, e4); felem_reduce(ftmp2, tmp); /* 2^92 - 2^0 */ felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); /* 2^93 - 2^1 */ felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); /* 2^94 - 2^2 */ felem_mul(tmp, ftmp2, e2); felem_reduce(ftmp2, tmp); /* 2^94 - 2^0 */ felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); /* 2^95 - 2^1 */ felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); /* 2^96 - 2^2 */ felem_mul(tmp, ftmp2, in); felem_reduce(ftmp2, tmp); /* 2^96 - 3 */ felem_mul(tmp, ftmp2, ftmp); felem_reduce(out, tmp); /* 2^256 - 2^224 + 2^192 + 2^96 - 3 */ } static void smallfelem_inv_contract(smallfelem out, const smallfelem in) { felem tmp; smallfelem_expand(tmp, in); felem_inv(tmp, tmp); felem_contract(out, tmp); } /*- * Group operations * ---------------- * * Building on top of the field operations we have the operations on the * elliptic curve group itself. Points on the curve are represented in Jacobian * coordinates */ /*- * point_double calculates 2*(x_in, y_in, z_in) * * The method is taken from: * http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b * * Outputs can equal corresponding inputs, i.e., x_out == x_in is allowed. * while x_out == y_in is not (maybe this works, but it's not tested). */ static void point_double(felem x_out, felem y_out, felem z_out, const felem x_in, const felem y_in, const felem z_in) { longfelem tmp, tmp2; felem delta, gamma, beta, alpha, ftmp, ftmp2; smallfelem small1, small2; felem_assign(ftmp, x_in); /* ftmp[i] < 2^106 */ felem_assign(ftmp2, x_in); /* ftmp2[i] < 2^106 */ /* delta = z^2 */ felem_square(tmp, z_in); felem_reduce(delta, tmp); /* delta[i] < 2^101 */ /* gamma = y^2 */ felem_square(tmp, y_in); felem_reduce(gamma, tmp); /* gamma[i] < 2^101 */ felem_shrink(small1, gamma); /* beta = x*gamma */ felem_small_mul(tmp, small1, x_in); felem_reduce(beta, tmp); /* beta[i] < 2^101 */ /* alpha = 3*(x-delta)*(x+delta) */ felem_diff(ftmp, delta); /* ftmp[i] < 2^105 + 2^106 < 2^107 */ felem_sum(ftmp2, delta); /* ftmp2[i] < 2^105 + 2^106 < 2^107 */ felem_scalar(ftmp2, 3); /* ftmp2[i] < 3 * 2^107 < 2^109 */ felem_mul(tmp, ftmp, ftmp2); felem_reduce(alpha, tmp); /* alpha[i] < 2^101 */ felem_shrink(small2, alpha); /* x' = alpha^2 - 8*beta */ smallfelem_square(tmp, small2); felem_reduce(x_out, tmp); felem_assign(ftmp, beta); felem_scalar(ftmp, 8); /* ftmp[i] < 8 * 2^101 = 2^104 */ felem_diff(x_out, ftmp); /* x_out[i] < 2^105 + 2^101 < 2^106 */ /* z' = (y + z)^2 - gamma - delta */ felem_sum(delta, gamma); /* delta[i] < 2^101 + 2^101 = 2^102 */ felem_assign(ftmp, y_in); felem_sum(ftmp, z_in); /* ftmp[i] < 2^106 + 2^106 = 2^107 */ felem_square(tmp, ftmp); felem_reduce(z_out, tmp); felem_diff(z_out, delta); /* z_out[i] < 2^105 + 2^101 < 2^106 */ /* y' = alpha*(4*beta - x') - 8*gamma^2 */ felem_scalar(beta, 4); /* beta[i] < 4 * 2^101 = 2^103 */ felem_diff_zero107(beta, x_out); /* beta[i] < 2^107 + 2^103 < 2^108 */ felem_small_mul(tmp, small2, beta); /* tmp[i] < 7 * 2^64 < 2^67 */ smallfelem_square(tmp2, small1); /* tmp2[i] < 7 * 2^64 */ longfelem_scalar(tmp2, 8); /* tmp2[i] < 8 * 7 * 2^64 = 7 * 2^67 */ longfelem_diff(tmp, tmp2); /* tmp[i] < 2^67 + 2^70 + 2^40 < 2^71 */ felem_reduce_zero105(y_out, tmp); /* y_out[i] < 2^106 */ } /* * point_double_small is the same as point_double, except that it operates on * smallfelems */ static void point_double_small(smallfelem x_out, smallfelem y_out, smallfelem z_out, const smallfelem x_in, const smallfelem y_in, const smallfelem z_in) { felem felem_x_out, felem_y_out, felem_z_out; felem felem_x_in, felem_y_in, felem_z_in; smallfelem_expand(felem_x_in, x_in); smallfelem_expand(felem_y_in, y_in); smallfelem_expand(felem_z_in, z_in); point_double(felem_x_out, felem_y_out, felem_z_out, felem_x_in, felem_y_in, felem_z_in); felem_shrink(x_out, felem_x_out); felem_shrink(y_out, felem_y_out); felem_shrink(z_out, felem_z_out); } /* copy_conditional copies in to out iff mask is all ones. */ static void copy_conditional(felem out, const felem in, limb mask) { unsigned i; for (i = 0; i < NLIMBS; ++i) { const limb tmp = mask & (in[i] ^ out[i]); out[i] ^= tmp; } } /* copy_small_conditional copies in to out iff mask is all ones. */ static void copy_small_conditional(felem out, const smallfelem in, limb mask) { unsigned i; const u64 mask64 = mask; for (i = 0; i < NLIMBS; ++i) { out[i] = ((limb) (in[i] & mask64)) | (out[i] & ~mask); } } /*- * point_add calcuates (x1, y1, z1) + (x2, y2, z2) * * The method is taken from: * http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#addition-add-2007-bl, * adapted for mixed addition (z2 = 1, or z2 = 0 for the point at infinity). * * This function includes a branch for checking whether the two input points * are equal, (while not equal to the point at infinity). This case never * happens during single point multiplication, so there is no timing leak for * ECDH or ECDSA signing. */ static void point_add(felem x3, felem y3, felem z3, const felem x1, const felem y1, const felem z1, const int mixed, const smallfelem x2, const smallfelem y2, const smallfelem z2) { felem ftmp, ftmp2, ftmp3, ftmp4, ftmp5, ftmp6, x_out, y_out, z_out; longfelem tmp, tmp2; smallfelem small1, small2, small3, small4, small5; limb x_equal, y_equal, z1_is_zero, z2_is_zero; felem_shrink(small3, z1); z1_is_zero = smallfelem_is_zero(small3); z2_is_zero = smallfelem_is_zero(z2); /* ftmp = z1z1 = z1**2 */ smallfelem_square(tmp, small3); felem_reduce(ftmp, tmp); /* ftmp[i] < 2^101 */ felem_shrink(small1, ftmp); if (!mixed) { /* ftmp2 = z2z2 = z2**2 */ smallfelem_square(tmp, z2); felem_reduce(ftmp2, tmp); /* ftmp2[i] < 2^101 */ felem_shrink(small2, ftmp2); felem_shrink(small5, x1); /* u1 = ftmp3 = x1*z2z2 */ smallfelem_mul(tmp, small5, small2); felem_reduce(ftmp3, tmp); /* ftmp3[i] < 2^101 */ /* ftmp5 = z1 + z2 */ felem_assign(ftmp5, z1); felem_small_sum(ftmp5, z2); /* ftmp5[i] < 2^107 */ /* ftmp5 = (z1 + z2)**2 - (z1z1 + z2z2) = 2z1z2 */ felem_square(tmp, ftmp5); felem_reduce(ftmp5, tmp); /* ftmp2 = z2z2 + z1z1 */ felem_sum(ftmp2, ftmp); /* ftmp2[i] < 2^101 + 2^101 = 2^102 */ felem_diff(ftmp5, ftmp2); /* ftmp5[i] < 2^105 + 2^101 < 2^106 */ /* ftmp2 = z2 * z2z2 */ smallfelem_mul(tmp, small2, z2); felem_reduce(ftmp2, tmp); /* s1 = ftmp2 = y1 * z2**3 */ felem_mul(tmp, y1, ftmp2); felem_reduce(ftmp6, tmp); /* ftmp6[i] < 2^101 */ } else { /* * We'll assume z2 = 1 (special case z2 = 0 is handled later) */ /* u1 = ftmp3 = x1*z2z2 */ felem_assign(ftmp3, x1); /* ftmp3[i] < 2^106 */ /* ftmp5 = 2z1z2 */ felem_assign(ftmp5, z1); felem_scalar(ftmp5, 2); /* ftmp5[i] < 2*2^106 = 2^107 */ /* s1 = ftmp2 = y1 * z2**3 */ felem_assign(ftmp6, y1); /* ftmp6[i] < 2^106 */ } /* u2 = x2*z1z1 */ smallfelem_mul(tmp, x2, small1); felem_reduce(ftmp4, tmp); /* h = ftmp4 = u2 - u1 */ felem_diff_zero107(ftmp4, ftmp3); /* ftmp4[i] < 2^107 + 2^101 < 2^108 */ felem_shrink(small4, ftmp4); x_equal = smallfelem_is_zero(small4); /* z_out = ftmp5 * h */ felem_small_mul(tmp, small4, ftmp5); felem_reduce(z_out, tmp); /* z_out[i] < 2^101 */ /* ftmp = z1 * z1z1 */ smallfelem_mul(tmp, small1, small3); felem_reduce(ftmp, tmp); /* s2 = tmp = y2 * z1**3 */ felem_small_mul(tmp, y2, ftmp); felem_reduce(ftmp5, tmp); /* r = ftmp5 = (s2 - s1)*2 */ felem_diff_zero107(ftmp5, ftmp6); /* ftmp5[i] < 2^107 + 2^107 = 2^108 */ felem_scalar(ftmp5, 2); /* ftmp5[i] < 2^109 */ felem_shrink(small1, ftmp5); y_equal = smallfelem_is_zero(small1); if (x_equal && y_equal && !z1_is_zero && !z2_is_zero) { point_double(x3, y3, z3, x1, y1, z1); return; } /* I = ftmp = (2h)**2 */ felem_assign(ftmp, ftmp4); felem_scalar(ftmp, 2); /* ftmp[i] < 2*2^108 = 2^109 */ felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); /* J = ftmp2 = h * I */ felem_mul(tmp, ftmp4, ftmp); felem_reduce(ftmp2, tmp); /* V = ftmp4 = U1 * I */ felem_mul(tmp, ftmp3, ftmp); felem_reduce(ftmp4, tmp); /* x_out = r**2 - J - 2V */ smallfelem_square(tmp, small1); felem_reduce(x_out, tmp); felem_assign(ftmp3, ftmp4); felem_scalar(ftmp4, 2); felem_sum(ftmp4, ftmp2); /* ftmp4[i] < 2*2^101 + 2^101 < 2^103 */ felem_diff(x_out, ftmp4); /* x_out[i] < 2^105 + 2^101 */ /* y_out = r(V-x_out) - 2 * s1 * J */ felem_diff_zero107(ftmp3, x_out); /* ftmp3[i] < 2^107 + 2^101 < 2^108 */ felem_small_mul(tmp, small1, ftmp3); felem_mul(tmp2, ftmp6, ftmp2); longfelem_scalar(tmp2, 2); /* tmp2[i] < 2*2^67 = 2^68 */ longfelem_diff(tmp, tmp2); /* tmp[i] < 2^67 + 2^70 + 2^40 < 2^71 */ felem_reduce_zero105(y_out, tmp); /* y_out[i] < 2^106 */ copy_small_conditional(x_out, x2, z1_is_zero); copy_conditional(x_out, x1, z2_is_zero); copy_small_conditional(y_out, y2, z1_is_zero); copy_conditional(y_out, y1, z2_is_zero); copy_small_conditional(z_out, z2, z1_is_zero); copy_conditional(z_out, z1, z2_is_zero); felem_assign(x3, x_out); felem_assign(y3, y_out); felem_assign(z3, z_out); } /* * point_add_small is the same as point_add, except that it operates on * smallfelems */ static void point_add_small(smallfelem x3, smallfelem y3, smallfelem z3, smallfelem x1, smallfelem y1, smallfelem z1, smallfelem x2, smallfelem y2, smallfelem z2) { felem felem_x3, felem_y3, felem_z3; felem felem_x1, felem_y1, felem_z1; smallfelem_expand(felem_x1, x1); smallfelem_expand(felem_y1, y1); smallfelem_expand(felem_z1, z1); point_add(felem_x3, felem_y3, felem_z3, felem_x1, felem_y1, felem_z1, 0, x2, y2, z2); felem_shrink(x3, felem_x3); felem_shrink(y3, felem_y3); felem_shrink(z3, felem_z3); } /*- * Base point pre computation * -------------------------- * * Two different sorts of precomputed tables are used in the following code. * Each contain various points on the curve, where each point is three field * elements (x, y, z). * * For the base point table, z is usually 1 (0 for the point at infinity). * This table has 2 * 16 elements, starting with the following: * index | bits | point * ------+---------+------------------------------ * 0 | 0 0 0 0 | 0G * 1 | 0 0 0 1 | 1G * 2 | 0 0 1 0 | 2^64G * 3 | 0 0 1 1 | (2^64 + 1)G * 4 | 0 1 0 0 | 2^128G * 5 | 0 1 0 1 | (2^128 + 1)G * 6 | 0 1 1 0 | (2^128 + 2^64)G * 7 | 0 1 1 1 | (2^128 + 2^64 + 1)G * 8 | 1 0 0 0 | 2^192G * 9 | 1 0 0 1 | (2^192 + 1)G * 10 | 1 0 1 0 | (2^192 + 2^64)G * 11 | 1 0 1 1 | (2^192 + 2^64 + 1)G * 12 | 1 1 0 0 | (2^192 + 2^128)G * 13 | 1 1 0 1 | (2^192 + 2^128 + 1)G * 14 | 1 1 1 0 | (2^192 + 2^128 + 2^64)G * 15 | 1 1 1 1 | (2^192 + 2^128 + 2^64 + 1)G * followed by a copy of this with each element multiplied by 2^32. * * The reason for this is so that we can clock bits into four different * locations when doing simple scalar multiplies against the base point, * and then another four locations using the second 16 elements. * * Tables for other points have table[i] = iG for i in 0 .. 16. */ /* gmul is the table of precomputed base points */ static const smallfelem gmul[2][16][3] = { {{{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}, {{0xf4a13945d898c296, 0x77037d812deb33a0, 0xf8bce6e563a440f2, 0x6b17d1f2e12c4247}, {0xcbb6406837bf51f5, 0x2bce33576b315ece, 0x8ee7eb4a7c0f9e16, 0x4fe342e2fe1a7f9b}, {1, 0, 0, 0}}, {{0x90e75cb48e14db63, 0x29493baaad651f7e, 0x8492592e326e25de, 0x0fa822bc2811aaa5}, {0xe41124545f462ee7, 0x34b1a65050fe82f5, 0x6f4ad4bcb3df188b, 0xbff44ae8f5dba80d}, {1, 0, 0, 0}}, {{0x93391ce2097992af, 0xe96c98fd0d35f1fa, 0xb257c0de95e02789, 0x300a4bbc89d6726f}, {0xaa54a291c08127a0, 0x5bb1eeada9d806a5, 0x7f1ddb25ff1e3c6f, 0x72aac7e0d09b4644}, {1, 0, 0, 0}}, {{0x57c84fc9d789bd85, 0xfc35ff7dc297eac3, 0xfb982fd588c6766e, 0x447d739beedb5e67}, {0x0c7e33c972e25b32, 0x3d349b95a7fae500, 0xe12e9d953a4aaff7, 0x2d4825ab834131ee}, {1, 0, 0, 0}}, {{0x13949c932a1d367f, 0xef7fbd2b1a0a11b7, 0xddc6068bb91dfc60, 0xef9519328a9c72ff}, {0x196035a77376d8a8, 0x23183b0895ca1740, 0xc1ee9807022c219c, 0x611e9fc37dbb2c9b}, {1, 0, 0, 0}}, {{0xcae2b1920b57f4bc, 0x2936df5ec6c9bc36, 0x7dea6482e11238bf, 0x550663797b51f5d8}, {0x44ffe216348a964c, 0x9fb3d576dbdefbe1, 0x0afa40018d9d50e5, 0x157164848aecb851}, {1, 0, 0, 0}}, {{0xe48ecafffc5cde01, 0x7ccd84e70d715f26, 0xa2e8f483f43e4391, 0xeb5d7745b21141ea}, {0xcac917e2731a3479, 0x85f22cfe2844b645, 0x0990e6a158006cee, 0xeafd72ebdbecc17b}, {1, 0, 0, 0}}, {{0x6cf20ffb313728be, 0x96439591a3c6b94a, 0x2736ff8344315fc5, 0xa6d39677a7849276}, {0xf2bab833c357f5f4, 0x824a920c2284059b, 0x66b8babd2d27ecdf, 0x674f84749b0b8816}, {1, 0, 0, 0}}, {{0x2df48c04677c8a3e, 0x74e02f080203a56b, 0x31855f7db8c7fedb, 0x4e769e7672c9ddad}, {0xa4c36165b824bbb0, 0xfb9ae16f3b9122a5, 0x1ec0057206947281, 0x42b99082de830663}, {1, 0, 0, 0}}, {{0x6ef95150dda868b9, 0xd1f89e799c0ce131, 0x7fdc1ca008a1c478, 0x78878ef61c6ce04d}, {0x9c62b9121fe0d976, 0x6ace570ebde08d4f, 0xde53142c12309def, 0xb6cb3f5d7b72c321}, {1, 0, 0, 0}}, {{0x7f991ed2c31a3573, 0x5b82dd5bd54fb496, 0x595c5220812ffcae, 0x0c88bc4d716b1287}, {0x3a57bf635f48aca8, 0x7c8181f4df2564f3, 0x18d1b5b39c04e6aa, 0xdd5ddea3f3901dc6}, {1, 0, 0, 0}}, {{0xe96a79fb3e72ad0c, 0x43a0a28c42ba792f, 0xefe0a423083e49f3, 0x68f344af6b317466}, {0xcdfe17db3fb24d4a, 0x668bfc2271f5c626, 0x604ed93c24d67ff3, 0x31b9c405f8540a20}, {1, 0, 0, 0}}, {{0xd36b4789a2582e7f, 0x0d1a10144ec39c28, 0x663c62c3edbad7a0, 0x4052bf4b6f461db9}, {0x235a27c3188d25eb, 0xe724f33999bfcc5b, 0x862be6bd71d70cc8, 0xfecf4d5190b0fc61}, {1, 0, 0, 0}}, {{0x74346c10a1d4cfac, 0xafdf5cc08526a7a4, 0x123202a8f62bff7a, 0x1eddbae2c802e41a}, {0x8fa0af2dd603f844, 0x36e06b7e4c701917, 0x0c45f45273db33a0, 0x43104d86560ebcfc}, {1, 0, 0, 0}}, {{0x9615b5110d1d78e5, 0x66b0de3225c4744b, 0x0a4a46fb6aaf363a, 0xb48e26b484f7a21c}, {0x06ebb0f621a01b2d, 0xc004e4048b7b0f98, 0x64131bcdfed6f668, 0xfac015404d4d3dab}, {1, 0, 0, 0}}}, {{{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}, {{0x3a5a9e22185a5943, 0x1ab919365c65dfb6, 0x21656b32262c71da, 0x7fe36b40af22af89}, {0xd50d152c699ca101, 0x74b3d5867b8af212, 0x9f09f40407dca6f1, 0xe697d45825b63624}, {1, 0, 0, 0}}, {{0xa84aa9397512218e, 0xe9a521b074ca0141, 0x57880b3a18a2e902, 0x4a5b506612a677a6}, {0x0beada7a4c4f3840, 0x626db15419e26d9d, 0xc42604fbe1627d40, 0xeb13461ceac089f1}, {1, 0, 0, 0}}, {{0xf9faed0927a43281, 0x5e52c4144103ecbc, 0xc342967aa815c857, 0x0781b8291c6a220a}, {0x5a8343ceeac55f80, 0x88f80eeee54a05e3, 0x97b2a14f12916434, 0x690cde8df0151593}, {1, 0, 0, 0}}, {{0xaee9c75df7f82f2a, 0x9e4c35874afdf43a, 0xf5622df437371326, 0x8a535f566ec73617}, {0xc5f9a0ac223094b7, 0xcde533864c8c7669, 0x37e02819085a92bf, 0x0455c08468b08bd7}, {1, 0, 0, 0}}, {{0x0c0a6e2c9477b5d9, 0xf9a4bf62876dc444, 0x5050a949b6cdc279, 0x06bada7ab77f8276}, {0xc8b4aed1ea48dac9, 0xdebd8a4b7ea1070f, 0x427d49101366eb70, 0x5b476dfd0e6cb18a}, {1, 0, 0, 0}}, {{0x7c5c3e44278c340a, 0x4d54606812d66f3b, 0x29a751b1ae23c5d8, 0x3e29864e8a2ec908}, {0x142d2a6626dbb850, 0xad1744c4765bd780, 0x1f150e68e322d1ed, 0x239b90ea3dc31e7e}, {1, 0, 0, 0}}, {{0x78c416527a53322a, 0x305dde6709776f8e, 0xdbcab759f8862ed4, 0x820f4dd949f72ff7}, {0x6cc544a62b5debd4, 0x75be5d937b4e8cc4, 0x1b481b1b215c14d3, 0x140406ec783a05ec}, {1, 0, 0, 0}}, {{0x6a703f10e895df07, 0xfd75f3fa01876bd8, 0xeb5b06e70ce08ffe, 0x68f6b8542783dfee}, {0x90c76f8a78712655, 0xcf5293d2f310bf7f, 0xfbc8044dfda45028, 0xcbe1feba92e40ce6}, {1, 0, 0, 0}}, {{0xe998ceea4396e4c1, 0xfc82ef0b6acea274, 0x230f729f2250e927, 0xd0b2f94d2f420109}, {0x4305adddb38d4966, 0x10b838f8624c3b45, 0x7db2636658954e7a, 0x971459828b0719e5}, {1, 0, 0, 0}}, {{0x4bd6b72623369fc9, 0x57f2929e53d0b876, 0xc2d5cba4f2340687, 0x961610004a866aba}, {0x49997bcd2e407a5e, 0x69ab197d92ddcb24, 0x2cf1f2438fe5131c, 0x7acb9fadcee75e44}, {1, 0, 0, 0}}, {{0x254e839423d2d4c0, 0xf57f0c917aea685b, 0xa60d880f6f75aaea, 0x24eb9acca333bf5b}, {0xe3de4ccb1cda5dea, 0xfeef9341c51a6b4f, 0x743125f88bac4c4d, 0x69f891c5acd079cc}, {1, 0, 0, 0}}, {{0xeee44b35702476b5, 0x7ed031a0e45c2258, 0xb422d1e7bd6f8514, 0xe51f547c5972a107}, {0xa25bcd6fc9cf343d, 0x8ca922ee097c184e, 0xa62f98b3a9fe9a06, 0x1c309a2b25bb1387}, {1, 0, 0, 0}}, {{0x9295dbeb1967c459, 0xb00148833472c98e, 0xc504977708011828, 0x20b87b8aa2c4e503}, {0x3063175de057c277, 0x1bd539338fe582dd, 0x0d11adef5f69a044, 0xf5c6fa49919776be}, {1, 0, 0, 0}}, {{0x8c944e760fd59e11, 0x3876cba1102fad5f, 0xa454c3fad83faa56, 0x1ed7d1b9332010b9}, {0xa1011a270024b889, 0x05e4d0dcac0cd344, 0x52b520f0eb6a2a24, 0x3a2b03f03217257a}, {1, 0, 0, 0}}, {{0xf20fc2afdf1d043d, 0xf330240db58d5a62, 0xfc7d229ca0058c3b, 0x15fee545c78dd9f6}, {0x501e82885bc98cda, 0x41ef80e5d046ac04, 0x557d9f49461210fb, 0x4ab5b6b2b8753f81}, {1, 0, 0, 0}}} }; /* * select_point selects the |idx|th point from a precomputation table and * copies it to out. */ static void select_point(const u64 idx, unsigned int size, const smallfelem pre_comp[16][3], smallfelem out[3]) { unsigned i, j; u64 *outlimbs = &out[0][0]; memset(outlimbs, 0, 3 * sizeof(smallfelem)); for (i = 0; i < size; i++) { const u64 *inlimbs = (u64 *)&pre_comp[i][0][0]; u64 mask = i ^ idx; mask |= mask >> 4; mask |= mask >> 2; mask |= mask >> 1; mask &= 1; mask--; for (j = 0; j < NLIMBS * 3; j++) outlimbs[j] |= inlimbs[j] & mask; } } /* get_bit returns the |i|th bit in |in| */ static char get_bit(const felem_bytearray in, int i) { if ((i < 0) || (i >= 256)) return 0; return (in[i >> 3] >> (i & 7)) & 1; } /* * Interleaved point multiplication using precomputed point multiples: The * small point multiples 0*P, 1*P, ..., 17*P are in pre_comp[], the scalars * in scalars[]. If g_scalar is non-NULL, we also add this multiple of the * generator, using certain (large) precomputed multiples in g_pre_comp. * Output point (X, Y, Z) is stored in x_out, y_out, z_out */ static void batch_mul(felem x_out, felem y_out, felem z_out, const felem_bytearray scalars[], const unsigned num_points, const u8 *g_scalar, const int mixed, const smallfelem pre_comp[][17][3], const smallfelem g_pre_comp[2][16][3]) { int i, skip; unsigned num, gen_mul = (g_scalar != NULL); felem nq[3], ftmp; smallfelem tmp[3]; u64 bits; u8 sign, digit; /* set nq to the point at infinity */ memset(nq, 0, 3 * sizeof(felem)); /* * Loop over all scalars msb-to-lsb, interleaving additions of multiples * of the generator (two in each of the last 32 rounds) and additions of * other points multiples (every 5th round). */ skip = 1; /* save two point operations in the first * round */ for (i = (num_points ? 255 : 31); i >= 0; --i) { /* double */ if (!skip) point_double(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2]); /* add multiples of the generator */ if (gen_mul && (i <= 31)) { /* first, look 32 bits upwards */ bits = get_bit(g_scalar, i + 224) << 3; bits |= get_bit(g_scalar, i + 160) << 2; bits |= get_bit(g_scalar, i + 96) << 1; bits |= get_bit(g_scalar, i + 32); /* select the point to add, in constant time */ select_point(bits, 16, g_pre_comp[1], tmp); if (!skip) { /* Arg 1 below is for "mixed" */ point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1, tmp[0], tmp[1], tmp[2]); } else { smallfelem_expand(nq[0], tmp[0]); smallfelem_expand(nq[1], tmp[1]); smallfelem_expand(nq[2], tmp[2]); skip = 0; } /* second, look at the current position */ bits = get_bit(g_scalar, i + 192) << 3; bits |= get_bit(g_scalar, i + 128) << 2; bits |= get_bit(g_scalar, i + 64) << 1; bits |= get_bit(g_scalar, i); /* select the point to add, in constant time */ select_point(bits, 16, g_pre_comp[0], tmp); /* Arg 1 below is for "mixed" */ point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1, tmp[0], tmp[1], tmp[2]); } /* do other additions every 5 doublings */ if (num_points && (i % 5 == 0)) { /* loop over all scalars */ for (num = 0; num < num_points; ++num) { bits = get_bit(scalars[num], i + 4) << 5; bits |= get_bit(scalars[num], i + 3) << 4; bits |= get_bit(scalars[num], i + 2) << 3; bits |= get_bit(scalars[num], i + 1) << 2; bits |= get_bit(scalars[num], i) << 1; bits |= get_bit(scalars[num], i - 1); ec_GFp_nistp_recode_scalar_bits(&sign, &digit, bits); /* * select the point to add or subtract, in constant time */ select_point(digit, 17, pre_comp[num], tmp); smallfelem_neg(ftmp, tmp[1]); /* (X, -Y, Z) is the negative * point */ copy_small_conditional(ftmp, tmp[1], (((limb) sign) - 1)); felem_contract(tmp[1], ftmp); if (!skip) { point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], mixed, tmp[0], tmp[1], tmp[2]); } else { smallfelem_expand(nq[0], tmp[0]); smallfelem_expand(nq[1], tmp[1]); smallfelem_expand(nq[2], tmp[2]); skip = 0; } } } } felem_assign(x_out, nq[0]); felem_assign(y_out, nq[1]); felem_assign(z_out, nq[2]); } /* Precomputation for the group generator. */ typedef struct { smallfelem g_pre_comp[2][16][3]; int references; } NISTP256_PRE_COMP; const EC_METHOD *EC_GFp_nistp256_method(void) { static const EC_METHOD ret = { EC_FLAGS_DEFAULT_OCT, NID_X9_62_prime_field, ec_GFp_nistp256_group_init, ec_GFp_simple_group_finish, ec_GFp_simple_group_clear_finish, ec_GFp_nist_group_copy, ec_GFp_nistp256_group_set_curve, ec_GFp_simple_group_get_curve, ec_GFp_simple_group_get_degree, ec_GFp_simple_group_check_discriminant, ec_GFp_simple_point_init, ec_GFp_simple_point_finish, ec_GFp_simple_point_clear_finish, ec_GFp_simple_point_copy, ec_GFp_simple_point_set_to_infinity, ec_GFp_simple_set_Jprojective_coordinates_GFp, ec_GFp_simple_get_Jprojective_coordinates_GFp, ec_GFp_simple_point_set_affine_coordinates, ec_GFp_nistp256_point_get_affine_coordinates, 0 /* point_set_compressed_coordinates */ , 0 /* point2oct */ , 0 /* oct2point */ , ec_GFp_simple_add, ec_GFp_simple_dbl, ec_GFp_simple_invert, ec_GFp_simple_is_at_infinity, ec_GFp_simple_is_on_curve, ec_GFp_simple_cmp, ec_GFp_simple_make_affine, ec_GFp_simple_points_make_affine, ec_GFp_nistp256_points_mul, ec_GFp_nistp256_precompute_mult, ec_GFp_nistp256_have_precompute_mult, ec_GFp_nist_field_mul, ec_GFp_nist_field_sqr, 0 /* field_div */ , 0 /* field_encode */ , 0 /* field_decode */ , 0 /* field_set_to_one */ }; return &ret; } /******************************************************************************/ /* * FUNCTIONS TO MANAGE PRECOMPUTATION */ static NISTP256_PRE_COMP *nistp256_pre_comp_new() { NISTP256_PRE_COMP *ret = NULL; ret = (NISTP256_PRE_COMP *) OPENSSL_malloc(sizeof *ret); if (!ret) { ECerr(EC_F_NISTP256_PRE_COMP_NEW, ERR_R_MALLOC_FAILURE); return ret; } memset(ret->g_pre_comp, 0, sizeof(ret->g_pre_comp)); ret->references = 1; return ret; } static void *nistp256_pre_comp_dup(void *src_) { NISTP256_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 nistp256_pre_comp_free(void *pre_) { int i; NISTP256_PRE_COMP *pre = pre_; if (!pre) return; i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP); if (i > 0) return; OPENSSL_free(pre); } static void nistp256_pre_comp_clear_free(void *pre_) { int i; NISTP256_PRE_COMP *pre = pre_; if (!pre) return; i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP); if (i > 0) return; OPENSSL_cleanse(pre, sizeof *pre); OPENSSL_free(pre); } /******************************************************************************/ /* * OPENSSL EC_METHOD FUNCTIONS */ int ec_GFp_nistp256_group_init(EC_GROUP *group) { int ret; ret = ec_GFp_simple_group_init(group); group->a_is_minus3 = 1; return ret; } int ec_GFp_nistp256_group_set_curve(EC_GROUP *group, const BIGNUM *p, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { int ret = 0; BN_CTX *new_ctx = NULL; BIGNUM *curve_p, *curve_a, *curve_b; if (ctx == NULL) if ((ctx = new_ctx = BN_CTX_new()) == NULL) return 0; BN_CTX_start(ctx); if (((curve_p = BN_CTX_get(ctx)) == NULL) || ((curve_a = BN_CTX_get(ctx)) == NULL) || ((curve_b = BN_CTX_get(ctx)) == NULL)) goto err; BN_bin2bn(nistp256_curve_params[0], sizeof(felem_bytearray), curve_p); BN_bin2bn(nistp256_curve_params[1], sizeof(felem_bytearray), curve_a); BN_bin2bn(nistp256_curve_params[2], sizeof(felem_bytearray), curve_b); if ((BN_cmp(curve_p, p)) || (BN_cmp(curve_a, a)) || (BN_cmp(curve_b, b))) { ECerr(EC_F_EC_GFP_NISTP256_GROUP_SET_CURVE, EC_R_WRONG_CURVE_PARAMETERS); goto err; } group->field_mod_func = BN_nist_mod_256; ret = ec_GFp_simple_group_set_curve(group, p, a, b, ctx); err: BN_CTX_end(ctx); if (new_ctx != NULL) BN_CTX_free(new_ctx); return ret; } /* * Takes the Jacobian coordinates (X, Y, Z) of a point and returns (X', Y') = * (X/Z^2, Y/Z^3) */ int ec_GFp_nistp256_point_get_affine_coordinates(const EC_GROUP *group, const EC_POINT *point, BIGNUM *x, BIGNUM *y, BN_CTX *ctx) { felem z1, z2, x_in, y_in; smallfelem x_out, y_out; longfelem tmp; if (EC_POINT_is_at_infinity(group, point)) { ECerr(EC_F_EC_GFP_NISTP256_POINT_GET_AFFINE_COORDINATES, EC_R_POINT_AT_INFINITY); return 0; } if ((!BN_to_felem(x_in, &point->X)) || (!BN_to_felem(y_in, &point->Y)) || (!BN_to_felem(z1, &point->Z))) return 0; felem_inv(z2, z1); felem_square(tmp, z2); felem_reduce(z1, tmp); felem_mul(tmp, x_in, z1); felem_reduce(x_in, tmp); felem_contract(x_out, x_in); if (x != NULL) { if (!smallfelem_to_BN(x, x_out)) { ECerr(EC_F_EC_GFP_NISTP256_POINT_GET_AFFINE_COORDINATES, ERR_R_BN_LIB); return 0; } } felem_mul(tmp, z1, z2); felem_reduce(z1, tmp); felem_mul(tmp, y_in, z1); felem_reduce(y_in, tmp); felem_contract(y_out, y_in); if (y != NULL) { if (!smallfelem_to_BN(y, y_out)) { ECerr(EC_F_EC_GFP_NISTP256_POINT_GET_AFFINE_COORDINATES, ERR_R_BN_LIB); return 0; } } return 1; } /* points below is of size |num|, and tmp_smallfelems is of size |num+1| */ static void make_points_affine(size_t num, smallfelem points[][3], smallfelem tmp_smallfelems[]) { /* * Runs in constant time, unless an input is the point at infinity (which * normally shouldn't happen). */ ec_GFp_nistp_points_make_affine_internal(num, points, sizeof(smallfelem), tmp_smallfelems, (void (*)(void *))smallfelem_one, - (int (*)(const void *)) smallfelem_is_zero_int, (void (*)(void *, const void *)) smallfelem_assign, (void (*)(void *, const void *)) smallfelem_square_contract, (void (*) (void *, const void *, const void *)) smallfelem_mul_contract, (void (*)(void *, const void *)) smallfelem_inv_contract, /* nothing to contract */ (void (*)(void *, const void *)) smallfelem_assign); } /* * Computes scalar*generator + \sum scalars[i]*points[i], ignoring NULL * values Result is stored in r (r can equal one of the inputs). */ int ec_GFp_nistp256_points_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar, size_t num, const EC_POINT *points[], const BIGNUM *scalars[], BN_CTX *ctx) { int ret = 0; int j; int mixed = 0; BN_CTX *new_ctx = NULL; BIGNUM *x, *y, *z, *tmp_scalar; felem_bytearray g_secret; felem_bytearray *secrets = NULL; smallfelem(*pre_comp)[17][3] = NULL; smallfelem *tmp_smallfelems = NULL; felem_bytearray tmp; unsigned i, num_bytes; int have_pre_comp = 0; size_t num_points = num; smallfelem x_in, y_in, z_in; felem x_out, y_out, z_out; NISTP256_PRE_COMP *pre = NULL; const smallfelem(*g_pre_comp)[16][3] = NULL; EC_POINT *generator = NULL; const EC_POINT *p = NULL; const BIGNUM *p_scalar = NULL; if (ctx == NULL) if ((ctx = new_ctx = BN_CTX_new()) == NULL) return 0; BN_CTX_start(ctx); if (((x = BN_CTX_get(ctx)) == NULL) || ((y = BN_CTX_get(ctx)) == NULL) || ((z = BN_CTX_get(ctx)) == NULL) || ((tmp_scalar = BN_CTX_get(ctx)) == NULL)) goto err; if (scalar != NULL) { pre = EC_EX_DATA_get_data(group->extra_data, nistp256_pre_comp_dup, nistp256_pre_comp_free, nistp256_pre_comp_clear_free); if (pre) /* we have precomputation, try to use it */ g_pre_comp = (const smallfelem(*)[16][3])pre->g_pre_comp; else /* try to use the standard precomputation */ g_pre_comp = &gmul[0]; generator = EC_POINT_new(group); if (generator == NULL) goto err; /* get the generator from precomputation */ if (!smallfelem_to_BN(x, g_pre_comp[0][1][0]) || !smallfelem_to_BN(y, g_pre_comp[0][1][1]) || !smallfelem_to_BN(z, g_pre_comp[0][1][2])) { ECerr(EC_F_EC_GFP_NISTP256_POINTS_MUL, ERR_R_BN_LIB); goto err; } if (!EC_POINT_set_Jprojective_coordinates_GFp(group, generator, x, y, z, ctx)) goto err; if (0 == EC_POINT_cmp(group, generator, group->generator, ctx)) /* precomputation matches generator */ have_pre_comp = 1; else /* * we don't have valid precomputation: treat the generator as a * random point */ num_points++; } if (num_points > 0) { if (num_points >= 3) { /* * unless we precompute multiples for just one or two points, * converting those into affine form is time well spent */ mixed = 1; } secrets = OPENSSL_malloc(num_points * sizeof(felem_bytearray)); pre_comp = OPENSSL_malloc(num_points * 17 * 3 * sizeof(smallfelem)); if (mixed) tmp_smallfelems = OPENSSL_malloc((num_points * 17 + 1) * sizeof(smallfelem)); if ((secrets == NULL) || (pre_comp == NULL) || (mixed && (tmp_smallfelems == NULL))) { ECerr(EC_F_EC_GFP_NISTP256_POINTS_MUL, ERR_R_MALLOC_FAILURE); goto err; } /* * we treat NULL scalars as 0, and NULL points as points at infinity, * i.e., they contribute nothing to the linear combination */ memset(secrets, 0, num_points * sizeof(felem_bytearray)); memset(pre_comp, 0, num_points * 17 * 3 * sizeof(smallfelem)); for (i = 0; i < num_points; ++i) { if (i == num) /* * we didn't have a valid precomputation, so we pick the * generator */ { p = EC_GROUP_get0_generator(group); p_scalar = scalar; } else /* the i^th point */ { p = points[i]; p_scalar = scalars[i]; } if ((p_scalar != NULL) && (p != NULL)) { /* reduce scalar to 0 <= scalar < 2^256 */ if ((BN_num_bits(p_scalar) > 256) || (BN_is_negative(p_scalar))) { /* * this is an unusual input, and we don't guarantee * constant-timeness */ if (!BN_nnmod(tmp_scalar, p_scalar, &group->order, ctx)) { ECerr(EC_F_EC_GFP_NISTP256_POINTS_MUL, ERR_R_BN_LIB); goto err; } num_bytes = BN_bn2bin(tmp_scalar, tmp); } else num_bytes = BN_bn2bin(p_scalar, tmp); flip_endian(secrets[i], tmp, num_bytes); /* precompute multiples */ if ((!BN_to_felem(x_out, &p->X)) || (!BN_to_felem(y_out, &p->Y)) || (!BN_to_felem(z_out, &p->Z))) goto err; felem_shrink(pre_comp[i][1][0], x_out); felem_shrink(pre_comp[i][1][1], y_out); felem_shrink(pre_comp[i][1][2], z_out); for (j = 2; j <= 16; ++j) { if (j & 1) { point_add_small(pre_comp[i][j][0], pre_comp[i][j][1], pre_comp[i][j][2], pre_comp[i][1][0], pre_comp[i][1][1], pre_comp[i][1][2], pre_comp[i][j - 1][0], pre_comp[i][j - 1][1], pre_comp[i][j - 1][2]); } else { point_double_small(pre_comp[i][j][0], pre_comp[i][j][1], pre_comp[i][j][2], pre_comp[i][j / 2][0], pre_comp[i][j / 2][1], pre_comp[i][j / 2][2]); } } } } if (mixed) make_points_affine(num_points * 17, pre_comp[0], tmp_smallfelems); } /* the scalar for the generator */ if ((scalar != NULL) && (have_pre_comp)) { memset(g_secret, 0, sizeof(g_secret)); /* reduce scalar to 0 <= scalar < 2^256 */ if ((BN_num_bits(scalar) > 256) || (BN_is_negative(scalar))) { /* * this is an unusual input, and we don't guarantee * constant-timeness */ if (!BN_nnmod(tmp_scalar, scalar, &group->order, ctx)) { ECerr(EC_F_EC_GFP_NISTP256_POINTS_MUL, ERR_R_BN_LIB); goto err; } num_bytes = BN_bn2bin(tmp_scalar, tmp); } else num_bytes = BN_bn2bin(scalar, tmp); flip_endian(g_secret, tmp, num_bytes); /* do the multiplication with generator precomputation */ batch_mul(x_out, y_out, z_out, (const felem_bytearray(*))secrets, num_points, g_secret, mixed, (const smallfelem(*)[17][3])pre_comp, g_pre_comp); } else /* do the multiplication without generator precomputation */ batch_mul(x_out, y_out, z_out, (const felem_bytearray(*))secrets, num_points, NULL, mixed, (const smallfelem(*)[17][3])pre_comp, NULL); /* reduce the output to its unique minimal representation */ felem_contract(x_in, x_out); felem_contract(y_in, y_out); felem_contract(z_in, z_out); if ((!smallfelem_to_BN(x, x_in)) || (!smallfelem_to_BN(y, y_in)) || (!smallfelem_to_BN(z, z_in))) { ECerr(EC_F_EC_GFP_NISTP256_POINTS_MUL, ERR_R_BN_LIB); goto err; } ret = EC_POINT_set_Jprojective_coordinates_GFp(group, r, x, y, z, ctx); err: BN_CTX_end(ctx); if (generator != NULL) EC_POINT_free(generator); if (new_ctx != NULL) BN_CTX_free(new_ctx); if (secrets != NULL) OPENSSL_free(secrets); if (pre_comp != NULL) OPENSSL_free(pre_comp); if (tmp_smallfelems != NULL) OPENSSL_free(tmp_smallfelems); return ret; } int ec_GFp_nistp256_precompute_mult(EC_GROUP *group, BN_CTX *ctx) { int ret = 0; NISTP256_PRE_COMP *pre = NULL; int i, j; BN_CTX *new_ctx = NULL; BIGNUM *x, *y; EC_POINT *generator = NULL; smallfelem tmp_smallfelems[32]; felem x_tmp, y_tmp, z_tmp; /* throw away old precomputation */ EC_EX_DATA_free_data(&group->extra_data, nistp256_pre_comp_dup, nistp256_pre_comp_free, nistp256_pre_comp_clear_free); if (ctx == NULL) if ((ctx = new_ctx = BN_CTX_new()) == NULL) return 0; BN_CTX_start(ctx); if (((x = BN_CTX_get(ctx)) == NULL) || ((y = BN_CTX_get(ctx)) == NULL)) goto err; /* get the generator */ if (group->generator == NULL) goto err; generator = EC_POINT_new(group); if (generator == NULL) goto err; BN_bin2bn(nistp256_curve_params[3], sizeof(felem_bytearray), x); BN_bin2bn(nistp256_curve_params[4], sizeof(felem_bytearray), y); if (!EC_POINT_set_affine_coordinates_GFp(group, generator, x, y, ctx)) goto err; if ((pre = nistp256_pre_comp_new()) == NULL) goto err; /* * if the generator is the standard one, use built-in precomputation */ if (0 == EC_POINT_cmp(group, generator, group->generator, ctx)) { memcpy(pre->g_pre_comp, gmul, sizeof(pre->g_pre_comp)); goto done; } if ((!BN_to_felem(x_tmp, &group->generator->X)) || (!BN_to_felem(y_tmp, &group->generator->Y)) || (!BN_to_felem(z_tmp, &group->generator->Z))) goto err; felem_shrink(pre->g_pre_comp[0][1][0], x_tmp); felem_shrink(pre->g_pre_comp[0][1][1], y_tmp); felem_shrink(pre->g_pre_comp[0][1][2], z_tmp); /* * compute 2^64*G, 2^128*G, 2^192*G for the first table, 2^32*G, 2^96*G, * 2^160*G, 2^224*G for the second one */ for (i = 1; i <= 8; i <<= 1) { point_double_small(pre->g_pre_comp[1][i][0], pre->g_pre_comp[1][i][1], pre->g_pre_comp[1][i][2], pre->g_pre_comp[0][i][0], pre->g_pre_comp[0][i][1], pre->g_pre_comp[0][i][2]); for (j = 0; j < 31; ++j) { point_double_small(pre->g_pre_comp[1][i][0], pre->g_pre_comp[1][i][1], pre->g_pre_comp[1][i][2], pre->g_pre_comp[1][i][0], pre->g_pre_comp[1][i][1], pre->g_pre_comp[1][i][2]); } if (i == 8) break; point_double_small(pre->g_pre_comp[0][2 * i][0], pre->g_pre_comp[0][2 * i][1], pre->g_pre_comp[0][2 * i][2], pre->g_pre_comp[1][i][0], pre->g_pre_comp[1][i][1], pre->g_pre_comp[1][i][2]); for (j = 0; j < 31; ++j) { point_double_small(pre->g_pre_comp[0][2 * i][0], pre->g_pre_comp[0][2 * i][1], pre->g_pre_comp[0][2 * i][2], pre->g_pre_comp[0][2 * i][0], pre->g_pre_comp[0][2 * i][1], pre->g_pre_comp[0][2 * i][2]); } } for (i = 0; i < 2; i++) { /* g_pre_comp[i][0] is the point at infinity */ memset(pre->g_pre_comp[i][0], 0, sizeof(pre->g_pre_comp[i][0])); /* the remaining multiples */ /* 2^64*G + 2^128*G resp. 2^96*G + 2^160*G */ point_add_small(pre->g_pre_comp[i][6][0], pre->g_pre_comp[i][6][1], pre->g_pre_comp[i][6][2], pre->g_pre_comp[i][4][0], pre->g_pre_comp[i][4][1], pre->g_pre_comp[i][4][2], pre->g_pre_comp[i][2][0], pre->g_pre_comp[i][2][1], pre->g_pre_comp[i][2][2]); /* 2^64*G + 2^192*G resp. 2^96*G + 2^224*G */ point_add_small(pre->g_pre_comp[i][10][0], pre->g_pre_comp[i][10][1], pre->g_pre_comp[i][10][2], pre->g_pre_comp[i][8][0], pre->g_pre_comp[i][8][1], pre->g_pre_comp[i][8][2], pre->g_pre_comp[i][2][0], pre->g_pre_comp[i][2][1], pre->g_pre_comp[i][2][2]); /* 2^128*G + 2^192*G resp. 2^160*G + 2^224*G */ point_add_small(pre->g_pre_comp[i][12][0], pre->g_pre_comp[i][12][1], pre->g_pre_comp[i][12][2], pre->g_pre_comp[i][8][0], pre->g_pre_comp[i][8][1], pre->g_pre_comp[i][8][2], pre->g_pre_comp[i][4][0], pre->g_pre_comp[i][4][1], pre->g_pre_comp[i][4][2]); /* * 2^64*G + 2^128*G + 2^192*G resp. 2^96*G + 2^160*G + 2^224*G */ point_add_small(pre->g_pre_comp[i][14][0], pre->g_pre_comp[i][14][1], pre->g_pre_comp[i][14][2], pre->g_pre_comp[i][12][0], pre->g_pre_comp[i][12][1], pre->g_pre_comp[i][12][2], pre->g_pre_comp[i][2][0], pre->g_pre_comp[i][2][1], pre->g_pre_comp[i][2][2]); for (j = 1; j < 8; ++j) { /* odd multiples: add G resp. 2^32*G */ point_add_small(pre->g_pre_comp[i][2 * j + 1][0], pre->g_pre_comp[i][2 * j + 1][1], pre->g_pre_comp[i][2 * j + 1][2], pre->g_pre_comp[i][2 * j][0], pre->g_pre_comp[i][2 * j][1], pre->g_pre_comp[i][2 * j][2], pre->g_pre_comp[i][1][0], pre->g_pre_comp[i][1][1], pre->g_pre_comp[i][1][2]); } } make_points_affine(31, &(pre->g_pre_comp[0][1]), tmp_smallfelems); done: if (!EC_EX_DATA_set_data(&group->extra_data, pre, nistp256_pre_comp_dup, nistp256_pre_comp_free, nistp256_pre_comp_clear_free)) goto err; ret = 1; pre = NULL; err: BN_CTX_end(ctx); if (generator != NULL) EC_POINT_free(generator); if (new_ctx != NULL) BN_CTX_free(new_ctx); if (pre) nistp256_pre_comp_free(pre); return ret; } int ec_GFp_nistp256_have_precompute_mult(const EC_GROUP *group) { if (EC_EX_DATA_get_data(group->extra_data, nistp256_pre_comp_dup, nistp256_pre_comp_free, nistp256_pre_comp_clear_free) != NULL) return 1; else return 0; } #else static void *dummy = &dummy; #endif Index: vendor-crypto/openssl/dist/crypto/ec/ecp_nistp521.c =================================================================== --- vendor-crypto/openssl/dist/crypto/ec/ecp_nistp521.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/ec/ecp_nistp521.c (revision 325326) @@ -1,2148 +1,2147 @@ /* crypto/ec/ecp_nistp521.c */ /* * Written by Adam Langley (Google) for the OpenSSL project */ /* Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * A 64-bit implementation of the NIST P-521 elliptic curve point multiplication * * OpenSSL integration was taken from Emilia Kasper's work in ecp_nistp224.c. * Otherwise based on Emilia's P224 work, which was inspired by my curve25519 * work which got its smarts from Daniel J. Bernstein's work on the same. */ #include #ifndef OPENSSL_NO_EC_NISTP_64_GCC_128 # ifndef OPENSSL_SYS_VMS # include # else # include # endif # include # include # include "ec_lcl.h" # if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) /* even with gcc, the typedef won't work for 32-bit platforms */ typedef __uint128_t uint128_t; /* nonstandard; implemented by gcc on 64-bit * platforms */ # else # error "Need GCC 3.1 or later to define type uint128_t" # endif typedef uint8_t u8; typedef uint64_t u64; typedef int64_t s64; /* * The underlying field. P521 operates over GF(2^521-1). We can serialise an * element of this field into 66 bytes where the most significant byte * contains only a single bit. We call this an felem_bytearray. */ typedef u8 felem_bytearray[66]; /* * These are the parameters of P521, taken from FIPS 186-3, section D.1.2.5. * These values are big-endian. */ static const felem_bytearray nistp521_curve_params[5] = { {0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* p */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* a = -3 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc}, {0x00, 0x51, 0x95, 0x3e, 0xb9, 0x61, 0x8e, 0x1c, /* b */ 0x9a, 0x1f, 0x92, 0x9a, 0x21, 0xa0, 0xb6, 0x85, 0x40, 0xee, 0xa2, 0xda, 0x72, 0x5b, 0x99, 0xb3, 0x15, 0xf3, 0xb8, 0xb4, 0x89, 0x91, 0x8e, 0xf1, 0x09, 0xe1, 0x56, 0x19, 0x39, 0x51, 0xec, 0x7e, 0x93, 0x7b, 0x16, 0x52, 0xc0, 0xbd, 0x3b, 0xb1, 0xbf, 0x07, 0x35, 0x73, 0xdf, 0x88, 0x3d, 0x2c, 0x34, 0xf1, 0xef, 0x45, 0x1f, 0xd4, 0x6b, 0x50, 0x3f, 0x00}, {0x00, 0xc6, 0x85, 0x8e, 0x06, 0xb7, 0x04, 0x04, /* x */ 0xe9, 0xcd, 0x9e, 0x3e, 0xcb, 0x66, 0x23, 0x95, 0xb4, 0x42, 0x9c, 0x64, 0x81, 0x39, 0x05, 0x3f, 0xb5, 0x21, 0xf8, 0x28, 0xaf, 0x60, 0x6b, 0x4d, 0x3d, 0xba, 0xa1, 0x4b, 0x5e, 0x77, 0xef, 0xe7, 0x59, 0x28, 0xfe, 0x1d, 0xc1, 0x27, 0xa2, 0xff, 0xa8, 0xde, 0x33, 0x48, 0xb3, 0xc1, 0x85, 0x6a, 0x42, 0x9b, 0xf9, 0x7e, 0x7e, 0x31, 0xc2, 0xe5, 0xbd, 0x66}, {0x01, 0x18, 0x39, 0x29, 0x6a, 0x78, 0x9a, 0x3b, /* y */ 0xc0, 0x04, 0x5c, 0x8a, 0x5f, 0xb4, 0x2c, 0x7d, 0x1b, 0xd9, 0x98, 0xf5, 0x44, 0x49, 0x57, 0x9b, 0x44, 0x68, 0x17, 0xaf, 0xbd, 0x17, 0x27, 0x3e, 0x66, 0x2c, 0x97, 0xee, 0x72, 0x99, 0x5e, 0xf4, 0x26, 0x40, 0xc5, 0x50, 0xb9, 0x01, 0x3f, 0xad, 0x07, 0x61, 0x35, 0x3c, 0x70, 0x86, 0xa2, 0x72, 0xc2, 0x40, 0x88, 0xbe, 0x94, 0x76, 0x9f, 0xd1, 0x66, 0x50} }; /*- * The representation of field elements. * ------------------------------------ * * We represent field elements with nine values. These values are either 64 or * 128 bits and the field element represented is: * v[0]*2^0 + v[1]*2^58 + v[2]*2^116 + ... + v[8]*2^464 (mod p) * Each of the nine values is called a 'limb'. Since the limbs are spaced only * 58 bits apart, but are greater than 58 bits in length, the most significant * bits of each limb overlap with the least significant bits of the next. * * A field element with 64-bit limbs is an 'felem'. One with 128-bit limbs is a * 'largefelem' */ # define NLIMBS 9 typedef uint64_t limb; typedef limb felem[NLIMBS]; typedef uint128_t largefelem[NLIMBS]; static const limb bottom57bits = 0x1ffffffffffffff; static const limb bottom58bits = 0x3ffffffffffffff; /* * bin66_to_felem takes a little-endian byte array and converts it into felem * form. This assumes that the CPU is little-endian. */ static void bin66_to_felem(felem out, const u8 in[66]) { out[0] = (*((limb *) & in[0])) & bottom58bits; out[1] = (*((limb *) & in[7]) >> 2) & bottom58bits; out[2] = (*((limb *) & in[14]) >> 4) & bottom58bits; out[3] = (*((limb *) & in[21]) >> 6) & bottom58bits; out[4] = (*((limb *) & in[29])) & bottom58bits; out[5] = (*((limb *) & in[36]) >> 2) & bottom58bits; out[6] = (*((limb *) & in[43]) >> 4) & bottom58bits; out[7] = (*((limb *) & in[50]) >> 6) & bottom58bits; out[8] = (*((limb *) & in[58])) & bottom57bits; } /* * felem_to_bin66 takes an felem and serialises into a little endian, 66 byte * array. This assumes that the CPU is little-endian. */ static void felem_to_bin66(u8 out[66], const felem in) { memset(out, 0, 66); (*((limb *) & out[0])) = in[0]; (*((limb *) & out[7])) |= in[1] << 2; (*((limb *) & out[14])) |= in[2] << 4; (*((limb *) & out[21])) |= in[3] << 6; (*((limb *) & out[29])) = in[4]; (*((limb *) & out[36])) |= in[5] << 2; (*((limb *) & out[43])) |= in[6] << 4; (*((limb *) & out[50])) |= in[7] << 6; (*((limb *) & out[58])) = in[8]; } /* To preserve endianness when using BN_bn2bin and BN_bin2bn */ static void flip_endian(u8 *out, const u8 *in, unsigned len) { unsigned i; for (i = 0; i < len; ++i) out[i] = in[len - 1 - i]; } /* BN_to_felem converts an OpenSSL BIGNUM into an felem */ static int BN_to_felem(felem out, const BIGNUM *bn) { felem_bytearray b_in; felem_bytearray b_out; unsigned num_bytes; /* BN_bn2bin eats leading zeroes */ memset(b_out, 0, sizeof b_out); num_bytes = BN_num_bytes(bn); if (num_bytes > sizeof b_out) { ECerr(EC_F_BN_TO_FELEM, EC_R_BIGNUM_OUT_OF_RANGE); return 0; } if (BN_is_negative(bn)) { ECerr(EC_F_BN_TO_FELEM, EC_R_BIGNUM_OUT_OF_RANGE); return 0; } num_bytes = BN_bn2bin(bn, b_in); flip_endian(b_out, b_in, num_bytes); bin66_to_felem(out, b_out); return 1; } /* felem_to_BN converts an felem into an OpenSSL BIGNUM */ static BIGNUM *felem_to_BN(BIGNUM *out, const felem in) { felem_bytearray b_in, b_out; felem_to_bin66(b_in, in); flip_endian(b_out, b_in, sizeof b_out); return BN_bin2bn(b_out, sizeof b_out, out); } /*- * Field operations * ---------------- */ static void felem_one(felem out) { out[0] = 1; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 0; out[5] = 0; out[6] = 0; out[7] = 0; out[8] = 0; } static void felem_assign(felem out, const felem in) { out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; out[3] = in[3]; out[4] = in[4]; out[5] = in[5]; out[6] = in[6]; out[7] = in[7]; out[8] = in[8]; } /* felem_sum64 sets out = out + in. */ static void felem_sum64(felem out, const felem in) { out[0] += in[0]; out[1] += in[1]; out[2] += in[2]; out[3] += in[3]; out[4] += in[4]; out[5] += in[5]; out[6] += in[6]; out[7] += in[7]; out[8] += in[8]; } /* felem_scalar sets out = in * scalar */ static void felem_scalar(felem out, const felem in, limb scalar) { out[0] = in[0] * scalar; out[1] = in[1] * scalar; out[2] = in[2] * scalar; out[3] = in[3] * scalar; out[4] = in[4] * scalar; out[5] = in[5] * scalar; out[6] = in[6] * scalar; out[7] = in[7] * scalar; out[8] = in[8] * scalar; } /* felem_scalar64 sets out = out * scalar */ static void felem_scalar64(felem out, limb scalar) { out[0] *= scalar; out[1] *= scalar; out[2] *= scalar; out[3] *= scalar; out[4] *= scalar; out[5] *= scalar; out[6] *= scalar; out[7] *= scalar; out[8] *= scalar; } /* felem_scalar128 sets out = out * scalar */ static void felem_scalar128(largefelem out, limb scalar) { out[0] *= scalar; out[1] *= scalar; out[2] *= scalar; out[3] *= scalar; out[4] *= scalar; out[5] *= scalar; out[6] *= scalar; out[7] *= scalar; out[8] *= scalar; } /*- * felem_neg sets |out| to |-in| * On entry: * in[i] < 2^59 + 2^14 * On exit: * out[i] < 2^62 */ static void felem_neg(felem out, const felem in) { /* In order to prevent underflow, we subtract from 0 mod p. */ static const limb two62m3 = (((limb) 1) << 62) - (((limb) 1) << 5); static const limb two62m2 = (((limb) 1) << 62) - (((limb) 1) << 4); out[0] = two62m3 - in[0]; out[1] = two62m2 - in[1]; out[2] = two62m2 - in[2]; out[3] = two62m2 - in[3]; out[4] = two62m2 - in[4]; out[5] = two62m2 - in[5]; out[6] = two62m2 - in[6]; out[7] = two62m2 - in[7]; out[8] = two62m2 - in[8]; } /*- * felem_diff64 subtracts |in| from |out| * On entry: * in[i] < 2^59 + 2^14 * On exit: * out[i] < out[i] + 2^62 */ static void felem_diff64(felem out, const felem in) { /* * In order to prevent underflow, we add 0 mod p before subtracting. */ static const limb two62m3 = (((limb) 1) << 62) - (((limb) 1) << 5); static const limb two62m2 = (((limb) 1) << 62) - (((limb) 1) << 4); out[0] += two62m3 - in[0]; out[1] += two62m2 - in[1]; out[2] += two62m2 - in[2]; out[3] += two62m2 - in[3]; out[4] += two62m2 - in[4]; out[5] += two62m2 - in[5]; out[6] += two62m2 - in[6]; out[7] += two62m2 - in[7]; out[8] += two62m2 - in[8]; } /*- * felem_diff_128_64 subtracts |in| from |out| * On entry: * in[i] < 2^62 + 2^17 * On exit: * out[i] < out[i] + 2^63 */ static void felem_diff_128_64(largefelem out, const felem in) { /* * In order to prevent underflow, we add 0 mod p before subtracting. */ static const limb two63m6 = (((limb) 1) << 62) - (((limb) 1) << 5); static const limb two63m5 = (((limb) 1) << 62) - (((limb) 1) << 4); out[0] += two63m6 - in[0]; out[1] += two63m5 - in[1]; out[2] += two63m5 - in[2]; out[3] += two63m5 - in[3]; out[4] += two63m5 - in[4]; out[5] += two63m5 - in[5]; out[6] += two63m5 - in[6]; out[7] += two63m5 - in[7]; out[8] += two63m5 - in[8]; } /*- * felem_diff_128_64 subtracts |in| from |out| * On entry: * in[i] < 2^126 * On exit: * out[i] < out[i] + 2^127 - 2^69 */ static void felem_diff128(largefelem out, const largefelem in) { /* * In order to prevent underflow, we add 0 mod p before subtracting. */ static const uint128_t two127m70 = (((uint128_t) 1) << 127) - (((uint128_t) 1) << 70); static const uint128_t two127m69 = (((uint128_t) 1) << 127) - (((uint128_t) 1) << 69); out[0] += (two127m70 - in[0]); out[1] += (two127m69 - in[1]); out[2] += (two127m69 - in[2]); out[3] += (two127m69 - in[3]); out[4] += (two127m69 - in[4]); out[5] += (two127m69 - in[5]); out[6] += (two127m69 - in[6]); out[7] += (two127m69 - in[7]); out[8] += (two127m69 - in[8]); } /*- * felem_square sets |out| = |in|^2 * On entry: * in[i] < 2^62 * On exit: * out[i] < 17 * max(in[i]) * max(in[i]) */ static void felem_square(largefelem out, const felem in) { felem inx2, inx4; felem_scalar(inx2, in, 2); felem_scalar(inx4, in, 4); /*- * We have many cases were we want to do * in[x] * in[y] + * in[y] * in[x] * This is obviously just * 2 * in[x] * in[y] * However, rather than do the doubling on the 128 bit result, we * double one of the inputs to the multiplication by reading from * |inx2| */ out[0] = ((uint128_t) in[0]) * in[0]; out[1] = ((uint128_t) in[0]) * inx2[1]; out[2] = ((uint128_t) in[0]) * inx2[2] + ((uint128_t) in[1]) * in[1]; out[3] = ((uint128_t) in[0]) * inx2[3] + ((uint128_t) in[1]) * inx2[2]; out[4] = ((uint128_t) in[0]) * inx2[4] + ((uint128_t) in[1]) * inx2[3] + ((uint128_t) in[2]) * in[2]; out[5] = ((uint128_t) in[0]) * inx2[5] + ((uint128_t) in[1]) * inx2[4] + ((uint128_t) in[2]) * inx2[3]; out[6] = ((uint128_t) in[0]) * inx2[6] + ((uint128_t) in[1]) * inx2[5] + ((uint128_t) in[2]) * inx2[4] + ((uint128_t) in[3]) * in[3]; out[7] = ((uint128_t) in[0]) * inx2[7] + ((uint128_t) in[1]) * inx2[6] + ((uint128_t) in[2]) * inx2[5] + ((uint128_t) in[3]) * inx2[4]; out[8] = ((uint128_t) in[0]) * inx2[8] + ((uint128_t) in[1]) * inx2[7] + ((uint128_t) in[2]) * inx2[6] + ((uint128_t) in[3]) * inx2[5] + ((uint128_t) in[4]) * in[4]; /* * The remaining limbs fall above 2^521, with the first falling at 2^522. * They correspond to locations one bit up from the limbs produced above * so we would have to multiply by two to align them. Again, rather than * operate on the 128-bit result, we double one of the inputs to the * multiplication. If we want to double for both this reason, and the * reason above, then we end up multiplying by four. */ /* 9 */ out[0] += ((uint128_t) in[1]) * inx4[8] + ((uint128_t) in[2]) * inx4[7] + ((uint128_t) in[3]) * inx4[6] + ((uint128_t) in[4]) * inx4[5]; /* 10 */ out[1] += ((uint128_t) in[2]) * inx4[8] + ((uint128_t) in[3]) * inx4[7] + ((uint128_t) in[4]) * inx4[6] + ((uint128_t) in[5]) * inx2[5]; /* 11 */ out[2] += ((uint128_t) in[3]) * inx4[8] + ((uint128_t) in[4]) * inx4[7] + ((uint128_t) in[5]) * inx4[6]; /* 12 */ out[3] += ((uint128_t) in[4]) * inx4[8] + ((uint128_t) in[5]) * inx4[7] + ((uint128_t) in[6]) * inx2[6]; /* 13 */ out[4] += ((uint128_t) in[5]) * inx4[8] + ((uint128_t) in[6]) * inx4[7]; /* 14 */ out[5] += ((uint128_t) in[6]) * inx4[8] + ((uint128_t) in[7]) * inx2[7]; /* 15 */ out[6] += ((uint128_t) in[7]) * inx4[8]; /* 16 */ out[7] += ((uint128_t) in[8]) * inx2[8]; } /*- * felem_mul sets |out| = |in1| * |in2| * On entry: * in1[i] < 2^64 * in2[i] < 2^63 * On exit: * out[i] < 17 * max(in1[i]) * max(in2[i]) */ static void felem_mul(largefelem out, const felem in1, const felem in2) { felem in2x2; felem_scalar(in2x2, in2, 2); out[0] = ((uint128_t) in1[0]) * in2[0]; out[1] = ((uint128_t) in1[0]) * in2[1] + ((uint128_t) in1[1]) * in2[0]; out[2] = ((uint128_t) in1[0]) * in2[2] + ((uint128_t) in1[1]) * in2[1] + ((uint128_t) in1[2]) * in2[0]; out[3] = ((uint128_t) in1[0]) * in2[3] + ((uint128_t) in1[1]) * in2[2] + ((uint128_t) in1[2]) * in2[1] + ((uint128_t) in1[3]) * in2[0]; out[4] = ((uint128_t) in1[0]) * in2[4] + ((uint128_t) in1[1]) * in2[3] + ((uint128_t) in1[2]) * in2[2] + ((uint128_t) in1[3]) * in2[1] + ((uint128_t) in1[4]) * in2[0]; out[5] = ((uint128_t) in1[0]) * in2[5] + ((uint128_t) in1[1]) * in2[4] + ((uint128_t) in1[2]) * in2[3] + ((uint128_t) in1[3]) * in2[2] + ((uint128_t) in1[4]) * in2[1] + ((uint128_t) in1[5]) * in2[0]; out[6] = ((uint128_t) in1[0]) * in2[6] + ((uint128_t) in1[1]) * in2[5] + ((uint128_t) in1[2]) * in2[4] + ((uint128_t) in1[3]) * in2[3] + ((uint128_t) in1[4]) * in2[2] + ((uint128_t) in1[5]) * in2[1] + ((uint128_t) in1[6]) * in2[0]; out[7] = ((uint128_t) in1[0]) * in2[7] + ((uint128_t) in1[1]) * in2[6] + ((uint128_t) in1[2]) * in2[5] + ((uint128_t) in1[3]) * in2[4] + ((uint128_t) in1[4]) * in2[3] + ((uint128_t) in1[5]) * in2[2] + ((uint128_t) in1[6]) * in2[1] + ((uint128_t) in1[7]) * in2[0]; out[8] = ((uint128_t) in1[0]) * in2[8] + ((uint128_t) in1[1]) * in2[7] + ((uint128_t) in1[2]) * in2[6] + ((uint128_t) in1[3]) * in2[5] + ((uint128_t) in1[4]) * in2[4] + ((uint128_t) in1[5]) * in2[3] + ((uint128_t) in1[6]) * in2[2] + ((uint128_t) in1[7]) * in2[1] + ((uint128_t) in1[8]) * in2[0]; /* See comment in felem_square about the use of in2x2 here */ out[0] += ((uint128_t) in1[1]) * in2x2[8] + ((uint128_t) in1[2]) * in2x2[7] + ((uint128_t) in1[3]) * in2x2[6] + ((uint128_t) in1[4]) * in2x2[5] + ((uint128_t) in1[5]) * in2x2[4] + ((uint128_t) in1[6]) * in2x2[3] + ((uint128_t) in1[7]) * in2x2[2] + ((uint128_t) in1[8]) * in2x2[1]; out[1] += ((uint128_t) in1[2]) * in2x2[8] + ((uint128_t) in1[3]) * in2x2[7] + ((uint128_t) in1[4]) * in2x2[6] + ((uint128_t) in1[5]) * in2x2[5] + ((uint128_t) in1[6]) * in2x2[4] + ((uint128_t) in1[7]) * in2x2[3] + ((uint128_t) in1[8]) * in2x2[2]; out[2] += ((uint128_t) in1[3]) * in2x2[8] + ((uint128_t) in1[4]) * in2x2[7] + ((uint128_t) in1[5]) * in2x2[6] + ((uint128_t) in1[6]) * in2x2[5] + ((uint128_t) in1[7]) * in2x2[4] + ((uint128_t) in1[8]) * in2x2[3]; out[3] += ((uint128_t) in1[4]) * in2x2[8] + ((uint128_t) in1[5]) * in2x2[7] + ((uint128_t) in1[6]) * in2x2[6] + ((uint128_t) in1[7]) * in2x2[5] + ((uint128_t) in1[8]) * in2x2[4]; out[4] += ((uint128_t) in1[5]) * in2x2[8] + ((uint128_t) in1[6]) * in2x2[7] + ((uint128_t) in1[7]) * in2x2[6] + ((uint128_t) in1[8]) * in2x2[5]; out[5] += ((uint128_t) in1[6]) * in2x2[8] + ((uint128_t) in1[7]) * in2x2[7] + ((uint128_t) in1[8]) * in2x2[6]; out[6] += ((uint128_t) in1[7]) * in2x2[8] + ((uint128_t) in1[8]) * in2x2[7]; out[7] += ((uint128_t) in1[8]) * in2x2[8]; } static const limb bottom52bits = 0xfffffffffffff; /*- * felem_reduce converts a largefelem to an felem. * On entry: * in[i] < 2^128 * On exit: * out[i] < 2^59 + 2^14 */ static void felem_reduce(felem out, const largefelem in) { u64 overflow1, overflow2; out[0] = ((limb) in[0]) & bottom58bits; out[1] = ((limb) in[1]) & bottom58bits; out[2] = ((limb) in[2]) & bottom58bits; out[3] = ((limb) in[3]) & bottom58bits; out[4] = ((limb) in[4]) & bottom58bits; out[5] = ((limb) in[5]) & bottom58bits; out[6] = ((limb) in[6]) & bottom58bits; out[7] = ((limb) in[7]) & bottom58bits; out[8] = ((limb) in[8]) & bottom58bits; /* out[i] < 2^58 */ out[1] += ((limb) in[0]) >> 58; out[1] += (((limb) (in[0] >> 64)) & bottom52bits) << 6; /*- * out[1] < 2^58 + 2^6 + 2^58 * = 2^59 + 2^6 */ out[2] += ((limb) (in[0] >> 64)) >> 52; out[2] += ((limb) in[1]) >> 58; out[2] += (((limb) (in[1] >> 64)) & bottom52bits) << 6; out[3] += ((limb) (in[1] >> 64)) >> 52; out[3] += ((limb) in[2]) >> 58; out[3] += (((limb) (in[2] >> 64)) & bottom52bits) << 6; out[4] += ((limb) (in[2] >> 64)) >> 52; out[4] += ((limb) in[3]) >> 58; out[4] += (((limb) (in[3] >> 64)) & bottom52bits) << 6; out[5] += ((limb) (in[3] >> 64)) >> 52; out[5] += ((limb) in[4]) >> 58; out[5] += (((limb) (in[4] >> 64)) & bottom52bits) << 6; out[6] += ((limb) (in[4] >> 64)) >> 52; out[6] += ((limb) in[5]) >> 58; out[6] += (((limb) (in[5] >> 64)) & bottom52bits) << 6; out[7] += ((limb) (in[5] >> 64)) >> 52; out[7] += ((limb) in[6]) >> 58; out[7] += (((limb) (in[6] >> 64)) & bottom52bits) << 6; out[8] += ((limb) (in[6] >> 64)) >> 52; out[8] += ((limb) in[7]) >> 58; out[8] += (((limb) (in[7] >> 64)) & bottom52bits) << 6; /*- * out[x > 1] < 2^58 + 2^6 + 2^58 + 2^12 * < 2^59 + 2^13 */ overflow1 = ((limb) (in[7] >> 64)) >> 52; overflow1 += ((limb) in[8]) >> 58; overflow1 += (((limb) (in[8] >> 64)) & bottom52bits) << 6; overflow2 = ((limb) (in[8] >> 64)) >> 52; overflow1 <<= 1; /* overflow1 < 2^13 + 2^7 + 2^59 */ overflow2 <<= 1; /* overflow2 < 2^13 */ out[0] += overflow1; /* out[0] < 2^60 */ out[1] += overflow2; /* out[1] < 2^59 + 2^6 + 2^13 */ out[1] += out[0] >> 58; out[0] &= bottom58bits; /*- * out[0] < 2^58 * out[1] < 2^59 + 2^6 + 2^13 + 2^2 * < 2^59 + 2^14 */ } static void felem_square_reduce(felem out, const felem in) { largefelem tmp; felem_square(tmp, in); felem_reduce(out, tmp); } static void felem_mul_reduce(felem out, const felem in1, const felem in2) { largefelem tmp; felem_mul(tmp, in1, in2); felem_reduce(out, tmp); } /*- * felem_inv calculates |out| = |in|^{-1} * * Based on Fermat's Little Theorem: * a^p = a (mod p) * a^{p-1} = 1 (mod p) * a^{p-2} = a^{-1} (mod p) */ static void felem_inv(felem out, const felem in) { felem ftmp, ftmp2, ftmp3, ftmp4; largefelem tmp; unsigned i; felem_square(tmp, in); felem_reduce(ftmp, tmp); /* 2^1 */ felem_mul(tmp, in, ftmp); felem_reduce(ftmp, tmp); /* 2^2 - 2^0 */ felem_assign(ftmp2, ftmp); felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); /* 2^3 - 2^1 */ felem_mul(tmp, in, ftmp); felem_reduce(ftmp, tmp); /* 2^3 - 2^0 */ felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); /* 2^4 - 2^1 */ felem_square(tmp, ftmp2); felem_reduce(ftmp3, tmp); /* 2^3 - 2^1 */ felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^4 - 2^2 */ felem_mul(tmp, ftmp3, ftmp2); felem_reduce(ftmp3, tmp); /* 2^4 - 2^0 */ felem_assign(ftmp2, ftmp3); felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^5 - 2^1 */ felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^6 - 2^2 */ felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^7 - 2^3 */ felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^8 - 2^4 */ felem_assign(ftmp4, ftmp3); felem_mul(tmp, ftmp3, ftmp); felem_reduce(ftmp4, tmp); /* 2^8 - 2^1 */ felem_square(tmp, ftmp4); felem_reduce(ftmp4, tmp); /* 2^9 - 2^2 */ felem_mul(tmp, ftmp3, ftmp2); felem_reduce(ftmp3, tmp); /* 2^8 - 2^0 */ felem_assign(ftmp2, ftmp3); for (i = 0; i < 8; i++) { felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^16 - 2^8 */ } felem_mul(tmp, ftmp3, ftmp2); felem_reduce(ftmp3, tmp); /* 2^16 - 2^0 */ felem_assign(ftmp2, ftmp3); for (i = 0; i < 16; i++) { felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^32 - 2^16 */ } felem_mul(tmp, ftmp3, ftmp2); felem_reduce(ftmp3, tmp); /* 2^32 - 2^0 */ felem_assign(ftmp2, ftmp3); for (i = 0; i < 32; i++) { felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^64 - 2^32 */ } felem_mul(tmp, ftmp3, ftmp2); felem_reduce(ftmp3, tmp); /* 2^64 - 2^0 */ felem_assign(ftmp2, ftmp3); for (i = 0; i < 64; i++) { felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^128 - 2^64 */ } felem_mul(tmp, ftmp3, ftmp2); felem_reduce(ftmp3, tmp); /* 2^128 - 2^0 */ felem_assign(ftmp2, ftmp3); for (i = 0; i < 128; i++) { felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^256 - 2^128 */ } felem_mul(tmp, ftmp3, ftmp2); felem_reduce(ftmp3, tmp); /* 2^256 - 2^0 */ felem_assign(ftmp2, ftmp3); for (i = 0; i < 256; i++) { felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^512 - 2^256 */ } felem_mul(tmp, ftmp3, ftmp2); felem_reduce(ftmp3, tmp); /* 2^512 - 2^0 */ for (i = 0; i < 9; i++) { felem_square(tmp, ftmp3); felem_reduce(ftmp3, tmp); /* 2^521 - 2^9 */ } felem_mul(tmp, ftmp3, ftmp4); felem_reduce(ftmp3, tmp); /* 2^512 - 2^2 */ felem_mul(tmp, ftmp3, in); felem_reduce(out, tmp); /* 2^512 - 3 */ } /* This is 2^521-1, expressed as an felem */ static const felem kPrime = { 0x03ffffffffffffff, 0x03ffffffffffffff, 0x03ffffffffffffff, 0x03ffffffffffffff, 0x03ffffffffffffff, 0x03ffffffffffffff, 0x03ffffffffffffff, 0x03ffffffffffffff, 0x01ffffffffffffff }; /*- * felem_is_zero returns a limb with all bits set if |in| == 0 (mod p) and 0 * otherwise. * On entry: * in[i] < 2^59 + 2^14 */ static limb felem_is_zero(const felem in) { felem ftmp; limb is_zero, is_p; felem_assign(ftmp, in); ftmp[0] += ftmp[8] >> 57; ftmp[8] &= bottom57bits; /* ftmp[8] < 2^57 */ ftmp[1] += ftmp[0] >> 58; ftmp[0] &= bottom58bits; ftmp[2] += ftmp[1] >> 58; ftmp[1] &= bottom58bits; ftmp[3] += ftmp[2] >> 58; ftmp[2] &= bottom58bits; ftmp[4] += ftmp[3] >> 58; ftmp[3] &= bottom58bits; ftmp[5] += ftmp[4] >> 58; ftmp[4] &= bottom58bits; ftmp[6] += ftmp[5] >> 58; ftmp[5] &= bottom58bits; ftmp[7] += ftmp[6] >> 58; ftmp[6] &= bottom58bits; ftmp[8] += ftmp[7] >> 58; ftmp[7] &= bottom58bits; /* ftmp[8] < 2^57 + 4 */ /* * The ninth limb of 2*(2^521-1) is 0x03ffffffffffffff, which is greater * than our bound for ftmp[8]. Therefore we only have to check if the * zero is zero or 2^521-1. */ is_zero = 0; is_zero |= ftmp[0]; is_zero |= ftmp[1]; is_zero |= ftmp[2]; is_zero |= ftmp[3]; is_zero |= ftmp[4]; is_zero |= ftmp[5]; is_zero |= ftmp[6]; is_zero |= ftmp[7]; is_zero |= ftmp[8]; is_zero--; /* * We know that ftmp[i] < 2^63, therefore the only way that the top bit * can be set is if is_zero was 0 before the decrement. */ is_zero = ((s64) is_zero) >> 63; is_p = ftmp[0] ^ kPrime[0]; is_p |= ftmp[1] ^ kPrime[1]; is_p |= ftmp[2] ^ kPrime[2]; is_p |= ftmp[3] ^ kPrime[3]; is_p |= ftmp[4] ^ kPrime[4]; is_p |= ftmp[5] ^ kPrime[5]; is_p |= ftmp[6] ^ kPrime[6]; is_p |= ftmp[7] ^ kPrime[7]; is_p |= ftmp[8] ^ kPrime[8]; is_p--; is_p = ((s64) is_p) >> 63; is_zero |= is_p; return is_zero; } -static int felem_is_zero_int(const felem in) +static int felem_is_zero_int(const void *in) { return (int)(felem_is_zero(in) & ((limb) 1)); } /*- * felem_contract converts |in| to its unique, minimal representation. * On entry: * in[i] < 2^59 + 2^14 */ static void felem_contract(felem out, const felem in) { limb is_p, is_greater, sign; static const limb two58 = ((limb) 1) << 58; felem_assign(out, in); out[0] += out[8] >> 57; out[8] &= bottom57bits; /* out[8] < 2^57 */ out[1] += out[0] >> 58; out[0] &= bottom58bits; out[2] += out[1] >> 58; out[1] &= bottom58bits; out[3] += out[2] >> 58; out[2] &= bottom58bits; out[4] += out[3] >> 58; out[3] &= bottom58bits; out[5] += out[4] >> 58; out[4] &= bottom58bits; out[6] += out[5] >> 58; out[5] &= bottom58bits; out[7] += out[6] >> 58; out[6] &= bottom58bits; out[8] += out[7] >> 58; out[7] &= bottom58bits; /* out[8] < 2^57 + 4 */ /* * If the value is greater than 2^521-1 then we have to subtract 2^521-1 * out. See the comments in felem_is_zero regarding why we don't test for * other multiples of the prime. */ /* * First, if |out| is equal to 2^521-1, we subtract it out to get zero. */ is_p = out[0] ^ kPrime[0]; is_p |= out[1] ^ kPrime[1]; is_p |= out[2] ^ kPrime[2]; is_p |= out[3] ^ kPrime[3]; is_p |= out[4] ^ kPrime[4]; is_p |= out[5] ^ kPrime[5]; is_p |= out[6] ^ kPrime[6]; is_p |= out[7] ^ kPrime[7]; is_p |= out[8] ^ kPrime[8]; is_p--; is_p &= is_p << 32; is_p &= is_p << 16; is_p &= is_p << 8; is_p &= is_p << 4; is_p &= is_p << 2; is_p &= is_p << 1; is_p = ((s64) is_p) >> 63; is_p = ~is_p; /* is_p is 0 iff |out| == 2^521-1 and all ones otherwise */ out[0] &= is_p; out[1] &= is_p; out[2] &= is_p; out[3] &= is_p; out[4] &= is_p; out[5] &= is_p; out[6] &= is_p; out[7] &= is_p; out[8] &= is_p; /* * In order to test that |out| >= 2^521-1 we need only test if out[8] >> * 57 is greater than zero as (2^521-1) + x >= 2^522 */ is_greater = out[8] >> 57; is_greater |= is_greater << 32; is_greater |= is_greater << 16; is_greater |= is_greater << 8; is_greater |= is_greater << 4; is_greater |= is_greater << 2; is_greater |= is_greater << 1; is_greater = ((s64) is_greater) >> 63; out[0] -= kPrime[0] & is_greater; out[1] -= kPrime[1] & is_greater; out[2] -= kPrime[2] & is_greater; out[3] -= kPrime[3] & is_greater; out[4] -= kPrime[4] & is_greater; out[5] -= kPrime[5] & is_greater; out[6] -= kPrime[6] & is_greater; out[7] -= kPrime[7] & is_greater; out[8] -= kPrime[8] & is_greater; /* Eliminate negative coefficients */ sign = -(out[0] >> 63); out[0] += (two58 & sign); out[1] -= (1 & sign); sign = -(out[1] >> 63); out[1] += (two58 & sign); out[2] -= (1 & sign); sign = -(out[2] >> 63); out[2] += (two58 & sign); out[3] -= (1 & sign); sign = -(out[3] >> 63); out[3] += (two58 & sign); out[4] -= (1 & sign); sign = -(out[4] >> 63); out[4] += (two58 & sign); out[5] -= (1 & sign); sign = -(out[0] >> 63); out[5] += (two58 & sign); out[6] -= (1 & sign); sign = -(out[6] >> 63); out[6] += (two58 & sign); out[7] -= (1 & sign); sign = -(out[7] >> 63); out[7] += (two58 & sign); out[8] -= (1 & sign); sign = -(out[5] >> 63); out[5] += (two58 & sign); out[6] -= (1 & sign); sign = -(out[6] >> 63); out[6] += (two58 & sign); out[7] -= (1 & sign); sign = -(out[7] >> 63); out[7] += (two58 & sign); out[8] -= (1 & sign); } /*- * Group operations * ---------------- * * Building on top of the field operations we have the operations on the * elliptic curve group itself. Points on the curve are represented in Jacobian * coordinates */ /*- * point_double calcuates 2*(x_in, y_in, z_in) * * The method is taken from: * http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b * * Outputs can equal corresponding inputs, i.e., x_out == x_in is allowed. * while x_out == y_in is not (maybe this works, but it's not tested). */ static void point_double(felem x_out, felem y_out, felem z_out, const felem x_in, const felem y_in, const felem z_in) { largefelem tmp, tmp2; felem delta, gamma, beta, alpha, ftmp, ftmp2; felem_assign(ftmp, x_in); felem_assign(ftmp2, x_in); /* delta = z^2 */ felem_square(tmp, z_in); felem_reduce(delta, tmp); /* delta[i] < 2^59 + 2^14 */ /* gamma = y^2 */ felem_square(tmp, y_in); felem_reduce(gamma, tmp); /* gamma[i] < 2^59 + 2^14 */ /* beta = x*gamma */ felem_mul(tmp, x_in, gamma); felem_reduce(beta, tmp); /* beta[i] < 2^59 + 2^14 */ /* alpha = 3*(x-delta)*(x+delta) */ felem_diff64(ftmp, delta); /* ftmp[i] < 2^61 */ felem_sum64(ftmp2, delta); /* ftmp2[i] < 2^60 + 2^15 */ felem_scalar64(ftmp2, 3); /* ftmp2[i] < 3*2^60 + 3*2^15 */ felem_mul(tmp, ftmp, ftmp2); /*- * tmp[i] < 17(3*2^121 + 3*2^76) * = 61*2^121 + 61*2^76 * < 64*2^121 + 64*2^76 * = 2^127 + 2^82 * < 2^128 */ felem_reduce(alpha, tmp); /* x' = alpha^2 - 8*beta */ felem_square(tmp, alpha); /* * tmp[i] < 17*2^120 < 2^125 */ felem_assign(ftmp, beta); felem_scalar64(ftmp, 8); /* ftmp[i] < 2^62 + 2^17 */ felem_diff_128_64(tmp, ftmp); /* tmp[i] < 2^125 + 2^63 + 2^62 + 2^17 */ felem_reduce(x_out, tmp); /* z' = (y + z)^2 - gamma - delta */ felem_sum64(delta, gamma); /* delta[i] < 2^60 + 2^15 */ felem_assign(ftmp, y_in); felem_sum64(ftmp, z_in); /* ftmp[i] < 2^60 + 2^15 */ felem_square(tmp, ftmp); /* * tmp[i] < 17(2^122) < 2^127 */ felem_diff_128_64(tmp, delta); /* tmp[i] < 2^127 + 2^63 */ felem_reduce(z_out, tmp); /* y' = alpha*(4*beta - x') - 8*gamma^2 */ felem_scalar64(beta, 4); /* beta[i] < 2^61 + 2^16 */ felem_diff64(beta, x_out); /* beta[i] < 2^61 + 2^60 + 2^16 */ felem_mul(tmp, alpha, beta); /*- * tmp[i] < 17*((2^59 + 2^14)(2^61 + 2^60 + 2^16)) * = 17*(2^120 + 2^75 + 2^119 + 2^74 + 2^75 + 2^30) * = 17*(2^120 + 2^119 + 2^76 + 2^74 + 2^30) * < 2^128 */ felem_square(tmp2, gamma); /*- * tmp2[i] < 17*(2^59 + 2^14)^2 * = 17*(2^118 + 2^74 + 2^28) */ felem_scalar128(tmp2, 8); /*- * tmp2[i] < 8*17*(2^118 + 2^74 + 2^28) * = 2^125 + 2^121 + 2^81 + 2^77 + 2^35 + 2^31 * < 2^126 */ felem_diff128(tmp, tmp2); /*- * tmp[i] < 2^127 - 2^69 + 17(2^120 + 2^119 + 2^76 + 2^74 + 2^30) * = 2^127 + 2^124 + 2^122 + 2^120 + 2^118 + 2^80 + 2^78 + 2^76 + * 2^74 + 2^69 + 2^34 + 2^30 * < 2^128 */ felem_reduce(y_out, tmp); } /* copy_conditional copies in to out iff mask is all ones. */ static void copy_conditional(felem out, const felem in, limb mask) { unsigned i; for (i = 0; i < NLIMBS; ++i) { const limb tmp = mask & (in[i] ^ out[i]); out[i] ^= tmp; } } /*- * point_add calcuates (x1, y1, z1) + (x2, y2, z2) * * The method is taken from * http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#addition-add-2007-bl, * adapted for mixed addition (z2 = 1, or z2 = 0 for the point at infinity). * * This function includes a branch for checking whether the two input points * are equal (while not equal to the point at infinity). This case never * happens during single point multiplication, so there is no timing leak for * ECDH or ECDSA signing. */ static void point_add(felem x3, felem y3, felem z3, const felem x1, const felem y1, const felem z1, const int mixed, const felem x2, const felem y2, const felem z2) { felem ftmp, ftmp2, ftmp3, ftmp4, ftmp5, ftmp6, x_out, y_out, z_out; largefelem tmp, tmp2; limb x_equal, y_equal, z1_is_zero, z2_is_zero; z1_is_zero = felem_is_zero(z1); z2_is_zero = felem_is_zero(z2); /* ftmp = z1z1 = z1**2 */ felem_square(tmp, z1); felem_reduce(ftmp, tmp); if (!mixed) { /* ftmp2 = z2z2 = z2**2 */ felem_square(tmp, z2); felem_reduce(ftmp2, tmp); /* u1 = ftmp3 = x1*z2z2 */ felem_mul(tmp, x1, ftmp2); felem_reduce(ftmp3, tmp); /* ftmp5 = z1 + z2 */ felem_assign(ftmp5, z1); felem_sum64(ftmp5, z2); /* ftmp5[i] < 2^61 */ /* ftmp5 = (z1 + z2)**2 - z1z1 - z2z2 = 2*z1z2 */ felem_square(tmp, ftmp5); /* tmp[i] < 17*2^122 */ felem_diff_128_64(tmp, ftmp); /* tmp[i] < 17*2^122 + 2^63 */ felem_diff_128_64(tmp, ftmp2); /* tmp[i] < 17*2^122 + 2^64 */ felem_reduce(ftmp5, tmp); /* ftmp2 = z2 * z2z2 */ felem_mul(tmp, ftmp2, z2); felem_reduce(ftmp2, tmp); /* s1 = ftmp6 = y1 * z2**3 */ felem_mul(tmp, y1, ftmp2); felem_reduce(ftmp6, tmp); } else { /* * We'll assume z2 = 1 (special case z2 = 0 is handled later) */ /* u1 = ftmp3 = x1*z2z2 */ felem_assign(ftmp3, x1); /* ftmp5 = 2*z1z2 */ felem_scalar(ftmp5, z1, 2); /* s1 = ftmp6 = y1 * z2**3 */ felem_assign(ftmp6, y1); } /* u2 = x2*z1z1 */ felem_mul(tmp, x2, ftmp); /* tmp[i] < 17*2^120 */ /* h = ftmp4 = u2 - u1 */ felem_diff_128_64(tmp, ftmp3); /* tmp[i] < 17*2^120 + 2^63 */ felem_reduce(ftmp4, tmp); x_equal = felem_is_zero(ftmp4); /* z_out = ftmp5 * h */ felem_mul(tmp, ftmp5, ftmp4); felem_reduce(z_out, tmp); /* ftmp = z1 * z1z1 */ felem_mul(tmp, ftmp, z1); felem_reduce(ftmp, tmp); /* s2 = tmp = y2 * z1**3 */ felem_mul(tmp, y2, ftmp); /* tmp[i] < 17*2^120 */ /* r = ftmp5 = (s2 - s1)*2 */ felem_diff_128_64(tmp, ftmp6); /* tmp[i] < 17*2^120 + 2^63 */ felem_reduce(ftmp5, tmp); y_equal = felem_is_zero(ftmp5); felem_scalar64(ftmp5, 2); /* ftmp5[i] < 2^61 */ if (x_equal && y_equal && !z1_is_zero && !z2_is_zero) { point_double(x3, y3, z3, x1, y1, z1); return; } /* I = ftmp = (2h)**2 */ felem_assign(ftmp, ftmp4); felem_scalar64(ftmp, 2); /* ftmp[i] < 2^61 */ felem_square(tmp, ftmp); /* tmp[i] < 17*2^122 */ felem_reduce(ftmp, tmp); /* J = ftmp2 = h * I */ felem_mul(tmp, ftmp4, ftmp); felem_reduce(ftmp2, tmp); /* V = ftmp4 = U1 * I */ felem_mul(tmp, ftmp3, ftmp); felem_reduce(ftmp4, tmp); /* x_out = r**2 - J - 2V */ felem_square(tmp, ftmp5); /* tmp[i] < 17*2^122 */ felem_diff_128_64(tmp, ftmp2); /* tmp[i] < 17*2^122 + 2^63 */ felem_assign(ftmp3, ftmp4); felem_scalar64(ftmp4, 2); /* ftmp4[i] < 2^61 */ felem_diff_128_64(tmp, ftmp4); /* tmp[i] < 17*2^122 + 2^64 */ felem_reduce(x_out, tmp); /* y_out = r(V-x_out) - 2 * s1 * J */ felem_diff64(ftmp3, x_out); /* * ftmp3[i] < 2^60 + 2^60 = 2^61 */ felem_mul(tmp, ftmp5, ftmp3); /* tmp[i] < 17*2^122 */ felem_mul(tmp2, ftmp6, ftmp2); /* tmp2[i] < 17*2^120 */ felem_scalar128(tmp2, 2); /* tmp2[i] < 17*2^121 */ felem_diff128(tmp, tmp2); /*- * tmp[i] < 2^127 - 2^69 + 17*2^122 * = 2^126 - 2^122 - 2^6 - 2^2 - 1 * < 2^127 */ felem_reduce(y_out, tmp); copy_conditional(x_out, x2, z1_is_zero); copy_conditional(x_out, x1, z2_is_zero); copy_conditional(y_out, y2, z1_is_zero); copy_conditional(y_out, y1, z2_is_zero); copy_conditional(z_out, z2, z1_is_zero); copy_conditional(z_out, z1, z2_is_zero); felem_assign(x3, x_out); felem_assign(y3, y_out); felem_assign(z3, z_out); } /*- * Base point pre computation * -------------------------- * * Two different sorts of precomputed tables are used in the following code. * Each contain various points on the curve, where each point is three field * elements (x, y, z). * * For the base point table, z is usually 1 (0 for the point at infinity). * This table has 16 elements: * index | bits | point * ------+---------+------------------------------ * 0 | 0 0 0 0 | 0G * 1 | 0 0 0 1 | 1G * 2 | 0 0 1 0 | 2^130G * 3 | 0 0 1 1 | (2^130 + 1)G * 4 | 0 1 0 0 | 2^260G * 5 | 0 1 0 1 | (2^260 + 1)G * 6 | 0 1 1 0 | (2^260 + 2^130)G * 7 | 0 1 1 1 | (2^260 + 2^130 + 1)G * 8 | 1 0 0 0 | 2^390G * 9 | 1 0 0 1 | (2^390 + 1)G * 10 | 1 0 1 0 | (2^390 + 2^130)G * 11 | 1 0 1 1 | (2^390 + 2^130 + 1)G * 12 | 1 1 0 0 | (2^390 + 2^260)G * 13 | 1 1 0 1 | (2^390 + 2^260 + 1)G * 14 | 1 1 1 0 | (2^390 + 2^260 + 2^130)G * 15 | 1 1 1 1 | (2^390 + 2^260 + 2^130 + 1)G * * The reason for this is so that we can clock bits into four different * locations when doing simple scalar multiplies against the base point. * * Tables for other points have table[i] = iG for i in 0 .. 16. */ /* gmul is the table of precomputed base points */ static const felem gmul[16][3] = { {{0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x017e7e31c2e5bd66, 0x022cf0615a90a6fe, 0x00127a2ffa8de334, 0x01dfbf9d64a3f877, 0x006b4d3dbaa14b5e, 0x014fed487e0a2bd8, 0x015b4429c6481390, 0x03a73678fb2d988e, 0x00c6858e06b70404}, {0x00be94769fd16650, 0x031c21a89cb09022, 0x039013fad0761353, 0x02657bd099031542, 0x03273e662c97ee72, 0x01e6d11a05ebef45, 0x03d1bd998f544495, 0x03001172297ed0b1, 0x011839296a789a3b}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x0373faacbc875bae, 0x00f325023721c671, 0x00f666fd3dbde5ad, 0x01a6932363f88ea7, 0x01fc6d9e13f9c47b, 0x03bcbffc2bbf734e, 0x013ee3c3647f3a92, 0x029409fefe75d07d, 0x00ef9199963d85e5}, {0x011173743ad5b178, 0x02499c7c21bf7d46, 0x035beaeabb8b1a58, 0x00f989c4752ea0a3, 0x0101e1de48a9c1a3, 0x01a20076be28ba6c, 0x02f8052e5eb2de95, 0x01bfe8f82dea117c, 0x0160074d3c36ddb7}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x012f3fc373393b3b, 0x03d3d6172f1419fa, 0x02adc943c0b86873, 0x00d475584177952b, 0x012a4d1673750ee2, 0x00512517a0f13b0c, 0x02b184671a7b1734, 0x0315b84236f1a50a, 0x00a4afc472edbdb9}, {0x00152a7077f385c4, 0x03044007d8d1c2ee, 0x0065829d61d52b52, 0x00494ff6b6631d0d, 0x00a11d94d5f06bcf, 0x02d2f89474d9282e, 0x0241c5727c06eeb9, 0x0386928710fbdb9d, 0x01f883f727b0dfbe}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x019b0c3c9185544d, 0x006243a37c9d97db, 0x02ee3cbe030a2ad2, 0x00cfdd946bb51e0d, 0x0271c00932606b91, 0x03f817d1ec68c561, 0x03f37009806a369c, 0x03c1f30baf184fd5, 0x01091022d6d2f065}, {0x0292c583514c45ed, 0x0316fca51f9a286c, 0x00300af507c1489a, 0x0295f69008298cf1, 0x02c0ed8274943d7b, 0x016509b9b47a431e, 0x02bc9de9634868ce, 0x005b34929bffcb09, 0x000c1a0121681524}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x0286abc0292fb9f2, 0x02665eee9805b3f7, 0x01ed7455f17f26d6, 0x0346355b83175d13, 0x006284944cd0a097, 0x0191895bcdec5e51, 0x02e288370afda7d9, 0x03b22312bfefa67a, 0x01d104d3fc0613fe}, {0x0092421a12f7e47f, 0x0077a83fa373c501, 0x03bd25c5f696bd0d, 0x035c41e4d5459761, 0x01ca0d1742b24f53, 0x00aaab27863a509c, 0x018b6de47df73917, 0x025c0b771705cd01, 0x01fd51d566d760a7}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x01dd92ff6b0d1dbd, 0x039c5e2e8f8afa69, 0x0261ed13242c3b27, 0x0382c6e67026e6a0, 0x01d60b10be2089f9, 0x03c15f3dce86723f, 0x03c764a32d2a062d, 0x017307eac0fad056, 0x018207c0b96c5256}, {0x0196a16d60e13154, 0x03e6ce74c0267030, 0x00ddbf2b4e52a5aa, 0x012738241bbf31c8, 0x00ebe8dc04685a28, 0x024c2ad6d380d4a2, 0x035ee062a6e62d0e, 0x0029ed74af7d3a0f, 0x00eef32aec142ebd}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x00c31ec398993b39, 0x03a9f45bcda68253, 0x00ac733c24c70890, 0x00872b111401ff01, 0x01d178c23195eafb, 0x03bca2c816b87f74, 0x0261a9af46fbad7a, 0x0324b2a8dd3d28f9, 0x00918121d8f24e23}, {0x032bc8c1ca983cd7, 0x00d869dfb08fc8c6, 0x01693cb61fce1516, 0x012a5ea68f4e88a8, 0x010869cab88d7ae3, 0x009081ad277ceee1, 0x033a77166d064cdc, 0x03955235a1fb3a95, 0x01251a4a9b25b65e}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x00148a3a1b27f40b, 0x0123186df1b31fdc, 0x00026e7beaad34ce, 0x01db446ac1d3dbba, 0x0299c1a33437eaec, 0x024540610183cbb7, 0x0173bb0e9ce92e46, 0x02b937e43921214b, 0x01ab0436a9bf01b5}, {0x0383381640d46948, 0x008dacbf0e7f330f, 0x03602122bcc3f318, 0x01ee596b200620d6, 0x03bd0585fda430b3, 0x014aed77fd123a83, 0x005ace749e52f742, 0x0390fe041da2b842, 0x0189a8ceb3299242}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x012a19d6b3282473, 0x00c0915918b423ce, 0x023a954eb94405ae, 0x00529f692be26158, 0x0289fa1b6fa4b2aa, 0x0198ae4ceea346ef, 0x0047d8cdfbdedd49, 0x00cc8c8953f0f6b8, 0x001424abbff49203}, {0x0256732a1115a03a, 0x0351bc38665c6733, 0x03f7b950fb4a6447, 0x000afffa94c22155, 0x025763d0a4dab540, 0x000511e92d4fc283, 0x030a7e9eda0ee96c, 0x004c3cd93a28bf0a, 0x017edb3a8719217f}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x011de5675a88e673, 0x031d7d0f5e567fbe, 0x0016b2062c970ae5, 0x03f4a2be49d90aa7, 0x03cef0bd13822866, 0x03f0923dcf774a6c, 0x0284bebc4f322f72, 0x016ab2645302bb2c, 0x01793f95dace0e2a}, {0x010646e13527a28f, 0x01ca1babd59dc5e7, 0x01afedfd9a5595df, 0x01f15785212ea6b1, 0x0324e5d64f6ae3f4, 0x02d680f526d00645, 0x0127920fadf627a7, 0x03b383f75df4f684, 0x0089e0057e783b0a}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x00f334b9eb3c26c6, 0x0298fdaa98568dce, 0x01c2d24843a82292, 0x020bcb24fa1b0711, 0x02cbdb3d2b1875e6, 0x0014907598f89422, 0x03abe3aa43b26664, 0x02cbf47f720bc168, 0x0133b5e73014b79b}, {0x034aab5dab05779d, 0x00cdc5d71fee9abb, 0x0399f16bd4bd9d30, 0x03582fa592d82647, 0x02be1cdfb775b0e9, 0x0034f7cea32e94cb, 0x0335a7f08f56f286, 0x03b707e9565d1c8b, 0x0015c946ea5b614f}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x024676f6cff72255, 0x00d14625cac96378, 0x00532b6008bc3767, 0x01fc16721b985322, 0x023355ea1b091668, 0x029de7afdc0317c3, 0x02fc8a7ca2da037c, 0x02de1217d74a6f30, 0x013f7173175b73bf}, {0x0344913f441490b5, 0x0200f9e272b61eca, 0x0258a246b1dd55d2, 0x03753db9ea496f36, 0x025e02937a09c5ef, 0x030cbd3d14012692, 0x01793a67e70dc72a, 0x03ec1d37048a662e, 0x006550f700c32a8d}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x00d3f48a347eba27, 0x008e636649b61bd8, 0x00d3b93716778fb3, 0x004d1915757bd209, 0x019d5311a3da44e0, 0x016d1afcbbe6aade, 0x0241bf5f73265616, 0x0384672e5d50d39b, 0x005009fee522b684}, {0x029b4fab064435fe, 0x018868ee095bbb07, 0x01ea3d6936cc92b8, 0x000608b00f78a2f3, 0x02db911073d1c20f, 0x018205938470100a, 0x01f1e4964cbe6ff2, 0x021a19a29eed4663, 0x01414485f42afa81}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x01612b3a17f63e34, 0x03813992885428e6, 0x022b3c215b5a9608, 0x029b4057e19f2fcb, 0x0384059a587af7e6, 0x02d6400ace6fe610, 0x029354d896e8e331, 0x00c047ee6dfba65e, 0x0037720542e9d49d}, {0x02ce9eed7c5e9278, 0x0374ed703e79643b, 0x01316c54c4072006, 0x005aaa09054b2ee8, 0x002824000c840d57, 0x03d4eba24771ed86, 0x0189c50aabc3bdae, 0x0338c01541e15510, 0x00466d56e38eed42}, {1, 0, 0, 0, 0, 0, 0, 0, 0}}, {{0x007efd8330ad8bd6, 0x02465ed48047710b, 0x0034c6606b215e0c, 0x016ae30c53cbf839, 0x01fa17bd37161216, 0x018ead4e61ce8ab9, 0x005482ed5f5dee46, 0x037543755bba1d7f, 0x005e5ac7e70a9d0f}, {0x0117e1bb2fdcb2a2, 0x03deea36249f40c4, 0x028d09b4a6246cb7, 0x03524b8855bcf756, 0x023d7d109d5ceb58, 0x0178e43e3223ef9c, 0x0154536a0c6e966a, 0x037964d1286ee9fe, 0x0199bcd90e125055}, {1, 0, 0, 0, 0, 0, 0, 0, 0}} }; /* * select_point selects the |idx|th point from a precomputation table and * copies it to out. */ /* pre_comp below is of the size provided in |size| */ static void select_point(const limb idx, unsigned int size, const felem pre_comp[][3], felem out[3]) { unsigned i, j; limb *outlimbs = &out[0][0]; memset(outlimbs, 0, 3 * sizeof(felem)); for (i = 0; i < size; i++) { const limb *inlimbs = &pre_comp[i][0][0]; limb mask = i ^ idx; mask |= mask >> 4; mask |= mask >> 2; mask |= mask >> 1; mask &= 1; mask--; for (j = 0; j < NLIMBS * 3; j++) outlimbs[j] |= inlimbs[j] & mask; } } /* get_bit returns the |i|th bit in |in| */ static char get_bit(const felem_bytearray in, int i) { if (i < 0) return 0; return (in[i >> 3] >> (i & 7)) & 1; } /* * Interleaved point multiplication using precomputed point multiples: The * small point multiples 0*P, 1*P, ..., 16*P are in pre_comp[], the scalars * in scalars[]. If g_scalar is non-NULL, we also add this multiple of the * generator, using certain (large) precomputed multiples in g_pre_comp. * Output point (X, Y, Z) is stored in x_out, y_out, z_out */ static void batch_mul(felem x_out, felem y_out, felem z_out, const felem_bytearray scalars[], const unsigned num_points, const u8 *g_scalar, const int mixed, const felem pre_comp[][17][3], const felem g_pre_comp[16][3]) { int i, skip; unsigned num, gen_mul = (g_scalar != NULL); felem nq[3], tmp[4]; limb bits; u8 sign, digit; /* set nq to the point at infinity */ memset(nq, 0, 3 * sizeof(felem)); /* * Loop over all scalars msb-to-lsb, interleaving additions of multiples * of the generator (last quarter of rounds) and additions of other * points multiples (every 5th round). */ skip = 1; /* save two point operations in the first * round */ for (i = (num_points ? 520 : 130); i >= 0; --i) { /* double */ if (!skip) point_double(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2]); /* add multiples of the generator */ if (gen_mul && (i <= 130)) { bits = get_bit(g_scalar, i + 390) << 3; if (i < 130) { bits |= get_bit(g_scalar, i + 260) << 2; bits |= get_bit(g_scalar, i + 130) << 1; bits |= get_bit(g_scalar, i); } /* select the point to add, in constant time */ select_point(bits, 16, g_pre_comp, tmp); if (!skip) { /* The 1 argument below is for "mixed" */ point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1, tmp[0], tmp[1], tmp[2]); } else { memcpy(nq, tmp, 3 * sizeof(felem)); skip = 0; } } /* do other additions every 5 doublings */ if (num_points && (i % 5 == 0)) { /* loop over all scalars */ for (num = 0; num < num_points; ++num) { bits = get_bit(scalars[num], i + 4) << 5; bits |= get_bit(scalars[num], i + 3) << 4; bits |= get_bit(scalars[num], i + 2) << 3; bits |= get_bit(scalars[num], i + 1) << 2; bits |= get_bit(scalars[num], i) << 1; bits |= get_bit(scalars[num], i - 1); ec_GFp_nistp_recode_scalar_bits(&sign, &digit, bits); /* * select the point to add or subtract, in constant time */ select_point(digit, 17, pre_comp[num], tmp); felem_neg(tmp[3], tmp[1]); /* (X, -Y, Z) is the negative * point */ copy_conditional(tmp[1], tmp[3], (-(limb) sign)); if (!skip) { point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], mixed, tmp[0], tmp[1], tmp[2]); } else { memcpy(nq, tmp, 3 * sizeof(felem)); skip = 0; } } } } felem_assign(x_out, nq[0]); felem_assign(y_out, nq[1]); felem_assign(z_out, nq[2]); } /* Precomputation for the group generator. */ typedef struct { felem g_pre_comp[16][3]; int references; } NISTP521_PRE_COMP; const EC_METHOD *EC_GFp_nistp521_method(void) { static const EC_METHOD ret = { EC_FLAGS_DEFAULT_OCT, NID_X9_62_prime_field, ec_GFp_nistp521_group_init, ec_GFp_simple_group_finish, ec_GFp_simple_group_clear_finish, ec_GFp_nist_group_copy, ec_GFp_nistp521_group_set_curve, ec_GFp_simple_group_get_curve, ec_GFp_simple_group_get_degree, ec_GFp_simple_group_check_discriminant, ec_GFp_simple_point_init, ec_GFp_simple_point_finish, ec_GFp_simple_point_clear_finish, ec_GFp_simple_point_copy, ec_GFp_simple_point_set_to_infinity, ec_GFp_simple_set_Jprojective_coordinates_GFp, ec_GFp_simple_get_Jprojective_coordinates_GFp, ec_GFp_simple_point_set_affine_coordinates, ec_GFp_nistp521_point_get_affine_coordinates, 0 /* point_set_compressed_coordinates */ , 0 /* point2oct */ , 0 /* oct2point */ , ec_GFp_simple_add, ec_GFp_simple_dbl, ec_GFp_simple_invert, ec_GFp_simple_is_at_infinity, ec_GFp_simple_is_on_curve, ec_GFp_simple_cmp, ec_GFp_simple_make_affine, ec_GFp_simple_points_make_affine, ec_GFp_nistp521_points_mul, ec_GFp_nistp521_precompute_mult, ec_GFp_nistp521_have_precompute_mult, ec_GFp_nist_field_mul, ec_GFp_nist_field_sqr, 0 /* field_div */ , 0 /* field_encode */ , 0 /* field_decode */ , 0 /* field_set_to_one */ }; return &ret; } /******************************************************************************/ /* * FUNCTIONS TO MANAGE PRECOMPUTATION */ static NISTP521_PRE_COMP *nistp521_pre_comp_new() { NISTP521_PRE_COMP *ret = NULL; ret = (NISTP521_PRE_COMP *) OPENSSL_malloc(sizeof(NISTP521_PRE_COMP)); if (!ret) { ECerr(EC_F_NISTP521_PRE_COMP_NEW, ERR_R_MALLOC_FAILURE); return ret; } memset(ret->g_pre_comp, 0, sizeof(ret->g_pre_comp)); ret->references = 1; return ret; } static void *nistp521_pre_comp_dup(void *src_) { NISTP521_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 nistp521_pre_comp_free(void *pre_) { int i; NISTP521_PRE_COMP *pre = pre_; if (!pre) return; i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP); if (i > 0) return; OPENSSL_free(pre); } static void nistp521_pre_comp_clear_free(void *pre_) { int i; NISTP521_PRE_COMP *pre = pre_; if (!pre) return; i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP); if (i > 0) return; OPENSSL_cleanse(pre, sizeof(*pre)); OPENSSL_free(pre); } /******************************************************************************/ /* * OPENSSL EC_METHOD FUNCTIONS */ int ec_GFp_nistp521_group_init(EC_GROUP *group) { int ret; ret = ec_GFp_simple_group_init(group); group->a_is_minus3 = 1; return ret; } int ec_GFp_nistp521_group_set_curve(EC_GROUP *group, const BIGNUM *p, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { int ret = 0; BN_CTX *new_ctx = NULL; BIGNUM *curve_p, *curve_a, *curve_b; if (ctx == NULL) if ((ctx = new_ctx = BN_CTX_new()) == NULL) return 0; BN_CTX_start(ctx); if (((curve_p = BN_CTX_get(ctx)) == NULL) || ((curve_a = BN_CTX_get(ctx)) == NULL) || ((curve_b = BN_CTX_get(ctx)) == NULL)) goto err; BN_bin2bn(nistp521_curve_params[0], sizeof(felem_bytearray), curve_p); BN_bin2bn(nistp521_curve_params[1], sizeof(felem_bytearray), curve_a); BN_bin2bn(nistp521_curve_params[2], sizeof(felem_bytearray), curve_b); if ((BN_cmp(curve_p, p)) || (BN_cmp(curve_a, a)) || (BN_cmp(curve_b, b))) { ECerr(EC_F_EC_GFP_NISTP521_GROUP_SET_CURVE, EC_R_WRONG_CURVE_PARAMETERS); goto err; } group->field_mod_func = BN_nist_mod_521; ret = ec_GFp_simple_group_set_curve(group, p, a, b, ctx); err: BN_CTX_end(ctx); if (new_ctx != NULL) BN_CTX_free(new_ctx); return ret; } /* * Takes the Jacobian coordinates (X, Y, Z) of a point and returns (X', Y') = * (X/Z^2, Y/Z^3) */ int ec_GFp_nistp521_point_get_affine_coordinates(const EC_GROUP *group, const EC_POINT *point, BIGNUM *x, BIGNUM *y, BN_CTX *ctx) { felem z1, z2, x_in, y_in, x_out, y_out; largefelem tmp; if (EC_POINT_is_at_infinity(group, point)) { ECerr(EC_F_EC_GFP_NISTP521_POINT_GET_AFFINE_COORDINATES, EC_R_POINT_AT_INFINITY); return 0; } if ((!BN_to_felem(x_in, &point->X)) || (!BN_to_felem(y_in, &point->Y)) || (!BN_to_felem(z1, &point->Z))) return 0; felem_inv(z2, z1); felem_square(tmp, z2); felem_reduce(z1, tmp); felem_mul(tmp, x_in, z1); felem_reduce(x_in, tmp); felem_contract(x_out, x_in); if (x != NULL) { if (!felem_to_BN(x, x_out)) { ECerr(EC_F_EC_GFP_NISTP521_POINT_GET_AFFINE_COORDINATES, ERR_R_BN_LIB); return 0; } } felem_mul(tmp, z1, z2); felem_reduce(z1, tmp); felem_mul(tmp, y_in, z1); felem_reduce(y_in, tmp); felem_contract(y_out, y_in); if (y != NULL) { if (!felem_to_BN(y, y_out)) { ECerr(EC_F_EC_GFP_NISTP521_POINT_GET_AFFINE_COORDINATES, ERR_R_BN_LIB); return 0; } } return 1; } /* points below is of size |num|, and tmp_felems is of size |num+1/ */ static void make_points_affine(size_t num, felem points[][3], felem tmp_felems[]) { /* * Runs in constant time, unless an input is the point at infinity (which * normally shouldn't happen). */ ec_GFp_nistp_points_make_affine_internal(num, points, sizeof(felem), tmp_felems, (void (*)(void *))felem_one, - (int (*)(const void *)) felem_is_zero_int, (void (*)(void *, const void *)) felem_assign, (void (*)(void *, const void *)) felem_square_reduce, (void (*) (void *, const void *, const void *)) felem_mul_reduce, (void (*)(void *, const void *)) felem_inv, (void (*)(void *, const void *)) felem_contract); } /* * Computes scalar*generator + \sum scalars[i]*points[i], ignoring NULL * values Result is stored in r (r can equal one of the inputs). */ int ec_GFp_nistp521_points_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar, size_t num, const EC_POINT *points[], const BIGNUM *scalars[], BN_CTX *ctx) { int ret = 0; int j; int mixed = 0; BN_CTX *new_ctx = NULL; BIGNUM *x, *y, *z, *tmp_scalar; felem_bytearray g_secret; felem_bytearray *secrets = NULL; felem(*pre_comp)[17][3] = NULL; felem *tmp_felems = NULL; felem_bytearray tmp; unsigned i, num_bytes; int have_pre_comp = 0; size_t num_points = num; felem x_in, y_in, z_in, x_out, y_out, z_out; NISTP521_PRE_COMP *pre = NULL; felem(*g_pre_comp)[3] = NULL; EC_POINT *generator = NULL; const EC_POINT *p = NULL; const BIGNUM *p_scalar = NULL; if (ctx == NULL) if ((ctx = new_ctx = BN_CTX_new()) == NULL) return 0; BN_CTX_start(ctx); if (((x = BN_CTX_get(ctx)) == NULL) || ((y = BN_CTX_get(ctx)) == NULL) || ((z = BN_CTX_get(ctx)) == NULL) || ((tmp_scalar = BN_CTX_get(ctx)) == NULL)) goto err; if (scalar != NULL) { pre = EC_EX_DATA_get_data(group->extra_data, nistp521_pre_comp_dup, nistp521_pre_comp_free, nistp521_pre_comp_clear_free); if (pre) /* we have precomputation, try to use it */ g_pre_comp = &pre->g_pre_comp[0]; else /* try to use the standard precomputation */ g_pre_comp = (felem(*)[3]) gmul; generator = EC_POINT_new(group); if (generator == NULL) goto err; /* get the generator from precomputation */ if (!felem_to_BN(x, g_pre_comp[1][0]) || !felem_to_BN(y, g_pre_comp[1][1]) || !felem_to_BN(z, g_pre_comp[1][2])) { ECerr(EC_F_EC_GFP_NISTP521_POINTS_MUL, ERR_R_BN_LIB); goto err; } if (!EC_POINT_set_Jprojective_coordinates_GFp(group, generator, x, y, z, ctx)) goto err; if (0 == EC_POINT_cmp(group, generator, group->generator, ctx)) /* precomputation matches generator */ have_pre_comp = 1; else /* * we don't have valid precomputation: treat the generator as a * random point */ num_points++; } if (num_points > 0) { if (num_points >= 2) { /* * unless we precompute multiples for just one point, converting * those into affine form is time well spent */ mixed = 1; } secrets = OPENSSL_malloc(num_points * sizeof(felem_bytearray)); pre_comp = OPENSSL_malloc(num_points * 17 * 3 * sizeof(felem)); if (mixed) tmp_felems = OPENSSL_malloc((num_points * 17 + 1) * sizeof(felem)); if ((secrets == NULL) || (pre_comp == NULL) || (mixed && (tmp_felems == NULL))) { ECerr(EC_F_EC_GFP_NISTP521_POINTS_MUL, ERR_R_MALLOC_FAILURE); goto err; } /* * we treat NULL scalars as 0, and NULL points as points at infinity, * i.e., they contribute nothing to the linear combination */ memset(secrets, 0, num_points * sizeof(felem_bytearray)); memset(pre_comp, 0, num_points * 17 * 3 * sizeof(felem)); for (i = 0; i < num_points; ++i) { if (i == num) /* * we didn't have a valid precomputation, so we pick the * generator */ { p = EC_GROUP_get0_generator(group); p_scalar = scalar; } else /* the i^th point */ { p = points[i]; p_scalar = scalars[i]; } if ((p_scalar != NULL) && (p != NULL)) { /* reduce scalar to 0 <= scalar < 2^521 */ if ((BN_num_bits(p_scalar) > 521) || (BN_is_negative(p_scalar))) { /* * this is an unusual input, and we don't guarantee * constant-timeness */ if (!BN_nnmod(tmp_scalar, p_scalar, &group->order, ctx)) { ECerr(EC_F_EC_GFP_NISTP521_POINTS_MUL, ERR_R_BN_LIB); goto err; } num_bytes = BN_bn2bin(tmp_scalar, tmp); } else num_bytes = BN_bn2bin(p_scalar, tmp); flip_endian(secrets[i], tmp, num_bytes); /* precompute multiples */ if ((!BN_to_felem(x_out, &p->X)) || (!BN_to_felem(y_out, &p->Y)) || (!BN_to_felem(z_out, &p->Z))) goto err; memcpy(pre_comp[i][1][0], x_out, sizeof(felem)); memcpy(pre_comp[i][1][1], y_out, sizeof(felem)); memcpy(pre_comp[i][1][2], z_out, sizeof(felem)); for (j = 2; j <= 16; ++j) { if (j & 1) { point_add(pre_comp[i][j][0], pre_comp[i][j][1], pre_comp[i][j][2], pre_comp[i][1][0], pre_comp[i][1][1], pre_comp[i][1][2], 0, pre_comp[i][j - 1][0], pre_comp[i][j - 1][1], pre_comp[i][j - 1][2]); } else { point_double(pre_comp[i][j][0], pre_comp[i][j][1], pre_comp[i][j][2], pre_comp[i][j / 2][0], pre_comp[i][j / 2][1], pre_comp[i][j / 2][2]); } } } } if (mixed) make_points_affine(num_points * 17, pre_comp[0], tmp_felems); } /* the scalar for the generator */ if ((scalar != NULL) && (have_pre_comp)) { memset(g_secret, 0, sizeof(g_secret)); /* reduce scalar to 0 <= scalar < 2^521 */ if ((BN_num_bits(scalar) > 521) || (BN_is_negative(scalar))) { /* * this is an unusual input, and we don't guarantee * constant-timeness */ if (!BN_nnmod(tmp_scalar, scalar, &group->order, ctx)) { ECerr(EC_F_EC_GFP_NISTP521_POINTS_MUL, ERR_R_BN_LIB); goto err; } num_bytes = BN_bn2bin(tmp_scalar, tmp); } else num_bytes = BN_bn2bin(scalar, tmp); flip_endian(g_secret, tmp, num_bytes); /* do the multiplication with generator precomputation */ batch_mul(x_out, y_out, z_out, (const felem_bytearray(*))secrets, num_points, g_secret, mixed, (const felem(*)[17][3])pre_comp, (const felem(*)[3])g_pre_comp); } else /* do the multiplication without generator precomputation */ batch_mul(x_out, y_out, z_out, (const felem_bytearray(*))secrets, num_points, NULL, mixed, (const felem(*)[17][3])pre_comp, NULL); /* reduce the output to its unique minimal representation */ felem_contract(x_in, x_out); felem_contract(y_in, y_out); felem_contract(z_in, z_out); if ((!felem_to_BN(x, x_in)) || (!felem_to_BN(y, y_in)) || (!felem_to_BN(z, z_in))) { ECerr(EC_F_EC_GFP_NISTP521_POINTS_MUL, ERR_R_BN_LIB); goto err; } ret = EC_POINT_set_Jprojective_coordinates_GFp(group, r, x, y, z, ctx); err: BN_CTX_end(ctx); if (generator != NULL) EC_POINT_free(generator); if (new_ctx != NULL) BN_CTX_free(new_ctx); if (secrets != NULL) OPENSSL_free(secrets); if (pre_comp != NULL) OPENSSL_free(pre_comp); if (tmp_felems != NULL) OPENSSL_free(tmp_felems); return ret; } int ec_GFp_nistp521_precompute_mult(EC_GROUP *group, BN_CTX *ctx) { int ret = 0; NISTP521_PRE_COMP *pre = NULL; int i, j; BN_CTX *new_ctx = NULL; BIGNUM *x, *y; EC_POINT *generator = NULL; felem tmp_felems[16]; /* throw away old precomputation */ EC_EX_DATA_free_data(&group->extra_data, nistp521_pre_comp_dup, nistp521_pre_comp_free, nistp521_pre_comp_clear_free); if (ctx == NULL) if ((ctx = new_ctx = BN_CTX_new()) == NULL) return 0; BN_CTX_start(ctx); if (((x = BN_CTX_get(ctx)) == NULL) || ((y = BN_CTX_get(ctx)) == NULL)) goto err; /* get the generator */ if (group->generator == NULL) goto err; generator = EC_POINT_new(group); if (generator == NULL) goto err; BN_bin2bn(nistp521_curve_params[3], sizeof(felem_bytearray), x); BN_bin2bn(nistp521_curve_params[4], sizeof(felem_bytearray), y); if (!EC_POINT_set_affine_coordinates_GFp(group, generator, x, y, ctx)) goto err; if ((pre = nistp521_pre_comp_new()) == NULL) goto err; /* * if the generator is the standard one, use built-in precomputation */ if (0 == EC_POINT_cmp(group, generator, group->generator, ctx)) { memcpy(pre->g_pre_comp, gmul, sizeof(pre->g_pre_comp)); goto done; } if ((!BN_to_felem(pre->g_pre_comp[1][0], &group->generator->X)) || (!BN_to_felem(pre->g_pre_comp[1][1], &group->generator->Y)) || (!BN_to_felem(pre->g_pre_comp[1][2], &group->generator->Z))) goto err; /* compute 2^130*G, 2^260*G, 2^390*G */ for (i = 1; i <= 4; i <<= 1) { point_double(pre->g_pre_comp[2 * i][0], pre->g_pre_comp[2 * i][1], pre->g_pre_comp[2 * i][2], pre->g_pre_comp[i][0], pre->g_pre_comp[i][1], pre->g_pre_comp[i][2]); for (j = 0; j < 129; ++j) { point_double(pre->g_pre_comp[2 * i][0], pre->g_pre_comp[2 * i][1], pre->g_pre_comp[2 * i][2], pre->g_pre_comp[2 * i][0], pre->g_pre_comp[2 * i][1], pre->g_pre_comp[2 * i][2]); } } /* g_pre_comp[0] is the point at infinity */ memset(pre->g_pre_comp[0], 0, sizeof(pre->g_pre_comp[0])); /* the remaining multiples */ /* 2^130*G + 2^260*G */ point_add(pre->g_pre_comp[6][0], pre->g_pre_comp[6][1], pre->g_pre_comp[6][2], pre->g_pre_comp[4][0], pre->g_pre_comp[4][1], pre->g_pre_comp[4][2], 0, pre->g_pre_comp[2][0], pre->g_pre_comp[2][1], pre->g_pre_comp[2][2]); /* 2^130*G + 2^390*G */ point_add(pre->g_pre_comp[10][0], pre->g_pre_comp[10][1], pre->g_pre_comp[10][2], pre->g_pre_comp[8][0], pre->g_pre_comp[8][1], pre->g_pre_comp[8][2], 0, pre->g_pre_comp[2][0], pre->g_pre_comp[2][1], pre->g_pre_comp[2][2]); /* 2^260*G + 2^390*G */ point_add(pre->g_pre_comp[12][0], pre->g_pre_comp[12][1], pre->g_pre_comp[12][2], pre->g_pre_comp[8][0], pre->g_pre_comp[8][1], pre->g_pre_comp[8][2], 0, pre->g_pre_comp[4][0], pre->g_pre_comp[4][1], pre->g_pre_comp[4][2]); /* 2^130*G + 2^260*G + 2^390*G */ point_add(pre->g_pre_comp[14][0], pre->g_pre_comp[14][1], pre->g_pre_comp[14][2], pre->g_pre_comp[12][0], pre->g_pre_comp[12][1], pre->g_pre_comp[12][2], 0, pre->g_pre_comp[2][0], pre->g_pre_comp[2][1], pre->g_pre_comp[2][2]); for (i = 1; i < 8; ++i) { /* odd multiples: add G */ point_add(pre->g_pre_comp[2 * i + 1][0], pre->g_pre_comp[2 * i + 1][1], pre->g_pre_comp[2 * i + 1][2], pre->g_pre_comp[2 * i][0], pre->g_pre_comp[2 * i][1], pre->g_pre_comp[2 * i][2], 0, pre->g_pre_comp[1][0], pre->g_pre_comp[1][1], pre->g_pre_comp[1][2]); } make_points_affine(15, &(pre->g_pre_comp[1]), tmp_felems); done: if (!EC_EX_DATA_set_data(&group->extra_data, pre, nistp521_pre_comp_dup, nistp521_pre_comp_free, nistp521_pre_comp_clear_free)) goto err; ret = 1; pre = NULL; err: BN_CTX_end(ctx); if (generator != NULL) EC_POINT_free(generator); if (new_ctx != NULL) BN_CTX_free(new_ctx); if (pre) nistp521_pre_comp_free(pre); return ret; } int ec_GFp_nistp521_have_precompute_mult(const EC_GROUP *group) { if (EC_EX_DATA_get_data(group->extra_data, nistp521_pre_comp_dup, nistp521_pre_comp_free, nistp521_pre_comp_clear_free) != NULL) return 1; else return 0; } #else static void *dummy = &dummy; #endif Index: vendor-crypto/openssl/dist/crypto/ecdh/ech_lib.c =================================================================== --- vendor-crypto/openssl/dist/crypto/ecdh/ech_lib.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/ecdh/ech_lib.c (revision 325326) @@ -1,265 +1,272 @@ /* crypto/ecdh/ech_lib.c */ /* ==================================================================== * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. * * The Elliptic Curve Public-Key Crypto Library (ECC Code) included * herein is developed by SUN MICROSYSTEMS, INC., and is contributed * to the OpenSSL project. * * The ECC Code is licensed pursuant to the OpenSSL open source * license provided below. * * The ECDH software is originally written by Douglas Stebila of * Sun Microsystems Laboratories. * */ /* ==================================================================== * Copyright (c) 1998-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 * 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 "ech_locl.h" #include #ifndef OPENSSL_NO_ENGINE # include #endif #include #ifdef OPENSSL_FIPS # include #endif const char ECDH_version[] = "ECDH" OPENSSL_VERSION_PTEXT; static const ECDH_METHOD *default_ECDH_method = NULL; static void *ecdh_data_new(void); static void *ecdh_data_dup(void *); static void ecdh_data_free(void *); void ECDH_set_default_method(const ECDH_METHOD *meth) { default_ECDH_method = meth; } const ECDH_METHOD *ECDH_get_default_method(void) { if (!default_ECDH_method) { #ifdef OPENSSL_FIPS if (FIPS_mode()) return FIPS_ecdh_openssl(); else return ECDH_OpenSSL(); #else default_ECDH_method = ECDH_OpenSSL(); #endif } return default_ECDH_method; } int ECDH_set_method(EC_KEY *eckey, const ECDH_METHOD *meth) { ECDH_DATA *ecdh; ecdh = ecdh_check(eckey); if (ecdh == NULL) return 0; #if 0 mtmp = ecdh->meth; if (mtmp->finish) mtmp->finish(eckey); #endif #ifndef OPENSSL_NO_ENGINE if (ecdh->engine) { ENGINE_finish(ecdh->engine); ecdh->engine = NULL; } #endif ecdh->meth = meth; #if 0 if (meth->init) meth->init(eckey); #endif return 1; } static ECDH_DATA *ECDH_DATA_new_method(ENGINE *engine) { ECDH_DATA *ret; ret = (ECDH_DATA *)OPENSSL_malloc(sizeof(ECDH_DATA)); if (ret == NULL) { ECDHerr(ECDH_F_ECDH_DATA_NEW_METHOD, ERR_R_MALLOC_FAILURE); return (NULL); } ret->init = NULL; ret->meth = ECDH_get_default_method(); ret->engine = engine; #ifndef OPENSSL_NO_ENGINE if (!ret->engine) ret->engine = ENGINE_get_default_ECDH(); if (ret->engine) { ret->meth = ENGINE_get_ECDH(ret->engine); if (!ret->meth) { ECDHerr(ECDH_F_ECDH_DATA_NEW_METHOD, ERR_R_ENGINE_LIB); ENGINE_finish(ret->engine); OPENSSL_free(ret); return NULL; } } #endif ret->flags = ret->meth->flags; CRYPTO_new_ex_data(CRYPTO_EX_INDEX_ECDH, ret, &ret->ex_data); #if 0 if ((ret->meth->init != NULL) && !ret->meth->init(ret)) { CRYPTO_free_ex_data(CRYPTO_EX_INDEX_ECDH, ret, &ret->ex_data); OPENSSL_free(ret); ret = NULL; } #endif return (ret); } static void *ecdh_data_new(void) { return (void *)ECDH_DATA_new_method(NULL); } static void *ecdh_data_dup(void *data) { ECDH_DATA *r = (ECDH_DATA *)data; /* XXX: dummy operation */ if (r == NULL) return NULL; return (void *)ecdh_data_new(); } void ecdh_data_free(void *data) { ECDH_DATA *r = (ECDH_DATA *)data; #ifndef OPENSSL_NO_ENGINE if (r->engine) ENGINE_finish(r->engine); #endif CRYPTO_free_ex_data(CRYPTO_EX_INDEX_ECDH, r, &r->ex_data); OPENSSL_cleanse((void *)r, sizeof(ECDH_DATA)); OPENSSL_free(r); } ECDH_DATA *ecdh_check(EC_KEY *key) { ECDH_DATA *ecdh_data; void *data = EC_KEY_get_key_method_data(key, ecdh_data_dup, ecdh_data_free, ecdh_data_free); if (data == NULL) { ecdh_data = (ECDH_DATA *)ecdh_data_new(); if (ecdh_data == NULL) return NULL; data = EC_KEY_insert_key_method_data(key, (void *)ecdh_data, ecdh_data_dup, ecdh_data_free, ecdh_data_free); if (data != NULL) { /* * Another thread raced us to install the key_method data and * won. */ ecdh_data_free(ecdh_data); ecdh_data = (ECDH_DATA *)data; + } else if (EC_KEY_get_key_method_data(key, ecdh_data_dup, + ecdh_data_free, + ecdh_data_free) != ecdh_data) { + /* Or an out of memory error in EC_KEY_insert_key_method_data. */ + ecdh_data_free(ecdh_data); + return NULL; } - } else + } else { ecdh_data = (ECDH_DATA *)data; + } #ifdef OPENSSL_FIPS if (FIPS_mode() && !(ecdh_data->flags & ECDH_FLAG_FIPS_METHOD) && !(EC_KEY_get_flags(key) & EC_FLAG_NON_FIPS_ALLOW)) { ECDHerr(ECDH_F_ECDH_CHECK, ECDH_R_NON_FIPS_METHOD); return NULL; } #endif return ecdh_data; } int ECDH_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_ECDH, argl, argp, new_func, dup_func, free_func); } int ECDH_set_ex_data(EC_KEY *d, int idx, void *arg) { ECDH_DATA *ecdh; ecdh = ecdh_check(d); if (ecdh == NULL) return 0; return (CRYPTO_set_ex_data(&ecdh->ex_data, idx, arg)); } void *ECDH_get_ex_data(EC_KEY *d, int idx) { ECDH_DATA *ecdh; ecdh = ecdh_check(d); if (ecdh == NULL) return NULL; return (CRYPTO_get_ex_data(&ecdh->ex_data, idx)); } Index: vendor-crypto/openssl/dist/crypto/ecdsa/ecs_lib.c =================================================================== --- vendor-crypto/openssl/dist/crypto/ecdsa/ecs_lib.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/ecdsa/ecs_lib.c (revision 325326) @@ -1,354 +1,361 @@ /* crypto/ecdsa/ecs_lib.c */ /* ==================================================================== * 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). * */ #include #include "ecs_locl.h" #ifndef OPENSSL_NO_ENGINE # include #endif #include #include #ifdef OPENSSL_FIPS # include #endif const char ECDSA_version[] = "ECDSA" OPENSSL_VERSION_PTEXT; static const ECDSA_METHOD *default_ECDSA_method = NULL; static void *ecdsa_data_new(void); static void *ecdsa_data_dup(void *); static void ecdsa_data_free(void *); void ECDSA_set_default_method(const ECDSA_METHOD *meth) { default_ECDSA_method = meth; } const ECDSA_METHOD *ECDSA_get_default_method(void) { if (!default_ECDSA_method) { #ifdef OPENSSL_FIPS if (FIPS_mode()) return FIPS_ecdsa_openssl(); else return ECDSA_OpenSSL(); #else default_ECDSA_method = ECDSA_OpenSSL(); #endif } return default_ECDSA_method; } int ECDSA_set_method(EC_KEY *eckey, const ECDSA_METHOD *meth) { ECDSA_DATA *ecdsa; ecdsa = ecdsa_check(eckey); if (ecdsa == NULL) return 0; #ifndef OPENSSL_NO_ENGINE if (ecdsa->engine) { ENGINE_finish(ecdsa->engine); ecdsa->engine = NULL; } #endif ecdsa->meth = meth; return 1; } static ECDSA_DATA *ECDSA_DATA_new_method(ENGINE *engine) { ECDSA_DATA *ret; ret = (ECDSA_DATA *)OPENSSL_malloc(sizeof(ECDSA_DATA)); if (ret == NULL) { ECDSAerr(ECDSA_F_ECDSA_DATA_NEW_METHOD, ERR_R_MALLOC_FAILURE); return (NULL); } ret->init = NULL; ret->meth = ECDSA_get_default_method(); ret->engine = engine; #ifndef OPENSSL_NO_ENGINE if (!ret->engine) ret->engine = ENGINE_get_default_ECDSA(); if (ret->engine) { ret->meth = ENGINE_get_ECDSA(ret->engine); if (!ret->meth) { ECDSAerr(ECDSA_F_ECDSA_DATA_NEW_METHOD, ERR_R_ENGINE_LIB); ENGINE_finish(ret->engine); OPENSSL_free(ret); return NULL; } } #endif ret->flags = ret->meth->flags; CRYPTO_new_ex_data(CRYPTO_EX_INDEX_ECDSA, ret, &ret->ex_data); #if 0 if ((ret->meth->init != NULL) && !ret->meth->init(ret)) { CRYPTO_free_ex_data(CRYPTO_EX_INDEX_ECDSA, ret, &ret->ex_data); OPENSSL_free(ret); ret = NULL; } #endif return (ret); } static void *ecdsa_data_new(void) { return (void *)ECDSA_DATA_new_method(NULL); } static void *ecdsa_data_dup(void *data) { ECDSA_DATA *r = (ECDSA_DATA *)data; /* XXX: dummy operation */ if (r == NULL) return NULL; return ecdsa_data_new(); } static void ecdsa_data_free(void *data) { ECDSA_DATA *r = (ECDSA_DATA *)data; #ifndef OPENSSL_NO_ENGINE if (r->engine) ENGINE_finish(r->engine); #endif CRYPTO_free_ex_data(CRYPTO_EX_INDEX_ECDSA, r, &r->ex_data); OPENSSL_cleanse((void *)r, sizeof(ECDSA_DATA)); OPENSSL_free(r); } ECDSA_DATA *ecdsa_check(EC_KEY *key) { ECDSA_DATA *ecdsa_data; void *data = EC_KEY_get_key_method_data(key, ecdsa_data_dup, ecdsa_data_free, ecdsa_data_free); if (data == NULL) { ecdsa_data = (ECDSA_DATA *)ecdsa_data_new(); if (ecdsa_data == NULL) return NULL; data = EC_KEY_insert_key_method_data(key, (void *)ecdsa_data, ecdsa_data_dup, ecdsa_data_free, ecdsa_data_free); if (data != NULL) { /* * Another thread raced us to install the key_method data and * won. */ ecdsa_data_free(ecdsa_data); ecdsa_data = (ECDSA_DATA *)data; + } else if (EC_KEY_get_key_method_data(key, ecdsa_data_dup, + ecdsa_data_free, + ecdsa_data_free) != ecdsa_data) { + /* Or an out of memory error in EC_KEY_insert_key_method_data. */ + ecdsa_data_free(ecdsa_data); + return NULL; } - } else + } else { ecdsa_data = (ECDSA_DATA *)data; + } #ifdef OPENSSL_FIPS if (FIPS_mode() && !(ecdsa_data->flags & ECDSA_FLAG_FIPS_METHOD) && !(EC_KEY_get_flags(key) & EC_FLAG_NON_FIPS_ALLOW)) { ECDSAerr(ECDSA_F_ECDSA_CHECK, ECDSA_R_NON_FIPS_METHOD); return NULL; } #endif return ecdsa_data; } int ECDSA_size(const EC_KEY *r) { int ret, i; ASN1_INTEGER bs; BIGNUM *order = NULL; unsigned char buf[4]; const EC_GROUP *group; if (r == NULL) return 0; group = EC_KEY_get0_group(r); if (group == NULL) return 0; if ((order = BN_new()) == NULL) return 0; if (!EC_GROUP_get_order(group, order, NULL)) { BN_clear_free(order); return 0; } i = BN_num_bits(order); bs.length = (i + 7) / 8; bs.data = buf; bs.type = V_ASN1_INTEGER; /* If the top bit is set the asn1 encoding is 1 larger. */ buf[0] = 0xff; i = i2d_ASN1_INTEGER(&bs, NULL); i += i; /* r and s */ ret = ASN1_object_size(1, i, V_ASN1_SEQUENCE); BN_clear_free(order); return (ret); } int ECDSA_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_ECDSA, argl, argp, new_func, dup_func, free_func); } int ECDSA_set_ex_data(EC_KEY *d, int idx, void *arg) { ECDSA_DATA *ecdsa; ecdsa = ecdsa_check(d); if (ecdsa == NULL) return 0; return (CRYPTO_set_ex_data(&ecdsa->ex_data, idx, arg)); } void *ECDSA_get_ex_data(EC_KEY *d, int idx) { ECDSA_DATA *ecdsa; ecdsa = ecdsa_check(d); if (ecdsa == NULL) return NULL; return (CRYPTO_get_ex_data(&ecdsa->ex_data, idx)); } ECDSA_METHOD *ECDSA_METHOD_new(const ECDSA_METHOD *ecdsa_meth) { ECDSA_METHOD *ret; ret = OPENSSL_malloc(sizeof(ECDSA_METHOD)); if (ret == NULL) { ECDSAerr(ECDSA_F_ECDSA_METHOD_NEW, ERR_R_MALLOC_FAILURE); return NULL; } if (ecdsa_meth) *ret = *ecdsa_meth; else { ret->ecdsa_sign_setup = 0; ret->ecdsa_do_sign = 0; ret->ecdsa_do_verify = 0; ret->name = NULL; ret->flags = 0; } ret->flags |= ECDSA_METHOD_FLAG_ALLOCATED; return ret; } void ECDSA_METHOD_set_sign(ECDSA_METHOD *ecdsa_method, ECDSA_SIG *(*ecdsa_do_sign) (const unsigned char *dgst, int dgst_len, const BIGNUM *inv, const BIGNUM *rp, EC_KEY *eckey)) { ecdsa_method->ecdsa_do_sign = ecdsa_do_sign; } void ECDSA_METHOD_set_sign_setup(ECDSA_METHOD *ecdsa_method, int (*ecdsa_sign_setup) (EC_KEY *eckey, BN_CTX *ctx, BIGNUM **kinv, BIGNUM **r)) { ecdsa_method->ecdsa_sign_setup = ecdsa_sign_setup; } void ECDSA_METHOD_set_verify(ECDSA_METHOD *ecdsa_method, int (*ecdsa_do_verify) (const unsigned char *dgst, int dgst_len, const ECDSA_SIG *sig, EC_KEY *eckey)) { ecdsa_method->ecdsa_do_verify = ecdsa_do_verify; } void ECDSA_METHOD_set_flags(ECDSA_METHOD *ecdsa_method, int flags) { ecdsa_method->flags = flags | ECDSA_METHOD_FLAG_ALLOCATED; } void ECDSA_METHOD_set_name(ECDSA_METHOD *ecdsa_method, char *name) { ecdsa_method->name = name; } void ECDSA_METHOD_free(ECDSA_METHOD *ecdsa_method) { if (ecdsa_method->flags & ECDSA_METHOD_FLAG_ALLOCATED) OPENSSL_free(ecdsa_method); } void ECDSA_METHOD_set_app_data(ECDSA_METHOD *ecdsa_method, void *app) { ecdsa_method->app_data = app; } void *ECDSA_METHOD_get_app_data(ECDSA_METHOD *ecdsa_method) { return ecdsa_method->app_data; } Index: vendor-crypto/openssl/dist/crypto/ecdsa/ecs_ossl.c =================================================================== --- vendor-crypto/openssl/dist/crypto/ecdsa/ecs_ossl.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/ecdsa/ecs_ossl.c (revision 325326) @@ -1,464 +1,478 @@ /* crypto/ecdsa/ecs_ossl.c */ /* * Written by Nils Larsch for the OpenSSL project */ /* ==================================================================== * Copyright (c) 1998-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 "ecs_locl.h" #include #include #include static ECDSA_SIG *ecdsa_do_sign(const unsigned char *dgst, int dlen, const BIGNUM *, const BIGNUM *, EC_KEY *eckey); static int ecdsa_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp); static int ecdsa_do_verify(const unsigned char *dgst, int dgst_len, const ECDSA_SIG *sig, EC_KEY *eckey); static ECDSA_METHOD openssl_ecdsa_meth = { "OpenSSL ECDSA method", ecdsa_do_sign, ecdsa_sign_setup, ecdsa_do_verify, #if 0 NULL, /* init */ NULL, /* finish */ #endif 0, /* flags */ NULL /* app_data */ }; const ECDSA_METHOD *ECDSA_OpenSSL(void) { return &openssl_ecdsa_meth; } static int ecdsa_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp) { BN_CTX *ctx = NULL; BIGNUM *k = NULL, *r = NULL, *order = NULL, *X = NULL; EC_POINT *tmp_point = NULL; const EC_GROUP *group; int ret = 0; + int order_bits; if (eckey == NULL || (group = EC_KEY_get0_group(eckey)) == NULL) { ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (ctx_in == NULL) { if ((ctx = BN_CTX_new()) == NULL) { ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_MALLOC_FAILURE); return 0; } } else ctx = ctx_in; k = BN_new(); /* this value is later returned in *kinvp */ r = BN_new(); /* this value is later returned in *rp */ order = BN_new(); X = BN_new(); if (!k || !r || !order || !X) { ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_MALLOC_FAILURE); goto err; } if ((tmp_point = EC_POINT_new(group)) == NULL) { ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_EC_LIB); goto err; } if (!EC_GROUP_get_order(group, order, ctx)) { ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_EC_LIB); goto err; } + /* Preallocate space */ + order_bits = BN_num_bits(order); + if (!BN_set_bit(k, order_bits) + || !BN_set_bit(r, order_bits) + || !BN_set_bit(X, order_bits)) + goto err; + do { /* get random k */ do if (!BN_rand_range(k, order)) { ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ECDSA_R_RANDOM_NUMBER_GENERATION_FAILED); goto err; } while (BN_is_zero(k)) ; /* * We do not want timing information to leak the length of k, so we * compute G*k using an equivalent scalar of fixed bit-length. + * + * We unconditionally perform both of these additions to prevent a + * small timing information leakage. We then choose the sum that is + * one bit longer than the order. This guarantees the code + * path used in the constant time implementations elsewhere. + * + * TODO: revisit the BN_copy aiming for a memory access agnostic + * conditional copy. */ - - if (!BN_add(k, k, order)) + if (!BN_add(r, k, order) + || !BN_add(X, r, order) + || !BN_copy(k, BN_num_bits(r) > order_bits ? r : X)) goto err; - if (BN_num_bits(k) <= BN_num_bits(order)) - if (!BN_add(k, k, order)) - goto err; /* compute r the x-coordinate of generator * k */ if (!EC_POINT_mul(group, tmp_point, k, NULL, NULL, ctx)) { ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_EC_LIB); goto err; } if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) == NID_X9_62_prime_field) { if (!EC_POINT_get_affine_coordinates_GFp (group, tmp_point, X, NULL, ctx)) { ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_EC_LIB); goto err; } } #ifndef OPENSSL_NO_EC2M else { /* NID_X9_62_characteristic_two_field */ if (!EC_POINT_get_affine_coordinates_GF2m(group, tmp_point, X, NULL, ctx)) { ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_EC_LIB); goto err; } } #endif if (!BN_nnmod(r, X, order, ctx)) { ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_BN_LIB); goto err; } } while (BN_is_zero(r)); /* compute the inverse of k */ if (EC_GROUP_get_mont_data(group) != NULL) { /* * We want inverse in constant time, therefore we utilize the fact * order must be prime and use Fermats Little Theorem instead. */ if (!BN_set_word(X, 2)) { ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_BN_LIB); goto err; } if (!BN_mod_sub(X, order, X, order, ctx)) { ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_BN_LIB); goto err; } BN_set_flags(X, BN_FLG_CONSTTIME); if (!BN_mod_exp_mont_consttime (k, k, X, order, ctx, EC_GROUP_get_mont_data(group))) { ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_BN_LIB); goto err; } } else { if (!BN_mod_inverse(k, k, order, ctx)) { ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_BN_LIB); goto err; } } /* clear old values if necessary */ if (*rp != NULL) BN_clear_free(*rp); if (*kinvp != NULL) BN_clear_free(*kinvp); /* save the pre-computed values */ *rp = r; *kinvp = k; ret = 1; err: if (!ret) { if (k != NULL) BN_clear_free(k); if (r != NULL) BN_clear_free(r); } if (ctx_in == NULL) BN_CTX_free(ctx); if (order != NULL) BN_free(order); if (tmp_point != NULL) EC_POINT_free(tmp_point); if (X) BN_clear_free(X); return (ret); } static ECDSA_SIG *ecdsa_do_sign(const unsigned char *dgst, int dgst_len, const BIGNUM *in_kinv, const BIGNUM *in_r, EC_KEY *eckey) { int ok = 0, i; BIGNUM *kinv = NULL, *s, *m = NULL, *tmp = NULL, *order = NULL; const BIGNUM *ckinv; BN_CTX *ctx = NULL; const EC_GROUP *group; ECDSA_SIG *ret; ECDSA_DATA *ecdsa; const BIGNUM *priv_key; ecdsa = ecdsa_check(eckey); group = EC_KEY_get0_group(eckey); priv_key = EC_KEY_get0_private_key(eckey); if (group == NULL || priv_key == NULL || ecdsa == NULL) { ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_PASSED_NULL_PARAMETER); return NULL; } ret = ECDSA_SIG_new(); if (!ret) { ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_MALLOC_FAILURE); return NULL; } s = ret->s; if ((ctx = BN_CTX_new()) == NULL || (order = BN_new()) == NULL || (tmp = BN_new()) == NULL || (m = BN_new()) == NULL) { ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_MALLOC_FAILURE); goto err; } if (!EC_GROUP_get_order(group, order, ctx)) { ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_EC_LIB); goto err; } i = BN_num_bits(order); /* * Need to truncate digest if it is too long: first truncate whole bytes. */ if (8 * dgst_len > i) dgst_len = (i + 7) / 8; if (!BN_bin2bn(dgst, dgst_len, m)) { ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB); goto err; } /* If still too long truncate remaining bits with a shift */ if ((8 * dgst_len > i) && !BN_rshift(m, m, 8 - (i & 0x7))) { ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB); goto err; } do { if (in_kinv == NULL || in_r == NULL) { if (!ECDSA_sign_setup(eckey, ctx, &kinv, &ret->r)) { ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_ECDSA_LIB); goto err; } ckinv = kinv; } else { ckinv = in_kinv; if (BN_copy(ret->r, in_r) == NULL) { ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_MALLOC_FAILURE); goto err; } } if (!BN_mod_mul(tmp, priv_key, ret->r, order, ctx)) { ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB); goto err; } if (!BN_mod_add_quick(s, tmp, m, order)) { ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB); goto err; } if (!BN_mod_mul(s, s, ckinv, order, ctx)) { ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB); goto err; } if (BN_is_zero(s)) { /* * if kinv and r have been supplied by the caller don't to * generate new kinv and r values */ if (in_kinv != NULL && in_r != NULL) { ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ECDSA_R_NEED_NEW_SETUP_VALUES); goto err; } } else /* s != 0 => we have a valid signature */ break; } while (1); ok = 1; err: if (!ok) { ECDSA_SIG_free(ret); ret = NULL; } if (ctx) BN_CTX_free(ctx); if (m) BN_clear_free(m); if (tmp) BN_clear_free(tmp); if (order) BN_free(order); if (kinv) BN_clear_free(kinv); return ret; } static int ecdsa_do_verify(const unsigned char *dgst, int dgst_len, const ECDSA_SIG *sig, EC_KEY *eckey) { int ret = -1, i; BN_CTX *ctx; BIGNUM *order, *u1, *u2, *m, *X; EC_POINT *point = NULL; const EC_GROUP *group; const EC_POINT *pub_key; /* check input values */ if (eckey == NULL || (group = EC_KEY_get0_group(eckey)) == NULL || (pub_key = EC_KEY_get0_public_key(eckey)) == NULL || sig == NULL) { ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ECDSA_R_MISSING_PARAMETERS); return -1; } ctx = BN_CTX_new(); if (!ctx) { ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_MALLOC_FAILURE); return -1; } BN_CTX_start(ctx); order = BN_CTX_get(ctx); u1 = BN_CTX_get(ctx); u2 = BN_CTX_get(ctx); m = BN_CTX_get(ctx); X = BN_CTX_get(ctx); if (!X) { ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_BN_LIB); goto err; } if (!EC_GROUP_get_order(group, order, ctx)) { ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_EC_LIB); goto err; } if (BN_is_zero(sig->r) || BN_is_negative(sig->r) || BN_ucmp(sig->r, order) >= 0 || BN_is_zero(sig->s) || BN_is_negative(sig->s) || BN_ucmp(sig->s, order) >= 0) { ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ECDSA_R_BAD_SIGNATURE); ret = 0; /* signature is invalid */ goto err; } /* calculate tmp1 = inv(S) mod order */ if (!BN_mod_inverse(u2, sig->s, order, ctx)) { ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_BN_LIB); goto err; } /* digest -> m */ i = BN_num_bits(order); /* * Need to truncate digest if it is too long: first truncate whole bytes. */ if (8 * dgst_len > i) dgst_len = (i + 7) / 8; if (!BN_bin2bn(dgst, dgst_len, m)) { ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_BN_LIB); goto err; } /* If still too long truncate remaining bits with a shift */ if ((8 * dgst_len > i) && !BN_rshift(m, m, 8 - (i & 0x7))) { ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_BN_LIB); goto err; } /* u1 = m * tmp mod order */ if (!BN_mod_mul(u1, m, u2, order, ctx)) { ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_BN_LIB); goto err; } /* u2 = r * w mod q */ if (!BN_mod_mul(u2, sig->r, u2, order, ctx)) { ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_BN_LIB); goto err; } if ((point = EC_POINT_new(group)) == NULL) { ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_MALLOC_FAILURE); goto err; } if (!EC_POINT_mul(group, point, u1, pub_key, u2, ctx)) { ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_EC_LIB); goto err; } if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) == NID_X9_62_prime_field) { if (!EC_POINT_get_affine_coordinates_GFp(group, point, X, NULL, ctx)) { ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_EC_LIB); goto err; } } #ifndef OPENSSL_NO_EC2M else { /* NID_X9_62_characteristic_two_field */ if (!EC_POINT_get_affine_coordinates_GF2m(group, point, X, NULL, ctx)) { ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_EC_LIB); goto err; } } #endif if (!BN_nnmod(u1, X, order, ctx)) { ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_BN_LIB); goto err; } /* if the signature is correct u1 is equal to sig->r */ ret = (BN_ucmp(u1, sig->r) == 0); err: BN_CTX_end(ctx); BN_CTX_free(ctx); if (point) EC_POINT_free(point); return ret; } Index: vendor-crypto/openssl/dist/crypto/err/err.c =================================================================== --- vendor-crypto/openssl/dist/crypto/err/err.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/err/err.c (revision 325326) @@ -1,1149 +1,1158 @@ /* 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(); + if (es == NULL) + return; 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(); + if (es == NULL) + return; 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 (es == NULL) + return 0; 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); + return NULL; 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); + return NULL; } /* * 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(); + if (es == NULL) + return; 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 == NULL) + return 0; 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(); + if (es == NULL) + return 0; 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/evp/e_aes_cbc_hmac_sha1.c =================================================================== --- vendor-crypto/openssl/dist/crypto/evp/e_aes_cbc_hmac_sha1.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/evp/e_aes_cbc_hmac_sha1.c (revision 325326) @@ -1,1010 +1,1015 @@ /* ==================================================================== * 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); + mask = constant_time_ge(maxpad, pad); + ret &= mask; + /* + * If pad is invalid then we will fail the above test but we must + * continue anyway because we are in constant time code. However, + * we'll use the maxpad value instead of the supplied pad to make + * sure we perform well defined pointer arithmetic. + */ + pad = constant_time_select(mask, pad, maxpad); 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 325325) +++ vendor-crypto/openssl/dist/crypto/evp/e_aes_cbc_hmac_sha256.c (revision 325326) @@ -1,989 +1,996 @@ /* ==================================================================== * 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. + * But SHAEXT-capable go ahead... */ - 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"? */ + if (((OPENSSL_ia32cap_P[2] & (1 << 29)) || /* SHAEXT? */ + ((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); + mask = constant_time_ge(maxpad, pad); + ret &= mask; + /* + * If pad is invalid then we will fail the above test but we must + * continue anyway because we are in constant time code. However, + * we'll use the maxpad value instead of the supplied pad to make + * sure we perform well defined pointer arithmetic. + */ + pad = constant_time_select(mask, pad, maxpad); 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; 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/evp.h =================================================================== --- vendor-crypto/openssl/dist/crypto/evp/evp.h (revision 325325) +++ vendor-crypto/openssl/dist/crypto/evp/evp.h (revision 325326) @@ -1,1536 +1,1628 @@ /* crypto/evp/evp.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_ENVELOPE_H # define HEADER_ENVELOPE_H # ifdef OPENSSL_ALGORITHM_DEFINES # include # else # define OPENSSL_ALGORITHM_DEFINES # include # undef OPENSSL_ALGORITHM_DEFINES # endif # include # include # ifndef OPENSSL_NO_BIO # include # endif /*- #define EVP_RC2_KEY_SIZE 16 #define EVP_RC4_KEY_SIZE 16 #define EVP_BLOWFISH_KEY_SIZE 16 #define EVP_CAST5_KEY_SIZE 16 #define EVP_RC5_32_12_16_KEY_SIZE 16 */ # define EVP_MAX_MD_SIZE 64/* longest known is SHA512 */ # define EVP_MAX_KEY_LENGTH 64 # define EVP_MAX_IV_LENGTH 16 # define EVP_MAX_BLOCK_LENGTH 32 # define PKCS5_SALT_LEN 8 /* Default PKCS#5 iteration count */ # define PKCS5_DEFAULT_ITER 2048 # include # define EVP_PK_RSA 0x0001 # define EVP_PK_DSA 0x0002 # define EVP_PK_DH 0x0004 # define EVP_PK_EC 0x0008 # define EVP_PKT_SIGN 0x0010 # define EVP_PKT_ENC 0x0020 # define EVP_PKT_EXCH 0x0040 # define EVP_PKS_RSA 0x0100 # define EVP_PKS_DSA 0x0200 # define EVP_PKS_EC 0x0400 # define EVP_PKEY_NONE NID_undef # define EVP_PKEY_RSA NID_rsaEncryption # define EVP_PKEY_RSA2 NID_rsa # define EVP_PKEY_DSA NID_dsa # define EVP_PKEY_DSA1 NID_dsa_2 # define EVP_PKEY_DSA2 NID_dsaWithSHA # define EVP_PKEY_DSA3 NID_dsaWithSHA1 # define EVP_PKEY_DSA4 NID_dsaWithSHA1_2 # define EVP_PKEY_DH NID_dhKeyAgreement # define EVP_PKEY_DHX NID_dhpublicnumber # define EVP_PKEY_EC NID_X9_62_id_ecPublicKey # define EVP_PKEY_HMAC NID_hmac # define EVP_PKEY_CMAC NID_cmac #ifdef __cplusplus extern "C" { #endif /* * Type needs to be a bit field Sub-type needs to be for variations on the * method, as in, can it do arbitrary encryption.... */ struct evp_pkey_st { int type; int save_type; int references; const EVP_PKEY_ASN1_METHOD *ameth; ENGINE *engine; union { char *ptr; # ifndef OPENSSL_NO_RSA struct rsa_st *rsa; /* RSA */ # endif # ifndef OPENSSL_NO_DSA struct dsa_st *dsa; /* DSA */ # endif # ifndef OPENSSL_NO_DH struct dh_st *dh; /* DH */ # endif # ifndef OPENSSL_NO_EC struct ec_key_st *ec; /* ECC */ # endif } pkey; int save_parameters; STACK_OF(X509_ATTRIBUTE) *attributes; /* [ 0 ] */ } /* EVP_PKEY */ ; # define EVP_PKEY_MO_SIGN 0x0001 # define EVP_PKEY_MO_VERIFY 0x0002 # define EVP_PKEY_MO_ENCRYPT 0x0004 # define EVP_PKEY_MO_DECRYPT 0x0008 # ifndef EVP_MD struct env_md_st { int type; int pkey_type; int md_size; unsigned long flags; int (*init) (EVP_MD_CTX *ctx); int (*update) (EVP_MD_CTX *ctx, const void *data, size_t count); int (*final) (EVP_MD_CTX *ctx, unsigned char *md); int (*copy) (EVP_MD_CTX *to, const EVP_MD_CTX *from); int (*cleanup) (EVP_MD_CTX *ctx); /* FIXME: prototype these some day */ int (*sign) (int type, const unsigned char *m, unsigned int m_length, unsigned char *sigret, unsigned int *siglen, void *key); int (*verify) (int type, const unsigned char *m, unsigned int m_length, const unsigned char *sigbuf, unsigned int siglen, void *key); int required_pkey_type[5]; /* EVP_PKEY_xxx */ int block_size; int ctx_size; /* how big does the ctx->md_data need to be */ /* control function */ int (*md_ctrl) (EVP_MD_CTX *ctx, int cmd, int p1, void *p2); } /* EVP_MD */ ; typedef int evp_sign_method(int type, const unsigned char *m, unsigned int m_length, unsigned char *sigret, unsigned int *siglen, void *key); typedef int evp_verify_method(int type, const unsigned char *m, unsigned int m_length, const unsigned char *sigbuf, unsigned int siglen, void *key); /* digest can only handle a single block */ # define EVP_MD_FLAG_ONESHOT 0x0001 /* * digest is a "clone" digest used * which is a copy of an existing * one for a specific public key type. * EVP_dss1() etc */ # define EVP_MD_FLAG_PKEY_DIGEST 0x0002 /* Digest uses EVP_PKEY_METHOD for signing instead of MD specific signing */ # define EVP_MD_FLAG_PKEY_METHOD_SIGNATURE 0x0004 /* DigestAlgorithmIdentifier flags... */ # define EVP_MD_FLAG_DIGALGID_MASK 0x0018 /* NULL or absent parameter accepted. Use NULL */ # define EVP_MD_FLAG_DIGALGID_NULL 0x0000 /* NULL or absent parameter accepted. Use NULL for PKCS#1 otherwise absent */ # define EVP_MD_FLAG_DIGALGID_ABSENT 0x0008 /* Custom handling via ctrl */ # define EVP_MD_FLAG_DIGALGID_CUSTOM 0x0018 /* Note if suitable for use in FIPS mode */ # define EVP_MD_FLAG_FIPS 0x0400 /* Digest ctrls */ # define EVP_MD_CTRL_DIGALGID 0x1 # define EVP_MD_CTRL_MICALG 0x2 /* Minimum Algorithm specific ctrl value */ # define EVP_MD_CTRL_ALG_CTRL 0x1000 # define EVP_PKEY_NULL_method NULL,NULL,{0,0,0,0} # ifndef OPENSSL_NO_DSA # define EVP_PKEY_DSA_method (evp_sign_method *)DSA_sign, \ (evp_verify_method *)DSA_verify, \ {EVP_PKEY_DSA,EVP_PKEY_DSA2,EVP_PKEY_DSA3, \ EVP_PKEY_DSA4,0} # else # define EVP_PKEY_DSA_method EVP_PKEY_NULL_method # endif # ifndef OPENSSL_NO_ECDSA # define EVP_PKEY_ECDSA_method (evp_sign_method *)ECDSA_sign, \ (evp_verify_method *)ECDSA_verify, \ {EVP_PKEY_EC,0,0,0} # else # define EVP_PKEY_ECDSA_method EVP_PKEY_NULL_method # endif # ifndef OPENSSL_NO_RSA # define EVP_PKEY_RSA_method (evp_sign_method *)RSA_sign, \ (evp_verify_method *)RSA_verify, \ {EVP_PKEY_RSA,EVP_PKEY_RSA2,0,0} # define EVP_PKEY_RSA_ASN1_OCTET_STRING_method \ (evp_sign_method *)RSA_sign_ASN1_OCTET_STRING, \ (evp_verify_method *)RSA_verify_ASN1_OCTET_STRING, \ {EVP_PKEY_RSA,EVP_PKEY_RSA2,0,0} # else # define EVP_PKEY_RSA_method EVP_PKEY_NULL_method # define EVP_PKEY_RSA_ASN1_OCTET_STRING_method EVP_PKEY_NULL_method # endif # endif /* !EVP_MD */ struct env_md_ctx_st { const EVP_MD *digest; ENGINE *engine; /* functional reference if 'digest' is * ENGINE-provided */ unsigned long flags; void *md_data; /* Public key context for sign/verify */ EVP_PKEY_CTX *pctx; /* Update function: usually copied from EVP_MD */ int (*update) (EVP_MD_CTX *ctx, const void *data, size_t count); } /* EVP_MD_CTX */ ; /* values for EVP_MD_CTX flags */ # define EVP_MD_CTX_FLAG_ONESHOT 0x0001/* digest update will be * called once only */ # define EVP_MD_CTX_FLAG_CLEANED 0x0002/* context has already been * cleaned */ # define EVP_MD_CTX_FLAG_REUSE 0x0004/* Don't free up ctx->md_data * in EVP_MD_CTX_cleanup */ /* * FIPS and pad options are ignored in 1.0.0, definitions are here so we * don't accidentally reuse the values for other purposes. */ # define EVP_MD_CTX_FLAG_NON_FIPS_ALLOW 0x0008/* Allow use of non FIPS * digest in FIPS mode */ /* * The following PAD options are also currently ignored in 1.0.0, digest * parameters are handled through EVP_DigestSign*() and EVP_DigestVerify*() * instead. */ # define EVP_MD_CTX_FLAG_PAD_MASK 0xF0/* RSA mode to use */ # define EVP_MD_CTX_FLAG_PAD_PKCS1 0x00/* PKCS#1 v1.5 mode */ # define EVP_MD_CTX_FLAG_PAD_X931 0x10/* X9.31 mode */ # define EVP_MD_CTX_FLAG_PAD_PSS 0x20/* PSS mode */ # define EVP_MD_CTX_FLAG_NO_INIT 0x0100/* Don't initialize md_data */ struct evp_cipher_st { int nid; int block_size; /* Default value for variable length ciphers */ int key_len; int iv_len; /* Various flags */ unsigned long flags; /* init key */ int (*init) (EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); /* encrypt/decrypt data */ int (*do_cipher) (EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl); /* cleanup ctx */ int (*cleanup) (EVP_CIPHER_CTX *); /* how big ctx->cipher_data needs to be */ int ctx_size; /* Populate a ASN1_TYPE with parameters */ int (*set_asn1_parameters) (EVP_CIPHER_CTX *, ASN1_TYPE *); /* Get parameters from a ASN1_TYPE */ int (*get_asn1_parameters) (EVP_CIPHER_CTX *, ASN1_TYPE *); /* Miscellaneous operations */ int (*ctrl) (EVP_CIPHER_CTX *, int type, int arg, void *ptr); /* Application data */ void *app_data; } /* EVP_CIPHER */ ; /* Values for cipher flags */ /* Modes for ciphers */ # define EVP_CIPH_STREAM_CIPHER 0x0 # define EVP_CIPH_ECB_MODE 0x1 # define EVP_CIPH_CBC_MODE 0x2 # define EVP_CIPH_CFB_MODE 0x3 # define EVP_CIPH_OFB_MODE 0x4 # define EVP_CIPH_CTR_MODE 0x5 # define EVP_CIPH_GCM_MODE 0x6 # define EVP_CIPH_CCM_MODE 0x7 # define EVP_CIPH_XTS_MODE 0x10001 # define EVP_CIPH_WRAP_MODE 0x10002 # define EVP_CIPH_MODE 0xF0007 /* Set if variable length cipher */ # define EVP_CIPH_VARIABLE_LENGTH 0x8 /* Set if the iv handling should be done by the cipher itself */ # define EVP_CIPH_CUSTOM_IV 0x10 /* Set if the cipher's init() function should be called if key is NULL */ # define EVP_CIPH_ALWAYS_CALL_INIT 0x20 /* Call ctrl() to init cipher parameters */ # define EVP_CIPH_CTRL_INIT 0x40 /* Don't use standard key length function */ # define EVP_CIPH_CUSTOM_KEY_LENGTH 0x80 /* Don't use standard block padding */ # define EVP_CIPH_NO_PADDING 0x100 /* cipher handles random key generation */ # define EVP_CIPH_RAND_KEY 0x200 /* cipher has its own additional copying logic */ # define EVP_CIPH_CUSTOM_COPY 0x400 /* Allow use default ASN1 get/set iv */ # define EVP_CIPH_FLAG_DEFAULT_ASN1 0x1000 /* Buffer length in bits not bytes: CFB1 mode only */ # define EVP_CIPH_FLAG_LENGTH_BITS 0x2000 /* Note if suitable for use in FIPS mode */ # define EVP_CIPH_FLAG_FIPS 0x4000 /* Allow non FIPS cipher in FIPS mode */ # define EVP_CIPH_FLAG_NON_FIPS_ALLOW 0x8000 /* * Cipher handles any and all padding logic as well as finalisation. */ # define EVP_CIPH_FLAG_CUSTOM_CIPHER 0x100000 # define EVP_CIPH_FLAG_AEAD_CIPHER 0x200000 # define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0x400000 /* * Cipher context flag to indicate we can handle wrap mode: if allowed in * older applications it could overflow buffers. */ # define EVP_CIPHER_CTX_FLAG_WRAP_ALLOW 0x1 /* ctrl() values */ # define EVP_CTRL_INIT 0x0 # define EVP_CTRL_SET_KEY_LENGTH 0x1 # define EVP_CTRL_GET_RC2_KEY_BITS 0x2 # define EVP_CTRL_SET_RC2_KEY_BITS 0x3 # define EVP_CTRL_GET_RC5_ROUNDS 0x4 # define EVP_CTRL_SET_RC5_ROUNDS 0x5 # define EVP_CTRL_RAND_KEY 0x6 # define EVP_CTRL_PBE_PRF_NID 0x7 # define EVP_CTRL_COPY 0x8 # define EVP_CTRL_GCM_SET_IVLEN 0x9 # define EVP_CTRL_GCM_GET_TAG 0x10 # define EVP_CTRL_GCM_SET_TAG 0x11 # define EVP_CTRL_GCM_SET_IV_FIXED 0x12 # define EVP_CTRL_GCM_IV_GEN 0x13 # define EVP_CTRL_CCM_SET_IVLEN EVP_CTRL_GCM_SET_IVLEN # define EVP_CTRL_CCM_GET_TAG EVP_CTRL_GCM_GET_TAG # define EVP_CTRL_CCM_SET_TAG EVP_CTRL_GCM_SET_TAG # define EVP_CTRL_CCM_SET_L 0x14 # define EVP_CTRL_CCM_SET_MSGLEN 0x15 /* * AEAD cipher deduces payload length and returns number of bytes required to * store MAC and eventual padding. Subsequent call to EVP_Cipher even * appends/verifies MAC. */ # define EVP_CTRL_AEAD_TLS1_AAD 0x16 /* Used by composite AEAD ciphers, no-op in GCM, CCM... */ # define EVP_CTRL_AEAD_SET_MAC_KEY 0x17 /* Set the GCM invocation field, decrypt only */ # define EVP_CTRL_GCM_SET_IV_INV 0x18 # define EVP_CTRL_TLS1_1_MULTIBLOCK_AAD 0x19 # define EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT 0x1a # define EVP_CTRL_TLS1_1_MULTIBLOCK_DECRYPT 0x1b # define EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE 0x1c /* RFC 5246 defines additional data to be 13 bytes in length */ # define EVP_AEAD_TLS1_AAD_LEN 13 typedef struct { unsigned char *out; const unsigned char *inp; size_t len; unsigned int interleave; } EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM; /* GCM TLS constants */ /* Length of fixed part of IV derived from PRF */ # define EVP_GCM_TLS_FIXED_IV_LEN 4 /* Length of explicit part of IV part of TLS records */ # define EVP_GCM_TLS_EXPLICIT_IV_LEN 8 /* Length of tag for TLS */ # define EVP_GCM_TLS_TAG_LEN 16 typedef struct evp_cipher_info_st { const EVP_CIPHER *cipher; unsigned char iv[EVP_MAX_IV_LENGTH]; } EVP_CIPHER_INFO; struct evp_cipher_ctx_st { const EVP_CIPHER *cipher; ENGINE *engine; /* functional reference if 'cipher' is * ENGINE-provided */ int encrypt; /* encrypt or decrypt */ int buf_len; /* number we have left */ unsigned char oiv[EVP_MAX_IV_LENGTH]; /* original iv */ unsigned char iv[EVP_MAX_IV_LENGTH]; /* working iv */ unsigned char buf[EVP_MAX_BLOCK_LENGTH]; /* saved partial block */ int num; /* used by cfb/ofb/ctr mode */ void *app_data; /* application stuff */ int key_len; /* May change for variable length cipher */ unsigned long flags; /* Various flags */ void *cipher_data; /* per EVP data */ int final_used; int block_mask; unsigned char final[EVP_MAX_BLOCK_LENGTH]; /* possible final block */ } /* EVP_CIPHER_CTX */ ; typedef struct evp_Encode_Ctx_st { /* number saved in a partial encode/decode */ int num; /* * The length is either the output line length (in input bytes) or the * shortest input line length that is ok. Once decoding begins, the * length is adjusted up each time a longer line is decoded */ int length; /* data to encode */ unsigned char enc_data[80]; /* number read on current line */ int line_num; int expect_nl; } EVP_ENCODE_CTX; /* Password based encryption function */ typedef int (EVP_PBE_KEYGEN) (EVP_CIPHER_CTX *ctx, const char *pass, int passlen, ASN1_TYPE *param, const EVP_CIPHER *cipher, const EVP_MD *md, int en_de); # ifndef OPENSSL_NO_RSA # define EVP_PKEY_assign_RSA(pkey,rsa) EVP_PKEY_assign((pkey),EVP_PKEY_RSA,\ (char *)(rsa)) # endif # ifndef OPENSSL_NO_DSA # define EVP_PKEY_assign_DSA(pkey,dsa) EVP_PKEY_assign((pkey),EVP_PKEY_DSA,\ (char *)(dsa)) # endif # ifndef OPENSSL_NO_DH # define EVP_PKEY_assign_DH(pkey,dh) EVP_PKEY_assign((pkey),EVP_PKEY_DH,\ (char *)(dh)) # endif # ifndef OPENSSL_NO_EC # define EVP_PKEY_assign_EC_KEY(pkey,eckey) EVP_PKEY_assign((pkey),EVP_PKEY_EC,\ (char *)(eckey)) # endif /* Add some extra combinations */ # define EVP_get_digestbynid(a) EVP_get_digestbyname(OBJ_nid2sn(a)) # define EVP_get_digestbyobj(a) EVP_get_digestbynid(OBJ_obj2nid(a)) # define EVP_get_cipherbynid(a) EVP_get_cipherbyname(OBJ_nid2sn(a)) # define EVP_get_cipherbyobj(a) EVP_get_cipherbynid(OBJ_obj2nid(a)) int EVP_MD_type(const EVP_MD *md); # define EVP_MD_nid(e) EVP_MD_type(e) # define EVP_MD_name(e) OBJ_nid2sn(EVP_MD_nid(e)) int EVP_MD_pkey_type(const EVP_MD *md); int EVP_MD_size(const EVP_MD *md); int EVP_MD_block_size(const EVP_MD *md); unsigned long EVP_MD_flags(const EVP_MD *md); const EVP_MD *EVP_MD_CTX_md(const EVP_MD_CTX *ctx); # define EVP_MD_CTX_size(e) EVP_MD_size(EVP_MD_CTX_md(e)) # define EVP_MD_CTX_block_size(e) EVP_MD_block_size(EVP_MD_CTX_md(e)) # define EVP_MD_CTX_type(e) EVP_MD_type(EVP_MD_CTX_md(e)) int EVP_CIPHER_nid(const EVP_CIPHER *cipher); # define EVP_CIPHER_name(e) OBJ_nid2sn(EVP_CIPHER_nid(e)) int EVP_CIPHER_block_size(const EVP_CIPHER *cipher); int EVP_CIPHER_key_length(const EVP_CIPHER *cipher); int EVP_CIPHER_iv_length(const EVP_CIPHER *cipher); unsigned long EVP_CIPHER_flags(const EVP_CIPHER *cipher); # define EVP_CIPHER_mode(e) (EVP_CIPHER_flags(e) & EVP_CIPH_MODE) const EVP_CIPHER *EVP_CIPHER_CTX_cipher(const EVP_CIPHER_CTX *ctx); int EVP_CIPHER_CTX_nid(const EVP_CIPHER_CTX *ctx); int EVP_CIPHER_CTX_block_size(const EVP_CIPHER_CTX *ctx); int EVP_CIPHER_CTX_key_length(const EVP_CIPHER_CTX *ctx); int EVP_CIPHER_CTX_iv_length(const EVP_CIPHER_CTX *ctx); int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in); void *EVP_CIPHER_CTX_get_app_data(const EVP_CIPHER_CTX *ctx); void EVP_CIPHER_CTX_set_app_data(EVP_CIPHER_CTX *ctx, void *data); # define EVP_CIPHER_CTX_type(c) EVP_CIPHER_type(EVP_CIPHER_CTX_cipher(c)) unsigned long EVP_CIPHER_CTX_flags(const EVP_CIPHER_CTX *ctx); # define EVP_CIPHER_CTX_mode(e) (EVP_CIPHER_CTX_flags(e) & EVP_CIPH_MODE) # define EVP_ENCODE_LENGTH(l) (((l+2)/3*4)+(l/48+1)*2+80) # define EVP_DECODE_LENGTH(l) ((l+3)/4*3+80) # define EVP_SignInit_ex(a,b,c) EVP_DigestInit_ex(a,b,c) # define EVP_SignInit(a,b) EVP_DigestInit(a,b) # define EVP_SignUpdate(a,b,c) EVP_DigestUpdate(a,b,c) # define EVP_VerifyInit_ex(a,b,c) EVP_DigestInit_ex(a,b,c) # define EVP_VerifyInit(a,b) EVP_DigestInit(a,b) # define EVP_VerifyUpdate(a,b,c) EVP_DigestUpdate(a,b,c) # define EVP_OpenUpdate(a,b,c,d,e) EVP_DecryptUpdate(a,b,c,d,e) # define EVP_SealUpdate(a,b,c,d,e) EVP_EncryptUpdate(a,b,c,d,e) # define EVP_DigestSignUpdate(a,b,c) EVP_DigestUpdate(a,b,c) # define EVP_DigestVerifyUpdate(a,b,c) EVP_DigestUpdate(a,b,c) # ifdef CONST_STRICT void BIO_set_md(BIO *, const EVP_MD *md); # else # define BIO_set_md(b,md) BIO_ctrl(b,BIO_C_SET_MD,0,(char *)md) # endif # define BIO_get_md(b,mdp) BIO_ctrl(b,BIO_C_GET_MD,0,(char *)mdp) # define BIO_get_md_ctx(b,mdcp) BIO_ctrl(b,BIO_C_GET_MD_CTX,0,(char *)mdcp) # define BIO_set_md_ctx(b,mdcp) BIO_ctrl(b,BIO_C_SET_MD_CTX,0,(char *)mdcp) # define BIO_get_cipher_status(b) BIO_ctrl(b,BIO_C_GET_CIPHER_STATUS,0,NULL) # define BIO_get_cipher_ctx(b,c_pp) BIO_ctrl(b,BIO_C_GET_CIPHER_CTX,0,(char *)c_pp) int EVP_Cipher(EVP_CIPHER_CTX *c, unsigned char *out, const unsigned char *in, unsigned int inl); # define EVP_add_cipher_alias(n,alias) \ OBJ_NAME_add((alias),OBJ_NAME_TYPE_CIPHER_METH|OBJ_NAME_ALIAS,(n)) # define EVP_add_digest_alias(n,alias) \ OBJ_NAME_add((alias),OBJ_NAME_TYPE_MD_METH|OBJ_NAME_ALIAS,(n)) # define EVP_delete_cipher_alias(alias) \ OBJ_NAME_remove(alias,OBJ_NAME_TYPE_CIPHER_METH|OBJ_NAME_ALIAS); # define EVP_delete_digest_alias(alias) \ OBJ_NAME_remove(alias,OBJ_NAME_TYPE_MD_METH|OBJ_NAME_ALIAS); void EVP_MD_CTX_init(EVP_MD_CTX *ctx); int EVP_MD_CTX_cleanup(EVP_MD_CTX *ctx); EVP_MD_CTX *EVP_MD_CTX_create(void); void EVP_MD_CTX_destroy(EVP_MD_CTX *ctx); int EVP_MD_CTX_copy_ex(EVP_MD_CTX *out, const EVP_MD_CTX *in); void EVP_MD_CTX_set_flags(EVP_MD_CTX *ctx, int flags); void EVP_MD_CTX_clear_flags(EVP_MD_CTX *ctx, int flags); int EVP_MD_CTX_test_flags(const EVP_MD_CTX *ctx, int flags); int EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *impl); int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *d, size_t cnt); int EVP_DigestFinal_ex(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *s); int EVP_Digest(const void *data, size_t count, unsigned char *md, unsigned int *size, const EVP_MD *type, ENGINE *impl); int EVP_MD_CTX_copy(EVP_MD_CTX *out, const EVP_MD_CTX *in); int EVP_DigestInit(EVP_MD_CTX *ctx, const EVP_MD *type); int EVP_DigestFinal(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *s); int EVP_read_pw_string(char *buf, int length, const char *prompt, int verify); int EVP_read_pw_string_min(char *buf, int minlen, int maxlen, const char *prompt, int verify); void EVP_set_pw_prompt(const char *prompt); char *EVP_get_pw_prompt(void); int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md, const unsigned char *salt, const unsigned char *data, int datal, int count, unsigned char *key, unsigned char *iv); void EVP_CIPHER_CTX_set_flags(EVP_CIPHER_CTX *ctx, int flags); void EVP_CIPHER_CTX_clear_flags(EVP_CIPHER_CTX *ctx, int flags); int EVP_CIPHER_CTX_test_flags(const EVP_CIPHER_CTX *ctx, int flags); int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, const unsigned char *key, const unsigned char *iv); int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, ENGINE *impl, const unsigned char *key, const unsigned char *iv); int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl); int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl); int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl); int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, const unsigned char *key, const unsigned char *iv); int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, ENGINE *impl, const unsigned char *key, const unsigned char *iv); int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl); int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl); int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl); int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, const unsigned char *key, const unsigned char *iv, int 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); int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl); int EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl); int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl); int EVP_SignFinal(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *s, EVP_PKEY *pkey); int EVP_VerifyFinal(EVP_MD_CTX *ctx, const unsigned char *sigbuf, unsigned int siglen, EVP_PKEY *pkey); int EVP_DigestSignInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, const EVP_MD *type, ENGINE *e, EVP_PKEY *pkey); int EVP_DigestSignFinal(EVP_MD_CTX *ctx, unsigned char *sigret, size_t *siglen); int EVP_DigestVerifyInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, const EVP_MD *type, ENGINE *e, EVP_PKEY *pkey); int EVP_DigestVerifyFinal(EVP_MD_CTX *ctx, const unsigned char *sig, size_t siglen); int EVP_OpenInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, const unsigned char *ek, int ekl, const unsigned char *iv, EVP_PKEY *priv); int EVP_OpenFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl); int EVP_SealInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, unsigned char **ek, int *ekl, unsigned char *iv, EVP_PKEY **pubk, int npubk); int EVP_SealFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl); void EVP_EncodeInit(EVP_ENCODE_CTX *ctx); void EVP_EncodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl); void EVP_EncodeFinal(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl); int EVP_EncodeBlock(unsigned char *t, const unsigned char *f, int n); void EVP_DecodeInit(EVP_ENCODE_CTX *ctx); int EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl); int EVP_DecodeFinal(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl); int EVP_DecodeBlock(unsigned char *t, const unsigned char *f, int n); void EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *a); int EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *a); EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void); void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *a); int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *x, int keylen); int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *c, int pad); int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr); int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key); # ifndef OPENSSL_NO_BIO BIO_METHOD *BIO_f_md(void); BIO_METHOD *BIO_f_base64(void); BIO_METHOD *BIO_f_cipher(void); BIO_METHOD *BIO_f_reliable(void); void BIO_set_cipher(BIO *b, const EVP_CIPHER *c, const unsigned char *k, const unsigned char *i, int enc); # endif const EVP_MD *EVP_md_null(void); # ifndef OPENSSL_NO_MD2 const EVP_MD *EVP_md2(void); # endif # ifndef OPENSSL_NO_MD4 const EVP_MD *EVP_md4(void); # endif # ifndef OPENSSL_NO_MD5 const EVP_MD *EVP_md5(void); # endif # ifndef OPENSSL_NO_SHA const EVP_MD *EVP_sha(void); const EVP_MD *EVP_sha1(void); const EVP_MD *EVP_dss(void); const EVP_MD *EVP_dss1(void); const EVP_MD *EVP_ecdsa(void); # endif # ifndef OPENSSL_NO_SHA256 const EVP_MD *EVP_sha224(void); const EVP_MD *EVP_sha256(void); # endif # ifndef OPENSSL_NO_SHA512 const EVP_MD *EVP_sha384(void); const EVP_MD *EVP_sha512(void); # endif # ifndef OPENSSL_NO_MDC2 const EVP_MD *EVP_mdc2(void); # endif # ifndef OPENSSL_NO_RIPEMD const EVP_MD *EVP_ripemd160(void); # endif # ifndef OPENSSL_NO_WHIRLPOOL const EVP_MD *EVP_whirlpool(void); # endif const EVP_CIPHER *EVP_enc_null(void); /* does nothing :-) */ # ifndef OPENSSL_NO_DES const EVP_CIPHER *EVP_des_ecb(void); const EVP_CIPHER *EVP_des_ede(void); const EVP_CIPHER *EVP_des_ede3(void); const EVP_CIPHER *EVP_des_ede_ecb(void); const EVP_CIPHER *EVP_des_ede3_ecb(void); const EVP_CIPHER *EVP_des_cfb64(void); # define EVP_des_cfb EVP_des_cfb64 const EVP_CIPHER *EVP_des_cfb1(void); const EVP_CIPHER *EVP_des_cfb8(void); const EVP_CIPHER *EVP_des_ede_cfb64(void); # define EVP_des_ede_cfb EVP_des_ede_cfb64 # if 0 const EVP_CIPHER *EVP_des_ede_cfb1(void); const EVP_CIPHER *EVP_des_ede_cfb8(void); # endif const EVP_CIPHER *EVP_des_ede3_cfb64(void); # define EVP_des_ede3_cfb EVP_des_ede3_cfb64 const EVP_CIPHER *EVP_des_ede3_cfb1(void); const EVP_CIPHER *EVP_des_ede3_cfb8(void); const EVP_CIPHER *EVP_des_ofb(void); const EVP_CIPHER *EVP_des_ede_ofb(void); const EVP_CIPHER *EVP_des_ede3_ofb(void); const EVP_CIPHER *EVP_des_cbc(void); const EVP_CIPHER *EVP_des_ede_cbc(void); const EVP_CIPHER *EVP_des_ede3_cbc(void); const EVP_CIPHER *EVP_desx_cbc(void); const EVP_CIPHER *EVP_des_ede3_wrap(void); /* * This should now be supported through the dev_crypto ENGINE. But also, why * are rc4 and md5 declarations made here inside a "NO_DES" precompiler * branch? */ # if 0 # ifdef OPENSSL_OPENBSD_DEV_CRYPTO const EVP_CIPHER *EVP_dev_crypto_des_ede3_cbc(void); const EVP_CIPHER *EVP_dev_crypto_rc4(void); const EVP_MD *EVP_dev_crypto_md5(void); # endif # endif # endif # ifndef OPENSSL_NO_RC4 const EVP_CIPHER *EVP_rc4(void); const EVP_CIPHER *EVP_rc4_40(void); # ifndef OPENSSL_NO_MD5 const EVP_CIPHER *EVP_rc4_hmac_md5(void); # endif # endif # ifndef OPENSSL_NO_IDEA const EVP_CIPHER *EVP_idea_ecb(void); const EVP_CIPHER *EVP_idea_cfb64(void); # define EVP_idea_cfb EVP_idea_cfb64 const EVP_CIPHER *EVP_idea_ofb(void); const EVP_CIPHER *EVP_idea_cbc(void); # endif # ifndef OPENSSL_NO_RC2 const EVP_CIPHER *EVP_rc2_ecb(void); const EVP_CIPHER *EVP_rc2_cbc(void); const EVP_CIPHER *EVP_rc2_40_cbc(void); const EVP_CIPHER *EVP_rc2_64_cbc(void); const EVP_CIPHER *EVP_rc2_cfb64(void); # define EVP_rc2_cfb EVP_rc2_cfb64 const EVP_CIPHER *EVP_rc2_ofb(void); # endif # ifndef OPENSSL_NO_BF const EVP_CIPHER *EVP_bf_ecb(void); const EVP_CIPHER *EVP_bf_cbc(void); const EVP_CIPHER *EVP_bf_cfb64(void); # define EVP_bf_cfb EVP_bf_cfb64 const EVP_CIPHER *EVP_bf_ofb(void); # endif # ifndef OPENSSL_NO_CAST const EVP_CIPHER *EVP_cast5_ecb(void); const EVP_CIPHER *EVP_cast5_cbc(void); const EVP_CIPHER *EVP_cast5_cfb64(void); # define EVP_cast5_cfb EVP_cast5_cfb64 const EVP_CIPHER *EVP_cast5_ofb(void); # endif # ifndef OPENSSL_NO_RC5 const EVP_CIPHER *EVP_rc5_32_12_16_cbc(void); const EVP_CIPHER *EVP_rc5_32_12_16_ecb(void); const EVP_CIPHER *EVP_rc5_32_12_16_cfb64(void); # define EVP_rc5_32_12_16_cfb EVP_rc5_32_12_16_cfb64 const EVP_CIPHER *EVP_rc5_32_12_16_ofb(void); # endif # ifndef OPENSSL_NO_AES const EVP_CIPHER *EVP_aes_128_ecb(void); const EVP_CIPHER *EVP_aes_128_cbc(void); const EVP_CIPHER *EVP_aes_128_cfb1(void); const EVP_CIPHER *EVP_aes_128_cfb8(void); const EVP_CIPHER *EVP_aes_128_cfb128(void); # define EVP_aes_128_cfb EVP_aes_128_cfb128 const EVP_CIPHER *EVP_aes_128_ofb(void); const EVP_CIPHER *EVP_aes_128_ctr(void); const EVP_CIPHER *EVP_aes_128_ccm(void); const EVP_CIPHER *EVP_aes_128_gcm(void); const EVP_CIPHER *EVP_aes_128_xts(void); const EVP_CIPHER *EVP_aes_128_wrap(void); const EVP_CIPHER *EVP_aes_192_ecb(void); const EVP_CIPHER *EVP_aes_192_cbc(void); const EVP_CIPHER *EVP_aes_192_cfb1(void); const EVP_CIPHER *EVP_aes_192_cfb8(void); const EVP_CIPHER *EVP_aes_192_cfb128(void); # define EVP_aes_192_cfb EVP_aes_192_cfb128 const EVP_CIPHER *EVP_aes_192_ofb(void); const EVP_CIPHER *EVP_aes_192_ctr(void); const EVP_CIPHER *EVP_aes_192_ccm(void); const EVP_CIPHER *EVP_aes_192_gcm(void); const EVP_CIPHER *EVP_aes_192_wrap(void); const EVP_CIPHER *EVP_aes_256_ecb(void); const EVP_CIPHER *EVP_aes_256_cbc(void); const EVP_CIPHER *EVP_aes_256_cfb1(void); const EVP_CIPHER *EVP_aes_256_cfb8(void); const EVP_CIPHER *EVP_aes_256_cfb128(void); # define EVP_aes_256_cfb EVP_aes_256_cfb128 const EVP_CIPHER *EVP_aes_256_ofb(void); const EVP_CIPHER *EVP_aes_256_ctr(void); const EVP_CIPHER *EVP_aes_256_ccm(void); const EVP_CIPHER *EVP_aes_256_gcm(void); const EVP_CIPHER *EVP_aes_256_xts(void); const EVP_CIPHER *EVP_aes_256_wrap(void); # if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_SHA1) const EVP_CIPHER *EVP_aes_128_cbc_hmac_sha1(void); const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha1(void); # endif # ifndef OPENSSL_NO_SHA256 const EVP_CIPHER *EVP_aes_128_cbc_hmac_sha256(void); const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha256(void); # endif # endif # ifndef OPENSSL_NO_CAMELLIA const EVP_CIPHER *EVP_camellia_128_ecb(void); const EVP_CIPHER *EVP_camellia_128_cbc(void); const EVP_CIPHER *EVP_camellia_128_cfb1(void); const EVP_CIPHER *EVP_camellia_128_cfb8(void); const EVP_CIPHER *EVP_camellia_128_cfb128(void); # define EVP_camellia_128_cfb EVP_camellia_128_cfb128 const EVP_CIPHER *EVP_camellia_128_ofb(void); const EVP_CIPHER *EVP_camellia_192_ecb(void); const EVP_CIPHER *EVP_camellia_192_cbc(void); const EVP_CIPHER *EVP_camellia_192_cfb1(void); const EVP_CIPHER *EVP_camellia_192_cfb8(void); const EVP_CIPHER *EVP_camellia_192_cfb128(void); # define EVP_camellia_192_cfb EVP_camellia_192_cfb128 const EVP_CIPHER *EVP_camellia_192_ofb(void); const EVP_CIPHER *EVP_camellia_256_ecb(void); const EVP_CIPHER *EVP_camellia_256_cbc(void); const EVP_CIPHER *EVP_camellia_256_cfb1(void); const EVP_CIPHER *EVP_camellia_256_cfb8(void); const EVP_CIPHER *EVP_camellia_256_cfb128(void); # define EVP_camellia_256_cfb EVP_camellia_256_cfb128 const EVP_CIPHER *EVP_camellia_256_ofb(void); # endif # ifndef OPENSSL_NO_SEED const EVP_CIPHER *EVP_seed_ecb(void); const EVP_CIPHER *EVP_seed_cbc(void); const EVP_CIPHER *EVP_seed_cfb128(void); # define EVP_seed_cfb EVP_seed_cfb128 const EVP_CIPHER *EVP_seed_ofb(void); # endif void OPENSSL_add_all_algorithms_noconf(void); void OPENSSL_add_all_algorithms_conf(void); # ifdef OPENSSL_LOAD_CONF # define OpenSSL_add_all_algorithms() \ OPENSSL_add_all_algorithms_conf() # else # define OpenSSL_add_all_algorithms() \ OPENSSL_add_all_algorithms_noconf() # endif void OpenSSL_add_all_ciphers(void); void OpenSSL_add_all_digests(void); # define SSLeay_add_all_algorithms() OpenSSL_add_all_algorithms() # define SSLeay_add_all_ciphers() OpenSSL_add_all_ciphers() # define SSLeay_add_all_digests() OpenSSL_add_all_digests() int EVP_add_cipher(const EVP_CIPHER *cipher); int EVP_add_digest(const EVP_MD *digest); const EVP_CIPHER *EVP_get_cipherbyname(const char *name); const EVP_MD *EVP_get_digestbyname(const char *name); void EVP_cleanup(void); void EVP_CIPHER_do_all(void (*fn) (const EVP_CIPHER *ciph, const char *from, const char *to, void *x), void *arg); void EVP_CIPHER_do_all_sorted(void (*fn) (const EVP_CIPHER *ciph, const char *from, const char *to, void *x), void *arg); void EVP_MD_do_all(void (*fn) (const EVP_MD *ciph, const char *from, const char *to, void *x), void *arg); void EVP_MD_do_all_sorted(void (*fn) (const EVP_MD *ciph, const char *from, const char *to, void *x), void *arg); int EVP_PKEY_decrypt_old(unsigned char *dec_key, const unsigned char *enc_key, int enc_key_len, EVP_PKEY *private_key); int EVP_PKEY_encrypt_old(unsigned char *enc_key, const unsigned char *key, int key_len, EVP_PKEY *pub_key); int EVP_PKEY_type(int type); int EVP_PKEY_id(const EVP_PKEY *pkey); int EVP_PKEY_base_id(const EVP_PKEY *pkey); int EVP_PKEY_bits(EVP_PKEY *pkey); int EVP_PKEY_size(EVP_PKEY *pkey); int EVP_PKEY_set_type(EVP_PKEY *pkey, int type); int EVP_PKEY_set_type_str(EVP_PKEY *pkey, const char *str, int len); int EVP_PKEY_assign(EVP_PKEY *pkey, int type, void *key); void *EVP_PKEY_get0(EVP_PKEY *pkey); # ifndef OPENSSL_NO_RSA struct rsa_st; int EVP_PKEY_set1_RSA(EVP_PKEY *pkey, struct rsa_st *key); struct rsa_st *EVP_PKEY_get1_RSA(EVP_PKEY *pkey); # endif # ifndef OPENSSL_NO_DSA struct dsa_st; int EVP_PKEY_set1_DSA(EVP_PKEY *pkey, struct dsa_st *key); struct dsa_st *EVP_PKEY_get1_DSA(EVP_PKEY *pkey); # endif # ifndef OPENSSL_NO_DH struct dh_st; int EVP_PKEY_set1_DH(EVP_PKEY *pkey, struct dh_st *key); struct dh_st *EVP_PKEY_get1_DH(EVP_PKEY *pkey); # endif # ifndef OPENSSL_NO_EC struct ec_key_st; int EVP_PKEY_set1_EC_KEY(EVP_PKEY *pkey, struct ec_key_st *key); struct ec_key_st *EVP_PKEY_get1_EC_KEY(EVP_PKEY *pkey); # endif EVP_PKEY *EVP_PKEY_new(void); void EVP_PKEY_free(EVP_PKEY *pkey); EVP_PKEY *d2i_PublicKey(int type, EVP_PKEY **a, const unsigned char **pp, long length); int i2d_PublicKey(EVP_PKEY *a, unsigned char **pp); EVP_PKEY *d2i_PrivateKey(int type, EVP_PKEY **a, const unsigned char **pp, long length); EVP_PKEY *d2i_AutoPrivateKey(EVP_PKEY **a, const unsigned char **pp, long length); int i2d_PrivateKey(EVP_PKEY *a, unsigned char **pp); int EVP_PKEY_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from); int EVP_PKEY_missing_parameters(const EVP_PKEY *pkey); int EVP_PKEY_save_parameters(EVP_PKEY *pkey, int mode); int EVP_PKEY_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b); int EVP_PKEY_cmp(const EVP_PKEY *a, const EVP_PKEY *b); int EVP_PKEY_print_public(BIO *out, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx); int EVP_PKEY_print_private(BIO *out, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx); int EVP_PKEY_print_params(BIO *out, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx); int EVP_PKEY_get_default_digest_nid(EVP_PKEY *pkey, int *pnid); int EVP_CIPHER_type(const EVP_CIPHER *ctx); /* calls methods */ int EVP_CIPHER_param_to_asn1(EVP_CIPHER_CTX *c, ASN1_TYPE *type); int EVP_CIPHER_asn1_to_param(EVP_CIPHER_CTX *c, ASN1_TYPE *type); /* These are used by EVP_CIPHER methods */ int EVP_CIPHER_set_asn1_iv(EVP_CIPHER_CTX *c, ASN1_TYPE *type); int EVP_CIPHER_get_asn1_iv(EVP_CIPHER_CTX *c, ASN1_TYPE *type); /* PKCS5 password based encryption */ int PKCS5_PBE_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass, int passlen, ASN1_TYPE *param, const EVP_CIPHER *cipher, const EVP_MD *md, int en_de); int PKCS5_PBKDF2_HMAC_SHA1(const char *pass, int passlen, const unsigned char *salt, int saltlen, int iter, int keylen, unsigned char *out); int PKCS5_PBKDF2_HMAC(const char *pass, int passlen, const unsigned char *salt, int saltlen, int iter, const EVP_MD *digest, int keylen, unsigned char *out); int PKCS5_v2_PBE_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass, int passlen, ASN1_TYPE *param, const EVP_CIPHER *cipher, const EVP_MD *md, int en_de); void PKCS5_PBE_add(void); int EVP_PBE_CipherInit(ASN1_OBJECT *pbe_obj, const char *pass, int passlen, ASN1_TYPE *param, EVP_CIPHER_CTX *ctx, int en_de); /* PBE type */ /* Can appear as the outermost AlgorithmIdentifier */ # define EVP_PBE_TYPE_OUTER 0x0 /* Is an PRF type OID */ # define EVP_PBE_TYPE_PRF 0x1 int EVP_PBE_alg_add_type(int pbe_type, int pbe_nid, int cipher_nid, int md_nid, EVP_PBE_KEYGEN *keygen); int EVP_PBE_alg_add(int nid, const EVP_CIPHER *cipher, const EVP_MD *md, EVP_PBE_KEYGEN *keygen); int EVP_PBE_find(int type, int pbe_nid, int *pcnid, int *pmnid, EVP_PBE_KEYGEN **pkeygen); void EVP_PBE_cleanup(void); # define ASN1_PKEY_ALIAS 0x1 # define ASN1_PKEY_DYNAMIC 0x2 # define ASN1_PKEY_SIGPARAM_NULL 0x4 # define ASN1_PKEY_CTRL_PKCS7_SIGN 0x1 # define ASN1_PKEY_CTRL_PKCS7_ENCRYPT 0x2 # define ASN1_PKEY_CTRL_DEFAULT_MD_NID 0x3 # define ASN1_PKEY_CTRL_CMS_SIGN 0x5 # define ASN1_PKEY_CTRL_CMS_ENVELOPE 0x7 # define ASN1_PKEY_CTRL_CMS_RI_TYPE 0x8 int EVP_PKEY_asn1_get_count(void); const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_get0(int idx); const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_find(ENGINE **pe, int type); const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_find_str(ENGINE **pe, const char *str, int len); int EVP_PKEY_asn1_add0(const EVP_PKEY_ASN1_METHOD *ameth); int EVP_PKEY_asn1_add_alias(int to, int from); int EVP_PKEY_asn1_get0_info(int *ppkey_id, int *pkey_base_id, int *ppkey_flags, const char **pinfo, const char **ppem_str, const EVP_PKEY_ASN1_METHOD *ameth); const EVP_PKEY_ASN1_METHOD *EVP_PKEY_get0_asn1(EVP_PKEY *pkey); EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_new(int id, int flags, const char *pem_str, const char *info); void EVP_PKEY_asn1_copy(EVP_PKEY_ASN1_METHOD *dst, const EVP_PKEY_ASN1_METHOD *src); void EVP_PKEY_asn1_free(EVP_PKEY_ASN1_METHOD *ameth); void EVP_PKEY_asn1_set_public(EVP_PKEY_ASN1_METHOD *ameth, int (*pub_decode) (EVP_PKEY *pk, X509_PUBKEY *pub), int (*pub_encode) (X509_PUBKEY *pub, const EVP_PKEY *pk), int (*pub_cmp) (const EVP_PKEY *a, const EVP_PKEY *b), int (*pub_print) (BIO *out, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx), int (*pkey_size) (const EVP_PKEY *pk), int (*pkey_bits) (const EVP_PKEY *pk)); void EVP_PKEY_asn1_set_private(EVP_PKEY_ASN1_METHOD *ameth, int (*priv_decode) (EVP_PKEY *pk, PKCS8_PRIV_KEY_INFO *p8inf), int (*priv_encode) (PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pk), int (*priv_print) (BIO *out, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx)); void EVP_PKEY_asn1_set_param(EVP_PKEY_ASN1_METHOD *ameth, int (*param_decode) (EVP_PKEY *pkey, const unsigned char **pder, int derlen), int (*param_encode) (const EVP_PKEY *pkey, unsigned char **pder), int (*param_missing) (const EVP_PKEY *pk), int (*param_copy) (EVP_PKEY *to, const EVP_PKEY *from), int (*param_cmp) (const EVP_PKEY *a, const EVP_PKEY *b), int (*param_print) (BIO *out, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx)); void EVP_PKEY_asn1_set_free(EVP_PKEY_ASN1_METHOD *ameth, void (*pkey_free) (EVP_PKEY *pkey)); void EVP_PKEY_asn1_set_ctrl(EVP_PKEY_ASN1_METHOD *ameth, int (*pkey_ctrl) (EVP_PKEY *pkey, int op, long arg1, void *arg2)); void EVP_PKEY_asn1_set_item(EVP_PKEY_ASN1_METHOD *ameth, int (*item_verify) (EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn, X509_ALGOR *a, ASN1_BIT_STRING *sig, EVP_PKEY *pkey), int (*item_sign) (EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn, X509_ALGOR *alg1, X509_ALGOR *alg2, ASN1_BIT_STRING *sig)); # define EVP_PKEY_OP_UNDEFINED 0 # define EVP_PKEY_OP_PARAMGEN (1<<1) # define EVP_PKEY_OP_KEYGEN (1<<2) # define EVP_PKEY_OP_SIGN (1<<3) # define EVP_PKEY_OP_VERIFY (1<<4) # define EVP_PKEY_OP_VERIFYRECOVER (1<<5) # define EVP_PKEY_OP_SIGNCTX (1<<6) # define EVP_PKEY_OP_VERIFYCTX (1<<7) # define EVP_PKEY_OP_ENCRYPT (1<<8) # define EVP_PKEY_OP_DECRYPT (1<<9) # define EVP_PKEY_OP_DERIVE (1<<10) # define EVP_PKEY_OP_TYPE_SIG \ (EVP_PKEY_OP_SIGN | EVP_PKEY_OP_VERIFY | EVP_PKEY_OP_VERIFYRECOVER \ | EVP_PKEY_OP_SIGNCTX | EVP_PKEY_OP_VERIFYCTX) # define EVP_PKEY_OP_TYPE_CRYPT \ (EVP_PKEY_OP_ENCRYPT | EVP_PKEY_OP_DECRYPT) # define EVP_PKEY_OP_TYPE_NOGEN \ (EVP_PKEY_OP_SIG | EVP_PKEY_OP_CRYPT | EVP_PKEY_OP_DERIVE) # define EVP_PKEY_OP_TYPE_GEN \ (EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN) # define EVP_PKEY_CTX_set_signature_md(ctx, md) \ EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_TYPE_SIG, \ EVP_PKEY_CTRL_MD, 0, (void *)md) # define EVP_PKEY_CTX_get_signature_md(ctx, pmd) \ EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_TYPE_SIG, \ EVP_PKEY_CTRL_GET_MD, 0, (void *)pmd) # define EVP_PKEY_CTRL_MD 1 # define EVP_PKEY_CTRL_PEER_KEY 2 # define EVP_PKEY_CTRL_PKCS7_ENCRYPT 3 # define EVP_PKEY_CTRL_PKCS7_DECRYPT 4 # define EVP_PKEY_CTRL_PKCS7_SIGN 5 # define EVP_PKEY_CTRL_SET_MAC_KEY 6 # define EVP_PKEY_CTRL_DIGESTINIT 7 /* Used by GOST key encryption in TLS */ # define EVP_PKEY_CTRL_SET_IV 8 # define EVP_PKEY_CTRL_CMS_ENCRYPT 9 # define EVP_PKEY_CTRL_CMS_DECRYPT 10 # define EVP_PKEY_CTRL_CMS_SIGN 11 # define EVP_PKEY_CTRL_CIPHER 12 # define EVP_PKEY_CTRL_GET_MD 13 # define EVP_PKEY_ALG_CTRL 0x1000 # define EVP_PKEY_FLAG_AUTOARGLEN 2 /* * Method handles all operations: don't assume any digest related defaults. */ # define EVP_PKEY_FLAG_SIGCTX_CUSTOM 4 const EVP_PKEY_METHOD *EVP_PKEY_meth_find(int type); EVP_PKEY_METHOD *EVP_PKEY_meth_new(int id, int flags); void EVP_PKEY_meth_get0_info(int *ppkey_id, int *pflags, const EVP_PKEY_METHOD *meth); void EVP_PKEY_meth_copy(EVP_PKEY_METHOD *dst, const EVP_PKEY_METHOD *src); void EVP_PKEY_meth_free(EVP_PKEY_METHOD *pmeth); int EVP_PKEY_meth_add0(const EVP_PKEY_METHOD *pmeth); EVP_PKEY_CTX *EVP_PKEY_CTX_new(EVP_PKEY *pkey, ENGINE *e); EVP_PKEY_CTX *EVP_PKEY_CTX_new_id(int id, ENGINE *e); EVP_PKEY_CTX *EVP_PKEY_CTX_dup(EVP_PKEY_CTX *ctx); void EVP_PKEY_CTX_free(EVP_PKEY_CTX *ctx); int EVP_PKEY_CTX_ctrl(EVP_PKEY_CTX *ctx, int keytype, int optype, int cmd, int p1, void *p2); int EVP_PKEY_CTX_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, const char *value); int EVP_PKEY_CTX_get_operation(EVP_PKEY_CTX *ctx); void EVP_PKEY_CTX_set0_keygen_info(EVP_PKEY_CTX *ctx, int *dat, int datlen); EVP_PKEY *EVP_PKEY_new_mac_key(int type, ENGINE *e, const unsigned char *key, int keylen); void EVP_PKEY_CTX_set_data(EVP_PKEY_CTX *ctx, void *data); void *EVP_PKEY_CTX_get_data(EVP_PKEY_CTX *ctx); EVP_PKEY *EVP_PKEY_CTX_get0_pkey(EVP_PKEY_CTX *ctx); EVP_PKEY *EVP_PKEY_CTX_get0_peerkey(EVP_PKEY_CTX *ctx); void EVP_PKEY_CTX_set_app_data(EVP_PKEY_CTX *ctx, void *data); void *EVP_PKEY_CTX_get_app_data(EVP_PKEY_CTX *ctx); int EVP_PKEY_sign_init(EVP_PKEY_CTX *ctx); int EVP_PKEY_sign(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, const unsigned char *tbs, size_t tbslen); int EVP_PKEY_verify_init(EVP_PKEY_CTX *ctx); int EVP_PKEY_verify(EVP_PKEY_CTX *ctx, const unsigned char *sig, size_t siglen, const unsigned char *tbs, size_t tbslen); int EVP_PKEY_verify_recover_init(EVP_PKEY_CTX *ctx); int EVP_PKEY_verify_recover(EVP_PKEY_CTX *ctx, unsigned char *rout, size_t *routlen, const unsigned char *sig, size_t siglen); int EVP_PKEY_encrypt_init(EVP_PKEY_CTX *ctx); int EVP_PKEY_encrypt(EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, const unsigned char *in, size_t inlen); int EVP_PKEY_decrypt_init(EVP_PKEY_CTX *ctx); int EVP_PKEY_decrypt(EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, const unsigned char *in, size_t inlen); int EVP_PKEY_derive_init(EVP_PKEY_CTX *ctx); int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *ctx, EVP_PKEY *peer); int EVP_PKEY_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen); typedef int EVP_PKEY_gen_cb (EVP_PKEY_CTX *ctx); int EVP_PKEY_paramgen_init(EVP_PKEY_CTX *ctx); int EVP_PKEY_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY **ppkey); int EVP_PKEY_keygen_init(EVP_PKEY_CTX *ctx); int EVP_PKEY_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY **ppkey); void EVP_PKEY_CTX_set_cb(EVP_PKEY_CTX *ctx, EVP_PKEY_gen_cb *cb); EVP_PKEY_gen_cb *EVP_PKEY_CTX_get_cb(EVP_PKEY_CTX *ctx); int EVP_PKEY_CTX_get_keygen_info(EVP_PKEY_CTX *ctx, int idx); void EVP_PKEY_meth_set_init(EVP_PKEY_METHOD *pmeth, int (*init) (EVP_PKEY_CTX *ctx)); void EVP_PKEY_meth_set_copy(EVP_PKEY_METHOD *pmeth, int (*copy) (EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src)); void EVP_PKEY_meth_set_cleanup(EVP_PKEY_METHOD *pmeth, void (*cleanup) (EVP_PKEY_CTX *ctx)); 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)); 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)); 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)); 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)); 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)); 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)); 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)); 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)); 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)); 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)); 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)); +void EVP_PKEY_meth_get_init(EVP_PKEY_METHOD *pmeth, + int (**pinit) (EVP_PKEY_CTX *ctx)); + +void EVP_PKEY_meth_get_copy(EVP_PKEY_METHOD *pmeth, + int (**pcopy) (EVP_PKEY_CTX *dst, + EVP_PKEY_CTX *src)); + +void EVP_PKEY_meth_get_cleanup(EVP_PKEY_METHOD *pmeth, + void (**pcleanup) (EVP_PKEY_CTX *ctx)); + +void EVP_PKEY_meth_get_paramgen(EVP_PKEY_METHOD *pmeth, + int (**pparamgen_init) (EVP_PKEY_CTX *ctx), + int (**pparamgen) (EVP_PKEY_CTX *ctx, + EVP_PKEY *pkey)); + +void EVP_PKEY_meth_get_keygen(EVP_PKEY_METHOD *pmeth, + int (**pkeygen_init) (EVP_PKEY_CTX *ctx), + int (**pkeygen) (EVP_PKEY_CTX *ctx, + EVP_PKEY *pkey)); + +void EVP_PKEY_meth_get_sign(EVP_PKEY_METHOD *pmeth, + int (**psign_init) (EVP_PKEY_CTX *ctx), + int (**psign) (EVP_PKEY_CTX *ctx, + unsigned char *sig, size_t *siglen, + const unsigned char *tbs, + size_t tbslen)); + +void EVP_PKEY_meth_get_verify(EVP_PKEY_METHOD *pmeth, + int (**pverify_init) (EVP_PKEY_CTX *ctx), + int (**pverify) (EVP_PKEY_CTX *ctx, + const unsigned char *sig, + size_t siglen, + const unsigned char *tbs, + size_t tbslen)); + +void EVP_PKEY_meth_get_verify_recover(EVP_PKEY_METHOD *pmeth, + int (**pverify_recover_init) (EVP_PKEY_CTX + *ctx), + int (**pverify_recover) (EVP_PKEY_CTX + *ctx, + unsigned char + *sig, + size_t *siglen, + const unsigned + char *tbs, + size_t tbslen)); + +void EVP_PKEY_meth_get_signctx(EVP_PKEY_METHOD *pmeth, + int (**psignctx_init) (EVP_PKEY_CTX *ctx, + EVP_MD_CTX *mctx), + int (**psignctx) (EVP_PKEY_CTX *ctx, + unsigned char *sig, + size_t *siglen, + EVP_MD_CTX *mctx)); + +void EVP_PKEY_meth_get_verifyctx(EVP_PKEY_METHOD *pmeth, + int (**pverifyctx_init) (EVP_PKEY_CTX *ctx, + EVP_MD_CTX *mctx), + int (**pverifyctx) (EVP_PKEY_CTX *ctx, + const unsigned char *sig, + int siglen, + EVP_MD_CTX *mctx)); + +void EVP_PKEY_meth_get_encrypt(EVP_PKEY_METHOD *pmeth, + int (**pencrypt_init) (EVP_PKEY_CTX *ctx), + int (**pencryptfn) (EVP_PKEY_CTX *ctx, + unsigned char *out, + size_t *outlen, + const unsigned char *in, + size_t inlen)); + +void EVP_PKEY_meth_get_decrypt(EVP_PKEY_METHOD *pmeth, + int (**pdecrypt_init) (EVP_PKEY_CTX *ctx), + int (**pdecrypt) (EVP_PKEY_CTX *ctx, + unsigned char *out, + size_t *outlen, + const unsigned char *in, + size_t inlen)); + +void EVP_PKEY_meth_get_derive(EVP_PKEY_METHOD *pmeth, + int (**pderive_init) (EVP_PKEY_CTX *ctx), + int (**pderive) (EVP_PKEY_CTX *ctx, + unsigned char *key, + size_t *keylen)); + +void EVP_PKEY_meth_get_ctrl(EVP_PKEY_METHOD *pmeth, + int (**pctrl) (EVP_PKEY_CTX *ctx, int type, int p1, + void *p2), + int (**pctrl_str) (EVP_PKEY_CTX *ctx, + const char *type, + const char *value)); + void EVP_add_alg_module(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_EVP_strings(void); /* Error codes for the EVP functions. */ /* Function codes. */ # define EVP_F_AESNI_INIT_KEY 165 # define EVP_F_AESNI_XTS_CIPHER 176 # define EVP_F_AES_INIT_KEY 133 # define EVP_F_AES_T4_INIT_KEY 178 # define EVP_F_AES_XTS 172 # define EVP_F_AES_XTS_CIPHER 175 # define EVP_F_ALG_MODULE_INIT 177 # define EVP_F_CAMELLIA_INIT_KEY 159 # define EVP_F_CMAC_INIT 173 # define EVP_F_CMLL_T4_INIT_KEY 179 # define EVP_F_D2I_PKEY 100 # define EVP_F_DO_SIGVER_INIT 161 # define EVP_F_DSAPKEY2PKCS8 134 # define EVP_F_DSA_PKEY2PKCS8 135 # define EVP_F_ECDSA_PKEY2PKCS8 129 # define EVP_F_ECKEY_PKEY2PKCS8 132 # define EVP_F_EVP_CIPHERINIT_EX 123 # define EVP_F_EVP_CIPHER_CTX_COPY 163 # define EVP_F_EVP_CIPHER_CTX_CTRL 124 # define EVP_F_EVP_CIPHER_CTX_SET_KEY_LENGTH 122 # define EVP_F_EVP_DECRYPTFINAL_EX 101 # define EVP_F_EVP_DIGESTINIT_EX 128 # define EVP_F_EVP_ENCRYPTFINAL_EX 127 # define EVP_F_EVP_MD_CTX_COPY_EX 110 # define EVP_F_EVP_MD_SIZE 162 # define EVP_F_EVP_OPENINIT 102 # define EVP_F_EVP_PBE_ALG_ADD 115 # define EVP_F_EVP_PBE_ALG_ADD_TYPE 160 # define EVP_F_EVP_PBE_CIPHERINIT 116 # define EVP_F_EVP_PKCS82PKEY 111 # define EVP_F_EVP_PKCS82PKEY_BROKEN 136 # define EVP_F_EVP_PKEY2PKCS8_BROKEN 113 # define EVP_F_EVP_PKEY_COPY_PARAMETERS 103 # define EVP_F_EVP_PKEY_CTX_CTRL 137 # define EVP_F_EVP_PKEY_CTX_CTRL_STR 150 # define EVP_F_EVP_PKEY_CTX_DUP 156 # define EVP_F_EVP_PKEY_DECRYPT 104 # define EVP_F_EVP_PKEY_DECRYPT_INIT 138 # define EVP_F_EVP_PKEY_DECRYPT_OLD 151 # define EVP_F_EVP_PKEY_DERIVE 153 # define EVP_F_EVP_PKEY_DERIVE_INIT 154 # define EVP_F_EVP_PKEY_DERIVE_SET_PEER 155 # define EVP_F_EVP_PKEY_ENCRYPT 105 # define EVP_F_EVP_PKEY_ENCRYPT_INIT 139 # define EVP_F_EVP_PKEY_ENCRYPT_OLD 152 # define EVP_F_EVP_PKEY_GET1_DH 119 # define EVP_F_EVP_PKEY_GET1_DSA 120 # define EVP_F_EVP_PKEY_GET1_ECDSA 130 # define EVP_F_EVP_PKEY_GET1_EC_KEY 131 # define EVP_F_EVP_PKEY_GET1_RSA 121 # define EVP_F_EVP_PKEY_KEYGEN 146 # define EVP_F_EVP_PKEY_KEYGEN_INIT 147 # define EVP_F_EVP_PKEY_NEW 106 # define EVP_F_EVP_PKEY_PARAMGEN 148 # define EVP_F_EVP_PKEY_PARAMGEN_INIT 149 # define EVP_F_EVP_PKEY_SIGN 140 # define EVP_F_EVP_PKEY_SIGN_INIT 141 # define EVP_F_EVP_PKEY_VERIFY 142 # define EVP_F_EVP_PKEY_VERIFY_INIT 143 # define EVP_F_EVP_PKEY_VERIFY_RECOVER 144 # define EVP_F_EVP_PKEY_VERIFY_RECOVER_INIT 145 # define EVP_F_EVP_RIJNDAEL 126 # define EVP_F_EVP_SIGNFINAL 107 # define EVP_F_EVP_VERIFYFINAL 108 # define EVP_F_FIPS_CIPHERINIT 166 # define EVP_F_FIPS_CIPHER_CTX_COPY 170 # define EVP_F_FIPS_CIPHER_CTX_CTRL 167 # define EVP_F_FIPS_CIPHER_CTX_SET_KEY_LENGTH 171 # define EVP_F_FIPS_DIGESTINIT 168 # define EVP_F_FIPS_MD_CTX_COPY 169 # define EVP_F_HMAC_INIT_EX 174 # define EVP_F_INT_CTX_NEW 157 # define EVP_F_PKCS5_PBE_KEYIVGEN 117 # define EVP_F_PKCS5_V2_PBE_KEYIVGEN 118 # define EVP_F_PKCS5_V2_PBKDF2_KEYIVGEN 164 # define EVP_F_PKCS8_SET_BROKEN 112 # define EVP_F_PKEY_SET_TYPE 158 # define EVP_F_RC2_MAGIC_TO_METH 109 # define EVP_F_RC5_CTRL 125 /* Reason codes. */ # define EVP_R_AES_IV_SETUP_FAILED 162 # define EVP_R_AES_KEY_SETUP_FAILED 143 # define EVP_R_ASN1_LIB 140 # define EVP_R_BAD_BLOCK_LENGTH 136 # define EVP_R_BAD_DECRYPT 100 # define EVP_R_BAD_KEY_LENGTH 137 # define EVP_R_BN_DECODE_ERROR 112 # define EVP_R_BN_PUBKEY_ERROR 113 # define EVP_R_BUFFER_TOO_SMALL 155 # define EVP_R_CAMELLIA_KEY_SETUP_FAILED 157 # define EVP_R_CIPHER_PARAMETER_ERROR 122 # define EVP_R_COMMAND_NOT_SUPPORTED 147 # define EVP_R_CTRL_NOT_IMPLEMENTED 132 # define EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED 133 # define EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH 138 # define EVP_R_DECODE_ERROR 114 # define EVP_R_DIFFERENT_KEY_TYPES 101 # define EVP_R_DIFFERENT_PARAMETERS 153 # define EVP_R_DISABLED_FOR_FIPS 163 # define EVP_R_ENCODE_ERROR 115 # define EVP_R_ERROR_LOADING_SECTION 165 # define EVP_R_ERROR_SETTING_FIPS_MODE 166 # define EVP_R_EVP_PBE_CIPHERINIT_ERROR 119 # define EVP_R_EXPECTING_AN_RSA_KEY 127 # define EVP_R_EXPECTING_A_DH_KEY 128 # define EVP_R_EXPECTING_A_DSA_KEY 129 # define EVP_R_EXPECTING_A_ECDSA_KEY 141 # define EVP_R_EXPECTING_A_EC_KEY 142 # define EVP_R_FIPS_MODE_NOT_SUPPORTED 167 # define EVP_R_INITIALIZATION_ERROR 134 # define EVP_R_INPUT_NOT_INITIALIZED 111 # define EVP_R_INVALID_DIGEST 152 # define EVP_R_INVALID_FIPS_MODE 168 # define EVP_R_INVALID_KEY 171 # define EVP_R_INVALID_KEY_LENGTH 130 # define EVP_R_INVALID_OPERATION 148 # define EVP_R_IV_TOO_LARGE 102 # define EVP_R_KEYGEN_FAILURE 120 # define EVP_R_MESSAGE_DIGEST_IS_NULL 159 # define EVP_R_METHOD_NOT_SUPPORTED 144 # define EVP_R_MISSING_PARAMETERS 103 # define EVP_R_NO_CIPHER_SET 131 # define EVP_R_NO_DEFAULT_DIGEST 158 # define EVP_R_NO_DIGEST_SET 139 # define EVP_R_NO_DSA_PARAMETERS 116 # define EVP_R_NO_KEY_SET 154 # define EVP_R_NO_OPERATION_SET 149 # define EVP_R_NO_SIGN_FUNCTION_CONFIGURED 104 # define EVP_R_NO_VERIFY_FUNCTION_CONFIGURED 105 # define EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE 150 # define EVP_R_OPERATON_NOT_INITIALIZED 151 # define EVP_R_PKCS8_UNKNOWN_BROKEN_TYPE 117 # define EVP_R_PRIVATE_KEY_DECODE_ERROR 145 # define EVP_R_PRIVATE_KEY_ENCODE_ERROR 146 # define EVP_R_PUBLIC_KEY_NOT_RSA 106 # define EVP_R_TOO_LARGE 164 # define EVP_R_UNKNOWN_CIPHER 160 # define EVP_R_UNKNOWN_DIGEST 161 # define EVP_R_UNKNOWN_OPTION 169 # define EVP_R_UNKNOWN_PBE_ALGORITHM 121 # define EVP_R_UNSUPORTED_NUMBER_OF_ROUNDS 135 # define EVP_R_UNSUPPORTED_ALGORITHM 156 # define EVP_R_UNSUPPORTED_CIPHER 107 # define EVP_R_UNSUPPORTED_KEYLENGTH 123 # define EVP_R_UNSUPPORTED_KEY_DERIVATION_FUNCTION 124 # define EVP_R_UNSUPPORTED_KEY_SIZE 108 # define EVP_R_UNSUPPORTED_PRF 125 # define EVP_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM 118 # define EVP_R_UNSUPPORTED_SALT_TYPE 126 # define EVP_R_WRAP_MODE_NOT_ALLOWED 170 # define EVP_R_WRONG_FINAL_BLOCK_LENGTH 109 # define EVP_R_WRONG_PUBLIC_KEY_TYPE 110 # ifdef __cplusplus } # endif #endif Index: vendor-crypto/openssl/dist/crypto/evp/evp_key.c =================================================================== --- vendor-crypto/openssl/dist/crypto/evp/evp_key.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/evp/evp_key.c (revision 325326) @@ -1,195 +1,197 @@ /* crypto/evp/evp_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.] */ #include #include "cryptlib.h" #include #include #include #include /* should be init to zeros. */ static char prompt_string[80]; void EVP_set_pw_prompt(const char *prompt) { if (prompt == NULL) prompt_string[0] = '\0'; else { strncpy(prompt_string, prompt, 79); prompt_string[79] = '\0'; } } char *EVP_get_pw_prompt(void) { if (prompt_string[0] == '\0') return (NULL); else return (prompt_string); } /* * For historical reasons, the standard function for reading passwords is in * the DES library -- if someone ever wants to disable DES, this function * will fail */ int EVP_read_pw_string(char *buf, int len, const char *prompt, int verify) { return EVP_read_pw_string_min(buf, 0, len, prompt, verify); } int EVP_read_pw_string_min(char *buf, int min, int len, const char *prompt, int verify) { - int ret; + int ret = -1; char buff[BUFSIZ]; UI *ui; if ((prompt == NULL) && (prompt_string[0] != '\0')) prompt = prompt_string; ui = UI_new(); if (ui == NULL) - return -1; - UI_add_input_string(ui, prompt, 0, buf, min, - (len >= BUFSIZ) ? BUFSIZ - 1 : len); - if (verify) - UI_add_verify_string(ui, prompt, 0, - buff, min, (len >= BUFSIZ) ? BUFSIZ - 1 : len, - buf); + return ret; + if (UI_add_input_string(ui, prompt, 0, buf, min, + (len >= BUFSIZ) ? BUFSIZ - 1 : len) < 0 + || (verify + && UI_add_verify_string(ui, prompt, 0, buff, min, + (len >= BUFSIZ) ? BUFSIZ - 1 : len, + buf) < 0)) + goto end; ret = UI_process(ui); - UI_free(ui); OPENSSL_cleanse(buff, BUFSIZ); + end: + UI_free(ui); return ret; } int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md, const unsigned char *salt, const unsigned char *data, int datal, int count, unsigned char *key, unsigned char *iv) { EVP_MD_CTX c; unsigned char md_buf[EVP_MAX_MD_SIZE]; int niv, nkey, addmd = 0; unsigned int mds = 0, i; int rv = 0; nkey = type->key_len; niv = type->iv_len; OPENSSL_assert(nkey <= EVP_MAX_KEY_LENGTH); OPENSSL_assert(niv <= EVP_MAX_IV_LENGTH); if (data == NULL) return (nkey); EVP_MD_CTX_init(&c); for (;;) { if (!EVP_DigestInit_ex(&c, md, NULL)) goto err; if (addmd++) if (!EVP_DigestUpdate(&c, &(md_buf[0]), mds)) goto err; if (!EVP_DigestUpdate(&c, data, datal)) goto err; if (salt != NULL) if (!EVP_DigestUpdate(&c, salt, PKCS5_SALT_LEN)) goto err; if (!EVP_DigestFinal_ex(&c, &(md_buf[0]), &mds)) goto err; for (i = 1; i < (unsigned int)count; i++) { if (!EVP_DigestInit_ex(&c, md, NULL)) goto err; if (!EVP_DigestUpdate(&c, &(md_buf[0]), mds)) goto err; if (!EVP_DigestFinal_ex(&c, &(md_buf[0]), &mds)) goto err; } i = 0; if (nkey) { for (;;) { if (nkey == 0) break; if (i == mds) break; if (key != NULL) *(key++) = md_buf[i]; nkey--; i++; } } if (niv && (i != mds)) { for (;;) { if (niv == 0) break; if (i == mds) break; if (iv != NULL) *(iv++) = md_buf[i]; niv--; i++; } } if ((nkey == 0) && (niv == 0)) break; } rv = type->key_len; err: EVP_MD_CTX_cleanup(&c); OPENSSL_cleanse(md_buf, sizeof(md_buf)); return rv; } Index: vendor-crypto/openssl/dist/crypto/evp/pmeth_lib.c =================================================================== --- vendor-crypto/openssl/dist/crypto/evp/pmeth_lib.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/evp/pmeth_lib.c (revision 325326) @@ -1,591 +1,758 @@ /* 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; } + +void EVP_PKEY_meth_get_init(EVP_PKEY_METHOD *pmeth, + int (**pinit) (EVP_PKEY_CTX *ctx)) +{ + *pinit = pmeth->init; +} + +void EVP_PKEY_meth_get_copy(EVP_PKEY_METHOD *pmeth, + int (**pcopy) (EVP_PKEY_CTX *dst, + EVP_PKEY_CTX *src)) +{ + *pcopy = pmeth->copy; +} + +void EVP_PKEY_meth_get_cleanup(EVP_PKEY_METHOD *pmeth, + void (**pcleanup) (EVP_PKEY_CTX *ctx)) +{ + *pcleanup = pmeth->cleanup; +} + +void EVP_PKEY_meth_get_paramgen(EVP_PKEY_METHOD *pmeth, + int (**pparamgen_init) (EVP_PKEY_CTX *ctx), + int (**pparamgen) (EVP_PKEY_CTX *ctx, + EVP_PKEY *pkey)) +{ + if (pparamgen_init) + *pparamgen_init = pmeth->paramgen_init; + if (pparamgen) + *pparamgen = pmeth->paramgen; +} + +void EVP_PKEY_meth_get_keygen(EVP_PKEY_METHOD *pmeth, + int (**pkeygen_init) (EVP_PKEY_CTX *ctx), + int (**pkeygen) (EVP_PKEY_CTX *ctx, + EVP_PKEY *pkey)) +{ + if (pkeygen_init) + *pkeygen_init = pmeth->keygen_init; + if (pkeygen) + *pkeygen = pmeth->keygen; +} + +void EVP_PKEY_meth_get_sign(EVP_PKEY_METHOD *pmeth, + int (**psign_init) (EVP_PKEY_CTX *ctx), + int (**psign) (EVP_PKEY_CTX *ctx, + unsigned char *sig, size_t *siglen, + const unsigned char *tbs, + size_t tbslen)) +{ + if (psign_init) + *psign_init = pmeth->sign_init; + if (psign) + *psign = pmeth->sign; +} + +void EVP_PKEY_meth_get_verify(EVP_PKEY_METHOD *pmeth, + int (**pverify_init) (EVP_PKEY_CTX *ctx), + int (**pverify) (EVP_PKEY_CTX *ctx, + const unsigned char *sig, + size_t siglen, + const unsigned char *tbs, + size_t tbslen)) +{ + if (pverify_init) + *pverify_init = pmeth->verify_init; + if (pverify) + *pverify = pmeth->verify; +} + +void EVP_PKEY_meth_get_verify_recover(EVP_PKEY_METHOD *pmeth, + int (**pverify_recover_init) (EVP_PKEY_CTX + *ctx), + int (**pverify_recover) (EVP_PKEY_CTX + *ctx, + unsigned char + *sig, + size_t *siglen, + const unsigned + char *tbs, + size_t tbslen)) +{ + if (pverify_recover_init) + *pverify_recover_init = pmeth->verify_recover_init; + if (pverify_recover) + *pverify_recover = pmeth->verify_recover; +} + +void EVP_PKEY_meth_get_signctx(EVP_PKEY_METHOD *pmeth, + int (**psignctx_init) (EVP_PKEY_CTX *ctx, + EVP_MD_CTX *mctx), + int (**psignctx) (EVP_PKEY_CTX *ctx, + unsigned char *sig, + size_t *siglen, + EVP_MD_CTX *mctx)) +{ + if (psignctx_init) + *psignctx_init = pmeth->signctx_init; + if (psignctx) + *psignctx = pmeth->signctx; +} + +void EVP_PKEY_meth_get_verifyctx(EVP_PKEY_METHOD *pmeth, + int (**pverifyctx_init) (EVP_PKEY_CTX *ctx, + EVP_MD_CTX *mctx), + int (**pverifyctx) (EVP_PKEY_CTX *ctx, + const unsigned char *sig, + int siglen, + EVP_MD_CTX *mctx)) +{ + if (pverifyctx_init) + *pverifyctx_init = pmeth->verifyctx_init; + if (pverifyctx) + *pverifyctx = pmeth->verifyctx; +} + +void EVP_PKEY_meth_get_encrypt(EVP_PKEY_METHOD *pmeth, + int (**pencrypt_init) (EVP_PKEY_CTX *ctx), + int (**pencryptfn) (EVP_PKEY_CTX *ctx, + unsigned char *out, + size_t *outlen, + const unsigned char *in, + size_t inlen)) +{ + if (pencrypt_init) + *pencrypt_init = pmeth->encrypt_init; + if (pencryptfn) + *pencryptfn = pmeth->encrypt; +} + +void EVP_PKEY_meth_get_decrypt(EVP_PKEY_METHOD *pmeth, + int (**pdecrypt_init) (EVP_PKEY_CTX *ctx), + int (**pdecrypt) (EVP_PKEY_CTX *ctx, + unsigned char *out, + size_t *outlen, + const unsigned char *in, + size_t inlen)) +{ + if (pdecrypt_init) + *pdecrypt_init = pmeth->decrypt_init; + if (pdecrypt) + *pdecrypt = pmeth->decrypt; +} + +void EVP_PKEY_meth_get_derive(EVP_PKEY_METHOD *pmeth, + int (**pderive_init) (EVP_PKEY_CTX *ctx), + int (**pderive) (EVP_PKEY_CTX *ctx, + unsigned char *key, + size_t *keylen)) +{ + if (pderive_init) + *pderive_init = pmeth->derive_init; + if (pderive) + *pderive = pmeth->derive; +} + +void EVP_PKEY_meth_get_ctrl(EVP_PKEY_METHOD *pmeth, + int (**pctrl) (EVP_PKEY_CTX *ctx, int type, int p1, + void *p2), + int (**pctrl_str) (EVP_PKEY_CTX *ctx, + const char *type, + const char *value)) +{ + if (pctrl) + *pctrl = pmeth->ctrl; + if (pctrl_str) + *pctrl_str = pmeth->ctrl_str; +} Index: vendor-crypto/openssl/dist/crypto/ex_data.c =================================================================== --- vendor-crypto/openssl/dist/crypto/ex_data.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/ex_data.c (revision 325326) @@ -1,653 +1,660 @@ /* 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 = 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; 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)) + /* + * Make sure the ex_data stack is at least |mx| elements long to avoid + * issues in the for loop that follows; so go get the |mx|'th element + * (if it does not exist CRYPTO_get_ex_data() returns NULL), and assign + * to itself. This is normally a no-op; but ensures the stack is the + * proper size + */ + if (!CRYPTO_set_ex_data(to, mx - 1, CRYPTO_get_ex_data(to, mx - 1))) 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) goto err; if ((item = def_get_class(class_index)) == NULL) 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); for (i = 0; i < mx; i++) { 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); f->free_func(obj, ptr, ad, i, f->argl, f->argp); } } 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/lhash/lhash.c =================================================================== --- vendor-crypto/openssl/dist/crypto/lhash/lhash.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/lhash/lhash.c (revision 325326) @@ -1,458 +1,477 @@ /* crypto/lhash/lhash.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.] */ /*- * Code for dynamic hash table routines * Author - Eric Young v 2.0 * * 2.2 eay - added #include "crypto.h" so the memory leak checking code is * present. eay 18-Jun-98 * * 2.1 eay - Added an 'error in last operation' flag. eay 6-May-98 * * 2.0 eay - Fixed a bug that occurred when using lh_delete * from inside lh_doall(). As entries were deleted, * the 'table' was 'contract()ed', making some entries * jump from the end of the table to the start, there by * skipping the lh_doall() processing. eay - 4/12/95 * * 1.9 eay - Fixed a memory leak in lh_free, the LHASH_NODEs * were not being free()ed. 21/11/95 * * 1.8 eay - Put the stats routines into a separate file, lh_stats.c * 19/09/95 * * 1.7 eay - Removed the fputs() for realloc failures - the code * should silently tolerate them. I have also fixed things * lint complained about 04/05/95 * * 1.6 eay - Fixed an invalid pointers in contract/expand 27/07/92 * * 1.5 eay - Fixed a misuse of realloc in expand 02/03/1992 * * 1.4 eay - Fixed lh_doall so the function can call lh_delete 28/05/91 * * 1.3 eay - Fixed a few lint problems 19/3/1991 * * 1.2 eay - Fixed lh_doall problem 13/3/1991 * * 1.1 eay - Added lh_doall * * 1.0 eay - First version */ #include #include #include #include #include +/* + * A hashing implementation that appears to be based on the linear hashing + * alogrithm: + * https://en.wikipedia.org/wiki/Linear_hashing + * + * Litwin, Witold (1980), "Linear hashing: A new tool for file and table + * addressing", Proc. 6th Conference on Very Large Databases: 212–223 + * http://hackthology.com/pdfs/Litwin-1980-Linear_Hashing.pdf + * + * From the wikipedia article "Linear hashing is used in the BDB Berkeley + * database system, which in turn is used by many software systems such as + * OpenLDAP, using a C implementation derived from the CACM article and first + * published on the Usenet in 1988 by Esmond Pitt." + * + * The CACM paper is available here: + * https://pdfs.semanticscholar.org/ff4d/1c5deca6269cc316bfd952172284dbf610ee.pdf + */ + const char lh_version[] = "lhash" OPENSSL_VERSION_PTEXT; #undef MIN_NODES #define MIN_NODES 16 #define UP_LOAD (2*LH_LOAD_MULT) /* load times 256 (default 2) */ #define DOWN_LOAD (LH_LOAD_MULT) /* load times 256 (default 1) */ -static void expand(_LHASH *lh); +static int expand(_LHASH *lh); static void contract(_LHASH *lh); static LHASH_NODE **getrn(_LHASH *lh, const void *data, unsigned long *rhash); _LHASH *lh_new(LHASH_HASH_FN_TYPE h, LHASH_COMP_FN_TYPE c) { _LHASH *ret; int i; if ((ret = OPENSSL_malloc(sizeof(_LHASH))) == NULL) goto err0; if ((ret->b = OPENSSL_malloc(sizeof(LHASH_NODE *) * MIN_NODES)) == NULL) goto err1; for (i = 0; i < MIN_NODES; i++) ret->b[i] = NULL; ret->comp = ((c == NULL) ? (LHASH_COMP_FN_TYPE)strcmp : c); ret->hash = ((h == NULL) ? (LHASH_HASH_FN_TYPE)lh_strhash : h); ret->num_nodes = MIN_NODES / 2; ret->num_alloc_nodes = MIN_NODES; ret->p = 0; ret->pmax = MIN_NODES / 2; ret->up_load = UP_LOAD; ret->down_load = DOWN_LOAD; ret->num_items = 0; ret->num_expands = 0; ret->num_expand_reallocs = 0; ret->num_contracts = 0; ret->num_contract_reallocs = 0; ret->num_hash_calls = 0; ret->num_comp_calls = 0; ret->num_insert = 0; ret->num_replace = 0; ret->num_delete = 0; ret->num_no_delete = 0; ret->num_retrieve = 0; ret->num_retrieve_miss = 0; ret->num_hash_comps = 0; ret->error = 0; return (ret); err1: OPENSSL_free(ret); err0: return (NULL); } void lh_free(_LHASH *lh) { unsigned int i; LHASH_NODE *n, *nn; if (lh == NULL) return; for (i = 0; i < lh->num_nodes; i++) { n = lh->b[i]; while (n != NULL) { nn = n->next; OPENSSL_free(n); n = nn; } } OPENSSL_free(lh->b); OPENSSL_free(lh); } void *lh_insert(_LHASH *lh, void *data) { unsigned long hash; LHASH_NODE *nn, **rn; void *ret; lh->error = 0; - if (lh->up_load <= (lh->num_items * LH_LOAD_MULT / lh->num_nodes)) - expand(lh); + if (lh->up_load <= (lh->num_items * LH_LOAD_MULT / lh->num_nodes) + && !expand(lh)) + return NULL; rn = getrn(lh, data, &hash); if (*rn == NULL) { if ((nn = (LHASH_NODE *)OPENSSL_malloc(sizeof(LHASH_NODE))) == NULL) { lh->error++; return (NULL); } nn->data = data; nn->next = NULL; #ifndef OPENSSL_NO_HASH_COMP nn->hash = hash; #endif *rn = nn; ret = NULL; lh->num_insert++; lh->num_items++; } else { /* replace same key */ ret = (*rn)->data; (*rn)->data = data; lh->num_replace++; } return (ret); } void *lh_delete(_LHASH *lh, const void *data) { unsigned long hash; LHASH_NODE *nn, **rn; void *ret; lh->error = 0; rn = getrn(lh, data, &hash); if (*rn == NULL) { lh->num_no_delete++; return (NULL); } else { nn = *rn; *rn = nn->next; ret = nn->data; OPENSSL_free(nn); lh->num_delete++; } lh->num_items--; if ((lh->num_nodes > MIN_NODES) && (lh->down_load >= (lh->num_items * LH_LOAD_MULT / lh->num_nodes))) contract(lh); return (ret); } void *lh_retrieve(_LHASH *lh, const void *data) { unsigned long hash; LHASH_NODE **rn; void *ret; lh->error = 0; rn = getrn(lh, data, &hash); if (*rn == NULL) { lh->num_retrieve_miss++; return (NULL); } else { ret = (*rn)->data; lh->num_retrieve++; } return (ret); } static void doall_util_fn(_LHASH *lh, int use_arg, LHASH_DOALL_FN_TYPE func, LHASH_DOALL_ARG_FN_TYPE func_arg, void *arg) { int i; LHASH_NODE *a, *n; if (lh == NULL) return; /* * reverse the order so we search from 'top to bottom' We were having * memory leaks otherwise */ for (i = lh->num_nodes - 1; i >= 0; i--) { a = lh->b[i]; while (a != NULL) { /* * 28/05/91 - eay - n added so items can be deleted via lh_doall */ /* * 22/05/08 - ben - eh? since a is not passed, this should not be * needed */ n = a->next; if (use_arg) func_arg(a->data, arg); else func(a->data); a = n; } } } void lh_doall(_LHASH *lh, LHASH_DOALL_FN_TYPE func) { doall_util_fn(lh, 0, func, (LHASH_DOALL_ARG_FN_TYPE)0, NULL); } void lh_doall_arg(_LHASH *lh, LHASH_DOALL_ARG_FN_TYPE func, void *arg) { doall_util_fn(lh, 1, (LHASH_DOALL_FN_TYPE)0, func, arg); } -static void expand(_LHASH *lh) +static int expand(_LHASH *lh) { LHASH_NODE **n, **n1, **n2, *np; - unsigned int p, i, j; - unsigned long hash, nni; + unsigned int p, pmax, nni, j; + unsigned long hash; + nni = lh->num_alloc_nodes; + p = lh->p; + pmax = lh->pmax; + if (p + 1 >= pmax) { + j = nni * 2; + n = OPENSSL_realloc(lh->b, (int)(sizeof(LHASH_NODE *) * j)); + if (n == NULL) { + lh->error++; + return 0; + } + lh->b = n; + memset(n + nni, 0, sizeof(*n) * (j - nni)); + lh->pmax = nni; + lh->num_alloc_nodes = j; + lh->num_expand_reallocs++; + lh->p = 0; + } else { + lh->p++; + } + lh->num_nodes++; lh->num_expands++; - p = (int)lh->p++; n1 = &(lh->b[p]); - n2 = &(lh->b[p + (int)lh->pmax]); - *n2 = NULL; /* 27/07/92 - eay - undefined pointer bug */ - nni = lh->num_alloc_nodes; + n2 = &(lh->b[p + pmax]); + *n2 = NULL; for (np = *n1; np != NULL;) { #ifndef OPENSSL_NO_HASH_COMP hash = np->hash; #else hash = lh->hash(np->data); lh->num_hash_calls++; #endif if ((hash % nni) != p) { /* move it */ *n1 = (*n1)->next; np->next = *n2; *n2 = np; } else n1 = &((*n1)->next); np = *n1; } - if ((lh->p) >= lh->pmax) { - j = (int)lh->num_alloc_nodes * 2; - n = (LHASH_NODE **)OPENSSL_realloc(lh->b, - (int)(sizeof(LHASH_NODE *) * j)); - if (n == NULL) { - lh->error++; - lh->num_nodes--; - lh->p = 0; - return; - } - /* else */ - for (i = (int)lh->num_alloc_nodes; i < j; i++) /* 26/02/92 eay */ - n[i] = NULL; /* 02/03/92 eay */ - lh->pmax = lh->num_alloc_nodes; - lh->num_alloc_nodes = j; - lh->num_expand_reallocs++; - lh->p = 0; - lh->b = n; - } + return 1; } static void contract(_LHASH *lh) { LHASH_NODE **n, *n1, *np; np = lh->b[lh->p + lh->pmax - 1]; lh->b[lh->p + lh->pmax - 1] = NULL; /* 24/07-92 - eay - weird but :-( */ if (lh->p == 0) { n = (LHASH_NODE **)OPENSSL_realloc(lh->b, (unsigned int)(sizeof(LHASH_NODE *) * lh->pmax)); if (n == NULL) { /* fputs("realloc error in lhash",stderr); */ lh->error++; return; } lh->num_contract_reallocs++; lh->num_alloc_nodes /= 2; lh->pmax /= 2; lh->p = lh->pmax - 1; lh->b = n; } else lh->p--; lh->num_nodes--; lh->num_contracts++; n1 = lh->b[(int)lh->p]; if (n1 == NULL) lh->b[(int)lh->p] = np; else { while (n1->next != NULL) n1 = n1->next; n1->next = np; } } static LHASH_NODE **getrn(_LHASH *lh, const void *data, unsigned long *rhash) { LHASH_NODE **ret, *n1; unsigned long hash, nn; LHASH_COMP_FN_TYPE cf; hash = (*(lh->hash)) (data); lh->num_hash_calls++; *rhash = hash; nn = hash % lh->pmax; if (nn < lh->p) nn = hash % lh->num_alloc_nodes; cf = lh->comp; ret = &(lh->b[(int)nn]); for (n1 = *ret; n1 != NULL; n1 = n1->next) { #ifndef OPENSSL_NO_HASH_COMP lh->num_hash_comps++; if (n1->hash != hash) { ret = &(n1->next); continue; } #endif lh->num_comp_calls++; if (cf(n1->data, data) == 0) break; ret = &(n1->next); } return (ret); } /* * The following hash seems to work very well on normal text strings no * collisions on /usr/dict/words and it distributes on %2^n quite well, not * as good as MD5, but still good. */ unsigned long lh_strhash(const char *c) { unsigned long ret = 0; long n; unsigned long v; int r; if ((c == NULL) || (*c == '\0')) return (ret); /*- unsigned char b[16]; MD5(c,strlen(c),b); return(b[0]|(b[1]<<8)|(b[2]<<16)|(b[3]<<24)); */ n = 0x100; while (*c) { v = n | (*c); n += 0x100; r = (int)((v >> 2) ^ v) & 0x0f; ret = (ret << r) | (ret >> (32 - r)); ret &= 0xFFFFFFFFL; ret ^= v * v; c++; } return ((ret >> 16) ^ ret); } unsigned long lh_num_items(const _LHASH *lh) { return lh ? lh->num_items : 0; } Index: vendor-crypto/openssl/dist/crypto/ocsp/ocsp_vfy.c =================================================================== --- vendor-crypto/openssl/dist/crypto/ocsp/ocsp_vfy.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/ocsp/ocsp_vfy.c (revision 325326) @@ -1,454 +1,456 @@ /* ocsp_vfy.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 static int ocsp_find_signer(X509 **psigner, OCSP_BASICRESP *bs, STACK_OF(X509) *certs, X509_STORE *st, unsigned long flags); static X509 *ocsp_find_signer_sk(STACK_OF(X509) *certs, OCSP_RESPID *id); static int ocsp_check_issuer(OCSP_BASICRESP *bs, STACK_OF(X509) *chain, unsigned long flags); static int ocsp_check_ids(STACK_OF(OCSP_SINGLERESP) *sresp, OCSP_CERTID **ret); static int ocsp_match_issuerid(X509 *cert, OCSP_CERTID *cid, STACK_OF(OCSP_SINGLERESP) *sresp); static int ocsp_check_delegated(X509 *x, int flags); static int ocsp_req_find_signer(X509 **psigner, OCSP_REQUEST *req, X509_NAME *nm, STACK_OF(X509) *certs, X509_STORE *st, unsigned long flags); /* Verify a basic response message */ int OCSP_basic_verify(OCSP_BASICRESP *bs, STACK_OF(X509) *certs, X509_STORE *st, unsigned long flags) { X509 *signer, *x; STACK_OF(X509) *chain = NULL; STACK_OF(X509) *untrusted = NULL; X509_STORE_CTX ctx; int i, ret = 0; ret = ocsp_find_signer(&signer, bs, certs, st, flags); if (!ret) { OCSPerr(OCSP_F_OCSP_BASIC_VERIFY, OCSP_R_SIGNER_CERTIFICATE_NOT_FOUND); goto end; } if ((ret == 2) && (flags & OCSP_TRUSTOTHER)) flags |= OCSP_NOVERIFY; if (!(flags & OCSP_NOSIGS)) { EVP_PKEY *skey; skey = X509_get_pubkey(signer); if (skey) { ret = OCSP_BASICRESP_verify(bs, skey, 0); EVP_PKEY_free(skey); } if (!skey || ret <= 0) { OCSPerr(OCSP_F_OCSP_BASIC_VERIFY, OCSP_R_SIGNATURE_FAILURE); goto end; } } if (!(flags & OCSP_NOVERIFY)) { int init_res; if (flags & OCSP_NOCHAIN) { untrusted = NULL; } else if (bs->certs && certs) { untrusted = sk_X509_dup(bs->certs); for (i = 0; i < sk_X509_num(certs); i++) { if (!sk_X509_push(untrusted, sk_X509_value(certs, i))) { OCSPerr(OCSP_F_OCSP_BASIC_VERIFY, ERR_R_MALLOC_FAILURE); goto end; } } + } else if (certs != NULL) { + untrusted = certs; } else { untrusted = bs->certs; } init_res = X509_STORE_CTX_init(&ctx, st, signer, untrusted); if (!init_res) { ret = -1; OCSPerr(OCSP_F_OCSP_BASIC_VERIFY, ERR_R_X509_LIB); goto end; } X509_STORE_CTX_set_purpose(&ctx, X509_PURPOSE_OCSP_HELPER); ret = X509_verify_cert(&ctx); chain = X509_STORE_CTX_get1_chain(&ctx); X509_STORE_CTX_cleanup(&ctx); if (ret <= 0) { i = X509_STORE_CTX_get_error(&ctx); OCSPerr(OCSP_F_OCSP_BASIC_VERIFY, OCSP_R_CERTIFICATE_VERIFY_ERROR); ERR_add_error_data(2, "Verify error:", X509_verify_cert_error_string(i)); goto end; } if (flags & OCSP_NOCHECKS) { ret = 1; goto end; } /* * At this point we have a valid certificate chain need to verify it * against the OCSP issuer criteria. */ ret = ocsp_check_issuer(bs, chain, flags); /* If fatal error or valid match then finish */ if (ret != 0) goto end; /* * Easy case: explicitly trusted. Get root CA and check for explicit * trust */ if (flags & OCSP_NOEXPLICIT) goto end; x = sk_X509_value(chain, sk_X509_num(chain) - 1); if (X509_check_trust(x, NID_OCSP_sign, 0) != X509_TRUST_TRUSTED) { OCSPerr(OCSP_F_OCSP_BASIC_VERIFY, OCSP_R_ROOT_CA_NOT_TRUSTED); goto end; } ret = 1; } end: if (chain) sk_X509_pop_free(chain, X509_free); if (bs->certs && certs) sk_X509_free(untrusted); return ret; } static int ocsp_find_signer(X509 **psigner, OCSP_BASICRESP *bs, STACK_OF(X509) *certs, X509_STORE *st, unsigned long flags) { X509 *signer; OCSP_RESPID *rid = bs->tbsResponseData->responderId; if ((signer = ocsp_find_signer_sk(certs, rid))) { *psigner = signer; return 2; } if (!(flags & OCSP_NOINTERN) && (signer = ocsp_find_signer_sk(bs->certs, rid))) { *psigner = signer; return 1; } /* Maybe lookup from store if by subject name */ *psigner = NULL; return 0; } static X509 *ocsp_find_signer_sk(STACK_OF(X509) *certs, OCSP_RESPID *id) { int i; unsigned char tmphash[SHA_DIGEST_LENGTH], *keyhash; X509 *x; /* Easy if lookup by name */ if (id->type == V_OCSP_RESPID_NAME) return X509_find_by_subject(certs, id->value.byName); /* Lookup by key hash */ /* If key hash isn't SHA1 length then forget it */ if (id->value.byKey->length != SHA_DIGEST_LENGTH) return NULL; keyhash = id->value.byKey->data; /* Calculate hash of each key and compare */ for (i = 0; i < sk_X509_num(certs); i++) { x = sk_X509_value(certs, i); X509_pubkey_digest(x, EVP_sha1(), tmphash, NULL); if (!memcmp(keyhash, tmphash, SHA_DIGEST_LENGTH)) return x; } return NULL; } static int ocsp_check_issuer(OCSP_BASICRESP *bs, STACK_OF(X509) *chain, unsigned long flags) { STACK_OF(OCSP_SINGLERESP) *sresp; X509 *signer, *sca; OCSP_CERTID *caid = NULL; int i; sresp = bs->tbsResponseData->responses; if (sk_X509_num(chain) <= 0) { OCSPerr(OCSP_F_OCSP_CHECK_ISSUER, OCSP_R_NO_CERTIFICATES_IN_CHAIN); return -1; } /* See if the issuer IDs match. */ i = ocsp_check_ids(sresp, &caid); /* If ID mismatch or other error then return */ if (i <= 0) return i; signer = sk_X509_value(chain, 0); /* Check to see if OCSP responder CA matches request CA */ if (sk_X509_num(chain) > 1) { sca = sk_X509_value(chain, 1); i = ocsp_match_issuerid(sca, caid, sresp); if (i < 0) return i; if (i) { /* We have a match, if extensions OK then success */ if (ocsp_check_delegated(signer, flags)) return 1; return 0; } } /* Otherwise check if OCSP request signed directly by request CA */ return ocsp_match_issuerid(signer, caid, sresp); } /* * Check the issuer certificate IDs for equality. If there is a mismatch with * the same algorithm then there's no point trying to match any certificates * against the issuer. If the issuer IDs all match then we just need to check * equality against one of them. */ static int ocsp_check_ids(STACK_OF(OCSP_SINGLERESP) *sresp, OCSP_CERTID **ret) { OCSP_CERTID *tmpid, *cid; int i, idcount; idcount = sk_OCSP_SINGLERESP_num(sresp); if (idcount <= 0) { OCSPerr(OCSP_F_OCSP_CHECK_IDS, OCSP_R_RESPONSE_CONTAINS_NO_REVOCATION_DATA); return -1; } cid = sk_OCSP_SINGLERESP_value(sresp, 0)->certId; *ret = NULL; for (i = 1; i < idcount; i++) { tmpid = sk_OCSP_SINGLERESP_value(sresp, i)->certId; /* Check to see if IDs match */ if (OCSP_id_issuer_cmp(cid, tmpid)) { /* If algoritm mismatch let caller deal with it */ if (OBJ_cmp(tmpid->hashAlgorithm->algorithm, cid->hashAlgorithm->algorithm)) return 2; /* Else mismatch */ return 0; } } /* All IDs match: only need to check one ID */ *ret = cid; return 1; } static int ocsp_match_issuerid(X509 *cert, OCSP_CERTID *cid, STACK_OF(OCSP_SINGLERESP) *sresp) { /* If only one ID to match then do it */ if (cid) { const EVP_MD *dgst; X509_NAME *iname; int mdlen; unsigned char md[EVP_MAX_MD_SIZE]; if (!(dgst = EVP_get_digestbyobj(cid->hashAlgorithm->algorithm))) { OCSPerr(OCSP_F_OCSP_MATCH_ISSUERID, OCSP_R_UNKNOWN_MESSAGE_DIGEST); return -1; } mdlen = EVP_MD_size(dgst); if (mdlen < 0) return -1; if ((cid->issuerNameHash->length != mdlen) || (cid->issuerKeyHash->length != mdlen)) return 0; iname = X509_get_subject_name(cert); if (!X509_NAME_digest(iname, dgst, md, NULL)) return -1; if (memcmp(md, cid->issuerNameHash->data, mdlen)) return 0; X509_pubkey_digest(cert, dgst, md, NULL); if (memcmp(md, cid->issuerKeyHash->data, mdlen)) return 0; return 1; } else { /* We have to match the whole lot */ int i, ret; OCSP_CERTID *tmpid; for (i = 0; i < sk_OCSP_SINGLERESP_num(sresp); i++) { tmpid = sk_OCSP_SINGLERESP_value(sresp, i)->certId; ret = ocsp_match_issuerid(cert, tmpid, NULL); if (ret <= 0) return ret; } return 1; } } static int ocsp_check_delegated(X509 *x, int flags) { X509_check_purpose(x, -1, 0); if ((x->ex_flags & EXFLAG_XKUSAGE) && (x->ex_xkusage & XKU_OCSP_SIGN)) return 1; OCSPerr(OCSP_F_OCSP_CHECK_DELEGATED, OCSP_R_MISSING_OCSPSIGNING_USAGE); return 0; } /* * Verify an OCSP request. This is fortunately much easier than OCSP response * verify. Just find the signers certificate and verify it against a given * trust value. */ int OCSP_request_verify(OCSP_REQUEST *req, STACK_OF(X509) *certs, X509_STORE *store, unsigned long flags) { X509 *signer; X509_NAME *nm; GENERAL_NAME *gen; int ret; X509_STORE_CTX ctx; if (!req->optionalSignature) { OCSPerr(OCSP_F_OCSP_REQUEST_VERIFY, OCSP_R_REQUEST_NOT_SIGNED); return 0; } gen = req->tbsRequest->requestorName; if (!gen || gen->type != GEN_DIRNAME) { OCSPerr(OCSP_F_OCSP_REQUEST_VERIFY, OCSP_R_UNSUPPORTED_REQUESTORNAME_TYPE); return 0; } nm = gen->d.directoryName; ret = ocsp_req_find_signer(&signer, req, nm, certs, store, flags); if (ret <= 0) { OCSPerr(OCSP_F_OCSP_REQUEST_VERIFY, OCSP_R_SIGNER_CERTIFICATE_NOT_FOUND); return 0; } if ((ret == 2) && (flags & OCSP_TRUSTOTHER)) flags |= OCSP_NOVERIFY; if (!(flags & OCSP_NOSIGS)) { EVP_PKEY *skey; skey = X509_get_pubkey(signer); ret = OCSP_REQUEST_verify(req, skey); EVP_PKEY_free(skey); if (ret <= 0) { OCSPerr(OCSP_F_OCSP_REQUEST_VERIFY, OCSP_R_SIGNATURE_FAILURE); return 0; } } if (!(flags & OCSP_NOVERIFY)) { int init_res; if (flags & OCSP_NOCHAIN) init_res = X509_STORE_CTX_init(&ctx, store, signer, NULL); else init_res = X509_STORE_CTX_init(&ctx, store, signer, req->optionalSignature->certs); if (!init_res) { OCSPerr(OCSP_F_OCSP_REQUEST_VERIFY, ERR_R_X509_LIB); return 0; } X509_STORE_CTX_set_purpose(&ctx, X509_PURPOSE_OCSP_HELPER); X509_STORE_CTX_set_trust(&ctx, X509_TRUST_OCSP_REQUEST); ret = X509_verify_cert(&ctx); X509_STORE_CTX_cleanup(&ctx); if (ret <= 0) { ret = X509_STORE_CTX_get_error(&ctx); OCSPerr(OCSP_F_OCSP_REQUEST_VERIFY, OCSP_R_CERTIFICATE_VERIFY_ERROR); ERR_add_error_data(2, "Verify error:", X509_verify_cert_error_string(ret)); return 0; } } return 1; } static int ocsp_req_find_signer(X509 **psigner, OCSP_REQUEST *req, X509_NAME *nm, STACK_OF(X509) *certs, X509_STORE *st, unsigned long flags) { X509 *signer; if (!(flags & OCSP_NOINTERN)) { signer = X509_find_by_subject(req->optionalSignature->certs, nm); if (signer) { *psigner = signer; return 1; } } signer = X509_find_by_subject(certs, nm); if (signer) { *psigner = signer; return 2; } return 0; } Index: vendor-crypto/openssl/dist/crypto/opensslv.h =================================================================== --- vendor-crypto/openssl/dist/crypto/opensslv.h (revision 325325) +++ vendor-crypto/openssl/dist/crypto/opensslv.h (revision 325326) @@ -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 0x100020cfL +# define OPENSSL_VERSION_NUMBER 0x100020dfL # ifdef OPENSSL_FIPS -# define OPENSSL_VERSION_TEXT "OpenSSL 1.0.2l-fips 25 May 2017" +# define OPENSSL_VERSION_TEXT "OpenSSL 1.0.2m-fips 2 Nov 2017" # else -# define OPENSSL_VERSION_TEXT "OpenSSL 1.0.2l 25 May 2017" +# define OPENSSL_VERSION_TEXT "OpenSSL 1.0.2m 2 Nov 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/pem/pem_lib.c =================================================================== --- vendor-crypto/openssl/dist/crypto/pem/pem_lib.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/pem/pem_lib.c (revision 325326) @@ -1,871 +1,872 @@ /* crypto/pem/pem_lib.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 #include #include #include #include #include "asn1_locl.h" #ifndef OPENSSL_NO_DES # include #endif #ifndef OPENSSL_NO_ENGINE # include #endif const char PEM_version[] = "PEM" OPENSSL_VERSION_PTEXT; #define MIN_LENGTH 4 static int load_iv(char **fromp, unsigned char *to, int num); static int check_pem(const char *nm, const char *name); int pem_check_suffix(const char *pem_str, const char *suffix); int PEM_def_callback(char *buf, int num, int w, void *key) { #ifdef OPENSSL_NO_FP_API /* * We should not ever call the default callback routine from windows. */ PEMerr(PEM_F_PEM_DEF_CALLBACK, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return (-1); #else int i, j; const char *prompt; if (key) { i = strlen(key); i = (i > num) ? num : i; memcpy(buf, key, i); return (i); } prompt = EVP_get_pw_prompt(); if (prompt == NULL) prompt = "Enter PEM pass phrase:"; for (;;) { /* * We assume that w == 0 means decryption, * while w == 1 means encryption */ int min_len = w ? MIN_LENGTH : 0; i = EVP_read_pw_string_min(buf, min_len, num, prompt, w); if (i != 0) { PEMerr(PEM_F_PEM_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD); memset(buf, 0, (unsigned int)num); return (-1); } j = strlen(buf); if (min_len && j < min_len) { fprintf(stderr, "phrase is too short, needs to be at least %d chars\n", min_len); } else break; } return (j); #endif } void PEM_proc_type(char *buf, int type) { const char *str; if (type == PEM_TYPE_ENCRYPTED) str = "ENCRYPTED"; else if (type == PEM_TYPE_MIC_CLEAR) str = "MIC-CLEAR"; else if (type == PEM_TYPE_MIC_ONLY) str = "MIC-ONLY"; else str = "BAD-TYPE"; BUF_strlcat(buf, "Proc-Type: 4,", PEM_BUFSIZE); BUF_strlcat(buf, str, PEM_BUFSIZE); BUF_strlcat(buf, "\n", PEM_BUFSIZE); } void PEM_dek_info(char *buf, const char *type, int len, char *str) { static const unsigned char map[17] = "0123456789ABCDEF"; long i; int j; BUF_strlcat(buf, "DEK-Info: ", PEM_BUFSIZE); BUF_strlcat(buf, type, PEM_BUFSIZE); BUF_strlcat(buf, ",", PEM_BUFSIZE); j = strlen(buf); if (j + (len * 2) + 1 > PEM_BUFSIZE) return; for (i = 0; i < len; i++) { buf[j + i * 2] = map[(str[i] >> 4) & 0x0f]; buf[j + i * 2 + 1] = map[(str[i]) & 0x0f]; } buf[j + i * 2] = '\n'; buf[j + i * 2 + 1] = '\0'; } #ifndef OPENSSL_NO_FP_API void *PEM_ASN1_read(d2i_of_void *d2i, const char *name, FILE *fp, void **x, pem_password_cb *cb, void *u) { BIO *b; void *ret; if ((b = BIO_new(BIO_s_file())) == NULL) { PEMerr(PEM_F_PEM_ASN1_READ, ERR_R_BUF_LIB); return (0); } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = PEM_ASN1_read_bio(d2i, name, b, x, cb, u); BIO_free(b); return (ret); } #endif static int check_pem(const char *nm, const char *name) { /* Normal matching nm and name */ if (!strcmp(nm, name)) return 1; /* Make PEM_STRING_EVP_PKEY match any private key */ if (!strcmp(name, PEM_STRING_EVP_PKEY)) { int slen; const EVP_PKEY_ASN1_METHOD *ameth; if (!strcmp(nm, PEM_STRING_PKCS8)) return 1; if (!strcmp(nm, PEM_STRING_PKCS8INF)) return 1; slen = pem_check_suffix(nm, "PRIVATE KEY"); if (slen > 0) { /* * NB: ENGINE implementations wont contain a deprecated old * private key decode function so don't look for them. */ ameth = EVP_PKEY_asn1_find_str(NULL, nm, slen); if (ameth && ameth->old_priv_decode) return 1; } return 0; } if (!strcmp(name, PEM_STRING_PARAMETERS)) { int slen; const EVP_PKEY_ASN1_METHOD *ameth; slen = pem_check_suffix(nm, "PARAMETERS"); if (slen > 0) { ENGINE *e; ameth = EVP_PKEY_asn1_find_str(&e, nm, slen); if (ameth) { int r; if (ameth->param_decode) r = 1; else r = 0; #ifndef OPENSSL_NO_ENGINE if (e) ENGINE_finish(e); #endif return r; } } return 0; } /* If reading DH parameters handle X9.42 DH format too */ if (!strcmp(nm, PEM_STRING_DHXPARAMS) && !strcmp(name, PEM_STRING_DHPARAMS)) return 1; /* Permit older strings */ if (!strcmp(nm, PEM_STRING_X509_OLD) && !strcmp(name, PEM_STRING_X509)) return 1; if (!strcmp(nm, PEM_STRING_X509_REQ_OLD) && !strcmp(name, PEM_STRING_X509_REQ)) return 1; /* Allow normal certs to be read as trusted certs */ if (!strcmp(nm, PEM_STRING_X509) && !strcmp(name, PEM_STRING_X509_TRUSTED)) return 1; if (!strcmp(nm, PEM_STRING_X509_OLD) && !strcmp(name, PEM_STRING_X509_TRUSTED)) return 1; /* Some CAs use PKCS#7 with CERTIFICATE headers */ if (!strcmp(nm, PEM_STRING_X509) && !strcmp(name, PEM_STRING_PKCS7)) return 1; if (!strcmp(nm, PEM_STRING_PKCS7_SIGNED) && !strcmp(name, PEM_STRING_PKCS7)) return 1; #ifndef OPENSSL_NO_CMS if (!strcmp(nm, PEM_STRING_X509) && !strcmp(name, PEM_STRING_CMS)) return 1; /* Allow CMS to be read from PKCS#7 headers */ if (!strcmp(nm, PEM_STRING_PKCS7) && !strcmp(name, PEM_STRING_CMS)) return 1; #endif return 0; } int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm, const char *name, BIO *bp, pem_password_cb *cb, void *u) { EVP_CIPHER_INFO cipher; char *nm = NULL, *header = NULL; unsigned char *data = NULL; long len; int ret = 0; for (;;) { if (!PEM_read_bio(bp, &nm, &header, &data, &len)) { if (ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE) ERR_add_error_data(2, "Expecting: ", name); return 0; } if (check_pem(nm, name)) break; OPENSSL_free(nm); OPENSSL_free(header); OPENSSL_free(data); } if (!PEM_get_EVP_CIPHER_INFO(header, &cipher)) goto err; if (!PEM_do_header(&cipher, data, &len, cb, u)) goto err; *pdata = data; *plen = len; if (pnm) *pnm = nm; ret = 1; err: if (!ret || !pnm) OPENSSL_free(nm); OPENSSL_free(header); if (!ret) OPENSSL_free(data); return ret; } #ifndef OPENSSL_NO_FP_API int PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp, void *x, const EVP_CIPHER *enc, unsigned char *kstr, int klen, pem_password_cb *callback, void *u) { BIO *b; int ret; if ((b = BIO_new(BIO_s_file())) == NULL) { PEMerr(PEM_F_PEM_ASN1_WRITE, ERR_R_BUF_LIB); return (0); } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = PEM_ASN1_write_bio(i2d, name, b, x, enc, kstr, klen, callback, u); BIO_free(b); return (ret); } #endif int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp, void *x, const EVP_CIPHER *enc, unsigned char *kstr, int klen, pem_password_cb *callback, void *u) { EVP_CIPHER_CTX ctx; int dsize = 0, i, j, ret = 0; unsigned char *p, *data = NULL; const char *objstr = NULL; char buf[PEM_BUFSIZE]; unsigned char key[EVP_MAX_KEY_LENGTH]; unsigned char iv[EVP_MAX_IV_LENGTH]; if (enc != NULL) { objstr = OBJ_nid2sn(EVP_CIPHER_nid(enc)); if (objstr == NULL || EVP_CIPHER_iv_length(enc) == 0) { PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_UNSUPPORTED_CIPHER); goto err; } } if ((dsize = i2d(x, NULL)) < 0) { PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_ASN1_LIB); dsize = 0; goto err; } /* dzise + 8 bytes are needed */ /* actually it needs the cipher block size extra... */ data = (unsigned char *)OPENSSL_malloc((unsigned int)dsize + 20); if (data == NULL) { PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_MALLOC_FAILURE); goto err; } p = data; i = i2d(x, &p); if (enc != NULL) { if (kstr == NULL) { if (callback == NULL) klen = PEM_def_callback(buf, PEM_BUFSIZE, 1, u); else klen = (*callback) (buf, PEM_BUFSIZE, 1, u); if (klen <= 0) { PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_READ_KEY); goto err; } #ifdef CHARSET_EBCDIC /* Convert the pass phrase from EBCDIC */ ebcdic2ascii(buf, buf, klen); #endif kstr = (unsigned char *)buf; } RAND_add(data, i, 0); /* put in the RSA key. */ OPENSSL_assert(enc->iv_len <= (int)sizeof(iv)); if (RAND_bytes(iv, enc->iv_len) <= 0) /* Generate a salt */ goto err; /* * The 'iv' is used as the iv and as a salt. It is NOT taken from * the BytesToKey function */ if (!EVP_BytesToKey(enc, EVP_md5(), iv, kstr, klen, 1, key, NULL)) goto err; if (kstr == (unsigned char *)buf) OPENSSL_cleanse(buf, PEM_BUFSIZE); OPENSSL_assert(strlen(objstr) + 23 + 2 * enc->iv_len + 13 <= sizeof buf); buf[0] = '\0'; PEM_proc_type(buf, PEM_TYPE_ENCRYPTED); PEM_dek_info(buf, objstr, enc->iv_len, (char *)iv); /* k=strlen(buf); */ EVP_CIPHER_CTX_init(&ctx); ret = 1; if (!EVP_EncryptInit_ex(&ctx, enc, NULL, key, iv) || !EVP_EncryptUpdate(&ctx, data, &j, data, i) || !EVP_EncryptFinal_ex(&ctx, &(data[j]), &i)) ret = 0; EVP_CIPHER_CTX_cleanup(&ctx); if (ret == 0) goto err; i += j; } else { ret = 1; buf[0] = '\0'; } i = PEM_write_bio(bp, name, buf, data, i); if (i <= 0) ret = 0; err: OPENSSL_cleanse(key, sizeof(key)); OPENSSL_cleanse(iv, sizeof(iv)); OPENSSL_cleanse((char *)&ctx, sizeof(ctx)); OPENSSL_cleanse(buf, PEM_BUFSIZE); if (data != NULL) { OPENSSL_cleanse(data, (unsigned int)dsize); OPENSSL_free(data); } return (ret); } int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen, pem_password_cb *callback, void *u) { int i = 0, j, o, klen; long len; EVP_CIPHER_CTX ctx; unsigned char key[EVP_MAX_KEY_LENGTH]; char buf[PEM_BUFSIZE]; len = *plen; if (cipher->cipher == NULL) return (1); if (callback == NULL) klen = PEM_def_callback(buf, PEM_BUFSIZE, 0, u); else klen = callback(buf, PEM_BUFSIZE, 0, u); if (klen <= 0) { PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_PASSWORD_READ); return (0); } #ifdef CHARSET_EBCDIC /* Convert the pass phrase from EBCDIC */ ebcdic2ascii(buf, buf, klen); #endif if (!EVP_BytesToKey(cipher->cipher, EVP_md5(), &(cipher->iv[0]), (unsigned char *)buf, klen, 1, key, NULL)) return 0; j = (int)len; EVP_CIPHER_CTX_init(&ctx); o = EVP_DecryptInit_ex(&ctx, cipher->cipher, NULL, key, &(cipher->iv[0])); if (o) o = EVP_DecryptUpdate(&ctx, data, &i, data, j); if (o) o = EVP_DecryptFinal_ex(&ctx, &(data[i]), &j); EVP_CIPHER_CTX_cleanup(&ctx); OPENSSL_cleanse((char *)buf, sizeof(buf)); OPENSSL_cleanse((char *)key, sizeof(key)); if (o) j += i; else { PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_DECRYPT); return (0); } *plen = j; return (1); } int PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher) { const EVP_CIPHER *enc = NULL; char *p, c; char **header_pp = &header; cipher->cipher = NULL; if ((header == NULL) || (*header == '\0') || (*header == '\n')) return (1); if (strncmp(header, "Proc-Type: ", 11) != 0) { PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_PROC_TYPE); return (0); } header += 11; if (*header != '4') return (0); header++; if (*header != ',') return (0); header++; if (strncmp(header, "ENCRYPTED", 9) != 0) { PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_ENCRYPTED); return (0); } for (; (*header != '\n') && (*header != '\0'); header++) ; if (*header == '\0') { PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_SHORT_HEADER); return (0); } header++; if (strncmp(header, "DEK-Info: ", 10) != 0) { PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_DEK_INFO); return (0); } header += 10; p = header; for (;;) { c = *header; #ifndef CHARSET_EBCDIC if (!(((c >= 'A') && (c <= 'Z')) || (c == '-') || ((c >= '0') && (c <= '9')))) break; #else - if (!(isupper(c) || (c == '-') || isdigit(c))) + if (!(isupper((unsigned char)c) || (c == '-') + || isdigit((unsigned char)c))) break; #endif header++; } *header = '\0'; cipher->cipher = enc = EVP_get_cipherbyname(p); *header = c; header++; if (enc == NULL) { PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_UNSUPPORTED_ENCRYPTION); return (0); } if (!load_iv(header_pp, &(cipher->iv[0]), enc->iv_len)) return (0); return (1); } static int load_iv(char **fromp, unsigned char *to, int num) { int v, i; char *from; from = *fromp; for (i = 0; i < num; i++) to[i] = 0; num *= 2; for (i = 0; i < num; i++) { if ((*from >= '0') && (*from <= '9')) v = *from - '0'; else if ((*from >= 'A') && (*from <= 'F')) v = *from - 'A' + 10; else if ((*from >= 'a') && (*from <= 'f')) v = *from - 'a' + 10; else { PEMerr(PEM_F_LOAD_IV, PEM_R_BAD_IV_CHARS); return (0); } from++; to[i / 2] |= v << (long)((!(i & 1)) * 4); } *fromp = from; return (1); } #ifndef OPENSSL_NO_FP_API int PEM_write(FILE *fp, const char *name, const char *header, const unsigned char *data, long len) { BIO *b; int ret; if ((b = BIO_new(BIO_s_file())) == NULL) { PEMerr(PEM_F_PEM_WRITE, ERR_R_BUF_LIB); return (0); } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = PEM_write_bio(b, name, header, data, len); BIO_free(b); return (ret); } #endif int PEM_write_bio(BIO *bp, const char *name, const char *header, const unsigned char *data, long len) { int nlen, n, i, j, outl; unsigned char *buf = NULL; EVP_ENCODE_CTX ctx; int reason = ERR_R_BUF_LIB; EVP_EncodeInit(&ctx); nlen = strlen(name); if ((BIO_write(bp, "-----BEGIN ", 11) != 11) || (BIO_write(bp, name, nlen) != nlen) || (BIO_write(bp, "-----\n", 6) != 6)) goto err; i = strlen(header); if (i > 0) { if ((BIO_write(bp, header, i) != i) || (BIO_write(bp, "\n", 1) != 1)) goto err; } buf = OPENSSL_malloc(PEM_BUFSIZE * 8); if (buf == NULL) { reason = ERR_R_MALLOC_FAILURE; goto err; } i = j = 0; while (len > 0) { n = (int)((len > (PEM_BUFSIZE * 5)) ? (PEM_BUFSIZE * 5) : len); EVP_EncodeUpdate(&ctx, buf, &outl, &(data[j]), n); if ((outl) && (BIO_write(bp, (char *)buf, outl) != outl)) goto err; i += outl; len -= n; j += n; } EVP_EncodeFinal(&ctx, buf, &outl); if ((outl > 0) && (BIO_write(bp, (char *)buf, outl) != outl)) goto err; OPENSSL_cleanse(buf, PEM_BUFSIZE * 8); OPENSSL_free(buf); buf = NULL; if ((BIO_write(bp, "-----END ", 9) != 9) || (BIO_write(bp, name, nlen) != nlen) || (BIO_write(bp, "-----\n", 6) != 6)) goto err; return (i + outl); err: if (buf) { OPENSSL_cleanse(buf, PEM_BUFSIZE * 8); OPENSSL_free(buf); } PEMerr(PEM_F_PEM_WRITE_BIO, reason); return (0); } #ifndef OPENSSL_NO_FP_API int PEM_read(FILE *fp, char **name, char **header, unsigned char **data, long *len) { BIO *b; int ret; if ((b = BIO_new(BIO_s_file())) == NULL) { PEMerr(PEM_F_PEM_READ, ERR_R_BUF_LIB); return (0); } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = PEM_read_bio(b, name, header, data, len); BIO_free(b); return (ret); } #endif int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data, long *len) { EVP_ENCODE_CTX ctx; int end = 0, i, k, bl = 0, hl = 0, nohead = 0; char buf[256]; BUF_MEM *nameB; BUF_MEM *headerB; BUF_MEM *dataB, *tmpB; nameB = BUF_MEM_new(); headerB = BUF_MEM_new(); dataB = BUF_MEM_new(); if ((nameB == NULL) || (headerB == NULL) || (dataB == NULL)) { BUF_MEM_free(nameB); BUF_MEM_free(headerB); BUF_MEM_free(dataB); PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE); return (0); } buf[254] = '\0'; for (;;) { i = BIO_gets(bp, buf, 254); if (i <= 0) { PEMerr(PEM_F_PEM_READ_BIO, PEM_R_NO_START_LINE); goto err; } while ((i >= 0) && (buf[i] <= ' ')) i--; buf[++i] = '\n'; buf[++i] = '\0'; if (strncmp(buf, "-----BEGIN ", 11) == 0) { i = strlen(&(buf[11])); if (strncmp(&(buf[11 + i - 6]), "-----\n", 6) != 0) continue; if (!BUF_MEM_grow(nameB, i + 9)) { PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE); goto err; } memcpy(nameB->data, &(buf[11]), i - 6); nameB->data[i - 6] = '\0'; break; } } hl = 0; if (!BUF_MEM_grow(headerB, 256)) { PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE); goto err; } headerB->data[0] = '\0'; for (;;) { i = BIO_gets(bp, buf, 254); if (i <= 0) break; while ((i >= 0) && (buf[i] <= ' ')) i--; buf[++i] = '\n'; buf[++i] = '\0'; if (buf[0] == '\n') break; if (!BUF_MEM_grow(headerB, hl + i + 9)) { PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE); goto err; } if (strncmp(buf, "-----END ", 9) == 0) { nohead = 1; break; } memcpy(&(headerB->data[hl]), buf, i); headerB->data[hl + i] = '\0'; hl += i; } bl = 0; if (!BUF_MEM_grow(dataB, 1024)) { PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE); goto err; } dataB->data[0] = '\0'; if (!nohead) { for (;;) { i = BIO_gets(bp, buf, 254); if (i <= 0) break; while ((i >= 0) && (buf[i] <= ' ')) i--; buf[++i] = '\n'; buf[++i] = '\0'; if (i != 65) end = 1; if (strncmp(buf, "-----END ", 9) == 0) break; if (i > 65) break; if (!BUF_MEM_grow_clean(dataB, i + bl + 9)) { PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE); goto err; } memcpy(&(dataB->data[bl]), buf, i); dataB->data[bl + i] = '\0'; bl += i; if (end) { buf[0] = '\0'; i = BIO_gets(bp, buf, 254); if (i <= 0) break; while ((i >= 0) && (buf[i] <= ' ')) i--; buf[++i] = '\n'; buf[++i] = '\0'; break; } } } else { tmpB = headerB; headerB = dataB; dataB = tmpB; bl = hl; } i = strlen(nameB->data); if ((strncmp(buf, "-----END ", 9) != 0) || (strncmp(nameB->data, &(buf[9]), i) != 0) || (strncmp(&(buf[9 + i]), "-----\n", 6) != 0)) { PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_END_LINE); goto err; } EVP_DecodeInit(&ctx); i = EVP_DecodeUpdate(&ctx, (unsigned char *)dataB->data, &bl, (unsigned char *)dataB->data, bl); if (i < 0) { PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_BASE64_DECODE); goto err; } i = EVP_DecodeFinal(&ctx, (unsigned char *)&(dataB->data[bl]), &k); if (i < 0) { PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_BASE64_DECODE); goto err; } bl += k; if (bl == 0) goto err; *name = nameB->data; *header = headerB->data; *data = (unsigned char *)dataB->data; *len = bl; OPENSSL_free(nameB); OPENSSL_free(headerB); OPENSSL_free(dataB); return (1); err: BUF_MEM_free(nameB); BUF_MEM_free(headerB); BUF_MEM_free(dataB); return (0); } /* * Check pem string and return prefix length. If for example the pem_str == * "RSA PRIVATE KEY" and suffix = "PRIVATE KEY" the return value is 3 for the * string "RSA". */ int pem_check_suffix(const char *pem_str, const char *suffix) { int pem_len = strlen(pem_str); int suffix_len = strlen(suffix); const char *p; if (suffix_len + 1 >= pem_len) return 0; p = pem_str + pem_len - suffix_len; if (strcmp(p, suffix)) return 0; p--; if (*p != ' ') return 0; return p - pem_str; } Index: vendor-crypto/openssl/dist/crypto/pem/pem_pk8.c =================================================================== --- vendor-crypto/openssl/dist/crypto/pem/pem_pk8.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/pem/pem_pk8.c (revision 325326) @@ -1,259 +1,260 @@ /* crypto/pem/pem_pkey.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 #include #include #include #include static int do_pk8pkey(BIO *bp, EVP_PKEY *x, int isder, int nid, const EVP_CIPHER *enc, char *kstr, int klen, pem_password_cb *cb, void *u); static int do_pk8pkey_fp(FILE *bp, EVP_PKEY *x, int isder, int nid, const EVP_CIPHER *enc, char *kstr, int klen, pem_password_cb *cb, void *u); /* * These functions write a private key in PKCS#8 format: it is a "drop in" * replacement for PEM_write_bio_PrivateKey() and friends. As usual if 'enc' * is NULL then it uses the unencrypted private key form. The 'nid' versions * uses PKCS#5 v1.5 PBE algorithms whereas the others use PKCS#5 v2.0. */ int PEM_write_bio_PKCS8PrivateKey_nid(BIO *bp, EVP_PKEY *x, int nid, char *kstr, int klen, pem_password_cb *cb, void *u) { return do_pk8pkey(bp, x, 0, nid, NULL, kstr, klen, cb, u); } int PEM_write_bio_PKCS8PrivateKey(BIO *bp, EVP_PKEY *x, const EVP_CIPHER *enc, char *kstr, int klen, pem_password_cb *cb, void *u) { return do_pk8pkey(bp, x, 0, -1, enc, kstr, klen, cb, u); } int i2d_PKCS8PrivateKey_bio(BIO *bp, EVP_PKEY *x, const EVP_CIPHER *enc, char *kstr, int klen, pem_password_cb *cb, void *u) { return do_pk8pkey(bp, x, 1, -1, enc, kstr, klen, cb, u); } int i2d_PKCS8PrivateKey_nid_bio(BIO *bp, EVP_PKEY *x, int nid, char *kstr, int klen, pem_password_cb *cb, void *u) { return do_pk8pkey(bp, x, 1, nid, NULL, kstr, klen, cb, u); } static int do_pk8pkey(BIO *bp, EVP_PKEY *x, int isder, int nid, const EVP_CIPHER *enc, char *kstr, int klen, pem_password_cb *cb, void *u) { X509_SIG *p8; PKCS8_PRIV_KEY_INFO *p8inf; char buf[PEM_BUFSIZE]; int ret; if (!(p8inf = EVP_PKEY2PKCS8(x))) { PEMerr(PEM_F_DO_PK8PKEY, PEM_R_ERROR_CONVERTING_PRIVATE_KEY); return 0; } if (enc || (nid != -1)) { if (!kstr) { if (!cb) klen = PEM_def_callback(buf, PEM_BUFSIZE, 1, u); else klen = cb(buf, PEM_BUFSIZE, 1, u); if (klen <= 0) { PEMerr(PEM_F_DO_PK8PKEY, PEM_R_READ_KEY); PKCS8_PRIV_KEY_INFO_free(p8inf); return 0; } kstr = buf; } p8 = PKCS8_encrypt(nid, enc, kstr, klen, NULL, 0, 0, p8inf); if (kstr == buf) OPENSSL_cleanse(buf, klen); PKCS8_PRIV_KEY_INFO_free(p8inf); if (p8 == NULL) return 0; if (isder) ret = i2d_PKCS8_bio(bp, p8); else ret = PEM_write_bio_PKCS8(bp, p8); X509_SIG_free(p8); return ret; } else { if (isder) ret = i2d_PKCS8_PRIV_KEY_INFO_bio(bp, p8inf); else ret = PEM_write_bio_PKCS8_PRIV_KEY_INFO(bp, p8inf); PKCS8_PRIV_KEY_INFO_free(p8inf); return ret; } } EVP_PKEY *d2i_PKCS8PrivateKey_bio(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u) { PKCS8_PRIV_KEY_INFO *p8inf = NULL; X509_SIG *p8 = NULL; int klen; EVP_PKEY *ret; char psbuf[PEM_BUFSIZE]; p8 = d2i_PKCS8_bio(bp, NULL); if (!p8) return NULL; if (cb) klen = cb(psbuf, PEM_BUFSIZE, 0, u); else klen = PEM_def_callback(psbuf, PEM_BUFSIZE, 0, u); if (klen <= 0) { PEMerr(PEM_F_D2I_PKCS8PRIVATEKEY_BIO, PEM_R_BAD_PASSWORD_READ); X509_SIG_free(p8); return NULL; } p8inf = PKCS8_decrypt(p8, psbuf, klen); X509_SIG_free(p8); + OPENSSL_cleanse(psbuf, klen); if (!p8inf) return NULL; ret = EVP_PKCS82PKEY(p8inf); PKCS8_PRIV_KEY_INFO_free(p8inf); if (!ret) return NULL; if (x) { if (*x) EVP_PKEY_free(*x); *x = ret; } return ret; } #ifndef OPENSSL_NO_FP_API int i2d_PKCS8PrivateKey_fp(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc, char *kstr, int klen, pem_password_cb *cb, void *u) { return do_pk8pkey_fp(fp, x, 1, -1, enc, kstr, klen, cb, u); } int i2d_PKCS8PrivateKey_nid_fp(FILE *fp, EVP_PKEY *x, int nid, char *kstr, int klen, pem_password_cb *cb, void *u) { return do_pk8pkey_fp(fp, x, 1, nid, NULL, kstr, klen, cb, u); } int PEM_write_PKCS8PrivateKey_nid(FILE *fp, EVP_PKEY *x, int nid, char *kstr, int klen, pem_password_cb *cb, void *u) { return do_pk8pkey_fp(fp, x, 0, nid, NULL, kstr, klen, cb, u); } int PEM_write_PKCS8PrivateKey(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc, char *kstr, int klen, pem_password_cb *cb, void *u) { return do_pk8pkey_fp(fp, x, 0, -1, enc, kstr, klen, cb, u); } static int do_pk8pkey_fp(FILE *fp, EVP_PKEY *x, int isder, int nid, const EVP_CIPHER *enc, char *kstr, int klen, pem_password_cb *cb, void *u) { BIO *bp; int ret; if (!(bp = BIO_new_fp(fp, BIO_NOCLOSE))) { PEMerr(PEM_F_DO_PK8PKEY_FP, ERR_R_BUF_LIB); return (0); } ret = do_pk8pkey(bp, x, isder, nid, enc, kstr, klen, cb, u); BIO_free(bp); return ret; } EVP_PKEY *d2i_PKCS8PrivateKey_fp(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u) { BIO *bp; EVP_PKEY *ret; if (!(bp = BIO_new_fp(fp, BIO_NOCLOSE))) { PEMerr(PEM_F_D2I_PKCS8PRIVATEKEY_FP, ERR_R_BUF_LIB); return NULL; } ret = d2i_PKCS8PrivateKey_bio(bp, x, cb, u); BIO_free(bp); return ret; } #endif IMPLEMENT_PEM_rw(PKCS8, X509_SIG, PEM_STRING_PKCS8, X509_SIG) IMPLEMENT_PEM_rw(PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO, PEM_STRING_PKCS8INF, PKCS8_PRIV_KEY_INFO) Index: vendor-crypto/openssl/dist/crypto/pem/pem_pkey.c =================================================================== --- vendor-crypto/openssl/dist/crypto/pem/pem_pkey.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/pem/pem_pkey.c (revision 325326) @@ -1,293 +1,294 @@ /* crypto/pem/pem_pkey.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 #include #include #include #include #ifndef OPENSSL_NO_ENGINE # include #endif #ifndef OPENSSL_NO_DH # include #endif #include "asn1_locl.h" int pem_check_suffix(const char *pem_str, const char *suffix); EVP_PKEY *PEM_read_bio_PrivateKey(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u) { char *nm = NULL; const unsigned char *p = NULL; unsigned char *data = NULL; long len; int slen; EVP_PKEY *ret = NULL; if (!PEM_bytes_read_bio(&data, &len, &nm, PEM_STRING_EVP_PKEY, bp, cb, u)) return NULL; p = data; if (strcmp(nm, PEM_STRING_PKCS8INF) == 0) { PKCS8_PRIV_KEY_INFO *p8inf; p8inf = d2i_PKCS8_PRIV_KEY_INFO(NULL, &p, len); if (!p8inf) goto p8err; ret = EVP_PKCS82PKEY(p8inf); if (x) { if (*x) EVP_PKEY_free((EVP_PKEY *)*x); *x = ret; } PKCS8_PRIV_KEY_INFO_free(p8inf); } else if (strcmp(nm, PEM_STRING_PKCS8) == 0) { PKCS8_PRIV_KEY_INFO *p8inf; X509_SIG *p8; int klen; char psbuf[PEM_BUFSIZE]; p8 = d2i_X509_SIG(NULL, &p, len); if (!p8) goto p8err; if (cb) klen = cb(psbuf, PEM_BUFSIZE, 0, u); else klen = PEM_def_callback(psbuf, PEM_BUFSIZE, 0, u); if (klen <= 0) { PEMerr(PEM_F_PEM_READ_BIO_PRIVATEKEY, PEM_R_BAD_PASSWORD_READ); X509_SIG_free(p8); goto err; } p8inf = PKCS8_decrypt(p8, psbuf, klen); X509_SIG_free(p8); + OPENSSL_cleanse(psbuf, klen); if (!p8inf) goto p8err; ret = EVP_PKCS82PKEY(p8inf); if (x) { if (*x) EVP_PKEY_free((EVP_PKEY *)*x); *x = ret; } PKCS8_PRIV_KEY_INFO_free(p8inf); } else if ((slen = pem_check_suffix(nm, "PRIVATE KEY")) > 0) { const EVP_PKEY_ASN1_METHOD *ameth; ameth = EVP_PKEY_asn1_find_str(NULL, nm, slen); if (!ameth || !ameth->old_priv_decode) goto p8err; ret = d2i_PrivateKey(ameth->pkey_id, x, &p, len); } p8err: if (ret == NULL) PEMerr(PEM_F_PEM_READ_BIO_PRIVATEKEY, ERR_R_ASN1_LIB); err: OPENSSL_free(nm); OPENSSL_cleanse(data, len); OPENSSL_free(data); return (ret); } int PEM_write_bio_PrivateKey(BIO *bp, EVP_PKEY *x, const EVP_CIPHER *enc, unsigned char *kstr, int klen, pem_password_cb *cb, void *u) { char pem_str[80]; if (!x->ameth || x->ameth->priv_encode) return PEM_write_bio_PKCS8PrivateKey(bp, x, enc, (char *)kstr, klen, cb, u); BIO_snprintf(pem_str, 80, "%s PRIVATE KEY", x->ameth->pem_str); return PEM_ASN1_write_bio((i2d_of_void *)i2d_PrivateKey, pem_str, bp, x, enc, kstr, klen, cb, u); } EVP_PKEY *PEM_read_bio_Parameters(BIO *bp, EVP_PKEY **x) { char *nm = NULL; const unsigned char *p = NULL; unsigned char *data = NULL; long len; int slen; EVP_PKEY *ret = NULL; if (!PEM_bytes_read_bio(&data, &len, &nm, PEM_STRING_PARAMETERS, bp, 0, NULL)) return NULL; p = data; if ((slen = pem_check_suffix(nm, "PARAMETERS")) > 0) { ret = EVP_PKEY_new(); if (!ret) goto err; if (!EVP_PKEY_set_type_str(ret, nm, slen) || !ret->ameth->param_decode || !ret->ameth->param_decode(ret, &p, len)) { EVP_PKEY_free(ret); ret = NULL; goto err; } if (x) { if (*x) EVP_PKEY_free((EVP_PKEY *)*x); *x = ret; } } err: if (ret == NULL) PEMerr(PEM_F_PEM_READ_BIO_PARAMETERS, ERR_R_ASN1_LIB); OPENSSL_free(nm); OPENSSL_free(data); return (ret); } int PEM_write_bio_Parameters(BIO *bp, EVP_PKEY *x) { char pem_str[80]; if (!x->ameth || !x->ameth->param_encode) return 0; BIO_snprintf(pem_str, 80, "%s PARAMETERS", x->ameth->pem_str); return PEM_ASN1_write_bio((i2d_of_void *)x->ameth->param_encode, pem_str, bp, x, NULL, NULL, 0, 0, NULL); } #ifndef OPENSSL_NO_FP_API EVP_PKEY *PEM_read_PrivateKey(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u) { BIO *b; EVP_PKEY *ret; if ((b = BIO_new(BIO_s_file())) == NULL) { PEMerr(PEM_F_PEM_READ_PRIVATEKEY, ERR_R_BUF_LIB); return (0); } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = PEM_read_bio_PrivateKey(b, x, cb, u); BIO_free(b); return (ret); } int PEM_write_PrivateKey(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc, unsigned char *kstr, int klen, pem_password_cb *cb, void *u) { BIO *b; int ret; if ((b = BIO_new_fp(fp, BIO_NOCLOSE)) == NULL) { PEMerr(PEM_F_PEM_WRITE_PRIVATEKEY, ERR_R_BUF_LIB); return 0; } ret = PEM_write_bio_PrivateKey(b, x, enc, kstr, klen, cb, u); BIO_free(b); return ret; } #endif #ifndef OPENSSL_NO_DH /* Transparently read in PKCS#3 or X9.42 DH parameters */ DH *PEM_read_bio_DHparams(BIO *bp, DH **x, pem_password_cb *cb, void *u) { char *nm = NULL; const unsigned char *p = NULL; unsigned char *data = NULL; long len; DH *ret = NULL; if (!PEM_bytes_read_bio(&data, &len, &nm, PEM_STRING_DHPARAMS, bp, cb, u)) return NULL; p = data; if (!strcmp(nm, PEM_STRING_DHXPARAMS)) ret = d2i_DHxparams(x, &p, len); else ret = d2i_DHparams(x, &p, len); if (ret == NULL) PEMerr(PEM_F_PEM_READ_BIO_DHPARAMS, ERR_R_ASN1_LIB); OPENSSL_free(nm); OPENSSL_free(data); return ret; } # ifndef OPENSSL_NO_FP_API DH *PEM_read_DHparams(FILE *fp, DH **x, pem_password_cb *cb, void *u) { BIO *b; DH *ret; if ((b = BIO_new(BIO_s_file())) == NULL) { PEMerr(PEM_F_PEM_READ_DHPARAMS, ERR_R_BUF_LIB); return (0); } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = PEM_read_bio_DHparams(b, x, cb, u); BIO_free(b); return (ret); } # endif #endif Index: vendor-crypto/openssl/dist/crypto/pkcs12/p12_kiss.c =================================================================== --- vendor-crypto/openssl/dist/crypto/pkcs12/p12_kiss.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/pkcs12/p12_kiss.c (revision 325326) @@ -1,299 +1,304 @@ /* p12_kiss.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 /* Simplified PKCS#12 routines */ static int parse_pk12(PKCS12 *p12, const char *pass, int passlen, EVP_PKEY **pkey, STACK_OF(X509) *ocerts); static int parse_bags(STACK_OF(PKCS12_SAFEBAG) *bags, const char *pass, int passlen, EVP_PKEY **pkey, STACK_OF(X509) *ocerts); static int parse_bag(PKCS12_SAFEBAG *bag, const char *pass, int passlen, EVP_PKEY **pkey, STACK_OF(X509) *ocerts); /* * Parse and decrypt a PKCS#12 structure returning user key, user cert and * other (CA) certs. Note either ca should be NULL, *ca should be NULL, or it * should point to a valid STACK structure. pkey and cert can be passed * unitialised. */ int PKCS12_parse(PKCS12 *p12, const char *pass, EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca) { STACK_OF(X509) *ocerts = NULL; X509 *x = NULL; + + if (pkey) + *pkey = NULL; + if (cert) + *cert = NULL; + /* Check for NULL PKCS12 structure */ if (!p12) { PKCS12err(PKCS12_F_PKCS12_PARSE, PKCS12_R_INVALID_NULL_PKCS12_POINTER); return 0; } - if (pkey) - *pkey = NULL; - if (cert) - *cert = NULL; - /* Check the mac */ /* * If password is zero length or NULL then try verifying both cases to * determine which password is correct. The reason for this is that under * PKCS#12 password based encryption no password and a zero length * password are two different things... */ if (!pass || !*pass) { if (PKCS12_verify_mac(p12, NULL, 0)) pass = NULL; else if (PKCS12_verify_mac(p12, "", 0)) pass = ""; else { PKCS12err(PKCS12_F_PKCS12_PARSE, PKCS12_R_MAC_VERIFY_FAILURE); goto err; } } else if (!PKCS12_verify_mac(p12, pass, -1)) { PKCS12err(PKCS12_F_PKCS12_PARSE, PKCS12_R_MAC_VERIFY_FAILURE); goto err; } /* Allocate stack for other certificates */ ocerts = sk_X509_new_null(); if (!ocerts) { PKCS12err(PKCS12_F_PKCS12_PARSE, ERR_R_MALLOC_FAILURE); - return 0; + goto err; } if (!parse_pk12(p12, pass, -1, pkey, ocerts)) { PKCS12err(PKCS12_F_PKCS12_PARSE, PKCS12_R_PARSE_ERROR); goto err; } while ((x = sk_X509_pop(ocerts))) { if (pkey && *pkey && cert && !*cert) { ERR_set_mark(); if (X509_check_private_key(x, *pkey)) { *cert = x; x = NULL; } ERR_pop_to_mark(); } if (ca && x) { if (!*ca) *ca = sk_X509_new_null(); if (!*ca) goto err; if (!sk_X509_push(*ca, x)) goto err; x = NULL; } if (x) X509_free(x); } if (ocerts) sk_X509_pop_free(ocerts, X509_free); return 1; err: - if (pkey && *pkey) + if (pkey) { EVP_PKEY_free(*pkey); - if (cert && *cert) + *pkey = NULL; + } + if (cert) { X509_free(*cert); + *cert = NULL; + } if (x) X509_free(x); if (ocerts) sk_X509_pop_free(ocerts, X509_free); return 0; } /* Parse the outer PKCS#12 structure */ static int parse_pk12(PKCS12 *p12, const char *pass, int passlen, EVP_PKEY **pkey, STACK_OF(X509) *ocerts) { STACK_OF(PKCS7) *asafes; STACK_OF(PKCS12_SAFEBAG) *bags; int i, bagnid; PKCS7 *p7; if (!(asafes = PKCS12_unpack_authsafes(p12))) return 0; for (i = 0; i < sk_PKCS7_num(asafes); i++) { p7 = sk_PKCS7_value(asafes, i); bagnid = OBJ_obj2nid(p7->type); if (bagnid == NID_pkcs7_data) { bags = PKCS12_unpack_p7data(p7); } else if (bagnid == NID_pkcs7_encrypted) { bags = PKCS12_unpack_p7encdata(p7, pass, passlen); } else continue; if (!bags) { sk_PKCS7_pop_free(asafes, PKCS7_free); return 0; } if (!parse_bags(bags, pass, passlen, pkey, ocerts)) { sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); sk_PKCS7_pop_free(asafes, PKCS7_free); return 0; } sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); } sk_PKCS7_pop_free(asafes, PKCS7_free); return 1; } static int parse_bags(STACK_OF(PKCS12_SAFEBAG) *bags, const char *pass, int passlen, EVP_PKEY **pkey, STACK_OF(X509) *ocerts) { int i; for (i = 0; i < sk_PKCS12_SAFEBAG_num(bags); i++) { if (!parse_bag(sk_PKCS12_SAFEBAG_value(bags, i), pass, passlen, pkey, ocerts)) return 0; } return 1; } static int parse_bag(PKCS12_SAFEBAG *bag, const char *pass, int passlen, EVP_PKEY **pkey, STACK_OF(X509) *ocerts) { PKCS8_PRIV_KEY_INFO *p8; X509 *x509; ASN1_TYPE *attrib; ASN1_BMPSTRING *fname = NULL; ASN1_OCTET_STRING *lkid = NULL; if ((attrib = PKCS12_get_attr(bag, NID_friendlyName))) fname = attrib->value.bmpstring; if ((attrib = PKCS12_get_attr(bag, NID_localKeyID))) lkid = attrib->value.octet_string; switch (M_PKCS12_bag_type(bag)) { case NID_keyBag: if (!pkey || *pkey) return 1; if (!(*pkey = EVP_PKCS82PKEY(bag->value.keybag))) return 0; break; case NID_pkcs8ShroudedKeyBag: if (!pkey || *pkey) return 1; if (!(p8 = PKCS12_decrypt_skey(bag, pass, passlen))) return 0; *pkey = EVP_PKCS82PKEY(p8); PKCS8_PRIV_KEY_INFO_free(p8); if (!(*pkey)) return 0; break; case NID_certBag: if (M_PKCS12_cert_bag_type(bag) != NID_x509Certificate) return 1; if (!(x509 = PKCS12_certbag2x509(bag))) return 0; if (lkid && !X509_keyid_set1(x509, lkid->data, lkid->length)) { X509_free(x509); return 0; } if (fname) { int len, r; unsigned char *data; len = ASN1_STRING_to_UTF8(&data, fname); if (len >= 0) { r = X509_alias_set1(x509, data, len); OPENSSL_free(data); if (!r) { X509_free(x509); return 0; } } } if (!sk_X509_push(ocerts, x509)) { X509_free(x509); return 0; } break; case NID_safeContentsBag: return parse_bags(bag->value.safes, pass, passlen, pkey, ocerts); break; default: return 1; break; } return 1; } Index: vendor-crypto/openssl/dist/crypto/rsa/rsa_ameth.c =================================================================== --- vendor-crypto/openssl/dist/crypto/rsa/rsa_ameth.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/rsa/rsa_ameth.c (revision 325326) @@ -1,967 +1,967 @@ /* crypto/rsa/rsa_ameth.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 #ifndef OPENSSL_NO_CMS # include #endif #include "asn1_locl.h" #ifndef OPENSSL_NO_CMS static int rsa_cms_sign(CMS_SignerInfo *si); static int rsa_cms_verify(CMS_SignerInfo *si); static int rsa_cms_decrypt(CMS_RecipientInfo *ri); static int rsa_cms_encrypt(CMS_RecipientInfo *ri); #endif static int rsa_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey) { unsigned char *penc = NULL; int penclen; penclen = i2d_RSAPublicKey(pkey->pkey.rsa, &penc); if (penclen <= 0) return 0; if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(EVP_PKEY_RSA), V_ASN1_NULL, NULL, penc, penclen)) return 1; OPENSSL_free(penc); return 0; } static int rsa_pub_decode(EVP_PKEY *pkey, X509_PUBKEY *pubkey) { const unsigned char *p; int pklen; RSA *rsa = NULL; if (!X509_PUBKEY_get0_param(NULL, &p, &pklen, NULL, pubkey)) return 0; if (!(rsa = d2i_RSAPublicKey(NULL, &p, pklen))) { RSAerr(RSA_F_RSA_PUB_DECODE, ERR_R_RSA_LIB); return 0; } EVP_PKEY_assign_RSA(pkey, rsa); return 1; } static int rsa_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b) { if (BN_cmp(b->pkey.rsa->n, a->pkey.rsa->n) != 0 || BN_cmp(b->pkey.rsa->e, a->pkey.rsa->e) != 0) return 0; return 1; } static int old_rsa_priv_decode(EVP_PKEY *pkey, const unsigned char **pder, int derlen) { RSA *rsa; if (!(rsa = d2i_RSAPrivateKey(NULL, pder, derlen))) { RSAerr(RSA_F_OLD_RSA_PRIV_DECODE, ERR_R_RSA_LIB); return 0; } EVP_PKEY_assign_RSA(pkey, rsa); return 1; } static int old_rsa_priv_encode(const EVP_PKEY *pkey, unsigned char **pder) { return i2d_RSAPrivateKey(pkey->pkey.rsa, pder); } static int rsa_priv_encode(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pkey) { unsigned char *rk = NULL; int rklen; rklen = i2d_RSAPrivateKey(pkey->pkey.rsa, &rk); if (rklen <= 0) { RSAerr(RSA_F_RSA_PRIV_ENCODE, ERR_R_MALLOC_FAILURE); return 0; } if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(NID_rsaEncryption), 0, V_ASN1_NULL, NULL, rk, rklen)) { RSAerr(RSA_F_RSA_PRIV_ENCODE, ERR_R_MALLOC_FAILURE); return 0; } return 1; } static int rsa_priv_decode(EVP_PKEY *pkey, PKCS8_PRIV_KEY_INFO *p8) { const unsigned char *p; int pklen; if (!PKCS8_pkey_get0(NULL, &p, &pklen, NULL, p8)) return 0; return old_rsa_priv_decode(pkey, &p, pklen); } static int int_rsa_size(const EVP_PKEY *pkey) { return RSA_size(pkey->pkey.rsa); } static int rsa_bits(const EVP_PKEY *pkey) { return BN_num_bits(pkey->pkey.rsa->n); } static void int_rsa_free(EVP_PKEY *pkey) { RSA_free(pkey->pkey.rsa); } static void update_buflen(const BIGNUM *b, size_t *pbuflen) { size_t i; if (!b) return; if (*pbuflen < (i = (size_t)BN_num_bytes(b))) *pbuflen = i; } static int do_rsa_print(BIO *bp, const RSA *x, int off, int priv) { char *str; const char *s; unsigned char *m = NULL; int ret = 0, mod_len = 0; size_t buf_len = 0; update_buflen(x->n, &buf_len); update_buflen(x->e, &buf_len); if (priv) { update_buflen(x->d, &buf_len); update_buflen(x->p, &buf_len); update_buflen(x->q, &buf_len); update_buflen(x->dmp1, &buf_len); update_buflen(x->dmq1, &buf_len); update_buflen(x->iqmp, &buf_len); } m = (unsigned char *)OPENSSL_malloc(buf_len + 10); if (m == NULL) { RSAerr(RSA_F_DO_RSA_PRINT, ERR_R_MALLOC_FAILURE); goto err; } if (x->n != NULL) mod_len = BN_num_bits(x->n); if (!BIO_indent(bp, off, 128)) goto err; if (priv && x->d) { if (BIO_printf(bp, "Private-Key: (%d bit)\n", mod_len) <= 0) goto err; str = "modulus:"; s = "publicExponent:"; } else { if (BIO_printf(bp, "Public-Key: (%d bit)\n", mod_len) <= 0) goto err; str = "Modulus:"; s = "Exponent:"; } if (!ASN1_bn_print(bp, str, x->n, m, off)) goto err; if (!ASN1_bn_print(bp, s, x->e, m, off)) goto err; if (priv) { if (!ASN1_bn_print(bp, "privateExponent:", x->d, m, off)) goto err; if (!ASN1_bn_print(bp, "prime1:", x->p, m, off)) goto err; if (!ASN1_bn_print(bp, "prime2:", x->q, m, off)) goto err; if (!ASN1_bn_print(bp, "exponent1:", x->dmp1, m, off)) goto err; if (!ASN1_bn_print(bp, "exponent2:", x->dmq1, m, off)) goto err; if (!ASN1_bn_print(bp, "coefficient:", x->iqmp, m, off)) goto err; } ret = 1; err: if (m != NULL) OPENSSL_free(m); return (ret); } static int rsa_pub_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return do_rsa_print(bp, pkey->pkey.rsa, indent, 0); } static int rsa_priv_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return do_rsa_print(bp, pkey->pkey.rsa, indent, 1); } /* Given an MGF1 Algorithm ID decode to an Algorithm Identifier */ static X509_ALGOR *rsa_mgf1_decode(X509_ALGOR *alg) { const unsigned char *p; int plen; if (alg == NULL || alg->parameter == NULL) return NULL; if (OBJ_obj2nid(alg->algorithm) != NID_mgf1) return NULL; if (alg->parameter->type != V_ASN1_SEQUENCE) return NULL; p = alg->parameter->value.sequence->data; plen = alg->parameter->value.sequence->length; return d2i_X509_ALGOR(NULL, &p, plen); } static RSA_PSS_PARAMS *rsa_pss_decode(const X509_ALGOR *alg, X509_ALGOR **pmaskHash) { const unsigned char *p; int plen; RSA_PSS_PARAMS *pss; *pmaskHash = NULL; if (!alg->parameter || alg->parameter->type != V_ASN1_SEQUENCE) return NULL; p = alg->parameter->value.sequence->data; plen = alg->parameter->value.sequence->length; pss = d2i_RSA_PSS_PARAMS(NULL, &p, plen); if (!pss) return NULL; *pmaskHash = rsa_mgf1_decode(pss->maskGenAlgorithm); return pss; } static int rsa_pss_param_print(BIO *bp, RSA_PSS_PARAMS *pss, X509_ALGOR *maskHash, int indent) { int rv = 0; if (!pss) { if (BIO_puts(bp, " (INVALID PSS PARAMETERS)\n") <= 0) return 0; return 1; } if (BIO_puts(bp, "\n") <= 0) goto err; if (!BIO_indent(bp, indent, 128)) goto err; if (BIO_puts(bp, "Hash Algorithm: ") <= 0) goto err; if (pss->hashAlgorithm) { if (i2a_ASN1_OBJECT(bp, pss->hashAlgorithm->algorithm) <= 0) goto err; } else if (BIO_puts(bp, "sha1 (default)") <= 0) goto err; if (BIO_puts(bp, "\n") <= 0) goto err; if (!BIO_indent(bp, indent, 128)) goto err; if (BIO_puts(bp, "Mask Algorithm: ") <= 0) goto err; if (pss->maskGenAlgorithm) { if (i2a_ASN1_OBJECT(bp, pss->maskGenAlgorithm->algorithm) <= 0) goto err; if (BIO_puts(bp, " with ") <= 0) goto err; if (maskHash) { if (i2a_ASN1_OBJECT(bp, maskHash->algorithm) <= 0) goto err; } else if (BIO_puts(bp, "INVALID") <= 0) goto err; } else if (BIO_puts(bp, "mgf1 with sha1 (default)") <= 0) goto err; BIO_puts(bp, "\n"); if (!BIO_indent(bp, indent, 128)) goto err; if (BIO_puts(bp, "Salt Length: 0x") <= 0) goto err; if (pss->saltLength) { if (i2a_ASN1_INTEGER(bp, pss->saltLength) <= 0) goto err; } else if (BIO_puts(bp, "14 (default)") <= 0) goto err; BIO_puts(bp, "\n"); if (!BIO_indent(bp, indent, 128)) goto err; if (BIO_puts(bp, "Trailer Field: 0x") <= 0) goto err; if (pss->trailerField) { if (i2a_ASN1_INTEGER(bp, pss->trailerField) <= 0) goto err; } else if (BIO_puts(bp, "BC (default)") <= 0) goto err; BIO_puts(bp, "\n"); rv = 1; err: return rv; } static int rsa_sig_print(BIO *bp, const X509_ALGOR *sigalg, const ASN1_STRING *sig, int indent, ASN1_PCTX *pctx) { if (OBJ_obj2nid(sigalg->algorithm) == NID_rsassaPss) { int rv; RSA_PSS_PARAMS *pss; X509_ALGOR *maskHash; pss = rsa_pss_decode(sigalg, &maskHash); rv = rsa_pss_param_print(bp, pss, maskHash, indent); if (pss) RSA_PSS_PARAMS_free(pss); if (maskHash) X509_ALGOR_free(maskHash); if (!rv) return 0; } else if (!sig && BIO_puts(bp, "\n") <= 0) return 0; if (sig) return X509_signature_dump(bp, sig, indent); return 1; } static int rsa_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2) { X509_ALGOR *alg = NULL; switch (op) { case ASN1_PKEY_CTRL_PKCS7_SIGN: if (arg1 == 0) PKCS7_SIGNER_INFO_get0_algs(arg2, NULL, NULL, &alg); break; case ASN1_PKEY_CTRL_PKCS7_ENCRYPT: if (arg1 == 0) PKCS7_RECIP_INFO_get0_alg(arg2, &alg); break; #ifndef OPENSSL_NO_CMS case ASN1_PKEY_CTRL_CMS_SIGN: if (arg1 == 0) return rsa_cms_sign(arg2); else if (arg1 == 1) return rsa_cms_verify(arg2); break; case ASN1_PKEY_CTRL_CMS_ENVELOPE: if (arg1 == 0) return rsa_cms_encrypt(arg2); else if (arg1 == 1) return rsa_cms_decrypt(arg2); break; case ASN1_PKEY_CTRL_CMS_RI_TYPE: *(int *)arg2 = CMS_RECIPINFO_TRANS; return 1; #endif case ASN1_PKEY_CTRL_DEFAULT_MD_NID: *(int *)arg2 = NID_sha256; return 1; default: return -2; } if (alg) X509_ALGOR_set0(alg, OBJ_nid2obj(NID_rsaEncryption), V_ASN1_NULL, 0); return 1; } /* allocate and set algorithm ID from EVP_MD, default SHA1 */ static int rsa_md_to_algor(X509_ALGOR **palg, const EVP_MD *md) { if (EVP_MD_type(md) == NID_sha1) return 1; *palg = X509_ALGOR_new(); if (!*palg) return 0; X509_ALGOR_set_md(*palg, md); return 1; } /* Allocate and set MGF1 algorithm ID from EVP_MD */ static int rsa_md_to_mgf1(X509_ALGOR **palg, const EVP_MD *mgf1md) { X509_ALGOR *algtmp = NULL; ASN1_STRING *stmp = NULL; *palg = NULL; if (EVP_MD_type(mgf1md) == NID_sha1) return 1; /* need to embed algorithm ID inside another */ if (!rsa_md_to_algor(&algtmp, mgf1md)) goto err; if (!ASN1_item_pack(algtmp, ASN1_ITEM_rptr(X509_ALGOR), &stmp)) goto err; *palg = X509_ALGOR_new(); if (!*palg) goto err; X509_ALGOR_set0(*palg, OBJ_nid2obj(NID_mgf1), V_ASN1_SEQUENCE, stmp); stmp = NULL; err: if (stmp) ASN1_STRING_free(stmp); if (algtmp) X509_ALGOR_free(algtmp); if (*palg) return 1; return 0; } /* convert algorithm ID to EVP_MD, default SHA1 */ static const EVP_MD *rsa_algor_to_md(X509_ALGOR *alg) { const EVP_MD *md; if (!alg) return EVP_sha1(); md = EVP_get_digestbyobj(alg->algorithm); if (md == NULL) RSAerr(RSA_F_RSA_ALGOR_TO_MD, RSA_R_UNKNOWN_DIGEST); return md; } /* convert MGF1 algorithm ID to EVP_MD, default SHA1 */ static const EVP_MD *rsa_mgf1_to_md(X509_ALGOR *alg, X509_ALGOR *maskHash) { const EVP_MD *md; if (!alg) return EVP_sha1(); /* Check mask and lookup mask hash algorithm */ if (OBJ_obj2nid(alg->algorithm) != NID_mgf1) { RSAerr(RSA_F_RSA_MGF1_TO_MD, RSA_R_UNSUPPORTED_MASK_ALGORITHM); return NULL; } if (!maskHash) { RSAerr(RSA_F_RSA_MGF1_TO_MD, RSA_R_UNSUPPORTED_MASK_PARAMETER); return NULL; } md = EVP_get_digestbyobj(maskHash->algorithm); if (md == NULL) { RSAerr(RSA_F_RSA_MGF1_TO_MD, RSA_R_UNKNOWN_MASK_DIGEST); return NULL; } return md; } /* * Convert EVP_PKEY_CTX is PSS mode into corresponding algorithm parameter, * suitable for setting an AlgorithmIdentifier. */ static ASN1_STRING *rsa_ctx_to_pss(EVP_PKEY_CTX *pkctx) { const EVP_MD *sigmd, *mgf1md; RSA_PSS_PARAMS *pss = NULL; ASN1_STRING *os = NULL; EVP_PKEY *pk = EVP_PKEY_CTX_get0_pkey(pkctx); int saltlen, rv = 0; if (EVP_PKEY_CTX_get_signature_md(pkctx, &sigmd) <= 0) goto err; if (EVP_PKEY_CTX_get_rsa_mgf1_md(pkctx, &mgf1md) <= 0) goto err; if (!EVP_PKEY_CTX_get_rsa_pss_saltlen(pkctx, &saltlen)) goto err; if (saltlen == -1) saltlen = EVP_MD_size(sigmd); else if (saltlen == -2) { saltlen = EVP_PKEY_size(pk) - EVP_MD_size(sigmd) - 2; if (((EVP_PKEY_bits(pk) - 1) & 0x7) == 0) saltlen--; } pss = RSA_PSS_PARAMS_new(); if (!pss) goto err; if (saltlen != 20) { pss->saltLength = ASN1_INTEGER_new(); if (!pss->saltLength) goto err; if (!ASN1_INTEGER_set(pss->saltLength, saltlen)) goto err; } if (!rsa_md_to_algor(&pss->hashAlgorithm, sigmd)) goto err; if (!rsa_md_to_mgf1(&pss->maskGenAlgorithm, mgf1md)) goto err; /* Finally create string with pss parameter encoding. */ if (!ASN1_item_pack(pss, ASN1_ITEM_rptr(RSA_PSS_PARAMS), &os)) goto err; rv = 1; err: if (pss) RSA_PSS_PARAMS_free(pss); if (rv) return os; if (os) ASN1_STRING_free(os); return NULL; } /* * From PSS AlgorithmIdentifier set public key parameters. If pkey isn't NULL * then the EVP_MD_CTX is setup and initalised. If it is NULL parameters are * passed to pkctx instead. */ static int rsa_pss_to_ctx(EVP_MD_CTX *ctx, EVP_PKEY_CTX *pkctx, X509_ALGOR *sigalg, EVP_PKEY *pkey) { int rv = -1; int saltlen; const EVP_MD *mgf1md = NULL, *md = NULL; RSA_PSS_PARAMS *pss; X509_ALGOR *maskHash; /* Sanity check: make sure it is PSS */ if (OBJ_obj2nid(sigalg->algorithm) != NID_rsassaPss) { RSAerr(RSA_F_RSA_PSS_TO_CTX, RSA_R_UNSUPPORTED_SIGNATURE_TYPE); return -1; } /* Decode PSS parameters */ pss = rsa_pss_decode(sigalg, &maskHash); if (pss == NULL) { RSAerr(RSA_F_RSA_PSS_TO_CTX, RSA_R_INVALID_PSS_PARAMETERS); goto err; } mgf1md = rsa_mgf1_to_md(pss->maskGenAlgorithm, maskHash); if (!mgf1md) goto err; md = rsa_algor_to_md(pss->hashAlgorithm); if (!md) goto err; if (pss->saltLength) { saltlen = ASN1_INTEGER_get(pss->saltLength); /* * Could perform more salt length sanity checks but the main RSA * routines will trap other invalid values anyway. */ if (saltlen < 0) { RSAerr(RSA_F_RSA_PSS_TO_CTX, RSA_R_INVALID_SALT_LENGTH); goto err; } } else saltlen = 20; /* * low-level routines support only trailer field 0xbc (value 1) and * PKCS#1 says we should reject any other value anyway. */ if (pss->trailerField && ASN1_INTEGER_get(pss->trailerField) != 1) { RSAerr(RSA_F_RSA_PSS_TO_CTX, RSA_R_INVALID_TRAILER); goto err; } /* We have all parameters now set up context */ if (pkey) { if (!EVP_DigestVerifyInit(ctx, &pkctx, md, NULL, pkey)) goto err; } else { const EVP_MD *checkmd; if (EVP_PKEY_CTX_get_signature_md(pkctx, &checkmd) <= 0) goto err; if (EVP_MD_type(md) != EVP_MD_type(checkmd)) { RSAerr(RSA_F_RSA_PSS_TO_CTX, RSA_R_DIGEST_DOES_NOT_MATCH); goto err; } } if (EVP_PKEY_CTX_set_rsa_padding(pkctx, RSA_PKCS1_PSS_PADDING) <= 0) goto err; if (EVP_PKEY_CTX_set_rsa_pss_saltlen(pkctx, saltlen) <= 0) goto err; if (EVP_PKEY_CTX_set_rsa_mgf1_md(pkctx, mgf1md) <= 0) goto err; /* Carry on */ rv = 1; err: RSA_PSS_PARAMS_free(pss); if (maskHash) X509_ALGOR_free(maskHash); return rv; } #ifndef OPENSSL_NO_CMS static int rsa_cms_verify(CMS_SignerInfo *si) { int nid, nid2; X509_ALGOR *alg; EVP_PKEY_CTX *pkctx = CMS_SignerInfo_get0_pkey_ctx(si); CMS_SignerInfo_get0_algs(si, NULL, NULL, NULL, &alg); nid = OBJ_obj2nid(alg->algorithm); if (nid == NID_rsaEncryption) return 1; if (nid == NID_rsassaPss) return rsa_pss_to_ctx(NULL, pkctx, alg, NULL); /* Workaround for some implementation that use a signature OID */ if (OBJ_find_sigid_algs(nid, NULL, &nid2)) { if (nid2 == NID_rsaEncryption) return 1; } return 0; } #endif /* * Customised RSA item verification routine. This is called when a signature * is encountered requiring special handling. We currently only handle PSS. */ static int rsa_item_verify(EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn, X509_ALGOR *sigalg, ASN1_BIT_STRING *sig, EVP_PKEY *pkey) { /* Sanity check: make sure it is PSS */ if (OBJ_obj2nid(sigalg->algorithm) != NID_rsassaPss) { RSAerr(RSA_F_RSA_ITEM_VERIFY, RSA_R_UNSUPPORTED_SIGNATURE_TYPE); return -1; } if (rsa_pss_to_ctx(ctx, NULL, sigalg, pkey) > 0) { /* Carry on */ return 2; } return -1; } #ifndef OPENSSL_NO_CMS static int rsa_cms_sign(CMS_SignerInfo *si) { int pad_mode = RSA_PKCS1_PADDING; X509_ALGOR *alg; EVP_PKEY_CTX *pkctx = CMS_SignerInfo_get0_pkey_ctx(si); ASN1_STRING *os = NULL; CMS_SignerInfo_get0_algs(si, NULL, NULL, NULL, &alg); if (pkctx) { if (EVP_PKEY_CTX_get_rsa_padding(pkctx, &pad_mode) <= 0) return 0; } if (pad_mode == RSA_PKCS1_PADDING) { X509_ALGOR_set0(alg, OBJ_nid2obj(NID_rsaEncryption), V_ASN1_NULL, 0); return 1; } /* We don't support it */ if (pad_mode != RSA_PKCS1_PSS_PADDING) return 0; os = rsa_ctx_to_pss(pkctx); if (!os) return 0; X509_ALGOR_set0(alg, OBJ_nid2obj(NID_rsassaPss), V_ASN1_SEQUENCE, os); return 1; } #endif static int rsa_item_sign(EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn, X509_ALGOR *alg1, X509_ALGOR *alg2, ASN1_BIT_STRING *sig) { int pad_mode; EVP_PKEY_CTX *pkctx = ctx->pctx; if (EVP_PKEY_CTX_get_rsa_padding(pkctx, &pad_mode) <= 0) return 0; if (pad_mode == RSA_PKCS1_PADDING) return 2; if (pad_mode == RSA_PKCS1_PSS_PADDING) { ASN1_STRING *os1 = NULL; os1 = rsa_ctx_to_pss(pkctx); if (!os1) return 0; /* Duplicate parameters if we have to */ if (alg2) { ASN1_STRING *os2 = ASN1_STRING_dup(os1); if (!os2) { ASN1_STRING_free(os1); return 0; } X509_ALGOR_set0(alg2, OBJ_nid2obj(NID_rsassaPss), V_ASN1_SEQUENCE, os2); } X509_ALGOR_set0(alg1, OBJ_nid2obj(NID_rsassaPss), V_ASN1_SEQUENCE, os1); return 3; } return 2; } +#ifndef OPENSSL_NO_CMS static RSA_OAEP_PARAMS *rsa_oaep_decode(const X509_ALGOR *alg, X509_ALGOR **pmaskHash) { const unsigned char *p; int plen; RSA_OAEP_PARAMS *pss; *pmaskHash = NULL; if (!alg->parameter || alg->parameter->type != V_ASN1_SEQUENCE) return NULL; p = alg->parameter->value.sequence->data; plen = alg->parameter->value.sequence->length; pss = d2i_RSA_OAEP_PARAMS(NULL, &p, plen); if (!pss) return NULL; *pmaskHash = rsa_mgf1_decode(pss->maskGenFunc); return pss; } -#ifndef OPENSSL_NO_CMS static int rsa_cms_decrypt(CMS_RecipientInfo *ri) { EVP_PKEY_CTX *pkctx; X509_ALGOR *cmsalg; int nid; int rv = -1; unsigned char *label = NULL; int labellen = 0; const EVP_MD *mgf1md = NULL, *md = NULL; RSA_OAEP_PARAMS *oaep; X509_ALGOR *maskHash; pkctx = CMS_RecipientInfo_get0_pkey_ctx(ri); if (!pkctx) return 0; if (!CMS_RecipientInfo_ktri_get0_algs(ri, NULL, NULL, &cmsalg)) return -1; nid = OBJ_obj2nid(cmsalg->algorithm); if (nid == NID_rsaEncryption) return 1; if (nid != NID_rsaesOaep) { RSAerr(RSA_F_RSA_CMS_DECRYPT, RSA_R_UNSUPPORTED_ENCRYPTION_TYPE); return -1; } /* Decode OAEP parameters */ oaep = rsa_oaep_decode(cmsalg, &maskHash); if (oaep == NULL) { RSAerr(RSA_F_RSA_CMS_DECRYPT, RSA_R_INVALID_OAEP_PARAMETERS); goto err; } mgf1md = rsa_mgf1_to_md(oaep->maskGenFunc, maskHash); if (!mgf1md) goto err; md = rsa_algor_to_md(oaep->hashFunc); if (!md) goto err; if (oaep->pSourceFunc) { X509_ALGOR *plab = oaep->pSourceFunc; if (OBJ_obj2nid(plab->algorithm) != NID_pSpecified) { RSAerr(RSA_F_RSA_CMS_DECRYPT, RSA_R_UNSUPPORTED_LABEL_SOURCE); goto err; } if (plab->parameter->type != V_ASN1_OCTET_STRING) { RSAerr(RSA_F_RSA_CMS_DECRYPT, RSA_R_INVALID_LABEL); goto err; } label = plab->parameter->value.octet_string->data; /* Stop label being freed when OAEP parameters are freed */ plab->parameter->value.octet_string->data = NULL; labellen = plab->parameter->value.octet_string->length; } if (EVP_PKEY_CTX_set_rsa_padding(pkctx, RSA_PKCS1_OAEP_PADDING) <= 0) goto err; if (EVP_PKEY_CTX_set_rsa_oaep_md(pkctx, md) <= 0) goto err; if (EVP_PKEY_CTX_set_rsa_mgf1_md(pkctx, mgf1md) <= 0) goto err; if (EVP_PKEY_CTX_set0_rsa_oaep_label(pkctx, label, labellen) <= 0) goto err; /* Carry on */ rv = 1; err: RSA_OAEP_PARAMS_free(oaep); if (maskHash) X509_ALGOR_free(maskHash); return rv; } static int rsa_cms_encrypt(CMS_RecipientInfo *ri) { const EVP_MD *md, *mgf1md; RSA_OAEP_PARAMS *oaep = NULL; ASN1_STRING *os = NULL; X509_ALGOR *alg; EVP_PKEY_CTX *pkctx = CMS_RecipientInfo_get0_pkey_ctx(ri); int pad_mode = RSA_PKCS1_PADDING, rv = 0, labellen; unsigned char *label; CMS_RecipientInfo_ktri_get0_algs(ri, NULL, NULL, &alg); if (pkctx) { if (EVP_PKEY_CTX_get_rsa_padding(pkctx, &pad_mode) <= 0) return 0; } if (pad_mode == RSA_PKCS1_PADDING) { X509_ALGOR_set0(alg, OBJ_nid2obj(NID_rsaEncryption), V_ASN1_NULL, 0); return 1; } /* Not supported */ if (pad_mode != RSA_PKCS1_OAEP_PADDING) return 0; if (EVP_PKEY_CTX_get_rsa_oaep_md(pkctx, &md) <= 0) goto err; if (EVP_PKEY_CTX_get_rsa_mgf1_md(pkctx, &mgf1md) <= 0) goto err; labellen = EVP_PKEY_CTX_get0_rsa_oaep_label(pkctx, &label); if (labellen < 0) goto err; oaep = RSA_OAEP_PARAMS_new(); if (!oaep) goto err; if (!rsa_md_to_algor(&oaep->hashFunc, md)) goto err; if (!rsa_md_to_mgf1(&oaep->maskGenFunc, mgf1md)) goto err; if (labellen > 0) { ASN1_OCTET_STRING *los = ASN1_OCTET_STRING_new(); oaep->pSourceFunc = X509_ALGOR_new(); if (!oaep->pSourceFunc) goto err; if (!los) goto err; if (!ASN1_OCTET_STRING_set(los, label, labellen)) { ASN1_OCTET_STRING_free(los); goto err; } X509_ALGOR_set0(oaep->pSourceFunc, OBJ_nid2obj(NID_pSpecified), V_ASN1_OCTET_STRING, los); } /* create string with pss parameter encoding. */ if (!ASN1_item_pack(oaep, ASN1_ITEM_rptr(RSA_OAEP_PARAMS), &os)) goto err; X509_ALGOR_set0(alg, OBJ_nid2obj(NID_rsaesOaep), V_ASN1_SEQUENCE, os); os = NULL; rv = 1; err: if (oaep) RSA_OAEP_PARAMS_free(oaep); if (os) ASN1_STRING_free(os); return rv; } #endif const EVP_PKEY_ASN1_METHOD rsa_asn1_meths[] = { { EVP_PKEY_RSA, EVP_PKEY_RSA, ASN1_PKEY_SIGPARAM_NULL, "RSA", "OpenSSL RSA method", rsa_pub_decode, rsa_pub_encode, rsa_pub_cmp, rsa_pub_print, rsa_priv_decode, rsa_priv_encode, rsa_priv_print, int_rsa_size, rsa_bits, 0, 0, 0, 0, 0, 0, rsa_sig_print, int_rsa_free, rsa_pkey_ctrl, old_rsa_priv_decode, old_rsa_priv_encode, rsa_item_verify, rsa_item_sign}, { EVP_PKEY_RSA2, EVP_PKEY_RSA, ASN1_PKEY_ALIAS} }; Index: vendor-crypto/openssl/dist/crypto/rsa/rsa_oaep.c =================================================================== --- vendor-crypto/openssl/dist/crypto/rsa/rsa_oaep.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/rsa/rsa_oaep.c (revision 325326) @@ -1,287 +1,291 @@ /* crypto/rsa/rsa_oaep.c */ /* * Written by Ulf Moeller. This software is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. */ /* EME-OAEP as defined in RFC 2437 (PKCS #1 v2.0) */ /* * See Victor Shoup, "OAEP reconsidered," Nov. 2000, for problems with the security * proof for the original OAEP scheme, which EME-OAEP is based on. A new * proof can be found in E. Fujisaki, T. Okamoto, D. Pointcheval, J. Stern, * "RSA-OEAP is Still Alive!", Dec. 2000, . The new proof has stronger requirements * for the underlying permutation: "partial-one-wayness" instead of * one-wayness. For the RSA function, this is an equivalent notion. */ #include "constant_time_locl.h" #if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_SHA1) # include # include "cryptlib.h" # include # include # include # include # include int RSA_padding_add_PKCS1_OAEP(unsigned char *to, int tlen, const unsigned char *from, int flen, const unsigned char *param, int plen) { return RSA_padding_add_PKCS1_OAEP_mgf1(to, tlen, from, flen, param, plen, NULL, NULL); } int RSA_padding_add_PKCS1_OAEP_mgf1(unsigned char *to, int tlen, const unsigned char *from, int flen, const unsigned char *param, int plen, const EVP_MD *md, const EVP_MD *mgf1md) { int i, emlen = tlen - 1; unsigned char *db, *seed; unsigned char *dbmask, seedmask[EVP_MAX_MD_SIZE]; int mdlen; if (md == NULL) md = EVP_sha1(); if (mgf1md == NULL) mgf1md = md; mdlen = EVP_MD_size(md); if (flen > emlen - 2 * mdlen - 1) { RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_OAEP_MGF1, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); return 0; } if (emlen < 2 * mdlen + 1) { RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_OAEP_MGF1, RSA_R_KEY_SIZE_TOO_SMALL); return 0; } to[0] = 0; seed = to + 1; db = to + mdlen + 1; if (!EVP_Digest((void *)param, plen, db, NULL, md, NULL)) return 0; memset(db + mdlen, 0, emlen - flen - 2 * mdlen - 1); db[emlen - flen - mdlen - 1] = 0x01; memcpy(db + emlen - flen - mdlen, from, (unsigned int)flen); if (RAND_bytes(seed, mdlen) <= 0) return 0; # ifdef PKCS_TESTVECT memcpy(seed, "\xaa\xfd\x12\xf6\x59\xca\xe6\x34\x89\xb4\x79\xe5\x07\x6d\xde\xc2\xf0\x6c\xb5\x8f", 20); # endif dbmask = OPENSSL_malloc(emlen - mdlen); if (dbmask == NULL) { RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_OAEP_MGF1, ERR_R_MALLOC_FAILURE); return 0; } if (PKCS1_MGF1(dbmask, emlen - mdlen, seed, mdlen, mgf1md) < 0) goto err; for (i = 0; i < emlen - mdlen; i++) db[i] ^= dbmask[i]; if (PKCS1_MGF1(seedmask, mdlen, db, emlen - mdlen, mgf1md) < 0) goto err; for (i = 0; i < mdlen; i++) seed[i] ^= seedmask[i]; OPENSSL_free(dbmask); return 1; err: OPENSSL_free(dbmask); return 0; } int RSA_padding_check_PKCS1_OAEP(unsigned char *to, int tlen, const unsigned char *from, int flen, int num, const unsigned char *param, int plen) { return RSA_padding_check_PKCS1_OAEP_mgf1(to, tlen, from, flen, num, param, plen, NULL, NULL); } int RSA_padding_check_PKCS1_OAEP_mgf1(unsigned char *to, int tlen, const unsigned char *from, int flen, int num, const unsigned char *param, int plen, const EVP_MD *md, const EVP_MD *mgf1md) { int i, dblen, mlen = -1, one_index = 0, msg_index; unsigned int good, found_one_byte; const unsigned char *maskedseed, *maskeddb; /* * |em| is the encoded message, zero-padded to exactly |num| bytes: em = * Y || maskedSeed || maskedDB */ unsigned char *db = NULL, *em = NULL, seed[EVP_MAX_MD_SIZE], phash[EVP_MAX_MD_SIZE]; int mdlen; if (md == NULL) md = EVP_sha1(); if (mgf1md == NULL) mgf1md = md; mdlen = EVP_MD_size(md); if (tlen <= 0 || flen <= 0) return -1; /* * |num| is the length of the modulus; |flen| is the length of the * encoded message. Therefore, for any |from| that was obtained by * decrypting a ciphertext, we must have |flen| <= |num|. Similarly, * num < 2 * mdlen + 2 must hold for the modulus irrespective of * the ciphertext, see PKCS #1 v2.2, section 7.1.2. * This does not leak any side-channel information. */ if (num < flen || num < 2 * mdlen + 2) goto decoding_err; dblen = num - mdlen - 1; db = OPENSSL_malloc(dblen); em = OPENSSL_malloc(num); if (db == NULL || em == NULL) { RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_OAEP_MGF1, ERR_R_MALLOC_FAILURE); goto cleanup; } /* * Always do this zero-padding copy (even when num == flen) to avoid * leaking that information. The copy still leaks some side-channel * information, but it's impossible to have a fixed memory access * pattern since we can't read out of the bounds of |from|. * * TODO(emilia): Consider porting BN_bn2bin_padded from BoringSSL. */ memset(em, 0, num); memcpy(em + num - flen, from, flen); /* * The first byte must be zero, however we must not leak if this is * true. See James H. Manger, "A Chosen Ciphertext Attack on RSA * Optimal Asymmetric Encryption Padding (OAEP) [...]", CRYPTO 2001). */ good = constant_time_is_zero(em[0]); maskedseed = em + 1; maskeddb = em + 1 + mdlen; if (PKCS1_MGF1(seed, mdlen, maskeddb, dblen, mgf1md)) goto cleanup; for (i = 0; i < mdlen; i++) seed[i] ^= maskedseed[i]; if (PKCS1_MGF1(db, dblen, seed, mdlen, mgf1md)) goto cleanup; for (i = 0; i < dblen; i++) db[i] ^= maskeddb[i]; if (!EVP_Digest((void *)param, plen, phash, NULL, md, NULL)) goto cleanup; good &= constant_time_is_zero(CRYPTO_memcmp(db, phash, mdlen)); found_one_byte = 0; for (i = mdlen; i < dblen; i++) { /* * Padding consists of a number of 0-bytes, followed by a 1. */ unsigned int equals1 = constant_time_eq(db[i], 1); unsigned int equals0 = constant_time_is_zero(db[i]); one_index = constant_time_select_int(~found_one_byte & equals1, i, one_index); found_one_byte |= equals1; good &= (found_one_byte | equals0); } good &= found_one_byte; /* * At this point |good| is zero unless the plaintext was valid, * so plaintext-awareness ensures timing side-channels are no longer a * concern. */ if (!good) goto decoding_err; msg_index = one_index + 1; mlen = dblen - msg_index; if (tlen < mlen) { RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_OAEP_MGF1, RSA_R_DATA_TOO_LARGE); mlen = -1; } else { memcpy(to, db + msg_index, mlen); goto cleanup; } decoding_err: /* * To avoid chosen ciphertext attacks, the error message should not * reveal which kind of decoding error happened. */ RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_OAEP_MGF1, RSA_R_OAEP_DECODING_ERROR); cleanup: - if (db != NULL) + if (db != NULL) { + OPENSSL_cleanse(db, dblen); OPENSSL_free(db); - if (em != NULL) + } + if (em != NULL) { + OPENSSL_cleanse(em, num); OPENSSL_free(em); + } return mlen; } int PKCS1_MGF1(unsigned char *mask, long len, const unsigned char *seed, long seedlen, const EVP_MD *dgst) { long i, outlen = 0; unsigned char cnt[4]; EVP_MD_CTX c; unsigned char md[EVP_MAX_MD_SIZE]; int mdlen; int rv = -1; EVP_MD_CTX_init(&c); mdlen = EVP_MD_size(dgst); if (mdlen < 0) goto err; for (i = 0; outlen < len; i++) { cnt[0] = (unsigned char)((i >> 24) & 255); cnt[1] = (unsigned char)((i >> 16) & 255); cnt[2] = (unsigned char)((i >> 8)) & 255; cnt[3] = (unsigned char)(i & 255); if (!EVP_DigestInit_ex(&c, dgst, NULL) || !EVP_DigestUpdate(&c, seed, seedlen) || !EVP_DigestUpdate(&c, cnt, 4)) goto err; if (outlen + mdlen <= len) { if (!EVP_DigestFinal_ex(&c, mask + outlen, NULL)) goto err; outlen += mdlen; } else { if (!EVP_DigestFinal_ex(&c, md, NULL)) goto err; memcpy(mask + outlen, md, len - outlen); outlen = len; } } rv = 0; err: EVP_MD_CTX_cleanup(&c); return rv; } #endif Index: vendor-crypto/openssl/dist/crypto/rsa/rsa_pk1.c =================================================================== --- vendor-crypto/openssl/dist/crypto/rsa/rsa_pk1.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/rsa/rsa_pk1.c (revision 325326) @@ -1,275 +1,275 @@ /* crypto/rsa/rsa_pk1.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 "constant_time_locl.h" #include #include "cryptlib.h" #include #include #include int RSA_padding_add_PKCS1_type_1(unsigned char *to, int tlen, const unsigned char *from, int flen) { int j; unsigned char *p; if (flen > (tlen - RSA_PKCS1_PADDING_SIZE)) { RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_TYPE_1, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); return (0); } p = (unsigned char *)to; *(p++) = 0; *(p++) = 1; /* Private Key BT (Block Type) */ /* pad out with 0xff data */ j = tlen - 3 - flen; memset(p, 0xff, j); p += j; *(p++) = '\0'; memcpy(p, from, (unsigned int)flen); return (1); } int RSA_padding_check_PKCS1_type_1(unsigned char *to, int tlen, const unsigned char *from, int flen, int num) { int i, j; const unsigned char *p; p = from; if ((num != (flen + 1)) || (*(p++) != 01)) { RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_1, RSA_R_BLOCK_TYPE_IS_NOT_01); return (-1); } /* scan over padding data */ j = flen - 1; /* one for type. */ for (i = 0; i < j; i++) { if (*p != 0xff) { /* should decrypt to 0xff */ if (*p == 0) { p++; break; } else { RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_1, RSA_R_BAD_FIXED_HEADER_DECRYPT); return (-1); } } p++; } if (i == j) { RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_1, RSA_R_NULL_BEFORE_BLOCK_MISSING); return (-1); } if (i < 8) { RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_1, RSA_R_BAD_PAD_BYTE_COUNT); return (-1); } i++; /* Skip over the '\0' */ j -= i; if (j > tlen) { RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_1, RSA_R_DATA_TOO_LARGE); return (-1); } memcpy(to, p, (unsigned int)j); return (j); } int RSA_padding_add_PKCS1_type_2(unsigned char *to, int tlen, const unsigned char *from, int flen) { int i, j; unsigned char *p; if (flen > (tlen - 11)) { RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_TYPE_2, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); return (0); } p = (unsigned char *)to; *(p++) = 0; *(p++) = 2; /* Public Key BT (Block Type) */ /* pad out with non-zero random data */ j = tlen - 3 - flen; if (RAND_bytes(p, j) <= 0) return (0); for (i = 0; i < j; i++) { if (*p == '\0') do { if (RAND_bytes(p, 1) <= 0) return (0); } while (*p == '\0'); p++; } *(p++) = '\0'; memcpy(p, from, (unsigned int)flen); return (1); } int RSA_padding_check_PKCS1_type_2(unsigned char *to, int tlen, const unsigned char *from, int flen, int num) { int i; /* |em| is the encoded message, zero-padded to exactly |num| bytes */ unsigned char *em = NULL; unsigned int good, found_zero_byte; int zero_index = 0, msg_index, mlen = -1; if (tlen < 0 || flen < 0) return -1; /* * PKCS#1 v1.5 decryption. See "PKCS #1 v2.2: RSA Cryptography Standard", * section 7.2.2. */ if (flen > num) goto err; if (num < 11) goto err; em = OPENSSL_malloc(num); if (em == NULL) { RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_2, ERR_R_MALLOC_FAILURE); return -1; } memset(em, 0, num); /* * Always do this zero-padding copy (even when num == flen) to avoid * leaking that information. The copy still leaks some side-channel * information, but it's impossible to have a fixed memory access * pattern since we can't read out of the bounds of |from|. * * TODO(emilia): Consider porting BN_bn2bin_padded from BoringSSL. */ memcpy(em + num - flen, from, flen); good = constant_time_is_zero(em[0]); good &= constant_time_eq(em[1], 2); found_zero_byte = 0; for (i = 2; i < num; i++) { unsigned int equals0 = constant_time_is_zero(em[i]); zero_index = constant_time_select_int(~found_zero_byte & equals0, i, zero_index); found_zero_byte |= equals0; } /* * PS must be at least 8 bytes long, and it starts two bytes into |em|. * If we never found a 0-byte, then |zero_index| is 0 and the check * also fails. */ good &= constant_time_ge((unsigned int)(zero_index), 2 + 8); /* * Skip the zero byte. This is incorrect if we never found a zero-byte * but in this case we also do not copy the message out. */ msg_index = zero_index + 1; mlen = num - msg_index; /* * For good measure, do this check in constant time as well; it could * leak something if |tlen| was assuming valid padding. */ good &= constant_time_ge((unsigned int)(tlen), (unsigned int)(mlen)); /* * We can't continue in constant-time because we need to copy the result * and we cannot fake its length. This unavoidably leaks timing * information at the API boundary. - * TODO(emilia): this could be addressed at the call site, - * see BoringSSL commit 0aa0767340baf925bda4804882aab0cb974b2d26. */ if (!good) { mlen = -1; goto err; } memcpy(to, em + msg_index, mlen); err: - if (em != NULL) + if (em != NULL) { + OPENSSL_cleanse(em, num); OPENSSL_free(em); + } if (mlen == -1) RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_2, RSA_R_PKCS_DECODING_ERROR); return mlen; } Index: vendor-crypto/openssl/dist/crypto/rsa/rsa_pmeth.c =================================================================== --- vendor-crypto/openssl/dist/crypto/rsa/rsa_pmeth.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/rsa/rsa_pmeth.c (revision 325326) @@ -1,785 +1,778 @@ /* 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) +static int pkey_fips_check_rsa(const RSA *rsa, const EVP_MD **pmd, + const EVP_MD **pmgf1md) { - 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)) + if (*pmd != NULL) { + *pmd = FIPS_get_digestbynid(EVP_MD_type(*pmd)); + if (*pmd == NULL || !((*pmd)->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)) + if (*pmgf1md != NULL) { + *pmgf1md = FIPS_get_digestbynid(EVP_MD_type(*pmgf1md)); + if (*pmgf1md == NULL || !((*pmgf1md)->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; + const EVP_MD *md = rctx->md; + const EVP_MD *mgf1md = rctx->mgf1md; #ifdef OPENSSL_FIPS - ret = pkey_fips_check_ctx(ctx); + ret = pkey_fips_check_rsa(rsa, &md, &mgf1md); 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)) { + if (md != NULL) { + if (tbslen != (size_t)EVP_MD_size(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); + ret = FIPS_rsa_sign_digest(rsa, tbs, tbslen, md, rctx->pad_mode, + rctx->saltlen, mgf1md, sig, &slen); if (ret > 0) *siglen = slen; else *siglen = 0; return ret; } #endif - if (EVP_MD_type(rctx->md) == NID_mdc2) { + if (EVP_MD_type(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); + 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)); + rctx->tbuf[tbslen] = RSA_X931_hash_id(EVP_MD_type(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); + ret = RSA_sign(EVP_MD_type(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)) + if (!RSA_padding_add_PKCS1_PSS_mgf1(rsa, rctx->tbuf, tbs, + md, 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; + const EVP_MD *md = rctx->md; + const EVP_MD *mgf1md = rctx->mgf1md; size_t rslen; + #ifdef OPENSSL_FIPS - int rv; - rv = pkey_fips_check_ctx(ctx); + int rv = pkey_fips_check_rsa(rsa, &md, &mgf1md); + if (rv < 0) { RSAerr(RSA_F_PKEY_RSA_VERIFY, RSA_R_OPERATION_NOT_ALLOWED_IN_FIPS_MODE); return -1; } #endif - if (rctx->md) { + if (md != NULL) { #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); + return FIPS_rsa_verify_digest(rsa, tbs, tbslen, md, rctx->pad_mode, + rctx->saltlen, mgf1md, sig, siglen); } #endif if (rctx->pad_mode == RSA_PKCS1_PADDING) - return RSA_verify(EVP_MD_type(rctx->md), tbs, tbslen, + return RSA_verify(EVP_MD_type(md), tbs, tbslen, sig, siglen, rsa); - if (tbslen != (size_t)EVP_MD_size(rctx->md)) { + if (tbslen != (size_t)EVP_MD_size(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, + ret = RSA_verify_PKCS1_PSS_mgf1(rsa, tbs, md, 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) { 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; 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/ui/ui_lib.c =================================================================== --- vendor-crypto/openssl/dist/crypto/ui/ui_lib.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/ui/ui_lib.c (revision 325326) @@ -1,877 +1,878 @@ /* 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_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/whrlpool/wp_dgst.c =================================================================== --- vendor-crypto/openssl/dist/crypto/whrlpool/wp_dgst.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/whrlpool/wp_dgst.c (revision 325326) @@ -1,258 +1,258 @@ /** * The Whirlpool hashing function. * *

* References * *

* The Whirlpool algorithm was developed by * Paulo S. L. M. Barreto and * Vincent Rijmen. * * See * P.S.L.M. Barreto, V. Rijmen, * ``The Whirlpool hashing function,'' * NESSIE submission, 2000 (tweaked version, 2001), * * * Based on "@version 3.0 (2003.03.12)" by Paulo S.L.M. Barreto and * Vincent Rijmen. Lookup "reference implementations" on * * * ============================================================================= * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''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 AUTHORS 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. * */ /* * OpenSSL-specific implementation notes. * * WHIRLPOOL_Update as well as one-stroke WHIRLPOOL both expect * number of *bytes* as input length argument. Bit-oriented routine * as specified by authors is called WHIRLPOOL_BitUpdate[!] and * does not have one-stroke counterpart. * * WHIRLPOOL_BitUpdate implements byte-oriented loop, essentially * to serve WHIRLPOOL_Update. This is done for performance. * * Unlike authors' reference implementation, block processing * routine whirlpool_block is designed to operate on multi-block * input. This is done for perfomance. */ #include #include "wp_locl.h" #include #include fips_md_init(WHIRLPOOL) { memset(c, 0, sizeof(*c)); return (1); } int WHIRLPOOL_Update(WHIRLPOOL_CTX *c, const void *_inp, size_t bytes) { /* * Well, largest suitable chunk size actually is * (1<<(sizeof(size_t)*8-3))-64, but below number is large enough for not * to care about excessive calls to WHIRLPOOL_BitUpdate... */ size_t chunk = ((size_t)1) << (sizeof(size_t) * 8 - 4); const unsigned char *inp = _inp; while (bytes >= chunk) { WHIRLPOOL_BitUpdate(c, inp, chunk * 8); bytes -= chunk; inp += chunk; } if (bytes) WHIRLPOOL_BitUpdate(c, inp, bytes * 8); return (1); } void WHIRLPOOL_BitUpdate(WHIRLPOOL_CTX *c, const void *_inp, size_t bits) { size_t n; unsigned int bitoff = c->bitoff, bitrem = bitoff % 8, inpgap = (8 - (unsigned int)bits % 8) & 7; const unsigned char *inp = _inp; /* * This 256-bit increment procedure relies on the size_t being natural * size of CPU register, so that we don't have to mask the value in order * to detect overflows. */ c->bitlen[0] += bits; if (c->bitlen[0] < bits) { /* overflow */ n = 1; do { c->bitlen[n]++; } while (c->bitlen[n] == 0 && ++n < (WHIRLPOOL_COUNTER / sizeof(size_t))); } #ifndef OPENSSL_SMALL_FOOTPRINT reconsider: if (inpgap == 0 && bitrem == 0) { /* byte-oriented loop */ while (bits) { if (bitoff == 0 && (n = bits / WHIRLPOOL_BBLOCK)) { whirlpool_block(c, inp, n); inp += n * WHIRLPOOL_BBLOCK / 8; bits %= WHIRLPOOL_BBLOCK; } else { unsigned int byteoff = bitoff / 8; bitrem = WHIRLPOOL_BBLOCK - bitoff; /* re-use bitrem */ if (bits >= bitrem) { bits -= bitrem; bitrem /= 8; memcpy(c->data + byteoff, inp, bitrem); inp += bitrem; whirlpool_block(c, c->data, 1); bitoff = 0; } else { memcpy(c->data + byteoff, inp, bits / 8); bitoff += (unsigned int)bits; bits = 0; } c->bitoff = bitoff; } } } else /* bit-oriented loop */ #endif { /*- inp | +-------+-------+------- ||||||||||||||||||||| +-------+-------+------- +-------+-------+-------+-------+------- |||||||||||||| c->data +-------+-------+-------+-------+------- | c->bitoff/8 */ while (bits) { unsigned int byteoff = bitoff / 8; unsigned char b; #ifndef OPENSSL_SMALL_FOOTPRINT if (bitrem == inpgap) { c->data[byteoff++] |= inp[0] & (0xff >> inpgap); inpgap = 8 - inpgap; bitoff += inpgap; bitrem = 0; /* bitoff%8 */ bits -= inpgap; inpgap = 0; /* bits%8 */ inp++; if (bitoff == WHIRLPOOL_BBLOCK) { whirlpool_block(c, c->data, 1); bitoff = 0; } c->bitoff = bitoff; goto reconsider; } else #endif - if (bits >= 8) { + if (bits > 8) { b = ((inp[0] << inpgap) | (inp[1] >> (8 - inpgap))); b &= 0xff; if (bitrem) c->data[byteoff++] |= b >> bitrem; else c->data[byteoff++] = b; bitoff += 8; bits -= 8; inp++; if (bitoff >= WHIRLPOOL_BBLOCK) { whirlpool_block(c, c->data, 1); byteoff = 0; bitoff %= WHIRLPOOL_BBLOCK; } if (bitrem) c->data[byteoff] = b << (8 - bitrem); - } else { /* remaining less than 8 bits */ + } else { /* remaining less than or equal to 8 bits */ b = (inp[0] << inpgap) & 0xff; if (bitrem) c->data[byteoff++] |= b >> bitrem; else c->data[byteoff++] = b; bitoff += (unsigned int)bits; if (bitoff == WHIRLPOOL_BBLOCK) { whirlpool_block(c, c->data, 1); byteoff = 0; bitoff %= WHIRLPOOL_BBLOCK; } if (bitrem) c->data[byteoff] = b << (8 - bitrem); bits = 0; } c->bitoff = bitoff; } } } int WHIRLPOOL_Final(unsigned char *md, WHIRLPOOL_CTX *c) { unsigned int bitoff = c->bitoff, byteoff = bitoff / 8; size_t i, j, v; unsigned char *p; bitoff %= 8; if (bitoff) c->data[byteoff] |= 0x80 >> bitoff; else c->data[byteoff] = 0x80; byteoff++; /* pad with zeros */ if (byteoff > (WHIRLPOOL_BBLOCK / 8 - WHIRLPOOL_COUNTER)) { if (byteoff < WHIRLPOOL_BBLOCK / 8) memset(&c->data[byteoff], 0, WHIRLPOOL_BBLOCK / 8 - byteoff); whirlpool_block(c, c->data, 1); byteoff = 0; } if (byteoff < (WHIRLPOOL_BBLOCK / 8 - WHIRLPOOL_COUNTER)) memset(&c->data[byteoff], 0, (WHIRLPOOL_BBLOCK / 8 - WHIRLPOOL_COUNTER) - byteoff); /* smash 256-bit c->bitlen in big-endian order */ p = &c->data[WHIRLPOOL_BBLOCK / 8 - 1]; /* last byte in c->data */ for (i = 0; i < WHIRLPOOL_COUNTER / sizeof(size_t); i++) for (v = c->bitlen[i], j = 0; j < sizeof(size_t); j++, v >>= 8) *p-- = (unsigned char)(v & 0xff); whirlpool_block(c, c->data, 1); if (md) { memcpy(md, c->H.c, WHIRLPOOL_DIGEST_LENGTH); OPENSSL_cleanse(c, sizeof(*c)); return (1); } return (0); } unsigned char *WHIRLPOOL(const void *inp, size_t bytes, unsigned char *md) { WHIRLPOOL_CTX ctx; static unsigned char m[WHIRLPOOL_DIGEST_LENGTH]; if (md == NULL) md = m; WHIRLPOOL_Init(&ctx); WHIRLPOOL_Update(&ctx, inp, bytes); WHIRLPOOL_Final(md, &ctx); return (md); } Index: vendor-crypto/openssl/dist/crypto/x509/by_dir.c =================================================================== --- vendor-crypto/openssl/dist/crypto/x509/by_dir.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/x509/by_dir.c (revision 325326) @@ -1,440 +1,441 @@ /* crypto/x509/by_dir.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" #ifndef NO_SYS_TYPES_H # include #endif #ifndef OPENSSL_NO_POSIX_IO # include #endif #include #include typedef struct lookup_dir_hashes_st { unsigned long hash; int suffix; } BY_DIR_HASH; typedef struct lookup_dir_entry_st { char *dir; int dir_type; STACK_OF(BY_DIR_HASH) *hashes; } BY_DIR_ENTRY; typedef struct lookup_dir_st { BUF_MEM *buffer; STACK_OF(BY_DIR_ENTRY) *dirs; } BY_DIR; DECLARE_STACK_OF(BY_DIR_HASH) DECLARE_STACK_OF(BY_DIR_ENTRY) static int dir_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl, char **ret); static int new_dir(X509_LOOKUP *lu); static void free_dir(X509_LOOKUP *lu); static int add_cert_dir(BY_DIR *ctx, const char *dir, int type); static int get_cert_by_subject(X509_LOOKUP *xl, int type, X509_NAME *name, X509_OBJECT *ret); X509_LOOKUP_METHOD x509_dir_lookup = { "Load certs from files in a directory", new_dir, /* new */ free_dir, /* free */ NULL, /* init */ NULL, /* shutdown */ dir_ctrl, /* ctrl */ get_cert_by_subject, /* get_by_subject */ NULL, /* get_by_issuer_serial */ NULL, /* get_by_fingerprint */ NULL, /* get_by_alias */ }; X509_LOOKUP_METHOD *X509_LOOKUP_hash_dir(void) { return (&x509_dir_lookup); } static int dir_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl, char **retp) { int ret = 0; BY_DIR *ld; char *dir = NULL; ld = (BY_DIR *)ctx->method_data; switch (cmd) { case X509_L_ADD_DIR: if (argl == X509_FILETYPE_DEFAULT) { dir = (char *)getenv(X509_get_default_cert_dir_env()); if (dir) ret = add_cert_dir(ld, dir, X509_FILETYPE_PEM); else ret = add_cert_dir(ld, X509_get_default_cert_dir(), X509_FILETYPE_PEM); if (!ret) { X509err(X509_F_DIR_CTRL, X509_R_LOADING_CERT_DIR); } } else ret = add_cert_dir(ld, argp, (int)argl); break; } return (ret); } static int new_dir(X509_LOOKUP *lu) { BY_DIR *a; if ((a = (BY_DIR *)OPENSSL_malloc(sizeof(BY_DIR))) == NULL) return (0); if ((a->buffer = BUF_MEM_new()) == NULL) { OPENSSL_free(a); return (0); } a->dirs = NULL; lu->method_data = (char *)a; return (1); } static void by_dir_hash_free(BY_DIR_HASH *hash) { OPENSSL_free(hash); } static int by_dir_hash_cmp(const BY_DIR_HASH *const *a, const BY_DIR_HASH *const *b) { if ((*a)->hash > (*b)->hash) return 1; if ((*a)->hash < (*b)->hash) return -1; return 0; } static void by_dir_entry_free(BY_DIR_ENTRY *ent) { if (ent->dir) OPENSSL_free(ent->dir); if (ent->hashes) sk_BY_DIR_HASH_pop_free(ent->hashes, by_dir_hash_free); OPENSSL_free(ent); } static void free_dir(X509_LOOKUP *lu) { BY_DIR *a; a = (BY_DIR *)lu->method_data; if (a->dirs != NULL) sk_BY_DIR_ENTRY_pop_free(a->dirs, by_dir_entry_free); if (a->buffer != NULL) BUF_MEM_free(a->buffer); OPENSSL_free(a); } static int add_cert_dir(BY_DIR *ctx, const char *dir, int type) { int j, len; const char *s, *ss, *p; if (dir == NULL || !*dir) { X509err(X509_F_ADD_CERT_DIR, X509_R_INVALID_DIRECTORY); return 0; } s = dir; p = s; do { if ((*p == LIST_SEPARATOR_CHAR) || (*p == '\0')) { BY_DIR_ENTRY *ent; ss = s; s = p + 1; len = (int)(p - ss); if (len == 0) continue; for (j = 0; j < sk_BY_DIR_ENTRY_num(ctx->dirs); j++) { ent = sk_BY_DIR_ENTRY_value(ctx->dirs, j); if (strlen(ent->dir) == (size_t)len && strncmp(ent->dir, ss, (unsigned int)len) == 0) break; } if (j < sk_BY_DIR_ENTRY_num(ctx->dirs)) continue; if (ctx->dirs == NULL) { ctx->dirs = sk_BY_DIR_ENTRY_new_null(); if (!ctx->dirs) { X509err(X509_F_ADD_CERT_DIR, ERR_R_MALLOC_FAILURE); return 0; } } ent = OPENSSL_malloc(sizeof(BY_DIR_ENTRY)); if (!ent) return 0; ent->dir_type = type; ent->hashes = sk_BY_DIR_HASH_new(by_dir_hash_cmp); ent->dir = OPENSSL_malloc((unsigned int)len + 1); if (!ent->dir || !ent->hashes) { by_dir_entry_free(ent); return 0; } strncpy(ent->dir, ss, (unsigned int)len); ent->dir[len] = '\0'; if (!sk_BY_DIR_ENTRY_push(ctx->dirs, ent)) { by_dir_entry_free(ent); return 0; } } } while (*p++ != '\0'); return 1; } static int get_cert_by_subject(X509_LOOKUP *xl, int type, X509_NAME *name, X509_OBJECT *ret) { BY_DIR *ctx; union { struct { X509 st_x509; X509_CINF st_x509_cinf; } x509; struct { X509_CRL st_crl; X509_CRL_INFO st_crl_info; } crl; } data; int ok = 0; int i, j, k; unsigned long h; BUF_MEM *b = NULL; X509_OBJECT stmp, *tmp; const char *postfix = ""; if (name == NULL) return (0); stmp.type = type; if (type == X509_LU_X509) { data.x509.st_x509.cert_info = &data.x509.st_x509_cinf; data.x509.st_x509_cinf.subject = name; stmp.data.x509 = &data.x509.st_x509; postfix = ""; } else if (type == X509_LU_CRL) { data.crl.st_crl.crl = &data.crl.st_crl_info; data.crl.st_crl_info.issuer = name; stmp.data.crl = &data.crl.st_crl; postfix = "r"; } else { X509err(X509_F_GET_CERT_BY_SUBJECT, X509_R_WRONG_LOOKUP_TYPE); goto finish; } if ((b = BUF_MEM_new()) == NULL) { X509err(X509_F_GET_CERT_BY_SUBJECT, ERR_R_BUF_LIB); goto finish; } ctx = (BY_DIR *)xl->method_data; h = X509_NAME_hash(name); for (i = 0; i < sk_BY_DIR_ENTRY_num(ctx->dirs); i++) { BY_DIR_ENTRY *ent; int idx; BY_DIR_HASH htmp, *hent; ent = sk_BY_DIR_ENTRY_value(ctx->dirs, i); j = strlen(ent->dir) + 1 + 8 + 6 + 1 + 1; if (!BUF_MEM_grow(b, j)) { X509err(X509_F_GET_CERT_BY_SUBJECT, ERR_R_MALLOC_FAILURE); goto finish; } if (type == X509_LU_CRL && ent->hashes) { htmp.hash = h; CRYPTO_r_lock(CRYPTO_LOCK_X509_STORE); idx = sk_BY_DIR_HASH_find(ent->hashes, &htmp); if (idx >= 0) { hent = sk_BY_DIR_HASH_value(ent->hashes, idx); k = hent->suffix; } else { hent = NULL; k = 0; } CRYPTO_r_unlock(CRYPTO_LOCK_X509_STORE); } else { k = 0; hent = NULL; } for (;;) { char c = '/'; #ifdef OPENSSL_SYS_VMS c = ent->dir[strlen(ent->dir) - 1]; if (c != ':' && c != '>' && c != ']') { /* * If no separator is present, we assume the directory * specifier is a logical name, and add a colon. We really * should use better VMS routines for merging things like * this, but this will do for now... -- Richard Levitte */ c = ':'; } else { c = '\0'; } #endif if (c == '\0') { /* * This is special. When c == '\0', no directory separator * should be added. */ BIO_snprintf(b->data, b->max, "%s%08lx.%s%d", ent->dir, h, postfix, k); } else { BIO_snprintf(b->data, b->max, "%s%c%08lx.%s%d", ent->dir, c, h, postfix, k); } #ifndef OPENSSL_NO_POSIX_IO # ifdef _WIN32 # define stat _stat # endif { struct stat st; if (stat(b->data, &st) < 0) break; } #endif /* found one. */ if (type == X509_LU_X509) { if ((X509_load_cert_file(xl, b->data, ent->dir_type)) == 0) break; } else if (type == X509_LU_CRL) { if ((X509_load_crl_file(xl, b->data, ent->dir_type)) == 0) break; } /* else case will caught higher up */ k++; } /* * we have added it to the cache so now pull it out again */ CRYPTO_w_lock(CRYPTO_LOCK_X509_STORE); j = sk_X509_OBJECT_find(xl->store_ctx->objs, &stmp); if (j != -1) tmp = sk_X509_OBJECT_value(xl->store_ctx->objs, j); else tmp = NULL; CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE); /* If a CRL, update the last file suffix added for this */ if (type == X509_LU_CRL) { CRYPTO_w_lock(CRYPTO_LOCK_X509_STORE); /* * Look for entry again in case another thread added an entry * first. */ if (!hent) { htmp.hash = h; idx = sk_BY_DIR_HASH_find(ent->hashes, &htmp); if (idx >= 0) hent = sk_BY_DIR_HASH_value(ent->hashes, idx); } if (!hent) { hent = OPENSSL_malloc(sizeof(BY_DIR_HASH)); if (hent == NULL) { + CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE); X509err(X509_F_GET_CERT_BY_SUBJECT, ERR_R_MALLOC_FAILURE); goto finish; } hent->hash = h; hent->suffix = k; if (!sk_BY_DIR_HASH_push(ent->hashes, hent)) { CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE); OPENSSL_free(hent); ok = 0; goto finish; } } else if (hent->suffix < k) hent->suffix = k; CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE); } if (tmp != NULL) { ok = 1; ret->type = tmp->type; memcpy(&ret->data, &tmp->data, sizeof(ret->data)); /* * If we were going to up the reference count, we would need to * do it on a perl 'type' basis */ /*- CRYPTO_add(&tmp->data.x509->references,1, CRYPTO_LOCK_X509);*/ goto finish; } } finish: if (b != NULL) BUF_MEM_free(b); return (ok); } Index: vendor-crypto/openssl/dist/crypto/x509/by_file.c =================================================================== --- vendor-crypto/openssl/dist/crypto/x509/by_file.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/x509/by_file.c (revision 325326) @@ -1,277 +1,277 @@ /* crypto/x509/by_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.] */ #include #include #include #include "cryptlib.h" #include #include #include #include #ifndef OPENSSL_NO_STDIO static int by_file_ctrl(X509_LOOKUP *ctx, int cmd, const char *argc, long argl, char **ret); X509_LOOKUP_METHOD x509_file_lookup = { "Load file into cache", NULL, /* new */ NULL, /* free */ NULL, /* init */ NULL, /* shutdown */ by_file_ctrl, /* ctrl */ NULL, /* get_by_subject */ NULL, /* get_by_issuer_serial */ NULL, /* get_by_fingerprint */ NULL, /* get_by_alias */ }; X509_LOOKUP_METHOD *X509_LOOKUP_file(void) { return (&x509_file_lookup); } static int by_file_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl, char **ret) { int ok = 0; - char *file; + const char *file; switch (cmd) { case X509_L_FILE_LOAD: if (argl == X509_FILETYPE_DEFAULT) { - file = (char *)getenv(X509_get_default_cert_file_env()); + file = getenv(X509_get_default_cert_file_env()); if (file) ok = (X509_load_cert_crl_file(ctx, file, X509_FILETYPE_PEM) != 0); else ok = (X509_load_cert_crl_file (ctx, X509_get_default_cert_file(), X509_FILETYPE_PEM) != 0); if (!ok) { X509err(X509_F_BY_FILE_CTRL, X509_R_LOADING_DEFAULTS); } } else { if (argl == X509_FILETYPE_PEM) ok = (X509_load_cert_crl_file(ctx, argp, X509_FILETYPE_PEM) != 0); else ok = (X509_load_cert_file(ctx, argp, (int)argl) != 0); } break; } return (ok); } int X509_load_cert_file(X509_LOOKUP *ctx, const char *file, int type) { int ret = 0; BIO *in = NULL; int i, count = 0; X509 *x = NULL; if (file == NULL) return (1); in = BIO_new(BIO_s_file_internal()); if ((in == NULL) || (BIO_read_filename(in, file) <= 0)) { X509err(X509_F_X509_LOAD_CERT_FILE, ERR_R_SYS_LIB); goto err; } if (type == X509_FILETYPE_PEM) { for (;;) { - x = PEM_read_bio_X509_AUX(in, NULL, NULL, NULL); + x = PEM_read_bio_X509_AUX(in, NULL, NULL, ""); if (x == NULL) { if ((ERR_GET_REASON(ERR_peek_last_error()) == PEM_R_NO_START_LINE) && (count > 0)) { ERR_clear_error(); break; } else { X509err(X509_F_X509_LOAD_CERT_FILE, ERR_R_PEM_LIB); goto err; } } i = X509_STORE_add_cert(ctx->store_ctx, x); if (!i) goto err; count++; X509_free(x); x = NULL; } ret = count; } else if (type == X509_FILETYPE_ASN1) { x = d2i_X509_bio(in, NULL); if (x == NULL) { X509err(X509_F_X509_LOAD_CERT_FILE, ERR_R_ASN1_LIB); goto err; } i = X509_STORE_add_cert(ctx->store_ctx, x); if (!i) goto err; ret = i; } else { X509err(X509_F_X509_LOAD_CERT_FILE, X509_R_BAD_X509_FILETYPE); goto err; } err: if (x != NULL) X509_free(x); if (in != NULL) BIO_free(in); return (ret); } int X509_load_crl_file(X509_LOOKUP *ctx, const char *file, int type) { int ret = 0; BIO *in = NULL; int i, count = 0; X509_CRL *x = NULL; if (file == NULL) return (1); in = BIO_new(BIO_s_file_internal()); if ((in == NULL) || (BIO_read_filename(in, file) <= 0)) { X509err(X509_F_X509_LOAD_CRL_FILE, ERR_R_SYS_LIB); goto err; } if (type == X509_FILETYPE_PEM) { for (;;) { - x = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL); + x = PEM_read_bio_X509_CRL(in, NULL, NULL, ""); if (x == NULL) { if ((ERR_GET_REASON(ERR_peek_last_error()) == PEM_R_NO_START_LINE) && (count > 0)) { ERR_clear_error(); break; } else { X509err(X509_F_X509_LOAD_CRL_FILE, ERR_R_PEM_LIB); goto err; } } i = X509_STORE_add_crl(ctx->store_ctx, x); if (!i) goto err; count++; X509_CRL_free(x); x = NULL; } ret = count; } else if (type == X509_FILETYPE_ASN1) { x = d2i_X509_CRL_bio(in, NULL); if (x == NULL) { X509err(X509_F_X509_LOAD_CRL_FILE, ERR_R_ASN1_LIB); goto err; } i = X509_STORE_add_crl(ctx->store_ctx, x); if (!i) goto err; ret = i; } else { X509err(X509_F_X509_LOAD_CRL_FILE, X509_R_BAD_X509_FILETYPE); goto err; } err: if (x != NULL) X509_CRL_free(x); if (in != NULL) BIO_free(in); return (ret); } int X509_load_cert_crl_file(X509_LOOKUP *ctx, const char *file, int type) { STACK_OF(X509_INFO) *inf; X509_INFO *itmp; BIO *in; int i, count = 0; if (type != X509_FILETYPE_PEM) return X509_load_cert_file(ctx, file, type); in = BIO_new_file(file, "r"); if (!in) { X509err(X509_F_X509_LOAD_CERT_CRL_FILE, ERR_R_SYS_LIB); return 0; } - inf = PEM_X509_INFO_read_bio(in, NULL, NULL, NULL); + inf = PEM_X509_INFO_read_bio(in, NULL, NULL, ""); BIO_free(in); if (!inf) { X509err(X509_F_X509_LOAD_CERT_CRL_FILE, ERR_R_PEM_LIB); return 0; } for (i = 0; i < sk_X509_INFO_num(inf); i++) { itmp = sk_X509_INFO_value(inf, i); if (itmp->x509) { X509_STORE_add_cert(ctx->store_ctx, itmp->x509); count++; } if (itmp->crl) { X509_STORE_add_crl(ctx->store_ctx, itmp->crl); count++; } } sk_X509_INFO_pop_free(inf, X509_INFO_free); return count; } #endif /* OPENSSL_NO_STDIO */ Index: vendor-crypto/openssl/dist/crypto/x509v3/pcy_tree.c =================================================================== --- vendor-crypto/openssl/dist/crypto/x509v3/pcy_tree.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/x509v3/pcy_tree.c (revision 325326) @@ -1,831 +1,835 @@ /* pcy_tree.c */ /* * Written by Dr Stephen N Henson (steve@openssl.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 * 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 "cryptlib.h" #include #include #include "pcy_int.h" /* * Enable this to print out the complete policy tree at various point during * evaluation. */ /* * #define OPENSSL_POLICY_DEBUG */ #ifdef OPENSSL_POLICY_DEBUG static void expected_print(BIO *err, X509_POLICY_LEVEL *lev, X509_POLICY_NODE *node, int indent) { if ((lev->flags & X509_V_FLAG_INHIBIT_MAP) || !(node->data->flags & POLICY_DATA_FLAG_MAP_MASK)) BIO_puts(err, " Not Mapped\n"); else { int i; STACK_OF(ASN1_OBJECT) *pset = node->data->expected_policy_set; ASN1_OBJECT *oid; BIO_puts(err, " Expected: "); for (i = 0; i < sk_ASN1_OBJECT_num(pset); i++) { oid = sk_ASN1_OBJECT_value(pset, i); if (i) BIO_puts(err, ", "); i2a_ASN1_OBJECT(err, oid); } BIO_puts(err, "\n"); } } static void tree_print(char *str, X509_POLICY_TREE *tree, X509_POLICY_LEVEL *curr) { X509_POLICY_LEVEL *plev; X509_POLICY_NODE *node; int i; BIO *err; err = BIO_new_fp(stderr, BIO_NOCLOSE); if (!curr) curr = tree->levels + tree->nlevel; else curr++; BIO_printf(err, "Level print after %s\n", str); BIO_printf(err, "Printing Up to Level %ld\n", curr - tree->levels); for (plev = tree->levels; plev != curr; plev++) { BIO_printf(err, "Level %ld, flags = %x\n", plev - tree->levels, plev->flags); for (i = 0; i < sk_X509_POLICY_NODE_num(plev->nodes); i++) { node = sk_X509_POLICY_NODE_value(plev->nodes, i); X509_POLICY_NODE_print(err, node, 2); expected_print(err, plev, node, 2); BIO_printf(err, " Flags: %x\n", node->data->flags); } if (plev->anyPolicy) X509_POLICY_NODE_print(err, plev->anyPolicy, 2); } BIO_free(err); } #else # define tree_print(a,b,c) /* */ #endif /*- * Initialize policy tree. Return values: * 0 Some internal error occurred. * -1 Inconsistent or invalid extensions in certificates. * 1 Tree initialized OK. * 2 Policy tree is empty. * 5 Tree OK and requireExplicitPolicy true. * 6 Tree empty and requireExplicitPolicy true. */ static int tree_init(X509_POLICY_TREE **ptree, STACK_OF(X509) *certs, unsigned int flags) { X509_POLICY_TREE *tree; X509_POLICY_LEVEL *level; const X509_POLICY_CACHE *cache; X509_POLICY_DATA *data = NULL; X509 *x; int ret = 1; int i, n; int explicit_policy; int any_skip; int map_skip; *ptree = NULL; n = sk_X509_num(certs); #if 0 /* Disable policy mapping for now... */ flags |= X509_V_FLAG_INHIBIT_MAP; #endif if (flags & X509_V_FLAG_EXPLICIT_POLICY) explicit_policy = 0; else explicit_policy = n + 1; if (flags & X509_V_FLAG_INHIBIT_ANY) any_skip = 0; else any_skip = n + 1; if (flags & X509_V_FLAG_INHIBIT_MAP) map_skip = 0; else map_skip = n + 1; /* Can't do anything with just a trust anchor */ if (n == 1) return 1; /* * First setup policy cache in all certificates apart from the trust * anchor. Note any bad cache results on the way. Also can calculate * explicit_policy value at this point. */ for (i = n - 2; i >= 0; i--) { x = sk_X509_value(certs, i); X509_check_purpose(x, -1, -1); cache = policy_cache_set(x); /* If cache NULL something bad happened: return immediately */ if (cache == NULL) return 0; /* * If inconsistent extensions keep a note of it but continue */ if (x->ex_flags & EXFLAG_INVALID_POLICY) ret = -1; /* * Otherwise if we have no data (hence no CertificatePolicies) and * haven't already set an inconsistent code note it. */ else if ((ret == 1) && !cache->data) ret = 2; if (explicit_policy > 0) { if (!(x->ex_flags & EXFLAG_SI)) explicit_policy--; if ((cache->explicit_skip != -1) && (cache->explicit_skip < explicit_policy)) explicit_policy = cache->explicit_skip; } } if (ret != 1) { if (ret == 2 && !explicit_policy) return 6; return ret; } /* If we get this far initialize the tree */ tree = OPENSSL_malloc(sizeof(X509_POLICY_TREE)); if (!tree) return 0; tree->flags = 0; tree->levels = OPENSSL_malloc(sizeof(X509_POLICY_LEVEL) * n); tree->nlevel = 0; tree->extra_data = NULL; tree->auth_policies = NULL; tree->user_policies = NULL; if (!tree->levels) { OPENSSL_free(tree); return 0; } memset(tree->levels, 0, n * sizeof(X509_POLICY_LEVEL)); tree->nlevel = n; level = tree->levels; /* Root data: initialize to anyPolicy */ data = policy_data_new(NULL, OBJ_nid2obj(NID_any_policy), 0); if (!data || !level_add_node(level, data, NULL, tree)) goto bad_tree; for (i = n - 2; i >= 0; i--) { level++; x = sk_X509_value(certs, i); cache = policy_cache_set(x); CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509); level->cert = x; if (!cache->anyPolicy) level->flags |= X509_V_FLAG_INHIBIT_ANY; /* Determine inhibit any and inhibit map flags */ if (any_skip == 0) { /* * Any matching allowed if certificate is self issued and not the * last in the chain. */ if (!(x->ex_flags & EXFLAG_SI) || (i == 0)) level->flags |= X509_V_FLAG_INHIBIT_ANY; } else { if (!(x->ex_flags & EXFLAG_SI)) any_skip--; if ((cache->any_skip >= 0) && (cache->any_skip < any_skip)) any_skip = cache->any_skip; } if (map_skip == 0) level->flags |= X509_V_FLAG_INHIBIT_MAP; else { if (!(x->ex_flags & EXFLAG_SI)) map_skip--; if ((cache->map_skip >= 0) && (cache->map_skip < map_skip)) map_skip = cache->map_skip; } } *ptree = tree; if (explicit_policy) return 1; else return 5; bad_tree: X509_policy_tree_free(tree); return 0; } static int tree_link_matching_nodes(X509_POLICY_LEVEL *curr, const X509_POLICY_DATA *data) { X509_POLICY_LEVEL *last = curr - 1; X509_POLICY_NODE *node; int i, matched = 0; /* Iterate through all in nodes linking matches */ for (i = 0; i < sk_X509_POLICY_NODE_num(last->nodes); i++) { node = sk_X509_POLICY_NODE_value(last->nodes, i); if (policy_node_match(last, node, data->valid_policy)) { if (!level_add_node(curr, data, node, NULL)) return 0; matched = 1; } } if (!matched && last->anyPolicy) { if (!level_add_node(curr, data, last->anyPolicy, NULL)) return 0; } return 1; } /* * This corresponds to RFC3280 6.1.3(d)(1): link any data from * CertificatePolicies onto matching parent or anyPolicy if no match. */ static int tree_link_nodes(X509_POLICY_LEVEL *curr, const X509_POLICY_CACHE *cache) { int i; X509_POLICY_DATA *data; for (i = 0; i < sk_X509_POLICY_DATA_num(cache->data); i++) { data = sk_X509_POLICY_DATA_value(cache->data, i); /* * If a node is mapped any it doesn't have a corresponding * CertificatePolicies entry. However such an identical node would * be created if anyPolicy matching is enabled because there would be * no match with the parent valid_policy_set. So we create link * because then it will have the mapping flags right and we can prune * it later. */ #if 0 if ((data->flags & POLICY_DATA_FLAG_MAPPED_ANY) && !(curr->flags & X509_V_FLAG_INHIBIT_ANY)) continue; #endif /* Look for matching nodes in previous level */ if (!tree_link_matching_nodes(curr, data)) return 0; } return 1; } /* * This corresponds to RFC3280 6.1.3(d)(2): Create new data for any unmatched * policies in the parent and link to anyPolicy. */ static int tree_add_unmatched(X509_POLICY_LEVEL *curr, const X509_POLICY_CACHE *cache, const ASN1_OBJECT *id, X509_POLICY_NODE *node, X509_POLICY_TREE *tree) { X509_POLICY_DATA *data; if (id == NULL) id = node->data->valid_policy; /* * Create a new node with qualifiers from anyPolicy and id from unmatched * node. */ data = policy_data_new(NULL, id, node_critical(node)); if (data == NULL) return 0; /* Curr may not have anyPolicy */ data->qualifier_set = cache->anyPolicy->qualifier_set; data->flags |= POLICY_DATA_FLAG_SHARED_QUALIFIERS; if (!level_add_node(curr, data, node, tree)) { policy_data_free(data); return 0; } return 1; } static int tree_link_unmatched(X509_POLICY_LEVEL *curr, const X509_POLICY_CACHE *cache, X509_POLICY_NODE *node, X509_POLICY_TREE *tree) { const X509_POLICY_LEVEL *last = curr - 1; int i; if ((last->flags & X509_V_FLAG_INHIBIT_MAP) || !(node->data->flags & POLICY_DATA_FLAG_MAPPED)) { /* If no policy mapping: matched if one child present */ if (node->nchild) return 1; if (!tree_add_unmatched(curr, cache, NULL, node, tree)) return 0; /* Add it */ } else { /* If mapping: matched if one child per expected policy set */ STACK_OF(ASN1_OBJECT) *expset = node->data->expected_policy_set; if (node->nchild == sk_ASN1_OBJECT_num(expset)) return 1; /* Locate unmatched nodes */ for (i = 0; i < sk_ASN1_OBJECT_num(expset); i++) { ASN1_OBJECT *oid = sk_ASN1_OBJECT_value(expset, i); if (level_find_node(curr, node, oid)) continue; if (!tree_add_unmatched(curr, cache, oid, node, tree)) return 0; } } return 1; } static int tree_link_any(X509_POLICY_LEVEL *curr, const X509_POLICY_CACHE *cache, X509_POLICY_TREE *tree) { int i; /* * X509_POLICY_DATA *data; */ X509_POLICY_NODE *node; X509_POLICY_LEVEL *last = curr - 1; for (i = 0; i < sk_X509_POLICY_NODE_num(last->nodes); i++) { node = sk_X509_POLICY_NODE_value(last->nodes, i); if (!tree_link_unmatched(curr, cache, node, tree)) return 0; #if 0 /* * Skip any node with any children: we only want unmathced nodes. * Note: need something better for policy mapping because each node * may have multiple children */ if (node->nchild) continue; /* * Create a new node with qualifiers from anyPolicy and id from * unmatched node. */ data = policy_data_new(NULL, node->data->valid_policy, node_critical(node)); if (data == NULL) return 0; /* Curr may not have anyPolicy */ data->qualifier_set = cache->anyPolicy->qualifier_set; data->flags |= POLICY_DATA_FLAG_SHARED_QUALIFIERS; if (!level_add_node(curr, data, node, tree)) { policy_data_free(data); return 0; } #endif } /* Finally add link to anyPolicy */ if (last->anyPolicy) { if (!level_add_node(curr, cache->anyPolicy, last->anyPolicy, NULL)) return 0; } return 1; } /* * Prune the tree: delete any child mapped child data on the current level * then proceed up the tree deleting any data with no children. If we ever * have no data on a level we can halt because the tree will be empty. */ static int tree_prune(X509_POLICY_TREE *tree, X509_POLICY_LEVEL *curr) { STACK_OF(X509_POLICY_NODE) *nodes; X509_POLICY_NODE *node; int i; nodes = curr->nodes; if (curr->flags & X509_V_FLAG_INHIBIT_MAP) { for (i = sk_X509_POLICY_NODE_num(nodes) - 1; i >= 0; i--) { node = sk_X509_POLICY_NODE_value(nodes, i); /* Delete any mapped data: see RFC3280 XXXX */ if (node->data->flags & POLICY_DATA_FLAG_MAP_MASK) { node->parent->nchild--; OPENSSL_free(node); (void)sk_X509_POLICY_NODE_delete(nodes, i); } } } for (;;) { --curr; nodes = curr->nodes; for (i = sk_X509_POLICY_NODE_num(nodes) - 1; i >= 0; i--) { node = sk_X509_POLICY_NODE_value(nodes, i); if (node->nchild == 0) { node->parent->nchild--; OPENSSL_free(node); (void)sk_X509_POLICY_NODE_delete(nodes, i); } } if (curr->anyPolicy && !curr->anyPolicy->nchild) { if (curr->anyPolicy->parent) curr->anyPolicy->parent->nchild--; OPENSSL_free(curr->anyPolicy); curr->anyPolicy = NULL; } if (curr == tree->levels) { /* If we zapped anyPolicy at top then tree is empty */ if (!curr->anyPolicy) return 2; return 1; } } return 1; } static int tree_add_auth_node(STACK_OF(X509_POLICY_NODE) **pnodes, X509_POLICY_NODE *pcy) { if (!*pnodes) { *pnodes = policy_node_cmp_new(); if (!*pnodes) return 0; } else if (sk_X509_POLICY_NODE_find(*pnodes, pcy) != -1) return 1; if (!sk_X509_POLICY_NODE_push(*pnodes, pcy)) return 0; return 1; } /* * Calculate the authority set based on policy tree. The 'pnodes' parameter * is used as a store for the set of policy nodes used to calculate the user * set. If the authority set is not anyPolicy then pnodes will just point to * the authority set. If however the authority set is anyPolicy then the set * of valid policies (other than anyPolicy) is store in pnodes. The return * value of '2' is used in this case to indicate that pnodes should be freed. */ static int tree_calculate_authority_set(X509_POLICY_TREE *tree, STACK_OF(X509_POLICY_NODE) **pnodes) { X509_POLICY_LEVEL *curr; X509_POLICY_NODE *node, *anyptr; STACK_OF(X509_POLICY_NODE) **addnodes; int i, j; curr = tree->levels + tree->nlevel - 1; /* If last level contains anyPolicy set is anyPolicy */ if (curr->anyPolicy) { if (!tree_add_auth_node(&tree->auth_policies, curr->anyPolicy)) return 0; addnodes = pnodes; } else /* Add policies to authority set */ addnodes = &tree->auth_policies; curr = tree->levels; for (i = 1; i < tree->nlevel; i++) { /* * If no anyPolicy node on this this level it can't appear on lower * levels so end search. */ if (!(anyptr = curr->anyPolicy)) break; curr++; for (j = 0; j < sk_X509_POLICY_NODE_num(curr->nodes); j++) { node = sk_X509_POLICY_NODE_value(curr->nodes, j); if ((node->parent == anyptr) && !tree_add_auth_node(addnodes, node)) return 0; } } if (addnodes == pnodes) return 2; *pnodes = tree->auth_policies; return 1; } static int tree_calculate_user_set(X509_POLICY_TREE *tree, STACK_OF(ASN1_OBJECT) *policy_oids, STACK_OF(X509_POLICY_NODE) *auth_nodes) { int i; X509_POLICY_NODE *node; ASN1_OBJECT *oid; X509_POLICY_NODE *anyPolicy; X509_POLICY_DATA *extra; /* * Check if anyPolicy present in authority constrained policy set: this * will happen if it is a leaf node. */ if (sk_ASN1_OBJECT_num(policy_oids) <= 0) return 1; anyPolicy = tree->levels[tree->nlevel - 1].anyPolicy; for (i = 0; i < sk_ASN1_OBJECT_num(policy_oids); i++) { oid = sk_ASN1_OBJECT_value(policy_oids, i); if (OBJ_obj2nid(oid) == NID_any_policy) { tree->flags |= POLICY_FLAG_ANY_POLICY; return 1; } } for (i = 0; i < sk_ASN1_OBJECT_num(policy_oids); i++) { oid = sk_ASN1_OBJECT_value(policy_oids, i); node = tree_find_sk(auth_nodes, oid); if (!node) { if (!anyPolicy) continue; /* * Create a new node with policy ID from user set and qualifiers * from anyPolicy. */ extra = policy_data_new(NULL, oid, node_critical(anyPolicy)); if (!extra) return 0; extra->qualifier_set = anyPolicy->data->qualifier_set; extra->flags = POLICY_DATA_FLAG_SHARED_QUALIFIERS | POLICY_DATA_FLAG_EXTRA_NODE; node = level_add_node(NULL, extra, anyPolicy->parent, tree); } if (!tree->user_policies) { tree->user_policies = sk_X509_POLICY_NODE_new_null(); if (!tree->user_policies) return 1; } if (!sk_X509_POLICY_NODE_push(tree->user_policies, node)) return 0; } return 1; } static int tree_evaluate(X509_POLICY_TREE *tree) { int ret, i; X509_POLICY_LEVEL *curr = tree->levels + 1; const X509_POLICY_CACHE *cache; for (i = 1; i < tree->nlevel; i++, curr++) { cache = policy_cache_set(curr->cert); if (!tree_link_nodes(curr, cache)) return 0; if (!(curr->flags & X509_V_FLAG_INHIBIT_ANY) && !tree_link_any(curr, cache, tree)) return 0; tree_print("before tree_prune()", tree, curr); ret = tree_prune(tree, curr); if (ret != 1) return ret; } return 1; } static void exnode_free(X509_POLICY_NODE *node) { if (node->data && (node->data->flags & POLICY_DATA_FLAG_EXTRA_NODE)) OPENSSL_free(node); } void X509_policy_tree_free(X509_POLICY_TREE *tree) { X509_POLICY_LEVEL *curr; int i; if (!tree) return; sk_X509_POLICY_NODE_free(tree->auth_policies); sk_X509_POLICY_NODE_pop_free(tree->user_policies, exnode_free); for (i = 0, curr = tree->levels; i < tree->nlevel; i++, curr++) { if (curr->cert) X509_free(curr->cert); if (curr->nodes) sk_X509_POLICY_NODE_pop_free(curr->nodes, policy_node_free); if (curr->anyPolicy) policy_node_free(curr->anyPolicy); } if (tree->extra_data) sk_X509_POLICY_DATA_pop_free(tree->extra_data, policy_data_free); OPENSSL_free(tree->levels); OPENSSL_free(tree); } /*- * Application policy checking function. * Return codes: * 0 Internal Error. * 1 Successful. * -1 One or more certificates contain invalid or inconsistent extensions * -2 User constrained policy set empty and requireExplicit true. */ int X509_policy_check(X509_POLICY_TREE **ptree, int *pexplicit_policy, STACK_OF(X509) *certs, STACK_OF(ASN1_OBJECT) *policy_oids, unsigned int flags) { int ret; + int calc_ret; X509_POLICY_TREE *tree = NULL; STACK_OF(X509_POLICY_NODE) *nodes, *auth_nodes = NULL; *ptree = NULL; *pexplicit_policy = 0; ret = tree_init(&tree, certs, flags); switch (ret) { /* Tree empty requireExplicit False: OK */ case 2: return 1; /* Some internal error */ case -1: return -1; /* Some internal error */ case 0: return 0; /* Tree empty requireExplicit True: Error */ case 6: *pexplicit_policy = 1; return -2; /* Tree OK requireExplicit True: OK and continue */ case 5: *pexplicit_policy = 1; break; /* Tree OK: continue */ case 1: if (!tree) /* * tree_init() returns success and a null tree * if it's just looking at a trust anchor. * I'm not sure that returning success here is * correct, but I'm sure that reporting this * as an internal error which our caller * interprets as a malloc failure is wrong. */ return 1; break; } if (!tree) goto error; ret = tree_evaluate(tree); tree_print("tree_evaluate()", tree, NULL); if (ret <= 0) goto error; /* Return value 2 means tree empty */ if (ret == 2) { X509_policy_tree_free(tree); if (*pexplicit_policy) return -2; else return 1; } /* Tree is not empty: continue */ - ret = tree_calculate_authority_set(tree, &auth_nodes); + calc_ret = tree_calculate_authority_set(tree, &auth_nodes); - if (!ret) + if (!calc_ret) goto error; - if (!tree_calculate_user_set(tree, policy_oids, auth_nodes)) - goto error; + ret = tree_calculate_user_set(tree, policy_oids, auth_nodes); - if (ret == 2) + if (calc_ret == 2) sk_X509_POLICY_NODE_free(auth_nodes); + + if (!ret) + goto error; + if (tree) *ptree = tree; if (*pexplicit_policy) { nodes = X509_policy_tree_get0_user_policies(tree); if (sk_X509_POLICY_NODE_num(nodes) <= 0) return -2; } return 1; error: X509_policy_tree_free(tree); return 0; } Index: vendor-crypto/openssl/dist/crypto/x509v3/v3_addr.c =================================================================== --- vendor-crypto/openssl/dist/crypto/x509v3/v3_addr.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/x509v3/v3_addr.c (revision 325326) @@ -1,1350 +1,1352 @@ /* * Contributed to the OpenSSL Project by the American Registry for * Internet Numbers ("ARIN"). */ /* ==================================================================== * 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). */ /* * Implementation of RFC 3779 section 2.2. */ #include #include #include "cryptlib.h" #include #include #include #include #include #ifndef OPENSSL_NO_RFC3779 /* * OpenSSL ASN.1 template translation of RFC 3779 2.2.3. */ ASN1_SEQUENCE(IPAddressRange) = { ASN1_SIMPLE(IPAddressRange, min, ASN1_BIT_STRING), ASN1_SIMPLE(IPAddressRange, max, ASN1_BIT_STRING) } ASN1_SEQUENCE_END(IPAddressRange) ASN1_CHOICE(IPAddressOrRange) = { ASN1_SIMPLE(IPAddressOrRange, u.addressPrefix, ASN1_BIT_STRING), ASN1_SIMPLE(IPAddressOrRange, u.addressRange, IPAddressRange) } ASN1_CHOICE_END(IPAddressOrRange) ASN1_CHOICE(IPAddressChoice) = { ASN1_SIMPLE(IPAddressChoice, u.inherit, ASN1_NULL), ASN1_SEQUENCE_OF(IPAddressChoice, u.addressesOrRanges, IPAddressOrRange) } ASN1_CHOICE_END(IPAddressChoice) ASN1_SEQUENCE(IPAddressFamily) = { ASN1_SIMPLE(IPAddressFamily, addressFamily, ASN1_OCTET_STRING), ASN1_SIMPLE(IPAddressFamily, ipAddressChoice, IPAddressChoice) } ASN1_SEQUENCE_END(IPAddressFamily) ASN1_ITEM_TEMPLATE(IPAddrBlocks) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, IPAddrBlocks, IPAddressFamily) ASN1_ITEM_TEMPLATE_END(IPAddrBlocks) IMPLEMENT_ASN1_FUNCTIONS(IPAddressRange) IMPLEMENT_ASN1_FUNCTIONS(IPAddressOrRange) IMPLEMENT_ASN1_FUNCTIONS(IPAddressChoice) IMPLEMENT_ASN1_FUNCTIONS(IPAddressFamily) /* * How much buffer space do we need for a raw address? */ # define ADDR_RAW_BUF_LEN 16 /* * What's the address length associated with this AFI? */ static int length_from_afi(const unsigned afi) { switch (afi) { case IANA_AFI_IPV4: return 4; case IANA_AFI_IPV6: return 16; default: return 0; } } /* * Extract the AFI from an IPAddressFamily. */ unsigned int v3_addr_get_afi(const IPAddressFamily *f) { - return ((f != NULL && - f->addressFamily != NULL && f->addressFamily->data != NULL) - ? ((f->addressFamily->data[0] << 8) | (f->addressFamily->data[1])) - : 0); + if (f == NULL + || f->addressFamily == NULL + || f->addressFamily->data == NULL + || f->addressFamily->length < 2) + return 0; + return (f->addressFamily->data[0] << 8) | f->addressFamily->data[1]; } /* * Expand the bitstring form of an address into a raw byte array. * At the moment this is coded for simplicity, not speed. */ static int addr_expand(unsigned char *addr, const ASN1_BIT_STRING *bs, const int length, const unsigned char fill) { if (bs->length < 0 || bs->length > length) return 0; if (bs->length > 0) { memcpy(addr, bs->data, bs->length); if ((bs->flags & 7) != 0) { unsigned char mask = 0xFF >> (8 - (bs->flags & 7)); if (fill == 0) addr[bs->length - 1] &= ~mask; else addr[bs->length - 1] |= mask; } } memset(addr + bs->length, fill, length - bs->length); return 1; } /* * Extract the prefix length from a bitstring. */ # define addr_prefixlen(bs) ((int) ((bs)->length * 8 - ((bs)->flags & 7))) /* * i2r handler for one address bitstring. */ static int i2r_address(BIO *out, const unsigned afi, const unsigned char fill, const ASN1_BIT_STRING *bs) { unsigned char addr[ADDR_RAW_BUF_LEN]; int i, n; if (bs->length < 0) return 0; switch (afi) { case IANA_AFI_IPV4: if (!addr_expand(addr, bs, 4, fill)) return 0; BIO_printf(out, "%d.%d.%d.%d", addr[0], addr[1], addr[2], addr[3]); break; case IANA_AFI_IPV6: if (!addr_expand(addr, bs, 16, fill)) return 0; for (n = 16; n > 1 && addr[n - 1] == 0x00 && addr[n - 2] == 0x00; n -= 2) ; for (i = 0; i < n; i += 2) BIO_printf(out, "%x%s", (addr[i] << 8) | addr[i + 1], (i < 14 ? ":" : "")); if (i < 16) BIO_puts(out, ":"); if (i == 0) BIO_puts(out, ":"); break; default: for (i = 0; i < bs->length; i++) BIO_printf(out, "%s%02x", (i > 0 ? ":" : ""), bs->data[i]); BIO_printf(out, "[%d]", (int)(bs->flags & 7)); break; } return 1; } /* * i2r handler for a sequence of addresses and ranges. */ static int i2r_IPAddressOrRanges(BIO *out, const int indent, const IPAddressOrRanges *aors, const unsigned afi) { int i; for (i = 0; i < sk_IPAddressOrRange_num(aors); i++) { const IPAddressOrRange *aor = sk_IPAddressOrRange_value(aors, i); BIO_printf(out, "%*s", indent, ""); switch (aor->type) { case IPAddressOrRange_addressPrefix: if (!i2r_address(out, afi, 0x00, aor->u.addressPrefix)) return 0; BIO_printf(out, "/%d\n", addr_prefixlen(aor->u.addressPrefix)); continue; case IPAddressOrRange_addressRange: if (!i2r_address(out, afi, 0x00, aor->u.addressRange->min)) return 0; BIO_puts(out, "-"); if (!i2r_address(out, afi, 0xFF, aor->u.addressRange->max)) return 0; BIO_puts(out, "\n"); continue; } } return 1; } /* * i2r handler for an IPAddrBlocks extension. */ static int i2r_IPAddrBlocks(const X509V3_EXT_METHOD *method, void *ext, BIO *out, int indent) { const IPAddrBlocks *addr = ext; int i; for (i = 0; i < sk_IPAddressFamily_num(addr); i++) { IPAddressFamily *f = sk_IPAddressFamily_value(addr, i); const unsigned int afi = v3_addr_get_afi(f); switch (afi) { case IANA_AFI_IPV4: BIO_printf(out, "%*sIPv4", indent, ""); break; case IANA_AFI_IPV6: BIO_printf(out, "%*sIPv6", indent, ""); break; default: BIO_printf(out, "%*sUnknown AFI %u", indent, "", afi); break; } if (f->addressFamily->length > 2) { switch (f->addressFamily->data[2]) { case 1: BIO_puts(out, " (Unicast)"); break; case 2: BIO_puts(out, " (Multicast)"); break; case 3: BIO_puts(out, " (Unicast/Multicast)"); break; case 4: BIO_puts(out, " (MPLS)"); break; case 64: BIO_puts(out, " (Tunnel)"); break; case 65: BIO_puts(out, " (VPLS)"); break; case 66: BIO_puts(out, " (BGP MDT)"); break; case 128: BIO_puts(out, " (MPLS-labeled VPN)"); break; default: BIO_printf(out, " (Unknown SAFI %u)", (unsigned)f->addressFamily->data[2]); break; } } switch (f->ipAddressChoice->type) { case IPAddressChoice_inherit: BIO_puts(out, ": inherit\n"); break; case IPAddressChoice_addressesOrRanges: BIO_puts(out, ":\n"); if (!i2r_IPAddressOrRanges(out, indent + 2, f->ipAddressChoice-> u.addressesOrRanges, afi)) return 0; break; } } return 1; } /* * Sort comparison function for a sequence of IPAddressOrRange * elements. * * There's no sane answer we can give if addr_expand() fails, and an * assertion failure on externally supplied data is seriously uncool, * so we just arbitrarily declare that if given invalid inputs this * function returns -1. If this messes up your preferred sort order * for garbage input, tough noogies. */ static int IPAddressOrRange_cmp(const IPAddressOrRange *a, const IPAddressOrRange *b, const int length) { unsigned char addr_a[ADDR_RAW_BUF_LEN], addr_b[ADDR_RAW_BUF_LEN]; int prefixlen_a = 0, prefixlen_b = 0; int r; switch (a->type) { case IPAddressOrRange_addressPrefix: if (!addr_expand(addr_a, a->u.addressPrefix, length, 0x00)) return -1; prefixlen_a = addr_prefixlen(a->u.addressPrefix); break; case IPAddressOrRange_addressRange: if (!addr_expand(addr_a, a->u.addressRange->min, length, 0x00)) return -1; prefixlen_a = length * 8; break; } switch (b->type) { case IPAddressOrRange_addressPrefix: if (!addr_expand(addr_b, b->u.addressPrefix, length, 0x00)) return -1; prefixlen_b = addr_prefixlen(b->u.addressPrefix); break; case IPAddressOrRange_addressRange: if (!addr_expand(addr_b, b->u.addressRange->min, length, 0x00)) return -1; prefixlen_b = length * 8; break; } if ((r = memcmp(addr_a, addr_b, length)) != 0) return r; else return prefixlen_a - prefixlen_b; } /* * IPv4-specific closure over IPAddressOrRange_cmp, since sk_sort() * comparision routines are only allowed two arguments. */ static int v4IPAddressOrRange_cmp(const IPAddressOrRange *const *a, const IPAddressOrRange *const *b) { return IPAddressOrRange_cmp(*a, *b, 4); } /* * IPv6-specific closure over IPAddressOrRange_cmp, since sk_sort() * comparision routines are only allowed two arguments. */ static int v6IPAddressOrRange_cmp(const IPAddressOrRange *const *a, const IPAddressOrRange *const *b) { return IPAddressOrRange_cmp(*a, *b, 16); } /* * Calculate whether a range collapses to a prefix. * See last paragraph of RFC 3779 2.2.3.7. */ static int range_should_be_prefix(const unsigned char *min, const unsigned char *max, const int length) { unsigned char mask; int i, j; OPENSSL_assert(memcmp(min, max, length) <= 0); for (i = 0; i < length && min[i] == max[i]; i++) ; for (j = length - 1; j >= 0 && min[j] == 0x00 && max[j] == 0xFF; j--) ; if (i < j) return -1; if (i > j) return i * 8; mask = min[i] ^ max[i]; switch (mask) { case 0x01: j = 7; break; case 0x03: j = 6; break; case 0x07: j = 5; break; case 0x0F: j = 4; break; case 0x1F: j = 3; break; case 0x3F: j = 2; break; case 0x7F: j = 1; break; default: return -1; } if ((min[i] & mask) != 0 || (max[i] & mask) != mask) return -1; else return i * 8 + j; } /* * Construct a prefix. */ static int make_addressPrefix(IPAddressOrRange **result, unsigned char *addr, const int prefixlen) { int bytelen = (prefixlen + 7) / 8, bitlen = prefixlen % 8; IPAddressOrRange *aor = IPAddressOrRange_new(); if (aor == NULL) return 0; aor->type = IPAddressOrRange_addressPrefix; if (aor->u.addressPrefix == NULL && (aor->u.addressPrefix = ASN1_BIT_STRING_new()) == NULL) goto err; if (!ASN1_BIT_STRING_set(aor->u.addressPrefix, addr, bytelen)) goto err; aor->u.addressPrefix->flags &= ~7; aor->u.addressPrefix->flags |= ASN1_STRING_FLAG_BITS_LEFT; if (bitlen > 0) { aor->u.addressPrefix->data[bytelen - 1] &= ~(0xFF >> bitlen); aor->u.addressPrefix->flags |= 8 - bitlen; } *result = aor; return 1; err: IPAddressOrRange_free(aor); return 0; } /* * Construct a range. If it can be expressed as a prefix, * return a prefix instead. Doing this here simplifies * the rest of the code considerably. */ static int make_addressRange(IPAddressOrRange **result, unsigned char *min, unsigned char *max, const int length) { IPAddressOrRange *aor; int i, prefixlen; if ((prefixlen = range_should_be_prefix(min, max, length)) >= 0) return make_addressPrefix(result, min, prefixlen); if ((aor = IPAddressOrRange_new()) == NULL) return 0; aor->type = IPAddressOrRange_addressRange; OPENSSL_assert(aor->u.addressRange == NULL); if ((aor->u.addressRange = IPAddressRange_new()) == NULL) goto err; if (aor->u.addressRange->min == NULL && (aor->u.addressRange->min = ASN1_BIT_STRING_new()) == NULL) goto err; if (aor->u.addressRange->max == NULL && (aor->u.addressRange->max = ASN1_BIT_STRING_new()) == NULL) goto err; for (i = length; i > 0 && min[i - 1] == 0x00; --i) ; if (!ASN1_BIT_STRING_set(aor->u.addressRange->min, min, i)) goto err; aor->u.addressRange->min->flags &= ~7; aor->u.addressRange->min->flags |= ASN1_STRING_FLAG_BITS_LEFT; if (i > 0) { unsigned char b = min[i - 1]; int j = 1; while ((b & (0xFFU >> j)) != 0) ++j; aor->u.addressRange->min->flags |= 8 - j; } for (i = length; i > 0 && max[i - 1] == 0xFF; --i) ; if (!ASN1_BIT_STRING_set(aor->u.addressRange->max, max, i)) goto err; aor->u.addressRange->max->flags &= ~7; aor->u.addressRange->max->flags |= ASN1_STRING_FLAG_BITS_LEFT; if (i > 0) { unsigned char b = max[i - 1]; int j = 1; while ((b & (0xFFU >> j)) != (0xFFU >> j)) ++j; aor->u.addressRange->max->flags |= 8 - j; } *result = aor; return 1; err: IPAddressOrRange_free(aor); return 0; } /* * Construct a new address family or find an existing one. */ static IPAddressFamily *make_IPAddressFamily(IPAddrBlocks *addr, const unsigned afi, const unsigned *safi) { IPAddressFamily *f; unsigned char key[3]; unsigned keylen; int i; key[0] = (afi >> 8) & 0xFF; key[1] = afi & 0xFF; if (safi != NULL) { key[2] = *safi & 0xFF; keylen = 3; } else { keylen = 2; } for (i = 0; i < sk_IPAddressFamily_num(addr); i++) { f = sk_IPAddressFamily_value(addr, i); OPENSSL_assert(f->addressFamily->data != NULL); if (f->addressFamily->length == keylen && !memcmp(f->addressFamily->data, key, keylen)) return f; } if ((f = IPAddressFamily_new()) == NULL) goto err; if (f->ipAddressChoice == NULL && (f->ipAddressChoice = IPAddressChoice_new()) == NULL) goto err; if (f->addressFamily == NULL && (f->addressFamily = ASN1_OCTET_STRING_new()) == NULL) goto err; if (!ASN1_OCTET_STRING_set(f->addressFamily, key, keylen)) goto err; if (!sk_IPAddressFamily_push(addr, f)) goto err; return f; err: IPAddressFamily_free(f); return NULL; } /* * Add an inheritance element. */ int v3_addr_add_inherit(IPAddrBlocks *addr, const unsigned afi, const unsigned *safi) { IPAddressFamily *f = make_IPAddressFamily(addr, afi, safi); if (f == NULL || f->ipAddressChoice == NULL || (f->ipAddressChoice->type == IPAddressChoice_addressesOrRanges && f->ipAddressChoice->u.addressesOrRanges != NULL)) return 0; if (f->ipAddressChoice->type == IPAddressChoice_inherit && f->ipAddressChoice->u.inherit != NULL) return 1; if (f->ipAddressChoice->u.inherit == NULL && (f->ipAddressChoice->u.inherit = ASN1_NULL_new()) == NULL) return 0; f->ipAddressChoice->type = IPAddressChoice_inherit; return 1; } /* * Construct an IPAddressOrRange sequence, or return an existing one. */ static IPAddressOrRanges *make_prefix_or_range(IPAddrBlocks *addr, const unsigned afi, const unsigned *safi) { IPAddressFamily *f = make_IPAddressFamily(addr, afi, safi); IPAddressOrRanges *aors = NULL; if (f == NULL || f->ipAddressChoice == NULL || (f->ipAddressChoice->type == IPAddressChoice_inherit && f->ipAddressChoice->u.inherit != NULL)) return NULL; if (f->ipAddressChoice->type == IPAddressChoice_addressesOrRanges) aors = f->ipAddressChoice->u.addressesOrRanges; if (aors != NULL) return aors; if ((aors = sk_IPAddressOrRange_new_null()) == NULL) return NULL; switch (afi) { case IANA_AFI_IPV4: (void)sk_IPAddressOrRange_set_cmp_func(aors, v4IPAddressOrRange_cmp); break; case IANA_AFI_IPV6: (void)sk_IPAddressOrRange_set_cmp_func(aors, v6IPAddressOrRange_cmp); break; } f->ipAddressChoice->type = IPAddressChoice_addressesOrRanges; f->ipAddressChoice->u.addressesOrRanges = aors; return aors; } /* * Add a prefix. */ int v3_addr_add_prefix(IPAddrBlocks *addr, const unsigned afi, const unsigned *safi, unsigned char *a, const int prefixlen) { IPAddressOrRanges *aors = make_prefix_or_range(addr, afi, safi); IPAddressOrRange *aor; if (aors == NULL || !make_addressPrefix(&aor, a, prefixlen)) return 0; if (sk_IPAddressOrRange_push(aors, aor)) return 1; IPAddressOrRange_free(aor); return 0; } /* * Add a range. */ int v3_addr_add_range(IPAddrBlocks *addr, const unsigned afi, const unsigned *safi, unsigned char *min, unsigned char *max) { IPAddressOrRanges *aors = make_prefix_or_range(addr, afi, safi); IPAddressOrRange *aor; int length = length_from_afi(afi); if (aors == NULL) return 0; if (!make_addressRange(&aor, min, max, length)) return 0; if (sk_IPAddressOrRange_push(aors, aor)) return 1; IPAddressOrRange_free(aor); return 0; } /* * Extract min and max values from an IPAddressOrRange. */ static int extract_min_max(IPAddressOrRange *aor, unsigned char *min, unsigned char *max, int length) { if (aor == NULL || min == NULL || max == NULL) return 0; switch (aor->type) { case IPAddressOrRange_addressPrefix: return (addr_expand(min, aor->u.addressPrefix, length, 0x00) && addr_expand(max, aor->u.addressPrefix, length, 0xFF)); case IPAddressOrRange_addressRange: return (addr_expand(min, aor->u.addressRange->min, length, 0x00) && addr_expand(max, aor->u.addressRange->max, length, 0xFF)); } return 0; } /* * Public wrapper for extract_min_max(). */ int v3_addr_get_range(IPAddressOrRange *aor, const unsigned afi, unsigned char *min, unsigned char *max, const int length) { int afi_length = length_from_afi(afi); if (aor == NULL || min == NULL || max == NULL || afi_length == 0 || length < afi_length || (aor->type != IPAddressOrRange_addressPrefix && aor->type != IPAddressOrRange_addressRange) || !extract_min_max(aor, min, max, afi_length)) return 0; return afi_length; } /* * Sort comparision function for a sequence of IPAddressFamily. * * The last paragraph of RFC 3779 2.2.3.3 is slightly ambiguous about * the ordering: I can read it as meaning that IPv6 without a SAFI * comes before IPv4 with a SAFI, which seems pretty weird. The * examples in appendix B suggest that the author intended the * null-SAFI rule to apply only within a single AFI, which is what I * would have expected and is what the following code implements. */ static int IPAddressFamily_cmp(const IPAddressFamily *const *a_, const IPAddressFamily *const *b_) { const ASN1_OCTET_STRING *a = (*a_)->addressFamily; const ASN1_OCTET_STRING *b = (*b_)->addressFamily; int len = ((a->length <= b->length) ? a->length : b->length); int cmp = memcmp(a->data, b->data, len); return cmp ? cmp : a->length - b->length; } /* * Check whether an IPAddrBLocks is in canonical form. */ int v3_addr_is_canonical(IPAddrBlocks *addr) { unsigned char a_min[ADDR_RAW_BUF_LEN], a_max[ADDR_RAW_BUF_LEN]; unsigned char b_min[ADDR_RAW_BUF_LEN], b_max[ADDR_RAW_BUF_LEN]; IPAddressOrRanges *aors; int i, j, k; /* * Empty extension is cannonical. */ if (addr == NULL) return 1; /* * Check whether the top-level list is in order. */ for (i = 0; i < sk_IPAddressFamily_num(addr) - 1; i++) { const IPAddressFamily *a = sk_IPAddressFamily_value(addr, i); const IPAddressFamily *b = sk_IPAddressFamily_value(addr, i + 1); if (IPAddressFamily_cmp(&a, &b) >= 0) return 0; } /* * Top level's ok, now check each address family. */ for (i = 0; i < sk_IPAddressFamily_num(addr); i++) { IPAddressFamily *f = sk_IPAddressFamily_value(addr, i); int length = length_from_afi(v3_addr_get_afi(f)); /* * Inheritance is canonical. Anything other than inheritance or * a SEQUENCE OF IPAddressOrRange is an ASN.1 error or something. */ if (f == NULL || f->ipAddressChoice == NULL) return 0; switch (f->ipAddressChoice->type) { case IPAddressChoice_inherit: continue; case IPAddressChoice_addressesOrRanges: break; default: return 0; } /* * It's an IPAddressOrRanges sequence, check it. */ aors = f->ipAddressChoice->u.addressesOrRanges; if (sk_IPAddressOrRange_num(aors) == 0) return 0; for (j = 0; j < sk_IPAddressOrRange_num(aors) - 1; j++) { IPAddressOrRange *a = sk_IPAddressOrRange_value(aors, j); IPAddressOrRange *b = sk_IPAddressOrRange_value(aors, j + 1); if (!extract_min_max(a, a_min, a_max, length) || !extract_min_max(b, b_min, b_max, length)) return 0; /* * Punt misordered list, overlapping start, or inverted range. */ if (memcmp(a_min, b_min, length) >= 0 || memcmp(a_min, a_max, length) > 0 || memcmp(b_min, b_max, length) > 0) return 0; /* * Punt if adjacent or overlapping. Check for adjacency by * subtracting one from b_min first. */ for (k = length - 1; k >= 0 && b_min[k]-- == 0x00; k--) ; if (memcmp(a_max, b_min, length) >= 0) return 0; /* * Check for range that should be expressed as a prefix. */ if (a->type == IPAddressOrRange_addressRange && range_should_be_prefix(a_min, a_max, length) >= 0) return 0; } /* * Check range to see if it's inverted or should be a * prefix. */ j = sk_IPAddressOrRange_num(aors) - 1; { IPAddressOrRange *a = sk_IPAddressOrRange_value(aors, j); if (a != NULL && a->type == IPAddressOrRange_addressRange) { if (!extract_min_max(a, a_min, a_max, length)) return 0; if (memcmp(a_min, a_max, length) > 0 || range_should_be_prefix(a_min, a_max, length) >= 0) return 0; } } } /* * If we made it through all that, we're happy. */ return 1; } /* * Whack an IPAddressOrRanges into canonical form. */ static int IPAddressOrRanges_canonize(IPAddressOrRanges *aors, const unsigned afi) { int i, j, length = length_from_afi(afi); /* * Sort the IPAddressOrRanges sequence. */ sk_IPAddressOrRange_sort(aors); /* * Clean up representation issues, punt on duplicates or overlaps. */ for (i = 0; i < sk_IPAddressOrRange_num(aors) - 1; i++) { IPAddressOrRange *a = sk_IPAddressOrRange_value(aors, i); IPAddressOrRange *b = sk_IPAddressOrRange_value(aors, i + 1); unsigned char a_min[ADDR_RAW_BUF_LEN], a_max[ADDR_RAW_BUF_LEN]; unsigned char b_min[ADDR_RAW_BUF_LEN], b_max[ADDR_RAW_BUF_LEN]; if (!extract_min_max(a, a_min, a_max, length) || !extract_min_max(b, b_min, b_max, length)) return 0; /* * Punt inverted ranges. */ if (memcmp(a_min, a_max, length) > 0 || memcmp(b_min, b_max, length) > 0) return 0; /* * Punt overlaps. */ if (memcmp(a_max, b_min, length) >= 0) return 0; /* * Merge if a and b are adjacent. We check for * adjacency by subtracting one from b_min first. */ for (j = length - 1; j >= 0 && b_min[j]-- == 0x00; j--) ; if (memcmp(a_max, b_min, length) == 0) { IPAddressOrRange *merged; if (!make_addressRange(&merged, a_min, b_max, length)) return 0; (void)sk_IPAddressOrRange_set(aors, i, merged); (void)sk_IPAddressOrRange_delete(aors, i + 1); IPAddressOrRange_free(a); IPAddressOrRange_free(b); --i; continue; } } /* * Check for inverted final range. */ j = sk_IPAddressOrRange_num(aors) - 1; { IPAddressOrRange *a = sk_IPAddressOrRange_value(aors, j); if (a != NULL && a->type == IPAddressOrRange_addressRange) { unsigned char a_min[ADDR_RAW_BUF_LEN], a_max[ADDR_RAW_BUF_LEN]; extract_min_max(a, a_min, a_max, length); if (memcmp(a_min, a_max, length) > 0) return 0; } } return 1; } /* * Whack an IPAddrBlocks extension into canonical form. */ int v3_addr_canonize(IPAddrBlocks *addr) { int i; for (i = 0; i < sk_IPAddressFamily_num(addr); i++) { IPAddressFamily *f = sk_IPAddressFamily_value(addr, i); if (f->ipAddressChoice->type == IPAddressChoice_addressesOrRanges && !IPAddressOrRanges_canonize(f->ipAddressChoice-> u.addressesOrRanges, v3_addr_get_afi(f))) return 0; } (void)sk_IPAddressFamily_set_cmp_func(addr, IPAddressFamily_cmp); sk_IPAddressFamily_sort(addr); OPENSSL_assert(v3_addr_is_canonical(addr)); return 1; } /* * v2i handler for the IPAddrBlocks extension. */ static void *v2i_IPAddrBlocks(const struct v3_ext_method *method, struct v3_ext_ctx *ctx, STACK_OF(CONF_VALUE) *values) { static const char v4addr_chars[] = "0123456789."; static const char v6addr_chars[] = "0123456789.:abcdefABCDEF"; IPAddrBlocks *addr = NULL; char *s = NULL, *t; int i; if ((addr = sk_IPAddressFamily_new(IPAddressFamily_cmp)) == NULL) { X509V3err(X509V3_F_V2I_IPADDRBLOCKS, ERR_R_MALLOC_FAILURE); return NULL; } for (i = 0; i < sk_CONF_VALUE_num(values); i++) { CONF_VALUE *val = sk_CONF_VALUE_value(values, i); unsigned char min[ADDR_RAW_BUF_LEN], max[ADDR_RAW_BUF_LEN]; unsigned afi, *safi = NULL, safi_; const char *addr_chars; int prefixlen, i1, i2, delim, length; if (!name_cmp(val->name, "IPv4")) { afi = IANA_AFI_IPV4; } else if (!name_cmp(val->name, "IPv6")) { afi = IANA_AFI_IPV6; } else if (!name_cmp(val->name, "IPv4-SAFI")) { afi = IANA_AFI_IPV4; safi = &safi_; } else if (!name_cmp(val->name, "IPv6-SAFI")) { afi = IANA_AFI_IPV6; safi = &safi_; } else { X509V3err(X509V3_F_V2I_IPADDRBLOCKS, X509V3_R_EXTENSION_NAME_ERROR); X509V3_conf_err(val); goto err; } switch (afi) { case IANA_AFI_IPV4: addr_chars = v4addr_chars; break; case IANA_AFI_IPV6: addr_chars = v6addr_chars; break; } length = length_from_afi(afi); /* * Handle SAFI, if any, and BUF_strdup() so we can null-terminate * the other input values. */ if (safi != NULL) { *safi = strtoul(val->value, &t, 0); t += strspn(t, " \t"); if (*safi > 0xFF || *t++ != ':') { X509V3err(X509V3_F_V2I_IPADDRBLOCKS, X509V3_R_INVALID_SAFI); X509V3_conf_err(val); goto err; } t += strspn(t, " \t"); s = BUF_strdup(t); } else { s = BUF_strdup(val->value); } if (s == NULL) { X509V3err(X509V3_F_V2I_IPADDRBLOCKS, ERR_R_MALLOC_FAILURE); goto err; } /* * Check for inheritance. Not worth additional complexity to * optimize this (seldom-used) case. */ if (!strcmp(s, "inherit")) { if (!v3_addr_add_inherit(addr, afi, safi)) { X509V3err(X509V3_F_V2I_IPADDRBLOCKS, X509V3_R_INVALID_INHERITANCE); X509V3_conf_err(val); goto err; } OPENSSL_free(s); s = NULL; continue; } i1 = strspn(s, addr_chars); i2 = i1 + strspn(s + i1, " \t"); delim = s[i2++]; s[i1] = '\0'; if (a2i_ipadd(min, s) != length) { X509V3err(X509V3_F_V2I_IPADDRBLOCKS, X509V3_R_INVALID_IPADDRESS); X509V3_conf_err(val); goto err; } switch (delim) { case '/': prefixlen = (int)strtoul(s + i2, &t, 10); if (t == s + i2 || *t != '\0') { X509V3err(X509V3_F_V2I_IPADDRBLOCKS, X509V3_R_EXTENSION_VALUE_ERROR); X509V3_conf_err(val); goto err; } if (!v3_addr_add_prefix(addr, afi, safi, min, prefixlen)) { X509V3err(X509V3_F_V2I_IPADDRBLOCKS, ERR_R_MALLOC_FAILURE); goto err; } break; case '-': i1 = i2 + strspn(s + i2, " \t"); i2 = i1 + strspn(s + i1, addr_chars); if (i1 == i2 || s[i2] != '\0') { X509V3err(X509V3_F_V2I_IPADDRBLOCKS, X509V3_R_EXTENSION_VALUE_ERROR); X509V3_conf_err(val); goto err; } if (a2i_ipadd(max, s + i1) != length) { X509V3err(X509V3_F_V2I_IPADDRBLOCKS, X509V3_R_INVALID_IPADDRESS); X509V3_conf_err(val); goto err; } if (memcmp(min, max, length_from_afi(afi)) > 0) { X509V3err(X509V3_F_V2I_IPADDRBLOCKS, X509V3_R_EXTENSION_VALUE_ERROR); X509V3_conf_err(val); goto err; } if (!v3_addr_add_range(addr, afi, safi, min, max)) { X509V3err(X509V3_F_V2I_IPADDRBLOCKS, ERR_R_MALLOC_FAILURE); goto err; } break; case '\0': if (!v3_addr_add_prefix(addr, afi, safi, min, length * 8)) { X509V3err(X509V3_F_V2I_IPADDRBLOCKS, ERR_R_MALLOC_FAILURE); goto err; } break; default: X509V3err(X509V3_F_V2I_IPADDRBLOCKS, X509V3_R_EXTENSION_VALUE_ERROR); X509V3_conf_err(val); goto err; } OPENSSL_free(s); s = NULL; } /* * Canonize the result, then we're done. */ if (!v3_addr_canonize(addr)) goto err; return addr; err: OPENSSL_free(s); sk_IPAddressFamily_pop_free(addr, IPAddressFamily_free); return NULL; } /* * OpenSSL dispatch */ const X509V3_EXT_METHOD v3_addr = { NID_sbgp_ipAddrBlock, /* nid */ 0, /* flags */ ASN1_ITEM_ref(IPAddrBlocks), /* template */ 0, 0, 0, 0, /* old functions, ignored */ 0, /* i2s */ 0, /* s2i */ 0, /* i2v */ v2i_IPAddrBlocks, /* v2i */ i2r_IPAddrBlocks, /* i2r */ 0, /* r2i */ NULL /* extension-specific data */ }; /* * Figure out whether extension sues inheritance. */ int v3_addr_inherits(IPAddrBlocks *addr) { int i; if (addr == NULL) return 0; for (i = 0; i < sk_IPAddressFamily_num(addr); i++) { IPAddressFamily *f = sk_IPAddressFamily_value(addr, i); if (f->ipAddressChoice->type == IPAddressChoice_inherit) return 1; } return 0; } /* * Figure out whether parent contains child. */ static int addr_contains(IPAddressOrRanges *parent, IPAddressOrRanges *child, int length) { unsigned char p_min[ADDR_RAW_BUF_LEN], p_max[ADDR_RAW_BUF_LEN]; unsigned char c_min[ADDR_RAW_BUF_LEN], c_max[ADDR_RAW_BUF_LEN]; int p, c; if (child == NULL || parent == child) return 1; if (parent == NULL) return 0; p = 0; for (c = 0; c < sk_IPAddressOrRange_num(child); c++) { if (!extract_min_max(sk_IPAddressOrRange_value(child, c), c_min, c_max, length)) return -1; for (;; p++) { if (p >= sk_IPAddressOrRange_num(parent)) return 0; if (!extract_min_max(sk_IPAddressOrRange_value(parent, p), p_min, p_max, length)) return 0; if (memcmp(p_max, c_max, length) < 0) continue; if (memcmp(p_min, c_min, length) > 0) return 0; break; } } return 1; } /* * Test whether a is a subset of b. */ int v3_addr_subset(IPAddrBlocks *a, IPAddrBlocks *b) { int i; if (a == NULL || a == b) return 1; if (b == NULL || v3_addr_inherits(a) || v3_addr_inherits(b)) return 0; (void)sk_IPAddressFamily_set_cmp_func(b, IPAddressFamily_cmp); for (i = 0; i < sk_IPAddressFamily_num(a); i++) { IPAddressFamily *fa = sk_IPAddressFamily_value(a, i); int j = sk_IPAddressFamily_find(b, fa); IPAddressFamily *fb; fb = sk_IPAddressFamily_value(b, j); if (fb == NULL) return 0; if (!addr_contains(fb->ipAddressChoice->u.addressesOrRanges, fa->ipAddressChoice->u.addressesOrRanges, length_from_afi(v3_addr_get_afi(fb)))) return 0; } return 1; } /* * Validation error handling via callback. */ # define validation_err(_err_) \ do { \ if (ctx != NULL) { \ ctx->error = _err_; \ ctx->error_depth = i; \ ctx->current_cert = x; \ ret = ctx->verify_cb(0, ctx); \ } else { \ ret = 0; \ } \ if (!ret) \ goto done; \ } while (0) /* * Core code for RFC 3779 2.3 path validation. * * Returns 1 for success, 0 on error. * * When returning 0, ctx->error MUST be set to an appropriate value other than * X509_V_OK. */ static int v3_addr_validate_path_internal(X509_STORE_CTX *ctx, STACK_OF(X509) *chain, IPAddrBlocks *ext) { IPAddrBlocks *child = NULL; int i, j, ret = 1; X509 *x; OPENSSL_assert(chain != NULL && sk_X509_num(chain) > 0); OPENSSL_assert(ctx != NULL || ext != NULL); OPENSSL_assert(ctx == NULL || ctx->verify_cb != NULL); /* * Figure out where to start. If we don't have an extension to * check, we're done. Otherwise, check canonical form and * set up for walking up the chain. */ if (ext != NULL) { i = -1; x = NULL; } else { i = 0; x = sk_X509_value(chain, i); OPENSSL_assert(x != NULL); if ((ext = x->rfc3779_addr) == NULL) goto done; } if (!v3_addr_is_canonical(ext)) validation_err(X509_V_ERR_INVALID_EXTENSION); (void)sk_IPAddressFamily_set_cmp_func(ext, IPAddressFamily_cmp); if ((child = sk_IPAddressFamily_dup(ext)) == NULL) { X509V3err(X509V3_F_V3_ADDR_VALIDATE_PATH_INTERNAL, ERR_R_MALLOC_FAILURE); ctx->error = X509_V_ERR_OUT_OF_MEM; ret = 0; goto done; } /* * Now walk up the chain. No cert may list resources that its * parent doesn't list. */ for (i++; i < sk_X509_num(chain); i++) { x = sk_X509_value(chain, i); OPENSSL_assert(x != NULL); if (!v3_addr_is_canonical(x->rfc3779_addr)) validation_err(X509_V_ERR_INVALID_EXTENSION); if (x->rfc3779_addr == NULL) { for (j = 0; j < sk_IPAddressFamily_num(child); j++) { IPAddressFamily *fc = sk_IPAddressFamily_value(child, j); if (fc->ipAddressChoice->type != IPAddressChoice_inherit) { validation_err(X509_V_ERR_UNNESTED_RESOURCE); break; } } continue; } (void)sk_IPAddressFamily_set_cmp_func(x->rfc3779_addr, IPAddressFamily_cmp); for (j = 0; j < sk_IPAddressFamily_num(child); j++) { IPAddressFamily *fc = sk_IPAddressFamily_value(child, j); int k = sk_IPAddressFamily_find(x->rfc3779_addr, fc); IPAddressFamily *fp = sk_IPAddressFamily_value(x->rfc3779_addr, k); if (fp == NULL) { if (fc->ipAddressChoice->type == IPAddressChoice_addressesOrRanges) { validation_err(X509_V_ERR_UNNESTED_RESOURCE); break; } continue; } if (fp->ipAddressChoice->type == IPAddressChoice_addressesOrRanges) { if (fc->ipAddressChoice->type == IPAddressChoice_inherit || addr_contains(fp->ipAddressChoice->u.addressesOrRanges, fc->ipAddressChoice->u.addressesOrRanges, length_from_afi(v3_addr_get_afi(fc)))) sk_IPAddressFamily_set(child, j, fp); else validation_err(X509_V_ERR_UNNESTED_RESOURCE); } } } /* * Trust anchor can't inherit. */ OPENSSL_assert(x != NULL); if (x->rfc3779_addr != NULL) { for (j = 0; j < sk_IPAddressFamily_num(x->rfc3779_addr); j++) { IPAddressFamily *fp = sk_IPAddressFamily_value(x->rfc3779_addr, j); if (fp->ipAddressChoice->type == IPAddressChoice_inherit && sk_IPAddressFamily_find(child, fp) >= 0) validation_err(X509_V_ERR_UNNESTED_RESOURCE); } } done: sk_IPAddressFamily_free(child); return ret; } # undef validation_err /* * RFC 3779 2.3 path validation -- called from X509_verify_cert(). */ int v3_addr_validate_path(X509_STORE_CTX *ctx) { return v3_addr_validate_path_internal(ctx, ctx->chain, NULL); } /* * RFC 3779 2.3 path validation of an extension. * Test whether chain covers extension. */ int v3_addr_validate_resource_set(STACK_OF(X509) *chain, IPAddrBlocks *ext, int allow_inheritance) { if (ext == NULL) return 1; if (chain == NULL || sk_X509_num(chain) == 0) return 0; if (!allow_inheritance && v3_addr_inherits(ext)) return 0; return v3_addr_validate_path_internal(NULL, chain, ext); } #endif /* OPENSSL_NO_RFC3779 */ Index: vendor-crypto/openssl/dist/crypto/x509v3/v3_genn.c =================================================================== --- vendor-crypto/openssl/dist/crypto/x509v3/v3_genn.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/x509v3/v3_genn.c (revision 325326) @@ -1,250 +1,251 @@ /* v3_genn.c */ /* * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project * 1999. */ /* ==================================================================== * Copyright (c) 1999-2008 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 ASN1_SEQUENCE(OTHERNAME) = { ASN1_SIMPLE(OTHERNAME, type_id, ASN1_OBJECT), /* Maybe have a true ANY DEFINED BY later */ ASN1_EXP(OTHERNAME, value, ASN1_ANY, 0) } ASN1_SEQUENCE_END(OTHERNAME) IMPLEMENT_ASN1_FUNCTIONS(OTHERNAME) ASN1_SEQUENCE(EDIPARTYNAME) = { ASN1_IMP_OPT(EDIPARTYNAME, nameAssigner, DIRECTORYSTRING, 0), ASN1_IMP_OPT(EDIPARTYNAME, partyName, DIRECTORYSTRING, 1) } ASN1_SEQUENCE_END(EDIPARTYNAME) IMPLEMENT_ASN1_FUNCTIONS(EDIPARTYNAME) ASN1_CHOICE(GENERAL_NAME) = { ASN1_IMP(GENERAL_NAME, d.otherName, OTHERNAME, GEN_OTHERNAME), ASN1_IMP(GENERAL_NAME, d.rfc822Name, ASN1_IA5STRING, GEN_EMAIL), ASN1_IMP(GENERAL_NAME, d.dNSName, ASN1_IA5STRING, GEN_DNS), /* Don't decode this */ ASN1_IMP(GENERAL_NAME, d.x400Address, ASN1_SEQUENCE, GEN_X400), /* X509_NAME is a CHOICE type so use EXPLICIT */ ASN1_EXP(GENERAL_NAME, d.directoryName, X509_NAME, GEN_DIRNAME), ASN1_IMP(GENERAL_NAME, d.ediPartyName, EDIPARTYNAME, GEN_EDIPARTY), ASN1_IMP(GENERAL_NAME, d.uniformResourceIdentifier, ASN1_IA5STRING, GEN_URI), ASN1_IMP(GENERAL_NAME, d.iPAddress, ASN1_OCTET_STRING, GEN_IPADD), ASN1_IMP(GENERAL_NAME, d.registeredID, ASN1_OBJECT, GEN_RID) } ASN1_CHOICE_END(GENERAL_NAME) IMPLEMENT_ASN1_FUNCTIONS(GENERAL_NAME) ASN1_ITEM_TEMPLATE(GENERAL_NAMES) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, GeneralNames, GENERAL_NAME) ASN1_ITEM_TEMPLATE_END(GENERAL_NAMES) IMPLEMENT_ASN1_FUNCTIONS(GENERAL_NAMES) GENERAL_NAME *GENERAL_NAME_dup(GENERAL_NAME *a) { return (GENERAL_NAME *)ASN1_dup((i2d_of_void *)i2d_GENERAL_NAME, (d2i_of_void *)d2i_GENERAL_NAME, (char *)a); } /* Returns 0 if they are equal, != 0 otherwise. */ int GENERAL_NAME_cmp(GENERAL_NAME *a, GENERAL_NAME *b) { int result = -1; if (!a || !b || a->type != b->type) return -1; switch (a->type) { case GEN_X400: case GEN_EDIPARTY: result = ASN1_TYPE_cmp(a->d.other, b->d.other); break; case GEN_OTHERNAME: result = OTHERNAME_cmp(a->d.otherName, b->d.otherName); break; case GEN_EMAIL: case GEN_DNS: case GEN_URI: result = ASN1_STRING_cmp(a->d.ia5, b->d.ia5); break; case GEN_DIRNAME: result = X509_NAME_cmp(a->d.dirn, b->d.dirn); break; case GEN_IPADD: result = ASN1_OCTET_STRING_cmp(a->d.ip, b->d.ip); break; case GEN_RID: result = OBJ_cmp(a->d.rid, b->d.rid); break; } return result; } /* Returns 0 if they are equal, != 0 otherwise. */ int OTHERNAME_cmp(OTHERNAME *a, OTHERNAME *b) { int result = -1; if (!a || !b) return -1; /* Check their type first. */ if ((result = OBJ_cmp(a->type_id, b->type_id)) != 0) return result; /* Check the value. */ result = ASN1_TYPE_cmp(a->value, b->value); return result; } void GENERAL_NAME_set0_value(GENERAL_NAME *a, int type, void *value) { switch (type) { case GEN_X400: case GEN_EDIPARTY: a->d.other = value; break; case GEN_OTHERNAME: a->d.otherName = value; break; case GEN_EMAIL: case GEN_DNS: case GEN_URI: a->d.ia5 = value; break; case GEN_DIRNAME: a->d.dirn = value; break; case GEN_IPADD: a->d.ip = value; break; case GEN_RID: a->d.rid = value; break; } a->type = type; } void *GENERAL_NAME_get0_value(GENERAL_NAME *a, int *ptype) { if (ptype) *ptype = a->type; switch (a->type) { case GEN_X400: case GEN_EDIPARTY: return a->d.other; case GEN_OTHERNAME: return a->d.otherName; case GEN_EMAIL: case GEN_DNS: case GEN_URI: return a->d.ia5; case GEN_DIRNAME: return a->d.dirn; case GEN_IPADD: return a->d.ip; case GEN_RID: return a->d.rid; default: return NULL; } } int GENERAL_NAME_set0_othername(GENERAL_NAME *gen, ASN1_OBJECT *oid, ASN1_TYPE *value) { OTHERNAME *oth; oth = OTHERNAME_new(); if (!oth) return 0; + ASN1_TYPE_free(oth->value); oth->type_id = oid; oth->value = value; GENERAL_NAME_set0_value(gen, GEN_OTHERNAME, oth); return 1; } int GENERAL_NAME_get0_otherName(GENERAL_NAME *gen, ASN1_OBJECT **poid, ASN1_TYPE **pvalue) { if (gen->type != GEN_OTHERNAME) return 0; if (poid) *poid = gen->d.otherName->type_id; if (pvalue) *pvalue = gen->d.otherName->value; return 1; } Index: vendor-crypto/openssl/dist/crypto/x509v3/v3_ncons.c =================================================================== --- vendor-crypto/openssl/dist/crypto/x509v3/v3_ncons.c (revision 325325) +++ vendor-crypto/openssl/dist/crypto/x509v3/v3_ncons.c (revision 325326) @@ -1,479 +1,520 @@ /* v3_ncons.c */ /* * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL * project. */ /* ==================================================================== * Copyright (c) 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 #include static void *v2i_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval); static int i2r_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, void *a, BIO *bp, int ind); static int do_i2r_name_constraints(const X509V3_EXT_METHOD *method, STACK_OF(GENERAL_SUBTREE) *trees, BIO *bp, int ind, char *name); static int print_nc_ipadd(BIO *bp, ASN1_OCTET_STRING *ip); static int nc_match(GENERAL_NAME *gen, NAME_CONSTRAINTS *nc); static int nc_match_single(GENERAL_NAME *sub, GENERAL_NAME *gen); static int nc_dn(X509_NAME *sub, X509_NAME *nm); static int nc_dns(ASN1_IA5STRING *sub, ASN1_IA5STRING *dns); static int nc_email(ASN1_IA5STRING *sub, ASN1_IA5STRING *eml); static int nc_uri(ASN1_IA5STRING *uri, ASN1_IA5STRING *base); const X509V3_EXT_METHOD v3_name_constraints = { NID_name_constraints, 0, ASN1_ITEM_ref(NAME_CONSTRAINTS), 0, 0, 0, 0, 0, 0, 0, v2i_NAME_CONSTRAINTS, i2r_NAME_CONSTRAINTS, 0, NULL }; ASN1_SEQUENCE(GENERAL_SUBTREE) = { ASN1_SIMPLE(GENERAL_SUBTREE, base, GENERAL_NAME), ASN1_IMP_OPT(GENERAL_SUBTREE, minimum, ASN1_INTEGER, 0), ASN1_IMP_OPT(GENERAL_SUBTREE, maximum, ASN1_INTEGER, 1) } ASN1_SEQUENCE_END(GENERAL_SUBTREE) ASN1_SEQUENCE(NAME_CONSTRAINTS) = { ASN1_IMP_SEQUENCE_OF_OPT(NAME_CONSTRAINTS, permittedSubtrees, GENERAL_SUBTREE, 0), ASN1_IMP_SEQUENCE_OF_OPT(NAME_CONSTRAINTS, excludedSubtrees, GENERAL_SUBTREE, 1), } ASN1_SEQUENCE_END(NAME_CONSTRAINTS) IMPLEMENT_ASN1_ALLOC_FUNCTIONS(GENERAL_SUBTREE) IMPLEMENT_ASN1_ALLOC_FUNCTIONS(NAME_CONSTRAINTS) +/* + * We cannot use strncasecmp here because that applies locale specific rules. + * For example in Turkish 'I' is not the uppercase character for 'i'. We need to + * do a simple ASCII case comparison ignoring the locale (that is why we use + * numeric constants below). + */ +static int ia5ncasecmp(const char *s1, const char *s2, size_t n) +{ + for (; n > 0; n--, s1++, s2++) { + if (*s1 != *s2) { + unsigned char c1 = (unsigned char)*s1, c2 = (unsigned char)*s2; + + /* Convert to lower case */ + if (c1 >= 0x41 /* A */ && c1 <= 0x5A /* Z */) + c1 += 0x20; + if (c2 >= 0x41 /* A */ && c2 <= 0x5A /* Z */) + c2 += 0x20; + + if (c1 == c2) + continue; + + if (c1 < c2) + return -1; + + /* c1 > c2 */ + return 1; + } else if (*s1 == 0) { + /* If we get here we know that *s2 == 0 too */ + return 0; + } + } + + return 0; +} + +static int ia5casecmp(const char *s1, const char *s2) +{ + /* No portable definition of SIZE_MAX, so we use (size_t)(-1) instead */ + return ia5ncasecmp(s1, s2, (size_t)(-1)); +} + static void *v2i_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval) { int i; CONF_VALUE tval, *val; STACK_OF(GENERAL_SUBTREE) **ptree = NULL; NAME_CONSTRAINTS *ncons = NULL; GENERAL_SUBTREE *sub = NULL; ncons = NAME_CONSTRAINTS_new(); if (!ncons) goto memerr; for (i = 0; i < sk_CONF_VALUE_num(nval); i++) { val = sk_CONF_VALUE_value(nval, i); if (!strncmp(val->name, "permitted", 9) && val->name[9]) { ptree = &ncons->permittedSubtrees; tval.name = val->name + 10; } else if (!strncmp(val->name, "excluded", 8) && val->name[8]) { ptree = &ncons->excludedSubtrees; tval.name = val->name + 9; } else { X509V3err(X509V3_F_V2I_NAME_CONSTRAINTS, X509V3_R_INVALID_SYNTAX); goto err; } tval.value = val->value; sub = GENERAL_SUBTREE_new(); if (sub == NULL) goto memerr; if (!v2i_GENERAL_NAME_ex(sub->base, method, ctx, &tval, 1)) goto err; if (!*ptree) *ptree = sk_GENERAL_SUBTREE_new_null(); if (!*ptree || !sk_GENERAL_SUBTREE_push(*ptree, sub)) goto memerr; sub = NULL; } return ncons; memerr: X509V3err(X509V3_F_V2I_NAME_CONSTRAINTS, ERR_R_MALLOC_FAILURE); err: if (ncons) NAME_CONSTRAINTS_free(ncons); if (sub) GENERAL_SUBTREE_free(sub); return NULL; } static int i2r_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, void *a, BIO *bp, int ind) { NAME_CONSTRAINTS *ncons = a; do_i2r_name_constraints(method, ncons->permittedSubtrees, bp, ind, "Permitted"); do_i2r_name_constraints(method, ncons->excludedSubtrees, bp, ind, "Excluded"); return 1; } static int do_i2r_name_constraints(const X509V3_EXT_METHOD *method, STACK_OF(GENERAL_SUBTREE) *trees, BIO *bp, int ind, char *name) { GENERAL_SUBTREE *tree; int i; if (sk_GENERAL_SUBTREE_num(trees) > 0) BIO_printf(bp, "%*s%s:\n", ind, "", name); for (i = 0; i < sk_GENERAL_SUBTREE_num(trees); i++) { tree = sk_GENERAL_SUBTREE_value(trees, i); BIO_printf(bp, "%*s", ind + 2, ""); if (tree->base->type == GEN_IPADD) print_nc_ipadd(bp, tree->base->d.ip); else GENERAL_NAME_print(bp, tree->base); BIO_puts(bp, "\n"); } return 1; } static int print_nc_ipadd(BIO *bp, ASN1_OCTET_STRING *ip) { int i, len; unsigned char *p; p = ip->data; len = ip->length; BIO_puts(bp, "IP:"); if (len == 8) { BIO_printf(bp, "%d.%d.%d.%d/%d.%d.%d.%d", p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]); } else if (len == 32) { for (i = 0; i < 16; i++) { BIO_printf(bp, "%X", p[0] << 8 | p[1]); p += 2; if (i == 7) BIO_puts(bp, "/"); else if (i != 15) BIO_puts(bp, ":"); } } else BIO_printf(bp, "IP Address:"); return 1; } /*- * Check a certificate conforms to a specified set of constraints. * Return values: * X509_V_OK: All constraints obeyed. * X509_V_ERR_PERMITTED_VIOLATION: Permitted subtree violation. * X509_V_ERR_EXCLUDED_VIOLATION: Excluded subtree violation. * X509_V_ERR_SUBTREE_MINMAX: Min or max values present and matching type. * X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE: Unsupported constraint type. * X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX: bad unsupported constraint syntax. * X509_V_ERR_UNSUPPORTED_NAME_SYNTAX: bad or unsupported syntax of name */ int NAME_CONSTRAINTS_check(X509 *x, NAME_CONSTRAINTS *nc) { int r, i; X509_NAME *nm; nm = X509_get_subject_name(x); if (X509_NAME_entry_count(nm) > 0) { GENERAL_NAME gntmp; gntmp.type = GEN_DIRNAME; gntmp.d.directoryName = nm; r = nc_match(&gntmp, nc); if (r != X509_V_OK) return r; gntmp.type = GEN_EMAIL; /* Process any email address attributes in subject name */ for (i = -1;;) { X509_NAME_ENTRY *ne; i = X509_NAME_get_index_by_NID(nm, NID_pkcs9_emailAddress, i); if (i == -1) break; ne = X509_NAME_get_entry(nm, i); gntmp.d.rfc822Name = X509_NAME_ENTRY_get_data(ne); if (gntmp.d.rfc822Name->type != V_ASN1_IA5STRING) return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX; r = nc_match(&gntmp, nc); if (r != X509_V_OK) return r; } } for (i = 0; i < sk_GENERAL_NAME_num(x->altname); i++) { GENERAL_NAME *gen = sk_GENERAL_NAME_value(x->altname, i); r = nc_match(gen, nc); if (r != X509_V_OK) return r; } return X509_V_OK; } static int nc_match(GENERAL_NAME *gen, NAME_CONSTRAINTS *nc) { GENERAL_SUBTREE *sub; int i, r, match = 0; /* * Permitted subtrees: if any subtrees exist of matching the type at * least one subtree must match. */ for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->permittedSubtrees); i++) { sub = sk_GENERAL_SUBTREE_value(nc->permittedSubtrees, i); if (gen->type != sub->base->type) continue; if (sub->minimum || sub->maximum) return X509_V_ERR_SUBTREE_MINMAX; /* If we already have a match don't bother trying any more */ if (match == 2) continue; if (match == 0) match = 1; r = nc_match_single(gen, sub->base); if (r == X509_V_OK) match = 2; else if (r != X509_V_ERR_PERMITTED_VIOLATION) return r; } if (match == 1) return X509_V_ERR_PERMITTED_VIOLATION; /* Excluded subtrees: must not match any of these */ for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->excludedSubtrees); i++) { sub = sk_GENERAL_SUBTREE_value(nc->excludedSubtrees, i); if (gen->type != sub->base->type) continue; if (sub->minimum || sub->maximum) return X509_V_ERR_SUBTREE_MINMAX; r = nc_match_single(gen, sub->base); if (r == X509_V_OK) return X509_V_ERR_EXCLUDED_VIOLATION; else if (r != X509_V_ERR_PERMITTED_VIOLATION) return r; } return X509_V_OK; } static int nc_match_single(GENERAL_NAME *gen, GENERAL_NAME *base) { switch (base->type) { case GEN_DIRNAME: return nc_dn(gen->d.directoryName, base->d.directoryName); case GEN_DNS: return nc_dns(gen->d.dNSName, base->d.dNSName); case GEN_EMAIL: return nc_email(gen->d.rfc822Name, base->d.rfc822Name); case GEN_URI: return nc_uri(gen->d.uniformResourceIdentifier, base->d.uniformResourceIdentifier); default: return X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE; } } /* * directoryName name constraint matching. The canonical encoding of * X509_NAME makes this comparison easy. It is matched if the subtree is a * subset of the name. */ static int nc_dn(X509_NAME *nm, X509_NAME *base) { /* Ensure canonical encodings are up to date. */ if (nm->modified && i2d_X509_NAME(nm, NULL) < 0) return X509_V_ERR_OUT_OF_MEM; if (base->modified && i2d_X509_NAME(base, NULL) < 0) return X509_V_ERR_OUT_OF_MEM; if (base->canon_enclen > nm->canon_enclen) return X509_V_ERR_PERMITTED_VIOLATION; if (memcmp(base->canon_enc, nm->canon_enc, base->canon_enclen)) return X509_V_ERR_PERMITTED_VIOLATION; return X509_V_OK; } static int nc_dns(ASN1_IA5STRING *dns, ASN1_IA5STRING *base) { char *baseptr = (char *)base->data; char *dnsptr = (char *)dns->data; /* Empty matches everything */ if (!*baseptr) return X509_V_OK; /* * Otherwise can add zero or more components on the left so compare RHS * and if dns is longer and expect '.' as preceding character. */ if (dns->length > base->length) { dnsptr += dns->length - base->length; if (*baseptr != '.' && dnsptr[-1] != '.') return X509_V_ERR_PERMITTED_VIOLATION; } - if (strcasecmp(baseptr, dnsptr)) + if (ia5casecmp(baseptr, dnsptr)) return X509_V_ERR_PERMITTED_VIOLATION; return X509_V_OK; } static int nc_email(ASN1_IA5STRING *eml, ASN1_IA5STRING *base) { const char *baseptr = (char *)base->data; const char *emlptr = (char *)eml->data; const char *baseat = strchr(baseptr, '@'); const char *emlat = strchr(emlptr, '@'); if (!emlat) return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX; /* Special case: inital '.' is RHS match */ if (!baseat && (*baseptr == '.')) { if (eml->length > base->length) { emlptr += eml->length - base->length; - if (!strcasecmp(baseptr, emlptr)) + if (ia5casecmp(baseptr, emlptr) == 0) return X509_V_OK; } return X509_V_ERR_PERMITTED_VIOLATION; } /* If we have anything before '@' match local part */ if (baseat) { if (baseat != baseptr) { if ((baseat - baseptr) != (emlat - emlptr)) return X509_V_ERR_PERMITTED_VIOLATION; /* Case sensitive match of local part */ if (strncmp(baseptr, emlptr, emlat - emlptr)) return X509_V_ERR_PERMITTED_VIOLATION; } /* Position base after '@' */ baseptr = baseat + 1; } emlptr = emlat + 1; /* Just have hostname left to match: case insensitive */ - if (strcasecmp(baseptr, emlptr)) + if (ia5casecmp(baseptr, emlptr)) return X509_V_ERR_PERMITTED_VIOLATION; return X509_V_OK; } static int nc_uri(ASN1_IA5STRING *uri, ASN1_IA5STRING *base) { const char *baseptr = (char *)base->data; const char *hostptr = (char *)uri->data; const char *p = strchr(hostptr, ':'); int hostlen; /* Check for foo:// and skip past it */ if (!p || (p[1] != '/') || (p[2] != '/')) return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX; hostptr = p + 3; /* Determine length of hostname part of URI */ /* Look for a port indicator as end of hostname first */ p = strchr(hostptr, ':'); /* Otherwise look for trailing slash */ if (!p) p = strchr(hostptr, '/'); if (!p) hostlen = strlen(hostptr); else hostlen = p - hostptr; if (hostlen == 0) return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX; /* Special case: inital '.' is RHS match */ if (*baseptr == '.') { if (hostlen > base->length) { p = hostptr + hostlen - base->length; - if (!strncasecmp(p, baseptr, base->length)) + if (ia5ncasecmp(p, baseptr, base->length) == 0) return X509_V_OK; } return X509_V_ERR_PERMITTED_VIOLATION; } if ((base->length != (int)hostlen) - || strncasecmp(hostptr, baseptr, hostlen)) + || ia5ncasecmp(hostptr, baseptr, hostlen)) return X509_V_ERR_PERMITTED_VIOLATION; return X509_V_OK; } Index: vendor-crypto/openssl/dist/crypto/x86_64cpuid.pl =================================================================== --- vendor-crypto/openssl/dist/crypto/x86_64cpuid.pl (revision 325325) +++ vendor-crypto/openssl/dist/crypto/x86_64cpuid.pl (revision 325326) @@ -1,310 +1,325 @@ #!/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 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 .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 + jne .LnotP4 or \$0x00100000,%edx # set reserved bit#20 to engage RC4_CHAR +.LnotP4: + cmp \$6,%ah + jne .Lnotintel + and \$0x0fff0ff0,%eax + cmp \$0x00050670,%eax # Knights Landing + je .Lknights + cmp \$0x00080650,%eax # Knights Mill (according to sde) + jne .Lnotintel +.Lknights: + and \$0xfbffffff,%ecx # clear XSAVE flag to mimic Silvermont + .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 + bt \$26,%r9d # check XSAVE bit, cleared on Knights + jc .Lnotknights + and \$0xfff7ffff,%ebx # clear ADCX/ADOX flag +.Lnotknights: 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) + andl \$0xffffffdf,8(%rdi) # clear 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/doc/apps/asn1parse.pod =================================================================== --- vendor-crypto/openssl/dist/doc/apps/asn1parse.pod (revision 325325) +++ vendor-crypto/openssl/dist/doc/apps/asn1parse.pod (revision 325326) @@ -1,185 +1,186 @@ =pod =head1 NAME +openssl-asn1parse, asn1parse - ASN.1 parsing tool =head1 SYNOPSIS B B [B<-inform PEM|DER>] [B<-in filename>] [B<-out filename>] [B<-noout>] [B<-offset number>] [B<-length number>] [B<-i>] [B<-oid filename>] [B<-dump>] [B<-dlimit num>] [B<-strparse offset>] [B<-genstr string>] [B<-genconf file>] =head1 DESCRIPTION The B command is a diagnostic utility that can parse ASN.1 structures. It can also be used to extract data from ASN.1 formatted data. =head1 OPTIONS =over 4 =item B<-inform> B the input format. B is binary format and B (the default) is base64 encoded. =item B<-in filename> the input file, default is standard input =item B<-out filename> output file to place the DER encoded data into. If this option is not present then no data will be output. This is most useful when combined with the B<-strparse> option. =item B<-noout> don't output the parsed version of the input file. =item B<-offset number> starting offset to begin parsing, default is start of file. =item B<-length number> number of bytes to parse, default is until end of file. =item B<-i> indents the output according to the "depth" of the structures. =item B<-oid filename> a file containing additional OBJECT IDENTIFIERs (OIDs). The format of this file is described in the NOTES section below. =item B<-dump> dump unknown data in hex format. =item B<-dlimit num> like B<-dump>, but only the first B bytes are output. =item B<-strparse offset> parse the contents octets of the ASN.1 object starting at B. This option can be used multiple times to "drill down" into a nested structure. =item B<-genstr string>, B<-genconf file> generate encoded data based on B, B or both using L format. If B only is present then the string is obtained from the default section using the name B. The encoded data is passed through the ASN1 parser and printed out as though it came from a file, the contents can thus be examined and written to a file using the B option. =back =head2 OUTPUT The output will typically contain lines like this: 0:d=0 hl=4 l= 681 cons: SEQUENCE ..... 229:d=3 hl=3 l= 141 prim: BIT STRING 373:d=2 hl=3 l= 162 cons: cont [ 3 ] 376:d=3 hl=3 l= 159 cons: SEQUENCE 379:d=4 hl=2 l= 29 cons: SEQUENCE 381:d=5 hl=2 l= 3 prim: OBJECT :X509v3 Subject Key Identifier 386:d=5 hl=2 l= 22 prim: OCTET STRING 410:d=4 hl=2 l= 112 cons: SEQUENCE 412:d=5 hl=2 l= 3 prim: OBJECT :X509v3 Authority Key Identifier 417:d=5 hl=2 l= 105 prim: OCTET STRING 524:d=4 hl=2 l= 12 cons: SEQUENCE ..... This example is part of a self signed certificate. Each line starts with the offset in decimal. B specifies the current depth. The depth is increased within the scope of any SET or SEQUENCE. B gives the header length (tag and length octets) of the current type. B gives the length of the contents octets. The B<-i> option can be used to make the output more readable. Some knowledge of the ASN.1 structure is needed to interpret the output. In this example the BIT STRING at offset 229 is the certificate public key. The contents octets of this will contain the public key information. This can be examined using the option B<-strparse 229> to yield: 0:d=0 hl=3 l= 137 cons: SEQUENCE 3:d=1 hl=3 l= 129 prim: INTEGER :E5D21E1F5C8D208EA7A2166C7FAF9F6BDF2059669C60876DDB70840F1A5AAFA59699FE471F379F1DD6A487E7D5409AB6A88D4A9746E24B91D8CF55DB3521015460C8EDE44EE8A4189F7A7BE77D6CD3A9AF2696F486855CF58BF0EDF2B4068058C7A947F52548DDF7E15E96B385F86422BEA9064A3EE9E1158A56E4A6F47E5897 135:d=1 hl=2 l= 3 prim: INTEGER :010001 =head1 NOTES If an OID is not part of OpenSSL's internal table it will be represented in numerical form (for example 1.2.3.4). The file passed to the B<-oid> option allows additional OIDs to be included. Each line consists of three columns, the first column is the OID in numerical format and should be followed by white space. The second column is the "short name" which is a single word followed by white space. The final column is the rest of the line and is the "long name". B displays the long name. Example: C<1.2.3.4 shortName A long name> =head1 EXAMPLES Parse a file: openssl asn1parse -in file.pem Parse a DER file: openssl asn1parse -inform DER -in file.der Generate a simple UTF8String: openssl asn1parse -genstr 'UTF8:Hello World' Generate and write out a UTF8String, don't print parsed output: openssl asn1parse -genstr 'UTF8:Hello World' -noout -out utf8.der Generate using a config file: openssl asn1parse -genconf asn1.cnf -noout -out asn1.der Example config file: asn1=SEQUENCE:seq_sect [seq_sect] field1=BOOL:TRUE field2=EXP:0, UTF8:some random string =head1 BUGS There should be options to change the format of output lines. The output of some ASN.1 types is not well handled (if at all). =head1 SEE ALSO L =cut Index: vendor-crypto/openssl/dist/doc/apps/ca.pod =================================================================== --- vendor-crypto/openssl/dist/doc/apps/ca.pod (revision 325325) +++ vendor-crypto/openssl/dist/doc/apps/ca.pod (revision 325326) @@ -1,696 +1,697 @@ =pod =head1 NAME +openssl-ca, ca - sample minimal CA application =head1 SYNOPSIS B B [B<-verbose>] [B<-config filename>] [B<-name section>] [B<-gencrl>] [B<-revoke file>] [B<-status serial>] [B<-updatedb>] [B<-crl_reason reason>] [B<-crl_hold instruction>] [B<-crl_compromise time>] [B<-crl_CA_compromise time>] [B<-crldays days>] [B<-crlhours hours>] [B<-crlexts section>] [B<-startdate date>] [B<-enddate date>] [B<-days arg>] [B<-md arg>] [B<-policy arg>] [B<-keyfile arg>] [B<-keyform PEM|DER>] [B<-key arg>] [B<-passin arg>] [B<-cert file>] [B<-selfsign>] [B<-in file>] [B<-out file>] [B<-notext>] [B<-outdir dir>] [B<-infiles>] [B<-spkac file>] [B<-ss_cert file>] [B<-preserveDN>] [B<-noemailDN>] [B<-batch>] [B<-msie_hack>] [B<-extensions section>] [B<-extfile section>] [B<-engine id>] [B<-subj arg>] [B<-utf8>] [B<-multivalue-rdn>] =head1 DESCRIPTION The B command is a minimal CA application. It can be used to sign certificate requests in a variety of forms and generate CRLs it also maintains a text database of issued certificates and their status. The options descriptions will be divided into each purpose. =head1 CA OPTIONS =over 4 =item B<-config filename> specifies the configuration file to use. =item B<-name section> specifies the configuration file section to use (overrides B in the B section). =item B<-in filename> an input filename containing a single certificate request to be signed by the CA. =item B<-ss_cert filename> a single self signed certificate to be signed by the CA. =item B<-spkac filename> a file containing a single Netscape signed public key and challenge and additional field values to be signed by the CA. See the B section for information on the required input and output format. =item B<-infiles> if present this should be the last option, all subsequent arguments are assumed to the the names of files containing certificate requests. =item B<-out filename> the output file to output certificates to. The default is standard output. The certificate details will also be printed out to this file in PEM format (except that B<-spkac> outputs DER format). =item B<-outdir directory> the directory to output certificates to. The certificate will be written to a filename consisting of the serial number in hex with ".pem" appended. =item B<-cert> the CA certificate file. =item B<-keyfile filename> the private key to sign requests with. =item B<-keyform PEM|DER> the format of the data in the private key file. The default is PEM. =item B<-key password> the password used to encrypt the private key. Since on some systems the command line arguments are visible (e.g. Unix with the 'ps' utility) this option should be used with caution. =item B<-selfsign> indicates the issued certificates are to be signed with the key the certificate requests were signed with (given with B<-keyfile>). Cerificate requests signed with a different key are ignored. If B<-spkac>, B<-ss_cert> or B<-gencrl> are given, B<-selfsign> is ignored. A consequence of using B<-selfsign> is that the self-signed certificate appears among the entries in the certificate database (see the configuration option B), and uses the same serial number counter as all other certificates sign with the self-signed certificate. =item B<-passin arg> the key password source. For more information about the format of B see the B section in L. =item B<-verbose> this prints extra details about the operations being performed. =item B<-notext> don't output the text form of a certificate to the output file. =item B<-startdate date> this allows the start date to be explicitly set. The format of the date is YYMMDDHHMMSSZ (the same as an ASN1 UTCTime structure). =item B<-enddate date> this allows the expiry date to be explicitly set. The format of the date is YYMMDDHHMMSSZ (the same as an ASN1 UTCTime structure). =item B<-days arg> the number of days to certify the certificate for. =item B<-md alg> the message digest to use. Possible values include md5, sha1 and mdc2. This option also applies to CRLs. =item B<-policy arg> this option defines the CA "policy" to use. This is a section in the configuration file which decides which fields should be mandatory or match the CA certificate. Check out the B section for more information. =item B<-msie_hack> this is a legacy option to make B work with very old versions of the IE certificate enrollment control "certenr3". It used UniversalStrings for almost everything. Since the old control has various security bugs its use is strongly discouraged. The newer control "Xenroll" does not need this option. =item B<-preserveDN> Normally the DN order of a certificate is the same as the order of the fields in the relevant policy section. When this option is set the order is the same as the request. This is largely for compatibility with the older IE enrollment control which would only accept certificates if their DNs match the order of the request. This is not needed for Xenroll. =item B<-noemailDN> The DN of a certificate can contain the EMAIL field if present in the request DN, however it is good policy just having the e-mail set into the altName extension of the certificate. When this option is set the EMAIL field is removed from the certificate' subject and set only in the, eventually present, extensions. The B keyword can be used in the configuration file to enable this behaviour. =item B<-batch> this sets the batch mode. In this mode no questions will be asked and all certificates will be certified automatically. =item B<-extensions section> the section of the configuration file containing certificate extensions to be added when a certificate is issued (defaults to B unless the B<-extfile> option is used). If no extension section is present then, a V1 certificate is created. If the extension section is present (even if it is empty), then a V3 certificate is created. See the:w L manual page for details of the extension section format. =item B<-extfile file> an additional configuration file to read certificate extensions from (using the default section unless the B<-extensions> option is also used). =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<-subj arg> supersedes subject name given in the request. The arg must be formatted as I, characters may be escaped by \ (backslash), no spaces are skipped. =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<-multivalue-rdn> this option causes the -subj argument to be interpretedt with full support for multivalued RDNs. Example: I If -multi-rdn is not used then the UID value is I<123456+CN=John Doe>. =back =head1 CRL OPTIONS =over 4 =item B<-gencrl> this option generates a CRL based on information in the index file. =item B<-crldays num> the number of days before the next CRL is due. That is the days from now to place in the CRL nextUpdate field. =item B<-crlhours num> the number of hours before the next CRL is due. =item B<-revoke filename> a filename containing a certificate to revoke. =item B<-status serial> displays the revocation status of the certificate with the specified serial number and exits. =item B<-updatedb> Updates the database index to purge expired certificates. =item B<-crl_reason reason> revocation reason, where B is one of: B, B, B, B, B, B, B or B. The matching of B is case insensitive. Setting any revocation reason will make the CRL v2. In practive B is not particularly useful because it is only used in delta CRLs which are not currently implemented. =item B<-crl_hold instruction> This sets the CRL revocation reason code to B and the hold instruction to B which must be an OID. Although any OID can be used only B (the use of which is discouraged by RFC2459) B or B will normally be used. =item B<-crl_compromise time> This sets the revocation reason to B and the compromise time to B