diff --git a/CHANGES.md b/CHANGES.md index d5c0ba8daf1b..a26bdbdd0ad0 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,19892 +1,19917 @@ OpenSSL CHANGES =============== This is a high-level summary of the most important changes. For a full list of changes, see the [git commit log][log] and pick the appropriate release branch. [log]: https://github.com/openssl/openssl/commits/ OpenSSL Releases ---------------- - [OpenSSL 3.0](#openssl-30) - [OpenSSL 1.1.1](#openssl-111) - [OpenSSL 1.1.0](#openssl-110) - [OpenSSL 1.0.2](#openssl-102) - [OpenSSL 1.0.1](#openssl-101) - [OpenSSL 1.0.0](#openssl-100) - [OpenSSL 0.9.x](#openssl-09x) OpenSSL 3.0 ----------- For OpenSSL 3.0 a [Migration guide][] has been added, so the CHANGES entries listed here are only a brief description. The migration guide contains more detailed information related to new features, breaking changes, and mappings for the large list of deprecated functions. [Migration guide]: https://github.com/openssl/openssl/tree/master/doc/man7/migration_guide.pod +### Changes between 3.0.10 and 3.0.11 [19 Sep 2023] + + * Fix POLY1305 MAC implementation corrupting XMM registers on Windows. + + The POLY1305 MAC (message authentication code) implementation in OpenSSL + does not save the contents of non-volatile XMM registers on Windows 64 + platform when calculating the MAC of data larger than 64 bytes. Before + returning to the caller all the XMM registers are set to zero rather than + restoring their previous content. The vulnerable code is used only on newer + x86_64 processors supporting the AVX512-IFMA instructions. + + The consequences of this kind of internal application state corruption can + be various - from no consequences, if the calling application does not + depend on the contents of non-volatile XMM registers at all, to the worst + consequences, where the attacker could get complete control of the + application process. However given the contents of the registers are just + zeroized so the attacker cannot put arbitrary values inside, the most likely + consequence, if any, would be an incorrect result of some application + dependent calculations or a crash leading to a denial of service. + + ([CVE-2023-4807]) + + *Bernd Edlinger* + ### Changes between 3.0.9 and 3.0.10 [1 Aug 2023] * Fix excessive time spent checking DH q parameter value. The function DH_check() performs various checks on DH parameters. After fixing CVE-2023-3446 it was discovered that a large q parameter value can also trigger an overly long computation during some of these checks. A correct q value, if present, cannot be larger than the modulus p parameter, thus it is unnecessary to perform these checks if q is larger than p. If DH_check() is called with such q parameter value, DH_CHECK_INVALID_Q_VALUE return flag is set and the computationally intensive checks are skipped. ([CVE-2023-3817]) *Tomáš Mráz* * Fix DH_check() excessive time with over sized modulus. The function DH_check() performs various checks on DH parameters. One of those checks confirms that the modulus ("p" parameter) is not too large. Trying to use a very large modulus is slow and OpenSSL will not normally use a modulus which is over 10,000 bits in length. However the DH_check() function checks numerous aspects of the key or parameters that have been supplied. Some of those checks use the supplied modulus value even if it has already been found to be too large. A new limit has been added to DH_check of 32,768 bits. Supplying a key/parameters with a modulus over this size will simply cause DH_check() to fail. ([CVE-2023-3446]) *Matt Caswell* * Do not ignore empty associated data entries with AES-SIV. The AES-SIV algorithm allows for authentication of multiple associated data entries along with the encryption. To authenticate empty data the application has to call `EVP_EncryptUpdate()` (or `EVP_CipherUpdate()`) with NULL pointer as the output buffer and 0 as the input buffer length. The AES-SIV implementation in OpenSSL just returns success for such call instead of performing the associated data authentication operation. The empty data thus will not be authenticated. ([CVE-2023-2975]) Thanks to Juerg Wullschleger (Google) for discovering the issue. The fix changes the authentication tag value and the ciphertext for applications that use empty associated data entries with AES-SIV. To decrypt data encrypted with previous versions of OpenSSL the application has to skip calls to `EVP_DecryptUpdate()` for empty associated data entries. *Tomáš Mráz* ### Changes between 3.0.8 and 3.0.9 [30 May 2023] * Mitigate for the time it takes for `OBJ_obj2txt` to translate gigantic OBJECT IDENTIFIER sub-identifiers to canonical numeric text form. OBJ_obj2txt() would translate any size OBJECT IDENTIFIER to canonical numeric text form. For gigantic sub-identifiers, this would take a very long time, the time complexity being O(n^2) where n is the size of that sub-identifier. ([CVE-2023-2650]) To mitigitate this, `OBJ_obj2txt()` will only translate an OBJECT IDENTIFIER to canonical numeric text form if the size of that OBJECT IDENTIFIER is 586 bytes or less, and fail otherwise. The basis for this restriction is [RFC 2578 (STD 58), section 3.5]. OBJECT IDENTIFIER values, which stipulates that OBJECT IDENTIFIERS may have at most 128 sub-identifiers, and that the maximum value that each sub- identifier may have is 2^32-1 (4294967295 decimal). For each byte of every sub-identifier, only the 7 lower bits are part of the value, so the maximum amount of bytes that an OBJECT IDENTIFIER with these restrictions may occupy is 32 * 128 / 7, which is approximately 586 bytes. *Richard Levitte* * Fixed buffer overread in AES-XTS decryption on ARM 64 bit platforms which happens if the buffer size is 4 mod 5 in 16 byte AES blocks. This can trigger a crash of an application using AES-XTS decryption if the memory just after the buffer being decrypted is not mapped. Thanks to Anton Romanov (Amazon) for discovering the issue. ([CVE-2023-1255]) *Nevine Ebeid* * Reworked the Fix for the Timing Oracle in RSA Decryption ([CVE-2022-4304]). The previous fix for this timing side channel turned out to cause a severe 2-3x performance regression in the typical use case compared to 3.0.7. The new fix uses existing constant time code paths, and restores the previous performance level while fully eliminating all existing timing side channels. The fix was developed by Bernd Edlinger with testing support by Hubert Kario. *Bernd Edlinger* * Corrected documentation of X509_VERIFY_PARAM_add0_policy() to mention that it does not enable policy checking. Thanks to David Benjamin for discovering this issue. ([CVE-2023-0466]) *Tomáš Mráz* * Fixed an issue where invalid certificate policies in leaf certificates are silently ignored by OpenSSL and other certificate policy checks are skipped for that certificate. A malicious CA could use this to deliberately assert invalid certificate policies in order to circumvent policy checking on the certificate altogether. ([CVE-2023-0465]) *Matt Caswell* * Limited the number of nodes created in a policy tree to mitigate against CVE-2023-0464. The default limit is set to 1000 nodes, which should be sufficient for most installations. If required, the limit can be adjusted by setting the OPENSSL_POLICY_TREE_NODES_MAX build time define to a desired maximum number of nodes or zero to allow unlimited growth. ([CVE-2023-0464]) *Paul Dale* ### Changes between 3.0.7 and 3.0.8 [7 Feb 2023] * Fixed NULL dereference during PKCS7 data verification. A NULL pointer can be dereferenced when signatures are being verified on PKCS7 signed or signedAndEnveloped data. In case the hash algorithm used for the signature is known to the OpenSSL library but the implementation of the hash algorithm is not available the digest initialization will fail. There is a missing check for the return value from the initialization function which later leads to invalid usage of the digest API most likely leading to a crash. ([CVE-2023-0401]) PKCS7 data is processed by the SMIME library calls and also by the time stamp (TS) library calls. The TLS implementation in OpenSSL does not call these functions however third party applications would be affected if they call these functions to verify signatures on untrusted data. *Tomáš Mráz* * Fixed X.400 address type confusion in X.509 GeneralName. There is a type confusion vulnerability relating to X.400 address processing inside an X.509 GeneralName. X.400 addresses were parsed as an ASN1_STRING but the public structure definition for GENERAL_NAME incorrectly specified the type of the x400Address field as ASN1_TYPE. This field is subsequently interpreted by the OpenSSL function GENERAL_NAME_cmp as an ASN1_TYPE rather than an ASN1_STRING. When CRL checking is enabled (i.e. the application sets the X509_V_FLAG_CRL_CHECK flag), this vulnerability may allow an attacker to pass arbitrary pointers to a memcmp call, enabling them to read memory contents or enact a denial of service. ([CVE-2023-0286]) *Hugo Landau* * Fixed NULL dereference validating DSA public key. An invalid pointer dereference on read can be triggered when an application tries to check a malformed DSA public key by the EVP_PKEY_public_check() function. This will most likely lead to an application crash. This function can be called on public keys supplied from untrusted sources which could allow an attacker to cause a denial of service attack. The TLS implementation in OpenSSL does not call this function but applications might call the function if there are additional security requirements imposed by standards such as FIPS 140-3. ([CVE-2023-0217]) *Shane Lontis, Tomáš Mráz* * Fixed Invalid pointer dereference in d2i_PKCS7 functions. An invalid pointer dereference on read can be triggered when an application tries to load malformed PKCS7 data with the d2i_PKCS7(), d2i_PKCS7_bio() or d2i_PKCS7_fp() functions. The result of the dereference is an application crash which could lead to a denial of service attack. The TLS implementation in OpenSSL does not call this function however third party applications might call these functions on untrusted data. ([CVE-2023-0216]) *Tomáš Mráz* * Fixed Use-after-free following BIO_new_NDEF. The public API function BIO_new_NDEF is a helper function used for streaming ASN.1 data via a BIO. It is primarily used internally to OpenSSL to support the SMIME, CMS and PKCS7 streaming capabilities, but may also be called directly by end user applications. The function receives a BIO from the caller, prepends a new BIO_f_asn1 filter BIO onto the front of it to form a BIO chain, and then returns the new head of the BIO chain to the caller. Under certain conditions, for example if a CMS recipient public key is invalid, the new filter BIO is freed and the function returns a NULL result indicating a failure. However, in this case, the BIO chain is not properly cleaned up and the BIO passed by the caller still retains internal pointers to the previously freed filter BIO. If the caller then goes on to call BIO_pop() on the BIO then a use-after-free will occur. This will most likely result in a crash. ([CVE-2023-0215]) *Viktor Dukhovni, Matt Caswell* * Fixed Double free after calling PEM_read_bio_ex. The function PEM_read_bio_ex() reads a PEM file from a BIO and parses and decodes the "name" (e.g. "CERTIFICATE"), any header data and the payload data. If the function succeeds then the "name_out", "header" and "data" arguments are populated with pointers to buffers containing the relevant decoded data. The caller is responsible for freeing those buffers. It is possible to construct a PEM file that results in 0 bytes of payload data. In this case PEM_read_bio_ex() will return a failure code but will populate the header argument with a pointer to a buffer that has already been freed. If the caller also frees this buffer then a double free will occur. This will most likely lead to a crash. The functions PEM_read_bio() and PEM_read() are simple wrappers around PEM_read_bio_ex() and therefore these functions are also directly affected. These functions are also called indirectly by a number of other OpenSSL functions including PEM_X509_INFO_read_bio_ex() and SSL_CTX_use_serverinfo_file() which are also vulnerable. Some OpenSSL internal uses of these functions are not vulnerable because the caller does not free the header argument if PEM_read_bio_ex() returns a failure code. ([CVE-2022-4450]) *Kurt Roeckx, Matt Caswell* * Fixed Timing Oracle in RSA Decryption. A timing based side channel exists in the OpenSSL RSA Decryption implementation which could be sufficient to recover a plaintext across a network in a Bleichenbacher style attack. To achieve a successful decryption an attacker would have to be able to send a very large number of trial messages for decryption. The vulnerability affects all RSA padding modes: PKCS#1 v1.5, RSA-OEAP and RSASVE. ([CVE-2022-4304]) *Dmitry Belyavsky, Hubert Kario* * Fixed X.509 Name Constraints Read Buffer Overflow. A read buffer overrun can be triggered in X.509 certificate verification, specifically in name constraint checking. The read buffer overrun might result in a crash which could lead to a denial of service attack. In a TLS client, this can be triggered by connecting to a malicious server. In a TLS server, this can be triggered if the server requests client authentication and a malicious client connects. ([CVE-2022-4203]) *Viktor Dukhovni* * Fixed X.509 Policy Constraints Double Locking security issue. If an X.509 certificate contains a malformed policy constraint and policy processing is enabled, then a write lock will be taken twice recursively. On some operating systems (most widely: Windows) this results in a denial of service when the affected process hangs. Policy processing being enabled on a publicly facing server is not considered to be a common setup. ([CVE-2022-3996]) *Paul Dale* * Our provider implementations of `OSSL_FUNC_KEYMGMT_EXPORT` and `OSSL_FUNC_KEYMGMT_GET_PARAMS` for EC and SM2 keys now honor `OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT` as set (and default to `POINT_CONVERSION_UNCOMPRESSED`) when exporting `OSSL_PKEY_PARAM_PUB_KEY`, instead of unconditionally using `POINT_CONVERSION_COMPRESSED` as in previous 3.x releases. For symmetry, our implementation of `EVP_PKEY_ASN1_METHOD->export_to` for legacy EC and SM2 keys is also changed similarly to honor the equivalent conversion format flag as specified in the underlying `EC_KEY` object being exported to a provider, when this function is called through `EVP_PKEY_export()`. *Nicola Tuveri* ### Changes between 3.0.6 and 3.0.7 [1 Nov 2022] * Fixed two buffer overflows in punycode decoding functions. A buffer overrun can be triggered in X.509 certificate verification, specifically in name constraint checking. Note that this occurs after certificate chain signature verification and requires either a CA to have signed the malicious certificate or for the application to continue certificate verification despite failure to construct a path to a trusted issuer. In a TLS client, this can be triggered by connecting to a malicious server. In a TLS server, this can be triggered if the server requests client authentication and a malicious client connects. An attacker can craft a malicious email address to overflow an arbitrary number of bytes containing the `.` character (decimal 46) on the stack. This buffer overflow could result in a crash (causing a denial of service). ([CVE-2022-3786]) An attacker can craft a malicious email address to overflow four attacker-controlled bytes on the stack. This buffer overflow could result in a crash (causing a denial of service) or potentially remote code execution depending on stack layout for any given platform/compiler. ([CVE-2022-3602]) *Paul Dale* * Removed all references to invalid OSSL_PKEY_PARAM_RSA names for CRT parameters in OpenSSL code. Applications should not use the names OSSL_PKEY_PARAM_RSA_FACTOR, OSSL_PKEY_PARAM_RSA_EXPONENT and OSSL_PKEY_PARAM_RSA_COEFFICIENT. Use the numbered names such as OSSL_PKEY_PARAM_RSA_FACTOR1 instead. Using these invalid names may cause algorithms to use slower methods that ignore the CRT parameters. *Shane Lontis* * Fixed a regression introduced in 3.0.6 version raising errors on some stack operations. *Tomáš Mráz* * Fixed a regression introduced in 3.0.6 version not refreshing the certificate data to be signed before signing the certificate. *Gibeom Gwon* * Added RIPEMD160 to the default provider. *Paul Dale* * Ensured that the key share group sent or accepted for the key exchange is allowed for the protocol version. *Matt Caswell* ### Changes between 3.0.5 and 3.0.6 [11 Oct 2022] * OpenSSL supports creating a custom cipher via the legacy EVP_CIPHER_meth_new() function and associated function calls. This function was deprecated in OpenSSL 3.0 and application authors are instead encouraged to use the new provider mechanism in order to implement custom ciphers. OpenSSL versions 3.0.0 to 3.0.5 incorrectly handle legacy custom ciphers passed to the EVP_EncryptInit_ex2(), EVP_DecryptInit_ex2() and EVP_CipherInit_ex2() functions (as well as other similarly named encryption and decryption initialisation functions). Instead of using the custom cipher directly it incorrectly tries to fetch an equivalent cipher from the available providers. An equivalent cipher is found based on the NID passed to EVP_CIPHER_meth_new(). This NID is supposed to represent the unique NID for a given cipher. However it is possible for an application to incorrectly pass NID_undef as this value in the call to EVP_CIPHER_meth_new(). When NID_undef is used in this way the OpenSSL encryption/decryption initialisation function will match the NULL cipher as being equivalent and will fetch this from the available providers. This will succeed if the default provider has been loaded (or if a third party provider has been loaded that offers this cipher). Using the NULL cipher means that the plaintext is emitted as the ciphertext. Applications are only affected by this issue if they call EVP_CIPHER_meth_new() using NID_undef and subsequently use it in a call to an encryption/decryption initialisation function. Applications that only use SSL/TLS are not impacted by this issue. ([CVE-2022-3358]) *Matt Caswell* * Fix LLVM vs Apple LLVM version numbering confusion that caused build failures on MacOS 10.11 *Richard Levitte* * Fixed the linux-mips64 Configure target which was missing the SIXTY_FOUR_BIT bn_ops flag. This was causing heap corruption on that platform. *Adam Joseph* * Fix handling of a ticket key callback that returns 0 in TLSv1.3 to not send a ticket *Matt Caswell* * Correctly handle a retransmitted ClientHello in DTLS *Matt Caswell* * Fixed detection of ktls support in cross-compile environment on Linux *Tomas Mraz* * Fixed some regressions and test failures when running the 3.0.0 FIPS provider against 3.0.x *Paul Dale* * Fixed SSL_pending() and SSL_has_pending() with DTLS which were failing to report correct results in some cases *Matt Caswell* * Fix UWP builds by defining VirtualLock *Charles Milette* * For known safe primes use the minimum key length according to RFC 7919. Longer private key sizes unnecessarily raise the cycles needed to compute the shared secret without any increase of the real security. This fixes a regression from 1.1.1 where these shorter keys were generated for the known safe primes. *Tomas Mraz* * Added the loongarch64 target *Shi Pujin* * Fixed EC ASM flag passing. Flags for ASM implementations of EC curves were only passed to the FIPS provider and not to the default or legacy provider. *Juergen Christ* * Fixed reported performance degradation on aarch64. Restored the implementation prior to commit 2621751 ("aes/asm/aesv8-armx.pl: avoid 32-bit lane assignment in CTR mode") for 64bit targets only, since it is reportedly 2-17% slower and the silicon errata only affects 32bit targets. The new algorithm is still used for 32 bit targets. *Bernd Edlinger* * Added a missing header for memcmp that caused compilation failure on some platforms *Gregor Jasny* ### Changes between 3.0.4 and 3.0.5 [5 Jul 2022] * The OpenSSL 3.0.4 release introduced a serious bug in the RSA implementation for X86_64 CPUs supporting the AVX512IFMA instructions. This issue makes the RSA implementation with 2048 bit private keys incorrect on such machines and memory corruption will happen during the computation. As a consequence of the memory corruption an attacker may be able to trigger a remote code execution on the machine performing the computation. SSL/TLS servers or other servers using 2048 bit RSA private keys running on machines supporting AVX512IFMA instructions of the X86_64 architecture are affected by this issue. ([CVE-2022-2274]) *Xi Ruoyao* * AES OCB mode for 32-bit x86 platforms using the AES-NI assembly optimised implementation would not encrypt the entirety of the data under some circumstances. This could reveal sixteen bytes of data that was preexisting in the memory that wasn't written. In the special case of "in place" encryption, sixteen bytes of the plaintext would be revealed. Since OpenSSL does not support OCB based cipher suites for TLS and DTLS, they are both unaffected. ([CVE-2022-2097]) *Alex Chernyakhovsky, David Benjamin, Alejandro Sedeño* ### Changes between 3.0.3 and 3.0.4 [21 Jun 2022] * In addition to the c_rehash shell command injection identified in CVE-2022-1292, further bugs where the c_rehash script does not properly sanitise shell metacharacters to prevent command injection have been fixed. When the CVE-2022-1292 was fixed it was not discovered that there are other places in the script where the file names of certificates being hashed were possibly passed to a command executed through the shell. This script is distributed by some operating systems in a manner where it is automatically executed. On such operating systems, an attacker could execute arbitrary commands with the privileges of the script. Use of the c_rehash script is considered obsolete and should be replaced by the OpenSSL rehash command line tool. (CVE-2022-2068) *Daniel Fiala, Tomáš Mráz* * Case insensitive string comparison no longer uses locales. It has instead been directly implemented. *Paul Dale* ### Changes between 3.0.2 and 3.0.3 [3 May 2022] * Case insensitive string comparison is reimplemented via new locale-agnostic comparison functions OPENSSL_str[n]casecmp always using the POSIX locale for comparison. The previous implementation had problems when the Turkish locale was used. *Dmitry Belyavskiy* * Fixed a bug in the c_rehash script which was not properly sanitising shell metacharacters to prevent command injection. This script is distributed by some operating systems in a manner where it is automatically executed. On such operating systems, an attacker could execute arbitrary commands with the privileges of the script. Use of the c_rehash script is considered obsolete and should be replaced by the OpenSSL rehash command line tool. (CVE-2022-1292) *Tomáš Mráz* * Fixed a bug in the function `OCSP_basic_verify` that verifies the signer certificate on an OCSP response. The bug caused the function in the case where the (non-default) flag OCSP_NOCHECKS is used to return a postivie response (meaning a successful verification) even in the case where the response signing certificate fails to verify. It is anticipated that most users of `OCSP_basic_verify` will not use the OCSP_NOCHECKS flag. In this case the `OCSP_basic_verify` function will return a negative value (indicating a fatal error) in the case of a certificate verification failure. The normal expected return value in this case would be 0. This issue also impacts the command line OpenSSL "ocsp" application. When verifying an ocsp response with the "-no_cert_checks" option the command line application will report that the verification is successful even though it has in fact failed. In this case the incorrect successful response will also be accompanied by error messages showing the failure and contradicting the apparently successful result. ([CVE-2022-1343]) *Matt Caswell* * Fixed a bug where the RC4-MD5 ciphersuite incorrectly used the AAD data as the MAC key. This made the MAC key trivially predictable. An attacker could exploit this issue by performing a man-in-the-middle attack to modify data being sent from one endpoint to an OpenSSL 3.0 recipient such that the modified data would still pass the MAC integrity check. Note that data sent from an OpenSSL 3.0 endpoint to a non-OpenSSL 3.0 endpoint will always be rejected by the recipient and the connection will fail at that point. Many application protocols require data to be sent from the client to the server first. Therefore, in such a case, only an OpenSSL 3.0 server would be impacted when talking to a non-OpenSSL 3.0 client. If both endpoints are OpenSSL 3.0 then the attacker could modify data being sent in both directions. In this case both clients and servers could be affected, regardless of the application protocol. Note that in the absence of an attacker this bug means that an OpenSSL 3.0 endpoint communicating with a non-OpenSSL 3.0 endpoint will fail to complete the handshake when using this ciphersuite. The confidentiality of data is not impacted by this issue, i.e. an attacker cannot decrypt data that has been encrypted using this ciphersuite - they can only modify it. In order for this attack to work both endpoints must legitimately negotiate the RC4-MD5 ciphersuite. This ciphersuite is not compiled by default in OpenSSL 3.0, and is not available within the default provider or the default ciphersuite list. This ciphersuite will never be used if TLSv1.3 has been negotiated. In order for an OpenSSL 3.0 endpoint to use this ciphersuite the following must have occurred: 1) OpenSSL must have been compiled with the (non-default) compile time option enable-weak-ssl-ciphers 2) OpenSSL must have had the legacy provider explicitly loaded (either through application code or via configuration) 3) The ciphersuite must have been explicitly added to the ciphersuite list 4) The libssl security level must have been set to 0 (default is 1) 5) A version of SSL/TLS below TLSv1.3 must have been negotiated 6) Both endpoints must negotiate the RC4-MD5 ciphersuite in preference to any others that both endpoints have in common (CVE-2022-1434) *Matt Caswell* * Fix a bug in the OPENSSL_LH_flush() function that breaks reuse of the memory occuppied by the removed hash table entries. This function is used when decoding certificates or keys. If a long lived process periodically decodes certificates or keys its memory usage will expand without bounds and the process might be terminated by the operating system causing a denial of service. Also traversing the empty hash table entries will take increasingly more time. Typically such long lived processes might be TLS clients or TLS servers configured to accept client certificate authentication. (CVE-2022-1473) *Hugo Landau, Aliaksei Levin* * The functions `OPENSSL_LH_stats` and `OPENSSL_LH_stats_bio` now only report the `num_items`, `num_nodes` and `num_alloc_nodes` statistics. All other statistics are no longer supported. For compatibility, these statistics are still listed in the output but are now always reported as zero. *Hugo Landau* ### Changes between 3.0.1 and 3.0.2 [15 Mar 2022] * Fixed a bug in the BN_mod_sqrt() function that can cause it to loop forever for non-prime moduli. Internally this function is used when parsing certificates that contain elliptic curve public keys in compressed form or explicit elliptic curve parameters with a base point encoded in compressed form. It is possible to trigger the infinite loop by crafting a certificate that has invalid explicit curve parameters. Since certificate parsing happens prior to verification of the certificate signature, any process that parses an externally supplied certificate may thus be subject to a denial of service attack. The infinite loop can also be reached when parsing crafted private keys as they can contain explicit elliptic curve parameters. Thus vulnerable situations include: - TLS clients consuming server certificates - TLS servers consuming client certificates - Hosting providers taking certificates or private keys from customers - Certificate authorities parsing certification requests from subscribers - Anything else which parses ASN.1 elliptic curve parameters Also any other applications that use the BN_mod_sqrt() where the attacker can control the parameter values are vulnerable to this DoS issue. ([CVE-2022-0778]) *Tomáš Mráz* * Add ciphersuites based on DHE_PSK (RFC 4279) and ECDHE_PSK (RFC 5489) to the list of ciphersuites providing Perfect Forward Secrecy as required by SECLEVEL >= 3. *Dmitry Belyavskiy, Nicola Tuveri* * Made the AES constant time code for no-asm configurations optional due to the resulting 95% performance degradation. The AES constant time code can be enabled, for no assembly builds, with: ./config no-asm -DOPENSSL_AES_CONST_TIME *Paul Dale* * Fixed PEM_write_bio_PKCS8PrivateKey() to make it possible to use empty passphrase strings. *Darshan Sen* * The negative return value handling of the certificate verification callback was reverted. The replacement is to set the verification retry state with the SSL_set_retry_verify() function. *Tomáš Mráz* ### Changes between 3.0.0 and 3.0.1 [14 Dec 2021] * Fixed invalid handling of X509_verify_cert() internal errors in libssl Internally libssl in OpenSSL calls X509_verify_cert() on the client side to verify a certificate supplied by a server. That function may return a negative return value to indicate an internal error (for example out of memory). Such a negative return value is mishandled by OpenSSL and will cause an IO function (such as SSL_connect() or SSL_do_handshake()) to not indicate success and a subsequent call to SSL_get_error() to return the value SSL_ERROR_WANT_RETRY_VERIFY. This return value is only supposed to be returned by OpenSSL if the application has previously called SSL_CTX_set_cert_verify_callback(). Since most applications do not do this the SSL_ERROR_WANT_RETRY_VERIFY return value from SSL_get_error() will be totally unexpected and applications may not behave correctly as a result. The exact behaviour will depend on the application but it could result in crashes, infinite loops or other similar incorrect responses. This issue is made more serious in combination with a separate bug in OpenSSL 3.0 that will cause X509_verify_cert() to indicate an internal error when processing a certificate chain. This will occur where a certificate does not include the Subject Alternative Name extension but where a Certificate Authority has enforced name constraints. This issue can occur even with valid chains. ([CVE-2021-4044]) *Matt Caswell* * Corrected a few file name and file reference bugs in the build, installation and setup scripts, which lead to installation verification failures. Slightly enhanced the installation verification script. *Richard Levitte* * Fixed EVP_PKEY_eq() to make it possible to use it with strictly private keys. *Richard Levitte* * Fixed PVK encoder to properly query for the passphrase. *Tomáš Mráz* * Multiple fixes in the OSSL_HTTP API functions. *David von Oheimb* * Allow sign extension in OSSL_PARAM_allocate_from_text() for the OSSL_PARAM_INTEGER data type and return error on negative numbers used with the OSSL_PARAM_UNSIGNED_INTEGER data type. Make OSSL_PARAM_BLD_push_BN{,_pad}() return an error on negative numbers. *Richard Levitte* * Allow copying uninitialized digest contexts with EVP_MD_CTX_copy_ex. *Tomáš Mráz* * Fixed detection of ARMv7 and ARM64 CPU features on FreeBSD. *Allan Jude* * Multiple threading fixes. *Matt Caswell* * Added NULL digest implementation to keep compatibility with 1.1.1 version. *Tomáš Mráz* * Allow fetching an operation from the provider that owns an unexportable key as a fallback if that is still allowed by the property query. *Richard Levitte* ### Changes between 1.1.1 and 3.0.0 [7 sep 2021] * TLS_MAX_VERSION, DTLS_MAX_VERSION and DTLS_MIN_VERSION constants are now deprecated. *Matt Caswell* * The `OPENSSL_s390xcap` environment variable can be used to set bits in the S390X capability vector to zero. This simplifies testing of different code paths on S390X architecture. *Patrick Steuer* * Encrypting more than 2^64 TLS records with AES-GCM is disallowed as per FIPS 140-2 IG A.5 "Key/IV Pair Uniqueness Requirements from SP 800-38D". The communication will fail at this point. *Paul Dale* * The EC_GROUP_clear_free() function is deprecated as there is nothing confidential in EC_GROUP data. *Nicola Tuveri* * The byte order mark (BOM) character is ignored if encountered at the beginning of a PEM-formatted file. *Dmitry Belyavskiy* * Added CMS support for the Russian GOST algorithms. *Dmitry Belyavskiy* * Due to move of the implementation of cryptographic operations to the providers, validation of various operation parameters can be postponed until the actual operation is executed where previously it happened immediately when an operation parameter was set. For example when setting an unsupported curve with EVP_PKEY_CTX_set_ec_paramgen_curve_nid() this function call will not fail but later keygen operations with the EVP_PKEY_CTX will fail. *OpenSSL team members and many third party contributors* * The EVP_get_cipherbyname() function will return NULL for algorithms such as "AES-128-SIV", "AES-128-CBC-CTS" and "CAMELLIA-128-CBC-CTS" which were previously only accessible via low level interfaces. Use EVP_CIPHER_fetch() instead to retrieve these algorithms from a provider. *Shane Lontis* * On build targets where the multilib postfix is set in the build configuration the libdir directory was changing based on whether the lib directory with the multilib postfix exists on the system or not. This unpredictable behavior was removed and eventual multilib postfix is now always added to the default libdir. Use `--libdir=lib` to override the libdir if adding the postfix is undesirable. *Jan Lána* * The triple DES key wrap functionality now conforms to RFC 3217 but is no longer interoperable with OpenSSL 1.1.1. *Paul Dale* * The ERR_GET_FUNC() function was removed. With the loss of meaningful function codes, this function can only cause problems for calling applications. *Paul Dale* * Add a configurable flag to output date formats as ISO 8601. Does not change the default date format. *William Edmisten* * Version of MSVC earlier than 1300 could get link warnings, which could be suppressed if the undocumented -DI_CAN_LIVE_WITH_LNK4049 was set. Support for this flag has been removed. *Rich Salz* * Rework and make DEBUG macros consistent. Remove unused -DCONF_DEBUG, -DBN_CTX_DEBUG, and REF_PRINT. Add a new tracing category and use it for printing reference counts. Rename -DDEBUG_UNUSED to -DUNUSED_RESULT_DEBUG Fix BN_DEBUG_RAND so it compiles and, when set, force DEBUG_RAND to be set also. Rename engine_debug_ref to be ENGINE_REF_PRINT also for consistency. *Rich Salz* * The signatures of the functions to get and set options on SSL and SSL_CTX objects changed from "unsigned long" to "uint64_t" type. Some source code changes may be required. *Rich Salz* * The public definitions of conf_method_st and conf_st have been deprecated. They will be made opaque in a future release. *Rich Salz and Tomáš Mráz* * Client-initiated renegotiation is disabled by default. To allow it, use the -client_renegotiation option, the SSL_OP_ALLOW_CLIENT_RENEGOTIATION flag, or the "ClientRenegotiation" config parameter as appropriate. *Rich Salz* * Add "abspath" and "includedir" pragma's to config files, to prevent, or modify relative pathname inclusion. *Rich Salz* * OpenSSL includes a cryptographic module that is intended to be FIPS 140-2 validated. Please consult the README-FIPS and README-PROVIDERS files, as well as the migration guide. *OpenSSL team members and many third party contributors* * For the key types DH and DHX the allowed settable parameters are now different. *Shane Lontis* * The openssl commands that read keys, certificates, and CRLs now automatically detect the PEM or DER format of the input files. *David von Oheimb, Richard Levitte, and Tomáš Mráz* * Added enhanced PKCS#12 APIs which accept a library context. *Jon Spillett* * The default manual page suffix ($MANSUFFIX) has been changed to "ossl" *Matt Caswell* * Added support for Kernel TLS (KTLS). *Boris Pismenny, John Baldwin and Andrew Gallatin* * Support for RFC 5746 secure renegotiation is now required by default for SSL or TLS connections to succeed. *Benjamin Kaduk* * The signature of the `copy` functional parameter of the EVP_PKEY_meth_set_copy() function has changed so its `src` argument is now `const EVP_PKEY_CTX *` instead of `EVP_PKEY_CTX *`. Similarly the signature of the `pub_decode` functional parameter of the EVP_PKEY_asn1_set_public() function has changed so its `pub` argument is now `const X509_PUBKEY *` instead of `X509_PUBKEY *`. *David von Oheimb* * The error return values from some control calls (ctrl) have changed. *Paul Dale* * A public key check is now performed during EVP_PKEY_derive_set_peer(). *Shane Lontis* * Many functions in the EVP_ namespace that are getters of values from implementations or contexts were renamed to include get or get0 in their names. Old names are provided as macro aliases for compatibility and are not deprecated. *Tomáš Mráz* * The EVP_PKEY_CTRL_PKCS7_ENCRYPT, EVP_PKEY_CTRL_PKCS7_DECRYPT, EVP_PKEY_CTRL_PKCS7_SIGN, EVP_PKEY_CTRL_CMS_ENCRYPT, EVP_PKEY_CTRL_CMS_DECRYPT, and EVP_PKEY_CTRL_CMS_SIGN control operations are deprecated. *Tomáš Mráz* * The EVP_PKEY_public_check() and EVP_PKEY_param_check() functions now work for more key types. * The output from the command line applications may have minor changes. *Paul Dale* * The output from numerous "printing" may have minor changes. *David von Oheimb* * Windows thread synchronization uses read/write primitives (SRWLock) when supported by the OS, otherwise CriticalSection continues to be used. *Vincent Drake* * Add filter BIO BIO_f_readbuffer() that allows BIO_tell() and BIO_seek() to work on read only BIO source/sinks that do not support these functions. This allows piping or redirection of a file BIO using stdin to be buffered into memory. This is used internally in OSSL_DECODER_from_bio(). *Shane Lontis* * OSSL_STORE_INFO_get_type() may now return an additional value. In 1.1.1 this function would return one of the values OSSL_STORE_INFO_NAME, OSSL_STORE_INFO_PKEY, OSSL_STORE_INFO_PARAMS, OSSL_STORE_INFO_CERT or OSSL_STORE_INFO_CRL. Decoded public keys would previously have been reported as type OSSL_STORE_INFO_PKEY in 1.1.1. In 3.0 decoded public keys are now reported as having the new type OSSL_STORE_INFO_PUBKEY. Applications using this function should be amended to handle the changed return value. *Richard Levitte* * Improved adherence to Enhanced Security Services (ESS, RFC 2634 and RFC 5035) for the TSP and CMS Advanced Electronic Signatures (CAdES) implementations. As required by RFC 5035 check both ESSCertID and ESSCertIDv2 if both present. Correct the semantics of checking the validation chain in case ESSCertID{,v2} contains more than one certificate identifier: This means that all certificates referenced there MUST be part of the validation chain. *David von Oheimb* * The implementation of older EVP ciphers related to CAST, IDEA, SEED, RC2, RC4, RC5, DESX and DES have been moved to the legacy provider. *Matt Caswell* * The implementation of the EVP digests MD2, MD4, MDC2, WHIRLPOOL and RIPEMD-160 have been moved to the legacy provider. *Matt Caswell* * The deprecated function EVP_PKEY_get0() now returns NULL being called for a provided key. *Dmitry Belyavskiy* * The deprecated functions EVP_PKEY_get0_RSA(), EVP_PKEY_get0_DSA(), EVP_PKEY_get0_EC_KEY(), EVP_PKEY_get0_DH(), EVP_PKEY_get0_hmac(), EVP_PKEY_get0_poly1305() and EVP_PKEY_get0_siphash() as well as the similarly named "get1" functions behave differently in OpenSSL 3.0. *Matt Caswell* * A number of functions handling low-level keys or engines were deprecated including EVP_PKEY_set1_engine(), EVP_PKEY_get0_engine(), EVP_PKEY_assign(), EVP_PKEY_get0(), EVP_PKEY_get0_hmac(), EVP_PKEY_get0_poly1305() and EVP_PKEY_get0_siphash(). *Matt Caswell* * PKCS#5 PBKDF1 key derivation has been moved from PKCS5_PBE_keyivgen() into the legacy crypto provider as an EVP_KDF. Applications requiring this KDF will need to load the legacy crypto provider. This includes these PBE algorithms which use this KDF: - NID_pbeWithMD2AndDES_CBC - NID_pbeWithMD5AndDES_CBC - NID_pbeWithSHA1AndRC2_CBC - NID_pbeWithMD2AndRC2_CBC - NID_pbeWithMD5AndRC2_CBC - NID_pbeWithSHA1AndDES_CBC *Jon Spillett* * Deprecated obsolete BIO_set_callback(), BIO_get_callback(), and BIO_debug_callback() functions. *Tomáš Mráz* * Deprecated obsolete EVP_PKEY_CTX_get0_dh_kdf_ukm() and EVP_PKEY_CTX_get0_ecdh_kdf_ukm() functions. *Tomáš Mráz* * The RAND_METHOD APIs have been deprecated. *Paul Dale* * The SRP APIs have been deprecated. *Matt Caswell* * Add a compile time option to prevent the caching of provider fetched algorithms. This is enabled by including the no-cached-fetch option at configuration time. *Paul Dale* * pkcs12 now uses defaults of PBKDF2, AES and SHA-256, with a MAC iteration count of PKCS12_DEFAULT_ITER. *Tomáš Mráz and Sahana Prasad* * The openssl speed command does not use low-level API calls anymore. *Tomáš Mráz* * Parallel dual-prime 1024-bit modular exponentiation for AVX512_IFMA capable processors. *Ilya Albrekht, Sergey Kirillov, Andrey Matyukov (Intel Corp)* * Combining the Configure options no-ec and no-dh no longer disables TLSv1.3. *Matt Caswell* * Implemented support for fully "pluggable" TLSv1.3 groups. This means that providers may supply their own group implementations (using either the "key exchange" or the "key encapsulation" methods) which will automatically be detected and used by libssl. *Matt Caswell, Nicola Tuveri* * The undocumented function X509_certificate_type() has been deprecated; *Rich Salz* * Deprecated the obsolete BN_pseudo_rand() and BN_pseudo_rand_range(). *Tomáš Mráz* * Removed RSA padding mode for SSLv23 (which was only used for SSLv2). This includes the functions RSA_padding_check_SSLv23() and RSA_padding_add_SSLv23() and the `-ssl` option in the deprecated `rsautl` command. *Rich Salz* * Deprecated the obsolete X9.31 RSA key generation related functions. * While a callback function set via `SSL_CTX_set_cert_verify_callback()` is not allowed to return a value > 1, this is no more taken as failure. *Viktor Dukhovni and David von Oheimb* * Deprecated the obsolete X9.31 RSA key generation related functions BN_X931_generate_Xpq(), BN_X931_derive_prime_ex(), and BN_X931_generate_prime_ex(). *Tomáš Mráz* * The default key generation method for the regular 2-prime RSA keys was changed to the FIPS 186-4 B.3.6 method. *Shane Lontis* * Deprecated the BN_is_prime_ex() and BN_is_prime_fasttest_ex() functions. *Kurt Roeckx* * Deprecated EVP_MD_CTX_set_update_fn() and EVP_MD_CTX_update_fn(). *Rich Salz* * Deprecated the type OCSP_REQ_CTX and the functions OCSP_REQ_CTX_*() and replaced with OSSL_HTTP_REQ_CTX and the functions OSSL_HTTP_REQ_CTX_*(). *Rich Salz, Richard Levitte, and David von Oheimb* * Deprecated `X509_http_nbio()` and `X509_CRL_http_nbio()`. *David von Oheimb* * Deprecated `OCSP_parse_url()`. *David von Oheimb* * Validation of SM2 keys has been separated from the validation of regular EC keys. *Nicola Tuveri* * Behavior of the `pkey` app is changed, when using the `-check` or `-pubcheck` switches: a validation failure triggers an early exit, returning a failure exit status to the parent process. *Nicola Tuveri* * Changed behavior of SSL_CTX_set_ciphersuites() and SSL_set_ciphersuites() to ignore unknown ciphers. *Otto Hollmann* * The `-cipher-commands` and `-digest-commands` options of the command line utility `list` have been deprecated. Instead use the `-cipher-algorithms` and `-digest-algorithms` options. *Dmitry Belyavskiy* * Added convenience functions for generating asymmetric key pairs: The 'quick' one-shot (yet somewhat limited) function L and macros for the most common cases: and L. *David von Oheimb* * All of the low level EC_KEY functions have been deprecated. *Shane Lontis, Paul Dale, Richard Levitte, and Tomáš Mráz* * Deprecated all the libcrypto and libssl error string loading functions. *Richard Levitte* * The functions SSL_CTX_set_tmp_dh_callback and SSL_set_tmp_dh_callback, as well as the macros SSL_CTX_set_tmp_dh() and SSL_set_tmp_dh() have been deprecated. *Matt Caswell* * The `-crypt` option to the `passwd` command line tool has been removed. *Paul Dale* * The -C option to the `x509`, `dhparam`, `dsaparam`, and `ecparam` commands were removed. *Rich Salz* * Add support for AES Key Wrap inverse ciphers to the EVP layer. *Shane Lontis* * Deprecated EVP_PKEY_set1_tls_encodedpoint() and EVP_PKEY_get1_tls_encodedpoint(). *Matt Caswell* * The security callback, which can be customised by application code, supports the security operation SSL_SECOP_TMP_DH. One location of the "other" parameter was incorrectly passing a DH object. It now passed an EVP_PKEY in all cases. *Matt Caswell* * Add PKCS7_get_octet_string() and PKCS7_type_is_other() to the public interface. Their functionality remains unchanged. *Jordan Montgomery* * Added new option for 'openssl list', '-providers', which will display the list of loaded providers, their names, version and status. It optionally displays their gettable parameters. *Paul Dale* * Removed EVP_PKEY_set_alias_type(). *Richard Levitte* * Deprecated `EVP_PKEY_CTX_set_rsa_keygen_pubexp()` and introduced `EVP_PKEY_CTX_set1_rsa_keygen_pubexp()`, which is now preferred. *Jeremy Walch* * Changed all "STACK" functions to be macros instead of inline functions. Macro parameters are still checked for type safety at compile time via helper inline functions. *Matt Caswell* * Remove the RAND_DRBG API *Paul Dale and Matthias St. Pierre* * Allow `SSL_set1_host()` and `SSL_add1_host()` to take IP literal addresses as well as actual hostnames. *David Woodhouse* * The 'MinProtocol' and 'MaxProtocol' configuration commands now silently ignore TLS protocol version bounds when configuring DTLS-based contexts, and conversely, silently ignore DTLS protocol version bounds when configuring TLS-based contexts. The commands can be repeated to set bounds of both types. The same applies with the corresponding "min_protocol" and "max_protocol" command-line switches, in case some application uses both TLS and DTLS. SSL_CTX instances that are created for a fixed protocol version (e.g. `TLSv1_server_method()`) also silently ignore version bounds. Previously attempts to apply bounds to these protocol versions would result in an error. Now only the "version-flexible" SSL_CTX instances are subject to limits in configuration files in command-line options. *Viktor Dukhovni* * Deprecated the `ENGINE` API. Engines should be replaced with providers going forward. *Paul Dale* * Reworked the recorded ERR codes to make better space for system errors. To distinguish them, the macro `ERR_SYSTEM_ERROR()` indicates if the given code is a system error (true) or an OpenSSL error (false). *Richard Levitte* * Reworked the test perl framework to better allow parallel testing. *Nicola Tuveri and David von Oheimb* * Added ciphertext stealing algorithms AES-128-CBC-CTS, AES-192-CBC-CTS and AES-256-CBC-CTS to the providers. CS1, CS2 and CS3 variants are supported. *Shane Lontis* * 'Configure' has been changed to figure out the configuration target if none is given on the command line. Consequently, the 'config' script is now only a mere wrapper. All documentation is changed to only mention 'Configure'. *Rich Salz and Richard Levitte* * Added a library context `OSSL_LIB_CTX` that applications as well as other libraries can use to form a separate context within which libcrypto operations are performed. *Richard Levitte* * Added various `_ex` functions to the OpenSSL API that support using a non-default `OSSL_LIB_CTX`. *OpenSSL team* * Handshake now fails if Extended Master Secret extension is dropped on renegotiation. *Tomáš Mráz* * Dropped interactive mode from the `openssl` program. *Richard Levitte* * Deprecated `EVP_PKEY_cmp()` and `EVP_PKEY_cmp_parameters()`. *David von Oheimb and Shane Lontis* * Deprecated `EC_METHOD_get_field_type()`. *Billy Bob Brumley* * Deprecated EC_GFp_simple_method(), EC_GFp_mont_method(), EC_GF2m_simple_method(), EC_GFp_nist_method(), EC_GFp_nistp224_method() EC_GFp_nistp256_method(), and EC_GFp_nistp521_method(). *Billy Bob Brumley* * Deprecated EC_GROUP_new(), EC_GROUP_method_of(), and EC_POINT_method_of(). *Billy Bob Brumley* * Add CAdES-BES signature verification support, mostly derived from ESSCertIDv2 TS (RFC 5816) contribution by Marek Klein. *Filipe Raimundo da Silva* * Add CAdES-BES signature scheme and attributes support (RFC 5126) to CMS API. *Antonio Iacono* * Added the AuthEnvelopedData content type structure (RFC 5083) with AES-GCM parameter (RFC 5084) for the Cryptographic Message Syntax (CMS). *Jakub Zelenka* * Deprecated EC_POINT_make_affine() and EC_POINTs_make_affine(). *Billy Bob Brumley* * Deprecated EC_GROUP_precompute_mult(), EC_GROUP_have_precompute_mult(), and EC_KEY_precompute_mult(). *Billy Bob Brumley* * Deprecated EC_POINTs_mul(). *Billy Bob Brumley* * Removed FIPS_mode() and FIPS_mode_set(). *Shane Lontis* * The SSL option SSL_OP_IGNORE_UNEXPECTED_EOF is introduced. *Dmitry Belyavskiy* * Deprecated EC_POINT_set_Jprojective_coordinates_GFp() and EC_POINT_get_Jprojective_coordinates_GFp(). *Billy Bob Brumley* * Added OSSL_PARAM_BLD to the public interface. This allows OSSL_PARAM arrays to be more easily constructed via a series of utility functions. Create a parameter builder using OSSL_PARAM_BLD_new(), add parameters using the various push functions and finally convert to a passable OSSL_PARAM array using OSSL_PARAM_BLD_to_param(). *Paul Dale* * The security strength of SHA1 and MD5 based signatures in TLS has been reduced. *Kurt Roeckx* * Added EVP_PKEY_set_type_by_keymgmt(), to initialise an EVP_PKEY to contain a provider side internal key. *Richard Levitte* * ASN1_verify(), ASN1_digest() and ASN1_sign() have been deprecated. *Richard Levitte* * Project text documents not yet having a proper file name extension (`HACKING`, `LICENSE`, `NOTES*`, `README*`, `VERSION`) have been renamed to `*.md` as far as reasonable, else `*.txt`, for better use with file managers. *David von Oheimb* * The main project documents (README, NEWS, CHANGES, INSTALL, SUPPORT) have been converted to Markdown with the goal to produce documents which not only look pretty when viewed online in the browser, but remain well readable inside a plain text editor. To achieve this goal, a 'minimalistic' Markdown style has been applied which avoids formatting elements that interfere too much with the reading flow in the text file. For example, it * avoids [ATX headings][] and uses [setext headings][] instead (which works for `

` and `

` headings only). * avoids [inline links][] and uses [reference links][] instead. * avoids [fenced code blocks][] and uses [indented code blocks][] instead. [ATX headings]: https://github.github.com/gfm/#atx-headings [setext headings]: https://github.github.com/gfm/#setext-headings [inline links]: https://github.github.com/gfm/#inline-link [reference links]: https://github.github.com/gfm/#reference-link [fenced code blocks]: https://github.github.com/gfm/#fenced-code-blocks [indented code blocks]: https://github.github.com/gfm/#indented-code-blocks *Matthias St. Pierre* * The test suite is changed to preserve results of each test recipe. A new directory test-runs/ with subdirectories named like the test recipes are created in the build tree for this purpose. *Richard Levitte* * Added an implementation of CMP and CRMF (RFC 4210, RFC 4211 RFC 6712). This adds `crypto/cmp/`, `crpyto/crmf/`, `apps/cmp.c`, and `test/cmp_*`. See L and L as starting points. *David von Oheimb, Martin Peylo* * Generalized the HTTP client code from `crypto/ocsp/` into `crpyto/http/`. It supports arbitrary request and response content types, GET redirection, TLS, connections via HTTP(S) proxies, connections and exchange via user-defined BIOs (allowing implicit connections), persistent connections, and timeout checks. See L etc. for details. The legacy OCSP-focused (and only partly documented) API is retained for backward compatibility, while most of it is deprecated. *David von Oheimb* * Added `util/check-format.pl`, a tool for checking adherence to the OpenSSL coding style . The checks performed are incomplete and yield some false positives. Still the tool should be useful for detecting most typical glitches. *David von Oheimb* * `BIO_do_connect()` and `BIO_do_handshake()` have been extended: If domain name resolution yields multiple IP addresses all of them are tried after `connect()` failures. *David von Oheimb* * All of the low level RSA functions have been deprecated. *Paul Dale* * X509 certificates signed using SHA1 are no longer allowed at security level 1 and above. *Kurt Roeckx* * The command line utilities dhparam, dsa, gendsa and dsaparam have been modified to use PKEY APIs. These commands are now in maintenance mode and no new features will be added to them. *Paul Dale* * The command line utility rsautl has been deprecated. *Paul Dale* * The command line utilities genrsa and rsa have been modified to use PKEY APIs. They now write PKCS#8 keys by default. These commands are now in maintenance mode and no new features will be added to them. *Paul Dale* * All of the low level DH functions have been deprecated. *Paul Dale and Matt Caswell* * All of the low level DSA functions have been deprecated. *Paul Dale* * Reworked the treatment of EC EVP_PKEYs with the SM2 curve to automatically become EVP_PKEY_SM2 rather than EVP_PKEY_EC. *Richard Levitte* * Deprecated low level ECDH and ECDSA functions. *Paul Dale* * Deprecated EVP_PKEY_decrypt_old() and EVP_PKEY_encrypt_old(). *Richard Levitte* * Enhanced the documentation of EVP_PKEY_get_size(), EVP_PKEY_get_bits() and EVP_PKEY_get_security_bits(). Especially EVP_PKEY_get_size() needed a new formulation to include all the things it can be used for, as well as words of caution. *Richard Levitte* * The SSL_CTX_set_tlsext_ticket_key_cb(3) function has been deprecated. *Paul Dale* * All of the low level HMAC functions have been deprecated. *Paul Dale and David von Oheimb* * Over two thousand fixes were made to the documentation, including: - Common options (such as -rand/-writerand, TLS version control, etc) were refactored and point to newly-enhanced descriptions in openssl.pod. - Added style conformance for all options (with help from Richard Levitte), documented all reported missing options, added a CI build to check that all options are documented and that no unimplemented options are documented. - Documented some internals, such as all use of environment variables. - Addressed all internal broken L<> references. *Rich Salz* * All of the low level CMAC functions have been deprecated. *Paul Dale* * The low-level MD2, MD4, MD5, MDC2, RIPEMD160 and Whirlpool digest functions have been deprecated. *Paul Dale and David von Oheimb* * Corrected the documentation of the return values from the `EVP_DigestSign*` set of functions. The documentation mentioned negative values for some errors, but this was never the case, so the mention of negative values was removed. Code that followed the documentation and thereby check with something like `EVP_DigestSignInit(...) <= 0` will continue to work undisturbed. *Richard Levitte* * All of the low level cipher functions have been deprecated. *Matt Caswell and Paul Dale* * Removed include/openssl/opensslconf.h.in and replaced it with include/openssl/configuration.h.in, which differs in not including . A short header include/openssl/opensslconf.h was added to include both. This allows internal hacks where one might need to modify the set of configured macros, for example this if deprecated symbols are still supposed to be available internally: #include #undef OPENSSL_NO_DEPRECATED #define OPENSSL_SUPPRESS_DEPRECATED #include This should not be used by applications that use the exported symbols, as that will lead to linking errors. *Richard Levitte* * Fixed an overflow bug in the x64_64 Montgomery squaring procedure used in exponentiation with 512-bit moduli. No EC algorithms are affected. Analysis suggests that attacks against 2-prime RSA1024, 3-prime RSA1536, and DSA1024 as a result of this defect would be very difficult to perform and are not believed likely. Attacks against DH512 are considered just feasible. However, for an attack the target would have to re-use the DH512 private key, which is not recommended anyway. Also applications directly using the low-level API BN_mod_exp may be affected if they use BN_FLG_CONSTTIME. ([CVE-2019-1551]) *Andy Polyakov* * Most memory-debug features have been deprecated, and the functionality replaced with no-ops. *Rich Salz* * Added documentation for the STACK API. *Rich Salz* * Introduced a new method type and API, OSSL_ENCODER, to represent generic encoders. These do the same sort of job that PEM writers and d2i functions do, but with support for methods supplied by providers, and the possibility for providers to support other formats as well. *Richard Levitte* * Introduced a new method type and API, OSSL_DECODER, to represent generic decoders. These do the same sort of job that PEM readers and i2d functions do, but with support for methods supplied by providers, and the possibility for providers to support other formats as well. *Richard Levitte* * Added a .pragma directive to the syntax of configuration files, to allow varying behavior in a supported and predictable manner. Currently added pragma: .pragma dollarid:on This allows dollar signs to be a keyword character unless it's followed by a opening brace or parenthesis. This is useful for platforms where dollar signs are commonly used in names, such as volume names and system directory names on VMS. *Richard Levitte* * Added functionality to create an EVP_PKEY from user data. *Richard Levitte* * Change the interpretation of the '--api' configuration option to mean that this is a desired API compatibility level with no further meaning. The previous interpretation, that this would also mean to remove all deprecated symbols up to and including the given version, no requires that 'no-deprecated' is also used in the configuration. When building applications, the desired API compatibility level can be set with the OPENSSL_API_COMPAT macro like before. For API compatibility version below 3.0, the old style numerical value is valid as before, such as -DOPENSSL_API_COMPAT=0x10100000L. For version 3.0 and on, the value is expected to be the decimal value calculated from the major and minor version like this: MAJOR * 10000 + MINOR * 100 Examples: -DOPENSSL_API_COMPAT=30000 For 3.0 -DOPENSSL_API_COMPAT=30200 For 3.2 To hide declarations that are deprecated up to and including the given API compatibility level, -DOPENSSL_NO_DEPRECATED must be given when building the application as well. *Richard Levitte* * Added the X509_LOOKUP_METHOD called X509_LOOKUP_store, to allow access to certificate and CRL stores via URIs and OSSL_STORE loaders. This adds the following functions: - X509_LOOKUP_store() - X509_STORE_load_file() - X509_STORE_load_path() - X509_STORE_load_store() - SSL_add_store_cert_subjects_to_stack() - SSL_CTX_set_default_verify_store() - SSL_CTX_load_verify_file() - SSL_CTX_load_verify_dir() - SSL_CTX_load_verify_store() *Richard Levitte* * Added a new method to gather entropy on VMS, based on SYS$GET_ENTROPY. The presence of this system service is determined at run-time. *Richard Levitte* * Added functionality to create an EVP_PKEY context based on data for methods from providers. This takes an algorithm name and a property query string and simply stores them, with the intent that any operation that uses this context will use those strings to fetch the needed methods implicitly, thereby making the port of application written for pre-3.0 OpenSSL easier. *Richard Levitte* * The undocumented function NCONF_WIN32() has been deprecated; for conversion details see the HISTORY section of doc/man5/config.pod *Rich Salz* * Introduced the new functions EVP_DigestSignInit_ex() and EVP_DigestVerifyInit_ex(). The macros EVP_DigestSignUpdate() and EVP_DigestVerifyUpdate() have been converted to functions. See the man pages for further details. *Matt Caswell* * Over two thousand fixes were made to the documentation, including: adding missing command flags, better style conformance, documentation of internals, etc. *Rich Salz, Richard Levitte* * s390x assembly pack: add hardware-support for P-256, P-384, P-521, X25519, X448, Ed25519 and Ed448. *Patrick Steuer* * Print all values for a PKCS#12 attribute with 'openssl pkcs12', not just the first value. *Jon Spillett* * Deprecated the public definition of `ERR_STATE` as well as the function `ERR_get_state()`. This is done in preparation of making `ERR_STATE` an opaque type. *Richard Levitte* * Added ERR functionality to give callers access to the stored function names that have replaced the older function code based functions. New functions are ERR_peek_error_func(), ERR_peek_last_error_func(), ERR_peek_error_data(), ERR_peek_last_error_data(), ERR_get_error_all(), ERR_peek_error_all() and ERR_peek_last_error_all(). Deprecate ERR functions ERR_get_error_line(), ERR_get_error_line_data(), ERR_peek_error_line_data(), ERR_peek_last_error_line_data() and ERR_func_error_string(). *Richard Levitte* * Extended testing to be verbose for failing tests only. The make variables VERBOSE_FAILURE or VF can be used to enable this: $ make VF=1 test # Unix $ mms /macro=(VF=1) test ! OpenVMS $ nmake VF=1 test # Windows *Richard Levitte* * Added the `-copy_extensions` option to the `x509` command for use with `-req` and `-x509toreq`. When given with the `copy` or `copyall` argument, all extensions in the request are copied to the certificate or vice versa. *David von Oheimb*, *Kirill Stefanenkov * * Added the `-copy_extensions` option to the `req` command for use with `-x509`. When given with the `copy` or `copyall` argument, all extensions in the certification request are copied to the certificate. *David von Oheimb* * The `x509`, `req`, and `ca` commands now make sure that X.509v3 certificates they generate are by default RFC 5280 compliant in the following sense: There is a subjectKeyIdentifier extension with a hash value of the public key and for not self-signed certs there is an authorityKeyIdentifier extension with a keyIdentifier field or issuer information identifying the signing key. This is done unless some configuration overrides the new default behavior, such as `subjectKeyIdentifier = none` and `authorityKeyIdentifier = none`. *David von Oheimb* * Added several checks to `X509_verify_cert()` according to requirements in RFC 5280 in case `X509_V_FLAG_X509_STRICT` is set (which may be done by using the CLI option `-x509_strict`): * The basicConstraints of CA certificates must be marked critical. * CA certificates must explicitly include the keyUsage extension. * If a pathlenConstraint is given the key usage keyCertSign must be allowed. * The issuer name of any certificate must not be empty. * The subject name of CA certs, certs with keyUsage crlSign, and certs without subjectAlternativeName must not be empty. * If a subjectAlternativeName extension is given it must not be empty. * The signatureAlgorithm field and the cert signature must be consistent. * Any given authorityKeyIdentifier and any given subjectKeyIdentifier must not be marked critical. * The authorityKeyIdentifier must be given for X.509v3 certs unless they are self-signed. * The subjectKeyIdentifier must be given for all X.509v3 CA certs. *David von Oheimb* * Certificate verification using `X509_verify_cert()` meanwhile rejects EC keys with explicit curve parameters (specifiedCurve) as required by RFC 5480. *Tomáš Mráz* * For built-in EC curves, ensure an EC_GROUP built from the curve name is used even when parsing explicit parameters, when loading a encoded key or calling `EC_GROUP_new_from_ecpkparameters()`/ `EC_GROUP_new_from_ecparameters()`. This prevents bypass of security hardening and performance gains, especially for curves with specialized EC_METHODs. By default, if a key encoded with explicit parameters is loaded and later encoded, the output is still encoded with explicit parameters, even if internally a "named" EC_GROUP is used for computation. *Nicola Tuveri* * Compute ECC cofactors if not provided during EC_GROUP construction. Before this change, EC_GROUP_set_generator would accept order and/or cofactor as NULL. After this change, only the cofactor parameter can be NULL. It also does some minimal sanity checks on the passed order. ([CVE-2019-1547]) *Billy Bob Brumley* * Fixed a padding oracle in PKCS7_dataDecode and CMS_decrypt_set1_pkey. An attack is simple, if the first CMS_recipientInfo is valid but the second CMS_recipientInfo is chosen ciphertext. If the second recipientInfo decodes to PKCS #1 v1.5 form plaintext, the correct encryption key will be replaced by garbage, and the message cannot be decoded, but if the RSA decryption fails, the correct encryption key is used and the recipient will not notice the attack. As a work around for this potential attack the length of the decrypted key must be equal to the cipher default key length, in case the certifiate is not given and all recipientInfo are tried out. The old behaviour can be re-enabled in the CMS code by setting the CMS_DEBUG_DECRYPT flag. *Bernd Edlinger* * Early start up entropy quality from the DEVRANDOM seed source has been improved for older Linux systems. The RAND subsystem will wait for /dev/random to be producing output before seeding from /dev/urandom. The seeded state is stored for future library initialisations using a system global shared memory segment. The shared memory identifier can be configured by defining OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID to the desired value. The default identifier is 114. *Paul Dale* * Revised BN_generate_prime_ex to not avoid factors 2..17863 in p-1 when primes for RSA keys are computed. Since we previously always generated primes == 2 (mod 3) for RSA keys, the 2-prime and 3-prime RSA modules were easy to distinguish, since `N = p*q = 1 (mod 3)`, but `N = p*q*r = 2 (mod 3)`. Therefore fingerprinting 2-prime vs. 3-prime RSA keys was possible by computing N mod 3. This avoids possible fingerprinting of newly generated RSA modules. *Bernd Edlinger* * Correct the extended master secret constant on EBCDIC systems. Without this fix TLS connections between an EBCDIC system and a non-EBCDIC system that negotiate EMS will fail. Unfortunately this also means that TLS connections between EBCDIC systems with this fix, and EBCDIC systems without this fix will fail if they negotiate EMS. *Matt Caswell* * Changed the library initialisation so that the config file is now loaded by default. This was already the case for libssl. It now occurs for both libcrypto and libssl. Use the OPENSSL_INIT_NO_LOAD_CONFIG option to `OPENSSL_init_crypto()` to suppress automatic loading of a config file. *Matt Caswell* * Introduced new error raising macros, `ERR_raise()` and `ERR_raise_data()`, where the former acts as a replacement for `ERR_put_error()`, and the latter replaces the combination `ERR_put_error()` + `ERR_add_error_data()`. `ERR_raise_data()` adds more flexibility by taking a format string and an arbitrary number of arguments following it, to be processed with `BIO_snprintf()`. *Richard Levitte* * Introduced a new function, `OSSL_PROVIDER_available()`, which can be used to check if a named provider is loaded and available. When called, it will also activate all fallback providers if such are still present. *Richard Levitte* * Enforce a minimum DH modulus size of 512 bits. *Bernd Edlinger* * Changed DH parameters to generate the order q subgroup instead of 2q. Previously generated DH parameters are still accepted by DH_check but DH_generate_key works around that by clearing bit 0 of the private key for those. This avoids leaking bit 0 of the private key. *Bernd Edlinger* * Significantly reduce secure memory usage by the randomness pools. *Paul Dale* * `{CRYPTO,OPENSSL}_mem_debug_{push,pop}` are now no-ops and have been deprecated. *Rich Salz* * A new type, EVP_KEYEXCH, has been introduced to represent key exchange algorithms. An implementation of a key exchange algorithm can be obtained by using the function EVP_KEYEXCH_fetch(). An EVP_KEYEXCH algorithm can be used in a call to EVP_PKEY_derive_init_ex() which works in a similar way to the older EVP_PKEY_derive_init() function. See the man pages for the new functions for further details. *Matt Caswell* * The EVP_PKEY_CTX_set_dh_pad() macro has now been converted to a function. *Matt Caswell* * Removed the function names from error messages and deprecated the xxx_F_xxx define's. *Richard Levitte* * Removed NextStep support and the macro OPENSSL_UNISTD *Rich Salz* * Removed DES_check_key. Also removed OPENSSL_IMPLEMENT_GLOBAL, OPENSSL_GLOBAL_REF, OPENSSL_DECLARE_GLOBAL. Also removed "export var as function" capability; we do not export variables, only functions. *Rich Salz* * RC5_32_set_key has been changed to return an int type, with 0 indicating an error and 1 indicating success. In previous versions of OpenSSL this was a void type. If a key was set longer than the maximum possible this would crash. *Matt Caswell* * Support SM2 signing and verification schemes with X509 certificate. *Paul Yang* * Use SHA256 as the default digest for TS query in the `ts` app. *Tomáš Mráz* * Change PBKDF2 to conform to SP800-132 instead of the older PKCS5 RFC2898. *Shane Lontis* * Default cipher lists/suites are now available via a function, the #defines are deprecated. *Todd Short* * Add target VC-WIN32-UWP, VC-WIN64A-UWP, VC-WIN32-ARM-UWP and VC-WIN64-ARM-UWP in Windows OneCore target for making building libraries for Windows Store apps easier. Also, the "no-uplink" option has been added. *Kenji Mouri* * Join the directories crypto/x509 and crypto/x509v3 *Richard Levitte* * Added command 'openssl kdf' that uses the EVP_KDF API. *Shane Lontis* * Added command 'openssl mac' that uses the EVP_MAC API. *Shane Lontis* * Added OPENSSL_info() to get diverse built-in OpenSSL data, such as default directories. Also added the command 'openssl info' for scripting purposes. *Richard Levitte* * The functions AES_ige_encrypt() and AES_bi_ige_encrypt() have been deprecated. *Matt Caswell* * Add prediction resistance to the DRBG reseeding process. *Paul Dale* * Limit the number of blocks in a data unit for AES-XTS to 2^20 as mandated by IEEE Std 1619-2018. *Paul Dale* * Added newline escaping functionality to a filename when using openssl dgst. This output format is to replicate the output format found in the `*sum` checksum programs. This aims to preserve backward compatibility. *Matt Eaton, Richard Levitte, and Paul Dale* * Removed the heartbeat message in DTLS feature, as it has very little usage and doesn't seem to fulfill a valuable purpose. The configuration option is now deprecated. *Richard Levitte* * Changed the output of 'openssl {digestname} < file' to display the digest name in its output. *Richard Levitte* * Added a new generic trace API which provides support for enabling instrumentation through trace output. *Richard Levitte & Matthias St. Pierre* * Added build tests for C++. These are generated files that only do one thing, to include one public OpenSSL head file each. This tests that the public header files can be usefully included in a C++ application. This test isn't enabled by default. It can be enabled with the option 'enable-buildtest-c++'. *Richard Levitte* * Added KB KDF (EVP_KDF_KB) to EVP_KDF. *Robbie Harwood* * Added SSH KDF (EVP_KDF_SSHKDF) and KRB5 KDF (EVP_KDF_KRB5KDF) to EVP_KDF. *Simo Sorce* * Added Single Step KDF (EVP_KDF_SS), X963 KDF, and X942 KDF to EVP_KDF. *Shane Lontis* * Added KMAC to EVP_MAC. *Shane Lontis* * Added property based algorithm implementation selection framework to the core. *Paul Dale* * Added SCA hardening for modular field inversion in EC_GROUP through a new dedicated field_inv() pointer in EC_METHOD. This also addresses a leakage affecting conversions from projective to affine coordinates. *Billy Bob Brumley, Nicola Tuveri* * Added EVP_KDF, an EVP layer KDF API, to simplify adding KDF and PRF implementations. This includes an EVP_PKEY to EVP_KDF bridge for those algorithms that were already supported through the EVP_PKEY API (scrypt, TLS1 PRF and HKDF). The low-level KDF functions for PBKDF2 and scrypt are now wrappers that call EVP_KDF. *David Makepeace* * Build devcrypto engine as a dynamic engine. *Eneas U de Queiroz* * Add keyed BLAKE2 to EVP_MAC. *Antoine Salon* * Fix a bug in the computation of the endpoint-pair shared secret used by DTLS over SCTP. This breaks interoperability with older versions of OpenSSL like OpenSSL 1.1.0 and OpenSSL 1.0.2. There is a runtime switch SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG (off by default) enabling interoperability with such broken implementations. However, enabling this switch breaks interoperability with correct implementations. * Fix a use after free bug in d2i_X509_PUBKEY when overwriting a re-used X509_PUBKEY object if the second PUBKEY is malformed. *Bernd Edlinger* * Move strictness check from EVP_PKEY_asn1_new() to EVP_PKEY_asn1_add0(). *Richard Levitte* * Changed the license to the Apache License v2.0. *Richard Levitte* * Switch to a new version scheme using three numbers MAJOR.MINOR.PATCH. - Major releases (indicated by incrementing the MAJOR release number) may introduce incompatible API/ABI changes. - Minor releases (indicated by incrementing the MINOR release number) may introduce new features but retain API/ABI compatibility. - Patch releases (indicated by incrementing the PATCH number) are intended for bug fixes and other improvements of existing features only (like improving performance or adding documentation) and retain API/ABI compatibility. *Richard Levitte* * Add support for RFC5297 SIV mode (siv128), including AES-SIV. *Todd Short* * Remove the 'dist' target and add a tarball building script. The 'dist' target has fallen out of use, and it shouldn't be necessary to configure just to create a source distribution. *Richard Levitte* * Recreate the OS390-Unix config target. It no longer relies on a special script like it did for OpenSSL pre-1.1.0. *Richard Levitte* * Instead of having the source directories listed in Configure, add a 'build.info' keyword SUBDIRS to indicate what sub-directories to look into. *Richard Levitte* * Add GMAC to EVP_MAC. *Paul Dale* * Ported the HMAC, CMAC and SipHash EVP_PKEY_METHODs to EVP_MAC. *Richard Levitte* * Added EVP_MAC, an EVP layer MAC API, to simplify adding MAC implementations. This includes a generic EVP_PKEY to EVP_MAC bridge, to facilitate the continued use of MACs through raw private keys in functionality such as `EVP_DigestSign*` and `EVP_DigestVerify*`. *Richard Levitte* * Deprecate ECDH_KDF_X9_62(). *Antoine Salon* * Added EVP_PKEY_ECDH_KDF_X9_63 and ecdh_KDF_X9_63() as replacements for the EVP_PKEY_ECDH_KDF_X9_62 KDF type and ECDH_KDF_X9_62(). The old names are retained for backwards compatibility. *Antoine Salon* * AES-XTS mode now enforces that its two keys are different to mitigate the attacked described in "Efficient Instantiations of Tweakable Blockciphers and Refinements to Modes OCB and PMAC" by Phillip Rogaway. Details of this attack can be obtained from: *Paul Dale* * Rename the object files, i.e. give them other names than in previous versions. Their names now include the name of the final product, as well as its type mnemonic (bin, lib, shlib). *Richard Levitte* * Added new option for 'openssl list', '-objects', which will display the list of built in objects, i.e. OIDs with names. *Richard Levitte* * Added the options `-crl_lastupdate` and `-crl_nextupdate` to `openssl ca`, allowing the `lastUpdate` and `nextUpdate` fields in the generated CRL to be set explicitly. *Chris Novakovic* * Added support for Linux Kernel TLS data-path. The Linux Kernel data-path improves application performance by removing data copies and providing applications with zero-copy system calls such as sendfile and splice. *Boris Pismenny* * The SSL option SSL_OP_CLEANSE_PLAINTEXT is introduced. *Martin Elshuber* * `PKCS12_parse` now maintains the order of the parsed certificates when outputting them via `*ca` (rather than reversing it). *David von Oheimb* * Deprecated pthread fork support methods. *Randall S. Becker* * Added support for FFDHE key exchange in TLS 1.3. *Raja Ashok* * Added a new concept for OpenSSL plugability: providers. This functionality is designed to replace the ENGINE API and ENGINE implementations, and to be much more dynamic, allowing provider authors to introduce new algorithms among other things, as long as there's an API that supports the algorithm type. With this concept comes a new core API for interaction between libcrypto and provider implementations. Public libcrypto functions that want to use providers do so through this core API. The main documentation for this core API is found in doc/man7/provider.pod, doc/man7/provider-base.pod, and they in turn refer to other manuals describing the API specific for supported algorithm types (also called operations). *The OpenSSL team* OpenSSL 1.1.1 ------------- ### Changes between 1.1.1l and 1.1.1m [xx XXX xxxx] * Avoid loading of a dynamic engine twice. *Bernd Edlinger* * Prioritise DANE TLSA issuer certs over peer certs *Viktor Dukhovni* * Fixed random API for MacOS prior to 10.12 These MacOS versions don't support the CommonCrypto APIs *Lenny Primak* ### Changes between 1.1.1k and 1.1.1l [24 Aug 2021] * Fixed an SM2 Decryption Buffer Overflow. In order to decrypt SM2 encrypted data an application is expected to call the API function EVP_PKEY_decrypt(). Typically an application will call this function twice. The first time, on entry, the "out" parameter can be NULL and, on exit, the "outlen" parameter is populated with the buffer size required to hold the decrypted plaintext. The application can then allocate a sufficiently sized buffer and call EVP_PKEY_decrypt() again, but this time passing a non-NULL value for the "out" parameter. A bug in the implementation of the SM2 decryption code means that the calculation of the buffer size required to hold the plaintext returned by the first call to EVP_PKEY_decrypt() can be smaller than the actual size required by the second call. This can lead to a buffer overflow when EVP_PKEY_decrypt() is called by the application a second time with a buffer that is too small. A malicious attacker who is able present SM2 content for decryption to an application could cause attacker chosen data to overflow the buffer by up to a maximum of 62 bytes altering the contents of other data held after the buffer, possibly changing application behaviour or causing the application to crash. The location of the buffer is application dependent but is typically heap allocated. ([CVE-2021-3711]) *Matt Caswell* * Fixed various read buffer overruns processing ASN.1 strings ASN.1 strings are represented internally within OpenSSL as an ASN1_STRING structure which contains a buffer holding the string data and a field holding the buffer length. This contrasts with normal C strings which are repesented as a buffer for the string data which is terminated with a NUL (0) byte. Although not a strict requirement, ASN.1 strings that are parsed using OpenSSL's own "d2i" functions (and other similar parsing functions) as well as any string whose value has been set with the ASN1_STRING_set() function will additionally NUL terminate the byte array in the ASN1_STRING structure. However, it is possible for applications to directly construct valid ASN1_STRING structures which do not NUL terminate the byte array by directly setting the "data" and "length" fields in the ASN1_STRING array. This can also happen by using the ASN1_STRING_set0() function. Numerous OpenSSL functions that print ASN.1 data have been found to assume that the ASN1_STRING byte array will be NUL terminated, even though this is not guaranteed for strings that have been directly constructed. Where an application requests an ASN.1 structure to be printed, and where that ASN.1 structure contains ASN1_STRINGs that have been directly constructed by the application without NUL terminating the "data" field, then a read buffer overrun can occur. The same thing can also occur during name constraints processing of certificates (for example if a certificate has been directly constructed by the application instead of loading it via the OpenSSL parsing functions, and the certificate contains non NUL terminated ASN1_STRING structures). It can also occur in the X509_get1_email(), X509_REQ_get1_email() and X509_get1_ocsp() functions. If a malicious actor can cause an application to directly construct an ASN1_STRING and then process it through one of the affected OpenSSL functions then this issue could be hit. This might result in a crash (causing a Denial of Service attack). It could also result in the disclosure of private memory contents (such as private keys, or sensitive plaintext). ([CVE-2021-3712]) *Matt Caswell* ### Changes between 1.1.1j and 1.1.1k [25 Mar 2021] * Fixed a problem with verifying a certificate chain when using the X509_V_FLAG_X509_STRICT flag. This flag enables additional security checks of the certificates present in a certificate chain. It is not set by default. Starting from OpenSSL version 1.1.1h a check to disallow certificates in the chain that have explicitly encoded elliptic curve parameters was added as an additional strict check. An error in the implementation of this check meant that the result of a previous check to confirm that certificates in the chain are valid CA certificates was overwritten. This effectively bypasses the check that non-CA certificates must not be able to issue other certificates. If a "purpose" has been configured then there is a subsequent opportunity for checks that the certificate is a valid CA. All of the named "purpose" values implemented in libcrypto perform this check. Therefore, where a purpose is set the certificate chain will still be rejected even when the strict flag has been used. A purpose is set by default in libssl client and server certificate verification routines, but it can be overridden or removed by an application. In order to be affected, an application must explicitly set the X509_V_FLAG_X509_STRICT verification flag and either not set a purpose for the certificate verification or, in the case of TLS client or server applications, override the default purpose. ([CVE-2021-3450]) *Tomáš Mráz* * Fixed an issue where an OpenSSL TLS server may crash if sent a maliciously crafted renegotiation ClientHello message from a client. If a TLSv1.2 renegotiation ClientHello omits the signature_algorithms extension (where it was present in the initial ClientHello), but includes a signature_algorithms_cert extension then a NULL pointer dereference will result, leading to a crash and a denial of service attack. A server is only vulnerable if it has TLSv1.2 and renegotiation enabled (which is the default configuration). OpenSSL TLS clients are not impacted by this issue. ([CVE-2021-3449]) *Peter Kästle and Samuel Sapalski* ### Changes between 1.1.1i and 1.1.1j [16 Feb 2021] * Fixed the X509_issuer_and_serial_hash() function. It attempts to create a unique hash value based on the issuer and serial number data contained within an X509 certificate. However it was failing to correctly handle any errors that may occur while parsing the issuer field (which might occur if the issuer field is maliciously constructed). This may subsequently result in a NULL pointer deref and a crash leading to a potential denial of service attack. ([CVE-2021-23841]) *Matt Caswell* * Fixed the RSA_padding_check_SSLv23() function and the RSA_SSLV23_PADDING padding mode to correctly check for rollback attacks. This is considered a bug in OpenSSL 1.1.1 because it does not support SSLv2. In 1.0.2 this is CVE-2021-23839. *Matt Caswell* Fixed the EVP_CipherUpdate, EVP_EncryptUpdate and EVP_DecryptUpdate functions. Previously they could overflow the output length argument in some cases where the input length is close to the maximum permissable length for an integer on the platform. In such cases the return value from the function call would be 1 (indicating success), but the output length value would be negative. This could cause applications to behave incorrectly or crash. ([CVE-2021-23840]) *Matt Caswell* * Fixed SRP_Calc_client_key so that it runs in constant time. The previous implementation called BN_mod_exp without setting BN_FLG_CONSTTIME. This could be exploited in a side channel attack to recover the password. Since the attack is local host only this is outside of the current OpenSSL threat model and therefore no CVE is assigned. Thanks to Mohammed Sabt and Daniel De Almeida Braga for reporting this issue. *Matt Caswell* ### Changes between 1.1.1h and 1.1.1i [8 Dec 2020] * Fixed NULL pointer deref in the GENERAL_NAME_cmp function This function could crash if both GENERAL_NAMEs contain an EDIPARTYNAME. If an attacker can control both items being compared then this could lead to a possible denial of service attack. OpenSSL itself uses the GENERAL_NAME_cmp function for two purposes: 1) Comparing CRL distribution point names between an available CRL and a CRL distribution point embedded in an X509 certificate 2) When verifying that a timestamp response token signer matches the timestamp authority name (exposed via the API functions TS_RESP_verify_response and TS_RESP_verify_token) ([CVE-2020-1971]) *Matt Caswell* ### Changes between 1.1.1g and 1.1.1h [22 Sep 2020] * Certificates with explicit curve parameters are now disallowed in verification chains if the X509_V_FLAG_X509_STRICT flag is used. *Tomáš Mráz* * The 'MinProtocol' and 'MaxProtocol' configuration commands now silently ignore TLS protocol version bounds when configuring DTLS-based contexts, and conversely, silently ignore DTLS protocol version bounds when configuring TLS-based contexts. The commands can be repeated to set bounds of both types. The same applies with the corresponding "min_protocol" and "max_protocol" command-line switches, in case some application uses both TLS and DTLS. SSL_CTX instances that are created for a fixed protocol version (e.g. TLSv1_server_method()) also silently ignore version bounds. Previously attempts to apply bounds to these protocol versions would result in an error. Now only the "version-flexible" SSL_CTX instances are subject to limits in configuration files in command-line options. *Viktor Dukhovni* * Handshake now fails if Extended Master Secret extension is dropped on renegotiation. *Tomáš Mráz* * The Oracle Developer Studio compiler will start reporting deprecated APIs ### Changes between 1.1.1f and 1.1.1g [21 Apr 2020] * Fixed segmentation fault in SSL_check_chain() Server or client applications that call the SSL_check_chain() function during or after a TLS 1.3 handshake may crash due to a NULL pointer dereference as a result of incorrect handling of the "signature_algorithms_cert" TLS extension. The crash occurs if an invalid or unrecognised signature algorithm is received from the peer. This could be exploited by a malicious peer in a Denial of Service attack. ([CVE-2020-1967]) *Benjamin Kaduk* * Added AES consttime code for no-asm configurations an optional constant time support for AES was added when building openssl for no-asm. Enable with: ./config no-asm -DOPENSSL_AES_CONST_TIME Disable with: ./config no-asm -DOPENSSL_NO_AES_CONST_TIME At this time this feature is by default disabled. It will be enabled by default in 3.0. *Bernd Edlinger* ### Changes between 1.1.1e and 1.1.1f [31 Mar 2020] * Revert the change of EOF detection while reading in libssl to avoid regressions in applications depending on the current way of reporting the EOF. As the existing method is not fully accurate the change to reporting the EOF via SSL_ERROR_SSL is kept on the current development branch and will be present in the 3.0 release. *Tomáš Mráz* * Revised BN_generate_prime_ex to not avoid factors 3..17863 in p-1 when primes for RSA keys are computed. Since we previously always generated primes == 2 (mod 3) for RSA keys, the 2-prime and 3-prime RSA modules were easy to distinguish, since N = p*q = 1 (mod 3), but N = p*q*r = 2 (mod 3). Therefore fingerprinting 2-prime vs. 3-prime RSA keys was possible by computing N mod 3. This avoids possible fingerprinting of newly generated RSA modules. *Bernd Edlinger* ### Changes between 1.1.1d and 1.1.1e [17 Mar 2020] * Properly detect EOF while reading in libssl. Previously if we hit an EOF while reading in libssl then we would report an error back to the application (SSL_ERROR_SYSCALL) but errno would be 0. We now add an error to the stack (which means we instead return SSL_ERROR_SSL) and therefore give a hint as to what went wrong. *Matt Caswell* * Check that ed25519 and ed448 are allowed by the security level. Previously signature algorithms not using an MD were not being checked that they were allowed by the security level. *Kurt Roeckx* * Fixed SSL_get_servername() behaviour. The behaviour of SSL_get_servername() was not quite right. The behaviour was not consistent between resumption and normal handshakes, and also not quite consistent with historical behaviour. The behaviour in various scenarios has been clarified and it has been updated to make it match historical behaviour as closely as possible. *Matt Caswell* * *[VMS only]* The header files that the VMS compilers include automatically, `__DECC_INCLUDE_PROLOGUE.H` and `__DECC_INCLUDE_EPILOGUE.H`, use pragmas that the C++ compiler doesn't understand. This is a shortcoming in the compiler, but can be worked around with `__cplusplus` guards. C++ applications that use OpenSSL libraries must be compiled using the qualifier `/NAMES=(AS_IS,SHORTENED)` to be able to use all the OpenSSL functions. Otherwise, only functions with symbols of less than 31 characters can be used, as the linker will not be able to successfully resolve symbols with longer names. *Richard Levitte* * Added a new method to gather entropy on VMS, based on SYS$GET_ENTROPY. The presence of this system service is determined at run-time. *Richard Levitte* * Print all values for a PKCS#12 attribute with 'openssl pkcs12', not just the first value. *Jon Spillett* ### Changes between 1.1.1c and 1.1.1d [10 Sep 2019] * Fixed a fork protection issue. OpenSSL 1.1.1 introduced a rewritten random number generator (RNG). This was intended to include protection in the event of a fork() system call in order to ensure that the parent and child processes did not share the same RNG state. However this protection was not being used in the default case. A partial mitigation for this issue is that the output from a high precision timer is mixed into the RNG state so the likelihood of a parent and child process sharing state is significantly reduced. If an application already calls OPENSSL_init_crypto() explicitly using OPENSSL_INIT_ATFORK then this problem does not occur at all. ([CVE-2019-1549]) *Matthias St. Pierre* * For built-in EC curves, ensure an EC_GROUP built from the curve name is used even when parsing explicit parameters, when loading a encoded key or calling `EC_GROUP_new_from_ecpkparameters()`/ `EC_GROUP_new_from_ecparameters()`. This prevents bypass of security hardening and performance gains, especially for curves with specialized EC_METHODs. By default, if a key encoded with explicit parameters is loaded and later encoded, the output is still encoded with explicit parameters, even if internally a "named" EC_GROUP is used for computation. *Nicola Tuveri* * Compute ECC cofactors if not provided during EC_GROUP construction. Before this change, EC_GROUP_set_generator would accept order and/or cofactor as NULL. After this change, only the cofactor parameter can be NULL. It also does some minimal sanity checks on the passed order. ([CVE-2019-1547]) *Billy Bob Brumley* * Fixed a padding oracle in PKCS7_dataDecode and CMS_decrypt_set1_pkey. An attack is simple, if the first CMS_recipientInfo is valid but the second CMS_recipientInfo is chosen ciphertext. If the second recipientInfo decodes to PKCS #1 v1.5 form plaintext, the correct encryption key will be replaced by garbage, and the message cannot be decoded, but if the RSA decryption fails, the correct encryption key is used and the recipient will not notice the attack. As a work around for this potential attack the length of the decrypted key must be equal to the cipher default key length, in case the certifiate is not given and all recipientInfo are tried out. The old behaviour can be re-enabled in the CMS code by setting the CMS_DEBUG_DECRYPT flag. ([CVE-2019-1563]) *Bernd Edlinger* * Early start up entropy quality from the DEVRANDOM seed source has been improved for older Linux systems. The RAND subsystem will wait for /dev/random to be producing output before seeding from /dev/urandom. The seeded state is stored for future library initialisations using a system global shared memory segment. The shared memory identifier can be configured by defining OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID to the desired value. The default identifier is 114. *Paul Dale* * Correct the extended master secret constant on EBCDIC systems. Without this fix TLS connections between an EBCDIC system and a non-EBCDIC system that negotiate EMS will fail. Unfortunately this also means that TLS connections between EBCDIC systems with this fix, and EBCDIC systems without this fix will fail if they negotiate EMS. *Matt Caswell* * Use Windows installation paths in the mingw builds Mingw isn't a POSIX environment per se, which means that Windows paths should be used for installation. ([CVE-2019-1552]) *Richard Levitte* * Changed DH_check to accept parameters with order q and 2q subgroups. With order 2q subgroups the bit 0 of the private key is not secret but DH_generate_key works around that by clearing bit 0 of the private key for those. This avoids leaking bit 0 of the private key. *Bernd Edlinger* * Significantly reduce secure memory usage by the randomness pools. *Paul Dale* * Revert the DEVRANDOM_WAIT feature for Linux systems The DEVRANDOM_WAIT feature added a select() call to wait for the /dev/random device to become readable before reading from the /dev/urandom device. It turned out that this change had negative side effects on performance which were not acceptable. After some discussion it was decided to revert this feature and leave it up to the OS resp. the platform maintainer to ensure a proper initialization during early boot time. *Matthias St. Pierre* ### Changes between 1.1.1b and 1.1.1c [28 May 2019] * Add build tests for C++. These are generated files that only do one thing, to include one public OpenSSL head file each. This tests that the public header files can be usefully included in a C++ application. This test isn't enabled by default. It can be enabled with the option 'enable-buildtest-c++'. *Richard Levitte* * Enable SHA3 pre-hashing for ECDSA and DSA. *Patrick Steuer* * Change the default RSA, DSA and DH size to 2048 bit instead of 1024. This changes the size when using the `genpkey` command when no size is given. It fixes an omission in earlier changes that changed all RSA, DSA and DH generation commands to use 2048 bits by default. *Kurt Roeckx* * Reorganize the manual pages to consistently have RETURN VALUES, EXAMPLES, SEE ALSO and HISTORY come in that order, and adjust util/fix-doc-nits accordingly. *Paul Yang, Joshua Lock* * Add the missing accessor EVP_PKEY_get0_engine() *Matt Caswell* * Have commands like `s_client` and `s_server` output the signature scheme along with other cipher suite parameters when debugging. *Lorinczy Zsigmond* * Make OPENSSL_config() error agnostic again. *Richard Levitte* * Do the error handling in RSA decryption constant time. *Bernd Edlinger* * Prevent over long nonces in ChaCha20-Poly1305. ChaCha20-Poly1305 is an AEAD cipher, and requires a unique nonce input for every encryption operation. RFC 7539 specifies that the nonce value (IV) should be 96 bits (12 bytes). OpenSSL allows a variable nonce length and front pads the nonce with 0 bytes if it is less than 12 bytes. However it also incorrectly allows a nonce to be set of up to 16 bytes. In this case only the last 12 bytes are significant and any additional leading bytes are ignored. It is a requirement of using this cipher that nonce values are unique. Messages encrypted using a reused nonce value are susceptible to serious confidentiality and integrity attacks. If an application changes the default nonce length to be longer than 12 bytes and then makes a change to the leading bytes of the nonce expecting the new value to be a new unique nonce then such an application could inadvertently encrypt messages with a reused nonce. Additionally the ignored bytes in a long nonce are not covered by the integrity guarantee of this cipher. Any application that relies on the integrity of these ignored leading bytes of a long nonce may be further affected. Any OpenSSL internal use of this cipher, including in SSL/TLS, is safe because no such use sets such a long nonce value. However user applications that use this cipher directly and set a non-default nonce length to be longer than 12 bytes may be vulnerable. This issue was reported to OpenSSL on 16th of March 2019 by Joran Dirk Greef of Ronomon. ([CVE-2019-1543]) *Matt Caswell* * Add DEVRANDOM_WAIT feature for Linux systems On older Linux systems where the getrandom() system call is not available, OpenSSL normally uses the /dev/urandom device for seeding its CSPRNG. Contrary to getrandom(), the /dev/urandom device will not block during early boot when the kernel CSPRNG has not been seeded yet. To mitigate this known weakness, use select() to wait for /dev/random to become readable before reading from /dev/urandom. * Ensure that SM2 only uses SM3 as digest algorithm *Paul Yang* ### Changes between 1.1.1a and 1.1.1b [26 Feb 2019] * Change the info callback signals for the start and end of a post-handshake message exchange in TLSv1.3. In 1.1.1/1.1.1a we used SSL_CB_HANDSHAKE_START and SSL_CB_HANDSHAKE_DONE. Experience has shown that many applications get confused by this and assume that a TLSv1.2 renegotiation has started. This can break KeyUpdate handling. Instead we no longer signal the start and end of a post handshake message exchange (although the messages themselves are still signalled). This could break some applications that were expecting the old signals. However without this KeyUpdate is not usable for many applications. *Matt Caswell* ### Changes between 1.1.1 and 1.1.1a [20 Nov 2018] * Timing vulnerability in DSA signature generation The OpenSSL DSA signature algorithm has been shown to be vulnerable to a timing side channel attack. An attacker could use variations in the signing algorithm to recover the private key. This issue was reported to OpenSSL on 16th October 2018 by Samuel Weiser. ([CVE-2018-0734]) *Paul Dale* * Timing vulnerability in ECDSA signature generation The OpenSSL ECDSA signature algorithm has been shown to be vulnerable to a timing side channel attack. An attacker could use variations in the signing algorithm to recover the private key. This issue was reported to OpenSSL on 25th October 2018 by Samuel Weiser. ([CVE-2018-0735]) *Paul Dale* * Fixed the issue that RAND_add()/RAND_seed() silently discards random input if its length exceeds 4096 bytes. The limit has been raised to a buffer size of two gigabytes and the error handling improved. This issue was reported to OpenSSL by Dr. Falko Strenzke. It has been categorized as a normal bug, not a security issue, because the DRBG reseeds automatically and is fully functional even without additional randomness provided by the application. ### Changes between 1.1.0i and 1.1.1 [11 Sep 2018] * Add a new ClientHello callback. Provides a callback interface that gives the application the ability to adjust the nascent SSL object at the earliest stage of ClientHello processing, immediately after extensions have been collected but before they have been processed. In particular, this callback can adjust the supported TLS versions in response to the contents of the ClientHello *Benjamin Kaduk* * Add SM2 base algorithm support. *Jack Lloyd* * s390x assembly pack: add (improved) hardware-support for the following cryptographic primitives: sha3, shake, aes-gcm, aes-ccm, aes-ctr, aes-ofb, aes-cfb/cfb8, aes-ecb. *Patrick Steuer* * Make EVP_PKEY_asn1_new() a bit stricter about its input. A NULL pem_str parameter is no longer accepted, as it leads to a corrupt table. NULL pem_str is reserved for alias entries only. *Richard Levitte* * Use the new ec_scalar_mul_ladder scaffold to implement a specialized ladder step for prime curves. The new implementation is based on formulae from differential addition-and-doubling in homogeneous projective coordinates from Izu-Takagi "A fast parallel elliptic curve multiplication resistant against side channel attacks" and Brier-Joye "Weierstrass Elliptic Curves and Side-Channel Attacks" Eq. (8) for y-coordinate recovery, modified to work in projective coordinates. *Billy Bob Brumley, Nicola Tuveri* * Change generating and checking of primes so that the error rate of not being prime depends on the intended use based on the size of the input. For larger primes this will result in more rounds of Miller-Rabin. The maximal error rate for primes with more than 1080 bits is lowered to 2^-128. *Kurt Roeckx, Annie Yousar* * Increase the number of Miller-Rabin rounds for DSA key generating to 64. *Kurt Roeckx* * The 'tsget' script is renamed to 'tsget.pl', to avoid confusion when moving between systems, and to avoid confusion when a Windows build is done with mingw vs with MSVC. For POSIX installs, there's still a symlink or copy named 'tsget' to avoid that confusion as well. *Richard Levitte* * Revert blinding in ECDSA sign and instead make problematic addition length-invariant. Switch even to fixed-length Montgomery multiplication. *Andy Polyakov* * Use the new ec_scalar_mul_ladder scaffold to implement a specialized ladder step for binary curves. The new implementation is based on formulae from differential addition-and-doubling in mixed Lopez-Dahab projective coordinates, modified to independently blind the operands. *Billy Bob Brumley, Sohaib ul Hassan, Nicola Tuveri* * Add a scaffold to optionally enhance the Montgomery ladder implementation for `ec_scalar_mul_ladder` (formerly `ec_mul_consttime`) allowing EC_METHODs to implement their own specialized "ladder step", to take advantage of more favorable coordinate systems or more efficient differential addition-and-doubling algorithms. *Billy Bob Brumley, Sohaib ul Hassan, Nicola Tuveri* * Modified the random device based seed sources to keep the relevant file descriptors open rather than reopening them on each access. This allows such sources to operate in a chroot() jail without the associated device nodes being available. This behaviour can be controlled using RAND_keep_random_devices_open(). *Paul Dale* * Numerous side-channel attack mitigations have been applied. This may have performance impacts for some algorithms for the benefit of improved security. Specific changes are noted in this change log by their respective authors. *Matt Caswell* * AIX shared library support overhaul. Switch to AIX "natural" way of handling shared libraries, which means collecting shared objects of different versions and bitnesses in one common archive. This allows to mitigate conflict between 1.0 and 1.1 side-by-side installations. It doesn't affect the way 3rd party applications are linked, only how multi-version installation is managed. *Andy Polyakov* * Make ec_group_do_inverse_ord() more robust and available to other EC cryptosystems, so that irrespective of BN_FLG_CONSTTIME, SCA mitigations are applied to the fallback BN_mod_inverse(). When using this function rather than BN_mod_inverse() directly, new EC cryptosystem implementations are then safer-by-default. *Billy Bob Brumley* * Add coordinate blinding for EC_POINT and implement projective coordinate blinding for generic prime curves as a countermeasure to chosen point SCA attacks. *Sohaib ul Hassan, Nicola Tuveri, Billy Bob Brumley* * Add blinding to ECDSA and DSA signatures to protect against side channel attacks discovered by Keegan Ryan (NCC Group). *Matt Caswell* * Enforce checking in the `pkeyutl` command to ensure that the input length does not exceed the maximum supported digest length when performing a sign, verify or verifyrecover operation. *Matt Caswell* * SSL_MODE_AUTO_RETRY is enabled by default. Applications that use blocking I/O in combination with something like select() or poll() will hang. This can be turned off again using SSL_CTX_clear_mode(). Many applications do not properly handle non-application data records, and TLS 1.3 sends more of such records. Setting SSL_MODE_AUTO_RETRY works around the problems in those applications, but can also break some. It's recommended to read the manpages about SSL_read(), SSL_write(), SSL_get_error(), SSL_shutdown(), SSL_CTX_set_mode() and SSL_CTX_set_read_ahead() again. *Kurt Roeckx* * When unlocking a pass phrase protected PEM file or PKCS#8 container, we now allow empty (zero character) pass phrases. *Richard Levitte* * Apply blinding to binary field modular inversion and remove patent pending (OPENSSL_SUN_GF2M_DIV) BN_GF2m_mod_div implementation. *Billy Bob Brumley* * Deprecate ec2_mult.c and unify scalar multiplication code paths for binary and prime elliptic curves. *Billy Bob Brumley* * Remove ECDSA nonce padding: EC_POINT_mul is now responsible for constant time fixed point multiplication. *Billy Bob Brumley* * Revise elliptic curve scalar multiplication with timing attack defenses: ec_wNAF_mul redirects to a constant time implementation when computing fixed point and variable point multiplication (which in OpenSSL are mostly used with secret scalars in keygen, sign, ECDH derive operations). *Billy Bob Brumley, Nicola Tuveri, Cesar Pereida García, Sohaib ul Hassan* * Updated CONTRIBUTING *Rich Salz* * Updated DRBG / RAND to request nonce and additional low entropy randomness from the system. *Matthias St. Pierre* * Updated 'openssl rehash' to use OpenSSL consistent default. *Richard Levitte* * Moved the load of the ssl_conf module to libcrypto, which helps loading engines that libssl uses before libssl is initialised. *Matt Caswell* * Added EVP_PKEY_sign() and EVP_PKEY_verify() for EdDSA *Matt Caswell* * Fixed X509_NAME_ENTRY_set to get multi-valued RDNs right in all cases. *Ingo Schwarze, Rich Salz* * Added output of accepting IP address and port for 'openssl s_server' *Richard Levitte* * Added a new API for TLSv1.3 ciphersuites: SSL_CTX_set_ciphersuites() SSL_set_ciphersuites() *Matt Caswell* * Memory allocation failures consistently add an error to the error stack. *Rich Salz* * Don't use OPENSSL_ENGINES and OPENSSL_CONF environment values in libcrypto when run as setuid/setgid. *Bernd Edlinger* * Load any config file by default when libssl is used. *Matt Caswell* * Added new public header file and documentation for the RAND_DRBG API. See manual page RAND_DRBG(7) for an overview. *Matthias St. Pierre* * QNX support removed (cannot find contributors to get their approval for the license change). *Rich Salz* * TLSv1.3 replay protection for early data has been implemented. See the SSL_read_early_data() man page for further details. *Matt Caswell* * Separated TLSv1.3 ciphersuite configuration out from TLSv1.2 ciphersuite configuration. TLSv1.3 ciphersuites are not compatible with TLSv1.2 and below. Similarly TLSv1.2 ciphersuites are not compatible with TLSv1.3. In order to avoid issues where legacy TLSv1.2 ciphersuite configuration would otherwise inadvertently disable all TLSv1.3 ciphersuites the configuration has been separated out. See the ciphers man page or the SSL_CTX_set_ciphersuites() man page for more information. *Matt Caswell* * On POSIX (BSD, Linux, ...) systems the ocsp(1) command running in responder mode now supports the new "-multi" option, which spawns the specified number of child processes to handle OCSP requests. The "-timeout" option now also limits the OCSP responder's patience to wait to receive the full client request on a newly accepted connection. Child processes are respawned as needed, and the CA index file is automatically reloaded when changed. This makes it possible to run the "ocsp" responder as a long-running service, making the OpenSSL CA somewhat more feature-complete. In this mode, most diagnostic messages logged after entering the event loop are logged via syslog(3) rather than written to stderr. *Viktor Dukhovni* * Added support for X448 and Ed448. Heavily based on original work by Mike Hamburg. *Matt Caswell* * Extend OSSL_STORE with capabilities to search and to narrow the set of objects loaded. This adds the functions OSSL_STORE_expect() and OSSL_STORE_find() as well as needed tools to construct searches and get the search data out of them. *Richard Levitte* * Support for TLSv1.3 added. Note that users upgrading from an earlier version of OpenSSL should review their configuration settings to ensure that they are still appropriate for TLSv1.3. For further information see: *Matt Caswell* * Grand redesign of the OpenSSL random generator The default RAND method now utilizes an AES-CTR DRBG according to NIST standard SP 800-90Ar1. The new random generator is essentially a port of the default random generator from the OpenSSL FIPS 2.0 object module. It is a hybrid deterministic random bit generator using an AES-CTR bit stream and which seeds and reseeds itself automatically using trusted system entropy sources. Some of its new features are: - Support for multiple DRBG instances with seed chaining. - The default RAND method makes use of a DRBG. - There is a public and private DRBG instance. - The DRBG instances are fork-safe. - Keep all global DRBG instances on the secure heap if it is enabled. - The public and private DRBG instance are per thread for lock free operation *Paul Dale, Benjamin Kaduk, Kurt Roeckx, Rich Salz, Matthias St. Pierre* * Changed Configure so it only says what it does and doesn't dump so much data. Instead, ./configdata.pm should be used as a script to display all sorts of configuration data. *Richard Levitte* * Added processing of "make variables" to Configure. *Richard Levitte* * Added SHA512/224 and SHA512/256 algorithm support. *Paul Dale* * The last traces of Netware support, first removed in 1.1.0, have now been removed. *Rich Salz* * Get rid of Makefile.shared, and in the process, make the processing of certain files (rc.obj, or the .def/.map/.opt files produced from the ordinal files) more visible and hopefully easier to trace and debug (or make silent). *Richard Levitte* * Make it possible to have environment variable assignments as arguments to config / Configure. *Richard Levitte* * Add multi-prime RSA (RFC 8017) support. *Paul Yang* * Add SM3 implemented according to GB/T 32905-2016 *Jack Lloyd ,* *Ronald Tse ,* *Erick Borsboom * * Add 'Maximum Fragment Length' TLS extension negotiation and support as documented in RFC6066. Based on a patch from Tomasz Moń *Filipe Raimundo da Silva* * Add SM4 implemented according to GB/T 32907-2016. *Jack Lloyd ,* *Ronald Tse ,* *Erick Borsboom * * Reimplement -newreq-nodes and ERR_error_string_n; the original author does not agree with the license change. *Rich Salz* * Add ARIA AEAD TLS support. *Jon Spillett* * Some macro definitions to support VS6 have been removed. Visual Studio 6 has not worked since 1.1.0 *Rich Salz* * Add ERR_clear_last_mark(), to allow callers to clear the last mark without clearing the errors. *Richard Levitte* * Add "atfork" functions. If building on a system that without pthreads, see doc/man3/OPENSSL_fork_prepare.pod for application requirements. The RAND facility now uses/requires this. *Rich Salz* * Add SHA3. *Andy Polyakov* * The UI API becomes a permanent and integral part of libcrypto, i.e. not possible to disable entirely. However, it's still possible to disable the console reading UI method, UI_OpenSSL() (use UI_null() as a fallback). To disable, configure with 'no-ui-console'. 'no-ui' is still possible to use as an alias. Check at compile time with the macro OPENSSL_NO_UI_CONSOLE. The macro OPENSSL_NO_UI is still possible to check and is an alias for OPENSSL_NO_UI_CONSOLE. *Richard Levitte* * Add a STORE module, which implements a uniform and URI based reader of stores that can contain keys, certificates, CRLs and numerous other objects. The main API is loosely based on a few stdio functions, and includes OSSL_STORE_open, OSSL_STORE_load, OSSL_STORE_eof, OSSL_STORE_error and OSSL_STORE_close. The implementation uses backends called "loaders" to implement arbitrary URI schemes. There is one built in "loader" for the 'file' scheme. *Richard Levitte* * Add devcrypto engine. This has been implemented against cryptodev-linux, then adjusted to work on FreeBSD 8.4 as well. Enable by configuring with 'enable-devcryptoeng'. This is done by default on BSD implementations, as cryptodev.h is assumed to exist on all of them. *Richard Levitte* * Module names can prefixed with OSSL_ or OPENSSL_. This affects util/mkerr.pl, which is adapted to allow those prefixes, leading to error code calls like this: OSSL_FOOerr(OSSL_FOO_F_SOMETHING, OSSL_FOO_R_WHATEVER); With this change, we claim the namespaces OSSL and OPENSSL in a manner that can be encoded in C. For the foreseeable future, this will only affect new modules. *Richard Levitte and Tim Hudson* * Removed BSD cryptodev engine. *Rich Salz* * Add a build target 'build_all_generated', to build all generated files and only that. This can be used to prepare everything that requires things like perl for a system that lacks perl and then move everything to that system and do the rest of the build there. *Richard Levitte* * In the UI interface, make it possible to duplicate the user data. This can be used by engines that need to retain the data for a longer time than just the call where this user data is passed. *Richard Levitte* * Ignore the '-named_curve auto' value for compatibility of applications with OpenSSL 1.0.2. *Tomáš Mráz * * Fragmented SSL/TLS alerts are no longer accepted. An alert message is 2 bytes long. In theory it is permissible in SSLv3 - TLSv1.2 to fragment such alerts across multiple records (some of which could be empty). In practice it make no sense to send an empty alert record, or to fragment one. TLSv1.3 prohibits this altogether and other libraries (BoringSSL, NSS) do not support this at all. Supporting it adds significant complexity to the record layer, and its removal is unlikely to cause interoperability issues. *Matt Caswell* * Add the ASN.1 types INT32, UINT32, INT64, UINT64 and variants prefixed with Z. These are meant to replace LONG and ZLONG and to be size safe. The use of LONG and ZLONG is discouraged and scheduled for deprecation in OpenSSL 1.2.0. *Richard Levitte* * Add the 'z' and 'j' modifiers to BIO_printf() et al formatting string, 'z' is to be used for [s]size_t, and 'j' - with [u]int64_t. *Richard Levitte, Andy Polyakov* * Add EC_KEY_get0_engine(), which does for EC_KEY what RSA_get0_engine() does for RSA, etc. *Richard Levitte* * Have 'config' recognise 64-bit mingw and choose 'mingw64' as the target platform rather than 'mingw'. *Richard Levitte* * The functions X509_STORE_add_cert and X509_STORE_add_crl return success if they are asked to add an object which already exists in the store. This change cascades to other functions which load certificates and CRLs. *Paul Dale* * x86_64 assembly pack: annotate code with DWARF CFI directives to facilitate stack unwinding even from assembly subroutines. *Andy Polyakov* * Remove VAX C specific definitions of OPENSSL_EXPORT, OPENSSL_EXTERN. Also remove OPENSSL_GLOBAL entirely, as it became a no-op. *Richard Levitte* * Remove the VMS-specific reimplementation of gmtime from crypto/o_times.c. VMS C's RTL has a fully up to date gmtime() and gmtime_r() since V7.1, which is the minimum version we support. *Richard Levitte* * Certificate time validation (X509_cmp_time) enforces stricter compliance with RFC 5280. Fractional seconds and timezone offsets are no longer allowed. *Emilia Käsper* * Add support for ARIA *Paul Dale* * s_client will now send the Server Name Indication (SNI) extension by default unless the new "-noservername" option is used. The server name is based on the host provided to the "-connect" option unless overridden by using "-servername". *Matt Caswell* * Add support for SipHash *Todd Short* * 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* * 'openssl passwd' can now produce SHA256 and SHA512 based output, using the algorithm defined in *Richard Levitte* * Heartbeat support has been removed; the ABI is changed for now. *Richard Levitte, Rich Salz* * Support for SSL_OP_NO_ENCRYPT_THEN_MAC in SSL_CONF_cmd. *Emilia Käsper* * The RSA "null" method, which was partially supported to avoid patent issues, has been replaced to always returns NULL. *Rich Salz* OpenSSL 1.1.0 ------------- ### Changes between 1.1.0k and 1.1.0l [10 Sep 2019] * For built-in EC curves, ensure an EC_GROUP built from the curve name is used even when parsing explicit parameters, when loading a encoded key or calling `EC_GROUP_new_from_ecpkparameters()`/ `EC_GROUP_new_from_ecparameters()`. This prevents bypass of security hardening and performance gains, especially for curves with specialized EC_METHODs. By default, if a key encoded with explicit parameters is loaded and later encoded, the output is still encoded with explicit parameters, even if internally a "named" EC_GROUP is used for computation. *Nicola Tuveri* * Compute ECC cofactors if not provided during EC_GROUP construction. Before this change, EC_GROUP_set_generator would accept order and/or cofactor as NULL. After this change, only the cofactor parameter can be NULL. It also does some minimal sanity checks on the passed order. ([CVE-2019-1547]) *Billy Bob Brumley* * Fixed a padding oracle in PKCS7_dataDecode and CMS_decrypt_set1_pkey. An attack is simple, if the first CMS_recipientInfo is valid but the second CMS_recipientInfo is chosen ciphertext. If the second recipientInfo decodes to PKCS #1 v1.5 form plaintext, the correct encryption key will be replaced by garbage, and the message cannot be decoded, but if the RSA decryption fails, the correct encryption key is used and the recipient will not notice the attack. As a work around for this potential attack the length of the decrypted key must be equal to the cipher default key length, in case the certifiate is not given and all recipientInfo are tried out. The old behaviour can be re-enabled in the CMS code by setting the CMS_DEBUG_DECRYPT flag. ([CVE-2019-1563]) *Bernd Edlinger* * Use Windows installation paths in the mingw builds Mingw isn't a POSIX environment per se, which means that Windows paths should be used for installation. ([CVE-2019-1552]) *Richard Levitte* ### Changes between 1.1.0j and 1.1.0k [28 May 2019] * Change the default RSA, DSA and DH size to 2048 bit instead of 1024. This changes the size when using the `genpkey` command when no size is given. It fixes an omission in earlier changes that changed all RSA, DSA and DH generation commands to use 2048 bits by default. *Kurt Roeckx* * Prevent over long nonces in ChaCha20-Poly1305. ChaCha20-Poly1305 is an AEAD cipher, and requires a unique nonce input for every encryption operation. RFC 7539 specifies that the nonce value (IV) should be 96 bits (12 bytes). OpenSSL allows a variable nonce length and front pads the nonce with 0 bytes if it is less than 12 bytes. However it also incorrectly allows a nonce to be set of up to 16 bytes. In this case only the last 12 bytes are significant and any additional leading bytes are ignored. It is a requirement of using this cipher that nonce values are unique. Messages encrypted using a reused nonce value are susceptible to serious confidentiality and integrity attacks. If an application changes the default nonce length to be longer than 12 bytes and then makes a change to the leading bytes of the nonce expecting the new value to be a new unique nonce then such an application could inadvertently encrypt messages with a reused nonce. Additionally the ignored bytes in a long nonce are not covered by the integrity guarantee of this cipher. Any application that relies on the integrity of these ignored leading bytes of a long nonce may be further affected. Any OpenSSL internal use of this cipher, including in SSL/TLS, is safe because no such use sets such a long nonce value. However user applications that use this cipher directly and set a non-default nonce length to be longer than 12 bytes may be vulnerable. This issue was reported to OpenSSL on 16th of March 2019 by Joran Dirk Greef of Ronomon. ([CVE-2019-1543]) *Matt Caswell* * Added SCA hardening for modular field inversion in EC_GROUP through a new dedicated field_inv() pointer in EC_METHOD. This also addresses a leakage affecting conversions from projective to affine coordinates. *Billy Bob Brumley, Nicola Tuveri* * Fix a use after free bug in d2i_X509_PUBKEY when overwriting a re-used X509_PUBKEY object if the second PUBKEY is malformed. *Bernd Edlinger* * Move strictness check from EVP_PKEY_asn1_new() to EVP_PKEY_asn1_add0(). *Richard Levitte* * Remove the 'dist' target and add a tarball building script. The 'dist' target has fallen out of use, and it shouldn't be necessary to configure just to create a source distribution. *Richard Levitte* ### Changes between 1.1.0i and 1.1.0j [20 Nov 2018] * Timing vulnerability in DSA signature generation The OpenSSL DSA signature algorithm has been shown to be vulnerable to a timing side channel attack. An attacker could use variations in the signing algorithm to recover the private key. This issue was reported to OpenSSL on 16th October 2018 by Samuel Weiser. ([CVE-2018-0734]) *Paul Dale* * Timing vulnerability in ECDSA signature generation The OpenSSL ECDSA signature algorithm has been shown to be vulnerable to a timing side channel attack. An attacker could use variations in the signing algorithm to recover the private key. This issue was reported to OpenSSL on 25th October 2018 by Samuel Weiser. ([CVE-2018-0735]) *Paul Dale* * Add coordinate blinding for EC_POINT and implement projective coordinate blinding for generic prime curves as a countermeasure to chosen point SCA attacks. *Sohaib ul Hassan, Nicola Tuveri, Billy Bob Brumley* ### Changes between 1.1.0h and 1.1.0i [14 Aug 2018] * Client DoS due to large DH parameter During key agreement in a TLS handshake using a DH(E) based ciphersuite a malicious server can send a very large prime value to the client. This will cause the client to spend an unreasonably long period of time generating a key for this prime resulting in a hang until the client has finished. This could be exploited in a Denial Of Service attack. This issue was reported to OpenSSL on 5th June 2018 by Guido Vranken ([CVE-2018-0732]) *Guido Vranken* * Cache timing vulnerability in RSA Key Generation The OpenSSL RSA Key generation algorithm has been shown to be vulnerable to a cache timing side channel attack. An attacker with sufficient access to mount cache timing attacks during the RSA key generation process could recover the private key. This issue was reported to OpenSSL on 4th April 2018 by Alejandro Cabrera Aldaya, Billy Brumley, Cesar Pereida Garcia and Luis Manuel Alvarez Tapia. ([CVE-2018-0737]) *Billy Brumley* * Make EVP_PKEY_asn1_new() a bit stricter about its input. A NULL pem_str parameter is no longer accepted, as it leads to a corrupt table. NULL pem_str is reserved for alias entries only. *Richard Levitte* * Revert blinding in ECDSA sign and instead make problematic addition length-invariant. Switch even to fixed-length Montgomery multiplication. *Andy Polyakov* * Change generating and checking of primes so that the error rate of not being prime depends on the intended use based on the size of the input. For larger primes this will result in more rounds of Miller-Rabin. The maximal error rate for primes with more than 1080 bits is lowered to 2^-128. *Kurt Roeckx, Annie Yousar* * Increase the number of Miller-Rabin rounds for DSA key generating to 64. *Kurt Roeckx* * Add blinding to ECDSA and DSA signatures to protect against side channel attacks discovered by Keegan Ryan (NCC Group). *Matt Caswell* * When unlocking a pass phrase protected PEM file or PKCS#8 container, we now allow empty (zero character) pass phrases. *Richard Levitte* * Certificate time validation (X509_cmp_time) enforces stricter compliance with RFC 5280. Fractional seconds and timezone offsets are no longer allowed. *Emilia Käsper* * Fixed a text canonicalisation bug in CMS Where a CMS detached signature is used with text content the text goes through a canonicalisation process first prior to signing or verifying a signature. This process strips trailing space at the end of lines, converts line terminators to CRLF and removes additional trailing line terminators at the end of a file. A bug in the canonicalisation process meant that some characters, such as form-feed, were incorrectly treated as whitespace and removed. This is contrary to the specification (RFC5485). This fix could mean that detached text data signed with an earlier version of OpenSSL 1.1.0 may fail to verify using the fixed version, or text data signed with a fixed OpenSSL may fail to verify with an earlier version of OpenSSL 1.1.0. A workaround is to only verify the canonicalised text data and use the "-binary" flag (for the "cms" command line application) or set the SMIME_BINARY/PKCS7_BINARY/CMS_BINARY flags (if using CMS_verify()). *Matt Caswell* ### Changes between 1.1.0g and 1.1.0h [27 Mar 2018] * Constructed ASN.1 types with a recursive definition could exceed the stack Constructed ASN.1 types with a recursive definition (such as can be found in PKCS7) could eventually exceed the stack given malicious input with excessive recursion. This could result in a Denial Of Service attack. There are no such structures used within SSL/TLS that come from untrusted sources so this is considered safe. This issue was reported to OpenSSL on 4th January 2018 by the OSS-fuzz project. ([CVE-2018-0739]) *Matt Caswell* * Incorrect CRYPTO_memcmp on HP-UX PA-RISC Because of an implementation bug the PA-RISC CRYPTO_memcmp function is effectively reduced to only comparing the least significant bit of each byte. This allows an attacker to forge messages that would be considered as authenticated in an amount of tries lower than that guaranteed by the security claims of the scheme. The module can only be compiled by the HP-UX assembler, so that only HP-UX PA-RISC targets are affected. This issue was reported to OpenSSL on 2nd March 2018 by Peter Waltenberg (IBM). ([CVE-2018-0733]) *Andy Polyakov* * Add a build target 'build_all_generated', to build all generated files and only that. This can be used to prepare everything that requires things like perl for a system that lacks perl and then move everything to that system and do the rest of the build there. *Richard Levitte* * Backport SSL_OP_NO_RENGOTIATION OpenSSL 1.0.2 and below had the ability to disable renegotiation using the (undocumented) SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS flag. Due to the opacity changes this is no longer possible in 1.1.0. Therefore the new SSL_OP_NO_RENEGOTIATION option from 1.1.1-dev has been backported to 1.1.0 to provide equivalent functionality. Note that if an application built against 1.1.0h headers (or above) is run using an older version of 1.1.0 (prior to 1.1.0h) then the option will be accepted but nothing will happen, i.e. renegotiation will not be prevented. *Matt Caswell* * Removed the OS390-Unix config target. It relied on a script that doesn't exist. *Rich Salz* * rsaz_1024_mul_avx2 overflow bug on x86_64 There is an overflow bug in the AVX2 Montgomery multiplication procedure used in exponentiation with 1024-bit moduli. 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 DH1024 are considered just feasible, 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 significant. However, for an attack on TLS to be meaningful, the server would have to share the DH1024 private key among multiple clients, which is no longer an option since CVE-2016-0701. This only affects processors that support the AVX2 but not ADX extensions like Intel Haswell (4th generation). This issue was reported to OpenSSL by David Benjamin (Google). The issue was originally found via the OSS-Fuzz project. ([CVE-2017-3738]) *Andy Polyakov* ### Changes between 1.1.0f and 1.1.0g [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.1.0e and 1.1.0f [25 May 2017] * Have 'config' recognise 64-bit mingw and choose 'mingw64' as the target platform rather than 'mingw'. *Richard Levitte* * Remove the VMS-specific reimplementation of gmtime from crypto/o_times.c. VMS C's RTL has a fully up to date gmtime() and gmtime_r() since V7.1, which is the minimum version we support. *Richard Levitte* ### Changes between 1.1.0d and 1.1.0e [16 Feb 2017] * Encrypt-Then-Mac renegotiation crash During a renegotiation handshake if the Encrypt-Then-Mac extension is negotiated where it was not in the original handshake (or vice-versa) then this can cause OpenSSL to crash (dependant on ciphersuite). Both clients and servers are affected. This issue was reported to OpenSSL by Joe Orton (Red Hat). ([CVE-2017-3733]) *Matt Caswell* ### Changes between 1.1.0c and 1.1.0d [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* * Bad (EC)DHE parameters cause a client crash If a malicious server supplies bad parameters for a DHE or ECDHE key exchange then this can result in the client attempting to dereference a NULL pointer leading to a client crash. This could be exploited in a Denial of Service attack. This issue was reported to OpenSSL by Guido Vranken. ([CVE-2017-3730]) *Matt Caswell* * 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* ### Changes between 1.1.0b and 1.1.0c [10 Nov 2016] * ChaCha20/Poly1305 heap-buffer-overflow TLS connections using `*-CHACHA20-POLY1305` ciphersuites are susceptible to a DoS attack by corrupting larger payloads. This can result in an OpenSSL crash. This issue is not considered to be exploitable beyond a DoS. This issue was reported to OpenSSL by Robert Święcki (Google Security Team) ([CVE-2016-7054]) *Richard Levitte* * CMS Null dereference Applications parsing invalid CMS structures can crash with a NULL pointer dereference. This is caused by a bug in the handling of the ASN.1 CHOICE type in OpenSSL 1.1.0 which can result in a NULL value being passed to the structure callback if an attempt is made to free certain invalid encodings. Only CHOICE structures using a callback which do not handle NULL value are affected. This issue was reported to OpenSSL by Tyler Nighswander of ForAllSecure. ([CVE-2016-7053]) *Stephen Henson* * 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* * Removed automatic addition of RPATH in shared libraries and executables, as this was a remainder from OpenSSL 1.0.x and isn't needed any more. *Richard Levitte* ### Changes between 1.1.0a and 1.1.0b [26 Sep 2016] * Fix Use After Free for large message sizes The patch applied to address CVE-2016-6307 resulted in an issue where if a message larger than approx 16k is received then the underlying buffer to store the incoming message is reallocated and moved. Unfortunately a dangling pointer to the old location is left which results in an attempt to write to the previously freed location. This is likely to result in a crash, however it could potentially lead to execution of arbitrary code. This issue only affects OpenSSL 1.1.0a. This issue was reported to OpenSSL by Robert Święcki. ([CVE-2016-6309]) *Matt Caswell* ### Changes between 1.1.0 and 1.1.0a [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* * SSL_peek() hang on empty record OpenSSL 1.1.0 SSL/TLS will hang during a call to SSL_peek() if the peer sends an empty record. This could be exploited by a malicious peer in a Denial Of Service attack. This issue was reported to OpenSSL by Alex Gaynor. ([CVE-2016-6305]) *Matt Caswell* * Excessive allocation of memory in tls_get_message_header() and dtls1_preprocess_fragment() A (D)TLS message includes 3 bytes for its length in the header for the message. This would allow for messages up to 16Mb in length. Messages of this length are excessive and OpenSSL includes a check to ensure that a peer is sending reasonably sized messages in order to avoid too much memory being consumed to service a connection. A flaw in the logic of version 1.1.0 means that memory for the message is allocated too early, prior to the excessive message length check. Due to way memory is allocated in OpenSSL this could mean an attacker could force up to 21Mb to be allocated to service a connection. This could lead to a Denial of Service through memory exhaustion. However, the excessive message length check still takes place, and this would cause the connection to immediately fail. Assuming that the application calls SSL_free() on the failed connection in a timely manner then the 21Mb of allocated memory will then be immediately freed again. Therefore the excessive memory allocation will be transitory in nature. This then means that there is only a security impact if: 1) The application does not call SSL_free() in a timely manner in the event that the connection fails or 2) The application is working in a constrained environment where there is very little free memory or 3) The attacker initiates multiple connection attempts such that there are multiple connections in a state where memory has been allocated for the connection; SSL_free() has not yet been called; and there is insufficient memory to service the multiple requests. Except in the instance of (1) above any Denial Of Service is likely to be transitory because as soon as the connection fails the memory is subsequently freed again in the SSL_free() call. However there is an increased risk during this period of application crashes due to the lack of memory - which would then mean a more serious Denial of Service. This issue was reported to OpenSSL by Shi Lei (Gear Team, Qihoo 360 Inc.) (CVE-2016-6307 and CVE-2016-6308) *Matt Caswell* * solaris-x86-cc, i.e. 32-bit configuration with vendor compiler, had to be removed. Primary reason is that vendor assembler can't assemble our modules with -KPIC flag. As result it, assembly support, was not even available as option. But its lack means lack of side-channel resistant code, which is incompatible with security by todays standards. Fortunately gcc is readily available prepackaged option, which we firmly point at... *Andy Polyakov* ### Changes between 1.0.2h and 1.1.0 [25 Aug 2016] * Windows command-line tool supports UTF-8 opt-in option for arguments and console input. Setting OPENSSL_WIN32_UTF8 environment variable (to any value) allows Windows user to access PKCS#12 file generated with Windows CryptoAPI and protected with non-ASCII password, as well as files generated under UTF-8 locale on Linux also protected with non-ASCII password. *Andy Polyakov* * To mitigate the SWEET32 attack ([CVE-2016-2183]), 3DES cipher suites have been disabled by default and removed from DEFAULT, just like RC4. See the RC4 item below to re-enable both. *Rich Salz* * The method for finding the storage location for the Windows RAND seed file has changed. First we check %RANDFILE%. If that is not set then we check the directories %HOME%, %USERPROFILE% and %SYSTEMROOT% in that order. If all else fails we fall back to C:\. *Matt Caswell* * The EVP_EncryptUpdate() function has had its return type changed from void to int. A return of 0 indicates and error while a return of 1 indicates success. *Matt Caswell* * The flags RSA_FLAG_NO_CONSTTIME, DSA_FLAG_NO_EXP_CONSTTIME and DH_FLAG_NO_EXP_CONSTTIME which previously provided the ability to switch off the constant time implementation for RSA, DSA and DH have been made no-ops and deprecated. *Matt Caswell* * Windows RAND implementation was simplified to only get entropy by calling CryptGenRandom(). Various other RAND-related tickets were also closed. *Joseph Wylie Yandle, Rich Salz* * The stack and lhash API's were renamed to start with `OPENSSL_SK_` and `OPENSSL_LH_`, respectively. The old names are available with API compatibility. They new names are now completely documented. *Rich Salz* * Unify TYPE_up_ref(obj) methods signature. SSL_CTX_up_ref(), SSL_up_ref(), X509_up_ref(), EVP_PKEY_up_ref(), X509_CRL_up_ref(), X509_OBJECT_up_ref_count() methods are now returning an int (instead of void) like all others TYPE_up_ref() methods. So now these methods also check the return value of CRYPTO_atomic_add(), and the validity of object reference counter. *fdasilvayy@gmail.com* * With Windows Visual Studio builds, the .pdb files are installed alongside the installed libraries and executables. For a static library installation, ossl_static.pdb is the associate compiler generated .pdb file to be used when linking programs. *Richard Levitte* * Remove openssl.spec. Packaging files belong with the packagers. *Richard Levitte* * Automatic Darwin/OSX configuration has had a refresh, it will now recognise x86_64 architectures automatically. You can still decide to build for a different bitness with the environment variable KERNEL_BITS (can be 32 or 64), for example: KERNEL_BITS=32 ./config *Richard Levitte* * Change default algorithms in pkcs8 utility to use PKCS#5 v2.0, 256 bit AES and HMAC with SHA256. *Steve Henson* * Remove support for MIPS o32 ABI on IRIX (and IRIX only). *Andy Polyakov* * Triple-DES ciphers have been moved from HIGH to MEDIUM. *Rich Salz* * To enable users to have their own config files and build file templates, Configure looks in the directory indicated by the environment variable OPENSSL_LOCAL_CONFIG_DIR as well as the in-source Configurations/ directory. On VMS, OPENSSL_LOCAL_CONFIG_DIR is expected to be a logical name and is used as is. *Richard Levitte* * The following datatypes were made opaque: X509_OBJECT, X509_STORE_CTX, X509_STORE, X509_LOOKUP, and X509_LOOKUP_METHOD. The unused type X509_CERT_FILE_CTX was removed. *Rich Salz* * "shared" builds are now the default. To create only static libraries use the "no-shared" Configure option. *Matt Caswell* * Remove the no-aes, no-hmac, no-rsa, no-sha and no-md5 Configure options. All of these option have not worked for some while and are fundamental algorithms. *Matt Caswell* * Make various cleanup routines no-ops and mark them as deprecated. Most global cleanup functions are no longer required because they are handled via auto-deinit (see OPENSSL_init_crypto and OPENSSL_init_ssl man pages). Explicitly de-initing can cause problems (e.g. where a library that uses OpenSSL de-inits, but an application is still using it). The affected functions are CONF_modules_free(), ENGINE_cleanup(), OBJ_cleanup(), EVP_cleanup(), BIO_sock_cleanup(), CRYPTO_cleanup_all_ex_data(), RAND_cleanup(), SSL_COMP_free_compression_methods(), ERR_free_strings() and COMP_zlib_cleanup(). *Matt Caswell* * --strict-warnings no longer enables runtime debugging options such as REF_DEBUG. Instead, debug options are automatically enabled with '--debug' builds. *Andy Polyakov, Emilia Käsper* * Made DH and DH_METHOD opaque. The structures for managing DH objects have been moved out of the public header files. New functions for managing these have been added. *Matt Caswell* * Made RSA and RSA_METHOD opaque. The structures for managing RSA objects have been moved out of the public header files. New functions for managing these have been added. *Richard Levitte* * Made DSA and DSA_METHOD opaque. The structures for managing DSA objects have been moved out of the public header files. New functions for managing these have been added. *Matt Caswell* * Made BIO and BIO_METHOD opaque. The structures for managing BIOs have been moved out of the public header files. New functions for managing these have been added. *Matt Caswell* * Removed no-rijndael as a config option. Rijndael is an old name for AES. *Matt Caswell* * Removed the mk1mf build scripts. *Richard Levitte* * Headers are now wrapped, if necessary, with OPENSSL_NO_xxx, so it is always safe to #include a header now. *Rich Salz* * Removed the aged BC-32 config and all its supporting scripts *Richard Levitte* * Removed support for Ultrix, Netware, and OS/2. *Rich Salz* * Add support for HKDF. *Alessandro Ghedini* * Add support for blake2b and blake2s *Bill Cox* * Added support for "pipelining". Ciphers that have the EVP_CIPH_FLAG_PIPELINE flag set have a capability to process multiple encryptions/decryptions simultaneously. There are currently no built-in ciphers with this property but the expectation is that engines will be able to offer it to significantly improve throughput. Support has been extended into libssl so that multiple records for a single connection can be processed in one go (for >=TLS 1.1). *Matt Caswell* * Added the AFALG engine. This is an async capable engine which is able to offload work to the Linux kernel. In this initial version it only supports AES128-CBC. The kernel must be version 4.1.0 or greater. *Catriona Lucey* * OpenSSL now uses a new threading API. It is no longer necessary to set locking callbacks to use OpenSSL in a multi-threaded environment. There are two supported threading models: pthreads and windows threads. It is also possible to configure OpenSSL at compile time for "no-threads". The old threading API should no longer be used. The functions have been replaced with "no-op" compatibility macros. *Alessandro Ghedini, Matt Caswell* * Modify behavior of ALPN to invoke callback after SNI/servername callback, such that updates to the SSL_CTX affect ALPN. *Todd Short* * Add SSL_CIPHER queries for authentication and key-exchange. *Todd Short* * Changes to the DEFAULT cipherlist: - Prefer (EC)DHE handshakes over plain RSA. - Prefer AEAD ciphers over legacy ciphers. - Prefer ECDSA over RSA when both certificates are available. - Prefer TLSv1.2 ciphers/PRF. - Remove DSS, SEED, IDEA, CAMELLIA, and AES-CCM from the default cipherlist. *Emilia Käsper* * Change the ECC default curve list to be this, in order: x25519, secp256r1, secp521r1, secp384r1. *Rich Salz* * RC4 based libssl ciphersuites are now classed as "weak" ciphers and are disabled by default. They can be re-enabled using the enable-weak-ssl-ciphers option to Configure. *Matt Caswell* * If the server has ALPN configured, but supports no protocols that the client advertises, send a fatal "no_application_protocol" alert. This behaviour is SHALL in RFC 7301, though it isn't universally implemented by other servers. *Emilia Käsper* * Add X25519 support. Add ASN.1 and EVP_PKEY methods for X25519. This includes support for public and private key encoding using the format documented in draft-ietf-curdle-pkix-02. The corresponding EVP_PKEY method supports key generation and key derivation. TLS support complies with draft-ietf-tls-rfc4492bis-08 and uses X25519(29). *Steve Henson* * Deprecate SRP_VBASE_get_by_user. SRP_VBASE_get_by_user had inconsistent memory management behaviour. In order to fix an unavoidable memory leak ([CVE-2016-0798]), 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. *Emilia Käsper* * Configuration change; it's now possible to build dynamic engines without having to build shared libraries and vice versa. This only applies to the engines in `engines/`, those in `crypto/engine/` will always be built into libcrypto (i.e. "static"). Building dynamic engines is enabled by default; to disable, use the configuration option "disable-dynamic-engine". The only requirements for building dynamic engines are the presence of the DSO module and building with position independent code, so they will also automatically be disabled if configuring with "disable-dso" or "disable-pic". The macros OPENSSL_NO_STATIC_ENGINE and OPENSSL_NO_DYNAMIC_ENGINE are also taken away from openssl/opensslconf.h, as they are irrelevant. *Richard Levitte* * Configuration change; if there is a known flag to compile position independent code, it will always be applied on the libcrypto and libssl object files, and never on the application object files. This means other libraries that use routines from libcrypto / libssl can be made into shared libraries regardless of how OpenSSL was configured. If this isn't desirable, the configuration options "disable-pic" or "no-pic" can be used to disable the use of PIC. This will also disable building shared libraries and dynamic engines. *Richard Levitte* * Removed JPAKE code. It was experimental and has no wide use. *Rich Salz* * The INSTALL_PREFIX Makefile variable has been renamed to DESTDIR. That makes for less confusion on what this variable is for. Also, the configuration option --install_prefix is removed. *Richard Levitte* * Heartbeat for TLS has been removed and is disabled by default for DTLS; configure with enable-heartbeats. Code that uses the old #define's might need to be updated. *Emilia Käsper, Rich Salz* * Rename REF_CHECK to REF_DEBUG. *Rich Salz* * New "unified" build system The "unified" build system is aimed to be a common system for all platforms we support. With it comes new support for VMS. This system builds supports building in a different directory tree than the source tree. It produces one Makefile (for unix family or lookalikes), or one descrip.mms (for VMS). The source of information to make the Makefile / descrip.mms is small files called 'build.info', holding the necessary information for each directory with source to compile, and a template in Configurations, like unix-Makefile.tmpl or descrip.mms.tmpl. With this change, the library names were also renamed on Windows and on VMS. They now have names that are closer to the standard on Unix, and include the major version number, and in certain cases, the architecture they are built for. See "Notes on shared libraries" in INSTALL. We rely heavily on the perl module Text::Template. *Richard Levitte* * Added support for auto-initialisation and de-initialisation of the library. OpenSSL no longer requires explicit init or deinit routines to be called, except in certain circumstances. See the OPENSSL_init_crypto() and OPENSSL_init_ssl() man pages for further information. *Matt Caswell* * The arguments to the DTLSv1_listen function have changed. Specifically the "peer" argument is now expected to be a BIO_ADDR object. * Rewrite of BIO networking library. The BIO library lacked consistent support of IPv6, and adding it required some more extensive modifications. This introduces the BIO_ADDR and BIO_ADDRINFO types, which hold all types of addresses and chains of address information. It also introduces a new API, with functions like BIO_socket, BIO_connect, BIO_listen, BIO_lookup and a rewrite of BIO_accept. The source/sink BIOs BIO_s_connect, BIO_s_accept and BIO_s_datagram have been adapted accordingly. *Richard Levitte* * RSA_padding_check_PKCS1_type_1 now accepts inputs with and without the leading 0-byte. *Emilia Käsper* * CRIME protection: disable compression by default, even if OpenSSL is compiled with zlib enabled. Applications can still enable compression by calling SSL_CTX_clear_options(ctx, SSL_OP_NO_COMPRESSION), or by using the SSL_CONF library to configure compression. *Emilia Käsper* * The signature of the session callback configured with SSL_CTX_sess_set_get_cb was changed. The read-only input buffer was explicitly marked as `const unsigned char*` instead of `unsigned char*`. *Emilia Käsper* * Always DPURIFY. Remove the use of uninitialized memory in the RNG, and other conditional uses of DPURIFY. This makes -DPURIFY a no-op. *Emilia Käsper* * Removed many obsolete configuration items, including DES_PTR, DES_RISC1, DES_RISC2, DES_INT MD2_CHAR, MD2_INT, MD2_LONG BF_PTR, BF_PTR2 IDEA_SHORT, IDEA_LONG RC2_SHORT, RC2_LONG, RC4_LONG, RC4_CHUNK, RC4_INDEX *Rich Salz, with advice from Andy Polyakov* * Many BN internals have been moved to an internal header file. *Rich Salz with help from Andy Polyakov* * Configuration and writing out the results from it has changed. Files such as Makefile include/openssl/opensslconf.h and are now produced through general templates, such as Makefile.in and crypto/opensslconf.h.in and some help from the perl module Text::Template. Also, the center of configuration information is no longer Makefile. Instead, Configure produces a perl module in configdata.pm which holds most of the config data (in the hash table %config), the target data that comes from the target configuration in one of the `Configurations/*.conf` files (in %target). *Richard Levitte* * To clarify their intended purposes, the Configure options --prefix and --openssldir change their semantics, and become more straightforward and less interdependent. --prefix shall be used exclusively to give the location INSTALLTOP where programs, scripts, libraries, include files and manuals are going to be installed. The default is now /usr/local. --openssldir shall be used exclusively to give the default location OPENSSLDIR where certificates, private keys, CRLs are managed. This is also where the default openssl.cnf gets installed. If the directory given with this option is a relative path, the values of both the --prefix value and the --openssldir value will be combined to become OPENSSLDIR. The default for --openssldir is INSTALLTOP/ssl. Anyone who uses --openssldir to specify where OpenSSL is to be installed MUST change to use --prefix instead. *Richard Levitte* * The GOST engine was out of date and therefore it has been removed. An up to date GOST engine is now being maintained in an external repository. See: . Libssl still retains support for GOST ciphersuites (these are only activated if a GOST engine is present). *Matt Caswell* * EGD is no longer supported by default; use enable-egd when configuring. *Ben Kaduk and Rich Salz* * The distribution now has Makefile.in files, which are used to create Makefile's when Configure is run. *Configure must be run before trying to build now.* *Rich Salz* * The return value for SSL_CIPHER_description() for error conditions has changed. *Rich Salz* * Support for RFC6698/RFC7671 DANE TLSA peer authentication. Obtaining and performing DNSSEC validation of TLSA records is the application's responsibility. The application provides the TLSA records of its choice to OpenSSL, and these are then used to authenticate the peer. The TLSA records need not even come from DNS. They can, for example, be used to implement local end-entity certificate or trust-anchor "pinning", where the "pin" data takes the form of TLSA records, which can augment or replace verification based on the usual WebPKI public certification authorities. *Viktor Dukhovni* * Revert default OPENSSL_NO_DEPRECATED setting. Instead OpenSSL continues to support deprecated interfaces in default builds. However, applications are strongly advised to compile their source files with -DOPENSSL_API_COMPAT=0x10100000L, which hides the declarations of all interfaces deprecated in 0.9.8, 1.0.0 or the 1.1.0 releases. In environments in which all applications have been ported to not use any deprecated interfaces OpenSSL's Configure script should be used with the --api=1.1.0 option to entirely remove support for the deprecated features from the library and unconditionally disable them in the installed headers. Essentially the same effect can be achieved with the "no-deprecated" argument to Configure, except that this will always restrict the build to just the latest API, rather than a fixed API version. As applications are ported to future revisions of the API, they should update their compile-time OPENSSL_API_COMPAT define accordingly, but in most cases should be able to continue to compile with later releases. The OPENSSL_API_COMPAT versions for 1.0.0, and 0.9.8 are 0x10000000L and 0x00908000L, respectively. However those versions did not support the OPENSSL_API_COMPAT feature, and so applications are not typically tested for explicit support of just the undeprecated features of either release. *Viktor Dukhovni* * Add support for setting the minimum and maximum supported protocol. It can bet set via the SSL_set_min_proto_version() and SSL_set_max_proto_version(), or via the SSL_CONF's MinProtocol and MaxProtocol. It's recommended to use the new APIs to disable protocols instead of disabling individual protocols using SSL_set_options() or SSL_CONF's Protocol. This change also removes support for disabling TLS 1.2 in the OpenSSL TLS client at compile time by defining OPENSSL_NO_TLS1_2_CLIENT. *Kurt Roeckx* * Support for ChaCha20 and Poly1305 added to libcrypto and libssl. *Andy Polyakov* * New EC_KEY_METHOD, this replaces the older ECDSA_METHOD and ECDH_METHOD and integrates ECDSA and ECDH functionality into EC. Implementations can now redirect key generation and no longer need to convert to or from ECDSA_SIG format. Note: the ecdsa.h and ecdh.h headers are now no longer needed and just include the ec.h header file instead. *Steve Henson* * Remove support for all 40 and 56 bit ciphers. This includes all the export ciphers who are no longer supported and drops support the ephemeral RSA key exchange. The LOW ciphers currently doesn't have any ciphers in it. *Kurt Roeckx* * Made EVP_MD_CTX, EVP_MD, EVP_CIPHER_CTX, EVP_CIPHER and HMAC_CTX opaque. For HMAC_CTX, the following constructors and destructors were added: HMAC_CTX *HMAC_CTX_new(void); void HMAC_CTX_free(HMAC_CTX *ctx); For EVP_MD and EVP_CIPHER, complete APIs to create, fill and destroy such methods has been added. See EVP_MD_meth_new(3) and EVP_CIPHER_meth_new(3) for documentation. Additional changes: 1) `EVP_MD_CTX_cleanup()`, `EVP_CIPHER_CTX_cleanup()` and `HMAC_CTX_cleanup()` were removed. `HMAC_CTX_reset()` and `EVP_MD_CTX_reset()` should be called instead to reinitialise an already created structure. 2) For consistency with the majority of our object creators and destructors, `EVP_MD_CTX_(create|destroy)` were renamed to `EVP_MD_CTX_(new|free)`. The old names are retained as macros for deprecated builds. *Richard Levitte* * Added ASYNC support. Libcrypto now includes the async sub-library to enable cryptographic operations to be performed asynchronously as long as an asynchronous capable engine is used. See the ASYNC_start_job() man page for further details. Libssl has also had this capability integrated with the introduction of the new mode SSL_MODE_ASYNC and associated error SSL_ERROR_WANT_ASYNC. See the SSL_CTX_set_mode() and SSL_get_error() man pages. This work was developed in partnership with Intel Corp. *Matt Caswell* * SSL_{CTX_}set_ecdh_auto() has been removed and ECDH is support is always enabled now. If you want to disable the support you should exclude it using the list of supported ciphers. This also means that the "-no_ecdhe" option has been removed from s_server. *Kurt Roeckx* * SSL_{CTX}_set_tmp_ecdh() which can set 1 EC curve now internally calls SSL_{CTX_}set1_curves() which can set a list. *Kurt Roeckx* * Remove support for SSL_{CTX_}set_tmp_ecdh_callback(). You should set the curve you want to support using SSL_{CTX_}set1_curves(). *Kurt Roeckx* * State machine rewrite. The state machine code has been significantly refactored in order to remove much duplication of code and solve issues with the old code (see [ssl/statem/README.md](ssl/statem/README.md) for further details). This change does have some associated API changes. Notably the SSL_state() function has been removed and replaced by SSL_get_state which now returns an "OSSL_HANDSHAKE_STATE" instead of an int. SSL_set_state() has been removed altogether. The previous handshake states defined in ssl.h and ssl3.h have also been removed. *Matt Caswell* * All instances of the string "ssleay" in the public API were replaced with OpenSSL (case-matching; e.g., OPENSSL_VERSION for #define's) Some error codes related to internal RSA_eay API's were renamed. *Rich Salz* * The demo files in crypto/threads were moved to demo/threads. *Rich Salz* * Removed obsolete engines: 4758cca, aep, atalla, cswift, nuron, gmp, sureware and ubsec. *Matt Caswell, Rich Salz* * New ASN.1 embed macro. New ASN.1 macro ASN1_EMBED. This is the same as ASN1_SIMPLE except the structure is not allocated: it is part of the parent. That is instead of FOO *x; it must be: FOO x; This reduces memory fragmentation and make it impossible to accidentally set a mandatory field to NULL. This currently only works for some fields specifically a SEQUENCE, CHOICE, or ASN1_STRING type which is part of a parent SEQUENCE. Since it is equivalent to ASN1_SIMPLE it cannot be tagged, OPTIONAL, SET OF or SEQUENCE OF. *Steve Henson* * Remove EVP_CHECK_DES_KEY, a compile-time option that never compiled. *Emilia Käsper* * Removed DES and RC4 ciphersuites from DEFAULT. Also removed RC2 although in 1.0.2 EXPORT was already removed and the only RC2 ciphersuite is also an EXPORT one. COMPLEMENTOFDEFAULT has been updated accordingly to add DES and RC4 ciphersuites. *Matt Caswell* * 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* * Fix no-stdio build. *David Woodhouse and also* *Ivan Nestlerode * * New testing framework The testing framework has been largely rewritten and is now using perl and the perl modules Test::Harness and an extended variant of Test::More called OpenSSL::Test to do its work. All test scripts in test/ have been rewritten into test recipes, and all direct calls to executables in test/Makefile have become individual recipes using the simplified testing OpenSSL::Test::Simple. For documentation on our testing modules, do: perldoc test/testlib/OpenSSL/Test/Simple.pm perldoc test/testlib/OpenSSL/Test.pm *Richard Levitte* * Revamped memory debug; only -DCRYPTO_MDEBUG and -DCRYPTO_MDEBUG_ABORT are used; the latter aborts on memory leaks (usually checked on exit). Some undocumented "set malloc, etc., hooks" functions were removed and others were changed. All are now documented. *Rich Salz* * In DSA_generate_parameters_ex, if the provided seed is too short, return an error *Rich Salz and Ismo Puustinen * * Rewrite PSK to support ECDHE_PSK, DHE_PSK and RSA_PSK. Add ciphersuites from RFC4279, RFC4785, RFC5487, RFC5489. Thanks to Christian J. Dietrich and Giuseppe D'Angelo for the original RSA_PSK patch. *Steve Henson* * Dropped support for the SSL3_FLAGS_DELAY_CLIENT_FINISHED flag. This SSLeay era flag was never set throughout the codebase (only read). Also removed SSL3_FLAGS_POP_BUFFER which was only used if SSL3_FLAGS_DELAY_CLIENT_FINISHED was also set. *Matt Caswell* * Changed the default name options in the "ca", "crl", "req" and "x509" to be "oneline" instead of "compat". *Richard Levitte* * Remove SSL_OP_TLS_BLOCK_PADDING_BUG. This is SSLeay legacy, we're not aware of clients that still exhibit this bug, and the workaround hasn't been working properly for a while. *Emilia Käsper* * The return type of BIO_number_read() and BIO_number_written() as well as the corresponding num_read and num_write members in the BIO structure has changed from unsigned long to uint64_t. On platforms where an unsigned long is 32 bits (e.g. Windows) these counters could overflow if >4Gb is transferred. *Matt Caswell* * Given the pervasive nature of TLS extensions it is inadvisable to run OpenSSL without support for them. It also means that maintaining the OPENSSL_NO_TLSEXT option within the code is very invasive (and probably not well tested). Therefore the OPENSSL_NO_TLSEXT option has been removed. *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* * Version negotiation has been rewritten. In particular SSLv23_method(), SSLv23_client_method() and SSLv23_server_method() have been deprecated, and turned into macros which simply call the new preferred function names TLS_method(), TLS_client_method() and TLS_server_method(). All new code should use the new names instead. Also as part of this change the ssl23.h header file has been removed. *Matt Caswell* * Support for Kerberos ciphersuites in TLS (RFC2712) has been removed. This code and the associated standard is no longer considered fit-for-purpose. *Matt Caswell* * RT2547 was closed. When generating a private key, try to make the output file readable only by the owner. This behavior change might be noticeable when interacting with other software. * Documented all exdata functions. Added CRYPTO_free_ex_index. Added a test. *Rich Salz* * Added HTTP GET support to the ocsp command. *Rich Salz* * Changed default digest for the dgst and enc commands from MD5 to sha256 *Rich Salz* * RAND_pseudo_bytes has been deprecated. Users should use RAND_bytes instead. *Matt Caswell* * Added support for TLS extended master secret from draft-ietf-tls-session-hash-03.txt. Thanks for Alfredo Pironti for an initial patch which was a great help during development. *Steve Henson* * All libssl internal structures have been removed from the public header files, and the OPENSSL_NO_SSL_INTERN option has been removed (since it is now redundant). Users should not attempt to access internal structures directly. Instead they should use the provided API functions. *Matt Caswell* * config has been changed so that by default OPENSSL_NO_DEPRECATED is used. Access to deprecated functions can be re-enabled by running config with "enable-deprecated". In addition applications wishing to use deprecated functions must define OPENSSL_USE_DEPRECATED. Note that this new behaviour will, by default, disable some transitive includes that previously existed in the header files (e.g. ec.h will no longer, by default, include bn.h) *Matt Caswell* * Added support for OCB mode. OpenSSL has been granted a patent license compatible with the OpenSSL license for use of OCB. Details are available at . Support for OCB can be removed by calling config with no-ocb. *Matt Caswell* * SSLv2 support has been removed. It still supports receiving a SSLv2 compatible client hello. *Kurt Roeckx* * Increased the minimal RSA keysize from 256 to 512 bits [Rich Salz], done while fixing the error code for the key-too-small case. *Annie Yousar * * CA.sh has been removed; use CA.pl instead. *Rich Salz* * Removed old DES API. *Rich Salz* * Remove various unsupported platforms: Sony NEWS4 BEOS and BEOS_R5 NeXT SUNOS MPE/iX Sinix/ReliantUNIX RM400 DGUX NCR Tandem Cray 16-bit platforms such as WIN16 *Rich Salz* * Clean up OPENSSL_NO_xxx #define's - Use setbuf() and remove OPENSSL_NO_SETVBUF_IONBF - Rename OPENSSL_SYSNAME_xxx to OPENSSL_SYS_xxx - OPENSSL_NO_EC{DH,DSA} merged into OPENSSL_NO_EC - OPENSSL_NO_RIPEMD160, OPENSSL_NO_RIPEMD merged into OPENSSL_NO_RMD160 - OPENSSL_NO_FP_API merged into OPENSSL_NO_STDIO - Remove OPENSSL_NO_BIO OPENSSL_NO_BUFFER OPENSSL_NO_CHAIN_VERIFY OPENSSL_NO_EVP OPENSSL_NO_FIPS_ERR OPENSSL_NO_HASH_COMP OPENSSL_NO_LHASH OPENSSL_NO_OBJECT OPENSSL_NO_SPEED OPENSSL_NO_STACK OPENSSL_NO_X509 OPENSSL_NO_X509_VERIFY - Remove MS_STATIC; it's a relic from platforms <32 bits. *Rich Salz* * Cleaned up dead code Remove all but one '#ifdef undef' which is to be looked at. *Rich Salz* * Clean up calling of xxx_free routines. Just like free(), fix most of the xxx_free routines to accept NULL. Remove the non-null checks from callers. Save much code. *Rich Salz* * Add secure heap for storage of private keys (when possible). Add BIO_s_secmem(), CBIGNUM, etc. Contributed by Akamai Technologies under our Corporate CLA. *Rich Salz* * Experimental support for a new, fast, unbiased prime candidate generator, bn_probable_prime_dh_coprime(). Not currently used by any prime generator. *Felix Laurie von Massenbach * * New output format NSS in the sess_id command line tool. This allows exporting the session id and the master key in NSS keylog format. *Martin Kaiser * * 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 * * 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: 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* * Use algorithm specific chains in SSL_CTX_use_certificate_chain_file(): this fixes a limitation in previous versions of OpenSSL. *Steve Henson* * Experimental encrypt-then-mac support. Experimental support for encrypt then mac from draft-gutmann-tls-encrypt-then-mac-02.txt To enable it set the appropriate extension number (0x42 for the test server) using e.g. -DTLSEXT_TYPE_encrypt_then_mac=0x42 For non-compliant peers (i.e. just about everything) this should have no effect. WARNING: EXPERIMENTAL, SUBJECT TO CHANGE. *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* * Extend CMS code to support RSA-PSS signatures and RSA-OAEP for enveloped data. *Steve Henson* * Extended RSA OAEP support via EVP_PKEY API. Options to specify digest, MGF1 digest and OAEP label. *Steve Henson* * Make openssl verify return errors. *Chris Palmer and Ben Laurie* * New function ASN1_TIME_diff to calculate the difference between two ASN1_TIME structures or one structure and the current time. *Steve Henson* * Update fips_test_suite to support multiple command line options. New test to induce all self test errors in sequence and check expected failures. *Steve Henson* * Add FIPS_{rsa,dsa,ecdsa}_{sign,verify} functions which digest and sign or verify all in one operation. *Steve Henson* * Add fips_algvs: a multicall fips utility incorporating all the algorithm test programs and fips_test_suite. Includes functionality to parse the minimal script output of fipsalgest.pl directly. *Steve Henson* * Add authorisation parameter to FIPS_module_mode_set(). *Steve Henson* * Add FIPS selftest for ECDH algorithm using P-224 and B-233 curves. *Steve Henson* * Use separate DRBG fields for internal and external flags. New function FIPS_drbg_health_check() to perform on demand health checking. Add generation tests to fips_test_suite with reduced health check interval to demonstrate periodic health checking. Add "nodh" option to fips_test_suite to skip very slow DH test. *Steve Henson* * New function FIPS_get_cipherbynid() to lookup FIPS supported ciphers based on NID. *Steve Henson* * More extensive health check for DRBG checking many more failure modes. New function FIPS_selftest_drbg_all() to handle every possible DRBG combination: call this in fips_test_suite. *Steve Henson* * Add support for canonical generation of DSA parameter 'g'. See FIPS 186-3 A.2.3. * Add support for HMAC DRBG from SP800-90. Update DRBG algorithm test and POST to handle HMAC cases. *Steve Henson* * Add functions FIPS_module_version() and FIPS_module_version_text() to return numerical and string versions of the FIPS module number. *Steve Henson* * Rename FIPS_mode_set and FIPS_mode to FIPS_module_mode_set and FIPS_module_mode. FIPS_mode and FIPS_mode_set will be implemented outside the validated module in the FIPS capable OpenSSL. *Steve Henson* * Minor change to DRBG entropy callback semantics. In some cases there is no multiple of the block length between min_len and max_len. Allow the callback to return more than max_len bytes of entropy but discard any extra: it is the callback's responsibility to ensure that the extra data discarded does not impact the requested amount of entropy. *Steve Henson* * Add PRNG security strength checks to RSA, DSA and ECDSA using information in FIPS186-3, SP800-57 and SP800-131A. *Steve Henson* * CCM support via EVP. Interface is very similar to GCM case except we must supply all data in one chunk (i.e. no update, final) and the message length must be supplied if AAD is used. Add algorithm test support. *Steve Henson* * Initial version of POST overhaul. Add POST callback to allow the status of POST to be monitored and/or failures induced. Modify fips_test_suite to use callback. Always run all selftests even if one fails. *Steve Henson* * XTS support including algorithm test driver in the fips_gcmtest program. Note: this does increase the maximum key length from 32 to 64 bytes but there should be no binary compatibility issues as existing applications will never use XTS mode. *Steve Henson* * Extensive reorganisation of FIPS PRNG behaviour. Remove all dependencies to OpenSSL RAND code and replace with a tiny FIPS RAND API which also performs algorithm blocking for unapproved PRNG types. Also do not set PRNG type in FIPS_mode_set(): leave this to the application. Add default OpenSSL DRBG handling: sets up FIPS PRNG and seeds with the standard OpenSSL PRNG: set additional data to a date time vector. *Steve Henson* * Rename old X9.31 PRNG functions of the form `FIPS_rand*` to `FIPS_x931*`. This shouldn't present any incompatibility problems because applications shouldn't be using these directly and any that are will need to rethink anyway as the X9.31 PRNG is now deprecated by FIPS 140-2 *Steve Henson* * Extensive self tests and health checking required by SP800-90 DRBG. Remove strength parameter from FIPS_drbg_instantiate and always instantiate at maximum supported strength. *Steve Henson* * Add ECDH code to fips module and fips_ecdhvs for primitives only testing. *Steve Henson* * New algorithm test program fips_dhvs to handle DH primitives only testing. *Steve Henson* * New function DH_compute_key_padded() to compute a DH key and pad with leading zeroes if needed: this complies with SP800-56A et al. *Steve Henson* * Initial implementation of SP800-90 DRBGs for Hash and CTR. Not used by anything, incomplete, subject to change and largely untested at present. *Steve Henson* * Modify fipscanisteronly build option to only build the necessary object files by filtering FIPS_EX_OBJ through a perl script in crypto/Makefile. *Steve Henson* * Add experimental option FIPSSYMS to give all symbols in fipscanister.o and FIPS or fips prefix. This will avoid conflicts with future versions of OpenSSL. Add perl script util/fipsas.pl to preprocess assembly language source files and rename any affected symbols. *Steve Henson* * Add selftest checks and algorithm block of non-fips algorithms in FIPS mode. Remove DES2 from selftests. *Steve Henson* * Add ECDSA code to fips module. Add tiny fips_ecdsa_check to just return internal method without any ENGINE dependencies. Add new tiny fips sign and verify functions. *Steve Henson* * New build option no-ec2m to disable characteristic 2 code. *Steve Henson* * New build option "fipscanisteronly". This only builds fipscanister.o and (currently) associated fips utilities. Uses the file Makefile.fips instead of Makefile.org as the prototype. *Steve Henson* * Add some FIPS mode restrictions to GCM. Add internal IV generator. Update fips_gcmtest to use IV generator. *Steve Henson* * Initial, experimental EVP support for AES-GCM. AAD can be input by setting output buffer to NULL. The `*Final` function must be called although it will not retrieve any additional data. The tag can be set or retrieved with a ctrl. The IV length is by default 12 bytes (96 bits) but can be set to an alternative value. If the IV length exceeds the maximum IV length (currently 16 bytes) it cannot be set before the key. *Steve Henson* * New flag in ciphers: EVP_CIPH_FLAG_CUSTOM_CIPHER. This means the underlying do_cipher function handles all cipher semantics itself including padding and finalisation. This is useful if (for example) an ENGINE cipher handles block padding itself. The behaviour of do_cipher is subtly changed if this flag is set: the return value is the number of characters written to the output buffer (zero is no longer an error code) or a negative error code. Also if the input buffer is NULL and length 0 finalisation should be performed. *Steve Henson* * If a candidate issuer certificate is already part of the constructed path ignore it: new debug notification X509_V_ERR_PATH_LOOP for this case. *Steve Henson* * Improve forward-security support: add functions void SSL_CTX_set_not_resumable_session_callback( SSL_CTX *ctx, int (*cb)(SSL *ssl, int is_forward_secure)) void SSL_set_not_resumable_session_callback( SSL *ssl, int (*cb)(SSL *ssl, int is_forward_secure)) for use by SSL/TLS servers; the callback function will be called whenever a new session is created, and gets to decide whether the session may be cached to make it resumable (return 0) or not (return 1). (As by the SSL/TLS protocol specifications, the session_id sent by the server will be empty to indicate that the session is not resumable; also, the server will not generate RFC 4507 (RFC 5077) session tickets.) A simple reasonable callback implementation is to return is_forward_secure. This parameter will be set to 1 or 0 depending on the ciphersuite selected by the SSL/TLS server library, indicating whether it can provide forward security. *Emilia Käsper (Google)* * New -verify_name option in command line utilities to set verification parameters by name. *Steve Henson* * Initial CMAC implementation. WARNING: EXPERIMENTAL, API MAY CHANGE. Add CMAC pkey methods. *Steve Henson* * Experimental renegotiation in s_server -www mode. If the client browses /reneg connection is renegotiated. If /renegcert it is renegotiated requesting a certificate. *Steve Henson* * Add an "external" session cache for debugging purposes to s_server. This should help trace issues which normally are only apparent in deployed multi-process servers. *Steve Henson* * Extensive audit of libcrypto with DEBUG_UNUSED. Fix many cases where return value is ignored. NB. The functions RAND_add(), RAND_seed(), BIO_set_cipher() and some obscure PEM functions were changed so they can now return an error. The RAND changes required a change to the RAND_METHOD structure. *Steve Henson* * New macro `__owur` for "OpenSSL Warn Unused Result". This makes use of a gcc attribute to warn if the result of a function is ignored. This is enable if DEBUG_UNUSED is set. Add to several functions in evp.h whose return value is often ignored. *Steve Henson* * New -noct, -requestct, -requirect and -ctlogfile options for s_client. These allow SCTs (signed certificate timestamps) to be requested and validated when establishing a connection. *Rob Percival * OpenSSL 1.0.2 ------------- ### Changes between 1.0.2s and 1.0.2t [10 Sep 2019] * For built-in EC curves, ensure an EC_GROUP built from the curve name is used even when parsing explicit parameters, when loading a encoded key or calling `EC_GROUP_new_from_ecpkparameters()`/ `EC_GROUP_new_from_ecparameters()`. This prevents bypass of security hardening and performance gains, especially for curves with specialized EC_METHODs. By default, if a key encoded with explicit parameters is loaded and later encoded, the output is still encoded with explicit parameters, even if internally a "named" EC_GROUP is used for computation. *Nicola Tuveri* * Compute ECC cofactors if not provided during EC_GROUP construction. Before this change, EC_GROUP_set_generator would accept order and/or cofactor as NULL. After this change, only the cofactor parameter can be NULL. It also does some minimal sanity checks on the passed order. ([CVE-2019-1547]) *Billy Bob Brumley* * Fixed a padding oracle in PKCS7_dataDecode and CMS_decrypt_set1_pkey. An attack is simple, if the first CMS_recipientInfo is valid but the second CMS_recipientInfo is chosen ciphertext. If the second recipientInfo decodes to PKCS #1 v1.5 form plaintext, the correct encryption key will be replaced by garbage, and the message cannot be decoded, but if the RSA decryption fails, the correct encryption key is used and the recipient will not notice the attack. As a work around for this potential attack the length of the decrypted key must be equal to the cipher default key length, in case the certifiate is not given and all recipientInfo are tried out. The old behaviour can be re-enabled in the CMS code by setting the CMS_DEBUG_DECRYPT flag. ([CVE-2019-1563]) *Bernd Edlinger* * Document issue with installation paths in diverse Windows builds '/usr/local/ssl' is an unsafe prefix for location to install OpenSSL binaries and run-time config file. ([CVE-2019-1552]) *Richard Levitte* ### Changes between 1.0.2r and 1.0.2s [28 May 2019] * Change the default RSA, DSA and DH size to 2048 bit instead of 1024. This changes the size when using the `genpkey` command when no size is given. It fixes an omission in earlier changes that changed all RSA, DSA and DH generation commands to use 2048 bits by default. *Kurt Roeckx* * Add FIPS support for Android Arm 64-bit Support for Android Arm 64-bit was added to the OpenSSL FIPS Object Module in Version 2.0.10. For some reason, the corresponding target 'android64-aarch64' was missing OpenSSL 1.0.2, whence it could not be built with FIPS support on Android Arm 64-bit. This omission has been fixed. *Matthias St. Pierre* ### Changes between 1.0.2q and 1.0.2r [26 Feb 2019] * 0-byte record padding oracle If an application encounters a fatal protocol error and then calls SSL_shutdown() twice (once to send a close_notify, and once to receive one) then OpenSSL can respond differently to the calling application if a 0 byte record is received with invalid padding compared to if a 0 byte record is received with an invalid MAC. If the application then behaves differently based on that in a way that is detectable to the remote peer, then this amounts to a padding oracle that could be used to decrypt data. In order for this to be exploitable "non-stitched" ciphersuites must be in use. Stitched ciphersuites are optimised implementations of certain commonly used ciphersuites. Also the application must call SSL_shutdown() twice even if a protocol error has occurred (applications should not do this but some do anyway). This issue was discovered by Juraj Somorovsky, Robert Merget and Nimrod Aviram, with additional investigation by Steven Collison and Andrew Hourselt. It was reported to OpenSSL on 10th December 2018. ([CVE-2019-1559]) *Matt Caswell* * Move strictness check from EVP_PKEY_asn1_new() to EVP_PKEY_asn1_add0(). *Richard Levitte* ### Changes between 1.0.2p and 1.0.2q [20 Nov 2018] * Microarchitecture timing vulnerability in ECC scalar multiplication OpenSSL ECC scalar multiplication, used in e.g. ECDSA and ECDH, has been shown to be vulnerable to a microarchitecture timing side channel attack. An attacker with sufficient access to mount local timing attacks during ECDSA signature generation could recover the private key. This issue was reported to OpenSSL on 26th October 2018 by Alejandro Cabrera Aldaya, Billy Brumley, Sohaib ul Hassan, Cesar Pereida Garcia and Nicola Tuveri. ([CVE-2018-5407]) *Billy Brumley* * Timing vulnerability in DSA signature generation The OpenSSL DSA signature algorithm has been shown to be vulnerable to a timing side channel attack. An attacker could use variations in the signing algorithm to recover the private key. This issue was reported to OpenSSL on 16th October 2018 by Samuel Weiser. ([CVE-2018-0734]) *Paul Dale* * Resolve a compatibility issue in EC_GROUP handling with the FIPS Object Module, accidentally introduced while backporting security fixes from the development branch and hindering the use of ECC in FIPS mode. *Nicola Tuveri* ### Changes between 1.0.2o and 1.0.2p [14 Aug 2018] * Client DoS due to large DH parameter During key agreement in a TLS handshake using a DH(E) based ciphersuite a malicious server can send a very large prime value to the client. This will cause the client to spend an unreasonably long period of time generating a key for this prime resulting in a hang until the client has finished. This could be exploited in a Denial Of Service attack. This issue was reported to OpenSSL on 5th June 2018 by Guido Vranken ([CVE-2018-0732]) *Guido Vranken* * Cache timing vulnerability in RSA Key Generation The OpenSSL RSA Key generation algorithm has been shown to be vulnerable to a cache timing side channel attack. An attacker with sufficient access to mount cache timing attacks during the RSA key generation process could recover the private key. This issue was reported to OpenSSL on 4th April 2018 by Alejandro Cabrera Aldaya, Billy Brumley, Cesar Pereida Garcia and Luis Manuel Alvarez Tapia. ([CVE-2018-0737]) *Billy Brumley* * Make EVP_PKEY_asn1_new() a bit stricter about its input. A NULL pem_str parameter is no longer accepted, as it leads to a corrupt table. NULL pem_str is reserved for alias entries only. *Richard Levitte* * Revert blinding in ECDSA sign and instead make problematic addition length-invariant. Switch even to fixed-length Montgomery multiplication. *Andy Polyakov* * Change generating and checking of primes so that the error rate of not being prime depends on the intended use based on the size of the input. For larger primes this will result in more rounds of Miller-Rabin. The maximal error rate for primes with more than 1080 bits is lowered to 2^-128. *Kurt Roeckx, Annie Yousar* * Increase the number of Miller-Rabin rounds for DSA key generating to 64. *Kurt Roeckx* * Add blinding to ECDSA and DSA signatures to protect against side channel attacks discovered by Keegan Ryan (NCC Group). *Matt Caswell* * When unlocking a pass phrase protected PEM file or PKCS#8 container, we now allow empty (zero character) pass phrases. *Richard Levitte* * Certificate time validation (X509_cmp_time) enforces stricter compliance with RFC 5280. Fractional seconds and timezone offsets are no longer allowed. *Emilia Käsper* ### Changes between 1.0.2n and 1.0.2o [27 Mar 2018] * Constructed ASN.1 types with a recursive definition could exceed the stack Constructed ASN.1 types with a recursive definition (such as can be found in PKCS7) could eventually exceed the stack given malicious input with excessive recursion. This could result in a Denial Of Service attack. There are no such structures used within SSL/TLS that come from untrusted sources so this is considered safe. This issue was reported to OpenSSL on 4th January 2018 by the OSS-fuzz project. ([CVE-2018-0739]) *Matt Caswell* ### Changes between 1.0.2m and 1.0.2n [7 Dec 2017] * Read/write after SSL object in error state OpenSSL 1.0.2 (starting from version 1.0.2b) introduced an "error state" mechanism. The intent was that if a fatal error occurred during a handshake then OpenSSL would move into the error state and would immediately fail if you attempted to continue the handshake. This works as designed for the explicit handshake functions (SSL_do_handshake(), SSL_accept() and SSL_connect()), however due to a bug it does not work correctly if SSL_read() or SSL_write() is called directly. In that scenario, if the handshake fails then a fatal error will be returned in the initial function call. If SSL_read()/SSL_write() is subsequently called by the application for the same SSL object then it will succeed and the data is passed without being decrypted/encrypted directly from the SSL/TLS record layer. In order to exploit this issue an application bug would have to be present that resulted in a call to SSL_read()/SSL_write() being issued after having already received a fatal error. This issue was reported to OpenSSL by David Benjamin (Google). ([CVE-2017-3737]) *Matt Caswell* * rsaz_1024_mul_avx2 overflow bug on x86_64 There is an overflow bug in the AVX2 Montgomery multiplication procedure used in exponentiation with 1024-bit moduli. 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 DH1024 are considered just feasible, 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 significant. However, for an attack on TLS to be meaningful, the server would have to share the DH1024 private key among multiple clients, which is no longer an option since CVE-2016-0701. This only affects processors that support the AVX2 but not ADX extensions like Intel Haswell (4th generation). This issue was reported to OpenSSL by David Benjamin (Google). The issue was originally found via the OSS-Fuzz project. ([CVE-2017-3738]) *Andy Polyakov* ### 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. *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. *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 primarily 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 cause 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 . ([CVE-2016-0702]) *Andy Polyakov* * Change the `req` command 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 commands 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* ### 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, return an error *Rich Salz and Ismo Puustinen * ### Changes between 1.0.2c and 1.0.2d [9 Jul 2015] * Alternate chains certificate forgery During certificate verification, 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). *Matt Caswell* ### 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. *Matt Caswell* ### 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* * 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* ### 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] * 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 platforms 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 limitation 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 distinct 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: returning 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 openssl 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 performance) 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. OpenSSL 1.0.1 ------------- ### Changes between 1.0.1t and 1.0.1u [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.1s and 1.0.1t [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.1r and 1.0.1s [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 . ([CVE-2016-0702]) *Andy Polyakov* * Change the req command 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 commands to use 2048 bits by default. *Emilia Käsper* ### Changes between 1.0.1q and 1.0.1r [28 Jan 2016] * Protection for DH small subgroup attacks As a precautionary measure the SSL_OP_SINGLE_DH_USE option has been switched on by default and cannot be disabled. This could have some performance impact. *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.1p and 1.0.1q [3 Dec 2015] * 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.1o and 1.0.1p [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.1n and 1.0.1o [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.1m and 1.0.1n [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* * Reject DH handshakes with parameters shorter than 768 bits. *Kurt Roeckx and Emilia Kasper* * dhparam: generate 2048-bit parameters by default. *Kurt Roeckx and Emilia Kasper* ### Changes between 1.0.1l and 1.0.1m [19 Mar 2015] * 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* * 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* * 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.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. Re-encode 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. Re-encode 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. *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: 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: 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 . *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 disabling 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 interoperability 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 permitted 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, . 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 instead 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 include 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 appropriate default but do *not* set the default. This means we can return the appropriate method in applications that switch 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* * A long standing patch to add support for SRP from EdelWeb (Peter Sylvester and Christophe Renou) was integrated. *Christophe Renou , Peter Sylvester , 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* OpenSSL 1.0.0 ------------- ### Changes between 1.0.0s and 1.0.0t [3 Dec 2015] * 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* * 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.0r and 1.0.0s [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* ### Changes between 1.0.0q and 1.0.0r [19 Mar 2015] * 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* * 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* * 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.0p and 1.0.0q [15 Jan 2015] * Build fixes for the Windows and OpenVMS platforms *Matt Caswell and Richard Levitte* ### Changes between 1.0.0o and 1.0.0p [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* * 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* * 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* ### Changes between 1.0.0n and 1.0.0o [15 Oct 2014] * 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.0m and 1.0.0n [6 Aug 2014] * 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 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.0l and 1.0.0m [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. *mancha * * Fix some double frees. These are not thought to be exploitable. *mancha * * 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: 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* ### Changes between 1.0.0k and 1.0.0l [6 Jan 2014] * 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.0j and 1.0.0k [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: 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* * Return an error when checking OCSP signatures when key is NULL. This fixes a DoS attack. ([CVE-2013-0166]) *Steve Henson* * 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 . (This is a backport) *Rob Stradling * * Fix possible deadlock when decoding public keys. *Steve Henson* ### Changes between 1.0.0i and 1.0.0j [10 May 2012] [NB: OpenSSL 1.0.0i and later 1.0.0 patch levels were released after OpenSSL 1.0.1.] * Sanity check record length before skipping explicit IV in 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* ### Changes between 1.0.0h and 1.0.0i [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* ### 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 re-enabled 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: 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: *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 commands 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 won't 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 internal 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 parameters 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 functionality) such that between otherwise identical ciphersuites, 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 enhanced 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 preference 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 analogous 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 unrecognized_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 setting 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* OpenSSL 0.9.x ------------- ### 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_wexpand() 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 message 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 determine 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 transition 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: don't set attribute using ASN1_TYPE_set1 if MBSTRING flag set. This bug would crash certain attribute creation routines such as certificate 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 client 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 implementation 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 unrecognized_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 ) 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 (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. Similarly, 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 occurred 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 ). 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 compression 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: 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 incomplete 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` commands. *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 interdependencies 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 addition 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 multi-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 overridden 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 overridden 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. Adapt 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 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 occurred 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 explicitly 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 re-encode DNs into UTF8Strings (in violation of RFC3280) and can't or won't 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 incorrect 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 its 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 successful, 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 initialized 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 initialized 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* * Preliminary 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 interfaces. 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.md](crypto/engine/README.md) 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 received 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.md](README-Engine.md)). *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.md](README-Engine.md) 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: crypt pe 8 bytes 64 bytes 256 bytes 1024 bytes 8192 bytes s-cbc 4408.85k 5560.51k 5778.46k 5862.20k 5825.16k s-cbc 4389.55k 5571.17k 5792.23k 5846.91k 5832.11k s-cbc 4394.32k 5575.92k 5807.44k 5848.37k 5841.30k crypt s-cbc 3482.66k 5069.49k 5496.39k 5614.16k 5639.28k s-cbc 3480.74k 5068.76k 5510.34k 5609.87k 5635.52k s-cbc 3483.72k 5067.62k 5504.60k 5708.01k 5724.80k After: crypt s-cbc 4660.16k 5650.19k 5807.19k 5827.13k 5783.32k crypt s-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *Ben Laurie* * Added the OS2-EMX target. *"Brian Havard" and Richard Levitte* * Rewrite commands 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 w.rt. 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; won't 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, outputted 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, querying 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 won't 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, recognize 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 certificates 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 appropriate 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* * 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 incorrect 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 its 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 erroneously 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 circumvents 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 occurred. (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 specifically 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, ). *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 disabled 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 presenting 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 outputting 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 () 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 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 [crypto/objects/README.md](crypto/objects/README.md). - 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 instead. 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 with the exception of the first that must be a `CONF *` instead of a `LHASH *`. To make it easier 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, meaning you effectively 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 divisor 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 because 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 analogous 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 ASN1_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 occurred 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 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* * DES CBC did not update the IV. Weird. *Ben Laurie* lse 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. ndif * 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 embedded 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 ciphers 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 comparison 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 every time: One now can use `perl Configure :
`, i.e. platform ids are allowed to have details appended to them (separated 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`. Additionally 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 , 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 is 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 commands. 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: - 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 adding 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` command working and add it to the `list` command. 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 constructed 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 documentation 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 an 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 * +[CVE-2023-4807]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-4807 [CVE-2023-3817]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-3817 [CVE-2023-3446]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-3446 [CVE-2023-2975]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-2975 [RFC 2578 (STD 58), section 3.5]: https://datatracker.ietf.org/doc/html/rfc2578#section-3.5 [CVE-2023-2650]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-2650 [CVE-2023-1255]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-1255 [CVE-2023-0466]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0466 [CVE-2023-0465]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0465 [CVE-2023-0464]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0464 [CVE-2023-0401]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0401 [CVE-2023-0286]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0286 [CVE-2023-0217]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0217 [CVE-2023-0216]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0216 [CVE-2023-0215]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0215 [CVE-2022-4450]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-4450 [CVE-2022-4304]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-4304 [CVE-2022-4203]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-4203 [CVE-2022-3996]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-3996 [CVE-2022-2274]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-2274 [CVE-2022-2097]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-2097 [CVE-2020-1971]: https://www.openssl.org/news/vulnerabilities.html#CVE-2020-1971 [CVE-2020-1967]: https://www.openssl.org/news/vulnerabilities.html#CVE-2020-1967 [CVE-2019-1563]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1563 [CVE-2019-1559]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1559 [CVE-2019-1552]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1552 [CVE-2019-1551]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1551 [CVE-2019-1549]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1549 [CVE-2019-1547]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1547 [CVE-2019-1543]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1543 [CVE-2018-5407]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-5407 [CVE-2018-0739]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0739 [CVE-2018-0737]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0737 [CVE-2018-0735]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0735 [CVE-2018-0734]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0734 [CVE-2018-0733]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0733 [CVE-2018-0732]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0732 [CVE-2017-3738]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3738 [CVE-2017-3737]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3737 [CVE-2017-3736]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3736 [CVE-2017-3735]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3735 [CVE-2017-3733]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3733 [CVE-2017-3732]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3732 [CVE-2017-3731]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3731 [CVE-2017-3730]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3730 [CVE-2016-7055]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-7055 [CVE-2016-7054]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-7054 [CVE-2016-7053]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-7053 [CVE-2016-7052]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-7052 [CVE-2016-6309]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6309 [CVE-2016-6308]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6308 [CVE-2016-6307]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6307 [CVE-2016-6306]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6306 [CVE-2016-6305]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6305 [CVE-2016-6304]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6304 [CVE-2016-6303]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6303 [CVE-2016-6302]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6302 [CVE-2016-2183]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2183 [CVE-2016-2182]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2182 [CVE-2016-2181]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2181 [CVE-2016-2180]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2180 [CVE-2016-2179]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2179 [CVE-2016-2178]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2178 [CVE-2016-2177]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2177 [CVE-2016-2176]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2176 [CVE-2016-2109]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2109 [CVE-2016-2107]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2107 [CVE-2016-2106]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2106 [CVE-2016-2105]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2105 [CVE-2016-0800]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0800 [CVE-2016-0799]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0799 [CVE-2016-0798]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0798 [CVE-2016-0797]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0797 [CVE-2016-0705]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0705 [CVE-2016-0702]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0702 [CVE-2016-0701]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0701 [CVE-2015-3197]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-3197 [CVE-2015-3196]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-3196 [CVE-2015-3195]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-3195 [CVE-2015-3194]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-3194 [CVE-2015-3193]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-3193 [CVE-2015-1793]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1793 [CVE-2015-1792]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1792 [CVE-2015-1791]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1791 [CVE-2015-1790]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1790 [CVE-2015-1789]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1789 [CVE-2015-1788]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1788 [CVE-2015-1787]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1787 [CVE-2015-0293]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0293 [CVE-2015-0291]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0291 [CVE-2015-0290]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0290 [CVE-2015-0289]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0289 [CVE-2015-0288]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0288 [CVE-2015-0287]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0287 [CVE-2015-0286]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0286 [CVE-2015-0285]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0285 [CVE-2015-0209]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0209 [CVE-2015-0208]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0208 [CVE-2015-0207]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0207 [CVE-2015-0206]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0206 [CVE-2015-0205]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0205 [CVE-2015-0204]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0204 [CVE-2014-8275]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-8275 [CVE-2014-5139]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-5139 [CVE-2014-3572]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3572 [CVE-2014-3571]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3571 [CVE-2014-3570]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3570 [CVE-2014-3569]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3569 [CVE-2014-3568]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3568 [CVE-2014-3567]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3567 [CVE-2014-3566]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3566 [CVE-2014-3513]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3513 [CVE-2014-3512]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3512 [CVE-2014-3511]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3511 [CVE-2014-3510]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3510 [CVE-2014-3509]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3509 [CVE-2014-3508]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3508 [CVE-2014-3507]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3507 [CVE-2014-3506]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3506 [CVE-2014-3505]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3505 [CVE-2014-3470]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3470 [CVE-2014-0224]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-0224 [CVE-2014-0221]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-0221 [CVE-2014-0195]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-0195 [CVE-2014-0160]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-0160 [CVE-2014-0076]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-0076 [CVE-2013-6450]: https://www.openssl.org/news/vulnerabilities.html#CVE-2013-6450 [CVE-2013-4353]: https://www.openssl.org/news/vulnerabilities.html#CVE-2013-4353 [CVE-2013-0169]: https://www.openssl.org/news/vulnerabilities.html#CVE-2013-0169 [CVE-2013-0166]: https://www.openssl.org/news/vulnerabilities.html#CVE-2013-0166 [CVE-2012-2686]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-2686 [CVE-2012-2333]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-2333 [CVE-2012-2110]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-2110 [CVE-2012-0884]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-0884 [CVE-2012-0050]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-0050 [CVE-2012-0027]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-0027 [CVE-2011-4619]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-4619 [CVE-2011-4577]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-4577 [CVE-2011-4576]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-4576 [CVE-2011-4109]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-4109 [CVE-2011-4108]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-4108 [CVE-2011-3210]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-3210 [CVE-2011-3207]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-3207 [CVE-2011-0014]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-0014 [CVE-2010-4252]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-4252 [CVE-2010-4180]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-4180 [CVE-2010-3864]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-3864 [CVE-2010-1633]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-1633 [CVE-2010-0740]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-0740 [CVE-2010-0433]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-0433 [CVE-2009-4355]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-4355 [CVE-2009-3555]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-3555 [CVE-2009-3245]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-3245 [CVE-2009-1386]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-1386 [CVE-2009-1379]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-1379 [CVE-2009-1378]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-1378 [CVE-2009-1377]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-1377 [CVE-2009-0789]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-0789 [CVE-2009-0591]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-0591 [CVE-2009-0590]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-0590 [CVE-2008-5077]: https://www.openssl.org/news/vulnerabilities.html#CVE-2008-5077 [CVE-2008-1678]: https://www.openssl.org/news/vulnerabilities.html#CVE-2008-1678 [CVE-2008-1672]: https://www.openssl.org/news/vulnerabilities.html#CVE-2008-1672 [CVE-2008-0891]: https://www.openssl.org/news/vulnerabilities.html#CVE-2008-0891 [CVE-2007-5135]: https://www.openssl.org/news/vulnerabilities.html#CVE-2007-5135 [CVE-2007-4995]: https://www.openssl.org/news/vulnerabilities.html#CVE-2007-4995 [CVE-2006-4343]: https://www.openssl.org/news/vulnerabilities.html#CVE-2006-4343 [CVE-2006-4339]: https://www.openssl.org/news/vulnerabilities.html#CVE-2006-4339 [CVE-2006-3738]: https://www.openssl.org/news/vulnerabilities.html#CVE-2006-3738 [CVE-2006-2940]: https://www.openssl.org/news/vulnerabilities.html#CVE-2006-2940 [CVE-2006-2937]: https://www.openssl.org/news/vulnerabilities.html#CVE-2006-2937 [CVE-2005-2969]: https://www.openssl.org/news/vulnerabilities.html#CVE-2005-2969 [CVE-2004-0112]: https://www.openssl.org/news/vulnerabilities.html#CVE-2004-0112 [CVE-2004-0079]: https://www.openssl.org/news/vulnerabilities.html#CVE-2004-0079 [CVE-2003-0851]: https://www.openssl.org/news/vulnerabilities.html#CVE-2003-0851 [CVE-2003-0545]: https://www.openssl.org/news/vulnerabilities.html#CVE-2003-0545 [CVE-2003-0544]: https://www.openssl.org/news/vulnerabilities.html#CVE-2003-0544 [CVE-2003-0543]: https://www.openssl.org/news/vulnerabilities.html#CVE-2003-0543 [CVE-2003-0078]: https://www.openssl.org/news/vulnerabilities.html#CVE-2003-0078 [CVE-2002-0659]: https://www.openssl.org/news/vulnerabilities.html#CVE-2002-0659 [CVE-2002-0657]: https://www.openssl.org/news/vulnerabilities.html#CVE-2002-0657 [CVE-2002-0656]: https://www.openssl.org/news/vulnerabilities.html#CVE-2002-0656 [CVE-2002-0655]: https://www.openssl.org/news/vulnerabilities.html#CVE-2002-0655 diff --git a/NEWS.md b/NEWS.md index feed90269760..f7ca47baff87 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,1612 +1,1618 @@ NEWS ==== This file gives a brief overview of the major changes between each OpenSSL release. For more details please read the CHANGES file. OpenSSL Releases ---------------- - [OpenSSL 3.0](#openssl-30) - [OpenSSL 1.1.1](#openssl-111) - [OpenSSL 1.1.0](#openssl-110) - [OpenSSL 1.0.2](#openssl-102) - [OpenSSL 1.0.1](#openssl-101) - [OpenSSL 1.0.0](#openssl-100) - [OpenSSL 0.9.x](#openssl-09x) OpenSSL 3.0 ----------- +### Major changes between OpenSSL 3.0.10 and OpenSSL 3.0.11 [19 Sep 2023] + + * Fix POLY1305 MAC implementation corrupting XMM registers on Windows + ([CVE-2023-4807]) + ### Major changes between OpenSSL 3.0.9 and OpenSSL 3.0.10 [1 Aug 2023] * Fix excessive time spent checking DH q parameter value ([CVE-2023-3817]) * Fix DH_check() excessive time with over sized modulus ([CVE-2023-3446]) * Do not ignore empty associated data entries with AES-SIV ([CVE-2023-2975]) ### Major changes between OpenSSL 3.0.8 and OpenSSL 3.0.9 [30 May 2023] * Mitigate for very slow `OBJ_obj2txt()` performance with gigantic OBJECT IDENTIFIER sub-identities. ([CVE-2023-2650]) * Fixed buffer overread in AES-XTS decryption on ARM 64 bit platforms ([CVE-2023-1255]) * Fixed documentation of X509_VERIFY_PARAM_add0_policy() ([CVE-2023-0466]) * Fixed handling of invalid certificate policies in leaf certificates ([CVE-2023-0465]) * Limited the number of nodes created in a policy tree ([CVE-2023-0464]) ### Major changes between OpenSSL 3.0.7 and OpenSSL 3.0.8 [7 Feb 2023] * Fixed NULL dereference during PKCS7 data verification ([CVE-2023-0401]) * Fixed X.400 address type confusion in X.509 GeneralName ([CVE-2023-0286]) * Fixed NULL dereference validating DSA public key ([CVE-2023-0217]) * Fixed Invalid pointer dereference in d2i_PKCS7 functions ([CVE-2023-0216]) * Fixed Use-after-free following BIO_new_NDEF ([CVE-2023-0215]) * Fixed Double free after calling PEM_read_bio_ex ([CVE-2022-4450]) * Fixed Timing Oracle in RSA Decryption ([CVE-2022-4304]) * Fixed X.509 Name Constraints Read Buffer Overflow ([CVE-2022-4203]) * Fixed X.509 Policy Constraints Double Locking ([CVE-2022-3996]) ### Major changes between OpenSSL 3.0.6 and OpenSSL 3.0.7 [1 Nov 2022] * Added RIPEMD160 to the default provider. * Fixed regressions introduced in 3.0.6 version. * Fixed two buffer overflows in punycode decoding functions. ([CVE-2022-3786]) and ([CVE-2022-3602]) ### Major changes between OpenSSL 3.0.5 and OpenSSL 3.0.6 [11 Oct 2022] * Fix for custom ciphers to prevent accidental use of NULL encryption ([CVE-2022-3358]) ### Major changes between OpenSSL 3.0.4 and OpenSSL 3.0.5 [5 Jul 2022] * Fixed heap memory corruption with RSA private key operation ([CVE-2022-2274]) * Fixed AES OCB failure to encrypt some bytes on 32-bit x86 platforms ([CVE-2022-2097]) ### Major changes between OpenSSL 3.0.3 and OpenSSL 3.0.4 [21 Jun 2022] * Fixed additional bugs in the c_rehash script which was not properly sanitising shell metacharacters to prevent command injection ([CVE-2022-2068]) ### Major changes between OpenSSL 3.0.2 and OpenSSL 3.0.3 [3 May 2022] * Fixed a bug in the c_rehash script which was not properly sanitising shell metacharacters to prevent command injection ([CVE-2022-1292]) * Fixed a bug in the function `OCSP_basic_verify` that verifies the signer certificate on an OCSP response ([CVE-2022-1343]) * Fixed a bug where the RC4-MD5 ciphersuite incorrectly used the AAD data as the MAC key ([CVE-2022-1434]) * Fix a bug in the OPENSSL_LH_flush() function that breaks reuse of the memory occuppied by the removed hash table entries ([CVE-2022-1473]) ### Major changes between OpenSSL 3.0.1 and OpenSSL 3.0.2 [15 Mar 2022] * Fixed a bug in the BN_mod_sqrt() function that can cause it to loop forever for non-prime moduli ([CVE-2022-0778]) ### Major changes between OpenSSL 3.0.0 and OpenSSL 3.0.1 [14 Dec 2021] * Fixed invalid handling of X509_verify_cert() internal errors in libssl ([CVE-2021-4044]) * Allow fetching an operation from the provider that owns an unexportable key as a fallback if that is still allowed by the property query. ### Major changes between OpenSSL 1.1.1 and OpenSSL 3.0.0 [7 sep 2021] * Enhanced 'openssl list' with many new options. * Added migration guide to man7. * Implemented support for fully "pluggable" TLSv1.3 groups. * Added suport for Kernel TLS (KTLS). * Changed the license to the Apache License v2.0. * Moved all variations of the EVP ciphers CAST5, BF, IDEA, SEED, RC2, RC4, RC5, and DES to the legacy provider. * Moved the EVP digests MD2, MD4, MDC2, WHIRLPOOL and RIPEMD-160 to the legacy provider. * Added convenience functions for generating asymmetric key pairs. * Deprecated the `OCSP_REQ_CTX` type and functions. * Deprecated the `EC_KEY` and `EC_KEY_METHOD` types and functions. * Deprecated the `RSA` and `RSA_METHOD` types and functions. * Deprecated the `DSA` and `DSA_METHOD` types and functions. * Deprecated the `DH` and `DH_METHOD` types and functions. * Deprecated the `ERR_load_` functions. * Remove the `RAND_DRBG` API. * Deprecated the `ENGINE` API. * Added `OSSL_LIB_CTX`, a libcrypto library context. * Added various `_ex` functions to the OpenSSL API that support using a non-default `OSSL_LIB_CTX`. * Interactive mode is removed from the 'openssl' program. * The X25519, X448, Ed25519, Ed448, SHAKE128 and SHAKE256 algorithms are included in the FIPS provider. * X509 certificates signed using SHA1 are no longer allowed at security level 1 or higher. The default security level for TLS is 1, so certificates signed using SHA1 are by default no longer trusted to authenticate servers or clients. * enable-crypto-mdebug and enable-crypto-mdebug-backtrace were mostly disabled; the project uses address sanitize/leak-detect instead. * Added a Certificate Management Protocol (CMP, RFC 4210) implementation also covering CRMF (RFC 4211) and HTTP transfer (RFC 6712). It is part of the crypto lib and adds a 'cmp' app with a demo configuration. All widely used CMP features are supported for both clients and servers. * Added a proper HTTP client supporting GET with optional redirection, POST, arbitrary request and response content types, TLS, persistent connections, connections via HTTP(s) proxies, connections and exchange via user-defined BIOs (allowing implicit connections), and timeout checks. * Added util/check-format.pl for checking adherence to the coding guidelines. * Added OSSL_ENCODER, a generic encoder API. * Added OSSL_DECODER, a generic decoder API. * Added OSSL_PARAM_BLD, an easier to use API to OSSL_PARAM. * Added error raising macros, ERR_raise() and ERR_raise_data(). * Deprecated ERR_put_error(), ERR_get_error_line(), ERR_get_error_line_data(), ERR_peek_error_line_data(), ERR_peek_last_error_line_data() and ERR_func_error_string(). * Added OSSL_PROVIDER_available(), to check provider availibility. * Added 'openssl mac' that uses the EVP_MAC API. * Added 'openssl kdf' that uses the EVP_KDF API. * Add OPENSSL_info() and 'openssl info' to get built-in data. * Add support for enabling instrumentation through trace and debug output. * Changed our version number scheme and set the next major release to 3.0.0 * Added EVP_MAC, an EVP layer MAC API, and a generic EVP_PKEY to EVP_MAC bridge. Supported MACs are: BLAKE2, CMAC, GMAC, HMAC, KMAC, POLY1305 and SIPHASH. * Removed the heartbeat message in DTLS feature. * Added EVP_KDF, an EVP layer KDF and PRF API, and a generic EVP_PKEY to EVP_KDF bridge. Supported KDFs are: HKDF, KBKDF, KRB5 KDF, PBKDF2, PKCS12 KDF, SCRYPT, SSH KDF, SSKDF, TLS1 PRF, X9.42 KDF and X9.63 KDF. * All of the low-level MD2, MD4, MD5, MDC2, RIPEMD160, SHA1, SHA224, SHA256, SHA384, SHA512 and Whirlpool digest functions have been deprecated. * All of the low-level AES, Blowfish, Camellia, CAST, DES, IDEA, RC2, RC4, RC5 and SEED cipher functions have been deprecated. * All of the low-level DH, DSA, ECDH, ECDSA and RSA public key functions have been deprecated. * SSL 3, TLS 1.0, TLS 1.1, and DTLS 1.0 only work at security level 0, except when RSA key exchange without SHA1 is used. * Added providers, a new pluggability concept that will replace the ENGINE API and ENGINE implementations. OpenSSL 1.1.1 ------------- ### Major changes between OpenSSL 1.1.1k and OpenSSL 1.1.1l [24 Aug 2021] * Fixed an SM2 Decryption Buffer Overflow ([CVE-2021-3711]) * Fixed various read buffer overruns processing ASN.1 strings ([CVE-2021-3712]) ### Major changes between OpenSSL 1.1.1j and OpenSSL 1.1.1k [25 Mar 2021] * Fixed a problem with verifying a certificate chain when using the X509_V_FLAG_X509_STRICT flag ([CVE-2021-3450]) * Fixed an issue where an OpenSSL TLS server may crash if sent a maliciously crafted renegotiation ClientHello message from a client ([CVE-2021-3449]) ### Major changes between OpenSSL 1.1.1i and OpenSSL 1.1.1j [16 Feb 2021] * Fixed a NULL pointer deref in the X509_issuer_and_serial_hash() function ([CVE-2021-23841]) * Fixed the RSA_padding_check_SSLv23() function and the RSA_SSLV23_PADDING padding mode to correctly check for rollback attacks * Fixed an overflow in the EVP_CipherUpdate, EVP_EncryptUpdate and EVP_DecryptUpdate functions ([CVE-2021-23840]) * Fixed SRP_Calc_client_key so that it runs in constant time ### Major changes between OpenSSL 1.1.1h and OpenSSL 1.1.1i [8 Dec 2020] * Fixed NULL pointer deref in GENERAL_NAME_cmp ([CVE-2020-1971]) ### Major changes between OpenSSL 1.1.1g and OpenSSL 1.1.1h [22 Sep 2020] * Disallow explicit curve parameters in verifications chains when X509_V_FLAG_X509_STRICT is used * Enable 'MinProtocol' and 'MaxProtocol' to configure both TLS and DTLS contexts * Oracle Developer Studio will start reporting deprecation warnings ### Major changes between OpenSSL 1.1.1f and OpenSSL 1.1.1g [21 Apr 2020] * Fixed segmentation fault in SSL_check_chain() ([CVE-2020-1967]) ### Major changes between OpenSSL 1.1.1e and OpenSSL 1.1.1f [31 Mar 2020] * Revert the unexpected EOF reporting via SSL_ERROR_SSL ### Major changes between OpenSSL 1.1.1d and OpenSSL 1.1.1e [17 Mar 2020] * Fixed an overflow bug in the x64_64 Montgomery squaring procedure used in exponentiation with 512-bit moduli ([CVE-2019-1551]) ### Major changes between OpenSSL 1.1.1c and OpenSSL 1.1.1d [10 Sep 2019] * Fixed a fork protection issue ([CVE-2019-1549]) * Fixed a padding oracle in PKCS7_dataDecode and CMS_decrypt_set1_pkey ([CVE-2019-1563]) * For built-in EC curves, ensure an EC_GROUP built from the curve name is used even when parsing explicit parameters * Compute ECC cofactors if not provided during EC_GROUP construction ([CVE-2019-1547]) * Early start up entropy quality from the DEVRANDOM seed source has been improved for older Linux systems * Correct the extended master secret constant on EBCDIC systems * Use Windows installation paths in the mingw builds ([CVE-2019-1552]) * Changed DH_check to accept parameters with order q and 2q subgroups * Significantly reduce secure memory usage by the randomness pools * Revert the DEVRANDOM_WAIT feature for Linux systems ### Major changes between OpenSSL 1.1.1b and OpenSSL 1.1.1c [28 May 2019] * Prevent over long nonces in ChaCha20-Poly1305 ([CVE-2019-1543]) ### Major changes between OpenSSL 1.1.1a and OpenSSL 1.1.1b [26 Feb 2019] * Change the info callback signals for the start and end of a post-handshake message exchange in TLSv1.3. * Fix a bug in DTLS over SCTP. This breaks interoperability with older versions of OpenSSL like OpenSSL 1.1.0 and OpenSSL 1.0.2. ### Major changes between OpenSSL 1.1.1 and OpenSSL 1.1.1a [20 Nov 2018] * Timing vulnerability in DSA signature generation ([CVE-2018-0734]) * Timing vulnerability in ECDSA signature generation ([CVE-2018-0735]) ### Major changes between OpenSSL 1.1.0i and OpenSSL 1.1.1 [11 Sep 2018] * Support for TLSv1.3 added. The TLSv1.3 implementation includes: * Fully compliant implementation of RFC8446 (TLSv1.3) on by default * Early data (0-RTT) * Post-handshake authentication and key update * Middlebox Compatibility Mode * TLSv1.3 PSKs * Support for all five RFC8446 ciphersuites * RSA-PSS signature algorithms (backported to TLSv1.2) * Configurable session ticket support * Stateless server support * Rewrite of the packet construction code for "safer" packet handling * Rewrite of the extension handling code For further important information, see the [TLS1.3 page]( https://wiki.openssl.org/index.php/TLS1.3) in the OpenSSL Wiki. * Complete rewrite of the OpenSSL random number generator to introduce the following capabilities * The default RAND method now utilizes an AES-CTR DRBG according to NIST standard SP 800-90Ar1. * Support for multiple DRBG instances with seed chaining. * There is a public and private DRBG instance. * The DRBG instances are fork-safe. * Keep all global DRBG instances on the secure heap if it is enabled. * The public and private DRBG instance are per thread for lock free operation * Support for various new cryptographic algorithms including: * SHA3 * SHA512/224 and SHA512/256 * EdDSA (both Ed25519 and Ed448) including X509 and TLS support * X448 (adding to the existing X25519 support in 1.1.0) * Multi-prime RSA * SM2 * SM3 * SM4 * SipHash * ARIA (including TLS support) * Significant Side-Channel attack security improvements * Add a new ClientHello callback to provide the ability to adjust the SSL object at an early stage. * Add 'Maximum Fragment Length' TLS extension negotiation and support * A new STORE module, which implements a uniform and URI based reader of stores that can contain keys, certificates, CRLs and numerous other objects. * Move the display of configuration data to configdata.pm. * Allow GNU style "make variables" to be used with Configure. * Claim the namespaces OSSL and OPENSSL, represented as symbol prefixes * Rewrite of devcrypto engine OpenSSL 1.1.0 ------------- ### Major changes between OpenSSL 1.1.0k and OpenSSL 1.1.0l [10 Sep 2019] * Fixed a padding oracle in PKCS7_dataDecode and CMS_decrypt_set1_pkey ([CVE-2019-1563]) * For built-in EC curves, ensure an EC_GROUP built from the curve name is used even when parsing explicit parameters * Compute ECC cofactors if not provided during EC_GROUP construction ([CVE-2019-1547]) * Use Windows installation paths in the mingw builds ([CVE-2019-1552]) ### Major changes between OpenSSL 1.1.0j and OpenSSL 1.1.0k [28 May 2019] * Prevent over long nonces in ChaCha20-Poly1305 ([CVE-2019-1543]) ### Major changes between OpenSSL 1.1.0i and OpenSSL 1.1.0j [20 Nov 2018] * Timing vulnerability in DSA signature generation ([CVE-2018-0734]) * Timing vulnerability in ECDSA signature generation ([CVE-2018-0735]) ### Major changes between OpenSSL 1.1.0h and OpenSSL 1.1.0i [14 Aug 2018] * Client DoS due to large DH parameter ([CVE-2018-0732]) * Cache timing vulnerability in RSA Key Generation ([CVE-2018-0737]) ### Major changes between OpenSSL 1.1.0g and OpenSSL 1.1.0h [27 Mar 2018] * Constructed ASN.1 types with a recursive definition could exceed the stack ([CVE-2018-0739]) * Incorrect CRYPTO_memcmp on HP-UX PA-RISC ([CVE-2018-0733]) * rsaz_1024_mul_avx2 overflow bug on x86_64 ([CVE-2017-3738]) ### Major changes between OpenSSL 1.1.0f and OpenSSL 1.1.0g [2 Nov 2017] * bn_sqrx8x_internal carry bug on x86_64 ([CVE-2017-3736]) * Malformed X.509 IPAddressFamily could cause OOB read ([CVE-2017-3735]) ### Major changes between OpenSSL 1.1.0e and OpenSSL 1.1.0f [25 May 2017] * config now recognises 64-bit mingw and chooses mingw64 instead of mingw ### Major changes between OpenSSL 1.1.0d and OpenSSL 1.1.0e [16 Feb 2017] * Encrypt-Then-Mac renegotiation crash ([CVE-2017-3733]) ### Major changes between OpenSSL 1.1.0c and OpenSSL 1.1.0d [26 Jan 2017] * Truncated packet could crash via OOB read ([CVE-2017-3731]) * Bad (EC)DHE parameters cause a client crash ([CVE-2017-3730]) * BN_mod_exp may produce incorrect results on x86_64 ([CVE-2017-3732]) ### Major changes between OpenSSL 1.1.0b and OpenSSL 1.1.0c [10 Nov 2016] * ChaCha20/Poly1305 heap-buffer-overflow ([CVE-2016-7054]) * CMS Null dereference ([CVE-2016-7053]) * Montgomery multiplication may produce incorrect results ([CVE-2016-7055]) ### Major changes between OpenSSL 1.1.0a and OpenSSL 1.1.0b [26 Sep 2016] * Fix Use After Free for large message sizes ([CVE-2016-6309]) ### Major changes between OpenSSL 1.1.0 and OpenSSL 1.1.0a [22 Sep 2016] * OCSP Status Request extension unbounded memory growth ([CVE-2016-6304]) * SSL_peek() hang on empty record ([CVE-2016-6305]) * Excessive allocation of memory in tls_get_message_header() ([CVE-2016-6307]) * Excessive allocation of memory in dtls1_preprocess_fragment() ([CVE-2016-6308]) ### Major changes between OpenSSL 1.0.2h and OpenSSL 1.1.0 [25 Aug 2016] * Copyright text was shrunk to a boilerplate that points to the license * "shared" builds are now the default when possible * Added support for "pipelining" * Added the AFALG engine * New threading API implemented * Support for ChaCha20 and Poly1305 added to libcrypto and libssl * Support for extended master secret * CCM ciphersuites * Reworked test suite, now based on perl, Test::Harness and Test::More * *Most* libcrypto and libssl public structures were made opaque, including: BIGNUM and associated types, EC_KEY and EC_KEY_METHOD, DH and DH_METHOD, DSA and DSA_METHOD, RSA and RSA_METHOD, BIO and BIO_METHOD, EVP_MD_CTX, EVP_MD, EVP_CIPHER_CTX, EVP_CIPHER, EVP_PKEY and associated types, HMAC_CTX, X509, X509_CRL, X509_OBJECT, X509_STORE_CTX, X509_STORE, X509_LOOKUP, X509_LOOKUP_METHOD * libssl internal structures made opaque * SSLv2 support removed * Kerberos ciphersuite support removed * RC4 removed from DEFAULT ciphersuites in libssl * 40 and 56 bit cipher support removed from libssl * All public header files moved to include/openssl, no more symlinking * SSL/TLS state machine, version negotiation and record layer rewritten * EC revision: now operations use new EC_KEY_METHOD. * Support for OCB mode added to libcrypto * Support for asynchronous crypto operations added to libcrypto and libssl * Deprecated interfaces can now be disabled at build time either relative to the latest release via the "no-deprecated" Configure argument, or via the "--api=1.1.0|1.0.0|0.9.8" option. * Application software can be compiled with -DOPENSSL_API_COMPAT=version to ensure that features deprecated in that version are not exposed. * Support for RFC6698/RFC7671 DANE TLSA peer authentication * Change of Configure to use --prefix as the main installation directory location rather than --openssldir. The latter becomes the directory for certs, private key and openssl.cnf exclusively. * Reworked BIO networking library, with full support for IPv6. * New "unified" build system * New security levels * Support for scrypt algorithm * Support for X25519 * Extended SSL_CONF support using configuration files * KDF algorithm support. Implement TLS PRF as a KDF. * Support for Certificate Transparency * HKDF support. OpenSSL 1.0.2 ------------- ### Major changes between OpenSSL 1.0.2s and OpenSSL 1.0.2t [10 Sep 2019] * Fixed a padding oracle in PKCS7_dataDecode and CMS_decrypt_set1_pkey ([CVE-2019-1563]) * For built-in EC curves, ensure an EC_GROUP built from the curve name is used even when parsing explicit parameters * Compute ECC cofactors if not provided during EC_GROUP construction ([CVE-2019-1547]) * Document issue with installation paths in diverse Windows builds ([CVE-2019-1552]) ### Major changes between OpenSSL 1.0.2r and OpenSSL 1.0.2s [28 May 2019] * None ### Major changes between OpenSSL 1.0.2q and OpenSSL 1.0.2r [26 Feb 2019] * 0-byte record padding oracle ([CVE-2019-1559]) ### Major changes between OpenSSL 1.0.2p and OpenSSL 1.0.2q [20 Nov 2018] * Microarchitecture timing vulnerability in ECC scalar multiplication ([CVE-2018-5407]) * Timing vulnerability in DSA signature generation ([CVE-2018-0734]) ### Major changes between OpenSSL 1.0.2o and OpenSSL 1.0.2p [14 Aug 2018] * Client DoS due to large DH parameter ([CVE-2018-0732]) * Cache timing vulnerability in RSA Key Generation ([CVE-2018-0737]) ### Major changes between OpenSSL 1.0.2n and OpenSSL 1.0.2o [27 Mar 2018] * Constructed ASN.1 types with a recursive definition could exceed the stack ([CVE-2018-0739]) ### Major changes between OpenSSL 1.0.2m and OpenSSL 1.0.2n [7 Dec 2017] * Read/write after SSL object in error state ([CVE-2017-3737]) * rsaz_1024_mul_avx2 overflow bug on x86_64 ([CVE-2017-3738]) ### Major changes between OpenSSL 1.0.2l and OpenSSL 1.0.2m [2 Nov 2017] * bn_sqrx8x_internal carry bug on x86_64 ([CVE-2017-3736]) * 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] * 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] * Truncated packet could crash via OOB read ([CVE-2017-3731]) * BN_mod_exp may produce incorrect results on x86_64 ([CVE-2017-3732]) * Montgomery multiplication may produce incorrect results ([CVE-2016-7055]) ### Major changes between OpenSSL 1.0.2i and OpenSSL 1.0.2j [26 Sep 2016] * Missing CRL sanity check ([CVE-2016-7052]) ### Major changes between OpenSSL 1.0.2h and OpenSSL 1.0.2i [22 Sep 2016] * OCSP Status Request extension unbounded memory growth ([CVE-2016-6304]) * SWEET32 Mitigation ([CVE-2016-2183]) * OOB write in MDC2_Update() ([CVE-2016-6303]) * Malformed SHA512 ticket DoS ([CVE-2016-6302]) * OOB write in BN_bn2dec() ([CVE-2016-2182]) * OOB read in TS_OBJ_print_bio() ([CVE-2016-2180]) * Pointer arithmetic undefined behaviour ([CVE-2016-2177]) * Constant time flag not preserved in DSA signing ([CVE-2016-2178]) * DTLS buffered message DoS ([CVE-2016-2179]) * DTLS replay protection DoS ([CVE-2016-2181]) * Certificate message OOB reads ([CVE-2016-6306]) ### Major changes between OpenSSL 1.0.2g and OpenSSL 1.0.2h [3 May 2016] * Prevent padding oracle in AES-NI CBC MAC check ([CVE-2016-2107]) * Fix EVP_EncodeUpdate overflow ([CVE-2016-2105]) * Fix EVP_EncryptUpdate overflow ([CVE-2016-2106]) * Prevent ASN.1 BIO excessive memory allocation ([CVE-2016-2109]) * EBCDIC overread ([CVE-2016-2176]) * Modify behavior of ALPN to invoke callback after SNI/servername callback, such that updates to the SSL_CTX affect ALPN. * Remove LOW from the DEFAULT cipher list. This removes singles DES from the default. * 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] * Disable weak ciphers in SSLv3 and up in default builds of OpenSSL. * Disable SSLv2 default build, default negotiation and weak ciphers ([CVE-2016-0800]) * Fix a double-free in DSA code ([CVE-2016-0705]) * Disable SRP fake user seed to address a server memory leak ([CVE-2016-0798]) * Fix BN_hex2bn/BN_dec2bn NULL pointer deref/heap corruption ([CVE-2016-0797]) * Fix memory issues in BIO_*printf functions ([CVE-2016-0799]) * 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] * DH small subgroups ([CVE-2016-0701]) * SSLv2 doesn't block disabled ciphers ([CVE-2015-3197]) ### Major changes between OpenSSL 1.0.2d and OpenSSL 1.0.2e [3 Dec 2015] * BN_mod_exp may produce incorrect results on x86_64 ([CVE-2015-3193]) * Certificate verify crash with missing PSS parameter ([CVE-2015-3194]) * X509_ATTRIBUTE memory leak ([CVE-2015-3195]) * Rewrite EVP_DecodeUpdate (base64 decoding) to fix several bugs * 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] * Alternate chains certificate forgery ([CVE-2015-1793]) * Race condition handling PSK identify hint ([CVE-2015-3196]) ### Major changes between OpenSSL 1.0.2b and OpenSSL 1.0.2c [12 Jun 2015] * Fix HMAC ABI incompatibility ### Major changes between OpenSSL 1.0.2a and OpenSSL 1.0.2b [11 Jun 2015] * Malformed ECParameters causes infinite loop ([CVE-2015-1788]) * Exploitable out-of-bounds read in X509_cmp_time ([CVE-2015-1789]) * PKCS7 crash with missing EnvelopedContent ([CVE-2015-1790]) * CMS verify infinite loop with unknown hash function ([CVE-2015-1792]) * Race condition handling NewSessionTicket ([CVE-2015-1791]) ### Major changes between OpenSSL 1.0.2 and OpenSSL 1.0.2a [19 Mar 2015] * OpenSSL 1.0.2 ClientHello sigalgs DoS fix ([CVE-2015-0291]) * Multiblock corrupted pointer fix ([CVE-2015-0290]) * Segmentation fault in DTLSv1_listen fix ([CVE-2015-0207]) * Segmentation fault in ASN1_TYPE_cmp fix ([CVE-2015-0286]) * Segmentation fault for invalid PSS parameters fix ([CVE-2015-0208]) * ASN.1 structure reuse memory corruption fix ([CVE-2015-0287]) * PKCS7 NULL pointer dereferences fix ([CVE-2015-0289]) * DoS via reachable assert in SSLv2 servers fix ([CVE-2015-0293]) * Empty CKE with client auth and DHE fix ([CVE-2015-1787]) * Handshake with unseeded PRNG fix ([CVE-2015-0285]) * Use After Free following d2i_ECPrivatekey error fix ([CVE-2015-0209]) * X509_to_X509_REQ NULL pointer deref fix ([CVE-2015-0288]) * Removed the export ciphers from the DEFAULT ciphers ### Major changes between OpenSSL 1.0.1l and OpenSSL 1.0.2 [22 Jan 2015] * Suite B support for TLS 1.2 and DTLS 1.2 * Support for DTLS 1.2 * TLS automatic EC curve selection. * API to set TLS supported signature algorithms and curves * SSL_CONF configuration API. * TLS Brainpool support. * ALPN support. * CMS support for RSA-PSS, RSA-OAEP, ECDH and X9.42 DH. OpenSSL 1.0.1 ------------- ### Major changes between OpenSSL 1.0.1t and OpenSSL 1.0.1u [22 Sep 2016] * OCSP Status Request extension unbounded memory growth ([CVE-2016-6304]) * SWEET32 Mitigation ([CVE-2016-2183]) * OOB write in MDC2_Update() ([CVE-2016-6303]) * Malformed SHA512 ticket DoS ([CVE-2016-6302]) * OOB write in BN_bn2dec() ([CVE-2016-2182]) * OOB read in TS_OBJ_print_bio() ([CVE-2016-2180]) * Pointer arithmetic undefined behaviour ([CVE-2016-2177]) * Constant time flag not preserved in DSA signing ([CVE-2016-2178]) * DTLS buffered message DoS ([CVE-2016-2179]) * DTLS replay protection DoS ([CVE-2016-2181]) * Certificate message OOB reads ([CVE-2016-6306]) ### Major changes between OpenSSL 1.0.1s and OpenSSL 1.0.1t [3 May 2016] * Prevent padding oracle in AES-NI CBC MAC check ([CVE-2016-2107]) * Fix EVP_EncodeUpdate overflow ([CVE-2016-2105]) * Fix EVP_EncryptUpdate overflow ([CVE-2016-2106]) * Prevent ASN.1 BIO excessive memory allocation ([CVE-2016-2109]) * EBCDIC overread ([CVE-2016-2176]) * Modify behavior of ALPN to invoke callback after SNI/servername callback, such that updates to the SSL_CTX affect ALPN. * Remove LOW from the DEFAULT cipher list. This removes singles DES from the default. * Only remove the SSLv2 methods with the no-ssl2-method option. ### Major changes between OpenSSL 1.0.1r and OpenSSL 1.0.1s [1 Mar 2016] * Disable weak ciphers in SSLv3 and up in default builds of OpenSSL. * Disable SSLv2 default build, default negotiation and weak ciphers ([CVE-2016-0800]) * Fix a double-free in DSA code ([CVE-2016-0705]) * Disable SRP fake user seed to address a server memory leak ([CVE-2016-0798]) * Fix BN_hex2bn/BN_dec2bn NULL pointer deref/heap corruption ([CVE-2016-0797]) * Fix memory issues in BIO_*printf functions ([CVE-2016-0799]) * Fix side channel attack on modular exponentiation ([CVE-2016-0702]) ### Major changes between OpenSSL 1.0.1q and OpenSSL 1.0.1r [28 Jan 2016] * Protection for DH small subgroup attacks * SSLv2 doesn't block disabled ciphers ([CVE-2015-3197]) ### Major changes between OpenSSL 1.0.1p and OpenSSL 1.0.1q [3 Dec 2015] * Certificate verify crash with missing PSS parameter ([CVE-2015-3194]) * X509_ATTRIBUTE memory leak ([CVE-2015-3195]) * Rewrite EVP_DecodeUpdate (base64 decoding) to fix several bugs * In DSA_generate_parameters_ex, if the provided seed is too short, return an error ### Major changes between OpenSSL 1.0.1o and OpenSSL 1.0.1p [9 Jul 2015] * Alternate chains certificate forgery ([CVE-2015-1793]) * Race condition handling PSK identify hint ([CVE-2015-3196]) ### Major changes between OpenSSL 1.0.1n and OpenSSL 1.0.1o [12 Jun 2015] * Fix HMAC ABI incompatibility ### Major changes between OpenSSL 1.0.1m and OpenSSL 1.0.1n [11 Jun 2015] * Malformed ECParameters causes infinite loop ([CVE-2015-1788]) * Exploitable out-of-bounds read in X509_cmp_time ([CVE-2015-1789]) * PKCS7 crash with missing EnvelopedContent ([CVE-2015-1790]) * CMS verify infinite loop with unknown hash function ([CVE-2015-1792]) * Race condition handling NewSessionTicket ([CVE-2015-1791]) ### Major changes between OpenSSL 1.0.1l and OpenSSL 1.0.1m [19 Mar 2015] * Segmentation fault in ASN1_TYPE_cmp fix ([CVE-2015-0286]) * ASN.1 structure reuse memory corruption fix ([CVE-2015-0287]) * PKCS7 NULL pointer dereferences fix ([CVE-2015-0289]) * DoS via reachable assert in SSLv2 servers fix ([CVE-2015-0293]) * Use After Free following d2i_ECPrivatekey error fix ([CVE-2015-0209]) * X509_to_X509_REQ NULL pointer deref fix ([CVE-2015-0288]) * Removed the export ciphers from the DEFAULT ciphers ### Major changes between OpenSSL 1.0.1k and OpenSSL 1.0.1l [15 Jan 2015] * Build fixes for the Windows and OpenVMS platforms ### Major changes between OpenSSL 1.0.1j and OpenSSL 1.0.1k [8 Jan 2015] * Fix for [CVE-2014-3571] * Fix for [CVE-2015-0206] * Fix for [CVE-2014-3569] * Fix for [CVE-2014-3572] * Fix for [CVE-2015-0204] * Fix for [CVE-2015-0205] * Fix for [CVE-2014-8275] * Fix for [CVE-2014-3570] ### Major changes between OpenSSL 1.0.1i and OpenSSL 1.0.1j [15 Oct 2014] * Fix for [CVE-2014-3513] * Fix for [CVE-2014-3567] * Mitigation for [CVE-2014-3566] (SSL protocol vulnerability) * Fix for [CVE-2014-3568] ### Major changes between OpenSSL 1.0.1h and OpenSSL 1.0.1i [6 Aug 2014] * Fix for [CVE-2014-3512] * Fix for [CVE-2014-3511] * Fix for [CVE-2014-3510] * Fix for [CVE-2014-3507] * Fix for [CVE-2014-3506] * Fix for [CVE-2014-3505] * Fix for [CVE-2014-3509] * Fix for [CVE-2014-5139] * Fix for [CVE-2014-3508] ### Major changes between OpenSSL 1.0.1g and OpenSSL 1.0.1h [5 Jun 2014] * Fix for [CVE-2014-0224] * Fix for [CVE-2014-0221] * Fix for [CVE-2014-0198] * Fix for [CVE-2014-0195] * Fix for [CVE-2014-3470] * Fix for [CVE-2010-5298] ### Major changes between OpenSSL 1.0.1f and OpenSSL 1.0.1g [7 Apr 2014] * Fix for [CVE-2014-0160] * Add TLS padding extension workaround for broken servers. * Fix for [CVE-2014-0076] ### Major changes between OpenSSL 1.0.1e and OpenSSL 1.0.1f [6 Jan 2014] * Don't include gmt_unix_time in TLS server and client random values * Fix for TLS record tampering bug ([CVE-2013-4353]) * Fix for TLS version checking bug ([CVE-2013-6449]) * Fix for DTLS retransmission bug ([CVE-2013-6450]) ### Major changes between OpenSSL 1.0.1d and OpenSSL 1.0.1e [11 Feb 2013] * Corrected fix for ([CVE-2013-0169]) ### Major changes between OpenSSL 1.0.1c and OpenSSL 1.0.1d [4 Feb 2013] * Fix renegotiation in TLS 1.1, 1.2 by using the correct TLS version. * Include the fips configuration module. * Fix OCSP bad key DoS attack ([CVE-2013-0166]) * Fix for SSL/TLS/DTLS CBC plaintext recovery attack ([CVE-2013-0169]) * 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] * Fix TLS/DTLS record length checking bug ([CVE-2012-2333]) * 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] * Fix compilation error on non-x86 platforms. * Make FIPS capable OpenSSL ciphers work in non-FIPS mode. * 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] * Fix for ASN1 overflow bug ([CVE-2012-2110]) * Workarounds for some servers that hang on long client hellos. * Fix SEGV in AES code. ### Major changes between OpenSSL 1.0.0h and OpenSSL 1.0.1 [14 Mar 2012] * TLS/DTLS heartbeat support. * SCTP support. * RFC 5705 TLS key material exporter. * RFC 5764 DTLS-SRTP negotiation. * Next Protocol Negotiation. * PSS signatures in certificates, requests and CRLs. * Support for password based recipient info for CMS. * Support TLS v1.2 and TLS v1.1. * Preliminary FIPS capability for unvalidated 2.0 FIPS module. * SRP support. OpenSSL 1.0.0 ------------- ### Major changes between OpenSSL 1.0.0s and OpenSSL 1.0.0t [3 Dec 2015] * X509_ATTRIBUTE memory leak (([CVE-2015-3195])) * Race condition handling PSK identify hint ([CVE-2015-3196]) ### Major changes between OpenSSL 1.0.0r and OpenSSL 1.0.0s [11 Jun 2015] * Malformed ECParameters causes infinite loop ([CVE-2015-1788]) * Exploitable out-of-bounds read in X509_cmp_time ([CVE-2015-1789]) * PKCS7 crash with missing EnvelopedContent ([CVE-2015-1790]) * CMS verify infinite loop with unknown hash function ([CVE-2015-1792]) * Race condition handling NewSessionTicket ([CVE-2015-1791]) ### Major changes between OpenSSL 1.0.0q and OpenSSL 1.0.0r [19 Mar 2015] * Segmentation fault in ASN1_TYPE_cmp fix ([CVE-2015-0286]) * ASN.1 structure reuse memory corruption fix ([CVE-2015-0287]) * PKCS7 NULL pointer dereferences fix ([CVE-2015-0289]) * DoS via reachable assert in SSLv2 servers fix ([CVE-2015-0293]) * Use After Free following d2i_ECPrivatekey error fix ([CVE-2015-0209]) * X509_to_X509_REQ NULL pointer deref fix ([CVE-2015-0288]) * Removed the export ciphers from the DEFAULT ciphers ### Major changes between OpenSSL 1.0.0p and OpenSSL 1.0.0q [15 Jan 2015] * Build fixes for the Windows and OpenVMS platforms ### Major changes between OpenSSL 1.0.0o and OpenSSL 1.0.0p [8 Jan 2015] * Fix for [CVE-2014-3571] * Fix for [CVE-2015-0206] * Fix for [CVE-2014-3569] * Fix for [CVE-2014-3572] * Fix for [CVE-2015-0204] * Fix for [CVE-2015-0205] * Fix for [CVE-2014-8275] * Fix for [CVE-2014-3570] ### Major changes between OpenSSL 1.0.0n and OpenSSL 1.0.0o [15 Oct 2014] * Fix for [CVE-2014-3513] * Fix for [CVE-2014-3567] * Mitigation for [CVE-2014-3566] (SSL protocol vulnerability) * Fix for [CVE-2014-3568] ### Major changes between OpenSSL 1.0.0m and OpenSSL 1.0.0n [6 Aug 2014] * Fix for [CVE-2014-3510] * Fix for [CVE-2014-3507] * Fix for [CVE-2014-3506] * Fix for [CVE-2014-3505] * Fix for [CVE-2014-3509] * Fix for [CVE-2014-3508] Known issues in OpenSSL 1.0.0m: * EAP-FAST and other applications using tls_session_secret_cb won't resume sessions. Fixed in 1.0.0n-dev * Compilation failure of s3_pkt.c on some platforms due to missing `` include. Fixed in 1.0.0n-dev ### Major changes between OpenSSL 1.0.0l and OpenSSL 1.0.0m [5 Jun 2014] * Fix for [CVE-2014-0224] * Fix for [CVE-2014-0221] * Fix for [CVE-2014-0198] * Fix for [CVE-2014-0195] * Fix for [CVE-2014-3470] * Fix for [CVE-2014-0076] * Fix for [CVE-2010-5298] ### Major changes between OpenSSL 1.0.0k and OpenSSL 1.0.0l [6 Jan 2014] * Fix for DTLS retransmission bug ([CVE-2013-6450]) ### Major changes between OpenSSL 1.0.0j and OpenSSL 1.0.0k [5 Feb 2013] * Fix for SSL/TLS/DTLS CBC plaintext recovery attack ([CVE-2013-0169]) * Fix OCSP bad key DoS attack ([CVE-2013-0166]) ### Major changes between OpenSSL 1.0.0i and OpenSSL 1.0.0j [10 May 2012] * Fix DTLS record length checking bug ([CVE-2012-2333]) ### Major changes between OpenSSL 1.0.0h and OpenSSL 1.0.0i [19 Apr 2012] * Fix for ASN1 overflow bug ([CVE-2012-2110]) ### Major changes between OpenSSL 1.0.0g and OpenSSL 1.0.0h [12 Mar 2012] * Fix for CMS/PKCS#7 MMA ([CVE-2012-0884]) * Corrected fix for ([CVE-2011-4619]) * Various DTLS fixes. ### Major changes between OpenSSL 1.0.0f and OpenSSL 1.0.0g [18 Jan 2012] * Fix for DTLS DoS issue ([CVE-2012-0050]) ### Major changes between OpenSSL 1.0.0e and OpenSSL 1.0.0f [4 Jan 2012] * Fix for DTLS plaintext recovery attack ([CVE-2011-4108]) * Clear block padding bytes of SSL 3.0 records ([CVE-2011-4576]) * Only allow one SGC handshake restart for SSL/TLS ([CVE-2011-4619]) * Check parameters are not NULL in GOST ENGINE ([CVE-2012-0027]) * Check for malformed RFC3779 data ([CVE-2011-4577]) ### Major changes between OpenSSL 1.0.0d and OpenSSL 1.0.0e [6 Sep 2011] * Fix for CRL vulnerability issue ([CVE-2011-3207]) * Fix for ECDH crashes ([CVE-2011-3210]) * Protection against EC timing attacks. * Support ECDH ciphersuites for certificates using SHA2 algorithms. * Various DTLS fixes. ### Major changes between OpenSSL 1.0.0c and OpenSSL 1.0.0d [8 Feb 2011] * Fix for security issue ([CVE-2011-0014]) ### Major changes between OpenSSL 1.0.0b and OpenSSL 1.0.0c [2 Dec 2010] * Fix for security issue ([CVE-2010-4180]) * Fix for ([CVE-2010-4252]) * Fix mishandling of absent EC point format extension. * Fix various platform compilation issues. * Corrected fix for security issue ([CVE-2010-3864]). ### Major changes between OpenSSL 1.0.0a and OpenSSL 1.0.0b [16 Nov 2010] * Fix for security issue ([CVE-2010-3864]). * Fix for ([CVE-2010-2939]) * Fix WIN32 build system for GOST ENGINE. ### Major changes between OpenSSL 1.0.0 and OpenSSL 1.0.0a [1 Jun 2010] * Fix for security issue ([CVE-2010-1633]). * GOST MAC and CFB fixes. ### Major changes between OpenSSL 0.9.8n and OpenSSL 1.0.0 [29 Mar 2010] * RFC3280 path validation: sufficient to process PKITS tests. * Integrated support for PVK files and keyblobs. * Change default private key format to PKCS#8. * CMS support: able to process all examples in RFC4134 * Streaming ASN1 encode support for PKCS#7 and CMS. * Multiple signer and signer add support for PKCS#7 and CMS. * ASN1 printing support. * Whirlpool hash algorithm added. * RFC3161 time stamp support. * New generalised public key API supporting ENGINE based algorithms. * New generalised public key API utilities. * New ENGINE supporting GOST algorithms. * SSL/TLS GOST ciphersuite support. * PKCS#7 and CMS GOST support. * RFC4279 PSK ciphersuite support. * Supported points format extension for ECC ciphersuites. * ecdsa-with-SHA224/256/384/512 signature types. * dsa-with-SHA224 and dsa-with-SHA256 signature types. * Opaque PRF Input TLS extension support. * Updated time routines to avoid OS limitations. OpenSSL 0.9.x ------------- ### Major changes between OpenSSL 0.9.8m and OpenSSL 0.9.8n [24 Mar 2010] * CFB cipher definition fixes. * 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] * Cipher definition fixes. * Workaround for slow RAND_poll() on some WIN32 versions. * Remove MD2 from algorithm tables. * SPKAC handling fixes. * Support for RFC5746 TLS renegotiation extension. * Compression memory leak fixed. * Compression session resumption fixed. * Ticket and SNI coexistence fixes. * Many fixes to DTLS handling. ### Major changes between OpenSSL 0.9.8k and OpenSSL 0.9.8l [5 Nov 2009] * Temporary work around for [CVE-2009-3555]: disable renegotiation. ### Major changes between OpenSSL 0.9.8j and OpenSSL 0.9.8k [25 Mar 2009] * Fix various build issues. * 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] * Fix security issue ([CVE-2008-5077]) * Merge FIPS 140-2 branch code. ### Major changes between OpenSSL 0.9.8g and OpenSSL 0.9.8h [28 May 2008] * CryptoAPI ENGINE support. * Various precautionary measures. * Fix for bugs affecting certificate request creation. * 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] * Backport of CMS functionality to 0.9.8. * Fixes for bugs introduced with 0.9.8f. ### Major changes between OpenSSL 0.9.8e and OpenSSL 0.9.8f [11 Oct 2007] * Add gcc 4.2 support. * Add support for AES and SSE2 assembly language optimization for VC++ build. * Support for RFC4507bis and server name extensions if explicitly selected at compile time. * DTLS improvements. * RFC4507bis support. * TLS Extensions support. ### Major changes between OpenSSL 0.9.8d and OpenSSL 0.9.8e [23 Feb 2007] * Various ciphersuite selection fixes. * RFC3779 support. ### Major changes between OpenSSL 0.9.8c and OpenSSL 0.9.8d [28 Sep 2006] * Introduce limits to prevent malicious key DoS ([CVE-2006-2940]) * Fix security issues [CVE-2006-2937], [CVE-2006-3737], [CVE-2006-4343] * Changes to ciphersuite selection algorithm ### Major changes between OpenSSL 0.9.8b and OpenSSL 0.9.8c [5 Sep 2006] * Fix Daniel Bleichenbacher forged signature attack, [CVE-2006-4339] * New cipher Camellia ### Major changes between OpenSSL 0.9.8a and OpenSSL 0.9.8b [4 May 2006] * Cipher string fixes. * Fixes for VC++ 2005. * Updated ECC cipher suite support. * New functions EVP_CIPHER_CTX_new() and EVP_CIPHER_CTX_free(). * Zlib compression usage fixes. * Built in dynamic engine compilation support on Win32. * Fixes auto dynamic engine loading in Win32. ### Major changes between OpenSSL 0.9.8 and OpenSSL 0.9.8a [11 Oct 2005] * Fix potential SSL 2.0 rollback ([CVE-2005-2969]) * Extended Windows CE support ### Major changes between OpenSSL 0.9.7g and OpenSSL 0.9.8 [5 Jul 2005] * 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. * Addition of BIGNUM functions for fields GF(2^m) and NIST curves, to support the Elliptic Crypto functions. * Major work on Elliptic Crypto; ECDH and ECDSA added, including the use through EVP, X509 and ENGINE. * New ASN.1 mini-compiler that's usable through the OpenSSL configuration file. * Added support for ASN.1 indefinite length constructed encoding. * New PKCS#12 'medium level' API to manipulate PKCS#12 files. * Complete rework of shared library construction and linking programs with shared or static libraries, through a separate Makefile.shared. * Rework of the passing of parameters from one Makefile to another. * Changed ENGINE framework to load dynamic engine modules automatically from specifically given directories. * New structure and ASN.1 functions for CertificatePair. * Changed the ZLIB compression method to be stateful. * Changed the key-generation and primality testing "progress" mechanism to take a structure that contains the ticker function and an argument. * New engine module: GMP (performs private key exponentiation). * New engine module: VIA PadLOck ACE extension in VIA C3 Nehemiah processors. * Added support for IPv6 addresses in certificate extensions. See RFC 1884, section 2.2. * Added support for certificate policy mappings, policy constraints and name constraints. * Added support for multi-valued AVAs in the OpenSSL configuration file. * Added support for multiple certificates with the same subject in the 'openssl ca' index file. * Make it possible to create self-signed certificates using 'openssl ca -selfsign'. * Make it possible to generate a serial number file with 'openssl ca -create_serial'. * New binary search functions with extended functionality. * New BUF functions. * 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 within OpenSSL. * New control functions for the error stack. * Changed the PKCS#7 library to support one-pass S/MIME processing. * 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. * Constification of all ASN.1 conversion functions, and other affected functions. * Improved platform support for PowerPC. * New FIPS 180-2 algorithms (SHA-224, -256, -384 and -512). * New X509_VERIFY_PARAM structure to support parameterisation of X.509 path validation. * Major overhaul of RC4 performance on Intel P4, IA-64 and AMD64. * Changed the Configure script to have some algorithms disabled by default. Those can be explicitly enabled with the new argument form 'enable-xxx'. * Change the default digest in 'openssl' commands from MD5 to SHA-1. * Added support for DTLS. * New BIGNUM blinding. * Added support for the RSA-PSS encryption scheme * Added support for the RSA X.931 padding. * Added support for BSD sockets on NetWare. * Added support for files larger than 2GB. * Added initial support for Win64. * Added alternate pkg-config files. ### Major changes between OpenSSL 0.9.7l and OpenSSL 0.9.7m [23 Feb 2007] * FIPS 1.1.1 module linking. * Various ciphersuite selection fixes. ### Major changes between OpenSSL 0.9.7k and OpenSSL 0.9.7l [28 Sep 2006] * Introduce limits to prevent malicious key DoS ([CVE-2006-2940]) * 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] * Fix Daniel Bleichenbacher forged signature attack, [CVE-2006-4339] ### Major changes between OpenSSL 0.9.7i and OpenSSL 0.9.7j [4 May 2006] * Visual C++ 2005 fixes. * Update Windows build system for FIPS. ### Major changes between OpenSSL 0.9.7h and OpenSSL 0.9.7i [14 Oct 2005] * Give EVP_MAX_MD_SIZE its old value, except for a FIPS build. ### Major changes between OpenSSL 0.9.7g and OpenSSL 0.9.7h [11 Oct 2005] * Fix SSL 2.0 Rollback ([CVE-2005-2969]) * Allow use of fixed-length exponent on DSA signing * Default fixed-window RSA, DSA, DH private-key operations ### Major changes between OpenSSL 0.9.7f and OpenSSL 0.9.7g [11 Apr 2005] * More compilation issues fixed. * Adaptation to more modern Kerberos API. * Enhanced or corrected configuration for Solaris64, Mingw and Cygwin. * Enhanced x86_64 assembler BIGNUM module. * More constification. * Added processing of proxy certificates (RFC 3820). ### Major changes between OpenSSL 0.9.7e and OpenSSL 0.9.7f [22 Mar 2005] * Several compilation issues fixed. * Many memory allocation failure checks added. * Improved comparison of X509 Name type. * Mandatory basic checks on certificates. * Performance improvements. ### Major changes between OpenSSL 0.9.7d and OpenSSL 0.9.7e [25 Oct 2004] * Fix race condition in CRL checking code. * Fixes to PKCS#7 (S/MIME) code. ### Major changes between OpenSSL 0.9.7c and OpenSSL 0.9.7d [17 Mar 2004] * Security: Fix Kerberos ciphersuite SSL/TLS handshaking bug * Security: Fix null-pointer assignment in do_change_cipher_spec() * Allow multiple active certificates with same subject in CA index * Multiple X509 verification fixes * Speed up HMAC and other operations ### Major changes between OpenSSL 0.9.7b and OpenSSL 0.9.7c [30 Sep 2003] * Security: fix various ASN1 parsing bugs. * New -ignore_err option to OCSP utility. * Various interop and bug fixes in S/MIME code. * SSL/TLS protocol fix for unrequested client certificates. ### Major changes between OpenSSL 0.9.7a and OpenSSL 0.9.7b [10 Apr 2003] * Security: counter the Klima-Pokorny-Rosa extension of Bleichbacher's attack * Security: make RSA blinding default. * Configuration: Irix fixes, AIX fixes, better mingw support. * Support for new platforms: linux-ia64-ecc. * Build: shared library support fixes. * ASN.1: treat domainComponent correctly. * Documentation: fixes and additions. ### Major changes between OpenSSL 0.9.7 and OpenSSL 0.9.7a [19 Feb 2003] * Security: Important security related bugfixes. * Enhanced compatibility with MIT Kerberos. * Can be built without the ENGINE framework. * IA32 assembler enhancements. * Support for new platforms: FreeBSD/IA64 and FreeBSD/Sparc64. * Configuration: the no-err option now works properly. * SSL/TLS: now handles manual certificate chain building. * SSL/TLS: certain session ID malfunctions corrected. ### Major changes between OpenSSL 0.9.6 and OpenSSL 0.9.7 [30 Dec 2002] * New library section OCSP. * Complete rewrite of ASN1 code. * CRL checking in verify code and openssl utility. * Extension copying in 'ca' utility. * Flexible display options in 'ca' utility. * Provisional support for international characters with UTF8. * Support for external crypto devices ('engine') is no longer a separate distribution. * New elliptic curve library section. * New AES (Rijndael) library section. * Support for new platforms: Windows CE, Tandem OSS, A/UX, AIX 64-bit, Linux x86_64, Linux 64-bit on Sparc v9 * Extended support for some platforms: VxWorks * Enhanced support for shared libraries. * Now only builds PIC code when shared library support is requested. * Support for pkg-config. * Lots of new manuals. * Makes symbolic links to or copies of manuals to cover all described functions. * 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). * Unify handling of cryptographic algorithms (software and engine) to be available via EVP routines for asymmetric and symmetric ciphers. * NCONF: new configuration handling routines. * Change API to use more 'const' modifiers to improve error checking and help optimizers. * Finally remove references to RSAref. * Reworked parts of the BIGNUM code. * Support for new engines: Broadcom ubsec, Accelerated Encryption Processing, IBM 4758. * A few new engines added in the demos area. * Extended and corrected OID (object identifier) table. * PRNG: query at more locations for a random device, automatic query for EGD style random sources at several locations. * SSL/TLS: allow optional cipher choice according to server's preference. * SSL/TLS: allow server to explicitly set new session ids. * SSL/TLS: support Kerberos cipher suites (RFC2712). Only supports MIT Kerberos for now. * SSL/TLS: allow more precise control of renegotiations and sessions. * SSL/TLS: add callback to retrieve SSL/TLS messages. * SSL/TLS: support AES cipher suites (RFC3268). ### Major changes between OpenSSL 0.9.6j and OpenSSL 0.9.6k [30 Sep 2003] * Security: fix various ASN1 parsing bugs. * SSL/TLS protocol fix for unrequested client certificates. ### Major changes between OpenSSL 0.9.6i and OpenSSL 0.9.6j [10 Apr 2003] * Security: counter the Klima-Pokorny-Rosa extension of Bleichbacher's attack * Security: make RSA blinding default. * Build: shared library support fixes. ### Major changes between OpenSSL 0.9.6h and OpenSSL 0.9.6i [19 Feb 2003] * Important security related bugfixes. ### Major changes between OpenSSL 0.9.6g and OpenSSL 0.9.6h [5 Dec 2002] * New configuration targets for Tandem OSS and A/UX. * New OIDs for Microsoft attributes. * Better handling of SSL session caching. * Better comparison of distinguished names. * Better handling of shared libraries in a mixed GNU/non-GNU environment. * Support assembler code with Borland C. * Fixes for length problems. * Fixes for uninitialised variables. * Fixes for memory leaks, some unusual crashes and some race conditions. * Fixes for smaller building problems. * Updates of manuals, FAQ and other instructive documents. ### Major changes between OpenSSL 0.9.6f and OpenSSL 0.9.6g [9 Aug 2002] * Important building fixes on Unix. ### Major changes between OpenSSL 0.9.6e and OpenSSL 0.9.6f [8 Aug 2002] * Various important bugfixes. ### Major changes between OpenSSL 0.9.6d and OpenSSL 0.9.6e [30 Jul 2002] * Important security related bugfixes. * Various SSL/TLS library bugfixes. ### Major changes between OpenSSL 0.9.6c and OpenSSL 0.9.6d [9 May 2002] * Various SSL/TLS library bugfixes. * Fix DH parameter generation for 'non-standard' generators. ### Major changes between OpenSSL 0.9.6b and OpenSSL 0.9.6c [21 Dec 2001] * Various SSL/TLS library bugfixes. * BIGNUM library fixes. * RSA OAEP and random number generation fixes. * Object identifiers corrected and added. * Add assembler BN routines for IA64. * Add support for OS/390 Unix, UnixWare with gcc, OpenUNIX 8, MIPS Linux; shared library support for Irix, HP-UX. * 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] * Security fix: PRNG improvements. * Security fix: RSA OAEP check. * Security fix: Reinsert and fix countermeasure to Bleichbacher's attack. * MIPS bug fix in BIGNUM. * Bug fix in "openssl enc". * Bug fix in X.509 printing routine. * Bug fix in DSA verification routine and DSA S/MIME verification. * Bug fix to make PRNG thread-safe. * Bug fix in RAND_file_name(). * Bug fix in compatibility mode trust settings. * Bug fix in blowfish EVP. * Increase default size for BIO buffering filter. * Compatibility fixes in some scripts. ### Major changes between OpenSSL 0.9.6 and OpenSSL 0.9.6a [5 Apr 2001] * Security fix: change behavior of OpenSSL to avoid using environment variables when running as root. * Security fix: check the result of RSA-CRT to reduce the possibility of deducing the private key from an incorrectly calculated signature. * Security fix: prevent Bleichenbacher's DSA attack. * Security fix: Zero the premaster secret after deriving the master secret in DH ciphersuites. * Reimplement SSL_peek(), which had various problems. * Compatibility fix: the function des_encrypt() renamed to des_encrypt1() to avoid clashes with some Unixen libc. * Bug fixes for Win32, HP/UX and Irix. * Bug fixes in BIGNUM, SSL, PKCS#7, PKCS#12, X.509, CONF and memory checking routines. * Bug fixes for RSA operations in threaded environments. * Bug fixes in misc. openssl applications. * Remove a few potential memory leaks. * Add tighter checks of BIGNUM routines. * Shared library support has been reworked for generality. * More documentation. * New function BN_rand_range(). * 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] * Some documentation for BIO and SSL libraries. * Enhanced chain verification using key identifiers. * New sign and verify options to 'dgst' application. * Support for DER and PEM encoded messages in 'smime' application. * New 'rsautl' application, low-level RSA utility. * MD4 now included. * Bugfix for SSL rollback padding check. * Support for external crypto devices [1]. * Enhanced EVP interface. [1] The support for external crypto devices is currently a separate distribution. See the file README-Engine.md. ### Major changes between OpenSSL 0.9.5 and OpenSSL 0.9.5a [1 Apr 2000] * Bug fixes for Win32, SuSE Linux, NeXTSTEP and FreeBSD 2.2.8 * Shared library support for HPUX and Solaris-gcc * Support of Linux/IA64 * Assembler support for Mingw32 * New 'rand' application * 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] * S/MIME support in new 'smime' command * Documentation for the OpenSSL command line application * Automation of 'req' application * Fixes to make s_client, s_server work under Windows * Support for multiple fieldnames in SPKACs * New SPKAC command line utility and associated library functions * Options to allow passwords to be obtained from various sources * New public key PEM format and options to handle it * Many other fixes and enhancements to command line utilities * Usable certificate chain verification * Certificate purpose checking * Certificate trust settings * Support of authority information access extension * Extensions in certificate requests * Simplified X509 name and attribute routines * Initial (incomplete) support for international character sets * New DH_METHOD, DSA_METHOD and enhanced RSA_METHOD * Read only memory BIOs and simplified creation function * TLS/SSL protocol bugfixes: Accept TLS 'client hello' in SSL 3.0 record; allow fragmentation and interleaving of handshake and other data * TLS/SSL code now "tolerates" MS SGC * Work around for Netscape client certificate hang bug * RSA_NULL option that removes RSA patent code but keeps other RSA functionality * Memory leak detection now allows applications to add extra information via a per-thread stack * PRNG robustness improved * EGD support * BIGNUM library bug fixes * Faster DSA parameter generation * Enhanced support for Alpha Linux * Experimental macOS support ### Major changes between OpenSSL 0.9.3 and OpenSSL 0.9.4 [9 Aug 1999] * Transparent support for PKCS#8 format private keys: these are used by several software packages and are more secure than the standard form * PKCS#5 v2.0 implementation * Password callbacks have a new void * argument for application data * Avoid various memory leaks * 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] * Lots of enhancements and cleanups to the Configuration mechanism * RSA OEAP related fixes * Added "openssl ca -revoke" option for revoking a certificate * Source cleanups: const correctness, type-safe stacks and ASN.1 SETs * Source tree cleanups: removed lots of obsolete files * Thawte SXNet, certificate policies and CRL distribution points extension support * Preliminary (experimental) S/MIME support * Support for ASN.1 UTF8String and VisibleString * Full integration of PKCS#12 code * Sparc assembler bignum implementation, optimized hash functions * Option to disable selected ciphers ### Major changes between OpenSSL 0.9.1c and OpenSSL 0.9.2b [22 Mar 1999] * Fixed a security hole related to session resumption * Fixed RSA encryption routines for the p < q case * "ALL" in cipher lists now means "everything except NULL ciphers" * Support for Triple-DES CBCM cipher * Support of Optimal Asymmetric Encryption Padding (OAEP) for RSA * First support for new TLSv1 ciphers * Added a few new BIOs (syslog BIO, reliable BIO) * Extended support for DSA certificate/keys. * Extended support for Certificate Signing Requests (CSR) * Initial support for X.509v3 extensions * Extended support for compression inside the SSL record layer * Overhauled Win32 builds * Cleanups and fixes to the Big Number (BN) library * Support for ASN.1 GeneralizedTime * Splitted ASN.1 SETs from SEQUENCEs * ASN1 and PEM support for Netscape Certificate Sequences * Overhauled Perl interface * Lots of source tree cleanups. * Lots of memory leak fixes. * Lots of bug fixes. ### Major changes between SSLeay 0.9.0b and OpenSSL 0.9.1c [23 Dec 1998] * Integration of the popular NO_RSA/NO_DSA patches * Initial support for compression inside the SSL record layer * Added BIO proxy and filtering functionality * Extended Big Number (BN) library * Added RIPE MD160 message digest * Added support for RC2/64bit cipher * Extended ASN.1 parser routines * Adjustments of the source tree for CVS * Support for various new platforms +[CVE-2023-4807]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-4807 [CVE-2023-3817]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-3817 [CVE-2023-3446]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-3446 [CVE-2023-2975]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-2975 [CVE-2023-2650]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-2650 [CVE-2023-1255]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-1255 [CVE-2023-0466]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0466 [CVE-2023-0465]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0465 [CVE-2023-0464]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0464 [CVE-2023-0401]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0401 [CVE-2023-0286]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0286 [CVE-2023-0217]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0217 [CVE-2023-0216]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0216 [CVE-2023-0215]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-0215 [CVE-2022-4450]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-4450 [CVE-2022-4304]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-4304 [CVE-2022-4203]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-4203 [CVE-2022-3996]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-3996 [CVE-2022-2274]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-2274 [CVE-2022-2097]: https://www.openssl.org/news/vulnerabilities.html#CVE-2022-2097 [CVE-2020-1971]: https://www.openssl.org/news/vulnerabilities.html#CVE-2020-1971 [CVE-2020-1967]: https://www.openssl.org/news/vulnerabilities.html#CVE-2020-1967 [CVE-2019-1563]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1563 [CVE-2019-1559]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1559 [CVE-2019-1552]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1552 [CVE-2019-1551]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1551 [CVE-2019-1549]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1549 [CVE-2019-1547]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1547 [CVE-2019-1543]: https://www.openssl.org/news/vulnerabilities.html#CVE-2019-1543 [CVE-2018-5407]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-5407 [CVE-2018-0739]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0739 [CVE-2018-0737]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0737 [CVE-2018-0735]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0735 [CVE-2018-0734]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0734 [CVE-2018-0733]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0733 [CVE-2018-0732]: https://www.openssl.org/news/vulnerabilities.html#CVE-2018-0732 [CVE-2017-3738]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3738 [CVE-2017-3737]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3737 [CVE-2017-3736]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3736 [CVE-2017-3735]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3735 [CVE-2017-3733]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3733 [CVE-2017-3732]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3732 [CVE-2017-3731]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3731 [CVE-2017-3730]: https://www.openssl.org/news/vulnerabilities.html#CVE-2017-3730 [CVE-2016-7055]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-7055 [CVE-2016-7054]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-7054 [CVE-2016-7053]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-7053 [CVE-2016-7052]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-7052 [CVE-2016-6309]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6309 [CVE-2016-6308]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6308 [CVE-2016-6307]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6307 [CVE-2016-6306]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6306 [CVE-2016-6305]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6305 [CVE-2016-6304]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6304 [CVE-2016-6303]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6303 [CVE-2016-6302]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-6302 [CVE-2016-2183]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2183 [CVE-2016-2182]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2182 [CVE-2016-2181]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2181 [CVE-2016-2180]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2180 [CVE-2016-2179]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2179 [CVE-2016-2178]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2178 [CVE-2016-2177]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2177 [CVE-2016-2176]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2176 [CVE-2016-2109]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2109 [CVE-2016-2107]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2107 [CVE-2016-2106]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2106 [CVE-2016-2105]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-2105 [CVE-2016-0800]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0800 [CVE-2016-0799]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0799 [CVE-2016-0798]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0798 [CVE-2016-0797]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0797 [CVE-2016-0705]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0705 [CVE-2016-0702]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0702 [CVE-2016-0701]: https://www.openssl.org/news/vulnerabilities.html#CVE-2016-0701 [CVE-2015-3197]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-3197 [CVE-2015-3196]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-3196 [CVE-2015-3195]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-3195 [CVE-2015-3194]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-3194 [CVE-2015-3193]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-3193 [CVE-2015-1793]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1793 [CVE-2015-1792]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1792 [CVE-2015-1791]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1791 [CVE-2015-1790]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1790 [CVE-2015-1789]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1789 [CVE-2015-1788]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1788 [CVE-2015-1787]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-1787 [CVE-2015-0293]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0293 [CVE-2015-0291]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0291 [CVE-2015-0290]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0290 [CVE-2015-0289]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0289 [CVE-2015-0288]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0288 [CVE-2015-0287]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0287 [CVE-2015-0286]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0286 [CVE-2015-0285]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0285 [CVE-2015-0209]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0209 [CVE-2015-0208]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0208 [CVE-2015-0207]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0207 [CVE-2015-0206]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0206 [CVE-2015-0205]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0205 [CVE-2015-0204]: https://www.openssl.org/news/vulnerabilities.html#CVE-2015-0204 [CVE-2014-8275]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-8275 [CVE-2014-5139]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-5139 [CVE-2014-3572]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3572 [CVE-2014-3571]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3571 [CVE-2014-3570]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3570 [CVE-2014-3569]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3569 [CVE-2014-3568]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3568 [CVE-2014-3567]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3567 [CVE-2014-3566]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3566 [CVE-2014-3513]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3513 [CVE-2014-3512]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3512 [CVE-2014-3511]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3511 [CVE-2014-3510]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3510 [CVE-2014-3509]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3509 [CVE-2014-3508]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3508 [CVE-2014-3507]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3507 [CVE-2014-3506]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3506 [CVE-2014-3505]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3505 [CVE-2014-3470]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-3470 [CVE-2014-0224]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-0224 [CVE-2014-0221]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-0221 [CVE-2014-0198]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-0198 [CVE-2014-0195]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-0195 [CVE-2014-0160]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-0160 [CVE-2014-0076]: https://www.openssl.org/news/vulnerabilities.html#CVE-2014-0076 [CVE-2013-6450]: https://www.openssl.org/news/vulnerabilities.html#CVE-2013-6450 [CVE-2013-6449]: https://www.openssl.org/news/vulnerabilities.html#CVE-2013-6449 [CVE-2013-4353]: https://www.openssl.org/news/vulnerabilities.html#CVE-2013-4353 [CVE-2013-0169]: https://www.openssl.org/news/vulnerabilities.html#CVE-2013-0169 [CVE-2013-0166]: https://www.openssl.org/news/vulnerabilities.html#CVE-2013-0166 [CVE-2012-2686]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-2686 [CVE-2012-2333]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-2333 [CVE-2012-2110]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-2110 [CVE-2012-0884]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-0884 [CVE-2012-0050]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-0050 [CVE-2012-0027]: https://www.openssl.org/news/vulnerabilities.html#CVE-2012-0027 [CVE-2011-4619]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-4619 [CVE-2011-4577]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-4577 [CVE-2011-4576]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-4576 [CVE-2011-4108]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-4108 [CVE-2011-3210]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-3210 [CVE-2011-3207]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-3207 [CVE-2011-0014]: https://www.openssl.org/news/vulnerabilities.html#CVE-2011-0014 [CVE-2010-5298]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-5298 [CVE-2010-4252]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-4252 [CVE-2010-4180]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-4180 [CVE-2010-3864]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-3864 [CVE-2010-2939]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-2939 [CVE-2010-1633]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-1633 [CVE-2010-0740]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-0740 [CVE-2010-0433]: https://www.openssl.org/news/vulnerabilities.html#CVE-2010-0433 [CVE-2009-3555]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-3555 [CVE-2009-0789]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-0789 [CVE-2009-0591]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-0591 [CVE-2009-0590]: https://www.openssl.org/news/vulnerabilities.html#CVE-2009-0590 [CVE-2008-5077]: https://www.openssl.org/news/vulnerabilities.html#CVE-2008-5077 [CVE-2006-4343]: https://www.openssl.org/news/vulnerabilities.html#CVE-2006-4343 [CVE-2006-4339]: https://www.openssl.org/news/vulnerabilities.html#CVE-2006-4339 [CVE-2006-3737]: https://www.openssl.org/news/vulnerabilities.html#CVE-2006-3737 [CVE-2006-2940]: https://www.openssl.org/news/vulnerabilities.html#CVE-2006-2940 [CVE-2006-2937]: https://www.openssl.org/news/vulnerabilities.html#CVE-2006-2937 [CVE-2005-2969]: https://www.openssl.org/news/vulnerabilities.html#CVE-2005-2969 diff --git a/README.md b/README.md index f2f4fd39ad05..b848d050132a 100644 --- a/README.md +++ b/README.md @@ -1,224 +1,224 @@ Welcome to the OpenSSL Project ============================== [![openssl logo]][www.openssl.org] [![github actions ci badge]][github actions ci] [![appveyor badge]][appveyor jobs] OpenSSL is a robust, commercial-grade, full-featured Open Source Toolkit for the Transport Layer Security (TLS) protocol formerly known as the Secure Sockets Layer (SSL) protocol. The protocol implementation is based on a full-strength general purpose cryptographic library, which can also be used stand-alone. OpenSSL is descended from the SSLeay library developed by Eric A. Young and Tim J. Hudson. The official Home Page of the OpenSSL Project is [www.openssl.org]. Table of Contents ================= - [Overview](#overview) - [Download](#download) - [Build and Install](#build-and-install) - [Documentation](#documentation) - [License](#license) - [Support](#support) - [Contributing](#contributing) - [Legalities](#legalities) Overview ======== The OpenSSL toolkit includes: - **libssl** an implementation of all TLS protocol versions up to TLSv1.3 ([RFC 8446]). - **libcrypto** a full-strength general purpose cryptographic library. It constitutes the basis of the TLS implementation, but can also be used independently. - **openssl** the OpenSSL command line tool, a swiss army knife for cryptographic tasks, testing and analyzing. It 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... Download ======== For Production Use ------------------ Source code tarballs of the official releases can be downloaded from [www.openssl.org/source](https://www.openssl.org/source). The OpenSSL project does not distribute the toolkit in binary form. However, for a large variety of operating systems precompiled versions of the OpenSSL toolkit are available. In particular on Linux and other Unix operating systems it is normally recommended to link against the precompiled shared libraries provided by the distributor or vendor. For Testing and Development --------------------------- Although testing and development could in theory also be done using the source tarballs, having a local copy of the git repository with the entire project history gives you much more insight into the code base. The official OpenSSL Git Repository is located at [git.openssl.org]. There is a GitHub mirror of the repository at [github.com/openssl/openssl], which is updated automatically from the former on every commit. A local copy of the Git Repository can be obtained by cloning it from the original OpenSSL repository using git clone git://git.openssl.org/openssl.git or from the GitHub mirror using git clone https://github.com/openssl/openssl.git If you intend to contribute to OpenSSL, either to fix bugs or contribute new features, you need to fork the OpenSSL repository openssl/openssl on GitHub and clone your public fork instead. git clone https://github.com/yourname/openssl.git This is necessary, because all development of OpenSSL nowadays is done via GitHub pull requests. For more details, see [Contributing](#contributing). Build and Install ================= After obtaining the Source, have a look at the [INSTALL](INSTALL.md) file for detailed instructions about building and installing OpenSSL. For some platforms, the installation instructions are amended by a platform specific document. * [Notes for UNIX-like platforms](NOTES-UNIX.md) * [Notes for Android platforms](NOTES-ANDROID.md) * [Notes for Windows platforms](NOTES-WINDOWS.md) * [Notes for the DOS platform with DJGPP](NOTES-DJGPP.md) * [Notes for the OpenVMS platform](NOTES-VMS.md) * [Notes on Perl](NOTES-PERL.md) * [Notes on Valgrind](NOTES-VALGRIND.md) Specific notes on upgrading to OpenSSL 3.0 from previous versions can be found in the [migration_guide(7ossl)] manual page. Documentation ============= Manual Pages ------------ The manual pages for the master branch and all current stable releases are available online. - [OpenSSL master](https://www.openssl.org/docs/manmaster) - [OpenSSL 3.0](https://www.openssl.org/docs/man3.0) - [OpenSSL 1.1.1](https://www.openssl.org/docs/man1.1.1) Wiki ---- There is a Wiki at [wiki.openssl.org] which is currently not very active. It contains a lot of useful information, not all of which is up to date. License ======= OpenSSL is licensed under the Apache License 2.0, which means that you are free to get and use it for commercial and non-commercial purposes as long as you fulfill its conditions. See the [LICENSE.txt](LICENSE.txt) file for more details. Support ======= There are various ways to get in touch. The correct channel depends on your requirement. see the [SUPPORT](SUPPORT.md) file for more details. Contributing ============ If you are interested and willing to contribute to the OpenSSL project, please take a look at the [CONTRIBUTING](CONTRIBUTING.md) file. Legalities ========== A number of nations restrict the use or export of cryptography. If you are potentially subject to such restrictions you should seek legal advice before attempting to develop or distribute cryptographic code. Copyright ========= -Copyright (c) 1998-2022 The OpenSSL Project +Copyright (c) 1998-2023 The OpenSSL Project Copyright (c) 1995-1998 Eric A. Young, Tim J. Hudson All rights reserved. [www.openssl.org]: "OpenSSL Homepage" [git.openssl.org]: "OpenSSL Git Repository" [git.openssl.org]: "OpenSSL Git Repository" [github.com/openssl/openssl]: "OpenSSL GitHub Mirror" [wiki.openssl.org]: "OpenSSL Wiki" [migration_guide(7ossl)]: "OpenSSL Migration Guide" [RFC 8446]: [openssl logo]: doc/images/openssl.svg "OpenSSL Logo" [github actions ci badge]: "GitHub Actions CI Status" [github actions ci]: "GitHub Actions CI" [appveyor badge]: "AppVeyor Build Status" [appveyor jobs]: "AppVeyor Jobs" diff --git a/VERSION.dat b/VERSION.dat index 34658d316b4c..c4157a86274d 100644 --- a/VERSION.dat +++ b/VERSION.dat @@ -1,7 +1,7 @@ MAJOR=3 MINOR=0 -PATCH=10 +PATCH=11 PRE_RELEASE_TAG= BUILD_METADATA= -RELEASE_DATE="1 Aug 2023" +RELEASE_DATE="19 Sep 2023" SHLIB_VERSION=3 diff --git a/apps/cmp.c b/apps/cmp.c index a317fdb0bf3e..c479b1549660 100644 --- a/apps/cmp.c +++ b/apps/cmp.c @@ -1,3084 +1,3084 @@ /* * Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* This app is disabled when OPENSSL_NO_CMP is defined. */ #include #include #include "apps.h" #include "http_server.h" #include "s_apps.h" #include "progs.h" #include "cmp_mock_srv.h" /* tweaks needed due to missing unistd.h on Windows */ #if defined(_WIN32) && !defined(__BORLANDC__) # define access _access #endif #ifndef F_OK # define F_OK 0 #endif #include #include #include /* explicit #includes not strictly needed since implied by the above: */ #include #include #include #include #include #include #include #include #include static char *prog; static char *opt_config = NULL; #define CMP_SECTION "cmp" #define SECTION_NAME_MAX 40 /* max length of section name */ #define DEFAULT_SECTION "default" static char *opt_section = CMP_SECTION; static int opt_verbosity = OSSL_CMP_LOG_INFO; static int read_config(void); static CONF *conf = NULL; /* OpenSSL config file context structure */ static OSSL_CMP_CTX *cmp_ctx = NULL; /* the client-side CMP context */ /* the type of cmp command we want to send */ typedef enum { CMP_IR, CMP_KUR, CMP_CR, CMP_P10CR, CMP_RR, CMP_GENM } cmp_cmd_t; /* message transfer */ #ifndef OPENSSL_NO_SOCK static char *opt_server = NULL; static char *opt_proxy = NULL; static char *opt_no_proxy = NULL; #endif static char *opt_recipient = NULL; static char *opt_path = NULL; static int opt_keep_alive = 1; static int opt_msg_timeout = -1; static int opt_total_timeout = -1; /* server authentication */ static char *opt_trusted = NULL; static char *opt_untrusted = NULL; static char *opt_srvcert = NULL; static char *opt_expect_sender = NULL; static int opt_ignore_keyusage = 0; static int opt_unprotected_errors = 0; static char *opt_extracertsout = NULL; static char *opt_cacertsout = NULL; /* client authentication */ static char *opt_ref = NULL; static char *opt_secret = NULL; static char *opt_cert = NULL; static char *opt_own_trusted = NULL; static char *opt_key = NULL; static char *opt_keypass = NULL; static char *opt_digest = NULL; static char *opt_mac = NULL; static char *opt_extracerts = NULL; static int opt_unprotected_requests = 0; /* generic message */ static char *opt_cmd_s = NULL; static int opt_cmd = -1; static char *opt_geninfo = NULL; static char *opt_infotype_s = NULL; static int opt_infotype = NID_undef; /* certificate enrollment */ static char *opt_newkey = NULL; static char *opt_newkeypass = NULL; static char *opt_subject = NULL; static char *opt_issuer = NULL; static int opt_days = 0; static char *opt_reqexts = NULL; static char *opt_sans = NULL; static int opt_san_nodefault = 0; static char *opt_policies = NULL; static char *opt_policy_oids = NULL; static int opt_policy_oids_critical = 0; static int opt_popo = OSSL_CRMF_POPO_NONE - 1; static char *opt_csr = NULL; static char *opt_out_trusted = NULL; static int opt_implicit_confirm = 0; static int opt_disable_confirm = 0; static char *opt_certout = NULL; static char *opt_chainout = NULL; /* certificate enrollment and revocation */ static char *opt_oldcert = NULL; static int opt_revreason = CRL_REASON_NONE; /* credentials format */ static char *opt_certform_s = "PEM"; static int opt_certform = FORMAT_PEM; static char *opt_keyform_s = NULL; static int opt_keyform = FORMAT_UNDEF; static char *opt_otherpass = NULL; static char *opt_engine = NULL; #ifndef OPENSSL_NO_SOCK /* TLS connection */ static int opt_tls_used = 0; static char *opt_tls_cert = NULL; static char *opt_tls_key = NULL; static char *opt_tls_keypass = NULL; static char *opt_tls_extra = NULL; static char *opt_tls_trusted = NULL; static char *opt_tls_host = NULL; #endif /* client-side debugging */ static int opt_batch = 0; static int opt_repeat = 1; static char *opt_reqin = NULL; static int opt_reqin_new_tid = 0; static char *opt_reqout = NULL; static char *opt_rspin = NULL; static int rspin_in_use = 0; static char *opt_rspout = NULL; static int opt_use_mock_srv = 0; /* mock server */ #ifndef OPENSSL_NO_SOCK static char *opt_port = NULL; static int opt_max_msgs = 0; #endif static char *opt_srv_ref = NULL; static char *opt_srv_secret = NULL; static char *opt_srv_cert = NULL; static char *opt_srv_key = NULL; static char *opt_srv_keypass = NULL; static char *opt_srv_trusted = NULL; static char *opt_srv_untrusted = NULL; static char *opt_rsp_cert = NULL; static char *opt_rsp_extracerts = NULL; static char *opt_rsp_capubs = NULL; static int opt_poll_count = 0; static int opt_check_after = 1; static int opt_grant_implicitconf = 0; static int opt_pkistatus = OSSL_CMP_PKISTATUS_accepted; static int opt_failure = INT_MIN; static int opt_failurebits = 0; static char *opt_statusstring = NULL; static int opt_send_error = 0; static int opt_send_unprotected = 0; static int opt_send_unprot_err = 0; static int opt_accept_unprotected = 0; static int opt_accept_unprot_err = 0; static int opt_accept_raverified = 0; static X509_VERIFY_PARAM *vpm = NULL; typedef enum OPTION_choice { OPT_COMMON, OPT_CONFIG, OPT_SECTION, OPT_VERBOSITY, OPT_CMD, OPT_INFOTYPE, OPT_GENINFO, OPT_NEWKEY, OPT_NEWKEYPASS, OPT_SUBJECT, OPT_ISSUER, OPT_DAYS, OPT_REQEXTS, OPT_SANS, OPT_SAN_NODEFAULT, OPT_POLICIES, OPT_POLICY_OIDS, OPT_POLICY_OIDS_CRITICAL, OPT_POPO, OPT_CSR, OPT_OUT_TRUSTED, OPT_IMPLICIT_CONFIRM, OPT_DISABLE_CONFIRM, OPT_CERTOUT, OPT_CHAINOUT, OPT_OLDCERT, OPT_REVREASON, #ifndef OPENSSL_NO_SOCK OPT_SERVER, OPT_PROXY, OPT_NO_PROXY, #endif OPT_RECIPIENT, OPT_PATH, OPT_KEEP_ALIVE, OPT_MSG_TIMEOUT, OPT_TOTAL_TIMEOUT, OPT_TRUSTED, OPT_UNTRUSTED, OPT_SRVCERT, OPT_EXPECT_SENDER, OPT_IGNORE_KEYUSAGE, OPT_UNPROTECTED_ERRORS, OPT_EXTRACERTSOUT, OPT_CACERTSOUT, OPT_REF, OPT_SECRET, OPT_CERT, OPT_OWN_TRUSTED, OPT_KEY, OPT_KEYPASS, OPT_DIGEST, OPT_MAC, OPT_EXTRACERTS, OPT_UNPROTECTED_REQUESTS, OPT_CERTFORM, OPT_KEYFORM, OPT_OTHERPASS, #ifndef OPENSSL_NO_ENGINE OPT_ENGINE, #endif OPT_PROV_ENUM, OPT_R_ENUM, #ifndef OPENSSL_NO_SOCK OPT_TLS_USED, OPT_TLS_CERT, OPT_TLS_KEY, OPT_TLS_KEYPASS, OPT_TLS_EXTRA, OPT_TLS_TRUSTED, OPT_TLS_HOST, #endif OPT_BATCH, OPT_REPEAT, OPT_REQIN, OPT_REQIN_NEW_TID, OPT_REQOUT, OPT_RSPIN, OPT_RSPOUT, OPT_USE_MOCK_SRV, #ifndef OPENSSL_NO_SOCK OPT_PORT, OPT_MAX_MSGS, #endif OPT_SRV_REF, OPT_SRV_SECRET, OPT_SRV_CERT, OPT_SRV_KEY, OPT_SRV_KEYPASS, OPT_SRV_TRUSTED, OPT_SRV_UNTRUSTED, OPT_RSP_CERT, OPT_RSP_EXTRACERTS, OPT_RSP_CAPUBS, OPT_POLL_COUNT, OPT_CHECK_AFTER, OPT_GRANT_IMPLICITCONF, OPT_PKISTATUS, OPT_FAILURE, OPT_FAILUREBITS, OPT_STATUSSTRING, OPT_SEND_ERROR, OPT_SEND_UNPROTECTED, OPT_SEND_UNPROT_ERR, OPT_ACCEPT_UNPROTECTED, OPT_ACCEPT_UNPROT_ERR, OPT_ACCEPT_RAVERIFIED, OPT_V_ENUM } OPTION_CHOICE; const OPTIONS cmp_options[] = { /* entries must be in the same order as enumerated above!! */ {"help", OPT_HELP, '-', "Display this summary"}, {"config", OPT_CONFIG, 's', "Configuration file to use. \"\" = none. Default from env variable OPENSSL_CONF"}, {"section", OPT_SECTION, 's', "Section(s) in config file to get options from. \"\" = 'default'. Default 'cmp'"}, {"verbosity", OPT_VERBOSITY, 'N', "Log level; 3=ERR, 4=WARN, 6=INFO, 7=DEBUG, 8=TRACE. Default 6 = INFO"}, OPT_SECTION("Generic message"), {"cmd", OPT_CMD, 's', "CMP request to send: ir/cr/kur/p10cr/rr/genm"}, {"infotype", OPT_INFOTYPE, 's', "InfoType name for requesting specific info in genm, e.g. 'signKeyPairTypes'"}, {"geninfo", OPT_GENINFO, 's', "generalInfo integer values to place in request PKIHeader with given OID"}, {OPT_MORE_STR, 0, 0, "specified in the form :int:, e.g. \"1.2.3.4:int:56789\""}, OPT_SECTION("Certificate enrollment"), {"newkey", OPT_NEWKEY, 's', "Private or public key for the requested cert. Default: CSR key or client key"}, {"newkeypass", OPT_NEWKEYPASS, 's', "New private key pass phrase source"}, {"subject", OPT_SUBJECT, 's', "Distinguished Name (DN) of subject to use in the requested cert template"}, {OPT_MORE_STR, 0, 0, "For kur, default is subject of -csr arg or reference cert (see -oldcert)"}, {OPT_MORE_STR, 0, 0, "this default is used for ir and cr only if no Subject Alt Names are set"}, {"issuer", OPT_ISSUER, 's', "DN of the issuer to place in the requested certificate template"}, {OPT_MORE_STR, 0, 0, "also used as recipient if neither -recipient nor -srvcert are given"}, {"days", OPT_DAYS, 'N', "Requested validity time of the new certificate in number of days"}, {"reqexts", OPT_REQEXTS, 's', "Name of config file section defining certificate request extensions."}, {OPT_MORE_STR, 0, 0, "Augments or replaces any extensions contained CSR given with -csr"}, {"sans", OPT_SANS, 's', "Subject Alt Names (IPADDR/DNS/URI) to add as (critical) cert req extension"}, {"san_nodefault", OPT_SAN_NODEFAULT, '-', "Do not take default SANs from reference certificate (see -oldcert)"}, {"policies", OPT_POLICIES, 's', "Name of config file section defining policies certificate request extension"}, {"policy_oids", OPT_POLICY_OIDS, 's', "Policy OID(s) to add as policies certificate request extension"}, {"policy_oids_critical", OPT_POLICY_OIDS_CRITICAL, '-', "Flag the policy OID(s) given with -policy_oids as critical"}, {"popo", OPT_POPO, 'n', "Proof-of-Possession (POPO) method to use for ir/cr/kur where"}, {OPT_MORE_STR, 0, 0, "-1 = NONE, 0 = RAVERIFIED, 1 = SIGNATURE (default), 2 = KEYENC"}, {"csr", OPT_CSR, 's', "PKCS#10 CSR file in PEM or DER format to convert or to use in p10cr"}, {"out_trusted", OPT_OUT_TRUSTED, 's', "Certificates to trust when verifying newly enrolled certificates"}, {"implicit_confirm", OPT_IMPLICIT_CONFIRM, '-', "Request implicit confirmation of newly enrolled certificates"}, {"disable_confirm", OPT_DISABLE_CONFIRM, '-', "Do not confirm newly enrolled certificate w/o requesting implicit"}, {OPT_MORE_STR, 0, 0, "confirmation. WARNING: This leads to behavior violating RFC 4210"}, {"certout", OPT_CERTOUT, 's', "File to save newly enrolled certificate"}, {"chainout", OPT_CHAINOUT, 's', "File to save the chain of newly enrolled certificate"}, OPT_SECTION("Certificate enrollment and revocation"), {"oldcert", OPT_OLDCERT, 's', "Certificate to be updated (defaulting to -cert) or to be revoked in rr;"}, {OPT_MORE_STR, 0, 0, "also used as reference (defaulting to -cert) for subject DN and SANs."}, {OPT_MORE_STR, 0, 0, "Issuer is used as recipient unless -recipient, -srvcert, or -issuer given"}, {"revreason", OPT_REVREASON, 'n', "Reason code to include in revocation request (rr); possible values:"}, {OPT_MORE_STR, 0, 0, "0..6, 8..10 (see RFC5280, 5.3.1) or -1. Default -1 = none included"}, OPT_SECTION("Message transfer"), #ifdef OPENSSL_NO_SOCK {OPT_MORE_STR, 0, 0, "NOTE: -server, -proxy, and -no_proxy not supported due to no-sock build"}, #else {"server", OPT_SERVER, 's', "[http[s]://]address[:port][/path] of CMP server. Default port 80 or 443."}, {OPT_MORE_STR, 0, 0, "address may be a DNS name or an IP address; path can be overridden by -path"}, {"proxy", OPT_PROXY, 's', "[http[s]://]address[:port][/path] of HTTP(S) proxy to use; path is ignored"}, {"no_proxy", OPT_NO_PROXY, 's', "List of addresses of servers not to use HTTP(S) proxy for"}, {OPT_MORE_STR, 0, 0, "Default from environment variable 'no_proxy', else 'NO_PROXY', else none"}, #endif {"recipient", OPT_RECIPIENT, 's', "DN of CA. Default: subject of -srvcert, -issuer, issuer of -oldcert or -cert"}, {"path", OPT_PATH, 's', "HTTP path (aka CMP alias) at the CMP server. Default from -server, else \"/\""}, {"keep_alive", OPT_KEEP_ALIVE, 'N', "Persistent HTTP connections. 0: no, 1 (the default): request, 2: require"}, {"msg_timeout", OPT_MSG_TIMEOUT, 'N', "Number of seconds allowed per CMP message round trip, or 0 for infinite"}, {"total_timeout", OPT_TOTAL_TIMEOUT, 'N', "Overall time an enrollment incl. polling may take. Default 0 = infinite"}, OPT_SECTION("Server authentication"), {"trusted", OPT_TRUSTED, 's', "Certificates to use as trust anchors when verifying signed CMP responses"}, {OPT_MORE_STR, 0, 0, "unless -srvcert is given"}, {"untrusted", OPT_UNTRUSTED, 's', "Intermediate CA certs for chain construction for CMP/TLS/enrolled certs"}, {"srvcert", OPT_SRVCERT, 's', "Server cert to pin and trust directly when verifying signed CMP responses"}, {"expect_sender", OPT_EXPECT_SENDER, 's', "DN of expected sender of responses. Defaults to subject of -srvcert, if any"}, {"ignore_keyusage", OPT_IGNORE_KEYUSAGE, '-', "Ignore CMP signer cert key usage, else 'digitalSignature' must be allowed"}, {"unprotected_errors", OPT_UNPROTECTED_ERRORS, '-', "Accept missing or invalid protection of regular error messages and negative"}, {OPT_MORE_STR, 0, 0, "certificate responses (ip/cp/kup), revocation responses (rp), and PKIConf"}, {OPT_MORE_STR, 0, 0, "WARNING: This setting leads to behavior allowing violation of RFC 4210"}, {"extracertsout", OPT_EXTRACERTSOUT, 's', "File to save extra certificates received in the extraCerts field"}, {"cacertsout", OPT_CACERTSOUT, 's', "File to save CA certificates received in the caPubs field of 'ip' messages"}, OPT_SECTION("Client authentication"), {"ref", OPT_REF, 's', "Reference value to use as senderKID in case no -cert is given"}, {"secret", OPT_SECRET, 's', "Prefer PBM (over signatures) for protecting msgs with given password source"}, {"cert", OPT_CERT, 's', "Client's CMP signer certificate; its public key must match the -key argument"}, {OPT_MORE_STR, 0, 0, "This also used as default reference for subject DN and SANs."}, {OPT_MORE_STR, 0, 0, "Any further certs included are appended to the untrusted certs"}, {"own_trusted", OPT_OWN_TRUSTED, 's', "Optional certs to verify chain building for own CMP signer cert"}, {"key", OPT_KEY, 's', "CMP signer private key, not used when -secret given"}, {"keypass", OPT_KEYPASS, 's', "Client private key (and cert and old cert) pass phrase source"}, {"digest", OPT_DIGEST, 's', "Digest to use in message protection and POPO signatures. Default \"sha256\""}, {"mac", OPT_MAC, 's', "MAC algorithm to use in PBM-based message protection. Default \"hmac-sha1\""}, {"extracerts", OPT_EXTRACERTS, 's', "Certificates to append in extraCerts field of outgoing messages."}, {OPT_MORE_STR, 0, 0, "This can be used as the default CMP signer cert chain to include"}, {"unprotected_requests", OPT_UNPROTECTED_REQUESTS, '-', "Send request messages without CMP-level protection"}, OPT_SECTION("Credentials format"), {"certform", OPT_CERTFORM, 's', "Format (PEM or DER) to use when saving a certificate to a file. Default PEM"}, {"keyform", OPT_KEYFORM, 's', "Format of the key input (ENGINE, other values ignored)"}, {"otherpass", OPT_OTHERPASS, 's', "Pass phrase source potentially needed for loading certificates of others"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use crypto engine with given identifier, possibly a hardware device."}, {OPT_MORE_STR, 0, 0, "Engines may also be defined in OpenSSL config file engine section."}, #endif OPT_PROV_OPTIONS, OPT_R_OPTIONS, OPT_SECTION("TLS connection"), #ifdef OPENSSL_NO_SOCK {OPT_MORE_STR, 0, 0, "NOTE: -tls_used and all other TLS options not supported due to no-sock build"}, #else {"tls_used", OPT_TLS_USED, '-', "Enable using TLS (also when other TLS options are not set)"}, {"tls_cert", OPT_TLS_CERT, 's', "Client's TLS certificate. May include chain to be provided to TLS server"}, {"tls_key", OPT_TLS_KEY, 's', "Private key for the client's TLS certificate"}, {"tls_keypass", OPT_TLS_KEYPASS, 's', "Pass phrase source for the client's private TLS key (and TLS cert)"}, {"tls_extra", OPT_TLS_EXTRA, 's', "Extra certificates to provide to TLS server during TLS handshake"}, {"tls_trusted", OPT_TLS_TRUSTED, 's', "Trusted certificates to use for verifying the TLS server certificate;"}, {OPT_MORE_STR, 0, 0, "this implies host name validation"}, {"tls_host", OPT_TLS_HOST, 's', "Address to be checked (rather than -server) during TLS host name validation"}, #endif OPT_SECTION("Client-side debugging"), {"batch", OPT_BATCH, '-', "Do not interactively prompt for input when a password is required etc."}, {"repeat", OPT_REPEAT, 'p', "Invoke the transaction the given positive number of times. Default 1"}, {"reqin", OPT_REQIN, 's', "Take sequence of CMP requests to send to server from file(s)"}, {"reqin_new_tid", OPT_REQIN_NEW_TID, '-', "Use fresh transactionID for CMP requests read from -reqin"}, {"reqout", OPT_REQOUT, 's', "Save sequence of CMP requests created by the client to file(s)"}, {"rspin", OPT_RSPIN, 's', "Process sequence of CMP responses provided in file(s), skipping server"}, {"rspout", OPT_RSPOUT, 's', "Save sequence of actually used CMP responses to file(s)"}, {"use_mock_srv", OPT_USE_MOCK_SRV, '-', "Use internal mock server at API level, bypassing socket-based HTTP"}, OPT_SECTION("Mock server"), #ifdef OPENSSL_NO_SOCK {OPT_MORE_STR, 0, 0, "NOTE: -port and -max_msgs not supported due to no-sock build"}, #else {"port", OPT_PORT, 's', "Act as HTTP-based mock server listening on given port"}, {"max_msgs", OPT_MAX_MSGS, 'N', "max number of messages handled by HTTP mock server. Default: 0 = unlimited"}, #endif {"srv_ref", OPT_SRV_REF, 's', "Reference value to use as senderKID of server in case no -srv_cert is given"}, {"srv_secret", OPT_SRV_SECRET, 's', "Password source for server authentication with a pre-shared key (secret)"}, {"srv_cert", OPT_SRV_CERT, 's', "Certificate of the server"}, {"srv_key", OPT_SRV_KEY, 's', "Private key used by the server for signing messages"}, {"srv_keypass", OPT_SRV_KEYPASS, 's', "Server private key (and cert) pass phrase source"}, {"srv_trusted", OPT_SRV_TRUSTED, 's', "Trusted certificates for client authentication"}, {"srv_untrusted", OPT_SRV_UNTRUSTED, 's', "Intermediate certs that may be useful for verifying CMP protection"}, {"rsp_cert", OPT_RSP_CERT, 's', "Certificate to be returned as mock enrollment result"}, {"rsp_extracerts", OPT_RSP_EXTRACERTS, 's', "Extra certificates to be included in mock certification responses"}, {"rsp_capubs", OPT_RSP_CAPUBS, 's', "CA certificates to be included in mock ip response"}, {"poll_count", OPT_POLL_COUNT, 'N', "Number of times the client must poll before receiving a certificate"}, {"check_after", OPT_CHECK_AFTER, 'N', "The check_after value (time to wait) to include in poll response"}, {"grant_implicitconf", OPT_GRANT_IMPLICITCONF, '-', "Grant implicit confirmation of newly enrolled certificate"}, {"pkistatus", OPT_PKISTATUS, 'N', "PKIStatus to be included in server response. Possible values: 0..6"}, {"failure", OPT_FAILURE, 'N', "A single failure info bit number to include in server response, 0..26"}, {"failurebits", OPT_FAILUREBITS, 'N', "Number representing failure bits to include in server response, 0..2^27 - 1"}, {"statusstring", OPT_STATUSSTRING, 's', "Status string to be included in server response"}, {"send_error", OPT_SEND_ERROR, '-', "Force server to reply with error message"}, {"send_unprotected", OPT_SEND_UNPROTECTED, '-', "Send response messages without CMP-level protection"}, {"send_unprot_err", OPT_SEND_UNPROT_ERR, '-', "In case of negative responses, server shall send unprotected error messages,"}, {OPT_MORE_STR, 0, 0, "certificate responses (ip/cp/kup), and revocation responses (rp)."}, {OPT_MORE_STR, 0, 0, "WARNING: This setting leads to behavior violating RFC 4210"}, {"accept_unprotected", OPT_ACCEPT_UNPROTECTED, '-', "Accept missing or invalid protection of requests"}, {"accept_unprot_err", OPT_ACCEPT_UNPROT_ERR, '-', "Accept unprotected error messages from client"}, {"accept_raverified", OPT_ACCEPT_RAVERIFIED, '-', "Accept RAVERIFIED as proof-of-possession (POPO)"}, OPT_V_OPTIONS, {NULL} }; typedef union { char **txt; int *num; long *num_long; } varref; static varref cmp_vars[] = { /* must be in same order as enumerated above! */ {&opt_config}, {&opt_section}, {(char **)&opt_verbosity}, {&opt_cmd_s}, {&opt_infotype_s}, {&opt_geninfo}, {&opt_newkey}, {&opt_newkeypass}, {&opt_subject}, {&opt_issuer}, {(char **)&opt_days}, {&opt_reqexts}, {&opt_sans}, {(char **)&opt_san_nodefault}, {&opt_policies}, {&opt_policy_oids}, {(char **)&opt_policy_oids_critical}, {(char **)&opt_popo}, {&opt_csr}, {&opt_out_trusted}, {(char **)&opt_implicit_confirm}, {(char **)&opt_disable_confirm}, {&opt_certout}, {&opt_chainout}, {&opt_oldcert}, {(char **)&opt_revreason}, #ifndef OPENSSL_NO_SOCK {&opt_server}, {&opt_proxy}, {&opt_no_proxy}, #endif {&opt_recipient}, {&opt_path}, {(char **)&opt_keep_alive}, {(char **)&opt_msg_timeout}, {(char **)&opt_total_timeout}, {&opt_trusted}, {&opt_untrusted}, {&opt_srvcert}, {&opt_expect_sender}, {(char **)&opt_ignore_keyusage}, {(char **)&opt_unprotected_errors}, {&opt_extracertsout}, {&opt_cacertsout}, {&opt_ref}, {&opt_secret}, {&opt_cert}, {&opt_own_trusted}, {&opt_key}, {&opt_keypass}, {&opt_digest}, {&opt_mac}, {&opt_extracerts}, {(char **)&opt_unprotected_requests}, {&opt_certform_s}, {&opt_keyform_s}, {&opt_otherpass}, #ifndef OPENSSL_NO_ENGINE {&opt_engine}, #endif #ifndef OPENSSL_NO_SOCK {(char **)&opt_tls_used}, {&opt_tls_cert}, {&opt_tls_key}, {&opt_tls_keypass}, {&opt_tls_extra}, {&opt_tls_trusted}, {&opt_tls_host}, #endif {(char **)&opt_batch}, {(char **)&opt_repeat}, {&opt_reqin}, {(char **)&opt_reqin_new_tid}, {&opt_reqout}, {&opt_rspin}, {&opt_rspout}, {(char **)&opt_use_mock_srv}, #ifndef OPENSSL_NO_SOCK {&opt_port}, {(char **)&opt_max_msgs}, #endif {&opt_srv_ref}, {&opt_srv_secret}, {&opt_srv_cert}, {&opt_srv_key}, {&opt_srv_keypass}, {&opt_srv_trusted}, {&opt_srv_untrusted}, {&opt_rsp_cert}, {&opt_rsp_extracerts}, {&opt_rsp_capubs}, {(char **)&opt_poll_count}, {(char **)&opt_check_after}, {(char **)&opt_grant_implicitconf}, {(char **)&opt_pkistatus}, {(char **)&opt_failure}, {(char **)&opt_failurebits}, {&opt_statusstring}, {(char **)&opt_send_error}, {(char **)&opt_send_unprotected}, {(char **)&opt_send_unprot_err}, {(char **)&opt_accept_unprotected}, {(char **)&opt_accept_unprot_err}, {(char **)&opt_accept_raverified}, {NULL} }; #define FUNC (strcmp(OPENSSL_FUNC, "(unknown function)") == 0 \ ? "CMP" : OPENSSL_FUNC) #define CMP_print(bio, level, prefix, msg, a1, a2, a3) \ ((void)(level > opt_verbosity ? 0 : \ (BIO_printf(bio, "%s:%s:%d:CMP %s: " msg "\n", \ FUNC, OPENSSL_FILE, OPENSSL_LINE, prefix, a1, a2, a3)))) #define CMP_DEBUG(m, a1, a2, a3) \ CMP_print(bio_out, OSSL_CMP_LOG_DEBUG, "debug", m, a1, a2, a3) #define CMP_debug(msg) CMP_DEBUG(msg"%s%s%s", "", "", "") #define CMP_debug1(msg, a1) CMP_DEBUG(msg"%s%s", a1, "", "") #define CMP_debug2(msg, a1, a2) CMP_DEBUG(msg"%s", a1, a2, "") #define CMP_debug3(msg, a1, a2, a3) CMP_DEBUG(msg, a1, a2, a3) #define CMP_INFO(msg, a1, a2, a3) \ CMP_print(bio_out, OSSL_CMP_LOG_INFO, "info", msg, a1, a2, a3) #define CMP_info(msg) CMP_INFO(msg"%s%s%s", "", "", "") #define CMP_info1(msg, a1) CMP_INFO(msg"%s%s", a1, "", "") #define CMP_info2(msg, a1, a2) CMP_INFO(msg"%s", a1, a2, "") #define CMP_info3(msg, a1, a2, a3) CMP_INFO(msg, a1, a2, a3) #define CMP_WARN(m, a1, a2, a3) \ CMP_print(bio_out, OSSL_CMP_LOG_WARNING, "warning", m, a1, a2, a3) #define CMP_warn(msg) CMP_WARN(msg"%s%s%s", "", "", "") #define CMP_warn1(msg, a1) CMP_WARN(msg"%s%s", a1, "", "") #define CMP_warn2(msg, a1, a2) CMP_WARN(msg"%s", a1, a2, "") #define CMP_warn3(msg, a1, a2, a3) CMP_WARN(msg, a1, a2, a3) #define CMP_ERR(msg, a1, a2, a3) \ CMP_print(bio_err, OSSL_CMP_LOG_ERR, "error", msg, a1, a2, a3) #define CMP_err(msg) CMP_ERR(msg"%s%s%s", "", "", "") #define CMP_err1(msg, a1) CMP_ERR(msg"%s%s", a1, "", "") #define CMP_err2(msg, a1, a2) CMP_ERR(msg"%s", a1, a2, "") #define CMP_err3(msg, a1, a2, a3) CMP_ERR(msg, a1, a2, a3) static int print_to_bio_out(const char *func, const char *file, int line, OSSL_CMP_severity level, const char *msg) { return OSSL_CMP_print_to_bio(bio_out, func, file, line, level, msg); } static int print_to_bio_err(const char *func, const char *file, int line, OSSL_CMP_severity level, const char *msg) { return OSSL_CMP_print_to_bio(bio_err, func, file, line, level, msg); } static int set_verbosity(int level) { if (level < OSSL_CMP_LOG_EMERG || level > OSSL_CMP_LOG_MAX) { CMP_err1("Logging verbosity level %d out of range (0 .. 8)", level); return 0; } opt_verbosity = level; return 1; } static EVP_PKEY *load_key_pwd(const char *uri, int format, const char *pass, ENGINE *eng, const char *desc) { char *pass_string = get_passwd(pass, desc); EVP_PKEY *pkey = load_key(uri, format, 0, pass_string, eng, desc); clear_free(pass_string); return pkey; } static X509 *load_cert_pwd(const char *uri, const char *pass, const char *desc) { X509 *cert; char *pass_string = get_passwd(pass, desc); cert = load_cert_pass(uri, FORMAT_UNDEF, 0, pass_string, desc); clear_free(pass_string); return cert; } static X509_REQ *load_csr_autofmt(const char *infile, const char *desc) { X509_REQ *csr; BIO *bio_bak = bio_err; bio_err = NULL; /* do not show errors on more than one try */ csr = load_csr(infile, FORMAT_PEM, desc); bio_err = bio_bak; if (csr == NULL) { ERR_clear_error(); csr = load_csr(infile, FORMAT_ASN1, desc); } if (csr == NULL) { ERR_print_errors(bio_err); BIO_printf(bio_err, "error: unable to load %s from file '%s'\n", desc, infile); } else { EVP_PKEY *pkey = X509_REQ_get0_pubkey(csr); int ret = do_X509_REQ_verify(csr, pkey, NULL /* vfyopts */); if (pkey == NULL || ret < 0) CMP_warn("error while verifying CSR self-signature"); else if (ret == 0) CMP_warn("CSR self-signature does not match the contents"); } return csr; } /* set expected host name/IP addr and clears the email addr in the given ts */ static int truststore_set_host_etc(X509_STORE *ts, const char *host) { X509_VERIFY_PARAM *ts_vpm = X509_STORE_get0_param(ts); /* first clear any host names, IP, and email addresses */ if (!X509_VERIFY_PARAM_set1_host(ts_vpm, NULL, 0) || !X509_VERIFY_PARAM_set1_ip(ts_vpm, NULL, 0) || !X509_VERIFY_PARAM_set1_email(ts_vpm, NULL, 0)) return 0; X509_VERIFY_PARAM_set_hostflags(ts_vpm, X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT | X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); return (host != NULL && X509_VERIFY_PARAM_set1_ip_asc(ts_vpm, host)) || X509_VERIFY_PARAM_set1_host(ts_vpm, host, 0); } /* write OSSL_CMP_MSG DER-encoded to the specified file name item */ static int write_PKIMESSAGE(const OSSL_CMP_MSG *msg, char **filenames) { char *file; if (msg == NULL || filenames == NULL) { CMP_err("NULL arg to write_PKIMESSAGE"); return 0; } if (*filenames == NULL) { CMP_err("not enough file names provided for writing PKIMessage"); return 0; } file = *filenames; *filenames = next_item(file); if (OSSL_CMP_MSG_write(file, msg) < 0) { CMP_err1("cannot write PKIMessage to file '%s'", file); return 0; } return 1; } /* read DER-encoded OSSL_CMP_MSG from the specified file name item */ static OSSL_CMP_MSG *read_PKIMESSAGE(const char *desc, char **filenames) { char *file; OSSL_CMP_MSG *ret; if (filenames == NULL || desc == NULL) { CMP_err("NULL arg to read_PKIMESSAGE"); return NULL; } if (*filenames == NULL) { CMP_err("not enough file names provided for reading PKIMessage"); return NULL; } file = *filenames; *filenames = next_item(file); ret = OSSL_CMP_MSG_read(file, app_get0_libctx(), app_get0_propq()); if (ret == NULL) CMP_err1("cannot read PKIMessage from file '%s'", file); else CMP_info2("%s %s", desc, file); return ret; } /*- * Sends the PKIMessage req and on success place the response in *res * basically like OSSL_CMP_MSG_http_perform(), but in addition allows * to dump the sequence of requests and responses to files and/or * to take the sequence of requests and responses from files. */ static OSSL_CMP_MSG *read_write_req_resp(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *req) { OSSL_CMP_MSG *req_new = NULL; OSSL_CMP_MSG *res = NULL; OSSL_CMP_PKIHEADER *hdr; const char *prev_opt_rspin = opt_rspin; if (req != NULL && opt_reqout != NULL && !write_PKIMESSAGE(req, &opt_reqout)) goto err; if (opt_reqin != NULL && opt_rspin == NULL) { if ((req_new = read_PKIMESSAGE("actually sending", &opt_reqin)) == NULL) goto err; /*- * The transaction ID in req_new read from opt_reqin may not be fresh. * In this case the server may complain "Transaction id already in use." * The following workaround unfortunately requires re-protection. */ if (opt_reqin_new_tid && !OSSL_CMP_MSG_update_transactionID(ctx, req_new)) goto err; /* * Except for first request, need to satisfy recipNonce check by server. * Unfortunately requires re-protection if protection is required. */ if (!OSSL_CMP_MSG_update_recipNonce(ctx, req_new)) goto err; } if (opt_rspin != NULL) { res = read_PKIMESSAGE("actually using", &opt_rspin); } else { const OSSL_CMP_MSG *actual_req = req_new != NULL ? req_new : req; if (opt_use_mock_srv) { if (rspin_in_use) CMP_warn("too few -rspin filename arguments; resorting to using mock server"); res = OSSL_CMP_CTX_server_perform(ctx, actual_req); } else { #ifndef OPENSSL_NO_SOCK if (opt_server == NULL) { CMP_err("missing -server or -use_mock_srv option, or too few -rspin filename arguments"); goto err; } if (rspin_in_use) CMP_warn("too few -rspin filename arguments; resorting to contacting server"); res = OSSL_CMP_MSG_http_perform(ctx, actual_req); #else CMP_err("-server not supported on no-sock build; missing -use_mock_srv option or too few -rspin filename arguments"); #endif } rspin_in_use = 0; } if (res == NULL) goto err; if (req_new != NULL || prev_opt_rspin != NULL) { /* need to satisfy nonce and transactionID checks by client */ ASN1_OCTET_STRING *nonce; ASN1_OCTET_STRING *tid; hdr = OSSL_CMP_MSG_get0_header(res); nonce = OSSL_CMP_HDR_get0_recipNonce(hdr); tid = OSSL_CMP_HDR_get0_transactionID(hdr); if (!OSSL_CMP_CTX_set1_senderNonce(ctx, nonce) || !OSSL_CMP_CTX_set1_transactionID(ctx, tid)) { OSSL_CMP_MSG_free(res); res = NULL; goto err; } } if (opt_rspout != NULL && !write_PKIMESSAGE(res, &opt_rspout)) { OSSL_CMP_MSG_free(res); res = NULL; } err: OSSL_CMP_MSG_free(req_new); return res; } static int set_name(const char *str, int (*set_fn) (OSSL_CMP_CTX *ctx, const X509_NAME *name), OSSL_CMP_CTX *ctx, const char *desc) { if (str != NULL) { X509_NAME *n = parse_name(str, MBSTRING_ASC, 1, desc); if (n == NULL) return 0; if (!(*set_fn) (ctx, n)) { X509_NAME_free(n); CMP_err("out of memory"); return 0; } X509_NAME_free(n); } return 1; } static int set_gennames(OSSL_CMP_CTX *ctx, char *names, const char *desc) { char *next; for (; names != NULL; names = next) { GENERAL_NAME *n; next = next_item(names); if (strcmp(names, "critical") == 0) { (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_SUBJECTALTNAME_CRITICAL, 1); continue; } /* try IP address first, then URI or domain name */ (void)ERR_set_mark(); n = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_IPADD, names, 0); if (n == NULL) n = a2i_GENERAL_NAME(NULL, NULL, NULL, strchr(names, ':') != NULL ? GEN_URI : GEN_DNS, names, 0); (void)ERR_pop_to_mark(); if (n == NULL) { CMP_err2("bad syntax of %s '%s'", desc, names); return 0; } if (!OSSL_CMP_CTX_push1_subjectAltName(ctx, n)) { GENERAL_NAME_free(n); CMP_err("out of memory"); return 0; } GENERAL_NAME_free(n); } return 1; } static X509_STORE *load_trusted(char *input, int for_new_cert, const char *desc) { X509_STORE *ts = load_certstore(input, opt_otherpass, desc, vpm); if (ts == NULL) return NULL; X509_STORE_set_verify_cb(ts, X509_STORE_CTX_print_verify_cb); /* copy vpm to store */ if (X509_STORE_set1_param(ts, vpm /* may be NULL */) && (for_new_cert || truststore_set_host_etc(ts, NULL))) return ts; BIO_printf(bio_err, "error setting verification parameters for %s\n", desc); OSSL_CMP_CTX_print_errors(cmp_ctx); X509_STORE_free(ts); return NULL; } typedef int (*add_X509_stack_fn_t)(void *ctx, const STACK_OF(X509) *certs); static int setup_certs(char *files, const char *desc, void *ctx, add_X509_stack_fn_t set1_fn) { STACK_OF(X509) *certs; int ok; if (files == NULL) return 1; if ((certs = load_certs_multifile(files, opt_otherpass, desc, vpm)) == NULL) return 0; ok = (*set1_fn)(ctx, certs); sk_X509_pop_free(certs, X509_free); return ok; } /* * parse and transform some options, checking their syntax. * Returns 1 on success, 0 on error */ static int transform_opts(void) { if (opt_cmd_s != NULL) { if (!strcmp(opt_cmd_s, "ir")) { opt_cmd = CMP_IR; } else if (!strcmp(opt_cmd_s, "kur")) { opt_cmd = CMP_KUR; } else if (!strcmp(opt_cmd_s, "cr")) { opt_cmd = CMP_CR; } else if (!strcmp(opt_cmd_s, "p10cr")) { opt_cmd = CMP_P10CR; } else if (!strcmp(opt_cmd_s, "rr")) { opt_cmd = CMP_RR; } else if (!strcmp(opt_cmd_s, "genm")) { opt_cmd = CMP_GENM; } else { CMP_err1("unknown cmp command '%s'", opt_cmd_s); return 0; } } else { CMP_err("no cmp command to execute"); return 0; } #ifndef OPENSSL_NO_ENGINE # define FORMAT_OPTIONS (OPT_FMT_PEMDER | OPT_FMT_PKCS12 | OPT_FMT_ENGINE) #else # define FORMAT_OPTIONS (OPT_FMT_PEMDER | OPT_FMT_PKCS12) #endif if (opt_keyform_s != NULL && !opt_format(opt_keyform_s, FORMAT_OPTIONS, &opt_keyform)) { CMP_err("unknown option given for key loading format"); return 0; } #undef FORMAT_OPTIONS if (opt_certform_s != NULL && !opt_format(opt_certform_s, OPT_FMT_PEMDER, &opt_certform)) { CMP_err("unknown option given for certificate storing format"); return 0; } return 1; } static OSSL_CMP_SRV_CTX *setup_srv_ctx(ENGINE *engine) { OSSL_CMP_CTX *ctx; /* extra CMP (client) ctx partly used by server */ OSSL_CMP_SRV_CTX *srv_ctx = ossl_cmp_mock_srv_new(app_get0_libctx(), app_get0_propq()); if (srv_ctx == NULL) return NULL; ctx = OSSL_CMP_SRV_CTX_get0_cmp_ctx(srv_ctx); if (opt_srv_ref == NULL) { if (opt_srv_cert == NULL) { /* opt_srv_cert should determine the sender */ CMP_err("must give -srv_ref for mock server if no -srv_cert given"); goto err; } } else { if (!OSSL_CMP_CTX_set1_referenceValue(ctx, (unsigned char *)opt_srv_ref, strlen(opt_srv_ref))) goto err; } if (opt_srv_secret != NULL) { int res; char *pass_str = get_passwd(opt_srv_secret, "PBMAC secret of mock server"); if (pass_str != NULL) { cleanse(opt_srv_secret); res = OSSL_CMP_CTX_set1_secretValue(ctx, (unsigned char *)pass_str, strlen(pass_str)); clear_free(pass_str); if (res == 0) goto err; } } else if (opt_srv_cert == NULL) { CMP_err("server credentials (-srv_secret or -srv_cert) must be given if -use_mock_srv or -port is used"); goto err; } else { CMP_warn("server will not be able to handle PBM-protected requests since -srv_secret is not given"); } if (opt_srv_secret == NULL && ((opt_srv_cert == NULL) != (opt_srv_key == NULL))) { CMP_err("must give both -srv_cert and -srv_key options or neither"); goto err; } if (opt_srv_cert != NULL) { X509 *srv_cert = load_cert_pwd(opt_srv_cert, opt_srv_keypass, "certificate of the mock server"); if (srv_cert == NULL || !OSSL_CMP_CTX_set1_cert(ctx, srv_cert)) { X509_free(srv_cert); goto err; } X509_free(srv_cert); } if (opt_srv_key != NULL) { EVP_PKEY *pkey = load_key_pwd(opt_srv_key, opt_keyform, opt_srv_keypass, engine, "private key for mock server cert"); if (pkey == NULL || !OSSL_CMP_CTX_set1_pkey(ctx, pkey)) { EVP_PKEY_free(pkey); goto err; } EVP_PKEY_free(pkey); } cleanse(opt_srv_keypass); if (opt_srv_trusted != NULL) { X509_STORE *ts = load_trusted(opt_srv_trusted, 0, "certs trusted by mock server"); if (ts == NULL || !OSSL_CMP_CTX_set0_trustedStore(ctx, ts)) { X509_STORE_free(ts); goto err; } } else { CMP_warn("mock server will not be able to handle signature-protected requests since -srv_trusted is not given"); } if (!setup_certs(opt_srv_untrusted, "untrusted certificates for mock server", ctx, (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_untrusted)) goto err; if (opt_rsp_cert == NULL) { CMP_warn("no -rsp_cert given for mock server"); } else { X509 *cert = load_cert_pwd(opt_rsp_cert, opt_keypass, "cert to be returned by the mock server"); if (cert == NULL) goto err; /* from server perspective the server is the client */ if (!ossl_cmp_mock_srv_set1_certOut(srv_ctx, cert)) { X509_free(cert); goto err; } X509_free(cert); } if (!setup_certs(opt_rsp_extracerts, "CMP extra certificates for mock server", srv_ctx, (add_X509_stack_fn_t)ossl_cmp_mock_srv_set1_chainOut)) goto err; if (!setup_certs(opt_rsp_capubs, "caPubs for mock server", srv_ctx, (add_X509_stack_fn_t)ossl_cmp_mock_srv_set1_caPubsOut)) goto err; (void)ossl_cmp_mock_srv_set_pollCount(srv_ctx, opt_poll_count); (void)ossl_cmp_mock_srv_set_checkAfterTime(srv_ctx, opt_check_after); if (opt_grant_implicitconf) (void)OSSL_CMP_SRV_CTX_set_grant_implicit_confirm(srv_ctx, 1); if (opt_failure != INT_MIN) { /* option has been set explicity */ if (opt_failure < 0 || OSSL_CMP_PKIFAILUREINFO_MAX < opt_failure) { CMP_err1("-failure out of range, should be >= 0 and <= %d", OSSL_CMP_PKIFAILUREINFO_MAX); goto err; } if (opt_failurebits != 0) CMP_warn("-failurebits overrides -failure"); else opt_failurebits = 1 << opt_failure; } if ((unsigned)opt_failurebits > OSSL_CMP_PKIFAILUREINFO_MAX_BIT_PATTERN) { CMP_err("-failurebits out of range"); goto err; } if (!ossl_cmp_mock_srv_set_statusInfo(srv_ctx, opt_pkistatus, opt_failurebits, opt_statusstring)) goto err; if (opt_send_error) (void)ossl_cmp_mock_srv_set_sendError(srv_ctx, 1); if (opt_send_unprotected) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_SEND, 1); if (opt_send_unprot_err) (void)OSSL_CMP_SRV_CTX_set_send_unprotected_errors(srv_ctx, 1); if (opt_accept_unprotected) (void)OSSL_CMP_SRV_CTX_set_accept_unprotected(srv_ctx, 1); if (opt_accept_unprot_err) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_ERRORS, 1); if (opt_accept_raverified) (void)OSSL_CMP_SRV_CTX_set_accept_raverified(srv_ctx, 1); return srv_ctx; err: ossl_cmp_mock_srv_free(srv_ctx); return NULL; } /* * set up verification aspects of OSSL_CMP_CTX w.r.t. opts from config file/CLI. * Returns pointer on success, NULL on error */ static int setup_verification_ctx(OSSL_CMP_CTX *ctx) { if (!setup_certs(opt_untrusted, "untrusted certificates", ctx, (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_untrusted)) return 0; if (opt_srvcert != NULL || opt_trusted != NULL) { X509 *srvcert; X509_STORE *ts; int ok; if (opt_srvcert != NULL) { if (opt_trusted != NULL) { CMP_warn("-trusted option is ignored since -srvcert option is present"); opt_trusted = NULL; } if (opt_recipient != NULL) { CMP_warn("-recipient option is ignored since -srvcert option is present"); opt_recipient = NULL; } srvcert = load_cert_pwd(opt_srvcert, opt_otherpass, "directly trusted CMP server certificate"); ok = srvcert != NULL && OSSL_CMP_CTX_set1_srvCert(ctx, srvcert); X509_free(srvcert); if (!ok) return 0; } if (opt_trusted != NULL) { /* * the 0 arg below clears any expected host/ip/email address; * opt_expect_sender is used instead */ ts = load_trusted(opt_trusted, 0, "certs trusted by client"); if (ts == NULL || !OSSL_CMP_CTX_set0_trustedStore(ctx, ts)) { X509_STORE_free(ts); return 0; } } } if (opt_ignore_keyusage) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_IGNORE_KEYUSAGE, 1); if (opt_unprotected_errors) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_ERRORS, 1); if (opt_out_trusted != NULL) { /* for use in OSSL_CMP_certConf_cb() */ X509_VERIFY_PARAM *out_vpm = NULL; X509_STORE *out_trusted = load_trusted(opt_out_trusted, 1, "trusted certs for verifying newly enrolled cert"); if (out_trusted == NULL) return 0; /* ignore any -attime here, new certs are current anyway */ out_vpm = X509_STORE_get0_param(out_trusted); X509_VERIFY_PARAM_clear_flags(out_vpm, X509_V_FLAG_USE_CHECK_TIME); (void)OSSL_CMP_CTX_set_certConf_cb_arg(ctx, out_trusted); } if (opt_disable_confirm) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_DISABLE_CONFIRM, 1); if (opt_implicit_confirm) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_IMPLICIT_CONFIRM, 1); return 1; } #ifndef OPENSSL_NO_SOCK /* * set up ssl_ctx for the OSSL_CMP_CTX based on options from config file/CLI. * Returns pointer on success, NULL on error */ static SSL_CTX *setup_ssl_ctx(OSSL_CMP_CTX *ctx, const char *host, ENGINE *engine) { STACK_OF(X509) *untrusted = OSSL_CMP_CTX_get0_untrusted(ctx); EVP_PKEY *pkey = NULL; X509_STORE *trust_store = NULL; SSL_CTX *ssl_ctx; int i; ssl_ctx = SSL_CTX_new(TLS_client_method()); if (ssl_ctx == NULL) return NULL; if (opt_tls_trusted != NULL) { trust_store = load_trusted(opt_tls_trusted, 0, "trusted TLS certs"); if (trust_store == NULL) goto err; SSL_CTX_set_cert_store(ssl_ctx, trust_store); } if (opt_tls_cert != NULL && opt_tls_key != NULL) { X509 *cert; STACK_OF(X509) *certs = NULL; int ok; if (!load_cert_certs(opt_tls_cert, &cert, &certs, 0, opt_tls_keypass, "TLS client certificate (optionally with chain)", vpm)) /* need opt_tls_keypass if opt_tls_cert is encrypted PKCS#12 file */ goto err; ok = SSL_CTX_use_certificate(ssl_ctx, cert) > 0; X509_free(cert); /* * Any further certs and any untrusted certs are used for constructing * the chain to be provided with the TLS client cert to the TLS server. */ if (!ok || !SSL_CTX_set0_chain(ssl_ctx, certs)) { CMP_err1("unable to use client TLS certificate file '%s'", opt_tls_cert); sk_X509_pop_free(certs, X509_free); goto err; } for (i = 0; i < sk_X509_num(untrusted); i++) { cert = sk_X509_value(untrusted, i); if (!SSL_CTX_add1_chain_cert(ssl_ctx, cert)) { CMP_err("could not add untrusted cert to TLS client cert chain"); goto err; } } { X509_VERIFY_PARAM *tls_vpm = NULL; unsigned long bak_flags = 0; /* compiler warns without init */ if (trust_store != NULL) { tls_vpm = X509_STORE_get0_param(trust_store); bak_flags = X509_VERIFY_PARAM_get_flags(tls_vpm); /* disable any cert status/revocation checking etc. */ X509_VERIFY_PARAM_clear_flags(tls_vpm, ~(X509_V_FLAG_USE_CHECK_TIME | X509_V_FLAG_NO_CHECK_TIME | X509_V_FLAG_PARTIAL_CHAIN | X509_V_FLAG_POLICY_CHECK)); } CMP_debug("trying to build cert chain for own TLS cert"); if (SSL_CTX_build_cert_chain(ssl_ctx, SSL_BUILD_CHAIN_FLAG_UNTRUSTED | SSL_BUILD_CHAIN_FLAG_NO_ROOT)) { CMP_debug("success building cert chain for own TLS cert"); } else { OSSL_CMP_CTX_print_errors(ctx); CMP_warn("could not build cert chain for own TLS cert"); } if (trust_store != NULL) X509_VERIFY_PARAM_set_flags(tls_vpm, bak_flags); } /* If present we append to the list also the certs from opt_tls_extra */ if (opt_tls_extra != NULL) { STACK_OF(X509) *tls_extra = load_certs_multifile(opt_tls_extra, opt_otherpass, "extra certificates for TLS", vpm); int res = 1; if (tls_extra == NULL) goto err; for (i = 0; i < sk_X509_num(tls_extra); i++) { cert = sk_X509_value(tls_extra, i); if (res != 0) res = SSL_CTX_add_extra_chain_cert(ssl_ctx, cert); if (res == 0) X509_free(cert); } sk_X509_free(tls_extra); if (res == 0) { BIO_printf(bio_err, "error: unable to add TLS extra certs\n"); goto err; } } pkey = load_key_pwd(opt_tls_key, opt_keyform, opt_tls_keypass, engine, "TLS client private key"); cleanse(opt_tls_keypass); if (pkey == NULL) goto err; /* * verify the key matches the cert, * not using SSL_CTX_check_private_key(ssl_ctx) * because it gives poor and sometimes misleading diagnostics */ if (!X509_check_private_key(SSL_CTX_get0_certificate(ssl_ctx), pkey)) { CMP_err2("TLS private key '%s' does not match the TLS certificate '%s'\n", opt_tls_key, opt_tls_cert); EVP_PKEY_free(pkey); pkey = NULL; /* otherwise, for some reason double free! */ goto err; } if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) <= 0) { CMP_err1("unable to use TLS client private key '%s'", opt_tls_key); EVP_PKEY_free(pkey); pkey = NULL; /* otherwise, for some reason double free! */ goto err; } EVP_PKEY_free(pkey); /* we do not need the handle any more */ } if (opt_tls_trusted != NULL) { /* enable and parameterize server hostname/IP address check */ if (!truststore_set_host_etc(trust_store, opt_tls_host != NULL ? opt_tls_host : host)) goto err; SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL); } return ssl_ctx; err: SSL_CTX_free(ssl_ctx); return NULL; } #endif /* OPENSSL_NO_SOCK */ /* * set up protection aspects of OSSL_CMP_CTX based on options from config * file/CLI while parsing options and checking their consistency. * Returns 1 on success, 0 on error */ static int setup_protection_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine) { if (!opt_unprotected_requests && opt_secret == NULL && opt_key == NULL) { CMP_err("must give -key or -secret unless -unprotected_requests is used"); return 0; } if (opt_ref == NULL && opt_cert == NULL && opt_subject == NULL) { /* cert or subject should determine the sender */ CMP_err("must give -ref if no -cert and no -subject given"); return 0; } if (!opt_secret && ((opt_cert == NULL) != (opt_key == NULL))) { CMP_err("must give both -cert and -key options or neither"); return 0; } if (opt_secret != NULL) { char *pass_string = get_passwd(opt_secret, "PBMAC"); int res; if (pass_string != NULL) { cleanse(opt_secret); res = OSSL_CMP_CTX_set1_secretValue(ctx, (unsigned char *)pass_string, strlen(pass_string)); clear_free(pass_string); if (res == 0) return 0; } if (opt_cert != NULL || opt_key != NULL) CMP_warn("-cert and -key not used for protection since -secret is given"); } if (opt_ref != NULL && !OSSL_CMP_CTX_set1_referenceValue(ctx, (unsigned char *)opt_ref, strlen(opt_ref))) return 0; if (opt_key != NULL) { EVP_PKEY *pkey = load_key_pwd(opt_key, opt_keyform, opt_keypass, engine, "private key for CMP client certificate"); if (pkey == NULL || !OSSL_CMP_CTX_set1_pkey(ctx, pkey)) { EVP_PKEY_free(pkey); return 0; } EVP_PKEY_free(pkey); } if (opt_secret == NULL && opt_srvcert == NULL && opt_trusted == NULL) CMP_warn("will not authenticate server due to missing -secret, -trusted, or -srvcert"); if (opt_cert != NULL) { X509 *cert; STACK_OF(X509) *certs = NULL; X509_STORE *own_trusted = NULL; int ok; if (!load_cert_certs(opt_cert, &cert, &certs, 0, opt_keypass, "CMP client certificate (optionally with chain)", vpm)) /* opt_keypass is needed if opt_cert is an encrypted PKCS#12 file */ return 0; ok = OSSL_CMP_CTX_set1_cert(ctx, cert); X509_free(cert); if (!ok) { CMP_err("out of memory"); } else { if (opt_own_trusted != NULL) { own_trusted = load_trusted(opt_own_trusted, 0, "trusted certs for verifying own CMP signer cert"); ok = own_trusted != NULL; } ok = ok && OSSL_CMP_CTX_build_cert_chain(ctx, own_trusted, certs); } X509_STORE_free(own_trusted); sk_X509_pop_free(certs, X509_free); if (!ok) return 0; } else if (opt_own_trusted != NULL) { CMP_warn("-own_trusted option is ignored without -cert"); } if (!setup_certs(opt_extracerts, "extra certificates for CMP", ctx, (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_extraCertsOut)) return 0; cleanse(opt_otherpass); if (opt_unprotected_requests) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_SEND, 1); if (opt_digest != NULL) { int digest = OBJ_ln2nid(opt_digest); if (digest == NID_undef) { CMP_err1("digest algorithm name not recognized: '%s'", opt_digest); return 0; } if (!OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_DIGEST_ALGNID, digest) || !OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_OWF_ALGNID, digest)) { CMP_err1("digest algorithm name not supported: '%s'", opt_digest); return 0; } } if (opt_mac != NULL) { int mac = OBJ_ln2nid(opt_mac); if (mac == NID_undef) { CMP_err1("MAC algorithm name not recognized: '%s'", opt_mac); return 0; } (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_MAC_ALGNID, mac); } return 1; } /* * set up IR/CR/KUR/CertConf/RR specific parts of the OSSL_CMP_CTX * based on options from config file/CLI. * Returns pointer on success, NULL on error */ static int setup_request_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine) { X509_REQ *csr = NULL; X509_EXTENSIONS *exts = NULL; X509V3_CTX ext_ctx; if (opt_subject == NULL && opt_csr == NULL && opt_oldcert == NULL && opt_cert == NULL && opt_cmd != CMP_RR && opt_cmd != CMP_GENM) CMP_warn("no -subject given; no -csr or -oldcert or -cert available for fallback"); if (opt_cmd == CMP_IR || opt_cmd == CMP_CR || opt_cmd == CMP_KUR) { if (opt_newkey == NULL && opt_key == NULL && opt_csr == NULL && opt_oldcert == NULL) { CMP_err("missing -newkey (or -key) to be certified and no -csr, -oldcert, or -cert given for fallback public key"); return 0; } if (opt_newkey == NULL && opt_popo != OSSL_CRMF_POPO_NONE && opt_popo != OSSL_CRMF_POPO_RAVERIFIED) { if (opt_csr != NULL) { CMP_err1("no -newkey option given with private key for POPO, -csr option only provides public key%s", opt_key == NULL ? "" : ", and -key option superseded by by -csr"); return 0; } if (opt_key == NULL) { CMP_err("missing -newkey (or -key) option for POPO"); return 0; } } if (opt_certout == NULL) { CMP_err("-certout not given, nowhere to save newly enrolled certificate"); return 0; } if (!set_name(opt_subject, OSSL_CMP_CTX_set1_subjectName, ctx, "subject") || !set_name(opt_issuer, OSSL_CMP_CTX_set1_issuer, ctx, "issuer")) return 0; } else { const char *msg = "option is ignored for commands other than 'ir', 'cr', and 'kur'"; if (opt_subject != NULL) { if (opt_ref == NULL && opt_cert == NULL) { /* use subject as default sender unless oldcert subject is used */ if (!set_name(opt_subject, OSSL_CMP_CTX_set1_subjectName, ctx, "subject")) return 0; } else { CMP_warn1("-subject %s since -ref or -cert is given", msg); } } if (opt_issuer != NULL) CMP_warn1("-issuer %s", msg); if (opt_reqexts != NULL) CMP_warn1("-reqexts %s", msg); if (opt_san_nodefault) CMP_warn1("-san_nodefault %s", msg); if (opt_sans != NULL) CMP_warn1("-sans %s", msg); if (opt_policies != NULL) CMP_warn1("-policies %s", msg); if (opt_policy_oids != NULL) CMP_warn1("-policy_oids %s", msg); } if (opt_cmd == CMP_KUR) { char *ref_cert = opt_oldcert != NULL ? opt_oldcert : opt_cert; if (ref_cert == NULL && opt_csr == NULL) { CMP_err("missing -oldcert for certificate to be updated and no -csr given"); return 0; } if (opt_subject != NULL) CMP_warn2("given -subject '%s' overrides the subject of '%s' for KUR", opt_subject, ref_cert != NULL ? ref_cert : opt_csr); } if (opt_cmd == CMP_RR) { if (opt_oldcert == NULL && opt_csr == NULL) { CMP_err("missing -oldcert for certificate to be revoked and no -csr given"); return 0; } if (opt_oldcert != NULL && opt_csr != NULL) CMP_warn("ignoring -csr since certificate to be revoked is given"); } if (opt_cmd == CMP_P10CR && opt_csr == NULL) { CMP_err("missing PKCS#10 CSR for p10cr"); return 0; } if (opt_recipient == NULL && opt_srvcert == NULL && opt_issuer == NULL && opt_oldcert == NULL && opt_cert == NULL) CMP_warn("missing -recipient, -srvcert, -issuer, -oldcert or -cert; recipient will be set to \"NULL-DN\""); if (opt_cmd == CMP_P10CR || opt_cmd == CMP_RR) { const char *msg = "option is ignored for 'p10cr' and 'rr' commands"; if (opt_newkeypass != NULL) CMP_warn1("-newkeytype %s", msg); if (opt_newkey != NULL) CMP_warn1("-newkey %s", msg); if (opt_days != 0) CMP_warn1("-days %s", msg); if (opt_popo != OSSL_CRMF_POPO_NONE - 1) CMP_warn1("-popo %s", msg); } else if (opt_newkey != NULL) { const char *file = opt_newkey; const int format = opt_keyform; const char *pass = opt_newkeypass; const char *desc = "new private key for cert to be enrolled"; EVP_PKEY *pkey; int priv = 1; BIO *bio_bak = bio_err; bio_err = NULL; /* suppress diagnostics on first try loading key */ pkey = load_key_pwd(file, format, pass, engine, desc); bio_err = bio_bak; if (pkey == NULL) { ERR_clear_error(); desc = opt_csr == NULL ? "fallback public key for cert to be enrolled" : "public key for checking cert resulting from p10cr"; pkey = load_pubkey(file, format, 0, pass, engine, desc); priv = 0; } cleanse(opt_newkeypass); if (pkey == NULL || !OSSL_CMP_CTX_set0_newPkey(ctx, priv, pkey)) { EVP_PKEY_free(pkey); return 0; } } if (opt_days > 0 && !OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_VALIDITY_DAYS, opt_days)) { CMP_err("could not set requested cert validity period"); return 0; } if (opt_policies != NULL && opt_policy_oids != NULL) { CMP_err("cannot have policies both via -policies and via -policy_oids"); return 0; } if (opt_csr != NULL) { if (opt_cmd == CMP_GENM) { CMP_warn("-csr option is ignored for command 'genm'"); } else { if ((csr = load_csr_autofmt(opt_csr, "PKCS#10 CSR")) == NULL) return 0; if (!OSSL_CMP_CTX_set1_p10CSR(ctx, csr)) goto oom; } } if (opt_reqexts != NULL || opt_policies != NULL) { if ((exts = sk_X509_EXTENSION_new_null()) == NULL) goto oom; X509V3_set_ctx(&ext_ctx, NULL, NULL, csr, NULL, X509V3_CTX_REPLACE); X509V3_set_nconf(&ext_ctx, conf); if (opt_reqexts != NULL && !X509V3_EXT_add_nconf_sk(conf, &ext_ctx, opt_reqexts, &exts)) { CMP_err1("cannot load certificate request extension section '%s'", opt_reqexts); goto exts_err; } if (opt_policies != NULL && !X509V3_EXT_add_nconf_sk(conf, &ext_ctx, opt_policies, &exts)) { CMP_err1("cannot load policy cert request extension section '%s'", opt_policies); goto exts_err; } OSSL_CMP_CTX_set0_reqExtensions(ctx, exts); } X509_REQ_free(csr); /* After here, must not goto oom/exts_err */ if (OSSL_CMP_CTX_reqExtensions_have_SAN(ctx) && opt_sans != NULL) { CMP_err("cannot have Subject Alternative Names both via -reqexts and via -sans"); return 0; } if (!set_gennames(ctx, opt_sans, "Subject Alternative Name")) return 0; if (opt_san_nodefault) { if (opt_sans != NULL) CMP_warn("-opt_san_nodefault has no effect when -sans is used"); (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_SUBJECTALTNAME_NODEFAULT, 1); } if (opt_policy_oids_critical) { if (opt_policy_oids == NULL) CMP_warn("-opt_policy_oids_critical has no effect unless -policy_oids is given"); (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_POLICIES_CRITICAL, 1); } while (opt_policy_oids != NULL) { ASN1_OBJECT *policy; POLICYINFO *pinfo; char *next = next_item(opt_policy_oids); if ((policy = OBJ_txt2obj(opt_policy_oids, 1)) == 0) { CMP_err1("unknown policy OID '%s'", opt_policy_oids); return 0; } if ((pinfo = POLICYINFO_new()) == NULL) { ASN1_OBJECT_free(policy); return 0; } pinfo->policyid = policy; if (!OSSL_CMP_CTX_push0_policy(ctx, pinfo)) { CMP_err1("cannot add policy with OID '%s'", opt_policy_oids); POLICYINFO_free(pinfo); return 0; } opt_policy_oids = next; } if (opt_popo >= OSSL_CRMF_POPO_NONE) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_POPO_METHOD, opt_popo); if (opt_oldcert != NULL) { if (opt_cmd == CMP_GENM) { CMP_warn("-oldcert option is ignored for command 'genm'"); } else { X509 *oldcert = load_cert_pwd(opt_oldcert, opt_keypass, opt_cmd == CMP_KUR ? "certificate to be updated" : opt_cmd == CMP_RR ? "certificate to be revoked" : "reference certificate (oldcert)"); /* opt_keypass needed if opt_oldcert is an encrypted PKCS#12 file */ if (oldcert == NULL) return 0; if (!OSSL_CMP_CTX_set1_oldCert(ctx, oldcert)) { X509_free(oldcert); CMP_err("out of memory"); return 0; } X509_free(oldcert); } } cleanse(opt_keypass); if (opt_revreason > CRL_REASON_NONE) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_REVOCATION_REASON, opt_revreason); return 1; oom: CMP_err("out of memory"); exts_err: sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free); X509_REQ_free(csr); return 0; } static int handle_opt_geninfo(OSSL_CMP_CTX *ctx) { long value; ASN1_OBJECT *type; ASN1_INTEGER *aint; ASN1_TYPE *val; OSSL_CMP_ITAV *itav; char *endstr; char *valptr = strchr(opt_geninfo, ':'); if (valptr == NULL) { CMP_err("missing ':' in -geninfo option"); return 0; } valptr[0] = '\0'; valptr++; if (OPENSSL_strncasecmp(valptr, "int:", 4) != 0) { CMP_err("missing 'int:' in -geninfo option"); return 0; } valptr += 4; value = strtol(valptr, &endstr, 10); if (endstr == valptr || *endstr != '\0') { CMP_err("cannot parse int in -geninfo option"); return 0; } type = OBJ_txt2obj(opt_geninfo, 1); if (type == NULL) { CMP_err("cannot parse OID in -geninfo option"); return 0; } if ((aint = ASN1_INTEGER_new()) == NULL) goto oom; val = ASN1_TYPE_new(); if (!ASN1_INTEGER_set(aint, value) || val == NULL) { ASN1_INTEGER_free(aint); goto oom; } ASN1_TYPE_set(val, V_ASN1_INTEGER, aint); itav = OSSL_CMP_ITAV_create(type, val); if (itav == NULL) { ASN1_TYPE_free(val); goto oom; } if (!OSSL_CMP_CTX_push0_geninfo_ITAV(ctx, itav)) { OSSL_CMP_ITAV_free(itav); return 0; } return 1; oom: ASN1_OBJECT_free(type); CMP_err("out of memory"); return 0; } /* * set up the client-side OSSL_CMP_CTX based on options from config file/CLI * while parsing options and checking their consistency. * Prints reason for error to bio_err. * Returns 1 on success, 0 on error */ static int setup_client_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine) { int ret = 0; char *host = NULL, *port = NULL, *path = NULL, *used_path = opt_path; #ifndef OPENSSL_NO_SOCK int portnum, ssl; static char server_port[32] = { '\0' }; const char *proxy_host = NULL; #endif char server_buf[200] = "mock server"; char proxy_buf[200] = ""; if (!opt_use_mock_srv && opt_rspin == NULL) { /* note: -port is not given */ #ifndef OPENSSL_NO_SOCK if (opt_server == NULL) { CMP_err("missing -server or -use_mock_srv or -rspin option"); goto err; } #else CMP_err("missing -use_mock_srv or -rspin option; -server option is not supported due to no-sock build"); goto err; #endif } #ifndef OPENSSL_NO_SOCK if (opt_server == NULL) { if (opt_proxy != NULL) CMP_warn("ignoring -proxy option since -server is not given"); if (opt_no_proxy != NULL) CMP_warn("ignoring -no_proxy option since -server is not given"); if (opt_tls_used) { CMP_warn("ignoring -tls_used option since -server is not given"); opt_tls_used = 0; } goto set_path; } if (!OSSL_HTTP_parse_url(opt_server, &ssl, NULL /* user */, &host, &port, &portnum, &path, NULL /* q */, NULL /* frag */)) { CMP_err1("cannot parse -server URL: %s", opt_server); goto err; } if (ssl && !opt_tls_used) { CMP_err("missing -tls_used option since -server URL indicates https"); goto err; } BIO_snprintf(server_port, sizeof(server_port), "%s", port); if (opt_path == NULL) used_path = path; if (!OSSL_CMP_CTX_set1_server(ctx, host) || !OSSL_CMP_CTX_set_serverPort(ctx, portnum)) goto oom; if (opt_proxy != NULL && !OSSL_CMP_CTX_set1_proxy(ctx, opt_proxy)) goto oom; if (opt_no_proxy != NULL && !OSSL_CMP_CTX_set1_no_proxy(ctx, opt_no_proxy)) goto oom; (void)BIO_snprintf(server_buf, sizeof(server_buf), "http%s://%s:%s/%s", opt_tls_used ? "s" : "", host, port, *used_path == '/' ? used_path + 1 : used_path); proxy_host = OSSL_HTTP_adapt_proxy(opt_proxy, opt_no_proxy, host, ssl); if (proxy_host != NULL) (void)BIO_snprintf(proxy_buf, sizeof(proxy_buf), " via %s", proxy_host); set_path: #endif if (!OSSL_CMP_CTX_set1_serverPath(ctx, used_path)) goto oom; if (!transform_opts()) goto err; if (opt_infotype_s != NULL) { char id_buf[100] = "id-it-"; strncat(id_buf, opt_infotype_s, sizeof(id_buf) - strlen(id_buf) - 1); if ((opt_infotype = OBJ_sn2nid(id_buf)) == NID_undef) { CMP_err("unknown OID name in -infotype option"); goto err; } } if (!setup_verification_ctx(ctx)) goto err; if (opt_keep_alive != 1) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_KEEP_ALIVE, opt_keep_alive); if (opt_total_timeout > 0 && opt_msg_timeout > 0 && opt_total_timeout < opt_msg_timeout) { CMP_err2("-total_timeout argument = %d must not be < %d (-msg_timeout)", opt_total_timeout, opt_msg_timeout); goto err; } if (opt_msg_timeout >= 0) /* must do this before setup_ssl_ctx() */ (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_MSG_TIMEOUT, opt_msg_timeout); if (opt_total_timeout >= 0) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_TOTAL_TIMEOUT, opt_total_timeout); if (opt_rspin != NULL) { rspin_in_use = 1; if (opt_reqin != NULL) CMP_warn("-reqin is ignored since -rspin is present"); } if (opt_reqin_new_tid && opt_reqin == NULL) CMP_warn("-reqin_new_tid is ignored since -reqin is not present"); if (opt_reqin != NULL || opt_reqout != NULL || opt_rspin != NULL || opt_rspout != NULL || opt_use_mock_srv) (void)OSSL_CMP_CTX_set_transfer_cb(ctx, read_write_req_resp); #ifndef OPENSSL_NO_SOCK if (opt_tls_used) { APP_HTTP_TLS_INFO *info; if (opt_tls_cert != NULL || opt_tls_key != NULL || opt_tls_keypass != NULL) { if (opt_tls_key == NULL) { CMP_err("missing -tls_key option"); goto err; } else if (opt_tls_cert == NULL) { CMP_err("missing -tls_cert option"); goto err; } } if ((info = OPENSSL_zalloc(sizeof(*info))) == NULL) goto err; (void)OSSL_CMP_CTX_set_http_cb_arg(ctx, info); info->ssl_ctx = setup_ssl_ctx(ctx, host, engine); info->server = host; host = NULL; /* prevent deallocation */ if ((info->port = OPENSSL_strdup(server_port)) == NULL) goto err; /* workaround for callback design flaw, see #17088: */ info->use_proxy = proxy_host != NULL; info->timeout = OSSL_CMP_CTX_get_option(ctx, OSSL_CMP_OPT_MSG_TIMEOUT); if (info->ssl_ctx == NULL) goto err; (void)OSSL_CMP_CTX_set_http_cb(ctx, app_http_tls_cb); } #endif if (!setup_protection_ctx(ctx, engine)) goto err; if (!setup_request_ctx(ctx, engine)) goto err; if (!set_name(opt_recipient, OSSL_CMP_CTX_set1_recipient, ctx, "recipient") || !set_name(opt_expect_sender, OSSL_CMP_CTX_set1_expected_sender, ctx, "expected sender")) goto err; if (opt_geninfo != NULL && !handle_opt_geninfo(ctx)) goto err; /* not printing earlier, to minimize confusion in case setup fails before */ if (opt_rspin != NULL) CMP_info2("will contact %s%s " "only if -rspin argument gives too few filenames", server_buf, proxy_buf); else CMP_info2("will contact %s%s", server_buf, proxy_buf); ret = 1; err: OPENSSL_free(host); OPENSSL_free(port); OPENSSL_free(path); return ret; oom: CMP_err("out of memory"); goto err; } /* * write out the given certificate to the output specified by bio. * Depending on options use either PEM or DER format. * Returns 1 on success, 0 on error */ static int write_cert(BIO *bio, X509 *cert) { if ((opt_certform == FORMAT_PEM && PEM_write_bio_X509(bio, cert)) || (opt_certform == FORMAT_ASN1 && i2d_X509_bio(bio, cert))) return 1; if (opt_certform != FORMAT_PEM && opt_certform != FORMAT_ASN1) BIO_printf(bio_err, "error: unsupported type '%s' for writing certificates\n", opt_certform_s); return 0; } /* * If destFile != NULL writes out a stack of certs to the given file. * In any case frees the certs. * Depending on options use either PEM or DER format, * where DER does not make much sense for writing more than one cert! * Returns number of written certificates on success, -1 on error. */ static int save_free_certs(OSSL_CMP_CTX *ctx, STACK_OF(X509) *certs, char *destFile, char *desc) { BIO *bio = NULL; int i; int n = sk_X509_num(certs); if (destFile == NULL) goto end; CMP_info3("received %d %s certificate(s), saving to file '%s'", n, desc, destFile); if (n > 1 && opt_certform != FORMAT_PEM) CMP_warn("saving more than one certificate in non-PEM format"); if (destFile == NULL || (bio = BIO_new(BIO_s_file())) == NULL || !BIO_write_filename(bio, (char *)destFile)) { CMP_err1("could not open file '%s' for writing", destFile); n = -1; goto end; } for (i = 0; i < n; i++) { if (!write_cert(bio, sk_X509_value(certs, i))) { CMP_err1("cannot write certificate to file '%s'", destFile); n = -1; goto end; } } end: BIO_free(bio); sk_X509_pop_free(certs, X509_free); return n; } static void print_itavs(STACK_OF(OSSL_CMP_ITAV) *itavs) { OSSL_CMP_ITAV *itav = NULL; char buf[128]; int i, r; int n = sk_OSSL_CMP_ITAV_num(itavs); /* itavs == NULL leads to 0 */ if (n == 0) { CMP_info("genp contains no ITAV"); return; } for (i = 0; i < n; i++) { itav = sk_OSSL_CMP_ITAV_value(itavs, i); r = OBJ_obj2txt(buf, 128, OSSL_CMP_ITAV_get0_type(itav), 0); if (r < 0) CMP_err("could not get ITAV details"); else if (r == 0) CMP_info("genp contains empty ITAV"); else CMP_info1("genp contains ITAV of type: %s", buf); } } static char opt_item[SECTION_NAME_MAX + 1]; /* get previous name from a comma or space-separated list of names */ static const char *prev_item(const char *opt, const char *end) { const char *beg; size_t len; if (end == opt) return NULL; beg = end; while (beg > opt) { --beg; if (beg[0] == ',' || isspace(_UC(beg[0]))) { ++beg; break; } } len = end - beg; if (len > SECTION_NAME_MAX) { CMP_warn3("using only first %d characters of section name starting with \"%.*s\"", SECTION_NAME_MAX, SECTION_NAME_MAX, beg); len = SECTION_NAME_MAX; } memcpy(opt_item, beg, len); opt_item[len] = '\0'; while (beg > opt) { --beg; if (beg[0] != ',' && !isspace(_UC(beg[0]))) { ++beg; break; } } return beg; } /* get str value for name from a comma-separated hierarchy of config sections */ static char *conf_get_string(const CONF *src_conf, const char *groups, const char *name) { char *res = NULL; const char *end = groups + strlen(groups); while ((end = prev_item(groups, end)) != NULL) { if ((res = NCONF_get_string(src_conf, opt_item, name)) != NULL) return res; ERR_clear_error(); } return res; } /* get long val for name from a comma-separated hierarchy of config sections */ static int conf_get_number_e(const CONF *conf_, const char *groups, const char *name, long *result) { char *str = conf_get_string(conf_, groups, name); char *tailptr; long res; if (str == NULL || *str == '\0') return 0; res = strtol(str, &tailptr, 10); if (res == LONG_MIN || res == LONG_MAX || *tailptr != '\0') return 0; *result = res; return 1; } /* * use the command line option table to read values from the CMP section * of openssl.cnf. Defaults are taken from the config file, they can be * overwritten on the command line. */ static int read_config(void) { unsigned int i; long num = 0; char *txt = NULL; const OPTIONS *opt; int start_opt = OPT_VERBOSITY - OPT_HELP; int start_idx = OPT_VERBOSITY - 2; /* * starting with offset OPT_VERBOSITY because OPT_CONFIG and OPT_SECTION * would not make sense within the config file. */ int n_options = OSSL_NELEM(cmp_options) - 1; for (opt = &cmp_options[start_opt], i = start_idx; opt->name != NULL; i++, opt++) if (!strcmp(opt->name, OPT_SECTION_STR) || !strcmp(opt->name, OPT_MORE_STR)) n_options--; OPENSSL_assert(OSSL_NELEM(cmp_vars) == n_options + OPT_PROV__FIRST + 1 - OPT_PROV__LAST + OPT_R__FIRST + 1 - OPT_R__LAST + OPT_V__FIRST + 1 - OPT_V__LAST); for (opt = &cmp_options[start_opt], i = start_idx; opt->name != NULL; i++, opt++) { int provider_option = (OPT_PROV__FIRST <= opt->retval && opt->retval < OPT_PROV__LAST); int rand_state_option = (OPT_R__FIRST <= opt->retval && opt->retval < OPT_R__LAST); int verification_option = (OPT_V__FIRST <= opt->retval && opt->retval < OPT_V__LAST); if (strcmp(opt->name, OPT_SECTION_STR) == 0 || strcmp(opt->name, OPT_MORE_STR) == 0) { i--; continue; } if (provider_option || rand_state_option || verification_option) i--; switch (opt->valtype) { case '-': case 'p': case 'n': case 'N': case 'l': if (!conf_get_number_e(conf, opt_section, opt->name, &num)) { ERR_clear_error(); continue; /* option not provided */ } if (opt->valtype == 'p' && num <= 0) { opt_printf_stderr("Non-positive number \"%ld\" for config option -%s\n", num, opt->name); return -1; } if (opt->valtype == 'N' && num < 0) { opt_printf_stderr("Negative number \"%ld\" for config option -%s\n", num, opt->name); return -1; } break; case 's': case '>': case 'M': txt = conf_get_string(conf, opt_section, opt->name); if (txt == NULL) { ERR_clear_error(); continue; /* option not provided */ } break; default: CMP_err2("internal: unsupported type '%c' for option '%s'", opt->valtype, opt->name); return 0; break; } if (provider_option || verification_option) { int conf_argc = 1; char *conf_argv[3]; char arg1[82]; BIO_snprintf(arg1, 81, "-%s", (char *)opt->name); conf_argv[0] = prog; conf_argv[1] = arg1; if (opt->valtype == '-') { if (num != 0) conf_argc = 2; } else { conf_argc = 3; conf_argv[2] = conf_get_string(conf, opt_section, opt->name); /* not NULL */ } if (conf_argc > 1) { (void)opt_init(conf_argc, conf_argv, cmp_options); if (provider_option ? !opt_provider(opt_next()) : !opt_verify(opt_next(), vpm)) { CMP_err2("for option '%s' in config file section '%s'", opt->name, opt_section); return 0; } } } else { switch (opt->valtype) { case '-': case 'p': case 'n': case 'N': if (num < INT_MIN || INT_MAX < num) { BIO_printf(bio_err, "integer value out of range for option '%s'\n", opt->name); return 0; } *cmp_vars[i].num = (int)num; break; case 'l': *cmp_vars[i].num_long = num; break; default: if (txt != NULL && txt[0] == '\0') txt = NULL; /* reset option on empty string input */ *cmp_vars[i].txt = txt; break; } } } return 1; } static char *opt_str(void) { char *arg = opt_arg(); if (arg[0] == '\0') { CMP_warn1("%s option argument is empty string, resetting option", opt_flag()); arg = NULL; } else if (arg[0] == '-') { CMP_warn1("%s option argument starts with hyphen", opt_flag()); } return arg; } /* returns 1 on success, 0 on error, -1 on -help (i.e., stop with success) */ static int get_opts(int argc, char **argv) { OPTION_CHOICE o; prog = opt_init(argc, argv, cmp_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); return 0; case OPT_HELP: opt_help(cmp_options); return -1; case OPT_CONFIG: /* has already been handled */ case OPT_SECTION: /* has already been handled */ break; case OPT_VERBOSITY: if (!set_verbosity(opt_int_arg())) goto opthelp; break; #ifndef OPENSSL_NO_SOCK case OPT_SERVER: opt_server = opt_str(); break; case OPT_PROXY: opt_proxy = opt_str(); break; case OPT_NO_PROXY: opt_no_proxy = opt_str(); break; #endif case OPT_RECIPIENT: opt_recipient = opt_str(); break; case OPT_PATH: opt_path = opt_str(); break; case OPT_KEEP_ALIVE: opt_keep_alive = opt_int_arg(); if (opt_keep_alive > 2) { CMP_err("-keep_alive argument must be 0, 1, or 2"); goto opthelp; } break; case OPT_MSG_TIMEOUT: opt_msg_timeout = opt_int_arg(); break; case OPT_TOTAL_TIMEOUT: opt_total_timeout = opt_int_arg(); break; #ifndef OPENSSL_NO_SOCK case OPT_TLS_USED: opt_tls_used = 1; break; case OPT_TLS_CERT: opt_tls_cert = opt_str(); break; case OPT_TLS_KEY: opt_tls_key = opt_str(); break; case OPT_TLS_KEYPASS: opt_tls_keypass = opt_str(); break; case OPT_TLS_EXTRA: opt_tls_extra = opt_str(); break; case OPT_TLS_TRUSTED: opt_tls_trusted = opt_str(); break; case OPT_TLS_HOST: opt_tls_host = opt_str(); break; #endif case OPT_REF: opt_ref = opt_str(); break; case OPT_SECRET: opt_secret = opt_str(); break; case OPT_CERT: opt_cert = opt_str(); break; case OPT_OWN_TRUSTED: opt_own_trusted = opt_str(); break; case OPT_KEY: opt_key = opt_str(); break; case OPT_KEYPASS: opt_keypass = opt_str(); break; case OPT_DIGEST: opt_digest = opt_str(); break; case OPT_MAC: opt_mac = opt_str(); break; case OPT_EXTRACERTS: opt_extracerts = opt_str(); break; case OPT_UNPROTECTED_REQUESTS: opt_unprotected_requests = 1; break; case OPT_TRUSTED: opt_trusted = opt_str(); break; case OPT_UNTRUSTED: opt_untrusted = opt_str(); break; case OPT_SRVCERT: opt_srvcert = opt_str(); break; case OPT_EXPECT_SENDER: opt_expect_sender = opt_str(); break; case OPT_IGNORE_KEYUSAGE: opt_ignore_keyusage = 1; break; case OPT_UNPROTECTED_ERRORS: opt_unprotected_errors = 1; break; case OPT_EXTRACERTSOUT: opt_extracertsout = opt_str(); break; case OPT_CACERTSOUT: opt_cacertsout = opt_str(); break; case OPT_V_CASES: if (!opt_verify(o, vpm)) goto opthelp; break; case OPT_CMD: opt_cmd_s = opt_str(); break; case OPT_INFOTYPE: opt_infotype_s = opt_str(); break; case OPT_GENINFO: opt_geninfo = opt_str(); break; case OPT_NEWKEY: opt_newkey = opt_str(); break; case OPT_NEWKEYPASS: opt_newkeypass = opt_str(); break; case OPT_SUBJECT: opt_subject = opt_str(); break; case OPT_ISSUER: opt_issuer = opt_str(); break; case OPT_DAYS: opt_days = opt_int_arg(); break; case OPT_REQEXTS: opt_reqexts = opt_str(); break; case OPT_SANS: opt_sans = opt_str(); break; case OPT_SAN_NODEFAULT: opt_san_nodefault = 1; break; case OPT_POLICIES: opt_policies = opt_str(); break; case OPT_POLICY_OIDS: opt_policy_oids = opt_str(); break; case OPT_POLICY_OIDS_CRITICAL: opt_policy_oids_critical = 1; break; case OPT_POPO: opt_popo = opt_int_arg(); if (opt_popo < OSSL_CRMF_POPO_NONE || opt_popo > OSSL_CRMF_POPO_KEYENC) { CMP_err("invalid popo spec. Valid values are -1 .. 2"); goto opthelp; } break; case OPT_CSR: - opt_csr = opt_arg(); + opt_csr = opt_str(); break; case OPT_OUT_TRUSTED: opt_out_trusted = opt_str(); break; case OPT_IMPLICIT_CONFIRM: opt_implicit_confirm = 1; break; case OPT_DISABLE_CONFIRM: opt_disable_confirm = 1; break; case OPT_CERTOUT: opt_certout = opt_str(); break; case OPT_CHAINOUT: opt_chainout = opt_str(); break; case OPT_OLDCERT: opt_oldcert = opt_str(); break; case OPT_REVREASON: opt_revreason = opt_int_arg(); if (opt_revreason < CRL_REASON_NONE || opt_revreason > CRL_REASON_AA_COMPROMISE || opt_revreason == 7) { CMP_err("invalid revreason. Valid values are -1 .. 6, 8 .. 10"); goto opthelp; } break; case OPT_CERTFORM: opt_certform_s = opt_str(); break; case OPT_KEYFORM: opt_keyform_s = opt_str(); break; case OPT_OTHERPASS: opt_otherpass = opt_str(); break; #ifndef OPENSSL_NO_ENGINE case OPT_ENGINE: opt_engine = opt_str(); break; #endif case OPT_PROV_CASES: if (!opt_provider(o)) goto opthelp; break; case OPT_R_CASES: if (!opt_rand(o)) goto opthelp; break; case OPT_BATCH: opt_batch = 1; break; case OPT_REPEAT: opt_repeat = opt_int_arg(); break; case OPT_REQIN: opt_reqin = opt_str(); break; case OPT_REQIN_NEW_TID: opt_reqin_new_tid = 1; break; case OPT_REQOUT: opt_reqout = opt_str(); break; case OPT_RSPIN: opt_rspin = opt_str(); break; case OPT_RSPOUT: opt_rspout = opt_str(); break; case OPT_USE_MOCK_SRV: opt_use_mock_srv = 1; break; #ifndef OPENSSL_NO_SOCK case OPT_PORT: opt_port = opt_str(); break; case OPT_MAX_MSGS: opt_max_msgs = opt_int_arg(); break; #endif case OPT_SRV_REF: opt_srv_ref = opt_str(); break; case OPT_SRV_SECRET: opt_srv_secret = opt_str(); break; case OPT_SRV_CERT: opt_srv_cert = opt_str(); break; case OPT_SRV_KEY: opt_srv_key = opt_str(); break; case OPT_SRV_KEYPASS: opt_srv_keypass = opt_str(); break; case OPT_SRV_TRUSTED: opt_srv_trusted = opt_str(); break; case OPT_SRV_UNTRUSTED: opt_srv_untrusted = opt_str(); break; case OPT_RSP_CERT: opt_rsp_cert = opt_str(); break; case OPT_RSP_EXTRACERTS: opt_rsp_extracerts = opt_str(); break; case OPT_RSP_CAPUBS: opt_rsp_capubs = opt_str(); break; case OPT_POLL_COUNT: opt_poll_count = opt_int_arg(); break; case OPT_CHECK_AFTER: opt_check_after = opt_int_arg(); break; case OPT_GRANT_IMPLICITCONF: opt_grant_implicitconf = 1; break; case OPT_PKISTATUS: opt_pkistatus = opt_int_arg(); break; case OPT_FAILURE: opt_failure = opt_int_arg(); break; case OPT_FAILUREBITS: opt_failurebits = opt_int_arg(); break; case OPT_STATUSSTRING: opt_statusstring = opt_str(); break; case OPT_SEND_ERROR: opt_send_error = 1; break; case OPT_SEND_UNPROTECTED: opt_send_unprotected = 1; break; case OPT_SEND_UNPROT_ERR: opt_send_unprot_err = 1; break; case OPT_ACCEPT_UNPROTECTED: opt_accept_unprotected = 1; break; case OPT_ACCEPT_UNPROT_ERR: opt_accept_unprot_err = 1; break; case OPT_ACCEPT_RAVERIFIED: opt_accept_raverified = 1; break; } } /* No extra args. */ argc = opt_num_rest(); argv = opt_rest(); if (argc != 0) goto opthelp; return 1; } #ifndef OPENSSL_NO_SOCK static int cmp_server(OSSL_CMP_CTX *srv_cmp_ctx) { BIO *acbio; BIO *cbio = NULL; int keep_alive = 0; int msgs = 0; int retry = 1; int ret = 1; if ((acbio = http_server_init_bio(prog, opt_port)) == NULL) return 0; while (opt_max_msgs <= 0 || msgs < opt_max_msgs) { char *path = NULL; OSSL_CMP_MSG *req = NULL; OSSL_CMP_MSG *resp = NULL; ret = http_server_get_asn1_req(ASN1_ITEM_rptr(OSSL_CMP_MSG), (ASN1_VALUE **)&req, &path, &cbio, acbio, &keep_alive, prog, opt_port, 0, 0); if (ret == 0) { /* no request yet */ if (retry) { ossl_sleep(1000); retry = 0; continue; } ret = 0; goto next; } if (ret++ == -1) /* fatal error */ break; ret = 0; msgs++; if (req != NULL) { if (strcmp(path, "") != 0 && strcmp(path, "pkix/") != 0) { (void)http_server_send_status(cbio, 404, "Not Found"); CMP_err1("expecting empty path or 'pkix/' but got '%s'", path); OPENSSL_free(path); OSSL_CMP_MSG_free(req); goto next; } OPENSSL_free(path); resp = OSSL_CMP_CTX_server_perform(cmp_ctx, req); OSSL_CMP_MSG_free(req); if (resp == NULL) { (void)http_server_send_status(cbio, 500, "Internal Server Error"); break; /* treated as fatal error */ } ret = http_server_send_asn1_resp(cbio, keep_alive, "application/pkixcmp", ASN1_ITEM_rptr(OSSL_CMP_MSG), (const ASN1_VALUE *)resp); OSSL_CMP_MSG_free(resp); if (!ret) break; /* treated as fatal error */ } next: if (!ret) { /* on transmission error, cancel CMP transaction */ (void)OSSL_CMP_CTX_set1_transactionID(srv_cmp_ctx, NULL); (void)OSSL_CMP_CTX_set1_senderNonce(srv_cmp_ctx, NULL); } if (!ret || !keep_alive || OSSL_CMP_CTX_get_status(srv_cmp_ctx) != OSSL_CMP_PKISTATUS_trans /* transaction closed by OSSL_CMP_CTX_server_perform() */) { BIO_free_all(cbio); cbio = NULL; } } BIO_free_all(cbio); BIO_free_all(acbio); return ret; } #endif static void print_status(void) { /* print PKIStatusInfo */ int status = OSSL_CMP_CTX_get_status(cmp_ctx); char *buf = app_malloc(OSSL_CMP_PKISI_BUFLEN, "PKIStatusInfo buf"); const char *string = OSSL_CMP_CTX_snprint_PKIStatus(cmp_ctx, buf, OSSL_CMP_PKISI_BUFLEN); const char *from = "", *server = ""; #ifndef OPENSSL_NO_SOCK if (opt_server != NULL) { from = " from "; server = opt_server; } #endif CMP_print(bio_err, status == OSSL_CMP_PKISTATUS_accepted ? OSSL_CMP_LOG_INFO : status == OSSL_CMP_PKISTATUS_rejection || status == OSSL_CMP_PKISTATUS_waiting ? OSSL_CMP_LOG_ERR : OSSL_CMP_LOG_WARNING, status == OSSL_CMP_PKISTATUS_accepted ? "info" : status == OSSL_CMP_PKISTATUS_rejection ? "server error" : status == OSSL_CMP_PKISTATUS_waiting ? "internal error" : "warning", "received%s%s %s", from, server, string != NULL ? string : ""); OPENSSL_free(buf); } int cmp_main(int argc, char **argv) { char *configfile = NULL; int i; X509 *newcert = NULL; ENGINE *engine = NULL; OSSL_CMP_CTX *srv_cmp_ctx = NULL; int ret = 0; /* default: failure */ prog = opt_appname(argv[0]); if (argc <= 1) { opt_help(cmp_options); goto err; } /* * handle options -config, -section, and -verbosity upfront * to take effect for other options */ for (i = 1; i < argc - 1; i++) { if (*argv[i] == '-') { if (!strcmp(argv[i] + 1, cmp_options[OPT_CONFIG - OPT_HELP].name)) opt_config = argv[++i]; else if (!strcmp(argv[i] + 1, cmp_options[OPT_SECTION - OPT_HELP].name)) opt_section = argv[++i]; else if (strcmp(argv[i] + 1, cmp_options[OPT_VERBOSITY - OPT_HELP].name) == 0 && !set_verbosity(atoi(argv[++i]))) goto err; } } if (opt_section[0] == '\0') /* empty string */ opt_section = DEFAULT_SECTION; vpm = X509_VERIFY_PARAM_new(); if (vpm == NULL) { CMP_err("out of memory"); goto err; } /* read default values for options from config file */ configfile = opt_config != NULL ? opt_config : default_config_file; if (configfile != NULL && configfile[0] != '\0' /* non-empty string */ && (configfile != default_config_file || access(configfile, F_OK) != -1)) { CMP_info2("using section(s) '%s' of OpenSSL configuration file '%s'", opt_section, configfile); conf = app_load_config(configfile); if (conf == NULL) { goto err; } else { if (strcmp(opt_section, CMP_SECTION) == 0) { /* default */ if (!NCONF_get_section(conf, opt_section)) CMP_info2("no [%s] section found in config file '%s';" " will thus use just [default] and unnamed section if present", opt_section, configfile); } else { const char *end = opt_section + strlen(opt_section); while ((end = prev_item(opt_section, end)) != NULL) { if (!NCONF_get_section(conf, opt_item)) { CMP_err2("no [%s] section found in config file '%s'", opt_item, configfile); goto err; } } } ret = read_config(); if (!set_verbosity(opt_verbosity)) /* just for checking range */ ret = -1; if (ret <= 0) { if (ret == -1) BIO_printf(bio_err, "Use -help for summary.\n"); goto err; } } } (void)BIO_flush(bio_err); /* prevent interference with opt_help() */ ret = get_opts(argc, argv); if (ret <= 0) goto err; ret = 0; if (!app_RAND_load()) goto err; if (opt_batch) set_base_ui_method(UI_null()); if (opt_engine != NULL) { engine = setup_engine_methods(opt_engine, 0 /* not: ENGINE_METHOD_ALL */, 0); if (engine == NULL) { CMP_err1("cannot load engine %s", opt_engine); goto err; } } cmp_ctx = OSSL_CMP_CTX_new(app_get0_libctx(), app_get0_propq()); if (cmp_ctx == NULL) goto err; OSSL_CMP_CTX_set_log_verbosity(cmp_ctx, opt_verbosity); if (!OSSL_CMP_CTX_set_log_cb(cmp_ctx, print_to_bio_out)) { CMP_err1("cannot set up error reporting and logging for %s", prog); goto err; } #ifndef OPENSSL_NO_SOCK if ((opt_tls_cert != NULL || opt_tls_key != NULL || opt_tls_keypass != NULL || opt_tls_extra != NULL || opt_tls_trusted != NULL || opt_tls_host != NULL) && !opt_tls_used) CMP_warn("Ingnoring TLS options(s) since -tls_used is not given"); if (opt_port != NULL) { if (opt_tls_used) { CMP_err("-tls_used option not supported with -port option"); goto err; } if (opt_server != NULL || opt_use_mock_srv) { CMP_err("The -port option excludes -server and -use_mock_srv"); goto err; } if (opt_reqin != NULL || opt_reqout != NULL) { CMP_err("The -port option does not support -reqin and -reqout"); goto err; } if (opt_rspin != NULL || opt_rspout != NULL) { CMP_err("The -port option does not support -rspin and -rspout"); goto err; } } if (opt_server != NULL && opt_use_mock_srv) { CMP_err("cannot use both -server and -use_mock_srv options"); goto err; } #endif if (opt_use_mock_srv #ifndef OPENSSL_NO_SOCK || opt_port != NULL #endif ) { OSSL_CMP_SRV_CTX *srv_ctx; if ((srv_ctx = setup_srv_ctx(engine)) == NULL) goto err; srv_cmp_ctx = OSSL_CMP_SRV_CTX_get0_cmp_ctx(srv_ctx); OSSL_CMP_CTX_set_transfer_cb_arg(cmp_ctx, srv_ctx); if (!OSSL_CMP_CTX_set_log_cb(srv_cmp_ctx, print_to_bio_err)) { CMP_err1("cannot set up error reporting and logging for %s", prog); goto err; } OSSL_CMP_CTX_set_log_verbosity(srv_cmp_ctx, opt_verbosity); } #ifndef OPENSSL_NO_SOCK if (opt_tls_used && (opt_use_mock_srv || opt_server == NULL)) { CMP_warn("ignoring -tls_used option since -use_mock_srv is given or -server is not given"); opt_tls_used = 0; } if (opt_port != NULL) { /* act as very basic CMP HTTP server */ ret = cmp_server(srv_cmp_ctx); goto err; } /* act as CMP client, possibly using internal mock server */ if (opt_rspin != NULL) { if (opt_server != NULL) CMP_warn("-server option is not used if enough filenames given for -rspin"); if (opt_use_mock_srv) CMP_warn("-use_mock_srv option is not used if enough filenames given for -rspin"); } #endif if (!setup_client_ctx(cmp_ctx, engine)) { CMP_err("cannot set up CMP context"); goto err; } for (i = 0; i < opt_repeat; i++) { /* everything is ready, now connect and perform the command! */ switch (opt_cmd) { case CMP_IR: newcert = OSSL_CMP_exec_IR_ses(cmp_ctx); if (newcert != NULL) ret = 1; break; case CMP_KUR: newcert = OSSL_CMP_exec_KUR_ses(cmp_ctx); if (newcert != NULL) ret = 1; break; case CMP_CR: newcert = OSSL_CMP_exec_CR_ses(cmp_ctx); if (newcert != NULL) ret = 1; break; case CMP_P10CR: newcert = OSSL_CMP_exec_P10CR_ses(cmp_ctx); if (newcert != NULL) ret = 1; break; case CMP_RR: ret = OSSL_CMP_exec_RR_ses(cmp_ctx); break; case CMP_GENM: { STACK_OF(OSSL_CMP_ITAV) *itavs; if (opt_infotype != NID_undef) { OSSL_CMP_ITAV *itav = OSSL_CMP_ITAV_create(OBJ_nid2obj(opt_infotype), NULL); if (itav == NULL) goto err; OSSL_CMP_CTX_push0_genm_ITAV(cmp_ctx, itav); } if ((itavs = OSSL_CMP_exec_GENM_ses(cmp_ctx)) != NULL) { print_itavs(itavs); sk_OSSL_CMP_ITAV_pop_free(itavs, OSSL_CMP_ITAV_free); ret = 1; } break; } default: break; } if (OSSL_CMP_CTX_get_status(cmp_ctx) < OSSL_CMP_PKISTATUS_accepted) goto err; /* we got no response, maybe even did not send request */ print_status(); if (save_free_certs(cmp_ctx, OSSL_CMP_CTX_get1_extraCertsIn(cmp_ctx), opt_extracertsout, "extra") < 0) ret = 0; if (!ret) goto err; ret = 0; if (save_free_certs(cmp_ctx, OSSL_CMP_CTX_get1_caPubs(cmp_ctx), opt_cacertsout, "CA") < 0) goto err; if (newcert != NULL) { STACK_OF(X509) *certs = sk_X509_new_null(); if (!X509_add_cert(certs, newcert, X509_ADD_FLAG_UP_REF)) { sk_X509_free(certs); goto err; } if (save_free_certs(cmp_ctx, certs, opt_certout, "enrolled") < 0) goto err; } if (save_free_certs(cmp_ctx, OSSL_CMP_CTX_get1_newChain(cmp_ctx), opt_chainout, "chain") < 0) goto err; if (!OSSL_CMP_CTX_reinit(cmp_ctx)) goto err; } ret = 1; err: /* in case we ended up here on error without proper cleaning */ cleanse(opt_keypass); cleanse(opt_newkeypass); cleanse(opt_otherpass); #ifndef OPENSSL_NO_SOCK cleanse(opt_tls_keypass); #endif cleanse(opt_secret); cleanse(opt_srv_keypass); cleanse(opt_srv_secret); if (ret != 1) OSSL_CMP_CTX_print_errors(cmp_ctx); if (cmp_ctx != NULL) { #ifndef OPENSSL_NO_SOCK APP_HTTP_TLS_INFO *info = OSSL_CMP_CTX_get_http_cb_arg(cmp_ctx); #endif ossl_cmp_mock_srv_free(OSSL_CMP_CTX_get_transfer_cb_arg(cmp_ctx)); X509_STORE_free(OSSL_CMP_CTX_get_certConf_cb_arg(cmp_ctx)); /* cannot free info already here, as it may be used indirectly by: */ OSSL_CMP_CTX_free(cmp_ctx); #ifndef OPENSSL_NO_SOCK if (info != NULL) { OPENSSL_free((char *)info->server); OPENSSL_free((char *)info->port); APP_HTTP_TLS_INFO_free(info); } #endif } X509_VERIFY_PARAM_free(vpm); release_engine(engine); NCONF_free(conf); /* must not do as long as opt_... variables are used */ OSSL_CMP_log_close(); return ret == 0 ? EXIT_FAILURE : EXIT_SUCCESS; /* ret == -1 for -help */ } diff --git a/apps/lib/apps.c b/apps/lib/apps.c index 4baeb352fedf..572f6a3f8f28 100644 --- a/apps/lib/apps.c +++ b/apps/lib/apps.c @@ -1,3397 +1,3396 @@ /* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS) /* * On VMS, you need to define this to get the declaration of fileno(). The * value 2 is to make sure no function defined in POSIX-2 is left undefined. */ # define _POSIX_C_SOURCE 2 #endif #ifndef OPENSSL_NO_ENGINE /* We need to use some deprecated APIs */ # define OPENSSL_SUPPRESS_DEPRECATED # include #endif #include #include #include #include #ifndef OPENSSL_NO_POSIX_IO # include # include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "s_apps.h" #include "apps.h" #ifdef _WIN32 static int WIN32_rename(const char *from, const char *to); # define rename(from,to) WIN32_rename((from),(to)) #endif #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) # include #endif #if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32) || defined(__BORLANDC__) # define _kbhit kbhit #endif static BIO *bio_open_default_(const char *filename, char mode, int format, int quiet); #define PASS_SOURCE_SIZE_MAX 4 DEFINE_STACK_OF(CONF) typedef struct { const char *name; unsigned long flag; unsigned long mask; } NAME_EX_TBL; static int set_table_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL * in_tbl); static int set_multi_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL * in_tbl); static int load_key_certs_crls_suppress(const char *uri, int format, int maybe_stdin, const char *pass, const char *desc, EVP_PKEY **ppkey, EVP_PKEY **ppubkey, EVP_PKEY **pparams, X509 **pcert, STACK_OF(X509) **pcerts, X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls, int suppress_decode_errors); int app_init(long mesgwin); int chopup_args(ARGS *arg, char *buf) { int quoted; char c = '\0', *p = NULL; arg->argc = 0; if (arg->size == 0) { arg->size = 20; arg->argv = app_malloc(sizeof(*arg->argv) * arg->size, "argv space"); } for (p = buf;;) { /* Skip whitespace. */ while (*p && isspace(_UC(*p))) p++; if (*p == '\0') break; /* The start of something good :-) */ if (arg->argc >= arg->size) { char **tmp; arg->size += 20; tmp = OPENSSL_realloc(arg->argv, sizeof(*arg->argv) * arg->size); if (tmp == NULL) return 0; arg->argv = tmp; } quoted = *p == '\'' || *p == '"'; if (quoted) c = *p++; arg->argv[arg->argc++] = p; /* now look for the end of this */ if (quoted) { while (*p && *p != c) p++; *p++ = '\0'; } else { while (*p && !isspace(_UC(*p))) p++; if (*p) *p++ = '\0'; } } arg->argv[arg->argc] = NULL; return 1; } #ifndef APP_INIT int app_init(long mesgwin) { return 1; } #endif int ctx_set_verify_locations(SSL_CTX *ctx, const char *CAfile, int noCAfile, const char *CApath, int noCApath, const char *CAstore, int noCAstore) { if (CAfile == NULL && CApath == NULL && CAstore == NULL) { if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0) return 0; if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0) return 0; if (!noCAstore && SSL_CTX_set_default_verify_store(ctx) <= 0) return 0; return 1; } if (CAfile != NULL && !SSL_CTX_load_verify_file(ctx, CAfile)) return 0; if (CApath != NULL && !SSL_CTX_load_verify_dir(ctx, CApath)) return 0; if (CAstore != NULL && !SSL_CTX_load_verify_store(ctx, CAstore)) return 0; return 1; } #ifndef OPENSSL_NO_CT int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path) { if (path == NULL) return SSL_CTX_set_default_ctlog_list_file(ctx); return SSL_CTX_set_ctlog_list_file(ctx, path); } #endif static unsigned long nmflag = 0; static char nmflag_set = 0; int set_nameopt(const char *arg) { int ret = set_name_ex(&nmflag, arg); if (ret) nmflag_set = 1; return ret; } unsigned long get_nameopt(void) { return (nmflag_set) ? nmflag : XN_FLAG_ONELINE; } void dump_cert_text(BIO *out, X509 *x) { print_name(out, "subject=", X509_get_subject_name(x)); print_name(out, "issuer=", X509_get_issuer_name(x)); } int wrap_password_callback(char *buf, int bufsiz, int verify, void *userdata) { return password_callback(buf, bufsiz, verify, (PW_CB_DATA *)userdata); } static char *app_get_pass(const char *arg, int keepbio); char *get_passwd(const char *pass, const char *desc) { char *result = NULL; if (desc == NULL) desc = ""; if (!app_passwd(pass, NULL, &result, NULL)) BIO_printf(bio_err, "Error getting password for %s\n", desc); if (pass != NULL && result == NULL) { BIO_printf(bio_err, "Trying plain input string (better precede with 'pass:')\n"); result = OPENSSL_strdup(pass); if (result == NULL) BIO_printf(bio_err, "Out of memory getting password for %s\n", desc); } return result; } int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2) { int same = arg1 != NULL && arg2 != NULL && strcmp(arg1, arg2) == 0; if (arg1 != NULL) { *pass1 = app_get_pass(arg1, same); if (*pass1 == NULL) return 0; } else if (pass1 != NULL) { *pass1 = NULL; } if (arg2 != NULL) { *pass2 = app_get_pass(arg2, same ? 2 : 0); if (*pass2 == NULL) return 0; } else if (pass2 != NULL) { *pass2 = NULL; } return 1; } static char *app_get_pass(const char *arg, int keepbio) { static BIO *pwdbio = NULL; char *tmp, tpass[APP_PASS_LEN]; int i; /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */ if (strncmp(arg, "pass:", 5) == 0) return OPENSSL_strdup(arg + 5); if (strncmp(arg, "env:", 4) == 0) { tmp = getenv(arg + 4); if (tmp == NULL) { BIO_printf(bio_err, "No environment variable %s\n", arg + 4); return NULL; } return OPENSSL_strdup(tmp); } if (!keepbio || pwdbio == NULL) { if (strncmp(arg, "file:", 5) == 0) { pwdbio = BIO_new_file(arg + 5, "r"); if (pwdbio == NULL) { BIO_printf(bio_err, "Can't open file %s\n", arg + 5); return NULL; } #if !defined(_WIN32) /* * Under _WIN32, which covers even Win64 and CE, file * descriptors referenced by BIO_s_fd are not inherited * by child process and therefore below is not an option. * It could have been an option if bss_fd.c was operating * on real Windows descriptors, such as those obtained * with CreateFile. */ } else if (strncmp(arg, "fd:", 3) == 0) { BIO *btmp; i = atoi(arg + 3); if (i >= 0) pwdbio = BIO_new_fd(i, BIO_NOCLOSE); if ((i < 0) || pwdbio == NULL) { BIO_printf(bio_err, "Can't access file descriptor %s\n", arg + 3); return NULL; } /* * Can't do BIO_gets on an fd BIO so add a buffering BIO */ btmp = BIO_new(BIO_f_buffer()); if (btmp == NULL) { BIO_free_all(pwdbio); pwdbio = NULL; BIO_printf(bio_err, "Out of memory\n"); return NULL; } pwdbio = BIO_push(btmp, pwdbio); #endif } else if (strcmp(arg, "stdin") == 0) { unbuffer(stdin); pwdbio = dup_bio_in(FORMAT_TEXT); if (pwdbio == NULL) { BIO_printf(bio_err, "Can't open BIO for stdin\n"); return NULL; } } else { /* argument syntax error; do not reveal too much about arg */ tmp = strchr(arg, ':'); if (tmp == NULL || tmp - arg > PASS_SOURCE_SIZE_MAX) BIO_printf(bio_err, "Invalid password argument, missing ':' within the first %d chars\n", PASS_SOURCE_SIZE_MAX + 1); else BIO_printf(bio_err, "Invalid password argument, starting with \"%.*s\"\n", (int)(tmp - arg + 1), arg); return NULL; } } i = BIO_gets(pwdbio, tpass, APP_PASS_LEN); if (keepbio != 1) { BIO_free_all(pwdbio); pwdbio = NULL; } if (i <= 0) { BIO_printf(bio_err, "Error reading password from BIO\n"); return NULL; } tmp = strchr(tpass, '\n'); if (tmp != NULL) *tmp = 0; return OPENSSL_strdup(tpass); } CONF *app_load_config_bio(BIO *in, const char *filename) { long errorline = -1; CONF *conf; int i; conf = NCONF_new_ex(app_get0_libctx(), NULL); i = NCONF_load_bio(conf, in, &errorline); if (i > 0) return conf; if (errorline <= 0) { BIO_printf(bio_err, "%s: Can't load ", opt_getprog()); } else { BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(), errorline); } if (filename != NULL) BIO_printf(bio_err, "config file \"%s\"\n", filename); else BIO_printf(bio_err, "config input"); NCONF_free(conf); return NULL; } CONF *app_load_config_verbose(const char *filename, int verbose) { if (verbose) { if (*filename == '\0') BIO_printf(bio_err, "No configuration used\n"); else BIO_printf(bio_err, "Using configuration from %s\n", filename); } return app_load_config_internal(filename, 0); } CONF *app_load_config_internal(const char *filename, int quiet) { BIO *in; CONF *conf; if (filename == NULL || *filename != '\0') { if ((in = bio_open_default_(filename, 'r', FORMAT_TEXT, quiet)) == NULL) return NULL; conf = app_load_config_bio(in, filename); BIO_free(in); } else { /* Return empty config if filename is empty string. */ conf = NCONF_new_ex(app_get0_libctx(), NULL); } return conf; } int app_load_modules(const CONF *config) { CONF *to_free = NULL; if (config == NULL) config = to_free = app_load_config_quiet(default_config_file); if (config == NULL) return 1; if (CONF_modules_load(config, NULL, 0) <= 0) { BIO_printf(bio_err, "Error configuring OpenSSL modules\n"); ERR_print_errors(bio_err); NCONF_free(to_free); return 0; } NCONF_free(to_free); return 1; } int add_oid_section(CONF *conf) { char *p; STACK_OF(CONF_VALUE) *sktmp; CONF_VALUE *cnf; int i; if ((p = NCONF_get_string(conf, NULL, "oid_section")) == NULL) { ERR_clear_error(); return 1; } if ((sktmp = NCONF_get_section(conf, p)) == NULL) { BIO_printf(bio_err, "problem loading oid section %s\n", p); return 0; } for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) { cnf = sk_CONF_VALUE_value(sktmp, i); if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) { BIO_printf(bio_err, "problem creating object %s=%s\n", cnf->name, cnf->value); return 0; } } return 1; } CONF *app_load_config_modules(const char *configfile) { CONF *conf = NULL; if (configfile != NULL) { if ((conf = app_load_config_verbose(configfile, 1)) == NULL) return NULL; if (configfile != default_config_file && !app_load_modules(conf)) { NCONF_free(conf); conf = NULL; } } return conf; } #define IS_HTTP(uri) ((uri) != NULL \ && strncmp(uri, OSSL_HTTP_PREFIX, strlen(OSSL_HTTP_PREFIX)) == 0) #define IS_HTTPS(uri) ((uri) != NULL \ && strncmp(uri, OSSL_HTTPS_PREFIX, strlen(OSSL_HTTPS_PREFIX)) == 0) X509 *load_cert_pass(const char *uri, int format, int maybe_stdin, const char *pass, const char *desc) { X509 *cert = NULL; if (desc == NULL) desc = "certificate"; if (IS_HTTPS(uri)) BIO_printf(bio_err, "Loading %s over HTTPS is unsupported\n", desc); else if (IS_HTTP(uri)) cert = X509_load_http(uri, NULL, NULL, 0 /* timeout */); else (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc, NULL, NULL, NULL, &cert, NULL, NULL, NULL); if (cert == NULL) { BIO_printf(bio_err, "Unable to load %s\n", desc); ERR_print_errors(bio_err); } return cert; } X509_CRL *load_crl(const char *uri, int format, int maybe_stdin, const char *desc) { X509_CRL *crl = NULL; if (desc == NULL) desc = "CRL"; if (IS_HTTPS(uri)) BIO_printf(bio_err, "Loading %s over HTTPS is unsupported\n", desc); else if (IS_HTTP(uri)) crl = X509_CRL_load_http(uri, NULL, NULL, 0 /* timeout */); else (void)load_key_certs_crls(uri, format, maybe_stdin, NULL, desc, NULL, NULL, NULL, NULL, NULL, &crl, NULL); if (crl == NULL) { BIO_printf(bio_err, "Unable to load %s\n", desc); ERR_print_errors(bio_err); } return crl; } X509_REQ *load_csr(const char *file, int format, const char *desc) { X509_REQ *req = NULL; BIO *in; if (format == FORMAT_UNDEF) format = FORMAT_PEM; if (desc == NULL) desc = "CSR"; in = bio_open_default(file, 'r', format); if (in == NULL) goto end; if (format == FORMAT_ASN1) req = d2i_X509_REQ_bio(in, NULL); else if (format == FORMAT_PEM) req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL); else print_format_error(format, OPT_FMT_PEMDER); end: if (req == NULL) { BIO_printf(bio_err, "Unable to load %s\n", desc); ERR_print_errors(bio_err); } BIO_free(in); return req; } void cleanse(char *str) { if (str != NULL) OPENSSL_cleanse(str, strlen(str)); } void clear_free(char *str) { if (str != NULL) OPENSSL_clear_free(str, strlen(str)); } EVP_PKEY *load_key(const char *uri, int format, int may_stdin, const char *pass, ENGINE *e, const char *desc) { EVP_PKEY *pkey = NULL; char *allocated_uri = NULL; if (desc == NULL) desc = "private key"; if (format == FORMAT_ENGINE) { uri = allocated_uri = make_engine_uri(e, uri, desc); } (void)load_key_certs_crls(uri, format, may_stdin, pass, desc, &pkey, NULL, NULL, NULL, NULL, NULL, NULL); OPENSSL_free(allocated_uri); return pkey; } EVP_PKEY *load_pubkey(const char *uri, int format, int maybe_stdin, const char *pass, ENGINE *e, const char *desc) { EVP_PKEY *pkey = NULL; char *allocated_uri = NULL; if (desc == NULL) desc = "public key"; if (format == FORMAT_ENGINE) { uri = allocated_uri = make_engine_uri(e, uri, desc); } (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc, NULL, &pkey, NULL, NULL, NULL, NULL, NULL); OPENSSL_free(allocated_uri); return pkey; } EVP_PKEY *load_keyparams_suppress(const char *uri, int format, int maybe_stdin, const char *keytype, const char *desc, int suppress_decode_errors) { EVP_PKEY *params = NULL; if (desc == NULL) desc = "key parameters"; (void)load_key_certs_crls_suppress(uri, format, maybe_stdin, NULL, desc, NULL, NULL, ¶ms, NULL, NULL, NULL, NULL, suppress_decode_errors); if (params != NULL && keytype != NULL && !EVP_PKEY_is_a(params, keytype)) { if (!suppress_decode_errors) { BIO_printf(bio_err, "Unable to load %s from %s (unexpected parameters type)\n", desc, uri); ERR_print_errors(bio_err); } EVP_PKEY_free(params); params = NULL; } return params; } EVP_PKEY *load_keyparams(const char *uri, int format, int maybe_stdin, const char *keytype, const char *desc) { return load_keyparams_suppress(uri, format, maybe_stdin, keytype, desc, 0); } void app_bail_out(char *fmt, ...) { va_list args; va_start(args, fmt); BIO_vprintf(bio_err, fmt, args); va_end(args); ERR_print_errors(bio_err); exit(EXIT_FAILURE); } void *app_malloc(size_t sz, const char *what) { void *vp = OPENSSL_malloc(sz); if (vp == NULL) app_bail_out("%s: Could not allocate %zu bytes for %s\n", opt_getprog(), sz, what); return vp; } char *next_item(char *opt) /* in list separated by comma and/or space */ { /* advance to separator (comma or whitespace), if any */ while (*opt != ',' && !isspace(_UC(*opt)) && *opt != '\0') opt++; if (*opt != '\0') { /* terminate current item */ *opt++ = '\0'; /* skip over any whitespace after separator */ while (isspace(_UC(*opt))) opt++; } return *opt == '\0' ? NULL : opt; /* NULL indicates end of input */ } static void warn_cert_msg(const char *uri, X509 *cert, const char *msg) { char *subj = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0); BIO_printf(bio_err, "Warning: certificate from '%s' with subject '%s' %s\n", uri, subj, msg); OPENSSL_free(subj); } static void warn_cert(const char *uri, X509 *cert, int warn_EE, X509_VERIFY_PARAM *vpm) { uint32_t ex_flags = X509_get_extension_flags(cert); int res = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert), X509_get0_notAfter(cert)); if (res != 0) warn_cert_msg(uri, cert, res > 0 ? "has expired" : "not yet valid"); if (warn_EE && (ex_flags & EXFLAG_V1) == 0 && (ex_flags & EXFLAG_CA) == 0) warn_cert_msg(uri, cert, "is not a CA cert"); } static void warn_certs(const char *uri, STACK_OF(X509) *certs, int warn_EE, X509_VERIFY_PARAM *vpm) { int i; for (i = 0; i < sk_X509_num(certs); i++) warn_cert(uri, sk_X509_value(certs, i), warn_EE, vpm); } int load_cert_certs(const char *uri, X509 **pcert, STACK_OF(X509) **pcerts, int exclude_http, const char *pass, const char *desc, X509_VERIFY_PARAM *vpm) { int ret = 0; char *pass_string; if (exclude_http && (OPENSSL_strncasecmp(uri, "http://", 7) == 0 || OPENSSL_strncasecmp(uri, "https://", 8) == 0)) { BIO_printf(bio_err, "error: HTTP retrieval not allowed for %s\n", desc); return ret; } pass_string = get_passwd(pass, desc); ret = load_key_certs_crls(uri, FORMAT_UNDEF, 0, pass_string, desc, NULL, NULL, NULL, pcert, pcerts, NULL, NULL); clear_free(pass_string); if (ret) { if (pcert != NULL) warn_cert(uri, *pcert, 0, vpm); if (pcerts != NULL) warn_certs(uri, *pcerts, 1, vpm); } else { if (pcerts != NULL) { sk_X509_pop_free(*pcerts, X509_free); *pcerts = NULL; } } return ret; } STACK_OF(X509) *load_certs_multifile(char *files, const char *pass, const char *desc, X509_VERIFY_PARAM *vpm) { STACK_OF(X509) *certs = NULL; STACK_OF(X509) *result = sk_X509_new_null(); if (files == NULL) goto err; if (result == NULL) goto oom; while (files != NULL) { char *next = next_item(files); if (!load_cert_certs(files, NULL, &certs, 0, pass, desc, vpm)) goto err; if (!X509_add_certs(result, certs, X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP)) goto oom; sk_X509_pop_free(certs, X509_free); certs = NULL; files = next; } return result; oom: BIO_printf(bio_err, "out of memory\n"); err: sk_X509_pop_free(certs, X509_free); sk_X509_pop_free(result, X509_free); return NULL; } static X509_STORE *sk_X509_to_store(X509_STORE *store /* may be NULL */, const STACK_OF(X509) *certs /* may NULL */) { int i; if (store == NULL) store = X509_STORE_new(); if (store == NULL) return NULL; for (i = 0; i < sk_X509_num(certs); i++) { if (!X509_STORE_add_cert(store, sk_X509_value(certs, i))) { X509_STORE_free(store); return NULL; } } return store; } /* * Create cert store structure with certificates read from given file(s). * Returns pointer to created X509_STORE on success, NULL on error. */ X509_STORE *load_certstore(char *input, const char *pass, const char *desc, X509_VERIFY_PARAM *vpm) { X509_STORE *store = NULL; STACK_OF(X509) *certs = NULL; while (input != NULL) { char *next = next_item(input); int ok; if (!load_cert_certs(input, NULL, &certs, 1, pass, desc, vpm)) { X509_STORE_free(store); return NULL; } ok = (store = sk_X509_to_store(store, certs)) != NULL; sk_X509_pop_free(certs, X509_free); certs = NULL; if (!ok) return NULL; input = next; } return store; } /* * Initialize or extend, if *certs != NULL, a certificate stack. * The caller is responsible for freeing *certs if its value is left not NULL. */ int load_certs(const char *uri, int maybe_stdin, STACK_OF(X509) **certs, const char *pass, const char *desc) { int was_NULL = *certs == NULL; int ret = load_key_certs_crls(uri, FORMAT_UNDEF, maybe_stdin, pass, desc, NULL, NULL, NULL, NULL, certs, NULL, NULL); if (!ret && was_NULL) { sk_X509_pop_free(*certs, X509_free); *certs = NULL; } return ret; } /* * Initialize or extend, if *crls != NULL, a certificate stack. * The caller is responsible for freeing *crls if its value is left not NULL. */ int load_crls(const char *uri, STACK_OF(X509_CRL) **crls, const char *pass, const char *desc) { int was_NULL = *crls == NULL; int ret = load_key_certs_crls(uri, FORMAT_UNDEF, 0, pass, desc, NULL, NULL, NULL, NULL, NULL, NULL, crls); if (!ret && was_NULL) { sk_X509_CRL_pop_free(*crls, X509_CRL_free); *crls = NULL; } return ret; } static const char *format2string(int format) { switch(format) { case FORMAT_PEM: return "PEM"; case FORMAT_ASN1: return "DER"; } return NULL; } /* Set type expectation, but clear it if objects of different types expected. */ #define SET_EXPECT(expect, val) ((expect) = (expect) < 0 ? (val) : ((expect) == (val) ? (val) : 0)) /* * Load those types of credentials for which the result pointer is not NULL. * Reads from stdio if uri is NULL and maybe_stdin is nonzero. * For non-NULL ppkey, pcert, and pcrl the first suitable value found is loaded. * If pcerts is non-NULL and *pcerts == NULL then a new cert list is allocated. * If pcerts is non-NULL then all available certificates are appended to *pcerts * except any certificate assigned to *pcert. * If pcrls is non-NULL and *pcrls == NULL then a new list of CRLs is allocated. * If pcrls is non-NULL then all available CRLs are appended to *pcerts * except any CRL assigned to *pcrl. * In any case (also on error) the caller is responsible for freeing all members * of *pcerts and *pcrls (as far as they are not NULL). */ static int load_key_certs_crls_suppress(const char *uri, int format, int maybe_stdin, const char *pass, const char *desc, EVP_PKEY **ppkey, EVP_PKEY **ppubkey, EVP_PKEY **pparams, X509 **pcert, STACK_OF(X509) **pcerts, X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls, int suppress_decode_errors) { PW_CB_DATA uidata; OSSL_STORE_CTX *ctx = NULL; OSSL_LIB_CTX *libctx = app_get0_libctx(); const char *propq = app_get0_propq(); int ncerts = 0; int ncrls = 0; const char *failed = ppkey != NULL ? "key" : ppubkey != NULL ? "public key" : pparams != NULL ? "params" : pcert != NULL ? "cert" : pcrl != NULL ? "CRL" : pcerts != NULL ? "certs" : pcrls != NULL ? "CRLs" : NULL; int cnt_expectations = 0; int expect = -1; const char *input_type; OSSL_PARAM itp[2]; const OSSL_PARAM *params = NULL; if (ppkey != NULL) { *ppkey = NULL; cnt_expectations++; SET_EXPECT(expect, OSSL_STORE_INFO_PKEY); } if (ppubkey != NULL) { *ppubkey = NULL; cnt_expectations++; SET_EXPECT(expect, OSSL_STORE_INFO_PUBKEY); } if (pparams != NULL) { *pparams = NULL; cnt_expectations++; SET_EXPECT(expect, OSSL_STORE_INFO_PARAMS); } if (pcert != NULL) { *pcert = NULL; cnt_expectations++; SET_EXPECT(expect, OSSL_STORE_INFO_CERT); } if (pcerts != NULL) { if (*pcerts == NULL && (*pcerts = sk_X509_new_null()) == NULL) { BIO_printf(bio_err, "Out of memory loading"); goto end; } cnt_expectations++; SET_EXPECT(expect, OSSL_STORE_INFO_CERT); } if (pcrl != NULL) { *pcrl = NULL; cnt_expectations++; SET_EXPECT(expect, OSSL_STORE_INFO_CRL); } if (pcrls != NULL) { if (*pcrls == NULL && (*pcrls = sk_X509_CRL_new_null()) == NULL) { BIO_printf(bio_err, "Out of memory loading"); goto end; } cnt_expectations++; SET_EXPECT(expect, OSSL_STORE_INFO_CRL); } if (cnt_expectations == 0) { BIO_printf(bio_err, "Internal error: nothing to load from %s\n", uri != NULL ? uri : ""); return 0; } uidata.password = pass; uidata.prompt_info = uri; if ((input_type = format2string(format)) != NULL) { itp[0] = OSSL_PARAM_construct_utf8_string(OSSL_STORE_PARAM_INPUT_TYPE, (char *)input_type, 0); itp[1] = OSSL_PARAM_construct_end(); params = itp; } if (uri == NULL) { BIO *bio; if (!maybe_stdin) { - BIO_printf(bio_err, "No filename or uri specified for loading"); + BIO_printf(bio_err, "No filename or uri specified for loading\n"); goto end; } uri = ""; unbuffer(stdin); bio = BIO_new_fp(stdin, 0); if (bio != NULL) { ctx = OSSL_STORE_attach(bio, "file", libctx, propq, get_ui_method(), &uidata, params, NULL, NULL); BIO_free(bio); } } else { ctx = OSSL_STORE_open_ex(uri, libctx, propq, get_ui_method(), &uidata, params, NULL, NULL); } - if (ctx == NULL) { - BIO_printf(bio_err, "Could not open file or uri for loading"); + if (ctx == NULL) goto end; - } if (expect > 0 && !OSSL_STORE_expect(ctx, expect)) goto end; failed = NULL; while (cnt_expectations > 0 && !OSSL_STORE_eof(ctx)) { OSSL_STORE_INFO *info = OSSL_STORE_load(ctx); int type, ok = 1; /* * This can happen (for example) if we attempt to load a file with * multiple different types of things in it - but the thing we just * tried to load wasn't one of the ones we wanted, e.g. if we're trying * to load a certificate but the file has both the private key and the * certificate in it. We just retry until eof. */ if (info == NULL) { continue; } type = OSSL_STORE_INFO_get_type(info); switch (type) { case OSSL_STORE_INFO_PKEY: if (ppkey != NULL && *ppkey == NULL) { ok = (*ppkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL; cnt_expectations -= ok; } /* * An EVP_PKEY with private parts also holds the public parts, * so if the caller asked for a public key, and we got a private * key, we can still pass it back. */ if (ok && ppubkey != NULL && *ppubkey == NULL) { ok = ((*ppubkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL); cnt_expectations -= ok; } break; case OSSL_STORE_INFO_PUBKEY: if (ppubkey != NULL && *ppubkey == NULL) { ok = ((*ppubkey = OSSL_STORE_INFO_get1_PUBKEY(info)) != NULL); cnt_expectations -= ok; } break; case OSSL_STORE_INFO_PARAMS: if (pparams != NULL && *pparams == NULL) { ok = ((*pparams = OSSL_STORE_INFO_get1_PARAMS(info)) != NULL); cnt_expectations -= ok; } break; case OSSL_STORE_INFO_CERT: if (pcert != NULL && *pcert == NULL) { ok = (*pcert = OSSL_STORE_INFO_get1_CERT(info)) != NULL; cnt_expectations -= ok; } else if (pcerts != NULL) ok = X509_add_cert(*pcerts, OSSL_STORE_INFO_get1_CERT(info), X509_ADD_FLAG_DEFAULT); ncerts += ok; break; case OSSL_STORE_INFO_CRL: if (pcrl != NULL && *pcrl == NULL) { ok = (*pcrl = OSSL_STORE_INFO_get1_CRL(info)) != NULL; cnt_expectations -= ok; } else if (pcrls != NULL) ok = sk_X509_CRL_push(*pcrls, OSSL_STORE_INFO_get1_CRL(info)); ncrls += ok; break; default: /* skip any other type */ break; } OSSL_STORE_INFO_free(info); if (!ok) { failed = info == NULL ? NULL : OSSL_STORE_INFO_type_string(type); BIO_printf(bio_err, "Error reading"); break; } } end: OSSL_STORE_close(ctx); if (failed == NULL) { int any = 0; if ((ppkey != NULL && *ppkey == NULL) || (ppubkey != NULL && *ppubkey == NULL)) { failed = "key"; } else if (pparams != NULL && *pparams == NULL) { failed = "params"; } else if ((pcert != NULL || pcerts != NULL) && ncerts == 0) { if (pcert == NULL) any = 1; failed = "cert"; } else if ((pcrl != NULL || pcrls != NULL) && ncrls == 0) { if (pcrl == NULL) any = 1; failed = "CRL"; } if (!suppress_decode_errors) { if (failed != NULL) BIO_printf(bio_err, "Could not read"); if (any) BIO_printf(bio_err, " any"); } } if (!suppress_decode_errors && failed != NULL) { if (desc != NULL && strstr(desc, failed) != NULL) { BIO_printf(bio_err, " %s", desc); } else { BIO_printf(bio_err, " %s", failed); if (desc != NULL) BIO_printf(bio_err, " of %s", desc); } if (uri != NULL) BIO_printf(bio_err, " from %s", uri); BIO_printf(bio_err, "\n"); ERR_print_errors(bio_err); } if (suppress_decode_errors || failed == NULL) /* clear any spurious errors */ ERR_clear_error(); return failed == NULL; } int load_key_certs_crls(const char *uri, int format, int maybe_stdin, const char *pass, const char *desc, EVP_PKEY **ppkey, EVP_PKEY **ppubkey, EVP_PKEY **pparams, X509 **pcert, STACK_OF(X509) **pcerts, X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls) { return load_key_certs_crls_suppress(uri, format, maybe_stdin, pass, desc, ppkey, ppubkey, pparams, pcert, pcerts, pcrl, pcrls, 0); } #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16) /* Return error for unknown extensions */ #define X509V3_EXT_DEFAULT 0 /* Print error for unknown extensions */ #define X509V3_EXT_ERROR_UNKNOWN (1L << 16) /* ASN1 parse unknown extensions */ #define X509V3_EXT_PARSE_UNKNOWN (2L << 16) /* BIO_dump unknown extensions */ #define X509V3_EXT_DUMP_UNKNOWN (3L << 16) #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \ X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION) int set_cert_ex(unsigned long *flags, const char *arg) { static const NAME_EX_TBL cert_tbl[] = { {"compatible", X509_FLAG_COMPAT, 0xffffffffl}, {"ca_default", X509_FLAG_CA, 0xffffffffl}, {"no_header", X509_FLAG_NO_HEADER, 0}, {"no_version", X509_FLAG_NO_VERSION, 0}, {"no_serial", X509_FLAG_NO_SERIAL, 0}, {"no_signame", X509_FLAG_NO_SIGNAME, 0}, {"no_validity", X509_FLAG_NO_VALIDITY, 0}, {"no_subject", X509_FLAG_NO_SUBJECT, 0}, {"no_issuer", X509_FLAG_NO_ISSUER, 0}, {"no_pubkey", X509_FLAG_NO_PUBKEY, 0}, {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0}, {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0}, {"no_aux", X509_FLAG_NO_AUX, 0}, {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0}, {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK}, {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK}, {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK}, {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK}, {NULL, 0, 0} }; return set_multi_opts(flags, arg, cert_tbl); } int set_name_ex(unsigned long *flags, const char *arg) { static const NAME_EX_TBL ex_tbl[] = { {"esc_2253", ASN1_STRFLGS_ESC_2253, 0}, {"esc_2254", ASN1_STRFLGS_ESC_2254, 0}, {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0}, {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0}, {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0}, {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0}, {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0}, {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0}, {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0}, {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0}, {"dump_der", ASN1_STRFLGS_DUMP_DER, 0}, {"compat", XN_FLAG_COMPAT, 0xffffffffL}, {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK}, {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK}, {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK}, {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK}, {"dn_rev", XN_FLAG_DN_REV, 0}, {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK}, {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK}, {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK}, {"align", XN_FLAG_FN_ALIGN, 0}, {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK}, {"space_eq", XN_FLAG_SPC_EQ, 0}, {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0}, {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL}, {"oneline", XN_FLAG_ONELINE, 0xffffffffL}, {"multiline", XN_FLAG_MULTILINE, 0xffffffffL}, {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL}, {NULL, 0, 0} }; if (set_multi_opts(flags, arg, ex_tbl) == 0) return 0; if (*flags != XN_FLAG_COMPAT && (*flags & XN_FLAG_SEP_MASK) == 0) *flags |= XN_FLAG_SEP_CPLUS_SPC; return 1; } int set_dateopt(unsigned long *dateopt, const char *arg) { if (OPENSSL_strcasecmp(arg, "rfc_822") == 0) *dateopt = ASN1_DTFLGS_RFC822; else if (OPENSSL_strcasecmp(arg, "iso_8601") == 0) *dateopt = ASN1_DTFLGS_ISO8601; else return 0; return 1; } int set_ext_copy(int *copy_type, const char *arg) { if (OPENSSL_strcasecmp(arg, "none") == 0) *copy_type = EXT_COPY_NONE; else if (OPENSSL_strcasecmp(arg, "copy") == 0) *copy_type = EXT_COPY_ADD; else if (OPENSSL_strcasecmp(arg, "copyall") == 0) *copy_type = EXT_COPY_ALL; else return 0; return 1; } int copy_extensions(X509 *x, X509_REQ *req, int copy_type) { STACK_OF(X509_EXTENSION) *exts; int i, ret = 0; if (x == NULL || req == NULL) return 0; if (copy_type == EXT_COPY_NONE) return 1; exts = X509_REQ_get_extensions(req); for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) { X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i); ASN1_OBJECT *obj = X509_EXTENSION_get_object(ext); int idx = X509_get_ext_by_OBJ(x, obj, -1); /* Does extension exist in target? */ if (idx != -1) { /* If normal copy don't override existing extension */ if (copy_type == EXT_COPY_ADD) continue; /* Delete all extensions of same type */ do { X509_EXTENSION_free(X509_delete_ext(x, idx)); idx = X509_get_ext_by_OBJ(x, obj, -1); } while (idx != -1); } if (!X509_add_ext(x, ext, -1)) goto end; } ret = 1; end: sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free); return ret; } static int set_multi_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL * in_tbl) { STACK_OF(CONF_VALUE) *vals; CONF_VALUE *val; int i, ret = 1; if (!arg) return 0; vals = X509V3_parse_list(arg); for (i = 0; i < sk_CONF_VALUE_num(vals); i++) { val = sk_CONF_VALUE_value(vals, i); if (!set_table_opts(flags, val->name, in_tbl)) ret = 0; } sk_CONF_VALUE_pop_free(vals, X509V3_conf_free); return ret; } static int set_table_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL * in_tbl) { char c; const NAME_EX_TBL *ptbl; c = arg[0]; if (c == '-') { c = 0; arg++; } else if (c == '+') { c = 1; arg++; } else { c = 1; } for (ptbl = in_tbl; ptbl->name; ptbl++) { if (OPENSSL_strcasecmp(arg, ptbl->name) == 0) { *flags &= ~ptbl->mask; if (c) *flags |= ptbl->flag; else *flags &= ~ptbl->flag; return 1; } } return 0; } void print_name(BIO *out, const char *title, const X509_NAME *nm) { char *buf; char mline = 0; int indent = 0; unsigned long lflags = get_nameopt(); if (out == NULL) return; if (title != NULL) BIO_puts(out, title); if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) { mline = 1; indent = 4; } if (lflags == XN_FLAG_COMPAT) { buf = X509_NAME_oneline(nm, 0, 0); BIO_puts(out, buf); BIO_puts(out, "\n"); OPENSSL_free(buf); } else { if (mline) BIO_puts(out, "\n"); X509_NAME_print_ex(out, nm, indent, lflags); BIO_puts(out, "\n"); } } void print_bignum_var(BIO *out, const BIGNUM *in, const char *var, int len, unsigned char *buffer) { BIO_printf(out, " static unsigned char %s_%d[] = {", var, len); if (BN_is_zero(in)) { BIO_printf(out, "\n 0x00"); } else { int i, l; l = BN_bn2bin(in, buffer); for (i = 0; i < l; i++) { BIO_printf(out, (i % 10) == 0 ? "\n " : " "); if (i < l - 1) BIO_printf(out, "0x%02X,", buffer[i]); else BIO_printf(out, "0x%02X", buffer[i]); } } BIO_printf(out, "\n };\n"); } void print_array(BIO *out, const char* title, int len, const unsigned char* d) { int i; BIO_printf(out, "unsigned char %s[%d] = {", title, len); for (i = 0; i < len; i++) { if ((i % 10) == 0) BIO_printf(out, "\n "); if (i < len - 1) BIO_printf(out, "0x%02X, ", d[i]); else BIO_printf(out, "0x%02X", d[i]); } BIO_printf(out, "\n};\n"); } X509_STORE *setup_verify(const char *CAfile, int noCAfile, const char *CApath, int noCApath, const char *CAstore, int noCAstore) { X509_STORE *store = X509_STORE_new(); X509_LOOKUP *lookup; OSSL_LIB_CTX *libctx = app_get0_libctx(); const char *propq = app_get0_propq(); if (store == NULL) goto end; if (CAfile != NULL || !noCAfile) { lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); if (lookup == NULL) goto end; if (CAfile != NULL) { if (X509_LOOKUP_load_file_ex(lookup, CAfile, X509_FILETYPE_PEM, libctx, propq) <= 0) { BIO_printf(bio_err, "Error loading file %s\n", CAfile); goto end; } } else { X509_LOOKUP_load_file_ex(lookup, NULL, X509_FILETYPE_DEFAULT, libctx, propq); } } if (CApath != NULL || !noCApath) { lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir()); if (lookup == NULL) goto end; if (CApath != NULL) { if (X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM) <= 0) { BIO_printf(bio_err, "Error loading directory %s\n", CApath); goto end; } } else { X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT); } } if (CAstore != NULL || !noCAstore) { lookup = X509_STORE_add_lookup(store, X509_LOOKUP_store()); if (lookup == NULL) goto end; if (!X509_LOOKUP_add_store_ex(lookup, CAstore, libctx, propq)) { if (CAstore != NULL) BIO_printf(bio_err, "Error loading store URI %s\n", CAstore); goto end; } } ERR_clear_error(); return store; end: ERR_print_errors(bio_err); X509_STORE_free(store); return NULL; } static unsigned long index_serial_hash(const OPENSSL_CSTRING *a) { const char *n; n = a[DB_serial]; while (*n == '0') n++; return OPENSSL_LH_strhash(n); } static int index_serial_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b) { const char *aa, *bb; for (aa = a[DB_serial]; *aa == '0'; aa++) ; for (bb = b[DB_serial]; *bb == '0'; bb++) ; return strcmp(aa, bb); } static int index_name_qual(char **a) { return (a[0][0] == 'V'); } static unsigned long index_name_hash(const OPENSSL_CSTRING *a) { return OPENSSL_LH_strhash(a[DB_name]); } int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b) { return strcmp(a[DB_name], b[DB_name]); } static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING) static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING) static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING) static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING) #undef BSIZE #define BSIZE 256 BIGNUM *load_serial(const char *serialfile, int *exists, int create, ASN1_INTEGER **retai) { BIO *in = NULL; BIGNUM *ret = NULL; char buf[1024]; ASN1_INTEGER *ai = NULL; ai = ASN1_INTEGER_new(); if (ai == NULL) goto err; in = BIO_new_file(serialfile, "r"); if (exists != NULL) *exists = in != NULL; if (in == NULL) { if (!create) { perror(serialfile); goto err; } ERR_clear_error(); ret = BN_new(); if (ret == NULL) { BIO_printf(bio_err, "Out of memory\n"); } else if (!rand_serial(ret, ai)) { BIO_printf(bio_err, "Error creating random number to store in %s\n", serialfile); BN_free(ret); ret = NULL; } } else { if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) { BIO_printf(bio_err, "Unable to load number from %s\n", serialfile); goto err; } ret = ASN1_INTEGER_to_BN(ai, NULL); if (ret == NULL) { BIO_printf(bio_err, "Error converting number from bin to BIGNUM\n"); goto err; } } if (ret != NULL && retai != NULL) { *retai = ai; ai = NULL; } err: if (ret == NULL) ERR_print_errors(bio_err); BIO_free(in); ASN1_INTEGER_free(ai); return ret; } int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial, ASN1_INTEGER **retai) { char buf[1][BSIZE]; BIO *out = NULL; int ret = 0; ASN1_INTEGER *ai = NULL; int j; if (suffix == NULL) j = strlen(serialfile); else j = strlen(serialfile) + strlen(suffix) + 1; if (j >= BSIZE) { BIO_printf(bio_err, "File name too long\n"); goto err; } if (suffix == NULL) OPENSSL_strlcpy(buf[0], serialfile, BSIZE); else { #ifndef OPENSSL_SYS_VMS j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix); #else j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix); #endif } out = BIO_new_file(buf[0], "w"); if (out == NULL) { goto err; } if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) { BIO_printf(bio_err, "error converting serial to ASN.1 format\n"); goto err; } i2a_ASN1_INTEGER(out, ai); BIO_puts(out, "\n"); ret = 1; if (retai) { *retai = ai; ai = NULL; } err: if (!ret) ERR_print_errors(bio_err); BIO_free_all(out); ASN1_INTEGER_free(ai); return ret; } int rotate_serial(const char *serialfile, const char *new_suffix, const char *old_suffix) { char buf[2][BSIZE]; int i, j; i = strlen(serialfile) + strlen(old_suffix); j = strlen(serialfile) + strlen(new_suffix); if (i > j) j = i; if (j + 1 >= BSIZE) { BIO_printf(bio_err, "File name too long\n"); goto err; } #ifndef OPENSSL_SYS_VMS j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix); j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix); #else j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix); j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix); #endif if (rename(serialfile, buf[1]) < 0 && errno != ENOENT #ifdef ENOTDIR && errno != ENOTDIR #endif ) { BIO_printf(bio_err, "Unable to rename %s to %s\n", serialfile, buf[1]); perror("reason"); goto err; } if (rename(buf[0], serialfile) < 0) { BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[0], serialfile); perror("reason"); rename(buf[1], serialfile); goto err; } return 1; err: ERR_print_errors(bio_err); return 0; } int rand_serial(BIGNUM *b, ASN1_INTEGER *ai) { BIGNUM *btmp; int ret = 0; btmp = b == NULL ? BN_new() : b; if (btmp == NULL) return 0; if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY)) goto error; if (ai && !BN_to_ASN1_INTEGER(btmp, ai)) goto error; ret = 1; error: if (btmp != b) BN_free(btmp); return ret; } CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr) { CA_DB *retdb = NULL; TXT_DB *tmpdb = NULL; BIO *in; CONF *dbattr_conf = NULL; char buf[BSIZE]; #ifndef OPENSSL_NO_POSIX_IO FILE *dbfp; struct stat dbst; #endif in = BIO_new_file(dbfile, "r"); if (in == NULL) goto err; #ifndef OPENSSL_NO_POSIX_IO BIO_get_fp(in, &dbfp); if (fstat(fileno(dbfp), &dbst) == -1) { ERR_raise_data(ERR_LIB_SYS, errno, "calling fstat(%s)", dbfile); goto err; } #endif if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL) goto err; #ifndef OPENSSL_SYS_VMS BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile); #else BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile); #endif dbattr_conf = app_load_config_quiet(buf); retdb = app_malloc(sizeof(*retdb), "new DB"); retdb->db = tmpdb; tmpdb = NULL; if (db_attr) retdb->attributes = *db_attr; else { retdb->attributes.unique_subject = 1; } if (dbattr_conf) { char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject"); if (p) { retdb->attributes.unique_subject = parse_yesno(p, 1); } else { ERR_clear_error(); } } retdb->dbfname = OPENSSL_strdup(dbfile); #ifndef OPENSSL_NO_POSIX_IO retdb->dbst = dbst; #endif err: ERR_print_errors(bio_err); NCONF_free(dbattr_conf); TXT_DB_free(tmpdb); BIO_free_all(in); return retdb; } /* * Returns > 0 on success, <= 0 on error */ int index_index(CA_DB *db) { if (!TXT_DB_create_index(db->db, DB_serial, NULL, LHASH_HASH_FN(index_serial), LHASH_COMP_FN(index_serial))) { BIO_printf(bio_err, "Error creating serial number index:(%ld,%ld,%ld)\n", db->db->error, db->db->arg1, db->db->arg2); goto err; } if (db->attributes.unique_subject && !TXT_DB_create_index(db->db, DB_name, index_name_qual, LHASH_HASH_FN(index_name), LHASH_COMP_FN(index_name))) { BIO_printf(bio_err, "Error creating name index:(%ld,%ld,%ld)\n", db->db->error, db->db->arg1, db->db->arg2); goto err; } return 1; err: ERR_print_errors(bio_err); return 0; } int save_index(const char *dbfile, const char *suffix, CA_DB *db) { char buf[3][BSIZE]; BIO *out; int j; j = strlen(dbfile) + strlen(suffix); if (j + 6 >= BSIZE) { BIO_printf(bio_err, "File name too long\n"); goto err; } #ifndef OPENSSL_SYS_VMS j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile); j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix); j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix); #else j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile); j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix); j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix); #endif out = BIO_new_file(buf[0], "w"); if (out == NULL) { perror(dbfile); BIO_printf(bio_err, "Unable to open '%s'\n", dbfile); goto err; } j = TXT_DB_write(out, db->db); BIO_free(out); if (j <= 0) goto err; out = BIO_new_file(buf[1], "w"); if (out == NULL) { perror(buf[2]); BIO_printf(bio_err, "Unable to open '%s'\n", buf[2]); goto err; } BIO_printf(out, "unique_subject = %s\n", db->attributes.unique_subject ? "yes" : "no"); BIO_free(out); return 1; err: ERR_print_errors(bio_err); return 0; } int rotate_index(const char *dbfile, const char *new_suffix, const char *old_suffix) { char buf[5][BSIZE]; int i, j; i = strlen(dbfile) + strlen(old_suffix); j = strlen(dbfile) + strlen(new_suffix); if (i > j) j = i; if (j + 6 >= BSIZE) { BIO_printf(bio_err, "File name too long\n"); goto err; } #ifndef OPENSSL_SYS_VMS j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile); j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix); j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix); j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix); j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix); #else j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile); j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix); j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix); j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix); j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix); #endif if (rename(dbfile, buf[1]) < 0 && errno != ENOENT #ifdef ENOTDIR && errno != ENOTDIR #endif ) { BIO_printf(bio_err, "Unable to rename %s to %s\n", dbfile, buf[1]); perror("reason"); goto err; } if (rename(buf[0], dbfile) < 0) { BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[0], dbfile); perror("reason"); rename(buf[1], dbfile); goto err; } if (rename(buf[4], buf[3]) < 0 && errno != ENOENT #ifdef ENOTDIR && errno != ENOTDIR #endif ) { BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[4], buf[3]); perror("reason"); rename(dbfile, buf[0]); rename(buf[1], dbfile); goto err; } if (rename(buf[2], buf[4]) < 0) { BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[2], buf[4]); perror("reason"); rename(buf[3], buf[4]); rename(dbfile, buf[0]); rename(buf[1], dbfile); goto err; } return 1; err: ERR_print_errors(bio_err); return 0; } void free_index(CA_DB *db) { if (db) { TXT_DB_free(db->db); OPENSSL_free(db->dbfname); OPENSSL_free(db); } } int parse_yesno(const char *str, int def) { if (str) { switch (*str) { case 'f': /* false */ case 'F': /* FALSE */ case 'n': /* no */ case 'N': /* NO */ case '0': /* 0 */ return 0; case 't': /* true */ case 'T': /* TRUE */ case 'y': /* yes */ case 'Y': /* YES */ case '1': /* 1 */ return 1; } } return def; } /* * name is expected to be in the format /type0=value0/type1=value1/type2=... * where + can be used instead of / to form multi-valued RDNs if canmulti * and characters may be escaped by \ */ X509_NAME *parse_name(const char *cp, int chtype, int canmulti, const char *desc) { int nextismulti = 0; char *work; X509_NAME *n; if (*cp++ != '/') { BIO_printf(bio_err, "%s: %s name is expected to be in the format " "/type0=value0/type1=value1/type2=... where characters may " "be escaped by \\. This name is not in that format: '%s'\n", opt_getprog(), desc, --cp); return NULL; } n = X509_NAME_new(); if (n == NULL) { BIO_printf(bio_err, "%s: Out of memory\n", opt_getprog()); return NULL; } work = OPENSSL_strdup(cp); if (work == NULL) { BIO_printf(bio_err, "%s: Error copying %s name input\n", opt_getprog(), desc); goto err; } while (*cp != '\0') { char *bp = work; char *typestr = bp; unsigned char *valstr; int nid; int ismulti = nextismulti; nextismulti = 0; /* Collect the type */ while (*cp != '\0' && *cp != '=') *bp++ = *cp++; *bp++ = '\0'; if (*cp == '\0') { BIO_printf(bio_err, "%s: Missing '=' after RDN type string '%s' in %s name string\n", opt_getprog(), typestr, desc); goto err; } ++cp; /* Collect the value. */ valstr = (unsigned char *)bp; for (; *cp != '\0' && *cp != '/'; *bp++ = *cp++) { /* unescaped '+' symbol string signals further member of multiRDN */ if (canmulti && *cp == '+') { nextismulti = 1; break; } if (*cp == '\\' && *++cp == '\0') { BIO_printf(bio_err, "%s: Escape character at end of %s name string\n", opt_getprog(), desc); goto err; } } *bp++ = '\0'; /* If not at EOS (must be + or /), move forward. */ if (*cp != '\0') ++cp; /* Parse */ nid = OBJ_txt2nid(typestr); if (nid == NID_undef) { BIO_printf(bio_err, - "%s: Skipping unknown %s name attribute \"%s\"\n", + "%s warning: Skipping unknown %s name attribute \"%s\"\n", opt_getprog(), desc, typestr); if (ismulti) BIO_printf(bio_err, - "Hint: a '+' in a value string needs be escaped using '\\' else a new member of a multi-valued RDN is expected\n"); + "%s hint: a '+' in a value string needs be escaped using '\\' else a new member of a multi-valued RDN is expected\n", + opt_getprog()); continue; } if (*valstr == '\0') { BIO_printf(bio_err, - "%s: No value provided for %s name attribute \"%s\", skipped\n", + "%s warning: No value provided for %s name attribute \"%s\", skipped\n", opt_getprog(), desc, typestr); continue; } if (!X509_NAME_add_entry_by_NID(n, nid, chtype, valstr, strlen((char *)valstr), -1, ismulti ? -1 : 0)) { ERR_print_errors(bio_err); BIO_printf(bio_err, "%s: Error adding %s name attribute \"/%s=%s\"\n", opt_getprog(), desc, typestr ,valstr); goto err; } } OPENSSL_free(work); return n; err: X509_NAME_free(n); OPENSSL_free(work); return NULL; } /* * Read whole contents of a BIO into an allocated memory buffer and return * it. */ int bio_to_mem(unsigned char **out, int maxlen, BIO *in) { BIO *mem; int len, ret; unsigned char tbuf[1024]; mem = BIO_new(BIO_s_mem()); if (mem == NULL) return -1; for (;;) { if ((maxlen != -1) && maxlen < 1024) len = maxlen; else len = 1024; len = BIO_read(in, tbuf, len); if (len < 0) { BIO_free(mem); return -1; } if (len == 0) break; if (BIO_write(mem, tbuf, len) != len) { BIO_free(mem); return -1; } if (maxlen != -1) maxlen -= len; if (maxlen == 0) break; } ret = BIO_get_mem_data(mem, (char **)out); BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY); BIO_free(mem); return ret; } int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value) { int rv = 0; char *stmp, *vtmp = NULL; stmp = OPENSSL_strdup(value); if (stmp == NULL) return -1; vtmp = strchr(stmp, ':'); if (vtmp == NULL) goto err; *vtmp = 0; vtmp++; rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp); err: OPENSSL_free(stmp); return rv; } static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes) { X509_POLICY_NODE *node; int i; BIO_printf(bio_err, "%s Policies:", name); if (nodes) { BIO_puts(bio_err, "\n"); for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) { node = sk_X509_POLICY_NODE_value(nodes, i); X509_POLICY_NODE_print(bio_err, node, 2); } } else { BIO_puts(bio_err, " \n"); } } void policies_print(X509_STORE_CTX *ctx) { X509_POLICY_TREE *tree; int explicit_policy; tree = X509_STORE_CTX_get0_policy_tree(ctx); explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx); BIO_printf(bio_err, "Require explicit Policy: %s\n", explicit_policy ? "True" : "False"); nodes_print("Authority", X509_policy_tree_get0_policies(tree)); nodes_print("User", X509_policy_tree_get0_user_policies(tree)); } /*- * next_protos_parse parses a comma separated list of strings into a string * in a format suitable for passing to SSL_CTX_set_next_protos_advertised. * outlen: (output) set to the length of the resulting buffer on success. * err: (maybe NULL) on failure, an error message line is written to this BIO. * in: a NUL terminated string like "abc,def,ghi" * * returns: a malloc'd buffer or NULL on failure. */ unsigned char *next_protos_parse(size_t *outlen, const char *in) { size_t len; unsigned char *out; size_t i, start = 0; size_t skipped = 0; len = strlen(in); if (len == 0 || len >= 65535) return NULL; out = app_malloc(len + 1, "NPN buffer"); for (i = 0; i <= len; ++i) { if (i == len || in[i] == ',') { /* * Zero-length ALPN elements are invalid on the wire, we could be * strict and reject the entire string, but just ignoring extra * commas seems harmless and more friendly. * * Every comma we skip in this way puts the input buffer another * byte ahead of the output buffer, so all stores into the output * buffer need to be decremented by the number commas skipped. */ if (i == start) { ++start; ++skipped; continue; } if (i - start > 255) { OPENSSL_free(out); return NULL; } out[start-skipped] = (unsigned char)(i - start); start = i + 1; } else { out[i + 1 - skipped] = in[i]; } } if (len <= skipped) { OPENSSL_free(out); return NULL; } *outlen = len + 1 - skipped; return out; } void print_cert_checks(BIO *bio, X509 *x, const char *checkhost, const char *checkemail, const char *checkip) { if (x == NULL) return; if (checkhost) { BIO_printf(bio, "Hostname %s does%s match certificate\n", checkhost, X509_check_host(x, checkhost, 0, 0, NULL) == 1 ? "" : " NOT"); } if (checkemail) { BIO_printf(bio, "Email %s does%s match certificate\n", checkemail, X509_check_email(x, checkemail, 0, 0) ? "" : " NOT"); } if (checkip) { BIO_printf(bio, "IP %s does%s match certificate\n", checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT"); } } static int do_pkey_ctx_init(EVP_PKEY_CTX *pkctx, STACK_OF(OPENSSL_STRING) *opts) { int i; if (opts == NULL) return 1; for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) { char *opt = sk_OPENSSL_STRING_value(opts, i); if (pkey_ctrl_string(pkctx, opt) <= 0) { BIO_printf(bio_err, "parameter error \"%s\"\n", opt); ERR_print_errors(bio_err); return 0; } } return 1; } static int do_x509_init(X509 *x, STACK_OF(OPENSSL_STRING) *opts) { int i; if (opts == NULL) return 1; for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) { char *opt = sk_OPENSSL_STRING_value(opts, i); if (x509_ctrl_string(x, opt) <= 0) { BIO_printf(bio_err, "parameter error \"%s\"\n", opt); ERR_print_errors(bio_err); return 0; } } return 1; } static int do_x509_req_init(X509_REQ *x, STACK_OF(OPENSSL_STRING) *opts) { int i; if (opts == NULL) return 1; for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) { char *opt = sk_OPENSSL_STRING_value(opts, i); if (x509_req_ctrl_string(x, opt) <= 0) { BIO_printf(bio_err, "parameter error \"%s\"\n", opt); ERR_print_errors(bio_err); return 0; } } return 1; } static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey, const char *md, STACK_OF(OPENSSL_STRING) *sigopts) { EVP_PKEY_CTX *pkctx = NULL; char def_md[80]; if (ctx == NULL) return 0; /* * EVP_PKEY_get_default_digest_name() returns 2 if the digest is mandatory * for this algorithm. */ if (EVP_PKEY_get_default_digest_name(pkey, def_md, sizeof(def_md)) == 2 && strcmp(def_md, "UNDEF") == 0) { /* The signing algorithm requires there to be no digest */ md = NULL; } return EVP_DigestSignInit_ex(ctx, &pkctx, md, app_get0_libctx(), app_get0_propq(), pkey, NULL) && do_pkey_ctx_init(pkctx, sigopts); } static int adapt_keyid_ext(X509 *cert, X509V3_CTX *ext_ctx, const char *name, const char *value, int add_default) { const STACK_OF(X509_EXTENSION) *exts = X509_get0_extensions(cert); X509_EXTENSION *new_ext = X509V3_EXT_nconf(NULL, ext_ctx, name, value); int idx, rv = 0; if (new_ext == NULL) return rv; idx = X509v3_get_ext_by_OBJ(exts, X509_EXTENSION_get_object(new_ext), -1); if (idx >= 0) { X509_EXTENSION *found_ext = X509v3_get_ext(exts, idx); ASN1_OCTET_STRING *data = X509_EXTENSION_get_data(found_ext); int disabled = ASN1_STRING_length(data) <= 2; /* config said "none" */ if (disabled) { X509_delete_ext(cert, idx); X509_EXTENSION_free(found_ext); } /* else keep existing key identifier, which might be outdated */ rv = 1; } else { rv = !add_default || X509_add_ext(cert, new_ext, -1); } X509_EXTENSION_free(new_ext); return rv; } /* Ensure RFC 5280 compliance, adapt keyIDs as needed, and sign the cert info */ int do_X509_sign(X509 *cert, EVP_PKEY *pkey, const char *md, STACK_OF(OPENSSL_STRING) *sigopts, X509V3_CTX *ext_ctx) { const STACK_OF(X509_EXTENSION) *exts = X509_get0_extensions(cert); EVP_MD_CTX *mctx = EVP_MD_CTX_new(); int self_sign; int rv = 0; if (sk_X509_EXTENSION_num(exts /* may be NULL */) > 0) { /* Prevent X509_V_ERR_EXTENSIONS_REQUIRE_VERSION_3 */ if (!X509_set_version(cert, X509_VERSION_3)) goto end; /* * Add default SKID before such that default AKID can make use of it * in case the certificate is self-signed */ /* Prevent X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER */ if (!adapt_keyid_ext(cert, ext_ctx, "subjectKeyIdentifier", "hash", 1)) goto end; /* Prevent X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER */ ERR_set_mark(); self_sign = X509_check_private_key(cert, pkey); ERR_pop_to_mark(); if (!adapt_keyid_ext(cert, ext_ctx, "authorityKeyIdentifier", "keyid, issuer", !self_sign)) goto end; } if (mctx != NULL && do_sign_init(mctx, pkey, md, sigopts) > 0) rv = (X509_sign_ctx(cert, mctx) > 0); end: EVP_MD_CTX_free(mctx); return rv; } /* Sign the certificate request info */ int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const char *md, STACK_OF(OPENSSL_STRING) *sigopts) { int rv = 0; EVP_MD_CTX *mctx = EVP_MD_CTX_new(); if (do_sign_init(mctx, pkey, md, sigopts) > 0) rv = (X509_REQ_sign_ctx(x, mctx) > 0); EVP_MD_CTX_free(mctx); return rv; } /* Sign the CRL info */ int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const char *md, STACK_OF(OPENSSL_STRING) *sigopts) { int rv = 0; EVP_MD_CTX *mctx = EVP_MD_CTX_new(); if (do_sign_init(mctx, pkey, md, sigopts) > 0) rv = (X509_CRL_sign_ctx(x, mctx) > 0); EVP_MD_CTX_free(mctx); return rv; } /* * do_X509_verify returns 1 if the signature is valid, * 0 if the signature check fails, or -1 if error occurs. */ int do_X509_verify(X509 *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts) { int rv = 0; if (do_x509_init(x, vfyopts) > 0) rv = X509_verify(x, pkey); else rv = -1; return rv; } /* * do_X509_REQ_verify returns 1 if the signature is valid, * 0 if the signature check fails, or -1 if error occurs. */ int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts) { int rv = 0; if (do_x509_req_init(x, vfyopts) > 0) rv = X509_REQ_verify_ex(x, pkey, app_get0_libctx(), app_get0_propq()); else rv = -1; return rv; } /* Get first http URL from a DIST_POINT structure */ static const char *get_dp_url(DIST_POINT *dp) { GENERAL_NAMES *gens; GENERAL_NAME *gen; int i, gtype; ASN1_STRING *uri; if (!dp->distpoint || dp->distpoint->type != 0) return NULL; gens = dp->distpoint->name.fullname; for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) { gen = sk_GENERAL_NAME_value(gens, i); uri = GENERAL_NAME_get0_value(gen, >ype); if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) { const char *uptr = (const char *)ASN1_STRING_get0_data(uri); if (IS_HTTP(uptr)) /* can/should not use HTTPS here */ return uptr; } } return NULL; } /* * Look through a CRLDP structure and attempt to find an http URL to * downloads a CRL from. */ static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp) { int i; const char *urlptr = NULL; for (i = 0; i < sk_DIST_POINT_num(crldp); i++) { DIST_POINT *dp = sk_DIST_POINT_value(crldp, i); urlptr = get_dp_url(dp); if (urlptr != NULL) return load_crl(urlptr, FORMAT_UNDEF, 0, "CRL via CDP"); } return NULL; } /* * Example of downloading CRLs from CRLDP: * not usable for real world as it always downloads and doesn't cache anything. */ static STACK_OF(X509_CRL) *crls_http_cb(const X509_STORE_CTX *ctx, const X509_NAME *nm) { X509 *x; STACK_OF(X509_CRL) *crls = NULL; X509_CRL *crl; STACK_OF(DIST_POINT) *crldp; crls = sk_X509_CRL_new_null(); if (!crls) return NULL; x = X509_STORE_CTX_get_current_cert(ctx); crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL); crl = load_crl_crldp(crldp); sk_DIST_POINT_pop_free(crldp, DIST_POINT_free); if (!crl) { sk_X509_CRL_free(crls); return NULL; } sk_X509_CRL_push(crls, crl); /* Try to download delta CRL */ crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL); crl = load_crl_crldp(crldp); sk_DIST_POINT_pop_free(crldp, DIST_POINT_free); if (crl) sk_X509_CRL_push(crls, crl); return crls; } void store_setup_crl_download(X509_STORE *st) { X509_STORE_set_lookup_crls_cb(st, crls_http_cb); } #ifndef OPENSSL_NO_SOCK static const char *tls_error_hint(void) { unsigned long err = ERR_peek_error(); if (ERR_GET_LIB(err) != ERR_LIB_SSL) err = ERR_peek_last_error(); if (ERR_GET_LIB(err) != ERR_LIB_SSL) return NULL; switch (ERR_GET_REASON(err)) { case SSL_R_WRONG_VERSION_NUMBER: return "The server does not support (a suitable version of) TLS"; case SSL_R_UNKNOWN_PROTOCOL: return "The server does not support HTTPS"; case SSL_R_CERTIFICATE_VERIFY_FAILED: return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status"; case SSL_AD_REASON_OFFSET + TLS1_AD_UNKNOWN_CA: return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status"; case SSL_AD_REASON_OFFSET + SSL3_AD_HANDSHAKE_FAILURE: return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it"; default: /* no error or no hint available for error */ return NULL; } } /* HTTP callback function that supports TLS connection also via HTTPS proxy */ BIO *app_http_tls_cb(BIO *bio, void *arg, int connect, int detail) { APP_HTTP_TLS_INFO *info = (APP_HTTP_TLS_INFO *)arg; SSL_CTX *ssl_ctx = info->ssl_ctx; if (ssl_ctx == NULL) /* not using TLS */ return bio; if (connect) { SSL *ssl; BIO *sbio = NULL; X509_STORE *ts = SSL_CTX_get_cert_store(ssl_ctx); X509_VERIFY_PARAM *vpm = X509_STORE_get0_param(ts); const char *host = vpm == NULL ? NULL : X509_VERIFY_PARAM_get0_host(vpm, 0 /* first hostname */); /* adapt after fixing callback design flaw, see #17088 */ if ((info->use_proxy && !OSSL_HTTP_proxy_connect(bio, info->server, info->port, NULL, NULL, /* no proxy credentials */ info->timeout, bio_err, opt_getprog())) || (sbio = BIO_new(BIO_f_ssl())) == NULL) { return NULL; } if (ssl_ctx == NULL || (ssl = SSL_new(ssl_ctx)) == NULL) { BIO_free(sbio); return NULL; } if (vpm != NULL) SSL_set_tlsext_host_name(ssl, host /* may be NULL */); SSL_set_connect_state(ssl); BIO_set_ssl(sbio, ssl, BIO_CLOSE); bio = BIO_push(sbio, bio); } if (!connect) { const char *hint; BIO *cbio; if (!detail) { /* disconnecting after error */ hint = tls_error_hint(); if (hint != NULL) ERR_add_error_data(2, " : ", hint); } if (ssl_ctx != NULL) { (void)ERR_set_mark(); BIO_ssl_shutdown(bio); cbio = BIO_pop(bio); /* connect+HTTP BIO */ BIO_free(bio); /* SSL BIO */ (void)ERR_pop_to_mark(); /* hide SSL_R_READ_BIO_NOT_SET etc. */ bio = cbio; } } return bio; } void APP_HTTP_TLS_INFO_free(APP_HTTP_TLS_INFO *info) { if (info != NULL) { SSL_CTX_free(info->ssl_ctx); OPENSSL_free(info); } } ASN1_VALUE *app_http_get_asn1(const char *url, const char *proxy, const char *no_proxy, SSL_CTX *ssl_ctx, const STACK_OF(CONF_VALUE) *headers, long timeout, const char *expected_content_type, const ASN1_ITEM *it) { APP_HTTP_TLS_INFO info; char *server; char *port; int use_ssl; BIO *mem; ASN1_VALUE *resp = NULL; if (url == NULL || it == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (!OSSL_HTTP_parse_url(url, &use_ssl, NULL /* userinfo */, &server, &port, NULL /* port_num, */, NULL, NULL, NULL)) return NULL; if (use_ssl && ssl_ctx == NULL) { ERR_raise_data(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER, "missing SSL_CTX"); goto end; } if (!use_ssl && ssl_ctx != NULL) { ERR_raise_data(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT, "SSL_CTX given but use_ssl == 0"); goto end; } info.server = server; info.port = port; info.use_proxy = /* workaround for callback design flaw, see #17088 */ OSSL_HTTP_adapt_proxy(proxy, no_proxy, server, use_ssl) != NULL; info.timeout = timeout; info.ssl_ctx = ssl_ctx; mem = OSSL_HTTP_get(url, proxy, no_proxy, NULL /* bio */, NULL /* rbio */, app_http_tls_cb, &info, 0 /* buf_size */, headers, expected_content_type, 1 /* expect_asn1 */, OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout); resp = ASN1_item_d2i_bio(it, mem, NULL); BIO_free(mem); end: OPENSSL_free(server); OPENSSL_free(port); return resp; } ASN1_VALUE *app_http_post_asn1(const char *host, const char *port, const char *path, const char *proxy, const char *no_proxy, SSL_CTX *ssl_ctx, const STACK_OF(CONF_VALUE) *headers, const char *content_type, ASN1_VALUE *req, const ASN1_ITEM *req_it, const char *expected_content_type, long timeout, const ASN1_ITEM *rsp_it) { int use_ssl = ssl_ctx != NULL; APP_HTTP_TLS_INFO info; BIO *rsp, *req_mem = ASN1_item_i2d_mem_bio(req_it, req); ASN1_VALUE *res; if (req_mem == NULL) return NULL; info.server = host; info.port = port; info.use_proxy = /* workaround for callback design flaw, see #17088 */ OSSL_HTTP_adapt_proxy(proxy, no_proxy, host, use_ssl) != NULL; info.timeout = timeout; info.ssl_ctx = ssl_ctx; rsp = OSSL_HTTP_transfer(NULL, host, port, path, use_ssl, proxy, no_proxy, NULL /* bio */, NULL /* rbio */, app_http_tls_cb, &info, 0 /* buf_size */, headers, content_type, req_mem, expected_content_type, 1 /* expect_asn1 */, OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout, 0 /* keep_alive */); BIO_free(req_mem); res = ASN1_item_d2i_bio(rsp_it, rsp, NULL); BIO_free(rsp); return res; } #endif /* * Platform-specific sections */ #if defined(_WIN32) # ifdef fileno # undef fileno # define fileno(a) (int)_fileno(a) # endif # include # include static int WIN32_rename(const char *from, const char *to) { TCHAR *tfrom = NULL, *tto; DWORD err; int ret = 0; if (sizeof(TCHAR) == 1) { tfrom = (TCHAR *)from; tto = (TCHAR *)to; } else { /* UNICODE path */ size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1; tfrom = malloc(sizeof(*tfrom) * (flen + tlen)); if (tfrom == NULL) goto err; tto = tfrom + flen; # if !defined(_WIN32_WCE) || _WIN32_WCE>=101 if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen)) # endif for (i = 0; i < flen; i++) tfrom[i] = (TCHAR)from[i]; # if !defined(_WIN32_WCE) || _WIN32_WCE>=101 if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen)) # endif for (i = 0; i < tlen; i++) tto[i] = (TCHAR)to[i]; } if (MoveFile(tfrom, tto)) goto ok; err = GetLastError(); if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) { if (DeleteFile(tto) && MoveFile(tfrom, tto)) goto ok; err = GetLastError(); } if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND) errno = ENOENT; else if (err == ERROR_ACCESS_DENIED) errno = EACCES; else errno = EINVAL; /* we could map more codes... */ err: ret = -1; ok: if (tfrom != NULL && tfrom != (TCHAR *)from) free(tfrom); return ret; } #endif /* app_tminterval section */ #if defined(_WIN32) double app_tminterval(int stop, int usertime) { FILETIME now; double ret = 0; static ULARGE_INTEGER tmstart; static int warning = 1; # ifdef _WIN32_WINNT static HANDLE proc = NULL; if (proc == NULL) { if (check_winnt()) proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, GetCurrentProcessId()); if (proc == NULL) proc = (HANDLE) - 1; } if (usertime && proc != (HANDLE) - 1) { FILETIME junk; GetProcessTimes(proc, &junk, &junk, &junk, &now); } else # endif { SYSTEMTIME systime; if (usertime && warning) { BIO_printf(bio_err, "To get meaningful results, run " "this program on idle system.\n"); warning = 0; } GetSystemTime(&systime); SystemTimeToFileTime(&systime, &now); } if (stop == TM_START) { tmstart.u.LowPart = now.dwLowDateTime; tmstart.u.HighPart = now.dwHighDateTime; } else { ULARGE_INTEGER tmstop; tmstop.u.LowPart = now.dwLowDateTime; tmstop.u.HighPart = now.dwHighDateTime; ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7; } return ret; } #elif defined(OPENSSL_SYS_VXWORKS) # include double app_tminterval(int stop, int usertime) { double ret = 0; # ifdef CLOCK_REALTIME static struct timespec tmstart; struct timespec now; # else static unsigned long tmstart; unsigned long now; # endif static int warning = 1; if (usertime && warning) { BIO_printf(bio_err, "To get meaningful results, run " "this program on idle system.\n"); warning = 0; } # ifdef CLOCK_REALTIME clock_gettime(CLOCK_REALTIME, &now); if (stop == TM_START) tmstart = now; else ret = ((now.tv_sec + now.tv_nsec * 1e-9) - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9)); # else now = tickGet(); if (stop == TM_START) tmstart = now; else ret = (now - tmstart) / (double)sysClkRateGet(); # endif return ret; } #elif defined(_SC_CLK_TCK) /* by means of unistd.h */ # include double app_tminterval(int stop, int usertime) { double ret = 0; struct tms rus; clock_t now = times(&rus); static clock_t tmstart; if (usertime) now = rus.tms_utime; if (stop == TM_START) { tmstart = now; } else { long int tck = sysconf(_SC_CLK_TCK); ret = (now - tmstart) / (double)tck; } return ret; } #else # include # include double app_tminterval(int stop, int usertime) { double ret = 0; struct rusage rus; struct timeval now; static struct timeval tmstart; if (usertime) getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime; else gettimeofday(&now, NULL); if (stop == TM_START) tmstart = now; else ret = ((now.tv_sec + now.tv_usec * 1e-6) - (tmstart.tv_sec + tmstart.tv_usec * 1e-6)); return ret; } #endif int app_access(const char* name, int flag) { #ifdef _WIN32 return _access(name, flag); #else return access(name, flag); #endif } int app_isdir(const char *name) { return opt_isdir(name); } /* raw_read|write section */ #if defined(__VMS) # include "vms_term_sock.h" static int stdin_sock = -1; static void close_stdin_sock(void) { TerminalSocket (TERM_SOCK_DELETE, &stdin_sock); } int fileno_stdin(void) { if (stdin_sock == -1) { TerminalSocket(TERM_SOCK_CREATE, &stdin_sock); atexit(close_stdin_sock); } return stdin_sock; } #else int fileno_stdin(void) { return fileno(stdin); } #endif int fileno_stdout(void) { return fileno(stdout); } #if defined(_WIN32) && defined(STD_INPUT_HANDLE) int raw_read_stdin(void *buf, int siz) { DWORD n; if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL)) return n; else return -1; } #elif defined(__VMS) # include int raw_read_stdin(void *buf, int siz) { return recv(fileno_stdin(), buf, siz, 0); } #else # if defined(__TANDEM) # if defined(OPENSSL_TANDEM_FLOSS) # include # endif # endif int raw_read_stdin(void *buf, int siz) { return read(fileno_stdin(), buf, siz); } #endif #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE) int raw_write_stdout(const void *buf, int siz) { DWORD n; if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL)) return n; else return -1; } #elif defined(OPENSSL_SYS_TANDEM) && defined(OPENSSL_THREADS) && defined(_SPT_MODEL_) # if defined(__TANDEM) # if defined(OPENSSL_TANDEM_FLOSS) # include # endif # endif int raw_write_stdout(const void *buf,int siz) { return write(fileno(stdout),(void*)buf,siz); } #else # if defined(__TANDEM) # if defined(OPENSSL_TANDEM_FLOSS) # include # endif # endif int raw_write_stdout(const void *buf, int siz) { return write(fileno_stdout(), buf, siz); } #endif /* * Centralized handling of input and output files with format specification * The format is meant to show what the input and output is supposed to be, * and is therefore a show of intent more than anything else. However, it * does impact behavior on some platforms, such as differentiating between * text and binary input/output on non-Unix platforms */ BIO *dup_bio_in(int format) { return BIO_new_fp(stdin, BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0)); } BIO *dup_bio_out(int format) { BIO *b = BIO_new_fp(stdout, BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0)); void *prefix = NULL; if (b == NULL) return NULL; #ifdef OPENSSL_SYS_VMS if (FMT_istext(format)) b = BIO_push(BIO_new(BIO_f_linebuffer()), b); #endif if (FMT_istext(format) && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) { b = BIO_push(BIO_new(BIO_f_prefix()), b); BIO_set_prefix(b, prefix); } return b; } BIO *dup_bio_err(int format) { BIO *b = BIO_new_fp(stderr, BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0)); #ifdef OPENSSL_SYS_VMS if (b != NULL && FMT_istext(format)) b = BIO_push(BIO_new(BIO_f_linebuffer()), b); #endif return b; } void unbuffer(FILE *fp) { /* * On VMS, setbuf() will only take 32-bit pointers, and a compilation * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here. * However, we trust that the C RTL will never give us a FILE pointer * above the first 4 GB of memory, so we simply turn off the warning * temporarily. */ #if defined(OPENSSL_SYS_VMS) && defined(__DECC) # pragma environment save # pragma message disable maylosedata2 #endif setbuf(fp, NULL); #if defined(OPENSSL_SYS_VMS) && defined(__DECC) # pragma environment restore #endif } static const char *modestr(char mode, int format) { OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w'); switch (mode) { case 'a': return FMT_istext(format) ? "a" : "ab"; case 'r': return FMT_istext(format) ? "r" : "rb"; case 'w': return FMT_istext(format) ? "w" : "wb"; } /* The assert above should make sure we never reach this point */ return NULL; } static const char *modeverb(char mode) { switch (mode) { case 'a': return "appending"; case 'r': return "reading"; case 'w': return "writing"; } return "(doing something)"; } /* * Open a file for writing, owner-read-only. */ BIO *bio_open_owner(const char *filename, int format, int private) { FILE *fp = NULL; BIO *b = NULL; int textmode, bflags; #ifndef OPENSSL_NO_POSIX_IO int fd = -1, mode; #endif if (!private || filename == NULL || strcmp(filename, "-") == 0) return bio_open_default(filename, 'w', format); textmode = FMT_istext(format); #ifndef OPENSSL_NO_POSIX_IO mode = O_WRONLY; # ifdef O_CREAT mode |= O_CREAT; # endif # ifdef O_TRUNC mode |= O_TRUNC; # endif if (!textmode) { # ifdef O_BINARY mode |= O_BINARY; # elif defined(_O_BINARY) mode |= _O_BINARY; # endif } # ifdef OPENSSL_SYS_VMS /* VMS doesn't have O_BINARY, it just doesn't make sense. But, * it still needs to know that we're going binary, or fdopen() * will fail with "invalid argument"... so we tell VMS what the * context is. */ if (!textmode) fd = open(filename, mode, 0600, "ctx=bin"); else # endif fd = open(filename, mode, 0600); if (fd < 0) goto err; fp = fdopen(fd, modestr('w', format)); #else /* OPENSSL_NO_POSIX_IO */ /* Have stdio but not Posix IO, do the best we can */ fp = fopen(filename, modestr('w', format)); #endif /* OPENSSL_NO_POSIX_IO */ if (fp == NULL) goto err; bflags = BIO_CLOSE; if (textmode) bflags |= BIO_FP_TEXT; b = BIO_new_fp(fp, bflags); if (b != NULL) return b; err: BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n", opt_getprog(), filename, strerror(errno)); ERR_print_errors(bio_err); /* If we have fp, then fdopen took over fd, so don't close both. */ if (fp != NULL) fclose(fp); #ifndef OPENSSL_NO_POSIX_IO else if (fd >= 0) close(fd); #endif return NULL; } static BIO *bio_open_default_(const char *filename, char mode, int format, int quiet) { BIO *ret; if (filename == NULL || strcmp(filename, "-") == 0) { ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format); if (quiet) { ERR_clear_error(); return ret; } if (ret != NULL) return ret; BIO_printf(bio_err, "Can't open %s, %s\n", mode == 'r' ? "stdin" : "stdout", strerror(errno)); } else { ret = BIO_new_file(filename, modestr(mode, format)); if (quiet) { ERR_clear_error(); return ret; } if (ret != NULL) return ret; BIO_printf(bio_err, "Can't open \"%s\" for %s, %s\n", filename, modeverb(mode), strerror(errno)); } ERR_print_errors(bio_err); return NULL; } BIO *bio_open_default(const char *filename, char mode, int format) { return bio_open_default_(filename, mode, format, 0); } BIO *bio_open_default_quiet(const char *filename, char mode, int format) { return bio_open_default_(filename, mode, format, 1); } void wait_for_async(SSL *s) { /* On Windows select only works for sockets, so we simply don't wait */ #ifndef OPENSSL_SYS_WINDOWS int width = 0; fd_set asyncfds; OSSL_ASYNC_FD *fds; size_t numfds; size_t i; if (!SSL_get_all_async_fds(s, NULL, &numfds)) return; if (numfds == 0) return; fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds"); if (!SSL_get_all_async_fds(s, fds, &numfds)) { OPENSSL_free(fds); return; } FD_ZERO(&asyncfds); for (i = 0; i < numfds; i++) { if (width <= (int)fds[i]) width = (int)fds[i] + 1; openssl_fdset((int)fds[i], &asyncfds); } select(width, (void *)&asyncfds, NULL, NULL, NULL); OPENSSL_free(fds); #endif } /* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */ #if defined(OPENSSL_SYS_MSDOS) int has_stdin_waiting(void) { # if defined(OPENSSL_SYS_WINDOWS) HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE); DWORD events = 0; INPUT_RECORD inputrec; DWORD insize = 1; BOOL peeked; if (inhand == INVALID_HANDLE_VALUE) { return 0; } peeked = PeekConsoleInput(inhand, &inputrec, insize, &events); if (!peeked) { /* Probably redirected input? _kbhit() does not work in this case */ if (!feof(stdin)) { return 1; } return 0; } # endif return _kbhit(); } #endif /* Corrupt a signature by modifying final byte */ void corrupt_signature(const ASN1_STRING *signature) { unsigned char *s = signature->data; s[signature->length - 1] ^= 0x1; } int set_cert_times(X509 *x, const char *startdate, const char *enddate, int days) { if (startdate == NULL || strcmp(startdate, "today") == 0) { if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL) return 0; } else { if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate)) return 0; } if (enddate == NULL) { if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL) == NULL) return 0; } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) { return 0; } return 1; } int set_crl_lastupdate(X509_CRL *crl, const char *lastupdate) { int ret = 0; ASN1_TIME *tm = ASN1_TIME_new(); if (tm == NULL) goto end; if (lastupdate == NULL) { if (X509_gmtime_adj(tm, 0) == NULL) goto end; } else { if (!ASN1_TIME_set_string_X509(tm, lastupdate)) goto end; } if (!X509_CRL_set1_lastUpdate(crl, tm)) goto end; ret = 1; end: ASN1_TIME_free(tm); return ret; } int set_crl_nextupdate(X509_CRL *crl, const char *nextupdate, long days, long hours, long secs) { int ret = 0; ASN1_TIME *tm = ASN1_TIME_new(); if (tm == NULL) goto end; if (nextupdate == NULL) { if (X509_time_adj_ex(tm, days, hours * 60 * 60 + secs, NULL) == NULL) goto end; } else { if (!ASN1_TIME_set_string_X509(tm, nextupdate)) goto end; } if (!X509_CRL_set1_nextUpdate(crl, tm)) goto end; ret = 1; end: ASN1_TIME_free(tm); return ret; } void make_uppercase(char *string) { int i; for (i = 0; string[i] != '\0'; i++) string[i] = toupper((unsigned char)string[i]); } /* This function is defined here due to visibility of bio_err */ int opt_printf_stderr(const char *fmt, ...) { va_list ap; int ret; va_start(ap, fmt); ret = BIO_vprintf(bio_err, fmt, ap); va_end(ap); return ret; } OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts, const OSSL_PARAM *paramdefs) { OSSL_PARAM *params = NULL; size_t sz = (size_t)sk_OPENSSL_STRING_num(opts); size_t params_n; char *opt = "", *stmp, *vtmp = NULL; int found = 1; if (opts == NULL) return NULL; params = OPENSSL_zalloc(sizeof(OSSL_PARAM) * (sz + 1)); if (params == NULL) return NULL; for (params_n = 0; params_n < sz; params_n++) { opt = sk_OPENSSL_STRING_value(opts, (int)params_n); if ((stmp = OPENSSL_strdup(opt)) == NULL || (vtmp = strchr(stmp, ':')) == NULL) goto err; /* Replace ':' with 0 to terminate the string pointed to by stmp */ *vtmp = 0; /* Skip over the separator so that vmtp points to the value */ vtmp++; if (!OSSL_PARAM_allocate_from_text(¶ms[params_n], paramdefs, stmp, vtmp, strlen(vtmp), &found)) goto err; OPENSSL_free(stmp); } params[params_n] = OSSL_PARAM_construct_end(); return params; err: OPENSSL_free(stmp); BIO_printf(bio_err, "Parameter %s '%s'\n", found ? "error" : "unknown", opt); ERR_print_errors(bio_err); app_params_free(params); return NULL; } void app_params_free(OSSL_PARAM *params) { int i; if (params != NULL) { for (i = 0; params[i].key != NULL; ++i) OPENSSL_free(params[i].data); OPENSSL_free(params); } } EVP_PKEY *app_keygen(EVP_PKEY_CTX *ctx, const char *alg, int bits, int verbose) { EVP_PKEY *res = NULL; if (verbose && alg != NULL) { BIO_printf(bio_err, "Generating %s key", alg); if (bits > 0) BIO_printf(bio_err, " with %d bits\n", bits); else BIO_printf(bio_err, "\n"); } if (!RAND_status()) BIO_printf(bio_err, "Warning: generating random key material may take a long time\n" "if the system has a poor entropy source\n"); if (EVP_PKEY_keygen(ctx, &res) <= 0) app_bail_out("%s: Error generating %s key\n", opt_getprog(), alg != NULL ? alg : "asymmetric"); return res; } EVP_PKEY *app_paramgen(EVP_PKEY_CTX *ctx, const char *alg) { EVP_PKEY *res = NULL; if (!RAND_status()) BIO_printf(bio_err, "Warning: generating random key parameters may take a long time\n" "if the system has a poor entropy source\n"); if (EVP_PKEY_paramgen(ctx, &res) <= 0) app_bail_out("%s: Generating %s key parameters failed\n", opt_getprog(), alg != NULL ? alg : "asymmetric"); return res; } /* * Return non-zero if the legacy path is still an option. * This decision is based on the global command line operations and the * behaviour thus far. */ int opt_legacy_okay(void) { int provider_options = opt_provider_option_given(); int libctx = app_get0_libctx() != NULL || app_get0_propq() != NULL; /* * Having a provider option specified or a custom library context or * property query, is a sure sign we're not using legacy. */ if (provider_options || libctx) return 0; return 1; } diff --git a/apps/req.c b/apps/req.c index 73b320a7098c..926f0796bc8f 100644 --- a/apps/req.c +++ b/apps/req.c @@ -1,1684 +1,1684 @@ /* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include #include #include #include #include #include "apps.h" #include "progs.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef OPENSSL_NO_DSA # include #endif #define BITS "default_bits" #define KEYFILE "default_keyfile" #define PROMPT "prompt" #define DISTINGUISHED_NAME "distinguished_name" #define ATTRIBUTES "attributes" #define V3_EXTENSIONS "x509_extensions" #define REQ_EXTENSIONS "req_extensions" #define STRING_MASK "string_mask" #define UTF8_IN "utf8" #define DEFAULT_KEY_LENGTH 2048 #define MIN_KEY_LENGTH 512 #define DEFAULT_DAYS 30 /* default cert validity period in days */ #define UNSET_DAYS -2 /* -1 may be used for testing expiration checks */ #define EXT_COPY_UNSET -1 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, X509_NAME *fsubj, int mutlirdn, int attribs, unsigned long chtype); static int prompt_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect, STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect, int attribs, unsigned long chtype); static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk, STACK_OF(CONF_VALUE) *attr, int attribs, unsigned long chtype); static int add_attribute_object(X509_REQ *req, char *text, const char *def, char *value, int nid, int n_min, int n_max, unsigned long chtype); static int add_DN_object(X509_NAME *n, char *text, const char *def, char *value, int nid, int n_min, int n_max, unsigned long chtype, int mval); static int genpkey_cb(EVP_PKEY_CTX *ctx); static int build_data(char *text, const char *def, char *value, int n_min, int n_max, char *buf, const int buf_size, const char *desc1, const char *desc2); static int req_check_len(int len, int n_min, int n_max); static int check_end(const char *str, const char *end); static int join(char buf[], size_t buf_size, const char *name, const char *tail, const char *desc); static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr, char **pkeytype, long *pkeylen, ENGINE *keygen_engine); static const char *section = "req"; static CONF *req_conf = NULL; static CONF *addext_conf = NULL; static int batch = 0; typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY, OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT, OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY, OPT_PKEYOPT, OPT_SIGOPT, OPT_VFYOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS, OPT_VERIFY, OPT_NOENC, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8, OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509, OPT_CA, OPT_CAKEY, OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_COPY_EXTENSIONS, OPT_ADDEXT, OPT_EXTENSIONS, OPT_REQEXTS, OPT_PRECERT, OPT_MD, OPT_SECTION, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS req_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, {"keygen_engine", OPT_KEYGEN_ENGINE, 's', "Specify engine to be used for key generation operations"}, #endif {"in", OPT_IN, '<', "X.509 request input file (default stdin)"}, {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"}, {"verify", OPT_VERIFY, '-', "Verify self-signature on the request"}, OPT_SECTION("Certificate"), {"new", OPT_NEW, '-', "New request"}, {"config", OPT_CONFIG, '<', "Request template file"}, {"section", OPT_SECTION, 's', "Config section to use (default \"req\")"}, {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"}, {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"}, {"reqopt", OPT_REQOPT, 's', "Various request text options"}, {"text", OPT_TEXT, '-', "Text form of request"}, {"x509", OPT_X509, '-', "Output an X.509 certificate structure instead of a cert request"}, {"CA", OPT_CA, '<', "Issuer cert to use for signing a cert, implies -x509"}, {"CAkey", OPT_CAKEY, 's', "Issuer private key to use with -CA; default is -CA arg"}, {OPT_MORE_STR, 1, 1, "(Required by some CA's)"}, {"subj", OPT_SUBJ, 's', "Set or modify subject of request or cert"}, {"subject", OPT_SUBJECT, '-', "Print the subject of the output request or cert"}, {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-', "Deprecated; multi-valued RDNs support is always on."}, {"days", OPT_DAYS, 'p', "Number of days cert is valid for"}, {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"}, {"copy_extensions", OPT_COPY_EXTENSIONS, 's', "copy extensions from request when using -x509"}, {"addext", OPT_ADDEXT, 's', "Additional cert extension key=value pair (may be given more than once)"}, {"extensions", OPT_EXTENSIONS, 's', "Cert extension section (override value in config file)"}, {"reqexts", OPT_REQEXTS, 's', "Request extension section (override value in config file)"}, {"precert", OPT_PRECERT, '-', "Add a poison extension to the generated cert (implies -new)"}, OPT_SECTION("Keys and Signing"), {"key", OPT_KEY, 's', "Key for signing, and to include unless -in given"}, {"keyform", OPT_KEYFORM, 'f', "Key file format (ENGINE, other values ignored)"}, {"pubkey", OPT_PUBKEY, '-', "Output public key"}, {"keyout", OPT_KEYOUT, '>', "File to write private key to"}, {"passin", OPT_PASSIN, 's', "Private key and certificate password source"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, {"newkey", OPT_NEWKEY, 's', "Generate new key with [:] or [:] or param:"}, {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"}, {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"}, {"vfyopt", OPT_VFYOPT, 's', "Verification parameter in n:v form"}, {"", OPT_MD, '-', "Any supported digest"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"}, {"batch", OPT_BATCH, '-', "Do not ask anything during request generation"}, {"verbose", OPT_VERBOSE, '-', "Verbose output"}, {"noenc", OPT_NOENC, '-', "Don't encrypt private keys"}, {"nodes", OPT_NODES, '-', "Don't encrypt private keys; deprecated"}, {"noout", OPT_NOOUT, '-', "Do not output REQ"}, {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"}, {"modulus", OPT_MODULUS, '-', "RSA modulus"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, {NULL} }; /* * An LHASH of strings, where each string is an extension name. */ static unsigned long ext_name_hash(const OPENSSL_STRING *a) { return OPENSSL_LH_strhash((const char *)a); } static int ext_name_cmp(const OPENSSL_STRING *a, const OPENSSL_STRING *b) { return strcmp((const char *)a, (const char *)b); } static void exts_cleanup(OPENSSL_STRING *x) { OPENSSL_free((char *)x); } /* * Is the |kv| key already duplicated? This is remarkably tricky to get right. * Return 0 if unique, -1 on runtime error; 1 if found or a syntax error. */ static int duplicated(LHASH_OF(OPENSSL_STRING) *addexts, char *kv) { char *p; size_t off; /* Check syntax. */ /* Skip leading whitespace, make a copy. */ while (*kv && isspace(_UC(*kv))) if (*++kv == '\0') return 1; if ((p = strchr(kv, '=')) == NULL) return 1; off = p - kv; if ((kv = OPENSSL_strdup(kv)) == NULL) return -1; /* Skip trailing space before the equal sign. */ for (p = kv + off; p > kv; --p) if (!isspace(_UC(p[-1]))) break; if (p == kv) { OPENSSL_free(kv); return 1; } *p = '\0'; /* Finally have a clean "key"; see if it's there [by attempt to add it]. */ p = (char *)lh_OPENSSL_STRING_insert(addexts, (OPENSSL_STRING *)kv); if (p != NULL) { OPENSSL_free(p); return 1; } else if (lh_OPENSSL_STRING_error(addexts)) { OPENSSL_free(kv); return -1; } return 0; } int req_main(int argc, char **argv) { ASN1_INTEGER *serial = NULL; BIO *out = NULL; ENGINE *e = NULL, *gen_eng = NULL; EVP_PKEY *pkey = NULL, *CAkey = NULL; EVP_PKEY_CTX *genctx = NULL; STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL, *vfyopts = NULL; LHASH_OF(OPENSSL_STRING) *addexts = NULL; X509 *new_x509 = NULL, *CAcert = NULL; X509_REQ *req = NULL; EVP_CIPHER *cipher = NULL; EVP_MD *md = NULL; int ext_copy = EXT_COPY_UNSET; BIO *addext_bio = NULL; char *extensions = NULL; const char *infile = NULL, *CAfile = NULL, *CAkeyfile = NULL; char *outfile = NULL, *keyfile = NULL, *digest = NULL; char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL; char *passin = NULL, *passout = NULL; char *nofree_passin = NULL, *nofree_passout = NULL; char *req_exts = NULL, *subj = NULL; X509_NAME *fsubj = NULL; char *template = default_config_file, *keyout = NULL; const char *keyalg = NULL; OPTION_CHOICE o; int days = UNSET_DAYS; int ret = 1, gen_x509 = 0, i = 0, newreq = 0, verbose = 0; int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, keyform = FORMAT_UNDEF; int modulus = 0, multirdn = 1, verify = 0, noout = 0, text = 0; int noenc = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0; long newkey_len = -1; unsigned long chtype = MBSTRING_ASC, reqflag = 0; #ifndef OPENSSL_NO_DES cipher = (EVP_CIPHER *)EVP_des_ede3_cbc(); #endif prog = opt_init(argc, argv, req_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(req_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_KEYGEN_ENGINE: #ifndef OPENSSL_NO_ENGINE gen_eng = setup_engine(opt_arg(), 0); if (gen_eng == NULL) { BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv); goto opthelp; } #endif break; case OPT_KEY: keyfile = opt_arg(); break; case OPT_PUBKEY: pubkey = 1; break; case OPT_NEW: newreq = 1; break; case OPT_CONFIG: template = opt_arg(); break; case OPT_SECTION: section = opt_arg(); break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_KEYOUT: keyout = opt_arg(); break; case OPT_PASSIN: passargin = opt_arg(); break; case OPT_PASSOUT: passargout = opt_arg(); break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_NEWKEY: keyalg = opt_arg(); newreq = 1; break; case OPT_PKEYOPT: if (pkeyopts == NULL) pkeyopts = sk_OPENSSL_STRING_new_null(); if (pkeyopts == NULL || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg())) goto opthelp; break; case OPT_SIGOPT: if (!sigopts) sigopts = sk_OPENSSL_STRING_new_null(); if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg())) goto opthelp; break; case OPT_VFYOPT: if (!vfyopts) vfyopts = sk_OPENSSL_STRING_new_null(); if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg())) goto opthelp; break; case OPT_BATCH: batch = 1; break; case OPT_NEWHDR: newhdr = 1; break; case OPT_MODULUS: modulus = 1; break; case OPT_VERIFY: verify = 1; break; case OPT_NODES: case OPT_NOENC: noenc = 1; break; case OPT_NOOUT: noout = 1; break; case OPT_VERBOSE: verbose = 1; break; case OPT_UTF8: chtype = MBSTRING_UTF8; break; case OPT_NAMEOPT: if (!set_nameopt(opt_arg())) goto opthelp; break; case OPT_REQOPT: if (!set_cert_ex(&reqflag, opt_arg())) goto opthelp; break; case OPT_TEXT: text = 1; break; case OPT_X509: gen_x509 = 1; break; case OPT_CA: CAfile = opt_arg(); gen_x509 = 1; break; case OPT_CAKEY: CAkeyfile = opt_arg(); break; case OPT_DAYS: days = atoi(opt_arg()); if (days < -1) { BIO_printf(bio_err, "%s: -days parameter arg must be >= -1\n", prog); goto end; } break; case OPT_SET_SERIAL: if (serial != NULL) { BIO_printf(bio_err, "Serial number supplied twice\n"); goto opthelp; } serial = s2i_ASN1_INTEGER(NULL, opt_arg()); if (serial == NULL) goto opthelp; break; case OPT_SUBJECT: subject = 1; break; case OPT_SUBJ: subj = opt_arg(); break; case OPT_MULTIVALUE_RDN: /* obsolete */ break; case OPT_COPY_EXTENSIONS: if (!set_ext_copy(&ext_copy, opt_arg())) { BIO_printf(bio_err, "Invalid extension copy option: \"%s\"\n", opt_arg()); goto end; } break; case OPT_ADDEXT: p = opt_arg(); if (addexts == NULL) { addexts = lh_OPENSSL_STRING_new(ext_name_hash, ext_name_cmp); addext_bio = BIO_new(BIO_s_mem()); if (addexts == NULL || addext_bio == NULL) goto end; } i = duplicated(addexts, p); if (i == 1) { BIO_printf(bio_err, "Duplicate extension: %s\n", p); goto opthelp; } if (i < 0 || BIO_printf(addext_bio, "%s\n", p) < 0) goto end; break; case OPT_EXTENSIONS: extensions = opt_arg(); break; case OPT_REQEXTS: req_exts = opt_arg(); break; case OPT_PRECERT: newreq = precert = 1; break; case OPT_MD: digest = opt_unknown(); break; } } /* No extra arguments. */ argc = opt_num_rest(); if (argc != 0) goto opthelp; if (!app_RAND_load()) goto end; if (!gen_x509) { if (days != UNSET_DAYS) BIO_printf(bio_err, "Ignoring -days without -x509; not generating a certificate\n"); if (ext_copy == EXT_COPY_NONE) BIO_printf(bio_err, "Ignoring -copy_extensions 'none' when -x509 is not given\n"); } if (gen_x509 && infile == NULL) newreq = 1; if (!app_passwd(passargin, passargout, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } if ((req_conf = app_load_config_verbose(template, verbose)) == NULL) goto end; if (addext_bio != NULL) { if (verbose) BIO_printf(bio_err, "Using additional configuration from -addext options\n"); if ((addext_conf = app_load_config_bio(addext_bio, NULL)) == NULL) goto end; } if (template != default_config_file && !app_load_modules(req_conf)) goto end; if (req_conf != NULL) { p = NCONF_get_string(req_conf, NULL, "oid_file"); if (p == NULL) ERR_clear_error(); if (p != NULL) { BIO *oid_bio = BIO_new_file(p, "r"); if (oid_bio == NULL) { if (verbose) BIO_printf(bio_err, "Problems opening '%s' for extra OIDs\n", p); } else { OBJ_create_objects(oid_bio); BIO_free(oid_bio); } } } if (!add_oid_section(req_conf)) goto end; /* Check that any specified digest is fetchable */ if (digest != NULL) { if (!opt_md(digest, &md)) { ERR_clear_error(); goto opthelp; } EVP_MD_free(md); } else { /* No digest specified, default to configuration */ p = NCONF_get_string(req_conf, section, "default_md"); if (p == NULL) ERR_clear_error(); else digest = p; } if (extensions == NULL) { extensions = NCONF_get_string(req_conf, section, V3_EXTENSIONS); if (extensions == NULL) ERR_clear_error(); } if (extensions != NULL) { /* Check syntax of file */ X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); X509V3_set_nconf(&ctx, req_conf); if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) { BIO_printf(bio_err, "Error checking x509 extension section %s\n", extensions); goto end; } } if (addext_conf != NULL) { /* Check syntax of command line extensions */ X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); X509V3_set_nconf(&ctx, addext_conf); if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) { BIO_printf(bio_err, "Error checking extensions defined using -addext\n"); goto end; } } if (passin == NULL) { passin = nofree_passin = NCONF_get_string(req_conf, section, "input_password"); if (passin == NULL) ERR_clear_error(); } if (passout == NULL) { passout = nofree_passout = NCONF_get_string(req_conf, section, "output_password"); if (passout == NULL) ERR_clear_error(); } p = NCONF_get_string(req_conf, section, STRING_MASK); if (p == NULL) ERR_clear_error(); if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) { BIO_printf(bio_err, "Invalid global string mask setting %s\n", p); goto end; } if (chtype != MBSTRING_UTF8) { p = NCONF_get_string(req_conf, section, UTF8_IN); if (p == NULL) ERR_clear_error(); else if (strcmp(p, "yes") == 0) chtype = MBSTRING_UTF8; } if (req_exts == NULL) { req_exts = NCONF_get_string(req_conf, section, REQ_EXTENSIONS); if (req_exts == NULL) ERR_clear_error(); } if (req_exts != NULL) { /* Check syntax of file */ X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); X509V3_set_nconf(&ctx, req_conf); if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) { BIO_printf(bio_err, "Error checking request extension section %s\n", req_exts); goto end; } } if (keyfile != NULL) { pkey = load_key(keyfile, keyform, 0, passin, e, "private key"); if (pkey == NULL) goto end; app_RAND_load_conf(req_conf, section); } if (newreq && pkey == NULL) { app_RAND_load_conf(req_conf, section); if (!NCONF_get_number(req_conf, section, BITS, &newkey_len)) { ERR_clear_error(); newkey_len = DEFAULT_KEY_LENGTH; } genctx = set_keygen_ctx(keyalg, &keyalgstr, &newkey_len, gen_eng); if (genctx == NULL) goto end; if (newkey_len < MIN_KEY_LENGTH && (EVP_PKEY_CTX_is_a(genctx, "RSA") || EVP_PKEY_CTX_is_a(genctx, "RSA-PSS") || EVP_PKEY_CTX_is_a(genctx, "DSA"))) { BIO_printf(bio_err, "Private key length too short, needs to be at least %d bits, not %ld.\n", MIN_KEY_LENGTH, newkey_len); goto end; } if (newkey_len > OPENSSL_RSA_MAX_MODULUS_BITS && (EVP_PKEY_CTX_is_a(genctx, "RSA") || EVP_PKEY_CTX_is_a(genctx, "RSA-PSS"))) BIO_printf(bio_err, "Warning: It is not recommended to use more than %d bit for RSA keys.\n" " Your key size is %ld! Larger key size may behave not as expected.\n", OPENSSL_RSA_MAX_MODULUS_BITS, newkey_len); #ifndef OPENSSL_NO_DSA if (EVP_PKEY_CTX_is_a(genctx, "DSA") && newkey_len > OPENSSL_DSA_MAX_MODULUS_BITS) BIO_printf(bio_err, "Warning: It is not recommended to use more than %d bit for DSA keys.\n" " Your key size is %ld! Larger key size may behave not as expected.\n", OPENSSL_DSA_MAX_MODULUS_BITS, newkey_len); #endif if (pkeyopts != NULL) { char *genopt; for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) { genopt = sk_OPENSSL_STRING_value(pkeyopts, i); if (pkey_ctrl_string(genctx, genopt) <= 0) { BIO_printf(bio_err, "Key parameter error \"%s\"\n", genopt); goto end; } } } EVP_PKEY_CTX_set_cb(genctx, genpkey_cb); EVP_PKEY_CTX_set_app_data(genctx, bio_err); pkey = app_keygen(genctx, keyalgstr, newkey_len, verbose); EVP_PKEY_CTX_free(genctx); genctx = NULL; } if (keyout == NULL && keyfile == NULL) { keyout = NCONF_get_string(req_conf, section, KEYFILE); if (keyout == NULL) ERR_clear_error(); } if (pkey != NULL && (keyfile == NULL || keyout != NULL)) { if (verbose) { BIO_printf(bio_err, "Writing private key to "); if (keyout == NULL) BIO_printf(bio_err, "stdout\n"); else BIO_printf(bio_err, "'%s'\n", keyout); } out = bio_open_owner(keyout, outformat, newreq); if (out == NULL) goto end; p = NCONF_get_string(req_conf, section, "encrypt_rsa_key"); if (p == NULL) { ERR_clear_error(); p = NCONF_get_string(req_conf, section, "encrypt_key"); if (p == NULL) ERR_clear_error(); } if ((p != NULL) && (strcmp(p, "no") == 0)) cipher = NULL; if (noenc) cipher = NULL; i = 0; loop: if (!PEM_write_bio_PrivateKey(out, pkey, cipher, NULL, 0, NULL, passout)) { if ((ERR_GET_REASON(ERR_peek_error()) == PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) { ERR_clear_error(); i++; goto loop; } goto end; } BIO_free(out); out = NULL; BIO_printf(bio_err, "-----\n"); } /* * subj is expected to be in the format /type0=value0/type1=value1/type2=... * where characters may be escaped by \ */ if (subj != NULL && (fsubj = parse_name(subj, chtype, multirdn, "subject")) == NULL) goto end; if (!newreq) { req = load_csr(infile /* if NULL, reads from stdin */, informat, "X509 request"); if (req == NULL) goto end; } if (CAkeyfile == NULL) CAkeyfile = CAfile; if (CAkeyfile != NULL) { if (CAfile == NULL) { BIO_printf(bio_err, "Warning: Ignoring -CAkey option since no -CA option is given\n"); } else { if ((CAkey = load_key(CAkeyfile, FORMAT_UNDEF, 0, passin, e, CAkeyfile != CAfile ? "issuer private key from -CAkey arg" : "issuer private key from -CA arg")) == NULL) goto end; } } if (CAfile != NULL) { if ((CAcert = load_cert_pass(CAfile, FORMAT_UNDEF, 1, passin, "issuer cert from -CA arg")) == NULL) goto end; if (!X509_check_private_key(CAcert, CAkey)) { BIO_printf(bio_err, "Issuer CA certificate and key do not match\n"); goto end; } } if (newreq || gen_x509) { if (CAcert == NULL && pkey == NULL) { BIO_printf(bio_err, "Must provide a signature key using -key or" " provide -CA / -CAkey\n"); goto end; } if (req == NULL) { req = X509_REQ_new_ex(app_get0_libctx(), app_get0_propq()); if (req == NULL) { goto end; } if (!make_REQ(req, pkey, fsubj, multirdn, !gen_x509, chtype)){ BIO_printf(bio_err, "Error making certificate request\n"); goto end; } /* Note that -x509 can take over -key and -subj option values. */ } if (gen_x509) { EVP_PKEY *pub_key = X509_REQ_get0_pubkey(req); EVP_PKEY *issuer_key = CAcert != NULL ? CAkey : pkey; X509V3_CTX ext_ctx; X509_NAME *issuer = CAcert != NULL ? X509_get_subject_name(CAcert) : X509_REQ_get_subject_name(req); X509_NAME *n_subj = fsubj != NULL ? fsubj : X509_REQ_get_subject_name(req); if ((new_x509 = X509_new_ex(app_get0_libctx(), app_get0_propq())) == NULL) goto end; if (serial != NULL) { if (!X509_set_serialNumber(new_x509, serial)) goto end; } else { if (!rand_serial(NULL, X509_get_serialNumber(new_x509))) goto end; } if (!X509_set_issuer_name(new_x509, issuer)) goto end; if (days == UNSET_DAYS) { days = DEFAULT_DAYS; } if (!set_cert_times(new_x509, NULL, NULL, days)) goto end; if (!X509_set_subject_name(new_x509, n_subj)) goto end; if (!pub_key || !X509_set_pubkey(new_x509, pub_key)) goto end; if (ext_copy == EXT_COPY_UNSET) { if (infile != NULL) BIO_printf(bio_err, "Warning: No -copy_extensions given; ignoring any extensions in the request\n"); } else if (!copy_extensions(new_x509, req, ext_copy)) { BIO_printf(bio_err, "Error copying extensions from request\n"); goto end; } /* Set up V3 context struct */ X509V3_set_ctx(&ext_ctx, CAcert != NULL ? CAcert : new_x509, new_x509, NULL, NULL, X509V3_CTX_REPLACE); /* prepare fallback for AKID, but only if issuer cert == new_x509 */ if (CAcert == NULL) { if (!X509V3_set_issuer_pkey(&ext_ctx, issuer_key)) goto end; ERR_set_mark(); if (!X509_check_private_key(new_x509, issuer_key)) BIO_printf(bio_err, "Warning: Signature key and public key of cert do not match\n"); ERR_pop_to_mark(); } X509V3_set_nconf(&ext_ctx, req_conf); /* Add extensions */ if (extensions != NULL && !X509V3_EXT_add_nconf(req_conf, &ext_ctx, extensions, new_x509)) { BIO_printf(bio_err, "Error adding x509 extensions from section %s\n", extensions); goto end; } if (addext_conf != NULL && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default", new_x509)) { BIO_printf(bio_err, "Error adding extensions defined via -addext\n"); goto end; } /* If a pre-cert was requested, we need to add a poison extension */ if (precert) { if (X509_add1_ext_i2d(new_x509, NID_ct_precert_poison, NULL, 1, 0) != 1) { BIO_printf(bio_err, "Error adding poison extension\n"); goto end; } } i = do_X509_sign(new_x509, issuer_key, digest, sigopts, &ext_ctx); if (!i) goto end; } else { X509V3_CTX ext_ctx; /* Set up V3 context struct */ X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0); X509V3_set_nconf(&ext_ctx, req_conf); /* Add extensions */ if (req_exts != NULL && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx, req_exts, req)) { BIO_printf(bio_err, "Error adding request extensions from section %s\n", req_exts); goto end; } if (addext_conf != NULL && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default", req)) { BIO_printf(bio_err, "Error adding extensions defined via -addext\n"); goto end; } i = do_X509_REQ_sign(req, pkey, digest, sigopts); if (!i) goto end; } } if (subj != NULL && !newreq && !gen_x509) { if (verbose) { BIO_printf(out, "Modifying subject of certificate request\n"); print_name(out, "Old subject=", X509_REQ_get_subject_name(req)); } if (!X509_REQ_set_subject_name(req, fsubj)) { BIO_printf(bio_err, "Error modifying subject of certificate request\n"); goto end; } if (verbose) { print_name(out, "New subject=", X509_REQ_get_subject_name(req)); } } if (verify) { EVP_PKEY *tpubkey = pkey; if (tpubkey == NULL) { tpubkey = X509_REQ_get0_pubkey(req); if (tpubkey == NULL) goto end; } i = do_X509_REQ_verify(req, tpubkey, vfyopts); if (i < 0) goto end; if (i == 0) BIO_printf(bio_err, "Certificate request self-signature verify failure\n"); else /* i > 0 */ BIO_printf(bio_err, "Certificate request self-signature verify OK\n"); } if (noout && !text && !modulus && !subject && !pubkey) { ret = 0; goto end; } out = bio_open_default(outfile, keyout != NULL && outfile != NULL && strcmp(keyout, outfile) == 0 ? 'a' : 'w', outformat); if (out == NULL) goto end; if (pubkey) { EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req); if (tpubkey == NULL) { BIO_printf(bio_err, "Error getting public key\n"); goto end; } PEM_write_bio_PUBKEY(out, tpubkey); } if (text) { if (gen_x509) ret = X509_print_ex(out, new_x509, get_nameopt(), reqflag); else ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag); if (ret == 0) { if (gen_x509) BIO_printf(bio_err, "Error printing certificate\n"); else BIO_printf(bio_err, "Error printing certificate request\n"); goto end; } } if (subject) { print_name(out, "subject=", gen_x509 ? X509_get_subject_name(new_x509) : X509_REQ_get_subject_name(req)); } if (modulus) { EVP_PKEY *tpubkey; if (gen_x509) tpubkey = X509_get0_pubkey(new_x509); else tpubkey = X509_REQ_get0_pubkey(req); if (tpubkey == NULL) { - fprintf(stdout, "Modulus is unavailable\n"); + BIO_puts(bio_err, "Modulus is unavailable\n"); goto end; } - fprintf(stdout, "Modulus="); + BIO_puts(out, "Modulus="); if (EVP_PKEY_is_a(tpubkey, "RSA") || EVP_PKEY_is_a(tpubkey, "RSA-PSS")) { BIGNUM *n = NULL; if (!EVP_PKEY_get_bn_param(tpubkey, "n", &n)) goto end; BN_print(out, n); BN_free(n); } else { - fprintf(stdout, "Wrong Algorithm type"); + BIO_puts(out, "Wrong Algorithm type"); } - fprintf(stdout, "\n"); + BIO_puts(out, "\n"); } if (!noout && !gen_x509) { if (outformat == FORMAT_ASN1) i = i2d_X509_REQ_bio(out, req); else if (newhdr) i = PEM_write_bio_X509_REQ_NEW(out, req); else i = PEM_write_bio_X509_REQ(out, req); if (!i) { BIO_printf(bio_err, "Unable to write certificate request\n"); goto end; } } if (!noout && gen_x509 && new_x509 != NULL) { if (outformat == FORMAT_ASN1) i = i2d_X509_bio(out, new_x509); else i = PEM_write_bio_X509(out, new_x509); if (!i) { BIO_printf(bio_err, "Unable to write X509 certificate\n"); goto end; } } ret = 0; end: if (ret) { ERR_print_errors(bio_err); } NCONF_free(req_conf); NCONF_free(addext_conf); BIO_free(addext_bio); BIO_free_all(out); EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(genctx); sk_OPENSSL_STRING_free(pkeyopts); sk_OPENSSL_STRING_free(sigopts); sk_OPENSSL_STRING_free(vfyopts); lh_OPENSSL_STRING_doall(addexts, exts_cleanup); lh_OPENSSL_STRING_free(addexts); #ifndef OPENSSL_NO_ENGINE release_engine(gen_eng); #endif OPENSSL_free(keyalgstr); X509_REQ_free(req); X509_NAME_free(fsubj); X509_free(new_x509); X509_free(CAcert); EVP_PKEY_free(CAkey); ASN1_INTEGER_free(serial); release_engine(e); if (passin != nofree_passin) OPENSSL_free(passin); if (passout != nofree_passout) OPENSSL_free(passout); return ret; } static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, X509_NAME *fsubj, int multirdn, int attribs, unsigned long chtype) { int ret = 0, i; char no_prompt = 0; STACK_OF(CONF_VALUE) *dn_sk = NULL, *attr_sk = NULL; char *tmp, *dn_sect, *attr_sect; tmp = NCONF_get_string(req_conf, section, PROMPT); if (tmp == NULL) ERR_clear_error(); if ((tmp != NULL) && strcmp(tmp, "no") == 0) no_prompt = 1; dn_sect = NCONF_get_string(req_conf, section, DISTINGUISHED_NAME); if (dn_sect == NULL) { ERR_clear_error(); } else { dn_sk = NCONF_get_section(req_conf, dn_sect); if (dn_sk == NULL) { BIO_printf(bio_err, "Unable to get '%s' section\n", dn_sect); goto err; } } attr_sect = NCONF_get_string(req_conf, section, ATTRIBUTES); if (attr_sect == NULL) { ERR_clear_error(); } else { attr_sk = NCONF_get_section(req_conf, attr_sect); if (attr_sk == NULL) { BIO_printf(bio_err, "Unable to get '%s' section\n", attr_sect); goto err; } } /* so far there is only version 1 */ if (!X509_REQ_set_version(req, X509_REQ_VERSION_1)) goto err; if (fsubj != NULL) i = X509_REQ_set_subject_name(req, fsubj); else if (no_prompt) i = auto_info(req, dn_sk, attr_sk, attribs, chtype); else i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs, chtype); if (!i) goto err; if (!X509_REQ_set_pubkey(req, pkey)) goto err; ret = 1; err: return ret; } static int prompt_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect, STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect, int attribs, unsigned long chtype) { int i; char *p, *q; char buf[100]; int nid, mval; long n_min, n_max; char *type, *value; const char *def; CONF_VALUE *v; X509_NAME *subj = X509_REQ_get_subject_name(req); if (!batch) { BIO_printf(bio_err, "You are about to be asked to enter information that will be incorporated\n"); BIO_printf(bio_err, "into your certificate request.\n"); BIO_printf(bio_err, "What you are about to enter is what is called a Distinguished Name or a DN.\n"); BIO_printf(bio_err, "There are quite a few fields but you can leave some blank\n"); BIO_printf(bio_err, "For some fields there will be a default value,\n"); BIO_printf(bio_err, "If you enter '.', the field will be left blank.\n"); BIO_printf(bio_err, "-----\n"); } if (sk_CONF_VALUE_num(dn_sk)) { i = -1; start: for (;;) { i++; if (sk_CONF_VALUE_num(dn_sk) <= i) break; v = sk_CONF_VALUE_value(dn_sk, i); p = q = NULL; type = v->name; if (!check_end(type, "_min") || !check_end(type, "_max") || !check_end(type, "_default") || !check_end(type, "_value")) continue; /* * Skip past any leading X. X: X, etc to allow for multiple * instances */ for (p = v->name; *p; p++) if ((*p == ':') || (*p == ',') || (*p == '.')) { p++; if (*p) type = p; break; } if (*type == '+') { mval = -1; type++; } else { mval = 0; } /* If OBJ not recognised ignore it */ if ((nid = OBJ_txt2nid(type)) == NID_undef) goto start; if (!join(buf, sizeof(buf), v->name, "_default", "Name")) return 0; if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) { ERR_clear_error(); def = ""; } if (!join(buf, sizeof(buf), v->name, "_value", "Name")) return 0; if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) { ERR_clear_error(); value = NULL; } if (!join(buf, sizeof(buf), v->name, "_min", "Name")) return 0; if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) { ERR_clear_error(); n_min = -1; } if (!join(buf, sizeof(buf), v->name, "_max", "Name")) return 0; if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) { ERR_clear_error(); n_max = -1; } if (!add_DN_object(subj, v->value, def, value, nid, n_min, n_max, chtype, mval)) return 0; } if (X509_NAME_entry_count(subj) == 0) { BIO_printf(bio_err, "Error: No objects specified in config file\n"); return 0; } if (attribs) { if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0) && (!batch)) { BIO_printf(bio_err, "\nPlease enter the following 'extra' attributes\n"); BIO_printf(bio_err, "to be sent with your certificate request\n"); } i = -1; start2: for (;;) { i++; if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i)) break; v = sk_CONF_VALUE_value(attr_sk, i); type = v->name; if ((nid = OBJ_txt2nid(type)) == NID_undef) goto start2; if (!join(buf, sizeof(buf), type, "_default", "Name")) return 0; if ((def = NCONF_get_string(req_conf, attr_sect, buf)) == NULL) { ERR_clear_error(); def = ""; } if (!join(buf, sizeof(buf), type, "_value", "Name")) return 0; if ((value = NCONF_get_string(req_conf, attr_sect, buf)) == NULL) { ERR_clear_error(); value = NULL; } if (!join(buf, sizeof(buf), type, "_min", "Name")) return 0; if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) { ERR_clear_error(); n_min = -1; } if (!join(buf, sizeof(buf), type, "_max", "Name")) return 0; if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) { ERR_clear_error(); n_max = -1; } if (!add_attribute_object(req, v->value, def, value, nid, n_min, n_max, chtype)) return 0; } } } else { BIO_printf(bio_err, "No template, please set one up.\n"); return 0; } return 1; } static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk, STACK_OF(CONF_VALUE) *attr_sk, int attribs, unsigned long chtype) { int i, spec_char, plus_char; char *p, *q; char *type; CONF_VALUE *v; X509_NAME *subj; subj = X509_REQ_get_subject_name(req); for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) { int mval; v = sk_CONF_VALUE_value(dn_sk, i); p = q = NULL; type = v->name; /* * Skip past any leading X. X: X, etc to allow for multiple instances */ for (p = v->name; *p; p++) { #ifndef CHARSET_EBCDIC spec_char = (*p == ':' || *p == ',' || *p == '.'); #else spec_char = (*p == os_toascii[':'] || *p == os_toascii[','] || *p == os_toascii['.']); #endif if (spec_char) { p++; if (*p) type = p; break; } } #ifndef CHARSET_EBCDIC plus_char = (*type == '+'); #else plus_char = (*type == os_toascii['+']); #endif if (plus_char) { type++; mval = -1; } else { mval = 0; } if (!X509_NAME_add_entry_by_txt(subj, type, chtype, (unsigned char *)v->value, -1, -1, mval)) return 0; } if (!X509_NAME_entry_count(subj)) { BIO_printf(bio_err, "Error: No objects specified in config file\n"); return 0; } if (attribs) { for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) { v = sk_CONF_VALUE_value(attr_sk, i); if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype, (unsigned char *)v->value, -1)) return 0; } } return 1; } static int add_DN_object(X509_NAME *n, char *text, const char *def, char *value, int nid, int n_min, int n_max, unsigned long chtype, int mval) { int ret = 0; char buf[1024]; ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf), "DN value", "DN default"); if ((ret == 0) || (ret == 1)) return ret; ret = 1; if (!X509_NAME_add_entry_by_NID(n, nid, chtype, (unsigned char *)buf, -1, -1, mval)) ret = 0; return ret; } static int add_attribute_object(X509_REQ *req, char *text, const char *def, char *value, int nid, int n_min, int n_max, unsigned long chtype) { int ret = 0; char buf[1024]; ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf), "Attribute value", "Attribute default"); if ((ret == 0) || (ret == 1)) return ret; ret = 1; if (!X509_REQ_add1_attr_by_NID(req, nid, chtype, (unsigned char *)buf, -1)) { BIO_printf(bio_err, "Error adding attribute\n"); ret = 0; } return ret; } static int build_data(char *text, const char *def, char *value, int n_min, int n_max, char *buf, const int buf_size, const char *desc1, const char *desc2) { int i; start: if (!batch) BIO_printf(bio_err, "%s [%s]:", text, def); (void)BIO_flush(bio_err); if (value != NULL) { if (!join(buf, buf_size, value, "\n", desc1)) return 0; BIO_printf(bio_err, "%s\n", value); } else { buf[0] = '\0'; if (!batch) { if (!fgets(buf, buf_size, stdin)) return 0; } else { buf[0] = '\n'; buf[1] = '\0'; } } if (buf[0] == '\0') return 0; if (buf[0] == '\n') { if ((def == NULL) || (def[0] == '\0')) return 1; if (!join(buf, buf_size, def, "\n", desc2)) return 0; } else if ((buf[0] == '.') && (buf[1] == '\n')) { return 1; } i = strlen(buf); if (buf[i - 1] != '\n') { BIO_printf(bio_err, "Missing newline at end of input\n"); return 0; } buf[--i] = '\0'; #ifdef CHARSET_EBCDIC ebcdic2ascii(buf, buf, i); #endif if (!req_check_len(i, n_min, n_max)) { if (batch || value) return 0; goto start; } return 2; } static int req_check_len(int len, int n_min, int n_max) { if (n_min > 0 && len < n_min) { BIO_printf(bio_err, "String too short, must be at least %d bytes long\n", n_min); return 0; } if (n_max >= 0 && len > n_max) { BIO_printf(bio_err, "String too long, must be at most %d bytes long\n", n_max); return 0; } return 1; } /* Check if the end of a string matches 'end' */ static int check_end(const char *str, const char *end) { size_t elen, slen; const char *tmp; elen = strlen(end); slen = strlen(str); if (elen > slen) return 1; tmp = str + slen - elen; return strcmp(tmp, end); } /* * Merge the two strings together into the result buffer checking for * overflow and producing an error message if there is. */ static int join(char buf[], size_t buf_size, const char *name, const char *tail, const char *desc) { const size_t name_len = strlen(name), tail_len = strlen(tail); if (name_len + tail_len + 1 > buf_size) { BIO_printf(bio_err, "%s '%s' too long\n", desc, name); return 0; } memcpy(buf, name, name_len); memcpy(buf + name_len, tail, tail_len + 1); return 1; } static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr, char **pkeytype, long *pkeylen, ENGINE *keygen_engine) { EVP_PKEY_CTX *gctx = NULL; EVP_PKEY *param = NULL; long keylen = -1; BIO *pbio = NULL; const char *keytype = NULL; size_t keytypelen = 0; int expect_paramfile = 0; const char *paramfile = NULL; /* Treat the first part of gstr, and only that */ if (gstr == NULL) { /* * Special case: when no string given, default to RSA and the * key length given by |*pkeylen|. */ keytype = "RSA"; keylen = *pkeylen; } else if (gstr[0] >= '0' && gstr[0] <= '9') { /* Special case: only keylength given from string, so default to RSA */ keytype = "RSA"; /* The second part treatment will do the rest */ } else { const char *p = strchr(gstr, ':'); int len; if (p != NULL) len = p - gstr; else len = strlen(gstr); if (strncmp(gstr, "param", len) == 0) { expect_paramfile = 1; if (p == NULL) { BIO_printf(bio_err, "Parameter file requested but no path given: %s\n", gstr); return NULL; } } else { keytype = gstr; keytypelen = len; } if (p != NULL) gstr = gstr + len + 1; else gstr = NULL; } /* Treat the second part of gstr, if there is one */ if (gstr != NULL) { /* If the second part starts with a digit, we assume it's a size */ if (!expect_paramfile && gstr[0] >= '0' && gstr[0] <= '9') keylen = atol(gstr); else paramfile = gstr; } if (paramfile != NULL) { pbio = BIO_new_file(paramfile, "r"); if (pbio == NULL) { BIO_printf(bio_err, "Cannot open parameter file %s\n", paramfile); return NULL; } param = PEM_read_bio_Parameters(pbio, NULL); if (param == NULL) { X509 *x; (void)BIO_reset(pbio); x = PEM_read_bio_X509(pbio, NULL, NULL, NULL); if (x != NULL) { param = X509_get_pubkey(x); X509_free(x); } } BIO_free(pbio); if (param == NULL) { BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile); return NULL; } if (keytype == NULL) { keytype = EVP_PKEY_get0_type_name(param); if (keytype == NULL) { EVP_PKEY_free(param); BIO_puts(bio_err, "Unable to determine key type\n"); return NULL; } } } if (keytypelen > 0) *pkeytype = OPENSSL_strndup(keytype, keytypelen); else *pkeytype = OPENSSL_strdup(keytype); if (*pkeytype == NULL) { BIO_printf(bio_err, "Out of memory\n"); EVP_PKEY_free(param); return NULL; } if (keylen >= 0) *pkeylen = keylen; if (param != NULL) { if (!EVP_PKEY_is_a(param, *pkeytype)) { BIO_printf(bio_err, "Key type does not match parameters\n"); EVP_PKEY_free(param); return NULL; } if (keygen_engine != NULL) gctx = EVP_PKEY_CTX_new(param, keygen_engine); else gctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), param, app_get0_propq()); *pkeylen = EVP_PKEY_get_bits(param); EVP_PKEY_free(param); } else { if (keygen_engine != NULL) { int pkey_id = get_legacy_pkey_id(app_get0_libctx(), *pkeytype, keygen_engine); if (pkey_id != NID_undef) gctx = EVP_PKEY_CTX_new_id(pkey_id, keygen_engine); } else { gctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(), *pkeytype, app_get0_propq()); } } if (gctx == NULL) { BIO_puts(bio_err, "Error allocating keygen context\n"); return NULL; } if (EVP_PKEY_keygen_init(gctx) <= 0) { BIO_puts(bio_err, "Error initializing keygen context\n"); EVP_PKEY_CTX_free(gctx); return NULL; } if (keylen == -1 && (EVP_PKEY_CTX_is_a(gctx, "RSA") || EVP_PKEY_CTX_is_a(gctx, "RSA-PSS"))) keylen = *pkeylen; if (keylen != -1) { OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END }; size_t bits = keylen; params[0] = OSSL_PARAM_construct_size_t(OSSL_PKEY_PARAM_BITS, &bits); if (EVP_PKEY_CTX_set_params(gctx, params) <= 0) { BIO_puts(bio_err, "Error setting keysize\n"); EVP_PKEY_CTX_free(gctx); return NULL; } } return gctx; } static int genpkey_cb(EVP_PKEY_CTX *ctx) { char c = '*'; BIO *b = EVP_PKEY_CTX_get_app_data(ctx); int p; p = EVP_PKEY_CTX_get_keygen_info(ctx, 0); if (p == 0) c = '.'; if (p == 1) c = '+'; if (p == 2) c = '*'; if (p == 3) c = '\n'; BIO_write(b, &c, 1); (void)BIO_flush(b); return 1; } diff --git a/apps/s_server.c b/apps/s_server.c index a203d6a091ca..c8ccdfd03ca1 100644 --- a/apps/s_server.c +++ b/apps/s_server.c @@ -1,3791 +1,3791 @@ /* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved * Copyright 2005 Nokia. All rights reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include #include #include #include #if defined(_WIN32) /* Included before async.h to avoid some warnings */ # include #endif #include #include #include #include #ifndef OPENSSL_NO_SOCK /* * 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 "apps.h" #include "progs.h" #include #include #include #include #include #include #ifndef OPENSSL_NO_DH # include #endif #include #include "s_apps.h" #include "timeouts.h" #ifdef CHARSET_EBCDIC #include #endif #include "internal/sockets.h" static int not_resumable_sess_cb(SSL *s, int is_forward_secure); static int sv_body(int s, int stype, int prot, unsigned char *context); static int www_body(int s, int stype, int prot, unsigned char *context); static int rev_body(int s, int stype, int prot, unsigned char *context); static void close_accept_socket(void); static int init_ssl_connection(SSL *s); static void print_stats(BIO *bp, SSL_CTX *ctx); static int generate_session_id(SSL *ssl, unsigned char *id, unsigned int *id_len); static void init_session_cache_ctx(SSL_CTX *sctx); static void free_sessions(void); static void print_connection_info(SSL *con); static const int bufsize = 16 * 1024; static int accept_socket = -1; #define TEST_CERT "server.pem" #define TEST_CERT2 "server2.pem" static int s_nbio = 0; static int s_nbio_test = 0; static int s_crlf = 0; static SSL_CTX *ctx = NULL; static SSL_CTX *ctx2 = NULL; static int www = 0; static BIO *bio_s_out = NULL; static BIO *bio_s_msg = NULL; static int s_debug = 0; static int s_tlsextdebug = 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 async = 0; static int use_sendfile = 0; static const char *session_id_prefix = NULL; #ifndef OPENSSL_NO_DTLS static int enable_timeouts = 0; static long socket_mtu; #endif /* * We define this but make it always be 0 in no-dtls builds to simplify the * code. */ static int dtlslisten = 0; static int stateless = 0; static int early_data = 0; static SSL_SESSION *psksess = NULL; static char *psk_identity = "Client_identity"; char *psk_key = NULL; /* by default PSK is not used */ static char http_server_binmode = 0; /* for now: 0/1 = default/binary */ #ifndef OPENSSL_NO_PSK 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 (!SSL_is_dtls(ssl) && SSL_version(ssl) >= TLS1_3_VERSION) { /* * This callback is designed for use in (D)TLSv1.2 (or below). It is * possible to use a single callback for all protocol versions - but it * is preferred to use a dedicated callback for TLSv1.3. For TLSv1.3 we * have psk_find_session_cb. */ return 0; } if (identity == NULL) { BIO_printf(bio_err, "Error: client did not send PSK identity\n"); goto out_err; } 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 warning: client identity not what we expected" " (got '%s' expected '%s')\n", identity, psk_identity); } else { if (s_debug) BIO_printf(bio_s_out, "PSK client identity found\n"); } /* convert the PSK key to binary */ key = OPENSSL_hexstr2buf(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"); (void)BIO_flush(bio_err); (void)BIO_flush(bio_s_out); return 0; } #endif static int psk_find_session_cb(SSL *ssl, const unsigned char *identity, size_t identity_len, SSL_SESSION **sess) { SSL_SESSION *tmpsess = NULL; unsigned char *key; long key_len; const SSL_CIPHER *cipher = NULL; if (strlen(psk_identity) != identity_len || memcmp(psk_identity, identity, identity_len) != 0) { *sess = NULL; return 1; } if (psksess != NULL) { SSL_SESSION_up_ref(psksess); *sess = psksess; return 1; } key = OPENSSL_hexstr2buf(psk_key, &key_len); if (key == NULL) { BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n", psk_key); return 0; } /* We default to SHA256 */ cipher = SSL_CIPHER_find(ssl, tls13_aes128gcmsha256_id); if (cipher == NULL) { BIO_printf(bio_err, "Error finding suitable ciphersuite\n"); OPENSSL_free(key); return 0; } tmpsess = SSL_SESSION_new(); if (tmpsess == NULL || !SSL_SESSION_set1_master_key(tmpsess, key, key_len) || !SSL_SESSION_set_cipher(tmpsess, cipher) || !SSL_SESSION_set_protocol_version(tmpsess, SSL_version(ssl))) { OPENSSL_free(key); SSL_SESSION_free(tmpsess); return 0; } OPENSSL_free(key); *sess = tmpsess; return 1; } #ifndef OPENSSL_NO_SRP static srpsrvparm srp_callback_parm; #endif 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 = NULL; /* This struct is "unwarranted chumminess with the compiler." */ typedef struct { size_t alloced; char buff[1]; } EBCDIC_OUTBUFF; static const BIO_METHOD *BIO_f_ebcdic_filter() { if (methods_ebcdic == NULL) { methods_ebcdic = BIO_meth_new(BIO_TYPE_EBCDIC_FILTER, "EBCDIC/ASCII filter"); if (methods_ebcdic == NULL || !BIO_meth_set_write(methods_ebcdic, ebcdic_write) || !BIO_meth_set_read(methods_ebcdic, ebcdic_read) || !BIO_meth_set_puts(methods_ebcdic, ebcdic_puts) || !BIO_meth_set_gets(methods_ebcdic, ebcdic_gets) || !BIO_meth_set_ctrl(methods_ebcdic, ebcdic_ctrl) || !BIO_meth_set_create(methods_ebcdic, ebcdic_new) || !BIO_meth_set_destroy(methods_ebcdic, ebcdic_free)) return NULL; } return methods_ebcdic; } static int ebcdic_new(BIO *bi) { EBCDIC_OUTBUFF *wbuf; wbuf = app_malloc(sizeof(*wbuf) + 1024, "ebcdic wbuf"); wbuf->alloced = 1024; wbuf->buff[0] = '\0'; BIO_set_data(bi, wbuf); BIO_set_init(bi, 1); return 1; } static int ebcdic_free(BIO *a) { EBCDIC_OUTBUFF *wbuf; if (a == NULL) return 0; wbuf = BIO_get_data(a); OPENSSL_free(wbuf); BIO_set_data(a, NULL); BIO_set_init(a, 0); return 1; } static int ebcdic_read(BIO *b, char *out, int outl) { int ret = 0; BIO *next = BIO_next(b); if (out == NULL || outl == 0) return 0; if (next == NULL) return 0; ret = BIO_read(next, 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; BIO *next = BIO_next(b); int ret = 0; int num; if ((in == NULL) || (inl <= 0)) return 0; if (next == NULL) return 0; wbuf = (EBCDIC_OUTBUFF *) BIO_get_data(b); if (inl > (num = wbuf->alloced)) { num = num + num; /* double the size */ if (num < inl) num = inl; OPENSSL_free(wbuf); wbuf = app_malloc(sizeof(*wbuf) + num, "grow ebcdic wbuf"); wbuf->alloced = num; wbuf->buff[0] = '\0'; BIO_set_data(b, wbuf); } ebcdic2ascii(wbuf->buff, in, inl); ret = BIO_write(next, wbuf->buff, inl); return ret; } static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr) { long ret; BIO *next = BIO_next(b); if (next == NULL) return 0; switch (cmd) { case BIO_CTRL_DUP: ret = 0L; break; default: ret = BIO_ctrl(next, cmd, num, ptr); break; } return ret; } static int ebcdic_gets(BIO *bp, char *buf, int size) { int i, ret = 0; BIO *next = BIO_next(bp); if (next == 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 (BIO_next(bp) == NULL) return 0; return ebcdic_write(bp, str, strlen(str)); } #endif /* This is a context that we pass to callbacks */ typedef struct tlsextctx_st { char *servername; BIO *biodebug; int extension_error; } tlsextctx; static int 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 != NULL && p->biodebug != NULL) { const char *cp = servername; unsigned char uc; BIO_printf(p->biodebug, "Hostname in TLS extension: \""); while ((uc = *cp++) != 0) BIO_printf(p->biodebug, (((uc) & ~127) == 0) && isprint(uc) ? "%c" : "\\x%02x", uc); BIO_printf(p->biodebug, "\"\n"); } if (p->servername == NULL) return SSL_TLSEXT_ERR_NOACK; if (servername != NULL) { if (OPENSSL_strcasecmp(servername, p->servername)) return p->extension_error; if (ctx2 != NULL) { 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 { int timeout; /* File to load OCSP Response from (or NULL if no file) */ char *respin; /* Default responder to use */ char *host, *path, *port; char *proxy, *no_proxy; int use_ssl; int verbose; } tlsextstatusctx; static tlsextstatusctx tlscstatp = { -1 }; #ifndef OPENSSL_NO_OCSP /* * Helper function to get an OCSP_RESPONSE from a responder. 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 get_ocsp_resp_from_responder(SSL *s, tlsextstatusctx *srctx, OCSP_RESPONSE **resp) { char *host = NULL, *port = NULL, *path = NULL; char *proxy = NULL, *no_proxy = NULL; int use_ssl; STACK_OF(OPENSSL_STRING) *aia = NULL; X509 *x = NULL; X509_STORE_CTX *inctx = NULL; X509_OBJECT *obj; OCSP_REQUEST *req = NULL; OCSP_CERTID *id = NULL; STACK_OF(X509_EXTENSION) *exts; int ret = SSL_TLSEXT_ERR_NOACK; int i; /* Build up OCSP query from server certificate */ x = SSL_get_certificate(s); aia = X509_get1_ocsp(x); if (aia != NULL) { if (!OSSL_HTTP_parse_url(sk_OPENSSL_STRING_value(aia, 0), &use_ssl, NULL, &host, &port, NULL, &path, NULL, NULL)) { BIO_puts(bio_err, "cert_status: can't parse AIA URL\n"); goto err; } if (srctx->verbose) BIO_printf(bio_err, "cert_status: AIA URL: %s\n", sk_OPENSSL_STRING_value(aia, 0)); } else { if (srctx->host == NULL) { BIO_puts(bio_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; } proxy = srctx->proxy; no_proxy = srctx->no_proxy; inctx = X509_STORE_CTX_new(); if (inctx == NULL) goto err; if (!X509_STORE_CTX_init(inctx, SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)), NULL, NULL)) goto err; obj = X509_STORE_CTX_get_obj_by_subject(inctx, X509_LU_X509, X509_get_issuer_name(x)); if (obj == NULL) { BIO_puts(bio_err, "cert_status: Can't retrieve issuer certificate.\n"); goto done; } id = OCSP_cert_to_id(NULL, x, X509_OBJECT_get0_X509(obj)); X509_OBJECT_free(obj); if (id == NULL) goto err; req = OCSP_REQUEST_new(); if (req == NULL) 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(req, host, port, path, proxy, no_proxy, use_ssl, NULL /* headers */, srctx->timeout); if (*resp == NULL) { BIO_puts(bio_err, "cert_status: error querying responder\n"); goto done; } ret = SSL_TLSEXT_ERR_OK; goto done; err: ret = SSL_TLSEXT_ERR_ALERT_FATAL; done: /* * If we parsed aia we need to free; otherwise they were copied and we * don't */ if (aia != NULL) { OPENSSL_free(host); OPENSSL_free(path); OPENSSL_free(port); X509_email_free(aia); } OCSP_CERTID_free(id); OCSP_REQUEST_free(req); X509_STORE_CTX_free(inctx); return ret; } /* * Certificate Status callback. This is called when a client includes a * certificate status request extension. The response is either obtained from a * file, or from an OCSP responder. */ static int cert_status_cb(SSL *s, void *arg) { tlsextstatusctx *srctx = arg; OCSP_RESPONSE *resp = NULL; unsigned char *rspder = NULL; int rspderlen; int ret = SSL_TLSEXT_ERR_ALERT_FATAL; if (srctx->verbose) BIO_puts(bio_err, "cert_status: callback called\n"); if (srctx->respin != NULL) { BIO *derbio = bio_open_default(srctx->respin, 'r', FORMAT_ASN1); if (derbio == NULL) { BIO_puts(bio_err, "cert_status: Cannot open OCSP response file\n"); goto err; } resp = d2i_OCSP_RESPONSE_bio(derbio, NULL); BIO_free(derbio); if (resp == NULL) { BIO_puts(bio_err, "cert_status: Error reading OCSP response\n"); goto err; } } else { ret = get_ocsp_resp_from_responder(s, srctx, &resp); if (ret != SSL_TLSEXT_ERR_OK) goto err; } 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(bio_err, "cert_status: ocsp response sent:\n"); OCSP_RESPONSE_print(bio_err, resp, 2); } ret = SSL_TLSEXT_ERR_OK; err: if (ret != SSL_TLSEXT_ERR_OK) ERR_print_errors(bio_err); OCSP_RESPONSE_free(resp); return ret; } #endif #ifndef OPENSSL_NO_NEXTPROTONEG /* This is the context that we pass to next_proto_cb */ typedef struct tlsextnextprotoctx_st { unsigned char *data; size_t 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; size_t 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 int 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_ALERT_FATAL; } 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; } static int not_resumable_sess_cb(SSL *s, int is_forward_secure) { /* disable resumption for sessions with forward secure ciphers */ return is_forward_secure; } typedef enum OPTION_choice { OPT_COMMON, OPT_ENGINE, OPT_4, OPT_6, OPT_ACCEPT, OPT_PORT, OPT_UNIX, OPT_UNLINK, OPT_NACCEPT, OPT_VERIFY, OPT_NAMEOPT, OPT_UPPER_V_VERIFY, OPT_CONTEXT, OPT_CERT, OPT_CRL, OPT_CRL_DOWNLOAD, OPT_SERVERINFO, OPT_CERTFORM, OPT_KEY, OPT_KEYFORM, OPT_PASS, OPT_CERT_CHAIN, OPT_DHPARAM, OPT_DCERTFORM, OPT_DCERT, OPT_DKEYFORM, OPT_DPASS, OPT_DKEY, OPT_DCERT_CHAIN, OPT_NOCERT, OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_NO_CACHE, OPT_EXT_CACHE, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET, OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE, OPT_VERIFYCAFILE, OPT_CASTORE, OPT_NOCASTORE, OPT_CHAINCASTORE, OPT_VERIFYCASTORE, OPT_NBIO, OPT_NBIO_TEST, OPT_IGN_EOF, OPT_NO_IGN_EOF, OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_STATUS_VERBOSE, OPT_STATUS_TIMEOUT, OPT_PROXY, OPT_NO_PROXY, OPT_STATUS_URL, OPT_STATUS_FILE, OPT_MSG, OPT_MSGFILE, OPT_TRACE, OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_STATE, OPT_CRLF, OPT_QUIET, OPT_BRIEF, OPT_NO_DHE, OPT_NO_RESUME_EPHEMERAL, OPT_PSK_IDENTITY, OPT_PSK_HINT, OPT_PSK, OPT_PSK_SESS, OPT_SRPVFILE, OPT_SRPUSERSEED, OPT_REV, OPT_WWW, OPT_UPPER_WWW, OPT_HTTP, OPT_ASYNC, OPT_SSL_CONFIG, OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF, OPT_SSL3, OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1, OPT_DTLS1_2, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_LISTEN, OPT_STATELESS, OPT_ID_PREFIX, OPT_SERVERNAME, OPT_SERVERNAME_FATAL, OPT_CERT2, OPT_KEY2, OPT_NEXTPROTONEG, OPT_ALPN, OPT_SENDFILE, OPT_SRTP_PROFILES, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN, OPT_KEYLOG_FILE, OPT_MAX_EARLY, OPT_RECV_MAX_EARLY, OPT_EARLY_DATA, OPT_S_NUM_TICKETS, OPT_ANTI_REPLAY, OPT_NO_ANTI_REPLAY, OPT_SCTP_LABEL_BUG, OPT_HTTP_SERVER_BINMODE, OPT_NOCANAMES, OPT_IGNORE_UNEXPECTED_EOF, OPT_R_ENUM, OPT_S_ENUM, OPT_V_ENUM, OPT_X_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS s_server_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"ssl_config", OPT_SSL_CONFIG, 's', "Configure SSL_CTX using the given configuration value"}, #ifndef OPENSSL_NO_SSL_TRACE {"trace", OPT_TRACE, '-', "trace protocol messages"}, #endif #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Network"), {"port", OPT_PORT, 'p', "TCP/IP port to listen on for connections (default is " PORT ")"}, {"accept", OPT_ACCEPT, 's', "TCP/IP optional host and port to listen on for connections (default is *:" PORT ")"}, #ifdef AF_UNIX {"unix", OPT_UNIX, 's', "Unix domain socket to accept on"}, {"unlink", OPT_UNLINK, '-', "For -unix, unlink existing socket first"}, #endif {"4", OPT_4, '-', "Use IPv4 only"}, {"6", OPT_6, '-', "Use IPv6 only"}, OPT_SECTION("Identity"), {"context", OPT_CONTEXT, 's', "Set session ID context"}, {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"}, {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"}, {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"}, {"no-CAfile", OPT_NOCAFILE, '-', "Do not load the default certificates file"}, {"no-CApath", OPT_NOCAPATH, '-', "Do not load certificates from the default certificates directory"}, {"no-CAstore", OPT_NOCASTORE, '-', "Do not load certificates from the default certificates store URI"}, {"nocert", OPT_NOCERT, '-', "Don't use any certificates (Anon-DH)"}, {"verify", OPT_VERIFY, 'n', "Turn on peer certificate verification"}, {"Verify", OPT_UPPER_V_VERIFY, 'n', "Turn on peer certificate verification, must have a cert"}, {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"}, {"cert", OPT_CERT, '<', "Server certificate file to use; default " TEST_CERT}, {"cert2", OPT_CERT2, '<', "Certificate file to use for servername; default " TEST_CERT2}, {"certform", OPT_CERTFORM, 'F', "Server certificate file format (PEM/DER/P12); has no effect"}, {"cert_chain", OPT_CERT_CHAIN, '<', "Server certificate chain file in PEM format"}, {"build_chain", OPT_BUILD_CHAIN, '-', "Build server certificate chain"}, {"serverinfo", OPT_SERVERINFO, 's', "PEM serverinfo file for certificate"}, {"key", OPT_KEY, 's', "Private key file to use; default is -cert file or else" TEST_CERT}, {"key2", OPT_KEY2, '<', "-Private Key file to use for servername if not in -cert2"}, {"keyform", OPT_KEYFORM, 'f', "Key format (ENGINE, other values ignored)"}, {"pass", OPT_PASS, 's', "Private key and cert file pass phrase source"}, {"dcert", OPT_DCERT, '<', "Second server certificate file to use (usually for DSA)"}, {"dcertform", OPT_DCERTFORM, 'F', "Second server certificate file format (PEM/DER/P12); has no effect"}, {"dcert_chain", OPT_DCERT_CHAIN, '<', "second server certificate chain file in PEM format"}, {"dkey", OPT_DKEY, '<', "Second private key file to use (usually for DSA)"}, - {"dkeyform", OPT_DKEYFORM, 'F', + {"dkeyform", OPT_DKEYFORM, 'f', "Second key file format (ENGINE, other values ignored)"}, {"dpass", OPT_DPASS, 's', "Second private key and cert file pass phrase source"}, {"dhparam", OPT_DHPARAM, '<', "DH parameters file to use"}, {"servername", OPT_SERVERNAME, 's', "Servername for HostName TLS extension"}, {"servername_fatal", OPT_SERVERNAME_FATAL, '-', "On servername mismatch send fatal alert (default warning alert)"}, {"nbio_test", OPT_NBIO_TEST, '-', "Test with the non-blocking test bio"}, {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"}, {"quiet", OPT_QUIET, '-', "No server output"}, {"no_resume_ephemeral", OPT_NO_RESUME_EPHEMERAL, '-', "Disable caching and tickets if ephemeral (EC)DH is used"}, {"www", OPT_WWW, '-', "Respond to a 'GET /' with a status page"}, {"WWW", OPT_UPPER_WWW, '-', "Respond to a 'GET with the file ./path"}, {"ignore_unexpected_eof", OPT_IGNORE_UNEXPECTED_EOF, '-', "Do not treat lack of close_notify from a peer as an error"}, {"tlsextdebug", OPT_TLSEXTDEBUG, '-', "Hex dump of all TLS extensions received"}, {"HTTP", OPT_HTTP, '-', "Like -WWW but ./path includes HTTP headers"}, {"id_prefix", OPT_ID_PREFIX, 's', "Generate SSL/TLS session IDs prefixed by arg"}, {"keymatexport", OPT_KEYMATEXPORT, 's', "Export keying material using label"}, {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p', "Export len bytes of keying material; default 20"}, {"CRL", OPT_CRL, '<', "CRL file to use"}, {"CRLform", OPT_CRLFORM, 'F', "CRL file format (PEM or DER); default PEM"}, {"crl_download", OPT_CRL_DOWNLOAD, '-', "Download CRLs from distribution points in certificate CDP entries"}, {"chainCAfile", OPT_CHAINCAFILE, '<', "CA file for certificate chain (PEM format)"}, {"chainCApath", OPT_CHAINCAPATH, '/', "use dir as certificate store path to build CA certificate chain"}, {"chainCAstore", OPT_CHAINCASTORE, ':', "use URI as certificate store to build CA certificate chain"}, {"verifyCAfile", OPT_VERIFYCAFILE, '<', "CA file for certificate verification (PEM format)"}, {"verifyCApath", OPT_VERIFYCAPATH, '/', "use dir as certificate store path to verify CA certificate"}, {"verifyCAstore", OPT_VERIFYCASTORE, ':', "use URI as certificate store to verify CA certificate"}, {"no_cache", OPT_NO_CACHE, '-', "Disable session cache"}, {"ext_cache", OPT_EXT_CACHE, '-', "Disable internal cache, set up and use external cache"}, {"verify_return_error", OPT_VERIFY_RET_ERROR, '-', "Close connection on verification error"}, {"verify_quiet", OPT_VERIFY_QUIET, '-', "No verify output except verify errors"}, {"ign_eof", OPT_IGN_EOF, '-', "Ignore input EOF (default when -quiet)"}, {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Do not ignore input EOF"}, #ifndef OPENSSL_NO_OCSP OPT_SECTION("OCSP"), {"status", OPT_STATUS, '-', "Request certificate status from server"}, {"status_verbose", OPT_STATUS_VERBOSE, '-', "Print more output in certificate status callback"}, {"status_timeout", OPT_STATUS_TIMEOUT, 'n', "Status request responder timeout"}, {"status_url", OPT_STATUS_URL, 's', "Status request fallback URL"}, {"proxy", OPT_PROXY, 's', "[http[s]://]host[:port][/path] of HTTP(S) proxy to use; path is ignored"}, {"no_proxy", OPT_NO_PROXY, 's', "List of addresses of servers not to use HTTP(S) proxy for"}, {OPT_MORE_STR, 0, 0, "Default from environment variable 'no_proxy', else 'NO_PROXY', else none"}, {"status_file", OPT_STATUS_FILE, '<', "File containing DER encoded OCSP Response"}, #endif OPT_SECTION("Debug"), {"security_debug", OPT_SECURITY_DEBUG, '-', "Print output from SSL/TLS security framework"}, {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-', "Print more output from SSL/TLS security framework"}, {"brief", OPT_BRIEF, '-', "Restrict output to brief summary of connection parameters"}, {"rev", OPT_REV, '-', "act as an echo server that sends back received text reversed"}, {"debug", OPT_DEBUG, '-', "Print more output"}, {"msg", OPT_MSG, '-', "Show protocol messages"}, {"msgfile", OPT_MSGFILE, '>', "File to send output of -msg or -trace, instead of stdout"}, {"state", OPT_STATE, '-', "Print the SSL states"}, {"async", OPT_ASYNC, '-', "Operate in asynchronous mode"}, {"max_pipelines", OPT_MAX_PIPELINES, 'p', "Maximum number of encrypt/decrypt pipelines to be used"}, {"naccept", OPT_NACCEPT, 'p', "Terminate after #num connections"}, {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"}, OPT_SECTION("Network"), {"nbio", OPT_NBIO, '-', "Use non-blocking IO"}, {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"}, {"mtu", OPT_MTU, 'p', "Set link-layer MTU"}, {"read_buf", OPT_READ_BUF, 'p', "Default read buffer size to be used for connections"}, {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p', "Size used to split data for encrypt pipelines"}, {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "}, OPT_SECTION("Server identity"), {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity to expect"}, #ifndef OPENSSL_NO_PSK {"psk_hint", OPT_PSK_HINT, 's', "PSK identity hint to use"}, #endif {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"}, {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"}, #ifndef OPENSSL_NO_SRP {"srpvfile", OPT_SRPVFILE, '<', "(deprecated) The verifier file for SRP"}, {"srpuserseed", OPT_SRPUSERSEED, 's', "(deprecated) A seed string for a default user salt"}, #endif OPT_SECTION("Protocol and version"), {"max_early_data", OPT_MAX_EARLY, 'n', "The maximum number of bytes of early data as advertised in tickets"}, {"recv_max_early_data", OPT_RECV_MAX_EARLY, 'n', "The maximum number of bytes of early data (hard limit)"}, {"early_data", OPT_EARLY_DATA, '-', "Attempt to read early data"}, {"num_tickets", OPT_S_NUM_TICKETS, 'n', "The number of TLSv1.3 session tickets that a server will automatically issue" }, {"anti_replay", OPT_ANTI_REPLAY, '-', "Switch on anti-replay protection (default)"}, {"no_anti_replay", OPT_NO_ANTI_REPLAY, '-', "Switch off anti-replay protection"}, {"http_server_binmode", OPT_HTTP_SERVER_BINMODE, '-', "opening files in binary mode when acting as http server (-WWW and -HTTP)"}, {"no_ca_names", OPT_NOCANAMES, '-', "Disable TLS Extension CA Names"}, {"stateless", OPT_STATELESS, '-', "Require TLSv1.3 cookies"}, #ifndef OPENSSL_NO_SSL3 {"ssl3", OPT_SSL3, '-', "Just talk SSLv3"}, #endif #ifndef OPENSSL_NO_TLS1 {"tls1", OPT_TLS1, '-', "Just talk TLSv1"}, #endif #ifndef OPENSSL_NO_TLS1_1 {"tls1_1", OPT_TLS1_1, '-', "Just talk TLSv1.1"}, #endif #ifndef OPENSSL_NO_TLS1_2 {"tls1_2", OPT_TLS1_2, '-', "just talk TLSv1.2"}, #endif #ifndef OPENSSL_NO_TLS1_3 {"tls1_3", OPT_TLS1_3, '-', "just talk TLSv1.3"}, #endif #ifndef OPENSSL_NO_DTLS {"dtls", OPT_DTLS, '-', "Use any DTLS version"}, {"listen", OPT_LISTEN, '-', "Listen for a DTLS ClientHello with a cookie and then connect"}, #endif #ifndef OPENSSL_NO_DTLS1 {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"}, #endif #ifndef OPENSSL_NO_DTLS1_2 {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"}, #endif #ifndef OPENSSL_NO_SCTP {"sctp", OPT_SCTP, '-', "Use SCTP"}, {"sctp_label_bug", OPT_SCTP_LABEL_BUG, '-', "Enable SCTP label length bug"}, #endif #ifndef OPENSSL_NO_SRTP {"use_srtp", OPT_SRTP_PROFILES, 's', "Offer SRTP key management with a colon-separated profile list"}, #endif {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"}, #ifndef OPENSSL_NO_NEXTPROTONEG {"nextprotoneg", OPT_NEXTPROTONEG, 's', "Set the advertised protocols for the NPN extension (comma-separated list)"}, #endif {"alpn", OPT_ALPN, 's', "Set the advertised protocols for the ALPN extension (comma-separated list)"}, #ifndef OPENSSL_NO_KTLS {"sendfile", OPT_SENDFILE, '-', "Use sendfile to response file with -WWW"}, #endif OPT_R_OPTIONS, OPT_S_OPTIONS, OPT_V_OPTIONS, OPT_X_OPTIONS, OPT_PROV_OPTIONS, {NULL} }; #define IS_PROT_FLAG(o) \ (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \ || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2) int s_server_main(int argc, char *argv[]) { ENGINE *engine = NULL; EVP_PKEY *s_key = NULL, *s_dkey = NULL; SSL_CONF_CTX *cctx = NULL; const SSL_METHOD *meth = TLS_server_method(); SSL_EXCERT *exc = NULL; STACK_OF(OPENSSL_STRING) *ssl_args = NULL; STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL; STACK_OF(X509_CRL) *crls = NULL; X509 *s_cert = NULL, *s_dcert = NULL; X509_VERIFY_PARAM *vpm = NULL; const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL; const char *chCApath = NULL, *chCAfile = NULL, *chCAstore = NULL; char *dpassarg = NULL, *dpass = NULL; char *passarg = NULL, *pass = NULL; char *vfyCApath = NULL, *vfyCAfile = NULL, *vfyCAstore = NULL; char *crl_file = NULL, *prog; #ifdef AF_UNIX int unlink_unix_path = 0; #endif do_server_cb server_cb; int vpmtouched = 0, build_chain = 0, no_cache = 0, ext_cache = 0; char *dhfile = NULL; int no_dhe = 0; int nocert = 0, ret = 1; int noCApath = 0, noCAfile = 0, noCAstore = 0; int s_cert_format = FORMAT_UNDEF, s_key_format = FORMAT_UNDEF; int s_dcert_format = FORMAT_UNDEF, s_dkey_format = FORMAT_UNDEF; int rev = 0, naccept = -1, sdebug = 0; int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0; int state = 0, crl_format = FORMAT_UNDEF, crl_download = 0; char *host = NULL; char *port = NULL; unsigned char *context = NULL; OPTION_CHOICE o; EVP_PKEY *s_key2 = NULL; X509 *s_cert2 = NULL; tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING }; const char *ssl_config = NULL; int read_buf_len = 0; #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 }; #ifndef OPENSSL_NO_PSK /* by default do not send a PSK identity hint */ char *psk_identity_hint = NULL; #endif char *p; #ifndef OPENSSL_NO_SRP char *srpuserseed = NULL; char *srp_verifier_file = NULL; #endif #ifndef OPENSSL_NO_SRTP char *srtp_profiles = NULL; #endif int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0; int s_server_verify = SSL_VERIFY_NONE; int s_server_session_id_context = 1; /* anything will do */ const char *s_cert_file = TEST_CERT, *s_key_file = NULL, *s_chain_file = NULL; const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL; char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL; #ifndef OPENSSL_NO_OCSP int s_tlsextstatus = 0; #endif int no_resume_ephemeral = 0; unsigned int max_send_fragment = 0; unsigned int split_send_fragment = 0, max_pipelines = 0; const char *s_serverinfo_file = NULL; const char *keylog_file = NULL; int max_early_data = -1, recv_max_early_data = -1; char *psksessf = NULL; int no_ca_names = 0; #ifndef OPENSSL_NO_SCTP int sctp_label_bug = 0; #endif int ignore_unexpected_eof = 0; /* Init of few remaining global variables */ local_argc = argc; local_argv = argv; ctx = ctx2 = NULL; s_nbio = s_nbio_test = 0; www = 0; bio_s_out = NULL; s_debug = 0; s_msg = 0; s_quiet = 0; s_brief = 0; async = 0; use_sendfile = 0; port = OPENSSL_strdup(PORT); cctx = SSL_CONF_CTX_new(); vpm = X509_VERIFY_PARAM_new(); if (port == NULL || cctx == NULL || vpm == NULL) goto end; SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CMDLINE); prog = opt_init(argc, argv, s_server_options); while ((o = opt_next()) != OPT_EOF) { if (IS_PROT_FLAG(o) && ++prot_opt > 1) { BIO_printf(bio_err, "Cannot supply multiple protocol flags\n"); goto end; } if (IS_NO_PROT_FLAG(o)) no_prot_opt++; if (prot_opt == 1 && no_prot_opt) { BIO_printf(bio_err, "Cannot supply both a protocol flag and '-no_'\n"); goto end; } switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(s_server_options); ret = 0; goto end; case OPT_4: #ifdef AF_UNIX if (socket_family == AF_UNIX) { OPENSSL_free(host); host = NULL; OPENSSL_free(port); port = NULL; } #endif socket_family = AF_INET; break; case OPT_6: if (1) { #ifdef AF_INET6 #ifdef AF_UNIX if (socket_family == AF_UNIX) { OPENSSL_free(host); host = NULL; OPENSSL_free(port); port = NULL; } #endif socket_family = AF_INET6; } else { #endif BIO_printf(bio_err, "%s: IPv6 domain sockets unsupported\n", prog); goto end; } break; case OPT_PORT: #ifdef AF_UNIX if (socket_family == AF_UNIX) { socket_family = AF_UNSPEC; } #endif OPENSSL_free(port); port = NULL; OPENSSL_free(host); host = NULL; if (BIO_parse_hostserv(opt_arg(), NULL, &port, BIO_PARSE_PRIO_SERV) < 1) { BIO_printf(bio_err, "%s: -port argument malformed or ambiguous\n", port); goto end; } break; case OPT_ACCEPT: #ifdef AF_UNIX if (socket_family == AF_UNIX) { socket_family = AF_UNSPEC; } #endif OPENSSL_free(port); port = NULL; OPENSSL_free(host); host = NULL; if (BIO_parse_hostserv(opt_arg(), &host, &port, BIO_PARSE_PRIO_SERV) < 1) { BIO_printf(bio_err, "%s: -accept argument malformed or ambiguous\n", port); goto end; } break; #ifdef AF_UNIX case OPT_UNIX: socket_family = AF_UNIX; OPENSSL_free(host); host = OPENSSL_strdup(opt_arg()); if (host == NULL) goto end; OPENSSL_free(port); port = NULL; break; case OPT_UNLINK: unlink_unix_path = 1; break; #endif case OPT_NACCEPT: naccept = atol(opt_arg()); break; case OPT_VERIFY: s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE; verify_args.depth = atoi(opt_arg()); if (!s_quiet) BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth); break; case OPT_UPPER_V_VERIFY: s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE; verify_args.depth = atoi(opt_arg()); if (!s_quiet) BIO_printf(bio_err, "verify depth is %d, must return a certificate\n", verify_args.depth); break; case OPT_CONTEXT: context = (unsigned char *)opt_arg(); break; case OPT_CERT: s_cert_file = opt_arg(); break; case OPT_NAMEOPT: if (!set_nameopt(opt_arg())) goto end; break; case OPT_CRL: crl_file = opt_arg(); break; case OPT_CRL_DOWNLOAD: crl_download = 1; break; case OPT_SERVERINFO: s_serverinfo_file = opt_arg(); break; case OPT_CERTFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_cert_format)) goto opthelp; break; case OPT_KEY: s_key_file = opt_arg(); break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_key_format)) goto opthelp; break; case OPT_PASS: passarg = opt_arg(); break; case OPT_CERT_CHAIN: s_chain_file = opt_arg(); break; case OPT_DHPARAM: dhfile = opt_arg(); break; case OPT_DCERTFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_dcert_format)) goto opthelp; break; case OPT_DCERT: s_dcert_file = opt_arg(); break; case OPT_DKEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_dkey_format)) goto opthelp; break; case OPT_DPASS: dpassarg = opt_arg(); break; case OPT_DKEY: s_dkey_file = opt_arg(); break; case OPT_DCERT_CHAIN: s_dchain_file = opt_arg(); break; case OPT_NOCERT: nocert = 1; break; case OPT_CAPATH: CApath = opt_arg(); break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_CHAINCAPATH: chCApath = opt_arg(); break; case OPT_VERIFYCAPATH: vfyCApath = opt_arg(); break; case OPT_CASTORE: CAstore = opt_arg(); break; case OPT_NOCASTORE: noCAstore = 1; break; case OPT_CHAINCASTORE: chCAstore = opt_arg(); break; case OPT_VERIFYCASTORE: vfyCAstore = opt_arg(); break; case OPT_NO_CACHE: no_cache = 1; break; case OPT_EXT_CACHE: ext_cache = 1; break; case OPT_CRLFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format)) goto opthelp; break; case OPT_S_CASES: case OPT_S_NUM_TICKETS: case OPT_ANTI_REPLAY: case OPT_NO_ANTI_REPLAY: if (ssl_args == NULL) ssl_args = sk_OPENSSL_STRING_new_null(); if (ssl_args == NULL || !sk_OPENSSL_STRING_push(ssl_args, opt_flag()) || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) { BIO_printf(bio_err, "%s: Memory allocation failure\n", prog); goto end; } break; case OPT_V_CASES: if (!opt_verify(o, vpm)) goto end; vpmtouched++; break; case OPT_X_CASES: if (!args_excert(o, &exc)) goto end; break; case OPT_VERIFY_RET_ERROR: verify_args.return_error = 1; break; case OPT_VERIFY_QUIET: verify_args.quiet = 1; break; case OPT_BUILD_CHAIN: build_chain = 1; break; case OPT_CAFILE: CAfile = opt_arg(); break; case OPT_NOCAFILE: noCAfile = 1; break; case OPT_CHAINCAFILE: chCAfile = opt_arg(); break; case OPT_VERIFYCAFILE: vfyCAfile = opt_arg(); break; case OPT_NBIO: s_nbio = 1; break; case OPT_NBIO_TEST: s_nbio = s_nbio_test = 1; break; case OPT_IGN_EOF: s_ign_eof = 1; break; case OPT_NO_IGN_EOF: s_ign_eof = 0; break; case OPT_DEBUG: s_debug = 1; break; case OPT_TLSEXTDEBUG: s_tlsextdebug = 1; break; case OPT_STATUS: #ifndef OPENSSL_NO_OCSP s_tlsextstatus = 1; #endif break; case OPT_STATUS_VERBOSE: #ifndef OPENSSL_NO_OCSP s_tlsextstatus = tlscstatp.verbose = 1; #endif break; case OPT_STATUS_TIMEOUT: #ifndef OPENSSL_NO_OCSP s_tlsextstatus = 1; tlscstatp.timeout = atoi(opt_arg()); #endif break; case OPT_PROXY: #ifndef OPENSSL_NO_OCSP tlscstatp.proxy = opt_arg(); #endif break; case OPT_NO_PROXY: #ifndef OPENSSL_NO_OCSP tlscstatp.no_proxy = opt_arg(); #endif break; case OPT_STATUS_URL: #ifndef OPENSSL_NO_OCSP s_tlsextstatus = 1; if (!OSSL_HTTP_parse_url(opt_arg(), &tlscstatp.use_ssl, NULL, &tlscstatp.host, &tlscstatp.port, NULL, &tlscstatp.path, NULL, NULL)) { BIO_printf(bio_err, "Error parsing -status_url argument\n"); goto end; } #endif break; case OPT_STATUS_FILE: #ifndef OPENSSL_NO_OCSP s_tlsextstatus = 1; tlscstatp.respin = opt_arg(); #endif break; case OPT_MSG: s_msg = 1; break; case OPT_MSGFILE: bio_s_msg = BIO_new_file(opt_arg(), "w"); if (bio_s_msg == NULL) { BIO_printf(bio_err, "Error writing file %s\n", opt_arg()); goto end; } break; case OPT_TRACE: #ifndef OPENSSL_NO_SSL_TRACE s_msg = 2; #endif break; case OPT_SECURITY_DEBUG: sdebug = 1; break; case OPT_SECURITY_DEBUG_VERBOSE: sdebug = 2; break; case OPT_STATE: state = 1; break; case OPT_CRLF: s_crlf = 1; break; case OPT_QUIET: s_quiet = 1; break; case OPT_BRIEF: s_quiet = s_brief = verify_args.quiet = 1; break; case OPT_NO_DHE: no_dhe = 1; break; case OPT_NO_RESUME_EPHEMERAL: no_resume_ephemeral = 1; break; case OPT_PSK_IDENTITY: psk_identity = opt_arg(); break; case OPT_PSK_HINT: #ifndef OPENSSL_NO_PSK psk_identity_hint = opt_arg(); #endif break; case OPT_PSK: for (p = psk_key = opt_arg(); *p; p++) { if (isxdigit(_UC(*p))) continue; BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key); goto end; } break; case OPT_PSK_SESS: psksessf = opt_arg(); break; case OPT_SRPVFILE: #ifndef OPENSSL_NO_SRP srp_verifier_file = opt_arg(); if (min_version < TLS1_VERSION) min_version = TLS1_VERSION; #endif break; case OPT_SRPUSERSEED: #ifndef OPENSSL_NO_SRP srpuserseed = opt_arg(); if (min_version < TLS1_VERSION) min_version = TLS1_VERSION; #endif break; case OPT_REV: rev = 1; break; case OPT_WWW: www = 1; break; case OPT_UPPER_WWW: www = 2; break; case OPT_HTTP: www = 3; break; case OPT_SSL_CONFIG: ssl_config = opt_arg(); break; case OPT_SSL3: min_version = SSL3_VERSION; max_version = SSL3_VERSION; break; case OPT_TLS1_3: min_version = TLS1_3_VERSION; max_version = TLS1_3_VERSION; break; case OPT_TLS1_2: min_version = TLS1_2_VERSION; max_version = TLS1_2_VERSION; break; case OPT_TLS1_1: min_version = TLS1_1_VERSION; max_version = TLS1_1_VERSION; break; case OPT_TLS1: min_version = TLS1_VERSION; max_version = TLS1_VERSION; break; case OPT_DTLS: #ifndef OPENSSL_NO_DTLS meth = DTLS_server_method(); socket_type = SOCK_DGRAM; #endif break; case OPT_DTLS1: #ifndef OPENSSL_NO_DTLS meth = DTLS_server_method(); min_version = DTLS1_VERSION; max_version = DTLS1_VERSION; socket_type = SOCK_DGRAM; #endif break; case OPT_DTLS1_2: #ifndef OPENSSL_NO_DTLS meth = DTLS_server_method(); min_version = DTLS1_2_VERSION; max_version = DTLS1_2_VERSION; socket_type = SOCK_DGRAM; #endif break; case OPT_SCTP: #ifndef OPENSSL_NO_SCTP protocol = IPPROTO_SCTP; #endif break; case OPT_SCTP_LABEL_BUG: #ifndef OPENSSL_NO_SCTP sctp_label_bug = 1; #endif break; case OPT_TIMEOUT: #ifndef OPENSSL_NO_DTLS enable_timeouts = 1; #endif break; case OPT_MTU: #ifndef OPENSSL_NO_DTLS socket_mtu = atol(opt_arg()); #endif break; case OPT_LISTEN: #ifndef OPENSSL_NO_DTLS dtlslisten = 1; #endif break; case OPT_STATELESS: stateless = 1; break; case OPT_ID_PREFIX: session_id_prefix = opt_arg(); break; case OPT_ENGINE: #ifndef OPENSSL_NO_ENGINE engine = setup_engine(opt_arg(), s_debug); #endif break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_SERVERNAME: tlsextcbp.servername = opt_arg(); break; case OPT_SERVERNAME_FATAL: tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL; break; case OPT_CERT2: s_cert_file2 = opt_arg(); break; case OPT_KEY2: s_key_file2 = opt_arg(); break; case OPT_NEXTPROTONEG: # ifndef OPENSSL_NO_NEXTPROTONEG next_proto_neg_in = opt_arg(); #endif break; case OPT_ALPN: alpn_in = opt_arg(); break; case OPT_SRTP_PROFILES: #ifndef OPENSSL_NO_SRTP srtp_profiles = opt_arg(); #endif break; case OPT_KEYMATEXPORT: keymatexportlabel = opt_arg(); break; case OPT_KEYMATEXPORTLEN: keymatexportlen = atoi(opt_arg()); break; case OPT_ASYNC: async = 1; break; case OPT_MAX_SEND_FRAG: max_send_fragment = atoi(opt_arg()); break; case OPT_SPLIT_SEND_FRAG: split_send_fragment = atoi(opt_arg()); break; case OPT_MAX_PIPELINES: max_pipelines = atoi(opt_arg()); break; case OPT_READ_BUF: read_buf_len = atoi(opt_arg()); break; case OPT_KEYLOG_FILE: keylog_file = opt_arg(); break; case OPT_MAX_EARLY: max_early_data = atoi(opt_arg()); if (max_early_data < 0) { BIO_printf(bio_err, "Invalid value for max_early_data\n"); goto end; } break; case OPT_RECV_MAX_EARLY: recv_max_early_data = atoi(opt_arg()); if (recv_max_early_data < 0) { BIO_printf(bio_err, "Invalid value for recv_max_early_data\n"); goto end; } break; case OPT_EARLY_DATA: early_data = 1; if (max_early_data == -1) max_early_data = SSL3_RT_MAX_PLAIN_LENGTH; break; case OPT_HTTP_SERVER_BINMODE: http_server_binmode = 1; break; case OPT_NOCANAMES: no_ca_names = 1; break; case OPT_SENDFILE: #ifndef OPENSSL_NO_KTLS use_sendfile = 1; #endif break; case OPT_IGNORE_UNEXPECTED_EOF: ignore_unexpected_eof = 1; break; } } /* No extra arguments. */ argc = opt_num_rest(); if (argc != 0) goto opthelp; if (!app_RAND_load()) goto end; #ifndef OPENSSL_NO_NEXTPROTONEG if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) { BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n"); goto opthelp; } #endif #ifndef OPENSSL_NO_DTLS if (www && socket_type == SOCK_DGRAM) { BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n"); goto end; } if (dtlslisten && socket_type != SOCK_DGRAM) { BIO_printf(bio_err, "Can only use -listen with DTLS\n"); goto end; } #endif if (stateless && socket_type != SOCK_STREAM) { BIO_printf(bio_err, "Can only use --stateless with TLS\n"); goto end; } #ifdef AF_UNIX if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) { BIO_printf(bio_err, "Can't use unix sockets and datagrams together\n"); goto end; } #endif if (early_data && (www > 0 || rev)) { BIO_printf(bio_err, "Can't use -early_data in combination with -www, -WWW, -HTTP, or -rev\n"); goto end; } #ifndef OPENSSL_NO_SCTP if (protocol == IPPROTO_SCTP) { if (socket_type != SOCK_DGRAM) { BIO_printf(bio_err, "Can't use -sctp without DTLS\n"); goto end; } /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */ socket_type = SOCK_STREAM; } #endif #ifndef OPENSSL_NO_KTLS if (use_sendfile && www <= 1) { BIO_printf(bio_err, "Can't use -sendfile without -WWW or -HTTP\n"); goto end; } #endif if (!app_passwd(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; if (s_key_file2 == NULL) s_key_file2 = s_cert_file2; if (!load_excert(&exc)) goto end; if (nocert == 0) { s_key = load_key(s_key_file, s_key_format, 0, pass, engine, "server certificate private key"); if (s_key == NULL) goto end; s_cert = load_cert_pass(s_cert_file, s_cert_format, 1, pass, "server certificate"); if (s_cert == NULL) goto end; if (s_chain_file != NULL) { if (!load_certs(s_chain_file, 0, &s_chain, NULL, "server certificate chain")) goto end; } if (tlsextcbp.servername != NULL) { s_key2 = load_key(s_key_file2, s_key_format, 0, pass, engine, "second server certificate private key"); if (s_key2 == NULL) goto end; s_cert2 = load_cert_pass(s_cert_file2, s_cert_format, 1, pass, "second server certificate"); if (s_cert2 == NULL) goto end; } } #if !defined(OPENSSL_NO_NEXTPROTONEG) if (next_proto_neg_in) { next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in); if (next_proto.data == NULL) goto end; } #endif alpn_ctx.data = NULL; if (alpn_in) { alpn_ctx.data = next_protos_parse(&alpn_ctx.len, alpn_in); if (alpn_ctx.data == NULL) goto end; } if (crl_file != NULL) { X509_CRL *crl; crl = load_crl(crl_file, crl_format, 0, "CRL"); if (crl == NULL) goto end; crls = sk_X509_CRL_new_null(); if (crls == NULL || !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 != NULL) { if (s_dkey_file == NULL) s_dkey_file = s_dcert_file; s_dkey = load_key(s_dkey_file, s_dkey_format, 0, dpass, engine, "second certificate private key"); if (s_dkey == NULL) goto end; s_dcert = load_cert_pass(s_dcert_file, s_dcert_format, 1, dpass, "second server certificate"); if (s_dcert == NULL) { ERR_print_errors(bio_err); goto end; } if (s_dchain_file != NULL) { if (!load_certs(s_dchain_file, 0, &s_dchain, NULL, "second server certificate chain")) goto end; } } if (bio_s_out == NULL) { if (s_quiet && !s_debug) { bio_s_out = BIO_new(BIO_s_null()); if (s_msg && bio_s_msg == NULL) { bio_s_msg = dup_bio_out(FORMAT_TEXT); if (bio_s_msg == NULL) { BIO_printf(bio_err, "Out of memory\n"); goto end; } } } else { bio_s_out = dup_bio_out(FORMAT_TEXT); } } if (bio_s_out == NULL) goto end; if (nocert) { s_cert_file = NULL; s_key_file = NULL; s_dcert_file = NULL; s_dkey_file = NULL; s_cert_file2 = NULL; s_key_file2 = NULL; } ctx = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth); if (ctx == NULL) { ERR_print_errors(bio_err); goto end; } SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY); if (sdebug) ssl_ctx_security_debug(ctx, sdebug); if (!config_ctx(cctx, ssl_args, ctx)) goto end; if (ssl_config) { if (SSL_CTX_config(ctx, ssl_config) == 0) { BIO_printf(bio_err, "Error using configuration \"%s\"\n", ssl_config); ERR_print_errors(bio_err); goto end; } } #ifndef OPENSSL_NO_SCTP if (protocol == IPPROTO_SCTP && sctp_label_bug == 1) SSL_CTX_set_mode(ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG); #endif if (min_version != 0 && SSL_CTX_set_min_proto_version(ctx, min_version) == 0) goto end; if (max_version != 0 && SSL_CTX_set_max_proto_version(ctx, max_version) == 0) 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"); 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); } if (exc != NULL) 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); if (async) { SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC); } if (no_ca_names) { SSL_CTX_set_options(ctx, SSL_OP_DISABLE_TLSEXT_CA_NAMES); } if (ignore_unexpected_eof) SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF); if (max_send_fragment > 0 && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) { BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n", prog, max_send_fragment); goto end; } if (split_send_fragment > 0 && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) { BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n", prog, split_send_fragment); goto end; } if (max_pipelines > 0 && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) { BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n", prog, max_pipelines); goto end; } if (read_buf_len > 0) { SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len); } #ifndef OPENSSL_NO_SRTP if (srtp_profiles != NULL) { /* Returns 0 on success! */ if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) { BIO_printf(bio_err, "Error setting SRTP profile\n"); ERR_print_errors(bio_err); goto end; } } #endif if (!ctx_set_verify_locations(ctx, CAfile, noCAfile, CApath, noCApath, CAstore, noCAstore)) { ERR_print_errors(bio_err); goto end; } if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) { BIO_printf(bio_err, "Error setting verify params\n"); ERR_print_errors(bio_err); goto end; } ssl_ctx_add_crls(ctx, crls, 0); if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, vfyCAstore, chCApath, chCAfile, chCAstore, crls, crl_download)) { BIO_printf(bio_err, "Error loading store locations\n"); ERR_print_errors(bio_err); goto end; } if (s_cert2) { ctx2 = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth); if (ctx2 == NULL) { ERR_print_errors(bio_err); goto end; } } if (ctx2 != NULL) { BIO_printf(bio_s_out, "Setting secondary ctx parameters\n"); if (sdebug) ssl_ctx_security_debug(ctx2, sdebug); 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"); 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); } if (exc != NULL) 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 (async) SSL_CTX_set_mode(ctx2, SSL_MODE_ASYNC); if (!ctx_set_verify_locations(ctx2, CAfile, noCAfile, CApath, noCApath, CAstore, noCAstore)) { ERR_print_errors(bio_err); goto end; } if (vpmtouched && !SSL_CTX_set1_param(ctx2, vpm)) { BIO_printf(bio_err, "Error setting verify params\n"); ERR_print_errors(bio_err); goto end; } ssl_ctx_add_crls(ctx2, crls, 0); if (!config_ctx(cctx, ssl_args, ctx2)) 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); if (!no_dhe) { EVP_PKEY *dhpkey = NULL; if (dhfile != NULL) dhpkey = load_keyparams(dhfile, FORMAT_UNDEF, 0, "DH", "DH parameters"); else if (s_cert_file != NULL) dhpkey = load_keyparams_suppress(s_cert_file, FORMAT_UNDEF, 0, "DH", "DH parameters", 1); if (dhpkey != NULL) { BIO_printf(bio_s_out, "Setting temp DH parameters\n"); } else { BIO_printf(bio_s_out, "Using default temp DH parameters\n"); } (void)BIO_flush(bio_s_out); if (dhpkey == NULL) { SSL_CTX_set_dh_auto(ctx, 1); } else { /* * We need 2 references: one for use by ctx and one for use by * ctx2 */ if (!EVP_PKEY_up_ref(dhpkey)) { EVP_PKEY_free(dhpkey); goto end; } if (!SSL_CTX_set0_tmp_dh_pkey(ctx, dhpkey)) { BIO_puts(bio_err, "Error setting temp DH parameters\n"); ERR_print_errors(bio_err); /* Free 2 references */ EVP_PKEY_free(dhpkey); EVP_PKEY_free(dhpkey); goto end; } } if (ctx2 != NULL) { if (dhfile != NULL) { EVP_PKEY *dhpkey2 = load_keyparams_suppress(s_cert_file2, FORMAT_UNDEF, 0, "DH", "DH parameters", 1); if (dhpkey2 != NULL) { BIO_printf(bio_s_out, "Setting temp DH parameters\n"); (void)BIO_flush(bio_s_out); EVP_PKEY_free(dhpkey); dhpkey = dhpkey2; } } if (dhpkey == NULL) { SSL_CTX_set_dh_auto(ctx2, 1); } else if (!SSL_CTX_set0_tmp_dh_pkey(ctx2, dhpkey)) { BIO_puts(bio_err, "Error setting temp DH parameters\n"); ERR_print_errors(bio_err); EVP_PKEY_free(dhpkey); goto end; } dhpkey = NULL; } EVP_PKEY_free(dhpkey); } if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain)) goto end; if (s_serverinfo_file != NULL && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) { ERR_print_errors(bio_err); goto end; } if (ctx2 != NULL && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain)) goto end; if (s_dcert != NULL) { if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain)) goto end; } if (no_resume_ephemeral) { SSL_CTX_set_not_resumable_session_callback(ctx, not_resumable_sess_cb); if (ctx2 != NULL) SSL_CTX_set_not_resumable_session_callback(ctx2, not_resumable_sess_cb); } #ifndef OPENSSL_NO_PSK if (psk_key != NULL) { if (s_debug) BIO_printf(bio_s_out, "PSK key given, setting server callback\n"); SSL_CTX_set_psk_server_callback(ctx, psk_server_cb); } if (psk_identity_hint != NULL) { if (min_version == TLS1_3_VERSION) { BIO_printf(bio_s_out, "PSK warning: there is NO identity hint in TLSv1.3\n"); } else { 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 if (psksessf != NULL) { BIO *stmp = BIO_new_file(psksessf, "r"); if (stmp == NULL) { BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf); ERR_print_errors(bio_err); goto end; } psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL); BIO_free(stmp); if (psksess == NULL) { BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf); ERR_print_errors(bio_err); goto end; } } if (psk_key != NULL || psksess != NULL) SSL_CTX_set_psk_find_session_callback(ctx, psk_find_session_cb); SSL_CTX_set_verify(ctx, s_server_verify, verify_callback); if (!SSL_CTX_set_session_id_context(ctx, (void *)&s_server_session_id_context, sizeof(s_server_session_id_context))) { BIO_printf(bio_err, "error setting session id context\n"); ERR_print_errors(bio_err); goto end; } /* 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); /* Set TLS1.3 cookie generation and verification callbacks */ SSL_CTX_set_stateless_cookie_generate_cb(ctx, generate_stateless_cookie_callback); SSL_CTX_set_stateless_cookie_verify_cb(ctx, verify_stateless_cookie_callback); if (ctx2 != NULL) { SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback); if (!SSL_CTX_set_session_id_context(ctx2, (void *)&s_server_session_id_context, sizeof(s_server_session_id_context))) { BIO_printf(bio_err, "error setting session id context\n"); ERR_print_errors(bio_err); goto end; } 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); } #ifndef OPENSSL_NO_SRP if (srp_verifier_file != NULL) { if (!set_up_srp_verifier_file(ctx, &srp_callback_parm, srpuserseed, srp_verifier_file)) goto end; } else #endif if (CAfile != NULL) { SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile)); if (ctx2) SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile)); } #ifndef OPENSSL_NO_OCSP if (s_tlsextstatus) { SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb); SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp); if (ctx2) { SSL_CTX_set_tlsext_status_cb(ctx2, cert_status_cb); SSL_CTX_set_tlsext_status_arg(ctx2, &tlscstatp); } } #endif if (set_keylog_file(ctx, keylog_file)) goto end; if (max_early_data >= 0) SSL_CTX_set_max_early_data(ctx, max_early_data); if (recv_max_early_data >= 0) SSL_CTX_set_recv_max_early_data(ctx, recv_max_early_data); if (rev) server_cb = rev_body; else if (www) server_cb = www_body; else server_cb = sv_body; #ifdef AF_UNIX if (socket_family == AF_UNIX && unlink_unix_path) unlink(host); #endif do_server(&accept_socket, host, port, socket_family, socket_type, protocol, server_cb, context, naccept, bio_s_out); print_stats(bio_s_out, ctx); ret = 0; end: SSL_CTX_free(ctx); SSL_SESSION_free(psksess); set_keylog_file(NULL, NULL); X509_free(s_cert); sk_X509_CRL_pop_free(crls, X509_CRL_free); X509_free(s_dcert); EVP_PKEY_free(s_key); EVP_PKEY_free(s_dkey); sk_X509_pop_free(s_chain, X509_free); sk_X509_pop_free(s_dchain, X509_free); OPENSSL_free(pass); OPENSSL_free(dpass); OPENSSL_free(host); OPENSSL_free(port); X509_VERIFY_PARAM_free(vpm); free_sessions(); OPENSSL_free(tlscstatp.host); OPENSSL_free(tlscstatp.port); OPENSSL_free(tlscstatp.path); SSL_CTX_free(ctx2); X509_free(s_cert2); EVP_PKEY_free(s_key2); #ifndef OPENSSL_NO_NEXTPROTONEG OPENSSL_free(next_proto.data); #endif OPENSSL_free(alpn_ctx.data); ssl_excert_free(exc); sk_OPENSSL_STRING_free(ssl_args); SSL_CONF_CTX_free(cctx); release_engine(engine); BIO_free(bio_s_out); bio_s_out = NULL; BIO_free(bio_s_msg); bio_s_msg = NULL; #ifdef CHARSET_EBCDIC BIO_meth_free(methods_ebcdic); #endif return 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 long int count_reads_callback(BIO *bio, int cmd, const char *argp, size_t len, int argi, long argl, int ret, size_t *processed) { unsigned int *p_counter = (unsigned int *)BIO_get_callback_arg(bio); switch (cmd) { case BIO_CB_READ: /* No break here */ case BIO_CB_GETS: if (p_counter != NULL) ++*p_counter; break; default: break; } if (s_debug) { BIO_set_callback_arg(bio, (char *)bio_s_out); ret = (int)bio_dump_callback(bio, cmd, argp, len, argi, argl, ret, processed); BIO_set_callback_arg(bio, (char *)p_counter); } return ret; } static int sv_body(int s, int stype, int prot, unsigned char *context) { char *buf = NULL; fd_set readfds; int ret = 1, width; int k, i; unsigned long l; SSL *con = NULL; BIO *sbio; struct timeval timeout; #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)) struct timeval *timeoutp; #endif #ifndef OPENSSL_NO_DTLS # ifndef OPENSSL_NO_SCTP int isdtls = (stype == SOCK_DGRAM || prot == IPPROTO_SCTP); # else int isdtls = (stype == SOCK_DGRAM); # endif #endif buf = app_malloc(bufsize, "server buffer"); if (s_nbio) { if (!BIO_socket_nbio(s, 1)) ERR_print_errors(bio_err); else if (!s_quiet) BIO_printf(bio_err, "Turned on non blocking io\n"); } con = SSL_new(ctx); if (con == NULL) { ret = -1; goto err; } if (s_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_s_out); } if (context != NULL && !SSL_set_session_id_context(con, context, strlen((char *)context))) { BIO_printf(bio_err, "Error setting session id context\n"); ret = -1; goto err; } if (!SSL_clear(con)) { BIO_printf(bio_err, "Error clearing SSL connection\n"); ret = -1; goto err; } #ifndef OPENSSL_NO_DTLS if (isdtls) { # ifndef OPENSSL_NO_SCTP if (prot == IPPROTO_SCTP) sbio = BIO_new_dgram_sctp(s, BIO_NOCLOSE); else # endif sbio = BIO_new_dgram(s, BIO_NOCLOSE); if (sbio == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); ERR_print_errors(bio_err); goto err; } 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); # ifndef OPENSSL_NO_SCTP if (prot != IPPROTO_SCTP) # endif /* Turn on cookie exchange. Not necessary for SCTP */ SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE); } else #endif sbio = BIO_new_socket(s, BIO_NOCLOSE); if (sbio == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); ERR_print_errors(bio_err); goto err; } if (s_nbio_test) { BIO *test; test = BIO_new(BIO_f_nbio_test()); if (test == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); ret = -1; BIO_free(sbio); goto err; } sbio = BIO_push(test, sbio); } SSL_set_bio(con, sbio, sbio); SSL_set_accept_state(con); /* SSL_set_fd(con,s); */ BIO_set_callback_ex(SSL_get_rbio(con), count_reads_callback); 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); } if (s_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_s_out); } if (early_data) { int write_header = 1, edret = SSL_READ_EARLY_DATA_ERROR; size_t readbytes; while (edret != SSL_READ_EARLY_DATA_FINISH) { for (;;) { edret = SSL_read_early_data(con, buf, bufsize, &readbytes); if (edret != SSL_READ_EARLY_DATA_ERROR) break; switch (SSL_get_error(con, 0)) { case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_ASYNC: case SSL_ERROR_WANT_READ: /* Just keep trying - busy waiting */ continue; default: BIO_printf(bio_err, "Error reading early data\n"); ERR_print_errors(bio_err); goto err; } } if (readbytes > 0) { if (write_header) { BIO_printf(bio_s_out, "Early data received:\n"); write_header = 0; } raw_write_stdout(buf, (unsigned int)readbytes); (void)BIO_flush(bio_s_out); } } if (write_header) { if (SSL_get_early_data_status(con) == SSL_EARLY_DATA_NOT_SENT) BIO_printf(bio_s_out, "No early data received\n"); else BIO_printf(bio_s_out, "Early data was rejected\n"); } else { BIO_printf(bio_s_out, "\nEnd of early data\n"); } if (SSL_is_init_finished(con)) print_connection_info(con); } 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_has_pending(con) || (async && SSL_waiting_for_async(con)); if (!read_from_sslcon) { FD_ZERO(&readfds); #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) 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) /* * 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. */ timeout.tv_sec = 1; timeout.tv_usec = 0; i = select(width, (void *)&readfds, NULL, NULL, &timeout); if (has_stdin_waiting()) read_from_terminal = 1; if ((i < 0) || (!i && !read_from_terminal)) continue; #else if (SSL_is_dtls(con) && DTLSv1_get_timeout(con, &timeout)) timeoutp = &timeout; else timeoutp = NULL; i = select(width, (void *)&readfds, NULL, NULL, timeoutp); if ((SSL_is_dtls(con)) && DTLSv1_handle_timeout(con) > 0) BIO_printf(bio_err, "TIMEOUT occurred\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"); (void)BIO_flush(bio_s_out); BIO_closesocket(s); close_accept_socket(); ret = -11; goto err; } if ((i <= 0) || (buf[0] == 'q')) { BIO_printf(bio_s_out, "DONE\n"); (void)BIO_flush(bio_s_out); if (SSL_version(con) != DTLS1_VERSION) BIO_closesocket(s); /* * close_accept_socket(); ret= -11; */ goto err; } 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; } 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; } if ((buf[0] == 'K' || buf[0] == 'k') && ((buf[1] == '\n') || (buf[1] == '\r'))) { SSL_key_update(con, buf[0] == 'K' ? SSL_KEY_UPDATE_REQUESTED : SSL_KEY_UPDATE_NOT_REQUESTED); i = SSL_do_handshake(con); printf("SSL_do_handshake -> %d\n", i); i = 0; continue; } if (buf[0] == 'c' && ((buf[1] == '\n') || (buf[1] == '\r'))) { SSL_set_verify(con, SSL_VERIFY_PEER, NULL); i = SSL_verify_client_post_handshake(con); if (i == 0) { printf("Failed to initiate request\n"); ERR_print_errors(bio_err); } else { i = SSL_do_handshake(con); printf("SSL_do_handshake -> %d\n", i); i = 0; } continue; } if (buf[0] == 'P') { static const char str[] = "Lets print some clear text\n"; BIO_write(SSL_get_wbio(con), str, sizeof(str) -1); } 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"); lookup_srp_user(&srp_callback_parm, bio_s_out); 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_ASYNC: BIO_printf(bio_s_out, "Write BLOCK (Async)\n"); (void)BIO_flush(bio_s_out); wait_for_async(con); 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"); (void)BIO_flush(bio_s_out); break; case SSL_ERROR_WANT_ASYNC_JOB: /* * This shouldn't ever happen in s_server. Treat as an error */ case SSL_ERROR_SYSCALL: case SSL_ERROR_SSL: BIO_printf(bio_s_out, "ERROR\n"); (void)BIO_flush(bio_s_out); ERR_print_errors(bio_err); ret = 1; goto err; /* break; */ case SSL_ERROR_ZERO_RETURN: BIO_printf(bio_s_out, "DONE\n"); (void)BIO_flush(bio_s_out); ret = 1; goto err; } if (k > 0) { l += k; i -= k; } if (i <= 0) break; } } if (read_from_sslcon) { /* * init_ssl_connection handles all async events itself so if we're * waiting for async then we shouldn't go back into * init_ssl_connection */ if ((!async || !SSL_waiting_for_async(con)) && !SSL_is_init_finished(con)) { /* * Count number of reads during init_ssl_connection. * It helps us to distinguish configuration errors from errors * caused by a client. */ unsigned int read_counter = 0; BIO_set_callback_arg(SSL_get_rbio(con), (char *)&read_counter); i = init_ssl_connection(con); BIO_set_callback_arg(SSL_get_rbio(con), NULL); /* * If initialization fails without reads, then * there was a fatal error in configuration. */ if (i <= 0 && read_counter == 0) { ret = -1; goto err; } 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"); lookup_srp_user(&srp_callback_parm, bio_s_out); 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); (void)BIO_flush(bio_s_out); if (SSL_has_pending(con)) goto again; break; case SSL_ERROR_WANT_ASYNC: BIO_printf(bio_s_out, "Read BLOCK (Async)\n"); (void)BIO_flush(bio_s_out); wait_for_async(con); break; case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_READ: BIO_printf(bio_s_out, "Read BLOCK\n"); (void)BIO_flush(bio_s_out); break; case SSL_ERROR_WANT_ASYNC_JOB: /* * This shouldn't ever happen in s_server. Treat as an error */ case SSL_ERROR_SYSCALL: case SSL_ERROR_SSL: BIO_printf(bio_s_out, "ERROR\n"); (void)BIO_flush(bio_s_out); ERR_print_errors(bio_err); ret = 1; goto err; case SSL_ERROR_ZERO_RETURN: BIO_printf(bio_s_out, "DONE\n"); (void)BIO_flush(bio_s_out); ret = 1; goto err; } } } } err: if (con != NULL) { BIO_printf(bio_s_out, "shutting down SSL\n"); do_ssl_shutdown(con); SSL_free(con); } BIO_printf(bio_s_out, "CONNECTION CLOSED\n"); OPENSSL_clear_free(buf, bufsize); return ret; } static void close_accept_socket(void) { BIO_printf(bio_err, "shutdown accept socket\n"); if (accept_socket >= 0) { BIO_closesocket(accept_socket); } } static int is_retryable(SSL *con, int i) { int err = SSL_get_error(con, i); /* If it's not a fatal error, it must be retryable */ return (err != SSL_ERROR_SSL) && (err != SSL_ERROR_SYSCALL) && (err != SSL_ERROR_ZERO_RETURN); } static int init_ssl_connection(SSL *con) { int i; long verify_err; int retry = 0; if (dtlslisten || stateless) { BIO_ADDR *client = NULL; if (dtlslisten) { if ((client = BIO_ADDR_new()) == NULL) { BIO_printf(bio_err, "ERROR - memory\n"); return 0; } i = DTLSv1_listen(con, client); } else { i = SSL_stateless(con); } if (i > 0) { BIO *wbio; int fd = -1; if (dtlslisten) { wbio = SSL_get_wbio(con); if (wbio) { BIO_get_fd(wbio, &fd); } if (!wbio || BIO_connect(fd, client, 0) == 0) { BIO_printf(bio_err, "ERROR - unable to connect\n"); BIO_ADDR_free(client); return 0; } (void)BIO_ctrl_set_connected(wbio, client); BIO_ADDR_free(client); dtlslisten = 0; } else { stateless = 0; } i = SSL_accept(con); } else { BIO_ADDR_free(client); } } else { do { i = SSL_accept(con); if (i <= 0) retry = is_retryable(con, i); #ifdef CERT_CB_TEST_RETRY { while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP && SSL_get_state(con) == TLS_ST_SR_CLNT_HELLO) { BIO_printf(bio_err, "LOOKUP from certificate callback during accept\n"); i = SSL_accept(con); if (i <= 0) retry = is_retryable(con, i); } } #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); lookup_srp_user(&srp_callback_parm, bio_s_out); i = SSL_accept(con); if (i <= 0) retry = is_retryable(con, i); } #endif } while (i < 0 && SSL_waiting_for_async(con)); } if (i <= 0) { if (((dtlslisten || stateless) && i == 0) || (!dtlslisten && !stateless && retry)) { BIO_printf(bio_s_out, "DELAY\n"); return 1; } BIO_printf(bio_err, "ERROR\n"); verify_err = SSL_get_verify_result(con); if (verify_err != X509_V_OK) { BIO_printf(bio_err, "verify error:%s\n", X509_verify_cert_error_string(verify_err)); } /* Always print any error messages */ ERR_print_errors(bio_err); return 0; } print_connection_info(con); return 1; } static void print_connection_info(SSL *con) { const char *str; X509 *peer; char buf[BUFSIZ]; #if !defined(OPENSSL_NO_NEXTPROTONEG) const unsigned char *next_proto_neg; unsigned next_proto_neg_len; #endif unsigned char *exportedkeymat; int i; if (s_brief) print_ssl_summary(con); PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con)); peer = SSL_get0_peer_certificate(con); if (peer != NULL) { BIO_printf(bio_s_out, "Client certificate\n"); PEM_write_bio_X509(bio_s_out, peer); dump_cert_text(bio_s_out, peer); peer = NULL; } 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_groups(bio_s_out, con, 0); #endif print_ca_names(bio_s_out, con); BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)"); #if !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_session_reused(con)) BIO_printf(bio_s_out, "Reused session-id\n"); BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n", SSL_get_secure_renegotiation_support(con) ? "" : " NOT"); if ((SSL_get_options(con) & SSL_OP_NO_RENEGOTIATION)) BIO_printf(bio_s_out, "Renegotiation is DISABLED\n"); 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 = app_malloc(keymatexportlen, "export key"); if (SSL_export_keying_material(con, exportedkeymat, keymatexportlen, keymatexportlabel, strlen(keymatexportlabel), NULL, 0, 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); } #ifndef OPENSSL_NO_KTLS if (BIO_get_ktls_send(SSL_get_wbio(con))) BIO_printf(bio_err, "Using Kernel TLS for sending\n"); if (BIO_get_ktls_recv(SSL_get_rbio(con))) BIO_printf(bio_err, "Using Kernel TLS for receiving\n"); #endif (void)BIO_flush(bio_s_out); } static int www_body(int s, int stype, int prot, 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; #ifdef RENEG int total_bytes = 0; #endif int width; #ifndef OPENSSL_NO_KTLS int use_sendfile_for_req = use_sendfile; #endif fd_set readfds; const char *opmode; #ifdef CHARSET_EBCDIC BIO *filter; #endif /* Set width for a select call if needed */ width = s + 1; /* as we use BIO_gets(), and it always null terminates data, we need * to allocate 1 byte longer buffer to fit the full 2^14 byte record */ buf = app_malloc(bufsize + 1, "server www buffer"); io = BIO_new(BIO_f_buffer()); ssl_bio = BIO_new(BIO_f_ssl()); if ((io == NULL) || (ssl_bio == NULL)) goto err; if (s_nbio) { if (!BIO_socket_nbio(s, 1)) ERR_print_errors(bio_err); else if (!s_quiet) BIO_printf(bio_err, "Turned on non blocking io\n"); } /* lets make the output buffer a reasonable size */ if (BIO_set_write_buffer_size(io, bufsize) <= 0) goto err; if ((con = SSL_new(ctx)) == NULL) goto err; if (s_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_s_out); } if (context != NULL && !SSL_set_session_id_context(con, context, strlen((char *)context))) { SSL_free(con); goto err; } sbio = BIO_new_socket(s, BIO_NOCLOSE); if (sbio == NULL) { SSL_free(con); goto err; } if (s_nbio_test) { BIO *test; test = BIO_new(BIO_f_nbio_test()); if (test == NULL) { SSL_free(con); BIO_free(sbio); goto err; } sbio = BIO_push(test, sbio); } SSL_set_bio(con, sbio, sbio); SSL_set_accept_state(con); /* No need to free |con| after this. Done by BIO_free(ssl_bio) */ BIO_set_ssl(ssl_bio, con, BIO_CLOSE); BIO_push(io, ssl_bio); ssl_bio = NULL; #ifdef CHARSET_EBCDIC filter = BIO_new(BIO_f_ebcdic_filter()); if (filter == NULL) goto err; io = BIO_push(filter, io); #endif if (s_debug) { BIO_set_callback_ex(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_gets(io, buf, bufsize + 1); if (i < 0) { /* error */ if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) { 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"); lookup_srp_user(&srp_callback_parm, bio_s_out); continue; } #endif ossl_sleep(1000); 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 = NULL; STACK_OF(SSL_CIPHER) *sk; static const char *space = " "; if (www == 1 && strncmp("GET /reneg", buf, 10) == 0) { if (strncmp("GET /renegcert", buf, 14) == 0) SSL_set_verify(con, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, NULL); i = SSL_renegotiate(con); BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i); /* Send the HelloRequest */ i = SSL_do_handshake(con); if (i <= 0) { BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n", SSL_get_error(con, i)); ERR_print_errors(bio_err); goto err; } /* Wait for a ClientHello to come back */ FD_ZERO(&readfds); openssl_fdset(s, &readfds); i = select(width, (void *)&readfds, NULL, NULL, NULL); if (i <= 0 || !FD_ISSET(s, &readfds)) { BIO_printf(bio_s_out, "Error waiting for client response\n"); ERR_print_errors(bio_err); goto err; } /* * We're not actually expecting any data here and we ignore * any that is sent. This is just to force the handshake that * we're expecting to come from the client. If they haven't * sent one there's not much we can do. */ BIO_gets(io, buf, bufsize + 1); } 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, OpenSSL_version(OPENSSL_VERSION)); */
             BIO_puts(io, "\n");
             for (i = 0; i < local_argc; i++) {
                 const char *myp;
                 for (myp = local_argv[i]; *myp; myp++)
                     switch (*myp) {
                     case '<':
                         BIO_puts(io, "<");
                         break;
                     case '>':
                         BIO_puts(io, ">");
                         break;
                     case '&':
                         BIO_puts(io, "&");
                         break;
                     default:
                         BIO_write(io, myp, 1);
                         break;
                     }
                 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_groups(io, con, 0);
 #endif
             print_ca_names(io, con);
             BIO_printf(io, (SSL_session_reused(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_get0_peer_certificate(con);
             if (peer != NULL) {
                 BIO_printf(io, "Client certificate\n");
                 X509_print(io, peer);
                 PEM_write_bio_X509(io, peer);
                 peer = NULL;
             } else {
                 BIO_puts(io, "no client certificate available\n");
             }
             BIO_puts(io, "
\r\n\r\n"); break; } else if ((www == 2 || www == 3) && (strncmp("GET /", buf, 5) == 0)) { BIO *file; char *p, *e; static const char *text = "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n"; /* skip the '/' */ p = &(buf[5]); dot = 1; for (e = p; *e != '\0'; e++) { if (e[0] == ' ') break; if (e[0] == ':') { /* Windows drive. We treat this the same way as ".." */ dot = -1; break; } switch (dot) { case 1: dot = (e[0] == '.') ? 2 : 0; break; case 2: dot = (e[0] == '.') ? 3 : 0; break; case 3: dot = (e[0] == '/' || e[0] == '\\') ? -1 : 0; break; } if (dot == 0) dot = (e[0] == '/' || 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 '..' or ':'\r\n", p); break; } if (*p == '/' || *p == '\\') { BIO_puts(io, text); BIO_printf(io, "'%s' is an invalid path\r\n", p); break; } /* if a directory, do the index thang */ if (app_isdir(p) > 0) { BIO_puts(io, text); BIO_printf(io, "'%s' is a directory\r\n", p); break; } opmode = (http_server_binmode == 1) ? "rb" : "r"; if ((file = BIO_new_file(p, opmode)) == NULL) { BIO_puts(io, text); BIO_printf(io, "Error opening '%s' mode='%s'\r\n", p, opmode); 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 */ #ifndef OPENSSL_NO_KTLS if (use_sendfile_for_req && !BIO_get_ktls_send(SSL_get_wbio(con))) { BIO_printf(bio_err, "Warning: sendfile requested but KTLS is not available\n"); use_sendfile_for_req = 0; } if (use_sendfile_for_req) { FILE *fp = NULL; int fd; struct stat st; off_t offset = 0; size_t filesize; BIO_get_fp(file, &fp); fd = fileno(fp); if (fstat(fd, &st) < 0) { BIO_printf(io, "Error fstat '%s'\r\n", p); ERR_print_errors(io); goto write_error; } filesize = st.st_size; if (((int)BIO_flush(io)) < 0) goto write_error; for (;;) { i = SSL_sendfile(con, fd, offset, filesize, 0); if (i < 0) { BIO_printf(io, "Error SSL_sendfile '%s'\r\n", p); ERR_print_errors(io); break; } else { offset += i; filesize -= i; } if (filesize <= 0) { if (!s_quiet) BIO_printf(bio_err, "KTLS SENDFILE '%s' OK\n", p); break; } } } else #endif { for (;;) { i = BIO_read(file, buf, bufsize); if (i <= 0) break; #ifdef RENEG total_bytes += i; BIO_printf(bio_err, "%d\n", i); if (total_bytes > 3 * 1024) { total_bytes = 0; BIO_printf(bio_err, "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) && !SSL_waiting_for_async(con)) { 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: /* make sure we re-use sessions */ do_ssl_shutdown(con); err: OPENSSL_free(buf); BIO_free(ssl_bio); BIO_free_all(io); return ret; } static int rev_body(int s, int stype, int prot, unsigned char *context) { char *buf = NULL; int i; int ret = 1; SSL *con; BIO *io, *ssl_bio, *sbio; #ifdef CHARSET_EBCDIC BIO *filter; #endif /* as we use BIO_gets(), and it always null terminates data, we need * to allocate 1 byte longer buffer to fit the full 2^14 byte record */ buf = app_malloc(bufsize + 1, "server rev buffer"); 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) <= 0) goto err; if ((con = SSL_new(ctx)) == NULL) goto err; if (s_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_s_out); } if (context != NULL && !SSL_set_session_id_context(con, context, strlen((char *)context))) { SSL_free(con); ERR_print_errors(bio_err); goto err; } sbio = BIO_new_socket(s, BIO_NOCLOSE); if (sbio == NULL) { SSL_free(con); ERR_print_errors(bio_err); goto err; } SSL_set_bio(con, sbio, sbio); SSL_set_accept_state(con); /* No need to free |con| after this. Done by BIO_free(ssl_bio) */ BIO_set_ssl(ssl_bio, con, BIO_CLOSE); BIO_push(io, ssl_bio); ssl_bio = NULL; #ifdef CHARSET_EBCDIC filter = BIO_new(BIO_f_ebcdic_filter()); if (filter == NULL) goto err; io = BIO_push(filter, io); #endif if (s_debug) { BIO_set_callback_ex(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"); lookup_srp_user(&srp_callback_parm, bio_s_out); continue; } #endif } BIO_printf(bio_err, "CONNECTION ESTABLISHED\n"); print_ssl_summary(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"); lookup_srp_user(&srp_callback_parm, bio_s_out); continue; } #endif ossl_sleep(1000); 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) == 0)) { 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 */ do_ssl_shutdown(con); err: OPENSSL_free(buf); BIO_free(ssl_bio); BIO_free_all(io); return ret; } #define MAX_SESSION_ID_ATTEMPTS 10 static int generate_session_id(SSL *ssl, unsigned char *id, unsigned int *id_len) { unsigned int count = 0; unsigned int session_id_prefix_len = strlen(session_id_prefix); 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, (session_id_prefix_len < *id_len) ? session_id_prefix_len : *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 serialization. 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 = app_malloc(sizeof(*sess), "get session"); unsigned char *p; SSL_SESSION_get_id(session, &sess->idlen); sess->derlen = i2d_SSL_SESSION(session, NULL); if (sess->derlen < 0) { BIO_printf(bio_err, "Error encoding session\n"); OPENSSL_free(sess); return 0; } sess->id = OPENSSL_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen); sess->der = app_malloc(sess->derlen, "get session buffer"); if (!sess->id) { BIO_printf(bio_err, "Out of memory adding to external cache\n"); OPENSSL_free(sess->id); OPENSSL_free(sess->der); OPENSSL_free(sess); return 0; } p = sess->der; /* Assume it still works. */ if (i2d_SSL_SESSION(session, &p) != sess->derlen) { BIO_printf(bio_err, "Unexpected session encoding length\n"); OPENSSL_free(sess->id); OPENSSL_free(sess->der); OPENSSL_free(sess); return 0; } 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, const 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; } #endif /* OPENSSL_NO_SOCK */ diff --git a/crypto/asn1/a_strnid.c b/crypto/asn1/a_strnid.c index 9e54db929282..d052935661d3 100644 --- a/crypto/asn1/a_strnid.c +++ b/crypto/asn1/a_strnid.c @@ -1,222 +1,224 @@ /* - * Copyright 1999-2020 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1999-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include #include "internal/cryptlib.h" #include #include static STACK_OF(ASN1_STRING_TABLE) *stable = NULL; static void st_free(ASN1_STRING_TABLE *tbl); static int sk_table_cmp(const ASN1_STRING_TABLE *const *a, const ASN1_STRING_TABLE *const *b); /* * This is the global mask for the mbstring functions: this is use to mask * out certain types (such as BMPString and UTF8String) because certain * software (e.g. Netscape) has problems with them. */ static unsigned long global_mask = B_ASN1_UTF8STRING; void ASN1_STRING_set_default_mask(unsigned long mask) { global_mask = mask; } unsigned long ASN1_STRING_get_default_mask(void) { return global_mask; } /*- * This function sets the default to various "flavours" of configuration. * based on an ASCII string. Currently this is: * MASK:XXXX : a numerical mask value. * nobmp : Don't use BMPStrings (just Printable, T61). * pkix : PKIX recommendation in RFC2459. * utf8only : only use UTF8Strings (RFC2459 recommendation for 2004). * default: the default value, Printable, T61, BMP. */ int ASN1_STRING_set_default_mask_asc(const char *p) { unsigned long mask; char *end; if (strncmp(p, "MASK:", 5) == 0) { if (p[5] == '\0') return 0; mask = strtoul(p + 5, &end, 0); if (*end) return 0; } else if (strcmp(p, "nombstr") == 0) mask = ~((unsigned long)(B_ASN1_BMPSTRING | B_ASN1_UTF8STRING)); else if (strcmp(p, "pkix") == 0) mask = ~((unsigned long)B_ASN1_T61STRING); else if (strcmp(p, "utf8only") == 0) mask = B_ASN1_UTF8STRING; else if (strcmp(p, "default") == 0) mask = 0xFFFFFFFFL; else return 0; ASN1_STRING_set_default_mask(mask); return 1; } /* * The following function generates an ASN1_STRING based on limits in a * table. Frequently the types and length of an ASN1_STRING are restricted by * a corresponding OID. For example certificates and certificate requests. */ ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out, const unsigned char *in, int inlen, int inform, int nid) { ASN1_STRING_TABLE *tbl; ASN1_STRING *str = NULL; unsigned long mask; int ret; if (out == NULL) out = &str; tbl = ASN1_STRING_TABLE_get(nid); if (tbl != NULL) { mask = tbl->mask; if (!(tbl->flags & STABLE_NO_MASK)) mask &= global_mask; ret = ASN1_mbstring_ncopy(out, in, inlen, inform, mask, tbl->minsize, tbl->maxsize); } else { ret = ASN1_mbstring_copy(out, in, inlen, inform, DIRSTRING_TYPE & global_mask); } if (ret <= 0) return NULL; return *out; } /* * Now the tables and helper functions for the string table: */ #include "tbl_standard.h" static int sk_table_cmp(const ASN1_STRING_TABLE *const *a, const ASN1_STRING_TABLE *const *b) { return (*a)->nid - (*b)->nid; } DECLARE_OBJ_BSEARCH_CMP_FN(ASN1_STRING_TABLE, ASN1_STRING_TABLE, table); static int table_cmp(const ASN1_STRING_TABLE *a, const ASN1_STRING_TABLE *b) { return a->nid - b->nid; } IMPLEMENT_OBJ_BSEARCH_CMP_FN(ASN1_STRING_TABLE, ASN1_STRING_TABLE, table); ASN1_STRING_TABLE *ASN1_STRING_TABLE_get(int nid) { int idx; ASN1_STRING_TABLE fnd; +#ifndef OPENSSL_NO_AUTOLOAD_CONFIG /* "stable" can be impacted by config, so load the config file first */ OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL); +#endif fnd.nid = nid; if (stable) { idx = sk_ASN1_STRING_TABLE_find(stable, &fnd); if (idx >= 0) return sk_ASN1_STRING_TABLE_value(stable, idx); } return OBJ_bsearch_table(&fnd, tbl_standard, OSSL_NELEM(tbl_standard)); } /* * Return a string table pointer which can be modified: either directly from * table or a copy of an internal value added to the table. */ static ASN1_STRING_TABLE *stable_get(int nid) { ASN1_STRING_TABLE *tmp, *rv; /* Always need a string table so allocate one if NULL */ if (stable == NULL) { stable = sk_ASN1_STRING_TABLE_new(sk_table_cmp); if (stable == NULL) return NULL; } tmp = ASN1_STRING_TABLE_get(nid); if (tmp != NULL && tmp->flags & STABLE_FLAGS_MALLOC) return tmp; if ((rv = OPENSSL_zalloc(sizeof(*rv))) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE); return NULL; } if (!sk_ASN1_STRING_TABLE_push(stable, rv)) { OPENSSL_free(rv); return NULL; } if (tmp != NULL) { rv->nid = tmp->nid; rv->minsize = tmp->minsize; rv->maxsize = tmp->maxsize; rv->mask = tmp->mask; rv->flags = tmp->flags | STABLE_FLAGS_MALLOC; } else { rv->nid = nid; rv->minsize = -1; rv->maxsize = -1; rv->flags = STABLE_FLAGS_MALLOC; } return rv; } int ASN1_STRING_TABLE_add(int nid, long minsize, long maxsize, unsigned long mask, unsigned long flags) { ASN1_STRING_TABLE *tmp; tmp = stable_get(nid); if (tmp == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE); return 0; } if (minsize >= 0) tmp->minsize = minsize; if (maxsize >= 0) tmp->maxsize = maxsize; if (mask) tmp->mask = mask; if (flags) tmp->flags = STABLE_FLAGS_MALLOC | flags; return 1; } void ASN1_STRING_TABLE_cleanup(void) { STACK_OF(ASN1_STRING_TABLE) *tmp; tmp = stable; if (tmp == NULL) return; stable = NULL; sk_ASN1_STRING_TABLE_pop_free(tmp, st_free); } static void st_free(ASN1_STRING_TABLE *tbl) { if (tbl->flags & STABLE_FLAGS_MALLOC) OPENSSL_free(tbl); } diff --git a/crypto/asn1/asn1_gen.c b/crypto/asn1/asn1_gen.c index 64620a4f28a7..402ab34e6a46 100644 --- a/crypto/asn1/asn1_gen.c +++ b/crypto/asn1/asn1_gen.c @@ -1,786 +1,789 @@ /* - * Copyright 2002-2022 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2002-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/cryptlib.h" #include #include #define ASN1_GEN_FLAG 0x10000 #define ASN1_GEN_FLAG_IMP (ASN1_GEN_FLAG|1) #define ASN1_GEN_FLAG_EXP (ASN1_GEN_FLAG|2) #define ASN1_GEN_FLAG_TAG (ASN1_GEN_FLAG|3) #define ASN1_GEN_FLAG_BITWRAP (ASN1_GEN_FLAG|4) #define ASN1_GEN_FLAG_OCTWRAP (ASN1_GEN_FLAG|5) #define ASN1_GEN_FLAG_SEQWRAP (ASN1_GEN_FLAG|6) #define ASN1_GEN_FLAG_SETWRAP (ASN1_GEN_FLAG|7) #define ASN1_GEN_FLAG_FORMAT (ASN1_GEN_FLAG|8) #define ASN1_GEN_STR(str,val) {str, sizeof(str) - 1, val} #define ASN1_FLAG_EXP_MAX 20 /* Maximum number of nested sequences */ #define ASN1_GEN_SEQ_MAX_DEPTH 50 /* Input formats */ /* ASCII: default */ #define ASN1_GEN_FORMAT_ASCII 1 /* UTF8 */ #define ASN1_GEN_FORMAT_UTF8 2 /* Hex */ #define ASN1_GEN_FORMAT_HEX 3 /* List of bits */ #define ASN1_GEN_FORMAT_BITLIST 4 struct tag_name_st { const char *strnam; int len; int tag; }; typedef struct { int exp_tag; int exp_class; int exp_constructed; int exp_pad; long exp_len; } tag_exp_type; typedef struct { int imp_tag; int imp_class; int utype; int format; const char *str; tag_exp_type exp_list[ASN1_FLAG_EXP_MAX]; int exp_count; } tag_exp_arg; static ASN1_TYPE *generate_v3(const char *str, X509V3_CTX *cnf, int depth, int *perr); static int bitstr_cb(const char *elem, int len, void *bitstr); static int asn1_cb(const char *elem, int len, void *bitstr); static int append_exp(tag_exp_arg *arg, int exp_tag, int exp_class, int exp_constructed, int exp_pad, int imp_ok); static int parse_tagging(const char *vstart, int vlen, int *ptag, int *pclass); static ASN1_TYPE *asn1_multi(int utype, const char *section, X509V3_CTX *cnf, int depth, int *perr); static ASN1_TYPE *asn1_str2type(const char *str, int format, int utype); static int asn1_str2tag(const char *tagstr, int len); ASN1_TYPE *ASN1_generate_nconf(const char *str, CONF *nconf) { X509V3_CTX cnf; if (!nconf) return ASN1_generate_v3(str, NULL); X509V3_set_nconf(&cnf, nconf); return ASN1_generate_v3(str, &cnf); } ASN1_TYPE *ASN1_generate_v3(const char *str, X509V3_CTX *cnf) { int err = 0; ASN1_TYPE *ret = generate_v3(str, cnf, 0, &err); if (err) ERR_raise(ERR_LIB_ASN1, err); return ret; } static ASN1_TYPE *generate_v3(const char *str, X509V3_CTX *cnf, int depth, int *perr) { ASN1_TYPE *ret; tag_exp_arg asn1_tags; tag_exp_type *etmp; int i, len; unsigned char *orig_der = NULL, *new_der = NULL; const unsigned char *cpy_start; unsigned char *p; const unsigned char *cp; int cpy_len; long hdr_len = 0; int hdr_constructed = 0, hdr_tag, hdr_class; int r; asn1_tags.imp_tag = -1; asn1_tags.imp_class = -1; asn1_tags.format = ASN1_GEN_FORMAT_ASCII; asn1_tags.exp_count = 0; if (CONF_parse_list(str, ',', 1, asn1_cb, &asn1_tags) != 0) { *perr = ASN1_R_UNKNOWN_TAG; return NULL; } if ((asn1_tags.utype == V_ASN1_SEQUENCE) || (asn1_tags.utype == V_ASN1_SET)) { if (!cnf) { *perr = ASN1_R_SEQUENCE_OR_SET_NEEDS_CONFIG; return NULL; } if (depth >= ASN1_GEN_SEQ_MAX_DEPTH) { *perr = ASN1_R_ILLEGAL_NESTED_TAGGING; return NULL; } ret = asn1_multi(asn1_tags.utype, asn1_tags.str, cnf, depth, perr); } else ret = asn1_str2type(asn1_tags.str, asn1_tags.format, asn1_tags.utype); if (!ret) return NULL; /* If no tagging return base type */ if ((asn1_tags.imp_tag == -1) && (asn1_tags.exp_count == 0)) return ret; /* Generate the encoding */ cpy_len = i2d_ASN1_TYPE(ret, &orig_der); ASN1_TYPE_free(ret); ret = NULL; /* Set point to start copying for modified encoding */ cpy_start = orig_der; /* Do we need IMPLICIT tagging? */ if (asn1_tags.imp_tag != -1) { /* If IMPLICIT we will replace the underlying tag */ /* Skip existing tag+len */ r = ASN1_get_object(&cpy_start, &hdr_len, &hdr_tag, &hdr_class, cpy_len); if (r & 0x80) goto err; /* Update copy length */ cpy_len -= cpy_start - orig_der; /* * For IMPLICIT tagging the length should match the original length * and constructed flag should be consistent. */ if (r & 0x1) { /* Indefinite length constructed */ hdr_constructed = 2; hdr_len = 0; } else /* Just retain constructed flag */ hdr_constructed = r & V_ASN1_CONSTRUCTED; /* * Work out new length with IMPLICIT tag: ignore constructed because * it will mess up if indefinite length */ len = ASN1_object_size(0, hdr_len, asn1_tags.imp_tag); } else len = cpy_len; /* Work out length in any EXPLICIT, starting from end */ for (i = 0, etmp = asn1_tags.exp_list + asn1_tags.exp_count - 1; i < asn1_tags.exp_count; i++, etmp--) { /* Content length: number of content octets + any padding */ len += etmp->exp_pad; etmp->exp_len = len; /* Total object length: length including new header */ len = ASN1_object_size(0, len, etmp->exp_tag); } /* Allocate buffer for new encoding */ new_der = OPENSSL_malloc(len); if (new_der == NULL) goto err; /* Generate tagged encoding */ p = new_der; /* Output explicit tags first */ for (i = 0, etmp = asn1_tags.exp_list; i < asn1_tags.exp_count; i++, etmp++) { ASN1_put_object(&p, etmp->exp_constructed, etmp->exp_len, etmp->exp_tag, etmp->exp_class); if (etmp->exp_pad) *p++ = 0; } /* If IMPLICIT, output tag */ if (asn1_tags.imp_tag != -1) { if (asn1_tags.imp_class == V_ASN1_UNIVERSAL && (asn1_tags.imp_tag == V_ASN1_SEQUENCE || asn1_tags.imp_tag == V_ASN1_SET)) hdr_constructed = V_ASN1_CONSTRUCTED; ASN1_put_object(&p, hdr_constructed, hdr_len, asn1_tags.imp_tag, asn1_tags.imp_class); } /* Copy across original encoding */ memcpy(p, cpy_start, cpy_len); cp = new_der; /* Obtain new ASN1_TYPE structure */ ret = d2i_ASN1_TYPE(NULL, &cp, len); err: OPENSSL_free(orig_der); OPENSSL_free(new_der); return ret; } static int asn1_cb(const char *elem, int len, void *bitstr) { tag_exp_arg *arg = bitstr; int i; int utype; int vlen = 0; const char *p, *vstart = NULL; int tmp_tag, tmp_class; if (elem == NULL) return -1; for (i = 0, p = elem; i < len; p++, i++) { /* Look for the ':' in name value pairs */ if (*p == ':') { vstart = p + 1; vlen = len - (vstart - elem); len = p - elem; break; } } utype = asn1_str2tag(elem, len); if (utype == -1) { ERR_raise_data(ERR_LIB_ASN1, ASN1_R_UNKNOWN_TAG, "tag=%s", elem); return -1; } /* If this is not a modifier mark end of string and exit */ if (!(utype & ASN1_GEN_FLAG)) { arg->utype = utype; arg->str = vstart; /* If no value and not end of string, error */ if (!vstart && elem[len]) { ERR_raise(ERR_LIB_ASN1, ASN1_R_MISSING_VALUE); return -1; } return 0; } switch (utype) { case ASN1_GEN_FLAG_IMP: /* Check for illegal multiple IMPLICIT tagging */ if (arg->imp_tag != -1) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_NESTED_TAGGING); return -1; } if (!parse_tagging(vstart, vlen, &arg->imp_tag, &arg->imp_class)) return -1; break; case ASN1_GEN_FLAG_EXP: if (!parse_tagging(vstart, vlen, &tmp_tag, &tmp_class)) return -1; if (!append_exp(arg, tmp_tag, tmp_class, 1, 0, 0)) return -1; break; case ASN1_GEN_FLAG_SEQWRAP: if (!append_exp(arg, V_ASN1_SEQUENCE, V_ASN1_UNIVERSAL, 1, 0, 1)) return -1; break; case ASN1_GEN_FLAG_SETWRAP: if (!append_exp(arg, V_ASN1_SET, V_ASN1_UNIVERSAL, 1, 0, 1)) return -1; break; case ASN1_GEN_FLAG_BITWRAP: if (!append_exp(arg, V_ASN1_BIT_STRING, V_ASN1_UNIVERSAL, 0, 1, 1)) return -1; break; case ASN1_GEN_FLAG_OCTWRAP: if (!append_exp(arg, V_ASN1_OCTET_STRING, V_ASN1_UNIVERSAL, 0, 0, 1)) return -1; break; case ASN1_GEN_FLAG_FORMAT: if (!vstart) { ERR_raise(ERR_LIB_ASN1, ASN1_R_UNKNOWN_FORMAT); return -1; } if (strncmp(vstart, "ASCII", 5) == 0) arg->format = ASN1_GEN_FORMAT_ASCII; else if (strncmp(vstart, "UTF8", 4) == 0) arg->format = ASN1_GEN_FORMAT_UTF8; else if (strncmp(vstart, "HEX", 3) == 0) arg->format = ASN1_GEN_FORMAT_HEX; else if (strncmp(vstart, "BITLIST", 7) == 0) arg->format = ASN1_GEN_FORMAT_BITLIST; else { ERR_raise(ERR_LIB_ASN1, ASN1_R_UNKNOWN_FORMAT); return -1; } break; } return 1; } static int parse_tagging(const char *vstart, int vlen, int *ptag, int *pclass) { long tag_num; char *eptr; if (!vstart) return 0; tag_num = strtoul(vstart, &eptr, 10); /* Check we haven't gone past max length: should be impossible */ if (eptr && *eptr && (eptr > vstart + vlen)) return 0; if (tag_num < 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_NUMBER); return 0; } *ptag = tag_num; /* If we have non numeric characters, parse them */ if (eptr) vlen -= eptr - vstart; else vlen = 0; if (vlen) { switch (*eptr) { case 'U': *pclass = V_ASN1_UNIVERSAL; break; case 'A': *pclass = V_ASN1_APPLICATION; break; case 'P': *pclass = V_ASN1_PRIVATE; break; case 'C': *pclass = V_ASN1_CONTEXT_SPECIFIC; break; default: ERR_raise_data(ERR_LIB_ASN1, ASN1_R_INVALID_MODIFIER, "Char=%c", *eptr); return 0; } } else *pclass = V_ASN1_CONTEXT_SPECIFIC; return 1; } /* Handle multiple types: SET and SEQUENCE */ static ASN1_TYPE *asn1_multi(int utype, const char *section, X509V3_CTX *cnf, int depth, int *perr) { ASN1_TYPE *ret = NULL; STACK_OF(ASN1_TYPE) *sk = NULL; STACK_OF(CONF_VALUE) *sect = NULL; unsigned char *der = NULL; int derlen; int i; sk = sk_ASN1_TYPE_new_null(); if (!sk) goto bad; if (section) { if (!cnf) goto bad; sect = X509V3_get_section(cnf, (char *)section); if (!sect) goto bad; for (i = 0; i < sk_CONF_VALUE_num(sect); i++) { ASN1_TYPE *typ = generate_v3(sk_CONF_VALUE_value(sect, i)->value, cnf, depth + 1, perr); if (!typ) goto bad; if (!sk_ASN1_TYPE_push(sk, typ)) goto bad; } } /* * Now we has a STACK of the components, convert to the correct form */ if (utype == V_ASN1_SET) derlen = i2d_ASN1_SET_ANY(sk, &der); else derlen = i2d_ASN1_SEQUENCE_ANY(sk, &der); if (derlen < 0) goto bad; if ((ret = ASN1_TYPE_new()) == NULL) goto bad; if ((ret->value.asn1_string = ASN1_STRING_type_new(utype)) == NULL) goto bad; ret->type = utype; ret->value.asn1_string->data = der; ret->value.asn1_string->length = derlen; der = NULL; bad: OPENSSL_free(der); sk_ASN1_TYPE_pop_free(sk, ASN1_TYPE_free); X509V3_section_free(cnf, sect); return ret; } static int append_exp(tag_exp_arg *arg, int exp_tag, int exp_class, int exp_constructed, int exp_pad, int imp_ok) { tag_exp_type *exp_tmp; /* Can only have IMPLICIT if permitted */ if ((arg->imp_tag != -1) && !imp_ok) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_IMPLICIT_TAG); return 0; } if (arg->exp_count == ASN1_FLAG_EXP_MAX) { ERR_raise(ERR_LIB_ASN1, ASN1_R_DEPTH_EXCEEDED); return 0; } exp_tmp = &arg->exp_list[arg->exp_count++]; /* * If IMPLICIT set tag to implicit value then reset implicit tag since it * has been used. */ if (arg->imp_tag != -1) { exp_tmp->exp_tag = arg->imp_tag; exp_tmp->exp_class = arg->imp_class; arg->imp_tag = -1; arg->imp_class = -1; } else { exp_tmp->exp_tag = exp_tag; exp_tmp->exp_class = exp_class; } exp_tmp->exp_constructed = exp_constructed; exp_tmp->exp_pad = exp_pad; return 1; } static int asn1_str2tag(const char *tagstr, int len) { unsigned int i; static const struct tag_name_st *tntmp, tnst[] = { ASN1_GEN_STR("BOOL", V_ASN1_BOOLEAN), ASN1_GEN_STR("BOOLEAN", V_ASN1_BOOLEAN), ASN1_GEN_STR("NULL", V_ASN1_NULL), ASN1_GEN_STR("INT", V_ASN1_INTEGER), ASN1_GEN_STR("INTEGER", V_ASN1_INTEGER), ASN1_GEN_STR("ENUM", V_ASN1_ENUMERATED), ASN1_GEN_STR("ENUMERATED", V_ASN1_ENUMERATED), ASN1_GEN_STR("OID", V_ASN1_OBJECT), ASN1_GEN_STR("OBJECT", V_ASN1_OBJECT), ASN1_GEN_STR("UTCTIME", V_ASN1_UTCTIME), ASN1_GEN_STR("UTC", V_ASN1_UTCTIME), ASN1_GEN_STR("GENERALIZEDTIME", V_ASN1_GENERALIZEDTIME), ASN1_GEN_STR("GENTIME", V_ASN1_GENERALIZEDTIME), ASN1_GEN_STR("OCT", V_ASN1_OCTET_STRING), ASN1_GEN_STR("OCTETSTRING", V_ASN1_OCTET_STRING), ASN1_GEN_STR("BITSTR", V_ASN1_BIT_STRING), ASN1_GEN_STR("BITSTRING", V_ASN1_BIT_STRING), ASN1_GEN_STR("UNIVERSALSTRING", V_ASN1_UNIVERSALSTRING), ASN1_GEN_STR("UNIV", V_ASN1_UNIVERSALSTRING), ASN1_GEN_STR("IA5", V_ASN1_IA5STRING), ASN1_GEN_STR("IA5STRING", V_ASN1_IA5STRING), ASN1_GEN_STR("UTF8", V_ASN1_UTF8STRING), ASN1_GEN_STR("UTF8String", V_ASN1_UTF8STRING), ASN1_GEN_STR("BMP", V_ASN1_BMPSTRING), ASN1_GEN_STR("BMPSTRING", V_ASN1_BMPSTRING), ASN1_GEN_STR("VISIBLESTRING", V_ASN1_VISIBLESTRING), ASN1_GEN_STR("VISIBLE", V_ASN1_VISIBLESTRING), ASN1_GEN_STR("PRINTABLESTRING", V_ASN1_PRINTABLESTRING), ASN1_GEN_STR("PRINTABLE", V_ASN1_PRINTABLESTRING), ASN1_GEN_STR("T61", V_ASN1_T61STRING), ASN1_GEN_STR("T61STRING", V_ASN1_T61STRING), ASN1_GEN_STR("TELETEXSTRING", V_ASN1_T61STRING), ASN1_GEN_STR("GeneralString", V_ASN1_GENERALSTRING), ASN1_GEN_STR("GENSTR", V_ASN1_GENERALSTRING), ASN1_GEN_STR("NUMERIC", V_ASN1_NUMERICSTRING), ASN1_GEN_STR("NUMERICSTRING", V_ASN1_NUMERICSTRING), /* Special cases */ ASN1_GEN_STR("SEQUENCE", V_ASN1_SEQUENCE), ASN1_GEN_STR("SEQ", V_ASN1_SEQUENCE), ASN1_GEN_STR("SET", V_ASN1_SET), /* type modifiers */ /* Explicit tag */ ASN1_GEN_STR("EXP", ASN1_GEN_FLAG_EXP), ASN1_GEN_STR("EXPLICIT", ASN1_GEN_FLAG_EXP), /* Implicit tag */ ASN1_GEN_STR("IMP", ASN1_GEN_FLAG_IMP), ASN1_GEN_STR("IMPLICIT", ASN1_GEN_FLAG_IMP), /* OCTET STRING wrapper */ ASN1_GEN_STR("OCTWRAP", ASN1_GEN_FLAG_OCTWRAP), /* SEQUENCE wrapper */ ASN1_GEN_STR("SEQWRAP", ASN1_GEN_FLAG_SEQWRAP), /* SET wrapper */ ASN1_GEN_STR("SETWRAP", ASN1_GEN_FLAG_SETWRAP), /* BIT STRING wrapper */ ASN1_GEN_STR("BITWRAP", ASN1_GEN_FLAG_BITWRAP), ASN1_GEN_STR("FORM", ASN1_GEN_FLAG_FORMAT), ASN1_GEN_STR("FORMAT", ASN1_GEN_FLAG_FORMAT), }; if (len == -1) len = strlen(tagstr); tntmp = tnst; for (i = 0; i < OSSL_NELEM(tnst); i++, tntmp++) { if ((len == tntmp->len) && (OPENSSL_strncasecmp(tntmp->strnam, tagstr, len) == 0)) return tntmp->tag; } return -1; } static ASN1_TYPE *asn1_str2type(const char *str, int format, int utype) { ASN1_TYPE *atmp = NULL; CONF_VALUE vtmp; unsigned char *rdata; long rdlen; int no_unused = 1; if ((atmp = ASN1_TYPE_new()) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE); return NULL; } if (!str) str = ""; switch (utype) { case V_ASN1_NULL: if (str && *str) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_NULL_VALUE); goto bad_form; } break; case V_ASN1_BOOLEAN: if (format != ASN1_GEN_FORMAT_ASCII) { ERR_raise(ERR_LIB_ASN1, ASN1_R_NOT_ASCII_FORMAT); goto bad_form; } vtmp.name = NULL; vtmp.section = NULL; vtmp.value = (char *)str; if (!X509V3_get_value_bool(&vtmp, &atmp->value.boolean)) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_BOOLEAN); goto bad_str; } break; case V_ASN1_INTEGER: case V_ASN1_ENUMERATED: if (format != ASN1_GEN_FORMAT_ASCII) { ERR_raise(ERR_LIB_ASN1, ASN1_R_INTEGER_NOT_ASCII_FORMAT); goto bad_form; } if ((atmp->value.integer = s2i_ASN1_INTEGER(NULL, str)) == NULL) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_INTEGER); goto bad_str; } break; case V_ASN1_OBJECT: if (format != ASN1_GEN_FORMAT_ASCII) { ERR_raise(ERR_LIB_ASN1, ASN1_R_OBJECT_NOT_ASCII_FORMAT); goto bad_form; } if ((atmp->value.object = OBJ_txt2obj(str, 0)) == NULL) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_OBJECT); goto bad_str; } break; case V_ASN1_UTCTIME: case V_ASN1_GENERALIZEDTIME: if (format != ASN1_GEN_FORMAT_ASCII) { ERR_raise(ERR_LIB_ASN1, ASN1_R_TIME_NOT_ASCII_FORMAT); goto bad_form; } if ((atmp->value.asn1_string = ASN1_STRING_new()) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE); goto bad_str; } if (!ASN1_STRING_set(atmp->value.asn1_string, str, -1)) { ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE); goto bad_str; } atmp->value.asn1_string->type = utype; if (!ASN1_TIME_check(atmp->value.asn1_string)) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_TIME_VALUE); goto bad_str; } break; case V_ASN1_BMPSTRING: case V_ASN1_PRINTABLESTRING: case V_ASN1_IA5STRING: case V_ASN1_T61STRING: case V_ASN1_UTF8STRING: case V_ASN1_VISIBLESTRING: case V_ASN1_UNIVERSALSTRING: case V_ASN1_GENERALSTRING: case V_ASN1_NUMERICSTRING: if (format == ASN1_GEN_FORMAT_ASCII) format = MBSTRING_ASC; else if (format == ASN1_GEN_FORMAT_UTF8) format = MBSTRING_UTF8; else { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_FORMAT); goto bad_form; } if (ASN1_mbstring_copy(&atmp->value.asn1_string, (unsigned char *)str, -1, format, ASN1_tag2bit(utype)) <= 0) { ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE); goto bad_str; } break; case V_ASN1_BIT_STRING: case V_ASN1_OCTET_STRING: if ((atmp->value.asn1_string = ASN1_STRING_new()) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE); goto bad_form; } if (format == ASN1_GEN_FORMAT_HEX) { if ((rdata = OPENSSL_hexstr2buf(str, &rdlen)) == NULL) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_HEX); goto bad_str; } atmp->value.asn1_string->data = rdata; atmp->value.asn1_string->length = rdlen; atmp->value.asn1_string->type = utype; - } else if (format == ASN1_GEN_FORMAT_ASCII) - ASN1_STRING_set(atmp->value.asn1_string, str, -1); - else if ((format == ASN1_GEN_FORMAT_BITLIST) + } else if (format == ASN1_GEN_FORMAT_ASCII) { + if (!ASN1_STRING_set(atmp->value.asn1_string, str, -1)) { + ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE); + goto bad_str; + } + } else if ((format == ASN1_GEN_FORMAT_BITLIST) && (utype == V_ASN1_BIT_STRING)) { if (!CONF_parse_list (str, ',', 1, bitstr_cb, atmp->value.bit_string)) { ERR_raise(ERR_LIB_ASN1, ASN1_R_LIST_ERROR); goto bad_str; } no_unused = 0; } else { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_BITSTRING_FORMAT); goto bad_form; } if ((utype == V_ASN1_BIT_STRING) && no_unused) { atmp->value.asn1_string->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07); atmp->value.asn1_string->flags |= ASN1_STRING_FLAG_BITS_LEFT; } break; default: ERR_raise(ERR_LIB_ASN1, ASN1_R_UNSUPPORTED_TYPE); goto bad_str; } atmp->type = utype; return atmp; bad_str: ERR_add_error_data(2, "string=", str); bad_form: ASN1_TYPE_free(atmp); return NULL; } static int bitstr_cb(const char *elem, int len, void *bitstr) { long bitnum; char *eptr; if (!elem) return 0; bitnum = strtoul(elem, &eptr, 10); if (eptr && *eptr && (eptr != elem + len)) return 0; if (bitnum < 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_NUMBER); return 0; } if (!ASN1_BIT_STRING_set_bit(bitstr, bitnum, 1)) { ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE); return 0; } return 1; } static int mask_cb(const char *elem, int len, void *arg) { unsigned long *pmask = arg, tmpmask; int tag; if (elem == NULL) return 0; if ((len == 3) && (strncmp(elem, "DIR", 3) == 0)) { *pmask |= B_ASN1_DIRECTORYSTRING; return 1; } tag = asn1_str2tag(elem, len); if (!tag || (tag & ASN1_GEN_FLAG)) return 0; tmpmask = ASN1_tag2bit(tag); if (!tmpmask) return 0; *pmask |= tmpmask; return 1; } int ASN1_str2mask(const char *str, unsigned long *pmask) { *pmask = 0; return CONF_parse_list(str, '|', 1, mask_cb, pmask); } diff --git a/crypto/chacha/asm/chacha-ia64.pl b/crypto/chacha/asm/chacha-ia64.pl index b13d97285575..78201649d550 100644 --- a/crypto/chacha/asm/chacha-ia64.pl +++ b/crypto/chacha/asm/chacha-ia64.pl @@ -1,291 +1,293 @@ #!/usr/bin/env perl # # ==================================================================== # Written by Andy Polyakov, @dot-asm, initially for use with OpenSSL. # ==================================================================== # # ChaCha20 for Itanium. # # March 2019 # # Itanium 9xxx, which has pair of shifters, manages to process one byte # in 9.3 cycles. This aligns perfectly with theoretical estimate. # On the other hand, pre-9000 CPU has single shifter and each extr/dep # pairs below takes additional cycle. Then final input->xor->output # pass runs slower than expected... Overall result is 15.6 cpb, two # cycles more than theoretical estimate. $output = pop and open STDOUT, ">$output"; my @k = map("r$_",(16..31)); my @x = map("r$_",(38..53)); my @y = map("r$_",(8..11)); my @z = map("r$_",(15,35..37)); my ($out,$inp,$len,$key,$counter) = map("r$_",(32..36)); $code.=<<___; #if defined(_HPUX_SOURCE) # if !defined(_LP64) # define ADDP addp4 # else # define ADDP add # endif #else # define ADDP add #endif .text .global ChaCha20_ctr32# .proc ChaCha20_ctr32# .align 32 ChaCha20_ctr32: .prologue .save ar.pfs,r2 { .mmi; alloc r2=ar.pfs,5,17,0,0 ADDP @k[11]=4,$key .save ar.lc,r3 mov r3=ar.lc } +{ .mmi; ADDP $out=0,$out + ADDP $inp=0,$inp } { .mmi; ADDP $key=0,$key ADDP $counter=0,$counter .save pr,r14 mov r14=pr };; .body { .mlx; ld4 @k[4]=[$key],8 movl @k[0]=0x61707865 } { .mlx; ld4 @k[5]=[@k[11]],8 movl @k[1]=0x3320646e };; { .mlx; ld4 @k[6]=[$key],8 movl @k[2]=0x79622d32 } { .mlx; ld4 @k[7]=[@k[11]],8 movl @k[3]=0x6b206574 };; { .mmi; ld4 @k[8]=[$key],8 ld4 @k[9]=[@k[11]],8 add @k[15]=4,$counter };; { .mmi; ld4 @k[10]=[$key] ld4 @k[11]=[@k[11]] mov @x[0]=@k[0] };; { .mmi; ld4 @k[12]=[$counter],8 ld4 @k[13]=[@k[15]],8 mov @x[1]=@k[1] };; { .mmi; ld4 @k[14]=[$counter] ld4 @k[15]=[@k[15]] mov @x[2]=@k[2] } { .mmi; mov @x[3]=@k[3] mov @x[4]=@k[4] mov @x[5]=@k[5] };; { .mmi; mov @x[6]=@k[6] mov @x[7]=@k[7] mov @x[8]=@k[8] } { .mmi; mov @x[9]=@k[9] mov @x[10]=@k[10] mov @x[11]=@k[11] } { .mmi; mov @x[12]=@k[12] mov @x[13]=@k[13] mov @x[14]=@k[14] };; .Loop_outer: { .mii; mov @x[15]=@k[15] mov ar.lc=9 mov ar.ec=1 } { .mmb; cmp.geu p6,p0=64,$len sub @z[1]=64,$len brp.loop.imp .Loop_top,.Loop_end-16 };; .Loop_top: ___ sub ROUND { my ($a0,$b0,$c0,$d0)=@_; my ($a1,$b1,$c1,$d1)=map(($_&~3)+(($_+1)&3),($a0,$b0,$c0,$d0)); my ($a2,$b2,$c2,$d2)=map(($_&~3)+(($_+1)&3),($a1,$b1,$c1,$d1)); my ($a3,$b3,$c3,$d3)=map(($_&~3)+(($_+1)&3),($a2,$b2,$c2,$d2)); $code.=<<___; { .mmi; add @x[$a0]=@x[$a0],@x[$b0] add @x[$a1]=@x[$a1],@x[$b1] add @x[$a2]=@x[$a2],@x[$b2] };; { .mmi; add @x[$a3]=@x[$a3],@x[$b3] xor @x[$d0]=@x[$d0],@x[$a0] xor @x[$d1]=@x[$d1],@x[$a1] };; { .mmi; xor @x[$d2]=@x[$d2],@x[$a2] xor @x[$d3]=@x[$d3],@x[$a3] extr.u @y[0]=@x[$d0],16,16 };; { .mii; extr.u @y[1]=@x[$d1],16,16 dep @x[$d0]=@x[$d0],@y[0],16,16 };; { .mii; add @x[$c0]=@x[$c0],@x[$d0] extr.u @y[2]=@x[$d2],16,16 dep @x[$d1]=@x[$d1],@y[1],16,16 };; { .mii; add @x[$c1]=@x[$c1],@x[$d1] xor @x[$b0]=@x[$b0],@x[$c0] extr.u @y[3]=@x[$d3],16,16 };; { .mii; xor @x[$b1]=@x[$b1],@x[$c1] dep @x[$d2]=@x[$d2],@y[2],16,16 dep @x[$d3]=@x[$d3],@y[3],16,16 };; { .mmi; add @x[$c2]=@x[$c2],@x[$d2] add @x[$c3]=@x[$c3],@x[$d3] extr.u @y[0]=@x[$b0],20,12 };; { .mmi; xor @x[$b2]=@x[$b2],@x[$c2] xor @x[$b3]=@x[$b3],@x[$c3] dep.z @x[$b0]=@x[$b0],12,20 };; { .mii; or @x[$b0]=@x[$b0],@y[0] extr.u @y[1]=@x[$b1],20,12 dep.z @x[$b1]=@x[$b1],12,20 };; { .mii; add @x[$a0]=@x[$a0],@x[$b0] extr.u @y[2]=@x[$b2],20,12 extr.u @y[3]=@x[$b3],20,12 } { .mii; or @x[$b1]=@x[$b1],@y[1] dep.z @x[$b2]=@x[$b2],12,20 dep.z @x[$b3]=@x[$b3],12,20 };; { .mmi; or @x[$b2]=@x[$b2],@y[2] or @x[$b3]=@x[$b3],@y[3] add @x[$a1]=@x[$a1],@x[$b1] };; { .mmi; add @x[$a2]=@x[$a2],@x[$b2] add @x[$a3]=@x[$a3],@x[$b3] xor @x[$d0]=@x[$d0],@x[$a0] };; { .mii; xor @x[$d1]=@x[$d1],@x[$a1] extr.u @y[0]=@x[$d0],24,8 dep.z @x[$d0]=@x[$d0],8,24 };; { .mii; or @x[$d0]=@x[$d0],@y[0] extr.u @y[1]=@x[$d1],24,8 dep.z @x[$d1]=@x[$d1],8,24 };; { .mmi; or @x[$d1]=@x[$d1],@y[1] xor @x[$d2]=@x[$d2],@x[$a2] xor @x[$d3]=@x[$d3],@x[$a3] };; { .mii; add @x[$c0]=@x[$c0],@x[$d0] extr.u @y[2]=@x[$d2],24,8 dep.z @x[$d2]=@x[$d2],8,24 };; { .mii; xor @x[$b0]=@x[$b0],@x[$c0] extr.u @y[3]=@x[$d3],24,8 dep.z @x[$d3]=@x[$d3],8,24 };; { .mmi; or @x[$d2]=@x[$d2],@y[2] or @x[$d3]=@x[$d3],@y[3] extr.u @y[0]=@x[$b0],25,7 };; { .mmi; add @x[$c1]=@x[$c1],@x[$d1] add @x[$c2]=@x[$c2],@x[$d2] dep.z @x[$b0]=@x[$b0],7,25 };; { .mmi; xor @x[$b1]=@x[$b1],@x[$c1] xor @x[$b2]=@x[$b2],@x[$c2] add @x[$c3]=@x[$c3],@x[$d3] };; { .mii; xor @x[$b3]=@x[$b3],@x[$c3] extr.u @y[1]=@x[$b1],25,7 dep.z @x[$b1]=@x[$b1],7,25 };; { .mii; or @x[$b0]=@x[$b0],@y[0] extr.u @y[2]=@x[$b2],25,7 dep.z @x[$b2]=@x[$b2],7,25 };; { .mii; or @x[$b1]=@x[$b1],@y[1] extr.u @y[3]=@x[$b3],25,7 dep.z @x[$b3]=@x[$b3],7,25 };; ___ $code.=<<___ if ($d0 == 12); { .mmi; or @x[$b2]=@x[$b2],@y[2] or @x[$b3]=@x[$b3],@y[3] mov @z[0]=-1 };; ___ $code.=<<___ if ($d0 == 15); { .mmb; or @x[$b2]=@x[$b2],@y[2] or @x[$b3]=@x[$b3],@y[3] br.ctop.sptk .Loop_top };; ___ } &ROUND(0, 4, 8, 12); &ROUND(0, 5, 10, 15); $code.=<<___; .Loop_end: { .mmi; add @x[0]=@x[0],@k[0] add @x[1]=@x[1],@k[1] (p6) shr.u @z[0]=@z[0],@z[1] } { .mmb; add @x[2]=@x[2],@k[2] add @x[3]=@x[3],@k[3] clrrrb.pr };; { .mmi; add @x[4]=@x[4],@k[4] add @x[5]=@x[5],@k[5] add @x[6]=@x[6],@k[6] } { .mmi; add @x[7]=@x[7],@k[7] add @x[8]=@x[8],@k[8] add @x[9]=@x[9],@k[9] } { .mmi; add @x[10]=@x[10],@k[10] add @x[11]=@x[11],@k[11] add @x[12]=@x[12],@k[12] } { .mmi; add @x[13]=@x[13],@k[13] add @x[14]=@x[14],@k[14] add @x[15]=@x[15],@k[15] } { .mmi; add @k[12]=1,@k[12] // next counter mov pr=@z[0],0x1ffff };; ////////////////////////////////////////////////////////////////// // Each predicate bit corresponds to byte to be processed. Note // that p0 is wired to 1, but it works out, because there always // is at least one byte to process... { .mmi; (p0) ld1 @z[0]=[$inp],1 shr.u @y[1]=@x[0],8 };; { .mmi; (p1) ld1 @z[1]=[$inp],1 (p2) shr.u @y[2]=@x[0],16 };; { .mmi; (p2) ld1 @z[2]=[$inp],1 (p0) xor @z[0]=@z[0],@x[0] (p3) shr.u @y[3]=@x[0],24 };; ___ for(my $i0=0; $i0<60; $i0+=4) { my ($i1, $i2, $i3, $i4, $i5, $i6, $i7) = map($i0+$_,(1..7)); my $k = $i0/4+1; $code.=<<___; { .mmi; (p$i3) ld1 @z[3]=[$inp],1 (p$i0) st1 [$out]=@z[0],1 (p$i1) xor @z[1]=@z[1],@y[1] };; { .mmi; (p$i4) ld1 @z[0]=[$inp],1 (p$i5) shr.u @y[1]=@x[$k],8 } { .mmi; (p$i1) st1 [$out]=@z[1],1 (p$i2) xor @z[2]=@z[2],@y[2] (p1) mov @x[$k-1]=@k[$k-1] };; { .mfi; (p$i5) ld1 @z[1]=[$inp],1 (p$i6) shr.u @y[2]=@x[$k],16 } { .mfi; (p$i2) st1 [$out]=@z[2],1 (p$i3) xor @z[3]=@z[3],@y[3] };; { .mfi; (p$i6) ld1 @z[2]=[$inp],1 (p$i7) shr.u @y[3]=@x[$k],24 } ___ $code.=<<___ if ($i0==0); # p1,p2 are available for reuse in first round { .mmi; (p$i3) st1 [$out]=@z[3],1 (p$i4) xor @z[0]=@z[0],@x[$k] cmp.ltu p1,p2=64,$len };; ___ $code.=<<___ if ($i0>0); { .mfi; (p$i3) st1 [$out]=@z[3],1 (p$i4) xor @z[0]=@z[0],@x[$k] };; ___ } $code.=<<___; { .mmi; (p63) ld1 @z[3]=[$inp],1 (p60) st1 [$out]=@z[0],1 (p61) xor @z[1]=@z[1],@y[1] };; { .mmi; (p61) st1 [$out]=@z[1],1 (p62) xor @z[2]=@z[2],@y[2] };; { .mmi; (p62) st1 [$out]=@z[2],1 (p63) xor @z[3]=@z[3],@y[3] (p2) mov ar.lc=r3 };; { .mib; (p63) st1 [$out]=@z[3],1 (p1) add $len=-64,$len (p1) br.dptk.many .Loop_outer };; { .mmi; mov @k[4]=0 // wipe key material mov @k[5]=0 mov @k[6]=0 } { .mmi; mov @k[7]=0 mov @k[8]=0 mov @k[9]=0 } { .mmi; mov @k[10]=0 mov @k[11]=0 mov @k[12]=0 } { .mmi; mov @k[13]=0 mov @k[14]=0 mov @k[15]=0 } { .mib; mov pr=r14,0x1ffff br.ret.sptk.many b0 };; .endp ChaCha20_ctr32# stringz "ChaCha20 for IA64, CRYPTOGAMS by \@dot-asm" ___ print $code; close STDOUT or die "error closing STDOUT: $!"; diff --git a/crypto/cmp/cmp_asn.c b/crypto/cmp/cmp_asn.c index 0ca107554c96..a8de73ad979b 100644 --- a/crypto/cmp/cmp_asn.c +++ b/crypto/cmp/cmp_asn.c @@ -1,459 +1,459 @@ /* - * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include #include "cmp_local.h" /* explicit #includes not strictly needed since implied by the above: */ #include #include /* ASN.1 declarations from RFC4210 */ ASN1_SEQUENCE(OSSL_CMP_REVANNCONTENT) = { /* OSSL_CMP_PKISTATUS is effectively ASN1_INTEGER so it is used directly */ ASN1_SIMPLE(OSSL_CMP_REVANNCONTENT, status, ASN1_INTEGER), ASN1_SIMPLE(OSSL_CMP_REVANNCONTENT, certId, OSSL_CRMF_CERTID), ASN1_SIMPLE(OSSL_CMP_REVANNCONTENT, willBeRevokedAt, ASN1_GENERALIZEDTIME), ASN1_SIMPLE(OSSL_CMP_REVANNCONTENT, badSinceDate, ASN1_GENERALIZEDTIME), ASN1_OPT(OSSL_CMP_REVANNCONTENT, crlDetails, X509_EXTENSIONS) } ASN1_SEQUENCE_END(OSSL_CMP_REVANNCONTENT) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_REVANNCONTENT) ASN1_SEQUENCE(OSSL_CMP_CHALLENGE) = { ASN1_OPT(OSSL_CMP_CHALLENGE, owf, X509_ALGOR), ASN1_SIMPLE(OSSL_CMP_CHALLENGE, witness, ASN1_OCTET_STRING), ASN1_SIMPLE(OSSL_CMP_CHALLENGE, challenge, ASN1_OCTET_STRING) } ASN1_SEQUENCE_END(OSSL_CMP_CHALLENGE) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_CHALLENGE) ASN1_ITEM_TEMPLATE(OSSL_CMP_POPODECKEYCHALLCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_POPODECKEYCHALLCONTENT, OSSL_CMP_CHALLENGE) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_POPODECKEYCHALLCONTENT) ASN1_ITEM_TEMPLATE(OSSL_CMP_POPODECKEYRESPCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_POPODECKEYRESPCONTENT, ASN1_INTEGER) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_POPODECKEYRESPCONTENT) ASN1_SEQUENCE(OSSL_CMP_CAKEYUPDANNCONTENT) = { /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ASN1_SIMPLE(OSSL_CMP_CAKEYUPDANNCONTENT, oldWithNew, X509), /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ASN1_SIMPLE(OSSL_CMP_CAKEYUPDANNCONTENT, newWithOld, X509), /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ASN1_SIMPLE(OSSL_CMP_CAKEYUPDANNCONTENT, newWithNew, X509) } ASN1_SEQUENCE_END(OSSL_CMP_CAKEYUPDANNCONTENT) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_CAKEYUPDANNCONTENT) ASN1_SEQUENCE(OSSL_CMP_ERRORMSGCONTENT) = { ASN1_SIMPLE(OSSL_CMP_ERRORMSGCONTENT, pKIStatusInfo, OSSL_CMP_PKISI), ASN1_OPT(OSSL_CMP_ERRORMSGCONTENT, errorCode, ASN1_INTEGER), /* * OSSL_CMP_PKIFREETEXT is effectively a sequence of ASN1_UTF8STRING * so it is used directly * */ ASN1_SEQUENCE_OF_OPT(OSSL_CMP_ERRORMSGCONTENT, errorDetails, ASN1_UTF8STRING) } ASN1_SEQUENCE_END(OSSL_CMP_ERRORMSGCONTENT) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_ERRORMSGCONTENT) ASN1_ADB_TEMPLATE(infotypeandvalue_default) = ASN1_OPT(OSSL_CMP_ITAV, infoValue.other, ASN1_ANY); /* ITAV means InfoTypeAndValue */ ASN1_ADB(OSSL_CMP_ITAV) = { /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ADB_ENTRY(NID_id_it_caProtEncCert, ASN1_OPT(OSSL_CMP_ITAV, infoValue.caProtEncCert, X509)), ADB_ENTRY(NID_id_it_signKeyPairTypes, ASN1_SEQUENCE_OF_OPT(OSSL_CMP_ITAV, infoValue.signKeyPairTypes, X509_ALGOR)), ADB_ENTRY(NID_id_it_encKeyPairTypes, ASN1_SEQUENCE_OF_OPT(OSSL_CMP_ITAV, infoValue.encKeyPairTypes, X509_ALGOR)), ADB_ENTRY(NID_id_it_preferredSymmAlg, ASN1_OPT(OSSL_CMP_ITAV, infoValue.preferredSymmAlg, X509_ALGOR)), ADB_ENTRY(NID_id_it_caKeyUpdateInfo, ASN1_OPT(OSSL_CMP_ITAV, infoValue.caKeyUpdateInfo, OSSL_CMP_CAKEYUPDANNCONTENT)), ADB_ENTRY(NID_id_it_currentCRL, ASN1_OPT(OSSL_CMP_ITAV, infoValue.currentCRL, X509_CRL)), ADB_ENTRY(NID_id_it_unsupportedOIDs, ASN1_SEQUENCE_OF_OPT(OSSL_CMP_ITAV, infoValue.unsupportedOIDs, ASN1_OBJECT)), ADB_ENTRY(NID_id_it_keyPairParamReq, ASN1_OPT(OSSL_CMP_ITAV, infoValue.keyPairParamReq, ASN1_OBJECT)), ADB_ENTRY(NID_id_it_keyPairParamRep, ASN1_OPT(OSSL_CMP_ITAV, infoValue.keyPairParamRep, X509_ALGOR)), ADB_ENTRY(NID_id_it_revPassphrase, ASN1_OPT(OSSL_CMP_ITAV, infoValue.revPassphrase, OSSL_CRMF_ENCRYPTEDVALUE)), ADB_ENTRY(NID_id_it_implicitConfirm, ASN1_OPT(OSSL_CMP_ITAV, infoValue.implicitConfirm, ASN1_NULL)), ADB_ENTRY(NID_id_it_confirmWaitTime, ASN1_OPT(OSSL_CMP_ITAV, infoValue.confirmWaitTime, ASN1_GENERALIZEDTIME)), ADB_ENTRY(NID_id_it_origPKIMessage, ASN1_OPT(OSSL_CMP_ITAV, infoValue.origPKIMessage, OSSL_CMP_MSGS)), ADB_ENTRY(NID_id_it_suppLangTags, ASN1_SEQUENCE_OF_OPT(OSSL_CMP_ITAV, infoValue.suppLangTagsValue, ASN1_UTF8STRING)), } ASN1_ADB_END(OSSL_CMP_ITAV, 0, infoType, 0, &infotypeandvalue_default_tt, NULL); ASN1_SEQUENCE(OSSL_CMP_ITAV) = { ASN1_SIMPLE(OSSL_CMP_ITAV, infoType, ASN1_OBJECT), ASN1_ADB_OBJECT(OSSL_CMP_ITAV) } ASN1_SEQUENCE_END(OSSL_CMP_ITAV) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_ITAV) IMPLEMENT_ASN1_DUP_FUNCTION(OSSL_CMP_ITAV) OSSL_CMP_ITAV *OSSL_CMP_ITAV_create(ASN1_OBJECT *type, ASN1_TYPE *value) { OSSL_CMP_ITAV *itav; if (type == NULL || (itav = OSSL_CMP_ITAV_new()) == NULL) return NULL; OSSL_CMP_ITAV_set0(itav, type, value); return itav; } void OSSL_CMP_ITAV_set0(OSSL_CMP_ITAV *itav, ASN1_OBJECT *type, ASN1_TYPE *value) { itav->infoType = type; itav->infoValue.other = value; } ASN1_OBJECT *OSSL_CMP_ITAV_get0_type(const OSSL_CMP_ITAV *itav) { if (itav == NULL) return NULL; return itav->infoType; } ASN1_TYPE *OSSL_CMP_ITAV_get0_value(const OSSL_CMP_ITAV *itav) { if (itav == NULL) return NULL; return itav->infoValue.other; } int OSSL_CMP_ITAV_push0_stack_item(STACK_OF(OSSL_CMP_ITAV) **itav_sk_p, OSSL_CMP_ITAV *itav) { int created = 0; if (itav_sk_p == NULL || itav == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); goto err; } if (*itav_sk_p == NULL) { if ((*itav_sk_p = sk_OSSL_CMP_ITAV_new_null()) == NULL) goto err; created = 1; } if (!sk_OSSL_CMP_ITAV_push(*itav_sk_p, itav)) goto err; return 1; err: if (created != 0) { sk_OSSL_CMP_ITAV_free(*itav_sk_p); *itav_sk_p = NULL; } return 0; } -/* get ASN.1 encoded integer, return -1 on error */ +/* get ASN.1 encoded integer, return -2 on error; -1 is valid for certReqId */ int ossl_cmp_asn1_get_int(const ASN1_INTEGER *a) { int64_t res; if (!ASN1_INTEGER_get_int64(&res, a)) { ERR_raise(ERR_LIB_CMP, ASN1_R_INVALID_NUMBER); - return -1; + return -2; } if (res < INT_MIN) { ERR_raise(ERR_LIB_CMP, ASN1_R_TOO_SMALL); - return -1; + return -2; } if (res > INT_MAX) { ERR_raise(ERR_LIB_CMP, ASN1_R_TOO_LARGE); - return -1; + return -2; } return (int)res; } static int ossl_cmp_msg_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { OSSL_CMP_MSG *msg = (OSSL_CMP_MSG *)*pval; switch (operation) { case ASN1_OP_FREE_POST: OPENSSL_free(msg->propq); break; case ASN1_OP_DUP_POST: { OSSL_CMP_MSG *old = exarg; if (!ossl_cmp_msg_set0_libctx(msg, old->libctx, old->propq)) return 0; } break; case ASN1_OP_GET0_LIBCTX: { OSSL_LIB_CTX **libctx = exarg; *libctx = msg->libctx; } break; case ASN1_OP_GET0_PROPQ: { const char **propq = exarg; *propq = msg->propq; } break; default: break; } return 1; } ASN1_CHOICE(OSSL_CMP_CERTORENCCERT) = { /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ASN1_EXP(OSSL_CMP_CERTORENCCERT, value.certificate, X509, 0), ASN1_EXP(OSSL_CMP_CERTORENCCERT, value.encryptedCert, OSSL_CRMF_ENCRYPTEDVALUE, 1), } ASN1_CHOICE_END(OSSL_CMP_CERTORENCCERT) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_CERTORENCCERT) ASN1_SEQUENCE(OSSL_CMP_CERTIFIEDKEYPAIR) = { ASN1_SIMPLE(OSSL_CMP_CERTIFIEDKEYPAIR, certOrEncCert, OSSL_CMP_CERTORENCCERT), ASN1_EXP_OPT(OSSL_CMP_CERTIFIEDKEYPAIR, privateKey, OSSL_CRMF_ENCRYPTEDVALUE, 0), ASN1_EXP_OPT(OSSL_CMP_CERTIFIEDKEYPAIR, publicationInfo, OSSL_CRMF_PKIPUBLICATIONINFO, 1) } ASN1_SEQUENCE_END(OSSL_CMP_CERTIFIEDKEYPAIR) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_CERTIFIEDKEYPAIR) ASN1_SEQUENCE(OSSL_CMP_REVDETAILS) = { ASN1_SIMPLE(OSSL_CMP_REVDETAILS, certDetails, OSSL_CRMF_CERTTEMPLATE), ASN1_OPT(OSSL_CMP_REVDETAILS, crlEntryDetails, X509_EXTENSIONS) } ASN1_SEQUENCE_END(OSSL_CMP_REVDETAILS) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_REVDETAILS) ASN1_ITEM_TEMPLATE(OSSL_CMP_REVREQCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_REVREQCONTENT, OSSL_CMP_REVDETAILS) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_REVREQCONTENT) ASN1_SEQUENCE(OSSL_CMP_REVREPCONTENT) = { ASN1_SEQUENCE_OF(OSSL_CMP_REVREPCONTENT, status, OSSL_CMP_PKISI), ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_REVREPCONTENT, revCerts, OSSL_CRMF_CERTID, 0), ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_REVREPCONTENT, crls, X509_CRL, 1) } ASN1_SEQUENCE_END(OSSL_CMP_REVREPCONTENT) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_REVREPCONTENT) ASN1_SEQUENCE(OSSL_CMP_KEYRECREPCONTENT) = { ASN1_SIMPLE(OSSL_CMP_KEYRECREPCONTENT, status, OSSL_CMP_PKISI), ASN1_EXP_OPT(OSSL_CMP_KEYRECREPCONTENT, newSigCert, X509, 0), ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_KEYRECREPCONTENT, caCerts, X509, 1), ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_KEYRECREPCONTENT, keyPairHist, OSSL_CMP_CERTIFIEDKEYPAIR, 2) } ASN1_SEQUENCE_END(OSSL_CMP_KEYRECREPCONTENT) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_KEYRECREPCONTENT) ASN1_ITEM_TEMPLATE(OSSL_CMP_PKISTATUS) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_UNIVERSAL, 0, status, ASN1_INTEGER) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_PKISTATUS) ASN1_SEQUENCE(OSSL_CMP_PKISI) = { ASN1_SIMPLE(OSSL_CMP_PKISI, status, OSSL_CMP_PKISTATUS), /* * CMP_PKIFREETEXT is effectively a sequence of ASN1_UTF8STRING * so it is used directly */ ASN1_SEQUENCE_OF_OPT(OSSL_CMP_PKISI, statusString, ASN1_UTF8STRING), /* * OSSL_CMP_PKIFAILUREINFO is effectively ASN1_BIT_STRING so used directly */ ASN1_OPT(OSSL_CMP_PKISI, failInfo, ASN1_BIT_STRING) } ASN1_SEQUENCE_END(OSSL_CMP_PKISI) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_PKISI) IMPLEMENT_ASN1_DUP_FUNCTION(OSSL_CMP_PKISI) ASN1_SEQUENCE(OSSL_CMP_CERTSTATUS) = { ASN1_SIMPLE(OSSL_CMP_CERTSTATUS, certHash, ASN1_OCTET_STRING), ASN1_SIMPLE(OSSL_CMP_CERTSTATUS, certReqId, ASN1_INTEGER), ASN1_OPT(OSSL_CMP_CERTSTATUS, statusInfo, OSSL_CMP_PKISI) } ASN1_SEQUENCE_END(OSSL_CMP_CERTSTATUS) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_CERTSTATUS) ASN1_ITEM_TEMPLATE(OSSL_CMP_CERTCONFIRMCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_CERTCONFIRMCONTENT, OSSL_CMP_CERTSTATUS) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_CERTCONFIRMCONTENT) ASN1_SEQUENCE(OSSL_CMP_CERTRESPONSE) = { ASN1_SIMPLE(OSSL_CMP_CERTRESPONSE, certReqId, ASN1_INTEGER), ASN1_SIMPLE(OSSL_CMP_CERTRESPONSE, status, OSSL_CMP_PKISI), ASN1_OPT(OSSL_CMP_CERTRESPONSE, certifiedKeyPair, OSSL_CMP_CERTIFIEDKEYPAIR), ASN1_OPT(OSSL_CMP_CERTRESPONSE, rspInfo, ASN1_OCTET_STRING) } ASN1_SEQUENCE_END(OSSL_CMP_CERTRESPONSE) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_CERTRESPONSE) ASN1_SEQUENCE(OSSL_CMP_POLLREQ) = { ASN1_SIMPLE(OSSL_CMP_POLLREQ, certReqId, ASN1_INTEGER) } ASN1_SEQUENCE_END(OSSL_CMP_POLLREQ) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_POLLREQ) ASN1_ITEM_TEMPLATE(OSSL_CMP_POLLREQCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_POLLREQCONTENT, OSSL_CMP_POLLREQ) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_POLLREQCONTENT) ASN1_SEQUENCE(OSSL_CMP_POLLREP) = { ASN1_SIMPLE(OSSL_CMP_POLLREP, certReqId, ASN1_INTEGER), ASN1_SIMPLE(OSSL_CMP_POLLREP, checkAfter, ASN1_INTEGER), ASN1_SEQUENCE_OF_OPT(OSSL_CMP_POLLREP, reason, ASN1_UTF8STRING), } ASN1_SEQUENCE_END(OSSL_CMP_POLLREP) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_POLLREP) ASN1_ITEM_TEMPLATE(OSSL_CMP_POLLREPCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_POLLREPCONTENT, OSSL_CMP_POLLREP) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_POLLREPCONTENT) ASN1_SEQUENCE(OSSL_CMP_CERTREPMESSAGE) = { /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_CERTREPMESSAGE, caPubs, X509, 1), ASN1_SEQUENCE_OF(OSSL_CMP_CERTREPMESSAGE, response, OSSL_CMP_CERTRESPONSE) } ASN1_SEQUENCE_END(OSSL_CMP_CERTREPMESSAGE) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_CERTREPMESSAGE) ASN1_ITEM_TEMPLATE(OSSL_CMP_GENMSGCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_GENMSGCONTENT, OSSL_CMP_ITAV) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_GENMSGCONTENT) ASN1_ITEM_TEMPLATE(OSSL_CMP_GENREPCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_GENREPCONTENT, OSSL_CMP_ITAV) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_GENREPCONTENT) ASN1_ITEM_TEMPLATE(OSSL_CMP_CRLANNCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_CRLANNCONTENT, X509_CRL) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_CRLANNCONTENT) ASN1_CHOICE(OSSL_CMP_PKIBODY) = { ASN1_EXP(OSSL_CMP_PKIBODY, value.ir, OSSL_CRMF_MSGS, 0), ASN1_EXP(OSSL_CMP_PKIBODY, value.ip, OSSL_CMP_CERTREPMESSAGE, 1), ASN1_EXP(OSSL_CMP_PKIBODY, value.cr, OSSL_CRMF_MSGS, 2), ASN1_EXP(OSSL_CMP_PKIBODY, value.cp, OSSL_CMP_CERTREPMESSAGE, 3), ASN1_EXP(OSSL_CMP_PKIBODY, value.p10cr, X509_REQ, 4), ASN1_EXP(OSSL_CMP_PKIBODY, value.popdecc, OSSL_CMP_POPODECKEYCHALLCONTENT, 5), ASN1_EXP(OSSL_CMP_PKIBODY, value.popdecr, OSSL_CMP_POPODECKEYRESPCONTENT, 6), ASN1_EXP(OSSL_CMP_PKIBODY, value.kur, OSSL_CRMF_MSGS, 7), ASN1_EXP(OSSL_CMP_PKIBODY, value.kup, OSSL_CMP_CERTREPMESSAGE, 8), ASN1_EXP(OSSL_CMP_PKIBODY, value.krr, OSSL_CRMF_MSGS, 9), ASN1_EXP(OSSL_CMP_PKIBODY, value.krp, OSSL_CMP_KEYRECREPCONTENT, 10), ASN1_EXP(OSSL_CMP_PKIBODY, value.rr, OSSL_CMP_REVREQCONTENT, 11), ASN1_EXP(OSSL_CMP_PKIBODY, value.rp, OSSL_CMP_REVREPCONTENT, 12), ASN1_EXP(OSSL_CMP_PKIBODY, value.ccr, OSSL_CRMF_MSGS, 13), ASN1_EXP(OSSL_CMP_PKIBODY, value.ccp, OSSL_CMP_CERTREPMESSAGE, 14), ASN1_EXP(OSSL_CMP_PKIBODY, value.ckuann, OSSL_CMP_CAKEYUPDANNCONTENT, 15), ASN1_EXP(OSSL_CMP_PKIBODY, value.cann, X509, 16), ASN1_EXP(OSSL_CMP_PKIBODY, value.rann, OSSL_CMP_REVANNCONTENT, 17), ASN1_EXP(OSSL_CMP_PKIBODY, value.crlann, OSSL_CMP_CRLANNCONTENT, 18), ASN1_EXP(OSSL_CMP_PKIBODY, value.pkiconf, ASN1_ANY, 19), ASN1_EXP(OSSL_CMP_PKIBODY, value.nested, OSSL_CMP_MSGS, 20), ASN1_EXP(OSSL_CMP_PKIBODY, value.genm, OSSL_CMP_GENMSGCONTENT, 21), ASN1_EXP(OSSL_CMP_PKIBODY, value.genp, OSSL_CMP_GENREPCONTENT, 22), ASN1_EXP(OSSL_CMP_PKIBODY, value.error, OSSL_CMP_ERRORMSGCONTENT, 23), ASN1_EXP(OSSL_CMP_PKIBODY, value.certConf, OSSL_CMP_CERTCONFIRMCONTENT, 24), ASN1_EXP(OSSL_CMP_PKIBODY, value.pollReq, OSSL_CMP_POLLREQCONTENT, 25), ASN1_EXP(OSSL_CMP_PKIBODY, value.pollRep, OSSL_CMP_POLLREPCONTENT, 26), } ASN1_CHOICE_END(OSSL_CMP_PKIBODY) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_PKIBODY) ASN1_SEQUENCE(OSSL_CMP_PKIHEADER) = { ASN1_SIMPLE(OSSL_CMP_PKIHEADER, pvno, ASN1_INTEGER), ASN1_SIMPLE(OSSL_CMP_PKIHEADER, sender, GENERAL_NAME), ASN1_SIMPLE(OSSL_CMP_PKIHEADER, recipient, GENERAL_NAME), ASN1_EXP_OPT(OSSL_CMP_PKIHEADER, messageTime, ASN1_GENERALIZEDTIME, 0), ASN1_EXP_OPT(OSSL_CMP_PKIHEADER, protectionAlg, X509_ALGOR, 1), ASN1_EXP_OPT(OSSL_CMP_PKIHEADER, senderKID, ASN1_OCTET_STRING, 2), ASN1_EXP_OPT(OSSL_CMP_PKIHEADER, recipKID, ASN1_OCTET_STRING, 3), ASN1_EXP_OPT(OSSL_CMP_PKIHEADER, transactionID, ASN1_OCTET_STRING, 4), ASN1_EXP_OPT(OSSL_CMP_PKIHEADER, senderNonce, ASN1_OCTET_STRING, 5), ASN1_EXP_OPT(OSSL_CMP_PKIHEADER, recipNonce, ASN1_OCTET_STRING, 6), /* * OSSL_CMP_PKIFREETEXT is effectively a sequence of ASN1_UTF8STRING * so it is used directly */ ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_PKIHEADER, freeText, ASN1_UTF8STRING, 7), ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_PKIHEADER, generalInfo, OSSL_CMP_ITAV, 8) } ASN1_SEQUENCE_END(OSSL_CMP_PKIHEADER) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_PKIHEADER) ASN1_SEQUENCE(OSSL_CMP_PROTECTEDPART) = { ASN1_SIMPLE(OSSL_CMP_MSG, header, OSSL_CMP_PKIHEADER), ASN1_SIMPLE(OSSL_CMP_MSG, body, OSSL_CMP_PKIBODY) } ASN1_SEQUENCE_END(OSSL_CMP_PROTECTEDPART) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_PROTECTEDPART) ASN1_SEQUENCE_cb(OSSL_CMP_MSG, ossl_cmp_msg_cb) = { ASN1_SIMPLE(OSSL_CMP_MSG, header, OSSL_CMP_PKIHEADER), ASN1_SIMPLE(OSSL_CMP_MSG, body, OSSL_CMP_PKIBODY), ASN1_EXP_OPT(OSSL_CMP_MSG, protection, ASN1_BIT_STRING, 0), /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_MSG, extraCerts, X509, 1) } ASN1_SEQUENCE_END_cb(OSSL_CMP_MSG, OSSL_CMP_MSG) IMPLEMENT_ASN1_DUP_FUNCTION(OSSL_CMP_MSG) ASN1_ITEM_TEMPLATE(OSSL_CMP_MSGS) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_MSGS, OSSL_CMP_MSG) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_MSGS) diff --git a/crypto/cmp/cmp_client.c b/crypto/cmp/cmp_client.c index dc41f4c3b7d9..df334cc00198 100644 --- a/crypto/cmp/cmp_client.c +++ b/crypto/cmp/cmp_client.c @@ -1,918 +1,918 @@ /* * Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "cmp_local.h" #include "internal/cryptlib.h" #include "e_os.h" /* ossl_sleep() */ /* explicit #includes not strictly needed since implied by the above: */ #include #include #include #include #include #include #define IS_CREP(t) ((t) == OSSL_CMP_PKIBODY_IP || (t) == OSSL_CMP_PKIBODY_CP \ || (t) == OSSL_CMP_PKIBODY_KUP) /*- * Evaluate whether there's an exception (violating the standard) configured for * handling negative responses without protection or with invalid protection. * Returns 1 on acceptance, 0 on rejection, or -1 on (internal) error. */ static int unprotected_exception(const OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *rep, int invalid_protection, int expected_type /* ignored here */) { int rcvd_type = OSSL_CMP_MSG_get_bodytype(rep /* may be NULL */); const char *msg_type = NULL; if (!ossl_assert(ctx != NULL && rep != NULL)) return -1; if (!ctx->unprotectedErrors) return 0; switch (rcvd_type) { case OSSL_CMP_PKIBODY_ERROR: msg_type = "error response"; break; case OSSL_CMP_PKIBODY_RP: { OSSL_CMP_PKISI *si = ossl_cmp_revrepcontent_get_pkisi(rep->body->value.rp, OSSL_CMP_REVREQSID); if (si == NULL) return -1; if (ossl_cmp_pkisi_get_status(si) == OSSL_CMP_PKISTATUS_rejection) msg_type = "revocation response message with rejection status"; break; } case OSSL_CMP_PKIBODY_PKICONF: msg_type = "PKI Confirmation message"; break; default: if (IS_CREP(rcvd_type)) { int any_rid = OSSL_CMP_CERTREQID_NONE; OSSL_CMP_CERTREPMESSAGE *crepmsg = rep->body->value.ip; OSSL_CMP_CERTRESPONSE *crep = ossl_cmp_certrepmessage_get0_certresponse(crepmsg, any_rid); if (sk_OSSL_CMP_CERTRESPONSE_num(crepmsg->response) > 1) return -1; if (crep == NULL) return -1; if (ossl_cmp_pkisi_get_status(crep->status) == OSSL_CMP_PKISTATUS_rejection) msg_type = "CertRepMessage with rejection status"; } } if (msg_type == NULL) return 0; ossl_cmp_log2(WARN, ctx, "ignoring %s protection of %s", invalid_protection ? "invalid" : "missing", msg_type); return 1; } /* Save error info from PKIStatusInfo field of a certresponse into ctx */ static int save_statusInfo(OSSL_CMP_CTX *ctx, OSSL_CMP_PKISI *si) { int i; OSSL_CMP_PKIFREETEXT *ss; if (!ossl_assert(ctx != NULL && si != NULL)) return 0; ctx->status = ossl_cmp_pkisi_get_status(si); if (ctx->status < OSSL_CMP_PKISTATUS_accepted) return 0; ctx->failInfoCode = ossl_cmp_pkisi_get_pkifailureinfo(si); if (!ossl_cmp_ctx_set0_statusString(ctx, sk_ASN1_UTF8STRING_new_null()) || (ctx->statusString == NULL)) return 0; ss = si->statusString; /* may be NULL */ for (i = 0; i < sk_ASN1_UTF8STRING_num(ss); i++) { ASN1_UTF8STRING *str = sk_ASN1_UTF8STRING_value(ss, i); if (!sk_ASN1_UTF8STRING_push(ctx->statusString, ASN1_STRING_dup(str))) return 0; } return 1; } /*- * Perform the generic aspects of sending a request and receiving a response. * Returns 1 on success and provides the received PKIMESSAGE in *rep. * Returns 0 on error. * Regardless of success, caller is responsible for freeing *rep (unless NULL). */ static int send_receive_check(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *req, OSSL_CMP_MSG **rep, int expected_type) { int begin_transaction = expected_type != OSSL_CMP_PKIBODY_POLLREP && expected_type != OSSL_CMP_PKIBODY_PKICONF; const char *req_type_str = ossl_cmp_bodytype_to_string(OSSL_CMP_MSG_get_bodytype(req)); const char *expected_type_str = ossl_cmp_bodytype_to_string(expected_type); int bak_msg_timeout = ctx->msg_timeout; int bt; time_t now = time(NULL); int time_left; OSSL_CMP_transfer_cb_t transfer_cb = ctx->transfer_cb; if (transfer_cb == NULL) transfer_cb = OSSL_CMP_MSG_http_perform; *rep = NULL; if (ctx->total_timeout != 0 /* not waiting indefinitely */) { if (begin_transaction) ctx->end_time = now + ctx->total_timeout; if (now >= ctx->end_time) { ERR_raise(ERR_LIB_CMP, CMP_R_TOTAL_TIMEOUT); return 0; } if (!ossl_assert(ctx->end_time - now < INT_MAX)) { /* actually cannot happen due to assignment in initial_certreq() */ ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_ARGS); return 0; } time_left = (int)(ctx->end_time - now); if (ctx->msg_timeout == 0 || time_left < ctx->msg_timeout) ctx->msg_timeout = time_left; } /* should print error queue since transfer_cb may call ERR_clear_error() */ OSSL_CMP_CTX_print_errors(ctx); ossl_cmp_log1(INFO, ctx, "sending %s", req_type_str); *rep = (*transfer_cb)(ctx, req); ctx->msg_timeout = bak_msg_timeout; if (*rep == NULL) { ERR_raise_data(ERR_LIB_CMP, ctx->total_timeout != 0 && time(NULL) >= ctx->end_time ? CMP_R_TOTAL_TIMEOUT : CMP_R_TRANSFER_ERROR, "request sent: %s, expected response: %s", req_type_str, expected_type_str); return 0; } bt = OSSL_CMP_MSG_get_bodytype(*rep); /* * The body type in the 'bt' variable is not yet verified. * Still we use this preliminary value already for a progress report because * the following msg verification may also produce log entries and may fail. */ ossl_cmp_log1(INFO, ctx, "received %s", ossl_cmp_bodytype_to_string(bt)); /* copy received extraCerts to ctx->extraCertsIn so they can be retrieved */ if (bt != OSSL_CMP_PKIBODY_POLLREP && bt != OSSL_CMP_PKIBODY_PKICONF && !ossl_cmp_ctx_set1_extraCertsIn(ctx, (*rep)->extraCerts)) return 0; if (!ossl_cmp_msg_check_update(ctx, *rep, unprotected_exception, expected_type)) return 0; if (bt == expected_type /* as an answer to polling, there could be IP/CP/KUP: */ || (IS_CREP(bt) && expected_type == OSSL_CMP_PKIBODY_POLLREP)) return 1; /* received message type is not one of the expected ones (e.g., error) */ ERR_raise(ERR_LIB_CMP, bt == OSSL_CMP_PKIBODY_ERROR ? CMP_R_RECEIVED_ERROR : CMP_R_UNEXPECTED_PKIBODY); /* in next line for mkerr.pl */ if (bt != OSSL_CMP_PKIBODY_ERROR) { ERR_add_error_data(3, "message type is '", ossl_cmp_bodytype_to_string(bt), "'"); } else { OSSL_CMP_ERRORMSGCONTENT *emc = (*rep)->body->value.error; OSSL_CMP_PKISI *si = emc->pKIStatusInfo; char buf[OSSL_CMP_PKISI_BUFLEN]; if (save_statusInfo(ctx, si) && OSSL_CMP_CTX_snprint_PKIStatus(ctx, buf, sizeof(buf)) != NULL) ERR_add_error_data(1, buf); if (emc->errorCode != NULL && BIO_snprintf(buf, sizeof(buf), "; errorCode: %08lX", ASN1_INTEGER_get(emc->errorCode)) > 0) ERR_add_error_data(1, buf); if (emc->errorDetails != NULL) { char *text = ossl_sk_ASN1_UTF8STRING2text(emc->errorDetails, ", ", OSSL_CMP_PKISI_BUFLEN - 1); if (text != NULL && *text != '\0') ERR_add_error_data(2, "; errorDetails: ", text); OPENSSL_free(text); } if (ctx->status != OSSL_CMP_PKISTATUS_rejection) { ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKISTATUS); if (ctx->status == OSSL_CMP_PKISTATUS_waiting) ctx->status = OSSL_CMP_PKISTATUS_rejection; } } return 0; } /*- * When a 'waiting' PKIStatus has been received, this function is used to * poll, which should yield a pollRep or finally a CertRepMessage in ip/cp/kup. * On receiving a pollRep, which includes a checkAfter value, it return this * value if sleep == 0, else it sleeps as long as indicated and retries. * * A transaction timeout is enabled if ctx->total_timeout is != 0. * In this case polling will continue until the timeout is reached and then * polling is done a last time even if this is before the "checkAfter" time. * * Returns -1 on receiving pollRep if sleep == 0, setting the checkAfter value. * Returns 1 on success and provides the received PKIMESSAGE in *rep. * In this case the caller is responsible for freeing *rep. * Returns 0 on error (which includes the case that timeout has been reached). */ static int poll_for_response(OSSL_CMP_CTX *ctx, int sleep, int rid, OSSL_CMP_MSG **rep, int *checkAfter) { OSSL_CMP_MSG *preq = NULL; OSSL_CMP_MSG *prep = NULL; ossl_cmp_info(ctx, "received 'waiting' PKIStatus, starting to poll for response"); *rep = NULL; for (;;) { if ((preq = ossl_cmp_pollReq_new(ctx, rid)) == NULL) goto err; if (!send_receive_check(ctx, preq, &prep, OSSL_CMP_PKIBODY_POLLREP)) goto err; /* handle potential pollRep */ if (OSSL_CMP_MSG_get_bodytype(prep) == OSSL_CMP_PKIBODY_POLLREP) { OSSL_CMP_POLLREPCONTENT *prc = prep->body->value.pollRep; OSSL_CMP_POLLREP *pollRep = NULL; int64_t check_after; char str[OSSL_CMP_PKISI_BUFLEN]; int len; if (sk_OSSL_CMP_POLLREP_num(prc) > 1) { ERR_raise(ERR_LIB_CMP, CMP_R_MULTIPLE_RESPONSES_NOT_SUPPORTED); goto err; } pollRep = ossl_cmp_pollrepcontent_get0_pollrep(prc, rid); if (pollRep == NULL) goto err; if (!ASN1_INTEGER_get_int64(&check_after, pollRep->checkAfter)) { ERR_raise(ERR_LIB_CMP, CMP_R_BAD_CHECKAFTER_IN_POLLREP); goto err; } if (check_after < 0 || (uint64_t)check_after > (sleep ? ULONG_MAX / 1000 : INT_MAX)) { ERR_raise(ERR_LIB_CMP, CMP_R_CHECKAFTER_OUT_OF_RANGE); if (BIO_snprintf(str, OSSL_CMP_PKISI_BUFLEN, "value = %jd", check_after) >= 0) ERR_add_error_data(1, str); goto err; } if (pollRep->reason == NULL || (len = BIO_snprintf(str, OSSL_CMP_PKISI_BUFLEN, " with reason = '")) < 0) { *str = '\0'; } else { char *text = ossl_sk_ASN1_UTF8STRING2text(pollRep->reason, ", ", sizeof(str) - len - 2); if (text == NULL || BIO_snprintf(str + len, sizeof(str) - len, "%s'", text) < 0) *str = '\0'; OPENSSL_free(text); } ossl_cmp_log2(INFO, ctx, "received polling response%s; checkAfter = %ld seconds", str, check_after); if (ctx->total_timeout != 0) { /* timeout is not infinite */ const int exp = 5; /* expected max time per msg round trip */ int64_t time_left = (int64_t)(ctx->end_time - exp - time(NULL)); if (time_left <= 0) { ERR_raise(ERR_LIB_CMP, CMP_R_TOTAL_TIMEOUT); goto err; } if (time_left < check_after) check_after = time_left; /* poll one last time just when timeout was reached */ } OSSL_CMP_MSG_free(preq); preq = NULL; OSSL_CMP_MSG_free(prep); prep = NULL; if (sleep) { ossl_sleep((unsigned long)(1000 * check_after)); } else { if (checkAfter != NULL) *checkAfter = (int)check_after; return -1; /* exits the loop */ } } else { ossl_cmp_info(ctx, "received ip/cp/kup after polling"); /* any other body type has been rejected by send_receive_check() */ break; } } if (prep == NULL) goto err; OSSL_CMP_MSG_free(preq); *rep = prep; return 1; err: OSSL_CMP_MSG_free(preq); OSSL_CMP_MSG_free(prep); return 0; } /* * Send certConf for IR, CR or KUR sequences and check response, * not modifying ctx->status during the certConf exchange */ int ossl_cmp_exchange_certConf(OSSL_CMP_CTX *ctx, int certReqId, int fail_info, const char *txt) { OSSL_CMP_MSG *certConf; OSSL_CMP_MSG *PKIconf = NULL; int res = 0; /* OSSL_CMP_certConf_new() also checks if all necessary options are set */ certConf = ossl_cmp_certConf_new(ctx, certReqId, fail_info, txt); if (certConf == NULL) goto err; res = send_receive_check(ctx, certConf, &PKIconf, OSSL_CMP_PKIBODY_PKICONF); err: OSSL_CMP_MSG_free(certConf); OSSL_CMP_MSG_free(PKIconf); return res; } /* Send given error and check response */ int ossl_cmp_exchange_error(OSSL_CMP_CTX *ctx, int status, int fail_info, const char *txt, int errorCode, const char *details) { OSSL_CMP_MSG *error = NULL; OSSL_CMP_PKISI *si = NULL; OSSL_CMP_MSG *PKIconf = NULL; int res = 0; /* not overwriting ctx->status on error exchange */ if ((si = OSSL_CMP_STATUSINFO_new(status, fail_info, txt)) == NULL) goto err; /* ossl_cmp_error_new() also checks if all necessary options are set */ if ((error = ossl_cmp_error_new(ctx, si, errorCode, details, 0)) == NULL) goto err; res = send_receive_check(ctx, error, &PKIconf, OSSL_CMP_PKIBODY_PKICONF); err: OSSL_CMP_MSG_free(error); OSSL_CMP_PKISI_free(si); OSSL_CMP_MSG_free(PKIconf); return res; } /*- * Retrieve a copy of the certificate, if any, from the given CertResponse. * Take into account PKIStatusInfo of CertResponse in ctx, report it on error. * Returns NULL if not found or on error. */ static X509 *get1_cert_status(OSSL_CMP_CTX *ctx, int bodytype, OSSL_CMP_CERTRESPONSE *crep) { char buf[OSSL_CMP_PKISI_BUFLEN]; X509 *crt = NULL; if (!ossl_assert(ctx != NULL && crep != NULL)) return NULL; switch (ossl_cmp_pkisi_get_status(crep->status)) { case OSSL_CMP_PKISTATUS_waiting: ossl_cmp_err(ctx, "received \"waiting\" status for cert when actually aiming to extract cert"); ERR_raise(ERR_LIB_CMP, CMP_R_ENCOUNTERED_WAITING); goto err; case OSSL_CMP_PKISTATUS_grantedWithMods: ossl_cmp_warn(ctx, "received \"grantedWithMods\" for certificate"); break; case OSSL_CMP_PKISTATUS_accepted: break; /* get all information in case of a rejection before going to error */ case OSSL_CMP_PKISTATUS_rejection: ossl_cmp_err(ctx, "received \"rejection\" status rather than cert"); ERR_raise(ERR_LIB_CMP, CMP_R_REQUEST_REJECTED_BY_SERVER); goto err; case OSSL_CMP_PKISTATUS_revocationWarning: ossl_cmp_warn(ctx, "received \"revocationWarning\" - a revocation of the cert is imminent"); break; case OSSL_CMP_PKISTATUS_revocationNotification: ossl_cmp_warn(ctx, "received \"revocationNotification\" - a revocation of the cert has occurred"); break; case OSSL_CMP_PKISTATUS_keyUpdateWarning: if (bodytype != OSSL_CMP_PKIBODY_KUR) { ERR_raise(ERR_LIB_CMP, CMP_R_ENCOUNTERED_KEYUPDATEWARNING); goto err; } break; default: ossl_cmp_log1(ERROR, ctx, "received unsupported PKIStatus %d for certificate", ctx->status); ERR_raise(ERR_LIB_CMP, CMP_R_UNKNOWN_PKISTATUS); goto err; } crt = ossl_cmp_certresponse_get1_cert(ctx, crep); if (crt == NULL) /* according to PKIStatus, we can expect a cert */ ERR_raise(ERR_LIB_CMP, CMP_R_CERTIFICATE_NOT_FOUND); return crt; err: if (OSSL_CMP_CTX_snprint_PKIStatus(ctx, buf, sizeof(buf)) != NULL) ERR_add_error_data(1, buf); return NULL; } /*- * Callback fn validating that the new certificate can be verified, using * ctx->certConf_cb_arg, which has been initialized using opt_out_trusted, and * ctx->untrusted, which at this point already contains msg->extraCerts. * Returns 0 on acceptance, else a bit field reflecting PKIFailureInfo. * Quoting from RFC 4210 section 5.1. Overall PKI Message: * The extraCerts field can contain certificates that may be useful to * the recipient. For example, this can be used by a CA or RA to * present an end entity with certificates that it needs to verify its * own new certificate (if, for example, the CA that issued the end * entity's certificate is not a root CA for the end entity). Note that * this field does not necessarily contain a certification path; the * recipient may have to sort, select from, or otherwise process the * extra certificates in order to use them. * Note: While often handy, there is no hard requirement by CMP that * an EE must be able to validate the certificates it gets enrolled. */ int OSSL_CMP_certConf_cb(OSSL_CMP_CTX *ctx, X509 *cert, int fail_info, const char **text) { X509_STORE *out_trusted = OSSL_CMP_CTX_get_certConf_cb_arg(ctx); STACK_OF(X509) *chain = NULL; (void)text; /* make (artificial) use of var to prevent compiler warning */ if (fail_info != 0) /* accept any error flagged by CMP core library */ return fail_info; if (out_trusted == NULL) { ossl_cmp_debug(ctx, "trying to build chain for newly enrolled cert"); chain = X509_build_chain(cert, ctx->untrusted, out_trusted, 0, ctx->libctx, ctx->propq); } else { X509_STORE_CTX *csc = X509_STORE_CTX_new_ex(ctx->libctx, ctx->propq); ossl_cmp_debug(ctx, "validating newly enrolled cert"); if (csc == NULL) goto err; if (!X509_STORE_CTX_init(csc, out_trusted, cert, ctx->untrusted)) goto err; /* disable any cert status/revocation checking etc. */ X509_VERIFY_PARAM_clear_flags(X509_STORE_CTX_get0_param(csc), ~(X509_V_FLAG_USE_CHECK_TIME | X509_V_FLAG_NO_CHECK_TIME | X509_V_FLAG_PARTIAL_CHAIN | X509_V_FLAG_POLICY_CHECK)); if (X509_verify_cert(csc) <= 0) goto err; if (!ossl_x509_add_certs_new(&chain, X509_STORE_CTX_get0_chain(csc), X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP | X509_ADD_FLAG_NO_SS)) { sk_X509_free(chain); chain = NULL; } err: X509_STORE_CTX_free(csc); } if (sk_X509_num(chain) > 0) X509_free(sk_X509_shift(chain)); /* remove leaf (EE) cert */ if (out_trusted != NULL) { if (chain == NULL) { ossl_cmp_err(ctx, "failed to validate newly enrolled cert"); fail_info = 1 << OSSL_CMP_PKIFAILUREINFO_incorrectData; } else { ossl_cmp_debug(ctx, "success validating newly enrolled cert"); } } else if (chain == NULL) { ossl_cmp_warn(ctx, "could not build approximate chain for newly enrolled cert, resorting to received extraCerts"); chain = OSSL_CMP_CTX_get1_extraCertsIn(ctx); } else { ossl_cmp_debug(ctx, "success building approximate chain for newly enrolled cert"); } (void)ossl_cmp_ctx_set1_newChain(ctx, chain); sk_X509_pop_free(chain, X509_free); return fail_info; } /*- * Perform the generic handling of certificate responses for IR/CR/KUR/P10CR. * |rid| must be OSSL_CMP_CERTREQID_NONE if not available, namely for p10cr * Returns -1 on receiving pollRep if sleep == 0, setting the checkAfter value. * Returns 1 on success and provides the received PKIMESSAGE in *resp. * Returns 0 on error (which includes the case that timeout has been reached). * Regardless of success, caller is responsible for freeing *resp (unless NULL). */ static int cert_response(OSSL_CMP_CTX *ctx, int sleep, int rid, OSSL_CMP_MSG **resp, int *checkAfter, int req_type, int expected_type) { EVP_PKEY *rkey = ossl_cmp_ctx_get0_newPubkey(ctx); int fail_info = 0; /* no failure */ const char *txt = NULL; OSSL_CMP_CERTREPMESSAGE *crepmsg; OSSL_CMP_CERTRESPONSE *crep; OSSL_CMP_certConf_cb_t cb; X509 *cert; char *subj = NULL; int ret = 1; if (!ossl_assert(ctx != NULL)) return 0; retry: crepmsg = (*resp)->body->value.ip; /* same for cp and kup */ if (sk_OSSL_CMP_CERTRESPONSE_num(crepmsg->response) > 1) { ERR_raise(ERR_LIB_CMP, CMP_R_MULTIPLE_RESPONSES_NOT_SUPPORTED); return 0; } crep = ossl_cmp_certrepmessage_get0_certresponse(crepmsg, rid); if (crep == NULL) return 0; if (!save_statusInfo(ctx, crep->status)) return 0; if (rid == OSSL_CMP_CERTREQID_NONE) { /* used for OSSL_CMP_PKIBODY_P10CR */ rid = ossl_cmp_asn1_get_int(crep->certReqId); - if (rid != OSSL_CMP_CERTREQID_NONE) { + if (rid < OSSL_CMP_CERTREQID_NONE) { ERR_raise(ERR_LIB_CMP, CMP_R_BAD_REQUEST_ID); return 0; } } if (ossl_cmp_pkisi_get_status(crep->status) == OSSL_CMP_PKISTATUS_waiting) { OSSL_CMP_MSG_free(*resp); *resp = NULL; if ((ret = poll_for_response(ctx, sleep, rid, resp, checkAfter)) != 0) { if (ret == -1) /* at this point implies sleep == 0 */ return ret; /* waiting */ goto retry; /* got ip/cp/kup, which may still indicate 'waiting' */ } else { ERR_raise(ERR_LIB_CMP, CMP_R_POLLING_FAILED); return 0; } } cert = get1_cert_status(ctx, (*resp)->body->type, crep); if (cert == NULL) { ERR_add_error_data(1, "; cannot extract certificate from response"); return 0; } if (!ossl_cmp_ctx_set0_newCert(ctx, cert)) return 0; /* * if the CMP server returned certificates in the caPubs field, copy them * to the context so that they can be retrieved if necessary */ if (crepmsg->caPubs != NULL && !ossl_cmp_ctx_set1_caPubs(ctx, crepmsg->caPubs)) return 0; subj = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0); if (rkey != NULL /* X509_check_private_key() also works if rkey is just public key */ && !(X509_check_private_key(ctx->newCert, rkey))) { fail_info = 1 << OSSL_CMP_PKIFAILUREINFO_incorrectData; txt = "public key in new certificate does not match our enrollment key"; /*- * not calling (void)ossl_cmp_exchange_error(ctx, * OSSL_CMP_PKISTATUS_rejection, fail_info, txt) * not throwing CMP_R_CERTIFICATE_NOT_ACCEPTED with txt * not returning 0 * since we better leave this for the certConf_cb to decide */ } /* * Execute the certification checking callback function, * which can determine whether to accept a newly enrolled certificate. * It may overrule the pre-decision reflected in 'fail_info' and '*txt'. */ cb = ctx->certConf_cb != NULL ? ctx->certConf_cb : OSSL_CMP_certConf_cb; if ((fail_info = cb(ctx, ctx->newCert, fail_info, &txt)) != 0 && txt == NULL) txt = "CMP client did not accept it"; if (fail_info != 0) /* immediately log error before any certConf exchange */ ossl_cmp_log1(ERROR, ctx, "rejecting newly enrolled cert with subject: %s", subj); if (!ctx->disableConfirm && !ossl_cmp_hdr_has_implicitConfirm((*resp)->header)) { if (!ossl_cmp_exchange_certConf(ctx, rid, fail_info, txt)) ret = 0; } /* not throwing failure earlier as transfer_cb may call ERR_clear_error() */ if (fail_info != 0) { ERR_raise_data(ERR_LIB_CMP, CMP_R_CERTIFICATE_NOT_ACCEPTED, "rejecting newly enrolled cert with subject: %s; %s", subj, txt); ctx->status = OSSL_CMP_PKISTATUS_rejection; ret = 0; } OPENSSL_free(subj); return ret; } static int initial_certreq(OSSL_CMP_CTX *ctx, int req_type, const OSSL_CRMF_MSG *crm, OSSL_CMP_MSG **p_rep, int rep_type) { OSSL_CMP_MSG *req; int res; ctx->status = OSSL_CMP_PKISTATUS_request; if (!ossl_cmp_ctx_set0_newCert(ctx, NULL)) return 0; /* also checks if all necessary options are set */ if ((req = ossl_cmp_certreq_new(ctx, req_type, crm)) == NULL) return 0; ctx->status = OSSL_CMP_PKISTATUS_trans; res = send_receive_check(ctx, req, p_rep, rep_type); OSSL_CMP_MSG_free(req); return res; } int OSSL_CMP_try_certreq(OSSL_CMP_CTX *ctx, int req_type, const OSSL_CRMF_MSG *crm, int *checkAfter) { OSSL_CMP_MSG *rep = NULL; int is_p10 = req_type == OSSL_CMP_PKIBODY_P10CR; int rid = is_p10 ? OSSL_CMP_CERTREQID_NONE : OSSL_CMP_CERTREQID; int rep_type = is_p10 ? OSSL_CMP_PKIBODY_CP : req_type + 1; int res = 0; if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (ctx->status != OSSL_CMP_PKISTATUS_waiting) { /* not polling already */ if (!initial_certreq(ctx, req_type, crm, &rep, rep_type)) goto err; } else { if (req_type < 0) return ossl_cmp_exchange_error(ctx, OSSL_CMP_PKISTATUS_rejection, 0, "polling aborted", 0 /* errorCode */, "by application"); res = poll_for_response(ctx, 0 /* no sleep */, rid, &rep, checkAfter); if (res <= 0) /* waiting or error */ return res; } res = cert_response(ctx, 0 /* no sleep */, rid, &rep, checkAfter, req_type, rep_type); err: OSSL_CMP_MSG_free(rep); return res; } /*- * Do the full sequence CR/IR/KUR/P10CR, CP/IP/KUP/CP, * certConf, PKIconf, and polling if required. * Will sleep as long as indicated by the server (according to checkAfter). * All enrollment options need to be present in the context. * Returns pointer to received certificate, or NULL if none was received. */ X509 *OSSL_CMP_exec_certreq(OSSL_CMP_CTX *ctx, int req_type, const OSSL_CRMF_MSG *crm) { OSSL_CMP_MSG *rep = NULL; int is_p10 = req_type == OSSL_CMP_PKIBODY_P10CR; int rid = is_p10 ? OSSL_CMP_CERTREQID_NONE : OSSL_CMP_CERTREQID; int rep_type = is_p10 ? OSSL_CMP_PKIBODY_CP : req_type + 1; X509 *result = NULL; if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } if (!initial_certreq(ctx, req_type, crm, &rep, rep_type)) goto err; if (cert_response(ctx, 1 /* sleep */, rid, &rep, NULL, req_type, rep_type) <= 0) goto err; result = ctx->newCert; err: OSSL_CMP_MSG_free(rep); return result; } int OSSL_CMP_exec_RR_ses(OSSL_CMP_CTX *ctx) { OSSL_CMP_MSG *rr = NULL; OSSL_CMP_MSG *rp = NULL; const int num_RevDetails = 1; const int rsid = OSSL_CMP_REVREQSID; OSSL_CMP_REVREPCONTENT *rrep = NULL; OSSL_CMP_PKISI *si = NULL; char buf[OSSL_CMP_PKISI_BUFLEN]; int ret = 0; if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_ARGS); return 0; } ctx->status = OSSL_CMP_PKISTATUS_request; if (ctx->oldCert == NULL && ctx->p10CSR == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_REFERENCE_CERT); return 0; } /* OSSL_CMP_rr_new() also checks if all necessary options are set */ if ((rr = ossl_cmp_rr_new(ctx)) == NULL) goto end; ctx->status = OSSL_CMP_PKISTATUS_trans; if (!send_receive_check(ctx, rr, &rp, OSSL_CMP_PKIBODY_RP)) goto end; rrep = rp->body->value.rp; #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION if (sk_OSSL_CMP_PKISI_num(rrep->status) != num_RevDetails) { ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_RP_COMPONENT_COUNT); goto end; } #else if (sk_OSSL_CMP_PKISI_num(rrep->status) < 1) { ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_RP_COMPONENT_COUNT); goto end; } #endif /* evaluate PKIStatus field */ si = ossl_cmp_revrepcontent_get_pkisi(rrep, rsid); if (!save_statusInfo(ctx, si)) goto err; switch (ossl_cmp_pkisi_get_status(si)) { case OSSL_CMP_PKISTATUS_accepted: ossl_cmp_info(ctx, "revocation accepted (PKIStatus=accepted)"); ret = 1; break; case OSSL_CMP_PKISTATUS_grantedWithMods: ossl_cmp_info(ctx, "revocation accepted (PKIStatus=grantedWithMods)"); ret = 1; break; case OSSL_CMP_PKISTATUS_rejection: ERR_raise(ERR_LIB_CMP, CMP_R_REQUEST_REJECTED_BY_SERVER); goto err; case OSSL_CMP_PKISTATUS_revocationWarning: ossl_cmp_info(ctx, "revocation accepted (PKIStatus=revocationWarning)"); ret = 1; break; case OSSL_CMP_PKISTATUS_revocationNotification: /* interpretation as warning or error depends on CA */ ossl_cmp_warn(ctx, "revocation accepted (PKIStatus=revocationNotification)"); ret = 1; break; case OSSL_CMP_PKISTATUS_waiting: case OSSL_CMP_PKISTATUS_keyUpdateWarning: ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKISTATUS); goto err; default: ERR_raise(ERR_LIB_CMP, CMP_R_UNKNOWN_PKISTATUS); goto err; } /* check any present CertId in optional revCerts field */ if (sk_OSSL_CRMF_CERTID_num(rrep->revCerts) >= 1) { OSSL_CRMF_CERTID *cid; OSSL_CRMF_CERTTEMPLATE *tmpl = sk_OSSL_CMP_REVDETAILS_value(rr->body->value.rr, rsid)->certDetails; const X509_NAME *issuer = OSSL_CRMF_CERTTEMPLATE_get0_issuer(tmpl); const ASN1_INTEGER *serial = OSSL_CRMF_CERTTEMPLATE_get0_serialNumber(tmpl); if (sk_OSSL_CRMF_CERTID_num(rrep->revCerts) != num_RevDetails) { ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_RP_COMPONENT_COUNT); ret = 0; goto err; } if ((cid = ossl_cmp_revrepcontent_get_CertId(rrep, rsid)) == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_CERTID); ret = 0; goto err; } if (X509_NAME_cmp(issuer, OSSL_CRMF_CERTID_get0_issuer(cid)) != 0) { #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_CERTID_IN_RP); ret = 0; goto err; #endif } if (ASN1_INTEGER_cmp(serial, OSSL_CRMF_CERTID_get0_serialNumber(cid)) != 0) { #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_SERIAL_IN_RP); ret = 0; goto err; #endif } } /* check number of any optionally present crls */ if (rrep->crls != NULL && sk_X509_CRL_num(rrep->crls) != num_RevDetails) { ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_RP_COMPONENT_COUNT); ret = 0; goto err; } err: if (ret == 0 && OSSL_CMP_CTX_snprint_PKIStatus(ctx, buf, sizeof(buf)) != NULL) ERR_add_error_data(1, buf); end: OSSL_CMP_MSG_free(rr); OSSL_CMP_MSG_free(rp); return ret; } STACK_OF(OSSL_CMP_ITAV) *OSSL_CMP_exec_GENM_ses(OSSL_CMP_CTX *ctx) { OSSL_CMP_MSG *genm; OSSL_CMP_MSG *genp = NULL; STACK_OF(OSSL_CMP_ITAV) *itavs = NULL; if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_ARGS); return NULL; } ctx->status = OSSL_CMP_PKISTATUS_request; if ((genm = ossl_cmp_genm_new(ctx)) == NULL) goto err; ctx->status = OSSL_CMP_PKISTATUS_trans; if (!send_receive_check(ctx, genm, &genp, OSSL_CMP_PKIBODY_GENP)) goto err; ctx->status = OSSL_CMP_PKISTATUS_accepted; itavs = genp->body->value.genp; if (itavs == NULL) itavs = sk_OSSL_CMP_ITAV_new_null(); /* received stack of itavs not to be freed with the genp */ genp->body->value.genp = NULL; err: OSSL_CMP_MSG_free(genm); OSSL_CMP_MSG_free(genp); return itavs; /* NULL indicates error case */ } diff --git a/crypto/cmp/cmp_status.c b/crypto/cmp/cmp_status.c index bfe6cd9906b8..68144aa4fed8 100644 --- a/crypto/cmp/cmp_status.c +++ b/crypto/cmp/cmp_status.c @@ -1,314 +1,317 @@ /* - * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* CMP functions for PKIStatusInfo handling and PKIMessage decomposition */ #include #include "cmp_local.h" /* explicit #includes not strictly needed since implied by the above: */ #include #include #include #include /* needed in case config no-deprecated */ #include #include #include #include #include /* for ASN1_R_TOO_SMALL and ASN1_R_TOO_LARGE */ /* CMP functions related to PKIStatus */ int ossl_cmp_pkisi_get_status(const OSSL_CMP_PKISI *si) { + int res ; + if (!ossl_assert(si != NULL && si->status != NULL)) return -1; - return ossl_cmp_asn1_get_int(si->status); + res = ossl_cmp_asn1_get_int(si->status); + return res == -2 ? -1 : res; } const char *ossl_cmp_PKIStatus_to_string(int status) { switch (status) { case OSSL_CMP_PKISTATUS_accepted: return "PKIStatus: accepted"; case OSSL_CMP_PKISTATUS_grantedWithMods: return "PKIStatus: granted with modifications"; case OSSL_CMP_PKISTATUS_rejection: return "PKIStatus: rejection"; case OSSL_CMP_PKISTATUS_waiting: return "PKIStatus: waiting"; case OSSL_CMP_PKISTATUS_revocationWarning: return "PKIStatus: revocation warning - a revocation of the cert is imminent"; case OSSL_CMP_PKISTATUS_revocationNotification: return "PKIStatus: revocation notification - a revocation of the cert has occurred"; case OSSL_CMP_PKISTATUS_keyUpdateWarning: return "PKIStatus: key update warning - update already done for the cert"; default: ERR_raise_data(ERR_LIB_CMP, CMP_R_ERROR_PARSING_PKISTATUS, "PKIStatus: invalid=%d", status); return NULL; } } OSSL_CMP_PKIFREETEXT *ossl_cmp_pkisi_get0_statusString(const OSSL_CMP_PKISI *si) { if (!ossl_assert(si != NULL)) return NULL; return si->statusString; } int ossl_cmp_pkisi_get_pkifailureinfo(const OSSL_CMP_PKISI *si) { int i; int res = 0; if (!ossl_assert(si != NULL)) return -1; if (si->failInfo != NULL) for (i = 0; i <= OSSL_CMP_PKIFAILUREINFO_MAX; i++) if (ASN1_BIT_STRING_get_bit(si->failInfo, i)) res |= 1 << i; return res; } /*- * convert PKIFailureInfo number to human-readable string * returns pointer to static string, or NULL on error */ static const char *CMP_PKIFAILUREINFO_to_string(int number) { switch (number) { case OSSL_CMP_PKIFAILUREINFO_badAlg: return "badAlg"; case OSSL_CMP_PKIFAILUREINFO_badMessageCheck: return "badMessageCheck"; case OSSL_CMP_PKIFAILUREINFO_badRequest: return "badRequest"; case OSSL_CMP_PKIFAILUREINFO_badTime: return "badTime"; case OSSL_CMP_PKIFAILUREINFO_badCertId: return "badCertId"; case OSSL_CMP_PKIFAILUREINFO_badDataFormat: return "badDataFormat"; case OSSL_CMP_PKIFAILUREINFO_wrongAuthority: return "wrongAuthority"; case OSSL_CMP_PKIFAILUREINFO_incorrectData: return "incorrectData"; case OSSL_CMP_PKIFAILUREINFO_missingTimeStamp: return "missingTimeStamp"; case OSSL_CMP_PKIFAILUREINFO_badPOP: return "badPOP"; case OSSL_CMP_PKIFAILUREINFO_certRevoked: return "certRevoked"; case OSSL_CMP_PKIFAILUREINFO_certConfirmed: return "certConfirmed"; case OSSL_CMP_PKIFAILUREINFO_wrongIntegrity: return "wrongIntegrity"; case OSSL_CMP_PKIFAILUREINFO_badRecipientNonce: return "badRecipientNonce"; case OSSL_CMP_PKIFAILUREINFO_timeNotAvailable: return "timeNotAvailable"; case OSSL_CMP_PKIFAILUREINFO_unacceptedPolicy: return "unacceptedPolicy"; case OSSL_CMP_PKIFAILUREINFO_unacceptedExtension: return "unacceptedExtension"; case OSSL_CMP_PKIFAILUREINFO_addInfoNotAvailable: return "addInfoNotAvailable"; case OSSL_CMP_PKIFAILUREINFO_badSenderNonce: return "badSenderNonce"; case OSSL_CMP_PKIFAILUREINFO_badCertTemplate: return "badCertTemplate"; case OSSL_CMP_PKIFAILUREINFO_signerNotTrusted: return "signerNotTrusted"; case OSSL_CMP_PKIFAILUREINFO_transactionIdInUse: return "transactionIdInUse"; case OSSL_CMP_PKIFAILUREINFO_unsupportedVersion: return "unsupportedVersion"; case OSSL_CMP_PKIFAILUREINFO_notAuthorized: return "notAuthorized"; case OSSL_CMP_PKIFAILUREINFO_systemUnavail: return "systemUnavail"; case OSSL_CMP_PKIFAILUREINFO_systemFailure: return "systemFailure"; case OSSL_CMP_PKIFAILUREINFO_duplicateCertReq: return "duplicateCertReq"; default: return NULL; /* illegal failure number */ } } int ossl_cmp_pkisi_check_pkifailureinfo(const OSSL_CMP_PKISI *si, int bit_index) { if (!ossl_assert(si != NULL && si->failInfo != NULL)) return -1; if (bit_index < 0 || bit_index > OSSL_CMP_PKIFAILUREINFO_MAX) { ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_ARGS); return -1; } return ASN1_BIT_STRING_get_bit(si->failInfo, bit_index); } /*- * place human-readable error string created from PKIStatusInfo in given buffer * returns pointer to the same buffer containing the string, or NULL on error */ static char *snprint_PKIStatusInfo_parts(int status, int fail_info, const OSSL_CMP_PKIFREETEXT *status_strings, char *buf, size_t bufsize) { int failure; const char *status_string, *failure_string; ASN1_UTF8STRING *text; int i; int printed_chars; int failinfo_found = 0; int n_status_strings; char *write_ptr = buf; if (buf == NULL || status < 0 || (status_string = ossl_cmp_PKIStatus_to_string(status)) == NULL) return NULL; #define ADVANCE_BUFFER \ if (printed_chars < 0 || (size_t)printed_chars >= bufsize) \ return NULL; \ write_ptr += printed_chars; \ bufsize -= printed_chars; printed_chars = BIO_snprintf(write_ptr, bufsize, "%s", status_string); ADVANCE_BUFFER; /* * failInfo is optional and may be empty; * if present, print failInfo before statusString because it is more concise */ if (fail_info != -1 && fail_info != 0) { printed_chars = BIO_snprintf(write_ptr, bufsize, "; PKIFailureInfo: "); ADVANCE_BUFFER; for (failure = 0; failure <= OSSL_CMP_PKIFAILUREINFO_MAX; failure++) { if ((fail_info & (1 << failure)) != 0) { failure_string = CMP_PKIFAILUREINFO_to_string(failure); if (failure_string != NULL) { printed_chars = BIO_snprintf(write_ptr, bufsize, "%s%s", failinfo_found ? ", " : "", failure_string); ADVANCE_BUFFER; failinfo_found = 1; } } } } if (!failinfo_found && status != OSSL_CMP_PKISTATUS_accepted && status != OSSL_CMP_PKISTATUS_grantedWithMods) { printed_chars = BIO_snprintf(write_ptr, bufsize, "; "); ADVANCE_BUFFER; } /* statusString sequence is optional and may be empty */ n_status_strings = sk_ASN1_UTF8STRING_num(status_strings); if (n_status_strings > 0) { printed_chars = BIO_snprintf(write_ptr, bufsize, "; StatusString%s: ", n_status_strings > 1 ? "s" : ""); ADVANCE_BUFFER; for (i = 0; i < n_status_strings; i++) { text = sk_ASN1_UTF8STRING_value(status_strings, i); printed_chars = BIO_snprintf(write_ptr, bufsize, "\"%.*s\"%s", ASN1_STRING_length(text), ASN1_STRING_get0_data(text), i < n_status_strings - 1 ? ", " : ""); ADVANCE_BUFFER; } } #undef ADVANCE_BUFFER return buf; } char *OSSL_CMP_snprint_PKIStatusInfo(const OSSL_CMP_PKISI *statusInfo, char *buf, size_t bufsize) { int failure_info; if (statusInfo == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } failure_info = ossl_cmp_pkisi_get_pkifailureinfo(statusInfo); return snprint_PKIStatusInfo_parts(ASN1_INTEGER_get(statusInfo->status), failure_info, statusInfo->statusString, buf, bufsize); } char *OSSL_CMP_CTX_snprint_PKIStatus(const OSSL_CMP_CTX *ctx, char *buf, size_t bufsize) { if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } return snprint_PKIStatusInfo_parts(OSSL_CMP_CTX_get_status(ctx), OSSL_CMP_CTX_get_failInfoCode(ctx), OSSL_CMP_CTX_get0_statusString(ctx), buf, bufsize); } /*- * Creates a new PKIStatusInfo structure and fills it in * returns a pointer to the structure on success, NULL on error * note: strongly overlaps with TS_RESP_CTX_set_status_info() * and TS_RESP_CTX_add_failure_info() in ../ts/ts_rsp_sign.c */ OSSL_CMP_PKISI *OSSL_CMP_STATUSINFO_new(int status, int fail_info, const char *text) { OSSL_CMP_PKISI *si = OSSL_CMP_PKISI_new(); ASN1_UTF8STRING *utf8_text = NULL; int failure; if (si == NULL) goto err; if (!ASN1_INTEGER_set(si->status, status)) goto err; if (text != NULL) { if ((utf8_text = ASN1_UTF8STRING_new()) == NULL || !ASN1_STRING_set(utf8_text, text, -1)) goto err; if ((si->statusString = sk_ASN1_UTF8STRING_new_null()) == NULL) goto err; if (!sk_ASN1_UTF8STRING_push(si->statusString, utf8_text)) goto err; /* Ownership is lost. */ utf8_text = NULL; } for (failure = 0; failure <= OSSL_CMP_PKIFAILUREINFO_MAX; failure++) { if ((fail_info & (1 << failure)) != 0) { if (si->failInfo == NULL && (si->failInfo = ASN1_BIT_STRING_new()) == NULL) goto err; if (!ASN1_BIT_STRING_set_bit(si->failInfo, failure, 1)) goto err; } } return si; err: OSSL_CMP_PKISI_free(si); ASN1_UTF8STRING_free(utf8_text); return NULL; } diff --git a/crypto/cms/cms_env.c b/crypto/cms/cms_env.c index bd1f3e7345d4..99cf1dcb396c 100644 --- a/crypto/cms/cms_env.c +++ b/crypto/cms/cms_env.c @@ -1,1338 +1,1355 @@ /* * Copyright 2008-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/cryptlib.h" #include #include #include #include #include #include #include "internal/sizes.h" #include "crypto/asn1.h" #include "crypto/evp.h" #include "crypto/x509.h" #include "cms_local.h" /* CMS EnvelopedData Utilities */ static void cms_env_set_version(CMS_EnvelopedData *env); #define CMS_ENVELOPED_STANDARD 1 #define CMS_ENVELOPED_AUTH 2 -static int cms_get_enveloped_type(const CMS_ContentInfo *cms) +static int cms_get_enveloped_type_simple(const CMS_ContentInfo *cms) { int nid = OBJ_obj2nid(cms->contentType); switch (nid) { case NID_pkcs7_enveloped: return CMS_ENVELOPED_STANDARD; case NID_id_smime_ct_authEnvelopedData: return CMS_ENVELOPED_AUTH; default: - ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA); return 0; } } +static int cms_get_enveloped_type(const CMS_ContentInfo *cms) +{ + int ret = cms_get_enveloped_type_simple(cms); + + if (ret == 0) + ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA); + return ret; +} + +void ossl_cms_env_enc_content_free(const CMS_ContentInfo *cinf) +{ + if (cms_get_enveloped_type_simple(cinf) != 0) { + CMS_EncryptedContentInfo *ec = ossl_cms_get0_env_enc_content(cinf); + if (ec != NULL) + OPENSSL_clear_free(ec->key, ec->keylen); + } +} + CMS_EnvelopedData *ossl_cms_get0_enveloped(CMS_ContentInfo *cms) { if (OBJ_obj2nid(cms->contentType) != NID_pkcs7_enveloped) { ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA); return NULL; } return cms->d.envelopedData; } CMS_AuthEnvelopedData *ossl_cms_get0_auth_enveloped(CMS_ContentInfo *cms) { if (OBJ_obj2nid(cms->contentType) != NID_id_smime_ct_authEnvelopedData) { ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA); return NULL; } return cms->d.authEnvelopedData; } static CMS_EnvelopedData *cms_enveloped_data_init(CMS_ContentInfo *cms) { if (cms->d.other == NULL) { cms->d.envelopedData = M_ASN1_new_of(CMS_EnvelopedData); if (cms->d.envelopedData == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); return NULL; } cms->d.envelopedData->version = 0; cms->d.envelopedData->encryptedContentInfo->contentType = OBJ_nid2obj(NID_pkcs7_data); ASN1_OBJECT_free(cms->contentType); cms->contentType = OBJ_nid2obj(NID_pkcs7_enveloped); return cms->d.envelopedData; } return ossl_cms_get0_enveloped(cms); } static CMS_AuthEnvelopedData * cms_auth_enveloped_data_init(CMS_ContentInfo *cms) { if (cms->d.other == NULL) { cms->d.authEnvelopedData = M_ASN1_new_of(CMS_AuthEnvelopedData); if (cms->d.authEnvelopedData == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); return NULL; } /* Defined in RFC 5083 - Section 2.1. "AuthEnvelopedData Type" */ cms->d.authEnvelopedData->version = 0; cms->d.authEnvelopedData->authEncryptedContentInfo->contentType = OBJ_nid2obj(NID_pkcs7_data); ASN1_OBJECT_free(cms->contentType); cms->contentType = OBJ_nid2obj(NID_id_smime_ct_authEnvelopedData); return cms->d.authEnvelopedData; } return ossl_cms_get0_auth_enveloped(cms); } int ossl_cms_env_asn1_ctrl(CMS_RecipientInfo *ri, int cmd) { EVP_PKEY *pkey; int i; if (ri->type == CMS_RECIPINFO_TRANS) pkey = ri->d.ktri->pkey; else if (ri->type == CMS_RECIPINFO_AGREE) { EVP_PKEY_CTX *pctx = ri->d.kari->pctx; if (pctx == NULL) return 0; pkey = EVP_PKEY_CTX_get0_pkey(pctx); if (pkey == NULL) return 0; } else return 0; if (EVP_PKEY_is_a(pkey, "DHX") || EVP_PKEY_is_a(pkey, "DH")) return ossl_cms_dh_envelope(ri, cmd); else if (EVP_PKEY_is_a(pkey, "EC")) return ossl_cms_ecdh_envelope(ri, cmd); else if (EVP_PKEY_is_a(pkey, "RSA")) return ossl_cms_rsa_envelope(ri, cmd); /* Something else? We'll give engines etc a chance to handle this */ if (pkey->ameth == NULL || pkey->ameth->pkey_ctrl == NULL) return 1; i = pkey->ameth->pkey_ctrl(pkey, ASN1_PKEY_CTRL_CMS_ENVELOPE, cmd, ri); if (i == -2) { ERR_raise(ERR_LIB_CMS, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE); return 0; } if (i <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_CTRL_FAILURE); return 0; } return 1; } CMS_EncryptedContentInfo *ossl_cms_get0_env_enc_content(const CMS_ContentInfo *cms) { switch (cms_get_enveloped_type(cms)) { case CMS_ENVELOPED_STANDARD: return cms->d.envelopedData == NULL ? NULL : cms->d.envelopedData->encryptedContentInfo; case CMS_ENVELOPED_AUTH: return cms->d.authEnvelopedData == NULL ? NULL : cms->d.authEnvelopedData->authEncryptedContentInfo; default: return NULL; } } STACK_OF(CMS_RecipientInfo) *CMS_get0_RecipientInfos(CMS_ContentInfo *cms) { switch (cms_get_enveloped_type(cms)) { case CMS_ENVELOPED_STANDARD: return cms->d.envelopedData->recipientInfos; case CMS_ENVELOPED_AUTH: return cms->d.authEnvelopedData->recipientInfos; default: return NULL; } } void ossl_cms_RecipientInfos_set_cmsctx(CMS_ContentInfo *cms) { int i; CMS_RecipientInfo *ri; const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms); STACK_OF(CMS_RecipientInfo) *rinfos = CMS_get0_RecipientInfos(cms); for (i = 0; i < sk_CMS_RecipientInfo_num(rinfos); i++) { ri = sk_CMS_RecipientInfo_value(rinfos, i); if (ri != NULL) { switch (ri->type) { case CMS_RECIPINFO_AGREE: ri->d.kari->cms_ctx = ctx; break; case CMS_RECIPINFO_TRANS: ri->d.ktri->cms_ctx = ctx; ossl_x509_set0_libctx(ri->d.ktri->recip, ossl_cms_ctx_get0_libctx(ctx), ossl_cms_ctx_get0_propq(ctx)); break; case CMS_RECIPINFO_KEK: ri->d.kekri->cms_ctx = ctx; break; case CMS_RECIPINFO_PASS: ri->d.pwri->cms_ctx = ctx; break; default: break; } } } } int CMS_RecipientInfo_type(CMS_RecipientInfo *ri) { return ri->type; } EVP_PKEY_CTX *CMS_RecipientInfo_get0_pkey_ctx(CMS_RecipientInfo *ri) { if (ri->type == CMS_RECIPINFO_TRANS) return ri->d.ktri->pctx; else if (ri->type == CMS_RECIPINFO_AGREE) return ri->d.kari->pctx; return NULL; } CMS_ContentInfo *CMS_EnvelopedData_create_ex(const EVP_CIPHER *cipher, OSSL_LIB_CTX *libctx, const char *propq) { CMS_ContentInfo *cms; CMS_EnvelopedData *env; cms = CMS_ContentInfo_new_ex(libctx, propq); if (cms == NULL) goto merr; env = cms_enveloped_data_init(cms); if (env == NULL) goto merr; if (!ossl_cms_EncryptedContent_init(env->encryptedContentInfo, cipher, NULL, 0, ossl_cms_get0_cmsctx(cms))) goto merr; return cms; merr: CMS_ContentInfo_free(cms); ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); return NULL; } CMS_ContentInfo *CMS_EnvelopedData_create(const EVP_CIPHER *cipher) { return CMS_EnvelopedData_create_ex(cipher, NULL, NULL); } CMS_ContentInfo * CMS_AuthEnvelopedData_create_ex(const EVP_CIPHER *cipher, OSSL_LIB_CTX *libctx, const char *propq) { CMS_ContentInfo *cms; CMS_AuthEnvelopedData *aenv; cms = CMS_ContentInfo_new_ex(libctx, propq); if (cms == NULL) goto merr; aenv = cms_auth_enveloped_data_init(cms); if (aenv == NULL) goto merr; if (!ossl_cms_EncryptedContent_init(aenv->authEncryptedContentInfo, cipher, NULL, 0, ossl_cms_get0_cmsctx(cms))) goto merr; return cms; merr: CMS_ContentInfo_free(cms); ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); return NULL; } CMS_ContentInfo *CMS_AuthEnvelopedData_create(const EVP_CIPHER *cipher) { return CMS_AuthEnvelopedData_create_ex(cipher, NULL, NULL); } /* Key Transport Recipient Info (KTRI) routines */ /* Initialise a ktri based on passed certificate and key */ static int cms_RecipientInfo_ktri_init(CMS_RecipientInfo *ri, X509 *recip, EVP_PKEY *pk, unsigned int flags, const CMS_CTX *ctx) { CMS_KeyTransRecipientInfo *ktri; int idtype; ri->d.ktri = M_ASN1_new_of(CMS_KeyTransRecipientInfo); if (!ri->d.ktri) return 0; ri->type = CMS_RECIPINFO_TRANS; ktri = ri->d.ktri; ktri->cms_ctx = ctx; if (flags & CMS_USE_KEYID) { ktri->version = 2; idtype = CMS_RECIPINFO_KEYIDENTIFIER; } else { ktri->version = 0; idtype = CMS_RECIPINFO_ISSUER_SERIAL; } /* * Not a typo: RecipientIdentifier and SignerIdentifier are the same * structure. */ if (!ossl_cms_set1_SignerIdentifier(ktri->rid, recip, idtype, ctx)) return 0; X509_up_ref(recip); EVP_PKEY_up_ref(pk); ktri->pkey = pk; ktri->recip = recip; if (flags & CMS_KEY_PARAM) { ktri->pctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(ctx), ktri->pkey, ossl_cms_ctx_get0_propq(ctx)); if (ktri->pctx == NULL) return 0; if (EVP_PKEY_encrypt_init(ktri->pctx) <= 0) return 0; } else if (!ossl_cms_env_asn1_ctrl(ri, 0)) return 0; return 1; } /* * Add a recipient certificate using appropriate type of RecipientInfo */ CMS_RecipientInfo *CMS_add1_recipient(CMS_ContentInfo *cms, X509 *recip, EVP_PKEY *originatorPrivKey, X509 *originator, unsigned int flags) { CMS_RecipientInfo *ri = NULL; STACK_OF(CMS_RecipientInfo) *ris; EVP_PKEY *pk = NULL; const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms); ris = CMS_get0_RecipientInfos(cms); if (ris == NULL) goto err; /* Initialize recipient info */ ri = M_ASN1_new_of(CMS_RecipientInfo); if (ri == NULL) goto merr; pk = X509_get0_pubkey(recip); if (pk == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_GETTING_PUBLIC_KEY); goto err; } switch (ossl_cms_pkey_get_ri_type(pk)) { case CMS_RECIPINFO_TRANS: if (!cms_RecipientInfo_ktri_init(ri, recip, pk, flags, ctx)) goto err; break; case CMS_RECIPINFO_AGREE: if (!ossl_cms_RecipientInfo_kari_init(ri, recip, pk, originator, originatorPrivKey, flags, ctx)) goto err; break; default: ERR_raise(ERR_LIB_CMS, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE); goto err; } if (!sk_CMS_RecipientInfo_push(ris, ri)) goto merr; return ri; merr: ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); err: M_ASN1_free_of(ri, CMS_RecipientInfo); return NULL; } CMS_RecipientInfo *CMS_add1_recipient_cert(CMS_ContentInfo *cms, X509 *recip, unsigned int flags) { return CMS_add1_recipient(cms, recip, NULL, NULL, flags); } int CMS_RecipientInfo_ktri_get0_algs(CMS_RecipientInfo *ri, EVP_PKEY **pk, X509 **recip, X509_ALGOR **palg) { CMS_KeyTransRecipientInfo *ktri; if (ri->type != CMS_RECIPINFO_TRANS) { ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT); return 0; } ktri = ri->d.ktri; if (pk) *pk = ktri->pkey; if (recip) *recip = ktri->recip; if (palg) *palg = ktri->keyEncryptionAlgorithm; return 1; } int CMS_RecipientInfo_ktri_get0_signer_id(CMS_RecipientInfo *ri, ASN1_OCTET_STRING **keyid, X509_NAME **issuer, ASN1_INTEGER **sno) { CMS_KeyTransRecipientInfo *ktri; if (ri->type != CMS_RECIPINFO_TRANS) { ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT); return 0; } ktri = ri->d.ktri; return ossl_cms_SignerIdentifier_get0_signer_id(ktri->rid, keyid, issuer, sno); } int CMS_RecipientInfo_ktri_cert_cmp(CMS_RecipientInfo *ri, X509 *cert) { if (ri->type != CMS_RECIPINFO_TRANS) { ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT); return -2; } return ossl_cms_SignerIdentifier_cert_cmp(ri->d.ktri->rid, cert); } int CMS_RecipientInfo_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pkey) { if (ri->type != CMS_RECIPINFO_TRANS) { ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT); return 0; } EVP_PKEY_free(ri->d.ktri->pkey); ri->d.ktri->pkey = pkey; return 1; } /* Encrypt content key in key transport recipient info */ static int cms_RecipientInfo_ktri_encrypt(const CMS_ContentInfo *cms, CMS_RecipientInfo *ri) { CMS_KeyTransRecipientInfo *ktri; CMS_EncryptedContentInfo *ec; EVP_PKEY_CTX *pctx; unsigned char *ek = NULL; size_t eklen; const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms); int ret = 0; if (ri->type != CMS_RECIPINFO_TRANS) { ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT); return 0; } ktri = ri->d.ktri; ec = ossl_cms_get0_env_enc_content(cms); pctx = ktri->pctx; if (pctx) { if (!ossl_cms_env_asn1_ctrl(ri, 0)) goto err; } else { pctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(ctx), ktri->pkey, ossl_cms_ctx_get0_propq(ctx)); if (pctx == NULL) return 0; if (EVP_PKEY_encrypt_init(pctx) <= 0) goto err; } if (EVP_PKEY_encrypt(pctx, NULL, &eklen, ec->key, ec->keylen) <= 0) goto err; ek = OPENSSL_malloc(eklen); if (ek == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); goto err; } if (EVP_PKEY_encrypt(pctx, ek, &eklen, ec->key, ec->keylen) <= 0) goto err; ASN1_STRING_set0(ktri->encryptedKey, ek, eklen); ek = NULL; ret = 1; err: EVP_PKEY_CTX_free(pctx); ktri->pctx = NULL; OPENSSL_free(ek); return ret; } /* Decrypt content key from KTRI */ static int cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri) { CMS_KeyTransRecipientInfo *ktri = ri->d.ktri; EVP_PKEY *pkey = ktri->pkey; unsigned char *ek = NULL; size_t eklen; int ret = 0; size_t fixlen = 0; const EVP_CIPHER *cipher = NULL; EVP_CIPHER *fetched_cipher = NULL; CMS_EncryptedContentInfo *ec; const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms); OSSL_LIB_CTX *libctx = ossl_cms_ctx_get0_libctx(ctx); const char *propq = ossl_cms_ctx_get0_propq(ctx); ec = ossl_cms_get0_env_enc_content(cms); if (ktri->pkey == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_PRIVATE_KEY); return 0; } if (cms->d.envelopedData->encryptedContentInfo->havenocert && !cms->d.envelopedData->encryptedContentInfo->debug) { X509_ALGOR *calg = ec->contentEncryptionAlgorithm; char name[OSSL_MAX_NAME_SIZE]; OBJ_obj2txt(name, sizeof(name), calg->algorithm, 0); (void)ERR_set_mark(); fetched_cipher = EVP_CIPHER_fetch(libctx, name, propq); if (fetched_cipher != NULL) cipher = fetched_cipher; else cipher = EVP_get_cipherbyobj(calg->algorithm); if (cipher == NULL) { (void)ERR_clear_last_mark(); ERR_raise(ERR_LIB_CMS, CMS_R_UNKNOWN_CIPHER); return 0; } (void)ERR_pop_to_mark(); fixlen = EVP_CIPHER_get_key_length(cipher); EVP_CIPHER_free(fetched_cipher); } ktri->pctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq); if (ktri->pctx == NULL) goto err; if (EVP_PKEY_decrypt_init(ktri->pctx) <= 0) goto err; if (!ossl_cms_env_asn1_ctrl(ri, 1)) goto err; if (EVP_PKEY_decrypt(ktri->pctx, NULL, &eklen, ktri->encryptedKey->data, ktri->encryptedKey->length) <= 0) goto err; ek = OPENSSL_malloc(eklen); if (ek == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); goto err; } if (EVP_PKEY_decrypt(ktri->pctx, ek, &eklen, ktri->encryptedKey->data, ktri->encryptedKey->length) <= 0 || eklen == 0 || (fixlen != 0 && eklen != fixlen)) { ERR_raise(ERR_LIB_CMS, CMS_R_CMS_LIB); goto err; } ret = 1; OPENSSL_clear_free(ec->key, ec->keylen); ec->key = ek; ec->keylen = eklen; err: EVP_PKEY_CTX_free(ktri->pctx); ktri->pctx = NULL; if (!ret) OPENSSL_free(ek); return ret; } /* Key Encrypted Key (KEK) RecipientInfo routines */ int CMS_RecipientInfo_kekri_id_cmp(CMS_RecipientInfo *ri, const unsigned char *id, size_t idlen) { ASN1_OCTET_STRING tmp_os; CMS_KEKRecipientInfo *kekri; if (ri->type != CMS_RECIPINFO_KEK) { ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEK); return -2; } kekri = ri->d.kekri; tmp_os.type = V_ASN1_OCTET_STRING; tmp_os.flags = 0; tmp_os.data = (unsigned char *)id; tmp_os.length = (int)idlen; return ASN1_OCTET_STRING_cmp(&tmp_os, kekri->kekid->keyIdentifier); } /* For now hard code AES key wrap info */ static size_t aes_wrap_keylen(int nid) { switch (nid) { case NID_id_aes128_wrap: return 16; case NID_id_aes192_wrap: return 24; case NID_id_aes256_wrap: return 32; default: return 0; } } CMS_RecipientInfo *CMS_add0_recipient_key(CMS_ContentInfo *cms, int nid, unsigned char *key, size_t keylen, unsigned char *id, size_t idlen, ASN1_GENERALIZEDTIME *date, ASN1_OBJECT *otherTypeId, ASN1_TYPE *otherType) { CMS_RecipientInfo *ri = NULL; CMS_KEKRecipientInfo *kekri; STACK_OF(CMS_RecipientInfo) *ris = CMS_get0_RecipientInfos(cms); if (ris == NULL) goto err; if (nid == NID_undef) { switch (keylen) { case 16: nid = NID_id_aes128_wrap; break; case 24: nid = NID_id_aes192_wrap; break; case 32: nid = NID_id_aes256_wrap; break; default: ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH); goto err; } } else { size_t exp_keylen = aes_wrap_keylen(nid); if (!exp_keylen) { ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_KEK_ALGORITHM); goto err; } if (keylen != exp_keylen) { ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH); goto err; } } /* Initialize recipient info */ ri = M_ASN1_new_of(CMS_RecipientInfo); if (!ri) goto merr; ri->d.kekri = M_ASN1_new_of(CMS_KEKRecipientInfo); if (!ri->d.kekri) goto merr; ri->type = CMS_RECIPINFO_KEK; kekri = ri->d.kekri; if (otherTypeId) { kekri->kekid->other = M_ASN1_new_of(CMS_OtherKeyAttribute); if (kekri->kekid->other == NULL) goto merr; } if (!sk_CMS_RecipientInfo_push(ris, ri)) goto merr; /* After this point no calls can fail */ kekri->version = 4; kekri->key = key; kekri->keylen = keylen; ASN1_STRING_set0(kekri->kekid->keyIdentifier, id, idlen); kekri->kekid->date = date; if (kekri->kekid->other) { kekri->kekid->other->keyAttrId = otherTypeId; kekri->kekid->other->keyAttr = otherType; } X509_ALGOR_set0(kekri->keyEncryptionAlgorithm, OBJ_nid2obj(nid), V_ASN1_UNDEF, NULL); return ri; merr: ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); err: M_ASN1_free_of(ri, CMS_RecipientInfo); return NULL; } int CMS_RecipientInfo_kekri_get0_id(CMS_RecipientInfo *ri, X509_ALGOR **palg, ASN1_OCTET_STRING **pid, ASN1_GENERALIZEDTIME **pdate, ASN1_OBJECT **potherid, ASN1_TYPE **pothertype) { CMS_KEKIdentifier *rkid; if (ri->type != CMS_RECIPINFO_KEK) { ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEK); return 0; } rkid = ri->d.kekri->kekid; if (palg) *palg = ri->d.kekri->keyEncryptionAlgorithm; if (pid) *pid = rkid->keyIdentifier; if (pdate) *pdate = rkid->date; if (potherid) { if (rkid->other) *potherid = rkid->other->keyAttrId; else *potherid = NULL; } if (pothertype) { if (rkid->other) *pothertype = rkid->other->keyAttr; else *pothertype = NULL; } return 1; } int CMS_RecipientInfo_set0_key(CMS_RecipientInfo *ri, unsigned char *key, size_t keylen) { CMS_KEKRecipientInfo *kekri; if (ri->type != CMS_RECIPINFO_KEK) { ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEK); return 0; } kekri = ri->d.kekri; kekri->key = key; kekri->keylen = keylen; return 1; } static EVP_CIPHER *cms_get_key_wrap_cipher(size_t keylen, const CMS_CTX *ctx) { const char *alg = NULL; switch(keylen) { case 16: alg = "AES-128-WRAP"; break; case 24: alg = "AES-192-WRAP"; break; case 32: alg = "AES-256-WRAP"; break; default: return NULL; } return EVP_CIPHER_fetch(ossl_cms_ctx_get0_libctx(ctx), alg, ossl_cms_ctx_get0_propq(ctx)); } /* Encrypt content key in KEK recipient info */ static int cms_RecipientInfo_kekri_encrypt(const CMS_ContentInfo *cms, CMS_RecipientInfo *ri) { CMS_EncryptedContentInfo *ec; CMS_KEKRecipientInfo *kekri; unsigned char *wkey = NULL; int wkeylen; int r = 0; EVP_CIPHER *cipher = NULL; int outlen = 0; EVP_CIPHER_CTX *ctx = NULL; const CMS_CTX *cms_ctx = ossl_cms_get0_cmsctx(cms); ec = ossl_cms_get0_env_enc_content(cms); if (ec == NULL) return 0; kekri = ri->d.kekri; if (kekri->key == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_KEY); return 0; } cipher = cms_get_key_wrap_cipher(kekri->keylen, cms_ctx); if (cipher == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH); goto err; } /* 8 byte prefix for AES wrap ciphers */ wkey = OPENSSL_malloc(ec->keylen + 8); if (wkey == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); goto err; } ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); goto err; } EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW); if (!EVP_EncryptInit_ex(ctx, cipher, NULL, kekri->key, NULL) || !EVP_EncryptUpdate(ctx, wkey, &wkeylen, ec->key, ec->keylen) || !EVP_EncryptFinal_ex(ctx, wkey + wkeylen, &outlen)) { ERR_raise(ERR_LIB_CMS, CMS_R_WRAP_ERROR); goto err; } wkeylen += outlen; if (!ossl_assert((size_t)wkeylen == ec->keylen + 8)) { ERR_raise(ERR_LIB_CMS, CMS_R_WRAP_ERROR); goto err; } ASN1_STRING_set0(kekri->encryptedKey, wkey, wkeylen); r = 1; err: EVP_CIPHER_free(cipher); if (!r) OPENSSL_free(wkey); EVP_CIPHER_CTX_free(ctx); return r; } /* Decrypt content key in KEK recipient info */ static int cms_RecipientInfo_kekri_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri) { CMS_EncryptedContentInfo *ec; CMS_KEKRecipientInfo *kekri; unsigned char *ukey = NULL; int ukeylen; int r = 0, wrap_nid; EVP_CIPHER *cipher = NULL; int outlen = 0; EVP_CIPHER_CTX *ctx = NULL; const CMS_CTX *cms_ctx = ossl_cms_get0_cmsctx(cms); ec = ossl_cms_get0_env_enc_content(cms); if (ec == NULL) return 0; kekri = ri->d.kekri; if (!kekri->key) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_KEY); return 0; } wrap_nid = OBJ_obj2nid(kekri->keyEncryptionAlgorithm->algorithm); if (aes_wrap_keylen(wrap_nid) != kekri->keylen) { ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH); return 0; } /* If encrypted key length is invalid don't bother */ if (kekri->encryptedKey->length < 16) { ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_ENCRYPTED_KEY_LENGTH); goto err; } cipher = cms_get_key_wrap_cipher(kekri->keylen, cms_ctx); if (cipher == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH); goto err; } ukey = OPENSSL_malloc(kekri->encryptedKey->length - 8); if (ukey == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); goto err; } ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); goto err; } if (!EVP_DecryptInit_ex(ctx, cipher, NULL, kekri->key, NULL) || !EVP_DecryptUpdate(ctx, ukey, &ukeylen, kekri->encryptedKey->data, kekri->encryptedKey->length) || !EVP_DecryptFinal_ex(ctx, ukey + ukeylen, &outlen)) { ERR_raise(ERR_LIB_CMS, CMS_R_UNWRAP_ERROR); goto err; } ukeylen += outlen; OPENSSL_clear_free(ec->key, ec->keylen); ec->key = ukey; ec->keylen = ukeylen; r = 1; err: EVP_CIPHER_free(cipher); if (!r) OPENSSL_free(ukey); EVP_CIPHER_CTX_free(ctx); return r; } int CMS_RecipientInfo_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri) { switch (ri->type) { case CMS_RECIPINFO_TRANS: return cms_RecipientInfo_ktri_decrypt(cms, ri); case CMS_RECIPINFO_KEK: return cms_RecipientInfo_kekri_decrypt(cms, ri); case CMS_RECIPINFO_PASS: return ossl_cms_RecipientInfo_pwri_crypt(cms, ri, 0); default: ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE); return 0; } } int CMS_RecipientInfo_encrypt(const CMS_ContentInfo *cms, CMS_RecipientInfo *ri) { switch (ri->type) { case CMS_RECIPINFO_TRANS: return cms_RecipientInfo_ktri_encrypt(cms, ri); case CMS_RECIPINFO_AGREE: return ossl_cms_RecipientInfo_kari_encrypt(cms, ri); case CMS_RECIPINFO_KEK: return cms_RecipientInfo_kekri_encrypt(cms, ri); case CMS_RECIPINFO_PASS: return ossl_cms_RecipientInfo_pwri_crypt(cms, ri, 1); default: ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_RECIPIENT_TYPE); return 0; } } /* Check structures and fixup version numbers (if necessary) */ static void cms_env_set_originfo_version(CMS_EnvelopedData *env) { CMS_OriginatorInfo *org = env->originatorInfo; int i; if (org == NULL) return; for (i = 0; i < sk_CMS_CertificateChoices_num(org->certificates); i++) { CMS_CertificateChoices *cch; cch = sk_CMS_CertificateChoices_value(org->certificates, i); if (cch->type == CMS_CERTCHOICE_OTHER) { env->version = 4; return; } else if (cch->type == CMS_CERTCHOICE_V2ACERT) { if (env->version < 3) env->version = 3; } } for (i = 0; i < sk_CMS_RevocationInfoChoice_num(org->crls); i++) { CMS_RevocationInfoChoice *rch; rch = sk_CMS_RevocationInfoChoice_value(org->crls, i); if (rch->type == CMS_REVCHOICE_OTHER) { env->version = 4; return; } } } static void cms_env_set_version(CMS_EnvelopedData *env) { int i; CMS_RecipientInfo *ri; /* * Can't set version higher than 4 so if 4 or more already nothing to do. */ if (env->version >= 4) return; cms_env_set_originfo_version(env); if (env->version >= 3) return; for (i = 0; i < sk_CMS_RecipientInfo_num(env->recipientInfos); i++) { ri = sk_CMS_RecipientInfo_value(env->recipientInfos, i); if (ri->type == CMS_RECIPINFO_PASS || ri->type == CMS_RECIPINFO_OTHER) { env->version = 3; return; } else if (ri->type != CMS_RECIPINFO_TRANS || ri->d.ktri->version != 0) { env->version = 2; } } if (env->originatorInfo || env->unprotectedAttrs) env->version = 2; if (env->version == 2) return; env->version = 0; } static int cms_env_encrypt_content_key(const CMS_ContentInfo *cms, STACK_OF(CMS_RecipientInfo) *ris) { int i; CMS_RecipientInfo *ri; for (i = 0; i < sk_CMS_RecipientInfo_num(ris); i++) { ri = sk_CMS_RecipientInfo_value(ris, i); if (CMS_RecipientInfo_encrypt(cms, ri) <= 0) return -1; } return 1; } static void cms_env_clear_ec(CMS_EncryptedContentInfo *ec) { ec->cipher = NULL; OPENSSL_clear_free(ec->key, ec->keylen); ec->key = NULL; ec->keylen = 0; } static BIO *cms_EnvelopedData_Decryption_init_bio(CMS_ContentInfo *cms) { CMS_EncryptedContentInfo *ec = cms->d.envelopedData->encryptedContentInfo; BIO *contentBio = ossl_cms_EncryptedContent_init_bio(ec, ossl_cms_get0_cmsctx(cms)); EVP_CIPHER_CTX *ctx = NULL; if (contentBio == NULL) return NULL; BIO_get_cipher_ctx(contentBio, &ctx); if (ctx == NULL) { BIO_free(contentBio); return NULL; } /* * If the selected cipher supports unprotected attributes, * deal with it using special ctrl function */ if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ctx)) & EVP_CIPH_FLAG_CIPHER_WITH_MAC) != 0 && EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_PROCESS_UNPROTECTED, 0, cms->d.envelopedData->unprotectedAttrs) <= 0) { BIO_free(contentBio); return NULL; } return contentBio; } static BIO *cms_EnvelopedData_Encryption_init_bio(CMS_ContentInfo *cms) { CMS_EncryptedContentInfo *ec; STACK_OF(CMS_RecipientInfo) *rinfos; int ok = 0; BIO *ret; CMS_EnvelopedData *env = cms->d.envelopedData; /* Get BIO first to set up key */ ec = env->encryptedContentInfo; ret = ossl_cms_EncryptedContent_init_bio(ec, ossl_cms_get0_cmsctx(cms)); /* If error end of processing */ if (!ret) return ret; /* Now encrypt content key according to each RecipientInfo type */ rinfos = env->recipientInfos; if (cms_env_encrypt_content_key(cms, rinfos) < 0) { ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_SETTING_RECIPIENTINFO); goto err; } /* And finally set the version */ cms_env_set_version(env); ok = 1; err: cms_env_clear_ec(ec); if (ok) return ret; BIO_free(ret); return NULL; } BIO *ossl_cms_EnvelopedData_init_bio(CMS_ContentInfo *cms) { if (cms->d.envelopedData->encryptedContentInfo->cipher != NULL) { /* If cipher is set it's encryption */ return cms_EnvelopedData_Encryption_init_bio(cms); } /* If cipher is not set it's decryption */ return cms_EnvelopedData_Decryption_init_bio(cms); } BIO *ossl_cms_AuthEnvelopedData_init_bio(CMS_ContentInfo *cms) { CMS_EncryptedContentInfo *ec; STACK_OF(CMS_RecipientInfo) *rinfos; int ok = 0; BIO *ret; CMS_AuthEnvelopedData *aenv = cms->d.authEnvelopedData; /* Get BIO first to set up key */ ec = aenv->authEncryptedContentInfo; /* Set tag for decryption */ if (ec->cipher == NULL) { ec->tag = aenv->mac->data; ec->taglen = aenv->mac->length; } ret = ossl_cms_EncryptedContent_init_bio(ec, ossl_cms_get0_cmsctx(cms)); /* If error or no cipher end of processing */ if (ret == NULL || ec->cipher == NULL) return ret; /* Now encrypt content key according to each RecipientInfo type */ rinfos = aenv->recipientInfos; if (cms_env_encrypt_content_key(cms, rinfos) < 0) { ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_SETTING_RECIPIENTINFO); goto err; } /* And finally set the version */ aenv->version = 0; ok = 1; err: cms_env_clear_ec(ec); if (ok) return ret; BIO_free(ret); return NULL; } int ossl_cms_EnvelopedData_final(CMS_ContentInfo *cms, BIO *chain) { CMS_EnvelopedData *env = NULL; EVP_CIPHER_CTX *ctx = NULL; BIO *mbio = BIO_find_type(chain, BIO_TYPE_CIPHER); env = ossl_cms_get0_enveloped(cms); if (env == NULL) return 0; if (mbio == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_NOT_FOUND); return 0; } BIO_get_cipher_ctx(mbio, &ctx); /* * If the selected cipher supports unprotected attributes, * deal with it using special ctrl function */ if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ctx)) & EVP_CIPH_FLAG_CIPHER_WITH_MAC) != 0) { if (env->unprotectedAttrs == NULL) env->unprotectedAttrs = sk_X509_ATTRIBUTE_new_null(); if (env->unprotectedAttrs == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); return 0; } if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_PROCESS_UNPROTECTED, 1, env->unprotectedAttrs) <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_CTRL_FAILURE); return 0; } } cms_env_set_version(cms->d.envelopedData); return 1; } int ossl_cms_AuthEnvelopedData_final(CMS_ContentInfo *cms, BIO *cmsbio) { EVP_CIPHER_CTX *ctx; unsigned char *tag = NULL; int taglen, ok = 0; BIO_get_cipher_ctx(cmsbio, &ctx); /* * The tag is set only for encryption. There is nothing to do for * decryption. */ if (!EVP_CIPHER_CTX_is_encrypting(ctx)) return 1; taglen = EVP_CIPHER_CTX_get_tag_length(ctx); if (taglen <= 0 || (tag = OPENSSL_malloc(taglen)) == NULL || EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag) <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_CIPHER_GET_TAG); goto err; } if (!ASN1_OCTET_STRING_set(cms->d.authEnvelopedData->mac, tag, taglen)) goto err; ok = 1; err: OPENSSL_free(tag); return ok; } /* * Get RecipientInfo type (if any) supported by a key (public or private). To * retain compatibility with previous behaviour if the ctrl value isn't * supported we assume key transport. */ int ossl_cms_pkey_get_ri_type(EVP_PKEY *pk) { /* Check types that we know about */ if (EVP_PKEY_is_a(pk, "DH")) return CMS_RECIPINFO_AGREE; else if (EVP_PKEY_is_a(pk, "DHX")) return CMS_RECIPINFO_AGREE; else if (EVP_PKEY_is_a(pk, "DSA")) return CMS_RECIPINFO_NONE; else if (EVP_PKEY_is_a(pk, "EC")) return CMS_RECIPINFO_AGREE; else if (EVP_PKEY_is_a(pk, "RSA")) return CMS_RECIPINFO_TRANS; /* * Otherwise this might ben an engine implementation, so see if we can get * the type from the ameth. */ if (pk->ameth && pk->ameth->pkey_ctrl) { int i, r; i = pk->ameth->pkey_ctrl(pk, ASN1_PKEY_CTRL_CMS_RI_TYPE, 0, &r); if (i > 0) return r; } return CMS_RECIPINFO_TRANS; } int ossl_cms_pkey_is_ri_type_supported(EVP_PKEY *pk, int ri_type) { int supportedRiType; if (pk->ameth != NULL && pk->ameth->pkey_ctrl != NULL) { int i, r; i = pk->ameth->pkey_ctrl(pk, ASN1_PKEY_CTRL_CMS_IS_RI_TYPE_SUPPORTED, ri_type, &r); if (i > 0) return r; } supportedRiType = ossl_cms_pkey_get_ri_type(pk); if (supportedRiType < 0) return 0; return (supportedRiType == ri_type); } diff --git a/crypto/cms/cms_lib.c b/crypto/cms/cms_lib.c index 1d2c5bc42288..8b135e95aacc 100644 --- a/crypto/cms/cms_lib.c +++ b/crypto/cms/cms_lib.c @@ -1,736 +1,733 @@ /* * Copyright 2008-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include #include #include #include #include #include #include #include #include "internal/sizes.h" #include "crypto/x509.h" #include "cms_local.h" static STACK_OF(CMS_CertificateChoices) **cms_get0_certificate_choices(CMS_ContentInfo *cms); IMPLEMENT_ASN1_PRINT_FUNCTION(CMS_ContentInfo) CMS_ContentInfo *d2i_CMS_ContentInfo(CMS_ContentInfo **a, const unsigned char **in, long len) { CMS_ContentInfo *ci; const CMS_CTX *ctx = ossl_cms_get0_cmsctx(a == NULL ? NULL : *a); ci = (CMS_ContentInfo *)ASN1_item_d2i_ex((ASN1_VALUE **)a, in, len, (CMS_ContentInfo_it()), ossl_cms_ctx_get0_libctx(ctx), ossl_cms_ctx_get0_propq(ctx)); if (ci != NULL) { ERR_set_mark(); ossl_cms_resolve_libctx(ci); ERR_pop_to_mark(); } return ci; } int i2d_CMS_ContentInfo(const CMS_ContentInfo *a, unsigned char **out) { return ASN1_item_i2d((const ASN1_VALUE *)a, out, (CMS_ContentInfo_it())); } CMS_ContentInfo *CMS_ContentInfo_new_ex(OSSL_LIB_CTX *libctx, const char *propq) { CMS_ContentInfo *ci; ci = (CMS_ContentInfo *)ASN1_item_new_ex(ASN1_ITEM_rptr(CMS_ContentInfo), libctx, propq); if (ci != NULL) { ci->ctx.libctx = libctx; ci->ctx.propq = NULL; if (propq != NULL) { ci->ctx.propq = OPENSSL_strdup(propq); if (ci->ctx.propq == NULL) { CMS_ContentInfo_free(ci); ci = NULL; ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE); } } } return ci; } CMS_ContentInfo *CMS_ContentInfo_new(void) { return CMS_ContentInfo_new_ex(NULL, NULL); } void CMS_ContentInfo_free(CMS_ContentInfo *cms) { if (cms != NULL) { - CMS_EncryptedContentInfo *ec = ossl_cms_get0_env_enc_content(cms); - - if (ec != NULL) - OPENSSL_clear_free(ec->key, ec->keylen); + ossl_cms_env_enc_content_free(cms); OPENSSL_free(cms->ctx.propq); ASN1_item_free((ASN1_VALUE *)cms, ASN1_ITEM_rptr(CMS_ContentInfo)); } } const CMS_CTX *ossl_cms_get0_cmsctx(const CMS_ContentInfo *cms) { return cms != NULL ? &cms->ctx : NULL; } OSSL_LIB_CTX *ossl_cms_ctx_get0_libctx(const CMS_CTX *ctx) { return ctx != NULL ? ctx->libctx : NULL; } const char *ossl_cms_ctx_get0_propq(const CMS_CTX *ctx) { return ctx != NULL ? ctx->propq : NULL; } void ossl_cms_resolve_libctx(CMS_ContentInfo *ci) { int i; CMS_CertificateChoices *cch; STACK_OF(CMS_CertificateChoices) **pcerts; const CMS_CTX *ctx = ossl_cms_get0_cmsctx(ci); OSSL_LIB_CTX *libctx = ossl_cms_ctx_get0_libctx(ctx); const char *propq = ossl_cms_ctx_get0_propq(ctx); ossl_cms_SignerInfos_set_cmsctx(ci); ossl_cms_RecipientInfos_set_cmsctx(ci); pcerts = cms_get0_certificate_choices(ci); if (pcerts != NULL) { for (i = 0; i < sk_CMS_CertificateChoices_num(*pcerts); i++) { cch = sk_CMS_CertificateChoices_value(*pcerts, i); if (cch->type == CMS_CERTCHOICE_CERT) ossl_x509_set0_libctx(cch->d.certificate, libctx, propq); } } } const ASN1_OBJECT *CMS_get0_type(const CMS_ContentInfo *cms) { return cms->contentType; } CMS_ContentInfo *ossl_cms_Data_create(OSSL_LIB_CTX *libctx, const char *propq) { CMS_ContentInfo *cms = CMS_ContentInfo_new_ex(libctx, propq); if (cms != NULL) { cms->contentType = OBJ_nid2obj(NID_pkcs7_data); /* Never detached */ CMS_set_detached(cms, 0); } return cms; } BIO *ossl_cms_content_bio(CMS_ContentInfo *cms) { ASN1_OCTET_STRING **pos = CMS_get0_content(cms); if (pos == NULL) return NULL; /* If content detached data goes nowhere: create NULL BIO */ if (*pos == NULL) return BIO_new(BIO_s_null()); /* * If content not detached and created return memory BIO */ if (*pos == NULL || ((*pos)->flags == ASN1_STRING_FLAG_CONT)) return BIO_new(BIO_s_mem()); /* Else content was read in: return read only BIO for it */ return BIO_new_mem_buf((*pos)->data, (*pos)->length); } BIO *CMS_dataInit(CMS_ContentInfo *cms, BIO *icont) { BIO *cmsbio, *cont; if (icont) cont = icont; else cont = ossl_cms_content_bio(cms); if (!cont) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_CONTENT); return NULL; } switch (OBJ_obj2nid(cms->contentType)) { case NID_pkcs7_data: return cont; case NID_pkcs7_signed: cmsbio = ossl_cms_SignedData_init_bio(cms); break; case NID_pkcs7_digest: cmsbio = ossl_cms_DigestedData_init_bio(cms); break; #ifdef ZLIB case NID_id_smime_ct_compressedData: cmsbio = ossl_cms_CompressedData_init_bio(cms); break; #endif case NID_pkcs7_encrypted: cmsbio = ossl_cms_EncryptedData_init_bio(cms); break; case NID_pkcs7_enveloped: cmsbio = ossl_cms_EnvelopedData_init_bio(cms); break; case NID_id_smime_ct_authEnvelopedData: cmsbio = ossl_cms_AuthEnvelopedData_init_bio(cms); break; default: ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_TYPE); goto err; } if (cmsbio) return BIO_push(cmsbio, cont); err: if (!icont) BIO_free(cont); return NULL; } /* unfortunately cannot constify SMIME_write_ASN1() due to this function */ int CMS_dataFinal(CMS_ContentInfo *cms, BIO *cmsbio) { ASN1_OCTET_STRING **pos = CMS_get0_content(cms); if (pos == NULL) return 0; /* If embedded content find memory BIO and set content */ if (*pos && ((*pos)->flags & ASN1_STRING_FLAG_CONT)) { BIO *mbio; unsigned char *cont; long contlen; mbio = BIO_find_type(cmsbio, BIO_TYPE_MEM); if (!mbio) { ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_NOT_FOUND); return 0; } contlen = BIO_get_mem_data(mbio, &cont); /* Set bio as read only so its content can't be clobbered */ BIO_set_flags(mbio, BIO_FLAGS_MEM_RDONLY); BIO_set_mem_eof_return(mbio, 0); ASN1_STRING_set0(*pos, cont, contlen); (*pos)->flags &= ~ASN1_STRING_FLAG_CONT; } switch (OBJ_obj2nid(cms->contentType)) { case NID_pkcs7_data: case NID_pkcs7_encrypted: case NID_id_smime_ct_compressedData: /* Nothing to do */ return 1; case NID_pkcs7_enveloped: return ossl_cms_EnvelopedData_final(cms, cmsbio); case NID_id_smime_ct_authEnvelopedData: return ossl_cms_AuthEnvelopedData_final(cms, cmsbio); case NID_pkcs7_signed: return ossl_cms_SignedData_final(cms, cmsbio); case NID_pkcs7_digest: return ossl_cms_DigestedData_do_final(cms, cmsbio, 0); default: ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_TYPE); return 0; } } /* * Return an OCTET STRING pointer to content. This allows it to be accessed * or set later. */ ASN1_OCTET_STRING **CMS_get0_content(CMS_ContentInfo *cms) { switch (OBJ_obj2nid(cms->contentType)) { case NID_pkcs7_data: return &cms->d.data; case NID_pkcs7_signed: return &cms->d.signedData->encapContentInfo->eContent; case NID_pkcs7_enveloped: return &cms->d.envelopedData->encryptedContentInfo->encryptedContent; case NID_pkcs7_digest: return &cms->d.digestedData->encapContentInfo->eContent; case NID_pkcs7_encrypted: return &cms->d.encryptedData->encryptedContentInfo->encryptedContent; case NID_id_smime_ct_authEnvelopedData: return &cms->d.authEnvelopedData->authEncryptedContentInfo ->encryptedContent; case NID_id_smime_ct_authData: return &cms->d.authenticatedData->encapContentInfo->eContent; case NID_id_smime_ct_compressedData: return &cms->d.compressedData->encapContentInfo->eContent; default: if (cms->d.other->type == V_ASN1_OCTET_STRING) return &cms->d.other->value.octet_string; ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_CONTENT_TYPE); return NULL; } } /* * Return an ASN1_OBJECT pointer to content type. This allows it to be * accessed or set later. */ static ASN1_OBJECT **cms_get0_econtent_type(CMS_ContentInfo *cms) { switch (OBJ_obj2nid(cms->contentType)) { case NID_pkcs7_signed: return &cms->d.signedData->encapContentInfo->eContentType; case NID_pkcs7_enveloped: return &cms->d.envelopedData->encryptedContentInfo->contentType; case NID_pkcs7_digest: return &cms->d.digestedData->encapContentInfo->eContentType; case NID_pkcs7_encrypted: return &cms->d.encryptedData->encryptedContentInfo->contentType; case NID_id_smime_ct_authEnvelopedData: return &cms->d.authEnvelopedData->authEncryptedContentInfo ->contentType; case NID_id_smime_ct_authData: return &cms->d.authenticatedData->encapContentInfo->eContentType; case NID_id_smime_ct_compressedData: return &cms->d.compressedData->encapContentInfo->eContentType; default: ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_CONTENT_TYPE); return NULL; } } const ASN1_OBJECT *CMS_get0_eContentType(CMS_ContentInfo *cms) { ASN1_OBJECT **petype; petype = cms_get0_econtent_type(cms); if (petype) return *petype; return NULL; } int CMS_set1_eContentType(CMS_ContentInfo *cms, const ASN1_OBJECT *oid) { ASN1_OBJECT **petype, *etype; petype = cms_get0_econtent_type(cms); if (petype == NULL) return 0; if (oid == NULL) return 1; etype = OBJ_dup(oid); if (etype == NULL) return 0; ASN1_OBJECT_free(*petype); *petype = etype; return 1; } int CMS_is_detached(CMS_ContentInfo *cms) { ASN1_OCTET_STRING **pos; pos = CMS_get0_content(cms); if (pos == NULL) return -1; if (*pos != NULL) return 0; return 1; } int CMS_set_detached(CMS_ContentInfo *cms, int detached) { ASN1_OCTET_STRING **pos; pos = CMS_get0_content(cms); if (pos == NULL) return 0; if (detached) { ASN1_OCTET_STRING_free(*pos); *pos = NULL; return 1; } if (*pos == NULL) *pos = ASN1_OCTET_STRING_new(); if (*pos != NULL) { /* * NB: special flag to show content is created and not read in. */ (*pos)->flags |= ASN1_STRING_FLAG_CONT; return 1; } ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); return 0; } /* Create a digest BIO from an X509_ALGOR structure */ BIO *ossl_cms_DigestAlgorithm_init_bio(X509_ALGOR *digestAlgorithm, const CMS_CTX *ctx) { BIO *mdbio = NULL; const ASN1_OBJECT *digestoid; const EVP_MD *digest = NULL; EVP_MD *fetched_digest = NULL; char alg[OSSL_MAX_NAME_SIZE]; X509_ALGOR_get0(&digestoid, NULL, NULL, digestAlgorithm); OBJ_obj2txt(alg, sizeof(alg), digestoid, 0); (void)ERR_set_mark(); fetched_digest = EVP_MD_fetch(ossl_cms_ctx_get0_libctx(ctx), alg, ossl_cms_ctx_get0_propq(ctx)); if (fetched_digest != NULL) digest = fetched_digest; else digest = EVP_get_digestbyobj(digestoid); if (digest == NULL) { (void)ERR_clear_last_mark(); ERR_raise(ERR_LIB_CMS, CMS_R_UNKNOWN_DIGEST_ALGORITHM); goto err; } (void)ERR_pop_to_mark(); mdbio = BIO_new(BIO_f_md()); if (mdbio == NULL || BIO_set_md(mdbio, digest) <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_MD_BIO_INIT_ERROR); goto err; } EVP_MD_free(fetched_digest); return mdbio; err: EVP_MD_free(fetched_digest); BIO_free(mdbio); return NULL; } /* Locate a message digest content from a BIO chain based on SignerInfo */ int ossl_cms_DigestAlgorithm_find_ctx(EVP_MD_CTX *mctx, BIO *chain, X509_ALGOR *mdalg) { int nid; const ASN1_OBJECT *mdoid; X509_ALGOR_get0(&mdoid, NULL, NULL, mdalg); nid = OBJ_obj2nid(mdoid); /* Look for digest type to match signature */ for (;;) { EVP_MD_CTX *mtmp; chain = BIO_find_type(chain, BIO_TYPE_MD); if (chain == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_MATCHING_DIGEST); return 0; } BIO_get_md_ctx(chain, &mtmp); if (EVP_MD_CTX_get_type(mtmp) == nid /* * Workaround for broken implementations that use signature * algorithm OID instead of digest. */ || EVP_MD_get_pkey_type(EVP_MD_CTX_get0_md(mtmp)) == nid) return EVP_MD_CTX_copy_ex(mctx, mtmp); chain = BIO_next(chain); } } static STACK_OF(CMS_CertificateChoices) **cms_get0_certificate_choices(CMS_ContentInfo *cms) { switch (OBJ_obj2nid(cms->contentType)) { case NID_pkcs7_signed: return &cms->d.signedData->certificates; case NID_pkcs7_enveloped: if (cms->d.envelopedData->originatorInfo == NULL) return NULL; return &cms->d.envelopedData->originatorInfo->certificates; case NID_id_smime_ct_authEnvelopedData: if (cms->d.authEnvelopedData->originatorInfo == NULL) return NULL; return &cms->d.authEnvelopedData->originatorInfo->certificates; default: ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_CONTENT_TYPE); return NULL; } } CMS_CertificateChoices *CMS_add0_CertificateChoices(CMS_ContentInfo *cms) { STACK_OF(CMS_CertificateChoices) **pcerts; CMS_CertificateChoices *cch; pcerts = cms_get0_certificate_choices(cms); if (pcerts == NULL) return NULL; if (*pcerts == NULL) *pcerts = sk_CMS_CertificateChoices_new_null(); if (*pcerts == NULL) return NULL; cch = M_ASN1_new_of(CMS_CertificateChoices); if (!cch) return NULL; if (!sk_CMS_CertificateChoices_push(*pcerts, cch)) { M_ASN1_free_of(cch, CMS_CertificateChoices); return NULL; } return cch; } int CMS_add0_cert(CMS_ContentInfo *cms, X509 *cert) { CMS_CertificateChoices *cch; STACK_OF(CMS_CertificateChoices) **pcerts; int i; pcerts = cms_get0_certificate_choices(cms); if (pcerts == NULL) return 0; for (i = 0; i < sk_CMS_CertificateChoices_num(*pcerts); i++) { cch = sk_CMS_CertificateChoices_value(*pcerts, i); if (cch->type == CMS_CERTCHOICE_CERT) { if (!X509_cmp(cch->d.certificate, cert)) { ERR_raise(ERR_LIB_CMS, CMS_R_CERTIFICATE_ALREADY_PRESENT); return 0; } } } cch = CMS_add0_CertificateChoices(cms); if (!cch) return 0; cch->type = CMS_CERTCHOICE_CERT; cch->d.certificate = cert; return 1; } int CMS_add1_cert(CMS_ContentInfo *cms, X509 *cert) { int r; r = CMS_add0_cert(cms, cert); if (r > 0) X509_up_ref(cert); return r; } static STACK_OF(CMS_RevocationInfoChoice) **cms_get0_revocation_choices(CMS_ContentInfo *cms) { switch (OBJ_obj2nid(cms->contentType)) { case NID_pkcs7_signed: return &cms->d.signedData->crls; case NID_pkcs7_enveloped: if (cms->d.envelopedData->originatorInfo == NULL) return NULL; return &cms->d.envelopedData->originatorInfo->crls; case NID_id_smime_ct_authEnvelopedData: if (cms->d.authEnvelopedData->originatorInfo == NULL) return NULL; return &cms->d.authEnvelopedData->originatorInfo->crls; default: ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_CONTENT_TYPE); return NULL; } } CMS_RevocationInfoChoice *CMS_add0_RevocationInfoChoice(CMS_ContentInfo *cms) { STACK_OF(CMS_RevocationInfoChoice) **pcrls; CMS_RevocationInfoChoice *rch; pcrls = cms_get0_revocation_choices(cms); if (pcrls == NULL) return NULL; if (*pcrls == NULL) *pcrls = sk_CMS_RevocationInfoChoice_new_null(); if (*pcrls == NULL) return NULL; rch = M_ASN1_new_of(CMS_RevocationInfoChoice); if (rch == NULL) return NULL; if (!sk_CMS_RevocationInfoChoice_push(*pcrls, rch)) { M_ASN1_free_of(rch, CMS_RevocationInfoChoice); return NULL; } return rch; } int CMS_add0_crl(CMS_ContentInfo *cms, X509_CRL *crl) { CMS_RevocationInfoChoice *rch; rch = CMS_add0_RevocationInfoChoice(cms); if (!rch) return 0; rch->type = CMS_REVCHOICE_CRL; rch->d.crl = crl; return 1; } int CMS_add1_crl(CMS_ContentInfo *cms, X509_CRL *crl) { if (!X509_CRL_up_ref(crl)) return 0; if (CMS_add0_crl(cms, crl)) return 1; X509_CRL_free(crl); return 0; } STACK_OF(X509) *CMS_get1_certs(CMS_ContentInfo *cms) { STACK_OF(X509) *certs = NULL; CMS_CertificateChoices *cch; STACK_OF(CMS_CertificateChoices) **pcerts; int i; pcerts = cms_get0_certificate_choices(cms); if (pcerts == NULL) return NULL; for (i = 0; i < sk_CMS_CertificateChoices_num(*pcerts); i++) { cch = sk_CMS_CertificateChoices_value(*pcerts, i); if (cch->type == 0) { if (!ossl_x509_add_cert_new(&certs, cch->d.certificate, X509_ADD_FLAG_UP_REF)) { sk_X509_pop_free(certs, X509_free); return NULL; } } } return certs; } STACK_OF(X509_CRL) *CMS_get1_crls(CMS_ContentInfo *cms) { STACK_OF(X509_CRL) *crls = NULL; STACK_OF(CMS_RevocationInfoChoice) **pcrls; CMS_RevocationInfoChoice *rch; int i; pcrls = cms_get0_revocation_choices(cms); if (pcrls == NULL) return NULL; for (i = 0; i < sk_CMS_RevocationInfoChoice_num(*pcrls); i++) { rch = sk_CMS_RevocationInfoChoice_value(*pcrls, i); if (rch->type == 0) { if (!crls) { crls = sk_X509_CRL_new_null(); if (!crls) return NULL; } if (!sk_X509_CRL_push(crls, rch->d.crl)) { sk_X509_CRL_pop_free(crls, X509_CRL_free); return NULL; } X509_CRL_up_ref(rch->d.crl); } } return crls; } int ossl_cms_ias_cert_cmp(CMS_IssuerAndSerialNumber *ias, X509 *cert) { int ret; ret = X509_NAME_cmp(ias->issuer, X509_get_issuer_name(cert)); if (ret) return ret; return ASN1_INTEGER_cmp(ias->serialNumber, X509_get0_serialNumber(cert)); } int ossl_cms_keyid_cert_cmp(ASN1_OCTET_STRING *keyid, X509 *cert) { const ASN1_OCTET_STRING *cert_keyid = X509_get0_subject_key_id(cert); if (cert_keyid == NULL) return -1; return ASN1_OCTET_STRING_cmp(keyid, cert_keyid); } int ossl_cms_set1_ias(CMS_IssuerAndSerialNumber **pias, X509 *cert) { CMS_IssuerAndSerialNumber *ias; ias = M_ASN1_new_of(CMS_IssuerAndSerialNumber); if (!ias) goto err; if (!X509_NAME_set(&ias->issuer, X509_get_issuer_name(cert))) goto err; if (!ASN1_STRING_copy(ias->serialNumber, X509_get0_serialNumber(cert))) goto err; M_ASN1_free_of(*pias, CMS_IssuerAndSerialNumber); *pias = ias; return 1; err: M_ASN1_free_of(ias, CMS_IssuerAndSerialNumber); ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); return 0; } int ossl_cms_set1_keyid(ASN1_OCTET_STRING **pkeyid, X509 *cert) { ASN1_OCTET_STRING *keyid = NULL; const ASN1_OCTET_STRING *cert_keyid; cert_keyid = X509_get0_subject_key_id(cert); if (cert_keyid == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_CERTIFICATE_HAS_NO_KEYID); return 0; } keyid = ASN1_STRING_dup(cert_keyid); if (!keyid) { ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); return 0; } ASN1_OCTET_STRING_free(*pkeyid); *pkeyid = keyid; return 1; } diff --git a/crypto/cms/cms_local.h b/crypto/cms/cms_local.h index 15b4a29ce03d..253f6819e435 100644 --- a/crypto/cms/cms_local.h +++ b/crypto/cms/cms_local.h @@ -1,503 +1,504 @@ /* - * Copyright 2008-2021 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2008-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifndef OSSL_CRYPTO_CMS_LOCAL_H # define OSSL_CRYPTO_CMS_LOCAL_H # include /* * Cryptographic message syntax (CMS) structures: taken from RFC3852 */ /* Forward references */ typedef struct CMS_IssuerAndSerialNumber_st CMS_IssuerAndSerialNumber; typedef struct CMS_EncapsulatedContentInfo_st CMS_EncapsulatedContentInfo; typedef struct CMS_SignerIdentifier_st CMS_SignerIdentifier; typedef struct CMS_SignedData_st CMS_SignedData; typedef struct CMS_OtherRevocationInfoFormat_st CMS_OtherRevocationInfoFormat; typedef struct CMS_OriginatorInfo_st CMS_OriginatorInfo; typedef struct CMS_EncryptedContentInfo_st CMS_EncryptedContentInfo; typedef struct CMS_EnvelopedData_st CMS_EnvelopedData; typedef struct CMS_DigestedData_st CMS_DigestedData; typedef struct CMS_EncryptedData_st CMS_EncryptedData; typedef struct CMS_AuthenticatedData_st CMS_AuthenticatedData; typedef struct CMS_AuthEnvelopedData_st CMS_AuthEnvelopedData; typedef struct CMS_CompressedData_st CMS_CompressedData; typedef struct CMS_OtherCertificateFormat_st CMS_OtherCertificateFormat; typedef struct CMS_KeyTransRecipientInfo_st CMS_KeyTransRecipientInfo; typedef struct CMS_OriginatorPublicKey_st CMS_OriginatorPublicKey; typedef struct CMS_OriginatorIdentifierOrKey_st CMS_OriginatorIdentifierOrKey; typedef struct CMS_KeyAgreeRecipientInfo_st CMS_KeyAgreeRecipientInfo; typedef struct CMS_RecipientKeyIdentifier_st CMS_RecipientKeyIdentifier; typedef struct CMS_KeyAgreeRecipientIdentifier_st CMS_KeyAgreeRecipientIdentifier; typedef struct CMS_KEKIdentifier_st CMS_KEKIdentifier; typedef struct CMS_KEKRecipientInfo_st CMS_KEKRecipientInfo; typedef struct CMS_PasswordRecipientInfo_st CMS_PasswordRecipientInfo; typedef struct CMS_OtherRecipientInfo_st CMS_OtherRecipientInfo; typedef struct CMS_ReceiptsFrom_st CMS_ReceiptsFrom; typedef struct CMS_CTX_st CMS_CTX; struct CMS_CTX_st { OSSL_LIB_CTX *libctx; char *propq; }; struct CMS_ContentInfo_st { ASN1_OBJECT *contentType; union { ASN1_OCTET_STRING *data; CMS_SignedData *signedData; CMS_EnvelopedData *envelopedData; CMS_DigestedData *digestedData; CMS_EncryptedData *encryptedData; CMS_AuthEnvelopedData *authEnvelopedData; CMS_AuthenticatedData *authenticatedData; CMS_CompressedData *compressedData; ASN1_TYPE *other; /* Other types ... */ void *otherData; } d; CMS_CTX ctx; }; DEFINE_STACK_OF(CMS_CertificateChoices) struct CMS_SignedData_st { int32_t version; STACK_OF(X509_ALGOR) *digestAlgorithms; CMS_EncapsulatedContentInfo *encapContentInfo; STACK_OF(CMS_CertificateChoices) *certificates; STACK_OF(CMS_RevocationInfoChoice) *crls; STACK_OF(CMS_SignerInfo) *signerInfos; }; struct CMS_EncapsulatedContentInfo_st { ASN1_OBJECT *eContentType; ASN1_OCTET_STRING *eContent; /* Set to 1 if incomplete structure only part set up */ int partial; }; struct CMS_SignerInfo_st { int32_t version; CMS_SignerIdentifier *sid; X509_ALGOR *digestAlgorithm; STACK_OF(X509_ATTRIBUTE) *signedAttrs; X509_ALGOR *signatureAlgorithm; ASN1_OCTET_STRING *signature; STACK_OF(X509_ATTRIBUTE) *unsignedAttrs; /* Signing certificate and key */ X509 *signer; EVP_PKEY *pkey; /* Digest and public key context for alternative parameters */ EVP_MD_CTX *mctx; EVP_PKEY_CTX *pctx; const CMS_CTX *cms_ctx; }; struct CMS_SignerIdentifier_st { int type; union { CMS_IssuerAndSerialNumber *issuerAndSerialNumber; ASN1_OCTET_STRING *subjectKeyIdentifier; } d; }; struct CMS_EnvelopedData_st { int32_t version; CMS_OriginatorInfo *originatorInfo; STACK_OF(CMS_RecipientInfo) *recipientInfos; CMS_EncryptedContentInfo *encryptedContentInfo; STACK_OF(X509_ATTRIBUTE) *unprotectedAttrs; }; struct CMS_OriginatorInfo_st { STACK_OF(CMS_CertificateChoices) *certificates; STACK_OF(CMS_RevocationInfoChoice) *crls; }; struct CMS_EncryptedContentInfo_st { ASN1_OBJECT *contentType; X509_ALGOR *contentEncryptionAlgorithm; ASN1_OCTET_STRING *encryptedContent; /* Content encryption algorithm, key and tag */ const EVP_CIPHER *cipher; unsigned char *key; size_t keylen; unsigned char *tag; size_t taglen; /* Set to 1 if we are debugging decrypt and don't fake keys for MMA */ int debug; /* Set to 1 if we have no cert and need extra safety measures for MMA */ int havenocert; }; struct CMS_RecipientInfo_st { int type; union { CMS_KeyTransRecipientInfo *ktri; CMS_KeyAgreeRecipientInfo *kari; CMS_KEKRecipientInfo *kekri; CMS_PasswordRecipientInfo *pwri; CMS_OtherRecipientInfo *ori; } d; }; typedef CMS_SignerIdentifier CMS_RecipientIdentifier; struct CMS_KeyTransRecipientInfo_st { int32_t version; CMS_RecipientIdentifier *rid; X509_ALGOR *keyEncryptionAlgorithm; ASN1_OCTET_STRING *encryptedKey; /* Recipient Key and cert */ X509 *recip; EVP_PKEY *pkey; /* Public key context for this operation */ EVP_PKEY_CTX *pctx; const CMS_CTX *cms_ctx; }; struct CMS_KeyAgreeRecipientInfo_st { int32_t version; CMS_OriginatorIdentifierOrKey *originator; ASN1_OCTET_STRING *ukm; X509_ALGOR *keyEncryptionAlgorithm; STACK_OF(CMS_RecipientEncryptedKey) *recipientEncryptedKeys; /* Public key context associated with current operation */ EVP_PKEY_CTX *pctx; /* Cipher context for CEK wrapping */ EVP_CIPHER_CTX *ctx; const CMS_CTX *cms_ctx; }; struct CMS_OriginatorIdentifierOrKey_st { int type; union { CMS_IssuerAndSerialNumber *issuerAndSerialNumber; ASN1_OCTET_STRING *subjectKeyIdentifier; CMS_OriginatorPublicKey *originatorKey; } d; }; struct CMS_OriginatorPublicKey_st { X509_ALGOR *algorithm; ASN1_BIT_STRING *publicKey; }; struct CMS_RecipientEncryptedKey_st { CMS_KeyAgreeRecipientIdentifier *rid; ASN1_OCTET_STRING *encryptedKey; /* Public key associated with this recipient */ EVP_PKEY *pkey; }; struct CMS_KeyAgreeRecipientIdentifier_st { int type; union { CMS_IssuerAndSerialNumber *issuerAndSerialNumber; CMS_RecipientKeyIdentifier *rKeyId; } d; }; struct CMS_RecipientKeyIdentifier_st { ASN1_OCTET_STRING *subjectKeyIdentifier; ASN1_GENERALIZEDTIME *date; CMS_OtherKeyAttribute *other; }; struct CMS_KEKRecipientInfo_st { int32_t version; CMS_KEKIdentifier *kekid; X509_ALGOR *keyEncryptionAlgorithm; ASN1_OCTET_STRING *encryptedKey; /* Extra info: symmetric key to use */ unsigned char *key; size_t keylen; const CMS_CTX *cms_ctx; }; struct CMS_KEKIdentifier_st { ASN1_OCTET_STRING *keyIdentifier; ASN1_GENERALIZEDTIME *date; CMS_OtherKeyAttribute *other; }; struct CMS_PasswordRecipientInfo_st { int32_t version; X509_ALGOR *keyDerivationAlgorithm; X509_ALGOR *keyEncryptionAlgorithm; ASN1_OCTET_STRING *encryptedKey; /* Extra info: password to use */ unsigned char *pass; size_t passlen; const CMS_CTX *cms_ctx; }; struct CMS_OtherRecipientInfo_st { ASN1_OBJECT *oriType; ASN1_TYPE *oriValue; }; struct CMS_DigestedData_st { int32_t version; X509_ALGOR *digestAlgorithm; CMS_EncapsulatedContentInfo *encapContentInfo; ASN1_OCTET_STRING *digest; }; struct CMS_EncryptedData_st { int32_t version; CMS_EncryptedContentInfo *encryptedContentInfo; STACK_OF(X509_ATTRIBUTE) *unprotectedAttrs; }; struct CMS_AuthenticatedData_st { int32_t version; CMS_OriginatorInfo *originatorInfo; STACK_OF(CMS_RecipientInfo) *recipientInfos; X509_ALGOR *macAlgorithm; X509_ALGOR *digestAlgorithm; CMS_EncapsulatedContentInfo *encapContentInfo; STACK_OF(X509_ATTRIBUTE) *authAttrs; ASN1_OCTET_STRING *mac; STACK_OF(X509_ATTRIBUTE) *unauthAttrs; }; struct CMS_AuthEnvelopedData_st { int32_t version; CMS_OriginatorInfo *originatorInfo; STACK_OF(CMS_RecipientInfo) *recipientInfos; CMS_EncryptedContentInfo *authEncryptedContentInfo; STACK_OF(X509_ATTRIBUTE) *authAttrs; ASN1_OCTET_STRING *mac; STACK_OF(X509_ATTRIBUTE) *unauthAttrs; }; struct CMS_CompressedData_st { int32_t version; X509_ALGOR *compressionAlgorithm; STACK_OF(CMS_RecipientInfo) *recipientInfos; CMS_EncapsulatedContentInfo *encapContentInfo; }; struct CMS_RevocationInfoChoice_st { int type; union { X509_CRL *crl; CMS_OtherRevocationInfoFormat *other; } d; }; # define CMS_REVCHOICE_CRL 0 # define CMS_REVCHOICE_OTHER 1 struct CMS_OtherRevocationInfoFormat_st { ASN1_OBJECT *otherRevInfoFormat; ASN1_TYPE *otherRevInfo; }; struct CMS_CertificateChoices { int type; union { X509 *certificate; ASN1_STRING *extendedCertificate; /* Obsolete */ ASN1_STRING *v1AttrCert; /* Left encoded for now */ ASN1_STRING *v2AttrCert; /* Left encoded for now */ CMS_OtherCertificateFormat *other; } d; }; # define CMS_CERTCHOICE_CERT 0 # define CMS_CERTCHOICE_EXCERT 1 # define CMS_CERTCHOICE_V1ACERT 2 # define CMS_CERTCHOICE_V2ACERT 3 # define CMS_CERTCHOICE_OTHER 4 struct CMS_OtherCertificateFormat_st { ASN1_OBJECT *otherCertFormat; ASN1_TYPE *otherCert; }; /* * This is also defined in pkcs7.h but we duplicate it to allow the CMS code * to be independent of PKCS#7 */ struct CMS_IssuerAndSerialNumber_st { X509_NAME *issuer; ASN1_INTEGER *serialNumber; }; struct CMS_OtherKeyAttribute_st { ASN1_OBJECT *keyAttrId; ASN1_TYPE *keyAttr; }; /* ESS structures */ struct CMS_ReceiptRequest_st { ASN1_OCTET_STRING *signedContentIdentifier; CMS_ReceiptsFrom *receiptsFrom; STACK_OF(GENERAL_NAMES) *receiptsTo; }; struct CMS_ReceiptsFrom_st { int type; union { int32_t allOrFirstTier; STACK_OF(GENERAL_NAMES) *receiptList; } d; }; struct CMS_Receipt_st { int32_t version; ASN1_OBJECT *contentType; ASN1_OCTET_STRING *signedContentIdentifier; ASN1_OCTET_STRING *originatorSignatureValue; }; DECLARE_ASN1_FUNCTIONS(CMS_ContentInfo) DECLARE_ASN1_ITEM(CMS_SignerInfo) DECLARE_ASN1_ITEM(CMS_IssuerAndSerialNumber) DECLARE_ASN1_ITEM(CMS_Attributes_Sign) DECLARE_ASN1_ITEM(CMS_Attributes_Verify) DECLARE_ASN1_ITEM(CMS_RecipientInfo) DECLARE_ASN1_ITEM(CMS_PasswordRecipientInfo) DECLARE_ASN1_ALLOC_FUNCTIONS(CMS_IssuerAndSerialNumber) # define CMS_SIGNERINFO_ISSUER_SERIAL 0 # define CMS_SIGNERINFO_KEYIDENTIFIER 1 # define CMS_RECIPINFO_ISSUER_SERIAL 0 # define CMS_RECIPINFO_KEYIDENTIFIER 1 # define CMS_REK_ISSUER_SERIAL 0 # define CMS_REK_KEYIDENTIFIER 1 # define CMS_OIK_ISSUER_SERIAL 0 # define CMS_OIK_KEYIDENTIFIER 1 # define CMS_OIK_PUBKEY 2 BIO *ossl_cms_content_bio(CMS_ContentInfo *cms); const CMS_CTX *ossl_cms_get0_cmsctx(const CMS_ContentInfo *cms); OSSL_LIB_CTX *ossl_cms_ctx_get0_libctx(const CMS_CTX *ctx); const char *ossl_cms_ctx_get0_propq(const CMS_CTX *ctx); void ossl_cms_resolve_libctx(CMS_ContentInfo *ci); CMS_ContentInfo *ossl_cms_Data_create(OSSL_LIB_CTX *ctx, const char *propq); CMS_ContentInfo *ossl_cms_DigestedData_create(const EVP_MD *md, OSSL_LIB_CTX *libctx, const char *propq); BIO *ossl_cms_DigestedData_init_bio(const CMS_ContentInfo *cms); int ossl_cms_DigestedData_do_final(const CMS_ContentInfo *cms, BIO *chain, int verify); BIO *ossl_cms_SignedData_init_bio(CMS_ContentInfo *cms); int ossl_cms_SignedData_final(CMS_ContentInfo *cms, BIO *chain); int ossl_cms_set1_SignerIdentifier(CMS_SignerIdentifier *sid, X509 *cert, int type, const CMS_CTX *ctx); int ossl_cms_SignerIdentifier_get0_signer_id(CMS_SignerIdentifier *sid, ASN1_OCTET_STRING **keyid, X509_NAME **issuer, ASN1_INTEGER **sno); int ossl_cms_SignerIdentifier_cert_cmp(CMS_SignerIdentifier *sid, X509 *cert); CMS_ContentInfo *ossl_cms_CompressedData_create(int comp_nid, OSSL_LIB_CTX *libctx, const char *propq); BIO *ossl_cms_CompressedData_init_bio(const CMS_ContentInfo *cms); BIO *ossl_cms_DigestAlgorithm_init_bio(X509_ALGOR *digestAlgorithm, const CMS_CTX *ctx); int ossl_cms_DigestAlgorithm_find_ctx(EVP_MD_CTX *mctx, BIO *chain, X509_ALGOR *mdalg); int ossl_cms_ias_cert_cmp(CMS_IssuerAndSerialNumber *ias, X509 *cert); int ossl_cms_keyid_cert_cmp(ASN1_OCTET_STRING *keyid, X509 *cert); int ossl_cms_set1_ias(CMS_IssuerAndSerialNumber **pias, X509 *cert); int ossl_cms_set1_keyid(ASN1_OCTET_STRING **pkeyid, X509 *cert); BIO *ossl_cms_EncryptedContent_init_bio(CMS_EncryptedContentInfo *ec, const CMS_CTX *ctx); BIO *ossl_cms_EncryptedData_init_bio(const CMS_ContentInfo *cms); int ossl_cms_EncryptedContent_init(CMS_EncryptedContentInfo *ec, const EVP_CIPHER *cipher, const unsigned char *key, size_t keylen, const CMS_CTX *ctx); int ossl_cms_Receipt_verify(CMS_ContentInfo *cms, CMS_ContentInfo *req_cms); int ossl_cms_msgSigDigest_add1(CMS_SignerInfo *dest, CMS_SignerInfo *src); ASN1_OCTET_STRING *ossl_cms_encode_Receipt(CMS_SignerInfo *si); BIO *ossl_cms_EnvelopedData_init_bio(CMS_ContentInfo *cms); int ossl_cms_EnvelopedData_final(CMS_ContentInfo *cms, BIO *chain); BIO *ossl_cms_AuthEnvelopedData_init_bio(CMS_ContentInfo *cms); int ossl_cms_AuthEnvelopedData_final(CMS_ContentInfo *cms, BIO *cmsbio); +void ossl_cms_env_enc_content_free(const CMS_ContentInfo *cinf); CMS_EnvelopedData *ossl_cms_get0_enveloped(CMS_ContentInfo *cms); CMS_AuthEnvelopedData *ossl_cms_get0_auth_enveloped(CMS_ContentInfo *cms); CMS_EncryptedContentInfo *ossl_cms_get0_env_enc_content(const CMS_ContentInfo *cms); /* RecipientInfo routines */ int ossl_cms_env_asn1_ctrl(CMS_RecipientInfo *ri, int cmd); int ossl_cms_pkey_get_ri_type(EVP_PKEY *pk); int ossl_cms_pkey_is_ri_type_supported(EVP_PKEY *pk, int ri_type); void ossl_cms_RecipientInfos_set_cmsctx(CMS_ContentInfo *cms); /* KARI routines */ int ossl_cms_RecipientInfo_kari_init(CMS_RecipientInfo *ri, X509 *recip, EVP_PKEY *recipPubKey, X509 *originator, EVP_PKEY *originatorPrivKey, unsigned int flags, const CMS_CTX *ctx); int ossl_cms_RecipientInfo_kari_encrypt(const CMS_ContentInfo *cms, CMS_RecipientInfo *ri); /* PWRI routines */ int ossl_cms_RecipientInfo_pwri_crypt(const CMS_ContentInfo *cms, CMS_RecipientInfo *ri, int en_de); /* SignerInfo routines */ int ossl_cms_si_check_attributes(const CMS_SignerInfo *si); void ossl_cms_SignerInfos_set_cmsctx(CMS_ContentInfo *cms); /* ESS routines */ int ossl_cms_check_signing_certs(const CMS_SignerInfo *si, const STACK_OF(X509) *chain); int ossl_cms_dh_envelope(CMS_RecipientInfo *ri, int decrypt); int ossl_cms_ecdh_envelope(CMS_RecipientInfo *ri, int decrypt); int ossl_cms_rsa_envelope(CMS_RecipientInfo *ri, int decrypt); int ossl_cms_ecdsa_dsa_sign(CMS_SignerInfo *si, int verify); int ossl_cms_rsa_sign(CMS_SignerInfo *si, int verify); DECLARE_ASN1_ITEM(CMS_CertificateChoices) DECLARE_ASN1_ITEM(CMS_DigestedData) DECLARE_ASN1_ITEM(CMS_EncryptedData) DECLARE_ASN1_ITEM(CMS_EnvelopedData) DECLARE_ASN1_ITEM(CMS_AuthEnvelopedData) DECLARE_ASN1_ITEM(CMS_KEKRecipientInfo) DECLARE_ASN1_ITEM(CMS_KeyAgreeRecipientInfo) DECLARE_ASN1_ITEM(CMS_KeyTransRecipientInfo) DECLARE_ASN1_ITEM(CMS_OriginatorPublicKey) DECLARE_ASN1_ITEM(CMS_OtherKeyAttribute) DECLARE_ASN1_ITEM(CMS_Receipt) DECLARE_ASN1_ITEM(CMS_ReceiptRequest) DECLARE_ASN1_ITEM(CMS_RecipientEncryptedKey) DECLARE_ASN1_ITEM(CMS_RecipientKeyIdentifier) DECLARE_ASN1_ITEM(CMS_RevocationInfoChoice) DECLARE_ASN1_ITEM(CMS_SignedData) DECLARE_ASN1_ITEM(CMS_CompressedData) #endif diff --git a/crypto/cms/cms_sd.c b/crypto/cms/cms_sd.c index 34c021bba64a..53c8e378f318 100644 --- a/crypto/cms/cms_sd.c +++ b/crypto/cms/cms_sd.c @@ -1,1091 +1,1091 @@ /* - * Copyright 2008-2021 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2008-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/cryptlib.h" #include #include #include #include #include #include #include #include "internal/sizes.h" #include "crypto/asn1.h" #include "crypto/evp.h" #include "crypto/ess.h" #include "crypto/x509.h" /* for ossl_x509_add_cert_new() */ #include "cms_local.h" /* CMS SignedData Utilities */ static CMS_SignedData *cms_get0_signed(CMS_ContentInfo *cms) { if (OBJ_obj2nid(cms->contentType) != NID_pkcs7_signed) { ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA); return NULL; } return cms->d.signedData; } static CMS_SignedData *cms_signed_data_init(CMS_ContentInfo *cms) { if (cms->d.other == NULL) { cms->d.signedData = M_ASN1_new_of(CMS_SignedData); if (!cms->d.signedData) { ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); return NULL; } cms->d.signedData->version = 1; cms->d.signedData->encapContentInfo->eContentType = OBJ_nid2obj(NID_pkcs7_data); cms->d.signedData->encapContentInfo->partial = 1; ASN1_OBJECT_free(cms->contentType); cms->contentType = OBJ_nid2obj(NID_pkcs7_signed); return cms->d.signedData; } return cms_get0_signed(cms); } /* Just initialise SignedData e.g. for certs only structure */ int CMS_SignedData_init(CMS_ContentInfo *cms) { if (cms_signed_data_init(cms)) return 1; else return 0; } /* Check structures and fixup version numbers (if necessary) */ static void cms_sd_set_version(CMS_SignedData *sd) { int i; CMS_CertificateChoices *cch; CMS_RevocationInfoChoice *rch; CMS_SignerInfo *si; for (i = 0; i < sk_CMS_CertificateChoices_num(sd->certificates); i++) { cch = sk_CMS_CertificateChoices_value(sd->certificates, i); if (cch->type == CMS_CERTCHOICE_OTHER) { if (sd->version < 5) sd->version = 5; } else if (cch->type == CMS_CERTCHOICE_V2ACERT) { if (sd->version < 4) sd->version = 4; } else if (cch->type == CMS_CERTCHOICE_V1ACERT) { if (sd->version < 3) sd->version = 3; } } for (i = 0; i < sk_CMS_RevocationInfoChoice_num(sd->crls); i++) { rch = sk_CMS_RevocationInfoChoice_value(sd->crls, i); if (rch->type == CMS_REVCHOICE_OTHER) { if (sd->version < 5) sd->version = 5; } } if ((OBJ_obj2nid(sd->encapContentInfo->eContentType) != NID_pkcs7_data) && (sd->version < 3)) sd->version = 3; for (i = 0; i < sk_CMS_SignerInfo_num(sd->signerInfos); i++) { si = sk_CMS_SignerInfo_value(sd->signerInfos, i); if (si->sid->type == CMS_SIGNERINFO_KEYIDENTIFIER) { if (si->version < 3) si->version = 3; if (sd->version < 3) sd->version = 3; } else if (si->version < 1) si->version = 1; } if (sd->version < 1) sd->version = 1; } /* * RFC 5652 Section 11.1 Content Type * The content-type attribute within signed-data MUST * 1) be present if there are signed attributes * 2) match the content type in the signed-data, * 3) be a signed attribute. * 4) not have more than one copy of the attribute. * * Note that since the CMS_SignerInfo_sign() always adds the "signing time" * attribute, the content type attribute MUST be added also. * Assumptions: This assumes that the attribute does not already exist. */ static int cms_set_si_contentType_attr(CMS_ContentInfo *cms, CMS_SignerInfo *si) { ASN1_OBJECT *ctype = cms->d.signedData->encapContentInfo->eContentType; /* Add the contentType attribute */ return CMS_signed_add1_attr_by_NID(si, NID_pkcs9_contentType, V_ASN1_OBJECT, ctype, -1) > 0; } /* Copy an existing messageDigest value */ static int cms_copy_messageDigest(CMS_ContentInfo *cms, CMS_SignerInfo *si) { STACK_OF(CMS_SignerInfo) *sinfos; CMS_SignerInfo *sitmp; int i; sinfos = CMS_get0_SignerInfos(cms); for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) { ASN1_OCTET_STRING *messageDigest; sitmp = sk_CMS_SignerInfo_value(sinfos, i); if (sitmp == si) continue; if (CMS_signed_get_attr_count(sitmp) < 0) continue; if (OBJ_cmp(si->digestAlgorithm->algorithm, sitmp->digestAlgorithm->algorithm)) continue; messageDigest = CMS_signed_get0_data_by_OBJ(sitmp, OBJ_nid2obj (NID_pkcs9_messageDigest), -3, V_ASN1_OCTET_STRING); if (!messageDigest) { ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE); return 0; } if (CMS_signed_add1_attr_by_NID(si, NID_pkcs9_messageDigest, V_ASN1_OCTET_STRING, messageDigest, -1)) return 1; else return 0; } ERR_raise(ERR_LIB_CMS, CMS_R_NO_MATCHING_DIGEST); return 0; } int ossl_cms_set1_SignerIdentifier(CMS_SignerIdentifier *sid, X509 *cert, int type, const CMS_CTX *ctx) { switch (type) { case CMS_SIGNERINFO_ISSUER_SERIAL: if (!ossl_cms_set1_ias(&sid->d.issuerAndSerialNumber, cert)) return 0; break; case CMS_SIGNERINFO_KEYIDENTIFIER: if (!ossl_cms_set1_keyid(&sid->d.subjectKeyIdentifier, cert)) return 0; break; default: ERR_raise(ERR_LIB_CMS, CMS_R_UNKNOWN_ID); return 0; } sid->type = type; return 1; } int ossl_cms_SignerIdentifier_get0_signer_id(CMS_SignerIdentifier *sid, ASN1_OCTET_STRING **keyid, X509_NAME **issuer, ASN1_INTEGER **sno) { if (sid->type == CMS_SIGNERINFO_ISSUER_SERIAL) { if (issuer) *issuer = sid->d.issuerAndSerialNumber->issuer; if (sno) *sno = sid->d.issuerAndSerialNumber->serialNumber; } else if (sid->type == CMS_SIGNERINFO_KEYIDENTIFIER) { if (keyid) *keyid = sid->d.subjectKeyIdentifier; } else return 0; return 1; } int ossl_cms_SignerIdentifier_cert_cmp(CMS_SignerIdentifier *sid, X509 *cert) { if (sid->type == CMS_SIGNERINFO_ISSUER_SERIAL) return ossl_cms_ias_cert_cmp(sid->d.issuerAndSerialNumber, cert); else if (sid->type == CMS_SIGNERINFO_KEYIDENTIFIER) return ossl_cms_keyid_cert_cmp(sid->d.subjectKeyIdentifier, cert); else return -1; } static int cms_sd_asn1_ctrl(CMS_SignerInfo *si, int cmd) { EVP_PKEY *pkey = si->pkey; int i; if (EVP_PKEY_is_a(pkey, "DSA") || EVP_PKEY_is_a(pkey, "EC")) - return ossl_cms_ecdsa_dsa_sign(si, cmd); + return ossl_cms_ecdsa_dsa_sign(si, cmd) > 0; else if (EVP_PKEY_is_a(pkey, "RSA") || EVP_PKEY_is_a(pkey, "RSA-PSS")) - return ossl_cms_rsa_sign(si, cmd); + return ossl_cms_rsa_sign(si, cmd) > 0; /* Something else? We'll give engines etc a chance to handle this */ if (pkey->ameth == NULL || pkey->ameth->pkey_ctrl == NULL) return 1; i = pkey->ameth->pkey_ctrl(pkey, ASN1_PKEY_CTRL_CMS_SIGN, cmd, si); if (i == -2) { ERR_raise(ERR_LIB_CMS, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE); return 0; } if (i <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_CTRL_FAILURE); return 0; } return 1; } /* Add SigningCertificate signed attribute to the signer info. */ static int ossl_cms_add1_signing_cert(CMS_SignerInfo *si, const ESS_SIGNING_CERT *sc) { ASN1_STRING *seq = NULL; unsigned char *p, *pp = NULL; int ret, len = i2d_ESS_SIGNING_CERT(sc, NULL); if (len <= 0 || (pp = OPENSSL_malloc(len)) == NULL) return 0; p = pp; i2d_ESS_SIGNING_CERT(sc, &p); if (!(seq = ASN1_STRING_new()) || !ASN1_STRING_set(seq, pp, len)) { ASN1_STRING_free(seq); OPENSSL_free(pp); return 0; } OPENSSL_free(pp); ret = CMS_signed_add1_attr_by_NID(si, NID_id_smime_aa_signingCertificate, V_ASN1_SEQUENCE, seq, -1); ASN1_STRING_free(seq); return ret; } /* Add SigningCertificateV2 signed attribute to the signer info. */ static int ossl_cms_add1_signing_cert_v2(CMS_SignerInfo *si, const ESS_SIGNING_CERT_V2 *sc) { ASN1_STRING *seq = NULL; unsigned char *p, *pp = NULL; int ret, len = i2d_ESS_SIGNING_CERT_V2(sc, NULL); if (len <= 0 || (pp = OPENSSL_malloc(len)) == NULL) return 0; p = pp; i2d_ESS_SIGNING_CERT_V2(sc, &p); if (!(seq = ASN1_STRING_new()) || !ASN1_STRING_set(seq, pp, len)) { ASN1_STRING_free(seq); OPENSSL_free(pp); return 0; } OPENSSL_free(pp); ret = CMS_signed_add1_attr_by_NID(si, NID_id_smime_aa_signingCertificateV2, V_ASN1_SEQUENCE, seq, -1); ASN1_STRING_free(seq); return ret; } CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms, X509 *signer, EVP_PKEY *pk, const EVP_MD *md, unsigned int flags) { CMS_SignedData *sd; CMS_SignerInfo *si = NULL; X509_ALGOR *alg; int i, type; const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms); if (!X509_check_private_key(signer, pk)) { ERR_raise(ERR_LIB_CMS, CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE); return NULL; } sd = cms_signed_data_init(cms); if (!sd) goto err; si = M_ASN1_new_of(CMS_SignerInfo); if (!si) goto merr; /* Call for side-effect of computing hash and caching extensions */ X509_check_purpose(signer, -1, -1); X509_up_ref(signer); EVP_PKEY_up_ref(pk); si->cms_ctx = ctx; si->pkey = pk; si->signer = signer; si->mctx = EVP_MD_CTX_new(); si->pctx = NULL; if (si->mctx == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); goto err; } if (flags & CMS_USE_KEYID) { si->version = 3; if (sd->version < 3) sd->version = 3; type = CMS_SIGNERINFO_KEYIDENTIFIER; } else { type = CMS_SIGNERINFO_ISSUER_SERIAL; si->version = 1; } if (!ossl_cms_set1_SignerIdentifier(si->sid, signer, type, ctx)) goto err; if (md == NULL) { int def_nid; if (EVP_PKEY_get_default_digest_nid(pk, &def_nid) <= 0) goto err; md = EVP_get_digestbynid(def_nid); if (md == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_DEFAULT_DIGEST); goto err; } } if (!md) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_DIGEST_SET); goto err; } if (md == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_DIGEST_SET); goto err; } X509_ALGOR_set_md(si->digestAlgorithm, md); /* See if digest is present in digestAlgorithms */ for (i = 0; i < sk_X509_ALGOR_num(sd->digestAlgorithms); i++) { const ASN1_OBJECT *aoid; char name[OSSL_MAX_NAME_SIZE]; alg = sk_X509_ALGOR_value(sd->digestAlgorithms, i); X509_ALGOR_get0(&aoid, NULL, NULL, alg); OBJ_obj2txt(name, sizeof(name), aoid, 0); if (EVP_MD_is_a(md, name)) break; } if (i == sk_X509_ALGOR_num(sd->digestAlgorithms)) { alg = X509_ALGOR_new(); if (alg == NULL) goto merr; X509_ALGOR_set_md(alg, md); if (!sk_X509_ALGOR_push(sd->digestAlgorithms, alg)) { X509_ALGOR_free(alg); goto merr; } } if (!(flags & CMS_KEY_PARAM) && !cms_sd_asn1_ctrl(si, 0)) goto err; if (!(flags & CMS_NOATTR)) { /* * Initialize signed attributes structure so other attributes * such as signing time etc are added later even if we add none here. */ if (!si->signedAttrs) { si->signedAttrs = sk_X509_ATTRIBUTE_new_null(); if (!si->signedAttrs) goto merr; } if (!(flags & CMS_NOSMIMECAP)) { STACK_OF(X509_ALGOR) *smcap = NULL; i = CMS_add_standard_smimecap(&smcap); if (i) i = CMS_add_smimecap(si, smcap); sk_X509_ALGOR_pop_free(smcap, X509_ALGOR_free); if (!i) goto merr; } if (flags & CMS_CADES) { ESS_SIGNING_CERT *sc = NULL; ESS_SIGNING_CERT_V2 *sc2 = NULL; int add_sc; if (md == NULL || EVP_MD_is_a(md, SN_sha1)) { if ((sc = OSSL_ESS_signing_cert_new_init(signer, NULL, 1)) == NULL) goto err; add_sc = ossl_cms_add1_signing_cert(si, sc); ESS_SIGNING_CERT_free(sc); } else { if ((sc2 = OSSL_ESS_signing_cert_v2_new_init(md, signer, NULL, 1)) == NULL) goto err; add_sc = ossl_cms_add1_signing_cert_v2(si, sc2); ESS_SIGNING_CERT_V2_free(sc2); } if (!add_sc) goto err; } if (flags & CMS_REUSE_DIGEST) { if (!cms_copy_messageDigest(cms, si)) goto err; if (!cms_set_si_contentType_attr(cms, si)) goto err; if (!(flags & (CMS_PARTIAL | CMS_KEY_PARAM)) && !CMS_SignerInfo_sign(si)) goto err; } } if (!(flags & CMS_NOCERTS)) { /* NB ignore -1 return for duplicate cert */ if (!CMS_add1_cert(cms, signer)) goto merr; } if (flags & CMS_KEY_PARAM) { if (flags & CMS_NOATTR) { si->pctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(ctx), si->pkey, ossl_cms_ctx_get0_propq(ctx)); if (si->pctx == NULL) goto err; if (EVP_PKEY_sign_init(si->pctx) <= 0) goto err; if (EVP_PKEY_CTX_set_signature_md(si->pctx, md) <= 0) goto err; } else if (EVP_DigestSignInit_ex(si->mctx, &si->pctx, EVP_MD_get0_name(md), ossl_cms_ctx_get0_libctx(ctx), ossl_cms_ctx_get0_propq(ctx), pk, NULL) <= 0) { goto err; } } if (!sd->signerInfos) sd->signerInfos = sk_CMS_SignerInfo_new_null(); if (!sd->signerInfos || !sk_CMS_SignerInfo_push(sd->signerInfos, si)) goto merr; return si; merr: ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); err: M_ASN1_free_of(si, CMS_SignerInfo); return NULL; } void ossl_cms_SignerInfos_set_cmsctx(CMS_ContentInfo *cms) { int i; CMS_SignerInfo *si; STACK_OF(CMS_SignerInfo) *sinfos; const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms); ERR_set_mark(); sinfos = CMS_get0_SignerInfos(cms); ERR_pop_to_mark(); /* removes error in case sinfos == NULL */ for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) { si = sk_CMS_SignerInfo_value(sinfos, i); if (si != NULL) si->cms_ctx = ctx; } } static int cms_add1_signingTime(CMS_SignerInfo *si, ASN1_TIME *t) { ASN1_TIME *tt; int r = 0; if (t != NULL) tt = t; else tt = X509_gmtime_adj(NULL, 0); if (tt == NULL) goto merr; if (CMS_signed_add1_attr_by_NID(si, NID_pkcs9_signingTime, tt->type, tt, -1) <= 0) goto merr; r = 1; merr: if (t == NULL) ASN1_TIME_free(tt); if (!r) ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); return r; } EVP_PKEY_CTX *CMS_SignerInfo_get0_pkey_ctx(CMS_SignerInfo *si) { return si->pctx; } EVP_MD_CTX *CMS_SignerInfo_get0_md_ctx(CMS_SignerInfo *si) { return si->mctx; } STACK_OF(CMS_SignerInfo) *CMS_get0_SignerInfos(CMS_ContentInfo *cms) { CMS_SignedData *sd = cms_get0_signed(cms); return sd != NULL ? sd->signerInfos : NULL; } STACK_OF(X509) *CMS_get0_signers(CMS_ContentInfo *cms) { STACK_OF(X509) *signers = NULL; STACK_OF(CMS_SignerInfo) *sinfos; CMS_SignerInfo *si; int i; sinfos = CMS_get0_SignerInfos(cms); for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) { si = sk_CMS_SignerInfo_value(sinfos, i); if (si->signer != NULL) { if (!ossl_x509_add_cert_new(&signers, si->signer, X509_ADD_FLAG_DEFAULT)) { sk_X509_free(signers); return NULL; } } } return signers; } void CMS_SignerInfo_set1_signer_cert(CMS_SignerInfo *si, X509 *signer) { if (signer != NULL) { X509_up_ref(signer); EVP_PKEY_free(si->pkey); si->pkey = X509_get_pubkey(signer); } X509_free(si->signer); si->signer = signer; } int CMS_SignerInfo_get0_signer_id(CMS_SignerInfo *si, ASN1_OCTET_STRING **keyid, X509_NAME **issuer, ASN1_INTEGER **sno) { return ossl_cms_SignerIdentifier_get0_signer_id(si->sid, keyid, issuer, sno); } int CMS_SignerInfo_cert_cmp(CMS_SignerInfo *si, X509 *cert) { return ossl_cms_SignerIdentifier_cert_cmp(si->sid, cert); } int CMS_set1_signers_certs(CMS_ContentInfo *cms, STACK_OF(X509) *scerts, unsigned int flags) { CMS_SignedData *sd; CMS_SignerInfo *si; CMS_CertificateChoices *cch; STACK_OF(CMS_CertificateChoices) *certs; X509 *x; int i, j; int ret = 0; sd = cms_get0_signed(cms); if (sd == NULL) return -1; certs = sd->certificates; for (i = 0; i < sk_CMS_SignerInfo_num(sd->signerInfos); i++) { si = sk_CMS_SignerInfo_value(sd->signerInfos, i); if (si->signer != NULL) continue; for (j = 0; j < sk_X509_num(scerts); j++) { x = sk_X509_value(scerts, j); if (CMS_SignerInfo_cert_cmp(si, x) == 0) { CMS_SignerInfo_set1_signer_cert(si, x); ret++; break; } } if (si->signer != NULL || (flags & CMS_NOINTERN)) continue; for (j = 0; j < sk_CMS_CertificateChoices_num(certs); j++) { cch = sk_CMS_CertificateChoices_value(certs, j); if (cch->type != 0) continue; x = cch->d.certificate; if (CMS_SignerInfo_cert_cmp(si, x) == 0) { CMS_SignerInfo_set1_signer_cert(si, x); ret++; break; } } } return ret; } void CMS_SignerInfo_get0_algs(CMS_SignerInfo *si, EVP_PKEY **pk, X509 **signer, X509_ALGOR **pdig, X509_ALGOR **psig) { if (pk != NULL) *pk = si->pkey; if (signer != NULL) *signer = si->signer; if (pdig != NULL) *pdig = si->digestAlgorithm; if (psig != NULL) *psig = si->signatureAlgorithm; } ASN1_OCTET_STRING *CMS_SignerInfo_get0_signature(CMS_SignerInfo *si) { return si->signature; } static int cms_SignerInfo_content_sign(CMS_ContentInfo *cms, CMS_SignerInfo *si, BIO *chain) { EVP_MD_CTX *mctx = EVP_MD_CTX_new(); int r = 0; EVP_PKEY_CTX *pctx = NULL; const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms); if (mctx == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); return 0; } if (si->pkey == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_PRIVATE_KEY); goto err; } if (!ossl_cms_DigestAlgorithm_find_ctx(mctx, chain, si->digestAlgorithm)) goto err; /* Set SignerInfo algorithm details if we used custom parameter */ if (si->pctx && !cms_sd_asn1_ctrl(si, 0)) goto err; /* * If any signed attributes calculate and add messageDigest attribute */ if (CMS_signed_get_attr_count(si) >= 0) { unsigned char md[EVP_MAX_MD_SIZE]; unsigned int mdlen; if (!EVP_DigestFinal_ex(mctx, md, &mdlen)) goto err; if (!CMS_signed_add1_attr_by_NID(si, NID_pkcs9_messageDigest, V_ASN1_OCTET_STRING, md, mdlen)) goto err; /* Copy content type across */ if (!cms_set_si_contentType_attr(cms, si)) goto err; if (!CMS_SignerInfo_sign(si)) goto err; } else if (si->pctx) { unsigned char *sig; size_t siglen; unsigned char md[EVP_MAX_MD_SIZE]; unsigned int mdlen; pctx = si->pctx; if (!EVP_DigestFinal_ex(mctx, md, &mdlen)) goto err; siglen = EVP_PKEY_get_size(si->pkey); sig = OPENSSL_malloc(siglen); if (sig == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); goto err; } if (EVP_PKEY_sign(pctx, sig, &siglen, md, mdlen) <= 0) { OPENSSL_free(sig); goto err; } ASN1_STRING_set0(si->signature, sig, siglen); } else { unsigned char *sig; unsigned int siglen; sig = OPENSSL_malloc(EVP_PKEY_get_size(si->pkey)); if (sig == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); goto err; } if (!EVP_SignFinal_ex(mctx, sig, &siglen, si->pkey, ossl_cms_ctx_get0_libctx(ctx), ossl_cms_ctx_get0_propq(ctx))) { ERR_raise(ERR_LIB_CMS, CMS_R_SIGNFINAL_ERROR); OPENSSL_free(sig); goto err; } ASN1_STRING_set0(si->signature, sig, siglen); } r = 1; err: EVP_MD_CTX_free(mctx); EVP_PKEY_CTX_free(pctx); return r; } int ossl_cms_SignedData_final(CMS_ContentInfo *cms, BIO *chain) { STACK_OF(CMS_SignerInfo) *sinfos; CMS_SignerInfo *si; int i; sinfos = CMS_get0_SignerInfos(cms); for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) { si = sk_CMS_SignerInfo_value(sinfos, i); if (!cms_SignerInfo_content_sign(cms, si, chain)) return 0; } cms->d.signedData->encapContentInfo->partial = 0; return 1; } int CMS_SignerInfo_sign(CMS_SignerInfo *si) { EVP_MD_CTX *mctx = si->mctx; EVP_PKEY_CTX *pctx = NULL; unsigned char *abuf = NULL; int alen; size_t siglen; const CMS_CTX *ctx = si->cms_ctx; char md_name[OSSL_MAX_NAME_SIZE]; if (OBJ_obj2txt(md_name, sizeof(md_name), si->digestAlgorithm->algorithm, 0) <= 0) return 0; if (CMS_signed_get_attr_by_NID(si, NID_pkcs9_signingTime, -1) < 0) { if (!cms_add1_signingTime(si, NULL)) goto err; } if (!ossl_cms_si_check_attributes(si)) goto err; if (si->pctx) pctx = si->pctx; else { EVP_MD_CTX_reset(mctx); if (EVP_DigestSignInit_ex(mctx, &pctx, md_name, ossl_cms_ctx_get0_libctx(ctx), ossl_cms_ctx_get0_propq(ctx), si->pkey, NULL) <= 0) goto err; si->pctx = pctx; } alen = ASN1_item_i2d((ASN1_VALUE *)si->signedAttrs, &abuf, ASN1_ITEM_rptr(CMS_Attributes_Sign)); if (!abuf) goto err; if (EVP_DigestSignUpdate(mctx, abuf, alen) <= 0) goto err; if (EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0) goto err; OPENSSL_free(abuf); abuf = OPENSSL_malloc(siglen); if (abuf == NULL) goto err; if (EVP_DigestSignFinal(mctx, abuf, &siglen) <= 0) goto err; EVP_MD_CTX_reset(mctx); ASN1_STRING_set0(si->signature, abuf, siglen); return 1; err: OPENSSL_free(abuf); EVP_MD_CTX_reset(mctx); return 0; } int CMS_SignerInfo_verify(CMS_SignerInfo *si) { EVP_MD_CTX *mctx = NULL; unsigned char *abuf = NULL; int alen, r = -1; char name[OSSL_MAX_NAME_SIZE]; const EVP_MD *md; EVP_MD *fetched_md = NULL; const CMS_CTX *ctx = si->cms_ctx; OSSL_LIB_CTX *libctx = ossl_cms_ctx_get0_libctx(ctx); const char *propq = ossl_cms_ctx_get0_propq(ctx); if (si->pkey == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_PUBLIC_KEY); return -1; } if (!ossl_cms_si_check_attributes(si)) return -1; OBJ_obj2txt(name, sizeof(name), si->digestAlgorithm->algorithm, 0); (void)ERR_set_mark(); fetched_md = EVP_MD_fetch(libctx, name, propq); if (fetched_md != NULL) md = fetched_md; else md = EVP_get_digestbyobj(si->digestAlgorithm->algorithm); if (md == NULL) { (void)ERR_clear_last_mark(); ERR_raise(ERR_LIB_CMS, CMS_R_UNKNOWN_DIGEST_ALGORITHM); return -1; } (void)ERR_pop_to_mark(); if (si->mctx == NULL && (si->mctx = EVP_MD_CTX_new()) == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); goto err; } mctx = si->mctx; if (EVP_DigestVerifyInit_ex(mctx, &si->pctx, EVP_MD_get0_name(md), libctx, propq, si->pkey, NULL) <= 0) goto err; if (!cms_sd_asn1_ctrl(si, 1)) goto err; alen = ASN1_item_i2d((ASN1_VALUE *)si->signedAttrs, &abuf, ASN1_ITEM_rptr(CMS_Attributes_Verify)); if (abuf == NULL || alen < 0) goto err; r = EVP_DigestVerifyUpdate(mctx, abuf, alen); OPENSSL_free(abuf); if (r <= 0) { r = -1; goto err; } r = EVP_DigestVerifyFinal(mctx, si->signature->data, si->signature->length); if (r <= 0) ERR_raise(ERR_LIB_CMS, CMS_R_VERIFICATION_FAILURE); err: EVP_MD_free(fetched_md); EVP_MD_CTX_reset(mctx); return r; } /* Create a chain of digest BIOs from a CMS ContentInfo */ BIO *ossl_cms_SignedData_init_bio(CMS_ContentInfo *cms) { int i; CMS_SignedData *sd; BIO *chain = NULL; sd = cms_get0_signed(cms); if (sd == NULL) return NULL; if (cms->d.signedData->encapContentInfo->partial) cms_sd_set_version(sd); for (i = 0; i < sk_X509_ALGOR_num(sd->digestAlgorithms); i++) { X509_ALGOR *digestAlgorithm; BIO *mdbio; digestAlgorithm = sk_X509_ALGOR_value(sd->digestAlgorithms, i); mdbio = ossl_cms_DigestAlgorithm_init_bio(digestAlgorithm, ossl_cms_get0_cmsctx(cms)); if (mdbio == NULL) goto err; if (chain != NULL) BIO_push(chain, mdbio); else chain = mdbio; } return chain; err: BIO_free_all(chain); return NULL; } int CMS_SignerInfo_verify_content(CMS_SignerInfo *si, BIO *chain) { ASN1_OCTET_STRING *os = NULL; EVP_MD_CTX *mctx = EVP_MD_CTX_new(); EVP_PKEY_CTX *pkctx = NULL; int r = -1; unsigned char mval[EVP_MAX_MD_SIZE]; unsigned int mlen; if (mctx == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE); goto err; } /* If we have any signed attributes look for messageDigest value */ if (CMS_signed_get_attr_count(si) >= 0) { os = CMS_signed_get0_data_by_OBJ(si, OBJ_nid2obj(NID_pkcs9_messageDigest), -3, V_ASN1_OCTET_STRING); if (os == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE); goto err; } } if (!ossl_cms_DigestAlgorithm_find_ctx(mctx, chain, si->digestAlgorithm)) goto err; if (EVP_DigestFinal_ex(mctx, mval, &mlen) <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_UNABLE_TO_FINALIZE_CONTEXT); goto err; } /* If messageDigest found compare it */ if (os != NULL) { if (mlen != (unsigned int)os->length) { ERR_raise(ERR_LIB_CMS, CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH); goto err; } if (memcmp(mval, os->data, mlen)) { ERR_raise(ERR_LIB_CMS, CMS_R_VERIFICATION_FAILURE); r = 0; } else r = 1; } else { const EVP_MD *md = EVP_MD_CTX_get0_md(mctx); const CMS_CTX *ctx = si->cms_ctx; pkctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(ctx), si->pkey, ossl_cms_ctx_get0_propq(ctx)); if (pkctx == NULL) goto err; if (EVP_PKEY_verify_init(pkctx) <= 0) goto err; if (EVP_PKEY_CTX_set_signature_md(pkctx, md) <= 0) goto err; si->pctx = pkctx; if (!cms_sd_asn1_ctrl(si, 1)) goto err; r = EVP_PKEY_verify(pkctx, si->signature->data, si->signature->length, mval, mlen); if (r <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_VERIFICATION_FAILURE); r = 0; } } err: EVP_PKEY_CTX_free(pkctx); EVP_MD_CTX_free(mctx); return r; } int CMS_add_smimecap(CMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs) { unsigned char *smder = NULL; int smderlen, r; smderlen = i2d_X509_ALGORS(algs, &smder); if (smderlen <= 0) return 0; r = CMS_signed_add1_attr_by_NID(si, NID_SMIMECapabilities, V_ASN1_SEQUENCE, smder, smderlen); OPENSSL_free(smder); return r; } int CMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs, int algnid, int keysize) { X509_ALGOR *alg; ASN1_INTEGER *key = NULL; if (keysize > 0) { key = ASN1_INTEGER_new(); if (key == NULL || !ASN1_INTEGER_set(key, keysize)) { ASN1_INTEGER_free(key); return 0; } } alg = X509_ALGOR_new(); if (alg == NULL) { ASN1_INTEGER_free(key); return 0; } X509_ALGOR_set0(alg, OBJ_nid2obj(algnid), key ? V_ASN1_INTEGER : V_ASN1_UNDEF, key); if (*algs == NULL) *algs = sk_X509_ALGOR_new_null(); if (*algs == NULL || !sk_X509_ALGOR_push(*algs, alg)) { X509_ALGOR_free(alg); return 0; } return 1; } /* Check to see if a cipher exists and if so add S/MIME capabilities */ static int cms_add_cipher_smcap(STACK_OF(X509_ALGOR) **sk, int nid, int arg) { if (EVP_get_cipherbynid(nid)) return CMS_add_simple_smimecap(sk, nid, arg); return 1; } static int cms_add_digest_smcap(STACK_OF(X509_ALGOR) **sk, int nid, int arg) { if (EVP_get_digestbynid(nid)) return CMS_add_simple_smimecap(sk, nid, arg); return 1; } int CMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap) { if (!cms_add_cipher_smcap(smcap, NID_aes_256_cbc, -1) || !cms_add_digest_smcap(smcap, NID_id_GostR3411_2012_256, -1) || !cms_add_digest_smcap(smcap, NID_id_GostR3411_2012_512, -1) || !cms_add_digest_smcap(smcap, NID_id_GostR3411_94, -1) || !cms_add_cipher_smcap(smcap, NID_id_Gost28147_89, -1) || !cms_add_cipher_smcap(smcap, NID_aes_192_cbc, -1) || !cms_add_cipher_smcap(smcap, NID_aes_128_cbc, -1) || !cms_add_cipher_smcap(smcap, NID_des_ede3_cbc, -1) || !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 128) || !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 64) || !cms_add_cipher_smcap(smcap, NID_des_cbc, -1) || !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 40)) return 0; return 1; } diff --git a/crypto/conf/conf_sap.c b/crypto/conf/conf_sap.c index 513f8bfc1fb9..3019bcf31af8 100644 --- a/crypto/conf/conf_sap.c +++ b/crypto/conf/conf_sap.c @@ -1,79 +1,80 @@ /* * Copyright 2002-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include #include #include "internal/cryptlib.h" #include "internal/conf.h" #include "conf_local.h" #include #include #include #if defined(_WIN32) && !defined(__BORLANDC__) # define strdup _strdup #endif /* * This is the automatic configuration loader: it is called automatically by * OpenSSL when any of a number of standard initialisation functions are * called, unless this is overridden by calling OPENSSL_no_config() */ static int openssl_configured = 0; #ifndef OPENSSL_NO_DEPRECATED_1_1_0 void OPENSSL_config(const char *appname) { OPENSSL_INIT_SETTINGS settings; memset(&settings, 0, sizeof(settings)); if (appname != NULL) settings.appname = strdup(appname); settings.flags = DEFAULT_CONF_MFLAGS; OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, &settings); } #endif int ossl_config_int(const OPENSSL_INIT_SETTINGS *settings) { int ret = 0; #if defined(OPENSSL_INIT_DEBUG) || !defined(OPENSSL_SYS_UEFI) const char *filename; const char *appname; unsigned long flags; #endif if (openssl_configured) return 1; #if defined(OPENSSL_INIT_DEBUG) || !defined(OPENSSL_SYS_UEFI) filename = settings ? settings->filename : NULL; appname = settings ? settings->appname : NULL; flags = settings ? settings->flags : DEFAULT_CONF_MFLAGS; #endif #ifdef OPENSSL_INIT_DEBUG fprintf(stderr, "OPENSSL_INIT: ossl_config_int(%s, %s, %lu)\n", filename, appname, flags); #endif #ifndef OPENSSL_SYS_UEFI - ret = CONF_modules_load_file(filename, appname, flags); + ret = CONF_modules_load_file_ex(OSSL_LIB_CTX_get0_global_default(), + filename, appname, flags); #else ret = 1; #endif openssl_configured = 1; return ret; } void ossl_no_config_int(void) { openssl_configured = 1; } diff --git a/crypto/encode_decode/decoder_lib.c b/crypto/encode_decode/decoder_lib.c index e24d2c6cd588..2e4b7ed60b9c 100644 --- a/crypto/encode_decode/decoder_lib.c +++ b/crypto/encode_decode/decoder_lib.c @@ -1,999 +1,1000 @@ /* - * Copyright 2020-2022 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2020-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include #include #include #include #include #include #include #include #include #include "internal/bio.h" #include "internal/provider.h" #include "crypto/decoder.h" #include "encoder_local.h" #include "e_os.h" struct decoder_process_data_st { OSSL_DECODER_CTX *ctx; /* Current BIO */ BIO *bio; /* Index of the current decoder instance to be processed */ size_t current_decoder_inst_index; /* For tracing, count recursion level */ size_t recursion; /*- * Flags */ unsigned int flag_next_level_called : 1; unsigned int flag_construct_called : 1; unsigned int flag_input_structure_checked : 1; }; static int decoder_process(const OSSL_PARAM params[], void *arg); int OSSL_DECODER_from_bio(OSSL_DECODER_CTX *ctx, BIO *in) { struct decoder_process_data_st data; int ok = 0; BIO *new_bio = NULL; unsigned long lasterr; if (in == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (OSSL_DECODER_CTX_get_num_decoders(ctx) == 0) { ERR_raise_data(ERR_LIB_OSSL_DECODER, OSSL_DECODER_R_DECODER_NOT_FOUND, "No decoders were found. For standard decoders you need " "at least one of the default or base providers " "available. Did you forget to load them?"); return 0; } lasterr = ERR_peek_last_error(); if (BIO_tell(in) < 0) { new_bio = BIO_new(BIO_f_readbuffer()); if (new_bio == NULL) return 0; in = BIO_push(new_bio, in); } memset(&data, 0, sizeof(data)); data.ctx = ctx; data.bio = in; /* Enable passphrase caching */ (void)ossl_pw_enable_passphrase_caching(&ctx->pwdata); ok = decoder_process(NULL, &data); if (!data.flag_construct_called) { const char *spaces = ctx->start_input_type != NULL && ctx->input_structure != NULL ? " " : ""; const char *input_type_label = ctx->start_input_type != NULL ? "Input type: " : ""; const char *input_structure_label = ctx->input_structure != NULL ? "Input structure: " : ""; const char *comma = ctx->start_input_type != NULL && ctx->input_structure != NULL ? ", " : ""; const char *input_type = ctx->start_input_type != NULL ? ctx->start_input_type : ""; const char *input_structure = ctx->input_structure != NULL ? ctx->input_structure : ""; if (ERR_peek_last_error() == lasterr || ERR_peek_error() == 0) /* Prevent spurious decoding error but add at least something */ ERR_raise_data(ERR_LIB_OSSL_DECODER, ERR_R_UNSUPPORTED, "No supported data to decode. %s%s%s%s%s%s", spaces, input_type_label, input_type, comma, input_structure_label, input_structure); ok = 0; } /* Clear any internally cached passphrase */ (void)ossl_pw_clear_passphrase_cache(&ctx->pwdata); if (new_bio != NULL) { BIO_pop(new_bio); BIO_free(new_bio); } return ok; } #ifndef OPENSSL_NO_STDIO static BIO *bio_from_file(FILE *fp) { BIO *b; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_BIO_LIB); return NULL; } BIO_set_fp(b, fp, BIO_NOCLOSE); return b; } int OSSL_DECODER_from_fp(OSSL_DECODER_CTX *ctx, FILE *fp) { BIO *b = bio_from_file(fp); int ret = 0; if (b != NULL) ret = OSSL_DECODER_from_bio(ctx, b); BIO_free(b); return ret; } #endif int OSSL_DECODER_from_data(OSSL_DECODER_CTX *ctx, const unsigned char **pdata, size_t *pdata_len) { BIO *membio; int ret = 0; if (pdata == NULL || *pdata == NULL || pdata_len == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } membio = BIO_new_mem_buf(*pdata, (int)*pdata_len); if (OSSL_DECODER_from_bio(ctx, membio)) { *pdata_len = (size_t)BIO_get_mem_data(membio, pdata); ret = 1; } BIO_free(membio); return ret; } int OSSL_DECODER_CTX_set_selection(OSSL_DECODER_CTX *ctx, int selection) { if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } /* * 0 is a valid selection, and means that the caller leaves * it to code to discover what the selection is. */ ctx->selection = selection; return 1; } int OSSL_DECODER_CTX_set_input_type(OSSL_DECODER_CTX *ctx, const char *input_type) { if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } /* * NULL is a valid starting input type, and means that the caller leaves * it to code to discover what the starting input type is. */ ctx->start_input_type = input_type; return 1; } int OSSL_DECODER_CTX_set_input_structure(OSSL_DECODER_CTX *ctx, const char *input_structure) { if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } /* * NULL is a valid starting input structure, and means that the caller * leaves it to code to discover what the starting input structure is. */ ctx->input_structure = input_structure; return 1; } OSSL_DECODER_INSTANCE *ossl_decoder_instance_new(OSSL_DECODER *decoder, void *decoderctx) { OSSL_DECODER_INSTANCE *decoder_inst = NULL; const OSSL_PROVIDER *prov; OSSL_LIB_CTX *libctx; const OSSL_PROPERTY_LIST *props; const OSSL_PROPERTY_DEFINITION *prop; if (!ossl_assert(decoder != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } if ((decoder_inst = OPENSSL_zalloc(sizeof(*decoder_inst))) == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_MALLOC_FAILURE); return 0; } prov = OSSL_DECODER_get0_provider(decoder); libctx = ossl_provider_libctx(prov); props = ossl_decoder_parsed_properties(decoder); if (props == NULL) { ERR_raise_data(ERR_LIB_OSSL_DECODER, ERR_R_INVALID_PROPERTY_DEFINITION, "there are no property definitions with decoder %s", OSSL_DECODER_get0_name(decoder)); goto err; } /* The "input" property is mandatory */ prop = ossl_property_find_property(props, libctx, "input"); decoder_inst->input_type = ossl_property_get_string_value(libctx, prop); if (decoder_inst->input_type == NULL) { ERR_raise_data(ERR_LIB_OSSL_DECODER, ERR_R_INVALID_PROPERTY_DEFINITION, "the mandatory 'input' property is missing " "for decoder %s (properties: %s)", OSSL_DECODER_get0_name(decoder), OSSL_DECODER_get0_properties(decoder)); goto err; } /* The "structure" property is optional */ prop = ossl_property_find_property(props, libctx, "structure"); if (prop != NULL) { decoder_inst->input_structure = ossl_property_get_string_value(libctx, prop); } if (!OSSL_DECODER_up_ref(decoder)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_INTERNAL_ERROR); goto err; } decoder_inst->decoder = decoder; decoder_inst->decoderctx = decoderctx; return decoder_inst; err: ossl_decoder_instance_free(decoder_inst); return NULL; } void ossl_decoder_instance_free(OSSL_DECODER_INSTANCE *decoder_inst) { if (decoder_inst != NULL) { if (decoder_inst->decoder != NULL) decoder_inst->decoder->freectx(decoder_inst->decoderctx); decoder_inst->decoderctx = NULL; OSSL_DECODER_free(decoder_inst->decoder); decoder_inst->decoder = NULL; OPENSSL_free(decoder_inst); } } int ossl_decoder_ctx_add_decoder_inst(OSSL_DECODER_CTX *ctx, OSSL_DECODER_INSTANCE *di) { int ok; if (ctx->decoder_insts == NULL && (ctx->decoder_insts = sk_OSSL_DECODER_INSTANCE_new_null()) == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_MALLOC_FAILURE); return 0; } ok = (sk_OSSL_DECODER_INSTANCE_push(ctx->decoder_insts, di) > 0); if (ok) { OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) Added decoder instance %p for decoder %p\n" " %s with %s\n", (void *)ctx, (void *)di, (void *)di->decoder, OSSL_DECODER_get0_name(di->decoder), OSSL_DECODER_get0_properties(di->decoder)); } OSSL_TRACE_END(DECODER); } return ok; } int OSSL_DECODER_CTX_add_decoder(OSSL_DECODER_CTX *ctx, OSSL_DECODER *decoder) { OSSL_DECODER_INSTANCE *decoder_inst = NULL; const OSSL_PROVIDER *prov = NULL; void *decoderctx = NULL; void *provctx = NULL; if (!ossl_assert(ctx != NULL) || !ossl_assert(decoder != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } prov = OSSL_DECODER_get0_provider(decoder); provctx = OSSL_PROVIDER_get0_provider_ctx(prov); if ((decoderctx = decoder->newctx(provctx)) == NULL || (decoder_inst = ossl_decoder_instance_new(decoder, decoderctx)) == NULL) goto err; /* Avoid double free of decoderctx on further errors */ decoderctx = NULL; if (!ossl_decoder_ctx_add_decoder_inst(ctx, decoder_inst)) goto err; return 1; err: ossl_decoder_instance_free(decoder_inst); if (decoderctx != NULL) decoder->freectx(decoderctx); return 0; } struct collect_extra_decoder_data_st { OSSL_DECODER_CTX *ctx; const char *output_type; /* * 0 to check that the decoder's input type is the same as the decoder name * 1 to check that the decoder's input type differs from the decoder name */ enum { IS_SAME = 0, IS_DIFFERENT = 1 } type_check; size_t w_prev_start, w_prev_end; /* "previous" decoders */ size_t w_new_start, w_new_end; /* "new" decoders */ }; DEFINE_STACK_OF(OSSL_DECODER) static void collect_all_decoders(OSSL_DECODER *decoder, void *arg) { STACK_OF(OSSL_DECODER) *skdecoders = arg; if (OSSL_DECODER_up_ref(decoder) && !sk_OSSL_DECODER_push(skdecoders, decoder)) OSSL_DECODER_free(decoder); } static void collect_extra_decoder(OSSL_DECODER *decoder, void *arg) { struct collect_extra_decoder_data_st *data = arg; size_t j; const OSSL_PROVIDER *prov = OSSL_DECODER_get0_provider(decoder); void *provctx = OSSL_PROVIDER_get0_provider_ctx(prov); if (OSSL_DECODER_is_a(decoder, data->output_type)) { void *decoderctx = NULL; OSSL_DECODER_INSTANCE *di = NULL; OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) [%d] Checking out decoder %p:\n" " %s with %s\n", (void *)data->ctx, data->type_check, (void *)decoder, OSSL_DECODER_get0_name(decoder), OSSL_DECODER_get0_properties(decoder)); } OSSL_TRACE_END(DECODER); /* * Check that we don't already have this decoder in our stack, * starting with the previous windows but also looking at what * we have added in the current window. */ for (j = data->w_prev_start; j < data->w_new_end; j++) { OSSL_DECODER_INSTANCE *check_inst = sk_OSSL_DECODER_INSTANCE_value(data->ctx->decoder_insts, j); if (decoder->base.algodef == check_inst->decoder->base.algodef) { /* We found it, so don't do anything more */ OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, " REJECTED: already exists in the chain\n"); } OSSL_TRACE_END(DECODER); return; } } if ((decoderctx = decoder->newctx(provctx)) == NULL) return; if ((di = ossl_decoder_instance_new(decoder, decoderctx)) == NULL) { decoder->freectx(decoderctx); return; } switch (data->type_check) { case IS_SAME: /* If it differs, this is not a decoder to add for now. */ if (!OSSL_DECODER_is_a(decoder, OSSL_DECODER_INSTANCE_get_input_type(di))) { ossl_decoder_instance_free(di); OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, " REJECTED: input type doesn't match output type\n"); } OSSL_TRACE_END(DECODER); return; } break; case IS_DIFFERENT: /* If it's the same, this is not a decoder to add for now. */ if (OSSL_DECODER_is_a(decoder, OSSL_DECODER_INSTANCE_get_input_type(di))) { ossl_decoder_instance_free(di); OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, " REJECTED: input type matches output type\n"); } OSSL_TRACE_END(DECODER); return; } break; } /* * Apart from keeping w_new_end up to date, We don't care about * errors here. If it doesn't collect, then it doesn't... */ if (!ossl_decoder_ctx_add_decoder_inst(data->ctx, di)) { ossl_decoder_instance_free(di); return; } data->w_new_end++; } } int OSSL_DECODER_CTX_add_extra(OSSL_DECODER_CTX *ctx, OSSL_LIB_CTX *libctx, const char *propq) { /* * This function goes through existing decoder methods in * |ctx->decoder_insts|, and tries to fetch new decoders that produce * what the existing ones want as input, and push those newly fetched * decoders on top of the same stack. * Then it does the same again, but looping over the newly fetched * decoders, until there are no more decoders to be fetched, or * when we have done this 10 times. * * we do this with sliding windows on the stack by keeping track of indexes * and of the end. * * +----------------+ * | DER to RSA | <--- w_prev_start * +----------------+ * | DER to DSA | * +----------------+ * | DER to DH | * +----------------+ * | PEM to DER | <--- w_prev_end, w_new_start * +----------------+ * <--- w_new_end */ struct collect_extra_decoder_data_st data; size_t depth = 0; /* Counts the number of iterations */ size_t count; /* Calculates how many were added in each iteration */ size_t numdecoders; STACK_OF(OSSL_DECODER) *skdecoders; if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } /* * If there is no stack of OSSL_DECODER_INSTANCE, we have nothing * more to add. That's fine. */ if (ctx->decoder_insts == NULL) return 1; OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) Looking for extra decoders\n", (void *)ctx); } OSSL_TRACE_END(DECODER); skdecoders = sk_OSSL_DECODER_new_null(); if (skdecoders == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_MALLOC_FAILURE); return 0; } OSSL_DECODER_do_all_provided(libctx, collect_all_decoders, skdecoders); numdecoders = sk_OSSL_DECODER_num(skdecoders); memset(&data, 0, sizeof(data)); data.ctx = ctx; data.w_prev_start = 0; data.w_prev_end = sk_OSSL_DECODER_INSTANCE_num(ctx->decoder_insts); do { size_t i, j; data.w_new_start = data.w_new_end = data.w_prev_end; /* * Two iterations: * 0. All decoders that have the same name as their input type. * This allows for decoders that unwrap some data in a specific * encoding, and pass the result on with the same encoding. * 1. All decoders that a different name than their input type. */ for (data.type_check = IS_SAME; data.type_check <= IS_DIFFERENT; data.type_check++) { for (i = data.w_prev_start; i < data.w_prev_end; i++) { OSSL_DECODER_INSTANCE *decoder_inst = sk_OSSL_DECODER_INSTANCE_value(ctx->decoder_insts, i); data.output_type = OSSL_DECODER_INSTANCE_get_input_type(decoder_inst); for (j = 0; j < numdecoders; j++) collect_extra_decoder(sk_OSSL_DECODER_value(skdecoders, j), &data); } } /* How many were added in this iteration */ count = data.w_new_end - data.w_new_start; /* Slide the "previous decoder" windows */ data.w_prev_start = data.w_new_start; data.w_prev_end = data.w_new_end; depth++; } while (count != 0 && depth <= 10); sk_OSSL_DECODER_pop_free(skdecoders, OSSL_DECODER_free); return 1; } int OSSL_DECODER_CTX_get_num_decoders(OSSL_DECODER_CTX *ctx) { if (ctx == NULL || ctx->decoder_insts == NULL) return 0; return sk_OSSL_DECODER_INSTANCE_num(ctx->decoder_insts); } int OSSL_DECODER_CTX_set_construct(OSSL_DECODER_CTX *ctx, OSSL_DECODER_CONSTRUCT *construct) { if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } ctx->construct = construct; return 1; } int OSSL_DECODER_CTX_set_construct_data(OSSL_DECODER_CTX *ctx, void *construct_data) { if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } ctx->construct_data = construct_data; return 1; } int OSSL_DECODER_CTX_set_cleanup(OSSL_DECODER_CTX *ctx, OSSL_DECODER_CLEANUP *cleanup) { if (!ossl_assert(ctx != NULL)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } ctx->cleanup = cleanup; return 1; } OSSL_DECODER_CONSTRUCT * OSSL_DECODER_CTX_get_construct(OSSL_DECODER_CTX *ctx) { if (ctx == NULL) return NULL; return ctx->construct; } void *OSSL_DECODER_CTX_get_construct_data(OSSL_DECODER_CTX *ctx) { if (ctx == NULL) return NULL; return ctx->construct_data; } OSSL_DECODER_CLEANUP * OSSL_DECODER_CTX_get_cleanup(OSSL_DECODER_CTX *ctx) { if (ctx == NULL) return NULL; return ctx->cleanup; } int OSSL_DECODER_export(OSSL_DECODER_INSTANCE *decoder_inst, void *reference, size_t reference_sz, OSSL_CALLBACK *export_cb, void *export_cbarg) { OSSL_DECODER *decoder = NULL; void *decoderctx = NULL; if (!(ossl_assert(decoder_inst != NULL) && ossl_assert(reference != NULL) && ossl_assert(export_cb != NULL) && ossl_assert(export_cbarg != NULL))) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER); return 0; } decoder = OSSL_DECODER_INSTANCE_get_decoder(decoder_inst); decoderctx = OSSL_DECODER_INSTANCE_get_decoder_ctx(decoder_inst); return decoder->export_object(decoderctx, reference, reference_sz, export_cb, export_cbarg); } OSSL_DECODER * OSSL_DECODER_INSTANCE_get_decoder(OSSL_DECODER_INSTANCE *decoder_inst) { if (decoder_inst == NULL) return NULL; return decoder_inst->decoder; } void * OSSL_DECODER_INSTANCE_get_decoder_ctx(OSSL_DECODER_INSTANCE *decoder_inst) { if (decoder_inst == NULL) return NULL; return decoder_inst->decoderctx; } const char * OSSL_DECODER_INSTANCE_get_input_type(OSSL_DECODER_INSTANCE *decoder_inst) { if (decoder_inst == NULL) return NULL; return decoder_inst->input_type; } const char * OSSL_DECODER_INSTANCE_get_input_structure(OSSL_DECODER_INSTANCE *decoder_inst, int *was_set) { if (decoder_inst == NULL) return NULL; *was_set = decoder_inst->flag_input_structure_was_set; return decoder_inst->input_structure; } static int decoder_process(const OSSL_PARAM params[], void *arg) { struct decoder_process_data_st *data = arg; OSSL_DECODER_CTX *ctx = data->ctx; OSSL_DECODER_INSTANCE *decoder_inst = NULL; OSSL_DECODER *decoder = NULL; OSSL_CORE_BIO *cbio = NULL; BIO *bio = data->bio; long loc; size_t i; int ok = 0; /* For recursions */ struct decoder_process_data_st new_data; const char *data_type = NULL; const char *data_structure = NULL; /* * This is an indicator up the call stack that something was indeed * decoded, leading to a recursive call of this function. */ data->flag_next_level_called = 1; memset(&new_data, 0, sizeof(new_data)); new_data.ctx = data->ctx; new_data.recursion = data->recursion + 1; #define LEVEL_STR ">>>>>>>>>>>>>>>>" #define LEVEL (new_data.recursion < sizeof(LEVEL_STR) \ ? &LEVEL_STR[sizeof(LEVEL_STR) - new_data.recursion - 1] \ : LEVEL_STR "...") if (params == NULL) { /* First iteration, where we prepare for what is to come */ OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) starting to walk the decoder chain\n", (void *)new_data.ctx); } OSSL_TRACE_END(DECODER); data->current_decoder_inst_index = OSSL_DECODER_CTX_get_num_decoders(ctx); bio = data->bio; } else { const OSSL_PARAM *p; const char *trace_data_structure; decoder_inst = sk_OSSL_DECODER_INSTANCE_value(ctx->decoder_insts, data->current_decoder_inst_index); decoder = OSSL_DECODER_INSTANCE_get_decoder(decoder_inst); data->flag_construct_called = 0; if (ctx->construct != NULL) { int rv; OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) %s Running constructor\n", (void *)new_data.ctx, LEVEL); } OSSL_TRACE_END(DECODER); rv = ctx->construct(decoder_inst, params, ctx->construct_data); OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) %s Running constructor => %d\n", (void *)new_data.ctx, LEVEL, rv); } OSSL_TRACE_END(DECODER); - data->flag_construct_called = 1; ok = (rv > 0); - if (ok) + if (ok) { + data->flag_construct_called = 1; goto end; + } } /* The constructor didn't return success */ /* * so we try to use the object we got and feed it to any next * decoder that will take it. Object references are not * allowed for this. * If this data isn't present, decoding has failed. */ p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA); if (p == NULL || p->data_type != OSSL_PARAM_OCTET_STRING) goto end; new_data.bio = BIO_new_mem_buf(p->data, (int)p->data_size); if (new_data.bio == NULL) goto end; bio = new_data.bio; /* Get the data type if there is one */ p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA_TYPE); if (p != NULL && !OSSL_PARAM_get_utf8_string_ptr(p, &data_type)) goto end; /* Get the data structure if there is one */ p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA_STRUCTURE); if (p != NULL && !OSSL_PARAM_get_utf8_string_ptr(p, &data_structure)) goto end; /* * If the data structure is "type-specific" and the data type is * given, we drop the data structure. The reasoning is that the * data type is already enough to find the applicable next decoder, * so an additional "type-specific" data structure is extraneous. * * Furthermore, if the OSSL_DECODER caller asked for a type specific * structure under another name, such as "DH", we get a mismatch * if the data structure we just received is "type-specific". * There's only so much you can do without infusing this code with * too special knowledge. */ trace_data_structure = data_structure; if (data_type != NULL && data_structure != NULL && OPENSSL_strcasecmp(data_structure, "type-specific") == 0) data_structure = NULL; OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) %s incoming from previous decoder (%p):\n" " data type: %s, data structure: %s%s\n", (void *)new_data.ctx, LEVEL, (void *)decoder, data_type, trace_data_structure, (trace_data_structure == data_structure ? "" : " (dropped)")); } OSSL_TRACE_END(DECODER); } /* * If we have no more decoders to look through at this point, * we failed */ if (data->current_decoder_inst_index == 0) goto end; if ((loc = BIO_tell(bio)) < 0) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_BIO_LIB); goto end; } if ((cbio = ossl_core_bio_new_from_bio(bio)) == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_MALLOC_FAILURE); goto end; } for (i = data->current_decoder_inst_index; i-- > 0;) { OSSL_DECODER_INSTANCE *new_decoder_inst = sk_OSSL_DECODER_INSTANCE_value(ctx->decoder_insts, i); OSSL_DECODER *new_decoder = OSSL_DECODER_INSTANCE_get_decoder(new_decoder_inst); void *new_decoderctx = OSSL_DECODER_INSTANCE_get_decoder_ctx(new_decoder_inst); const char *new_input_type = OSSL_DECODER_INSTANCE_get_input_type(new_decoder_inst); int n_i_s_was_set = 0; /* We don't care here */ const char *new_input_structure = OSSL_DECODER_INSTANCE_get_input_structure(new_decoder_inst, &n_i_s_was_set); OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) %s [%u] Considering decoder instance %p (decoder %p):\n" " %s with %s\n", (void *)new_data.ctx, LEVEL, (unsigned int)i, (void *)new_decoder_inst, (void *)new_decoder, OSSL_DECODER_get0_name(new_decoder), OSSL_DECODER_get0_properties(new_decoder)); } OSSL_TRACE_END(DECODER); /* * If |decoder| is NULL, it means we've just started, and the caller * may have specified what it expects the initial input to be. If * that's the case, we do this extra check. */ if (decoder == NULL && ctx->start_input_type != NULL && OPENSSL_strcasecmp(ctx->start_input_type, new_input_type) != 0) { OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) %s [%u] the start input type '%s' doesn't match the input type of the considered decoder, skipping...\n", (void *)new_data.ctx, LEVEL, (unsigned int)i, ctx->start_input_type); } OSSL_TRACE_END(DECODER); continue; } /* * If we have a previous decoder, we check that the input type * of the next to be used matches the type of this previous one. * |new_input_type| holds the value of the "input-type" parameter * for the decoder we're currently considering. */ if (decoder != NULL && !OSSL_DECODER_is_a(decoder, new_input_type)) { OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) %s [%u] the input type doesn't match the name of the previous decoder (%p), skipping...\n", (void *)new_data.ctx, LEVEL, (unsigned int)i, (void *)decoder); } OSSL_TRACE_END(DECODER); continue; } /* * If the previous decoder gave us a data type, we check to see * if that matches the decoder we're currently considering. */ if (data_type != NULL && !OSSL_DECODER_is_a(new_decoder, data_type)) { OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) %s [%u] the previous decoder's data type doesn't match the name of the considered decoder, skipping...\n", (void *)new_data.ctx, LEVEL, (unsigned int)i); } OSSL_TRACE_END(DECODER); continue; } /* * If the previous decoder gave us a data structure name, we check * to see that it matches the input data structure of the decoder * we're currently considering. */ if (data_structure != NULL && (new_input_structure == NULL || OPENSSL_strcasecmp(data_structure, new_input_structure) != 0)) { OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) %s [%u] the previous decoder's data structure doesn't match the input structure of the considered decoder, skipping...\n", (void *)new_data.ctx, LEVEL, (unsigned int)i); } OSSL_TRACE_END(DECODER); continue; } /* * If the decoder we're currently considering specifies a structure, * and this check hasn't already been done earlier in this chain of * decoder_process() calls, check that it matches the user provided * input structure, if one is given. */ if (!data->flag_input_structure_checked && ctx->input_structure != NULL && new_input_structure != NULL) { data->flag_input_structure_checked = 1; if (OPENSSL_strcasecmp(new_input_structure, ctx->input_structure) != 0) { OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) %s [%u] the previous decoder's data structure doesn't match the input structure given by the user, skipping...\n", (void *)new_data.ctx, LEVEL, (unsigned int)i); } OSSL_TRACE_END(DECODER); continue; } } /* * Checking the return value of BIO_reset() or BIO_seek() is unsafe. * Furthermore, BIO_reset() is unsafe to use if the source BIO happens * to be a BIO_s_mem(), because the earlier BIO_tell() gives us zero * no matter where we are in the underlying buffer we're reading from. * * So, we simply do a BIO_seek(), and use BIO_tell() that we're back * at the same position. This is a best effort attempt, but BIO_seek() * and BIO_tell() should come as a pair... */ (void)BIO_seek(bio, loc); if (BIO_tell(bio) != loc) goto end; /* Recurse */ OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) %s [%u] Running decoder instance %p\n", (void *)new_data.ctx, LEVEL, (unsigned int)i, (void *)new_decoder_inst); } OSSL_TRACE_END(DECODER); /* * We only care about errors reported from decoder implementations * if it returns false (i.e. there was a fatal error). */ ERR_set_mark(); new_data.current_decoder_inst_index = i; new_data.flag_input_structure_checked = data->flag_input_structure_checked; ok = new_decoder->decode(new_decoderctx, cbio, new_data.ctx->selection, decoder_process, &new_data, ossl_pw_passphrase_callback_dec, &new_data.ctx->pwdata); OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) %s [%u] Running decoder instance %p => %d" " (recursed further: %s, construct called: %s)\n", (void *)new_data.ctx, LEVEL, (unsigned int)i, (void *)new_decoder_inst, ok, new_data.flag_next_level_called ? "yes" : "no", new_data.flag_construct_called ? "yes" : "no"); } OSSL_TRACE_END(DECODER); data->flag_construct_called = new_data.flag_construct_called; /* Break on error or if we tried to construct an object already */ if (!ok || data->flag_construct_called) { ERR_clear_last_mark(); break; } ERR_pop_to_mark(); /* * Break if the decoder implementation that we called recursed, since * that indicates that it successfully decoded something. */ if (new_data.flag_next_level_called) break; } end: ossl_core_bio_free(cbio); BIO_free(new_data.bio); return ok; } diff --git a/crypto/encode_decode/decoder_pkey.c b/crypto/encode_decode/decoder_pkey.c index ed10bb1cee03..ad5e2805319b 100644 --- a/crypto/encode_decode/decoder_pkey.c +++ b/crypto/encode_decode/decoder_pkey.c @@ -1,462 +1,466 @@ /* - * Copyright 2020-2022 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2020-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include #include #include #include #include #include #include #include #include "crypto/evp.h" #include "crypto/decoder.h" #include "encoder_local.h" int OSSL_DECODER_CTX_set_passphrase(OSSL_DECODER_CTX *ctx, const unsigned char *kstr, size_t klen) { return ossl_pw_set_passphrase(&ctx->pwdata, kstr, klen); } int OSSL_DECODER_CTX_set_passphrase_ui(OSSL_DECODER_CTX *ctx, const UI_METHOD *ui_method, void *ui_data) { return ossl_pw_set_ui_method(&ctx->pwdata, ui_method, ui_data); } int OSSL_DECODER_CTX_set_pem_password_cb(OSSL_DECODER_CTX *ctx, pem_password_cb *cb, void *cbarg) { return ossl_pw_set_pem_password_cb(&ctx->pwdata, cb, cbarg); } int OSSL_DECODER_CTX_set_passphrase_cb(OSSL_DECODER_CTX *ctx, OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg) { return ossl_pw_set_ossl_passphrase_cb(&ctx->pwdata, cb, cbarg); } /* * Support for OSSL_DECODER_CTX_new_for_pkey: * The construct data, and collecting keymgmt information for it */ DEFINE_STACK_OF(EVP_KEYMGMT) struct decoder_pkey_data_st { OSSL_LIB_CTX *libctx; char *propq; int selection; STACK_OF(EVP_KEYMGMT) *keymgmts; char *object_type; /* recorded object data type, may be NULL */ void **object; /* Where the result should end up */ }; static int decoder_construct_pkey(OSSL_DECODER_INSTANCE *decoder_inst, const OSSL_PARAM *params, void *construct_data) { struct decoder_pkey_data_st *data = construct_data; OSSL_DECODER *decoder = OSSL_DECODER_INSTANCE_get_decoder(decoder_inst); void *decoderctx = OSSL_DECODER_INSTANCE_get_decoder_ctx(decoder_inst); const OSSL_PROVIDER *decoder_prov = OSSL_DECODER_get0_provider(decoder); EVP_KEYMGMT *keymgmt = NULL; const OSSL_PROVIDER *keymgmt_prov = NULL; int i, end; /* * |object_ref| points to a provider reference to an object, its exact * contents entirely opaque to us, but may be passed to any provider * function that expects this (such as OSSL_FUNC_keymgmt_load(). * * This pointer is considered volatile, i.e. whatever it points at * is assumed to be freed as soon as this function returns. */ void *object_ref = NULL; size_t object_ref_sz = 0; const OSSL_PARAM *p; p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA_TYPE); if (p != NULL) { char *object_type = NULL; if (!OSSL_PARAM_get_utf8_string(p, &object_type, 0)) return 0; OPENSSL_free(data->object_type); data->object_type = object_type; } /* * For stuff that should end up in an EVP_PKEY, we only accept an object * reference for the moment. This enforces that the key data itself * remains with the provider. */ p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_REFERENCE); if (p == NULL || p->data_type != OSSL_PARAM_OCTET_STRING) return 0; object_ref = p->data; object_ref_sz = p->data_size; /* * First, we try to find a keymgmt that comes from the same provider as * the decoder that passed the params. */ end = sk_EVP_KEYMGMT_num(data->keymgmts); for (i = 0; i < end; i++) { keymgmt = sk_EVP_KEYMGMT_value(data->keymgmts, i); keymgmt_prov = EVP_KEYMGMT_get0_provider(keymgmt); if (keymgmt_prov == decoder_prov && evp_keymgmt_has_load(keymgmt) && EVP_KEYMGMT_is_a(keymgmt, data->object_type)) break; } if (i < end) { /* To allow it to be freed further down */ if (!EVP_KEYMGMT_up_ref(keymgmt)) return 0; } else if ((keymgmt = EVP_KEYMGMT_fetch(data->libctx, data->object_type, data->propq)) != NULL) { keymgmt_prov = EVP_KEYMGMT_get0_provider(keymgmt); } if (keymgmt != NULL) { EVP_PKEY *pkey = NULL; void *keydata = NULL; /* * If the EVP_KEYMGMT and the OSSL_DECODER are from the * same provider, we assume that the KEYMGMT has a key loading * function that can handle the provider reference we hold. * * Otherwise, we export from the decoder and import the * result in the keymgmt. */ if (keymgmt_prov == decoder_prov) { keydata = evp_keymgmt_load(keymgmt, object_ref, object_ref_sz); } else { struct evp_keymgmt_util_try_import_data_st import_data; import_data.keymgmt = keymgmt; import_data.keydata = NULL; - import_data.selection = data->selection; + if (data->selection == 0) + /* import/export functions do not tolerate 0 selection */ + import_data.selection = OSSL_KEYMGMT_SELECT_ALL; + else + import_data.selection = data->selection; /* * No need to check for errors here, the value of * |import_data.keydata| is as much an indicator. */ (void)decoder->export_object(decoderctx, object_ref, object_ref_sz, &evp_keymgmt_util_try_import, &import_data); keydata = import_data.keydata; import_data.keydata = NULL; } if (keydata != NULL && (pkey = evp_keymgmt_util_make_pkey(keymgmt, keydata)) == NULL) evp_keymgmt_freedata(keymgmt, keydata); *data->object = pkey; /* * evp_keymgmt_util_make_pkey() increments the reference count when * assigning the EVP_PKEY, so we can free the keymgmt here. */ EVP_KEYMGMT_free(keymgmt); } /* * We successfully looked through, |*ctx->object| determines if we * actually found something. */ return (*data->object != NULL); } static void decoder_clean_pkey_construct_arg(void *construct_data) { struct decoder_pkey_data_st *data = construct_data; if (data != NULL) { sk_EVP_KEYMGMT_pop_free(data->keymgmts, EVP_KEYMGMT_free); OPENSSL_free(data->propq); OPENSSL_free(data->object_type); OPENSSL_free(data); } } static void collect_name(const char *name, void *arg) { STACK_OF(OPENSSL_CSTRING) *names = arg; sk_OPENSSL_CSTRING_push(names, name); } static void collect_keymgmt(EVP_KEYMGMT *keymgmt, void *arg) { STACK_OF(EVP_KEYMGMT) *keymgmts = arg; if (!EVP_KEYMGMT_up_ref(keymgmt) /* ref++ */) return; if (sk_EVP_KEYMGMT_push(keymgmts, keymgmt) <= 0) { EVP_KEYMGMT_free(keymgmt); /* ref-- */ return; } } struct collect_decoder_data_st { STACK_OF(OPENSSL_CSTRING) *names; OSSL_DECODER_CTX *ctx; int total; unsigned int error_occurred:1; }; static void collect_decoder(OSSL_DECODER *decoder, void *arg) { struct collect_decoder_data_st *data = arg; size_t i, end_i; const OSSL_PROVIDER *prov = OSSL_DECODER_get0_provider(decoder); void *provctx = OSSL_PROVIDER_get0_provider_ctx(prov); if (data->error_occurred) return; if (data->names == NULL) { data->error_occurred = 1; return; } /* * Either the caller didn't give a selection, or if they did, * the decoder must tell us if it supports that selection to * be accepted. If the decoder doesn't have |does_selection|, * it's seen as taking anything. */ if (decoder->does_selection != NULL && !decoder->does_selection(provctx, data->ctx->selection)) return; OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) Checking out decoder %p:\n" " %s with %s\n", (void *)data->ctx, (void *)decoder, OSSL_DECODER_get0_name(decoder), OSSL_DECODER_get0_properties(decoder)); } OSSL_TRACE_END(DECODER); end_i = sk_OPENSSL_CSTRING_num(data->names); for (i = 0; i < end_i; i++) { const char *name = sk_OPENSSL_CSTRING_value(data->names, i); if (OSSL_DECODER_is_a(decoder, name)) { void *decoderctx = NULL; OSSL_DECODER_INSTANCE *di = NULL; if ((decoderctx = decoder->newctx(provctx)) == NULL) { data->error_occurred = 1; return; } if ((di = ossl_decoder_instance_new(decoder, decoderctx)) == NULL) { decoder->freectx(decoderctx); data->error_occurred = 1; return; } OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) Checking out decoder %p:\n" " %s with %s\n", (void *)data->ctx, (void *)decoder, OSSL_DECODER_get0_name(decoder), OSSL_DECODER_get0_properties(decoder)); } OSSL_TRACE_END(DECODER); if (!ossl_decoder_ctx_add_decoder_inst(data->ctx, di)) { ossl_decoder_instance_free(di); data->error_occurred = 1; return; } data->total++; /* Success */ return; } } /* Decoder not suitable - but not a fatal error */ data->error_occurred = 0; } int ossl_decoder_ctx_setup_for_pkey(OSSL_DECODER_CTX *ctx, EVP_PKEY **pkey, const char *keytype, OSSL_LIB_CTX *libctx, const char *propquery) { struct decoder_pkey_data_st *process_data = NULL; STACK_OF(OPENSSL_CSTRING) *names = NULL; const char *input_type = ctx->start_input_type; const char *input_structure = ctx->input_structure; int ok = 0; int isecoid = 0; int i, end; if (keytype != NULL && (strcmp(keytype, "id-ecPublicKey") == 0 || strcmp(keytype, "1.2.840.10045.2.1") == 0)) isecoid = 1; OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) Looking for decoders producing %s%s%s%s%s%s\n", (void *)ctx, keytype != NULL ? keytype : "", keytype != NULL ? " keys" : "keys of any type", input_type != NULL ? " from " : "", input_type != NULL ? input_type : "", input_structure != NULL ? " with " : "", input_structure != NULL ? input_structure : ""); } OSSL_TRACE_END(DECODER); if ((process_data = OPENSSL_zalloc(sizeof(*process_data))) == NULL || (propquery != NULL && (process_data->propq = OPENSSL_strdup(propquery)) == NULL) || (process_data->keymgmts = sk_EVP_KEYMGMT_new_null()) == NULL || (names = sk_OPENSSL_CSTRING_new_null()) == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_MALLOC_FAILURE); goto err; } process_data->object = (void **)pkey; process_data->libctx = libctx; process_data->selection = ctx->selection; /* First, find all keymgmts to form goals */ EVP_KEYMGMT_do_all_provided(libctx, collect_keymgmt, process_data->keymgmts); /* Then, we collect all the keymgmt names */ end = sk_EVP_KEYMGMT_num(process_data->keymgmts); for (i = 0; i < end; i++) { EVP_KEYMGMT *keymgmt = sk_EVP_KEYMGMT_value(process_data->keymgmts, i); /* * If the key type is given by the caller, we only use the matching * KEYMGMTs, otherwise we use them all. * We have to special case SM2 here because of its abuse of the EC OID. * The EC OID can be used to identify an EC key or an SM2 key - so if * we have seen that OID we try both key types */ if (keytype == NULL || EVP_KEYMGMT_is_a(keymgmt, keytype) || (isecoid && EVP_KEYMGMT_is_a(keymgmt, "SM2"))) { if (!EVP_KEYMGMT_names_do_all(keymgmt, collect_name, names)) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_INTERNAL_ERROR); goto err; } } } OSSL_TRACE_BEGIN(DECODER) { end = sk_OPENSSL_CSTRING_num(names); BIO_printf(trc_out, " Found %d keytypes (possibly with duplicates)", end); for (i = 0; i < end; i++) BIO_printf(trc_out, "%s%s", i == 0 ? ": " : ", ", sk_OPENSSL_CSTRING_value(names, i)); BIO_printf(trc_out, "\n"); } OSSL_TRACE_END(DECODER); /* * Finally, find all decoders that have any keymgmt of the collected * keymgmt names */ { struct collect_decoder_data_st collect_decoder_data = { NULL, }; collect_decoder_data.names = names; collect_decoder_data.ctx = ctx; OSSL_DECODER_do_all_provided(libctx, collect_decoder, &collect_decoder_data); sk_OPENSSL_CSTRING_free(names); names = NULL; if (collect_decoder_data.error_occurred) goto err; OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) Got %d decoders producing keys\n", (void *)ctx, collect_decoder_data.total); } OSSL_TRACE_END(DECODER); } if (OSSL_DECODER_CTX_get_num_decoders(ctx) != 0) { if (!OSSL_DECODER_CTX_set_construct(ctx, decoder_construct_pkey) || !OSSL_DECODER_CTX_set_construct_data(ctx, process_data) || !OSSL_DECODER_CTX_set_cleanup(ctx, decoder_clean_pkey_construct_arg)) goto err; process_data = NULL; /* Avoid it being freed */ } ok = 1; err: decoder_clean_pkey_construct_arg(process_data); sk_OPENSSL_CSTRING_free(names); return ok; } OSSL_DECODER_CTX * OSSL_DECODER_CTX_new_for_pkey(EVP_PKEY **pkey, const char *input_type, const char *input_structure, const char *keytype, int selection, OSSL_LIB_CTX *libctx, const char *propquery) { OSSL_DECODER_CTX *ctx = NULL; if ((ctx = OSSL_DECODER_CTX_new()) == NULL) { ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_MALLOC_FAILURE); return NULL; } OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) Looking for %s decoders with selection %d\n", (void *)ctx, keytype, selection); BIO_printf(trc_out, " input type: %s, input structure: %s\n", input_type, input_structure); } OSSL_TRACE_END(DECODER); if (OSSL_DECODER_CTX_set_input_type(ctx, input_type) && OSSL_DECODER_CTX_set_input_structure(ctx, input_structure) && OSSL_DECODER_CTX_set_selection(ctx, selection) && ossl_decoder_ctx_setup_for_pkey(ctx, pkey, keytype, libctx, propquery) && OSSL_DECODER_CTX_add_extra(ctx, libctx, propquery)) { OSSL_TRACE_BEGIN(DECODER) { BIO_printf(trc_out, "(ctx %p) Got %d decoders\n", (void *)ctx, OSSL_DECODER_CTX_get_num_decoders(ctx)); } OSSL_TRACE_END(DECODER); return ctx; } OSSL_DECODER_CTX_free(ctx); return NULL; } diff --git a/crypto/engine/eng_lib.c b/crypto/engine/eng_lib.c index dfd53a433195..cfdb5a50f481 100644 --- a/crypto/engine/eng_lib.c +++ b/crypto/engine/eng_lib.c @@ -1,301 +1,307 @@ /* * Copyright 2001-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "e_os.h" #include "eng_local.h" #include #include "internal/refcount.h" CRYPTO_RWLOCK *global_engine_lock; CRYPTO_ONCE engine_lock_init = CRYPTO_ONCE_STATIC_INIT; /* The "new"/"free" stuff first */ DEFINE_RUN_ONCE(do_engine_lock_init) { global_engine_lock = CRYPTO_THREAD_lock_new(); return global_engine_lock != NULL; } ENGINE *ENGINE_new(void) { ENGINE *ret; if (!RUN_ONCE(&engine_lock_init, do_engine_lock_init) || (ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_MALLOC_FAILURE); return NULL; } ret->struct_ref = 1; ENGINE_REF_PRINT(ret, 0, 1); if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_ENGINE, ret, &ret->ex_data)) { OPENSSL_free(ret); return NULL; } return ret; } /* * Placed here (close proximity to ENGINE_new) so that modifications to the * elements of the ENGINE structure are more likely to be caught and changed * here. */ void engine_set_all_null(ENGINE *e) { e->id = NULL; e->name = NULL; e->rsa_meth = NULL; e->dsa_meth = NULL; e->dh_meth = NULL; e->rand_meth = NULL; e->ciphers = NULL; e->digests = NULL; e->destroy = NULL; e->init = NULL; e->finish = NULL; e->ctrl = NULL; e->load_privkey = NULL; e->load_pubkey = NULL; e->cmd_defns = NULL; e->flags = 0; e->dynamic_id = NULL; } int engine_free_util(ENGINE *e, int not_locked) { int i; if (e == NULL) return 1; if (not_locked) CRYPTO_DOWN_REF(&e->struct_ref, &i, global_engine_lock); else i = --e->struct_ref; ENGINE_REF_PRINT(e, 0, -1); if (i > 0) return 1; REF_ASSERT_ISNT(i < 0); /* Free up any dynamically allocated public key methods */ engine_pkey_meths_free(e); engine_pkey_asn1_meths_free(e); /* * Give the ENGINE a chance to do any structural cleanup corresponding to * allocation it did in its constructor (eg. unload error strings) */ if (e->destroy) e->destroy(e); engine_remove_dynamic_id(e, not_locked); CRYPTO_free_ex_data(CRYPTO_EX_INDEX_ENGINE, e, &e->ex_data); OPENSSL_free(e); return 1; } int ENGINE_free(ENGINE *e) { return engine_free_util(e, 1); } /* Cleanup stuff */ /* * engine_cleanup_int() is coded such that anything that does work that will * need cleanup can register a "cleanup" callback here. That way we don't get * linker bloat by referring to all *possible* cleanups, but any linker bloat * into code "X" will cause X's cleanup function to end up here. */ static STACK_OF(ENGINE_CLEANUP_ITEM) *cleanup_stack = NULL; static int int_cleanup_check(int create) { if (cleanup_stack) return 1; if (!create) return 0; cleanup_stack = sk_ENGINE_CLEANUP_ITEM_new_null(); return (cleanup_stack ? 1 : 0); } static ENGINE_CLEANUP_ITEM *int_cleanup_item(ENGINE_CLEANUP_CB *cb) { ENGINE_CLEANUP_ITEM *item; if ((item = OPENSSL_malloc(sizeof(*item))) == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_MALLOC_FAILURE); return NULL; } item->cb = cb; return item; } -void engine_cleanup_add_first(ENGINE_CLEANUP_CB *cb) +int engine_cleanup_add_first(ENGINE_CLEANUP_CB *cb) { ENGINE_CLEANUP_ITEM *item; if (!int_cleanup_check(1)) - return; + return 0; item = int_cleanup_item(cb); - if (item != NULL) - if (sk_ENGINE_CLEANUP_ITEM_insert(cleanup_stack, item, 0) <= 0) - OPENSSL_free(item); + if (item != NULL) { + if (sk_ENGINE_CLEANUP_ITEM_insert(cleanup_stack, item, 0)) + return 1; + OPENSSL_free(item); + } + return 0; } -void engine_cleanup_add_last(ENGINE_CLEANUP_CB *cb) +int engine_cleanup_add_last(ENGINE_CLEANUP_CB *cb) { ENGINE_CLEANUP_ITEM *item; + if (!int_cleanup_check(1)) - return; + return 0; item = int_cleanup_item(cb); if (item != NULL) { - if (sk_ENGINE_CLEANUP_ITEM_push(cleanup_stack, item) <= 0) - OPENSSL_free(item); + if (sk_ENGINE_CLEANUP_ITEM_push(cleanup_stack, item) > 0) + return 1; + OPENSSL_free(item); } + return 0; } /* The API function that performs all cleanup */ static void engine_cleanup_cb_free(ENGINE_CLEANUP_ITEM *item) { (*(item->cb)) (); OPENSSL_free(item); } void engine_cleanup_int(void) { if (int_cleanup_check(0)) { sk_ENGINE_CLEANUP_ITEM_pop_free(cleanup_stack, engine_cleanup_cb_free); cleanup_stack = NULL; } CRYPTO_THREAD_lock_free(global_engine_lock); global_engine_lock = NULL; } /* Now the "ex_data" support */ int ENGINE_set_ex_data(ENGINE *e, int idx, void *arg) { return CRYPTO_set_ex_data(&e->ex_data, idx, arg); } void *ENGINE_get_ex_data(const ENGINE *e, int idx) { return CRYPTO_get_ex_data(&e->ex_data, idx); } /* * Functions to get/set an ENGINE's elements - mainly to avoid exposing the * ENGINE structure itself. */ int ENGINE_set_id(ENGINE *e, const char *id) { if (id == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return 0; } e->id = id; return 1; } int ENGINE_set_name(ENGINE *e, const char *name) { if (name == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return 0; } e->name = name; return 1; } int ENGINE_set_destroy_function(ENGINE *e, ENGINE_GEN_INT_FUNC_PTR destroy_f) { e->destroy = destroy_f; return 1; } int ENGINE_set_init_function(ENGINE *e, ENGINE_GEN_INT_FUNC_PTR init_f) { e->init = init_f; return 1; } int ENGINE_set_finish_function(ENGINE *e, ENGINE_GEN_INT_FUNC_PTR finish_f) { e->finish = finish_f; return 1; } int ENGINE_set_ctrl_function(ENGINE *e, ENGINE_CTRL_FUNC_PTR ctrl_f) { e->ctrl = ctrl_f; return 1; } int ENGINE_set_flags(ENGINE *e, int flags) { e->flags = flags; return 1; } int ENGINE_set_cmd_defns(ENGINE *e, const ENGINE_CMD_DEFN *defns) { e->cmd_defns = defns; return 1; } const char *ENGINE_get_id(const ENGINE *e) { return e->id; } const char *ENGINE_get_name(const ENGINE *e) { return e->name; } ENGINE_GEN_INT_FUNC_PTR ENGINE_get_destroy_function(const ENGINE *e) { return e->destroy; } ENGINE_GEN_INT_FUNC_PTR ENGINE_get_init_function(const ENGINE *e) { return e->init; } ENGINE_GEN_INT_FUNC_PTR ENGINE_get_finish_function(const ENGINE *e) { return e->finish; } ENGINE_CTRL_FUNC_PTR ENGINE_get_ctrl_function(const ENGINE *e) { return e->ctrl; } int ENGINE_get_flags(const ENGINE *e) { return e->flags; } const ENGINE_CMD_DEFN *ENGINE_get_cmd_defns(const ENGINE *e) { return e->cmd_defns; } /* * eng_lib.o is pretty much linked into anything that touches ENGINE already, * so put the "static_state" hack here. */ static int internal_static_hack = 0; void *ENGINE_get_static_state(void) { return &internal_static_hack; } diff --git a/crypto/engine/eng_list.c b/crypto/engine/eng_list.c index 04c73c762864..f2eed3b07174 100644 --- a/crypto/engine/eng_list.c +++ b/crypto/engine/eng_list.c @@ -1,444 +1,447 @@ /* - * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2001-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* We need to use some engine deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include "eng_local.h" /* * The linked-list of pointers to engine types. engine_list_head incorporates * an implicit structural reference but engine_list_tail does not - the * latter is a computational optimization and only points to something that * is already pointed to by its predecessor in the list (or engine_list_head * itself). In the same way, the use of the "prev" pointer in each ENGINE is * to save excessive list iteration, it doesn't correspond to an extra * structural reference. Hence, engine_list_head, and each non-null "next" * pointer account for the list itself assuming exactly 1 structural * reference on each list member. */ static ENGINE *engine_list_head = NULL; static ENGINE *engine_list_tail = NULL; /* * The linked list of currently loaded dynamic engines. */ static ENGINE *engine_dyn_list_head = NULL; static ENGINE *engine_dyn_list_tail = NULL; /* * This cleanup function is only needed internally. If it should be called, * we register it with the "engine_cleanup_int()" stack to be called during * cleanup. */ static void engine_list_cleanup(void) { ENGINE *iterator = engine_list_head; while (iterator != NULL) { ENGINE_remove(iterator); iterator = engine_list_head; } return; } /* * These static functions starting with a lower case "engine_" always take * place when global_engine_lock has been locked up. */ static int engine_list_add(ENGINE *e) { int conflict = 0; ENGINE *iterator = NULL; if (e == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return 0; } iterator = engine_list_head; while (iterator && !conflict) { conflict = (strcmp(iterator->id, e->id) == 0); iterator = iterator->next; } if (conflict) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_CONFLICTING_ENGINE_ID); return 0; } if (engine_list_head == NULL) { /* We are adding to an empty list. */ if (engine_list_tail) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INTERNAL_LIST_ERROR); return 0; } - engine_list_head = e; - e->prev = NULL; /* * The first time the list allocates, we should register the cleanup. */ - engine_cleanup_add_last(engine_list_cleanup); + if (!engine_cleanup_add_last(engine_list_cleanup)) { + ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INTERNAL_LIST_ERROR); + return 0; + } + engine_list_head = e; + e->prev = NULL; } else { /* We are adding to the tail of an existing list. */ if ((engine_list_tail == NULL) || (engine_list_tail->next != NULL)) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INTERNAL_LIST_ERROR); return 0; } engine_list_tail->next = e; e->prev = engine_list_tail; } /* * Having the engine in the list assumes a structural reference. */ e->struct_ref++; ENGINE_REF_PRINT(e, 0, 1); /* However it came to be, e is the last item in the list. */ engine_list_tail = e; e->next = NULL; return 1; } static int engine_list_remove(ENGINE *e) { ENGINE *iterator; if (e == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return 0; } /* We need to check that e is in our linked list! */ iterator = engine_list_head; while (iterator && (iterator != e)) iterator = iterator->next; if (iterator == NULL) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_ENGINE_IS_NOT_IN_LIST); return 0; } /* un-link e from the chain. */ if (e->next) e->next->prev = e->prev; if (e->prev) e->prev->next = e->next; /* Correct our head/tail if necessary. */ if (engine_list_head == e) engine_list_head = e->next; if (engine_list_tail == e) engine_list_tail = e->prev; engine_free_util(e, 0); return 1; } /* Add engine to dynamic engine list. */ int engine_add_dynamic_id(ENGINE *e, ENGINE_DYNAMIC_ID dynamic_id, int not_locked) { int result = 0; ENGINE *iterator = NULL; if (e == NULL) return 0; if (e->dynamic_id == NULL && dynamic_id == NULL) return 0; if (not_locked && !CRYPTO_THREAD_write_lock(global_engine_lock)) return 0; if (dynamic_id != NULL) { iterator = engine_dyn_list_head; while (iterator != NULL) { if (iterator->dynamic_id == dynamic_id) goto err; iterator = iterator->next; } if (e->dynamic_id != NULL) goto err; e->dynamic_id = dynamic_id; } if (engine_dyn_list_head == NULL) { /* We are adding to an empty list. */ if (engine_dyn_list_tail != NULL) goto err; engine_dyn_list_head = e; e->prev_dyn = NULL; } else { /* We are adding to the tail of an existing list. */ if (engine_dyn_list_tail == NULL || engine_dyn_list_tail->next_dyn != NULL) goto err; engine_dyn_list_tail->next_dyn = e; e->prev_dyn = engine_dyn_list_tail; } engine_dyn_list_tail = e; e->next_dyn = NULL; result = 1; err: if (not_locked) CRYPTO_THREAD_unlock(global_engine_lock); return result; } /* Remove engine from dynamic engine list. */ void engine_remove_dynamic_id(ENGINE *e, int not_locked) { if (e == NULL || e->dynamic_id == NULL) return; if (not_locked && !CRYPTO_THREAD_write_lock(global_engine_lock)) return; e->dynamic_id = NULL; /* un-link e from the chain. */ if (e->next_dyn != NULL) e->next_dyn->prev_dyn = e->prev_dyn; if (e->prev_dyn != NULL) e->prev_dyn->next_dyn = e->next_dyn; /* Correct our head/tail if necessary. */ if (engine_dyn_list_head == e) engine_dyn_list_head = e->next_dyn; if (engine_dyn_list_tail == e) engine_dyn_list_tail = e->prev_dyn; if (not_locked) CRYPTO_THREAD_unlock(global_engine_lock); } /* Get the first/last "ENGINE" type available. */ ENGINE *ENGINE_get_first(void) { ENGINE *ret; if (!RUN_ONCE(&engine_lock_init, do_engine_lock_init)) { ERR_raise(ERR_LIB_ENGINE, ERR_R_MALLOC_FAILURE); return NULL; } if (!CRYPTO_THREAD_write_lock(global_engine_lock)) return NULL; ret = engine_list_head; if (ret) { ret->struct_ref++; ENGINE_REF_PRINT(ret, 0, 1); } CRYPTO_THREAD_unlock(global_engine_lock); return ret; } ENGINE *ENGINE_get_last(void) { ENGINE *ret; if (!RUN_ONCE(&engine_lock_init, do_engine_lock_init)) { ERR_raise(ERR_LIB_ENGINE, ERR_R_MALLOC_FAILURE); return NULL; } if (!CRYPTO_THREAD_write_lock(global_engine_lock)) return NULL; ret = engine_list_tail; if (ret) { ret->struct_ref++; ENGINE_REF_PRINT(ret, 0, 1); } CRYPTO_THREAD_unlock(global_engine_lock); return ret; } /* Iterate to the next/previous "ENGINE" type (NULL = end of the list). */ ENGINE *ENGINE_get_next(ENGINE *e) { ENGINE *ret = NULL; if (e == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (!CRYPTO_THREAD_write_lock(global_engine_lock)) return NULL; ret = e->next; if (ret) { /* Return a valid structural reference to the next ENGINE */ ret->struct_ref++; ENGINE_REF_PRINT(ret, 0, 1); } CRYPTO_THREAD_unlock(global_engine_lock); /* Release the structural reference to the previous ENGINE */ ENGINE_free(e); return ret; } ENGINE *ENGINE_get_prev(ENGINE *e) { ENGINE *ret = NULL; if (e == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (!CRYPTO_THREAD_write_lock(global_engine_lock)) return NULL; ret = e->prev; if (ret) { /* Return a valid structural reference to the next ENGINE */ ret->struct_ref++; ENGINE_REF_PRINT(ret, 0, 1); } CRYPTO_THREAD_unlock(global_engine_lock); /* Release the structural reference to the previous ENGINE */ ENGINE_free(e); return ret; } /* Add another "ENGINE" type into the list. */ int ENGINE_add(ENGINE *e) { int to_return = 1; if (e == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return 0; } if ((e->id == NULL) || (e->name == NULL)) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_ID_OR_NAME_MISSING); return 0; } if (!CRYPTO_THREAD_write_lock(global_engine_lock)) return 0; if (!engine_list_add(e)) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INTERNAL_LIST_ERROR); to_return = 0; } CRYPTO_THREAD_unlock(global_engine_lock); return to_return; } /* Remove an existing "ENGINE" type from the array. */ int ENGINE_remove(ENGINE *e) { int to_return = 1; if (e == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (!CRYPTO_THREAD_write_lock(global_engine_lock)) return 0; if (!engine_list_remove(e)) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INTERNAL_LIST_ERROR); to_return = 0; } CRYPTO_THREAD_unlock(global_engine_lock); return to_return; } static void engine_cpy(ENGINE *dest, const ENGINE *src) { dest->id = src->id; dest->name = src->name; dest->rsa_meth = src->rsa_meth; #ifndef OPENSSL_NO_DSA dest->dsa_meth = src->dsa_meth; #endif #ifndef OPENSSL_NO_DH dest->dh_meth = src->dh_meth; #endif #ifndef OPENSSL_NO_EC dest->ec_meth = src->ec_meth; #endif dest->rand_meth = src->rand_meth; dest->ciphers = src->ciphers; dest->digests = src->digests; dest->pkey_meths = src->pkey_meths; dest->destroy = src->destroy; dest->init = src->init; dest->finish = src->finish; dest->ctrl = src->ctrl; dest->load_privkey = src->load_privkey; dest->load_pubkey = src->load_pubkey; dest->cmd_defns = src->cmd_defns; dest->flags = src->flags; dest->dynamic_id = src->dynamic_id; engine_add_dynamic_id(dest, NULL, 0); } ENGINE *ENGINE_by_id(const char *id) { ENGINE *iterator; char *load_dir = NULL; if (id == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return NULL; } ENGINE_load_builtin_engines(); if (!RUN_ONCE(&engine_lock_init, do_engine_lock_init)) { ERR_raise(ERR_LIB_ENGINE, ERR_R_MALLOC_FAILURE); return NULL; } if (!CRYPTO_THREAD_write_lock(global_engine_lock)) return NULL; iterator = engine_list_head; while (iterator && (strcmp(id, iterator->id) != 0)) iterator = iterator->next; if (iterator != NULL) { /* * We need to return a structural reference. If this is an ENGINE * type that returns copies, make a duplicate - otherwise increment * the existing ENGINE's reference count. */ if (iterator->flags & ENGINE_FLAGS_BY_ID_COPY) { ENGINE *cp = ENGINE_new(); if (cp == NULL) iterator = NULL; else { engine_cpy(cp, iterator); iterator = cp; } } else { iterator->struct_ref++; ENGINE_REF_PRINT(iterator, 0, 1); } } CRYPTO_THREAD_unlock(global_engine_lock); if (iterator != NULL) return iterator; /* * Prevent infinite recursion if we're looking for the dynamic engine. */ if (strcmp(id, "dynamic")) { if ((load_dir = ossl_safe_getenv("OPENSSL_ENGINES")) == NULL) load_dir = ENGINESDIR; iterator = ENGINE_by_id("dynamic"); if (!iterator || !ENGINE_ctrl_cmd_string(iterator, "ID", id, 0) || !ENGINE_ctrl_cmd_string(iterator, "DIR_LOAD", "2", 0) || !ENGINE_ctrl_cmd_string(iterator, "DIR_ADD", load_dir, 0) || !ENGINE_ctrl_cmd_string(iterator, "LIST_ADD", "1", 0) || !ENGINE_ctrl_cmd_string(iterator, "LOAD", NULL, 0)) goto notfound; return iterator; } notfound: ENGINE_free(iterator); ERR_raise_data(ERR_LIB_ENGINE, ENGINE_R_NO_SUCH_ENGINE, "id=%s", id); return NULL; /* EEK! Experimental code ends */ } int ENGINE_up_ref(ENGINE *e) { int i; if (e == NULL) { ERR_raise(ERR_LIB_ENGINE, ERR_R_PASSED_NULL_PARAMETER); return 0; } CRYPTO_UP_REF(&e->struct_ref, &i, global_engine_lock); return 1; } diff --git a/crypto/engine/eng_local.h b/crypto/engine/eng_local.h index 03a86299cf88..75bc9e6f1675 100644 --- a/crypto/engine/eng_local.h +++ b/crypto/engine/eng_local.h @@ -1,161 +1,161 @@ /* - * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2001-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifndef OSSL_CRYPTO_ENGINE_ENG_LOCAL_H # define OSSL_CRYPTO_ENGINE_ENG_LOCAL_H # include # include "internal/cryptlib.h" # include "crypto/engine.h" # include "internal/thread_once.h" # include "internal/refcount.h" extern CRYPTO_RWLOCK *global_engine_lock; /* * This prints the engine's pointer address, "struct" or "funct" to * indicate the reference type, the before and after reference count, and * the file:line-number pair. The "ENGINE_REF_PRINT" statements must come * *after* the change. */ # define ENGINE_REF_PRINT(e, isfunct, diff) \ OSSL_TRACE6(ENGINE_REF_COUNT, \ "engine: %p %s from %d to %d (%s:%d)\n", \ (void *)(e), (isfunct ? "funct" : "struct"), \ ((isfunct) \ ? ((e)->funct_ref - (diff)) \ : ((e)->struct_ref - (diff))), \ ((isfunct) ? (e)->funct_ref : (e)->struct_ref), \ (OPENSSL_FILE), (OPENSSL_LINE)) /* * Any code that will need cleanup operations should use these functions to * register callbacks. engine_cleanup_int() will call all registered * callbacks in order. NB: both the "add" functions assume the engine lock to * already be held (in "write" mode). */ typedef void (ENGINE_CLEANUP_CB) (void); typedef struct st_engine_cleanup_item { ENGINE_CLEANUP_CB *cb; } ENGINE_CLEANUP_ITEM; DEFINE_STACK_OF(ENGINE_CLEANUP_ITEM) -void engine_cleanup_add_first(ENGINE_CLEANUP_CB *cb); -void engine_cleanup_add_last(ENGINE_CLEANUP_CB *cb); +int engine_cleanup_add_first(ENGINE_CLEANUP_CB *cb); +int engine_cleanup_add_last(ENGINE_CLEANUP_CB *cb); /* We need stacks of ENGINEs for use in eng_table.c */ DEFINE_STACK_OF(ENGINE) /* * This represents an implementation table. Dependent code should instantiate * it as a (ENGINE_TABLE *) pointer value set initially to NULL. */ typedef struct st_engine_table ENGINE_TABLE; int engine_table_register(ENGINE_TABLE **table, ENGINE_CLEANUP_CB *cleanup, ENGINE *e, const int *nids, int num_nids, int setdefault); void engine_table_unregister(ENGINE_TABLE **table, ENGINE *e); void engine_table_cleanup(ENGINE_TABLE **table); ENGINE *ossl_engine_table_select(ENGINE_TABLE **table, int nid, const char *f, int l); typedef void (engine_table_doall_cb) (int nid, STACK_OF(ENGINE) *sk, ENGINE *def, void *arg); void engine_table_doall(ENGINE_TABLE *table, engine_table_doall_cb *cb, void *arg); /* * Internal versions of API functions that have control over locking. These * are used between C files when functionality needs to be shared but the * caller may already be controlling of the engine lock. */ int engine_unlocked_init(ENGINE *e); int engine_unlocked_finish(ENGINE *e, int unlock_for_handlers); int engine_free_util(ENGINE *e, int not_locked); /* * This function will reset all "set"able values in an ENGINE to NULL. This * won't touch reference counts or ex_data, but is equivalent to calling all * the ENGINE_set_***() functions with a NULL value. */ void engine_set_all_null(ENGINE *e); /* * NB: Bitwise OR-able values for the "flags" variable in ENGINE are now * exposed in engine.h. */ /* Free up dynamically allocated public key methods associated with ENGINE */ void engine_pkey_meths_free(ENGINE *e); void engine_pkey_asn1_meths_free(ENGINE *e); /* Once initialisation function */ extern CRYPTO_ONCE engine_lock_init; DECLARE_RUN_ONCE(do_engine_lock_init) typedef void (*ENGINE_DYNAMIC_ID)(void); int engine_add_dynamic_id(ENGINE *e, ENGINE_DYNAMIC_ID dynamic_id, int not_locked); void engine_remove_dynamic_id(ENGINE *e, int not_locked); /* * This is a structure for storing implementations of various crypto * algorithms and functions. */ struct engine_st { const char *id; const char *name; const RSA_METHOD *rsa_meth; const DSA_METHOD *dsa_meth; const DH_METHOD *dh_meth; const EC_KEY_METHOD *ec_meth; const RAND_METHOD *rand_meth; /* Cipher handling is via this callback */ ENGINE_CIPHERS_PTR ciphers; /* Digest handling is via this callback */ ENGINE_DIGESTS_PTR digests; /* Public key handling via this callback */ ENGINE_PKEY_METHS_PTR pkey_meths; /* ASN1 public key handling via this callback */ ENGINE_PKEY_ASN1_METHS_PTR pkey_asn1_meths; ENGINE_GEN_INT_FUNC_PTR destroy; ENGINE_GEN_INT_FUNC_PTR init; ENGINE_GEN_INT_FUNC_PTR finish; ENGINE_CTRL_FUNC_PTR ctrl; ENGINE_LOAD_KEY_PTR load_privkey; ENGINE_LOAD_KEY_PTR load_pubkey; ENGINE_SSL_CLIENT_CERT_PTR load_ssl_client_cert; const ENGINE_CMD_DEFN *cmd_defns; int flags; /* reference count on the structure itself */ CRYPTO_REF_COUNT struct_ref; /* * reference count on usability of the engine type. NB: This controls the * loading and initialisation of any functionality required by this * engine, whereas the previous count is simply to cope with * (de)allocation of this structure. Hence, running_ref <= struct_ref at * all times. */ int funct_ref; /* A place to store per-ENGINE data */ CRYPTO_EX_DATA ex_data; /* Used to maintain the linked-list of engines. */ struct engine_st *prev; struct engine_st *next; /* Used to maintain the linked-list of dynamic engines. */ struct engine_st *prev_dyn; struct engine_st *next_dyn; ENGINE_DYNAMIC_ID dynamic_id; }; typedef struct st_engine_pile ENGINE_PILE; DEFINE_LHASH_OF(ENGINE_PILE); #endif /* OSSL_CRYPTO_ENGINE_ENG_LOCAL_H */ diff --git a/crypto/engine/eng_table.c b/crypto/engine/eng_table.c index a8209d9e7176..3138a1526002 100644 --- a/crypto/engine/eng_table.c +++ b/crypto/engine/eng_table.c @@ -1,309 +1,313 @@ /* - * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2001-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/cryptlib.h" #include #include #include #include "eng_local.h" /* The type of the items in the table */ struct st_engine_pile { /* The 'nid' of this algorithm/mode */ int nid; /* ENGINEs that implement this algorithm/mode. */ STACK_OF(ENGINE) *sk; /* The default ENGINE to perform this algorithm/mode. */ ENGINE *funct; /* * Zero if 'sk' is newer than the cached 'funct', non-zero otherwise */ int uptodate; }; /* The type exposed in eng_local.h */ struct st_engine_table { LHASH_OF(ENGINE_PILE) piles; }; /* ENGINE_TABLE */ typedef struct st_engine_pile_doall { engine_table_doall_cb *cb; void *arg; } ENGINE_PILE_DOALL; /* Global flags (ENGINE_TABLE_FLAG_***). */ static unsigned int table_flags = 0; /* API function manipulating 'table_flags' */ unsigned int ENGINE_get_table_flags(void) { return table_flags; } void ENGINE_set_table_flags(unsigned int flags) { table_flags = flags; } /* Internal functions for the "piles" hash table */ static unsigned long engine_pile_hash(const ENGINE_PILE *c) { return c->nid; } static int engine_pile_cmp(const ENGINE_PILE *a, const ENGINE_PILE *b) { return a->nid - b->nid; } static int int_table_check(ENGINE_TABLE **t, int create) { LHASH_OF(ENGINE_PILE) *lh; if (*t) return 1; if (!create) return 0; if ((lh = lh_ENGINE_PILE_new(engine_pile_hash, engine_pile_cmp)) == NULL) return 0; *t = (ENGINE_TABLE *)lh; return 1; } /* * Privately exposed (via eng_local.h) functions for adding and/or removing * ENGINEs from the implementation table */ int engine_table_register(ENGINE_TABLE **table, ENGINE_CLEANUP_CB *cleanup, ENGINE *e, const int *nids, int num_nids, int setdefault) { int ret = 0, added = 0; ENGINE_PILE tmplate, *fnd; if (!CRYPTO_THREAD_write_lock(global_engine_lock)) return 0; if (!(*table)) added = 1; if (!int_table_check(table, 1)) goto end; - if (added) - /* The cleanup callback needs to be added */ - engine_cleanup_add_first(cleanup); + /* The cleanup callback needs to be added */ + if (added && !engine_cleanup_add_first(cleanup)) { + lh_ENGINE_PILE_free(&(*table)->piles); + *table = NULL; + } while (num_nids--) { tmplate.nid = *nids; fnd = lh_ENGINE_PILE_retrieve(&(*table)->piles, &tmplate); if (!fnd) { fnd = OPENSSL_malloc(sizeof(*fnd)); if (fnd == NULL) goto end; fnd->uptodate = 1; fnd->nid = *nids; fnd->sk = sk_ENGINE_new_null(); if (!fnd->sk) { OPENSSL_free(fnd); goto end; } fnd->funct = NULL; (void)lh_ENGINE_PILE_insert(&(*table)->piles, fnd); if (lh_ENGINE_PILE_retrieve(&(*table)->piles, &tmplate) != fnd) { sk_ENGINE_free(fnd->sk); OPENSSL_free(fnd); goto end; } } /* A registration shouldn't add duplicate entries */ (void)sk_ENGINE_delete_ptr(fnd->sk, e); /* * if 'setdefault', this ENGINE goes to the head of the list */ if (!sk_ENGINE_push(fnd->sk, e)) goto end; /* "touch" this ENGINE_PILE */ fnd->uptodate = 0; if (setdefault) { if (!engine_unlocked_init(e)) { ERR_raise(ERR_LIB_ENGINE, ENGINE_R_INIT_FAILED); goto end; } if (fnd->funct) engine_unlocked_finish(fnd->funct, 0); fnd->funct = e; fnd->uptodate = 1; } nids++; } ret = 1; end: CRYPTO_THREAD_unlock(global_engine_lock); return ret; } static void int_unregister_cb(ENGINE_PILE *pile, ENGINE *e) { int n; /* Iterate the 'c->sk' stack removing any occurrence of 'e' */ while ((n = sk_ENGINE_find(pile->sk, e)) >= 0) { (void)sk_ENGINE_delete(pile->sk, n); pile->uptodate = 0; } if (pile->funct == e) { engine_unlocked_finish(e, 0); pile->funct = NULL; } } IMPLEMENT_LHASH_DOALL_ARG(ENGINE_PILE, ENGINE); void engine_table_unregister(ENGINE_TABLE **table, ENGINE *e) { if (!CRYPTO_THREAD_write_lock(global_engine_lock)) /* Can't return a value. :( */ return; if (int_table_check(table, 0)) lh_ENGINE_PILE_doall_ENGINE(&(*table)->piles, int_unregister_cb, e); CRYPTO_THREAD_unlock(global_engine_lock); } static void int_cleanup_cb_doall(ENGINE_PILE *p) { if (p == NULL) return; sk_ENGINE_free(p->sk); if (p->funct) engine_unlocked_finish(p->funct, 0); OPENSSL_free(p); } void engine_table_cleanup(ENGINE_TABLE **table) { if (!CRYPTO_THREAD_write_lock(global_engine_lock)) return; if (*table) { lh_ENGINE_PILE_doall(&(*table)->piles, int_cleanup_cb_doall); lh_ENGINE_PILE_free(&(*table)->piles); *table = NULL; } CRYPTO_THREAD_unlock(global_engine_lock); } /* return a functional reference for a given 'nid' */ ENGINE *ossl_engine_table_select(ENGINE_TABLE **table, int nid, const char *f, int l) { ENGINE *ret = NULL; ENGINE_PILE tmplate, *fnd = NULL; int initres, loop = 0; +#ifndef OPENSSL_NO_AUTOLOAD_CONFIG /* Load the config before trying to check if engines are available */ OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL); +#endif if (!(*table)) { OSSL_TRACE3(ENGINE_TABLE, "%s:%d, nid=%d, nothing registered!\n", f, l, nid); return NULL; } ERR_set_mark(); if (!CRYPTO_THREAD_write_lock(global_engine_lock)) goto end; /* * Check again inside the lock otherwise we could race against cleanup * operations. But don't worry about a debug printout */ if (!int_table_check(table, 0)) goto end; tmplate.nid = nid; fnd = lh_ENGINE_PILE_retrieve(&(*table)->piles, &tmplate); if (!fnd) goto end; if (fnd->funct && engine_unlocked_init(fnd->funct)) { OSSL_TRACE4(ENGINE_TABLE, "%s:%d, nid=%d, using ENGINE '%s' cached\n", f, l, nid, fnd->funct->id); ret = fnd->funct; goto end; } if (fnd->uptodate) { ret = fnd->funct; goto end; } trynext: ret = sk_ENGINE_value(fnd->sk, loop++); if (!ret) { OSSL_TRACE3(ENGINE_TABLE, "%s:%d, nid=%d, " "no registered implementations would initialise\n", f, l, nid); goto end; } /* Try to initialise the ENGINE? */ if ((ret->funct_ref > 0) || !(table_flags & ENGINE_TABLE_FLAG_NOINIT)) initres = engine_unlocked_init(ret); else initres = 0; if (initres) { /* Update 'funct' */ if ((fnd->funct != ret) && engine_unlocked_init(ret)) { /* If there was a previous default we release it. */ if (fnd->funct) engine_unlocked_finish(fnd->funct, 0); fnd->funct = ret; OSSL_TRACE4(ENGINE_TABLE, "%s:%d, nid=%d, setting default to '%s'\n", f, l, nid, ret->id); } OSSL_TRACE4(ENGINE_TABLE, "%s:%d, nid=%d, using newly initialised '%s'\n", f, l, nid, ret->id); goto end; } goto trynext; end: /* * If it failed, it is unlikely to succeed again until some future * registrations have taken place. In all cases, we cache. */ if (fnd) fnd->uptodate = 1; if (ret) OSSL_TRACE4(ENGINE_TABLE, "%s:%d, nid=%d, caching ENGINE '%s'\n", f, l, nid, ret->id); else OSSL_TRACE3(ENGINE_TABLE, "%s:%d, nid=%d, caching 'no matching ENGINE'\n", f, l, nid); CRYPTO_THREAD_unlock(global_engine_lock); /* * Whatever happened, any failed init()s are not failures in this * context, so clear our error state. */ ERR_pop_to_mark(); return ret; } /* Table enumeration */ static void int_dall(const ENGINE_PILE *pile, ENGINE_PILE_DOALL *dall) { dall->cb(pile->nid, pile->sk, pile->funct, dall->arg); } IMPLEMENT_LHASH_DOALL_ARG_CONST(ENGINE_PILE, ENGINE_PILE_DOALL); void engine_table_doall(ENGINE_TABLE *table, engine_table_doall_cb *cb, void *arg) { ENGINE_PILE_DOALL dall; dall.cb = cb; dall.arg = arg; if (table) lh_ENGINE_PILE_doall_ENGINE_PILE_DOALL(&table->piles, int_dall, &dall); } diff --git a/crypto/evp/ctrl_params_translate.c b/crypto/evp/ctrl_params_translate.c index b28875037c72..dcd53b43f92b 100644 --- a/crypto/evp/ctrl_params_translate.c +++ b/crypto/evp/ctrl_params_translate.c @@ -1,2869 +1,2875 @@ /* * Copyright 2021-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Some ctrls depend on deprecated functionality. We trust that this is * functionality that remains internally even when 'no-deprecated' is * configured. When we drop #legacy EVP_PKEYs, this source should be * possible to drop as well. */ #include "internal/deprecated.h" #include /* The following includes get us all the EVP_PKEY_CTRL macros */ #include #include #include #include #include /* This include gets us all the OSSL_PARAM key string macros */ #include #include #include #include #include "internal/nelem.h" #include "internal/cryptlib.h" #include "internal/ffc.h" #include "crypto/evp.h" #include "crypto/dh.h" #include "crypto/ec.h" struct translation_ctx_st; /* Forwarding */ struct translation_st; /* Forwarding */ /* * The fixup_args functions are called with the following parameters: * * |state| The state we're called in, explained further at the * end of this comment. * |translation| The translation item, to be pilfered for data as * necessary. * |ctx| The translation context, which contains copies of * the following arguments, applicable according to * the caller. All of the attributes in this context * may be freely modified by the fixup_args function. * For cleanup, call cleanup_translation_ctx(). * * The |state| tells the fixup_args function something about the caller and * what they may expect: * * PKEY The fixup_args function has been called * from an EVP_PKEY payload getter / setter, * and is fully responsible for getting or * setting the requested data. With this * state, the fixup_args function is expected * to use or modify |*params|, depending on * |action_type|. * * PRE_CTRL_TO_PARAMS The fixup_args function has been called * POST_CTRL_TO_PARAMS from EVP_PKEY_CTX_ctrl(), to help with * translating the ctrl data to an OSSL_PARAM * element or back. The calling sequence is * as follows: * * 1. fixup_args(PRE_CTRL_TO_PARAMS, ...) * 2. EVP_PKEY_CTX_set_params() or * EVP_PKEY_CTX_get_params() * 3. fixup_args(POST_CTRL_TO_PARAMS, ...) * * With the PRE_CTRL_TO_PARAMS state, the * fixup_args function is expected to modify * the passed |*params| in whatever way * necessary, when |action_type == SET|. * With the POST_CTRL_TO_PARAMS state, the * fixup_args function is expected to modify * the passed |p2| in whatever way necessary, * when |action_type == GET|. * * The return value from the fixup_args call * with the POST_CTRL_TO_PARAMS state becomes * the return value back to EVP_PKEY_CTX_ctrl(). * * CLEANUP_CTRL_TO_PARAMS The cleanup_args functions has been called * from EVP_PKEY_CTX_ctrl(), to clean up what * the fixup_args function has done, if needed. * * * PRE_CTRL_STR_TO_PARAMS The fixup_args function has been called * POST_CTRL_STR_TO_PARAMS from EVP_PKEY_CTX_ctrl_str(), to help with * translating the ctrl_str data to an * OSSL_PARAM element or back. The calling * sequence is as follows: * * 1. fixup_args(PRE_CTRL_STR_TO_PARAMS, ...) * 2. EVP_PKEY_CTX_set_params() or * EVP_PKEY_CTX_get_params() * 3. fixup_args(POST_CTRL_STR_TO_PARAMS, ...) * * With the PRE_CTRL_STR_TO_PARAMS state, * the fixup_args function is expected to * modify the passed |*params| in whatever * way necessary, when |action_type == SET|. * With the POST_CTRL_STR_TO_PARAMS state, * the fixup_args function is only expected * to return a value. * * CLEANUP_CTRL_STR_TO_PARAMS The cleanup_args functions has been called * from EVP_PKEY_CTX_ctrl_str(), to clean up * what the fixup_args function has done, if * needed. * * PRE_PARAMS_TO_CTRL The fixup_args function has been called * POST_PARAMS_TO_CTRL from EVP_PKEY_CTX_get_params() or * EVP_PKEY_CTX_set_params(), to help with * translating the OSSL_PARAM data to the * corresponding EVP_PKEY_CTX_ctrl() arguments * or the other way around. The calling * sequence is as follows: * * 1. fixup_args(PRE_PARAMS_TO_CTRL, ...) * 2. EVP_PKEY_CTX_ctrl() * 3. fixup_args(POST_PARAMS_TO_CTRL, ...) * * With the PRE_PARAMS_TO_CTRL state, the * fixup_args function is expected to modify * the passed |p1| and |p2| in whatever way * necessary, when |action_type == SET|. * With the POST_PARAMS_TO_CTRL state, the * fixup_args function is expected to * modify the passed |*params| in whatever * way necessary, when |action_type == GET|. * * CLEANUP_PARAMS_TO_CTRL The cleanup_args functions has been called * from EVP_PKEY_CTX_get_params() or * EVP_PKEY_CTX_set_params(), to clean up what * the fixup_args function has done, if needed. */ enum state { PKEY, PRE_CTRL_TO_PARAMS, POST_CTRL_TO_PARAMS, CLEANUP_CTRL_TO_PARAMS, PRE_CTRL_STR_TO_PARAMS, POST_CTRL_STR_TO_PARAMS, CLEANUP_CTRL_STR_TO_PARAMS, PRE_PARAMS_TO_CTRL, POST_PARAMS_TO_CTRL, CLEANUP_PARAMS_TO_CTRL }; enum action { NONE = 0, GET = 1, SET = 2 }; typedef int fixup_args_fn(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx); typedef int cleanup_args_fn(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx); struct translation_ctx_st { /* * The EVP_PKEY_CTX, for calls on that structure, to be pilfered for data * as necessary. */ EVP_PKEY_CTX *pctx; /* * The action type (GET or SET). This may be 0 in some cases, and should * be modified by the fixup_args function in the PRE states. It should * otherwise remain untouched once set. */ enum action action_type; /* * For ctrl to params translation, the actual ctrl command number used. * For params to ctrl translation, 0. */ int ctrl_cmd; /* * For ctrl_str to params translation, the actual ctrl command string * used. In this case, the (string) value is always passed as |p2|. * For params to ctrl translation, this is NULL. Along with it is also * and indicator whether it matched |ctrl_str| or |ctrl_hexstr| in the * translation item. */ const char *ctrl_str; int ishex; /* the ctrl-style int argument. */ int p1; /* the ctrl-style void* argument. */ void *p2; /* a size, for passing back the |p2| size where applicable */ size_t sz; /* pointer to the OSSL_PARAM-style params array. */ OSSL_PARAM *params; /*- * The following are used entirely internally by the fixup_args functions * and should not be touched by the callers, at all. */ /* * Copy of the ctrl-style void* argument, if the fixup_args function * needs to manipulate |p2| but wants to remember original. */ void *orig_p2; /* Diverse types of storage for the needy. */ char name_buf[OSSL_MAX_NAME_SIZE]; void *allocated_buf; void *bufp; size_t buflen; }; struct translation_st { /*- * What this table item does. * * If the item has this set to 0, it means that both GET and SET are * supported, and |fixup_args| will determine which it is. This is to * support translations of ctrls where the action type depends on the * value of |p1| or |p2| (ctrls are really bi-directional, but are * seldom used that way). * * This can be also used in the lookup template when it looks up by * OSSL_PARAM key, to indicate if a setter or a getter called. */ enum action action_type; /*- * Conditions, for params->ctrl translations. * * In table item, |keytype1| and |keytype2| can be set to -1 to indicate * that this item supports all key types (or rather, that |fixup_args| * will check and return an error if it's not supported). * Any of these may be set to 0 to indicate that they are unset. */ int keytype1; /* The EVP_PKEY_XXX type, i.e. NIDs. #legacy */ int keytype2; /* Another EVP_PKEY_XXX type, used for aliases */ int optype; /* The operation type */ /* * Lookup and translation attributes * * |ctrl_num|, |ctrl_str|, |ctrl_hexstr| and |param_key| are lookup * attributes. * * |ctrl_num| may be 0 or that |param_key| may be NULL in the table item, * but not at the same time. If they are, they are simply not used for * lookup. * When |ctrl_num| == 0, no ctrl will be called. Likewise, when * |param_key| == NULL, no OSSL_PARAM setter/getter will be called. * In that case the treatment of the translation item relies entirely on * |fixup_args|, which is then assumed to have side effects. * * As a special case, it's possible to set |ctrl_hexstr| and assign NULL * to |ctrl_str|. That will signal to default_fixup_args() that the * value must always be interpreted as hex. */ int ctrl_num; /* EVP_PKEY_CTRL_xxx */ const char *ctrl_str; /* The corresponding ctrl string */ const char *ctrl_hexstr; /* The alternative "hex{str}" ctrl string */ const char *param_key; /* The corresponding OSSL_PARAM key */ /* * The appropriate OSSL_PARAM data type. This may be 0 to indicate that * this OSSL_PARAM may have more than one data type, depending on input * material. In this case, |fixup_args| is expected to check and handle * it. */ unsigned int param_data_type; /* * Fixer functions * * |fixup_args| is always called before (for SET) or after (for GET) * the actual ctrl / OSSL_PARAM function. */ fixup_args_fn *fixup_args; }; /*- * Fixer function implementations * ============================== */ /* * default_check isn't a fixer per se, but rather a helper function to * perform certain standard checks. */ static int default_check(enum state state, const struct translation_st *translation, const struct translation_ctx_st *ctx) { switch (state) { default: break; case PRE_CTRL_TO_PARAMS: if (!ossl_assert(translation != NULL)) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return -2; } if (!ossl_assert(translation->param_key != 0) || !ossl_assert(translation->param_data_type != 0)) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return -1; } break; case PRE_CTRL_STR_TO_PARAMS: /* * For ctrl_str to params translation, we allow direct use of * OSSL_PARAM keys as ctrl_str keys. Therefore, it's possible that * we end up with |translation == NULL|, which is fine. The fixup * function will have to deal with it carefully. */ if (translation != NULL) { if (!ossl_assert(translation->action_type != GET)) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return -2; } if (!ossl_assert(translation->param_key != NULL) || !ossl_assert(translation->param_data_type != 0)) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return 0; } } break; case PRE_PARAMS_TO_CTRL: case POST_PARAMS_TO_CTRL: if (!ossl_assert(translation != NULL)) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return -2; } if (!ossl_assert(translation->ctrl_num != 0) || !ossl_assert(translation->param_data_type != 0)) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return -1; } } /* Nothing else to check */ return 1; } /*- * default_fixup_args fixes up all sorts of arguments, governed by the * diverse attributes in the translation item. It covers all "standard" * base ctrl functionality, meaning it can handle basic conversion of * data between p1+p2 (SET) or return value+p2 (GET) as long as the values * don't have extra semantics (such as NIDs, OIDs, that sort of stuff). * Extra semantics must be handled via specific fixup_args functions. * * The following states and action type combinations have standard handling * done in this function: * * PRE_CTRL_TO_PARAMS, 0 - ERROR. action type must be * determined by a fixup function. * PRE_CTRL_TO_PARAMS, SET | GET - |p1| and |p2| are converted to an * OSSL_PARAM according to the data * type given in |translattion|. * For OSSL_PARAM_UNSIGNED_INTEGER, * a BIGNUM passed as |p2| is accepted. * POST_CTRL_TO_PARAMS, GET - If the OSSL_PARAM data type is a * STRING or PTR type, |p1| is set * to the OSSL_PARAM return size, and * |p2| is set to the string. * PRE_CTRL_STR_TO_PARAMS, !SET - ERROR. That combination is not * supported. * PRE_CTRL_STR_TO_PARAMS, SET - |p2| is taken as a string, and is * converted to an OSSL_PARAM in a * standard manner, guided by the * param key and data type from * |translation|. * PRE_PARAMS_TO_CTRL, SET - the OSSL_PARAM is converted to * |p1| and |p2| according to the * data type given in |translation| * For OSSL_PARAM_UNSIGNED_INTEGER, * if |p2| is non-NULL, then |*p2| * is assigned a BIGNUM, otherwise * |p1| is assigned an unsigned int. * POST_PARAMS_TO_CTRL, GET - |p1| and |p2| are converted to * an OSSL_PARAM, in the same manner * as for the combination of * PRE_CTRL_TO_PARAMS, SET. */ static int default_fixup_args(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { int ret; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; switch (state) { default: /* For states this function should never have been called with */ ERR_raise_data(ERR_LIB_EVP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED, "[action:%d, state:%d]", ctx->action_type, state); return 0; /* * PRE_CTRL_TO_PARAMS and POST_CTRL_TO_PARAMS handle ctrl to params * translations. PRE_CTRL_TO_PARAMS is responsible for preparing * |*params|, and POST_CTRL_TO_PARAMS is responsible for bringing the * result back to |*p2| and the return value. */ case PRE_CTRL_TO_PARAMS: /* This is ctrl to params translation, so we need an OSSL_PARAM key */ if (ctx->action_type == NONE) { /* * No action type is an error here. That's a case for a * special fixup function. */ ERR_raise_data(ERR_LIB_EVP, ERR_R_UNSUPPORTED, "[action:%d, state:%d]", ctx->action_type, state); return 0; } if (translation->optype != 0) { if ((EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx->pctx) && ctx->pctx->op.sig.algctx == NULL) || (EVP_PKEY_CTX_IS_DERIVE_OP(ctx->pctx) && ctx->pctx->op.kex.algctx == NULL) || (EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx->pctx) && ctx->pctx->op.ciph.algctx == NULL) || (EVP_PKEY_CTX_IS_KEM_OP(ctx->pctx) && ctx->pctx->op.encap.algctx == NULL) /* * The following may be unnecessary, but we have them * for good measure... */ || (EVP_PKEY_CTX_IS_GEN_OP(ctx->pctx) && ctx->pctx->op.keymgmt.genctx == NULL) || (EVP_PKEY_CTX_IS_FROMDATA_OP(ctx->pctx) && ctx->pctx->op.keymgmt.genctx == NULL)) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); /* Uses the same return values as EVP_PKEY_CTX_ctrl */ return -2; } } /* * OSSL_PARAM_construct_TYPE() works equally well for both SET and GET. */ switch (translation->param_data_type) { case OSSL_PARAM_INTEGER: *ctx->params = OSSL_PARAM_construct_int(translation->param_key, &ctx->p1); break; case OSSL_PARAM_UNSIGNED_INTEGER: /* * BIGNUMs are passed via |p2|. For all ctrl's that just want * to pass a simple integer via |p1|, |p2| is expected to be * NULL. * * Note that this allocates a buffer, which the cleanup function * must deallocate. */ if (ctx->p2 != NULL) { if (ctx->action_type == SET) { ctx->buflen = BN_num_bytes(ctx->p2); if ((ctx->allocated_buf = OPENSSL_malloc(ctx->buflen)) == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE); return 0; } if (BN_bn2nativepad(ctx->p2, ctx->allocated_buf, ctx->buflen) < 0) { OPENSSL_free(ctx->allocated_buf); ctx->allocated_buf = NULL; return 0; } *ctx->params = OSSL_PARAM_construct_BN(translation->param_key, ctx->allocated_buf, ctx->buflen); } else { /* * No support for getting a BIGNUM by ctrl, this needs * fixup_args function support. */ ERR_raise_data(ERR_LIB_EVP, ERR_R_UNSUPPORTED, "[action:%d, state:%d] trying to get a " "BIGNUM via ctrl call", ctx->action_type, state); return 0; } } else { *ctx->params = OSSL_PARAM_construct_uint(translation->param_key, (unsigned int *)&ctx->p1); } break; case OSSL_PARAM_UTF8_STRING: *ctx->params = OSSL_PARAM_construct_utf8_string(translation->param_key, ctx->p2, (size_t)ctx->p1); break; case OSSL_PARAM_UTF8_PTR: *ctx->params = OSSL_PARAM_construct_utf8_ptr(translation->param_key, ctx->p2, (size_t)ctx->p1); break; case OSSL_PARAM_OCTET_STRING: *ctx->params = OSSL_PARAM_construct_octet_string(translation->param_key, ctx->p2, (size_t)ctx->p1); break; case OSSL_PARAM_OCTET_PTR: *ctx->params = OSSL_PARAM_construct_octet_ptr(translation->param_key, ctx->p2, (size_t)ctx->p1); break; } break; case POST_CTRL_TO_PARAMS: /* * Because EVP_PKEY_CTX_ctrl() returns the length of certain objects * as its return value, we need to ensure that we do it here as well, * for the OSSL_PARAM data types where this makes sense. */ if (ctx->action_type == GET) { switch (translation->param_data_type) { case OSSL_PARAM_UTF8_STRING: case OSSL_PARAM_UTF8_PTR: case OSSL_PARAM_OCTET_STRING: case OSSL_PARAM_OCTET_PTR: ctx->p1 = (int)ctx->params[0].return_size; break; } } break; /* * PRE_CTRL_STR_TO_PARAMS and POST_CTRL_STR_TO_PARAMS handle ctrl_str to * params translations. PRE_CTRL_TO_PARAMS is responsible for preparing * |*params|, and POST_CTRL_TO_PARAMS currently has nothing to do, since * there's no support for getting data via ctrl_str calls. */ case PRE_CTRL_STR_TO_PARAMS: { /* This is ctrl_str to params translation */ const char *tmp_ctrl_str = ctx->ctrl_str; const char *orig_ctrl_str = ctx->ctrl_str; const char *orig_value = ctx->p2; const OSSL_PARAM *settable = NULL; int exists = 0; /* Only setting is supported here */ if (ctx->action_type != SET) { ERR_raise_data(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED, "[action:%d, state:%d] only setting allowed", ctx->action_type, state); return 0; } /* * If no translation exists, we simply pass the control string * unmodified. */ if (translation != NULL) { tmp_ctrl_str = ctx->ctrl_str = translation->param_key; if (ctx->ishex) { strcpy(ctx->name_buf, "hex"); if (OPENSSL_strlcat(ctx->name_buf, tmp_ctrl_str, sizeof(ctx->name_buf)) <= 3) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return -1; } tmp_ctrl_str = ctx->name_buf; } } settable = EVP_PKEY_CTX_settable_params(ctx->pctx); if (!OSSL_PARAM_allocate_from_text(ctx->params, settable, tmp_ctrl_str, ctx->p2, strlen(ctx->p2), &exists)) { if (!exists) { ERR_raise_data(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED, "[action:%d, state:%d] name=%s, value=%s", ctx->action_type, state, orig_ctrl_str, orig_value); return -2; } return 0; } ctx->allocated_buf = ctx->params->data; ctx->buflen = ctx->params->data_size; } break; case POST_CTRL_STR_TO_PARAMS: /* Nothing to be done */ break; /* * PRE_PARAMS_TO_CTRL and POST_PARAMS_TO_CTRL handle params to ctrl * translations. PRE_PARAMS_TO_CTRL is responsible for preparing * |p1| and |p2|, and POST_PARAMS_TO_CTRL is responsible for bringing * the EVP_PKEY_CTX_ctrl() return value (passed as |p1|) and |p2| back * to |*params|. * * PKEY is treated just like POST_PARAMS_TO_CTRL, making it easy * for the related fixup_args functions to just set |p1| and |p2| * appropriately and leave it to this section of code to fix up * |ctx->params| accordingly. */ case PKEY: case POST_PARAMS_TO_CTRL: ret = ctx->p1; /* FALLTHRU */ case PRE_PARAMS_TO_CTRL: { /* This is params to ctrl translation */ if (state == PRE_PARAMS_TO_CTRL && ctx->action_type == SET) { /* For the PRE state, only setting needs some work to be done */ /* When setting, we populate |p1| and |p2| from |*params| */ switch (translation->param_data_type) { case OSSL_PARAM_INTEGER: return OSSL_PARAM_get_int(ctx->params, &ctx->p1); case OSSL_PARAM_UNSIGNED_INTEGER: if (ctx->p2 != NULL) { /* BIGNUM passed down with p2 */ if (!OSSL_PARAM_get_BN(ctx->params, ctx->p2)) return 0; } else { /* Normal C unsigned int passed down */ if (!OSSL_PARAM_get_uint(ctx->params, (unsigned int *)&ctx->p1)) return 0; } return 1; case OSSL_PARAM_UTF8_STRING: return OSSL_PARAM_get_utf8_string(ctx->params, ctx->p2, ctx->sz); case OSSL_PARAM_OCTET_STRING: return OSSL_PARAM_get_octet_string(ctx->params, &ctx->p2, ctx->sz, (size_t *)&ctx->p1); case OSSL_PARAM_OCTET_PTR: return OSSL_PARAM_get_octet_ptr(ctx->params, ctx->p2, &ctx->sz); default: ERR_raise_data(ERR_LIB_EVP, ERR_R_UNSUPPORTED, "[action:%d, state:%d] " "unknown OSSL_PARAM data type %d", ctx->action_type, state, translation->param_data_type); return 0; } } else if ((state == POST_PARAMS_TO_CTRL || state == PKEY) && ctx->action_type == GET) { /* For the POST state, only getting needs some work to be done */ unsigned int param_data_type = translation->param_data_type; size_t size = (size_t)ctx->p1; if (state == PKEY) size = ctx->sz; if (param_data_type == 0) { /* we must have a fixup_args function to work */ if (!ossl_assert(translation->fixup_args != NULL)) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return 0; } param_data_type = ctx->params->data_type; } /* When getting, we populate |*params| from |p1| and |p2| */ switch (param_data_type) { case OSSL_PARAM_INTEGER: return OSSL_PARAM_set_int(ctx->params, ctx->p1); case OSSL_PARAM_UNSIGNED_INTEGER: if (ctx->p2 != NULL) { /* BIGNUM passed back */ return OSSL_PARAM_set_BN(ctx->params, ctx->p2); } else { /* Normal C unsigned int passed back */ return OSSL_PARAM_set_uint(ctx->params, (unsigned int)ctx->p1); } return 0; case OSSL_PARAM_UTF8_STRING: return OSSL_PARAM_set_utf8_string(ctx->params, ctx->p2); case OSSL_PARAM_OCTET_STRING: return OSSL_PARAM_set_octet_string(ctx->params, ctx->p2, size); case OSSL_PARAM_OCTET_PTR: return OSSL_PARAM_set_octet_ptr(ctx->params, *(void **)ctx->p2, size); default: ERR_raise_data(ERR_LIB_EVP, ERR_R_UNSUPPORTED, "[action:%d, state:%d] " "unsupported OSSL_PARAM data type %d", ctx->action_type, state, translation->param_data_type); return 0; } } else if (state == PRE_PARAMS_TO_CTRL && ctx->action_type == GET) { if (translation->param_data_type == OSSL_PARAM_OCTET_PTR) ctx->p2 = &ctx->bufp; } } /* Any other combination is simply pass-through */ break; } return ret; } static int cleanup_translation_ctx(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { if (ctx->allocated_buf != NULL) OPENSSL_free(ctx->allocated_buf); ctx->allocated_buf = NULL; return 1; } /* * fix_cipher_md fixes up an EVP_CIPHER / EVP_MD to its name on SET, * and cipher / md name to EVP_MD on GET. */ static const char *get_cipher_name(void *cipher) { return EVP_CIPHER_get0_name(cipher); } static const char *get_md_name(void *md) { return EVP_MD_get0_name(md); } static const void *get_cipher_by_name(OSSL_LIB_CTX *libctx, const char *name) { return evp_get_cipherbyname_ex(libctx, name); } static const void *get_md_by_name(OSSL_LIB_CTX *libctx, const char *name) { return evp_get_digestbyname_ex(libctx, name); } static int fix_cipher_md(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx, const char *(*get_name)(void *algo), const void *(*get_algo_by_name)(OSSL_LIB_CTX *libctx, const char *name)) { int ret = 1; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; if (state == PRE_CTRL_TO_PARAMS && ctx->action_type == GET) { /* * |ctx->p2| contains the address to an EVP_CIPHER or EVP_MD pointer * to be filled in. We need to remember it, then make |ctx->p2| * point at a buffer to be filled in with the name, and |ctx->p1| * with its size. default_fixup_args() will take care of the rest * for us. */ ctx->orig_p2 = ctx->p2; ctx->p2 = ctx->name_buf; ctx->p1 = sizeof(ctx->name_buf); } else if (state == PRE_CTRL_TO_PARAMS && ctx->action_type == SET) { /* * In different parts of OpenSSL, this ctrl command is used * differently. Some calls pass a NID as p1, others pass an * EVP_CIPHER pointer as p2... */ ctx->p2 = (char *)(ctx->p2 == NULL ? OBJ_nid2sn(ctx->p1) : get_name(ctx->p2)); ctx->p1 = strlen(ctx->p2); } else if (state == POST_PARAMS_TO_CTRL && ctx->action_type == GET) { ctx->p2 = (ctx->p2 == NULL ? "" : (char *)get_name(ctx->p2)); ctx->p1 = strlen(ctx->p2); } if ((ret = default_fixup_args(state, translation, ctx)) <= 0) return ret; if (state == POST_CTRL_TO_PARAMS && ctx->action_type == GET) { /* * Here's how we re-use |ctx->orig_p2| that was set in the * PRE_CTRL_TO_PARAMS state above. */ *(void **)ctx->orig_p2 = (void *)get_algo_by_name(ctx->pctx->libctx, ctx->p2); ctx->p1 = 1; } else if (state == PRE_PARAMS_TO_CTRL && ctx->action_type == SET) { ctx->p2 = (void *)get_algo_by_name(ctx->pctx->libctx, ctx->p2); ctx->p1 = 0; } return ret; } static int fix_cipher(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { return fix_cipher_md(state, translation, ctx, get_cipher_name, get_cipher_by_name); } static int fix_md(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { return fix_cipher_md(state, translation, ctx, get_md_name, get_md_by_name); } static int fix_distid_len(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { int ret = default_fixup_args(state, translation, ctx); if (ret > 0) { ret = 0; if ((state == POST_CTRL_TO_PARAMS || state == POST_CTRL_STR_TO_PARAMS) && ctx->action_type == GET) { *(size_t *)ctx->p2 = ctx->sz; ret = 1; } } return ret; } struct kdf_type_map_st { int kdf_type_num; const char *kdf_type_str; }; static int fix_kdf_type(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx, const struct kdf_type_map_st *kdf_type_map) { /* * The EVP_PKEY_CTRL_DH_KDF_TYPE ctrl command is a bit special, in * that it's used both for setting a value, and for getting it, all * depending on the value if |p1|; if |p1| is -2, the backend is * supposed to place the current kdf type in |p2|, and if not, |p1| * is interpreted as the new kdf type. */ int ret = 0; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; if (state == PRE_CTRL_TO_PARAMS) { /* * In |translations|, the initial value for |ctx->action_type| must * be NONE. */ if (!ossl_assert(ctx->action_type == NONE)) return 0; /* The action type depends on the value of *p1 */ if (ctx->p1 == -2) { /* * The OSSL_PARAMS getter needs space to store a copy of the kdf * type string. We use |ctx->name_buf|, which has enough space * allocated. * * (this wouldn't be needed if the OSSL_xxx_PARAM_KDF_TYPE * had the data type OSSL_PARAM_UTF8_PTR) */ ctx->p2 = ctx->name_buf; ctx->p1 = sizeof(ctx->name_buf); ctx->action_type = GET; } else { ctx->action_type = SET; } } if ((ret = default_check(state, translation, ctx)) <= 0) return ret; if ((state == PRE_CTRL_TO_PARAMS && ctx->action_type == SET) || (state == POST_PARAMS_TO_CTRL && ctx->action_type == GET)) { ret = -2; /* Convert KDF type numbers to strings */ for (; kdf_type_map->kdf_type_str != NULL; kdf_type_map++) if (ctx->p1 == kdf_type_map->kdf_type_num) { ctx->p2 = (char *)kdf_type_map->kdf_type_str; ret = 1; break; } if (ret <= 0) goto end; ctx->p1 = strlen(ctx->p2); } if ((ret = default_fixup_args(state, translation, ctx)) <= 0) return ret; if ((state == POST_CTRL_TO_PARAMS && ctx->action_type == GET) || (state == PRE_PARAMS_TO_CTRL && ctx->action_type == SET)) { ctx->p1 = ret = -1; /* Convert KDF type strings to numbers */ for (; kdf_type_map->kdf_type_str != NULL; kdf_type_map++) if (OPENSSL_strcasecmp(ctx->p2, kdf_type_map->kdf_type_str) == 0) { ctx->p1 = kdf_type_map->kdf_type_num; ret = 1; break; } ctx->p2 = NULL; } else if (state == PRE_PARAMS_TO_CTRL && ctx->action_type == GET) { ctx->p1 = -2; } end: return ret; } /* EVP_PKEY_CTRL_DH_KDF_TYPE */ static int fix_dh_kdf_type(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { static const struct kdf_type_map_st kdf_type_map[] = { { EVP_PKEY_DH_KDF_NONE, "" }, { EVP_PKEY_DH_KDF_X9_42, OSSL_KDF_NAME_X942KDF_ASN1 }, { 0, NULL } }; return fix_kdf_type(state, translation, ctx, kdf_type_map); } /* EVP_PKEY_CTRL_EC_KDF_TYPE */ static int fix_ec_kdf_type(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { static const struct kdf_type_map_st kdf_type_map[] = { { EVP_PKEY_ECDH_KDF_NONE, "" }, { EVP_PKEY_ECDH_KDF_X9_63, OSSL_KDF_NAME_X963KDF }, { 0, NULL } }; return fix_kdf_type(state, translation, ctx, kdf_type_map); } /* EVP_PKEY_CTRL_DH_KDF_OID, EVP_PKEY_CTRL_GET_DH_KDF_OID, ...??? */ static int fix_oid(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { int ret; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; if ((state == PRE_CTRL_TO_PARAMS && ctx->action_type == SET) || (state == POST_PARAMS_TO_CTRL && ctx->action_type == GET)) { /* * We're translating from ctrl to params and setting the OID, or * we're translating from params to ctrl and getting the OID. * Either way, |ctx->p2| points at an ASN1_OBJECT, and needs to have * that replaced with the corresponding name. * default_fixup_args() will then be able to convert that to the * corresponding OSSL_PARAM. */ OBJ_obj2txt(ctx->name_buf, sizeof(ctx->name_buf), ctx->p2, 0); ctx->p2 = (char *)ctx->name_buf; ctx->p1 = 0; /* let default_fixup_args() figure out the length */ } if ((ret = default_fixup_args(state, translation, ctx)) <= 0) return ret; if ((state == PRE_PARAMS_TO_CTRL && ctx->action_type == SET) || (state == POST_CTRL_TO_PARAMS && ctx->action_type == GET)) { /* * We're translating from ctrl to params and setting the OID name, * or we're translating from params to ctrl and getting the OID * name. Either way, default_fixup_args() has placed the OID name * in |ctx->p2|, all we need to do now is to replace that with the * corresponding ASN1_OBJECT. */ ctx->p2 = (ASN1_OBJECT *)OBJ_txt2obj(ctx->p2, 0); } return ret; } /* EVP_PKEY_CTRL_DH_NID */ static int fix_dh_nid(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { int ret; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; /* This is only settable */ if (ctx->action_type != SET) return 0; if (state == PRE_CTRL_TO_PARAMS) { if ((ctx->p2 = (char *)ossl_ffc_named_group_get_name (ossl_ffc_uid_to_dh_named_group(ctx->p1))) == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_VALUE); return 0; } ctx->p1 = 0; } return default_fixup_args(state, translation, ctx); } /* EVP_PKEY_CTRL_DH_RFC5114 */ static int fix_dh_nid5114(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { int ret; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; /* This is only settable */ if (ctx->action_type != SET) return 0; switch (state) { case PRE_CTRL_TO_PARAMS: if ((ctx->p2 = (char *)ossl_ffc_named_group_get_name (ossl_ffc_uid_to_dh_named_group(ctx->p1))) == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_VALUE); return 0; } ctx->p1 = 0; break; case PRE_CTRL_STR_TO_PARAMS: if (ctx->p2 == NULL) return 0; if ((ctx->p2 = (char *)ossl_ffc_named_group_get_name (ossl_ffc_uid_to_dh_named_group(atoi(ctx->p2)))) == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_VALUE); return 0; } ctx->p1 = 0; break; default: break; } return default_fixup_args(state, translation, ctx); } /* EVP_PKEY_CTRL_DH_PARAMGEN_TYPE */ static int fix_dh_paramgen_type(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { int ret; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; /* This is only settable */ if (ctx->action_type != SET) return 0; if (state == PRE_CTRL_STR_TO_PARAMS) { if ((ctx->p2 = (char *)ossl_dh_gen_type_id2name(atoi(ctx->p2))) == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_VALUE); return 0; } ctx->p1 = strlen(ctx->p2); } return default_fixup_args(state, translation, ctx); } /* EVP_PKEY_CTRL_EC_PARAM_ENC */ static int fix_ec_param_enc(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { int ret; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; /* This is currently only settable */ if (ctx->action_type != SET) return 0; if (state == PRE_CTRL_TO_PARAMS) { switch (ctx->p1) { case OPENSSL_EC_EXPLICIT_CURVE: ctx->p2 = OSSL_PKEY_EC_ENCODING_EXPLICIT; break; case OPENSSL_EC_NAMED_CURVE: ctx->p2 = OSSL_PKEY_EC_ENCODING_GROUP; break; default: ret = -2; goto end; } ctx->p1 = 0; } if ((ret = default_fixup_args(state, translation, ctx)) <= 0) return ret; if (state == PRE_PARAMS_TO_CTRL) { if (strcmp(ctx->p2, OSSL_PKEY_EC_ENCODING_EXPLICIT) == 0) ctx->p1 = OPENSSL_EC_EXPLICIT_CURVE; else if (strcmp(ctx->p2, OSSL_PKEY_EC_ENCODING_GROUP) == 0) ctx->p1 = OPENSSL_EC_NAMED_CURVE; else ctx->p1 = ret = -2; ctx->p2 = NULL; } end: if (ret == -2) ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return ret; } /* EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID */ static int fix_ec_paramgen_curve_nid(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { char *p2 = NULL; int ret; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; /* This is currently only settable */ if (ctx->action_type != SET) return 0; if (state == PRE_CTRL_TO_PARAMS) { ctx->p2 = (char *)OBJ_nid2sn(ctx->p1); ctx->p1 = 0; } else if (state == PRE_PARAMS_TO_CTRL) { /* * We're translating from params to ctrl and setting the curve name. * The ctrl function needs it to be a NID, but meanwhile, we need * space to get the curve name from the param. |ctx->name_buf| is * sufficient for that. * The double indirection is necessary for default_fixup_args()'s * call of OSSL_PARAM_get_utf8_string() to be done correctly. */ p2 = ctx->name_buf; ctx->p2 = &p2; ctx->sz = sizeof(ctx->name_buf); } if ((ret = default_fixup_args(state, translation, ctx)) <= 0) return ret; if (state == PRE_PARAMS_TO_CTRL) { ctx->p1 = OBJ_sn2nid(p2); ctx->p2 = NULL; } return ret; } /* EVP_PKEY_CTRL_EC_ECDH_COFACTOR */ static int fix_ecdh_cofactor(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { /* * The EVP_PKEY_CTRL_EC_ECDH_COFACTOR ctrl command is a bit special, in * that it's used both for setting a value, and for getting it, all * depending on the value if |ctx->p1|; if |ctx->p1| is -2, the backend is * supposed to place the current cofactor mode in |ctx->p2|, and if not, * |ctx->p1| is interpreted as the new cofactor mode. */ int ret = 0; if (state == PRE_CTRL_TO_PARAMS) { /* * The initial value for |ctx->action_type| must be zero. * evp_pkey_ctrl_to_params() takes it from the translation item. */ if (!ossl_assert(ctx->action_type == NONE)) return 0; /* The action type depends on the value of ctx->p1 */ if (ctx->p1 == -2) ctx->action_type = GET; else ctx->action_type = SET; } else if (state == PRE_CTRL_STR_TO_PARAMS) { ctx->action_type = SET; } else if (state == PRE_PARAMS_TO_CTRL) { /* The initial value for |ctx->action_type| must not be zero. */ if (!ossl_assert(ctx->action_type != NONE)) return 0; } if ((ret = default_check(state, translation, ctx)) <= 0) return ret; if (state == PRE_CTRL_TO_PARAMS && ctx->action_type == SET) { if (ctx->p1 < -1 || ctx->p1 > 1) { /* Uses the same return value of pkey_ec_ctrl() */ return -2; } } if ((ret = default_fixup_args(state, translation, ctx)) <= 0) return ret; if (state == POST_CTRL_TO_PARAMS && ctx->action_type == GET) { if (ctx->p1 < 0 || ctx->p1 > 1) { /* * The provider should return either 0 or 1, any other value is a * provider error. */ ctx->p1 = ret = -1; } } else if (state == PRE_PARAMS_TO_CTRL && ctx->action_type == GET) { ctx->p1 = -2; } return ret; } /* EVP_PKEY_CTRL_RSA_PADDING, EVP_PKEY_CTRL_GET_RSA_PADDING */ static int fix_rsa_padding_mode(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { static const OSSL_ITEM str_value_map[] = { { RSA_PKCS1_PADDING, "pkcs1" }, { RSA_NO_PADDING, "none" }, { RSA_PKCS1_OAEP_PADDING, "oaep" }, { RSA_PKCS1_OAEP_PADDING, "oeap" }, { RSA_X931_PADDING, "x931" }, { RSA_PKCS1_PSS_PADDING, "pss" }, /* Special case, will pass directly as an integer */ { RSA_PKCS1_WITH_TLS_PADDING, NULL } }; int ret; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; if (state == PRE_CTRL_TO_PARAMS && ctx->action_type == GET) { /* * EVP_PKEY_CTRL_GET_RSA_PADDING returns the padding mode in the * weirdest way for a ctrl. Instead of doing like all other ctrls * that return a simple, i.e. just have that as a return value, * this particular ctrl treats p2 as the address for the int to be * returned. We must therefore remember |ctx->p2|, then make * |ctx->p2| point at a buffer to be filled in with the name, and * |ctx->p1| with its size. default_fixup_args() will take care * of the rest for us, along with the POST_CTRL_TO_PARAMS && GET * code section further down. */ ctx->orig_p2 = ctx->p2; ctx->p2 = ctx->name_buf; ctx->p1 = sizeof(ctx->name_buf); } else if (state == PRE_CTRL_TO_PARAMS && ctx->action_type == SET) { /* * Ideally, we should use utf8 strings for the diverse padding modes. * We only came here because someone called EVP_PKEY_CTX_ctrl(), * though, and since that can reasonably be seen as legacy code * that uses the diverse RSA macros for the padding mode, and we * know that at least our providers can handle the numeric modes, * we take the cheap route for now. * * The other solution would be to match |ctx->p1| against entries * in str_value_map and pass the corresponding string. However, * since we don't have a string for RSA_PKCS1_WITH_TLS_PADDING, * we have to do this same hack at least for that one. * * Since the "official" data type for the RSA padding mode is utf8 * string, we cannot count on default_fixup_args(). Instead, we * build the OSSL_PARAM item ourselves and return immediately. */ ctx->params[0] = OSSL_PARAM_construct_int(translation->param_key, &ctx->p1); return 1; } else if (state == POST_PARAMS_TO_CTRL && ctx->action_type == GET) { size_t i; /* * The EVP_PKEY_CTX_get_params() caller may have asked for a utf8 * string, or may have asked for an integer of some sort. If they * ask for an integer, we respond directly. If not, we translate * the response from the ctrl function into a string. */ switch (ctx->params->data_type) { case OSSL_PARAM_INTEGER: return OSSL_PARAM_get_int(ctx->params, &ctx->p1); case OSSL_PARAM_UNSIGNED_INTEGER: return OSSL_PARAM_get_uint(ctx->params, (unsigned int *)&ctx->p1); default: break; } for (i = 0; i < OSSL_NELEM(str_value_map); i++) { if (ctx->p1 == (int)str_value_map[i].id) break; } if (i == OSSL_NELEM(str_value_map)) { ERR_raise_data(ERR_LIB_RSA, RSA_R_UNKNOWN_PADDING_TYPE, "[action:%d, state:%d] padding number %d", ctx->action_type, state, ctx->p1); return -2; } /* * If we don't have a string, we can't do anything. The caller * should have asked for a number... */ if (str_value_map[i].ptr == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return -2; } ctx->p2 = str_value_map[i].ptr; ctx->p1 = strlen(ctx->p2); } if ((ret = default_fixup_args(state, translation, ctx)) <= 0) return ret; if ((ctx->action_type == SET && state == PRE_PARAMS_TO_CTRL) || (ctx->action_type == GET && state == POST_CTRL_TO_PARAMS)) { size_t i; for (i = 0; i < OSSL_NELEM(str_value_map); i++) { if (strcmp(ctx->p2, str_value_map[i].ptr) == 0) break; } if (i == OSSL_NELEM(str_value_map)) { ERR_raise_data(ERR_LIB_RSA, RSA_R_UNKNOWN_PADDING_TYPE, "[action:%d, state:%d] padding name %s", ctx->action_type, state, ctx->p1); ctx->p1 = ret = -2; } else if (state == POST_CTRL_TO_PARAMS) { /* EVP_PKEY_CTRL_GET_RSA_PADDING weirdness explained further up */ *(int *)ctx->orig_p2 = str_value_map[i].id; } else { ctx->p1 = str_value_map[i].id; } ctx->p2 = NULL; } return ret; } /* EVP_PKEY_CTRL_RSA_PSS_SALTLEN, EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN */ static int fix_rsa_pss_saltlen(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { static const OSSL_ITEM str_value_map[] = { { (unsigned int)RSA_PSS_SALTLEN_DIGEST, "digest" }, { (unsigned int)RSA_PSS_SALTLEN_MAX, "max" }, { (unsigned int)RSA_PSS_SALTLEN_AUTO, "auto" } }; int ret; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; if (state == PRE_CTRL_TO_PARAMS && ctx->action_type == GET) { /* * EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN returns the saltlen by filling * in the int pointed at by p2. This is potentially as weird as * the way EVP_PKEY_CTRL_GET_RSA_PADDING works, except that saltlen * might be a negative value, so it wouldn't work as a legitimate * return value. * In any case, we must therefore remember |ctx->p2|, then make * |ctx->p2| point at a buffer to be filled in with the name, and * |ctx->p1| with its size. default_fixup_args() will take care * of the rest for us, along with the POST_CTRL_TO_PARAMS && GET * code section further down. */ ctx->orig_p2 = ctx->p2; ctx->p2 = ctx->name_buf; ctx->p1 = sizeof(ctx->name_buf); } else if ((ctx->action_type == SET && state == PRE_CTRL_TO_PARAMS) || (ctx->action_type == GET && state == POST_PARAMS_TO_CTRL)) { size_t i; for (i = 0; i < OSSL_NELEM(str_value_map); i++) { if (ctx->p1 == (int)str_value_map[i].id) break; } if (i == OSSL_NELEM(str_value_map)) { BIO_snprintf(ctx->name_buf, sizeof(ctx->name_buf), "%d", ctx->p1); } else { /* This won't truncate but it will quiet static analysers */ strncpy(ctx->name_buf, str_value_map[i].ptr, sizeof(ctx->name_buf) - 1); ctx->name_buf[sizeof(ctx->name_buf) - 1] = '\0'; } ctx->p2 = ctx->name_buf; ctx->p1 = strlen(ctx->p2); } if ((ret = default_fixup_args(state, translation, ctx)) <= 0) return ret; if ((ctx->action_type == SET && state == PRE_PARAMS_TO_CTRL) || (ctx->action_type == GET && state == POST_CTRL_TO_PARAMS)) { size_t i; int val; for (i = 0; i < OSSL_NELEM(str_value_map); i++) { if (strcmp(ctx->p2, str_value_map[i].ptr) == 0) break; } val = i == OSSL_NELEM(str_value_map) ? atoi(ctx->p2) : (int)str_value_map[i].id; if (state == POST_CTRL_TO_PARAMS) { /* * EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN weirdness explained further * up */ *(int *)ctx->orig_p2 = val; } else { ctx->p1 = val; } ctx->p2 = NULL; } return ret; } /* EVP_PKEY_CTRL_HKDF_MODE */ static int fix_hkdf_mode(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { static const OSSL_ITEM str_value_map[] = { { EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND, "EXTRACT_AND_EXPAND" }, { EVP_KDF_HKDF_MODE_EXTRACT_ONLY, "EXTRACT_ONLY" }, { EVP_KDF_HKDF_MODE_EXPAND_ONLY, "EXPAND_ONLY" } }; int ret; if ((ret = default_check(state, translation, ctx)) <= 0) return ret; if ((ctx->action_type == SET && state == PRE_CTRL_TO_PARAMS) || (ctx->action_type == GET && state == POST_PARAMS_TO_CTRL)) { size_t i; for (i = 0; i < OSSL_NELEM(str_value_map); i++) { if (ctx->p1 == (int)str_value_map[i].id) break; } if (i == OSSL_NELEM(str_value_map)) return 0; ctx->p2 = str_value_map[i].ptr; ctx->p1 = strlen(ctx->p2); } if ((ret = default_fixup_args(state, translation, ctx)) <= 0) return ret; if ((ctx->action_type == SET && state == PRE_PARAMS_TO_CTRL) || (ctx->action_type == GET && state == POST_CTRL_TO_PARAMS)) { size_t i; for (i = 0; i < OSSL_NELEM(str_value_map); i++) { if (strcmp(ctx->p2, str_value_map[i].ptr) == 0) break; } if (i == OSSL_NELEM(str_value_map)) return 0; if (state == POST_CTRL_TO_PARAMS) ret = str_value_map[i].id; else ctx->p1 = str_value_map[i].id; ctx->p2 = NULL; } return 1; } /*- * Payload getters * =============== * * These all get the data they want, then call default_fixup_args() as * a post-ctrl GET fixup. They all get NULL ctx, ctrl_cmd, ctrl_str, * p1, sz */ /* Pilfering DH, DSA and EC_KEY */ static int get_payload_group_name(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { EVP_PKEY *pkey = ctx->p2; ctx->p2 = NULL; switch (EVP_PKEY_get_base_id(pkey)) { #ifndef OPENSSL_NO_DH case EVP_PKEY_DH: { const DH *dh = EVP_PKEY_get0_DH(pkey); int uid = DH_get_nid(dh); if (uid != NID_undef) { const DH_NAMED_GROUP *dh_group = ossl_ffc_uid_to_dh_named_group(uid); ctx->p2 = (char *)ossl_ffc_named_group_get_name(dh_group); } } break; #endif #ifndef OPENSSL_NO_EC case EVP_PKEY_EC: { const EC_GROUP *grp = EC_KEY_get0_group(EVP_PKEY_get0_EC_KEY(pkey)); int nid = NID_undef; if (grp != NULL) nid = EC_GROUP_get_curve_name(grp); if (nid != NID_undef) ctx->p2 = (char *)OSSL_EC_curve_nid2name(nid); } break; #endif default: ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE); return 0; } /* * Quietly ignoring unknown groups matches the behaviour on the provider * side. */ if (ctx->p2 == NULL) return 1; ctx->p1 = strlen(ctx->p2); return default_fixup_args(state, translation, ctx); } static int get_payload_private_key(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { EVP_PKEY *pkey = ctx->p2; ctx->p2 = NULL; if (ctx->params->data_type != OSSL_PARAM_UNSIGNED_INTEGER) return 0; switch (EVP_PKEY_get_base_id(pkey)) { #ifndef OPENSSL_NO_DH case EVP_PKEY_DH: { const DH *dh = EVP_PKEY_get0_DH(pkey); ctx->p2 = (BIGNUM *)DH_get0_priv_key(dh); } break; #endif #ifndef OPENSSL_NO_EC case EVP_PKEY_EC: { const EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey); ctx->p2 = (BIGNUM *)EC_KEY_get0_private_key(ec); } break; #endif default: ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE); return 0; } return default_fixup_args(state, translation, ctx); } static int get_payload_public_key(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { EVP_PKEY *pkey = ctx->p2; unsigned char *buf = NULL; int ret; ctx->p2 = NULL; switch (EVP_PKEY_get_base_id(pkey)) { #ifndef OPENSSL_NO_DH case EVP_PKEY_DHX: case EVP_PKEY_DH: switch (ctx->params->data_type) { case OSSL_PARAM_OCTET_STRING: ctx->sz = ossl_dh_key2buf(EVP_PKEY_get0_DH(pkey), &buf, 0, 1); ctx->p2 = buf; break; case OSSL_PARAM_UNSIGNED_INTEGER: ctx->p2 = (void *)DH_get0_pub_key(EVP_PKEY_get0_DH(pkey)); break; default: return 0; } break; #endif #ifndef OPENSSL_NO_DSA case EVP_PKEY_DSA: if (ctx->params->data_type == OSSL_PARAM_UNSIGNED_INTEGER) { ctx->p2 = (void *)DSA_get0_pub_key(EVP_PKEY_get0_DSA(pkey)); break; } return 0; #endif #ifndef OPENSSL_NO_EC case EVP_PKEY_EC: if (ctx->params->data_type == OSSL_PARAM_OCTET_STRING) { const EC_KEY *eckey = EVP_PKEY_get0_EC_KEY(pkey); BN_CTX *bnctx = BN_CTX_new_ex(ossl_ec_key_get_libctx(eckey)); const EC_GROUP *ecg = EC_KEY_get0_group(eckey); const EC_POINT *point = EC_KEY_get0_public_key(eckey); if (bnctx == NULL) return 0; ctx->sz = EC_POINT_point2buf(ecg, point, POINT_CONVERSION_COMPRESSED, &buf, bnctx); ctx->p2 = buf; BN_CTX_free(bnctx); break; } return 0; #endif default: ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE); return 0; } ret = default_fixup_args(state, translation, ctx); OPENSSL_free(buf); return ret; } static int get_payload_bn(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx, const BIGNUM *bn) { if (bn == NULL) return 0; if (ctx->params->data_type != OSSL_PARAM_UNSIGNED_INTEGER) return 0; ctx->p2 = (BIGNUM *)bn; return default_fixup_args(state, translation, ctx); } static int get_dh_dsa_payload_p(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { const BIGNUM *bn = NULL; EVP_PKEY *pkey = ctx->p2; switch (EVP_PKEY_get_base_id(pkey)) { #ifndef OPENSSL_NO_DH case EVP_PKEY_DH: bn = DH_get0_p(EVP_PKEY_get0_DH(pkey)); break; #endif #ifndef OPENSSL_NO_DSA case EVP_PKEY_DSA: bn = DSA_get0_p(EVP_PKEY_get0_DSA(pkey)); break; #endif default: ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE); } return get_payload_bn(state, translation, ctx, bn); } static int get_dh_dsa_payload_q(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { const BIGNUM *bn = NULL; switch (EVP_PKEY_get_base_id(ctx->p2)) { #ifndef OPENSSL_NO_DH case EVP_PKEY_DH: bn = DH_get0_q(EVP_PKEY_get0_DH(ctx->p2)); break; #endif #ifndef OPENSSL_NO_DSA case EVP_PKEY_DSA: bn = DSA_get0_q(EVP_PKEY_get0_DSA(ctx->p2)); break; #endif } return get_payload_bn(state, translation, ctx, bn); } static int get_dh_dsa_payload_g(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { const BIGNUM *bn = NULL; switch (EVP_PKEY_get_base_id(ctx->p2)) { #ifndef OPENSSL_NO_DH case EVP_PKEY_DH: bn = DH_get0_g(EVP_PKEY_get0_DH(ctx->p2)); break; #endif #ifndef OPENSSL_NO_DSA case EVP_PKEY_DSA: bn = DSA_get0_g(EVP_PKEY_get0_DSA(ctx->p2)); break; #endif } return get_payload_bn(state, translation, ctx, bn); } static int get_payload_int(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx, const int val) { if (ctx->params->data_type != OSSL_PARAM_INTEGER) return 0; ctx->p1 = val; ctx->p2 = NULL; return default_fixup_args(state, translation, ctx); } static int get_ec_decoded_from_explicit_params(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { int val = 0; EVP_PKEY *pkey = ctx->p2; switch (EVP_PKEY_base_id(pkey)) { #ifndef OPENSSL_NO_EC case EVP_PKEY_EC: val = EC_KEY_decoded_from_explicit_params(EVP_PKEY_get0_EC_KEY(pkey)); if (val < 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY); return 0; } break; #endif default: ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE); return 0; } return get_payload_int(state, translation, ctx, val); } static int get_rsa_payload_n(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { const BIGNUM *bn = NULL; - if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA) + if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA + && EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA_PSS) return 0; bn = RSA_get0_n(EVP_PKEY_get0_RSA(ctx->p2)); return get_payload_bn(state, translation, ctx, bn); } static int get_rsa_payload_e(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { const BIGNUM *bn = NULL; - if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA) + if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA + && EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA_PSS) return 0; bn = RSA_get0_e(EVP_PKEY_get0_RSA(ctx->p2)); return get_payload_bn(state, translation, ctx, bn); } static int get_rsa_payload_d(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { const BIGNUM *bn = NULL; - if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA) + if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA + && EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA_PSS) return 0; bn = RSA_get0_d(EVP_PKEY_get0_RSA(ctx->p2)); return get_payload_bn(state, translation, ctx, bn); } static int get_rsa_payload_factor(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx, size_t factornum) { const RSA *r = EVP_PKEY_get0_RSA(ctx->p2); const BIGNUM *bn = NULL; switch (factornum) { case 0: bn = RSA_get0_p(r); break; case 1: bn = RSA_get0_q(r); break; default: { size_t pnum = RSA_get_multi_prime_extra_count(r); const BIGNUM *factors[10]; if (factornum - 2 < pnum && RSA_get0_multi_prime_factors(r, factors)) bn = factors[factornum - 2]; } break; } return get_payload_bn(state, translation, ctx, bn); } static int get_rsa_payload_exponent(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx, size_t exponentnum) { const RSA *r = EVP_PKEY_get0_RSA(ctx->p2); const BIGNUM *bn = NULL; switch (exponentnum) { case 0: bn = RSA_get0_dmp1(r); break; case 1: bn = RSA_get0_dmq1(r); break; default: { size_t pnum = RSA_get_multi_prime_extra_count(r); const BIGNUM *exps[10], *coeffs[10]; if (exponentnum - 2 < pnum && RSA_get0_multi_prime_crt_params(r, exps, coeffs)) bn = exps[exponentnum - 2]; } break; } return get_payload_bn(state, translation, ctx, bn); } static int get_rsa_payload_coefficient(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx, size_t coefficientnum) { const RSA *r = EVP_PKEY_get0_RSA(ctx->p2); const BIGNUM *bn = NULL; switch (coefficientnum) { case 0: bn = RSA_get0_iqmp(r); break; default: { size_t pnum = RSA_get_multi_prime_extra_count(r); const BIGNUM *exps[10], *coeffs[10]; if (coefficientnum - 1 < pnum && RSA_get0_multi_prime_crt_params(r, exps, coeffs)) bn = coeffs[coefficientnum - 1]; } break; } return get_payload_bn(state, translation, ctx, bn); } #define IMPL_GET_RSA_PAYLOAD_FACTOR(n) \ static int \ get_rsa_payload_f##n(enum state state, \ const struct translation_st *translation, \ struct translation_ctx_st *ctx) \ { \ - if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA) \ + if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA \ + && EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA_PSS) \ return 0; \ return get_rsa_payload_factor(state, translation, ctx, n - 1); \ } #define IMPL_GET_RSA_PAYLOAD_EXPONENT(n) \ static int \ get_rsa_payload_e##n(enum state state, \ const struct translation_st *translation, \ struct translation_ctx_st *ctx) \ { \ - if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA) \ + if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA \ + && EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA_PSS) \ return 0; \ return get_rsa_payload_exponent(state, translation, ctx, \ n - 1); \ } #define IMPL_GET_RSA_PAYLOAD_COEFFICIENT(n) \ static int \ get_rsa_payload_c##n(enum state state, \ const struct translation_st *translation, \ struct translation_ctx_st *ctx) \ { \ - if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA) \ + if (EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA \ + && EVP_PKEY_get_base_id(ctx->p2) != EVP_PKEY_RSA_PSS) \ return 0; \ return get_rsa_payload_coefficient(state, translation, ctx, \ n - 1); \ } IMPL_GET_RSA_PAYLOAD_FACTOR(1) IMPL_GET_RSA_PAYLOAD_FACTOR(2) IMPL_GET_RSA_PAYLOAD_FACTOR(3) IMPL_GET_RSA_PAYLOAD_FACTOR(4) IMPL_GET_RSA_PAYLOAD_FACTOR(5) IMPL_GET_RSA_PAYLOAD_FACTOR(6) IMPL_GET_RSA_PAYLOAD_FACTOR(7) IMPL_GET_RSA_PAYLOAD_FACTOR(8) IMPL_GET_RSA_PAYLOAD_FACTOR(9) IMPL_GET_RSA_PAYLOAD_FACTOR(10) IMPL_GET_RSA_PAYLOAD_EXPONENT(1) IMPL_GET_RSA_PAYLOAD_EXPONENT(2) IMPL_GET_RSA_PAYLOAD_EXPONENT(3) IMPL_GET_RSA_PAYLOAD_EXPONENT(4) IMPL_GET_RSA_PAYLOAD_EXPONENT(5) IMPL_GET_RSA_PAYLOAD_EXPONENT(6) IMPL_GET_RSA_PAYLOAD_EXPONENT(7) IMPL_GET_RSA_PAYLOAD_EXPONENT(8) IMPL_GET_RSA_PAYLOAD_EXPONENT(9) IMPL_GET_RSA_PAYLOAD_EXPONENT(10) IMPL_GET_RSA_PAYLOAD_COEFFICIENT(1) IMPL_GET_RSA_PAYLOAD_COEFFICIENT(2) IMPL_GET_RSA_PAYLOAD_COEFFICIENT(3) IMPL_GET_RSA_PAYLOAD_COEFFICIENT(4) IMPL_GET_RSA_PAYLOAD_COEFFICIENT(5) IMPL_GET_RSA_PAYLOAD_COEFFICIENT(6) IMPL_GET_RSA_PAYLOAD_COEFFICIENT(7) IMPL_GET_RSA_PAYLOAD_COEFFICIENT(8) IMPL_GET_RSA_PAYLOAD_COEFFICIENT(9) static int fix_group_ecx(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { const char *value = NULL; switch (state) { case PRE_PARAMS_TO_CTRL: if (!EVP_PKEY_CTX_IS_GEN_OP(ctx->pctx)) return 0; ctx->action_type = NONE; return 1; case POST_PARAMS_TO_CTRL: if (OSSL_PARAM_get_utf8_string_ptr(ctx->params, &value) == 0 || OPENSSL_strcasecmp(ctx->pctx->keytype, value) != 0) { ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_INVALID_ARGUMENT); ctx->p1 = 0; return 0; } ctx->p1 = 1; return 1; default: return 0; } } /*- * The translation table itself * ============================ */ static const struct translation_st evp_pkey_ctx_translations[] = { /* * DistID: we pass it to the backend as an octet string, * but get it back as a pointer to an octet string. * * Note that the EVP_PKEY_CTRL_GET1_ID_LEN is purely for legacy purposes * that has no separate counterpart in OSSL_PARAM terms, since we get * the length of the DistID automatically when getting the DistID itself. */ { SET, -1, -1, EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_SET1_ID, "distid", "hexdistid", OSSL_PKEY_PARAM_DIST_ID, OSSL_PARAM_OCTET_STRING, NULL }, { GET, -1, -1, -1, EVP_PKEY_CTRL_GET1_ID, "distid", "hexdistid", OSSL_PKEY_PARAM_DIST_ID, OSSL_PARAM_OCTET_PTR, NULL }, { GET, -1, -1, -1, EVP_PKEY_CTRL_GET1_ID_LEN, NULL, NULL, OSSL_PKEY_PARAM_DIST_ID, OSSL_PARAM_OCTET_PTR, fix_distid_len }, /*- * DH & DHX * ======== */ /* * EVP_PKEY_CTRL_DH_KDF_TYPE is used both for setting and getting. The * fixup function has to handle this... */ { NONE, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_DH_KDF_TYPE, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_TYPE, OSSL_PARAM_UTF8_STRING, fix_dh_kdf_type }, { SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_DH_KDF_MD, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { GET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_DH_KDF_MD, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_DH_KDF_OUTLEN, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_OUTLEN, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { GET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_DH_KDF_OUTLEN, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_OUTLEN, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_DH_KDF_UKM, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_UKM, OSSL_PARAM_OCTET_STRING, NULL }, { GET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_DH_KDF_UKM, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_UKM, OSSL_PARAM_OCTET_PTR, NULL }, { SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_DH_KDF_OID, NULL, NULL, OSSL_KDF_PARAM_CEK_ALG, OSSL_PARAM_UTF8_STRING, fix_oid }, { GET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_DH_KDF_OID, NULL, NULL, OSSL_KDF_PARAM_CEK_ALG, OSSL_PARAM_UTF8_STRING, fix_oid }, /* DHX Keygen Parameters that are shared with DH */ { SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DH_PARAMGEN_TYPE, "dh_paramgen_type", NULL, OSSL_PKEY_PARAM_FFC_TYPE, OSSL_PARAM_UTF8_STRING, fix_dh_paramgen_type }, { SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DH_PARAMGEN_PRIME_LEN, "dh_paramgen_prime_len", NULL, OSSL_PKEY_PARAM_FFC_PBITS, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_DH_NID, "dh_param", NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, NULL }, { SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_DH_RFC5114, "dh_rfc5114", NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_dh_nid5114 }, /* DH Keygen Parameters that are shared with DHX */ { SET, EVP_PKEY_DH, 0, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DH_PARAMGEN_TYPE, "dh_paramgen_type", NULL, OSSL_PKEY_PARAM_FFC_TYPE, OSSL_PARAM_UTF8_STRING, fix_dh_paramgen_type }, { SET, EVP_PKEY_DH, 0, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DH_PARAMGEN_PRIME_LEN, "dh_paramgen_prime_len", NULL, OSSL_PKEY_PARAM_FFC_PBITS, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, EVP_PKEY_DH, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_DH_NID, "dh_param", NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_dh_nid }, { SET, EVP_PKEY_DH, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_DH_RFC5114, "dh_rfc5114", NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_dh_nid5114 }, /* DH specific Keygen Parameters */ { SET, EVP_PKEY_DH, 0, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DH_PARAMGEN_GENERATOR, "dh_paramgen_generator", NULL, OSSL_PKEY_PARAM_DH_GENERATOR, OSSL_PARAM_INTEGER, NULL }, /* DHX specific Keygen Parameters */ { SET, EVP_PKEY_DHX, 0, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DH_PARAMGEN_SUBPRIME_LEN, "dh_paramgen_subprime_len", NULL, OSSL_PKEY_PARAM_FFC_QBITS, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, EVP_PKEY_DH, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_DH_PAD, "dh_pad", NULL, OSSL_EXCHANGE_PARAM_PAD, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, /*- * DSA * === */ { SET, EVP_PKEY_DSA, 0, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DSA_PARAMGEN_BITS, "dsa_paramgen_bits", NULL, OSSL_PKEY_PARAM_FFC_PBITS, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, EVP_PKEY_DSA, 0, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DSA_PARAMGEN_Q_BITS, "dsa_paramgen_q_bits", NULL, OSSL_PKEY_PARAM_FFC_QBITS, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, EVP_PKEY_DSA, 0, EVP_PKEY_OP_PARAMGEN, EVP_PKEY_CTRL_DSA_PARAMGEN_MD, "dsa_paramgen_md", NULL, OSSL_PKEY_PARAM_FFC_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, /*- * EC * == */ { SET, EVP_PKEY_EC, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_EC_PARAM_ENC, "ec_param_enc", NULL, OSSL_PKEY_PARAM_EC_ENCODING, OSSL_PARAM_UTF8_STRING, fix_ec_param_enc }, { SET, EVP_PKEY_EC, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID, "ec_paramgen_curve", NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_ec_paramgen_curve_nid }, /* * EVP_PKEY_CTRL_EC_ECDH_COFACTOR and EVP_PKEY_CTRL_EC_KDF_TYPE are used * both for setting and getting. The fixup function has to handle this... */ { NONE, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_ECDH_COFACTOR, "ecdh_cofactor_mode", NULL, OSSL_EXCHANGE_PARAM_EC_ECDH_COFACTOR_MODE, OSSL_PARAM_INTEGER, fix_ecdh_cofactor }, { NONE, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_KDF_TYPE, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_TYPE, OSSL_PARAM_UTF8_STRING, fix_ec_kdf_type }, { SET, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_KDF_MD, "ecdh_kdf_md", NULL, OSSL_EXCHANGE_PARAM_KDF_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { GET, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_EC_KDF_MD, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { SET, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_KDF_OUTLEN, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_OUTLEN, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { GET, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_EC_KDF_OUTLEN, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_OUTLEN, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_KDF_UKM, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_UKM, OSSL_PARAM_OCTET_STRING, NULL }, { GET, EVP_PKEY_EC, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_EC_KDF_UKM, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_UKM, OSSL_PARAM_OCTET_PTR, NULL }, /*- * SM2 * == */ { SET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_EC_PARAM_ENC, "ec_param_enc", NULL, OSSL_PKEY_PARAM_EC_ENCODING, OSSL_PARAM_UTF8_STRING, fix_ec_param_enc }, { SET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID, "ec_paramgen_curve", NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_ec_paramgen_curve_nid }, /* * EVP_PKEY_CTRL_EC_ECDH_COFACTOR and EVP_PKEY_CTRL_EC_KDF_TYPE are used * both for setting and getting. The fixup function has to handle this... */ { NONE, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_ECDH_COFACTOR, "ecdh_cofactor_mode", NULL, OSSL_EXCHANGE_PARAM_EC_ECDH_COFACTOR_MODE, OSSL_PARAM_INTEGER, fix_ecdh_cofactor }, { NONE, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_KDF_TYPE, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_TYPE, OSSL_PARAM_UTF8_STRING, fix_ec_kdf_type }, { SET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_KDF_MD, "ecdh_kdf_md", NULL, OSSL_EXCHANGE_PARAM_KDF_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { GET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_EC_KDF_MD, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { SET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_KDF_OUTLEN, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_OUTLEN, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { GET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_EC_KDF_OUTLEN, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_OUTLEN, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_EC_KDF_UKM, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_UKM, OSSL_PARAM_OCTET_STRING, NULL }, { GET, EVP_PKEY_SM2, 0, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_GET_EC_KDF_UKM, NULL, NULL, OSSL_EXCHANGE_PARAM_KDF_UKM, OSSL_PARAM_OCTET_PTR, NULL }, /*- * RSA * === */ /* * RSA padding modes are numeric with ctrls, strings with ctrl_strs, * and can be both with OSSL_PARAM. We standardise on strings here, * fix_rsa_padding_mode() does the work when the caller has a different * idea. */ { SET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_TYPE_CRYPT | EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_RSA_PADDING, "rsa_padding_mode", NULL, OSSL_PKEY_PARAM_PAD_MODE, OSSL_PARAM_UTF8_STRING, fix_rsa_padding_mode }, { GET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_TYPE_CRYPT | EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_GET_RSA_PADDING, NULL, NULL, OSSL_PKEY_PARAM_PAD_MODE, OSSL_PARAM_UTF8_STRING, fix_rsa_padding_mode }, { SET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_TYPE_CRYPT | EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_RSA_MGF1_MD, "rsa_mgf1_md", NULL, OSSL_PKEY_PARAM_MGF1_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { GET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_TYPE_CRYPT | EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_GET_RSA_MGF1_MD, NULL, NULL, OSSL_PKEY_PARAM_MGF1_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, /* * RSA-PSS saltlen is essentially numeric, but certain values can be * expressed as keywords (strings) with ctrl_str. The corresponding * OSSL_PARAM allows both forms. * fix_rsa_pss_saltlen() takes care of the distinction. */ { SET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_RSA_PSS_SALTLEN, "rsa_pss_saltlen", NULL, OSSL_PKEY_PARAM_RSA_PSS_SALTLEN, OSSL_PARAM_UTF8_STRING, fix_rsa_pss_saltlen }, { GET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN, NULL, NULL, OSSL_PKEY_PARAM_RSA_PSS_SALTLEN, OSSL_PARAM_UTF8_STRING, fix_rsa_pss_saltlen }, { SET, EVP_PKEY_RSA, 0, EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_RSA_OAEP_MD, "rsa_oaep_md", NULL, OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { GET, EVP_PKEY_RSA, 0, EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_GET_RSA_OAEP_MD, NULL, NULL, OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, /* * The "rsa_oaep_label" ctrl_str expects the value to always be hex. * This is accomodated by default_fixup_args() above, which mimics that * expectation for any translation item where |ctrl_str| is NULL and * |ctrl_hexstr| is non-NULL. */ { SET, EVP_PKEY_RSA, 0, EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_RSA_OAEP_LABEL, NULL, "rsa_oaep_label", OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL, OSSL_PARAM_OCTET_STRING, NULL }, { GET, EVP_PKEY_RSA, 0, EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_GET_RSA_OAEP_LABEL, NULL, NULL, OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL, OSSL_PARAM_OCTET_PTR, NULL }, { SET, EVP_PKEY_RSA_PSS, 0, EVP_PKEY_OP_TYPE_GEN, EVP_PKEY_CTRL_MD, "rsa_pss_keygen_md", NULL, OSSL_ALG_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { SET, EVP_PKEY_RSA_PSS, 0, EVP_PKEY_OP_TYPE_GEN, EVP_PKEY_CTRL_RSA_MGF1_MD, "rsa_pss_keygen_mgf1_md", NULL, OSSL_PKEY_PARAM_MGF1_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { SET, EVP_PKEY_RSA_PSS, 0, EVP_PKEY_OP_TYPE_GEN, EVP_PKEY_CTRL_RSA_PSS_SALTLEN, "rsa_pss_keygen_saltlen", NULL, OSSL_SIGNATURE_PARAM_PSS_SALTLEN, OSSL_PARAM_INTEGER, NULL }, { SET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_RSA_KEYGEN_BITS, "rsa_keygen_bits", NULL, OSSL_PKEY_PARAM_RSA_BITS, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, - { SET, EVP_PKEY_RSA, 0, EVP_PKEY_OP_KEYGEN, + { SET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_RSA_KEYGEN_PUBEXP, "rsa_keygen_pubexp", NULL, OSSL_PKEY_PARAM_RSA_E, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, - { SET, EVP_PKEY_RSA, 0, EVP_PKEY_OP_KEYGEN, + { SET, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_RSA_KEYGEN_PRIMES, "rsa_keygen_primes", NULL, OSSL_PKEY_PARAM_RSA_PRIMES, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, /*- * SipHash * ====== */ { SET, -1, -1, EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_SET_DIGEST_SIZE, "digestsize", NULL, OSSL_MAC_PARAM_SIZE, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, /*- * TLS1-PRF * ======== */ { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_TLS_MD, "md", NULL, OSSL_KDF_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_TLS_SECRET, "secret", "hexsecret", OSSL_KDF_PARAM_SECRET, OSSL_PARAM_OCTET_STRING, NULL }, { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_TLS_SEED, "seed", "hexseed", OSSL_KDF_PARAM_SEED, OSSL_PARAM_OCTET_STRING, NULL }, /*- * HKDF * ==== */ { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_MD, "md", NULL, OSSL_KDF_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_SALT, "salt", "hexsalt", OSSL_KDF_PARAM_SALT, OSSL_PARAM_OCTET_STRING, NULL }, { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_KEY, "key", "hexkey", OSSL_KDF_PARAM_KEY, OSSL_PARAM_OCTET_STRING, NULL }, { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_INFO, "info", "hexinfo", OSSL_KDF_PARAM_INFO, OSSL_PARAM_OCTET_STRING, NULL }, { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_MODE, "mode", NULL, OSSL_KDF_PARAM_MODE, OSSL_PARAM_INTEGER, fix_hkdf_mode }, /*- * Scrypt * ====== */ { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_PASS, "pass", "hexpass", OSSL_KDF_PARAM_PASSWORD, OSSL_PARAM_OCTET_STRING, NULL }, { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_SALT, "salt", "hexsalt", OSSL_KDF_PARAM_SALT, OSSL_PARAM_OCTET_STRING, NULL }, { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_N, "N", NULL, OSSL_KDF_PARAM_SCRYPT_N, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_R, "r", NULL, OSSL_KDF_PARAM_SCRYPT_R, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_P, "p", NULL, OSSL_KDF_PARAM_SCRYPT_P, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_MAXMEM_BYTES, "maxmem_bytes", NULL, OSSL_KDF_PARAM_SCRYPT_MAXMEM, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { SET, -1, -1, EVP_PKEY_OP_KEYGEN | EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_CIPHER, NULL, NULL, OSSL_PKEY_PARAM_CIPHER, OSSL_PARAM_UTF8_STRING, fix_cipher }, { SET, -1, -1, EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_SET_MAC_KEY, "key", "hexkey", OSSL_PKEY_PARAM_PRIV_KEY, OSSL_PARAM_OCTET_STRING, NULL }, { SET, -1, -1, EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_MD, NULL, NULL, OSSL_SIGNATURE_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { GET, -1, -1, EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_GET_MD, NULL, NULL, OSSL_SIGNATURE_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, /*- * ECX * === */ { SET, EVP_PKEY_X25519, EVP_PKEY_X25519, EVP_PKEY_OP_KEYGEN, -1, NULL, NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_group_ecx }, { SET, EVP_PKEY_X25519, EVP_PKEY_X25519, EVP_PKEY_OP_PARAMGEN, -1, NULL, NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_group_ecx }, { SET, EVP_PKEY_X448, EVP_PKEY_X448, EVP_PKEY_OP_KEYGEN, -1, NULL, NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_group_ecx }, { SET, EVP_PKEY_X448, EVP_PKEY_X448, EVP_PKEY_OP_PARAMGEN, -1, NULL, NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, fix_group_ecx }, }; static const struct translation_st evp_pkey_translations[] = { /* * The following contain no ctrls, they are exclusively here to extract * key payloads from legacy keys, using OSSL_PARAMs, and rely entirely * on |fixup_args| to pass the actual data. The |fixup_args| should * expect to get the EVP_PKEY pointer through |ctx->p2|. */ /* DH, DSA & EC */ { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, get_payload_group_name }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_PRIV_KEY, OSSL_PARAM_UNSIGNED_INTEGER, get_payload_private_key }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_PUB_KEY, 0 /* no data type, let get_payload_public_key() handle that */, get_payload_public_key }, /* DH and DSA */ { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_FFC_P, OSSL_PARAM_UNSIGNED_INTEGER, get_dh_dsa_payload_p }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_FFC_G, OSSL_PARAM_UNSIGNED_INTEGER, get_dh_dsa_payload_g }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_FFC_Q, OSSL_PARAM_UNSIGNED_INTEGER, get_dh_dsa_payload_q }, /* RSA */ { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_N, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_n }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_E, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_D, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_d }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR1, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f1 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR2, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f2 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR3, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f3 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR4, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f4 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR5, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f5 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR6, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f6 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR7, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f7 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR8, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f8 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR9, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f9 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR10, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f10 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT1, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e1 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT2, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e2 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT3, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e3 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT4, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e4 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT5, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e5 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT6, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e6 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT7, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e7 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT8, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e8 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT9, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e9 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT10, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e10 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT1, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c1 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT2, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c2 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT3, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c3 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT4, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c4 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT5, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c5 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT6, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c6 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT7, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c7 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT8, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c8 }, { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT9, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c9 }, /* EC */ { GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_EC_DECODED_FROM_EXPLICIT_PARAMS, OSSL_PARAM_INTEGER, get_ec_decoded_from_explicit_params }, }; static const struct translation_st * lookup_translation(struct translation_st *tmpl, const struct translation_st *translations, size_t translations_num) { size_t i; for (i = 0; i < translations_num; i++) { const struct translation_st *item = &translations[i]; /* * Sanity check the translation table item. * * 1. Either both keytypes are -1, or neither of them are. * 2. TBA... */ if (!ossl_assert((item->keytype1 == -1) == (item->keytype2 == -1))) continue; /* * Base search criteria: check that the optype and keytypes match, * if relevant. All callers must synthesise these bits somehow. */ if (item->optype != -1 && (tmpl->optype & item->optype) == 0) continue; /* * This expression is stunningly simple thanks to the sanity check * above. */ if (item->keytype1 != -1 && tmpl->keytype1 != item->keytype1 && tmpl->keytype2 != item->keytype2) continue; /* * Done with the base search criteria, now we check the criteria for * the individual types of translations: * ctrl->params, ctrl_str->params, and params->ctrl */ if (tmpl->ctrl_num != 0) { if (tmpl->ctrl_num != item->ctrl_num) continue; } else if (tmpl->ctrl_str != NULL) { const char *ctrl_str = NULL; const char *ctrl_hexstr = NULL; /* * Search criteria that originates from a ctrl_str is only used * for setting, never for getting. Therefore, we only look at * the setter items. */ if (item->action_type != NONE && item->action_type != SET) continue; /* * At least one of the ctrl cmd names must be match the ctrl * cmd name in the template. */ if (item->ctrl_str != NULL && OPENSSL_strcasecmp(tmpl->ctrl_str, item->ctrl_str) == 0) ctrl_str = tmpl->ctrl_str; else if (item->ctrl_hexstr != NULL && OPENSSL_strcasecmp(tmpl->ctrl_hexstr, item->ctrl_hexstr) == 0) ctrl_hexstr = tmpl->ctrl_hexstr; else continue; /* Modify the template to signal which string matched */ tmpl->ctrl_str = ctrl_str; tmpl->ctrl_hexstr = ctrl_hexstr; } else if (tmpl->param_key != NULL) { /* * Search criteria that originates from a OSSL_PARAM setter or * getter. * * Ctrls were fundamentally bidirectional, with only the ctrl * command macro name implying direction (if you're lucky). * A few ctrl commands were even taking advantage of the * bidirectional nature, making the direction depend in the * value of the numeric argument. * * OSSL_PARAM functions are fundamentally different, in that * setters and getters are separated, so the data direction is * implied by the function that's used. The same OSSL_PARAM * key name can therefore be used in both directions. We must * therefore take the action type into account in this case. */ if ((item->action_type != NONE && tmpl->action_type != item->action_type) || (item->param_key != NULL && OPENSSL_strcasecmp(tmpl->param_key, item->param_key) != 0)) continue; } else { return NULL; } return item; } return NULL; } static const struct translation_st * lookup_evp_pkey_ctx_translation(struct translation_st *tmpl) { return lookup_translation(tmpl, evp_pkey_ctx_translations, OSSL_NELEM(evp_pkey_ctx_translations)); } static const struct translation_st * lookup_evp_pkey_translation(struct translation_st *tmpl) { return lookup_translation(tmpl, evp_pkey_translations, OSSL_NELEM(evp_pkey_translations)); } /* This must ONLY be called for provider side operations */ int evp_pkey_ctx_ctrl_to_param(EVP_PKEY_CTX *pctx, int keytype, int optype, int cmd, int p1, void *p2) { struct translation_ctx_st ctx = { 0, }; struct translation_st tmpl = { 0, }; const struct translation_st *translation = NULL; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; int ret; fixup_args_fn *fixup = default_fixup_args; if (keytype == -1) keytype = pctx->legacy_keytype; tmpl.ctrl_num = cmd; tmpl.keytype1 = tmpl.keytype2 = keytype; tmpl.optype = optype; translation = lookup_evp_pkey_ctx_translation(&tmpl); if (translation == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_COMMAND_NOT_SUPPORTED); return -2; } if (pctx->pmeth != NULL && pctx->pmeth->pkey_id != translation->keytype1 && pctx->pmeth->pkey_id != translation->keytype2) return -1; if (translation->fixup_args != NULL) fixup = translation->fixup_args; ctx.action_type = translation->action_type; ctx.ctrl_cmd = cmd; ctx.p1 = p1; ctx.p2 = p2; ctx.pctx = pctx; ctx.params = params; ret = fixup(PRE_CTRL_TO_PARAMS, translation, &ctx); if (ret > 0) { switch (ctx.action_type) { default: /* fixup_args is expected to make sure this is dead code */ break; case GET: ret = evp_pkey_ctx_get_params_strict(pctx, ctx.params); break; case SET: ret = evp_pkey_ctx_set_params_strict(pctx, ctx.params); break; } } /* * In POST, we pass the return value as p1, allowing the fixup_args * function to affect it by changing its value. */ if (ret > 0) { ctx.p1 = ret; fixup(POST_CTRL_TO_PARAMS, translation, &ctx); ret = ctx.p1; } cleanup_translation_ctx(POST_CTRL_TO_PARAMS, translation, &ctx); return ret; } /* This must ONLY be called for provider side operations */ int evp_pkey_ctx_ctrl_str_to_param(EVP_PKEY_CTX *pctx, const char *name, const char *value) { struct translation_ctx_st ctx = { 0, }; struct translation_st tmpl = { 0, }; const struct translation_st *translation = NULL; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; int keytype = pctx->legacy_keytype; int optype = pctx->operation == 0 ? -1 : pctx->operation; int ret; fixup_args_fn *fixup = default_fixup_args; tmpl.action_type = SET; tmpl.keytype1 = tmpl.keytype2 = keytype; tmpl.optype = optype; tmpl.ctrl_str = name; tmpl.ctrl_hexstr = name; translation = lookup_evp_pkey_ctx_translation(&tmpl); if (translation != NULL) { if (translation->fixup_args != NULL) fixup = translation->fixup_args; ctx.action_type = translation->action_type; ctx.ishex = (tmpl.ctrl_hexstr != NULL); } else { /* String controls really only support setting */ ctx.action_type = SET; } ctx.ctrl_str = name; ctx.p1 = (int)strlen(value); ctx.p2 = (char *)value; ctx.pctx = pctx; ctx.params = params; ret = fixup(PRE_CTRL_STR_TO_PARAMS, translation, &ctx); if (ret > 0) { switch (ctx.action_type) { default: /* fixup_args is expected to make sure this is dead code */ break; case GET: /* * this is dead code, but must be present, or some compilers * will complain */ break; case SET: ret = evp_pkey_ctx_set_params_strict(pctx, ctx.params); break; } } if (ret > 0) ret = fixup(POST_CTRL_STR_TO_PARAMS, translation, &ctx); cleanup_translation_ctx(CLEANUP_CTRL_STR_TO_PARAMS, translation, &ctx); return ret; } /* This must ONLY be called for legacy operations */ static int evp_pkey_ctx_setget_params_to_ctrl(EVP_PKEY_CTX *pctx, enum action action_type, OSSL_PARAM *params) { int keytype = pctx->legacy_keytype; int optype = pctx->operation == 0 ? -1 : pctx->operation; for (; params != NULL && params->key != NULL; params++) { struct translation_ctx_st ctx = { 0, }; struct translation_st tmpl = { 0, }; const struct translation_st *translation = NULL; fixup_args_fn *fixup = default_fixup_args; int ret; tmpl.action_type = action_type; tmpl.keytype1 = tmpl.keytype2 = keytype; tmpl.optype = optype; tmpl.param_key = params->key; translation = lookup_evp_pkey_ctx_translation(&tmpl); if (translation != NULL) { if (translation->fixup_args != NULL) fixup = translation->fixup_args; ctx.action_type = translation->action_type; ctx.ctrl_cmd = translation->ctrl_num; } ctx.pctx = pctx; ctx.params = params; ret = fixup(PRE_PARAMS_TO_CTRL, translation, &ctx); if (ret > 0 && ctx.action_type != NONE) ret = EVP_PKEY_CTX_ctrl(pctx, keytype, optype, ctx.ctrl_cmd, ctx.p1, ctx.p2); /* * In POST, we pass the return value as p1, allowing the fixup_args * function to put it to good use, or maybe affect it. */ if (ret > 0) { ctx.p1 = ret; fixup(POST_PARAMS_TO_CTRL, translation, &ctx); ret = ctx.p1; } cleanup_translation_ctx(CLEANUP_PARAMS_TO_CTRL, translation, &ctx); if (ret <= 0) return 0; } return 1; } int evp_pkey_ctx_set_params_to_ctrl(EVP_PKEY_CTX *ctx, const OSSL_PARAM *params) { return evp_pkey_ctx_setget_params_to_ctrl(ctx, SET, (OSSL_PARAM *)params); } int evp_pkey_ctx_get_params_to_ctrl(EVP_PKEY_CTX *ctx, OSSL_PARAM *params) { return evp_pkey_ctx_setget_params_to_ctrl(ctx, GET, params); } /* This must ONLY be called for legacy EVP_PKEYs */ static int evp_pkey_setget_params_to_ctrl(const EVP_PKEY *pkey, enum action action_type, OSSL_PARAM *params) { int ret = 1; for (; params != NULL && params->key != NULL; params++) { struct translation_ctx_st ctx = { 0, }; struct translation_st tmpl = { 0, }; const struct translation_st *translation = NULL; fixup_args_fn *fixup = default_fixup_args; tmpl.action_type = action_type; tmpl.param_key = params->key; translation = lookup_evp_pkey_translation(&tmpl); if (translation != NULL) { if (translation->fixup_args != NULL) fixup = translation->fixup_args; ctx.action_type = translation->action_type; } ctx.p2 = (void *)pkey; ctx.params = params; /* * EVP_PKEY doesn't have any ctrl function, so we rely completely * on fixup_args to do the whole work. Also, we currently only * support getting. */ if (!ossl_assert(translation != NULL) || !ossl_assert(translation->action_type == GET) || !ossl_assert(translation->fixup_args != NULL)) { return -2; } ret = fixup(PKEY, translation, &ctx); cleanup_translation_ctx(PKEY, translation, &ctx); } return ret; } int evp_pkey_get_params_to_ctrl(const EVP_PKEY *pkey, OSSL_PARAM *params) { return evp_pkey_setget_params_to_ctrl(pkey, GET, params); } diff --git a/crypto/evp/p_lib.c b/crypto/evp/p_lib.c index aa6ec31dab6e..59a7a867ecbb 100644 --- a/crypto/evp/p_lib.c +++ b/crypto/evp/p_lib.c @@ -1,2474 +1,2476 @@ /* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include #include #include "internal/cryptlib.h" #include "internal/refcount.h" #include "internal/namemap.h" #include #include #include #include #include #include #include #include #include #ifndef FIPS_MODULE # include #endif #include #include #include #include #include "internal/numbers.h" /* includes SIZE_MAX */ #include "internal/ffc.h" #include "crypto/evp.h" #include "crypto/dh.h" #include "crypto/dsa.h" #include "crypto/ec.h" #include "crypto/ecx.h" #include "crypto/rsa.h" #ifndef FIPS_MODULE # include "crypto/asn1.h" # include "crypto/x509.h" #endif #include "internal/provider.h" #include "evp_local.h" static int pkey_set_type(EVP_PKEY *pkey, ENGINE *e, int type, const char *str, int len, EVP_KEYMGMT *keymgmt); static void evp_pkey_free_it(EVP_PKEY *key); #ifndef FIPS_MODULE /* The type of parameters selected in key parameter functions */ # define SELECT_PARAMETERS OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS int EVP_PKEY_get_bits(const EVP_PKEY *pkey) { int size = 0; if (pkey != NULL) { size = pkey->cache.bits; if (pkey->ameth != NULL && pkey->ameth->pkey_bits != NULL) size = pkey->ameth->pkey_bits(pkey); } return size < 0 ? 0 : size; } int EVP_PKEY_get_security_bits(const EVP_PKEY *pkey) { int size = 0; if (pkey != NULL) { size = pkey->cache.security_bits; if (pkey->ameth != NULL && pkey->ameth->pkey_security_bits != NULL) size = pkey->ameth->pkey_security_bits(pkey); } return size < 0 ? 0 : size; } int EVP_PKEY_save_parameters(EVP_PKEY *pkey, int mode) { # ifndef OPENSSL_NO_DSA if (pkey->type == EVP_PKEY_DSA) { int ret = pkey->save_parameters; if (mode >= 0) pkey->save_parameters = mode; return ret; } # endif # ifndef OPENSSL_NO_EC if (pkey->type == EVP_PKEY_EC) { int ret = pkey->save_parameters; if (mode >= 0) pkey->save_parameters = mode; return ret; } # endif return 0; } int EVP_PKEY_set_ex_data(EVP_PKEY *key, int idx, void *arg) { return CRYPTO_set_ex_data(&key->ex_data, idx, arg); } void *EVP_PKEY_get_ex_data(const EVP_PKEY *key, int idx) { return CRYPTO_get_ex_data(&key->ex_data, idx); } int EVP_PKEY_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from) { /* * Clean up legacy stuff from this function when legacy support is gone. */ EVP_PKEY *downgraded_from = NULL; int ok = 0; /* * If |to| is a legacy key and |from| isn't, we must make a downgraded * copy of |from|. If that fails, this function fails. */ if (evp_pkey_is_legacy(to) && evp_pkey_is_provided(from)) { if (!evp_pkey_copy_downgraded(&downgraded_from, from)) goto end; from = downgraded_from; } /* * Make sure |to| is typed. Content is less important at this early * stage. * * 1. If |to| is untyped, assign |from|'s key type to it. * 2. If |to| contains a legacy key, compare its |type| to |from|'s. * (|from| was already downgraded above) * * If |to| is a provided key, there's nothing more to do here, functions * like evp_keymgmt_util_copy() and evp_pkey_export_to_provider() called * further down help us find out if they are the same or not. */ if (evp_pkey_is_blank(to)) { if (evp_pkey_is_legacy(from)) { if (EVP_PKEY_set_type(to, from->type) == 0) goto end; } else { if (EVP_PKEY_set_type_by_keymgmt(to, from->keymgmt) == 0) goto end; } } else if (evp_pkey_is_legacy(to)) { if (to->type != from->type) { ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_KEY_TYPES); goto end; } } if (EVP_PKEY_missing_parameters(from)) { ERR_raise(ERR_LIB_EVP, EVP_R_MISSING_PARAMETERS); goto end; } if (!EVP_PKEY_missing_parameters(to)) { if (EVP_PKEY_parameters_eq(to, from) == 1) ok = 1; else ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_PARAMETERS); goto end; } /* For purely provided keys, we just call the keymgmt utility */ if (to->keymgmt != NULL && from->keymgmt != NULL) { ok = evp_keymgmt_util_copy(to, (EVP_PKEY *)from, SELECT_PARAMETERS); goto end; } /* * If |to| is provided, we know that |from| is legacy at this point. * Try exporting |from| to |to|'s keymgmt, then use evp_keymgmt_dup() * to copy the appropriate data to |to|'s keydata. * We cannot override existing data so do it only if there is no keydata * in |to| yet. */ if (to->keymgmt != NULL && to->keydata == NULL) { EVP_KEYMGMT *to_keymgmt = to->keymgmt; void *from_keydata = evp_pkey_export_to_provider((EVP_PKEY *)from, NULL, &to_keymgmt, NULL); /* * If we get a NULL, it could be an internal error, or it could be * that there's a key mismatch. We're pretending the latter... */ if (from_keydata == NULL) ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_KEY_TYPES); else ok = (to->keydata = evp_keymgmt_dup(to->keymgmt, from_keydata, SELECT_PARAMETERS)) != NULL; goto end; } /* Both keys are legacy */ if (from->ameth != NULL && from->ameth->param_copy != NULL) ok = from->ameth->param_copy(to, from); end: EVP_PKEY_free(downgraded_from); return ok; } int EVP_PKEY_missing_parameters(const EVP_PKEY *pkey) { if (pkey != NULL) { if (pkey->keymgmt != NULL) return !evp_keymgmt_util_has((EVP_PKEY *)pkey, SELECT_PARAMETERS); else if (pkey->ameth != NULL && pkey->ameth->param_missing != NULL) return pkey->ameth->param_missing(pkey); } return 0; } /* * This function is called for any mixture of keys except pure legacy pair. * When legacy keys are gone, we replace a call to this functions with * a call to evp_keymgmt_util_match(). */ static int evp_pkey_cmp_any(const EVP_PKEY *a, const EVP_PKEY *b, int selection) { EVP_KEYMGMT *keymgmt1 = NULL, *keymgmt2 = NULL; void *keydata1 = NULL, *keydata2 = NULL, *tmp_keydata = NULL; /* If none of them are provided, this function shouldn't have been called */ if (!ossl_assert(evp_pkey_is_provided(a) || evp_pkey_is_provided(b))) return -2; /* For purely provided keys, we just call the keymgmt utility */ if (evp_pkey_is_provided(a) && evp_pkey_is_provided(b)) return evp_keymgmt_util_match((EVP_PKEY *)a, (EVP_PKEY *)b, selection); /* * At this point, one of them is provided, the other not. This allows * us to compare types using legacy NIDs. */ if (evp_pkey_is_legacy(a) && !EVP_KEYMGMT_is_a(b->keymgmt, OBJ_nid2sn(a->type))) return -1; /* not the same key type */ if (evp_pkey_is_legacy(b) && !EVP_KEYMGMT_is_a(a->keymgmt, OBJ_nid2sn(b->type))) return -1; /* not the same key type */ /* * We've determined that they both are the same keytype, so the next * step is to do a bit of cross export to ensure we have keydata for * both keys in the same keymgmt. */ keymgmt1 = a->keymgmt; keydata1 = a->keydata; keymgmt2 = b->keymgmt; keydata2 = b->keydata; if (keymgmt2 != NULL && keymgmt2->match != NULL) { tmp_keydata = evp_pkey_export_to_provider((EVP_PKEY *)a, NULL, &keymgmt2, NULL); if (tmp_keydata != NULL) { keymgmt1 = keymgmt2; keydata1 = tmp_keydata; } } if (tmp_keydata == NULL && keymgmt1 != NULL && keymgmt1->match != NULL) { tmp_keydata = evp_pkey_export_to_provider((EVP_PKEY *)b, NULL, &keymgmt1, NULL); if (tmp_keydata != NULL) { keymgmt2 = keymgmt1; keydata2 = tmp_keydata; } } /* If we still don't have matching keymgmt implementations, we give up */ if (keymgmt1 != keymgmt2) return -2; /* If the keymgmt implementations are NULL, the export failed */ if (keymgmt1 == NULL) return -2; return evp_keymgmt_match(keymgmt1, keydata1, keydata2, selection); } # ifndef OPENSSL_NO_DEPRECATED_3_0 int EVP_PKEY_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b) { return EVP_PKEY_parameters_eq(a, b); } #endif int EVP_PKEY_parameters_eq(const EVP_PKEY *a, const EVP_PKEY *b) { /* * This will just call evp_keymgmt_util_match when legacy support * is gone. */ if (a->keymgmt != NULL || b->keymgmt != NULL) return evp_pkey_cmp_any(a, b, SELECT_PARAMETERS); /* All legacy keys */ if (a->type != b->type) return -1; if (a->ameth != NULL && a->ameth->param_cmp != NULL) return a->ameth->param_cmp(a, b); return -2; } # ifndef OPENSSL_NO_DEPRECATED_3_0 int EVP_PKEY_cmp(const EVP_PKEY *a, const EVP_PKEY *b) { return EVP_PKEY_eq(a, b); } #endif int EVP_PKEY_eq(const EVP_PKEY *a, const EVP_PKEY *b) { /* * This will just call evp_keymgmt_util_match when legacy support * is gone. */ /* Trivial shortcuts */ if (a == b) return 1; if (a == NULL || b == NULL) return 0; if (a->keymgmt != NULL || b->keymgmt != NULL) { int selection = SELECT_PARAMETERS; if (evp_keymgmt_util_has((EVP_PKEY *)a, OSSL_KEYMGMT_SELECT_PUBLIC_KEY) && evp_keymgmt_util_has((EVP_PKEY *)b, OSSL_KEYMGMT_SELECT_PUBLIC_KEY)) selection |= OSSL_KEYMGMT_SELECT_PUBLIC_KEY; else selection |= OSSL_KEYMGMT_SELECT_KEYPAIR; return evp_pkey_cmp_any(a, b, selection); } /* All legacy keys */ if (a->type != b->type) return -1; if (a->ameth != NULL) { int ret; /* Compare parameters if the algorithm has them */ if (a->ameth->param_cmp != NULL) { ret = a->ameth->param_cmp(a, b); if (ret <= 0) return ret; } if (a->ameth->pub_cmp != NULL) return a->ameth->pub_cmp(a, b); } return -2; } static EVP_PKEY *new_raw_key_int(OSSL_LIB_CTX *libctx, const char *strtype, const char *propq, int nidtype, ENGINE *e, const unsigned char *key, size_t len, int key_is_priv) { EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; const EVP_PKEY_ASN1_METHOD *ameth = NULL; int result = 0; # ifndef OPENSSL_NO_ENGINE /* Check if there is an Engine for this type */ if (e == NULL) { ENGINE *tmpe = NULL; if (strtype != NULL) ameth = EVP_PKEY_asn1_find_str(&tmpe, strtype, -1); else if (nidtype != EVP_PKEY_NONE) ameth = EVP_PKEY_asn1_find(&tmpe, nidtype); /* If tmpe is NULL then no engine is claiming to support this type */ if (tmpe == NULL) ameth = NULL; ENGINE_finish(tmpe); } # endif if (e == NULL && ameth == NULL) { /* * No engine is claiming to support this type, so lets see if we have * a provider. */ ctx = EVP_PKEY_CTX_new_from_name(libctx, strtype != NULL ? strtype : OBJ_nid2sn(nidtype), propq); if (ctx == NULL) goto err; /* May fail if no provider available */ ERR_set_mark(); if (EVP_PKEY_fromdata_init(ctx) == 1) { OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END }; ERR_clear_last_mark(); params[0] = OSSL_PARAM_construct_octet_string( key_is_priv ? OSSL_PKEY_PARAM_PRIV_KEY : OSSL_PKEY_PARAM_PUB_KEY, (void *)key, len); if (EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEYPAIR, params) != 1) { ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED); goto err; } EVP_PKEY_CTX_free(ctx); return pkey; } ERR_pop_to_mark(); /* else not supported so fallback to legacy */ } /* Legacy code path */ pkey = EVP_PKEY_new(); if (pkey == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE); goto err; } if (!pkey_set_type(pkey, e, nidtype, strtype, -1, NULL)) { /* EVPerr already called */ goto err; } if (!ossl_assert(pkey->ameth != NULL)) goto err; if (key_is_priv) { if (pkey->ameth->set_priv_key == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); goto err; } if (!pkey->ameth->set_priv_key(pkey, key, len)) { ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED); goto err; } } else { if (pkey->ameth->set_pub_key == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); goto err; } if (!pkey->ameth->set_pub_key(pkey, key, len)) { ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED); goto err; } } result = 1; err: if (!result) { EVP_PKEY_free(pkey); pkey = NULL; } EVP_PKEY_CTX_free(ctx); return pkey; } EVP_PKEY *EVP_PKEY_new_raw_private_key_ex(OSSL_LIB_CTX *libctx, const char *keytype, const char *propq, const unsigned char *priv, size_t len) { return new_raw_key_int(libctx, keytype, propq, EVP_PKEY_NONE, NULL, priv, len, 1); } EVP_PKEY *EVP_PKEY_new_raw_private_key(int type, ENGINE *e, const unsigned char *priv, size_t len) { return new_raw_key_int(NULL, NULL, NULL, type, e, priv, len, 1); } EVP_PKEY *EVP_PKEY_new_raw_public_key_ex(OSSL_LIB_CTX *libctx, const char *keytype, const char *propq, const unsigned char *pub, size_t len) { return new_raw_key_int(libctx, keytype, propq, EVP_PKEY_NONE, NULL, pub, len, 0); } EVP_PKEY *EVP_PKEY_new_raw_public_key(int type, ENGINE *e, const unsigned char *pub, size_t len) { return new_raw_key_int(NULL, NULL, NULL, type, e, pub, len, 0); } struct raw_key_details_st { unsigned char **key; size_t *len; int selection; }; static OSSL_CALLBACK get_raw_key_details; static int get_raw_key_details(const OSSL_PARAM params[], void *arg) { const OSSL_PARAM *p = NULL; struct raw_key_details_st *raw_key = arg; if (raw_key->selection == OSSL_KEYMGMT_SELECT_PRIVATE_KEY) { if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PRIV_KEY)) != NULL) return OSSL_PARAM_get_octet_string(p, (void **)raw_key->key, raw_key->key == NULL ? 0 : *raw_key->len, raw_key->len); } else if (raw_key->selection == OSSL_KEYMGMT_SELECT_PUBLIC_KEY) { if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PUB_KEY)) != NULL) return OSSL_PARAM_get_octet_string(p, (void **)raw_key->key, raw_key->key == NULL ? 0 : *raw_key->len, raw_key->len); } return 0; } int EVP_PKEY_get_raw_private_key(const EVP_PKEY *pkey, unsigned char *priv, size_t *len) { if (pkey->keymgmt != NULL) { struct raw_key_details_st raw_key; raw_key.key = priv == NULL ? NULL : &priv; raw_key.len = len; raw_key.selection = OSSL_KEYMGMT_SELECT_PRIVATE_KEY; return evp_keymgmt_util_export(pkey, OSSL_KEYMGMT_SELECT_PRIVATE_KEY, get_raw_key_details, &raw_key); } if (pkey->ameth == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } if (pkey->ameth->get_priv_key == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } if (!pkey->ameth->get_priv_key(pkey, priv, len)) { ERR_raise(ERR_LIB_EVP, EVP_R_GET_RAW_KEY_FAILED); return 0; } return 1; } int EVP_PKEY_get_raw_public_key(const EVP_PKEY *pkey, unsigned char *pub, size_t *len) { if (pkey->keymgmt != NULL) { struct raw_key_details_st raw_key; raw_key.key = pub == NULL ? NULL : &pub; raw_key.len = len; raw_key.selection = OSSL_KEYMGMT_SELECT_PUBLIC_KEY; return evp_keymgmt_util_export(pkey, OSSL_KEYMGMT_SELECT_PUBLIC_KEY, get_raw_key_details, &raw_key); } if (pkey->ameth == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } if (pkey->ameth->get_pub_key == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return 0; } if (!pkey->ameth->get_pub_key(pkey, pub, len)) { ERR_raise(ERR_LIB_EVP, EVP_R_GET_RAW_KEY_FAILED); return 0; } return 1; } static EVP_PKEY *new_cmac_key_int(const unsigned char *priv, size_t len, const char *cipher_name, const EVP_CIPHER *cipher, OSSL_LIB_CTX *libctx, const char *propq, ENGINE *e) { # ifndef OPENSSL_NO_CMAC # ifndef OPENSSL_NO_ENGINE const char *engine_id = e != NULL ? ENGINE_get_id(e) : NULL; # endif OSSL_PARAM params[5], *p = params; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx; if (cipher != NULL) cipher_name = EVP_CIPHER_get0_name(cipher); if (cipher_name == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED); return NULL; } ctx = EVP_PKEY_CTX_new_from_name(libctx, "CMAC", propq); if (ctx == NULL) goto err; if (EVP_PKEY_fromdata_init(ctx) <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED); goto err; } *p++ = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_PRIV_KEY, (void *)priv, len); *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_CIPHER, (char *)cipher_name, 0); if (propq != NULL) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_PROPERTIES, (char *)propq, 0); # ifndef OPENSSL_NO_ENGINE if (engine_id != NULL) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_ENGINE, (char *)engine_id, 0); # endif *p = OSSL_PARAM_construct_end(); if (EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEYPAIR, params) <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED); goto err; } err: EVP_PKEY_CTX_free(ctx); return pkey; # else ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); return NULL; # endif } EVP_PKEY *EVP_PKEY_new_CMAC_key(ENGINE *e, const unsigned char *priv, size_t len, const EVP_CIPHER *cipher) { return new_cmac_key_int(priv, len, NULL, cipher, NULL, NULL, e); } int EVP_PKEY_set_type(EVP_PKEY *pkey, int type) { return pkey_set_type(pkey, NULL, type, NULL, -1, NULL); } int EVP_PKEY_set_type_str(EVP_PKEY *pkey, const char *str, int len) { return pkey_set_type(pkey, NULL, EVP_PKEY_NONE, str, len, NULL); } # ifndef OPENSSL_NO_ENGINE int EVP_PKEY_set1_engine(EVP_PKEY *pkey, ENGINE *e) { if (e != NULL) { if (!ENGINE_init(e)) { ERR_raise(ERR_LIB_EVP, ERR_R_ENGINE_LIB); return 0; } if (ENGINE_get_pkey_meth(e, pkey->type) == NULL) { ENGINE_finish(e); ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_ALGORITHM); return 0; } } ENGINE_finish(pkey->pmeth_engine); pkey->pmeth_engine = e; return 1; } ENGINE *EVP_PKEY_get0_engine(const EVP_PKEY *pkey) { return pkey->engine; } # endif # ifndef OPENSSL_NO_DEPRECATED_3_0 static void detect_foreign_key(EVP_PKEY *pkey) { switch (pkey->type) { case EVP_PKEY_RSA: + case EVP_PKEY_RSA_PSS: pkey->foreign = pkey->pkey.rsa != NULL && ossl_rsa_is_foreign(pkey->pkey.rsa); break; # ifndef OPENSSL_NO_EC case EVP_PKEY_SM2: break; case EVP_PKEY_EC: pkey->foreign = pkey->pkey.ec != NULL && ossl_ec_key_is_foreign(pkey->pkey.ec); break; # endif # ifndef OPENSSL_NO_DSA case EVP_PKEY_DSA: pkey->foreign = pkey->pkey.dsa != NULL && ossl_dsa_is_foreign(pkey->pkey.dsa); break; #endif # ifndef OPENSSL_NO_DH case EVP_PKEY_DH: pkey->foreign = pkey->pkey.dh != NULL && ossl_dh_is_foreign(pkey->pkey.dh); break; #endif default: pkey->foreign = 0; break; } } int EVP_PKEY_assign(EVP_PKEY *pkey, int type, void *key) { # ifndef OPENSSL_NO_EC int pktype; pktype = EVP_PKEY_type(type); if ((key != NULL) && (pktype == EVP_PKEY_EC || pktype == EVP_PKEY_SM2)) { const EC_GROUP *group = EC_KEY_get0_group(key); if (group != NULL) { int curve = EC_GROUP_get_curve_name(group); /* * Regardless of what is requested the SM2 curve must be SM2 type, * and non SM2 curves are EC type. */ if (curve == NID_sm2 && pktype == EVP_PKEY_EC) type = EVP_PKEY_SM2; else if(curve != NID_sm2 && pktype == EVP_PKEY_SM2) type = EVP_PKEY_EC; } } # endif if (pkey == NULL || !EVP_PKEY_set_type(pkey, type)) return 0; pkey->pkey.ptr = key; detect_foreign_key(pkey); return (key != NULL); } # endif void *EVP_PKEY_get0(const EVP_PKEY *pkey) { if (pkey == NULL) return NULL; if (!evp_pkey_is_provided(pkey)) return pkey->pkey.ptr; return NULL; } const unsigned char *EVP_PKEY_get0_hmac(const EVP_PKEY *pkey, size_t *len) { const ASN1_OCTET_STRING *os = NULL; if (pkey->type != EVP_PKEY_HMAC) { ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_AN_HMAC_KEY); return NULL; } os = evp_pkey_get_legacy((EVP_PKEY *)pkey); if (os != NULL) { *len = os->length; return os->data; } return NULL; } # ifndef OPENSSL_NO_POLY1305 const unsigned char *EVP_PKEY_get0_poly1305(const EVP_PKEY *pkey, size_t *len) { const ASN1_OCTET_STRING *os = NULL; if (pkey->type != EVP_PKEY_POLY1305) { ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_POLY1305_KEY); return NULL; } os = evp_pkey_get_legacy((EVP_PKEY *)pkey); if (os != NULL) { *len = os->length; return os->data; } return NULL; } # endif # ifndef OPENSSL_NO_SIPHASH const unsigned char *EVP_PKEY_get0_siphash(const EVP_PKEY *pkey, size_t *len) { const ASN1_OCTET_STRING *os = NULL; if (pkey->type != EVP_PKEY_SIPHASH) { ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_SIPHASH_KEY); return NULL; } os = evp_pkey_get_legacy((EVP_PKEY *)pkey); if (os != NULL) { *len = os->length; return os->data; } return NULL; } # endif # ifndef OPENSSL_NO_DSA static DSA *evp_pkey_get0_DSA_int(const EVP_PKEY *pkey) { if (pkey->type != EVP_PKEY_DSA) { ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_DSA_KEY); return NULL; } return evp_pkey_get_legacy((EVP_PKEY *)pkey); } const DSA *EVP_PKEY_get0_DSA(const EVP_PKEY *pkey) { return evp_pkey_get0_DSA_int(pkey); } int EVP_PKEY_set1_DSA(EVP_PKEY *pkey, DSA *key) { int ret = EVP_PKEY_assign_DSA(pkey, key); if (ret) DSA_up_ref(key); return ret; } DSA *EVP_PKEY_get1_DSA(EVP_PKEY *pkey) { DSA *ret = evp_pkey_get0_DSA_int(pkey); if (ret != NULL) DSA_up_ref(ret); return ret; } # endif /* OPENSSL_NO_DSA */ # ifndef OPENSSL_NO_EC static const ECX_KEY *evp_pkey_get0_ECX_KEY(const EVP_PKEY *pkey, int type) { if (EVP_PKEY_get_base_id(pkey) != type) { ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_ECX_KEY); return NULL; } return evp_pkey_get_legacy((EVP_PKEY *)pkey); } static ECX_KEY *evp_pkey_get1_ECX_KEY(EVP_PKEY *pkey, int type) { ECX_KEY *ret = (ECX_KEY *)evp_pkey_get0_ECX_KEY(pkey, type); if (ret != NULL && !ossl_ecx_key_up_ref(ret)) ret = NULL; return ret; } # define IMPLEMENT_ECX_VARIANT(NAME) \ ECX_KEY *ossl_evp_pkey_get1_##NAME(EVP_PKEY *pkey) \ { \ return evp_pkey_get1_ECX_KEY(pkey, EVP_PKEY_##NAME); \ } IMPLEMENT_ECX_VARIANT(X25519) IMPLEMENT_ECX_VARIANT(X448) IMPLEMENT_ECX_VARIANT(ED25519) IMPLEMENT_ECX_VARIANT(ED448) # endif # if !defined(OPENSSL_NO_DH) && !defined(OPENSSL_NO_DEPRECATED_3_0) int EVP_PKEY_set1_DH(EVP_PKEY *pkey, DH *dhkey) { int ret, type; /* * ossl_dh_is_named_safe_prime_group() returns 1 for named safe prime groups * related to ffdhe and modp (which cache q = (p - 1) / 2), * and returns 0 for all other dh parameter generation types including * RFC5114 named groups. * * The EVP_PKEY_DH type is used for dh parameter generation types: * - named safe prime groups related to ffdhe and modp * - safe prime generator * * The type EVP_PKEY_DHX is used for dh parameter generation types * - fips186-4 and fips186-2 * - rfc5114 named groups. * * The EVP_PKEY_DH type is used to save PKCS#3 data than can be stored * without a q value. * The EVP_PKEY_DHX type is used to save X9.42 data that requires the * q value to be stored. */ if (ossl_dh_is_named_safe_prime_group(dhkey)) type = EVP_PKEY_DH; else type = DH_get0_q(dhkey) == NULL ? EVP_PKEY_DH : EVP_PKEY_DHX; ret = EVP_PKEY_assign(pkey, type, dhkey); if (ret) DH_up_ref(dhkey); return ret; } DH *evp_pkey_get0_DH_int(const EVP_PKEY *pkey) { if (pkey->type != EVP_PKEY_DH && pkey->type != EVP_PKEY_DHX) { ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_DH_KEY); return NULL; } return evp_pkey_get_legacy((EVP_PKEY *)pkey); } const DH *EVP_PKEY_get0_DH(const EVP_PKEY *pkey) { return evp_pkey_get0_DH_int(pkey); } DH *EVP_PKEY_get1_DH(EVP_PKEY *pkey) { DH *ret = evp_pkey_get0_DH_int(pkey); if (ret != NULL) DH_up_ref(ret); return ret; } # endif int EVP_PKEY_type(int type) { int ret; const EVP_PKEY_ASN1_METHOD *ameth; ENGINE *e; ameth = EVP_PKEY_asn1_find(&e, type); if (ameth) ret = ameth->pkey_id; else ret = NID_undef; # ifndef OPENSSL_NO_ENGINE ENGINE_finish(e); # endif return ret; } int EVP_PKEY_get_id(const EVP_PKEY *pkey) { return pkey->type; } int EVP_PKEY_get_base_id(const EVP_PKEY *pkey) { return EVP_PKEY_type(pkey->type); } /* * These hard coded cases are pure hackery to get around the fact * that names in crypto/objects/objects.txt are a mess. There is * no "EC", and "RSA" leads to the NID for 2.5.8.1.1, an OID that's * fallen out in favor of { pkcs-1 1 }, i.e. 1.2.840.113549.1.1.1, * the NID of which is used for EVP_PKEY_RSA. Strangely enough, * "DSA" is accurate... but still, better be safe and hard-code * names that we know. * On a similar topic, EVP_PKEY_type(EVP_PKEY_SM2) will result in * EVP_PKEY_EC, because of aliasing. * This should be cleaned away along with all other #legacy support. */ static const OSSL_ITEM standard_name2type[] = { { EVP_PKEY_RSA, "RSA" }, { EVP_PKEY_RSA_PSS, "RSA-PSS" }, { EVP_PKEY_EC, "EC" }, { EVP_PKEY_ED25519, "ED25519" }, { EVP_PKEY_ED448, "ED448" }, { EVP_PKEY_X25519, "X25519" }, { EVP_PKEY_X448, "X448" }, { EVP_PKEY_SM2, "SM2" }, { EVP_PKEY_DH, "DH" }, { EVP_PKEY_DHX, "X9.42 DH" }, { EVP_PKEY_DHX, "DHX" }, { EVP_PKEY_DSA, "DSA" }, }; int evp_pkey_name2type(const char *name) { int type; size_t i; for (i = 0; i < OSSL_NELEM(standard_name2type); i++) { if (OPENSSL_strcasecmp(name, standard_name2type[i].ptr) == 0) return (int)standard_name2type[i].id; } if ((type = EVP_PKEY_type(OBJ_sn2nid(name))) != NID_undef) return type; return EVP_PKEY_type(OBJ_ln2nid(name)); } const char *evp_pkey_type2name(int type) { size_t i; for (i = 0; i < OSSL_NELEM(standard_name2type); i++) { if (type == (int)standard_name2type[i].id) return standard_name2type[i].ptr; } return OBJ_nid2sn(type); } int EVP_PKEY_is_a(const EVP_PKEY *pkey, const char *name) { if (pkey == NULL) return 0; if (pkey->keymgmt == NULL) return pkey->type == evp_pkey_name2type(name); return EVP_KEYMGMT_is_a(pkey->keymgmt, name); } int EVP_PKEY_type_names_do_all(const EVP_PKEY *pkey, void (*fn)(const char *name, void *data), void *data) { if (!evp_pkey_is_typed(pkey)) return 0; if (!evp_pkey_is_provided(pkey)) { const char *name = OBJ_nid2sn(EVP_PKEY_get_id(pkey)); fn(name, data); return 1; } return EVP_KEYMGMT_names_do_all(pkey->keymgmt, fn, data); } int EVP_PKEY_can_sign(const EVP_PKEY *pkey) { if (pkey->keymgmt == NULL) { switch (EVP_PKEY_get_base_id(pkey)) { case EVP_PKEY_RSA: + case EVP_PKEY_RSA_PSS: return 1; # ifndef OPENSSL_NO_DSA case EVP_PKEY_DSA: return 1; # endif # ifndef OPENSSL_NO_EC case EVP_PKEY_ED25519: case EVP_PKEY_ED448: return 1; case EVP_PKEY_EC: /* Including SM2 */ return EC_KEY_can_sign(pkey->pkey.ec); # endif default: break; } } else { const OSSL_PROVIDER *prov = EVP_KEYMGMT_get0_provider(pkey->keymgmt); OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov); const char *supported_sig = pkey->keymgmt->query_operation_name != NULL ? pkey->keymgmt->query_operation_name(OSSL_OP_SIGNATURE) : EVP_KEYMGMT_get0_name(pkey->keymgmt); EVP_SIGNATURE *signature = NULL; signature = EVP_SIGNATURE_fetch(libctx, supported_sig, NULL); if (signature != NULL) { EVP_SIGNATURE_free(signature); return 1; } } return 0; } static int print_reset_indent(BIO **out, int pop_f_prefix, long saved_indent) { BIO_set_indent(*out, saved_indent); if (pop_f_prefix) { BIO *next = BIO_pop(*out); BIO_free(*out); *out = next; } return 1; } static int print_set_indent(BIO **out, int *pop_f_prefix, long *saved_indent, long indent) { *pop_f_prefix = 0; *saved_indent = 0; if (indent > 0) { long i = BIO_get_indent(*out); *saved_indent = (i < 0 ? 0 : i); if (BIO_set_indent(*out, indent) <= 0) { BIO *prefbio = BIO_new(BIO_f_prefix()); if (prefbio == NULL) return 0; *out = BIO_push(prefbio, *out); *pop_f_prefix = 1; } if (BIO_set_indent(*out, indent) <= 0) { print_reset_indent(out, *pop_f_prefix, *saved_indent); return 0; } } return 1; } static int unsup_alg(BIO *out, const EVP_PKEY *pkey, int indent, const char *kstr) { return BIO_indent(out, indent, 128) && BIO_printf(out, "%s algorithm \"%s\" unsupported\n", kstr, OBJ_nid2ln(pkey->type)) > 0; } static int print_pkey(const EVP_PKEY *pkey, BIO *out, int indent, int selection /* For provided encoding */, const char *propquery /* For provided encoding */, int (*legacy_print)(BIO *out, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx), ASN1_PCTX *legacy_pctx /* For legacy print */) { int pop_f_prefix; long saved_indent; OSSL_ENCODER_CTX *ctx = NULL; int ret = -2; /* default to unsupported */ if (!print_set_indent(&out, &pop_f_prefix, &saved_indent, indent)) return 0; ctx = OSSL_ENCODER_CTX_new_for_pkey(pkey, selection, "TEXT", NULL, propquery); if (OSSL_ENCODER_CTX_get_num_encoders(ctx) != 0) ret = OSSL_ENCODER_to_bio(ctx, out); OSSL_ENCODER_CTX_free(ctx); if (ret != -2) goto end; /* legacy fallback */ if (legacy_print != NULL) ret = legacy_print(out, pkey, 0, legacy_pctx); else ret = unsup_alg(out, pkey, 0, "Public Key"); end: print_reset_indent(&out, pop_f_prefix, saved_indent); return ret; } int EVP_PKEY_print_public(BIO *out, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx) { return print_pkey(pkey, out, indent, EVP_PKEY_PUBLIC_KEY, NULL, (pkey->ameth != NULL ? pkey->ameth->pub_print : NULL), pctx); } int EVP_PKEY_print_private(BIO *out, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx) { return print_pkey(pkey, out, indent, EVP_PKEY_KEYPAIR, NULL, (pkey->ameth != NULL ? pkey->ameth->priv_print : NULL), pctx); } int EVP_PKEY_print_params(BIO *out, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx) { return print_pkey(pkey, out, indent, EVP_PKEY_KEY_PARAMETERS, NULL, (pkey->ameth != NULL ? pkey->ameth->param_print : NULL), pctx); } # ifndef OPENSSL_NO_STDIO int EVP_PKEY_print_public_fp(FILE *fp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx) { int ret; BIO *b = BIO_new_fp(fp, BIO_NOCLOSE); if (b == NULL) return 0; ret = EVP_PKEY_print_public(b, pkey, indent, pctx); BIO_free(b); return ret; } int EVP_PKEY_print_private_fp(FILE *fp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx) { int ret; BIO *b = BIO_new_fp(fp, BIO_NOCLOSE); if (b == NULL) return 0; ret = EVP_PKEY_print_private(b, pkey, indent, pctx); BIO_free(b); return ret; } int EVP_PKEY_print_params_fp(FILE *fp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *pctx) { int ret; BIO *b = BIO_new_fp(fp, BIO_NOCLOSE); if (b == NULL) return 0; ret = EVP_PKEY_print_params(b, pkey, indent, pctx); BIO_free(b); return ret; } # endif static void mdname2nid(const char *mdname, void *data) { int *nid = (int *)data; if (*nid != NID_undef) return; *nid = OBJ_sn2nid(mdname); if (*nid == NID_undef) *nid = OBJ_ln2nid(mdname); } static int legacy_asn1_ctrl_to_param(EVP_PKEY *pkey, int op, int arg1, void *arg2) { if (pkey->keymgmt == NULL) return 0; switch (op) { case ASN1_PKEY_CTRL_DEFAULT_MD_NID: { char mdname[80] = ""; int rv = EVP_PKEY_get_default_digest_name(pkey, mdname, sizeof(mdname)); if (rv > 0) { int mdnum; OSSL_LIB_CTX *libctx = ossl_provider_libctx(pkey->keymgmt->prov); /* Make sure the MD is in the namemap if available */ EVP_MD *md; OSSL_NAMEMAP *namemap; int nid = NID_undef; (void)ERR_set_mark(); md = EVP_MD_fetch(libctx, mdname, NULL); (void)ERR_pop_to_mark(); namemap = ossl_namemap_stored(libctx); /* * The only reason to fetch the MD was to make sure it is in the * namemap. We can immediately free it. */ EVP_MD_free(md); mdnum = ossl_namemap_name2num(namemap, mdname); if (mdnum == 0) return 0; /* * We have the namemap number - now we need to find the * associated nid */ if (!ossl_namemap_doall_names(namemap, mdnum, mdname2nid, &nid)) return 0; *(int *)arg2 = nid; } return rv; } default: return -2; } } static int evp_pkey_asn1_ctrl(EVP_PKEY *pkey, int op, int arg1, void *arg2) { if (pkey->ameth == NULL) return legacy_asn1_ctrl_to_param(pkey, op, arg1, arg2); if (pkey->ameth->pkey_ctrl == NULL) return -2; return pkey->ameth->pkey_ctrl(pkey, op, arg1, arg2); } int EVP_PKEY_get_default_digest_nid(EVP_PKEY *pkey, int *pnid) { if (pkey == NULL) return 0; return evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_DEFAULT_MD_NID, 0, pnid); } int EVP_PKEY_get_default_digest_name(EVP_PKEY *pkey, char *mdname, size_t mdname_sz) { if (pkey->ameth == NULL) return evp_keymgmt_util_get_deflt_digest_name(pkey->keymgmt, pkey->keydata, mdname, mdname_sz); { int nid = NID_undef; int rv = EVP_PKEY_get_default_digest_nid(pkey, &nid); const char *name = rv > 0 ? OBJ_nid2sn(nid) : NULL; if (rv > 0) OPENSSL_strlcpy(mdname, name, mdname_sz); return rv; } } int EVP_PKEY_get_group_name(const EVP_PKEY *pkey, char *gname, size_t gname_sz, size_t *gname_len) { return EVP_PKEY_get_utf8_string_param(pkey, OSSL_PKEY_PARAM_GROUP_NAME, gname, gname_sz, gname_len); } int EVP_PKEY_digestsign_supports_digest(EVP_PKEY *pkey, OSSL_LIB_CTX *libctx, const char *name, const char *propq) { int rv; EVP_MD_CTX *ctx = NULL; if ((ctx = EVP_MD_CTX_new()) == NULL) return -1; ERR_set_mark(); rv = EVP_DigestSignInit_ex(ctx, NULL, name, libctx, propq, pkey, NULL); ERR_pop_to_mark(); EVP_MD_CTX_free(ctx); return rv; } int EVP_PKEY_set1_encoded_public_key(EVP_PKEY *pkey, const unsigned char *pub, size_t publen) { if (pkey == NULL) return 0; if (evp_pkey_is_provided(pkey)) return EVP_PKEY_set_octet_string_param(pkey, OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, (unsigned char *)pub, publen); if (publen > INT_MAX) return 0; /* Historically this function was EVP_PKEY_set1_tls_encodedpoint */ if (evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_SET1_TLS_ENCPT, publen, (void *)pub) <= 0) return 0; return 1; } size_t EVP_PKEY_get1_encoded_public_key(EVP_PKEY *pkey, unsigned char **ppub) { int rv; if (pkey == NULL) return 0; if (evp_pkey_is_provided(pkey)) { size_t return_size = OSSL_PARAM_UNMODIFIED; unsigned char *buf; /* * We know that this is going to fail, but it will give us a size * to allocate. */ EVP_PKEY_get_octet_string_param(pkey, OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, NULL, 0, &return_size); if (return_size == OSSL_PARAM_UNMODIFIED) return 0; *ppub = NULL; buf = OPENSSL_malloc(return_size); if (buf == NULL) return 0; if (!EVP_PKEY_get_octet_string_param(pkey, OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, buf, return_size, NULL)) { OPENSSL_free(buf); return 0; } *ppub = buf; return return_size; } rv = evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_GET1_TLS_ENCPT, 0, ppub); if (rv <= 0) return 0; return rv; } #endif /* FIPS_MODULE */ /*- All methods below can also be used in FIPS_MODULE */ EVP_PKEY *EVP_PKEY_new(void) { EVP_PKEY *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE); return NULL; } ret->type = EVP_PKEY_NONE; ret->save_type = EVP_PKEY_NONE; ret->references = 1; ret->lock = CRYPTO_THREAD_lock_new(); if (ret->lock == NULL) { EVPerr(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE); goto err; } #ifndef FIPS_MODULE ret->save_parameters = 1; if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_EVP_PKEY, ret, &ret->ex_data)) { ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE); goto err; } #endif return ret; err: CRYPTO_THREAD_lock_free(ret->lock); OPENSSL_free(ret); return NULL; } /* * Setup a public key management method. * * For legacy keys, either |type| or |str| is expected to have the type * information. In this case, the setup consists of finding an ASN1 method * and potentially an ENGINE, and setting those fields in |pkey|. * * For provider side keys, |keymgmt| is expected to be non-NULL. In this * case, the setup consists of setting the |keymgmt| field in |pkey|. * * If pkey is NULL just return 1 or 0 if the key management method exists. */ static int pkey_set_type(EVP_PKEY *pkey, ENGINE *e, int type, const char *str, int len, EVP_KEYMGMT *keymgmt) { #ifndef FIPS_MODULE const EVP_PKEY_ASN1_METHOD *ameth = NULL; ENGINE **eptr = (e == NULL) ? &e : NULL; #endif /* * The setups can't set both legacy and provider side methods. * It is forbidden */ if (!ossl_assert(type == EVP_PKEY_NONE || keymgmt == NULL) || !ossl_assert(e == NULL || keymgmt == NULL)) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return 0; } if (pkey != NULL) { int free_it = 0; #ifndef FIPS_MODULE free_it = free_it || pkey->pkey.ptr != NULL; #endif free_it = free_it || pkey->keydata != NULL; if (free_it) evp_pkey_free_it(pkey); #ifndef FIPS_MODULE /* * If key type matches and a method exists then this lookup has * succeeded once so just indicate success. */ if (pkey->type != EVP_PKEY_NONE && type == pkey->save_type && pkey->ameth != NULL) return 1; # ifndef OPENSSL_NO_ENGINE /* If we have ENGINEs release them */ ENGINE_finish(pkey->engine); pkey->engine = NULL; ENGINE_finish(pkey->pmeth_engine); pkey->pmeth_engine = NULL; # endif #endif } #ifndef FIPS_MODULE if (str != NULL) ameth = EVP_PKEY_asn1_find_str(eptr, str, len); else if (type != EVP_PKEY_NONE) ameth = EVP_PKEY_asn1_find(eptr, type); # ifndef OPENSSL_NO_ENGINE if (pkey == NULL && eptr != NULL) ENGINE_finish(e); # endif #endif { int check = 1; #ifndef FIPS_MODULE check = check && ameth == NULL; #endif check = check && keymgmt == NULL; if (check) { ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_ALGORITHM); return 0; } } if (pkey != NULL) { if (keymgmt != NULL && !EVP_KEYMGMT_up_ref(keymgmt)) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return 0; } pkey->keymgmt = keymgmt; pkey->save_type = type; pkey->type = type; #ifndef FIPS_MODULE /* * If the internal "origin" key is provider side, don't save |ameth|. * The main reason is that |ameth| is one factor to detect that the * internal "origin" key is a legacy one. */ if (keymgmt == NULL) pkey->ameth = ameth; /* * The EVP_PKEY_ASN1_METHOD |pkey_id| retains its legacy key purpose * for any key type that has a legacy implementation, regardless of * if the internal key is a legacy or a provider side one. When * there is no legacy implementation for the key, the type becomes * EVP_PKEY_KEYMGMT, which indicates that one should be cautious * with functions that expect legacy internal keys. */ if (ameth != NULL) { if (type == EVP_PKEY_NONE) pkey->type = ameth->pkey_id; } else { pkey->type = EVP_PKEY_KEYMGMT; } # ifndef OPENSSL_NO_ENGINE if (eptr == NULL && e != NULL && !ENGINE_init(e)) { ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR); return 0; } # endif pkey->engine = e; #endif } return 1; } #ifndef FIPS_MODULE static void find_ameth(const char *name, void *data) { const char **str = data; /* * The error messages from pkey_set_type() are uninteresting here, * and misleading. */ ERR_set_mark(); if (pkey_set_type(NULL, NULL, EVP_PKEY_NONE, name, strlen(name), NULL)) { if (str[0] == NULL) str[0] = name; else if (str[1] == NULL) str[1] = name; } ERR_pop_to_mark(); } #endif int EVP_PKEY_set_type_by_keymgmt(EVP_PKEY *pkey, EVP_KEYMGMT *keymgmt) { #ifndef FIPS_MODULE # define EVP_PKEY_TYPE_STR str[0] # define EVP_PKEY_TYPE_STRLEN (str[0] == NULL ? -1 : (int)strlen(str[0])) /* * Find at most two strings that have an associated EVP_PKEY_ASN1_METHOD * Ideally, only one should be found. If two (or more) are found, the * match is ambiguous. This should never happen, but... */ const char *str[2] = { NULL, NULL }; if (!EVP_KEYMGMT_names_do_all(keymgmt, find_ameth, &str) || str[1] != NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR); return 0; } #else # define EVP_PKEY_TYPE_STR NULL # define EVP_PKEY_TYPE_STRLEN -1 #endif return pkey_set_type(pkey, NULL, EVP_PKEY_NONE, EVP_PKEY_TYPE_STR, EVP_PKEY_TYPE_STRLEN, keymgmt); #undef EVP_PKEY_TYPE_STR #undef EVP_PKEY_TYPE_STRLEN } int EVP_PKEY_up_ref(EVP_PKEY *pkey) { int i; if (CRYPTO_UP_REF(&pkey->references, &i, pkey->lock) <= 0) return 0; REF_PRINT_COUNT("EVP_PKEY", pkey); REF_ASSERT_ISNT(i < 2); return ((i > 1) ? 1 : 0); } #ifndef FIPS_MODULE EVP_PKEY *EVP_PKEY_dup(EVP_PKEY *pkey) { EVP_PKEY *dup_pk; if (pkey == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if ((dup_pk = EVP_PKEY_new()) == NULL) return NULL; if (evp_pkey_is_blank(pkey)) goto done; if (evp_pkey_is_provided(pkey)) { if (!evp_keymgmt_util_copy(dup_pk, pkey, OSSL_KEYMGMT_SELECT_ALL)) goto err; goto done; } if (evp_pkey_is_legacy(pkey)) { const EVP_PKEY_ASN1_METHOD *ameth = pkey->ameth; if (ameth == NULL || ameth->copy == NULL) { if (pkey->pkey.ptr == NULL /* empty key, just set type */ && EVP_PKEY_set_type(dup_pk, pkey->type) != 0) goto done; ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE); goto err; } if (!ameth->copy(dup_pk, pkey)) goto err; goto done; } goto err; done: /* copy auxiliary data */ if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_EVP_PKEY, &dup_pk->ex_data, &pkey->ex_data)) goto err; if (pkey->attributes != NULL) { if ((dup_pk->attributes = ossl_x509at_dup(pkey->attributes)) == NULL) goto err; } return dup_pk; err: EVP_PKEY_free(dup_pk); return NULL; } void evp_pkey_free_legacy(EVP_PKEY *x) { const EVP_PKEY_ASN1_METHOD *ameth = x->ameth; ENGINE *tmpe = NULL; if (ameth == NULL && x->legacy_cache_pkey.ptr != NULL) ameth = EVP_PKEY_asn1_find(&tmpe, x->type); if (ameth != NULL) { if (x->legacy_cache_pkey.ptr != NULL) { /* * We should never have both a legacy origin key, and a key in the * legacy cache. */ assert(x->pkey.ptr == NULL); /* * For the purposes of freeing we make the legacy cache look like * a legacy origin key. */ x->pkey = x->legacy_cache_pkey; x->legacy_cache_pkey.ptr = NULL; } if (ameth->pkey_free != NULL) ameth->pkey_free(x); x->pkey.ptr = NULL; } # ifndef OPENSSL_NO_ENGINE ENGINE_finish(tmpe); ENGINE_finish(x->engine); x->engine = NULL; ENGINE_finish(x->pmeth_engine); x->pmeth_engine = NULL; # endif } #endif /* FIPS_MODULE */ static void evp_pkey_free_it(EVP_PKEY *x) { /* internal function; x is never NULL */ evp_keymgmt_util_clear_operation_cache(x, 1); #ifndef FIPS_MODULE evp_pkey_free_legacy(x); #endif if (x->keymgmt != NULL) { evp_keymgmt_freedata(x->keymgmt, x->keydata); EVP_KEYMGMT_free(x->keymgmt); x->keymgmt = NULL; x->keydata = NULL; } x->type = EVP_PKEY_NONE; } void EVP_PKEY_free(EVP_PKEY *x) { int i; if (x == NULL) return; CRYPTO_DOWN_REF(&x->references, &i, x->lock); REF_PRINT_COUNT("EVP_PKEY", x); if (i > 0) return; REF_ASSERT_ISNT(i < 0); evp_pkey_free_it(x); #ifndef FIPS_MODULE CRYPTO_free_ex_data(CRYPTO_EX_INDEX_EVP_PKEY, x, &x->ex_data); #endif CRYPTO_THREAD_lock_free(x->lock); #ifndef FIPS_MODULE sk_X509_ATTRIBUTE_pop_free(x->attributes, X509_ATTRIBUTE_free); #endif OPENSSL_free(x); } int EVP_PKEY_get_size(const EVP_PKEY *pkey) { int size = 0; if (pkey != NULL) { size = pkey->cache.size; #ifndef FIPS_MODULE if (pkey->ameth != NULL && pkey->ameth->pkey_size != NULL) size = pkey->ameth->pkey_size(pkey); #endif } return size < 0 ? 0 : size; } const char *EVP_PKEY_get0_description(const EVP_PKEY *pkey) { if (!evp_pkey_is_assigned(pkey)) return NULL; if (evp_pkey_is_provided(pkey) && pkey->keymgmt->description != NULL) return pkey->keymgmt->description; #ifndef FIPS_MODULE if (pkey->ameth != NULL) return pkey->ameth->info; #endif return NULL; } void *evp_pkey_export_to_provider(EVP_PKEY *pk, OSSL_LIB_CTX *libctx, EVP_KEYMGMT **keymgmt, const char *propquery) { EVP_KEYMGMT *allocated_keymgmt = NULL; EVP_KEYMGMT *tmp_keymgmt = NULL; int selection = OSSL_KEYMGMT_SELECT_ALL; void *keydata = NULL; int check; if (pk == NULL) return NULL; /* No key data => nothing to export */ check = 1; #ifndef FIPS_MODULE check = check && pk->pkey.ptr == NULL; #endif check = check && pk->keydata == NULL; if (check) return NULL; #ifndef FIPS_MODULE if (pk->pkey.ptr != NULL) { /* * If the legacy key doesn't have an dirty counter or export function, * give up */ if (pk->ameth->dirty_cnt == NULL || pk->ameth->export_to == NULL) return NULL; } #endif if (keymgmt != NULL) { tmp_keymgmt = *keymgmt; *keymgmt = NULL; } /* * If no keymgmt was given or found, get a default keymgmt. We do so by * letting EVP_PKEY_CTX_new_from_pkey() do it for us, then we steal it. */ if (tmp_keymgmt == NULL) { EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pk, propquery); if (ctx == NULL) goto end; allocated_keymgmt = tmp_keymgmt = ctx->keymgmt; ctx->keymgmt = NULL; EVP_PKEY_CTX_free(ctx); } /* If there's still no keymgmt to be had, give up */ if (tmp_keymgmt == NULL) goto end; #ifndef FIPS_MODULE if (pk->pkey.ptr != NULL) { OP_CACHE_ELEM *op; /* * If the legacy "origin" hasn't changed since last time, we try * to find our keymgmt in the operation cache. If it has changed, * |i| remains zero, and we will clear the cache further down. */ if (pk->ameth->dirty_cnt(pk) == pk->dirty_cnt_copy) { if (!CRYPTO_THREAD_read_lock(pk->lock)) goto end; op = evp_keymgmt_util_find_operation_cache(pk, tmp_keymgmt, selection); /* * If |tmp_keymgmt| is present in the operation cache, it means * that export doesn't need to be redone. In that case, we take * token copies of the cached pointers, to have token success * values to return. */ if (op != NULL && op->keymgmt != NULL) { keydata = op->keydata; CRYPTO_THREAD_unlock(pk->lock); goto end; } CRYPTO_THREAD_unlock(pk->lock); } /* Make sure that the keymgmt key type matches the legacy NID */ if (!EVP_KEYMGMT_is_a(tmp_keymgmt, OBJ_nid2sn(pk->type))) goto end; if ((keydata = evp_keymgmt_newdata(tmp_keymgmt)) == NULL) goto end; if (!pk->ameth->export_to(pk, keydata, tmp_keymgmt->import, libctx, propquery)) { evp_keymgmt_freedata(tmp_keymgmt, keydata); keydata = NULL; goto end; } /* * If the dirty counter changed since last time, then clear the * operation cache. In that case, we know that |i| is zero. Just * in case this is a re-export, we increment then decrement the * keymgmt reference counter. */ if (!EVP_KEYMGMT_up_ref(tmp_keymgmt)) { /* refcnt++ */ evp_keymgmt_freedata(tmp_keymgmt, keydata); keydata = NULL; goto end; } if (!CRYPTO_THREAD_write_lock(pk->lock)) goto end; if (pk->ameth->dirty_cnt(pk) != pk->dirty_cnt_copy && !evp_keymgmt_util_clear_operation_cache(pk, 0)) { CRYPTO_THREAD_unlock(pk->lock); evp_keymgmt_freedata(tmp_keymgmt, keydata); keydata = NULL; EVP_KEYMGMT_free(tmp_keymgmt); goto end; } EVP_KEYMGMT_free(tmp_keymgmt); /* refcnt-- */ /* Check to make sure some other thread didn't get there first */ op = evp_keymgmt_util_find_operation_cache(pk, tmp_keymgmt, selection); if (op != NULL && op->keymgmt != NULL) { void *tmp_keydata = op->keydata; CRYPTO_THREAD_unlock(pk->lock); evp_keymgmt_freedata(tmp_keymgmt, keydata); keydata = tmp_keydata; goto end; } /* Add the new export to the operation cache */ if (!evp_keymgmt_util_cache_keydata(pk, tmp_keymgmt, keydata, selection)) { CRYPTO_THREAD_unlock(pk->lock); evp_keymgmt_freedata(tmp_keymgmt, keydata); keydata = NULL; goto end; } /* Synchronize the dirty count */ pk->dirty_cnt_copy = pk->ameth->dirty_cnt(pk); CRYPTO_THREAD_unlock(pk->lock); goto end; } #endif /* FIPS_MODULE */ keydata = evp_keymgmt_util_export_to_provider(pk, tmp_keymgmt, selection); end: /* * If nothing was exported, |tmp_keymgmt| might point at a freed * EVP_KEYMGMT, so we clear it to be safe. It shouldn't be useful for * the caller either way in that case. */ if (keydata == NULL) tmp_keymgmt = NULL; if (keymgmt != NULL && tmp_keymgmt != NULL) { *keymgmt = tmp_keymgmt; allocated_keymgmt = NULL; } EVP_KEYMGMT_free(allocated_keymgmt); return keydata; } #ifndef FIPS_MODULE int evp_pkey_copy_downgraded(EVP_PKEY **dest, const EVP_PKEY *src) { EVP_PKEY *allocpkey = NULL; if (!ossl_assert(dest != NULL)) return 0; if (evp_pkey_is_assigned(src) && evp_pkey_is_provided(src)) { EVP_KEYMGMT *keymgmt = src->keymgmt; void *keydata = src->keydata; int type = src->type; const char *keytype = NULL; keytype = EVP_KEYMGMT_get0_name(keymgmt); /* * If the type is EVP_PKEY_NONE, then we have a problem somewhere * else in our code. If it's not one of the well known EVP_PKEY_xxx * values, it should at least be EVP_PKEY_KEYMGMT at this point. * The check is kept as a safety measure. */ if (!ossl_assert(type != EVP_PKEY_NONE)) { ERR_raise_data(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR, "keymgmt key type = %s but legacy type = EVP_PKEY_NONE", keytype); return 0; } /* Prefer the legacy key type name for error reporting */ if (type != EVP_PKEY_KEYMGMT) keytype = OBJ_nid2sn(type); /* Make sure we have a clean slate to copy into */ if (*dest == NULL) { allocpkey = *dest = EVP_PKEY_new(); if (*dest == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE); return 0; } } else { evp_pkey_free_it(*dest); } if (EVP_PKEY_set_type(*dest, type)) { /* If the key is typed but empty, we're done */ if (keydata == NULL) return 1; if ((*dest)->ameth->import_from == NULL) { ERR_raise_data(ERR_LIB_EVP, EVP_R_NO_IMPORT_FUNCTION, "key type = %s", keytype); } else { /* * We perform the export in the same libctx as the keymgmt * that we are using. */ OSSL_LIB_CTX *libctx = ossl_provider_libctx(keymgmt->prov); EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_from_pkey(libctx, *dest, NULL); if (pctx == NULL) ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE); if (pctx != NULL && evp_keymgmt_export(keymgmt, keydata, OSSL_KEYMGMT_SELECT_ALL, (*dest)->ameth->import_from, pctx)) { /* Synchronize the dirty count */ (*dest)->dirty_cnt_copy = (*dest)->ameth->dirty_cnt(*dest); EVP_PKEY_CTX_free(pctx); return 1; } EVP_PKEY_CTX_free(pctx); } ERR_raise_data(ERR_LIB_EVP, EVP_R_KEYMGMT_EXPORT_FAILURE, "key type = %s", keytype); } } if (allocpkey != NULL) { EVP_PKEY_free(allocpkey); *dest = NULL; } return 0; } void *evp_pkey_get_legacy(EVP_PKEY *pk) { EVP_PKEY *tmp_copy = NULL; void *ret = NULL; if (!ossl_assert(pk != NULL)) return NULL; /* * If this isn't an assigned provider side key, we just use any existing * origin legacy key. */ if (!evp_pkey_is_assigned(pk)) return NULL; if (!evp_pkey_is_provided(pk)) return pk->pkey.ptr; if (!CRYPTO_THREAD_read_lock(pk->lock)) return NULL; ret = pk->legacy_cache_pkey.ptr; if (!CRYPTO_THREAD_unlock(pk->lock)) return NULL; if (ret != NULL) return ret; if (!evp_pkey_copy_downgraded(&tmp_copy, pk)) goto err; if (!CRYPTO_THREAD_write_lock(pk->lock)) goto err; /* Check again in case some other thread has updated it in the meantime */ ret = pk->legacy_cache_pkey.ptr; if (ret == NULL) { /* Steal the legacy key reference from the temporary copy */ ret = pk->legacy_cache_pkey.ptr = tmp_copy->pkey.ptr; tmp_copy->pkey.ptr = NULL; } if (!CRYPTO_THREAD_unlock(pk->lock)) { ret = NULL; goto err; } err: EVP_PKEY_free(tmp_copy); return ret; } #endif /* FIPS_MODULE */ int EVP_PKEY_get_bn_param(const EVP_PKEY *pkey, const char *key_name, BIGNUM **bn) { int ret = 0; OSSL_PARAM params[2]; unsigned char buffer[2048]; unsigned char *buf = NULL; size_t buf_sz = 0; if (key_name == NULL || bn == NULL) return 0; memset(buffer, 0, sizeof(buffer)); params[0] = OSSL_PARAM_construct_BN(key_name, buffer, sizeof(buffer)); params[1] = OSSL_PARAM_construct_end(); if (!EVP_PKEY_get_params(pkey, params)) { if (!OSSL_PARAM_modified(params) || params[0].return_size == 0) return 0; buf_sz = params[0].return_size; /* * If it failed because the buffer was too small then allocate the * required buffer size and retry. */ buf = OPENSSL_zalloc(buf_sz); if (buf == NULL) return 0; params[0].data = buf; params[0].data_size = buf_sz; if (!EVP_PKEY_get_params(pkey, params)) goto err; } /* Fail if the param was not found */ if (!OSSL_PARAM_modified(params)) goto err; ret = OSSL_PARAM_get_BN(params, bn); err: if (buf != NULL) { if (OSSL_PARAM_modified(params)) OPENSSL_clear_free(buf, buf_sz); else OPENSSL_free(buf); } else if (OSSL_PARAM_modified(params)) { OPENSSL_cleanse(buffer, params[0].data_size); } return ret; } int EVP_PKEY_get_octet_string_param(const EVP_PKEY *pkey, const char *key_name, unsigned char *buf, size_t max_buf_sz, size_t *out_len) { OSSL_PARAM params[2]; int ret1 = 0, ret2 = 0; if (key_name == NULL) return 0; params[0] = OSSL_PARAM_construct_octet_string(key_name, buf, max_buf_sz); params[1] = OSSL_PARAM_construct_end(); if ((ret1 = EVP_PKEY_get_params(pkey, params))) ret2 = OSSL_PARAM_modified(params); if (ret2 && out_len != NULL) *out_len = params[0].return_size; return ret1 && ret2; } int EVP_PKEY_get_utf8_string_param(const EVP_PKEY *pkey, const char *key_name, char *str, size_t max_buf_sz, size_t *out_len) { OSSL_PARAM params[2]; int ret1 = 0, ret2 = 0; if (key_name == NULL) return 0; params[0] = OSSL_PARAM_construct_utf8_string(key_name, str, max_buf_sz); params[1] = OSSL_PARAM_construct_end(); if ((ret1 = EVP_PKEY_get_params(pkey, params))) ret2 = OSSL_PARAM_modified(params); if (ret2 && out_len != NULL) *out_len = params[0].return_size; if (ret2 && params[0].return_size == max_buf_sz) /* There was no space for a NUL byte */ return 0; /* Add a terminating NUL byte for good measure */ if (ret2 && str != NULL) str[params[0].return_size] = '\0'; return ret1 && ret2; } int EVP_PKEY_get_int_param(const EVP_PKEY *pkey, const char *key_name, int *out) { OSSL_PARAM params[2]; if (key_name == NULL) return 0; params[0] = OSSL_PARAM_construct_int(key_name, out); params[1] = OSSL_PARAM_construct_end(); return EVP_PKEY_get_params(pkey, params) && OSSL_PARAM_modified(params); } int EVP_PKEY_get_size_t_param(const EVP_PKEY *pkey, const char *key_name, size_t *out) { OSSL_PARAM params[2]; if (key_name == NULL) return 0; params[0] = OSSL_PARAM_construct_size_t(key_name, out); params[1] = OSSL_PARAM_construct_end(); return EVP_PKEY_get_params(pkey, params) && OSSL_PARAM_modified(params); } int EVP_PKEY_set_int_param(EVP_PKEY *pkey, const char *key_name, int in) { OSSL_PARAM params[2]; if (key_name == NULL) return 0; params[0] = OSSL_PARAM_construct_int(key_name, &in); params[1] = OSSL_PARAM_construct_end(); return EVP_PKEY_set_params(pkey, params); } int EVP_PKEY_set_size_t_param(EVP_PKEY *pkey, const char *key_name, size_t in) { OSSL_PARAM params[2]; if (key_name == NULL) return 0; params[0] = OSSL_PARAM_construct_size_t(key_name, &in); params[1] = OSSL_PARAM_construct_end(); return EVP_PKEY_set_params(pkey, params); } int EVP_PKEY_set_bn_param(EVP_PKEY *pkey, const char *key_name, const BIGNUM *bn) { OSSL_PARAM params[2]; unsigned char buffer[2048]; int bsize = 0; if (key_name == NULL || bn == NULL || pkey == NULL || !evp_pkey_is_assigned(pkey)) return 0; bsize = BN_num_bytes(bn); if (!ossl_assert(bsize <= (int)sizeof(buffer))) return 0; if (BN_bn2nativepad(bn, buffer, bsize) < 0) return 0; params[0] = OSSL_PARAM_construct_BN(key_name, buffer, bsize); params[1] = OSSL_PARAM_construct_end(); return EVP_PKEY_set_params(pkey, params); } int EVP_PKEY_set_utf8_string_param(EVP_PKEY *pkey, const char *key_name, const char *str) { OSSL_PARAM params[2]; if (key_name == NULL) return 0; params[0] = OSSL_PARAM_construct_utf8_string(key_name, (char *)str, 0); params[1] = OSSL_PARAM_construct_end(); return EVP_PKEY_set_params(pkey, params); } int EVP_PKEY_set_octet_string_param(EVP_PKEY *pkey, const char *key_name, const unsigned char *buf, size_t bsize) { OSSL_PARAM params[2]; if (key_name == NULL) return 0; params[0] = OSSL_PARAM_construct_octet_string(key_name, (unsigned char *)buf, bsize); params[1] = OSSL_PARAM_construct_end(); return EVP_PKEY_set_params(pkey, params); } const OSSL_PARAM *EVP_PKEY_settable_params(const EVP_PKEY *pkey) { return (pkey != NULL && evp_pkey_is_provided(pkey)) ? EVP_KEYMGMT_settable_params(pkey->keymgmt) : NULL; } int EVP_PKEY_set_params(EVP_PKEY *pkey, OSSL_PARAM params[]) { if (pkey != NULL) { if (evp_pkey_is_provided(pkey)) { pkey->dirty_cnt++; return evp_keymgmt_set_params(pkey->keymgmt, pkey->keydata, params); } #ifndef FIPS_MODULE /* * We will hopefully never find the need to set individual data in * EVP_PKEYs with a legacy internal key, but we can't be entirely * sure. This bit of code can be enabled if we find the need. If * not, it can safely be removed when #legacy support is removed. */ # if 0 else if (evp_pkey_is_legacy(pkey)) { return evp_pkey_set_params_to_ctrl(pkey, params); } # endif #endif } ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY); return 0; } const OSSL_PARAM *EVP_PKEY_gettable_params(const EVP_PKEY *pkey) { return (pkey != NULL && evp_pkey_is_provided(pkey)) ? EVP_KEYMGMT_gettable_params(pkey->keymgmt) : NULL; } int EVP_PKEY_get_params(const EVP_PKEY *pkey, OSSL_PARAM params[]) { if (pkey != NULL) { if (evp_pkey_is_provided(pkey)) return evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params) > 0; #ifndef FIPS_MODULE else if (evp_pkey_is_legacy(pkey)) return evp_pkey_get_params_to_ctrl(pkey, params) > 0; #endif } ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY); return 0; } #ifndef FIPS_MODULE int EVP_PKEY_get_ec_point_conv_form(const EVP_PKEY *pkey) { char name[80]; size_t name_len; if (pkey == NULL) return 0; if (pkey->keymgmt == NULL || pkey->keydata == NULL) { # ifndef OPENSSL_NO_EC /* Might work through the legacy route */ const EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey); if (ec == NULL) return 0; return EC_KEY_get_conv_form(ec); # else return 0; # endif } if (!EVP_PKEY_get_utf8_string_param(pkey, OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT, name, sizeof(name), &name_len)) return 0; if (strcmp(name, "uncompressed") == 0) return POINT_CONVERSION_UNCOMPRESSED; if (strcmp(name, "compressed") == 0) return POINT_CONVERSION_COMPRESSED; if (strcmp(name, "hybrid") == 0) return POINT_CONVERSION_HYBRID; return 0; } int EVP_PKEY_get_field_type(const EVP_PKEY *pkey) { char fstr[80]; size_t fstrlen; if (pkey == NULL) return 0; if (pkey->keymgmt == NULL || pkey->keydata == NULL) { # ifndef OPENSSL_NO_EC /* Might work through the legacy route */ const EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey); const EC_GROUP *grp; if (ec == NULL) return 0; grp = EC_KEY_get0_group(ec); if (grp == NULL) return 0; return EC_GROUP_get_field_type(grp); # else return 0; # endif } if (!EVP_PKEY_get_utf8_string_param(pkey, OSSL_PKEY_PARAM_EC_FIELD_TYPE, fstr, sizeof(fstr), &fstrlen)) return 0; if (strcmp(fstr, SN_X9_62_prime_field) == 0) return NID_X9_62_prime_field; else if (strcmp(fstr, SN_X9_62_characteristic_two_field)) return NID_X9_62_characteristic_two_field; return 0; } #endif diff --git a/crypto/http/http_client.c b/crypto/http/http_client.c index ee41c03103e5..e3ccc6c4cc2f 100644 --- a/crypto/http/http_client.c +++ b/crypto/http/http_client.c @@ -1,1427 +1,1434 @@ /* * Copyright 2001-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright Siemens AG 2018-2020 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "e_os.h" #include #include #include "crypto/ctype.h" #include #include #include #include #include #include #include #include #include "internal/sockets.h" #include "internal/cryptlib.h" /* for ossl_assert() */ #define HAS_PREFIX(str, prefix) (strncmp(str, prefix, sizeof(prefix) - 1) == 0) #define HTTP_PREFIX "HTTP/" #define HTTP_VERSION_PATT "1." /* allow 1.x */ #define HTTP_VERSION_STR_LEN sizeof(HTTP_VERSION_PATT) /* == strlen("1.0") */ #define HTTP_PREFIX_VERSION HTTP_PREFIX""HTTP_VERSION_PATT #define HTTP_1_0 HTTP_PREFIX_VERSION"0" /* "HTTP/1.0" */ #define HTTP_LINE1_MINLEN (sizeof(HTTP_PREFIX_VERSION "x 200\n") - 1) #define HTTP_VERSION_MAX_REDIRECTIONS 50 #define HTTP_STATUS_CODE_OK 200 #define HTTP_STATUS_CODE_MOVED_PERMANENTLY 301 #define HTTP_STATUS_CODE_FOUND 302 /* Stateful HTTP request code, supporting blocking and non-blocking I/O */ /* Opaque HTTP request status structure */ struct ossl_http_req_ctx_st { int state; /* Current I/O state */ unsigned char *buf; /* Buffer to write request or read response */ int buf_size; /* Buffer size */ int free_wbio; /* wbio allocated internally, free with ctx */ BIO *wbio; /* BIO to write/send request to */ BIO *rbio; /* BIO to read/receive response from */ OSSL_HTTP_bio_cb_t upd_fn; /* Optional BIO update callback used for TLS */ void *upd_arg; /* Optional arg for update callback function */ int use_ssl; /* Use HTTPS */ char *proxy; /* Optional proxy name or URI */ char *server; /* Optional server host name */ char *port; /* Optional server port */ BIO *mem; /* Mem BIO holding request header or response */ BIO *req; /* BIO holding the request provided by caller */ int method_POST; /* HTTP method is POST (else GET) */ char *expected_ct; /* Optional expected Content-Type */ int expect_asn1; /* Response must be ASN.1-encoded */ unsigned char *pos; /* Current position sending data */ long len_to_send; /* Number of bytes still to send */ size_t resp_len; /* Length of response */ size_t max_resp_len; /* Maximum length of response, or 0 */ int keep_alive; /* Persistent conn. 0=no, 1=prefer, 2=require */ time_t max_time; /* Maximum end time of current transfer, or 0 */ time_t max_total_time; /* Maximum end time of total transfer, or 0 */ char *redirection_url; /* Location obtained from HTTP status 301/302 */ }; /* HTTP states */ #define OHS_NOREAD 0x1000 /* If set no reading should be performed */ #define OHS_ERROR (0 | OHS_NOREAD) /* Error condition */ #define OHS_ADD_HEADERS (1 | OHS_NOREAD) /* Adding header lines to request */ #define OHS_WRITE_INIT (2 | OHS_NOREAD) /* 1st call: ready to start send */ #define OHS_WRITE_HDR (3 | OHS_NOREAD) /* Request header being sent */ #define OHS_WRITE_REQ (4 | OHS_NOREAD) /* Request contents being sent */ #define OHS_FLUSH (5 | OHS_NOREAD) /* Request being flushed */ #define OHS_FIRSTLINE 1 /* First line of response being read */ #define OHS_HEADERS 2 /* MIME headers of response being read */ #define OHS_REDIRECT 3 /* MIME headers being read, expecting Location */ #define OHS_ASN1_HEADER 4 /* ASN1 sequence header (tag+length) being read */ #define OHS_ASN1_CONTENT 5 /* ASN1 content octets being read */ #define OHS_ASN1_DONE (6 | OHS_NOREAD) /* ASN1 content read completed */ #define OHS_STREAM (7 | OHS_NOREAD) /* HTTP content stream to be read */ /* Low-level HTTP API implementation */ OSSL_HTTP_REQ_CTX *OSSL_HTTP_REQ_CTX_new(BIO *wbio, BIO *rbio, int buf_size) { OSSL_HTTP_REQ_CTX *rctx; if (wbio == NULL || rbio == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if ((rctx = OPENSSL_zalloc(sizeof(*rctx))) == NULL) return NULL; rctx->state = OHS_ERROR; rctx->buf_size = buf_size > 0 ? buf_size : OSSL_HTTP_DEFAULT_MAX_LINE_LEN; rctx->buf = OPENSSL_malloc(rctx->buf_size); rctx->wbio = wbio; rctx->rbio = rbio; if (rctx->buf == NULL) { OPENSSL_free(rctx); return NULL; } rctx->max_resp_len = OSSL_HTTP_DEFAULT_MAX_RESP_LEN; /* everything else is 0, e.g. rctx->len_to_send, or NULL, e.g. rctx->mem */ return rctx; } void OSSL_HTTP_REQ_CTX_free(OSSL_HTTP_REQ_CTX *rctx) { if (rctx == NULL) return; /* * Use BIO_free_all() because bio_update_fn may prepend or append to cbio. * This also frees any (e.g., SSL/TLS) BIOs linked with bio and, * like BIO_reset(bio), calls SSL_shutdown() to notify/alert the peer. */ if (rctx->free_wbio) BIO_free_all(rctx->wbio); /* do not free rctx->rbio */ BIO_free(rctx->mem); BIO_free(rctx->req); OPENSSL_free(rctx->buf); OPENSSL_free(rctx->proxy); OPENSSL_free(rctx->server); OPENSSL_free(rctx->port); OPENSSL_free(rctx->expected_ct); OPENSSL_free(rctx); } BIO *OSSL_HTTP_REQ_CTX_get0_mem_bio(const OSSL_HTTP_REQ_CTX *rctx) { if (rctx == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return NULL; } return rctx->mem; } size_t OSSL_HTTP_REQ_CTX_get_resp_len(const OSSL_HTTP_REQ_CTX *rctx) { if (rctx == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return 0; } return rctx->resp_len; } void OSSL_HTTP_REQ_CTX_set_max_response_length(OSSL_HTTP_REQ_CTX *rctx, unsigned long len) { if (rctx == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return; } rctx->max_resp_len = len != 0 ? (size_t)len : OSSL_HTTP_DEFAULT_MAX_RESP_LEN; } /* * Create request line using |rctx| and |path| (or "/" in case |path| is NULL). - * Server name (and port) must be given if and only if plain HTTP proxy is used. + * Server name (and optional port) must be given if and only if + * a plain HTTP proxy is used and |path| does not begin with 'http://'. */ int OSSL_HTTP_REQ_CTX_set_request_line(OSSL_HTTP_REQ_CTX *rctx, int method_POST, const char *server, const char *port, const char *path) { if (rctx == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return 0; } BIO_free(rctx->mem); if ((rctx->mem = BIO_new(BIO_s_mem())) == NULL) return 0; rctx->method_POST = method_POST != 0; if (BIO_printf(rctx->mem, "%s ", rctx->method_POST ? "POST" : "GET") <= 0) return 0; if (server != NULL) { /* HTTP (but not HTTPS) proxy is used */ /* * Section 5.1.2 of RFC 1945 states that the absoluteURI form is only * allowed when using a proxy */ if (BIO_printf(rctx->mem, OSSL_HTTP_PREFIX"%s", server) <= 0) return 0; if (port != NULL && BIO_printf(rctx->mem, ":%s", port) <= 0) return 0; } - /* Make sure path includes a forward slash */ - if (path == NULL) + /* Make sure path includes a forward slash (abs_path) */ + if (path == NULL) { path = "/"; - if (path[0] != '/' && BIO_printf(rctx->mem, "/") <= 0) + } else if (HAS_PREFIX(path, "http://")) { /* absoluteURI for proxy use */ + if (server != NULL) { + ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT); + return 0; + } + } else if (path[0] != '/' && BIO_printf(rctx->mem, "/") <= 0) { return 0; + } /* * Add (the rest of) the path and the HTTP version, * which is fixed to 1.0 for straightforward implementation of keep-alive */ if (BIO_printf(rctx->mem, "%s "HTTP_1_0"\r\n", path) <= 0) return 0; rctx->resp_len = 0; rctx->state = OHS_ADD_HEADERS; return 1; } int OSSL_HTTP_REQ_CTX_add1_header(OSSL_HTTP_REQ_CTX *rctx, const char *name, const char *value) { if (rctx == NULL || name == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (rctx->mem == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } if (BIO_puts(rctx->mem, name) <= 0) return 0; if (value != NULL) { if (BIO_write(rctx->mem, ": ", 2) != 2) return 0; if (BIO_puts(rctx->mem, value) <= 0) return 0; } return BIO_write(rctx->mem, "\r\n", 2) == 2; } int OSSL_HTTP_REQ_CTX_set_expected(OSSL_HTTP_REQ_CTX *rctx, const char *content_type, int asn1, int timeout, int keep_alive) { if (rctx == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (keep_alive != 0 && rctx->state != OHS_ERROR && rctx->state != OHS_ADD_HEADERS) { /* Cannot anymore set keep-alive in request header */ ERR_raise(ERR_LIB_HTTP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } OPENSSL_free(rctx->expected_ct); rctx->expected_ct = NULL; if (content_type != NULL && (rctx->expected_ct = OPENSSL_strdup(content_type)) == NULL) return 0; rctx->expect_asn1 = asn1; if (timeout >= 0) rctx->max_time = timeout > 0 ? time(NULL) + timeout : 0; else /* take over any |overall_timeout| arg of OSSL_HTTP_open(), else 0 */ rctx->max_time = rctx->max_total_time; rctx->keep_alive = keep_alive; return 1; } static int set1_content(OSSL_HTTP_REQ_CTX *rctx, const char *content_type, BIO *req) { long req_len = 0; #ifndef OPENSSL_NO_STDIO FILE *fp = NULL; #endif if (rctx == NULL || (req == NULL && content_type != NULL)) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (rctx->keep_alive != 0 && !OSSL_HTTP_REQ_CTX_add1_header(rctx, "Connection", "keep-alive")) return 0; BIO_free(rctx->req); rctx->req = NULL; if (req == NULL) return 1; if (!rctx->method_POST) { ERR_raise(ERR_LIB_HTTP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } if (content_type != NULL && BIO_printf(rctx->mem, "Content-Type: %s\r\n", content_type) <= 0) return 0; /* * BIO_CTRL_INFO yields the data length at least for memory BIOs, but for * file-based BIOs it gives the current position, which is not what we need. */ if (BIO_method_type(req) == BIO_TYPE_FILE) { #ifndef OPENSSL_NO_STDIO if (BIO_get_fp(req, &fp) == 1 && fseek(fp, 0, SEEK_END) == 0) { req_len = ftell(fp); (void)fseek(fp, 0, SEEK_SET); } else { fp = NULL; } #endif } else { req_len = BIO_ctrl(req, BIO_CTRL_INFO, 0, NULL); /* * Streaming BIOs likely will not support querying the size at all, * and we assume we got a correct value if req_len > 0. */ } if (( #ifndef OPENSSL_NO_STDIO fp != NULL /* definitely correct req_len */ || #endif req_len > 0) && BIO_printf(rctx->mem, "Content-Length: %ld\r\n", req_len) < 0) return 0; if (!BIO_up_ref(req)) return 0; rctx->req = req; return 1; } int OSSL_HTTP_REQ_CTX_set1_req(OSSL_HTTP_REQ_CTX *rctx, const char *content_type, const ASN1_ITEM *it, const ASN1_VALUE *req) { BIO *mem = NULL; int res = 1; if (req != NULL) res = (mem = ASN1_item_i2d_mem_bio(it, req)) != NULL; res = res && set1_content(rctx, content_type, mem); BIO_free(mem); return res; } static int add1_headers(OSSL_HTTP_REQ_CTX *rctx, const STACK_OF(CONF_VALUE) *headers, const char *host) { int i; int add_host = host != NULL && *host != '\0'; CONF_VALUE *hdr; for (i = 0; i < sk_CONF_VALUE_num(headers); i++) { hdr = sk_CONF_VALUE_value(headers, i); if (add_host && OPENSSL_strcasecmp("host", hdr->name) == 0) add_host = 0; if (!OSSL_HTTP_REQ_CTX_add1_header(rctx, hdr->name, hdr->value)) return 0; } if (add_host && !OSSL_HTTP_REQ_CTX_add1_header(rctx, "Host", host)) return 0; return 1; } /* Create OSSL_HTTP_REQ_CTX structure using the values provided. */ static OSSL_HTTP_REQ_CTX *http_req_ctx_new(int free_wbio, BIO *wbio, BIO *rbio, OSSL_HTTP_bio_cb_t bio_update_fn, void *arg, int use_ssl, const char *proxy, const char *server, const char *port, int buf_size, int overall_timeout) { OSSL_HTTP_REQ_CTX *rctx = OSSL_HTTP_REQ_CTX_new(wbio, rbio, buf_size); if (rctx == NULL) return NULL; rctx->free_wbio = free_wbio; rctx->upd_fn = bio_update_fn; rctx->upd_arg = arg; rctx->use_ssl = use_ssl; if (proxy != NULL && (rctx->proxy = OPENSSL_strdup(proxy)) == NULL) goto err; if (server != NULL && (rctx->server = OPENSSL_strdup(server)) == NULL) goto err; if (port != NULL && (rctx->port = OPENSSL_strdup(port)) == NULL) goto err; rctx->max_total_time = overall_timeout > 0 ? time(NULL) + overall_timeout : 0; return rctx; err: OSSL_HTTP_REQ_CTX_free(rctx); return NULL; } /* * Parse first HTTP response line. This should be like this: "HTTP/1.0 200 OK". * We need to obtain the status code and (optional) informational message. * Return any received HTTP response status code, or 0 on fatal error. */ static int parse_http_line1(char *line, int *found_keep_alive) { int i, retcode, err; char *code, *reason, *end; if (!HAS_PREFIX(line, HTTP_PREFIX_VERSION)) goto err; /* above HTTP 1.0, connection persistence is the default */ *found_keep_alive = line[strlen(HTTP_PREFIX_VERSION)] > '0'; /* Skip to first whitespace (past protocol info) */ for (code = line; *code != '\0' && !ossl_isspace(*code); code++) continue; if (*code == '\0') goto err; /* Skip past whitespace to start of response code */ while (*code != '\0' && ossl_isspace(*code)) code++; if (*code == '\0') goto err; /* Find end of response code: first whitespace after start of code */ for (reason = code; *reason != '\0' && !ossl_isspace(*reason); reason++) continue; if (*reason == '\0') goto err; /* Set end of response code and start of message */ *reason++ = '\0'; /* Attempt to parse numeric code */ retcode = strtoul(code, &end, 10); if (*end != '\0') goto err; /* Skip over any leading whitespace in message */ while (*reason != '\0' && ossl_isspace(*reason)) reason++; if (*reason != '\0') { /* * Finally zap any trailing whitespace in message (include CRLF) */ /* chop any trailing whitespace from reason */ /* We know reason has a non-whitespace character so this is OK */ for (end = reason + strlen(reason) - 1; ossl_isspace(*end); end--) *end = '\0'; } switch (retcode) { case HTTP_STATUS_CODE_OK: case HTTP_STATUS_CODE_MOVED_PERMANENTLY: case HTTP_STATUS_CODE_FOUND: return retcode; default: err = HTTP_R_RECEIVED_ERROR; if (retcode < 400) err = HTTP_R_STATUS_CODE_UNSUPPORTED; if (*reason == '\0') ERR_raise_data(ERR_LIB_HTTP, err, "code=%s", code); else ERR_raise_data(ERR_LIB_HTTP, err, "code=%s, reason=%s", code, reason); return retcode; } err: for (i = 0; i < 60 && line[i] != '\0'; i++) if (!ossl_isprint(line[i])) line[i] = ' '; line[i] = '\0'; ERR_raise_data(ERR_LIB_HTTP, HTTP_R_HEADER_PARSE_ERROR, "content=%s", line); return 0; } static int check_set_resp_len(OSSL_HTTP_REQ_CTX *rctx, size_t len) { if (rctx->max_resp_len != 0 && len > rctx->max_resp_len) ERR_raise_data(ERR_LIB_HTTP, HTTP_R_MAX_RESP_LEN_EXCEEDED, "length=%zu, max=%zu", len, rctx->max_resp_len); if (rctx->resp_len != 0 && rctx->resp_len != len) ERR_raise_data(ERR_LIB_HTTP, HTTP_R_INCONSISTENT_CONTENT_LENGTH, "ASN.1 length=%zu, Content-Length=%zu", len, rctx->resp_len); rctx->resp_len = len; return 1; } static int may_still_retry(time_t max_time, int *ptimeout) { time_t time_diff, now = time(NULL); if (max_time != 0) { if (max_time < now) { ERR_raise(ERR_LIB_HTTP, HTTP_R_RETRY_TIMEOUT); return 0; } time_diff = max_time - now; *ptimeout = time_diff > INT_MAX ? INT_MAX : (int)time_diff; } return 1; } /* * Try exchanging request and response via HTTP on (non-)blocking BIO in rctx. * Returns 1 on success, 0 on error or redirection, -1 on BIO_should_retry. */ int OSSL_HTTP_REQ_CTX_nbio(OSSL_HTTP_REQ_CTX *rctx) { int i, found_expected_ct = 0, found_keep_alive = 0; long n; size_t resp_len; const unsigned char *p; char *buf, *key, *value, *line_end = NULL; if (rctx == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (rctx->mem == NULL || rctx->wbio == NULL || rctx->rbio == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return 0; } rctx->redirection_url = NULL; next_io: buf = (char *)rctx->buf; if ((rctx->state & OHS_NOREAD) == 0) { if (rctx->expect_asn1) { n = BIO_read(rctx->rbio, rctx->buf, rctx->buf_size); } else { (void)ERR_set_mark(); n = BIO_gets(rctx->rbio, buf, rctx->buf_size); if (n == -2) { /* unsupported method */ (void)ERR_pop_to_mark(); n = BIO_get_line(rctx->rbio, buf, rctx->buf_size); } else { (void)ERR_clear_last_mark(); } } if (n <= 0) { if (BIO_should_retry(rctx->rbio)) return -1; ERR_raise(ERR_LIB_HTTP, HTTP_R_FAILED_READING_DATA); return 0; } /* Write data to memory BIO */ if (BIO_write(rctx->mem, rctx->buf, n) != n) return 0; } switch (rctx->state) { case OHS_ADD_HEADERS: /* Last operation was adding headers: need a final \r\n */ if (BIO_write(rctx->mem, "\r\n", 2) != 2) { rctx->state = OHS_ERROR; return 0; } rctx->state = OHS_WRITE_INIT; /* fall thru */ case OHS_WRITE_INIT: rctx->len_to_send = BIO_get_mem_data(rctx->mem, &rctx->pos); rctx->state = OHS_WRITE_HDR; /* fall thru */ case OHS_WRITE_HDR: /* Copy some chunk of data from rctx->mem to rctx->wbio */ case OHS_WRITE_REQ: /* Copy some chunk of data from rctx->req to rctx->wbio */ if (rctx->len_to_send > 0) { i = BIO_write(rctx->wbio, rctx->pos, rctx->len_to_send); if (i <= 0) { if (BIO_should_retry(rctx->wbio)) return -1; rctx->state = OHS_ERROR; return 0; } rctx->pos += i; rctx->len_to_send -= i; goto next_io; } if (rctx->state == OHS_WRITE_HDR) { (void)BIO_reset(rctx->mem); rctx->state = OHS_WRITE_REQ; } if (rctx->req != NULL && !BIO_eof(rctx->req)) { n = BIO_read(rctx->req, rctx->buf, rctx->buf_size); if (n <= 0) { if (BIO_should_retry(rctx->req)) return -1; ERR_raise(ERR_LIB_HTTP, HTTP_R_FAILED_READING_DATA); return 0; } rctx->pos = rctx->buf; rctx->len_to_send = n; goto next_io; } rctx->state = OHS_FLUSH; /* fall thru */ case OHS_FLUSH: i = BIO_flush(rctx->wbio); if (i > 0) { rctx->state = OHS_FIRSTLINE; goto next_io; } if (BIO_should_retry(rctx->wbio)) return -1; rctx->state = OHS_ERROR; return 0; case OHS_ERROR: return 0; case OHS_FIRSTLINE: case OHS_HEADERS: case OHS_REDIRECT: /* Attempt to read a line in */ next_line: /* * Due to strange memory BIO behavior with BIO_gets we have to check * there's a complete line in there before calling BIO_gets or we'll * just get a partial read. */ n = BIO_get_mem_data(rctx->mem, &p); if (n <= 0 || memchr(p, '\n', n) == 0) { if (n >= rctx->buf_size) { rctx->state = OHS_ERROR; return 0; } goto next_io; } n = BIO_gets(rctx->mem, buf, rctx->buf_size); if (n <= 0) { if (BIO_should_retry(rctx->mem)) goto next_io; rctx->state = OHS_ERROR; return 0; } /* Don't allow excessive lines */ if (n == rctx->buf_size) { ERR_raise(ERR_LIB_HTTP, HTTP_R_RESPONSE_LINE_TOO_LONG); rctx->state = OHS_ERROR; return 0; } /* First line */ if (rctx->state == OHS_FIRSTLINE) { switch (parse_http_line1(buf, &found_keep_alive)) { case HTTP_STATUS_CODE_OK: rctx->state = OHS_HEADERS; goto next_line; case HTTP_STATUS_CODE_MOVED_PERMANENTLY: case HTTP_STATUS_CODE_FOUND: /* i.e., moved temporarily */ if (!rctx->method_POST) { /* method is GET */ rctx->state = OHS_REDIRECT; goto next_line; } ERR_raise(ERR_LIB_HTTP, HTTP_R_REDIRECTION_NOT_ENABLED); /* redirection is not supported/recommended for POST */ /* fall through */ default: rctx->state = OHS_ERROR; goto next_line; } } key = buf; value = strchr(key, ':'); if (value != NULL) { *(value++) = '\0'; while (ossl_isspace(*value)) value++; line_end = strchr(value, '\r'); if (line_end == NULL) line_end = strchr(value, '\n'); if (line_end != NULL) *line_end = '\0'; } if (value != NULL && line_end != NULL) { if (rctx->state == OHS_REDIRECT && OPENSSL_strcasecmp(key, "Location") == 0) { rctx->redirection_url = value; return 0; } if (rctx->state == OHS_HEADERS && rctx->expected_ct != NULL && OPENSSL_strcasecmp(key, "Content-Type") == 0) { if (OPENSSL_strcasecmp(rctx->expected_ct, value) != 0) { ERR_raise_data(ERR_LIB_HTTP, HTTP_R_UNEXPECTED_CONTENT_TYPE, "expected=%s, actual=%s", rctx->expected_ct, value); return 0; } found_expected_ct = 1; } /* https://tools.ietf.org/html/rfc7230#section-6.3 Persistence */ if (OPENSSL_strcasecmp(key, "Connection") == 0) { if (OPENSSL_strcasecmp(value, "keep-alive") == 0) found_keep_alive = 1; else if (OPENSSL_strcasecmp(value, "close") == 0) found_keep_alive = 0; } else if (OPENSSL_strcasecmp(key, "Content-Length") == 0) { resp_len = (size_t)strtoul(value, &line_end, 10); if (line_end == value || *line_end != '\0') { ERR_raise_data(ERR_LIB_HTTP, HTTP_R_ERROR_PARSING_CONTENT_LENGTH, "input=%s", value); return 0; } if (!check_set_resp_len(rctx, resp_len)) return 0; } } /* Look for blank line indicating end of headers */ for (p = rctx->buf; *p != '\0'; p++) { if (*p != '\r' && *p != '\n') break; } if (*p != '\0') /* not end of headers */ goto next_line; if (rctx->keep_alive != 0 /* do not let server initiate keep_alive */ && !found_keep_alive /* otherwise there is no change */) { if (rctx->keep_alive == 2) { rctx->keep_alive = 0; ERR_raise(ERR_LIB_HTTP, HTTP_R_SERVER_CANCELED_CONNECTION); return 0; } rctx->keep_alive = 0; } if (rctx->state == OHS_ERROR) return 0; if (rctx->expected_ct != NULL && !found_expected_ct) { ERR_raise_data(ERR_LIB_HTTP, HTTP_R_MISSING_CONTENT_TYPE, "expected=%s", rctx->expected_ct); return 0; } if (rctx->state == OHS_REDIRECT) { /* http status code indicated redirect but there was no Location */ ERR_raise(ERR_LIB_HTTP, HTTP_R_MISSING_REDIRECT_LOCATION); return 0; } if (!rctx->expect_asn1) { rctx->state = OHS_STREAM; return 1; } rctx->state = OHS_ASN1_HEADER; /* Fall thru */ case OHS_ASN1_HEADER: /* * Now reading ASN1 header: can read at least 2 bytes which is enough * for ASN1 SEQUENCE header and either length field or at least the * length of the length field. */ n = BIO_get_mem_data(rctx->mem, &p); if (n < 2) goto next_io; /* Check it is an ASN1 SEQUENCE */ if (*p++ != (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)) { ERR_raise(ERR_LIB_HTTP, HTTP_R_MISSING_ASN1_ENCODING); return 0; } /* Check out length field */ if ((*p & 0x80) != 0) { /* * If MSB set on initial length octet we can now always read 6 * octets: make sure we have them. */ if (n < 6) goto next_io; n = *p & 0x7F; /* Not NDEF or excessive length */ if (n == 0 || (n > 4)) { ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_PARSING_ASN1_LENGTH); return 0; } p++; resp_len = 0; for (i = 0; i < n; i++) { resp_len <<= 8; resp_len |= *p++; } resp_len += n + 2; } else { resp_len = *p + 2; } if (!check_set_resp_len(rctx, resp_len)) return 0; rctx->state = OHS_ASN1_CONTENT; /* Fall thru */ case OHS_ASN1_CONTENT: default: n = BIO_get_mem_data(rctx->mem, NULL); if (n < 0 || (size_t)n < rctx->resp_len) goto next_io; rctx->state = OHS_ASN1_DONE; return 1; } } int OSSL_HTTP_REQ_CTX_nbio_d2i(OSSL_HTTP_REQ_CTX *rctx, ASN1_VALUE **pval, const ASN1_ITEM *it) { const unsigned char *p; int rv; *pval = NULL; if ((rv = OSSL_HTTP_REQ_CTX_nbio(rctx)) != 1) return rv; *pval = ASN1_item_d2i(NULL, &p, BIO_get_mem_data(rctx->mem, &p), it); return *pval != NULL; } #ifndef OPENSSL_NO_SOCK /* set up a new connection BIO, to HTTP server or to HTTP(S) proxy if given */ static BIO *http_new_bio(const char *server /* optionally includes ":port" */, const char *server_port /* explicit server port */, int use_ssl, const char *proxy /* optionally includes ":port" */, const char *proxy_port /* explicit proxy port */) { const char *host = server; const char *port = server_port; BIO *cbio; if (!ossl_assert(server != NULL)) return NULL; if (proxy != NULL) { host = proxy; port = proxy_port; } if (port == NULL && strchr(host, ':') == NULL) port = use_ssl ? OSSL_HTTPS_PORT : OSSL_HTTP_PORT; cbio = BIO_new_connect(host /* optionally includes ":port" */); if (cbio == NULL) goto end; if (port != NULL) (void)BIO_set_conn_port(cbio, port); end: return cbio; } #endif /* OPENSSL_NO_SOCK */ /* Exchange request and response via HTTP on (non-)blocking BIO */ BIO *OSSL_HTTP_REQ_CTX_exchange(OSSL_HTTP_REQ_CTX *rctx) { int rv; if (rctx == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return NULL; } for (;;) { rv = OSSL_HTTP_REQ_CTX_nbio(rctx); if (rv != -1) break; /* BIO_should_retry was true */ /* will not actually wait if rctx->max_time == 0 */ if (BIO_wait(rctx->rbio, rctx->max_time, 100 /* milliseconds */) <= 0) return NULL; } if (rv == 0) { if (rctx->redirection_url == NULL) { /* an error occurred */ if (rctx->len_to_send > 0) ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_SENDING); else ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_RECEIVING); } return NULL; } return rctx->state == OHS_STREAM ? rctx->rbio : rctx->mem; } int OSSL_HTTP_is_alive(const OSSL_HTTP_REQ_CTX *rctx) { return rctx != NULL && rctx->keep_alive != 0; } /* High-level HTTP API implementation */ /* Initiate an HTTP session using bio, else use given server, proxy, etc. */ OSSL_HTTP_REQ_CTX *OSSL_HTTP_open(const char *server, const char *port, const char *proxy, const char *no_proxy, int use_ssl, BIO *bio, BIO *rbio, OSSL_HTTP_bio_cb_t bio_update_fn, void *arg, int buf_size, int overall_timeout) { BIO *cbio; /* == bio if supplied, used as connection BIO if rbio is NULL */ OSSL_HTTP_REQ_CTX *rctx = NULL; if (use_ssl && bio_update_fn == NULL) { ERR_raise(ERR_LIB_HTTP, HTTP_R_TLS_NOT_ENABLED); return NULL; } if (rbio != NULL && (bio == NULL || bio_update_fn != NULL)) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT); return NULL; } if (bio != NULL) { cbio = bio; if (proxy != NULL || no_proxy != NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT); return NULL; } } else { #ifndef OPENSSL_NO_SOCK char *proxy_host = NULL, *proxy_port = NULL; if (server == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (port != NULL && *port == '\0') port = NULL; if (port == NULL && strchr(server, ':') == NULL) port = use_ssl ? OSSL_HTTPS_PORT : OSSL_HTTP_PORT; proxy = OSSL_HTTP_adapt_proxy(proxy, no_proxy, server, use_ssl); if (proxy != NULL && !OSSL_HTTP_parse_url(proxy, NULL /* use_ssl */, NULL /* user */, &proxy_host, &proxy_port, NULL /* num */, NULL /* path */, NULL, NULL)) return NULL; cbio = http_new_bio(server, port, use_ssl, proxy_host, proxy_port); OPENSSL_free(proxy_host); OPENSSL_free(proxy_port); if (cbio == NULL) return NULL; #else ERR_raise(ERR_LIB_HTTP, HTTP_R_SOCK_NOT_SUPPORTED); return NULL; #endif } (void)ERR_set_mark(); /* prepare removing any spurious libssl errors */ if (rbio == NULL && BIO_do_connect_retry(cbio, overall_timeout, -1) <= 0) { if (bio == NULL) /* cbio was not provided by caller */ BIO_free_all(cbio); goto end; } /* now overall_timeout is guaranteed to be >= 0 */ /* adapt in order to fix callback design flaw, see #17088 */ /* callback can be used to wrap or prepend TLS session */ if (bio_update_fn != NULL) { BIO *orig_bio = cbio; cbio = (*bio_update_fn)(cbio, arg, 1 /* connect */, use_ssl != 0); if (cbio == NULL) { if (bio == NULL) /* cbio was not provided by caller */ BIO_free_all(orig_bio); goto end; } } rctx = http_req_ctx_new(bio == NULL, cbio, rbio != NULL ? rbio : cbio, bio_update_fn, arg, use_ssl, proxy, server, port, buf_size, overall_timeout); end: if (rctx != NULL) /* remove any spurious error queue entries by ssl_add_cert_chain() */ (void)ERR_pop_to_mark(); else (void)ERR_clear_last_mark(); return rctx; } int OSSL_HTTP_set1_request(OSSL_HTTP_REQ_CTX *rctx, const char *path, const STACK_OF(CONF_VALUE) *headers, const char *content_type, BIO *req, const char *expected_content_type, int expect_asn1, size_t max_resp_len, int timeout, int keep_alive) { int use_http_proxy; if (rctx == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return 0; } use_http_proxy = rctx->proxy != NULL && !rctx->use_ssl; if (use_http_proxy && rctx->server == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } rctx->max_resp_len = max_resp_len; /* allows for 0: indefinite */ return OSSL_HTTP_REQ_CTX_set_request_line(rctx, req != NULL, use_http_proxy ? rctx->server : NULL, rctx->port, path) && add1_headers(rctx, headers, rctx->server) && OSSL_HTTP_REQ_CTX_set_expected(rctx, expected_content_type, expect_asn1, timeout, keep_alive) && set1_content(rctx, content_type, req); } /*- * Exchange single HTTP request and response according to rctx. * If rctx->method_POST then use POST, else use GET and ignore content_type. * The redirection_url output (freed by caller) parameter is used only for GET. */ BIO *OSSL_HTTP_exchange(OSSL_HTTP_REQ_CTX *rctx, char **redirection_url) { BIO *resp; if (rctx == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (redirection_url != NULL) *redirection_url = NULL; /* do this beforehand to prevent dbl free */ resp = OSSL_HTTP_REQ_CTX_exchange(rctx); if (resp == NULL) { if (rctx->redirection_url != NULL) { if (redirection_url == NULL) ERR_raise(ERR_LIB_HTTP, HTTP_R_REDIRECTION_NOT_ENABLED); else /* may be NULL if out of memory: */ *redirection_url = OPENSSL_strdup(rctx->redirection_url); } else { char buf[200]; unsigned long err = ERR_peek_error(); int lib = ERR_GET_LIB(err); int reason = ERR_GET_REASON(err); if (lib == ERR_LIB_SSL || lib == ERR_LIB_HTTP || (lib == ERR_LIB_BIO && reason == BIO_R_CONNECT_TIMEOUT) || (lib == ERR_LIB_BIO && reason == BIO_R_CONNECT_ERROR) #ifndef OPENSSL_NO_CMP || (lib == ERR_LIB_CMP && reason == CMP_R_POTENTIALLY_INVALID_CERTIFICATE) #endif ) { if (rctx->server != NULL) { BIO_snprintf(buf, sizeof(buf), "server=http%s://%s%s%s", rctx->use_ssl ? "s" : "", rctx->server, rctx->port != NULL ? ":" : "", rctx->port != NULL ? rctx->port : ""); ERR_add_error_data(1, buf); } if (rctx->proxy != NULL) ERR_add_error_data(2, " proxy=", rctx->proxy); if (err == 0) { BIO_snprintf(buf, sizeof(buf), " peer has disconnected%s", rctx->use_ssl ? " violating the protocol" : ", likely because it requires the use of TLS"); ERR_add_error_data(1, buf); } } } } if (resp != NULL && !BIO_up_ref(resp)) resp = NULL; return resp; } static int redirection_ok(int n_redir, const char *old_url, const char *new_url) { if (n_redir >= HTTP_VERSION_MAX_REDIRECTIONS) { ERR_raise(ERR_LIB_HTTP, HTTP_R_TOO_MANY_REDIRECTIONS); return 0; } if (*new_url == '/') /* redirection to same server => same protocol */ return 1; if (HAS_PREFIX(old_url, OSSL_HTTPS_NAME":") && !HAS_PREFIX(new_url, OSSL_HTTPS_NAME":")) { ERR_raise(ERR_LIB_HTTP, HTTP_R_REDIRECTION_FROM_HTTPS_TO_HTTP); return 0; } return 1; } /* Get data via HTTP from server at given URL, potentially with redirection */ BIO *OSSL_HTTP_get(const char *url, const char *proxy, const char *no_proxy, BIO *bio, BIO *rbio, OSSL_HTTP_bio_cb_t bio_update_fn, void *arg, int buf_size, const STACK_OF(CONF_VALUE) *headers, const char *expected_ct, int expect_asn1, size_t max_resp_len, int timeout) { char *current_url, *redirection_url = NULL; int n_redirs = 0; char *host; char *port; char *path; int use_ssl; OSSL_HTTP_REQ_CTX *rctx = NULL; BIO *resp = NULL; time_t max_time = timeout > 0 ? time(NULL) + timeout : 0; if (url == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if ((current_url = OPENSSL_strdup(url)) == NULL) return NULL; for (;;) { if (!OSSL_HTTP_parse_url(current_url, &use_ssl, NULL /* user */, &host, &port, NULL /* port_num */, &path, NULL, NULL)) break; rctx = OSSL_HTTP_open(host, port, proxy, no_proxy, use_ssl, bio, rbio, bio_update_fn, arg, buf_size, timeout); new_rpath: if (rctx != NULL) { if (!OSSL_HTTP_set1_request(rctx, path, headers, NULL /* content_type */, NULL /* req */, expected_ct, expect_asn1, max_resp_len, -1 /* use same max time (timeout) */, 0 /* no keep_alive */)) { OSSL_HTTP_REQ_CTX_free(rctx); rctx = NULL; } else { resp = OSSL_HTTP_exchange(rctx, &redirection_url); } } OPENSSL_free(path); if (resp == NULL && redirection_url != NULL) { if (redirection_ok(++n_redirs, current_url, redirection_url) && may_still_retry(max_time, &timeout)) { (void)BIO_reset(bio); OPENSSL_free(current_url); current_url = redirection_url; if (*redirection_url == '/') { /* redirection to same server */ path = OPENSSL_strdup(redirection_url); if (path == NULL) { OPENSSL_free(host); OPENSSL_free(port); (void)OSSL_HTTP_close(rctx, 1); rctx = NULL; BIO_free(resp); OPENSSL_free(current_url); return NULL; } goto new_rpath; } OPENSSL_free(host); OPENSSL_free(port); (void)OSSL_HTTP_close(rctx, 1); rctx = NULL; continue; } /* if redirection not allowed, ignore it */ OPENSSL_free(redirection_url); } OPENSSL_free(host); OPENSSL_free(port); if (!OSSL_HTTP_close(rctx, resp != NULL)) { BIO_free(resp); rctx = NULL; resp = NULL; } break; } OPENSSL_free(current_url); return resp; } /* Exchange request and response over a connection managed via |prctx| */ BIO *OSSL_HTTP_transfer(OSSL_HTTP_REQ_CTX **prctx, const char *server, const char *port, const char *path, int use_ssl, const char *proxy, const char *no_proxy, BIO *bio, BIO *rbio, OSSL_HTTP_bio_cb_t bio_update_fn, void *arg, int buf_size, const STACK_OF(CONF_VALUE) *headers, const char *content_type, BIO *req, const char *expected_ct, int expect_asn1, size_t max_resp_len, int timeout, int keep_alive) { OSSL_HTTP_REQ_CTX *rctx = prctx == NULL ? NULL : *prctx; BIO *resp = NULL; if (rctx == NULL) { rctx = OSSL_HTTP_open(server, port, proxy, no_proxy, use_ssl, bio, rbio, bio_update_fn, arg, buf_size, timeout); timeout = -1; /* Already set during opening the connection */ } if (rctx != NULL) { if (OSSL_HTTP_set1_request(rctx, path, headers, content_type, req, expected_ct, expect_asn1, max_resp_len, timeout, keep_alive)) resp = OSSL_HTTP_exchange(rctx, NULL); if (resp == NULL || !OSSL_HTTP_is_alive(rctx)) { if (!OSSL_HTTP_close(rctx, resp != NULL)) { BIO_free(resp); resp = NULL; } rctx = NULL; } } if (prctx != NULL) *prctx = rctx; return resp; } int OSSL_HTTP_close(OSSL_HTTP_REQ_CTX *rctx, int ok) { BIO *wbio; int ret = 1; /* callback can be used to finish TLS session and free its BIO */ if (rctx != NULL && rctx->upd_fn != NULL) { wbio = (*rctx->upd_fn)(rctx->wbio, rctx->upd_arg, 0 /* disconnect */, ok); ret = wbio != NULL; if (ret) rctx->wbio = wbio; } OSSL_HTTP_REQ_CTX_free(rctx); return ret; } /* BASE64 encoder used for encoding basic proxy authentication credentials */ static char *base64encode(const void *buf, size_t len) { int i; size_t outl; char *out; /* Calculate size of encoded data */ outl = (len / 3); if (len % 3 > 0) outl++; outl <<= 2; out = OPENSSL_malloc(outl + 1); if (out == NULL) return 0; i = EVP_EncodeBlock((unsigned char *)out, buf, len); if (!ossl_assert(0 <= i && (size_t)i <= outl)) { OPENSSL_free(out); return NULL; } return out; } /* * Promote the given connection BIO using the CONNECT method for a TLS proxy. * This is typically called by an app, so bio_err and prog are used unless NULL * to print additional diagnostic information in a user-oriented way. */ int OSSL_HTTP_proxy_connect(BIO *bio, const char *server, const char *port, const char *proxyuser, const char *proxypass, int timeout, BIO *bio_err, const char *prog) { #undef BUF_SIZE #define BUF_SIZE (8 * 1024) char *mbuf = OPENSSL_malloc(BUF_SIZE); char *mbufp; int read_len = 0; int ret = 0; BIO *fbio = BIO_new(BIO_f_buffer()); int rv; time_t max_time = timeout > 0 ? time(NULL) + timeout : 0; if (bio == NULL || server == NULL || (bio_err != NULL && prog == NULL)) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); goto end; } if (port == NULL || *port == '\0') port = OSSL_HTTPS_PORT; if (mbuf == NULL || fbio == NULL) { BIO_printf(bio_err /* may be NULL */, "%s: out of memory", prog); goto end; } BIO_push(fbio, bio); BIO_printf(fbio, "CONNECT %s:%s "HTTP_1_0"\r\n", server, port); /* * Workaround for broken proxies which would otherwise close * the connection when entering tunnel mode (e.g., Squid 2.6) */ BIO_printf(fbio, "Proxy-Connection: Keep-Alive\r\n"); /* Support for basic (base64) proxy authentication */ if (proxyuser != NULL) { size_t len = strlen(proxyuser) + 1; char *proxyauth, *proxyauthenc = NULL; if (proxypass != NULL) len += strlen(proxypass); proxyauth = OPENSSL_malloc(len + 1); if (proxyauth == NULL) goto end; if (BIO_snprintf(proxyauth, len + 1, "%s:%s", proxyuser, proxypass != NULL ? proxypass : "") != (int)len) goto proxy_end; proxyauthenc = base64encode(proxyauth, len); if (proxyauthenc != NULL) { BIO_printf(fbio, "Proxy-Authorization: Basic %s\r\n", proxyauthenc); OPENSSL_clear_free(proxyauthenc, strlen(proxyauthenc)); } proxy_end: OPENSSL_clear_free(proxyauth, len); if (proxyauthenc == NULL) goto end; } /* Terminate the HTTP CONNECT request */ BIO_printf(fbio, "\r\n"); for (;;) { if (BIO_flush(fbio) != 0) break; /* potentially needs to be retried if BIO is non-blocking */ if (!BIO_should_retry(fbio)) break; } for (;;) { /* will not actually wait if timeout == 0 */ rv = BIO_wait(fbio, max_time, 100 /* milliseconds */); if (rv <= 0) { BIO_printf(bio_err, "%s: HTTP CONNECT %s\n", prog, rv == 0 ? "timed out" : "failed waiting for data"); goto end; } /*- * The first line is the HTTP response. * According to RFC 7230, it is formatted exactly like this: * HTTP/d.d ddd reason text\r\n */ read_len = BIO_gets(fbio, mbuf, BUF_SIZE); /* the BIO may not block, so we must wait for the 1st line to come in */ if (read_len < (int)HTTP_LINE1_MINLEN) continue; /* Check for HTTP/1.x */ if (!HAS_PREFIX(mbuf, HTTP_PREFIX) != 0) { ERR_raise(ERR_LIB_HTTP, HTTP_R_HEADER_PARSE_ERROR); BIO_printf(bio_err, "%s: HTTP CONNECT failed, non-HTTP response\n", prog); /* Wrong protocol, not even HTTP, so stop reading headers */ goto end; } mbufp = mbuf + strlen(HTTP_PREFIX); if (!HAS_PREFIX(mbufp, HTTP_VERSION_PATT) != 0) { ERR_raise(ERR_LIB_HTTP, HTTP_R_RECEIVED_WRONG_HTTP_VERSION); BIO_printf(bio_err, "%s: HTTP CONNECT failed, bad HTTP version %.*s\n", prog, (int)HTTP_VERSION_STR_LEN, mbufp); goto end; } mbufp += HTTP_VERSION_STR_LEN; /* RFC 7231 4.3.6: any 2xx status code is valid */ if (!HAS_PREFIX(mbufp, " 2")) { /* chop any trailing whitespace */ while (read_len > 0 && ossl_isspace(mbuf[read_len - 1])) read_len--; mbuf[read_len] = '\0'; ERR_raise_data(ERR_LIB_HTTP, HTTP_R_CONNECT_FAILURE, "reason=%s", mbufp); BIO_printf(bio_err, "%s: HTTP CONNECT failed, reason=%s\n", prog, mbufp); goto end; } ret = 1; break; } /* Read past all following headers */ do { /* * This does not necessarily catch the case when the full * HTTP response came in in more than a single TCP message. */ read_len = BIO_gets(fbio, mbuf, BUF_SIZE); } while (read_len > 2); end: if (fbio != NULL) { (void)BIO_flush(fbio); BIO_pop(fbio); BIO_free(fbio); } OPENSSL_free(mbuf); return ret; #undef BUF_SIZE } diff --git a/crypto/mem.c b/crypto/mem.c index f6cdcf5a423e..bc9dc111676f 100644 --- a/crypto/mem.c +++ b/crypto/mem.c @@ -1,337 +1,336 @@ /* - * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "e_os.h" #include "internal/cryptlib.h" #include "crypto/cryptlib.h" #include #include #include #include /* * the following pointers may be changed as long as 'allow_customize' is set */ static int allow_customize = 1; static CRYPTO_malloc_fn malloc_impl = CRYPTO_malloc; static CRYPTO_realloc_fn realloc_impl = CRYPTO_realloc; static CRYPTO_free_fn free_impl = CRYPTO_free; #if !defined(OPENSSL_NO_CRYPTO_MDEBUG) && !defined(FIPS_MODULE) # include "internal/tsan_assist.h" # ifdef TSAN_REQUIRES_LOCKING # define INCREMENT(x) /* empty */ # define LOAD(x) 0 # else /* TSAN_REQUIRES_LOCKING */ static TSAN_QUALIFIER int malloc_count; static TSAN_QUALIFIER int realloc_count; static TSAN_QUALIFIER int free_count; # define INCREMENT(x) tsan_counter(&(x)) # define LOAD(x) tsan_load(&x) # endif /* TSAN_REQUIRES_LOCKING */ static char *md_failstring; static long md_count; static int md_fail_percent = 0; static int md_tracefd = -1; static void parseit(void); static int shouldfail(void); # define FAILTEST() if (shouldfail()) return NULL #else # define INCREMENT(x) /* empty */ # define FAILTEST() /* empty */ #endif int CRYPTO_set_mem_functions(CRYPTO_malloc_fn malloc_fn, CRYPTO_realloc_fn realloc_fn, CRYPTO_free_fn free_fn) { if (!allow_customize) return 0; if (malloc_fn != NULL) malloc_impl = malloc_fn; if (realloc_fn != NULL) realloc_impl = realloc_fn; if (free_fn != NULL) free_impl = free_fn; return 1; } void CRYPTO_get_mem_functions(CRYPTO_malloc_fn *malloc_fn, CRYPTO_realloc_fn *realloc_fn, CRYPTO_free_fn *free_fn) { if (malloc_fn != NULL) *malloc_fn = malloc_impl; if (realloc_fn != NULL) *realloc_fn = realloc_impl; if (free_fn != NULL) *free_fn = free_impl; } #if !defined(OPENSSL_NO_CRYPTO_MDEBUG) && !defined(FIPS_MODULE) void CRYPTO_get_alloc_counts(int *mcount, int *rcount, int *fcount) { if (mcount != NULL) *mcount = LOAD(malloc_count); if (rcount != NULL) *rcount = LOAD(realloc_count); if (fcount != NULL) *fcount = LOAD(free_count); } /* * Parse a "malloc failure spec" string. This likes like a set of fields * separated by semicolons. Each field has a count and an optional failure * percentage. For example: * 100@0;100@25;0@0 * or 100;100@25;0 * This means 100 mallocs succeed, then next 100 fail 25% of the time, and * all remaining (count is zero) succeed. */ static void parseit(void) { char *semi = strchr(md_failstring, ';'); char *atsign; if (semi != NULL) *semi++ = '\0'; /* Get the count (atol will stop at the @ if there), and percentage */ md_count = atol(md_failstring); atsign = strchr(md_failstring, '@'); md_fail_percent = atsign == NULL ? 0 : atoi(atsign + 1); if (semi != NULL) md_failstring = semi; } /* * Windows doesn't have random(), but it has rand() * Some rand() implementations aren't good, but we're not * dealing with secure randomness here. */ # ifdef _WIN32 # define random() rand() # endif /* * See if the current malloc should fail. */ static int shouldfail(void) { int roll = (int)(random() % 100); int shoulditfail = roll < md_fail_percent; # ifndef _WIN32 /* suppressed on Windows as POSIX-like file descriptors are non-inheritable */ int len; char buff[80]; if (md_tracefd > 0) { BIO_snprintf(buff, sizeof(buff), "%c C%ld %%%d R%d\n", shoulditfail ? '-' : '+', md_count, md_fail_percent, roll); len = strlen(buff); if (write(md_tracefd, buff, len) != len) perror("shouldfail write failed"); } # endif if (md_count) { /* If we used up this one, go to the next. */ if (--md_count == 0) parseit(); } return shoulditfail; } void ossl_malloc_setup_failures(void) { const char *cp = getenv("OPENSSL_MALLOC_FAILURES"); if (cp != NULL && (md_failstring = strdup(cp)) != NULL) parseit(); if ((cp = getenv("OPENSSL_MALLOC_FD")) != NULL) md_tracefd = atoi(cp); } #endif void *CRYPTO_malloc(size_t num, const char *file, int line) { INCREMENT(malloc_count); if (malloc_impl != CRYPTO_malloc) return malloc_impl(num, file, line); if (num == 0) return NULL; FAILTEST(); if (allow_customize) { /* * Disallow customization after the first allocation. We only set this * if necessary to avoid a store to the same cache line on every * allocation. */ allow_customize = 0; } return malloc(num); } void *CRYPTO_zalloc(size_t num, const char *file, int line) { void *ret; ret = CRYPTO_malloc(num, file, line); - FAILTEST(); if (ret != NULL) memset(ret, 0, num); return ret; } void *CRYPTO_realloc(void *str, size_t num, const char *file, int line) { INCREMENT(realloc_count); if (realloc_impl != CRYPTO_realloc) return realloc_impl(str, num, file, line); - FAILTEST(); if (str == NULL) return CRYPTO_malloc(num, file, line); if (num == 0) { CRYPTO_free(str, file, line); return NULL; } + FAILTEST(); return realloc(str, num); } void *CRYPTO_clear_realloc(void *str, size_t old_len, size_t num, const char *file, int line) { void *ret = NULL; if (str == NULL) return CRYPTO_malloc(num, file, line); if (num == 0) { CRYPTO_clear_free(str, old_len, file, line); return NULL; } /* Can't shrink the buffer since memcpy below copies |old_len| bytes. */ if (num < old_len) { OPENSSL_cleanse((char*)str + num, old_len - num); return str; } ret = CRYPTO_malloc(num, file, line); if (ret != NULL) { memcpy(ret, str, old_len); CRYPTO_clear_free(str, old_len, file, line); } return ret; } void CRYPTO_free(void *str, const char *file, int line) { INCREMENT(free_count); if (free_impl != CRYPTO_free) { free_impl(str, file, line); return; } free(str); } void CRYPTO_clear_free(void *str, size_t num, const char *file, int line) { if (str == NULL) return; if (num) OPENSSL_cleanse(str, num); CRYPTO_free(str, file, line); } #if !defined(OPENSSL_NO_CRYPTO_MDEBUG) # ifndef OPENSSL_NO_DEPRECATED_3_0 int CRYPTO_mem_ctrl(int mode) { (void)mode; return -1; } int CRYPTO_set_mem_debug(int flag) { (void)flag; return -1; } int CRYPTO_mem_debug_push(const char *info, const char *file, int line) { (void)info; (void)file; (void)line; return 0; } int CRYPTO_mem_debug_pop(void) { return 0; } void CRYPTO_mem_debug_malloc(void *addr, size_t num, int flag, const char *file, int line) { (void)addr; (void)num; (void)flag; (void)file; (void)line; } void CRYPTO_mem_debug_realloc(void *addr1, void *addr2, size_t num, int flag, const char *file, int line) { (void)addr1; (void)addr2; (void)num; (void)flag; (void)file; (void)line; } void CRYPTO_mem_debug_free(void *addr, int flag, const char *file, int line) { (void)addr; (void)flag; (void)file; (void)line; } int CRYPTO_mem_leaks(BIO *b) { (void)b; return -1; } # ifndef OPENSSL_NO_STDIO int CRYPTO_mem_leaks_fp(FILE *fp) { (void)fp; return -1; } # endif int CRYPTO_mem_leaks_cb(int (*cb)(const char *str, size_t len, void *u), void *u) { (void)cb; (void)u; return -1; } # endif #endif diff --git a/crypto/pem/pem_pkey.c b/crypto/pem/pem_pkey.c index 3e76852c67a4..4deee46ce550 100644 --- a/crypto/pem/pem_pkey.c +++ b/crypto/pem/pem_pkey.c @@ -1,440 +1,449 @@ /* - * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* We need to use some deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include #include #include #include #include #include #include #include #include #include #include #include "internal/cryptlib.h" #include "internal/passphrase.h" #include "crypto/asn1.h" #include "crypto/x509.h" #include "crypto/evp.h" #include "pem_local.h" int ossl_pem_check_suffix(const char *pem_str, const char *suffix); static EVP_PKEY *pem_read_bio_key_decoder(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u, OSSL_LIB_CTX *libctx, const char *propq, int selection) { EVP_PKEY *pkey = NULL; OSSL_DECODER_CTX *dctx = NULL; int pos, newpos; if ((pos = BIO_tell(bp)) < 0) /* We can depend on BIO_tell() thanks to the BIO_f_readbuffer() */ return NULL; dctx = OSSL_DECODER_CTX_new_for_pkey(&pkey, "PEM", NULL, NULL, selection, libctx, propq); if (dctx == NULL) return NULL; if (cb == NULL) cb = PEM_def_callback; if (!OSSL_DECODER_CTX_set_pem_password_cb(dctx, cb, u)) goto err; ERR_set_mark(); while (!OSSL_DECODER_from_bio(dctx, bp) || pkey == NULL) if (BIO_eof(bp) != 0 || (newpos = BIO_tell(bp)) < 0 || newpos <= pos) { ERR_clear_last_mark(); goto err; } else { if (ERR_GET_REASON(ERR_peek_error()) == ERR_R_UNSUPPORTED) { /* unsupported PEM data, try again */ ERR_pop_to_mark(); ERR_set_mark(); } else { /* other error, bail out */ ERR_clear_last_mark(); goto err; } pos = newpos; } ERR_pop_to_mark(); /* if we were asked for private key, the public key is optional */ if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) selection = selection & ~OSSL_KEYMGMT_SELECT_PUBLIC_KEY; if (!evp_keymgmt_util_has(pkey, selection)) { EVP_PKEY_free(pkey); pkey = NULL; ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_KEY_COMPONENTS); goto err; } if (x != NULL) { EVP_PKEY_free(*x); *x = pkey; } err: OSSL_DECODER_CTX_free(dctx); return pkey; } static EVP_PKEY *pem_read_bio_key_legacy(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u, OSSL_LIB_CTX *libctx, const char *propq, int selection) { char *nm = NULL; const unsigned char *p = NULL; unsigned char *data = NULL; long len; int slen; EVP_PKEY *ret = NULL; ERR_set_mark(); /* not interested in PEM read errors */ if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) { if (!PEM_bytes_read_bio_secmem(&data, &len, &nm, PEM_STRING_EVP_PKEY, bp, cb, u)) { ERR_pop_to_mark(); return NULL; } } else { const char *pem_string = PEM_STRING_PARAMETERS; if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) pem_string = PEM_STRING_PUBLIC; if (!PEM_bytes_read_bio(&data, &len, &nm, pem_string, bp, cb, u)) { ERR_pop_to_mark(); return NULL; } } ERR_clear_last_mark(); p = data; if (strcmp(nm, PEM_STRING_PKCS8INF) == 0) { PKCS8_PRIV_KEY_INFO *p8inf; if ((p8inf = d2i_PKCS8_PRIV_KEY_INFO(NULL, &p, len)) == NULL) goto p8err; ret = evp_pkcs82pkey_legacy(p8inf, libctx, propq); if (x != NULL) { EVP_PKEY_free(*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]; if ((p8 = d2i_X509_SIG(NULL, &p, len)) == NULL) goto p8err; if (cb != NULL) klen = cb(psbuf, PEM_BUFSIZE, 0, u); else klen = PEM_def_callback(psbuf, PEM_BUFSIZE, 0, u); if (klen < 0) { ERR_raise(ERR_LIB_PEM, 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 == NULL) goto p8err; ret = evp_pkcs82pkey_legacy(p8inf, libctx, propq); if (x != NULL) { EVP_PKEY_free(*x); *x = ret; } PKCS8_PRIV_KEY_INFO_free(p8inf); } else if ((slen = ossl_pem_check_suffix(nm, "PRIVATE KEY")) > 0) { const EVP_PKEY_ASN1_METHOD *ameth; ameth = EVP_PKEY_asn1_find_str(NULL, nm, slen); if (ameth == NULL || ameth->old_priv_decode == NULL) goto p8err; ret = ossl_d2i_PrivateKey_legacy(ameth->pkey_id, x, &p, len, libctx, propq); } else if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) == 0 && (selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) { /* Trying legacy PUBKEY decoding only if we do not want private key. */ ret = ossl_d2i_PUBKEY_legacy(x, &p, len); } else if ((selection & EVP_PKEY_KEYPAIR) == 0 && (slen = ossl_pem_check_suffix(nm, "PARAMETERS")) > 0) { /* Trying legacy params decoding only if we do not want a key. */ ret = EVP_PKEY_new(); if (ret == NULL) 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) { EVP_PKEY_free(*x); *x = ret; } } p8err: if (ret == NULL && ERR_peek_last_error() == 0) /* ensure some error is reported but do not hide the real one */ ERR_raise(ERR_LIB_PEM, ERR_R_ASN1_LIB); err: OPENSSL_secure_free(nm); OPENSSL_secure_clear_free(data, len); return ret; } static EVP_PKEY *pem_read_bio_key(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u, OSSL_LIB_CTX *libctx, const char *propq, int selection) { EVP_PKEY *ret = NULL; BIO *new_bio = NULL; int pos; struct ossl_passphrase_data_st pwdata = { 0 }; if ((pos = BIO_tell(bp)) < 0) { new_bio = BIO_new(BIO_f_readbuffer()); if (new_bio == NULL) return NULL; bp = BIO_push(new_bio, bp); pos = BIO_tell(bp); } if (cb == NULL) cb = PEM_def_callback; if (!ossl_pw_set_pem_password_cb(&pwdata, cb, u) || !ossl_pw_enable_passphrase_caching(&pwdata)) goto err; ERR_set_mark(); ret = pem_read_bio_key_decoder(bp, x, ossl_pw_pem_password, &pwdata, libctx, propq, selection); if (ret == NULL && (BIO_seek(bp, pos) < 0 || (ret = pem_read_bio_key_legacy(bp, x, ossl_pw_pem_password, &pwdata, libctx, propq, selection)) == NULL)) ERR_clear_last_mark(); else ERR_pop_to_mark(); err: ossl_pw_clear_passphrase_data(&pwdata); if (new_bio != NULL) { BIO_pop(new_bio); BIO_free(new_bio); } return ret; } EVP_PKEY *PEM_read_bio_PUBKEY_ex(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u, OSSL_LIB_CTX *libctx, const char *propq) { return pem_read_bio_key(bp, x, cb, u, libctx, propq, EVP_PKEY_PUBLIC_KEY); } EVP_PKEY *PEM_read_bio_PUBKEY(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u) { return PEM_read_bio_PUBKEY_ex(bp, x, cb, u, NULL, NULL); } #ifndef OPENSSL_NO_STDIO EVP_PKEY *PEM_read_PUBKEY_ex(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u, OSSL_LIB_CTX *libctx, const char *propq) { BIO *b; EVP_PKEY *ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB); return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = PEM_read_bio_PUBKEY_ex(b, x, cb, u, libctx, propq); BIO_free(b); return ret; } EVP_PKEY *PEM_read_PUBKEY(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u) { return PEM_read_PUBKEY_ex(fp, x, cb, u, NULL, NULL); } #endif EVP_PKEY *PEM_read_bio_PrivateKey_ex(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u, OSSL_LIB_CTX *libctx, const char *propq) { return pem_read_bio_key(bp, x, cb, u, libctx, propq, /* we also want the public key, if available */ EVP_PKEY_KEYPAIR); } EVP_PKEY *PEM_read_bio_PrivateKey(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u) { return PEM_read_bio_PrivateKey_ex(bp, x, cb, u, NULL, NULL); } PEM_write_cb_ex_fnsig(PrivateKey, EVP_PKEY, BIO, write_bio) { IMPLEMENT_PEM_provided_write_body_vars(pkey, PrivateKey, propq); IMPLEMENT_PEM_provided_write_body_pass(); IMPLEMENT_PEM_provided_write_body_main(pkey, bio); legacy: if (x != NULL && (x->ameth == NULL || x->ameth->priv_encode != NULL)) return PEM_write_bio_PKCS8PrivateKey(out, x, enc, (const char *)kstr, klen, cb, u); return PEM_write_bio_PrivateKey_traditional(out, x, enc, kstr, klen, cb, u); } PEM_write_cb_fnsig(PrivateKey, EVP_PKEY, BIO, write_bio) { return PEM_write_bio_PrivateKey_ex(out, x, enc, kstr, klen, cb, u, NULL, NULL); } /* * Note: there is no way to tell a provided pkey encoder to use "traditional" * encoding. Therefore, if the pkey is provided, we try to take a copy */ int PEM_write_bio_PrivateKey_traditional(BIO *bp, const EVP_PKEY *x, const EVP_CIPHER *enc, const unsigned char *kstr, int klen, pem_password_cb *cb, void *u) { char pem_str[80]; EVP_PKEY *copy = NULL; int ret; if (x == NULL) return 0; if (evp_pkey_is_assigned(x) && evp_pkey_is_provided(x) && evp_pkey_copy_downgraded(©, x)) x = copy; if (x->ameth == NULL || x->ameth->old_priv_encode == NULL) { ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_PUBLIC_KEY_TYPE); EVP_PKEY_free(copy); return 0; } BIO_snprintf(pem_str, 80, "%s PRIVATE KEY", x->ameth->pem_str); ret = PEM_ASN1_write_bio((i2d_of_void *)i2d_PrivateKey, pem_str, bp, x, enc, kstr, klen, cb, u); EVP_PKEY_free(copy); return ret; } +static int no_password_cb(char *buf, int num, int rwflag, void *userdata) +{ + return -1; +} + EVP_PKEY *PEM_read_bio_Parameters_ex(BIO *bp, EVP_PKEY **x, OSSL_LIB_CTX *libctx, const char *propq) { - return pem_read_bio_key(bp, x, NULL, NULL, libctx, propq, + /* + * PEM_read_bio_Parameters(_ex) should never ask for a password. Any attempt + * to get a password just fails. + */ + return pem_read_bio_key(bp, x, no_password_cb, NULL, libctx, propq, EVP_PKEY_KEY_PARAMETERS); } EVP_PKEY *PEM_read_bio_Parameters(BIO *bp, EVP_PKEY **x) { return PEM_read_bio_Parameters_ex(bp, x, NULL, NULL); } PEM_write_fnsig(Parameters, EVP_PKEY, BIO, write_bio) { char pem_str[80]; IMPLEMENT_PEM_provided_write_body_vars(pkey, Parameters, NULL); IMPLEMENT_PEM_provided_write_body_main(pkey, bio); legacy: 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, out, x, NULL, NULL, 0, 0, NULL); } #ifndef OPENSSL_NO_STDIO EVP_PKEY *PEM_read_PrivateKey_ex(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u, OSSL_LIB_CTX *libctx, const char *propq) { BIO *b; EVP_PKEY *ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB); return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = PEM_read_bio_PrivateKey_ex(b, x, cb, u, libctx, propq); BIO_free(b); return ret; } EVP_PKEY *PEM_read_PrivateKey(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u) { return PEM_read_PrivateKey_ex(fp, x, cb, u, NULL, NULL); } PEM_write_cb_ex_fnsig(PrivateKey, EVP_PKEY, FILE, write) { BIO *b; int ret; if ((b = BIO_new_fp(out, BIO_NOCLOSE)) == NULL) { ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB); return 0; } ret = PEM_write_bio_PrivateKey_ex(b, x, enc, kstr, klen, cb, u, libctx, propq); BIO_free(b); return ret; } PEM_write_cb_fnsig(PrivateKey, EVP_PKEY, FILE, write) { return PEM_write_PrivateKey_ex(out, x, enc, kstr, klen, cb, u, NULL, NULL); } #endif diff --git a/crypto/perlasm/arm-xlate.pl b/crypto/perlasm/arm-xlate.pl index a90885905c0f..38d570c79017 100755 --- a/crypto/perlasm/arm-xlate.pl +++ b/crypto/perlasm/arm-xlate.pl @@ -1,194 +1,193 @@ #! /usr/bin/env perl -# Copyright 2015-2020 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 2015-2023 The OpenSSL Project Authors. All Rights Reserved. # # Licensed under the Apache License 2.0 (the "License"). You may not use # this file except in compliance with the License. You can obtain a copy # in the file LICENSE in the source distribution or at # https://www.openssl.org/source/license.html use strict; my $flavour = shift; my $output = shift; open STDOUT,">$output" || die "can't open $output: $!"; $flavour = "linux32" if (!$flavour or $flavour eq "void"); my %GLOBALS; my $dotinlocallabels=($flavour=~/linux/)?1:0; ################################################################ # directives which need special treatment on different platforms ################################################################ my $arch = sub { if ($flavour =~ /linux/) { ".arch\t".join(',',@_); } else { ""; } }; my $fpu = sub { if ($flavour =~ /linux/) { ".fpu\t".join(',',@_); } else { ""; } }; my $rodata = sub { SWITCH: for ($flavour) { /linux/ && return ".section\t.rodata"; /ios/ && return ".section\t__TEXT,__const"; last; } }; my $hidden = sub { if ($flavour =~ /ios/) { ".private_extern\t".join(',',@_); } else { ".hidden\t".join(',',@_); } }; my $comm = sub { my @args = split(/,\s*/,shift); my $name = @args[0]; my $global = \$GLOBALS{$name}; my $ret; if ($flavour =~ /ios32/) { $ret = ".comm\t_$name,@args[1]\n"; $ret .= ".non_lazy_symbol_pointer\n"; $ret .= "$name:\n"; $ret .= ".indirect_symbol\t_$name\n"; $ret .= ".long\t0"; $name = "_$name"; } else { $ret = ".comm\t".join(',',@args); } $$global = $name; $ret; }; my $globl = sub { my $name = shift; my $global = \$GLOBALS{$name}; my $ret; SWITCH: for ($flavour) { /ios/ && do { $name = "_$name"; last; }; } $ret = ".globl $name" if (!$ret); $$global = $name; $ret; }; my $global = $globl; my $extern = sub { &$globl(@_); return; # return nothing }; my $type = sub { if ($flavour =~ /linux/) { ".type\t".join(',',@_); } elsif ($flavour =~ /ios32/) { if (join(',',@_) =~ /(\w+),%function/) { "#ifdef __thumb2__\n". ".thumb_func $1\n". "#endif"; } } else { ""; } }; my $size = sub { if ($flavour =~ /linux/) { ".size\t".join(',',@_); } else { ""; } }; my $inst = sub { if ($flavour =~ /linux/) { ".inst\t".join(',',@_); } else { ".long\t".join(',',@_); } }; my $asciz = sub { my $line = join(",",@_); if ($line =~ /^"(.*)"$/) { ".byte " . join(",",unpack("C*",$1),0) . "\n.align 2"; } else { ""; } }; my $adrp = sub { my ($args,$comment) = split(m|\s*//|,shift); "\tadrp\t$args\@PAGE"; } if ($flavour =~ /ios64/); sub range { my ($r,$sfx,$start,$end) = @_; join(",",map("$r$_$sfx",($start..$end))); } sub expand_line { my $line = shift; my @ret = (); pos($line)=0; while ($line =~ m/\G[^@\/\{\"]*/g) { if ($line =~ m/\G(@|\/\/|$)/gc) { last; } elsif ($line =~ m/\G\{/gc) { my $saved_pos = pos($line); $line =~ s/\G([rdqv])([0-9]+)([^\-]*)\-\1([0-9]+)\3/range($1,$3,$2,$4)/e; pos($line) = $saved_pos; $line =~ m/\G[^\}]*\}/g; } elsif ($line =~ m/\G\"/gc) { $line =~ m/\G[^\"]*\"/g; } } $line =~ s/\b(\w+)/$GLOBALS{$1} or $1/ge; if ($flavour =~ /ios64/) { $line =~ s/#:lo12:(\w+)/$1\@PAGEOFF/; } return $line; } while(my $line=<>) { if ($line =~ m/^\s*(#|@|\/\/)/) { print $line; next; } $line =~ s|/\*.*\*/||; # get rid of C-style comments... $line =~ s|^\s+||; # ... and skip whitespace in beginning... $line =~ s|\s+$||; # ... and at the end { $line =~ s|[\b\.]L(\w{2,})|L$1|g; # common denominator for Locallabel $line =~ s|\bL(\w{2,})|\.L$1|g if ($dotinlocallabels); } { - $line =~ s|(^[\.\w]+)\:\s*||; - my $label = $1; - if ($label) { + if ($line =~ s|(^[\.\w]+)\:\s*||) { + my $label = $1; printf "%s:",($GLOBALS{$label} or $label); } } if ($line !~ m/^[#@]/) { $line =~ s|^\s*(\.?)(\S+)\s*||; my $c = $1; $c = "\t" if ($c eq ""); my $mnemonic = $2; my $opcode; if ($mnemonic =~ m/([^\.]+)\.([^\.]+)/) { $opcode = eval("\$$1_$2"); } else { $opcode = eval("\$$mnemonic"); } my $arg=expand_line($line); if (ref($opcode) eq 'CODE') { $line = &$opcode($arg); } elsif ($mnemonic) { $line = $c.$mnemonic; $line.= "\t$arg" if ($arg ne ""); } } print $line if ($line); print "\n"; } close STDOUT or die "error closing STDOUT: $!"; diff --git a/crypto/pkcs12/p12_crt.c b/crypto/pkcs12/p12_crt.c index 00c71297463d..26a444f868b0 100644 --- a/crypto/pkcs12/p12_crt.c +++ b/crypto/pkcs12/p12_crt.c @@ -1,337 +1,359 @@ /* - * Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1999-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include #include "internal/cryptlib.h" #include #include "p12_local.h" static int pkcs12_add_bag(STACK_OF(PKCS12_SAFEBAG) **pbags, PKCS12_SAFEBAG *bag); +static PKCS12_SAFEBAG *pkcs12_add_cert_bag(STACK_OF(PKCS12_SAFEBAG) **pbags, + X509 *cert, + const char *name, + int namelen, + unsigned char *keyid, + int keyidlen); static int copy_bag_attr(PKCS12_SAFEBAG *bag, EVP_PKEY *pkey, int nid) { int idx; X509_ATTRIBUTE *attr; idx = EVP_PKEY_get_attr_by_NID(pkey, nid, -1); if (idx < 0) return 1; attr = EVP_PKEY_get_attr(pkey, idx); if (!X509at_add1_attr(&bag->attrib, attr)) return 0; return 1; } PKCS12 *PKCS12_create_ex(const char *pass, const char *name, EVP_PKEY *pkey, X509 *cert, STACK_OF(X509) *ca, int nid_key, int nid_cert, int iter, int mac_iter, int keytype, OSSL_LIB_CTX *ctx, const char *propq) { PKCS12 *p12 = NULL; STACK_OF(PKCS7) *safes = NULL; STACK_OF(PKCS12_SAFEBAG) *bags = NULL; PKCS12_SAFEBAG *bag = NULL; int i; unsigned char keyid[EVP_MAX_MD_SIZE]; unsigned int keyidlen = 0; + int namelen = -1; + unsigned char *pkeyid = NULL; + int pkeyidlen = -1; /* Set defaults */ if (nid_cert == NID_undef) nid_cert = NID_aes_256_cbc; if (nid_key == NID_undef) nid_key = NID_aes_256_cbc; if (!iter) iter = PKCS12_DEFAULT_ITER; if (!mac_iter) mac_iter = PKCS12_DEFAULT_ITER; if (pkey == NULL && cert == NULL && ca == NULL) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_INVALID_NULL_ARGUMENT); return NULL; } if (pkey && cert) { if (!X509_check_private_key(cert, pkey)) return NULL; if (!X509_digest(cert, EVP_sha1(), keyid, &keyidlen)) return NULL; } if (cert) { - bag = PKCS12_add_cert(&bags, cert); - if (name && !PKCS12_add_friendlyname(bag, name, -1)) - goto err; - if (keyidlen && !PKCS12_add_localkeyid(bag, keyid, keyidlen)) - goto err; + if (name == NULL) + name = (char *)X509_alias_get0(cert, &namelen); + if (keyidlen > 0) { + pkeyid = keyid; + pkeyidlen = keyidlen; + } else { + pkeyid = X509_keyid_get0(cert, &pkeyidlen); + } + + bag = pkcs12_add_cert_bag(&bags, cert, name, namelen, pkeyid, pkeyidlen); } /* Add all other certificates */ for (i = 0; i < sk_X509_num(ca); i++) { if (!PKCS12_add_cert(&bags, sk_X509_value(ca, i))) goto err; } if (bags && !PKCS12_add_safe_ex(&safes, bags, nid_cert, iter, pass, ctx, propq)) goto err; sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); bags = NULL; if (pkey) { bag = PKCS12_add_key_ex(&bags, pkey, keytype, iter, nid_key, pass, ctx, propq); if (!bag) goto err; if (!copy_bag_attr(bag, pkey, NID_ms_csp_name)) goto err; if (!copy_bag_attr(bag, pkey, NID_LocalKeySet)) goto err; if (name && !PKCS12_add_friendlyname(bag, name, -1)) goto err; if (keyidlen && !PKCS12_add_localkeyid(bag, keyid, keyidlen)) goto err; } if (bags && !PKCS12_add_safe(&safes, bags, -1, 0, NULL)) goto err; sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); bags = NULL; p12 = PKCS12_add_safes_ex(safes, 0, ctx, propq); if (p12 == NULL) goto err; sk_PKCS7_pop_free(safes, PKCS7_free); safes = NULL; if ((mac_iter != -1) && !PKCS12_set_mac(p12, pass, -1, NULL, 0, mac_iter, NULL)) goto err; return p12; err: PKCS12_free(p12); sk_PKCS7_pop_free(safes, PKCS7_free); sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); return NULL; } PKCS12 *PKCS12_create(const char *pass, const char *name, EVP_PKEY *pkey, X509 *cert, STACK_OF(X509) *ca, int nid_key, int nid_cert, int iter, int mac_iter, int keytype) { return PKCS12_create_ex(pass, name, pkey, cert, ca, nid_key, nid_cert, iter, mac_iter, keytype, NULL, NULL); } -PKCS12_SAFEBAG *PKCS12_add_cert(STACK_OF(PKCS12_SAFEBAG) **pbags, X509 *cert) +static PKCS12_SAFEBAG *pkcs12_add_cert_bag(STACK_OF(PKCS12_SAFEBAG) **pbags, + X509 *cert, + const char *name, + int namelen, + unsigned char *keyid, + int keyidlen) { PKCS12_SAFEBAG *bag = NULL; - char *name; - int namelen = -1; - unsigned char *keyid; - int keyidlen = -1; /* Add user certificate */ if ((bag = PKCS12_SAFEBAG_create_cert(cert)) == NULL) goto err; - /* - * Use friendlyName and localKeyID in certificate. (if present) - */ - - name = (char *)X509_alias_get0(cert, &namelen); - - if (name && !PKCS12_add_friendlyname(bag, name, namelen)) + if (name != NULL && !PKCS12_add_friendlyname(bag, name, namelen)) goto err; - keyid = X509_keyid_get0(cert, &keyidlen); - - if (keyid && !PKCS12_add_localkeyid(bag, keyid, keyidlen)) + if (keyid != NULL && !PKCS12_add_localkeyid(bag, keyid, keyidlen)) goto err; if (!pkcs12_add_bag(pbags, bag)) goto err; return bag; err: PKCS12_SAFEBAG_free(bag); return NULL; +} + +PKCS12_SAFEBAG *PKCS12_add_cert(STACK_OF(PKCS12_SAFEBAG) **pbags, X509 *cert) +{ + char *name = NULL; + int namelen = -1; + unsigned char *keyid = NULL; + int keyidlen = -1; + + /* + * Use friendlyName and localKeyID in certificate. (if present) + */ + name = (char *)X509_alias_get0(cert, &namelen); + keyid = X509_keyid_get0(cert, &keyidlen); + return pkcs12_add_cert_bag(pbags, cert, name, namelen, keyid, keyidlen); } PKCS12_SAFEBAG *PKCS12_add_key_ex(STACK_OF(PKCS12_SAFEBAG) **pbags, EVP_PKEY *key, int key_usage, int iter, int nid_key, const char *pass, OSSL_LIB_CTX *ctx, const char *propq) { PKCS12_SAFEBAG *bag = NULL; PKCS8_PRIV_KEY_INFO *p8 = NULL; /* Make a PKCS#8 structure */ if ((p8 = EVP_PKEY2PKCS8(key)) == NULL) goto err; if (key_usage && !PKCS8_add_keyusage(p8, key_usage)) goto err; if (nid_key != -1) { bag = PKCS12_SAFEBAG_create_pkcs8_encrypt_ex(nid_key, pass, -1, NULL, 0, iter, p8, ctx, propq); PKCS8_PRIV_KEY_INFO_free(p8); } else bag = PKCS12_SAFEBAG_create0_p8inf(p8); if (!bag) goto err; if (!pkcs12_add_bag(pbags, bag)) goto err; return bag; err: PKCS12_SAFEBAG_free(bag); return NULL; } PKCS12_SAFEBAG *PKCS12_add_key(STACK_OF(PKCS12_SAFEBAG) **pbags, EVP_PKEY *key, int key_usage, int iter, int nid_key, const char *pass) { return PKCS12_add_key_ex(pbags, key, key_usage, iter, nid_key, pass, NULL, NULL); } PKCS12_SAFEBAG *PKCS12_add_secret(STACK_OF(PKCS12_SAFEBAG) **pbags, int nid_type, const unsigned char *value, int len) { PKCS12_SAFEBAG *bag = NULL; /* Add secret, storing the value as an octet string */ if ((bag = PKCS12_SAFEBAG_create_secret(nid_type, V_ASN1_OCTET_STRING, value, len)) == NULL) goto err; if (!pkcs12_add_bag(pbags, bag)) goto err; return bag; err: PKCS12_SAFEBAG_free(bag); return NULL; } int PKCS12_add_safe_ex(STACK_OF(PKCS7) **psafes, STACK_OF(PKCS12_SAFEBAG) *bags, int nid_safe, int iter, const char *pass, OSSL_LIB_CTX *ctx, const char *propq) { PKCS7 *p7 = NULL; int free_safes = 0; if (*psafes == NULL) { *psafes = sk_PKCS7_new_null(); if (*psafes == NULL) return 0; free_safes = 1; } if (nid_safe == 0) #ifdef OPENSSL_NO_RC2 nid_safe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC; #else nid_safe = NID_pbe_WithSHA1And40BitRC2_CBC; #endif if (nid_safe == -1) p7 = PKCS12_pack_p7data(bags); else p7 = PKCS12_pack_p7encdata_ex(nid_safe, pass, -1, NULL, 0, iter, bags, ctx, propq); if (p7 == NULL) goto err; if (!sk_PKCS7_push(*psafes, p7)) goto err; return 1; err: if (free_safes) { sk_PKCS7_free(*psafes); *psafes = NULL; } PKCS7_free(p7); return 0; } int PKCS12_add_safe(STACK_OF(PKCS7) **psafes, STACK_OF(PKCS12_SAFEBAG) *bags, int nid_safe, int iter, const char *pass) { return PKCS12_add_safe_ex(psafes, bags, nid_safe, iter, pass, NULL, NULL); } static int pkcs12_add_bag(STACK_OF(PKCS12_SAFEBAG) **pbags, PKCS12_SAFEBAG *bag) { int free_bags = 0; if (pbags == NULL) return 1; if (*pbags == NULL) { *pbags = sk_PKCS12_SAFEBAG_new_null(); if (*pbags == NULL) return 0; free_bags = 1; } if (!sk_PKCS12_SAFEBAG_push(*pbags, bag)) { if (free_bags) { sk_PKCS12_SAFEBAG_free(*pbags); *pbags = NULL; } return 0; } return 1; } PKCS12 *PKCS12_add_safes_ex(STACK_OF(PKCS7) *safes, int nid_p7, OSSL_LIB_CTX *ctx, const char *propq) { PKCS12 *p12; if (nid_p7 <= 0) nid_p7 = NID_pkcs7_data; p12 = PKCS12_init_ex(nid_p7, ctx, propq); if (p12 == NULL) return NULL; if (!PKCS12_pack_authsafes(p12, safes)) { PKCS12_free(p12); return NULL; } return p12; } PKCS12 *PKCS12_add_safes(STACK_OF(PKCS7) *safes, int nid_p7) { return PKCS12_add_safes_ex(safes, nid_p7, NULL, NULL); } diff --git a/crypto/poly1305/asm/poly1305-x86_64.pl b/crypto/poly1305/asm/poly1305-x86_64.pl index fa9bfb7a7b81..4cddca1c514c 100755 --- a/crypto/poly1305/asm/poly1305-x86_64.pl +++ b/crypto/poly1305/asm/poly1305-x86_64.pl @@ -1,4187 +1,4187 @@ #! /usr/bin/env perl -# Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 2016-2023 The OpenSSL Project Authors. All Rights Reserved. # # Licensed under the Apache License 2.0 (the "License"). You may not use # this file except in compliance with the License. You can obtain a copy # in the file LICENSE in the source distribution or at # https://www.openssl.org/source/license.html # # ==================================================================== # 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/. # ==================================================================== # # This module implements Poly1305 hash for x86_64. # # March 2015 # # Initial release. # # December 2016 # # Add AVX512F+VL+BW code path. # # November 2017 # # Convert AVX512F+VL+BW code path to pure AVX512F, so that it can be # executed even on Knights Landing. Trigger for modification was # observation that AVX512 code paths can negatively affect overall # Skylake-X system performance. Since we are likely to suppress # AVX512F capability flag [at least on Skylake-X], conversion serves # as kind of "investment protection". Note that next *lake processor, # Cannolake, has AVX512IFMA code path to execute... # # Numbers are cycles per processed byte with poly1305_blocks alone, # measured with rdtsc at fixed clock frequency. # # IALU/gcc-4.8(*) AVX(**) AVX2 AVX-512 # P4 4.46/+120% - # Core 2 2.41/+90% - # Westmere 1.88/+120% - # Sandy Bridge 1.39/+140% 1.10 # Haswell 1.14/+175% 1.11 0.65 # Skylake[-X] 1.13/+120% 0.96 0.51 [0.35] # Silvermont 2.83/+95% - # Knights L 3.60/? 1.65 1.10 0.41(***) # Goldmont 1.70/+180% - # VIA Nano 1.82/+150% - # Sledgehammer 1.38/+160% - # Bulldozer 2.30/+130% 0.97 # Ryzen 1.15/+200% 1.08 1.18 # # (*) improvement coefficients relative to clang are more modest and # are ~50% on most processors, in both cases we are comparing to # __int128 code; # (**) SSE2 implementation was attempted, but among non-AVX processors # it was faster than integer-only code only on older Intel P4 and # Core processors, 50-30%, less newer processor is, but slower on # contemporary ones, for example almost 2x slower on Atom, and as # former are naturally disappearing, SSE2 is deemed unnecessary; # (***) strangely enough performance seems to vary from core to core, # listed result is best case; # $output is the last argument if it looks like a file (it has an extension) # $flavour is the first argument if it doesn't look like a file $output = $#ARGV >= 0 && $ARGV[$#ARGV] =~ m|\.\w+$| ? pop : undef; $flavour = $#ARGV >= 0 && $ARGV[0] !~ m|\.| ? shift : undef; $win64=0; $win64=1 if ($flavour =~ /[nm]asm|mingw64/ || $output =~ /\.asm$/); $0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; ( $xlate="${dir}x86_64-xlate.pl" and -f $xlate ) or ( $xlate="${dir}../../perlasm/x86_64-xlate.pl" and -f $xlate) or die "can't locate x86_64-xlate.pl"; if (`$ENV{CC} -Wa,-v -c -o /dev/null -x assembler /dev/null 2>&1` =~ /GNU assembler version ([2-9]\.[0-9]+)/) { $avx = ($1>=2.19) + ($1>=2.22) + ($1>=2.25) + ($1>=2.26); } if (!$avx && $win64 && ($flavour =~ /nasm/ || $ENV{ASM} =~ /nasm/) && `nasm -v 2>&1` =~ /NASM version ([2-9]\.[0-9]+)(?:\.([0-9]+))?/) { $avx = ($1>=2.09) + ($1>=2.10) + 2 * ($1>=2.12); $avx += 2 if ($1==2.11 && $2>=8); } if (!$avx && $win64 && ($flavour =~ /masm/ || $ENV{ASM} =~ /ml64/) && `ml64 2>&1` =~ /Version ([0-9]+)\./) { $avx = ($1>=10) + ($1>=12); } if (!$avx && `$ENV{CC} -v 2>&1` =~ /((?:clang|LLVM) version|.*based on LLVM) ([0-9]+\.[0-9]+)/) { $avx = ($2>=3.0) + ($2>3.0); } open OUT,"| \"$^X\" \"$xlate\" $flavour \"$output\"" or die "can't call $xlate: $!"; *STDOUT=*OUT; my ($ctx,$inp,$len,$padbit)=("%rdi","%rsi","%rdx","%rcx"); my ($mac,$nonce)=($inp,$len); # *_emit arguments my ($d1,$d2,$d3, $r0,$r1,$s1)=map("%r$_",(8..13)); my ($h0,$h1,$h2)=("%r14","%rbx","%rbp"); sub poly1305_iteration { # input: copy of $r1 in %rax, $h0-$h2, $r0-$r1 # output: $h0-$h2 *= $r0-$r1 $code.=<<___; mulq $h0 # h0*r1 mov %rax,$d2 mov $r0,%rax mov %rdx,$d3 mulq $h0 # h0*r0 mov %rax,$h0 # future $h0 mov $r0,%rax mov %rdx,$d1 mulq $h1 # h1*r0 add %rax,$d2 mov $s1,%rax adc %rdx,$d3 mulq $h1 # h1*s1 mov $h2,$h1 # borrow $h1 add %rax,$h0 adc %rdx,$d1 imulq $s1,$h1 # h2*s1 add $h1,$d2 mov $d1,$h1 adc \$0,$d3 imulq $r0,$h2 # h2*r0 add $d2,$h1 mov \$-4,%rax # mask value adc $h2,$d3 and $d3,%rax # last reduction step mov $d3,$h2 shr \$2,$d3 and \$3,$h2 add $d3,%rax add %rax,$h0 adc \$0,$h1 adc \$0,$h2 ___ } ######################################################################## # Layout of opaque area is following. # # unsigned __int64 h[3]; # current hash value base 2^64 # unsigned __int64 r[2]; # key value base 2^64 $code.=<<___; .text .extern OPENSSL_ia32cap_P .globl poly1305_init .hidden poly1305_init .globl poly1305_blocks .hidden poly1305_blocks .globl poly1305_emit .hidden poly1305_emit .type poly1305_init,\@function,3 .align 32 poly1305_init: .cfi_startproc xor %rax,%rax mov %rax,0($ctx) # initialize hash value mov %rax,8($ctx) mov %rax,16($ctx) cmp \$0,$inp je .Lno_key lea poly1305_blocks(%rip),%r10 lea poly1305_emit(%rip),%r11 ___ $code.=<<___ if ($avx); mov OPENSSL_ia32cap_P+4(%rip),%r9 lea poly1305_blocks_avx(%rip),%rax lea poly1305_emit_avx(%rip),%rcx bt \$`60-32`,%r9 # AVX? cmovc %rax,%r10 cmovc %rcx,%r11 ___ $code.=<<___ if ($avx>1); lea poly1305_blocks_avx2(%rip),%rax bt \$`5+32`,%r9 # AVX2? cmovc %rax,%r10 ___ -$code.=<<___ if ($avx>3); +$code.=<<___ if ($avx>3 && !$win64); mov \$`(1<<31|1<<21|1<<16)`,%rax shr \$32,%r9 and %rax,%r9 cmp %rax,%r9 je .Linit_base2_44 ___ $code.=<<___; mov \$0x0ffffffc0fffffff,%rax mov \$0x0ffffffc0ffffffc,%rcx and 0($inp),%rax and 8($inp),%rcx mov %rax,24($ctx) mov %rcx,32($ctx) ___ $code.=<<___ if ($flavour !~ /elf32/); mov %r10,0(%rdx) mov %r11,8(%rdx) ___ $code.=<<___ if ($flavour =~ /elf32/); mov %r10d,0(%rdx) mov %r11d,4(%rdx) ___ $code.=<<___; mov \$1,%eax .Lno_key: ret .cfi_endproc .size poly1305_init,.-poly1305_init .type poly1305_blocks,\@function,4 .align 32 poly1305_blocks: .cfi_startproc .Lblocks: shr \$4,$len jz .Lno_data # too short push %rbx .cfi_push %rbx push %rbp .cfi_push %rbp push %r12 .cfi_push %r12 push %r13 .cfi_push %r13 push %r14 .cfi_push %r14 push %r15 .cfi_push %r15 .Lblocks_body: mov $len,%r15 # reassign $len mov 24($ctx),$r0 # load r mov 32($ctx),$s1 mov 0($ctx),$h0 # load hash value mov 8($ctx),$h1 mov 16($ctx),$h2 mov $s1,$r1 shr \$2,$s1 mov $r1,%rax add $r1,$s1 # s1 = r1 + (r1 >> 2) jmp .Loop .align 32 .Loop: add 0($inp),$h0 # accumulate input adc 8($inp),$h1 lea 16($inp),$inp adc $padbit,$h2 ___ &poly1305_iteration(); $code.=<<___; mov $r1,%rax dec %r15 # len-=16 jnz .Loop mov $h0,0($ctx) # store hash value mov $h1,8($ctx) mov $h2,16($ctx) mov 0(%rsp),%r15 .cfi_restore %r15 mov 8(%rsp),%r14 .cfi_restore %r14 mov 16(%rsp),%r13 .cfi_restore %r13 mov 24(%rsp),%r12 .cfi_restore %r12 mov 32(%rsp),%rbp .cfi_restore %rbp mov 40(%rsp),%rbx .cfi_restore %rbx lea 48(%rsp),%rsp .cfi_adjust_cfa_offset -48 .Lno_data: .Lblocks_epilogue: ret .cfi_endproc .size poly1305_blocks,.-poly1305_blocks .type poly1305_emit,\@function,3 .align 32 poly1305_emit: .cfi_startproc .Lemit: mov 0($ctx),%r8 # load hash value mov 8($ctx),%r9 mov 16($ctx),%r10 mov %r8,%rax add \$5,%r8 # compare to modulus mov %r9,%rcx adc \$0,%r9 adc \$0,%r10 shr \$2,%r10 # did 130-bit value overflow? cmovnz %r8,%rax cmovnz %r9,%rcx add 0($nonce),%rax # accumulate nonce adc 8($nonce),%rcx mov %rax,0($mac) # write result mov %rcx,8($mac) ret .cfi_endproc .size poly1305_emit,.-poly1305_emit ___ if ($avx) { ######################################################################## # Layout of opaque area is following. # # unsigned __int32 h[5]; # current hash value base 2^26 # unsigned __int32 is_base2_26; # unsigned __int64 r[2]; # key value base 2^64 # unsigned __int64 pad; # struct { unsigned __int32 r^2, r^1, r^4, r^3; } r[9]; # # where r^n are base 2^26 digits of degrees of multiplier key. There are # 5 digits, but last four are interleaved with multiples of 5, totalling # in 9 elements: r0, r1, 5*r1, r2, 5*r2, r3, 5*r3, r4, 5*r4. my ($H0,$H1,$H2,$H3,$H4, $T0,$T1,$T2,$T3,$T4, $D0,$D1,$D2,$D3,$D4, $MASK) = map("%xmm$_",(0..15)); $code.=<<___; .type __poly1305_block,\@abi-omnipotent .align 32 __poly1305_block: .cfi_startproc ___ &poly1305_iteration(); $code.=<<___; ret .cfi_endproc .size __poly1305_block,.-__poly1305_block .type __poly1305_init_avx,\@abi-omnipotent .align 32 __poly1305_init_avx: .cfi_startproc mov $r0,$h0 mov $r1,$h1 xor $h2,$h2 lea 48+64($ctx),$ctx # size optimization mov $r1,%rax call __poly1305_block # r^2 mov \$0x3ffffff,%eax # save interleaved r^2 and r base 2^26 mov \$0x3ffffff,%edx mov $h0,$d1 and $h0#d,%eax mov $r0,$d2 and $r0#d,%edx mov %eax,`16*0+0-64`($ctx) shr \$26,$d1 mov %edx,`16*0+4-64`($ctx) shr \$26,$d2 mov \$0x3ffffff,%eax mov \$0x3ffffff,%edx and $d1#d,%eax and $d2#d,%edx mov %eax,`16*1+0-64`($ctx) lea (%rax,%rax,4),%eax # *5 mov %edx,`16*1+4-64`($ctx) lea (%rdx,%rdx,4),%edx # *5 mov %eax,`16*2+0-64`($ctx) shr \$26,$d1 mov %edx,`16*2+4-64`($ctx) shr \$26,$d2 mov $h1,%rax mov $r1,%rdx shl \$12,%rax shl \$12,%rdx or $d1,%rax or $d2,%rdx and \$0x3ffffff,%eax and \$0x3ffffff,%edx mov %eax,`16*3+0-64`($ctx) lea (%rax,%rax,4),%eax # *5 mov %edx,`16*3+4-64`($ctx) lea (%rdx,%rdx,4),%edx # *5 mov %eax,`16*4+0-64`($ctx) mov $h1,$d1 mov %edx,`16*4+4-64`($ctx) mov $r1,$d2 mov \$0x3ffffff,%eax mov \$0x3ffffff,%edx shr \$14,$d1 shr \$14,$d2 and $d1#d,%eax and $d2#d,%edx mov %eax,`16*5+0-64`($ctx) lea (%rax,%rax,4),%eax # *5 mov %edx,`16*5+4-64`($ctx) lea (%rdx,%rdx,4),%edx # *5 mov %eax,`16*6+0-64`($ctx) shr \$26,$d1 mov %edx,`16*6+4-64`($ctx) shr \$26,$d2 mov $h2,%rax shl \$24,%rax or %rax,$d1 mov $d1#d,`16*7+0-64`($ctx) lea ($d1,$d1,4),$d1 # *5 mov $d2#d,`16*7+4-64`($ctx) lea ($d2,$d2,4),$d2 # *5 mov $d1#d,`16*8+0-64`($ctx) mov $d2#d,`16*8+4-64`($ctx) mov $r1,%rax call __poly1305_block # r^3 mov \$0x3ffffff,%eax # save r^3 base 2^26 mov $h0,$d1 and $h0#d,%eax shr \$26,$d1 mov %eax,`16*0+12-64`($ctx) mov \$0x3ffffff,%edx and $d1#d,%edx mov %edx,`16*1+12-64`($ctx) lea (%rdx,%rdx,4),%edx # *5 shr \$26,$d1 mov %edx,`16*2+12-64`($ctx) mov $h1,%rax shl \$12,%rax or $d1,%rax and \$0x3ffffff,%eax mov %eax,`16*3+12-64`($ctx) lea (%rax,%rax,4),%eax # *5 mov $h1,$d1 mov %eax,`16*4+12-64`($ctx) mov \$0x3ffffff,%edx shr \$14,$d1 and $d1#d,%edx mov %edx,`16*5+12-64`($ctx) lea (%rdx,%rdx,4),%edx # *5 shr \$26,$d1 mov %edx,`16*6+12-64`($ctx) mov $h2,%rax shl \$24,%rax or %rax,$d1 mov $d1#d,`16*7+12-64`($ctx) lea ($d1,$d1,4),$d1 # *5 mov $d1#d,`16*8+12-64`($ctx) mov $r1,%rax call __poly1305_block # r^4 mov \$0x3ffffff,%eax # save r^4 base 2^26 mov $h0,$d1 and $h0#d,%eax shr \$26,$d1 mov %eax,`16*0+8-64`($ctx) mov \$0x3ffffff,%edx and $d1#d,%edx mov %edx,`16*1+8-64`($ctx) lea (%rdx,%rdx,4),%edx # *5 shr \$26,$d1 mov %edx,`16*2+8-64`($ctx) mov $h1,%rax shl \$12,%rax or $d1,%rax and \$0x3ffffff,%eax mov %eax,`16*3+8-64`($ctx) lea (%rax,%rax,4),%eax # *5 mov $h1,$d1 mov %eax,`16*4+8-64`($ctx) mov \$0x3ffffff,%edx shr \$14,$d1 and $d1#d,%edx mov %edx,`16*5+8-64`($ctx) lea (%rdx,%rdx,4),%edx # *5 shr \$26,$d1 mov %edx,`16*6+8-64`($ctx) mov $h2,%rax shl \$24,%rax or %rax,$d1 mov $d1#d,`16*7+8-64`($ctx) lea ($d1,$d1,4),$d1 # *5 mov $d1#d,`16*8+8-64`($ctx) lea -48-64($ctx),$ctx # size [de-]optimization ret .cfi_endproc .size __poly1305_init_avx,.-__poly1305_init_avx .type poly1305_blocks_avx,\@function,4 .align 32 poly1305_blocks_avx: .cfi_startproc mov 20($ctx),%r8d # is_base2_26 cmp \$128,$len jae .Lblocks_avx test %r8d,%r8d jz .Lblocks .Lblocks_avx: and \$-16,$len jz .Lno_data_avx vzeroupper test %r8d,%r8d jz .Lbase2_64_avx test \$31,$len jz .Leven_avx push %rbx .cfi_push %rbx push %rbp .cfi_push %rbp push %r12 .cfi_push %r12 push %r13 .cfi_push %r13 push %r14 .cfi_push %r14 push %r15 .cfi_push %r15 .Lblocks_avx_body: mov $len,%r15 # reassign $len mov 0($ctx),$d1 # load hash value mov 8($ctx),$d2 mov 16($ctx),$h2#d mov 24($ctx),$r0 # load r mov 32($ctx),$s1 ################################# base 2^26 -> base 2^64 mov $d1#d,$h0#d and \$`-1*(1<<31)`,$d1 mov $d2,$r1 # borrow $r1 mov $d2#d,$h1#d and \$`-1*(1<<31)`,$d2 shr \$6,$d1 shl \$52,$r1 add $d1,$h0 shr \$12,$h1 shr \$18,$d2 add $r1,$h0 adc $d2,$h1 mov $h2,$d1 shl \$40,$d1 shr \$24,$h2 add $d1,$h1 adc \$0,$h2 # can be partially reduced... mov \$-4,$d2 # ... so reduce mov $h2,$d1 and $h2,$d2 shr \$2,$d1 and \$3,$h2 add $d2,$d1 # =*5 add $d1,$h0 adc \$0,$h1 adc \$0,$h2 mov $s1,$r1 mov $s1,%rax shr \$2,$s1 add $r1,$s1 # s1 = r1 + (r1 >> 2) add 0($inp),$h0 # accumulate input adc 8($inp),$h1 lea 16($inp),$inp adc $padbit,$h2 call __poly1305_block test $padbit,$padbit # if $padbit is zero, jz .Lstore_base2_64_avx # store hash in base 2^64 format ################################# base 2^64 -> base 2^26 mov $h0,%rax mov $h0,%rdx shr \$52,$h0 mov $h1,$r0 mov $h1,$r1 shr \$26,%rdx and \$0x3ffffff,%rax # h[0] shl \$12,$r0 and \$0x3ffffff,%rdx # h[1] shr \$14,$h1 or $r0,$h0 shl \$24,$h2 and \$0x3ffffff,$h0 # h[2] shr \$40,$r1 and \$0x3ffffff,$h1 # h[3] or $r1,$h2 # h[4] sub \$16,%r15 jz .Lstore_base2_26_avx vmovd %rax#d,$H0 vmovd %rdx#d,$H1 vmovd $h0#d,$H2 vmovd $h1#d,$H3 vmovd $h2#d,$H4 jmp .Lproceed_avx .align 32 .Lstore_base2_64_avx: mov $h0,0($ctx) mov $h1,8($ctx) mov $h2,16($ctx) # note that is_base2_26 is zeroed jmp .Ldone_avx .align 16 .Lstore_base2_26_avx: mov %rax#d,0($ctx) # store hash value base 2^26 mov %rdx#d,4($ctx) mov $h0#d,8($ctx) mov $h1#d,12($ctx) mov $h2#d,16($ctx) .align 16 .Ldone_avx: mov 0(%rsp),%r15 .cfi_restore %r15 mov 8(%rsp),%r14 .cfi_restore %r14 mov 16(%rsp),%r13 .cfi_restore %r13 mov 24(%rsp),%r12 .cfi_restore %r12 mov 32(%rsp),%rbp .cfi_restore %rbp mov 40(%rsp),%rbx .cfi_restore %rbx lea 48(%rsp),%rsp .cfi_adjust_cfa_offset -48 .Lno_data_avx: .Lblocks_avx_epilogue: ret .cfi_endproc .align 32 .Lbase2_64_avx: .cfi_startproc push %rbx .cfi_push %rbx push %rbp .cfi_push %rbp push %r12 .cfi_push %r12 push %r13 .cfi_push %r13 push %r14 .cfi_push %r14 push %r15 .cfi_push %r15 .Lbase2_64_avx_body: mov $len,%r15 # reassign $len mov 24($ctx),$r0 # load r mov 32($ctx),$s1 mov 0($ctx),$h0 # load hash value mov 8($ctx),$h1 mov 16($ctx),$h2#d mov $s1,$r1 mov $s1,%rax shr \$2,$s1 add $r1,$s1 # s1 = r1 + (r1 >> 2) test \$31,$len jz .Linit_avx add 0($inp),$h0 # accumulate input adc 8($inp),$h1 lea 16($inp),$inp adc $padbit,$h2 sub \$16,%r15 call __poly1305_block .Linit_avx: ################################# base 2^64 -> base 2^26 mov $h0,%rax mov $h0,%rdx shr \$52,$h0 mov $h1,$d1 mov $h1,$d2 shr \$26,%rdx and \$0x3ffffff,%rax # h[0] shl \$12,$d1 and \$0x3ffffff,%rdx # h[1] shr \$14,$h1 or $d1,$h0 shl \$24,$h2 and \$0x3ffffff,$h0 # h[2] shr \$40,$d2 and \$0x3ffffff,$h1 # h[3] or $d2,$h2 # h[4] vmovd %rax#d,$H0 vmovd %rdx#d,$H1 vmovd $h0#d,$H2 vmovd $h1#d,$H3 vmovd $h2#d,$H4 movl \$1,20($ctx) # set is_base2_26 call __poly1305_init_avx .Lproceed_avx: mov %r15,$len mov 0(%rsp),%r15 .cfi_restore %r15 mov 8(%rsp),%r14 .cfi_restore %r14 mov 16(%rsp),%r13 .cfi_restore %r13 mov 24(%rsp),%r12 .cfi_restore %r12 mov 32(%rsp),%rbp .cfi_restore %rbp mov 40(%rsp),%rbx .cfi_restore %rbx lea 48(%rsp),%rax lea 48(%rsp),%rsp .cfi_adjust_cfa_offset -48 .Lbase2_64_avx_epilogue: jmp .Ldo_avx .cfi_endproc .align 32 .Leven_avx: .cfi_startproc vmovd 4*0($ctx),$H0 # load hash value vmovd 4*1($ctx),$H1 vmovd 4*2($ctx),$H2 vmovd 4*3($ctx),$H3 vmovd 4*4($ctx),$H4 .Ldo_avx: ___ $code.=<<___ if (!$win64); lea -0x58(%rsp),%r11 .cfi_def_cfa %r11,0x60 sub \$0x178,%rsp ___ $code.=<<___ if ($win64); lea -0xf8(%rsp),%r11 sub \$0x218,%rsp vmovdqa %xmm6,0x50(%r11) vmovdqa %xmm7,0x60(%r11) vmovdqa %xmm8,0x70(%r11) vmovdqa %xmm9,0x80(%r11) vmovdqa %xmm10,0x90(%r11) vmovdqa %xmm11,0xa0(%r11) vmovdqa %xmm12,0xb0(%r11) vmovdqa %xmm13,0xc0(%r11) vmovdqa %xmm14,0xd0(%r11) vmovdqa %xmm15,0xe0(%r11) .Ldo_avx_body: ___ $code.=<<___; sub \$64,$len lea -32($inp),%rax cmovc %rax,$inp vmovdqu `16*3`($ctx),$D4 # preload r0^2 lea `16*3+64`($ctx),$ctx # size optimization lea .Lconst(%rip),%rcx ################################################################ # load input vmovdqu 16*2($inp),$T0 vmovdqu 16*3($inp),$T1 vmovdqa 64(%rcx),$MASK # .Lmask26 vpsrldq \$6,$T0,$T2 # splat input vpsrldq \$6,$T1,$T3 vpunpckhqdq $T1,$T0,$T4 # 4 vpunpcklqdq $T1,$T0,$T0 # 0:1 vpunpcklqdq $T3,$T2,$T3 # 2:3 vpsrlq \$40,$T4,$T4 # 4 vpsrlq \$26,$T0,$T1 vpand $MASK,$T0,$T0 # 0 vpsrlq \$4,$T3,$T2 vpand $MASK,$T1,$T1 # 1 vpsrlq \$30,$T3,$T3 vpand $MASK,$T2,$T2 # 2 vpand $MASK,$T3,$T3 # 3 vpor 32(%rcx),$T4,$T4 # padbit, yes, always jbe .Lskip_loop_avx # expand and copy pre-calculated table to stack vmovdqu `16*1-64`($ctx),$D1 vmovdqu `16*2-64`($ctx),$D2 vpshufd \$0xEE,$D4,$D3 # 34xx -> 3434 vpshufd \$0x44,$D4,$D0 # xx12 -> 1212 vmovdqa $D3,-0x90(%r11) vmovdqa $D0,0x00(%rsp) vpshufd \$0xEE,$D1,$D4 vmovdqu `16*3-64`($ctx),$D0 vpshufd \$0x44,$D1,$D1 vmovdqa $D4,-0x80(%r11) vmovdqa $D1,0x10(%rsp) vpshufd \$0xEE,$D2,$D3 vmovdqu `16*4-64`($ctx),$D1 vpshufd \$0x44,$D2,$D2 vmovdqa $D3,-0x70(%r11) vmovdqa $D2,0x20(%rsp) vpshufd \$0xEE,$D0,$D4 vmovdqu `16*5-64`($ctx),$D2 vpshufd \$0x44,$D0,$D0 vmovdqa $D4,-0x60(%r11) vmovdqa $D0,0x30(%rsp) vpshufd \$0xEE,$D1,$D3 vmovdqu `16*6-64`($ctx),$D0 vpshufd \$0x44,$D1,$D1 vmovdqa $D3,-0x50(%r11) vmovdqa $D1,0x40(%rsp) vpshufd \$0xEE,$D2,$D4 vmovdqu `16*7-64`($ctx),$D1 vpshufd \$0x44,$D2,$D2 vmovdqa $D4,-0x40(%r11) vmovdqa $D2,0x50(%rsp) vpshufd \$0xEE,$D0,$D3 vmovdqu `16*8-64`($ctx),$D2 vpshufd \$0x44,$D0,$D0 vmovdqa $D3,-0x30(%r11) vmovdqa $D0,0x60(%rsp) vpshufd \$0xEE,$D1,$D4 vpshufd \$0x44,$D1,$D1 vmovdqa $D4,-0x20(%r11) vmovdqa $D1,0x70(%rsp) vpshufd \$0xEE,$D2,$D3 vmovdqa 0x00(%rsp),$D4 # preload r0^2 vpshufd \$0x44,$D2,$D2 vmovdqa $D3,-0x10(%r11) vmovdqa $D2,0x80(%rsp) jmp .Loop_avx .align 32 .Loop_avx: ################################################################ # ((inp[0]*r^4+inp[2]*r^2+inp[4])*r^4+inp[6]*r^2 # ((inp[1]*r^4+inp[3]*r^2+inp[5])*r^3+inp[7]*r # \___________________/ # ((inp[0]*r^4+inp[2]*r^2+inp[4])*r^4+inp[6]*r^2+inp[8])*r^2 # ((inp[1]*r^4+inp[3]*r^2+inp[5])*r^4+inp[7]*r^2+inp[9])*r # \___________________/ \____________________/ # # Note that we start with inp[2:3]*r^2. This is because it # doesn't depend on reduction in previous iteration. ################################################################ # d4 = h4*r0 + h3*r1 + h2*r2 + h1*r3 + h0*r4 # d3 = h3*r0 + h2*r1 + h1*r2 + h0*r3 + h4*5*r4 # d2 = h2*r0 + h1*r1 + h0*r2 + h4*5*r3 + h3*5*r4 # d1 = h1*r0 + h0*r1 + h4*5*r2 + h3*5*r3 + h2*5*r4 # d0 = h0*r0 + h4*5*r1 + h3*5*r2 + h2*5*r3 + h1*5*r4 # # though note that $Tx and $Hx are "reversed" in this section, # and $D4 is preloaded with r0^2... vpmuludq $T0,$D4,$D0 # d0 = h0*r0 vpmuludq $T1,$D4,$D1 # d1 = h1*r0 vmovdqa $H2,0x20(%r11) # offload hash vpmuludq $T2,$D4,$D2 # d3 = h2*r0 vmovdqa 0x10(%rsp),$H2 # r1^2 vpmuludq $T3,$D4,$D3 # d3 = h3*r0 vpmuludq $T4,$D4,$D4 # d4 = h4*r0 vmovdqa $H0,0x00(%r11) # vpmuludq 0x20(%rsp),$T4,$H0 # h4*s1 vmovdqa $H1,0x10(%r11) # vpmuludq $T3,$H2,$H1 # h3*r1 vpaddq $H0,$D0,$D0 # d0 += h4*s1 vpaddq $H1,$D4,$D4 # d4 += h3*r1 vmovdqa $H3,0x30(%r11) # vpmuludq $T2,$H2,$H0 # h2*r1 vpmuludq $T1,$H2,$H1 # h1*r1 vpaddq $H0,$D3,$D3 # d3 += h2*r1 vmovdqa 0x30(%rsp),$H3 # r2^2 vpaddq $H1,$D2,$D2 # d2 += h1*r1 vmovdqa $H4,0x40(%r11) # vpmuludq $T0,$H2,$H2 # h0*r1 vpmuludq $T2,$H3,$H0 # h2*r2 vpaddq $H2,$D1,$D1 # d1 += h0*r1 vmovdqa 0x40(%rsp),$H4 # s2^2 vpaddq $H0,$D4,$D4 # d4 += h2*r2 vpmuludq $T1,$H3,$H1 # h1*r2 vpmuludq $T0,$H3,$H3 # h0*r2 vpaddq $H1,$D3,$D3 # d3 += h1*r2 vmovdqa 0x50(%rsp),$H2 # r3^2 vpaddq $H3,$D2,$D2 # d2 += h0*r2 vpmuludq $T4,$H4,$H0 # h4*s2 vpmuludq $T3,$H4,$H4 # h3*s2 vpaddq $H0,$D1,$D1 # d1 += h4*s2 vmovdqa 0x60(%rsp),$H3 # s3^2 vpaddq $H4,$D0,$D0 # d0 += h3*s2 vmovdqa 0x80(%rsp),$H4 # s4^2 vpmuludq $T1,$H2,$H1 # h1*r3 vpmuludq $T0,$H2,$H2 # h0*r3 vpaddq $H1,$D4,$D4 # d4 += h1*r3 vpaddq $H2,$D3,$D3 # d3 += h0*r3 vpmuludq $T4,$H3,$H0 # h4*s3 vpmuludq $T3,$H3,$H1 # h3*s3 vpaddq $H0,$D2,$D2 # d2 += h4*s3 vmovdqu 16*0($inp),$H0 # load input vpaddq $H1,$D1,$D1 # d1 += h3*s3 vpmuludq $T2,$H3,$H3 # h2*s3 vpmuludq $T2,$H4,$T2 # h2*s4 vpaddq $H3,$D0,$D0 # d0 += h2*s3 vmovdqu 16*1($inp),$H1 # vpaddq $T2,$D1,$D1 # d1 += h2*s4 vpmuludq $T3,$H4,$T3 # h3*s4 vpmuludq $T4,$H4,$T4 # h4*s4 vpsrldq \$6,$H0,$H2 # splat input vpaddq $T3,$D2,$D2 # d2 += h3*s4 vpaddq $T4,$D3,$D3 # d3 += h4*s4 vpsrldq \$6,$H1,$H3 # vpmuludq 0x70(%rsp),$T0,$T4 # h0*r4 vpmuludq $T1,$H4,$T0 # h1*s4 vpunpckhqdq $H1,$H0,$H4 # 4 vpaddq $T4,$D4,$D4 # d4 += h0*r4 vmovdqa -0x90(%r11),$T4 # r0^4 vpaddq $T0,$D0,$D0 # d0 += h1*s4 vpunpcklqdq $H1,$H0,$H0 # 0:1 vpunpcklqdq $H3,$H2,$H3 # 2:3 #vpsrlq \$40,$H4,$H4 # 4 vpsrldq \$`40/8`,$H4,$H4 # 4 vpsrlq \$26,$H0,$H1 vpand $MASK,$H0,$H0 # 0 vpsrlq \$4,$H3,$H2 vpand $MASK,$H1,$H1 # 1 vpand 0(%rcx),$H4,$H4 # .Lmask24 vpsrlq \$30,$H3,$H3 vpand $MASK,$H2,$H2 # 2 vpand $MASK,$H3,$H3 # 3 vpor 32(%rcx),$H4,$H4 # padbit, yes, always vpaddq 0x00(%r11),$H0,$H0 # add hash value vpaddq 0x10(%r11),$H1,$H1 vpaddq 0x20(%r11),$H2,$H2 vpaddq 0x30(%r11),$H3,$H3 vpaddq 0x40(%r11),$H4,$H4 lea 16*2($inp),%rax lea 16*4($inp),$inp sub \$64,$len cmovc %rax,$inp ################################################################ # Now we accumulate (inp[0:1]+hash)*r^4 ################################################################ # d4 = h4*r0 + h3*r1 + h2*r2 + h1*r3 + h0*r4 # d3 = h3*r0 + h2*r1 + h1*r2 + h0*r3 + h4*5*r4 # d2 = h2*r0 + h1*r1 + h0*r2 + h4*5*r3 + h3*5*r4 # d1 = h1*r0 + h0*r1 + h4*5*r2 + h3*5*r3 + h2*5*r4 # d0 = h0*r0 + h4*5*r1 + h3*5*r2 + h2*5*r3 + h1*5*r4 vpmuludq $H0,$T4,$T0 # h0*r0 vpmuludq $H1,$T4,$T1 # h1*r0 vpaddq $T0,$D0,$D0 vpaddq $T1,$D1,$D1 vmovdqa -0x80(%r11),$T2 # r1^4 vpmuludq $H2,$T4,$T0 # h2*r0 vpmuludq $H3,$T4,$T1 # h3*r0 vpaddq $T0,$D2,$D2 vpaddq $T1,$D3,$D3 vpmuludq $H4,$T4,$T4 # h4*r0 vpmuludq -0x70(%r11),$H4,$T0 # h4*s1 vpaddq $T4,$D4,$D4 vpaddq $T0,$D0,$D0 # d0 += h4*s1 vpmuludq $H2,$T2,$T1 # h2*r1 vpmuludq $H3,$T2,$T0 # h3*r1 vpaddq $T1,$D3,$D3 # d3 += h2*r1 vmovdqa -0x60(%r11),$T3 # r2^4 vpaddq $T0,$D4,$D4 # d4 += h3*r1 vpmuludq $H1,$T2,$T1 # h1*r1 vpmuludq $H0,$T2,$T2 # h0*r1 vpaddq $T1,$D2,$D2 # d2 += h1*r1 vpaddq $T2,$D1,$D1 # d1 += h0*r1 vmovdqa -0x50(%r11),$T4 # s2^4 vpmuludq $H2,$T3,$T0 # h2*r2 vpmuludq $H1,$T3,$T1 # h1*r2 vpaddq $T0,$D4,$D4 # d4 += h2*r2 vpaddq $T1,$D3,$D3 # d3 += h1*r2 vmovdqa -0x40(%r11),$T2 # r3^4 vpmuludq $H0,$T3,$T3 # h0*r2 vpmuludq $H4,$T4,$T0 # h4*s2 vpaddq $T3,$D2,$D2 # d2 += h0*r2 vpaddq $T0,$D1,$D1 # d1 += h4*s2 vmovdqa -0x30(%r11),$T3 # s3^4 vpmuludq $H3,$T4,$T4 # h3*s2 vpmuludq $H1,$T2,$T1 # h1*r3 vpaddq $T4,$D0,$D0 # d0 += h3*s2 vmovdqa -0x10(%r11),$T4 # s4^4 vpaddq $T1,$D4,$D4 # d4 += h1*r3 vpmuludq $H0,$T2,$T2 # h0*r3 vpmuludq $H4,$T3,$T0 # h4*s3 vpaddq $T2,$D3,$D3 # d3 += h0*r3 vpaddq $T0,$D2,$D2 # d2 += h4*s3 vmovdqu 16*2($inp),$T0 # load input vpmuludq $H3,$T3,$T2 # h3*s3 vpmuludq $H2,$T3,$T3 # h2*s3 vpaddq $T2,$D1,$D1 # d1 += h3*s3 vmovdqu 16*3($inp),$T1 # vpaddq $T3,$D0,$D0 # d0 += h2*s3 vpmuludq $H2,$T4,$H2 # h2*s4 vpmuludq $H3,$T4,$H3 # h3*s4 vpsrldq \$6,$T0,$T2 # splat input vpaddq $H2,$D1,$D1 # d1 += h2*s4 vpmuludq $H4,$T4,$H4 # h4*s4 vpsrldq \$6,$T1,$T3 # vpaddq $H3,$D2,$H2 # h2 = d2 + h3*s4 vpaddq $H4,$D3,$H3 # h3 = d3 + h4*s4 vpmuludq -0x20(%r11),$H0,$H4 # h0*r4 vpmuludq $H1,$T4,$H0 vpunpckhqdq $T1,$T0,$T4 # 4 vpaddq $H4,$D4,$H4 # h4 = d4 + h0*r4 vpaddq $H0,$D0,$H0 # h0 = d0 + h1*s4 vpunpcklqdq $T1,$T0,$T0 # 0:1 vpunpcklqdq $T3,$T2,$T3 # 2:3 #vpsrlq \$40,$T4,$T4 # 4 vpsrldq \$`40/8`,$T4,$T4 # 4 vpsrlq \$26,$T0,$T1 vmovdqa 0x00(%rsp),$D4 # preload r0^2 vpand $MASK,$T0,$T0 # 0 vpsrlq \$4,$T3,$T2 vpand $MASK,$T1,$T1 # 1 vpand 0(%rcx),$T4,$T4 # .Lmask24 vpsrlq \$30,$T3,$T3 vpand $MASK,$T2,$T2 # 2 vpand $MASK,$T3,$T3 # 3 vpor 32(%rcx),$T4,$T4 # padbit, yes, always ################################################################ # lazy reduction as discussed in "NEON crypto" by D.J. Bernstein # and P. Schwabe vpsrlq \$26,$H3,$D3 vpand $MASK,$H3,$H3 vpaddq $D3,$H4,$H4 # h3 -> h4 vpsrlq \$26,$H0,$D0 vpand $MASK,$H0,$H0 vpaddq $D0,$D1,$H1 # h0 -> h1 vpsrlq \$26,$H4,$D0 vpand $MASK,$H4,$H4 vpsrlq \$26,$H1,$D1 vpand $MASK,$H1,$H1 vpaddq $D1,$H2,$H2 # h1 -> h2 vpaddq $D0,$H0,$H0 vpsllq \$2,$D0,$D0 vpaddq $D0,$H0,$H0 # h4 -> h0 vpsrlq \$26,$H2,$D2 vpand $MASK,$H2,$H2 vpaddq $D2,$H3,$H3 # h2 -> h3 vpsrlq \$26,$H0,$D0 vpand $MASK,$H0,$H0 vpaddq $D0,$H1,$H1 # h0 -> h1 vpsrlq \$26,$H3,$D3 vpand $MASK,$H3,$H3 vpaddq $D3,$H4,$H4 # h3 -> h4 ja .Loop_avx .Lskip_loop_avx: ################################################################ # multiply (inp[0:1]+hash) or inp[2:3] by r^2:r^1 vpshufd \$0x10,$D4,$D4 # r0^n, xx12 -> x1x2 add \$32,$len jnz .Long_tail_avx vpaddq $H2,$T2,$T2 vpaddq $H0,$T0,$T0 vpaddq $H1,$T1,$T1 vpaddq $H3,$T3,$T3 vpaddq $H4,$T4,$T4 .Long_tail_avx: vmovdqa $H2,0x20(%r11) vmovdqa $H0,0x00(%r11) vmovdqa $H1,0x10(%r11) vmovdqa $H3,0x30(%r11) vmovdqa $H4,0x40(%r11) # d4 = h4*r0 + h3*r1 + h2*r2 + h1*r3 + h0*r4 # d3 = h3*r0 + h2*r1 + h1*r2 + h0*r3 + h4*5*r4 # d2 = h2*r0 + h1*r1 + h0*r2 + h4*5*r3 + h3*5*r4 # d1 = h1*r0 + h0*r1 + h4*5*r2 + h3*5*r3 + h2*5*r4 # d0 = h0*r0 + h4*5*r1 + h3*5*r2 + h2*5*r3 + h1*5*r4 vpmuludq $T2,$D4,$D2 # d2 = h2*r0 vpmuludq $T0,$D4,$D0 # d0 = h0*r0 vpshufd \$0x10,`16*1-64`($ctx),$H2 # r1^n vpmuludq $T1,$D4,$D1 # d1 = h1*r0 vpmuludq $T3,$D4,$D3 # d3 = h3*r0 vpmuludq $T4,$D4,$D4 # d4 = h4*r0 vpmuludq $T3,$H2,$H0 # h3*r1 vpaddq $H0,$D4,$D4 # d4 += h3*r1 vpshufd \$0x10,`16*2-64`($ctx),$H3 # s1^n vpmuludq $T2,$H2,$H1 # h2*r1 vpaddq $H1,$D3,$D3 # d3 += h2*r1 vpshufd \$0x10,`16*3-64`($ctx),$H4 # r2^n vpmuludq $T1,$H2,$H0 # h1*r1 vpaddq $H0,$D2,$D2 # d2 += h1*r1 vpmuludq $T0,$H2,$H2 # h0*r1 vpaddq $H2,$D1,$D1 # d1 += h0*r1 vpmuludq $T4,$H3,$H3 # h4*s1 vpaddq $H3,$D0,$D0 # d0 += h4*s1 vpshufd \$0x10,`16*4-64`($ctx),$H2 # s2^n vpmuludq $T2,$H4,$H1 # h2*r2 vpaddq $H1,$D4,$D4 # d4 += h2*r2 vpmuludq $T1,$H4,$H0 # h1*r2 vpaddq $H0,$D3,$D3 # d3 += h1*r2 vpshufd \$0x10,`16*5-64`($ctx),$H3 # r3^n vpmuludq $T0,$H4,$H4 # h0*r2 vpaddq $H4,$D2,$D2 # d2 += h0*r2 vpmuludq $T4,$H2,$H1 # h4*s2 vpaddq $H1,$D1,$D1 # d1 += h4*s2 vpshufd \$0x10,`16*6-64`($ctx),$H4 # s3^n vpmuludq $T3,$H2,$H2 # h3*s2 vpaddq $H2,$D0,$D0 # d0 += h3*s2 vpmuludq $T1,$H3,$H0 # h1*r3 vpaddq $H0,$D4,$D4 # d4 += h1*r3 vpmuludq $T0,$H3,$H3 # h0*r3 vpaddq $H3,$D3,$D3 # d3 += h0*r3 vpshufd \$0x10,`16*7-64`($ctx),$H2 # r4^n vpmuludq $T4,$H4,$H1 # h4*s3 vpaddq $H1,$D2,$D2 # d2 += h4*s3 vpshufd \$0x10,`16*8-64`($ctx),$H3 # s4^n vpmuludq $T3,$H4,$H0 # h3*s3 vpaddq $H0,$D1,$D1 # d1 += h3*s3 vpmuludq $T2,$H4,$H4 # h2*s3 vpaddq $H4,$D0,$D0 # d0 += h2*s3 vpmuludq $T0,$H2,$H2 # h0*r4 vpaddq $H2,$D4,$D4 # h4 = d4 + h0*r4 vpmuludq $T4,$H3,$H1 # h4*s4 vpaddq $H1,$D3,$D3 # h3 = d3 + h4*s4 vpmuludq $T3,$H3,$H0 # h3*s4 vpaddq $H0,$D2,$D2 # h2 = d2 + h3*s4 vpmuludq $T2,$H3,$H1 # h2*s4 vpaddq $H1,$D1,$D1 # h1 = d1 + h2*s4 vpmuludq $T1,$H3,$H3 # h1*s4 vpaddq $H3,$D0,$D0 # h0 = d0 + h1*s4 jz .Lshort_tail_avx vmovdqu 16*0($inp),$H0 # load input vmovdqu 16*1($inp),$H1 vpsrldq \$6,$H0,$H2 # splat input vpsrldq \$6,$H1,$H3 vpunpckhqdq $H1,$H0,$H4 # 4 vpunpcklqdq $H1,$H0,$H0 # 0:1 vpunpcklqdq $H3,$H2,$H3 # 2:3 vpsrlq \$40,$H4,$H4 # 4 vpsrlq \$26,$H0,$H1 vpand $MASK,$H0,$H0 # 0 vpsrlq \$4,$H3,$H2 vpand $MASK,$H1,$H1 # 1 vpsrlq \$30,$H3,$H3 vpand $MASK,$H2,$H2 # 2 vpand $MASK,$H3,$H3 # 3 vpor 32(%rcx),$H4,$H4 # padbit, yes, always vpshufd \$0x32,`16*0-64`($ctx),$T4 # r0^n, 34xx -> x3x4 vpaddq 0x00(%r11),$H0,$H0 vpaddq 0x10(%r11),$H1,$H1 vpaddq 0x20(%r11),$H2,$H2 vpaddq 0x30(%r11),$H3,$H3 vpaddq 0x40(%r11),$H4,$H4 ################################################################ # multiply (inp[0:1]+hash) by r^4:r^3 and accumulate vpmuludq $H0,$T4,$T0 # h0*r0 vpaddq $T0,$D0,$D0 # d0 += h0*r0 vpmuludq $H1,$T4,$T1 # h1*r0 vpaddq $T1,$D1,$D1 # d1 += h1*r0 vpmuludq $H2,$T4,$T0 # h2*r0 vpaddq $T0,$D2,$D2 # d2 += h2*r0 vpshufd \$0x32,`16*1-64`($ctx),$T2 # r1^n vpmuludq $H3,$T4,$T1 # h3*r0 vpaddq $T1,$D3,$D3 # d3 += h3*r0 vpmuludq $H4,$T4,$T4 # h4*r0 vpaddq $T4,$D4,$D4 # d4 += h4*r0 vpmuludq $H3,$T2,$T0 # h3*r1 vpaddq $T0,$D4,$D4 # d4 += h3*r1 vpshufd \$0x32,`16*2-64`($ctx),$T3 # s1 vpmuludq $H2,$T2,$T1 # h2*r1 vpaddq $T1,$D3,$D3 # d3 += h2*r1 vpshufd \$0x32,`16*3-64`($ctx),$T4 # r2 vpmuludq $H1,$T2,$T0 # h1*r1 vpaddq $T0,$D2,$D2 # d2 += h1*r1 vpmuludq $H0,$T2,$T2 # h0*r1 vpaddq $T2,$D1,$D1 # d1 += h0*r1 vpmuludq $H4,$T3,$T3 # h4*s1 vpaddq $T3,$D0,$D0 # d0 += h4*s1 vpshufd \$0x32,`16*4-64`($ctx),$T2 # s2 vpmuludq $H2,$T4,$T1 # h2*r2 vpaddq $T1,$D4,$D4 # d4 += h2*r2 vpmuludq $H1,$T4,$T0 # h1*r2 vpaddq $T0,$D3,$D3 # d3 += h1*r2 vpshufd \$0x32,`16*5-64`($ctx),$T3 # r3 vpmuludq $H0,$T4,$T4 # h0*r2 vpaddq $T4,$D2,$D2 # d2 += h0*r2 vpmuludq $H4,$T2,$T1 # h4*s2 vpaddq $T1,$D1,$D1 # d1 += h4*s2 vpshufd \$0x32,`16*6-64`($ctx),$T4 # s3 vpmuludq $H3,$T2,$T2 # h3*s2 vpaddq $T2,$D0,$D0 # d0 += h3*s2 vpmuludq $H1,$T3,$T0 # h1*r3 vpaddq $T0,$D4,$D4 # d4 += h1*r3 vpmuludq $H0,$T3,$T3 # h0*r3 vpaddq $T3,$D3,$D3 # d3 += h0*r3 vpshufd \$0x32,`16*7-64`($ctx),$T2 # r4 vpmuludq $H4,$T4,$T1 # h4*s3 vpaddq $T1,$D2,$D2 # d2 += h4*s3 vpshufd \$0x32,`16*8-64`($ctx),$T3 # s4 vpmuludq $H3,$T4,$T0 # h3*s3 vpaddq $T0,$D1,$D1 # d1 += h3*s3 vpmuludq $H2,$T4,$T4 # h2*s3 vpaddq $T4,$D0,$D0 # d0 += h2*s3 vpmuludq $H0,$T2,$T2 # h0*r4 vpaddq $T2,$D4,$D4 # d4 += h0*r4 vpmuludq $H4,$T3,$T1 # h4*s4 vpaddq $T1,$D3,$D3 # d3 += h4*s4 vpmuludq $H3,$T3,$T0 # h3*s4 vpaddq $T0,$D2,$D2 # d2 += h3*s4 vpmuludq $H2,$T3,$T1 # h2*s4 vpaddq $T1,$D1,$D1 # d1 += h2*s4 vpmuludq $H1,$T3,$T3 # h1*s4 vpaddq $T3,$D0,$D0 # d0 += h1*s4 .Lshort_tail_avx: ################################################################ # horizontal addition vpsrldq \$8,$D4,$T4 vpsrldq \$8,$D3,$T3 vpsrldq \$8,$D1,$T1 vpsrldq \$8,$D0,$T0 vpsrldq \$8,$D2,$T2 vpaddq $T3,$D3,$D3 vpaddq $T4,$D4,$D4 vpaddq $T0,$D0,$D0 vpaddq $T1,$D1,$D1 vpaddq $T2,$D2,$D2 ################################################################ # lazy reduction vpsrlq \$26,$D3,$H3 vpand $MASK,$D3,$D3 vpaddq $H3,$D4,$D4 # h3 -> h4 vpsrlq \$26,$D0,$H0 vpand $MASK,$D0,$D0 vpaddq $H0,$D1,$D1 # h0 -> h1 vpsrlq \$26,$D4,$H4 vpand $MASK,$D4,$D4 vpsrlq \$26,$D1,$H1 vpand $MASK,$D1,$D1 vpaddq $H1,$D2,$D2 # h1 -> h2 vpaddq $H4,$D0,$D0 vpsllq \$2,$H4,$H4 vpaddq $H4,$D0,$D0 # h4 -> h0 vpsrlq \$26,$D2,$H2 vpand $MASK,$D2,$D2 vpaddq $H2,$D3,$D3 # h2 -> h3 vpsrlq \$26,$D0,$H0 vpand $MASK,$D0,$D0 vpaddq $H0,$D1,$D1 # h0 -> h1 vpsrlq \$26,$D3,$H3 vpand $MASK,$D3,$D3 vpaddq $H3,$D4,$D4 # h3 -> h4 vmovd $D0,`4*0-48-64`($ctx) # save partially reduced vmovd $D1,`4*1-48-64`($ctx) vmovd $D2,`4*2-48-64`($ctx) vmovd $D3,`4*3-48-64`($ctx) vmovd $D4,`4*4-48-64`($ctx) ___ $code.=<<___ if ($win64); vmovdqa 0x50(%r11),%xmm6 vmovdqa 0x60(%r11),%xmm7 vmovdqa 0x70(%r11),%xmm8 vmovdqa 0x80(%r11),%xmm9 vmovdqa 0x90(%r11),%xmm10 vmovdqa 0xa0(%r11),%xmm11 vmovdqa 0xb0(%r11),%xmm12 vmovdqa 0xc0(%r11),%xmm13 vmovdqa 0xd0(%r11),%xmm14 vmovdqa 0xe0(%r11),%xmm15 lea 0xf8(%r11),%rsp .Ldo_avx_epilogue: ___ $code.=<<___ if (!$win64); lea 0x58(%r11),%rsp .cfi_def_cfa %rsp,8 ___ $code.=<<___; vzeroupper ret .cfi_endproc .size poly1305_blocks_avx,.-poly1305_blocks_avx .type poly1305_emit_avx,\@function,3 .align 32 poly1305_emit_avx: .cfi_startproc cmpl \$0,20($ctx) # is_base2_26? je .Lemit mov 0($ctx),%eax # load hash value base 2^26 mov 4($ctx),%ecx mov 8($ctx),%r8d mov 12($ctx),%r11d mov 16($ctx),%r10d shl \$26,%rcx # base 2^26 -> base 2^64 mov %r8,%r9 shl \$52,%r8 add %rcx,%rax shr \$12,%r9 add %rax,%r8 # h0 adc \$0,%r9 shl \$14,%r11 mov %r10,%rax shr \$24,%r10 add %r11,%r9 shl \$40,%rax add %rax,%r9 # h1 adc \$0,%r10 # h2 mov %r10,%rax # could be partially reduced, so reduce mov %r10,%rcx and \$3,%r10 shr \$2,%rax and \$-4,%rcx add %rcx,%rax add %rax,%r8 adc \$0,%r9 adc \$0,%r10 mov %r8,%rax add \$5,%r8 # compare to modulus mov %r9,%rcx adc \$0,%r9 adc \$0,%r10 shr \$2,%r10 # did 130-bit value overflow? cmovnz %r8,%rax cmovnz %r9,%rcx add 0($nonce),%rax # accumulate nonce adc 8($nonce),%rcx mov %rax,0($mac) # write result mov %rcx,8($mac) ret .cfi_endproc .size poly1305_emit_avx,.-poly1305_emit_avx ___ if ($avx>1) { my ($H0,$H1,$H2,$H3,$H4, $MASK, $T4,$T0,$T1,$T2,$T3, $D0,$D1,$D2,$D3,$D4) = map("%ymm$_",(0..15)); my $S4=$MASK; $code.=<<___; .type poly1305_blocks_avx2,\@function,4 .align 32 poly1305_blocks_avx2: .cfi_startproc mov 20($ctx),%r8d # is_base2_26 cmp \$128,$len jae .Lblocks_avx2 test %r8d,%r8d jz .Lblocks .Lblocks_avx2: and \$-16,$len jz .Lno_data_avx2 vzeroupper test %r8d,%r8d jz .Lbase2_64_avx2 test \$63,$len jz .Leven_avx2 push %rbx .cfi_push %rbx push %rbp .cfi_push %rbp push %r12 .cfi_push %r12 push %r13 .cfi_push %r13 push %r14 .cfi_push %r14 push %r15 .cfi_push %r15 .Lblocks_avx2_body: mov $len,%r15 # reassign $len mov 0($ctx),$d1 # load hash value mov 8($ctx),$d2 mov 16($ctx),$h2#d mov 24($ctx),$r0 # load r mov 32($ctx),$s1 ################################# base 2^26 -> base 2^64 mov $d1#d,$h0#d and \$`-1*(1<<31)`,$d1 mov $d2,$r1 # borrow $r1 mov $d2#d,$h1#d and \$`-1*(1<<31)`,$d2 shr \$6,$d1 shl \$52,$r1 add $d1,$h0 shr \$12,$h1 shr \$18,$d2 add $r1,$h0 adc $d2,$h1 mov $h2,$d1 shl \$40,$d1 shr \$24,$h2 add $d1,$h1 adc \$0,$h2 # can be partially reduced... mov \$-4,$d2 # ... so reduce mov $h2,$d1 and $h2,$d2 shr \$2,$d1 and \$3,$h2 add $d2,$d1 # =*5 add $d1,$h0 adc \$0,$h1 adc \$0,$h2 mov $s1,$r1 mov $s1,%rax shr \$2,$s1 add $r1,$s1 # s1 = r1 + (r1 >> 2) .Lbase2_26_pre_avx2: add 0($inp),$h0 # accumulate input adc 8($inp),$h1 lea 16($inp),$inp adc $padbit,$h2 sub \$16,%r15 call __poly1305_block mov $r1,%rax test \$63,%r15 jnz .Lbase2_26_pre_avx2 test $padbit,$padbit # if $padbit is zero, jz .Lstore_base2_64_avx2 # store hash in base 2^64 format ################################# base 2^64 -> base 2^26 mov $h0,%rax mov $h0,%rdx shr \$52,$h0 mov $h1,$r0 mov $h1,$r1 shr \$26,%rdx and \$0x3ffffff,%rax # h[0] shl \$12,$r0 and \$0x3ffffff,%rdx # h[1] shr \$14,$h1 or $r0,$h0 shl \$24,$h2 and \$0x3ffffff,$h0 # h[2] shr \$40,$r1 and \$0x3ffffff,$h1 # h[3] or $r1,$h2 # h[4] test %r15,%r15 jz .Lstore_base2_26_avx2 vmovd %rax#d,%x#$H0 vmovd %rdx#d,%x#$H1 vmovd $h0#d,%x#$H2 vmovd $h1#d,%x#$H3 vmovd $h2#d,%x#$H4 jmp .Lproceed_avx2 .align 32 .Lstore_base2_64_avx2: mov $h0,0($ctx) mov $h1,8($ctx) mov $h2,16($ctx) # note that is_base2_26 is zeroed jmp .Ldone_avx2 .align 16 .Lstore_base2_26_avx2: mov %rax#d,0($ctx) # store hash value base 2^26 mov %rdx#d,4($ctx) mov $h0#d,8($ctx) mov $h1#d,12($ctx) mov $h2#d,16($ctx) .align 16 .Ldone_avx2: mov 0(%rsp),%r15 .cfi_restore %r15 mov 8(%rsp),%r14 .cfi_restore %r14 mov 16(%rsp),%r13 .cfi_restore %r13 mov 24(%rsp),%r12 .cfi_restore %r12 mov 32(%rsp),%rbp .cfi_restore %rbp mov 40(%rsp),%rbx .cfi_restore %rbx lea 48(%rsp),%rsp .cfi_adjust_cfa_offset -48 .Lno_data_avx2: .Lblocks_avx2_epilogue: ret .cfi_endproc .align 32 .Lbase2_64_avx2: .cfi_startproc push %rbx .cfi_push %rbx push %rbp .cfi_push %rbp push %r12 .cfi_push %r12 push %r13 .cfi_push %r13 push %r14 .cfi_push %r14 push %r15 .cfi_push %r15 .Lbase2_64_avx2_body: mov $len,%r15 # reassign $len mov 24($ctx),$r0 # load r mov 32($ctx),$s1 mov 0($ctx),$h0 # load hash value mov 8($ctx),$h1 mov 16($ctx),$h2#d mov $s1,$r1 mov $s1,%rax shr \$2,$s1 add $r1,$s1 # s1 = r1 + (r1 >> 2) test \$63,$len jz .Linit_avx2 .Lbase2_64_pre_avx2: add 0($inp),$h0 # accumulate input adc 8($inp),$h1 lea 16($inp),$inp adc $padbit,$h2 sub \$16,%r15 call __poly1305_block mov $r1,%rax test \$63,%r15 jnz .Lbase2_64_pre_avx2 .Linit_avx2: ################################# base 2^64 -> base 2^26 mov $h0,%rax mov $h0,%rdx shr \$52,$h0 mov $h1,$d1 mov $h1,$d2 shr \$26,%rdx and \$0x3ffffff,%rax # h[0] shl \$12,$d1 and \$0x3ffffff,%rdx # h[1] shr \$14,$h1 or $d1,$h0 shl \$24,$h2 and \$0x3ffffff,$h0 # h[2] shr \$40,$d2 and \$0x3ffffff,$h1 # h[3] or $d2,$h2 # h[4] vmovd %rax#d,%x#$H0 vmovd %rdx#d,%x#$H1 vmovd $h0#d,%x#$H2 vmovd $h1#d,%x#$H3 vmovd $h2#d,%x#$H4 movl \$1,20($ctx) # set is_base2_26 call __poly1305_init_avx .Lproceed_avx2: mov %r15,$len # restore $len mov OPENSSL_ia32cap_P+8(%rip),%r10d mov \$`(1<<31|1<<30|1<<16)`,%r11d mov 0(%rsp),%r15 .cfi_restore %r15 mov 8(%rsp),%r14 .cfi_restore %r14 mov 16(%rsp),%r13 .cfi_restore %r13 mov 24(%rsp),%r12 .cfi_restore %r12 mov 32(%rsp),%rbp .cfi_restore %rbp mov 40(%rsp),%rbx .cfi_restore %rbx lea 48(%rsp),%rax lea 48(%rsp),%rsp .cfi_adjust_cfa_offset -48 .Lbase2_64_avx2_epilogue: jmp .Ldo_avx2 .cfi_endproc .align 32 .Leven_avx2: .cfi_startproc mov OPENSSL_ia32cap_P+8(%rip),%r10d vmovd 4*0($ctx),%x#$H0 # load hash value base 2^26 vmovd 4*1($ctx),%x#$H1 vmovd 4*2($ctx),%x#$H2 vmovd 4*3($ctx),%x#$H3 vmovd 4*4($ctx),%x#$H4 .Ldo_avx2: ___ $code.=<<___ if ($avx>2); cmp \$512,$len jb .Lskip_avx512 and %r11d,%r10d test \$`1<<16`,%r10d # check for AVX512F jnz .Lblocks_avx512 .Lskip_avx512: ___ $code.=<<___ if (!$win64); lea -8(%rsp),%r11 .cfi_def_cfa %r11,16 sub \$0x128,%rsp ___ $code.=<<___ if ($win64); lea -0xf8(%rsp),%r11 sub \$0x1c8,%rsp vmovdqa %xmm6,0x50(%r11) vmovdqa %xmm7,0x60(%r11) vmovdqa %xmm8,0x70(%r11) vmovdqa %xmm9,0x80(%r11) vmovdqa %xmm10,0x90(%r11) vmovdqa %xmm11,0xa0(%r11) vmovdqa %xmm12,0xb0(%r11) vmovdqa %xmm13,0xc0(%r11) vmovdqa %xmm14,0xd0(%r11) vmovdqa %xmm15,0xe0(%r11) .Ldo_avx2_body: ___ $code.=<<___; lea .Lconst(%rip),%rcx lea 48+64($ctx),$ctx # size optimization vmovdqa 96(%rcx),$T0 # .Lpermd_avx2 # expand and copy pre-calculated table to stack vmovdqu `16*0-64`($ctx),%x#$T2 and \$-512,%rsp vmovdqu `16*1-64`($ctx),%x#$T3 vmovdqu `16*2-64`($ctx),%x#$T4 vmovdqu `16*3-64`($ctx),%x#$D0 vmovdqu `16*4-64`($ctx),%x#$D1 vmovdqu `16*5-64`($ctx),%x#$D2 lea 0x90(%rsp),%rax # size optimization vmovdqu `16*6-64`($ctx),%x#$D3 vpermd $T2,$T0,$T2 # 00003412 -> 14243444 vmovdqu `16*7-64`($ctx),%x#$D4 vpermd $T3,$T0,$T3 vmovdqu `16*8-64`($ctx),%x#$MASK vpermd $T4,$T0,$T4 vmovdqa $T2,0x00(%rsp) vpermd $D0,$T0,$D0 vmovdqa $T3,0x20-0x90(%rax) vpermd $D1,$T0,$D1 vmovdqa $T4,0x40-0x90(%rax) vpermd $D2,$T0,$D2 vmovdqa $D0,0x60-0x90(%rax) vpermd $D3,$T0,$D3 vmovdqa $D1,0x80-0x90(%rax) vpermd $D4,$T0,$D4 vmovdqa $D2,0xa0-0x90(%rax) vpermd $MASK,$T0,$MASK vmovdqa $D3,0xc0-0x90(%rax) vmovdqa $D4,0xe0-0x90(%rax) vmovdqa $MASK,0x100-0x90(%rax) vmovdqa 64(%rcx),$MASK # .Lmask26 ################################################################ # load input vmovdqu 16*0($inp),%x#$T0 vmovdqu 16*1($inp),%x#$T1 vinserti128 \$1,16*2($inp),$T0,$T0 vinserti128 \$1,16*3($inp),$T1,$T1 lea 16*4($inp),$inp vpsrldq \$6,$T0,$T2 # splat input vpsrldq \$6,$T1,$T3 vpunpckhqdq $T1,$T0,$T4 # 4 vpunpcklqdq $T3,$T2,$T2 # 2:3 vpunpcklqdq $T1,$T0,$T0 # 0:1 vpsrlq \$30,$T2,$T3 vpsrlq \$4,$T2,$T2 vpsrlq \$26,$T0,$T1 vpsrlq \$40,$T4,$T4 # 4 vpand $MASK,$T2,$T2 # 2 vpand $MASK,$T0,$T0 # 0 vpand $MASK,$T1,$T1 # 1 vpand $MASK,$T3,$T3 # 3 vpor 32(%rcx),$T4,$T4 # padbit, yes, always vpaddq $H2,$T2,$H2 # accumulate input sub \$64,$len jz .Ltail_avx2 jmp .Loop_avx2 .align 32 .Loop_avx2: ################################################################ # ((inp[0]*r^4+inp[4])*r^4+inp[ 8])*r^4 # ((inp[1]*r^4+inp[5])*r^4+inp[ 9])*r^3 # ((inp[2]*r^4+inp[6])*r^4+inp[10])*r^2 # ((inp[3]*r^4+inp[7])*r^4+inp[11])*r^1 # \________/\__________/ ################################################################ #vpaddq $H2,$T2,$H2 # accumulate input vpaddq $H0,$T0,$H0 vmovdqa `32*0`(%rsp),$T0 # r0^4 vpaddq $H1,$T1,$H1 vmovdqa `32*1`(%rsp),$T1 # r1^4 vpaddq $H3,$T3,$H3 vmovdqa `32*3`(%rsp),$T2 # r2^4 vpaddq $H4,$T4,$H4 vmovdqa `32*6-0x90`(%rax),$T3 # s3^4 vmovdqa `32*8-0x90`(%rax),$S4 # s4^4 # d4 = h4*r0 + h3*r1 + h2*r2 + h1*r3 + h0*r4 # d3 = h3*r0 + h2*r1 + h1*r2 + h0*r3 + h4*5*r4 # d2 = h2*r0 + h1*r1 + h0*r2 + h4*5*r3 + h3*5*r4 # d1 = h1*r0 + h0*r1 + h4*5*r2 + h3*5*r3 + h2*5*r4 # d0 = h0*r0 + h4*5*r1 + h3*5*r2 + h2*5*r3 + h1*5*r4 # # however, as h2 is "chronologically" first one available pull # corresponding operations up, so it's # # d4 = h2*r2 + h4*r0 + h3*r1 + h1*r3 + h0*r4 # d3 = h2*r1 + h3*r0 + h1*r2 + h0*r3 + h4*5*r4 # d2 = h2*r0 + h1*r1 + h0*r2 + h4*5*r3 + h3*5*r4 # d1 = h2*5*r4 + h1*r0 + h0*r1 + h4*5*r2 + h3*5*r3 # d0 = h2*5*r3 + h0*r0 + h4*5*r1 + h3*5*r2 + h1*5*r4 vpmuludq $H2,$T0,$D2 # d2 = h2*r0 vpmuludq $H2,$T1,$D3 # d3 = h2*r1 vpmuludq $H2,$T2,$D4 # d4 = h2*r2 vpmuludq $H2,$T3,$D0 # d0 = h2*s3 vpmuludq $H2,$S4,$D1 # d1 = h2*s4 vpmuludq $H0,$T1,$T4 # h0*r1 vpmuludq $H1,$T1,$H2 # h1*r1, borrow $H2 as temp vpaddq $T4,$D1,$D1 # d1 += h0*r1 vpaddq $H2,$D2,$D2 # d2 += h1*r1 vpmuludq $H3,$T1,$T4 # h3*r1 vpmuludq `32*2`(%rsp),$H4,$H2 # h4*s1 vpaddq $T4,$D4,$D4 # d4 += h3*r1 vpaddq $H2,$D0,$D0 # d0 += h4*s1 vmovdqa `32*4-0x90`(%rax),$T1 # s2 vpmuludq $H0,$T0,$T4 # h0*r0 vpmuludq $H1,$T0,$H2 # h1*r0 vpaddq $T4,$D0,$D0 # d0 += h0*r0 vpaddq $H2,$D1,$D1 # d1 += h1*r0 vpmuludq $H3,$T0,$T4 # h3*r0 vpmuludq $H4,$T0,$H2 # h4*r0 vmovdqu 16*0($inp),%x#$T0 # load input vpaddq $T4,$D3,$D3 # d3 += h3*r0 vpaddq $H2,$D4,$D4 # d4 += h4*r0 vinserti128 \$1,16*2($inp),$T0,$T0 vpmuludq $H3,$T1,$T4 # h3*s2 vpmuludq $H4,$T1,$H2 # h4*s2 vmovdqu 16*1($inp),%x#$T1 vpaddq $T4,$D0,$D0 # d0 += h3*s2 vpaddq $H2,$D1,$D1 # d1 += h4*s2 vmovdqa `32*5-0x90`(%rax),$H2 # r3 vpmuludq $H1,$T2,$T4 # h1*r2 vpmuludq $H0,$T2,$T2 # h0*r2 vpaddq $T4,$D3,$D3 # d3 += h1*r2 vpaddq $T2,$D2,$D2 # d2 += h0*r2 vinserti128 \$1,16*3($inp),$T1,$T1 lea 16*4($inp),$inp vpmuludq $H1,$H2,$T4 # h1*r3 vpmuludq $H0,$H2,$H2 # h0*r3 vpsrldq \$6,$T0,$T2 # splat input vpaddq $T4,$D4,$D4 # d4 += h1*r3 vpaddq $H2,$D3,$D3 # d3 += h0*r3 vpmuludq $H3,$T3,$T4 # h3*s3 vpmuludq $H4,$T3,$H2 # h4*s3 vpsrldq \$6,$T1,$T3 vpaddq $T4,$D1,$D1 # d1 += h3*s3 vpaddq $H2,$D2,$D2 # d2 += h4*s3 vpunpckhqdq $T1,$T0,$T4 # 4 vpmuludq $H3,$S4,$H3 # h3*s4 vpmuludq $H4,$S4,$H4 # h4*s4 vpunpcklqdq $T1,$T0,$T0 # 0:1 vpaddq $H3,$D2,$H2 # h2 = d2 + h3*r4 vpaddq $H4,$D3,$H3 # h3 = d3 + h4*r4 vpunpcklqdq $T3,$T2,$T3 # 2:3 vpmuludq `32*7-0x90`(%rax),$H0,$H4 # h0*r4 vpmuludq $H1,$S4,$H0 # h1*s4 vmovdqa 64(%rcx),$MASK # .Lmask26 vpaddq $H4,$D4,$H4 # h4 = d4 + h0*r4 vpaddq $H0,$D0,$H0 # h0 = d0 + h1*s4 ################################################################ # lazy reduction (interleaved with tail of input splat) vpsrlq \$26,$H3,$D3 vpand $MASK,$H3,$H3 vpaddq $D3,$H4,$H4 # h3 -> h4 vpsrlq \$26,$H0,$D0 vpand $MASK,$H0,$H0 vpaddq $D0,$D1,$H1 # h0 -> h1 vpsrlq \$26,$H4,$D4 vpand $MASK,$H4,$H4 vpsrlq \$4,$T3,$T2 vpsrlq \$26,$H1,$D1 vpand $MASK,$H1,$H1 vpaddq $D1,$H2,$H2 # h1 -> h2 vpaddq $D4,$H0,$H0 vpsllq \$2,$D4,$D4 vpaddq $D4,$H0,$H0 # h4 -> h0 vpand $MASK,$T2,$T2 # 2 vpsrlq \$26,$T0,$T1 vpsrlq \$26,$H2,$D2 vpand $MASK,$H2,$H2 vpaddq $D2,$H3,$H3 # h2 -> h3 vpaddq $T2,$H2,$H2 # modulo-scheduled vpsrlq \$30,$T3,$T3 vpsrlq \$26,$H0,$D0 vpand $MASK,$H0,$H0 vpaddq $D0,$H1,$H1 # h0 -> h1 vpsrlq \$40,$T4,$T4 # 4 vpsrlq \$26,$H3,$D3 vpand $MASK,$H3,$H3 vpaddq $D3,$H4,$H4 # h3 -> h4 vpand $MASK,$T0,$T0 # 0 vpand $MASK,$T1,$T1 # 1 vpand $MASK,$T3,$T3 # 3 vpor 32(%rcx),$T4,$T4 # padbit, yes, always sub \$64,$len jnz .Loop_avx2 .byte 0x66,0x90 .Ltail_avx2: ################################################################ # while above multiplications were by r^4 in all lanes, in last # iteration we multiply least significant lane by r^4 and most # significant one by r, so copy of above except that references # to the precomputed table are displaced by 4... #vpaddq $H2,$T2,$H2 # accumulate input vpaddq $H0,$T0,$H0 vmovdqu `32*0+4`(%rsp),$T0 # r0^4 vpaddq $H1,$T1,$H1 vmovdqu `32*1+4`(%rsp),$T1 # r1^4 vpaddq $H3,$T3,$H3 vmovdqu `32*3+4`(%rsp),$T2 # r2^4 vpaddq $H4,$T4,$H4 vmovdqu `32*6+4-0x90`(%rax),$T3 # s3^4 vmovdqu `32*8+4-0x90`(%rax),$S4 # s4^4 vpmuludq $H2,$T0,$D2 # d2 = h2*r0 vpmuludq $H2,$T1,$D3 # d3 = h2*r1 vpmuludq $H2,$T2,$D4 # d4 = h2*r2 vpmuludq $H2,$T3,$D0 # d0 = h2*s3 vpmuludq $H2,$S4,$D1 # d1 = h2*s4 vpmuludq $H0,$T1,$T4 # h0*r1 vpmuludq $H1,$T1,$H2 # h1*r1 vpaddq $T4,$D1,$D1 # d1 += h0*r1 vpaddq $H2,$D2,$D2 # d2 += h1*r1 vpmuludq $H3,$T1,$T4 # h3*r1 vpmuludq `32*2+4`(%rsp),$H4,$H2 # h4*s1 vpaddq $T4,$D4,$D4 # d4 += h3*r1 vpaddq $H2,$D0,$D0 # d0 += h4*s1 vpmuludq $H0,$T0,$T4 # h0*r0 vpmuludq $H1,$T0,$H2 # h1*r0 vpaddq $T4,$D0,$D0 # d0 += h0*r0 vmovdqu `32*4+4-0x90`(%rax),$T1 # s2 vpaddq $H2,$D1,$D1 # d1 += h1*r0 vpmuludq $H3,$T0,$T4 # h3*r0 vpmuludq $H4,$T0,$H2 # h4*r0 vpaddq $T4,$D3,$D3 # d3 += h3*r0 vpaddq $H2,$D4,$D4 # d4 += h4*r0 vpmuludq $H3,$T1,$T4 # h3*s2 vpmuludq $H4,$T1,$H2 # h4*s2 vpaddq $T4,$D0,$D0 # d0 += h3*s2 vpaddq $H2,$D1,$D1 # d1 += h4*s2 vmovdqu `32*5+4-0x90`(%rax),$H2 # r3 vpmuludq $H1,$T2,$T4 # h1*r2 vpmuludq $H0,$T2,$T2 # h0*r2 vpaddq $T4,$D3,$D3 # d3 += h1*r2 vpaddq $T2,$D2,$D2 # d2 += h0*r2 vpmuludq $H1,$H2,$T4 # h1*r3 vpmuludq $H0,$H2,$H2 # h0*r3 vpaddq $T4,$D4,$D4 # d4 += h1*r3 vpaddq $H2,$D3,$D3 # d3 += h0*r3 vpmuludq $H3,$T3,$T4 # h3*s3 vpmuludq $H4,$T3,$H2 # h4*s3 vpaddq $T4,$D1,$D1 # d1 += h3*s3 vpaddq $H2,$D2,$D2 # d2 += h4*s3 vpmuludq $H3,$S4,$H3 # h3*s4 vpmuludq $H4,$S4,$H4 # h4*s4 vpaddq $H3,$D2,$H2 # h2 = d2 + h3*r4 vpaddq $H4,$D3,$H3 # h3 = d3 + h4*r4 vpmuludq `32*7+4-0x90`(%rax),$H0,$H4 # h0*r4 vpmuludq $H1,$S4,$H0 # h1*s4 vmovdqa 64(%rcx),$MASK # .Lmask26 vpaddq $H4,$D4,$H4 # h4 = d4 + h0*r4 vpaddq $H0,$D0,$H0 # h0 = d0 + h1*s4 ################################################################ # horizontal addition vpsrldq \$8,$D1,$T1 vpsrldq \$8,$H2,$T2 vpsrldq \$8,$H3,$T3 vpsrldq \$8,$H4,$T4 vpsrldq \$8,$H0,$T0 vpaddq $T1,$D1,$D1 vpaddq $T2,$H2,$H2 vpaddq $T3,$H3,$H3 vpaddq $T4,$H4,$H4 vpaddq $T0,$H0,$H0 vpermq \$0x2,$H3,$T3 vpermq \$0x2,$H4,$T4 vpermq \$0x2,$H0,$T0 vpermq \$0x2,$D1,$T1 vpermq \$0x2,$H2,$T2 vpaddq $T3,$H3,$H3 vpaddq $T4,$H4,$H4 vpaddq $T0,$H0,$H0 vpaddq $T1,$D1,$D1 vpaddq $T2,$H2,$H2 ################################################################ # lazy reduction vpsrlq \$26,$H3,$D3 vpand $MASK,$H3,$H3 vpaddq $D3,$H4,$H4 # h3 -> h4 vpsrlq \$26,$H0,$D0 vpand $MASK,$H0,$H0 vpaddq $D0,$D1,$H1 # h0 -> h1 vpsrlq \$26,$H4,$D4 vpand $MASK,$H4,$H4 vpsrlq \$26,$H1,$D1 vpand $MASK,$H1,$H1 vpaddq $D1,$H2,$H2 # h1 -> h2 vpaddq $D4,$H0,$H0 vpsllq \$2,$D4,$D4 vpaddq $D4,$H0,$H0 # h4 -> h0 vpsrlq \$26,$H2,$D2 vpand $MASK,$H2,$H2 vpaddq $D2,$H3,$H3 # h2 -> h3 vpsrlq \$26,$H0,$D0 vpand $MASK,$H0,$H0 vpaddq $D0,$H1,$H1 # h0 -> h1 vpsrlq \$26,$H3,$D3 vpand $MASK,$H3,$H3 vpaddq $D3,$H4,$H4 # h3 -> h4 vmovd %x#$H0,`4*0-48-64`($ctx)# save partially reduced vmovd %x#$H1,`4*1-48-64`($ctx) vmovd %x#$H2,`4*2-48-64`($ctx) vmovd %x#$H3,`4*3-48-64`($ctx) vmovd %x#$H4,`4*4-48-64`($ctx) ___ $code.=<<___ if ($win64); vmovdqa 0x50(%r11),%xmm6 vmovdqa 0x60(%r11),%xmm7 vmovdqa 0x70(%r11),%xmm8 vmovdqa 0x80(%r11),%xmm9 vmovdqa 0x90(%r11),%xmm10 vmovdqa 0xa0(%r11),%xmm11 vmovdqa 0xb0(%r11),%xmm12 vmovdqa 0xc0(%r11),%xmm13 vmovdqa 0xd0(%r11),%xmm14 vmovdqa 0xe0(%r11),%xmm15 lea 0xf8(%r11),%rsp .Ldo_avx2_epilogue: ___ $code.=<<___ if (!$win64); lea 8(%r11),%rsp .cfi_def_cfa %rsp,8 ___ $code.=<<___; vzeroupper ret .cfi_endproc .size poly1305_blocks_avx2,.-poly1305_blocks_avx2 ___ ####################################################################### if ($avx>2) { # On entry we have input length divisible by 64. But since inner loop # processes 128 bytes per iteration, cases when length is not divisible # by 128 are handled by passing tail 64 bytes to .Ltail_avx2. For this # reason stack layout is kept identical to poly1305_blocks_avx2. If not # for this tail, we wouldn't have to even allocate stack frame... my ($R0,$R1,$R2,$R3,$R4, $S1,$S2,$S3,$S4) = map("%zmm$_",(16..24)); my ($M0,$M1,$M2,$M3,$M4) = map("%zmm$_",(25..29)); my $PADBIT="%zmm30"; map(s/%y/%z/,($T4,$T0,$T1,$T2,$T3)); # switch to %zmm domain map(s/%y/%z/,($D0,$D1,$D2,$D3,$D4)); map(s/%y/%z/,($H0,$H1,$H2,$H3,$H4)); map(s/%y/%z/,($MASK)); $code.=<<___; .type poly1305_blocks_avx512,\@function,4 .align 32 poly1305_blocks_avx512: .cfi_startproc .Lblocks_avx512: mov \$15,%eax kmovw %eax,%k2 ___ $code.=<<___ if (!$win64); lea -8(%rsp),%r11 .cfi_def_cfa %r11,16 sub \$0x128,%rsp ___ $code.=<<___ if ($win64); lea -0xf8(%rsp),%r11 sub \$0x1c8,%rsp vmovdqa %xmm6,0x50(%r11) vmovdqa %xmm7,0x60(%r11) vmovdqa %xmm8,0x70(%r11) vmovdqa %xmm9,0x80(%r11) vmovdqa %xmm10,0x90(%r11) vmovdqa %xmm11,0xa0(%r11) vmovdqa %xmm12,0xb0(%r11) vmovdqa %xmm13,0xc0(%r11) vmovdqa %xmm14,0xd0(%r11) vmovdqa %xmm15,0xe0(%r11) .Ldo_avx512_body: ___ $code.=<<___; lea .Lconst(%rip),%rcx lea 48+64($ctx),$ctx # size optimization vmovdqa 96(%rcx),%y#$T2 # .Lpermd_avx2 # expand pre-calculated table vmovdqu `16*0-64`($ctx),%x#$D0 # will become expanded ${R0} and \$-512,%rsp vmovdqu `16*1-64`($ctx),%x#$D1 # will become ... ${R1} mov \$0x20,%rax vmovdqu `16*2-64`($ctx),%x#$T0 # ... ${S1} vmovdqu `16*3-64`($ctx),%x#$D2 # ... ${R2} vmovdqu `16*4-64`($ctx),%x#$T1 # ... ${S2} vmovdqu `16*5-64`($ctx),%x#$D3 # ... ${R3} vmovdqu `16*6-64`($ctx),%x#$T3 # ... ${S3} vmovdqu `16*7-64`($ctx),%x#$D4 # ... ${R4} vmovdqu `16*8-64`($ctx),%x#$T4 # ... ${S4} vpermd $D0,$T2,$R0 # 00003412 -> 14243444 vpbroadcastq 64(%rcx),$MASK # .Lmask26 vpermd $D1,$T2,$R1 vpermd $T0,$T2,$S1 vpermd $D2,$T2,$R2 vmovdqa64 $R0,0x00(%rsp){%k2} # save in case $len%128 != 0 vpsrlq \$32,$R0,$T0 # 14243444 -> 01020304 vpermd $T1,$T2,$S2 vmovdqu64 $R1,0x00(%rsp,%rax){%k2} vpsrlq \$32,$R1,$T1 vpermd $D3,$T2,$R3 vmovdqa64 $S1,0x40(%rsp){%k2} vpermd $T3,$T2,$S3 vpermd $D4,$T2,$R4 vmovdqu64 $R2,0x40(%rsp,%rax){%k2} vpermd $T4,$T2,$S4 vmovdqa64 $S2,0x80(%rsp){%k2} vmovdqu64 $R3,0x80(%rsp,%rax){%k2} vmovdqa64 $S3,0xc0(%rsp){%k2} vmovdqu64 $R4,0xc0(%rsp,%rax){%k2} vmovdqa64 $S4,0x100(%rsp){%k2} ################################################################ # calculate 5th through 8th powers of the key # # d0 = r0'*r0 + r1'*5*r4 + r2'*5*r3 + r3'*5*r2 + r4'*5*r1 # d1 = r0'*r1 + r1'*r0 + r2'*5*r4 + r3'*5*r3 + r4'*5*r2 # d2 = r0'*r2 + r1'*r1 + r2'*r0 + r3'*5*r4 + r4'*5*r3 # d3 = r0'*r3 + r1'*r2 + r2'*r1 + r3'*r0 + r4'*5*r4 # d4 = r0'*r4 + r1'*r3 + r2'*r2 + r3'*r1 + r4'*r0 vpmuludq $T0,$R0,$D0 # d0 = r0'*r0 vpmuludq $T0,$R1,$D1 # d1 = r0'*r1 vpmuludq $T0,$R2,$D2 # d2 = r0'*r2 vpmuludq $T0,$R3,$D3 # d3 = r0'*r3 vpmuludq $T0,$R4,$D4 # d4 = r0'*r4 vpsrlq \$32,$R2,$T2 vpmuludq $T1,$S4,$M0 vpmuludq $T1,$R0,$M1 vpmuludq $T1,$R1,$M2 vpmuludq $T1,$R2,$M3 vpmuludq $T1,$R3,$M4 vpsrlq \$32,$R3,$T3 vpaddq $M0,$D0,$D0 # d0 += r1'*5*r4 vpaddq $M1,$D1,$D1 # d1 += r1'*r0 vpaddq $M2,$D2,$D2 # d2 += r1'*r1 vpaddq $M3,$D3,$D3 # d3 += r1'*r2 vpaddq $M4,$D4,$D4 # d4 += r1'*r3 vpmuludq $T2,$S3,$M0 vpmuludq $T2,$S4,$M1 vpmuludq $T2,$R1,$M3 vpmuludq $T2,$R2,$M4 vpmuludq $T2,$R0,$M2 vpsrlq \$32,$R4,$T4 vpaddq $M0,$D0,$D0 # d0 += r2'*5*r3 vpaddq $M1,$D1,$D1 # d1 += r2'*5*r4 vpaddq $M3,$D3,$D3 # d3 += r2'*r1 vpaddq $M4,$D4,$D4 # d4 += r2'*r2 vpaddq $M2,$D2,$D2 # d2 += r2'*r0 vpmuludq $T3,$S2,$M0 vpmuludq $T3,$R0,$M3 vpmuludq $T3,$R1,$M4 vpmuludq $T3,$S3,$M1 vpmuludq $T3,$S4,$M2 vpaddq $M0,$D0,$D0 # d0 += r3'*5*r2 vpaddq $M3,$D3,$D3 # d3 += r3'*r0 vpaddq $M4,$D4,$D4 # d4 += r3'*r1 vpaddq $M1,$D1,$D1 # d1 += r3'*5*r3 vpaddq $M2,$D2,$D2 # d2 += r3'*5*r4 vpmuludq $T4,$S4,$M3 vpmuludq $T4,$R0,$M4 vpmuludq $T4,$S1,$M0 vpmuludq $T4,$S2,$M1 vpmuludq $T4,$S3,$M2 vpaddq $M3,$D3,$D3 # d3 += r2'*5*r4 vpaddq $M4,$D4,$D4 # d4 += r2'*r0 vpaddq $M0,$D0,$D0 # d0 += r2'*5*r1 vpaddq $M1,$D1,$D1 # d1 += r2'*5*r2 vpaddq $M2,$D2,$D2 # d2 += r2'*5*r3 ################################################################ # load input vmovdqu64 16*0($inp),%z#$T3 vmovdqu64 16*4($inp),%z#$T4 lea 16*8($inp),$inp ################################################################ # lazy reduction vpsrlq \$26,$D3,$M3 vpandq $MASK,$D3,$D3 vpaddq $M3,$D4,$D4 # d3 -> d4 vpsrlq \$26,$D0,$M0 vpandq $MASK,$D0,$D0 vpaddq $M0,$D1,$D1 # d0 -> d1 vpsrlq \$26,$D4,$M4 vpandq $MASK,$D4,$D4 vpsrlq \$26,$D1,$M1 vpandq $MASK,$D1,$D1 vpaddq $M1,$D2,$D2 # d1 -> d2 vpaddq $M4,$D0,$D0 vpsllq \$2,$M4,$M4 vpaddq $M4,$D0,$D0 # d4 -> d0 vpsrlq \$26,$D2,$M2 vpandq $MASK,$D2,$D2 vpaddq $M2,$D3,$D3 # d2 -> d3 vpsrlq \$26,$D0,$M0 vpandq $MASK,$D0,$D0 vpaddq $M0,$D1,$D1 # d0 -> d1 vpsrlq \$26,$D3,$M3 vpandq $MASK,$D3,$D3 vpaddq $M3,$D4,$D4 # d3 -> d4 ################################################################ # at this point we have 14243444 in $R0-$S4 and 05060708 in # $D0-$D4, ... vpunpcklqdq $T4,$T3,$T0 # transpose input vpunpckhqdq $T4,$T3,$T4 # ... since input 64-bit lanes are ordered as 73625140, we could # "vperm" it to 76543210 (here and in each loop iteration), *or* # we could just flow along, hence the goal for $R0-$S4 is # 1858286838784888 ... vmovdqa32 128(%rcx),$M0 # .Lpermd_avx512: mov \$0x7777,%eax kmovw %eax,%k1 vpermd $R0,$M0,$R0 # 14243444 -> 1---2---3---4--- vpermd $R1,$M0,$R1 vpermd $R2,$M0,$R2 vpermd $R3,$M0,$R3 vpermd $R4,$M0,$R4 vpermd $D0,$M0,${R0}{%k1} # 05060708 -> 1858286838784888 vpermd $D1,$M0,${R1}{%k1} vpermd $D2,$M0,${R2}{%k1} vpermd $D3,$M0,${R3}{%k1} vpermd $D4,$M0,${R4}{%k1} vpslld \$2,$R1,$S1 # *5 vpslld \$2,$R2,$S2 vpslld \$2,$R3,$S3 vpslld \$2,$R4,$S4 vpaddd $R1,$S1,$S1 vpaddd $R2,$S2,$S2 vpaddd $R3,$S3,$S3 vpaddd $R4,$S4,$S4 vpbroadcastq 32(%rcx),$PADBIT # .L129 vpsrlq \$52,$T0,$T2 # splat input vpsllq \$12,$T4,$T3 vporq $T3,$T2,$T2 vpsrlq \$26,$T0,$T1 vpsrlq \$14,$T4,$T3 vpsrlq \$40,$T4,$T4 # 4 vpandq $MASK,$T2,$T2 # 2 vpandq $MASK,$T0,$T0 # 0 #vpandq $MASK,$T1,$T1 # 1 #vpandq $MASK,$T3,$T3 # 3 #vporq $PADBIT,$T4,$T4 # padbit, yes, always vpaddq $H2,$T2,$H2 # accumulate input sub \$192,$len jbe .Ltail_avx512 jmp .Loop_avx512 .align 32 .Loop_avx512: ################################################################ # ((inp[0]*r^8+inp[ 8])*r^8+inp[16])*r^8 # ((inp[1]*r^8+inp[ 9])*r^8+inp[17])*r^7 # ((inp[2]*r^8+inp[10])*r^8+inp[18])*r^6 # ((inp[3]*r^8+inp[11])*r^8+inp[19])*r^5 # ((inp[4]*r^8+inp[12])*r^8+inp[20])*r^4 # ((inp[5]*r^8+inp[13])*r^8+inp[21])*r^3 # ((inp[6]*r^8+inp[14])*r^8+inp[22])*r^2 # ((inp[7]*r^8+inp[15])*r^8+inp[23])*r^1 # \________/\___________/ ################################################################ #vpaddq $H2,$T2,$H2 # accumulate input # d4 = h4*r0 + h3*r1 + h2*r2 + h1*r3 + h0*r4 # d3 = h3*r0 + h2*r1 + h1*r2 + h0*r3 + h4*5*r4 # d2 = h2*r0 + h1*r1 + h0*r2 + h4*5*r3 + h3*5*r4 # d1 = h1*r0 + h0*r1 + h4*5*r2 + h3*5*r3 + h2*5*r4 # d0 = h0*r0 + h4*5*r1 + h3*5*r2 + h2*5*r3 + h1*5*r4 # # however, as h2 is "chronologically" first one available pull # corresponding operations up, so it's # # d3 = h2*r1 + h0*r3 + h1*r2 + h3*r0 + h4*5*r4 # d4 = h2*r2 + h0*r4 + h1*r3 + h3*r1 + h4*r0 # d0 = h2*5*r3 + h0*r0 + h1*5*r4 + h3*5*r2 + h4*5*r1 # d1 = h2*5*r4 + h0*r1 + h1*r0 + h3*5*r3 + h4*5*r2 # d2 = h2*r0 + h0*r2 + h1*r1 + h3*5*r4 + h4*5*r3 vpmuludq $H2,$R1,$D3 # d3 = h2*r1 vpaddq $H0,$T0,$H0 vpmuludq $H2,$R2,$D4 # d4 = h2*r2 vpandq $MASK,$T1,$T1 # 1 vpmuludq $H2,$S3,$D0 # d0 = h2*s3 vpandq $MASK,$T3,$T3 # 3 vpmuludq $H2,$S4,$D1 # d1 = h2*s4 vporq $PADBIT,$T4,$T4 # padbit, yes, always vpmuludq $H2,$R0,$D2 # d2 = h2*r0 vpaddq $H1,$T1,$H1 # accumulate input vpaddq $H3,$T3,$H3 vpaddq $H4,$T4,$H4 vmovdqu64 16*0($inp),$T3 # load input vmovdqu64 16*4($inp),$T4 lea 16*8($inp),$inp vpmuludq $H0,$R3,$M3 vpmuludq $H0,$R4,$M4 vpmuludq $H0,$R0,$M0 vpmuludq $H0,$R1,$M1 vpaddq $M3,$D3,$D3 # d3 += h0*r3 vpaddq $M4,$D4,$D4 # d4 += h0*r4 vpaddq $M0,$D0,$D0 # d0 += h0*r0 vpaddq $M1,$D1,$D1 # d1 += h0*r1 vpmuludq $H1,$R2,$M3 vpmuludq $H1,$R3,$M4 vpmuludq $H1,$S4,$M0 vpmuludq $H0,$R2,$M2 vpaddq $M3,$D3,$D3 # d3 += h1*r2 vpaddq $M4,$D4,$D4 # d4 += h1*r3 vpaddq $M0,$D0,$D0 # d0 += h1*s4 vpaddq $M2,$D2,$D2 # d2 += h0*r2 vpunpcklqdq $T4,$T3,$T0 # transpose input vpunpckhqdq $T4,$T3,$T4 vpmuludq $H3,$R0,$M3 vpmuludq $H3,$R1,$M4 vpmuludq $H1,$R0,$M1 vpmuludq $H1,$R1,$M2 vpaddq $M3,$D3,$D3 # d3 += h3*r0 vpaddq $M4,$D4,$D4 # d4 += h3*r1 vpaddq $M1,$D1,$D1 # d1 += h1*r0 vpaddq $M2,$D2,$D2 # d2 += h1*r1 vpmuludq $H4,$S4,$M3 vpmuludq $H4,$R0,$M4 vpmuludq $H3,$S2,$M0 vpmuludq $H3,$S3,$M1 vpaddq $M3,$D3,$D3 # d3 += h4*s4 vpmuludq $H3,$S4,$M2 vpaddq $M4,$D4,$D4 # d4 += h4*r0 vpaddq $M0,$D0,$D0 # d0 += h3*s2 vpaddq $M1,$D1,$D1 # d1 += h3*s3 vpaddq $M2,$D2,$D2 # d2 += h3*s4 vpmuludq $H4,$S1,$M0 vpmuludq $H4,$S2,$M1 vpmuludq $H4,$S3,$M2 vpaddq $M0,$D0,$H0 # h0 = d0 + h4*s1 vpaddq $M1,$D1,$H1 # h1 = d2 + h4*s2 vpaddq $M2,$D2,$H2 # h2 = d3 + h4*s3 ################################################################ # lazy reduction (interleaved with input splat) vpsrlq \$52,$T0,$T2 # splat input vpsllq \$12,$T4,$T3 vpsrlq \$26,$D3,$H3 vpandq $MASK,$D3,$D3 vpaddq $H3,$D4,$H4 # h3 -> h4 vporq $T3,$T2,$T2 vpsrlq \$26,$H0,$D0 vpandq $MASK,$H0,$H0 vpaddq $D0,$H1,$H1 # h0 -> h1 vpandq $MASK,$T2,$T2 # 2 vpsrlq \$26,$H4,$D4 vpandq $MASK,$H4,$H4 vpsrlq \$26,$H1,$D1 vpandq $MASK,$H1,$H1 vpaddq $D1,$H2,$H2 # h1 -> h2 vpaddq $D4,$H0,$H0 vpsllq \$2,$D4,$D4 vpaddq $D4,$H0,$H0 # h4 -> h0 vpaddq $T2,$H2,$H2 # modulo-scheduled vpsrlq \$26,$T0,$T1 vpsrlq \$26,$H2,$D2 vpandq $MASK,$H2,$H2 vpaddq $D2,$D3,$H3 # h2 -> h3 vpsrlq \$14,$T4,$T3 vpsrlq \$26,$H0,$D0 vpandq $MASK,$H0,$H0 vpaddq $D0,$H1,$H1 # h0 -> h1 vpsrlq \$40,$T4,$T4 # 4 vpsrlq \$26,$H3,$D3 vpandq $MASK,$H3,$H3 vpaddq $D3,$H4,$H4 # h3 -> h4 vpandq $MASK,$T0,$T0 # 0 #vpandq $MASK,$T1,$T1 # 1 #vpandq $MASK,$T3,$T3 # 3 #vporq $PADBIT,$T4,$T4 # padbit, yes, always sub \$128,$len ja .Loop_avx512 .Ltail_avx512: ################################################################ # while above multiplications were by r^8 in all lanes, in last # iteration we multiply least significant lane by r^8 and most # significant one by r, that's why table gets shifted... vpsrlq \$32,$R0,$R0 # 0105020603070408 vpsrlq \$32,$R1,$R1 vpsrlq \$32,$R2,$R2 vpsrlq \$32,$S3,$S3 vpsrlq \$32,$S4,$S4 vpsrlq \$32,$R3,$R3 vpsrlq \$32,$R4,$R4 vpsrlq \$32,$S1,$S1 vpsrlq \$32,$S2,$S2 ################################################################ # load either next or last 64 byte of input lea ($inp,$len),$inp #vpaddq $H2,$T2,$H2 # accumulate input vpaddq $H0,$T0,$H0 vpmuludq $H2,$R1,$D3 # d3 = h2*r1 vpmuludq $H2,$R2,$D4 # d4 = h2*r2 vpmuludq $H2,$S3,$D0 # d0 = h2*s3 vpandq $MASK,$T1,$T1 # 1 vpmuludq $H2,$S4,$D1 # d1 = h2*s4 vpandq $MASK,$T3,$T3 # 3 vpmuludq $H2,$R0,$D2 # d2 = h2*r0 vporq $PADBIT,$T4,$T4 # padbit, yes, always vpaddq $H1,$T1,$H1 # accumulate input vpaddq $H3,$T3,$H3 vpaddq $H4,$T4,$H4 vmovdqu 16*0($inp),%x#$T0 vpmuludq $H0,$R3,$M3 vpmuludq $H0,$R4,$M4 vpmuludq $H0,$R0,$M0 vpmuludq $H0,$R1,$M1 vpaddq $M3,$D3,$D3 # d3 += h0*r3 vpaddq $M4,$D4,$D4 # d4 += h0*r4 vpaddq $M0,$D0,$D0 # d0 += h0*r0 vpaddq $M1,$D1,$D1 # d1 += h0*r1 vmovdqu 16*1($inp),%x#$T1 vpmuludq $H1,$R2,$M3 vpmuludq $H1,$R3,$M4 vpmuludq $H1,$S4,$M0 vpmuludq $H0,$R2,$M2 vpaddq $M3,$D3,$D3 # d3 += h1*r2 vpaddq $M4,$D4,$D4 # d4 += h1*r3 vpaddq $M0,$D0,$D0 # d0 += h1*s4 vpaddq $M2,$D2,$D2 # d2 += h0*r2 vinserti128 \$1,16*2($inp),%y#$T0,%y#$T0 vpmuludq $H3,$R0,$M3 vpmuludq $H3,$R1,$M4 vpmuludq $H1,$R0,$M1 vpmuludq $H1,$R1,$M2 vpaddq $M3,$D3,$D3 # d3 += h3*r0 vpaddq $M4,$D4,$D4 # d4 += h3*r1 vpaddq $M1,$D1,$D1 # d1 += h1*r0 vpaddq $M2,$D2,$D2 # d2 += h1*r1 vinserti128 \$1,16*3($inp),%y#$T1,%y#$T1 vpmuludq $H4,$S4,$M3 vpmuludq $H4,$R0,$M4 vpmuludq $H3,$S2,$M0 vpmuludq $H3,$S3,$M1 vpmuludq $H3,$S4,$M2 vpaddq $M3,$D3,$H3 # h3 = d3 + h4*s4 vpaddq $M4,$D4,$D4 # d4 += h4*r0 vpaddq $M0,$D0,$D0 # d0 += h3*s2 vpaddq $M1,$D1,$D1 # d1 += h3*s3 vpaddq $M2,$D2,$D2 # d2 += h3*s4 vpmuludq $H4,$S1,$M0 vpmuludq $H4,$S2,$M1 vpmuludq $H4,$S3,$M2 vpaddq $M0,$D0,$H0 # h0 = d0 + h4*s1 vpaddq $M1,$D1,$H1 # h1 = d2 + h4*s2 vpaddq $M2,$D2,$H2 # h2 = d3 + h4*s3 ################################################################ # horizontal addition mov \$1,%eax vpermq \$0xb1,$H3,$D3 vpermq \$0xb1,$D4,$H4 vpermq \$0xb1,$H0,$D0 vpermq \$0xb1,$H1,$D1 vpermq \$0xb1,$H2,$D2 vpaddq $D3,$H3,$H3 vpaddq $D4,$H4,$H4 vpaddq $D0,$H0,$H0 vpaddq $D1,$H1,$H1 vpaddq $D2,$H2,$H2 kmovw %eax,%k3 vpermq \$0x2,$H3,$D3 vpermq \$0x2,$H4,$D4 vpermq \$0x2,$H0,$D0 vpermq \$0x2,$H1,$D1 vpermq \$0x2,$H2,$D2 vpaddq $D3,$H3,$H3 vpaddq $D4,$H4,$H4 vpaddq $D0,$H0,$H0 vpaddq $D1,$H1,$H1 vpaddq $D2,$H2,$H2 vextracti64x4 \$0x1,$H3,%y#$D3 vextracti64x4 \$0x1,$H4,%y#$D4 vextracti64x4 \$0x1,$H0,%y#$D0 vextracti64x4 \$0x1,$H1,%y#$D1 vextracti64x4 \$0x1,$H2,%y#$D2 vpaddq $D3,$H3,${H3}{%k3}{z} # keep single qword in case vpaddq $D4,$H4,${H4}{%k3}{z} # it's passed to .Ltail_avx2 vpaddq $D0,$H0,${H0}{%k3}{z} vpaddq $D1,$H1,${H1}{%k3}{z} vpaddq $D2,$H2,${H2}{%k3}{z} ___ map(s/%z/%y/,($T0,$T1,$T2,$T3,$T4, $PADBIT)); map(s/%z/%y/,($H0,$H1,$H2,$H3,$H4, $D0,$D1,$D2,$D3,$D4, $MASK)); $code.=<<___; ################################################################ # lazy reduction (interleaved with input splat) vpsrlq \$26,$H3,$D3 vpand $MASK,$H3,$H3 vpsrldq \$6,$T0,$T2 # splat input vpsrldq \$6,$T1,$T3 vpunpckhqdq $T1,$T0,$T4 # 4 vpaddq $D3,$H4,$H4 # h3 -> h4 vpsrlq \$26,$H0,$D0 vpand $MASK,$H0,$H0 vpunpcklqdq $T3,$T2,$T2 # 2:3 vpunpcklqdq $T1,$T0,$T0 # 0:1 vpaddq $D0,$H1,$H1 # h0 -> h1 vpsrlq \$26,$H4,$D4 vpand $MASK,$H4,$H4 vpsrlq \$26,$H1,$D1 vpand $MASK,$H1,$H1 vpsrlq \$30,$T2,$T3 vpsrlq \$4,$T2,$T2 vpaddq $D1,$H2,$H2 # h1 -> h2 vpaddq $D4,$H0,$H0 vpsllq \$2,$D4,$D4 vpsrlq \$26,$T0,$T1 vpsrlq \$40,$T4,$T4 # 4 vpaddq $D4,$H0,$H0 # h4 -> h0 vpsrlq \$26,$H2,$D2 vpand $MASK,$H2,$H2 vpand $MASK,$T2,$T2 # 2 vpand $MASK,$T0,$T0 # 0 vpaddq $D2,$H3,$H3 # h2 -> h3 vpsrlq \$26,$H0,$D0 vpand $MASK,$H0,$H0 vpaddq $H2,$T2,$H2 # accumulate input for .Ltail_avx2 vpand $MASK,$T1,$T1 # 1 vpaddq $D0,$H1,$H1 # h0 -> h1 vpsrlq \$26,$H3,$D3 vpand $MASK,$H3,$H3 vpand $MASK,$T3,$T3 # 3 vpor 32(%rcx),$T4,$T4 # padbit, yes, always vpaddq $D3,$H4,$H4 # h3 -> h4 lea 0x90(%rsp),%rax # size optimization for .Ltail_avx2 add \$64,$len jnz .Ltail_avx2 vpsubq $T2,$H2,$H2 # undo input accumulation vmovd %x#$H0,`4*0-48-64`($ctx)# save partially reduced vmovd %x#$H1,`4*1-48-64`($ctx) vmovd %x#$H2,`4*2-48-64`($ctx) vmovd %x#$H3,`4*3-48-64`($ctx) vmovd %x#$H4,`4*4-48-64`($ctx) vzeroall ___ $code.=<<___ if ($win64); movdqa 0x50(%r11),%xmm6 movdqa 0x60(%r11),%xmm7 movdqa 0x70(%r11),%xmm8 movdqa 0x80(%r11),%xmm9 movdqa 0x90(%r11),%xmm10 movdqa 0xa0(%r11),%xmm11 movdqa 0xb0(%r11),%xmm12 movdqa 0xc0(%r11),%xmm13 movdqa 0xd0(%r11),%xmm14 movdqa 0xe0(%r11),%xmm15 lea 0xf8(%r11),%rsp .Ldo_avx512_epilogue: ___ $code.=<<___ if (!$win64); lea 8(%r11),%rsp .cfi_def_cfa %rsp,8 ___ $code.=<<___; ret .cfi_endproc .size poly1305_blocks_avx512,.-poly1305_blocks_avx512 ___ -if ($avx>3) { +if ($avx>3 && !$win64) { ######################################################################## # VPMADD52 version using 2^44 radix. # # One can argue that base 2^52 would be more natural. Well, even though # some operations would be more natural, one has to recognize couple of # things. Base 2^52 doesn't provide advantage over base 2^44 if you look # at amount of multiply-n-accumulate operations. Secondly, it makes it # impossible to pre-compute multiples of 5 [referred to as s[]/sN in # reference implementations], which means that more such operations # would have to be performed in inner loop, which in turn makes critical # path longer. In other words, even though base 2^44 reduction might # look less elegant, overall critical path is actually shorter... ######################################################################## # Layout of opaque area is following. # # unsigned __int64 h[3]; # current hash value base 2^44 # unsigned __int64 s[2]; # key value*20 base 2^44 # unsigned __int64 r[3]; # key value base 2^44 # struct { unsigned __int64 r^1, r^3, r^2, r^4; } R[4]; # # r^n positions reflect # # placement in register, not # # memory, R[3] is R[1]*20 $code.=<<___; .type poly1305_init_base2_44,\@function,3 .align 32 poly1305_init_base2_44: .cfi_startproc xor %rax,%rax mov %rax,0($ctx) # initialize hash value mov %rax,8($ctx) mov %rax,16($ctx) .Linit_base2_44: lea poly1305_blocks_vpmadd52(%rip),%r10 lea poly1305_emit_base2_44(%rip),%r11 mov \$0x0ffffffc0fffffff,%rax mov \$0x0ffffffc0ffffffc,%rcx and 0($inp),%rax mov \$0x00000fffffffffff,%r8 and 8($inp),%rcx mov \$0x00000fffffffffff,%r9 and %rax,%r8 shrd \$44,%rcx,%rax mov %r8,40($ctx) # r0 and %r9,%rax shr \$24,%rcx mov %rax,48($ctx) # r1 lea (%rax,%rax,4),%rax # *5 mov %rcx,56($ctx) # r2 shl \$2,%rax # magic <<2 lea (%rcx,%rcx,4),%rcx # *5 shl \$2,%rcx # magic <<2 mov %rax,24($ctx) # s1 mov %rcx,32($ctx) # s2 movq \$-1,64($ctx) # write impossible value ___ $code.=<<___ if ($flavour !~ /elf32/); mov %r10,0(%rdx) mov %r11,8(%rdx) ___ $code.=<<___ if ($flavour =~ /elf32/); mov %r10d,0(%rdx) mov %r11d,4(%rdx) ___ $code.=<<___; mov \$1,%eax ret .cfi_endproc .size poly1305_init_base2_44,.-poly1305_init_base2_44 ___ { my ($H0,$H1,$H2,$r2r1r0,$r1r0s2,$r0s2s1,$Dlo,$Dhi) = map("%ymm$_",(0..5,16,17)); my ($T0,$inp_permd,$inp_shift,$PAD) = map("%ymm$_",(18..21)); my ($reduc_mask,$reduc_rght,$reduc_left) = map("%ymm$_",(22..25)); $code.=<<___; .type poly1305_blocks_vpmadd52,\@function,4 .align 32 poly1305_blocks_vpmadd52: .cfi_startproc endbranch shr \$4,$len jz .Lno_data_vpmadd52 # too short shl \$40,$padbit mov 64($ctx),%r8 # peek on power of the key # if powers of the key are not calculated yet, process up to 3 # blocks with this single-block subroutine, otherwise ensure that # length is divisible by 2 blocks and pass the rest down to next # subroutine... mov \$3,%rax mov \$1,%r10 cmp \$4,$len # is input long cmovae %r10,%rax test %r8,%r8 # is power value impossible? cmovns %r10,%rax and $len,%rax # is input of favourable length? jz .Lblocks_vpmadd52_4x sub %rax,$len mov \$7,%r10d mov \$1,%r11d kmovw %r10d,%k7 lea .L2_44_inp_permd(%rip),%r10 kmovw %r11d,%k1 vmovq $padbit,%x#$PAD vmovdqa64 0(%r10),$inp_permd # .L2_44_inp_permd vmovdqa64 32(%r10),$inp_shift # .L2_44_inp_shift vpermq \$0xcf,$PAD,$PAD vmovdqa64 64(%r10),$reduc_mask # .L2_44_mask vmovdqu64 0($ctx),${Dlo}{%k7}{z} # load hash value vmovdqu64 40($ctx),${r2r1r0}{%k7}{z} # load keys vmovdqu64 32($ctx),${r1r0s2}{%k7}{z} vmovdqu64 24($ctx),${r0s2s1}{%k7}{z} vmovdqa64 96(%r10),$reduc_rght # .L2_44_shift_rgt vmovdqa64 128(%r10),$reduc_left # .L2_44_shift_lft jmp .Loop_vpmadd52 .align 32 .Loop_vpmadd52: vmovdqu32 0($inp),%x#$T0 # load input as ----3210 lea 16($inp),$inp vpermd $T0,$inp_permd,$T0 # ----3210 -> --322110 vpsrlvq $inp_shift,$T0,$T0 vpandq $reduc_mask,$T0,$T0 vporq $PAD,$T0,$T0 vpaddq $T0,$Dlo,$Dlo # accumulate input vpermq \$0,$Dlo,${H0}{%k7}{z} # smash hash value vpermq \$0b01010101,$Dlo,${H1}{%k7}{z} vpermq \$0b10101010,$Dlo,${H2}{%k7}{z} vpxord $Dlo,$Dlo,$Dlo vpxord $Dhi,$Dhi,$Dhi vpmadd52luq $r2r1r0,$H0,$Dlo vpmadd52huq $r2r1r0,$H0,$Dhi vpmadd52luq $r1r0s2,$H1,$Dlo vpmadd52huq $r1r0s2,$H1,$Dhi vpmadd52luq $r0s2s1,$H2,$Dlo vpmadd52huq $r0s2s1,$H2,$Dhi vpsrlvq $reduc_rght,$Dlo,$T0 # 0 in topmost qword vpsllvq $reduc_left,$Dhi,$Dhi # 0 in topmost qword vpandq $reduc_mask,$Dlo,$Dlo vpaddq $T0,$Dhi,$Dhi vpermq \$0b10010011,$Dhi,$Dhi # 0 in lowest qword vpaddq $Dhi,$Dlo,$Dlo # note topmost qword :-) vpsrlvq $reduc_rght,$Dlo,$T0 # 0 in topmost word vpandq $reduc_mask,$Dlo,$Dlo vpermq \$0b10010011,$T0,$T0 vpaddq $T0,$Dlo,$Dlo vpermq \$0b10010011,$Dlo,${T0}{%k1}{z} vpaddq $T0,$Dlo,$Dlo vpsllq \$2,$T0,$T0 vpaddq $T0,$Dlo,$Dlo dec %rax # len-=16 jnz .Loop_vpmadd52 vmovdqu64 $Dlo,0($ctx){%k7} # store hash value test $len,$len jnz .Lblocks_vpmadd52_4x .Lno_data_vpmadd52: ret .cfi_endproc .size poly1305_blocks_vpmadd52,.-poly1305_blocks_vpmadd52 ___ } { ######################################################################## # As implied by its name 4x subroutine processes 4 blocks in parallel # (but handles even 4*n+2 blocks lengths). It takes up to 4th key power # and is handled in 256-bit %ymm registers. my ($H0,$H1,$H2,$R0,$R1,$R2,$S1,$S2) = map("%ymm$_",(0..5,16,17)); my ($D0lo,$D0hi,$D1lo,$D1hi,$D2lo,$D2hi) = map("%ymm$_",(18..23)); my ($T0,$T1,$T2,$T3,$mask44,$mask42,$tmp,$PAD) = map("%ymm$_",(24..31)); $code.=<<___; .type poly1305_blocks_vpmadd52_4x,\@function,4 .align 32 poly1305_blocks_vpmadd52_4x: .cfi_startproc shr \$4,$len jz .Lno_data_vpmadd52_4x # too short shl \$40,$padbit mov 64($ctx),%r8 # peek on power of the key .Lblocks_vpmadd52_4x: vpbroadcastq $padbit,$PAD vmovdqa64 .Lx_mask44(%rip),$mask44 mov \$5,%eax vmovdqa64 .Lx_mask42(%rip),$mask42 kmovw %eax,%k1 # used in 2x path test %r8,%r8 # is power value impossible? js .Linit_vpmadd52 # if it is, then init R[4] vmovq 0($ctx),%x#$H0 # load current hash value vmovq 8($ctx),%x#$H1 vmovq 16($ctx),%x#$H2 test \$3,$len # is length 4*n+2? jnz .Lblocks_vpmadd52_2x_do .Lblocks_vpmadd52_4x_do: vpbroadcastq 64($ctx),$R0 # load 4th power of the key vpbroadcastq 96($ctx),$R1 vpbroadcastq 128($ctx),$R2 vpbroadcastq 160($ctx),$S1 .Lblocks_vpmadd52_4x_key_loaded: vpsllq \$2,$R2,$S2 # S2 = R2*5*4 vpaddq $R2,$S2,$S2 vpsllq \$2,$S2,$S2 test \$7,$len # is len 8*n? jz .Lblocks_vpmadd52_8x vmovdqu64 16*0($inp),$T2 # load data vmovdqu64 16*2($inp),$T3 lea 16*4($inp),$inp vpunpcklqdq $T3,$T2,$T1 # transpose data vpunpckhqdq $T3,$T2,$T3 # at this point 64-bit lanes are ordered as 3-1-2-0 vpsrlq \$24,$T3,$T2 # splat the data vporq $PAD,$T2,$T2 vpaddq $T2,$H2,$H2 # accumulate input vpandq $mask44,$T1,$T0 vpsrlq \$44,$T1,$T1 vpsllq \$20,$T3,$T3 vporq $T3,$T1,$T1 vpandq $mask44,$T1,$T1 sub \$4,$len jz .Ltail_vpmadd52_4x jmp .Loop_vpmadd52_4x ud2 .align 32 .Linit_vpmadd52: vmovq 24($ctx),%x#$S1 # load key vmovq 56($ctx),%x#$H2 vmovq 32($ctx),%x#$S2 vmovq 40($ctx),%x#$R0 vmovq 48($ctx),%x#$R1 vmovdqa $R0,$H0 vmovdqa $R1,$H1 vmovdqa $H2,$R2 mov \$2,%eax .Lmul_init_vpmadd52: vpxorq $D0lo,$D0lo,$D0lo vpmadd52luq $H2,$S1,$D0lo vpxorq $D0hi,$D0hi,$D0hi vpmadd52huq $H2,$S1,$D0hi vpxorq $D1lo,$D1lo,$D1lo vpmadd52luq $H2,$S2,$D1lo vpxorq $D1hi,$D1hi,$D1hi vpmadd52huq $H2,$S2,$D1hi vpxorq $D2lo,$D2lo,$D2lo vpmadd52luq $H2,$R0,$D2lo vpxorq $D2hi,$D2hi,$D2hi vpmadd52huq $H2,$R0,$D2hi vpmadd52luq $H0,$R0,$D0lo vpmadd52huq $H0,$R0,$D0hi vpmadd52luq $H0,$R1,$D1lo vpmadd52huq $H0,$R1,$D1hi vpmadd52luq $H0,$R2,$D2lo vpmadd52huq $H0,$R2,$D2hi vpmadd52luq $H1,$S2,$D0lo vpmadd52huq $H1,$S2,$D0hi vpmadd52luq $H1,$R0,$D1lo vpmadd52huq $H1,$R0,$D1hi vpmadd52luq $H1,$R1,$D2lo vpmadd52huq $H1,$R1,$D2hi ################################################################ # partial reduction vpsrlq \$44,$D0lo,$tmp vpsllq \$8,$D0hi,$D0hi vpandq $mask44,$D0lo,$H0 vpaddq $tmp,$D0hi,$D0hi vpaddq $D0hi,$D1lo,$D1lo vpsrlq \$44,$D1lo,$tmp vpsllq \$8,$D1hi,$D1hi vpandq $mask44,$D1lo,$H1 vpaddq $tmp,$D1hi,$D1hi vpaddq $D1hi,$D2lo,$D2lo vpsrlq \$42,$D2lo,$tmp vpsllq \$10,$D2hi,$D2hi vpandq $mask42,$D2lo,$H2 vpaddq $tmp,$D2hi,$D2hi vpaddq $D2hi,$H0,$H0 vpsllq \$2,$D2hi,$D2hi vpaddq $D2hi,$H0,$H0 vpsrlq \$44,$H0,$tmp # additional step vpandq $mask44,$H0,$H0 vpaddq $tmp,$H1,$H1 dec %eax jz .Ldone_init_vpmadd52 vpunpcklqdq $R1,$H1,$R1 # 1,2 vpbroadcastq %x#$H1,%x#$H1 # 2,2 vpunpcklqdq $R2,$H2,$R2 vpbroadcastq %x#$H2,%x#$H2 vpunpcklqdq $R0,$H0,$R0 vpbroadcastq %x#$H0,%x#$H0 vpsllq \$2,$R1,$S1 # S1 = R1*5*4 vpsllq \$2,$R2,$S2 # S2 = R2*5*4 vpaddq $R1,$S1,$S1 vpaddq $R2,$S2,$S2 vpsllq \$2,$S1,$S1 vpsllq \$2,$S2,$S2 jmp .Lmul_init_vpmadd52 ud2 .align 32 .Ldone_init_vpmadd52: vinserti128 \$1,%x#$R1,$H1,$R1 # 1,2,3,4 vinserti128 \$1,%x#$R2,$H2,$R2 vinserti128 \$1,%x#$R0,$H0,$R0 vpermq \$0b11011000,$R1,$R1 # 1,3,2,4 vpermq \$0b11011000,$R2,$R2 vpermq \$0b11011000,$R0,$R0 vpsllq \$2,$R1,$S1 # S1 = R1*5*4 vpaddq $R1,$S1,$S1 vpsllq \$2,$S1,$S1 vmovq 0($ctx),%x#$H0 # load current hash value vmovq 8($ctx),%x#$H1 vmovq 16($ctx),%x#$H2 test \$3,$len # is length 4*n+2? jnz .Ldone_init_vpmadd52_2x vmovdqu64 $R0,64($ctx) # save key powers vpbroadcastq %x#$R0,$R0 # broadcast 4th power vmovdqu64 $R1,96($ctx) vpbroadcastq %x#$R1,$R1 vmovdqu64 $R2,128($ctx) vpbroadcastq %x#$R2,$R2 vmovdqu64 $S1,160($ctx) vpbroadcastq %x#$S1,$S1 jmp .Lblocks_vpmadd52_4x_key_loaded ud2 .align 32 .Ldone_init_vpmadd52_2x: vmovdqu64 $R0,64($ctx) # save key powers vpsrldq \$8,$R0,$R0 # 0-1-0-2 vmovdqu64 $R1,96($ctx) vpsrldq \$8,$R1,$R1 vmovdqu64 $R2,128($ctx) vpsrldq \$8,$R2,$R2 vmovdqu64 $S1,160($ctx) vpsrldq \$8,$S1,$S1 jmp .Lblocks_vpmadd52_2x_key_loaded ud2 .align 32 .Lblocks_vpmadd52_2x_do: vmovdqu64 128+8($ctx),${R2}{%k1}{z}# load 2nd and 1st key powers vmovdqu64 160+8($ctx),${S1}{%k1}{z} vmovdqu64 64+8($ctx),${R0}{%k1}{z} vmovdqu64 96+8($ctx),${R1}{%k1}{z} .Lblocks_vpmadd52_2x_key_loaded: vmovdqu64 16*0($inp),$T2 # load data vpxorq $T3,$T3,$T3 lea 16*2($inp),$inp vpunpcklqdq $T3,$T2,$T1 # transpose data vpunpckhqdq $T3,$T2,$T3 # at this point 64-bit lanes are ordered as x-1-x-0 vpsrlq \$24,$T3,$T2 # splat the data vporq $PAD,$T2,$T2 vpaddq $T2,$H2,$H2 # accumulate input vpandq $mask44,$T1,$T0 vpsrlq \$44,$T1,$T1 vpsllq \$20,$T3,$T3 vporq $T3,$T1,$T1 vpandq $mask44,$T1,$T1 jmp .Ltail_vpmadd52_2x ud2 .align 32 .Loop_vpmadd52_4x: #vpaddq $T2,$H2,$H2 # accumulate input vpaddq $T0,$H0,$H0 vpaddq $T1,$H1,$H1 vpxorq $D0lo,$D0lo,$D0lo vpmadd52luq $H2,$S1,$D0lo vpxorq $D0hi,$D0hi,$D0hi vpmadd52huq $H2,$S1,$D0hi vpxorq $D1lo,$D1lo,$D1lo vpmadd52luq $H2,$S2,$D1lo vpxorq $D1hi,$D1hi,$D1hi vpmadd52huq $H2,$S2,$D1hi vpxorq $D2lo,$D2lo,$D2lo vpmadd52luq $H2,$R0,$D2lo vpxorq $D2hi,$D2hi,$D2hi vpmadd52huq $H2,$R0,$D2hi vmovdqu64 16*0($inp),$T2 # load data vmovdqu64 16*2($inp),$T3 lea 16*4($inp),$inp vpmadd52luq $H0,$R0,$D0lo vpmadd52huq $H0,$R0,$D0hi vpmadd52luq $H0,$R1,$D1lo vpmadd52huq $H0,$R1,$D1hi vpmadd52luq $H0,$R2,$D2lo vpmadd52huq $H0,$R2,$D2hi vpunpcklqdq $T3,$T2,$T1 # transpose data vpunpckhqdq $T3,$T2,$T3 vpmadd52luq $H1,$S2,$D0lo vpmadd52huq $H1,$S2,$D0hi vpmadd52luq $H1,$R0,$D1lo vpmadd52huq $H1,$R0,$D1hi vpmadd52luq $H1,$R1,$D2lo vpmadd52huq $H1,$R1,$D2hi ################################################################ # partial reduction (interleaved with data splat) vpsrlq \$44,$D0lo,$tmp vpsllq \$8,$D0hi,$D0hi vpandq $mask44,$D0lo,$H0 vpaddq $tmp,$D0hi,$D0hi vpsrlq \$24,$T3,$T2 vporq $PAD,$T2,$T2 vpaddq $D0hi,$D1lo,$D1lo vpsrlq \$44,$D1lo,$tmp vpsllq \$8,$D1hi,$D1hi vpandq $mask44,$D1lo,$H1 vpaddq $tmp,$D1hi,$D1hi vpandq $mask44,$T1,$T0 vpsrlq \$44,$T1,$T1 vpsllq \$20,$T3,$T3 vpaddq $D1hi,$D2lo,$D2lo vpsrlq \$42,$D2lo,$tmp vpsllq \$10,$D2hi,$D2hi vpandq $mask42,$D2lo,$H2 vpaddq $tmp,$D2hi,$D2hi vpaddq $T2,$H2,$H2 # accumulate input vpaddq $D2hi,$H0,$H0 vpsllq \$2,$D2hi,$D2hi vpaddq $D2hi,$H0,$H0 vporq $T3,$T1,$T1 vpandq $mask44,$T1,$T1 vpsrlq \$44,$H0,$tmp # additional step vpandq $mask44,$H0,$H0 vpaddq $tmp,$H1,$H1 sub \$4,$len # len-=64 jnz .Loop_vpmadd52_4x .Ltail_vpmadd52_4x: vmovdqu64 128($ctx),$R2 # load all key powers vmovdqu64 160($ctx),$S1 vmovdqu64 64($ctx),$R0 vmovdqu64 96($ctx),$R1 .Ltail_vpmadd52_2x: vpsllq \$2,$R2,$S2 # S2 = R2*5*4 vpaddq $R2,$S2,$S2 vpsllq \$2,$S2,$S2 #vpaddq $T2,$H2,$H2 # accumulate input vpaddq $T0,$H0,$H0 vpaddq $T1,$H1,$H1 vpxorq $D0lo,$D0lo,$D0lo vpmadd52luq $H2,$S1,$D0lo vpxorq $D0hi,$D0hi,$D0hi vpmadd52huq $H2,$S1,$D0hi vpxorq $D1lo,$D1lo,$D1lo vpmadd52luq $H2,$S2,$D1lo vpxorq $D1hi,$D1hi,$D1hi vpmadd52huq $H2,$S2,$D1hi vpxorq $D2lo,$D2lo,$D2lo vpmadd52luq $H2,$R0,$D2lo vpxorq $D2hi,$D2hi,$D2hi vpmadd52huq $H2,$R0,$D2hi vpmadd52luq $H0,$R0,$D0lo vpmadd52huq $H0,$R0,$D0hi vpmadd52luq $H0,$R1,$D1lo vpmadd52huq $H0,$R1,$D1hi vpmadd52luq $H0,$R2,$D2lo vpmadd52huq $H0,$R2,$D2hi vpmadd52luq $H1,$S2,$D0lo vpmadd52huq $H1,$S2,$D0hi vpmadd52luq $H1,$R0,$D1lo vpmadd52huq $H1,$R0,$D1hi vpmadd52luq $H1,$R1,$D2lo vpmadd52huq $H1,$R1,$D2hi ################################################################ # horizontal addition mov \$1,%eax kmovw %eax,%k1 vpsrldq \$8,$D0lo,$T0 vpsrldq \$8,$D0hi,$H0 vpsrldq \$8,$D1lo,$T1 vpsrldq \$8,$D1hi,$H1 vpaddq $T0,$D0lo,$D0lo vpaddq $H0,$D0hi,$D0hi vpsrldq \$8,$D2lo,$T2 vpsrldq \$8,$D2hi,$H2 vpaddq $T1,$D1lo,$D1lo vpaddq $H1,$D1hi,$D1hi vpermq \$0x2,$D0lo,$T0 vpermq \$0x2,$D0hi,$H0 vpaddq $T2,$D2lo,$D2lo vpaddq $H2,$D2hi,$D2hi vpermq \$0x2,$D1lo,$T1 vpermq \$0x2,$D1hi,$H1 vpaddq $T0,$D0lo,${D0lo}{%k1}{z} vpaddq $H0,$D0hi,${D0hi}{%k1}{z} vpermq \$0x2,$D2lo,$T2 vpermq \$0x2,$D2hi,$H2 vpaddq $T1,$D1lo,${D1lo}{%k1}{z} vpaddq $H1,$D1hi,${D1hi}{%k1}{z} vpaddq $T2,$D2lo,${D2lo}{%k1}{z} vpaddq $H2,$D2hi,${D2hi}{%k1}{z} ################################################################ # partial reduction vpsrlq \$44,$D0lo,$tmp vpsllq \$8,$D0hi,$D0hi vpandq $mask44,$D0lo,$H0 vpaddq $tmp,$D0hi,$D0hi vpaddq $D0hi,$D1lo,$D1lo vpsrlq \$44,$D1lo,$tmp vpsllq \$8,$D1hi,$D1hi vpandq $mask44,$D1lo,$H1 vpaddq $tmp,$D1hi,$D1hi vpaddq $D1hi,$D2lo,$D2lo vpsrlq \$42,$D2lo,$tmp vpsllq \$10,$D2hi,$D2hi vpandq $mask42,$D2lo,$H2 vpaddq $tmp,$D2hi,$D2hi vpaddq $D2hi,$H0,$H0 vpsllq \$2,$D2hi,$D2hi vpaddq $D2hi,$H0,$H0 vpsrlq \$44,$H0,$tmp # additional step vpandq $mask44,$H0,$H0 vpaddq $tmp,$H1,$H1 # at this point $len is # either 4*n+2 or 0... sub \$2,$len # len-=32 ja .Lblocks_vpmadd52_4x_do vmovq %x#$H0,0($ctx) vmovq %x#$H1,8($ctx) vmovq %x#$H2,16($ctx) vzeroall .Lno_data_vpmadd52_4x: ret .cfi_endproc .size poly1305_blocks_vpmadd52_4x,.-poly1305_blocks_vpmadd52_4x ___ } { ######################################################################## # As implied by its name 8x subroutine processes 8 blocks in parallel... # This is intermediate version, as it's used only in cases when input # length is either 8*n, 8*n+1 or 8*n+2... my ($H0,$H1,$H2,$R0,$R1,$R2,$S1,$S2) = map("%ymm$_",(0..5,16,17)); my ($D0lo,$D0hi,$D1lo,$D1hi,$D2lo,$D2hi) = map("%ymm$_",(18..23)); my ($T0,$T1,$T2,$T3,$mask44,$mask42,$tmp,$PAD) = map("%ymm$_",(24..31)); my ($RR0,$RR1,$RR2,$SS1,$SS2) = map("%ymm$_",(6..10)); $code.=<<___; .type poly1305_blocks_vpmadd52_8x,\@function,4 .align 32 poly1305_blocks_vpmadd52_8x: .cfi_startproc shr \$4,$len jz .Lno_data_vpmadd52_8x # too short shl \$40,$padbit mov 64($ctx),%r8 # peek on power of the key vmovdqa64 .Lx_mask44(%rip),$mask44 vmovdqa64 .Lx_mask42(%rip),$mask42 test %r8,%r8 # is power value impossible? js .Linit_vpmadd52 # if it is, then init R[4] vmovq 0($ctx),%x#$H0 # load current hash value vmovq 8($ctx),%x#$H1 vmovq 16($ctx),%x#$H2 .Lblocks_vpmadd52_8x: ################################################################ # fist we calculate more key powers vmovdqu64 128($ctx),$R2 # load 1-3-2-4 powers vmovdqu64 160($ctx),$S1 vmovdqu64 64($ctx),$R0 vmovdqu64 96($ctx),$R1 vpsllq \$2,$R2,$S2 # S2 = R2*5*4 vpaddq $R2,$S2,$S2 vpsllq \$2,$S2,$S2 vpbroadcastq %x#$R2,$RR2 # broadcast 4th power vpbroadcastq %x#$R0,$RR0 vpbroadcastq %x#$R1,$RR1 vpxorq $D0lo,$D0lo,$D0lo vpmadd52luq $RR2,$S1,$D0lo vpxorq $D0hi,$D0hi,$D0hi vpmadd52huq $RR2,$S1,$D0hi vpxorq $D1lo,$D1lo,$D1lo vpmadd52luq $RR2,$S2,$D1lo vpxorq $D1hi,$D1hi,$D1hi vpmadd52huq $RR2,$S2,$D1hi vpxorq $D2lo,$D2lo,$D2lo vpmadd52luq $RR2,$R0,$D2lo vpxorq $D2hi,$D2hi,$D2hi vpmadd52huq $RR2,$R0,$D2hi vpmadd52luq $RR0,$R0,$D0lo vpmadd52huq $RR0,$R0,$D0hi vpmadd52luq $RR0,$R1,$D1lo vpmadd52huq $RR0,$R1,$D1hi vpmadd52luq $RR0,$R2,$D2lo vpmadd52huq $RR0,$R2,$D2hi vpmadd52luq $RR1,$S2,$D0lo vpmadd52huq $RR1,$S2,$D0hi vpmadd52luq $RR1,$R0,$D1lo vpmadd52huq $RR1,$R0,$D1hi vpmadd52luq $RR1,$R1,$D2lo vpmadd52huq $RR1,$R1,$D2hi ################################################################ # partial reduction vpsrlq \$44,$D0lo,$tmp vpsllq \$8,$D0hi,$D0hi vpandq $mask44,$D0lo,$RR0 vpaddq $tmp,$D0hi,$D0hi vpaddq $D0hi,$D1lo,$D1lo vpsrlq \$44,$D1lo,$tmp vpsllq \$8,$D1hi,$D1hi vpandq $mask44,$D1lo,$RR1 vpaddq $tmp,$D1hi,$D1hi vpaddq $D1hi,$D2lo,$D2lo vpsrlq \$42,$D2lo,$tmp vpsllq \$10,$D2hi,$D2hi vpandq $mask42,$D2lo,$RR2 vpaddq $tmp,$D2hi,$D2hi vpaddq $D2hi,$RR0,$RR0 vpsllq \$2,$D2hi,$D2hi vpaddq $D2hi,$RR0,$RR0 vpsrlq \$44,$RR0,$tmp # additional step vpandq $mask44,$RR0,$RR0 vpaddq $tmp,$RR1,$RR1 ################################################################ # At this point Rx holds 1324 powers, RRx - 5768, and the goal # is 15263748, which reflects how data is loaded... vpunpcklqdq $R2,$RR2,$T2 # 3748 vpunpckhqdq $R2,$RR2,$R2 # 1526 vpunpcklqdq $R0,$RR0,$T0 vpunpckhqdq $R0,$RR0,$R0 vpunpcklqdq $R1,$RR1,$T1 vpunpckhqdq $R1,$RR1,$R1 ___ ######## switch to %zmm map(s/%y/%z/, $H0,$H1,$H2,$R0,$R1,$R2,$S1,$S2); map(s/%y/%z/, $D0lo,$D0hi,$D1lo,$D1hi,$D2lo,$D2hi); map(s/%y/%z/, $T0,$T1,$T2,$T3,$mask44,$mask42,$tmp,$PAD); map(s/%y/%z/, $RR0,$RR1,$RR2,$SS1,$SS2); $code.=<<___; vshufi64x2 \$0x44,$R2,$T2,$RR2 # 15263748 vshufi64x2 \$0x44,$R0,$T0,$RR0 vshufi64x2 \$0x44,$R1,$T1,$RR1 vmovdqu64 16*0($inp),$T2 # load data vmovdqu64 16*4($inp),$T3 lea 16*8($inp),$inp vpsllq \$2,$RR2,$SS2 # S2 = R2*5*4 vpsllq \$2,$RR1,$SS1 # S1 = R1*5*4 vpaddq $RR2,$SS2,$SS2 vpaddq $RR1,$SS1,$SS1 vpsllq \$2,$SS2,$SS2 vpsllq \$2,$SS1,$SS1 vpbroadcastq $padbit,$PAD vpbroadcastq %x#$mask44,$mask44 vpbroadcastq %x#$mask42,$mask42 vpbroadcastq %x#$SS1,$S1 # broadcast 8th power vpbroadcastq %x#$SS2,$S2 vpbroadcastq %x#$RR0,$R0 vpbroadcastq %x#$RR1,$R1 vpbroadcastq %x#$RR2,$R2 vpunpcklqdq $T3,$T2,$T1 # transpose data vpunpckhqdq $T3,$T2,$T3 # at this point 64-bit lanes are ordered as 73625140 vpsrlq \$24,$T3,$T2 # splat the data vporq $PAD,$T2,$T2 vpaddq $T2,$H2,$H2 # accumulate input vpandq $mask44,$T1,$T0 vpsrlq \$44,$T1,$T1 vpsllq \$20,$T3,$T3 vporq $T3,$T1,$T1 vpandq $mask44,$T1,$T1 sub \$8,$len jz .Ltail_vpmadd52_8x jmp .Loop_vpmadd52_8x .align 32 .Loop_vpmadd52_8x: #vpaddq $T2,$H2,$H2 # accumulate input vpaddq $T0,$H0,$H0 vpaddq $T1,$H1,$H1 vpxorq $D0lo,$D0lo,$D0lo vpmadd52luq $H2,$S1,$D0lo vpxorq $D0hi,$D0hi,$D0hi vpmadd52huq $H2,$S1,$D0hi vpxorq $D1lo,$D1lo,$D1lo vpmadd52luq $H2,$S2,$D1lo vpxorq $D1hi,$D1hi,$D1hi vpmadd52huq $H2,$S2,$D1hi vpxorq $D2lo,$D2lo,$D2lo vpmadd52luq $H2,$R0,$D2lo vpxorq $D2hi,$D2hi,$D2hi vpmadd52huq $H2,$R0,$D2hi vmovdqu64 16*0($inp),$T2 # load data vmovdqu64 16*4($inp),$T3 lea 16*8($inp),$inp vpmadd52luq $H0,$R0,$D0lo vpmadd52huq $H0,$R0,$D0hi vpmadd52luq $H0,$R1,$D1lo vpmadd52huq $H0,$R1,$D1hi vpmadd52luq $H0,$R2,$D2lo vpmadd52huq $H0,$R2,$D2hi vpunpcklqdq $T3,$T2,$T1 # transpose data vpunpckhqdq $T3,$T2,$T3 vpmadd52luq $H1,$S2,$D0lo vpmadd52huq $H1,$S2,$D0hi vpmadd52luq $H1,$R0,$D1lo vpmadd52huq $H1,$R0,$D1hi vpmadd52luq $H1,$R1,$D2lo vpmadd52huq $H1,$R1,$D2hi ################################################################ # partial reduction (interleaved with data splat) vpsrlq \$44,$D0lo,$tmp vpsllq \$8,$D0hi,$D0hi vpandq $mask44,$D0lo,$H0 vpaddq $tmp,$D0hi,$D0hi vpsrlq \$24,$T3,$T2 vporq $PAD,$T2,$T2 vpaddq $D0hi,$D1lo,$D1lo vpsrlq \$44,$D1lo,$tmp vpsllq \$8,$D1hi,$D1hi vpandq $mask44,$D1lo,$H1 vpaddq $tmp,$D1hi,$D1hi vpandq $mask44,$T1,$T0 vpsrlq \$44,$T1,$T1 vpsllq \$20,$T3,$T3 vpaddq $D1hi,$D2lo,$D2lo vpsrlq \$42,$D2lo,$tmp vpsllq \$10,$D2hi,$D2hi vpandq $mask42,$D2lo,$H2 vpaddq $tmp,$D2hi,$D2hi vpaddq $T2,$H2,$H2 # accumulate input vpaddq $D2hi,$H0,$H0 vpsllq \$2,$D2hi,$D2hi vpaddq $D2hi,$H0,$H0 vporq $T3,$T1,$T1 vpandq $mask44,$T1,$T1 vpsrlq \$44,$H0,$tmp # additional step vpandq $mask44,$H0,$H0 vpaddq $tmp,$H1,$H1 sub \$8,$len # len-=128 jnz .Loop_vpmadd52_8x .Ltail_vpmadd52_8x: #vpaddq $T2,$H2,$H2 # accumulate input vpaddq $T0,$H0,$H0 vpaddq $T1,$H1,$H1 vpxorq $D0lo,$D0lo,$D0lo vpmadd52luq $H2,$SS1,$D0lo vpxorq $D0hi,$D0hi,$D0hi vpmadd52huq $H2,$SS1,$D0hi vpxorq $D1lo,$D1lo,$D1lo vpmadd52luq $H2,$SS2,$D1lo vpxorq $D1hi,$D1hi,$D1hi vpmadd52huq $H2,$SS2,$D1hi vpxorq $D2lo,$D2lo,$D2lo vpmadd52luq $H2,$RR0,$D2lo vpxorq $D2hi,$D2hi,$D2hi vpmadd52huq $H2,$RR0,$D2hi vpmadd52luq $H0,$RR0,$D0lo vpmadd52huq $H0,$RR0,$D0hi vpmadd52luq $H0,$RR1,$D1lo vpmadd52huq $H0,$RR1,$D1hi vpmadd52luq $H0,$RR2,$D2lo vpmadd52huq $H0,$RR2,$D2hi vpmadd52luq $H1,$SS2,$D0lo vpmadd52huq $H1,$SS2,$D0hi vpmadd52luq $H1,$RR0,$D1lo vpmadd52huq $H1,$RR0,$D1hi vpmadd52luq $H1,$RR1,$D2lo vpmadd52huq $H1,$RR1,$D2hi ################################################################ # horizontal addition mov \$1,%eax kmovw %eax,%k1 vpsrldq \$8,$D0lo,$T0 vpsrldq \$8,$D0hi,$H0 vpsrldq \$8,$D1lo,$T1 vpsrldq \$8,$D1hi,$H1 vpaddq $T0,$D0lo,$D0lo vpaddq $H0,$D0hi,$D0hi vpsrldq \$8,$D2lo,$T2 vpsrldq \$8,$D2hi,$H2 vpaddq $T1,$D1lo,$D1lo vpaddq $H1,$D1hi,$D1hi vpermq \$0x2,$D0lo,$T0 vpermq \$0x2,$D0hi,$H0 vpaddq $T2,$D2lo,$D2lo vpaddq $H2,$D2hi,$D2hi vpermq \$0x2,$D1lo,$T1 vpermq \$0x2,$D1hi,$H1 vpaddq $T0,$D0lo,$D0lo vpaddq $H0,$D0hi,$D0hi vpermq \$0x2,$D2lo,$T2 vpermq \$0x2,$D2hi,$H2 vpaddq $T1,$D1lo,$D1lo vpaddq $H1,$D1hi,$D1hi vextracti64x4 \$1,$D0lo,%y#$T0 vextracti64x4 \$1,$D0hi,%y#$H0 vpaddq $T2,$D2lo,$D2lo vpaddq $H2,$D2hi,$D2hi vextracti64x4 \$1,$D1lo,%y#$T1 vextracti64x4 \$1,$D1hi,%y#$H1 vextracti64x4 \$1,$D2lo,%y#$T2 vextracti64x4 \$1,$D2hi,%y#$H2 ___ ######## switch back to %ymm map(s/%z/%y/, $H0,$H1,$H2,$R0,$R1,$R2,$S1,$S2); map(s/%z/%y/, $D0lo,$D0hi,$D1lo,$D1hi,$D2lo,$D2hi); map(s/%z/%y/, $T0,$T1,$T2,$T3,$mask44,$mask42,$tmp,$PAD); $code.=<<___; vpaddq $T0,$D0lo,${D0lo}{%k1}{z} vpaddq $H0,$D0hi,${D0hi}{%k1}{z} vpaddq $T1,$D1lo,${D1lo}{%k1}{z} vpaddq $H1,$D1hi,${D1hi}{%k1}{z} vpaddq $T2,$D2lo,${D2lo}{%k1}{z} vpaddq $H2,$D2hi,${D2hi}{%k1}{z} ################################################################ # partial reduction vpsrlq \$44,$D0lo,$tmp vpsllq \$8,$D0hi,$D0hi vpandq $mask44,$D0lo,$H0 vpaddq $tmp,$D0hi,$D0hi vpaddq $D0hi,$D1lo,$D1lo vpsrlq \$44,$D1lo,$tmp vpsllq \$8,$D1hi,$D1hi vpandq $mask44,$D1lo,$H1 vpaddq $tmp,$D1hi,$D1hi vpaddq $D1hi,$D2lo,$D2lo vpsrlq \$42,$D2lo,$tmp vpsllq \$10,$D2hi,$D2hi vpandq $mask42,$D2lo,$H2 vpaddq $tmp,$D2hi,$D2hi vpaddq $D2hi,$H0,$H0 vpsllq \$2,$D2hi,$D2hi vpaddq $D2hi,$H0,$H0 vpsrlq \$44,$H0,$tmp # additional step vpandq $mask44,$H0,$H0 vpaddq $tmp,$H1,$H1 ################################################################ vmovq %x#$H0,0($ctx) vmovq %x#$H1,8($ctx) vmovq %x#$H2,16($ctx) vzeroall .Lno_data_vpmadd52_8x: ret .cfi_endproc .size poly1305_blocks_vpmadd52_8x,.-poly1305_blocks_vpmadd52_8x ___ } $code.=<<___; .type poly1305_emit_base2_44,\@function,3 .align 32 poly1305_emit_base2_44: .cfi_startproc endbranch mov 0($ctx),%r8 # load hash value mov 8($ctx),%r9 mov 16($ctx),%r10 mov %r9,%rax shr \$20,%r9 shl \$44,%rax mov %r10,%rcx shr \$40,%r10 shl \$24,%rcx add %rax,%r8 adc %rcx,%r9 adc \$0,%r10 mov %r8,%rax add \$5,%r8 # compare to modulus mov %r9,%rcx adc \$0,%r9 adc \$0,%r10 shr \$2,%r10 # did 130-bit value overflow? cmovnz %r8,%rax cmovnz %r9,%rcx add 0($nonce),%rax # accumulate nonce adc 8($nonce),%rcx mov %rax,0($mac) # write result mov %rcx,8($mac) ret .cfi_endproc .size poly1305_emit_base2_44,.-poly1305_emit_base2_44 ___ } } } $code.=<<___; .align 64 .Lconst: .Lmask24: .long 0x0ffffff,0,0x0ffffff,0,0x0ffffff,0,0x0ffffff,0 .L129: .long `1<<24`,0,`1<<24`,0,`1<<24`,0,`1<<24`,0 .Lmask26: .long 0x3ffffff,0,0x3ffffff,0,0x3ffffff,0,0x3ffffff,0 .Lpermd_avx2: .long 2,2,2,3,2,0,2,1 .Lpermd_avx512: .long 0,0,0,1, 0,2,0,3, 0,4,0,5, 0,6,0,7 .L2_44_inp_permd: .long 0,1,1,2,2,3,7,7 .L2_44_inp_shift: .quad 0,12,24,64 .L2_44_mask: .quad 0xfffffffffff,0xfffffffffff,0x3ffffffffff,0xffffffffffffffff .L2_44_shift_rgt: .quad 44,44,42,64 .L2_44_shift_lft: .quad 8,8,10,64 .align 64 .Lx_mask44: .quad 0xfffffffffff,0xfffffffffff,0xfffffffffff,0xfffffffffff .quad 0xfffffffffff,0xfffffffffff,0xfffffffffff,0xfffffffffff .Lx_mask42: .quad 0x3ffffffffff,0x3ffffffffff,0x3ffffffffff,0x3ffffffffff .quad 0x3ffffffffff,0x3ffffffffff,0x3ffffffffff,0x3ffffffffff ___ } $code.=<<___; .asciz "Poly1305 for x86_64, CRYPTOGAMS by " .align 16 ___ { # chacha20-poly1305 helpers my ($out,$inp,$otp,$len)=$win64 ? ("%rcx","%rdx","%r8", "%r9") : # Win64 order ("%rdi","%rsi","%rdx","%rcx"); # Unix order $code.=<<___; .globl xor128_encrypt_n_pad .type xor128_encrypt_n_pad,\@abi-omnipotent .align 16 xor128_encrypt_n_pad: .cfi_startproc sub $otp,$inp sub $otp,$out mov $len,%r10 # put len aside shr \$4,$len # len / 16 jz .Ltail_enc nop .Loop_enc_xmm: movdqu ($inp,$otp),%xmm0 pxor ($otp),%xmm0 movdqu %xmm0,($out,$otp) movdqa %xmm0,($otp) lea 16($otp),$otp dec $len jnz .Loop_enc_xmm and \$15,%r10 # len % 16 jz .Ldone_enc .Ltail_enc: mov \$16,$len sub %r10,$len xor %eax,%eax .Loop_enc_byte: mov ($inp,$otp),%al xor ($otp),%al mov %al,($out,$otp) mov %al,($otp) lea 1($otp),$otp dec %r10 jnz .Loop_enc_byte xor %eax,%eax .Loop_enc_pad: mov %al,($otp) lea 1($otp),$otp dec $len jnz .Loop_enc_pad .Ldone_enc: mov $otp,%rax ret .cfi_endproc .size xor128_encrypt_n_pad,.-xor128_encrypt_n_pad .globl xor128_decrypt_n_pad .type xor128_decrypt_n_pad,\@abi-omnipotent .align 16 xor128_decrypt_n_pad: .cfi_startproc sub $otp,$inp sub $otp,$out mov $len,%r10 # put len aside shr \$4,$len # len / 16 jz .Ltail_dec nop .Loop_dec_xmm: movdqu ($inp,$otp),%xmm0 movdqa ($otp),%xmm1 pxor %xmm0,%xmm1 movdqu %xmm1,($out,$otp) movdqa %xmm0,($otp) lea 16($otp),$otp dec $len jnz .Loop_dec_xmm pxor %xmm1,%xmm1 and \$15,%r10 # len % 16 jz .Ldone_dec .Ltail_dec: mov \$16,$len sub %r10,$len xor %eax,%eax xor %r11,%r11 .Loop_dec_byte: mov ($inp,$otp),%r11b mov ($otp),%al xor %r11b,%al mov %al,($out,$otp) mov %r11b,($otp) lea 1($otp),$otp dec %r10 jnz .Loop_dec_byte xor %eax,%eax .Loop_dec_pad: mov %al,($otp) lea 1($otp),$otp dec $len jnz .Loop_dec_pad .Ldone_dec: mov $otp,%rax ret .cfi_endproc .size xor128_decrypt_n_pad,.-xor128_decrypt_n_pad ___ } # 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 se_handler,\@abi-omnipotent .align 16 se_handler: push %rsi push %rdi push %rbx push %rbp push %r12 push %r13 push %r14 push %r15 pushfq sub \$64,%rsp mov 120($context),%rax # pull context->Rax mov 248($context),%rbx # pull context->Rip mov 8($disp),%rsi # disp->ImageBase mov 56($disp),%r11 # disp->HandlerData mov 0(%r11),%r10d # HandlerData[0] lea (%rsi,%r10),%r10 # prologue label cmp %r10,%rbx # context->Rip<.Lprologue jb .Lcommon_seh_tail mov 152($context),%rax # pull context->Rsp mov 4(%r11),%r10d # HandlerData[1] lea (%rsi,%r10),%r10 # epilogue label cmp %r10,%rbx # context->Rip>=.Lepilogue jae .Lcommon_seh_tail lea 48(%rax),%rax 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->R14 jmp .Lcommon_seh_tail .size se_handler,.-se_handler .type avx_handler,\@abi-omnipotent .align 16 avx_handler: push %rsi push %rdi push %rbx push %rbp push %r12 push %r13 push %r14 push %r15 pushfq sub \$64,%rsp mov 120($context),%rax # pull context->Rax mov 248($context),%rbx # pull context->Rip mov 8($disp),%rsi # disp->ImageBase mov 56($disp),%r11 # disp->HandlerData mov 0(%r11),%r10d # HandlerData[0] lea (%rsi,%r10),%r10 # prologue label cmp %r10,%rbx # context->RipRsp mov 4(%r11),%r10d # HandlerData[1] lea (%rsi,%r10),%r10 # epilogue label cmp %r10,%rbx # context->Rip>=epilogue label jae .Lcommon_seh_tail mov 208($context),%rax # pull context->R11 lea 0x50(%rax),%rsi lea 0xf8(%rax),%rax lea 512($context),%rdi # &context.Xmm6 mov \$20,%ecx .long 0xa548f3fc # cld; rep movsq .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 avx_handler,.-avx_handler .section .pdata .align 4 .rva .LSEH_begin_poly1305_init .rva .LSEH_end_poly1305_init .rva .LSEH_info_poly1305_init .rva .LSEH_begin_poly1305_blocks .rva .LSEH_end_poly1305_blocks .rva .LSEH_info_poly1305_blocks .rva .LSEH_begin_poly1305_emit .rva .LSEH_end_poly1305_emit .rva .LSEH_info_poly1305_emit ___ $code.=<<___ if ($avx); .rva .LSEH_begin_poly1305_blocks_avx .rva .Lbase2_64_avx .rva .LSEH_info_poly1305_blocks_avx_1 .rva .Lbase2_64_avx .rva .Leven_avx .rva .LSEH_info_poly1305_blocks_avx_2 .rva .Leven_avx .rva .LSEH_end_poly1305_blocks_avx .rva .LSEH_info_poly1305_blocks_avx_3 .rva .LSEH_begin_poly1305_emit_avx .rva .LSEH_end_poly1305_emit_avx .rva .LSEH_info_poly1305_emit_avx ___ $code.=<<___ if ($avx>1); .rva .LSEH_begin_poly1305_blocks_avx2 .rva .Lbase2_64_avx2 .rva .LSEH_info_poly1305_blocks_avx2_1 .rva .Lbase2_64_avx2 .rva .Leven_avx2 .rva .LSEH_info_poly1305_blocks_avx2_2 .rva .Leven_avx2 .rva .LSEH_end_poly1305_blocks_avx2 .rva .LSEH_info_poly1305_blocks_avx2_3 ___ $code.=<<___ if ($avx>2); .rva .LSEH_begin_poly1305_blocks_avx512 .rva .LSEH_end_poly1305_blocks_avx512 .rva .LSEH_info_poly1305_blocks_avx512 ___ $code.=<<___; .section .xdata .align 8 .LSEH_info_poly1305_init: .byte 9,0,0,0 .rva se_handler .rva .LSEH_begin_poly1305_init,.LSEH_begin_poly1305_init .LSEH_info_poly1305_blocks: .byte 9,0,0,0 .rva se_handler .rva .Lblocks_body,.Lblocks_epilogue .LSEH_info_poly1305_emit: .byte 9,0,0,0 .rva se_handler .rva .LSEH_begin_poly1305_emit,.LSEH_begin_poly1305_emit ___ $code.=<<___ if ($avx); .LSEH_info_poly1305_blocks_avx_1: .byte 9,0,0,0 .rva se_handler .rva .Lblocks_avx_body,.Lblocks_avx_epilogue # HandlerData[] .LSEH_info_poly1305_blocks_avx_2: .byte 9,0,0,0 .rva se_handler .rva .Lbase2_64_avx_body,.Lbase2_64_avx_epilogue # HandlerData[] .LSEH_info_poly1305_blocks_avx_3: .byte 9,0,0,0 .rva avx_handler .rva .Ldo_avx_body,.Ldo_avx_epilogue # HandlerData[] .LSEH_info_poly1305_emit_avx: .byte 9,0,0,0 .rva se_handler .rva .LSEH_begin_poly1305_emit_avx,.LSEH_begin_poly1305_emit_avx ___ $code.=<<___ if ($avx>1); .LSEH_info_poly1305_blocks_avx2_1: .byte 9,0,0,0 .rva se_handler .rva .Lblocks_avx2_body,.Lblocks_avx2_epilogue # HandlerData[] .LSEH_info_poly1305_blocks_avx2_2: .byte 9,0,0,0 .rva se_handler .rva .Lbase2_64_avx2_body,.Lbase2_64_avx2_epilogue # HandlerData[] .LSEH_info_poly1305_blocks_avx2_3: .byte 9,0,0,0 .rva avx_handler .rva .Ldo_avx2_body,.Ldo_avx2_epilogue # HandlerData[] ___ $code.=<<___ if ($avx>2); .LSEH_info_poly1305_blocks_avx512: .byte 9,0,0,0 .rva avx_handler .rva .Ldo_avx512_body,.Ldo_avx512_epilogue # HandlerData[] ___ } foreach (split('\n',$code)) { s/\`([^\`]*)\`/eval($1)/ge; s/%r([a-z]+)#d/%e$1/g; s/%r([0-9]+)#d/%r$1d/g; s/%x#%[yz]/%x/g or s/%y#%z/%y/g or s/%z#%[yz]/%z/g; print $_,"\n"; } close STDOUT or die "error closing STDOUT: $!"; diff --git a/crypto/property/property.c b/crypto/property/property.c index b97861d4862f..602db0f3ff54 100644 --- a/crypto/property/property.c +++ b/crypto/property/property.c @@ -1,770 +1,770 @@ /* * Copyright 2019-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include #include #include #include #include "internal/core.h" #include "internal/property.h" #include "internal/provider.h" #include "internal/tsan_assist.h" #include "crypto/ctype.h" #include #include #include "internal/thread_once.h" #include "crypto/lhash.h" #include "crypto/sparse_array.h" #include "property_local.h" /* * The number of elements in the query cache before we initiate a flush. * If reducing this, also ensure the stochastic test in test/property_test.c * isn't likely to fail. */ #define IMPL_CACHE_FLUSH_THRESHOLD 500 typedef struct { void *method; int (*up_ref)(void *); void (*free)(void *); } METHOD; typedef struct { const OSSL_PROVIDER *provider; OSSL_PROPERTY_LIST *properties; METHOD method; } IMPLEMENTATION; DEFINE_STACK_OF(IMPLEMENTATION) typedef struct { const OSSL_PROVIDER *provider; const char *query; METHOD method; char body[1]; } QUERY; DEFINE_LHASH_OF(QUERY); typedef struct { int nid; STACK_OF(IMPLEMENTATION) *impls; LHASH_OF(QUERY) *cache; } ALGORITHM; struct ossl_method_store_st { OSSL_LIB_CTX *ctx; SPARSE_ARRAY_OF(ALGORITHM) *algs; /* * Lock to protect the |algs| array from concurrent writing, when * individual implementations or queries are inserted. This is used * by the appropriate functions here. */ CRYPTO_RWLOCK *lock; /* * Lock to reserve the whole store. This is used when fetching a set * of algorithms, via these functions, found in crypto/core_fetch.c: * ossl_method_construct_reserve_store() * ossl_method_construct_unreserve_store() */ CRYPTO_RWLOCK *biglock; /* query cache specific values */ /* Count of the query cache entries for all algs */ size_t cache_nelem; /* Flag: 1 if query cache entries for all algs need flushing */ int cache_need_flush; }; typedef struct { LHASH_OF(QUERY) *cache; size_t nelem; uint32_t seed; unsigned char using_global_seed; } IMPL_CACHE_FLUSH; DEFINE_SPARSE_ARRAY_OF(ALGORITHM); typedef struct ossl_global_properties_st { OSSL_PROPERTY_LIST *list; #ifndef FIPS_MODULE unsigned int no_mirrored : 1; #endif } OSSL_GLOBAL_PROPERTIES; static void ossl_method_cache_flush_alg(OSSL_METHOD_STORE *store, ALGORITHM *alg); static void ossl_method_cache_flush(OSSL_METHOD_STORE *store, int nid); /* Global properties are stored per library context */ static void ossl_ctx_global_properties_free(void *vglobp) { OSSL_GLOBAL_PROPERTIES *globp = vglobp; if (globp != NULL) { ossl_property_free(globp->list); OPENSSL_free(globp); } } static void *ossl_ctx_global_properties_new(OSSL_LIB_CTX *ctx) { return OPENSSL_zalloc(sizeof(OSSL_GLOBAL_PROPERTIES)); } static const OSSL_LIB_CTX_METHOD ossl_ctx_global_properties_method = { OSSL_LIB_CTX_METHOD_DEFAULT_PRIORITY, ossl_ctx_global_properties_new, ossl_ctx_global_properties_free, }; OSSL_PROPERTY_LIST **ossl_ctx_global_properties(OSSL_LIB_CTX *libctx, - int loadconfig) + ossl_unused int loadconfig) { OSSL_GLOBAL_PROPERTIES *globp; -#ifndef FIPS_MODULE +#if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_AUTOLOAD_CONFIG) if (loadconfig && !OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL)) return NULL; #endif globp = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_GLOBAL_PROPERTIES, &ossl_ctx_global_properties_method); return globp != NULL ? &globp->list : NULL; } #ifndef FIPS_MODULE int ossl_global_properties_no_mirrored(OSSL_LIB_CTX *libctx) { OSSL_GLOBAL_PROPERTIES *globp = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_GLOBAL_PROPERTIES, &ossl_ctx_global_properties_method); return globp != NULL && globp->no_mirrored ? 1 : 0; } void ossl_global_properties_stop_mirroring(OSSL_LIB_CTX *libctx) { OSSL_GLOBAL_PROPERTIES *globp = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_GLOBAL_PROPERTIES, &ossl_ctx_global_properties_method); if (globp != NULL) globp->no_mirrored = 1; } #endif static int ossl_method_up_ref(METHOD *method) { return (*method->up_ref)(method->method); } static void ossl_method_free(METHOD *method) { (*method->free)(method->method); } static __owur int ossl_property_read_lock(OSSL_METHOD_STORE *p) { return p != NULL ? CRYPTO_THREAD_read_lock(p->lock) : 0; } static __owur int ossl_property_write_lock(OSSL_METHOD_STORE *p) { return p != NULL ? CRYPTO_THREAD_write_lock(p->lock) : 0; } static int ossl_property_unlock(OSSL_METHOD_STORE *p) { return p != 0 ? CRYPTO_THREAD_unlock(p->lock) : 0; } static unsigned long query_hash(const QUERY *a) { return OPENSSL_LH_strhash(a->query); } static int query_cmp(const QUERY *a, const QUERY *b) { int res = strcmp(a->query, b->query); if (res == 0 && a->provider != NULL && b->provider != NULL) res = b->provider > a->provider ? 1 : b->provider < a->provider ? -1 : 0; return res; } static void impl_free(IMPLEMENTATION *impl) { if (impl != NULL) { ossl_method_free(&impl->method); OPENSSL_free(impl); } } static void impl_cache_free(QUERY *elem) { if (elem != NULL) { ossl_method_free(&elem->method); OPENSSL_free(elem); } } static void impl_cache_flush_alg(ossl_uintmax_t idx, ALGORITHM *alg) { lh_QUERY_doall(alg->cache, &impl_cache_free); lh_QUERY_flush(alg->cache); } static void alg_cleanup(ossl_uintmax_t idx, ALGORITHM *a, void *arg) { OSSL_METHOD_STORE *store = arg; if (a != NULL) { sk_IMPLEMENTATION_pop_free(a->impls, &impl_free); lh_QUERY_doall(a->cache, &impl_cache_free); lh_QUERY_free(a->cache); OPENSSL_free(a); } if (store != NULL) ossl_sa_ALGORITHM_set(store->algs, idx, NULL); } /* * The OSSL_LIB_CTX param here allows access to underlying property data needed * for computation */ OSSL_METHOD_STORE *ossl_method_store_new(OSSL_LIB_CTX *ctx) { OSSL_METHOD_STORE *res; res = OPENSSL_zalloc(sizeof(*res)); if (res != NULL) { res->ctx = ctx; if ((res->algs = ossl_sa_ALGORITHM_new()) == NULL || (res->lock = CRYPTO_THREAD_lock_new()) == NULL || (res->biglock = CRYPTO_THREAD_lock_new()) == NULL) { ossl_method_store_free(res); return NULL; } } return res; } void ossl_method_store_free(OSSL_METHOD_STORE *store) { if (store != NULL) { if (store->algs != NULL) ossl_sa_ALGORITHM_doall_arg(store->algs, &alg_cleanup, store); ossl_sa_ALGORITHM_free(store->algs); CRYPTO_THREAD_lock_free(store->lock); CRYPTO_THREAD_lock_free(store->biglock); OPENSSL_free(store); } } int ossl_method_lock_store(OSSL_METHOD_STORE *store) { return store != NULL ? CRYPTO_THREAD_write_lock(store->biglock) : 0; } int ossl_method_unlock_store(OSSL_METHOD_STORE *store) { return store != NULL ? CRYPTO_THREAD_unlock(store->biglock) : 0; } static ALGORITHM *ossl_method_store_retrieve(OSSL_METHOD_STORE *store, int nid) { return ossl_sa_ALGORITHM_get(store->algs, nid); } static int ossl_method_store_insert(OSSL_METHOD_STORE *store, ALGORITHM *alg) { return ossl_sa_ALGORITHM_set(store->algs, alg->nid, alg); } int ossl_method_store_add(OSSL_METHOD_STORE *store, const OSSL_PROVIDER *prov, int nid, const char *properties, void *method, int (*method_up_ref)(void *), void (*method_destruct)(void *)) { ALGORITHM *alg = NULL; IMPLEMENTATION *impl; int ret = 0; int i; if (nid <= 0 || method == NULL || store == NULL) return 0; if (properties == NULL) properties = ""; if (!ossl_assert(prov != NULL)) return 0; /* Create new entry */ impl = OPENSSL_malloc(sizeof(*impl)); if (impl == NULL) return 0; impl->method.method = method; impl->method.up_ref = method_up_ref; impl->method.free = method_destruct; if (!ossl_method_up_ref(&impl->method)) { OPENSSL_free(impl); return 0; } impl->provider = prov; /* Insert into the hash table if required */ if (!ossl_property_write_lock(store)) { OPENSSL_free(impl); return 0; } ossl_method_cache_flush(store, nid); if ((impl->properties = ossl_prop_defn_get(store->ctx, properties)) == NULL) { impl->properties = ossl_parse_property(store->ctx, properties); if (impl->properties == NULL) goto err; if (!ossl_prop_defn_set(store->ctx, properties, &impl->properties)) { ossl_property_free(impl->properties); impl->properties = NULL; goto err; } } alg = ossl_method_store_retrieve(store, nid); if (alg == NULL) { if ((alg = OPENSSL_zalloc(sizeof(*alg))) == NULL || (alg->impls = sk_IMPLEMENTATION_new_null()) == NULL || (alg->cache = lh_QUERY_new(&query_hash, &query_cmp)) == NULL) goto err; alg->nid = nid; if (!ossl_method_store_insert(store, alg)) goto err; } /* Push onto stack if there isn't one there already */ for (i = 0; i < sk_IMPLEMENTATION_num(alg->impls); i++) { const IMPLEMENTATION *tmpimpl = sk_IMPLEMENTATION_value(alg->impls, i); if (tmpimpl->provider == impl->provider && tmpimpl->properties == impl->properties) break; } if (i == sk_IMPLEMENTATION_num(alg->impls) && sk_IMPLEMENTATION_push(alg->impls, impl)) ret = 1; ossl_property_unlock(store); if (ret == 0) impl_free(impl); return ret; err: ossl_property_unlock(store); alg_cleanup(0, alg, NULL); impl_free(impl); return 0; } int ossl_method_store_remove(OSSL_METHOD_STORE *store, int nid, const void *method) { ALGORITHM *alg = NULL; int i; if (nid <= 0 || method == NULL || store == NULL) return 0; if (!ossl_property_write_lock(store)) return 0; ossl_method_cache_flush(store, nid); alg = ossl_method_store_retrieve(store, nid); if (alg == NULL) { ossl_property_unlock(store); return 0; } /* * A sorting find then a delete could be faster but these stacks should be * relatively small, so we avoid the overhead. Sorting could also surprise * users when result orderings change (even though they are not guaranteed). */ for (i = 0; i < sk_IMPLEMENTATION_num(alg->impls); i++) { IMPLEMENTATION *impl = sk_IMPLEMENTATION_value(alg->impls, i); if (impl->method.method == method) { impl_free(impl); (void)sk_IMPLEMENTATION_delete(alg->impls, i); ossl_property_unlock(store); return 1; } } ossl_property_unlock(store); return 0; } struct alg_cleanup_by_provider_data_st { OSSL_METHOD_STORE *store; const OSSL_PROVIDER *prov; }; static void alg_cleanup_by_provider(ossl_uintmax_t idx, ALGORITHM *alg, void *arg) { struct alg_cleanup_by_provider_data_st *data = arg; int i, count; /* * We walk the stack backwards, to avoid having to deal with stack shifts * caused by deletion */ for (count = 0, i = sk_IMPLEMENTATION_num(alg->impls); i-- > 0;) { IMPLEMENTATION *impl = sk_IMPLEMENTATION_value(alg->impls, i); if (impl->provider == data->prov) { impl_free(impl); (void)sk_IMPLEMENTATION_delete(alg->impls, i); count++; } } /* * If we removed any implementation, we also clear the whole associated * cache, 'cause that's the sensible thing to do. * There's no point flushing the cache entries where we didn't remove * any implementation, though. */ if (count > 0) ossl_method_cache_flush_alg(data->store, alg); } int ossl_method_store_remove_all_provided(OSSL_METHOD_STORE *store, const OSSL_PROVIDER *prov) { struct alg_cleanup_by_provider_data_st data; if (!ossl_property_write_lock(store)) return 0; data.prov = prov; data.store = store; ossl_sa_ALGORITHM_doall_arg(store->algs, &alg_cleanup_by_provider, &data); ossl_property_unlock(store); return 1; } static void alg_do_one(ALGORITHM *alg, IMPLEMENTATION *impl, void (*fn)(int id, void *method, void *fnarg), void *fnarg) { fn(alg->nid, impl->method.method, fnarg); } struct alg_do_each_data_st { void (*fn)(int id, void *method, void *fnarg); void *fnarg; }; static void alg_do_each(ossl_uintmax_t idx, ALGORITHM *alg, void *arg) { struct alg_do_each_data_st *data = arg; int i, end = sk_IMPLEMENTATION_num(alg->impls); for (i = 0; i < end; i++) { IMPLEMENTATION *impl = sk_IMPLEMENTATION_value(alg->impls, i); alg_do_one(alg, impl, data->fn, data->fnarg); } } void ossl_method_store_do_all(OSSL_METHOD_STORE *store, void (*fn)(int id, void *method, void *fnarg), void *fnarg) { struct alg_do_each_data_st data; data.fn = fn; data.fnarg = fnarg; if (store != NULL) ossl_sa_ALGORITHM_doall_arg(store->algs, alg_do_each, &data); } int ossl_method_store_fetch(OSSL_METHOD_STORE *store, int nid, const char *prop_query, const OSSL_PROVIDER **prov_rw, void **method) { OSSL_PROPERTY_LIST **plp; ALGORITHM *alg; IMPLEMENTATION *impl, *best_impl = NULL; OSSL_PROPERTY_LIST *pq = NULL, *p2 = NULL; const OSSL_PROVIDER *prov = prov_rw != NULL ? *prov_rw : NULL; int ret = 0; int j, best = -1, score, optional; if (nid <= 0 || method == NULL || store == NULL) return 0; -#ifndef FIPS_MODULE +#if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_AUTOLOAD_CONFIG) if (ossl_lib_ctx_is_default(store->ctx) && !OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL)) return 0; #endif /* This only needs to be a read lock, because the query won't create anything */ if (!ossl_property_read_lock(store)) return 0; alg = ossl_method_store_retrieve(store, nid); if (alg == NULL) { ossl_property_unlock(store); return 0; } if (prop_query != NULL) p2 = pq = ossl_parse_query(store->ctx, prop_query, 0); plp = ossl_ctx_global_properties(store->ctx, 0); if (plp != NULL && *plp != NULL) { if (pq == NULL) { pq = *plp; } else { p2 = ossl_property_merge(pq, *plp); ossl_property_free(pq); if (p2 == NULL) goto fin; pq = p2; } } if (pq == NULL) { for (j = 0; j < sk_IMPLEMENTATION_num(alg->impls); j++) { if ((impl = sk_IMPLEMENTATION_value(alg->impls, j)) != NULL && (prov == NULL || impl->provider == prov)) { best_impl = impl; ret = 1; break; } } goto fin; } optional = ossl_property_has_optional(pq); for (j = 0; j < sk_IMPLEMENTATION_num(alg->impls); j++) { if ((impl = sk_IMPLEMENTATION_value(alg->impls, j)) != NULL && (prov == NULL || impl->provider == prov)) { score = ossl_property_match_count(pq, impl->properties); if (score > best) { best_impl = impl; best = score; ret = 1; if (!optional) goto fin; } } } fin: if (ret && ossl_method_up_ref(&best_impl->method)) { *method = best_impl->method.method; if (prov_rw != NULL) *prov_rw = best_impl->provider; } else { ret = 0; } ossl_property_unlock(store); ossl_property_free(p2); return ret; } static void ossl_method_cache_flush_alg(OSSL_METHOD_STORE *store, ALGORITHM *alg) { store->cache_nelem -= lh_QUERY_num_items(alg->cache); impl_cache_flush_alg(0, alg); } static void ossl_method_cache_flush(OSSL_METHOD_STORE *store, int nid) { ALGORITHM *alg = ossl_method_store_retrieve(store, nid); if (alg != NULL) ossl_method_cache_flush_alg(store, alg); } int ossl_method_store_cache_flush_all(OSSL_METHOD_STORE *store) { if (!ossl_property_write_lock(store)) return 0; ossl_sa_ALGORITHM_doall(store->algs, &impl_cache_flush_alg); store->cache_nelem = 0; ossl_property_unlock(store); return 1; } IMPLEMENT_LHASH_DOALL_ARG(QUERY, IMPL_CACHE_FLUSH); /* * Flush an element from the query cache (perhaps). * * In order to avoid taking a write lock or using atomic operations * to keep accurate least recently used (LRU) or least frequently used * (LFU) information, the procedure used here is to stochastically * flush approximately half the cache. * * This procedure isn't ideal, LRU or LFU would be better. However, * in normal operation, reaching a full cache would be unexpected. * It means that no steady state of algorithm queries has been reached. * That is, it is most likely an attack of some form. A suboptimal clearance * strategy that doesn't degrade performance of the normal case is * preferable to a more refined approach that imposes a performance * impact. */ static void impl_cache_flush_cache(QUERY *c, IMPL_CACHE_FLUSH *state) { uint32_t n; /* * Implement the 32 bit xorshift as suggested by George Marsaglia in: * https://doi.org/10.18637/jss.v008.i14 * * This is a very fast PRNG so there is no need to extract bits one at a * time and use the entire value each time. */ n = state->seed; n ^= n << 13; n ^= n >> 17; n ^= n << 5; state->seed = n; if ((n & 1) != 0) impl_cache_free(lh_QUERY_delete(state->cache, c)); else state->nelem++; } static void impl_cache_flush_one_alg(ossl_uintmax_t idx, ALGORITHM *alg, void *v) { IMPL_CACHE_FLUSH *state = (IMPL_CACHE_FLUSH *)v; state->cache = alg->cache; lh_QUERY_doall_IMPL_CACHE_FLUSH(state->cache, &impl_cache_flush_cache, state); } static void ossl_method_cache_flush_some(OSSL_METHOD_STORE *store) { IMPL_CACHE_FLUSH state; static TSAN_QUALIFIER uint32_t global_seed = 1; state.nelem = 0; state.using_global_seed = 0; if ((state.seed = OPENSSL_rdtsc()) == 0) { /* If there is no timer available, seed another way */ state.using_global_seed = 1; state.seed = tsan_load(&global_seed); } store->cache_need_flush = 0; ossl_sa_ALGORITHM_doall_arg(store->algs, &impl_cache_flush_one_alg, &state); store->cache_nelem = state.nelem; /* Without a timer, update the global seed */ if (state.using_global_seed) tsan_store(&global_seed, state.seed); } int ossl_method_store_cache_get(OSSL_METHOD_STORE *store, OSSL_PROVIDER *prov, int nid, const char *prop_query, void **method) { ALGORITHM *alg; QUERY elem, *r; int res = 0; if (nid <= 0 || store == NULL || prop_query == NULL) return 0; if (!ossl_property_read_lock(store)) return 0; alg = ossl_method_store_retrieve(store, nid); if (alg == NULL) goto err; elem.query = prop_query; elem.provider = prov; r = lh_QUERY_retrieve(alg->cache, &elem); if (r == NULL) goto err; if (ossl_method_up_ref(&r->method)) { *method = r->method.method; res = 1; } err: ossl_property_unlock(store); return res; } int ossl_method_store_cache_set(OSSL_METHOD_STORE *store, OSSL_PROVIDER *prov, int nid, const char *prop_query, void *method, int (*method_up_ref)(void *), void (*method_destruct)(void *)) { QUERY elem, *old, *p = NULL; ALGORITHM *alg; size_t len; int res = 1; if (nid <= 0 || store == NULL || prop_query == NULL) return 0; if (!ossl_assert(prov != NULL)) return 0; if (!ossl_property_write_lock(store)) return 0; if (store->cache_need_flush) ossl_method_cache_flush_some(store); alg = ossl_method_store_retrieve(store, nid); if (alg == NULL) goto err; if (method == NULL) { elem.query = prop_query; elem.provider = prov; if ((old = lh_QUERY_delete(alg->cache, &elem)) != NULL) { impl_cache_free(old); store->cache_nelem--; } goto end; } p = OPENSSL_malloc(sizeof(*p) + (len = strlen(prop_query))); if (p != NULL) { p->query = p->body; p->provider = prov; p->method.method = method; p->method.up_ref = method_up_ref; p->method.free = method_destruct; if (!ossl_method_up_ref(&p->method)) goto err; memcpy((char *)p->query, prop_query, len + 1); if ((old = lh_QUERY_insert(alg->cache, p)) != NULL) { impl_cache_free(old); goto end; } if (!lh_QUERY_error(alg->cache)) { if (++store->cache_nelem >= IMPL_CACHE_FLUSH_THRESHOLD) store->cache_need_flush = 1; goto end; } ossl_method_free(&p->method); } err: res = 0; OPENSSL_free(p); end: ossl_property_unlock(store); return res; } diff --git a/crypto/provider_core.c b/crypto/provider_core.c index 7a1232812162..92cce32c5bbf 100644 --- a/crypto/provider_core.c +++ b/crypto/provider_core.c @@ -1,2171 +1,2171 @@ /* - * Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2019-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include #include #include #include #include #include #include #include "crypto/cryptlib.h" #ifndef FIPS_MODULE #include "crypto/decoder.h" /* ossl_decoder_store_cache_flush */ #include "crypto/encoder.h" /* ossl_encoder_store_cache_flush */ #include "crypto/store.h" /* ossl_store_loader_store_cache_flush */ #endif #include "crypto/evp.h" /* evp_method_store_cache_flush */ #include "crypto/rand.h" #include "internal/nelem.h" #include "internal/thread_once.h" #include "internal/provider.h" #include "internal/refcount.h" #include "internal/bio.h" #include "internal/core.h" #include "provider_local.h" #ifndef FIPS_MODULE # include #endif /* * This file defines and uses a number of different structures: * * OSSL_PROVIDER (provider_st): Used to represent all information related to a * single instance of a provider. * * provider_store_st: Holds information about the collection of providers that * are available within the current library context (OSSL_LIB_CTX). It also * holds configuration information about providers that could be loaded at some * future point. * * OSSL_PROVIDER_CHILD_CB: An instance of this structure holds the callbacks * that have been registered for a child library context and the associated * provider that registered those callbacks. * * Where a child library context exists then it has its own instance of the * provider store. Each provider that exists in the parent provider store, has * an associated child provider in the child library context's provider store. * As providers get activated or deactivated this needs to be mirrored in the * associated child providers. * * LOCKING * ======= * * There are a number of different locks used in this file and it is important * to understand how they should be used in order to avoid deadlocks. * * Fields within a structure can often be "write once" on creation, and then * "read many". Creation of a structure is done by a single thread, and * therefore no lock is required for the "write once/read many" fields. It is * safe for multiple threads to read these fields without a lock, because they * will never be changed. * * However some fields may be changed after a structure has been created and * shared between multiple threads. Where this is the case a lock is required. * * The locks available are: * * The provider flag_lock: Used to control updates to the various provider * "flags" (flag_initialized, flag_activated, flag_fallback) and associated * "counts" (activatecnt). * * The provider refcnt_lock: Only ever used to control updates to the provider * refcnt value. * * The provider optbits_lock: Used to control access to the provider's * operation_bits and operation_bits_sz fields. * * The store default_path_lock: Used to control access to the provider store's * default search path value (default_path) * * The store lock: Used to control the stack of provider's held within the * provider store, as well as the stack of registered child provider callbacks. * * As a general rule-of-thumb it is best to: * - keep the scope of the code that is protected by a lock to the absolute * minimum possible; * - try to keep the scope of the lock to within a single function (i.e. avoid * making calls to other functions while holding a lock); * - try to only ever hold one lock at a time. * * Unfortunately, it is not always possible to stick to the above guidelines. * Where they are not adhered to there is always a danger of inadvertently * introducing the possibility of deadlock. The following rules MUST be adhered * to in order to avoid that: * - Holding multiple locks at the same time is only allowed for the * provider store lock, the provider flag_lock and the provider refcnt_lock. * - When holding multiple locks they must be acquired in the following order of * precedence: * 1) provider store lock * 2) provider flag_lock * 3) provider refcnt_lock * - When releasing locks they must be released in the reverse order to which * they were acquired * - No locks may be held when making an upcall. NOTE: Some common functions * can make upcalls as part of their normal operation. If you need to call * some other function while holding a lock make sure you know whether it * will make any upcalls or not. For example ossl_provider_up_ref() can call * ossl_provider_up_ref_parent() which can call the c_prov_up_ref() upcall. * - It is permissible to hold the store and flag locks when calling child * provider callbacks. No other locks may be held during such callbacks. */ static OSSL_PROVIDER *provider_new(const char *name, OSSL_provider_init_fn *init_function, STACK_OF(INFOPAIR) *parameters); /*- * Provider Object structure * ========================= */ #ifndef FIPS_MODULE typedef struct { OSSL_PROVIDER *prov; int (*create_cb)(const OSSL_CORE_HANDLE *provider, void *cbdata); int (*remove_cb)(const OSSL_CORE_HANDLE *provider, void *cbdata); int (*global_props_cb)(const char *props, void *cbdata); void *cbdata; } OSSL_PROVIDER_CHILD_CB; DEFINE_STACK_OF(OSSL_PROVIDER_CHILD_CB) #endif struct provider_store_st; /* Forward declaration */ struct ossl_provider_st { /* Flag bits */ unsigned int flag_initialized:1; unsigned int flag_activated:1; unsigned int flag_fallback:1; /* Can be used as fallback */ /* Getting and setting the flags require synchronization */ CRYPTO_RWLOCK *flag_lock; /* OpenSSL library side data */ CRYPTO_REF_COUNT refcnt; CRYPTO_RWLOCK *refcnt_lock; /* For the ref counter */ int activatecnt; char *name; char *path; DSO *module; OSSL_provider_init_fn *init_function; STACK_OF(INFOPAIR) *parameters; OSSL_LIB_CTX *libctx; /* The library context this instance is in */ struct provider_store_st *store; /* The store this instance belongs to */ #ifndef FIPS_MODULE /* * In the FIPS module inner provider, this isn't needed, since the * error upcalls are always direct calls to the outer provider. */ int error_lib; /* ERR library number, one for each provider */ # ifndef OPENSSL_NO_ERR ERR_STRING_DATA *error_strings; /* Copy of what the provider gives us */ # endif #endif /* Provider side functions */ OSSL_FUNC_provider_teardown_fn *teardown; OSSL_FUNC_provider_gettable_params_fn *gettable_params; OSSL_FUNC_provider_get_params_fn *get_params; OSSL_FUNC_provider_get_capabilities_fn *get_capabilities; OSSL_FUNC_provider_self_test_fn *self_test; OSSL_FUNC_provider_query_operation_fn *query_operation; OSSL_FUNC_provider_unquery_operation_fn *unquery_operation; /* * Cache of bit to indicate of query_operation() has been called on * a specific operation or not. */ unsigned char *operation_bits; size_t operation_bits_sz; CRYPTO_RWLOCK *opbits_lock; #ifndef FIPS_MODULE /* Whether this provider is the child of some other provider */ const OSSL_CORE_HANDLE *handle; unsigned int ischild:1; #endif /* Provider side data */ void *provctx; const OSSL_DISPATCH *dispatch; }; DEFINE_STACK_OF(OSSL_PROVIDER) static int ossl_provider_cmp(const OSSL_PROVIDER * const *a, const OSSL_PROVIDER * const *b) { return strcmp((*a)->name, (*b)->name); } /*- * Provider Object store * ===================== * * The Provider Object store is a library context object, and therefore needs * an index. */ struct provider_store_st { OSSL_LIB_CTX *libctx; STACK_OF(OSSL_PROVIDER) *providers; STACK_OF(OSSL_PROVIDER_CHILD_CB) *child_cbs; CRYPTO_RWLOCK *default_path_lock; CRYPTO_RWLOCK *lock; char *default_path; OSSL_PROVIDER_INFO *provinfo; size_t numprovinfo; size_t provinfosz; unsigned int use_fallbacks:1; unsigned int freeing:1; }; /* * provider_deactivate_free() is a wrapper around ossl_provider_deactivate() * and ossl_provider_free(), called as needed. * Since this is only called when the provider store is being emptied, we * don't need to care about any lock. */ static void provider_deactivate_free(OSSL_PROVIDER *prov) { if (prov->flag_activated) ossl_provider_deactivate(prov, 1); ossl_provider_free(prov); } #ifndef FIPS_MODULE static void ossl_provider_child_cb_free(OSSL_PROVIDER_CHILD_CB *cb) { OPENSSL_free(cb); } #endif static void infopair_free(INFOPAIR *pair) { OPENSSL_free(pair->name); OPENSSL_free(pair->value); OPENSSL_free(pair); } static INFOPAIR *infopair_copy(const INFOPAIR *src) { INFOPAIR *dest = OPENSSL_zalloc(sizeof(*dest)); if (dest == NULL) return NULL; if (src->name != NULL) { dest->name = OPENSSL_strdup(src->name); if (dest->name == NULL) goto err; } if (src->value != NULL) { dest->value = OPENSSL_strdup(src->value); if (dest->value == NULL) goto err; } return dest; err: OPENSSL_free(dest->name); OPENSSL_free(dest); return NULL; } void ossl_provider_info_clear(OSSL_PROVIDER_INFO *info) { OPENSSL_free(info->name); OPENSSL_free(info->path); sk_INFOPAIR_pop_free(info->parameters, infopair_free); } static void provider_store_free(void *vstore) { struct provider_store_st *store = vstore; size_t i; if (store == NULL) return; store->freeing = 1; OPENSSL_free(store->default_path); sk_OSSL_PROVIDER_pop_free(store->providers, provider_deactivate_free); #ifndef FIPS_MODULE sk_OSSL_PROVIDER_CHILD_CB_pop_free(store->child_cbs, ossl_provider_child_cb_free); #endif CRYPTO_THREAD_lock_free(store->default_path_lock); CRYPTO_THREAD_lock_free(store->lock); for (i = 0; i < store->numprovinfo; i++) ossl_provider_info_clear(&store->provinfo[i]); OPENSSL_free(store->provinfo); OPENSSL_free(store); } static void *provider_store_new(OSSL_LIB_CTX *ctx) { struct provider_store_st *store = OPENSSL_zalloc(sizeof(*store)); if (store == NULL || (store->providers = sk_OSSL_PROVIDER_new(ossl_provider_cmp)) == NULL || (store->default_path_lock = CRYPTO_THREAD_lock_new()) == NULL #ifndef FIPS_MODULE || (store->child_cbs = sk_OSSL_PROVIDER_CHILD_CB_new_null()) == NULL #endif || (store->lock = CRYPTO_THREAD_lock_new()) == NULL) { provider_store_free(store); return NULL; } store->libctx = ctx; store->use_fallbacks = 1; return store; } static const OSSL_LIB_CTX_METHOD provider_store_method = { /* Needs to be freed before the child provider data is freed */ OSSL_LIB_CTX_METHOD_PRIORITY_1, provider_store_new, provider_store_free, }; static struct provider_store_st *get_provider_store(OSSL_LIB_CTX *libctx) { struct provider_store_st *store = NULL; store = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_PROVIDER_STORE_INDEX, &provider_store_method); if (store == NULL) ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); return store; } int ossl_provider_disable_fallback_loading(OSSL_LIB_CTX *libctx) { struct provider_store_st *store; if ((store = get_provider_store(libctx)) != NULL) { if (!CRYPTO_THREAD_write_lock(store->lock)) return 0; store->use_fallbacks = 0; CRYPTO_THREAD_unlock(store->lock); return 1; } return 0; } #define BUILTINS_BLOCK_SIZE 10 int ossl_provider_info_add_to_store(OSSL_LIB_CTX *libctx, OSSL_PROVIDER_INFO *entry) { struct provider_store_st *store = get_provider_store(libctx); int ret = 0; if (entry->name == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (store == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); return 0; } if (!CRYPTO_THREAD_write_lock(store->lock)) return 0; if (store->provinfosz == 0) { store->provinfo = OPENSSL_zalloc(sizeof(*store->provinfo) * BUILTINS_BLOCK_SIZE); if (store->provinfo == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE); goto err; } store->provinfosz = BUILTINS_BLOCK_SIZE; } else if (store->numprovinfo == store->provinfosz) { OSSL_PROVIDER_INFO *tmpbuiltins; size_t newsz = store->provinfosz + BUILTINS_BLOCK_SIZE; tmpbuiltins = OPENSSL_realloc(store->provinfo, sizeof(*store->provinfo) * newsz); if (tmpbuiltins == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE); goto err; } store->provinfo = tmpbuiltins; store->provinfosz = newsz; } store->provinfo[store->numprovinfo] = *entry; store->numprovinfo++; ret = 1; err: CRYPTO_THREAD_unlock(store->lock); return ret; } OSSL_PROVIDER *ossl_provider_find(OSSL_LIB_CTX *libctx, const char *name, - int noconfig) + ossl_unused int noconfig) { struct provider_store_st *store = NULL; OSSL_PROVIDER *prov = NULL; if ((store = get_provider_store(libctx)) != NULL) { OSSL_PROVIDER tmpl = { 0, }; int i; -#ifndef FIPS_MODULE +#if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_AUTOLOAD_CONFIG) /* * Make sure any providers are loaded from config before we try to find * them. */ if (!noconfig) { if (ossl_lib_ctx_is_default(libctx)) OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL); } #endif tmpl.name = (char *)name; /* * A "find" operation can sort the stack, and therefore a write lock is * required. */ if (!CRYPTO_THREAD_write_lock(store->lock)) return NULL; if ((i = sk_OSSL_PROVIDER_find(store->providers, &tmpl)) != -1) prov = sk_OSSL_PROVIDER_value(store->providers, i); CRYPTO_THREAD_unlock(store->lock); if (prov != NULL && !ossl_provider_up_ref(prov)) prov = NULL; } return prov; } /*- * Provider Object methods * ======================= */ static OSSL_PROVIDER *provider_new(const char *name, OSSL_provider_init_fn *init_function, STACK_OF(INFOPAIR) *parameters) { OSSL_PROVIDER *prov = NULL; if ((prov = OPENSSL_zalloc(sizeof(*prov))) == NULL #ifndef HAVE_ATOMICS || (prov->refcnt_lock = CRYPTO_THREAD_lock_new()) == NULL #endif ) { OPENSSL_free(prov); ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE); return NULL; } prov->refcnt = 1; /* 1 One reference to be returned */ if ((prov->opbits_lock = CRYPTO_THREAD_lock_new()) == NULL || (prov->flag_lock = CRYPTO_THREAD_lock_new()) == NULL || (prov->name = OPENSSL_strdup(name)) == NULL || (prov->parameters = sk_INFOPAIR_deep_copy(parameters, infopair_copy, infopair_free)) == NULL) { ossl_provider_free(prov); ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE); return NULL; } prov->init_function = init_function; return prov; } int ossl_provider_up_ref(OSSL_PROVIDER *prov) { int ref = 0; if (CRYPTO_UP_REF(&prov->refcnt, &ref, prov->refcnt_lock) <= 0) return 0; #ifndef FIPS_MODULE if (prov->ischild) { if (!ossl_provider_up_ref_parent(prov, 0)) { ossl_provider_free(prov); return 0; } } #endif return ref; } #ifndef FIPS_MODULE static int provider_up_ref_intern(OSSL_PROVIDER *prov, int activate) { if (activate) return ossl_provider_activate(prov, 1, 0); return ossl_provider_up_ref(prov); } static int provider_free_intern(OSSL_PROVIDER *prov, int deactivate) { if (deactivate) return ossl_provider_deactivate(prov, 1); ossl_provider_free(prov); return 1; } #endif /* * We assume that the requested provider does not already exist in the store. * The caller should check. If it does exist then adding it to the store later * will fail. */ OSSL_PROVIDER *ossl_provider_new(OSSL_LIB_CTX *libctx, const char *name, OSSL_provider_init_fn *init_function, int noconfig) { struct provider_store_st *store = NULL; OSSL_PROVIDER_INFO template; OSSL_PROVIDER *prov = NULL; if ((store = get_provider_store(libctx)) == NULL) return NULL; memset(&template, 0, sizeof(template)); if (init_function == NULL) { const OSSL_PROVIDER_INFO *p; size_t i; /* Check if this is a predefined builtin provider */ for (p = ossl_predefined_providers; p->name != NULL; p++) { if (strcmp(p->name, name) == 0) { template = *p; break; } } if (p->name == NULL) { /* Check if this is a user added builtin provider */ if (!CRYPTO_THREAD_read_lock(store->lock)) return NULL; for (i = 0, p = store->provinfo; i < store->numprovinfo; p++, i++) { if (strcmp(p->name, name) == 0) { template = *p; break; } } CRYPTO_THREAD_unlock(store->lock); } } else { template.init = init_function; } /* provider_new() generates an error, so no need here */ if ((prov = provider_new(name, template.init, template.parameters)) == NULL) return NULL; prov->libctx = libctx; #ifndef FIPS_MODULE prov->error_lib = ERR_get_next_error_library(); #endif /* * At this point, the provider is only partially "loaded". To be * fully "loaded", ossl_provider_activate() must also be called and it must * then be added to the provider store. */ return prov; } /* Assumes that the store lock is held */ static int create_provider_children(OSSL_PROVIDER *prov) { int ret = 1; #ifndef FIPS_MODULE struct provider_store_st *store = prov->store; OSSL_PROVIDER_CHILD_CB *child_cb; int i, max; max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs); for (i = 0; i < max; i++) { /* * This is newly activated (activatecnt == 1), so we need to * create child providers as necessary. */ child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs, i); ret &= child_cb->create_cb((OSSL_CORE_HANDLE *)prov, child_cb->cbdata); } #endif return ret; } int ossl_provider_add_to_store(OSSL_PROVIDER *prov, OSSL_PROVIDER **actualprov, int retain_fallbacks) { struct provider_store_st *store; int idx; OSSL_PROVIDER tmpl = { 0, }; OSSL_PROVIDER *actualtmp = NULL; if (actualprov != NULL) *actualprov = NULL; if ((store = get_provider_store(prov->libctx)) == NULL) return 0; if (!CRYPTO_THREAD_write_lock(store->lock)) return 0; tmpl.name = (char *)prov->name; idx = sk_OSSL_PROVIDER_find(store->providers, &tmpl); if (idx == -1) actualtmp = prov; else actualtmp = sk_OSSL_PROVIDER_value(store->providers, idx); if (idx == -1) { if (sk_OSSL_PROVIDER_push(store->providers, prov) == 0) goto err; prov->store = store; if (!create_provider_children(prov)) { sk_OSSL_PROVIDER_delete_ptr(store->providers, prov); goto err; } if (!retain_fallbacks) store->use_fallbacks = 0; } CRYPTO_THREAD_unlock(store->lock); if (actualprov != NULL) { if (!ossl_provider_up_ref(actualtmp)) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE); actualtmp = NULL; return 0; } *actualprov = actualtmp; } if (idx >= 0) { /* * The provider is already in the store. Probably two threads * independently initialised their own provider objects with the same * name and raced to put them in the store. This thread lost. We * deactivate the one we just created and use the one that already * exists instead. * If we get here then we know we did not create provider children * above, so we inform ossl_provider_deactivate not to attempt to remove * any. */ ossl_provider_deactivate(prov, 0); ossl_provider_free(prov); } return 1; err: CRYPTO_THREAD_unlock(store->lock); return 0; } void ossl_provider_free(OSSL_PROVIDER *prov) { if (prov != NULL) { int ref = 0; CRYPTO_DOWN_REF(&prov->refcnt, &ref, prov->refcnt_lock); /* * When the refcount drops to zero, we clean up the provider. * Note that this also does teardown, which may seem late, * considering that init happens on first activation. However, * there may be other structures hanging on to the provider after * the last deactivation and may therefore need full access to the * provider's services. Therefore, we deinit late. */ if (ref == 0) { if (prov->flag_initialized) { ossl_provider_teardown(prov); #ifndef OPENSSL_NO_ERR # ifndef FIPS_MODULE if (prov->error_strings != NULL) { ERR_unload_strings(prov->error_lib, prov->error_strings); OPENSSL_free(prov->error_strings); prov->error_strings = NULL; } # endif #endif OPENSSL_free(prov->operation_bits); prov->operation_bits = NULL; prov->operation_bits_sz = 0; prov->flag_initialized = 0; } #ifndef FIPS_MODULE /* * We deregister thread handling whether or not the provider was * initialized. If init was attempted but was not successful then * the provider may still have registered a thread handler. */ ossl_init_thread_deregister(prov); DSO_free(prov->module); #endif OPENSSL_free(prov->name); OPENSSL_free(prov->path); sk_INFOPAIR_pop_free(prov->parameters, infopair_free); CRYPTO_THREAD_lock_free(prov->opbits_lock); CRYPTO_THREAD_lock_free(prov->flag_lock); #ifndef HAVE_ATOMICS CRYPTO_THREAD_lock_free(prov->refcnt_lock); #endif OPENSSL_free(prov); } #ifndef FIPS_MODULE else if (prov->ischild) { ossl_provider_free_parent(prov, 0); } #endif } } /* Setters */ int ossl_provider_set_module_path(OSSL_PROVIDER *prov, const char *module_path) { OPENSSL_free(prov->path); prov->path = NULL; if (module_path == NULL) return 1; if ((prov->path = OPENSSL_strdup(module_path)) != NULL) return 1; ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE); return 0; } static int infopair_add(STACK_OF(INFOPAIR) **infopairsk, const char *name, const char *value) { INFOPAIR *pair = NULL; if ((pair = OPENSSL_zalloc(sizeof(*pair))) != NULL && (*infopairsk != NULL || (*infopairsk = sk_INFOPAIR_new_null()) != NULL) && (pair->name = OPENSSL_strdup(name)) != NULL && (pair->value = OPENSSL_strdup(value)) != NULL && sk_INFOPAIR_push(*infopairsk, pair) > 0) return 1; if (pair != NULL) { OPENSSL_free(pair->name); OPENSSL_free(pair->value); OPENSSL_free(pair); } ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE); return 0; } int ossl_provider_add_parameter(OSSL_PROVIDER *prov, const char *name, const char *value) { return infopair_add(&prov->parameters, name, value); } int ossl_provider_info_add_parameter(OSSL_PROVIDER_INFO *provinfo, const char *name, const char *value) { return infopair_add(&provinfo->parameters, name, value); } /* * Provider activation. * * What "activation" means depends on the provider form; for built in * providers (in the library or the application alike), the provider * can already be considered to be loaded, all that's needed is to * initialize it. However, for dynamically loadable provider modules, * we must first load that module. * * Built in modules are distinguished from dynamically loaded modules * with an already assigned init function. */ static const OSSL_DISPATCH *core_dispatch; /* Define further down */ int OSSL_PROVIDER_set_default_search_path(OSSL_LIB_CTX *libctx, const char *path) { struct provider_store_st *store; char *p = NULL; if (path != NULL) { p = OPENSSL_strdup(path); if (p == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE); return 0; } } if ((store = get_provider_store(libctx)) != NULL && CRYPTO_THREAD_write_lock(store->default_path_lock)) { OPENSSL_free(store->default_path); store->default_path = p; CRYPTO_THREAD_unlock(store->default_path_lock); return 1; } OPENSSL_free(p); return 0; } /* * Internal version that doesn't affect the store flags, and thereby avoid * locking. Direct callers must remember to set the store flags when * appropriate. */ static int provider_init(OSSL_PROVIDER *prov) { const OSSL_DISPATCH *provider_dispatch = NULL; void *tmp_provctx = NULL; /* safety measure */ #ifndef OPENSSL_NO_ERR # ifndef FIPS_MODULE OSSL_FUNC_provider_get_reason_strings_fn *p_get_reason_strings = NULL; # endif #endif int ok = 0; if (!ossl_assert(!prov->flag_initialized)) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto end; } /* * If the init function isn't set, it indicates that this provider is * a loadable module. */ if (prov->init_function == NULL) { #ifdef FIPS_MODULE goto end; #else if (prov->module == NULL) { char *allocated_path = NULL; const char *module_path = NULL; char *merged_path = NULL; const char *load_dir = NULL; char *allocated_load_dir = NULL; struct provider_store_st *store; if ((prov->module = DSO_new()) == NULL) { /* DSO_new() generates an error already */ goto end; } if ((store = get_provider_store(prov->libctx)) == NULL || !CRYPTO_THREAD_read_lock(store->default_path_lock)) goto end; if (store->default_path != NULL) { allocated_load_dir = OPENSSL_strdup(store->default_path); CRYPTO_THREAD_unlock(store->default_path_lock); if (allocated_load_dir == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE); goto end; } load_dir = allocated_load_dir; } else { CRYPTO_THREAD_unlock(store->default_path_lock); } if (load_dir == NULL) { load_dir = ossl_safe_getenv("OPENSSL_MODULES"); if (load_dir == NULL) load_dir = MODULESDIR; } DSO_ctrl(prov->module, DSO_CTRL_SET_FLAGS, DSO_FLAG_NAME_TRANSLATION_EXT_ONLY, NULL); module_path = prov->path; if (module_path == NULL) module_path = allocated_path = DSO_convert_filename(prov->module, prov->name); if (module_path != NULL) merged_path = DSO_merge(prov->module, module_path, load_dir); if (merged_path == NULL || (DSO_load(prov->module, merged_path, NULL, 0)) == NULL) { DSO_free(prov->module); prov->module = NULL; } OPENSSL_free(merged_path); OPENSSL_free(allocated_path); OPENSSL_free(allocated_load_dir); } if (prov->module == NULL) { /* DSO has already recorded errors, this is just a tracepoint */ ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_DSO_LIB, "name=%s", prov->name); goto end; } prov->init_function = (OSSL_provider_init_fn *) DSO_bind_func(prov->module, "OSSL_provider_init"); #endif } /* Check for and call the initialise function for the provider. */ if (prov->init_function == NULL) { ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_UNSUPPORTED, "name=%s, provider has no provider init function", prov->name); goto end; } if (!prov->init_function((OSSL_CORE_HANDLE *)prov, core_dispatch, &provider_dispatch, &tmp_provctx)) { ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_INIT_FAIL, "name=%s", prov->name); goto end; } prov->provctx = tmp_provctx; prov->dispatch = provider_dispatch; for (; provider_dispatch->function_id != 0; provider_dispatch++) { switch (provider_dispatch->function_id) { case OSSL_FUNC_PROVIDER_TEARDOWN: prov->teardown = OSSL_FUNC_provider_teardown(provider_dispatch); break; case OSSL_FUNC_PROVIDER_GETTABLE_PARAMS: prov->gettable_params = OSSL_FUNC_provider_gettable_params(provider_dispatch); break; case OSSL_FUNC_PROVIDER_GET_PARAMS: prov->get_params = OSSL_FUNC_provider_get_params(provider_dispatch); break; case OSSL_FUNC_PROVIDER_SELF_TEST: prov->self_test = OSSL_FUNC_provider_self_test(provider_dispatch); break; case OSSL_FUNC_PROVIDER_GET_CAPABILITIES: prov->get_capabilities = OSSL_FUNC_provider_get_capabilities(provider_dispatch); break; case OSSL_FUNC_PROVIDER_QUERY_OPERATION: prov->query_operation = OSSL_FUNC_provider_query_operation(provider_dispatch); break; case OSSL_FUNC_PROVIDER_UNQUERY_OPERATION: prov->unquery_operation = OSSL_FUNC_provider_unquery_operation(provider_dispatch); break; #ifndef OPENSSL_NO_ERR # ifndef FIPS_MODULE case OSSL_FUNC_PROVIDER_GET_REASON_STRINGS: p_get_reason_strings = OSSL_FUNC_provider_get_reason_strings(provider_dispatch); break; # endif #endif } } #ifndef OPENSSL_NO_ERR # ifndef FIPS_MODULE if (p_get_reason_strings != NULL) { const OSSL_ITEM *reasonstrings = p_get_reason_strings(prov->provctx); size_t cnt, cnt2; /* * ERR_load_strings() handles ERR_STRING_DATA rather than OSSL_ITEM, * although they are essentially the same type. * Furthermore, ERR_load_strings() patches the array's error number * with the error library number, so we need to make a copy of that * array either way. */ cnt = 0; while (reasonstrings[cnt].id != 0) { if (ERR_GET_LIB(reasonstrings[cnt].id) != 0) goto end; cnt++; } cnt++; /* One for the terminating item */ /* Allocate one extra item for the "library" name */ prov->error_strings = OPENSSL_zalloc(sizeof(ERR_STRING_DATA) * (cnt + 1)); if (prov->error_strings == NULL) goto end; /* * Set the "library" name. */ prov->error_strings[0].error = ERR_PACK(prov->error_lib, 0, 0); prov->error_strings[0].string = prov->name; /* * Copy reasonstrings item 0..cnt-1 to prov->error_trings positions * 1..cnt. */ for (cnt2 = 1; cnt2 <= cnt; cnt2++) { prov->error_strings[cnt2].error = (int)reasonstrings[cnt2-1].id; prov->error_strings[cnt2].string = reasonstrings[cnt2-1].ptr; } ERR_load_strings(prov->error_lib, prov->error_strings); } # endif #endif /* With this flag set, this provider has become fully "loaded". */ prov->flag_initialized = 1; ok = 1; end: return ok; } /* * Deactivate a provider. If upcalls is 0 then we suppress any upcalls to a * parent provider. If removechildren is 0 then we suppress any calls to remove * child providers. * Return -1 on failure and the activation count on success */ static int provider_deactivate(OSSL_PROVIDER *prov, int upcalls, int removechildren) { int count; struct provider_store_st *store; #ifndef FIPS_MODULE int freeparent = 0; #endif int lock = 1; if (!ossl_assert(prov != NULL)) return -1; /* * No need to lock if we've got no store because we've not been shared with * other threads. */ store = get_provider_store(prov->libctx); if (store == NULL) lock = 0; if (lock && !CRYPTO_THREAD_read_lock(store->lock)) return -1; if (lock && !CRYPTO_THREAD_write_lock(prov->flag_lock)) { CRYPTO_THREAD_unlock(store->lock); return -1; } #ifndef FIPS_MODULE if (prov->activatecnt >= 2 && prov->ischild && upcalls) { /* * We have had a direct activation in this child libctx so we need to * now down the ref count in the parent provider. We do the actual down * ref outside of the flag_lock, since it could involve getting other * locks. */ freeparent = 1; } #endif if ((count = --prov->activatecnt) < 1) prov->flag_activated = 0; #ifndef FIPS_MODULE else removechildren = 0; #endif #ifndef FIPS_MODULE if (removechildren && store != NULL) { int i, max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs); OSSL_PROVIDER_CHILD_CB *child_cb; for (i = 0; i < max; i++) { child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs, i); child_cb->remove_cb((OSSL_CORE_HANDLE *)prov, child_cb->cbdata); } } #endif if (lock) { CRYPTO_THREAD_unlock(prov->flag_lock); CRYPTO_THREAD_unlock(store->lock); } #ifndef FIPS_MODULE if (freeparent) ossl_provider_free_parent(prov, 1); #endif /* We don't deinit here, that's done in ossl_provider_free() */ return count; } /* * Activate a provider. * Return -1 on failure and the activation count on success */ static int provider_activate(OSSL_PROVIDER *prov, int lock, int upcalls) { int count = -1; struct provider_store_st *store; int ret = 1; store = prov->store; /* * If the provider hasn't been added to the store, then we don't need * any locks because we've not shared it with other threads. */ if (store == NULL) { lock = 0; if (!provider_init(prov)) return -1; } #ifndef FIPS_MODULE if (prov->ischild && upcalls && !ossl_provider_up_ref_parent(prov, 1)) return -1; #endif if (lock && !CRYPTO_THREAD_read_lock(store->lock)) { #ifndef FIPS_MODULE if (prov->ischild && upcalls) ossl_provider_free_parent(prov, 1); #endif return -1; } if (lock && !CRYPTO_THREAD_write_lock(prov->flag_lock)) { CRYPTO_THREAD_unlock(store->lock); #ifndef FIPS_MODULE if (prov->ischild && upcalls) ossl_provider_free_parent(prov, 1); #endif return -1; } count = ++prov->activatecnt; prov->flag_activated = 1; if (prov->activatecnt == 1 && store != NULL) { ret = create_provider_children(prov); } if (lock) { CRYPTO_THREAD_unlock(prov->flag_lock); CRYPTO_THREAD_unlock(store->lock); } if (!ret) return -1; return count; } static int provider_flush_store_cache(const OSSL_PROVIDER *prov) { struct provider_store_st *store; int freeing; if ((store = get_provider_store(prov->libctx)) == NULL) return 0; if (!CRYPTO_THREAD_read_lock(store->lock)) return 0; freeing = store->freeing; CRYPTO_THREAD_unlock(store->lock); if (!freeing) { int acc = evp_method_store_cache_flush(prov->libctx) #ifndef FIPS_MODULE + ossl_encoder_store_cache_flush(prov->libctx) + ossl_decoder_store_cache_flush(prov->libctx) + ossl_store_loader_store_cache_flush(prov->libctx) #endif ; #ifndef FIPS_MODULE return acc == 4; #else return acc == 1; #endif } return 1; } static int provider_remove_store_methods(OSSL_PROVIDER *prov) { struct provider_store_st *store; int freeing; if ((store = get_provider_store(prov->libctx)) == NULL) return 0; if (!CRYPTO_THREAD_read_lock(store->lock)) return 0; freeing = store->freeing; CRYPTO_THREAD_unlock(store->lock); if (!freeing) { int acc; if (!CRYPTO_THREAD_write_lock(prov->opbits_lock)) return 0; OPENSSL_free(prov->operation_bits); prov->operation_bits = NULL; prov->operation_bits_sz = 0; CRYPTO_THREAD_unlock(prov->opbits_lock); acc = evp_method_store_remove_all_provided(prov) #ifndef FIPS_MODULE + ossl_encoder_store_remove_all_provided(prov) + ossl_decoder_store_remove_all_provided(prov) + ossl_store_loader_store_remove_all_provided(prov) #endif ; #ifndef FIPS_MODULE return acc == 4; #else return acc == 1; #endif } return 1; } int ossl_provider_activate(OSSL_PROVIDER *prov, int upcalls, int aschild) { int count; if (prov == NULL) return 0; #ifndef FIPS_MODULE /* * If aschild is true, then we only actually do the activation if the * provider is a child. If its not, this is still success. */ if (aschild && !prov->ischild) return 1; #endif if ((count = provider_activate(prov, 1, upcalls)) > 0) return count == 1 ? provider_flush_store_cache(prov) : 1; return 0; } int ossl_provider_deactivate(OSSL_PROVIDER *prov, int removechildren) { int count; if (prov == NULL || (count = provider_deactivate(prov, 1, removechildren)) < 0) return 0; return count == 0 ? provider_remove_store_methods(prov) : 1; } void *ossl_provider_ctx(const OSSL_PROVIDER *prov) { return prov != NULL ? prov->provctx : NULL; } /* * This function only does something once when store->use_fallbacks == 1, * and then sets store->use_fallbacks = 0, so the second call and so on is * effectively a no-op. */ static int provider_activate_fallbacks(struct provider_store_st *store) { int use_fallbacks; int activated_fallback_count = 0; int ret = 0; const OSSL_PROVIDER_INFO *p; if (!CRYPTO_THREAD_read_lock(store->lock)) return 0; use_fallbacks = store->use_fallbacks; CRYPTO_THREAD_unlock(store->lock); if (!use_fallbacks) return 1; if (!CRYPTO_THREAD_write_lock(store->lock)) return 0; /* Check again, just in case another thread changed it */ use_fallbacks = store->use_fallbacks; if (!use_fallbacks) { CRYPTO_THREAD_unlock(store->lock); return 1; } for (p = ossl_predefined_providers; p->name != NULL; p++) { OSSL_PROVIDER *prov = NULL; if (!p->is_fallback) continue; /* * We use the internal constructor directly here, * otherwise we get a call loop */ prov = provider_new(p->name, p->init, NULL); if (prov == NULL) goto err; prov->libctx = store->libctx; #ifndef FIPS_MODULE prov->error_lib = ERR_get_next_error_library(); #endif /* * We are calling provider_activate while holding the store lock. This * means the init function will be called while holding a lock. Normally * we try to avoid calling a user callback while holding a lock. * However, fallbacks are never third party providers so we accept this. */ if (provider_activate(prov, 0, 0) < 0) { ossl_provider_free(prov); goto err; } prov->store = store; if (sk_OSSL_PROVIDER_push(store->providers, prov) == 0) { ossl_provider_free(prov); goto err; } activated_fallback_count++; } if (activated_fallback_count > 0) { store->use_fallbacks = 0; ret = 1; } err: CRYPTO_THREAD_unlock(store->lock); return ret; } int ossl_provider_doall_activated(OSSL_LIB_CTX *ctx, int (*cb)(OSSL_PROVIDER *provider, void *cbdata), void *cbdata) { int ret = 0, curr, max, ref = 0; struct provider_store_st *store = get_provider_store(ctx); STACK_OF(OSSL_PROVIDER) *provs = NULL; -#ifndef FIPS_MODULE +#if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_AUTOLOAD_CONFIG) /* * Make sure any providers are loaded from config before we try to use * them. */ if (ossl_lib_ctx_is_default(ctx)) OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL); #endif if (store == NULL) return 1; if (!provider_activate_fallbacks(store)) return 0; /* * Under lock, grab a copy of the provider list and up_ref each * provider so that they don't disappear underneath us. */ if (!CRYPTO_THREAD_read_lock(store->lock)) return 0; provs = sk_OSSL_PROVIDER_dup(store->providers); if (provs == NULL) { CRYPTO_THREAD_unlock(store->lock); return 0; } max = sk_OSSL_PROVIDER_num(provs); /* * We work backwards through the stack so that we can safely delete items * as we go. */ for (curr = max - 1; curr >= 0; curr--) { OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(provs, curr); if (!CRYPTO_THREAD_write_lock(prov->flag_lock)) goto err_unlock; if (prov->flag_activated) { /* * We call CRYPTO_UP_REF directly rather than ossl_provider_up_ref * to avoid upping the ref count on the parent provider, which we * must not do while holding locks. */ if (CRYPTO_UP_REF(&prov->refcnt, &ref, prov->refcnt_lock) <= 0) { CRYPTO_THREAD_unlock(prov->flag_lock); goto err_unlock; } /* * It's already activated, but we up the activated count to ensure * it remains activated until after we've called the user callback. * We do this with no locking (because we already hold the locks) * and no upcalls (which must not be called when locks are held). In * theory this could mean the parent provider goes inactive, whilst * still activated in the child for a short period. That's ok. */ if (provider_activate(prov, 0, 0) < 0) { CRYPTO_DOWN_REF(&prov->refcnt, &ref, prov->refcnt_lock); CRYPTO_THREAD_unlock(prov->flag_lock); goto err_unlock; } } else { sk_OSSL_PROVIDER_delete(provs, curr); max--; } CRYPTO_THREAD_unlock(prov->flag_lock); } CRYPTO_THREAD_unlock(store->lock); /* * Now, we sweep through all providers not under lock */ for (curr = 0; curr < max; curr++) { OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(provs, curr); if (!cb(prov, cbdata)) { curr = -1; goto finish; } } curr = -1; ret = 1; goto finish; err_unlock: CRYPTO_THREAD_unlock(store->lock); finish: /* * The pop_free call doesn't do what we want on an error condition. We * either start from the first item in the stack, or part way through if * we only processed some of the items. */ for (curr++; curr < max; curr++) { OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(provs, curr); provider_deactivate(prov, 0, 1); /* * As above where we did the up-ref, we don't call ossl_provider_free * to avoid making upcalls. There should always be at least one ref * to the provider in the store, so this should never drop to 0. */ CRYPTO_DOWN_REF(&prov->refcnt, &ref, prov->refcnt_lock); /* * Not much we can do if this assert ever fails. So we don't use * ossl_assert here. */ assert(ref > 0); } sk_OSSL_PROVIDER_free(provs); return ret; } int OSSL_PROVIDER_available(OSSL_LIB_CTX *libctx, const char *name) { OSSL_PROVIDER *prov = NULL; int available = 0; struct provider_store_st *store = get_provider_store(libctx); if (store == NULL || !provider_activate_fallbacks(store)) return 0; prov = ossl_provider_find(libctx, name, 0); if (prov != NULL) { if (!CRYPTO_THREAD_read_lock(prov->flag_lock)) return 0; available = prov->flag_activated; CRYPTO_THREAD_unlock(prov->flag_lock); ossl_provider_free(prov); } return available; } /* Setters of Provider Object data */ int ossl_provider_set_fallback(OSSL_PROVIDER *prov) { if (prov == NULL) return 0; prov->flag_fallback = 1; return 1; } /* Getters of Provider Object data */ const char *ossl_provider_name(const OSSL_PROVIDER *prov) { return prov->name; } const DSO *ossl_provider_dso(const OSSL_PROVIDER *prov) { return prov->module; } const char *ossl_provider_module_name(const OSSL_PROVIDER *prov) { #ifdef FIPS_MODULE return NULL; #else return DSO_get_filename(prov->module); #endif } const char *ossl_provider_module_path(const OSSL_PROVIDER *prov) { #ifdef FIPS_MODULE return NULL; #else /* FIXME: Ensure it's a full path */ return DSO_get_filename(prov->module); #endif } void *ossl_provider_prov_ctx(const OSSL_PROVIDER *prov) { if (prov != NULL) return prov->provctx; return NULL; } const OSSL_DISPATCH *ossl_provider_get0_dispatch(const OSSL_PROVIDER *prov) { if (prov != NULL) return prov->dispatch; return NULL; } OSSL_LIB_CTX *ossl_provider_libctx(const OSSL_PROVIDER *prov) { return prov != NULL ? prov->libctx : NULL; } /* Wrappers around calls to the provider */ void ossl_provider_teardown(const OSSL_PROVIDER *prov) { if (prov->teardown != NULL #ifndef FIPS_MODULE && !prov->ischild #endif ) prov->teardown(prov->provctx); } const OSSL_PARAM *ossl_provider_gettable_params(const OSSL_PROVIDER *prov) { return prov->gettable_params == NULL ? NULL : prov->gettable_params(prov->provctx); } int ossl_provider_get_params(const OSSL_PROVIDER *prov, OSSL_PARAM params[]) { return prov->get_params == NULL ? 0 : prov->get_params(prov->provctx, params); } int ossl_provider_self_test(const OSSL_PROVIDER *prov) { int ret; if (prov->self_test == NULL) return 1; ret = prov->self_test(prov->provctx); if (ret == 0) (void)provider_remove_store_methods((OSSL_PROVIDER *)prov); return ret; } int ossl_provider_get_capabilities(const OSSL_PROVIDER *prov, const char *capability, OSSL_CALLBACK *cb, void *arg) { return prov->get_capabilities == NULL ? 1 : prov->get_capabilities(prov->provctx, capability, cb, arg); } const OSSL_ALGORITHM *ossl_provider_query_operation(const OSSL_PROVIDER *prov, int operation_id, int *no_cache) { const OSSL_ALGORITHM *res; if (prov->query_operation == NULL) return NULL; res = prov->query_operation(prov->provctx, operation_id, no_cache); #if defined(OPENSSL_NO_CACHED_FETCH) /* Forcing the non-caching of queries */ if (no_cache != NULL) *no_cache = 1; #endif return res; } void ossl_provider_unquery_operation(const OSSL_PROVIDER *prov, int operation_id, const OSSL_ALGORITHM *algs) { if (prov->unquery_operation != NULL) prov->unquery_operation(prov->provctx, operation_id, algs); } int ossl_provider_set_operation_bit(OSSL_PROVIDER *provider, size_t bitnum) { size_t byte = bitnum / 8; unsigned char bit = (1 << (bitnum % 8)) & 0xFF; if (!CRYPTO_THREAD_write_lock(provider->opbits_lock)) return 0; if (provider->operation_bits_sz <= byte) { unsigned char *tmp = OPENSSL_realloc(provider->operation_bits, byte + 1); if (tmp == NULL) { CRYPTO_THREAD_unlock(provider->opbits_lock); ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE); return 0; } provider->operation_bits = tmp; memset(provider->operation_bits + provider->operation_bits_sz, '\0', byte + 1 - provider->operation_bits_sz); provider->operation_bits_sz = byte + 1; } provider->operation_bits[byte] |= bit; CRYPTO_THREAD_unlock(provider->opbits_lock); return 1; } int ossl_provider_test_operation_bit(OSSL_PROVIDER *provider, size_t bitnum, int *result) { size_t byte = bitnum / 8; unsigned char bit = (1 << (bitnum % 8)) & 0xFF; if (!ossl_assert(result != NULL)) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } *result = 0; if (!CRYPTO_THREAD_read_lock(provider->opbits_lock)) return 0; if (provider->operation_bits_sz > byte) *result = ((provider->operation_bits[byte] & bit) != 0); CRYPTO_THREAD_unlock(provider->opbits_lock); return 1; } #ifndef FIPS_MODULE const OSSL_CORE_HANDLE *ossl_provider_get_parent(OSSL_PROVIDER *prov) { return prov->handle; } int ossl_provider_is_child(const OSSL_PROVIDER *prov) { return prov->ischild; } int ossl_provider_set_child(OSSL_PROVIDER *prov, const OSSL_CORE_HANDLE *handle) { prov->handle = handle; prov->ischild = 1; return 1; } int ossl_provider_default_props_update(OSSL_LIB_CTX *libctx, const char *props) { #ifndef FIPS_MODULE struct provider_store_st *store = NULL; int i, max; OSSL_PROVIDER_CHILD_CB *child_cb; if ((store = get_provider_store(libctx)) == NULL) return 0; if (!CRYPTO_THREAD_read_lock(store->lock)) return 0; max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs); for (i = 0; i < max; i++) { child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs, i); child_cb->global_props_cb(props, child_cb->cbdata); } CRYPTO_THREAD_unlock(store->lock); #endif return 1; } static int ossl_provider_register_child_cb(const OSSL_CORE_HANDLE *handle, int (*create_cb)( const OSSL_CORE_HANDLE *provider, void *cbdata), int (*remove_cb)( const OSSL_CORE_HANDLE *provider, void *cbdata), int (*global_props_cb)( const char *props, void *cbdata), void *cbdata) { /* * This is really an OSSL_PROVIDER that we created and cast to * OSSL_CORE_HANDLE originally. Therefore it is safe to cast it back. */ OSSL_PROVIDER *thisprov = (OSSL_PROVIDER *)handle; OSSL_PROVIDER *prov; OSSL_LIB_CTX *libctx = thisprov->libctx; struct provider_store_st *store = NULL; int ret = 0, i, max; OSSL_PROVIDER_CHILD_CB *child_cb; char *propsstr = NULL; if ((store = get_provider_store(libctx)) == NULL) return 0; child_cb = OPENSSL_malloc(sizeof(*child_cb)); if (child_cb == NULL) return 0; child_cb->prov = thisprov; child_cb->create_cb = create_cb; child_cb->remove_cb = remove_cb; child_cb->global_props_cb = global_props_cb; child_cb->cbdata = cbdata; if (!CRYPTO_THREAD_write_lock(store->lock)) { OPENSSL_free(child_cb); return 0; } propsstr = evp_get_global_properties_str(libctx, 0); if (propsstr != NULL) { global_props_cb(propsstr, cbdata); OPENSSL_free(propsstr); } max = sk_OSSL_PROVIDER_num(store->providers); for (i = 0; i < max; i++) { int activated; prov = sk_OSSL_PROVIDER_value(store->providers, i); if (!CRYPTO_THREAD_read_lock(prov->flag_lock)) break; activated = prov->flag_activated; CRYPTO_THREAD_unlock(prov->flag_lock); /* * We hold the store lock while calling the user callback. This means * that the user callback must be short and simple and not do anything * likely to cause a deadlock. We don't hold the flag_lock during this * call. In theory this means that another thread could deactivate it * while we are calling create. This is ok because the other thread * will also call remove_cb, but won't be able to do so until we release * the store lock. */ if (activated && !create_cb((OSSL_CORE_HANDLE *)prov, cbdata)) break; } if (i == max) { /* Success */ ret = sk_OSSL_PROVIDER_CHILD_CB_push(store->child_cbs, child_cb); } if (i != max || ret <= 0) { /* Failed during creation. Remove everything we just added */ for (; i >= 0; i--) { prov = sk_OSSL_PROVIDER_value(store->providers, i); remove_cb((OSSL_CORE_HANDLE *)prov, cbdata); } OPENSSL_free(child_cb); ret = 0; } CRYPTO_THREAD_unlock(store->lock); return ret; } static void ossl_provider_deregister_child_cb(const OSSL_CORE_HANDLE *handle) { /* * This is really an OSSL_PROVIDER that we created and cast to * OSSL_CORE_HANDLE originally. Therefore it is safe to cast it back. */ OSSL_PROVIDER *thisprov = (OSSL_PROVIDER *)handle; OSSL_LIB_CTX *libctx = thisprov->libctx; struct provider_store_st *store = NULL; int i, max; OSSL_PROVIDER_CHILD_CB *child_cb; if ((store = get_provider_store(libctx)) == NULL) return; if (!CRYPTO_THREAD_write_lock(store->lock)) return; max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs); for (i = 0; i < max; i++) { child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs, i); if (child_cb->prov == thisprov) { /* Found an entry */ sk_OSSL_PROVIDER_CHILD_CB_delete(store->child_cbs, i); OPENSSL_free(child_cb); break; } } CRYPTO_THREAD_unlock(store->lock); } #endif /*- * Core functions for the provider * =============================== * * This is the set of functions that the core makes available to the provider */ /* * This returns a list of Provider Object parameters with their types, for * discovery. We do not expect that many providers will use this, but one * never knows. */ static const OSSL_PARAM param_types[] = { OSSL_PARAM_DEFN(OSSL_PROV_PARAM_CORE_VERSION, OSSL_PARAM_UTF8_PTR, NULL, 0), OSSL_PARAM_DEFN(OSSL_PROV_PARAM_CORE_PROV_NAME, OSSL_PARAM_UTF8_PTR, NULL, 0), #ifndef FIPS_MODULE OSSL_PARAM_DEFN(OSSL_PROV_PARAM_CORE_MODULE_FILENAME, OSSL_PARAM_UTF8_PTR, NULL, 0), #endif OSSL_PARAM_END }; /* * Forward declare all the functions that are provided aa dispatch. * This ensures that the compiler will complain if they aren't defined * with the correct signature. */ static OSSL_FUNC_core_gettable_params_fn core_gettable_params; static OSSL_FUNC_core_get_params_fn core_get_params; static OSSL_FUNC_core_get_libctx_fn core_get_libctx; static OSSL_FUNC_core_thread_start_fn core_thread_start; #ifndef FIPS_MODULE static OSSL_FUNC_core_new_error_fn core_new_error; static OSSL_FUNC_core_set_error_debug_fn core_set_error_debug; static OSSL_FUNC_core_vset_error_fn core_vset_error; static OSSL_FUNC_core_set_error_mark_fn core_set_error_mark; static OSSL_FUNC_core_clear_last_error_mark_fn core_clear_last_error_mark; static OSSL_FUNC_core_pop_error_to_mark_fn core_pop_error_to_mark; OSSL_FUNC_BIO_new_file_fn ossl_core_bio_new_file; OSSL_FUNC_BIO_new_membuf_fn ossl_core_bio_new_mem_buf; OSSL_FUNC_BIO_read_ex_fn ossl_core_bio_read_ex; OSSL_FUNC_BIO_write_ex_fn ossl_core_bio_write_ex; OSSL_FUNC_BIO_gets_fn ossl_core_bio_gets; OSSL_FUNC_BIO_puts_fn ossl_core_bio_puts; OSSL_FUNC_BIO_up_ref_fn ossl_core_bio_up_ref; OSSL_FUNC_BIO_free_fn ossl_core_bio_free; OSSL_FUNC_BIO_vprintf_fn ossl_core_bio_vprintf; OSSL_FUNC_BIO_vsnprintf_fn BIO_vsnprintf; static OSSL_FUNC_self_test_cb_fn core_self_test_get_callback; OSSL_FUNC_get_entropy_fn ossl_rand_get_entropy; OSSL_FUNC_cleanup_entropy_fn ossl_rand_cleanup_entropy; OSSL_FUNC_get_nonce_fn ossl_rand_get_nonce; OSSL_FUNC_cleanup_nonce_fn ossl_rand_cleanup_nonce; #endif OSSL_FUNC_CRYPTO_malloc_fn CRYPTO_malloc; OSSL_FUNC_CRYPTO_zalloc_fn CRYPTO_zalloc; OSSL_FUNC_CRYPTO_free_fn CRYPTO_free; OSSL_FUNC_CRYPTO_clear_free_fn CRYPTO_clear_free; OSSL_FUNC_CRYPTO_realloc_fn CRYPTO_realloc; OSSL_FUNC_CRYPTO_clear_realloc_fn CRYPTO_clear_realloc; OSSL_FUNC_CRYPTO_secure_malloc_fn CRYPTO_secure_malloc; OSSL_FUNC_CRYPTO_secure_zalloc_fn CRYPTO_secure_zalloc; OSSL_FUNC_CRYPTO_secure_free_fn CRYPTO_secure_free; OSSL_FUNC_CRYPTO_secure_clear_free_fn CRYPTO_secure_clear_free; OSSL_FUNC_CRYPTO_secure_allocated_fn CRYPTO_secure_allocated; OSSL_FUNC_OPENSSL_cleanse_fn OPENSSL_cleanse; #ifndef FIPS_MODULE OSSL_FUNC_provider_register_child_cb_fn ossl_provider_register_child_cb; OSSL_FUNC_provider_deregister_child_cb_fn ossl_provider_deregister_child_cb; static OSSL_FUNC_provider_name_fn core_provider_get0_name; static OSSL_FUNC_provider_get0_provider_ctx_fn core_provider_get0_provider_ctx; static OSSL_FUNC_provider_get0_dispatch_fn core_provider_get0_dispatch; static OSSL_FUNC_provider_up_ref_fn core_provider_up_ref_intern; static OSSL_FUNC_provider_free_fn core_provider_free_intern; static OSSL_FUNC_core_obj_add_sigid_fn core_obj_add_sigid; static OSSL_FUNC_core_obj_create_fn core_obj_create; #endif static const OSSL_PARAM *core_gettable_params(const OSSL_CORE_HANDLE *handle) { return param_types; } static int core_get_params(const OSSL_CORE_HANDLE *handle, OSSL_PARAM params[]) { int i; OSSL_PARAM *p; /* * We created this object originally and we know it is actually an * OSSL_PROVIDER *, so the cast is safe */ OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle; if ((p = OSSL_PARAM_locate(params, OSSL_PROV_PARAM_CORE_VERSION)) != NULL) OSSL_PARAM_set_utf8_ptr(p, OPENSSL_VERSION_STR); if ((p = OSSL_PARAM_locate(params, OSSL_PROV_PARAM_CORE_PROV_NAME)) != NULL) OSSL_PARAM_set_utf8_ptr(p, prov->name); #ifndef FIPS_MODULE if ((p = OSSL_PARAM_locate(params, OSSL_PROV_PARAM_CORE_MODULE_FILENAME)) != NULL) OSSL_PARAM_set_utf8_ptr(p, ossl_provider_module_path(prov)); #endif if (prov->parameters == NULL) return 1; for (i = 0; i < sk_INFOPAIR_num(prov->parameters); i++) { INFOPAIR *pair = sk_INFOPAIR_value(prov->parameters, i); if ((p = OSSL_PARAM_locate(params, pair->name)) != NULL) OSSL_PARAM_set_utf8_ptr(p, pair->value); } return 1; } static OPENSSL_CORE_CTX *core_get_libctx(const OSSL_CORE_HANDLE *handle) { /* * We created this object originally and we know it is actually an * OSSL_PROVIDER *, so the cast is safe */ OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle; /* * Using ossl_provider_libctx would be wrong as that returns * NULL for |prov| == NULL and NULL libctx has a special meaning * that does not apply here. Here |prov| == NULL can happen only in * case of a coding error. */ assert(prov != NULL); return (OPENSSL_CORE_CTX *)prov->libctx; } static int core_thread_start(const OSSL_CORE_HANDLE *handle, OSSL_thread_stop_handler_fn handfn, void *arg) { /* * We created this object originally and we know it is actually an * OSSL_PROVIDER *, so the cast is safe */ OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle; return ossl_init_thread_start(prov, arg, handfn); } /* * The FIPS module inner provider doesn't implement these. They aren't * needed there, since the FIPS module upcalls are always the outer provider * ones. */ #ifndef FIPS_MODULE /* * These error functions should use |handle| to select the proper * library context to report in the correct error stack if error * stacks become tied to the library context. * We cannot currently do that since there's no support for it in the * ERR subsystem. */ static void core_new_error(const OSSL_CORE_HANDLE *handle) { ERR_new(); } static void core_set_error_debug(const OSSL_CORE_HANDLE *handle, const char *file, int line, const char *func) { ERR_set_debug(file, line, func); } static void core_vset_error(const OSSL_CORE_HANDLE *handle, uint32_t reason, const char *fmt, va_list args) { /* * We created this object originally and we know it is actually an * OSSL_PROVIDER *, so the cast is safe */ OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle; /* * If the uppermost 8 bits are non-zero, it's an OpenSSL library * error and will be treated as such. Otherwise, it's a new style * provider error and will be treated as such. */ if (ERR_GET_LIB(reason) != 0) { ERR_vset_error(ERR_GET_LIB(reason), ERR_GET_REASON(reason), fmt, args); } else { ERR_vset_error(prov->error_lib, (int)reason, fmt, args); } } static int core_set_error_mark(const OSSL_CORE_HANDLE *handle) { return ERR_set_mark(); } static int core_clear_last_error_mark(const OSSL_CORE_HANDLE *handle) { return ERR_clear_last_mark(); } static int core_pop_error_to_mark(const OSSL_CORE_HANDLE *handle) { return ERR_pop_to_mark(); } static void core_self_test_get_callback(OPENSSL_CORE_CTX *libctx, OSSL_CALLBACK **cb, void **cbarg) { OSSL_SELF_TEST_get_callback((OSSL_LIB_CTX *)libctx, cb, cbarg); } static const char *core_provider_get0_name(const OSSL_CORE_HANDLE *prov) { return OSSL_PROVIDER_get0_name((const OSSL_PROVIDER *)prov); } static void *core_provider_get0_provider_ctx(const OSSL_CORE_HANDLE *prov) { return OSSL_PROVIDER_get0_provider_ctx((const OSSL_PROVIDER *)prov); } static const OSSL_DISPATCH * core_provider_get0_dispatch(const OSSL_CORE_HANDLE *prov) { return OSSL_PROVIDER_get0_dispatch((const OSSL_PROVIDER *)prov); } static int core_provider_up_ref_intern(const OSSL_CORE_HANDLE *prov, int activate) { return provider_up_ref_intern((OSSL_PROVIDER *)prov, activate); } static int core_provider_free_intern(const OSSL_CORE_HANDLE *prov, int deactivate) { return provider_free_intern((OSSL_PROVIDER *)prov, deactivate); } static int core_obj_add_sigid(const OSSL_CORE_HANDLE *prov, const char *sign_name, const char *digest_name, const char *pkey_name) { int sign_nid = OBJ_txt2nid(sign_name); int digest_nid = NID_undef; int pkey_nid = OBJ_txt2nid(pkey_name); if (digest_name != NULL && digest_name[0] != '\0' && (digest_nid = OBJ_txt2nid(digest_name)) == NID_undef) return 0; if (sign_nid == NID_undef) return 0; /* * Check if it already exists. This is a success if so (even if we don't * have nids for the digest/pkey) */ if (OBJ_find_sigid_algs(sign_nid, NULL, NULL)) return 1; if (pkey_nid == NID_undef) return 0; return OBJ_add_sigid(sign_nid, digest_nid, pkey_nid); } static int core_obj_create(const OSSL_CORE_HANDLE *prov, const char *oid, const char *sn, const char *ln) { /* Check if it already exists and create it if not */ return OBJ_txt2nid(oid) != NID_undef || OBJ_create(oid, sn, ln) != NID_undef; } #endif /* FIPS_MODULE */ /* * Functions provided by the core. */ static const OSSL_DISPATCH core_dispatch_[] = { { OSSL_FUNC_CORE_GETTABLE_PARAMS, (void (*)(void))core_gettable_params }, { OSSL_FUNC_CORE_GET_PARAMS, (void (*)(void))core_get_params }, { OSSL_FUNC_CORE_GET_LIBCTX, (void (*)(void))core_get_libctx }, { OSSL_FUNC_CORE_THREAD_START, (void (*)(void))core_thread_start }, #ifndef FIPS_MODULE { OSSL_FUNC_CORE_NEW_ERROR, (void (*)(void))core_new_error }, { OSSL_FUNC_CORE_SET_ERROR_DEBUG, (void (*)(void))core_set_error_debug }, { OSSL_FUNC_CORE_VSET_ERROR, (void (*)(void))core_vset_error }, { OSSL_FUNC_CORE_SET_ERROR_MARK, (void (*)(void))core_set_error_mark }, { OSSL_FUNC_CORE_CLEAR_LAST_ERROR_MARK, (void (*)(void))core_clear_last_error_mark }, { OSSL_FUNC_CORE_POP_ERROR_TO_MARK, (void (*)(void))core_pop_error_to_mark }, { OSSL_FUNC_BIO_NEW_FILE, (void (*)(void))ossl_core_bio_new_file }, { OSSL_FUNC_BIO_NEW_MEMBUF, (void (*)(void))ossl_core_bio_new_mem_buf }, { OSSL_FUNC_BIO_READ_EX, (void (*)(void))ossl_core_bio_read_ex }, { OSSL_FUNC_BIO_WRITE_EX, (void (*)(void))ossl_core_bio_write_ex }, { OSSL_FUNC_BIO_GETS, (void (*)(void))ossl_core_bio_gets }, { OSSL_FUNC_BIO_PUTS, (void (*)(void))ossl_core_bio_puts }, { OSSL_FUNC_BIO_CTRL, (void (*)(void))ossl_core_bio_ctrl }, { OSSL_FUNC_BIO_UP_REF, (void (*)(void))ossl_core_bio_up_ref }, { OSSL_FUNC_BIO_FREE, (void (*)(void))ossl_core_bio_free }, { OSSL_FUNC_BIO_VPRINTF, (void (*)(void))ossl_core_bio_vprintf }, { OSSL_FUNC_BIO_VSNPRINTF, (void (*)(void))BIO_vsnprintf }, { OSSL_FUNC_SELF_TEST_CB, (void (*)(void))core_self_test_get_callback }, { OSSL_FUNC_GET_ENTROPY, (void (*)(void))ossl_rand_get_entropy }, { OSSL_FUNC_CLEANUP_ENTROPY, (void (*)(void))ossl_rand_cleanup_entropy }, { OSSL_FUNC_GET_NONCE, (void (*)(void))ossl_rand_get_nonce }, { OSSL_FUNC_CLEANUP_NONCE, (void (*)(void))ossl_rand_cleanup_nonce }, #endif { OSSL_FUNC_CRYPTO_MALLOC, (void (*)(void))CRYPTO_malloc }, { OSSL_FUNC_CRYPTO_ZALLOC, (void (*)(void))CRYPTO_zalloc }, { OSSL_FUNC_CRYPTO_FREE, (void (*)(void))CRYPTO_free }, { OSSL_FUNC_CRYPTO_CLEAR_FREE, (void (*)(void))CRYPTO_clear_free }, { OSSL_FUNC_CRYPTO_REALLOC, (void (*)(void))CRYPTO_realloc }, { OSSL_FUNC_CRYPTO_CLEAR_REALLOC, (void (*)(void))CRYPTO_clear_realloc }, { OSSL_FUNC_CRYPTO_SECURE_MALLOC, (void (*)(void))CRYPTO_secure_malloc }, { OSSL_FUNC_CRYPTO_SECURE_ZALLOC, (void (*)(void))CRYPTO_secure_zalloc }, { OSSL_FUNC_CRYPTO_SECURE_FREE, (void (*)(void))CRYPTO_secure_free }, { OSSL_FUNC_CRYPTO_SECURE_CLEAR_FREE, (void (*)(void))CRYPTO_secure_clear_free }, { OSSL_FUNC_CRYPTO_SECURE_ALLOCATED, (void (*)(void))CRYPTO_secure_allocated }, { OSSL_FUNC_OPENSSL_CLEANSE, (void (*)(void))OPENSSL_cleanse }, #ifndef FIPS_MODULE { OSSL_FUNC_PROVIDER_REGISTER_CHILD_CB, (void (*)(void))ossl_provider_register_child_cb }, { OSSL_FUNC_PROVIDER_DEREGISTER_CHILD_CB, (void (*)(void))ossl_provider_deregister_child_cb }, { OSSL_FUNC_PROVIDER_NAME, (void (*)(void))core_provider_get0_name }, { OSSL_FUNC_PROVIDER_GET0_PROVIDER_CTX, (void (*)(void))core_provider_get0_provider_ctx }, { OSSL_FUNC_PROVIDER_GET0_DISPATCH, (void (*)(void))core_provider_get0_dispatch }, { OSSL_FUNC_PROVIDER_UP_REF, (void (*)(void))core_provider_up_ref_intern }, { OSSL_FUNC_PROVIDER_FREE, (void (*)(void))core_provider_free_intern }, { OSSL_FUNC_CORE_OBJ_ADD_SIGID, (void (*)(void))core_obj_add_sigid }, { OSSL_FUNC_CORE_OBJ_CREATE, (void (*)(void))core_obj_create }, #endif { 0, NULL } }; static const OSSL_DISPATCH *core_dispatch = core_dispatch_; diff --git a/crypto/rsa/rsa_ameth.c b/crypto/rsa/rsa_ameth.c index e819780e7d94..07734077e322 100644 --- a/crypto/rsa/rsa_ameth.c +++ b/crypto/rsa/rsa_ameth.c @@ -1,1029 +1,1032 @@ /* * Copyright 2006-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include #include "internal/cryptlib.h" #include #include #include #include #include #include "crypto/asn1.h" #include "crypto/evp.h" #include "crypto/rsa.h" #include "rsa_local.h" /* Set any parameters associated with pkey */ static int rsa_param_encode(const EVP_PKEY *pkey, ASN1_STRING **pstr, int *pstrtype) { const RSA *rsa = pkey->pkey.rsa; *pstr = NULL; /* If RSA it's just NULL type */ if (RSA_test_flags(rsa, RSA_FLAG_TYPE_MASK) != RSA_FLAG_TYPE_RSASSAPSS) { *pstrtype = V_ASN1_NULL; return 1; } /* If no PSS parameters we omit parameters entirely */ if (rsa->pss == NULL) { *pstrtype = V_ASN1_UNDEF; return 1; } /* Encode PSS parameters */ if (ASN1_item_pack(rsa->pss, ASN1_ITEM_rptr(RSA_PSS_PARAMS), pstr) == NULL) return 0; *pstrtype = V_ASN1_SEQUENCE; return 1; } /* Decode any parameters and set them in RSA structure */ static int rsa_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey) { unsigned char *penc = NULL; int penclen; ASN1_STRING *str; int strtype; if (!rsa_param_encode(pkey, &str, &strtype)) return 0; penclen = i2d_RSAPublicKey(pkey->pkey.rsa, &penc); - if (penclen <= 0) + if (penclen <= 0) { + ASN1_STRING_free(str); return 0; + } if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(pkey->ameth->pkey_id), strtype, str, penc, penclen)) return 1; OPENSSL_free(penc); + ASN1_STRING_free(str); return 0; } static int rsa_pub_decode(EVP_PKEY *pkey, const X509_PUBKEY *pubkey) { const unsigned char *p; int pklen; X509_ALGOR *alg; RSA *rsa = NULL; if (!X509_PUBKEY_get0_param(NULL, &p, &pklen, &alg, pubkey)) return 0; if ((rsa = d2i_RSAPublicKey(NULL, &p, pklen)) == NULL) return 0; if (!ossl_rsa_param_decode(rsa, alg)) { RSA_free(rsa); return 0; } RSA_clear_flags(rsa, RSA_FLAG_TYPE_MASK); switch (pkey->ameth->pkey_id) { case EVP_PKEY_RSA: RSA_set_flags(rsa, RSA_FLAG_TYPE_RSA); break; case EVP_PKEY_RSA_PSS: RSA_set_flags(rsa, RSA_FLAG_TYPE_RSASSAPSS); break; default: /* Leave the type bits zero */ break; } if (!EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, rsa)) { RSA_free(rsa); return 0; } return 1; } static int rsa_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b) { /* * Don't check the public/private key, this is mostly for smart * cards. */ if (((RSA_flags(a->pkey.rsa) & RSA_METHOD_FLAG_NO_CHECK)) || (RSA_flags(b->pkey.rsa) & RSA_METHOD_FLAG_NO_CHECK)) { return 1; } 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)) == NULL) return 0; EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, 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; ASN1_STRING *str; int strtype; if (!rsa_param_encode(pkey, &str, &strtype)) return 0; rklen = i2d_RSAPrivateKey(pkey->pkey.rsa, &rk); if (rklen <= 0) { ERR_raise(ERR_LIB_RSA, ERR_R_MALLOC_FAILURE); ASN1_STRING_free(str); return 0; } if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(pkey->ameth->pkey_id), 0, strtype, str, rk, rklen)) { ERR_raise(ERR_LIB_RSA, ERR_R_MALLOC_FAILURE); ASN1_STRING_free(str); OPENSSL_clear_free(rk, rklen); return 0; } return 1; } static int rsa_priv_decode(EVP_PKEY *pkey, const PKCS8_PRIV_KEY_INFO *p8) { int ret = 0; RSA *rsa = ossl_rsa_key_from_pkcs8(p8, NULL, NULL); if (rsa != NULL) { ret = 1; EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, rsa); } return ret; } 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 int rsa_security_bits(const EVP_PKEY *pkey) { return RSA_security_bits(pkey->pkey.rsa); } static void int_rsa_free(EVP_PKEY *pkey) { RSA_free(pkey->pkey.rsa); } static int rsa_pss_param_print(BIO *bp, int pss_key, RSA_PSS_PARAMS *pss, int indent) { int rv = 0; X509_ALGOR *maskHash = NULL; if (!BIO_indent(bp, indent, 128)) goto err; if (pss_key) { if (pss == NULL) { if (BIO_puts(bp, "No PSS parameter restrictions\n") <= 0) return 0; return 1; } else { if (BIO_puts(bp, "PSS parameter restrictions:") <= 0) return 0; } } else if (pss == NULL) { if (BIO_puts(bp,"(INVALID PSS PARAMETERS)\n") <= 0) return 0; return 1; } if (BIO_puts(bp, "\n") <= 0) goto err; if (pss_key) indent += 2; 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; maskHash = ossl_x509_algor_mgf1_decode(pss->maskGenAlgorithm); if (maskHash != NULL) { 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_printf(bp, "%s Salt Length: 0x", pss_key ? "Minimum" : "") <= 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, "01 (default)") <= 0) { goto err; } BIO_puts(bp, "\n"); rv = 1; err: X509_ALGOR_free(maskHash); return rv; } static int pkey_rsa_print(BIO *bp, const EVP_PKEY *pkey, int off, int priv) { const RSA *x = pkey->pkey.rsa; char *str; const char *s; int ret = 0, mod_len = 0, ex_primes; if (x->n != NULL) mod_len = BN_num_bits(x->n); ex_primes = sk_RSA_PRIME_INFO_num(x->prime_infos); if (!BIO_indent(bp, off, 128)) goto err; if (BIO_printf(bp, "%s ", pkey_is_pss(pkey) ? "RSA-PSS" : "RSA") <= 0) goto err; if (priv && x->d) { if (BIO_printf(bp, "Private-Key: (%d bit, %d primes)\n", mod_len, ex_primes <= 0 ? 2 : ex_primes + 2) <= 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, NULL, off)) goto err; if (!ASN1_bn_print(bp, s, x->e, NULL, off)) goto err; if (priv) { int i; if (!ASN1_bn_print(bp, "privateExponent:", x->d, NULL, off)) goto err; if (!ASN1_bn_print(bp, "prime1:", x->p, NULL, off)) goto err; if (!ASN1_bn_print(bp, "prime2:", x->q, NULL, off)) goto err; if (!ASN1_bn_print(bp, "exponent1:", x->dmp1, NULL, off)) goto err; if (!ASN1_bn_print(bp, "exponent2:", x->dmq1, NULL, off)) goto err; if (!ASN1_bn_print(bp, "coefficient:", x->iqmp, NULL, off)) goto err; for (i = 0; i < sk_RSA_PRIME_INFO_num(x->prime_infos); i++) { /* print multi-prime info */ BIGNUM *bn = NULL; RSA_PRIME_INFO *pinfo; int j; pinfo = sk_RSA_PRIME_INFO_value(x->prime_infos, i); for (j = 0; j < 3; j++) { if (!BIO_indent(bp, off, 128)) goto err; switch (j) { case 0: if (BIO_printf(bp, "prime%d:", i + 3) <= 0) goto err; bn = pinfo->r; break; case 1: if (BIO_printf(bp, "exponent%d:", i + 3) <= 0) goto err; bn = pinfo->d; break; case 2: if (BIO_printf(bp, "coefficient%d:", i + 3) <= 0) goto err; bn = pinfo->t; break; default: break; } if (!ASN1_bn_print(bp, "", bn, NULL, off)) goto err; } } } if (pkey_is_pss(pkey) && !rsa_pss_param_print(bp, 1, x->pss, off)) goto err; ret = 1; err: return ret; } static int rsa_pub_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return pkey_rsa_print(bp, pkey, indent, 0); } static int rsa_priv_print(BIO *bp, const EVP_PKEY *pkey, int indent, ASN1_PCTX *ctx) { return pkey_rsa_print(bp, pkey, indent, 1); } 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) == EVP_PKEY_RSA_PSS) { int rv; RSA_PSS_PARAMS *pss = ossl_rsa_pss_decode(sigalg); rv = rsa_pss_param_print(bp, 0, pss, indent); RSA_PSS_PARAMS_free(pss); if (!rv) return 0; } else if (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) { const EVP_MD *md; const EVP_MD *mgf1md; int min_saltlen; switch (op) { case ASN1_PKEY_CTRL_DEFAULT_MD_NID: if (pkey->pkey.rsa->pss != NULL) { if (!ossl_rsa_pss_get_param(pkey->pkey.rsa->pss, &md, &mgf1md, &min_saltlen)) { ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR); return 0; } *(int *)arg2 = EVP_MD_get_type(md); /* Return of 2 indicates this MD is mandatory */ return 2; } *(int *)arg2 = NID_sha256; return 1; default: return -2; } } /* * Convert EVP_PKEY_CTX in PSS mode into corresponding algorithm parameter, * suitable for setting an AlgorithmIdentifier. */ static RSA_PSS_PARAMS *rsa_ctx_to_pss(EVP_PKEY_CTX *pkctx) { const EVP_MD *sigmd, *mgf1md; EVP_PKEY *pk = EVP_PKEY_CTX_get0_pkey(pkctx); int saltlen; if (EVP_PKEY_CTX_get_signature_md(pkctx, &sigmd) <= 0) return NULL; if (EVP_PKEY_CTX_get_rsa_mgf1_md(pkctx, &mgf1md) <= 0) return NULL; if (EVP_PKEY_CTX_get_rsa_pss_saltlen(pkctx, &saltlen) <= 0) return NULL; if (saltlen == -1) { saltlen = EVP_MD_get_size(sigmd); } else if (saltlen == -2 || saltlen == -3) { saltlen = EVP_PKEY_get_size(pk) - EVP_MD_get_size(sigmd) - 2; if ((EVP_PKEY_get_bits(pk) & 0x7) == 1) saltlen--; if (saltlen < 0) return NULL; } return ossl_rsa_pss_params_create(sigmd, mgf1md, saltlen); } RSA_PSS_PARAMS *ossl_rsa_pss_params_create(const EVP_MD *sigmd, const EVP_MD *mgf1md, int saltlen) { RSA_PSS_PARAMS *pss = RSA_PSS_PARAMS_new(); if (pss == NULL) goto err; if (saltlen != 20) { pss->saltLength = ASN1_INTEGER_new(); if (pss->saltLength == NULL) goto err; if (!ASN1_INTEGER_set(pss->saltLength, saltlen)) goto err; } if (!ossl_x509_algor_new_from_md(&pss->hashAlgorithm, sigmd)) goto err; if (mgf1md == NULL) mgf1md = sigmd; if (!ossl_x509_algor_md_to_mgf1(&pss->maskGenAlgorithm, mgf1md)) goto err; if (!ossl_x509_algor_new_from_md(&pss->maskHash, mgf1md)) goto err; return pss; err: RSA_PSS_PARAMS_free(pss); return NULL; } ASN1_STRING *ossl_rsa_ctx_to_pss_string(EVP_PKEY_CTX *pkctx) { RSA_PSS_PARAMS *pss = rsa_ctx_to_pss(pkctx); ASN1_STRING *os; if (pss == NULL) return NULL; os = ASN1_item_pack(pss, ASN1_ITEM_rptr(RSA_PSS_PARAMS), NULL); RSA_PSS_PARAMS_free(pss); return os; } /* * From PSS AlgorithmIdentifier set public key parameters. If pkey isn't NULL * then the EVP_MD_CTX is setup and initialised. If it is NULL parameters are * passed to pkctx instead. */ int ossl_rsa_pss_to_ctx(EVP_MD_CTX *ctx, EVP_PKEY_CTX *pkctx, const X509_ALGOR *sigalg, EVP_PKEY *pkey) { int rv = -1; int saltlen; const EVP_MD *mgf1md = NULL, *md = NULL; RSA_PSS_PARAMS *pss; /* Sanity check: make sure it is PSS */ if (OBJ_obj2nid(sigalg->algorithm) != EVP_PKEY_RSA_PSS) { ERR_raise(ERR_LIB_RSA, RSA_R_UNSUPPORTED_SIGNATURE_TYPE); return -1; } /* Decode PSS parameters */ pss = ossl_rsa_pss_decode(sigalg); if (!ossl_rsa_pss_get_param(pss, &md, &mgf1md, &saltlen)) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_PSS_PARAMETERS); 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_get_type(md) != EVP_MD_get_type(checkmd)) { ERR_raise(ERR_LIB_RSA, 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); return rv; } static int rsa_pss_verify_param(const EVP_MD **pmd, const EVP_MD **pmgf1md, int *psaltlen, int *ptrailerField) { if (psaltlen != NULL && *psaltlen < 0) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_SALT_LENGTH); return 0; } /* * low-level routines support only trailer field 0xbc (value 1) and * PKCS#1 says we should reject any other value anyway. */ if (ptrailerField != NULL && *ptrailerField != 1) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_TRAILER); return 0; } return 1; } int ossl_rsa_pss_get_param(const RSA_PSS_PARAMS *pss, const EVP_MD **pmd, const EVP_MD **pmgf1md, int *psaltlen) { /* * Callers do not care about the trailer field, and yet, we must * pass it from get_param to verify_param, since the latter checks * its value. * * When callers start caring, it's a simple thing to add another * argument to this function. */ int trailerField = 0; return ossl_rsa_pss_get_param_unverified(pss, pmd, pmgf1md, psaltlen, &trailerField) && rsa_pss_verify_param(pmd, pmgf1md, psaltlen, &trailerField); } /* * 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, const void *asn, const X509_ALGOR *sigalg, const ASN1_BIT_STRING *sig, EVP_PKEY *pkey) { /* Sanity check: make sure it is PSS */ if (OBJ_obj2nid(sigalg->algorithm) != EVP_PKEY_RSA_PSS) { ERR_raise(ERR_LIB_RSA, RSA_R_UNSUPPORTED_SIGNATURE_TYPE); return -1; } if (ossl_rsa_pss_to_ctx(ctx, NULL, sigalg, pkey) > 0) { /* Carry on */ return 2; } return -1; } static int rsa_item_sign(EVP_MD_CTX *ctx, const ASN1_ITEM *it, const void *asn, X509_ALGOR *alg1, X509_ALGOR *alg2, ASN1_BIT_STRING *sig) { int pad_mode; EVP_PKEY_CTX *pkctx = EVP_MD_CTX_get_pkey_ctx(ctx); 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) { unsigned char aid[128]; size_t aid_len = 0; OSSL_PARAM params[2]; if (evp_pkey_ctx_is_legacy(pkctx)) { /* No provider -> we cannot query it for algorithm ID. */ ASN1_STRING *os1 = NULL; os1 = ossl_rsa_ctx_to_pss_string(pkctx); if (os1 == NULL) return 0; /* Duplicate parameters if we have to */ if (alg2 != NULL) { ASN1_STRING *os2 = ASN1_STRING_dup(os1); if (os2 == NULL) { ASN1_STRING_free(os1); return 0; } if (!X509_ALGOR_set0(alg2, OBJ_nid2obj(EVP_PKEY_RSA_PSS), V_ASN1_SEQUENCE, os2)) { ASN1_STRING_free(os1); ASN1_STRING_free(os2); return 0; } } if (!X509_ALGOR_set0(alg1, OBJ_nid2obj(EVP_PKEY_RSA_PSS), V_ASN1_SEQUENCE, os1)) { ASN1_STRING_free(os1); return 0; } return 3; } params[0] = OSSL_PARAM_construct_octet_string( OSSL_SIGNATURE_PARAM_ALGORITHM_ID, aid, sizeof(aid)); params[1] = OSSL_PARAM_construct_end(); if (EVP_PKEY_CTX_get_params(pkctx, params) <= 0) return 0; if ((aid_len = params[0].return_size) == 0) return 0; if (alg1 != NULL) { const unsigned char *pp = aid; if (d2i_X509_ALGOR(&alg1, &pp, aid_len) == NULL) return 0; } if (alg2 != NULL) { const unsigned char *pp = aid; if (d2i_X509_ALGOR(&alg2, &pp, aid_len) == NULL) return 0; } return 3; } return 2; } static int rsa_sig_info_set(X509_SIG_INFO *siginf, const X509_ALGOR *sigalg, const ASN1_STRING *sig) { int rv = 0; int mdnid, saltlen; uint32_t flags; const EVP_MD *mgf1md = NULL, *md = NULL; RSA_PSS_PARAMS *pss; int secbits; /* Sanity check: make sure it is PSS */ if (OBJ_obj2nid(sigalg->algorithm) != EVP_PKEY_RSA_PSS) return 0; /* Decode PSS parameters */ pss = ossl_rsa_pss_decode(sigalg); if (!ossl_rsa_pss_get_param(pss, &md, &mgf1md, &saltlen)) goto err; mdnid = EVP_MD_get_type(md); /* * For TLS need SHA256, SHA384 or SHA512, digest and MGF1 digest must * match and salt length must equal digest size */ if ((mdnid == NID_sha256 || mdnid == NID_sha384 || mdnid == NID_sha512) && mdnid == EVP_MD_get_type(mgf1md) && saltlen == EVP_MD_get_size(md)) flags = X509_SIG_INFO_TLS; else flags = 0; /* Note: security bits half number of digest bits */ secbits = EVP_MD_get_size(md) * 4; /* * SHA1 and MD5 are known to be broken. Reduce security bits so that * they're no longer accepted at security level 1. The real values don't * really matter as long as they're lower than 80, which is our security * level 1. * https://eprint.iacr.org/2020/014 puts a chosen-prefix attack for SHA1 at * 2^63.4 * https://documents.epfl.ch/users/l/le/lenstra/public/papers/lat.pdf * puts a chosen-prefix attack for MD5 at 2^39. */ if (mdnid == NID_sha1) secbits = 64; else if (mdnid == NID_md5_sha1) secbits = 68; else if (mdnid == NID_md5) secbits = 39; X509_SIG_INFO_set(siginf, mdnid, EVP_PKEY_RSA_PSS, secbits, flags); rv = 1; err: RSA_PSS_PARAMS_free(pss); return rv; } static int rsa_pkey_check(const EVP_PKEY *pkey) { return RSA_check_key_ex(pkey->pkey.rsa, NULL); } static size_t rsa_pkey_dirty_cnt(const EVP_PKEY *pkey) { return pkey->pkey.rsa->dirty_cnt; } /* * There is no need to do RSA_test_flags(rsa, RSA_FLAG_TYPE_RSASSAPSS) * checks in this method since the caller tests EVP_KEYMGMT_is_a() first. */ static int rsa_int_export_to(const EVP_PKEY *from, int rsa_type, void *to_keydata, OSSL_FUNC_keymgmt_import_fn *importer, OSSL_LIB_CTX *libctx, const char *propq) { RSA *rsa = from->pkey.rsa; OSSL_PARAM_BLD *tmpl = OSSL_PARAM_BLD_new(); OSSL_PARAM *params = NULL; int selection = 0; int rv = 0; if (tmpl == NULL) return 0; /* Public parameters must always be present */ if (RSA_get0_n(rsa) == NULL || RSA_get0_e(rsa) == NULL) goto err; if (!ossl_rsa_todata(rsa, tmpl, NULL, 1)) goto err; selection |= OSSL_KEYMGMT_SELECT_PUBLIC_KEY; if (RSA_get0_d(rsa) != NULL) selection |= OSSL_KEYMGMT_SELECT_PRIVATE_KEY; if (rsa->pss != NULL) { const EVP_MD *md = NULL, *mgf1md = NULL; int md_nid, mgf1md_nid, saltlen, trailerfield; RSA_PSS_PARAMS_30 pss_params; if (!ossl_rsa_pss_get_param_unverified(rsa->pss, &md, &mgf1md, &saltlen, &trailerfield)) goto err; md_nid = EVP_MD_get_type(md); mgf1md_nid = EVP_MD_get_type(mgf1md); if (!ossl_rsa_pss_params_30_set_defaults(&pss_params) || !ossl_rsa_pss_params_30_set_hashalg(&pss_params, md_nid) || !ossl_rsa_pss_params_30_set_maskgenhashalg(&pss_params, mgf1md_nid) || !ossl_rsa_pss_params_30_set_saltlen(&pss_params, saltlen) || !ossl_rsa_pss_params_30_todata(&pss_params, tmpl, NULL)) goto err; selection |= OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS; } if ((params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) goto err; /* We export, the provider imports */ rv = importer(to_keydata, selection, params); err: OSSL_PARAM_free(params); OSSL_PARAM_BLD_free(tmpl); return rv; } static int rsa_int_import_from(const OSSL_PARAM params[], void *vpctx, int rsa_type) { EVP_PKEY_CTX *pctx = vpctx; EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(pctx); RSA *rsa = ossl_rsa_new_with_ctx(pctx->libctx); RSA_PSS_PARAMS_30 rsa_pss_params = { 0, }; int pss_defaults_set = 0; int ok = 0; if (rsa == NULL) { ERR_raise(ERR_LIB_DH, ERR_R_MALLOC_FAILURE); return 0; } RSA_clear_flags(rsa, RSA_FLAG_TYPE_MASK); RSA_set_flags(rsa, rsa_type); if (!ossl_rsa_pss_params_30_fromdata(&rsa_pss_params, &pss_defaults_set, params, pctx->libctx)) goto err; switch (rsa_type) { case RSA_FLAG_TYPE_RSA: /* * Were PSS parameters filled in? * In that case, something's wrong */ if (!ossl_rsa_pss_params_30_is_unrestricted(&rsa_pss_params)) goto err; break; case RSA_FLAG_TYPE_RSASSAPSS: /* * Were PSS parameters filled in? In that case, create the old * RSA_PSS_PARAMS structure. Otherwise, this is an unrestricted key. */ if (!ossl_rsa_pss_params_30_is_unrestricted(&rsa_pss_params)) { /* Create the older RSA_PSS_PARAMS from RSA_PSS_PARAMS_30 data */ int mdnid = ossl_rsa_pss_params_30_hashalg(&rsa_pss_params); int mgf1mdnid = ossl_rsa_pss_params_30_maskgenhashalg(&rsa_pss_params); int saltlen = ossl_rsa_pss_params_30_saltlen(&rsa_pss_params); const EVP_MD *md = EVP_get_digestbynid(mdnid); const EVP_MD *mgf1md = EVP_get_digestbynid(mgf1mdnid); if ((rsa->pss = ossl_rsa_pss_params_create(md, mgf1md, saltlen)) == NULL) goto err; } break; default: /* RSA key sub-types we don't know how to handle yet */ goto err; } if (!ossl_rsa_fromdata(rsa, params, 1)) goto err; switch (rsa_type) { case RSA_FLAG_TYPE_RSA: ok = EVP_PKEY_assign_RSA(pkey, rsa); break; case RSA_FLAG_TYPE_RSASSAPSS: ok = EVP_PKEY_assign(pkey, EVP_PKEY_RSA_PSS, rsa); break; } err: if (!ok) RSA_free(rsa); return ok; } static int rsa_pkey_export_to(const EVP_PKEY *from, void *to_keydata, OSSL_FUNC_keymgmt_import_fn *importer, OSSL_LIB_CTX *libctx, const char *propq) { return rsa_int_export_to(from, RSA_FLAG_TYPE_RSA, to_keydata, importer, libctx, propq); } static int rsa_pss_pkey_export_to(const EVP_PKEY *from, void *to_keydata, OSSL_FUNC_keymgmt_import_fn *importer, OSSL_LIB_CTX *libctx, const char *propq) { return rsa_int_export_to(from, RSA_FLAG_TYPE_RSASSAPSS, to_keydata, importer, libctx, propq); } static int rsa_pkey_import_from(const OSSL_PARAM params[], void *vpctx) { return rsa_int_import_from(params, vpctx, RSA_FLAG_TYPE_RSA); } static int rsa_pss_pkey_import_from(const OSSL_PARAM params[], void *vpctx) { return rsa_int_import_from(params, vpctx, RSA_FLAG_TYPE_RSASSAPSS); } static int rsa_pkey_copy(EVP_PKEY *to, EVP_PKEY *from) { RSA *rsa = from->pkey.rsa; RSA *dupkey = NULL; int ret; if (rsa != NULL) { dupkey = ossl_rsa_dup(rsa, OSSL_KEYMGMT_SELECT_ALL); if (dupkey == NULL) return 0; } ret = EVP_PKEY_assign(to, from->type, dupkey); if (!ret) RSA_free(dupkey); return ret; } const EVP_PKEY_ASN1_METHOD ossl_rsa_asn1_meths[2] = { { 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, rsa_security_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, rsa_sig_info_set, rsa_pkey_check, 0, 0, 0, 0, 0, 0, rsa_pkey_dirty_cnt, rsa_pkey_export_to, rsa_pkey_import_from, rsa_pkey_copy }, { EVP_PKEY_RSA2, EVP_PKEY_RSA, ASN1_PKEY_ALIAS} }; const EVP_PKEY_ASN1_METHOD ossl_rsa_pss_asn1_meth = { EVP_PKEY_RSA_PSS, EVP_PKEY_RSA_PSS, ASN1_PKEY_SIGPARAM_NULL, "RSA-PSS", "OpenSSL RSA-PSS 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, rsa_security_bits, 0, 0, 0, 0, 0, 0, rsa_sig_print, int_rsa_free, rsa_pkey_ctrl, 0, 0, rsa_item_verify, rsa_item_sign, rsa_sig_info_set, rsa_pkey_check, 0, 0, 0, 0, 0, 0, rsa_pkey_dirty_cnt, rsa_pss_pkey_export_to, rsa_pss_pkey_import_from, rsa_pkey_copy }; diff --git a/crypto/srp/srp_vfy.c b/crypto/srp/srp_vfy.c index e8beb60d278a..96d511ffe636 100644 --- a/crypto/srp/srp_vfy.c +++ b/crypto/srp/srp_vfy.c @@ -1,773 +1,774 @@ /* - * Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2004-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2004, EdelKey Project. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html * * Originally written by Christophe Renou and Peter Sylvester, * for the EdelKey project. */ /* All the SRP APIs in this file are deprecated */ #define OPENSSL_SUPPRESS_DEPRECATED #ifndef OPENSSL_NO_SRP # include "internal/cryptlib.h" # include "crypto/evp.h" # include # include # include # include # include # include # include # define SRP_RANDOM_SALT_LEN 20 # define MAX_LEN 2500 /* * Note that SRP uses its own variant of base 64 encoding. A different base64 * alphabet is used and no padding '=' characters are added. Instead we pad to * the front with 0 bytes and subsequently strip off leading encoded padding. * This variant is used for compatibility with other SRP implementations - * notably libsrp, but also others. It is also required for backwards * compatibility in order to load verifier files from other OpenSSL versions. */ /* * Convert a base64 string into raw byte array representation. * Returns the length of the decoded data, or -1 on error. */ static int t_fromb64(unsigned char *a, size_t alen, const char *src) { EVP_ENCODE_CTX *ctx; int outl = 0, outl2 = 0; size_t size, padsize; const unsigned char *pad = (const unsigned char *)"00"; while (*src == ' ' || *src == '\t' || *src == '\n') ++src; size = strlen(src); padsize = 4 - (size & 3); padsize &= 3; /* Four bytes in src become three bytes output. */ if (size > INT_MAX || ((size + padsize) / 4) * 3 > alen) return -1; ctx = EVP_ENCODE_CTX_new(); if (ctx == NULL) return -1; /* * This should never occur because 1 byte of data always requires 2 bytes of * encoding, i.e. * 0 bytes unencoded = 0 bytes encoded * 1 byte unencoded = 2 bytes encoded * 2 bytes unencoded = 3 bytes encoded * 3 bytes unencoded = 4 bytes encoded * 4 bytes unencoded = 6 bytes encoded * etc */ if (padsize == 3) { outl = -1; goto err; } /* Valid padsize values are now 0, 1 or 2 */ EVP_DecodeInit(ctx); evp_encode_ctx_set_flags(ctx, EVP_ENCODE_CTX_USE_SRP_ALPHABET); /* Add any encoded padding that is required */ if (padsize != 0 && EVP_DecodeUpdate(ctx, a, &outl, pad, padsize) < 0) { outl = -1; goto err; } if (EVP_DecodeUpdate(ctx, a, &outl2, (const unsigned char *)src, size) < 0) { outl = -1; goto err; } outl += outl2; EVP_DecodeFinal(ctx, a + outl, &outl2); outl += outl2; /* Strip off the leading padding */ if (padsize != 0) { if ((int)padsize >= outl) { outl = -1; goto err; } /* * If we added 1 byte of padding prior to encoding then we have 2 bytes * of "real" data which gets spread across 4 encoded bytes like this: * (6 bits pad)(2 bits pad | 4 bits data)(6 bits data)(6 bits data) * So 1 byte of pre-encoding padding results in 1 full byte of encoded * padding. * If we added 2 bytes of padding prior to encoding this gets encoded * as: * (6 bits pad)(6 bits pad)(4 bits pad | 2 bits data)(6 bits data) * So 2 bytes of pre-encoding padding results in 2 full bytes of encoded * padding, i.e. we have to strip the same number of bytes of padding * from the encoded data as we added to the pre-encoded data. */ memmove(a, a + padsize, outl - padsize); outl -= padsize; } err: EVP_ENCODE_CTX_free(ctx); return outl; } /* * Convert a raw byte string into a null-terminated base64 ASCII string. * Returns 1 on success or 0 on error. */ static int t_tob64(char *dst, const unsigned char *src, int size) { EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new(); int outl = 0, outl2 = 0; unsigned char pad[2] = {0, 0}; size_t leadz = 0; if (ctx == NULL) return 0; EVP_EncodeInit(ctx); evp_encode_ctx_set_flags(ctx, EVP_ENCODE_CTX_NO_NEWLINES | EVP_ENCODE_CTX_USE_SRP_ALPHABET); /* * We pad at the front with zero bytes until the length is a multiple of 3 * so that EVP_EncodeUpdate/EVP_EncodeFinal does not add any of its own "=" * padding */ leadz = 3 - (size % 3); if (leadz != 3 && !EVP_EncodeUpdate(ctx, (unsigned char *)dst, &outl, pad, leadz)) { EVP_ENCODE_CTX_free(ctx); return 0; } if (!EVP_EncodeUpdate(ctx, (unsigned char *)dst + outl, &outl2, src, size)) { EVP_ENCODE_CTX_free(ctx); return 0; } outl += outl2; EVP_EncodeFinal(ctx, (unsigned char *)dst + outl, &outl2); outl += outl2; /* Strip the encoded padding at the front */ if (leadz != 3) { memmove(dst, dst + leadz, outl - leadz); dst[outl - leadz] = '\0'; } EVP_ENCODE_CTX_free(ctx); return 1; } void SRP_user_pwd_free(SRP_user_pwd *user_pwd) { if (user_pwd == NULL) return; BN_free(user_pwd->s); BN_clear_free(user_pwd->v); OPENSSL_free(user_pwd->id); OPENSSL_free(user_pwd->info); OPENSSL_free(user_pwd); } SRP_user_pwd *SRP_user_pwd_new(void) { SRP_user_pwd *ret; if ((ret = OPENSSL_malloc(sizeof(*ret))) == NULL) { /* ERR_raise(ERR_LIB_SRP, ERR_R_MALLOC_FAILURE); */ /*ckerr_ignore*/ return NULL; } ret->N = NULL; ret->g = NULL; ret->s = NULL; ret->v = NULL; ret->id = NULL; ret->info = NULL; return ret; } void SRP_user_pwd_set_gN(SRP_user_pwd *vinfo, const BIGNUM *g, const BIGNUM *N) { vinfo->N = N; vinfo->g = g; } int SRP_user_pwd_set1_ids(SRP_user_pwd *vinfo, const char *id, const char *info) { OPENSSL_free(vinfo->id); OPENSSL_free(vinfo->info); if (id != NULL && NULL == (vinfo->id = OPENSSL_strdup(id))) return 0; return (info == NULL || NULL != (vinfo->info = OPENSSL_strdup(info))); } static int SRP_user_pwd_set_sv(SRP_user_pwd *vinfo, const char *s, const char *v) { unsigned char tmp[MAX_LEN]; int len; vinfo->v = NULL; vinfo->s = NULL; len = t_fromb64(tmp, sizeof(tmp), v); if (len < 0) return 0; if (NULL == (vinfo->v = BN_bin2bn(tmp, len, NULL))) return 0; len = t_fromb64(tmp, sizeof(tmp), s); if (len < 0) goto err; vinfo->s = BN_bin2bn(tmp, len, NULL); if (vinfo->s == NULL) goto err; return 1; err: BN_free(vinfo->v); vinfo->v = NULL; return 0; } int SRP_user_pwd_set0_sv(SRP_user_pwd *vinfo, BIGNUM *s, BIGNUM *v) { BN_free(vinfo->s); BN_clear_free(vinfo->v); vinfo->v = v; vinfo->s = s; return (vinfo->s != NULL && vinfo->v != NULL); } static SRP_user_pwd *srp_user_pwd_dup(SRP_user_pwd *src) { SRP_user_pwd *ret; if (src == NULL) return NULL; if ((ret = SRP_user_pwd_new()) == NULL) return NULL; SRP_user_pwd_set_gN(ret, src->g, src->N); if (!SRP_user_pwd_set1_ids(ret, src->id, src->info) || !SRP_user_pwd_set0_sv(ret, BN_dup(src->s), BN_dup(src->v))) { SRP_user_pwd_free(ret); return NULL; } return ret; } SRP_VBASE *SRP_VBASE_new(char *seed_key) { SRP_VBASE *vb = OPENSSL_malloc(sizeof(*vb)); if (vb == NULL) return NULL; if ((vb->users_pwd = sk_SRP_user_pwd_new_null()) == NULL || (vb->gN_cache = sk_SRP_gN_cache_new_null()) == NULL) { + sk_SRP_user_pwd_free(vb->users_pwd); OPENSSL_free(vb); return NULL; } vb->default_g = NULL; vb->default_N = NULL; vb->seed_key = NULL; if ((seed_key != NULL) && (vb->seed_key = OPENSSL_strdup(seed_key)) == NULL) { sk_SRP_user_pwd_free(vb->users_pwd); sk_SRP_gN_cache_free(vb->gN_cache); OPENSSL_free(vb); return NULL; } return vb; } void SRP_VBASE_free(SRP_VBASE *vb) { if (!vb) return; sk_SRP_user_pwd_pop_free(vb->users_pwd, SRP_user_pwd_free); sk_SRP_gN_cache_free(vb->gN_cache); OPENSSL_free(vb->seed_key); OPENSSL_free(vb); } static SRP_gN_cache *SRP_gN_new_init(const char *ch) { unsigned char tmp[MAX_LEN]; int len; SRP_gN_cache *newgN = OPENSSL_malloc(sizeof(*newgN)); if (newgN == NULL) return NULL; len = t_fromb64(tmp, sizeof(tmp), ch); if (len < 0) goto err; if ((newgN->b64_bn = OPENSSL_strdup(ch)) == NULL) goto err; if ((newgN->bn = BN_bin2bn(tmp, len, NULL))) return newgN; OPENSSL_free(newgN->b64_bn); err: OPENSSL_free(newgN); return NULL; } static void SRP_gN_free(SRP_gN_cache *gN_cache) { if (gN_cache == NULL) return; OPENSSL_free(gN_cache->b64_bn); BN_free(gN_cache->bn); OPENSSL_free(gN_cache); } static SRP_gN *SRP_get_gN_by_id(const char *id, STACK_OF(SRP_gN) *gN_tab) { int i; SRP_gN *gN; if (gN_tab != NULL) { for (i = 0; i < sk_SRP_gN_num(gN_tab); i++) { gN = sk_SRP_gN_value(gN_tab, i); if (gN && (id == NULL || strcmp(gN->id, id) == 0)) return gN; } } return SRP_get_default_gN(id); } static BIGNUM *SRP_gN_place_bn(STACK_OF(SRP_gN_cache) *gN_cache, char *ch) { int i; if (gN_cache == NULL) return NULL; /* search if we have already one... */ for (i = 0; i < sk_SRP_gN_cache_num(gN_cache); i++) { SRP_gN_cache *cache = sk_SRP_gN_cache_value(gN_cache, i); if (strcmp(cache->b64_bn, ch) == 0) return cache->bn; } { /* it is the first time that we find it */ SRP_gN_cache *newgN = SRP_gN_new_init(ch); if (newgN) { if (sk_SRP_gN_cache_insert(gN_cache, newgN, 0) > 0) return newgN->bn; SRP_gN_free(newgN); } } return NULL; } /* * This function parses the verifier file generated by the srp app. * The format for each entry is: * V base64(verifier) base64(salt) username gNid userinfo(optional) * or * I base64(N) base64(g) * Note that base64 is the SRP variant of base64 encoding described * in t_fromb64(). */ int SRP_VBASE_init(SRP_VBASE *vb, char *verifier_file) { int error_code; STACK_OF(SRP_gN) *SRP_gN_tab = sk_SRP_gN_new_null(); char *last_index = NULL; int i; char **pp; SRP_gN *gN = NULL; SRP_user_pwd *user_pwd = NULL; TXT_DB *tmpdb = NULL; BIO *in = BIO_new(BIO_s_file()); error_code = SRP_ERR_OPEN_FILE; if (in == NULL || BIO_read_filename(in, verifier_file) <= 0) goto err; error_code = SRP_ERR_VBASE_INCOMPLETE_FILE; if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL) goto err; error_code = SRP_ERR_MEMORY; if (vb->seed_key) { last_index = SRP_get_default_gN(NULL)->id; } for (i = 0; i < sk_OPENSSL_PSTRING_num(tmpdb->data); i++) { pp = sk_OPENSSL_PSTRING_value(tmpdb->data, i); if (pp[DB_srptype][0] == DB_SRP_INDEX) { /* * we add this couple in the internal Stack */ if ((gN = OPENSSL_malloc(sizeof(*gN))) == NULL) goto err; if ((gN->id = OPENSSL_strdup(pp[DB_srpid])) == NULL || (gN->N = SRP_gN_place_bn(vb->gN_cache, pp[DB_srpverifier])) == NULL || (gN->g = SRP_gN_place_bn(vb->gN_cache, pp[DB_srpsalt])) == NULL || sk_SRP_gN_insert(SRP_gN_tab, gN, 0) == 0) goto err; gN = NULL; if (vb->seed_key != NULL) { last_index = pp[DB_srpid]; } } else if (pp[DB_srptype][0] == DB_SRP_VALID) { /* it is a user .... */ const SRP_gN *lgN; if ((lgN = SRP_get_gN_by_id(pp[DB_srpgN], SRP_gN_tab)) != NULL) { error_code = SRP_ERR_MEMORY; if ((user_pwd = SRP_user_pwd_new()) == NULL) goto err; SRP_user_pwd_set_gN(user_pwd, lgN->g, lgN->N); if (!SRP_user_pwd_set1_ids (user_pwd, pp[DB_srpid], pp[DB_srpinfo])) goto err; error_code = SRP_ERR_VBASE_BN_LIB; if (!SRP_user_pwd_set_sv (user_pwd, pp[DB_srpsalt], pp[DB_srpverifier])) goto err; if (sk_SRP_user_pwd_insert(vb->users_pwd, user_pwd, 0) == 0) goto err; user_pwd = NULL; /* abandon responsibility */ } } } if (last_index != NULL) { /* this means that we want to simulate a default user */ if (((gN = SRP_get_gN_by_id(last_index, SRP_gN_tab)) == NULL)) { error_code = SRP_ERR_VBASE_BN_LIB; goto err; } vb->default_g = gN->g; vb->default_N = gN->N; gN = NULL; } error_code = SRP_NO_ERROR; err: /* * there may be still some leaks to fix, if this fails, the application * terminates most likely */ if (gN != NULL) { OPENSSL_free(gN->id); OPENSSL_free(gN); } SRP_user_pwd_free(user_pwd); TXT_DB_free(tmpdb); BIO_free_all(in); sk_SRP_gN_free(SRP_gN_tab); return error_code; } static SRP_user_pwd *find_user(SRP_VBASE *vb, char *username) { int i; SRP_user_pwd *user; if (vb == NULL) return NULL; for (i = 0; i < sk_SRP_user_pwd_num(vb->users_pwd); i++) { user = sk_SRP_user_pwd_value(vb->users_pwd, i); if (strcmp(user->id, username) == 0) return user; } return NULL; } int SRP_VBASE_add0_user(SRP_VBASE *vb, SRP_user_pwd *user_pwd) { if (sk_SRP_user_pwd_push(vb->users_pwd, user_pwd) <= 0) return 0; return 1; } # ifndef OPENSSL_NO_DEPRECATED_1_1_0 /* * DEPRECATED: use SRP_VBASE_get1_by_user instead. * This method ignores the configured seed and fails for an unknown user. * Ownership of the returned pointer is not released to the caller. * In other words, caller must not free the result. */ SRP_user_pwd *SRP_VBASE_get_by_user(SRP_VBASE *vb, char *username) { return find_user(vb, username); } # endif /* * Ownership of the returned pointer is released to the caller. * In other words, caller must free the result once done. */ SRP_user_pwd *SRP_VBASE_get1_by_user(SRP_VBASE *vb, char *username) { SRP_user_pwd *user; unsigned char digv[SHA_DIGEST_LENGTH]; unsigned char digs[SHA_DIGEST_LENGTH]; EVP_MD_CTX *ctxt = NULL; EVP_MD *md = NULL; if (vb == NULL) return NULL; if ((user = find_user(vb, username)) != NULL) return srp_user_pwd_dup(user); if ((vb->seed_key == NULL) || (vb->default_g == NULL) || (vb->default_N == NULL)) return NULL; /* if the user is unknown we set parameters as well if we have a seed_key */ if ((user = SRP_user_pwd_new()) == NULL) return NULL; SRP_user_pwd_set_gN(user, vb->default_g, vb->default_N); if (!SRP_user_pwd_set1_ids(user, username, NULL)) goto err; if (RAND_priv_bytes(digv, SHA_DIGEST_LENGTH) <= 0) goto err; md = EVP_MD_fetch(NULL, SN_sha1, NULL); if (md == NULL) goto err; ctxt = EVP_MD_CTX_new(); if (ctxt == NULL || !EVP_DigestInit_ex(ctxt, md, NULL) || !EVP_DigestUpdate(ctxt, vb->seed_key, strlen(vb->seed_key)) || !EVP_DigestUpdate(ctxt, username, strlen(username)) || !EVP_DigestFinal_ex(ctxt, digs, NULL)) goto err; EVP_MD_CTX_free(ctxt); ctxt = NULL; EVP_MD_free(md); md = NULL; if (SRP_user_pwd_set0_sv(user, BN_bin2bn(digs, SHA_DIGEST_LENGTH, NULL), BN_bin2bn(digv, SHA_DIGEST_LENGTH, NULL))) return user; err: EVP_MD_free(md); EVP_MD_CTX_free(ctxt); SRP_user_pwd_free(user); return NULL; } /* * create a verifier (*salt,*verifier,g and N are in base64) */ char *SRP_create_verifier_ex(const char *user, const char *pass, char **salt, char **verifier, const char *N, const char *g, OSSL_LIB_CTX *libctx, const char *propq) { int len; char *result = NULL, *vf = NULL; const BIGNUM *N_bn = NULL, *g_bn = NULL; BIGNUM *N_bn_alloc = NULL, *g_bn_alloc = NULL, *s = NULL, *v = NULL; unsigned char tmp[MAX_LEN]; unsigned char tmp2[MAX_LEN]; char *defgNid = NULL; int vfsize = 0; if ((user == NULL) || (pass == NULL) || (salt == NULL) || (verifier == NULL)) goto err; if (N) { if ((len = t_fromb64(tmp, sizeof(tmp), N)) <= 0) goto err; N_bn_alloc = BN_bin2bn(tmp, len, NULL); if (N_bn_alloc == NULL) goto err; N_bn = N_bn_alloc; if ((len = t_fromb64(tmp, sizeof(tmp) ,g)) <= 0) goto err; g_bn_alloc = BN_bin2bn(tmp, len, NULL); if (g_bn_alloc == NULL) goto err; g_bn = g_bn_alloc; defgNid = "*"; } else { SRP_gN *gN = SRP_get_default_gN(g); if (gN == NULL) goto err; N_bn = gN->N; g_bn = gN->g; defgNid = gN->id; } if (*salt == NULL) { if (RAND_bytes_ex(libctx, tmp2, SRP_RANDOM_SALT_LEN, 0) <= 0) goto err; s = BN_bin2bn(tmp2, SRP_RANDOM_SALT_LEN, NULL); } else { if ((len = t_fromb64(tmp2, sizeof(tmp2), *salt)) <= 0) goto err; s = BN_bin2bn(tmp2, len, NULL); } if (s == NULL) goto err; if (!SRP_create_verifier_BN_ex(user, pass, &s, &v, N_bn, g_bn, libctx, propq)) goto err; if (BN_bn2bin(v, tmp) < 0) goto err; vfsize = BN_num_bytes(v) * 2; if (((vf = OPENSSL_malloc(vfsize)) == NULL)) goto err; if (!t_tob64(vf, tmp, BN_num_bytes(v))) goto err; if (*salt == NULL) { char *tmp_salt; if ((tmp_salt = OPENSSL_malloc(SRP_RANDOM_SALT_LEN * 2)) == NULL) { goto err; } if (!t_tob64(tmp_salt, tmp2, SRP_RANDOM_SALT_LEN)) { OPENSSL_free(tmp_salt); goto err; } *salt = tmp_salt; } *verifier = vf; vf = NULL; result = defgNid; err: BN_free(N_bn_alloc); BN_free(g_bn_alloc); OPENSSL_clear_free(vf, vfsize); BN_clear_free(s); BN_clear_free(v); return result; } char *SRP_create_verifier(const char *user, const char *pass, char **salt, char **verifier, const char *N, const char *g) { return SRP_create_verifier_ex(user, pass, salt, verifier, N, g, NULL, NULL); } /* * create a verifier (*salt,*verifier,g and N are BIGNUMs). If *salt != NULL * then the provided salt will be used. On successful exit *verifier will point * to a newly allocated BIGNUM containing the verifier and (if a salt was not * provided) *salt will be populated with a newly allocated BIGNUM containing a * random salt. * The caller is responsible for freeing the allocated *salt and *verifier * BIGNUMS. */ int SRP_create_verifier_BN_ex(const char *user, const char *pass, BIGNUM **salt, BIGNUM **verifier, const BIGNUM *N, const BIGNUM *g, OSSL_LIB_CTX *libctx, const char *propq) { int result = 0; BIGNUM *x = NULL; BN_CTX *bn_ctx = BN_CTX_new_ex(libctx); unsigned char tmp2[MAX_LEN]; BIGNUM *salttmp = NULL, *verif; if ((user == NULL) || (pass == NULL) || (salt == NULL) || (verifier == NULL) || (N == NULL) || (g == NULL) || (bn_ctx == NULL)) goto err; if (*salt == NULL) { if (RAND_bytes_ex(libctx, tmp2, SRP_RANDOM_SALT_LEN, 0) <= 0) goto err; salttmp = BN_bin2bn(tmp2, SRP_RANDOM_SALT_LEN, NULL); if (salttmp == NULL) goto err; } else { salttmp = *salt; } x = SRP_Calc_x_ex(salttmp, user, pass, libctx, propq); if (x == NULL) goto err; verif = BN_new(); if (verif == NULL) goto err; if (!BN_mod_exp(verif, g, x, N, bn_ctx)) { BN_clear_free(verif); goto err; } result = 1; *salt = salttmp; *verifier = verif; err: if (salt != NULL && *salt != salttmp) BN_clear_free(salttmp); BN_clear_free(x); BN_CTX_free(bn_ctx); return result; } int SRP_create_verifier_BN(const char *user, const char *pass, BIGNUM **salt, BIGNUM **verifier, const BIGNUM *N, const BIGNUM *g) { return SRP_create_verifier_BN_ex(user, pass, salt, verifier, N, g, NULL, NULL); } #endif diff --git a/crypto/store/store_lib.c b/crypto/store/store_lib.c index 5ff927862916..bc12d8dd13a2 100644 --- a/crypto/store/store_lib.c +++ b/crypto/store/store_lib.c @@ -1,1039 +1,1039 @@ /* - * Copyright 2016-2022 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2016-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include #include #include /* We need to use some STORE deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include "e_os.h" #include #include #include #include #include #include #include #include "internal/thread_once.h" #include "internal/cryptlib.h" #include "internal/provider.h" #include "internal/bio.h" #include "crypto/store.h" #include "store_local.h" static int ossl_store_close_it(OSSL_STORE_CTX *ctx); static int loader_set_params(OSSL_STORE_LOADER *loader, OSSL_STORE_LOADER_CTX *loader_ctx, const OSSL_PARAM params[], const char *propq) { if (params != NULL) { if (!loader->p_set_ctx_params(loader_ctx, params)) return 0; } if (propq != NULL) { OSSL_PARAM propp[2]; if (OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_PROPERTIES) != NULL) /* use the propq from params */ return 1; propp[0] = OSSL_PARAM_construct_utf8_string(OSSL_STORE_PARAM_PROPERTIES, (char *)propq, 0); propp[1] = OSSL_PARAM_construct_end(); if (!loader->p_set_ctx_params(loader_ctx, propp)) return 0; } return 1; } OSSL_STORE_CTX * OSSL_STORE_open_ex(const char *uri, OSSL_LIB_CTX *libctx, const char *propq, const UI_METHOD *ui_method, void *ui_data, const OSSL_PARAM params[], OSSL_STORE_post_process_info_fn post_process, void *post_process_data) { const OSSL_STORE_LOADER *loader = NULL; OSSL_STORE_LOADER *fetched_loader = NULL; OSSL_STORE_LOADER_CTX *loader_ctx = NULL; OSSL_STORE_CTX *ctx = NULL; char *propq_copy = NULL; int no_loader_found = 1; char scheme_copy[256], *p, *schemes[2], *scheme = NULL; size_t schemes_n = 0; size_t i; /* * Put the file scheme first. If the uri does represent an existing file, * possible device name and all, then it should be loaded. Only a failed * attempt at loading a local file should have us try something else. */ schemes[schemes_n++] = "file"; /* * Now, check if we have something that looks like a scheme, and add it * as a second scheme. However, also check if there's an authority start * (://), because that will invalidate the previous file scheme. Also, * check that this isn't actually the file scheme, as there's no point * going through that one twice! */ OPENSSL_strlcpy(scheme_copy, uri, sizeof(scheme_copy)); if ((p = strchr(scheme_copy, ':')) != NULL) { *p++ = '\0'; if (OPENSSL_strcasecmp(scheme_copy, "file") != 0) { if (strncmp(p, "//", 2) == 0) schemes_n--; /* Invalidate the file scheme */ schemes[schemes_n++] = scheme_copy; } } ERR_set_mark(); /* * Try each scheme until we find one that could open the URI. * * For each scheme, we look for the engine implementation first, and * failing that, we then try to fetch a provided implementation. * This is consistent with how we handle legacy / engine implementations * elsewhere. */ for (i = 0; loader_ctx == NULL && i < schemes_n; i++) { scheme = schemes[i]; OSSL_TRACE1(STORE, "Looking up scheme %s\n", scheme); #ifndef OPENSSL_NO_DEPRECATED_3_0 if ((loader = ossl_store_get0_loader_int(scheme)) != NULL) { no_loader_found = 0; if (loader->open_ex != NULL) loader_ctx = loader->open_ex(loader, uri, libctx, propq, ui_method, ui_data); else loader_ctx = loader->open(loader, uri, ui_method, ui_data); } #endif if (loader == NULL && (fetched_loader = OSSL_STORE_LOADER_fetch(libctx, scheme, propq)) != NULL) { const OSSL_PROVIDER *provider = OSSL_STORE_LOADER_get0_provider(fetched_loader); void *provctx = OSSL_PROVIDER_get0_provider_ctx(provider); no_loader_found = 0; loader_ctx = fetched_loader->p_open(provctx, uri); if (loader_ctx == NULL) { OSSL_STORE_LOADER_free(fetched_loader); fetched_loader = NULL; } else if(!loader_set_params(fetched_loader, loader_ctx, params, propq)) { (void)fetched_loader->p_close(loader_ctx); OSSL_STORE_LOADER_free(fetched_loader); fetched_loader = NULL; } loader = fetched_loader; } } if (no_loader_found) /* * It's assumed that ossl_store_get0_loader_int() and * OSSL_STORE_LOADER_fetch() report their own errors */ goto err; OSSL_TRACE1(STORE, "Found loader for scheme %s\n", scheme); if (loader_ctx == NULL) /* * It's assumed that the loader's open() method reports its own * errors */ goto err; OSSL_TRACE2(STORE, "Opened %s => %p\n", uri, (void *)loader_ctx); if ((propq != NULL && (propq_copy = OPENSSL_strdup(propq)) == NULL) || (ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_MALLOC_FAILURE); goto err; } if (ui_method != NULL && (!ossl_pw_set_ui_method(&ctx->pwdata, ui_method, ui_data) || !ossl_pw_enable_passphrase_caching(&ctx->pwdata))) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_CRYPTO_LIB); goto err; } ctx->properties = propq_copy; ctx->fetched_loader = fetched_loader; ctx->loader = loader; ctx->loader_ctx = loader_ctx; ctx->post_process = post_process; ctx->post_process_data = post_process_data; /* * If the attempt to open with the 'file' scheme loader failed and the * other scheme loader succeeded, the failure to open with the 'file' * scheme loader leaves an error on the error stack. Let's remove it. */ ERR_pop_to_mark(); return ctx; err: ERR_clear_last_mark(); if (loader_ctx != NULL) { /* * Temporary structure so OSSL_STORE_close() can work even when * |ctx| couldn't be allocated properly */ OSSL_STORE_CTX tmpctx = { NULL, }; tmpctx.fetched_loader = fetched_loader; tmpctx.loader = loader; tmpctx.loader_ctx = loader_ctx; /* * We ignore a returned error because we will return NULL anyway in * this case, so if something goes wrong when closing, that'll simply * just add another entry on the error stack. */ (void)ossl_store_close_it(&tmpctx); } OSSL_STORE_LOADER_free(fetched_loader); OPENSSL_free(propq_copy); OPENSSL_free(ctx); return NULL; } OSSL_STORE_CTX *OSSL_STORE_open(const char *uri, const UI_METHOD *ui_method, void *ui_data, OSSL_STORE_post_process_info_fn post_process, void *post_process_data) { return OSSL_STORE_open_ex(uri, NULL, NULL, ui_method, ui_data, NULL, post_process, post_process_data); } #ifndef OPENSSL_NO_DEPRECATED_3_0 int OSSL_STORE_ctrl(OSSL_STORE_CTX *ctx, int cmd, ...) { va_list args; int ret; va_start(args, cmd); ret = OSSL_STORE_vctrl(ctx, cmd, args); va_end(args); return ret; } int OSSL_STORE_vctrl(OSSL_STORE_CTX *ctx, int cmd, va_list args) { if (ctx->fetched_loader != NULL) { if (ctx->fetched_loader->p_set_ctx_params != NULL) { OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; switch (cmd) { case OSSL_STORE_C_USE_SECMEM: { int on = *(va_arg(args, int *)); params[0] = OSSL_PARAM_construct_int("use_secmem", &on); } break; default: break; } return ctx->fetched_loader->p_set_ctx_params(ctx->loader_ctx, params); } } else if (ctx->loader->ctrl != NULL) { return ctx->loader->ctrl(ctx->loader_ctx, cmd, args); } /* * If the fetched loader doesn't have a set_ctx_params or a ctrl, it's as * if there was one that ignored our params, which usually returns 1. */ return 1; } #endif int OSSL_STORE_expect(OSSL_STORE_CTX *ctx, int expected_type) { int ret = 1; if (ctx == NULL || expected_type < 0 || expected_type > OSSL_STORE_INFO_CRL) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (ctx->loading) { ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_LOADING_STARTED); return 0; } ctx->expected_type = expected_type; if (ctx->fetched_loader != NULL && ctx->fetched_loader->p_set_ctx_params != NULL) { OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; params[0] = OSSL_PARAM_construct_int(OSSL_STORE_PARAM_EXPECT, &expected_type); ret = ctx->fetched_loader->p_set_ctx_params(ctx->loader_ctx, params); } #ifndef OPENSSL_NO_DEPRECATED_3_0 if (ctx->fetched_loader == NULL && ctx->loader->expect != NULL) { ret = ctx->loader->expect(ctx->loader_ctx, expected_type); } #endif return ret; } int OSSL_STORE_find(OSSL_STORE_CTX *ctx, const OSSL_STORE_SEARCH *search) { int ret = 1; if (ctx->loading) { ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_LOADING_STARTED); return 0; } if (search == NULL) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (ctx->fetched_loader != NULL) { OSSL_PARAM_BLD *bld; OSSL_PARAM *params; /* OSSL_STORE_SEARCH_BY_NAME, OSSL_STORE_SEARCH_BY_ISSUER_SERIAL*/ void *name_der = NULL; int name_der_sz; /* OSSL_STORE_SEARCH_BY_ISSUER_SERIAL */ BIGNUM *number = NULL; if (ctx->fetched_loader->p_set_ctx_params == NULL) { ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_UNSUPPORTED_OPERATION); return 0; } if ((bld = OSSL_PARAM_BLD_new()) == NULL) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_MALLOC_FAILURE); return 0; } ret = 0; /* Assume the worst */ switch (search->search_type) { case OSSL_STORE_SEARCH_BY_NAME: if ((name_der_sz = i2d_X509_NAME(search->name, (unsigned char **)&name_der)) > 0 && OSSL_PARAM_BLD_push_octet_string(bld, OSSL_STORE_PARAM_SUBJECT, name_der, name_der_sz)) ret = 1; break; case OSSL_STORE_SEARCH_BY_ISSUER_SERIAL: if ((name_der_sz = i2d_X509_NAME(search->name, (unsigned char **)&name_der)) > 0 && (number = ASN1_INTEGER_to_BN(search->serial, NULL)) != NULL && OSSL_PARAM_BLD_push_octet_string(bld, OSSL_STORE_PARAM_ISSUER, name_der, name_der_sz) && OSSL_PARAM_BLD_push_BN(bld, OSSL_STORE_PARAM_SERIAL, number)) ret = 1; break; case OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT: if (OSSL_PARAM_BLD_push_utf8_string(bld, OSSL_STORE_PARAM_DIGEST, EVP_MD_get0_name(search->digest), 0) && OSSL_PARAM_BLD_push_octet_string(bld, OSSL_STORE_PARAM_FINGERPRINT, search->string, search->stringlength)) ret = 1; break; case OSSL_STORE_SEARCH_BY_ALIAS: if (OSSL_PARAM_BLD_push_utf8_string(bld, OSSL_STORE_PARAM_ALIAS, (char *)search->string, search->stringlength)) ret = 1; break; } if (ret) { params = OSSL_PARAM_BLD_to_param(bld); ret = ctx->fetched_loader->p_set_ctx_params(ctx->loader_ctx, params); OSSL_PARAM_free(params); } OSSL_PARAM_BLD_free(bld); OPENSSL_free(name_der); BN_free(number); } else { #ifndef OPENSSL_NO_DEPRECATED_3_0 /* legacy loader section */ if (ctx->loader->find == NULL) { ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_UNSUPPORTED_OPERATION); return 0; } ret = ctx->loader->find(ctx->loader_ctx, search); #endif } return ret; } OSSL_STORE_INFO *OSSL_STORE_load(OSSL_STORE_CTX *ctx) { OSSL_STORE_INFO *v = NULL; ctx->loading = 1; again: if (OSSL_STORE_eof(ctx)) return NULL; if (ctx->loader != NULL) OSSL_TRACE(STORE, "Loading next object\n"); if (ctx->cached_info != NULL && sk_OSSL_STORE_INFO_num(ctx->cached_info) == 0) { sk_OSSL_STORE_INFO_free(ctx->cached_info); ctx->cached_info = NULL; } if (ctx->cached_info != NULL) { v = sk_OSSL_STORE_INFO_shift(ctx->cached_info); } else { if (ctx->fetched_loader != NULL) { struct ossl_load_result_data_st load_data; load_data.v = NULL; load_data.ctx = ctx; + ctx->error_flag = 0; if (!ctx->fetched_loader->p_load(ctx->loader_ctx, ossl_store_handle_load_result, &load_data, ossl_pw_passphrase_callback_dec, &ctx->pwdata)) { - if (!OSSL_STORE_eof(ctx)) - ctx->error_flag = 1; + ctx->error_flag = 1; return NULL; } v = load_data.v; } #ifndef OPENSSL_NO_DEPRECATED_3_0 if (ctx->fetched_loader == NULL) v = ctx->loader->load(ctx->loader_ctx, ctx->pwdata._.ui_method.ui_method, ctx->pwdata._.ui_method.ui_method_data); #endif } if (ctx->post_process != NULL && v != NULL) { v = ctx->post_process(v, ctx->post_process_data); /* * By returning NULL, the callback decides that this object should * be ignored. */ if (v == NULL) goto again; } /* Clear any internally cached passphrase */ (void)ossl_pw_clear_passphrase_cache(&ctx->pwdata); if (v != NULL && ctx->expected_type != 0) { int returned_type = OSSL_STORE_INFO_get_type(v); if (returned_type != OSSL_STORE_INFO_NAME && returned_type != 0) { if (ctx->expected_type != returned_type) { OSSL_STORE_INFO_free(v); goto again; } } } if (v != NULL) OSSL_TRACE1(STORE, "Got a %s\n", OSSL_STORE_INFO_type_string(OSSL_STORE_INFO_get_type(v))); return v; } int OSSL_STORE_error(OSSL_STORE_CTX *ctx) { int ret = 1; if (ctx->fetched_loader != NULL) ret = ctx->error_flag; #ifndef OPENSSL_NO_DEPRECATED_3_0 if (ctx->fetched_loader == NULL) ret = ctx->loader->error(ctx->loader_ctx); #endif return ret; } int OSSL_STORE_eof(OSSL_STORE_CTX *ctx) { int ret = 1; if (ctx->fetched_loader != NULL) ret = ctx->loader->p_eof(ctx->loader_ctx); #ifndef OPENSSL_NO_DEPRECATED_3_0 if (ctx->fetched_loader == NULL) ret = ctx->loader->eof(ctx->loader_ctx); #endif return ret != 0; } static int ossl_store_close_it(OSSL_STORE_CTX *ctx) { int ret = 0; if (ctx == NULL) return 1; OSSL_TRACE1(STORE, "Closing %p\n", (void *)ctx->loader_ctx); if (ctx->fetched_loader != NULL) ret = ctx->loader->p_close(ctx->loader_ctx); #ifndef OPENSSL_NO_DEPRECATED_3_0 if (ctx->fetched_loader == NULL) ret = ctx->loader->closefn(ctx->loader_ctx); #endif sk_OSSL_STORE_INFO_pop_free(ctx->cached_info, OSSL_STORE_INFO_free); OSSL_STORE_LOADER_free(ctx->fetched_loader); OPENSSL_free(ctx->properties); ossl_pw_clear_passphrase_data(&ctx->pwdata); return ret; } int OSSL_STORE_close(OSSL_STORE_CTX *ctx) { int ret = ossl_store_close_it(ctx); OPENSSL_free(ctx); return ret; } /* * Functions to generate OSSL_STORE_INFOs, one function for each type we * support having in them as well as a generic constructor. * * In all cases, ownership of the object is transferred to the OSSL_STORE_INFO * and will therefore be freed when the OSSL_STORE_INFO is freed. */ OSSL_STORE_INFO *OSSL_STORE_INFO_new(int type, void *data) { OSSL_STORE_INFO *info = OPENSSL_zalloc(sizeof(*info)); if (info == NULL) return NULL; info->type = type; info->_.data = data; return info; } OSSL_STORE_INFO *OSSL_STORE_INFO_new_NAME(char *name) { OSSL_STORE_INFO *info = OSSL_STORE_INFO_new(OSSL_STORE_INFO_NAME, NULL); if (info == NULL) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_MALLOC_FAILURE); return NULL; } info->_.name.name = name; info->_.name.desc = NULL; return info; } int OSSL_STORE_INFO_set0_NAME_description(OSSL_STORE_INFO *info, char *desc) { if (info->type != OSSL_STORE_INFO_NAME) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } info->_.name.desc = desc; return 1; } OSSL_STORE_INFO *OSSL_STORE_INFO_new_PARAMS(EVP_PKEY *params) { OSSL_STORE_INFO *info = OSSL_STORE_INFO_new(OSSL_STORE_INFO_PARAMS, params); if (info == NULL) ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_MALLOC_FAILURE); return info; } OSSL_STORE_INFO *OSSL_STORE_INFO_new_PUBKEY(EVP_PKEY *pkey) { OSSL_STORE_INFO *info = OSSL_STORE_INFO_new(OSSL_STORE_INFO_PUBKEY, pkey); if (info == NULL) ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_MALLOC_FAILURE); return info; } OSSL_STORE_INFO *OSSL_STORE_INFO_new_PKEY(EVP_PKEY *pkey) { OSSL_STORE_INFO *info = OSSL_STORE_INFO_new(OSSL_STORE_INFO_PKEY, pkey); if (info == NULL) ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_MALLOC_FAILURE); return info; } OSSL_STORE_INFO *OSSL_STORE_INFO_new_CERT(X509 *x509) { OSSL_STORE_INFO *info = OSSL_STORE_INFO_new(OSSL_STORE_INFO_CERT, x509); if (info == NULL) ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_MALLOC_FAILURE); return info; } OSSL_STORE_INFO *OSSL_STORE_INFO_new_CRL(X509_CRL *crl) { OSSL_STORE_INFO *info = OSSL_STORE_INFO_new(OSSL_STORE_INFO_CRL, crl); if (info == NULL) ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_MALLOC_FAILURE); return info; } /* * Functions to try to extract data from a OSSL_STORE_INFO. */ int OSSL_STORE_INFO_get_type(const OSSL_STORE_INFO *info) { return info->type; } void *OSSL_STORE_INFO_get0_data(int type, const OSSL_STORE_INFO *info) { if (info->type == type) return info->_.data; return NULL; } const char *OSSL_STORE_INFO_get0_NAME(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_NAME) return info->_.name.name; return NULL; } char *OSSL_STORE_INFO_get1_NAME(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_NAME) { char *ret = OPENSSL_strdup(info->_.name.name); if (ret == NULL) ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_MALLOC_FAILURE); return ret; } ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_NOT_A_NAME); return NULL; } const char *OSSL_STORE_INFO_get0_NAME_description(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_NAME) return info->_.name.desc; return NULL; } char *OSSL_STORE_INFO_get1_NAME_description(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_NAME) { char *ret = OPENSSL_strdup(info->_.name.desc ? info->_.name.desc : ""); if (ret == NULL) ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_MALLOC_FAILURE); return ret; } ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_NOT_A_NAME); return NULL; } EVP_PKEY *OSSL_STORE_INFO_get0_PARAMS(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_PARAMS) return info->_.params; return NULL; } EVP_PKEY *OSSL_STORE_INFO_get1_PARAMS(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_PARAMS) { EVP_PKEY_up_ref(info->_.params); return info->_.params; } ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_NOT_PARAMETERS); return NULL; } EVP_PKEY *OSSL_STORE_INFO_get0_PUBKEY(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_PUBKEY) return info->_.pubkey; return NULL; } EVP_PKEY *OSSL_STORE_INFO_get1_PUBKEY(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_PUBKEY) { EVP_PKEY_up_ref(info->_.pubkey); return info->_.pubkey; } ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_NOT_A_PUBLIC_KEY); return NULL; } EVP_PKEY *OSSL_STORE_INFO_get0_PKEY(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_PKEY) return info->_.pkey; return NULL; } EVP_PKEY *OSSL_STORE_INFO_get1_PKEY(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_PKEY) { EVP_PKEY_up_ref(info->_.pkey); return info->_.pkey; } ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_NOT_A_PRIVATE_KEY); return NULL; } X509 *OSSL_STORE_INFO_get0_CERT(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_CERT) return info->_.x509; return NULL; } X509 *OSSL_STORE_INFO_get1_CERT(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_CERT) { X509_up_ref(info->_.x509); return info->_.x509; } ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_NOT_A_CERTIFICATE); return NULL; } X509_CRL *OSSL_STORE_INFO_get0_CRL(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_CRL) return info->_.crl; return NULL; } X509_CRL *OSSL_STORE_INFO_get1_CRL(const OSSL_STORE_INFO *info) { if (info->type == OSSL_STORE_INFO_CRL) { X509_CRL_up_ref(info->_.crl); return info->_.crl; } ERR_raise(ERR_LIB_OSSL_STORE, OSSL_STORE_R_NOT_A_CRL); return NULL; } /* * Free the OSSL_STORE_INFO */ void OSSL_STORE_INFO_free(OSSL_STORE_INFO *info) { if (info != NULL) { switch (info->type) { case OSSL_STORE_INFO_NAME: OPENSSL_free(info->_.name.name); OPENSSL_free(info->_.name.desc); break; case OSSL_STORE_INFO_PARAMS: EVP_PKEY_free(info->_.params); break; case OSSL_STORE_INFO_PUBKEY: EVP_PKEY_free(info->_.pubkey); break; case OSSL_STORE_INFO_PKEY: EVP_PKEY_free(info->_.pkey); break; case OSSL_STORE_INFO_CERT: X509_free(info->_.x509); break; case OSSL_STORE_INFO_CRL: X509_CRL_free(info->_.crl); break; } OPENSSL_free(info); } } int OSSL_STORE_supports_search(OSSL_STORE_CTX *ctx, int search_type) { int ret = 0; if (ctx->fetched_loader != NULL) { void *provctx = ossl_provider_ctx(OSSL_STORE_LOADER_get0_provider(ctx->fetched_loader)); const OSSL_PARAM *params; const OSSL_PARAM *p_subject = NULL; const OSSL_PARAM *p_issuer = NULL; const OSSL_PARAM *p_serial = NULL; const OSSL_PARAM *p_fingerprint = NULL; const OSSL_PARAM *p_alias = NULL; if (ctx->fetched_loader->p_settable_ctx_params == NULL) return 0; params = ctx->fetched_loader->p_settable_ctx_params(provctx); p_subject = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_SUBJECT); p_issuer = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_ISSUER); p_serial = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_SERIAL); p_fingerprint = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_FINGERPRINT); p_alias = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_ALIAS); switch (search_type) { case OSSL_STORE_SEARCH_BY_NAME: ret = (p_subject != NULL); break; case OSSL_STORE_SEARCH_BY_ISSUER_SERIAL: ret = (p_issuer != NULL && p_serial != NULL); break; case OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT: ret = (p_fingerprint != NULL); break; case OSSL_STORE_SEARCH_BY_ALIAS: ret = (p_alias != NULL); break; } } #ifndef OPENSSL_NO_DEPRECATED_3_0 if (ctx->fetched_loader == NULL) { OSSL_STORE_SEARCH tmp_search; if (ctx->loader->find == NULL) return 0; tmp_search.search_type = search_type; ret = ctx->loader->find(NULL, &tmp_search); } #endif return ret; } /* Search term constructors */ OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_name(X509_NAME *name) { OSSL_STORE_SEARCH *search = OPENSSL_zalloc(sizeof(*search)); if (search == NULL) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_MALLOC_FAILURE); return NULL; } search->search_type = OSSL_STORE_SEARCH_BY_NAME; search->name = name; return search; } OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_issuer_serial(X509_NAME *name, const ASN1_INTEGER *serial) { OSSL_STORE_SEARCH *search = OPENSSL_zalloc(sizeof(*search)); if (search == NULL) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_MALLOC_FAILURE); return NULL; } search->search_type = OSSL_STORE_SEARCH_BY_ISSUER_SERIAL; search->name = name; search->serial = serial; return search; } OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_key_fingerprint(const EVP_MD *digest, const unsigned char *bytes, size_t len) { OSSL_STORE_SEARCH *search = OPENSSL_zalloc(sizeof(*search)); if (search == NULL) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_MALLOC_FAILURE); return NULL; } if (digest != NULL && len != (size_t)EVP_MD_get_size(digest)) { ERR_raise_data(ERR_LIB_OSSL_STORE, OSSL_STORE_R_FINGERPRINT_SIZE_DOES_NOT_MATCH_DIGEST, "%s size is %d, fingerprint size is %zu", EVP_MD_get0_name(digest), EVP_MD_get_size(digest), len); OPENSSL_free(search); return NULL; } search->search_type = OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT; search->digest = digest; search->string = bytes; search->stringlength = len; return search; } OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_alias(const char *alias) { OSSL_STORE_SEARCH *search = OPENSSL_zalloc(sizeof(*search)); if (search == NULL) { ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_MALLOC_FAILURE); return NULL; } search->search_type = OSSL_STORE_SEARCH_BY_ALIAS; search->string = (const unsigned char *)alias; search->stringlength = strlen(alias); return search; } /* Search term destructor */ void OSSL_STORE_SEARCH_free(OSSL_STORE_SEARCH *search) { OPENSSL_free(search); } /* Search term accessors */ int OSSL_STORE_SEARCH_get_type(const OSSL_STORE_SEARCH *criterion) { return criterion->search_type; } X509_NAME *OSSL_STORE_SEARCH_get0_name(const OSSL_STORE_SEARCH *criterion) { return criterion->name; } const ASN1_INTEGER *OSSL_STORE_SEARCH_get0_serial(const OSSL_STORE_SEARCH *criterion) { return criterion->serial; } const unsigned char *OSSL_STORE_SEARCH_get0_bytes(const OSSL_STORE_SEARCH *criterion, size_t *length) { *length = criterion->stringlength; return criterion->string; } const char *OSSL_STORE_SEARCH_get0_string(const OSSL_STORE_SEARCH *criterion) { return (const char *)criterion->string; } const EVP_MD *OSSL_STORE_SEARCH_get0_digest(const OSSL_STORE_SEARCH *criterion) { return criterion->digest; } OSSL_STORE_CTX *OSSL_STORE_attach(BIO *bp, const char *scheme, OSSL_LIB_CTX *libctx, const char *propq, const UI_METHOD *ui_method, void *ui_data, const OSSL_PARAM params[], OSSL_STORE_post_process_info_fn post_process, void *post_process_data) { const OSSL_STORE_LOADER *loader = NULL; OSSL_STORE_LOADER *fetched_loader = NULL; OSSL_STORE_LOADER_CTX *loader_ctx = NULL; OSSL_STORE_CTX *ctx = NULL; if (scheme == NULL) scheme = "file"; OSSL_TRACE1(STORE, "Looking up scheme %s\n", scheme); ERR_set_mark(); #ifndef OPENSSL_NO_DEPRECATED_3_0 if ((loader = ossl_store_get0_loader_int(scheme)) != NULL) loader_ctx = loader->attach(loader, bp, libctx, propq, ui_method, ui_data); #endif if (loader == NULL && (fetched_loader = OSSL_STORE_LOADER_fetch(libctx, scheme, propq)) != NULL) { const OSSL_PROVIDER *provider = OSSL_STORE_LOADER_get0_provider(fetched_loader); void *provctx = OSSL_PROVIDER_get0_provider_ctx(provider); OSSL_CORE_BIO *cbio = ossl_core_bio_new_from_bio(bp); if (cbio == NULL || (loader_ctx = fetched_loader->p_attach(provctx, cbio)) == NULL) { OSSL_STORE_LOADER_free(fetched_loader); fetched_loader = NULL; } else if (!loader_set_params(fetched_loader, loader_ctx, params, propq)) { (void)fetched_loader->p_close(loader_ctx); OSSL_STORE_LOADER_free(fetched_loader); fetched_loader = NULL; } loader = fetched_loader; ossl_core_bio_free(cbio); } if (loader_ctx == NULL) { ERR_clear_last_mark(); return NULL; } if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL) { ERR_clear_last_mark(); ERR_raise(ERR_LIB_OSSL_STORE, ERR_R_MALLOC_FAILURE); return NULL; } if (ui_method != NULL && !ossl_pw_set_ui_method(&ctx->pwdata, ui_method, ui_data)) { ERR_clear_last_mark(); OPENSSL_free(ctx); return NULL; } ctx->fetched_loader = fetched_loader; ctx->loader = loader; ctx->loader_ctx = loader_ctx; ctx->post_process = post_process; ctx->post_process_data = post_process_data; /* * ossl_store_get0_loader_int will raise an error if the loader for the * the scheme cannot be retrieved. But if a loader was successfully * fetched then we remove this error from the error stack. */ ERR_pop_to_mark(); return ctx; } diff --git a/crypto/threads_pthread.c b/crypto/threads_pthread.c index bfc05a4e878c..801855c9306e 100644 --- a/crypto/threads_pthread.c +++ b/crypto/threads_pthread.c @@ -1,286 +1,284 @@ /* - * Copyright 2016-2022 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2016-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* We need to use the OPENSSL_fork_*() deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include #include "internal/cryptlib.h" #if defined(__sun) # include #endif #if defined(__apple_build_version__) && __apple_build_version__ < 6000000 /* * OS/X 10.7 and 10.8 had a weird version of clang which has __ATOMIC_ACQUIRE and * __ATOMIC_ACQ_REL but which expects only one parameter for __atomic_is_lock_free() * rather than two which has signature __atomic_is_lock_free(sizeof(_Atomic(T))). * All of this makes impossible to use __atomic_is_lock_free here. * * See: https://github.com/llvm/llvm-project/commit/a4c2602b714e6c6edb98164550a5ae829b2de760 */ #define BROKEN_CLANG_ATOMICS #endif #if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) && !defined(OPENSSL_SYS_WINDOWS) # if defined(OPENSSL_SYS_UNIX) # include # include #endif # include # ifdef PTHREAD_RWLOCK_INITIALIZER # define USE_RWLOCK # endif CRYPTO_RWLOCK *CRYPTO_THREAD_lock_new(void) { # ifdef USE_RWLOCK CRYPTO_RWLOCK *lock; if ((lock = OPENSSL_zalloc(sizeof(pthread_rwlock_t))) == NULL) { /* Don't set error, to avoid recursion blowup. */ return NULL; } if (pthread_rwlock_init(lock, NULL) != 0) { OPENSSL_free(lock); return NULL; } # else pthread_mutexattr_t attr; CRYPTO_RWLOCK *lock; if ((lock = OPENSSL_zalloc(sizeof(pthread_mutex_t))) == NULL) { /* Don't set error, to avoid recursion blowup. */ return NULL; } /* * We don't use recursive mutexes, but try to catch errors if we do. */ pthread_mutexattr_init(&attr); # if !defined (__TANDEM) && !defined (_SPT_MODEL_) # if !defined(NDEBUG) && !defined(OPENSSL_NO_MUTEX_ERRORCHECK) pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); -# else - pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL); # endif # else /* The SPT Thread Library does not define MUTEX attributes. */ # endif if (pthread_mutex_init(lock, &attr) != 0) { pthread_mutexattr_destroy(&attr); OPENSSL_free(lock); return NULL; } pthread_mutexattr_destroy(&attr); # endif return lock; } __owur int CRYPTO_THREAD_read_lock(CRYPTO_RWLOCK *lock) { # ifdef USE_RWLOCK if (pthread_rwlock_rdlock(lock) != 0) return 0; # else if (pthread_mutex_lock(lock) != 0) { assert(errno != EDEADLK && errno != EBUSY); return 0; } # endif return 1; } __owur int CRYPTO_THREAD_write_lock(CRYPTO_RWLOCK *lock) { # ifdef USE_RWLOCK if (pthread_rwlock_wrlock(lock) != 0) return 0; # else if (pthread_mutex_lock(lock) != 0) { assert(errno != EDEADLK && errno != EBUSY); return 0; } # endif return 1; } int CRYPTO_THREAD_unlock(CRYPTO_RWLOCK *lock) { # ifdef USE_RWLOCK if (pthread_rwlock_unlock(lock) != 0) return 0; # else if (pthread_mutex_unlock(lock) != 0) { assert(errno != EPERM); return 0; } # endif return 1; } void CRYPTO_THREAD_lock_free(CRYPTO_RWLOCK *lock) { if (lock == NULL) return; # ifdef USE_RWLOCK pthread_rwlock_destroy(lock); # else pthread_mutex_destroy(lock); # endif OPENSSL_free(lock); return; } int CRYPTO_THREAD_run_once(CRYPTO_ONCE *once, void (*init)(void)) { if (pthread_once(once, init) != 0) return 0; return 1; } int CRYPTO_THREAD_init_local(CRYPTO_THREAD_LOCAL *key, void (*cleanup)(void *)) { if (pthread_key_create(key, cleanup) != 0) return 0; return 1; } void *CRYPTO_THREAD_get_local(CRYPTO_THREAD_LOCAL *key) { return pthread_getspecific(*key); } int CRYPTO_THREAD_set_local(CRYPTO_THREAD_LOCAL *key, void *val) { if (pthread_setspecific(*key, val) != 0) return 0; return 1; } int CRYPTO_THREAD_cleanup_local(CRYPTO_THREAD_LOCAL *key) { if (pthread_key_delete(*key) != 0) return 0; return 1; } CRYPTO_THREAD_ID CRYPTO_THREAD_get_current_id(void) { return pthread_self(); } int CRYPTO_THREAD_compare_id(CRYPTO_THREAD_ID a, CRYPTO_THREAD_ID b) { return pthread_equal(a, b); } int CRYPTO_atomic_add(int *val, int amount, int *ret, CRYPTO_RWLOCK *lock) { # if defined(__GNUC__) && defined(__ATOMIC_ACQ_REL) && !defined(BROKEN_CLANG_ATOMICS) if (__atomic_is_lock_free(sizeof(*val), val)) { *ret = __atomic_add_fetch(val, amount, __ATOMIC_ACQ_REL); return 1; } # elif defined(__sun) && (defined(__SunOS_5_10) || defined(__SunOS_5_11)) /* This will work for all future Solaris versions. */ if (ret != NULL) { *ret = atomic_add_int_nv((volatile unsigned int *)val, amount); return 1; } # endif if (lock == NULL || !CRYPTO_THREAD_write_lock(lock)) return 0; *val += amount; *ret = *val; if (!CRYPTO_THREAD_unlock(lock)) return 0; return 1; } int CRYPTO_atomic_or(uint64_t *val, uint64_t op, uint64_t *ret, CRYPTO_RWLOCK *lock) { # if defined(__GNUC__) && defined(__ATOMIC_ACQ_REL) && !defined(BROKEN_CLANG_ATOMICS) if (__atomic_is_lock_free(sizeof(*val), val)) { *ret = __atomic_or_fetch(val, op, __ATOMIC_ACQ_REL); return 1; } # elif defined(__sun) && (defined(__SunOS_5_10) || defined(__SunOS_5_11)) /* This will work for all future Solaris versions. */ if (ret != NULL) { *ret = atomic_or_64_nv(val, op); return 1; } # endif if (lock == NULL || !CRYPTO_THREAD_write_lock(lock)) return 0; *val |= op; *ret = *val; if (!CRYPTO_THREAD_unlock(lock)) return 0; return 1; } int CRYPTO_atomic_load(uint64_t *val, uint64_t *ret, CRYPTO_RWLOCK *lock) { # if defined(__GNUC__) && defined(__ATOMIC_ACQUIRE) && !defined(BROKEN_CLANG_ATOMICS) if (__atomic_is_lock_free(sizeof(*val), val)) { __atomic_load(val, ret, __ATOMIC_ACQUIRE); return 1; } # elif defined(__sun) && (defined(__SunOS_5_10) || defined(__SunOS_5_11)) /* This will work for all future Solaris versions. */ if (ret != NULL) { *ret = atomic_or_64_nv(val, 0); return 1; } # endif if (lock == NULL || !CRYPTO_THREAD_read_lock(lock)) return 0; *ret = *val; if (!CRYPTO_THREAD_unlock(lock)) return 0; return 1; } # ifndef FIPS_MODULE int openssl_init_fork_handlers(void) { return 1; } # endif /* FIPS_MODULE */ int openssl_get_fork_id(void) { return getpid(); } #endif diff --git a/crypto/x509/v3_ist.c b/crypto/x509/v3_ist.c index e6fef0153c8e..4a3cfa12a471 100644 --- a/crypto/x509/v3_ist.c +++ b/crypto/x509/v3_ist.c @@ -1,144 +1,144 @@ /* * Copyright 2020-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include #include "internal/cryptlib.h" #include #include #include #include #include "ext_dat.h" /* * Issuer Sign Tool (1.2.643.100.112) The name of the tool used to signs the subject (ASN1_SEQUENCE) * This extention is required to obtain the status of a qualified certificate at Russian Federation. * RFC-style description is available here: https://tools.ietf.org/html/draft-deremin-rfc4491-bis-04#section-5 * Russian Federal Law 63 "Digital Sign" is available here: http://www.consultant.ru/document/cons_doc_LAW_112701/ */ ASN1_SEQUENCE(ISSUER_SIGN_TOOL) = { ASN1_SIMPLE(ISSUER_SIGN_TOOL, signTool, ASN1_UTF8STRING), ASN1_SIMPLE(ISSUER_SIGN_TOOL, cATool, ASN1_UTF8STRING), ASN1_SIMPLE(ISSUER_SIGN_TOOL, signToolCert, ASN1_UTF8STRING), ASN1_SIMPLE(ISSUER_SIGN_TOOL, cAToolCert, ASN1_UTF8STRING) } ASN1_SEQUENCE_END(ISSUER_SIGN_TOOL) IMPLEMENT_ASN1_FUNCTIONS(ISSUER_SIGN_TOOL) static ISSUER_SIGN_TOOL *v2i_issuer_sign_tool(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval) { ISSUER_SIGN_TOOL *ist = ISSUER_SIGN_TOOL_new(); int i; if (ist == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_MALLOC_FAILURE); return NULL; } for (i = 0; i < sk_CONF_VALUE_num(nval); ++i) { CONF_VALUE *cnf = sk_CONF_VALUE_value(nval, i); if (cnf == NULL) { continue; } if (strcmp(cnf->name, "signTool") == 0) { ist->signTool = ASN1_UTF8STRING_new(); if (ist->signTool == NULL || !ASN1_STRING_set(ist->signTool, cnf->value, strlen(cnf->value))) { - ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); + ERR_raise(ERR_LIB_X509V3, ERR_R_MALLOC_FAILURE); goto err; } } else if (strcmp(cnf->name, "cATool") == 0) { ist->cATool = ASN1_UTF8STRING_new(); if (ist->cATool == NULL || !ASN1_STRING_set(ist->cATool, cnf->value, strlen(cnf->value))) { - ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); + ERR_raise(ERR_LIB_X509V3, ERR_R_MALLOC_FAILURE); goto err; } } else if (strcmp(cnf->name, "signToolCert") == 0) { ist->signToolCert = ASN1_UTF8STRING_new(); if (ist->signToolCert == NULL || !ASN1_STRING_set(ist->signToolCert, cnf->value, strlen(cnf->value))) { - ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); + ERR_raise(ERR_LIB_X509V3, ERR_R_MALLOC_FAILURE); goto err; } } else if (strcmp(cnf->name, "cAToolCert") == 0) { ist->cAToolCert = ASN1_UTF8STRING_new(); if (ist->cAToolCert == NULL || !ASN1_STRING_set(ist->cAToolCert, cnf->value, strlen(cnf->value))) { - ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB); + ERR_raise(ERR_LIB_X509V3, ERR_R_MALLOC_FAILURE); goto err; } } else { ERR_raise(ERR_LIB_X509V3, ERR_R_PASSED_INVALID_ARGUMENT); goto err; } } return ist; err: ISSUER_SIGN_TOOL_free(ist); return NULL; } static int i2r_issuer_sign_tool(X509V3_EXT_METHOD *method, ISSUER_SIGN_TOOL *ist, BIO *out, int indent) { int new_line = 0; if (ist == NULL) { ERR_raise(ERR_LIB_X509V3, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (ist->signTool != NULL) { if (new_line == 1) { BIO_write(out, "\n", 1); } BIO_printf(out, "%*ssignTool : ", indent, ""); BIO_write(out, ist->signTool->data, ist->signTool->length); new_line = 1; } if (ist->cATool != NULL) { if (new_line == 1) { BIO_write(out, "\n", 1); } BIO_printf(out, "%*scATool : ", indent, ""); BIO_write(out, ist->cATool->data, ist->cATool->length); new_line = 1; } if (ist->signToolCert != NULL) { if (new_line == 1) { BIO_write(out, "\n", 1); } BIO_printf(out, "%*ssignToolCert: ", indent, ""); BIO_write(out, ist->signToolCert->data, ist->signToolCert->length); new_line = 1; } if (ist->cAToolCert != NULL) { if (new_line == 1) { BIO_write(out, "\n", 1); } BIO_printf(out, "%*scAToolCert : ", indent, ""); BIO_write(out, ist->cAToolCert->data, ist->cAToolCert->length); new_line = 1; } return 1; } const X509V3_EXT_METHOD ossl_v3_issuer_sign_tool = { NID_issuerSignTool, /* nid */ X509V3_EXT_MULTILINE, /* flags */ ASN1_ITEM_ref(ISSUER_SIGN_TOOL), /* template */ 0, 0, 0, 0, /* old functions, ignored */ 0, /* i2s */ 0, /* s2i */ 0, /* i2v */ (X509V3_EXT_V2I)v2i_issuer_sign_tool, /* v2i */ (X509V3_EXT_I2R)i2r_issuer_sign_tool, /* i2r */ 0, /* r2i */ NULL /* extension-specific data */ }; diff --git a/crypto/x509/x509_cmp.c b/crypto/x509/x509_cmp.c index 1027bed82e69..989fb8faa9f4 100644 --- a/crypto/x509/x509_cmp.c +++ b/crypto/x509/x509_cmp.c @@ -1,585 +1,588 @@ /* * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include #include "internal/cryptlib.h" #include #include #include #include #include #include "crypto/x509.h" int X509_issuer_and_serial_cmp(const X509 *a, const X509 *b) { int i; const X509_CINF *ai, *bi; if (b == NULL) return a != NULL; if (a == NULL) return -1; ai = &a->cert_info; bi = &b->cert_info; i = ASN1_INTEGER_cmp(&ai->serialNumber, &bi->serialNumber); if (i != 0) return i < 0 ? -1 : 1; return X509_NAME_cmp(ai->issuer, bi->issuer); } #ifndef OPENSSL_NO_MD5 unsigned long X509_issuer_and_serial_hash(X509 *a) { unsigned long ret = 0; EVP_MD_CTX *ctx = EVP_MD_CTX_new(); unsigned char md[16]; char *f = NULL; EVP_MD *digest = NULL; if (ctx == NULL) goto err; f = X509_NAME_oneline(a->cert_info.issuer, NULL, 0); if (f == NULL) goto err; digest = EVP_MD_fetch(a->libctx, SN_md5, a->propq); if (digest == NULL) goto err; if (!EVP_DigestInit_ex(ctx, digest, NULL)) goto err; if (!EVP_DigestUpdate(ctx, (unsigned char *)f, strlen(f))) goto err; if (!EVP_DigestUpdate (ctx, (unsigned char *)a->cert_info.serialNumber.data, (unsigned long)a->cert_info.serialNumber.length)) goto err; if (!EVP_DigestFinal_ex(ctx, &(md[0]), NULL)) goto err; ret = (((unsigned long)md[0]) | ((unsigned long)md[1] << 8L) | ((unsigned long)md[2] << 16L) | ((unsigned long)md[3] << 24L) ) & 0xffffffffL; err: OPENSSL_free(f); EVP_MD_free(digest); EVP_MD_CTX_free(ctx); return ret; } #endif int X509_issuer_name_cmp(const X509 *a, const X509 *b) { return X509_NAME_cmp(a->cert_info.issuer, b->cert_info.issuer); } int X509_subject_name_cmp(const X509 *a, const X509 *b) { return X509_NAME_cmp(a->cert_info.subject, b->cert_info.subject); } int X509_CRL_cmp(const X509_CRL *a, const X509_CRL *b) { return X509_NAME_cmp(a->crl.issuer, b->crl.issuer); } int X509_CRL_match(const X509_CRL *a, const X509_CRL *b) { int rv; if ((a->flags & EXFLAG_NO_FINGERPRINT) == 0 && (b->flags & EXFLAG_NO_FINGERPRINT) == 0) rv = memcmp(a->sha1_hash, b->sha1_hash, SHA_DIGEST_LENGTH); else return -2; return rv < 0 ? -1 : rv > 0; } X509_NAME *X509_get_issuer_name(const X509 *a) { return a->cert_info.issuer; } unsigned long X509_issuer_name_hash(X509 *x) { return X509_NAME_hash_ex(x->cert_info.issuer, NULL, NULL, NULL); } #ifndef OPENSSL_NO_MD5 unsigned long X509_issuer_name_hash_old(X509 *x) { return X509_NAME_hash_old(x->cert_info.issuer); } #endif X509_NAME *X509_get_subject_name(const X509 *a) { return a->cert_info.subject; } ASN1_INTEGER *X509_get_serialNumber(X509 *a) { return &a->cert_info.serialNumber; } const ASN1_INTEGER *X509_get0_serialNumber(const X509 *a) { return &a->cert_info.serialNumber; } unsigned long X509_subject_name_hash(X509 *x) { return X509_NAME_hash_ex(x->cert_info.subject, NULL, NULL, NULL); } #ifndef OPENSSL_NO_MD5 unsigned long X509_subject_name_hash_old(X509 *x) { return X509_NAME_hash_old(x->cert_info.subject); } #endif /* * Compare two certificates: they must be identical for this to work. NB: * Although "cmp" operations are generally prototyped to take "const" * arguments (eg. for use in STACKs), the way X509 handling is - these * operations may involve ensuring the hashes are up-to-date and ensuring * certain cert information is cached. So this is the point where the * "depth-first" constification tree has to halt with an evil cast. */ int X509_cmp(const X509 *a, const X509 *b) { int rv = 0; if (a == b) /* for efficiency */ return 0; /* attempt to compute cert hash */ (void)X509_check_purpose((X509 *)a, -1, 0); (void)X509_check_purpose((X509 *)b, -1, 0); if ((a->ex_flags & EXFLAG_NO_FINGERPRINT) == 0 && (b->ex_flags & EXFLAG_NO_FINGERPRINT) == 0) rv = memcmp(a->sha1_hash, b->sha1_hash, SHA_DIGEST_LENGTH); if (rv != 0) return rv < 0 ? -1 : 1; /* Check for match against stored encoding too */ if (!a->cert_info.enc.modified && !b->cert_info.enc.modified) { if (a->cert_info.enc.len < b->cert_info.enc.len) return -1; if (a->cert_info.enc.len > b->cert_info.enc.len) return 1; rv = memcmp(a->cert_info.enc.enc, b->cert_info.enc.enc, a->cert_info.enc.len); } return rv < 0 ? -1 : rv > 0; } int ossl_x509_add_cert_new(STACK_OF(X509) **p_sk, X509 *cert, int flags) { if (*p_sk == NULL && (*p_sk = sk_X509_new_null()) == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE); return 0; } return X509_add_cert(*p_sk, cert, flags); } int X509_add_cert(STACK_OF(X509) *sk, X509 *cert, int flags) { if (sk == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER); return 0; } if ((flags & X509_ADD_FLAG_NO_DUP) != 0) { /* * not using sk_X509_set_cmp_func() and sk_X509_find() * because this re-orders the certs on the stack */ int i; for (i = 0; i < sk_X509_num(sk); i++) { if (X509_cmp(sk_X509_value(sk, i), cert) == 0) return 1; } } if ((flags & X509_ADD_FLAG_NO_SS) != 0) { int ret = X509_self_signed(cert, 0); if (ret != 0) return ret > 0 ? 1 : 0; } if (!sk_X509_insert(sk, cert, (flags & X509_ADD_FLAG_PREPEND) != 0 ? 0 : -1)) { ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE); return 0; } if ((flags & X509_ADD_FLAG_UP_REF) != 0) (void)X509_up_ref(cert); return 1; } int X509_add_certs(STACK_OF(X509) *sk, STACK_OF(X509) *certs, int flags) /* compiler would allow 'const' for the certs, yet they may get up-ref'ed */ { if (sk == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER); return 0; } return ossl_x509_add_certs_new(&sk, certs, flags); } int ossl_x509_add_certs_new(STACK_OF(X509) **p_sk, STACK_OF(X509) *certs, int flags) /* compiler would allow 'const' for the certs, yet they may get up-ref'ed */ { int n = sk_X509_num(certs /* may be NULL */); int i; for (i = 0; i < n; i++) { int j = (flags & X509_ADD_FLAG_PREPEND) == 0 ? i : n - 1 - i; /* if prepend, add certs in reverse order to keep original order */ if (!ossl_x509_add_cert_new(p_sk, sk_X509_value(certs, j), flags)) return 0; } return 1; } int X509_NAME_cmp(const X509_NAME *a, const X509_NAME *b) { int ret; if (b == NULL) return a != NULL; if (a == NULL) return -1; /* Ensure canonical encoding is present and up to date */ if (a->canon_enc == NULL || a->modified) { ret = i2d_X509_NAME((X509_NAME *)a, NULL); if (ret < 0) return -2; } if (b->canon_enc == NULL || b->modified) { ret = i2d_X509_NAME((X509_NAME *)b, NULL); if (ret < 0) return -2; } ret = a->canon_enclen - b->canon_enclen; if (ret == 0 && a->canon_enclen == 0) return 0; if (ret == 0) { if (a->canon_enc == NULL || b->canon_enc == NULL) return -2; ret = memcmp(a->canon_enc, b->canon_enc, a->canon_enclen); } return ret < 0 ? -1 : ret > 0; } unsigned long X509_NAME_hash_ex(const X509_NAME *x, OSSL_LIB_CTX *libctx, const char *propq, int *ok) { unsigned long ret = 0; unsigned char md[SHA_DIGEST_LENGTH]; EVP_MD *sha1 = EVP_MD_fetch(libctx, "SHA1", propq); + int i2d_ret; /* Make sure X509_NAME structure contains valid cached encoding */ - i2d_X509_NAME(x, NULL); + i2d_ret = i2d_X509_NAME(x, NULL); if (ok != NULL) *ok = 0; - if (sha1 != NULL + if (i2d_ret >= 0 && sha1 != NULL && EVP_Digest(x->canon_enc, x->canon_enclen, md, NULL, sha1, NULL)) { ret = (((unsigned long)md[0]) | ((unsigned long)md[1] << 8L) | ((unsigned long)md[2] << 16L) | ((unsigned long)md[3] << 24L) ) & 0xffffffffL; if (ok != NULL) *ok = 1; } EVP_MD_free(sha1); return ret; } #ifndef OPENSSL_NO_MD5 /* * I now DER encode the name and hash it. Since I cache the DER encoding, * this is reasonably efficient. */ unsigned long X509_NAME_hash_old(const X509_NAME *x) { EVP_MD *md5 = EVP_MD_fetch(NULL, OSSL_DIGEST_NAME_MD5, "-fips"); EVP_MD_CTX *md_ctx = EVP_MD_CTX_new(); unsigned long ret = 0; unsigned char md[16]; if (md5 == NULL || md_ctx == NULL) goto end; /* Make sure X509_NAME structure contains valid cached encoding */ - i2d_X509_NAME(x, NULL); + if (i2d_X509_NAME(x, NULL) < 0) + goto end; + if (EVP_DigestInit_ex(md_ctx, md5, NULL) && EVP_DigestUpdate(md_ctx, x->bytes->data, x->bytes->length) && EVP_DigestFinal_ex(md_ctx, md, NULL)) ret = (((unsigned long)md[0]) | ((unsigned long)md[1] << 8L) | ((unsigned long)md[2] << 16L) | ((unsigned long)md[3] << 24L) ) & 0xffffffffL; end: EVP_MD_CTX_free(md_ctx); EVP_MD_free(md5); return ret; } #endif /* Search a stack of X509 for a match */ X509 *X509_find_by_issuer_and_serial(STACK_OF(X509) *sk, const X509_NAME *name, const ASN1_INTEGER *serial) { int i; X509 x, *x509 = NULL; if (!sk) return NULL; x.cert_info.serialNumber = *serial; x.cert_info.issuer = (X509_NAME *)name; /* won't modify it */ for (i = 0; i < sk_X509_num(sk); i++) { x509 = sk_X509_value(sk, i); if (X509_issuer_and_serial_cmp(x509, &x) == 0) return x509; } return NULL; } X509 *X509_find_by_subject(STACK_OF(X509) *sk, const X509_NAME *name) { X509 *x509; int i; for (i = 0; i < sk_X509_num(sk); i++) { x509 = sk_X509_value(sk, i); if (X509_NAME_cmp(X509_get_subject_name(x509), name) == 0) return x509; } return NULL; } EVP_PKEY *X509_get0_pubkey(const X509 *x) { if (x == NULL) return NULL; return X509_PUBKEY_get0(x->cert_info.key); } EVP_PKEY *X509_get_pubkey(X509 *x) { if (x == NULL) return NULL; return X509_PUBKEY_get(x->cert_info.key); } int X509_check_private_key(const X509 *x, const EVP_PKEY *k) { const EVP_PKEY *xk; int ret; xk = X509_get0_pubkey(x); if (xk == NULL) { ERR_raise(ERR_LIB_X509, X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY); return 0; } switch (ret = EVP_PKEY_eq(xk, k)) { case 0: ERR_raise(ERR_LIB_X509, X509_R_KEY_VALUES_MISMATCH); break; case -1: ERR_raise(ERR_LIB_X509, X509_R_KEY_TYPE_MISMATCH); break; case -2: ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_KEY_TYPE); break; } return ret > 0; } /* * Check a suite B algorithm is permitted: pass in a public key and the NID * of its signature (or 0 if no signature). The pflags is a pointer to a * flags field which must contain the suite B verification flags. */ #ifndef OPENSSL_NO_EC static int check_suite_b(EVP_PKEY *pkey, int sign_nid, unsigned long *pflags) { char curve_name[80]; size_t curve_name_len; int curve_nid; if (pkey == NULL || !EVP_PKEY_is_a(pkey, "EC")) return X509_V_ERR_SUITE_B_INVALID_ALGORITHM; if (!EVP_PKEY_get_group_name(pkey, curve_name, sizeof(curve_name), &curve_name_len)) return X509_V_ERR_SUITE_B_INVALID_CURVE; curve_nid = OBJ_txt2nid(curve_name); /* Check curve is consistent with LOS */ if (curve_nid == NID_secp384r1) { /* P-384 */ /* * Check signature algorithm is consistent with curve. */ if (sign_nid != -1 && sign_nid != NID_ecdsa_with_SHA384) return X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM; if (!(*pflags & X509_V_FLAG_SUITEB_192_LOS)) return X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED; /* If we encounter P-384 we cannot use P-256 later */ *pflags &= ~X509_V_FLAG_SUITEB_128_LOS_ONLY; } else if (curve_nid == NID_X9_62_prime256v1) { /* P-256 */ if (sign_nid != -1 && sign_nid != NID_ecdsa_with_SHA256) return X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM; if (!(*pflags & X509_V_FLAG_SUITEB_128_LOS_ONLY)) return X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED; } else { return X509_V_ERR_SUITE_B_INVALID_CURVE; } return X509_V_OK; } int X509_chain_check_suiteb(int *perror_depth, X509 *x, STACK_OF(X509) *chain, unsigned long flags) { int rv, i, sign_nid; EVP_PKEY *pk; unsigned long tflags = flags; if (!(flags & X509_V_FLAG_SUITEB_128_LOS)) return X509_V_OK; /* If no EE certificate passed in must be first in chain */ if (x == NULL) { x = sk_X509_value(chain, 0); i = 1; } else { i = 0; } pk = X509_get0_pubkey(x); /* * With DANE-EE(3) success, or DANE-EE(3)/PKIX-EE(1) failure we don't build * a chain all, just report trust success or failure, but must also report * Suite-B errors if applicable. This is indicated via a NULL chain * pointer. All we need to do is check the leaf key algorithm. */ if (chain == NULL) return check_suite_b(pk, -1, &tflags); if (X509_get_version(x) != X509_VERSION_3) { rv = X509_V_ERR_SUITE_B_INVALID_VERSION; /* Correct error depth */ i = 0; goto end; } /* Check EE key only */ rv = check_suite_b(pk, -1, &tflags); if (rv != X509_V_OK) { /* Correct error depth */ i = 0; goto end; } for (; i < sk_X509_num(chain); i++) { sign_nid = X509_get_signature_nid(x); x = sk_X509_value(chain, i); if (X509_get_version(x) != X509_VERSION_3) { rv = X509_V_ERR_SUITE_B_INVALID_VERSION; goto end; } pk = X509_get0_pubkey(x); rv = check_suite_b(pk, sign_nid, &tflags); if (rv != X509_V_OK) goto end; } /* Final check: root CA signature */ rv = check_suite_b(pk, X509_get_signature_nid(x), &tflags); end: if (rv != X509_V_OK) { /* Invalid signature or LOS errors are for previous cert */ if ((rv == X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM || rv == X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED) && i) i--; /* * If we have LOS error and flags changed then we are signing P-384 * with P-256. Use more meaningful error. */ if (rv == X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED && flags != tflags) rv = X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256; if (perror_depth) *perror_depth = i; } return rv; } int X509_CRL_check_suiteb(X509_CRL *crl, EVP_PKEY *pk, unsigned long flags) { int sign_nid; if (!(flags & X509_V_FLAG_SUITEB_128_LOS)) return X509_V_OK; sign_nid = OBJ_obj2nid(crl->crl.sig_alg.algorithm); return check_suite_b(pk, sign_nid, &flags); } #else int X509_chain_check_suiteb(int *perror_depth, X509 *x, STACK_OF(X509) *chain, unsigned long flags) { return 0; } int X509_CRL_check_suiteb(X509_CRL *crl, EVP_PKEY *pk, unsigned long flags) { return 0; } #endif /* * Not strictly speaking an "up_ref" as a STACK doesn't have a reference * count but it has the same effect by duping the STACK and upping the ref of * each X509 structure. */ STACK_OF(X509) *X509_chain_up_ref(STACK_OF(X509) *chain) { STACK_OF(X509) *ret = sk_X509_dup(chain); int i; if (ret == NULL) return NULL; for (i = 0; i < sk_X509_num(ret); i++) { X509 *x = sk_X509_value(ret, i); if (!X509_up_ref(x)) goto err; } return ret; err: while (i-- > 0) X509_free(sk_X509_value(ret, i)); sk_X509_free(ret); return NULL; } diff --git a/doc/man1/openssl-cmp.pod.in b/doc/man1/openssl-cmp.pod.in index 4250deb426fc..9240916fce40 100644 --- a/doc/man1/openssl-cmp.pod.in +++ b/doc/man1/openssl-cmp.pod.in @@ -1,1298 +1,1307 @@ =pod {- OpenSSL::safe::output_do_not_edit_headers(); -} =head1 NAME openssl-cmp - Certificate Management Protocol (CMP, RFC 4210) application =head1 SYNOPSIS B B [B<-help>] [B<-config> I] [B<-section> I] [B<-verbosity> I] Generic message options: [B<-cmd> I] [B<-infotype> I] [B<-geninfo> I] Certificate enrollment options: [B<-newkey> I|I] [B<-newkeypass> I] [B<-subject> I] [B<-issuer> I] [B<-days> I] [B<-reqexts> I] [B<-sans> I] [B<-san_nodefault>] [B<-policies> I] [B<-policy_oids> I] [B<-policy_oids_critical>] [B<-popo> I] [B<-csr> I] [B<-out_trusted> I|I] [B<-implicit_confirm>] [B<-disable_confirm>] [B<-certout> I] [B<-chainout> I] Certificate enrollment and revocation options: [B<-oldcert> I|I] [B<-revreason> I] Message transfer options: [B<-server> I<[http[s]://][userinfo@]host[:port][/path][?query][#fragment]>] [B<-proxy> I<[http[s]://][userinfo@]host[:port][/path][?query][#fragment]>] [B<-no_proxy> I] [B<-recipient> I] [B<-path> I] [B<-keep_alive> I] [B<-msg_timeout> I] [B<-total_timeout> I] Server authentication options: [B<-trusted> I|I] [B<-untrusted> I|I] [B<-srvcert> I|I] [B<-expect_sender> I] [B<-ignore_keyusage>] [B<-unprotected_errors>] [B<-extracertsout> I] [B<-cacertsout> I] Client authentication and protection options: [B<-ref> I] [B<-secret> I] [B<-cert> I|I] [B<-own_trusted> I|I] [B<-key> I|I] [B<-keypass> I] [B<-digest> I] [B<-mac> I] [B<-extracerts> I|I] [B<-unprotected_requests>] Credentials format options: [B<-certform> I] [B<-keyform> I] [B<-otherpass> I] {- $OpenSSL::safe::opt_engine_synopsis -}{- $OpenSSL::safe::opt_provider_synopsis -} Random state options: {- $OpenSSL::safe::opt_r_synopsis -} TLS connection options: [B<-tls_used>] [B<-tls_cert> I|I] [B<-tls_key> I|I] [B<-tls_keypass> I] [B<-tls_extra> I|I] [B<-tls_trusted> I|I] [B<-tls_host> I] Client-side debugging options: [B<-batch>] [B<-repeat> I] [B<-reqin> I] [B<-reqin_new_tid>] [B<-reqout> I] [B<-rspin> I] [B<-rspout> I] [B<-use_mock_srv>] Mock server options: [B<-port> I] [B<-max_msgs> I] [B<-srv_ref> I] [B<-srv_secret> I] [B<-srv_cert> I|I] [B<-srv_key> I|I] [B<-srv_keypass> I] [B<-srv_trusted> I|I] [B<-srv_untrusted> I|I] [B<-rsp_cert> I|I] [B<-rsp_extracerts> I|I] [B<-rsp_capubs> I|I] [B<-poll_count> I] [B<-check_after> I] [B<-grant_implicitconf>] [B<-pkistatus> I] [B<-failure> I] [B<-failurebits> I] [B<-statusstring> I] [B<-send_error>] [B<-send_unprotected>] [B<-send_unprot_err>] [B<-accept_unprotected>] [B<-accept_unprot_err>] [B<-accept_raverified>] Certificate verification options, for both CMP and TLS: {- $OpenSSL::safe::opt_v_synopsis -} =head1 DESCRIPTION The B command is a client implementation for the Certificate Management Protocol (CMP) as defined in RFC4210. It can be used to request certificates from a CA server, update their certificates, request certificates to be revoked, and perform other types of CMP requests. =head1 OPTIONS =over 4 =item B<-help> Display a summary of all options =item B<-config> I Configuration file to use. An empty string C<""> means none. Default filename is from the environment variable C. =item B<-section> I Section(s) to use within config file defining CMP options. An empty string C<""> means no specific section. Default is C. Multiple section names may be given, separated by commas and/or whitespace (where in the latter case the whole argument must be enclosed in "..."). Contents of sections named later may override contents of sections named before. In any case, as usual, the C<[default]> section and finally the unnamed section (as far as present) can provide per-option fallback values. =item B<-verbosity> I Level of verbosity for logging, error output, etc. 0 = EMERG, 1 = ALERT, 2 = CRIT, 3 = ERR, 4 = WARN, 5 = NOTE, 6 = INFO, 7 = DEBUG, 8 = TRACE. Defaults to 6 = INFO. =back =head2 Generic message options =over 4 =item B<-cmd> I CMP command to execute. Currently implemented commands are: =over 8 =item ir E - Initialization Request =item cr E - Certificate Request =item p10cr - PKCS#10 Certification Request (for legacy support) =item kur EE- Key Update Request =item rr E - Revocation Request =item genm - General Message =back B requests initialization of an end entity into a PKI hierarchy by issuing a first certificate. B requests issuing an additional certificate for an end entity already initialized to the PKI hierarchy. B requests issuing an additional certificate similarly to B but using legacy PKCS#10 CSR format. B requests a (key) update for an existing certificate. B requests revocation of an existing certificate. B requests information using a General Message, where optionally included Bs may be used to state which info is of interest. Upon receipt of the General Response, information about all received ITAV Bs is printed to stdout. =item B<-infotype> I Set InfoType name to use for requesting specific info in B, e.g., C. =item B<-geninfo> I generalInfo integer values to place in request PKIHeader with given OID, e.g., C<1.2.3.4:int:56789>. =back =head2 Certificate enrollment options =over 4 =item B<-newkey> I|I The source of the private or public key for the certificate being requested. Defaults to the public key in the PKCS#10 CSR given with the B<-csr> option, the public key of the reference certificate, or the current client key. The public portion of the key is placed in the certification request. Unless B<-cmd> I, B<-popo> I<-1>, or B<-popo> I<0> is given, the private key will be needed as well to provide the proof of possession (POPO), where the B<-key> option may provide a fallback. =item B<-newkeypass> I Pass phrase source for the key given with the B<-newkey> option. If not given here, the password will be prompted for if needed. For more information about the format of I see L. =item B<-subject> I X509 Distinguished Name (DN) of subject to use in the requested certificate template. If the NULL-DN (C<"/">) is given then no subject is placed in the template. Default is the subject DN of any PKCS#10 CSR given with the B<-csr> option. For KUR, a further fallback is the subject DN of the reference certificate (see B<-oldcert>) if provided. This fallback is used for IR and CR only if no SANs are set. If provided and neither B<-cert> nor B<-oldcert> is given, the subject DN is used as fallback sender of outgoing CMP messages. The argument must be formatted as I. Special characters may be escaped by C<\> (backslash); whitespace is retained. Empty values are permitted, but the corresponding type will not be included. Giving a single C will lead to an empty sequence of RDNs (a NULL-DN). Multi-valued RDNs can be formed by placing a C<+> character instead of a C between the AttributeValueAssertions (AVAs) that specify the members of the set. Example: C =item B<-issuer> I X509 issuer Distinguished Name (DN) of the CA server to place in the requested certificate template in IR/CR/KUR. If the NULL-DN (C<"/">) is given then no issuer is placed in the template. If provided and neither B<-recipient> nor B<-srvcert> is given, the issuer DN is used as fallback recipient of outgoing CMP messages. The argument must be formatted as I. For details see the description of the B<-subject> option. =item B<-days> I Number of days the new certificate is requested to be valid for, counting from the current time of the host. Also triggers the explicit request that the validity period starts from the current time (as seen by the host). =item B<-reqexts> I Name of section in OpenSSL config file defining certificate request extensions. If the B<-csr> option is present, these extensions augment the extensions contained the given PKCS#10 CSR, overriding any extensions with same OIDs. =item B<-sans> I One or more IP addresses, DNS names, or URIs separated by commas or whitespace (where in the latter case the whole argument must be enclosed in "...") to add as Subject Alternative Name(s) (SAN) certificate request extension. If the special element "critical" is given the SANs are flagged as critical. Cannot be used if any Subject Alternative Name extension is set via B<-reqexts>. =item B<-san_nodefault> When Subject Alternative Names are not given via B<-sans> nor defined via B<-reqexts>, they are copied by default from the reference certificate (see B<-oldcert>). This can be disabled by giving the B<-san_nodefault> option. =item B<-policies> I Name of section in OpenSSL config file defining policies to be set as certificate request extension. This option cannot be used together with B<-policy_oids>. =item B<-policy_oids> I One or more OID(s), separated by commas and/or whitespace (where in the latter case the whole argument must be enclosed in "...") to add as certificate policies request extension. This option cannot be used together with B<-policies>. =item B<-policy_oids_critical> Flag the policies given with B<-policy_oids> as critical. =item B<-popo> I Proof-of-possession (POPO) method to use for IR/CR/KUR; values: C<-1>..<2> where C<-1> = NONE, C<0> = RAVERIFIED, C<1> = SIGNATURE (default), C<2> = KEYENC. Note that a signature-based POPO can only be produced if a private key is provided via the B<-newkey> or B<-key> options. =item B<-csr> I PKCS#10 CSR in PEM or DER format containing a certificate request. With B<-cmd> I it is used directly in a legacy P10CR message. When used with B<-cmd> I, I, or I, it is transformed into the respective regular CMP request. In this case, a private key must be provided (with B<-newkey> or B<-key>) for the proof of possession (unless B<-popo> I<-1> or B<-popo> I<0> is used) and the respective public key is placed in the certification request (rather than taking over the public key contained in the PKCS#10 CSR). PKCS#10 CSR input may also be used with B<-cmd> I to specify the certificate to be revoked via the included subject name and public key. =item B<-out_trusted> I|I Trusted certificate(s) to use for validating the newly enrolled certificate. During this verification, any certificate status checking is disabled. Multiple sources may be given, separated by commas and/or whitespace (where in the latter case the whole argument must be enclosed in "..."). Each source may contain multiple certificates. The certificate verification options B<-verify_hostname>, B<-verify_ip>, and B<-verify_email> only affect the certificate verification enabled via this option. =item B<-implicit_confirm> Request implicit confirmation of newly enrolled certificates. =item B<-disable_confirm> Do not send certificate confirmation message for newly enrolled certificate without requesting implicit confirmation to cope with broken servers not supporting implicit confirmation correctly. B This leads to behavior violating RFC 4210. =item B<-certout> I The file where the newly enrolled certificate should be saved. =item B<-chainout> I The file where the chain of the newly enrolled certificate should be saved. =back =head2 Certificate enrollment and revocation options =over 4 =item B<-oldcert> I|I The certificate to be updated (i.e., renewed or re-keyed) in Key Update Request (KUR) messages or to be revoked in Revocation Request (RR) messages. For KUR the certificate to be updated defaults to B<-cert>, and the resulting certificate is called I. For RR the certificate to be revoked can also be specified using B<-csr>. The reference certificate, if any, is also used for deriving default subject DN and Subject Alternative Names and the default issuer entry in the requested certificate template of an IR/CR/KUR. Its public key is used as a fallback in the template of certification requests. Its subject is used as sender of outgoing messages if B<-cert> is not given. Its issuer is used as default recipient in CMP message headers if neither B<-recipient>, B<-srvcert>, nor B<-issuer> is given. =item B<-revreason> I Set CRLReason to be included in revocation request (RR); values: C<0>..C<10> or C<-1> for none (which is the default). Reason numbers defined in RFC 5280 are: CRLReason ::= ENUMERATED { unspecified (0), keyCompromise (1), cACompromise (2), affiliationChanged (3), superseded (4), cessationOfOperation (5), certificateHold (6), -- value 7 is not used removeFromCRL (8), privilegeWithdrawn (9), aACompromise (10) } =back =head2 Message transfer options =over 4 =item B<-server> I<[http[s]://][userinfo@]host[:port][/path][?query][#fragment]> The DNS hostname or IP address and optionally port of the CMP server to connect to using HTTP(S). This option excludes I<-port> and I<-use_mock_srv>. It is ignored if I<-rspin> is given with enough filename arguments. The scheme C may be given only if the B<-tls_used> option is used. In this case the default port is 443, else 80. The optional userinfo and fragment components are ignored. Any given query component is handled as part of the path component. If a path is included it provides the default value for the B<-path> option. =item B<-proxy> I<[http[s]://][userinfo@]host[:port][/path][?query][#fragment]> The HTTP(S) proxy server to use for reaching the CMP server unless B<-no_proxy> applies, see below. The proxy port defaults to 80 or 443 if the scheme is C; apart from that the optional C or C prefix is ignored (note that TLS may be selected by B<-tls_used>), as well as any path, userinfo, and query, and fragment components. Defaults to the environment variable C if set, else C in case no TLS is used, otherwise C if set, else C. This option is ignored if I<-server> is not given. =item B<-no_proxy> I List of IP addresses and/or DNS names of servers not to use an HTTP(S) proxy for, separated by commas and/or whitespace (where in the latter case the whole argument must be enclosed in "..."). Default is from the environment variable C if set, else C. This option is ignored if I<-server> is not given. =item B<-recipient> I Distinguished Name (DN) to use in the recipient field of CMP request message headers, i.e., the CMP server (usually the addressed CA). The recipient field in the header of a CMP message is mandatory. If not given explicitly the recipient is determined in the following order: the subject of the CMP server certificate given with the B<-srvcert> option, the B<-issuer> option, the issuer of the certificate given with the B<-oldcert> option, the issuer of the CMP client certificate (B<-cert> option), as far as any of those is present, else the NULL-DN as last resort. The argument must be formatted as I. For details see the description of the B<-subject> option. =item B<-path> I HTTP path at the CMP server (aka CMP alias) to use for POST requests. Defaults to any path given with B<-server>, else C<"/">. =item B<-keep_alive> I If the given value is 0 then HTTP connections are not kept open after receiving a response, which is the default behavior for HTTP 1.0. If the value is 1 or 2 then persistent connections are requested. If the value is 2 then persistent connections are required, i.e., in case the server does not grant them an error occurs. The default value is 1, which means preferring to keep the connection open. =item B<-msg_timeout> I Number of seconds a CMP request-response message round trip is allowed to take before a timeout error is returned. A value <= 0 means no limitation (waiting indefinitely). Default is to use the B<-total_timeout> setting. =item B<-total_timeout> I Maximum total number of seconds a transaction may take, including polling etc. A value <= 0 means no limitation (waiting indefinitely). Default is 0. =back =head2 Server authentication options =over 4 =item B<-trusted> I|I The certificate(s), typically of root CAs, the client shall use as trust anchors when validating signature-based protection of CMP response messages. This option is ignored if the B<-srvcert> option is given as well. It provides more flexibility than B<-srvcert> because the CMP protection certificate of the server is not pinned but may be any certificate from which a chain to one of the given trust anchors can be constructed. If none of B<-trusted>, B<-srvcert>, and B<-secret> is given, message validation errors will be thrown unless B<-unprotected_errors> permits an exception. Multiple sources may be given, separated by commas and/or whitespace (where in the latter case the whole argument must be enclosed in "..."). Each source may contain multiple certificates. The certificate verification options B<-verify_hostname>, B<-verify_ip>, and B<-verify_email> have no effect on the certificate verification enabled via this option. =item B<-untrusted> I|I Non-trusted intermediate CA certificate(s). Any extra certificates given with the B<-cert> option are appended to it. All these certificates may be useful for cert path construction for the own CMP signer certificate (to include in the extraCerts field of request messages) and for the TLS client certificate (if TLS is enabled) as well as for chain building when validating server certificates (checking signature-based CMP message protection) and when validating newly enrolled certificates. Multiple filenames or URLs may be given, separated by commas and/or whitespace. Each source may contain multiple certificates. =item B<-srvcert> I|I The specific CMP server certificate to expect and directly trust (even if it is expired) when verifying signature-based protection of CMP response messages. This pins the accepted server and results in ignoring the B<-trusted> option. If set, the subject of the certificate is also used as default value for the recipient of CMP requests and as default value for the expected sender of CMP responses. =item B<-expect_sender> I Distinguished Name (DN) expected in the sender field of incoming CMP messages. Defaults to the subject DN of the pinned B<-srvcert>, if any. This can be used to make sure that only a particular entity is accepted as CMP message signer, and attackers are not able to use arbitrary certificates of a trusted PKI hierarchy to fraudulently pose as a CMP server. Note that this option gives slightly more freedom than setting the B<-srvcert>, which pins the server to the holder of a particular certificate, while the expected sender name will continue to match after updates of the server cert. The argument must be formatted as I. For details see the description of the B<-subject> option. =item B<-ignore_keyusage> Ignore key usage restrictions in CMP signer certificates when validating signature-based protection of incoming CMP messages. By default, C must be allowed by CMP signer certificates. =item B<-unprotected_errors> Accept missing or invalid protection of negative responses from the server. This applies to the following message types and contents: =over 4 =item * error messages =item * negative certificate responses (IP/CP/KUP) =item * negative revocation responses (RP) =item * negative PKIConf messages =back B This setting leads to unspecified behavior and it is meant exclusively to allow interoperability with server implementations violating RFC 4210, e.g.: =over 4 =item * section 5.1.3.1 allows exceptions from protecting only for special cases: "There MAY be cases in which the PKIProtection BIT STRING is deliberately not used to protect a message [...] because other protection, external to PKIX, will be applied instead." =item * section 5.3.21 is clear on ErrMsgContent: "The CA MUST always sign it with a signature key." =item * appendix D.4 shows PKIConf message having protection =back =item B<-extracertsout> I The file where to save all certificates contained in the extraCerts field of the last received response message (except for pollRep and PKIConf). =item B<-cacertsout> I The file where to save any CA certificates contained in the caPubs field of the last received certificate response (i.e., IP, CP, or KUP) message. =back =head2 Client authentication options =over 4 =item B<-ref> I Reference number/string/value to use as fallback senderKID; this is required if no sender name can be determined from the B<-cert> or <-subject> options and is typically used when authenticating with pre-shared key (password-based MAC). =item B<-secret> I -Prefer PBM-based message protection with given source of a secret value. -The secret is used for creating PBM-based protection of outgoing messages -and (as far as needed) for validating PBM-based protection of incoming messages. -PBM stands for Password-Based Message Authentication Code. +Provides the source of a secret value to use with MAC-based message protection. This takes precedence over the B<-cert> and B<-key> options. +The secret is used for creating MAC-based protection of outgoing messages +and for validating incoming messages that have MAC-based protection. +The algorithm used by default is Password-Based Message Authentication Code (PBM) +as defined in RFC 4210 section 5.1.3.1. For more information about the format of I see L. =item B<-cert> I|I The client's current CMP signer certificate. Requires the corresponding key to be given with B<-key>. The subject and the public key contained in this certificate serve as fallback values in the certificate template of IR/CR/KUR messages. The subject of this certificate will be used as sender of outgoing CMP messages, while the subject of B<-oldcert> or B<-subjectName> may provide fallback values. The issuer of this certificate is used as one of the recipient fallback values and as fallback issuer entry in the certificate template of IR/CR/KUR messages. -When using signature-based message protection, this "protection certificate" +When performing signature-based message protection, +this "protection certificate", also called "signer certificate", will be included first in the extraCerts field of outgoing messages and the signature is done with the corresponding key. In Initialization Request (IR) messages this can be used for authenticating using an external entity certificate as defined in appendix E.7 of RFC 4210. For Key Update Request (KUR) messages this is also used as the certificate to be updated if the B<-oldcert> option is not given. If the file includes further certs, they are appended to the untrusted certs because they typically constitute the chain of the client certificate, which is included in the extraCerts field in signature-protected request messages. =item B<-own_trusted> I|I If this list of certificates is provided then the chain built for the client-side CMP signer certificate given with the B<-cert> option is verified using the given certificates as trust anchors. Multiple sources may be given, separated by commas and/or whitespace (where in the latter case the whole argument must be enclosed in "..."). Each source may contain multiple certificates. The certificate verification options B<-verify_hostname>, B<-verify_ip>, and B<-verify_email> have no effect on the certificate verification enabled via this option. =item B<-key> I|I The corresponding private key file for the client's current certificate given in the B<-cert> option. -This will be used for signature-based message protection unless -the B<-secret> option indicating PBM or B<-unprotected_requests> is given. +This will be used for signature-based message protection unless the B<-secret> +option indicating MAC-based protection or B<-unprotected_requests> is given. It is also used as a fallback for the B<-newkey> option with IR/CR/KUR messages. =item B<-keypass> I Pass phrase source for the private key given with the B<-key> option. Also used for B<-cert> and B<-oldcert> in case it is an encrypted PKCS#12 file. If not given here, the password will be prompted for if needed. For more information about the format of I see L. =item B<-digest> I Specifies name of supported digest to use in RFC 4210's MSG_SIG_ALG -and as the one-way function (OWF) in MSG_MAC_ALG. +and as the one-way function (OWF) in C. If applicable, this is used for message protection and proof-of-possession (POPO) signatures. To see the list of supported digests, use C. Defaults to C. =item B<-mac> I -Specifies the name of the MAC algorithm in MSG_MAC_ALG. +Specifies the name of the MAC algorithm in C. To get the names of supported MAC algorithms use C and possibly combine such a name with the name of a supported digest algorithm, e.g., hmacWithSHA256. Defaults to C as per RFC 4210. =item B<-extracerts> I|I Certificates to append in the extraCerts field when sending messages. They can be used as the default CMP signer certificate chain to include. Multiple sources may be given, separated by commas and/or whitespace (where in the latter case the whole argument must be enclosed in "..."). Each source may contain multiple certificates. =item B<-unprotected_requests> Send request messages without CMP-level protection. =back =head2 Credentials format options =over 4 =item B<-certform> I File format to use when saving a certificate to a file. Default value is PEM. =item B<-keyform> I The format of the key input; unspecified by default. See L for details. =item B<-otherpass> I Pass phrase source for certificate given with the B<-trusted>, B<-untrusted>, B<-own_trusted>, B<-srvcert>, B<-out_trusted>, B<-extracerts>, B<-srv_trusted>, B<-srv_untrusted>, B<-rsp_extracerts>, B<-rsp_capubs>, B<-tls_extra>, and B<-tls_trusted> options. If not given here, the password will be prompted for if needed. For more information about the format of I see L. {- $OpenSSL::safe::opt_engine_item -} {- output_off() if $disabled{"deprecated-3.0"}; "" -} As an alternative to using this combination: -engine {engineid} -key {keyid} -keyform ENGINE ... it's also possible to just give the key ID in URI form to B<-key>, like this: -key org.openssl.engine:{engineid}:{keyid} This applies to all options specifying keys: B<-key>, B<-newkey>, and B<-tls_key>. {- output_on() if $disabled{"deprecated-3.0"}; "" -} =back =head2 Provider options =over 4 {- $OpenSSL::safe::opt_provider_item -} =back =head2 Random state options =over 4 {- $OpenSSL::safe::opt_r_item -} =back =head2 TLS connection options =over 4 =item B<-tls_used> Enable using TLS (even when other TLS-related options are not set) for message exchange with CMP server via HTTP. This option is not supported with the I<-port> option. It is ignored if the I<-server> option is not given or I<-use_mock_srv> is given or I<-rspin> is given with enough filename arguments. The following TLS-related options are ignored if B<-tls_used> is not given or does not take effect. =item B<-tls_cert> I|I Client's TLS certificate. If the source includes further certs they are used (along with B<-untrusted> certs) for constructing the client cert chain provided to the TLS server. =item B<-tls_key> I|I Private key for the client's TLS certificate. =item B<-tls_keypass> I Pass phrase source for client's private TLS key B<-tls_key>. Also used for B<-tls_cert> in case it is an encrypted PKCS#12 file. If not given here, the password will be prompted for if needed. For more information about the format of I see L. =item B<-tls_extra> I|I Extra certificates to provide to TLS server during TLS handshake =item B<-tls_trusted> I|I Trusted certificate(s) to use for validating the TLS server certificate. This implies hostname validation. Multiple sources may be given, separated by commas and/or whitespace (where in the latter case the whole argument must be enclosed in "..."). Each source may contain multiple certificates. The certificate verification options B<-verify_hostname>, B<-verify_ip>, and B<-verify_email> have no effect on the certificate verification enabled via this option. =item B<-tls_host> I Address to be checked during hostname validation. This may be a DNS name or an IP address. If not given it defaults to the B<-server> address. =back =head2 Client-side debugging options =over 4 =item B<-batch> Do not interactively prompt for input, for instance when a password is needed. This can be useful for batch processing and testing. =item B<-repeat> I Invoke the command the given positive number of times with the same parameters. Default is one invocation. =item B<-reqin> I Take the sequence of CMP requests to send to the server from the given file(s) rather than from the sequence of requests produced internally. This option is ignored if the B<-rspin> option is given because in the latter case no requests are actually sent. Multiple filenames may be given, separated by commas and/or whitespace (where in the latter case the whole argument must be enclosed in "..."). The files are read as far as needed to complete the transaction and filenames have been provided. If more requests are needed, the remaining ones are taken from the items at the respective position in the sequence of requests produced internally. The client needs to update the recipNonce field in the given requests (except for the first one) in order to satisfy the checks to be performed by the server. This causes re-protection (if protecting requests is required). =item B<-reqin_new_tid> Use a fresh transactionID for CMP request messages read using B<-reqin>, which causes their reprotection (if protecting requests is required). This may be needed in case the sequence of requests is reused and the CMP server complains that the transaction ID has already been used. =item B<-reqout> I Save the sequence of CMP requests created by the client to the given file(s). These requests are not sent to the server if the B<-reqin> option is used, too. Multiple filenames may be given, separated by commas and/or whitespace. Files are written as far as needed to save the transaction and filenames have been provided. If the transaction contains more requests, the remaining ones are not saved. =item B<-rspin> I Process the sequence of CMP responses provided in the given file(s), not contacting any given server, as long as enough filenames are provided to complete the transaction. Multiple filenames may be given, separated by commas and/or whitespace. Any server specified via the I<-server> or I<-use_mock_srv> options is contacted only if more responses are needed to complete the transaction. In this case the transaction will fail unless the server has been prepared to continue the already started transaction. =item B<-rspout> I Save the sequence of actually used CMP responses to the given file(s). These have been received from the server unless B<-rspin> takes effect. Multiple filenames may be given, separated by commas and/or whitespace. Files are written as far as needed to save the responses contained in the transaction and filenames have been provided. If the transaction contains more responses, the remaining ones are not saved. =item B<-use_mock_srv> Test the client using the internal CMP server mock-up at API level, bypassing socket-based transfer via HTTP. This excludes the B<-server> and B<-port> options. =back =head2 Mock server options =over 4 =item B<-port> I Act as HTTP-based CMP server mock-up listening on the given port. This excludes the B<-server> and B<-use_mock_srv> options. The B<-rspin>, B<-rspout>, B<-reqin>, and B<-reqout> options so far are not supported in this mode. =item B<-max_msgs> I Maximum number of CMP (request) messages the CMP HTTP server mock-up should handle, which must be nonnegative. The default value is 0, which means that no limit is imposed. In any case the server terminates on internal errors, but not when it detects a CMP-level error that it can successfully answer with an error message. =item B<-srv_ref> I Reference value to use as senderKID of server in case no B<-srv_cert> is given. =item B<-srv_secret> I Password source for server authentication with a pre-shared key (secret). =item B<-srv_cert> I|I Certificate of the server. =item B<-srv_key> I|I Private key used by the server for signing messages. =item B<-srv_keypass> I Server private key (and cert) file pass phrase source. =item B<-srv_trusted> I|I Trusted certificates for client authentication. The certificate verification options B<-verify_hostname>, B<-verify_ip>, and B<-verify_email> have no effect on the certificate verification enabled via this option. =item B<-srv_untrusted> I|I Intermediate CA certs that may be useful when validating client certificates. =item B<-rsp_cert> I|I Certificate to be returned as mock enrollment result. =item B<-rsp_extracerts> I|I Extra certificates to be included in mock certification responses. =item B<-rsp_capubs> I|I CA certificates to be included in mock Initialization Response (IP) message. =item B<-poll_count> I Number of times the client must poll before receiving a certificate. =item B<-check_after> I The checkAfter value (number of seconds to wait) to include in poll response. =item B<-grant_implicitconf> Grant implicit confirmation of newly enrolled certificate. =item B<-pkistatus> I PKIStatus to be included in server response. Valid range is 0 (accepted) .. 6 (keyUpdateWarning). =item B<-failure> I A single failure info bit number to be included in server response. Valid range is 0 (badAlg) .. 26 (duplicateCertReq). =item B<-failurebits> I Number representing failure bits to be included in server response. Valid range is 0 .. 2^27 - 1. =item B<-statusstring> I Text to be included as status string in server response. =item B<-send_error> Force server to reply with error message. =item B<-send_unprotected> Send response messages without CMP-level protection. =item B<-send_unprot_err> In case of negative responses, server shall send unprotected error messages, certificate responses (IP/CP/KUP), and revocation responses (RP). WARNING: This setting leads to behavior violating RFC 4210. =item B<-accept_unprotected> Accept missing or invalid protection of requests. =item B<-accept_unprot_err> Accept unprotected error messages from client. So far this has no effect because the server does not accept any error messages. =item B<-accept_raverified> Accept RAVERIFED as proof of possession (POPO). =back =head2 Certificate verification options, for both CMP and TLS =over 4 {- $OpenSSL::safe::opt_v_item -} The certificate verification options B<-verify_hostname>, B<-verify_ip>, and B<-verify_email> only affect the certificate verification enabled via the B<-out_trusted> option. =back =head1 NOTES +When a client obtains from a CMP server CA certificates that it is going to +trust, for instance via the C field of a certificate response, +authentication of the CMP server is particularly critical. +So special care must be taken setting up server authentication +using B<-trusted> and related options for certificate-based authentication +or B<-secret> for MAC-based protection. + When setting up CMP configurations and experimenting with enrollment options typically various errors occur until the configuration is correct and complete. When the CMP server reports an error the client will by default check the protection of the CMP response message. Yet some CMP services tend not to protect negative responses. In this case the client will reject them, and thus their contents are not shown although they usually contain hints that would be helpful for diagnostics. For assisting in such cases the CMP client offers a workaround via the B<-unprotected_errors> option, which allows accepting such negative messages. =head1 EXAMPLES =head2 Simple examples using the default OpenSSL configuration file This CMP client implementation comes with demonstrative CMP sections in the example configuration file F, which can be used to interact conveniently with the Insta Demo CA. In order to enroll an initial certificate from that CA it is sufficient to issue the following shell commands. export OPENSSL_CONF=/path/to/openssl/apps/openssl.cnf =begin comment wget 'http://pki.certificate.fi:8081/install-ca-cert.html/ca-certificate.crt\ ?ca-id=632&download-certificate=1' -O insta.ca.crt =end comment openssl genrsa -out insta.priv.pem openssl cmp -section insta This should produce the file F containing a new certificate for the private key held in F. It can be viewed using, e.g., openssl x509 -noout -text -in insta.cert.pem In case the network setup requires using an HTTP proxy it may be given as usual via the environment variable B or via the B<-proxy> option in the configuration file or the CMP command-line argument B<-proxy>, for example -proxy http://192.168.1.1:8080 In the Insta Demo CA scenario both clients and the server may use the pre-shared secret I and the reference value I<3078> to authenticate to each other. Alternatively, CMP messages may be protected in signature-based manner, where the trust anchor in this case is F and the client may use any certificate already obtained from that CA, as specified in the B<[signature]> section of the example configuration. This can be used in combination with the B<[insta]> section simply by openssl cmp -section insta,signature By default the CMP IR message type is used, yet CR works equally here. This may be specified directly at the command line: openssl cmp -section insta -cmd cr or by referencing in addition the B<[cr]> section of the example configuration: openssl cmp -section insta,cr In order to update the enrolled certificate one may call openssl cmp -section insta,kur -using with PBM-based protection or +using MAC-based protection with PBM or openssl cmp -section insta,kur,signature using signature-based protection. In a similar way any previously enrolled certificate may be revoked by openssl cmp -section insta,rr -trusted insta.ca.crt or openssl cmp -section insta,rr,signature Many more options can be given in the configuration file and/or on the command line. For instance, the B<-reqexts> CLI option may refer to a section in the configuration file defining X.509 extensions to use in certificate requests, such as C in F: openssl cmp -section insta,cr -reqexts v3_req =head2 Certificate enrollment The following examples do not make use of a configuration file at first. They assume that a CMP server can be contacted on the local TCP port 80 and accepts requests under the alias I. For enrolling its very first certificate the client generates a client key and sends an initial request message to the local CMP server using a pre-shared secret key for mutual authentication. In this example the client does not have the CA certificate yet, so we specify the name of the CA with the B<-recipient> option and save any CA certificates that we may receive in the C file. In below command line usage examples the C<\> at line ends is used just for formatting; each of the command invocations should be on a single line. openssl genrsa -out cl_key.pem openssl cmp -cmd ir -server 127.0.0.1:80/pkix/ -recipient "/CN=CMPserver" \ -ref 1234 -secret pass:1234-5678 \ -newkey cl_key.pem -subject "/CN=MyName" \ -cacertsout capubs.pem -certout cl_cert.pem =head2 Certificate update Then, when the client certificate and its related key pair needs to be updated, the client can send a key update request taking the certs in C as trusted for authenticating the server and using the previous cert and key for its own authentication. Then it can start using the new cert and key. openssl genrsa -out cl_key_new.pem openssl cmp -cmd kur -server 127.0.0.1:80/pkix/ \ -trusted capubs.pem \ -cert cl_cert.pem -key cl_key.pem \ -newkey cl_key_new.pem -certout cl_cert.pem cp cl_key_new.pem cl_key.pem -This command sequence can be repated as often as needed. +This command sequence can be repeated as often as needed. =head2 Requesting information from CMP server Requesting "all relevant information" with an empty General Message. This prints information about all received ITAV Bs to stdout. openssl cmp -cmd genm -server 127.0.0.1/pkix/ -recipient "/CN=CMPserver" \ -ref 1234 -secret pass:1234-5678 =head2 Using a custom configuration file For CMP client invocations, in particular for certificate enrollment, usually many parameters need to be set, which is tedious and error-prone to do on the command line. Therefore, the client offers the possibility to read options from sections of the OpenSSL config file, usually called F. The values found there can still be extended and even overridden by any subsequently loaded sections and on the command line. After including in the configuration file the following sections: [cmp] server = 127.0.0.1 path = pkix/ trusted = capubs.pem cert = cl_cert.pem key = cl_key.pem newkey = cl_key.pem certout = cl_cert.pem [init] recipient = "/CN=CMPserver" trusted = cert = key = ref = 1234 secret = pass:1234-5678-1234-567 subject = "/CN=MyName" cacertsout = capubs.pem the above enrollment transactions reduce to openssl cmp -section cmp,init openssl cmp -cmd kur -newkey cl_key_new.pem and the above transaction using a general message reduces to openssl cmp -section cmp,init -cmd genm =head1 SEE ALSO L, L, L, L, L, L =head1 HISTORY The B application was added in OpenSSL 3.0. The B<-engine option> was deprecated in OpenSSL 3.0. =head1 COPYRIGHT Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved. Licensed under the Apache License 2.0 (the "License"). You may not use this file except in compliance with the License. You can obtain a copy in the file LICENSE in the source distribution or at L. =cut diff --git a/doc/man1/openssl-cms.pod.in b/doc/man1/openssl-cms.pod.in index c63a7f330ba6..65a61ee97f1d 100644 --- a/doc/man1/openssl-cms.pod.in +++ b/doc/man1/openssl-cms.pod.in @@ -1,912 +1,912 @@ =pod {- OpenSSL::safe::output_do_not_edit_headers(); -} =head1 NAME openssl-cms - CMS command =head1 SYNOPSIS B B [B<-help>] General options: [B<-in> I] [B<-out> I] {- $OpenSSL::safe::opt_config_synopsis -} Operation options: [B<-encrypt>] [B<-decrypt>] [B<-sign>] [B<-verify>] [B<-resign>] [B<-sign_receipt>] [B<-verify_receipt> I] [B<-digest_create>] [B<-digest_verify>] [B<-compress>] [B<-uncompress>] [B<-EncryptedData_encrypt>] [B<-EncryptedData_decrypt>] [B<-data_create>] [B<-data_out>] [B<-cmsout>] File format options: [B<-inform> B|B|B] [B<-outform> B|B|B] [B<-rctform> B|B|B] [B<-stream>] [B<-indef>] [B<-noindef>] [B<-binary>] [B<-crlfeol>] [B<-asciicrlf>] Keys and password options: [B<-pwri_password> I] [B<-secretkey> I] [B<-secretkeyid> I] [B<-inkey> I|I] [B<-passin> I] [B<-keyopt> I:I] [B<-keyform> B|B|B|B] {- $OpenSSL::safe::opt_engine_synopsis -}{- $OpenSSL::safe::opt_provider_synopsis -} {- $OpenSSL::safe::opt_r_synopsis -} Encryption options: [B<-originator> I] [B<-recip> I] [I ...] [B<-I>] [B<-wrap> I] [B<-aes128-wrap>] [B<-aes192-wrap>] [B<-aes256-wrap>] [B<-des3-wrap>] [B<-debug_decrypt>] Signing options: [B<-md> I] [B<-signer> I] [B<-certfile> I] [B<-cades>] [B<-nodetach>] [B<-nocerts>] [B<-noattr>] [B<-nosmimecap>] [B<-receipt_request_all>] [B<-receipt_request_first>] [B<-receipt_request_from> I] [B<-receipt_request_to> I] Verification options: [B<-signer> I] [B<-content> I] [B<-no_content_verify>] [B<-no_attr_verify>] [B<-nosigs>] [B<-noverify>] [B<-nointern>] [B<-cades>] [B<-verify_retcode>] {- $OpenSSL::safe::opt_trust_synopsis -} Output options: [B<-keyid>] [B<-econtent_type> I] [B<-text>] [B<-certsout> I] [B<-to> I] [B<-from> I] [B<-subject> I] Printing options: [B<-noout>] [B<-print>] [B<-nameopt> I