diff --git a/CHANGES.md b/CHANGES.md index 5f5ba3ef1751..b991285aedb2 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,21484 +1,21553 @@ OpenSSL CHANGES =============== This is a detailed breakdown of significant changes. For a high-level overview of changes in each release, see [NEWS.md](./NEWS.md). 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.5](#openssl-35) - [OpenSSL 3.4](#openssl-34) - [OpenSSL 3.3](#openssl-33) - [OpenSSL 3.2](#openssl-32) - [OpenSSL 3.1](#openssl-31) - [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.5 ----------- +### Changes between 3.5.3 and 3.5.4 [30 Sep 2025] + + * Fix Out-of-bounds read & write in RFC 3211 KEK Unwrap + + Issue summary: An application trying to decrypt CMS messages encrypted using + password based encryption can trigger an out-of-bounds read and write. + + Impact summary: This out-of-bounds read may trigger a crash which leads to + Denial of Service for an application. The out-of-bounds write can cause + a memory corruption which can have various consequences including + a Denial of Service or Execution of attacker-supplied code. + + The issue was reported by Stanislav Fort (Aisle Research). + + ([CVE-2025-9230]) + + *Viktor Dukhovni* + + * Fix Timing side-channel in SM2 algorithm on 64 bit ARM + + Issue summary: A timing side-channel which could potentially allow remote + recovery of the private key exists in the SM2 algorithm implementation on + 64 bit ARM platforms. + + Impact summary: A timing side-channel in SM2 signature computations on + 64 bit ARM platforms could allow recovering the private key by an attacker. + + The issue was reported by Stanislav Fort (Aisle Research). + + ([CVE-2025-9231]) + + *Stanislav Fort and Tomáš Mráz* + + * Fix Out-of-bounds read in HTTP client no_proxy handling + + Issue summary: An application using the OpenSSL HTTP client API functions + may trigger an out-of-bounds read if the "no_proxy" environment variable is + set and the host portion of the authority component of the HTTP URL is an + IPv6 address. + + Impact summary: An out-of-bounds read can trigger a crash which leads to + Denial of Service for an application. + + The issue was reported by Stanislav Fort (Aisle Research). + + ([CVE-2025-9232]) + + *Stanislav Fort* + + * The FIPS provider no longer performs a PCT on key import for ECX keys + (that was introduced in 3.5.2), following the latest update + on that requirement in FIPS 140-3 IG 10.3.A additional comment 1. + + *Eugene Syromiatnikov* + + * Fixed the length of the ASN.1 sequence for the SM3 digests of RSA-encrypted + signatures. + + *Xiao Lou Dong Feng* + + * Reverted the synthesised `OPENSSL_VERSION_NUMBER` change for the release + builds, as it broke some exiting applications that relied on the previous + 3.x semantics, as documented in `OpenSSL_version(3)`. + + *Richard Levitte* + ### Changes between 3.5.2 and 3.5.3 [16 Sep 2025] * Avoided a potential race condition introduced in 3.5.1, where `OSSL_STORE_CTX` kept open during lookup while potentially being used by multiple threads simultaneously, that could lead to potential crashes when multiple concurrent TLS connections are served. *Matt Caswell* * The FIPS provider no longer performs a PCT on key import for RSA, DH, and EC keys (that was introduced in 3.5.2), following the latest update on that requirement in FIPS 140-3 IG 10.3.A additional comment 1. *Dr Paul Dale* * Secure memory allocation calls are no longer used for HMAC keys. *Dr Paul Dale* * `openssl req` no longer generates certificates with an empty extension list when SKID/AKID are set to `none` during generation. *David Benjamin* * The man page date is now derived from the release date provided in `VERSION.dat` and not the current date for the released builds. *Enji Cooper* * Hardened the provider implementation of the RSA public key "encrypt" operation to add a missing check that the caller-indicated output buffer size is at least as large as the byte count of the RSA modulus. The issue was reported by Arash Ale Ebrahim from SYSPWN. This operation is typically invoked via `EVP_PKEY_encrypt(3)`. Callers that in fact provide a sufficiently large buffer, but fail to correctly indicate its size may now encounter unexpected errors. In applications that attempt RSA public encryption into a buffer that is too small, an out-of-bounds write is now avoided and an error is reported instead. *Viktor Dukhovni* * Added FIPS 140-3 PCT on DH key generation. *Nikola Pajkovsky* * Fixed the synthesised `OPENSSL_VERSION_NUMBER`. *Richard Levitte* ### Changes between 3.5.1 and 3.5.2 [5 Aug 2025] * The FIPS provider now performs a PCT on key import for RSA, EC and ECX. This is mandated by FIPS 140-3 IG 10.3.A additional comment 1. *Dr Paul Dale* ### Changes between 3.5.0 and 3.5.1 [1 Jul 2025] * Fix x509 application adds trusted use instead of rejected use. Issue summary: Use of -addreject option with the openssl x509 application adds a trusted use instead of a rejected use for a certificate. Impact summary: If a user intends to make a trusted certificate rejected for a particular use it will be instead marked as trusted for that use. ([CVE-2025-4575]) *Tomas Mraz* * Aligned the behaviour of TLS and DTLS in the event of a no_renegotiation alert being received. Older versions of OpenSSL failed with DTLS if a no_renegotiation alert was received. All versions of OpenSSL do this for TLS. From 3.2 a bug was exposed that meant that DTLS ignored no_rengotiation. We have now restored the original behaviour and brought DTLS back into line with TLS. *Matt Caswell* ### Changes between 3.4 and 3.5.0 [8 Apr 2025] * Added server side support for QUIC *Hugo Landau, Matt Caswell, Tomáš Mráz, Neil Horman, Sasha Nedvedicky, Andrew Dinh* * Tolerate PKCS#8 version 2 with optional public keys. The public key data is currently ignored. *Viktor Dukhovni* * Signature schemes without an explicit signing digest in CMS are now supported. Examples of such schemes are ED25519 or ML-DSA. *Michael Schroeder* * The TLS Signature algorithms defaults now include all three ML-DSA variants as first algorithms. *Viktor Dukhovni* * Added a `no-tls-deprecated-ec` configuration option. The `no-tls-deprecated-ec` option disables support for TLS elliptic curve groups deprecated in RFC8422 at compile time. This does not affect use of the associated curves outside TLS. By default support for these groups is compiled in, but, as before, they are not included in the default run-time list of supported groups. With the `enable-tls-deprecated-ec` option these TLS groups remain enabled at compile time even if the default configuration is changed, provided the underlying EC curves remain implemented. *Viktor Dukhovni* * Added new API to enable 0-RTT for 3rd party QUIC stacks. *Cheng Zhang* * Added support for a new callback registration `SSL_CTX_set_new_pending_conn_cb`, which allows for application notification of new connection SSL object creation, which occurs independently of calls to `SSL_accept_connection()`. Note: QUIC objects passed through SSL callbacks should not have their state mutated via calls back into the SSL api until such time as they have been received via a call to `SSL_accept_connection()`. *Neil Horman* * Add SLH-DSA as specified in FIPS 205. *Shane Lontis and Dr Paul Dale* * ML-KEM as specified in FIPS 203. Based on the original implementation in BoringSSL, ported from C++ to C, refactored, and integrated into the OpenSSL default and FIPS providers. Including also the X25519MLKEM768, SecP256r1MLKEM768, SecP384r1MLKEM1024 TLS hybrid key post-quantum/classical key agreement schemes. *Michael Baentsch, Viktor Dukhovni, Shane Lontis and Paul Dale* * Add ML-DSA as specified in FIPS 204. The base code was derived from BoringSSL C++ code. *Shane Lontis, Viktor Dukhovni and Paul Dale* * Added new API calls to enable 3rd party QUIC stacks to use the OpenSSL TLS implementation. *Matt Caswell* * The default DRBG implementations have been changed to prefer to fetch algorithm implementations from the default provider (the provider the DRBG implementation is built in) regardless of the default properties set in the configuration file. The code will still fallback to find an implementation, as done previously, if needed. *Simo Sorce* * Initial support for opaque symmetric keys objects (EVP_SKEY). These replace the ad-hoc byte arrays that are pervasive throughout the library. *Dmitry Belyavskiy and Simo Sorce* * The default TLS group list setting is now set to: `?*X25519MLKEM768 / ?*X25519:?secp256r1 / ?X448:?secp384r1:?secp521r1 / ?ffdhe2048:?ffdhe3072` This means two key shares (X25519MLKEM768 and X25519) will be sent by default by the TLS client. GOST groups and FFDHE groups larger than 3072 bits are no longer enabled by default. The group names in the group list setting are now also case insensitive. *Viktor Dukhovni* * For TLSv1.3: Add capability for a client to send multiple key shares. Extend the scope of `SSL_OP_CIPHER_SERVER_PREFERENCE` to cover server-side key exchange group selection. Extend the server-side key exchange group selection algorithm and related group list syntax to support multiple group priorities, e.g. to prioritize (hybrid-)KEMs. *David Kelsey*, *Martin Schmatz* * A new random generation API has been introduced which modifies all of the L family of calls so they are routed through a specific named provider instead of being resolved via the normal DRBG chaining. In a future OpenSSL release, this will obsolete RAND_METHOD. *Dr Paul Dale* * New inline functions were added to support loads and stores of unsigned 16-bit, 32-bit and 64-bit integers in either little-endian or big-endian form, regardless of the host byte-order. See the `OPENSSL_load_u16_le(3)` manpage for details. *Viktor Dukhovni* * All the `BIO_meth_get_*()` functions allowing reuse of the internal OpenSSL BIO method implementations were deprecated. The reuse is unsafe due to dependency on the code of the internal methods not changing. *Tomáš Mráz* * Support DEFAULT keyword and '-' prefix in `SSL_CTX_set1_groups_list()`. `SSL_CTX_set1_groups_list()` now supports the DEFAULT keyword which sets the available groups to the default selection. The '-' prefix allows the calling application to remove a group from the selection. *Frederik Wedel-Heinen* * Updated the default encryption cipher for the `req`, `cms`, and `smime` applications from `des-ede3-cbc` to `aes-256-cbc`. AES-256 provides a stronger 256-bit key encryption than legacy 3DES. *Aditya* * Enhanced PKCS#7 inner contents verification. In the `PKCS7_verify()` function, the BIO *indata parameter refers to the signed data if the content is detached from p7. Otherwise, indata should be NULL, and then the signed data must be in p7. The previous OpenSSL implementation only supported MIME inner content [RFC 5652, section 5.2]. The added functionality now enables support for PKCS#7 inner content [RFC 2315, section 7]. *Małgorzata Olszówka* * The `-rawin` option of the `pkeyutl` command is now implied (and thus no longer required) when using `-digest` or when signing or verifying with an Ed25519 or Ed448 key. The `-digest` and `-rawin` option may only be given with `-sign` or `verify`. *David von Oheimb* * `X509_PURPOSE_add()` has been modified to take `sname` instead of `id` as the primary purpose identifier. For its convenient use, `X509_PURPOSE_get_unused_id()` has been added. This work was sponsored by Siemens AG. *David von Oheimb* * Added support for central key generation in CMP. This work was sponsored by Siemens AG. *Rajeev Ranjan* * Optionally allow the FIPS provider to use the `JITTER` entropy source. Note that using this option will require the resulting FIPS provider to undergo entropy source validation [ESV] by the [CMVP], without this the FIPS provider will not be FIPS compliant. Enable this using the configuration option `enable-fips-jitter`. *Paul Dale* * Extended `OPENSSL_ia32cap` support to accommodate additional `CPUID` feature/capability bits in leaf `0x7` (Extended Feature Flags) as well as leaf `0x24` (Converged Vector ISA). *Dan Zimmerman, Alina Elizarova* * Cipher pipelining support for provided ciphers with new API functions EVP_CIPHER_can_pipeline(), EVP_CipherPipelineEncryptInit(), EVP_CipherPipelineDecryptInit(), EVP_CipherPipelineUpdate(), and EVP_CipherPipelineFinal(). Cipher pipelining support allows application to submit multiple chunks of data in one cipher update call, thereby allowing the provided implementation to take advantage of parallel computing. There are currently no built-in ciphers that support pipelining. This new API replaces the legacy pipeline API [SSL_CTX_set_max_pipelines](https://docs.openssl.org/3.3/man3/SSL_CTX_set_split_send_fragment/) used with Engines. *Ramkumar* * Add CMS_NO_SIGNING_TIME flag to CMS_sign(), CMS_add1_signer() Previously there was no way to create a CMS SignedData signature without a signing time attribute, because CMS_SignerInfo_sign added it unconditionally. However, there is a use case (PAdES signatures [ETSI EN 319 142-1](https://www.etsi.org/deliver/etsi_en/319100_319199/31914201/01.01.01_60/en_31914201v010101p.pdf) ) where this attribute is not allowed, so a new flag was added to the CMS API that causes this attribute to be omitted at signing time. The new `-no_signing_time` option of the `cms` command enables this flag. *Juhász Péter* * Parallel dual-prime 1024/1536/2048-bit modular exponentiation for AVX_IFMA capable processors (Intel Sierra Forest and its successor). This optimization brings performance enhancement, ranging from 1.8 to 2.2 times, for the sign/decryption operations of rsaz-2k/3k/4k (`openssl speed rsa`) on the Intel Sierra Forest. *Zhiguo Zhou, Wangyang Guo (Intel Corp)* * VAES/AVX-512 support for AES-XTS. For capable processors (>= Intel Icelake), this provides a vectorized implementation of AES-XTS with a throughput improvement between 1.3x to 2x, depending on the block size. *Pablo De Lara Guarch, Dan Pittman* * Fixed EVP_DecodeUpdate() to not write padding zeros to the decoded output. According to the documentation, for every 4 valid base64 bytes processed (ignoring whitespace, carriage returns and line feeds), EVP_DecodeUpdate() produces 3 bytes of binary output data (except at the end of data terminated with one or two padding characters). However, the function behaved like an EVP_DecodeBlock(). It produced exactly 3 output bytes for every 4 input bytes. Such behaviour could cause writes to a non-allocated output buffer if a user allocates its size based on the documentation and knowing the padding size. The fix makes EVP_DecodeUpdate() produce exactly as many output bytes as in the initial non-encoded message. *Valerii Krygin* * Added support for aAissuingDistributionPoint, allowedAttributeAssignments, timeSpecification, attributeDescriptor, roleSpecCertIdentifier, authorityAttributeIdentifier and attributeMappings X.509v3 extensions. *Jonathan M. Wilbur* * Added a new CLI option `-provparam` and API functions for setting of provider configuration parameters. *Viktor Dukhovni* * Added a new trace category for PROVIDER calls and added new tracing calls in provider and algorithm fetching API functions. *Neil Horman* * Fixed benchmarking for AEAD ciphers in the `openssl speed` utility. *Mohammed Alhabib* * Added a build configuration option `enable-sslkeylog` for enabling support for SSLKEYLOGFILE environment variable to log TLS connection secrets. *Neil Horman* * Added EVP_get_default_properties() function to retrieve the current default property query string. *Dmitry Belyavskiy* OpenSSL 3.4 ----------- ### Changes between 3.4.1 and 3.4.2 [xx XXX xxxx] * When displaying distinguished names in the openssl application escape control characters by default. *Tomáš Mráz* ### Changes between 3.4.0 and 3.4.1 [11 Feb 2025] * Fixed RFC7250 handshakes with unauthenticated servers don't abort as expected. Clients using RFC7250 Raw Public Keys (RPKs) to authenticate a server may fail to notice that the server was not authenticated, because handshakes don't abort as expected when the SSL_VERIFY_PEER verification mode is set. ([CVE-2024-12797]) *Viktor Dukhovni* * Fixed timing side-channel in ECDSA signature computation. There is a timing signal of around 300 nanoseconds when the top word of the inverted ECDSA nonce value is zero. This can happen with significant probability only for some of the supported elliptic curves. In particular the NIST P-521 curve is affected. To be able to measure this leak, the attacker process must either be located in the same physical computer or must have a very fast network connection with low latency. ([CVE-2024-13176]) *Tomáš Mráz* * Reverted the behavior change of CMS_get1_certs() and CMS_get1_crls() that happened in the 3.4.0 release. These functions now return NULL again if there are no certs or crls in the CMS object. *Tomáš Mráz* ### Changes between 3.3 and 3.4.0 [22 Oct 2024] * For the FIPS provider only, replaced the primary DRBG with a continuous health check module. This also removes the now forbidden DRBG chaining. *Paul Dale* * Improved base64 BIO correctness and error reporting. *Viktor Dukhovni* * Added support for directly fetched composite signature algorithms such as RSA-SHA2-256 including new API functions in the EVP_PKEY_sign, EVP_PKEY_verify and EVP_PKEY_verify_recover groups. *Richard Levitte* * XOF Digest API improvements EVP_MD_CTX_get_size() and EVP_MD_CTX_size are macros that were aliased to EVP_MD_get_size which returns a constant value. XOF Digests such as SHAKE have an output size that is not fixed, so calling EVP_MD_get_size() is not sufficent. The existing macros now point to the new function EVP_MD_CTX_get_size_ex() which will retrieve the "size" for a XOF digest, otherwise it falls back to calling EVP_MD_get_size(). Note that the SHAKE implementation did not have a context getter previously, so the "size" will only be able to be retrieved with new providers. Also added a EVP_xof() helper. *Shane Lontis* * Added FIPS indicators to the FIPS provider. FIPS 140-3 requires indicators to be used if the FIPS provider allows non-approved algorithms. An algorithm is approved if it passes all required checks such as minimum key size. By default an error will occur if any check fails. For backwards compatibility individual algorithms may override the checks by using either an option in the FIPS configuration OR in code using an algorithm context setter. Overriding the check means that the algorithm is not FIPS compliant. OSSL_INDICATOR_set_callback() can be called to register a callback to log unapproved algorithms. At the end of any algorithm operation the approved status can be queried using an algorithm context getter. FIPS provider configuration options are set using 'openssl fipsinstall'. Note that new FIPS 140-3 restrictions have been enforced such as RSA Encryption using PKCS1 padding is no longer approved. Documentation related to the changes can be found on the [fips_module(7)] manual page. [fips_module(7)]: https://docs.openssl.org/master/man7/fips_module/#FIPS indicators *Shane Lontis, Paul Dale, Po-Hsing Wu and Dimitri John Ledkov* * Added support for hardware acceleration for HMAC on S390x architecture. *Ingo Franzki* * Added debuginfo Makefile target for unix platforms to produce a separate DWARF info file from the corresponding shared libs. *Neil Horman* * Added support for encapsulation and decapsulation operations in the pkeyutl command. *Dmitry Belyavskiy* * Added implementation of RFC 9579 (PBMAC1) in PKCS#12. *Dmitry Belyavskiy* * Add a new random seed source RNG `JITTER` using a statically linked jitterentropy library. *Dimitri John Ledkov* * Added a feature to retrieve configured TLS signature algorithms, e.g., via the openssl list command. *Michael Baentsch* * Deprecated TS_VERIFY_CTX_set_* functions and added replacement TS_VERIFY_CTX_set0_* functions with improved semantics. *Tobias Erbsland* * Redesigned Windows use of OPENSSLDIR/ENGINESDIR/MODULESDIR such that what were formerly build time locations can now be defined at run time with registry keys. See NOTES-WINDOWS.md. *Neil Horman* * Added options `-not_before` and `-not_after` for explicit setting start and end dates of certificates created with the `req` and `x509` commands. Added the same options also to `ca` command as alias for `-startdate` and `-enddate` options. *Stephan Wurm* * The X25519 and X448 key exchange implementation in the FIPS provider is unapproved and has `fips=no` property. *Tomáš Mráz* * SHAKE-128 and SHAKE-256 implementations have no default digest length anymore. That means these algorithms cannot be used with EVP_DigestFinal/_ex() unless the `xoflen` param is set before. This change was necessary because the preexisting default lengths were half the size necessary for full collision resistance supported by these algorithms. *Tomáš Mráz* * Setting `config_diagnostics=1` in the config file will cause errors to be returned from SSL_CTX_new() and SSL_CTX_new_ex() if there is an error in the ssl module configuration. *Tomáš Mráz* * An empty renegotiate extension will be used in TLS client hellos instead of the empty renegotiation SCSV, for all connections with a minimum TLS version > 1.0. *Tim Perry* * Added support for integrity-only cipher suites TLS_SHA256_SHA256 and TLS_SHA384_SHA384 in TLS 1.3, as defined in RFC 9150. This work was sponsored by Siemens AG. *Rajeev Ranjan* * Added support for retrieving certificate request templates and CRLs in CMP, with the respective CLI options `-template`, `-crlcert`, `-oldcrl`, `-crlout`, `-crlform>`, and `-rsp_crl`. This work was sponsored by Siemens AG. *Rajeev Ranjan* * Added support for issuedOnBehalfOf, auditIdentity, basicAttConstraints, userNotice, acceptablePrivilegePolicies, acceptableCertPolicies, subjectDirectoryAttributes, associatedInformation, delegatedNameConstraints, holderNameConstraints and targetingInformation X.509v3 extensions. *Jonathan M. Wilbur* * Added Attribute Certificate (RFC 5755) support. Attribute Certificates can be created, parsed, modified and printed via the public API. There is no command-line tool support at this time. *Damian Hobson-Garcia* * Added support to build Position Independent Executables (PIE). Configuration option `enable-pie` configures the cflag '-fPIE' and ldflag '-pie' to support Address Space Layout Randomization (ASLR) in the openssl executable, removes reliance on external toolchain configurations. *Craig Lorentzen* * SSL_SESSION_get_time()/SSL_SESSION_set_time()/SSL_CTX_flush_sessions() have been deprecated in favour of their respective ..._ex() replacement functions which are Y2038-safe. *Alexander Kanavin* * ECC groups may now customize their initialization to save CPU by using precomputed values. This is used by the P-256 implementation. *Watson Ladd* OpenSSL 3.3 ----------- ### Changes between 3.3.2 and 3.3.3 [xx XXX xxxx] * Fixed possible OOB memory access with invalid low-level GF(2^m) elliptic curve parameters. Use of the low-level GF(2^m) elliptic curve APIs with untrusted explicit values for the field polynomial can lead to out-of-bounds memory reads or writes. Applications working with "exotic" explicit binary (GF(2^m)) curve parameters, that make it possible to represent invalid field polynomials with a zero constant term, via the above or similar APIs, may terminate abruptly as a result of reading or writing outside of array bounds. Remote code execution cannot easily be ruled out. ([CVE-2024-9143]) *Viktor Dukhovni* ### Changes between 3.3.1 and 3.3.2 [3 Sep 2024] * Fixed possible denial of service in X.509 name checks. Applications performing certificate name checks (e.g., TLS clients checking server certificates) may attempt to read an invalid memory address when comparing the expected name with an `otherName` subject alternative name of an X.509 certificate. This may result in an exception that terminates the application program. ([CVE-2024-6119]) *Viktor Dukhovni* * Fixed possible buffer overread in SSL_select_next_proto(). Calling the OpenSSL API function SSL_select_next_proto with an empty supported client protocols buffer may cause a crash or memory contents to be sent to the peer. ([CVE-2024-5535]) *Matt Caswell* ### Changes between 3.3.0 and 3.3.1 [4 Jun 2024] * Fixed potential use after free after SSL_free_buffers() is called. The SSL_free_buffers function is used to free the internal OpenSSL buffer used when processing an incoming record from the network. The call is only expected to succeed if the buffer is not currently in use. However, two scenarios have been identified where the buffer is freed even when still in use. The first scenario occurs where a record header has been received from the network and processed by OpenSSL, but the full record body has not yet arrived. In this case calling SSL_free_buffers will succeed even though a record has only been partially processed and the buffer is still in use. The second scenario occurs where a full record containing application data has been received and processed by OpenSSL but the application has only read part of this data. Again a call to SSL_free_buffers will succeed even though the buffer is still in use. ([CVE-2024-4741]) *Matt Caswell* * Fixed an issue where checking excessively long DSA keys or parameters may be very slow. Applications that use the functions EVP_PKEY_param_check() or EVP_PKEY_public_check() to check a DSA public key or DSA parameters may experience long delays. Where the key or parameters that are being checked have been obtained from an untrusted source this may lead to a Denial of Service. To resolve this issue DSA keys larger than OPENSSL_DSA_MAX_MODULUS_BITS will now fail the check immediately with a DSA_R_MODULUS_TOO_LARGE error reason. ([CVE-2024-4603]) *Tomáš Mráz* * Improved EC/DSA nonce generation routines to avoid bias and timing side channel leaks. Thanks to Florian Sieck from Universität zu Lübeck and George Pantelakis and Hubert Kario from Red Hat for reporting the issues. *Tomáš Mráz and Paul Dale* ### Changes between 3.2 and 3.3.0 [9 Apr 2024] * The `-verify` option to the `openssl crl` and `openssl req` will make the program exit with 1 on failure. *Vladimír Kotal* * The BIO_get_new_index() function can only be called 127 times before it reaches its upper bound of BIO_TYPE_MASK. It will now correctly return an error of -1 once it is exhausted. Users may need to reserve using this function for cases where BIO_find_type() is required. Either BIO_TYPE_NONE or BIO_get_new_index() can be used to supply a type to BIO_meth_new(). *Shane Lontis* * Added API functions SSL_SESSION_get_time_ex(), SSL_SESSION_set_time_ex() using time_t which is Y2038 safe on 32 bit systems when 64 bit time is enabled (e.g via setting glibc macro _TIME_BITS=64). *Ijtaba Hussain* * The d2i_ASN1_GENERALIZEDTIME(), d2i_ASN1_UTCTIME(), ASN1_TIME_check(), and related functions have been augmented to check for a minimum length of the input string, in accordance with ITU-T X.690 section 11.7 and 11.8. *Job Snijders* * Unknown entries in TLS SignatureAlgorithms, ClientSignatureAlgorithms config options and the respective calls to SSL[_CTX]_set1_sigalgs() and SSL[_CTX]_set1_client_sigalgs() that start with `?` character are ignored and the configuration will still be used. Similarly unknown entries that start with `?` character in a TLS Groups config option or set with SSL[_CTX]_set1_groups_list() are ignored and the configuration will still be used. In both cases if the resulting list is empty, an error is returned. *Tomáš Mráz* * The EVP_PKEY_fromdata function has been augmented to allow for the derivation of CRT (Chinese Remainder Theorem) parameters when requested. See the OSSL_PKEY_PARAM_RSA_DERIVE_FROM_PQ param in the EVP_PKEY-RSA documentation. *Neil Horman* * The activate and soft_load configuration settings for providers in openssl.cnf have been updated to require a value of [1|yes|true|on] (in lower or UPPER case) to enable the setting. Conversely a value of [0|no|false|off] will disable the setting. All other values, or the omission of a value for these settings will result in an error. *Neil Horman* * Added `-set_issuer` and `-set_subject` options to `openssl x509` to override the Issuer and Subject when creating a certificate. The `-subj` option now is an alias for `-set_subject`. *Job Snijders, George Michaelson* * OPENSSL_sk_push() and sk__push() functions now return 0 instead of -1 if called with a NULL stack argument. *Tomáš Mráz* * In `openssl speed`, changed the default hash function used with `hmac` from `md5` to `sha256`. *James Muir* * Added several new features of CMPv3 defined in RFC 9480 and RFC 9483: - `certProfile` request message header and respective `-profile` CLI option - support for delayed delivery of all types of response messages This work was sponsored by Siemens AG. *David von Oheimb* * The build of exporters (such as `.pc` files for pkg-config) cleaned up to be less hard coded in the build file templates, and to allow easier addition of more exporters. With that, an exporter for CMake is also added. *Richard Levitte* * The BLAKE2s hash algorithm matches BLAKE2b's support for configurable output length. *Ahelenia Ziemiańska* * New option `SSL_OP_PREFER_NO_DHE_KEX`, which allows configuring a TLS1.3 server to prefer session resumption using PSK-only key exchange over PSK with DHE, if both are available. *Markus Minichmayr, Tapkey GmbH* * New API `SSL_write_ex2`, which can be used to send an end-of-stream (FIN) condition in an optimised way when using QUIC. *Hugo Landau* * New atexit configuration switch, which controls whether the OPENSSL_cleanup is registered when libcrypto is unloaded. This is turned off on NonStop configurations because of loader differences on that platform compared to Linux. *Randall S. Becker* * Support for qlog for tracing QUIC connections has been added. The qlog output from OpenSSL currently uses a pre-standard draft version of qlog. The output from OpenSSL will change in incompatible ways in future releases, and is not subject to any format stability or compatibility guarantees at this time. This functionality can be disabled with the build-time option `no-unstable-qlog`. See the openssl-qlog(7) manpage for details. *Hugo Landau* * Added APIs to allow configuring the negotiated idle timeout for QUIC connections, and to allow determining the number of additional streams that can currently be created for a QUIC connection. *Hugo Landau* * Added APIs to allow disabling implicit QUIC event processing for QUIC SSL objects, allowing applications to control when event handling occurs. Refer to the SSL_get_value_uint(3) manpage for details. *Hugo Landau* * Limited support for polling of QUIC connection and stream objects in a non-blocking manner. Refer to the SSL_poll(3) manpage for details. *Hugo Landau* * Added APIs to allow querying the size and utilisation of a QUIC stream's write buffer. Refer to the SSL_get_value_uint(3) manpage for details. *Hugo Landau* * New limit on HTTP response headers is introduced to HTTP client. The default limit is set to 256 header lines. If limit is exceeded the response processing stops with error HTTP_R_RESPONSE_TOO_MANY_HDRLINES. Application may call OSSL_HTTP_REQ_CTX_set_max_response_hdr_lines(3) to change the default. Setting the value to 0 disables the limit. *Alexandr Nedvedicky* * Applied AES-GCM unroll8 optimisation to Microsoft Azure Cobalt 100 *Tom Cosgrove* * Added X509_STORE_get1_objects to avoid issues with the existing X509_STORE_get0_objects API in multi-threaded applications. Refer to the documentation for details. *David Benjamin* * Added assembly implementation for md5 on loongarch64 *Min Zhou* * Optimized AES-CTR for ARM Neoverse V1 and V2 *Fisher Yu* * Enable AES and SHA3 optimisations on Apple Silicon M3-based MacOS systems similar to M1/M2. *Tom Cosgrove* * Added a new EVP_DigestSqueeze() API. This allows SHAKE to squeeze multiple times with different output sizes. *Shane Lontis, Holger Dengler* * Various optimizations for cryptographic routines using RISC-V vector crypto extensions *Christoph Müllner, Charalampos Mitrodimas, Ard Biesheuvel, Phoebe Chen, Jerry Shih* * Accept longer context for TLS 1.2 exporters While RFC 5705 implies that the maximum length of a context for exporters is 65535 bytes as the length is embedded in uint16, the previous implementation enforced a much smaller limit, which is less than 1024 bytes. This restriction has been removed. *Daiki Ueno* OpenSSL 3.2 ----------- ### Changes between 3.2.1 and 3.2.2 [xx XXX xxxx] * Fixed an issue where some non-default TLS server configurations can cause unbounded memory growth when processing TLSv1.3 sessions. An attacker may exploit certain server configurations to trigger unbounded memory growth that would lead to a Denial of Service This problem can occur in TLSv1.3 if the non-default SSL_OP_NO_TICKET option is being used (but not if early_data is also configured and the default anti-replay protection is in use). In this case, under certain conditions, the session cache can get into an incorrect state and it will fail to flush properly as it fills. The session cache will continue to grow in an unbounded manner. A malicious client could deliberately create the scenario for this failure to force a Denial of Service. It may also happen by accident in normal operation. ([CVE-2024-2511]) *Matt Caswell* * Fixed bug where SSL_export_keying_material() could not be used with QUIC connections. (#23560) *Hugo Landau* ### Changes between 3.2.0 and 3.2.1 [30 Jan 2024] * A file in PKCS12 format can contain certificates and keys and may come from an untrusted source. The PKCS12 specification allows certain fields to be NULL, but OpenSSL did not correctly check for this case. A fix has been applied to prevent a NULL pointer dereference that results in OpenSSL crashing. If an application processes PKCS12 files from an untrusted source using the OpenSSL APIs then that application will be vulnerable to this issue prior to this fix. OpenSSL APIs that were vulnerable to this are: PKCS12_parse(), PKCS12_unpack_p7data(), PKCS12_unpack_p7encdata(), PKCS12_unpack_authsafes() and PKCS12_newpass(). We have also fixed a similar issue in SMIME_write_PKCS7(). However since this function is related to writing data we do not consider it security significant. ([CVE-2024-0727]) *Matt Caswell* * When function EVP_PKEY_public_check() is called on RSA public keys, a computation is done to confirm that the RSA modulus, n, is composite. For valid RSA keys, n is a product of two or more large primes and this computation completes quickly. However, if n is an overly large prime, then this computation would take a long time. An application that calls EVP_PKEY_public_check() and supplies an RSA key obtained from an untrusted source could be vulnerable to a Denial of Service attack. The function EVP_PKEY_public_check() is not called from other OpenSSL functions however it is called from the OpenSSL pkey command line application. For that reason that application is also vulnerable if used with the "-pubin" and "-check" options on untrusted data. To resolve this issue RSA keys larger than OPENSSL_RSA_MAX_MODULUS_BITS will now fail the check immediately with an RSA_R_MODULUS_TOO_LARGE error reason. ([CVE-2023-6237]) *Tomáš Mráz* * Restore the encoding of SM2 PrivateKeyInfo and SubjectPublicKeyInfo to have the contained AlgorithmIdentifier.algorithm set to id-ecPublicKey rather than SM2. *Richard Levitte* * The POLY1305 MAC (message authentication code) implementation in OpenSSL for PowerPC CPUs saves the contents of vector registers in different order than they are restored. Thus the contents of some of these vector registers is corrupted when returning to the caller. The vulnerable code is used only on newer PowerPC processors supporting the PowerISA 2.07 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 unless the compiler uses the vector registers for storing pointers, 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-6129]) *Rohan McLure* * Disable building QUIC server utility when OpenSSL is configured with `no-apps`. *Vitalii Koshura* ### Changes between 3.1 and 3.2.0 [23 Nov 2023] * Fix excessive time spent in DH check / generation with large Q parameter value. Applications that use the functions DH_generate_key() to generate an X9.42 DH key may experience long delays. Likewise, applications that use DH_check_pub_key(), DH_check_pub_key_ex() or EVP_PKEY_public_check() to check an X9.42 DH key or X9.42 DH parameters may experience long delays. Where the key or parameters that are being checked have been obtained from an untrusted source this may lead to a Denial of Service. ([CVE-2023-5678]) *Richard Levitte* * The BLAKE2b hash algorithm supports a configurable output length by setting the "size" parameter. *Čestmír Kalina and Tomáš Mráz* * Enable extra Arm64 optimization on Windows for GHASH, RAND and AES. *Evgeny Karpov* * Added a function to delete objects from store by URI - OSSL_STORE_delete() and the corresponding provider-storemgmt API function OSSL_FUNC_store_delete(). *Dmitry Belyavskiy* * Added OSSL_FUNC_store_open_ex() provider-storemgmt API function to pass a passphrase callback when opening a store. *Simo Sorce* * Changed the default salt length used by PBES2 KDF's (PBKDF2 and scrypt) from 8 bytes to 16 bytes. The PKCS5 (RFC 8018) standard uses a 64 bit salt length for PBE, and recommends a minimum of 64 bits for PBES2. For FIPS compliance PBKDF2 requires a salt length of 128 bits. This affects OpenSSL command line applications such as "genrsa" and "pkcs8" and API's such as PEM_write_bio_PrivateKey() that are reliant on the default value. The additional commandline option 'saltlen' has been added to the OpenSSL command line applications for "pkcs8" and "enc" to allow the salt length to be set to a non default value. *Shane Lontis* * Changed the default value of the `ess_cert_id_alg` configuration option which is used to calculate the TSA's public key certificate identifier. The default algorithm is updated to be sha256 instead of sha1. *Małgorzata Olszówka* * Added optimization for SM2 algorithm on aarch64. It uses a huge precomputed table for point multiplication of the base point, which increases the size of libcrypto from 4.4 MB to 4.9 MB. A new configure option `no-sm2-precomp` has been added to disable the precomputed table. *Xu Yizhou* * Added client side support for QUIC *Hugo Landau, Matt Caswell, Paul Dale, Tomáš Mráz, Richard Levitte* * Added multiple tutorials on the OpenSSL library and in particular on writing various clients (using TLS and QUIC protocols) with libssl. *Matt Caswell* * Added secp384r1 implementation using Solinas' reduction to improve speed of the NIST P-384 elliptic curve. To enable the implementation the build option `enable-ec_nistp_64_gcc_128` must be used. *Rohan McLure* * Improved RFC7468 compliance of the asn1parse command. *Matthias St. Pierre* * Added SHA256/192 algorithm support. *Fergus Dall* * Improved contention on global write locks by using more read locks where appropriate. *Matt Caswell* * Improved performance of OSSL_PARAM lookups in performance critical provider functions. *Paul Dale* * Added the SSL_get0_group_name() function to provide access to the name of the group used for the TLS key exchange. *Alex Bozarth* * Provide a new configure option `no-http` that can be used to disable the HTTP support. Provide new configure options `no-apps` and `no-docs` to disable building the openssl command line application and the documentation. *Vladimír Kotal* * Provide a new configure option `no-ecx` that can be used to disable the X25519, X448, and EdDSA support. *Yi Li* * When multiple OSSL_KDF_PARAM_INFO parameters are passed to the EVP_KDF_CTX_set_params() function they are now concatenated not just for the HKDF algorithm but also for SSKDF and X9.63 KDF algorithms. *Paul Dale* * Added OSSL_FUNC_keymgmt_im/export_types_ex() provider functions that get the provider context as a parameter. *Ingo Franzki* * TLS round-trip time calculation was added by a Brigham Young University Capstone team partnering with Sandia National Laboratories. A new function in ssl_lib titled SSL_get_handshake_rtt will calculate and retrieve this value. *Jairus Christensen* * Added the "-quic" option to s_client to enable connectivity to QUIC servers. QUIC requires the use of ALPN, so this must be specified via the "-alpn" option. Use of the "advanced" s_client command command via the "-adv" option is recommended. *Matt Caswell* * Added an "advanced" command mode to s_client. Use this with the "-adv" option. The old "basic" command mode recognises certain letters that must always appear at the start of a line and cannot be escaped. The advanced command mode enables commands to be entered anywhere and there is an escaping mechanism. After starting s_client with "-adv" type "{help}" to show a list of available commands. *Matt Caswell* * Add Raw Public Key (RFC7250) support. Authentication is supported by matching keys against either local policy (TLSA records synthesised from the expected keys) or DANE (TLSA records obtained by the application from DNS). TLSA records will also match the same key in the server certificate, should RPK use not happen to be negotiated. *Todd Short* * Added support for modular exponentiation and CRT offloading for the S390x architecture. *Juergen Christ* * Added further assembler code for the RISC-V architecture. *Christoph Müllner* * Added EC_GROUP_to_params() which creates an OSSL_PARAM array from a given EC_GROUP. *Oliver Mihatsch* * Improved support for non-default library contexts and property queries when parsing PKCS#12 files. *Shane Lontis* * Implemented support for all five instances of EdDSA from RFC8032: Ed25519, Ed25519ctx, Ed25519ph, Ed448, and Ed448ph. The streaming is not yet supported for the HashEdDSA variants (Ed25519ph and Ed448ph). *James Muir* * Added SM4 optimization for ARM processors using ASIMD and AES HW instructions. *Xu Yizhou* * Implemented SM4-XTS support. *Xu Yizhou* * Added platform-agnostic OSSL_sleep() function. *Richard Levitte* * Implemented deterministic ECDSA signatures (RFC6979) support. *Shane Lontis* * Implemented AES-GCM-SIV (RFC8452) support. *Todd Short* * Added support for pluggable (provider-based) TLS signature algorithms. This enables TLS 1.3 authentication operations with algorithms embedded in providers not included by default in OpenSSL. In combination with the already available pluggable KEM and X.509 support, this enables for example suitable providers to deliver post-quantum or quantum-safe cryptography to OpenSSL users. *Michael Baentsch* * Added support for pluggable (provider-based) CMS signature algorithms. This enables CMS sign and verify operations with algorithms embedded in providers not included by default in OpenSSL. *Michael Baentsch* * Added support for Hybrid Public Key Encryption (HPKE) as defined in RFC9180. HPKE is required for TLS Encrypted ClientHello (ECH), Message Layer Security (MLS) and other IETF specifications. HPKE can also be used by other applications that require encrypting "to" an ECDH public key. External APIs are defined in include/openssl/hpke.h and documented in doc/man3/OSSL_HPKE_CTX_new.pod *Stephen Farrell* * Implemented HPKE DHKEM support in providers used by HPKE (RFC9180) API. *Shane Lontis* * Add support for certificate compression (RFC8879), including library support for Brotli and Zstandard compression. *Todd Short* * Add the ability to add custom attributes to PKCS12 files. Add a new API PKCS12_create_ex2, identical to the existing PKCS12_create_ex but allows for a user specified callback and optional argument. Added a new PKCS12_SAFEBAG_set0_attr, which allows for a new attr to be added to the existing STACK_OF attrs. *Graham Woodward* * Major refactor of the libssl record layer. *Matt Caswell* * Add a mac salt length option for the pkcs12 command. *Xinping Chen* * Add more SRTP protection profiles from RFC8723 and RFC8269. *Kijin Kim* * Extended Kernel TLS (KTLS) to support TLS 1.3 receive offload. *Daiki Ueno, John Baldwin and Dmitry Podgorny* * Add support for TCP Fast Open (RFC7413) to macOS, Linux, and FreeBSD where supported and enabled. *Todd Short* * 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* * Add new SSL APIs to aid in efficiently implementing TLS/SSL fingerprinting. The SSL_CTRL_GET_IANA_GROUPS control code, exposed as the SSL_get0_iana_groups() function-like macro, retrieves the list of supported groups sent by the peer. The function SSL_client_hello_get_extension_order() populates a caller-supplied array with the list of extension types present in the ClientHello, in order of appearance. *Phus Lu* * Fixed PEM_write_bio_PKCS8PrivateKey() and PEM_write_bio_PKCS8PrivateKey_nid() to make it possible to use empty passphrase strings. *Darshan Sen* * The PKCS12_parse() function now supports MAC-less PKCS12 files. *Daniel Fiala* * Added ASYNC_set_mem_functions() and ASYNC_get_mem_functions() calls to be able to change functions used for allocating the memory of asynchronous call stack. *Arran Cudbard-Bell* * Added support for signed BIGNUMs in the OSSL_PARAM APIs. *Richard Levitte* * A failure exit code is returned when using the openssl x509 command to check certificate attributes and the checks fail. *Rami Khaldi* * The default SSL/TLS security level has been changed from 1 to 2. RSA, DSA and DH keys of 1024 bits and above and less than 2048 bits and ECC keys of 160 bits and above and less than 224 bits were previously accepted by default but are now no longer allowed. By default TLS compression was already disabled in previous OpenSSL versions. At security level 2 it cannot be enabled. *Matt Caswell* * The SSL_CTX_set_cipher_list family functions now accept ciphers using their IANA standard names. *Erik Lax* * The PVK key derivation function has been moved from b2i_PVK_bio_ex() into the legacy crypto provider as an EVP_KDF. Applications requiring this KDF will need to load the legacy crypto provider. *Paul Dale* * CCM8 cipher suites in TLS have been downgraded to security level zero because they use a short authentication tag which lowers their strength. *Paul Dale* * Subject or issuer names in X.509 objects are now displayed as UTF-8 strings by default. Also spaces surrounding `=` in DN output are removed. *Dmitry Belyavskiy* * Add X.509 certificate codeSigning purpose and related checks on key usage and extended key usage of the leaf certificate according to the CA/Browser Forum. * Lutz Jänicke* * The `x509`, `ca`, and `req` commands now produce X.509 v3 certificates. The `-x509v1` option of `req` prefers generation of X.509 v1 certificates. `X509_sign()` and `X509_sign_ctx()` make sure that the certificate has X.509 version 3 if the certificate information includes X.509 extensions. *David von Oheimb* * Fix and extend certificate handling and the commands `x509`, `verify` etc. such as adding a trace facility for debugging certificate chain building. *David von Oheimb* * Various fixes and extensions to the CMP+CRMF implementation and the `cmp` app in particular supporting various types of genm/genp exchanges such as getting CA certificates and root CA cert updates defined in CMP Updates [RFC 9480], as well as the `-srvcertout` and `-serial` CLI options. This work was sponsored by Siemens AG. *David von Oheimb* * Fixes and extensions to the HTTP client and to the HTTP server in `apps/` like correcting the TLS and proxy support and adding tracing for debugging. *David von Oheimb* * Extended the CMS API for handling `CMS_SignedData` and `CMS_EnvelopedData`. *David von Oheimb* * `CMS_add0_cert()` and `CMS_add1_cert()` no longer throw an error if a certificate to be added is already present. `CMS_sign_ex()` and `CMS_sign()` now ignore any duplicate certificates in their `certs` argument and no longer throw an error for them. *David von Oheimb* * Fixed and extended `util/check-format.pl` for checking adherence to the coding style . The checks are meanwhile more complete and yield fewer false positives. *David von Oheimb* * Added BIO_s_dgram_pair() and BIO_s_dgram_mem() that provide memory-based BIOs with datagram semantics and support for BIO_sendmmsg() and BIO_recvmmsg() calls. They can be used as the transport BIOs for QUIC. *Hugo Landau, Matt Caswell and Tomáš Mráz* * Add new BIO_sendmmsg() and BIO_recvmmsg() BIO methods which allow sending and receiving multiple messages in a single call. An implementation is provided for BIO_dgram. For further details, see BIO_sendmmsg(3). *Hugo Landau* * Support for loading root certificates from the Windows certificate store has been added. The support is in the form of a store which recognises the URI string of `org.openssl.winstore://`. This URI scheme currently takes no arguments. This store is built by default and can be disabled using the new compile-time option `no-winstore`. This store is not currently used by default and must be loaded explicitly using the above store URI. It is expected to be loaded by default in the future. *Hugo Landau* * Enable KTLS with the TLS 1.3 CCM mode ciphersuites. Note that some linux kernel versions that support KTLS have a known bug in CCM processing. That has been fixed in stable releases starting from 5.4.164, 5.10.84, 5.15.7, and all releases since 5.16. KTLS with CCM ciphersuites should be only used on these releases. *Tianjia Zhang* * Added `-ktls` option to `s_server` and `s_client` commands to enable the KTLS support. *Tianjia Zhang* * Zerocopy KTLS sendfile() support on Linux. *Maxim Mikityanskiy* * The OBJ_ calls are now thread safe using a global lock. *Paul Dale* * New parameter `-digest` for openssl cms command allowing signing pre-computed digests and new CMS API functions supporting that functionality. *Viktor Söderqvist* * OPENSSL_malloc() and other allocation functions now raise errors on allocation failures. The callers do not need to explicitly raise errors unless they want to for tracing purposes. *David von Oheimb* * Added and enabled by default implicit rejection in RSA PKCS#1 v1.5 decryption as a protection against Bleichenbacher-like attacks. The RSA decryption API will now return a randomly generated deterministic message instead of an error in case it detects an error when checking padding during PKCS#1 v1.5 decryption. This is a general protection against issues like CVE-2020-25659 and CVE-2020-25657. This protection can be disabled by calling `EVP_PKEY_CTX_ctrl_str(ctx, "rsa_pkcs1_implicit_rejection". "0")` on the RSA decryption context. *Hubert Kario* * Added support for Brainpool curves in TLS-1.3. *Bernd Edlinger and Matt Caswell* * Added OpenBSD specific build targets. *David Carlier* * Support for Argon2d, Argon2i, Argon2id KDFs has been added along with a basic thread pool implementation for select platforms. *Čestmír Kalina* OpenSSL 3.1 ----------- ### Changes between 3.1.3 and 3.1.4 [24 Oct 2023] * Fix incorrect key and IV resizing issues when calling EVP_EncryptInit_ex2(), EVP_DecryptInit_ex2() or EVP_CipherInit_ex2() with OSSL_PARAM parameters that alter the key or IV length ([CVE-2023-5363]). *Paul Dale* ### Changes between 3.1.2 and 3.1.3 [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.1.1 and 3.1.2 [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* * When building with the `enable-fips` option and using the resulting FIPS provider, TLS 1.2 will, by default, mandate the use of an extended master secret (FIPS 140-3 IG G.Q) and the Hash and HMAC DRBGs will not operate with truncated digests (FIPS 140-3 IG G.R). *Paul Dale* ### Changes between 3.1.0 and 3.1.1 [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* * Multiple algorithm implementation fixes for ARM BE platforms. *Liu-ErMeng* * Added a -pedantic option to fipsinstall that adjusts the various settings to ensure strict FIPS compliance rather than backwards compatibility. *Paul Dale* * 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* * Add FIPS provider configuration option to disallow the use of truncated digests with Hash and HMAC DRBGs (q.v. FIPS 140-3 IG D.R.). The option '-no_drbg_truncated_digests' can optionally be supplied to 'openssl fipsinstall'. *Paul Dale* * 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 and 3.1.0 [14 Mar 2023] * Add FIPS provider configuration option to enforce the Extended Master Secret (EMS) check during the TLS1_PRF KDF. The option '-ems_check' can optionally be supplied to 'openssl fipsinstall'. *Shane Lontis* * The FIPS provider includes a few non-approved algorithms for backward compatibility purposes and the "fips=yes" property query must be used for all algorithm fetches to ensure FIPS compliance. The algorithms that are included but not approved are Triple DES ECB, Triple DES CBC and EdDSA. *Paul Dale* * Added support for KMAC in KBKDF. *Shane Lontis* * RNDR and RNDRRS support in provider functions to provide random number generation for Arm CPUs (aarch64). *Orr Toledano* * `s_client` and `s_server` commands now explicitly say when the TLS version does not include the renegotiation mechanism. This avoids confusion between that scenario versus when the TLS version includes secure renegotiation but the peer lacks support for it. *Felipe Gasper* * AES-GCM enabled with AVX512 vAES and vPCLMULQDQ. *Tomasz Kantecki, Andrey Matyukov* * The various OBJ_* functions have been made thread safe. *Paul Dale* * Parallel dual-prime 1536/2048-bit modular exponentiation for AVX512_IFMA capable processors. *Sergey Kirillov, Andrey Matyukov (Intel Corp)* * The functions `OPENSSL_LH_stats`, `OPENSSL_LH_node_stats`, `OPENSSL_LH_node_usage_stats`, `OPENSSL_LH_stats_bio`, `OPENSSL_LH_node_stats_bio` and `OPENSSL_LH_node_usage_stats_bio` are now marked deprecated from OpenSSL 3.1 onwards and can be disabled by defining `OPENSSL_NO_DEPRECATED_3_1`. The macro `DEFINE_LHASH_OF` is now deprecated in favour of the macro `DEFINE_LHASH_OF_EX`, which omits the corresponding type-specific function definitions for these functions regardless of whether `OPENSSL_NO_DEPRECATED_3_1` is defined. Users of `DEFINE_LHASH_OF` may start receiving deprecation warnings for these functions regardless of whether they are using them. It is recommended that users transition to the new macro, `DEFINE_LHASH_OF_EX`. *Hugo Landau* * When generating safe-prime DH parameters set the recommended private key length equivalent to minimum key lengths as in RFC 7919. *Tomáš Mráz* * Change the default salt length for PKCS#1 RSASSA-PSS signatures to the maximum size that is smaller or equal to the digest length to comply with FIPS 186-4 section 5. This is implemented by a new option `OSSL_PKEY_RSA_PSS_SALT_LEN_AUTO_DIGEST_MAX` ("auto-digestmax") for the `rsa_pss_saltlen` parameter, which is now the default. Signature verification is not affected by this change and continues to work as before. *Clemens Lang* 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.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 occupied 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` command 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 reuse 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 certificate 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 reused 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.1m and 1.1.1n [xx XXX xxxx] ### Changes between 1.1.1l and 1.1.1m [14 Dec 2021] * 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 represented 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 permissible 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 certificate 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 certificate 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 reused 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 (dependent 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 an 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 * * SSLv3 is by default disabled at build-time. Builds that are not configured with "enable-ssl3" will not support SSLv3. *Kurt Roeckx* 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 certificate 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 simultaneous 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 simultaneous 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 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 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 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). ([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 an 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 an 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 an 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. 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* ### 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 an 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.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 hostname. 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 hostname ('-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 hostname. 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 hostname ('-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 an 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 an 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. (Reused 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 an 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-2025-9232]: https://www.openssl.org/news/vulnerabilities.html#CVE-2025-9232 +[CVE-2025-9231]: https://www.openssl.org/news/vulnerabilities.html#CVE-2025-9231 +[CVE-2025-9230]: https://www.openssl.org/news/vulnerabilities.html#CVE-2025-9230 [CVE-2025-4575]: https://www.openssl.org/news/vulnerabilities.html#CVE-2025-4575 [CVE-2024-13176]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-13176 [CVE-2024-9143]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-9143 [CVE-2024-6119]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-6119 [CVE-2024-5535]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-5535 [CVE-2024-4741]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-4741 [CVE-2024-4603]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-4603 [CVE-2024-2511]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-2511 [CVE-2024-0727]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-0727 [CVE-2023-6237]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-6237 [CVE-2023-6129]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-6129 [CVE-2023-5678]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-5678 [CVE-2023-5363]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-5363 [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 [CMVP]: https://csrc.nist.gov/projects/cryptographic-module-validation-program [ESV]: https://csrc.nist.gov/Projects/cryptographic-module-validation-program/entropy-validations diff --git a/NEWS.md b/NEWS.md index 5d8a83f43068..b194dfb7cb06 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,2098 +1,2128 @@ 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.5](#openssl-35) - [OpenSSL 3.4](#openssl-34) - [OpenSSL 3.3](#openssl-33) - [OpenSSL 3.2](#openssl-32) - [OpenSSL 3.1](#openssl-31) - [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.5 ----------- +### Major changes between OpenSSL 3.5.3 and OpenSSL 3.5.4 [30 Sep 2025] + +OpenSSL 3.5.4 is a security patch release. The most severe CVE fixed in this +release is Moderate. + +This release incorporates the following bug fixes and mitigations: + + * Fix Out-of-bounds read & write in RFC 3211 KEK Unwrap. + ([CVE-2025-9230]) + + * Fix Timing side-channel in SM2 algorithm on 64 bit ARM. + ([CVE-2025-9231]) + + * Fix Out-of-bounds read in HTTP client no_proxy handling. + ([CVE-2025-9232]) + + * Reverted the synthesised `OPENSSL_VERSION_NUMBER` change for the release + builds, as it broke some exiting applications that relied on the previous + 3.x semantics, as documented in `OpenSSL_version(3)`. + ### Major changes between OpenSSL 3.5.2 and OpenSSL 3.5.3 [16 Sep 2025] - * Added FIPS 140-3 PCT on DH key generation. +OpenSSL 3.5.3 is a bug fix release. + +This release incorporates the following bug fixes and mitigations: - *Nikola Pajkovsky* + * Added FIPS 140-3 PCT on DH key generation. * Fixed the synthesised `OPENSSL_VERSION_NUMBER`. - *Richard Levitte* + * Removed PCT on key import in the FIPS provider as it is not required by + the standard. ### Major changes between OpenSSL 3.5.1 and OpenSSL 3.5.2 [5 Aug 2025] - * none +OpenSSL 3.5.2 is a bug fix release. + +This release incorporates the following bug fixes and mitigations: + + * The FIPS provider now performs a PCT on key import for RSA, EC and ECX. ### Major changes between OpenSSL 3.5.0 and OpenSSL 3.5.1 [1 Jul 2025] OpenSSL 3.5.1 is a security patch release. The most severe CVE fixed in this release is Low. This release incorporates the following bug fixes and mitigations: * Fix x509 application adds trusted use instead of rejected use. - ([CVE-2025-4575]) + ([CVE-2025-4575]) ### Major changes between OpenSSL 3.4 and OpenSSL 3.5.0 [8 Apr 2025] OpenSSL 3.5.0 is a feature release adding significant new functionality to OpenSSL. This release incorporates the following potentially significant or incompatible changes: * Default encryption cipher for the `req`, `cms`, and `smime` applications changed from `des-ede3-cbc` to `aes-256-cbc`. * The default TLS supported groups list has been changed to include and prefer hybrid PQC KEM groups. Some practically unused groups were removed from the default list. * The default TLS keyshares have been changed to offer X25519MLKEM768 and and X25519. * All `BIO_meth_get_*()` functions were deprecated. This release adds the following new features: * Support for server side QUIC (RFC 9000) * Support for 3rd party QUIC stacks including 0-RTT support * Support for PQC algorithms (ML-KEM, ML-DSA and SLH-DSA) * A new configuration option `no-tls-deprecated-ec` to disable support for TLS groups deprecated in RFC8422 * A new configuration option `enable-fips-jitter` to make the FIPS provider to use the `JITTER` seed source * Support for central key generation in CMP * Support added for opaque symmetric key objects (EVP_SKEY) * Support for multiple TLS keyshares and improved TLS key establishment group configurability * API support for pipelining in provided cipher algorithms Known issues in 3.5.0 * Calling SSL_accept on objects returned from SSL_accept_connection results in error. It is expected that making this call will advance the SSL handshake for the passed connection, but currently it does not. This can be handled by calling SSL_do_handshake instead. A fix is planned for OpenSSL 3.5.1 OpenSSL 3.4 ----------- ### Major changes between OpenSSL 3.4.0 and OpenSSL 3.4.1 [11 Feb 2025] OpenSSL 3.4.1 is a security patch release. The most severe CVE fixed in this release is High. This release incorporates the following bug fixes and mitigations: * Fixed RFC7250 handshakes with unauthenticated servers don't abort as expected. ([CVE-2024-12797]) * Fixed timing side-channel in ECDSA signature computation. ([CVE-2024-13176]) ### Major changes between OpenSSL 3.3 and OpenSSL 3.4.0 [22 Oct 2024] OpenSSL 3.4.0 is a feature release adding significant new functionality to OpenSSL. This release incorporates the following potentially significant or incompatible changes: * Deprecation of TS_VERIFY_CTX_set_* functions and addition of replacement TS_VERIFY_CTX_set0_* functions with improved semantics * Redesigned use of OPENSSLDIR/ENGINESDIR/MODULESDIR on Windows such that what were formerly build time locations can now be defined at run time with registry keys * The X25519 and X448 key exchange implementation in the FIPS provider is unapproved and has `fips=no` property. * SHAKE-128 and SHAKE-256 implementations have no default digest length anymore. That means these algorithms cannot be used with EVP_DigestFinal/_ex() unless the `xoflen` param is set before. * Setting `config_diagnostics=1` in the config file will cause errors to be returned from SSL_CTX_new() and SSL_CTX_new_ex() if there is an error in the ssl module configuration. * An empty renegotiate extension will be used in TLS client hellos instead of the empty renegotiation SCSV, for all connections with a minimum TLS version > 1.0. * Deprecation of SSL_SESSION_get_time(), SSL_SESSION_set_time() and SSL_CTX_flush_sessions() functions in favor of their respective `_ex` functions which are Y2038-safe on platforms with Y2038-safe `time_t` This release adds the following new features: * Support for directly fetched composite signature algorithms such as RSA-SHA2-256 including new API functions * FIPS indicators support in the FIPS provider and various updates of the FIPS provider required for future FIPS 140-3 validations * Implementation of RFC 9579 (PBMAC1) in PKCS#12 * An optional additional random seed source RNG `JITTER` using a statically linked jitterentropy library * New options `-not_before` and `-not_after` for explicit setting start and end dates of certificates created with the `req` and `x509` apps * Support for integrity-only cipher suites TLS_SHA256_SHA256 and TLS_SHA384_SHA384 in TLS 1.3, as defined in RFC 9150 * Support for retrieving certificate request templates and CRLs in CMP * Support for additional X.509v3 extensions related to Attribute Certificates * Initial Attribute Certificate (RFC 5755) support * Possibility to customize ECC groups initialization to use precomputed values to save CPU time and use of this feature by the P-256 implementation OpenSSL 3.3 ----------- ### Major changes between OpenSSL 3.3.2 and OpenSSL 3.3.3 [under development] OpenSSL 3.3.3 is a security patch release. The most severe CVE fixed in this release is Low. This release incorporates the following bug fixes and mitigations: * Fixed possible OOB memory access with invalid low-level GF(2^m) elliptic curve parameters. ([CVE-2024-9143]) ### Major changes between OpenSSL 3.3.1 and OpenSSL 3.3.2 [3 Sep 2024] OpenSSL 3.3.2 is a security patch release. The most severe CVE fixed in this release is Moderate. This release incorporates the following bug fixes and mitigations: * Fixed possible denial of service in X.509 name checks ([CVE-2024-6119]) * Fixed possible buffer overread in SSL_select_next_proto() ([CVE-2024-5535]) ### Major changes between OpenSSL 3.3.0 and OpenSSL 3.3.1 [4 Jun 2024] OpenSSL 3.3.1 is a security patch release. The most severe CVE fixed in this release is Low. This release incorporates the following bug fixes and mitigations: * Fixed potential use after free after SSL_free_buffers() is called ([CVE-2024-4741]) * Fixed an issue where checking excessively long DSA keys or parameters may be very slow ([CVE-2024-4603]) ### Major changes between OpenSSL 3.2 and OpenSSL 3.3.0 [9 Apr 2024] OpenSSL 3.3.0 is a feature release adding significant new functionality to OpenSSL. This release adds the following new features: * Support for qlog for tracing QUIC connections has been added * Added APIs to allow configuring the negotiated idle timeout for QUIC connections, and to allow determining the number of additional streams that can currently be created for a QUIC connection. * Added APIs to allow disabling implicit QUIC event processing for QUIC SSL objects * Added APIs to allow querying the size and utilisation of a QUIC stream's write buffer * New API `SSL_write_ex2`, which can be used to send an end-of-stream (FIN) condition in an optimised way when using QUIC. * Limited support for polling of QUIC connection and stream objects in a non-blocking manner. * Added a new EVP_DigestSqueeze() API. This allows SHAKE to squeeze multiple times with different output sizes. * Added exporter for CMake on Unix and Windows, alongside the pkg-config exporter. * The BLAKE2s hash algorithm matches BLAKE2b's support for configurable output length. * The EVP_PKEY_fromdata function has been augmented to allow for the derivation of CRT (Chinese Remainder Theorem) parameters when requested * Added API functions SSL_SESSION_get_time_ex(), SSL_SESSION_set_time_ex() using time_t which is Y2038 safe on 32 bit systems when 64 bit time is enabled * Unknown entries in TLS SignatureAlgorithms, ClientSignatureAlgorithms config options and the respective calls to SSL[_CTX]_set1_sigalgs() and SSL[_CTX]_set1_client_sigalgs() that start with `?` character are ignored and the configuration will still be used. * Added `-set_issuer` and `-set_subject` options to `openssl x509` to override the Issuer and Subject when creating a certificate. The `-subj` option now is an alias for `-set_subject`. * Added several new features of CMPv3 defined in RFC 9480 and RFC 9483 * New option `SSL_OP_PREFER_NO_DHE_KEX`, which allows configuring a TLS1.3 server to prefer session resumption using PSK-only key exchange over PSK with DHE, if both are available. * New atexit configuration switch, which controls whether the OPENSSL_cleanup is registered when libcrypto is unloaded. * Added X509_STORE_get1_objects to avoid issues with the existing X509_STORE_get0_objects API in multi-threaded applications. * Support for using certificate profiles and extened delayed delivery in CMP This release incorporates the following potentially significant or incompatible changes: * Applied AES-GCM unroll8 optimisation to Microsoft Azure Cobalt 100 * Optimized AES-CTR for ARM Neoverse V1 and V2 * Enable AES and SHA3 optimisations on Apple Silicon M3-based MacOS systems similar to M1/M2. * Various optimizations for cryptographic routines using RISC-V vector crypto extensions * Added assembly implementation for md5 on loongarch64 * Accept longer context for TLS 1.2 exporters * The activate and soft_load configuration settings for providers in openssl.cnf have been updated to require a value of [1|yes|true|on] (in lower or UPPER case) to enable the setting. Conversely a value of [0|no|false|off] will disable the setting. * In `openssl speed`, changed the default hash function used with `hmac` from `md5` to `sha256`. * The `-verify` option to the `openssl crl` and `openssl req` will make the program exit with 1 on failure. * The d2i_ASN1_GENERALIZEDTIME(), d2i_ASN1_UTCTIME(), ASN1_TIME_check(), and related functions have been augmented to check for a minimum length of the input string, in accordance with ITU-T X.690 section 11.7 and 11.8. * OPENSSL_sk_push() and sk__push() functions now return 0 instead of -1 if called with a NULL stack argument. * New limit on HTTP response headers is introduced to HTTP client. The default limit is set to 256 header lines. This release incorporates the following bug fixes and mitigations: * The BIO_get_new_index() function can only be called 127 times before it reaches its upper bound of BIO_TYPE_MASK and will now return -1 once its exhausted. A more detailed list of changes in this release can be found in the [CHANGES.md] file. Users interested in using the new QUIC functionality are encouraged to read the [README file for QUIC][README-QUIC.md], which provides links to relevant documentation and example code. As always, bug reports and issues relating to OpenSSL can be [filed on our issue tracker][issue tracker]. OpenSSL 3.2 ----------- ### Major changes between OpenSSL 3.2.1 and OpenSSL 3.2.2 [under development] OpenSSL 3.2.2 is a security patch release. The most severe CVE fixed in this release is Low. This release incorporates the following bug fixes and mitigations: * Fixed unbounded memory growth with session handling in TLSv1.3 ([CVE-2024-2511]) ### Major changes between OpenSSL 3.2.0 and OpenSSL 3.2.1 [30 Jan 2024] OpenSSL 3.2.1 is a security patch release. The most severe CVE fixed in this release is Low. This release incorporates the following bug fixes and mitigations: * Fixed PKCS12 Decoding crashes ([CVE-2024-0727]) * Fixed excessive time spent checking invalid RSA public keys ([CVE-2023-6237]) * Fixed POLY1305 MAC implementation corrupting vector registers on PowerPC CPUs which support PowerISA 2.07 ([CVE-2023-6129]) ### Major changes between OpenSSL 3.1 and OpenSSL 3.2.0 [23 Nov 2023] OpenSSL 3.2.0 is a feature release adding significant new functionality to OpenSSL. This release incorporates the following potentially significant or incompatible changes: * The default SSL/TLS security level has been changed from 1 to 2. * The `x509`, `ca`, and `req` apps now always produce X.509v3 certificates. * Subject or issuer names in X.509 objects are now displayed as UTF-8 strings by default. Also spaces surrounding `=` in DN output are removed. This release adds the following new features: * Support for client side QUIC, including support for multiple streams (RFC 9000) * Support for Ed25519ctx, Ed25519ph and Ed448ph in addition to existing support for Ed25519 and Ed448 (RFC 8032) * Support for deterministic ECDSA signatures (RFC 6979) * Support for AES-GCM-SIV, a nonce-misuse-resistant AEAD (RFC 8452) * Support for the Argon2 KDF, along with supporting thread pool functionality (RFC 9106) * Support for Hybrid Public Key Encryption (HPKE) (RFC 9180) * Support for SM4-XTS * Support for Brainpool curves in TLS 1.3 * Support for TLS Raw Public Keys (RFC 7250) * Support for TCP Fast Open on Linux, macOS and FreeBSD, where enabled and supported (RFC 7413) * Support for TLS certificate compression, including library support for zlib, Brotli and zstd (RFC 8879) * Support for provider-based pluggable signature algorithms in TLS 1.3 with supporting CMS and X.509 functionality With a suitable provider this enables the use of post-quantum/quantum-safe cryptography. * Support for using the Windows system certificate store as a source of trusted root certificates This is not yet enabled by default and must be activated using an environment variable. This is likely to become enabled by default in a future feature release. * Support for using the IANA standard names in TLS ciphersuite configuration * Multiple new features and improvements to CMP protocol support The following known issues are present in this release and will be rectified in a future release: * Provider-based signature algorithms cannot be configured using the SignatureAlgorithms configuration file parameter (#22761) This release incorporates the following documentation enhancements: * Added multiple tutorials on the OpenSSL library and in particular on writing various clients (using TLS and QUIC protocols) with libssl See [OpenSSL Guide]. This release incorporates the following bug fixes and mitigations: * Fixed excessive time spent in DH check / generation with large Q parameter value ([CVE-2023-5678]) A more detailed list of changes in this release can be found in the [CHANGES.md] file. Users interested in using the new QUIC functionality are encouraged to read the [README file for QUIC][README-QUIC.md], which provides links to relevant documentation and example code. As always, bug reports and issues relating to OpenSSL can be [filed on our issue tracker][issue tracker]. OpenSSL 3.1 ----------- ### Major changes between OpenSSL 3.1.3 and OpenSSL 3.1.4 [24 Oct 2023] * Mitigate incorrect resize handling for symmetric cipher keys and IVs. ([CVE-2023-5363]) ### Major changes between OpenSSL 3.1.2 and OpenSSL 3.1.3 [19 Sep 2023] * Fix POLY1305 MAC implementation corrupting XMM registers on Windows ([CVE-2023-4807]) ### Major changes between OpenSSL 3.1.1 and OpenSSL 3.1.2 [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]) * When building with the `enable-fips` option and using the resulting FIPS provider, TLS 1.2 will, by default, mandate the use of an extended master secret and the Hash and HMAC DRBGs will not operate with truncated digests. ### Major changes between OpenSSL 3.1.0 and OpenSSL 3.1.1 [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 and OpenSSL 3.1.0 [14 Mar 2023] * SSL 3, TLS 1.0, TLS 1.1, and DTLS 1.0 only work at security level 0. * Performance enhancements and new platform support including new assembler code algorithm implementations. * Deprecated LHASH statistics functions. * FIPS 140-3 compliance changes. OpenSSL 3.0 ----------- ### 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 occupied 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 support 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 availability. * 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://github.com/openssl/openssl/wiki/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 * Split 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-2025-9232]: https://www.openssl.org/news/vulnerabilities.html#CVE-2025-9232 +[CVE-2025-9231]: https://www.openssl.org/news/vulnerabilities.html#CVE-2025-9231 +[CVE-2025-9230]: https://www.openssl.org/news/vulnerabilities.html#CVE-2025-9230 [CVE-2025-4575]: https://www.openssl.org/news/vulnerabilities.html#CVE-2025-4575 [CVE-2024-13176]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-13176 [CVE-2024-9143]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-9143 [CVE-2024-6119]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-6119 [CVE-2024-5535]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-5535 [CVE-2024-4741]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-4741 [CVE-2024-4603]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-4603 [CVE-2024-2511]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-2511 [CVE-2024-0727]: https://www.openssl.org/news/vulnerabilities.html#CVE-2024-0727 [CVE-2023-6237]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-6237 [CVE-2023-6129]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-6129 [CVE-2023-5678]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-5678 [CVE-2023-5363]: https://www.openssl.org/news/vulnerabilities.html#CVE-2023-5363 [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 [OpenSSL Guide]: https://www.openssl.org/docs/manmaster/man7/ossl-guide-introduction.html [CHANGES.md]: ./CHANGES.md [README-QUIC.md]: ./README-QUIC.md [issue tracker]: https://github.com/openssl/openssl/issues [CMVP]: https://csrc.nist.gov/projects/cryptographic-module-validation-program [ESV]: https://csrc.nist.gov/Projects/cryptographic-module-validation-program/entropy-validations [jitterentropy-library]: https://github.com/smuellerDD/jitterentropy-library diff --git a/VERSION.dat b/VERSION.dat index 8a2893b68006..a8eb3ac9c421 100644 --- a/VERSION.dat +++ b/VERSION.dat @@ -1,7 +1,7 @@ MAJOR=3 MINOR=5 -PATCH=3 +PATCH=4 PRE_RELEASE_TAG= BUILD_METADATA= -RELEASE_DATE="16 Sep 2025" +RELEASE_DATE="30 Sep 2025" SHLIB_VERSION=3 diff --git a/apps/storeutl.c b/apps/storeutl.c index 62f0e6135640..f8ebde44481c 100644 --- a/apps/storeutl.c +++ b/apps/storeutl.c @@ -1,499 +1,507 @@ /* * Copyright 2016-2025 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 "apps.h" #include "progs.h" #include #include #include #include /* s2i_ASN1_INTEGER */ static int process(const char *uri, const UI_METHOD *uimeth, PW_CB_DATA *uidata, int expected, int criterion, OSSL_STORE_SEARCH *search, int text, int noout, int recursive, int indent, const char *outfile, const char *prog, OSSL_LIB_CTX *libctx); static BIO *out = NULL; typedef enum OPTION_choice { OPT_COMMON, OPT_ENGINE, OPT_OUT, OPT_PASSIN, OPT_NOOUT, OPT_TEXT, OPT_RECURSIVE, OPT_SEARCHFOR_CERTS, OPT_SEARCHFOR_KEYS, OPT_SEARCHFOR_CRLS, OPT_CRITERION_SUBJECT, OPT_CRITERION_ISSUER, OPT_CRITERION_SERIAL, OPT_CRITERION_FINGERPRINT, OPT_CRITERION_ALIAS, OPT_MD, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS storeutl_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] uri\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"", OPT_MD, '-', "Any supported digest"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Search"), {"certs", OPT_SEARCHFOR_CERTS, '-', "Search for certificates only"}, {"keys", OPT_SEARCHFOR_KEYS, '-', "Search for keys only"}, {"crls", OPT_SEARCHFOR_CRLS, '-', "Search for CRLs only"}, {"subject", OPT_CRITERION_SUBJECT, 's', "Search by subject"}, {"issuer", OPT_CRITERION_ISSUER, 's', "Search by issuer and serial, issuer name"}, {"serial", OPT_CRITERION_SERIAL, 's', "Search by issuer and serial, serial number"}, {"fingerprint", OPT_CRITERION_FINGERPRINT, 's', "Search by public key fingerprint, given in hex"}, {"alias", OPT_CRITERION_ALIAS, 's', "Search by alias"}, {"r", OPT_RECURSIVE, '-', "Recurse through names"}, OPT_SECTION("Input"), {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file - default stdout"}, {"text", OPT_TEXT, '-', "Print a text form of the objects"}, {"noout", OPT_NOOUT, '-', "No PEM output, just status"}, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"uri", 0, 0, "URI of the store object"}, {NULL} }; int storeutl_main(int argc, char *argv[]) { int ret = 1, noout = 0, text = 0, recursive = 0; char *outfile = NULL, *passin = NULL, *passinarg = NULL; ENGINE *e = NULL; OPTION_CHOICE o; char *prog; PW_CB_DATA pw_cb_data; int expected = 0; int criterion = 0; X509_NAME *subject = NULL, *issuer = NULL; ASN1_INTEGER *serial = NULL; unsigned char *fingerprint = NULL; size_t fingerprintlen = 0; char *alias = NULL, *digestname = NULL; OSSL_STORE_SEARCH *search = NULL; EVP_MD *digest = NULL; OSSL_LIB_CTX *libctx = app_get0_libctx(); opt_set_unknown_name("digest"); prog = opt_init(argc, argv, storeutl_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(storeutl_options); ret = 0; goto end; case OPT_OUT: outfile = opt_arg(); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_NOOUT: noout = 1; break; case OPT_TEXT: text = 1; break; case OPT_RECURSIVE: recursive = 1; break; case OPT_SEARCHFOR_CERTS: case OPT_SEARCHFOR_KEYS: case OPT_SEARCHFOR_CRLS: if (expected != 0) { BIO_printf(bio_err, "%s: only one search type can be given.\n", prog); goto end; } { static const struct { enum OPTION_choice choice; int type; } map[] = { {OPT_SEARCHFOR_CERTS, OSSL_STORE_INFO_CERT}, {OPT_SEARCHFOR_KEYS, OSSL_STORE_INFO_PKEY}, {OPT_SEARCHFOR_CRLS, OSSL_STORE_INFO_CRL}, }; size_t i; for (i = 0; i < OSSL_NELEM(map); i++) { if (o == map[i].choice) { expected = map[i].type; break; } } /* * If expected wasn't set at this point, it means the map * isn't synchronised with the possible options leading here. */ OPENSSL_assert(expected != 0); } break; case OPT_CRITERION_SUBJECT: if (criterion != 0) { BIO_printf(bio_err, "%s: criterion already given.\n", prog); goto end; } criterion = OSSL_STORE_SEARCH_BY_NAME; if (subject != NULL) { BIO_printf(bio_err, "%s: subject already given.\n", prog); goto end; } subject = parse_name(opt_arg(), MBSTRING_UTF8, 1, "subject"); if (subject == NULL) goto end; break; case OPT_CRITERION_ISSUER: if (criterion != 0 && criterion != OSSL_STORE_SEARCH_BY_ISSUER_SERIAL) { BIO_printf(bio_err, "%s: criterion already given.\n", prog); goto end; } criterion = OSSL_STORE_SEARCH_BY_ISSUER_SERIAL; if (issuer != NULL) { BIO_printf(bio_err, "%s: issuer already given.\n", prog); goto end; } issuer = parse_name(opt_arg(), MBSTRING_UTF8, 1, "issuer"); if (issuer == NULL) goto end; break; case OPT_CRITERION_SERIAL: if (criterion != 0 && criterion != OSSL_STORE_SEARCH_BY_ISSUER_SERIAL) { BIO_printf(bio_err, "%s: criterion already given.\n", prog); goto end; } criterion = OSSL_STORE_SEARCH_BY_ISSUER_SERIAL; if (serial != NULL) { BIO_printf(bio_err, "%s: serial number already given.\n", prog); goto end; } if ((serial = s2i_ASN1_INTEGER(NULL, opt_arg())) == NULL) { BIO_printf(bio_err, "%s: can't parse serial number argument.\n", prog); goto end; } break; case OPT_CRITERION_FINGERPRINT: if (criterion != 0) { BIO_printf(bio_err, "%s: criterion already given.\n", prog); goto end; } criterion = OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT; if (fingerprint != NULL) { BIO_printf(bio_err, "%s: fingerprint already given.\n", prog); goto end; } { long tmplen = 0; if ((fingerprint = OPENSSL_hexstr2buf(opt_arg(), &tmplen)) == NULL) { BIO_printf(bio_err, "%s: can't parse fingerprint argument.\n", prog); goto end; } fingerprintlen = (size_t)tmplen; } break; case OPT_CRITERION_ALIAS: if (criterion != 0) { BIO_printf(bio_err, "%s: criterion already given.\n", prog); goto end; } criterion = OSSL_STORE_SEARCH_BY_ALIAS; if (alias != NULL) { BIO_printf(bio_err, "%s: alias already given.\n", prog); goto end; } if ((alias = OPENSSL_strdup(opt_arg())) == NULL) { BIO_printf(bio_err, "%s: can't parse alias argument.\n", prog); goto end; } break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_MD: digestname = opt_unknown(); break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } /* One argument, the URI */ if (!opt_check_rest_arg("URI")) goto opthelp; argv = opt_rest(); if (!opt_md(digestname, &digest)) goto opthelp; if (criterion != 0) { switch (criterion) { case OSSL_STORE_SEARCH_BY_NAME: if ((search = OSSL_STORE_SEARCH_by_name(subject)) == NULL) { ERR_print_errors(bio_err); goto end; } break; case OSSL_STORE_SEARCH_BY_ISSUER_SERIAL: if (issuer == NULL || serial == NULL) { BIO_printf(bio_err, "%s: both -issuer and -serial must be given.\n", prog); goto end; } if ((search = OSSL_STORE_SEARCH_by_issuer_serial(issuer, serial)) == NULL) { ERR_print_errors(bio_err); goto end; } break; case OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT: if ((search = OSSL_STORE_SEARCH_by_key_fingerprint(digest, fingerprint, fingerprintlen)) == NULL) { ERR_print_errors(bio_err); goto end; } break; case OSSL_STORE_SEARCH_BY_ALIAS: if ((search = OSSL_STORE_SEARCH_by_alias(alias)) == NULL) { ERR_print_errors(bio_err); goto end; } break; } } if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } pw_cb_data.password = passin; pw_cb_data.prompt_info = argv[0]; ret = process(argv[0], get_ui_method(), &pw_cb_data, expected, criterion, search, text, noout, recursive, 0, outfile, prog, libctx); end: EVP_MD_free(digest); OPENSSL_free(fingerprint); OPENSSL_free(alias); ASN1_INTEGER_free(serial); X509_NAME_free(subject); X509_NAME_free(issuer); OSSL_STORE_SEARCH_free(search); BIO_free_all(out); OPENSSL_free(passin); release_engine(e); return ret; } static int indent_printf(int indent, BIO *bio, const char *format, ...) { va_list args; - int ret; + int ret, vret; + + ret = BIO_printf(bio, "%*s", indent, ""); + if (ret < 0) + return ret; va_start(args, format); + vret = BIO_vprintf(bio, format, args); + va_end(args); - ret = BIO_printf(bio, "%*s", indent, "") + BIO_vprintf(bio, format, args); + if (vret < 0) + return vret; + if (vret > INT_MAX - ret) + return INT_MAX; - va_end(args); - return ret; + return ret + vret; } static int process(const char *uri, const UI_METHOD *uimeth, PW_CB_DATA *uidata, int expected, int criterion, OSSL_STORE_SEARCH *search, int text, int noout, int recursive, int indent, const char *outfile, const char *prog, OSSL_LIB_CTX *libctx) { OSSL_STORE_CTX *store_ctx = NULL; int ret = 1, items = 0; if ((store_ctx = OSSL_STORE_open_ex(uri, libctx, app_get0_propq(), uimeth, uidata, NULL, NULL, NULL)) == NULL) { BIO_printf(bio_err, "Couldn't open file or uri %s\n", uri); ERR_print_errors(bio_err); return ret; } if (expected != 0) { if (!OSSL_STORE_expect(store_ctx, expected)) { ERR_print_errors(bio_err); goto end2; } } if (criterion != 0) { if (!OSSL_STORE_supports_search(store_ctx, criterion)) { BIO_printf(bio_err, "%s: the store scheme doesn't support the given search criteria.\n", prog); goto end2; } if (!OSSL_STORE_find(store_ctx, search)) { ERR_print_errors(bio_err); goto end2; } } /* From here on, we count errors, and we'll return the count at the end */ ret = 0; for (;;) { OSSL_STORE_INFO *info = OSSL_STORE_load(store_ctx); int type = info == NULL ? 0 : OSSL_STORE_INFO_get_type(info); const char *infostr = info == NULL ? NULL : OSSL_STORE_INFO_type_string(type); if (info == NULL) { if (OSSL_STORE_error(store_ctx)) { if (recursive) ERR_clear_error(); else ERR_print_errors(bio_err); if (OSSL_STORE_eof(store_ctx)) break; ret++; continue; } if (OSSL_STORE_eof(store_ctx)) break; BIO_printf(bio_err, "ERROR: OSSL_STORE_load() returned NULL without " "eof or error indications\n"); BIO_printf(bio_err, " This is an error in the loader\n"); ERR_print_errors(bio_err); ret++; break; } if (type == OSSL_STORE_INFO_NAME) { const char *name = OSSL_STORE_INFO_get0_NAME(info); const char *desc = OSSL_STORE_INFO_get0_NAME_description(info); indent_printf(indent, bio_out, "%d: %s: %s\n", items, infostr, name); if (desc != NULL) indent_printf(indent, bio_out, "%s\n", desc); } else { indent_printf(indent, bio_out, "%d: %s\n", items, infostr); } if (out == NULL) { if ((out = bio_open_default(outfile, 'w', FORMAT_TEXT)) == NULL) { ret++; goto end2; } } /* * Unfortunately, PEM_X509_INFO_write_bio() is sorely lacking in * functionality, so we must figure out how exactly to write things * ourselves... */ switch (type) { case OSSL_STORE_INFO_NAME: if (recursive) { const char *suburi = OSSL_STORE_INFO_get0_NAME(info); ret += process(suburi, uimeth, uidata, expected, criterion, search, text, noout, recursive, indent + 2, outfile, prog, libctx); } break; case OSSL_STORE_INFO_PARAMS: if (text) EVP_PKEY_print_params(out, OSSL_STORE_INFO_get0_PARAMS(info), 0, NULL); if (!noout) PEM_write_bio_Parameters(out, OSSL_STORE_INFO_get0_PARAMS(info)); break; case OSSL_STORE_INFO_PUBKEY: if (text) EVP_PKEY_print_public(out, OSSL_STORE_INFO_get0_PUBKEY(info), 0, NULL); if (!noout) PEM_write_bio_PUBKEY(out, OSSL_STORE_INFO_get0_PUBKEY(info)); break; case OSSL_STORE_INFO_PKEY: if (text) EVP_PKEY_print_private(out, OSSL_STORE_INFO_get0_PKEY(info), 0, NULL); if (!noout) PEM_write_bio_PrivateKey(out, OSSL_STORE_INFO_get0_PKEY(info), NULL, NULL, 0, NULL, NULL); break; case OSSL_STORE_INFO_CERT: if (text) X509_print(out, OSSL_STORE_INFO_get0_CERT(info)); if (!noout) PEM_write_bio_X509(out, OSSL_STORE_INFO_get0_CERT(info)); break; case OSSL_STORE_INFO_CRL: if (text) X509_CRL_print(out, OSSL_STORE_INFO_get0_CRL(info)); if (!noout) PEM_write_bio_X509_CRL(out, OSSL_STORE_INFO_get0_CRL(info)); break; default: BIO_printf(bio_err, "!!! Unknown code\n"); ret++; break; } items++; OSSL_STORE_INFO_free(info); } indent_printf(indent, out, "Total found: %d\n", items); end2: if (!OSSL_STORE_close(store_ctx)) { ERR_print_errors(bio_err); ret++; } return ret; } diff --git a/crypto/bio/bss_file.c b/crypto/bio/bss_file.c index 2743a14417cf..ddcb4feb6a58 100644 --- a/crypto/bio/bss_file.c +++ b/crypto/bio/bss_file.c @@ -1,421 +1,421 @@ /* * Copyright 1995-2025 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(__linux) || defined(__sun) || defined(__hpux) /* * Following definition aliases fopen to fopen64 on above mentioned * platforms. This makes it possible to open and sequentially access files * larger than 2GB from 32-bit application. It does not allow one to traverse * them beyond 2GB with fseek/ftell, but on the other hand *no* 32-bit * platform permits that, not with fseek/ftell. Not to mention that breaking * 2GB limit for seeking would require surgery to *our* API. But sequential * access suffices for practical cases when you can run into large files, * such as fingerprinting, so we can let API alone. For reference, the list * of 32-bit platforms which allow for sequential access of large files * without extra "magic" comprise *BSD, Darwin, IRIX... */ # ifndef _FILE_OFFSET_BITS # define _FILE_OFFSET_BITS 64 # endif #endif #include #include #include "bio_local.h" #include #if !defined(OPENSSL_NO_STDIO) static int file_write(BIO *h, const char *buf, int num); static int file_read(BIO *h, char *buf, int size); static int file_puts(BIO *h, const char *str); static int file_gets(BIO *h, char *str, int size); static long file_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int file_new(BIO *h); static int file_free(BIO *data); static const BIO_METHOD methods_filep = { BIO_TYPE_FILE, "FILE pointer", bwrite_conv, file_write, bread_conv, file_read, file_puts, file_gets, file_ctrl, file_new, file_free, NULL, /* file_callback_ctrl */ }; BIO *BIO_new_file(const char *filename, const char *mode) { BIO *ret; FILE *file = openssl_fopen(filename, mode); int fp_flags = BIO_CLOSE; if (strchr(mode, 'b') == NULL) fp_flags |= BIO_FP_TEXT; if (file == NULL) { ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(), "calling fopen(%s, %s)", filename, mode); if (errno == ENOENT #ifdef ENXIO || errno == ENXIO #endif ) ERR_raise(ERR_LIB_BIO, BIO_R_NO_SUCH_FILE); else ERR_raise(ERR_LIB_BIO, ERR_R_SYS_LIB); return NULL; } if ((ret = BIO_new(BIO_s_file())) == NULL) { fclose(file); return NULL; } /* we did fopen -> we disengage UPLINK */ BIO_clear_flags(ret, BIO_FLAGS_UPLINK_INTERNAL); BIO_set_fp(ret, file, fp_flags); return ret; } BIO *BIO_new_fp(FILE *stream, int close_flag) { BIO *ret; if ((ret = BIO_new(BIO_s_file())) == NULL) return NULL; /* redundant flag, left for documentation purposes */ BIO_set_flags(ret, BIO_FLAGS_UPLINK_INTERNAL); BIO_set_fp(ret, stream, close_flag); return ret; } const BIO_METHOD *BIO_s_file(void) { return &methods_filep; } static int file_new(BIO *bi) { bi->init = 0; bi->num = 0; bi->ptr = NULL; bi->flags = BIO_FLAGS_UPLINK_INTERNAL; /* default to UPLINK */ return 1; } static int file_free(BIO *a) { if (a == NULL) return 0; if (a->shutdown) { if ((a->init) && (a->ptr != NULL)) { if (a->flags & BIO_FLAGS_UPLINK_INTERNAL) UP_fclose(a->ptr); else fclose(a->ptr); a->ptr = NULL; a->flags = BIO_FLAGS_UPLINK_INTERNAL; } a->init = 0; } return 1; } static int file_read(BIO *b, char *out, int outl) { int ret = 0; if (b->init && (out != NULL)) { if (b->flags & BIO_FLAGS_UPLINK_INTERNAL) ret = UP_fread(out, 1, (int)outl, b->ptr); else ret = fread(out, 1, (int)outl, (FILE *)b->ptr); if (ret == 0 && (b->flags & BIO_FLAGS_UPLINK_INTERNAL ? UP_ferror((FILE *)b->ptr) : ferror((FILE *)b->ptr))) { ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(), "calling fread()"); ERR_raise(ERR_LIB_BIO, ERR_R_SYS_LIB); ret = -1; } } return ret; } static int file_write(BIO *b, const char *in, int inl) { int ret = 0; if (b->init && (in != NULL)) { if (b->flags & BIO_FLAGS_UPLINK_INTERNAL) ret = UP_fwrite(in, (int)inl, 1, b->ptr); else ret = fwrite(in, (int)inl, 1, (FILE *)b->ptr); if (ret) ret = inl; /* ret=fwrite(in,1,(int)inl,(FILE *)b->ptr); */ /* * according to Tim Hudson , the commented out * version above can cause 'inl' write calls under some stupid stdio * implementations (VMS) */ } return ret; } static long file_ctrl(BIO *b, int cmd, long num, void *ptr) { long ret = 1; FILE *fp = (FILE *)b->ptr; FILE **fpp; char p[4]; int st; switch (cmd) { case BIO_C_FILE_SEEK: case BIO_CTRL_RESET: if (b->flags & BIO_FLAGS_UPLINK_INTERNAL) ret = (long)UP_fseek(b->ptr, num, 0); else ret = (long)fseek(fp, num, 0); break; case BIO_CTRL_EOF: if (b->flags & BIO_FLAGS_UPLINK_INTERNAL) ret = (long)UP_feof(fp); else ret = (long)feof(fp); break; case BIO_C_FILE_TELL: case BIO_CTRL_INFO: if (b->flags & BIO_FLAGS_UPLINK_INTERNAL) ret = UP_ftell(b->ptr); else ret = ftell(fp); break; case BIO_C_SET_FILE_PTR: file_free(b); b->shutdown = (int)num & BIO_CLOSE; b->ptr = ptr; b->init = 1; # if BIO_FLAGS_UPLINK_INTERNAL!=0 # if defined(__MINGW32__) && defined(__MSVCRT__) && !defined(_IOB_ENTRIES) # define _IOB_ENTRIES 20 # endif /* Safety net to catch purely internal BIO_set_fp calls */ # if (defined(_MSC_VER) && _MSC_VER>=1900) || defined(__BORLANDC__) if (ptr == stdin || ptr == stdout || ptr == stderr) BIO_clear_flags(b, BIO_FLAGS_UPLINK_INTERNAL); # elif defined(_IOB_ENTRIES) if ((size_t)ptr >= (size_t)stdin && (size_t)ptr < (size_t)(stdin + _IOB_ENTRIES)) BIO_clear_flags(b, BIO_FLAGS_UPLINK_INTERNAL); # endif # endif # ifdef UP_fsetmod if (b->flags & BIO_FLAGS_UPLINK_INTERNAL) UP_fsetmod(b->ptr, (char)((num & BIO_FP_TEXT) ? 't' : 'b')); else # endif { # if defined(OPENSSL_SYS_WINDOWS) int fd = _fileno((FILE *)ptr); if (num & BIO_FP_TEXT) _setmode(fd, _O_TEXT); else _setmode(fd, _O_BINARY); # elif defined(OPENSSL_SYS_MSDOS) int fd = fileno((FILE *)ptr); /* Set correct text/binary mode */ if (num & BIO_FP_TEXT) _setmode(fd, _O_TEXT); /* Dangerous to set stdin/stdout to raw (unless redirected) */ else { if (fd == STDIN_FILENO || fd == STDOUT_FILENO) { if (isatty(fd) <= 0) _setmode(fd, _O_BINARY); } else _setmode(fd, _O_BINARY); } # elif defined(OPENSSL_SYS_WIN32_CYGWIN) int fd = fileno((FILE *)ptr); if (!(num & BIO_FP_TEXT)) setmode(fd, O_BINARY); # endif } break; case BIO_C_SET_FILENAME: file_free(b); b->shutdown = (int)num & BIO_CLOSE; if (num & BIO_FP_APPEND) { if (num & BIO_FP_READ) OPENSSL_strlcpy(p, "a+", sizeof(p)); else OPENSSL_strlcpy(p, "a", sizeof(p)); } else if ((num & BIO_FP_READ) && (num & BIO_FP_WRITE)) OPENSSL_strlcpy(p, "r+", sizeof(p)); else if (num & BIO_FP_WRITE) OPENSSL_strlcpy(p, "w", sizeof(p)); else if (num & BIO_FP_READ) OPENSSL_strlcpy(p, "r", sizeof(p)); else { ERR_raise(ERR_LIB_BIO, BIO_R_BAD_FOPEN_MODE); ret = 0; break; } # if defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_WINDOWS) if (!(num & BIO_FP_TEXT)) OPENSSL_strlcat(p, "b", sizeof(p)); else OPENSSL_strlcat(p, "t", sizeof(p)); # elif defined(OPENSSL_SYS_WIN32_CYGWIN) if (!(num & BIO_FP_TEXT)) OPENSSL_strlcat(p, "b", sizeof(p)); # endif fp = openssl_fopen(ptr, p); if (fp == NULL) { ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(), "calling fopen(%s, %s)", - ptr, p); + (const char *)ptr, p); ERR_raise(ERR_LIB_BIO, ERR_R_SYS_LIB); ret = 0; break; } b->ptr = fp; b->init = 1; /* we did fopen -> we disengage UPLINK */ BIO_clear_flags(b, BIO_FLAGS_UPLINK_INTERNAL); break; case BIO_C_GET_FILE_PTR: /* the ptr parameter is actually a FILE ** in this case. */ if (ptr != NULL) { fpp = (FILE **)ptr; *fpp = (FILE *)b->ptr; } break; case BIO_CTRL_GET_CLOSE: ret = (long)b->shutdown; break; case BIO_CTRL_SET_CLOSE: b->shutdown = (int)num; break; case BIO_CTRL_FLUSH: st = b->flags & BIO_FLAGS_UPLINK_INTERNAL ? UP_fflush(b->ptr) : fflush((FILE *)b->ptr); if (st == EOF) { ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(), "calling fflush()"); ERR_raise(ERR_LIB_BIO, ERR_R_SYS_LIB); ret = 0; } break; case BIO_CTRL_DUP: ret = 1; break; case BIO_CTRL_WPENDING: case BIO_CTRL_PENDING: case BIO_CTRL_PUSH: case BIO_CTRL_POP: default: ret = 0; break; } return ret; } static int file_gets(BIO *bp, char *buf, int size) { int ret = 0; buf[0] = '\0'; if (bp->flags & BIO_FLAGS_UPLINK_INTERNAL) { if (!UP_fgets(buf, size, bp->ptr)) goto err; } else { if (!fgets(buf, size, (FILE *)bp->ptr)) goto err; } if (buf[0] != '\0') ret = strlen(buf); err: return ret; } static int file_puts(BIO *bp, const char *str) { int n, ret; n = strlen(str); ret = file_write(bp, str, n); return ret; } #else static int file_write(BIO *b, const char *in, int inl) { return -1; } static int file_read(BIO *b, char *out, int outl) { return -1; } static int file_puts(BIO *bp, const char *str) { return -1; } static int file_gets(BIO *bp, char *buf, int size) { return 0; } static long file_ctrl(BIO *b, int cmd, long num, void *ptr) { return 0; } static int file_new(BIO *bi) { return 0; } static int file_free(BIO *a) { return 0; } static const BIO_METHOD methods_filep = { BIO_TYPE_FILE, "FILE pointer", bwrite_conv, file_write, bread_conv, file_read, file_puts, file_gets, file_ctrl, file_new, file_free, NULL, /* file_callback_ctrl */ }; const BIO_METHOD *BIO_s_file(void) { return &methods_filep; } BIO *BIO_new_file(const char *filename, const char *mode) { return NULL; } #endif /* OPENSSL_NO_STDIO */ diff --git a/crypto/cms/cms_pwri.c b/crypto/cms/cms_pwri.c index a7d609f83791..ee1b8aa6ed61 100644 --- a/crypto/cms/cms_pwri.c +++ b/crypto/cms/cms_pwri.c @@ -1,425 +1,425 @@ /* * Copyright 2009-2025 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 "cms_local.h" int CMS_RecipientInfo_set0_password(CMS_RecipientInfo *ri, unsigned char *pass, ossl_ssize_t passlen) { CMS_PasswordRecipientInfo *pwri; if (ri->type != CMS_RECIPINFO_PASS) { ERR_raise(ERR_LIB_CMS, CMS_R_NOT_PWRI); return 0; } pwri = ri->d.pwri; pwri->pass = pass; if (pass && passlen < 0) passlen = strlen((char *)pass); pwri->passlen = passlen; return 1; } CMS_RecipientInfo *CMS_add0_recipient_password(CMS_ContentInfo *cms, int iter, int wrap_nid, int pbe_nid, unsigned char *pass, ossl_ssize_t passlen, const EVP_CIPHER *kekciph) { STACK_OF(CMS_RecipientInfo) *ris; CMS_RecipientInfo *ri = NULL; CMS_EncryptedContentInfo *ec; CMS_PasswordRecipientInfo *pwri; EVP_CIPHER_CTX *ctx = NULL; X509_ALGOR *encalg = NULL; unsigned char iv[EVP_MAX_IV_LENGTH]; int ivlen; const CMS_CTX *cms_ctx = ossl_cms_get0_cmsctx(cms); ec = ossl_cms_get0_env_enc_content(cms); if (ec == NULL) return NULL; ris = CMS_get0_RecipientInfos(cms); if (ris == NULL) return NULL; if (wrap_nid <= 0) wrap_nid = NID_id_alg_PWRI_KEK; if (pbe_nid <= 0) pbe_nid = NID_id_pbkdf2; /* Get from enveloped data */ if (kekciph == NULL) kekciph = ec->cipher; if (kekciph == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_CIPHER); return NULL; } if (wrap_nid != NID_id_alg_PWRI_KEK) { ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM); return NULL; } /* Setup algorithm identifier for cipher */ encalg = X509_ALGOR_new(); if (encalg == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); goto err; } ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB); goto err; } if (EVP_EncryptInit_ex(ctx, kekciph, NULL, NULL, NULL) <= 0) { ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB); goto err; } ivlen = EVP_CIPHER_CTX_get_iv_length(ctx); if (ivlen < 0) { ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB); goto err; } if (ivlen > 0) { if (RAND_bytes_ex(ossl_cms_ctx_get0_libctx(cms_ctx), iv, ivlen, 0) <= 0) goto err; if (EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, iv) <= 0) { ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB); goto err; } encalg->parameter = ASN1_TYPE_new(); if (!encalg->parameter) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); goto err; } if (EVP_CIPHER_param_to_asn1(ctx, encalg->parameter) <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR); goto err; } } encalg->algorithm = OBJ_nid2obj(EVP_CIPHER_CTX_get_type(ctx)); EVP_CIPHER_CTX_free(ctx); ctx = NULL; /* Initialize recipient info */ ri = M_ASN1_new_of(CMS_RecipientInfo); if (ri == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); goto err; } ri->d.pwri = M_ASN1_new_of(CMS_PasswordRecipientInfo); if (ri->d.pwri == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); goto err; } ri->type = CMS_RECIPINFO_PASS; pwri = ri->d.pwri; pwri->cms_ctx = cms_ctx; /* Since this is overwritten, free up empty structure already there */ X509_ALGOR_free(pwri->keyEncryptionAlgorithm); pwri->keyEncryptionAlgorithm = X509_ALGOR_new(); if (pwri->keyEncryptionAlgorithm == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); goto err; } pwri->keyEncryptionAlgorithm->algorithm = OBJ_nid2obj(wrap_nid); pwri->keyEncryptionAlgorithm->parameter = ASN1_TYPE_new(); if (pwri->keyEncryptionAlgorithm->parameter == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); goto err; } if (!ASN1_item_pack(encalg, ASN1_ITEM_rptr(X509_ALGOR), &pwri->keyEncryptionAlgorithm->parameter-> value.sequence)) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); goto err; } pwri->keyEncryptionAlgorithm->parameter->type = V_ASN1_SEQUENCE; X509_ALGOR_free(encalg); encalg = NULL; /* Setup PBE algorithm */ pwri->keyDerivationAlgorithm = PKCS5_pbkdf2_set_ex(iter, NULL, 0, -1, -1, cms_ctx->libctx); if (pwri->keyDerivationAlgorithm == NULL) goto err; CMS_RecipientInfo_set0_password(ri, pass, passlen); pwri->version = 0; if (!sk_CMS_RecipientInfo_push(ris, ri)) { ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB); goto err; } return ri; err: EVP_CIPHER_CTX_free(ctx); if (ri) M_ASN1_free_of(ri, CMS_RecipientInfo); X509_ALGOR_free(encalg); return NULL; } /* * This is an implementation of the key wrapping mechanism in RFC3211, at * some point this should go into EVP. */ static int kek_unwrap_key(unsigned char *out, size_t *outlen, const unsigned char *in, size_t inlen, EVP_CIPHER_CTX *ctx) { size_t blocklen = EVP_CIPHER_CTX_get_block_size(ctx); unsigned char *tmp; int outl, rv = 0; if (blocklen == 0) return 0; if (inlen < 2 * blocklen) { /* too small */ return 0; } if (inlen % blocklen) { /* Invalid size */ return 0; } if ((tmp = OPENSSL_malloc(inlen)) == NULL) return 0; /* setup IV by decrypting last two blocks */ if (!EVP_DecryptUpdate(ctx, tmp + inlen - 2 * blocklen, &outl, in + inlen - 2 * blocklen, blocklen * 2) /* * Do a decrypt of last decrypted block to set IV to correct value * output it to start of buffer so we don't corrupt decrypted block * this works because buffer is at least two block lengths long. */ || !EVP_DecryptUpdate(ctx, tmp, &outl, tmp + inlen - blocklen, blocklen) /* Can now decrypt first n - 1 blocks */ || !EVP_DecryptUpdate(ctx, tmp, &outl, in, inlen - blocklen) /* Reset IV to original value */ || !EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, NULL) /* Decrypt again */ || !EVP_DecryptUpdate(ctx, tmp, &outl, tmp, inlen)) goto err; /* Check check bytes */ if (((tmp[1] ^ tmp[4]) & (tmp[2] ^ tmp[5]) & (tmp[3] ^ tmp[6])) != 0xff) { /* Check byte failure */ goto err; } - if (inlen < (size_t)(tmp[0] - 4)) { + if (inlen < 4 + (size_t)tmp[0]) { /* Invalid length value */ goto err; } *outlen = (size_t)tmp[0]; memcpy(out, tmp + 4, *outlen); rv = 1; err: OPENSSL_clear_free(tmp, inlen); return rv; } static int kek_wrap_key(unsigned char *out, size_t *outlen, const unsigned char *in, size_t inlen, EVP_CIPHER_CTX *ctx, const CMS_CTX *cms_ctx) { size_t blocklen = EVP_CIPHER_CTX_get_block_size(ctx); size_t olen; int dummy; if (blocklen == 0) return 0; /* * First decide length of output buffer: need header and round up to * multiple of block length. */ olen = (inlen + 4 + blocklen - 1) / blocklen; olen *= blocklen; if (olen < 2 * blocklen) { /* Key too small */ return 0; } if (inlen > 0xFF) { /* Key too large */ return 0; } if (out) { /* Set header */ out[0] = (unsigned char)inlen; out[1] = in[0] ^ 0xFF; out[2] = in[1] ^ 0xFF; out[3] = in[2] ^ 0xFF; memcpy(out + 4, in, inlen); /* Add random padding to end */ if (olen > inlen + 4 && RAND_bytes_ex(ossl_cms_ctx_get0_libctx(cms_ctx), out + 4 + inlen, olen - 4 - inlen, 0) <= 0) return 0; /* Encrypt twice */ if (!EVP_EncryptUpdate(ctx, out, &dummy, out, olen) || !EVP_EncryptUpdate(ctx, out, &dummy, out, olen)) return 0; } *outlen = olen; return 1; } /* Encrypt/Decrypt content key in PWRI recipient info */ int ossl_cms_RecipientInfo_pwri_crypt(const CMS_ContentInfo *cms, CMS_RecipientInfo *ri, int en_de) { CMS_EncryptedContentInfo *ec; CMS_PasswordRecipientInfo *pwri; int r = 0; X509_ALGOR *algtmp, *kekalg = NULL; EVP_CIPHER_CTX *kekctx = NULL; char name[OSSL_MAX_NAME_SIZE]; EVP_CIPHER *kekcipher; unsigned char *key = NULL; size_t keylen; const CMS_CTX *cms_ctx = ossl_cms_get0_cmsctx(cms); ec = ossl_cms_get0_env_enc_content(cms); pwri = ri->d.pwri; if (pwri->pass == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_PASSWORD); return 0; } algtmp = pwri->keyEncryptionAlgorithm; if (!algtmp || OBJ_obj2nid(algtmp->algorithm) != NID_id_alg_PWRI_KEK) { ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM); return 0; } kekalg = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(X509_ALGOR), algtmp->parameter); if (kekalg == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER); return 0; } OBJ_obj2txt(name, sizeof(name), kekalg->algorithm, 0); kekcipher = EVP_CIPHER_fetch(ossl_cms_ctx_get0_libctx(cms_ctx), name, ossl_cms_ctx_get0_propq(cms_ctx)); if (kekcipher == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_UNKNOWN_CIPHER); goto err; } kekctx = EVP_CIPHER_CTX_new(); if (kekctx == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB); goto err; } /* Fixup cipher based on AlgorithmIdentifier to set IV etc */ if (!EVP_CipherInit_ex(kekctx, kekcipher, NULL, NULL, NULL, en_de)) goto err; EVP_CIPHER_CTX_set_padding(kekctx, 0); if (EVP_CIPHER_asn1_to_param(kekctx, kekalg->parameter) <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR); goto err; } algtmp = pwri->keyDerivationAlgorithm; /* Finish password based key derivation to setup key in "ctx" */ if (EVP_PBE_CipherInit_ex(algtmp->algorithm, (char *)pwri->pass, pwri->passlen, algtmp->parameter, kekctx, en_de, cms_ctx->libctx, cms_ctx->propq) < 0) { ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB); goto err; } /* Finally wrap/unwrap the key */ if (en_de) { if (!kek_wrap_key(NULL, &keylen, ec->key, ec->keylen, kekctx, cms_ctx)) goto err; key = OPENSSL_malloc(keylen); if (key == NULL) goto err; if (!kek_wrap_key(key, &keylen, ec->key, ec->keylen, kekctx, cms_ctx)) goto err; pwri->encryptedKey->data = key; pwri->encryptedKey->length = keylen; } else { key = OPENSSL_malloc(pwri->encryptedKey->length); if (key == NULL) goto err; if (!kek_unwrap_key(key, &keylen, pwri->encryptedKey->data, pwri->encryptedKey->length, kekctx)) { ERR_raise(ERR_LIB_CMS, CMS_R_UNWRAP_FAILURE); goto err; } OPENSSL_clear_free(ec->key, ec->keylen); ec->key = key; ec->keylen = keylen; } r = 1; err: EVP_CIPHER_free(kekcipher); EVP_CIPHER_CTX_free(kekctx); if (!r) OPENSSL_free(key); X509_ALGOR_free(kekalg); return r; } diff --git a/crypto/ec/ecp_sm2p256.c b/crypto/ec/ecp_sm2p256.c index 7668b61378b6..4c39be2186fb 100644 --- a/crypto/ec/ecp_sm2p256.c +++ b/crypto/ec/ecp_sm2p256.c @@ -1,790 +1,695 @@ /* - * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2023-2025 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 * */ /* * SM2 low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include #include #include "crypto/bn.h" #include "ec_local.h" #include "internal/common.h" #include "internal/constant_time.h" #define P256_LIMBS (256 / BN_BITS2) #if !defined(OPENSSL_NO_SM2_PRECOMP) extern const BN_ULONG ecp_sm2p256_precomputed[8 * 32 * 256]; #endif typedef struct { BN_ULONG X[P256_LIMBS]; BN_ULONG Y[P256_LIMBS]; BN_ULONG Z[P256_LIMBS]; } P256_POINT; typedef struct { BN_ULONG X[P256_LIMBS]; BN_ULONG Y[P256_LIMBS]; } P256_POINT_AFFINE; #if !defined(OPENSSL_NO_SM2_PRECOMP) /* Coordinates of G, for which we have precomputed tables */ ALIGN32 static const BN_ULONG def_xG[P256_LIMBS] = { 0x715a4589334c74c7, 0x8fe30bbff2660be1, 0x5f9904466a39c994, 0x32c4ae2c1f198119 }; ALIGN32 static const BN_ULONG def_yG[P256_LIMBS] = { 0x02df32e52139f0a0, 0xd0a9877cc62a4740, 0x59bdcee36b692153, 0xbc3736a2f4f6779c, }; #endif /* p and order for SM2 according to GB/T 32918.5-2017 */ ALIGN32 static const BN_ULONG def_p[P256_LIMBS] = { 0xffffffffffffffff, 0xffffffff00000000, 0xffffffffffffffff, 0xfffffffeffffffff }; -ALIGN32 static const BN_ULONG def_ord[P256_LIMBS] = { - 0x53bbf40939d54123, 0x7203df6b21c6052b, - 0xffffffffffffffff, 0xfffffffeffffffff -}; ALIGN32 static const BN_ULONG ONE[P256_LIMBS] = {1, 0, 0, 0}; /* Functions implemented in assembly */ /* * Most of below mentioned functions *preserve* the property of inputs * being fully reduced, i.e. being in [0, modulus) range. Simply put if * inputs are fully reduced, then output is too. */ /* Right shift: a >> 1 */ void bn_rshift1(BN_ULONG *a); /* Sub: r = a - b */ void bn_sub(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b); /* Modular div by 2: r = a / 2 mod p */ void ecp_sm2p256_div_by_2(BN_ULONG *r, const BN_ULONG *a); /* Modular div by 2: r = a / 2 mod n, where n = ord(p) */ void ecp_sm2p256_div_by_2_mod_ord(BN_ULONG *r, const BN_ULONG *a); /* Modular add: r = a + b mod p */ void ecp_sm2p256_add(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b); /* Modular sub: r = a - b mod p */ void ecp_sm2p256_sub(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b); /* Modular sub: r = a - b mod n, where n = ord(p) */ void ecp_sm2p256_sub_mod_ord(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b); /* Modular mul by 3: out = 3 * a mod p */ void ecp_sm2p256_mul_by_3(BN_ULONG *r, const BN_ULONG *a); /* Modular mul: r = a * b mod p */ void ecp_sm2p256_mul(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b); /* Modular sqr: r = a ^ 2 mod p */ void ecp_sm2p256_sqr(BN_ULONG *r, const BN_ULONG *a); static ossl_inline BN_ULONG is_zeros(const BN_ULONG *a) { BN_ULONG res; res = a[0] | a[1] | a[2] | a[3]; return constant_time_is_zero_64(res); } static ossl_inline int is_equal(const BN_ULONG *a, const BN_ULONG *b) { BN_ULONG res; res = a[0] ^ b[0]; res |= a[1] ^ b[1]; res |= a[2] ^ b[2]; res |= a[3] ^ b[3]; return constant_time_is_zero_64(res); } static ossl_inline int is_greater(const BN_ULONG *a, const BN_ULONG *b) { int i; for (i = P256_LIMBS - 1; i >= 0; --i) { if (a[i] > b[i]) return 1; if (a[i] < b[i]) return -1; } return 0; } #define is_one(a) is_equal(a, ONE) #define is_even(a) !(a[0] & 1) #define is_point_equal(a, b) \ is_equal(a->X, b->X) && \ is_equal(a->Y, b->Y) && \ is_equal(a->Z, b->Z) /* Bignum and field elements conversion */ #define ecp_sm2p256_bignum_field_elem(out, in) \ bn_copy_words(out, in, P256_LIMBS) /* Binary algorithm for inversion in Fp */ #define BN_MOD_INV(out, in, mod_div, mod_sub, mod) \ do { \ ALIGN32 BN_ULONG u[4]; \ ALIGN32 BN_ULONG v[4]; \ ALIGN32 BN_ULONG x1[4] = {1, 0, 0, 0}; \ ALIGN32 BN_ULONG x2[4] = {0}; \ \ if (is_zeros(in)) \ return; \ memcpy(u, in, 32); \ memcpy(v, mod, 32); \ while (!is_one(u) && !is_one(v)) { \ while (is_even(u)) { \ bn_rshift1(u); \ mod_div(x1, x1); \ } \ while (is_even(v)) { \ bn_rshift1(v); \ mod_div(x2, x2); \ } \ if (is_greater(u, v) == 1) { \ bn_sub(u, u, v); \ mod_sub(x1, x1, x2); \ } else { \ bn_sub(v, v, u); \ mod_sub(x2, x2, x1); \ } \ } \ if (is_one(u)) \ memcpy(out, x1, 32); \ else \ memcpy(out, x2, 32); \ } while (0) /* Modular inverse |out| = |in|^(-1) mod |p|. */ static ossl_inline void ecp_sm2p256_mod_inverse(BN_ULONG* out, const BN_ULONG* in) { BN_MOD_INV(out, in, ecp_sm2p256_div_by_2, ecp_sm2p256_sub, def_p); } -/* Modular inverse mod order |out| = |in|^(-1) % |ord|. */ -static ossl_inline void ecp_sm2p256_mod_ord_inverse(BN_ULONG* out, - const BN_ULONG* in) { - BN_MOD_INV(out, in, ecp_sm2p256_div_by_2_mod_ord, ecp_sm2p256_sub_mod_ord, - def_ord); -} - /* Point double: R <- P + P */ static void ecp_sm2p256_point_double(P256_POINT *R, const P256_POINT *P) { unsigned int i; ALIGN32 BN_ULONG tmp0[P256_LIMBS]; ALIGN32 BN_ULONG tmp1[P256_LIMBS]; ALIGN32 BN_ULONG tmp2[P256_LIMBS]; /* zero-check P->Z */ if (is_zeros(P->Z)) { for (i = 0; i < P256_LIMBS; ++i) R->Z[i] = 0; return; } ecp_sm2p256_sqr(tmp0, P->Z); ecp_sm2p256_sub(tmp1, P->X, tmp0); ecp_sm2p256_add(tmp0, P->X, tmp0); ecp_sm2p256_mul(tmp1, tmp1, tmp0); ecp_sm2p256_mul_by_3(tmp1, tmp1); ecp_sm2p256_add(R->Y, P->Y, P->Y); ecp_sm2p256_mul(R->Z, R->Y, P->Z); ecp_sm2p256_sqr(R->Y, R->Y); ecp_sm2p256_mul(tmp2, R->Y, P->X); ecp_sm2p256_sqr(R->Y, R->Y); ecp_sm2p256_div_by_2(R->Y, R->Y); ecp_sm2p256_sqr(R->X, tmp1); ecp_sm2p256_add(tmp0, tmp2, tmp2); ecp_sm2p256_sub(R->X, R->X, tmp0); ecp_sm2p256_sub(tmp0, tmp2, R->X); ecp_sm2p256_mul(tmp0, tmp0, tmp1); ecp_sm2p256_sub(tmp1, tmp0, R->Y); memcpy(R->Y, tmp1, 32); } /* Point add affine: R <- P + Q */ static void ecp_sm2p256_point_add_affine(P256_POINT *R, const P256_POINT *P, const P256_POINT_AFFINE *Q) { unsigned int i; ALIGN32 BN_ULONG tmp0[P256_LIMBS] = {0}; ALIGN32 BN_ULONG tmp1[P256_LIMBS] = {0}; ALIGN32 BN_ULONG tmp2[P256_LIMBS] = {0}; ALIGN32 BN_ULONG tmp3[P256_LIMBS] = {0}; /* zero-check P->Z */ if (is_zeros(P->Z)) { for (i = 0; i < P256_LIMBS; ++i) { R->X[i] = Q->X[i]; R->Y[i] = Q->Y[i]; R->Z[i] = 0; } R->Z[0] = 1; return; } ecp_sm2p256_sqr(tmp0, P->Z); ecp_sm2p256_mul(tmp1, tmp0, P->Z); ecp_sm2p256_mul(tmp0, tmp0, Q->X); ecp_sm2p256_mul(tmp1, tmp1, Q->Y); ecp_sm2p256_sub(tmp0, tmp0, P->X); ecp_sm2p256_sub(tmp1, tmp1, P->Y); /* zero-check tmp0, tmp1 */ if (is_zeros(tmp0)) { if (is_zeros(tmp1)) { P256_POINT K; for (i = 0; i < P256_LIMBS; ++i) { K.X[i] = Q->X[i]; K.Y[i] = Q->Y[i]; K.Z[i] = 0; } K.Z[0] = 1; ecp_sm2p256_point_double(R, &K); } else { for (i = 0; i < P256_LIMBS; ++i) R->Z[i] = 0; } return; } ecp_sm2p256_mul(R->Z, P->Z, tmp0); ecp_sm2p256_sqr(tmp2, tmp0); ecp_sm2p256_mul(tmp3, tmp2, tmp0); ecp_sm2p256_mul(tmp2, tmp2, P->X); ecp_sm2p256_add(tmp0, tmp2, tmp2); ecp_sm2p256_sqr(R->X, tmp1); ecp_sm2p256_sub(R->X, R->X, tmp0); ecp_sm2p256_sub(R->X, R->X, tmp3); ecp_sm2p256_sub(tmp2, tmp2, R->X); ecp_sm2p256_mul(tmp2, tmp2, tmp1); ecp_sm2p256_mul(tmp3, tmp3, P->Y); ecp_sm2p256_sub(R->Y, tmp2, tmp3); } /* Point add: R <- P + Q */ static void ecp_sm2p256_point_add(P256_POINT *R, const P256_POINT *P, const P256_POINT *Q) { unsigned int i; ALIGN32 BN_ULONG tmp0[P256_LIMBS] = {0}; ALIGN32 BN_ULONG tmp1[P256_LIMBS] = {0}; ALIGN32 BN_ULONG tmp2[P256_LIMBS] = {0}; /* zero-check P | Q ->Z */ if (is_zeros(P->Z)) { for (i = 0; i < P256_LIMBS; ++i) { R->X[i] = Q->X[i]; R->Y[i] = Q->Y[i]; R->Z[i] = Q->Z[i]; } return; } else if (is_zeros(Q->Z)) { for (i = 0; i < P256_LIMBS; ++i) { R->X[i] = P->X[i]; R->Y[i] = P->Y[i]; R->Z[i] = P->Z[i]; } return; } else if (is_point_equal(P, Q)) { ecp_sm2p256_point_double(R, Q); return; } ecp_sm2p256_sqr(tmp0, P->Z); ecp_sm2p256_mul(tmp1, tmp0, P->Z); ecp_sm2p256_mul(tmp0, tmp0, Q->X); ecp_sm2p256_mul(tmp1, tmp1, Q->Y); ecp_sm2p256_mul(R->Y, P->Y, Q->Z); ecp_sm2p256_mul(R->Z, Q->Z, P->Z); ecp_sm2p256_sqr(tmp2, Q->Z); ecp_sm2p256_mul(R->Y, tmp2, R->Y); ecp_sm2p256_mul(R->X, tmp2, P->X); ecp_sm2p256_sub(tmp0, tmp0, R->X); ecp_sm2p256_mul(R->Z, tmp0, R->Z); ecp_sm2p256_sub(tmp1, tmp1, R->Y); ecp_sm2p256_sqr(tmp2, tmp0); ecp_sm2p256_mul(tmp0, tmp0, tmp2); ecp_sm2p256_mul(tmp2, tmp2, R->X); ecp_sm2p256_sqr(R->X, tmp1); ecp_sm2p256_sub(R->X, R->X, tmp2); ecp_sm2p256_sub(R->X, R->X, tmp2); ecp_sm2p256_sub(R->X, R->X, tmp0); ecp_sm2p256_sub(tmp2, tmp2, R->X); ecp_sm2p256_mul(tmp2, tmp1, tmp2); ecp_sm2p256_mul(tmp0, tmp0, R->Y); ecp_sm2p256_sub(R->Y, tmp2, tmp0); } #if !defined(OPENSSL_NO_SM2_PRECOMP) /* Base point mul by scalar: k - scalar, G - base point */ static void ecp_sm2p256_point_G_mul_by_scalar(P256_POINT *R, const BN_ULONG *k) { unsigned int i, index, mask = 0xff; P256_POINT_AFFINE Q; memset(R, 0, sizeof(P256_POINT)); if (is_zeros(k)) return; index = k[0] & mask; if (index) { index = index * 8; memcpy(R->X, ecp_sm2p256_precomputed + index, 32); memcpy(R->Y, ecp_sm2p256_precomputed + index + P256_LIMBS, 32); R->Z[0] = 1; } for (i = 1; i < 32; ++i) { index = (k[i / 8] >> (8 * (i % 8))) & mask; if (index) { index = index + i * 256; index = index * 8; memcpy(Q.X, ecp_sm2p256_precomputed + index, 32); memcpy(Q.Y, ecp_sm2p256_precomputed + index + P256_LIMBS, 32); ecp_sm2p256_point_add_affine(R, R, &Q); } } } #endif /* * Affine point mul by scalar: k - scalar, P - affine point */ static void ecp_sm2p256_point_P_mul_by_scalar(P256_POINT *R, const BN_ULONG *k, P256_POINT_AFFINE P) { int i, init = 0; unsigned int index, mask = 0x0f; ALIGN64 P256_POINT precomputed[16]; memset(R, 0, sizeof(P256_POINT)); if (is_zeros(k)) return; /* The first value of the precomputed table is P. */ memcpy(precomputed[1].X, P.X, 32); memcpy(precomputed[1].Y, P.Y, 32); precomputed[1].Z[0] = 1; precomputed[1].Z[1] = 0; precomputed[1].Z[2] = 0; precomputed[1].Z[3] = 0; /* The second value of the precomputed table is 2P. */ ecp_sm2p256_point_double(&precomputed[2], &precomputed[1]); /* The subsequent elements are 3P, 4P, and so on. */ for (i = 3; i < 16; ++i) ecp_sm2p256_point_add_affine(&precomputed[i], &precomputed[i - 1], &P); for (i = 64 - 1; i >= 0; --i) { index = (k[i / 16] >> (4 * (i % 16))) & mask; if (init == 0) { if (index) { memcpy(R, &precomputed[index], sizeof(P256_POINT)); init = 1; } } else { ecp_sm2p256_point_double(R, R); ecp_sm2p256_point_double(R, R); ecp_sm2p256_point_double(R, R); ecp_sm2p256_point_double(R, R); if (index) ecp_sm2p256_point_add(R, R, &precomputed[index]); } } } /* Get affine point */ static void ecp_sm2p256_point_get_affine(P256_POINT_AFFINE *R, const P256_POINT *P) { ALIGN32 BN_ULONG z_inv3[P256_LIMBS] = {0}; ALIGN32 BN_ULONG z_inv2[P256_LIMBS] = {0}; if (is_one(P->Z)) { memcpy(R->X, P->X, 32); memcpy(R->Y, P->Y, 32); return; } ecp_sm2p256_mod_inverse(z_inv3, P->Z); ecp_sm2p256_sqr(z_inv2, z_inv3); ecp_sm2p256_mul(R->X, P->X, z_inv2); ecp_sm2p256_mul(z_inv3, z_inv3, z_inv2); ecp_sm2p256_mul(R->Y, P->Y, z_inv3); } #if !defined(OPENSSL_NO_SM2_PRECOMP) static int ecp_sm2p256_is_affine_G(const EC_POINT *generator) { return (bn_get_top(generator->X) == P256_LIMBS) && (bn_get_top(generator->Y) == P256_LIMBS) && is_equal(bn_get_words(generator->X), def_xG) && is_equal(bn_get_words(generator->Y), def_yG) && (generator->Z_is_one == 1); } #endif -/* - * Convert Jacobian coordinate point into affine coordinate (x,y) - */ -static int ecp_sm2p256_get_affine(const EC_GROUP *group, - const EC_POINT *point, - BIGNUM *x, BIGNUM *y, BN_CTX *ctx) -{ - ALIGN32 BN_ULONG z_inv2[P256_LIMBS] = {0}; - ALIGN32 BN_ULONG z_inv3[P256_LIMBS] = {0}; - ALIGN32 BN_ULONG x_aff[P256_LIMBS] = {0}; - ALIGN32 BN_ULONG y_aff[P256_LIMBS] = {0}; - ALIGN32 BN_ULONG point_x[P256_LIMBS] = {0}; - ALIGN32 BN_ULONG point_y[P256_LIMBS] = {0}; - ALIGN32 BN_ULONG point_z[P256_LIMBS] = {0}; - - if (EC_POINT_is_at_infinity(group, point)) { - ECerr(ERR_LIB_EC, EC_R_POINT_AT_INFINITY); - return 0; - } - - if (ecp_sm2p256_bignum_field_elem(point_x, point->X) <= 0 - || ecp_sm2p256_bignum_field_elem(point_y, point->Y) <= 0 - || ecp_sm2p256_bignum_field_elem(point_z, point->Z) <= 0) { - ECerr(ERR_LIB_EC, EC_R_COORDINATES_OUT_OF_RANGE); - return 0; - } - - ecp_sm2p256_mod_inverse(z_inv3, point_z); - ecp_sm2p256_sqr(z_inv2, z_inv3); - - if (x != NULL) { - ecp_sm2p256_mul(x_aff, point_x, z_inv2); - if (!bn_set_words(x, x_aff, P256_LIMBS)) - return 0; - } - - if (y != NULL) { - ecp_sm2p256_mul(z_inv3, z_inv3, z_inv2); - ecp_sm2p256_mul(y_aff, point_y, z_inv3); - if (!bn_set_words(y, y_aff, P256_LIMBS)) - return 0; - } - - return 1; -} - /* r = sum(scalar[i]*point[i]) */ static int ecp_sm2p256_windowed_mul(const EC_GROUP *group, P256_POINT *r, const BIGNUM **scalar, const EC_POINT **point, size_t num, BN_CTX *ctx) { unsigned int i; int ret = 0; const BIGNUM **scalars = NULL; ALIGN32 BN_ULONG k[P256_LIMBS] = {0}; P256_POINT kP; ALIGN32 union { P256_POINT p; P256_POINT_AFFINE a; } t, p; if (num > OPENSSL_MALLOC_MAX_NELEMS(P256_POINT) || (scalars = OPENSSL_malloc(num * sizeof(BIGNUM *))) == NULL) { ECerr(ERR_LIB_EC, ERR_R_MALLOC_FAILURE); goto err; } memset(r, 0, sizeof(P256_POINT)); for (i = 0; i < num; i++) { if (EC_POINT_is_at_infinity(group, point[i])) continue; if ((BN_num_bits(scalar[i]) > 256) || BN_is_negative(scalar[i])) { BIGNUM *tmp; if ((tmp = BN_CTX_get(ctx)) == NULL) goto err; if (!BN_nnmod(tmp, scalar[i], group->order, ctx)) { ECerr(ERR_LIB_EC, ERR_R_BN_LIB); goto err; } scalars[i] = tmp; } else { scalars[i] = scalar[i]; } if (ecp_sm2p256_bignum_field_elem(k, scalars[i]) <= 0 || ecp_sm2p256_bignum_field_elem(p.p.X, point[i]->X) <= 0 || ecp_sm2p256_bignum_field_elem(p.p.Y, point[i]->Y) <= 0 || ecp_sm2p256_bignum_field_elem(p.p.Z, point[i]->Z) <= 0) { ECerr(ERR_LIB_EC, EC_R_COORDINATES_OUT_OF_RANGE); goto err; } ecp_sm2p256_point_get_affine(&t.a, &p.p); ecp_sm2p256_point_P_mul_by_scalar(&kP, k, t.a); ecp_sm2p256_point_add(r, r, &kP); } ret = 1; err: OPENSSL_free(scalars); return ret; } /* r = scalar*G + sum(scalars[i]*points[i]) */ static int ecp_sm2p256_points_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar, size_t num, const EC_POINT *points[], const BIGNUM *scalars[], BN_CTX *ctx) { int ret = 0, p_is_infinity = 0; const EC_POINT *generator = NULL; ALIGN32 BN_ULONG k[P256_LIMBS] = {0}; ALIGN32 union { P256_POINT p; P256_POINT_AFFINE a; } t, p; if ((num + 1) == 0 || (num + 1) > OPENSSL_MALLOC_MAX_NELEMS(void *)) { ECerr(ERR_LIB_EC, ERR_R_MALLOC_FAILURE); goto err; } BN_CTX_start(ctx); if (scalar) { generator = EC_GROUP_get0_generator(group); if (generator == NULL) { ECerr(ERR_LIB_EC, EC_R_UNDEFINED_GENERATOR); goto err; } if (!ecp_sm2p256_bignum_field_elem(k, scalar)) { ECerr(ERR_LIB_EC, EC_R_COORDINATES_OUT_OF_RANGE); goto err; } #if !defined(OPENSSL_NO_SM2_PRECOMP) if (ecp_sm2p256_is_affine_G(generator)) { ecp_sm2p256_point_G_mul_by_scalar(&p.p, k); } else #endif { /* if no precomputed table */ const EC_POINT *new_generator[1]; const BIGNUM *g_scalars[1]; new_generator[0] = generator; g_scalars[0] = scalar; if (!ecp_sm2p256_windowed_mul(group, &p.p, g_scalars, new_generator, (new_generator[0] != NULL && g_scalars[0] != NULL), ctx)) goto err; } } else { p_is_infinity = 1; } if (num) { P256_POINT *out = &t.p; if (p_is_infinity) out = &p.p; if (!ecp_sm2p256_windowed_mul(group, out, scalars, points, num, ctx)) goto err; if (!p_is_infinity) ecp_sm2p256_point_add(&p.p, &p.p, out); } /* Not constant-time, but we're only operating on the public output. */ if (!bn_set_words(r->X, p.p.X, P256_LIMBS) || !bn_set_words(r->Y, p.p.Y, P256_LIMBS) || !bn_set_words(r->Z, p.p.Z, P256_LIMBS)) goto err; r->Z_is_one = is_equal(bn_get_words(r->Z), ONE) & 1; ret = 1; err: BN_CTX_end(ctx); return ret; } static int ecp_sm2p256_field_mul(const EC_GROUP *group, BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { ALIGN32 BN_ULONG a_fe[P256_LIMBS] = {0}; ALIGN32 BN_ULONG b_fe[P256_LIMBS] = {0}; ALIGN32 BN_ULONG r_fe[P256_LIMBS] = {0}; if (a == NULL || b == NULL || r == NULL) return 0; if (!ecp_sm2p256_bignum_field_elem(a_fe, a) || !ecp_sm2p256_bignum_field_elem(b_fe, b)) { ECerr(ERR_LIB_EC, EC_R_COORDINATES_OUT_OF_RANGE); return 0; } ecp_sm2p256_mul(r_fe, a_fe, b_fe); if (!bn_set_words(r, r_fe, P256_LIMBS)) return 0; return 1; } static int ecp_sm2p256_field_sqr(const EC_GROUP *group, BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) { ALIGN32 BN_ULONG a_fe[P256_LIMBS] = {0}; ALIGN32 BN_ULONG r_fe[P256_LIMBS] = {0}; if (a == NULL || r == NULL) return 0; if (!ecp_sm2p256_bignum_field_elem(a_fe, a)) { ECerr(ERR_LIB_EC, EC_R_COORDINATES_OUT_OF_RANGE); return 0; } ecp_sm2p256_sqr(r_fe, a_fe); if (!bn_set_words(r, r_fe, P256_LIMBS)) return 0; return 1; } -static int ecp_sm2p256_inv_mod_ord(const EC_GROUP *group, BIGNUM *r, - const BIGNUM *x, BN_CTX *ctx) -{ - int ret = 0; - ALIGN32 BN_ULONG t[P256_LIMBS] = {0}; - ALIGN32 BN_ULONG out[P256_LIMBS] = {0}; - - if (bn_wexpand(r, P256_LIMBS) == NULL) { - ECerr(ERR_LIB_EC, ERR_R_BN_LIB); - goto err; - } - - if ((BN_num_bits(x) > 256) || BN_is_negative(x)) { - BIGNUM *tmp; - - if ((tmp = BN_CTX_get(ctx)) == NULL - || !BN_nnmod(tmp, x, group->order, ctx)) { - ECerr(ERR_LIB_EC, ERR_R_BN_LIB); - goto err; - } - x = tmp; - } - - if (!ecp_sm2p256_bignum_field_elem(t, x)) { - ECerr(ERR_LIB_EC, EC_R_COORDINATES_OUT_OF_RANGE); - goto err; - } - - ecp_sm2p256_mod_ord_inverse(out, t); - - if (!bn_set_words(r, out, P256_LIMBS)) - goto err; - - ret = 1; -err: - return ret; -} - const EC_METHOD *EC_GFp_sm2p256_method(void) { static const EC_METHOD ret = { EC_FLAGS_DEFAULT_OCT, NID_X9_62_prime_field, ossl_ec_GFp_simple_group_init, ossl_ec_GFp_simple_group_finish, ossl_ec_GFp_simple_group_clear_finish, ossl_ec_GFp_simple_group_copy, ossl_ec_GFp_simple_group_set_curve, ossl_ec_GFp_simple_group_get_curve, ossl_ec_GFp_simple_group_get_degree, ossl_ec_group_simple_order_bits, ossl_ec_GFp_simple_group_check_discriminant, ossl_ec_GFp_simple_point_init, ossl_ec_GFp_simple_point_finish, ossl_ec_GFp_simple_point_clear_finish, ossl_ec_GFp_simple_point_copy, ossl_ec_GFp_simple_point_set_to_infinity, ossl_ec_GFp_simple_point_set_affine_coordinates, - ecp_sm2p256_get_affine, + ossl_ec_GFp_simple_point_get_affine_coordinates, 0, 0, 0, ossl_ec_GFp_simple_add, ossl_ec_GFp_simple_dbl, ossl_ec_GFp_simple_invert, ossl_ec_GFp_simple_is_at_infinity, ossl_ec_GFp_simple_is_on_curve, ossl_ec_GFp_simple_cmp, ossl_ec_GFp_simple_make_affine, ossl_ec_GFp_simple_points_make_affine, ecp_sm2p256_points_mul, /* mul */ 0 /* precompute_mult */, 0 /* have_precompute_mult */, ecp_sm2p256_field_mul, ecp_sm2p256_field_sqr, 0 /* field_div */, - 0 /* field_inv */, + ossl_ec_GFp_simple_field_inv, 0 /* field_encode */, 0 /* field_decode */, 0 /* field_set_to_one */, ossl_ec_key_simple_priv2oct, ossl_ec_key_simple_oct2priv, 0, /* set private */ ossl_ec_key_simple_generate_key, ossl_ec_key_simple_check_key, ossl_ec_key_simple_generate_public_key, 0, /* keycopy */ 0, /* keyfinish */ ossl_ecdh_simple_compute_key, ossl_ecdsa_simple_sign_setup, ossl_ecdsa_simple_sign_sig, ossl_ecdsa_simple_verify_sig, - ecp_sm2p256_inv_mod_ord, + 0, /* use constant‑time fallback for inverse mod order */ 0, /* blind_coordinates */ 0, /* ladder_pre */ 0, /* ladder_step */ 0 /* ladder_post */ }; return &ret; } diff --git a/crypto/evp/bio_ok.c b/crypto/evp/bio_ok.c index 20811ffded6f..d7f6c71ee1ad 100644 --- a/crypto/evp/bio_ok.c +++ b/crypto/evp/bio_ok.c @@ -1,604 +1,607 @@ /* - * Copyright 1995-2024 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2025 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 */ /*- From: Arne Ansper Why BIO_f_reliable? I wrote function which took BIO* as argument, read data from it and processed it. Then I wanted to store the input file in encrypted form. OK I pushed BIO_f_cipher to the BIO stack and everything was OK. BUT if user types wrong password BIO_f_cipher outputs only garbage and my function crashes. Yes I can and I should fix my function, but BIO_f_cipher is easy way to add encryption support to many existing applications and it's hard to debug and fix them all. So I wanted another BIO which would catch the incorrect passwords and file damages which cause garbage on BIO_f_cipher's output. The easy way is to push the BIO_f_md and save the checksum at the end of the file. However there are several problems with this approach: 1) you must somehow separate checksum from actual data. 2) you need lot's of memory when reading the file, because you must read to the end of the file and verify the checksum before letting the application to read the data. BIO_f_reliable tries to solve both problems, so that you can read and write arbitrary long streams using only fixed amount of memory. BIO_f_reliable splits data stream into blocks. Each block is prefixed with its length and suffixed with its digest. So you need only several Kbytes of memory to buffer single block before verifying its digest. BIO_f_reliable goes further and adds several important capabilities: 1) the digest of the block is computed over the whole stream -- so nobody can rearrange the blocks or remove or replace them. 2) to detect invalid passwords right at the start BIO_f_reliable adds special prefix to the stream. In order to avoid known plain-text attacks this prefix is generated as follows: *) digest is initialized with random seed instead of standardized one. *) same seed is written to output *) well-known text is then hashed and the output of the digest is also written to output. reader can now read the seed from stream, hash the same string and then compare the digest output. Bad things: BIO_f_reliable knows what's going on in EVP_Digest. I initially wrote and tested this code on x86 machine and wrote the digests out in machine-dependent order :( There are people using this code and I cannot change this easily without making existing data files unreadable. */ #include #include #include #include "internal/cryptlib.h" #include #include "internal/bio.h" #include #include #include "internal/endian.h" #include "crypto/evp.h" static int ok_write(BIO *h, const char *buf, int num); static int ok_read(BIO *h, char *buf, int size); static long ok_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int ok_new(BIO *h); static int ok_free(BIO *data); static long ok_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fp); static __owur int sig_out(BIO *b); static __owur int sig_in(BIO *b); static __owur int block_out(BIO *b); static __owur int block_in(BIO *b); #define OK_BLOCK_SIZE (1024*4) #define OK_BLOCK_BLOCK 4 #define IOBS (OK_BLOCK_SIZE+ OK_BLOCK_BLOCK+ 3*EVP_MAX_MD_SIZE) #define WELLKNOWN "The quick brown fox jumped over the lazy dog's back." typedef struct ok_struct { size_t buf_len; size_t buf_off; size_t buf_len_save; size_t buf_off_save; int cont; /* <= 0 when finished */ int finished; EVP_MD_CTX *md; int blockout; /* output block is ready */ int sigio; /* must process signature */ unsigned char buf[IOBS]; } BIO_OK_CTX; static const BIO_METHOD methods_ok = { BIO_TYPE_CIPHER, "reliable", bwrite_conv, ok_write, bread_conv, ok_read, NULL, /* ok_puts, */ NULL, /* ok_gets, */ ok_ctrl, ok_new, ok_free, ok_callback_ctrl, }; const BIO_METHOD *BIO_f_reliable(void) { return &methods_ok; } static int ok_new(BIO *bi) { BIO_OK_CTX *ctx; if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL) return 0; ctx->cont = 1; ctx->sigio = 1; ctx->md = EVP_MD_CTX_new(); if (ctx->md == NULL) { OPENSSL_free(ctx); return 0; } BIO_set_init(bi, 0); BIO_set_data(bi, ctx); return 1; } static int ok_free(BIO *a) { BIO_OK_CTX *ctx; if (a == NULL) return 0; ctx = BIO_get_data(a); EVP_MD_CTX_free(ctx->md); OPENSSL_clear_free(ctx, sizeof(BIO_OK_CTX)); BIO_set_data(a, NULL); BIO_set_init(a, 0); return 1; } static int ok_read(BIO *b, char *out, int outl) { int ret = 0, i, n; BIO_OK_CTX *ctx; BIO *next; if (out == NULL) return 0; ctx = BIO_get_data(b); next = BIO_next(b); if ((ctx == NULL) || (next == NULL) || (BIO_get_init(b) == 0)) return 0; while (outl > 0) { /* copy clean bytes to output buffer */ if (ctx->blockout) { i = ctx->buf_len - ctx->buf_off; if (i > outl) i = outl; memcpy(out, &(ctx->buf[ctx->buf_off]), i); ret += i; out += i; outl -= i; ctx->buf_off += i; /* all clean bytes are out */ if (ctx->buf_len == ctx->buf_off) { ctx->buf_off = 0; /* * copy start of the next block into proper place */ if (ctx->buf_len_save > ctx->buf_off_save) { ctx->buf_len = ctx->buf_len_save - ctx->buf_off_save; memmove(ctx->buf, &(ctx->buf[ctx->buf_off_save]), ctx->buf_len); } else { ctx->buf_len = 0; } ctx->blockout = 0; } } /* output buffer full -- cancel */ if (outl == 0) break; /* no clean bytes in buffer -- fill it */ n = IOBS - ctx->buf_len; i = BIO_read(next, &(ctx->buf[ctx->buf_len]), n); if (i <= 0) break; /* nothing new */ ctx->buf_len += i; /* no signature yet -- check if we got one */ if (ctx->sigio == 1) { if (!sig_in(b)) { BIO_clear_retry_flags(b); return 0; } } /* signature ok -- check if we got block */ if (ctx->sigio == 0) { if (!block_in(b)) { BIO_clear_retry_flags(b); return 0; } } /* invalid block -- cancel */ if (ctx->cont <= 0) break; } BIO_clear_retry_flags(b); BIO_copy_next_retry(b); return ret; } static int ok_write(BIO *b, const char *in, int inl) { int ret = 0, n, i; BIO_OK_CTX *ctx; BIO *next; if (inl <= 0) return inl; ctx = BIO_get_data(b); next = BIO_next(b); ret = inl; if ((ctx == NULL) || (next == NULL) || (BIO_get_init(b) == 0)) return 0; if (ctx->sigio && !sig_out(b)) return 0; do { BIO_clear_retry_flags(b); n = ctx->buf_len - ctx->buf_off; while (ctx->blockout && n > 0) { i = BIO_write(next, &(ctx->buf[ctx->buf_off]), n); if (i <= 0) { BIO_copy_next_retry(b); if (!BIO_should_retry(b)) ctx->cont = 0; return i; } ctx->buf_off += i; n -= i; } /* at this point all pending data has been written */ ctx->blockout = 0; if (ctx->buf_len == ctx->buf_off) { ctx->buf_len = OK_BLOCK_BLOCK; ctx->buf_off = 0; } if ((in == NULL) || (inl <= 0)) return 0; n = (inl + ctx->buf_len > OK_BLOCK_SIZE + OK_BLOCK_BLOCK) ? (int)(OK_BLOCK_SIZE + OK_BLOCK_BLOCK - ctx->buf_len) : inl; memcpy(&ctx->buf[ctx->buf_len], in, n); ctx->buf_len += n; inl -= n; in += n; if (ctx->buf_len >= OK_BLOCK_SIZE + OK_BLOCK_BLOCK) { if (!block_out(b)) { BIO_clear_retry_flags(b); return 0; } } } while (inl > 0); BIO_clear_retry_flags(b); BIO_copy_next_retry(b); return ret; } static long ok_ctrl(BIO *b, int cmd, long num, void *ptr) { BIO_OK_CTX *ctx; EVP_MD *md; const EVP_MD **ppmd; long ret = 1; int i; BIO *next; ctx = BIO_get_data(b); next = BIO_next(b); switch (cmd) { case BIO_CTRL_RESET: ctx->buf_len = 0; ctx->buf_off = 0; ctx->buf_len_save = 0; ctx->buf_off_save = 0; ctx->cont = 1; ctx->finished = 0; ctx->blockout = 0; ctx->sigio = 1; ret = BIO_ctrl(next, cmd, num, ptr); break; case BIO_CTRL_EOF: /* More to read */ if (ctx->cont <= 0) ret = 1; else ret = BIO_ctrl(next, cmd, num, ptr); break; case BIO_CTRL_PENDING: /* More to read in buffer */ case BIO_CTRL_WPENDING: /* More to read in buffer */ ret = ctx->blockout ? ctx->buf_len - ctx->buf_off : 0; if (ret <= 0) ret = BIO_ctrl(next, cmd, num, ptr); break; case BIO_CTRL_FLUSH: /* do a final write */ if (ctx->blockout == 0) if (!block_out(b)) return 0; while (ctx->blockout) { i = ok_write(b, NULL, 0); if (i < 0) { ret = i; break; } } ctx->finished = 1; ctx->buf_off = ctx->buf_len = 0; ctx->cont = (int)ret; /* Finally flush the underlying BIO */ ret = BIO_ctrl(next, cmd, num, ptr); BIO_copy_next_retry(b); break; case BIO_C_DO_STATE_MACHINE: BIO_clear_retry_flags(b); ret = BIO_ctrl(next, cmd, num, ptr); BIO_copy_next_retry(b); break; case BIO_CTRL_INFO: ret = (long)ctx->cont; break; case BIO_C_SET_MD: md = ptr; if (!EVP_DigestInit_ex(ctx->md, md, NULL)) return 0; BIO_set_init(b, 1); break; case BIO_C_GET_MD: if (BIO_get_init(b)) { ppmd = ptr; *ppmd = EVP_MD_CTX_get0_md(ctx->md); } else ret = 0; break; default: ret = BIO_ctrl(next, cmd, num, ptr); break; } return ret; } static long ok_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) { BIO *next; next = BIO_next(b); if (next == NULL) return 0; return BIO_callback_ctrl(next, cmd, fp); } static void longswap(void *_ptr, size_t len) { DECLARE_IS_ENDIAN; if (IS_LITTLE_ENDIAN) { size_t i; unsigned char *p = _ptr, c; for (i = 0; i < len; i += 4) { c = p[0], p[0] = p[3], p[3] = c; c = p[1], p[1] = p[2], p[2] = c; } } } static int sig_out(BIO *b) { BIO_OK_CTX *ctx; EVP_MD_CTX *md; const EVP_MD *digest; int md_size; void *md_data; ctx = BIO_get_data(b); md = ctx->md; digest = EVP_MD_CTX_get0_md(md); md_size = EVP_MD_get_size(digest); md_data = EVP_MD_CTX_get0_md_data(md); if (md_size <= 0) goto berr; if (ctx->buf_len + 2 * md_size > OK_BLOCK_SIZE) return 1; if (!EVP_DigestInit_ex(md, digest, NULL)) goto berr; /* * FIXME: there's absolutely no guarantee this makes any sense at all, * particularly now EVP_MD_CTX has been restructured. */ if (RAND_bytes(md_data, md_size) <= 0) goto berr; memcpy(&(ctx->buf[ctx->buf_len]), md_data, md_size); longswap(&(ctx->buf[ctx->buf_len]), md_size); ctx->buf_len += md_size; if (!EVP_DigestUpdate(md, WELLKNOWN, strlen(WELLKNOWN))) goto berr; if (!EVP_DigestFinal_ex(md, &(ctx->buf[ctx->buf_len]), NULL)) goto berr; ctx->buf_len += md_size; ctx->blockout = 1; ctx->sigio = 0; return 1; berr: BIO_clear_retry_flags(b); return 0; } static int sig_in(BIO *b) { BIO_OK_CTX *ctx; EVP_MD_CTX *md; unsigned char tmp[EVP_MAX_MD_SIZE]; int ret = 0; const EVP_MD *digest; int md_size; void *md_data; ctx = BIO_get_data(b); if ((md = ctx->md) == NULL) goto berr; digest = EVP_MD_CTX_get0_md(md); if ((md_size = EVP_MD_get_size(digest)) <= 0) goto berr; md_data = EVP_MD_CTX_get0_md_data(md); if ((int)(ctx->buf_len - ctx->buf_off) < 2 * md_size) return 1; if (!EVP_DigestInit_ex(md, digest, NULL)) goto berr; memcpy(md_data, &(ctx->buf[ctx->buf_off]), md_size); longswap(md_data, md_size); ctx->buf_off += md_size; if (!EVP_DigestUpdate(md, WELLKNOWN, strlen(WELLKNOWN))) goto berr; if (!EVP_DigestFinal_ex(md, tmp, NULL)) goto berr; ret = memcmp(&(ctx->buf[ctx->buf_off]), tmp, md_size) == 0; ctx->buf_off += md_size; if (ret == 1) { ctx->sigio = 0; if (ctx->buf_len != ctx->buf_off) { memmove(ctx->buf, &(ctx->buf[ctx->buf_off]), ctx->buf_len - ctx->buf_off); } ctx->buf_len -= ctx->buf_off; ctx->buf_off = 0; } else { ctx->cont = 0; } return 1; berr: BIO_clear_retry_flags(b); return 0; } static int block_out(BIO *b) { BIO_OK_CTX *ctx; EVP_MD_CTX *md; unsigned long tl; const EVP_MD *digest; int md_size; ctx = BIO_get_data(b); md = ctx->md; digest = EVP_MD_CTX_get0_md(md); md_size = EVP_MD_get_size(digest); if (md_size <= 0) goto berr; tl = ctx->buf_len - OK_BLOCK_BLOCK; ctx->buf[0] = (unsigned char)(tl >> 24); ctx->buf[1] = (unsigned char)(tl >> 16); ctx->buf[2] = (unsigned char)(tl >> 8); ctx->buf[3] = (unsigned char)(tl); if (!EVP_DigestUpdate(md, (unsigned char *)&(ctx->buf[OK_BLOCK_BLOCK]), tl)) goto berr; if (!EVP_DigestFinal_ex(md, &(ctx->buf[ctx->buf_len]), NULL)) goto berr; ctx->buf_len += md_size; ctx->blockout = 1; return 1; berr: BIO_clear_retry_flags(b); return 0; } static int block_in(BIO *b) { BIO_OK_CTX *ctx; EVP_MD_CTX *md; - unsigned long tl = 0; + size_t tl = 0; unsigned char tmp[EVP_MAX_MD_SIZE]; int md_size; ctx = BIO_get_data(b); md = ctx->md; md_size = EVP_MD_get_size(EVP_MD_CTX_get0_md(md)); if (md_size <= 0) goto berr; assert(sizeof(tl) >= OK_BLOCK_BLOCK); /* always true */ - tl = ctx->buf[0]; - tl <<= 8; - tl |= ctx->buf[1]; - tl <<= 8; - tl |= ctx->buf[2]; - tl <<= 8; - tl |= ctx->buf[3]; - - if (ctx->buf_len < tl + OK_BLOCK_BLOCK + md_size) + tl = ((size_t)ctx->buf[0] << 24) + | ((size_t)ctx->buf[1] << 16) + | ((size_t)ctx->buf[2] << 8) + | ((size_t)ctx->buf[3]); + + if (tl > OK_BLOCK_SIZE) + goto berr; + + if (tl > SIZE_MAX - OK_BLOCK_BLOCK - (size_t)md_size) + goto berr; + + if (ctx->buf_len < tl + OK_BLOCK_BLOCK + (size_t)md_size) return 1; if (!EVP_DigestUpdate(md, (unsigned char *)&(ctx->buf[OK_BLOCK_BLOCK]), tl)) goto berr; if (!EVP_DigestFinal_ex(md, tmp, NULL)) goto berr; - if (memcmp(&(ctx->buf[tl + OK_BLOCK_BLOCK]), tmp, md_size) == 0) { + if (memcmp(&(ctx->buf[tl + OK_BLOCK_BLOCK]), tmp, (size_t)md_size) == 0) { /* there might be parts from next block lurking around ! */ ctx->buf_off_save = tl + OK_BLOCK_BLOCK + md_size; ctx->buf_len_save = ctx->buf_len; ctx->buf_off = OK_BLOCK_BLOCK; ctx->buf_len = tl + OK_BLOCK_BLOCK; ctx->blockout = 1; } else { ctx->cont = 0; } return 1; berr: BIO_clear_retry_flags(b); return 0; } diff --git a/crypto/evp/ctrl_params_translate.c b/crypto/evp/ctrl_params_translate.c index ed73fc0fbb8d..c846353200b2 100644 --- a/crypto/evp/ctrl_params_translate.c +++ b/crypto/evp/ctrl_params_translate.c @@ -1,2959 +1,2959 @@ /* * Copyright 2021-2025 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 == OSSL_ACTION_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 == OSSL_ACTION_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 == OSSL_ACTION_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 == OSSL_ACTION_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 == OSSL_ACTION_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 { OSSL_ACTION_NONE = 0, OSSL_ACTION_GET = 1, OSSL_ACTION_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 (OSSL_ACTION_GET or OSSL_ACTION_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 OSSL_ACTION_GET and OSSL_ACTION_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 OSSL_ACTION_SET) or after (for OSSL_ACTION_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 != OSSL_ACTION_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 (OSSL_ACTION_SET) or return value+p2 (OSSL_ACTION_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, OSSL_ACTION_SET * | OSSL_ACTION_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, OSSL_ACTION_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, * !OSSL_ACTION_SET - ERROR. That combination is not * supported. * PRE_CTRL_STR_TO_PARAMS, * OSSL_ACTION_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, OSSL_ACTION_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, OSSL_ACTION_GET - |p1| and |p2| are converted to * an OSSL_PARAM, in the same manner * as for the combination of * PRE_CTRL_TO_PARAMS, OSSL_ACTION_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 == OSSL_ACTION_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 OSSL_ACTION_SET and OSSL_ACTION_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 == OSSL_ACTION_SET) { ctx->buflen = BN_num_bytes(ctx->p2); if ((ctx->allocated_buf = OPENSSL_malloc(ctx->buflen)) == NULL) 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 == OSSL_ACTION_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 != OSSL_ACTION_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 == OSSL_ACTION_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 == OSSL_ACTION_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 == OSSL_ACTION_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 OSSL_ACTION_SET, * and cipher / md name to EVP_MD on OSSL_ACTION_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 == OSSL_ACTION_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 == OSSL_ACTION_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 == OSSL_ACTION_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 == OSSL_ACTION_GET) { /* * Here's how we reuse |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 == OSSL_ACTION_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 == OSSL_ACTION_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 OSSL_ACTION_NONE. */ if (!ossl_assert(ctx->action_type == OSSL_ACTION_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 = OSSL_ACTION_GET; } else { ctx->action_type = OSSL_ACTION_SET; } } if ((ret = default_check(state, translation, ctx)) <= 0) return ret; if ((state == PRE_CTRL_TO_PARAMS && ctx->action_type == OSSL_ACTION_SET) || (state == POST_PARAMS_TO_CTRL && ctx->action_type == OSSL_ACTION_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 == OSSL_ACTION_GET) || (state == PRE_PARAMS_TO_CTRL && ctx->action_type == OSSL_ACTION_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 == OSSL_ACTION_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 == OSSL_ACTION_SET) || (state == POST_PARAMS_TO_CTRL && ctx->action_type == OSSL_ACTION_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 == OSSL_ACTION_SET) || (state == POST_CTRL_TO_PARAMS && ctx->action_type == OSSL_ACTION_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 != OSSL_ACTION_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 != OSSL_ACTION_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 != OSSL_ACTION_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 != OSSL_ACTION_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 != OSSL_ACTION_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 == OSSL_ACTION_NONE)) return 0; /* The action type depends on the value of ctx->p1 */ if (ctx->p1 == -2) ctx->action_type = OSSL_ACTION_GET; else ctx->action_type = OSSL_ACTION_SET; } else if (state == PRE_CTRL_STR_TO_PARAMS) { ctx->action_type = OSSL_ACTION_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 != OSSL_ACTION_NONE)) return 0; } else if (state == POST_PARAMS_TO_CTRL && ctx->action_type == OSSL_ACTION_NONE) { ctx->action_type = OSSL_ACTION_GET; } if ((ret = default_check(state, translation, ctx)) <= 0) return ret; if (state == PRE_CTRL_TO_PARAMS && ctx->action_type == OSSL_ACTION_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 == OSSL_ACTION_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 == OSSL_ACTION_GET) { ctx->p1 = -2; } else if (state == POST_PARAMS_TO_CTRL && ctx->action_type == OSSL_ACTION_GET) { ctx->p1 = ret; } 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 == OSSL_ACTION_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 && OSSL_ACTION_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 == OSSL_ACTION_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 == OSSL_ACTION_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 == OSSL_ACTION_SET && state == PRE_PARAMS_TO_CTRL) || (ctx->action_type == OSSL_ACTION_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->action_type, state, (const char *)ctx->p2); 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 == OSSL_ACTION_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 && OSSL_ACTION_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 == OSSL_ACTION_SET && state == PRE_CTRL_TO_PARAMS) || (ctx->action_type == OSSL_ACTION_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 == OSSL_ACTION_SET && state == PRE_PARAMS_TO_CTRL) || (ctx->action_type == OSSL_ACTION_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 == OSSL_ACTION_SET && state == PRE_CTRL_TO_PARAMS) || (ctx->action_type == OSSL_ACTION_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 == OSSL_ACTION_SET && state == PRE_PARAMS_TO_CTRL) || (ctx->action_type == OSSL_ACTION_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 OSSL_ACTION_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_public_key_ec(enum state state, const struct translation_st *translation, struct translation_ctx_st *ctx) { #ifndef OPENSSL_NO_EC EVP_PKEY *pkey = ctx->p2; const EC_KEY *eckey = EVP_PKEY_get0_EC_KEY(pkey); BN_CTX *bnctx; const EC_POINT *point; const EC_GROUP *ecg; BIGNUM *x = NULL; BIGNUM *y = NULL; int ret = 0; ctx->p2 = NULL; if (eckey == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE); return 0; } bnctx = BN_CTX_new_ex(ossl_ec_key_get_libctx(eckey)); if (bnctx == NULL) return 0; point = EC_KEY_get0_public_key(eckey); ecg = EC_KEY_get0_group(eckey); /* Caller should have requested a BN, fail if not */ if (ctx->params->data_type != OSSL_PARAM_UNSIGNED_INTEGER) goto out; x = BN_CTX_get(bnctx); y = BN_CTX_get(bnctx); if (y == NULL) goto out; if (!EC_POINT_get_affine_coordinates(ecg, point, x, y, bnctx)) goto out; if (strncmp(ctx->params->key, OSSL_PKEY_PARAM_EC_PUB_X, 2) == 0) ctx->p2 = x; else if (strncmp(ctx->params->key, OSSL_PKEY_PARAM_EC_PUB_Y, 2) == 0) ctx->p2 = y; else goto out; /* Return the payload */ ret = default_fixup_args(state, translation, ctx); out: BN_CTX_free(bnctx); return ret; #else ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE); return 0; #endif } 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 && 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 && 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 && 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 \ && 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 \ && 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 \ && 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 = OSSL_ACTION_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. */ { OSSL_ACTION_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 }, { OSSL_ACTION_GET, -1, -1, -1, EVP_PKEY_CTRL_GET1_ID, "distid", "hexdistid", OSSL_PKEY_PARAM_DIST_ID, OSSL_PARAM_OCTET_PTR, NULL }, { OSSL_ACTION_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... */ { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 */ { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 */ { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 */ { OSSL_ACTION_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 */ { OSSL_ACTION_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 }, { OSSL_ACTION_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 * === */ { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 * == */ { OSSL_ACTION_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 }, { OSSL_ACTION_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... */ { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 * == */ { OSSL_ACTION_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 }, { OSSL_ACTION_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... */ { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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. */ { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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. */ { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 accommodated by default_fixup_args() above, which mimics that * expectation for any translation item where |ctrl_str| is NULL and * |ctrl_hexstr| is non-NULL. */ { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_SET, EVP_PKEY_RSA, 0, EVP_PKEY_OP_TYPE_CRYPT, EVP_PKEY_CTRL_RSA_IMPLICIT_REJECTION, NULL, "rsa_pkcs1_implicit_rejection", OSSL_ASYM_CIPHER_PARAM_IMPLICIT_REJECTION, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 * ====== */ { OSSL_ACTION_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 * ======== */ { OSSL_ACTION_SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_TLS_MD, "md", NULL, OSSL_KDF_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { OSSL_ACTION_SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_TLS_SECRET, "secret", "hexsecret", OSSL_KDF_PARAM_SECRET, OSSL_PARAM_OCTET_STRING, NULL }, { OSSL_ACTION_SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_TLS_SEED, "seed", "hexseed", OSSL_KDF_PARAM_SEED, OSSL_PARAM_OCTET_STRING, NULL }, /*- * HKDF * ==== */ { OSSL_ACTION_SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_MD, "md", NULL, OSSL_KDF_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { OSSL_ACTION_SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_SALT, "salt", "hexsalt", OSSL_KDF_PARAM_SALT, OSSL_PARAM_OCTET_STRING, NULL }, { OSSL_ACTION_SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_KEY, "key", "hexkey", OSSL_KDF_PARAM_KEY, OSSL_PARAM_OCTET_STRING, NULL }, { OSSL_ACTION_SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_HKDF_INFO, "info", "hexinfo", OSSL_KDF_PARAM_INFO, OSSL_PARAM_OCTET_STRING, NULL }, { OSSL_ACTION_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 * ====== */ { OSSL_ACTION_SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_PASS, "pass", "hexpass", OSSL_KDF_PARAM_PASSWORD, OSSL_PARAM_OCTET_STRING, NULL }, { OSSL_ACTION_SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_SALT, "salt", "hexsalt", OSSL_KDF_PARAM_SALT, OSSL_PARAM_OCTET_STRING, NULL }, { OSSL_ACTION_SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_N, "N", NULL, OSSL_KDF_PARAM_SCRYPT_N, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { OSSL_ACTION_SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_R, "r", NULL, OSSL_KDF_PARAM_SCRYPT_R, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { OSSL_ACTION_SET, -1, -1, EVP_PKEY_OP_DERIVE, EVP_PKEY_CTRL_SCRYPT_P, "p", NULL, OSSL_KDF_PARAM_SCRYPT_P, OSSL_PARAM_UNSIGNED_INTEGER, NULL }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_SET, -1, -1, EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_MD, NULL, NULL, OSSL_SIGNATURE_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING, fix_md }, { OSSL_ACTION_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 * === */ { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 }, { OSSL_ACTION_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 */ { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_GROUP_NAME, OSSL_PARAM_UTF8_STRING, get_payload_group_name }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_PRIV_KEY, OSSL_PARAM_UNSIGNED_INTEGER, get_payload_private_key }, { OSSL_ACTION_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 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_EC_PUB_X, OSSL_PARAM_UNSIGNED_INTEGER, get_payload_public_key_ec }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_EC_PUB_Y, OSSL_PARAM_UNSIGNED_INTEGER, get_payload_public_key_ec }, /* DH and DSA */ { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_FFC_P, OSSL_PARAM_UNSIGNED_INTEGER, get_dh_dsa_payload_p }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_FFC_G, OSSL_PARAM_UNSIGNED_INTEGER, get_dh_dsa_payload_g }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_FFC_Q, OSSL_PARAM_UNSIGNED_INTEGER, get_dh_dsa_payload_q }, /* RSA */ { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_N, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_n }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_E, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_D, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_d }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR1, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f1 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR2, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f2 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR3, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f3 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR4, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f4 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR5, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f5 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR6, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f6 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR7, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f7 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR8, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f8 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR9, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f9 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_FACTOR10, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_f10 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT1, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e1 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT2, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e2 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT3, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e3 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT4, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e4 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT5, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e5 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT6, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e6 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT7, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e7 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT8, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e8 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT9, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e9 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_EXPONENT10, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_e10 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT1, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c1 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT2, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c2 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT3, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c3 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT4, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c4 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT5, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c5 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT6, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c6 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT7, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c7 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT8, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c8 }, { OSSL_ACTION_GET, -1, -1, -1, 0, NULL, NULL, OSSL_PKEY_PARAM_RSA_COEFFICIENT9, OSSL_PARAM_UNSIGNED_INTEGER, get_rsa_payload_c9 }, /* EC */ { OSSL_ACTION_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 != OSSL_ACTION_NONE && item->action_type != OSSL_ACTION_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 an 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 != OSSL_ACTION_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 OSSL_ACTION_GET: ret = evp_pkey_ctx_get_params_strict(pctx, ctx.params); break; case OSSL_ACTION_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 = OSSL_ACTION_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 = OSSL_ACTION_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 OSSL_ACTION_GET: /* * this is dead code, but must be present, or some compilers * will complain */ break; case OSSL_ACTION_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; ctx.action_type = 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.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 != OSSL_ACTION_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. * * NOTE: even though EVP_PKEY_CTX_ctrl return value is documented * as return positive on Success and 0 or negative on falure. There * maybe parameters (e.g. ecdh_cofactor), which actually return 0 * as success value. That is why we do POST_PARAMS_TO_CTRL for 0 * value as well */ 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) { if (ctx->keymgmt != NULL) return 0; return evp_pkey_ctx_setget_params_to_ctrl(ctx, OSSL_ACTION_SET, (OSSL_PARAM *)params); } int evp_pkey_ctx_get_params_to_ctrl(EVP_PKEY_CTX *ctx, OSSL_PARAM *params) { if (ctx->keymgmt != NULL) return 0; return evp_pkey_ctx_setget_params_to_ctrl(ctx, OSSL_ACTION_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 == OSSL_ACTION_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, OSSL_ACTION_GET, params); } diff --git a/crypto/evp/p_lib.c b/crypto/evp/p_lib.c index 7f4508169dfa..63953a84e1f5 100644 --- a/crypto/evp/p_lib.c +++ b/crypto/evp/p_lib.c @@ -1,2555 +1,2554 @@ /* * Copyright 1995-2025 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); /* The type of parameters selected in key parameter functions */ # define SELECT_PARAMETERS OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS #ifndef FIPS_MODULE 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); } if (size <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_UNKNOWN_BITS); return 0; } return 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); } if (size <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_UNKNOWN_SECURITY_BITS); return 0; } return 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); } #endif /* !FIPS_MODULE */ 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; #ifndef FIPS_MODULE /* * 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; } #endif /* !FIPS_MODULE */ /* * 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)) { #ifndef FIPS_MODULE if (evp_pkey_is_legacy(from)) { if (EVP_PKEY_set_type(to, from->type) == 0) goto end; } else #endif /* !FIPS_MODULE */ { if (EVP_PKEY_set_type_by_keymgmt(to, from->keymgmt) == 0) goto end; } } #ifndef FIPS_MODULE else if (evp_pkey_is_legacy(to)) { if (to->type != from->type) { ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_KEY_TYPES); goto end; } } #endif /* !FIPS_MODULE */ 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; } #ifndef FIPS_MODULE /* * 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); #endif /* !FIPS_MODULE */ end: EVP_PKEY_free(downgraded_from); return ok; } int EVP_PKEY_missing_parameters(const EVP_PKEY *pkey) { if (pkey != NULL) { #ifdef FIPS_MODULE return !evp_keymgmt_util_has((EVP_PKEY *)pkey, SELECT_PARAMETERS); #else if (pkey->keymgmt != NULL) return !evp_keymgmt_util_has((EVP_PKEY *)pkey, SELECT_PARAMETERS); if (pkey->ameth != NULL && pkey->ameth->param_missing != NULL) return pkey->ameth->param_missing(pkey); #endif /* FIPS_MODULE */ } 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) { #ifdef FIPS_MODULE return evp_keymgmt_util_match((EVP_PKEY *)a, (EVP_PKEY *)b, selection); #else 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); #endif /* FIPS_MODULE */ } #ifndef FIPS_MODULE # 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 #endif /* FIPS_MODULE */ int EVP_PKEY_parameters_eq(const EVP_PKEY *a, const EVP_PKEY *b) { #ifdef FIPS_MODULE return evp_pkey_cmp_any(a, b, SELECT_PARAMETERS); #else /* * 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; #endif /* !FIPS_MODULE */ } #ifndef FIPS_MODULE # 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 #endif /* !FIPS_MODULE */ 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; #ifndef FIPS_MODULE if (a->keymgmt != NULL || b->keymgmt != NULL) #endif /* !FIPS_MODULE */ { 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); } #ifndef FIPS_MODULE /* 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; #endif /* !FIPS_MODULE */ } #ifndef FIPS_MODULE 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_EVP_LIB); goto err; } if (!pkey_set_type(pkey, e, nidtype, strtype, -1, NULL)) { /* ERR_raise(ERR_LIB_EVP, ...) 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; if (!DSA_up_ref(key)) return 0; ret = EVP_PKEY_assign_DSA(pkey, key); if (!ret) DSA_free(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 NULL; return ret; } # endif /* OPENSSL_NO_DSA */ # ifndef OPENSSL_NO_ECX 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 /* OPENSSL_NO_ECX */ # 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; if (!DH_up_ref(dhkey)) return 0; ret = EVP_PKEY_assign(pkey, type, dhkey); if (!ret) DH_free(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)) ret = NULL; 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); + EVP_SIGNATURE *sig; + const char *name; + + name = evp_keymgmt_util_query_operation_name(pkey->keymgmt, + OSSL_OP_SIGNATURE); + sig = EVP_SIGNATURE_fetch(libctx, name, NULL); + if (sig != NULL) { + EVP_SIGNATURE_free(sig); 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_PRIVATE_KEY, 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; } #endif /* !FIPS_MODULE */ int EVP_PKEY_set1_encoded_public_key(EVP_PKEY *pkey, const unsigned char *pub, size_t publen) { if (pkey == NULL) return 0; #ifndef FIPS_MODULE if (evp_pkey_is_provided(pkey)) #endif /* !FIPS_MODULE */ return EVP_PKEY_set_octet_string_param(pkey, OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, (unsigned char *)pub, publen); #ifndef FIPS_MODULE 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; #endif /* !FIPS_MODULE */ } size_t EVP_PKEY_get1_encoded_public_key(EVP_PKEY *pkey, unsigned char **ppub) { if (pkey == NULL) return 0; #ifndef FIPS_MODULE if (evp_pkey_is_provided(pkey)) #endif { 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; } #ifndef FIPS_MODULE { int 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) return NULL; ret->type = EVP_PKEY_NONE; ret->save_type = EVP_PKEY_NONE; if (!CRYPTO_NEW_REF(&ret->references, 1)) goto err; ret->lock = CRYPTO_THREAD_lock_new(); if (ret->lock == NULL) { ERR_raise(ERR_LIB_EVP, ERR_R_CRYPTO_LIB); 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_CRYPTO_LIB); goto err; } #endif return ret; err: CRYPTO_FREE_REF(&ret->references); 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) <= 0) return 0; REF_PRINT_COUNT("EVP_PKEY", i, pkey); REF_ASSERT_ISNT(i < 2); return ((i > 1) ? 1 : 0); } 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; #ifndef FIPS_MODULE if (evp_pkey_is_provided(pkey)) #endif /* !FIPS_MODULE */ { if (!evp_keymgmt_util_copy(dup_pk, pkey, OSSL_KEYMGMT_SELECT_ALL)) goto err; goto done; } #ifndef FIPS_MODULE 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; } #endif /* !FIPS_MODULE */ goto err; done: #ifndef FIPS_MODULE /* 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; } #endif /* !FIPS_MODULE */ return dup_pk; err: EVP_PKEY_free(dup_pk); return NULL; } #ifndef FIPS_MODULE 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); #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); REF_PRINT_COUNT("EVP_PKEY", i, 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); CRYPTO_FREE_REF(&x->references); #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 } if (size <= 0) { ERR_raise(ERR_LIB_EVP, EVP_R_UNKNOWN_MAX_SIZE); return 0; } return 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. It is possible (e.g. in a no-cached-fetch * build), for op->keymgmt to be a different pointer to tmp_keymgmt * even though the name/provider must be the same. In other words * the keymgmt instance may be different but still equivalent, i.e. * same algorithm/provider instance - but we make the simplifying * assumption that the keydata can be used with either keymgmt * instance. Not doing so introduces significant complexity and * probably requires refactoring - since we would have to ripple * the change in keymgmt instance up the call chain. */ 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)) { 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_EVP_LIB); 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_EVP_LIB); 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_lib.c b/crypto/http/http_lib.c index fcf8a69e07a8..022b8c194cbe 100644 --- a/crypto/http/http_lib.c +++ b/crypto/http/http_lib.c @@ -1,305 +1,306 @@ /* * Copyright 2001-2025 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 /* for sscanf() */ #include #include #include #include /* for BIO_snprintf() */ #include #include "internal/cryptlib.h" /* for ossl_assert() */ #ifndef OPENSSL_NO_SOCK # include "internal/bio_addr.h" /* for NI_MAXHOST */ #endif #ifndef NI_MAXHOST # define NI_MAXHOST 255 #endif #include "crypto/ctype.h" /* for ossl_isspace() */ static void init_pstring(char **pstr) { if (pstr != NULL) { *pstr = NULL; } } static void init_pint(int *pint) { if (pint != NULL) { *pint = 0; } } static int copy_substring(char **dest, const char *start, const char *end) { return dest == NULL || (*dest = OPENSSL_strndup(start, end - start)) != NULL; } static void free_pstring(char **pstr) { if (pstr != NULL) { OPENSSL_free(*pstr); *pstr = NULL; } } int OSSL_parse_url(const char *url, char **pscheme, char **puser, char **phost, char **pport, int *pport_num, char **ppath, char **pquery, char **pfrag) { const char *p, *tmp; const char *scheme, *scheme_end; const char *user, *user_end; const char *host, *host_end; const char *port, *port_end; unsigned int portnum = 0; const char *path, *path_end; const char *query, *query_end; const char *frag, *frag_end; init_pstring(pscheme); init_pstring(puser); init_pstring(phost); init_pstring(pport); init_pint(pport_num); init_pstring(ppath); init_pstring(pfrag); init_pstring(pquery); if (url == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return 0; } /* check for optional prefix "://" */ scheme = scheme_end = url; p = strstr(url, "://"); if (p == NULL) { p = url; } else { scheme_end = p; if (scheme_end == scheme) goto parse_err; p += strlen("://"); } /* parse optional "userinfo@" */ user = user_end = host = p; host = strchr(p, '@'); if (host != NULL) user_end = host++; else host = p; /* parse hostname/address as far as needed here */ if (host[0] == '[') { /* IPv6 literal, which may include ':' */ host_end = strchr(host + 1, ']'); if (host_end == NULL) goto parse_err; p = ++host_end; } else { /* look for start of optional port, path, query, or fragment */ host_end = strpbrk(host, ":/?#"); if (host_end == NULL) /* the remaining string is just the hostname */ host_end = host + strlen(host); p = host_end; } /* parse optional port specification starting with ':' */ port = "0"; /* default */ if (*p == ':') port = ++p; /* remaining port spec handling is also done for the default values */ /* make sure a decimal port number is given */ if (sscanf(port, "%u", &portnum) <= 0 || portnum > 65535) { ERR_raise_data(ERR_LIB_HTTP, HTTP_R_INVALID_PORT_NUMBER, "%s", port); goto err; } for (port_end = port; '0' <= *port_end && *port_end <= '9'; port_end++) ; if (port == p) /* port was given explicitly */ p += port_end - port; /* check for optional path starting with '/' or '?'. Else must start '#' */ path = p; if (*path != '\0' && *path != '/' && *path != '?' && *path != '#') { ERR_raise(ERR_LIB_HTTP, HTTP_R_INVALID_URL_PATH); goto parse_err; } path_end = query = query_end = frag = frag_end = path + strlen(path); /* parse optional "?query" */ tmp = strchr(p, '?'); if (tmp != NULL) { p = tmp; if (pquery != NULL) { path_end = p; query = p + 1; } } /* parse optional "#fragment" */ tmp = strchr(p, '#'); if (tmp != NULL) { if (query == path_end) /* we did not record a query component */ path_end = tmp; query_end = tmp; frag = tmp + 1; } if (!copy_substring(pscheme, scheme, scheme_end) || !copy_substring(phost, host, host_end) || !copy_substring(pport, port, port_end) || !copy_substring(puser, user, user_end) || !copy_substring(pquery, query, query_end) || !copy_substring(pfrag, frag, frag_end)) goto err; if (pport_num != NULL) *pport_num = (int)portnum; if (*path == '/') { if (!copy_substring(ppath, path, path_end)) goto err; } else if (ppath != NULL) { /* must prepend '/' */ size_t buflen = 1 + path_end - path + 1; if ((*ppath = OPENSSL_malloc(buflen)) == NULL) goto err; BIO_snprintf(*ppath, buflen, "/%s", path); } return 1; parse_err: ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_PARSING_URL); err: free_pstring(pscheme); free_pstring(puser); free_pstring(phost); free_pstring(pport); free_pstring(ppath); free_pstring(pquery); free_pstring(pfrag); return 0; } #ifndef OPENSSL_NO_HTTP int OSSL_HTTP_parse_url(const char *url, int *pssl, char **puser, char **phost, char **pport, int *pport_num, char **ppath, char **pquery, char **pfrag) { char *scheme, *port; int ssl = 0, portnum; init_pstring(pport); if (pssl != NULL) *pssl = 0; if (!OSSL_parse_url(url, &scheme, puser, phost, &port, pport_num, ppath, pquery, pfrag)) return 0; /* check for optional HTTP scheme "http[s]" */ if (strcmp(scheme, OSSL_HTTPS_NAME) == 0) { ssl = 1; if (pssl != NULL) *pssl = ssl; } else if (*scheme != '\0' && strcmp(scheme, OSSL_HTTP_NAME) != 0) { ERR_raise(ERR_LIB_HTTP, HTTP_R_INVALID_URL_SCHEME); OPENSSL_free(scheme); OPENSSL_free(port); goto err; } OPENSSL_free(scheme); if (strcmp(port, "0") == 0) { /* set default port */ OPENSSL_free(port); port = ssl ? OSSL_HTTPS_PORT : OSSL_HTTP_PORT; if (!ossl_assert(sscanf(port, "%d", &portnum) == 1)) goto err; if (pport_num != NULL) *pport_num = portnum; if (pport != NULL) { *pport = OPENSSL_strdup(port); if (*pport == NULL) goto err; } } else { if (pport != NULL) *pport = port; else OPENSSL_free(port); } return 1; err: free_pstring(puser); free_pstring(phost); free_pstring(ppath); free_pstring(pquery); free_pstring(pfrag); return 0; } /* Respect no_proxy, taking default value from environment variable(s) */ static int use_proxy(const char *no_proxy, const char *server) { size_t sl; const char *found = NULL; char host[NI_MAXHOST]; if (!ossl_assert(server != NULL)) return 0; sl = strlen(server); if (sl >= 2 && sl < sizeof(host) + 2 && server[0] == '[' && server[sl - 1] == ']') { /* strip leading '[' and trailing ']' from escaped IPv6 address */ sl -= 2; strncpy(host, server + 1, sl); + host[sl] = '\0'; server = host; } /* * using environment variable names, both lowercase and uppercase variants, * compatible with other HTTP client implementations like wget, curl and git */ if (no_proxy == NULL) no_proxy = ossl_safe_getenv("no_proxy"); if (no_proxy == NULL) no_proxy = ossl_safe_getenv(OPENSSL_NO_PROXY); if (no_proxy != NULL) found = strstr(no_proxy, server); while (found != NULL && ((found != no_proxy && !ossl_isspace(found[-1]) && found[-1] != ',') || (found[sl] != '\0' && !ossl_isspace(found[sl]) && found[sl] != ','))) found = strstr(found + 1, server); return found == NULL; } /* Take default value from environment variable(s), respect no_proxy */ const char *OSSL_HTTP_adapt_proxy(const char *proxy, const char *no_proxy, const char *server, int use_ssl) { /* * using environment variable names, both lowercase and uppercase variants, * compatible with other HTTP client implementations like wget, curl and git */ if (proxy == NULL) proxy = ossl_safe_getenv(use_ssl ? "https_proxy" : "http_proxy"); if (proxy == NULL) proxy = ossl_safe_getenv(use_ssl ? OPENSSL_HTTPS_PROXY : OPENSSL_HTTP_PROXY); if (proxy == NULL || *proxy == '\0' || !use_proxy(no_proxy, server)) return NULL; return proxy; } #endif /* !defined(OPENSSL_NO_HTTP) */ diff --git a/crypto/info.c b/crypto/info.c index 4d70471be255..e760ec094027 100644 --- a/crypto/info.c +++ b/crypto/info.c @@ -1,260 +1,272 @@ /* - * Copyright 2019-2024 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2019-2025 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 "crypto/rand.h" #include "crypto/dso_conf.h" #include "internal/thread_once.h" #include "internal/cryptlib.h" #include "internal/e_os.h" #include "buildinf.h" #ifndef OPENSSL_NO_JITTER # include # include #endif #if defined(__arm__) || defined(__arm) || defined(__aarch64__) # include "arm_arch.h" # define CPU_INFO_STR_LEN 128 +#elif defined(__powerpc__) || defined(__POWERPC__) || defined(_ARCH_PPC) +# include "crypto/ppc_arch.h" +# define CPU_INFO_STR_LEN 128 #elif defined(__s390__) || defined(__s390x__) # include "s390x_arch.h" # define CPU_INFO_STR_LEN 2048 #elif defined(__riscv) # include "crypto/riscv_arch.h" # define CPU_INFO_STR_LEN 2048 #else # define CPU_INFO_STR_LEN 256 #endif /* extern declaration to avoid warning */ extern char ossl_cpu_info_str[]; static char *seed_sources = NULL; char ossl_cpu_info_str[CPU_INFO_STR_LEN] = ""; #define CPUINFO_PREFIX "CPUINFO: " static CRYPTO_ONCE init_info = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(init_info_strings) { #if defined(OPENSSL_CPUID_OBJ) # if defined(__i386) || defined(__i386__) || defined(_M_IX86) || \ defined(__x86_64) || defined(__x86_64__) || \ defined(_M_AMD64) || defined(_M_X64) const char *env; BIO_snprintf(ossl_cpu_info_str, sizeof(ossl_cpu_info_str), CPUINFO_PREFIX "OPENSSL_ia32cap=0x%.16llx:0x%.16llx:0x%.16llx:0x%.16llx:0x%.16llx", (unsigned long long)OPENSSL_ia32cap_P[0] | (unsigned long long)OPENSSL_ia32cap_P[1] << 32, (unsigned long long)OPENSSL_ia32cap_P[2] | (unsigned long long)OPENSSL_ia32cap_P[3] << 32, (unsigned long long)OPENSSL_ia32cap_P[4] | (unsigned long long)OPENSSL_ia32cap_P[5] << 32, (unsigned long long)OPENSSL_ia32cap_P[6] | (unsigned long long)OPENSSL_ia32cap_P[7] << 32, (unsigned long long)OPENSSL_ia32cap_P[8] | (unsigned long long)OPENSSL_ia32cap_P[9] << 32); if ((env = getenv("OPENSSL_ia32cap")) != NULL) BIO_snprintf(ossl_cpu_info_str + strlen(ossl_cpu_info_str), sizeof(ossl_cpu_info_str) - strlen(ossl_cpu_info_str), " env:%s", env); # elif defined(__arm__) || defined(__arm) || defined(__aarch64__) const char *env; BIO_snprintf(ossl_cpu_info_str, sizeof(ossl_cpu_info_str), CPUINFO_PREFIX "OPENSSL_armcap=0x%x", OPENSSL_armcap_P); if ((env = getenv("OPENSSL_armcap")) != NULL) BIO_snprintf(ossl_cpu_info_str + strlen(ossl_cpu_info_str), sizeof(ossl_cpu_info_str) - strlen(ossl_cpu_info_str), " env:%s", env); +# elif defined(__powerpc__) || defined(__POWERPC__) || defined(_ARCH_PPC) + const char *env; + + BIO_snprintf(ossl_cpu_info_str, sizeof(ossl_cpu_info_str), + CPUINFO_PREFIX "OPENSSL_ppccap=0x%x", OPENSSL_ppccap_P); + if ((env = getenv("OPENSSL_ppccap")) != NULL) + BIO_snprintf(ossl_cpu_info_str + strlen(ossl_cpu_info_str), + sizeof(ossl_cpu_info_str) - strlen(ossl_cpu_info_str), + " env:%s", env); # elif defined(__s390__) || defined(__s390x__) const char *env; BIO_snprintf(ossl_cpu_info_str, sizeof(ossl_cpu_info_str), CPUINFO_PREFIX "OPENSSL_s390xcap=" "stfle:0x%llx:0x%llx:0x%llx:0x%llx:" "kimd:0x%llx:0x%llx:" "klmd:0x%llx:0x%llx:" "km:0x%llx:0x%llx:" "kmc:0x%llx:0x%llx:" "kmac:0x%llx:0x%llx:" "kmctr:0x%llx:0x%llx:" "kmo:0x%llx:0x%llx:" "kmf:0x%llx:0x%llx:" "prno:0x%llx:0x%llx:" "kma:0x%llx:0x%llx:" "pcc:0x%llx:0x%llx:" "kdsa:0x%llx:0x%llx", OPENSSL_s390xcap_P.stfle[0], OPENSSL_s390xcap_P.stfle[1], OPENSSL_s390xcap_P.stfle[2], OPENSSL_s390xcap_P.stfle[3], OPENSSL_s390xcap_P.kimd[0], OPENSSL_s390xcap_P.kimd[1], OPENSSL_s390xcap_P.klmd[0], OPENSSL_s390xcap_P.klmd[1], OPENSSL_s390xcap_P.km[0], OPENSSL_s390xcap_P.km[1], OPENSSL_s390xcap_P.kmc[0], OPENSSL_s390xcap_P.kmc[1], OPENSSL_s390xcap_P.kmac[0], OPENSSL_s390xcap_P.kmac[1], OPENSSL_s390xcap_P.kmctr[0], OPENSSL_s390xcap_P.kmctr[1], OPENSSL_s390xcap_P.kmo[0], OPENSSL_s390xcap_P.kmo[1], OPENSSL_s390xcap_P.kmf[0], OPENSSL_s390xcap_P.kmf[1], OPENSSL_s390xcap_P.prno[0], OPENSSL_s390xcap_P.prno[1], OPENSSL_s390xcap_P.kma[0], OPENSSL_s390xcap_P.kma[1], OPENSSL_s390xcap_P.pcc[0], OPENSSL_s390xcap_P.pcc[1], OPENSSL_s390xcap_P.kdsa[0], OPENSSL_s390xcap_P.kdsa[1]); if ((env = getenv("OPENSSL_s390xcap")) != NULL) BIO_snprintf(ossl_cpu_info_str + strlen(ossl_cpu_info_str), sizeof(ossl_cpu_info_str) - strlen(ossl_cpu_info_str), " env:%s", env); # elif defined(__riscv) const char *env; char sep = '='; BIO_snprintf(ossl_cpu_info_str, sizeof(ossl_cpu_info_str), CPUINFO_PREFIX "OPENSSL_riscvcap"); for (size_t i = 0; i < kRISCVNumCaps; ++i) { if (OPENSSL_riscvcap_P[RISCV_capabilities[i].index] & (1 << RISCV_capabilities[i].bit_offset)) { /* Match, display the name */ BIO_snprintf(ossl_cpu_info_str + strlen(ossl_cpu_info_str), sizeof(ossl_cpu_info_str) - strlen(ossl_cpu_info_str), "%c%s", sep, RISCV_capabilities[i].name); /* Only the first sep is '=' */ sep = '_'; } } /* If no capability is found, add back the = */ if (sep == '=') { BIO_snprintf(ossl_cpu_info_str + strlen(ossl_cpu_info_str), sizeof(ossl_cpu_info_str) - strlen(ossl_cpu_info_str), "%c", sep); } if ((env = getenv("OPENSSL_riscvcap")) != NULL) BIO_snprintf(ossl_cpu_info_str + strlen(ossl_cpu_info_str), sizeof(ossl_cpu_info_str) - strlen(ossl_cpu_info_str), " env:%s", env); # endif #endif { static char seeds[512] = ""; #define add_seeds_string(str) \ do { \ if (seeds[0] != '\0') \ OPENSSL_strlcat(seeds, " ", sizeof(seeds)); \ OPENSSL_strlcat(seeds, str, sizeof(seeds)); \ } while (0) #define add_seeds_stringlist(label, strlist) \ do { \ add_seeds_string(label "("); \ { \ const char *dev[] = { strlist, NULL }; \ const char **p; \ int first = 1; \ \ for (p = dev; *p != NULL; p++) { \ if (!first) \ OPENSSL_strlcat(seeds, " ", sizeof(seeds)); \ first = 0; \ OPENSSL_strlcat(seeds, *p, sizeof(seeds)); \ } \ } \ OPENSSL_strlcat(seeds, ")", sizeof(seeds)); \ } while (0) #ifdef OPENSSL_RAND_SEED_NONE add_seeds_string("none"); #endif #ifdef OPENSSL_RAND_SEED_RDTSC add_seeds_string("rdtsc"); #endif #ifdef OPENSSL_RAND_SEED_RDCPU # ifdef __aarch64__ add_seeds_string("rndr ( rndrrs rndr )"); # else add_seeds_string("rdrand ( rdseed rdrand )"); # endif #endif #ifdef OPENSSL_RAND_SEED_GETRANDOM add_seeds_string("getrandom-syscall"); #endif #ifdef OPENSSL_RAND_SEED_DEVRANDOM add_seeds_stringlist("random-device", DEVRANDOM); #endif #ifdef OPENSSL_RAND_SEED_EGD add_seeds_stringlist("EGD", DEVRANDOM_EGD); #endif #ifdef OPENSSL_RAND_SEED_OS add_seeds_string("os-specific"); #endif #ifndef OPENSSL_NO_JITTER { char buf[32]; BIO_snprintf(buf, sizeof(buf), "JITTER (%d)", jent_version()); add_seeds_string(buf); } #endif seed_sources = seeds; } return 1; } const char *OPENSSL_info(int t) { /* * We don't care about the result. Worst case scenario, the strings * won't be initialised, i.e. remain NULL, which means that the info * isn't available anyway... */ (void)RUN_ONCE(&init_info, init_info_strings); switch (t) { case OPENSSL_INFO_CONFIG_DIR: return ossl_get_openssldir(); case OPENSSL_INFO_ENGINES_DIR: return ossl_get_enginesdir(); case OPENSSL_INFO_MODULES_DIR: return ossl_get_modulesdir(); case OPENSSL_INFO_DSO_EXTENSION: return DSO_EXTENSION; case OPENSSL_INFO_DIR_FILENAME_SEPARATOR: #if defined(_WIN32) return "\\"; #elif defined(__VMS) return ""; #else /* Assume POSIX */ return "/"; #endif case OPENSSL_INFO_LIST_SEPARATOR: { static const char list_sep[] = { LIST_SEPARATOR_CHAR, '\0' }; return list_sep; } case OPENSSL_INFO_SEED_SOURCE: return seed_sources; case OPENSSL_INFO_CPU_SETTINGS: /* * If successfully initialized, ossl_cpu_info_str will start * with CPUINFO_PREFIX, if failed it will be an empty string. * Strip away the CPUINFO_PREFIX which we don't need here. */ if (ossl_cpu_info_str[0] != '\0') return ossl_cpu_info_str + strlen(CPUINFO_PREFIX); break; case OPENSSL_INFO_WINDOWS_CONTEXT: return ossl_get_wininstallcontext(); default: break; } /* Not an error */ return NULL; } diff --git a/crypto/ml_dsa/ml_dsa_key.c b/crypto/ml_dsa/ml_dsa_key.c index 41df1a956fb8..50e3b5433085 100644 --- a/crypto/ml_dsa/ml_dsa_key.c +++ b/crypto/ml_dsa/ml_dsa_key.c @@ -1,547 +1,549 @@ /* * Copyright 2024-2025 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 "ml_dsa_key.h" #include "ml_dsa_matrix.h" #include "ml_dsa_hash.h" #include "internal/encoder.h" const ML_DSA_PARAMS *ossl_ml_dsa_key_params(const ML_DSA_KEY *key) { return key->params; } /* Returns the seed data or NULL if there is no seed */ const uint8_t *ossl_ml_dsa_key_get_seed(const ML_DSA_KEY *key) { return key->seed; } int ossl_ml_dsa_key_get_prov_flags(const ML_DSA_KEY *key) { return key->prov_flags; } int ossl_ml_dsa_set_prekey(ML_DSA_KEY *key, int flags_set, int flags_clr, const uint8_t *seed, size_t seed_len, const uint8_t *sk, size_t sk_len) { int ret = 0; if (key == NULL || key->pub_encoding != NULL || key->priv_encoding != NULL || (sk != NULL && sk_len != key->params->sk_len) || (seed != NULL && seed_len != ML_DSA_SEED_BYTES) || key->seed != NULL) return 0; if (sk != NULL && (key->priv_encoding = OPENSSL_memdup(sk, sk_len)) == NULL) goto end; if (seed != NULL && (key->seed = OPENSSL_memdup(seed, seed_len)) == NULL) goto end; key->prov_flags |= flags_set; key->prov_flags &= ~flags_clr; ret = 1; end: if (!ret) { OPENSSL_free(key->priv_encoding); OPENSSL_free(key->seed); key->priv_encoding = key->seed = NULL; } return ret; } /** * @brief Create a new ML_DSA_KEY object * * @param libctx A OSSL_LIB_CTX object used for fetching algorithms. * @param propq The property query used for fetching algorithms * @param alg The algorithm name associated with the key type * @returns The new ML_DSA_KEY object on success, or NULL on malloc failure */ ML_DSA_KEY *ossl_ml_dsa_key_new(OSSL_LIB_CTX *libctx, const char *propq, int evp_type) { ML_DSA_KEY *ret; const ML_DSA_PARAMS *params = ossl_ml_dsa_params_get(evp_type); if (params == NULL) return NULL; ret = OPENSSL_zalloc(sizeof(*ret)); if (ret != NULL) { ret->libctx = libctx; ret->params = params; ret->prov_flags = ML_DSA_KEY_PROV_FLAGS_DEFAULT; ret->shake128_md = EVP_MD_fetch(libctx, "SHAKE-128", propq); ret->shake256_md = EVP_MD_fetch(libctx, "SHAKE-256", propq); if (ret->shake128_md == NULL || ret->shake256_md == NULL) goto err; } return ret; err: ossl_ml_dsa_key_free(ret); return NULL; } int ossl_ml_dsa_key_pub_alloc(ML_DSA_KEY *key) { if (key->t1.poly != NULL) return 0; return vector_alloc(&key->t1, key->params->k); } int ossl_ml_dsa_key_priv_alloc(ML_DSA_KEY *key) { size_t k = key->params->k, l = key->params->l; POLY *poly; if (key->s1.poly != NULL) return 0; if (!vector_alloc(&key->s1, l + 2 * k)) return 0; poly = key->s1.poly; key->s1.num_poly = l; vector_init(&key->s2, poly + l, k); vector_init(&key->t0, poly + l + k, k); return 1; } /** * @brief Destroy an ML_DSA_KEY object */ void ossl_ml_dsa_key_free(ML_DSA_KEY *key) { if (key == NULL) return; EVP_MD_free(key->shake128_md); EVP_MD_free(key->shake256_md); ossl_ml_dsa_key_reset(key); OPENSSL_free(key); } /** * @brief Factory reset an ML_DSA_KEY object */ void ossl_ml_dsa_key_reset(ML_DSA_KEY *key) { /* * The allocation for |s1.poly| subsumes those for |s2| and |t0|, which we * must not access after |s1|'s poly is freed. */ if (key->s1.poly != NULL) { vector_zero(&key->s1); vector_zero(&key->s2); vector_zero(&key->t0); vector_free(&key->s1); key->s2.poly = NULL; key->t0.poly = NULL; } /* The |t1| vector is public and allocated separately */ vector_free(&key->t1); OPENSSL_cleanse(key->K, sizeof(key->K)); OPENSSL_free(key->pub_encoding); key->pub_encoding = NULL; if (key->priv_encoding != NULL) OPENSSL_clear_free(key->priv_encoding, key->params->sk_len); key->priv_encoding = NULL; if (key->seed != NULL) OPENSSL_clear_free(key->seed, ML_DSA_SEED_BYTES); key->seed = NULL; } /** * @brief Duplicate a key * * @param src A ML_DSA_KEY object to copy * @param selection to select public and/or private components. Selecting the * private key will also select the public key * @returns The duplicated key, or NULL on failure. */ ML_DSA_KEY *ossl_ml_dsa_key_dup(const ML_DSA_KEY *src, int selection) { ML_DSA_KEY *ret = NULL; if (src == NULL) return NULL; /* Prekeys with just a seed or private key are not dupable */ if (src->pub_encoding == NULL && (src->priv_encoding != NULL || src->seed != NULL)) return NULL; ret = OPENSSL_zalloc(sizeof(*ret)); if (ret != NULL) { ret->libctx = src->libctx; ret->params = src->params; ret->prov_flags = src->prov_flags; if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) { if (src->pub_encoding != NULL) { /* The public components are present if the private key is present */ memcpy(ret->rho, src->rho, sizeof(src->rho)); memcpy(ret->tr, src->tr, sizeof(src->tr)); if (src->t1.poly != NULL) { if (!ossl_ml_dsa_key_pub_alloc(ret)) goto err; vector_copy(&ret->t1, &src->t1); } if ((ret->pub_encoding = OPENSSL_memdup(src->pub_encoding, src->params->pk_len)) == NULL) goto err; } if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) { if (src->priv_encoding != NULL) { memcpy(ret->K, src->K, sizeof(src->K)); if (src->s1.poly != NULL) { if (!ossl_ml_dsa_key_priv_alloc(ret)) goto err; vector_copy(&ret->s1, &src->s1); vector_copy(&ret->s2, &src->s2); vector_copy(&ret->t0, &src->t0); } if ((ret->priv_encoding = OPENSSL_memdup(src->priv_encoding, src->params->sk_len)) == NULL) goto err; } if (src->seed != NULL && (ret->seed = OPENSSL_memdup(src->seed, ML_DSA_SEED_BYTES)) == NULL) goto err; } } EVP_MD_up_ref(src->shake128_md); EVP_MD_up_ref(src->shake256_md); ret->shake128_md = src->shake128_md; ret->shake256_md = src->shake256_md; } return ret; err: ossl_ml_dsa_key_free(ret); return NULL; } /** * @brief Are 2 keys equal? * * To be equal the keys must have matching public or private key data and * contain the same parameters. * (Note that in OpenSSL that the private key always has a public key component). * * @param key1 A ML_DSA_KEY object * @param key2 A ML_DSA_KEY object * @param selection to select public and/or private component comparison. * @returns 1 if the keys are equal otherwise it returns 0. */ int ossl_ml_dsa_key_equal(const ML_DSA_KEY *key1, const ML_DSA_KEY *key2, int selection) { int key_checked = 0; if (key1->params != key2->params) return 0; if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) { if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) { if (key1->pub_encoding != NULL && key2->pub_encoding != NULL) { if (memcmp(key1->pub_encoding, key2->pub_encoding, key1->params->pk_len) != 0) return 0; key_checked = 1; } } if (!key_checked && (selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) { if (key1->priv_encoding != NULL && key2->priv_encoding != NULL) { if (memcmp(key1->priv_encoding, key2->priv_encoding, key1->params->sk_len) != 0) return 0; key_checked = 1; } } return key_checked; } return 1; } int ossl_ml_dsa_key_has(const ML_DSA_KEY *key, int selection) { if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) { /* Note that the public key always exists if there is a private key */ if (ossl_ml_dsa_key_get_pub(key) == NULL) return 0; /* No public key */ if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0 && ossl_ml_dsa_key_get_priv(key) == NULL) return 0; /* No private key */ return 1; } return 0; } /* * @brief Given a key containing private key values for rho, s1 & s2 * generate the public value t and return the compressed values t1, t0. * * @param key A private key containing params, rh0, s1 & s2. * @param md_ctx A EVP_MD_CTX used for sampling. * @param t1 The returned polynomial encoding of the 10 MSB of each coefficient * of the uncompressed public key polynomial t. * @param t0 The returned polynomial encoding of the 13 LSB of each coefficient * of the uncompressed public key polynomial t. * @returns 1 on success, or 0 on failure. */ static int public_from_private(const ML_DSA_KEY *key, EVP_MD_CTX *md_ctx, VECTOR *t1, VECTOR *t0) { + int ret = 0; const ML_DSA_PARAMS *params = key->params; uint32_t k = params->k, l = params->l; POLY *polys; MATRIX a_ntt; VECTOR s1_ntt; VECTOR t; polys = OPENSSL_malloc(sizeof(*polys) * (k + l + k * l)); if (polys == NULL) return 0; vector_init(&t, polys, k); vector_init(&s1_ntt, t.poly + k, l); matrix_init(&a_ntt, s1_ntt.poly + l, k, l); /* Using rho generate A' = A in NTT form */ if (!matrix_expand_A(md_ctx, key->shake128_md, key->rho, &a_ntt)) goto err; /* t = NTT_inv(A' * NTT(s1)) + s2 */ vector_copy(&s1_ntt, &key->s1); vector_ntt(&s1_ntt); matrix_mult_vector(&a_ntt, &s1_ntt, &t); vector_ntt_inverse(&t); vector_add(&t, &key->s2, &t); /* Compress t */ vector_power2_round(&t, t1, t0); /* Zeroize secret */ vector_zero(&s1_ntt); + ret = 1; err: OPENSSL_free(polys); - return 1; + return ret; } int ossl_ml_dsa_key_public_from_private(ML_DSA_KEY *key) { int ret = 0; VECTOR t0; EVP_MD_CTX *md_ctx = NULL; if (!vector_alloc(&t0, key->params->k)) /* t0 is already in the private key */ return 0; ret = ((md_ctx = EVP_MD_CTX_new())!= NULL) && ossl_ml_dsa_key_pub_alloc(key) /* allocate space for t1 */ && public_from_private(key, md_ctx, &key->t1, &t0) && vector_equal(&t0, &key->t0) /* compare the generated t0 to the expected */ && ossl_ml_dsa_pk_encode(key) && shake_xof(md_ctx, key->shake256_md, key->pub_encoding, key->params->pk_len, key->tr, sizeof(key->tr)); vector_free(&t0); EVP_MD_CTX_free(md_ctx); return ret; } int ossl_ml_dsa_key_pairwise_check(const ML_DSA_KEY *key) { int ret = 0; VECTOR t1, t0; POLY *polys = NULL; uint32_t k = key->params->k; EVP_MD_CTX *md_ctx = NULL; if (key->pub_encoding == NULL || key->priv_encoding == 0) return 0; polys = OPENSSL_malloc(sizeof(*polys) * (2 * k)); if (polys == NULL) return 0; md_ctx = EVP_MD_CTX_new(); if (md_ctx == NULL) goto err; vector_init(&t1, polys, k); vector_init(&t0, polys + k, k); if (!public_from_private(key, md_ctx, &t1, &t0)) goto err; ret = vector_equal(&t1, &key->t1) && vector_equal(&t0, &key->t0); err: EVP_MD_CTX_free(md_ctx); OPENSSL_free(polys); return ret; } /* * @brief Generate a public-private key pair from a seed. * See FIPS 204, Algorithm 6 ML-DSA.KeyGen_internal(). * * @param out The generated key (which contains params on input) * * @returns 1 on success or 0 on failure. */ static int keygen_internal(ML_DSA_KEY *out) { int ret = 0; uint8_t augmented_seed[ML_DSA_SEED_BYTES + 2]; uint8_t expanded_seed[ML_DSA_RHO_BYTES + ML_DSA_PRIV_SEED_BYTES + ML_DSA_K_BYTES]; const uint8_t *const rho = expanded_seed; /* p = Public Random Seed */ const uint8_t *const priv_seed = expanded_seed + ML_DSA_RHO_BYTES; const uint8_t *const K = priv_seed + ML_DSA_PRIV_SEED_BYTES; const ML_DSA_PARAMS *params = out->params; EVP_MD_CTX *md_ctx = NULL; if (out->seed == NULL || (md_ctx = EVP_MD_CTX_new()) == NULL || !ossl_ml_dsa_key_pub_alloc(out) || !ossl_ml_dsa_key_priv_alloc(out)) goto err; /* augmented_seed = seed || k || l */ memcpy(augmented_seed, out->seed, ML_DSA_SEED_BYTES); augmented_seed[ML_DSA_SEED_BYTES] = (uint8_t)params->k; augmented_seed[ML_DSA_SEED_BYTES + 1] = (uint8_t)params->l; /* Expand the seed into p[32], p'[64], K[32] */ if (!shake_xof(md_ctx, out->shake256_md, augmented_seed, sizeof(augmented_seed), expanded_seed, sizeof(expanded_seed))) goto err; memcpy(out->rho, rho, sizeof(out->rho)); memcpy(out->K, K, sizeof(out->K)); ret = vector_expand_S(md_ctx, out->shake256_md, params->eta, priv_seed, &out->s1, &out->s2) && public_from_private(out, md_ctx, &out->t1, &out->t0) && ossl_ml_dsa_pk_encode(out) && shake_xof(md_ctx, out->shake256_md, out->pub_encoding, out->params->pk_len, out->tr, sizeof(out->tr)) && ossl_ml_dsa_sk_encode(out); err: if (out->seed != NULL && (out->prov_flags & ML_DSA_KEY_RETAIN_SEED) == 0) { OPENSSL_clear_free(out->seed, ML_DSA_SEED_BYTES); out->seed = NULL; } EVP_MD_CTX_free(md_ctx); OPENSSL_cleanse(augmented_seed, sizeof(augmented_seed)); OPENSSL_cleanse(expanded_seed, sizeof(expanded_seed)); return ret; } int ossl_ml_dsa_generate_key(ML_DSA_KEY *out) { size_t seed_len = ML_DSA_SEED_BYTES; uint8_t *sk; int ret; if (out->seed == NULL) { if ((out->seed = OPENSSL_malloc(seed_len)) == NULL) return 0; if (RAND_priv_bytes_ex(out->libctx, out->seed, seed_len, 0) <= 0) { OPENSSL_free(out->seed); out->seed = NULL; return 0; } } /* We're generating from a seed, drop private prekey encoding */ sk = out->priv_encoding; out->priv_encoding = NULL; if (sk == NULL) { ret = keygen_internal(out); } else { if ((ret = keygen_internal(out)) != 0 && memcmp(out->priv_encoding, sk, out->params->sk_len) != 0) { ret = 0; ossl_ml_dsa_key_reset(out); ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_KEY, "explicit %s private key does not match seed", out->params->alg); } OPENSSL_free(sk); } return ret; } /** * @brief This is used when a ML DSA key is used for an operation. * This checks that the algorithm is the same (i.e. uses the same parameters) * * @param key A ML_DSA key to use for an operation. * @param evp_type The algorithm nid associated with an operation * * @returns 1 if the algorithm matches, or 0 otherwise. */ int ossl_ml_dsa_key_matches(const ML_DSA_KEY *key, int evp_type) { return (key->params->evp_type == evp_type); } /* Returns the public key data or NULL if there is no public key */ const uint8_t *ossl_ml_dsa_key_get_pub(const ML_DSA_KEY *key) { return key->pub_encoding; } /* Returns the encoded public key size */ size_t ossl_ml_dsa_key_get_pub_len(const ML_DSA_KEY *key) { return key->params->pk_len; } size_t ossl_ml_dsa_key_get_collision_strength_bits(const ML_DSA_KEY *key) { return key->params->bit_strength; } /* Returns the private key data or NULL if there is no private key */ const uint8_t *ossl_ml_dsa_key_get_priv(const ML_DSA_KEY *key) { return key->priv_encoding; } size_t ossl_ml_dsa_key_get_priv_len(const ML_DSA_KEY *key) { return key->params->sk_len; } size_t ossl_ml_dsa_key_get_sig_len(const ML_DSA_KEY *key) { return key->params->sig_len; } OSSL_LIB_CTX *ossl_ml_dsa_key_get0_libctx(const ML_DSA_KEY *key) { return key != NULL ? key->libctx : NULL; } const char *ossl_ml_dsa_key_get_name(const ML_DSA_KEY *key) { return key->params->alg; } diff --git a/crypto/ml_kem/ml_kem.c b/crypto/ml_kem/ml_kem.c index 4474af0f87cb..716c3bf4275e 100644 --- a/crypto/ml_kem/ml_kem.c +++ b/crypto/ml_kem/ml_kem.c @@ -1,2050 +1,2050 @@ /* * Copyright 2024-2025 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 "crypto/ml_kem.h" #include "internal/common.h" #include "internal/constant_time.h" #include "internal/sha3.h" #if defined(OPENSSL_CONSTANT_TIME_VALIDATION) #include #endif #if ML_KEM_SEED_BYTES != ML_KEM_SHARED_SECRET_BYTES + ML_KEM_RANDOM_BYTES # error "ML-KEM keygen seed length != shared secret + random bytes length" #endif #if ML_KEM_SHARED_SECRET_BYTES != ML_KEM_RANDOM_BYTES # error "Invalid unequal lengths of ML-KEM shared secret and random inputs" #endif #if UINT_MAX < UINT32_MAX # error "Unsupported compiler: sizeof(unsigned int) < sizeof(uint32_t)" #endif /* Handy function-like bit-extraction macros */ #define bit0(b) ((b) & 1) #define bitn(n, b) (((b) >> n) & 1) /* * 12 bits are sufficient to losslessly represent values in [0, q-1]. * INVERSE_DEGREE is (n/2)^-1 mod q; used in inverse NTT. */ #define DEGREE ML_KEM_DEGREE #define INVERSE_DEGREE (ML_KEM_PRIME - 2 * 13) #define LOG2PRIME 12 #define BARRETT_SHIFT (2 * LOG2PRIME) #ifdef SHA3_BLOCKSIZE # define SHAKE128_BLOCKSIZE SHA3_BLOCKSIZE(128) #endif /* * Return whether a value that can only be 0 or 1 is non-zero, in constant time * in practice! The return value is a mask that is all ones if true, and all * zeros otherwise (twos-complement arithmentic assumed for unsigned values). * * Although this is used in constant-time selects, we omit a value barrier * here. Value barriers impede auto-vectorization (likely because it forces * the value to transit through a general-purpose register). On AArch64, this * is a difference of 2x. * * We usually add value barriers to selects because Clang turns consecutive * selects with the same condition into a branch instead of CMOV/CSEL. This * condition does not occur in Kyber, so omitting it seems to be safe so far, * but see |cbd_2|, |cbd_3|, where reduction needs to be specialised to the * sign of the input, rather than adding |q| in advance, and using the generic * |reduce_once|. (David Benjamin, Chromium) */ #if 0 # define constish_time_non_zero(b) (~constant_time_is_zero(b)); #else # define constish_time_non_zero(b) (0u - (b)) #endif /* * The scalar rejection-sampling buffer size needs to be a multiple of 12, but * is otherwise arbitrary, the preferred block size matches the internal buffer * size of SHAKE128, avoiding internal buffering and copying in SHAKE128. That * block size of (1600 - 256)/8 bytes, or 168, just happens to divide by 12! * * If the blocksize is unknown, or is not divisible by 12, 168 is used as a * fallback. */ #if defined(SHAKE128_BLOCKSIZE) && (SHAKE128_BLOCKSIZE) % 12 == 0 # define SCALAR_SAMPLING_BUFSIZE (SHAKE128_BLOCKSIZE) #else # define SCALAR_SAMPLING_BUFSIZE 168 #endif /* * Structure of keys */ typedef struct ossl_ml_kem_scalar_st { /* On every function entry and exit, 0 <= c[i] < ML_KEM_PRIME. */ uint16_t c[ML_KEM_DEGREE]; } scalar; /* Key material allocation layout */ #define DECLARE_ML_KEM_KEYDATA(name, rank, private_sz) \ struct name##_alloc { \ /* Public vector |t| */ \ scalar tbuf[(rank)]; \ /* Pre-computed matrix |m| (FIPS 203 |A| transpose) */ \ scalar mbuf[(rank)*(rank)] \ /* optional private key data */ \ private_sz \ } /* Declare variant-specific public and private storage */ #define DECLARE_ML_KEM_VARIANT_KEYDATA(bits) \ DECLARE_ML_KEM_KEYDATA(pubkey_##bits, ML_KEM_##bits##_RANK,;); \ DECLARE_ML_KEM_KEYDATA(prvkey_##bits, ML_KEM_##bits##_RANK,;\ scalar sbuf[ML_KEM_##bits##_RANK]; \ uint8_t zbuf[2 * ML_KEM_RANDOM_BYTES];) DECLARE_ML_KEM_VARIANT_KEYDATA(512); DECLARE_ML_KEM_VARIANT_KEYDATA(768); DECLARE_ML_KEM_VARIANT_KEYDATA(1024); #undef DECLARE_ML_KEM_VARIANT_KEYDATA #undef DECLARE_ML_KEM_KEYDATA typedef __owur int (*CBD_FUNC)(scalar *out, uint8_t in[ML_KEM_RANDOM_BYTES + 1], EVP_MD_CTX *mdctx, const ML_KEM_KEY *key); static void scalar_encode(uint8_t *out, const scalar *s, int bits); /* * The wire-form of a losslessly encoded vector uses 12-bits per element. * * The wire-form public key consists of the lossless encoding of the public * vector |t|, followed by the public seed |rho|. * * Our serialised private key concatenates serialisations of the private vector * |s|, the public key, the public key hash, and the failure secret |z|. */ #define VECTOR_BYTES(b) ((3 * DEGREE / 2) * ML_KEM_##b##_RANK) #define PUBKEY_BYTES(b) (VECTOR_BYTES(b) + ML_KEM_RANDOM_BYTES) #define PRVKEY_BYTES(b) (2 * PUBKEY_BYTES(b) + ML_KEM_PKHASH_BYTES) /* * Encapsulation produces a vector "u" and a scalar "v", whose coordinates * (numbers modulo the ML-KEM prime "q") are lossily encoded using as "du" and * "dv" bits, respectively. This encoding is the ciphertext input for * decapsulation. */ #define U_VECTOR_BYTES(b) ((DEGREE / 8) * ML_KEM_##b##_DU * ML_KEM_##b##_RANK) #define V_SCALAR_BYTES(b) ((DEGREE / 8) * ML_KEM_##b##_DV) #define CTEXT_BYTES(b) (U_VECTOR_BYTES(b) + V_SCALAR_BYTES(b)) #if defined(OPENSSL_CONSTANT_TIME_VALIDATION) /* * CONSTTIME_SECRET takes a pointer and a number of bytes and marks that region * of memory as secret. Secret data is tracked as it flows to registers and * other parts of a memory. If secret data is used as a condition for a branch, * or as a memory index, it will trigger warnings in valgrind. */ # define CONSTTIME_SECRET(ptr, len) VALGRIND_MAKE_MEM_UNDEFINED(ptr, len) /* * CONSTTIME_DECLASSIFY takes a pointer and a number of bytes and marks that * region of memory as public. Public data is not subject to constant-time * rules. */ # define CONSTTIME_DECLASSIFY(ptr, len) VALGRIND_MAKE_MEM_DEFINED(ptr, len) #else # define CONSTTIME_SECRET(ptr, len) # define CONSTTIME_DECLASSIFY(ptr, len) #endif /* * Indices of slots in the vinfo tables below */ #define ML_KEM_512_VINFO 0 #define ML_KEM_768_VINFO 1 #define ML_KEM_1024_VINFO 2 /* * Per-variant fixed parameters */ static const ML_KEM_VINFO vinfo_map[3] = { { "ML-KEM-512", PRVKEY_BYTES(512), sizeof(struct prvkey_512_alloc), PUBKEY_BYTES(512), sizeof(struct pubkey_512_alloc), CTEXT_BYTES(512), VECTOR_BYTES(512), U_VECTOR_BYTES(512), EVP_PKEY_ML_KEM_512, ML_KEM_512_BITS, ML_KEM_512_RANK, ML_KEM_512_DU, ML_KEM_512_DV, ML_KEM_512_SECBITS }, { "ML-KEM-768", PRVKEY_BYTES(768), sizeof(struct prvkey_768_alloc), PUBKEY_BYTES(768), sizeof(struct pubkey_768_alloc), CTEXT_BYTES(768), VECTOR_BYTES(768), U_VECTOR_BYTES(768), EVP_PKEY_ML_KEM_768, ML_KEM_768_BITS, ML_KEM_768_RANK, ML_KEM_768_DU, ML_KEM_768_DV, ML_KEM_768_SECBITS }, { "ML-KEM-1024", PRVKEY_BYTES(1024), sizeof(struct prvkey_1024_alloc), PUBKEY_BYTES(1024), sizeof(struct pubkey_1024_alloc), CTEXT_BYTES(1024), VECTOR_BYTES(1024), U_VECTOR_BYTES(1024), EVP_PKEY_ML_KEM_1024, ML_KEM_1024_BITS, ML_KEM_1024_RANK, ML_KEM_1024_DU, ML_KEM_1024_DV, ML_KEM_1024_SECBITS } }; /* * Remainders modulo `kPrime`, for sufficiently small inputs, are computed in * constant time via Barrett reduction, and a final call to reduce_once(), * which reduces inputs that are at most 2*kPrime and is also constant-time. */ static const int kPrime = ML_KEM_PRIME; static const unsigned int kBarrettShift = BARRETT_SHIFT; static const size_t kBarrettMultiplier = (1 << BARRETT_SHIFT) / ML_KEM_PRIME; static const uint16_t kHalfPrime = (ML_KEM_PRIME - 1) / 2; static const uint16_t kInverseDegree = INVERSE_DEGREE; /* * Python helper: * * p = 3329 * def bitreverse(i): * ret = 0 * for n in range(7): * bit = i & 1 * ret <<= 1 * ret |= bit * i >>= 1 * return ret */ /*- * First precomputed array from Appendix A of FIPS 203, or else Python: * kNTTRoots = [pow(17, bitreverse(i), p) for i in range(128)] */ static const uint16_t kNTTRoots[128] = { 1, 1729, 2580, 3289, 2642, 630, 1897, 848, 1062, 1919, 193, 797, 2786, 3260, 569, 1746, 296, 2447, 1339, 1476, 3046, 56, 2240, 1333, 1426, 2094, 535, 2882, 2393, 2879, 1974, 821, 289, 331, 3253, 1756, 1197, 2304, 2277, 2055, 650, 1977, 2513, 632, 2865, 33, 1320, 1915, 2319, 1435, 807, 452, 1438, 2868, 1534, 2402, 2647, 2617, 1481, 648, 2474, 3110, 1227, 910, 17, 2761, 583, 2649, 1637, 723, 2288, 1100, 1409, 2662, 3281, 233, 756, 2156, 3015, 3050, 1703, 1651, 2789, 1789, 1847, 952, 1461, 2687, 939, 2308, 2437, 2388, 733, 2337, 268, 641, 1584, 2298, 2037, 3220, 375, 2549, 2090, 1645, 1063, 319, 2773, 757, 2099, 561, 2466, 2594, 2804, 1092, 403, 1026, 1143, 2150, 2775, 886, 1722, 1212, 1874, 1029, 2110, 2935, 885, 2154, }; /* * InverseNTTRoots = [pow(17, -bitreverse(i), p) for i in range(128)] * Listed in order of use in the inverse NTT loop (index 0 is skipped): * * 0, 64, 65, ..., 127, 32, 33, ..., 63, 16, 17, ..., 31, 8, 9, ... */ static const uint16_t kInverseNTTRoots[128] = { 1, 1175, 2444, 394, 1219, 2300, 1455, 2117, 1607, 2443, 554, 1179, 2186, 2303, 2926, 2237, 525, 735, 863, 2768, 1230, 2572, 556, 3010, 2266, 1684, 1239, 780, 2954, 109, 1292, 1031, 1745, 2688, 3061, 992, 2596, 941, 892, 1021, 2390, 642, 1868, 2377, 1482, 1540, 540, 1678, 1626, 279, 314, 1173, 2573, 3096, 48, 667, 1920, 2229, 1041, 2606, 1692, 680, 2746, 568, 3312, 2419, 2102, 219, 855, 2681, 1848, 712, 682, 927, 1795, 461, 1891, 2877, 2522, 1894, 1010, 1414, 2009, 3296, 464, 2697, 816, 1352, 2679, 1274, 1052, 1025, 2132, 1573, 76, 2998, 3040, 2508, 1355, 450, 936, 447, 2794, 1235, 1903, 1996, 1089, 3273, 283, 1853, 1990, 882, 3033, 1583, 2760, 69, 543, 2532, 3136, 1410, 2267, 2481, 1432, 2699, 687, 40, 749, 1600, }; /* * Second precomputed array from Appendix A of FIPS 203 (normalised positive), * or else Python: * ModRoots = [pow(17, 2*bitreverse(i) + 1, p) for i in range(128)] */ static const uint16_t kModRoots[128] = { 17, 3312, 2761, 568, 583, 2746, 2649, 680, 1637, 1692, 723, 2606, 2288, 1041, 1100, 2229, 1409, 1920, 2662, 667, 3281, 48, 233, 3096, 756, 2573, 2156, 1173, 3015, 314, 3050, 279, 1703, 1626, 1651, 1678, 2789, 540, 1789, 1540, 1847, 1482, 952, 2377, 1461, 1868, 2687, 642, 939, 2390, 2308, 1021, 2437, 892, 2388, 941, 733, 2596, 2337, 992, 268, 3061, 641, 2688, 1584, 1745, 2298, 1031, 2037, 1292, 3220, 109, 375, 2954, 2549, 780, 2090, 1239, 1645, 1684, 1063, 2266, 319, 3010, 2773, 556, 757, 2572, 2099, 1230, 561, 2768, 2466, 863, 2594, 735, 2804, 525, 1092, 2237, 403, 2926, 1026, 2303, 1143, 2186, 2150, 1179, 2775, 554, 886, 2443, 1722, 1607, 1212, 2117, 1874, 1455, 1029, 2300, 2110, 1219, 2935, 394, 885, 2444, 2154, 1175, }; /* * single_keccak hashes |inlen| bytes from |in| and writes |outlen| bytes of * output to |out|. If the |md| specifies a fixed-output function, like * SHA3-256, then |outlen| must be the correct length for that function. */ static __owur int single_keccak(uint8_t *out, size_t outlen, const uint8_t *in, size_t inlen, EVP_MD_CTX *mdctx) { unsigned int sz = (unsigned int) outlen; if (!EVP_DigestUpdate(mdctx, in, inlen)) return 0; if (EVP_MD_xof(EVP_MD_CTX_get0_md(mdctx))) return EVP_DigestFinalXOF(mdctx, out, outlen); return EVP_DigestFinal_ex(mdctx, out, &sz) && ossl_assert((size_t) sz == outlen); } /* * FIPS 203, Section 4.1, equation (4.3): PRF. Takes 32+1 input bytes, and uses * SHAKE256 to produce the input to SamplePolyCBD_eta: FIPS 203, algorithm 8. */ static __owur int prf(uint8_t *out, size_t len, const uint8_t in[ML_KEM_RANDOM_BYTES + 1], EVP_MD_CTX *mdctx, const ML_KEM_KEY *key) { return EVP_DigestInit_ex(mdctx, key->shake256_md, NULL) && single_keccak(out, len, in, ML_KEM_RANDOM_BYTES + 1, mdctx); } /* * FIPS 203, Section 4.1, equation (4.4): H. SHA3-256 hash of a variable * length input, producing 32 bytes of output. */ static __owur int hash_h(uint8_t out[ML_KEM_PKHASH_BYTES], const uint8_t *in, size_t len, EVP_MD_CTX *mdctx, const ML_KEM_KEY *key) { return EVP_DigestInit_ex(mdctx, key->sha3_256_md, NULL) && single_keccak(out, ML_KEM_PKHASH_BYTES, in, len, mdctx); } /* Incremental hash_h of expanded public key */ static int hash_h_pubkey(uint8_t pkhash[ML_KEM_PKHASH_BYTES], EVP_MD_CTX *mdctx, ML_KEM_KEY *key) { const ML_KEM_VINFO *vinfo = key->vinfo; const scalar *t = key->t, *end = t + vinfo->rank; unsigned int sz; if (!EVP_DigestInit_ex(mdctx, key->sha3_256_md, NULL)) return 0; do { uint8_t buf[3 * DEGREE / 2]; scalar_encode(buf, t++, 12); if (!EVP_DigestUpdate(mdctx, buf, sizeof(buf))) return 0; } while (t < end); if (!EVP_DigestUpdate(mdctx, key->rho, ML_KEM_RANDOM_BYTES)) return 0; return EVP_DigestFinal_ex(mdctx, pkhash, &sz) && ossl_assert(sz == ML_KEM_PKHASH_BYTES); } /* * FIPS 203, Section 4.1, equation (4.5): G. SHA3-512 hash of a variable * length input, producing 64 bytes of output, in particular the seeds * (d,z) for key generation. */ static __owur int hash_g(uint8_t out[ML_KEM_SEED_BYTES], const uint8_t *in, size_t len, EVP_MD_CTX *mdctx, const ML_KEM_KEY *key) { return EVP_DigestInit_ex(mdctx, key->sha3_512_md, NULL) && single_keccak(out, ML_KEM_SEED_BYTES, in, len, mdctx); } /* * FIPS 203, Section 4.1, equation (4.4): J. SHAKE256 taking a variable length * input to compute a 32-byte implicit rejection shared secret, of the same * length as the expected shared secret. (Computed even on success to avoid * side-channel leaks). */ static __owur int kdf(uint8_t out[ML_KEM_SHARED_SECRET_BYTES], const uint8_t z[ML_KEM_RANDOM_BYTES], const uint8_t *ctext, size_t len, EVP_MD_CTX *mdctx, const ML_KEM_KEY *key) { return EVP_DigestInit_ex(mdctx, key->shake256_md, NULL) && EVP_DigestUpdate(mdctx, z, ML_KEM_RANDOM_BYTES) && EVP_DigestUpdate(mdctx, ctext, len) && EVP_DigestFinalXOF(mdctx, out, ML_KEM_SHARED_SECRET_BYTES); } /* * FIPS 203, Section 4.2.2, Algorithm 7: "SampleNTT" (steps 3-17, steps 1, 2 * are performed by the caller). Rejection-samples a Keccak stream to get * uniformly distributed elements in the range [0,q). This is used for matrix * expansion and only operates on public inputs. */ static __owur int sample_scalar(scalar *out, EVP_MD_CTX *mdctx) { uint16_t *curr = out->c, *endout = curr + DEGREE; uint8_t buf[SCALAR_SAMPLING_BUFSIZE], *in; uint8_t *endin = buf + sizeof(buf); uint16_t d; uint8_t b1, b2, b3; do { if (!EVP_DigestSqueeze(mdctx, in = buf, sizeof(buf))) return 0; do { b1 = *in++; b2 = *in++; b3 = *in++; if (curr >= endout) break; if ((d = ((b2 & 0x0f) << 8) + b1) < kPrime) *curr++ = d; if (curr >= endout) break; if ((d = (b3 << 4) + (b2 >> 4)) < kPrime) *curr++ = d; } while (in < endin); } while (curr < endout); return 1; } /*- * reduce_once reduces 0 <= x < 2*kPrime, mod kPrime. * * Subtract |q| if the input is larger, without exposing a side-channel, * avoiding the "clangover" attack. See |constish_time_non_zero| for a * discussion on why the value barrier is by default omitted. */ static __owur uint16_t reduce_once(uint16_t x) { const uint16_t subtracted = x - kPrime; uint16_t mask = constish_time_non_zero(subtracted >> 15); return (mask & x) | (~mask & subtracted); } /* * Constant-time reduce x mod kPrime using Barrett reduction. x must be less * than kPrime + 2 * kPrime^2. This is sufficient to reduce a product of * two already reduced u_int16 values, in fact it is sufficient for each * to be less than 2^12, because (kPrime * (2 * kPrime + 1)) > 2^24. */ static __owur uint16_t reduce(uint32_t x) { uint64_t product = (uint64_t)x * kBarrettMultiplier; uint32_t quotient = (uint32_t)(product >> kBarrettShift); uint32_t remainder = x - quotient * kPrime; return reduce_once(remainder); } /* Multiply a scalar by a constant. */ static void scalar_mult_const(scalar *s, uint16_t a) { uint16_t *curr = s->c, *end = curr + DEGREE, tmp; do { tmp = reduce(*curr * a); *curr++ = tmp; } while (curr < end); } /*- * FIPS 203, Section 4.3, Algoritm 9: "NTT". * In-place number theoretic transform of a given scalar. Note that ML-KEM's * kPrime 3329 does not have a 512th root of unity, so this transform leaves * off the last iteration of the usual FFT code, with the 128 relevant roots of * unity being stored in NTTRoots. This means the output should be seen as 128 * elements in GF(3329^2), with the coefficients of the elements being * consecutive entries in |s->c|. */ static void scalar_ntt(scalar *s) { const uint16_t *roots = kNTTRoots; uint16_t *end = s->c + DEGREE; int offset = DEGREE / 2; do { uint16_t *curr = s->c, *peer; do { uint16_t *pause = curr + offset, even, odd; uint32_t zeta = *++roots; peer = pause; do { even = *curr; odd = reduce(*peer * zeta); *peer++ = reduce_once(even - odd + kPrime); *curr++ = reduce_once(odd + even); } while (curr < pause); } while ((curr = peer) < end); } while ((offset >>= 1) >= 2); } /*- * FIPS 203, Section 4.3, Algoritm 10: "NTT^(-1)". * In-place inverse number theoretic transform of a given scalar, with pairs of * entries of s->v being interpreted as elements of GF(3329^2). Just as with * the number theoretic transform, this leaves off the first step of the normal * iFFT to account for the fact that 3329 does not have a 512th root of unity, * using the precomputed 128 roots of unity stored in InverseNTTRoots. */ static void scalar_inverse_ntt(scalar *s) { const uint16_t *roots = kInverseNTTRoots; uint16_t *end = s->c + DEGREE; int offset = 2; do { uint16_t *curr = s->c, *peer; do { uint16_t *pause = curr + offset, even, odd; uint32_t zeta = *++roots; peer = pause; do { even = *curr; odd = *peer; *peer++ = reduce(zeta * (even - odd + kPrime)); *curr++ = reduce_once(odd + even); } while (curr < pause); } while ((curr = peer) < end); } while ((offset <<= 1) < DEGREE); scalar_mult_const(s, kInverseDegree); } /* Addition updating the LHS scalar in-place. */ static void scalar_add(scalar *lhs, const scalar *rhs) { int i; for (i = 0; i < DEGREE; i++) lhs->c[i] = reduce_once(lhs->c[i] + rhs->c[i]); } /* Subtraction updating the LHS scalar in-place. */ static void scalar_sub(scalar *lhs, const scalar *rhs) { int i; for (i = 0; i < DEGREE; i++) lhs->c[i] = reduce_once(lhs->c[i] - rhs->c[i] + kPrime); } /* * Multiplying two scalars in the number theoretically transformed state. Since * 3329 does not have a 512th root of unity, this means we have to interpret * the 2*ith and (2*i+1)th entries of the scalar as elements of * GF(3329)[X]/(X^2 - 17^(2*bitreverse(i)+1)). * * The value of 17^(2*bitreverse(i)+1) mod 3329 is stored in the precomputed * ModRoots table. Note that our Barrett transform only allows us to multipy * two reduced numbers together, so we need some intermediate reduction steps, * even if an uint64_t could hold 3 multiplied numbers. */ static void scalar_mult(scalar *out, const scalar *lhs, const scalar *rhs) { uint16_t *curr = out->c, *end = curr + DEGREE; const uint16_t *lc = lhs->c, *rc = rhs->c; const uint16_t *roots = kModRoots; do { uint32_t l0 = *lc++, r0 = *rc++; uint32_t l1 = *lc++, r1 = *rc++; uint32_t zetapow = *roots++; *curr++ = reduce(l0 * r0 + reduce(l1 * r1) * zetapow); *curr++ = reduce(l0 * r1 + l1 * r0); } while (curr < end); } /* Above, but add the result to an existing scalar */ static ossl_inline void scalar_mult_add(scalar *out, const scalar *lhs, const scalar *rhs) { uint16_t *curr = out->c, *end = curr + DEGREE; const uint16_t *lc = lhs->c, *rc = rhs->c; const uint16_t *roots = kModRoots; do { uint32_t l0 = *lc++, r0 = *rc++; uint32_t l1 = *lc++, r1 = *rc++; uint16_t *c0 = curr++; uint16_t *c1 = curr++; uint32_t zetapow = *roots++; *c0 = reduce(*c0 + l0 * r0 + reduce(l1 * r1) * zetapow); *c1 = reduce(*c1 + l0 * r1 + l1 * r0); } while (curr < end); } /*- * FIPS 203, Section 4.2.1, Algorithm 5: "ByteEncode_d", for 2<=d<=12. * Here |bits| is |d|. For efficiency, we handle the d=1 case separately. */ static void scalar_encode(uint8_t *out, const scalar *s, int bits) { const uint16_t *curr = s->c, *end = curr + DEGREE; uint64_t accum = 0, element; int used = 0; do { element = *curr++; if (used + bits < 64) { accum |= element << used; used += bits; } else if (used + bits > 64) { out = OPENSSL_store_u64_le(out, accum | (element << used)); accum = element >> (64 - used); used = (used + bits) - 64; } else { out = OPENSSL_store_u64_le(out, accum | (element << used)); accum = 0; used = 0; } } while (curr < end); } /* * scalar_encode_1 is |scalar_encode| specialised for |bits| == 1. */ static void scalar_encode_1(uint8_t out[DEGREE / 8], const scalar *s) { int i, j; uint8_t out_byte; for (i = 0; i < DEGREE; i += 8) { out_byte = 0; for (j = 0; j < 8; j++) out_byte |= bit0(s->c[i + j]) << j; *out = out_byte; out++; } } /*- * FIPS 203, Section 4.2.1, Algorithm 6: "ByteDecode_d", for 2<=d<12. * Here |bits| is |d|. For efficiency, we handle the d=1 and d=12 cases * separately. * * scalar_decode parses |DEGREE * bits| bits from |in| into |DEGREE| values in * |out|. */ static void scalar_decode(scalar *out, const uint8_t *in, int bits) { uint16_t *curr = out->c, *end = curr + DEGREE; uint64_t accum = 0; int accum_bits = 0, todo = bits; uint16_t bitmask = (((uint16_t) 1) << bits) - 1, mask = bitmask; uint16_t element = 0; do { if (accum_bits == 0) { in = OPENSSL_load_u64_le(&accum, in); accum_bits = 64; } if (todo == bits && accum_bits >= bits) { /* No partial "element", and all the required bits available */ *curr++ = ((uint16_t) accum) & mask; accum >>= bits; accum_bits -= bits; } else if (accum_bits >= todo) { /* A partial "element", and all the required bits available */ *curr++ = element | ((((uint16_t) accum) & mask) << (bits - todo)); accum >>= todo; accum_bits -= todo; element = 0; todo = bits; mask = bitmask; } else { /* * Only some of the requisite bits accumulated, store |accum_bits| * of these in |element|. The accumulated bitcount becomes 0, but * as soon as we have more bits we'll want to merge accum_bits * fewer of them into the final |element|. * * Note that with a 64-bit accumulator and |bits| always 12 or * less, if we're here, the previous iteration had all the * requisite bits, and so there are no kept bits in |element|. */ element = ((uint16_t) accum) & mask; todo -= accum_bits; mask = bitmask >> accum_bits; accum_bits = 0; } } while (curr < end); } static __owur int scalar_decode_12(scalar *out, const uint8_t in[3 * DEGREE / 2]) { int i; uint16_t *c = out->c; for (i = 0; i < DEGREE / 2; ++i) { uint8_t b1 = *in++; uint8_t b2 = *in++; uint8_t b3 = *in++; int outOfRange1 = (*c++ = b1 | ((b2 & 0x0f) << 8)) >= kPrime; int outOfRange2 = (*c++ = (b2 >> 4) | (b3 << 4)) >= kPrime; if (outOfRange1 | outOfRange2) return 0; } return 1; } /*- * scalar_decode_decompress_add is a combination of decoding and decompression * both specialised for |bits| == 1, with the result added (and sum reduced) to * the output scalar. * * NOTE: this function MUST not leak an input-data-depedennt timing signal. * A timing leak in a related function in the reference Kyber implementation * made the "clangover" attack (CVE-2024-37880) possible, giving key recovery * for ML-KEM-512 in minutes, provided the attacker has access to precise * timing of a CPU performing chosen-ciphertext decap. Admittedly this is only * a risk when private keys are reused (perhaps KEMTLS servers). */ static void scalar_decode_decompress_add(scalar *out, const uint8_t in[DEGREE / 8]) { static const uint16_t half_q_plus_1 = (ML_KEM_PRIME >> 1) + 1; uint16_t *curr = out->c, *end = curr + DEGREE; uint16_t mask; uint8_t b; /* * Add |half_q_plus_1| if the bit is set, without exposing a side-channel, * avoiding the "clangover" attack. See |constish_time_non_zero| for a * discussion on why the value barrier is by default omitted. */ #define decode_decompress_add_bit \ mask = constish_time_non_zero(bit0(b)); \ *curr = reduce_once(*curr + (mask & half_q_plus_1)); \ curr++; \ b >>= 1 /* Unrolled to process each byte in one iteration */ do { b = *in++; decode_decompress_add_bit; decode_decompress_add_bit; decode_decompress_add_bit; decode_decompress_add_bit; decode_decompress_add_bit; decode_decompress_add_bit; decode_decompress_add_bit; decode_decompress_add_bit; } while (curr < end); #undef decode_decompress_add_bit } /* * FIPS 203, Section 4.2.1, Equation (4.7): Compress_d. * * Compresses (lossily) an input |x| mod 3329 into |bits| many bits by grouping * numbers close to each other together. The formula used is * round(2^|bits|/kPrime*x) mod 2^|bits|. * Uses Barrett reduction to achieve constant time. Since we need both the * remainder (for rounding) and the quotient (as the result), we cannot use * |reduce| here, but need to do the Barrett reduction directly. */ static __owur uint16_t compress(uint16_t x, int bits) { uint32_t shifted = (uint32_t)x << bits; uint64_t product = (uint64_t)shifted * kBarrettMultiplier; uint32_t quotient = (uint32_t)(product >> kBarrettShift); uint32_t remainder = shifted - quotient * kPrime; /* * Adjust the quotient to round correctly: * 0 <= remainder <= kHalfPrime round to 0 * kHalfPrime < remainder <= kPrime + kHalfPrime round to 1 * kPrime + kHalfPrime < remainder < 2 * kPrime round to 2 */ quotient += 1 & constant_time_lt_32(kHalfPrime, remainder); quotient += 1 & constant_time_lt_32(kPrime + kHalfPrime, remainder); return quotient & ((1 << bits) - 1); } /* * FIPS 203, Section 4.2.1, Equation (4.8): Decompress_d. * Decompresses |x| by using a close equi-distant representative. The formula * is round(kPrime/2^|bits|*x). Note that 2^|bits| being the divisor allows us * to implement this logic using only bit operations. */ static __owur uint16_t decompress(uint16_t x, int bits) { uint32_t product = (uint32_t)x * kPrime; uint32_t power = 1 << bits; /* This is |product| % power, since |power| is a power of 2. */ uint32_t remainder = product & (power - 1); /* This is |product| / power, since |power| is a power of 2. */ uint32_t lower = product >> bits; /* * The rounding logic works since the first half of numbers mod |power| * have a 0 as first bit, and the second half has a 1 as first bit, since * |power| is a power of 2. As a 12 bit number, |remainder| is always * positive, so we will shift in 0s for a right shift. */ return lower + (remainder >> (bits - 1)); } /*- * FIPS 203, Section 4.2.1, Equation (4.7): "Compress_d". * In-place lossy rounding of scalars to 2^d bits. */ static void scalar_compress(scalar *s, int bits) { int i; for (i = 0; i < DEGREE; i++) s->c[i] = compress(s->c[i], bits); } /* * FIPS 203, Section 4.2.1, Equation (4.8): "Decompress_d". * In-place approximate recovery of scalars from 2^d bit compression. */ static void scalar_decompress(scalar *s, int bits) { int i; for (i = 0; i < DEGREE; i++) s->c[i] = decompress(s->c[i], bits); } /* Addition updating the LHS vector in-place. */ static void vector_add(scalar *lhs, const scalar *rhs, int rank) { do { scalar_add(lhs++, rhs++); } while (--rank > 0); } /* * Encodes an entire vector into 32*|rank|*|bits| bytes. Note that since 256 * (DEGREE) is divisible by 8, the individual vector entries will always fill a * whole number of bytes, so we do not need to worry about bit packing here. */ static void vector_encode(uint8_t *out, const scalar *a, int bits, int rank) { int stride = bits * DEGREE / 8; for (; rank-- > 0; out += stride) scalar_encode(out, a++, bits); } /* * Decodes 32*|rank|*|bits| bytes from |in| into |out|. It returns early * if any parsed value is >= |ML_KEM_PRIME|. The resulting scalars are * then decompressed and transformed via the NTT. * * Note: Used only in decrypt_cpa(), which returns void and so does not check * the return value of this function. Side-channels are fine when the input * ciphertext to decap() is simply syntactically invalid. */ static void vector_decode_decompress_ntt(scalar *out, const uint8_t *in, int bits, int rank) { int stride = bits * DEGREE / 8; for (; rank-- > 0; in += stride, ++out) { scalar_decode(out, in, bits); scalar_decompress(out, bits); scalar_ntt(out); } } /* vector_decode(), specialised to bits == 12. */ static __owur int vector_decode_12(scalar *out, const uint8_t in[3 * DEGREE / 2], int rank) { int stride = 3 * DEGREE / 2; for (; rank-- > 0; in += stride) if (!scalar_decode_12(out++, in)) return 0; return 1; } /* In-place compression of each scalar component */ static void vector_compress(scalar *a, int bits, int rank) { do { scalar_compress(a++, bits); } while (--rank > 0); } /* The output scalar must not overlap with the inputs */ static void inner_product(scalar *out, const scalar *lhs, const scalar *rhs, int rank) { scalar_mult(out, lhs, rhs); while (--rank > 0) scalar_mult_add(out, ++lhs, ++rhs); } /* * Here, the output vector must not overlap with the inputs, the result is * directly subjected to inverse NTT. */ static void matrix_mult_intt(scalar *out, const scalar *m, const scalar *a, int rank) { const scalar *ar; int i, j; for (i = rank; i-- > 0; ++out) { scalar_mult(out, m++, ar = a); for (j = rank - 1; j > 0; --j) scalar_mult_add(out, m++, ++ar); scalar_inverse_ntt(out); } } /* Here, the output vector must not overlap with the inputs */ static void matrix_mult_transpose_add(scalar *out, const scalar *m, const scalar *a, int rank) { const scalar *mc = m, *mr, *ar; int i, j; for (i = rank; i-- > 0; ++out) { scalar_mult_add(out, mr = mc++, ar = a); for (j = rank; --j > 0; ) scalar_mult_add(out, (mr += rank), ++ar); } } /*- * Expands the matrix from a seed for key generation and for encaps-CPA. * NOTE: FIPS 203 matrix "A" is the transpose of this matrix, computed * by appending the (i,j) indices to the seed in the opposite order! * * Where FIPS 203 computes t = A * s + e, we use the transpose of "m". */ static __owur int matrix_expand(EVP_MD_CTX *mdctx, ML_KEM_KEY *key) { scalar *out = key->m; uint8_t input[ML_KEM_RANDOM_BYTES + 2]; int rank = key->vinfo->rank; int i, j; memcpy(input, key->rho, ML_KEM_RANDOM_BYTES); for (i = 0; i < rank; i++) { for (j = 0; j < rank; j++) { input[ML_KEM_RANDOM_BYTES] = i; input[ML_KEM_RANDOM_BYTES + 1] = j; if (!EVP_DigestInit_ex(mdctx, key->shake128_md, NULL) || !EVP_DigestUpdate(mdctx, input, sizeof(input)) || !sample_scalar(out++, mdctx)) return 0; } } return 1; } /* * Algorithm 7 from the spec, with eta fixed to two and the PRF call * included. Creates binominally distributed elements by sampling 2*|eta| bits, * and setting the coefficient to the count of the first bits minus the count of * the second bits, resulting in a centered binomial distribution. Since eta is * two this gives -2/2 with a probability of 1/16, -1/1 with probability 1/4, * and 0 with probability 3/8. */ static __owur int cbd_2(scalar *out, uint8_t in[ML_KEM_RANDOM_BYTES + 1], EVP_MD_CTX *mdctx, const ML_KEM_KEY *key) { uint16_t *curr = out->c, *end = curr + DEGREE; uint8_t randbuf[4 * DEGREE / 8], *r = randbuf; /* 64 * eta slots */ uint16_t value, mask; uint8_t b; if (!prf(randbuf, sizeof(randbuf), in, mdctx, key)) return 0; do { b = *r++; /* * Add |kPrime| if |value| underflowed. See |constish_time_non_zero| * for a discussion on why the value barrier is by default omitted. * While this could have been written reduce_once(value + kPrime), this * is one extra addition and small range of |value| tempts some * versions of Clang to emit a branch. */ value = bit0(b) + bitn(1, b); value -= bitn(2, b) + bitn(3, b); mask = constish_time_non_zero(value >> 15); *curr++ = value + (kPrime & mask); value = bitn(4, b) + bitn(5, b); value -= bitn(6, b) + bitn(7, b); mask = constish_time_non_zero(value >> 15); *curr++ = value + (kPrime & mask); } while (curr < end); return 1; } /* * Algorithm 7 from the spec, with eta fixed to three and the PRF call * included. Creates binominally distributed elements by sampling 3*|eta| bits, * and setting the coefficient to the count of the first bits minus the count of * the second bits, resulting in a centered binomial distribution. */ static __owur int cbd_3(scalar *out, uint8_t in[ML_KEM_RANDOM_BYTES + 1], EVP_MD_CTX *mdctx, const ML_KEM_KEY *key) { uint16_t *curr = out->c, *end = curr + DEGREE; uint8_t randbuf[6 * DEGREE / 8], *r = randbuf; /* 64 * eta slots */ uint8_t b1, b2, b3; uint16_t value, mask; if (!prf(randbuf, sizeof(randbuf), in, mdctx, key)) return 0; do { b1 = *r++; b2 = *r++; b3 = *r++; /* * Add |kPrime| if |value| underflowed. See |constish_time_non_zero| * for a discussion on why the value barrier is by default omitted. * While this could have been written reduce_once(value + kPrime), this * is one extra addition and small range of |value| tempts some * versions of Clang to emit a branch. */ value = bit0(b1) + bitn(1, b1) + bitn(2, b1); value -= bitn(3, b1) + bitn(4, b1) + bitn(5, b1); mask = constish_time_non_zero(value >> 15); *curr++ = value + (kPrime & mask); value = bitn(6, b1) + bitn(7, b1) + bit0(b2); value -= bitn(1, b2) + bitn(2, b2) + bitn(3, b2); mask = constish_time_non_zero(value >> 15); *curr++ = value + (kPrime & mask); value = bitn(4, b2) + bitn(5, b2) + bitn(6, b2); value -= bitn(7, b2) + bit0(b3) + bitn(1, b3); mask = constish_time_non_zero(value >> 15); *curr++ = value + (kPrime & mask); value = bitn(2, b3) + bitn(3, b3) + bitn(4, b3); value -= bitn(5, b3) + bitn(6, b3) + bitn(7, b3); mask = constish_time_non_zero(value >> 15); *curr++ = value + (kPrime & mask); } while (curr < end); return 1; } /* * Generates a secret vector by using |cbd| with the given seed to generate * scalar elements and incrementing |counter| for each slot of the vector. */ static __owur int gencbd_vector(scalar *out, CBD_FUNC cbd, uint8_t *counter, const uint8_t seed[ML_KEM_RANDOM_BYTES], int rank, EVP_MD_CTX *mdctx, const ML_KEM_KEY *key) { uint8_t input[ML_KEM_RANDOM_BYTES + 1]; memcpy(input, seed, ML_KEM_RANDOM_BYTES); do { input[ML_KEM_RANDOM_BYTES] = (*counter)++; if (!cbd(out++, input, mdctx, key)) return 0; } while (--rank > 0); return 1; } /* * As above plus NTT transform. */ static __owur int gencbd_vector_ntt(scalar *out, CBD_FUNC cbd, uint8_t *counter, const uint8_t seed[ML_KEM_RANDOM_BYTES], int rank, EVP_MD_CTX *mdctx, const ML_KEM_KEY *key) { uint8_t input[ML_KEM_RANDOM_BYTES + 1]; memcpy(input, seed, ML_KEM_RANDOM_BYTES); do { input[ML_KEM_RANDOM_BYTES] = (*counter)++; if (!cbd(out, input, mdctx, key)) return 0; scalar_ntt(out++); } while (--rank > 0); return 1; } /* The |ETA1| value for ML-KEM-512 is 3, the rest and all ETA2 values are 2. */ #define CBD1(evp_type) ((evp_type) == EVP_PKEY_ML_KEM_512 ? cbd_3 : cbd_2) /* * FIPS 203, Section 5.2, Algorithm 14: K-PKE.Encrypt. * * Encrypts a message with given randomness to the ciphertext in |out|. Without * applying the Fujisaki-Okamoto transform this would not result in a CCA * secure scheme, since lattice schemes are vulnerable to decryption failure * oracles. * * The steps are re-ordered to make more efficient/localised use of storage. * * Note also that the input public key is assumed to hold a precomputed matrix * |A| (our key->m, with the public key holding an expanded (16-bit per scalar * coefficient) key->t vector). * * Caller passes storage in |tmp| for for two temporary vectors. */ static __owur int encrypt_cpa(uint8_t out[ML_KEM_SHARED_SECRET_BYTES], const uint8_t message[DEGREE / 8], const uint8_t r[ML_KEM_RANDOM_BYTES], scalar *tmp, EVP_MD_CTX *mdctx, const ML_KEM_KEY *key) { const ML_KEM_VINFO *vinfo = key->vinfo; CBD_FUNC cbd_1 = CBD1(vinfo->evp_type); int rank = vinfo->rank; /* We can use tmp[0..rank-1] as storage for |y|, then |e1|, ... */ scalar *y = &tmp[0], *e1 = y, *e2 = y; /* We can use tmp[rank]..tmp[2*rank - 1] for |u| */ scalar *u = &tmp[rank]; scalar v; uint8_t input[ML_KEM_RANDOM_BYTES + 1]; uint8_t counter = 0; int du = vinfo->du; int dv = vinfo->dv; /* FIPS 203 "y" vector */ if (!gencbd_vector_ntt(y, cbd_1, &counter, r, rank, mdctx, key)) return 0; /* FIPS 203 "v" scalar */ inner_product(&v, key->t, y, rank); scalar_inverse_ntt(&v); /* FIPS 203 "u" vector */ matrix_mult_intt(u, key->m, y, rank); /* All done with |y|, now free to reuse tmp[0] for FIPS 203 |e1| */ if (!gencbd_vector(e1, cbd_2, &counter, r, rank, mdctx, key)) return 0; vector_add(u, e1, rank); vector_compress(u, du, rank); vector_encode(out, u, du, rank); /* All done with |e1|, now free to reuse tmp[0] for FIPS 203 |e2| */ memcpy(input, r, ML_KEM_RANDOM_BYTES); input[ML_KEM_RANDOM_BYTES] = counter; if (!cbd_2(e2, input, mdctx, key)) return 0; scalar_add(&v, e2); /* Combine message with |v| */ scalar_decode_decompress_add(&v, message); scalar_compress(&v, dv); scalar_encode(out + vinfo->u_vector_bytes, &v, dv); return 1; } /* * FIPS 203, Section 5.3, Algorithm 15: K-PKE.Decrypt. */ static void decrypt_cpa(uint8_t out[ML_KEM_SHARED_SECRET_BYTES], const uint8_t *ctext, scalar *u, const ML_KEM_KEY *key) { const ML_KEM_VINFO *vinfo = key->vinfo; scalar v, mask; int rank = vinfo->rank; int du = vinfo->du; int dv = vinfo->dv; vector_decode_decompress_ntt(u, ctext, du, rank); scalar_decode(&v, ctext + vinfo->u_vector_bytes, dv); scalar_decompress(&v, dv); inner_product(&mask, key->s, u, rank); scalar_inverse_ntt(&mask); scalar_sub(&v, &mask); scalar_compress(&v, 1); scalar_encode_1(out, &v); } /*- * FIPS 203, Section 7.1, Algorithm 19: "ML-KEM.KeyGen". * FIPS 203, Section 7.2, Algorithm 20: "ML-KEM.Encaps". * * Fills the |out| buffer with the |ek| output of "ML-KEM.KeyGen", or, * equivalently, the |ek| input of "ML-KEM.Encaps", i.e. returns the * wire-format of an ML-KEM public key. */ static void encode_pubkey(uint8_t *out, const ML_KEM_KEY *key) { const uint8_t *rho = key->rho; const ML_KEM_VINFO *vinfo = key->vinfo; vector_encode(out, key->t, 12, vinfo->rank); memcpy(out + vinfo->vector_bytes, rho, ML_KEM_RANDOM_BYTES); } /*- * FIPS 203, Section 7.1, Algorithm 19: "ML-KEM.KeyGen". * * Fills the |out| buffer with the |dk| output of "ML-KEM.KeyGen". * This matches the input format of parse_prvkey() below. */ static void encode_prvkey(uint8_t *out, const ML_KEM_KEY *key) { const ML_KEM_VINFO *vinfo = key->vinfo; vector_encode(out, key->s, 12, vinfo->rank); out += vinfo->vector_bytes; encode_pubkey(out, key); out += vinfo->pubkey_bytes; memcpy(out, key->pkhash, ML_KEM_PKHASH_BYTES); out += ML_KEM_PKHASH_BYTES; memcpy(out, key->z, ML_KEM_RANDOM_BYTES); } /*- * FIPS 203, Section 7.1, Algorithm 19: "ML-KEM.KeyGen". * FIPS 203, Section 7.2, Algorithm 20: "ML-KEM.Encaps". * * This function parses the |in| buffer as the |ek| output of "ML-KEM.KeyGen", * or, equivalently, the |ek| input of "ML-KEM.Encaps", i.e. decodes the * wire-format of the ML-KEM public key. */ static int parse_pubkey(const uint8_t *in, EVP_MD_CTX *mdctx, ML_KEM_KEY *key) { const ML_KEM_VINFO *vinfo = key->vinfo; /* Decode and check |t| */ if (!vector_decode_12(key->t, in, vinfo->rank)) { ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_KEY, "%s invalid public 't' vector", vinfo->algorithm_name); return 0; } /* Save the matrix |m| recovery seed |rho| */ memcpy(key->rho, in + vinfo->vector_bytes, ML_KEM_RANDOM_BYTES); /* * Pre-compute the public key hash, needed for both encap and decap. * Also pre-compute the matrix expansion, stored with the public key. */ if (!hash_h(key->pkhash, in, vinfo->pubkey_bytes, mdctx, key) || !matrix_expand(mdctx, key)) { ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR, "internal error while parsing %s public key", vinfo->algorithm_name); return 0; } return 1; } /* * FIPS 203, Section 7.1, Algorithm 19: "ML-KEM.KeyGen". * * Parses the |in| buffer as a |dk| output of "ML-KEM.KeyGen". * This matches the output format of encode_prvkey() above. */ static int parse_prvkey(const uint8_t *in, EVP_MD_CTX *mdctx, ML_KEM_KEY *key) { const ML_KEM_VINFO *vinfo = key->vinfo; /* Decode and check |s|. */ if (!vector_decode_12(key->s, in, vinfo->rank)) { ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_KEY, "%s invalid private 's' vector", vinfo->algorithm_name); return 0; } in += vinfo->vector_bytes; if (!parse_pubkey(in, mdctx, key)) return 0; in += vinfo->pubkey_bytes; /* Check public key hash. */ if (memcmp(key->pkhash, in, ML_KEM_PKHASH_BYTES) != 0) { ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_KEY, "%s public key hash mismatch", vinfo->algorithm_name); return 0; } in += ML_KEM_PKHASH_BYTES; memcpy(key->z, in, ML_KEM_RANDOM_BYTES); return 1; } /* * FIPS 203, Section 6.1, Algorithm 16: "ML-KEM.KeyGen_internal". * * The implementation of Section 5.1, Algorithm 13, "K-PKE.KeyGen(d)" is * inlined. * * The caller MUST pass a pre-allocated digest context that is not shared with * any concurrent computation. * * This function optionally outputs the serialised wire-form |ek| public key * into the provided |pubenc| buffer, and generates the content of the |rho|, * |pkhash|, |t|, |m|, |s| and |z| components of the private |key| (which must * have preallocated space for these). * * Keys are computed from a 32-byte random |d| plus the 1 byte rank for * domain separation. These are concatenated and hashed to produce a pair of * 32-byte seeds public "rho", used to generate the matrix, and private "sigma", * used to generate the secret vector |s|. * * The second random input |z| is copied verbatim into the Fujisaki-Okamoto * (FO) transform "implicit-rejection" secret (the |z| component of the private * key), which thwarts chosen-ciphertext attacks, provided decap() runs in * constant time, with no side channel leaks, on all well-formed (valid length, * and correctly encoded) ciphertext inputs. */ static __owur int genkey(const uint8_t seed[ML_KEM_SEED_BYTES], EVP_MD_CTX *mdctx, uint8_t *pubenc, ML_KEM_KEY *key) { uint8_t hashed[2 * ML_KEM_RANDOM_BYTES]; const uint8_t *const sigma = hashed + ML_KEM_RANDOM_BYTES; uint8_t augmented_seed[ML_KEM_RANDOM_BYTES + 1]; const ML_KEM_VINFO *vinfo = key->vinfo; CBD_FUNC cbd_1 = CBD1(vinfo->evp_type); int rank = vinfo->rank; uint8_t counter = 0; int ret = 0; /* * Use the "d" seed salted with the rank to derive the public and private * seeds rho and sigma. */ memcpy(augmented_seed, seed, ML_KEM_RANDOM_BYTES); augmented_seed[ML_KEM_RANDOM_BYTES] = (uint8_t) rank; if (!hash_g(hashed, augmented_seed, sizeof(augmented_seed), mdctx, key)) goto end; memcpy(key->rho, hashed, ML_KEM_RANDOM_BYTES); /* The |rho| matrix seed is public */ CONSTTIME_DECLASSIFY(key->rho, ML_KEM_RANDOM_BYTES); /* FIPS 203 |e| vector is initial value of key->t */ if (!matrix_expand(mdctx, key) || !gencbd_vector_ntt(key->s, cbd_1, &counter, sigma, rank, mdctx, key) || !gencbd_vector_ntt(key->t, cbd_1, &counter, sigma, rank, mdctx, key)) goto end; /* To |e| we now add the product of transpose |m| and |s|, giving |t|. */ matrix_mult_transpose_add(key->t, key->m, key->s, rank); /* The |t| vector is public */ CONSTTIME_DECLASSIFY(key->t, vinfo->rank * sizeof(scalar)); if (pubenc == NULL) { /* Incremental digest of public key without in-full serialisation. */ if (!hash_h_pubkey(key->pkhash, mdctx, key)) goto end; } else { encode_pubkey(pubenc, key); if (!hash_h(key->pkhash, pubenc, vinfo->pubkey_bytes, mdctx, key)) goto end; } /* Save |z| portion of seed for "implicit rejection" on failure. */ memcpy(key->z, seed + ML_KEM_RANDOM_BYTES, ML_KEM_RANDOM_BYTES); /* Optionally save the |d| portion of the seed */ key->d = key->z + ML_KEM_RANDOM_BYTES; if (key->prov_flags & ML_KEM_KEY_RETAIN_SEED) { memcpy(key->d, seed, ML_KEM_RANDOM_BYTES); } else { OPENSSL_cleanse(key->d, ML_KEM_RANDOM_BYTES); key->d = NULL; } ret = 1; end: OPENSSL_cleanse((void *)augmented_seed, ML_KEM_RANDOM_BYTES); OPENSSL_cleanse((void *)sigma, ML_KEM_RANDOM_BYTES); if (ret == 0) { ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR, "internal error while generating %s private key", vinfo->algorithm_name); } return ret; } /*- * FIPS 203, Section 6.2, Algorithm 17: "ML-KEM.Encaps_internal". * This is the deterministic version with randomness supplied externally. * * The caller must pass space for two vectors in |tmp|. * The |ctext| buffer have space for the ciphertext of the ML-KEM variant * of the provided key. */ static int encap(uint8_t *ctext, uint8_t secret[ML_KEM_SHARED_SECRET_BYTES], const uint8_t entropy[ML_KEM_RANDOM_BYTES], scalar *tmp, EVP_MD_CTX *mdctx, const ML_KEM_KEY *key) { uint8_t input[ML_KEM_RANDOM_BYTES + ML_KEM_PKHASH_BYTES]; uint8_t Kr[ML_KEM_SHARED_SECRET_BYTES + ML_KEM_RANDOM_BYTES]; uint8_t *r = Kr + ML_KEM_SHARED_SECRET_BYTES; int ret; memcpy(input, entropy, ML_KEM_RANDOM_BYTES); memcpy(input + ML_KEM_RANDOM_BYTES, key->pkhash, ML_KEM_PKHASH_BYTES); ret = hash_g(Kr, input, sizeof(input), mdctx, key) && encrypt_cpa(ctext, entropy, r, tmp, mdctx, key); OPENSSL_cleanse((void *)input, sizeof(input)); if (ret) memcpy(secret, Kr, ML_KEM_SHARED_SECRET_BYTES); else ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR, "internal error while performing %s encapsulation", key->vinfo->algorithm_name); return ret; } /* * FIPS 203, Section 6.3, Algorithm 18: ML-KEM.Decaps_internal * * Barring failure of the supporting SHA3/SHAKE primitives, this is fully * deterministic, the randomness for the FO transform is extracted during * private key generation. * * The caller must pass space for two vectors in |tmp|. * The |ctext| and |tmp_ctext| buffers must each have space for the ciphertext * of the key's ML-KEM variant. */ static int decap(uint8_t secret[ML_KEM_SHARED_SECRET_BYTES], const uint8_t *ctext, uint8_t *tmp_ctext, scalar *tmp, EVP_MD_CTX *mdctx, const ML_KEM_KEY *key) { uint8_t decrypted[ML_KEM_SHARED_SECRET_BYTES + ML_KEM_PKHASH_BYTES]; uint8_t failure_key[ML_KEM_RANDOM_BYTES]; uint8_t Kr[ML_KEM_SHARED_SECRET_BYTES + ML_KEM_RANDOM_BYTES]; uint8_t *r = Kr + ML_KEM_SHARED_SECRET_BYTES; const uint8_t *pkhash = key->pkhash; const ML_KEM_VINFO *vinfo = key->vinfo; int i; uint8_t mask; /* * If our KDF is unavailable, fail early! Otherwise, keep going ignoring * any further errors, returning success, and whatever we got for a shared * secret. The decrypt_cpa() function is just arithmetic on secret data, * so should not be subject to failure that makes its output predictable. * * We guard against "should never happen" catastrophic failure of the * "pure" function |hash_g| by overwriting the shared secret with the * content of the failure key and returning early, if nevertheless hash_g * fails. This is not constant-time, but a failure of |hash_g| already * implies loss of side-channel resistance. * * The same action is taken, if also |encrypt_cpa| should catastrophically * fail, due to failure of the |PRF| underlying the CBD functions. */ if (!kdf(failure_key, key->z, ctext, vinfo->ctext_bytes, mdctx, key)) { ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR, "internal error while performing %s decapsulation", vinfo->algorithm_name); return 0; } decrypt_cpa(decrypted, ctext, tmp, key); memcpy(decrypted + ML_KEM_SHARED_SECRET_BYTES, pkhash, ML_KEM_PKHASH_BYTES); if (!hash_g(Kr, decrypted, sizeof(decrypted), mdctx, key) || !encrypt_cpa(tmp_ctext, decrypted, r, tmp, mdctx, key)) { memcpy(secret, failure_key, ML_KEM_SHARED_SECRET_BYTES); OPENSSL_cleanse(decrypted, ML_KEM_SHARED_SECRET_BYTES); return 1; } mask = constant_time_eq_int_8(0, CRYPTO_memcmp(ctext, tmp_ctext, vinfo->ctext_bytes)); for (i = 0; i < ML_KEM_SHARED_SECRET_BYTES; i++) secret[i] = constant_time_select_8(mask, Kr[i], failure_key[i]); OPENSSL_cleanse(decrypted, ML_KEM_SHARED_SECRET_BYTES); OPENSSL_cleanse(Kr, sizeof(Kr)); return 1; } /* * After allocating storage for public or private key data, update the key * component pointers to reference that storage. */ static __owur int add_storage(scalar *p, int private, ML_KEM_KEY *key) { int rank = key->vinfo->rank; if (p == NULL) return 0; /* * We're adding key material, the seed buffer will now hold |rho| and * |pkhash|. */ memset(key->seedbuf, 0, sizeof(key->seedbuf)); key->rho = key->seedbuf; key->pkhash = key->seedbuf + ML_KEM_RANDOM_BYTES; key->d = key->z = NULL; /* A public key needs space for |t| and |m| */ key->m = (key->t = p) + rank; /* * A private key also needs space for |s| and |z|. * The |z| buffer always includes additional space for |d|, but a key's |d| * pointer is left NULL when parsed from the NIST format, which omits that * information. Only keys generated from a (d, z) seed pair will have a * non-NULL |d| pointer. */ if (private) key->z = (uint8_t *)(rank + (key->s = key->m + rank * rank)); return 1; } /* * After freeing the storage associated with a key that failed to be * constructed, reset the internal pointers back to NULL. */ void ossl_ml_kem_key_reset(ML_KEM_KEY *key) { if (key->t == NULL) return; /*- * Cleanse any sensitive data: * - The private vector |s| is immediately followed by the FO failure * secret |z|, and seed |d|, we can cleanse all three in one call. * * - Otherwise, when key->d is set, cleanse the stashed seed. */ if (ossl_ml_kem_have_prvkey(key)) OPENSSL_cleanse(key->s, key->vinfo->rank * sizeof(scalar) + 2 * ML_KEM_RANDOM_BYTES); OPENSSL_free(key->t); key->d = key->z = (uint8_t *)(key->s = key->m = key->t = NULL); } /* * ----- API exported to the provider * * Parameters with an implicit fixed length in the internal static API of each * variant have an explicit checked length argument at this layer. */ /* Retrieve the parameters of one of the ML-KEM variants */ const ML_KEM_VINFO *ossl_ml_kem_get_vinfo(int evp_type) { switch (evp_type) { case EVP_PKEY_ML_KEM_512: return &vinfo_map[ML_KEM_512_VINFO]; case EVP_PKEY_ML_KEM_768: return &vinfo_map[ML_KEM_768_VINFO]; case EVP_PKEY_ML_KEM_1024: return &vinfo_map[ML_KEM_1024_VINFO]; } return NULL; } ML_KEM_KEY *ossl_ml_kem_key_new(OSSL_LIB_CTX *libctx, const char *properties, int evp_type) { const ML_KEM_VINFO *vinfo = ossl_ml_kem_get_vinfo(evp_type); ML_KEM_KEY *key; if (vinfo == NULL) { ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT, "unsupported ML-KEM key type: %d", evp_type); return NULL; } if ((key = OPENSSL_malloc(sizeof(*key))) == NULL) return NULL; key->vinfo = vinfo; key->libctx = libctx; key->prov_flags = ML_KEM_KEY_PROV_FLAGS_DEFAULT; key->shake128_md = EVP_MD_fetch(libctx, "SHAKE128", properties); key->shake256_md = EVP_MD_fetch(libctx, "SHAKE256", properties); key->sha3_256_md = EVP_MD_fetch(libctx, "SHA3-256", properties); key->sha3_512_md = EVP_MD_fetch(libctx, "SHA3-512", properties); key->d = key->z = key->rho = key->pkhash = key->encoded_dk = NULL; key->s = key->m = key->t = NULL; if (key->shake128_md != NULL && key->shake256_md != NULL && key->sha3_256_md != NULL && key->sha3_512_md != NULL) return key; ossl_ml_kem_key_free(key); ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR, "missing SHA3 digest algorithms while creating %s key", vinfo->algorithm_name); return NULL; } ML_KEM_KEY *ossl_ml_kem_key_dup(const ML_KEM_KEY *key, int selection) { int ok = 0; ML_KEM_KEY *ret; /* * Partially decoded keys, not yet imported or loaded, should never be * duplicated. */ if (ossl_ml_kem_decoded_key(key)) return NULL; if (key == NULL || (ret = OPENSSL_memdup(key, sizeof(*key))) == NULL) return NULL; ret->d = ret->z = ret->rho = ret->pkhash = NULL; ret->s = ret->m = ret->t = NULL; /* Clear selection bits we can't fulfill */ if (!ossl_ml_kem_have_pubkey(key)) selection = 0; else if (!ossl_ml_kem_have_prvkey(key)) selection &= ~OSSL_KEYMGMT_SELECT_PRIVATE_KEY; switch (selection & OSSL_KEYMGMT_SELECT_KEYPAIR) { case 0: ok = 1; break; case OSSL_KEYMGMT_SELECT_PUBLIC_KEY: ok = add_storage(OPENSSL_memdup(key->t, key->vinfo->puballoc), 0, ret); ret->rho = ret->seedbuf; ret->pkhash = ret->rho + ML_KEM_RANDOM_BYTES; break; case OSSL_KEYMGMT_SELECT_PRIVATE_KEY: ok = add_storage(OPENSSL_memdup(key->t, key->vinfo->prvalloc), 1, ret); /* Duplicated keys retain |d|, if available */ if (key->d != NULL) ret->d = ret->z + ML_KEM_RANDOM_BYTES; break; } if (!ok) { OPENSSL_free(ret); return NULL; } EVP_MD_up_ref(ret->shake128_md); EVP_MD_up_ref(ret->shake256_md); EVP_MD_up_ref(ret->sha3_256_md); EVP_MD_up_ref(ret->sha3_512_md); return ret; } void ossl_ml_kem_key_free(ML_KEM_KEY *key) { if (key == NULL) return; EVP_MD_free(key->shake128_md); EVP_MD_free(key->shake256_md); EVP_MD_free(key->sha3_256_md); EVP_MD_free(key->sha3_512_md); if (ossl_ml_kem_decoded_key(key)) { OPENSSL_cleanse(key->seedbuf, sizeof(key->seedbuf)); if (ossl_ml_kem_have_dkenc(key)) { OPENSSL_cleanse(key->encoded_dk, key->vinfo->prvkey_bytes); OPENSSL_free(key->encoded_dk); } } ossl_ml_kem_key_reset(key); OPENSSL_free(key); } /* Serialise the public component of an ML-KEM key */ int ossl_ml_kem_encode_public_key(uint8_t *out, size_t len, const ML_KEM_KEY *key) { if (!ossl_ml_kem_have_pubkey(key) || len != key->vinfo->pubkey_bytes) return 0; encode_pubkey(out, key); return 1; } /* Serialise an ML-KEM private key */ int ossl_ml_kem_encode_private_key(uint8_t *out, size_t len, const ML_KEM_KEY *key) { if (!ossl_ml_kem_have_prvkey(key) || len != key->vinfo->prvkey_bytes) return 0; encode_prvkey(out, key); return 1; } int ossl_ml_kem_encode_seed(uint8_t *out, size_t len, const ML_KEM_KEY *key) { if (key == NULL || key->d == NULL || len != ML_KEM_SEED_BYTES) return 0; /* * Both in the seed buffer, and in the allocated storage, the |d| component * of the seed is stored last, so we must copy each separately. */ memcpy(out, key->d, ML_KEM_RANDOM_BYTES); out += ML_KEM_RANDOM_BYTES; memcpy(out, key->z, ML_KEM_RANDOM_BYTES); return 1; } /* * Stash the seed without (yet) performing a keygen, used during decoding, to * avoid an extra keygen if we're only going to export the key again to load * into another provider. */ ML_KEM_KEY *ossl_ml_kem_set_seed(const uint8_t *seed, size_t seedlen, ML_KEM_KEY *key) { if (key == NULL || ossl_ml_kem_have_pubkey(key) || ossl_ml_kem_have_seed(key) || seedlen != ML_KEM_SEED_BYTES) return NULL; /* * With no public or private key material on hand, we can use the seed * buffer for |z| and |d|, in that order. */ key->z = key->seedbuf; key->d = key->z + ML_KEM_RANDOM_BYTES; memcpy(key->d, seed, ML_KEM_RANDOM_BYTES); seed += ML_KEM_RANDOM_BYTES; memcpy(key->z, seed, ML_KEM_RANDOM_BYTES); return key; } /* Parse input as a public key */ int ossl_ml_kem_parse_public_key(const uint8_t *in, size_t len, ML_KEM_KEY *key) { EVP_MD_CTX *mdctx = NULL; const ML_KEM_VINFO *vinfo; int ret = 0; /* Keys with key material are immutable */ if (key == NULL || ossl_ml_kem_have_pubkey(key) || ossl_ml_kem_have_dkenc(key)) return 0; vinfo = key->vinfo; if (len != vinfo->pubkey_bytes || (mdctx = EVP_MD_CTX_new()) == NULL) return 0; if (add_storage(OPENSSL_malloc(vinfo->puballoc), 0, key)) ret = parse_pubkey(in, mdctx, key); if (!ret) ossl_ml_kem_key_reset(key); EVP_MD_CTX_free(mdctx); return ret; } /* Parse input as a new private key */ int ossl_ml_kem_parse_private_key(const uint8_t *in, size_t len, ML_KEM_KEY *key) { EVP_MD_CTX *mdctx = NULL; const ML_KEM_VINFO *vinfo; int ret = 0; /* Keys with key material are immutable */ if (key == NULL || ossl_ml_kem_have_pubkey(key) || ossl_ml_kem_have_dkenc(key)) return 0; vinfo = key->vinfo; if (len != vinfo->prvkey_bytes || (mdctx = EVP_MD_CTX_new()) == NULL) return 0; if (add_storage(OPENSSL_malloc(vinfo->prvalloc), 1, key)) ret = parse_prvkey(in, mdctx, key); if (!ret) ossl_ml_kem_key_reset(key); EVP_MD_CTX_free(mdctx); return ret; } /* * Generate a new keypair, either from the saved seed (when non-null), or from * the RNG. */ int ossl_ml_kem_genkey(uint8_t *pubenc, size_t publen, ML_KEM_KEY *key) { uint8_t seed[ML_KEM_SEED_BYTES]; EVP_MD_CTX *mdctx = NULL; const ML_KEM_VINFO *vinfo; int ret = 0; if (key == NULL || ossl_ml_kem_have_pubkey(key) || ossl_ml_kem_have_dkenc(key)) return 0; vinfo = key->vinfo; if (pubenc != NULL && publen != vinfo->pubkey_bytes) return 0; if (ossl_ml_kem_have_seed(key)) { if (!ossl_ml_kem_encode_seed(seed, sizeof(seed), key)) return 0; key->d = key->z = NULL; } else if (RAND_priv_bytes_ex(key->libctx, seed, sizeof(seed), key->vinfo->secbits) <= 0) { return 0; } if ((mdctx = EVP_MD_CTX_new()) == NULL) return 0; /* * Data derived from (d, z) defaults secret, and to avoid side-channel * leaks should not influence control flow. */ CONSTTIME_SECRET(seed, ML_KEM_SEED_BYTES); if (add_storage(OPENSSL_malloc(vinfo->prvalloc), 1, key)) ret = genkey(seed, mdctx, pubenc, key); OPENSSL_cleanse(seed, sizeof(seed)); /* Declassify secret inputs and derived outputs before returning control */ CONSTTIME_DECLASSIFY(seed, ML_KEM_SEED_BYTES); EVP_MD_CTX_free(mdctx); if (!ret) { ossl_ml_kem_key_reset(key); return 0; } /* The public components are already declassified */ CONSTTIME_DECLASSIFY(key->s, vinfo->rank * sizeof(scalar)); CONSTTIME_DECLASSIFY(key->z, 2 * ML_KEM_RANDOM_BYTES); return 1; } /* * FIPS 203, Section 6.2, Algorithm 17: ML-KEM.Encaps_internal * This is the deterministic version with randomness supplied externally. */ int ossl_ml_kem_encap_seed(uint8_t *ctext, size_t clen, uint8_t *shared_secret, size_t slen, const uint8_t *entropy, size_t elen, const ML_KEM_KEY *key) { const ML_KEM_VINFO *vinfo; EVP_MD_CTX *mdctx; int ret = 0; if (key == NULL || !ossl_ml_kem_have_pubkey(key)) return 0; vinfo = key->vinfo; if (ctext == NULL || clen != vinfo->ctext_bytes || shared_secret == NULL || slen != ML_KEM_SHARED_SECRET_BYTES || entropy == NULL || elen != ML_KEM_RANDOM_BYTES || (mdctx = EVP_MD_CTX_new()) == NULL) return 0; /* * Data derived from the encap entropy defaults secret, and to avoid * side-channel leaks should not influence control flow. */ CONSTTIME_SECRET(entropy, elen); /*- * This avoids the need to handle allocation failures for two (max 2KB * each) vectors, that are never retained on return from this function. * We stack-allocate these. */ # define case_encap_seed(bits) \ case EVP_PKEY_ML_KEM_##bits: \ { \ scalar tmp[2 * ML_KEM_##bits##_RANK]; \ \ ret = encap(ctext, shared_secret, entropy, tmp, mdctx, key); \ OPENSSL_cleanse((void *)tmp, sizeof(tmp)); \ break; \ } switch (vinfo->evp_type) { case_encap_seed(512); case_encap_seed(768); case_encap_seed(1024); } # undef case_encap_seed /* Declassify secret inputs and derived outputs before returning control */ CONSTTIME_DECLASSIFY(entropy, elen); CONSTTIME_DECLASSIFY(ctext, clen); CONSTTIME_DECLASSIFY(shared_secret, slen); EVP_MD_CTX_free(mdctx); return ret; } int ossl_ml_kem_encap_rand(uint8_t *ctext, size_t clen, uint8_t *shared_secret, size_t slen, const ML_KEM_KEY *key) { uint8_t r[ML_KEM_RANDOM_BYTES]; if (key == NULL) return 0; if (RAND_bytes_ex(key->libctx, r, ML_KEM_RANDOM_BYTES, key->vinfo->secbits) < 1) return 0; return ossl_ml_kem_encap_seed(ctext, clen, shared_secret, slen, r, sizeof(r), key); } int ossl_ml_kem_decap(uint8_t *shared_secret, size_t slen, const uint8_t *ctext, size_t clen, const ML_KEM_KEY *key) { const ML_KEM_VINFO *vinfo; EVP_MD_CTX *mdctx; int ret = 0; #if defined(OPENSSL_CONSTANT_TIME_VALIDATION) int classify_bytes; #endif /* Need a private key here */ if (!ossl_ml_kem_have_prvkey(key)) return 0; vinfo = key->vinfo; if (shared_secret == NULL || slen != ML_KEM_SHARED_SECRET_BYTES || ctext == NULL || clen != vinfo->ctext_bytes || (mdctx = EVP_MD_CTX_new()) == NULL) { (void)RAND_bytes_ex(key->libctx, shared_secret, ML_KEM_SHARED_SECRET_BYTES, vinfo->secbits); return 0; } #if defined(OPENSSL_CONSTANT_TIME_VALIDATION) /* * Data derived from |s| and |z| defaults secret, and to avoid side-channel * leaks should not influence control flow. */ classify_bytes = 2 * sizeof(scalar) + ML_KEM_RANDOM_BYTES; CONSTTIME_SECRET(key->s, classify_bytes); #endif /*- * This avoids the need to handle allocation failures for two (max 2KB * each) vectors and an encoded ciphertext (max 1568 bytes), that are never * retained on return from this function. * We stack-allocate these. */ # define case_decap(bits) \ case EVP_PKEY_ML_KEM_##bits: \ { \ uint8_t cbuf[CTEXT_BYTES(bits)]; \ scalar tmp[2 * ML_KEM_##bits##_RANK]; \ \ ret = decap(shared_secret, ctext, cbuf, tmp, mdctx, key); \ OPENSSL_cleanse((void *)tmp, sizeof(tmp)); \ break; \ } switch (vinfo->evp_type) { case_decap(512); case_decap(768); case_decap(1024); } /* Declassify secret inputs and derived outputs before returning control */ CONSTTIME_DECLASSIFY(key->s, classify_bytes); CONSTTIME_DECLASSIFY(shared_secret, slen); EVP_MD_CTX_free(mdctx); return ret; # undef case_decap } int ossl_ml_kem_pubkey_cmp(const ML_KEM_KEY *key1, const ML_KEM_KEY *key2) { /* * This handles any unexpected differences in the ML-KEM variant rank, * giving different key component structures, barring SHA3-256 hash * collisions, the keys are the same size. */ if (ossl_ml_kem_have_pubkey(key1) && ossl_ml_kem_have_pubkey(key2)) return memcmp(key1->pkhash, key2->pkhash, ML_KEM_PKHASH_BYTES) == 0; /* * No match if just one of the public keys is not available, otherwise both * are unavailable, and for now such keys are considered equal. */ - return (ossl_ml_kem_have_pubkey(key1) ^ ossl_ml_kem_have_pubkey(key2)); + return (!(ossl_ml_kem_have_pubkey(key1) ^ ossl_ml_kem_have_pubkey(key2))); } diff --git a/crypto/modes/siv128.c b/crypto/modes/siv128.c index 72526b849eaf..4e52d8eb8782 100644 --- a/crypto/modes/siv128.c +++ b/crypto/modes/siv128.c @@ -1,393 +1,396 @@ /* * Copyright 2018-2025 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 "internal/endian.h" #include "crypto/modes.h" #include "crypto/siv.h" #ifndef OPENSSL_NO_SIV __owur static ossl_inline uint32_t rotl8(uint32_t x) { return (x << 8) | (x >> 24); } __owur static ossl_inline uint32_t rotr8(uint32_t x) { return (x >> 8) | (x << 24); } __owur static ossl_inline uint64_t byteswap8(uint64_t x) { uint32_t high = (uint32_t)(x >> 32); uint32_t low = (uint32_t)x; high = (rotl8(high) & 0x00ff00ff) | (rotr8(high) & 0xff00ff00); low = (rotl8(low) & 0x00ff00ff) | (rotr8(low) & 0xff00ff00); return ((uint64_t)low) << 32 | (uint64_t)high; } __owur static ossl_inline uint64_t siv128_getword(SIV_BLOCK const *b, size_t i) { DECLARE_IS_ENDIAN; if (IS_LITTLE_ENDIAN) return byteswap8(b->word[i]); return b->word[i]; } static ossl_inline void siv128_putword(SIV_BLOCK *b, size_t i, uint64_t x) { DECLARE_IS_ENDIAN; if (IS_LITTLE_ENDIAN) b->word[i] = byteswap8(x); else b->word[i] = x; } static ossl_inline void siv128_xorblock(SIV_BLOCK *x, SIV_BLOCK const *y) { x->word[0] ^= y->word[0]; x->word[1] ^= y->word[1]; } /* * Doubles |b|, which is 16 bytes representing an element * of GF(2**128) modulo the irreducible polynomial * x**128 + x**7 + x**2 + x + 1. * Assumes two's-complement arithmetic */ static ossl_inline void siv128_dbl(SIV_BLOCK *b) { uint64_t high = siv128_getword(b, 0); uint64_t low = siv128_getword(b, 1); uint64_t high_carry = high & (((uint64_t)1) << 63); uint64_t low_carry = low & (((uint64_t)1) << 63); int64_t low_mask = -((int64_t)(high_carry >> 63)) & 0x87; uint64_t high_mask = low_carry >> 63; high = (high << 1) | high_mask; low = (low << 1) ^ (uint64_t)low_mask; siv128_putword(b, 0, high); siv128_putword(b, 1, low); } __owur static ossl_inline int siv128_do_s2v_p(SIV128_CONTEXT *ctx, SIV_BLOCK *out, unsigned char const* in, size_t len) { SIV_BLOCK t; size_t out_len = sizeof(out->byte); EVP_MAC_CTX *mac_ctx; int ret = 0; mac_ctx = EVP_MAC_CTX_dup(ctx->mac_ctx_init); if (mac_ctx == NULL) return 0; if (len >= SIV_LEN) { if (!EVP_MAC_update(mac_ctx, in, len - SIV_LEN)) goto err; memcpy(&t, in + (len-SIV_LEN), SIV_LEN); siv128_xorblock(&t, &ctx->d); if (!EVP_MAC_update(mac_ctx, t.byte, SIV_LEN)) goto err; } else { memset(&t, 0, sizeof(t)); memcpy(&t, in, len); t.byte[len] = 0x80; siv128_dbl(&ctx->d); siv128_xorblock(&t, &ctx->d); if (!EVP_MAC_update(mac_ctx, t.byte, SIV_LEN)) goto err; } if (!EVP_MAC_final(mac_ctx, out->byte, &out_len, sizeof(out->byte)) || out_len != SIV_LEN) goto err; ret = 1; err: EVP_MAC_CTX_free(mac_ctx); return ret; } __owur static ossl_inline int siv128_do_encrypt(EVP_CIPHER_CTX *ctx, unsigned char *out, unsigned char const *in, size_t len, SIV_BLOCK *icv) { int out_len = (int)len; if (!EVP_CipherInit_ex(ctx, NULL, NULL, NULL, icv->byte, 1)) return 0; return EVP_EncryptUpdate(ctx, out, &out_len, in, out_len); } /* * Create a new SIV128_CONTEXT */ SIV128_CONTEXT *ossl_siv128_new(const unsigned char *key, int klen, EVP_CIPHER *cbc, EVP_CIPHER *ctr, OSSL_LIB_CTX *libctx, const char *propq) { SIV128_CONTEXT *ctx; int ret; if ((ctx = OPENSSL_malloc(sizeof(*ctx))) != NULL) { ret = ossl_siv128_init(ctx, key, klen, cbc, ctr, libctx, propq); if (ret) return ctx; OPENSSL_free(ctx); } return NULL; } /* * Initialise an existing SIV128_CONTEXT */ int ossl_siv128_init(SIV128_CONTEXT *ctx, const unsigned char *key, int klen, const EVP_CIPHER *cbc, const EVP_CIPHER *ctr, OSSL_LIB_CTX *libctx, const char *propq) { static const unsigned char zero[SIV_LEN] = { 0 }; size_t out_len = SIV_LEN; EVP_MAC_CTX *mac_ctx = NULL; OSSL_PARAM params[3]; const char *cbc_name; if (ctx == NULL) return 0; memset(&ctx->d, 0, sizeof(ctx->d)); EVP_CIPHER_CTX_free(ctx->cipher_ctx); EVP_MAC_CTX_free(ctx->mac_ctx_init); EVP_MAC_free(ctx->mac); ctx->mac = NULL; ctx->cipher_ctx = NULL; ctx->mac_ctx_init = NULL; if (key == NULL || cbc == NULL || ctr == NULL) return 0; cbc_name = EVP_CIPHER_get0_name(cbc); params[0] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_CIPHER, (char *)cbc_name, 0); params[1] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, (void *)key, klen); params[2] = OSSL_PARAM_construct_end(); if ((ctx->cipher_ctx = EVP_CIPHER_CTX_new()) == NULL || (ctx->mac = EVP_MAC_fetch(libctx, OSSL_MAC_NAME_CMAC, propq)) == NULL || (ctx->mac_ctx_init = EVP_MAC_CTX_new(ctx->mac)) == NULL || !EVP_MAC_CTX_set_params(ctx->mac_ctx_init, params) || !EVP_EncryptInit_ex(ctx->cipher_ctx, ctr, NULL, key + klen, NULL) || (mac_ctx = EVP_MAC_CTX_dup(ctx->mac_ctx_init)) == NULL || !EVP_MAC_update(mac_ctx, zero, sizeof(zero)) || !EVP_MAC_final(mac_ctx, ctx->d.byte, &out_len, sizeof(ctx->d.byte))) { EVP_CIPHER_CTX_free(ctx->cipher_ctx); + ctx->cipher_ctx = NULL; EVP_MAC_CTX_free(ctx->mac_ctx_init); + ctx->mac_ctx_init = NULL; EVP_MAC_CTX_free(mac_ctx); EVP_MAC_free(ctx->mac); + ctx->mac = NULL; return 0; } EVP_MAC_CTX_free(mac_ctx); ctx->final_ret = -1; ctx->crypto_ok = 1; return 1; } /* * Copy an SIV128_CONTEXT object */ int ossl_siv128_copy_ctx(SIV128_CONTEXT *dest, SIV128_CONTEXT *src) { memcpy(&dest->d, &src->d, sizeof(src->d)); if (dest->cipher_ctx == NULL) { dest->cipher_ctx = EVP_CIPHER_CTX_new(); if (dest->cipher_ctx == NULL) return 0; } if (!EVP_CIPHER_CTX_copy(dest->cipher_ctx, src->cipher_ctx)) return 0; EVP_MAC_CTX_free(dest->mac_ctx_init); dest->mac_ctx_init = EVP_MAC_CTX_dup(src->mac_ctx_init); if (dest->mac_ctx_init == NULL) return 0; dest->mac = src->mac; if (dest->mac != NULL) EVP_MAC_up_ref(dest->mac); return 1; } /* * Provide any AAD. This can be called multiple times. * Per RFC5297, the last piece of associated data * is the nonce, but it's not treated special */ int ossl_siv128_aad(SIV128_CONTEXT *ctx, const unsigned char *aad, size_t len) { SIV_BLOCK mac_out; size_t out_len = SIV_LEN; EVP_MAC_CTX *mac_ctx; siv128_dbl(&ctx->d); if ((mac_ctx = EVP_MAC_CTX_dup(ctx->mac_ctx_init)) == NULL || !EVP_MAC_update(mac_ctx, aad, len) || !EVP_MAC_final(mac_ctx, mac_out.byte, &out_len, sizeof(mac_out.byte)) || out_len != SIV_LEN) { EVP_MAC_CTX_free(mac_ctx); return 0; } EVP_MAC_CTX_free(mac_ctx); siv128_xorblock(&ctx->d, &mac_out); return 1; } /* * Provide any data to be encrypted. This can be called once. */ int ossl_siv128_encrypt(SIV128_CONTEXT *ctx, const unsigned char *in, unsigned char *out, size_t len) { SIV_BLOCK q; /* can only do one crypto operation */ if (ctx->crypto_ok == 0) return 0; ctx->crypto_ok--; if (!siv128_do_s2v_p(ctx, &q, in, len)) return 0; memcpy(ctx->tag.byte, &q, SIV_LEN); q.byte[8] &= 0x7f; q.byte[12] &= 0x7f; if (!siv128_do_encrypt(ctx->cipher_ctx, out, in, len, &q)) return 0; ctx->final_ret = 0; return 1; } /* * Provide any data to be decrypted. This can be called once. */ int ossl_siv128_decrypt(SIV128_CONTEXT *ctx, const unsigned char *in, unsigned char *out, size_t len) { unsigned char* p; SIV_BLOCK t, q; int i; /* can only do one crypto operation */ if (ctx->crypto_ok == 0) return 0; ctx->crypto_ok--; memcpy(&q, ctx->tag.byte, SIV_LEN); q.byte[8] &= 0x7f; q.byte[12] &= 0x7f; if (!siv128_do_encrypt(ctx->cipher_ctx, out, in, len, &q) || !siv128_do_s2v_p(ctx, &t, out, len)) return 0; p = ctx->tag.byte; for (i = 0; i < SIV_LEN; i++) t.byte[i] ^= p[i]; if ((t.word[0] | t.word[1]) != 0) { OPENSSL_cleanse(out, len); return 0; } ctx->final_ret = 0; return 1; } /* * Return the already calculated final result. */ int ossl_siv128_finish(SIV128_CONTEXT *ctx) { return ctx->final_ret; } /* * Set the tag */ int ossl_siv128_set_tag(SIV128_CONTEXT *ctx, const unsigned char *tag, size_t len) { if (len != SIV_LEN) return 0; /* Copy the tag from the supplied buffer */ memcpy(ctx->tag.byte, tag, len); return 1; } /* * Retrieve the calculated tag */ int ossl_siv128_get_tag(SIV128_CONTEXT *ctx, unsigned char *tag, size_t len) { if (len != SIV_LEN) return 0; /* Copy the tag into the supplied buffer */ memcpy(tag, ctx->tag.byte, len); return 1; } /* * Release all resources */ int ossl_siv128_cleanup(SIV128_CONTEXT *ctx) { if (ctx != NULL) { EVP_CIPHER_CTX_free(ctx->cipher_ctx); ctx->cipher_ctx = NULL; EVP_MAC_CTX_free(ctx->mac_ctx_init); ctx->mac_ctx_init = NULL; EVP_MAC_free(ctx->mac); ctx->mac = NULL; OPENSSL_cleanse(&ctx->d, sizeof(ctx->d)); OPENSSL_cleanse(&ctx->tag, sizeof(ctx->tag)); ctx->final_ret = -1; ctx->crypto_ok = 1; } return 1; } int ossl_siv128_speed(SIV128_CONTEXT *ctx, int arg) { ctx->crypto_ok = (arg == 1) ? -1 : 1; return 1; } #endif /* OPENSSL_NO_SIV */ diff --git a/crypto/property/property_parse.c b/crypto/property/property_parse.c index 3a67754224f0..23963c89bc46 100644 --- a/crypto/property/property_parse.c +++ b/crypto/property/property_parse.c @@ -1,762 +1,762 @@ /* * Copyright 2019-2025 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/propertyerr.h" #include "internal/property.h" #include "internal/numbers.h" #include "crypto/ctype.h" #include "internal/nelem.h" #include "property_local.h" #include "internal/e_os.h" DEFINE_STACK_OF(OSSL_PROPERTY_DEFINITION) static const char *skip_space(const char *s) { while (ossl_isspace(*s)) s++; return s; } static int match_ch(const char *t[], char m) { const char *s = *t; if (*s == m) { *t = skip_space(s + 1); return 1; } return 0; } #define MATCH(s, m) match(s, m, sizeof(m) - 1) static int match(const char *t[], const char m[], size_t m_len) { const char *s = *t; if (OPENSSL_strncasecmp(s, m, m_len) == 0) { *t = skip_space(s + m_len); return 1; } return 0; } static int parse_name(OSSL_LIB_CTX *ctx, const char *t[], int create, OSSL_PROPERTY_IDX *idx) { char name[100]; int err = 0; size_t i = 0; const char *s = *t; int user_name = 0; for (;;) { if (!ossl_isalpha(*s)) { ERR_raise_data(ERR_LIB_PROP, PROP_R_NOT_AN_IDENTIFIER, "HERE-->%s", *t); return 0; } do { if (i < sizeof(name) - 1) name[i++] = ossl_tolower(*s); else err = 1; } while (*++s == '_' || ossl_isalnum(*s)); if (*s != '.') break; user_name = 1; if (i < sizeof(name) - 1) name[i++] = *s; else err = 1; s++; } name[i] = '\0'; if (err) { ERR_raise_data(ERR_LIB_PROP, PROP_R_NAME_TOO_LONG, "HERE-->%s", *t); return 0; } *t = skip_space(s); *idx = ossl_property_name(ctx, name, user_name && create); return 1; } static int parse_number(const char *t[], OSSL_PROPERTY_DEFINITION *res) { const char *s = *t; int64_t v = 0; do { if (!ossl_isdigit(*s)) { ERR_raise_data(ERR_LIB_PROP, PROP_R_NOT_A_DECIMAL_DIGIT, "HERE-->%s", *t); return 0; } /* overflow check */ if (v > ((INT64_MAX - (*s - '0')) / 10)) { ERR_raise_data(ERR_LIB_PROP, PROP_R_PARSE_FAILED, "Property %s overflows", *t); return 0; } v = v * 10 + (*s++ - '0'); } while (ossl_isdigit(*s)); if (!ossl_isspace(*s) && *s != '\0' && *s != ',') { ERR_raise_data(ERR_LIB_PROP, PROP_R_NOT_A_DECIMAL_DIGIT, "HERE-->%s", *t); return 0; } *t = skip_space(s); res->type = OSSL_PROPERTY_TYPE_NUMBER; res->v.int_val = v; return 1; } static int parse_hex(const char *t[], OSSL_PROPERTY_DEFINITION *res) { const char *s = *t; int64_t v = 0; int sval; do { if (ossl_isdigit(*s)) { sval = *s - '0'; } else if (ossl_isxdigit(*s)) { sval = ossl_tolower(*s) - 'a' + 10; } else { ERR_raise_data(ERR_LIB_PROP, PROP_R_NOT_AN_HEXADECIMAL_DIGIT, "%s", *t); return 0; } if (v > ((INT64_MAX - sval) / 16)) { ERR_raise_data(ERR_LIB_PROP, PROP_R_PARSE_FAILED, "Property %s overflows", *t); return 0; } v <<= 4; v += sval; } while (ossl_isxdigit(*++s)); if (!ossl_isspace(*s) && *s != '\0' && *s != ',') { ERR_raise_data(ERR_LIB_PROP, PROP_R_NOT_AN_HEXADECIMAL_DIGIT, "HERE-->%s", *t); return 0; } *t = skip_space(s); res->type = OSSL_PROPERTY_TYPE_NUMBER; res->v.int_val = v; return 1; } static int parse_oct(const char *t[], OSSL_PROPERTY_DEFINITION *res) { const char *s = *t; int64_t v = 0; do { if (*s == '9' || *s == '8' || !ossl_isdigit(*s)) { ERR_raise_data(ERR_LIB_PROP, PROP_R_NOT_AN_OCTAL_DIGIT, "HERE-->%s", *t); return 0; } if (v > ((INT64_MAX - (*s - '0')) / 8)) { ERR_raise_data(ERR_LIB_PROP, PROP_R_PARSE_FAILED, "Property %s overflows", *t); return 0; } v = (v << 3) + (*s - '0'); } while (ossl_isdigit(*++s) && *s != '9' && *s != '8'); if (!ossl_isspace(*s) && *s != '\0' && *s != ',') { ERR_raise_data(ERR_LIB_PROP, PROP_R_NOT_AN_OCTAL_DIGIT, "HERE-->%s", *t); return 0; } *t = skip_space(s); res->type = OSSL_PROPERTY_TYPE_NUMBER; res->v.int_val = v; return 1; } static int parse_string(OSSL_LIB_CTX *ctx, const char *t[], char delim, OSSL_PROPERTY_DEFINITION *res, const int create) { char v[1000]; const char *s = *t; size_t i = 0; int err = 0; while (*s != '\0' && *s != delim) { if (i < sizeof(v) - 1) v[i++] = *s; else err = 1; s++; } if (*s == '\0') { ERR_raise_data(ERR_LIB_PROP, PROP_R_NO_MATCHING_STRING_DELIMITER, "HERE-->%c%s", delim, *t); return 0; } v[i] = '\0'; if (err) { ERR_raise_data(ERR_LIB_PROP, PROP_R_STRING_TOO_LONG, "HERE-->%s", *t); } else { res->v.str_val = ossl_property_value(ctx, v, create); } *t = skip_space(s + 1); res->type = OSSL_PROPERTY_TYPE_STRING; return !err; } static int parse_unquoted(OSSL_LIB_CTX *ctx, const char *t[], OSSL_PROPERTY_DEFINITION *res, const int create) { char v[1000]; const char *s = *t; size_t i = 0; int err = 0; if (*s == '\0' || *s == ',') return 0; while (ossl_isprint(*s) && !ossl_isspace(*s) && *s != ',') { if (i < sizeof(v) - 1) v[i++] = ossl_tolower(*s); else err = 1; s++; } if (!ossl_isspace(*s) && *s != '\0' && *s != ',') { ERR_raise_data(ERR_LIB_PROP, PROP_R_NOT_AN_ASCII_CHARACTER, "HERE-->%s", s); return 0; } v[i] = 0; if (err) ERR_raise_data(ERR_LIB_PROP, PROP_R_STRING_TOO_LONG, "HERE-->%s", *t); else if ((res->v.str_val = ossl_property_value(ctx, v, create)) == 0) err = 1; *t = skip_space(s); res->type = OSSL_PROPERTY_TYPE_STRING; return !err; } static int parse_value(OSSL_LIB_CTX *ctx, const char *t[], OSSL_PROPERTY_DEFINITION *res, int create) { const char *s = *t; int r = 0; if (*s == '"' || *s == '\'') { s++; r = parse_string(ctx, &s, s[-1], res, create); } else if (*s == '+') { s++; r = parse_number(&s, res); } else if (*s == '-') { s++; r = parse_number(&s, res); res->v.int_val = -res->v.int_val; } else if (*s == '0' && s[1] == 'x') { s += 2; r = parse_hex(&s, res); } else if (*s == '0' && ossl_isdigit(s[1])) { s++; r = parse_oct(&s, res); } else if (ossl_isdigit(*s)) { return parse_number(t, res); } else if (ossl_isalpha(*s)) return parse_unquoted(ctx, t, res, create); if (r) *t = s; return r; } static int pd_compare(const OSSL_PROPERTY_DEFINITION *const *p1, const OSSL_PROPERTY_DEFINITION *const *p2) { const OSSL_PROPERTY_DEFINITION *pd1 = *p1; const OSSL_PROPERTY_DEFINITION *pd2 = *p2; if (pd1->name_idx < pd2->name_idx) return -1; if (pd1->name_idx > pd2->name_idx) return 1; return 0; } static void pd_free(OSSL_PROPERTY_DEFINITION *pd) { OPENSSL_free(pd); } /* * Convert a stack of property definitions and queries into a fixed array. * The items are sorted for efficient query. The stack is not freed. * This function also checks for duplicated names and returns an error if * any exist. */ static OSSL_PROPERTY_LIST * stack_to_property_list(OSSL_LIB_CTX *ctx, STACK_OF(OSSL_PROPERTY_DEFINITION) *sk) { const int n = sk_OSSL_PROPERTY_DEFINITION_num(sk); OSSL_PROPERTY_LIST *r; OSSL_PROPERTY_IDX prev_name_idx = 0; int i; r = OPENSSL_malloc(sizeof(*r) + (n <= 0 ? 0 : n - 1) * sizeof(r->properties[0])); if (r != NULL) { sk_OSSL_PROPERTY_DEFINITION_sort(sk); r->has_optional = 0; for (i = 0; i < n; i++) { r->properties[i] = *sk_OSSL_PROPERTY_DEFINITION_value(sk, i); r->has_optional |= r->properties[i].optional; /* Check for duplicated names */ if (i > 0 && r->properties[i].name_idx == prev_name_idx) { OPENSSL_free(r); ERR_raise_data(ERR_LIB_PROP, PROP_R_PARSE_FAILED, "Duplicated name `%s'", ossl_property_name_str(ctx, prev_name_idx)); return NULL; } prev_name_idx = r->properties[i].name_idx; } r->num_properties = n; } return r; } OSSL_PROPERTY_LIST *ossl_parse_property(OSSL_LIB_CTX *ctx, const char *defn) { OSSL_PROPERTY_DEFINITION *prop = NULL; OSSL_PROPERTY_LIST *res = NULL; STACK_OF(OSSL_PROPERTY_DEFINITION) *sk; const char *s = defn; int done; if (s == NULL || (sk = sk_OSSL_PROPERTY_DEFINITION_new(&pd_compare)) == NULL) return NULL; s = skip_space(s); done = *s == '\0'; while (!done) { const char *start = s; prop = OPENSSL_malloc(sizeof(*prop)); if (prop == NULL) goto err; memset(&prop->v, 0, sizeof(prop->v)); prop->optional = 0; if (!parse_name(ctx, &s, 1, &prop->name_idx)) goto err; prop->oper = OSSL_PROPERTY_OPER_EQ; if (prop->name_idx == 0) { ERR_raise_data(ERR_LIB_PROP, PROP_R_PARSE_FAILED, "Unknown name HERE-->%s", start); goto err; } if (match_ch(&s, '=')) { if (!parse_value(ctx, &s, prop, 1)) { ERR_raise_data(ERR_LIB_PROP, PROP_R_NO_VALUE, "HERE-->%s", start); goto err; } } else { /* A name alone means a true Boolean */ prop->type = OSSL_PROPERTY_TYPE_STRING; prop->v.str_val = OSSL_PROPERTY_TRUE; } if (!sk_OSSL_PROPERTY_DEFINITION_push(sk, prop)) goto err; prop = NULL; done = !match_ch(&s, ','); } if (*s != '\0') { ERR_raise_data(ERR_LIB_PROP, PROP_R_TRAILING_CHARACTERS, "HERE-->%s", s); goto err; } res = stack_to_property_list(ctx, sk); err: OPENSSL_free(prop); sk_OSSL_PROPERTY_DEFINITION_pop_free(sk, &pd_free); return res; } OSSL_PROPERTY_LIST *ossl_parse_query(OSSL_LIB_CTX *ctx, const char *s, int create_values) { STACK_OF(OSSL_PROPERTY_DEFINITION) *sk; OSSL_PROPERTY_LIST *res = NULL; OSSL_PROPERTY_DEFINITION *prop = NULL; int done; if (s == NULL || (sk = sk_OSSL_PROPERTY_DEFINITION_new(&pd_compare)) == NULL) return NULL; s = skip_space(s); done = *s == '\0'; while (!done) { prop = OPENSSL_malloc(sizeof(*prop)); if (prop == NULL) goto err; memset(&prop->v, 0, sizeof(prop->v)); if (match_ch(&s, '-')) { prop->oper = OSSL_PROPERTY_OVERRIDE; prop->optional = 0; if (!parse_name(ctx, &s, 1, &prop->name_idx)) goto err; goto skip_value; } prop->optional = match_ch(&s, '?'); if (!parse_name(ctx, &s, 1, &prop->name_idx)) goto err; if (match_ch(&s, '=')) { prop->oper = OSSL_PROPERTY_OPER_EQ; } else if (MATCH(&s, "!=")) { prop->oper = OSSL_PROPERTY_OPER_NE; } else { /* A name alone is a Boolean comparison for true */ prop->oper = OSSL_PROPERTY_OPER_EQ; prop->type = OSSL_PROPERTY_TYPE_STRING; prop->v.str_val = OSSL_PROPERTY_TRUE; goto skip_value; } if (!parse_value(ctx, &s, prop, create_values)) prop->type = OSSL_PROPERTY_TYPE_VALUE_UNDEFINED; skip_value: if (!sk_OSSL_PROPERTY_DEFINITION_push(sk, prop)) goto err; prop = NULL; done = !match_ch(&s, ','); } if (*s != '\0') { ERR_raise_data(ERR_LIB_PROP, PROP_R_TRAILING_CHARACTERS, "HERE-->%s", s); goto err; } res = stack_to_property_list(ctx, sk); err: OPENSSL_free(prop); sk_OSSL_PROPERTY_DEFINITION_pop_free(sk, &pd_free); return res; } /* * Compare a query against a definition. * Return the number of clauses matched or -1 if a mandatory clause is false. */ int ossl_property_match_count(const OSSL_PROPERTY_LIST *query, const OSSL_PROPERTY_LIST *defn) { const OSSL_PROPERTY_DEFINITION *const q = query->properties; const OSSL_PROPERTY_DEFINITION *const d = defn->properties; int i = 0, j = 0, matches = 0; OSSL_PROPERTY_OPER oper; while (i < query->num_properties) { if ((oper = q[i].oper) == OSSL_PROPERTY_OVERRIDE) { i++; continue; } if (j < defn->num_properties) { if (q[i].name_idx > d[j].name_idx) { /* skip defn, not in query */ j++; continue; } if (q[i].name_idx == d[j].name_idx) { /* both in defn and query */ const int eq = q[i].type == d[j].type && memcmp(&q[i].v, &d[j].v, sizeof(q[i].v)) == 0; if ((eq && oper == OSSL_PROPERTY_OPER_EQ) || (!eq && oper == OSSL_PROPERTY_OPER_NE)) matches++; else if (!q[i].optional) return -1; i++; j++; continue; } } /* * Handle the cases of a missing value and a query with no corresponding * definition. The former fails for any comparison except inequality, * the latter is treated as a comparison against the Boolean false. */ if (q[i].type == OSSL_PROPERTY_TYPE_VALUE_UNDEFINED) { if (oper == OSSL_PROPERTY_OPER_NE) matches++; else if (!q[i].optional) return -1; } else if (q[i].type != OSSL_PROPERTY_TYPE_STRING || (oper == OSSL_PROPERTY_OPER_EQ && q[i].v.str_val != OSSL_PROPERTY_FALSE) || (oper == OSSL_PROPERTY_OPER_NE && q[i].v.str_val == OSSL_PROPERTY_FALSE)) { if (!q[i].optional) return -1; } else { matches++; } i++; } return matches; } void ossl_property_free(OSSL_PROPERTY_LIST *p) { OPENSSL_free(p); } /* * Merge two property lists. * If there is a common name, the one from the first list is used. */ OSSL_PROPERTY_LIST *ossl_property_merge(const OSSL_PROPERTY_LIST *a, const OSSL_PROPERTY_LIST *b) { const OSSL_PROPERTY_DEFINITION *const ap = a->properties; const OSSL_PROPERTY_DEFINITION *const bp = b->properties; const OSSL_PROPERTY_DEFINITION *copy; OSSL_PROPERTY_LIST *r; int i, j, n; const int t = a->num_properties + b->num_properties; r = OPENSSL_malloc(sizeof(*r) + (t == 0 ? 0 : t - 1) * sizeof(r->properties[0])); if (r == NULL) return NULL; r->has_optional = 0; for (i = j = n = 0; i < a->num_properties || j < b->num_properties; n++) { if (i >= a->num_properties) { copy = &bp[j++]; } else if (j >= b->num_properties) { copy = &ap[i++]; } else if (ap[i].name_idx <= bp[j].name_idx) { if (ap[i].name_idx == bp[j].name_idx) j++; copy = &ap[i++]; } else { copy = &bp[j++]; } memcpy(r->properties + n, copy, sizeof(r->properties[0])); r->has_optional |= copy->optional; } r->num_properties = n; return r; } int ossl_property_parse_init(OSSL_LIB_CTX *ctx) { static const char *const predefined_names[] = { "provider", /* Name of provider (default, legacy, fips) */ "version", /* Version number of this provider */ "fips", /* FIPS validated or FIPS supporting algorithm */ "output", /* Output type for encoders */ "input", /* Input type for decoders */ "structure", /* Structure name for encoders and decoders */ }; size_t i; for (i = 0; i < OSSL_NELEM(predefined_names); i++) if (ossl_property_name(ctx, predefined_names[i], 1) == 0) goto err; /* * Pre-populate the two Boolean values. We must do them before any other * values and in this order so that we get the same index as the global * OSSL_PROPERTY_TRUE and OSSL_PROPERTY_FALSE values */ if ((ossl_property_value(ctx, "yes", 1) != OSSL_PROPERTY_TRUE) || (ossl_property_value(ctx, "no", 1) != OSSL_PROPERTY_FALSE)) goto err; return 1; err: return 0; } static void put_char(char ch, char **buf, size_t *remain, size_t *needed) { if (*remain == 0) { ++*needed; return; } if (*remain == 1) **buf = '\0'; else **buf = ch; ++*buf; ++*needed; --*remain; } static void put_str(const char *str, char **buf, size_t *remain, size_t *needed) { size_t olen, len, i; char quote = '\0'; int quotes; len = olen = strlen(str); *needed += len; /* * Check to see if we need quotes or not. * Characters that are legal in a PropertyName don't need quoting. * We simply assume all others require quotes. */ for (i = 0; i < len; i++) if (!ossl_isalnum(str[i]) && str[i] != '.' && str[i] != '_') { /* Default to single quotes ... */ if (quote == '\0') quote = '\''; /* ... but use double quotes if a single is present */ if (str[i] == '\'') quote = '"'; } quotes = quote != '\0'; - if (*remain == 0) { + if (*remain <= (size_t)quotes) { *needed += 2 * quotes; return; } if (quotes) put_char(quote, buf, remain, needed); if (*remain < len + 1 + quotes) len = *remain - 1; if (len > 0) { memcpy(*buf, str, len); *buf += len; *remain -= len; } if (quotes) put_char(quote, buf, remain, needed); if (len < olen && *remain == 1) { **buf = '\0'; ++*buf; --*remain; } } static void put_num(int64_t val, char **buf, size_t *remain, size_t *needed) { int64_t tmpval = val; size_t len = 1; if (tmpval < 0) { len++; tmpval = -tmpval; } for (; tmpval > 9; len++, tmpval /= 10); *needed += len; if (*remain == 0) return; BIO_snprintf(*buf, *remain, "%lld", (long long int)val); if (*remain < len) { *buf += *remain; *remain = 0; } else { *buf += len; *remain -= len; } } size_t ossl_property_list_to_string(OSSL_LIB_CTX *ctx, const OSSL_PROPERTY_LIST *list, char *buf, size_t bufsize) { int i; const OSSL_PROPERTY_DEFINITION *prop = NULL; size_t needed = 0; const char *val; if (list == NULL) { if (bufsize > 0) *buf = '\0'; return 1; } if (list->num_properties != 0) prop = &list->properties[list->num_properties - 1]; for (i = 0; i < list->num_properties; i++, prop--) { /* Skip invalid names */ if (prop->name_idx == 0) continue; if (needed > 0) put_char(',', &buf, &bufsize, &needed); if (prop->optional) put_char('?', &buf, &bufsize, &needed); else if (prop->oper == OSSL_PROPERTY_OVERRIDE) put_char('-', &buf, &bufsize, &needed); val = ossl_property_name_str(ctx, prop->name_idx); if (val == NULL) return 0; put_str(val, &buf, &bufsize, &needed); switch (prop->oper) { case OSSL_PROPERTY_OPER_NE: put_char('!', &buf, &bufsize, &needed); /* fall through */ case OSSL_PROPERTY_OPER_EQ: put_char('=', &buf, &bufsize, &needed); /* put value */ switch (prop->type) { case OSSL_PROPERTY_TYPE_STRING: val = ossl_property_value_str(ctx, prop->v.str_val); if (val == NULL) return 0; put_str(val, &buf, &bufsize, &needed); break; case OSSL_PROPERTY_TYPE_NUMBER: put_num(prop->v.int_val, &buf, &bufsize, &needed); break; default: return 0; } break; default: /* do nothing */ break; } } put_char('\0', &buf, &bufsize, &needed); return needed; } diff --git a/crypto/rsa/rsa_gen.c b/crypto/rsa/rsa_gen.c index 033f66714add..f76bb7748369 100644 --- a/crypto/rsa/rsa_gen.c +++ b/crypto/rsa/rsa_gen.c @@ -1,751 +1,736 @@ /* * Copyright 1995-2025 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 */ /* * NB: these functions have been "upgraded", the deprecated versions (which * are compatibility wrappers using these functions) are in rsa_depr.c. - * Geoff */ /* * RSA 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 #include #include "prov/providercommon.h" #include "rsa_local.h" static int rsa_keygen_pairwise_test(RSA *rsa, OSSL_CALLBACK *cb, void *cbarg); static int rsa_keygen(OSSL_LIB_CTX *libctx, RSA *rsa, int bits, int primes, BIGNUM *e_value, BN_GENCB *cb, int pairwise_test); /* * NB: this wrapper would normally be placed in rsa_lib.c and the static * implementation would probably be in rsa_eay.c. Nonetheless, is kept here * so that we don't introduce a new linker dependency. Eg. any application * that wasn't previously linking object code related to key-generation won't * have to now just because key-generation is part of RSA_METHOD. */ int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb) { if (rsa->meth->rsa_keygen != NULL) return rsa->meth->rsa_keygen(rsa, bits, e_value, cb); return RSA_generate_multi_prime_key(rsa, bits, RSA_DEFAULT_PRIME_NUM, e_value, cb); } int RSA_generate_multi_prime_key(RSA *rsa, int bits, int primes, BIGNUM *e_value, BN_GENCB *cb) { #ifndef FIPS_MODULE /* multi-prime is only supported with the builtin key generation */ if (rsa->meth->rsa_multi_prime_keygen != NULL) { return rsa->meth->rsa_multi_prime_keygen(rsa, bits, primes, e_value, cb); } else if (rsa->meth->rsa_keygen != NULL) { /* * However, if rsa->meth implements only rsa_keygen, then we * have to honour it in 2-prime case and assume that it wouldn't * know what to do with multi-prime key generated by builtin * subroutine... */ if (primes == 2) return rsa->meth->rsa_keygen(rsa, bits, e_value, cb); else return 0; } #endif /* FIPS_MODULE */ return rsa_keygen(rsa->libctx, rsa, bits, primes, e_value, cb, 0); } DEFINE_STACK_OF(BIGNUM) /* * Given input values, q, p, n, d and e, derive the exponents * and coefficients for each prime in this key, placing the result * on their respective exps and coeffs stacks */ #ifndef FIPS_MODULE int ossl_rsa_multiprime_derive(RSA *rsa, int bits, int primes, BIGNUM *e_value, STACK_OF(BIGNUM) *factors, STACK_OF(BIGNUM) *exps, STACK_OF(BIGNUM) *coeffs) { STACK_OF(BIGNUM) *pplist = NULL, *pdlist = NULL; BIGNUM *factor = NULL, *newpp = NULL, *newpd = NULL; BIGNUM *dval = NULL, *newexp = NULL, *newcoeff = NULL; BIGNUM *p = NULL, *q = NULL; BIGNUM *dmp1 = NULL, *dmq1 = NULL, *iqmp = NULL; BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL; BN_CTX *ctx = NULL; BIGNUM *tmp = NULL; int i; int ret = 0; ctx = BN_CTX_new_ex(rsa->libctx); if (ctx == NULL) goto err; BN_CTX_start(ctx); pplist = sk_BIGNUM_new_null(); if (pplist == NULL) goto err; pdlist = sk_BIGNUM_new_null(); if (pdlist == NULL) goto err; r0 = BN_CTX_get(ctx); r1 = BN_CTX_get(ctx); r2 = BN_CTX_get(ctx); if (r2 == NULL) goto err; BN_set_flags(r0, BN_FLG_CONSTTIME); BN_set_flags(r1, BN_FLG_CONSTTIME); BN_set_flags(r2, BN_FLG_CONSTTIME); if (BN_copy(r1, rsa->n) == NULL) goto err; p = sk_BIGNUM_value(factors, 0); q = sk_BIGNUM_value(factors, 1); /* Build list of partial products of primes */ for (i = 0; i < sk_BIGNUM_num(factors); i++) { switch (i) { case 0: /* our first prime, p */ if (!BN_sub(r2, p, BN_value_one())) goto err; BN_set_flags(r2, BN_FLG_CONSTTIME); if (BN_mod_inverse(r1, r2, rsa->e, ctx) == NULL) goto err; break; case 1: /* second prime q */ if (!BN_mul(r1, p, q, ctx)) goto err; tmp = BN_dup(r1); if (tmp == NULL) goto err; if (!sk_BIGNUM_insert(pplist, tmp, sk_BIGNUM_num(pplist))) goto err; tmp = NULL; break; default: factor = sk_BIGNUM_value(factors, i); /* all other primes */ if (!BN_mul(r1, r1, factor, ctx)) goto err; tmp = BN_dup(r1); if (tmp == NULL) goto err; if (!sk_BIGNUM_insert(pplist, tmp, sk_BIGNUM_num(pplist))) goto err; tmp = NULL; break; } } /* build list of relative d values */ /* p -1 */ if (!BN_sub(r1, p, BN_value_one())) goto err; if (!BN_sub(r2, q, BN_value_one())) goto err; if (!BN_mul(r0, r1, r2, ctx)) goto err; for (i = 2; i < sk_BIGNUM_num(factors); i++) { factor = sk_BIGNUM_value(factors, i); dval = BN_new(); if (dval == NULL) goto err; BN_set_flags(dval, BN_FLG_CONSTTIME); if (!BN_sub(dval, factor, BN_value_one())) goto err; if (!BN_mul(r0, r0, dval, ctx)) goto err; if (!sk_BIGNUM_insert(pdlist, dval, sk_BIGNUM_num(pdlist))) goto err; dval = NULL; } /* Calculate dmp1, dmq1 and additional exponents */ dmp1 = BN_secure_new(); if (dmp1 == NULL) goto err; dmq1 = BN_secure_new(); if (dmq1 == NULL) goto err; if (!BN_mod(dmp1, rsa->d, r1, ctx)) goto err; if (!sk_BIGNUM_insert(exps, dmp1, sk_BIGNUM_num(exps))) goto err; dmp1 = NULL; if (!BN_mod(dmq1, rsa->d, r2, ctx)) goto err; if (!sk_BIGNUM_insert(exps, dmq1, sk_BIGNUM_num(exps))) goto err; dmq1 = NULL; for (i = 2; i < sk_BIGNUM_num(factors); i++) { newpd = sk_BIGNUM_value(pdlist, i - 2); newexp = BN_new(); if (newexp == NULL) goto err; if (!BN_mod(newexp, rsa->d, newpd, ctx)) goto err; if (!sk_BIGNUM_insert(exps, newexp, sk_BIGNUM_num(exps))) goto err; newexp = NULL; } /* Calculate iqmp and additional coefficients */ iqmp = BN_new(); if (iqmp == NULL) goto err; if (BN_mod_inverse(iqmp, sk_BIGNUM_value(factors, 1), sk_BIGNUM_value(factors, 0), ctx) == NULL) goto err; if (!sk_BIGNUM_insert(coeffs, iqmp, sk_BIGNUM_num(coeffs))) goto err; iqmp = NULL; for (i = 2; i < sk_BIGNUM_num(factors); i++) { newpp = sk_BIGNUM_value(pplist, i - 2); newcoeff = BN_new(); if (newcoeff == NULL) goto err; if (BN_mod_inverse(newcoeff, newpp, sk_BIGNUM_value(factors, i), ctx) == NULL) goto err; if (!sk_BIGNUM_insert(coeffs, newcoeff, sk_BIGNUM_num(coeffs))) goto err; newcoeff = NULL; } ret = 1; err: BN_free(newcoeff); BN_free(newexp); BN_free(dval); BN_free(tmp); sk_BIGNUM_pop_free(pplist, BN_free); sk_BIGNUM_pop_free(pdlist, BN_free); BN_CTX_end(ctx); BN_CTX_free(ctx); BN_clear_free(dmp1); BN_clear_free(dmq1); BN_clear_free(iqmp); return ret; } static int rsa_multiprime_keygen(RSA *rsa, int bits, int primes, BIGNUM *e_value, BN_GENCB *cb) { BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *tmp, *tmp2, *prime; int n = 0, bitsr[RSA_MAX_PRIME_NUM], bitse = 0; int i = 0, quo = 0, rmd = 0, adj = 0, retries = 0; RSA_PRIME_INFO *pinfo = NULL; STACK_OF(RSA_PRIME_INFO) *prime_infos = NULL; STACK_OF(BIGNUM) *factors = NULL; STACK_OF(BIGNUM) *exps = NULL; STACK_OF(BIGNUM) *coeffs = NULL; BN_CTX *ctx = NULL; BN_ULONG bitst = 0; unsigned long error = 0; int ok = -1; if (bits < RSA_MIN_MODULUS_BITS) { ERR_raise(ERR_LIB_RSA, RSA_R_KEY_SIZE_TOO_SMALL); return 0; } if (e_value == NULL) { ERR_raise(ERR_LIB_RSA, RSA_R_BAD_E_VALUE); return 0; } /* A bad value for e can cause infinite loops */ if (!ossl_rsa_check_public_exponent(e_value)) { ERR_raise(ERR_LIB_RSA, RSA_R_PUB_EXPONENT_OUT_OF_RANGE); return 0; } if (primes < RSA_DEFAULT_PRIME_NUM || primes > ossl_rsa_multip_cap(bits)) { ERR_raise(ERR_LIB_RSA, RSA_R_KEY_PRIME_NUM_INVALID); return 0; } factors = sk_BIGNUM_new_null(); if (factors == NULL) return 0; exps = sk_BIGNUM_new_null(); if (exps == NULL) goto err; coeffs = sk_BIGNUM_new_null(); if (coeffs == NULL) goto err; ctx = BN_CTX_new_ex(rsa->libctx); if (ctx == NULL) goto err; BN_CTX_start(ctx); r0 = BN_CTX_get(ctx); r1 = BN_CTX_get(ctx); r2 = BN_CTX_get(ctx); if (r2 == NULL) goto err; /* divide bits into 'primes' pieces evenly */ quo = bits / primes; rmd = bits % primes; for (i = 0; i < primes; i++) bitsr[i] = (i < rmd) ? quo + 1 : quo; rsa->dirty_cnt++; /* We need the RSA components non-NULL */ if (!rsa->n && ((rsa->n = BN_new()) == NULL)) goto err; if (!rsa->d && ((rsa->d = BN_secure_new()) == NULL)) goto err; BN_set_flags(rsa->d, BN_FLG_CONSTTIME); if (!rsa->e && ((rsa->e = BN_new()) == NULL)) goto err; if (!rsa->p && ((rsa->p = BN_secure_new()) == NULL)) goto err; BN_set_flags(rsa->p, BN_FLG_CONSTTIME); if (!rsa->q && ((rsa->q = BN_secure_new()) == NULL)) goto err; BN_set_flags(rsa->q, BN_FLG_CONSTTIME); /* initialize multi-prime components */ if (primes > RSA_DEFAULT_PRIME_NUM) { rsa->version = RSA_ASN1_VERSION_MULTI; prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, primes - 2); if (prime_infos == NULL) goto err; if (rsa->prime_infos != NULL) { /* could this happen? */ sk_RSA_PRIME_INFO_pop_free(rsa->prime_infos, ossl_rsa_multip_info_free); } rsa->prime_infos = prime_infos; /* prime_info from 2 to |primes| -1 */ for (i = 2; i < primes; i++) { pinfo = ossl_rsa_multip_info_new(); if (pinfo == NULL) goto err; (void)sk_RSA_PRIME_INFO_push(prime_infos, pinfo); } } if (BN_copy(rsa->e, e_value) == NULL) goto err; /* generate p, q and other primes (if any) */ for (i = 0; i < primes; i++) { adj = 0; retries = 0; if (i == 0) { prime = rsa->p; } else if (i == 1) { prime = rsa->q; } else { pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2); prime = pinfo->r; } BN_set_flags(prime, BN_FLG_CONSTTIME); for (;;) { redo: if (!BN_generate_prime_ex2(prime, bitsr[i] + adj, 0, NULL, NULL, cb, ctx)) goto err; /* * prime should not be equal to p, q, r_3... * (those primes prior to this one) */ { int j; for (j = 0; j < i; j++) { BIGNUM *prev_prime; if (j == 0) prev_prime = rsa->p; else if (j == 1) prev_prime = rsa->q; else prev_prime = sk_RSA_PRIME_INFO_value(prime_infos, j - 2)->r; if (!BN_cmp(prime, prev_prime)) { goto redo; } } } if (!BN_sub(r2, prime, BN_value_one())) goto err; ERR_set_mark(); BN_set_flags(r2, BN_FLG_CONSTTIME); if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) { /* GCD == 1 since inverse exists */ break; } error = ERR_peek_last_error(); if (ERR_GET_LIB(error) == ERR_LIB_BN && ERR_GET_REASON(error) == BN_R_NO_INVERSE) { /* GCD != 1 */ ERR_pop_to_mark(); } else { goto err; } if (!BN_GENCB_call(cb, 2, n++)) goto err; } bitse += bitsr[i]; /* calculate n immediately to see if it's sufficient */ if (i == 1) { /* we get at least 2 primes */ if (!BN_mul(r1, rsa->p, rsa->q, ctx)) goto err; } else if (i != 0) { /* modulus n = p * q * r_3 * r_4 ... */ if (!BN_mul(r1, rsa->n, prime, ctx)) goto err; } else { /* i == 0, do nothing */ if (!BN_GENCB_call(cb, 3, i)) goto err; tmp = BN_dup(prime); if (tmp == NULL) goto err; if (!sk_BIGNUM_insert(factors, tmp, sk_BIGNUM_num(factors))) goto err; continue; } /* * if |r1|, product of factors so far, is not as long as expected * (by checking the first 4 bits are less than 0x9 or greater than * 0xF). If so, re-generate the last prime. * * NOTE: This actually can't happen in two-prime case, because of * the way factors are generated. * * Besides, another consideration is, for multi-prime case, even the * length modulus is as long as expected, the modulus could start at * 0x8, which could be utilized to distinguish a multi-prime private * key by using the modulus in a certificate. This is also covered * by checking the length should not be less than 0x9. */ if (!BN_rshift(r2, r1, bitse - 4)) goto err; bitst = BN_get_word(r2); if (bitst < 0x9 || bitst > 0xF) { /* * For keys with more than 4 primes, we attempt longer factor to * meet length requirement. * * Otherwise, we just re-generate the prime with the same length. * * This strategy has the following goals: * * 1. 1024-bit factors are efficient when using 3072 and 4096-bit key * 2. stay the same logic with normal 2-prime key */ bitse -= bitsr[i]; if (!BN_GENCB_call(cb, 2, n++)) goto err; if (primes > 4) { if (bitst < 0x9) adj++; else adj--; } else if (retries == 4) { /* * re-generate all primes from scratch, mainly used * in 4 prime case to avoid long loop. Max retry times * is set to 4. */ i = -1; bitse = 0; sk_BIGNUM_pop_free(factors, BN_clear_free); factors = sk_BIGNUM_new_null(); if (factors == NULL) goto err; continue; } retries++; goto redo; } /* save product of primes for further use, for multi-prime only */ if (i > 1 && BN_copy(pinfo->pp, rsa->n) == NULL) goto err; if (BN_copy(rsa->n, r1) == NULL) goto err; if (!BN_GENCB_call(cb, 3, i)) goto err; tmp = BN_dup(prime); if (tmp == NULL) goto err; if (!sk_BIGNUM_insert(factors, tmp, sk_BIGNUM_num(factors))) goto err; } if (BN_cmp(rsa->p, rsa->q) < 0) { tmp = rsa->p; rsa->p = rsa->q; rsa->q = tmp; /* mirror this in our factor stack */ if (!sk_BIGNUM_insert(factors, sk_BIGNUM_delete(factors, 0), 1)) goto err; } /* calculate d */ /* p - 1 */ if (!BN_sub(r1, rsa->p, BN_value_one())) goto err; /* q - 1 */ if (!BN_sub(r2, rsa->q, BN_value_one())) goto err; /* (p - 1)(q - 1) */ if (!BN_mul(r0, r1, r2, ctx)) goto err; /* multi-prime */ for (i = 2; i < primes; i++) { pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2); /* save r_i - 1 to pinfo->d temporarily */ if (!BN_sub(pinfo->d, pinfo->r, BN_value_one())) goto err; if (!BN_mul(r0, r0, pinfo->d, ctx)) goto err; } BN_set_flags(r0, BN_FLG_CONSTTIME); if (BN_mod_inverse(rsa->d, rsa->e, r0, ctx) == NULL) { goto err; /* d */ } /* derive any missing exponents and coefficients */ if (!ossl_rsa_multiprime_derive(rsa, bits, primes, e_value, factors, exps, coeffs)) goto err; /* * first 2 factors/exps are already tracked in p/q/dmq1/dmp1 * and the first coeff is in iqmp, so pop those off the stack * Note, the first 2 factors/exponents are already tracked by p and q * assign dmp1/dmq1 and iqmp * the remaining pinfo values are separately allocated, so copy and delete * those */ BN_clear_free(sk_BIGNUM_delete(factors, 0)); BN_clear_free(sk_BIGNUM_delete(factors, 0)); rsa->dmp1 = sk_BIGNUM_delete(exps, 0); rsa->dmq1 = sk_BIGNUM_delete(exps, 0); rsa->iqmp = sk_BIGNUM_delete(coeffs, 0); for (i = 2; i < primes; i++) { pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2); tmp = sk_BIGNUM_delete(factors, 0); BN_copy(pinfo->r, tmp); BN_clear_free(tmp); tmp = sk_BIGNUM_delete(exps, 0); tmp2 = BN_copy(pinfo->d, tmp); BN_clear_free(tmp); if (tmp2 == NULL) goto err; tmp = sk_BIGNUM_delete(coeffs, 0); tmp2 = BN_copy(pinfo->t, tmp); BN_clear_free(tmp); if (tmp2 == NULL) goto err; } ok = 1; err: sk_BIGNUM_free(factors); sk_BIGNUM_free(exps); sk_BIGNUM_free(coeffs); if (ok == -1) { ERR_raise(ERR_LIB_RSA, ERR_R_BN_LIB); ok = 0; } BN_CTX_end(ctx); BN_CTX_free(ctx); return ok; } #endif /* FIPS_MODULE */ static int rsa_keygen(OSSL_LIB_CTX *libctx, RSA *rsa, int bits, int primes, BIGNUM *e_value, BN_GENCB *cb, int pairwise_test) { int ok = 0; #ifdef FIPS_MODULE ok = ossl_rsa_sp800_56b_generate_key(rsa, bits, e_value, cb); pairwise_test = 1; /* FIPS MODE needs to always run the pairwise test */ #else /* * Only multi-prime keys or insecure keys with a small key length or a * public exponent <= 2^16 will use the older rsa_multiprime_keygen(). */ if (primes == 2 && bits >= 2048 && (e_value == NULL || BN_num_bits(e_value) > 16)) ok = ossl_rsa_sp800_56b_generate_key(rsa, bits, e_value, cb); else ok = rsa_multiprime_keygen(rsa, bits, primes, e_value, cb); #endif /* FIPS_MODULE */ if (pairwise_test && ok > 0) { OSSL_CALLBACK *stcb = NULL; void *stcbarg = NULL; OSSL_SELF_TEST_get_callback(libctx, &stcb, &stcbarg); ok = rsa_keygen_pairwise_test(rsa, stcb, stcbarg); if (!ok) { ossl_set_error_state(OSSL_SELF_TEST_TYPE_PCT); /* Clear intermediate results */ BN_clear_free(rsa->d); BN_clear_free(rsa->p); BN_clear_free(rsa->q); BN_clear_free(rsa->dmp1); BN_clear_free(rsa->dmq1); BN_clear_free(rsa->iqmp); rsa->d = NULL; rsa->p = NULL; rsa->q = NULL; rsa->dmp1 = NULL; rsa->dmq1 = NULL; rsa->iqmp = NULL; } } return ok; } /* * AS10.35 (and its VEs/TEs) of the FIPS 140-3 standard requires a PCT for every * generated key pair. There are 3 options: * 1) If the key pair is to be used for key transport (asymmetric cipher), the * PCT consists of encrypting a plaintext, verifying that the result * (ciphertext) is not equal to the plaintext, decrypting the ciphertext, and * verifying that the result is equal to the plaintext. * 2) If the key pair is to be used for digital signatures, the PCT consists of * computing and verifying a signature. * 3) If the key pair is to be used for key agreement, the exact PCT is defined * in the applicable standards. For RSA-based schemes, this is defined in * SP 800-56Br2 (Section 6.4.1.1) as: * "The owner shall perform a pair-wise consistency test by verifying that m * = (m^e)^d mod n for some integer m satisfying 1 < m < (n - 1)." * * OpenSSL implements all three use cases: RSA-OAEP for key transport, * RSA signatures with PKCS#1 v1.5 or PSS padding, and KAS-IFC-SSC (KAS1/KAS2) * using RSASVE. * * According to FIPS 140-3 IG 10.3.A, if at the time when the PCT is performed * the keys' intended usage is not known, then any of the three PCTs described * in AS10.35 shall be performed on this key pair. * * Because of this allowance from the IG, the simplest option is 3, i.e. * RSA_public_encrypt() and RSA_private_decrypt() with RSA_NO_PADDING. */ static int rsa_keygen_pairwise_test(RSA *rsa, OSSL_CALLBACK *cb, void *cbarg) { int ret = 0; unsigned int plaintxt_len; unsigned char *plaintxt = NULL; unsigned int ciphertxt_len; unsigned char *ciphertxt = NULL; unsigned char *decoded = NULL; unsigned int decoded_len; int padding = RSA_NO_PADDING; OSSL_SELF_TEST *st = NULL; st = OSSL_SELF_TEST_new(cb, cbarg); if (st == NULL) goto err; OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_PCT, OSSL_SELF_TEST_DESC_PCT_RSA); /* * For RSA_NO_PADDING, RSA_public_encrypt() and RSA_private_decrypt() * require the 'to' and 'from' parameters to have equal length and a * maximum of RSA_size() - allocate space for plaintxt, ciphertxt, and * decoded. */ plaintxt_len = RSA_size(rsa); plaintxt = OPENSSL_zalloc(plaintxt_len * 3); if (plaintxt == NULL) goto err; ciphertxt = plaintxt + plaintxt_len; decoded = ciphertxt + plaintxt_len; /* SP 800-56Br2 Section 6.4.1.1 requires that plaintext is greater than 1 */ plaintxt[plaintxt_len - 1] = 2; ciphertxt_len = RSA_public_encrypt(plaintxt_len, plaintxt, ciphertxt, rsa, padding); if (ciphertxt_len <= 0) goto err; OSSL_SELF_TEST_oncorrupt_byte(st, ciphertxt); decoded_len = RSA_private_decrypt(ciphertxt_len, ciphertxt, decoded, rsa, padding); if (decoded_len != plaintxt_len || memcmp(decoded, plaintxt, decoded_len) != 0) goto err; ret = 1; err: OSSL_SELF_TEST_onend(st, ret); OSSL_SELF_TEST_free(st); OPENSSL_free(plaintxt); return ret; } - -#ifdef FIPS_MODULE -int ossl_rsa_key_pairwise_test(RSA *rsa) -{ - OSSL_CALLBACK *stcb; - void *stcbarg; - int res; - - OSSL_SELF_TEST_get_callback(rsa->libctx, &stcb, &stcbarg); - res = rsa_keygen_pairwise_test(rsa, stcb, stcbarg); - if (res <= 0) - ossl_set_error_state(OSSL_SELF_TEST_TYPE_PCT_IMPORT); - return res; -} -#endif /* FIPS_MODULE */ diff --git a/crypto/rsa/rsa_sign.c b/crypto/rsa/rsa_sign.c index 78e4bad69e49..bb6e99acf9d3 100644 --- a/crypto/rsa/rsa_sign.c +++ b/crypto/rsa/rsa_sign.c @@ -1,469 +1,469 @@ /* - * Copyright 1995-2024 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2025 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 #ifndef FIPS_MODULE # ifndef OPENSSL_NO_MD2 # include /* uses MD2_DIGEST_LENGTH */ # endif # ifndef OPENSSL_NO_MD4 # include /* uses MD4_DIGEST_LENGTH */ # endif # ifndef OPENSSL_NO_MD5 # include /* uses MD5_DIGEST_LENGTH */ # endif # ifndef OPENSSL_NO_MDC2 # include /* uses MDC2_DIGEST_LENGTH */ # endif # ifndef OPENSSL_NO_RMD160 # include /* uses RIPEMD160_DIGEST_LENGTH */ # endif # ifndef OPENSSL_NO_SM3 # include "internal/sm3.h" /* uses SM3_DIGEST_LENGTH */ # endif #endif #include /* uses SHA???_DIGEST_LENGTH */ #include "crypto/rsa.h" #include "rsa_local.h" /* * The general purpose ASN1 code is not available inside the FIPS provider. * To remove the dependency RSASSA-PKCS1-v1_5 DigestInfo encodings can be * treated as a special case by pregenerating the required ASN1 encoding. * This encoding will also be shared by the default provider. * * The EMSA-PKCS1-v1_5 encoding method includes an ASN.1 value of type * DigestInfo, where the type DigestInfo has the syntax * * DigestInfo ::= SEQUENCE { * digestAlgorithm DigestAlgorithm, * digest OCTET STRING * } * * DigestAlgorithm ::= AlgorithmIdentifier { * {PKCS1-v1-5DigestAlgorithms} * } * * The AlgorithmIdentifier is a sequence containing the digest OID and * parameters (a value of type NULL). * * The ENCODE_DIGESTINFO_SHA() and ENCODE_DIGESTINFO_MD() macros define an * initialized array containing the DER encoded DigestInfo for the specified * SHA or MD digest. The content of the OCTET STRING is not included. * |name| is the digest name. * |n| is last byte in the encoded OID for the digest. * |sz| is the digest length in bytes. It must not be greater than 110. */ #define ASN1_SEQUENCE 0x30 #define ASN1_OCTET_STRING 0x04 #define ASN1_NULL 0x05 #define ASN1_OID 0x06 /* SHA OIDs are of the form: (2 16 840 1 101 3 4 2 |n|) */ #define ENCODE_DIGESTINFO_SHA(name, n, sz) \ static const unsigned char digestinfo_##name##_der[] = { \ ASN1_SEQUENCE, 0x11 + sz, \ ASN1_SEQUENCE, 0x0d, \ ASN1_OID, 0x09, 2 * 40 + 16, 0x86, 0x48, 1, 101, 3, 4, 2, n, \ ASN1_NULL, 0x00, \ ASN1_OCTET_STRING, sz \ }; /* MD2, MD4 and MD5 OIDs are of the form: (1 2 840 113549 2 |n|) */ #define ENCODE_DIGESTINFO_MD(name, n, sz) \ static const unsigned char digestinfo_##name##_der[] = { \ ASN1_SEQUENCE, 0x10 + sz, \ ASN1_SEQUENCE, 0x0c, \ ASN1_OID, 0x08, 1 * 40 + 2, 0x86, 0x48, 0x86, 0xf7, 0x0d, 2, n, \ ASN1_NULL, 0x00, \ ASN1_OCTET_STRING, sz \ }; #ifndef FIPS_MODULE # ifndef OPENSSL_NO_MD2 ENCODE_DIGESTINFO_MD(md2, 0x02, MD2_DIGEST_LENGTH) # endif # ifndef OPENSSL_NO_MD4 ENCODE_DIGESTINFO_MD(md4, 0x03, MD4_DIGEST_LENGTH) # endif # ifndef OPENSSL_NO_MD5 ENCODE_DIGESTINFO_MD(md5, 0x05, MD5_DIGEST_LENGTH) # endif # ifndef OPENSSL_NO_MDC2 /* MDC-2 (2 5 8 3 101) */ static const unsigned char digestinfo_mdc2_der[] = { ASN1_SEQUENCE, 0x0c + MDC2_DIGEST_LENGTH, ASN1_SEQUENCE, 0x08, ASN1_OID, 0x04, 2 * 40 + 5, 8, 3, 101, ASN1_NULL, 0x00, ASN1_OCTET_STRING, MDC2_DIGEST_LENGTH }; # endif # ifndef OPENSSL_NO_RMD160 /* RIPEMD160 (1 3 36 3 2 1) */ static const unsigned char digestinfo_ripemd160_der[] = { ASN1_SEQUENCE, 0x0d + RIPEMD160_DIGEST_LENGTH, ASN1_SEQUENCE, 0x09, ASN1_OID, 0x05, 1 * 40 + 3, 36, 3, 2, 1, ASN1_NULL, 0x00, ASN1_OCTET_STRING, RIPEMD160_DIGEST_LENGTH }; # endif # ifndef OPENSSL_NO_SM3 /* SM3 (1 2 156 10197 1 401) */ static const unsigned char digestinfo_sm3_der[] = { - ASN1_SEQUENCE, 0x0f + SM3_DIGEST_LENGTH, + ASN1_SEQUENCE, 0x10 + SM3_DIGEST_LENGTH, ASN1_SEQUENCE, 0x0c, ASN1_OID, 0x08, 1 * 40 + 2, 0x81, 0x1c, 0xcf, 0x55, 1, 0x83, 0x78, ASN1_NULL, 0x00, ASN1_OCTET_STRING, SM3_DIGEST_LENGTH }; # endif #endif /* FIPS_MODULE */ /* SHA-1 (1 3 14 3 2 26) */ static const unsigned char digestinfo_sha1_der[] = { ASN1_SEQUENCE, 0x0d + SHA_DIGEST_LENGTH, ASN1_SEQUENCE, 0x09, ASN1_OID, 0x05, 1 * 40 + 3, 14, 3, 2, 26, ASN1_NULL, 0x00, ASN1_OCTET_STRING, SHA_DIGEST_LENGTH }; ENCODE_DIGESTINFO_SHA(sha256, 0x01, SHA256_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha384, 0x02, SHA384_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha512, 0x03, SHA512_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha224, 0x04, SHA224_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha512_224, 0x05, SHA224_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha512_256, 0x06, SHA256_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha3_224, 0x07, SHA224_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha3_256, 0x08, SHA256_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha3_384, 0x09, SHA384_DIGEST_LENGTH) ENCODE_DIGESTINFO_SHA(sha3_512, 0x0a, SHA512_DIGEST_LENGTH) #define MD_CASE(name) \ case NID_##name: \ *len = sizeof(digestinfo_##name##_der); \ return digestinfo_##name##_der; const unsigned char *ossl_rsa_digestinfo_encoding(int md_nid, size_t *len) { switch (md_nid) { #ifndef FIPS_MODULE # ifndef OPENSSL_NO_MDC2 MD_CASE(mdc2) # endif # ifndef OPENSSL_NO_MD2 MD_CASE(md2) # endif # ifndef OPENSSL_NO_MD4 MD_CASE(md4) # endif # ifndef OPENSSL_NO_MD5 MD_CASE(md5) # endif # ifndef OPENSSL_NO_RMD160 MD_CASE(ripemd160) # endif # ifndef OPENSSL_NO_SM3 MD_CASE(sm3) # endif #endif /* FIPS_MODULE */ MD_CASE(sha1) MD_CASE(sha224) MD_CASE(sha256) MD_CASE(sha384) MD_CASE(sha512) MD_CASE(sha512_224) MD_CASE(sha512_256) MD_CASE(sha3_224) MD_CASE(sha3_256) MD_CASE(sha3_384) MD_CASE(sha3_512) default: return NULL; } } #define MD_NID_CASE(name, sz) \ case NID_##name: \ return sz; static int digest_sz_from_nid(int nid) { switch (nid) { #ifndef FIPS_MODULE # ifndef OPENSSL_NO_MDC2 MD_NID_CASE(mdc2, MDC2_DIGEST_LENGTH) # endif # ifndef OPENSSL_NO_MD2 MD_NID_CASE(md2, MD2_DIGEST_LENGTH) # endif # ifndef OPENSSL_NO_MD4 MD_NID_CASE(md4, MD4_DIGEST_LENGTH) # endif # ifndef OPENSSL_NO_MD5 MD_NID_CASE(md5, MD5_DIGEST_LENGTH) # endif # ifndef OPENSSL_NO_RMD160 MD_NID_CASE(ripemd160, RIPEMD160_DIGEST_LENGTH) # endif #endif /* FIPS_MODULE */ MD_NID_CASE(sha1, SHA_DIGEST_LENGTH) MD_NID_CASE(sha224, SHA224_DIGEST_LENGTH) MD_NID_CASE(sha256, SHA256_DIGEST_LENGTH) MD_NID_CASE(sha384, SHA384_DIGEST_LENGTH) MD_NID_CASE(sha512, SHA512_DIGEST_LENGTH) MD_NID_CASE(sha512_224, SHA224_DIGEST_LENGTH) MD_NID_CASE(sha512_256, SHA256_DIGEST_LENGTH) MD_NID_CASE(sha3_224, SHA224_DIGEST_LENGTH) MD_NID_CASE(sha3_256, SHA256_DIGEST_LENGTH) MD_NID_CASE(sha3_384, SHA384_DIGEST_LENGTH) MD_NID_CASE(sha3_512, SHA512_DIGEST_LENGTH) default: return 0; } } /* Size of an SSL signature: MD5+SHA1 */ #define SSL_SIG_LENGTH 36 /* * Encodes a DigestInfo prefix of hash |type| and digest |m|, as * described in EMSA-PKCS1-v1_5-ENCODE, RFC 3447 section 9.2 step 2. This * encodes the DigestInfo (T and tLen) but does not add the padding. * * On success, it returns one and sets |*out| to a newly allocated buffer * containing the result and |*out_len| to its length. The caller must free * |*out| with OPENSSL_free(). Otherwise, it returns zero. */ static int encode_pkcs1(unsigned char **out, size_t *out_len, int type, const unsigned char *m, size_t m_len) { size_t di_prefix_len, dig_info_len; const unsigned char *di_prefix; unsigned char *dig_info; if (type == NID_undef) { ERR_raise(ERR_LIB_RSA, RSA_R_UNKNOWN_ALGORITHM_TYPE); return 0; } di_prefix = ossl_rsa_digestinfo_encoding(type, &di_prefix_len); if (di_prefix == NULL) { ERR_raise(ERR_LIB_RSA, RSA_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD); return 0; } dig_info_len = di_prefix_len + m_len; dig_info = OPENSSL_malloc(dig_info_len); if (dig_info == NULL) return 0; memcpy(dig_info, di_prefix, di_prefix_len); memcpy(dig_info + di_prefix_len, m, m_len); *out = dig_info; *out_len = dig_info_len; return 1; } int RSA_sign(int type, const unsigned char *m, unsigned int m_len, unsigned char *sigret, unsigned int *siglen, RSA *rsa) { int encrypt_len, ret = 0; size_t encoded_len = 0; unsigned char *tmps = NULL; const unsigned char *encoded = NULL; #ifndef FIPS_MODULE if (rsa->meth->rsa_sign != NULL) return rsa->meth->rsa_sign(type, m, m_len, sigret, siglen, rsa) > 0; #endif /* FIPS_MODULE */ /* Compute the encoded digest. */ if (type == NID_md5_sha1) { /* * NID_md5_sha1 corresponds to the MD5/SHA1 combination in TLS 1.1 and * earlier. It has no DigestInfo wrapper but otherwise is * RSASSA-PKCS1-v1_5. */ if (m_len != SSL_SIG_LENGTH) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_MESSAGE_LENGTH); return 0; } encoded_len = SSL_SIG_LENGTH; encoded = m; } else { if (!encode_pkcs1(&tmps, &encoded_len, type, m, m_len)) goto err; encoded = tmps; } if (encoded_len + RSA_PKCS1_PADDING_SIZE > (size_t)RSA_size(rsa)) { ERR_raise(ERR_LIB_RSA, RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY); goto err; } encrypt_len = RSA_private_encrypt((int)encoded_len, encoded, sigret, rsa, RSA_PKCS1_PADDING); if (encrypt_len <= 0) goto err; *siglen = encrypt_len; ret = 1; err: OPENSSL_clear_free(tmps, encoded_len); return ret; } /* * Verify an RSA signature in |sigbuf| using |rsa|. * |type| is the NID of the digest algorithm to use. * If |rm| is NULL, it verifies the signature for digest |m|, otherwise * it recovers the digest from the signature, writing the digest to |rm| and * the length to |*prm_len|. * * It returns one on successful verification or zero otherwise. */ int ossl_rsa_verify(int type, const unsigned char *m, unsigned int m_len, unsigned char *rm, size_t *prm_len, const unsigned char *sigbuf, size_t siglen, RSA *rsa) { int len, ret = 0; size_t decrypt_len, encoded_len = 0; unsigned char *decrypt_buf = NULL, *encoded = NULL; if (siglen != (size_t)RSA_size(rsa)) { ERR_raise(ERR_LIB_RSA, RSA_R_WRONG_SIGNATURE_LENGTH); return 0; } /* Recover the encoded digest. */ decrypt_buf = OPENSSL_malloc(siglen); if (decrypt_buf == NULL) goto err; len = RSA_public_decrypt((int)siglen, sigbuf, decrypt_buf, rsa, RSA_PKCS1_PADDING); if (len <= 0) goto err; decrypt_len = len; #ifndef FIPS_MODULE if (type == NID_md5_sha1) { /* * NID_md5_sha1 corresponds to the MD5/SHA1 combination in TLS 1.1 and * earlier. It has no DigestInfo wrapper but otherwise is * RSASSA-PKCS1-v1_5. */ if (decrypt_len != SSL_SIG_LENGTH) { ERR_raise(ERR_LIB_RSA, RSA_R_BAD_SIGNATURE); goto err; } if (rm != NULL) { memcpy(rm, decrypt_buf, SSL_SIG_LENGTH); *prm_len = SSL_SIG_LENGTH; } else { if (m_len != SSL_SIG_LENGTH) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_MESSAGE_LENGTH); goto err; } if (memcmp(decrypt_buf, m, SSL_SIG_LENGTH) != 0) { ERR_raise(ERR_LIB_RSA, RSA_R_BAD_SIGNATURE); goto err; } } } else if (type == NID_mdc2 && decrypt_len == 2 + 16 && decrypt_buf[0] == 0x04 && decrypt_buf[1] == 0x10) { /* * Oddball MDC2 case: signature can be OCTET STRING. check for correct * tag and length octets. */ if (rm != NULL) { memcpy(rm, decrypt_buf + 2, 16); *prm_len = 16; } else { if (m_len != 16) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_MESSAGE_LENGTH); goto err; } if (memcmp(m, decrypt_buf + 2, 16) != 0) { ERR_raise(ERR_LIB_RSA, RSA_R_BAD_SIGNATURE); goto err; } } } else #endif /* FIPS_MODULE */ { /* * If recovering the digest, extract a digest-sized output from the end * of |decrypt_buf| for |encode_pkcs1|, then compare the decryption * output as in a standard verification. */ if (rm != NULL) { len = digest_sz_from_nid(type); if (len <= 0) goto err; m_len = (unsigned int)len; if (m_len > decrypt_len) { ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_DIGEST_LENGTH); goto err; } m = decrypt_buf + decrypt_len - m_len; } /* Construct the encoded digest and ensure it matches. */ if (!encode_pkcs1(&encoded, &encoded_len, type, m, m_len)) goto err; if (encoded_len != decrypt_len || memcmp(encoded, decrypt_buf, encoded_len) != 0) { ERR_raise(ERR_LIB_RSA, RSA_R_BAD_SIGNATURE); goto err; } /* Output the recovered digest. */ if (rm != NULL) { memcpy(rm, m, m_len); *prm_len = m_len; } } ret = 1; err: OPENSSL_clear_free(encoded, encoded_len); OPENSSL_clear_free(decrypt_buf, siglen); return ret; } int RSA_verify(int type, const unsigned char *m, unsigned int m_len, const unsigned char *sigbuf, unsigned int siglen, RSA *rsa) { if (rsa->meth->rsa_verify != NULL) return rsa->meth->rsa_verify(type, m, m_len, sigbuf, siglen, rsa); return ossl_rsa_verify(type, m, m_len, NULL, NULL, sigbuf, siglen, rsa); } diff --git a/crypto/threads_pthread.c b/crypto/threads_pthread.c index 44d6ebe09231..ace2dc499061 100644 --- a/crypto/threads_pthread.c +++ b/crypto/threads_pthread.c @@ -1,915 +1,921 @@ /* * Copyright 2016-2025 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 #include "internal/cryptlib.h" #include "internal/rcu.h" #include "rcu_internal.h" #if defined(__clang__) && defined(__has_feature) # if __has_feature(thread_sanitizer) # define __SANITIZE_THREAD__ # endif #endif #if defined(__SANITIZE_THREAD__) # include # define TSAN_FAKE_UNLOCK(x) __tsan_mutex_pre_unlock((x), 0); \ __tsan_mutex_post_unlock((x), 0) # define TSAN_FAKE_LOCK(x) __tsan_mutex_pre_lock((x), 0); \ __tsan_mutex_post_lock((x), 0, 0) #else # define TSAN_FAKE_UNLOCK(x) # define TSAN_FAKE_LOCK(x) #endif #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 /* * The Non-Stop KLT thread model currently seems broken in its rwlock * implementation + * Likewise is there a problem with the glibc implementation on riscv. */ -# if defined(PTHREAD_RWLOCK_INITIALIZER) && !defined(_KLT_MODEL_) +# if defined(PTHREAD_RWLOCK_INITIALIZER) && !defined(_KLT_MODEL_) \ + && !defined(__riscv) # define USE_RWLOCK # endif /* * For all GNU/clang atomic builtins, we also need fallbacks, to cover all * other compilers. * Unfortunately, we can't do that with some "generic type", because there's no * guarantee that the chosen generic type is large enough to cover all cases. * Therefore, we implement fallbacks for each applicable type, with composed * names that include the type they handle. * * (an anecdote: we previously tried to use |void *| as the generic type, with * the thought that the pointer itself is the largest type. However, this is * not true on 32-bit pointer platforms, as a |uint64_t| is twice as large) * * All applicable ATOMIC_ macros take the intended type as first parameter, so * they can map to the correct fallback function. In the GNU/clang case, that * parameter is simply ignored. */ /* * Internal types used with the ATOMIC_ macros, to make it possible to compose * fallback function names. */ typedef void *pvoid; # if defined(__GNUC__) && defined(__ATOMIC_ACQUIRE) && !defined(BROKEN_CLANG_ATOMICS) \ && !defined(USE_ATOMIC_FALLBACKS) # define ATOMIC_LOAD_N(t, p, o) __atomic_load_n(p, o) # define ATOMIC_STORE_N(t, p, v, o) __atomic_store_n(p, v, o) # define ATOMIC_STORE(t, p, v, o) __atomic_store(p, v, o) # define ATOMIC_ADD_FETCH(p, v, o) __atomic_add_fetch(p, v, o) # define ATOMIC_SUB_FETCH(p, v, o) __atomic_sub_fetch(p, v, o) # else static pthread_mutex_t atomic_sim_lock = PTHREAD_MUTEX_INITIALIZER; # define IMPL_fallback_atomic_load_n(t) \ static ossl_inline t fallback_atomic_load_n_##t(t *p) \ { \ t ret; \ \ pthread_mutex_lock(&atomic_sim_lock); \ ret = *p; \ pthread_mutex_unlock(&atomic_sim_lock); \ return ret; \ } IMPL_fallback_atomic_load_n(uint32_t) IMPL_fallback_atomic_load_n(uint64_t) IMPL_fallback_atomic_load_n(pvoid) # define ATOMIC_LOAD_N(t, p, o) fallback_atomic_load_n_##t(p) # define IMPL_fallback_atomic_store_n(t) \ static ossl_inline t fallback_atomic_store_n_##t(t *p, t v) \ { \ t ret; \ \ pthread_mutex_lock(&atomic_sim_lock); \ ret = *p; \ *p = v; \ pthread_mutex_unlock(&atomic_sim_lock); \ return ret; \ } IMPL_fallback_atomic_store_n(uint32_t) # define ATOMIC_STORE_N(t, p, v, o) fallback_atomic_store_n_##t(p, v) # define IMPL_fallback_atomic_store(t) \ static ossl_inline void fallback_atomic_store_##t(t *p, t *v) \ { \ pthread_mutex_lock(&atomic_sim_lock); \ *p = *v; \ pthread_mutex_unlock(&atomic_sim_lock); \ } IMPL_fallback_atomic_store(pvoid) # define ATOMIC_STORE(t, p, v, o) fallback_atomic_store_##t(p, v) /* * The fallbacks that follow don't need any per type implementation, as * they are designed for uint64_t only. If there comes a time when multiple * types need to be covered, it's relatively easy to refactor them the same * way as the fallbacks above. */ static ossl_inline uint64_t fallback_atomic_add_fetch(uint64_t *p, uint64_t v) { uint64_t ret; pthread_mutex_lock(&atomic_sim_lock); *p += v; ret = *p; pthread_mutex_unlock(&atomic_sim_lock); return ret; } # define ATOMIC_ADD_FETCH(p, v, o) fallback_atomic_add_fetch(p, v) static ossl_inline uint64_t fallback_atomic_sub_fetch(uint64_t *p, uint64_t v) { uint64_t ret; pthread_mutex_lock(&atomic_sim_lock); *p -= v; ret = *p; pthread_mutex_unlock(&atomic_sim_lock); return ret; } # define ATOMIC_SUB_FETCH(p, v, o) fallback_atomic_sub_fetch(p, v) # endif /* * This is the core of an rcu lock. It tracks the readers and writers for the * current quiescence point for a given lock. Users is the 64 bit value that * stores the READERS/ID as defined above * */ struct rcu_qp { uint64_t users; }; struct thread_qp { struct rcu_qp *qp; unsigned int depth; CRYPTO_RCU_LOCK *lock; }; # define MAX_QPS 10 /* * This is the per thread tracking data * that is assigned to each thread participating * in an rcu qp * * qp points to the qp that it last acquired * */ struct rcu_thr_data { struct thread_qp thread_qps[MAX_QPS]; }; /* * This is the internal version of a CRYPTO_RCU_LOCK * it is cast from CRYPTO_RCU_LOCK */ struct rcu_lock_st { /* Callbacks to call for next ossl_synchronize_rcu */ struct rcu_cb_item *cb_items; /* The context we are being created against */ OSSL_LIB_CTX *ctx; /* Array of quiescent points for synchronization */ struct rcu_qp *qp_group; /* rcu generation counter for in-order retirement */ uint32_t id_ctr; /* Number of elements in qp_group array */ uint32_t group_count; /* Index of the current qp in the qp_group array */ uint32_t reader_idx; /* value of the next id_ctr value to be retired */ uint32_t next_to_retire; /* index of the next free rcu_qp in the qp_group */ uint32_t current_alloc_idx; /* number of qp's in qp_group array currently being retired */ uint32_t writers_alloced; /* lock protecting write side operations */ pthread_mutex_t write_lock; /* lock protecting updates to writers_alloced/current_alloc_idx */ pthread_mutex_t alloc_lock; /* signal to wake threads waiting on alloc_lock */ pthread_cond_t alloc_signal; /* lock to enforce in-order retirement */ pthread_mutex_t prior_lock; /* signal to wake threads waiting on prior_lock */ pthread_cond_t prior_signal; }; /* Read side acquisition of the current qp */ static struct rcu_qp *get_hold_current_qp(struct rcu_lock_st *lock) { uint32_t qp_idx; /* get the current qp index */ for (;;) { qp_idx = ATOMIC_LOAD_N(uint32_t, &lock->reader_idx, __ATOMIC_RELAXED); /* * Notes on use of __ATOMIC_ACQUIRE * We need to ensure the following: * 1) That subsequent operations aren't optimized by hoisting them above * this operation. Specifically, we don't want the below re-load of * qp_idx to get optimized away * 2) We want to ensure that any updating of reader_idx on the write side * of the lock is flushed from a local cpu cache so that we see any * updates prior to the load. This is a non-issue on cache coherent * systems like x86, but is relevant on other arches */ ATOMIC_ADD_FETCH(&lock->qp_group[qp_idx].users, (uint64_t)1, __ATOMIC_ACQUIRE); /* if the idx hasn't changed, we're good, else try again */ if (qp_idx == ATOMIC_LOAD_N(uint32_t, &lock->reader_idx, - __ATOMIC_RELAXED)) + __ATOMIC_ACQUIRE)) break; ATOMIC_SUB_FETCH(&lock->qp_group[qp_idx].users, (uint64_t)1, __ATOMIC_RELAXED); } return &lock->qp_group[qp_idx]; } static void ossl_rcu_free_local_data(void *arg) { OSSL_LIB_CTX *ctx = arg; CRYPTO_THREAD_LOCAL *lkey = ossl_lib_ctx_get_rcukey(ctx); struct rcu_thr_data *data = CRYPTO_THREAD_get_local(lkey); OPENSSL_free(data); CRYPTO_THREAD_set_local(lkey, NULL); } void ossl_rcu_read_lock(CRYPTO_RCU_LOCK *lock) { struct rcu_thr_data *data; int i, available_qp = -1; CRYPTO_THREAD_LOCAL *lkey = ossl_lib_ctx_get_rcukey(lock->ctx); /* * we're going to access current_qp here so ask the * processor to fetch it */ data = CRYPTO_THREAD_get_local(lkey); if (data == NULL) { data = OPENSSL_zalloc(sizeof(*data)); OPENSSL_assert(data != NULL); CRYPTO_THREAD_set_local(lkey, data); ossl_init_thread_start(NULL, lock->ctx, ossl_rcu_free_local_data); } for (i = 0; i < MAX_QPS; i++) { if (data->thread_qps[i].qp == NULL && available_qp == -1) available_qp = i; /* If we have a hold on this lock already, we're good */ if (data->thread_qps[i].lock == lock) { data->thread_qps[i].depth++; return; } } /* * if we get here, then we don't have a hold on this lock yet */ assert(available_qp != -1); data->thread_qps[available_qp].qp = get_hold_current_qp(lock); data->thread_qps[available_qp].depth = 1; data->thread_qps[available_qp].lock = lock; } void ossl_rcu_read_unlock(CRYPTO_RCU_LOCK *lock) { int i; CRYPTO_THREAD_LOCAL *lkey = ossl_lib_ctx_get_rcukey(lock->ctx); struct rcu_thr_data *data = CRYPTO_THREAD_get_local(lkey); uint64_t ret; assert(data != NULL); for (i = 0; i < MAX_QPS; i++) { if (data->thread_qps[i].lock == lock) { /* * we have to use __ATOMIC_RELEASE here * to ensure that all preceding read instructions complete * before the decrement is visible to ossl_synchronize_rcu */ data->thread_qps[i].depth--; if (data->thread_qps[i].depth == 0) { ret = ATOMIC_SUB_FETCH(&data->thread_qps[i].qp->users, (uint64_t)1, __ATOMIC_RELEASE); OPENSSL_assert(ret != UINT64_MAX); data->thread_qps[i].qp = NULL; data->thread_qps[i].lock = NULL; } return; } } /* * If we get here, we're trying to unlock a lock that we never acquired - * that's fatal. */ assert(0); } /* * Write side allocation routine to get the current qp * and replace it with a new one */ static struct rcu_qp *update_qp(CRYPTO_RCU_LOCK *lock, uint32_t *curr_id) { uint32_t current_idx; pthread_mutex_lock(&lock->alloc_lock); /* * we need at least one qp to be available with one * left over, so that readers can start working on * one that isn't yet being waited on */ while (lock->group_count - lock->writers_alloced < 2) /* we have to wait for one to be free */ pthread_cond_wait(&lock->alloc_signal, &lock->alloc_lock); current_idx = lock->current_alloc_idx; /* Allocate the qp */ lock->writers_alloced++; /* increment the allocation index */ lock->current_alloc_idx = (lock->current_alloc_idx + 1) % lock->group_count; *curr_id = lock->id_ctr; lock->id_ctr++; + /* + * make the current state of everything visible by this release + * when get_hold_current_qp acquires the next qp + */ ATOMIC_STORE_N(uint32_t, &lock->reader_idx, lock->current_alloc_idx, - __ATOMIC_RELAXED); + __ATOMIC_RELEASE); /* * this should make sure that the new value of reader_idx is visible in * get_hold_current_qp, directly after incrementing the users count */ ATOMIC_ADD_FETCH(&lock->qp_group[current_idx].users, (uint64_t)0, __ATOMIC_RELEASE); /* wake up any waiters */ pthread_cond_signal(&lock->alloc_signal); pthread_mutex_unlock(&lock->alloc_lock); return &lock->qp_group[current_idx]; } static void retire_qp(CRYPTO_RCU_LOCK *lock, struct rcu_qp *qp) { pthread_mutex_lock(&lock->alloc_lock); lock->writers_alloced--; pthread_cond_signal(&lock->alloc_signal); pthread_mutex_unlock(&lock->alloc_lock); } static struct rcu_qp *allocate_new_qp_group(CRYPTO_RCU_LOCK *lock, uint32_t count) { struct rcu_qp *new = OPENSSL_zalloc(sizeof(*new) * count); lock->group_count = count; return new; } void ossl_rcu_write_lock(CRYPTO_RCU_LOCK *lock) { pthread_mutex_lock(&lock->write_lock); TSAN_FAKE_UNLOCK(&lock->write_lock); } void ossl_rcu_write_unlock(CRYPTO_RCU_LOCK *lock) { TSAN_FAKE_LOCK(&lock->write_lock); pthread_mutex_unlock(&lock->write_lock); } void ossl_synchronize_rcu(CRYPTO_RCU_LOCK *lock) { struct rcu_qp *qp; uint64_t count; uint32_t curr_id; struct rcu_cb_item *cb_items, *tmpcb; pthread_mutex_lock(&lock->write_lock); cb_items = lock->cb_items; lock->cb_items = NULL; pthread_mutex_unlock(&lock->write_lock); qp = update_qp(lock, &curr_id); /* retire in order */ pthread_mutex_lock(&lock->prior_lock); while (lock->next_to_retire != curr_id) pthread_cond_wait(&lock->prior_signal, &lock->prior_lock); /* * wait for the reader count to reach zero * Note the use of __ATOMIC_ACQUIRE here to ensure that any * prior __ATOMIC_RELEASE write operation in ossl_rcu_read_unlock * is visible prior to our read * however this is likely just necessary to silence a tsan warning * because the read side should not do any write operation * outside the atomic itself */ do { count = ATOMIC_LOAD_N(uint64_t, &qp->users, __ATOMIC_ACQUIRE); } while (count != (uint64_t)0); lock->next_to_retire++; pthread_cond_broadcast(&lock->prior_signal); pthread_mutex_unlock(&lock->prior_lock); retire_qp(lock, qp); /* handle any callbacks that we have */ while (cb_items != NULL) { tmpcb = cb_items; cb_items = cb_items->next; tmpcb->fn(tmpcb->data); OPENSSL_free(tmpcb); } } /* * Note: This call assumes its made under the protection of * ossl_rcu_write_lock */ int ossl_rcu_call(CRYPTO_RCU_LOCK *lock, rcu_cb_fn cb, void *data) { struct rcu_cb_item *new = OPENSSL_zalloc(sizeof(*new)); if (new == NULL) return 0; new->data = data; new->fn = cb; new->next = lock->cb_items; lock->cb_items = new; return 1; } void *ossl_rcu_uptr_deref(void **p) { return ATOMIC_LOAD_N(pvoid, p, __ATOMIC_ACQUIRE); } void ossl_rcu_assign_uptr(void **p, void **v) { ATOMIC_STORE(pvoid, p, v, __ATOMIC_RELEASE); } CRYPTO_RCU_LOCK *ossl_rcu_lock_new(int num_writers, OSSL_LIB_CTX *ctx) { struct rcu_lock_st *new; /* * We need a minimum of 2 qp's */ if (num_writers < 2) num_writers = 2; ctx = ossl_lib_ctx_get_concrete(ctx); if (ctx == NULL) return 0; new = OPENSSL_zalloc(sizeof(*new)); if (new == NULL) return NULL; new->ctx = ctx; pthread_mutex_init(&new->write_lock, NULL); pthread_mutex_init(&new->prior_lock, NULL); pthread_mutex_init(&new->alloc_lock, NULL); pthread_cond_init(&new->prior_signal, NULL); pthread_cond_init(&new->alloc_signal, NULL); new->qp_group = allocate_new_qp_group(new, num_writers); if (new->qp_group == NULL) { OPENSSL_free(new); new = NULL; } return new; } void ossl_rcu_lock_free(CRYPTO_RCU_LOCK *lock) { struct rcu_lock_st *rlock = (struct rcu_lock_st *)lock; if (lock == NULL) return; /* make sure we're synchronized */ ossl_synchronize_rcu(rlock); OPENSSL_free(rlock->qp_group); /* There should only be a single qp left now */ OPENSSL_free(rlock); } 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); # 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 (!ossl_assert(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 (!ossl_assert(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_add64(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_add_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_add_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_and(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_and_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_and_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_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_ACQ_REL) && !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; } int CRYPTO_atomic_store(uint64_t *dst, uint64_t val, CRYPTO_RWLOCK *lock) { # if defined(__GNUC__) && defined(__ATOMIC_ACQ_REL) && !defined(BROKEN_CLANG_ATOMICS) if (__atomic_is_lock_free(sizeof(*dst), dst)) { __atomic_store(dst, &val, __ATOMIC_RELEASE); return 1; } # elif defined(__sun) && (defined(__SunOS_5_10) || defined(__SunOS_5_11)) /* This will work for all future Solaris versions. */ if (dst != NULL) { atomic_swap_64(dst, val); return 1; } # endif if (lock == NULL || !CRYPTO_THREAD_write_lock(lock)) return 0; *dst = val; if (!CRYPTO_THREAD_unlock(lock)) return 0; return 1; } int CRYPTO_atomic_load_int(int *val, int *ret, CRYPTO_RWLOCK *lock) { # if defined(__GNUC__) && defined(__ATOMIC_ACQ_REL) && !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 = (int)atomic_or_uint_nv((unsigned int *)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/t_x509.c b/crypto/x509/t_x509.c index 7d693669cd36..d849e642ce8b 100644 --- a/crypto/x509/t_x509.c +++ b/crypto/x509/t_x509.c @@ -1,551 +1,552 @@ /* * Copyright 1995-2025 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/asn1.h" #include "crypto/x509.h" void OSSL_STACK_OF_X509_free(STACK_OF(X509) *certs) { sk_X509_pop_free(certs, X509_free); } #ifndef OPENSSL_NO_STDIO int X509_print_fp(FILE *fp, X509 *x) { return X509_print_ex_fp(fp, x, XN_FLAG_COMPAT, X509_FLAG_COMPAT); } int X509_print_ex_fp(FILE *fp, X509 *x, unsigned long nmflag, unsigned long cflag) { BIO *b; int ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_BUF_LIB); return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = X509_print_ex(b, x, nmflag, cflag); BIO_free(b); return ret; } #endif int X509_print(BIO *bp, X509 *x) { return X509_print_ex(bp, x, XN_FLAG_COMPAT, X509_FLAG_COMPAT); } int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflags, unsigned long cflag) { long l; int ret = 0; char mlch = ' '; int nmindent = 0, printok = 0; EVP_PKEY *pkey = NULL; if ((nmflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) { mlch = '\n'; nmindent = 12; } if (nmflags == XN_FLAG_COMPAT) printok = 1; if (!(cflag & X509_FLAG_NO_HEADER)) { if (BIO_write(bp, "Certificate:\n", 13) <= 0) goto err; if (BIO_write(bp, " Data:\n", 10) <= 0) goto err; } if (!(cflag & X509_FLAG_NO_VERSION)) { l = X509_get_version(x); if (l >= X509_VERSION_1 && l <= X509_VERSION_3) { if (BIO_printf(bp, "%8sVersion: %ld (0x%lx)\n", "", l + 1, (unsigned long)l) <= 0) goto err; } else { if (BIO_printf(bp, "%8sVersion: Unknown (%ld)\n", "", l) <= 0) goto err; } } if (!(cflag & X509_FLAG_NO_SERIAL)) { const ASN1_INTEGER *bs = X509_get0_serialNumber(x); if (BIO_write(bp, " Serial Number:", 22) <= 0) goto err; if (ossl_serial_number_print(bp, bs, 12) != 0) goto err; if (BIO_puts(bp, "\n") <= 0) goto err; } if (!(cflag & X509_FLAG_NO_SIGNAME)) { const X509_ALGOR *tsig_alg = X509_get0_tbs_sigalg(x); if (BIO_puts(bp, " ") <= 0) goto err; if (X509_signature_print(bp, tsig_alg, NULL) <= 0) goto err; } if (!(cflag & X509_FLAG_NO_ISSUER)) { if (BIO_printf(bp, " Issuer:%c", mlch) <= 0) goto err; if (X509_NAME_print_ex(bp, X509_get_issuer_name(x), nmindent, nmflags) < printok) goto err; if (BIO_write(bp, "\n", 1) <= 0) goto err; } if (!(cflag & X509_FLAG_NO_VALIDITY)) { if (BIO_write(bp, " Validity\n", 17) <= 0) goto err; if (BIO_write(bp, " Not Before: ", 24) <= 0) goto err; if (ossl_asn1_time_print_ex(bp, X509_get0_notBefore(x), ASN1_DTFLGS_RFC822) == 0) goto err; if (BIO_write(bp, "\n Not After : ", 25) <= 0) goto err; if (ossl_asn1_time_print_ex(bp, X509_get0_notAfter(x), ASN1_DTFLGS_RFC822) == 0) goto err; if (BIO_write(bp, "\n", 1) <= 0) goto err; } if (!(cflag & X509_FLAG_NO_SUBJECT)) { if (BIO_printf(bp, " Subject:%c", mlch) <= 0) goto err; if (X509_NAME_print_ex (bp, X509_get_subject_name(x), nmindent, nmflags) < printok) goto err; if (BIO_write(bp, "\n", 1) <= 0) goto err; } if (!(cflag & X509_FLAG_NO_PUBKEY)) { X509_PUBKEY *xpkey = X509_get_X509_PUBKEY(x); ASN1_OBJECT *xpoid; X509_PUBKEY_get0_param(&xpoid, NULL, NULL, NULL, xpkey); if (BIO_write(bp, " Subject Public Key Info:\n", 33) <= 0) goto err; if (BIO_printf(bp, "%12sPublic Key Algorithm: ", "") <= 0) goto err; if (i2a_ASN1_OBJECT(bp, xpoid) <= 0) goto err; if (BIO_puts(bp, "\n") <= 0) goto err; pkey = X509_get0_pubkey(x); if (pkey == NULL) { BIO_printf(bp, "%12sUnable to load Public Key\n", ""); ERR_print_errors(bp); } else { EVP_PKEY_print_public(bp, pkey, 16, NULL); } } if (!(cflag & X509_FLAG_NO_IDS)) { const ASN1_BIT_STRING *iuid, *suid; X509_get0_uids(x, &iuid, &suid); if (iuid != NULL) { if (BIO_printf(bp, "%8sIssuer Unique ID: ", "") <= 0) goto err; if (!X509_signature_dump(bp, iuid, 12)) goto err; } if (suid != NULL) { if (BIO_printf(bp, "%8sSubject Unique ID: ", "") <= 0) goto err; if (!X509_signature_dump(bp, suid, 12)) goto err; } } if (!(cflag & X509_FLAG_NO_EXTENSIONS) && !X509V3_extensions_print(bp, "X509v3 extensions", X509_get0_extensions(x), cflag, 8)) goto err; if (!(cflag & X509_FLAG_NO_SIGDUMP)) { const X509_ALGOR *sig_alg; const ASN1_BIT_STRING *sig; X509_get0_signature(&sig, &sig_alg, x); if (X509_signature_print(bp, sig_alg, sig) <= 0) goto err; } if (!(cflag & X509_FLAG_NO_AUX)) { if (!X509_aux_print(bp, x, 0)) goto err; } ret = 1; err: return ret; } int X509_ocspid_print(BIO *bp, X509 *x) { unsigned char *der = NULL; unsigned char *dertmp; int derlen; int i; unsigned char SHA1md[SHA_DIGEST_LENGTH]; ASN1_BIT_STRING *keybstr; const X509_NAME *subj; EVP_MD *md = NULL; if (x == NULL || bp == NULL) return 0; /* * display the hash of the subject as it would appear in OCSP requests */ if (BIO_printf(bp, " Subject OCSP hash: ") <= 0) goto err; subj = X509_get_subject_name(x); derlen = i2d_X509_NAME(subj, NULL); if (derlen <= 0) goto err; if ((der = dertmp = OPENSSL_malloc(derlen)) == NULL) goto err; - i2d_X509_NAME(subj, &dertmp); + if (i2d_X509_NAME(subj, &dertmp) < 0) + goto err; md = EVP_MD_fetch(x->libctx, SN_sha1, x->propq); if (md == NULL) goto err; if (!EVP_Digest(der, derlen, SHA1md, NULL, md, NULL)) goto err; for (i = 0; i < SHA_DIGEST_LENGTH; i++) { if (BIO_printf(bp, "%02X", SHA1md[i]) <= 0) goto err; } OPENSSL_free(der); der = NULL; /* * display the hash of the public key as it would appear in OCSP requests */ if (BIO_printf(bp, "\n Public key OCSP hash: ") <= 0) goto err; keybstr = X509_get0_pubkey_bitstr(x); if (keybstr == NULL) goto err; if (!EVP_Digest(ASN1_STRING_get0_data(keybstr), ASN1_STRING_length(keybstr), SHA1md, NULL, md, NULL)) goto err; for (i = 0; i < SHA_DIGEST_LENGTH; i++) { if (BIO_printf(bp, "%02X", SHA1md[i]) <= 0) goto err; } BIO_printf(bp, "\n"); EVP_MD_free(md); return 1; err: OPENSSL_free(der); EVP_MD_free(md); return 0; } int X509_signature_dump(BIO *bp, const ASN1_STRING *sig, int indent) { const unsigned char *s; int i, n; n = sig->length; s = sig->data; for (i = 0; i < n; i++) { if ((i % 18) == 0) { if (i > 0 && BIO_write(bp, "\n", 1) <= 0) return 0; if (BIO_indent(bp, indent, indent) <= 0) return 0; } if (BIO_printf(bp, "%02x%s", s[i], ((i + 1) == n) ? "" : ":") <= 0) return 0; } if (BIO_write(bp, "\n", 1) != 1) return 0; return 1; } int X509_signature_print(BIO *bp, const X509_ALGOR *sigalg, const ASN1_STRING *sig) { int sig_nid; int indent = 4; if (BIO_printf(bp, "%*sSignature Algorithm: ", indent, "") <= 0) return 0; if (i2a_ASN1_OBJECT(bp, sigalg->algorithm) <= 0) return 0; if (sig && BIO_printf(bp, "\n%*sSignature Value:", indent, "") <= 0) return 0; sig_nid = OBJ_obj2nid(sigalg->algorithm); if (sig_nid != NID_undef) { int pkey_nid, dig_nid; const EVP_PKEY_ASN1_METHOD *ameth; if (OBJ_find_sigid_algs(sig_nid, &dig_nid, &pkey_nid)) { ameth = EVP_PKEY_asn1_find(NULL, pkey_nid); if (ameth && ameth->sig_print) return ameth->sig_print(bp, sigalg, sig, indent + 4, 0); } } if (BIO_write(bp, "\n", 1) != 1) return 0; if (sig) return X509_signature_dump(bp, sig, indent + 4); return 1; } int X509_aux_print(BIO *out, X509 *x, int indent) { char oidstr[80], first; STACK_OF(ASN1_OBJECT) *trust, *reject; const unsigned char *alias, *keyid; int keyidlen; int i; if (X509_trusted(x) == 0) return 1; trust = X509_get0_trust_objects(x); reject = X509_get0_reject_objects(x); if (trust) { first = 1; BIO_printf(out, "%*sTrusted Uses:\n%*s", indent, "", indent + 2, ""); for (i = 0; i < sk_ASN1_OBJECT_num(trust); i++) { if (!first) BIO_puts(out, ", "); else first = 0; OBJ_obj2txt(oidstr, sizeof(oidstr), sk_ASN1_OBJECT_value(trust, i), 0); BIO_puts(out, oidstr); } BIO_puts(out, "\n"); } else BIO_printf(out, "%*sNo Trusted Uses.\n", indent, ""); if (reject) { first = 1; BIO_printf(out, "%*sRejected Uses:\n%*s", indent, "", indent + 2, ""); for (i = 0; i < sk_ASN1_OBJECT_num(reject); i++) { if (!first) BIO_puts(out, ", "); else first = 0; OBJ_obj2txt(oidstr, sizeof(oidstr), sk_ASN1_OBJECT_value(reject, i), 0); BIO_puts(out, oidstr); } BIO_puts(out, "\n"); } else BIO_printf(out, "%*sNo Rejected Uses.\n", indent, ""); alias = X509_alias_get0(x, &i); if (alias) BIO_printf(out, "%*sAlias: %.*s\n", indent, "", i, alias); keyid = X509_keyid_get0(x, &keyidlen); if (keyid) { BIO_printf(out, "%*sKey Id: ", indent, ""); for (i = 0; i < keyidlen; i++) BIO_printf(out, "%s%02X", i ? ":" : "", keyid[i]); BIO_write(out, "\n", 1); } return 1; } /* * Helper functions for improving certificate verification error diagnostics */ int ossl_x509_print_ex_brief(BIO *bio, X509 *cert, unsigned long neg_cflags) { unsigned long flags = ASN1_STRFLGS_RFC2253 | ASN1_STRFLGS_ESC_QUOTE | XN_FLAG_SEP_CPLUS_SPC | XN_FLAG_FN_SN; if (cert == NULL) return BIO_printf(bio, " (no certificate)\n") > 0; if (BIO_printf(bio, " certificate\n") <= 0 || !X509_print_ex(bio, cert, flags, ~X509_FLAG_NO_SUBJECT)) return 0; if (X509_check_issued((X509 *)cert, cert) == X509_V_OK) { if (BIO_printf(bio, " self-issued\n") <= 0) return 0; } else { if (BIO_printf(bio, " ") <= 0 || !X509_print_ex(bio, cert, flags, ~X509_FLAG_NO_ISSUER)) return 0; } if (!X509_print_ex(bio, cert, flags, ~(X509_FLAG_NO_SERIAL | X509_FLAG_NO_VALIDITY))) return 0; if (X509_cmp_current_time(X509_get0_notBefore(cert)) > 0) if (BIO_printf(bio, " not yet valid\n") <= 0) return 0; if (X509_cmp_current_time(X509_get0_notAfter(cert)) < 0) if (BIO_printf(bio, " no more valid\n") <= 0) return 0; return X509_print_ex(bio, cert, flags, ~neg_cflags & ~X509_FLAG_EXTENSIONS_ONLY_KID); } static int print_certs(BIO *bio, const STACK_OF(X509) *certs) { int i; if (certs == NULL || sk_X509_num(certs) <= 0) return BIO_printf(bio, " (no certificates)\n") >= 0; for (i = 0; i < sk_X509_num(certs); i++) { X509 *cert = sk_X509_value(certs, i); if (cert != NULL) { if (!ossl_x509_print_ex_brief(bio, cert, 0)) return 0; if (!X509V3_extensions_print(bio, NULL, X509_get0_extensions(cert), X509_FLAG_EXTENSIONS_ONLY_KID, 8)) return 0; } } return 1; } static int print_store_certs(BIO *bio, X509_STORE *store) { if (store != NULL) { STACK_OF(X509) *certs = X509_STORE_get1_all_certs(store); int ret = print_certs(bio, certs); OSSL_STACK_OF_X509_free(certs); return ret; } else { return BIO_printf(bio, " (no trusted store)\n") >= 0; } } /* Extend the error queue with details on a failed cert verification */ int X509_STORE_CTX_print_verify_cb(int ok, X509_STORE_CTX *ctx) { if (ok == 0 && ctx != NULL) { int cert_error = X509_STORE_CTX_get_error(ctx); BIO *bio = BIO_new(BIO_s_mem()); /* may be NULL */ if (bio == NULL) return 0; BIO_printf(bio, "%s at depth = %d error = %d (%s)\n", X509_STORE_CTX_get0_parent_ctx(ctx) != NULL ? "CRL path validation" : "Certificate verification", X509_STORE_CTX_get_error_depth(ctx), cert_error, X509_verify_cert_error_string(cert_error)); { X509_STORE *ts = X509_STORE_CTX_get0_store(ctx); X509_VERIFY_PARAM *vpm = X509_STORE_get0_param(ts); char *str; int idx = 0; switch (cert_error) { case X509_V_ERR_HOSTNAME_MISMATCH: BIO_printf(bio, "Expected hostname(s) = "); while ((str = X509_VERIFY_PARAM_get0_host(vpm, idx++)) != NULL) BIO_printf(bio, "%s%s", idx == 1 ? "" : ", ", str); BIO_printf(bio, "\n"); break; case X509_V_ERR_EMAIL_MISMATCH: str = X509_VERIFY_PARAM_get0_email(vpm); if (str != NULL) BIO_printf(bio, "Expected email address = %s\n", str); break; case X509_V_ERR_IP_ADDRESS_MISMATCH: str = X509_VERIFY_PARAM_get1_ip_asc(vpm); if (str != NULL) BIO_printf(bio, "Expected IP address = %s\n", str); OPENSSL_free(str); break; default: break; } } BIO_printf(bio, "Failure for:\n"); ossl_x509_print_ex_brief(bio, X509_STORE_CTX_get_current_cert(ctx), X509_FLAG_NO_EXTENSIONS); if (cert_error == X509_V_ERR_CERT_UNTRUSTED || cert_error == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT || cert_error == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN || cert_error == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT || cert_error == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY || cert_error == X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER || cert_error == X509_V_ERR_STORE_LOOKUP) { BIO_printf(bio, "Non-trusted certs:\n"); print_certs(bio, X509_STORE_CTX_get0_untrusted(ctx)); BIO_printf(bio, "Certs in trust store:\n"); print_store_certs(bio, X509_STORE_CTX_get0_store(ctx)); } ERR_raise(ERR_LIB_X509, X509_R_CERTIFICATE_VERIFICATION_FAILED); ERR_add_error_mem_bio("\n", bio); BIO_free(bio); } return ok; } /* * Prints serial numbers in decimal and hexadecimal. The indent argument is only * used if the serial number is too large to fit in an int64_t. */ int ossl_serial_number_print(BIO *out, const ASN1_INTEGER *bs, int indent) { int i, ok; int64_t l; uint64_t ul; const char *neg; if (bs->length == 0) { if (BIO_puts(out, " (Empty)") <= 0) return -1; return 0; } ERR_set_mark(); ok = ASN1_INTEGER_get_int64(&l, bs); ERR_pop_to_mark(); if (ok) { /* Reading an int64_t succeeded: print decimal and hex. */ if (bs->type == V_ASN1_NEG_INTEGER) { ul = 0 - (uint64_t)l; neg = "-"; } else { ul = l; neg = ""; } if (BIO_printf(out, " %s%ju (%s0x%jx)", neg, ul, neg, ul) <= 0) return -1; } else { /* Reading an int64_t failed: just print hex. */ neg = (bs->type == V_ASN1_NEG_INTEGER) ? " (Negative)" : ""; if (BIO_printf(out, "\n%*s%s", indent, "", neg) <= 0) return -1; for (i = 0; i < bs->length - 1; i++) { if (BIO_printf(out, "%02x%c", bs->data[i], ':') <= 0) return -1; } if (BIO_printf(out, "%02x", bs->data[i]) <= 0) return -1; } return 0; } diff --git a/crypto/x509/x509_lu.c b/crypto/x509/x509_lu.c index 05ee7c8c6b51..eb2d47955b2e 100644 --- a/crypto/x509/x509_lu.c +++ b/crypto/x509/x509_lu.c @@ -1,954 +1,953 @@ /* * Copyright 1995-2025 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 "internal/refcount.h" #include #include "crypto/x509.h" #include #include "x509_local.h" X509_LOOKUP *X509_LOOKUP_new(X509_LOOKUP_METHOD *method) { X509_LOOKUP *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; ret->method = method; if (method->new_item != NULL && method->new_item(ret) == 0) { OPENSSL_free(ret); return NULL; } return ret; } void X509_LOOKUP_free(X509_LOOKUP *ctx) { if (ctx == NULL) return; if ((ctx->method != NULL) && (ctx->method->free != NULL)) (*ctx->method->free) (ctx); OPENSSL_free(ctx); } int X509_STORE_lock(X509_STORE *xs) { return CRYPTO_THREAD_write_lock(xs->lock); } int ossl_x509_store_read_lock(X509_STORE *xs) { return CRYPTO_THREAD_read_lock(xs->lock); } int X509_STORE_unlock(X509_STORE *xs) { return CRYPTO_THREAD_unlock(xs->lock); } int X509_LOOKUP_init(X509_LOOKUP *ctx) { if (ctx->method == NULL) return 0; if (ctx->method->init != NULL) return ctx->method->init(ctx); else return 1; } int X509_LOOKUP_shutdown(X509_LOOKUP *ctx) { if (ctx->method == NULL) return 0; if (ctx->method->shutdown != NULL) return ctx->method->shutdown(ctx); else return 1; } int X509_LOOKUP_ctrl_ex(X509_LOOKUP *ctx, int cmd, const char *argc, long argl, char **ret, OSSL_LIB_CTX *libctx, const char *propq) { if (ctx->method == NULL) return -1; if (ctx->method->ctrl_ex != NULL) return ctx->method->ctrl_ex(ctx, cmd, argc, argl, ret, libctx, propq); if (ctx->method->ctrl != NULL) return ctx->method->ctrl(ctx, cmd, argc, argl, ret); return 1; } int X509_LOOKUP_ctrl(X509_LOOKUP *ctx, int cmd, const char *argc, long argl, char **ret) { return X509_LOOKUP_ctrl_ex(ctx, cmd, argc, argl, ret, NULL, NULL); } int X509_LOOKUP_by_subject_ex(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type, const X509_NAME *name, X509_OBJECT *ret, OSSL_LIB_CTX *libctx, const char *propq) { if (ctx->skip || ctx->method == NULL || (ctx->method->get_by_subject == NULL && ctx->method->get_by_subject_ex == NULL)) return 0; if (ctx->method->get_by_subject_ex != NULL) return ctx->method->get_by_subject_ex(ctx, type, name, ret, libctx, propq); else return ctx->method->get_by_subject(ctx, type, name, ret); } int X509_LOOKUP_by_subject(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type, const X509_NAME *name, X509_OBJECT *ret) { return X509_LOOKUP_by_subject_ex(ctx, type, name, ret, NULL, NULL); } int X509_LOOKUP_by_issuer_serial(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type, const X509_NAME *name, const ASN1_INTEGER *serial, X509_OBJECT *ret) { if ((ctx->method == NULL) || (ctx->method->get_by_issuer_serial == NULL)) return 0; return ctx->method->get_by_issuer_serial(ctx, type, name, serial, ret); } int X509_LOOKUP_by_fingerprint(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type, const unsigned char *bytes, int len, X509_OBJECT *ret) { if ((ctx->method == NULL) || (ctx->method->get_by_fingerprint == NULL)) return 0; return ctx->method->get_by_fingerprint(ctx, type, bytes, len, ret); } int X509_LOOKUP_by_alias(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type, const char *str, int len, X509_OBJECT *ret) { if ((ctx->method == NULL) || (ctx->method->get_by_alias == NULL)) return 0; return ctx->method->get_by_alias(ctx, type, str, len, ret); } int X509_LOOKUP_set_method_data(X509_LOOKUP *ctx, void *data) { ctx->method_data = data; return 1; } void *X509_LOOKUP_get_method_data(const X509_LOOKUP *ctx) { return ctx->method_data; } X509_STORE *X509_LOOKUP_get_store(const X509_LOOKUP *ctx) { return ctx->store_ctx; } static int x509_object_cmp(const X509_OBJECT *const *a, const X509_OBJECT *const *b) { int ret; ret = ((*a)->type - (*b)->type); if (ret) return ret; switch ((*a)->type) { case X509_LU_X509: ret = X509_subject_name_cmp((*a)->data.x509, (*b)->data.x509); break; case X509_LU_CRL: ret = X509_CRL_cmp((*a)->data.crl, (*b)->data.crl); break; case X509_LU_NONE: /* abort(); */ return 0; } return ret; } X509_STORE *X509_STORE_new(void) { X509_STORE *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; if ((ret->objs = sk_X509_OBJECT_new(x509_object_cmp)) == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); goto err; } ret->cache = 1; if ((ret->get_cert_methods = sk_X509_LOOKUP_new_null()) == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); goto err; } if ((ret->param = X509_VERIFY_PARAM_new()) == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB); goto err; } if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE, ret, &ret->ex_data)) { ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); goto err; } ret->lock = CRYPTO_THREAD_lock_new(); if (ret->lock == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); goto err; } if (!CRYPTO_NEW_REF(&ret->references, 1)) goto err; return ret; err: X509_VERIFY_PARAM_free(ret->param); sk_X509_OBJECT_free(ret->objs); sk_X509_LOOKUP_free(ret->get_cert_methods); CRYPTO_THREAD_lock_free(ret->lock); OPENSSL_free(ret); return NULL; } void X509_STORE_free(X509_STORE *xs) { int i; STACK_OF(X509_LOOKUP) *sk; X509_LOOKUP *lu; if (xs == NULL) return; CRYPTO_DOWN_REF(&xs->references, &i); REF_PRINT_COUNT("X509_STORE", i, xs); if (i > 0) return; REF_ASSERT_ISNT(i < 0); sk = xs->get_cert_methods; for (i = 0; i < sk_X509_LOOKUP_num(sk); i++) { lu = sk_X509_LOOKUP_value(sk, i); X509_LOOKUP_shutdown(lu); X509_LOOKUP_free(lu); } sk_X509_LOOKUP_free(sk); sk_X509_OBJECT_pop_free(xs->objs, X509_OBJECT_free); CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509_STORE, xs, &xs->ex_data); X509_VERIFY_PARAM_free(xs->param); CRYPTO_THREAD_lock_free(xs->lock); CRYPTO_FREE_REF(&xs->references); OPENSSL_free(xs); } int X509_STORE_up_ref(X509_STORE *xs) { int i; if (CRYPTO_UP_REF(&xs->references, &i) <= 0) return 0; REF_PRINT_COUNT("X509_STORE", i, xs); REF_ASSERT_ISNT(i < 2); return i > 1 ? 1 : 0; } X509_LOOKUP *X509_STORE_add_lookup(X509_STORE *xs, X509_LOOKUP_METHOD *m) { int i; STACK_OF(X509_LOOKUP) *sk; X509_LOOKUP *lu; sk = xs->get_cert_methods; for (i = 0; i < sk_X509_LOOKUP_num(sk); i++) { lu = sk_X509_LOOKUP_value(sk, i); if (m == lu->method) { return lu; } } /* a new one */ lu = X509_LOOKUP_new(m); if (lu == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB); return NULL; } lu->store_ctx = xs; if (sk_X509_LOOKUP_push(xs->get_cert_methods, lu)) return lu; /* sk_X509_LOOKUP_push() failed */ ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB); X509_LOOKUP_free(lu); return NULL; } /* Also fill the cache (ctx->store->objs) with all matching certificates. */ X509_OBJECT *X509_STORE_CTX_get_obj_by_subject(X509_STORE_CTX *ctx, X509_LOOKUP_TYPE type, const X509_NAME *name) { X509_OBJECT *ret = X509_OBJECT_new(); if (ret == NULL) return NULL; if (!X509_STORE_CTX_get_by_subject(ctx, type, name, ret)) { X509_OBJECT_free(ret); return NULL; } return ret; } /* * May be called with |ret| == NULL just for the side effect of * caching all certs matching the given subject DN in |ctx->store->objs|. * Returns 1 if successful, * 0 if not found or X509_LOOKUP_by_subject_ex() returns an error, * -1 on failure */ int ossl_x509_store_ctx_get_by_subject(const X509_STORE_CTX *ctx, X509_LOOKUP_TYPE type, const X509_NAME *name, X509_OBJECT *ret) { X509_STORE *store = ctx->store; X509_LOOKUP *lu; X509_OBJECT stmp, *tmp; int i, j; if (store == NULL) return 0; stmp.type = X509_LU_NONE; stmp.data.x509 = NULL; if (!ossl_x509_store_read_lock(store)) return 0; /* Should already be sorted...but just in case */ if (!sk_X509_OBJECT_is_sorted(store->objs)) { X509_STORE_unlock(store); /* Take a write lock instead of a read lock */ if (!X509_STORE_lock(store)) return 0; /* * Another thread might have sorted it in the meantime. But if so, * sk_X509_OBJECT_sort() exits early. */ sk_X509_OBJECT_sort(store->objs); } tmp = X509_OBJECT_retrieve_by_subject(store->objs, type, name); X509_STORE_unlock(store); if (tmp == NULL || type == X509_LU_CRL) { for (i = 0; i < sk_X509_LOOKUP_num(store->get_cert_methods); i++) { lu = sk_X509_LOOKUP_value(store->get_cert_methods, i); if (lu->skip) continue; if (lu->method == NULL) return -1; j = X509_LOOKUP_by_subject_ex(lu, type, name, &stmp, ctx->libctx, ctx->propq); if (j != 0) { /* non-zero value is considered success here */ tmp = &stmp; break; } } if (tmp == NULL) return 0; } if (ret != NULL) { if (!X509_OBJECT_up_ref_count(tmp)) return -1; ret->type = tmp->type; ret->data = tmp->data; } return 1; } /* Also fill the cache |ctx->store->objs| with all matching certificates. */ int X509_STORE_CTX_get_by_subject(const X509_STORE_CTX *ctx, X509_LOOKUP_TYPE type, const X509_NAME *name, X509_OBJECT *ret) { return ossl_x509_store_ctx_get_by_subject(ctx, type, name, ret) > 0; } static int x509_store_add(X509_STORE *store, void *x, int crl) { X509_OBJECT *obj; int ret = 0, added = 0; if (x == NULL) return 0; obj = X509_OBJECT_new(); if (obj == NULL) return 0; if (crl) { obj->type = X509_LU_CRL; obj->data.crl = (X509_CRL *)x; } else { obj->type = X509_LU_X509; obj->data.x509 = (X509 *)x; } if (!X509_OBJECT_up_ref_count(obj)) { obj->type = X509_LU_NONE; X509_OBJECT_free(obj); return 0; } if (!X509_STORE_lock(store)) { - obj->type = X509_LU_NONE; X509_OBJECT_free(obj); return 0; } if (X509_OBJECT_retrieve_match(store->objs, obj)) { ret = 1; } else { added = sk_X509_OBJECT_push(store->objs, obj); ret = added != 0; } X509_STORE_unlock(store); if (added == 0) /* obj not pushed */ X509_OBJECT_free(obj); return ret; } int X509_STORE_add_cert(X509_STORE *xs, X509 *x) { if (!x509_store_add(xs, x, 0)) { ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB); return 0; } return 1; } int X509_STORE_add_crl(X509_STORE *xs, X509_CRL *x) { if (!x509_store_add(xs, x, 1)) { ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB); return 0; } return 1; } int X509_OBJECT_up_ref_count(X509_OBJECT *a) { switch (a->type) { case X509_LU_NONE: break; case X509_LU_X509: return X509_up_ref(a->data.x509); case X509_LU_CRL: return X509_CRL_up_ref(a->data.crl); } return 1; } X509 *X509_OBJECT_get0_X509(const X509_OBJECT *a) { if (a == NULL || a->type != X509_LU_X509) return NULL; return a->data.x509; } X509_CRL *X509_OBJECT_get0_X509_CRL(const X509_OBJECT *a) { if (a == NULL || a->type != X509_LU_CRL) return NULL; return a->data.crl; } X509_LOOKUP_TYPE X509_OBJECT_get_type(const X509_OBJECT *a) { return a->type; } X509_OBJECT *X509_OBJECT_new(void) { X509_OBJECT *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; ret->type = X509_LU_NONE; return ret; } static void x509_object_free_internal(X509_OBJECT *a) { if (a == NULL) return; switch (a->type) { case X509_LU_NONE: break; case X509_LU_X509: X509_free(a->data.x509); break; case X509_LU_CRL: X509_CRL_free(a->data.crl); break; } } int X509_OBJECT_set1_X509(X509_OBJECT *a, X509 *obj) { if (a == NULL || !X509_up_ref(obj)) return 0; x509_object_free_internal(a); a->type = X509_LU_X509; a->data.x509 = obj; return 1; } int X509_OBJECT_set1_X509_CRL(X509_OBJECT *a, X509_CRL *obj) { if (a == NULL || !X509_CRL_up_ref(obj)) return 0; x509_object_free_internal(a); a->type = X509_LU_CRL; a->data.crl = obj; return 1; } void X509_OBJECT_free(X509_OBJECT *a) { x509_object_free_internal(a); OPENSSL_free(a); } /* Returns -1 if not found, but also on error */ static int x509_object_idx_cnt(STACK_OF(X509_OBJECT) *h, X509_LOOKUP_TYPE type, const X509_NAME *name, int *pnmatch) { X509_OBJECT stmp; X509 x509_s; X509_CRL crl_s; stmp.type = type; switch (type) { case X509_LU_X509: stmp.data.x509 = &x509_s; x509_s.cert_info.subject = (X509_NAME *)name; /* won't modify it */ break; case X509_LU_CRL: stmp.data.crl = &crl_s; crl_s.crl.issuer = (X509_NAME *)name; /* won't modify it */ break; case X509_LU_NONE: default: /* abort(); */ return -1; } /* Assumes h is locked for read if applicable */ return sk_X509_OBJECT_find_all(h, &stmp, pnmatch); } /* Assumes h is locked for read if applicable */ int X509_OBJECT_idx_by_subject(STACK_OF(X509_OBJECT) *h, X509_LOOKUP_TYPE type, const X509_NAME *name) { return x509_object_idx_cnt(h, type, name, NULL); } /* Assumes h is locked for read if applicable */ X509_OBJECT *X509_OBJECT_retrieve_by_subject(STACK_OF(X509_OBJECT) *h, X509_LOOKUP_TYPE type, const X509_NAME *name) { int idx = X509_OBJECT_idx_by_subject(h, type, name); if (idx == -1) return NULL; return sk_X509_OBJECT_value(h, idx); } STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(const X509_STORE *xs) { return xs->objs; } static X509_OBJECT *x509_object_dup(const X509_OBJECT *obj) { X509_OBJECT *ret = X509_OBJECT_new(); if (ret == NULL) return NULL; ret->type = obj->type; ret->data = obj->data; X509_OBJECT_up_ref_count(ret); return ret; } STACK_OF(X509_OBJECT) *X509_STORE_get1_objects(X509_STORE *store) { STACK_OF(X509_OBJECT) *objs; if (store == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (!ossl_x509_store_read_lock(store)) return NULL; objs = sk_X509_OBJECT_deep_copy(store->objs, x509_object_dup, X509_OBJECT_free); X509_STORE_unlock(store); return objs; } STACK_OF(X509) *X509_STORE_get1_all_certs(X509_STORE *store) { STACK_OF(X509) *sk; STACK_OF(X509_OBJECT) *objs; int i; if (store == NULL) { ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if ((sk = sk_X509_new_null()) == NULL) return NULL; if (!X509_STORE_lock(store)) goto out_free; sk_X509_OBJECT_sort(store->objs); objs = X509_STORE_get0_objects(store); for (i = 0; i < sk_X509_OBJECT_num(objs); i++) { X509 *cert = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i)); if (cert != NULL && !X509_add_cert(sk, cert, X509_ADD_FLAG_UP_REF)) goto err; } X509_STORE_unlock(store); return sk; err: X509_STORE_unlock(store); out_free: OSSL_STACK_OF_X509_free(sk); return NULL; } /*- * Collect from |ctx->store| all certs with subject matching |nm|. * Returns NULL on internal/fatal error, empty stack if not found. */ STACK_OF(X509) *X509_STORE_CTX_get1_certs(X509_STORE_CTX *ctx, const X509_NAME *nm) { int i, idx, cnt; STACK_OF(X509) *sk = NULL; X509 *x; X509_OBJECT *obj; X509_STORE *store = ctx->store; if (store == NULL) return sk_X509_new_null(); if (!X509_STORE_lock(store)) return NULL; sk_X509_OBJECT_sort(store->objs); idx = x509_object_idx_cnt(store->objs, X509_LU_X509, nm, &cnt); if (idx < 0) { /* * Nothing found in cache: do lookup to possibly add new objects to * cache */ X509_STORE_unlock(store); i = ossl_x509_store_ctx_get_by_subject(ctx, X509_LU_X509, nm, NULL); if (i <= 0) return i < 0 ? NULL : sk_X509_new_null(); if (!X509_STORE_lock(store)) return NULL; sk_X509_OBJECT_sort(store->objs); idx = x509_object_idx_cnt(store->objs, X509_LU_X509, nm, &cnt); } sk = sk_X509_new_null(); if (idx < 0 || sk == NULL) goto end; for (i = 0; i < cnt; i++, idx++) { obj = sk_X509_OBJECT_value(store->objs, idx); x = obj->data.x509; if (!X509_add_cert(sk, x, X509_ADD_FLAG_UP_REF)) { X509_STORE_unlock(store); OSSL_STACK_OF_X509_free(sk); return NULL; } } end: X509_STORE_unlock(store); return sk; } /* Returns NULL on internal/fatal error, empty stack if not found */ STACK_OF(X509_CRL) *X509_STORE_CTX_get1_crls(const X509_STORE_CTX *ctx, const X509_NAME *nm) { int i = 1, idx, cnt; STACK_OF(X509_CRL) *sk; X509_CRL *x; X509_OBJECT *obj; X509_STORE *store = ctx->store; /* Always do lookup to possibly add new CRLs to cache */ i = ossl_x509_store_ctx_get_by_subject(ctx, X509_LU_CRL, nm, NULL); if (i < 0) return NULL; sk = sk_X509_CRL_new_null(); if (i == 0) return sk; if (!X509_STORE_lock(store)) { sk_X509_CRL_free(sk); return NULL; } sk_X509_OBJECT_sort(store->objs); idx = x509_object_idx_cnt(store->objs, X509_LU_CRL, nm, &cnt); if (idx < 0) { X509_STORE_unlock(store); return sk; } for (i = 0; i < cnt; i++, idx++) { obj = sk_X509_OBJECT_value(store->objs, idx); x = obj->data.crl; if (!X509_CRL_up_ref(x)) { X509_STORE_unlock(store); sk_X509_CRL_pop_free(sk, X509_CRL_free); return NULL; } if (!sk_X509_CRL_push(sk, x)) { X509_STORE_unlock(store); X509_CRL_free(x); sk_X509_CRL_pop_free(sk, X509_CRL_free); return NULL; } } X509_STORE_unlock(store); return sk; } X509_OBJECT *X509_OBJECT_retrieve_match(STACK_OF(X509_OBJECT) *h, X509_OBJECT *x) { int idx, i, num; X509_OBJECT *obj; idx = sk_X509_OBJECT_find(h, x); if (idx < 0) return NULL; if ((x->type != X509_LU_X509) && (x->type != X509_LU_CRL)) return sk_X509_OBJECT_value(h, idx); for (i = idx, num = sk_X509_OBJECT_num(h); i < num; i++) { obj = sk_X509_OBJECT_value(h, i); if (x509_object_cmp((const X509_OBJECT **)&obj, (const X509_OBJECT **)&x)) return NULL; if (x->type == X509_LU_X509) { if (!X509_cmp(obj->data.x509, x->data.x509)) return obj; } else if (x->type == X509_LU_CRL) { if (X509_CRL_match(obj->data.crl, x->data.crl) == 0) return obj; } else { return obj; } } return NULL; } int X509_STORE_set_flags(X509_STORE *xs, unsigned long flags) { return X509_VERIFY_PARAM_set_flags(xs->param, flags); } int X509_STORE_set_depth(X509_STORE *xs, int depth) { X509_VERIFY_PARAM_set_depth(xs->param, depth); return 1; } int X509_STORE_set_purpose(X509_STORE *xs, int purpose) { return X509_VERIFY_PARAM_set_purpose(xs->param, purpose); } int X509_STORE_set_trust(X509_STORE *xs, int trust) { return X509_VERIFY_PARAM_set_trust(xs->param, trust); } int X509_STORE_set1_param(X509_STORE *xs, const X509_VERIFY_PARAM *param) { return X509_VERIFY_PARAM_set1(xs->param, param); } X509_VERIFY_PARAM *X509_STORE_get0_param(const X509_STORE *xs) { return xs->param; } void X509_STORE_set_verify(X509_STORE *xs, X509_STORE_CTX_verify_fn verify) { xs->verify = verify; } X509_STORE_CTX_verify_fn X509_STORE_get_verify(const X509_STORE *xs) { return xs->verify; } void X509_STORE_set_verify_cb(X509_STORE *xs, X509_STORE_CTX_verify_cb verify_cb) { xs->verify_cb = verify_cb; } X509_STORE_CTX_verify_cb X509_STORE_get_verify_cb(const X509_STORE *xs) { return xs->verify_cb; } void X509_STORE_set_get_issuer(X509_STORE *xs, X509_STORE_CTX_get_issuer_fn get_issuer) { xs->get_issuer = get_issuer; } X509_STORE_CTX_get_issuer_fn X509_STORE_get_get_issuer(const X509_STORE *xs) { return xs->get_issuer; } void X509_STORE_set_check_issued(X509_STORE *xs, X509_STORE_CTX_check_issued_fn check_issued) { xs->check_issued = check_issued; } X509_STORE_CTX_check_issued_fn X509_STORE_get_check_issued(const X509_STORE *xs) { return xs->check_issued; } void X509_STORE_set_check_revocation(X509_STORE *xs, X509_STORE_CTX_check_revocation_fn cb) { xs->check_revocation = cb; } X509_STORE_CTX_check_revocation_fn X509_STORE_get_check_revocation(const X509_STORE *xs) { return xs->check_revocation; } void X509_STORE_set_get_crl(X509_STORE *xs, X509_STORE_CTX_get_crl_fn get_crl) { xs->get_crl = get_crl; } X509_STORE_CTX_get_crl_fn X509_STORE_get_get_crl(const X509_STORE *xs) { return xs->get_crl; } void X509_STORE_set_check_crl(X509_STORE *xs, X509_STORE_CTX_check_crl_fn check_crl) { xs->check_crl = check_crl; } X509_STORE_CTX_check_crl_fn X509_STORE_get_check_crl(const X509_STORE *xs) { return xs->check_crl; } void X509_STORE_set_cert_crl(X509_STORE *xs, X509_STORE_CTX_cert_crl_fn cert_crl) { xs->cert_crl = cert_crl; } X509_STORE_CTX_cert_crl_fn X509_STORE_get_cert_crl(const X509_STORE *xs) { return xs->cert_crl; } void X509_STORE_set_check_policy(X509_STORE *xs, X509_STORE_CTX_check_policy_fn check_policy) { xs->check_policy = check_policy; } X509_STORE_CTX_check_policy_fn X509_STORE_get_check_policy(const X509_STORE *xs) { return xs->check_policy; } void X509_STORE_set_lookup_certs(X509_STORE *xs, X509_STORE_CTX_lookup_certs_fn lookup_certs) { xs->lookup_certs = lookup_certs; } X509_STORE_CTX_lookup_certs_fn X509_STORE_get_lookup_certs(const X509_STORE *xs) { return xs->lookup_certs; } void X509_STORE_set_lookup_crls(X509_STORE *xs, X509_STORE_CTX_lookup_crls_fn lookup_crls) { xs->lookup_crls = lookup_crls; } X509_STORE_CTX_lookup_crls_fn X509_STORE_get_lookup_crls(const X509_STORE *xs) { return xs->lookup_crls; } void X509_STORE_set_cleanup(X509_STORE *xs, X509_STORE_CTX_cleanup_fn cleanup) { xs->cleanup = cleanup; } X509_STORE_CTX_cleanup_fn X509_STORE_get_cleanup(const X509_STORE *xs) { return xs->cleanup; } int X509_STORE_set_ex_data(X509_STORE *xs, int idx, void *data) { return CRYPTO_set_ex_data(&xs->ex_data, idx, data); } void *X509_STORE_get_ex_data(const X509_STORE *xs, int idx) { return CRYPTO_get_ex_data(&xs->ex_data, idx); } X509_STORE *X509_STORE_CTX_get0_store(const X509_STORE_CTX *ctx) { return ctx->store; } diff --git a/doc/man3/DEFINE_STACK_OF.pod b/doc/man3/DEFINE_STACK_OF.pod index ff2074820f68..eeb882f291e4 100644 --- a/doc/man3/DEFINE_STACK_OF.pod +++ b/doc/man3/DEFINE_STACK_OF.pod @@ -1,311 +1,310 @@ =pod =head1 NAME DEFINE_STACK_OF, DEFINE_STACK_OF_CONST, DEFINE_SPECIAL_STACK_OF, DEFINE_SPECIAL_STACK_OF_CONST, sk_TYPE_num, sk_TYPE_value, sk_TYPE_new, sk_TYPE_new_null, sk_TYPE_reserve, sk_TYPE_free, sk_TYPE_zero, sk_TYPE_delete, sk_TYPE_delete_ptr, sk_TYPE_push, sk_TYPE_unshift, sk_TYPE_pop, sk_TYPE_shift, sk_TYPE_pop_free, sk_TYPE_insert, sk_TYPE_set, sk_TYPE_find, sk_TYPE_find_ex, sk_TYPE_find_all, sk_TYPE_sort, sk_TYPE_is_sorted, sk_TYPE_dup, sk_TYPE_deep_copy, sk_TYPE_set_cmp_func, sk_TYPE_new_reserve, OPENSSL_sk_deep_copy, OPENSSL_sk_delete, OPENSSL_sk_delete_ptr, OPENSSL_sk_dup, OPENSSL_sk_find, OPENSSL_sk_find_ex, OPENSSL_sk_find_all, OPENSSL_sk_free, OPENSSL_sk_insert, OPENSSL_sk_is_sorted, OPENSSL_sk_new, OPENSSL_sk_new_null, OPENSSL_sk_new_reserve, OPENSSL_sk_num, OPENSSL_sk_pop, OPENSSL_sk_pop_free, OPENSSL_sk_push, OPENSSL_sk_reserve, OPENSSL_sk_set, OPENSSL_sk_set_cmp_func, OPENSSL_sk_shift, OPENSSL_sk_sort, OPENSSL_sk_unshift, OPENSSL_sk_value, OPENSSL_sk_zero - stack container =head1 SYNOPSIS =for openssl generic #include STACK_OF(TYPE) DEFINE_STACK_OF(TYPE) DEFINE_STACK_OF_CONST(TYPE) DEFINE_SPECIAL_STACK_OF(FUNCTYPE, TYPE) DEFINE_SPECIAL_STACK_OF_CONST(FUNCTYPE, TYPE) typedef int (*sk_TYPE_compfunc)(const TYPE *const *a, const TYPE *const *b); typedef TYPE * (*sk_TYPE_copyfunc)(const TYPE *a); typedef void (*sk_TYPE_freefunc)(TYPE *a); int sk_TYPE_num(const STACK_OF(TYPE) *sk); TYPE *sk_TYPE_value(const STACK_OF(TYPE) *sk, int idx); STACK_OF(TYPE) *sk_TYPE_new(sk_TYPE_compfunc compare); STACK_OF(TYPE) *sk_TYPE_new_null(void); int sk_TYPE_reserve(STACK_OF(TYPE) *sk, int n); void sk_TYPE_free(STACK_OF(TYPE) *sk); void sk_TYPE_zero(STACK_OF(TYPE) *sk); TYPE *sk_TYPE_delete(STACK_OF(TYPE) *sk, int i); TYPE *sk_TYPE_delete_ptr(STACK_OF(TYPE) *sk, TYPE *ptr); int sk_TYPE_push(STACK_OF(TYPE) *sk, const TYPE *ptr); int sk_TYPE_unshift(STACK_OF(TYPE) *sk, const TYPE *ptr); TYPE *sk_TYPE_pop(STACK_OF(TYPE) *sk); TYPE *sk_TYPE_shift(STACK_OF(TYPE) *sk); void sk_TYPE_pop_free(STACK_OF(TYPE) *sk, sk_TYPE_freefunc freefunc); int sk_TYPE_insert(STACK_OF(TYPE) *sk, TYPE *ptr, int idx); TYPE *sk_TYPE_set(STACK_OF(TYPE) *sk, int idx, const TYPE *ptr); int sk_TYPE_find(STACK_OF(TYPE) *sk, TYPE *ptr); int sk_TYPE_find_ex(STACK_OF(TYPE) *sk, TYPE *ptr); int sk_TYPE_find_all(STACK_OF(TYPE) *sk, TYPE *ptr, int *pnum); void sk_TYPE_sort(const STACK_OF(TYPE) *sk); int sk_TYPE_is_sorted(const STACK_OF(TYPE) *sk); STACK_OF(TYPE) *sk_TYPE_dup(const STACK_OF(TYPE) *sk); STACK_OF(TYPE) *sk_TYPE_deep_copy(const STACK_OF(TYPE) *sk, sk_TYPE_copyfunc copyfunc, sk_TYPE_freefunc freefunc); sk_TYPE_compfunc (*sk_TYPE_set_cmp_func(STACK_OF(TYPE) *sk, sk_TYPE_compfunc compare)); STACK_OF(TYPE) *sk_TYPE_new_reserve(sk_TYPE_compfunc compare, int n); =head1 DESCRIPTION Applications can create and use their own stacks by placing any of the macros described below in a header file. These macros define typesafe inline functions that wrap around the utility B API. In the description here, B> is used as a placeholder for any of the OpenSSL datatypes, such as B. The STACK_OF() macro returns the name for a stack of the specified B>. This is an opaque pointer to a structure declaration. This can be used in every header file that references the stack. There are several B macros that create static inline functions for all of the functions described on this page. This should normally be used in one source file, and the stack manipulation is wrapped with application-specific functions. DEFINE_STACK_OF() creates set of functions for a stack of B> elements. The type is referenced by B(B>) and each function name begins with B_>. DEFINE_STACK_OF_CONST() is identical to DEFINE_STACK_OF() except each element is constant. /* DEFINE_STACK_OF(TYPE) */ TYPE *sk_TYPE_value(STACK_OF(TYPE) *sk, int idx); /* DEFINE_STACK_OF_CONST(TYPE) */ const TYPE *sk_TYPE_value(STACK_OF(TYPE) *sk, int idx); DEFINE_SPECIAL_STACK_OF() and DEFINE_SPECIAL_STACK_OF_CONST() are similar except B is used in the function names: /* DEFINE_SPECIAL_STACK_OF(TYPE, FUNCNAME) */ TYPE *sk_FUNCNAME_value(STACK_OF(TYPE) *sk, int idx); /* DEFINE_SPECIAL_STACK_OF(TYPE, FUNCNAME) */ const TYPE *sk_FUNCNAME_value(STACK_OF(TYPE) *sk, int idx); B_num>() returns the number of elements in I or -1 if I is NULL. B_value>() returns element I in I, where I starts at zero. If I is out of range then NULL is returned. B_new>() allocates a new empty stack using comparison function I. If I is NULL then no comparison function is used. This function is equivalent to B_new_reserve>(I, 0). B_new_null>() allocates a new empty stack with no comparison function. This function is equivalent to B_new_reserve>(NULL, 0). B_reserve>() allocates additional memory in the I structure such that the next I calls to B_insert>(), B_push>() or B_unshift>() will not fail or cause memory to be allocated or reallocated. If I is zero, any excess space allocated in the I structure is freed. On error I is unchanged. B_new_reserve>() allocates a new stack. The new stack will have additional memory allocated to hold I elements if I is positive. The next I calls to B_insert>(), B_push>() or B_unshift>() will not fail or cause memory to be allocated or reallocated. If I is zero or less than zero, no memory is allocated. B_new_reserve>() also sets the comparison function I to the newly created stack. If I is NULL then no comparison function is used. B_set_cmp_func>() sets the comparison function of I to I. The previous comparison function is returned or NULL if there was no previous comparison function. B_free>() frees up the I structure. It does I free up any elements of I. After this call I is no longer valid. B_zero>() sets the number of elements in I to zero. It does not free I so after this call I is still valid. B_pop_free>() frees up all elements of I and I itself. The free function freefunc() is called on each element to free it. B_delete>() deletes element I from I. It returns the deleted element or NULL if I is out of range. B_delete_ptr>() deletes element matching I from I. It returns the deleted element or NULL if no element matching I was found. B_insert>() inserts I into I at position I. Any existing elements at or after I are moved downwards. If I is out of range the new element is appended to I. B_insert>() either returns the number of elements in I after the new element is inserted or zero if an error (such as memory allocation failure) occurred. B_push>() appends I to I it is equivalent to: sk_TYPE_insert(sk, ptr, -1); B_unshift>() inserts I at the start of I it is equivalent to: sk_TYPE_insert(sk, ptr, 0); B_pop>() returns and removes the last element from I. B_shift>() returns and removes the first element from I. B_set>() sets element I of I to I replacing the current element. The new element value is returned or NULL if an error occurred: this will only happen if I is NULL or I is out of range. -B_find>() searches I for the element I. In the case -where no comparison function has been specified, the function performs -a linear search for a pointer equal to I. The index of the first -matching element is returned or B<-1> if there is no match. In the case -where a comparison function has been specified, I is sorted and -B_find>() returns the index of a matching element or B<-1> if there -is no match. Note that, in this case the comparison function will usually -compare the values pointed to rather than the pointers themselves and -the order of elements in I can change. +B_find>() searches I for the element I. In the +case where no comparison function has been specified, the function +performs a linear search for a pointer equal to I. In the case +where a comparison function has been specified, the function performs +a search for a element that the comparison function indicates is a +match. If the stack is sorted, a binary search is used, otherwise, a +linear search is used. B_find>() returns the index of a +matching element or B<-1> if there is no match. B_find_ex>() operates like B_find>() except when a comparison function has been specified and no matching element is found. Instead of returning B<-1>, B_find_ex>() returns the index of the element either before or after the location where I would be if it were present in I. The function also does not guarantee that the first matching element in the sorted stack is returned. B_find_all>() operates like B_find>() but it also sets the I<*pnum> to number of matching elements in the stack. In case no comparison function has been specified the I<*pnum> will be always set to 1 if matching element was found, 0 otherwise. B_sort>() sorts I using the supplied comparison function. B_is_sorted>() returns B<1> if I is sorted and B<0> otherwise. B_dup>() returns a shallow copy of I or an empty stack if the passed stack is NULL. Note the pointers in the copy are identical to the original. B_deep_copy>() returns a new stack where each element has been copied or an empty stack if the passed stack is NULL. Copying is performed by the supplied copyfunc() and freeing by freefunc(). The function freefunc() is only called if an error occurs. =head1 NOTES Care should be taken when accessing stacks in multi-threaded environments. Any operation which increases the size of a stack such as B_insert>() or B_push>() can "grow" the size of an internal array and cause race conditions if the same stack is accessed in a different thread. Operations such as B_find>() and B_sort>() can also reorder the stack. Any comparison function supplied should use a metric suitable for use in a binary search operation. That is it should return zero, a positive or negative value if I is equal to, greater than or less than I respectively. Care should be taken when checking the return values of the functions B_find>() and B_find_ex>(). They return an index to the matching element. In particular B<0> indicates a matching first element. A failed search is indicated by a B<-1> return value. STACK_OF(), DEFINE_STACK_OF(), DEFINE_STACK_OF_CONST(), and DEFINE_SPECIAL_STACK_OF() are implemented as macros. It is not an error to call B_num>(), B_value>(), B_free>(), B_zero>(), B_pop_free>(), B_delete>(), B_delete_ptr>(), B_pop>(), B_shift>(), B_find>(), B_find_ex>(), and B_find_all>() on a NULL stack, empty stack, or with an invalid index. An error is not raised in these conditions. The underlying utility B API should not be used directly. It defines these functions: OPENSSL_sk_deep_copy(), OPENSSL_sk_delete(), OPENSSL_sk_delete_ptr(), OPENSSL_sk_dup(), OPENSSL_sk_find(), OPENSSL_sk_find_ex(), OPENSSL_sk_find_all(), OPENSSL_sk_free(), OPENSSL_sk_insert(), OPENSSL_sk_is_sorted(), OPENSSL_sk_new(), OPENSSL_sk_new_null(), OPENSSL_sk_new_reserve(), OPENSSL_sk_num(), OPENSSL_sk_pop(), OPENSSL_sk_pop_free(), OPENSSL_sk_push(), OPENSSL_sk_reserve(), OPENSSL_sk_set(), OPENSSL_sk_set_cmp_func(), OPENSSL_sk_shift(), OPENSSL_sk_sort(), OPENSSL_sk_unshift(), OPENSSL_sk_value(), OPENSSL_sk_zero(). =head1 RETURN VALUES B_num>() returns the number of elements in the stack or B<-1> if the passed stack is NULL. B_value>() returns a pointer to a stack element or NULL if the index is out of range. B_new>(), B_new_null>() and B_new_reserve>() return an empty stack or NULL if an error occurs. B_reserve>() returns B<1> on successful allocation of the required memory or B<0> on error. B_set_cmp_func>() returns the old comparison function or NULL if there was no old comparison function. B_free>(), B_zero>(), B_pop_free>() and B_sort>() do not return values. B_pop>(), B_shift>(), B_delete>() and B_delete_ptr>() return a pointer to the deleted element or NULL on error. B_insert>(), B_push>() and B_unshift>() return the total number of elements in the stack and 0 if an error occurred. B_set>() returns a pointer to the replacement element or NULL on error. B_find>() and B_find_ex>() return an index to the found element or B<-1> on error. B_is_sorted>() returns B<1> if the stack is sorted and B<0> if it is not. B_dup>() and B_deep_copy>() return a pointer to the copy of the stack or NULL on error. =head1 HISTORY Before OpenSSL 1.1.0, this was implemented via macros and not inline functions and was not a public API. B_reserve>() and B_new_reserve>() were added in OpenSSL 1.1.1. From OpenSSL 3.2.0, the B_find>(), B_find_ex>() and B_find_all>() calls are read-only and do not sort the stack. To avoid any performance implications this change introduces, B_sort>() should be called before these find operations. Before OpenSSL 3.3.0 B_push>() returned -1 if I was NULL. It was changed to return 0 in this condition as for other errors. =head1 COPYRIGHT -Copyright 2000-2024 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-2025 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/man3/OpenSSL_version.pod b/doc/man3/OpenSSL_version.pod index e5dff33dcdda..6b899cbe5438 100644 --- a/doc/man3/OpenSSL_version.pod +++ b/doc/man3/OpenSSL_version.pod @@ -1,268 +1,275 @@ =pod =head1 NAME OPENSSL_VERSION_MAJOR, OPENSSL_VERSION_MINOR, OPENSSL_VERSION_PATCH, OPENSSL_VERSION_PRE_RELEASE, OPENSSL_VERSION_BUILD_METADATA, OPENSSL_VERSION_TEXT, OPENSSL_VERSION_PREREQ, OPENSSL_version_major, OPENSSL_version_minor, OPENSSL_version_patch, OPENSSL_version_pre_release, OPENSSL_version_build_metadata, OpenSSL_version, OPENSSL_VERSION_NUMBER, OpenSSL_version_num, OPENSSL_info - get OpenSSL version number and other information =head1 SYNOPSIS #include #define OPENSSL_VERSION_MAJOR x #define OPENSSL_VERSION_MINOR y #define OPENSSL_VERSION_PATCH z /* The definitions here are typical release values */ #define OPENSSL_VERSION_PRE_RELEASE "" #define OPENSSL_VERSION_BUILD_METADATA "" #define OPENSSL_VERSION_TEXT "OpenSSL x.y.z xx XXX xxxx" #define OPENSSL_VERSION_PREREQ(maj,min) #include unsigned int OPENSSL_version_major(void); unsigned int OPENSSL_version_minor(void); unsigned int OPENSSL_version_patch(void); const char *OPENSSL_version_pre_release(void); const char *OPENSSL_version_build_metadata(void); const char *OpenSSL_version(int t); const char *OPENSSL_info(int t); /* from openssl/opensslv.h */ #define OPENSSL_VERSION_NUMBER 0xnnnnnnnnL /* from openssl/crypto.h */ unsigned long OpenSSL_version_num(); =head1 DESCRIPTION =head2 Macros The three macros B, B and B represent the three parts of a version identifier, B.I.I>. The macro B is an added bit of text that indicates that this is a pre-release version, such as C<"-dev"> for an ongoing development snapshot or C<"-alpha3"> for an alpha release. The value must be a string. The macro B is extra information, reserved for other parties, such as C<"+fips">, or C<"+vendor.1">). The OpenSSL project will not touch this macro (will leave it an empty string). The value must be a string. B is a convenience macro to get the short version identifier string, C<"I.I.I">. B is a convenience macro to get the longer version identifier string, which combines B, B and B. B is a convenience macro to get a full descriptive version text, which includes B and the release date. B is a useful macro for checking whether the OpenSSL version for the headers in use is at least at the given pre-requisite major (B) and minor (B) number or not. It will evaluate to true if the header version number (B.B) is greater than or equal to B.B. B is a combination of the major, minor and patch version into a single integer 0xMNN00PP0L, where: =over 4 =item M is the number from B, in hexadecimal notation =item NN is the number from B, in hexadecimal notation =item PP is the number from B, in hexadecimal notation =back =head2 Functions OPENSSL_version_major(), OPENSSL_version_minor(), OPENSSL_version_patch(), OPENSSL_version_pre_release(), and OPENSSL_version_build_metadata() return the values of the macros above for the build of the library, respectively. OpenSSL_version() returns different strings depending on I: =over 4 =item OPENSSL_VERSION The value of B =item OPENSSL_VERSION_STRING The value of B =item OPENSSL_FULL_VERSION_STRING The value of B =item OPENSSL_CFLAGS The compiler flags set for the compilation process in the form C if available, or C otherwise. =item OPENSSL_BUILT_ON The date of the build process in the form C if available or C otherwise. The date would not be available in a reproducible build, for example. =item OPENSSL_PLATFORM The "Configure" target of the library build in the form C if available, or C otherwise. =item OPENSSL_DIR The B setting of the library build in the form C if available, or C otherwise. =item OPENSSL_ENGINES_DIR The B setting of the library build in the form C if available, or C otherwise. This option is deprecated in OpenSSL 3.0. =item OPENSSL_MODULES_DIR The B setting of the library build in the form C if available, or C otherwise. =item OPENSSL_CPU_INFO The current OpenSSL cpu settings. This is the current setting of the cpu capability flags. It is usually automatically configured but may be set via an environment variable. The value has the same syntax as the environment variable. For x86 the string looks like C or C if not available. =item OPENSSL_WINCTX The Windows install context. The Windows install context is used to compute the OpenSSL registry key name on Windows. The full registry key is C, where C<{major}>, C<{minor}> and C<{context}> are OpenSSL's major version number, minor version number and the Windows install context, respectively. =back For an unknown I, the text C is returned. OPENSSL_info() also returns different strings depending on I: =over 4 =item OPENSSL_INFO_CONFIG_DIR The configured C, which is the default location for OpenSSL configuration files. =item OPENSSL_INFO_ENGINES_DIR The configured C, which is the default location for OpenSSL engines. =item OPENSSL_INFO_MODULES_DIR The configured C, which is the default location for dynamically loadable OpenSSL modules other than engines. =item OPENSSL_INFO_DSO_EXTENSION The configured dynamically loadable module extension. =item OPENSSL_INFO_DIR_FILENAME_SEPARATOR The separator between a directory specification and a filename. Note that on some operating systems, this is not the same as the separator between directory elements. =item OPENSSL_INFO_LIST_SEPARATOR The OpenSSL list separator. This is typically used in strings that are lists of items, such as the value of the environment variable C<$PATH> on Unix (where the separator is C<:>) or C<%PATH%> on Windows (where the separator is C<;>). =item OPENSSL_INFO_CPU_SETTINGS The current OpenSSL cpu settings. This is the current setting of the cpu capability flags. It is usually automatically configured but may be set via an environment variable. The value has the same syntax as the environment variable. For x86 the string looks like C. =item OPENSSL_INFO_WINDOWS_CONTEXT The Windows install context. The Windows install context is used to compute the OpenSSL registry key name on Windows. The full registry key is C, where C<{major}>, C<{minor}> and C<{context}> are OpenSSL's major version number, minor version number and the Windows install context, respectively. =back For an unknown I, NULL is returned. OpenSSL_version_num() returns the value of B. =head1 RETURN VALUES OPENSSL_version_major(), OPENSSL_version_minor() and OPENSSL_version_patch() return the version number parts as integers. OPENSSL_version_pre_release() and OPENSSL_version_build_metadata() return the values of B and B respectively as constant strings. For any of them that is undefined, the empty string is returned. OpenSSL_version() returns constant strings. =head1 SEE ALSO L =head1 HISTORY The macros and functions described here were added in OpenSSL 3.0, except for OPENSSL_VERSION_NUMBER and OpenSSL_version_num(). +=head1 BUGS + +There was a discrepancy between this manual and commentary + code +in F<< >>, where the latter suggested that the +four least significant bits of B could be +C<0x0f> in released OpenSSL versions. + =head1 COPYRIGHT -Copyright 2018-2022 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2018-2025 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/man3/SSL_CIPHER_get_name.pod b/doc/man3/SSL_CIPHER_get_name.pod index 09b7280bdd58..a10942433aa7 100644 --- a/doc/man3/SSL_CIPHER_get_name.pod +++ b/doc/man3/SSL_CIPHER_get_name.pod @@ -1,213 +1,213 @@ =pod =head1 NAME SSL_CIPHER_get_name, SSL_CIPHER_standard_name, OPENSSL_cipher_name, SSL_CIPHER_get_bits, SSL_CIPHER_get_version, SSL_CIPHER_description, SSL_CIPHER_get_cipher_nid, SSL_CIPHER_get_digest_nid, SSL_CIPHER_get_handshake_digest, SSL_CIPHER_get_kx_nid, SSL_CIPHER_get_auth_nid, SSL_CIPHER_is_aead, SSL_CIPHER_find, SSL_CIPHER_get_id, SSL_CIPHER_get_protocol_id - get SSL_CIPHER properties =head1 SYNOPSIS #include const char *SSL_CIPHER_get_name(const SSL_CIPHER *cipher); const char *SSL_CIPHER_standard_name(const SSL_CIPHER *cipher); const char *OPENSSL_cipher_name(const char *stdname); int SSL_CIPHER_get_bits(const SSL_CIPHER *cipher, int *alg_bits); const char *SSL_CIPHER_get_version(const SSL_CIPHER *cipher); char *SSL_CIPHER_description(const SSL_CIPHER *cipher, char *buf, int size); int SSL_CIPHER_get_cipher_nid(const SSL_CIPHER *c); int SSL_CIPHER_get_digest_nid(const SSL_CIPHER *c); const EVP_MD *SSL_CIPHER_get_handshake_digest(const SSL_CIPHER *c); int SSL_CIPHER_get_kx_nid(const SSL_CIPHER *c); int SSL_CIPHER_get_auth_nid(const SSL_CIPHER *c); int SSL_CIPHER_is_aead(const SSL_CIPHER *c); const SSL_CIPHER *SSL_CIPHER_find(SSL *ssl, const unsigned char *ptr); uint32_t SSL_CIPHER_get_id(const SSL_CIPHER *c); - uint32_t SSL_CIPHER_get_protocol_id(const SSL_CIPHER *c); + uint16_t SSL_CIPHER_get_protocol_id(const SSL_CIPHER *c); =head1 DESCRIPTION SSL_CIPHER_get_name() returns a pointer to the name of B. If the B is NULL, it returns "(NONE)". SSL_CIPHER_standard_name() returns a pointer to the standard RFC name of B. If the B is NULL, it returns "(NONE)". If the B has no standard name, it returns B. If B was defined in both SSLv3 and TLS, it returns the TLS name. OPENSSL_cipher_name() returns a pointer to the OpenSSL name of B. If the B is NULL, or B has no corresponding OpenSSL name, it returns "(NONE)". Where both exist, B should be the TLS name rather than the SSLv3 name. SSL_CIPHER_get_bits() returns the number of secret bits used for B. If B is NULL, 0 is returned. SSL_CIPHER_get_version() returns string which indicates the SSL/TLS protocol version that first defined the cipher. It returns "(NONE)" if B is NULL. SSL_CIPHER_get_cipher_nid() returns the cipher NID corresponding to B. If there is no cipher (e.g. for cipher suites with no encryption) then B is returned. SSL_CIPHER_get_digest_nid() returns the digest NID corresponding to the MAC used by B during record encryption/decryption. If there is no digest (e.g. for AEAD cipher suites) then B is returned. SSL_CIPHER_get_handshake_digest() returns an EVP_MD for the digest used during the SSL/TLS handshake when using the SSL_CIPHER B. Note that this may be different to the digest used to calculate the MAC for encrypted records. SSL_CIPHER_get_kx_nid() returns the key exchange NID corresponding to the method used by B. If there is no key exchange, then B is returned. If any appropriate key exchange algorithm can be used (as in the case of TLS 1.3 cipher suites) B is returned. Examples (not comprehensive): NID_kx_rsa NID_kx_ecdhe NID_kx_dhe NID_kx_psk SSL_CIPHER_get_auth_nid() returns the authentication NID corresponding to the method used by B. If there is no authentication, then B is returned. If any appropriate authentication algorithm can be used (as in the case of TLS 1.3 cipher suites) B is returned. Examples (not comprehensive): NID_auth_rsa NID_auth_ecdsa NID_auth_psk SSL_CIPHER_is_aead() returns 1 if the cipher B is AEAD (e.g. GCM or ChaCha20/Poly1305), and 0 if it is not AEAD. SSL_CIPHER_find() returns a B structure which has the cipher ID stored in B. The B parameter is a two element array of B, which stores the two-byte TLS cipher ID (as allocated by IANA) in network byte order. This parameter is usually retrieved from a TLS packet by using functions like L. SSL_CIPHER_find() returns NULL if an error occurs or the indicated cipher is not found. SSL_CIPHER_get_id() returns the OpenSSL-specific ID of the given cipher B. That ID is not the same as the IANA-specific ID. SSL_CIPHER_get_protocol_id() returns the two-byte ID used in the TLS protocol of the given cipher B. SSL_CIPHER_description() returns a textual description of the cipher used into the buffer B of length B provided. If B is provided, it must be at least 128 bytes. If B is NULL it will be allocated using OPENSSL_malloc(). If the provided buffer is too small, or the allocation fails, B is returned. The string returned by SSL_CIPHER_description() consists of several fields separated by whitespace: =over 4 =item Textual representation of the cipher name. =item The minimum protocol version that the ciphersuite supports, such as B. Note that this is not always the same as the protocol version in which the ciphersuite was first defined because some ciphersuites are backwards compatible with earlier protocol versions. =item Kx= Key exchange method such as B, B, etc. =item Au= Authentication method such as B, B, etc.. None is the representation of anonymous ciphers. =item Enc= Encryption method, with number of secret bits, such as B. =item Mac= Message digest, such as B. =back Some examples for the output of SSL_CIPHER_description(): ECDHE-RSA-AES256-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA Enc=AESGCM(256) Mac=AEAD RSA-PSK-AES256-CBC-SHA384 TLSv1.0 Kx=RSAPSK Au=RSA Enc=AES(256) Mac=SHA384 =head1 RETURN VALUES SSL_CIPHER_get_name(), SSL_CIPHER_standard_name(), OPENSSL_cipher_name(), SSL_CIPHER_get_version() and SSL_CIPHER_description() return the corresponding value in a NUL-terminated string for a specific cipher or "(NONE)" if the cipher is not found. SSL_CIPHER_get_bits() returns a positive integer representing the number of secret bits or 0 if an error occurred. SSL_CIPHER_get_cipher_nid(), SSL_CIPHER_get_digest_nid(), SSL_CIPHER_get_kx_nid() and SSL_CIPHER_get_auth_nid() return the NID value or B if an error occurred. SSL_CIPHER_get_handshake_digest() returns a valid B structure or NULL if an error occurred. SSL_CIPHER_is_aead() returns 1 if the cipher is AEAD or 0 otherwise. SSL_CIPHER_find() returns a valid B structure or NULL if an error occurred. SSL_CIPHER_get_id() returns a 4-byte integer representing the OpenSSL-specific ID. SSL_CIPHER_get_protocol_id() returns a 2-byte integer representing the TLS protocol-specific ID. =head1 SEE ALSO L, L, L, L =head1 HISTORY The SSL_CIPHER_get_version() function was updated to always return the correct protocol string in OpenSSL 1.1.0. The SSL_CIPHER_description() function was changed to return B on error, rather than a fixed string, in OpenSSL 1.1.0. The SSL_CIPHER_get_handshake_digest() function was added in OpenSSL 1.1.1. The SSL_CIPHER_standard_name() function was globally available in OpenSSL 1.1.1. Before OpenSSL 1.1.1, tracing (B argument to Configure) was required to enable this function. The OPENSSL_cipher_name() function was added in OpenSSL 1.1.1. =head1 COPYRIGHT -Copyright 2000-2024 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-2025 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/man3/SSL_SESSION_get0_hostname.pod b/doc/man3/SSL_SESSION_get0_hostname.pod index f7add16d7bdd..0140deee9a5e 100644 --- a/doc/man3/SSL_SESSION_get0_hostname.pod +++ b/doc/man3/SSL_SESSION_get0_hostname.pod @@ -1,75 +1,75 @@ =pod =head1 NAME SSL_SESSION_get0_hostname, SSL_SESSION_set1_hostname, SSL_SESSION_get0_alpn_selected, SSL_SESSION_set1_alpn_selected - get and set SNI and ALPN data associated with a session =head1 SYNOPSIS #include const char *SSL_SESSION_get0_hostname(const SSL_SESSION *s); int SSL_SESSION_set1_hostname(SSL_SESSION *s, const char *hostname); void SSL_SESSION_get0_alpn_selected(const SSL_SESSION *s, const unsigned char **alpn, size_t *len); int SSL_SESSION_set1_alpn_selected(SSL_SESSION *s, const unsigned char *alpn, size_t len); =head1 DESCRIPTION -SSL_SESSION_get0_hostname() retrieves the SNI value that was sent by the -client when the session was created if it was accepted by the server. Otherwise -NULL is returned. +SSL_SESSION_get0_hostname() retrieves the Server Name Indication (SNI) value +that was sent by the client when the session was created if the server +acknowledged the client's SNI extension by including an empty SNI extension +in response. Otherwise NULL is returned. The value returned is a pointer to memory maintained within B and should not be free'd. SSL_SESSION_set1_hostname() sets the SNI value for the hostname to a copy of the string provided in hostname. SSL_SESSION_get0_alpn_selected() retrieves the selected ALPN protocol for this session and its associated length in bytes. The returned value of B<*alpn> is a pointer to memory maintained within B and should not be free'd. SSL_SESSION_set1_alpn_selected() sets the ALPN protocol for this session to the value in B which should be of length B bytes. A copy of the input value is made, and the caller retains ownership of the memory pointed to by B. =head1 RETURN VALUES -SSL_SESSION_get0_hostname() returns either a string or NULL based on if there -is the SNI value sent by client. +SSL_SESSION_get0_hostname() returns the SNI string if available, or NULL if not. SSL_SESSION_set1_hostname() returns 1 on success or 0 on error. SSL_SESSION_set1_alpn_selected() returns 1 on success or 0 on error. =head1 SEE ALSO L, L, L, L =head1 HISTORY The SSL_SESSION_set1_hostname(), SSL_SESSION_get0_alpn_selected() and SSL_SESSION_set1_alpn_selected() functions were added in OpenSSL 1.1.1. =head1 COPYRIGHT Copyright 2016-2025 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/include/crypto/rsa.h b/include/crypto/rsa.h index ffbc95a77888..55cc814ce913 100644 --- a/include/crypto/rsa.h +++ b/include/crypto/rsa.h @@ -1,145 +1,141 @@ /* * Copyright 2019-2025 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_INTERNAL_RSA_H # define OSSL_INTERNAL_RSA_H # pragma once # include # include # include "crypto/types.h" #define RSA_MIN_MODULUS_BITS 512 typedef struct rsa_pss_params_30_st { int hash_algorithm_nid; struct { int algorithm_nid; /* Currently always NID_mgf1 */ int hash_algorithm_nid; } mask_gen; int salt_len; int trailer_field; } RSA_PSS_PARAMS_30; RSA_PSS_PARAMS_30 *ossl_rsa_get0_pss_params_30(RSA *r); int ossl_rsa_pss_params_30_set_defaults(RSA_PSS_PARAMS_30 *rsa_pss_params); int ossl_rsa_pss_params_30_copy(RSA_PSS_PARAMS_30 *to, const RSA_PSS_PARAMS_30 *from); int ossl_rsa_pss_params_30_is_unrestricted(const RSA_PSS_PARAMS_30 *rsa_pss_params); int ossl_rsa_pss_params_30_set_hashalg(RSA_PSS_PARAMS_30 *rsa_pss_params, int hashalg_nid); int ossl_rsa_pss_params_30_set_maskgenhashalg(RSA_PSS_PARAMS_30 *rsa_pss_params, int maskgenhashalg_nid); int ossl_rsa_pss_params_30_set_saltlen(RSA_PSS_PARAMS_30 *rsa_pss_params, int saltlen); int ossl_rsa_pss_params_30_set_trailerfield(RSA_PSS_PARAMS_30 *rsa_pss_params, int trailerfield); int ossl_rsa_pss_params_30_hashalg(const RSA_PSS_PARAMS_30 *rsa_pss_params); int ossl_rsa_pss_params_30_maskgenalg(const RSA_PSS_PARAMS_30 *rsa_pss_params); int ossl_rsa_pss_params_30_maskgenhashalg(const RSA_PSS_PARAMS_30 *rsa_pss_params); int ossl_rsa_pss_params_30_saltlen(const RSA_PSS_PARAMS_30 *rsa_pss_params); int ossl_rsa_pss_params_30_trailerfield(const RSA_PSS_PARAMS_30 *rsa_pss_params); int ossl_rsa_verify_PKCS1_PSS_mgf1(RSA *rsa, const unsigned char *mHash, const EVP_MD *Hash, const EVP_MD *mgf1Hash, const unsigned char *EM, int *sLenOut); int ossl_rsa_padding_add_PKCS1_PSS_mgf1(RSA *rsa, unsigned char *EM, const unsigned char *mHash, const EVP_MD *Hash, const EVP_MD *mgf1Hash, int *sLenOut); const char *ossl_rsa_mgf_nid2name(int mgf); int ossl_rsa_oaeppss_md2nid(const EVP_MD *md); const char *ossl_rsa_oaeppss_nid2name(int md); RSA *ossl_rsa_new_with_ctx(OSSL_LIB_CTX *libctx); OSSL_LIB_CTX *ossl_rsa_get0_libctx(RSA *r); void ossl_rsa_set0_libctx(RSA *r, OSSL_LIB_CTX *libctx); int ossl_rsa_set0_all_params(RSA *r, STACK_OF(BIGNUM) *primes, STACK_OF(BIGNUM) *exps, STACK_OF(BIGNUM) *coeffs); int ossl_rsa_get0_all_params(RSA *r, STACK_OF(BIGNUM_const) *primes, STACK_OF(BIGNUM_const) *exps, STACK_OF(BIGNUM_const) *coeffs); int ossl_rsa_is_foreign(const RSA *rsa); RSA *ossl_rsa_dup(const RSA *rsa, int selection); int ossl_rsa_todata(RSA *rsa, OSSL_PARAM_BLD *bld, OSSL_PARAM params[], int include_private); int ossl_rsa_fromdata(RSA *rsa, const OSSL_PARAM params[], int include_private); int ossl_rsa_pss_params_30_todata(const RSA_PSS_PARAMS_30 *pss, OSSL_PARAM_BLD *bld, OSSL_PARAM params[]); int ossl_rsa_pss_params_30_fromdata(RSA_PSS_PARAMS_30 *pss_params, int *defaults_set, const OSSL_PARAM params[], OSSL_LIB_CTX *libctx); int ossl_rsa_set0_pss_params(RSA *r, RSA_PSS_PARAMS *pss); int ossl_rsa_pss_get_param_unverified(const RSA_PSS_PARAMS *pss, const EVP_MD **pmd, const EVP_MD **pmgf1md, int *psaltlen, int *ptrailerField); RSA_PSS_PARAMS *ossl_rsa_pss_decode(const X509_ALGOR *alg); int ossl_rsa_param_decode(RSA *rsa, const X509_ALGOR *alg); RSA *ossl_rsa_key_from_pkcs8(const PKCS8_PRIV_KEY_INFO *p8inf, OSSL_LIB_CTX *libctx, const char *propq); int ossl_rsa_padding_check_PKCS1_type_2(OSSL_LIB_CTX *ctx, unsigned char *to, int tlen, const unsigned char *from, int flen, int num, unsigned char *kdk); int ossl_rsa_padding_check_PKCS1_type_2_TLS(OSSL_LIB_CTX *ctx, unsigned char *to, size_t tlen, const unsigned char *from, size_t flen, int client_version, int alt_version); int ossl_rsa_padding_add_PKCS1_OAEP_mgf1_ex(OSSL_LIB_CTX *libctx, unsigned char *to, int tlen, const unsigned char *from, int flen, const unsigned char *param, int plen, const EVP_MD *md, const EVP_MD *mgf1md); int ossl_rsa_validate_public(const RSA *key); int ossl_rsa_validate_private(const RSA *key); int ossl_rsa_validate_pairwise(const RSA *key); int ossl_rsa_verify(int dtype, const unsigned char *m, unsigned int m_len, unsigned char *rm, size_t *prm_len, const unsigned char *sigbuf, size_t siglen, RSA *rsa); const unsigned char *ossl_rsa_digestinfo_encoding(int md_nid, size_t *len); extern const char *ossl_rsa_mp_factor_names[]; extern const char *ossl_rsa_mp_exp_names[]; extern const char *ossl_rsa_mp_coeff_names[]; ASN1_STRING *ossl_rsa_ctx_to_pss_string(EVP_PKEY_CTX *pkctx); int ossl_rsa_pss_to_ctx(EVP_MD_CTX *ctx, EVP_PKEY_CTX *pkctx, const X509_ALGOR *sigalg, EVP_PKEY *pkey); -# ifdef FIPS_MODULE -int ossl_rsa_key_pairwise_test(RSA *rsa); -# endif /* FIPS_MODULE */ - # if defined(FIPS_MODULE) && !defined(OPENSSL_NO_ACVP_TESTS) int ossl_rsa_acvp_test_gen_params_new(OSSL_PARAM **dst, const OSSL_PARAM src[]); void ossl_rsa_acvp_test_gen_params_free(OSSL_PARAM *dst); int ossl_rsa_acvp_test_set_params(RSA *r, const OSSL_PARAM params[]); int ossl_rsa_acvp_test_get_params(RSA *r, OSSL_PARAM params[]); typedef struct rsa_acvp_test_st RSA_ACVP_TEST; void ossl_rsa_acvp_test_free(RSA_ACVP_TEST *t); # else # define RSA_ACVP_TEST void # endif int ossl_rsa_check_factors(RSA *r); RSA *evp_pkey_get1_RSA_PSS(EVP_PKEY *pkey); #endif diff --git a/include/openssl/opensslv.h.in b/include/openssl/opensslv.h.in index e547281ff527..69b9caacf4dc 100644 --- a/include/openssl/opensslv.h.in +++ b/include/openssl/opensslv.h.in @@ -1,108 +1,108 @@ /* * {- join("\n * ", @autowarntext) -} * * Copyright 1999-2025 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 OPENSSL_OPENSSLV_H # define OPENSSL_OPENSSLV_H # pragma once # ifdef __cplusplus extern "C" { # endif /* * SECTION 1: VERSION DATA. These will change for each release */ /* * Base version macros * * These macros express version number MAJOR.MINOR.PATCH exactly */ # define OPENSSL_VERSION_MAJOR {- $config{major} -} # define OPENSSL_VERSION_MINOR {- $config{minor} -} # define OPENSSL_VERSION_PATCH {- $config{patch} -} /* * Additional version information * * These are also part of the new version scheme, but aren't part * of the version number itself. */ /* Could be: #define OPENSSL_VERSION_PRE_RELEASE "-alpha.1" */ # define OPENSSL_VERSION_PRE_RELEASE "{- $config{prerelease} -}" /* Could be: #define OPENSSL_VERSION_BUILD_METADATA "+fips" */ /* Could be: #define OPENSSL_VERSION_BUILD_METADATA "+vendor.1" */ # define OPENSSL_VERSION_BUILD_METADATA "{- $config{build_metadata} -}" /* * Note: The OpenSSL Project will never define OPENSSL_VERSION_BUILD_METADATA * to be anything but the empty string. Its use is entirely reserved for * others */ /* * Shared library version * * This is strictly to express ABI version, which may or may not * be related to the API version expressed with the macros above. * This is defined in free form. */ # define OPENSSL_SHLIB_VERSION {- $config{shlib_version} -} /* * SECTION 2: USEFUL MACROS */ /* For checking general API compatibility when preprocessing */ # define OPENSSL_VERSION_PREREQ(maj,min) \ ((OPENSSL_VERSION_MAJOR << 16) + OPENSSL_VERSION_MINOR >= ((maj) << 16) + (min)) /* * Macros to get the version in easily digested string form, both the short * "MAJOR.MINOR.PATCH" variant (where MAJOR, MINOR and PATCH are replaced * with the values from the corresponding OPENSSL_VERSION_ macros) and the * longer variant with OPENSSL_VERSION_PRE_RELEASE_STR and * OPENSSL_VERSION_BUILD_METADATA_STR appended. */ # define OPENSSL_VERSION_STR "{- $config{version} -}" # define OPENSSL_FULL_VERSION_STR "{- $config{full_version} -}" /* * SECTION 3: ADDITIONAL METADATA * * These strings are defined separately to allow them to be parsable. */ # define OPENSSL_RELEASE_DATE "{- $config{release_date} -}" /* * SECTION 4: BACKWARD COMPATIBILITY */ # define OPENSSL_VERSION_TEXT "OpenSSL {- "$config{full_version} $config{release_date}" -}" -/* Synthesize OPENSSL_VERSION_NUMBER with the layout 0xMNN00PPSL */ +/* Synthesize OPENSSL_VERSION_NUMBER with the layout 0xMNN00PP0L */ # define OPENSSL_VERSION_NUMBER \ ( (OPENSSL_VERSION_MAJOR<<28) \ |(OPENSSL_VERSION_MINOR<<20) \ |(OPENSSL_VERSION_PATCH<<4) \ - |{- @config{prerelease} ? "0x0L" : "0xfL" -} ) + |0x0L ) # ifdef __cplusplus } # endif # include # ifndef OPENSSL_NO_DEPRECATED_3_0 # define HEADER_OPENSSLV_H # endif #endif /* OPENSSL_OPENSSLV_H */ diff --git a/providers/fips-sources.checksums b/providers/fips-sources.checksums index d48a9c85f57b..334b4ad6b7f2 100644 --- a/providers/fips-sources.checksums +++ b/providers/fips-sources.checksums @@ -1,732 +1,732 @@ 0e22ea0cf34ef3871e30df0bc302dc29352d38001d1622ddb78a27a374b6aee8 crypto/aes/aes_cbc.c c049a936d74100fcced225f575d46662792a6a0039777d2d4df0cf61eff90a68 crypto/aes/aes_core.c 3fac41ce96acb9189eac2d5571425c3ff33a34c884ae7e275e1fd3068b5fc662 crypto/aes/aes_ecb.c c1e674d08683a25bc053f6233f73a0d0b3a90aafe591ff57b702c7da1582e4a5 crypto/aes/aes_local.h a2466f18da5847c7d9fbced17524633c10ce024671a72f53f9c9c55b9b9923dd crypto/aes/aes_misc.c 6979c133f76f4623e62e6e970deae70fa025e713a72b71aead5a048d49e47f6f crypto/aes/asm/aes-586.pl 92be9ff608331a432e95247a8f4fb9e46897d0cb76f2b6db809b61d44287964a crypto/aes/asm/aes-armv4.pl 953897f86e2de9fa27ef411155ab3aed133af94885f1507e76449c142da78656 crypto/aes/asm/aes-c64xplus.pl 00196f01f5218ad731e6a058d406078f7228a9756d9d73f51c0d0c2a68f885af crypto/aes/asm/aes-ia64.S 88b6f8396cd9d86004743d5c3b0f72b7b8c3d5a2b00b0bbb761ba91ae5a7cdc8 crypto/aes/asm/aes-mips.pl 7ff9c96ef3d591d45d776fa4b244601ea0d9328e289aeab1e1b92436ce7d02ad crypto/aes/asm/aes-parisc.pl f1244cdeadcb4e48f35bc5df19d4cfaf07e0086ad951b84f07ff6966501faa5b crypto/aes/asm/aes-ppc.pl 538ce0e80698d773c9419a9ca8892d61bc5b3cd1b071c5fc5f315d7f5573e96d crypto/aes/asm/aes-riscv32-zkn.pl b5cdd6858b1eff7d17b29b78ac8c4a7642c0a74710f8b50821a6265328845aaf crypto/aes/asm/aes-riscv64-zkn.pl e1f3805332eb811d9d0c9377b67fe0681063364f1af84d8598f7daa30da65b4d crypto/aes/asm/aes-riscv64-zvbb-zvkg-zvkned.pl ecd9bdfaf25cdd3d8ec0c50cb4306d98374da1c6056e27e0cf31a057dc5ee150 crypto/aes/asm/aes-riscv64-zvkb-zvkned.pl d372152dac004b96a89f8531256bd05597ca0b614b444bb02aee93238dcf83ab crypto/aes/asm/aes-riscv64-zvkned.pl f0388e17ba4268ed0b562da60e0780072180a824a379b79fafb60e25b8da3b52 crypto/aes/asm/aes-riscv64.pl 290ae2a09826d24e83763415a021e328d41a163f41cff8c9e3b882e973677f33 crypto/aes/asm/aes-s390x.pl ee4e8cacef972942d2a89c1a83c984df9cad87c61a54383403c5c4864c403ba1 crypto/aes/asm/aes-sparcv9.pl 391497550eaca253f64b2aba7ba2e53c6bae7dff01583bc6bfc12e930bb7e217 crypto/aes/asm/aes-x86_64.pl c56c324667b67d726e040d70379efba5b270e2937f403c1b5979018b836903c7 crypto/aes/asm/aesfx-sparcv9.pl 14359dc32b7f4e5c08227fb9ac8f9232c1287399463b233fec4a2ab0c19f68d1 crypto/aes/asm/aesni-mb-x86_64.pl f525e1bca51d39adcd411cbf8f874fe1441b23a6f614644da78dfd8544d13b23 crypto/aes/asm/aesni-sha1-x86_64.pl 895f94d7befb90e82f9d300ed8f870e790101f30ba72b249a2c503f07aec7dd2 crypto/aes/asm/aesni-sha256-x86_64.pl 4ff74d4e629a88ef5a9e3d3f5b340fc0a4793d16d7cc7f1b70da62512a856248 crypto/aes/asm/aesni-x86.pl 25881237d026cebd96877a2ea2729db1ce512875cb2a10ca0cd1d6ddf4b51a3b crypto/aes/asm/aesni-x86_64.pl 5d03d59af5d77979bed0662a2e971951899d407d11dcf6a8e174453aaebecea2 crypto/aes/asm/aesni-xts-avx512.pl 0489a10fbb1a8ca3652848d5c1e14e519501e189bad3e5827a573c26df359691 crypto/aes/asm/aesp8-ppc.pl e397a5781893e97dd90a5a52049633be12a43f379ec5751bca2a6350c39444c8 crypto/aes/asm/aest4-sparcv9.pl 578142d03bc47353952fca2027eb63ec97ce9a1379c0f3c7ac0fdf110eb3378b crypto/aes/asm/aesv8-armx.pl 5e8005fdb6641df465bdda20c3476f7176e6bcd63d5073044a0c02a327c7f172 crypto/aes/asm/bsaes-armv7.pl 12cd3c8a9ce7153c577ff6238d81ec1947dfc43ee80cb15ee886cdf811969417 crypto/aes/asm/bsaes-armv8.pl c72f6cbf3b9900d956e05003ec8df758b29b43519c7801d677c3f992bc589d4e crypto/aes/asm/bsaes-x86_64.pl 41e737a3c2985564dd7f7a56fbf3e6ea9c93f1e27e2b64ed13767faaac71a11a crypto/aes/asm/vpaes-armv8.pl 7ec25456a8ad4127c3bec83550d8ec411a12b506dfcbd4f1dadac2c66e468c22 crypto/aes/asm/vpaes-loongarch64.pl c3541865cd02d81101cdbab4877ed82772e6980d2c677b9008b38fa1b26d36d4 crypto/aes/asm/vpaes-ppc.pl 3ec24185750a995377516bc2fb2eae8b1c52094c6fff093bff591837fc12d6c3 crypto/aes/asm/vpaes-x86.pl c6935d2ab7925022cb3d76446536ff01b1a1b8eb7eac619d034a29aad17ed45f crypto/aes/asm/vpaes-x86_64.pl 2bc67270155e2d6c7da87d9070e005ee79cea18311004907edfd6a078003532a crypto/alphacpuid.pl 269e52f8867c13ca75d2f88ec1f89b692cb8c6c3ee89abe2fd3c1821925191d8 crypto/arm64cpuid.pl 783fda04d852c00caf3d1ae71c726058f75a8554c6cdc5346855603f75c9f61c crypto/armcap.c d9f923daabe7537d1063b182f9f220655abd182ef4c55a0194a7ee8d6030b5bd crypto/armv4cpuid.pl 16739d54200fb81ca7835b5814f965022a2ab41589c7787e2697e3ea72d4fafa crypto/asn1_dsa.c 819c9fd2b0cae9aab81c3cbd1815c2e22949d75f132f649b5883812d0bbaa39a crypto/bn/asm/alpha-mont.pl 565edec9b6fa0702c07ab2f7507b0a45fb2ab649ed509fd79013ea7378bb5891 crypto/bn/asm/armv4-gf2m.pl 5469ab174b62361c6ced8f5c1007c462700761c1aae72f0d2928ca39e57d47a1 crypto/bn/asm/armv4-mont.pl 1a2c890bcb9d96b24ef025c4894f89c56e83c05eb0db9532ba3b17a50753c2c2 crypto/bn/asm/armv8-mont.pl cb4ad7b7461fcb8e2a0d52881158d0211b79544842d4eae36fc566869a2d62c8 crypto/bn/asm/bn-586.pl 636da7e2a66272a81f9c99e90b36c6f132ad6236c739e8b9f2e7315f30b72edd crypto/bn/asm/c64xplus-gf2m.pl c86664fb974362ee52a454c83c2c4b23fd5b7d64b3c9e23ef1e0dfd130a46ee5 crypto/bn/asm/co-586.pl 199b9b100f194a2a128c14f2a71be5a04d50d069666d90ca5b69baee1318ccb7 crypto/bn/asm/ia64-mont.pl a511aafbf76647a0c83705d4491c898a5584d300aa449fa6166c8803372946eb crypto/bn/asm/ia64.S 687c5d6606fdfd0e242005972d15db74a9cbac2b8a9a54a56fcb1e99d3880ff3 crypto/bn/asm/mips-mont.pl 5cb8b5381d03aa76d456a594ff7d2dcb2ede310debb43031868af55ddb832523 crypto/bn/asm/mips.pl b27ec5181e387e812925bb26823b830f49d7a6e4971b6d11ea583f5632a1504b crypto/bn/asm/parisc-mont.pl 9973523b361db963eea4938a7a8a3adc692e1a4e1aec4fa1f1e57dc93da37921 crypto/bn/asm/ppc-mont.pl 59cd27e1e10c4984b7fb684b27f491e7634473b1bcff197a07e0ca653124aa9a crypto/bn/asm/ppc.pl 0b3350f56d423a4df918a08e90c7c66227c4449a9f9c44096eacc254ebc65f9f crypto/bn/asm/ppc64-mont-fixed.pl a25be64867ab837d93855af232e2bfa71b85b2c6f00e35e620fdc5618187fb6f crypto/bn/asm/ppc64-mont.pl a6982e91f35fbcefe897106b3f5c8957359fb58b74beac12bdcb8d3b7daa15f5 crypto/bn/asm/rsaz-2k-avx512.pl 1b059fa9056c6b476f036ffa5dc74092d9366ee94a98f8f3e57e9b452a695232 crypto/bn/asm/rsaz-2k-avxifma.pl df7268cd5461269db0d8d1ef62c2d9ff6608eb0c071e798b06ad9ddfcbef1a31 crypto/bn/asm/rsaz-3k-avx512.pl b8424d830f41a038f3c98d8664c6cf7d2d3e1748cdce260db41fa3c74f1d88d9 crypto/bn/asm/rsaz-3k-avxifma.pl 9ae9cf7a926eea6543237eb4c537860a36e6373e9091e2c581868871ba84fd74 crypto/bn/asm/rsaz-4k-avx512.pl afcf51a732c80eadae1650e22e4af34904112a8b95467087a16d9d2394934730 crypto/bn/asm/rsaz-4k-avxifma.pl 6e47bf041e51d8086c4933c2a5da3ce6d1b136592984754461d59aa81e4995a6 crypto/bn/asm/rsaz-avx2.pl 149842bf63d1ef1895a251a83d9941fc3ed744dab359b42d635d04cc8d2f2864 crypto/bn/asm/rsaz-x86_64.pl 30fedf48dfc5fec1c2044b6c226dd9fc42a92522cc589797a23a79d452bdd2cf crypto/bn/asm/s390x-gf2m.pl 590388d69d7ac3a0e9af4014792f4f0fdb9552719e8fb48ebc7e5dfca2a491d4 crypto/bn/asm/s390x-mont.pl aa02597f3dc09cfbc190aedb75711859ba0f3efff87067ebfba1ec78ebee40d7 crypto/bn/asm/s390x.S 2f7cbc2c3d93b1bbc4953dda38b9ae0ab3a0a8331a0418d94d9b286183736c9e crypto/bn/asm/sparct4-mont.pl ca21a9ccbc54e19fb7c2e6cdf286ce7cb08b0fba960c777c6edce5c57ccc2101 crypto/bn/asm/sparcv8.S fbc93c8dbbecefe66086f58fe9719ed87b13b2cdc61454a10e841228296fecef crypto/bn/asm/sparcv8plus.S 127832c1e3d298aad805236776488f5f8836b6a0fdbce3f6b42678163df3909f crypto/bn/asm/sparcv9-gf2m.pl 1622f04a8918724ac0e8804baf285fdafa0eeaaecc36c7facd459d0ff13a8cac crypto/bn/asm/sparcv9-mont.pl b69083f78b4b4f7097de4462d16649532fb82c453a82cdd9cc1393122661d6e2 crypto/bn/asm/sparcv9a-mont.pl d404375a21d33396824a3da212d6646d4f3150dd141ee4b4a250aefae3482efb crypto/bn/asm/via-mont.pl d24f3e97239c8eed5efc721521b025b7256c15e67a54ea6b5c4cf8f7cd0f89ea crypto/bn/asm/vis3-mont.pl 89278854f44d95be916516609ce6f79dcd346bab52574b9b6336a9952aa94bee crypto/bn/asm/x86-gf2m.pl 90d4ae234c08267adce9ed38d56e0edc223f7480cb9605f5d7399d0b3914c6be crypto/bn/asm/x86-mont.pl d444ca73875e97e0ea88b20e4c02f2fcf3850e8b9311e3b67a2d04fe2796d543 crypto/bn/asm/x86_64-gcc.c 709ddee92e9222ee0ed27bfb90db556e85e2d302e4a9131afa25fdc14c4d858f crypto/bn/asm/x86_64-gf2m.pl da7f7780d27eed164797e5334cd45b35d9c113e86afaca051463aef9a8fd787c crypto/bn/asm/x86_64-mont.pl c3217af276175509230fcf4f8c169aab36729b474c3887f730ec018395abea1c crypto/bn/asm/x86_64-mont5.pl 0ea8185a037a2951bb3d1e590bbbdeac305176d5e618f3e43a04c09733a9de34 crypto/bn/bn_add.c 964c7eecef99ef56997cbb90b6560d41e0e90bb1f87dcc5e2a1bf177851c005f crypto/bn/bn_asm.c 22269bec400abc2d4b38f250134070680075aa320a1a8a2e0c4dcd33fd66cd8c crypto/bn/bn_blind.c 7b761d541e3b7f6a3f2b14a09b2b3836a079a845cf67a54db4853e3fd38277c6 crypto/bn/bn_const.c eee3d2710144b0e860c57e84f5adc6b2bf64fc27cbd202a8ca2630aefed3b84c crypto/bn/bn_conv.c f53d3804456b787be45ace2b33b7a323e5e4fb6cfbe3aa3b6696e3ce0a640baa crypto/bn/bn_ctx.c d94295953ab91469fe2b9da2a542b8ea11ac38551ecde8f8202b7f645c2dea16 crypto/bn/bn_dh.c 74b63a4515894592b7241fb30b91b21510beaa3d397809e3d74bc9a73e879d18 crypto/bn/bn_div.c a14183415e8de385964b0045af6d155a0c9dfbc5f0bd11cb4b848c31eac086af crypto/bn/bn_exp.c ec2b6e3af6df473a23e7f1a8522f2554cb0eb5d34e3282458c4a66d242278434 crypto/bn/bn_exp2.c 98b2c9a4ffa3063731a10d74318a9f0b808bfa0bb9a5e1c2faca4121a2390d76 crypto/bn/bn_gcd.c 6c5c69c03d5390467aecb5344c7928f62122e47a4e0e2742af9ee1610dd233a1 crypto/bn/bn_gf2m.c 73ee247467879d4ec984c9900dfe7761233c5b889b8762be37c7e8fdd6d1d210 crypto/bn/bn_intern.c 602ed46fbfe12c899dfb7d9d99ff0dbfff96b454fce3cd02817f3e2488dd9192 crypto/bn/bn_kron.c b0b02639e782fe3a5ed41f2248ad485ccc2a2bc1132a1326b8fa204066c2aa12 crypto/bn/bn_lib.c d5beb9fbac2ff5dc3ccbdfa4d1aabca7225c778cff4e3b05b6d6c63e182637f5 crypto/bn/bn_local.h 929c636ccc31899f366717c1adf691d69534c2329aa79bb3edc2ad1935204ecb crypto/bn/bn_mod.c e1fd447361388b6f1290971543149db346c9e6871ccbf54143c61a5872746bef crypto/bn/bn_mont.c 2da73a76b746a47d8cf8ec8b3e0708c2a34e810abde4b4f1241a49e7f5bb2b60 crypto/bn/bn_mpi.c 76982b18b0803d59b33168b260677e7412970757d3b9513de5c80025290f211d crypto/bn/bn_mul.c 6bf1d67ea493401f7765647828d3f426305fd0686cc89956c9d205922b7ab4db crypto/bn/bn_nist.c 5377e9596c3b9a3153ce75004599dce1f0fef23612d4e086cc936a87d4d5fa99 crypto/bn/bn_prime.c c56ad3073108a0de21c5820a48beae2bccdbf5aa8075ec21738878222eb9adc3 crypto/bn/bn_prime.h 4e1f3e71cdb05d41608224d1837da6f261d5f60a570be1045c10738e1e6646ff crypto/bn/bn_rand.c b5cc902624b3af2149c9ea91f9d18bea56302144e87dfe49105ec6789b73764b crypto/bn/bn_recp.c 669a157968afe07588507a2e9e35c1c4df9c2b0a95cd9c21404b0bfa21be0d37 crypto/bn/bn_rsa_fips186_4.c 6889866bca4673bccb8adf870859a867757ccd3c8ad4652675615afff710add3 crypto/bn/bn_shift.c 622e90766b29e0d25f46474429aebda8eba2246835b9e85dc26da7cdbd49334f crypto/bn/bn_sqr.c 42c8ce944c889abcfcf089d0ad2744b7587696d8d7785efa91b3f7ec53dc062a crypto/bn/bn_sqrt.c 24e62baa56e02f2db6454e10168b7c7fa7638db9221b9acda1803d43f38f36e0 crypto/bn/bn_word.c ec684bfc01a74492150e930fe6d6cc5586be48b9674bbd7a492efa517d04c340 crypto/bn/rsaz_exp.c 2c8c8217197cc7ce0c987c44c1de6752ad385c4934600de8b1be181b4893234a crypto/bn/rsaz_exp.h ad80d38930e576afdf55dfd88c3c7ddfa390cb474b9b1b72d8a37fa0dde177db crypto/bn/rsaz_exp_x2.c 834db8ff36006e5cb53e09ca6c44290124bd23692f4341ea6563b66fcade4cea crypto/bsearch.c 82117f6a7cfc31fc86ecd9629bd3bf614126b8e8b2c23717a03ff5c1db7c3c5c crypto/buffer/buffer.c 5f43844b5d8665de9ab895f93599150a327d73ec2674bbf7d7c512d30163022d crypto/c64xpluscpuid.pl 205f0be0317343b17003f261b427008aad1b31aacc6979c4557fc837e9548b92 crypto/cmac/cmac.c 1d2760fae983b7fdba8fbb63b0f357dc161f6d0f0695f6b73e8d92ed19899185 crypto/context.c 67c2367871b9350a7f7af5be903d6bcca9ebdbff0e9a9bd9f61b56bef5b76696 crypto/core_algorithm.c ab29529cca1308302d852999f2790c404a4dc0ef8cd6653260739f70b2f22758 crypto/core_fetch.c 79522ab7376ba85aca2cfce84a77613e3721470307f2acb28fd318a51182be0d crypto/core_namemap.c 819f75bcb1cbd6633381ec9ad043152ae2ec1f71471650864f2cb8c88612cab5 crypto/cpuid.c a6732e22ccb49cf51fc9dbf23f6059774b70ecc3d7e848c5df112a2d3c179027 crypto/cryptlib.c 66dbfc58916709d5a6913777346083247942a8d9458ee9b2bf443f0ea4988d64 crypto/ctype.c 51e56541daea6d4a26d5bae2ea458414063bf08b045bab8df370f6695903e0a5 crypto/der_writer.c fea3ba4225df97aee90690adf387625b746d8edfdc5af2357ee65151a3d236ac crypto/des/des_enc.c 3c5e1c156ebc771701f0adbcfcd099d700796255991c1bf79bd2ca78fc009c87 crypto/des/des_local.h eeef5722ad56bf1af2ff71681bcc8b8525bc7077e973c98cee920ce9bcc66c81 crypto/des/ecb3_enc.c 04d4cc355200b57f1e7d265a2cebdf094df1eb6e96621b533adddc3d60d31fbe crypto/des/fcrypt_b.c 499513b3ad386fe694c4e04b3c8a9fd4c4e18fc44bb6c4f94d6bf2d9362a3a5a crypto/des/ncbc_enc.c 9549901d6f0f96cd17bd76c2b6cb33fb25641707bfdb8ed34aab250c34f7f4f6 crypto/des/set_key.c 8344811b14d151f6cd40a7bc45c8f4a1106252b119c1d5e6a589a023f39b107d crypto/des/spr.h a54b1b60cf48ca89dfb3f71d299794dd6c2e462c576b0fe583d1448f819c80ea crypto/dh/dh_backend.c 9db32c052fb3cf7c36ab8e642f4852c2fa68a7b6bae0e3b1746522f826827068 crypto/dh/dh_check.c c117ac4fd24369c7813ac9dc9685640700a82bb32b0f7e038e85afd6c8db75c7 crypto/dh/dh_gen.c 6b17861887b2535159b9e6ca4f927767dad3e71b6e8be50055bc784f78e92d64 crypto/dh/dh_group_params.c a539a8930035fee3b723d74a1d13e931ff69a2b523c83d4a2d0d9db6c78ba902 crypto/dh/dh_kdf.c af27b02f3fc5c176bc9f61bc9a67475c5a2a81bce4999f2676311a96059b8dbd crypto/dh/dh_key.c 7eae94965827bc5b0178269e85c77d6671c85255dc1f05e90b0f14500c765cce crypto/dh/dh_lib.c 8300775d88db0a1aa26a77eb49d6c4f7252e7fee69e1440de4c40edadc9da044 crypto/dh/dh_local.h bbcf4fc3067ac462a27d7277973180b7dc140df9262a686c7fbe4318ca01f7b8 crypto/dsa/dsa_backend.c 786d6c65ced7ee4e25f5dd7c3150259ec95b6aa321a7590d905757b8139f8230 crypto/dsa/dsa_check.c ae727bf6319eb57e682de35d75ea357921987953b3688365c710e7fba51c7c58 crypto/dsa/dsa_gen.c 9978d27e9fc8ff152830ebb781f71338e56a5e116f29c1c2d59a5a112d86362a crypto/dsa/dsa_key.c 7d44106570c0ff9a44de874ea2daeaa87ea4c814fef6af0a26f655120a54f529 crypto/dsa/dsa_lib.c f261f9d4f83ecc51ab58de89083e9af4ba4a4c922ccd06b0d628f4b60fc104ec crypto/dsa/dsa_local.h d270b56fd894090319c9491ef745c34bc43add82daecf742916c64a4e956c765 crypto/dsa/dsa_ossl.c 3a38575de4b1409653f330f241848e6c7b554dec44c2415a5ae1baf90fb47ac0 crypto/dsa/dsa_sign.c 53fa10cc87ac63e35df661882852dc46ae68e6fee83b842f1aeefe00b8900ee1 crypto/dsa/dsa_vrf.c 5335741d0f6c1afac107c9ec66e6b5436bd2164535f114c23cdc2a199560c28a crypto/ec/asm/ecp_nistp384-ppc64.pl d9722ad8c6b6e209865a921f3cda831d09bf54a55cacd1edd9802edb6559190a crypto/ec/asm/ecp_nistp521-ppc64.pl 78ad06b88fcc8689a3a846b82f9ee01546e5734acd1bccf2494e523b71dc74d1 crypto/ec/asm/ecp_nistz256-armv4.pl 9463569b439ccee629540d5e02b586f9cc6a87ff382066efe430ac0b85bca281 crypto/ec/asm/ecp_nistz256-armv8.pl 3715ddd921425f3018741037f01455ed26a840ace08691a800708170a66cf4d2 crypto/ec/asm/ecp_nistz256-ppc64.pl cfe7e75a2fddc87a7251684469a8808b9da82b2f5725eafad5806920f89932bd crypto/ec/asm/ecp_nistz256-sparcv9.pl 922725c4761cfa567af6ed9ecab04f2c7729ae2595f2fc0fa46dc67879dc87b0 crypto/ec/asm/ecp_nistz256-x86.pl afa4497cfbf9ef7805e42ae6a61c7d983e8a789b270d498a07785570ab85a9fa crypto/ec/asm/ecp_nistz256-x86_64.pl cc727533130f5f1a29229929b3d4e8454585d647be25d6344f3c6a0240998368 crypto/ec/asm/x25519-ppc64.pl ee897e230964511baa0d1bf95fb938312407a40a88ebe01476879c2763e5f732 crypto/ec/asm/x25519-x86_64.pl d0e81e6185fd589094e06854460cce0d070cc10901ff993c36312fd58420908a crypto/ec/curve25519.c 5daf9f524cd63dd95a2136535b27f2b3d90966562ea5766f4b2d1cd4fccf2502 crypto/ec/curve448/arch_32/f_impl32.c 063dac1e4a9573c47532123e9e03e3532a7473cc3e146521ba9ec6f486ddf3b1 crypto/ec/curve448/arch_64/arch_intrinsics.h 43423b7ee85a5c740c1d81499ee06f4a17732c7731a598e7429d5e402ee77cf4 crypto/ec/curve448/arch_64/f_impl.h 75c8103fddef2b6a1b43245e7b4fa2fc8507aacc61dd8916d1a28e1c28c86623 crypto/ec/curve448/arch_64/f_impl64.c 242421aa2568931f2d175a0cfd1ca3927fddbc31e89187417cce50ad6376a344 crypto/ec/curve448/curve448.c a6c70707c520234ccd111562f012e1abf83c43b20b3b36c339ef1ea0369a9e5f crypto/ec/curve448/curve448_local.h 178fb9863c33174b633c2e7607160b1bedb506d66cc06d53382d87431441f306 crypto/ec/curve448/curve448_tables.c f30e13bba5a136ab9ba5225c98b9b94c2cd73fb3aef60f9dcde3cd471cfa1ca4 crypto/ec/curve448/curve448utils.h 4a45e7828831fbe9f282f933cda54b12cd393ec9bffe5c0ace8e4d1c4d5d6358 crypto/ec/curve448/ed448.h de75ada19d49a0943cc1badf4b258c4d827e6c33921a1a412f9a0e37f2728d0c crypto/ec/curve448/eddsa.c 9f712e7397b10f1dc88a6d18ff38dcda13d09c02775f3682f2b8698715b1095a crypto/ec/curve448/f_generic.c 070daafb9a532ebb8bc0af8b1341254f0cd3e8932a8c8a2dca7baeef6678768b crypto/ec/curve448/field.h 514014f9fa7835056aab1e6df5511fd7de8ecef3cfcada8e0eadec9b727b419c crypto/ec/curve448/point_448.h 1ff6e467d72530c71d21c310180d04a24f0a9cb41168fba94b43309ecdda3888 crypto/ec/curve448/scalar.c 3052a044afae2e91b677542fc8b34b3ec9d033e0c6562b0d43098cfb34ab3c9d crypto/ec/curve448/word.h ae1637d89287c9d22a34bdc0d67f6e01262a2f8dcef9b61369dba8c334f5a80d crypto/ec/ec2_oct.c 9965a95c878438eb94bb0c21876b5a971f47b91f9d22f9c93cf7209a184cd1d1 crypto/ec/ec2_smpl.c a1f22814f501780591da20de5e724895438094824fce440fd026850c46ad8149 crypto/ec/ec_asn1.c 805c42cf4deff93ceb8553c9d572f46e08d148a4de3ed8695a6db290b00b92f1 crypto/ec/ec_backend.c 7f19cebad4a94db291464b0d93006a87d15ccec93b94f725052a1037107a96be crypto/ec/ec_check.c b5d1182daa207e0f27b817801da96af15c8f13a9ceeb04fcc66b45d36f67f6aa crypto/ec/ec_curve.c 8cfd0dcfb5acbf6105691a2d5e2826dba1ff3906707bc9dd6ff9bffcc306468f crypto/ec/ec_cvt.c e656516aa9a322c3b6568cd37fb432ce1bc48369abdeb13eb99d3c38f2fc8c6c crypto/ec/ec_key.c 93f35d2e21d49bb6780d200fda8486edd4a7123956337ba535720bb547a47c4a crypto/ec/ec_kmeth.c 4c5e0cd2b6db049b41098ca7ea1f5c920926392f9fe356d076eae35002b69298 crypto/ec/ec_lib.c 9f86576ca885dd5523879dfdf928c5781bd13d2dbe626a90a785d04184c7a8bc crypto/ec/ec_local.h fd70a4598ab61576535d06417b3b3e367f928e6cc0b20b690326e64076c95068 crypto/ec/ec_mult.c 7a777b96560b44bbb9965f099ebc31ee6c8057b9778e854b0f9f3b4125f8dcda crypto/ec/ec_oct.c c7fba2f2c33f67dafa23caef8c3abd12f5336274a9a07d412b83be0366969ee6 crypto/ec/ecdh_kdf.c b86a943ae62145438a7214539ceb3e0de5a30e17a6e59742c6e30991db730ab6 crypto/ec/ecdh_ossl.c 8515ff7e69bc5387e97de76f3663f49c4901ab942d51b36035cf3f9e9c147406 crypto/ec/ecdsa_ossl.c b6baa42b16e8df69a12e0ab101033100cddc808ec2682ba1574373e6ec86ae93 crypto/ec/ecdsa_sign.c f686cea8c8a3259d95c1e6142813d9da47b6d624c62f26c7e4a16d5607cddb35 crypto/ec/ecdsa_vrf.c 141cfc1459214555b623517a054a9e8d5e4065a11301237b7247be2c6f397a0a crypto/ec/ecp_mont.c 13b30f34aeeb0c98747239bfe91b5f0f14e91b2c1f11db62ebb5950c7219daa0 crypto/ec/ecp_nist.c a47d8541bb2cc180f4c7d3ac0f888657e17621b318ea8a2eacdefb1926efb500 crypto/ec/ecp_nistz256.c 51cb98e7e9c241e33261589f0d74103238baaa850e333c61ff1da360e127518a crypto/ec/ecp_oct.c 9cf3bacc8a990f6dffe369c28f2f47b192c8d17178185acec601e3fee5b05fac crypto/ec/ecp_smpl.c 43f81968983e9a466b7dc9cffe64302418703f7a66adcbac4b7c4d8cb19c9af5 crypto/ec/ecx_backend.c 5ee19c357c318b2948ff5d9118a626a6207af2b2eade7d8536051d4a522668d3 crypto/ec/ecx_backend.h 2be4ca60082891bdc99f8c6ebc5392c1f0a7a53f0bcf18dcf5497a7aee0b9c84 crypto/ec/ecx_key.c c1f04d877f96f2d0852290e34b1994dd48222650ac1121903cee9c259fe3ebf2 crypto/evp/asymcipher.c 80da494704c8fc54fea36e5de7100a6c2fdcc5f8c50f43ac477df5f56fa57e58 crypto/evp/dh_support.c bc9f3b827e3d29ac485fff9fb1c8f71d7e2bcd883ccc44c776de2f620081df58 crypto/evp/digest.c 838277f228cd3025cf95a9cd435e5606ad1fb5d207bbb057aa29892e6a657c55 crypto/evp/ec_support.c 74b24b40447a9d614265a5a9738c6398e588f950c40d4a501828666bb5bfa1f4 crypto/evp/evp_enc.c baccbd623a94ba350c07e0811033ad66a2c892ef51ccb051b4a65bf2ba625a85 crypto/evp/evp_fetch.c 52b4aba9e2beb9d382ebd09daf44009e5ddaeae8d3434546e2884ab8ea481d7a crypto/evp/evp_lib.c 32949d15dfc1a3049eb3000ddc10db077eb442e1fa224b2541aa1fcc6137d80e crypto/evp/evp_local.h 603c97974acd94e66f9718d3d68ab5cd6e0093499feabb1f1417778d768b5d6e crypto/evp/evp_rand.c 2a128617ec0178e9eeacbe41d75a5530755f41ea524cd124607543cf73456a0c crypto/evp/evp_utils.c 3d04aa938f45a04550ce4d53306d60da4ca6a54e1a4e9f19b75ca22277ce7bdb crypto/evp/exchange.c 294284ad040fe4b74845f91b1903c961c757e1ef3fcc2ffa35f43f37f1655e64 crypto/evp/kdf_lib.c 90742590db894920ffdb737a450ee591488aa455802e777400b1bf887618fd7a crypto/evp/kdf_meth.c 948f7904e81008588288a1ba7969b9de83546c687230ffe2a3fd0be1651bce8f crypto/evp/kem.c 55d141a74405415ad21789abcace9557f1d1ef54cf207e99993bf0a801f4b81e crypto/evp/keymgmt_lib.c d57908a9473d2af324f32549649016f7a3c196b5ac8b54d6ca3c82f84cab5d48 crypto/evp/keymgmt_meth.c 9e44d1ffb52fee194b12c50962907c8637e7d92f08339345ec9fd3bd4a248e69 crypto/evp/mac_lib.c cd611921dc773b47207c036b9108ec820ab39d67780ba4adc9ccb9dc8da58627 crypto/evp/mac_meth.c 4f0a9a7baa72c6984edb53c46101b6ff774543603bec1e1d3a6123adf27e41db crypto/evp/p_lib.c 3b4228b92eebd04616ecc3ee58684095313dd5ffd1b43cf698a7d6c202cb4622 crypto/evp/pmeth_check.c 759573aea2a4cc7b6f763b440e6868bfcfcb7ca94d812fa61ab24a194be2cb36 crypto/evp/pmeth_gn.c c2c8f6d17dc3d85ffcced051047c0b00ce99d119635f4626c5c6db3d59d86fbb crypto/evp/pmeth_lib.c ba4ff38738cbcfd3841d53a2fab92227638ceca176d3ffe50e486c9dcbabb5dd crypto/evp/s_lib.c 3c003fa01341a69c461b75cffd93cf31a1899373d7e95a1ef3754ea1bfbb77fe crypto/evp/signature.c 30af153213f8b008955486000c5a92507dc694c4af9ac6ed6fef3f290efa3e52 crypto/evp/skeymgmt_meth.c 64f7e366e681930ba10267272b87dba223b9744a01c27ba0504a4941802a580d crypto/ex_data.c d986ec74995b05ff65a68df320ab45894ba35d7be4906f8d78ca5fca294a4e6c crypto/ffc/ffc_backend.c a12af33e605315cdddd6d759e70cd9632f0f33682b9aa7103ed1ecd354fc7e55 crypto/ffc/ffc_dh.c 854378f57707e31ad02cca6eec94369f91f327288d3665713e249c12f7b13211 crypto/ffc/ffc_key_generate.c 4e973d956d4ec2087994de8e963be1a512da1441f22e6e7b9cd7ee536e3ff834 crypto/ffc/ffc_key_validate.c e032f3d46830d31cd957e1f3917a6a663c5ad3b9d79fc3d661f025822318d0de crypto/ffc/ffc_params.c be43754acce63bfd3caf08118d67af31b6f024c9df23debba7432a220bf293a1 crypto/ffc/ffc_params_generate.c 73dac805abab36cd9df53a421221c71d06a366a4ce479fa788be777f11b47159 crypto/ffc/ffc_params_validate.c f172c8c2112ee82716a7bc3a3e05d5cc26188c66b9d768ac1ff906845063d2cc crypto/hashtable/hashfunc.c 066192a43f3464714656bb98702d4b02f135becc3c5e1fd943886bd5dc808b0b crypto/hashtable/hashtable.c 7a9af0b14f1463b36de0689bc434a318adcb7990bb23862bf1d2a0adf510583a crypto/hmac/hmac.c df7ed80c3c2c0df4bf6a3d5379655d0ba9147d4f4e9f7509672bc9273f163bb8 crypto/hmac/hmac_local.h 0e2d6129504d15ffaf5baa63158ccec0e4b6193a8275333956d8f868ef35127e crypto/ia64cpuid.S c685813be6ad35b0861ba888670ef54aa2b399d003472698e39426de6e52db59 crypto/initthread.c 8727fbbb867fca990238ba37c17ae67e4b78a02769913425925ee841af5c0b07 crypto/lhash/lhash.c 22261096a117533e78012f5f18586b6a81edb3e09ae8b206b5eb9a0a5c054adc crypto/lhash/lhash_local.h 899ba6a9049a61d5b175637907f747f58863cd8950409cefac8fbc8f574f970c crypto/loongarch64cpuid.pl 460a7af09cde89a820b091522ada1310cfcec99c60aee505f94c48c35e9a29e8 crypto/loongarchcap.c f866aafae928db1b439ac950dc90744a2397dfe222672fe68b3798396190c8b0 crypto/mem_clr.c 18127868d868ca5705444c24f7dc385391ba31154fc04ff54949739e8fa7fdfc crypto/ml_dsa/ml_dsa_encoders.c 825105b0a2c4844b2b4229001650ff7e61e1348e52f1072210f70b97cd4adb71 crypto/ml_dsa/ml_dsa_hash.h -c82201cf1a17ff2d4b169dcd4402d3d56f4685e460a1447e021db4abd67f7f0e crypto/ml_dsa/ml_dsa_key.c +c467f4400d399aad6b51746ef2575d1e04d260a1bf901b35ca55624fe62e650e crypto/ml_dsa/ml_dsa_key.c 579c1a12a5c5f014476a6bf695dc271f63074fb187e23ffc3f9ccb5b7ea044f1 crypto/ml_dsa/ml_dsa_key.h 3f98eb0467033d0a40867ef1c1036dcfea5d231eeac2321196f7d7c7243edace crypto/ml_dsa/ml_dsa_key_compress.c 983d164bfa3dbe8d85ad1fdc24d897e79d9246d96d9c1862855c6c538b387ad9 crypto/ml_dsa/ml_dsa_local.h 0490a89372b79d98c2fdc294f836fddd7a54a148202ffbd50c2d4371816a94d8 crypto/ml_dsa/ml_dsa_matrix.c ff65c82c56e341f47df03d0c74de7fb537de0e68a4fa23fa07a9fdb51c511f1c crypto/ml_dsa/ml_dsa_matrix.h 5367cefcf6cdfc4f301e719ce884910f86b31c84b27e2a7337aae43af8623205 crypto/ml_dsa/ml_dsa_ntt.c 5927088185ecfdbfec666fb252162e11e7dbccb67320683b14349a189b770f8d crypto/ml_dsa/ml_dsa_params.c 10e37ab3ee09a45d99007665e073efb2b062c819f30af8694c6b0f411eb33822 crypto/ml_dsa/ml_dsa_poly.h 672a4ff05096f5253afd0f4d8447c298299c1901a1d052e64e41daa5c8ddcd27 crypto/ml_dsa/ml_dsa_sample.c 1d7f57a41034988a4e7d4c9a998760d2ef802c5e90275d09a3ca31c5f3403d94 crypto/ml_dsa/ml_dsa_sign.c 5217ef237e21872205703b95577290c34898423466a465c7bd609b2eb4627964 crypto/ml_dsa/ml_dsa_sign.h abd934284bcd8061027a69f437fa4410c6b72cd950be1ebe048244d036371208 crypto/ml_dsa/ml_dsa_vector.h -defc2e4e81ff1b78056c795bc0565f4241a259c2957abe84a51bcbc1e4ace3f1 crypto/ml_kem/ml_kem.c +8c4f7238f68f959f2ad1e2529c567364c5a8818898355c82818521e03239ea76 crypto/ml_kem/ml_kem.c 36e24eae5d38cc9666ae40e4e8a2dc12328e1159fea68447cb19dab174d25adf crypto/modes/asm/aes-gcm-armv8-unroll8_64.pl 33357356cd739d4ae89d52f0804b6900e4b94d8829323819c6f64c8908e978df crypto/modes/asm/aes-gcm-armv8_64.pl bcc09bdb474f045d04c983fa09c31a010c5a25513f53a5d3653ade91304f0f96 crypto/modes/asm/aes-gcm-avx512.pl 400a202abf66c6a3430965c38f7164ac297c856e8585862f59e3ff188bb35a6b crypto/modes/asm/aes-gcm-ppc.pl dd0de5ca8913a941cfff781a42fba43227e133976a24d0fddebf63909f7e010a crypto/modes/asm/aes-gcm-riscv64-zvkb-zvkg-zvkned.pl 4589a5c1d612631be70c998415dceabd344b6553e55528be4d62f2d923b99230 crypto/modes/asm/aesni-gcm-x86_64.pl c2e874a8deb418b5d8c935b2e256370566a5150e040c9fa008cdb5b463c26904 crypto/modes/asm/ghash-alpha.pl 6bc7d63569c73d7020ede481f2de05221ac92403c7cc11e7263ada7644f6aa9b crypto/modes/asm/ghash-armv4.pl 097975df63370de7ebea012d17de14fc1f361fb83acf03b432a99ae7d5bceb24 crypto/modes/asm/ghash-c64xplus.pl fdde3bc48b37790c6e0006014da71e7a831bbb4fdbfcda2d01dbe0ceb0ba88fa crypto/modes/asm/ghash-ia64.pl e472d73d06933667a51a0af973479993eed333c71b43af03095450acb36dbeb4 crypto/modes/asm/ghash-parisc.pl e6d6ce559210aee1e97f098683e290c221cc90f6f4f8047b331e8071a8387559 crypto/modes/asm/ghash-riscv64-zvkb-zvbc.pl 4c960949a5b7688f9019e177c24382dd1e78f6d343f3c4326bebbc065eb3a9f2 crypto/modes/asm/ghash-riscv64-zvkg.pl 494b4b36fd7c7d0e464be76f723c46ae7ad173593ff0556525edfdc974e66c32 crypto/modes/asm/ghash-riscv64.pl 92071f9c046f312c4eb7df483f385bc71ade863392e1acf3e821912bcc5cfaa7 crypto/modes/asm/ghash-s390x.pl 6af1a05981e1d41e4dea51e58938360e3abc4a4f58e179908242466d032b1a8a crypto/modes/asm/ghash-sparcv9.pl 26f55a57e77f774d17dfba93d757f78edfa3a03f68a71ffa37ccf3bfc468b1e2 crypto/modes/asm/ghash-x86.pl 487e23973c9c782d375a956da6231e91f450182d8822d3f86fd4924e143fed70 crypto/modes/asm/ghash-x86_64.pl a4e9f2e496bd9362b17a1b5989aa4682647cefcff6117f0607122a9e11a9dfd9 crypto/modes/asm/ghashp8-ppc.pl 92f17ee53bd40123358ce5b37bcd6063bfa7d6860dd734d4ac585249c03a6b32 crypto/modes/asm/ghashv8-armx.pl 65112dfe63cd59487e7bdb1706b44acfcf48ecede12cc3ae51daa5b661f41f06 crypto/modes/cbc128.c 1611e73dc1e01b5c2201f51756a7405b7673aa0bb872e2957d1ec80c3530486f crypto/modes/ccm128.c d8c2f256532a4b94db6d03aea5cb609cccc938069f644b2fc77c5015648d148d crypto/modes/cfb128.c af1c034152d82b29cb7c938c8516cfd136b62bac0908c1d40eb50790d23b288c crypto/modes/ctr128.c d4ddb087eb4dd54b8e37a414e32d8a2d4e42a7cf2766fc2051e4e31acdf3419c crypto/modes/gcm128.c bdf25257b15eca206be4d950d2dd807ca5f058f91f54edbd7a0d312ed83eef8e crypto/modes/ofb128.c e55a816c356b2d526bc6e40c8b81afa02576e4d44c7d7b6bbe444fb8b01aad41 crypto/modes/wrap128.c 608a04f387be2a509b4d4ad414b7015ab833e56b85020e692e193160f36883a2 crypto/modes/xts128.c fb874ea18e9754dde11ef1c2993818074ff7cd8a74a981598745f7e11317bb91 crypto/modes/xts128gb.c f867b6de6ac34a6aa5e2438f3d74506bfe808d3ed74217a40e61890230b32f5d crypto/o_str.c b0decda3aae1d3e07cf3cbe9153cdde9deafe65fae346cd208951b4d7dec512e crypto/packet.c 05563d44cb345e7859093296f95a3ea5139fcc316e98fcb86c6748ee49363a84 crypto/param_build.c cae7bd4973d36edbdc3bdd8d2c8d157f2c4fcfae00fdf821b67aebb789bc8aa6 crypto/param_build_set.c 7b32b19c1cf7152ef7e55e8ae7a045be4882da84ecd82ddf24df961656ec581b crypto/params.c c0e0ba07ca5d4acfe450e4ae53a10ed254097ed2f537f01a4a43a9f5b5cab501 crypto/params_dup.c fc2432f5a76784d4ca47db1803c8b19acbaea26987f8e33dd8cc5571f8101b40 crypto/params_from_text.c f50450f7e5f6896fb8e3cde2fdc11cc543124c854ef9d88252a166606ca80081 crypto/params_idx.c 9620a96eb5e411f5c96c210fb7975afe6b24635e4c5565be34fb8d10589890e7 crypto/ppccap.c 46fa4994a6234a98a2845d9337475913f6bc229f1928abc82224de7edf2784b8 crypto/ppccpuid.pl 467c416422ecf61e3b713c5eb259fdbcb4aa73ae8dee61804d0b85cfd3fff4f7 crypto/property/defn_cache.c 91c1f1f8eb5588ed9da17386c244ae68a6a81717b1c7ab6c9f1a6a57973a039f crypto/property/property.c 66da4f28d408133fb544b14aeb9ad4913e7c5c67e2826e53f0dc5bf4d8fada26 crypto/property/property_local.h -d32105cb087d708d0504a787f74bc163cc398c299faf2e98d6bb5ae02f5ce9b7 crypto/property/property_parse.c +1e99a3934812f99dad79cbfbb6727ad61b6093711c1a6c74d4b50f9318152611 crypto/property/property_parse.c a7cefda6a117550e2c76e0f307565ce1e11640b11ba10c80e469a837fd1212a3 crypto/property/property_query.c 20e69b9d594dfc443075eddbb0e6bcc0ed36ca51993cd50cc5a4f86eb31127f8 crypto/property/property_string.c 10644e9d20214660706de58d34edf635c110d4e4f2628cd5284a08c60ed9aff8 crypto/provider_core.c d0af10d4091b2032aac1b7db80f8c2e14fa7176592716b25b9437ab6b53c0a89 crypto/provider_local.h 5ba2e1c74ddcd0453d02e32612299d1eef18eff8493a7606c15d0dc3738ad1d9 crypto/provider_predefined.c e13cf63765dd538a75eb9d2cb8fcb0243e6bd2988dd420c83806a69984dad558 crypto/rand/rand_lib.c fd03b9bb2c23470fa40880ed3bf9847bb17d50592101a78c0ad7a0f121209788 crypto/rand/rand_local.h 426ba915ca65a770f8264129f8ac47db7aaf06c6ae51517c5d775eacdf91b9f6 crypto/rcu_internal.h 0c1d3e0e857e9e4f84752a8ef0b619d8af0d81427b52facbd0174e685dac9a47 crypto/riscv32cpuid.pl 231263dffc16987f5288592ebf4c0738902d5146bfc16bcd8a157e044cb697da crypto/riscv64cpuid.pl 0b0f3c7757447c2374338f2008c6545a1d176dcbdb41f06873f4681dc43fd42e crypto/riscvcap.c f0c8792a99132e0b9c027cfa7370f45594a115934cdc9e8f23bdd64abecaf7fd crypto/rsa/rsa_acvp_test_params.c 1b828f428f0e78b591378f7b780164c4574620c68f9097de041cbd576f811bf6 crypto/rsa/rsa_backend.c 38a102cd1da1f6ca5a46e6a22f018237964336274385f5c70cbedcaa6997647e crypto/rsa/rsa_chk.c e762c599b17d5c89f4b1c9eb7d0ca1f04a95d815c86a3e72c30b231ce57fb199 crypto/rsa/rsa_crpt.c -0fa3e4687510e2d91c8f4b1c460b1d51375d9855ed825b3d6697620b146b52d1 crypto/rsa/rsa_gen.c +a3d20f27ae3cb41af5b62febd0bb19025e59d401b136306d570cdba103b15542 crypto/rsa/rsa_gen.c f22bc4e2c3acab83e67820c906c1caf048ec1f0d4fcb7472c1bec753c75f8e93 crypto/rsa/rsa_lib.c 5ae8edaf654645996385fbd420ef73030762fc146bf41deb5294d6d83e257a16 crypto/rsa/rsa_local.h cf0b75cd54b61b9b9a290ef18d0ddce9fb26a029a54eb3f720d9b25188440f00 crypto/rsa/rsa_mp_names.c 5c60f6e05db82e13178d805deb1947b8eee4a905e6e77523d3b288da70a46bb5 crypto/rsa/rsa_none.c cf7e95467a6e6681069ba0c6a0befeb631b499d9b2ab12db0e93967746686f11 crypto/rsa/rsa_oaep.c 752f35ccaea51eaee693c5b08e8e9909a978d8e79f71dda0b33b3ef72554f6e0 crypto/rsa/rsa_ossl.c 54446a41065d85d22ed521285196bf285427a071d32d00d070b2248723c2a914 crypto/rsa/rsa_pk1.c b0fbf0b55d2afac9b1a1e871bf8cc6f0a41b34cf695c393d97e716536928931a crypto/rsa/rsa_pss.c bf6d300b7e7e9e512a47c5bd1f8713806ae3033a140d83dfae4a16ad58d11170 crypto/rsa/rsa_schemes.c 58db0509f34d970a2f206d468f718c17513970315d5d5ec92822fe6f4b6523fa crypto/rsa/rsa_sign.c 83529424639f77832d2c189c0134ce514b35a296567ac1a2936a9c4ed6407239 crypto/rsa/rsa_sp800_56b_check.c dc0af42319118811e1fa250f1647634f510f9ffcd720ea5141db4fd090938c46 crypto/rsa/rsa_sp800_56b_gen.c 1c1c2aeeb18bf1d69e8f134315b7e50d8f43d30eb1aa5bf42983eec9136a2fdc crypto/rsa/rsa_x931.c 0cfca169d8071429d969d5beccd2b93f824202b4371f29344feb3e06800e3c77 crypto/s390xcap.c f5ef5e2b93dd4e4c2d43b684fcbadf500e8fb0e5738d5f480dcb053a2dc3bd53 crypto/s390xcpuid.pl c865dba12debe9ad4a0f0b8c078b5c3e614c83a851cf9666cd3c4c7a9992f319 crypto/self_test_core.c 8f31ece930473524b73fe7729a71cf925e8083ae8883c179d710c45ce748952a crypto/sha/asm/keccak1600-armv4.pl 94751245b4ef1fabb755e8fe53dd0bb26029900e97c4111e5d9a56458ccced98 crypto/sha/asm/keccak1600-armv8.pl 12b7acce2fba0bc0e1ca07842ec84be6a022f141c86e077abb42c864af1d8d9c crypto/sha/asm/keccak1600-avx2.pl faf0cccb685d5abc807e08db194f847c67b940da2fc3c235c210dc31d73a5334 crypto/sha/asm/keccak1600-avx512.pl be1e7dd9998e3f31cfa6e1b17bc198aeec584a8b76820e38f71d51b05f8a9f2a crypto/sha/asm/keccak1600-avx512vl.pl 33bdcc6f7668460c3bdf779633e43bfad62b937042a73acb007b462fc5b0a034 crypto/sha/asm/keccak1600-c64x.pl 09fc831dd39bd90a701e9b16d9e9987cc215252a22e1e0355f5da6c495fca35a crypto/sha/asm/keccak1600-mmx.pl 6689c3adaa270bd88026ca686ce76b8aaa83a7cadf3954d84d3cf89c044cc958 crypto/sha/asm/keccak1600-ppc64.pl fea3ce181c7a33bc673e3a4607e0f737a3a3e5958a3826596fb911b1297e2ca4 crypto/sha/asm/keccak1600-s390x.pl 3fb93b9440f5c3008b5c876a8106acc5f8d38f1afedd79381f0befec7dd7d72b crypto/sha/asm/keccak1600-x86_64.pl 831b8b02ab25d78ba6300ce960d96c13439bfba5844e13061e19c4e25cbacc3d crypto/sha/asm/keccak1600p8-ppc.pl 75d832db9bf0e98e7a5c522169060a6dd276c5118cfb297fc3f1111f55cd4007 crypto/sha/asm/sha1-586.pl c96e87d4f5311cd73bbdf499acc03418588be12426d878e157dd67e0099e0219 crypto/sha/asm/sha1-alpha.pl 695ef6f8041f37f4b39cb7099e9c7c3a29d6f823823df7333530d375f5f5e01b crypto/sha/asm/sha1-armv4-large.pl cb32284af92d99d7046b99dd5bbd894d53531f7b99d351235a939c542680193b crypto/sha/asm/sha1-armv8.pl 11d332b4e058e9fa418d6633316d2e9f9bf520a08b2d933e877bdf38b2edefcf crypto/sha/asm/sha1-c64xplus.pl 32ff0e701a7b8f25bcfe8477b20795de54f536527bd87d3ce694fd9aaae356d4 crypto/sha/asm/sha1-ia64.pl de6c7e8c1e27779a8cf1ce2a04f487a3d4dc510d5ba240cd06128ecc8574e424 crypto/sha/asm/sha1-mb-x86_64.pl 0f5c63cf09e950d1b488935ab3b5562e3e9d5cd1a563fb88a41e3dae90a35e6d crypto/sha/asm/sha1-mips.pl b5ffd7b6dbb04c05de7efa2945adb67ea845e7e61a3bf163a532f7b6acdf4267 crypto/sha/asm/sha1-parisc.pl 482cd23ca6ec38d6f62b90c68f9f20643579c50f2c0fbb0dab1c10a0e35efe77 crypto/sha/asm/sha1-ppc.pl 28cf69efd53d7a5a8c32e0f8db32c193f41b91faf44f5f59944334bc3f5aa337 crypto/sha/asm/sha1-s390x.pl 7fd355b412ddfa1c510e0ba3284f75b1c0d621b6db2ecb1d2a935d5cdb706628 crypto/sha/asm/sha1-sparcv9.pl 24554e68b0e7b7db7b635ff149549015f623ca0bcd9ae90439586a2076f6ae80 crypto/sha/asm/sha1-sparcv9a.pl 74d197cdd72400cabbff7e173f72c8976723081508b095dc995e8cd1abf3daa6 crypto/sha/asm/sha1-thumb.pl dc363497de4fa3bc88b16e834ddf4967aecabdba5ea3ddd6113cf00da7e278bd crypto/sha/asm/sha1-x86_64.pl c099059ef107f548ea2c2bab64a4eb8c277070ce6d74c4d32bb9808dc19c5fa3 crypto/sha/asm/sha256-586.pl 0f01f7b5b0699f1e8ca260439d009febfa5b85b9e7b0933d236467e383aaaa2e crypto/sha/asm/sha256-armv4.pl 93ddc97651ee3e779144a3c6b3e46a1bc4aa81e75cd7b9df068a2aef8743d25f crypto/sha/asm/sha256-c64xplus.pl 9a68b6642b20e3cdccd636c4a934a6e0114160506784583f684ad65aefac2872 crypto/sha/asm/sha256-mb-x86_64.pl b14670492f24cd0d2fedf8780e981b7da123203395c085334d4571b619b0a610 crypto/sha/asm/sha256-riscv64-zvkb-zvknha_or_zvknhb.pl dd82e1311703abb019975fc7b61fb87d67e1ed916dddd065aced051e851114b9 crypto/sha/asm/sha512-586.pl 16e68ac669860c5bf8e4db81cd3d64fc2c22168e129c2597e94b0f56fafcdfa8 crypto/sha/asm/sha512-armv4.pl c5c34b4633ce01517188f7179821e1bf50faf9c7d7255d34ab7c066b20920eb6 crypto/sha/asm/sha512-armv8.pl 6f548a088feae3b6faa179653ba449df9d3f5cda1e0561e5b5f120b32274d1eb crypto/sha/asm/sha512-c64xplus.pl 9fa54fbc34fd881f4b344374b9b4f8fb15b641424be7af9a31c71af89ae5d577 crypto/sha/asm/sha512-ia64.pl fb06844e7c3b014a58dccc8ec6020c71843cfdc5be08288bc7d204f0a840c474 crypto/sha/asm/sha512-mips.pl 11548f06d213947104a80898e000218ec0d6ff3f6913f6582de498476482ce9f crypto/sha/asm/sha512-parisc.pl 7c0c490ce6bb11a228853aecad5e164ce84e5bdabb8a6658ae7184782076c7d3 crypto/sha/asm/sha512-ppc.pl 07804b96dda856cffaef291641c4ae7f59288ed1e65e38823cfdcb74f8ac5295 crypto/sha/asm/sha512-riscv64-zvkb-zvknhb.pl 38e0455fd6a2b93a7a5385379ca92bc6526585ca1eb4af365fac4c78f7285c72 crypto/sha/asm/sha512-s390x.pl 0611845c52091b0208dd41f22ddef9dd1e68d3d92fa4c4360738b840a6314de6 crypto/sha/asm/sha512-sparcv9.pl 473874a27b031e3d6c3dd0388c7231aa299e07c5832fa7499a081488e6f5680a crypto/sha/asm/sha512-x86_64.pl 8725cabb8d695c576619f19283b034074a3fa0f1c0be952a9dbe9793be15b907 crypto/sha/asm/sha512p8-ppc.pl e10cd2ff1fb57f3a3b5a9264878910627de989284ed4f78483e5863285f7f26e crypto/sha/keccak1600.c 306cacd3f86e5cacaca74c58ef862516515e5c0cafaff48636d537fd84f1c2fb crypto/sha/sha1dgst.c 65ca7d67f3e3fc0314ccb179b734530bf1cdbde3d3cf428adc4c402f52e4b394 crypto/sha/sha256.c ac714ce14a0b1fe1c0cb5fea9e0e76a188048649c43f3b3a527945ab8554cba4 crypto/sha/sha3.c aef204d50f96b636576d8a52f8858fb5a4b2eb14bb60ebc14eb533df7a210e33 crypto/sha/sha512.c 6c6f0e6069ac98e407a5810b84deace2d1396d252c584703bcd154d1a015c3ea crypto/sha/sha_local.h dfd99e02830973ab349409ac6ba0ee901ba7736216030965bd7e5a54356abd7c crypto/slh_dsa/slh_adrs.c 1a2e505ac8ef45ff46f36ab89f5fb1d6a6888b2123a7cb75cf0eae849ee5de70 crypto/slh_dsa/slh_adrs.h 11d3895ea104d1238999f00b2beee4de71f35eea79065ac7b4536ee79d61d2dd crypto/slh_dsa/slh_dsa.c ab7b580b1cba302c5675918b457794a3b3d00aac42297312d9447bc6f6a40b09 crypto/slh_dsa/slh_dsa_hash_ctx.c 36007c2d3c7f6a405745a25d1a10b97ce781c7541b1610e51981f549c9852a5b crypto/slh_dsa/slh_dsa_key.c 4c7981f7db69025f52495c549fb3b3a76be62b9e13072c3f3b7f1dedeaf8cc91 crypto/slh_dsa/slh_dsa_key.h 5dcb631891eb6afcd27a6b19d2de4d493c71dab159e53620d86d9b96642e97e8 crypto/slh_dsa/slh_dsa_local.h adb3f4dea52396935b8442df7b36ed99324d3f3e8ce3fdf714d6dfd683e1f9f0 crypto/slh_dsa/slh_fors.c 3891252acdefc4eff77d7a65cc35d77bdca8083c9dd0d44ff91889ceafcccb45 crypto/slh_dsa/slh_hash.c a146cdf01b4b6e20127f0e48b30ed5e8820bec0fca2d9423c7b63eddf0f19af3 crypto/slh_dsa/slh_hash.h 6402664fbb259808a6f7b5a5d6be2b4a3cc8a905399d97b160cdb3e4a97c02c4 crypto/slh_dsa/slh_hypertree.c 98ba100862bb45d13bcddff79bc55e44eadd95f528dd49accb4da3ca85fcc52d crypto/slh_dsa/slh_params.c 86b16a2c36d708cb880ba49648bb3051c2997188c8ea6aec9292534b97232c7f crypto/slh_dsa/slh_params.h 1aa9dc1c6fe59d024485df9a6b782ac4d0656a31b12faee749fe098911799eaf crypto/slh_dsa/slh_wots.c 59db81a3342c0c89b030756168b9a7f09c938b2cd3498335108e0a32c041b6e7 crypto/slh_dsa/slh_xmss.c 9ef5a01caccc2eb15f72e367d0424737040ac8018479bbbbce3d216c655765c2 crypto/sparccpuid.S 5056b14a55665ffa342a9a1bb32c1c36886add5d0819869193427f33cee028f7 crypto/sparcv9cap.c c50c584c55e56347bb43aca4b796b5344d70daece3061f586b79c871c21f5d1a crypto/sparse_array.c 00f5a33a4c0fbba02685519d0fb3de75680619384f8fac30b43b9109ca0e5fec crypto/stack/stack.c c0c4fd0f112465c6766072e25268c2f9019430e2c08c3c0a4271603d24d79f04 crypto/thread/api.c e298c753be277ad9a2ac0132d9897cb4c85607dbb2d11cfefd0c98e0f6a723d9 crypto/thread/arch.c 5c02ff77d290ca0deb19672c1ed6fc0f47a0d630f61398a204a2684a7d418f0a crypto/thread/arch/thread_none.c 1506ddf108b99cd192b70dbb00154fbb5e632527fa0ef56796bda4c68f833464 crypto/thread/arch/thread_posix.c a00e16963e1e2a0126c6a8e62da8a14f98de9736027654c925925dadd0ca3cc1 crypto/thread/arch/thread_win.c 27ec0090f4243c96e4fbe1babfd4320c2a16615ffa368275433217d50a1ef76c crypto/thread/internal.c 67ba8d87fbbb7c9a9e438018e7ecfd1cedd4d00224be05755580d044f5f1317a crypto/threads_lib.c b1a828491d9ce305802662561788facac92dff70cca9ead807f3e28741ff21e0 crypto/threads_none.c -c659f7ce5c4b59d2a1cff78485fa8e89c8d20d5798df4afc1b94ff635ffc0262 crypto/threads_pthread.c +491e9c29d4a7b4dd627ea25c20ce4a33103565b3108b618c41c6816dfc675569 crypto/threads_pthread.c 9c3bf7b4baa302a4017150fbcaa114ee9df935b18d5a3a8c8015003780d4e7de crypto/threads_win.c 7edd638df588b14711a50c98d458c4fc83f223ed03bc6c39c7c8edf7915b7cfa crypto/time.c 88c5f9f4d2611223d283ebd2ae10ae5ecbb9972d00f747d93fcb74b62641e3f9 crypto/x86_64cpuid.pl 085d9fe93adf232f1ff838be9235046c2c2abe2daeb0e6342921d8f2e955dc18 crypto/x86cpuid.pl f061000d8eafc58cebc40adc6484a392653a43dad6e1b963e794a87b4c85a7a4 include/crypto/aes_platform.h 44222ee3dbcc71acf0fc40fcb5f700d307eb843b3d456e11d04539d9613e920b include/crypto/asn1.h 8c6f308c1ca774e6127e325c3b80511dbcdc99631f032694d8db53a5c02364ee include/crypto/asn1_dsa.h 7a879191cabf49ed390354e776b40b07f3d238a5b4d1e9207357a69de0416b2a include/crypto/bn.h 1c46818354d42bd1b1c4e5fdae9e019814936e775fd8c918ca49959c2a6416df include/crypto/bn_conf.h.in 7a43a4898fcc8446065e6c99249bcc14e475716e8c1d40d50408c0ab179520e6 include/crypto/bn_dh.h 76cec717df68b4cbe33cf6fb557c9724ab027a1ab5e06b27eb0294fef2edd75b include/crypto/cmac.h 66d6f120bef9ff1bb33867a1071a315528a616c0ae0c64fa88d70710cccb8b5b include/crypto/context.h e69b2b20fb415e24b970941c84a62b752b5d0175bc68126e467f7cc970495504 include/crypto/cryptlib.h 6c72cfa9e59d276c1debcfd36a0aff277539b43d2272267147fad4165d72747c include/crypto/ctype.h f69643f16687c5a290b2ce6b846c6d1dddabfaf7e4d26fde8b1181955de32833 include/crypto/decoder.h 89693e0a7528a9574e1d2f80644b29e3b895d3684111dd07c18cc5bed28b45b7 include/crypto/des_platform.h 48d133a1eb8c3b3198cfe1cafda47f9abe8050d53004f3874f258a78f29b9e48 include/crypto/dh.h 679f6e52d9becdf51fde1649478083d18fa4f5a6ece21eeb1decf70f739f49d5 include/crypto/dsa.h c7aafee54cc3ace0c563f15aa5af2cdce13e2cfc4f9a9a133952825fb7c8faf5 include/crypto/ec.h adf369f3c9392e9f2dec5a87f61ac9e48160f4a763dae51d4ad5306c4ca4e226 include/crypto/ecx.h ac1f521e6ab314b29389ee229f2a1fbed93ba945f9300ee4231e5fe4e7c40ac9 include/crypto/evp.h bbe5e52d84e65449a13e42cd2d6adce59b8ed6e73d6950917aa77dc1f3f5dff6 include/crypto/lhash.h 906bc2316e4f4651e5db7a8273ec3bb4bcbfb55f0f484bebdae4f6d0ce033bdf include/crypto/md32_common.h 6a6d2e4cd3195da0bc8eaba09fb9751ab8374b3870364542cceeaac6fc5e1aa5 include/crypto/ml_dsa.h 21800b12e6ff053fc7fcaec6352734700238b23c275525df92075d4f569b7d57 include/crypto/ml_kem.h 6e7762e7fb63f56d25b24f70209f4dc834c59a87f74467531ec81646f565dbe3 include/crypto/modes.h 920bc48a4dad3712bdcef188c0ce8e8a8304e0ce332b54843bab366fc5eab472 include/crypto/rand.h 71f23915ea74e93971fb0205901031be3abea7ffef2c52e4cc4848515079f68d include/crypto/rand_pool.h -b1df067691f9741ef9c42b2e5f12461bcd87b745514fc5701b9c9402fb10b224 include/crypto/rsa.h +6f16685ffbc97dc2ac1240bfddf4bbac2dd1ad83fff6da91aee6f3f64c6ee8ff include/crypto/rsa.h 32f0149ab1d82fddbdfbbc44e3078b4a4cc6936d35187e0f8d02cc0bc19f2401 include/crypto/security_bits.h 80338f3865b7c74aab343879432a6399507b834e2f55dd0e9ee7a5eeba11242a include/crypto/sha.h dc7808729c3231a08bbe470b3e1b562420030f59f7bc05b14d7b516fa77b4f3a include/crypto/slh_dsa.h 7676b02824b2d68df6bddeb251e9b8a8fa2e35a95dad9a7ebeca53f9ab8d2dad include/crypto/sparse_array.h d6d1cd1ec7581046f5a84359a32ed41caad9e7c1b4d1eb9665ea4763de10e6b3 include/crypto/types.h 27d13538d9303b1c2f0b2ce9b6d376097ce7661354fbefbde24b7ef07206ea45 include/internal/bio.h 7c8bdf83fc61de37027111c24c41049debb2c9f856fa97bf6ac93319cfef1f35 include/internal/common.h 77616e7546ed1bae9df366327663261282b16664a616725436715df9ff99b598 include/internal/constant_time.h c5bb97f654984130c8b44c09a52395bce0b22985d5dbc9c4d9377d86283f11f8 include/internal/core.h bbba72ba1d0e2985cb316dd9f3bf63893dd58d5624ad7caa10aad81d8b6df0fc include/internal/cryptlib.h 9571cfd3d5666749084b354a6d65adee443deeb5713a58c098c7b03bc69dbc63 include/internal/deprecated.h dc5afb955d810feb5af9f8d25cd8a92118abef320fee95c07b04f301c4e0d96c include/internal/der.h 8059e715f981fbe02b5731610ed24bb6ae617a55e90b03f4260cbb6ccd71e8de include/internal/deterministic_nonce.h fd1722d6b79520ee4ac477280d5131eb1b744c3b422fd15f5e737ef966a97c3b include/internal/dso.h f144daebef828a5bd4416466257a50f06b894e0ce0adf1601aa381f34f25a9e7 include/internal/dsoerr.h 924fddff69e5ee237e38d48dd55d4c5f6d6ef8b6443bbe217c760009bbcc87c4 include/internal/e_os.h 6e33d1c6f82a4483a0e52ee3c9713e123efc5aba0601e7f13078aa45910cd70a include/internal/e_winsock.h c9cb7a25ba2c1a451ba7cca7e165606f891ee8d3e927c06a2e4f84db7f7622eb include/internal/encoder.h 70d3e0d5a1bd8db58dcc57bea4d1c3ed816c735fe0e6b2f4b07073712d2dc5ef include/internal/endian.h 4838a68ff626825c261df6a1fd21e156e25d8365af45552f29054d7038a7db3d include/internal/ffc.h 4c9c4b7fc19615fb480fe18c86521d57313d24a8de556681741054abc2e3a690 include/internal/fips.h 45e1f3a274ddce17d62681f3150eeb522ef9716b0b41bfdc33327cf72c4356d2 include/internal/hashfunc.h d9c95e7fe7ae09b2c4aff57eaefbec962cbbeb202ee3cf15950716760c83460f include/internal/hashtable.h f6f30785e3eced1ccdd4b149286ff2b8bbb860eb7e070cbe54c997aa022854da include/internal/namemap.h b02701592960eb4608bb83b297eed90184004828c7fc03ea81568062f347623d include/internal/nelem.h 3363405b2d6afab68f7e13921385ccb648fe7f77522bd0aa5fdf2d7af0b87660 include/internal/numbers.h 66f7c420e531383e8a93c1daccbdc4ab64d11e0ed167af1b7f7be54bd61329aa include/internal/packet.h f42d4a6108a18ade3eb99682c072adf83889b6ba3fc80ee3e20929ed8d0f7137 include/internal/param_build_set.h 5c6c98b1a642b999c909c7cfb91e7925422fbd0b9eca56210ea745bc20668783 include/internal/param_names.h.in 46d7980258a8d11353af3e3dab87c368eec054e46ac8a0facec68b23ba94d91b include/internal/params.h d4ac19b28ea61f03383364cfad1e941cac44fc36787d80882c5b76ecc9d34e29 include/internal/property.h 727326afb3d33fdffdf26471e313f27892708318c0934089369e4b28267e2635 include/internal/propertyerr.h f3ac89b2eaaa7f83d7d2606be65aff28136aec5b961884c45f79bf8540ad6f34 include/internal/provider.h 95d21e761402fcbf1d3bdb261e425316b07d2790dd190e4eeaa1e21e40ff9a59 include/internal/rcu.h baf5df9b8b91cb5b821ee27348a47364c9dfc86144c9573403e9d54fa970f81f include/internal/refcount.h a01805714966e6de536ee182d5476cb1708d019631f016f331a034cf3b2b3158 include/internal/safe_math.h d11b69bed0965e47c3be0e0f44a812a7eb69ae91d7ca8f148a91d6ef6d255a47 include/internal/sha3.h 9a2db71c880a62946d7c4ed259c5069d689a364a23fc275d97b638517bca8f01 include/internal/sizes.h d44d03310e0af9aaf33f2f8552f7ef84ba7612d55ceec48b53bf86d774bbb149 include/internal/skey.h abf03dc8635f2925bdc2299feabe115f8d5d6eaa450b421172ded222872386ba include/internal/ssl3_cbc.h 24f41a1985fa305833c3f58030c494d2563d15fc922cdf3eeb6a7ea8c135a880 include/internal/symhacks.h 6b186bc71a3a41681c94b5bf0a201741f15ee5e6e6a3973d5e878ea3de22e6db include/internal/thread.h 8a14b0e830da8ace10e661d7b1bca301a9bf2662f0c55e07aef3ff7344142b53 include/internal/thread_arch.h 640cc6a2aae208073a7f495c08b4c5006a69e8ac1c2d9aaaafd56b0e74d5f859 include/internal/thread_once.h 634148b5dffee774f7c3e271885cfc69219d403526936e390d4925f209f09630 include/internal/time.h d7930b6d7f59dda7b6c39adb76d0be05db90ae7448dde7eae52ed9230ed93e3b include/internal/tlsgroups.h 0b41d6646786c16083fa071b788dd9fec0da1c8f715a7e2ad3a05d77520b162d include/internal/to_hex.h 7d97636320f6ce993ff6ff15741b90323a32fbeea4960fa64be2eb147063a149 include/internal/tsan_assist.h 2b38fb6e65d549aca3b2c76907daf67124f395251c0261dec26faa54da8d6d73 include/openssl/aes.h 8edd30869dcc93e7452d6443b1757383e06f92ee7ade59c6f5c698783f334266 include/openssl/asn1.h.in 8bc93f8b980835aff9b8e788c3cd6654a8fc5f1405d3934b968118c4b56c282a include/openssl/asn1err.h 1550474ee05423896ec4abfb6346f1bc44c7be22329efac9ea25de10e81d549c include/openssl/asn1t.h.in 73ff02a145387accef5b019f77f2611c12a70fdc0c0826e34322ac4b65d05326 include/openssl/bio.h.in fe5ab4bc904b7c77e5411c4b7dda6d29595eb60a87f00e30ab32f48391f98b44 include/openssl/bioerr.h 9caa80699882befcce556446a45e5ffde5aa938aa2aae0e8ecd46c9c6a3fe419 include/openssl/bn.h 9ad8b04764797f5138f01f549ba18b44cf698ffc7fe795fef42c1822d84a6ff4 include/openssl/bnerr.h 93954e6c450716e158948d67f64736a451ea9473d02f3a908f3bc8a96cf049a5 include/openssl/buffer.h 9d48e6cab2ee98ae94d7113e4c65f000d97e125fdb3445642865ace3f34d06ac include/openssl/buffererr.h c1f6110f5f8d5faa3805215d8e5877e81e4108cd6d04f73b06d43ba5661d1a1a include/openssl/byteorder.h 8e772c24b051e59d2f65339f54584e3e44165a3eaf997d497faea764990130f5 include/openssl/cmac.h 1342636127f3d365ac538115e706ea1aea43ab8fa79e86756e818b30a72789c7 include/openssl/conf.h.in bb45de4eafdd89c14096e9af9b0aee12b09adcee43b9313a3a373294dec99142 include/openssl/conferr.h 69d98c5230b1c2a1b70c3e6b244fcfd8460a80ebf548542ea43bb1a57fe6cf57 include/openssl/configuration.h.in 6b3810dac6c9d6f5ee36a10ad6d895a5e4553afdfb9641ce9b7dc5db7eef30b7 include/openssl/conftypes.h 28c6f0ede39c821dcf4abeeb4e41972038ebb3e3c9d0a43ffdf28edb559470e1 include/openssl/core.h b59255ddb1ead5531c3f0acf72fa6627d5c7192f3d23e9536eed00f32258c43b include/openssl/core_dispatch.h d37532e62315d733862d0bff8d8de9fe40292a75deacae606f4776e544844316 include/openssl/core_names.h.in 01ed3af4e25b9be3453a8f13d7dd3b4e9e73889bbed338e0d4b8021f0d17aa82 include/openssl/crypto.h.in 628e2a9e67412e2903ecb75efb27b262db1f266b805c07ece6b85bf7ffa19dac include/openssl/cryptoerr.h bbc82260cbcadd406091f39b9e3b5ea63146d9a4822623ead16fa12c43ab9fc6 include/openssl/cryptoerr_legacy.h 83af275af84cf88c4e420030a9ea07c38d1887009c8f471874ed1458a4b1cda7 include/openssl/decoder.h 503b45367b035ddf6e54587125c2100ceec324d646e6f3df92c12513185e977c include/openssl/decodererr.h fa3e6b6c2e6222424b9cd7005e3c5499a2334c831cd5d6a29256ce945be8cb1d include/openssl/des.h 0837b1ec7074b37d2e1d5ac46d6003c3fc4f1ff10f2e44c64b5709b0bacec4e8 include/openssl/dh.h b74a54335bb2f55caacd5c3fd10db3575166fc35077dc5740059243f70e0b179 include/openssl/dherr.h 3cfb7211419c5dcc98b9a20713e2245befa0182a10615edb89a5ce0a0725a787 include/openssl/dsa.h 276d1f6e111ba933bc708e6a0670047cbe0d0b67aabe31807abbbc231de4d8cf include/openssl/dsaerr.h 25bcf84a034502eaa16354c61bb9a2f2f3d607b2f343bbe7fa1f1e810a353db0 include/openssl/e_os2.h bc9ec2be442a4f49980ba2c63c8f0da701de1f6e23d7db35d781658f833dd7b9 include/openssl/ebcdic.h 49e8a9d226d543ac482cecdc01c83b7ccdfbfca6ad92d690aad75a245148e2ab include/openssl/ec.h 7aa8c5bee779af59d4733f6a50f7f6be39f1eb43409e5b3357440f9a7d0ca115 include/openssl/ecerr.h 61c76ee3f12ed0e42503a56421ca00f1cb9a0f4caa5f9c4421c374bcd45917d7 include/openssl/encoder.h 69dd983f45b8ccd551f084796519446552963a18c52b70470d978b597c81b2dc include/openssl/encodererr.h aa02455482d744418123266f581b9b4310ba678c7d28c10fffc5eec74ce3c8ef include/openssl/err.h.in 29ea398f6a2dfa3d42516030f4b5e6b1de06bbff4326ae42a7e63e2380abe33a include/openssl/evp.h b2a8058dd51abe6c1ac4a0f32175f550a308efd31607a9cf1620aa032b1f7e55 include/openssl/evperr.h f37c13a7cc0b05a734efcafb7da321dcc366090c255da8ee532e5f2be2eaa152 include/openssl/fips_names.h fef2b79b4de2cd74b02f12f1c0515cb2eaca742b8ded67fce722fb417e818e25 include/openssl/fipskey.h.in 47a088c98ad536ea99f2c6a9333e372507cb61b9bdffb930c586ed52f8f261eb include/openssl/hmac.h aef20807146a62481c0dbd6c86b818a84fdfd877601738b4e51afc944ec3d59a include/openssl/http.h 3644c7094fd5310a103aa9adff947ad9aa87e0a48432471a4ca10b4885d215d3 include/openssl/indicator.h faab8accc9520269dd874126ae164a43526d5784e6280521c7ab3772c02b0a0c include/openssl/kdf.h 625258d115ddc5117eaa2ff126e548e25fb81336abead079e6f2028f4bce4e92 include/openssl/lhash.h.in 348e5a4083332bd3076e7195d31894405aa9acd3655fc090074b316f481c5f46 include/openssl/macros.h a8a45996fd21411cb7ed610bc202dbd06570cdfa0a2d14f7dfc8bfadc820e636 include/openssl/ml_kem.h 9184207c562fd1fa7bd3a4f1fadcb984130561279818f0cdfcf3e9c55be8a7d1 include/openssl/modes.h 6d40e3edc18bac56826b2beb9439e7e43a680867a0a9ae1d3f75e07dc72b024d include/openssl/obj_mac.h cb6bca3913c60a57bac39583eee0f789d49c3d29be3ecde9aecc7f3287117aa5 include/openssl/objects.h d25537af264684dff033dd8ae62b0348f868fcfec4aa51fa8f07bcfa4bd807ad include/openssl/objectserr.h fe6acd42c3e90db31aaafc2236a7d30ebfa53c4c07ea4d8265064c7fcb951970 include/openssl/opensslconf.h -fc914a750d798ac9fc9287e6359cfa1da214b91651deaaaa7e1a46b595cd0425 include/openssl/opensslv.h.in +6c1a8837bbba633db2a8951ff29ccfe09e7d2a24a37ee2af90f2d897c190da9a include/openssl/opensslv.h.in 767d9d7d5051c937a3ce8a268c702902fda93eeaa210a94dfde1f45c23277d20 include/openssl/param_build.h 1c442aaaa4dda7fbf727a451bc676fb4d855ef617c14dc77ff2a5e958ae33c3e include/openssl/params.h 44f178176293c6ce8142890ff9dc2d466364c734e4e811f56bd62010c5403183 include/openssl/pkcs7.h.in 8394828da6fd7a794777320c955d27069bfef694356c25c62b7a9eb47cd55832 include/openssl/pkcs7err.h ed785c451189aa5f7299f9f32a841e7f25b67c4ee937c8de8491a39240f5bd9d include/openssl/prov_ssl.h d8e2e31fbf88649efaabb6a999d9c464d4462b016c65c6bdf830b2ab4261a792 include/openssl/proverr.h 01ecfa6add534dfe98c23382e0f2faf86f627c21ce16c5b49bf90333fb4cac9f include/openssl/provider.h 765846563fbd69411aff6ce00bcc22f577f6407f5a80d592edb1dc10b580a145 include/openssl/rand.h 1c135b1e5ef06e052f554d52a744a9a807a8c371c848389ad836f9e4a923dd8e include/openssl/randerr.h 2f4f0106e9b2db6636491dbe3ef81b80dbf01aefe6f73d19663423b7fcd54466 include/openssl/rsa.h 2f339ba2f22b8faa406692289a6e51fdbbb04b03f85cf3ca849835e58211ad23 include/openssl/rsaerr.h 6586f2187991731835353de0ffad0b6b57609b495e53d0f32644491ece629eb2 include/openssl/safestack.h.in 39300fe80a46e0b76e07f10ada73a0ba55887c8cd5f98180b337ef6d5a3344d1 include/openssl/self_test.h a435cb5d87a37c05921afb2d68f581018ec9f62fd9b3194ab651139b24f616d2 include/openssl/sha.h c169a015d7be52b7b99dd41c418a48d97e52ad21687c39c512a83a7c3f3ddb70 include/openssl/stack.h 22d7584ad609e30e818b54dca1dfae8dea38913fffedd25cd540c550372fb9a6 include/openssl/symhacks.h 8acd8147402a816c835b4240e18972072bab41d3fb6ee364fc17e543d6a854f6 include/openssl/thread.h f09bc8a337d80f65dafb281a1c129a258e51ec320bd35f82b8baff780f22dadb include/openssl/trace.h 164a4df1283504b2a08a0682e722ebced269ad0660382f6cba74063b013a2165 include/openssl/types.h 19ef0ff7da7c46425f8425745de75a24eed318abc0d715f1ac4095257101d5f3 include/openssl/x509.h.in 81b3468e98d4a94b8ea95517f38b440feede2dbbba610e47ff2f0a694cb55015 include/openssl/x509_vfy.h.in ef9e7c7a2176cf1b3f2d0c52b7cc1f47ad0666fbbd8a9479cbb39b7bf0dfe06b include/openssl/x509err.h c0a9551efccf43f3dd748d4fd8ec897ddaabbc629c00ec1ad76ce983e1195a13 providers/common/bio_prov.c 4786999b1fd6933b05f21abd7033451fbd56e1d842c620cf65160ac22d03791f providers/common/capabilities.c f94b7435d4ec888ec30df1c611afa8b9eedbb59e905a2c7cb17cfc8c4b9b85b8 providers/common/der/der_digests_gen.c.in 424d7b2ece984a0904b80c73e541400c6e2d50a285c397dd323b440a4f2a8d8e providers/common/der/der_dsa_gen.c.in 27ff361a5fbfc97cd41690ab26639708961d0507b60912f55f5919649842c6ae providers/common/der/der_dsa_key.c 2529d253b3e45c33249461fdedb2c32b3c16a7a305fe4920f2a79e7b3f16ed3f providers/common/der/der_dsa_sig.c a81d36446eb8afa5c2318e24b86b52647059b4721ee52309b741e4ee78af29dd providers/common/der/der_ec_gen.c.in b8f2f94daeaf20c636c90e386284c246cfded0c8275411fa02fe68b534520b95 providers/common/der/der_ec_key.c 9104cd39dddd6e1a6e8f267656482131f4d0765e96fdced1f7344817a1c8ed7e providers/common/der/der_ec_sig.c 03a5620654438c58a8f971398e68922a3f33a519e2c92edb141d13ef4cbc4651 providers/common/der/der_ecx_gen.c.in f3b089fd3dcccc8e3ebfbbdbf87c47d58330f82bd0e2a1223da74977930cccf1 providers/common/der/der_ecx_key.c 4132ea0bbb9dcdc44d90ca072b7a8d715dca0875d426aa12d770e60d5f0d46cc providers/common/der/der_ml_dsa_gen.c.in 341a74d94c93a9fbe663e489801fa586d8ff306615e230d2b1c74354003c90e0 providers/common/der/der_ml_dsa_key.c 5b3b0ae8da0fad1f7ba8b5fba2206210884728bf69a8aa00644036eb51953467 providers/common/der/der_rsa_gen.c.in 029aec80a45b477f7c8bd8d24d48e36de92f8056b421e9f128c336dc246dbc4e providers/common/der/der_rsa_key.c 7e8d579986f53eaf1875d677e5cf4adfd4ccf79db0275368f6cac580ab6007ca providers/common/der/der_rsa_sig.c 3c0fa8fb3050077f82176790b0a06ac88891ae236fbc918b18d1ae7e75c0da94 providers/common/der/der_slh_dsa_gen.c.in 5d0e18a680f82632bda6ee9fb9ef61993ce0f2bc9884451e946a25130f27fc99 providers/common/der/der_slh_dsa_key.c 0b18bc007f296e16f6210956f5b6ab612b77d8a95170f12ae32764125901db6d providers/common/der/der_wrap_gen.c.in d447cd774869da68a2cc0bbb19c547ee6ed4858c7aee1f3d5bba7796f97823a9 providers/common/digest_to_nid.c 440c8ce0a4ca9f63157202bbfa26e12fec25847215fbae3416274124604ada6e providers/common/include/prov/bio.h 18ce379903b078446945da9116026da8639b4b0d81d357f86f9674a2a5cb94ef providers/common/include/prov/der_digests.h.in c0a020765feb7ededc7e6f20b2b140dca09f347cc72404a5c7971df82b2f9ad0 providers/common/include/prov/der_dsa.h.in 6024645ac9e165685b0a44a20feb342355eb06c07b7c7954508a125348570aea providers/common/include/prov/der_ec.h.in 5b6b7d8d12011c48195b7db8f65bc4bc4a48fb753763a3ce5006dc227b5139d7 providers/common/include/prov/der_ecx.h.in ceea7616712e6ec4ff475a806998d66354d228f634e733a75e345bf78da32958 providers/common/include/prov/der_ml_dsa.h.in ce605f32413b09d33ce5795de9498a08183895c3347f33344f9ae5d31c29ccac providers/common/include/prov/der_rsa.h.in a36d6762f74d9ac4f437e634e60f2b4de1ff5416bb6dd5d2cffe2e4556556b1b providers/common/include/prov/der_slh_dsa.h.in 6c1fa3f229c6f049c3ac152c4c265f3eb056d94221b82df95a15400649690e93 providers/common/include/prov/der_wrap.h.in 76087f04f4de6414c240f88807659fb2a04af914108f0c5f2515a4cb5482f655 providers/common/include/prov/proverr.h 59786e2e358912d977ba792fb387d2df0156cac16267e399a1c93b3b0b65f725 providers/common/include/prov/provider_ctx.h c02d1fa866192dee1bf6d06338714efad5e7cae6ac0470ba20820599b4f811e8 providers/common/include/prov/provider_util.h f221ca9b117c9cccb776bb230f71b86553ce6c24196bea120124a4be7b8a712f providers/common/include/prov/providercommon.h 4a6e35be7600e78633324422f019443747a62777eba4987efc50f900c43fda25 providers/common/include/prov/securitycheck.h ba12773ee7d5afbd55e240798a0e36a2b0bdb4472f3aa3984bb8059f68cfba25 providers/common/provider_ctx.c 1f724e74106fa406999d706ec4b88c7185d2d1ceb7cc431a3340f778f533dbda providers/common/provider_err.c c4032b7cb033b588c6eb0585b8dfbed029d5b112a74ddd134dbcb1d78b0f9684 providers/common/provider_seeding.c 976aed982b0091a8f5320ee15e9b3d56c638c2a6b8481ddf9478d07927522f82 providers/common/provider_util.c bde6107744cf6840a4c350a48265ed000c49b0524fa60b0d68d6d7b33df5fce6 providers/common/securitycheck.c c0ba8608dd7719c9a8d9f8668ce60007eaadd6635162d4448815a7b76a9b2439 providers/common/securitycheck_fips.c abd5997bc33b681a4ab275978b92aebca0806a4a3f0c2f41dacf11b3b6f4e101 providers/fips/fips_entry.c d8cb05784ae8533a7d9569d4fbaaea4175b63a7c9f4fb0f254215224069dea6b providers/fips/fipsindicator.c 485441c31b5ff7916a12d0b8438d131a58cbc1ff6267cd266ae2dd6128c825cc providers/fips/fipsprov.c 6e024bbebae12014997c105df04c22bd07bbbc0a0b0a9ddd14fb798dbd3f0f26 providers/fips/include/fips/fipsindicator.h ef204adc49776214dbb299265bc4f2c40b48848cbea4c25b8029f2b46a5c9797 providers/fips/include/fips_indicator_params.inc f2581d7b4e105f2bb6d30908f3c2d9959313be08cec6dbeb49030c125a7676d3 providers/fips/include/fips_selftest_params.inc 669f76f742bcaaf28846b057bfab97da7c162d69da244de71b7c743bf16e430f providers/fips/include/fipscommon.h f111fd7e016af8cc6f96cd8059c28227b328dd466ed137ae0c0bc0c3c3eec3ba providers/fips/self_test.c 5c2c6c2f69e2eb01b88fa35630f27948e00dd2c2fd351735c74f34ccb2005cbe providers/fips/self_test.h -663441de9aba1d1b81ce02b3acded520b88cc460330d4d98adb7450d9664c474 providers/fips/self_test_data.inc -2e568e2b161131240e97bd77a730c2299f961c2f1409ea8466422fc07f9be23f providers/fips/self_test_kats.c +df83c901ad13675fbbb4708b6087feba6099870ad3dd0e8d09cfdb6798419770 providers/fips/self_test_data.inc +6779d5afb3f48d82868b247ffb0a6a572f6e3964738296ad47e7ccafdb263c88 providers/fips/self_test_kats.c dde79dfdedfe0e73006a0cf912fdde1ff109dfbc5ba6ecab319c938bc4275950 providers/implementations/asymciphers/rsa_enc.c c2f1b12c64fc369dfc3b9bc9e76a76de7280e6429adaee55d332eb1971ad1879 providers/implementations/ciphers/cipher_aes.c 6ba7d817081cf0d87ba7bfb38cd9d70e41505480bb8bc796ef896f68d4514ea6 providers/implementations/ciphers/cipher_aes.h c20072ecf42c87f9fad2ea241d358f57ed2a04cf0cc51bdb8cb5086172f6fc8a providers/implementations/ciphers/cipher_aes_cbc_hmac_sha.c 7668e5c1cac474ad7b0f28aa78ca885edf44815fe4a606a6cd328b3c02fac25a providers/implementations/ciphers/cipher_aes_cbc_hmac_sha.h 26e0f28523b416ba4067e471061f5a11fd76f5dc8bfe57ce37a137cf5667630b providers/implementations/ciphers/cipher_aes_cbc_hmac_sha1_hw.c 6d2ab2e059ef38fad342d4c65eebd533c08a2092bb174ff3566c6604e175c5a4 providers/implementations/ciphers/cipher_aes_cbc_hmac_sha256_hw.c 1b6d31811a6729f0c75c7c7ccfb7d3a75ab6001605b229593187918a592da789 providers/implementations/ciphers/cipher_aes_ccm.c 00f36bf48e522dbb5ec71df0ec13e387955fa3672e6ff90e8a412ae95c4a642f providers/implementations/ciphers/cipher_aes_ccm.h 4812d59ab6e1380f38e0c7cc0d7995eb6a2abf1438cedf233b939a17c4111482 providers/implementations/ciphers/cipher_aes_ccm_hw.c 302b3819ff9fdfed750185421616b248b0e1233d75b45a065490fe4762b42f55 providers/implementations/ciphers/cipher_aes_ccm_hw_aesni.inc a8eaca99a71521ff8ac4ffcf08315e59220f7e0b7f505ecddad04fadd021ec14 providers/implementations/ciphers/cipher_aes_cts.inc 14de031ae6a95653f7d819bfdb2abaf873f884b8313901bee4c2ec3ffc286712 providers/implementations/ciphers/cipher_aes_gcm.c 79f5a732820d2512a7f4fc2a99ece7e6e2523a51e62561eb67a4b70d5538b0c4 providers/implementations/ciphers/cipher_aes_gcm.h c6f091629dadb1b0b55e45636a28c31268fea4abfd3c068917c6c94b9aab704d providers/implementations/ciphers/cipher_aes_gcm_hw.c be18c20e0197f25fe7b9e0268657a2271a69d216b89cb100f082fa5fcaad1e07 providers/implementations/ciphers/cipher_aes_gcm_hw_aesni.inc 60c4f604cf9b5457be48f31cc24ca21729660381081b2dbf99f362a013a09684 providers/implementations/ciphers/cipher_aes_gcm_hw_vaes_avx512.inc d65415e14317e58673808b90a4dcd9aea47ae1ef2250edc1a8f1b872f0e9b1cf providers/implementations/ciphers/cipher_aes_hw.c 89de794c090192459d99d95bc4a422e7782e62192cd0fdb3bdef4128cfedee68 providers/implementations/ciphers/cipher_aes_hw_aesni.inc 087421bd0dde41d944dbae3ef9b262502d80425b9badb28aaa2a27c887259d98 providers/implementations/ciphers/cipher_aes_ocb.c 88138a1aff9705e608c0557653be92eb4de65b152555a2b79ec8b2a8fae73e8f providers/implementations/ciphers/cipher_aes_ocb.h 634cd29f13e5dd8ced3467504e8313b454a90371735ef42a5fe82c027b473064 providers/implementations/ciphers/cipher_aes_ocb_hw.c c7aac28a9dca1ad46e5bce4de93e07dffec1f89fab82394c3ff7cf1bda8b483f providers/implementations/ciphers/cipher_aes_wrp.c 8ee40234d051dfd9557439001d5d9f43d86623e23188a05ae00df99553cb4dca providers/implementations/ciphers/cipher_aes_xts.c ff870fcdc063e2e9f99693e4dad5f2128130591b05928bb5395f60ddcf81b1cf providers/implementations/ciphers/cipher_aes_xts.h 281157d1da4d7285d878978e6d42d0d33b3a6bc16e3bc5b6879e39093a7d70da providers/implementations/ciphers/cipher_aes_xts_fips.c 4f1f7258fe58651d9714ac7c3cfb30df2b49e7c14619c1acb8e5cf3d1fd5ad26 providers/implementations/ciphers/cipher_aes_xts_hw.c dc4626becaabc3990549483d9ef5f05c7dd9a9c2cf9be96ade3ba6a6e203f7f5 providers/implementations/ciphers/cipher_cts.c 57ee5e4d0af6d6006b04e60c5727b43a71ed37b67aa2410e03ec8932ad4a69e4 providers/implementations/ciphers/cipher_cts.h fcc3bb0637864252402aaa9d543209909df9a39611127f777b168bc888498dc0 providers/implementations/ciphers/cipher_tdes.c ccd6cc0ba06a8ecd8ce50019a6a62f8a185125d9ee045fd68a3c16e71c7a7794 providers/implementations/ciphers/cipher_tdes.h b59e3978b70cecdf8b0d867bd1b9202e19bef0b8e5bc243db42704a49dc5b22d providers/implementations/ciphers/cipher_tdes_common.c 50645122f08ef4891cd96cace833bd550be7f5278ab785515fd61fe8993c8c25 providers/implementations/ciphers/cipher_tdes_hw.c 765c90cabcbdc33097a7197af1a44152d57d38670adfeb295c1e392b13739337 providers/implementations/ciphers/ciphercommon.c ab9a2edb23aa61cf31da6addd8674a6028f93399eceeeee35a56ee770338fd6c providers/implementations/ciphers/ciphercommon_block.c 6b6090c233ddf29d819f2559361aeeae03505de7626a127628d5f0f6d3bce295 providers/implementations/ciphers/ciphercommon_ccm.c 8b6828f188c2590c7d9c6cac13fa0eb6d38a522b0f2859e7c8a766580fa9b66e providers/implementations/ciphers/ciphercommon_ccm_hw.c 00d480e133ffa2b63b1e704de9d321b4883118fecf126b2b7512f7b9f316e705 providers/implementations/ciphers/ciphercommon_gcm.c bb67eaa7a98494ca938726f9218213870fc97dd87b56bda950626cc794baf20b providers/implementations/ciphers/ciphercommon_gcm_hw.c 23fd89e3239e596c325a8c5d23eb1fe157a8d23aa4d90ed2c574bf06dfabd693 providers/implementations/ciphers/ciphercommon_hw.c c4b1cb143de15acc396ce2e03fdd165defd25ebc831de9cdfacf408ea883c666 providers/implementations/ciphers/ciphercommon_local.h 39b47b6ef9d71852964c26e07ef0e9b23f04c7493b1b16ba7c3dba7074b6b70d providers/implementations/digests/digestcommon.c 6b1b0223a8ed6cd9210bcef2e148266bd5131d0f5fc6cd459f4bc0db808c6008 providers/implementations/digests/sha2_prov.c efb4d6e3b1d870ba680c73beb509398e6cce633937c58e6cc5fbbfcf7888711f providers/implementations/digests/sha3_prov.c 9b37f34d48b3346c6ca3de430e190d7bfbd4e327d728870a64c7bd806ab700b6 providers/implementations/exchange/dh_exch.c ad943431c43913443461c709a179c577f7278aa061fab6e1ecbb4d0f211db63d providers/implementations/exchange/ecdh_exch.c d44c5a6d3156392757415f34afc1ab164fb0e9cd1e97977386d7cd13f3555df5 providers/implementations/exchange/ecx_exch.c b1115636f53bf70f417b183cafeb6d38e230d11d8de731e6896ba60cc850d931 providers/implementations/exchange/kdf_exch.c 0418ae17d54b602bfddefb96c7b4386aa97c43fdce1c8dcd12a7ce3bdecd0b58 providers/implementations/include/prov/ciphercommon.h a5ea831a23c0f52a37660437f6c61f129c3f8428daf6f8cd8dd458f358c56937 providers/implementations/include/prov/ciphercommon_aead.h a07b9c86346100feef15c9abb57e48a6099bc9fa782724a2283f17910ef192fb providers/implementations/include/prov/ciphercommon_ccm.h 0da2601354752c1d7085d1aee30ccc45a4066db9ec042fcd7a9da1644cac2330 providers/implementations/include/prov/ciphercommon_gcm.h b2f4aa477c3a2731dfbb5720ce87df653c55df24947c95d50a229be23e108661 providers/implementations/include/prov/digestcommon.h 1baf1c06b20a0eb8ec271452544922d67c1cc168dbe9853b259191de4bd99918 providers/implementations/include/prov/ecx.h 062b49fc5cfa405fbcb184b1b48c9141db22531493bf828ba8543d24b0b72692 providers/implementations/include/prov/hmac_drbg.h 20346aa1dc04854684fcc5ad53d7d436d63e32bbc66bb8cfd4d3cb2d2f2c8d60 providers/implementations/include/prov/implementations.h 05eedab6b16c80025f72281fa619d9480c437b800cb821b761fe4c05bc9d3af0 providers/implementations/include/prov/kdfexchange.h 4014246d44fa3f34aad5372c75d3f7eea528f1cf1798e30d5627e7620a356631 providers/implementations/include/prov/macsignature.h b41c9a4e90d951a2d0e796b1cbbdbe8cb6fc18306d9b70be7a489249c11c294a providers/implementations/include/prov/ml_dsa.h 511ad835639f071e99eaff6dcbf516999d108ea8b3f5f3f027e0982a916cf3c3 providers/implementations/include/prov/ml_kem.h 190f66af533067b80f18d7a12ba5440927e3e93b218f67473b4dea7dd9db88a6 providers/implementations/include/prov/mlx_kem.h af1adbeaa97de9b550f987e4badfa3809ba8c734bf7b90b830882cd95175d667 providers/implementations/include/prov/names.h b9f8781167f274ccd8b643b3bb6c4e1108fb27b2aae588518261af9415228dae providers/implementations/include/prov/seeding.h f63b54479dcc4923db9d0baa87b38a8da6f8186b8838a906e6b9ef52522bf489 providers/implementations/kdfs/hkdf.c 8a294c68ed3369ba4f3f7ee87b322702ddb59b63bf5ec2c72719ef121618c3ca providers/implementations/kdfs/kbkdf.c c0acc0869b8adbd399fbd024f7f7e664c462f4be51b72b41b7aebf1e3233a897 providers/implementations/kdfs/pbkdf2.c c0778565abff112c0c5257329a7750ec4605e62f26cc36851fa1fbee6e03c70c providers/implementations/kdfs/pbkdf2.h abe2b0f3711eaa34846e155cffc9242e4051c45de896f747afd5ac9d87f637dc providers/implementations/kdfs/pbkdf2_fips.c 08ccef4cc61dcd3bf4afcda8308a5e979bfa93d37f676841bed0cda7e7b1a9a9 providers/implementations/kdfs/sshkdf.c e18ef50cd62647a2cc784c45169d75054dccd58fc106bf623d921de995bb3c34 providers/implementations/kdfs/sskdf.c 6d9767a99a5b46d44ac9e0898ee18d219c04dfb34fda42e71d54adccbed7d57c providers/implementations/kdfs/tls1_prf.c 88d04ff4c93648a4fbfd9ce137cfc64f2c85e1850593c1ab35334b8b3de8ad99 providers/implementations/kdfs/x942kdf.c b04249bcc64d6f7ec16f494afef252356b2f56424a034ab53def90463de0cb6f providers/implementations/kem/ml_kem_kem.c a2e2b44064ef44b880b89ab6adc83686936acaa906313a37e5ec69d632912034 providers/implementations/kem/mlx_kem.c c764555b9dc9b273c280514a5d2d44156f82f3e99155a77c627f2c773209bcd7 providers/implementations/kem/rsa_kem.c 56e173f4ddb3e91314abd79b18de513c8cbc645669a287942fca4632c3851f6b providers/implementations/keymgmt/dh_kmgmt.c 24cc3cc8e8681c77b7f96c83293bd66045fd8ad69f756e673ca7f8ca9e82b0af providers/implementations/keymgmt/dsa_kmgmt.c 36a9c1c8658ce7918453827cb58ed52787e590e3f148c5510deeb2c16c25a29d providers/implementations/keymgmt/ec_kmgmt.c 258ae17bb2dd87ed1511a8eb3fe99eed9b77f5c2f757215ff6b3d0e8791fc251 providers/implementations/keymgmt/ec_kmgmt_imexport.inc -9728d696d249b2d224724c9872138a60e1998e5cfa5c49f3f48ad0666f7eed34 providers/implementations/keymgmt/ecx_kmgmt.c +11c27cc3c9f38885c484f25d11987e93f197aa90bef2fc1d6e8f508c2d014d4d providers/implementations/keymgmt/ecx_kmgmt.c daf35a7ab961ef70aefca981d80407935904c5da39dca6692432d6e6bc98759d providers/implementations/keymgmt/kdf_legacy_kmgmt.c d97d7c8d3410b3e560ef2becaea2a47948e22205be5162f964c5e51a7eef08cb providers/implementations/keymgmt/mac_legacy_kmgmt.c a428de71082fd01e5dcfa030a6fc34f6700b86d037b4e22f015c917862a158ce providers/implementations/keymgmt/ml_dsa_kmgmt.c ae129b80f400c2d520262a44842fb02898d6986dd1417ac468293dc104337120 providers/implementations/keymgmt/ml_kem_kmgmt.c e15b780a1489bbe4c7d40d6aaa3bccfbf973e3946578f460eeb8373c657eee91 providers/implementations/keymgmt/mlx_kmgmt.c d37e7a96253cf146e45c9adf9dbf83ab83fccbe41a5e5a6736f9085a60c38167 providers/implementations/keymgmt/rsa_kmgmt.c 6bb62b5417afb24a43b726148862770689f420a310722398f714f396ba07f205 providers/implementations/keymgmt/slh_dsa_kmgmt.c 9d02d481b9c7c0c9e0932267d1a3e1fef00830aaa03093f000b88aa042972b9f providers/implementations/macs/cmac_prov.c 3c558b57fff3588b6832475e0b1c5be590229ad50d95a6ebb089b62bf5fe382d providers/implementations/macs/gmac_prov.c b78305d36f248499a97800873a6bd215b2b7ae2e767c04b7ffcbad7add066040 providers/implementations/macs/hmac_prov.c 6f9100c9cdd39f94601d04a6564772686571711ff198cf8469e86444d1ba25f3 providers/implementations/macs/kmac_prov.c 4115f822e2477cd2c92a1c956cca1e4dbc5d86366e2a44a37526756153c0e432 providers/implementations/rands/drbg.c b7e24bb9265501e37253e801028f3fd0af5111a100c0b2005c53d43f02c03389 providers/implementations/rands/drbg_ctr.c 857043f63023b1b74936600aca189f39910d1b109720903cbe7f0d5752f381e9 providers/implementations/rands/drbg_hash.c 8bdd3fef08e6395de772b04648bf819268907bcf1f0f1b150880dc2056d9cb10 providers/implementations/rands/drbg_hmac.c 2c63defffcc681ada17a6cc3eb895634fd8bf86110796a6381cc3dedd26fd47d providers/implementations/rands/drbg_local.h ddae75f1e08416c92802faafba9d524e3bf58c13e9fcb51735733e161006f89e providers/implementations/rands/fips_crng_test.c 04e726d547a00d0254362b0ebd3ddf87f58a53b78d3a070a1620f5fa714330bb providers/implementations/rands/test_rng.c 732a4402f2621e2b676f0c0e885fb5ca8bc22d00842d47e7607a875fdff8a980 providers/implementations/signature/dsa_sig.c 72d09f89a9645d365fb357a512fb5687c04a924c34f1bbfc17e17c1ca169d7c6 providers/implementations/signature/ecdsa_sig.c bd48b0fe43f0d0d91eb34bdfd48fbcfd69bceabf0ddc678702fe9ef968064bb6 providers/implementations/signature/eddsa_sig.c e0e67e402ff19b0d2eb5228d7ebd70b9477c12595ac34d6f201373d7c8a516f4 providers/implementations/signature/mac_legacy_sig.c 51251a1ca4c0b6faea059de5d5268167fe47565163317177d09db39978134f78 providers/implementations/signature/ml_dsa_sig.c bab268ab5ad1d5e8dfdd8c01d25b216c657406ec2ff4e7ce190814ac7b92509f providers/implementations/signature/rsa_sig.c 14e7640b4db5e59e29b0266256d3d821adf871afa9703e18285f2fc957ac5971 providers/implementations/signature/slh_dsa_sig.c 21f537f9083f0341d9d1b0ace090a8d8f0b2b9e9cf76771c359b6ea00667a469 providers/implementations/skeymgmt/aes_skmgmt.c 2dbf9b8e738fad556c3248fb554ff4cc269ade3c86fa3d2786ba9b6d6016bf22 providers/implementations/skeymgmt/generic.c 414bbe942af0b94e90ee493612a3ce8ccbb9c6915b69464e4f71175921a0aeb8 providers/implementations/skeymgmt/skeymgmt_lcl.h 0b73a04f8a03106e2a0fea10978f9888158046c29c3993ca6557f5a6403d5580 ssl/record/methods/ssl3_cbc.c a8914c1661c53bcb0f435ec280c35c5a135e6c71296554c7322186847e194683 ssl/record/methods/tls_pad.c diff --git a/providers/fips.checksum b/providers/fips.checksum index 7fa4ea19bba3..5d1117361d27 100644 --- a/providers/fips.checksum +++ b/providers/fips.checksum @@ -1 +1 @@ -8d0c2c2b986f4c98f511c9aa020e98aa984dce5976d8e1966a7721f8b559cda8 providers/fips-sources.checksums +c342f9dc7075a6ecd0e4b3c9db06e180765278a7bbae233ec1a65095a0e524ec providers/fips-sources.checksums diff --git a/providers/fips/self_test_data.inc b/providers/fips/self_test_data.inc index b6aa433ca93c..6abab0a7a173 100644 --- a/providers/fips/self_test_data.inc +++ b/providers/fips/self_test_data.inc @@ -1,3499 +1,3541 @@ /* * Copyright 2019-2025 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 */ /* * This file contains self test data required by FIPS 140-3 IG * 10.3.A Cryptographic Algorithm Self test Requirements * * Note that in the 'General CAST requirements': Note33 Allows individual * self tests for low level algorithms (such as digests) to be omitted, if * they are tested as part of a higher level algorithm (such as HMAC). */ /* Macros to build Self test data */ #define ITM(x) ((void *)&x), sizeof(x) #define ITM_STR(x) ((void *)&x), (sizeof(x) - 1) #define ST_KAT_PARAM_END() { "", 0, NULL, 0 } #define ST_KAT_PARAM_BIGNUM(name, data) \ { name, OSSL_PARAM_UNSIGNED_INTEGER, ITM(data) } #define ST_KAT_PARAM_OCTET(name, data) \ { name, OSSL_PARAM_OCTET_STRING, ITM(data) } #define ST_KAT_PARAM_UTF8STRING(name, data) \ { name, OSSL_PARAM_UTF8_STRING, ITM_STR(data) } #define ST_KAT_PARAM_UTF8CHAR(name, data) \ { name, OSSL_PARAM_UTF8_STRING, ITM(data) } #define ST_KAT_PARAM_INT(name, i) \ { name, OSSL_PARAM_INTEGER, ITM(i) } /* used to store raw parameters for keys and algorithms */ typedef struct st_kat_param_st { const char *name; /* an OSSL_PARAM name */ size_t type; /* the type associated with the data */ const void *data; /* unsigned char [], or char [] depending on the type */ size_t data_len; /* the length of the data */ } ST_KAT_PARAM; typedef struct st_kat_st { const char *desc; const char *algorithm; const unsigned char *pt; size_t pt_len; const unsigned char *expected; size_t expected_len; } ST_KAT; #define CIPHER_MODE_ENCRYPT 1 #define CIPHER_MODE_DECRYPT 2 #define CIPHER_MODE_ALL (CIPHER_MODE_ENCRYPT | CIPHER_MODE_DECRYPT) /* FIPS 140-3 only allows DSA verification for legacy purposes */ #define SIGNATURE_MODE_VERIFY_ONLY 1 #define SIGNATURE_MODE_SIGN_ONLY 2 #define SIGNATURE_MODE_DIGESTED 4 #define SIGNATURE_MODE_SIG_DIGESTED 8 typedef ST_KAT ST_KAT_DIGEST; typedef struct st_kat_cipher_st { ST_KAT base; int mode; const unsigned char *key; size_t key_len; const unsigned char *iv; size_t iv_len; const unsigned char *aad; size_t aad_len; const unsigned char *tag; size_t tag_len; } ST_KAT_CIPHER; typedef struct st_kat_kdf_st { const char *desc; const char *algorithm; const ST_KAT_PARAM *params; const unsigned char *expected; size_t expected_len; } ST_KAT_KDF; typedef struct st_kat_drbg_st { const char *desc; const char *algorithm; const char *param_name; char *param_value; const unsigned char *entropyin; size_t entropyinlen; const unsigned char *nonce; size_t noncelen; const unsigned char *persstr; size_t persstrlen; const unsigned char *entropyinpr1; size_t entropyinpr1len; const unsigned char *entropyinpr2; size_t entropyinpr2len; const unsigned char *entropyaddin1; size_t entropyaddin1len; const unsigned char *entropyaddin2; size_t entropyaddin2len; const unsigned char *expected; size_t expectedlen; } ST_KAT_DRBG; typedef struct st_kat_kas_st { const char *desc; const char *algorithm; const ST_KAT_PARAM *key_group; const ST_KAT_PARAM *key_host_data; const ST_KAT_PARAM *key_peer_data; const unsigned char *expected; size_t expected_len; } ST_KAT_KAS; typedef struct st_kat_sign_st { const char *desc; const char *keytype; const char *sigalgorithm; int mode; const ST_KAT_PARAM *key; const unsigned char *msg; size_t msg_len; const unsigned char *entropy; size_t entropy_len; const unsigned char *nonce; size_t nonce_len; const unsigned char *persstr; size_t persstr_len; const unsigned char *sig_expected; /* Set to NULL if this value changes */ size_t sig_expected_len; const ST_KAT_PARAM *init; const ST_KAT_PARAM *verify; } ST_KAT_SIGN; typedef struct st_kat_asym_cipher_st { const char *desc; const char *algorithm; int encrypt; const ST_KAT_PARAM *key; const ST_KAT_PARAM *postinit; const unsigned char *in; size_t in_len; const unsigned char *expected; size_t expected_len; } ST_KAT_ASYM_CIPHER; typedef struct st_kat_keygen_st { const char *desc; const char *algorithm; const ST_KAT_PARAM *keygen_params; const ST_KAT_PARAM *expected_params; } ST_KAT_ASYM_KEYGEN; typedef struct st_kat_kem_st { const char *desc; const char *algorithm; const ST_KAT_PARAM *key; const unsigned char *cipher_text; size_t cipher_text_len; const unsigned char *entropy; size_t entropy_len; const unsigned char *secret; size_t secret_len; const unsigned char *reject_secret; } ST_KAT_KEM; /*- DIGEST SELF TEST DATA */ static const unsigned char sha1_pt[] = "abc"; static const unsigned char sha1_digest[] = { 0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A, 0xBA, 0x3E, 0x25, 0x71, 0x78, 0x50, 0xC2, 0x6C, 0x9C, 0xD0, 0xD8, 0x9D }; static const unsigned char sha512_pt[] = "abc"; static const unsigned char sha512_digest[] = { 0xDD, 0xAF, 0x35, 0xA1, 0x93, 0x61, 0x7A, 0xBA, 0xCC, 0x41, 0x73, 0x49, 0xAE, 0x20, 0x41, 0x31, 0x12, 0xE6, 0xFA, 0x4E, 0x89, 0xA9, 0x7E, 0xA2, 0x0A, 0x9E, 0xEE, 0xE6, 0x4B, 0x55, 0xD3, 0x9A, 0x21, 0x92, 0x99, 0x2A, 0x27, 0x4F, 0xC1, 0xA8, 0x36, 0xBA, 0x3C, 0x23, 0xA3, 0xFE, 0xEB, 0xBD, 0x45, 0x4D, 0x44, 0x23, 0x64, 0x3C, 0xE8, 0x0E, 0x2A, 0x9A, 0xC9, 0x4F, 0xA5, 0x4C, 0xA4, 0x9F }; static const unsigned char sha3_256_pt[] = { 0xe7, 0x37, 0x21, 0x05 }; static const unsigned char sha3_256_digest[] = { 0x3a, 0x42, 0xb6, 0x8a, 0xb0, 0x79, 0xf2, 0x8c, 0x4c, 0xa3, 0xc7, 0x52, 0x29, 0x6f, 0x27, 0x90, 0x06, 0xc4, 0xfe, 0x78, 0xb1, 0xeb, 0x79, 0xd9, 0x89, 0x77, 0x7f, 0x05, 0x1e, 0x40, 0x46, 0xae }; /* * Note: * SHA256 is tested by higher level algorithms so a * CAST is not needed. */ static const ST_KAT_DIGEST st_kat_digest_tests[] = { { OSSL_SELF_TEST_DESC_MD_SHA1, "SHA1", ITM_STR(sha1_pt), ITM(sha1_digest), }, { OSSL_SELF_TEST_DESC_MD_SHA2, "SHA512", ITM_STR(sha512_pt), ITM(sha512_digest), }, { OSSL_SELF_TEST_DESC_MD_SHA3, "SHA3-256", ITM(sha3_256_pt), ITM(sha3_256_digest), }, }; /*- CIPHER TEST DATA */ /* AES-256 GCM test data */ static const unsigned char aes_256_gcm_key[] = { 0x92, 0xe1, 0x1d, 0xcd, 0xaa, 0x86, 0x6f, 0x5c, 0xe7, 0x90, 0xfd, 0x24, 0x50, 0x1f, 0x92, 0x50, 0x9a, 0xac, 0xf4, 0xcb, 0x8b, 0x13, 0x39, 0xd5, 0x0c, 0x9c, 0x12, 0x40, 0x93, 0x5d, 0xd0, 0x8b }; static const unsigned char aes_256_gcm_iv[] = { 0xac, 0x93, 0xa1, 0xa6, 0x14, 0x52, 0x99, 0xbd, 0xe9, 0x02, 0xf2, 0x1a }; static const unsigned char aes_256_gcm_pt[] = { 0x2d, 0x71, 0xbc, 0xfa, 0x91, 0x4e, 0x4a, 0xc0, 0x45, 0xb2, 0xaa, 0x60, 0x95, 0x5f, 0xad, 0x24 }; static const unsigned char aes_256_gcm_aad[] = { 0x1e, 0x08, 0x89, 0x01, 0x6f, 0x67, 0x60, 0x1c, 0x8e, 0xbe, 0xa4, 0x94, 0x3b, 0xc2, 0x3a, 0xd6 }; static const unsigned char aes_256_gcm_ct[] = { 0x89, 0x95, 0xae, 0x2e, 0x6d, 0xf3, 0xdb, 0xf9, 0x6f, 0xac, 0x7b, 0x71, 0x37, 0xba, 0xe6, 0x7f }; static const unsigned char aes_256_gcm_tag[] = { 0xec, 0xa5, 0xaa, 0x77, 0xd5, 0x1d, 0x4a, 0x0a, 0x14, 0xd9, 0xc5, 0x1e, 0x1d, 0xa4, 0x74, 0xab }; /* AES-ECB test data */ static const unsigned char aes_128_ecb_key[] = { 0x10, 0xa5, 0x88, 0x69, 0xd7, 0x4b, 0xe5, 0xa3, 0x74, 0xcf, 0x86, 0x7c, 0xfb, 0x47, 0x38, 0x59 }; static const unsigned char aes_128_ecb_pt[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; static const unsigned char aes_128_ecb_ct[] = { 0x6d, 0x25, 0x1e, 0x69, 0x44, 0xb0, 0x51, 0xe0, 0x4e, 0xaa, 0x6f, 0xb4, 0xdb, 0xf7, 0x84, 0x65 }; #ifndef OPENSSL_NO_DES /* * TDES-ECB test data from * https://github.com/usnistgov/ACVP-Server/blob/master/gen-val/json-files/ACVP-TDES-ECB-1.0 * Decrypt */ static const unsigned char tdes_key[] = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE }; static const unsigned char tdes_ct[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }; static const unsigned char tdes_pt[] = { 0x4B, 0xAB, 0x3B, 0xE1, 0x50, 0x2E, 0x3B, 0x36 }; #endif static const ST_KAT_CIPHER st_kat_cipher_tests[] = { { { OSSL_SELF_TEST_DESC_CIPHER_AES_GCM, "AES-256-GCM", ITM(aes_256_gcm_pt), ITM(aes_256_gcm_ct) }, CIPHER_MODE_ENCRYPT | CIPHER_MODE_DECRYPT, ITM(aes_256_gcm_key), ITM(aes_256_gcm_iv), ITM(aes_256_gcm_aad), ITM(aes_256_gcm_tag) }, { { OSSL_SELF_TEST_DESC_CIPHER_AES_ECB, "AES-128-ECB", ITM(aes_128_ecb_pt), ITM(aes_128_ecb_ct) }, CIPHER_MODE_DECRYPT, ITM(aes_128_ecb_key) }, #ifndef OPENSSL_NO_DES { { OSSL_SELF_TEST_DESC_CIPHER_TDES, "DES-EDE3-ECB", ITM(tdes_pt), ITM(tdes_ct) }, CIPHER_MODE_DECRYPT, ITM(tdes_key) } #endif }; static const char hkdf_digest[] = "SHA256"; /* * Input parameters and expected result are from RFC 5869 test case 1, which is * with a key-derivation key >= 112 bits required by NIST SP 800-131Ar2 * section 8. */ static const unsigned char hkdf_secret[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b }; static const unsigned char hkdf_salt[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c }; static const unsigned char hkdf_info[] = { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9 }; static const unsigned char hkdf_expected[] = { 0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90, 0x43, 0x4f, 0x64, 0xd0, 0x36, 0x2f, 0x2a, 0x2d, 0x2d, 0x0a, 0x90, 0xcf, 0x1a, 0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56, 0xec, 0xc4, 0xc5, 0xbf, 0x34, 0x00, 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, 0x58, 0x65 }; static const ST_KAT_PARAM hkdf_params[] = { ST_KAT_PARAM_UTF8STRING(OSSL_KDF_PARAM_DIGEST, hkdf_digest), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_KEY, hkdf_secret), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_SALT, hkdf_salt), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_INFO, hkdf_info), ST_KAT_PARAM_END() }; static const char sskdf_digest[] = "SHA256"; static const unsigned char sskdf_secret[] = { 0x6d, 0xbd, 0xc2, 0x3f, 0x04, 0x54, 0x88, 0xe4, 0x06, 0x27, 0x57, 0xb0, 0x6b, 0x9e, 0xba, 0xe1, 0x83, 0xfc, 0x5a, 0x59, 0x46, 0xd8, 0x0d, 0xb9, 0x3f, 0xec, 0x6f, 0x62, 0xec, 0x07, 0xe3, 0x72, 0x7f, 0x01, 0x26, 0xae, 0xd1, 0x2c, 0xe4, 0xb2, 0x62, 0xf4, 0x7d, 0x48, 0xd5, 0x42, 0x87, 0xf8, 0x1d, 0x47, 0x4c, 0x7c, 0x3b, 0x18, 0x50, 0xe9 }; static const unsigned char sskdf_otherinfo[] = { 0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0x43, 0x41, 0x56, 0x53, 0x69, 0x64, 0x3c, 0x83, 0x2e, 0x98, 0x49, 0xdc, 0xdb, 0xa7, 0x1e, 0x9a, 0x31, 0x39, 0xe6, 0x06, 0xe0, 0x95, 0xde, 0x3c, 0x26, 0x4a, 0x66, 0xe9, 0x8a, 0x16, 0x58, 0x54, 0xcd, 0x07, 0x98, 0x9b, 0x1e, 0xe0, 0xec, 0x3f, 0x8d, 0xbe }; static const unsigned char sskdf_expected[] = { 0x27, 0xce, 0x57, 0xed, 0xb1, 0x7e, 0x1f, 0xf2, 0xe4, 0x79, 0x2e, 0x84, 0x8b, 0x04, 0xf1, 0xae }; static const ST_KAT_PARAM sskdf_params[] = { ST_KAT_PARAM_UTF8STRING(OSSL_KDF_PARAM_DIGEST, sskdf_digest), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_KEY, sskdf_secret), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_INFO, sskdf_otherinfo), ST_KAT_PARAM_END() }; static const char x942kdf_digest[] = "SHA256"; static const char x942kdf_cekalg[] = "AES-128-WRAP"; static const unsigned char x942kdf_secret[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13 }; static const unsigned char x942kdf_expected[] = { 0x79, 0x66, 0xa0, 0x38, 0x22, 0x28, 0x1e, 0xa3, 0xeb, 0x08, 0xd9, 0xbc, 0x69, 0x5b, 0xd8, 0xff }; static const ST_KAT_PARAM x942kdf_params[] = { ST_KAT_PARAM_UTF8STRING(OSSL_KDF_PARAM_DIGEST, x942kdf_digest), ST_KAT_PARAM_UTF8STRING(OSSL_KDF_PARAM_CEK_ALG, x942kdf_cekalg), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_KEY, x942kdf_secret), ST_KAT_PARAM_END() }; static const char x963kdf_digest[] = "SHA256"; static const unsigned char x963kdf_otherinfo[] = { 0x75, 0xee, 0xf8, 0x1a, 0xa3, 0x04, 0x1e, 0x33, 0xb8, 0x09, 0x71, 0x20, 0x3d, 0x2c, 0x0c, 0x52 }; static const unsigned char x963kdf_secret[] = { 0x22, 0x51, 0x8b, 0x10, 0xe7, 0x0f, 0x2a, 0x3f, 0x24, 0x38, 0x10, 0xae, 0x32, 0x54, 0x13, 0x9e, 0xfb, 0xee, 0x04, 0xaa, 0x57, 0xc7, 0xaf, 0x7d }; static const unsigned char x963kdf_expected[] = { 0xc4, 0x98, 0xaf, 0x77, 0x16, 0x1c, 0xc5, 0x9f, 0x29, 0x62, 0xb9, 0xa7, 0x13, 0xe2, 0xb2, 0x15, 0x15, 0x2d, 0x13, 0x97, 0x66, 0xce, 0x34, 0xa7, 0x76, 0xdf, 0x11, 0x86, 0x6a, 0x69, 0xbf, 0x2e }; static const ST_KAT_PARAM x963kdf_params[] = { ST_KAT_PARAM_UTF8STRING(OSSL_KDF_PARAM_DIGEST, x963kdf_digest), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_KEY, x963kdf_secret), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_INFO, x963kdf_otherinfo), ST_KAT_PARAM_END() }; static const char pbkdf2_digest[] = "SHA256"; /* * Input parameters from RFC 6070, vector 5 (because it is the only one with * a salt >= 16 bytes, which NIST SP 800-132 section 5.1 requires). The * expected output is taken from * https://github.com/brycx/Test-Vector-Generation/blob/master/PBKDF2/pbkdf2-hmac-sha2-test-vectors.md, * which ran these test vectors with SHA-256. * Note that the output only uses 2 iterations. */ static const unsigned char pbkdf2_password[] = { 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x50, 0x41, 0x53, 0x53, 0x57, 0x4f, 0x52, 0x44, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64 }; static const unsigned char pbkdf2_salt[] = { 0x73, 0x61, 0x6c, 0x74, 0x53, 0x41, 0x4c, 0x54, 0x73, 0x61, 0x6c, 0x74, 0x53, 0x41, 0x4c, 0x54, 0x73, 0x61, 0x6c, 0x74, 0x53, 0x41, 0x4c, 0x54, 0x73, 0x61, 0x6c, 0x74, 0x53, 0x41, 0x4c, 0x54, 0x73, 0x61, 0x6c, 0x74 }; static const unsigned char pbkdf2_expected[] = { 0x13, 0xdc, 0x8a, 0x7c, 0x13, 0xd3, 0x72, 0xc9, 0x03, 0x82, 0x82, 0x2d, 0x2d, 0xc4, 0x92, 0xf2, 0xed, 0x52, 0x46, 0x7f, 0xb7, 0x82, 0x8e, 0xa8, 0x64 }; /* * FIPS 140-3 IG 10.3.A.8 allows the iteration count to be smaller * so we use the minimum of 2 here. */ static int pbkdf2_iterations = 2; static int pbkdf2_pkcs5 = 1; /* Disable compliance checks so a smaller iteration count can be used */ static const ST_KAT_PARAM pbkdf2_params[] = { ST_KAT_PARAM_UTF8STRING(OSSL_KDF_PARAM_DIGEST, pbkdf2_digest), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_PASSWORD, pbkdf2_password), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_SALT, pbkdf2_salt), ST_KAT_PARAM_INT(OSSL_KDF_PARAM_ITER, pbkdf2_iterations), ST_KAT_PARAM_INT(OSSL_KDF_PARAM_PKCS5, pbkdf2_pkcs5), ST_KAT_PARAM_END() }; static const char tls12prf_digest[] = "SHA256"; static const unsigned char tls12prf_secret[] = { 0x20, 0x2c, 0x88, 0xc0, 0x0f, 0x84, 0xa1, 0x7a, 0x20, 0x02, 0x70, 0x79, 0x60, 0x47, 0x87, 0x46, 0x11, 0x76, 0x45, 0x55, 0x39, 0xe7, 0x05, 0xbe, 0x73, 0x08, 0x90, 0x60, 0x2c, 0x28, 0x9a, 0x50, 0x01, 0xe3, 0x4e, 0xeb, 0x3a, 0x04, 0x3e, 0x5d, 0x52, 0xa6, 0x5e, 0x66, 0x12, 0x51, 0x88, 0xbf, }; static const unsigned char tls12prf_seed[] = { 'k', 'e', 'y', ' ', 'e', 'x', 'p', 'a', 'n', 's', 'i', 'o', 'n', 0xae, 0x6c, 0x80, 0x6f, 0x8a, 0xd4, 0xd8, 0x07, 0x84, 0x54, 0x9d, 0xff, 0x28, 0xa4, 0xb5, 0x8f, 0xd8, 0x37, 0x68, 0x1a, 0x51, 0xd9, 0x28, 0xc3, 0xe3, 0x0e, 0xe5, 0xff, 0x14, 0xf3, 0x98, 0x68, 0x62, 0xe1, 0xfd, 0x91, 0xf2, 0x3f, 0x55, 0x8a, 0x60, 0x5f, 0x28, 0x47, 0x8c, 0x58, 0xcf, 0x72, 0x63, 0x7b, 0x89, 0x78, 0x4d, 0x95, 0x9d, 0xf7, 0xe9, 0x46, 0xd3, 0xf0, 0x7b, 0xd1, 0xb6, 0x16, }; static const unsigned char tls12prf_expected[] = { 0xd0, 0x61, 0x39, 0x88, 0x9f, 0xff, 0xac, 0x1e, 0x3a, 0x71, 0x86, 0x5f, 0x50, 0x4a, 0xa5, 0xd0, 0xd2, 0xa2, 0xe8, 0x95, 0x06, 0xc6, 0xf2, 0x27, 0x9b, 0x67, 0x0c, 0x3e, 0x1b, 0x74, 0xf5, 0x31, 0x01, 0x6a, 0x25, 0x30, 0xc5, 0x1a, 0x3a, 0x0f, 0x7e, 0x1d, 0x65, 0x90, 0xd0, 0xf0, 0x56, 0x6b, 0x2f, 0x38, 0x7f, 0x8d, 0x11, 0xfd, 0x4f, 0x73, 0x1c, 0xdd, 0x57, 0x2d, 0x2e, 0xae, 0x92, 0x7f, 0x6f, 0x2f, 0x81, 0x41, 0x0b, 0x25, 0xe6, 0x96, 0x0b, 0xe6, 0x89, 0x85, 0xad, 0xd6, 0xc3, 0x84, 0x45, 0xad, 0x9f, 0x8c, 0x64, 0xbf, 0x80, 0x68, 0xbf, 0x9a, 0x66, 0x79, 0x48, 0x5d, 0x96, 0x6f, 0x1a, 0xd6, 0xf6, 0x8b, 0x43, 0x49, 0x5b, 0x10, 0xa6, 0x83, 0x75, 0x5e, 0xa2, 0xb8, 0x58, 0xd7, 0x0c, 0xca, 0xc7, 0xec, 0x8b, 0x05, 0x3c, 0x6b, 0xd4, 0x1c, 0xa2, 0x99, 0xd4, 0xe5, 0x19, 0x28, }; static const ST_KAT_PARAM tls12prf_params[] = { ST_KAT_PARAM_UTF8STRING(OSSL_KDF_PARAM_DIGEST, tls12prf_digest), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_SECRET, tls12prf_secret), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_SEED, tls12prf_seed), ST_KAT_PARAM_END() }; static const char kbkdf_digest[] = "SHA256"; static const char kbkdf_mac[] = "HMAC"; static const unsigned char kbkdf_salt[] = { 'p', 'r', 'f' }; static const unsigned char kbkdf_prfinput[] = { 't', 'e', 's', 't' }; static unsigned char kbkdf_key[] = { 0x37, 0x05, 0xD9, 0x60, 0x80, 0xC1, 0x77, 0x28, 0xA0, 0xE8, 0x00, 0xEA, 0xB6, 0xE0, 0xD2, 0x3C, }; static unsigned char kbkdf_expected[] = { 0x9D, 0x18, 0x86, 0x16, 0xF6, 0x38, 0x52, 0xFE, 0x86, 0x91, 0x5B, 0xB8, 0x40, 0xB4, 0xA8, 0x86, 0xFF, 0x3E, 0x6B, 0xB0, 0xF8, 0x19, 0xB4, 0x9B, 0x89, 0x33, 0x93, 0xD3, 0x93, 0x85, 0x42, 0x95, }; static const ST_KAT_PARAM kbkdf_params[] = { ST_KAT_PARAM_UTF8STRING(OSSL_KDF_PARAM_DIGEST, kbkdf_digest), ST_KAT_PARAM_UTF8STRING(OSSL_KDF_PARAM_MAC, kbkdf_mac), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_KEY, kbkdf_key), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_SALT, kbkdf_salt), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_INFO, kbkdf_prfinput), ST_KAT_PARAM_END() }; static const char kbkdf_kmac_mac[] = "KMAC128"; static unsigned char kbkdf_kmac_label[] = { 0xB5, 0xB5, 0xF3, 0x71, 0x9F, 0xBE, 0x5B, 0x3D, 0x7B, 0x8D, 0x05, 0xA1, 0xD3, 0x25, 0x19, 0x50, }; static unsigned char kbkdf_kmac_context[] = { 0x36, 0x60, 0x0E, 0xF3, 0xC3, 0x70, 0xB5, 0xEF, 0x58, 0xBE, 0xF1, 0xBA, 0x1C, 0xF2, 0x74, 0xCB, }; static unsigned char kbkdf_kmac_key[] = { 0xB2, 0x51, 0x4C, 0xC1, 0xD5, 0xCD, 0x7B, 0x6B, 0xA3, 0x3C, 0x90, 0x05, 0xBD, 0xAC, 0x32, 0x2A, }; static unsigned char kbkdf_kmac_expected[] = { 0xB1, 0x58, 0xEE, 0xB1, 0x34, 0xA4, 0xDD, 0x9D, 0xAC, 0x52, 0xBD, 0x9E, 0x30, 0xE8, 0x0D, 0x76, 0x42, 0x57, 0x01, 0x89, 0x5F, 0x82, 0x74, 0xB9, 0xEB, 0x3E, 0x84, 0xD8, 0xA5, 0xDE, 0x6E, 0x54, }; static const ST_KAT_PARAM kbkdf_kmac_params[] = { ST_KAT_PARAM_UTF8STRING(OSSL_KDF_PARAM_MAC, kbkdf_kmac_mac), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_KEY, kbkdf_kmac_key), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_SALT, kbkdf_kmac_label), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_INFO, kbkdf_kmac_context), ST_KAT_PARAM_END() }; static const char tls13_kdf_digest[] = "SHA256"; static int tls13_kdf_extract_mode = EVP_KDF_HKDF_MODE_EXTRACT_ONLY; static int tls13_kdf_expand_mode = EVP_KDF_HKDF_MODE_EXPAND_ONLY; static const unsigned char tls13_kdf_prefix[] = { 0x74, 0x6C, 0x73, 0x31, 0x33, 0x20 /* "tls13 " */ }; static const unsigned char tls13_kdf_client_early_secret_label[] = { 0x63, 0x20, 0x65, 0x20, 0x74, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63 /* "c e traffic"*/ }; static const unsigned char tls13_kdf_psk[] = { 0xF8, 0xAF, 0x6A, 0xEA, 0x2D, 0x39, 0x7B, 0xAF, 0x29, 0x48, 0xA2, 0x5B, 0x28, 0x34, 0x20, 0x06, 0x92, 0xCF, 0xF1, 0x7E, 0xEE, 0x91, 0x65, 0xE4, 0xE2, 0x7B, 0xAB, 0xEE, 0x9E, 0xDE, 0xFD, 0x05 }; static const unsigned char tls13_kdf_client_hello_hash[] = { 0x7c, 0x92, 0xf6, 0x8b, 0xd5, 0xbf, 0x36, 0x38, 0xea, 0x33, 0x8a, 0x64, 0x94, 0x72, 0x2e, 0x1b, 0x44, 0x12, 0x7e, 0x1b, 0x7e, 0x8a, 0xad, 0x53, 0x5f, 0x23, 0x22, 0xa6, 0x44, 0xff, 0x22, 0xb3 }; static const unsigned char tls13_kdf_early_secret[] = { 0x15, 0x3B, 0x63, 0x94, 0xA9, 0xC0, 0x3C, 0xF3, 0xF5, 0xAC, 0xCC, 0x6E, 0x45, 0x5A, 0x76, 0x93, 0x28, 0x11, 0x38, 0xA1, 0xBC, 0xFA, 0x38, 0x03, 0xC2, 0x67, 0x35, 0xDD, 0x11, 0x94, 0xD2, 0x16 }; static const unsigned char tls13_kdf_client_early_traffic_secret[] = { 0xC8, 0x05, 0x83, 0xA9, 0x0E, 0x99, 0x5C, 0x48, 0x96, 0x00, 0x49, 0x2A, 0x5D, 0xA6, 0x42, 0xE6, 0xB1, 0xF6, 0x79, 0xBA, 0x67, 0x48, 0x28, 0x79, 0x2D, 0xF0, 0x87, 0xB9, 0x39, 0x63, 0x61, 0x71 }; static const ST_KAT_PARAM tls13_kdf_early_secret_params[] = { ST_KAT_PARAM_INT(OSSL_KDF_PARAM_MODE, tls13_kdf_extract_mode), ST_KAT_PARAM_UTF8STRING(OSSL_KDF_PARAM_DIGEST, tls13_kdf_digest), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_KEY, tls13_kdf_psk), ST_KAT_PARAM_END() }; static const ST_KAT_PARAM tls13_kdf_client_early_secret_params[] = { ST_KAT_PARAM_INT(OSSL_KDF_PARAM_MODE, tls13_kdf_expand_mode), ST_KAT_PARAM_UTF8STRING(OSSL_KDF_PARAM_DIGEST, tls13_kdf_digest), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_KEY, tls13_kdf_early_secret), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_DATA, tls13_kdf_client_hello_hash), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_PREFIX, tls13_kdf_prefix), ST_KAT_PARAM_OCTET(OSSL_KDF_PARAM_LABEL, tls13_kdf_client_early_secret_label), ST_KAT_PARAM_END() }; /* * NOTES: * According to FIPS 140-3 10.3.A Note18: SSH KDF is not required, since it is * sufficient to self-test the underlying SHA hash functions. */ static const ST_KAT_KDF st_kat_kdf_tests[] = { { OSSL_SELF_TEST_DESC_KDF_TLS13_EXTRACT, OSSL_KDF_NAME_TLS1_3_KDF, tls13_kdf_early_secret_params, ITM(tls13_kdf_early_secret) }, { OSSL_SELF_TEST_DESC_KDF_TLS13_EXPAND, OSSL_KDF_NAME_TLS1_3_KDF, tls13_kdf_client_early_secret_params, ITM(tls13_kdf_client_early_traffic_secret) }, { OSSL_SELF_TEST_DESC_KDF_TLS12_PRF, OSSL_KDF_NAME_TLS1_PRF, tls12prf_params, ITM(tls12prf_expected) }, { OSSL_SELF_TEST_DESC_KDF_PBKDF2, OSSL_KDF_NAME_PBKDF2, pbkdf2_params, ITM(pbkdf2_expected) }, { OSSL_SELF_TEST_DESC_KDF_KBKDF, OSSL_KDF_NAME_KBKDF, kbkdf_params, ITM(kbkdf_expected) }, { OSSL_SELF_TEST_DESC_KDF_KBKDF_KMAC, OSSL_KDF_NAME_KBKDF, kbkdf_kmac_params, ITM(kbkdf_kmac_expected) }, { OSSL_SELF_TEST_DESC_KDF_HKDF, OSSL_KDF_NAME_HKDF, hkdf_params, ITM(hkdf_expected) }, { OSSL_SELF_TEST_DESC_KDF_SSKDF, OSSL_KDF_NAME_SSKDF, sskdf_params, ITM(sskdf_expected) }, { OSSL_SELF_TEST_DESC_KDF_X963KDF, OSSL_KDF_NAME_X963KDF, x963kdf_params, ITM(x963kdf_expected) }, { OSSL_SELF_TEST_DESC_KDF_X942KDF, OSSL_KDF_NAME_X942KDF_ASN1, x942kdf_params, ITM(x942kdf_expected) }, }; /*- * DRBG test vectors are a small subset of * https://csrc.nist.rip/groups/STM/cavp/documents/drbg/drbgtestvectors.zip * Using the folder drbgvectors_pr_true * Generated for CAVS 14.3. */ /* * Hash_DRBG.rsp * * [SHA-256] * [PredictionResistance = True] * [EntropyInputLen = 256] * [NonceLen = 128] * [PersonalizationStringLen = 256] * [AdditionalInputLen = 256] * [ReturnedBitsLen = 1024] * * COUNT = 14 */ static const unsigned char drbg_hash_sha256_pr_entropyin[] = { 0x06, 0x6d, 0xc8, 0xce, 0x75, 0xb2, 0x89, 0x66, 0xa6, 0x85, 0x16, 0x3f, 0xe2, 0xa4, 0xd4, 0x27, 0xfb, 0xdb, 0x61, 0x66, 0x50, 0x61, 0x6b, 0xa2, 0x82, 0xfc, 0x33, 0x2b, 0x4e, 0x6f, 0x12, 0x20 }; static const unsigned char drbg_hash_sha256_pr_nonce[] = { 0x55, 0x9f, 0x7c, 0x64, 0x89, 0x70, 0x83, 0xec, 0x2d, 0x73, 0x70, 0xd9, 0xf0, 0xe5, 0x07, 0x1f }; static const unsigned char drbg_hash_sha256_pr_persstr[] = { 0x88, 0x6f, 0x54, 0x9a, 0xad, 0x1a, 0xc6, 0x3d, 0x18, 0xcb, 0xcc, 0x66, 0x85, 0xda, 0xa2, 0xc2, 0xf7, 0x9e, 0xb0, 0x89, 0x4c, 0xb4, 0xae, 0xf1, 0xac, 0x54, 0x4f, 0xce, 0x57, 0xf1, 0x5e, 0x11 }; static const unsigned char drbg_hash_sha256_pr_entropyinpr0[] = { 0xff, 0x80, 0xb7, 0xd2, 0x6a, 0x05, 0xbc, 0x8a, 0x7a, 0xbe, 0x53, 0x28, 0x6b, 0x0e, 0xeb, 0x73, 0x3b, 0x71, 0x5a, 0x20, 0x5b, 0xfa, 0x4f, 0xf6, 0x37, 0x03, 0xde, 0xad, 0xb6, 0xea, 0x0e, 0xf4 }; static const unsigned char drbg_hash_sha256_pr_entropyinpr1[] = { 0xc7, 0x38, 0x32, 0x53, 0x46, 0x81, 0xed, 0xe3, 0x7e, 0x03, 0x84, 0x6d, 0x3c, 0x84, 0x17, 0x67, 0x29, 0x7d, 0x24, 0x6c, 0x68, 0x92, 0x41, 0xd2, 0xe7, 0x75, 0xbe, 0x7e, 0xc9, 0x96, 0x29, 0x3d }; static const unsigned char drbg_hash_sha256_pr_addin0[] = { 0xb7, 0x21, 0x5f, 0x14, 0xac, 0x7b, 0xaf, 0xd0, 0xa9, 0x17, 0x72, 0xba, 0x22, 0xf7, 0x19, 0xaf, 0xbd, 0x20, 0xb3, 0x11, 0x63, 0x6c, 0x2b, 0x1e, 0x83, 0xe4, 0xa8, 0x23, 0x35, 0x3f, 0xc6, 0xea }; static const unsigned char drbg_hash_sha256_pr_addin1[] = { 0xce, 0xd3, 0x1f, 0x7e, 0x0d, 0xae, 0x5b, 0xb5, 0xc0, 0x43, 0xe2, 0x46, 0xb2, 0x94, 0x73, 0xe2, 0xfd, 0x39, 0x51, 0x2e, 0xad, 0x45, 0x69, 0xee, 0xe3, 0xe3, 0x80, 0x33, 0x14, 0xab, 0xa7, 0xa3 }; static const unsigned char drbg_hash_sha256_pr_expected[] = { 0x60, 0xc2, 0x34, 0xcf, 0xaf, 0xb4, 0x68, 0x03, 0x3b, 0xf1, 0x95, 0xe5, 0x78, 0xce, 0x26, 0x6e, 0x14, 0x65, 0x32, 0x6a, 0x96, 0xa9, 0xe0, 0x3f, 0x8b, 0x89, 0x36, 0x70, 0xef, 0x62, 0x75, 0x4d, 0x5e, 0x80, 0xd5, 0x53, 0xa1, 0xf8, 0x49, 0x50, 0x20, 0x8b, 0x93, 0x43, 0x07, 0x9f, 0x2e, 0xf8, 0x56, 0xe9, 0xc5, 0x70, 0x61, 0x85, 0x97, 0xb5, 0xdc, 0x82, 0xa2, 0xda, 0xea, 0xa3, 0xfd, 0x9b, 0x2f, 0xd2, 0xa0, 0xd7, 0x1b, 0xc6, 0x29, 0x35, 0xcc, 0xb8, 0x3d, 0xa0, 0x67, 0x98, 0x05, 0xa0, 0xe3, 0x1e, 0xfe, 0xe4, 0xf0, 0xe5, 0x13, 0xb0, 0x83, 0x17, 0xfa, 0xca, 0x93, 0x5e, 0x38, 0x29, 0x48, 0xd2, 0x72, 0xdb, 0x76, 0x3e, 0x6d, 0xf3, 0x25, 0x10, 0xff, 0x1b, 0x99, 0xff, 0xf8, 0xc6, 0x0e, 0xb0, 0xdd, 0x29, 0x2e, 0xbc, 0xbb, 0xc8, 0x0a, 0x01, 0x6e, 0xd3, 0xb0, 0x0e, 0x4e, 0xab }; /* * CTR_DRBG.rsp * * [AES-128 use df] * [PredictionResistance = True] * [EntropyInputLen = 128] * [NonceLen = 64] * [PersonalizationStringLen = 128] * [AdditionalInputLen = 128] * [ReturnedBitsLen = 512] * * COUNT = 0 */ static const unsigned char drbg_ctr_aes128_pr_df_entropyin[] = { 0x92, 0x89, 0x8f, 0x31, 0xfa, 0x1c, 0xff, 0x6d, 0x18, 0x2f, 0x26, 0x06, 0x43, 0xdf, 0xf8, 0x18 }; static const unsigned char drbg_ctr_aes128_pr_df_nonce[] = { 0xc2, 0xa4, 0xd9, 0x72, 0xc3, 0xb9, 0xb6, 0x97 }; static const unsigned char drbg_ctr_aes128_pr_df_persstr[] = { 0xea, 0x65, 0xee, 0x60, 0x26, 0x4e, 0x7e, 0xb6, 0x0e, 0x82, 0x68, 0xc4, 0x37, 0x3c, 0x5c, 0x0b }; static const unsigned char drbg_ctr_aes128_pr_df_entropyinpr0[] = { 0x20, 0x72, 0x8a, 0x06, 0xf8, 0x6f, 0x8d, 0xd4, 0x41, 0xe2, 0x72, 0xb7, 0xc4, 0x2c, 0xe8, 0x10 }; static const unsigned char drbg_ctr_aes128_pr_df_entropyinpr1[] = { 0x3d, 0xb0, 0xf0, 0x94, 0xf3, 0x05, 0x50, 0x33, 0x17, 0x86, 0x3e, 0x22, 0x08, 0xf7, 0xa5, 0x01 }; static const unsigned char drbg_ctr_aes128_pr_df_addin0[] = { 0x1a, 0x40, 0xfa, 0xe3, 0xcc, 0x6c, 0x7c, 0xa0, 0xf8, 0xda, 0xba, 0x59, 0x23, 0x6d, 0xad, 0x1d }; static const unsigned char drbg_ctr_aes128_pr_df_addin1[] = { 0x9f, 0x72, 0x76, 0x6c, 0xc7, 0x46, 0xe5, 0xed, 0x2e, 0x53, 0x20, 0x12, 0xbc, 0x59, 0x31, 0x8c }; static const unsigned char drbg_ctr_aes128_pr_df_expected[] = { 0x5a, 0x35, 0x39, 0x87, 0x0f, 0x4d, 0x22, 0xa4, 0x09, 0x24, 0xee, 0x71, 0xc9, 0x6f, 0xac, 0x72, 0x0a, 0xd6, 0xf0, 0x88, 0x82, 0xd0, 0x83, 0x28, 0x73, 0xec, 0x3f, 0x93, 0xd8, 0xab, 0x45, 0x23, 0xf0, 0x7e, 0xac, 0x45, 0x14, 0x5e, 0x93, 0x9f, 0xb1, 0xd6, 0x76, 0x43, 0x3d, 0xb6, 0xe8, 0x08, 0x88, 0xf6, 0xda, 0x89, 0x08, 0x77, 0x42, 0xfe, 0x1a, 0xf4, 0x3f, 0xc4, 0x23, 0xc5, 0x1f, 0x68 }; /* * HMAC_DRBG.rsp * * [SHA-256] * [PredictionResistance = True] * [EntropyInputLen = 256] * [NonceLen = 128] * [PersonalizationStringLen = 256] * [AdditionalInputLen = 256] * [ReturnedBitsLen = 1024] * * COUNT = 0 */ static const unsigned char drbg_hmac_sha2_pr_entropyin[] = { 0xca, 0x85, 0x19, 0x11, 0x34, 0x93, 0x84, 0xbf, 0xfe, 0x89, 0xde, 0x1c, 0xbd, 0xc4, 0x6e, 0x68, 0x31, 0xe4, 0x4d, 0x34, 0xa4, 0xfb, 0x93, 0x5e, 0xe2, 0x85, 0xdd, 0x14, 0xb7, 0x1a, 0x74, 0x88 }; static const unsigned char drbg_hmac_sha2_pr_nonce[] = { 0x65, 0x9b, 0xa9, 0x6c, 0x60, 0x1d, 0xc6, 0x9f, 0xc9, 0x02, 0x94, 0x08, 0x05, 0xec, 0x0c, 0xa8 }; static const unsigned char drbg_hmac_sha2_pr_persstr[] = { 0xe7, 0x2d, 0xd8, 0x59, 0x0d, 0x4e, 0xd5, 0x29, 0x55, 0x15, 0xc3, 0x5e, 0xd6, 0x19, 0x9e, 0x9d, 0x21, 0x1b, 0x8f, 0x06, 0x9b, 0x30, 0x58, 0xca, 0xa6, 0x67, 0x0b, 0x96, 0xef, 0x12, 0x08, 0xd0 }; static const unsigned char drbg_hmac_sha2_pr_entropyinpr0[] = { 0x5c, 0xac, 0xc6, 0x81, 0x65, 0xa2, 0xe2, 0xee, 0x20, 0x81, 0x2f, 0x35, 0xec, 0x73, 0xa7, 0x9d, 0xbf, 0x30, 0xfd, 0x47, 0x54, 0x76, 0xac, 0x0c, 0x44, 0xfc, 0x61, 0x74, 0xcd, 0xac, 0x2b, 0x55 }; static const unsigned char drbg_hmac_sha2_pr_entropyinpr1[] = { 0x8d, 0xf0, 0x13, 0xb4, 0xd1, 0x03, 0x52, 0x30, 0x73, 0x91, 0x7d, 0xdf, 0x6a, 0x86, 0x97, 0x93, 0x05, 0x9e, 0x99, 0x43, 0xfc, 0x86, 0x54, 0x54, 0x9e, 0x7a, 0xb2, 0x2f, 0x7c, 0x29, 0xf1, 0x22 }; static const unsigned char drbg_hmac_sha2_pr_addin0[] = { 0x79, 0x3a, 0x7e, 0xf8, 0xf6, 0xf0, 0x48, 0x2b, 0xea, 0xc5, 0x42, 0xbb, 0x78, 0x5c, 0x10, 0xf8, 0xb7, 0xb4, 0x06, 0xa4, 0xde, 0x92, 0x66, 0x7a, 0xb1, 0x68, 0xec, 0xc2, 0xcf, 0x75, 0x73, 0xc6 }; static const unsigned char drbg_hmac_sha2_pr_addin1[] = { 0x22, 0x38, 0xcd, 0xb4, 0xe2, 0x3d, 0x62, 0x9f, 0xe0, 0xc2, 0xa8, 0x3d, 0xd8, 0xd5, 0x14, 0x4c, 0xe1, 0xa6, 0x22, 0x9e, 0xf4, 0x1d, 0xab, 0xe2, 0xa9, 0x9f, 0xf7, 0x22, 0xe5, 0x10, 0xb5, 0x30 }; static const unsigned char drbg_hmac_sha2_pr_expected[] = { 0xb1, 0xd1, 0x7c, 0x00, 0x2a, 0x7f, 0xeb, 0xd2, 0x84, 0x12, 0xd8, 0xe5, 0x8a, 0x7f, 0x32, 0x31, 0x8e, 0x4e, 0xe3, 0x60, 0x5a, 0x99, 0xb0, 0x5b, 0x05, 0xd5, 0x93, 0x56, 0xd5, 0xf0, 0xc6, 0xb4, 0x96, 0x0a, 0x4b, 0x8f, 0x96, 0x3b, 0x7e, 0xfa, 0x55, 0xbb, 0x68, 0x72, 0xfb, 0xea, 0xc7, 0xb9, 0x9b, 0x78, 0xde, 0xa8, 0xf3, 0x53, 0x19, 0x73, 0x63, 0x7c, 0x94, 0x6a, 0x9c, 0xab, 0x33, 0x49, 0x74, 0x4b, 0x24, 0xa0, 0x85, 0x1d, 0xd4, 0x7f, 0x2b, 0x3b, 0x46, 0x0c, 0x2c, 0x61, 0x84, 0x6e, 0x91, 0x18, 0x1d, 0x62, 0xd4, 0x2c, 0x60, 0xa4, 0xef, 0xda, 0x5e, 0xd5, 0x79, 0x02, 0xbf, 0xd7, 0x02, 0xb3, 0x49, 0xc5, 0x49, 0x52, 0xc7, 0xf6, 0x44, 0x76, 0x9d, 0x8e, 0xf4, 0x01, 0x5e, 0xcc, 0x5f, 0x5b, 0xbd, 0x4a, 0xf0, 0x61, 0x34, 0x68, 0x8e, 0x30, 0x05, 0x0e, 0x04, 0x97, 0xfb, 0x0a }; static const ST_KAT_DRBG st_kat_drbg_tests[] = { { OSSL_SELF_TEST_DESC_DRBG_HASH, "HASH-DRBG", "digest", "SHA256", ITM(drbg_hash_sha256_pr_entropyin), ITM(drbg_hash_sha256_pr_nonce), ITM(drbg_hash_sha256_pr_persstr), ITM(drbg_hash_sha256_pr_entropyinpr0), ITM(drbg_hash_sha256_pr_entropyinpr1), ITM(drbg_hash_sha256_pr_addin0), ITM(drbg_hash_sha256_pr_addin1), ITM(drbg_hash_sha256_pr_expected) }, { OSSL_SELF_TEST_DESC_DRBG_CTR, "CTR-DRBG", "cipher", "AES-128-CTR", ITM(drbg_ctr_aes128_pr_df_entropyin), ITM(drbg_ctr_aes128_pr_df_nonce), ITM(drbg_ctr_aes128_pr_df_persstr), ITM(drbg_ctr_aes128_pr_df_entropyinpr0), ITM(drbg_ctr_aes128_pr_df_entropyinpr1), ITM(drbg_ctr_aes128_pr_df_addin0), ITM(drbg_ctr_aes128_pr_df_addin1), ITM(drbg_ctr_aes128_pr_df_expected) }, { OSSL_SELF_TEST_DESC_DRBG_HMAC, "HMAC-DRBG", "digest", "SHA256", ITM(drbg_hmac_sha2_pr_entropyin), ITM(drbg_hmac_sha2_pr_nonce), ITM(drbg_hmac_sha2_pr_persstr), ITM(drbg_hmac_sha2_pr_entropyinpr0), ITM(drbg_hmac_sha2_pr_entropyinpr1), ITM(drbg_hmac_sha2_pr_addin0), ITM(drbg_hmac_sha2_pr_addin1), ITM(drbg_hmac_sha2_pr_expected) } }; /* KEY EXCHANGE TEST DATA */ #ifndef OPENSSL_NO_DH /* DH KAT */ static const unsigned char dh_priv[] = { 0x14, 0x33, 0xe0, 0xb5, 0xa9, 0x17, 0xb6, 0x0a, 0x30, 0x23, 0xf2, 0xf8, 0xaa, 0x2c, 0x2d, 0x70, 0xd2, 0x96, 0x8a, 0xba, 0x9a, 0xea, 0xc8, 0x15, 0x40, 0xb8, 0xfc, 0xe6 }; static const unsigned char dh_pub[] = { 0x00, 0x8f, 0x81, 0x67, 0x68, 0xce, 0x97, 0x99, 0x7e, 0x11, 0x5c, 0xad, 0x5b, 0xe1, 0x0c, 0xd4, 0x15, 0x44, 0xdf, 0xc2, 0x47, 0xe7, 0x06, 0x27, 0x5e, 0xf3, 0x9d, 0x5c, 0x4b, 0x2e, 0x35, 0x05, 0xfd, 0x3c, 0x8f, 0x35, 0x85, 0x1b, 0x82, 0xdd, 0x49, 0xc9, 0xa8, 0x7e, 0x3a, 0x5f, 0x33, 0xdc, 0x8f, 0x5e, 0x32, 0x76, 0xe1, 0x52, 0x1b, 0x88, 0x85, 0xda, 0xa9, 0x1d, 0x5f, 0x1c, 0x05, 0x3a, 0xd4, 0x8d, 0xbb, 0xe7, 0x46, 0x46, 0x1e, 0x29, 0x4b, 0x5a, 0x02, 0x88, 0x46, 0x94, 0xd0, 0x68, 0x7d, 0xb2, 0x9f, 0x3a, 0x3d, 0x82, 0x05, 0xe5, 0xa7, 0xbe, 0x6c, 0x7e, 0x24, 0x35, 0x25, 0x14, 0xf3, 0x45, 0x08, 0x90, 0xfc, 0x55, 0x2e, 0xa8, 0xb8, 0xb1, 0x89, 0x15, 0x94, 0x51, 0x44, 0xa9, 0x9f, 0x68, 0xcb, 0x90, 0xbc, 0xd3, 0xae, 0x02, 0x37, 0x26, 0xe4, 0xe9, 0x1a, 0x90, 0x95, 0x7e, 0x1d, 0xac, 0x0c, 0x91, 0x97, 0x83, 0x24, 0x83, 0xb9, 0xa1, 0x40, 0x72, 0xac, 0xf0, 0x55, 0x32, 0x18, 0xab, 0xb8, 0x90, 0xda, 0x13, 0x4a, 0xc8, 0x4b, 0x7c, 0x18, 0xbc, 0x33, 0xbf, 0x99, 0x85, 0x39, 0x3e, 0xc6, 0x95, 0x9b, 0x48, 0x8e, 0xbe, 0x46, 0x59, 0x48, 0x41, 0x0d, 0x37, 0x25, 0x94, 0xbe, 0x8d, 0xf5, 0x81, 0x52, 0xf6, 0xdc, 0xeb, 0x98, 0xd7, 0x3b, 0x44, 0x61, 0x6f, 0xa3, 0xef, 0x7b, 0xfe, 0xbb, 0xc2, 0x8e, 0x46, 0x63, 0xbc, 0x52, 0x65, 0xf9, 0xf8, 0x85, 0x41, 0xdf, 0x82, 0x4a, 0x10, 0x2a, 0xe3, 0x0c, 0xb7, 0xad, 0x84, 0xa6, 0x6f, 0x4e, 0x8e, 0x96, 0x1e, 0x04, 0xf7, 0x57, 0x39, 0xca, 0x58, 0xd4, 0xef, 0x5a, 0xf1, 0xf5, 0x69, 0xc2, 0xb1, 0x5c, 0x0a, 0xce, 0xbe, 0x38, 0x01, 0xb5, 0x3f, 0x07, 0x8a, 0x72, 0x90, 0x10, 0xac, 0x51, 0x3a, 0x96, 0x43, 0xdf, 0x6f, 0xea }; static const unsigned char dh_peer_pub[] = { 0x1f, 0xc1, 0xda, 0x34, 0x1d, 0x1a, 0x84, 0x6a, 0x96, 0xb7, 0xbe, 0x24, 0x34, 0x0f, 0x87, 0x7d, 0xd0, 0x10, 0xaa, 0x03, 0x56, 0xd5, 0xad, 0x58, 0xaa, 0xe9, 0xc7, 0xb0, 0x8f, 0x74, 0x9a, 0x32, 0x23, 0x51, 0x10, 0xb5, 0xd8, 0x8e, 0xb5, 0xdb, 0xfa, 0x97, 0x8d, 0x27, 0xec, 0xc5, 0x30, 0xf0, 0x2d, 0x31, 0x14, 0x00, 0x5b, 0x64, 0xb1, 0xc0, 0xe0, 0x24, 0xcb, 0x8a, 0xe2, 0x16, 0x98, 0xbc, 0xa9, 0xe6, 0x0d, 0x42, 0x80, 0x86, 0x22, 0xf1, 0x81, 0xc5, 0x6e, 0x1d, 0xe7, 0xa9, 0x6e, 0x6e, 0xfe, 0xe9, 0xd6, 0x65, 0x67, 0xe9, 0x1b, 0x97, 0x70, 0x42, 0xc7, 0xe3, 0xd0, 0x44, 0x8f, 0x05, 0xfb, 0x77, 0xf5, 0x22, 0xb9, 0xbf, 0xc8, 0xd3, 0x3c, 0xc3, 0xc3, 0x1e, 0xd3, 0xb3, 0x1f, 0x0f, 0xec, 0xb6, 0xdb, 0x4f, 0x6e, 0xa3, 0x11, 0xe7, 0x7a, 0xfd, 0xbc, 0xd4, 0x7a, 0xee, 0x1b, 0xb1, 0x50, 0xf2, 0x16, 0x87, 0x35, 0x78, 0xfb, 0x96, 0x46, 0x8e, 0x8f, 0x9f, 0x3d, 0xe8, 0xef, 0xbf, 0xce, 0x75, 0x62, 0x4b, 0x1d, 0xf0, 0x53, 0x22, 0xa3, 0x4f, 0x14, 0x63, 0xe8, 0x39, 0xe8, 0x98, 0x4c, 0x4a, 0xd0, 0xa9, 0x6e, 0x1a, 0xc8, 0x42, 0xe5, 0x31, 0x8c, 0xc2, 0x3c, 0x06, 0x2a, 0x8c, 0xa1, 0x71, 0xb8, 0xd5, 0x75, 0x98, 0x0d, 0xde, 0x7f, 0xc5, 0x6f, 0x15, 0x36, 0x52, 0x38, 0x20, 0xd4, 0x31, 0x92, 0xbf, 0xd5, 0x1e, 0x8e, 0x22, 0x89, 0x78, 0xac, 0xa5, 0xb9, 0x44, 0x72, 0xf3, 0x39, 0xca, 0xeb, 0x99, 0x31, 0xb4, 0x2b, 0xe3, 0x01, 0x26, 0x8b, 0xc9, 0x97, 0x89, 0xc9, 0xb2, 0x55, 0x71, 0xc3, 0xc0, 0xe4, 0xcb, 0x3f, 0x00, 0x7f, 0x1a, 0x51, 0x1c, 0xbb, 0x53, 0xc8, 0x51, 0x9c, 0xdd, 0x13, 0x02, 0xab, 0xca, 0x6c, 0x0f, 0x34, 0xf9, 0x67, 0x39, 0xf1, 0x7f, 0xf4, 0x8b }; static const unsigned char dh_secret_expected[256] = { 0xa0, 0x38, 0x64, 0x37, 0xdf, 0x2d, 0x2c, 0x78, 0x49, 0xb9, 0xa7, 0x77, 0xfb, 0xc1, 0x69, 0x94, 0x85, 0xc5, 0x5a, 0xbc, 0x8d, 0x43, 0x32, 0x23, 0x94, 0xf5, 0xba, 0xb4, 0x5f, 0x22, 0x4b, 0x4e, 0xc4, 0xfd, 0x89, 0x41, 0x56, 0x41, 0xe8, 0x9f, 0x2d, 0x0d, 0x26, 0x33, 0x60, 0x13, 0x8a, 0x20, 0xf1, 0x7e, 0xb3, 0x76, 0x38, 0x03, 0x0e, 0x48, 0x4f, 0x27, 0x8c, 0x32, 0xdb, 0x66, 0x5c, 0xbf, 0x7f, 0xc7, 0xeb, 0xc6, 0x2d, 0xfd, 0x00, 0x08, 0xb0, 0x98, 0x4e, 0xad, 0x68, 0x65, 0xca, 0x9e, 0x78, 0xe1, 0xaa, 0xb7, 0x8e, 0x08, 0x4d, 0x67, 0xa6, 0x15, 0x16, 0xbb, 0x41, 0xac, 0x15, 0xb5, 0x08, 0x92, 0x5d, 0x25, 0x1d, 0x7f, 0xf3, 0x1b, 0x5c, 0xea, 0x21, 0x6b, 0xe5, 0x00, 0x4d, 0xb6, 0x8e, 0xae, 0x84, 0xb4, 0xee, 0xf7, 0xcc, 0xdd, 0x64, 0x19, 0x4e, 0x25, 0xce, 0x37, 0x4f, 0xde, 0xb6, 0x21, 0xba, 0xd9, 0xc0, 0x7a, 0x87, 0xc7, 0x90, 0x0a, 0x78, 0x8b, 0xdd, 0xbc, 0x68, 0x77, 0x2d, 0xa6, 0xdf, 0x4d, 0x2e, 0xca, 0xdc, 0x86, 0xb6, 0x1e, 0x54, 0x2b, 0x3a, 0xa9, 0x52, 0x67, 0xf3, 0x1a, 0x35, 0xb7, 0x5a, 0xcd, 0x99, 0x59, 0xe9, 0x07, 0x6f, 0xd7, 0xd7, 0x96, 0x8a, 0x47, 0xdf, 0x9f, 0x51, 0x1b, 0x04, 0xa9, 0x45, 0x30, 0x89, 0x8a, 0x3f, 0x7e, 0xca, 0xfc, 0x05, 0x2d, 0x18, 0x77, 0x8f, 0x45, 0x25, 0x39, 0xdb, 0xf2, 0x13, 0x36, 0x31, 0xdb, 0x50, 0x65, 0x63, 0x4a, 0xae, 0x3e, 0xd1, 0x3e, 0xde, 0xc1, 0x32, 0x4b, 0x78, 0x19, 0x03, 0x70, 0x0a, 0xc2, 0xa2, 0x6f, 0x9b, 0xd4, 0xa6, 0x1d, 0x47, 0xf2, 0xa6, 0x91, 0x61, 0x4a, 0x74, 0xf8, 0x70, 0x39, 0x42, 0x72, 0xd5, 0x58, 0x7f, 0xcd, 0x16, 0xeb, 0x82, 0x0c, 0x2c, 0xf4, 0xd0, 0x95, 0x22, 0xf9, 0xbe, 0x99, }; static const char dh_ffdhe2048[] = "ffdhe2048"; static const ST_KAT_PARAM dh_group[] = { ST_KAT_PARAM_UTF8STRING(OSSL_PKEY_PARAM_GROUP_NAME, dh_ffdhe2048), ST_KAT_PARAM_END() }; /* The host's private key */ static const ST_KAT_PARAM dh_host_key[] = { ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_PUB_KEY, dh_pub), ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_PRIV_KEY, dh_priv), ST_KAT_PARAM_END() }; /* The peer's public key */ static const ST_KAT_PARAM dh_peer_key[] = { ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_PUB_KEY, dh_peer_pub), ST_KAT_PARAM_END() }; #endif /* OPENSSL_NO_DH */ #ifndef OPENSSL_NO_EC static const char ecdh_curve_name[] = "prime256v1"; static const unsigned char ecdh_privd[] = { 0x33, 0xd0, 0x43, 0x83, 0xa9, 0x89, 0x56, 0x03, 0xd2, 0xd7, 0xfe, 0x6b, 0x01, 0x6f, 0xe4, 0x59, 0xcc, 0x0d, 0x9a, 0x24, 0x6c, 0x86, 0x1b, 0x2e, 0xdc, 0x4b, 0x4d, 0x35, 0x43, 0xe1, 0x1b, 0xad }; static const unsigned char ecdh_pub[] = { 0x04, 0x1b, 0x93, 0x67, 0x55, 0x1c, 0x55, 0x9f, 0x63, 0xd1, 0x22, 0xa4, 0xd8, 0xd1, 0x0a, 0x60, 0x6d, 0x02, 0xa5, 0x77, 0x57, 0xc8, 0xa3, 0x47, 0x73, 0x3a, 0x6a, 0x08, 0x28, 0x39, 0xbd, 0xc9, 0xd2, 0x80, 0xec, 0xe9, 0xa7, 0x08, 0x29, 0x71, 0x2f, 0xc9, 0x56, 0x82, 0xee, 0x9a, 0x85, 0x0f, 0x6d, 0x7f, 0x59, 0x5f, 0x8c, 0xd1, 0x96, 0x0b, 0xdf, 0x29, 0x3e, 0x49, 0x07, 0x88, 0x3f, 0x9a, 0x29 }; static const unsigned char ecdh_peer_pub[] = { 0x04, 0x1f, 0x72, 0xbd, 0x2a, 0x3e, 0xeb, 0x6c, 0x76, 0xe5, 0x5d, 0x69, 0x75, 0x24, 0xbf, 0x2f, 0x5b, 0x96, 0xb2, 0x91, 0x62, 0x06, 0x35, 0xcc, 0xb2, 0x4b, 0x31, 0x1b, 0x0c, 0x6f, 0x06, 0x9f, 0x86, 0xcf, 0xc8, 0xac, 0xd5, 0x4f, 0x4d, 0x77, 0xf3, 0x70, 0x4a, 0x8f, 0x04, 0x9a, 0xb1, 0x03, 0xc7, 0xeb, 0xd5, 0x94, 0x78, 0x61, 0xab, 0x78, 0x0c, 0x4a, 0x2d, 0x6b, 0xf3, 0x2f, 0x2e, 0x4a, 0xbc }; static const ST_KAT_PARAM ecdh_group[] = { ST_KAT_PARAM_UTF8STRING(OSSL_PKEY_PARAM_GROUP_NAME, ecdh_curve_name), ST_KAT_PARAM_END() }; static const ST_KAT_PARAM ecdh_host_key[] = { ST_KAT_PARAM_OCTET(OSSL_PKEY_PARAM_PUB_KEY, ecdh_pub), ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_PRIV_KEY, ecdh_privd), ST_KAT_PARAM_END() }; static const ST_KAT_PARAM ecdh_peer_key[] = { ST_KAT_PARAM_OCTET(OSSL_PKEY_PARAM_PUB_KEY, ecdh_peer_pub), ST_KAT_PARAM_END() }; static const unsigned char ecdh_secret_expected[] = { 0x45, 0x2a, 0x2f, 0x0d, 0x24, 0xe6, 0x8d, 0xd0, 0xda, 0x59, 0x7b, 0x0c, 0xec, 0x9b, 0x4c, 0x38, 0x41, 0xdd, 0xce, 0xb3, 0xcc, 0xf1, 0x90, 0x8e, 0x30, 0xdb, 0x5b, 0x5f, 0x97, 0xea, 0xe0, 0xc2 }; #endif /* OPENSSL_NO_EC */ #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_EC) static const ST_KAT_KAS st_kat_kas_tests[] = { # ifndef OPENSSL_NO_DH { OSSL_SELF_TEST_DESC_KA_DH, "DH", dh_group, dh_host_key, dh_peer_key, ITM(dh_secret_expected) }, # endif /* OPENSSL_NO_DH */ # ifndef OPENSSL_NO_EC { OSSL_SELF_TEST_DESC_KA_ECDH, "EC", ecdh_group, ecdh_host_key, ecdh_peer_key, ITM(ecdh_secret_expected) }, # endif /* OPENSSL_NO_EC */ }; #endif /* !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_EC) */ /* RSA key data */ static const unsigned char rsa_n[] = { 0xDB, 0x10, 0x1A, 0xC2, 0xA3, 0xF1, 0xDC, 0xFF, 0x13, 0x6B, 0xED, 0x44, 0xDF, 0xF0, 0x02, 0x6D, 0x13, 0xC7, 0x88, 0xDA, 0x70, 0x6B, 0x54, 0xF1, 0xE8, 0x27, 0xDC, 0xC3, 0x0F, 0x99, 0x6A, 0xFA, 0xC6, 0x67, 0xFF, 0x1D, 0x1E, 0x3C, 0x1D, 0xC1, 0xB5, 0x5F, 0x6C, 0xC0, 0xB2, 0x07, 0x3A, 0x6D, 0x41, 0xE4, 0x25, 0x99, 0xAC, 0xFC, 0xD2, 0x0F, 0x02, 0xD3, 0xD1, 0x54, 0x06, 0x1A, 0x51, 0x77, 0xBD, 0xB6, 0xBF, 0xEA, 0xA7, 0x5C, 0x06, 0xA9, 0x5D, 0x69, 0x84, 0x45, 0xD7, 0xF5, 0x05, 0xBA, 0x47, 0xF0, 0x1B, 0xD7, 0x2B, 0x24, 0xEC, 0xCB, 0x9B, 0x1B, 0x10, 0x8D, 0x81, 0xA0, 0xBE, 0xB1, 0x8C, 0x33, 0xE4, 0x36, 0xB8, 0x43, 0xEB, 0x19, 0x2A, 0x81, 0x8D, 0xDE, 0x81, 0x0A, 0x99, 0x48, 0xB6, 0xF6, 0xBC, 0xCD, 0x49, 0x34, 0x3A, 0x8F, 0x26, 0x94, 0xE3, 0x28, 0x82, 0x1A, 0x7C, 0x8F, 0x59, 0x9F, 0x45, 0xE8, 0x5D, 0x1A, 0x45, 0x76, 0x04, 0x56, 0x05, 0xA1, 0xD0, 0x1B, 0x8C, 0x77, 0x6D, 0xAF, 0x53, 0xFA, 0x71, 0xE2, 0x67, 0xE0, 0x9A, 0xFE, 0x03, 0xA9, 0x85, 0xD2, 0xC9, 0xAA, 0xBA, 0x2A, 0xBC, 0xF4, 0xA0, 0x08, 0xF5, 0x13, 0x98, 0x13, 0x5D, 0xF0, 0xD9, 0x33, 0x34, 0x2A, 0x61, 0xC3, 0x89, 0x55, 0xF0, 0xAE, 0x1A, 0x9C, 0x22, 0xEE, 0x19, 0x05, 0x8D, 0x32, 0xFE, 0xEC, 0x9C, 0x84, 0xBA, 0xB7, 0xF9, 0x6C, 0x3A, 0x4F, 0x07, 0xFC, 0x45, 0xEB, 0x12, 0xE5, 0x7B, 0xFD, 0x55, 0xE6, 0x29, 0x69, 0xD1, 0xC2, 0xE8, 0xB9, 0x78, 0x59, 0xF6, 0x79, 0x10, 0xC6, 0x4E, 0xEB, 0x6A, 0x5E, 0xB9, 0x9A, 0xC7, 0xC4, 0x5B, 0x63, 0xDA, 0xA3, 0x3F, 0x5E, 0x92, 0x7A, 0x81, 0x5E, 0xD6, 0xB0, 0xE2, 0x62, 0x8F, 0x74, 0x26, 0xC2, 0x0C, 0xD3, 0x9A, 0x17, 0x47, 0xE6, 0x8E, 0xAB }; static const unsigned char rsa_e[] = { 0x01, 0x00, 0x01 }; static const unsigned char rsa_d[] = { 0x52, 0x41, 0xF4, 0xDA, 0x7B, 0xB7, 0x59, 0x55, 0xCA, 0xD4, 0x2F, 0x0F, 0x3A, 0xCB, 0xA4, 0x0D, 0x93, 0x6C, 0xCC, 0x9D, 0xC1, 0xB2, 0xFB, 0xFD, 0xAE, 0x40, 0x31, 0xAC, 0x69, 0x52, 0x21, 0x92, 0xB3, 0x27, 0xDF, 0xEA, 0xEE, 0x2C, 0x82, 0xBB, 0xF7, 0x40, 0x32, 0xD5, 0x14, 0xC4, 0x94, 0x12, 0xEC, 0xB8, 0x1F, 0xCA, 0x59, 0xE3, 0xC1, 0x78, 0xF3, 0x85, 0xD8, 0x47, 0xA5, 0xD7, 0x02, 0x1A, 0x65, 0x79, 0x97, 0x0D, 0x24, 0xF4, 0xF0, 0x67, 0x6E, 0x75, 0x2D, 0xBF, 0x10, 0x3D, 0xA8, 0x7D, 0xEF, 0x7F, 0x60, 0xE4, 0xE6, 0x05, 0x82, 0x89, 0x5D, 0xDF, 0xC6, 0xD2, 0x6C, 0x07, 0x91, 0x33, 0x98, 0x42, 0xF0, 0x02, 0x00, 0x25, 0x38, 0xC5, 0x85, 0x69, 0x8A, 0x7D, 0x2F, 0x95, 0x6C, 0x43, 0x9A, 0xB8, 0x81, 0xE2, 0xD0, 0x07, 0x35, 0xAA, 0x05, 0x41, 0xC9, 0x1E, 0xAF, 0xE4, 0x04, 0x3B, 0x19, 0xB8, 0x73, 0xA2, 0xAC, 0x4B, 0x1E, 0x66, 0x48, 0xD8, 0x72, 0x1F, 0xAC, 0xF6, 0xCB, 0xBC, 0x90, 0x09, 0xCA, 0xEC, 0x0C, 0xDC, 0xF9, 0x2C, 0xD7, 0xEB, 0xAE, 0xA3, 0xA4, 0x47, 0xD7, 0x33, 0x2F, 0x8A, 0xCA, 0xBC, 0x5E, 0xF0, 0x77, 0xE4, 0x97, 0x98, 0x97, 0xC7, 0x10, 0x91, 0x7D, 0x2A, 0xA6, 0xFF, 0x46, 0x83, 0x97, 0xDE, 0xE9, 0xE2, 0x17, 0x03, 0x06, 0x14, 0xE2, 0xD7, 0xB1, 0x1D, 0x77, 0xAF, 0x51, 0x27, 0x5B, 0x5E, 0x69, 0xB8, 0x81, 0xE6, 0x11, 0xC5, 0x43, 0x23, 0x81, 0x04, 0x62, 0xFF, 0xE9, 0x46, 0xB8, 0xD8, 0x44, 0xDB, 0xA5, 0xCC, 0x31, 0x54, 0x34, 0xCE, 0x3E, 0x82, 0xD6, 0xBF, 0x7A, 0x0B, 0x64, 0x21, 0x6D, 0x88, 0x7E, 0x5B, 0x45, 0x12, 0x1E, 0x63, 0x8D, 0x49, 0xA7, 0x1D, 0xD9, 0x1E, 0x06, 0xCD, 0xE8, 0xBA, 0x2C, 0x8C, 0x69, 0x32, 0xEA, 0xBE, 0x60, 0x71 }; static const unsigned char rsa_p[] = { 0xFA, 0xAC, 0xE1, 0x37, 0x5E, 0x32, 0x11, 0x34, 0xC6, 0x72, 0x58, 0x2D, 0x91, 0x06, 0x3E, 0x77, 0xE7, 0x11, 0x21, 0xCD, 0x4A, 0xF8, 0xA4, 0x3F, 0x0F, 0xEF, 0x31, 0xE3, 0xF3, 0x55, 0xA0, 0xB9, 0xAC, 0xB6, 0xCB, 0xBB, 0x41, 0xD0, 0x32, 0x81, 0x9A, 0x8F, 0x7A, 0x99, 0x30, 0x77, 0x6C, 0x68, 0x27, 0xE2, 0x96, 0xB5, 0x72, 0xC9, 0xC3, 0xD4, 0x42, 0xAA, 0xAA, 0xCA, 0x95, 0x8F, 0xFF, 0xC9, 0x9B, 0x52, 0x34, 0x30, 0x1D, 0xCF, 0xFE, 0xCF, 0x3C, 0x56, 0x68, 0x6E, 0xEF, 0xE7, 0x6C, 0xD7, 0xFB, 0x99, 0xF5, 0x4A, 0xA5, 0x21, 0x1F, 0x2B, 0xEA, 0x93, 0xE8, 0x98, 0x26, 0xC4, 0x6E, 0x42, 0x21, 0x5E, 0xA0, 0xA1, 0x2A, 0x58, 0x35, 0xBB, 0x10, 0xE7, 0xBA, 0x27, 0x0A, 0x3B, 0xB3, 0xAF, 0xE2, 0x75, 0x36, 0x04, 0xAC, 0x56, 0xA0, 0xAB, 0x52, 0xDE, 0xCE, 0xDD, 0x2C, 0x28, 0x77, 0x03 }; static const unsigned char rsa_q[] = { 0xDF, 0xB7, 0x52, 0xB6, 0xD7, 0xC0, 0xE2, 0x96, 0xE7, 0xC9, 0xFE, 0x5D, 0x71, 0x5A, 0xC4, 0x40, 0x96, 0x2F, 0xE5, 0x87, 0xEA, 0xF3, 0xA5, 0x77, 0x11, 0x67, 0x3C, 0x8D, 0x56, 0x08, 0xA7, 0xB5, 0x67, 0xFA, 0x37, 0xA8, 0xB8, 0xCF, 0x61, 0xE8, 0x63, 0xD8, 0x38, 0x06, 0x21, 0x2B, 0x92, 0x09, 0xA6, 0x39, 0x3A, 0xEA, 0xA8, 0xB4, 0x45, 0x4B, 0x36, 0x10, 0x4C, 0xE4, 0x00, 0x66, 0x71, 0x65, 0xF8, 0x0B, 0x94, 0x59, 0x4F, 0x8C, 0xFD, 0xD5, 0x34, 0xA2, 0xE7, 0x62, 0x84, 0x0A, 0xA7, 0xBB, 0xDB, 0xD9, 0x8A, 0xCD, 0x05, 0xE1, 0xCC, 0x57, 0x7B, 0xF1, 0xF1, 0x1F, 0x11, 0x9D, 0xBA, 0x3E, 0x45, 0x18, 0x99, 0x1B, 0x41, 0x64, 0x43, 0xEE, 0x97, 0x5D, 0x77, 0x13, 0x5B, 0x74, 0x69, 0x73, 0x87, 0x95, 0x05, 0x07, 0xBE, 0x45, 0x07, 0x17, 0x7E, 0x4A, 0x69, 0x22, 0xF3, 0xDB, 0x05, 0x39 }; static const unsigned char rsa_dp[] = { 0x5E, 0xD8, 0xDC, 0xDA, 0x53, 0x44, 0xC4, 0x67, 0xE0, 0x92, 0x51, 0x34, 0xE4, 0x83, 0xA5, 0x4D, 0x3E, 0xDB, 0xA7, 0x9B, 0x82, 0xBB, 0x73, 0x81, 0xFC, 0xE8, 0x77, 0x4B, 0x15, 0xBE, 0x17, 0x73, 0x49, 0x9B, 0x5C, 0x98, 0xBC, 0xBD, 0x26, 0xEF, 0x0C, 0xE9, 0x2E, 0xED, 0x19, 0x7E, 0x86, 0x41, 0x1E, 0x9E, 0x48, 0x81, 0xDD, 0x2D, 0xE4, 0x6F, 0xC2, 0xCD, 0xCA, 0x93, 0x9E, 0x65, 0x7E, 0xD5, 0xEC, 0x73, 0xFD, 0x15, 0x1B, 0xA2, 0xA0, 0x7A, 0x0F, 0x0D, 0x6E, 0xB4, 0x53, 0x07, 0x90, 0x92, 0x64, 0x3B, 0x8B, 0xA9, 0x33, 0xB3, 0xC5, 0x94, 0x9B, 0x4C, 0x5D, 0x9C, 0x7C, 0x46, 0xA4, 0xA5, 0x56, 0xF4, 0xF3, 0xF8, 0x27, 0x0A, 0x7B, 0x42, 0x0D, 0x92, 0x70, 0x47, 0xE7, 0x42, 0x51, 0xA9, 0xC2, 0x18, 0xB1, 0x58, 0xB1, 0x50, 0x91, 0xB8, 0x61, 0x41, 0xB6, 0xA9, 0xCE, 0xD4, 0x7C, 0xBB }; static const unsigned char rsa_dq[] = { 0x54, 0x09, 0x1F, 0x0F, 0x03, 0xD8, 0xB6, 0xC5, 0x0C, 0xE8, 0xB9, 0x9E, 0x0C, 0x38, 0x96, 0x43, 0xD4, 0xA6, 0xC5, 0x47, 0xDB, 0x20, 0x0E, 0xE5, 0xBD, 0x29, 0xD4, 0x7B, 0x1A, 0xF8, 0x41, 0x57, 0x49, 0x69, 0x9A, 0x82, 0xCC, 0x79, 0x4A, 0x43, 0xEB, 0x4D, 0x8B, 0x2D, 0xF2, 0x43, 0xD5, 0xA5, 0xBE, 0x44, 0xFD, 0x36, 0xAC, 0x8C, 0x9B, 0x02, 0xF7, 0x9A, 0x03, 0xE8, 0x19, 0xA6, 0x61, 0xAE, 0x76, 0x10, 0x93, 0x77, 0x41, 0x04, 0xAB, 0x4C, 0xED, 0x6A, 0xCC, 0x14, 0x1B, 0x99, 0x8D, 0x0C, 0x6A, 0x37, 0x3B, 0x86, 0x6C, 0x51, 0x37, 0x5B, 0x1D, 0x79, 0xF2, 0xA3, 0x43, 0x10, 0xC6, 0xA7, 0x21, 0x79, 0x6D, 0xF9, 0xE9, 0x04, 0x6A, 0xE8, 0x32, 0xFF, 0xAE, 0xFD, 0x1C, 0x7B, 0x8C, 0x29, 0x13, 0xA3, 0x0C, 0xB2, 0xAD, 0xEC, 0x6C, 0x0F, 0x8D, 0x27, 0x12, 0x7B, 0x48, 0xB2, 0xDB, 0x31 }; static const unsigned char rsa_qInv[] = { 0x8D, 0x1B, 0x05, 0xCA, 0x24, 0x1F, 0x0C, 0x53, 0x19, 0x52, 0x74, 0x63, 0x21, 0xFA, 0x78, 0x46, 0x79, 0xAF, 0x5C, 0xDE, 0x30, 0xA4, 0x6C, 0x20, 0x38, 0xE6, 0x97, 0x39, 0xB8, 0x7A, 0x70, 0x0D, 0x8B, 0x6C, 0x6D, 0x13, 0x74, 0xD5, 0x1C, 0xDE, 0xA9, 0xF4, 0x60, 0x37, 0xFE, 0x68, 0x77, 0x5E, 0x0B, 0x4E, 0x5E, 0x03, 0x31, 0x30, 0xDF, 0xD6, 0xAE, 0x85, 0xD0, 0x81, 0xBB, 0x61, 0xC7, 0xB1, 0x04, 0x5A, 0xC4, 0x6D, 0x56, 0x1C, 0xD9, 0x64, 0xE7, 0x85, 0x7F, 0x88, 0x91, 0xC9, 0x60, 0x28, 0x05, 0xE2, 0xC6, 0x24, 0x8F, 0xDD, 0x61, 0x64, 0xD8, 0x09, 0xDE, 0x7E, 0xD3, 0x4A, 0x61, 0x1A, 0xD3, 0x73, 0x58, 0x4B, 0xD8, 0xA0, 0x54, 0x25, 0x48, 0x83, 0x6F, 0x82, 0x6C, 0xAF, 0x36, 0x51, 0x2A, 0x5D, 0x14, 0x2F, 0x41, 0x25, 0x00, 0xDD, 0xF8, 0xF3, 0x95, 0xFE, 0x31, 0x25, 0x50, 0x12 }; static const ST_KAT_PARAM rsa_crt_key[] = { ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_RSA_N, rsa_n), ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_RSA_E, rsa_e), ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_RSA_D, rsa_d), ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_RSA_FACTOR1, rsa_p), ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_RSA_FACTOR2, rsa_q), ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_RSA_EXPONENT1, rsa_dp), ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_RSA_EXPONENT2, rsa_dq), ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_RSA_COEFFICIENT1, rsa_qInv), ST_KAT_PARAM_END() }; static const ST_KAT_PARAM rsa_pub_key[] = { ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_RSA_N, rsa_n), ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_RSA_E, rsa_e), ST_KAT_PARAM_END() }; static const ST_KAT_PARAM rsa_priv_key[] = { ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_RSA_N, rsa_n), ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_RSA_E, rsa_e), ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_RSA_D, rsa_d), ST_KAT_PARAM_END() }; +/*- + * Using OSSL_PKEY_RSA_PAD_MODE_NONE directly in the expansion of the + * ST_KAT_PARAM_UTF8STRING macro below causes a failure on ancient + * HP/UX PA-RISC compilers. + */ +static const char pad_mode_none[] = OSSL_PKEY_RSA_PAD_MODE_NONE; + +static const ST_KAT_PARAM rsa_enc_params[] = { + ST_KAT_PARAM_UTF8STRING(OSSL_ASYM_CIPHER_PARAM_PAD_MODE, pad_mode_none), + ST_KAT_PARAM_END() +}; + static const unsigned char rsa_sig_msg[] = "Hello World!"; static const unsigned char rsa_expected_sig[256] = { 0xad, 0xbe, 0x2a, 0xaf, 0x16, 0x85, 0xc5, 0x00, 0x91, 0x3e, 0xd0, 0x49, 0xfb, 0x3a, 0x81, 0xb9, 0x6c, 0x28, 0xbc, 0xbf, 0xea, 0x96, 0x5f, 0xe4, 0x9f, 0x99, 0xf7, 0x18, 0x8c, 0xec, 0x60, 0x28, 0xeb, 0x29, 0x02, 0x49, 0xfc, 0xda, 0xd7, 0x78, 0x68, 0xf8, 0xe1, 0xe9, 0x4d, 0x20, 0x6d, 0x32, 0xa6, 0xde, 0xfc, 0xe4, 0xda, 0xcc, 0x6c, 0x75, 0x36, 0x6b, 0xff, 0x5a, 0xac, 0x01, 0xa8, 0xc2, 0xa9, 0xe6, 0x8b, 0x18, 0x3e, 0xec, 0xea, 0x4c, 0x4a, 0x9e, 0x00, 0x09, 0xd1, 0x8a, 0x69, 0x1b, 0x8b, 0xd9, 0xad, 0x37, 0xe5, 0x7c, 0xff, 0x7d, 0x59, 0x56, 0x3e, 0xa0, 0xc6, 0x32, 0xd8, 0x35, 0x2f, 0xff, 0xfb, 0x05, 0x02, 0xcd, 0xd7, 0x19, 0xb9, 0x00, 0x86, 0x2a, 0xcf, 0xaa, 0x78, 0x16, 0x4b, 0xf1, 0xa7, 0x59, 0xef, 0x7d, 0xe8, 0x74, 0x23, 0x5c, 0xb2, 0xd4, 0x8a, 0x99, 0xa5, 0xbc, 0xfa, 0x63, 0xd8, 0xf7, 0xbd, 0xc6, 0x00, 0x13, 0x06, 0x02, 0x9a, 0xd4, 0xa7, 0xb4, 0x3d, 0x61, 0xab, 0xf1, 0xc2, 0x95, 0x59, 0x9b, 0x3d, 0x67, 0x1f, 0xde, 0x57, 0xb6, 0xb6, 0x9f, 0xb0, 0x87, 0xd6, 0x51, 0xd5, 0x3e, 0x00, 0xe2, 0xc9, 0xa0, 0x03, 0x66, 0xbc, 0x01, 0xb3, 0x8e, 0xfa, 0xf1, 0x15, 0xeb, 0x26, 0xf1, 0x5d, 0x81, 0x90, 0xb4, 0x1c, 0x00, 0x7c, 0x83, 0x4a, 0xa5, 0xde, 0x64, 0xae, 0xea, 0x6c, 0x43, 0xc3, 0x20, 0x77, 0x77, 0x42, 0x12, 0x24, 0xf5, 0xe3, 0x70, 0xdd, 0x59, 0x48, 0x9c, 0xef, 0xd4, 0x8a, 0x3c, 0x29, 0x6a, 0x0c, 0x9c, 0xf2, 0x13, 0xa4, 0x1c, 0x2f, 0x49, 0xcd, 0xb4, 0xaa, 0x28, 0x40, 0x34, 0xc6, 0x75, 0xba, 0x30, 0xe6, 0xd8, 0x5b, 0x2f, 0x08, 0xd0, 0x29, 0xa5, 0x39, 0xfb, 0x6e, 0x3b, 0x0f, 0x52, 0x2c, 0x68, 0xf0, 0x37, 0xa9, 0xd2, 0x56, 0xd6 }; static const unsigned char rsa_asym_plaintext_encrypt[256] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, }; static const unsigned char rsa_asym_expected_encrypt[256] = { 0x54, 0xac, 0x23, 0x96, 0x1d, 0x82, 0x5d, 0x8b, 0x8f, 0x36, 0x33, 0xd0, 0xf4, 0x02, 0xa2, 0x61, 0xb1, 0x13, 0xd4, 0x4a, 0x46, 0x06, 0x37, 0x3c, 0xbf, 0x40, 0x05, 0x3c, 0xc6, 0x3b, 0x64, 0xdc, 0x22, 0x22, 0xaf, 0x36, 0x79, 0x62, 0x45, 0xf0, 0x97, 0x82, 0x22, 0x44, 0x86, 0x4a, 0x7c, 0xfa, 0xac, 0x03, 0x21, 0x84, 0x3f, 0x31, 0xad, 0x2a, 0xa4, 0x6e, 0x7a, 0xc5, 0x93, 0xf3, 0x0f, 0xfc, 0xf1, 0x62, 0xce, 0x82, 0x12, 0x45, 0xc9, 0x35, 0xb0, 0x7a, 0xcd, 0x99, 0x8c, 0x91, 0x6b, 0x5a, 0xd3, 0x46, 0xdb, 0xf9, 0x9e, 0x52, 0x49, 0xbd, 0x1e, 0xe8, 0xda, 0xac, 0x61, 0x47, 0xc2, 0xda, 0xfc, 0x1e, 0xfb, 0x74, 0xd7, 0xd6, 0xc1, 0x18, 0x86, 0x3e, 0x20, 0x9c, 0x7a, 0xe1, 0x04, 0xb7, 0x38, 0x43, 0xb1, 0x4e, 0xa0, 0xd8, 0xc1, 0x39, 0x4d, 0xe1, 0xd3, 0xb0, 0xb3, 0xf1, 0x82, 0x87, 0x1f, 0x74, 0xb5, 0x69, 0xfd, 0x33, 0xd6, 0x21, 0x7c, 0x61, 0x60, 0x28, 0xca, 0x70, 0xdb, 0xa0, 0xbb, 0xc8, 0x73, 0xa9, 0x82, 0xf8, 0x6b, 0xd8, 0xf0, 0xc9, 0x7b, 0x20, 0xdf, 0x9d, 0xfb, 0x8c, 0xd4, 0xa2, 0x89, 0xe1, 0x9b, 0x04, 0xad, 0xaa, 0x11, 0x6c, 0x8f, 0xce, 0x83, 0x29, 0x56, 0x69, 0xbb, 0x00, 0x3b, 0xef, 0xca, 0x2d, 0xcd, 0x52, 0xc8, 0xf1, 0xb3, 0x9b, 0xb4, 0x4f, 0x6d, 0x9c, 0x3d, 0x69, 0xcc, 0x6d, 0x1f, 0x38, 0x4d, 0xe6, 0xbb, 0x0c, 0x87, 0xdc, 0x5f, 0xa9, 0x24, 0x93, 0x03, 0x46, 0xa2, 0x33, 0x6c, 0xf4, 0xd8, 0x5d, 0x68, 0xf3, 0xd3, 0xe0, 0xf2, 0x30, 0xdb, 0xf5, 0x4f, 0x0f, 0xad, 0xc7, 0xd0, 0xaa, 0x47, 0xd9, 0x9f, 0x85, 0x1b, 0x2e, 0x6c, 0x3c, 0x57, 0x04, 0x29, 0xf4, 0xf5, 0x66, 0x7d, 0x93, 0x4a, 0xaa, 0x05, 0x52, 0x55, 0xc1, 0xc6, 0x06, 0x90, 0xab, }; #ifndef OPENSSL_NO_EC /* ECDSA key data */ static const char ecd_prime_curve_name[] = "secp224r1"; static const unsigned char ecd_prime_priv[] = { 0x98, 0x1f, 0xb5, 0xf1, 0xfc, 0x87, 0x1d, 0x7d, 0xde, 0x1e, 0x01, 0x64, 0x09, 0x9b, 0xe7, 0x1b, 0x9f, 0xad, 0x63, 0xdd, 0x33, 0x01, 0xd1, 0x50, 0x80, 0x93, 0x50, 0x30 }; static const unsigned char ecd_prime_pub[] = { 0x04, 0x95, 0x47, 0x99, 0x44, 0x29, 0x8f, 0x51, 0x39, 0xe2, 0x53, 0xec, 0x79, 0xb0, 0x4d, 0xde, 0x87, 0x1a, 0x76, 0x54, 0xd5, 0x96, 0xb8, 0x7a, 0x6d, 0xf4, 0x1c, 0x2c, 0x87, 0x91, 0x5f, 0xd5, 0x31, 0xdd, 0x24, 0xe5, 0x78, 0xd9, 0x08, 0x24, 0x8a, 0x49, 0x99, 0xec, 0x55, 0xf2, 0x82, 0xb3, 0xc4, 0xb7, 0x33, 0x68, 0xe4, 0x24, 0xa9, 0x12, 0x82 }; static const unsigned char ecdsa_prime_expected_sig[] = { 0x30, 0x3d, 0x02, 0x1c, 0x48, 0x4f, 0x3c, 0x97, 0x5b, 0xfa, 0x40, 0x6c, 0xdb, 0xd6, 0x70, 0xb5, 0xbd, 0x2d, 0xd0, 0xc6, 0x22, 0x93, 0x5a, 0x88, 0x56, 0xd0, 0xaf, 0x0a, 0x94, 0x92, 0x20, 0x01, 0x02, 0x1d, 0x00, 0xa4, 0x80, 0xe0, 0x47, 0x88, 0x8a, 0xef, 0x2a, 0x47, 0x9d, 0x81, 0x9a, 0xbf, 0x45, 0xc3, 0x6f, 0x9e, 0x2e, 0xc1, 0x44, 0x9f, 0xfd, 0x79, 0xdb, 0x90, 0x3e, 0xb9, 0xb2 }; static const ST_KAT_PARAM ecdsa_prime_key[] = { ST_KAT_PARAM_UTF8STRING(OSSL_PKEY_PARAM_GROUP_NAME, ecd_prime_curve_name), ST_KAT_PARAM_OCTET(OSSL_PKEY_PARAM_PUB_KEY, ecd_prime_pub), ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_PRIV_KEY, ecd_prime_priv), ST_KAT_PARAM_END() }; # ifndef OPENSSL_NO_EC2M static const char ecd_bin_curve_name[] = "sect233r1"; static const unsigned char ecd_bin_priv[] = { 0x00, 0x6d, 0xd6, 0x39, 0x9d, 0x2a, 0xa2, 0xc8, 0x8c, 0xfc, 0x7b, 0x80, 0x66, 0xaa, 0xe1, 0xaa, 0xba, 0xee, 0xcb, 0xfd, 0xc9, 0xe5, 0x36, 0x38, 0x2e, 0xf7, 0x37, 0x6d, 0xd3, 0x20 }; static const unsigned char ecd_bin_pub[] = { 0x04, 0x00, 0x06, 0xe2, 0x56, 0xf7, 0x37, 0xf9, 0xea, 0xb6, 0xd1, 0x0f, 0x59, 0xfa, 0x23, 0xc3, 0x93, 0xa8, 0xb2, 0x26, 0xe2, 0x5c, 0x08, 0xbe, 0x63, 0x49, 0x26, 0xdc, 0xc7, 0x1e, 0x6f, 0x01, 0x32, 0x3b, 0xe6, 0x54, 0x8d, 0xc1, 0x13, 0x3e, 0x54, 0xb2, 0x66, 0x89, 0xb2, 0x82, 0x0a, 0x72, 0x02, 0xa8, 0xe9, 0x6f, 0x54, 0xfd, 0x3a, 0x6b, 0x99, 0xb6, 0x8f, 0x80, 0x46 }; static const unsigned char ecdsa_bin_expected_sig[] = { 0x30, 0x3f, 0x02, 0x1d, 0x58, 0xe9, 0xd0, 0x84, 0x5c, 0xad, 0x29, 0x03, 0xf6, 0xa6, 0xbc, 0xe0, 0x24, 0x6d, 0x9e, 0x79, 0x5d, 0x1e, 0xe8, 0x5a, 0xc3, 0x31, 0x0a, 0xa9, 0xfb, 0xe3, 0x99, 0x54, 0x11, 0x02, 0x1e, 0x00, 0xa3, 0x44, 0x28, 0xa3, 0x70, 0x97, 0x98, 0x17, 0xd7, 0xa6, 0xad, 0x91, 0xaf, 0x41, 0x69, 0xb6, 0x06, 0x99, 0x39, 0xc7, 0x63, 0xa4, 0x6a, 0x81, 0xe4, 0x9a, 0x9d, 0x15, 0x8b }; static const ST_KAT_PARAM ecdsa_bin_key[] = { ST_KAT_PARAM_UTF8STRING(OSSL_PKEY_PARAM_GROUP_NAME, ecd_bin_curve_name), ST_KAT_PARAM_OCTET(OSSL_PKEY_PARAM_PUB_KEY, ecd_bin_pub), ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_PRIV_KEY, ecd_bin_priv), ST_KAT_PARAM_END() }; # endif /* OPENSSL_NO_EC2M */ # ifndef OPENSSL_NO_ECX static const unsigned char ecx_sig_msg[] = { 0x64, 0xa6, 0x5f, 0x3c, 0xde, 0xdc, 0xdd, 0x66, 0x81, 0x1e, 0x29, 0x15 }; static const unsigned char ed25519_pub[] = { 0xfc, 0x51, 0xcd, 0x8e, 0x62, 0x18, 0xa1, 0xa3, 0x8d, 0xa4, 0x7e, 0xd0, 0x02, 0x30, 0xf0, 0x58, 0x08, 0x16, 0xed, 0x13, 0xba, 0x33, 0x03, 0xac, 0x5d, 0xeb, 0x91, 0x15, 0x48, 0x90, 0x80, 0x25 }; static const unsigned char ed25519_priv[] = { 0xc5, 0xaa, 0x8d, 0xf4, 0x3f, 0x9f, 0x83, 0x7b, 0xed, 0xb7, 0x44, 0x2f, 0x31, 0xdc, 0xb7, 0xb1, 0x66, 0xd3, 0x85, 0x35, 0x07, 0x6f, 0x09, 0x4b, 0x85, 0xce, 0x3a, 0x2e, 0x0b, 0x44, 0x58, 0xf7 }; static const ST_KAT_PARAM ed25519_key[] = { ST_KAT_PARAM_OCTET(OSSL_PKEY_PARAM_PUB_KEY, ed25519_pub), ST_KAT_PARAM_OCTET(OSSL_PKEY_PARAM_PRIV_KEY, ed25519_priv), ST_KAT_PARAM_END() }; static const unsigned char ed25519_expected_sig[] = { 0x1e, 0xf4, 0xc5, 0x61, 0xdc, 0x97, 0x9f, 0xaf, 0x55, 0x6b, 0x46, 0xa1, 0xae, 0xb0, 0x64, 0x13, 0x1c, 0x98, 0x09, 0x96, 0x88, 0xe0, 0x9d, 0x0e, 0x4e, 0x7d, 0xc4, 0xa5, 0xa1, 0x91, 0x09, 0xca, 0xd9, 0x5b, 0x4f, 0x1c, 0x80, 0x82, 0x9f, 0x65, 0xc1, 0x41, 0xa4, 0xe8, 0x02, 0x05, 0x0c, 0xa6, 0x7e, 0xa0, 0xfa, 0x01, 0xee, 0xeb, 0xaa, 0x91, 0x62, 0xfd, 0x0f, 0x25, 0xa0, 0x2d, 0x37, 0x09 }; static const unsigned char ed448_pub[] = { 0x3b, 0xa1, 0x6d, 0xa0, 0xc6, 0xf2, 0xcc, 0x1f, 0x30, 0x18, 0x77, 0x40, 0x75, 0x6f, 0x5e, 0x79, 0x8d, 0x6b, 0xc5, 0xfc, 0x01, 0x5d, 0x7c, 0x63, 0xcc, 0x95, 0x10, 0xee, 0x3f, 0xd4, 0x4a, 0xdc, 0x24, 0xd8, 0xe9, 0x68, 0xb6, 0xe4, 0x6e, 0x6f, 0x94, 0xd1, 0x9b, 0x94, 0x53, 0x61, 0x72, 0x6b, 0xd7, 0x5e, 0x14, 0x9e, 0xf0, 0x98, 0x17, 0xf5, 0x80 }; static const unsigned char ed448_priv[] = { 0x25, 0x8c, 0xdd, 0x4a, 0xda, 0x32, 0xed, 0x9c, 0x9f, 0xf5, 0x4e, 0x63, 0x75, 0x6a, 0xe5, 0x82, 0xfb, 0x8f, 0xab, 0x2a, 0xc7, 0x21, 0xf2, 0xc8, 0xe6, 0x76, 0xa7, 0x27, 0x68, 0x51, 0x3d, 0x93, 0x9f, 0x63, 0xdd, 0xdb, 0x55, 0x60, 0x91, 0x33, 0xf2, 0x9a, 0xdf, 0x86, 0xec, 0x99, 0x29, 0xdc, 0xcb, 0x52, 0xc1, 0xc5, 0xfd, 0x2f, 0xf7, 0xe2, 0x1b }; static const ST_KAT_PARAM ed448_key[] = { ST_KAT_PARAM_OCTET(OSSL_PKEY_PARAM_PUB_KEY, ed448_pub), ST_KAT_PARAM_OCTET(OSSL_PKEY_PARAM_PRIV_KEY, ed448_priv), ST_KAT_PARAM_END() }; static const unsigned char ed448_expected_sig[] = { 0x7e, 0xee, 0xab, 0x7c, 0x4e, 0x50, 0xfb, 0x79, 0x9b, 0x41, 0x8e, 0xe5, 0xe3, 0x19, 0x7f, 0xf6, 0xbf, 0x15, 0xd4, 0x3a, 0x14, 0xc3, 0x43, 0x89, 0xb5, 0x9d, 0xd1, 0xa7, 0xb1, 0xb8, 0x5b, 0x4a, 0xe9, 0x04, 0x38, 0xac, 0xa6, 0x34, 0xbe, 0xa4, 0x5e, 0x3a, 0x26, 0x95, 0xf1, 0x27, 0x0f, 0x07, 0xfd, 0xcd, 0xf7, 0xc6, 0x2b, 0x8e, 0xfe, 0xaf, 0x00, 0xb4, 0x5c, 0x2c, 0x96, 0xba, 0x45, 0x7e, 0xb1, 0xa8, 0xbf, 0x07, 0x5a, 0x3d, 0xb2, 0x8e, 0x5c, 0x24, 0xf6, 0xb9, 0x23, 0xed, 0x4a, 0xd7, 0x47, 0xc3, 0xc9, 0xe0, 0x3c, 0x70, 0x79, 0xef, 0xb8, 0x7c, 0xb1, 0x10, 0xd3, 0xa9, 0x98, 0x61, 0xe7, 0x20, 0x03, 0xcb, 0xae, 0x6d, 0x6b, 0x8b, 0x82, 0x7e, 0x4e, 0x6c, 0x14, 0x30, 0x64, 0xff, 0x3c, 0x00 }; # endif /* OPENSSL_NO_ECX */ #endif /* OPENSSL_NO_EC */ #ifndef OPENSSL_NO_DSA /* dsa 2048 */ static const unsigned char dsa_p[] = { 0xa2, 0x9b, 0x88, 0x72, 0xce, 0x8b, 0x84, 0x23, 0xb7, 0xd5, 0xd2, 0x1d, 0x4b, 0x02, 0xf5, 0x7e, 0x03, 0xe9, 0xe6, 0xb8, 0xa2, 0x58, 0xdc, 0x16, 0x61, 0x1b, 0xa0, 0x98, 0xab, 0x54, 0x34, 0x15, 0xe4, 0x15, 0xf1, 0x56, 0x99, 0x7a, 0x3e, 0xe2, 0x36, 0x65, 0x8f, 0xa0, 0x93, 0x26, 0x0d, 0xe3, 0xad, 0x42, 0x2e, 0x05, 0xe0, 0x46, 0xf9, 0xec, 0x29, 0x16, 0x1a, 0x37, 0x5f, 0x0e, 0xb4, 0xef, 0xfc, 0xef, 0x58, 0x28, 0x5c, 0x5d, 0x39, 0xed, 0x42, 0x5d, 0x7a, 0x62, 0xca, 0x12, 0x89, 0x6c, 0x4a, 0x92, 0xcb, 0x19, 0x46, 0xf2, 0x95, 0x2a, 0x48, 0x13, 0x3f, 0x07, 0xda, 0x36, 0x4d, 0x1b, 0xdf, 0x6b, 0x0f, 0x71, 0x39, 0x98, 0x3e, 0x69, 0x3c, 0x80, 0x05, 0x9b, 0x0e, 0xac, 0xd1, 0x47, 0x9b, 0xa9, 0xf2, 0x85, 0x77, 0x54, 0xed, 0xe7, 0x5f, 0x11, 0x2b, 0x07, 0xeb, 0xbf, 0x35, 0x34, 0x8b, 0xbf, 0x3e, 0x01, 0xe0, 0x2f, 0x2d, 0x47, 0x3d, 0xe3, 0x94, 0x53, 0xf9, 0x9d, 0xd2, 0x36, 0x75, 0x41, 0xca, 0xca, 0x3b, 0xa0, 0x11, 0x66, 0x34, 0x3d, 0x7b, 0x5b, 0x58, 0xa3, 0x7b, 0xd1, 0xb7, 0x52, 0x1d, 0xb2, 0xf1, 0x3b, 0x86, 0x70, 0x71, 0x32, 0xfe, 0x09, 0xf4, 0xcd, 0x09, 0xdc, 0x16, 0x18, 0xfa, 0x34, 0x01, 0xeb, 0xf9, 0xcc, 0x7b, 0x19, 0xfa, 0x94, 0xaa, 0x47, 0x20, 0x88, 0x13, 0x3d, 0x6c, 0xb2, 0xd3, 0x5c, 0x11, 0x79, 0xc8, 0xc8, 0xff, 0x36, 0x87, 0x58, 0xd5, 0x07, 0xd9, 0xf9, 0xa1, 0x7d, 0x46, 0xc1, 0x10, 0xfe, 0x31, 0x44, 0xce, 0x9b, 0x02, 0x2b, 0x42, 0xe4, 0x19, 0xeb, 0x4f, 0x53, 0x88, 0x61, 0x3b, 0xfc, 0x3e, 0x26, 0x24, 0x1a, 0x43, 0x2e, 0x87, 0x06, 0xbc, 0x58, 0xef, 0x76, 0x11, 0x72, 0x78, 0xde, 0xab, 0x6c, 0xf6, 0x92, 0x61, 0x82, 0x91, 0xb7 }; static const unsigned char dsa_q[] = { 0xa3, 0xbf, 0xd9, 0xab, 0x78, 0x84, 0x79, 0x4e, 0x38, 0x34, 0x50, 0xd5, 0x89, 0x1d, 0xc1, 0x8b, 0x65, 0x15, 0x7b, 0xdc, 0xfc, 0xda, 0xc5, 0x15, 0x18, 0x90, 0x28, 0x67 }; static const unsigned char dsa_g[] = { 0x68, 0x19, 0x27, 0x88, 0x69, 0xc7, 0xfd, 0x3d, 0x2d, 0x7b, 0x77, 0xf7, 0x7e, 0x81, 0x50, 0xd9, 0xad, 0x43, 0x3b, 0xea, 0x3b, 0xa8, 0x5e, 0xfc, 0x80, 0x41, 0x5a, 0xa3, 0x54, 0x5f, 0x78, 0xf7, 0x22, 0x96, 0xf0, 0x6c, 0xb1, 0x9c, 0xed, 0xa0, 0x6c, 0x94, 0xb0, 0x55, 0x1c, 0xfe, 0x6e, 0x6f, 0x86, 0x3e, 0x31, 0xd1, 0xde, 0x6e, 0xed, 0x7d, 0xab, 0x8b, 0x0c, 0x9d, 0xf2, 0x31, 0xe0, 0x84, 0x34, 0xd1, 0x18, 0x4f, 0x91, 0xd0, 0x33, 0x69, 0x6b, 0xb3, 0x82, 0xf8, 0x45, 0x5e, 0x98, 0x88, 0xf5, 0xd3, 0x1d, 0x47, 0x84, 0xec, 0x40, 0x12, 0x02, 0x46, 0xf4, 0xbe, 0xa6, 0x17, 0x94, 0xbb, 0xa5, 0x86, 0x6f, 0x09, 0x74, 0x64, 0x63, 0xbd, 0xf8, 0xe9, 0xe1, 0x08, 0xcd, 0x95, 0x29, 0xc3, 0xd0, 0xf6, 0xdf, 0x80, 0x31, 0x6e, 0x2e, 0x70, 0xaa, 0xeb, 0x1b, 0x26, 0xcd, 0xb8, 0xad, 0x97, 0xbc, 0x3d, 0x28, 0x7e, 0x0b, 0x8d, 0x61, 0x6c, 0x42, 0xe6, 0x5b, 0x87, 0xdb, 0x20, 0xde, 0xb7, 0x00, 0x5b, 0xc4, 0x16, 0x74, 0x7a, 0x64, 0x70, 0x14, 0x7a, 0x68, 0xa7, 0x82, 0x03, 0x88, 0xeb, 0xf4, 0x4d, 0x52, 0xe0, 0x62, 0x8a, 0xf9, 0xcf, 0x1b, 0x71, 0x66, 0xd0, 0x34, 0x65, 0xf3, 0x5a, 0xcc, 0x31, 0xb6, 0x11, 0x0c, 0x43, 0xda, 0xbc, 0x7c, 0x5d, 0x59, 0x1e, 0x67, 0x1e, 0xaf, 0x7c, 0x25, 0x2c, 0x1c, 0x14, 0x53, 0x36, 0xa1, 0xa4, 0xdd, 0xf1, 0x32, 0x44, 0xd5, 0x5e, 0x83, 0x56, 0x80, 0xca, 0xb2, 0x53, 0x3b, 0x82, 0xdf, 0x2e, 0xfe, 0x55, 0xec, 0x18, 0xc1, 0xe6, 0xcd, 0x00, 0x7b, 0xb0, 0x89, 0x75, 0x8b, 0xb1, 0x7c, 0x2c, 0xbe, 0x14, 0x44, 0x1b, 0xd0, 0x93, 0xae, 0x66, 0xe5, 0x97, 0x6d, 0x53, 0x73, 0x3f, 0x4f, 0xa3, 0x26, 0x97, 0x01, 0xd3, 0x1d, 0x23, 0xd4, 0x67 }; static const unsigned char dsa_pub[] = { 0xa0, 0x12, 0xb3, 0xb1, 0x70, 0xb3, 0x07, 0x22, 0x79, 0x57, 0xb7, 0xca, 0x20, 0x61, 0xa8, 0x16, 0xac, 0x7a, 0x2b, 0x3d, 0x9a, 0xe9, 0x95, 0xa5, 0x11, 0x9c, 0x38, 0x5b, 0x60, 0x3b, 0xf6, 0xf6, 0xc5, 0xde, 0x4d, 0xc5, 0xec, 0xb5, 0xdf, 0xa4, 0xa4, 0x1c, 0x68, 0x66, 0x2e, 0xb2, 0x5b, 0x63, 0x8b, 0x7e, 0x26, 0x20, 0xba, 0x89, 0x8d, 0x07, 0xda, 0x6c, 0x49, 0x91, 0xe7, 0x6c, 0xc0, 0xec, 0xd1, 0xad, 0x34, 0x21, 0x07, 0x70, 0x67, 0xe4, 0x7c, 0x18, 0xf5, 0x8a, 0x92, 0xa7, 0x2a, 0xd4, 0x31, 0x99, 0xec, 0xb7, 0xbd, 0x84, 0xe7, 0xd3, 0xaf, 0xb9, 0x01, 0x9f, 0x0e, 0x9d, 0xd0, 0xfb, 0xaa, 0x48, 0x73, 0x00, 0xb1, 0x30, 0x81, 0xe3, 0x3c, 0x90, 0x28, 0x76, 0x43, 0x6f, 0x7b, 0x03, 0xc3, 0x45, 0x52, 0x84, 0x81, 0xd3, 0x62, 0x81, 0x5e, 0x24, 0xfe, 0x59, 0xda, 0xc5, 0xac, 0x34, 0x66, 0x0d, 0x4c, 0x8a, 0x76, 0xcb, 0x99, 0xa7, 0xc7, 0xde, 0x93, 0xeb, 0x95, 0x6c, 0xd6, 0xbc, 0x88, 0xe5, 0x8d, 0x90, 0x10, 0x34, 0x94, 0x4a, 0x09, 0x4b, 0x01, 0x80, 0x3a, 0x43, 0xc6, 0x72, 0xb9, 0x68, 0x8c, 0x0e, 0x01, 0xd8, 0xf4, 0xfc, 0x91, 0xc6, 0x2a, 0x3f, 0x88, 0x02, 0x1f, 0x7b, 0xd6, 0xa6, 0x51, 0xb1, 0xa8, 0x8f, 0x43, 0xaa, 0x4e, 0xf2, 0x76, 0x53, 0xd1, 0x2b, 0xf8, 0xb7, 0x09, 0x9f, 0xdf, 0x6b, 0x46, 0x10, 0x82, 0xf8, 0xe9, 0x39, 0x10, 0x7b, 0xfd, 0x2f, 0x72, 0x10, 0x08, 0x7d, 0x32, 0x6c, 0x37, 0x52, 0x00, 0xf1, 0xf5, 0x1e, 0x7e, 0x74, 0xa3, 0x41, 0x31, 0x90, 0x1b, 0xcd, 0x08, 0x63, 0x52, 0x1f, 0xf8, 0xd6, 0x76, 0xc4, 0x85, 0x81, 0x86, 0x87, 0x36, 0xc5, 0xe5, 0x1b, 0x16, 0xa4, 0xe3, 0x92, 0x15, 0xea, 0x0b, 0x17, 0xc4, 0x73, 0x59, 0x74, 0xc5, 0x16 }; static const unsigned char dsa_expected_sig[] = { 0x30, 0x3c, 0x02, 0x1c, 0x69, 0xc6, 0xd6, 0x9e, 0x2b, 0x91, 0xea, 0x72, 0xb3, 0x8b, 0x7c, 0x57, 0x48, 0x75, 0xb7, 0x65, 0xc0, 0xb4, 0xf7, 0xbb, 0x08, 0xa4, 0x95, 0x77, 0xfc, 0xa7, 0xed, 0x31, 0x02, 0x1c, 0x4c, 0x2c, 0xff, 0xc6, 0x55, 0xeb, 0x8f, 0xa7, 0x4f, 0x27, 0xd8, 0xec, 0xfd, 0x62, 0x73, 0xf2, 0xd1, 0x55, 0xa5, 0xf0, 0x41, 0x68, 0x34, 0x8d, 0x9e, 0x88, 0x08, 0x06 }; static const ST_KAT_PARAM dsa_key[] = { ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_FFC_P, dsa_p), ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_FFC_Q, dsa_q), ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_FFC_G, dsa_g), ST_KAT_PARAM_BIGNUM(OSSL_PKEY_PARAM_PUB_KEY, dsa_pub), ST_KAT_PARAM_END() }; #endif /* OPENSSL_NO_DSA */ #ifndef OPENSSL_NO_ML_DSA static const unsigned char ml_dsa_65_pub_key[] = { 0x3b, 0x5c, 0xb0, 0x79, 0xd2, 0xce, 0x76, 0x2b, 0x3b, 0x95, 0x7c, 0x26, 0x69, 0x8f, 0xe7, 0x01, 0xb9, 0x6b, 0x50, 0xa3, 0x2c, 0x73, 0x67, 0xcf, 0x9e, 0xf4, 0xb8, 0x7d, 0xe3, 0xaf, 0x27, 0x77, 0xc6, 0x7c, 0x34, 0xb7, 0x30, 0x4d, 0x01, 0xa4, 0xaa, 0xce, 0x16, 0x7c, 0x13, 0x2b, 0x30, 0x6c, 0x88, 0x31, 0xe4, 0x90, 0xf5, 0xc2, 0x80, 0xf5, 0xe8, 0xb9, 0x2d, 0x7a, 0x83, 0x17, 0xfc, 0xbb, 0x13, 0x6f, 0x18, 0x75, 0x5b, 0x40, 0x39, 0x2d, 0x47, 0x56, 0x15, 0xc7, 0x1c, 0x6e, 0x9a, 0x95, 0x7b, 0x6b, 0x77, 0x9f, 0x86, 0x38, 0x0e, 0xee, 0xc0, 0x82, 0x6c, 0x3c, 0xae, 0xc0, 0xcf, 0x5a, 0x85, 0x49, 0xb1, 0x0c, 0x2d, 0x0e, 0x51, 0x73, 0xf0, 0xe7, 0xad, 0x3b, 0xa7, 0x3f, 0xf5, 0x75, 0xb9, 0xb4, 0x63, 0xb9, 0xf0, 0x0a, 0xf4, 0x29, 0x90, 0x20, 0x72, 0x46, 0x8c, 0x7a, 0xaa, 0x86, 0xb7, 0x4e, 0xa7, 0x65, 0x23, 0xef, 0xec, 0x46, 0x67, 0x02, 0xf1, 0xbb, 0x88, 0xc7, 0xa4, 0xfc, 0x66, 0x52, 0x07, 0x67, 0x68, 0xa2, 0x72, 0xe8, 0x8a, 0x53, 0x97, 0xe6, 0x89, 0x96, 0x95, 0x9e, 0x6a, 0xe9, 0xa4, 0x7d, 0x19, 0x19, 0x5f, 0xb4, 0x77, 0x52, 0x17, 0xd6, 0xf2, 0xea, 0x7f, 0xfc, 0x5c, 0xd5, 0x18, 0x16, 0x8c, 0xc2, 0x2e, 0x31, 0xf8, 0x98, 0x4b, 0x72, 0xa1, 0x80, 0xb6, 0x5c, 0x32, 0x19, 0x2f, 0xe0, 0xae, 0x74, 0xf4, 0xc4, 0x0a, 0xe0, 0x54, 0x52, 0x46, 0x9e, 0xf3, 0xb9, 0x6c, 0x56, 0xd1, 0xe8, 0x99, 0x29, 0x39, 0x95, 0x30, 0xa2, 0x6a, 0xc6, 0x32, 0x8a, 0xa6, 0x02, 0x6a, 0x39, 0x2e, 0x13, 0x20, 0xbc, 0xf8, 0x7a, 0x09, 0xb6, 0xa7, 0xd1, 0x39, 0xa5, 0x12, 0x02, 0x81, 0x47, 0x8c, 0xc0, 0x1e, 0xfd, 0xf3, 0x28, 0xe5, 0x34, 0xec, 0xf0, 0xfc, 0x3f, 0x22, 0x16, 0xd2, 0xfe, 0xf0, 0xca, 0xaa, 0x6f, 0x82, 0xdd, 0xd6, 0x83, 0xaf, 0xf9, 0xeb, 0x1d, 0xa8, 0x45, 0x39, 0x63, 0xa5, 0xde, 0xee, 0x7d, 0x91, 0xe3, 0xaa, 0xcc, 0x07, 0x92, 0xce, 0x50, 0xfd, 0xe4, 0xa8, 0x50, 0x91, 0xd5, 0xec, 0xc1, 0x1b, 0x57, 0x92, 0x37, 0x68, 0xf8, 0xd6, 0x32, 0x55, 0xba, 0x65, 0xae, 0xb6, 0xc3, 0x9f, 0x6c, 0x18, 0xc5, 0x12, 0x17, 0x9a, 0x04, 0x29, 0xab, 0x14, 0x94, 0xbb, 0x13, 0x79, 0x5e, 0xb9, 0xf0, 0x62, 0x03, 0xe0, 0xa4, 0x91, 0xba, 0x81, 0x4b, 0xaa, 0xf1, 0x82, 0x47, 0x83, 0x43, 0x5f, 0x1e, 0x2d, 0x48, 0x40, 0x56, 0xe4, 0x29, 0x79, 0x01, 0xd5, 0x89, 0xaf, 0xa4, 0x56, 0x9e, 0x38, 0x62, 0x03, 0xa0, 0xe7, 0x9f, 0x08, 0x1f, 0xca, 0xd4, 0x31, 0x48, 0xf6, 0x68, 0xe0, 0xcc, 0x28, 0xff, 0x06, 0x97, 0x67, 0x4b, 0x70, 0x78, 0xa0, 0x2a, 0xf9, 0x46, 0x80, 0x6d, 0x37, 0xfb, 0xb3, 0x17, 0x12, 0xf0, 0x95, 0xc7, 0xee, 0x31, 0x54, 0x75, 0xdf, 0x2a, 0xa8, 0x7d, 0xff, 0x97, 0xbb, 0x45, 0x49, 0x55, 0xd5, 0xac, 0x9c, 0x6f, 0x0e, 0xc3, 0x94, 0x96, 0xc4, 0x9e, 0x9c, 0x45, 0x31, 0xcb, 0x23, 0xed, 0x21, 0xf1, 0xfe, 0xe9, 0xf9, 0x8c, 0xb6, 0x8e, 0x72, 0x6e, 0xdd, 0x37, 0x1c, 0xc7, 0xd6, 0x6b, 0x36, 0x35, 0xa0, 0x67, 0x54, 0x00, 0x65, 0x2c, 0xc8, 0xa4, 0xa0, 0x9e, 0x72, 0xd7, 0xc9, 0x3c, 0x8c, 0x78, 0x1a, 0xf8, 0x80, 0xad, 0xc4, 0x99, 0xc7, 0x35, 0x4e, 0x89, 0x3b, 0x4f, 0xa6, 0x9d, 0x5d, 0xce, 0x66, 0x4d, 0x82, 0xef, 0x47, 0x73, 0xa8, 0xc5, 0x14, 0x20, 0xdd, 0x57, 0x92, 0x10, 0x95, 0x8a, 0xe1, 0xac, 0x82, 0xec, 0x39, 0xe7, 0x2c, 0xa6, 0xfd, 0x50, 0x68, 0x0c, 0x3e, 0xcf, 0xbc, 0xc5, 0x12, 0xfe, 0x30, 0xc8, 0xb7, 0xb4, 0x84, 0xd8, 0x1d, 0x67, 0x54, 0x9d, 0x20, 0x49, 0xa5, 0xfd, 0xf9, 0x18, 0xef, 0xc2, 0xd2, 0xcd, 0xb7, 0x54, 0x2b, 0x31, 0x12, 0xf9, 0xaa, 0x8e, 0x0a, 0x29, 0x0c, 0x37, 0xd2, 0x7c, 0xcd, 0xc5, 0x0b, 0x98, 0x25, 0x97, 0x0b, 0x5a, 0xf7, 0x07, 0x91, 0x98, 0xd1, 0x42, 0xdf, 0xc4, 0xf9, 0x42, 0x97, 0xda, 0x20, 0xf4, 0x88, 0xe1, 0x6b, 0xd4, 0x85, 0xf5, 0x1d, 0xca, 0x2a, 0xba, 0x30, 0xc5, 0xdf, 0x9d, 0x4d, 0xb8, 0xb0, 0x30, 0x54, 0x61, 0xcf, 0x91, 0x6f, 0x90, 0xa5, 0x25, 0x05, 0x9b, 0x2b, 0x3e, 0x13, 0xcd, 0xcd, 0x40, 0x59, 0x7c, 0x92, 0x9b, 0x51, 0x81, 0x0d, 0x58, 0x32, 0x0a, 0x43, 0xbd, 0x01, 0xb4, 0xb8, 0x0b, 0xd5, 0xee, 0x0d, 0x67, 0x70, 0x59, 0xd7, 0x47, 0x4f, 0xe5, 0x84, 0x07, 0x75, 0x3e, 0x54, 0xfb, 0x5d, 0xd1, 0x3f, 0x72, 0x6e, 0xae, 0xf9, 0x4b, 0x7b, 0x57, 0xe0, 0xde, 0x8b, 0x8b, 0x12, 0x1b, 0x10, 0x3b, 0x5e, 0x17, 0xd1, 0x72, 0x18, 0x3d, 0xff, 0xc6, 0x83, 0xa5, 0xaf, 0xf9, 0x30, 0xae, 0xb7, 0x47, 0x46, 0x5d, 0xac, 0xba, 0x35, 0x04, 0x35, 0x0b, 0x42, 0x48, 0x7c, 0xa1, 0x00, 0x1a, 0xea, 0xea, 0x5f, 0x93, 0x2b, 0xb7, 0xe5, 0x8f, 0x91, 0x3c, 0x00, 0x98, 0x51, 0x40, 0xee, 0x11, 0x50, 0x70, 0x40, 0xe4, 0x28, 0xd4, 0x79, 0x2d, 0xcd, 0x82, 0xaf, 0x3f, 0xb2, 0xfc, 0x96, 0x8d, 0xbe, 0x79, 0xa3, 0xcd, 0xac, 0x35, 0x4b, 0x5e, 0xb4, 0x81, 0x0e, 0x6a, 0xde, 0x1f, 0x7e, 0xb0, 0x37, 0x3e, 0xdc, 0xe0, 0x21, 0xcc, 0x9f, 0x90, 0x26, 0xb6, 0x8a, 0x1d, 0xb3, 0x1e, 0xec, 0x7a, 0x88, 0x28, 0x95, 0xe2, 0xc2, 0x1d, 0x07, 0xb1, 0xfa, 0xc6, 0x21, 0x1b, 0x5e, 0x54, 0x7b, 0x37, 0x0e, 0x63, 0xff, 0xdd, 0x70, 0xf9, 0xea, 0x2f, 0x2d, 0x98, 0xe1, 0xbe, 0x37, 0xd0, 0x1f, 0x45, 0x5a, 0x63, 0xad, 0x44, 0xbc, 0x5f, 0xc6, 0x23, 0x8a, 0xac, 0x12, 0x71, 0xd5, 0xa2, 0x8b, 0xfc, 0x97, 0xbb, 0x00, 0x4b, 0xd7, 0x09, 0xa6, 0xaf, 0x40, 0x08, 0x6c, 0x8d, 0x10, 0x4a, 0x01, 0x34, 0xc1, 0x2c, 0x92, 0x30, 0x0a, 0x85, 0x8f, 0x3f, 0x08, 0xdd, 0xff, 0x9c, 0x10, 0xd1, 0x03, 0x03, 0x84, 0x1f, 0xf8, 0x4e, 0xf2, 0xe3, 0xd1, 0xd3, 0xb9, 0xdf, 0xfc, 0x97, 0x1c, 0xcf, 0x8a, 0x29, 0xe6, 0x59, 0x04, 0xe2, 0x87, 0x27, 0xbb, 0xb9, 0x96, 0xd0, 0x20, 0x2e, 0x91, 0x48, 0xaa, 0xbf, 0x53, 0x4a, 0x34, 0xb5, 0x0e, 0x11, 0xce, 0xf8, 0x65, 0xa6, 0x0d, 0x45, 0xda, 0xbf, 0x6a, 0xfb, 0x81, 0xe4, 0x7c, 0x8c, 0xa0, 0x4b, 0x00, 0x1b, 0xd7, 0x73, 0x61, 0x80, 0xc0, 0x6b, 0x60, 0xde, 0xf3, 0x32, 0xae, 0x62, 0x35, 0x66, 0xdd, 0xde, 0x53, 0x61, 0x86, 0xe9, 0x44, 0xf3, 0x01, 0x7b, 0xaa, 0xe7, 0x31, 0xd4, 0x5b, 0x06, 0x52, 0x0f, 0xf4, 0x90, 0x5c, 0x82, 0x3e, 0x12, 0x28, 0x88, 0x7f, 0xfc, 0xb8, 0xee, 0x17, 0x34, 0x4e, 0xc3, 0x2a, 0xfb, 0x84, 0x1b, 0x0f, 0xba, 0x51, 0x64, 0x96, 0x22, 0x0d, 0x88, 0x9b, 0xf2, 0x72, 0x04, 0x55, 0x44, 0x6a, 0x14, 0x2b, 0xa0, 0xc2, 0xbe, 0x9e, 0x7b, 0x48, 0x32, 0xa7, 0xf6, 0x11, 0xae, 0x60, 0xfb, 0xf8, 0x38, 0x67, 0x16, 0xdf, 0xdf, 0x46, 0x96, 0xd7, 0x6c, 0x39, 0xa2, 0xad, 0xf7, 0xb7, 0x78, 0x32, 0x2c, 0xba, 0xae, 0x33, 0x5a, 0x88, 0x4b, 0x40, 0x1f, 0x88, 0xcd, 0xe7, 0x8f, 0x50, 0x5e, 0xd8, 0x80, 0x82, 0x7b, 0x46, 0xc7, 0x07, 0x71, 0x4f, 0x3b, 0xca, 0x9d, 0x73, 0x7c, 0xdb, 0xeb, 0x4c, 0x37, 0xdd, 0xb4, 0xb8, 0x61, 0xf3, 0xdf, 0xb2, 0xb5, 0x34, 0x27, 0xec, 0xeb, 0xba, 0xcc, 0xdc, 0xe9, 0xde, 0x47, 0x2e, 0xe9, 0x3b, 0xa1, 0x36, 0xf1, 0x66, 0xdf, 0xc8, 0x70, 0x7f, 0x39, 0x82, 0xb3, 0x8c, 0x47, 0x9a, 0x45, 0x59, 0x2e, 0x30, 0x9b, 0xaf, 0x7c, 0xad, 0x43, 0x38, 0x6e, 0x05, 0x7d, 0x8b, 0xac, 0x5f, 0x70, 0x63, 0xeb, 0x85, 0xee, 0xab, 0xa4, 0x57, 0x1d, 0x63, 0xac, 0x48, 0x45, 0x74, 0xca, 0x0c, 0xa8, 0x65, 0x05, 0x1a, 0x47, 0xa1, 0x2f, 0x4b, 0x96, 0x26, 0x9e, 0xee, 0xec, 0x37, 0x57, 0xbf, 0xa0, 0x2b, 0x75, 0xf5, 0x9b, 0xb5, 0x1d, 0x12, 0x8a, 0x61, 0x9c, 0x8d, 0x2a, 0x7e, 0xee, 0x05, 0x2b, 0x85, 0x7c, 0x6f, 0x34, 0xc4, 0xcd, 0xd5, 0xd0, 0xac, 0xf9, 0x79, 0x24, 0xe7, 0x0f, 0x41, 0x95, 0xe2, 0x9a, 0x22, 0x32, 0xa5, 0x98, 0x2e, 0x82, 0xc0, 0x07, 0xf4, 0x74, 0x68, 0x00, 0xf9, 0x35, 0x5e, 0x12, 0xfe, 0xa2, 0x0e, 0x15, 0x96, 0x83, 0x84, 0x31, 0xc4, 0x25, 0xda, 0x7a, 0xec, 0x07, 0x15, 0xe4, 0x7d, 0xc5, 0xf5, 0xe1, 0xc5, 0xba, 0x9a, 0x59, 0x76, 0xae, 0x4e, 0x54, 0x27, 0x5e, 0xa9, 0x0d, 0xa0, 0xd3, 0xcd, 0x99, 0x39, 0x76, 0x6d, 0x58, 0xdf, 0x8a, 0xa9, 0x9e, 0x21, 0x22, 0x48, 0x7c, 0x0c, 0x13, 0xfa, 0x86, 0x63, 0x74, 0x92, 0xf4, 0xe5, 0x5d, 0xbf, 0xe4, 0x2d, 0xd7, 0xa1, 0xe3, 0x0f, 0xc6, 0x3e, 0x82, 0xa0, 0xcc, 0xfa, 0x38, 0x55, 0x36, 0x9b, 0x22, 0xd0, 0xb8, 0x7f, 0x3f, 0x0f, 0x35, 0x01, 0xf9, 0x6f, 0xa6, 0x51, 0x77, 0x21, 0xb7, 0x7a, 0x81, 0xca, 0x83, 0x6b, 0xec, 0xa7, 0x71, 0x12, 0x6d, 0x22, 0x78, 0xb1, 0xc8, 0x37, 0xda, 0x1d, 0xd1, 0x9c, 0xa5, 0x6c, 0xfa, 0xd3, 0x4b, 0x87, 0x39, 0x6f, 0x59, 0xe1, 0xec, 0x4a, 0xe5, 0x0e, 0x72, 0x2b, 0x31, 0x18, 0xd9, 0x54, 0x6a, 0x4c, 0xc3, 0xe0, 0x58, 0x3b, 0xd8, 0xe8, 0x65, 0xc1, 0x98, 0xed, 0x64, 0x7b, 0xb1, 0xee, 0xa9, 0x54, 0x95, 0x37, 0x98, 0x68, 0xca, 0x83, 0xef, 0xc5, 0x1b, 0x23, 0x71, 0x5c, 0x1a, 0xe6, 0xc0, 0xce, 0x2e, 0x16, 0x59, 0x79, 0xf4, 0x94, 0x43, 0xd8, 0xb1, 0x2e, 0xe3, 0xb9, 0xa0, 0x95, 0x80, 0x66, 0xdd, 0x1d, 0xdd, 0x0d, 0x78, 0x9d, 0xc3, 0x91, 0x60, 0x16, 0x8b, 0xc5, 0x39, 0xad, 0xdb, 0xa3, 0xc1, 0xd2, 0x8d, 0xa0, 0x78, 0x75, 0x68, 0xa6, 0xb9, 0x15, 0x57, 0x0b, 0x06, 0x64, 0x55, 0xd7, 0x07, 0x53, 0xf9, 0x8b, 0xd9, 0x97, 0x46, 0xca, 0x04, 0x95, 0xd4, 0x3c, 0xd3, 0x8f, 0x0a, 0x53, 0x27, 0xe6, 0xd4, 0xb4, 0x7b, 0x70, 0x12, 0x12, 0xc5, 0x14, 0xa0, 0x53, 0xe5, 0xd4, 0x30, 0xaa, 0xcc, 0xec, 0x03, 0x0a, 0x36, 0x21, 0x9f, 0x81, 0x16, 0x6d, 0x1d, 0x53, 0x6e, 0x08, 0xae, 0xf7, 0x05, 0xd9, 0x73, 0x5a, 0x45, 0x3a, 0x52, 0x3e, 0xeb, 0x67, 0x49, 0xe1, 0x1a, 0x8a, 0x4c, 0xd9, 0x83, 0x64, 0xd8, 0x16, 0x37, 0x1c, 0x6b, 0x1c, 0x0d, 0x8f, 0x6a, 0xbf, 0x21, 0xf1, 0x4f, 0x4c, 0x55, 0x6f, 0xe0, 0x5c, 0xa7, 0xb1, 0x7b, 0x57, 0xa9, 0xa2, 0xb4, 0x9d, 0x53, 0x7f, 0x0f, 0xb0, 0x21, 0x95, 0x70, 0x3a, 0x0d, 0xa2, 0xc1, 0x52, 0x26, 0xad, 0xa7, 0x48, 0x66, 0x2a, 0xfc, 0xaa, 0xaf, 0x25, 0x02, 0x58, 0x80, 0xbe, 0xe7, 0xe4, 0x2a, 0x50, 0xe5, 0x46, 0x13, 0xaa, 0x57, 0x0e, 0x6e, 0xee, 0xa9, 0x9e, 0x19, 0xa3, 0x92, 0x8e, 0xc6, 0x3d, 0x76, 0xbb, 0x12, 0xe2, 0x78, 0x77, 0x99, 0x6a, 0x06, 0xc4, 0x45, 0x1f, 0x45, 0xe1, 0xf6, 0x65, 0x1f, 0xba, 0xe4, 0xf6, 0xca, 0xa9, 0x62, 0xa9, 0x2c, 0x3a, 0x2d, 0x8d, 0x34, 0xe2, 0x32, 0x6e, 0x4a, 0x52, 0x9f, 0x3d, 0xcf, 0xab, 0xe8, 0x63, 0x66, 0x3f, 0x06, 0xa3, 0xaa, 0xd5, 0xcb, 0x5d, 0x41, 0xb8, 0xe7, 0x0a, 0x6b, 0x45, 0x90, 0x3a, 0xf0, 0xe5, 0x7f, 0x7e, 0xde, 0x68, 0x20, 0x5e, 0x5a, 0x31, 0x3a, 0x5c, 0x25, 0xb3, 0x82, 0xc7, 0x1e, 0x7d, 0x4d, 0xd0, 0x23, 0x9f, 0x22, 0x1a, 0x54, 0x0b, 0xe4, 0x3c, 0x1c, 0xc5, 0x24, 0x39, 0x4d, 0x96, 0x90, 0xce, 0xc9, 0x3a, 0x07, 0x45, 0x01, 0x9e, 0xb6, 0x55, 0x1b, 0xdc, 0xe0, 0x3b, 0xe8, 0x92, 0x57, 0x43, 0x12, 0x9b, 0x11, 0x3f, 0x81, 0x5a, 0xca, 0xc5, 0x85, 0x39, 0x25, 0x6d, 0xe4, 0x30, 0xef, 0x83, 0x21, 0xed, 0x9c, 0xb3, 0xcf, 0x10, 0xe6, 0xa1, 0x46, 0x10, 0x9a, 0x7b, 0xaf, 0x5f, 0x75, 0x99, 0x62, 0xc1, 0xf4, 0x2c, 0x28, 0x0a, 0x8a, 0xc7, 0xd2, 0xb4, 0x75, 0xb9, 0x66, 0x70, 0x9a, 0xaf, 0xe3, 0xf1, 0x2f, 0xf2, 0xb0, 0x59, 0x9c, 0x1e, 0x1a, 0xbd, 0xa9, 0x15, 0x55, 0x95, 0x4c, 0x5b, 0x78, 0x0b, 0x2c, 0x00, 0xbb, 0xf9, 0x8b, 0xeb, 0x72, 0x4f, 0xfb, 0xa4, 0x3a, 0xa0, 0x04, 0x45, 0x32, 0x02, 0x6c, 0x16, 0x52, 0x3f, 0x4a, 0x0a, 0x77, 0x64, 0xf4, 0x74, 0xed, 0x60, 0x6b, 0x5e, 0x43, 0xa7, 0xe3, 0x84, 0x7e, 0xda, 0xf0, 0xb1, 0x9e, 0x6d, 0x90, 0x9c, 0x32, 0xae, 0xba, 0x7c, 0xfb, 0x72, 0x22, 0x27, 0x9c, 0xe1, 0x85, 0xe1, 0xf6, 0x22, 0x4c, 0x3c, 0x4a, 0xd6, 0xed, 0x4c, 0xa7, 0x79, 0x59, 0xb5, 0x5b, 0x91, 0x65, 0x3f, 0x93, 0x97, 0x8d, 0xd7, 0xd0, 0xab, 0x17, 0x2f, 0x13, 0x74, 0x53, 0x69, 0x74, 0xf8, 0x6b, 0x39, 0x5c, 0x64, 0x5b, 0x3d, 0x75, 0xca, 0x85, 0x0e, 0xda, 0x0f, 0x01, 0x34, 0xa3, 0x67, 0x8e, 0x26, 0x6f, 0x26, 0x3c, 0xd0, 0xd9, 0xae, 0xe8, 0x52, 0x13, 0x7f, 0xf8, 0x69, 0x62, 0xfc, 0x9a, 0xc0, 0x0c, 0x66, 0x2e, 0x57, 0x21, 0x75, 0xb0, 0xb3, 0x8c, 0xf6, 0x97, 0x44, 0x46, 0x65, 0x15, 0x79, 0xd5, 0x6b, 0x68, 0x96, 0x47, 0xc1, 0xba, 0x75, 0x46, 0x87, 0x76, 0x7d, 0x2d, 0xac, 0xf3, 0x16, 0xae, 0xfb, 0x7e, 0x41, 0xe4, 0xae, 0x15, 0xc2, 0x51, 0x69, 0x71, 0x0b, 0x63, 0x20, 0x6a, 0xbd, 0xad, 0xce, 0x2a, 0x94, 0xac, 0xcf, 0x15, 0x4e, 0xdc, 0x8e, 0x2a, 0x48, 0xed, 0xb3, 0x48, 0x95, 0xf4, 0x41, 0xf3, 0x52, 0xef, 0x62, 0x90, 0x10, 0x30, 0x42, 0xec, 0xf9, 0x30, 0x25, 0xc3, 0xc5, 0x47, 0x76, 0xb5, 0x37, 0xeb, 0x9e, 0x87, 0xbe, 0x5c, 0x24, 0xa5, 0x34, 0xdd, 0x92, 0xa1, 0x20, 0x7d, 0xa7, 0x94, 0xa2, 0x67, 0x26, 0x70, 0xfe, 0xc9, 0x3f, 0x21, 0xd1, 0xc2, 0x5a, 0xb1, 0xaa, 0xac, 0x14, 0x1a, 0xe4, 0xdb, 0x71, 0x7e, 0x9c, 0xc2, 0x52, 0x59, 0xc9, 0x58, 0xca, 0x88, 0x71, 0x4f, 0x90, 0xb1, 0xbb, 0xac, 0x80, 0x53, 0x21, 0xfb, 0xff, 0xfd, 0x1e, 0x9f, 0xc0, 0x59, 0x8d, 0x80, 0x8e, 0x85, 0xa9, 0x3b, 0xd3, 0x20, 0x3b, 0x91, 0x16, 0x49, 0xb2, 0x2a, 0xa4, 0xe2, 0x30, 0xb2, 0x76, 0xf6, 0x92, 0x71, 0x37, 0x1b }; static const unsigned char ml_dsa_65_priv_key[] = { 0x3b, 0x5c, 0xb0, 0x79, 0xd2, 0xce, 0x76, 0x2b, 0x3b, 0x95, 0x7c, 0x26, 0x69, 0x8f, 0xe7, 0x01, 0xb9, 0x6b, 0x50, 0xa3, 0x2c, 0x73, 0x67, 0xcf, 0x9e, 0xf4, 0xb8, 0x7d, 0xe3, 0xaf, 0x27, 0x77, 0x39, 0x3e, 0xac, 0x91, 0xa1, 0xfb, 0xed, 0xf7, 0x52, 0x0a, 0x4f, 0x77, 0xb2, 0x57, 0x7c, 0x65, 0x05, 0x6e, 0x76, 0x3d, 0x28, 0xf4, 0x3a, 0x88, 0x49, 0x33, 0x7d, 0x30, 0x17, 0x21, 0x5a, 0xc0, 0x4b, 0x03, 0x74, 0x65, 0x6d, 0xbb, 0xfe, 0x8e, 0x0b, 0x8b, 0xb4, 0x42, 0xce, 0xc1, 0xdd, 0x11, 0xb1, 0x8f, 0x31, 0x06, 0x0b, 0xeb, 0xdf, 0xb3, 0x11, 0x12, 0x19, 0x22, 0x34, 0xd7, 0xaa, 0xf2, 0x17, 0xf0, 0x2e, 0x22, 0xef, 0x68, 0x0c, 0x8f, 0xc7, 0x42, 0x0b, 0xd6, 0x88, 0xd8, 0x3b, 0xa7, 0x22, 0xc5, 0x4e, 0x1a, 0xf2, 0x60, 0x85, 0x24, 0x75, 0x85, 0x49, 0x17, 0x1b, 0xd4, 0x69, 0xd8, 0x50, 0x68, 0x36, 0x83, 0x51, 0x12, 0x40, 0x24, 0x06, 0x04, 0x07, 0x47, 0x28, 0x62, 0x86, 0x26, 0x12, 0x24, 0x40, 0x83, 0x65, 0x44, 0x10, 0x62, 0x78, 0x58, 0x14, 0x67, 0x20, 0x20, 0x60, 0x53, 0x28, 0x73, 0x53, 0x34, 0x82, 0x18, 0x42, 0x43, 0x78, 0x67, 0x65, 0x28, 0x12, 0x65, 0x71, 0x17, 0x33, 0x06, 0x10, 0x51, 0x38, 0x07, 0x61, 0x42, 0x72, 0x60, 0x18, 0x52, 0x08, 0x74, 0x58, 0x72, 0x73, 0x06, 0x65, 0x20, 0x73, 0x20, 0x72, 0x42, 0x03, 0x86, 0x03, 0x03, 0x50, 0x85, 0x13, 0x43, 0x24, 0x53, 0x33, 0x82, 0x03, 0x36, 0x82, 0x73, 0x12, 0x15, 0x78, 0x54, 0x60, 0x64, 0x32, 0x60, 0x42, 0x47, 0x84, 0x73, 0x51, 0x60, 0x26, 0x03, 0x35, 0x58, 0x25, 0x28, 0x83, 0x55, 0x64, 0x06, 0x70, 0x82, 0x75, 0x54, 0x15, 0x70, 0x37, 0x61, 0x71, 0x38, 0x75, 0x36, 0x15, 0x70, 0x78, 0x17, 0x62, 0x01, 0x02, 0x13, 0x12, 0x46, 0x12, 0x56, 0x82, 0x51, 0x32, 0x16, 0x27, 0x00, 0x52, 0x41, 0x43, 0x86, 0x46, 0x00, 0x61, 0x24, 0x78, 0x33, 0x40, 0x13, 0x34, 0x47, 0x60, 0x18, 0x52, 0x18, 0x80, 0x01, 0x46, 0x53, 0x32, 0x74, 0x51, 0x72, 0x81, 0x21, 0x30, 0x50, 0x28, 0x28, 0x55, 0x53, 0x71, 0x03, 0x84, 0x87, 0x61, 0x88, 0x45, 0x35, 0x63, 0x72, 0x05, 0x37, 0x06, 0x37, 0x35, 0x36, 0x56, 0x71, 0x74, 0x53, 0x07, 0x61, 0x72, 0x65, 0x78, 0x57, 0x42, 0x41, 0x02, 0x06, 0x61, 0x06, 0x07, 0x66, 0x64, 0x50, 0x31, 0x24, 0x82, 0x43, 0x86, 0x31, 0x26, 0x76, 0x47, 0x45, 0x03, 0x66, 0x44, 0x00, 0x46, 0x04, 0x83, 0x03, 0x83, 0x81, 0x33, 0x08, 0x77, 0x57, 0x08, 0x40, 0x04, 0x22, 0x35, 0x17, 0x43, 0x63, 0x78, 0x44, 0x86, 0x24, 0x40, 0x17, 0x28, 0x67, 0x34, 0x18, 0x75, 0x72, 0x26, 0x83, 0x68, 0x63, 0x57, 0x47, 0x48, 0x84, 0x50, 0x16, 0x43, 0x17, 0x86, 0x16, 0x44, 0x17, 0x18, 0x70, 0x08, 0x51, 0x78, 0x70, 0x15, 0x58, 0x04, 0x10, 0x16, 0x03, 0x11, 0x04, 0x43, 0x70, 0x32, 0x77, 0x03, 0x23, 0x12, 0x74, 0x38, 0x26, 0x65, 0x66, 0x62, 0x04, 0x65, 0x75, 0x54, 0x00, 0x04, 0x01, 0x43, 0x15, 0x07, 0x47, 0x71, 0x12, 0x70, 0x41, 0x72, 0x34, 0x05, 0x26, 0x08, 0x11, 0x55, 0x22, 0x72, 0x83, 0x04, 0x66, 0x88, 0x80, 0x25, 0x17, 0x68, 0x60, 0x15, 0x37, 0x64, 0x14, 0x26, 0x64, 0x01, 0x45, 0x54, 0x51, 0x71, 0x38, 0x62, 0x65, 0x78, 0x43, 0x36, 0x21, 0x02, 0x27, 0x43, 0x47, 0x83, 0x86, 0x07, 0x05, 0x48, 0x56, 0x86, 0x31, 0x27, 0x66, 0x34, 0x35, 0x48, 0x81, 0x08, 0x38, 0x05, 0x10, 0x63, 0x32, 0x61, 0x73, 0x47, 0x30, 0x00, 0x82, 0x66, 0x54, 0x86, 0x81, 0x36, 0x06, 0x45, 0x01, 0x45, 0x87, 0x23, 0x36, 0x83, 0x00, 0x32, 0x81, 0x10, 0x06, 0x57, 0x76, 0x62, 0x40, 0x61, 0x77, 0x04, 0x17, 0x28, 0x70, 0x15, 0x07, 0x42, 0x18, 0x61, 0x70, 0x32, 0x42, 0x68, 0x12, 0x00, 0x18, 0x12, 0x72, 0x60, 0x50, 0x63, 0x28, 0x51, 0x87, 0x82, 0x03, 0x36, 0x63, 0x63, 0x25, 0x68, 0x54, 0x56, 0x16, 0x07, 0x58, 0x77, 0x83, 0x31, 0x85, 0x44, 0x43, 0x60, 0x22, 0x16, 0x01, 0x41, 0x23, 0x27, 0x11, 0x46, 0x60, 0x50, 0x84, 0x77, 0x18, 0x81, 0x31, 0x88, 0x47, 0x36, 0x51, 0x71, 0x56, 0x04, 0x25, 0x17, 0x44, 0x33, 0x78, 0x28, 0x72, 0x27, 0x87, 0x62, 0x78, 0x13, 0x83, 0x58, 0x12, 0x36, 0x22, 0x10, 0x25, 0x13, 0x50, 0x88, 0x10, 0x24, 0x78, 0x15, 0x12, 0x26, 0x43, 0x58, 0x02, 0x24, 0x17, 0x34, 0x75, 0x46, 0x15, 0x46, 0x42, 0x84, 0x52, 0x41, 0x75, 0x48, 0x77, 0x88, 0x33, 0x18, 0x18, 0x84, 0x31, 0x47, 0x22, 0x35, 0x64, 0x72, 0x35, 0x65, 0x73, 0x66, 0x88, 0x73, 0x12, 0x25, 0x51, 0x66, 0x57, 0x05, 0x23, 0x54, 0x74, 0x51, 0x76, 0x52, 0x24, 0x40, 0x64, 0x68, 0x28, 0x25, 0x65, 0x77, 0x12, 0x53, 0x35, 0x41, 0x85, 0x18, 0x25, 0x02, 0x25, 0x47, 0x22, 0x40, 0x37, 0x54, 0x03, 0x53, 0x26, 0x86, 0x50, 0x70, 0x25, 0x56, 0x27, 0x21, 0x11, 0x11, 0x72, 0x71, 0x54, 0x47, 0x63, 0x67, 0x22, 0x75, 0x61, 0x70, 0x05, 0x10, 0x03, 0x41, 0x48, 0x01, 0x47, 0x14, 0x70, 0x06, 0x64, 0x84, 0x02, 0x28, 0x06, 0x12, 0x45, 0x13, 0x56, 0x48, 0x65, 0x00, 0x74, 0x02, 0x10, 0x78, 0x42, 0x80, 0x02, 0x00, 0x16, 0x37, 0x43, 0x23, 0x56, 0x67, 0x20, 0x31, 0x86, 0x22, 0x20, 0x35, 0x51, 0x34, 0x58, 0x10, 0x87, 0x83, 0x43, 0x32, 0x85, 0x47, 0x72, 0x32, 0x28, 0x38, 0x47, 0x08, 0x73, 0x38, 0x20, 0x25, 0x14, 0x51, 0x66, 0x88, 0x85, 0x15, 0x88, 0x86, 0x86, 0x73, 0x46, 0x52, 0x81, 0x32, 0x70, 0x85, 0x31, 0x20, 0x80, 0x32, 0x42, 0x02, 0x33, 0x37, 0x68, 0x66, 0x70, 0x11, 0x27, 0x53, 0x75, 0x48, 0x65, 0x01, 0x25, 0x24, 0x53, 0x68, 0x15, 0x47, 0x25, 0x42, 0x01, 0x04, 0x47, 0x01, 0x58, 0x36, 0x17, 0x71, 0x44, 0x21, 0x63, 0x52, 0x61, 0x56, 0x16, 0x73, 0x17, 0x28, 0x08, 0x07, 0x76, 0x08, 0x42, 0x58, 0x11, 0x42, 0x18, 0x17, 0x18, 0x65, 0x63, 0x82, 0x45, 0x74, 0x35, 0x21, 0x01, 0x35, 0x26, 0x43, 0x56, 0x58, 0x56, 0x64, 0x81, 0x05, 0x52, 0x77, 0x31, 0x47, 0x27, 0x21, 0x82, 0x60, 0x05, 0x51, 0x04, 0x15, 0x34, 0x58, 0x00, 0x40, 0x83, 0x48, 0x21, 0x52, 0x04, 0x62, 0x23, 0x34, 0x64, 0x85, 0x77, 0x35, 0x81, 0x52, 0x35, 0x80, 0x24, 0x00, 0x03, 0x84, 0x32, 0x67, 0x76, 0x78, 0x32, 0x87, 0x50, 0x48, 0x00, 0x64, 0x45, 0x17, 0x05, 0x56, 0x84, 0x13, 0x02, 0x68, 0x42, 0x76, 0x81, 0x01, 0x41, 0x18, 0x56, 0x30, 0x58, 0x43, 0x72, 0x28, 0x71, 0x21, 0x87, 0x14, 0x64, 0x03, 0x31, 0x58, 0x04, 0x72, 0x11, 0x43, 0x50, 0x82, 0x57, 0x14, 0x38, 0x53, 0x36, 0x53, 0x44, 0x37, 0x36, 0x83, 0x47, 0x58, 0x58, 0x52, 0x08, 0x13, 0x33, 0x43, 0x40, 0x54, 0x26, 0x35, 0x28, 0x67, 0x02, 0x08, 0x18, 0x34, 0x67, 0x16, 0x17, 0x73, 0x13, 0x18, 0x02, 0x88, 0x32, 0x61, 0x60, 0x56, 0x38, 0x05, 0x87, 0x78, 0x52, 0x07, 0x53, 0x81, 0x06, 0x52, 0x88, 0x07, 0x35, 0x72, 0x72, 0x44, 0x28, 0x80, 0x86, 0x11, 0x70, 0x40, 0x41, 0x63, 0x80, 0x46, 0x15, 0x27, 0x62, 0x03, 0x45, 0x14, 0x33, 0x56, 0x07, 0x78, 0x43, 0x77, 0x62, 0x06, 0x54, 0x74, 0x43, 0x28, 0x72, 0x16, 0x40, 0x78, 0x62, 0x44, 0x34, 0x00, 0x25, 0x75, 0x74, 0x77, 0x37, 0x02, 0x48, 0x67, 0x18, 0x51, 0x67, 0x77, 0x68, 0x38, 0x72, 0x85, 0x34, 0x42, 0x54, 0x71, 0x61, 0x47, 0x42, 0x68, 0x55, 0x27, 0x26, 0x38, 0x85, 0x15, 0x15, 0x43, 0x14, 0x31, 0x24, 0x81, 0x26, 0x21, 0x17, 0x04, 0x00, 0x27, 0x21, 0x20, 0x72, 0x85, 0x77, 0x30, 0x17, 0x26, 0x48, 0x05, 0x48, 0x71, 0x41, 0x48, 0x27, 0x12, 0x43, 0x35, 0x26, 0x13, 0x00, 0x26, 0x67, 0x28, 0x25, 0x10, 0x05, 0x74, 0x06, 0x65, 0x16, 0x87, 0x17, 0x73, 0x37, 0x42, 0x20, 0x16, 0x44, 0x40, 0x68, 0x27, 0x23, 0x38, 0x28, 0x60, 0x52, 0x64, 0x40, 0x28, 0x46, 0x00, 0x00, 0x01, 0x43, 0x75, 0x15, 0x38, 0x12, 0x37, 0x11, 0x11, 0x87, 0x34, 0x43, 0x35, 0x76, 0x76, 0x50, 0x43, 0x05, 0x00, 0x27, 0x18, 0x70, 0x68, 0x14, 0x60, 0x26, 0x12, 0x75, 0x42, 0x06, 0x23, 0x56, 0x74, 0x74, 0x37, 0x17, 0x46, 0x20, 0x34, 0x72, 0x21, 0x33, 0x82, 0x73, 0x51, 0x64, 0x72, 0x02, 0x48, 0x82, 0x57, 0x53, 0x64, 0x74, 0x75, 0x28, 0x64, 0x02, 0x30, 0x22, 0x06, 0x73, 0x66, 0x72, 0x46, 0x56, 0x30, 0x11, 0x78, 0x32, 0x47, 0x52, 0x31, 0x02, 0x74, 0x13, 0x13, 0x41, 0x07, 0x27, 0x72, 0x07, 0x66, 0x63, 0x34, 0x84, 0x30, 0x66, 0x28, 0x72, 0x50, 0x62, 0x30, 0x52, 0x82, 0x37, 0x40, 0x78, 0x31, 0x35, 0x76, 0x83, 0x05, 0x02, 0x37, 0x25, 0x28, 0x85, 0x62, 0x10, 0x05, 0x38, 0x64, 0x87, 0x21, 0x76, 0x04, 0x51, 0x12, 0x45, 0x08, 0x50, 0x50, 0x75, 0x20, 0x86, 0x32, 0x43, 0x13, 0x47, 0x31, 0x24, 0x26, 0x57, 0x68, 0x64, 0x88, 0x17, 0x02, 0x70, 0x42, 0x72, 0x37, 0x32, 0x85, 0x87, 0x83, 0x86, 0x47, 0x70, 0x56, 0x22, 0x24, 0x53, 0x48, 0x85, 0x02, 0x48, 0x16, 0x01, 0x07, 0x57, 0x73, 0x76, 0x27, 0x43, 0x00, 0x88, 0x27, 0x38, 0x30, 0x86, 0x27, 0x18, 0x62, 0x05, 0x30, 0x37, 0x16, 0x80, 0x31, 0x72, 0x28, 0x37, 0x47, 0x57, 0x62, 0x55, 0x74, 0x07, 0x41, 0x72, 0x26, 0x58, 0x52, 0x68, 0x04, 0x80, 0x72, 0x77, 0x35, 0x43, 0x36, 0x47, 0x38, 0x76, 0x86, 0x60, 0x14, 0x22, 0x77, 0x61, 0x52, 0x74, 0x17, 0x64, 0x67, 0x85, 0x23, 0x58, 0x28, 0x23, 0x05, 0x33, 0x66, 0x64, 0x83, 0x71, 0x14, 0x03, 0x21, 0x70, 0x55, 0x43, 0x35, 0x58, 0x53, 0x78, 0x22, 0x00, 0x15, 0x00, 0x50, 0x16, 0x26, 0x84, 0x18, 0x51, 0x24, 0x01, 0x20, 0x51, 0x06, 0x74, 0x44, 0x83, 0x40, 0x55, 0x70, 0x28, 0x66, 0x11, 0x31, 0x02, 0x57, 0x55, 0x52, 0x72, 0x27, 0x84, 0x54, 0x71, 0x40, 0x78, 0x44, 0x75, 0x24, 0x78, 0x61, 0x21, 0x65, 0x57, 0x43, 0x58, 0x21, 0x15, 0x11, 0x87, 0x35, 0x82, 0x52, 0x00, 0x46, 0x11, 0x34, 0x68, 0x60, 0x60, 0x50, 0x15, 0x25, 0x62, 0x48, 0x08, 0x18, 0x31, 0x36, 0x86, 0x41, 0x26, 0x80, 0x82, 0x54, 0x68, 0x02, 0x07, 0x23, 0x22, 0x24, 0x33, 0x27, 0x02, 0x04, 0x40, 0x22, 0x47, 0x87, 0x62, 0x70, 0x21, 0x81, 0x22, 0x25, 0x78, 0x87, 0x67, 0x62, 0x38, 0x42, 0x10, 0x21, 0x58, 0x56, 0x06, 0x20, 0x18, 0x46, 0x18, 0x22, 0x61, 0x73, 0x45, 0x65, 0x73, 0x58, 0x57, 0x04, 0x76, 0x72, 0x54, 0x48, 0x00, 0x62, 0x27, 0x22, 0x25, 0x17, 0x43, 0x55, 0x58, 0x57, 0x64, 0x04, 0x61, 0x21, 0x24, 0x02, 0x20, 0x17, 0x34, 0x25, 0x13, 0x35, 0x14, 0x52, 0x76, 0x83, 0x11, 0x05, 0x05, 0x03, 0x11, 0x28, 0x71, 0x16, 0x40, 0x56, 0x21, 0x76, 0x18, 0x67, 0x38, 0x02, 0x15, 0x36, 0x67, 0xf3, 0xc8, 0x13, 0x98, 0x97, 0xb3, 0x28, 0x88, 0xb7, 0x32, 0x0d, 0xf8, 0xcf, 0x60, 0x47, 0x25, 0x85, 0xf5, 0x2d, 0x0c, 0x02, 0x62, 0xa7, 0xb3, 0x22, 0x3c, 0x55, 0xb6, 0x55, 0x9b, 0x20, 0x35, 0x10, 0x77, 0x87, 0xeb, 0xcf, 0xa0, 0x11, 0x37, 0xdc, 0x09, 0x0b, 0xdb, 0x94, 0x28, 0xc5, 0x30, 0x74, 0x7f, 0x73, 0x3a, 0x05, 0x10, 0xf2, 0x1a, 0x61, 0x88, 0xdb, 0x2e, 0xc9, 0xf1, 0x14, 0x75, 0x3d, 0xef, 0x09, 0x2f, 0x53, 0x57, 0x87, 0xb0, 0x78, 0xa2, 0xc1, 0xe3, 0x5b, 0xd4, 0x4e, 0x77, 0x86, 0x0c, 0x69, 0x06, 0x33, 0x59, 0x35, 0xdd, 0xbd, 0xa7, 0x9f, 0x3e, 0x2f, 0x0f, 0x22, 0x4d, 0x17, 0xa6, 0x5c, 0x60, 0x3e, 0xa3, 0xf1, 0xbf, 0x08, 0x38, 0x9f, 0x14, 0x0b, 0x07, 0xa4, 0x0d, 0x1e, 0xf8, 0x34, 0x23, 0x01, 0x62, 0xad, 0x3c, 0x65, 0x49, 0xca, 0x12, 0x01, 0x2b, 0x2d, 0x17, 0x4c, 0xa1, 0xa7, 0x40, 0xde, 0xdd, 0x2b, 0x4b, 0x14, 0xf1, 0x21, 0x6a, 0x68, 0xd5, 0x65, 0xe6, 0x16, 0x42, 0xdc, 0xf3, 0xce, 0x0e, 0x3a, 0xa4, 0x12, 0x16, 0x72, 0xa5, 0xa4, 0xbb, 0xa3, 0xb4, 0x08, 0x6d, 0xce, 0x95, 0x73, 0xc6, 0x4a, 0xe4, 0x5a, 0x14, 0x73, 0xb1, 0x14, 0xab, 0x65, 0xb7, 0x8b, 0xe4, 0x7c, 0xa1, 0xd2, 0xbb, 0x6a, 0xf2, 0xf2, 0x7d, 0x64, 0x26, 0x68, 0xec, 0xc2, 0x51, 0x3c, 0xf0, 0xcc, 0x7a, 0x04, 0x6a, 0x29, 0x8d, 0x76, 0x7f, 0xe5, 0x8f, 0x95, 0x20, 0xd1, 0xf7, 0x98, 0x29, 0xf5, 0x35, 0x80, 0x25, 0xda, 0x54, 0xde, 0xb9, 0x5f, 0x6d, 0x68, 0xcf, 0x7e, 0x85, 0xcf, 0x38, 0x0d, 0x32, 0x63, 0x37, 0x77, 0xe1, 0xa5, 0x9c, 0x0a, 0x6c, 0xc5, 0x3f, 0xde, 0xdb, 0xe6, 0x57, 0x16, 0x4e, 0xbc, 0xb1, 0x02, 0x7c, 0x58, 0x85, 0x60, 0x1f, 0x0d, 0x0f, 0x4f, 0x5f, 0xbf, 0xa3, 0xbc, 0x2c, 0xfe, 0x66, 0xbf, 0xb5, 0x93, 0xf0, 0x13, 0xfa, 0x52, 0x07, 0x40, 0xdb, 0xbf, 0x6e, 0x6c, 0xca, 0x74, 0x61, 0x0b, 0xa6, 0xaf, 0x02, 0x60, 0xf1, 0x57, 0x17, 0x08, 0xf1, 0x09, 0xf7, 0xc4, 0x4e, 0x51, 0xaf, 0x04, 0xf1, 0x4c, 0xbc, 0xe5, 0x77, 0x8f, 0x0f, 0x9b, 0xa7, 0xb3, 0xf7, 0xb0, 0x32, 0x14, 0xbc, 0x1d, 0x40, 0xe7, 0x06, 0x01, 0xd6, 0xf2, 0x7f, 0x84, 0xab, 0x47, 0x34, 0x15, 0x2c, 0x62, 0xfe, 0x95, 0x51, 0xaf, 0x51, 0x4a, 0x1d, 0xc4, 0xea, 0xaf, 0xdc, 0xe4, 0xea, 0xa7, 0x7d, 0x25, 0x2a, 0x79, 0x24, 0xf8, 0xaa, 0xf2, 0xe9, 0x82, 0x48, 0x7b, 0x0e, 0x2c, 0x5c, 0x38, 0x89, 0x21, 0xfe, 0x91, 0x72, 0xed, 0xd9, 0x41, 0xac, 0x0d, 0xdc, 0x12, 0xf4, 0x3f, 0x49, 0x91, 0x65, 0x2d, 0x39, 0xea, 0xdf, 0xc6, 0xcd, 0xa8, 0xbe, 0x53, 0x23, 0x04, 0xbf, 0xd3, 0xf0, 0xb8, 0x76, 0xc8, 0x01, 0x43, 0x2c, 0x6b, 0x79, 0xae, 0x23, 0x50, 0xe0, 0x34, 0x09, 0x85, 0xd8, 0xdb, 0xc5, 0x37, 0xb8, 0xd5, 0x49, 0x26, 0x9c, 0x0b, 0x85, 0x95, 0x5f, 0x28, 0x17, 0x8d, 0xd3, 0x0d, 0xe0, 0x34, 0x34, 0x23, 0x07, 0x74, 0x13, 0x55, 0xd7, 0xe5, 0xb4, 0x83, 0x4c, 0xd8, 0xdc, 0xdb, 0x5a, 0xe9, 0x3c, 0x36, 0x53, 0xa4, 0x3a, 0x80, 0xde, 0x77, 0xa0, 0xaa, 0x9a, 0xe7, 0x6e, 0xdd, 0x98, 0xdd, 0x6a, 0xf4, 0x34, 0xda, 0x83, 0x80, 0x9c, 0xe5, 0x83, 0xb3, 0xb6, 0xf7, 0x81, 0x39, 0x46, 0xea, 0x93, 0x85, 0xad, 0xf5, 0xa7, 0x1a, 0xb1, 0x31, 0x6f, 0xb9, 0x79, 0x11, 0x57, 0x62, 0x47, 0xd9, 0xcc, 0x67, 0x78, 0xec, 0x32, 0xd3, 0x0c, 0x34, 0xea, 0x1b, 0xa8, 0x84, 0x54, 0xb1, 0xf3, 0x80, 0x4b, 0x79, 0x32, 0x82, 0x18, 0x54, 0x2d, 0xdf, 0xbb, 0x4d, 0xbe, 0x75, 0xa0, 0x8e, 0x53, 0x52, 0xed, 0x6e, 0x0a, 0x9f, 0xa6, 0x9b, 0x14, 0x32, 0x10, 0xf1, 0x7e, 0xdd, 0xfa, 0xc5, 0xf5, 0xbd, 0x67, 0xfb, 0x64, 0xf6, 0xc3, 0xb1, 0xc9, 0x81, 0x17, 0x60, 0x56, 0x11, 0xdc, 0x63, 0x13, 0x16, 0x4a, 0xa8, 0xeb, 0x7f, 0x82, 0xd3, 0x90, 0xeb, 0x5e, 0xe7, 0xb0, 0xd9, 0x3e, 0x13, 0xd3, 0x73, 0x90, 0x0d, 0x67, 0xc1, 0x18, 0xcc, 0x3b, 0x88, 0xcd, 0x4d, 0x40, 0xbe, 0xd4, 0x5e, 0xee, 0x73, 0xa4, 0xee, 0xbd, 0xcb, 0xbc, 0x39, 0x8b, 0x6d, 0x15, 0x34, 0x18, 0xd2, 0x55, 0x93, 0xc0, 0xf4, 0x95, 0xd1, 0xe4, 0x7f, 0x37, 0xb1, 0x3a, 0x8c, 0x4b, 0xbc, 0x7d, 0x76, 0xb4, 0x34, 0xf4, 0x11, 0x5c, 0x10, 0xeb, 0x34, 0x88, 0x61, 0xd7, 0x89, 0xac, 0x87, 0x91, 0x6a, 0x80, 0xee, 0x07, 0x0d, 0x26, 0xfa, 0xd2, 0x75, 0x6b, 0xd6, 0x0b, 0xa5, 0xc6, 0x71, 0x6d, 0x0a, 0x5b, 0x59, 0x62, 0x32, 0x60, 0x42, 0x73, 0x75, 0xda, 0x63, 0x36, 0x96, 0xca, 0xde, 0xe9, 0x60, 0xfe, 0xa2, 0x64, 0xcc, 0x85, 0x22, 0x4c, 0xc5, 0x2f, 0x0e, 0xe8, 0xf5, 0x93, 0xdb, 0x16, 0xa7, 0x1f, 0xd9, 0x30, 0xbc, 0xa2, 0xba, 0x23, 0xca, 0xea, 0xc1, 0x4d, 0x2f, 0xd4, 0x81, 0x98, 0xff, 0x58, 0xfc, 0x40, 0x39, 0x75, 0x52, 0x3e, 0x3e, 0xf4, 0x8d, 0x95, 0x55, 0x0a, 0x95, 0x5f, 0x4f, 0x5d, 0xdd, 0x0d, 0xb8, 0xd4, 0x63, 0x98, 0x48, 0x6b, 0xec, 0xe8, 0xd9, 0xae, 0xeb, 0x9d, 0x48, 0xa4, 0x9a, 0x63, 0x03, 0xc4, 0x57, 0xcd, 0x7d, 0x97, 0xc8, 0x11, 0x7e, 0xcb, 0x78, 0xe8, 0x5d, 0x6e, 0xe6, 0xdd, 0x13, 0x33, 0xf2, 0x05, 0xcd, 0x5a, 0x44, 0x18, 0xf9, 0x32, 0x41, 0x4e, 0x5c, 0xfc, 0x7a, 0xe9, 0xc2, 0x28, 0xd3, 0x42, 0x56, 0xc8, 0x39, 0x26, 0x78, 0xdd, 0x92, 0x1c, 0xa6, 0xf4, 0x94, 0xa9, 0xc4, 0x69, 0xf9, 0x7e, 0xea, 0x9c, 0xd6, 0x92, 0xd6, 0xab, 0xd5, 0x1d, 0xde, 0x4e, 0x8d, 0x6c, 0xb2, 0xc3, 0x8a, 0xcb, 0xdb, 0xfc, 0x2d, 0xb6, 0xc6, 0x16, 0x49, 0xd1, 0x31, 0x51, 0x90, 0x0c, 0x75, 0x6e, 0x27, 0x3b, 0xda, 0x42, 0x0b, 0xdc, 0xd1, 0xea, 0xde, 0xd9, 0xbe, 0x02, 0xb8, 0xb0, 0x55, 0xba, 0xde, 0x0c, 0xcf, 0x68, 0xd2, 0x02, 0x7f, 0x16, 0x5a, 0x63, 0xcc, 0xd1, 0x42, 0xb3, 0x2f, 0x08, 0x4a, 0x8c, 0x06, 0xa9, 0x13, 0xa2, 0xca, 0xf0, 0x72, 0xff, 0xd1, 0x77, 0x58, 0xcd, 0x8d, 0x49, 0xca, 0x67, 0x9a, 0x21, 0x58, 0x94, 0xa6, 0x80, 0x57, 0xb4, 0xfb, 0x7a, 0x76, 0x30, 0xe8, 0xa1, 0xef, 0x45, 0x6f, 0xa9, 0x62, 0xf5, 0x51, 0xfa, 0x87, 0x56, 0x07, 0x9b, 0xc3, 0xab, 0xd6, 0x3c, 0xa4, 0x3a, 0x02, 0x1f, 0xcd, 0xaa, 0xce, 0x2c, 0xc9, 0x49, 0x30, 0x27, 0x3e, 0x27, 0x92, 0x59, 0xff, 0xb7, 0x35, 0x6e, 0xe7, 0x7e, 0x94, 0x06, 0xf0, 0x2b, 0x00, 0x58, 0x3f, 0x5e, 0x28, 0x12, 0x70, 0x1c, 0x6b, 0xef, 0x78, 0x22, 0x12, 0x03, 0xd7, 0x12, 0xd5, 0x46, 0xd6, 0xf2, 0xea, 0x16, 0x94, 0x2c, 0x1a, 0xfa, 0x52, 0x05, 0xed, 0xf1, 0x25, 0xf4, 0x06, 0x8b, 0x85, 0x7c, 0x38, 0x70, 0x53, 0x54, 0x41, 0x6c, 0x8a, 0x0a, 0x60, 0x83, 0x59, 0x7d, 0x73, 0xe0, 0xd8, 0xa5, 0x1b, 0x3a, 0xec, 0xcd, 0x5f, 0x44, 0x0b, 0xeb, 0xcc, 0xe9, 0x65, 0xd4, 0x68, 0xb0, 0x3d, 0x13, 0xf1, 0xb9, 0x2a, 0x67, 0xb7, 0xae, 0x4f, 0xf3, 0xa7, 0x2e, 0x33, 0xf3, 0x80, 0xc1, 0x4f, 0xd1, 0xcd, 0xdd, 0xd2, 0xab, 0xde, 0xcb, 0x04, 0xc8, 0x1b, 0x26, 0xd4, 0x86, 0xd8, 0x6f, 0xe1, 0x2b, 0x85, 0xb9, 0x2c, 0xe3, 0xaf, 0xf5, 0x9f, 0x4b, 0xfb, 0x41, 0xa9, 0xc9, 0x2e, 0xd0, 0x2d, 0xda, 0xba, 0xa0, 0xba, 0xfb, 0x14, 0x5d, 0x2e, 0xbf, 0x65, 0xbd, 0xe3, 0x51, 0x8d, 0xdd, 0xbb, 0x51, 0x35, 0x3a, 0xf0, 0xbe, 0x74, 0xae, 0x42, 0x8b, 0x5d, 0xd9, 0xef, 0x67, 0x1c, 0x01, 0xb5, 0x1c, 0xc9, 0x3d, 0x0c, 0x42, 0x3a, 0xce, 0x53, 0xbb, 0x23, 0xd0, 0x92, 0x2c, 0x60, 0x0f, 0xf1, 0x73, 0x37, 0xa9, 0x99, 0x86, 0xd9, 0x7e, 0xfc, 0x8a, 0x56, 0xa2, 0xf7, 0x17, 0x69, 0x75, 0x49, 0x1a, 0x8e, 0x4c, 0x4b, 0x87, 0xe0, 0xfb, 0xcc, 0x93, 0x14, 0x7d, 0x96, 0xdc, 0xcc, 0xc6, 0x3c, 0x8d, 0x71, 0x50, 0xf2, 0x0f, 0x67, 0xdd, 0xd9, 0x95, 0xb7, 0xc9, 0xd8, 0xf4, 0x1a, 0xca, 0x0c, 0x90, 0xe4, 0xf5, 0x0e, 0xf7, 0xfb, 0x8c, 0x4c, 0x92, 0x66, 0x3c, 0x3d, 0xf2, 0x47, 0x6f, 0x8c, 0x51, 0x71, 0xff, 0xe1, 0xba, 0x1f, 0x02, 0x64, 0x12, 0x79, 0xa5, 0xad, 0x6e, 0x7c, 0xab, 0xf1, 0x06, 0x01, 0xc1, 0x25, 0x4e, 0xd6, 0xb6, 0xc3, 0xe9, 0xbe, 0x64, 0x52, 0x18, 0x22, 0x01, 0x23, 0xc6, 0xd6, 0xbb, 0x13, 0xbe, 0x15, 0x40, 0xc4, 0x97, 0x4b, 0x24, 0xe7, 0xaa, 0xef, 0x3b, 0x24, 0x04, 0x47, 0xcc, 0x4d, 0xd8, 0xd2, 0x9f, 0xf6, 0x60, 0xb9, 0x04, 0x27, 0xc0, 0x1c, 0xbc, 0x28, 0xe6, 0x16, 0xa4, 0x06, 0xa8, 0xab, 0x52, 0x56, 0x58, 0x53, 0x4a, 0xda, 0x0d, 0xf0, 0xb2, 0x8a, 0x8e, 0x7d, 0xd7, 0x29, 0x45, 0xe9, 0xc6, 0xc3, 0xf4, 0xaa, 0x16, 0x01, 0x48, 0x1d, 0x6c, 0x90, 0xbe, 0x49, 0x5c, 0x28, 0x49, 0x18, 0xd5, 0x52, 0xd5, 0x12, 0x54, 0x9c, 0x1f, 0xc0, 0xb5, 0x8f, 0x22, 0xa7, 0x2a, 0xd7, 0x36, 0x41, 0xc2, 0xc1, 0x7d, 0x11, 0x9b, 0xbf, 0x84, 0x2a, 0x05, 0x9f, 0x41, 0xea, 0x54, 0xf2, 0xe1, 0x69, 0x4d, 0xd5, 0x63, 0x00, 0x28, 0x81, 0x75, 0xd3, 0x8c, 0x19, 0x81, 0xd6, 0x0a, 0x25, 0x62, 0x9e, 0x35, 0xd0, 0x4d, 0xc7, 0x73, 0x3e, 0xae, 0x39, 0x89, 0xf9, 0xb6, 0x67, 0xf0, 0x08, 0x98, 0xd7, 0x87, 0xf1, 0xf4, 0x58, 0x12, 0xf5, 0x22, 0x51, 0xad, 0x9a, 0x4d, 0xed, 0x09, 0x81, 0x82, 0x99, 0x9b, 0x5f, 0x05, 0xb6, 0x3e, 0x8e, 0xad, 0x34, 0xa1, 0x2d, 0xb6, 0xae, 0xc7, 0x7b, 0x7f, 0x39, 0xf9, 0x53, 0xaf, 0xcd, 0x0e, 0xcc, 0x98, 0x5b, 0x5b, 0x92, 0x8c, 0x75, 0x36, 0x0a, 0xa9, 0xfc, 0xf5, 0x22, 0x14, 0xf3, 0x44, 0x5e, 0xc7, 0xf6, 0x7f, 0x3a, 0x92, 0x0b, 0xc1, 0x68, 0xa3, 0xc2, 0xd8, 0xf3, 0xd1, 0x12, 0x5b, 0x12, 0xd1, 0x96, 0x18, 0x50, 0x0c, 0xb5, 0x13, 0x40, 0xcb, 0x38, 0xdd, 0xf7, 0xc2, 0x4f, 0xb9, 0xda, 0xd2, 0x94, 0x3f, 0xbf, 0x63, 0x4f, 0x0a, 0xb8, 0x03, 0x67, 0x65, 0xc6, 0x40, 0xff, 0xc8, 0xd7, 0x8e, 0x06, 0x92, 0x7a, 0xdb, 0xad, 0x7d, 0x1b, 0x82, 0xd5, 0x19, 0xf1, 0x4a, 0x11, 0x3a, 0xe4, 0x23, 0x39, 0x8d, 0x5d, 0x0a, 0x63, 0xb2, 0x67, 0x1f, 0x98, 0xde, 0x5a, 0x44, 0x6a, 0x70, 0xff, 0x83, 0x34, 0x78, 0xa5, 0x02, 0x0b, 0x51, 0x4b, 0x0a, 0xab, 0x16, 0x04, 0x2e, 0xce, 0x6a, 0xf2, 0x72, 0x4c, 0x6f, 0x2f, 0xfa, 0xca, 0xd8, 0x19, 0x4f, 0x48, 0x9f, 0x1c, 0x7d, 0x60, 0x34, 0x9c, 0x79, 0x44, 0xd3, 0xaa, 0xea, 0x5c, 0xfe, 0xa0, 0xa1, 0x6e, 0xff, 0xa8, 0xb6, 0xe3, 0xd9, 0x60, 0xf2, 0x93, 0x32, 0x77, 0x07, 0xd6, 0xbb, 0xdf, 0x3a, 0x49, 0x38, 0xad, 0xc4, 0x63, 0xaf, 0xd0, 0x00, 0x41, 0xdb, 0x96, 0x75, 0xbb, 0xb3, 0xa8, 0x10, 0x67, 0x7e, 0x47, 0x89, 0x8c, 0xce, 0xdd, 0xe8, 0x8b, 0xf3, 0xdb, 0xd7, 0xf5, 0x4f, 0x22, 0xbf, 0x19, 0x61, 0x64, 0xf7, 0xe3, 0xcd, 0x4e, 0x3d, 0x19, 0x8e, 0x45, 0x8c, 0xce, 0xd3, 0x65, 0x3e, 0xb0, 0xdc, 0x94, 0x2e, 0xa2, 0xc2, 0x53, 0xba, 0x46, 0x3a, 0xd1, 0x39, 0xd4, 0x7a, 0xd8, 0xd6, 0x95, 0xb7, 0xdb, 0xdd, 0x7a, 0x81, 0x78, 0xac, 0xfe, 0x0a, 0x1c, 0x74, 0x3f, 0x52, 0xa3, 0x4d, 0xee, 0x4d, 0x37, 0x15, 0xd7, 0x39, 0x06, 0x59, 0xec, 0xa7, 0x92, 0xb2, 0x65, 0xee, 0x49, 0x63, 0xf4, 0x01, 0x54, 0xc2, 0xa0, 0xab, 0xfc, 0x10, 0x03, 0x30, 0x22, 0x63, 0xdb, 0x6e, 0xed, 0xd9, 0x1c, 0x28, 0xb1, 0x48, 0x09, 0xa8, 0x1c, 0x97, 0x09, 0xda, 0xaa, 0x3e, 0xd7, 0xc3, 0x65, 0x2f, 0x81, 0x22, 0x8e, 0x4e, 0x0e, 0x71, 0xaa, 0x96, 0xe4, 0x23, 0xd7, 0xa1, 0x1f, 0xcb, 0x8c, 0x9e, 0xa0, 0x39, 0xc4, 0xb1, 0x01, 0x68, 0x90, 0x61, 0x58, 0xcd, 0x62, 0xa0, 0xa9, 0xeb, 0xb3, 0x07, 0xb4, 0xf5, 0xf9, 0xb6, 0xdf, 0x05, 0xc6, 0x03, 0x7a, 0xa5, 0x1e, 0x8c, 0x12, 0x79, 0x9a, 0xe3, 0x2b, 0x22, 0x25, 0x9a, 0x52, 0x68, 0x4b, 0x47, 0x71, 0xac, 0x71, 0x3e, 0x1a, 0x14, 0x7f, 0x34, 0x4d, 0xdc, 0x4e, 0x49, 0xf6, 0x5a, 0x91, 0x5b, 0x44, 0xc8, 0xef, 0x67, 0x9c, 0xfe, 0xb3, 0x04, 0xa9, 0x4f, 0xa8, 0xf3, 0x89, 0xdf, 0x89, 0x83, 0xff, 0xd2, 0x45, 0x95, 0x66, 0x56, 0x23, 0x84, 0x01, 0x13, 0x90, 0x5a, 0x7a, 0x04, 0xc3, 0x97, 0x60, 0xf2, 0x86, 0x35, 0x5c, 0x45, 0x6f, 0xcf, 0x27, 0xbc, 0xbb, 0xc3, 0x52, 0xf6, 0xb2, 0xd6, 0x5a, 0xe0, 0xbc, 0x14, 0xc8, 0xfd, 0x57, 0x38, 0x61, 0x8e, 0xc2, 0x58, 0x5e, 0xcc, 0x0d, 0x86, 0xb6, 0xf3, 0x27, 0x92, 0x4a, 0x44, 0xde, 0x27, 0x4b, 0xf9, 0xc3, 0x62, 0x5d, 0xe2, 0x72, 0xfe, 0xae, 0x22, 0x8f, 0x31, 0x52, 0x99, 0xda, 0x94, 0xd3, 0xaa, 0x73, 0x49, 0xdb, 0x48, 0x1a, 0x1f, 0x0b, 0x7b, 0x11, 0x3f, 0xcd, 0x57, 0xc4, 0x4e, 0x7b, 0x3e, 0xc6, 0x82, 0x8a, 0x17, 0x41, 0xe3, 0x00, 0x55, 0xec, 0x82, 0x9f, 0x65, 0x30, 0x4d, 0xfa, 0xc1, 0x91, 0x16, 0x89, 0x4d, 0xec, 0x5a, 0xee, 0x17, 0xa0, 0xaf, 0x03, 0xb4, 0x04, 0x01, 0x54, 0xa6, 0x13, 0xad, 0x7c, 0x49, 0x17, 0x75, 0x0c, 0x4a, 0xe6, 0xf8, 0x7c, 0xa2, 0xf3, 0x53, 0x84, 0xb1, 0xd3, 0x23, 0x53, 0xc7, 0x35, 0xdf, 0x66, 0xee, 0x0f, 0xbc, 0x8e, 0x2c, 0x21, 0x43, 0x46, 0x97, 0x89, 0x90, 0x35, 0x18, 0xcc, 0xd9, 0x3a, 0xc8, 0x58, 0x1c, 0x52, 0x94, 0x57, 0x4d, 0x5a, 0x37, 0xc3, 0xfb, 0x65, 0xdd, 0xbe, 0x96, 0x97, 0xdf, 0xda, 0x73, 0x60, 0x9a, 0x45, 0x1e, 0x18, 0xf4, 0xea, 0x5e, 0xfc, 0x0e, 0x39, 0xf3, 0x81, 0x88, 0x2a, 0xe5, 0xe1, 0x91, 0xed, 0x37, 0x32, 0x63, 0x4d, 0xd3, 0x90, 0xcb, 0x86, 0xc0, 0x5c, 0xbd, 0x04, 0x7e, 0x13, 0x69, 0xa0, 0xe1, 0x1f, 0xbd, 0x86, 0x33, 0xf4, 0x99, 0xd1, 0x4e, 0xde, 0x60, 0xbb, 0xd2, 0xd5, 0x9d, 0x3f, 0x15, 0x01, 0x79, 0x4a, 0x03, 0x5e, 0x39, 0x23, 0x99, 0xbb, 0x27, 0x8d, 0x93, 0x5c, 0x13, 0x6e, 0xbf, 0xc0, 0x3a, 0x32, 0xf9, 0xc0, 0xf4, 0xb4, 0x73, 0x16, 0x63, 0xba, 0x9d, 0x2c, 0xb1, 0x08, 0x63, 0x69, 0xa4, 0x71, 0x0d, 0x67, 0x06, 0xd3, 0x48, 0x0e, 0x7a, 0x53, 0xe0, 0xdd, 0x19, 0xc2, 0xfc, 0x96, 0x07, 0xbc, 0xe6, 0x3d, 0x76, 0x73, 0xcb, 0x7f, 0x0f, 0xe1, 0x9a, 0x70, 0xd0, 0x0c, 0xf7, 0xc9, 0x96, 0x04, 0x70, 0x4a, 0xf8, 0x9a, 0x68, 0x12, 0x1c, 0xfa, 0x2b, 0x96, 0x9c, 0x3f, 0x45, 0xf9, 0x02, 0x80, 0xf4, 0xcd, 0x60, 0xb3, 0xb2, 0x03, 0x69, 0x3f, 0x3f, 0x81, 0x2f, 0xfc, 0x9e, 0x6a, 0x0a, 0x72, 0xdb, 0x65, 0xe0, 0x20, 0xb9, 0x3e, 0x0f, 0xaa, 0xc7, 0x68, 0x29, 0xd1, 0xfe, 0xbf, 0x73, 0x32, 0xcb, 0x97, 0xa8, 0x67, 0x77, 0x08, 0x39, 0x0d, 0x1d, 0x01, 0xec, 0x5a, 0x7f, 0x60, 0x69, 0x13, 0x47, 0xa1, 0x7f, 0xfc, 0x0c, 0xee, 0x51, 0x6f, 0x53, 0x16, 0x2f, 0xd5, 0x50, 0x9d, 0x99, 0xe7, 0xa8, 0xf7, 0xda, 0xb2, 0x71, 0xcd, 0x3d, 0xaa, 0x40, 0x6d, 0x7a, 0x51, 0x76, 0xb2, 0xca, 0xc2, 0xc8, 0x88, 0x30, 0xf6, 0xa9, 0x9c, 0xb4, 0x7e, 0x24, 0xce, 0x20, 0x0f, 0x10, 0xf2, 0xdb, 0xad, 0x43, 0x5e, 0x0c, 0x3d, 0x27, 0x6a, 0xed, 0x38, 0x2b, 0xe2, 0xd0, 0x91, 0xff, 0x5b, 0x7c, 0x0c, 0xed, 0x87, 0xa7, 0xd5, 0x09, 0x79, 0xfd, 0xe5, 0xeb, 0x26, 0xe0, 0xa9, 0x71, 0xae, 0xd5, 0xba, 0xc4, 0x8a, 0xdf, 0x0e, 0xbf, 0x0e, 0x8a, 0x6a, 0x40, 0x3d, 0x48, 0x06, 0x53, 0x57, 0x43, 0xc6, 0x91, 0x4a, 0x3a, 0x19, 0xc4, 0x06, 0x85, 0xbb, 0x80, 0x6e, 0x0f, 0xf4, 0x54, 0xa9, 0xab, 0x2e, 0x85, 0xe8, 0x89, 0x48, 0x55, 0xe3, 0xca, 0x74, 0xf0, 0x59, 0x47, 0x01, 0x1d, 0x6b, 0xcd, 0x6c, 0xd3, 0x00, 0x9a, 0x82, 0xaf, 0x1e, 0x29, 0x82, 0xdb, 0xd3, 0x48, 0x24, 0x3e, 0x61, 0xf9, 0x40, 0xc7, 0x28, 0xc6, 0xe3, 0x27, 0x71, 0xf0, 0x37, 0xeb, 0xf4, 0x30, 0xdd, 0x1e, 0xf1, 0x1f, 0xa6, 0xc0, 0x7d, 0x8c, 0x83, 0xac, 0xd5, 0x91, 0x3a, 0x9f, 0x8b, 0x03, 0xe6, 0x7b, 0xef, 0x25, 0x57, 0xe9, 0x37, 0x52, 0x01, 0xa1, 0xf6, 0xa9, 0xaf, 0xbf, 0x43, 0xf2, 0x43, 0x79, 0x32, 0xf5, 0x03, 0x70, 0xde, 0x3c, 0x41, 0x4e, 0x7f, 0xeb, 0x9d, 0x0e, 0x91, 0x45, 0x0c, 0x98, 0xdd, 0x65, 0xcb, 0x41, 0xde, 0x75, 0xa8, 0xb6, 0xe0, 0xd6, 0xe9, 0xbe, 0xe7, 0xd9, 0xb0, 0x01, 0x27, 0x0c, 0xf1, 0xc0, 0x20, 0xed, 0x7b, 0x17, 0xb2, 0xfa, 0x56, 0x9b, 0x5a, 0xf5, 0xb1, 0x2e, 0x36, 0xd0, 0x88, 0x2b, 0x00, 0xc5, 0x02, 0x4a, 0xa0, 0xda, 0x65, 0xb6, 0x7b, 0xa1, 0x7b, 0x1e, 0x28, 0x72, 0xcf, 0x4f, 0xa3, 0xe6, 0x21, 0x14, 0x25, 0x40, 0xc4, 0x41, 0xda, 0xde, 0xd4, 0x10, 0xca, 0x02, 0x95, 0x31, 0xcd, 0xfc, 0xe9, 0x7b, 0xb8, 0x0f, 0xe3, 0xf1, 0xcb, 0x2e, 0x8f, 0xd4, 0x3e, 0xfa, 0xdc, 0x5f, 0x4c, 0xc3, 0xc1, 0x38, 0x8e, 0xbe, 0xf8, 0x21, 0x56, 0xaf, 0xba, 0x42, 0xb7, 0x76, 0xd8, 0xfc, 0xa3, 0x6c, 0x07, 0x62, 0xa2, 0xb5, 0x27, 0xe0, 0x18, 0x7c, 0x57, 0xe3, 0x6d, 0xfe, 0x47, 0x56, 0x61, 0xd5, 0xda, 0x17, 0x44, 0x7b, 0x47, 0xea, 0x43, 0x62, 0xcf, 0x11, 0xe4, 0x6b, 0x26, 0x82, 0x24, 0x13, 0x63, 0xc6, 0x14, 0xbb, 0x00, 0xad, 0xe6, 0xe7, 0x32, 0x4e, 0x79, 0xae, 0xc0, 0x1a, 0x51, 0x78, 0xc0, 0xd4, 0x13, 0x02, 0xb1, 0x55, 0xcf, 0xf0, 0x92, 0xaa, 0xad, 0x8f, 0x89, 0x4d, 0xfc, 0x2e, 0x3b, 0x1a, 0x22, 0xb2, 0x4e, 0xef, 0xdb, 0x98, 0x56, 0x0f, 0x7a, 0x0a, 0x5e, 0xf6, 0xde, 0x8e, 0xd5, 0xdc, 0x84, 0x72, 0xe6, 0xa9, 0xd2, 0x5f, 0xd5, 0x66, 0xab, 0x1e, 0x8b, 0xf2, 0x28, 0x9b, 0x77, 0xc5, 0x24, 0x04, 0x93, 0x85, 0x54, 0x5b, 0xcc, 0x0a, 0x18, 0xdc, 0xa9, 0x27, 0x34, 0x1d }; static const unsigned char ml_dsa_65_sig[] = { 0x5e, 0xc1, 0xb0, 0x64, 0x5c, 0x45, 0x6e, 0x22, 0x9f, 0x7c, 0x49, 0xbf, 0x8e, 0x93, 0xe5, 0x83, 0xfc, 0xa0, 0xf3, 0xb0, 0x93, 0x6f, 0x47, 0xa9, 0x11, 0x9e, 0x1b, 0x13, 0xae, 0x05, 0xdd, 0xc6, 0x55, 0x46, 0x81, 0x4f, 0x5e, 0x0c, 0xa7, 0x75, 0x6b, 0x5c, 0x13, 0xf2, 0xc7, 0x1f, 0x4d, 0x74, 0xa5, 0x50, 0xf4, 0xec, 0x3e, 0x75, 0x75, 0xbf, 0x4c, 0xef, 0x50, 0x02, 0x87, 0x7d, 0x88, 0x05, 0x40, 0xba, 0xc1, 0x8e, 0xd6, 0x5d, 0xe3, 0x3c, 0xd9, 0x98, 0x05, 0x76, 0x09, 0xdf, 0xcb, 0xd2, 0x0e, 0x56, 0x53, 0x88, 0x1e, 0xe1, 0x91, 0xcd, 0x7d, 0x67, 0x11, 0x89, 0xf8, 0x58, 0xb9, 0x76, 0xd6, 0x8f, 0x83, 0xca, 0xcc, 0x94, 0xf4, 0x97, 0x58, 0xf5, 0x3d, 0xc7, 0xaa, 0xa4, 0x3f, 0xe3, 0xcb, 0xcc, 0x67, 0xac, 0x50, 0x8f, 0xfe, 0xf7, 0x90, 0x33, 0x04, 0x8b, 0x82, 0x14, 0x26, 0xa7, 0x21, 0x4e, 0xf2, 0x37, 0x5a, 0x91, 0xe8, 0x7a, 0x30, 0xb6, 0xce, 0x8f, 0x31, 0xfc, 0xef, 0xbe, 0x7d, 0x16, 0x81, 0x18, 0xb3, 0x77, 0x0f, 0x4a, 0xe9, 0x31, 0xf8, 0x51, 0x0e, 0xaa, 0x44, 0x5c, 0x8b, 0x43, 0x0a, 0x61, 0x02, 0x6c, 0xdf, 0xee, 0x09, 0x9b, 0x8f, 0x91, 0x5c, 0x75, 0x10, 0xa8, 0xc6, 0xe3, 0x5d, 0x93, 0x74, 0x63, 0x73, 0x27, 0xb9, 0x29, 0xc0, 0x9b, 0x62, 0x6a, 0xc6, 0x75, 0x84, 0x78, 0x41, 0xf3, 0x5c, 0x5d, 0x60, 0xcf, 0xc5, 0xe4, 0x78, 0x87, 0x53, 0x6c, 0xab, 0xff, 0xbb, 0x53, 0xe9, 0x54, 0xf7, 0x1e, 0x06, 0xcf, 0x9e, 0x52, 0xd0, 0x3c, 0x8c, 0x5e, 0x64, 0xba, 0x28, 0x33, 0xb0, 0x14, 0x84, 0x56, 0x5a, 0xac, 0xd6, 0xee, 0x1e, 0x5e, 0x39, 0x08, 0xcb, 0x16, 0x54, 0x21, 0xe4, 0x6c, 0xa7, 0x29, 0xd2, 0x7b, 0xbe, 0x09, 0xd5, 0x1c, 0xf2, 0xf8, 0x11, 0x1e, 0x64, 0x6b, 0xca, 0x1a, 0xe4, 0xca, 0xab, 0xf1, 0x13, 0xdc, 0xa2, 0x1e, 0x78, 0x09, 0x2a, 0x08, 0xc5, 0xa1, 0x42, 0x62, 0xac, 0x94, 0x46, 0x61, 0x37, 0x98, 0x0d, 0x93, 0xa6, 0xc2, 0x4d, 0xb8, 0x00, 0x43, 0x4d, 0x6c, 0x5d, 0x06, 0x30, 0xaf, 0xd5, 0xb6, 0x32, 0x9e, 0xfe, 0xf2, 0x03, 0x8b, 0xa6, 0x7c, 0x6d, 0x36, 0x7e, 0xef, 0x99, 0x09, 0xaf, 0x2c, 0x79, 0x70, 0x26, 0xff, 0xc8, 0x99, 0x01, 0x93, 0x3b, 0x9c, 0xde, 0x0b, 0x5e, 0xf5, 0x44, 0x5f, 0x15, 0xb6, 0x49, 0xde, 0x89, 0xdd, 0x1e, 0x2b, 0x69, 0x7d, 0xb2, 0x88, 0xf2, 0x94, 0x24, 0x49, 0xeb, 0x23, 0xfc, 0x60, 0x95, 0x09, 0x89, 0xe5, 0xfd, 0xe3, 0x63, 0xfa, 0x3a, 0xb7, 0x18, 0x99, 0xe0, 0x5a, 0x25, 0x94, 0xd6, 0x3a, 0x6a, 0x48, 0x6e, 0xea, 0xe3, 0x61, 0xf8, 0x81, 0xe8, 0x4a, 0x43, 0xcb, 0x19, 0xfe, 0x2e, 0x16, 0x8d, 0xca, 0x7e, 0xeb, 0x81, 0x55, 0xc0, 0x8a, 0xf5, 0x14, 0x5b, 0xb6, 0x06, 0x45, 0x72, 0xa6, 0x8a, 0xc2, 0x16, 0x8d, 0xe4, 0x31, 0x54, 0x9c, 0xd2, 0x75, 0x5f, 0x7d, 0xf2, 0x19, 0x19, 0xf4, 0x4a, 0xfe, 0xaf, 0x18, 0x2d, 0x51, 0x43, 0x2e, 0x40, 0x02, 0xc0, 0x25, 0x53, 0x10, 0x37, 0x3d, 0xeb, 0xd6, 0x08, 0x75, 0x6c, 0xb2, 0x38, 0x72, 0xef, 0x67, 0x80, 0x50, 0xc7, 0x54, 0x4c, 0x91, 0xcb, 0x68, 0x64, 0x23, 0xa9, 0x4b, 0x0d, 0xcb, 0x71, 0x9c, 0x27, 0x67, 0x22, 0x98, 0xad, 0x3a, 0xa0, 0xd8, 0x9f, 0x21, 0x95, 0xdc, 0xb0, 0xa5, 0xb4, 0x44, 0x3b, 0xc8, 0xcb, 0x5c, 0x50, 0xd1, 0x38, 0x03, 0x91, 0x79, 0x73, 0x2f, 0x4a, 0xd7, 0x1f, 0xe5, 0xdc, 0x16, 0xaf, 0xb1, 0x2a, 0x86, 0x02, 0x0b, 0x31, 0x42, 0x64, 0x2f, 0x8a, 0x83, 0x7b, 0x13, 0x78, 0xdd, 0x6c, 0x72, 0x46, 0xa2, 0x84, 0x2f, 0xa8, 0x24, 0x43, 0xb0, 0x69, 0xaf, 0x52, 0x58, 0x13, 0x7c, 0xb3, 0xf8, 0x2d, 0x74, 0x87, 0x68, 0x17, 0xd6, 0x0c, 0x50, 0x19, 0xf8, 0x11, 0x68, 0xd5, 0x1c, 0x56, 0x30, 0x5d, 0x31, 0x56, 0xe4, 0x9d, 0x80, 0x39, 0x0c, 0xcd, 0x34, 0xfe, 0x67, 0x2f, 0xfa, 0x0c, 0x10, 0xb2, 0xcd, 0x66, 0x9e, 0x65, 0xac, 0xc5, 0x45, 0x33, 0x20, 0x16, 0x79, 0x82, 0x48, 0x26, 0xaa, 0x54, 0xd9, 0x32, 0x03, 0x99, 0x46, 0x65, 0xf8, 0xa8, 0xe7, 0x3c, 0xb1, 0xf9, 0xed, 0x76, 0x21, 0x36, 0xab, 0x98, 0x2d, 0xf2, 0xd1, 0x75, 0x33, 0x58, 0xb5, 0x7c, 0x4e, 0x3b, 0x78, 0xb6, 0x24, 0x15, 0xd2, 0xac, 0x41, 0x44, 0x46, 0x4d, 0x7a, 0x5b, 0x86, 0xce, 0xc2, 0x93, 0x11, 0x8f, 0x68, 0xb5, 0xc7, 0x83, 0x8f, 0xe1, 0x13, 0x91, 0xef, 0xca, 0x18, 0xa3, 0xf1, 0x04, 0x28, 0x58, 0xd8, 0x54, 0x12, 0x03, 0xbe, 0xe1, 0x29, 0xcf, 0x28, 0xa3, 0x43, 0x78, 0x00, 0xb7, 0x52, 0x00, 0xe3, 0x44, 0x07, 0x5f, 0x67, 0xb1, 0x78, 0x75, 0x9c, 0xe0, 0xc7, 0x33, 0x5f, 0x69, 0x27, 0x05, 0x15, 0xc3, 0xd4, 0x81, 0x09, 0x33, 0x7b, 0x3e, 0xc4, 0x71, 0xc3, 0xc0, 0x9a, 0x2c, 0xb5, 0xfc, 0x00, 0x79, 0x1d, 0x12, 0xb4, 0x90, 0xf1, 0xa3, 0xb1, 0xaa, 0xa8, 0xf9, 0x40, 0x48, 0xb1, 0x8b, 0x3c, 0xa9, 0xa9, 0x36, 0xe0, 0xe8, 0xd3, 0x43, 0x4f, 0x63, 0xcc, 0xe1, 0xbf, 0x93, 0xa5, 0xb0, 0x7a, 0xac, 0xd6, 0x69, 0x42, 0xce, 0x52, 0x8c, 0xd8, 0x30, 0x18, 0x9f, 0x77, 0xa2, 0xd6, 0xde, 0x5a, 0x3d, 0x59, 0x28, 0x3a, 0x2a, 0x58, 0x25, 0xcb, 0x95, 0x01, 0x9d, 0x04, 0x81, 0x1d, 0x63, 0xfb, 0xb1, 0xf3, 0x0b, 0x3d, 0x68, 0xc1, 0x42, 0x83, 0xc5, 0xc2, 0x27, 0x1e, 0x58, 0x4f, 0x42, 0x89, 0x45, 0x08, 0xb2, 0xf2, 0x8d, 0x26, 0xd1, 0xb3, 0x4d, 0xbd, 0xaf, 0x74, 0xc9, 0x7f, 0xbe, 0x81, 0x46, 0x73, 0xdb, 0x68, 0x45, 0x41, 0xb1, 0xbe, 0xe7, 0x76, 0x31, 0x01, 0xc8, 0x8c, 0xb5, 0x26, 0x9e, 0x2e, 0xde, 0x07, 0x9f, 0x5b, 0x7e, 0x73, 0x36, 0xbf, 0x51, 0x60, 0x98, 0xe0, 0x6e, 0x83, 0x85, 0x21, 0x2c, 0xdb, 0x28, 0x2c, 0x8f, 0x4b, 0xf9, 0x15, 0x08, 0x8f, 0x06, 0xa8, 0xfe, 0x26, 0x2b, 0xea, 0xaf, 0xb0, 0x97, 0x3c, 0xb9, 0xf8, 0x25, 0xef, 0xf5, 0x58, 0xd2, 0xf4, 0xbd, 0x1c, 0x1b, 0x84, 0x29, 0xde, 0xbe, 0xb6, 0xfd, 0x30, 0x47, 0x0c, 0x63, 0x3a, 0x3e, 0x6d, 0x8b, 0x0b, 0x1e, 0x64, 0x5d, 0x8f, 0x64, 0xc9, 0x35, 0x7a, 0xb4, 0xb9, 0xfb, 0x47, 0xe4, 0x50, 0xcd, 0xf6, 0x1a, 0xb1, 0xf6, 0x22, 0x0a, 0xd5, 0x63, 0xb5, 0x20, 0xed, 0x13, 0xfb, 0x43, 0x11, 0x67, 0x89, 0x6d, 0x9f, 0xb1, 0x6f, 0xe8, 0x48, 0x2f, 0x7e, 0xda, 0xbc, 0x08, 0xc2, 0xde, 0x1c, 0x29, 0xa4, 0x50, 0x7d, 0x9c, 0x8e, 0xbc, 0x0d, 0x2b, 0xe2, 0xda, 0xb6, 0x9c, 0x6c, 0x08, 0xd3, 0x3c, 0xf6, 0x71, 0x23, 0x90, 0x07, 0x8f, 0x99, 0x86, 0x85, 0xf8, 0xaa, 0xed, 0x65, 0x99, 0xf3, 0xf5, 0x69, 0xe2, 0x6b, 0x67, 0x47, 0x5c, 0x8d, 0x5d, 0xee, 0x9c, 0xda, 0xa1, 0x56, 0x73, 0x35, 0xf1, 0xe7, 0x2e, 0xb9, 0xf9, 0x70, 0xc5, 0xb4, 0xdd, 0x21, 0x9f, 0x25, 0x23, 0xf4, 0x74, 0x57, 0xc1, 0xfd, 0x09, 0x2e, 0x80, 0xea, 0x4d, 0x90, 0x93, 0x84, 0x06, 0x43, 0xc0, 0xbc, 0x26, 0xd2, 0xfd, 0x3b, 0x03, 0x2e, 0x93, 0x90, 0xb3, 0x4b, 0xd4, 0x58, 0x31, 0x18, 0xc5, 0xa5, 0xc4, 0x3c, 0xe5, 0xb5, 0x23, 0xfb, 0xec, 0xb0, 0xb8, 0xe7, 0x7e, 0x1a, 0xb3, 0xf9, 0xce, 0x5a, 0x25, 0x02, 0x2e, 0xcf, 0xb3, 0x4a, 0xe3, 0x5e, 0xd5, 0xc8, 0x78, 0x0a, 0x89, 0x7c, 0x3e, 0x30, 0x8a, 0xd5, 0xb0, 0x60, 0xc1, 0x52, 0x7c, 0xbc, 0x9e, 0x47, 0x0a, 0xa7, 0xc3, 0xee, 0x11, 0x06, 0x72, 0x89, 0x23, 0x8b, 0x51, 0xb8, 0xbb, 0x5d, 0xc1, 0xf0, 0x38, 0x66, 0x8e, 0xa7, 0x43, 0xad, 0xc1, 0x40, 0x80, 0x58, 0xe4, 0xdf, 0x0d, 0xb1, 0x2b, 0xa2, 0xd4, 0x58, 0x20, 0x95, 0xee, 0x51, 0x13, 0x94, 0x1e, 0x8d, 0x1e, 0xd4, 0x2d, 0x82, 0x73, 0xa6, 0x92, 0x0c, 0xec, 0x74, 0x12, 0xbe, 0x2a, 0x8c, 0x72, 0xb3, 0x99, 0x7d, 0x33, 0x50, 0xe4, 0xeb, 0xad, 0x24, 0x7c, 0xef, 0x1a, 0x41, 0x4b, 0x04, 0xe6, 0x21, 0xa3, 0x1a, 0xa4, 0x13, 0xf4, 0xdc, 0x70, 0xa2, 0xdc, 0x0d, 0xc1, 0x02, 0x43, 0xeb, 0xf7, 0x69, 0x82, 0x7a, 0x99, 0x61, 0x1b, 0x14, 0xaa, 0xce, 0x2b, 0x1b, 0xd1, 0xaa, 0x3a, 0x99, 0xae, 0x51, 0xae, 0x35, 0xb9, 0x8c, 0xe0, 0x43, 0x6e, 0x1e, 0x17, 0x36, 0xf0, 0x9e, 0xf2, 0x83, 0x22, 0x6c, 0x82, 0xee, 0xfb, 0x72, 0x35, 0x22, 0x45, 0x4a, 0xbc, 0xfa, 0x65, 0x44, 0xa1, 0xce, 0x6a, 0x6a, 0xe1, 0x3f, 0x6f, 0xd0, 0x45, 0x72, 0x29, 0xf4, 0xf4, 0xb0, 0x97, 0x0e, 0x1e, 0xe6, 0xa8, 0xb6, 0xc8, 0x44, 0x11, 0x99, 0x6e, 0xd9, 0xfd, 0x0b, 0x04, 0xaf, 0x10, 0x0a, 0xd0, 0xae, 0x5d, 0xff, 0x78, 0x32, 0x09, 0x39, 0x73, 0x2e, 0xaf, 0x65, 0x70, 0x3b, 0xd5, 0xfe, 0x90, 0xc0, 0x9c, 0xf5, 0xba, 0xbd, 0x9d, 0x78, 0xe9, 0x67, 0x87, 0x79, 0xad, 0x1f, 0x77, 0x12, 0x8e, 0x8d, 0x6e, 0xc3, 0x69, 0xc6, 0x22, 0x60, 0x2d, 0x4f, 0x49, 0x1b, 0xa7, 0xa3, 0x8a, 0x14, 0x9d, 0x48, 0xfe, 0x0c, 0x38, 0x9a, 0x0e, 0xbc, 0x7e, 0x5c, 0x6c, 0x01, 0xc5, 0x68, 0x39, 0xd1, 0x33, 0xca, 0x23, 0xf6, 0x12, 0x02, 0x59, 0x3f, 0xe2, 0x11, 0x9d, 0xa0, 0x41, 0x3d, 0xa5, 0x3b, 0x5a, 0xe1, 0xdc, 0x66, 0x00, 0xcb, 0x91, 0x39, 0x60, 0xd4, 0xa8, 0xdb, 0x91, 0xf3, 0x2a, 0x7b, 0xfc, 0xc7, 0x41, 0x66, 0x88, 0x68, 0x54, 0xff, 0x9f, 0x38, 0x03, 0x8c, 0x93, 0x72, 0x4c, 0xab, 0xbe, 0xeb, 0x3d, 0x74, 0x74, 0x38, 0xcf, 0x46, 0x08, 0xfa, 0x72, 0xcf, 0xbf, 0xed, 0xb6, 0xc1, 0x0c, 0xc5, 0x13, 0xa9, 0x76, 0x67, 0x6b, 0xe2, 0xad, 0xc4, 0x06, 0xfa, 0x0c, 0x81, 0xd8, 0xdd, 0x7b, 0x28, 0x3f, 0x15, 0xb7, 0x0d, 0xb3, 0x56, 0x5a, 0x3c, 0xa6, 0x8f, 0x96, 0x20, 0xa4, 0x02, 0x6e, 0x0a, 0x7f, 0x8d, 0x97, 0x5a, 0xb2, 0xf5, 0xa9, 0xd8, 0xb9, 0x0b, 0x72, 0x0c, 0x6c, 0x6c, 0xcc, 0x31, 0x76, 0x55, 0x1a, 0xde, 0xf5, 0x17, 0xd9, 0xb0, 0x57, 0xea, 0x39, 0xab, 0xcd, 0xb7, 0x5f, 0x16, 0x07, 0xdb, 0x36, 0x63, 0x16, 0x8c, 0x6f, 0x09, 0xe3, 0xc0, 0x43, 0xda, 0xd0, 0x77, 0x17, 0xb4, 0x72, 0x50, 0xfc, 0x8e, 0x1d, 0xdd, 0xec, 0x00, 0x2b, 0x21, 0xe4, 0x71, 0xa4, 0xdd, 0x51, 0xd9, 0xe0, 0xdb, 0x14, 0x21, 0x42, 0xf2, 0x90, 0x49, 0x25, 0x55, 0x48, 0x47, 0x58, 0x7b, 0x96, 0x97, 0x42, 0xb2, 0xd5, 0x50, 0xa9, 0x28, 0xba, 0xec, 0xba, 0x52, 0x6d, 0xd0, 0xb1, 0x75, 0xd8, 0xd4, 0xda, 0x81, 0x10, 0x0c, 0xb0, 0x75, 0x57, 0x57, 0x81, 0x7f, 0x8d, 0xf9, 0x29, 0xaf, 0x27, 0x85, 0x45, 0x4a, 0x84, 0x53, 0x78, 0xde, 0x09, 0xe9, 0xf5, 0x2c, 0xd4, 0x91, 0xc3, 0x3a, 0x9c, 0x50, 0xe1, 0xc6, 0x20, 0x66, 0x26, 0x4a, 0x7b, 0x4f, 0x05, 0x89, 0x97, 0x3b, 0xe1, 0xb8, 0xbc, 0x28, 0xa4, 0x31, 0xa8, 0x13, 0xb3, 0xc2, 0xf5, 0xee, 0x10, 0xec, 0x4c, 0xf4, 0xd6, 0x21, 0xab, 0x9b, 0x58, 0xe8, 0x95, 0x7c, 0x85, 0x64, 0x57, 0x81, 0x79, 0x1b, 0x8b, 0xb1, 0x84, 0xd5, 0xe9, 0x86, 0xe1, 0x6f, 0xce, 0x56, 0xe1, 0x8d, 0x1d, 0xa2, 0x4d, 0x54, 0x97, 0xc3, 0x2e, 0xc5, 0x5d, 0x6e, 0x9b, 0x4f, 0x43, 0x0c, 0xf0, 0x36, 0x68, 0x53, 0x9e, 0x2f, 0xbd, 0x5a, 0x8f, 0x3c, 0x30, 0x9f, 0x38, 0x40, 0x58, 0x34, 0x27, 0x18, 0xfc, 0x70, 0x54, 0x7e, 0x70, 0x15, 0xeb, 0x93, 0x29, 0x15, 0x7d, 0xa7, 0x6b, 0xa0, 0x5b, 0x7d, 0x2b, 0x7a, 0x79, 0x10, 0xb4, 0x8b, 0xd9, 0xfa, 0x94, 0x5d, 0xc2, 0x1b, 0x0d, 0xf7, 0x47, 0x18, 0xa9, 0x8f, 0xa2, 0x64, 0x32, 0x17, 0x15, 0x1d, 0x3b, 0xed, 0x3c, 0x32, 0x8a, 0x69, 0x2d, 0x14, 0xae, 0x5a, 0x4a, 0xa4, 0x79, 0xdb, 0x6e, 0x9e, 0x81, 0xa5, 0x32, 0x92, 0xa3, 0x55, 0x3e, 0xfa, 0x05, 0x21, 0x1e, 0x1d, 0xb8, 0x08, 0x5e, 0xee, 0x21, 0x14, 0xc4, 0x38, 0x17, 0x6c, 0x24, 0x1a, 0xdb, 0xbd, 0xf0, 0x37, 0x33, 0xc2, 0xc5, 0xec, 0xe9, 0x92, 0x6d, 0x1c, 0xc0, 0x3e, 0x58, 0x26, 0x26, 0xde, 0x87, 0xc2, 0xef, 0x2c, 0x9d, 0x18, 0x7b, 0x71, 0x05, 0xf7, 0x9f, 0x42, 0x29, 0x8c, 0x18, 0x9b, 0xf6, 0xe9, 0x34, 0x75, 0x59, 0x6f, 0x18, 0x8c, 0x43, 0xcc, 0x5c, 0xd7, 0x45, 0x14, 0xda, 0xa0, 0xcf, 0x11, 0x10, 0xb2, 0x00, 0xab, 0x94, 0x59, 0x36, 0xd6, 0x77, 0x7b, 0x8a, 0x84, 0xff, 0x22, 0xd3, 0x60, 0x66, 0x06, 0x42, 0xa2, 0xe6, 0xdd, 0xc0, 0xe6, 0xb7, 0x4c, 0xe7, 0xc6, 0x88, 0x71, 0xb9, 0xf2, 0x75, 0x96, 0x30, 0x85, 0xaf, 0x5f, 0xa7, 0xdb, 0x2b, 0xe7, 0x17, 0xbc, 0xa6, 0x6c, 0x2b, 0xec, 0xef, 0x53, 0x26, 0xe5, 0xad, 0xf2, 0x03, 0x02, 0xac, 0x51, 0xf7, 0xa5, 0x06, 0x8f, 0x80, 0x9f, 0xc6, 0xd0, 0xed, 0x0f, 0xed, 0xea, 0xf6, 0x5b, 0x61, 0xfc, 0x2b, 0xb3, 0x44, 0xfd, 0x26, 0x1c, 0xde, 0x45, 0x9f, 0xdb, 0x58, 0x2a, 0x12, 0x41, 0xdf, 0x9d, 0xf6, 0xf9, 0xfc, 0x89, 0xa0, 0x86, 0x33, 0xd2, 0xcf, 0x8b, 0x17, 0x10, 0x84, 0xbe, 0x94, 0x72, 0x77, 0x28, 0x58, 0x52, 0x9a, 0x24, 0x9c, 0x3a, 0x55, 0xd5, 0x57, 0x57, 0xb1, 0x3d, 0x03, 0xa6, 0x0d, 0xb7, 0x89, 0x61, 0xa6, 0x1d, 0xc6, 0x61, 0xa4, 0x75, 0xc2, 0xa7, 0x0e, 0xc9, 0x4c, 0x95, 0x2a, 0xa1, 0x65, 0x63, 0x1f, 0x82, 0x2c, 0xf0, 0xad, 0xcf, 0x24, 0xca, 0x89, 0x64, 0x72, 0x1e, 0x26, 0x66, 0x37, 0x36, 0x4c, 0x35, 0x1e, 0xe9, 0xb5, 0x64, 0xd9, 0xe1, 0x8f, 0x42, 0x5e, 0x9d, 0x1a, 0xd6, 0xfe, 0x20, 0xa9, 0x74, 0xa9, 0x85, 0x62, 0xc6, 0x17, 0x20, 0x63, 0x1b, 0x8e, 0xb5, 0x1a, 0x2a, 0x81, 0xc6, 0x21, 0xf9, 0x54, 0x04, 0x56, 0x26, 0x89, 0x90, 0xa0, 0xab, 0xcb, 0x5f, 0x86, 0x8f, 0x9e, 0xf1, 0x17, 0x65, 0xa7, 0xb7, 0x28, 0x63, 0x39, 0x5c, 0x3c, 0xeb, 0x1f, 0x9d, 0xf9, 0x19, 0xdb, 0xaa, 0x6c, 0x18, 0x8b, 0x57, 0xac, 0xec, 0x55, 0xf6, 0xb8, 0x2a, 0xc9, 0x24, 0x04, 0xa7, 0xcc, 0xec, 0x53, 0x28, 0x3d, 0xae, 0x75, 0x39, 0xaa, 0x66, 0x84, 0xc6, 0x94, 0xd7, 0xc2, 0xdc, 0x21, 0x12, 0x73, 0x0c, 0x06, 0x2b, 0x17, 0x40, 0x69, 0x49, 0xfd, 0x78, 0x7b, 0x9a, 0x13, 0x0f, 0xc4, 0x8a, 0xd2, 0x60, 0x9d, 0xa4, 0x0b, 0x3a, 0xf4, 0x3a, 0x9b, 0x0a, 0x79, 0x3e, 0x31, 0xaa, 0x27, 0x63, 0x41, 0x38, 0x4e, 0x46, 0x14, 0x8c, 0x55, 0x80, 0x7b, 0x75, 0xc8, 0xe9, 0x15, 0x64, 0xc8, 0xc7, 0xdd, 0xf4, 0x1d, 0xe9, 0x25, 0x4a, 0x0e, 0x06, 0x4a, 0x1a, 0xc8, 0x88, 0xec, 0x46, 0xd6, 0xfb, 0x6b, 0xb8, 0x94, 0x28, 0xaf, 0xbc, 0x2f, 0xe6, 0x28, 0x76, 0xc0, 0x0a, 0xfc, 0x60, 0x42, 0xef, 0x45, 0xff, 0x76, 0xf8, 0xe1, 0x50, 0x6f, 0x94, 0xaf, 0xa5, 0xd9, 0x4d, 0xe9, 0xa9, 0x7c, 0x2d, 0x1d, 0xb3, 0x78, 0x66, 0xc3, 0x6e, 0x4d, 0x22, 0xd9, 0x0f, 0xcf, 0xf0, 0x87, 0xa7, 0xdc, 0xec, 0x5a, 0x12, 0x65, 0x55, 0x3d, 0x9b, 0xc8, 0x33, 0xfd, 0x83, 0xfc, 0x02, 0xfb, 0x22, 0x0c, 0x1d, 0x7f, 0xff, 0x38, 0xe1, 0x6b, 0x78, 0x47, 0xa8, 0x54, 0x31, 0x36, 0x69, 0x44, 0x64, 0xae, 0x1a, 0xfc, 0x8b, 0x3c, 0x3a, 0x9f, 0x3e, 0xca, 0x85, 0xa1, 0x0d, 0x56, 0x72, 0x63, 0xb5, 0x7b, 0xfa, 0x4f, 0x18, 0x76, 0x57, 0x3a, 0xa7, 0xb0, 0x20, 0x24, 0x9b, 0xb1, 0x8d, 0x01, 0xec, 0x32, 0x9c, 0x84, 0xc1, 0x8d, 0x88, 0x0d, 0xe4, 0x71, 0xe5, 0x1f, 0xe2, 0x0b, 0xae, 0x87, 0xcf, 0x5f, 0xbf, 0xde, 0x57, 0x2f, 0x22, 0x5a, 0x63, 0x5a, 0x9c, 0x85, 0x46, 0xf1, 0x3a, 0x7e, 0x04, 0xec, 0xce, 0xb4, 0xa0, 0x00, 0x90, 0x9a, 0x09, 0x11, 0xb4, 0x6b, 0x53, 0x37, 0xd2, 0x03, 0xd1, 0x59, 0x2f, 0xdb, 0xda, 0xe9, 0xf8, 0x0a, 0x67, 0x6a, 0x83, 0x30, 0x09, 0x66, 0x82, 0x11, 0x10, 0xda, 0x52, 0x61, 0x40, 0xca, 0x86, 0x85, 0xdf, 0x01, 0xc3, 0x0e, 0x68, 0xd0, 0xb7, 0x0a, 0x37, 0x95, 0x30, 0xc3, 0x0f, 0x37, 0x49, 0x27, 0x4a, 0x93, 0xd3, 0x6a, 0x1a, 0xaf, 0xa2, 0x0a, 0xbf, 0xb7, 0xb7, 0x68, 0xe7, 0x8d, 0x4c, 0x50, 0xf0, 0x9c, 0x10, 0x93, 0x1c, 0xdf, 0x83, 0x7b, 0xe7, 0xfa, 0xc3, 0x41, 0xbd, 0x6c, 0x06, 0x10, 0x8d, 0x4c, 0x38, 0x0f, 0x74, 0x04, 0x48, 0x07, 0xdd, 0xba, 0xbe, 0x6f, 0x92, 0x7b, 0xc6, 0x87, 0xae, 0x0c, 0xe9, 0x46, 0x52, 0x97, 0xa7, 0xe6, 0x9a, 0x91, 0xbb, 0x7e, 0xb0, 0x65, 0xac, 0x22, 0xe0, 0xa3, 0xc7, 0xe8, 0xc5, 0x53, 0x99, 0x82, 0x1c, 0x2c, 0x54, 0x9b, 0xa0, 0xcf, 0x6b, 0xd5, 0x9e, 0x18, 0xf9, 0x3c, 0x17, 0x88, 0xb4, 0xfa, 0x01, 0x46, 0x6e, 0xd6, 0x41, 0xf2, 0xdd, 0xf1, 0xea, 0xbc, 0x1d, 0x6c, 0xbb, 0xe2, 0xcb, 0xe6, 0xfc, 0x22, 0xb5, 0x82, 0x9a, 0x89, 0x60, 0x30, 0xdc, 0x1f, 0x42, 0x20, 0x34, 0x05, 0x02, 0x70, 0x60, 0xbd, 0x95, 0x22, 0x0e, 0xeb, 0x29, 0x23, 0x0c, 0x51, 0x95, 0x74, 0x7e, 0xae, 0xed, 0x3a, 0x5d, 0x83, 0x20, 0xd9, 0x55, 0x80, 0x9b, 0xe0, 0x50, 0x25, 0xe5, 0xbd, 0xfb, 0x45, 0x43, 0xce, 0x34, 0x5a, 0x8a, 0xcf, 0x68, 0x2f, 0xde, 0xdc, 0x95, 0x1d, 0x72, 0x6b, 0x69, 0x7d, 0xe6, 0xd5, 0x82, 0x2f, 0x65, 0x31, 0x8e, 0xab, 0xbd, 0x66, 0xb9, 0x39, 0x15, 0x02, 0x0f, 0xa7, 0x62, 0xfc, 0xdb, 0xc1, 0x50, 0xfa, 0xf1, 0x6a, 0xe6, 0x88, 0x56, 0x16, 0x3d, 0x1a, 0x6c, 0x1c, 0x95, 0x6e, 0x93, 0xdc, 0x72, 0xc3, 0x35, 0x4d, 0x22, 0xe1, 0xd5, 0xa2, 0xa6, 0xcf, 0xe7, 0xaf, 0x2a, 0x02, 0x02, 0x2b, 0xb4, 0xaa, 0x42, 0x5c, 0x12, 0xbb, 0x1d, 0x0b, 0xe6, 0x16, 0x9e, 0x2a, 0xc8, 0xf5, 0xd4, 0x41, 0xf4, 0x72, 0x9b, 0x68, 0xd5, 0x3a, 0x53, 0xb1, 0x61, 0x7a, 0x5e, 0x74, 0x33, 0x52, 0xe7, 0x51, 0x62, 0xcb, 0x02, 0xfa, 0x0f, 0x9d, 0x7d, 0x51, 0xf4, 0x66, 0xeb, 0x80, 0xff, 0x83, 0xac, 0x1c, 0xde, 0x5d, 0xc6, 0x3a, 0x47, 0x3e, 0x03, 0x9d, 0xaf, 0x4d, 0x9d, 0x2e, 0x27, 0xb4, 0xd0, 0x69, 0x4a, 0xdc, 0x66, 0x96, 0xe9, 0x77, 0x81, 0xfe, 0x13, 0x25, 0xd6, 0x4d, 0xa2, 0x3e, 0xa5, 0xe3, 0xe0, 0xbb, 0x97, 0x27, 0x49, 0x92, 0x10, 0x36, 0xdc, 0x31, 0x25, 0x5e, 0xba, 0xa3, 0x5f, 0xca, 0x74, 0xbe, 0xe6, 0x57, 0xd0, 0xfa, 0x46, 0x81, 0x2a, 0xe4, 0xf6, 0x9d, 0xd8, 0xcf, 0xb4, 0x8f, 0x89, 0x75, 0x5e, 0x8b, 0x0e, 0x10, 0x9e, 0x1a, 0xa5, 0x17, 0xc4, 0x56, 0x97, 0x9e, 0x38, 0x38, 0xd8, 0xef, 0x4b, 0x82, 0x79, 0xc4, 0x54, 0x2c, 0x2b, 0xed, 0xe2, 0x6a, 0x83, 0x4b, 0x12, 0x6a, 0xa7, 0xff, 0x31, 0xe7, 0x8d, 0x0a, 0x9f, 0xab, 0x49, 0xae, 0xee, 0xc1, 0xa8, 0x87, 0xdf, 0x2d, 0x11, 0xda, 0xd9, 0xf6, 0xa1, 0x12, 0x82, 0x96, 0x64, 0x68, 0xa8, 0xe2, 0x13, 0xf8, 0x25, 0xf3, 0x3d, 0xa0, 0xcd, 0x0e, 0xfb, 0x1f, 0xbc, 0x27, 0xe3, 0xed, 0x72, 0xa9, 0x31, 0xee, 0x61, 0xcc, 0xb9, 0xb3, 0x4d, 0x72, 0x41, 0x5c, 0xb8, 0x2d, 0x6f, 0xae, 0xdf, 0xf7, 0xf4, 0x07, 0x04, 0xf3, 0xcf, 0x86, 0x30, 0x6f, 0xed, 0x0c, 0x61, 0x4e, 0x78, 0x56, 0x2e, 0x85, 0xf1, 0xaf, 0x6a, 0x76, 0x28, 0x0f, 0x4b, 0x14, 0xfa, 0xf2, 0xda, 0x0c, 0x7f, 0xe1, 0xe3, 0x76, 0x66, 0xb2, 0xd6, 0xb5, 0xe4, 0x61, 0xec, 0x21, 0xcd, 0xfa, 0x58, 0x61, 0x96, 0x3b, 0x91, 0x82, 0xd4, 0xf2, 0xd8, 0xac, 0x91, 0x7e, 0x2f, 0xaa, 0x92, 0x2e, 0x89, 0x02, 0x19, 0x02, 0xb8, 0xb4, 0x28, 0xde, 0x58, 0x69, 0xca, 0x8b, 0x31, 0x2d, 0x05, 0xab, 0x28, 0xdd, 0x82, 0x60, 0x72, 0x98, 0xa1, 0x50, 0x17, 0x22, 0x64, 0x4a, 0x4f, 0xb9, 0xad, 0xb7, 0x03, 0x0b, 0x84, 0x32, 0x06, 0xa6, 0xb9, 0xd2, 0x32, 0x2a, 0xda, 0xb6, 0xdd, 0xad, 0x57, 0xde, 0xfb, 0x81, 0x1e, 0x91, 0xa1, 0x75, 0xcc, 0x09, 0x2e, 0x1a, 0x0e, 0x90, 0x74, 0x26, 0xd1, 0x8f, 0x9e, 0x0a, 0xe6, 0x62, 0x75, 0xca, 0x2c, 0xc7, 0x85, 0xfa, 0x2b, 0xe2, 0x52, 0xe7, 0xb6, 0x01, 0xb8, 0x9a, 0x53, 0x71, 0x92, 0x7b, 0x4e, 0x48, 0x37, 0x2d, 0x18, 0x19, 0xb3, 0x91, 0xf5, 0x26, 0x66, 0x56, 0x17, 0xb8, 0xb9, 0x4d, 0x38, 0x7c, 0x03, 0x6e, 0x07, 0x1c, 0x25, 0xe0, 0x9c, 0x7d, 0xcf, 0xc5, 0xe8, 0x0c, 0x90, 0xa4, 0xad, 0xa3, 0xad, 0x7c, 0x40, 0x87, 0x4e, 0xe3, 0x9d, 0x23, 0x4b, 0x72, 0x72, 0x6e, 0xe6, 0xca, 0x6a, 0x6b, 0x5f, 0x49, 0x8d, 0xe5, 0x09, 0x42, 0x72, 0x0c, 0x84, 0xdc, 0x59, 0x7e, 0xad, 0x1c, 0x58, 0xdf, 0x7e, 0x0e, 0x5e, 0x36, 0xb8, 0x31, 0x64, 0x1c, 0x2e, 0x89, 0xd3, 0x6a, 0x81, 0x7d, 0xce, 0x04, 0xc9, 0x99, 0x5e, 0x52, 0x11, 0x20, 0x64, 0xc6, 0xf0, 0x9a, 0x5f, 0x3f, 0xad, 0x8a, 0xec, 0x26, 0xa2, 0x7b, 0x52, 0x32, 0x5f, 0x36, 0x4b, 0x28, 0xdc, 0xd3, 0xfb, 0x72, 0x7a, 0x1d, 0xeb, 0xf9, 0x74, 0xef, 0x66, 0xad, 0x86, 0x84, 0xda, 0x13, 0x35, 0x7e, 0xe3, 0x1d, 0xb0, 0xb3, 0xc2, 0x2a, 0xc9, 0x78, 0xed, 0x5f, 0x56, 0xd9, 0x08, 0x13, 0x84, 0x92, 0x72, 0xd5, 0x1c, 0xfd, 0x90, 0x5e, 0x11, 0xb5, 0x49, 0x52, 0x07, 0x9d, 0x5e, 0x4c, 0x43, 0x4f, 0x25, 0x0a, 0x7b, 0xc5, 0xaf, 0xbd, 0x68, 0x70, 0x1d, 0xe6, 0xe5, 0x79, 0x18, 0x2c, 0xa3, 0x92, 0x76, 0x59, 0x84, 0x72, 0x10, 0xf3, 0x6b, 0x8b, 0x15, 0xc1, 0x17, 0x35, 0x1a, 0x88, 0x35, 0x25, 0x07, 0xaa, 0xd6, 0x02, 0xaf, 0x03, 0xee, 0x64, 0x42, 0x23, 0x1c, 0x81, 0x01, 0x45, 0xb8, 0xb5, 0x90, 0xa4, 0x69, 0x58, 0xe4, 0xaa, 0xd9, 0x45, 0x91, 0x11, 0xed, 0x17, 0x01, 0x64, 0x1a, 0x87, 0x13, 0x5d, 0x52, 0xa3, 0xca, 0xa7, 0x50, 0xb7, 0xfa, 0x79, 0x1f, 0xce, 0x20, 0x58, 0x9c, 0x64, 0x1a, 0x2d, 0x15, 0xc9, 0xfa, 0x1e, 0x19, 0xcd, 0xcc, 0x11, 0x95, 0xfd, 0x1e, 0x9b, 0xce, 0xea, 0xbe, 0x33, 0x1c, 0xa5, 0x58, 0x02, 0x80, 0x8e, 0x95, 0xc5, 0x34, 0xa5, 0x66, 0x85, 0xf0, 0x45, 0x76, 0xf0, 0x49, 0x6b, 0xea, 0x0d, 0xaf, 0xb0, 0xa0, 0x7f, 0x8e, 0xe7, 0xfe, 0x8f, 0x42, 0x0f, 0xc9, 0xaf, 0x56, 0xea, 0xa4, 0x3e, 0x28, 0xbd, 0x66, 0x9d, 0x9f, 0x68, 0x41, 0x45, 0xcc, 0xa4, 0x21, 0xa3, 0x40, 0xa7, 0x96, 0xe1, 0xa3, 0x5d, 0x96, 0x40, 0xde, 0xe1, 0xd7, 0xb2, 0xbc, 0xc6, 0x01, 0xc5, 0xa0, 0x9f, 0xee, 0x08, 0x40, 0x29, 0xde, 0x90, 0x7e, 0x8a, 0x3a, 0x8f, 0xa2, 0x43, 0xd3, 0xd6, 0x19, 0xd2, 0xe6, 0xc0, 0xc6, 0x02, 0x8f, 0xb2, 0x81, 0x79, 0x2f, 0x58, 0x0c, 0x75, 0x55, 0xb3, 0x92, 0x23, 0x68, 0xd0, 0x30, 0x85, 0xcf, 0x95, 0xc5, 0x61, 0x06, 0x4b, 0x94, 0xa5, 0x36, 0x68, 0x4f, 0x3c, 0xa1, 0x1d, 0xcd, 0x10, 0xba, 0x1a, 0x5f, 0xa4, 0x52, 0x77, 0x99, 0xfa, 0x20, 0xb1, 0xf9, 0x66, 0xa4, 0x86, 0x3f, 0x7a, 0x87, 0x19, 0xdd, 0x4e, 0xb8, 0x99, 0x6f, 0x12, 0x41, 0x43, 0x0c, 0x08, 0x22, 0xc0, 0x47, 0x49, 0x71, 0x33, 0x6f, 0xc7, 0xd1, 0x22, 0x98, 0x15, 0x56, 0x6a, 0xa6, 0x27, 0x73, 0x03, 0x95, 0x5d, 0xb8, 0xe3, 0x6f, 0x49, 0x7a, 0xe1, 0x62, 0x20, 0xae, 0x3d, 0x8b, 0x33, 0x6b, 0x55, 0x2b, 0x3c, 0xcc, 0x0c, 0x13, 0x40, 0x86, 0xda, 0x79, 0x7c, 0x2a, 0x91, 0xd9, 0xf1, 0xad, 0x5d, 0x01, 0x7e, 0x84, 0xcc, 0xd9, 0xe0, 0xed, 0x02, 0x1c, 0x23, 0x6e, 0xa3, 0xa9, 0xbb, 0x02, 0x20, 0x6c, 0x77, 0x7e, 0x8d, 0xbe, 0xc7, 0xd3, 0xe4, 0x02, 0x2f, 0x48, 0x4d, 0x78, 0xcb, 0xe0, 0x23, 0x29, 0x4a, 0x4c, 0x66, 0x8a, 0xb3, 0xdb, 0xee, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x08, 0x0f, 0x19, 0x20, 0x29 }; /* * The message has been specially selected so that: * it fails the z_max rejection test on iteration one * it fails the r0_max rejection test on iteration two * it fails the h_ones rejection test on iteration three * it successfully generates the signature on iteration four * Thus, it is an optimal self test in terms of iterations and coverage. * * Refer to FIPS 140-3 IG 10.3.A.15 for details of the testing requirements. */ static const unsigned char ml_dsa_65_msg[] = { 0x23, 0x37, 0x34, 0x37, 0x36, 0x38, 0x23 }; static const ST_KAT_PARAM ml_dsa_key[] = { ST_KAT_PARAM_OCTET(OSSL_PKEY_PARAM_PRIV_KEY, ml_dsa_65_priv_key), ST_KAT_PARAM_END() }; static int ml_dsa_deterministic = 1; static int ml_dsa_encoding = 0; static const ST_KAT_PARAM ml_dsa_sig_init[] = { ST_KAT_PARAM_INT(OSSL_SIGNATURE_PARAM_DETERMINISTIC, ml_dsa_deterministic), ST_KAT_PARAM_INT(OSSL_SIGNATURE_PARAM_MESSAGE_ENCODING, ml_dsa_encoding), ST_KAT_PARAM_END() }; #endif /* OPENSSL_NO_ML_DSA */ #ifndef OPENSSL_NO_SLH_DSA /* * Deterministic SLH_DSA key generation supplies the private key elements and * Half of the public key. */ static const uint8_t slh_dsa_sha2_128f_keygen_entropy[] = { 0xae, 0xd6, 0xf6, 0xf5, 0xc5, 0x40, 0x8b, 0xbf, 0xfa, 0x11, 0x36, 0xbc, 0x90, 0x49, 0xa7, 0x01, 0x4d, 0x4c, 0xe0, 0x71, 0x1e, 0x17, 0x6a, 0x0c, 0x8a, 0x02, 0x35, 0x08, 0xa6, 0x92, 0xc2, 0x07, 0x74, 0xd9, 0x8d, 0x50, 0x00, 0xaf, 0x53, 0xb9, 0x8f, 0x36, 0x38, 0x9a, 0x12, 0x92, 0xbe, 0xd3 }; /* The expected outputs for the public and private key elements */ static const uint8_t slh_dsa_sha2_128f_keygen_priv_pub[] = { 0xAE, 0xD6, 0xF6, 0xF5, 0xC5, 0x40, 0x8B, 0xBF, 0xFA, 0x11, 0x36, 0xBC, 0x90, 0x49, 0xA7, 0x01, 0x4D, 0x4C, 0xE0, 0x71, 0x1E, 0x17, 0x6A, 0x0C, 0x8A, 0x02, 0x35, 0x08, 0xA6, 0x92, 0xC2, 0x07, 0x74, 0xD9, 0x8D, 0x50, 0x00, 0xAF, 0x53, 0xB9, 0x8F, 0x36, 0x38, 0x9A, 0x12, 0x92, 0xBE, 0xD3, 0xF4, 0xA6, 0x50, 0xC5, 0x6C, 0x42, 0x6F, 0xCF, 0xDB, 0x88, 0xE3, 0x35, 0x54, 0x59, 0x44, 0x0C }; static const uint8_t slh_dsa_sha2_128f_keygen_pub[] = { 0x74, 0xD9, 0x8D, 0x50, 0x00, 0xAF, 0x53, 0xB9, 0x8F, 0x36, 0x38, 0x9A, 0x12, 0x92, 0xBE, 0xD3, 0xF4, 0xA6, 0x50, 0xC5, 0x6C, 0x42, 0x6F, 0xCF, 0xDB, 0x88, 0xE3, 0x35, 0x54, 0x59, 0x44, 0x0C }; static const ST_KAT_PARAM slh_dsa_sha2_128f_keygen_init_params[] = { ST_KAT_PARAM_OCTET(OSSL_PKEY_PARAM_SLH_DSA_SEED, slh_dsa_sha2_128f_keygen_entropy), ST_KAT_PARAM_END() }; static const ST_KAT_PARAM slh_dsa_128f_keygen_expected_params[] = { ST_KAT_PARAM_OCTET(OSSL_PKEY_PARAM_PRIV_KEY, slh_dsa_sha2_128f_keygen_priv_pub), ST_KAT_PARAM_OCTET(OSSL_PKEY_PARAM_PUB_KEY, slh_dsa_sha2_128f_keygen_pub), ST_KAT_PARAM_END() }; static const unsigned char slh_dsa_sha2_sig_msg[] = { 0x3f }; static const unsigned char slh_dsa_shake_sig_msg[] = { 0x01, 0x02, 0x03, 0x04 }; static int deterministic = 1; static const ST_KAT_PARAM slh_dsa_sig_params[] = { ST_KAT_PARAM_INT(OSSL_SIGNATURE_PARAM_DETERMINISTIC, deterministic), ST_KAT_PARAM_END() }; static const unsigned char slh_dsa_sha2_128f_priv_pub[] = { 0xd5, 0x21, 0x3b, 0xa4, 0xbb, 0x64, 0x70, 0xf1, 0xb9, 0xed, 0xa8, 0x8c, 0xbc, 0x94, 0xe6, 0x27, 0x7a, 0x58, 0xa9, 0x51, 0xef, 0x7f, 0x2b, 0x81, 0x46, 0x1d, 0xba, 0xc4, 0x1b, 0x5a, 0x6b, 0x83, 0xfa, 0x49, 0x5f, 0xb8, 0x34, 0xde, 0xfe, 0xa7, 0xcc, 0x96, 0xa8, 0x13, 0x09, 0x47, 0x91, 0x35, 0xa6, 0x70, 0x29, 0xe9, 0x06, 0x68, 0xc5, 0xa5, 0x8b, 0x96, 0xe6, 0x01, 0x11, 0x49, 0x1f, 0x3d }; static const ST_KAT_PARAM slh_dsa_sha2_128f_key_params[] = { ST_KAT_PARAM_OCTET(OSSL_PKEY_PARAM_PRIV_KEY, slh_dsa_sha2_128f_priv_pub), ST_KAT_PARAM_END() }; static const unsigned char slh_dsa_shake_128f_priv_pub[] = { 0xbb, 0xc7, 0x43, 0x06, 0xf7, 0x5d, 0xc2, 0xda, 0xf7, 0x37, 0x2b, 0x3c, 0x98, 0x41, 0xa4, 0xd6, 0x85, 0x2c, 0x17, 0xb4, 0x59, 0xf1, 0x69, 0x2b, 0x8e, 0x9a, 0x1a, 0x0d, 0xac, 0xe5, 0xba, 0x26, 0x38, 0x0c, 0x99, 0x30, 0x4a, 0x0d, 0xdd, 0x32, 0xf3, 0x44, 0xb9, 0x51, 0x44, 0xe1, 0xfd, 0xef, 0x60, 0xbb, 0xc2, 0x34, 0x0e, 0x08, 0x77, 0x0f, 0xb4, 0x1a, 0x80, 0xa7, 0x6c, 0xb0, 0x8e, 0x34, }; static const ST_KAT_PARAM slh_dsa_shake_128f_key_params[] = { ST_KAT_PARAM_OCTET(OSSL_PKEY_PARAM_PRIV_KEY, slh_dsa_shake_128f_priv_pub), ST_KAT_PARAM_END() }; /* This is the SHA256 digest of the signature */ static const unsigned char slh_dsa_sha2_128f_sig_digest[] = { 0xd3, 0x53, 0x7e, 0x05, 0xae, 0x63, 0x87, 0x6b, 0xf7, 0x80, 0x15, 0xff, 0x86, 0xcc, 0x9e, 0x28, 0x4f, 0x91, 0xca, 0xbf, 0xac, 0x19, 0x12, 0x98, 0xfb, 0xaa, 0x37, 0x55, 0x96, 0x35, 0x1d, 0x55 }; static const unsigned char slh_dsa_shake_128f_sig_digest[] = { 0xb7, 0xeb, 0x1f, 0x00, 0x33, 0x41, 0xff, 0x11, 0x3f, 0xc7, 0x4d, 0xce, 0x90, 0x6c, 0x55, 0xf7, 0x4a, 0x54, 0x8b, 0x86, 0xc1, 0xb1, 0x08, 0x48, 0x89, 0x77, 0x00, 0x72, 0x03, 0x92, 0xd1, 0xa6, }; #endif /* OPENSSL_NO_SLH_DSA */ /* Hash DRBG inputs for signature KATs */ static const unsigned char sig_kat_entropyin[] = { 0x06, 0x6d, 0xc8, 0xce, 0x75, 0xb2, 0x89, 0x66, 0xa6, 0x85, 0x16, 0x3f, 0xe2, 0xa4, 0xd4, 0x27, 0xfb, 0xdb, 0x61, 0x66, 0x50, 0x61, 0x6b, 0xa2, 0x82, 0xfc, 0x33, 0x2b, 0x4e, 0x6f, 0x12, 0x20 }; static const unsigned char sig_kat_nonce[] = { 0x55, 0x9f, 0x7c, 0x64, 0x89, 0x70, 0x83, 0xec, 0x2d, 0x73, 0x70, 0xd9, 0xf0, 0xe5, 0x07, 0x1f }; static const unsigned char sig_kat_persstr[] = { 0x88, 0x6f, 0x54, 0x9a, 0xad, 0x1a, 0xc6, 0x3d, 0x18, 0xcb, 0xcc, 0x66, 0x85, 0xda, 0xa2, 0xc2, 0xf7, 0x9e, 0xb0, 0x89, 0x4c, 0xb4, 0xae, 0xf1, 0xac, 0x54, 0x4f, 0xce, 0x57, 0xf1, 0x5e, 0x11 }; static const ST_KAT_SIGN st_kat_sign_tests[] = { { OSSL_SELF_TEST_DESC_SIGN_RSA, "RSA", "RSA-SHA256", 0, rsa_crt_key, ITM_STR(rsa_sig_msg), ITM(sig_kat_entropyin), ITM(sig_kat_nonce), ITM(sig_kat_persstr), ITM(rsa_expected_sig) }, #ifndef OPENSSL_NO_EC { OSSL_SELF_TEST_DESC_SIGN_ECDSA, "EC", "ECDSA-SHA256", 0, ecdsa_prime_key, ITM_STR(rsa_sig_msg), ITM(sig_kat_entropyin), ITM(sig_kat_nonce), ITM(sig_kat_persstr), ITM(ecdsa_prime_expected_sig) }, # ifndef OPENSSL_NO_EC2M { OSSL_SELF_TEST_DESC_SIGN_ECDSA, "EC", "ECDSA-SHA256", 0, ecdsa_bin_key, ITM_STR(rsa_sig_msg), ITM(sig_kat_entropyin), ITM(sig_kat_nonce), ITM(sig_kat_persstr), ITM(ecdsa_bin_expected_sig) }, # endif # ifndef OPENSSL_NO_ECX { OSSL_SELF_TEST_DESC_SIGN_EDDSA, "ED448", "ED448", 0, ed448_key, ITM(ecx_sig_msg), NULL, 0, NULL, 0, NULL, 0, ITM(ed448_expected_sig), }, { OSSL_SELF_TEST_DESC_SIGN_EDDSA, "ED25519", "ED25519", 0, ed25519_key, ITM(ecx_sig_msg), NULL, 0, NULL, 0, NULL, 0, ITM(ed25519_expected_sig), }, # endif /* OPENSSL_NO_ECX */ #endif /* OPENSSL_NO_EC */ #ifndef OPENSSL_NO_DSA { OSSL_SELF_TEST_DESC_SIGN_DSA, "DSA", "DSA-SHA256", SIGNATURE_MODE_VERIFY_ONLY, dsa_key, ITM_STR(rsa_sig_msg), ITM(sig_kat_entropyin), ITM(sig_kat_nonce), ITM(sig_kat_persstr), ITM(dsa_expected_sig) }, #endif /* OPENSSL_NO_DSA */ #ifndef OPENSSL_NO_ML_DSA { OSSL_SELF_TEST_DESC_SIGN_ML_DSA, "ML-DSA-65", "ML-DSA-65", 0, ml_dsa_key, ITM(ml_dsa_65_msg), NULL, 0, NULL, 0, NULL, 0, ITM(ml_dsa_65_sig), ml_dsa_sig_init, ml_dsa_sig_init }, #endif /* OPENSSL_NO_ML_DSA */ #ifndef OPENSSL_NO_SLH_DSA /* * FIPS 140-3 IG 10.3.A.16 Note 29 says: * * It is recommended (but not required) that if the module implements * both "s" and "f" algorithms, the module self-test at least one of * each "s" and "f" algorithm. * * Because the "s" version is so slow, we only test the "f" versions * here. */ { OSSL_SELF_TEST_DESC_SIGN_SLH_DSA, "SLH-DSA-SHA2-128f", "SLH-DSA-SHA2-128f", SIGNATURE_MODE_SIG_DIGESTED, slh_dsa_sha2_128f_key_params, ITM(slh_dsa_sha2_sig_msg), NULL, 0, NULL, 0, NULL, 0, ITM(slh_dsa_sha2_128f_sig_digest), slh_dsa_sig_params, slh_dsa_sig_params }, { OSSL_SELF_TEST_DESC_SIGN_SLH_DSA, "SLH-DSA-SHAKE-128f", "SLH-DSA-SHAKE-128f", SIGNATURE_MODE_SIG_DIGESTED, slh_dsa_shake_128f_key_params, ITM(slh_dsa_shake_sig_msg), NULL, 0, NULL, 0, NULL, 0, ITM(slh_dsa_shake_128f_sig_digest), slh_dsa_sig_params, slh_dsa_sig_params }, #endif /* OPENSSL_NO_SLH_DSA */ }; #if !defined(OPENSSL_NO_ML_DSA) static const ST_KAT_PARAM ml_dsa_keygen_params[] = { ST_KAT_PARAM_OCTET(OSSL_PKEY_PARAM_ML_DSA_SEED, sig_kat_entropyin), ST_KAT_PARAM_END() }; #endif /*- KEM SELF TEST DATA */ /* * Test case generated via the OpenSSL commands: * * openssl genpkey -algorithm ML-KEM-512 -out priv-ml-kem-512.pem * openssl pkey -in priv-ml-kem-512.pem -pubout -out pub-ml-kem-512.pem * openssl pkeyutl -encap -inkey pub-ml-kem-512.pem \ * -pkeyopt ikme:00000000000000000000000000000000 -secret good.dat \ * -out ctext.dat * openssl pkeyutl -decap -inkey priv-ml-kem-512.pem \ * -secret goodcmp.dat -in ctext.dat * apps/openssl pkeyutl -decap -inkey priv-ml-kem-512.pem \ * -secret implicit-reject.dat -in <(head -c 768 /dev/zero) * openssl pkey -in priv-ml-kem-512.pem -text | * sed '1,/^priv:/d; /^pub:/,$d' | * tr -d ' :\n' | * xxd -r -p | * tail -c 32 > z.dat * (cat z.dat; head -c 768 /dev/zero) | * openssl dgst -shake256 -xoflen 32 -binary > expected.dat */ #ifndef OPENSSL_NO_ML_KEM static const unsigned char ml_kem_512_cipher_text[] = { 0x6b, 0xc5, 0x04, 0x00, 0x27, 0x7a, 0xbb, 0x7e, 0x6b, 0xf9, 0xfb, 0x56, 0x82, 0x01, 0x75, 0xeb, 0xb7, 0xb9, 0xf4, 0xf2, 0x82, 0x2c, 0x6d, 0x0a, 0xe0, 0x80, 0xa3, 0x49, 0x92, 0x0f, 0x6d, 0x00, 0x8e, 0xba, 0x35, 0xb5, 0x42, 0xb9, 0xd7, 0xed, 0x89, 0xcb, 0xfd, 0x38, 0xd7, 0x9f, 0x55, 0x3b, 0xf0, 0x8e, 0x63, 0x80, 0x95, 0xcf, 0x0d, 0x4f, 0x50, 0x40, 0xac, 0x1d, 0x1b, 0xdc, 0x24, 0x84, 0x3b, 0x18, 0xc2, 0x77, 0x9f, 0x24, 0x11, 0x81, 0xa6, 0xcc, 0xd8, 0xf4, 0xe8, 0x00, 0xdc, 0x26, 0x61, 0x36, 0xd1, 0xb6, 0x5d, 0x9c, 0x12, 0x6d, 0xf5, 0xe7, 0x93, 0xc8, 0x6d, 0xac, 0xaf, 0x3c, 0x78, 0x3f, 0xa9, 0xc1, 0x00, 0x6f, 0x08, 0x29, 0x4f, 0x1a, 0x4d, 0x3b, 0xb4, 0x4b, 0x6f, 0xc2, 0x09, 0x00, 0x4b, 0xc1, 0xf0, 0xe6, 0x7f, 0x48, 0x48, 0x09, 0x40, 0xf2, 0x0a, 0x86, 0x18, 0xbf, 0xc6, 0x4e, 0xb2, 0xb0, 0xab, 0xfe, 0x1b, 0xea, 0x91, 0x58, 0x8c, 0x18, 0x6e, 0x30, 0xe8, 0x33, 0x87, 0x29, 0x26, 0xef, 0xe9, 0x0c, 0x3b, 0x8b, 0x0c, 0x99, 0x40, 0x53, 0xb9, 0x30, 0xba, 0x17, 0xb3, 0x8a, 0x74, 0x59, 0x5d, 0x4c, 0x76, 0x1a, 0xd3, 0x3f, 0xe4, 0xf7, 0xa3, 0x0f, 0x3a, 0x2c, 0x85, 0xc1, 0x46, 0xf0, 0xa4, 0x91, 0xa3, 0x12, 0xb2, 0xa4, 0x4b, 0x88, 0x8d, 0x1c, 0x85, 0xb1, 0xe4, 0x41, 0x1f, 0x9d, 0xb7, 0x91, 0x2f, 0x60, 0x98, 0xfd, 0xfc, 0x29, 0x89, 0x11, 0x7d, 0x16, 0x09, 0x9e, 0x76, 0xf1, 0x9c, 0xb3, 0x50, 0xb9, 0xd0, 0x02, 0xd2, 0xa2, 0x0d, 0xdd, 0xee, 0x90, 0x47, 0x0d, 0xb9, 0x4a, 0x53, 0x11, 0xa2, 0x4f, 0x13, 0x5a, 0x40, 0xdc, 0xc6, 0xfe, 0xd7, 0x28, 0x36, 0xec, 0xa0, 0x5e, 0xab, 0xc1, 0x7d, 0x19, 0x33, 0x59, 0xe2, 0xe4, 0xea, 0x26, 0x67, 0x2f, 0xe5, 0x05, 0xd8, 0x34, 0x6e, 0x3c, 0xab, 0x63, 0x8b, 0x24, 0x16, 0xc7, 0x1b, 0x2a, 0x9b, 0xe5, 0x04, 0x78, 0x98, 0x6c, 0x6c, 0x1e, 0x94, 0xe3, 0x7f, 0x86, 0x52, 0xc0, 0x17, 0x56, 0x8d, 0x01, 0x7a, 0x28, 0x81, 0x07, 0x3d, 0x61, 0x2a, 0xcd, 0xc8, 0xb6, 0x7e, 0x5b, 0xad, 0xa8, 0x90, 0xbd, 0x0c, 0x95, 0xb5, 0x09, 0x9d, 0x7c, 0x34, 0x8c, 0x74, 0x8f, 0x8e, 0x7c, 0x28, 0x6c, 0xe2, 0x2f, 0xa2, 0x87, 0x7f, 0x80, 0x43, 0x46, 0x1c, 0xb2, 0x1c, 0x5a, 0xd2, 0xec, 0xad, 0xf9, 0x55, 0xe3, 0x6b, 0x19, 0x54, 0x08, 0x84, 0x1a, 0x34, 0x82, 0xf4, 0x9c, 0xec, 0x3d, 0x65, 0xf9, 0x78, 0x7f, 0x37, 0x47, 0xcf, 0xf1, 0xcb, 0x15, 0xf2, 0xac, 0xff, 0x3b, 0x8f, 0xa0, 0x8c, 0x25, 0x88, 0x5c, 0x38, 0x23, 0x9a, 0x27, 0x16, 0x6a, 0xdf, 0xa3, 0x98, 0x1d, 0x16, 0x33, 0x4b, 0x4f, 0xfb, 0x83, 0x85, 0x66, 0x76, 0x03, 0xb9, 0xb5, 0x46, 0x21, 0xb9, 0xf3, 0xf4, 0xf1, 0x3a, 0x85, 0xec, 0x9e, 0x56, 0x6a, 0xb6, 0x1d, 0xcc, 0xca, 0xfb, 0x11, 0xae, 0x47, 0x7d, 0x93, 0xa5, 0xbc, 0x90, 0x32, 0xde, 0xa1, 0xa5, 0x1e, 0x5d, 0x52, 0x17, 0x98, 0x0a, 0x8b, 0xc4, 0x1a, 0x28, 0x7c, 0x9c, 0x22, 0x3e, 0x33, 0x06, 0x40, 0x77, 0xe5, 0x22, 0x49, 0x86, 0xf9, 0x3c, 0xc5, 0xc1, 0xb9, 0x77, 0x25, 0x53, 0x66, 0x5a, 0x18, 0x83, 0x5a, 0x2b, 0xbf, 0xac, 0x04, 0x70, 0x26, 0xe8, 0x2b, 0xb6, 0x0c, 0xe8, 0x00, 0x95, 0xbb, 0x08, 0x75, 0xf3, 0x37, 0x31, 0x2e, 0xef, 0x28, 0x8d, 0x58, 0x92, 0xd4, 0xfd, 0xd7, 0x02, 0xce, 0x8f, 0x11, 0x83, 0x17, 0x53, 0x19, 0x44, 0xd7, 0xd5, 0x6d, 0x44, 0x04, 0x3a, 0x0a, 0x01, 0x46, 0xf2, 0xd2, 0xa5, 0x05, 0x88, 0xa0, 0xd9, 0x0d, 0xe1, 0xa0, 0x7a, 0xf2, 0x20, 0x2e, 0x5b, 0x05, 0xe4, 0x2b, 0x11, 0x3d, 0xb3, 0x82, 0x64, 0x3b, 0xef, 0xc1, 0x53, 0xba, 0x9f, 0x7f, 0x29, 0x59, 0x87, 0x39, 0x52, 0xda, 0x7b, 0xff, 0xd7, 0xdd, 0xa1, 0xa9, 0x9f, 0xa1, 0xe2, 0x38, 0x74, 0xb0, 0x94, 0xdc, 0xc5, 0xb5, 0xf3, 0x61, 0xdf, 0x92, 0x62, 0xe1, 0x96, 0x87, 0x6d, 0xb4, 0x2c, 0xc7, 0xf0, 0x38, 0xe9, 0x5e, 0xfc, 0xff, 0x4c, 0x01, 0xc7, 0x59, 0x39, 0xe5, 0x9b, 0xfb, 0xf5, 0x2b, 0x1b, 0xe5, 0xf8, 0x25, 0x06, 0x07, 0xc7, 0x82, 0x46, 0x2a, 0x99, 0xd0, 0xa9, 0x67, 0x81, 0xd7, 0xa2, 0x29, 0x96, 0x1a, 0x94, 0x8e, 0x7d, 0x51, 0x76, 0x99, 0xad, 0x61, 0xec, 0xb6, 0xc0, 0x58, 0x8e, 0xd0, 0x9d, 0xff, 0x58, 0x57, 0x1b, 0x2e, 0xad, 0x65, 0xd8, 0xde, 0xa5, 0xfa, 0x81, 0x4b, 0x2c, 0x06, 0x1b, 0xfe, 0x49, 0x20, 0x4d, 0x5e, 0x1b, 0xb7, 0x40, 0x96, 0xaa, 0x81, 0x25, 0xeb, 0x84, 0xdb, 0xea, 0x5d, 0x0b, 0xaf, 0xf9, 0x8e, 0x41, 0xa6, 0xdd, 0x91, 0x3a, 0x68, 0x54, 0xb7, 0x2e, 0xb1, 0x74, 0xff, 0xf5, 0x0d, 0xa7, 0x3c, 0xc7, 0x30, 0x5b, 0x55, 0xc6, 0x2d, 0xc8, 0x4c, 0xb4, 0xad, 0xcc, 0xd0, 0xa1, 0x1b, 0x41, 0xc7, 0x23, 0xe8, 0xda, 0xff, 0xb7, 0x3a, 0x12, 0xc2, 0xdc, 0x39, 0x7c, 0xf4, 0xb9, 0x50, 0x00, 0x53, 0x88, 0xc8, 0x77, 0x49, 0xfd, 0x70, 0x3d, 0xe0, 0xaa, 0x0c, 0x28, 0xd4, 0xa2, 0xec, 0x82, 0x5d, 0xda, 0xe8, 0x05, 0x2f, 0xe8, 0x9c, 0x21, 0x39, 0x3a, 0x22, 0x2f, 0x0a, 0x5c, 0x6d, 0x01, 0xdf, 0xc8, 0x9f, 0x46, 0xf7, 0x15, 0x02, 0xad, 0x19, 0x35, 0x63, 0x55, 0x58, 0xf5, 0x7a, 0x46, 0xc9, 0x7a, 0xe6, 0x33, 0x84, 0x48, 0x2b, 0xf0, 0xe7, 0xc5, 0x72, 0x98, 0x43, 0x6a, 0x99, 0xba, 0x00, 0x57, 0x4f, 0xaa, 0x0a }; static const unsigned char ml_kem_512_private_key[] = { 0x87, 0xca, 0x19, 0x93, 0xb6, 0x4d, 0x89, 0x32, 0xae, 0x3b, 0x22, 0x52, 0x82, 0xa1, 0xb3, 0xc1, 0x37, 0x65, 0xdc, 0xc1, 0x22, 0x4c, 0x43, 0x77, 0x33, 0x0a, 0x04, 0xec, 0xec, 0x0b, 0x25, 0x05, 0x40, 0x07, 0x53, 0x82, 0xbe, 0x37, 0x52, 0x53, 0x12, 0x87, 0x7d, 0x77, 0x69, 0xfd, 0x59, 0x4f, 0xbd, 0x16, 0x42, 0x82, 0x58, 0x9d, 0xee, 0x5c, 0x0f, 0x2c, 0x14, 0x7f, 0xc6, 0x2a, 0x95, 0x42, 0x10, 0x3c, 0x08, 0xbc, 0xcc, 0xa0, 0x05, 0x82, 0xe9, 0xc5, 0x26, 0x81, 0xfa, 0xb8, 0x79, 0x78, 0x5b, 0x3e, 0x79, 0x49, 0x68, 0x44, 0xb3, 0x7b, 0xf5, 0x26, 0x62, 0x7a, 0x8a, 0x3c, 0xd8, 0x82, 0x1f, 0x16, 0x1d, 0x92, 0x99, 0xac, 0xc4, 0xa9, 0xb9, 0x30, 0x32, 0x6b, 0x6b, 0x67, 0x3d, 0x16, 0x13, 0x1d, 0xf0, 0x98, 0x94, 0x42, 0x90, 0x68, 0xfc, 0x65, 0xa3, 0xe5, 0x16, 0x22, 0x09, 0x64, 0xc0, 0x7d, 0x54, 0x03, 0x47, 0x89, 0xbe, 0xae, 0x61, 0x4b, 0x13, 0xa1, 0xcd, 0xad, 0xbc, 0x20, 0x5e, 0x36, 0x36, 0x34, 0x41, 0x1d, 0x5b, 0x3a, 0x26, 0x91, 0x80, 0x75, 0xe0, 0x63, 0x9d, 0xd6, 0x35, 0xc9, 0x28, 0x81, 0xa4, 0x6e, 0xfb, 0x95, 0x01, 0x11, 0x8f, 0xcc, 0x18, 0xb3, 0x9a, 0x91, 0x66, 0xa6, 0x37, 0x6c, 0xeb, 0x71, 0x42, 0x29, 0xec, 0x71, 0xa4, 0x99, 0x6d, 0x92, 0x97, 0x9d, 0x94, 0x64, 0x6e, 0xc3, 0xf0, 0x5d, 0xa5, 0x49, 0x8f, 0x66, 0xa5, 0x0a, 0x9a, 0xb9, 0xcf, 0x85, 0x20, 0xa7, 0x28, 0xe1, 0xc2, 0x10, 0x08, 0x72, 0x58, 0x71, 0x56, 0x3e, 0x7b, 0x47, 0x46, 0x81, 0x7d, 0x74, 0xfa, 0xb2, 0xb6, 0xf2, 0xa0, 0xe3, 0x4a, 0x0a, 0x5e, 0x95, 0x2b, 0x32, 0xf1, 0x07, 0x2c, 0x30, 0x5e, 0x81, 0x84, 0x58, 0xf3, 0x42, 0x34, 0xdb, 0xaa, 0xc4, 0x06, 0xcb, 0x63, 0x72, 0xfa, 0x01, 0x86, 0xe8, 0xca, 0xd7, 0x73, 0x1d, 0xac, 0xd8, 0x64, 0x60, 0x66, 0xb1, 0x19, 0xb1, 0x59, 0xac, 0x78, 0x21, 0xab, 0x9a, 0x62, 0xbf, 0xe8, 0x1b, 0xd1, 0xdc, 0x75, 0x08, 0xa4, 0x9e, 0x22, 0x54, 0xa8, 0x36, 0x68, 0x4b, 0xb7, 0x22, 0xa3, 0xbc, 0x04, 0x09, 0xe2, 0xe9, 0x4d, 0xce, 0xf5, 0x46, 0x69, 0x1a, 0x47, 0x80, 0xb2, 0xa5, 0xa0, 0x24, 0xcf, 0x0d, 0x60, 0x95, 0x99, 0x33, 0xad, 0x6a, 0x58, 0x7a, 0x56, 0x53, 0x86, 0x44, 0xa8, 0x3c, 0x1f, 0x92, 0x55, 0x3f, 0x3a, 0x3b, 0x5f, 0x81, 0xaa, 0x0c, 0xc4, 0x4b, 0x1a, 0xe3, 0x61, 0x8a, 0xd0, 0x5d, 0x29, 0x87, 0xb6, 0x7d, 0x1c, 0x85, 0xa5, 0x14, 0xb0, 0xde, 0x1c, 0x8d, 0x5c, 0xc1, 0x5c, 0x04, 0xfc, 0x77, 0xad, 0x03, 0x55, 0x96, 0xe0, 0xa7, 0x43, 0xb5, 0x95, 0x9a, 0xd5, 0x22, 0xef, 0x13, 0x5f, 0x14, 0x9c, 0x0e, 0x7e, 0x56, 0x89, 0x37, 0x33, 0xc9, 0x00, 0x54, 0x7e, 0xea, 0x32, 0x4f, 0x02, 0x85, 0xcd, 0xe5, 0x9c, 0x25, 0x00, 0x3b, 0xad, 0xc2, 0x72, 0x3a, 0x38, 0x66, 0x95, 0xf9, 0xf4, 0x22, 0x1f, 0x50, 0x19, 0x20, 0x6a, 0x31, 0x03, 0xf8, 0x97, 0x91, 0xf0, 0x42, 0xbb, 0xc0, 0x86, 0xde, 0x56, 0x93, 0xf2, 0x78, 0x9b, 0xc9, 0x98, 0x16, 0x47, 0x83, 0x67, 0x55, 0x92, 0x4e, 0x5a, 0xfa, 0x5d, 0x88, 0xf9, 0xc8, 0xef, 0xa8, 0x21, 0x34, 0x58, 0x5f, 0xca, 0xbb, 0x52, 0x98, 0xbc, 0x5c, 0xf5, 0xa7, 0xae, 0xc5, 0xfc, 0x78, 0xf9, 0xa5, 0x30, 0x16, 0x68, 0x9d, 0x62, 0x17, 0x41, 0x7a, 0x95, 0xcf, 0x27, 0xb6, 0x6d, 0xae, 0x58, 0xa7, 0x28, 0x8c, 0x8f, 0xc3, 0x28, 0xac, 0x06, 0x79, 0x9d, 0x94, 0xc4, 0x9d, 0xed, 0xb2, 0x61, 0xf4, 0x44, 0x86, 0xec, 0x12, 0xc3, 0x13, 0x97, 0xa7, 0x8b, 0x9a, 0x63, 0x2e, 0xf1, 0x66, 0x08, 0x84, 0x32, 0xf6, 0x15, 0x3b, 0x91, 0xca, 0xce, 0xf7, 0x40, 0x53, 0xa9, 0x28, 0x11, 0x63, 0xa0, 0x23, 0x2e, 0xc4, 0x44, 0x28, 0x05, 0x01, 0x02, 0x74, 0xcf, 0x9c, 0x3a, 0x1a, 0xbc, 0x93, 0x8a, 0x2c, 0xe8, 0x9a, 0xca, 0xe1, 0x74, 0x62, 0x03, 0x88, 0xc7, 0x12, 0x20, 0x96, 0x3c, 0x4d, 0x10, 0x79, 0x28, 0x6f, 0x7b, 0xa8, 0x1b, 0xfb, 0x5e, 0x57, 0x17, 0xcc, 0x6d, 0xd0, 0x72, 0x8a, 0xb2, 0x70, 0xa3, 0x0a, 0x88, 0x03, 0x5b, 0x88, 0x5d, 0x35, 0x12, 0x8e, 0xac, 0xc1, 0x81, 0xca, 0xb7, 0x2b, 0xb1, 0x96, 0xf6, 0x35, 0xce, 0xbb, 0x75, 0xad, 0x0d, 0xd0, 0xba, 0x4e, 0x43, 0x5b, 0x31, 0x08, 0x93, 0x32, 0x72, 0x63, 0x58, 0xc5, 0xa2, 0x70, 0x95, 0x12, 0x8f, 0xf2, 0xc1, 0x61, 0xeb, 0x22, 0xe9, 0x4a, 0x65, 0xa5, 0x48, 0x5d, 0x4c, 0x11, 0x78, 0x69, 0x0b, 0x1f, 0x39, 0x2b, 0x7f, 0x63, 0x77, 0xad, 0x96, 0x6b, 0x67, 0x80, 0x90, 0x70, 0x57, 0x2b, 0xbc, 0x68, 0x9c, 0xaa, 0xb2, 0xd8, 0x3c, 0xbf, 0xd6, 0x4f, 0xc4, 0x28, 0x65, 0x74, 0x54, 0x84, 0x43, 0x9a, 0x1c, 0x96, 0x50, 0x02, 0x97, 0xc6, 0xcf, 0xb0, 0xb1, 0x1d, 0x98, 0x9a, 0x32, 0x94, 0x73, 0x88, 0x94, 0x78, 0x2d, 0x5f, 0x25, 0x05, 0x5f, 0xa6, 0x96, 0x7a, 0xc8, 0x3a, 0xdf, 0xa8, 0x19, 0xb2, 0x53, 0x53, 0x05, 0xf9, 0x31, 0xdc, 0x58, 0x6c, 0xd1, 0x3a, 0x9b, 0x47, 0x3b, 0x7d, 0x87, 0xe5, 0xb4, 0xb2, 0xd9, 0x96, 0x2a, 0x59, 0x90, 0x3c, 0xcc, 0xad, 0xdc, 0xa2, 0x57, 0x87, 0x71, 0xc6, 0x7e, 0x5a, 0x49, 0x98, 0xc8, 0x94, 0x29, 0x30, 0x7b, 0x0e, 0x01, 0x97, 0x53, 0x18, 0x32, 0x50, 0x73, 0x9e, 0x14, 0x47, 0x97, 0xbd, 0xcc, 0x22, 0xab, 0x02, 0x95, 0xd7, 0xc5, 0x32, 0xdf, 0x17, 0x84, 0x86, 0x77, 0x41, 0x6e, 0x95, 0x4d, 0x66, 0xf9, 0xb0, 0x9e, 0x12, 0x81, 0x53, 0x2a, 0x2e, 0x8f, 0x0c, 0x6a, 0xbe, 0x00, 0x37, 0xe7, 0xe8, 0x11, 0x90, 0x97, 0xc9, 0xec, 0x84, 0x5a, 0xa0, 0x69, 0x85, 0xc0, 0x88, 0x55, 0x2c, 0x41, 0xb6, 0x15, 0x17, 0x36, 0x42, 0xc1, 0x02, 0x51, 0xc0, 0x6e, 0x91, 0xa2, 0x5c, 0x24, 0x3c, 0x02, 0x63, 0xb6, 0x75, 0xc7, 0x20, 0x7d, 0x58, 0x70, 0x1d, 0x13, 0xa5, 0x2e, 0xab, 0x92, 0x56, 0x5e, 0xf1, 0xa1, 0xde, 0xfb, 0xae, 0xfe, 0x4c, 0x0b, 0x03, 0xf5, 0x04, 0x44, 0xa3, 0xbe, 0x20, 0xb1, 0x71, 0x31, 0x0b, 0xa3, 0xf2, 0x08, 0x52, 0xf3, 0xa2, 0xa1, 0x8e, 0x72, 0x29, 0x40, 0x70, 0x15, 0x64, 0x60, 0x52, 0xd2, 0xe7, 0x3a, 0xbe, 0xe3, 0x18, 0xd7, 0x55, 0x89, 0x9c, 0x78, 0x4a, 0x6f, 0xb5, 0xaa, 0xb1, 0x7c, 0x90, 0x2c, 0xb6, 0x8a, 0xfa, 0x36, 0x57, 0xb9, 0x01, 0x2e, 0x1b, 0xb8, 0xb6, 0xaa, 0xc2, 0x68, 0x9a, 0xa4, 0x8c, 0x2d, 0x42, 0x62, 0xbb, 0x29, 0x63, 0xb0, 0x6a, 0x24, 0x22, 0x82, 0x54, 0x1c, 0xf6, 0x14, 0x19, 0xd9, 0x0e, 0x2b, 0xd3, 0x66, 0xbe, 0xe7, 0xa4, 0x36, 0x9b, 0x72, 0x41, 0xa6, 0x6b, 0xf2, 0x64, 0x5d, 0x8e, 0x90, 0x4c, 0x3f, 0x7b, 0x30, 0x0c, 0x04, 0x1d, 0x56, 0x87, 0x39, 0x3d, 0x2c, 0xa9, 0x29, 0x75, 0xcb, 0xfd, 0xc0, 0x18, 0xdd, 0xc6, 0x0a, 0xf5, 0x62, 0x00, 0x9e, 0xb0, 0x88, 0x8e, 0x5a, 0x05, 0x76, 0x24, 0x6a, 0xce, 0x74, 0x5b, 0xb1, 0x63, 0x40, 0x8b, 0x5a, 0x9a, 0xe3, 0xc1, 0x94, 0xa8, 0x5c, 0x21, 0x90, 0x7b, 0x37, 0xb1, 0x62, 0x8e, 0xcd, 0x9a, 0x15, 0xec, 0x20, 0x24, 0x87, 0x30, 0x27, 0x34, 0x44, 0xb0, 0xa2, 0xf4, 0x54, 0xf9, 0xb4, 0x73, 0x0f, 0x33, 0x91, 0x50, 0x47, 0x6e, 0xe0, 0x70, 0x98, 0xf6, 0xbc, 0x1b, 0x97, 0xcc, 0x1b, 0xd3, 0xb8, 0xc1, 0xa2, 0xeb, 0x0e, 0x50, 0xa7, 0x82, 0xf2, 0x11, 0x5d, 0xf6, 0x17, 0x49, 0x6f, 0x6c, 0x6f, 0x8c, 0x09, 0xb0, 0x5f, 0x88, 0x8d, 0x9e, 0x93, 0x3d, 0x28, 0x77, 0x46, 0xc6, 0x31, 0xb3, 0x10, 0x87, 0x26, 0xb0, 0xc4, 0xa7, 0xc8, 0x8b, 0x09, 0xc8, 0x60, 0xac, 0xd7, 0x52, 0x35, 0x70, 0xc8, 0x02, 0xbd, 0x38, 0x72, 0x43, 0x16, 0x2d, 0x12, 0x8c, 0xa2, 0x29, 0x4c, 0x83, 0x43, 0x18, 0xcc, 0x21, 0xfb, 0x14, 0xd2, 0xab, 0x37, 0x3f, 0x22, 0x4e, 0x3f, 0xd4, 0x98, 0x43, 0x85, 0x95, 0x09, 0xf4, 0xca, 0x1a, 0x1a, 0x56, 0x6c, 0x05, 0x67, 0x88, 0xa3, 0xaa, 0x48, 0x4a, 0xaa, 0xbd, 0xf1, 0xa0, 0x8f, 0x1b, 0x44, 0xc7, 0x56, 0xab, 0x2a, 0x0c, 0x8b, 0xc5, 0x85, 0x1e, 0xe2, 0xeb, 0x23, 0x03, 0x4c, 0x2e, 0xaa, 0x5a, 0xc1, 0x5f, 0x89, 0x75, 0x1b, 0xd5, 0xca, 0xe1, 0xd5, 0x90, 0x89, 0xd5, 0x00, 0x2b, 0xb1, 0xb3, 0xbf, 0xca, 0x4a, 0xde, 0x09, 0x82, 0xad, 0x67, 0x83, 0xe9, 0xd3, 0x7f, 0xb3, 0xe3, 0x20, 0xac, 0x98, 0x55, 0xdf, 0x66, 0x6b, 0xfd, 0x7c, 0x6b, 0x87, 0xa9, 0xa4, 0x6e, 0x25, 0x97, 0x12, 0x56, 0x11, 0x61, 0x50, 0x7e, 0x17, 0x35, 0x98, 0xf9, 0x88, 0xac, 0xb6, 0xf9, 0xab, 0x3a, 0x10, 0x92, 0x63, 0x24, 0x46, 0x88, 0xc7, 0x08, 0x78, 0x75, 0x8f, 0xf4, 0xd4, 0x31, 0x3b, 0x76, 0x64, 0xf0, 0xf5, 0x10, 0xe9, 0x13, 0xca, 0x01, 0xc5, 0x2b, 0x3a, 0x1b, 0x46, 0x53, 0x51, 0x44, 0xe2, 0xdb, 0x0c, 0xac, 0xe8, 0xa6, 0x46, 0x66, 0x00, 0xcf, 0x2a, 0x87, 0x83, 0x50, 0x07, 0xe1, 0x6a, 0xa5, 0x07, 0x80, 0x1d, 0x86, 0xb7, 0x38, 0x5e, 0x66, 0x9b, 0xfa, 0xf6, 0xba, 0x1d, 0xf5, 0x68, 0x31, 0x63, 0xc2, 0xd5, 0x70, 0x53, 0x2f, 0xd7, 0x43, 0x90, 0x54, 0x64, 0x0f, 0x24, 0x4c, 0x52, 0x87, 0x13, 0x59, 0xd2, 0x84, 0x2f, 0xc3, 0x37, 0xa0, 0x60, 0x03, 0x3a, 0xf0, 0x5e, 0xaa, 0x00, 0x1c, 0x34, 0xfc, 0x7b, 0xd8, 0xf9, 0x10, 0x29, 0xe4, 0x6c, 0x29, 0x43, 0x36, 0x27, 0x64, 0x5d, 0x67, 0x86, 0x64, 0x21, 0xd6, 0x61, 0xaf, 0x25, 0x74, 0x80, 0x53, 0x2b, 0x88, 0x78, 0x50, 0xdc, 0x49, 0x9f, 0xfe, 0xd5, 0xb1, 0x40, 0x98, 0xa0, 0x33, 0x72, 0x5e, 0x82, 0x0a, 0x5b, 0xe1, 0x40, 0x0a, 0x0c, 0xb7, 0x03, 0x74, 0x1c, 0xa7, 0x4b, 0x47, 0x86, 0x73, 0xaa, 0xcf, 0x85, 0x16, 0x6e, 0xe8, 0xa1, 0x84, 0xdb, 0x2c, 0x58, 0x54, 0x9c, 0x22, 0x40, 0xb8, 0x30, 0x8c, 0x27, 0xbe, 0xba, 0x40, 0xc3, 0xb9, 0xd7, 0x29, 0xed, 0xb1, 0x8c, 0xc2, 0x06, 0x8e, 0xcd, 0xb2, 0x7d, 0xa2, 0x2b, 0x2c, 0xd3, 0xe7, 0xa0, 0xba, 0xa5, 0x30, 0xc5, 0x19, 0x3c, 0xd3, 0xc8, 0x6b, 0xf8, 0x6a, 0x44, 0xf0, 0x79, 0x9e, 0x51, 0x55, 0xb0, 0x9b, 0xe2, 0x50, 0x98, 0x85, 0x23, 0xb3, 0xa7, 0x31, 0xdd, 0x89, 0x1b, 0xc2, 0x00, 0x60, 0x11, 0xa0, 0x65, 0xc0, 0xab, 0x57, 0xf1, 0xa6, 0xc1, 0x78, 0x89, 0x55, 0xe0, 0x13, 0x5f, 0xa5, 0xca, 0x8f, 0x3e, 0x52, 0xc7, 0x5d, 0x37, 0x16, 0x97, 0x3a, 0x2f, 0xb2, 0x2c, 0x0e, 0xb1, 0x7c, 0x1b, 0x32, 0x85, 0x29, 0xd9, 0xfa, 0x76, 0x56, 0xd7, 0x4d, 0xea, 0x74, 0x0d, 0x9f, 0x07, 0x97, 0x77, 0xc3, 0x6c, 0x17, 0xa1, 0x9c, 0x19, 0x58, 0x9e, 0x84, 0xd2, 0xb8, 0xe4, 0xd1, 0xbc, 0x31, 0x07, 0xcb, 0xd2, 0x78, 0x14, 0x22, 0x48, 0x35, 0x48, 0x44, 0x6c, 0x89, 0x93, 0x14, 0x77, 0x44, 0xaa, 0x9e, 0xc1, 0xc5, 0x93, 0xec, 0x2d, 0x5b, 0xaa, 0xc8, 0x6a, 0x0a, 0xf6, 0x4a, 0x85, 0xe9, 0x09, 0xdf, 0x8e, 0x28, 0x16, 0x60, 0x5d, 0x20, 0xb4, 0xe3, 0x82, 0xb3, 0x0b, 0xbb, 0x61, 0xbf, 0x3a, 0x5f, 0x82, 0x1a, 0x0b, 0x5d, 0xba, 0x9a, 0xd3, 0xe7, 0xe5, 0xbd, 0x1b, 0x37, 0xa7, 0x5e, 0x0f, 0x09, 0x29, 0x74, 0xe8, 0x46, 0xe8, 0xc3, 0x7c, 0x45, 0x48, 0x7d, 0x60, 0x73, 0x9f, 0x99, 0x35, 0x17, 0x19, 0xa5, 0x39, 0x47, 0x23, 0x26, 0x2b, 0x3b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; static const unsigned char ml_kem_512_secret[] = { 0x4a, 0xd5, 0x3a, 0x06, 0xb2, 0x9f, 0x12, 0x56, 0x84, 0x21, 0xa5, 0x52, 0xc0, 0x81, 0x95, 0xb5, 0x86, 0x73, 0xc8, 0x2f, 0x87, 0x0c, 0xc1, 0xcc, 0xd6, 0x5a, 0x08, 0xe4, 0x32, 0x5f, 0xeb, 0x27 }; static const unsigned char ml_kem_512_reject_secret[] = { 0x87, 0xf1, 0xe8, 0x13, 0xb7, 0x2e, 0x04, 0x87, 0x47, 0x22, 0x56, 0x6e, 0x12, 0x80, 0xd8, 0x9d, 0x8b, 0x44, 0xb7, 0xfd, 0xff, 0x7d, 0x69, 0x23, 0x36, 0xd7, 0xb8, 0x7f, 0x38, 0xe7, 0x85, 0xce }; static const unsigned char ml_kem_512_entropy[ML_KEM_RANDOM_BYTES] = { 0 }; static const unsigned char ml_kem_512_seed[ML_KEM_SEED_BYTES] = { 0 }; static const ST_KAT_PARAM ml_kem_keygen_params[] = { ST_KAT_PARAM_OCTET(OSSL_PKEY_PARAM_ML_KEM_SEED, ml_kem_512_seed), ST_KAT_PARAM_END() }; static const ST_KAT_PARAM ml_kem_key[] = { ST_KAT_PARAM_OCTET(OSSL_PKEY_PARAM_PRIV_KEY, ml_kem_512_private_key), ST_KAT_PARAM_END() }; static const ST_KAT_KEM st_kat_kem_tests[] = { { OSSL_SELF_TEST_DESC_KEM, "ML-KEM-512", ml_kem_key, ITM(ml_kem_512_cipher_text), ITM(ml_kem_512_entropy), ITM(ml_kem_512_secret), ml_kem_512_reject_secret /* No length because same as _secret's */ }, }; #endif /* OPENSSL_NO_ML_KEM */ #if !defined(OPENSSL_NO_ML_KEM) || !defined(OPENSSL_NO_ML_DSA) || !defined(OPENSSL_NO_SLH_DSA) static const ST_KAT_ASYM_KEYGEN st_kat_asym_keygen_tests[] = { # if !defined(OPENSSL_NO_ML_KEM) /* * FIPS 140-3 IG 10.3.A resolution 14 mandates a CAST for ML-KEM * key generation. */ { OSSL_SELF_TEST_DESC_KEYGEN_ML_KEM, "ML-KEM-512", ml_kem_keygen_params, ml_kem_key }, # endif # if !defined(OPENSSL_NO_ML_DSA) { OSSL_SELF_TEST_DESC_KEYGEN_ML_DSA, "ML-DSA-65", ml_dsa_keygen_params, ml_dsa_key }, # endif # if !defined(OPENSSL_NO_SLH_DSA) { OSSL_SELF_TEST_DESC_KEYGEN_SLH_DSA, "SLH-DSA-SHA2-128f", slh_dsa_sha2_128f_keygen_init_params, slh_dsa_128f_keygen_expected_params }, # endif }; #endif /* !OPENSSL_NO_ML_DSA || !OPENSSL_NO_SLH_DSA */ + +static const ST_KAT_ASYM_CIPHER st_kat_asym_cipher_tests[] = { + { + OSSL_SELF_TEST_DESC_ASYM_RSA_ENC, + "RSA", + 1, + rsa_pub_key, + rsa_enc_params, + ITM(rsa_asym_plaintext_encrypt), + ITM(rsa_asym_expected_encrypt), + }, + { + OSSL_SELF_TEST_DESC_ASYM_RSA_DEC, + "RSA", + 0, + rsa_priv_key, + rsa_enc_params, + ITM(rsa_asym_expected_encrypt), + ITM(rsa_asym_plaintext_encrypt), + }, + { + OSSL_SELF_TEST_DESC_ASYM_RSA_DEC, + "RSA", + 0, + rsa_crt_key, + rsa_enc_params, + ITM(rsa_asym_expected_encrypt), + ITM(rsa_asym_plaintext_encrypt), + }, +}; diff --git a/providers/fips/self_test_kats.c b/providers/fips/self_test_kats.c index 35ecb43598ee..acb0b85f7343 100644 --- a/providers/fips/self_test_kats.c +++ b/providers/fips/self_test_kats.c @@ -1,1099 +1,1199 @@ /* * Copyright 2019-2025 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 "crypto/ml_dsa.h" #include "crypto/rand.h" #include "internal/cryptlib.h" #include "internal/nelem.h" #include "self_test.h" #include "crypto/ml_kem.h" #include "self_test_data.inc" static int set_kat_drbg(OSSL_LIB_CTX *ctx, const unsigned char *entropy, size_t entropy_len, const unsigned char *nonce, size_t nonce_len, const unsigned char *persstr, size_t persstr_len); static int reset_main_drbg(OSSL_LIB_CTX *ctx); static int self_test_digest(const ST_KAT_DIGEST *t, OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx) { int ok = 0; unsigned char out[EVP_MAX_MD_SIZE]; unsigned int out_len = 0; EVP_MD_CTX *ctx = EVP_MD_CTX_new(); EVP_MD *md = EVP_MD_fetch(libctx, t->algorithm, NULL); OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_KAT_DIGEST, t->desc); if (ctx == NULL || md == NULL || !EVP_DigestInit_ex(ctx, md, NULL) || !EVP_DigestUpdate(ctx, t->pt, t->pt_len) || !EVP_DigestFinal(ctx, out, &out_len)) goto err; /* Optional corruption */ OSSL_SELF_TEST_oncorrupt_byte(st, out); if (out_len != t->expected_len || memcmp(out, t->expected, out_len) != 0) goto err; ok = 1; err: EVP_MD_free(md); EVP_MD_CTX_free(ctx); OSSL_SELF_TEST_onend(st, ok); return ok; } /* * Helper function to setup a EVP_CipherInit * Used to hide the complexity of Authenticated ciphers. */ static int cipher_init(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, const ST_KAT_CIPHER *t, int enc) { unsigned char *in_tag = NULL; int pad = 0, tmp; /* Flag required for Key wrapping */ EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW); if (t->tag == NULL) { /* Use a normal cipher init */ return EVP_CipherInit_ex(ctx, cipher, NULL, t->key, t->iv, enc) && EVP_CIPHER_CTX_set_padding(ctx, pad); } /* The authenticated cipher init */ if (!enc) in_tag = (unsigned char *)t->tag; return EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, enc) && (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, t->iv_len, NULL) > 0) && (in_tag == NULL || EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, t->tag_len, in_tag) > 0) && EVP_CipherInit_ex(ctx, NULL, NULL, t->key, t->iv, enc) && EVP_CIPHER_CTX_set_padding(ctx, pad) && EVP_CipherUpdate(ctx, NULL, &tmp, t->aad, t->aad_len); } /* Test a single KAT for encrypt/decrypt */ static int self_test_cipher(const ST_KAT_CIPHER *t, OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx) { int ret = 0, encrypt = 1, len = 0, ct_len = 0, pt_len = 0; EVP_CIPHER_CTX *ctx = NULL; EVP_CIPHER *cipher = NULL; unsigned char ct_buf[256] = { 0 }; unsigned char pt_buf[256] = { 0 }; OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_KAT_CIPHER, t->base.desc); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) goto err; cipher = EVP_CIPHER_fetch(libctx, t->base.algorithm, NULL); if (cipher == NULL) goto err; /* Encrypt plain text message */ if ((t->mode & CIPHER_MODE_ENCRYPT) != 0) { if (!cipher_init(ctx, cipher, t, encrypt) || !EVP_CipherUpdate(ctx, ct_buf, &len, t->base.pt, t->base.pt_len) || !EVP_CipherFinal_ex(ctx, ct_buf + len, &ct_len)) goto err; OSSL_SELF_TEST_oncorrupt_byte(st, ct_buf); ct_len += len; if (ct_len != (int)t->base.expected_len || memcmp(t->base.expected, ct_buf, ct_len) != 0) goto err; if (t->tag != NULL) { unsigned char tag[16] = { 0 }; if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, t->tag_len, tag) <= 0 || memcmp(tag, t->tag, t->tag_len) != 0) goto err; } } /* Decrypt cipher text */ if ((t->mode & CIPHER_MODE_DECRYPT) != 0) { if (!(cipher_init(ctx, cipher, t, !encrypt) && EVP_CipherUpdate(ctx, pt_buf, &len, t->base.expected, t->base.expected_len) && EVP_CipherFinal_ex(ctx, pt_buf + len, &pt_len))) goto err; OSSL_SELF_TEST_oncorrupt_byte(st, pt_buf); pt_len += len; if (pt_len != (int)t->base.pt_len || memcmp(pt_buf, t->base.pt, pt_len) != 0) goto err; } ret = 1; err: EVP_CIPHER_free(cipher); EVP_CIPHER_CTX_free(ctx); OSSL_SELF_TEST_onend(st, ret); return ret; } static int add_params(OSSL_PARAM_BLD *bld, const ST_KAT_PARAM *params, BN_CTX *ctx) { int ret = 0; const ST_KAT_PARAM *p; if (params == NULL) return 1; for (p = params; p->data != NULL; ++p) { switch (p->type) { case OSSL_PARAM_UNSIGNED_INTEGER: { BIGNUM *bn = BN_CTX_get(ctx); if (bn == NULL || (BN_bin2bn(p->data, p->data_len, bn) == NULL) || !OSSL_PARAM_BLD_push_BN(bld, p->name, bn)) goto err; break; } case OSSL_PARAM_UTF8_STRING: { if (!OSSL_PARAM_BLD_push_utf8_string(bld, p->name, p->data, p->data_len)) goto err; break; } case OSSL_PARAM_OCTET_STRING: { if (!OSSL_PARAM_BLD_push_octet_string(bld, p->name, p->data, p->data_len)) goto err; break; } case OSSL_PARAM_INTEGER: { if (!OSSL_PARAM_BLD_push_int(bld, p->name, *(int *)p->data)) goto err; break; } default: break; } } ret = 1; err: return ret; } #if defined(__GNUC__) && __GNUC__ >= 4 # define SENTINEL __attribute__((sentinel)) #endif #if !defined(SENTINEL) && defined(__clang_major__) && __clang_major__ > 14 # define SENTINEL __attribute__((sentinel)) #endif #ifndef SENTINEL # define SENTINEL #endif static SENTINEL OSSL_PARAM *kat_params_to_ossl_params(OSSL_LIB_CTX *libctx, ...) { BN_CTX *bnc = NULL; OSSL_PARAM *params = NULL; OSSL_PARAM_BLD *bld = NULL; const ST_KAT_PARAM *pms; va_list ap; bnc = BN_CTX_new_ex(libctx); if (bnc == NULL) goto err; bld = OSSL_PARAM_BLD_new(); if (bld == NULL) goto err; va_start(ap, libctx); while ((pms = va_arg(ap, const ST_KAT_PARAM *)) != NULL) if (!add_params(bld, pms, bnc)) { va_end(ap); goto err; } va_end(ap); params = OSSL_PARAM_BLD_to_param(bld); err: OSSL_PARAM_BLD_free(bld); BN_CTX_free(bnc); return params; } static int self_test_kdf(const ST_KAT_KDF *t, OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx) { int ret = 0; unsigned char out[128]; EVP_KDF *kdf = NULL; EVP_KDF_CTX *ctx = NULL; OSSL_PARAM *params = NULL; OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_KAT_KDF, t->desc); kdf = EVP_KDF_fetch(libctx, t->algorithm, ""); if (kdf == NULL) goto err; ctx = EVP_KDF_CTX_new(kdf); if (ctx == NULL) goto err; params = kat_params_to_ossl_params(libctx, t->params, NULL); if (params == NULL) goto err; if (t->expected_len > sizeof(out)) goto err; if (EVP_KDF_derive(ctx, out, t->expected_len, params) <= 0) goto err; OSSL_SELF_TEST_oncorrupt_byte(st, out); if (memcmp(out, t->expected, t->expected_len) != 0) goto err; ret = 1; err: EVP_KDF_free(kdf); EVP_KDF_CTX_free(ctx); OSSL_PARAM_free(params); OSSL_SELF_TEST_onend(st, ret); return ret; } static int self_test_drbg(const ST_KAT_DRBG *t, OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx) { int ret = 0; unsigned char out[256]; EVP_RAND *rand; EVP_RAND_CTX *test = NULL, *drbg = NULL; unsigned int strength = 256; int prediction_resistance = 1; /* Causes a reseed */ OSSL_PARAM drbg_params[3] = { OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END }; OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_DRBG, t->desc); rand = EVP_RAND_fetch(libctx, "TEST-RAND", NULL); if (rand == NULL) goto err; test = EVP_RAND_CTX_new(rand, NULL); EVP_RAND_free(rand); if (test == NULL) goto err; drbg_params[0] = OSSL_PARAM_construct_uint(OSSL_RAND_PARAM_STRENGTH, &strength); if (!EVP_RAND_CTX_set_params(test, drbg_params)) goto err; rand = EVP_RAND_fetch(libctx, t->algorithm, NULL); if (rand == NULL) goto err; drbg = EVP_RAND_CTX_new(rand, test); EVP_RAND_free(rand); if (drbg == NULL) goto err; strength = EVP_RAND_get_strength(drbg); drbg_params[0] = OSSL_PARAM_construct_utf8_string(t->param_name, t->param_value, 0); /* This is only used by HMAC-DRBG but it is ignored by the others */ drbg_params[1] = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_MAC, "HMAC", 0); if (!EVP_RAND_CTX_set_params(drbg, drbg_params)) goto err; drbg_params[0] = OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY, (void *)t->entropyin, t->entropyinlen); drbg_params[1] = OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_NONCE, (void *)t->nonce, t->noncelen); if (!EVP_RAND_instantiate(test, strength, 0, NULL, 0, drbg_params)) goto err; if (!EVP_RAND_instantiate(drbg, strength, 0, t->persstr, t->persstrlen, NULL)) goto err; drbg_params[0] = OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY, (void *)t->entropyinpr1, t->entropyinpr1len); if (!EVP_RAND_CTX_set_params(test, drbg_params)) goto err; if (!EVP_RAND_generate(drbg, out, t->expectedlen, strength, prediction_resistance, t->entropyaddin1, t->entropyaddin1len)) goto err; drbg_params[0] = OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY, (void *)t->entropyinpr2, t->entropyinpr2len); if (!EVP_RAND_CTX_set_params(test, drbg_params)) goto err; /* * This calls ossl_prov_drbg_reseed() internally when * prediction_resistance = 1 */ if (!EVP_RAND_generate(drbg, out, t->expectedlen, strength, prediction_resistance, t->entropyaddin2, t->entropyaddin2len)) goto err; OSSL_SELF_TEST_oncorrupt_byte(st, out); if (memcmp(out, t->expected, t->expectedlen) != 0) goto err; if (!EVP_RAND_uninstantiate(drbg)) goto err; /* * Check that the DRBG data has been zeroized after * ossl_prov_drbg_uninstantiate. */ if (!EVP_RAND_verify_zeroization(drbg)) goto err; ret = 1; err: EVP_RAND_CTX_free(drbg); EVP_RAND_CTX_free(test); OSSL_SELF_TEST_onend(st, ret); return ret; } #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_EC) static int self_test_ka(const ST_KAT_KAS *t, OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx) { int ret = 0; EVP_PKEY_CTX *kactx = NULL, *dctx = NULL; EVP_PKEY *pkey = NULL, *peerkey = NULL; OSSL_PARAM *params = NULL; OSSL_PARAM *params_peer = NULL; unsigned char secret[256]; size_t secret_len = t->expected_len; OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_KAT_KA, t->desc); if (secret_len > sizeof(secret)) goto err; params = kat_params_to_ossl_params(libctx, t->key_group, t->key_host_data, NULL); params_peer = kat_params_to_ossl_params(libctx, t->key_group, t->key_peer_data, NULL); if (params == NULL || params_peer == NULL) goto err; /* Create a EVP_PKEY_CTX to load the DH keys into */ kactx = EVP_PKEY_CTX_new_from_name(libctx, t->algorithm, ""); if (kactx == NULL) goto err; if (EVP_PKEY_fromdata_init(kactx) <= 0 || EVP_PKEY_fromdata(kactx, &pkey, EVP_PKEY_KEYPAIR, params) <= 0) goto err; if (EVP_PKEY_fromdata_init(kactx) <= 0 || EVP_PKEY_fromdata(kactx, &peerkey, EVP_PKEY_KEYPAIR, params_peer) <= 0) goto err; /* Create a EVP_PKEY_CTX to perform key derivation */ dctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, NULL); if (dctx == NULL) goto err; if (EVP_PKEY_derive_init(dctx) <= 0 || EVP_PKEY_derive_set_peer(dctx, peerkey) <= 0 || EVP_PKEY_derive(dctx, secret, &secret_len) <= 0) goto err; OSSL_SELF_TEST_oncorrupt_byte(st, secret); if (secret_len != t->expected_len || memcmp(secret, t->expected, t->expected_len) != 0) goto err; ret = 1; err: EVP_PKEY_free(pkey); EVP_PKEY_free(peerkey); EVP_PKEY_CTX_free(kactx); EVP_PKEY_CTX_free(dctx); OSSL_PARAM_free(params_peer); OSSL_PARAM_free(params); OSSL_SELF_TEST_onend(st, ret); return ret; } #endif /* !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_EC) */ static int digest_signature(const uint8_t *sig, size_t sig_len, uint8_t *out, size_t *out_len, OSSL_LIB_CTX *lib_ctx) { int ret; unsigned int len = 0; EVP_MD_CTX *ctx = EVP_MD_CTX_new(); EVP_MD *md = EVP_MD_fetch(lib_ctx, "SHA256", NULL); ret = ctx != NULL && md != NULL && EVP_DigestInit_ex(ctx, md, NULL) == 1 && EVP_DigestUpdate(ctx, sig, sig_len) == 1 && EVP_DigestFinal(ctx, out, &len) == 1; EVP_MD_free(md); EVP_MD_CTX_free(ctx); *out_len = len; return ret; } static int self_test_digest_sign(const ST_KAT_SIGN *t, OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx) { int ret = 0; OSSL_PARAM *paramskey = NULL, *paramsinit = NULL, *paramsverify = NULL; EVP_SIGNATURE *sigalg = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY_CTX *fromctx = NULL; EVP_PKEY *pkey = NULL; unsigned char sig[MAX_ML_DSA_SIG_LEN], *psig = sig; size_t siglen; int digested = 0; const char *typ = OSSL_SELF_TEST_TYPE_KAT_SIGNATURE; if (t->sig_expected_len > sizeof(sig)) goto err; if (t->sig_expected == NULL) typ = OSSL_SELF_TEST_TYPE_PCT_SIGNATURE; OSSL_SELF_TEST_onbegin(st, typ, t->desc); if (t->entropy != NULL) { if (!set_kat_drbg(libctx, t->entropy, t->entropy_len, t->nonce, t->nonce_len, t->persstr, t->persstr_len)) goto err; } paramskey = kat_params_to_ossl_params(libctx, t->key, NULL); paramsinit = kat_params_to_ossl_params(libctx, t->init, NULL); paramsverify = kat_params_to_ossl_params(libctx, t->verify, NULL); fromctx = EVP_PKEY_CTX_new_from_name(libctx, t->keytype, NULL); if (fromctx == NULL || paramskey == NULL || paramsinit == NULL || paramsverify == NULL) goto err; if (EVP_PKEY_fromdata_init(fromctx) <= 0 || EVP_PKEY_fromdata(fromctx, &pkey, EVP_PKEY_KEYPAIR, paramskey) <= 0) goto err; sigalg = EVP_SIGNATURE_fetch(libctx, t->sigalgorithm, NULL); if (sigalg == NULL) goto err; ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, NULL); if (ctx == NULL) goto err; digested = ((t->mode & SIGNATURE_MODE_DIGESTED) != 0); if ((t->mode & SIGNATURE_MODE_VERIFY_ONLY) != 0) { siglen = t->sig_expected_len; memcpy(psig, t->sig_expected, siglen); } else { if (digested) { if (EVP_PKEY_sign_init_ex2(ctx, sigalg, paramsinit) <= 0) goto err; } else { if (EVP_PKEY_sign_message_init(ctx, sigalg, paramsinit) <= 0) goto err; } siglen = sizeof(sig); if ((t->mode & SIGNATURE_MODE_SIG_DIGESTED) != 0) { if (EVP_PKEY_sign(ctx, NULL, &siglen, t->msg, t->msg_len) <= 0) goto err; if (siglen > sizeof(sig)) { psig = OPENSSL_malloc(siglen); if (psig == NULL) goto err; } } if (EVP_PKEY_sign(ctx, psig, &siglen, t->msg, t->msg_len) <= 0) goto err; if (t->sig_expected != NULL) { if ((t->mode & SIGNATURE_MODE_SIG_DIGESTED) != 0) { uint8_t digested_sig[EVP_MAX_MD_SIZE]; size_t digested_sig_len = 0; if (!digest_signature(psig, siglen, digested_sig, &digested_sig_len, libctx) || digested_sig_len != t->sig_expected_len || memcmp(digested_sig, t->sig_expected, t->sig_expected_len) != 0) goto err; } else { if (siglen != t->sig_expected_len || memcmp(psig, t->sig_expected, t->sig_expected_len) != 0) goto err; } } } if ((t->mode & SIGNATURE_MODE_SIGN_ONLY) == 0) { if (digested) { if (EVP_PKEY_verify_init_ex2(ctx, sigalg, paramsverify) <= 0) goto err; } else { if (EVP_PKEY_verify_message_init(ctx, sigalg, paramsverify) <= 0) goto err; } OSSL_SELF_TEST_oncorrupt_byte(st, psig); if (EVP_PKEY_verify(ctx, psig, siglen, t->msg, t->msg_len) <= 0) goto err; } ret = 1; err: if (psig != sig) OPENSSL_free(psig); EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(fromctx); EVP_PKEY_CTX_free(ctx); EVP_SIGNATURE_free(sigalg); OSSL_PARAM_free(paramskey); OSSL_PARAM_free(paramsinit); OSSL_PARAM_free(paramsverify); if (t->entropy != NULL) { if (!reset_main_drbg(libctx)) ret = 0; } OSSL_SELF_TEST_onend(st, ret); return ret; } #if !defined(OPENSSL_NO_ML_DSA) || !defined(OPENSSL_NO_SLH_DSA) /* * Test that a deterministic key generation produces the correct key */ static int self_test_asym_keygen(const ST_KAT_ASYM_KEYGEN *t, OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx) { int ret = 0; const ST_KAT_PARAM *expected; OSSL_PARAM *key_params = NULL; EVP_PKEY_CTX *key_ctx = NULL; EVP_PKEY *key = NULL; uint8_t out[MAX_ML_DSA_PRIV_LEN]; size_t out_len = 0; OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_KAT_ASYM_KEYGEN, t->desc); key_ctx = EVP_PKEY_CTX_new_from_name(libctx, t->algorithm, NULL); if (key_ctx == NULL) goto err; if (t->keygen_params != NULL) { key_params = kat_params_to_ossl_params(libctx, t->keygen_params, NULL); if (key_params == NULL) goto err; } if (EVP_PKEY_keygen_init(key_ctx) != 1 || EVP_PKEY_CTX_set_params(key_ctx, key_params) != 1 || EVP_PKEY_generate(key_ctx, &key) != 1) goto err; for (expected = t->expected_params; expected->data != NULL; ++expected) { if (expected->type != OSSL_PARAM_OCTET_STRING || !EVP_PKEY_get_octet_string_param(key, expected->name, out, sizeof(out), &out_len)) goto err; OSSL_SELF_TEST_oncorrupt_byte(st, out); /* Check the KAT */ if (out_len != expected->data_len || memcmp(out, expected->data, expected->data_len) != 0) goto err; } ret = 1; err: EVP_PKEY_free(key); EVP_PKEY_CTX_free(key_ctx); OSSL_PARAM_free(key_params); OSSL_SELF_TEST_onend(st, ret); return ret; } #endif /* OPENSSL_NO_ML_DSA */ #ifndef OPENSSL_NO_ML_KEM /* * FIPS 140-3 IG 10.3.A resolution 14 mandates a CAST for ML-KEM * encapsulation. */ static int self_test_kem_encapsulate(const ST_KAT_KEM *t, OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx, EVP_PKEY *pkey) { int ret = 0; EVP_PKEY_CTX *ctx; unsigned char *wrapped = NULL, *secret = NULL; size_t wrappedlen = t->cipher_text_len, secretlen = t->secret_len; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_KAT_KEM, OSSL_SELF_TEST_DESC_ENCAP_KEM); ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, ""); if (ctx == NULL) goto err; *params = OSSL_PARAM_construct_octet_string(OSSL_KEM_PARAM_IKME, (unsigned char *)t->entropy, t->entropy_len); if (EVP_PKEY_encapsulate_init(ctx, params) <= 0) goto err; /* Allocate output buffers */ wrapped = OPENSSL_malloc(wrappedlen); secret = OPENSSL_malloc(secretlen); if (wrapped == NULL || secret == NULL) goto err; /* Encapsulate */ if (EVP_PKEY_encapsulate(ctx, wrapped, &wrappedlen, secret, &secretlen) <= 0) goto err; /* Compare outputs */ OSSL_SELF_TEST_oncorrupt_byte(st, wrapped); if (wrappedlen != t->cipher_text_len || memcmp(wrapped, t->cipher_text, t->cipher_text_len) != 0) goto err; OSSL_SELF_TEST_oncorrupt_byte(st, secret); if (secretlen != t->secret_len || memcmp(secret, t->secret, t->secret_len) != 0) goto err; ret = 1; err: OPENSSL_free(wrapped); OPENSSL_free(secret); EVP_PKEY_CTX_free(ctx); OSSL_SELF_TEST_onend(st, ret); return ret; } /* * FIPS 140-3 IG 10.3.A resolution 14 mandates a CAST for ML-KEM * decapsulation both for the rejection path and the normal path. */ static int self_test_kem_decapsulate(const ST_KAT_KEM *t, OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx, EVP_PKEY *pkey, int reject) { int ret = 0; EVP_PKEY_CTX *ctx = NULL; unsigned char *secret = NULL, *alloced = NULL; const unsigned char *test_secret = t->secret; const unsigned char *cipher_text = t->cipher_text; size_t secretlen = t->secret_len; OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_KAT_KEM, reject ? OSSL_SELF_TEST_DESC_DECAP_KEM_FAIL : OSSL_SELF_TEST_DESC_DECAP_KEM); if (reject) { cipher_text = alloced = OPENSSL_zalloc(t->cipher_text_len); if (alloced == NULL) goto err; test_secret = t->reject_secret; } ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, ""); if (ctx == NULL) goto err; if (EVP_PKEY_decapsulate_init(ctx, NULL) <= 0) goto err; /* Allocate output buffer */ secret = OPENSSL_malloc(secretlen); if (secret == NULL) goto err; /* Decapsulate */ if (EVP_PKEY_decapsulate(ctx, secret, &secretlen, cipher_text, t->cipher_text_len) <= 0) goto err; /* Compare output */ OSSL_SELF_TEST_oncorrupt_byte(st, secret); if (secretlen != t->secret_len || memcmp(secret, test_secret, t->secret_len) != 0) goto err; ret = 1; err: OPENSSL_free(alloced); OPENSSL_free(secret); EVP_PKEY_CTX_free(ctx); OSSL_SELF_TEST_onend(st, ret); return ret; } /* * Test encapsulation, decapsulation for KEM. * * FIPS 140-3 IG 10.3.A resolution 14 mandates a CAST for: * 1 ML-KEM encapsulation * 2a ML-KEM decapsulation non-rejection path * 2b ML-KEM decapsulation implicit rejection path * 3 ML-KEM key generation */ static int self_test_kem(const ST_KAT_KEM *t, OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx) { int ret = 0; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx; OSSL_PARAM *params = NULL; ctx = EVP_PKEY_CTX_new_from_name(libctx, t->algorithm, NULL); if (ctx == NULL) goto err; params = kat_params_to_ossl_params(libctx, t->key, NULL); if (params == NULL) goto err; if (EVP_PKEY_fromdata_init(ctx) <= 0 || EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEYPAIR, params) <= 0) goto err; if (!self_test_kem_encapsulate(t, st, libctx, pkey) || !self_test_kem_decapsulate(t, st, libctx, pkey, 0) || !self_test_kem_decapsulate(t, st, libctx, pkey, 1)) goto err; ret = 1; err: EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); OSSL_PARAM_free(params); return ret; } #endif +/* + * Test an encrypt or decrypt KAT.. + * + * FIPS 140-2 IG D.9 states that separate KAT tests are needed for encrypt + * and decrypt.. + */ +static int self_test_asym_cipher(const ST_KAT_ASYM_CIPHER *t, OSSL_SELF_TEST *st, + OSSL_LIB_CTX *libctx) +{ + int ret = 0; + OSSL_PARAM *keyparams = NULL, *initparams = NULL; + OSSL_PARAM_BLD *keybld = NULL, *initbld = NULL; + EVP_PKEY_CTX *encctx = NULL, *keyctx = NULL; + EVP_PKEY *key = NULL; + BN_CTX *bnctx = NULL; + unsigned char out[256]; + size_t outlen = sizeof(out); + + OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_KAT_ASYM_CIPHER, t->desc); + + bnctx = BN_CTX_new_ex(libctx); + if (bnctx == NULL) + goto err; + + /* Load a public or private key from data */ + keybld = OSSL_PARAM_BLD_new(); + if (keybld == NULL + || !add_params(keybld, t->key, bnctx)) + goto err; + keyparams = OSSL_PARAM_BLD_to_param(keybld); + keyctx = EVP_PKEY_CTX_new_from_name(libctx, t->algorithm, NULL); + if (keyctx == NULL || keyparams == NULL) + goto err; + if (EVP_PKEY_fromdata_init(keyctx) <= 0 + || EVP_PKEY_fromdata(keyctx, &key, EVP_PKEY_KEYPAIR, keyparams) <= 0) + goto err; + + /* Create a EVP_PKEY_CTX to use for the encrypt or decrypt operation */ + encctx = EVP_PKEY_CTX_new_from_pkey(libctx, key, NULL); + if (encctx == NULL + || (t->encrypt && EVP_PKEY_encrypt_init(encctx) <= 0) + || (!t->encrypt && EVP_PKEY_decrypt_init(encctx) <= 0)) + goto err; + + /* Add any additional parameters such as padding */ + if (t->postinit != NULL) { + initbld = OSSL_PARAM_BLD_new(); + if (initbld == NULL) + goto err; + if (!add_params(initbld, t->postinit, bnctx)) + goto err; + initparams = OSSL_PARAM_BLD_to_param(initbld); + if (initparams == NULL) + goto err; + if (EVP_PKEY_CTX_set_params(encctx, initparams) <= 0) + goto err; + } + + if (t->encrypt) { + if (EVP_PKEY_encrypt(encctx, out, &outlen, + t->in, t->in_len) <= 0) + goto err; + } else { + if (EVP_PKEY_decrypt(encctx, out, &outlen, + t->in, t->in_len) <= 0) + goto err; + } + /* Check the KAT */ + OSSL_SELF_TEST_oncorrupt_byte(st, out); + if (outlen != t->expected_len + || memcmp(out, t->expected, t->expected_len) != 0) + goto err; + + ret = 1; +err: + BN_CTX_free(bnctx); + EVP_PKEY_free(key); + EVP_PKEY_CTX_free(encctx); + EVP_PKEY_CTX_free(keyctx); + OSSL_PARAM_free(keyparams); + OSSL_PARAM_BLD_free(keybld); + OSSL_PARAM_free(initparams); + OSSL_PARAM_BLD_free(initbld); + OSSL_SELF_TEST_onend(st, ret); + return ret; +} + /* * Test a data driven list of KAT's for digest algorithms. * All tests are run regardless of if they fail or not. * Return 0 if any test fails. */ static int self_test_digests(OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx) { int i, ret = 1; for (i = 0; i < (int)OSSL_NELEM(st_kat_digest_tests); ++i) { if (!self_test_digest(&st_kat_digest_tests[i], st, libctx)) ret = 0; } return ret; } static int self_test_ciphers(OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx) { int i, ret = 1; for (i = 0; i < (int)OSSL_NELEM(st_kat_cipher_tests); ++i) { if (!self_test_cipher(&st_kat_cipher_tests[i], st, libctx)) ret = 0; } return ret; } static int self_test_kems(OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx) { int ret = 1; #ifndef OPENSSL_NO_ML_KEM int i; for (i = 0; i < (int)OSSL_NELEM(st_kat_kem_tests); ++i) { if (!self_test_kem(&st_kat_kem_tests[i], st, libctx)) ret = 0; } #endif return ret; } +static int self_test_asym_ciphers(OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx) +{ + int i, ret = 1; + + for (i = 0; i < (int)OSSL_NELEM(st_kat_asym_cipher_tests); ++i) { + if (!self_test_asym_cipher(&st_kat_asym_cipher_tests[i], st, libctx)) + ret = 0; + } + return ret; +} + static int self_test_kdfs(OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx) { int i, ret = 1; for (i = 0; i < (int)OSSL_NELEM(st_kat_kdf_tests); ++i) { if (!self_test_kdf(&st_kat_kdf_tests[i], st, libctx)) ret = 0; } return ret; } static int self_test_drbgs(OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx) { int i, ret = 1; for (i = 0; i < (int)OSSL_NELEM(st_kat_drbg_tests); ++i) { if (!self_test_drbg(&st_kat_drbg_tests[i], st, libctx)) ret = 0; } return ret; } static int self_test_kas(OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx) { int ret = 1; #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_EC) int i; for (i = 0; i < (int)OSSL_NELEM(st_kat_kas_tests); ++i) { if (!self_test_ka(&st_kat_kas_tests[i], st, libctx)) ret = 0; } #endif return ret; } static int self_test_signatures(OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx) { int i, ret = 1; for (i = 0; i < (int)OSSL_NELEM(st_kat_sign_tests); ++i) { if (!self_test_digest_sign(&st_kat_sign_tests[i], st, libctx)) ret = 0; } return ret; } /* * Swap the library context DRBG for KAT testing * * In FIPS 140-3, the asymmetric POST must be a KAT, not a PCT. For DSA and ECDSA, * the sign operation includes the random value 'k'. For a KAT to work, we * have to have control of the DRBG to make sure it is in a "test" state, where * its output is truly deterministic. * */ /* * Replacement "random" sources * main_rand is used for most tests and it's set to generate mode. * kat_rand is used for KATs where specific input is mandated. */ static EVP_RAND_CTX *kat_rand = NULL; static EVP_RAND_CTX *main_rand = NULL; static int set_kat_drbg(OSSL_LIB_CTX *ctx, const unsigned char *entropy, size_t entropy_len, const unsigned char *nonce, size_t nonce_len, const unsigned char *persstr, size_t persstr_len) { EVP_RAND *rand; unsigned int strength = 256; EVP_RAND_CTX *parent_rand = NULL; OSSL_PARAM drbg_params[3] = { OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END }; /* If not NULL, we didn't cleanup from last call: BAD */ if (kat_rand != NULL) return 0; rand = EVP_RAND_fetch(ctx, "TEST-RAND", NULL); if (rand == NULL) return 0; parent_rand = EVP_RAND_CTX_new(rand, NULL); EVP_RAND_free(rand); if (parent_rand == NULL) goto err; drbg_params[0] = OSSL_PARAM_construct_uint(OSSL_RAND_PARAM_STRENGTH, &strength); if (!EVP_RAND_CTX_set_params(parent_rand, drbg_params)) goto err; rand = EVP_RAND_fetch(ctx, "HASH-DRBG", NULL); if (rand == NULL) goto err; kat_rand = EVP_RAND_CTX_new(rand, parent_rand); EVP_RAND_free(rand); if (kat_rand == NULL) goto err; drbg_params[0] = OSSL_PARAM_construct_utf8_string("digest", "SHA256", 0); if (!EVP_RAND_CTX_set_params(kat_rand, drbg_params)) goto err; /* Instantiate the RNGs */ drbg_params[0] = OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY, (void *)entropy, entropy_len); drbg_params[1] = OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_NONCE, (void *)nonce, nonce_len); if (!EVP_RAND_instantiate(parent_rand, strength, 0, NULL, 0, drbg_params)) goto err; EVP_RAND_CTX_free(parent_rand); parent_rand = NULL; if (!EVP_RAND_instantiate(kat_rand, strength, 0, persstr, persstr_len, NULL)) goto err; /* When we set the new private generator this one is freed, so upref it */ if (!EVP_RAND_CTX_up_ref(main_rand)) goto err; /* Update the library context DRBG */ if (RAND_set0_private(ctx, kat_rand) > 0) { /* Keeping a copy to verify zeroization */ if (EVP_RAND_CTX_up_ref(kat_rand)) return 1; RAND_set0_private(ctx, main_rand); } err: EVP_RAND_CTX_free(parent_rand); EVP_RAND_CTX_free(kat_rand); kat_rand = NULL; return 0; } static int reset_main_drbg(OSSL_LIB_CTX *ctx) { int ret = 1; if (!RAND_set0_private(ctx, main_rand)) ret = 0; if (kat_rand != NULL) { if (!EVP_RAND_uninstantiate(kat_rand) || !EVP_RAND_verify_zeroization(kat_rand)) ret = 0; EVP_RAND_CTX_free(kat_rand); kat_rand = NULL; } return ret; } static int setup_main_random(OSSL_LIB_CTX *libctx) { OSSL_PARAM drbg_params[3] = { OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END }; unsigned int strength = 256, generate = 1; EVP_RAND *rand; rand = EVP_RAND_fetch(libctx, "TEST-RAND", NULL); if (rand == NULL) return 0; main_rand = EVP_RAND_CTX_new(rand, NULL); EVP_RAND_free(rand); if (main_rand == NULL) goto err; drbg_params[0] = OSSL_PARAM_construct_uint(OSSL_RAND_PARAM_GENERATE, &generate); drbg_params[1] = OSSL_PARAM_construct_uint(OSSL_RAND_PARAM_STRENGTH, &strength); if (!EVP_RAND_instantiate(main_rand, strength, 0, NULL, 0, drbg_params)) goto err; return 1; err: EVP_RAND_CTX_free(main_rand); return 0; } static int self_test_asym_keygens(OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx) { #if !defined(OPENSSL_NO_ML_DSA) || !defined(OPENSSL_NO_SLH_DSA) int i, ret = 1; for (i = 0; i < (int)OSSL_NELEM(st_kat_asym_keygen_tests); ++i) { if (!self_test_asym_keygen(&st_kat_asym_keygen_tests[i], st, libctx)) ret = 0; } return ret; #else return 1; #endif /* OPENSSL_NO_ML_DSA */ } /* * Run the algorithm KAT's. * Return 1 is successful, otherwise return 0. * This runs all the tests regardless of if any fail. */ int SELF_TEST_kats(OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx) { EVP_RAND_CTX *saved_rand = ossl_rand_get0_private_noncreating(libctx); int ret = 1; if (saved_rand != NULL && !EVP_RAND_CTX_up_ref(saved_rand)) return 0; if (!setup_main_random(libctx) || !RAND_set0_private(libctx, main_rand)) { /* Decrement saved_rand reference counter */ EVP_RAND_CTX_free(saved_rand); EVP_RAND_CTX_free(main_rand); return 0; } if (!self_test_digests(st, libctx)) ret = 0; if (!self_test_ciphers(st, libctx)) ret = 0; if (!self_test_signatures(st, libctx)) ret = 0; if (!self_test_kdfs(st, libctx)) ret = 0; if (!self_test_drbgs(st, libctx)) ret = 0; if (!self_test_kas(st, libctx)) ret = 0; if (!self_test_asym_keygens(st, libctx)) ret = 0; if (!self_test_kems(st, libctx)) ret = 0; + if (!self_test_asym_ciphers(st, libctx)) + ret = 0; RAND_set0_private(libctx, saved_rand); return ret; } diff --git a/providers/implementations/kdfs/krb5kdf.c b/providers/implementations/kdfs/krb5kdf.c index 566afa74fece..13623ec7302e 100644 --- a/providers/implementations/kdfs/krb5kdf.c +++ b/providers/implementations/kdfs/krb5kdf.c @@ -1,494 +1,497 @@ /* - * Copyright 2018-2024 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2018-2025 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 */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. We access the DES_set_odd_parity(3) function here. */ #include "internal/deprecated.h" #include #include #include #include #include #include #include #include #include "internal/cryptlib.h" #include "crypto/evp.h" #include "internal/numbers.h" #include "prov/implementations.h" #include "prov/provider_ctx.h" #include "prov/provider_util.h" #include "prov/providercommon.h" /* KRB5 KDF defined in RFC 3961, Section 5.1 */ static OSSL_FUNC_kdf_newctx_fn krb5kdf_new; static OSSL_FUNC_kdf_dupctx_fn krb5kdf_dup; static OSSL_FUNC_kdf_freectx_fn krb5kdf_free; static OSSL_FUNC_kdf_reset_fn krb5kdf_reset; static OSSL_FUNC_kdf_derive_fn krb5kdf_derive; static OSSL_FUNC_kdf_settable_ctx_params_fn krb5kdf_settable_ctx_params; static OSSL_FUNC_kdf_set_ctx_params_fn krb5kdf_set_ctx_params; static OSSL_FUNC_kdf_gettable_ctx_params_fn krb5kdf_gettable_ctx_params; static OSSL_FUNC_kdf_get_ctx_params_fn krb5kdf_get_ctx_params; static int KRB5KDF(const EVP_CIPHER *cipher, ENGINE *engine, const unsigned char *key, size_t key_len, const unsigned char *constant, size_t constant_len, unsigned char *okey, size_t okey_len); typedef struct { void *provctx; PROV_CIPHER cipher; unsigned char *key; size_t key_len; unsigned char *constant; size_t constant_len; } KRB5KDF_CTX; static void *krb5kdf_new(void *provctx) { KRB5KDF_CTX *ctx; if (!ossl_prov_is_running()) return NULL; if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL) return NULL; ctx->provctx = provctx; return ctx; } static void krb5kdf_free(void *vctx) { KRB5KDF_CTX *ctx = (KRB5KDF_CTX *)vctx; if (ctx != NULL) { krb5kdf_reset(ctx); OPENSSL_free(ctx); } } static void krb5kdf_reset(void *vctx) { KRB5KDF_CTX *ctx = (KRB5KDF_CTX *)vctx; void *provctx = ctx->provctx; ossl_prov_cipher_reset(&ctx->cipher); OPENSSL_clear_free(ctx->key, ctx->key_len); OPENSSL_clear_free(ctx->constant, ctx->constant_len); memset(ctx, 0, sizeof(*ctx)); ctx->provctx = provctx; } static int krb5kdf_set_membuf(unsigned char **dst, size_t *dst_len, const OSSL_PARAM *p) { OPENSSL_clear_free(*dst, *dst_len); *dst = NULL; *dst_len = 0; return OSSL_PARAM_get_octet_string(p, (void **)dst, 0, dst_len); } static void *krb5kdf_dup(void *vctx) { const KRB5KDF_CTX *src = (const KRB5KDF_CTX *)vctx; KRB5KDF_CTX *dest; dest = krb5kdf_new(src->provctx); if (dest != NULL) { if (!ossl_prov_memdup(src->key, src->key_len, &dest->key, &dest->key_len) || !ossl_prov_memdup(src->constant, src->constant_len, &dest->constant , &dest->constant_len) || !ossl_prov_cipher_copy(&dest->cipher, &src->cipher)) goto err; } return dest; err: krb5kdf_free(dest); return NULL; } static int krb5kdf_derive(void *vctx, unsigned char *key, size_t keylen, const OSSL_PARAM params[]) { KRB5KDF_CTX *ctx = (KRB5KDF_CTX *)vctx; const EVP_CIPHER *cipher; ENGINE *engine; if (!ossl_prov_is_running() || !krb5kdf_set_ctx_params(ctx, params)) return 0; cipher = ossl_prov_cipher_cipher(&ctx->cipher); if (cipher == NULL) { ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_CIPHER); return 0; } if (ctx->key == NULL) { ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_KEY); return 0; } if (ctx->constant == NULL) { ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_CONSTANT); return 0; } engine = ossl_prov_cipher_engine(&ctx->cipher); return KRB5KDF(cipher, engine, ctx->key, ctx->key_len, ctx->constant, ctx->constant_len, key, keylen); } static int krb5kdf_set_ctx_params(void *vctx, const OSSL_PARAM params[]) { const OSSL_PARAM *p; KRB5KDF_CTX *ctx = vctx; OSSL_LIB_CTX *provctx = PROV_LIBCTX_OF(ctx->provctx); if (ossl_param_is_empty(params)) return 1; if (!ossl_prov_cipher_load_from_params(&ctx->cipher, params, provctx)) return 0; if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_KEY)) != NULL) if (!krb5kdf_set_membuf(&ctx->key, &ctx->key_len, p)) return 0; if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_CONSTANT)) != NULL) if (!krb5kdf_set_membuf(&ctx->constant, &ctx->constant_len, p)) return 0; return 1; } static const OSSL_PARAM *krb5kdf_settable_ctx_params(ossl_unused void *ctx, ossl_unused void *provctx) { static const OSSL_PARAM known_settable_ctx_params[] = { OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0), OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_CIPHER, NULL, 0), OSSL_PARAM_octet_string(OSSL_KDF_PARAM_KEY, NULL, 0), OSSL_PARAM_octet_string(OSSL_KDF_PARAM_CONSTANT, NULL, 0), OSSL_PARAM_END }; return known_settable_ctx_params; } static int krb5kdf_get_ctx_params(void *vctx, OSSL_PARAM params[]) { KRB5KDF_CTX *ctx = (KRB5KDF_CTX *)vctx; const EVP_CIPHER *cipher; size_t len; OSSL_PARAM *p; cipher = ossl_prov_cipher_cipher(&ctx->cipher); if (cipher) len = EVP_CIPHER_get_key_length(cipher); else len = EVP_MAX_KEY_LENGTH; if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE)) != NULL) return OSSL_PARAM_set_size_t(p, len); return -2; } static const OSSL_PARAM *krb5kdf_gettable_ctx_params(ossl_unused void *ctx, ossl_unused void *provctx) { static const OSSL_PARAM known_gettable_ctx_params[] = { OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL), OSSL_PARAM_END }; return known_gettable_ctx_params; } const OSSL_DISPATCH ossl_kdf_krb5kdf_functions[] = { { OSSL_FUNC_KDF_NEWCTX, (void(*)(void))krb5kdf_new }, { OSSL_FUNC_KDF_DUPCTX, (void(*)(void))krb5kdf_dup }, { OSSL_FUNC_KDF_FREECTX, (void(*)(void))krb5kdf_free }, { OSSL_FUNC_KDF_RESET, (void(*)(void))krb5kdf_reset }, { OSSL_FUNC_KDF_DERIVE, (void(*)(void))krb5kdf_derive }, { OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS, (void(*)(void))krb5kdf_settable_ctx_params }, { OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))krb5kdf_set_ctx_params }, { OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS, (void(*)(void))krb5kdf_gettable_ctx_params }, { OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))krb5kdf_get_ctx_params }, OSSL_DISPATCH_END }; #ifndef OPENSSL_NO_DES /* * DES3 is a special case, it requires a random-to-key function and its * input truncated to 21 bytes of the 24 produced by the cipher. * See RFC3961 6.3.1 */ static int fixup_des3_key(unsigned char *key) { unsigned char *cblock; int i, j; for (i = 2; i >= 0; i--) { cblock = &key[i * 8]; memmove(cblock, &key[i * 7], 7); cblock[7] = 0; for (j = 0; j < 7; j++) cblock[7] |= (cblock[j] & 1) << (j + 1); DES_set_odd_parity((DES_cblock *)cblock); } /* fail if keys are such that triple des degrades to single des */ if (CRYPTO_memcmp(&key[0], &key[8], 8) == 0 || CRYPTO_memcmp(&key[8], &key[16], 8) == 0) { return 0; } return 1; } #endif /* * N-fold(K) where blocksize is N, and constant_len is K * Note: Here |= denotes concatenation * * L = lcm(N,K) * R = L/K * * for r: 1 -> R * s |= constant rot 13*(r-1)) * * block = 0 * for k: 1 -> K * block += s[N(k-1)..(N-1)k] (ones'-complement addition) * * Optimizing for space we compute: * for each l in L-1 -> 0: * s[l] = (constant rot 13*(l/K))[l%k] * block[l % N] += s[l] (with carry) * finally add carry if any */ static void n_fold(unsigned char *block, unsigned int blocksize, const unsigned char *constant, size_t constant_len) { unsigned int tmp, gcd, remainder, lcm, carry; int b, l; if (constant_len == blocksize) { memcpy(block, constant, constant_len); return; } /* Least Common Multiple of lengths: LCM(a,b)*/ gcd = blocksize; remainder = constant_len; /* Calculate Great Common Divisor first GCD(a,b) */ while (remainder != 0) { tmp = gcd % remainder; gcd = remainder; remainder = tmp; } /* resulting a is the GCD, LCM(a,b) = |a*b|/GCD(a,b) */ lcm = blocksize * constant_len / gcd; /* now spread out the bits */ memset(block, 0, blocksize); /* last to first to be able to bring carry forward */ carry = 0; for (l = lcm - 1; l >= 0; l--) { unsigned int rotbits, rshift, rbyte; /* destination byte in block is l % N */ b = l % blocksize; /* Our virtual s buffer is R = L/K long (K = constant_len) */ /* So we rotate backwards from R-1 to 0 (none) rotations */ rotbits = 13 * (l / constant_len); /* find the byte on s where rotbits falls onto */ rbyte = l - (rotbits / 8); /* calculate how much shift on that byte */ rshift = rotbits & 0x07; /* rbyte % constant_len gives us the unrotated byte in the * constant buffer, get also the previous byte then * appropriately shift them to get the rotated byte we need */ tmp = (constant[(rbyte-1) % constant_len] << (8 - rshift) | constant[rbyte % constant_len] >> rshift) & 0xff; /* add with carry to any value placed by previous passes */ tmp += carry + block[b]; block[b] = tmp & 0xff; /* save any carry that may be left */ carry = tmp >> 8; } /* if any carry is left at the end, add it through the number */ for (b = blocksize - 1; b >= 0 && carry != 0; b--) { carry += block[b]; block[b] = carry & 0xff; carry >>= 8; } } static int cipher_init(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, ENGINE *engine, const unsigned char *key, size_t key_len) { int klen, ret; - ret = EVP_EncryptInit_ex(ctx, cipher, engine, key, NULL); + ret = EVP_EncryptInit_ex(ctx, cipher, engine, NULL, NULL); if (!ret) goto out; /* set the key len for the odd variable key len cipher */ klen = EVP_CIPHER_CTX_get_key_length(ctx); if (key_len != (size_t)klen) { ret = EVP_CIPHER_CTX_set_key_length(ctx, key_len); if (ret <= 0) { ret = 0; goto out; } } + ret = EVP_EncryptInit_ex(ctx, NULL, NULL, key, NULL); + if (!ret) + goto out; /* we never want padding, either the length requested is a multiple of * the cipher block size or we are passed a cipher that can cope with * partial blocks via techniques like cipher text stealing */ ret = EVP_CIPHER_CTX_set_padding(ctx, 0); if (!ret) goto out; out: return ret; } static int KRB5KDF(const EVP_CIPHER *cipher, ENGINE *engine, const unsigned char *key, size_t key_len, const unsigned char *constant, size_t constant_len, unsigned char *okey, size_t okey_len) { EVP_CIPHER_CTX *ctx = NULL; unsigned char block[EVP_MAX_BLOCK_LENGTH * 2]; unsigned char *plainblock, *cipherblock; size_t blocksize; size_t cipherlen; size_t osize; #ifndef OPENSSL_NO_DES int des3_no_fixup = 0; #endif int ret; if (key_len != okey_len) { #ifndef OPENSSL_NO_DES /* special case for 3des, where the caller may be requesting * the random raw key, instead of the fixed up key */ if (EVP_CIPHER_get_nid(cipher) == NID_des_ede3_cbc && key_len == 24 && okey_len == 21) { des3_no_fixup = 1; } else { #endif ERR_raise(ERR_LIB_PROV, PROV_R_WRONG_OUTPUT_BUFFER_SIZE); return 0; #ifndef OPENSSL_NO_DES } #endif } ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) return 0; ret = cipher_init(ctx, cipher, engine, key, key_len); if (!ret) goto out; /* Initialize input block */ blocksize = EVP_CIPHER_CTX_get_block_size(ctx); if (blocksize == 0) { ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_CIPHER); ret = 0; goto out; } if (constant_len > blocksize) { ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CONSTANT_LENGTH); ret = 0; goto out; } n_fold(block, blocksize, constant, constant_len); plainblock = block; cipherblock = block + EVP_MAX_BLOCK_LENGTH; for (osize = 0; osize < okey_len; osize += cipherlen) { int olen; ret = EVP_EncryptUpdate(ctx, cipherblock, &olen, plainblock, blocksize); if (!ret) goto out; cipherlen = olen; ret = EVP_EncryptFinal_ex(ctx, cipherblock, &olen); if (!ret) goto out; if (olen != 0) { ERR_raise(ERR_LIB_PROV, PROV_R_WRONG_FINAL_BLOCK_LENGTH); ret = 0; goto out; } /* write cipherblock out */ if (cipherlen > okey_len - osize) cipherlen = okey_len - osize; memcpy(okey + osize, cipherblock, cipherlen); if (okey_len > osize + cipherlen) { /* we need to reinitialize cipher context per spec */ ret = EVP_CIPHER_CTX_reset(ctx); if (!ret) goto out; ret = cipher_init(ctx, cipher, engine, key, key_len); if (!ret) goto out; /* also swap block offsets so last ciphertext becomes new * plaintext */ plainblock = cipherblock; if (cipherblock == block) { cipherblock += EVP_MAX_BLOCK_LENGTH; } else { cipherblock = block; } } } #ifndef OPENSSL_NO_DES if (EVP_CIPHER_get_nid(cipher) == NID_des_ede3_cbc && !des3_no_fixup) { ret = fixup_des3_key(okey); if (!ret) { ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_GENERATE_KEY); goto out; } } #endif ret = 1; out: EVP_CIPHER_CTX_free(ctx); OPENSSL_cleanse(block, EVP_MAX_BLOCK_LENGTH * 2); return ret; } diff --git a/providers/implementations/keymgmt/ecx_kmgmt.c b/providers/implementations/keymgmt/ecx_kmgmt.c index e6d326a90705..0ebe8b4d59b1 100644 --- a/providers/implementations/keymgmt/ecx_kmgmt.c +++ b/providers/implementations/keymgmt/ecx_kmgmt.c @@ -1,1300 +1,1292 @@ /* * Copyright 2020-2025 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 #include "internal/fips.h" #include "internal/param_build_set.h" #include #include "crypto/ecx.h" #include "prov/implementations.h" #include "prov/providercommon.h" #include "prov/provider_ctx.h" #include "prov/ecx.h" #include "prov/securitycheck.h" #ifdef S390X_EC_ASM # include "s390x_arch.h" # include /* For SHA512_DIGEST_LENGTH */ #endif static OSSL_FUNC_keymgmt_new_fn x25519_new_key; static OSSL_FUNC_keymgmt_new_fn x448_new_key; static OSSL_FUNC_keymgmt_new_fn ed25519_new_key; static OSSL_FUNC_keymgmt_new_fn ed448_new_key; static OSSL_FUNC_keymgmt_gen_init_fn x25519_gen_init; static OSSL_FUNC_keymgmt_gen_init_fn x448_gen_init; static OSSL_FUNC_keymgmt_gen_init_fn ed25519_gen_init; static OSSL_FUNC_keymgmt_gen_init_fn ed448_gen_init; static OSSL_FUNC_keymgmt_gen_fn x25519_gen; static OSSL_FUNC_keymgmt_gen_fn x448_gen; static OSSL_FUNC_keymgmt_gen_fn ed25519_gen; static OSSL_FUNC_keymgmt_gen_fn ed448_gen; static OSSL_FUNC_keymgmt_gen_cleanup_fn ecx_gen_cleanup; static OSSL_FUNC_keymgmt_gen_set_params_fn ecx_gen_set_params; static OSSL_FUNC_keymgmt_gen_settable_params_fn ecx_gen_settable_params; static OSSL_FUNC_keymgmt_load_fn ecx_load; static OSSL_FUNC_keymgmt_get_params_fn x25519_get_params; static OSSL_FUNC_keymgmt_get_params_fn x448_get_params; static OSSL_FUNC_keymgmt_get_params_fn ed25519_get_params; static OSSL_FUNC_keymgmt_get_params_fn ed448_get_params; static OSSL_FUNC_keymgmt_gettable_params_fn x25519_gettable_params; static OSSL_FUNC_keymgmt_gettable_params_fn x448_gettable_params; static OSSL_FUNC_keymgmt_gettable_params_fn ed25519_gettable_params; static OSSL_FUNC_keymgmt_gettable_params_fn ed448_gettable_params; static OSSL_FUNC_keymgmt_set_params_fn x25519_set_params; static OSSL_FUNC_keymgmt_set_params_fn x448_set_params; static OSSL_FUNC_keymgmt_set_params_fn ed25519_set_params; static OSSL_FUNC_keymgmt_set_params_fn ed448_set_params; static OSSL_FUNC_keymgmt_settable_params_fn x25519_settable_params; static OSSL_FUNC_keymgmt_settable_params_fn x448_settable_params; static OSSL_FUNC_keymgmt_settable_params_fn ed25519_settable_params; static OSSL_FUNC_keymgmt_settable_params_fn ed448_settable_params; static OSSL_FUNC_keymgmt_has_fn ecx_has; static OSSL_FUNC_keymgmt_match_fn ecx_match; static OSSL_FUNC_keymgmt_validate_fn x25519_validate; static OSSL_FUNC_keymgmt_validate_fn x448_validate; static OSSL_FUNC_keymgmt_validate_fn ed25519_validate; static OSSL_FUNC_keymgmt_validate_fn ed448_validate; static OSSL_FUNC_keymgmt_import_fn ecx_import; static OSSL_FUNC_keymgmt_import_types_fn ecx_imexport_types; static OSSL_FUNC_keymgmt_export_fn ecx_export; static OSSL_FUNC_keymgmt_export_types_fn ecx_imexport_types; static OSSL_FUNC_keymgmt_dup_fn ecx_dup; #define ECX_POSSIBLE_SELECTIONS (OSSL_KEYMGMT_SELECT_KEYPAIR) struct ecx_gen_ctx { OSSL_LIB_CTX *libctx; char *propq; ECX_KEY_TYPE type; int selection; unsigned char *dhkem_ikm; size_t dhkem_ikmlen; }; #ifdef S390X_EC_ASM static void *s390x_ecx_keygen25519(struct ecx_gen_ctx *gctx); static void *s390x_ecx_keygen448(struct ecx_gen_ctx *gctx); static void *s390x_ecd_keygen25519(struct ecx_gen_ctx *gctx); static void *s390x_ecd_keygen448(struct ecx_gen_ctx *gctx); #endif #ifdef FIPS_MODULE static int ecd_fips140_pairwise_test(const ECX_KEY *ecx, int type, int self_test); #endif /* FIPS_MODULE */ static ossl_inline int ecx_key_type_is_ed(ECX_KEY_TYPE type) { return type == ECX_KEY_TYPE_ED25519 || type == ECX_KEY_TYPE_ED448; } static void *x25519_new_key(void *provctx) { if (!ossl_prov_is_running()) return 0; return ossl_ecx_key_new(PROV_LIBCTX_OF(provctx), ECX_KEY_TYPE_X25519, 0, NULL); } static void *x448_new_key(void *provctx) { if (!ossl_prov_is_running()) return 0; return ossl_ecx_key_new(PROV_LIBCTX_OF(provctx), ECX_KEY_TYPE_X448, 0, NULL); } static void *ed25519_new_key(void *provctx) { if (!ossl_prov_is_running()) return 0; return ossl_ecx_key_new(PROV_LIBCTX_OF(provctx), ECX_KEY_TYPE_ED25519, 0, NULL); } static void *ed448_new_key(void *provctx) { if (!ossl_prov_is_running()) return 0; return ossl_ecx_key_new(PROV_LIBCTX_OF(provctx), ECX_KEY_TYPE_ED448, 0, NULL); } static int ecx_has(const void *keydata, int selection) { const ECX_KEY *key = keydata; int ok = 0; if (ossl_prov_is_running() && key != NULL) { /* * ECX keys always have all the parameters they need (i.e. none). * Therefore we always return with 1, if asked about parameters. */ ok = 1; if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) ok = ok && key->haspubkey; if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) ok = ok && key->privkey != NULL; } return ok; } static int ecx_match(const void *keydata1, const void *keydata2, int selection) { const ECX_KEY *key1 = keydata1; const ECX_KEY *key2 = keydata2; int ok = 1; if (!ossl_prov_is_running()) return 0; if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0) ok = ok && key1->type == key2->type; if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) { int key_checked = 0; if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) { const unsigned char *pa = key1->haspubkey ? key1->pubkey : NULL; const unsigned char *pb = key2->haspubkey ? key2->pubkey : NULL; size_t pal = key1->keylen; size_t pbl = key2->keylen; if (pa != NULL && pb != NULL) { ok = ok && key1->type == key2->type && pal == pbl && CRYPTO_memcmp(pa, pb, pal) == 0; key_checked = 1; } } if (!key_checked && (selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) { const unsigned char *pa = key1->privkey; const unsigned char *pb = key2->privkey; size_t pal = key1->keylen; size_t pbl = key2->keylen; if (pa != NULL && pb != NULL) { ok = ok && key1->type == key2->type && pal == pbl && CRYPTO_memcmp(pa, pb, pal) == 0; key_checked = 1; } } ok = ok && key_checked; } return ok; } static int ecx_import(void *keydata, int selection, const OSSL_PARAM params[]) { ECX_KEY *key = keydata; int ok = 1; int include_private; if (!ossl_prov_is_running() || key == NULL) return 0; if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0) return 0; include_private = selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY ? 1 : 0; ok = ok && ossl_ecx_key_fromdata(key, params, include_private); -#ifdef FIPS_MODULE - if (ok > 0 && ecx_key_type_is_ed(key->type) && !ossl_fips_self_testing()) - if (key->haspubkey && key->privkey != NULL) { - ok = ecd_fips140_pairwise_test(key, key->type, 1); - if (ok <= 0) - ossl_set_error_state(OSSL_SELF_TEST_TYPE_PCT_IMPORT); - } -#endif /* FIPS_MODULE */ return ok; } static int key_to_params(ECX_KEY *key, OSSL_PARAM_BLD *tmpl, OSSL_PARAM params[], int include_private) { if (key == NULL) return 0; if (!ossl_param_build_set_octet_string(tmpl, params, OSSL_PKEY_PARAM_PUB_KEY, key->pubkey, key->keylen)) return 0; if (include_private && key->privkey != NULL && !ossl_param_build_set_octet_string(tmpl, params, OSSL_PKEY_PARAM_PRIV_KEY, key->privkey, key->keylen)) return 0; return 1; } static int ecx_export(void *keydata, int selection, OSSL_CALLBACK *param_cb, void *cbarg) { ECX_KEY *key = keydata; OSSL_PARAM_BLD *tmpl; OSSL_PARAM *params = NULL; int ret = 0; if (!ossl_prov_is_running() || key == NULL) return 0; if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0) return 0; tmpl = OSSL_PARAM_BLD_new(); if (tmpl == NULL) return 0; if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) { int include_private = ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0); if (!key_to_params(key, tmpl, NULL, include_private)) goto err; } params = OSSL_PARAM_BLD_to_param(tmpl); if (params == NULL) goto err; ret = param_cb(params, cbarg); OSSL_PARAM_free(params); err: OSSL_PARAM_BLD_free(tmpl); return ret; } #define ECX_KEY_TYPES() \ OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PUB_KEY, NULL, 0), \ OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PRIV_KEY, NULL, 0) static const OSSL_PARAM ecx_key_types[] = { ECX_KEY_TYPES(), OSSL_PARAM_END }; static const OSSL_PARAM *ecx_imexport_types(int selection) { if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) return ecx_key_types; return NULL; } static int ecx_get_params(void *key, OSSL_PARAM params[], int bits, int secbits, int size) { ECX_KEY *ecx = key; OSSL_PARAM *p; if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_BITS)) != NULL && !OSSL_PARAM_set_int(p, bits)) return 0; if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_SECURITY_BITS)) != NULL && !OSSL_PARAM_set_int(p, secbits)) return 0; if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_MAX_SIZE)) != NULL && !OSSL_PARAM_set_int(p, size)) return 0; if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY)) != NULL && (ecx->type == ECX_KEY_TYPE_X25519 || ecx->type == ECX_KEY_TYPE_X448)) { if (!OSSL_PARAM_set_octet_string(p, ecx->pubkey, ecx->keylen)) return 0; } #ifdef FIPS_MODULE { /* X25519 and X448 are not approved */ int approved = 0; p = OSSL_PARAM_locate(params, OSSL_ALG_PARAM_FIPS_APPROVED_INDICATOR); if (p != NULL && !OSSL_PARAM_set_int(p, approved)) return 0; } #endif return key_to_params(ecx, NULL, params, 1); } static int ed_get_params(void *key, OSSL_PARAM params[]) { OSSL_PARAM *p; if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_MANDATORY_DIGEST)) != NULL && !OSSL_PARAM_set_utf8_string(p, "")) return 0; return 1; } static int x25519_get_params(void *key, OSSL_PARAM params[]) { return ecx_get_params(key, params, X25519_BITS, X25519_SECURITY_BITS, X25519_KEYLEN); } static int x448_get_params(void *key, OSSL_PARAM params[]) { return ecx_get_params(key, params, X448_BITS, X448_SECURITY_BITS, X448_KEYLEN); } static int ed25519_get_params(void *key, OSSL_PARAM params[]) { return ecx_get_params(key, params, ED25519_BITS, ED25519_SECURITY_BITS, ED25519_SIGSIZE) && ed_get_params(key, params); } static int ed448_get_params(void *key, OSSL_PARAM params[]) { return ecx_get_params(key, params, ED448_BITS, ED448_SECURITY_BITS, ED448_SIGSIZE) && ed_get_params(key, params); } static const OSSL_PARAM ecx_gettable_params[] = { OSSL_PARAM_int(OSSL_PKEY_PARAM_BITS, NULL), OSSL_PARAM_int(OSSL_PKEY_PARAM_SECURITY_BITS, NULL), OSSL_PARAM_int(OSSL_PKEY_PARAM_MAX_SIZE, NULL), OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, NULL, 0), ECX_KEY_TYPES(), OSSL_FIPS_IND_GETTABLE_CTX_PARAM() OSSL_PARAM_END }; static const OSSL_PARAM ed_gettable_params[] = { OSSL_PARAM_int(OSSL_PKEY_PARAM_BITS, NULL), OSSL_PARAM_int(OSSL_PKEY_PARAM_SECURITY_BITS, NULL), OSSL_PARAM_int(OSSL_PKEY_PARAM_MAX_SIZE, NULL), OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_MANDATORY_DIGEST, NULL, 0), ECX_KEY_TYPES(), OSSL_PARAM_END }; static const OSSL_PARAM *x25519_gettable_params(void *provctx) { return ecx_gettable_params; } static const OSSL_PARAM *x448_gettable_params(void *provctx) { return ecx_gettable_params; } static const OSSL_PARAM *ed25519_gettable_params(void *provctx) { return ed_gettable_params; } static const OSSL_PARAM *ed448_gettable_params(void *provctx) { return ed_gettable_params; } static int set_property_query(ECX_KEY *ecxkey, const char *propq) { OPENSSL_free(ecxkey->propq); ecxkey->propq = NULL; if (propq != NULL) { ecxkey->propq = OPENSSL_strdup(propq); if (ecxkey->propq == NULL) return 0; } return 1; } static int ecx_set_params(void *key, const OSSL_PARAM params[]) { ECX_KEY *ecxkey = key; const OSSL_PARAM *p; if (ossl_param_is_empty(params)) return 1; p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY); if (p != NULL) { void *buf = ecxkey->pubkey; if (p->data_size != ecxkey->keylen || !OSSL_PARAM_get_octet_string(p, &buf, sizeof(ecxkey->pubkey), NULL)) return 0; OPENSSL_clear_free(ecxkey->privkey, ecxkey->keylen); ecxkey->privkey = NULL; ecxkey->haspubkey = 1; } p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PROPERTIES); if (p != NULL) { if (p->data_type != OSSL_PARAM_UTF8_STRING || !set_property_query(ecxkey, p->data)) return 0; } return 1; } static int x25519_set_params(void *key, const OSSL_PARAM params[]) { return ecx_set_params(key, params); } static int x448_set_params(void *key, const OSSL_PARAM params[]) { return ecx_set_params(key, params); } static int ed25519_set_params(void *key, const OSSL_PARAM params[]) { return 1; } static int ed448_set_params(void *key, const OSSL_PARAM params[]) { return 1; } static const OSSL_PARAM ecx_settable_params[] = { OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, NULL, 0), OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_PROPERTIES, NULL, 0), OSSL_PARAM_END }; static const OSSL_PARAM ed_settable_params[] = { OSSL_PARAM_END }; static const OSSL_PARAM *x25519_settable_params(void *provctx) { return ecx_settable_params; } static const OSSL_PARAM *x448_settable_params(void *provctx) { return ecx_settable_params; } static const OSSL_PARAM *ed25519_settable_params(void *provctx) { return ed_settable_params; } static const OSSL_PARAM *ed448_settable_params(void *provctx) { return ed_settable_params; } static void *ecx_gen_init(void *provctx, int selection, const OSSL_PARAM params[], ECX_KEY_TYPE type, const char *algdesc) { OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(provctx); struct ecx_gen_ctx *gctx = NULL; if (!ossl_prov_is_running()) return NULL; if ((gctx = OPENSSL_zalloc(sizeof(*gctx))) != NULL) { gctx->libctx = libctx; gctx->type = type; gctx->selection = selection; #ifdef FIPS_MODULE /* X25519/X448 are not FIPS approved, (ED25519/ED448 are approved) */ if (algdesc != NULL && !ossl_FIPS_IND_callback(libctx, algdesc, "KeyGen Init")) { OPENSSL_free(gctx); return NULL; } #endif } else { return NULL; } if (!ecx_gen_set_params(gctx, params)) { ecx_gen_cleanup(gctx); gctx = NULL; } return gctx; } static void *x25519_gen_init(void *provctx, int selection, const OSSL_PARAM params[]) { return ecx_gen_init(provctx, selection, params, ECX_KEY_TYPE_X25519, "X25519"); } static void *x448_gen_init(void *provctx, int selection, const OSSL_PARAM params[]) { return ecx_gen_init(provctx, selection, params, ECX_KEY_TYPE_X448, "X448"); } static void *ed25519_gen_init(void *provctx, int selection, const OSSL_PARAM params[]) { return ecx_gen_init(provctx, selection, params, ECX_KEY_TYPE_ED25519, NULL); } static void *ed448_gen_init(void *provctx, int selection, const OSSL_PARAM params[]) { return ecx_gen_init(provctx, selection, params, ECX_KEY_TYPE_ED448, NULL); } static int ecx_gen_set_params(void *genctx, const OSSL_PARAM params[]) { struct ecx_gen_ctx *gctx = genctx; const OSSL_PARAM *p; if (gctx == NULL) return 0; p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_GROUP_NAME); if (p != NULL) { const char *groupname = NULL; /* * We optionally allow setting a group name - but each algorithm only * support one such name, so all we do is verify that it is the one we * expected. */ switch (gctx->type) { case ECX_KEY_TYPE_X25519: groupname = "x25519"; break; case ECX_KEY_TYPE_X448: groupname = "x448"; break; default: /* We only support this for key exchange at the moment */ break; } if (p->data_type != OSSL_PARAM_UTF8_STRING || groupname == NULL || OPENSSL_strcasecmp(p->data, groupname) != 0) { ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } } p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_PROPERTIES); if (p != NULL) { if (p->data_type != OSSL_PARAM_UTF8_STRING) return 0; OPENSSL_free(gctx->propq); gctx->propq = OPENSSL_strdup(p->data); if (gctx->propq == NULL) return 0; } p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_DHKEM_IKM); if (p != NULL) { if (p->data_size != 0 && p->data != NULL) { OPENSSL_free(gctx->dhkem_ikm); gctx->dhkem_ikm = NULL; if (!OSSL_PARAM_get_octet_string(p, (void **)&gctx->dhkem_ikm, 0, &gctx->dhkem_ikmlen)) return 0; } } return 1; } static const OSSL_PARAM *ecx_gen_settable_params(ossl_unused void *genctx, ossl_unused void *provctx) { static OSSL_PARAM settable[] = { OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME, NULL, 0), OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0), OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_DHKEM_IKM, NULL, 0), OSSL_PARAM_END }; return settable; } #ifdef FIPS_MODULE /* * Refer: FIPS 140-3 IG 10.3.A Additional Comment 1 * Perform a pairwise test for EDDSA by signing and verifying signature. * * The parameter `self_test` is used to indicate whether to create OSSL_SELF_TEST * instance. */ static int ecd_fips140_pairwise_test(const ECX_KEY *ecx, int type, int self_test) { int ret = 0; OSSL_SELF_TEST *st = NULL; OSSL_CALLBACK *cb = NULL; void *cbarg = NULL; unsigned char msg[16] = {0}; size_t msg_len = sizeof(msg); unsigned char sig[ED448_SIGSIZE] = {0}; int is_ed25519 = (type == ECX_KEY_TYPE_ED25519) ? 1 : 0; int operation_result = 0; /* * The functions `OSSL_SELF_TEST_*` will return directly if parameter `st` * is NULL. */ if (self_test) { OSSL_SELF_TEST_get_callback(ecx->libctx, &cb, &cbarg); st = OSSL_SELF_TEST_new(cb, cbarg); if (st == NULL) return 0; } OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_PCT, OSSL_SELF_TEST_DESC_PCT_EDDSA); if (is_ed25519) operation_result = ossl_ed25519_sign(sig, msg, msg_len, ecx->pubkey, ecx->privkey, 0, 0, 0, NULL, 0, ecx->libctx, ecx->propq); else operation_result = ossl_ed448_sign(ecx->libctx, sig, msg, msg_len, ecx->pubkey, ecx->privkey, NULL, 0, 0, ecx->propq); if (operation_result != 1) goto err; OSSL_SELF_TEST_oncorrupt_byte(st, sig); if (is_ed25519) operation_result = ossl_ed25519_verify(msg, msg_len, sig, ecx->pubkey, 0, 0, 0, NULL, 0, ecx->libctx, ecx->propq); else operation_result = ossl_ed448_verify(ecx->libctx, msg, msg_len, sig, ecx->pubkey, NULL, 0, 0, ecx->propq); if (operation_result != 1) goto err; ret = 1; err: OSSL_SELF_TEST_onend(st, ret); OSSL_SELF_TEST_free(st); return ret; } #endif static void *ecx_gen(struct ecx_gen_ctx *gctx) { ECX_KEY *key; unsigned char *privkey; if (gctx == NULL) return NULL; if ((key = ossl_ecx_key_new(gctx->libctx, gctx->type, 0, gctx->propq)) == NULL) { ERR_raise(ERR_LIB_PROV, ERR_R_EC_LIB); return NULL; } /* If we're doing parameter generation then we just return a blank key */ if ((gctx->selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0) return key; if ((privkey = ossl_ecx_key_allocate_privkey(key)) == NULL) { ERR_raise(ERR_LIB_PROV, ERR_R_EC_LIB); goto err; } #ifndef FIPS_MODULE if (gctx->dhkem_ikm != NULL && gctx->dhkem_ikmlen != 0) { if (ecx_key_type_is_ed(gctx->type)) goto err; if (!ossl_ecx_dhkem_derive_private(key, privkey, gctx->dhkem_ikm, gctx->dhkem_ikmlen)) goto err; } else #endif { if (RAND_priv_bytes_ex(gctx->libctx, privkey, key->keylen, 0) <= 0) goto err; } switch (gctx->type) { case ECX_KEY_TYPE_X25519: privkey[0] &= 248; privkey[X25519_KEYLEN - 1] &= 127; privkey[X25519_KEYLEN - 1] |= 64; ossl_x25519_public_from_private(key->pubkey, privkey); break; case ECX_KEY_TYPE_X448: privkey[0] &= 252; privkey[X448_KEYLEN - 1] |= 128; ossl_x448_public_from_private(key->pubkey, privkey); break; case ECX_KEY_TYPE_ED25519: if (!ossl_ed25519_public_from_private(gctx->libctx, key->pubkey, privkey, gctx->propq)) goto err; break; case ECX_KEY_TYPE_ED448: if (!ossl_ed448_public_from_private(gctx->libctx, key->pubkey, privkey, gctx->propq)) goto err; break; } key->haspubkey = 1; return key; err: ossl_ecx_key_free(key); return NULL; } static void *x25519_gen(void *genctx, OSSL_CALLBACK *osslcb, void *cbarg) { struct ecx_gen_ctx *gctx = genctx; if (!ossl_prov_is_running()) return 0; #ifdef S390X_EC_ASM if (OPENSSL_s390xcap_P.pcc[1] & S390X_CAPBIT(S390X_SCALAR_MULTIPLY_X25519)) return s390x_ecx_keygen25519(gctx); #endif return ecx_gen(gctx); } static void *x448_gen(void *genctx, OSSL_CALLBACK *osslcb, void *cbarg) { struct ecx_gen_ctx *gctx = genctx; if (!ossl_prov_is_running()) return 0; #ifdef S390X_EC_ASM if (OPENSSL_s390xcap_P.pcc[1] & S390X_CAPBIT(S390X_SCALAR_MULTIPLY_X448)) return s390x_ecx_keygen448(gctx); #endif return ecx_gen(gctx); } static void *ed25519_gen(void *genctx, OSSL_CALLBACK *osslcb, void *cbarg) { ECX_KEY *key = NULL; struct ecx_gen_ctx *gctx = genctx; if (!ossl_prov_is_running()) return 0; #ifdef S390X_EC_ASM if (OPENSSL_s390xcap_P.pcc[1] & S390X_CAPBIT(S390X_SCALAR_MULTIPLY_ED25519) && OPENSSL_s390xcap_P.kdsa[0] & S390X_CAPBIT(S390X_EDDSA_SIGN_ED25519) && OPENSSL_s390xcap_P.kdsa[0] & S390X_CAPBIT(S390X_EDDSA_VERIFY_ED25519)) { key = s390x_ecd_keygen25519(gctx); } else #endif { key = ecx_gen(gctx); } #ifdef FIPS_MODULE /* Exit if keygen failed OR we are doing parameter generation (blank key) */ if (!key || ((gctx->selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0)) return key; if (ecd_fips140_pairwise_test(key, ECX_KEY_TYPE_ED25519, 1) != 1) { ossl_set_error_state(OSSL_SELF_TEST_TYPE_PCT); ossl_ecx_key_free(key); return NULL; } #endif return key; } static void *ed448_gen(void *genctx, OSSL_CALLBACK *osslcb, void *cbarg) { ECX_KEY *key = NULL; struct ecx_gen_ctx *gctx = genctx; if (!ossl_prov_is_running()) return 0; #ifdef S390X_EC_ASM if (OPENSSL_s390xcap_P.pcc[1] & S390X_CAPBIT(S390X_SCALAR_MULTIPLY_ED448) && OPENSSL_s390xcap_P.kdsa[0] & S390X_CAPBIT(S390X_EDDSA_SIGN_ED448) && OPENSSL_s390xcap_P.kdsa[0] & S390X_CAPBIT(S390X_EDDSA_VERIFY_ED448)) { key = s390x_ecd_keygen448(gctx); } else #endif { key = ecx_gen(gctx); } #ifdef FIPS_MODULE /* Exit if keygen failed OR we are doing parameter generation (blank key) */ if (!key || ((gctx->selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0)) return key; if (ecd_fips140_pairwise_test(key, ECX_KEY_TYPE_ED448, 1) != 1) { ossl_set_error_state(OSSL_SELF_TEST_TYPE_PCT); ossl_ecx_key_free(key); return NULL; } #endif return key; } static void ecx_gen_cleanup(void *genctx) { struct ecx_gen_ctx *gctx = genctx; if (gctx == NULL) return; OPENSSL_clear_free(gctx->dhkem_ikm, gctx->dhkem_ikmlen); OPENSSL_free(gctx->propq); OPENSSL_free(gctx); } void *ecx_load(const void *reference, size_t reference_sz) { ECX_KEY *key = NULL; if (ossl_prov_is_running() && reference_sz == sizeof(key)) { /* The contents of the reference is the address to our object */ key = *(ECX_KEY **)reference; /* We grabbed, so we detach it */ *(ECX_KEY **)reference = NULL; return key; } return NULL; } static void *ecx_dup(const void *keydata_from, int selection) { if (ossl_prov_is_running()) return ossl_ecx_key_dup(keydata_from, selection); return NULL; } static int ecx_key_pairwise_check(const ECX_KEY *ecx, int type) { uint8_t pub[64]; switch (type) { case ECX_KEY_TYPE_X25519: ossl_x25519_public_from_private(pub, ecx->privkey); break; case ECX_KEY_TYPE_X448: ossl_x448_public_from_private(pub, ecx->privkey); break; default: return 0; } return CRYPTO_memcmp(ecx->pubkey, pub, ecx->keylen) == 0; } #ifdef FIPS_MODULE /* * FIPS ACVP testing requires the ability to check if the public key is valid * This is not required normally since the ED signature verify does the test * internally. */ static int ecd_key_pub_check(const ECX_KEY *ecx, int type) { switch (type) { case ECX_KEY_TYPE_ED25519: return ossl_ed25519_pubkey_verify(ecx->pubkey, ecx->keylen); case ECX_KEY_TYPE_ED448: return ossl_ed448_pubkey_verify(ecx->pubkey, ecx->keylen); default: return 1; } } #endif #ifdef FIPS_MODULE static int ecd_key_pairwise_check(const ECX_KEY *ecx, int type) { return ecd_fips140_pairwise_test(ecx, type, 0); } #else static int ecd_key_pairwise_check(const ECX_KEY *ecx, int type) { uint8_t pub[64]; switch (type) { case ECX_KEY_TYPE_ED25519: if (!ossl_ed25519_public_from_private(ecx->libctx, pub, ecx->privkey, ecx->propq)) return 0; break; case ECX_KEY_TYPE_ED448: if (!ossl_ed448_public_from_private(ecx->libctx, pub, ecx->privkey, ecx->propq)) return 0; break; default: return 0; } return CRYPTO_memcmp(ecx->pubkey, pub, ecx->keylen) == 0; } #endif static int ecx_validate(const void *keydata, int selection, int type, size_t keylen) { const ECX_KEY *ecx = keydata; int ok = keylen == ecx->keylen; if (!ossl_prov_is_running()) return 0; if ((selection & ECX_POSSIBLE_SELECTIONS) == 0) return 1; /* nothing to validate */ if (!ok) { ERR_raise(ERR_LIB_PROV, PROV_R_ALGORITHM_MISMATCH); return 0; } if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) { ok = ok && ecx->haspubkey; #ifdef FIPS_MODULE ok = ok && ecd_key_pub_check(ecx, type); #endif } if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) ok = ok && ecx->privkey != NULL; if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != OSSL_KEYMGMT_SELECT_KEYPAIR) return ok; if (ecx_key_type_is_ed(type)) ok = ok && ecd_key_pairwise_check(ecx, type); else ok = ok && ecx_key_pairwise_check(ecx, type); return ok; } static int x25519_validate(const void *keydata, int selection, int checktype) { return ecx_validate(keydata, selection, ECX_KEY_TYPE_X25519, X25519_KEYLEN); } static int x448_validate(const void *keydata, int selection, int checktype) { return ecx_validate(keydata, selection, ECX_KEY_TYPE_X448, X448_KEYLEN); } static int ed25519_validate(const void *keydata, int selection, int checktype) { return ecx_validate(keydata, selection, ECX_KEY_TYPE_ED25519, ED25519_KEYLEN); } static int ed448_validate(const void *keydata, int selection, int checktype) { return ecx_validate(keydata, selection, ECX_KEY_TYPE_ED448, ED448_KEYLEN); } #define MAKE_KEYMGMT_FUNCTIONS(alg) \ const OSSL_DISPATCH ossl_##alg##_keymgmt_functions[] = { \ { OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))alg##_new_key }, \ { OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))ossl_ecx_key_free }, \ { OSSL_FUNC_KEYMGMT_GET_PARAMS, (void (*) (void))alg##_get_params }, \ { OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*) (void))alg##_gettable_params }, \ { OSSL_FUNC_KEYMGMT_SET_PARAMS, (void (*) (void))alg##_set_params }, \ { OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS, (void (*) (void))alg##_settable_params }, \ { OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))ecx_has }, \ { OSSL_FUNC_KEYMGMT_MATCH, (void (*)(void))ecx_match }, \ { OSSL_FUNC_KEYMGMT_VALIDATE, (void (*)(void))alg##_validate }, \ { OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))ecx_import }, \ { OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))ecx_imexport_types }, \ { OSSL_FUNC_KEYMGMT_EXPORT, (void (*)(void))ecx_export }, \ { OSSL_FUNC_KEYMGMT_EXPORT_TYPES, (void (*)(void))ecx_imexport_types }, \ { OSSL_FUNC_KEYMGMT_GEN_INIT, (void (*)(void))alg##_gen_init }, \ { OSSL_FUNC_KEYMGMT_GEN_SET_PARAMS, (void (*)(void))ecx_gen_set_params }, \ { OSSL_FUNC_KEYMGMT_GEN_SETTABLE_PARAMS, \ (void (*)(void))ecx_gen_settable_params }, \ { OSSL_FUNC_KEYMGMT_GEN, (void (*)(void))alg##_gen }, \ { OSSL_FUNC_KEYMGMT_GEN_CLEANUP, (void (*)(void))ecx_gen_cleanup }, \ { OSSL_FUNC_KEYMGMT_LOAD, (void (*)(void))ecx_load }, \ { OSSL_FUNC_KEYMGMT_DUP, (void (*)(void))ecx_dup }, \ OSSL_DISPATCH_END \ }; MAKE_KEYMGMT_FUNCTIONS(x25519) MAKE_KEYMGMT_FUNCTIONS(x448) MAKE_KEYMGMT_FUNCTIONS(ed25519) MAKE_KEYMGMT_FUNCTIONS(ed448) #ifdef S390X_EC_ASM # include "s390x_arch.h" static void *s390x_ecx_keygen25519(struct ecx_gen_ctx *gctx) { static const unsigned char generator[] = { 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; ECX_KEY *key = ossl_ecx_key_new(gctx->libctx, ECX_KEY_TYPE_X25519, 1, gctx->propq); unsigned char *privkey = NULL, *pubkey; if (key == NULL) { ERR_raise(ERR_LIB_PROV, ERR_R_EC_LIB); goto err; } /* If we're doing parameter generation then we just return a blank key */ if ((gctx->selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0) return key; pubkey = key->pubkey; privkey = ossl_ecx_key_allocate_privkey(key); if (privkey == NULL) { ERR_raise(ERR_LIB_PROV, ERR_R_EC_LIB); goto err; } #ifndef FIPS_MODULE if (gctx->dhkem_ikm != NULL && gctx->dhkem_ikmlen != 0) { if (gctx->type != ECX_KEY_TYPE_X25519) goto err; if (!ossl_ecx_dhkem_derive_private(key, privkey, gctx->dhkem_ikm, gctx->dhkem_ikmlen)) goto err; } else #endif { if (RAND_priv_bytes_ex(gctx->libctx, privkey, X25519_KEYLEN, 0) <= 0) goto err; } privkey[0] &= 248; privkey[31] &= 127; privkey[31] |= 64; if (s390x_x25519_mul(pubkey, generator, privkey) != 1) goto err; key->haspubkey = 1; return key; err: ossl_ecx_key_free(key); return NULL; } static void *s390x_ecx_keygen448(struct ecx_gen_ctx *gctx) { static const unsigned char generator[] = { 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; ECX_KEY *key = ossl_ecx_key_new(gctx->libctx, ECX_KEY_TYPE_X448, 1, gctx->propq); unsigned char *privkey = NULL, *pubkey; if (key == NULL) { ERR_raise(ERR_LIB_PROV, ERR_R_EC_LIB); goto err; } /* If we're doing parameter generation then we just return a blank key */ if ((gctx->selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0) return key; pubkey = key->pubkey; privkey = ossl_ecx_key_allocate_privkey(key); if (privkey == NULL) { ERR_raise(ERR_LIB_PROV, ERR_R_EC_LIB); goto err; } #ifndef FIPS_MODULE if (gctx->dhkem_ikm != NULL && gctx->dhkem_ikmlen != 0) { if (gctx->type != ECX_KEY_TYPE_X448) goto err; if (!ossl_ecx_dhkem_derive_private(key, privkey, gctx->dhkem_ikm, gctx->dhkem_ikmlen)) goto err; } else #endif { if (RAND_priv_bytes_ex(gctx->libctx, privkey, X448_KEYLEN, 0) <= 0) goto err; } privkey[0] &= 252; privkey[55] |= 128; if (s390x_x448_mul(pubkey, generator, privkey) != 1) goto err; key->haspubkey = 1; return key; err: ossl_ecx_key_free(key); return NULL; } static void *s390x_ecd_keygen25519(struct ecx_gen_ctx *gctx) { static const unsigned char generator_x[] = { 0x1a, 0xd5, 0x25, 0x8f, 0x60, 0x2d, 0x56, 0xc9, 0xb2, 0xa7, 0x25, 0x95, 0x60, 0xc7, 0x2c, 0x69, 0x5c, 0xdc, 0xd6, 0xfd, 0x31, 0xe2, 0xa4, 0xc0, 0xfe, 0x53, 0x6e, 0xcd, 0xd3, 0x36, 0x69, 0x21 }; static const unsigned char generator_y[] = { 0x58, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, }; unsigned char x_dst[32], buff[SHA512_DIGEST_LENGTH]; ECX_KEY *key = ossl_ecx_key_new(gctx->libctx, ECX_KEY_TYPE_ED25519, 1, gctx->propq); unsigned char *privkey = NULL, *pubkey; unsigned int sz; EVP_MD *sha = NULL; int j; if (key == NULL) { ERR_raise(ERR_LIB_PROV, ERR_R_EC_LIB); goto err; } /* If we're doing parameter generation then we just return a blank key */ if ((gctx->selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0) return key; pubkey = key->pubkey; privkey = ossl_ecx_key_allocate_privkey(key); if (privkey == NULL) { ERR_raise(ERR_LIB_PROV, ERR_R_EC_LIB); goto err; } if (RAND_priv_bytes_ex(gctx->libctx, privkey, ED25519_KEYLEN, 0) <= 0) goto err; sha = EVP_MD_fetch(gctx->libctx, "SHA512", gctx->propq); if (sha == NULL) goto err; j = EVP_Digest(privkey, 32, buff, &sz, sha, NULL); EVP_MD_free(sha); if (!j) goto err; buff[0] &= 248; buff[31] &= 63; buff[31] |= 64; if (s390x_ed25519_mul(x_dst, pubkey, generator_x, generator_y, buff) != 1) goto err; pubkey[31] |= ((x_dst[0] & 0x01) << 7); key->haspubkey = 1; return key; err: ossl_ecx_key_free(key); return NULL; } static void *s390x_ecd_keygen448(struct ecx_gen_ctx *gctx) { static const unsigned char generator_x[] = { 0x5e, 0xc0, 0x0c, 0xc7, 0x2b, 0xa8, 0x26, 0x26, 0x8e, 0x93, 0x00, 0x8b, 0xe1, 0x80, 0x3b, 0x43, 0x11, 0x65, 0xb6, 0x2a, 0xf7, 0x1a, 0xae, 0x12, 0x64, 0xa4, 0xd3, 0xa3, 0x24, 0xe3, 0x6d, 0xea, 0x67, 0x17, 0x0f, 0x47, 0x70, 0x65, 0x14, 0x9e, 0xda, 0x36, 0xbf, 0x22, 0xa6, 0x15, 0x1d, 0x22, 0xed, 0x0d, 0xed, 0x6b, 0xc6, 0x70, 0x19, 0x4f, 0x00 }; static const unsigned char generator_y[] = { 0x14, 0xfa, 0x30, 0xf2, 0x5b, 0x79, 0x08, 0x98, 0xad, 0xc8, 0xd7, 0x4e, 0x2c, 0x13, 0xbd, 0xfd, 0xc4, 0x39, 0x7c, 0xe6, 0x1c, 0xff, 0xd3, 0x3a, 0xd7, 0xc2, 0xa0, 0x05, 0x1e, 0x9c, 0x78, 0x87, 0x40, 0x98, 0xa3, 0x6c, 0x73, 0x73, 0xea, 0x4b, 0x62, 0xc7, 0xc9, 0x56, 0x37, 0x20, 0x76, 0x88, 0x24, 0xbc, 0xb6, 0x6e, 0x71, 0x46, 0x3f, 0x69, 0x00 }; unsigned char x_dst[57], buff[114]; ECX_KEY *key = ossl_ecx_key_new(gctx->libctx, ECX_KEY_TYPE_ED448, 1, gctx->propq); unsigned char *privkey = NULL, *pubkey; EVP_MD_CTX *hashctx = NULL; EVP_MD *shake = NULL; if (key == NULL) { ERR_raise(ERR_LIB_PROV, ERR_R_EC_LIB); goto err; } /* If we're doing parameter generation then we just return a blank key */ if ((gctx->selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0) return key; pubkey = key->pubkey; privkey = ossl_ecx_key_allocate_privkey(key); if (privkey == NULL) { ERR_raise(ERR_LIB_PROV, ERR_R_EC_LIB); goto err; } shake = EVP_MD_fetch(gctx->libctx, "SHAKE256", gctx->propq); if (shake == NULL) goto err; if (RAND_priv_bytes_ex(gctx->libctx, privkey, ED448_KEYLEN, 0) <= 0) goto err; hashctx = EVP_MD_CTX_new(); if (hashctx == NULL) goto err; if (EVP_DigestInit_ex(hashctx, shake, NULL) != 1) goto err; if (EVP_DigestUpdate(hashctx, privkey, 57) != 1) goto err; if (EVP_DigestFinalXOF(hashctx, buff, sizeof(buff)) != 1) goto err; buff[0] &= -4; buff[55] |= 0x80; buff[56] = 0; if (s390x_ed448_mul(x_dst, pubkey, generator_x, generator_y, buff) != 1) goto err; pubkey[56] |= ((x_dst[0] & 0x01) << 7); EVP_MD_CTX_free(hashctx); EVP_MD_free(shake); key->haspubkey = 1; return key; err: ossl_ecx_key_free(key); EVP_MD_CTX_free(hashctx); EVP_MD_free(shake); return NULL; } #endif diff --git a/ssl/quic/quic_impl.c b/ssl/quic/quic_impl.c index c44e6b33c2a8..cec05d5bd37b 100644 --- a/ssl/quic/quic_impl.c +++ b/ssl/quic/quic_impl.c @@ -1,5383 +1,5386 @@ /* * Copyright 2022-2025 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 "quic_local.h" #include "internal/hashfunc.h" #include "internal/ssl_unwrap.h" #include "internal/quic_tls.h" #include "internal/quic_rx_depack.h" #include "internal/quic_error.h" #include "internal/quic_engine.h" #include "internal/quic_port.h" #include "internal/quic_reactor_wait_ctx.h" #include "internal/time.h" typedef struct qctx_st QCTX; static void qc_cleanup(QUIC_CONNECTION *qc, int have_lock); static void aon_write_finish(QUIC_XSO *xso); static int create_channel(QUIC_CONNECTION *qc, SSL_CTX *ctx); static QUIC_XSO *create_xso_from_stream(QUIC_CONNECTION *qc, QUIC_STREAM *qs); static QUIC_CONNECTION *create_qc_from_incoming_conn(QUIC_LISTENER *ql, QUIC_CHANNEL *ch); static int qc_try_create_default_xso_for_write(QCTX *ctx); static int qc_wait_for_default_xso_for_read(QCTX *ctx, int peek); static void qctx_lock(QCTX *qctx); static void qctx_unlock(QCTX *qctx); static void qctx_lock_for_io(QCTX *ctx); static int quic_do_handshake(QCTX *ctx); static void qc_update_reject_policy(QUIC_CONNECTION *qc); static void qc_touch_default_xso(QUIC_CONNECTION *qc); static void qc_set_default_xso(QUIC_CONNECTION *qc, QUIC_XSO *xso, int touch); static void qc_set_default_xso_keep_ref(QUIC_CONNECTION *qc, QUIC_XSO *xso, int touch, QUIC_XSO **old_xso); static SSL *quic_conn_stream_new(QCTX *ctx, uint64_t flags, int need_lock); static int quic_validate_for_write(QUIC_XSO *xso, int *err); static int quic_mutation_allowed(QUIC_CONNECTION *qc, int req_active); static void qctx_maybe_autotick(QCTX *ctx); static int qctx_should_autotick(QCTX *ctx); /* * QCTX is a utility structure which provides information we commonly wish to * unwrap upon an API call being dispatched to us, namely: * * - a pointer to the QUIC_CONNECTION (regardless of whether a QCSO or QSSO * was passed); * - a pointer to any applicable QUIC_XSO (e.g. if a QSSO was passed, or if * a QCSO with a default stream was passed); * - whether a QSSO was passed (xso == NULL must not be used to determine this * because it may be non-NULL when a QCSO is passed if that QCSO has a * default stream); * - a pointer to a QUIC_LISTENER object, if one is relevant; * - whether we are in "I/O context", meaning that non-normal errors can * be reported via SSL_get_error() as well as via ERR. Functions such as * SSL_read(), SSL_write() and SSL_do_handshake() are "I/O context" * functions which are allowed to change the value returned by * SSL_get_error. However, other functions (including functions which call * SSL_do_handshake() implicitly) are not allowed to change the return value * of SSL_get_error. */ struct qctx_st { QUIC_OBJ *obj; QUIC_DOMAIN *qd; QUIC_LISTENER *ql; QUIC_CONNECTION *qc; QUIC_XSO *xso; int is_stream, is_listener, is_domain, in_io; }; QUIC_NEEDS_LOCK static void quic_set_last_error(QCTX *ctx, int last_error) { if (!ctx->in_io) return; if (ctx->is_stream && ctx->xso != NULL) ctx->xso->last_error = last_error; else if (!ctx->is_stream && ctx->qc != NULL) ctx->qc->last_error = last_error; } /* * Raise a 'normal' error, meaning one that can be reported via SSL_get_error() * rather than via ERR. Note that normal errors must always be raised while * holding a lock. */ QUIC_NEEDS_LOCK static int quic_raise_normal_error(QCTX *ctx, int err) { assert(ctx->in_io); quic_set_last_error(ctx, err); return 0; } /* * Raise a 'non-normal' error, meaning any error that is not reported via * SSL_get_error() and must be reported via ERR. * * qc should be provided if available. In exceptional circumstances when qc is * not known NULL may be passed. This should generally only happen when an * expect_...() function defined below fails, which generally indicates a * dispatch error or caller error. * * ctx should be NULL if the connection lock is not held. */ static int quic_raise_non_normal_error(QCTX *ctx, const char *file, int line, const char *func, int reason, const char *fmt, ...) { va_list args; if (ctx != NULL) { quic_set_last_error(ctx, SSL_ERROR_SSL); if (reason == SSL_R_PROTOCOL_IS_SHUTDOWN && ctx->qc != NULL) ossl_quic_channel_restore_err_state(ctx->qc->ch); } ERR_new(); ERR_set_debug(file, line, func); va_start(args, fmt); ERR_vset_error(ERR_LIB_SSL, reason, fmt, args); va_end(args); return 0; } #define QUIC_RAISE_NORMAL_ERROR(ctx, err) \ quic_raise_normal_error((ctx), (err)) #define QUIC_RAISE_NON_NORMAL_ERROR(ctx, reason, msg) \ quic_raise_non_normal_error((ctx), \ OPENSSL_FILE, OPENSSL_LINE, \ OPENSSL_FUNC, \ (reason), \ (msg)) /* * Flags for expect_quic_as: * * QCTX_C * The input SSL object may be a QCSO. * * QCTX_S * The input SSL object may be a QSSO or a QCSO with a default stream * attached. * * (Note this means there is no current way to require an SSL object with a * QUIC stream which is not a QCSO; a QCSO with a default stream attached * is always considered to satisfy QCTX_S.) * * QCTX_AUTO_S * The input SSL object may be a QSSO or a QCSO with a default stream * attached. If no default stream is currently attached to a QCSO, * one may be auto-created if possible. * * If QCTX_REMOTE_INIT is set, an auto-created default XSO is * initiated by the remote party (i.e., local party reads first). * * If it is not set, an auto-created default XSO is * initiated by the local party (i.e., local party writes first). * * QCTX_L * The input SSL object may be a QLSO. * * QCTX_LOCK * If and only if the function returns successfully, the ctx * is guaranteed to be locked. * * QCTX_IO * Begin an I/O context. If not set, begins a non-I/O context. * This determines whether SSL_get_error() is updated; the value it returns * is modified only by an I/O call. * * QCTX_NO_ERROR * Don't raise an error if the object type is wrong. Should not be used in * conjunction with any flags that may raise errors not related to a wrong * object type. */ #define QCTX_C (1U << 0) #define QCTX_S (1U << 1) #define QCTX_L (1U << 2) #define QCTX_AUTO_S (1U << 3) #define QCTX_REMOTE_INIT (1U << 4) #define QCTX_LOCK (1U << 5) #define QCTX_IO (1U << 6) #define QCTX_D (1U << 7) #define QCTX_NO_ERROR (1U << 8) /* * Called when expect_quic failed. Used to diagnose why such a call failed and * raise a reasonable error code based on the configured preconditions in flags. */ static int wrong_type(const SSL *s, uint32_t flags) { const uint32_t mask = QCTX_C | QCTX_S | QCTX_L | QCTX_D; int code = ERR_R_UNSUPPORTED; if ((flags & QCTX_NO_ERROR) != 0) return 1; else if ((flags & mask) == QCTX_D) code = SSL_R_DOMAIN_USE_ONLY; else if ((flags & mask) == QCTX_L) code = SSL_R_LISTENER_USE_ONLY; else if ((flags & mask) == QCTX_C) code = SSL_R_CONN_USE_ONLY; else if ((flags & mask) == QCTX_S || (flags & mask) == (QCTX_C | QCTX_S)) code = SSL_R_NO_STREAM; return QUIC_RAISE_NON_NORMAL_ERROR(NULL, code, NULL); } /* * Given a QDSO, QCSO, QSSO or QLSO, initialises a QCTX, determining the * contextually applicable QUIC_LISTENER, QUIC_CONNECTION and QUIC_XSO * pointers. * * After this returns 1, all fields of the passed QCTX are initialised. * Returns 0 on failure. This function is intended to be used to provide API * semantics and as such, it invokes QUIC_RAISE_NON_NORMAL_ERROR() on failure * unless the QCTX_NO_ERROR flag is set. * * The flags argument controls the preconditions and postconditions of this * function. See above for the different flags. * * The fields of a QCTX are initialised as follows depending on the identity of * the SSL object, and assuming the preconditions demanded by the flags field as * described above are met: * * QDSO QLSO QCSO QSSO * qd non-NULL maybe maybe maybe * ql NULL non-NULL maybe maybe * qc NULL NULL non-NULL non-NULL * xso NULL NULL maybe non-NULL * is_stream 0 0 0 1 * is_listener 0 1 0 0 * is_domain 1 0 0 0 * */ static int expect_quic_as(const SSL *s, QCTX *ctx, uint32_t flags) { int ok = 0, locked = 0, lock_requested = ((flags & QCTX_LOCK) != 0); QUIC_DOMAIN *qd; QUIC_LISTENER *ql; QUIC_CONNECTION *qc; QUIC_XSO *xso; if ((flags & QCTX_AUTO_S) != 0) flags |= QCTX_S; ctx->obj = NULL; ctx->qd = NULL; ctx->ql = NULL; ctx->qc = NULL; ctx->xso = NULL; ctx->is_stream = 0; ctx->is_listener = 0; ctx->is_domain = 0; ctx->in_io = ((flags & QCTX_IO) != 0); if (s == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_PASSED_NULL_PARAMETER, NULL); goto err; } switch (s->type) { case SSL_TYPE_QUIC_DOMAIN: if ((flags & QCTX_D) == 0) { wrong_type(s, flags); goto err; } qd = (QUIC_DOMAIN *)s; ctx->obj = &qd->obj; ctx->qd = qd; ctx->is_domain = 1; break; case SSL_TYPE_QUIC_LISTENER: if ((flags & QCTX_L) == 0) { wrong_type(s, flags); goto err; } ql = (QUIC_LISTENER *)s; ctx->obj = &ql->obj; ctx->qd = ql->domain; ctx->ql = ql; ctx->is_listener = 1; break; case SSL_TYPE_QUIC_CONNECTION: qc = (QUIC_CONNECTION *)s; ctx->obj = &qc->obj; ctx->qd = qc->domain; ctx->ql = qc->listener; /* never changes, so can be read without lock */ ctx->qc = qc; if ((flags & QCTX_AUTO_S) != 0) { if ((flags & QCTX_IO) != 0) qctx_lock_for_io(ctx); else qctx_lock(ctx); locked = 1; } if ((flags & QCTX_AUTO_S) != 0 && qc->default_xso == NULL) { if (!quic_mutation_allowed(qc, /*req_active=*/0)) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); goto err; } /* If we haven't finished the handshake, try to advance it. */ if (quic_do_handshake(ctx) < 1) /* ossl_quic_do_handshake raised error here */ goto err; if ((flags & QCTX_REMOTE_INIT) != 0) { if (!qc_wait_for_default_xso_for_read(ctx, /*peek=*/0)) goto err; } else { if (!qc_try_create_default_xso_for_write(ctx)) goto err; } } if ((flags & QCTX_C) == 0 && (qc->default_xso == NULL || (flags & QCTX_S) == 0)) { wrong_type(s, flags); goto err; } ctx->xso = qc->default_xso; break; case SSL_TYPE_QUIC_XSO: if ((flags & QCTX_S) == 0) { wrong_type(s, flags); goto err; } xso = (QUIC_XSO *)s; ctx->obj = &xso->obj; ctx->qd = xso->conn->domain; ctx->ql = xso->conn->listener; ctx->qc = xso->conn; ctx->xso = xso; ctx->is_stream = 1; break; default: QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL); goto err; } if (lock_requested && !locked) { if ((flags & QCTX_IO) != 0) qctx_lock_for_io(ctx); else qctx_lock(ctx); locked = 1; } ok = 1; err: if (locked && (!ok || !lock_requested)) qctx_unlock(ctx); return ok; } static int is_quic_c(const SSL *s, QCTX *ctx, int raiseerrs) { uint32_t flags = QCTX_C; if (!raiseerrs) flags |= QCTX_NO_ERROR; return expect_quic_as(s, ctx, flags); } /* Same as expect_quic_cs except that errors are not raised if raiseerrs == 0 */ static int is_quic_cs(const SSL *s, QCTX *ctx, int raiseerrs) { uint32_t flags = QCTX_C | QCTX_S; if (!raiseerrs) flags |= QCTX_NO_ERROR; return expect_quic_as(s, ctx, flags); } static int expect_quic_cs(const SSL *s, QCTX *ctx) { return expect_quic_as(s, ctx, QCTX_C | QCTX_S); } static int expect_quic_csl(const SSL *s, QCTX *ctx) { return expect_quic_as(s, ctx, QCTX_C | QCTX_S | QCTX_L); } static int expect_quic_csld(const SSL *s, QCTX *ctx) { return expect_quic_as(s, ctx, QCTX_C | QCTX_S | QCTX_L | QCTX_D); } #define expect_quic_any expect_quic_csld static int expect_quic_listener(const SSL *s, QCTX *ctx) { return expect_quic_as(s, ctx, QCTX_L); } static int expect_quic_domain(const SSL *s, QCTX *ctx) { return expect_quic_as(s, ctx, QCTX_D); } /* * Like expect_quic_cs(), but requires a QUIC_XSO be contextually available. In * other words, requires that the passed QSO be a QSSO or a QCSO with a default * stream. * * remote_init determines if we expect the default XSO to be remotely created or * not. If it is -1, do not instantiate a default XSO if one does not yet exist. * * Channel mutex is acquired and retained on success. */ QUIC_ACQUIRES_LOCK static int ossl_unused expect_quic_with_stream_lock(const SSL *s, int remote_init, int in_io, QCTX *ctx) { uint32_t flags = QCTX_S | QCTX_LOCK; if (remote_init >= 0) flags |= QCTX_AUTO_S; if (remote_init > 0) flags |= QCTX_REMOTE_INIT; if (in_io) flags |= QCTX_IO; return expect_quic_as(s, ctx, flags); } /* * Like expect_quic_cs(), but fails if called on a QUIC_XSO. ctx->xso may still * be non-NULL if the QCSO has a default stream. */ static int ossl_unused expect_quic_conn_only(const SSL *s, QCTX *ctx) { return expect_quic_as(s, ctx, QCTX_C); } /* * Ensures that the domain mutex is held for a method which touches channel * state. * * Precondition: Domain mutex is not held (unchecked) */ static void qctx_lock(QCTX *ctx) { #if defined(OPENSSL_THREADS) assert(ctx->obj != NULL); ossl_crypto_mutex_lock(ossl_quic_obj_get0_mutex(ctx->obj)); #endif } /* Precondition: Channel mutex is held (unchecked) */ QUIC_NEEDS_LOCK static void qctx_unlock(QCTX *ctx) { #if defined(OPENSSL_THREADS) assert(ctx->obj != NULL); ossl_crypto_mutex_unlock(ossl_quic_obj_get0_mutex(ctx->obj)); #endif } static void qctx_lock_for_io(QCTX *ctx) { qctx_lock(ctx); ctx->in_io = 1; /* * We are entering an I/O function so we must update the values returned by * SSL_get_error and SSL_want. Set no error. This will be overridden later * if a call to QUIC_RAISE_NORMAL_ERROR or QUIC_RAISE_NON_NORMAL_ERROR * occurs during the API call. */ quic_set_last_error(ctx, SSL_ERROR_NONE); } /* * This predicate is the criterion which should determine API call rejection for * *most* mutating API calls, particularly stream-related operations for send * parts. * * A call is rejected (this function returns 0) if shutdown is in progress * (stream flushing), or we are in a TERMINATING or TERMINATED state. If * req_active=1, the connection must be active (i.e., the IDLE state is also * rejected). */ static int quic_mutation_allowed(QUIC_CONNECTION *qc, int req_active) { if (qc->shutting_down || ossl_quic_channel_is_term_any(qc->ch)) return 0; if (req_active && !ossl_quic_channel_is_active(qc->ch)) return 0; return 1; } static int qctx_is_top_level(QCTX *ctx) { return ctx->obj->parent_obj == NULL; } static int qctx_blocking(QCTX *ctx) { return ossl_quic_obj_blocking(ctx->obj); } /* * Block until a predicate is met. * * Precondition: Must have a channel. * Precondition: Must hold channel lock (unchecked). */ QUIC_NEEDS_LOCK static int block_until_pred(QCTX *ctx, int (*pred)(void *arg), void *pred_arg, uint32_t flags) { QUIC_ENGINE *qeng; QUIC_REACTOR *rtor; qeng = ossl_quic_obj_get0_engine(ctx->obj); assert(qeng != NULL); /* * Any attempt to block auto-disables tick inhibition as otherwise we will * hang around forever. */ ossl_quic_engine_set_inhibit_tick(qeng, 0); rtor = ossl_quic_engine_get0_reactor(qeng); return ossl_quic_reactor_block_until_pred(rtor, pred, pred_arg, flags); } /* * QUIC Front-End I/O API: Initialization * ====================================== * * SSL_new => ossl_quic_new * ossl_quic_init * SSL_reset => ossl_quic_reset * SSL_clear => ossl_quic_clear * ossl_quic_deinit * SSL_free => ossl_quic_free * * SSL_set_options => ossl_quic_set_options * SSL_get_options => ossl_quic_get_options * SSL_clear_options => ossl_quic_clear_options * */ /* SSL_new */ SSL *ossl_quic_new(SSL_CTX *ctx) { QUIC_CONNECTION *qc = NULL; SSL_CONNECTION *sc = NULL; /* * QUIC_server_method should not be used with SSL_new. * It should only be used with SSL_new_listener. */ if (ctx->method == OSSL_QUIC_server_method()) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED, NULL); return NULL; } qc = OPENSSL_zalloc(sizeof(*qc)); if (qc == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_CRYPTO_LIB, NULL); return NULL; } /* Create the QUIC domain mutex. */ #if defined(OPENSSL_THREADS) if ((qc->mutex = ossl_crypto_mutex_new()) == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_CRYPTO_LIB, NULL); goto err; } #endif /* Create the handshake layer. */ qc->tls = ossl_ssl_connection_new_int(ctx, &qc->obj.ssl, TLS_method()); if (qc->tls == NULL || (sc = SSL_CONNECTION_FROM_SSL(qc->tls)) == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL); goto err; } /* override the user_ssl of the inner connection */ sc->s3.flags |= TLS1_FLAGS_QUIC | TLS1_FLAGS_QUIC_INTERNAL; /* Restrict options derived from the SSL_CTX. */ sc->options &= OSSL_QUIC_PERMITTED_OPTIONS_CONN; sc->pha_enabled = 0; /* Determine mode of operation. */ #if !defined(OPENSSL_NO_QUIC_THREAD_ASSIST) qc->is_thread_assisted = ((ctx->domain_flags & SSL_DOMAIN_FLAG_THREAD_ASSISTED) != 0); #endif qc->as_server = 0; qc->as_server_state = qc->as_server; if (!create_channel(qc, ctx)) goto err; ossl_quic_channel_set_msg_callback(qc->ch, ctx->msg_callback, &qc->obj.ssl); ossl_quic_channel_set_msg_callback_arg(qc->ch, ctx->msg_callback_arg); /* Initialise the QUIC_CONNECTION's QUIC_OBJ base. */ if (!ossl_quic_obj_init(&qc->obj, ctx, SSL_TYPE_QUIC_CONNECTION, NULL, qc->engine, qc->port)) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL); goto err; } /* Initialise libssl APL-related state. */ qc->default_stream_mode = SSL_DEFAULT_STREAM_MODE_AUTO_BIDI; qc->default_ssl_mode = qc->obj.ssl.ctx->mode; qc->default_ssl_options = qc->obj.ssl.ctx->options & OSSL_QUIC_PERMITTED_OPTIONS; qc->incoming_stream_policy = SSL_INCOMING_STREAM_POLICY_AUTO; qc->last_error = SSL_ERROR_NONE; qc_update_reject_policy(qc); /* * We do not create the default XSO yet. The reason for this is that the * stream ID of the default XSO will depend on whether the stream is client * or server-initiated, which depends on who transmits first. Since we do * not know whether the application will be using a client-transmits-first * or server-transmits-first protocol, we defer default XSO creation until * the client calls SSL_read() or SSL_write(). If it calls SSL_read() first, * we take that as a cue that the client is expecting a server-initiated * stream, and vice versa if SSL_write() is called first. */ return &qc->obj.ssl; err: if (qc != NULL) { qc_cleanup(qc, /*have_lock=*/0); OPENSSL_free(qc); } return NULL; } QUIC_NEEDS_LOCK static void quic_unref_port_bios(QUIC_PORT *port) { BIO *b; b = ossl_quic_port_get_net_rbio(port); BIO_free_all(b); b = ossl_quic_port_get_net_wbio(port); BIO_free_all(b); } QUIC_NEEDS_LOCK static void qc_cleanup(QUIC_CONNECTION *qc, int have_lock) { SSL_free(qc->tls); qc->tls = NULL; ossl_quic_channel_free(qc->ch); qc->ch = NULL; if (qc->port != NULL && qc->listener == NULL && qc->pending == 0) { /* TODO */ quic_unref_port_bios(qc->port); ossl_quic_port_free(qc->port); qc->port = NULL; ossl_quic_engine_free(qc->engine); qc->engine = NULL; } #if defined(OPENSSL_THREADS) if (have_lock) /* tsan doesn't like freeing locked mutexes */ ossl_crypto_mutex_unlock(qc->mutex); if (qc->listener == NULL && qc->pending == 0) ossl_crypto_mutex_free(&qc->mutex); #endif } /* SSL_free */ QUIC_TAKES_LOCK static void quic_free_listener(QCTX *ctx) { quic_unref_port_bios(ctx->ql->port); ossl_quic_port_drop_incoming(ctx->ql->port); ossl_quic_port_free(ctx->ql->port); if (ctx->ql->domain == NULL) { ossl_quic_engine_free(ctx->ql->engine); #if defined(OPENSSL_THREADS) ossl_crypto_mutex_free(&ctx->ql->mutex); #endif } else { SSL_free(&ctx->ql->domain->obj.ssl); } } /* SSL_free */ QUIC_TAKES_LOCK static void quic_free_domain(QCTX *ctx) { ossl_quic_engine_free(ctx->qd->engine); #if defined(OPENSSL_THREADS) ossl_crypto_mutex_free(&ctx->qd->mutex); #endif } QUIC_TAKES_LOCK void ossl_quic_free(SSL *s) { QCTX ctx; int is_default; /* We should never be called on anything but a QSO. */ if (!expect_quic_any(s, &ctx)) return; if (ctx.is_domain) { quic_free_domain(&ctx); return; } if (ctx.is_listener) { quic_free_listener(&ctx); return; } qctx_lock(&ctx); if (ctx.is_stream) { /* * When a QSSO is freed, the XSO is freed immediately, because the XSO * itself only contains API personality layer data. However the * underlying QUIC_STREAM is not freed immediately but is instead marked * as deleted for later collection. */ assert(ctx.qc->num_xso > 0); --ctx.qc->num_xso; /* If a stream's send part has not been finished, auto-reset it. */ if (( ctx.xso->stream->send_state == QUIC_SSTREAM_STATE_READY || ctx.xso->stream->send_state == QUIC_SSTREAM_STATE_SEND) && !ossl_quic_sstream_get_final_size(ctx.xso->stream->sstream, NULL)) ossl_quic_stream_map_reset_stream_send_part(ossl_quic_channel_get_qsm(ctx.qc->ch), ctx.xso->stream, 0); /* Do STOP_SENDING for the receive part, if applicable. */ if ( ctx.xso->stream->recv_state == QUIC_RSTREAM_STATE_RECV || ctx.xso->stream->recv_state == QUIC_RSTREAM_STATE_SIZE_KNOWN) ossl_quic_stream_map_stop_sending_recv_part(ossl_quic_channel_get_qsm(ctx.qc->ch), ctx.xso->stream, 0); /* Update stream state. */ ctx.xso->stream->deleted = 1; ossl_quic_stream_map_update_state(ossl_quic_channel_get_qsm(ctx.qc->ch), ctx.xso->stream); is_default = (ctx.xso == ctx.qc->default_xso); qctx_unlock(&ctx); /* * Unref the connection in most cases; the XSO has a ref to the QC and * not vice versa. But for a default XSO, to avoid circular references, * the QC refs the XSO but the XSO does not ref the QC. If we are the * default XSO, we only get here when the QC is being torn down anyway, * so don't call SSL_free(qc) as we are already in it. */ if (!is_default) SSL_free(&ctx.qc->obj.ssl); /* Note: SSL_free calls OPENSSL_free(xso) for us */ return; } /* * Free the default XSO, if any. The QUIC_STREAM is not deleted at this * stage, but is freed during the channel free when the whole QSM is freed. */ if (ctx.qc->default_xso != NULL) { QUIC_XSO *xso = ctx.qc->default_xso; qctx_unlock(&ctx); SSL_free(&xso->obj.ssl); qctx_lock(&ctx); ctx.qc->default_xso = NULL; } /* Ensure we have no remaining XSOs. */ assert(ctx.qc->num_xso == 0); #if !defined(OPENSSL_NO_QUIC_THREAD_ASSIST) if (ctx.qc->is_thread_assisted && ctx.qc->started) { ossl_quic_thread_assist_wait_stopped(&ctx.qc->thread_assist); ossl_quic_thread_assist_cleanup(&ctx.qc->thread_assist); } #endif /* * Note: SSL_free (that called this function) calls OPENSSL_free(ctx.qc) for * us */ qc_cleanup(ctx.qc, /*have_lock=*/1); /* Note: SSL_free calls OPENSSL_free(qc) for us */ if (ctx.qc->listener != NULL) SSL_free(&ctx.qc->listener->obj.ssl); if (ctx.qc->domain != NULL) SSL_free(&ctx.qc->domain->obj.ssl); } /* SSL method init */ int ossl_quic_init(SSL *s) { /* Same op as SSL_clear, forward the call. */ return ossl_quic_clear(s); } /* SSL method deinit */ void ossl_quic_deinit(SSL *s) { /* No-op. */ } /* SSL_clear (ssl_reset method) */ int ossl_quic_reset(SSL *s) { QCTX ctx; if (!expect_quic_any(s, &ctx)) return 0; ERR_raise(ERR_LIB_SSL, ERR_R_UNSUPPORTED); return 0; } /* ssl_clear method (unused) */ int ossl_quic_clear(SSL *s) { QCTX ctx; if (!expect_quic_any(s, &ctx)) return 0; ERR_raise(ERR_LIB_SSL, ERR_R_UNSUPPORTED); return 0; } int ossl_quic_set_override_now_cb(SSL *s, OSSL_TIME (*now_cb)(void *arg), void *now_cb_arg) { QCTX ctx; if (!expect_quic_any(s, &ctx)) return 0; qctx_lock(&ctx); ossl_quic_engine_set_time_cb(ctx.obj->engine, now_cb, now_cb_arg); qctx_unlock(&ctx); return 1; } void ossl_quic_conn_force_assist_thread_wake(SSL *s) { QCTX ctx; if (!expect_quic_conn_only(s, &ctx)) return; #if !defined(OPENSSL_NO_QUIC_THREAD_ASSIST) if (ctx.qc->is_thread_assisted && ctx.qc->started) ossl_quic_thread_assist_notify_deadline_changed(&ctx.qc->thread_assist); #endif } QUIC_NEEDS_LOCK static void qc_touch_default_xso(QUIC_CONNECTION *qc) { qc->default_xso_created = 1; qc_update_reject_policy(qc); } /* * Changes default XSO. Allows caller to keep reference to the old default XSO * (if any). Reference to new XSO is transferred from caller. */ QUIC_NEEDS_LOCK static void qc_set_default_xso_keep_ref(QUIC_CONNECTION *qc, QUIC_XSO *xso, int touch, QUIC_XSO **old_xso) { int refs; *old_xso = NULL; if (qc->default_xso != xso) { *old_xso = qc->default_xso; /* transfer old XSO ref to caller */ qc->default_xso = xso; if (xso == NULL) { /* * Changing to not having a default XSO. XSO becomes standalone and * now has a ref to the QC. */ if (!ossl_assert(SSL_up_ref(&qc->obj.ssl))) return; } else { /* * Changing from not having a default XSO to having one. The new XSO * will have had a reference to the QC we need to drop to avoid a * circular reference. * * Currently we never change directly from one default XSO to * another, though this function would also still be correct if this * weren't the case. */ assert(*old_xso == NULL); CRYPTO_DOWN_REF(&qc->obj.ssl.references, &refs); assert(refs > 0); } } if (touch) qc_touch_default_xso(qc); } /* * Changes default XSO, releasing the reference to any previous default XSO. * Reference to new XSO is transferred from caller. */ QUIC_NEEDS_LOCK static void qc_set_default_xso(QUIC_CONNECTION *qc, QUIC_XSO *xso, int touch) { QUIC_XSO *old_xso = NULL; qc_set_default_xso_keep_ref(qc, xso, touch, &old_xso); if (old_xso != NULL) SSL_free(&old_xso->obj.ssl); } QUIC_NEEDS_LOCK static void xso_update_options(QUIC_XSO *xso) { int cleanse = ((xso->ssl_options & SSL_OP_CLEANSE_PLAINTEXT) != 0); if (xso->stream->rstream != NULL) ossl_quic_rstream_set_cleanse(xso->stream->rstream, cleanse); if (xso->stream->sstream != NULL) ossl_quic_sstream_set_cleanse(xso->stream->sstream, cleanse); } /* * SSL_set_options * --------------- * * Setting options on a QCSO * - configures the handshake-layer options; * - configures the default data-plane options for new streams; * - configures the data-plane options on the default XSO, if there is one. * * Setting options on a QSSO * - configures data-plane options for that stream only. */ QUIC_TAKES_LOCK static uint64_t quic_mask_or_options(SSL *ssl, uint64_t mask_value, uint64_t or_value) { QCTX ctx; uint64_t hs_mask_value, hs_or_value, ret; if (!expect_quic_cs(ssl, &ctx)) return 0; qctx_lock(&ctx); if (!ctx.is_stream) { /* * If we were called on the connection, we apply any handshake option * changes. */ hs_mask_value = (mask_value & OSSL_QUIC_PERMITTED_OPTIONS_CONN); hs_or_value = (or_value & OSSL_QUIC_PERMITTED_OPTIONS_CONN); SSL_clear_options(ctx.qc->tls, hs_mask_value); SSL_set_options(ctx.qc->tls, hs_or_value); /* Update defaults for new streams. */ ctx.qc->default_ssl_options = ((ctx.qc->default_ssl_options & ~mask_value) | or_value) & OSSL_QUIC_PERMITTED_OPTIONS; } ret = ctx.qc->default_ssl_options; if (ctx.xso != NULL) { ctx.xso->ssl_options = ((ctx.xso->ssl_options & ~mask_value) | or_value) & OSSL_QUIC_PERMITTED_OPTIONS_STREAM; xso_update_options(ctx.xso); if (ctx.is_stream) ret = ctx.xso->ssl_options; } qctx_unlock(&ctx); return ret; } uint64_t ossl_quic_set_options(SSL *ssl, uint64_t options) { return quic_mask_or_options(ssl, 0, options); } /* SSL_clear_options */ uint64_t ossl_quic_clear_options(SSL *ssl, uint64_t options) { return quic_mask_or_options(ssl, options, 0); } /* SSL_get_options */ uint64_t ossl_quic_get_options(const SSL *ssl) { return quic_mask_or_options((SSL *)ssl, 0, 0); } /* * QUIC Front-End I/O API: Network BIO Configuration * ================================================= * * Handling the different BIOs is difficult: * * - It is more or less a requirement that we use non-blocking network I/O; * we need to be able to have timeouts on recv() calls, and make best effort * (non blocking) send() and recv() calls. * * The only sensible way to do this is to configure the socket into * non-blocking mode. We could try to do select() before calling send() or * recv() to get a guarantee that the call will not block, but this will * probably run into issues with buggy OSes which generate spurious socket * readiness events. In any case, relying on this to work reliably does not * seem sane. * * Timeouts could be handled via setsockopt() socket timeout options, but * this depends on OS support and adds another syscall to every network I/O * operation. It also has obvious thread safety concerns if we want to move * to concurrent use of a single socket at some later date. * * Some OSes support a MSG_DONTWAIT flag which allows a single I/O option to * be made non-blocking. However some OSes (e.g. Windows) do not support * this, so we cannot rely on this. * * As such, we need to configure any FD in non-blocking mode. This may * confound users who pass a blocking socket to libssl. However, in practice * it would be extremely strange for a user of QUIC to pass an FD to us, * then also try and send receive traffic on the same socket(!). Thus the * impact of this should be limited, and can be documented. * * - We support both blocking and non-blocking operation in terms of the API * presented to the user. One prospect is to set the blocking mode based on * whether the socket passed to us was already in blocking mode. However, * Windows has no API for determining if a socket is in blocking mode (!), * therefore this cannot be done portably. Currently therefore we expose an * explicit API call to set this, and default to blocking mode. * * - We need to determine our initial destination UDP address. The "natural" * way for a user to do this is to set the peer variable on a BIO_dgram. * However, this has problems because BIO_dgram's peer variable is used for * both transmission and reception. This means it can be constantly being * changed to a malicious value (e.g. if some random unrelated entity on the * network starts sending traffic to us) on every read call. This is not a * direct issue because we use the 'stateless' BIO_sendmmsg and BIO_recvmmsg * calls only, which do not use this variable. However, we do need to let * the user specify the peer in a 'normal' manner. The compromise here is * that we grab the current peer value set at the time the write BIO is set * and do not read the value again. * * - We also need to support memory BIOs (e.g. BIO_dgram_pair) or custom BIOs. * Currently we do this by only supporting non-blocking mode. * */ /* * Determines what initial destination UDP address we should use, if possible. * If this fails the client must set the destination address manually, or use a * BIO which does not need a destination address. */ static int csm_analyse_init_peer_addr(BIO *net_wbio, BIO_ADDR *peer) { if (BIO_dgram_detect_peer_addr(net_wbio, peer) <= 0) return 0; return 1; } static int quic_set0_net_rbio(QUIC_OBJ *obj, BIO *net_rbio) { QUIC_PORT *port; BIO *old_rbio = NULL; port = ossl_quic_obj_get0_port(obj); old_rbio = ossl_quic_port_get_net_rbio(port); if (old_rbio == net_rbio) return 0; if (!ossl_quic_port_set_net_rbio(port, net_rbio)) return 0; BIO_free_all(old_rbio); if (net_rbio != NULL) BIO_set_nbio(net_rbio, 1); /* best effort autoconfig */ return 1; } static int quic_set0_net_wbio(QUIC_OBJ *obj, BIO *net_wbio) { QUIC_PORT *port; BIO *old_wbio = NULL; port = ossl_quic_obj_get0_port(obj); old_wbio = ossl_quic_port_get_net_wbio(port); if (old_wbio == net_wbio) return 0; if (!ossl_quic_port_set_net_wbio(port, net_wbio)) return 0; BIO_free_all(old_wbio); if (net_wbio != NULL) BIO_set_nbio(net_wbio, 1); /* best effort autoconfig */ return 1; } void ossl_quic_conn_set0_net_rbio(SSL *s, BIO *net_rbio) { QCTX ctx; if (!expect_quic_csl(s, &ctx)) return; /* Returns 0 if no change. */ if (!quic_set0_net_rbio(ctx.obj, net_rbio)) return; } void ossl_quic_conn_set0_net_wbio(SSL *s, BIO *net_wbio) { QCTX ctx; if (!expect_quic_csl(s, &ctx)) return; /* Returns 0 if no change. */ if (!quic_set0_net_wbio(ctx.obj, net_wbio)) return; } BIO *ossl_quic_conn_get_net_rbio(const SSL *s) { QCTX ctx; QUIC_PORT *port; if (!expect_quic_csl(s, &ctx)) return NULL; port = ossl_quic_obj_get0_port(ctx.obj); assert(port != NULL); return ossl_quic_port_get_net_rbio(port); } BIO *ossl_quic_conn_get_net_wbio(const SSL *s) { QCTX ctx; QUIC_PORT *port; if (!expect_quic_csl(s, &ctx)) return NULL; port = ossl_quic_obj_get0_port(ctx.obj); assert(port != NULL); return ossl_quic_port_get_net_wbio(port); } int ossl_quic_conn_get_blocking_mode(const SSL *s) { QCTX ctx; if (!expect_quic_csl(s, &ctx)) return 0; return qctx_blocking(&ctx); } QUIC_TAKES_LOCK int ossl_quic_conn_set_blocking_mode(SSL *s, int blocking) { int ret = 0; unsigned int mode; QCTX ctx; if (!expect_quic_csl(s, &ctx)) return 0; qctx_lock(&ctx); /* Sanity check - can we support the request given the current network BIO? */ if (blocking) { /* * If called directly on a top-level object (QCSO or QLSO), update our * information on network BIO capabilities. */ if (qctx_is_top_level(&ctx)) ossl_quic_engine_update_poll_descriptors(ctx.obj->engine, /*force=*/1); /* Cannot enable blocking mode if we do not have pollable FDs. */ if (!ossl_quic_obj_can_support_blocking(ctx.obj)) { ret = QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_UNSUPPORTED, NULL); goto out; } } mode = (blocking != 0) ? QUIC_BLOCKING_MODE_BLOCKING : QUIC_BLOCKING_MODE_NONBLOCKING; ossl_quic_obj_set_blocking_mode(ctx.obj, mode); ret = 1; out: qctx_unlock(&ctx); return ret; } int ossl_quic_conn_set_initial_peer_addr(SSL *s, const BIO_ADDR *peer_addr) { QCTX ctx; if (!expect_quic_cs(s, &ctx)) return 0; if (ctx.qc->started) return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED, NULL); if (peer_addr == NULL) { BIO_ADDR_clear(&ctx.qc->init_peer_addr); return 1; } return BIO_ADDR_copy(&ctx.qc->init_peer_addr, peer_addr); } /* * QUIC Front-End I/O API: Asynchronous I/O Management * =================================================== * * (BIO/)SSL_handle_events => ossl_quic_handle_events * (BIO/)SSL_get_event_timeout => ossl_quic_get_event_timeout * (BIO/)SSL_get_poll_fd => ossl_quic_get_poll_fd * */ /* SSL_handle_events; performs QUIC I/O and timeout processing. */ QUIC_TAKES_LOCK int ossl_quic_handle_events(SSL *s) { QCTX ctx; if (!expect_quic_any(s, &ctx)) return 0; qctx_lock(&ctx); ossl_quic_reactor_tick(ossl_quic_obj_get0_reactor(ctx.obj), 0); qctx_unlock(&ctx); return 1; } /* * SSL_get_event_timeout. Get the time in milliseconds until the SSL object * should next have events handled by the application by calling * SSL_handle_events(). tv is set to 0 if the object should have events handled * immediately. If no timeout is currently active, *is_infinite is set to 1 and * the value of *tv is undefined. */ QUIC_TAKES_LOCK int ossl_quic_get_event_timeout(SSL *s, struct timeval *tv, int *is_infinite) { QCTX ctx; QUIC_REACTOR *reactor; OSSL_TIME deadline; OSSL_TIME basetime; if (!expect_quic_any(s, &ctx)) return 0; qctx_lock(&ctx); reactor = ossl_quic_obj_get0_reactor(ctx.obj); deadline = ossl_quic_reactor_get_tick_deadline(reactor); if (ossl_time_is_infinite(deadline)) { qctx_unlock(&ctx); *is_infinite = 1; /* * Robustness against faulty applications that don't check *is_infinite; * harmless long timeout. */ tv->tv_sec = 1000000; tv->tv_usec = 0; return 1; } basetime = ossl_quic_engine_get_time(ctx.obj->engine); qctx_unlock(&ctx); *tv = ossl_time_to_timeval(ossl_time_subtract(deadline, basetime)); *is_infinite = 0; return 1; } /* SSL_get_rpoll_descriptor */ int ossl_quic_get_rpoll_descriptor(SSL *s, BIO_POLL_DESCRIPTOR *desc) { QCTX ctx; QUIC_PORT *port = NULL; BIO *net_rbio; if (!expect_quic_csl(s, &ctx)) return 0; port = ossl_quic_obj_get0_port(ctx.obj); net_rbio = ossl_quic_port_get_net_rbio(port); if (desc == NULL || net_rbio == NULL) return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_PASSED_INVALID_ARGUMENT, NULL); return BIO_get_rpoll_descriptor(net_rbio, desc); } /* SSL_get_wpoll_descriptor */ int ossl_quic_get_wpoll_descriptor(SSL *s, BIO_POLL_DESCRIPTOR *desc) { QCTX ctx; QUIC_PORT *port = NULL; BIO *net_wbio; if (!expect_quic_csl(s, &ctx)) return 0; port = ossl_quic_obj_get0_port(ctx.obj); net_wbio = ossl_quic_port_get_net_wbio(port); if (desc == NULL || net_wbio == NULL) return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_PASSED_INVALID_ARGUMENT, NULL); return BIO_get_wpoll_descriptor(net_wbio, desc); } /* SSL_net_read_desired */ QUIC_TAKES_LOCK int ossl_quic_get_net_read_desired(SSL *s) { QCTX ctx; int ret; if (!expect_quic_csl(s, &ctx)) return 0; qctx_lock(&ctx); ret = ossl_quic_reactor_net_read_desired(ossl_quic_obj_get0_reactor(ctx.obj)); qctx_unlock(&ctx); return ret; } /* SSL_net_write_desired */ QUIC_TAKES_LOCK int ossl_quic_get_net_write_desired(SSL *s) { int ret; QCTX ctx; if (!expect_quic_csl(s, &ctx)) return 0; qctx_lock(&ctx); ret = ossl_quic_reactor_net_write_desired(ossl_quic_obj_get0_reactor(ctx.obj)); qctx_unlock(&ctx); return ret; } /* * QUIC Front-End I/O API: Connection Lifecycle Operations * ======================================================= * * SSL_do_handshake => ossl_quic_do_handshake * SSL_set_connect_state => ossl_quic_set_connect_state * SSL_set_accept_state => ossl_quic_set_accept_state * SSL_shutdown => ossl_quic_shutdown * SSL_ctrl => ossl_quic_ctrl * (BIO/)SSL_connect => ossl_quic_connect * (BIO/)SSL_accept => ossl_quic_accept * */ QUIC_NEEDS_LOCK static void qc_shutdown_flush_init(QUIC_CONNECTION *qc) { QUIC_STREAM_MAP *qsm; if (qc->shutting_down) return; qsm = ossl_quic_channel_get_qsm(qc->ch); ossl_quic_stream_map_begin_shutdown_flush(qsm); qc->shutting_down = 1; } /* Returns 1 if all shutdown-flush streams have been done with. */ QUIC_NEEDS_LOCK static int qc_shutdown_flush_finished(QUIC_CONNECTION *qc) { QUIC_STREAM_MAP *qsm = ossl_quic_channel_get_qsm(qc->ch); return qc->shutting_down && ossl_quic_stream_map_is_shutdown_flush_finished(qsm); } /* SSL_shutdown */ static int quic_shutdown_wait(void *arg) { QUIC_CONNECTION *qc = arg; return ossl_quic_channel_is_terminated(qc->ch); } /* Returns 1 if shutdown flush process has finished or is inapplicable. */ static int quic_shutdown_flush_wait(void *arg) { QUIC_CONNECTION *qc = arg; return ossl_quic_channel_is_term_any(qc->ch) || qc_shutdown_flush_finished(qc); } static int quic_shutdown_peer_wait(void *arg) { QUIC_CONNECTION *qc = arg; return ossl_quic_channel_is_term_any(qc->ch); } QUIC_TAKES_LOCK int ossl_quic_conn_shutdown(SSL *s, uint64_t flags, const SSL_SHUTDOWN_EX_ARGS *args, size_t args_len) { int ret; QCTX ctx; int stream_flush = ((flags & SSL_SHUTDOWN_FLAG_NO_STREAM_FLUSH) == 0); int no_block = ((flags & SSL_SHUTDOWN_FLAG_NO_BLOCK) != 0); int wait_peer = ((flags & SSL_SHUTDOWN_FLAG_WAIT_PEER) != 0); if (!expect_quic_cs(s, &ctx)) return -1; if (ctx.is_stream) { QUIC_RAISE_NON_NORMAL_ERROR(&ctx, SSL_R_CONN_USE_ONLY, NULL); return -1; } qctx_lock(&ctx); if (ossl_quic_channel_is_terminated(ctx.qc->ch)) { qctx_unlock(&ctx); return 1; } /* Phase 1: Stream Flushing */ if (!wait_peer && stream_flush) { qc_shutdown_flush_init(ctx.qc); if (!qc_shutdown_flush_finished(ctx.qc)) { if (!no_block && qctx_blocking(&ctx)) { ret = block_until_pred(&ctx, quic_shutdown_flush_wait, ctx.qc, 0); if (ret < 1) { ret = 0; goto err; } } else { qctx_maybe_autotick(&ctx); } } if (!qc_shutdown_flush_finished(ctx.qc)) { qctx_unlock(&ctx); return 0; /* ongoing */ } } /* Phase 2: Connection Closure */ if (wait_peer && !ossl_quic_channel_is_term_any(ctx.qc->ch)) { if (!no_block && qctx_blocking(&ctx)) { ret = block_until_pred(&ctx, quic_shutdown_peer_wait, ctx.qc, 0); if (ret < 1) { ret = 0; goto err; } } else { qctx_maybe_autotick(&ctx); } if (!ossl_quic_channel_is_term_any(ctx.qc->ch)) { ret = 0; /* peer hasn't closed yet - still not done */ goto err; } /* * We are at least terminating - go through the normal process of * waiting until we are in the TERMINATED state. */ } /* Block mutation ops regardless of if we did stream flush. */ ctx.qc->shutting_down = 1; /* * This call is a no-op if we are already terminating, so it doesn't * affect the wait_peer case. */ ossl_quic_channel_local_close(ctx.qc->ch, args != NULL ? args->quic_error_code : 0, args != NULL ? args->quic_reason : NULL); SSL_set_shutdown(ctx.qc->tls, SSL_SENT_SHUTDOWN); if (ossl_quic_channel_is_terminated(ctx.qc->ch)) { qctx_unlock(&ctx); return 1; } /* Phase 3: Terminating Wait Time */ if (!no_block && qctx_blocking(&ctx) && (flags & SSL_SHUTDOWN_FLAG_RAPID) == 0) { ret = block_until_pred(&ctx, quic_shutdown_wait, ctx.qc, 0); if (ret < 1) { ret = 0; goto err; } } else { qctx_maybe_autotick(&ctx); } ret = ossl_quic_channel_is_terminated(ctx.qc->ch); err: qctx_unlock(&ctx); return ret; } /* SSL_ctrl */ long ossl_quic_ctrl(SSL *s, int cmd, long larg, void *parg) { QCTX ctx; if (!expect_quic_csl(s, &ctx)) return 0; switch (cmd) { case SSL_CTRL_MODE: if (ctx.is_listener) return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_UNSUPPORTED, NULL); /* If called on a QCSO, update the default mode. */ if (!ctx.is_stream) ctx.qc->default_ssl_mode |= (uint32_t)larg; /* * If we were called on a QSSO or have a default stream, we also update * that. */ if (ctx.xso != NULL) { /* Cannot enable EPW while AON write in progress. */ if (ctx.xso->aon_write_in_progress) larg &= ~SSL_MODE_ENABLE_PARTIAL_WRITE; ctx.xso->ssl_mode |= (uint32_t)larg; return ctx.xso->ssl_mode; } return ctx.qc->default_ssl_mode; case SSL_CTRL_CLEAR_MODE: if (ctx.is_listener) return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_UNSUPPORTED, NULL); if (!ctx.is_stream) ctx.qc->default_ssl_mode &= ~(uint32_t)larg; if (ctx.xso != NULL) { ctx.xso->ssl_mode &= ~(uint32_t)larg; return ctx.xso->ssl_mode; } return ctx.qc->default_ssl_mode; case SSL_CTRL_SET_MSG_CALLBACK_ARG: if (ctx.is_listener) return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_UNSUPPORTED, NULL); ossl_quic_channel_set_msg_callback_arg(ctx.qc->ch, parg); /* This ctrl also needs to be passed to the internal SSL object */ return SSL_ctrl(ctx.qc->tls, cmd, larg, parg); case DTLS_CTRL_GET_TIMEOUT: /* DTLSv1_get_timeout */ { int is_infinite; if (!ossl_quic_get_event_timeout(s, parg, &is_infinite)) return 0; return !is_infinite; } case DTLS_CTRL_HANDLE_TIMEOUT: /* DTLSv1_handle_timeout */ /* For legacy compatibility with DTLS calls. */ return ossl_quic_handle_events(s) == 1 ? 1 : -1; /* Mask ctrls we shouldn't support for QUIC. */ case SSL_CTRL_GET_READ_AHEAD: case SSL_CTRL_SET_READ_AHEAD: case SSL_CTRL_SET_MAX_SEND_FRAGMENT: case SSL_CTRL_SET_SPLIT_SEND_FRAGMENT: case SSL_CTRL_SET_MAX_PIPELINES: return 0; default: /* * Probably a TLS related ctrl. Send back to the frontend SSL_ctrl * implementation. Either SSL_ctrl will handle it itself by direct * access into handshake layer state, or failing that, it will be passed * to the handshake layer via the SSL_METHOD vtable. If the ctrl is not * supported by anything, the handshake layer's ctrl method will finally * return 0. */ if (ctx.is_listener) return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_UNSUPPORTED, NULL); return ossl_ctrl_internal(&ctx.qc->obj.ssl, cmd, larg, parg, /*no_quic=*/1); } } /* SSL_set_connect_state */ int ossl_quic_set_connect_state(SSL *s, int raiseerrs) { QCTX ctx; if (!is_quic_c(s, &ctx, raiseerrs)) return 0; if (ctx.qc->as_server_state == 0) return 1; /* Cannot be changed after handshake started */ if (ctx.qc->started) { if (raiseerrs) QUIC_RAISE_NON_NORMAL_ERROR(NULL, SSL_R_INVALID_COMMAND, NULL); return 0; } ctx.qc->as_server_state = 0; return 1; } /* SSL_set_accept_state */ int ossl_quic_set_accept_state(SSL *s, int raiseerrs) { QCTX ctx; if (!is_quic_c(s, &ctx, raiseerrs)) return 0; if (ctx.qc->as_server_state == 1) return 1; /* Cannot be changed after handshake started */ if (ctx.qc->started) { if (raiseerrs) QUIC_RAISE_NON_NORMAL_ERROR(NULL, SSL_R_INVALID_COMMAND, NULL); return 0; } ctx.qc->as_server_state = 1; return 1; } /* SSL_do_handshake */ struct quic_handshake_wait_args { QUIC_CONNECTION *qc; }; static int tls_wants_non_io_retry(QUIC_CONNECTION *qc) { int want = SSL_want(qc->tls); if (want == SSL_X509_LOOKUP || want == SSL_CLIENT_HELLO_CB || want == SSL_RETRY_VERIFY) return 1; return 0; } static int quic_handshake_wait(void *arg) { struct quic_handshake_wait_args *args = arg; if (!quic_mutation_allowed(args->qc, /*req_active=*/1)) return -1; if (ossl_quic_channel_is_handshake_complete(args->qc->ch)) return 1; if (tls_wants_non_io_retry(args->qc)) return 1; return 0; } static int configure_channel(QUIC_CONNECTION *qc) { assert(qc->ch != NULL); if (!ossl_quic_channel_set_peer_addr(qc->ch, &qc->init_peer_addr)) return 0; return 1; } static int need_notifier_for_domain_flags(uint64_t domain_flags) { return (domain_flags & SSL_DOMAIN_FLAG_THREAD_ASSISTED) != 0 || ((domain_flags & SSL_DOMAIN_FLAG_MULTI_THREAD) != 0 && (domain_flags & SSL_DOMAIN_FLAG_BLOCKING) != 0); } QUIC_NEEDS_LOCK static int create_channel(QUIC_CONNECTION *qc, SSL_CTX *ctx) { QUIC_ENGINE_ARGS engine_args = {0}; QUIC_PORT_ARGS port_args = {0}; engine_args.libctx = ctx->libctx; engine_args.propq = ctx->propq; #if defined(OPENSSL_THREADS) engine_args.mutex = qc->mutex; #endif if (need_notifier_for_domain_flags(ctx->domain_flags)) engine_args.reactor_flags |= QUIC_REACTOR_FLAG_USE_NOTIFIER; qc->engine = ossl_quic_engine_new(&engine_args); if (qc->engine == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL); return 0; } port_args.channel_ctx = ctx; qc->port = ossl_quic_engine_create_port(qc->engine, &port_args); if (qc->port == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL); ossl_quic_engine_free(qc->engine); return 0; } qc->ch = ossl_quic_port_create_outgoing(qc->port, qc->tls); if (qc->ch == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL); ossl_quic_port_free(qc->port); ossl_quic_engine_free(qc->engine); return 0; } return 1; } /* * Configures a channel with the information we have accumulated via calls made * to us from the application prior to starting a handshake attempt. */ QUIC_NEEDS_LOCK static int ensure_channel_started(QCTX *ctx) { QUIC_CONNECTION *qc = ctx->qc; if (!qc->started) { if (!configure_channel(qc)) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, "failed to configure channel"); return 0; } if (!ossl_quic_channel_start(qc->ch)) { ossl_quic_channel_restore_err_state(qc->ch); QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, "failed to start channel"); return 0; } #if !defined(OPENSSL_NO_QUIC_THREAD_ASSIST) if (qc->is_thread_assisted) if (!ossl_quic_thread_assist_init_start(&qc->thread_assist, qc->ch)) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, "failed to start assist thread"); return 0; } #endif } qc->started = 1; return 1; } QUIC_NEEDS_LOCK static int quic_do_handshake(QCTX *ctx) { int ret; QUIC_CONNECTION *qc = ctx->qc; QUIC_PORT *port; BIO *net_rbio, *net_wbio; if (ossl_quic_channel_is_handshake_complete(qc->ch)) /* Handshake already completed. */ return 1; if (!quic_mutation_allowed(qc, /*req_active=*/0)) return QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); if (qc->as_server != qc->as_server_state) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_PASSED_INVALID_ARGUMENT, NULL); return -1; /* Non-protocol error */ } port = ossl_quic_obj_get0_port(ctx->obj); net_rbio = ossl_quic_port_get_net_rbio(port); net_wbio = ossl_quic_port_get_net_wbio(port); if (net_rbio == NULL || net_wbio == NULL) { /* Need read and write BIOs. */ QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_BIO_NOT_SET, NULL); return -1; /* Non-protocol error */ } if (!qc->started && ossl_quic_port_is_addressed_w(port) && BIO_ADDR_family(&qc->init_peer_addr) == AF_UNSPEC) { /* * We are trying to connect and are using addressed mode, which means we * need an initial peer address; if we do not have a peer address yet, * we should try to autodetect one. * * We do this as late as possible because some BIOs (e.g. BIO_s_connect) * may not be able to provide us with a peer address until they have * finished their own processing. They may not be able to perform this * processing until an application has finished configuring that BIO * (e.g. with setter calls), which might happen after SSL_set_bio is * called. */ if (!csm_analyse_init_peer_addr(net_wbio, &qc->init_peer_addr)) /* best effort */ BIO_ADDR_clear(&qc->init_peer_addr); else ossl_quic_channel_set_peer_addr(qc->ch, &qc->init_peer_addr); } if (!qc->started && ossl_quic_port_is_addressed_w(port) && BIO_ADDR_family(&qc->init_peer_addr) == AF_UNSPEC) { /* * If we still don't have a peer address in addressed mode, we can't do * anything. */ QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_REMOTE_PEER_ADDRESS_NOT_SET, NULL); return -1; /* Non-protocol error */ } /* * Start connection process. Note we may come here multiple times in * non-blocking mode, which is fine. */ if (!ensure_channel_started(ctx)) /* raises on failure */ return -1; /* Non-protocol error */ if (ossl_quic_channel_is_handshake_complete(qc->ch)) /* The handshake is now done. */ return 1; if (!qctx_blocking(ctx)) { /* Try to advance the reactor. */ qctx_maybe_autotick(ctx); if (ossl_quic_channel_is_handshake_complete(qc->ch)) /* The handshake is now done. */ return 1; if (ossl_quic_channel_is_term_any(qc->ch)) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); return 0; } else if (ossl_quic_obj_desires_blocking(&qc->obj)) { /* * As a special case when doing a handshake when blocking mode is * desired yet not available, see if the network BIOs have become * poll descriptor-enabled. This supports BIOs such as BIO_s_connect * which do late creation of socket FDs and therefore cannot expose * a poll descriptor until after a network BIO is set on the QCSO. */ ossl_quic_engine_update_poll_descriptors(qc->obj.engine, /*force=*/1); } } /* * We are either in blocking mode or just entered it due to the code above. */ if (qctx_blocking(ctx)) { /* In blocking mode, wait for the handshake to complete. */ struct quic_handshake_wait_args args; args.qc = qc; ret = block_until_pred(ctx, quic_handshake_wait, &args, 0); if (!quic_mutation_allowed(qc, /*req_active=*/1)) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); return 0; /* Shutdown before completion */ } else if (ret <= 0) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); return -1; /* Non-protocol error */ } if (tls_wants_non_io_retry(qc)) { QUIC_RAISE_NORMAL_ERROR(ctx, SSL_get_error(qc->tls, 0)); return -1; } assert(ossl_quic_channel_is_handshake_complete(qc->ch)); return 1; } if (tls_wants_non_io_retry(qc)) { QUIC_RAISE_NORMAL_ERROR(ctx, SSL_get_error(qc->tls, 0)); return -1; } /* * Otherwise, indicate that the handshake isn't done yet. * We can only get here in non-blocking mode. */ QUIC_RAISE_NORMAL_ERROR(ctx, SSL_ERROR_WANT_READ); return -1; /* Non-protocol error */ } QUIC_TAKES_LOCK int ossl_quic_do_handshake(SSL *s) { int ret; QCTX ctx; if (!expect_quic_cs(s, &ctx)) return 0; qctx_lock_for_io(&ctx); ret = quic_do_handshake(&ctx); qctx_unlock(&ctx); return ret; } /* SSL_connect */ int ossl_quic_connect(SSL *s) { /* Ensure we are in connect state (no-op if non-idle). */ if (!ossl_quic_set_connect_state(s, 1)) return -1; /* Begin or continue the handshake */ return ossl_quic_do_handshake(s); } /* SSL_accept */ int ossl_quic_accept(SSL *s) { /* Ensure we are in accept state (no-op if non-idle). */ if (!ossl_quic_set_accept_state(s, 1)) return -1; /* Begin or continue the handshake */ return ossl_quic_do_handshake(s); } /* * QUIC Front-End I/O API: Stream Lifecycle Operations * =================================================== * * SSL_stream_new => ossl_quic_conn_stream_new * */ /* * Try to create the default XSO if it doesn't already exist. Returns 1 if the * default XSO was created. Returns 0 if it was not (e.g. because it already * exists). Note that this is NOT an error condition. */ QUIC_NEEDS_LOCK static int qc_try_create_default_xso_for_write(QCTX *ctx) { uint64_t flags = 0; QUIC_CONNECTION *qc = ctx->qc; if (qc->default_xso_created || qc->default_stream_mode == SSL_DEFAULT_STREAM_MODE_NONE) /* * We only do this once. If the user detaches a previously created * default XSO we don't auto-create another one. */ return QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_NO_STREAM, NULL); /* Create a locally-initiated stream. */ if (qc->default_stream_mode == SSL_DEFAULT_STREAM_MODE_AUTO_UNI) flags |= SSL_STREAM_FLAG_UNI; qc_set_default_xso(qc, (QUIC_XSO *)quic_conn_stream_new(ctx, flags, /*needs_lock=*/0), /*touch=*/0); if (qc->default_xso == NULL) return QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); qc_touch_default_xso(qc); return 1; } struct quic_wait_for_stream_args { QUIC_CONNECTION *qc; QUIC_STREAM *qs; QCTX *ctx; uint64_t expect_id; }; QUIC_NEEDS_LOCK static int quic_wait_for_stream(void *arg) { struct quic_wait_for_stream_args *args = arg; if (!quic_mutation_allowed(args->qc, /*req_active=*/1)) { /* If connection is torn down due to an error while blocking, stop. */ QUIC_RAISE_NON_NORMAL_ERROR(args->ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); return -1; } args->qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(args->qc->ch), args->expect_id | QUIC_STREAM_DIR_BIDI); if (args->qs == NULL) args->qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(args->qc->ch), args->expect_id | QUIC_STREAM_DIR_UNI); if (args->qs != NULL) return 1; /* stream now exists */ return 0; /* did not get a stream, keep trying */ } QUIC_NEEDS_LOCK static int qc_wait_for_default_xso_for_read(QCTX *ctx, int peek) { /* Called on a QCSO and we don't currently have a default stream. */ uint64_t expect_id; QUIC_CONNECTION *qc = ctx->qc; QUIC_STREAM *qs; int res; struct quic_wait_for_stream_args wargs; OSSL_RTT_INFO rtt_info; /* * If default stream functionality is disabled or we already detached * one, don't make another default stream and just fail. */ if (qc->default_xso_created || qc->default_stream_mode == SSL_DEFAULT_STREAM_MODE_NONE) return QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_NO_STREAM, NULL); /* * The peer may have opened a stream since we last ticked. So tick and * see if the stream with ordinal 0 (remote, bidi/uni based on stream * mode) exists yet. QUIC stream IDs must be allocated in order, so the * first stream created by a peer must have an ordinal of 0. */ expect_id = qc->as_server ? QUIC_STREAM_INITIATOR_CLIENT : QUIC_STREAM_INITIATOR_SERVER; qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(qc->ch), expect_id | QUIC_STREAM_DIR_BIDI); if (qs == NULL) qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(qc->ch), expect_id | QUIC_STREAM_DIR_UNI); if (qs == NULL) { qctx_maybe_autotick(ctx); qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(qc->ch), expect_id); } if (qs == NULL) { if (peek) return 0; if (ossl_quic_channel_is_term_any(qc->ch)) { return QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); } else if (!qctx_blocking(ctx)) { /* Non-blocking mode, so just bail immediately. */ return QUIC_RAISE_NORMAL_ERROR(ctx, SSL_ERROR_WANT_READ); } /* Block until we have a stream. */ wargs.qc = qc; wargs.qs = NULL; wargs.ctx = ctx; wargs.expect_id = expect_id; res = block_until_pred(ctx, quic_wait_for_stream, &wargs, 0); if (res == 0) return QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); else if (res < 0 || wargs.qs == NULL) /* quic_wait_for_stream raised error here */ return 0; qs = wargs.qs; } /* * We now have qs != NULL. Remove it from the incoming stream queue so that * it isn't also returned by any future SSL_accept_stream calls. */ ossl_statm_get_rtt_info(ossl_quic_channel_get_statm(qc->ch), &rtt_info); ossl_quic_stream_map_remove_from_accept_queue(ossl_quic_channel_get_qsm(qc->ch), qs, rtt_info.smoothed_rtt); /* * Now make qs the default stream, creating the necessary XSO. */ qc_set_default_xso(qc, create_xso_from_stream(qc, qs), /*touch=*/0); if (qc->default_xso == NULL) return QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); qc_touch_default_xso(qc); /* inhibits default XSO */ return 1; } QUIC_NEEDS_LOCK static QUIC_XSO *create_xso_from_stream(QUIC_CONNECTION *qc, QUIC_STREAM *qs) { QUIC_XSO *xso = NULL; if ((xso = OPENSSL_zalloc(sizeof(*xso))) == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_CRYPTO_LIB, NULL); goto err; } if (!ossl_quic_obj_init(&xso->obj, qc->obj.ssl.ctx, SSL_TYPE_QUIC_XSO, &qc->obj.ssl, NULL, NULL)) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL); goto err; } /* XSO refs QC */ if (!SSL_up_ref(&qc->obj.ssl)) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_SSL_LIB, NULL); goto err; } xso->conn = qc; xso->ssl_mode = qc->default_ssl_mode; xso->ssl_options = qc->default_ssl_options & OSSL_QUIC_PERMITTED_OPTIONS_STREAM; xso->last_error = SSL_ERROR_NONE; xso->stream = qs; ++qc->num_xso; xso_update_options(xso); return xso; err: OPENSSL_free(xso); return NULL; } struct quic_new_stream_wait_args { QUIC_CONNECTION *qc; int is_uni; }; static int quic_new_stream_wait(void *arg) { struct quic_new_stream_wait_args *args = arg; QUIC_CONNECTION *qc = args->qc; if (!quic_mutation_allowed(qc, /*req_active=*/1)) return -1; if (ossl_quic_channel_is_new_local_stream_admissible(qc->ch, args->is_uni)) return 1; return 0; } /* locking depends on need_lock */ static SSL *quic_conn_stream_new(QCTX *ctx, uint64_t flags, int need_lock) { int ret; QUIC_CONNECTION *qc = ctx->qc; QUIC_XSO *xso = NULL; QUIC_STREAM *qs = NULL; int is_uni = ((flags & SSL_STREAM_FLAG_UNI) != 0); int no_blocking = ((flags & SSL_STREAM_FLAG_NO_BLOCK) != 0); int advance = ((flags & SSL_STREAM_FLAG_ADVANCE) != 0); if (need_lock) qctx_lock(ctx); if (!quic_mutation_allowed(qc, /*req_active=*/0)) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); goto err; } if (!advance && !ossl_quic_channel_is_new_local_stream_admissible(qc->ch, is_uni)) { struct quic_new_stream_wait_args args; /* * Stream count flow control currently doesn't permit this stream to be * opened. */ if (no_blocking || !qctx_blocking(ctx)) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_STREAM_COUNT_LIMITED, NULL); goto err; } args.qc = qc; args.is_uni = is_uni; /* Blocking mode - wait until we can get a stream. */ ret = block_until_pred(ctx, quic_new_stream_wait, &args, 0); if (!quic_mutation_allowed(qc, /*req_active=*/1)) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); goto err; /* Shutdown before completion */ } else if (ret <= 0) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); goto err; /* Non-protocol error */ } } qs = ossl_quic_channel_new_stream_local(qc->ch, is_uni); if (qs == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); goto err; } xso = create_xso_from_stream(qc, qs); if (xso == NULL) goto err; qc_touch_default_xso(qc); /* inhibits default XSO */ if (need_lock) qctx_unlock(ctx); return &xso->obj.ssl; err: OPENSSL_free(xso); ossl_quic_stream_map_release(ossl_quic_channel_get_qsm(qc->ch), qs); if (need_lock) qctx_unlock(ctx); return NULL; } QUIC_TAKES_LOCK SSL *ossl_quic_conn_stream_new(SSL *s, uint64_t flags) { QCTX ctx; if (!expect_quic_conn_only(s, &ctx)) return NULL; return quic_conn_stream_new(&ctx, flags, /*need_lock=*/1); } /* * QUIC Front-End I/O API: Steady-State Operations * =============================================== * * Here we dispatch calls to the steady-state front-end I/O API functions; that * is, the functions used during the established phase of a QUIC connection * (e.g. SSL_read, SSL_write). * * Each function must handle both blocking and non-blocking modes. As discussed * above, all QUIC I/O is implemented using non-blocking mode internally. * * SSL_get_error => partially implemented by ossl_quic_get_error * SSL_want => ossl_quic_want * (BIO/)SSL_read => ossl_quic_read * (BIO/)SSL_write => ossl_quic_write * SSL_pending => ossl_quic_pending * SSL_stream_conclude => ossl_quic_conn_stream_conclude * SSL_key_update => ossl_quic_key_update */ /* SSL_get_error */ int ossl_quic_get_error(const SSL *s, int i) { QCTX ctx; int net_error, last_error; /* SSL_get_errors() should not raise new errors */ if (!is_quic_cs(s, &ctx, 0 /* suppress errors */)) return SSL_ERROR_SSL; qctx_lock(&ctx); net_error = ossl_quic_channel_net_error(ctx.qc->ch); last_error = ctx.is_stream ? ctx.xso->last_error : ctx.qc->last_error; qctx_unlock(&ctx); if (net_error) return SSL_ERROR_SYSCALL; return last_error; } /* Converts a code returned by SSL_get_error to a code returned by SSL_want. */ static int error_to_want(int error) { switch (error) { case SSL_ERROR_WANT_CONNECT: /* never used - UDP is connectionless */ case SSL_ERROR_WANT_ACCEPT: /* never used - UDP is connectionless */ case SSL_ERROR_ZERO_RETURN: default: return SSL_NOTHING; case SSL_ERROR_WANT_READ: return SSL_READING; case SSL_ERROR_WANT_WRITE: return SSL_WRITING; case SSL_ERROR_WANT_RETRY_VERIFY: return SSL_RETRY_VERIFY; case SSL_ERROR_WANT_CLIENT_HELLO_CB: return SSL_CLIENT_HELLO_CB; case SSL_ERROR_WANT_X509_LOOKUP: return SSL_X509_LOOKUP; } } /* SSL_want */ int ossl_quic_want(const SSL *s) { QCTX ctx; int w; if (!expect_quic_cs(s, &ctx)) return SSL_NOTHING; qctx_lock(&ctx); w = error_to_want(ctx.is_stream ? ctx.xso->last_error : ctx.qc->last_error); qctx_unlock(&ctx); return w; } /* * SSL_write * --------- * * The set of functions below provide the implementation of the public SSL_write * function. We must handle: * * - both blocking and non-blocking operation at the application level, * depending on how we are configured; * * - SSL_MODE_ENABLE_PARTIAL_WRITE being on or off; * * - SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER. * */ QUIC_NEEDS_LOCK static void quic_post_write(QUIC_XSO *xso, int did_append, int did_append_all, uint64_t flags, int do_tick) { /* * We have appended at least one byte to the stream. * Potentially mark stream as active, depending on FC. */ if (did_append) ossl_quic_stream_map_update_state(ossl_quic_channel_get_qsm(xso->conn->ch), xso->stream); if (did_append_all && (flags & SSL_WRITE_FLAG_CONCLUDE) != 0) ossl_quic_sstream_fin(xso->stream->sstream); /* * Try and send. * * TODO(QUIC FUTURE): It is probably inefficient to try and do this * immediately, plus we should eventually consider Nagle's algorithm. */ if (do_tick) ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(xso->conn->ch), 0); } struct quic_write_again_args { QUIC_XSO *xso; const unsigned char *buf; size_t len; size_t total_written; int err; uint64_t flags; }; /* * Absolute maximum write buffer size, enforced to prevent a rogue peer from * deliberately inducing DoS. This has been chosen based on the optimal buffer * size for an RTT of 500ms and a bandwidth of 100 Mb/s. */ #define MAX_WRITE_BUF_SIZE (6 * 1024 * 1024) /* * Ensure spare buffer space available (up until a limit, at least). */ QUIC_NEEDS_LOCK static int sstream_ensure_spare(QUIC_SSTREAM *sstream, uint64_t spare) { size_t cur_sz = ossl_quic_sstream_get_buffer_size(sstream); size_t avail = ossl_quic_sstream_get_buffer_avail(sstream); size_t spare_ = (spare > SIZE_MAX) ? SIZE_MAX : (size_t)spare; size_t new_sz, growth; if (spare_ <= avail || cur_sz == MAX_WRITE_BUF_SIZE) return 1; growth = spare_ - avail; if (cur_sz + growth > MAX_WRITE_BUF_SIZE) new_sz = MAX_WRITE_BUF_SIZE; else new_sz = cur_sz + growth; return ossl_quic_sstream_set_buffer_size(sstream, new_sz); } /* * Append to a QUIC_STREAM's QUIC_SSTREAM, ensuring buffer space is expanded * as needed according to flow control. */ QUIC_NEEDS_LOCK static int xso_sstream_append(QUIC_XSO *xso, const unsigned char *buf, size_t len, size_t *actual_written) { QUIC_SSTREAM *sstream = xso->stream->sstream; uint64_t cur = ossl_quic_sstream_get_cur_size(sstream); uint64_t cwm = ossl_quic_txfc_get_cwm(&xso->stream->txfc); uint64_t permitted = (cwm >= cur ? cwm - cur : 0); if (len > permitted) len = (size_t)permitted; if (!sstream_ensure_spare(sstream, len)) return 0; return ossl_quic_sstream_append(sstream, buf, len, actual_written); } QUIC_NEEDS_LOCK static int quic_write_again(void *arg) { struct quic_write_again_args *args = arg; size_t actual_written = 0; if (!quic_mutation_allowed(args->xso->conn, /*req_active=*/1)) /* If connection is torn down due to an error while blocking, stop. */ return -2; if (!quic_validate_for_write(args->xso, &args->err)) /* * Stream may have become invalid for write due to connection events * while we blocked. */ return -2; args->err = ERR_R_INTERNAL_ERROR; if (!xso_sstream_append(args->xso, args->buf, args->len, &actual_written)) return -2; quic_post_write(args->xso, actual_written > 0, args->len == actual_written, args->flags, 0); args->buf += actual_written; args->len -= actual_written; args->total_written += actual_written; if (args->len == 0) /* Written everything, done. */ return 1; /* Not written everything yet, keep trying. */ return 0; } QUIC_NEEDS_LOCK static int quic_write_blocking(QCTX *ctx, const void *buf, size_t len, uint64_t flags, size_t *written) { int res; QUIC_XSO *xso = ctx->xso; struct quic_write_again_args args; size_t actual_written = 0; /* First make a best effort to append as much of the data as possible. */ if (!xso_sstream_append(xso, buf, len, &actual_written)) { /* Stream already finished or allocation error. */ *written = 0; return QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); } quic_post_write(xso, actual_written > 0, actual_written == len, flags, 1); /* * Record however much data we wrote */ *written = actual_written; if (actual_written == len) { /* Managed to append everything on the first try. */ return 1; } /* * We did not manage to append all of the data immediately, so the stream * buffer has probably filled up. This means we need to block until some of * it is freed up. */ args.xso = xso; args.buf = (const unsigned char *)buf + actual_written; args.len = len - actual_written; args.total_written = 0; args.err = ERR_R_INTERNAL_ERROR; args.flags = flags; res = block_until_pred(ctx, quic_write_again, &args, 0); if (res <= 0) { if (!quic_mutation_allowed(xso->conn, /*req_active=*/1)) return QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); else return QUIC_RAISE_NON_NORMAL_ERROR(ctx, args.err, NULL); } /* * When waiting on extra buffer space to be available, args.total_written * holds the amount of remaining data we requested to write, which will be * something less than the len parameter passed in, however much we wrote * here, add it to the value that we wrote when we initially called * xso_sstream_append */ *written += args.total_written; return 1; } /* * Functions to manage All-or-Nothing (AON) (that is, non-ENABLE_PARTIAL_WRITE) * write semantics. */ static void aon_write_begin(QUIC_XSO *xso, const unsigned char *buf, size_t buf_len, size_t already_sent) { assert(!xso->aon_write_in_progress); xso->aon_write_in_progress = 1; xso->aon_buf_base = buf; xso->aon_buf_pos = already_sent; xso->aon_buf_len = buf_len; } static void aon_write_finish(QUIC_XSO *xso) { xso->aon_write_in_progress = 0; xso->aon_buf_base = NULL; xso->aon_buf_pos = 0; xso->aon_buf_len = 0; } QUIC_NEEDS_LOCK static int quic_write_nonblocking_aon(QCTX *ctx, const void *buf, size_t len, uint64_t flags, size_t *written) { QUIC_XSO *xso = ctx->xso; const void *actual_buf; size_t actual_len, actual_written = 0; int accept_moving_buffer = ((xso->ssl_mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER) != 0); if (xso->aon_write_in_progress) { /* * We are in the middle of an AON write (i.e., a previous write did not * manage to append all data to the SSTREAM and we have Enable Partial * Write (EPW) mode disabled.) */ if ((!accept_moving_buffer && xso->aon_buf_base != buf) || len != xso->aon_buf_len) /* * Pointer must not have changed if we are not in accept moving * buffer mode. Length must never change. */ return QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_BAD_WRITE_RETRY, NULL); actual_buf = (unsigned char *)buf + xso->aon_buf_pos; actual_len = len - xso->aon_buf_pos; assert(actual_len > 0); } else { actual_buf = buf; actual_len = len; } /* First make a best effort to append as much of the data as possible. */ if (!xso_sstream_append(xso, actual_buf, actual_len, &actual_written)) { /* Stream already finished or allocation error. */ *written = 0; return QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); } quic_post_write(xso, actual_written > 0, actual_written == actual_len, flags, qctx_should_autotick(ctx)); if (actual_written == actual_len) { /* We have sent everything. */ if (xso->aon_write_in_progress) { /* * We have sent everything, and we were in the middle of an AON * write. The output write length is the total length of the AON * buffer, not however many bytes we managed to write to the stream * in this call. */ *written = xso->aon_buf_len; aon_write_finish(xso); } else { *written = actual_written; } return 1; } if (xso->aon_write_in_progress) { /* * AON write is in progress but we have not written everything yet. We * may have managed to send zero bytes, or some number of bytes less * than the total remaining which need to be appended during this * AON operation. */ xso->aon_buf_pos += actual_written; assert(xso->aon_buf_pos < xso->aon_buf_len); return QUIC_RAISE_NORMAL_ERROR(ctx, SSL_ERROR_WANT_WRITE); } /* * Not in an existing AON operation but partial write is not enabled, so we * need to begin a new AON operation. However we needn't bother if we didn't * actually append anything. */ if (actual_written > 0) aon_write_begin(xso, buf, len, actual_written); /* * AON - We do not publicly admit to having appended anything until AON * completes. */ *written = 0; return QUIC_RAISE_NORMAL_ERROR(ctx, SSL_ERROR_WANT_WRITE); } QUIC_NEEDS_LOCK static int quic_write_nonblocking_epw(QCTX *ctx, const void *buf, size_t len, uint64_t flags, size_t *written) { QUIC_XSO *xso = ctx->xso; /* Simple best effort operation. */ if (!xso_sstream_append(xso, buf, len, written)) { /* Stream already finished or allocation error. */ *written = 0; return QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); } quic_post_write(xso, *written > 0, *written == len, flags, qctx_should_autotick(ctx)); if (*written == 0) /* SSL_write_ex returns 0 if it didn't write anything. */ return QUIC_RAISE_NORMAL_ERROR(ctx, SSL_ERROR_WANT_WRITE); return 1; } QUIC_NEEDS_LOCK static int quic_validate_for_write(QUIC_XSO *xso, int *err) { QUIC_STREAM_MAP *qsm; if (xso == NULL || xso->stream == NULL) { *err = ERR_R_INTERNAL_ERROR; return 0; } switch (xso->stream->send_state) { default: case QUIC_SSTREAM_STATE_NONE: *err = SSL_R_STREAM_RECV_ONLY; return 0; case QUIC_SSTREAM_STATE_READY: qsm = ossl_quic_channel_get_qsm(xso->conn->ch); if (!ossl_quic_stream_map_ensure_send_part_id(qsm, xso->stream)) { *err = ERR_R_INTERNAL_ERROR; return 0; } /* FALLTHROUGH */ case QUIC_SSTREAM_STATE_SEND: case QUIC_SSTREAM_STATE_DATA_SENT: if (ossl_quic_sstream_get_final_size(xso->stream->sstream, NULL)) { *err = SSL_R_STREAM_FINISHED; return 0; } return 1; case QUIC_SSTREAM_STATE_DATA_RECVD: *err = SSL_R_STREAM_FINISHED; return 0; case QUIC_SSTREAM_STATE_RESET_SENT: case QUIC_SSTREAM_STATE_RESET_RECVD: *err = SSL_R_STREAM_RESET; return 0; } } QUIC_TAKES_LOCK int ossl_quic_write_flags(SSL *s, const void *buf, size_t len, uint64_t flags, size_t *written) { int ret; QCTX ctx; int partial_write, err; *written = 0; if (len == 0) { /* Do not autocreate default XSO for zero-length writes. */ if (!expect_quic_cs(s, &ctx)) return 0; qctx_lock_for_io(&ctx); } else { if (!expect_quic_with_stream_lock(s, /*remote_init=*/0, /*io=*/1, &ctx)) return 0; } partial_write = ((ctx.xso != NULL) ? ((ctx.xso->ssl_mode & SSL_MODE_ENABLE_PARTIAL_WRITE) != 0) : 0); if ((flags & ~SSL_WRITE_FLAG_CONCLUDE) != 0) { ret = QUIC_RAISE_NON_NORMAL_ERROR(&ctx, SSL_R_UNSUPPORTED_WRITE_FLAG, NULL); goto out; } if (!quic_mutation_allowed(ctx.qc, /*req_active=*/0)) { ret = QUIC_RAISE_NON_NORMAL_ERROR(&ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); goto out; } /* * If we haven't finished the handshake, try to advance it. * We don't accept writes until the handshake is completed. */ if (quic_do_handshake(&ctx) < 1) { ret = 0; goto out; } /* Ensure correct stream state, stream send part not concluded, etc. */ if (len > 0 && !quic_validate_for_write(ctx.xso, &err)) { ret = QUIC_RAISE_NON_NORMAL_ERROR(&ctx, err, NULL); goto out; } if (len == 0) { if ((flags & SSL_WRITE_FLAG_CONCLUDE) != 0) quic_post_write(ctx.xso, 0, 1, flags, qctx_should_autotick(&ctx)); ret = 1; goto out; } if (qctx_blocking(&ctx)) ret = quic_write_blocking(&ctx, buf, len, flags, written); else if (partial_write) ret = quic_write_nonblocking_epw(&ctx, buf, len, flags, written); else ret = quic_write_nonblocking_aon(&ctx, buf, len, flags, written); out: qctx_unlock(&ctx); return ret; } QUIC_TAKES_LOCK int ossl_quic_write(SSL *s, const void *buf, size_t len, size_t *written) { return ossl_quic_write_flags(s, buf, len, 0, written); } /* * SSL_read * -------- */ struct quic_read_again_args { QCTX *ctx; QUIC_STREAM *stream; void *buf; size_t len; size_t *bytes_read; int peek; }; QUIC_NEEDS_LOCK static int quic_validate_for_read(QUIC_XSO *xso, int *err, int *eos) { QUIC_STREAM_MAP *qsm; *eos = 0; if (xso == NULL || xso->stream == NULL) { *err = ERR_R_INTERNAL_ERROR; return 0; } switch (xso->stream->recv_state) { default: case QUIC_RSTREAM_STATE_NONE: *err = SSL_R_STREAM_SEND_ONLY; return 0; case QUIC_RSTREAM_STATE_RECV: case QUIC_RSTREAM_STATE_SIZE_KNOWN: case QUIC_RSTREAM_STATE_DATA_RECVD: return 1; case QUIC_RSTREAM_STATE_DATA_READ: *eos = 1; return 0; case QUIC_RSTREAM_STATE_RESET_RECVD: qsm = ossl_quic_channel_get_qsm(xso->conn->ch); ossl_quic_stream_map_notify_app_read_reset_recv_part(qsm, xso->stream); /* FALLTHROUGH */ case QUIC_RSTREAM_STATE_RESET_READ: *err = SSL_R_STREAM_RESET; return 0; } } QUIC_NEEDS_LOCK static int quic_read_actual(QCTX *ctx, QUIC_STREAM *stream, void *buf, size_t buf_len, size_t *bytes_read, int peek) { int is_fin = 0, err, eos; QUIC_CONNECTION *qc = ctx->qc; if (!quic_validate_for_read(ctx->xso, &err, &eos)) { if (eos) { ctx->xso->retired_fin = 1; return QUIC_RAISE_NORMAL_ERROR(ctx, SSL_ERROR_ZERO_RETURN); } else { return QUIC_RAISE_NON_NORMAL_ERROR(ctx, err, NULL); } } if (peek) { if (!ossl_quic_rstream_peek(stream->rstream, buf, buf_len, bytes_read, &is_fin)) return QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); } else { if (!ossl_quic_rstream_read(stream->rstream, buf, buf_len, bytes_read, &is_fin)) return QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); } if (!peek) { if (*bytes_read > 0) { /* * We have read at least one byte from the stream. Inform stream-level * RXFC of the retirement of controlled bytes. Update the active stream * status (the RXFC may now want to emit a frame granting more credit to * the peer). */ OSSL_RTT_INFO rtt_info; ossl_statm_get_rtt_info(ossl_quic_channel_get_statm(qc->ch), &rtt_info); if (!ossl_quic_rxfc_on_retire(&stream->rxfc, *bytes_read, rtt_info.smoothed_rtt)) return QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); } if (is_fin && !peek) { QUIC_STREAM_MAP *qsm = ossl_quic_channel_get_qsm(ctx->qc->ch); ossl_quic_stream_map_notify_totally_read(qsm, ctx->xso->stream); } if (*bytes_read > 0) ossl_quic_stream_map_update_state(ossl_quic_channel_get_qsm(qc->ch), stream); } if (*bytes_read == 0 && is_fin) { ctx->xso->retired_fin = 1; return QUIC_RAISE_NORMAL_ERROR(ctx, SSL_ERROR_ZERO_RETURN); } return 1; } QUIC_NEEDS_LOCK static int quic_read_again(void *arg) { struct quic_read_again_args *args = arg; if (!quic_mutation_allowed(args->ctx->qc, /*req_active=*/1)) { /* If connection is torn down due to an error while blocking, stop. */ QUIC_RAISE_NON_NORMAL_ERROR(args->ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); return -1; } if (!quic_read_actual(args->ctx, args->stream, args->buf, args->len, args->bytes_read, args->peek)) return -1; if (*args->bytes_read > 0) /* got at least one byte, the SSL_read op can finish now */ return 1; return 0; /* did not read anything, keep trying */ } QUIC_TAKES_LOCK static int quic_read(SSL *s, void *buf, size_t len, size_t *bytes_read, int peek) { int ret, res; QCTX ctx; struct quic_read_again_args args; *bytes_read = 0; if (!expect_quic_cs(s, &ctx)) return 0; qctx_lock_for_io(&ctx); /* If we haven't finished the handshake, try to advance it. */ if (quic_do_handshake(&ctx) < 1) { ret = 0; /* ossl_quic_do_handshake raised error here */ goto out; } if (ctx.xso == NULL) { /* * Called on a QCSO and we don't currently have a default stream. * * Wait until we get a stream initiated by the peer (blocking mode) or * fail if we don't have one yet (non-blocking mode). */ if (!qc_wait_for_default_xso_for_read(&ctx, /*peek=*/0)) { ret = 0; /* error already raised here */ goto out; } ctx.xso = ctx.qc->default_xso; } if (!quic_read_actual(&ctx, ctx.xso->stream, buf, len, bytes_read, peek)) { ret = 0; /* quic_read_actual raised error here */ goto out; } if (*bytes_read > 0) { /* * Even though we succeeded, tick the reactor here to ensure we are * handling other aspects of the QUIC connection. */ if (quic_mutation_allowed(ctx.qc, /*req_active=*/0)) qctx_maybe_autotick(&ctx); ret = 1; } else if (!quic_mutation_allowed(ctx.qc, /*req_active=*/0)) { ret = QUIC_RAISE_NON_NORMAL_ERROR(&ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); goto out; } else if (qctx_blocking(&ctx)) { /* * We were not able to read anything immediately, so our stream * buffer is empty. This means we need to block until we get * at least one byte. */ args.ctx = &ctx; args.stream = ctx.xso->stream; args.buf = buf; args.len = len; args.bytes_read = bytes_read; args.peek = peek; res = block_until_pred(&ctx, quic_read_again, &args, 0); if (res == 0) { ret = QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_INTERNAL_ERROR, NULL); goto out; } else if (res < 0) { ret = 0; /* quic_read_again raised error here */ goto out; } ret = 1; } else { /* * We did not get any bytes and are not in blocking mode. * Tick to see if this delivers any more. */ qctx_maybe_autotick(&ctx); /* Try the read again. */ if (!quic_read_actual(&ctx, ctx.xso->stream, buf, len, bytes_read, peek)) { ret = 0; /* quic_read_actual raised error here */ goto out; } if (*bytes_read > 0) ret = 1; /* Succeeded this time. */ else ret = QUIC_RAISE_NORMAL_ERROR(&ctx, SSL_ERROR_WANT_READ); } out: qctx_unlock(&ctx); return ret; } int ossl_quic_read(SSL *s, void *buf, size_t len, size_t *bytes_read) { return quic_read(s, buf, len, bytes_read, 0); } int ossl_quic_peek(SSL *s, void *buf, size_t len, size_t *bytes_read) { return quic_read(s, buf, len, bytes_read, 1); } /* * SSL_pending * ----------- */ QUIC_TAKES_LOCK static size_t ossl_quic_pending_int(const SSL *s, int check_channel) { QCTX ctx; size_t avail = 0; if (!expect_quic_cs(s, &ctx)) return 0; qctx_lock(&ctx); if (!ctx.qc->started) goto out; if (ctx.xso == NULL) { /* No XSO yet, but there might be a default XSO eligible to be created. */ if (qc_wait_for_default_xso_for_read(&ctx, /*peek=*/1)) { ctx.xso = ctx.qc->default_xso; } else { QUIC_RAISE_NON_NORMAL_ERROR(&ctx, SSL_R_NO_STREAM, NULL); goto out; } } if (ctx.xso->stream == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_INTERNAL_ERROR, NULL); goto out; } if (check_channel) avail = ossl_quic_stream_recv_pending(ctx.xso->stream, /*include_fin=*/1) || ossl_quic_channel_has_pending(ctx.qc->ch) || ossl_quic_channel_is_term_any(ctx.qc->ch); else avail = ossl_quic_stream_recv_pending(ctx.xso->stream, /*include_fin=*/0); out: qctx_unlock(&ctx); return avail; } size_t ossl_quic_pending(const SSL *s) { return ossl_quic_pending_int(s, /*check_channel=*/0); } int ossl_quic_has_pending(const SSL *s) { /* Do we have app-side pending data or pending URXEs or RXEs? */ return ossl_quic_pending_int(s, /*check_channel=*/1) > 0; } /* * SSL_stream_conclude * ------------------- */ QUIC_TAKES_LOCK int ossl_quic_conn_stream_conclude(SSL *s) { QCTX ctx; QUIC_STREAM *qs; int err; + int ret; if (!expect_quic_with_stream_lock(s, /*remote_init=*/0, /*io=*/0, &ctx)) return 0; qs = ctx.xso->stream; if (!quic_mutation_allowed(ctx.qc, /*req_active=*/1)) { + ret = QUIC_RAISE_NON_NORMAL_ERROR(&ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); qctx_unlock(&ctx); - return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); + return ret; } if (!quic_validate_for_write(ctx.xso, &err)) { + ret = QUIC_RAISE_NON_NORMAL_ERROR(&ctx, err, NULL); qctx_unlock(&ctx); - return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, err, NULL); + return ret; } if (ossl_quic_sstream_get_final_size(qs->sstream, NULL)) { qctx_unlock(&ctx); return 1; } ossl_quic_sstream_fin(qs->sstream); quic_post_write(ctx.xso, 1, 0, 0, qctx_should_autotick(&ctx)); qctx_unlock(&ctx); return 1; } /* * SSL_inject_net_dgram * -------------------- */ QUIC_TAKES_LOCK int SSL_inject_net_dgram(SSL *s, const unsigned char *buf, size_t buf_len, const BIO_ADDR *peer, const BIO_ADDR *local) { int ret = 0; QCTX ctx; QUIC_DEMUX *demux; QUIC_PORT *port; if (!expect_quic_csl(s, &ctx)) return 0; qctx_lock(&ctx); port = ossl_quic_obj_get0_port(ctx.obj); if (port == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_UNSUPPORTED, NULL); goto err; } demux = ossl_quic_port_get0_demux(port); ret = ossl_quic_demux_inject(demux, buf, buf_len, peer, local); err: qctx_unlock(&ctx); return ret; } /* * SSL_get0_connection * ------------------- */ SSL *ossl_quic_get0_connection(SSL *s) { QCTX ctx; if (!expect_quic_cs(s, &ctx)) return NULL; return &ctx.qc->obj.ssl; } /* * SSL_get0_listener * ----------------- */ SSL *ossl_quic_get0_listener(SSL *s) { QCTX ctx; if (!expect_quic_csl(s, &ctx)) return NULL; return ctx.ql != NULL ? &ctx.ql->obj.ssl : NULL; } /* * SSL_get0_domain * --------------- */ SSL *ossl_quic_get0_domain(SSL *s) { QCTX ctx; if (!expect_quic_any(s, &ctx)) return NULL; return ctx.qd != NULL ? &ctx.qd->obj.ssl : NULL; } /* * SSL_get_domain_flags * -------------------- */ int ossl_quic_get_domain_flags(const SSL *ssl, uint64_t *domain_flags) { QCTX ctx; if (!expect_quic_any(ssl, &ctx)) return 0; if (domain_flags != NULL) *domain_flags = ctx.obj->domain_flags; return 1; } /* * SSL_get_stream_type * ------------------- */ int ossl_quic_get_stream_type(SSL *s) { QCTX ctx; if (!expect_quic_cs(s, &ctx)) return SSL_STREAM_TYPE_BIDI; if (ctx.xso == NULL) { /* * If deferred XSO creation has yet to occur, proceed according to the * default stream mode. If AUTO_BIDI or AUTO_UNI is set, we cannot know * what kind of stream will be created yet, so return BIDI on the basis * that at this time, the client still has the option of calling * SSL_read() or SSL_write() first. */ if (ctx.qc->default_xso_created || ctx.qc->default_stream_mode == SSL_DEFAULT_STREAM_MODE_NONE) return SSL_STREAM_TYPE_NONE; else return SSL_STREAM_TYPE_BIDI; } if (ossl_quic_stream_is_bidi(ctx.xso->stream)) return SSL_STREAM_TYPE_BIDI; if (ossl_quic_stream_is_server_init(ctx.xso->stream) != ctx.qc->as_server) return SSL_STREAM_TYPE_READ; else return SSL_STREAM_TYPE_WRITE; } /* * SSL_get_stream_id * ----------------- */ QUIC_TAKES_LOCK uint64_t ossl_quic_get_stream_id(SSL *s) { QCTX ctx; uint64_t id; if (!expect_quic_with_stream_lock(s, /*remote_init=*/-1, /*io=*/0, &ctx)) return UINT64_MAX; id = ctx.xso->stream->id; qctx_unlock(&ctx); return id; } /* * SSL_is_stream_local * ------------------- */ QUIC_TAKES_LOCK int ossl_quic_is_stream_local(SSL *s) { QCTX ctx; int is_local; if (!expect_quic_with_stream_lock(s, /*remote_init=*/-1, /*io=*/0, &ctx)) return -1; is_local = ossl_quic_stream_is_local_init(ctx.xso->stream); qctx_unlock(&ctx); return is_local; } /* * SSL_set_default_stream_mode * --------------------------- */ QUIC_TAKES_LOCK int ossl_quic_set_default_stream_mode(SSL *s, uint32_t mode) { QCTX ctx; if (!expect_quic_conn_only(s, &ctx)) return 0; qctx_lock(&ctx); if (ctx.qc->default_xso_created) { qctx_unlock(&ctx); return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED, "too late to change default stream mode"); } switch (mode) { case SSL_DEFAULT_STREAM_MODE_NONE: case SSL_DEFAULT_STREAM_MODE_AUTO_BIDI: case SSL_DEFAULT_STREAM_MODE_AUTO_UNI: ctx.qc->default_stream_mode = mode; break; default: qctx_unlock(&ctx); return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_PASSED_INVALID_ARGUMENT, "bad default stream type"); } qctx_unlock(&ctx); return 1; } /* * SSL_detach_stream * ----------------- */ QUIC_TAKES_LOCK SSL *ossl_quic_detach_stream(SSL *s) { QCTX ctx; QUIC_XSO *xso = NULL; if (!expect_quic_conn_only(s, &ctx)) return NULL; qctx_lock(&ctx); /* Calling this function inhibits default XSO autocreation. */ /* QC ref to any default XSO is transferred to us and to caller. */ qc_set_default_xso_keep_ref(ctx.qc, NULL, /*touch=*/1, &xso); qctx_unlock(&ctx); return xso != NULL ? &xso->obj.ssl : NULL; } /* * SSL_attach_stream * ----------------- */ QUIC_TAKES_LOCK int ossl_quic_attach_stream(SSL *conn, SSL *stream) { QCTX ctx; QUIC_XSO *xso; int nref; if (!expect_quic_conn_only(conn, &ctx)) return 0; if (stream == NULL || stream->type != SSL_TYPE_QUIC_XSO) return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_PASSED_NULL_PARAMETER, "stream to attach must be a valid QUIC stream"); xso = (QUIC_XSO *)stream; qctx_lock(&ctx); if (ctx.qc->default_xso != NULL) { qctx_unlock(&ctx); return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED, "connection already has a default stream"); } /* * It is a caller error for the XSO being attached as a default XSO to have * more than one ref. */ if (!CRYPTO_GET_REF(&xso->obj.ssl.references, &nref)) { qctx_unlock(&ctx); return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_INTERNAL_ERROR, "ref"); } if (nref != 1) { qctx_unlock(&ctx); return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_PASSED_INVALID_ARGUMENT, "stream being attached must have " "only 1 reference"); } /* Caller's reference to the XSO is transferred to us. */ /* Calling this function inhibits default XSO autocreation. */ qc_set_default_xso(ctx.qc, xso, /*touch=*/1); qctx_unlock(&ctx); return 1; } /* * SSL_set_incoming_stream_policy * ------------------------------ */ QUIC_NEEDS_LOCK static int qc_get_effective_incoming_stream_policy(QUIC_CONNECTION *qc) { switch (qc->incoming_stream_policy) { case SSL_INCOMING_STREAM_POLICY_AUTO: if ((qc->default_xso == NULL && !qc->default_xso_created) || qc->default_stream_mode == SSL_DEFAULT_STREAM_MODE_NONE) return SSL_INCOMING_STREAM_POLICY_ACCEPT; else return SSL_INCOMING_STREAM_POLICY_REJECT; default: return qc->incoming_stream_policy; } } QUIC_NEEDS_LOCK static void qc_update_reject_policy(QUIC_CONNECTION *qc) { int policy = qc_get_effective_incoming_stream_policy(qc); int enable_reject = (policy == SSL_INCOMING_STREAM_POLICY_REJECT); ossl_quic_channel_set_incoming_stream_auto_reject(qc->ch, enable_reject, qc->incoming_stream_aec); } QUIC_TAKES_LOCK int ossl_quic_set_incoming_stream_policy(SSL *s, int policy, uint64_t aec) { int ret = 1; QCTX ctx; if (!expect_quic_conn_only(s, &ctx)) return 0; qctx_lock(&ctx); switch (policy) { case SSL_INCOMING_STREAM_POLICY_AUTO: case SSL_INCOMING_STREAM_POLICY_ACCEPT: case SSL_INCOMING_STREAM_POLICY_REJECT: ctx.qc->incoming_stream_policy = policy; ctx.qc->incoming_stream_aec = aec; break; default: QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_PASSED_INVALID_ARGUMENT, NULL); ret = 0; break; } qc_update_reject_policy(ctx.qc); qctx_unlock(&ctx); return ret; } /* * SSL_get_value, SSL_set_value * ---------------------------- */ QUIC_TAKES_LOCK static int qc_getset_idle_timeout(QCTX *ctx, uint32_t class_, uint64_t *p_value_out, uint64_t *p_value_in) { int ret = 0; uint64_t value_out = 0, value_in; qctx_lock(ctx); switch (class_) { case SSL_VALUE_CLASS_FEATURE_REQUEST: value_out = ossl_quic_channel_get_max_idle_timeout_request(ctx->qc->ch); if (p_value_in != NULL) { value_in = *p_value_in; if (value_in > OSSL_QUIC_VLINT_MAX) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_PASSED_INVALID_ARGUMENT, NULL); goto err; } if (ossl_quic_channel_have_generated_transport_params(ctx->qc->ch)) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_FEATURE_NOT_RENEGOTIABLE, NULL); goto err; } ossl_quic_channel_set_max_idle_timeout_request(ctx->qc->ch, value_in); } break; case SSL_VALUE_CLASS_FEATURE_PEER_REQUEST: case SSL_VALUE_CLASS_FEATURE_NEGOTIATED: if (p_value_in != NULL) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_UNSUPPORTED_CONFIG_VALUE_OP, NULL); goto err; } if (!ossl_quic_channel_is_handshake_complete(ctx->qc->ch)) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_FEATURE_NEGOTIATION_NOT_COMPLETE, NULL); goto err; } value_out = (class_ == SSL_VALUE_CLASS_FEATURE_NEGOTIATED) ? ossl_quic_channel_get_max_idle_timeout_actual(ctx->qc->ch) : ossl_quic_channel_get_max_idle_timeout_peer_request(ctx->qc->ch); break; default: QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_UNSUPPORTED_CONFIG_VALUE_CLASS, NULL); goto err; } ret = 1; err: qctx_unlock(ctx); if (ret && p_value_out != NULL) *p_value_out = value_out; return ret; } QUIC_TAKES_LOCK static int qc_get_stream_avail(QCTX *ctx, uint32_t class_, int is_uni, int is_remote, uint64_t *value) { int ret = 0; if (class_ != SSL_VALUE_CLASS_GENERIC) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_UNSUPPORTED_CONFIG_VALUE_CLASS, NULL); return 0; } qctx_lock(ctx); *value = is_remote ? ossl_quic_channel_get_remote_stream_count_avail(ctx->qc->ch, is_uni) : ossl_quic_channel_get_local_stream_count_avail(ctx->qc->ch, is_uni); ret = 1; qctx_unlock(ctx); return ret; } QUIC_NEEDS_LOCK static int qctx_should_autotick(QCTX *ctx) { int event_handling_mode; QUIC_OBJ *obj = ctx->obj; for (; (event_handling_mode = obj->event_handling_mode) == SSL_VALUE_EVENT_HANDLING_MODE_INHERIT && obj->parent_obj != NULL; obj = obj->parent_obj); return event_handling_mode != SSL_VALUE_EVENT_HANDLING_MODE_EXPLICIT; } QUIC_NEEDS_LOCK static void qctx_maybe_autotick(QCTX *ctx) { if (!qctx_should_autotick(ctx)) return; ossl_quic_reactor_tick(ossl_quic_obj_get0_reactor(ctx->obj), 0); } QUIC_TAKES_LOCK static int qc_getset_event_handling(QCTX *ctx, uint32_t class_, uint64_t *p_value_out, uint64_t *p_value_in) { int ret = 0; uint64_t value_out = 0; qctx_lock(ctx); if (class_ != SSL_VALUE_CLASS_GENERIC) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_UNSUPPORTED_CONFIG_VALUE_CLASS, NULL); goto err; } if (p_value_in != NULL) { switch (*p_value_in) { case SSL_VALUE_EVENT_HANDLING_MODE_INHERIT: case SSL_VALUE_EVENT_HANDLING_MODE_IMPLICIT: case SSL_VALUE_EVENT_HANDLING_MODE_EXPLICIT: break; default: QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_PASSED_INVALID_ARGUMENT, NULL); goto err; } value_out = *p_value_in; ctx->obj->event_handling_mode = (int)value_out; } else { value_out = ctx->obj->event_handling_mode; } ret = 1; err: qctx_unlock(ctx); if (ret && p_value_out != NULL) *p_value_out = value_out; return ret; } QUIC_TAKES_LOCK static int qc_get_stream_write_buf_stat(QCTX *ctx, uint32_t class_, uint64_t *p_value_out, size_t (*getter)(QUIC_SSTREAM *sstream)) { int ret = 0; size_t value = 0; qctx_lock(ctx); if (class_ != SSL_VALUE_CLASS_GENERIC) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_UNSUPPORTED_CONFIG_VALUE_CLASS, NULL); goto err; } if (ctx->xso == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_NO_STREAM, NULL); goto err; } if (!ossl_quic_stream_has_send(ctx->xso->stream)) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_STREAM_RECV_ONLY, NULL); goto err; } if (ossl_quic_stream_has_send_buffer(ctx->xso->stream)) value = getter(ctx->xso->stream->sstream); ret = 1; err: qctx_unlock(ctx); *p_value_out = (uint64_t)value; return ret; } QUIC_NEEDS_LOCK static int expect_quic_for_value(SSL *s, QCTX *ctx, uint32_t id) { switch (id) { case SSL_VALUE_EVENT_HANDLING_MODE: case SSL_VALUE_STREAM_WRITE_BUF_SIZE: case SSL_VALUE_STREAM_WRITE_BUF_USED: case SSL_VALUE_STREAM_WRITE_BUF_AVAIL: return expect_quic_cs(s, ctx); default: return expect_quic_conn_only(s, ctx); } } QUIC_TAKES_LOCK int ossl_quic_get_value_uint(SSL *s, uint32_t class_, uint32_t id, uint64_t *value) { QCTX ctx; if (!expect_quic_for_value(s, &ctx, id)) return 0; if (value == NULL) return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_PASSED_INVALID_ARGUMENT, NULL); switch (id) { case SSL_VALUE_QUIC_IDLE_TIMEOUT: return qc_getset_idle_timeout(&ctx, class_, value, NULL); case SSL_VALUE_QUIC_STREAM_BIDI_LOCAL_AVAIL: return qc_get_stream_avail(&ctx, class_, /*uni=*/0, /*remote=*/0, value); case SSL_VALUE_QUIC_STREAM_BIDI_REMOTE_AVAIL: return qc_get_stream_avail(&ctx, class_, /*uni=*/0, /*remote=*/1, value); case SSL_VALUE_QUIC_STREAM_UNI_LOCAL_AVAIL: return qc_get_stream_avail(&ctx, class_, /*uni=*/1, /*remote=*/0, value); case SSL_VALUE_QUIC_STREAM_UNI_REMOTE_AVAIL: return qc_get_stream_avail(&ctx, class_, /*uni=*/1, /*remote=*/1, value); case SSL_VALUE_EVENT_HANDLING_MODE: return qc_getset_event_handling(&ctx, class_, value, NULL); case SSL_VALUE_STREAM_WRITE_BUF_SIZE: return qc_get_stream_write_buf_stat(&ctx, class_, value, ossl_quic_sstream_get_buffer_size); case SSL_VALUE_STREAM_WRITE_BUF_USED: return qc_get_stream_write_buf_stat(&ctx, class_, value, ossl_quic_sstream_get_buffer_used); case SSL_VALUE_STREAM_WRITE_BUF_AVAIL: return qc_get_stream_write_buf_stat(&ctx, class_, value, ossl_quic_sstream_get_buffer_avail); default: return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, SSL_R_UNSUPPORTED_CONFIG_VALUE, NULL); } return 1; } QUIC_TAKES_LOCK int ossl_quic_set_value_uint(SSL *s, uint32_t class_, uint32_t id, uint64_t value) { QCTX ctx; if (!expect_quic_for_value(s, &ctx, id)) return 0; switch (id) { case SSL_VALUE_QUIC_IDLE_TIMEOUT: return qc_getset_idle_timeout(&ctx, class_, NULL, &value); case SSL_VALUE_EVENT_HANDLING_MODE: return qc_getset_event_handling(&ctx, class_, NULL, &value); default: return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, SSL_R_UNSUPPORTED_CONFIG_VALUE, NULL); } return 1; } /* * SSL_accept_stream * ----------------- */ struct wait_for_incoming_stream_args { QCTX *ctx; QUIC_STREAM *qs; }; QUIC_NEEDS_LOCK static int wait_for_incoming_stream(void *arg) { struct wait_for_incoming_stream_args *args = arg; QUIC_CONNECTION *qc = args->ctx->qc; QUIC_STREAM_MAP *qsm = ossl_quic_channel_get_qsm(qc->ch); if (!quic_mutation_allowed(qc, /*req_active=*/1)) { /* If connection is torn down due to an error while blocking, stop. */ QUIC_RAISE_NON_NORMAL_ERROR(args->ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); return -1; } args->qs = ossl_quic_stream_map_peek_accept_queue(qsm); if (args->qs != NULL) return 1; /* got a stream */ return 0; /* did not get a stream, keep trying */ } QUIC_TAKES_LOCK SSL *ossl_quic_accept_stream(SSL *s, uint64_t flags) { QCTX ctx; int ret; SSL *new_s = NULL; QUIC_STREAM_MAP *qsm; QUIC_STREAM *qs; QUIC_XSO *xso; OSSL_RTT_INFO rtt_info; if (!expect_quic_conn_only(s, &ctx)) return NULL; qctx_lock(&ctx); if (qc_get_effective_incoming_stream_policy(ctx.qc) == SSL_INCOMING_STREAM_POLICY_REJECT) { QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED, NULL); goto out; } qsm = ossl_quic_channel_get_qsm(ctx.qc->ch); qs = ossl_quic_stream_map_peek_accept_queue(qsm); if (qs == NULL) { if (qctx_blocking(&ctx) && (flags & SSL_ACCEPT_STREAM_NO_BLOCK) == 0) { struct wait_for_incoming_stream_args args; args.ctx = &ctx; args.qs = NULL; ret = block_until_pred(&ctx, wait_for_incoming_stream, &args, 0); if (ret == 0) { QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_INTERNAL_ERROR, NULL); goto out; } else if (ret < 0 || args.qs == NULL) { goto out; } qs = args.qs; } else { goto out; } } xso = create_xso_from_stream(ctx.qc, qs); if (xso == NULL) goto out; ossl_statm_get_rtt_info(ossl_quic_channel_get_statm(ctx.qc->ch), &rtt_info); ossl_quic_stream_map_remove_from_accept_queue(qsm, qs, rtt_info.smoothed_rtt); new_s = &xso->obj.ssl; /* Calling this function inhibits default XSO autocreation. */ qc_touch_default_xso(ctx.qc); /* inhibits default XSO */ out: qctx_unlock(&ctx); return new_s; } /* * SSL_get_accept_stream_queue_len * ------------------------------- */ QUIC_TAKES_LOCK size_t ossl_quic_get_accept_stream_queue_len(SSL *s) { QCTX ctx; size_t v; if (!expect_quic_conn_only(s, &ctx)) return 0; qctx_lock(&ctx); v = ossl_quic_stream_map_get_total_accept_queue_len(ossl_quic_channel_get_qsm(ctx.qc->ch)); qctx_unlock(&ctx); return v; } /* * SSL_stream_reset * ---------------- */ int ossl_quic_stream_reset(SSL *ssl, const SSL_STREAM_RESET_ARGS *args, size_t args_len) { QCTX ctx; QUIC_STREAM_MAP *qsm; QUIC_STREAM *qs; uint64_t error_code; int ok, err; if (!expect_quic_with_stream_lock(ssl, /*remote_init=*/0, /*io=*/0, &ctx)) return 0; qsm = ossl_quic_channel_get_qsm(ctx.qc->ch); qs = ctx.xso->stream; error_code = (args != NULL ? args->quic_error_code : 0); if (!quic_validate_for_write(ctx.xso, &err)) { ok = QUIC_RAISE_NON_NORMAL_ERROR(&ctx, err, NULL); goto err; } ok = ossl_quic_stream_map_reset_stream_send_part(qsm, qs, error_code); if (ok) ctx.xso->requested_reset = 1; err: qctx_unlock(&ctx); return ok; } /* * SSL_get_stream_read_state * ------------------------- */ static void quic_classify_stream(QUIC_CONNECTION *qc, QUIC_STREAM *qs, int is_write, int *state, uint64_t *app_error_code) { int local_init; uint64_t final_size; local_init = (ossl_quic_stream_is_server_init(qs) == qc->as_server); if (app_error_code != NULL) *app_error_code = UINT64_MAX; else app_error_code = &final_size; /* throw away value */ if (!ossl_quic_stream_is_bidi(qs) && local_init != is_write) { /* * Unidirectional stream and this direction of transmission doesn't * exist. */ *state = SSL_STREAM_STATE_WRONG_DIR; } else if (ossl_quic_channel_is_term_any(qc->ch)) { /* Connection already closed. */ *state = SSL_STREAM_STATE_CONN_CLOSED; } else if (!is_write && qs->recv_state == QUIC_RSTREAM_STATE_DATA_READ) { /* Application has read a FIN. */ *state = SSL_STREAM_STATE_FINISHED; } else if ((!is_write && qs->stop_sending) || (is_write && ossl_quic_stream_send_is_reset(qs))) { /* * Stream has been reset locally. FIN takes precedence over this for the * read case as the application need not care if the stream is reset * after a FIN has been successfully processed. */ *state = SSL_STREAM_STATE_RESET_LOCAL; *app_error_code = !is_write ? qs->stop_sending_aec : qs->reset_stream_aec; } else if ((!is_write && ossl_quic_stream_recv_is_reset(qs)) || (is_write && qs->peer_stop_sending)) { /* * Stream has been reset remotely. */ *state = SSL_STREAM_STATE_RESET_REMOTE; *app_error_code = !is_write ? qs->peer_reset_stream_aec : qs->peer_stop_sending_aec; } else if (is_write && ossl_quic_sstream_get_final_size(qs->sstream, &final_size)) { /* * Stream has been finished. Stream reset takes precedence over this for * the write case as peer may not have received all data. */ *state = SSL_STREAM_STATE_FINISHED; } else { /* Stream still healthy. */ *state = SSL_STREAM_STATE_OK; } } static int quic_get_stream_state(SSL *ssl, int is_write) { QCTX ctx; int state; if (!expect_quic_with_stream_lock(ssl, /*remote_init=*/-1, /*io=*/0, &ctx)) return SSL_STREAM_STATE_NONE; quic_classify_stream(ctx.qc, ctx.xso->stream, is_write, &state, NULL); qctx_unlock(&ctx); return state; } int ossl_quic_get_stream_read_state(SSL *ssl) { return quic_get_stream_state(ssl, /*is_write=*/0); } /* * SSL_get_stream_write_state * -------------------------- */ int ossl_quic_get_stream_write_state(SSL *ssl) { return quic_get_stream_state(ssl, /*is_write=*/1); } /* * SSL_get_stream_read_error_code * ------------------------------ */ static int quic_get_stream_error_code(SSL *ssl, int is_write, uint64_t *app_error_code) { QCTX ctx; int state; if (!expect_quic_with_stream_lock(ssl, /*remote_init=*/-1, /*io=*/0, &ctx)) return -1; quic_classify_stream(ctx.qc, ctx.xso->stream, /*is_write=*/0, &state, app_error_code); qctx_unlock(&ctx); switch (state) { case SSL_STREAM_STATE_FINISHED: return 0; case SSL_STREAM_STATE_RESET_LOCAL: case SSL_STREAM_STATE_RESET_REMOTE: return 1; default: return -1; } } int ossl_quic_get_stream_read_error_code(SSL *ssl, uint64_t *app_error_code) { return quic_get_stream_error_code(ssl, /*is_write=*/0, app_error_code); } /* * SSL_get_stream_write_error_code * ------------------------------- */ int ossl_quic_get_stream_write_error_code(SSL *ssl, uint64_t *app_error_code) { return quic_get_stream_error_code(ssl, /*is_write=*/1, app_error_code); } /* * Write buffer size mutation * -------------------------- */ int ossl_quic_set_write_buffer_size(SSL *ssl, size_t size) { int ret = 0; QCTX ctx; if (!expect_quic_with_stream_lock(ssl, /*remote_init=*/-1, /*io=*/0, &ctx)) return 0; if (!ossl_quic_stream_has_send(ctx.xso->stream)) { /* Called on a unidirectional receive-only stream - error. */ QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED, NULL); goto out; } if (!ossl_quic_stream_has_send_buffer(ctx.xso->stream)) { /* * If the stream has a send part but we have disposed of it because we * no longer need it, this is a no-op. */ ret = 1; goto out; } if (!ossl_quic_sstream_set_buffer_size(ctx.xso->stream->sstream, size)) { QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_INTERNAL_ERROR, NULL); goto out; } ret = 1; out: qctx_unlock(&ctx); return ret; } /* * SSL_get_conn_close_info * ----------------------- */ int ossl_quic_get_conn_close_info(SSL *ssl, SSL_CONN_CLOSE_INFO *info, size_t info_len) { QCTX ctx; const QUIC_TERMINATE_CAUSE *tc; if (!expect_quic_conn_only(ssl, &ctx)) return -1; tc = ossl_quic_channel_get_terminate_cause(ctx.qc->ch); if (tc == NULL) return 0; info->error_code = tc->error_code; info->frame_type = tc->frame_type; info->reason = tc->reason; info->reason_len = tc->reason_len; info->flags = 0; if (!tc->remote) info->flags |= SSL_CONN_CLOSE_FLAG_LOCAL; if (!tc->app) info->flags |= SSL_CONN_CLOSE_FLAG_TRANSPORT; return 1; } /* * SSL_key_update * -------------- */ int ossl_quic_key_update(SSL *ssl, int update_type) { QCTX ctx; if (!expect_quic_conn_only(ssl, &ctx)) return 0; switch (update_type) { case SSL_KEY_UPDATE_NOT_REQUESTED: /* * QUIC signals peer key update implicily by triggering a local * spontaneous TXKU. Silently upgrade this to SSL_KEY_UPDATE_REQUESTED. */ case SSL_KEY_UPDATE_REQUESTED: break; default: QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_PASSED_INVALID_ARGUMENT, NULL); return 0; } qctx_lock(&ctx); /* Attempt to perform a TXKU. */ if (!ossl_quic_channel_trigger_txku(ctx.qc->ch)) { QUIC_RAISE_NON_NORMAL_ERROR(&ctx, SSL_R_TOO_MANY_KEY_UPDATES, NULL); qctx_unlock(&ctx); return 0; } qctx_unlock(&ctx); return 1; } /* * SSL_get_key_update_type * ----------------------- */ int ossl_quic_get_key_update_type(const SSL *s) { /* * We always handle key updates immediately so a key update is never * pending. */ return SSL_KEY_UPDATE_NONE; } /** * @brief Allocates an SSL object for a user from a QUIC channel. * * This function creates a new QUIC_CONNECTION object based on an incoming * connection associated with the provided QUIC_LISTENER. If the connection * creation fails, the function returns NULL. Otherwise, it returns a pointer * to the SSL object associated with the newly created connection. * * Note: This function is a registered port callback made from * ossl_quic_new_listener and ossl_quic_new_listener_from, and allows for * pre-allocation of the user_ssl object when a channel is created, rather than * when it is accepted * * @param ch Pointer to the QUIC_CHANNEL representing the incoming connection. * @param arg Pointer to a QUIC_LISTENER used to create the connection. * * @return Pointer to the SSL object on success, or NULL on failure. */ static SSL *alloc_port_user_ssl(QUIC_CHANNEL *ch, void *arg) { QUIC_LISTENER *ql = arg; QUIC_CONNECTION *qc = create_qc_from_incoming_conn(ql, ch); return (qc == NULL) ? NULL : &qc->obj.ssl; } /* * QUIC Front-End I/O API: Listeners * ================================= */ /* * SSL_new_listener * ---------------- */ SSL *ossl_quic_new_listener(SSL_CTX *ctx, uint64_t flags) { QUIC_LISTENER *ql = NULL; QUIC_ENGINE_ARGS engine_args = {0}; QUIC_PORT_ARGS port_args = {0}; if ((ql = OPENSSL_zalloc(sizeof(*ql))) == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_CRYPTO_LIB, NULL); goto err; } #if defined(OPENSSL_THREADS) if ((ql->mutex = ossl_crypto_mutex_new()) == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_CRYPTO_LIB, NULL); goto err; } #endif engine_args.libctx = ctx->libctx; engine_args.propq = ctx->propq; #if defined(OPENSSL_THREADS) engine_args.mutex = ql->mutex; #endif if (need_notifier_for_domain_flags(ctx->domain_flags)) engine_args.reactor_flags |= QUIC_REACTOR_FLAG_USE_NOTIFIER; if ((ql->engine = ossl_quic_engine_new(&engine_args)) == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL); goto err; } port_args.channel_ctx = ctx; port_args.is_multi_conn = 1; port_args.get_conn_user_ssl = alloc_port_user_ssl; port_args.user_ssl_arg = ql; if ((flags & SSL_LISTENER_FLAG_NO_VALIDATE) == 0) port_args.do_addr_validation = 1; ql->port = ossl_quic_engine_create_port(ql->engine, &port_args); if (ql->port == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL); goto err; } /* TODO(QUIC FUTURE): Implement SSL_LISTENER_FLAG_NO_ACCEPT */ ossl_quic_port_set_allow_incoming(ql->port, 1); /* Initialise the QUIC_LISTENER's object header. */ if (!ossl_quic_obj_init(&ql->obj, ctx, SSL_TYPE_QUIC_LISTENER, NULL, ql->engine, ql->port)) goto err; return &ql->obj.ssl; err: if (ql != NULL) ossl_quic_engine_free(ql->engine); #if defined(OPENSSL_THREADS) ossl_crypto_mutex_free(&ql->mutex); #endif OPENSSL_free(ql); return NULL; } /* * SSL_new_listener_from * --------------------- */ SSL *ossl_quic_new_listener_from(SSL *ssl, uint64_t flags) { QCTX ctx; QUIC_LISTENER *ql = NULL; QUIC_PORT_ARGS port_args = {0}; if (!expect_quic_domain(ssl, &ctx)) return NULL; if (!SSL_up_ref(&ctx.qd->obj.ssl)) return NULL; qctx_lock(&ctx); if ((ql = OPENSSL_zalloc(sizeof(*ql))) == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_CRYPTO_LIB, NULL); goto err; } port_args.channel_ctx = ssl->ctx; port_args.is_multi_conn = 1; port_args.get_conn_user_ssl = alloc_port_user_ssl; port_args.user_ssl_arg = ql; if ((flags & SSL_LISTENER_FLAG_NO_VALIDATE) == 0) port_args.do_addr_validation = 1; ql->port = ossl_quic_engine_create_port(ctx.qd->engine, &port_args); if (ql->port == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL); goto err; } ql->domain = ctx.qd; ql->engine = ctx.qd->engine; #if defined(OPENSSL_THREADS) ql->mutex = ctx.qd->mutex; #endif /* * TODO(QUIC FUTURE): Implement SSL_LISTENER_FLAG_NO_ACCEPT * Given that we have apis to create client SSL objects from * server SSL objects (see SSL_new_from_listener), we have aspirations * to enable a flag that allows for the creation of the latter, but not * be used to do accept any connections. This is a placeholder for the * implementation of that flag */ ossl_quic_port_set_allow_incoming(ql->port, 1); /* Initialise the QUIC_LISTENER's object header. */ if (!ossl_quic_obj_init(&ql->obj, ssl->ctx, SSL_TYPE_QUIC_LISTENER, &ctx.qd->obj.ssl, NULL, ql->port)) goto err; qctx_unlock(&ctx); return &ql->obj.ssl; err: if (ql != NULL) ossl_quic_port_free(ql->port); OPENSSL_free(ql); qctx_unlock(&ctx); SSL_free(&ctx.qd->obj.ssl); return NULL; } /* * SSL_new_from_listener * --------------------- * code here is derived from ossl_quic_new(). The `ssl` argument is * a listener object which already comes with QUIC port/engine. The newly * created QUIC connection object (QCSO) is going to share the port/engine * with listener (`ssl`). The `ssl` also becomes a parent of QCSO created * by this function. The caller uses QCSO instance to connect to * remote QUIC server. * * The QCSO created here requires us to also create a channel so we * can connect to remote server. */ SSL *ossl_quic_new_from_listener(SSL *ssl, uint64_t flags) { QCTX ctx; QUIC_CONNECTION *qc = NULL; QUIC_LISTENER *ql; SSL_CONNECTION *sc = NULL; if (flags != 0) return NULL; if (!expect_quic_listener(ssl, &ctx)) return NULL; if (!SSL_up_ref(&ctx.ql->obj.ssl)) return NULL; qctx_lock(&ctx); ql = ctx.ql; /* * listeners (server) contexts don't typically * allocate a token cache because they don't need * to store them, but here we are using a server side * ctx as a client, so we should allocate one now */ if (ssl->ctx->tokencache == NULL) if ((ssl->ctx->tokencache = ossl_quic_new_token_store()) == NULL) goto err; if ((qc = OPENSSL_zalloc(sizeof(*qc))) == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_CRYPTO_LIB, NULL); goto err; } /* * NOTE: setting a listener here is needed so `qc_cleanup()` does the right * thing. Setting listener to ql avoids premature destruction of port in * qc_cleanup() */ qc->listener = ql; qc->engine = ql->engine; qc->port = ql->port; /* create channel */ #if defined(OPENSSL_THREADS) /* this is the engine mutex */ qc->mutex = ql->mutex; #endif #if !defined(OPENSSL_NO_QUIC_THREAD_ASSIST) qc->is_thread_assisted = ((ql->obj.domain_flags & SSL_DOMAIN_FLAG_THREAD_ASSISTED) != 0); #endif /* Create the handshake layer. */ qc->tls = ossl_ssl_connection_new_int(ql->obj.ssl.ctx, NULL, TLS_method()); if (qc->tls == NULL || (sc = SSL_CONNECTION_FROM_SSL(qc->tls)) == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL); goto err; } sc->s3.flags |= TLS1_FLAGS_QUIC | TLS1_FLAGS_QUIC_INTERNAL; qc->default_ssl_options = OSSL_QUIC_PERMITTED_OPTIONS; qc->last_error = SSL_ERROR_NONE; /* * This is QCSO, we don't expect to accept connections * on success the channel assumes ownership of tls, we need * to grab reference for qc. */ qc->ch = ossl_quic_port_create_outgoing(qc->port, qc->tls); ossl_quic_channel_set_msg_callback(qc->ch, ql->obj.ssl.ctx->msg_callback, &qc->obj.ssl); ossl_quic_channel_set_msg_callback_arg(qc->ch, ql->obj.ssl.ctx->msg_callback_arg); /* * We deliberately pass NULL for engine and port, because we don't want to * to turn QCSO we create here into an event leader, nor port leader. * Both those roles are occupied already by listener (`ssl`) we use * to create a new QCSO here. */ if (!ossl_quic_obj_init(&qc->obj, ql->obj.ssl.ctx, SSL_TYPE_QUIC_CONNECTION, &ql->obj.ssl, NULL, NULL)) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL); goto err; } /* Initialise libssl APL-related state. */ qc->default_stream_mode = SSL_DEFAULT_STREAM_MODE_AUTO_BIDI; qc->default_ssl_mode = qc->obj.ssl.ctx->mode; qc->default_ssl_options = qc->obj.ssl.ctx->options & OSSL_QUIC_PERMITTED_OPTIONS; qc->incoming_stream_policy = SSL_INCOMING_STREAM_POLICY_AUTO; qc->last_error = SSL_ERROR_NONE; qc_update_reject_policy(qc); qctx_unlock(&ctx); return &qc->obj.ssl; err: if (qc != NULL) { qc_cleanup(qc, /* have_lock= */ 0); OPENSSL_free(qc); } qctx_unlock(&ctx); SSL_free(&ctx.ql->obj.ssl); return NULL; } /* * SSL_listen * ---------- */ QUIC_NEEDS_LOCK static int ql_listen(QUIC_LISTENER *ql) { if (ql->listening) return 1; ossl_quic_port_set_allow_incoming(ql->port, 1); ql->listening = 1; return 1; } QUIC_TAKES_LOCK int ossl_quic_listen(SSL *ssl) { QCTX ctx; int ret; if (!expect_quic_listener(ssl, &ctx)) return 0; qctx_lock_for_io(&ctx); ret = ql_listen(ctx.ql); qctx_unlock(&ctx); return ret; } /* * SSL_accept_connection * --------------------- */ static int quic_accept_connection_wait(void *arg) { QUIC_PORT *port = arg; if (!ossl_quic_port_is_running(port)) return -1; if (ossl_quic_port_have_incoming(port)) return 1; return 0; } QUIC_TAKES_LOCK SSL *ossl_quic_accept_connection(SSL *ssl, uint64_t flags) { int ret; QCTX ctx; SSL *conn_ssl = NULL; SSL_CONNECTION *conn = NULL; QUIC_CHANNEL *new_ch = NULL; QUIC_CONNECTION *qc; int no_block = ((flags & SSL_ACCEPT_CONNECTION_NO_BLOCK) != 0); if (!expect_quic_listener(ssl, &ctx)) return NULL; qctx_lock_for_io(&ctx); if (!ql_listen(ctx.ql)) goto out; /* Wait for an incoming connection if needed. */ new_ch = ossl_quic_port_pop_incoming(ctx.ql->port); if (new_ch == NULL && ossl_quic_port_is_running(ctx.ql->port)) { if (!no_block && qctx_blocking(&ctx)) { ret = block_until_pred(&ctx, quic_accept_connection_wait, ctx.ql->port, 0); if (ret < 1) goto out; } else { qctx_maybe_autotick(&ctx); } if (!ossl_quic_port_is_running(ctx.ql->port)) goto out; new_ch = ossl_quic_port_pop_incoming(ctx.ql->port); } if (new_ch == NULL && ossl_quic_port_is_running(ctx.ql->port)) { /* No connections already queued. */ ossl_quic_reactor_tick(ossl_quic_engine_get0_reactor(ctx.ql->engine), 0); new_ch = ossl_quic_port_pop_incoming(ctx.ql->port); } /* * port_make_channel pre-allocates our user_ssl for us for each newly * created channel, so once we pop the new channel from the port above * we just need to extract it */ if (new_ch == NULL || (conn_ssl = ossl_quic_channel_get0_tls(new_ch)) == NULL || (conn = SSL_CONNECTION_FROM_SSL(conn_ssl)) == NULL || (conn_ssl = SSL_CONNECTION_GET_USER_SSL(conn)) == NULL) goto out; qc = (QUIC_CONNECTION *)conn_ssl; qc->listener = ctx.ql; qc->pending = 0; if (!SSL_up_ref(&ctx.ql->obj.ssl)) { SSL_free(conn_ssl); SSL_free(ossl_quic_channel_get0_tls(new_ch)); conn_ssl = NULL; } out: qctx_unlock(&ctx); return conn_ssl; } static QUIC_CONNECTION *create_qc_from_incoming_conn(QUIC_LISTENER *ql, QUIC_CHANNEL *ch) { QUIC_CONNECTION *qc = NULL; if ((qc = OPENSSL_zalloc(sizeof(*qc))) == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_CRYPTO_LIB, NULL); goto err; } if (!ossl_quic_obj_init(&qc->obj, ql->obj.ssl.ctx, SSL_TYPE_QUIC_CONNECTION, &ql->obj.ssl, NULL, NULL)) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL); goto err; } ossl_quic_channel_get_peer_addr(ch, &qc->init_peer_addr); /* best effort */ qc->pending = 1; qc->engine = ql->engine; qc->port = ql->port; qc->ch = ch; #if defined(OPENSSL_THREADS) qc->mutex = ql->mutex; #endif qc->tls = ossl_quic_channel_get0_tls(ch); qc->started = 1; qc->as_server = 1; qc->as_server_state = 1; qc->default_stream_mode = SSL_DEFAULT_STREAM_MODE_AUTO_BIDI; qc->default_ssl_options = ql->obj.ssl.ctx->options & OSSL_QUIC_PERMITTED_OPTIONS; qc->incoming_stream_policy = SSL_INCOMING_STREAM_POLICY_AUTO; qc->last_error = SSL_ERROR_NONE; qc_update_reject_policy(qc); return qc; err: OPENSSL_free(qc); return NULL; } DEFINE_LHASH_OF_EX(QUIC_TOKEN); struct ssl_token_store_st { LHASH_OF(QUIC_TOKEN) *cache; CRYPTO_REF_COUNT references; CRYPTO_MUTEX *mutex; }; static unsigned long quic_token_hash(const QUIC_TOKEN *item) { return (unsigned long)ossl_fnv1a_hash(item->hashkey, item->hashkey_len); } static int quic_token_cmp(const QUIC_TOKEN *a, const QUIC_TOKEN *b) { if (a->hashkey_len != b->hashkey_len) return 1; return memcmp(a->hashkey, b->hashkey, a->hashkey_len); } SSL_TOKEN_STORE *ossl_quic_new_token_store(void) { int ok = 0; SSL_TOKEN_STORE *newcache = OPENSSL_zalloc(sizeof(SSL_TOKEN_STORE)); if (newcache == NULL) goto out; newcache->cache = lh_QUIC_TOKEN_new(quic_token_hash, quic_token_cmp); if (newcache->cache == NULL) goto out; #if defined(OPENSSL_THREADS) if ((newcache->mutex = ossl_crypto_mutex_new()) == NULL) goto out; #endif if (!CRYPTO_NEW_REF(&newcache->references, 1)) goto out; ok = 1; out: if (!ok) { ossl_quic_free_token_store(newcache); newcache = NULL; } return newcache; } static void free_this_token(QUIC_TOKEN *tok) { ossl_quic_free_peer_token(tok); } void ossl_quic_free_token_store(SSL_TOKEN_STORE *hdl) { int refs; if (hdl == NULL) return; if (!CRYPTO_DOWN_REF(&hdl->references, &refs)) return; if (refs > 0) return; /* last reference, we can clean up */ ossl_crypto_mutex_free(&hdl->mutex); lh_QUIC_TOKEN_doall(hdl->cache, free_this_token); lh_QUIC_TOKEN_free(hdl->cache); CRYPTO_FREE_REF(&hdl->references); OPENSSL_free(hdl); return; } /** * @brief build a new QUIC_TOKEN * * This function creates a new token storage structure for saving in our * tokencache * * In an effort to make allocation and freeing of these tokens a bit faster * We do them in a single allocation in this format * +---------------+ --\ * | hashkey * |---| | * | hashkey_len | | | QUIC_TOKEN * | token * |---|--| | * | token_len | | | | * +---------------+<--| | --/ * | hashkey buf | | * | | | * |---------------|<-----| * | token buf | * | | * +---------------+ * * @param peer - the peer address that sent the token * @param token - the buffer holding the token * @param token_len - the size of token * * @returns a QUIC_TOKEN pointer or NULL on error */ static QUIC_TOKEN *ossl_quic_build_new_token(BIO_ADDR *peer, uint8_t *token, size_t token_len) { QUIC_TOKEN *new_token; size_t hashkey_len = 0; size_t addr_len = 0; int family; unsigned short port; int *famptr; unsigned short *portptr; uint8_t *addrptr; if ((token != NULL && token_len == 0) || (token == NULL && token_len != 0)) return NULL; if (!BIO_ADDR_rawaddress(peer, NULL, &addr_len)) return NULL; family = BIO_ADDR_family(peer); port = BIO_ADDR_rawport(peer); hashkey_len += sizeof(int); /* hashkey(family) */ hashkey_len += sizeof(unsigned short); /* hashkey(port) */ hashkey_len += addr_len; /* hashkey(address) */ new_token = OPENSSL_zalloc(sizeof(QUIC_TOKEN) + hashkey_len + token_len); if (new_token == NULL) return NULL; if (!CRYPTO_NEW_REF(&new_token->references, 1)) { OPENSSL_free(new_token); return NULL; } new_token->hashkey_len = hashkey_len; /* hashkey is allocated inline, immediately after the QUIC_TOKEN struct */ new_token->hashkey = (uint8_t *)(new_token + 1); /* token buffer follows the hashkey in the inline allocation */ new_token->token = new_token->hashkey + hashkey_len; new_token->token_len = token_len; famptr = (int *)new_token->hashkey; portptr = (unsigned short *)(famptr + 1); addrptr = (uint8_t *)(portptr + 1); *famptr = family; *portptr = port; if (!BIO_ADDR_rawaddress(peer, addrptr, NULL)) { ossl_quic_free_peer_token(new_token); return NULL; } if (token != NULL) memcpy(new_token->token, token, token_len); return new_token; } int ossl_quic_set_peer_token(SSL_CTX *ctx, BIO_ADDR *peer, const uint8_t *token, size_t token_len) { SSL_TOKEN_STORE *c = ctx->tokencache; QUIC_TOKEN *tok, *old = NULL; if (ctx->tokencache == NULL) return 0; tok = ossl_quic_build_new_token(peer, (uint8_t *)token, token_len); if (tok == NULL) return 0; /* we might be sharing this cache, lock it */ ossl_crypto_mutex_lock(c->mutex); old = lh_QUIC_TOKEN_retrieve(c->cache, tok); if (old != NULL) { lh_QUIC_TOKEN_delete(c->cache, old); ossl_quic_free_peer_token(old); } lh_QUIC_TOKEN_insert(c->cache, tok); ossl_crypto_mutex_unlock(c->mutex); return 1; } int ossl_quic_get_peer_token(SSL_CTX *ctx, BIO_ADDR *peer, QUIC_TOKEN **token) { SSL_TOKEN_STORE *c = ctx->tokencache; QUIC_TOKEN *key = NULL; QUIC_TOKEN *tok = NULL; int ret; int rc = 0; if (c == NULL) return 0; key = ossl_quic_build_new_token(peer, NULL, 0); if (key == NULL) return 0; ossl_crypto_mutex_lock(c->mutex); tok = lh_QUIC_TOKEN_retrieve(c->cache, key); if (tok != NULL) { *token = tok; CRYPTO_UP_REF(&tok->references, &ret); rc = 1; } ossl_crypto_mutex_unlock(c->mutex); ossl_quic_free_peer_token(key); return rc; } void ossl_quic_free_peer_token(QUIC_TOKEN *token) { int refs = 0; if (!CRYPTO_DOWN_REF(&token->references, &refs)) return; if (refs > 0) return; CRYPTO_FREE_REF(&token->references); OPENSSL_free(token); } /* * SSL_get_accept_connection_queue_len * ----------------------------------- */ QUIC_TAKES_LOCK size_t ossl_quic_get_accept_connection_queue_len(SSL *ssl) { QCTX ctx; int ret; if (!expect_quic_listener(ssl, &ctx)) return 0; qctx_lock(&ctx); ret = ossl_quic_port_get_num_incoming_channels(ctx.ql->port); qctx_unlock(&ctx); return ret; } /* * QUIC Front-End I/O API: Domains * =============================== */ /* * SSL_new_domain * -------------- */ SSL *ossl_quic_new_domain(SSL_CTX *ctx, uint64_t flags) { QUIC_DOMAIN *qd = NULL; QUIC_ENGINE_ARGS engine_args = {0}; uint64_t domain_flags; domain_flags = ctx->domain_flags; if ((flags & (SSL_DOMAIN_FLAG_SINGLE_THREAD | SSL_DOMAIN_FLAG_MULTI_THREAD | SSL_DOMAIN_FLAG_THREAD_ASSISTED)) != 0) domain_flags = flags; else domain_flags = ctx->domain_flags | flags; if (!ossl_adjust_domain_flags(domain_flags, &domain_flags)) return NULL; if ((qd = OPENSSL_zalloc(sizeof(*qd))) == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_CRYPTO_LIB, NULL); return NULL; } #if defined(OPENSSL_THREADS) if ((qd->mutex = ossl_crypto_mutex_new()) == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_CRYPTO_LIB, NULL); goto err; } #endif engine_args.libctx = ctx->libctx; engine_args.propq = ctx->propq; #if defined(OPENSSL_THREADS) engine_args.mutex = qd->mutex; #endif if (need_notifier_for_domain_flags(domain_flags)) engine_args.reactor_flags |= QUIC_REACTOR_FLAG_USE_NOTIFIER; if ((qd->engine = ossl_quic_engine_new(&engine_args)) == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL); goto err; } /* Initialise the QUIC_DOMAIN's object header. */ if (!ossl_quic_obj_init(&qd->obj, ctx, SSL_TYPE_QUIC_DOMAIN, NULL, qd->engine, NULL)) goto err; ossl_quic_obj_set_domain_flags(&qd->obj, domain_flags); return &qd->obj.ssl; err: ossl_quic_engine_free(qd->engine); #if defined(OPENSSL_THREADS) ossl_crypto_mutex_free(&qd->mutex); #endif OPENSSL_free(qd); return NULL; } /* * QUIC Front-End I/O API: SSL_CTX Management * ========================================== */ long ossl_quic_ctx_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg) { switch (cmd) { default: return ssl3_ctx_ctrl(ctx, cmd, larg, parg); } } long ossl_quic_callback_ctrl(SSL *s, int cmd, void (*fp) (void)) { QCTX ctx; if (!expect_quic_conn_only(s, &ctx)) return 0; switch (cmd) { case SSL_CTRL_SET_MSG_CALLBACK: ossl_quic_channel_set_msg_callback(ctx.qc->ch, (ossl_msg_cb)fp, &ctx.qc->obj.ssl); /* This callback also needs to be set on the internal SSL object */ return ssl3_callback_ctrl(ctx.qc->tls, cmd, fp);; default: /* Probably a TLS related ctrl. Defer to our internal SSL object */ return ssl3_callback_ctrl(ctx.qc->tls, cmd, fp); } } long ossl_quic_ctx_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp) (void)) { return ssl3_ctx_callback_ctrl(ctx, cmd, fp); } int ossl_quic_renegotiate_check(SSL *ssl, int initok) { /* We never do renegotiation. */ return 0; } const SSL_CIPHER *ossl_quic_get_cipher_by_char(const unsigned char *p) { const SSL_CIPHER *ciph = ssl3_get_cipher_by_char(p); if ((ciph->algorithm2 & SSL_QUIC) == 0) return NULL; return ciph; } /* * These functions define the TLSv1.2 (and below) ciphers that are supported by * the SSL_METHOD. Since QUIC only supports TLSv1.3 we don't support any. */ int ossl_quic_num_ciphers(void) { return 0; } const SSL_CIPHER *ossl_quic_get_cipher(unsigned int u) { return NULL; } /* * SSL_get_shutdown() * ------------------ */ int ossl_quic_get_shutdown(const SSL *s) { QCTX ctx; int shut = 0; if (!expect_quic_conn_only(s, &ctx)) return 0; if (ossl_quic_channel_is_term_any(ctx.qc->ch)) { shut |= SSL_SENT_SHUTDOWN; if (!ossl_quic_channel_is_closing(ctx.qc->ch)) shut |= SSL_RECEIVED_SHUTDOWN; } return shut; } /* * QUIC Polling Support APIs * ========================= */ /* Do we have the R (read) condition? */ QUIC_NEEDS_LOCK static int test_poll_event_r(QUIC_XSO *xso) { int fin = 0; size_t avail = 0; /* * If a stream has had the fin bit set on the last packet * received, then we need to return a 1 here to raise * SSL_POLL_EVENT_R, so that the stream can have its completion * detected and closed gracefully by an application. * However, if the client reads the data via SSL_read[_ex], that api * provides no stream status, and as a result the stream state moves to * QUIC_RSTREAM_STATE_DATA_READ, and the receive buffer is freed, which * stored the fin state, so its not directly know-able here. Instead * check for the stream state being QUIC_RSTREAM_STATE_DATA_READ, which * is only set if the last stream frame received had the fin bit set, and * the client read the data. This catches our poll/read/poll case */ if (xso->stream->recv_state == QUIC_RSTREAM_STATE_DATA_READ) return 1; return ossl_quic_stream_has_recv_buffer(xso->stream) && ossl_quic_rstream_available(xso->stream->rstream, &avail, &fin) && (avail > 0 || (fin && !xso->retired_fin)); } /* Do we have the ER (exception: read) condition? */ QUIC_NEEDS_LOCK static int test_poll_event_er(QUIC_XSO *xso) { return ossl_quic_stream_has_recv(xso->stream) && ossl_quic_stream_recv_is_reset(xso->stream) && !xso->retired_fin; } /* Do we have the W (write) condition? */ QUIC_NEEDS_LOCK static int test_poll_event_w(QUIC_XSO *xso) { return !xso->conn->shutting_down && ossl_quic_stream_has_send_buffer(xso->stream) && ossl_quic_sstream_get_buffer_avail(xso->stream->sstream) && !ossl_quic_sstream_get_final_size(xso->stream->sstream, NULL) && ossl_quic_txfc_get_cwm(&xso->stream->txfc) > ossl_quic_sstream_get_cur_size(xso->stream->sstream) && quic_mutation_allowed(xso->conn, /*req_active=*/1); } /* Do we have the EW (exception: write) condition? */ QUIC_NEEDS_LOCK static int test_poll_event_ew(QUIC_XSO *xso) { return ossl_quic_stream_has_send(xso->stream) && xso->stream->peer_stop_sending && !xso->requested_reset && !xso->conn->shutting_down; } /* Do we have the EC (exception: connection) condition? */ QUIC_NEEDS_LOCK static int test_poll_event_ec(QUIC_CONNECTION *qc) { return ossl_quic_channel_is_term_any(qc->ch); } /* Do we have the ECD (exception: connection drained) condition? */ QUIC_NEEDS_LOCK static int test_poll_event_ecd(QUIC_CONNECTION *qc) { return ossl_quic_channel_is_terminated(qc->ch); } /* Do we have the IS (incoming: stream) condition? */ QUIC_NEEDS_LOCK static int test_poll_event_is(QUIC_CONNECTION *qc, int is_uni) { return ossl_quic_stream_map_get_accept_queue_len(ossl_quic_channel_get_qsm(qc->ch), is_uni); } /* Do we have the OS (outgoing: stream) condition? */ QUIC_NEEDS_LOCK static int test_poll_event_os(QUIC_CONNECTION *qc, int is_uni) { /* Is it currently possible for us to make an outgoing stream? */ return quic_mutation_allowed(qc, /*req_active=*/1) && ossl_quic_channel_get_local_stream_count_avail(qc->ch, is_uni) > 0; } /* Do we have the EL (exception: listener) condition? */ QUIC_NEEDS_LOCK static int test_poll_event_el(QUIC_LISTENER *ql) { return !ossl_quic_port_is_running(ql->port); } /* Do we have the IC (incoming: connection) condition? */ QUIC_NEEDS_LOCK static int test_poll_event_ic(QUIC_LISTENER *ql) { return ossl_quic_port_get_num_incoming_channels(ql->port) > 0; } QUIC_TAKES_LOCK int ossl_quic_conn_poll_events(SSL *ssl, uint64_t events, int do_tick, uint64_t *p_revents) { QCTX ctx; uint64_t revents = 0; if (!expect_quic_csl(ssl, &ctx)) return 0; qctx_lock(&ctx); if (ctx.qc != NULL && !ctx.qc->started) { /* We can only try to write on non-started connection. */ if ((events & SSL_POLL_EVENT_W) != 0) revents |= SSL_POLL_EVENT_W; goto end; } if (do_tick) ossl_quic_reactor_tick(ossl_quic_obj_get0_reactor(ctx.obj), 0); if (ctx.xso != NULL) { /* SSL object has a stream component. */ if ((events & SSL_POLL_EVENT_R) != 0 && test_poll_event_r(ctx.xso)) revents |= SSL_POLL_EVENT_R; if ((events & SSL_POLL_EVENT_ER) != 0 && test_poll_event_er(ctx.xso)) revents |= SSL_POLL_EVENT_ER; if ((events & SSL_POLL_EVENT_W) != 0 && test_poll_event_w(ctx.xso)) revents |= SSL_POLL_EVENT_W; if ((events & SSL_POLL_EVENT_EW) != 0 && test_poll_event_ew(ctx.xso)) revents |= SSL_POLL_EVENT_EW; } if (ctx.qc != NULL && !ctx.is_stream) { if ((events & SSL_POLL_EVENT_EC) != 0 && test_poll_event_ec(ctx.qc)) revents |= SSL_POLL_EVENT_EC; if ((events & SSL_POLL_EVENT_ECD) != 0 && test_poll_event_ecd(ctx.qc)) revents |= SSL_POLL_EVENT_ECD; if ((events & SSL_POLL_EVENT_ISB) != 0 && test_poll_event_is(ctx.qc, /*uni=*/0)) revents |= SSL_POLL_EVENT_ISB; if ((events & SSL_POLL_EVENT_ISU) != 0 && test_poll_event_is(ctx.qc, /*uni=*/1)) revents |= SSL_POLL_EVENT_ISU; if ((events & SSL_POLL_EVENT_OSB) != 0 && test_poll_event_os(ctx.qc, /*uni=*/0)) revents |= SSL_POLL_EVENT_OSB; if ((events & SSL_POLL_EVENT_OSU) != 0 && test_poll_event_os(ctx.qc, /*uni=*/1)) revents |= SSL_POLL_EVENT_OSU; } if (ctx.is_listener) { if ((events & SSL_POLL_EVENT_EL) != 0 && test_poll_event_el(ctx.ql)) revents |= SSL_POLL_EVENT_EL; if ((events & SSL_POLL_EVENT_IC) != 0 && test_poll_event_ic(ctx.ql)) revents |= SSL_POLL_EVENT_IC; } end: qctx_unlock(&ctx); *p_revents = revents; return 1; } QUIC_TAKES_LOCK int ossl_quic_get_notifier_fd(SSL *ssl) { QCTX ctx; QUIC_REACTOR *rtor; RIO_NOTIFIER *nfy; int nfd = -1; if (!expect_quic_any(ssl, &ctx)) return -1; qctx_lock(&ctx); rtor = ossl_quic_obj_get0_reactor(ctx.obj); nfy = ossl_quic_reactor_get0_notifier(rtor); if (nfy == NULL) goto end; nfd = ossl_rio_notifier_as_fd(nfy); end: qctx_unlock(&ctx); return nfd; } QUIC_TAKES_LOCK void ossl_quic_enter_blocking_section(SSL *ssl, QUIC_REACTOR_WAIT_CTX *wctx) { QCTX ctx; QUIC_REACTOR *rtor; if (!expect_quic_any(ssl, &ctx)) return; qctx_lock(&ctx); rtor = ossl_quic_obj_get0_reactor(ctx.obj); ossl_quic_reactor_wait_ctx_enter(wctx, rtor); qctx_unlock(&ctx); } QUIC_TAKES_LOCK void ossl_quic_leave_blocking_section(SSL *ssl, QUIC_REACTOR_WAIT_CTX *wctx) { QCTX ctx; QUIC_REACTOR *rtor; if (!expect_quic_any(ssl, &ctx)) return; qctx_lock(&ctx); rtor = ossl_quic_obj_get0_reactor(ctx.obj); ossl_quic_reactor_wait_ctx_leave(wctx, rtor); qctx_unlock(&ctx); } /* * Internal Testing APIs * ===================== */ QUIC_CHANNEL *ossl_quic_conn_get_channel(SSL *s) { QCTX ctx; if (!expect_quic_conn_only(s, &ctx)) return NULL; return ctx.qc->ch; } int ossl_quic_set_diag_title(SSL_CTX *ctx, const char *title) { #ifndef OPENSSL_NO_QLOG OPENSSL_free(ctx->qlog_title); ctx->qlog_title = NULL; if (title == NULL) return 1; if ((ctx->qlog_title = OPENSSL_strdup(title)) == NULL) return 0; #endif return 1; } diff --git a/ssl/record/methods/tls_common.c b/ssl/record/methods/tls_common.c index 80d4477bd0c0..b9c79099462d 100644 --- a/ssl/record/methods/tls_common.c +++ b/ssl/record/methods/tls_common.c @@ -1,2184 +1,2187 @@ /* - * Copyright 2022-2024 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2022-2025 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 "internal/e_os.h" #include "internal/packet.h" #include "internal/ssl3_cbc.h" #include "../../ssl_local.h" #include "../record_local.h" #include "recmethod_local.h" static void tls_int_free(OSSL_RECORD_LAYER *rl); void ossl_tls_buffer_release(TLS_BUFFER *b) { OPENSSL_free(b->buf); b->buf = NULL; } static void TLS_RL_RECORD_release(TLS_RL_RECORD *r, size_t num_recs) { size_t i; for (i = 0; i < num_recs; i++) { OPENSSL_free(r[i].comp); r[i].comp = NULL; } } void ossl_tls_rl_record_set_seq_num(TLS_RL_RECORD *r, const unsigned char *seq_num) { memcpy(r->seq_num, seq_num, SEQ_NUM_SIZE); } void ossl_rlayer_fatal(OSSL_RECORD_LAYER *rl, int al, int reason, const char *fmt, ...) { va_list args; va_start(args, fmt); ERR_vset_error(ERR_LIB_SSL, reason, fmt, args); va_end(args); rl->alert = al; } int ossl_set_tls_provider_parameters(OSSL_RECORD_LAYER *rl, EVP_CIPHER_CTX *ctx, const EVP_CIPHER *ciph, const EVP_MD *md) { /* * Provided cipher, the TLS padding/MAC removal is performed provider * side so we need to tell the ctx about our TLS version and mac size */ OSSL_PARAM params[3], *pprm = params; size_t macsize = 0; int imacsize = -1; if ((EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0 && !rl->use_etm) imacsize = EVP_MD_get_size(md); if (imacsize > 0) macsize = (size_t)imacsize; *pprm++ = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_TLS_VERSION, &rl->version); *pprm++ = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_TLS_MAC_SIZE, &macsize); *pprm = OSSL_PARAM_construct_end(); if (!EVP_CIPHER_CTX_set_params(ctx, params)) { ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR); return 0; } return 1; } /* * ssl3_cbc_record_digest_supported returns 1 iff |ctx| uses a hash function * which ssl3_cbc_digest_record supports. */ char ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx) { switch (EVP_MD_CTX_get_type(ctx)) { case NID_md5: case NID_sha1: case NID_sha224: case NID_sha256: case NID_sha384: case NID_sha512: return 1; default: return 0; } } #ifndef OPENSSL_NO_COMP static int tls_allow_compression(OSSL_RECORD_LAYER *rl) { if (rl->options & SSL_OP_NO_COMPRESSION) return 0; return rl->security == NULL || rl->security(rl->cbarg, SSL_SECOP_COMPRESSION, 0, 0, NULL); } #endif static void tls_release_write_buffer_int(OSSL_RECORD_LAYER *rl, size_t start) { TLS_BUFFER *wb; size_t pipes; pipes = rl->numwpipes; while (pipes > start) { wb = &rl->wbuf[pipes - 1]; if (TLS_BUFFER_is_app_buffer(wb)) TLS_BUFFER_set_app_buffer(wb, 0); else OPENSSL_free(wb->buf); wb->buf = NULL; pipes--; } } int tls_setup_write_buffer(OSSL_RECORD_LAYER *rl, size_t numwpipes, size_t firstlen, size_t nextlen) { unsigned char *p; size_t maxalign = 0, headerlen; TLS_BUFFER *wb; size_t currpipe; size_t defltlen = 0; size_t contenttypelen = 0; if (firstlen == 0 || (numwpipes > 1 && nextlen == 0)) { if (rl->isdtls) headerlen = DTLS1_RT_HEADER_LENGTH + 1; else headerlen = SSL3_RT_HEADER_LENGTH; /* TLSv1.3 adds an extra content type byte after payload data */ if (rl->version == TLS1_3_VERSION) contenttypelen = 1; #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0 maxalign = SSL3_ALIGN_PAYLOAD - 1; #endif defltlen = maxalign + headerlen + rl->eivlen + rl->max_frag_len + contenttypelen + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD; #ifndef OPENSSL_NO_COMP if (tls_allow_compression(rl)) defltlen += SSL3_RT_MAX_COMPRESSED_OVERHEAD; #endif /* * We don't need to add eivlen here since empty fragments only occur * when we don't have an explicit IV. The contenttype byte will also * always be 0 in these protocol versions */ if ((rl->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) == 0) defltlen += headerlen + maxalign + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD; } wb = rl->wbuf; for (currpipe = 0; currpipe < numwpipes; currpipe++) { TLS_BUFFER *thiswb = &wb[currpipe]; size_t len = (currpipe == 0) ? firstlen : nextlen; if (len == 0) len = defltlen; if (thiswb->len != len) { OPENSSL_free(thiswb->buf); thiswb->buf = NULL; /* force reallocation */ } p = thiswb->buf; if (p == NULL) { p = OPENSSL_malloc(len); if (p == NULL) { if (rl->numwpipes < currpipe) rl->numwpipes = currpipe; /* * We've got a malloc failure, and we're still initialising * buffers. We assume we're so doomed that we won't even be able * to send an alert. */ RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_CRYPTO_LIB); return 0; } } memset(thiswb, 0, sizeof(TLS_BUFFER)); thiswb->buf = p; thiswb->len = len; } /* Free any previously allocated buffers that we are no longer using */ tls_release_write_buffer_int(rl, currpipe); rl->numwpipes = numwpipes; return 1; } static void tls_release_write_buffer(OSSL_RECORD_LAYER *rl) { tls_release_write_buffer_int(rl, 0); rl->numwpipes = 0; } int tls_setup_read_buffer(OSSL_RECORD_LAYER *rl) { unsigned char *p; size_t len, maxalign = 0, headerlen; TLS_BUFFER *b; b = &rl->rbuf; if (rl->isdtls) headerlen = DTLS1_RT_HEADER_LENGTH; else headerlen = SSL3_RT_HEADER_LENGTH; #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0 maxalign = SSL3_ALIGN_PAYLOAD - 1; #endif if (b->buf == NULL) { len = rl->max_frag_len + SSL3_RT_MAX_ENCRYPTED_OVERHEAD + headerlen + maxalign; #ifndef OPENSSL_NO_COMP if (tls_allow_compression(rl)) len += SSL3_RT_MAX_COMPRESSED_OVERHEAD; #endif /* Ensure our buffer is large enough to support all our pipelines */ if (rl->max_pipelines > 1) len *= rl->max_pipelines; if (b->default_len > len) len = b->default_len; if ((p = OPENSSL_malloc(len)) == NULL) { /* * We've got a malloc failure, and we're still initialising buffers. * We assume we're so doomed that we won't even be able to send an * alert. */ RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_CRYPTO_LIB); return 0; } b->buf = p; b->len = len; } return 1; } static int tls_release_read_buffer(OSSL_RECORD_LAYER *rl) { TLS_BUFFER *b; b = &rl->rbuf; if ((rl->options & SSL_OP_CLEANSE_PLAINTEXT) != 0) OPENSSL_cleanse(b->buf, b->len); OPENSSL_free(b->buf); b->buf = NULL; rl->packet = NULL; rl->packet_length = 0; return 1; } /* * Return values are as per SSL_read() */ int tls_default_read_n(OSSL_RECORD_LAYER *rl, size_t n, size_t max, int extend, int clearold, size_t *readbytes) { /* * If extend == 0, obtain new n-byte packet; if extend == 1, increase * packet by another n bytes. The packet will be in the sub-array of * rl->rbuf.buf specified by rl->packet and rl->packet_length. (If * rl->read_ahead is set, 'max' bytes may be stored in rbuf [plus * rl->packet_length bytes if extend == 1].) if clearold == 1, move the * packet to the start of the buffer; if clearold == 0 then leave any old * packets where they were */ size_t len, left, align = 0; unsigned char *pkt; TLS_BUFFER *rb; if (n == 0) return OSSL_RECORD_RETURN_NON_FATAL_ERR; rb = &rl->rbuf; left = rb->left; #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0 align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH; align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD); #endif if (!extend) { /* start with empty packet ... */ if (left == 0) rb->offset = align; rl->packet = rb->buf + rb->offset; rl->packet_length = 0; /* ... now we can act as if 'extend' was set */ } if (!ossl_assert(rl->packet != NULL)) { /* does not happen */ RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR); return OSSL_RECORD_RETURN_FATAL; } len = rl->packet_length; pkt = rb->buf + align; /* * Move any available bytes to front of buffer: 'len' bytes already * pointed to by 'packet', 'left' extra ones at the end */ if (rl->packet != pkt && clearold == 1) { memmove(pkt, rl->packet, len + left); rl->packet = pkt; rb->offset = len + align; } /* * For DTLS/UDP reads should not span multiple packets because the read * operation returns the whole packet at once (as long as it fits into * the buffer). */ if (rl->isdtls) { if (left == 0 && extend) { /* * We received a record with a header but no body data. This will * get dumped. */ return OSSL_RECORD_RETURN_NON_FATAL_ERR; } if (left > 0 && n > left) n = left; } /* if there is enough in the buffer from a previous read, take some */ if (left >= n) { rl->packet_length += n; rb->left = left - n; rb->offset += n; *readbytes = n; return OSSL_RECORD_RETURN_SUCCESS; } /* else we need to read more data */ if (n > rb->len - rb->offset) { /* does not happen */ RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR); return OSSL_RECORD_RETURN_FATAL; } /* We always act like read_ahead is set for DTLS */ if (!rl->read_ahead && !rl->isdtls) { /* ignore max parameter */ max = n; } else { if (max < n) max = n; if (max > rb->len - rb->offset) max = rb->len - rb->offset; } while (left < n) { size_t bioread = 0; int ret; BIO *bio = rl->prev != NULL ? rl->prev : rl->bio; /* * Now we have len+left bytes at the front of rl->rbuf.buf and * need to read in more until we have len + n (up to len + max if * possible) */ clear_sys_error(); if (bio != NULL) { ret = BIO_read(bio, pkt + len + left, max - left); if (ret > 0) { bioread = ret; ret = OSSL_RECORD_RETURN_SUCCESS; } else if (BIO_should_retry(bio)) { if (rl->prev != NULL) { /* * We were reading from the previous epoch. Now there is no * more data, so swap to the actual transport BIO */ BIO_free(rl->prev); rl->prev = NULL; continue; } ret = OSSL_RECORD_RETURN_RETRY; } else if (BIO_eof(bio)) { ret = OSSL_RECORD_RETURN_EOF; } else { ret = OSSL_RECORD_RETURN_FATAL; } } else { RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_READ_BIO_NOT_SET); ret = OSSL_RECORD_RETURN_FATAL; } if (ret <= OSSL_RECORD_RETURN_RETRY) { rb->left = left; if ((rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0 && !rl->isdtls) if (len + left == 0) tls_release_read_buffer(rl); return ret; } left += bioread; /* * reads should *never* span multiple packets for DTLS because the * underlying transport protocol is message oriented as opposed to * byte oriented as in the TLS case. */ if (rl->isdtls) { if (n > left) n = left; /* makes the while condition false */ } } /* done reading, now the book-keeping */ rb->offset += n; rb->left = left - n; rl->packet_length += n; *readbytes = n; return OSSL_RECORD_RETURN_SUCCESS; } /* * Peeks ahead into "read_ahead" data to see if we have a whole record waiting * for us in the buffer. */ static int tls_record_app_data_waiting(OSSL_RECORD_LAYER *rl) { TLS_BUFFER *rbuf; size_t left, len; unsigned char *p; rbuf = &rl->rbuf; p = TLS_BUFFER_get_buf(rbuf); if (p == NULL) return 0; left = TLS_BUFFER_get_left(rbuf); if (left < SSL3_RT_HEADER_LENGTH) return 0; p += TLS_BUFFER_get_offset(rbuf); /* * We only check the type and record length, we will sanity check version * etc later */ if (*p != SSL3_RT_APPLICATION_DATA) return 0; p += 3; n2s(p, len); if (left < SSL3_RT_HEADER_LENGTH + len) return 0; return 1; } static int rlayer_early_data_count_ok(OSSL_RECORD_LAYER *rl, size_t length, size_t overhead, int send) { uint32_t max_early_data = rl->max_early_data; if (max_early_data == 0) { RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE, SSL_R_TOO_MUCH_EARLY_DATA); return 0; } /* If we are dealing with ciphertext we need to allow for the overhead */ max_early_data += overhead; if (rl->early_data_count + length > max_early_data) { RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE, SSL_R_TOO_MUCH_EARLY_DATA); return 0; } rl->early_data_count += length; return 1; } /* * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that * will be processed per call to tls_get_more_records. Without this limit an * attacker could send empty records at a faster rate than we can process and * cause tls_get_more_records to loop forever. */ #define MAX_EMPTY_RECORDS 32 #define SSL2_RT_HEADER_LENGTH 2 /*- * Call this to buffer new input records in rl->rrec. * It will return a OSSL_RECORD_RETURN_* value. * When it finishes successfully (OSSL_RECORD_RETURN_SUCCESS), |rl->num_recs| * records have been decoded. For each record 'i': * rrec[i].type - is the type of record * rrec[i].data, - data * rrec[i].length, - number of bytes * Multiple records will only be returned if the record types are all * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <= * |max_pipelines| */ int tls_get_more_records(OSSL_RECORD_LAYER *rl) { int enc_err, rret; int i; size_t more, n; TLS_RL_RECORD *rr, *thisrr; TLS_BUFFER *rbuf; unsigned char *p; unsigned char md[EVP_MAX_MD_SIZE]; unsigned int version; size_t mac_size = 0; int imac_size; size_t num_recs = 0, max_recs, j; PACKET pkt, sslv2pkt; SSL_MAC_BUF *macbufs = NULL; int ret = OSSL_RECORD_RETURN_FATAL; rr = rl->rrec; rbuf = &rl->rbuf; if (rbuf->buf == NULL) { if (!tls_setup_read_buffer(rl)) { /* RLAYERfatal() already called */ return OSSL_RECORD_RETURN_FATAL; } } max_recs = rl->max_pipelines; if (max_recs == 0) max_recs = 1; do { thisrr = &rr[num_recs]; /* check if we have the header */ if ((rl->rstate != SSL_ST_READ_BODY) || (rl->packet_length < SSL3_RT_HEADER_LENGTH)) { size_t sslv2len; unsigned int type; rret = rl->funcs->read_n(rl, SSL3_RT_HEADER_LENGTH, TLS_BUFFER_get_len(rbuf), 0, num_recs == 0 ? 1 : 0, &n); if (rret < OSSL_RECORD_RETURN_SUCCESS) return rret; /* error or non-blocking */ rl->rstate = SSL_ST_READ_BODY; p = rl->packet; if (!PACKET_buf_init(&pkt, p, rl->packet_length)) { RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR); return OSSL_RECORD_RETURN_FATAL; } sslv2pkt = pkt; if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len) || !PACKET_get_1(&sslv2pkt, &type)) { RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR); return OSSL_RECORD_RETURN_FATAL; } /* * The first record received by the server may be a V2ClientHello. */ if (rl->role == OSSL_RECORD_ROLE_SERVER && rl->is_first_record && (sslv2len & 0x8000) != 0 && (type == SSL2_MT_CLIENT_HELLO)) { /* * SSLv2 style record * * |num_recs| here will actually always be 0 because * |num_recs > 0| only ever occurs when we are processing * multiple app data records - which we know isn't the case here * because it is an SSLv2ClientHello. We keep it using * |num_recs| for the sake of consistency */ thisrr->type = SSL3_RT_HANDSHAKE; thisrr->rec_version = SSL2_VERSION; thisrr->length = sslv2len & 0x7fff; if (thisrr->length > TLS_BUFFER_get_len(rbuf) - SSL2_RT_HEADER_LENGTH) { RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_PACKET_LENGTH_TOO_LONG); return OSSL_RECORD_RETURN_FATAL; } } else { /* SSLv3+ style record */ /* Pull apart the header into the TLS_RL_RECORD */ if (!PACKET_get_1(&pkt, &type) || !PACKET_get_net_2(&pkt, &version) || !PACKET_get_net_2_len(&pkt, &thisrr->length)) { if (rl->msg_callback != NULL) rl->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, rl->cbarg); RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR); return OSSL_RECORD_RETURN_FATAL; } thisrr->type = type; thisrr->rec_version = version; /* * When we call validate_record_header() only records actually * received in SSLv2 format should have the record version set * to SSL2_VERSION. This way validate_record_header() can know * what format the record was in based on the version. */ if (thisrr->rec_version == SSL2_VERSION) { RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_VERSION_NUMBER); return OSSL_RECORD_RETURN_FATAL; } if (rl->msg_callback != NULL) rl->msg_callback(0, version, SSL3_RT_HEADER, p, 5, rl->cbarg); if (thisrr->length > TLS_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) { RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_PACKET_LENGTH_TOO_LONG); return OSSL_RECORD_RETURN_FATAL; } } if (!rl->funcs->validate_record_header(rl, thisrr)) { /* RLAYERfatal already called */ return OSSL_RECORD_RETURN_FATAL; } /* now rl->rstate == SSL_ST_READ_BODY */ } /* * rl->rstate == SSL_ST_READ_BODY, get and decode the data. Calculate * how much more data we need to read for the rest of the record */ if (thisrr->rec_version == SSL2_VERSION) { more = thisrr->length + SSL2_RT_HEADER_LENGTH - SSL3_RT_HEADER_LENGTH; } else { more = thisrr->length; } if (more > 0) { /* now rl->packet_length == SSL3_RT_HEADER_LENGTH */ rret = rl->funcs->read_n(rl, more, more, 1, 0, &n); if (rret < OSSL_RECORD_RETURN_SUCCESS) return rret; /* error or non-blocking io */ } /* set state for later operations */ rl->rstate = SSL_ST_READ_HEADER; /* * At this point, rl->packet_length == SSL3_RT_HEADER_LENGTH * + thisrr->length, or rl->packet_length == SSL2_RT_HEADER_LENGTH * + thisrr->length and we have that many bytes in rl->packet */ if (thisrr->rec_version == SSL2_VERSION) thisrr->input = &(rl->packet[SSL2_RT_HEADER_LENGTH]); else thisrr->input = &(rl->packet[SSL3_RT_HEADER_LENGTH]); /* * ok, we can now read from 'rl->packet' data into 'thisrr'. * thisrr->input points at thisrr->length bytes, which need to be copied * into thisrr->data by either the decryption or by the decompression. * When the data is 'copied' into the thisrr->data buffer, * thisrr->input will be updated to point at the new buffer */ /* * We now have - encrypted [ MAC [ compressed [ plain ] ] ] * thisrr->length bytes of encrypted compressed stuff. */ /* decrypt in place in 'thisrr->input' */ thisrr->data = thisrr->input; thisrr->orig_len = thisrr->length; num_recs++; /* we have pulled in a full packet so zero things */ rl->packet_length = 0; rl->is_first_record = 0; } while (num_recs < max_recs && thisrr->type == SSL3_RT_APPLICATION_DATA && RLAYER_USE_EXPLICIT_IV(rl) && rl->enc_ctx != NULL && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx)) & EVP_CIPH_FLAG_PIPELINE) != 0 && tls_record_app_data_waiting(rl)); if (num_recs == 1 && thisrr->type == SSL3_RT_CHANGE_CIPHER_SPEC /* The following can happen in tlsany_meth after HRR */ && rl->version == TLS1_3_VERSION && rl->is_first_handshake) { /* * CCS messages must be exactly 1 byte long, containing the value 0x01 */ if (thisrr->length != 1 || thisrr->data[0] != 0x01) { RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_CCS_MESSAGE); return OSSL_RECORD_RETURN_FATAL; } /* * CCS messages are ignored in TLSv1.3. We treat it like an empty * handshake record - but we still call the msg_callback */ if (rl->msg_callback != NULL) rl->msg_callback(0, TLS1_3_VERSION, SSL3_RT_CHANGE_CIPHER_SPEC, thisrr->data, 1, rl->cbarg); thisrr->type = SSL3_RT_HANDSHAKE; if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) { RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_CCS_MESSAGE); return OSSL_RECORD_RETURN_FATAL; } rl->num_recs = 0; rl->curr_rec = 0; rl->num_released = 0; return OSSL_RECORD_RETURN_SUCCESS; } if (rl->md_ctx != NULL) { const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(rl->md_ctx); if (tmpmd != NULL) { imac_size = EVP_MD_get_size(tmpmd); if (!ossl_assert(imac_size > 0 && imac_size <= EVP_MAX_MD_SIZE)) { RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB); return OSSL_RECORD_RETURN_FATAL; } mac_size = (size_t)imac_size; } } /* * If in encrypt-then-mac mode calculate mac from encrypted record. All * the details below are public so no timing details can leak. */ if (rl->use_etm && rl->md_ctx != NULL) { unsigned char *mac; for (j = 0; j < num_recs; j++) { thisrr = &rr[j]; if (thisrr->length < mac_size) { RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT); return OSSL_RECORD_RETURN_FATAL; } thisrr->length -= mac_size; mac = thisrr->data + thisrr->length; i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */); if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) { RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC, SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC); return OSSL_RECORD_RETURN_FATAL; } } /* * We've handled the mac now - there is no MAC inside the encrypted * record */ mac_size = 0; } if (mac_size > 0) { macbufs = OPENSSL_zalloc(sizeof(*macbufs) * num_recs); if (macbufs == NULL) { RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB); return OSSL_RECORD_RETURN_FATAL; } } ERR_set_mark(); enc_err = rl->funcs->cipher(rl, rr, num_recs, 0, macbufs, mac_size); /*- * enc_err is: * 0: if the record is publicly invalid, or an internal error, or AEAD * decryption failed, or ETM decryption failed. * 1: Success or MTE decryption failed (MAC will be randomised) */ if (enc_err == 0) { if (rl->alert != SSL_AD_NO_ALERT) { /* RLAYERfatal() already got called */ ERR_clear_last_mark(); goto end; } if (num_recs == 1 && rl->skip_early_data != NULL && rl->skip_early_data(rl->cbarg)) { /* * Valid early_data that we cannot decrypt will fail here. We treat * it like an empty record. */ /* * Remove any errors from the stack. Decryption failures are normal * behaviour. */ ERR_pop_to_mark(); thisrr = &rr[0]; if (!rlayer_early_data_count_ok(rl, thisrr->length, EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) { /* RLAYERfatal() already called */ goto end; } thisrr->length = 0; rl->num_recs = 0; rl->curr_rec = 0; rl->num_released = 0; /* Reset the read sequence */ memset(rl->sequence, 0, sizeof(rl->sequence)); ret = 1; goto end; } ERR_clear_last_mark(); RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC, SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC); goto end; } else { ERR_clear_last_mark(); } OSSL_TRACE_BEGIN(TLS) { BIO_printf(trc_out, "dec %lu\n", (unsigned long)rr[0].length); BIO_dump_indent(trc_out, rr[0].data, rr[0].length, 4); } OSSL_TRACE_END(TLS); /* r->length is now the compressed data plus mac */ if (rl->enc_ctx != NULL && !rl->use_etm && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) { for (j = 0; j < num_recs; j++) { SSL_MAC_BUF *thismb = &macbufs[j]; thisrr = &rr[j]; i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */); if (i == 0 || thismb == NULL || thismb->mac == NULL || CRYPTO_memcmp(md, thismb->mac, (size_t)mac_size) != 0) enc_err = 0; if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size) enc_err = 0; #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION if (enc_err == 0 && mac_size > 0 && thismb != NULL && thismb->mac != NULL && (md[0] ^ thismb->mac[0]) != 0xFF) { enc_err = 1; } #endif } } if (enc_err == 0) { if (rl->alert != SSL_AD_NO_ALERT) { /* We already called RLAYERfatal() */ goto end; } /* * A separate 'decryption_failed' alert was introduced with TLS 1.0, * SSL 3.0 only has 'bad_record_mac'. But unless a decryption * failure is directly visible from the ciphertext anyway, we should * not reveal which kind of error occurred -- this might become * visible to an attacker (e.g. via a logfile) */ RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC, SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC); goto end; } for (j = 0; j < num_recs; j++) { thisrr = &rr[j]; if (!rl->funcs->post_process_record(rl, thisrr)) { /* RLAYERfatal already called */ goto end; } /* * Record overflow checking (e.g. checking if * thisrr->length > SSL3_RT_MAX_PLAIN_LENGTH) is the responsibility of * the post_process_record() function above. However we check here if * the received packet overflows the current Max Fragment Length setting * if there is one. * Note: rl->max_frag_len != SSL3_RT_MAX_PLAIN_LENGTH and KTLS are * mutually exclusive. Also note that with KTLS thisrr->length can * be > SSL3_RT_MAX_PLAIN_LENGTH (and rl->max_frag_len must be ignored) */ if (rl->max_frag_len != SSL3_RT_MAX_PLAIN_LENGTH && thisrr->length > rl->max_frag_len) { RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG); goto end; } thisrr->off = 0; /*- * So at this point the following is true * thisrr->type is the type of record * thisrr->length == number of bytes in record * thisrr->off == offset to first valid byte * thisrr->data == where to take bytes from, increment after use :-). */ /* just read a 0 length packet */ if (thisrr->length == 0) { if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) { RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_RECORD_TOO_SMALL); goto end; } } else { rl->empty_record_count = 0; } } if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_EARLY) { thisrr = &rr[0]; if (thisrr->type == SSL3_RT_APPLICATION_DATA && !rlayer_early_data_count_ok(rl, thisrr->length, 0, 0)) { /* RLAYERfatal already called */ goto end; } } rl->num_recs = num_recs; rl->curr_rec = 0; rl->num_released = 0; ret = OSSL_RECORD_RETURN_SUCCESS; end: if (macbufs != NULL) { for (j = 0; j < num_recs; j++) { if (macbufs[j].alloced) OPENSSL_free(macbufs[j].mac); } OPENSSL_free(macbufs); } return ret; } /* Shared by ssl3_meth and tls1_meth */ int tls_default_validate_record_header(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec) { size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH; if (rec->rec_version != rl->version) { RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_VERSION_NUMBER); return 0; } #ifndef OPENSSL_NO_COMP /* * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH * does not include the compression overhead anyway. */ if (rl->compctx == NULL) len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD; #endif if (rec->length > len) { RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_ENCRYPTED_LENGTH_TOO_LONG); return 0; } return 1; } int tls_do_compress(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *wr) { #ifndef OPENSSL_NO_COMP int i; i = COMP_compress_block(rl->compctx, wr->data, (int)(wr->length + SSL3_RT_MAX_COMPRESSED_OVERHEAD), wr->input, (int)wr->length); if (i < 0) return 0; wr->length = i; wr->input = wr->data; return 1; #else return 0; #endif } int tls_do_uncompress(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec) { #ifndef OPENSSL_NO_COMP int i; if (rec->comp == NULL) { rec->comp = (unsigned char *) OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH); } if (rec->comp == NULL) return 0; i = COMP_expand_block(rl->compctx, rec->comp, SSL3_RT_MAX_PLAIN_LENGTH, rec->data, (int)rec->length); if (i < 0) return 0; else rec->length = i; rec->data = rec->comp; return 1; #else return 0; #endif } /* Shared by tlsany_meth, ssl3_meth and tls1_meth */ int tls_default_post_process_record(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec) { if (rl->compctx != NULL) { if (rec->length > SSL3_RT_MAX_COMPRESSED_LENGTH) { RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_COMPRESSED_LENGTH_TOO_LONG); return 0; } if (!tls_do_uncompress(rl, rec)) { RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE, SSL_R_BAD_DECOMPRESSION); return 0; } } if (rec->length > SSL3_RT_MAX_PLAIN_LENGTH) { RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG); return 0; } return 1; } /* Shared by tls13_meth and ktls_meth */ int tls13_common_post_process_record(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec) { if (rec->type != SSL3_RT_APPLICATION_DATA && rec->type != SSL3_RT_ALERT && rec->type != SSL3_RT_HANDSHAKE) { RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_RECORD_TYPE); return 0; } - if (rl->msg_callback != NULL) - rl->msg_callback(0, rl->version, SSL3_RT_INNER_CONTENT_TYPE, &rec->type, - 1, rl->cbarg); + if (rl->msg_callback != NULL) { + unsigned char ctype = (unsigned char)rec->type; + + rl->msg_callback(0, rl->version, SSL3_RT_INNER_CONTENT_TYPE, &ctype, + 1, rl->cbarg); + } /* * TLSv1.3 alert and handshake records are required to be non-zero in * length. */ if ((rec->type == SSL3_RT_HANDSHAKE || rec->type == SSL3_RT_ALERT) && rec->length == 0) { RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_LENGTH); return 0; } return 1; } int tls_read_record(OSSL_RECORD_LAYER *rl, void **rechandle, int *rversion, uint8_t *type, const unsigned char **data, size_t *datalen, uint16_t *epoch, unsigned char *seq_num) { TLS_RL_RECORD *rec; /* * tls_get_more_records() can return success without actually reading * anything useful (i.e. if empty records are read). We loop here until * we have something useful. tls_get_more_records() will eventually fail if * too many sequential empty records are read. */ while (rl->curr_rec >= rl->num_recs) { int ret; if (rl->num_released != rl->num_recs) { RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_RECORDS_NOT_RELEASED); return OSSL_RECORD_RETURN_FATAL; } ret = rl->funcs->get_more_records(rl); if (ret != OSSL_RECORD_RETURN_SUCCESS) return ret; } /* * We have now got rl->num_recs records buffered in rl->rrec. rl->curr_rec * points to the next one to read. */ rec = &rl->rrec[rl->curr_rec++]; *rechandle = rec; *rversion = rec->rec_version; *type = rec->type; *data = rec->data + rec->off; *datalen = rec->length; if (rl->isdtls) { *epoch = rec->epoch; memcpy(seq_num, rec->seq_num, sizeof(rec->seq_num)); } return OSSL_RECORD_RETURN_SUCCESS; } int tls_release_record(OSSL_RECORD_LAYER *rl, void *rechandle, size_t length) { TLS_RL_RECORD *rec = &rl->rrec[rl->num_released]; if (!ossl_assert(rl->num_released < rl->curr_rec) || !ossl_assert(rechandle == rec)) { /* Should not happen */ RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_INVALID_RECORD); return OSSL_RECORD_RETURN_FATAL; } if (rec->length < length) { /* Should not happen */ RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR); return OSSL_RECORD_RETURN_FATAL; } if ((rl->options & SSL_OP_CLEANSE_PLAINTEXT) != 0) OPENSSL_cleanse(rec->data + rec->off, length); rec->off += length; rec->length -= length; if (rec->length > 0) return OSSL_RECORD_RETURN_SUCCESS; rl->num_released++; if (rl->curr_rec == rl->num_released && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0 && TLS_BUFFER_get_left(&rl->rbuf) == 0) tls_release_read_buffer(rl); return OSSL_RECORD_RETURN_SUCCESS; } int tls_set_options(OSSL_RECORD_LAYER *rl, const OSSL_PARAM *options) { const OSSL_PARAM *p; p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS); if (p != NULL && !OSSL_PARAM_get_uint64(p, &rl->options)) { ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER); return 0; } p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE); if (p != NULL && !OSSL_PARAM_get_uint32(p, &rl->mode)) { ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER); return 0; } if (rl->direction == OSSL_RECORD_DIRECTION_READ) { p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN); if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->rbuf.default_len)) { ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER); return 0; } } else { p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_BLOCK_PADDING); if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->block_padding)) { ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER); return 0; } p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_HS_PADDING); if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->hs_padding)) { ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER); return 0; } } if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) { /* * We ignore any read_ahead setting prior to the application protection * level. Otherwise we may read ahead data in a lower protection level * that is destined for a higher protection level. To simplify the logic * we don't support that at this stage. */ p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD); if (p != NULL && !OSSL_PARAM_get_int(p, &rl->read_ahead)) { ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER); return 0; } } return 1; } int tls_int_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers, int role, int direction, int level, const EVP_CIPHER *ciph, size_t taglen, const EVP_MD *md, COMP_METHOD *comp, BIO *prev, BIO *transport, BIO *next, const OSSL_PARAM *settings, const OSSL_PARAM *options, const OSSL_DISPATCH *fns, void *cbarg, OSSL_RECORD_LAYER **retrl) { OSSL_RECORD_LAYER *rl = OPENSSL_zalloc(sizeof(*rl)); const OSSL_PARAM *p; *retrl = NULL; if (rl == NULL) return OSSL_RECORD_RETURN_FATAL; /* * Default the value for max_frag_len. This may be overridden by the * settings */ rl->max_frag_len = SSL3_RT_MAX_PLAIN_LENGTH; /* Loop through all the settings since they must all be understood */ if (settings != NULL) { for (p = settings; p->key != NULL; p++) { if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM) == 0) { if (!OSSL_PARAM_get_int(p, &rl->use_etm)) { ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER); goto err; } } else if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN) == 0) { if (!OSSL_PARAM_get_uint(p, &rl->max_frag_len)) { ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER); goto err; } } else if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA) == 0) { if (!OSSL_PARAM_get_uint32(p, &rl->max_early_data)) { ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER); goto err; } } else if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC) == 0) { if (!OSSL_PARAM_get_int(p, &rl->stream_mac)) { ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER); goto err; } } else if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE) == 0) { if (!OSSL_PARAM_get_int(p, &rl->tlstree)) { ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER); goto err; } } else { ERR_raise(ERR_LIB_SSL, SSL_R_UNKNOWN_MANDATORY_PARAMETER); goto err; } } } rl->libctx = libctx; rl->propq = propq; rl->version = vers; rl->role = role; rl->direction = direction; rl->level = level; rl->taglen = taglen; rl->md = md; rl->alert = SSL_AD_NO_ALERT; rl->rstate = SSL_ST_READ_HEADER; if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE) rl->is_first_record = 1; if (!tls_set1_bio(rl, transport)) goto err; if (prev != NULL && !BIO_up_ref(prev)) goto err; rl->prev = prev; if (next != NULL && !BIO_up_ref(next)) goto err; rl->next = next; rl->cbarg = cbarg; if (fns != NULL) { for (; fns->function_id != 0; fns++) { switch (fns->function_id) { case OSSL_FUNC_RLAYER_SKIP_EARLY_DATA: rl->skip_early_data = OSSL_FUNC_rlayer_skip_early_data(fns); break; case OSSL_FUNC_RLAYER_MSG_CALLBACK: rl->msg_callback = OSSL_FUNC_rlayer_msg_callback(fns); break; case OSSL_FUNC_RLAYER_SECURITY: rl->security = OSSL_FUNC_rlayer_security(fns); break; case OSSL_FUNC_RLAYER_PADDING: rl->padding = OSSL_FUNC_rlayer_padding(fns); default: /* Just ignore anything we don't understand */ break; } } } if (!tls_set_options(rl, options)) { ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER); goto err; } if ((rl->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) == 0 && rl->version <= TLS1_VERSION && !EVP_CIPHER_is_a(ciph, "NULL") && !EVP_CIPHER_is_a(ciph, "RC4")) { /* * Enable vulnerability countermeasure for CBC ciphers with known-IV * problem (http://www.openssl.org/~bodo/tls-cbc.txt) */ rl->need_empty_fragments = 1; } *retrl = rl; return OSSL_RECORD_RETURN_SUCCESS; err: tls_int_free(rl); return OSSL_RECORD_RETURN_FATAL; } static int tls_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers, int role, int direction, int level, uint16_t epoch, unsigned char *secret, size_t secretlen, unsigned char *key, size_t keylen, unsigned char *iv, size_t ivlen, unsigned char *mackey, size_t mackeylen, const EVP_CIPHER *ciph, size_t taglen, int mactype, const EVP_MD *md, COMP_METHOD *comp, const EVP_MD *kdfdigest, BIO *prev, BIO *transport, BIO *next, BIO_ADDR *local, BIO_ADDR *peer, const OSSL_PARAM *settings, const OSSL_PARAM *options, const OSSL_DISPATCH *fns, void *cbarg, void *rlarg, OSSL_RECORD_LAYER **retrl) { int ret; ret = tls_int_new_record_layer(libctx, propq, vers, role, direction, level, ciph, taglen, md, comp, prev, transport, next, settings, options, fns, cbarg, retrl); if (ret != OSSL_RECORD_RETURN_SUCCESS) return ret; switch (vers) { case TLS_ANY_VERSION: (*retrl)->funcs = &tls_any_funcs; break; case TLS1_3_VERSION: (*retrl)->funcs = &tls_1_3_funcs; break; case TLS1_2_VERSION: case TLS1_1_VERSION: case TLS1_VERSION: (*retrl)->funcs = &tls_1_funcs; break; case SSL3_VERSION: (*retrl)->funcs = &ssl_3_0_funcs; break; default: /* Should not happen */ ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR); ret = OSSL_RECORD_RETURN_FATAL; goto err; } ret = (*retrl)->funcs->set_crypto_state(*retrl, level, key, keylen, iv, ivlen, mackey, mackeylen, ciph, taglen, mactype, md, comp); err: if (ret != OSSL_RECORD_RETURN_SUCCESS) { tls_int_free(*retrl); *retrl = NULL; } return ret; } static void tls_int_free(OSSL_RECORD_LAYER *rl) { BIO_free(rl->prev); BIO_free(rl->bio); BIO_free(rl->next); ossl_tls_buffer_release(&rl->rbuf); tls_release_write_buffer(rl); EVP_CIPHER_CTX_free(rl->enc_ctx); EVP_MAC_CTX_free(rl->mac_ctx); EVP_MD_CTX_free(rl->md_ctx); #ifndef OPENSSL_NO_COMP COMP_CTX_free(rl->compctx); #endif OPENSSL_free(rl->iv); OPENSSL_free(rl->nonce); if (rl->version == SSL3_VERSION) OPENSSL_cleanse(rl->mac_secret, sizeof(rl->mac_secret)); TLS_RL_RECORD_release(rl->rrec, SSL_MAX_PIPELINES); OPENSSL_free(rl); } int tls_free(OSSL_RECORD_LAYER *rl) { TLS_BUFFER *rbuf; size_t left, written; int ret = 1; if (rl == NULL) return 1; rbuf = &rl->rbuf; left = TLS_BUFFER_get_left(rbuf); if (left > 0) { /* * This record layer is closing but we still have data left in our * buffer. It must be destined for the next epoch - so push it there. */ ret = BIO_write_ex(rl->next, rbuf->buf + rbuf->offset, left, &written); } tls_int_free(rl); return ret; } int tls_unprocessed_read_pending(OSSL_RECORD_LAYER *rl) { return TLS_BUFFER_get_left(&rl->rbuf) != 0; } int tls_processed_read_pending(OSSL_RECORD_LAYER *rl) { return rl->curr_rec < rl->num_recs; } size_t tls_app_data_pending(OSSL_RECORD_LAYER *rl) { size_t i; size_t num = 0; for (i = rl->curr_rec; i < rl->num_recs; i++) { if (rl->rrec[i].type != SSL3_RT_APPLICATION_DATA) return num; num += rl->rrec[i].length; } return num; } size_t tls_get_max_records_default(OSSL_RECORD_LAYER *rl, uint8_t type, size_t len, size_t maxfrag, size_t *preffrag) { /* * If we have a pipeline capable cipher, and we have been configured to use * it, then return the preferred number of pipelines. */ if (rl->max_pipelines > 0 && rl->enc_ctx != NULL && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx)) & EVP_CIPH_FLAG_PIPELINE) != 0 && RLAYER_USE_EXPLICIT_IV(rl)) { size_t pipes; if (len == 0) return 1; pipes = ((len - 1) / *preffrag) + 1; return (pipes < rl->max_pipelines) ? pipes : rl->max_pipelines; } return 1; } size_t tls_get_max_records(OSSL_RECORD_LAYER *rl, uint8_t type, size_t len, size_t maxfrag, size_t *preffrag) { return rl->funcs->get_max_records(rl, type, len, maxfrag, preffrag); } int tls_allocate_write_buffers_default(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE *templates, size_t numtempl, size_t *prefix) { if (!tls_setup_write_buffer(rl, numtempl, 0, 0)) { /* RLAYERfatal() already called */ return 0; } return 1; } int tls_initialise_write_packets_default(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE *templates, size_t numtempl, OSSL_RECORD_TEMPLATE *prefixtempl, WPACKET *pkt, TLS_BUFFER *bufs, size_t *wpinited) { WPACKET *thispkt; size_t j, align; TLS_BUFFER *wb; for (j = 0; j < numtempl; j++) { thispkt = &pkt[j]; wb = &bufs[j]; wb->type = templates[j].type; #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0 align = (size_t)TLS_BUFFER_get_buf(wb); align += rl->isdtls ? DTLS1_RT_HEADER_LENGTH : SSL3_RT_HEADER_LENGTH; align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD); #endif TLS_BUFFER_set_offset(wb, align); if (!WPACKET_init_static_len(thispkt, TLS_BUFFER_get_buf(wb), TLS_BUFFER_get_len(wb), 0)) { RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR); return 0; } (*wpinited)++; if (!WPACKET_allocate_bytes(thispkt, align, NULL)) { RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR); return 0; } } return 1; } int tls_prepare_record_header_default(OSSL_RECORD_LAYER *rl, WPACKET *thispkt, OSSL_RECORD_TEMPLATE *templ, uint8_t rectype, unsigned char **recdata) { size_t maxcomplen; *recdata = NULL; maxcomplen = templ->buflen; if (rl->compctx != NULL) maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD; if (!WPACKET_put_bytes_u8(thispkt, rectype) || !WPACKET_put_bytes_u16(thispkt, templ->version) || !WPACKET_start_sub_packet_u16(thispkt) || (rl->eivlen > 0 && !WPACKET_allocate_bytes(thispkt, rl->eivlen, NULL)) || (maxcomplen > 0 && !WPACKET_reserve_bytes(thispkt, maxcomplen, recdata))) { RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR); return 0; } return 1; } int tls_prepare_for_encryption_default(OSSL_RECORD_LAYER *rl, size_t mac_size, WPACKET *thispkt, TLS_RL_RECORD *thiswr) { size_t len; unsigned char *recordstart; /* * we should still have the output to thiswr->data and the input from * wr->input. Length should be thiswr->length. thiswr->data still points * in the wb->buf */ if (!rl->use_etm && mac_size != 0) { unsigned char *mac; if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac) || !rl->funcs->mac(rl, thiswr, mac, 1)) { RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR); return 0; } } /* * Reserve some bytes for any growth that may occur during encryption. If * we are adding the MAC independently of the cipher algorithm, then the * max encrypted overhead does not need to include an allocation for that * MAC */ if (!WPACKET_reserve_bytes(thispkt, SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD - mac_size, NULL) /* * We also need next the amount of bytes written to this * sub-packet */ || !WPACKET_get_length(thispkt, &len)) { RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR); return 0; } /* Get a pointer to the start of this record excluding header */ recordstart = WPACKET_get_curr(thispkt) - len; TLS_RL_RECORD_set_data(thiswr, recordstart); TLS_RL_RECORD_reset_input(thiswr); TLS_RL_RECORD_set_length(thiswr, len); return 1; } int tls_post_encryption_processing_default(OSSL_RECORD_LAYER *rl, size_t mac_size, OSSL_RECORD_TEMPLATE *thistempl, WPACKET *thispkt, TLS_RL_RECORD *thiswr) { size_t origlen, len; size_t headerlen = rl->isdtls ? DTLS1_RT_HEADER_LENGTH : SSL3_RT_HEADER_LENGTH; /* Allocate bytes for the encryption overhead */ if (!WPACKET_get_length(thispkt, &origlen) /* Check we allowed enough room for the encryption growth */ || !ossl_assert(origlen + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD - mac_size >= thiswr->length) /* Encryption should never shrink the data! */ || origlen > thiswr->length || (thiswr->length > origlen && !WPACKET_allocate_bytes(thispkt, thiswr->length - origlen, NULL))) { RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR); return 0; } if (rl->use_etm && mac_size != 0) { unsigned char *mac; if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac) || !rl->funcs->mac(rl, thiswr, mac, 1)) { RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR); return 0; } TLS_RL_RECORD_add_length(thiswr, mac_size); } if (!WPACKET_get_length(thispkt, &len) || !WPACKET_close(thispkt)) { RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR); return 0; } if (rl->msg_callback != NULL) { unsigned char *recordstart; recordstart = WPACKET_get_curr(thispkt) - len - headerlen; rl->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart, headerlen, rl->cbarg); if (rl->version == TLS1_3_VERSION && rl->enc_ctx != NULL) { unsigned char ctype = thistempl->type; rl->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE, &ctype, 1, rl->cbarg); } } if (!WPACKET_finish(thispkt)) { RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR); return 0; } TLS_RL_RECORD_add_length(thiswr, headerlen); return 1; } int tls_write_records_default(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE *templates, size_t numtempl) { WPACKET pkt[SSL_MAX_PIPELINES + 1]; TLS_RL_RECORD wr[SSL_MAX_PIPELINES + 1]; WPACKET *thispkt; TLS_RL_RECORD *thiswr; int mac_size = 0, ret = 0; size_t wpinited = 0; size_t j, prefix = 0; OSSL_RECORD_TEMPLATE prefixtempl; OSSL_RECORD_TEMPLATE *thistempl; if (rl->md_ctx != NULL && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) { mac_size = EVP_MD_CTX_get_size(rl->md_ctx); if (mac_size < 0) { RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR); goto err; } } if (!rl->funcs->allocate_write_buffers(rl, templates, numtempl, &prefix)) { /* RLAYERfatal() already called */ goto err; } if (!rl->funcs->initialise_write_packets(rl, templates, numtempl, &prefixtempl, pkt, rl->wbuf, &wpinited)) { /* RLAYERfatal() already called */ goto err; } /* Clear our TLS_RL_RECORD structures */ memset(wr, 0, sizeof(wr)); for (j = 0; j < numtempl + prefix; j++) { unsigned char *compressdata = NULL; uint8_t rectype; thispkt = &pkt[j]; thiswr = &wr[j]; thistempl = (j < prefix) ? &prefixtempl : &templates[j - prefix]; /* * Default to the record type as specified in the template unless the * protocol implementation says differently. */ if (rl->funcs->get_record_type != NULL) rectype = rl->funcs->get_record_type(rl, thistempl); else rectype = thistempl->type; TLS_RL_RECORD_set_type(thiswr, rectype); TLS_RL_RECORD_set_rec_version(thiswr, thistempl->version); if (!rl->funcs->prepare_record_header(rl, thispkt, thistempl, rectype, &compressdata)) { /* RLAYERfatal() already called */ goto err; } /* lets setup the record stuff. */ TLS_RL_RECORD_set_data(thiswr, compressdata); TLS_RL_RECORD_set_length(thiswr, thistempl->buflen); TLS_RL_RECORD_set_input(thiswr, (unsigned char *)thistempl->buf); /* * we now 'read' from thiswr->input, thiswr->length bytes into * thiswr->data */ /* first we compress */ if (rl->compctx != NULL) { if (!tls_do_compress(rl, thiswr) || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) { RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE); goto err; } } else if (compressdata != NULL) { if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) { RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR); goto err; } TLS_RL_RECORD_reset_input(&wr[j]); } if (rl->funcs->add_record_padding != NULL && !rl->funcs->add_record_padding(rl, thistempl, thispkt, thiswr)) { /* RLAYERfatal() already called */ goto err; } if (!rl->funcs->prepare_for_encryption(rl, mac_size, thispkt, thiswr)) { /* RLAYERfatal() already called */ goto err; } } if (prefix) { if (rl->funcs->cipher(rl, wr, 1, 1, NULL, mac_size) < 1) { if (rl->alert == SSL_AD_NO_ALERT) { RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR); } goto err; } } if (rl->funcs->cipher(rl, wr + prefix, numtempl, 1, NULL, mac_size) < 1) { if (rl->alert == SSL_AD_NO_ALERT) { RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR); } goto err; } for (j = 0; j < numtempl + prefix; j++) { thispkt = &pkt[j]; thiswr = &wr[j]; thistempl = (j < prefix) ? &prefixtempl : &templates[j - prefix]; if (!rl->funcs->post_encryption_processing(rl, mac_size, thistempl, thispkt, thiswr)) { /* RLAYERfatal() already called */ goto err; } /* now let's set up wb */ TLS_BUFFER_set_left(&rl->wbuf[j], TLS_RL_RECORD_get_length(thiswr)); } ret = 1; err: for (j = 0; j < wpinited; j++) WPACKET_cleanup(&pkt[j]); return ret; } int tls_write_records(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE *templates, size_t numtempl) { /* Check we don't have pending data waiting to write */ if (!ossl_assert(rl->nextwbuf >= rl->numwpipes || TLS_BUFFER_get_left(&rl->wbuf[rl->nextwbuf]) == 0)) { RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return OSSL_RECORD_RETURN_FATAL; } if (!rl->funcs->write_records(rl, templates, numtempl)) { /* RLAYERfatal already called */ return OSSL_RECORD_RETURN_FATAL; } rl->nextwbuf = 0; /* we now just need to write the buffers */ return tls_retry_write_records(rl); } int tls_retry_write_records(OSSL_RECORD_LAYER *rl) { int i, ret; TLS_BUFFER *thiswb; size_t tmpwrit = 0; if (rl->nextwbuf >= rl->numwpipes) return OSSL_RECORD_RETURN_SUCCESS; for (;;) { thiswb = &rl->wbuf[rl->nextwbuf]; clear_sys_error(); if (rl->bio != NULL) { if (rl->funcs->prepare_write_bio != NULL) { ret = rl->funcs->prepare_write_bio(rl, thiswb->type); if (ret != OSSL_RECORD_RETURN_SUCCESS) return ret; } i = BIO_write(rl->bio, (char *) &(TLS_BUFFER_get_buf(thiswb) [TLS_BUFFER_get_offset(thiswb)]), (unsigned int)TLS_BUFFER_get_left(thiswb)); if (i >= 0) { tmpwrit = i; if (i == 0 && BIO_should_retry(rl->bio)) ret = OSSL_RECORD_RETURN_RETRY; else ret = OSSL_RECORD_RETURN_SUCCESS; } else { if (BIO_should_retry(rl->bio)) { ret = OSSL_RECORD_RETURN_RETRY; } else { ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(), "tls_retry_write_records failure"); ret = OSSL_RECORD_RETURN_FATAL; } } } else { RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET); ret = OSSL_RECORD_RETURN_FATAL; i = -1; } /* * When an empty fragment is sent on a connection using KTLS, * it is sent as a write of zero bytes. If this zero byte * write succeeds, i will be 0 rather than a non-zero value. * Treat i == 0 as success rather than an error for zero byte * writes to permit this case. */ if (i >= 0 && tmpwrit == TLS_BUFFER_get_left(thiswb)) { TLS_BUFFER_set_left(thiswb, 0); TLS_BUFFER_add_offset(thiswb, tmpwrit); if (++(rl->nextwbuf) < rl->numwpipes) continue; if (rl->nextwbuf == rl->numwpipes && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0) tls_release_write_buffer(rl); return OSSL_RECORD_RETURN_SUCCESS; } else if (i <= 0) { if (rl->isdtls) { /* * For DTLS, just drop it. That's kind of the whole point in * using a datagram service */ TLS_BUFFER_set_left(thiswb, 0); if (++(rl->nextwbuf) == rl->numwpipes && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0) tls_release_write_buffer(rl); } return ret; } TLS_BUFFER_add_offset(thiswb, tmpwrit); TLS_BUFFER_sub_left(thiswb, tmpwrit); } } int tls_get_alert_code(OSSL_RECORD_LAYER *rl) { return rl->alert; } int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio) { if (bio != NULL && !BIO_up_ref(bio)) return 0; BIO_free(rl->bio); rl->bio = bio; return 1; } /* Shared by most methods except tlsany_meth */ int tls_default_set_protocol_version(OSSL_RECORD_LAYER *rl, int version) { if (rl->version != version) return 0; return 1; } int tls_set_protocol_version(OSSL_RECORD_LAYER *rl, int version) { return rl->funcs->set_protocol_version(rl, version); } void tls_set_plain_alerts(OSSL_RECORD_LAYER *rl, int allow) { rl->allow_plain_alerts = allow; } void tls_set_first_handshake(OSSL_RECORD_LAYER *rl, int first) { rl->is_first_handshake = first; } void tls_set_max_pipelines(OSSL_RECORD_LAYER *rl, size_t max_pipelines) { rl->max_pipelines = max_pipelines; if (max_pipelines > 1) rl->read_ahead = 1; } void tls_get_state(OSSL_RECORD_LAYER *rl, const char **shortstr, const char **longstr) { const char *shrt, *lng; switch (rl->rstate) { case SSL_ST_READ_HEADER: shrt = "RH"; lng = "read header"; break; case SSL_ST_READ_BODY: shrt = "RB"; lng = "read body"; break; default: shrt = lng = "unknown"; break; } if (shortstr != NULL) *shortstr = shrt; if (longstr != NULL) *longstr = lng; } const COMP_METHOD *tls_get_compression(OSSL_RECORD_LAYER *rl) { #ifndef OPENSSL_NO_COMP return (rl->compctx == NULL) ? NULL : COMP_CTX_get_method(rl->compctx); #else return NULL; #endif } void tls_set_max_frag_len(OSSL_RECORD_LAYER *rl, size_t max_frag_len) { rl->max_frag_len = max_frag_len; /* * We don't need to adjust buffer sizes. Write buffer sizes are * automatically checked anyway. We should only be changing the read buffer * size during the handshake, so we will create a new buffer when we create * the new record layer. We can't change the existing buffer because it may * already have data in it. */ } int tls_increment_sequence_ctr(OSSL_RECORD_LAYER *rl) { int i; /* Increment the sequence counter */ for (i = SEQ_NUM_SIZE; i > 0; i--) { ++(rl->sequence[i - 1]); if (rl->sequence[i - 1] != 0) break; } if (i == 0) { /* Sequence has wrapped */ RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_SEQUENCE_CTR_WRAPPED); return 0; } return 1; } int tls_alloc_buffers(OSSL_RECORD_LAYER *rl) { if (rl->direction == OSSL_RECORD_DIRECTION_WRITE) { /* If we have a pending write then buffers are already allocated */ if (rl->nextwbuf < rl->numwpipes) return 1; /* * We assume 1 pipe with default sized buffer. If what we need ends up * being a different size to that then it will be reallocated on demand. * If we need more than 1 pipe then that will also be allocated on * demand */ if (!tls_setup_write_buffer(rl, 1, 0, 0)) return 0; /* * Normally when we allocate write buffers we immediately write * something into it. In this case we're not doing that so mark the * buffer as empty. */ TLS_BUFFER_set_left(&rl->wbuf[0], 0); return 1; } /* Read direction */ /* If we have pending data to be read then buffers are already allocated */ if (rl->curr_rec < rl->num_recs || TLS_BUFFER_get_left(&rl->rbuf) != 0) return 1; return tls_setup_read_buffer(rl); } int tls_free_buffers(OSSL_RECORD_LAYER *rl) { if (rl->direction == OSSL_RECORD_DIRECTION_WRITE) { if (rl->nextwbuf < rl->numwpipes) { /* * We may have pending data. If we've just got one empty buffer * allocated then it has probably just been alloc'd via * tls_alloc_buffers, and it is fine to free it. Otherwise this * looks like real pending data and it is an error. */ if (rl->nextwbuf != 0 || rl->numwpipes != 1 || TLS_BUFFER_get_left(&rl->wbuf[0]) != 0) return 0; } tls_release_write_buffer(rl); return 1; } /* Read direction */ /* If we have pending data to be read then fail */ if (rl->curr_rec < rl->num_recs || rl->curr_rec != rl->num_released || TLS_BUFFER_get_left(&rl->rbuf) != 0 || rl->rstate == SSL_ST_READ_BODY) return 0; return tls_release_read_buffer(rl); } const OSSL_RECORD_METHOD ossl_tls_record_method = { tls_new_record_layer, tls_free, tls_unprocessed_read_pending, tls_processed_read_pending, tls_app_data_pending, tls_get_max_records, tls_write_records, tls_retry_write_records, tls_read_record, tls_release_record, tls_get_alert_code, tls_set1_bio, tls_set_protocol_version, tls_set_plain_alerts, tls_set_first_handshake, tls_set_max_pipelines, NULL, tls_get_state, tls_set_options, tls_get_compression, tls_set_max_frag_len, NULL, tls_increment_sequence_ctr, tls_alloc_buffers, tls_free_buffers }; diff --git a/ssl/ssl_rsa.c b/ssl/ssl_rsa.c index e833bcdbc377..f4731a87af90 100644 --- a/ssl/ssl_rsa.c +++ b/ssl/ssl_rsa.c @@ -1,1094 +1,1097 @@ /* * Copyright 1995-2025 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 "ssl_local.h" #include "internal/packet.h" #include "internal/ssl_unwrap.h" #include #include #include #include #include #include static int ssl_set_cert(CERT *c, X509 *x509, SSL_CTX *ctx); static int ssl_set_pkey(CERT *c, EVP_PKEY *pkey, SSL_CTX *ctx); #define SYNTHV1CONTEXT (SSL_EXT_TLS1_2_AND_BELOW_ONLY \ | SSL_EXT_CLIENT_HELLO \ | SSL_EXT_TLS1_2_SERVER_HELLO \ | SSL_EXT_IGNORE_ON_RESUMPTION) #define NAME_PREFIX1 "SERVERINFO FOR " #define NAME_PREFIX2 "SERVERINFOV2 FOR " int SSL_use_certificate(SSL *ssl, X509 *x) { int rv; SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl); if (sc == NULL) return 0; if (x == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER); return 0; } rv = ssl_security_cert(sc, NULL, x, 0, 1); if (rv != 1) { ERR_raise(ERR_LIB_SSL, rv); return 0; } return ssl_set_cert(sc->cert, x, SSL_CONNECTION_GET_CTX(sc)); } int SSL_use_certificate_file(SSL *ssl, const char *file, int type) { int j; BIO *in = NULL; int ret = 0; X509 *cert = NULL, *x = NULL; if (file == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER); goto end; } in = BIO_new(BIO_s_file()); if (in == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_BUF_LIB); goto end; } if (BIO_read_filename(in, file) <= 0) { ERR_raise(ERR_LIB_SSL, ERR_R_SYS_LIB); goto end; } x = X509_new_ex(ssl->ctx->libctx, ssl->ctx->propq); if (x == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_ASN1_LIB); goto end; } if (type == SSL_FILETYPE_ASN1) { j = ERR_R_ASN1_LIB; cert = d2i_X509_bio(in, &x); } else if (type == SSL_FILETYPE_PEM) { SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl); if (sc == NULL) goto end; j = ERR_R_PEM_LIB; cert = PEM_read_bio_X509(in, &x, sc->default_passwd_callback, sc->default_passwd_callback_userdata); } else { ERR_raise(ERR_LIB_SSL, SSL_R_BAD_SSL_FILETYPE); goto end; } if (cert == NULL) { ERR_raise(ERR_LIB_SSL, j); goto end; } ret = SSL_use_certificate(ssl, x); end: X509_free(x); BIO_free(in); return ret; } int SSL_use_certificate_ASN1(SSL *ssl, const unsigned char *d, int len) { X509 *x; int ret; x = X509_new_ex(ssl->ctx->libctx, ssl->ctx->propq); if (x == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_ASN1_LIB); return 0; } if (d2i_X509(&x, &d, (long)len)== NULL) { X509_free(x); ERR_raise(ERR_LIB_SSL, ERR_R_ASN1_LIB); return 0; } ret = SSL_use_certificate(ssl, x); X509_free(x); return ret; } static int ssl_set_pkey(CERT *c, EVP_PKEY *pkey, SSL_CTX *ctx) { size_t i; if (ssl_cert_lookup_by_pkey(pkey, &i, ctx) == NULL) { ERR_raise(ERR_LIB_SSL, SSL_R_UNKNOWN_CERTIFICATE_TYPE); return 0; } if (c->pkeys[i].x509 != NULL && !X509_check_private_key(c->pkeys[i].x509, pkey)) return 0; if (!EVP_PKEY_up_ref(pkey)) return 0; EVP_PKEY_free(c->pkeys[i].privatekey); c->pkeys[i].privatekey = pkey; c->key = &c->pkeys[i]; return 1; } int SSL_use_PrivateKey(SSL *ssl, EVP_PKEY *pkey) { int ret; SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl); if (sc == NULL) return 0; if (pkey == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER); return 0; } ret = ssl_set_pkey(sc->cert, pkey, SSL_CONNECTION_GET_CTX(sc)); return ret; } int SSL_use_PrivateKey_file(SSL *ssl, const char *file, int type) { int j, ret = 0; BIO *in = NULL; EVP_PKEY *pkey = NULL; if (file == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER); goto end; } in = BIO_new(BIO_s_file()); if (in == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_BUF_LIB); goto end; } if (BIO_read_filename(in, file) <= 0) { ERR_raise(ERR_LIB_SSL, ERR_R_SYS_LIB); goto end; } if (type == SSL_FILETYPE_PEM) { SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl); if (sc == NULL) goto end; j = ERR_R_PEM_LIB; pkey = PEM_read_bio_PrivateKey_ex(in, NULL, sc->default_passwd_callback, sc->default_passwd_callback_userdata, ssl->ctx->libctx, ssl->ctx->propq); } else if (type == SSL_FILETYPE_ASN1) { j = ERR_R_ASN1_LIB; pkey = d2i_PrivateKey_ex_bio(in, NULL, ssl->ctx->libctx, ssl->ctx->propq); } else { ERR_raise(ERR_LIB_SSL, SSL_R_BAD_SSL_FILETYPE); goto end; } if (pkey == NULL) { ERR_raise(ERR_LIB_SSL, j); goto end; } ret = SSL_use_PrivateKey(ssl, pkey); EVP_PKEY_free(pkey); end: BIO_free(in); return ret; } int SSL_use_PrivateKey_ASN1(int type, SSL *ssl, const unsigned char *d, long len) { int ret; const unsigned char *p; EVP_PKEY *pkey; p = d; if ((pkey = d2i_PrivateKey_ex(type, NULL, &p, (long)len, ssl->ctx->libctx, ssl->ctx->propq)) == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_ASN1_LIB); return 0; } ret = SSL_use_PrivateKey(ssl, pkey); EVP_PKEY_free(pkey); return ret; } int SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x) { int rv; if (x == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER); return 0; } rv = ssl_security_cert(NULL, ctx, x, 0, 1); if (rv != 1) { ERR_raise(ERR_LIB_SSL, rv); return 0; } return ssl_set_cert(ctx->cert, x, ctx); } static int ssl_set_cert(CERT *c, X509 *x, SSL_CTX *ctx) { EVP_PKEY *pkey; size_t i; pkey = X509_get0_pubkey(x); if (pkey == NULL) { ERR_raise(ERR_LIB_SSL, SSL_R_X509_LIB); return 0; } if (ssl_cert_lookup_by_pkey(pkey, &i, ctx) == NULL) { ERR_raise(ERR_LIB_SSL, SSL_R_UNKNOWN_CERTIFICATE_TYPE); return 0; } if (i == SSL_PKEY_ECC && !EVP_PKEY_can_sign(pkey)) { ERR_raise(ERR_LIB_SSL, SSL_R_ECC_CERT_NOT_FOR_SIGNING); return 0; } if (c->pkeys[i].privatekey != NULL) { /* * The return code from EVP_PKEY_copy_parameters is deliberately * ignored. Some EVP_PKEY types cannot do this. * coverity[check_return] */ EVP_PKEY_copy_parameters(pkey, c->pkeys[i].privatekey); ERR_clear_error(); if (!X509_check_private_key(x, c->pkeys[i].privatekey)) { /* * don't fail for a cert/key mismatch, just free current private * key (when switching to a different cert & key, first this * function should be used, then ssl_set_pkey */ EVP_PKEY_free(c->pkeys[i].privatekey); c->pkeys[i].privatekey = NULL; /* clear error queue */ ERR_clear_error(); } } if (!X509_up_ref(x)) return 0; X509_free(c->pkeys[i].x509); c->pkeys[i].x509 = x; c->key = &(c->pkeys[i]); return 1; } int SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file, int type) { int j = SSL_R_BAD_VALUE; BIO *in = NULL; int ret = 0; X509 *x = NULL, *cert = NULL; if (file == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER); goto end; } in = BIO_new(BIO_s_file()); if (in == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_BUF_LIB); goto end; } if (BIO_read_filename(in, file) <= 0) { ERR_raise(ERR_LIB_SSL, ERR_R_SYS_LIB); goto end; } x = X509_new_ex(ctx->libctx, ctx->propq); if (x == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_ASN1_LIB); goto end; } if (type == SSL_FILETYPE_ASN1) { j = ERR_R_ASN1_LIB; cert = d2i_X509_bio(in, &x); } else if (type == SSL_FILETYPE_PEM) { j = ERR_R_PEM_LIB; cert = PEM_read_bio_X509(in, &x, ctx->default_passwd_callback, ctx->default_passwd_callback_userdata); } else { ERR_raise(ERR_LIB_SSL, SSL_R_BAD_SSL_FILETYPE); goto end; } if (cert == NULL) { ERR_raise(ERR_LIB_SSL, j); goto end; } ret = SSL_CTX_use_certificate(ctx, x); end: X509_free(x); BIO_free(in); return ret; } int SSL_CTX_use_certificate_ASN1(SSL_CTX *ctx, int len, const unsigned char *d) { X509 *x; int ret; x = X509_new_ex(ctx->libctx, ctx->propq); if (x == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_ASN1_LIB); return 0; } if (d2i_X509(&x, &d, (long)len) == NULL) { X509_free(x); ERR_raise(ERR_LIB_SSL, ERR_R_ASN1_LIB); return 0; } ret = SSL_CTX_use_certificate(ctx, x); X509_free(x); return ret; } int SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey) { if (pkey == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER); return 0; } return ssl_set_pkey(ctx->cert, pkey, ctx); } int SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file, int type) { int j, ret = 0; BIO *in = NULL; EVP_PKEY *pkey = NULL; if (file == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER); goto end; } in = BIO_new(BIO_s_file()); if (in == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_BUF_LIB); goto end; } if (BIO_read_filename(in, file) <= 0) { ERR_raise(ERR_LIB_SSL, ERR_R_SYS_LIB); goto end; } if (type == SSL_FILETYPE_PEM) { j = ERR_R_PEM_LIB; pkey = PEM_read_bio_PrivateKey_ex(in, NULL, ctx->default_passwd_callback, ctx->default_passwd_callback_userdata, ctx->libctx, ctx->propq); } else if (type == SSL_FILETYPE_ASN1) { j = ERR_R_ASN1_LIB; pkey = d2i_PrivateKey_ex_bio(in, NULL, ctx->libctx, ctx->propq); } else { ERR_raise(ERR_LIB_SSL, SSL_R_BAD_SSL_FILETYPE); goto end; } if (pkey == NULL) { ERR_raise(ERR_LIB_SSL, j); goto end; } ret = SSL_CTX_use_PrivateKey(ctx, pkey); EVP_PKEY_free(pkey); end: BIO_free(in); return ret; } int SSL_CTX_use_PrivateKey_ASN1(int type, SSL_CTX *ctx, const unsigned char *d, long len) { int ret; const unsigned char *p; EVP_PKEY *pkey; p = d; if ((pkey = d2i_PrivateKey_ex(type, NULL, &p, (long)len, ctx->libctx, ctx->propq)) == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_ASN1_LIB); return 0; } ret = SSL_CTX_use_PrivateKey(ctx, pkey); EVP_PKEY_free(pkey); return ret; } /* * Read a file that contains our certificate in "PEM" format, possibly * followed by a sequence of CA certificates that should be sent to the peer * in the Certificate message. */ static int use_certificate_chain_file(SSL_CTX *ctx, SSL *ssl, const char *file) { BIO *in = NULL; int ret = 0; X509 *x = NULL; pem_password_cb *passwd_callback; void *passwd_callback_userdata; SSL_CTX *real_ctx = (ssl == NULL) ? ctx : ssl->ctx; if (ctx == NULL && ssl == NULL) return 0; ERR_clear_error(); /* clear error stack for * SSL_CTX_use_certificate() */ if (ctx != NULL) { passwd_callback = ctx->default_passwd_callback; passwd_callback_userdata = ctx->default_passwd_callback_userdata; } else { SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl); if (sc == NULL) return 0; passwd_callback = sc->default_passwd_callback; passwd_callback_userdata = sc->default_passwd_callback_userdata; } if (file == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER); goto end; } in = BIO_new(BIO_s_file()); if (in == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_BUF_LIB); goto end; } if (BIO_read_filename(in, file) <= 0) { ERR_raise(ERR_LIB_SSL, ERR_R_SYS_LIB); goto end; } x = X509_new_ex(real_ctx->libctx, real_ctx->propq); if (x == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_ASN1_LIB); goto end; } if (PEM_read_bio_X509_AUX(in, &x, passwd_callback, passwd_callback_userdata) == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_PEM_LIB); goto end; } if (ctx) ret = SSL_CTX_use_certificate(ctx, x); else ret = SSL_use_certificate(ssl, x); if (ERR_peek_error() != 0) ret = 0; /* Key/certificate mismatch doesn't imply * ret==0 ... */ if (ret) { /* * If we could set up our certificate, now proceed to the CA * certificates. */ X509 *ca; int r; unsigned long err; if (ctx) r = SSL_CTX_clear_chain_certs(ctx); else r = SSL_clear_chain_certs(ssl); if (r == 0) { ret = 0; goto end; } while (1) { ca = X509_new_ex(real_ctx->libctx, real_ctx->propq); if (ca == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_ASN1_LIB); goto end; } if (PEM_read_bio_X509(in, &ca, passwd_callback, passwd_callback_userdata) != NULL) { if (ctx) r = SSL_CTX_add0_chain_cert(ctx, ca); else r = SSL_add0_chain_cert(ssl, ca); /* * Note that we must not free ca if it was successfully added to * the chain (while we must free the main certificate, since its * reference count is increased by SSL_CTX_use_certificate). */ if (!r) { X509_free(ca); ret = 0; goto end; } } else { X509_free(ca); break; } } /* When the while loop ends, it's usually just EOF. */ err = ERR_peek_last_error(); if (ERR_GET_LIB(err) == ERR_LIB_PEM && ERR_GET_REASON(err) == PEM_R_NO_START_LINE) ERR_clear_error(); else ret = 0; /* some real error */ } end: X509_free(x); BIO_free(in); return ret; } int SSL_CTX_use_certificate_chain_file(SSL_CTX *ctx, const char *file) { return use_certificate_chain_file(ctx, NULL, file); } int SSL_use_certificate_chain_file(SSL *ssl, const char *file) { return use_certificate_chain_file(NULL, ssl, file); } static int serverinfo_find_extension(const unsigned char *serverinfo, size_t serverinfo_length, unsigned int extension_type, const unsigned char **extension_data, size_t *extension_length) { PACKET pkt, data; *extension_data = NULL; *extension_length = 0; if (serverinfo == NULL || serverinfo_length == 0) return -1; if (!PACKET_buf_init(&pkt, serverinfo, serverinfo_length)) return -1; for (;;) { unsigned int type = 0; unsigned long context = 0; /* end of serverinfo */ if (PACKET_remaining(&pkt) == 0) return 0; /* Extension not found */ if (!PACKET_get_net_4(&pkt, &context) || !PACKET_get_net_2(&pkt, &type) || !PACKET_get_length_prefixed_2(&pkt, &data)) return -1; if (type == extension_type) { *extension_data = PACKET_data(&data); *extension_length = PACKET_remaining(&data); return 1; /* Success */ } } /* Unreachable */ } static int serverinfoex_srv_parse_cb(SSL *s, unsigned int ext_type, unsigned int context, const unsigned char *in, size_t inlen, X509 *x, size_t chainidx, int *al, void *arg) { if (inlen != 0) { *al = SSL_AD_DECODE_ERROR; return 0; } return 1; } static int serverinfo_srv_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *arg) { return serverinfoex_srv_parse_cb(s, ext_type, 0, in, inlen, NULL, 0, al, arg); } static int serverinfoex_srv_add_cb(SSL *s, unsigned int ext_type, unsigned int context, const unsigned char **out, size_t *outlen, X509 *x, size_t chainidx, int *al, void *arg) { const unsigned char *serverinfo = NULL; size_t serverinfo_length = 0; SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s); if (sc == NULL) { *al = SSL_AD_INTERNAL_ERROR; return -1; } /* We only support extensions for the first Certificate */ if ((context & SSL_EXT_TLS1_3_CERTIFICATE) != 0 && chainidx > 0) return 0; /* Is there serverinfo data for the chosen server cert? */ if ((ssl_get_server_cert_serverinfo(sc, &serverinfo, &serverinfo_length)) != 0) { /* Find the relevant extension from the serverinfo */ int retval = serverinfo_find_extension(serverinfo, serverinfo_length, ext_type, out, outlen); if (retval == -1) { *al = SSL_AD_INTERNAL_ERROR; return -1; /* Error */ } if (retval == 0) return 0; /* No extension found, don't send extension */ return 1; /* Send extension */ } return 0; /* No serverinfo data found, don't send * extension */ } static int serverinfo_srv_add_cb(SSL *s, unsigned int ext_type, const unsigned char **out, size_t *outlen, int *al, void *arg) { return serverinfoex_srv_add_cb(s, ext_type, 0, out, outlen, NULL, 0, al, arg); } /* * With a NULL context, this function just checks that the serverinfo data * parses correctly. With a non-NULL context, it registers callbacks for * the included extensions. */ static int serverinfo_process_buffer(unsigned int version, const unsigned char *serverinfo, size_t serverinfo_length, SSL_CTX *ctx) { PACKET pkt; if (serverinfo == NULL || serverinfo_length == 0) return 0; if (version != SSL_SERVERINFOV1 && version != SSL_SERVERINFOV2) return 0; if (!PACKET_buf_init(&pkt, serverinfo, serverinfo_length)) return 0; while (PACKET_remaining(&pkt)) { unsigned long context = 0; unsigned int ext_type = 0; PACKET data; if ((version == SSL_SERVERINFOV2 && !PACKET_get_net_4(&pkt, &context)) || !PACKET_get_net_2(&pkt, &ext_type) || !PACKET_get_length_prefixed_2(&pkt, &data)) return 0; if (ctx == NULL) continue; /* * The old style custom extensions API could be set separately for * server/client, i.e. you could set one custom extension for a client, * and *for the same extension in the same SSL_CTX* you could set a * custom extension for the server as well. It seems quite weird to be * setting a custom extension for both client and server in a single * SSL_CTX - but theoretically possible. This isn't possible in the * new API. Therefore, if we have V1 serverinfo we use the old API. We * also use the old API even if we have V2 serverinfo but the context * looks like an old style <= TLSv1.2 extension. */ if (version == SSL_SERVERINFOV1 || context == SYNTHV1CONTEXT) { if (!SSL_CTX_add_server_custom_ext(ctx, ext_type, serverinfo_srv_add_cb, NULL, NULL, serverinfo_srv_parse_cb, NULL)) return 0; } else { if (!SSL_CTX_add_custom_ext(ctx, ext_type, context, serverinfoex_srv_add_cb, NULL, NULL, serverinfoex_srv_parse_cb, NULL)) return 0; } } return 1; } static size_t extension_contextoff(unsigned int version) { return version == SSL_SERVERINFOV1 ? 4 : 0; } static size_t extension_append_length(unsigned int version, size_t extension_length) { return extension_length + extension_contextoff(version); } static void extension_append(unsigned int version, const unsigned char *extension, const size_t extension_length, unsigned char *serverinfo) { const size_t contextoff = extension_contextoff(version); if (contextoff > 0) { /* We know this only uses the last 2 bytes */ serverinfo[0] = 0; serverinfo[1] = 0; serverinfo[2] = (SYNTHV1CONTEXT >> 8) & 0xff; serverinfo[3] = SYNTHV1CONTEXT & 0xff; } memcpy(serverinfo + contextoff, extension, extension_length); } int SSL_CTX_use_serverinfo_ex(SSL_CTX *ctx, unsigned int version, const unsigned char *serverinfo, size_t serverinfo_length) { unsigned char *new_serverinfo = NULL; if (ctx == NULL || serverinfo == NULL || serverinfo_length == 0) { ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (version == SSL_SERVERINFOV1) { /* * Convert serverinfo version v1 to v2 and call yourself recursively * over the converted serverinfo. */ const size_t sinfo_length = extension_append_length(SSL_SERVERINFOV1, serverinfo_length); unsigned char *sinfo; int ret; sinfo = OPENSSL_malloc(sinfo_length); if (sinfo == NULL) return 0; extension_append(SSL_SERVERINFOV1, serverinfo, serverinfo_length, sinfo); ret = SSL_CTX_use_serverinfo_ex(ctx, SSL_SERVERINFOV2, sinfo, sinfo_length); OPENSSL_free(sinfo); return ret; } if (!serverinfo_process_buffer(version, serverinfo, serverinfo_length, NULL)) { ERR_raise(ERR_LIB_SSL, SSL_R_INVALID_SERVERINFO_DATA); return 0; } if (ctx->cert->key == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR); return 0; } new_serverinfo = OPENSSL_realloc(ctx->cert->key->serverinfo, serverinfo_length); if (new_serverinfo == NULL) return 0; ctx->cert->key->serverinfo = new_serverinfo; memcpy(ctx->cert->key->serverinfo, serverinfo, serverinfo_length); ctx->cert->key->serverinfo_length = serverinfo_length; /* * Now that the serverinfo is validated and stored, go ahead and * register callbacks. */ if (!serverinfo_process_buffer(version, serverinfo, serverinfo_length, ctx)) { ERR_raise(ERR_LIB_SSL, SSL_R_INVALID_SERVERINFO_DATA); return 0; } return 1; } int SSL_CTX_use_serverinfo(SSL_CTX *ctx, const unsigned char *serverinfo, size_t serverinfo_length) { return SSL_CTX_use_serverinfo_ex(ctx, SSL_SERVERINFOV1, serverinfo, serverinfo_length); } int SSL_CTX_use_serverinfo_file(SSL_CTX *ctx, const char *file) { unsigned char *serverinfo = NULL; unsigned char *tmp; size_t serverinfo_length = 0; unsigned char *extension = 0; long extension_length = 0; char *name = NULL; char *header = NULL; unsigned int name_len; int ret = 0; BIO *bin = NULL; size_t num_extensions = 0; if (ctx == NULL || file == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER); goto end; } bin = BIO_new(BIO_s_file()); if (bin == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_BUF_LIB); goto end; } if (BIO_read_filename(bin, file) <= 0) { ERR_raise(ERR_LIB_SSL, ERR_R_SYS_LIB); goto end; } for (num_extensions = 0;; num_extensions++) { unsigned int version; size_t append_length; if (PEM_read_bio(bin, &name, &header, &extension, &extension_length) == 0) { /* * There must be at least one extension in this file */ if (num_extensions == 0) { ERR_raise(ERR_LIB_SSL, SSL_R_NO_PEM_EXTENSIONS); goto end; } else /* End of file, we're done */ break; } /* Check that PEM name starts with "BEGIN SERVERINFO FOR " */ name_len = strlen(name); if (name_len < sizeof(NAME_PREFIX1) - 1) { ERR_raise(ERR_LIB_SSL, SSL_R_PEM_NAME_TOO_SHORT); goto end; } if (HAS_PREFIX(name, NAME_PREFIX1)) { version = SSL_SERVERINFOV1; } else { if (name_len < sizeof(NAME_PREFIX2) - 1) { ERR_raise(ERR_LIB_SSL, SSL_R_PEM_NAME_TOO_SHORT); goto end; } if (!HAS_PREFIX(name, NAME_PREFIX2)) { ERR_raise(ERR_LIB_SSL, SSL_R_PEM_NAME_BAD_PREFIX); goto end; } version = SSL_SERVERINFOV2; } /* * Check that the decoded PEM data is plausible (valid length field) */ if (version == SSL_SERVERINFOV1) { /* 4 byte header: 2 bytes type, 2 bytes len */ if (extension_length < 4 || (extension[2] << 8) + extension[3] != extension_length - 4) { ERR_raise(ERR_LIB_SSL, SSL_R_BAD_DATA); goto end; } } else { /* 8 byte header: 4 bytes context, 2 bytes type, 2 bytes len */ if (extension_length < 8 || (extension[6] << 8) + extension[7] != extension_length - 8) { ERR_raise(ERR_LIB_SSL, SSL_R_BAD_DATA); goto end; } } /* Append the decoded extension to the serverinfo buffer */ append_length = extension_append_length(version, extension_length); tmp = OPENSSL_realloc(serverinfo, serverinfo_length + append_length); if (tmp == NULL) goto end; serverinfo = tmp; extension_append(version, extension, extension_length, serverinfo + serverinfo_length); serverinfo_length += append_length; OPENSSL_free(name); name = NULL; OPENSSL_free(header); header = NULL; OPENSSL_free(extension); extension = NULL; } ret = SSL_CTX_use_serverinfo_ex(ctx, SSL_SERVERINFOV2, serverinfo, serverinfo_length); end: /* SSL_CTX_use_serverinfo makes a local copy of the serverinfo. */ OPENSSL_free(name); OPENSSL_free(header); OPENSSL_free(extension); OPENSSL_free(serverinfo); BIO_free(bin); return ret; } static int ssl_set_cert_and_key(SSL *ssl, SSL_CTX *ctx, X509 *x509, EVP_PKEY *privatekey, STACK_OF(X509) *chain, int override) { int ret = 0; size_t i; int j; int rv; CERT *c; STACK_OF(X509) *dup_chain = NULL; EVP_PKEY *pubkey = NULL; SSL_CONNECTION *sc = NULL; if (ctx == NULL && (sc = SSL_CONNECTION_FROM_SSL(ssl)) == NULL) return 0; c = sc != NULL ? sc->cert : ctx->cert; /* Do all security checks before anything else */ rv = ssl_security_cert(sc, ctx, x509, 0, 1); if (rv != 1) { ERR_raise(ERR_LIB_SSL, rv); goto out; } for (j = 0; j < sk_X509_num(chain); j++) { rv = ssl_security_cert(sc, ctx, sk_X509_value(chain, j), 0, 0); if (rv != 1) { ERR_raise(ERR_LIB_SSL, rv); goto out; } } pubkey = X509_get_pubkey(x509); /* bumps reference */ if (pubkey == NULL) goto out; if (privatekey == NULL) { privatekey = pubkey; } else { /* For RSA, which has no parameters, missing returns 0 */ if (EVP_PKEY_missing_parameters(privatekey)) { if (EVP_PKEY_missing_parameters(pubkey)) { /* nobody has parameters? - error */ ERR_raise(ERR_LIB_SSL, SSL_R_MISSING_PARAMETERS); goto out; } else { /* copy to privatekey from pubkey */ if (!EVP_PKEY_copy_parameters(privatekey, pubkey)) { ERR_raise(ERR_LIB_SSL, SSL_R_COPY_PARAMETERS_FAILED); goto out; } } } else if (EVP_PKEY_missing_parameters(pubkey)) { /* copy to pubkey from privatekey */ if (!EVP_PKEY_copy_parameters(pubkey, privatekey)) { ERR_raise(ERR_LIB_SSL, SSL_R_COPY_PARAMETERS_FAILED); goto out; } } /* else both have parameters */ /* check that key <-> cert match */ if (EVP_PKEY_eq(pubkey, privatekey) != 1) { ERR_raise(ERR_LIB_SSL, SSL_R_PRIVATE_KEY_MISMATCH); goto out; } } if (ssl_cert_lookup_by_pkey(pubkey, &i, ctx) == NULL) { ERR_raise(ERR_LIB_SSL, SSL_R_UNKNOWN_CERTIFICATE_TYPE); goto out; } if (!override && (c->pkeys[i].x509 != NULL || c->pkeys[i].privatekey != NULL || c->pkeys[i].chain != NULL)) { /* No override, and something already there */ ERR_raise(ERR_LIB_SSL, SSL_R_NOT_REPLACING_CERTIFICATE); goto out; } if (chain != NULL) { dup_chain = X509_chain_up_ref(chain); if (dup_chain == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_X509_LIB); goto out; } } - if (!X509_up_ref(x509)) + if (!X509_up_ref(x509)) { + OSSL_STACK_OF_X509_free(dup_chain); goto out; + } if (!EVP_PKEY_up_ref(privatekey)) { + OSSL_STACK_OF_X509_free(dup_chain); X509_free(x509); goto out; } OSSL_STACK_OF_X509_free(c->pkeys[i].chain); c->pkeys[i].chain = dup_chain; X509_free(c->pkeys[i].x509); c->pkeys[i].x509 = x509; EVP_PKEY_free(c->pkeys[i].privatekey); c->pkeys[i].privatekey = privatekey; c->key = &(c->pkeys[i]); ret = 1; out: EVP_PKEY_free(pubkey); return ret; } int SSL_use_cert_and_key(SSL *ssl, X509 *x509, EVP_PKEY *privatekey, STACK_OF(X509) *chain, int override) { return ssl_set_cert_and_key(ssl, NULL, x509, privatekey, chain, override); } int SSL_CTX_use_cert_and_key(SSL_CTX *ctx, X509 *x509, EVP_PKEY *privatekey, STACK_OF(X509) *chain, int override) { return ssl_set_cert_and_key(NULL, ctx, x509, privatekey, chain, override); } diff --git a/ssl/t1_trce.c b/ssl/t1_trce.c index 35c60feb4371..73fd4ebaa4b0 100644 --- a/ssl/t1_trce.c +++ b/ssl/t1_trce.c @@ -1,1806 +1,1810 @@ /* * Copyright 2012-2025 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 "ssl_local.h" #ifndef OPENSSL_NO_SSL_TRACE /* Packet trace support for OpenSSL */ #include "internal/nelem.h" #include "internal/ssl_unwrap.h" #include "internal/quic_trace.h" typedef struct { int num; const char *name; } ssl_trace_tbl; # define ssl_trace_str(val, tbl) \ do_ssl_trace_str(val, tbl, OSSL_NELEM(tbl)) # define ssl_trace_list(bio, indent, msg, msglen, value, table) \ do_ssl_trace_list(bio, indent, msg, msglen, value, \ table, OSSL_NELEM(table)) static const char *do_ssl_trace_str(int val, const ssl_trace_tbl *tbl, size_t ntbl) { size_t i; for (i = 0; i < ntbl; i++, tbl++) { if (tbl->num == val) return tbl->name; } return "UNKNOWN"; } static int do_ssl_trace_list(BIO *bio, int indent, const unsigned char *msg, size_t msglen, size_t vlen, const ssl_trace_tbl *tbl, size_t ntbl) { int val; if (msglen % vlen) return 0; while (msglen) { val = msg[0]; if (vlen == 2) val = (val << 8) | msg[1]; BIO_indent(bio, indent, 80); BIO_printf(bio, "%s (%d)\n", do_ssl_trace_str(val, tbl, ntbl), val); msg += vlen; msglen -= vlen; } return 1; } /* Version number */ static const ssl_trace_tbl ssl_version_tbl[] = { {SSL3_VERSION, "SSL 3.0"}, {TLS1_VERSION, "TLS 1.0"}, {TLS1_1_VERSION, "TLS 1.1"}, {TLS1_2_VERSION, "TLS 1.2"}, {TLS1_3_VERSION, "TLS 1.3"}, {DTLS1_VERSION, "DTLS 1.0"}, {DTLS1_2_VERSION, "DTLS 1.2"}, {DTLS1_BAD_VER, "DTLS 1.0 (bad)"} }; static const ssl_trace_tbl ssl_content_tbl[] = { {SSL3_RT_CHANGE_CIPHER_SPEC, "ChangeCipherSpec"}, {SSL3_RT_ALERT, "Alert"}, {SSL3_RT_HANDSHAKE, "Handshake"}, {SSL3_RT_APPLICATION_DATA, "ApplicationData"}, }; /* Handshake types, sorted by ascending id */ static const ssl_trace_tbl ssl_handshake_tbl[] = { {SSL3_MT_HELLO_REQUEST, "HelloRequest"}, {SSL3_MT_CLIENT_HELLO, "ClientHello"}, {SSL3_MT_SERVER_HELLO, "ServerHello"}, {DTLS1_MT_HELLO_VERIFY_REQUEST, "HelloVerifyRequest"}, {SSL3_MT_NEWSESSION_TICKET, "NewSessionTicket"}, {SSL3_MT_END_OF_EARLY_DATA, "EndOfEarlyData"}, {SSL3_MT_ENCRYPTED_EXTENSIONS, "EncryptedExtensions"}, {SSL3_MT_CERTIFICATE, "Certificate"}, {SSL3_MT_SERVER_KEY_EXCHANGE, "ServerKeyExchange"}, {SSL3_MT_CERTIFICATE_REQUEST, "CertificateRequest"}, {SSL3_MT_SERVER_DONE, "ServerHelloDone"}, {SSL3_MT_CERTIFICATE_VERIFY, "CertificateVerify"}, {SSL3_MT_CLIENT_KEY_EXCHANGE, "ClientKeyExchange"}, {SSL3_MT_FINISHED, "Finished"}, {SSL3_MT_CERTIFICATE_URL, "CertificateUrl"}, {SSL3_MT_CERTIFICATE_STATUS, "CertificateStatus"}, {SSL3_MT_SUPPLEMENTAL_DATA, "SupplementalData"}, {SSL3_MT_KEY_UPDATE, "KeyUpdate"}, {SSL3_MT_COMPRESSED_CERTIFICATE, "CompressedCertificate"}, # ifndef OPENSSL_NO_NEXTPROTONEG {SSL3_MT_NEXT_PROTO, "NextProto"}, # endif {SSL3_MT_MESSAGE_HASH, "MessageHash"} }; /* Cipher suites */ static const ssl_trace_tbl ssl_ciphers_tbl[] = { {0x0000, "TLS_NULL_WITH_NULL_NULL"}, {0x0001, "TLS_RSA_WITH_NULL_MD5"}, {0x0002, "TLS_RSA_WITH_NULL_SHA"}, {0x0003, "TLS_RSA_EXPORT_WITH_RC4_40_MD5"}, {0x0004, "TLS_RSA_WITH_RC4_128_MD5"}, {0x0005, "TLS_RSA_WITH_RC4_128_SHA"}, {0x0006, "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5"}, {0x0007, "TLS_RSA_WITH_IDEA_CBC_SHA"}, {0x0008, "TLS_RSA_EXPORT_WITH_DES40_CBC_SHA"}, {0x0009, "TLS_RSA_WITH_DES_CBC_SHA"}, {0x000A, "TLS_RSA_WITH_3DES_EDE_CBC_SHA"}, {0x000B, "TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA"}, {0x000C, "TLS_DH_DSS_WITH_DES_CBC_SHA"}, {0x000D, "TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA"}, {0x000E, "TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA"}, {0x000F, "TLS_DH_RSA_WITH_DES_CBC_SHA"}, {0x0010, "TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA"}, {0x0011, "TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"}, {0x0012, "TLS_DHE_DSS_WITH_DES_CBC_SHA"}, {0x0013, "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA"}, {0x0014, "TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA"}, {0x0015, "TLS_DHE_RSA_WITH_DES_CBC_SHA"}, {0x0016, "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA"}, {0x0017, "TLS_DH_anon_EXPORT_WITH_RC4_40_MD5"}, {0x0018, "TLS_DH_anon_WITH_RC4_128_MD5"}, {0x0019, "TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA"}, {0x001A, "TLS_DH_anon_WITH_DES_CBC_SHA"}, {0x001B, "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA"}, {0x001D, "SSL_FORTEZZA_KEA_WITH_FORTEZZA_CBC_SHA"}, {0x001E, "SSL_FORTEZZA_KEA_WITH_RC4_128_SHA"}, {0x001F, "TLS_KRB5_WITH_3DES_EDE_CBC_SHA"}, {0x0020, "TLS_KRB5_WITH_RC4_128_SHA"}, {0x0021, "TLS_KRB5_WITH_IDEA_CBC_SHA"}, {0x0022, "TLS_KRB5_WITH_DES_CBC_MD5"}, {0x0023, "TLS_KRB5_WITH_3DES_EDE_CBC_MD5"}, {0x0024, "TLS_KRB5_WITH_RC4_128_MD5"}, {0x0025, "TLS_KRB5_WITH_IDEA_CBC_MD5"}, {0x0026, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA"}, {0x0027, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA"}, {0x0028, "TLS_KRB5_EXPORT_WITH_RC4_40_SHA"}, {0x0029, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5"}, {0x002A, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5"}, {0x002B, "TLS_KRB5_EXPORT_WITH_RC4_40_MD5"}, {0x002C, "TLS_PSK_WITH_NULL_SHA"}, {0x002D, "TLS_DHE_PSK_WITH_NULL_SHA"}, {0x002E, "TLS_RSA_PSK_WITH_NULL_SHA"}, {0x002F, "TLS_RSA_WITH_AES_128_CBC_SHA"}, {0x0030, "TLS_DH_DSS_WITH_AES_128_CBC_SHA"}, {0x0031, "TLS_DH_RSA_WITH_AES_128_CBC_SHA"}, {0x0032, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA"}, {0x0033, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"}, {0x0034, "TLS_DH_anon_WITH_AES_128_CBC_SHA"}, {0x0035, "TLS_RSA_WITH_AES_256_CBC_SHA"}, {0x0036, "TLS_DH_DSS_WITH_AES_256_CBC_SHA"}, {0x0037, "TLS_DH_RSA_WITH_AES_256_CBC_SHA"}, {0x0038, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA"}, {0x0039, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"}, {0x003A, "TLS_DH_anon_WITH_AES_256_CBC_SHA"}, {0x003B, "TLS_RSA_WITH_NULL_SHA256"}, {0x003C, "TLS_RSA_WITH_AES_128_CBC_SHA256"}, {0x003D, "TLS_RSA_WITH_AES_256_CBC_SHA256"}, {0x003E, "TLS_DH_DSS_WITH_AES_128_CBC_SHA256"}, {0x003F, "TLS_DH_RSA_WITH_AES_128_CBC_SHA256"}, {0x0040, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256"}, {0x0041, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA"}, {0x0042, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA"}, {0x0043, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA"}, {0x0044, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA"}, {0x0045, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA"}, {0x0046, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA"}, {0x0067, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256"}, {0x0068, "TLS_DH_DSS_WITH_AES_256_CBC_SHA256"}, {0x0069, "TLS_DH_RSA_WITH_AES_256_CBC_SHA256"}, {0x006A, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"}, {0x006B, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256"}, {0x006C, "TLS_DH_anon_WITH_AES_128_CBC_SHA256"}, {0x006D, "TLS_DH_anon_WITH_AES_256_CBC_SHA256"}, {0x0081, "TLS_GOSTR341001_WITH_28147_CNT_IMIT"}, {0x0083, "TLS_GOSTR341001_WITH_NULL_GOSTR3411"}, {0x0084, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA"}, {0x0085, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA"}, {0x0086, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA"}, {0x0087, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA"}, {0x0088, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA"}, {0x0089, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA"}, {0x008A, "TLS_PSK_WITH_RC4_128_SHA"}, {0x008B, "TLS_PSK_WITH_3DES_EDE_CBC_SHA"}, {0x008C, "TLS_PSK_WITH_AES_128_CBC_SHA"}, {0x008D, "TLS_PSK_WITH_AES_256_CBC_SHA"}, {0x008E, "TLS_DHE_PSK_WITH_RC4_128_SHA"}, {0x008F, "TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA"}, {0x0090, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA"}, {0x0091, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA"}, {0x0092, "TLS_RSA_PSK_WITH_RC4_128_SHA"}, {0x0093, "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA"}, {0x0094, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA"}, {0x0095, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA"}, {0x0096, "TLS_RSA_WITH_SEED_CBC_SHA"}, {0x0097, "TLS_DH_DSS_WITH_SEED_CBC_SHA"}, {0x0098, "TLS_DH_RSA_WITH_SEED_CBC_SHA"}, {0x0099, "TLS_DHE_DSS_WITH_SEED_CBC_SHA"}, {0x009A, "TLS_DHE_RSA_WITH_SEED_CBC_SHA"}, {0x009B, "TLS_DH_anon_WITH_SEED_CBC_SHA"}, {0x009C, "TLS_RSA_WITH_AES_128_GCM_SHA256"}, {0x009D, "TLS_RSA_WITH_AES_256_GCM_SHA384"}, {0x009E, "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256"}, {0x009F, "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384"}, {0x00A0, "TLS_DH_RSA_WITH_AES_128_GCM_SHA256"}, {0x00A1, "TLS_DH_RSA_WITH_AES_256_GCM_SHA384"}, {0x00A2, "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256"}, {0x00A3, "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384"}, {0x00A4, "TLS_DH_DSS_WITH_AES_128_GCM_SHA256"}, {0x00A5, "TLS_DH_DSS_WITH_AES_256_GCM_SHA384"}, {0x00A6, "TLS_DH_anon_WITH_AES_128_GCM_SHA256"}, {0x00A7, "TLS_DH_anon_WITH_AES_256_GCM_SHA384"}, {0x00A8, "TLS_PSK_WITH_AES_128_GCM_SHA256"}, {0x00A9, "TLS_PSK_WITH_AES_256_GCM_SHA384"}, {0x00AA, "TLS_DHE_PSK_WITH_AES_128_GCM_SHA256"}, {0x00AB, "TLS_DHE_PSK_WITH_AES_256_GCM_SHA384"}, {0x00AC, "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256"}, {0x00AD, "TLS_RSA_PSK_WITH_AES_256_GCM_SHA384"}, {0x00AE, "TLS_PSK_WITH_AES_128_CBC_SHA256"}, {0x00AF, "TLS_PSK_WITH_AES_256_CBC_SHA384"}, {0x00B0, "TLS_PSK_WITH_NULL_SHA256"}, {0x00B1, "TLS_PSK_WITH_NULL_SHA384"}, {0x00B2, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA256"}, {0x00B3, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA384"}, {0x00B4, "TLS_DHE_PSK_WITH_NULL_SHA256"}, {0x00B5, "TLS_DHE_PSK_WITH_NULL_SHA384"}, {0x00B6, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA256"}, {0x00B7, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA384"}, {0x00B8, "TLS_RSA_PSK_WITH_NULL_SHA256"}, {0x00B9, "TLS_RSA_PSK_WITH_NULL_SHA384"}, {0x00BA, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256"}, {0x00BB, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256"}, {0x00BC, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256"}, {0x00BD, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256"}, {0x00BE, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256"}, {0x00BF, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256"}, {0x00C0, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256"}, {0x00C1, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256"}, {0x00C2, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256"}, {0x00C3, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256"}, {0x00C4, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256"}, {0x00C5, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256"}, {0x00FF, "TLS_EMPTY_RENEGOTIATION_INFO_SCSV"}, {0x5600, "TLS_FALLBACK_SCSV"}, {0xC001, "TLS_ECDH_ECDSA_WITH_NULL_SHA"}, {0xC002, "TLS_ECDH_ECDSA_WITH_RC4_128_SHA"}, {0xC003, "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA"}, {0xC004, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA"}, {0xC005, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA"}, {0xC006, "TLS_ECDHE_ECDSA_WITH_NULL_SHA"}, {0xC007, "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA"}, {0xC008, "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA"}, {0xC009, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA"}, {0xC00A, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA"}, {0xC00B, "TLS_ECDH_RSA_WITH_NULL_SHA"}, {0xC00C, "TLS_ECDH_RSA_WITH_RC4_128_SHA"}, {0xC00D, "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA"}, {0xC00E, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA"}, {0xC00F, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA"}, {0xC010, "TLS_ECDHE_RSA_WITH_NULL_SHA"}, {0xC011, "TLS_ECDHE_RSA_WITH_RC4_128_SHA"}, {0xC012, "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA"}, {0xC013, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"}, {0xC014, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"}, {0xC015, "TLS_ECDH_anon_WITH_NULL_SHA"}, {0xC016, "TLS_ECDH_anon_WITH_RC4_128_SHA"}, {0xC017, "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA"}, {0xC018, "TLS_ECDH_anon_WITH_AES_128_CBC_SHA"}, {0xC019, "TLS_ECDH_anon_WITH_AES_256_CBC_SHA"}, {0xC01A, "TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA"}, {0xC01B, "TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA"}, {0xC01C, "TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA"}, {0xC01D, "TLS_SRP_SHA_WITH_AES_128_CBC_SHA"}, {0xC01E, "TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA"}, {0xC01F, "TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA"}, {0xC020, "TLS_SRP_SHA_WITH_AES_256_CBC_SHA"}, {0xC021, "TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA"}, {0xC022, "TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA"}, {0xC023, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"}, {0xC024, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384"}, {0xC025, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256"}, {0xC026, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384"}, {0xC027, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"}, {0xC028, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"}, {0xC029, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256"}, {0xC02A, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384"}, {0xC02B, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"}, {0xC02C, "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"}, {0xC02D, "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256"}, {0xC02E, "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384"}, {0xC02F, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"}, {0xC030, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"}, {0xC031, "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256"}, {0xC032, "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384"}, {0xC033, "TLS_ECDHE_PSK_WITH_RC4_128_SHA"}, {0xC034, "TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA"}, {0xC035, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA"}, {0xC036, "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA"}, {0xC037, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256"}, {0xC038, "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384"}, {0xC039, "TLS_ECDHE_PSK_WITH_NULL_SHA"}, {0xC03A, "TLS_ECDHE_PSK_WITH_NULL_SHA256"}, {0xC03B, "TLS_ECDHE_PSK_WITH_NULL_SHA384"}, {0xC03C, "TLS_RSA_WITH_ARIA_128_CBC_SHA256"}, {0xC03D, "TLS_RSA_WITH_ARIA_256_CBC_SHA384"}, {0xC03E, "TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256"}, {0xC03F, "TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384"}, {0xC040, "TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256"}, {0xC041, "TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384"}, {0xC042, "TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256"}, {0xC043, "TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384"}, {0xC044, "TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256"}, {0xC045, "TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384"}, {0xC046, "TLS_DH_anon_WITH_ARIA_128_CBC_SHA256"}, {0xC047, "TLS_DH_anon_WITH_ARIA_256_CBC_SHA384"}, {0xC048, "TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256"}, {0xC049, "TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384"}, {0xC04A, "TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256"}, {0xC04B, "TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384"}, {0xC04C, "TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256"}, {0xC04D, "TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384"}, {0xC04E, "TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256"}, {0xC04F, "TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384"}, {0xC050, "TLS_RSA_WITH_ARIA_128_GCM_SHA256"}, {0xC051, "TLS_RSA_WITH_ARIA_256_GCM_SHA384"}, {0xC052, "TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256"}, {0xC053, "TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384"}, {0xC054, "TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256"}, {0xC055, "TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384"}, {0xC056, "TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256"}, {0xC057, "TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384"}, {0xC058, "TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256"}, {0xC059, "TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384"}, {0xC05A, "TLS_DH_anon_WITH_ARIA_128_GCM_SHA256"}, {0xC05B, "TLS_DH_anon_WITH_ARIA_256_GCM_SHA384"}, {0xC05C, "TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256"}, {0xC05D, "TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384"}, {0xC05E, "TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256"}, {0xC05F, "TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384"}, {0xC060, "TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256"}, {0xC061, "TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384"}, {0xC062, "TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256"}, {0xC063, "TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384"}, {0xC064, "TLS_PSK_WITH_ARIA_128_CBC_SHA256"}, {0xC065, "TLS_PSK_WITH_ARIA_256_CBC_SHA384"}, {0xC066, "TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256"}, {0xC067, "TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384"}, {0xC068, "TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256"}, {0xC069, "TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384"}, {0xC06A, "TLS_PSK_WITH_ARIA_128_GCM_SHA256"}, {0xC06B, "TLS_PSK_WITH_ARIA_256_GCM_SHA384"}, {0xC06C, "TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256"}, {0xC06D, "TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384"}, {0xC06E, "TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256"}, {0xC06F, "TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384"}, {0xC070, "TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256"}, {0xC071, "TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384"}, {0xC072, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256"}, {0xC073, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384"}, {0xC074, "TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256"}, {0xC075, "TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384"}, {0xC076, "TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256"}, {0xC077, "TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384"}, {0xC078, "TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256"}, {0xC079, "TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384"}, {0xC07A, "TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256"}, {0xC07B, "TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384"}, {0xC07C, "TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256"}, {0xC07D, "TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384"}, {0xC07E, "TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256"}, {0xC07F, "TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384"}, {0xC080, "TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256"}, {0xC081, "TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384"}, {0xC082, "TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256"}, {0xC083, "TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384"}, {0xC084, "TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256"}, {0xC085, "TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384"}, {0xC086, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256"}, {0xC087, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384"}, {0xC088, "TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256"}, {0xC089, "TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384"}, {0xC08A, "TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256"}, {0xC08B, "TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384"}, {0xC08C, "TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256"}, {0xC08D, "TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384"}, {0xC08E, "TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256"}, {0xC08F, "TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384"}, {0xC090, "TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256"}, {0xC091, "TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384"}, {0xC092, "TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256"}, {0xC093, "TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384"}, {0xC094, "TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256"}, {0xC095, "TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384"}, {0xC096, "TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256"}, {0xC097, "TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384"}, {0xC098, "TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256"}, {0xC099, "TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384"}, {0xC09A, "TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256"}, {0xC09B, "TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384"}, {0xC09C, "TLS_RSA_WITH_AES_128_CCM"}, {0xC09D, "TLS_RSA_WITH_AES_256_CCM"}, {0xC09E, "TLS_DHE_RSA_WITH_AES_128_CCM"}, {0xC09F, "TLS_DHE_RSA_WITH_AES_256_CCM"}, {0xC0A0, "TLS_RSA_WITH_AES_128_CCM_8"}, {0xC0A1, "TLS_RSA_WITH_AES_256_CCM_8"}, {0xC0A2, "TLS_DHE_RSA_WITH_AES_128_CCM_8"}, {0xC0A3, "TLS_DHE_RSA_WITH_AES_256_CCM_8"}, {0xC0A4, "TLS_PSK_WITH_AES_128_CCM"}, {0xC0A5, "TLS_PSK_WITH_AES_256_CCM"}, {0xC0A6, "TLS_DHE_PSK_WITH_AES_128_CCM"}, {0xC0A7, "TLS_DHE_PSK_WITH_AES_256_CCM"}, {0xC0A8, "TLS_PSK_WITH_AES_128_CCM_8"}, {0xC0A9, "TLS_PSK_WITH_AES_256_CCM_8"}, {0xC0AA, "TLS_PSK_DHE_WITH_AES_128_CCM_8"}, {0xC0AB, "TLS_PSK_DHE_WITH_AES_256_CCM_8"}, {0xC0AC, "TLS_ECDHE_ECDSA_WITH_AES_128_CCM"}, {0xC0AD, "TLS_ECDHE_ECDSA_WITH_AES_256_CCM"}, {0xC0AE, "TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8"}, {0xC0AF, "TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8"}, {0xC102, "IANA-GOST2012-GOST8912-GOST8912"}, {0xCCA8, "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256"}, {0xCCA9, "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256"}, {0xCCAA, "TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256"}, {0xCCAB, "TLS_PSK_WITH_CHACHA20_POLY1305_SHA256"}, {0xCCAC, "TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256"}, {0xCCAD, "TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256"}, {0xCCAE, "TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256"}, {0x1301, "TLS_AES_128_GCM_SHA256"}, {0x1302, "TLS_AES_256_GCM_SHA384"}, {0x1303, "TLS_CHACHA20_POLY1305_SHA256"}, {0x1304, "TLS_AES_128_CCM_SHA256"}, {0x1305, "TLS_AES_128_CCM_8_SHA256"}, {0xFEFE, "SSL_RSA_FIPS_WITH_DES_CBC_SHA"}, {0xFEFF, "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA"}, {0xFF85, "LEGACY-GOST2012-GOST8912-GOST8912"}, {0xFF87, "GOST2012-NULL-GOST12"}, {0xC0B4, "TLS_SHA256_SHA256"}, {0xC0B5, "TLS_SHA384_SHA384"}, {0xC100, "GOST2012-KUZNYECHIK-KUZNYECHIKOMAC"}, {0xC101, "GOST2012-MAGMA-MAGMAOMAC"}, {0xC102, "GOST2012-GOST8912-IANA"}, }; /* Compression methods */ static const ssl_trace_tbl ssl_comp_tbl[] = { {0x0000, "No Compression"}, {0x0001, "Zlib Compression"} }; /* Extensions sorted by ascending id */ static const ssl_trace_tbl ssl_exts_tbl[] = { {TLSEXT_TYPE_server_name, "server_name"}, {TLSEXT_TYPE_max_fragment_length, "max_fragment_length"}, {TLSEXT_TYPE_client_certificate_url, "client_certificate_url"}, {TLSEXT_TYPE_trusted_ca_keys, "trusted_ca_keys"}, {TLSEXT_TYPE_truncated_hmac, "truncated_hmac"}, {TLSEXT_TYPE_status_request, "status_request"}, {TLSEXT_TYPE_user_mapping, "user_mapping"}, {TLSEXT_TYPE_client_authz, "client_authz"}, {TLSEXT_TYPE_server_authz, "server_authz"}, {TLSEXT_TYPE_cert_type, "cert_type"}, {TLSEXT_TYPE_supported_groups, "supported_groups"}, {TLSEXT_TYPE_ec_point_formats, "ec_point_formats"}, {TLSEXT_TYPE_srp, "srp"}, {TLSEXT_TYPE_signature_algorithms, "signature_algorithms"}, {TLSEXT_TYPE_use_srtp, "use_srtp"}, {TLSEXT_TYPE_application_layer_protocol_negotiation, "application_layer_protocol_negotiation"}, {TLSEXT_TYPE_signed_certificate_timestamp, "signed_certificate_timestamps"}, {TLSEXT_TYPE_client_cert_type, "client_cert_type"}, {TLSEXT_TYPE_server_cert_type, "server_cert_type"}, {TLSEXT_TYPE_padding, "padding"}, {TLSEXT_TYPE_encrypt_then_mac, "encrypt_then_mac"}, {TLSEXT_TYPE_extended_master_secret, "extended_master_secret"}, {TLSEXT_TYPE_compress_certificate, "compress_certificate"}, {TLSEXT_TYPE_session_ticket, "session_ticket"}, {TLSEXT_TYPE_psk, "psk"}, {TLSEXT_TYPE_early_data, "early_data"}, {TLSEXT_TYPE_supported_versions, "supported_versions"}, {TLSEXT_TYPE_cookie, "cookie_ext"}, {TLSEXT_TYPE_psk_kex_modes, "psk_key_exchange_modes"}, {TLSEXT_TYPE_certificate_authorities, "certificate_authorities"}, {TLSEXT_TYPE_post_handshake_auth, "post_handshake_auth"}, {TLSEXT_TYPE_signature_algorithms_cert, "signature_algorithms_cert"}, {TLSEXT_TYPE_key_share, "key_share"}, {TLSEXT_TYPE_renegotiate, "renegotiate"}, # ifndef OPENSSL_NO_NEXTPROTONEG {TLSEXT_TYPE_next_proto_neg, "next_proto_neg"}, # endif }; static const ssl_trace_tbl ssl_groups_tbl[] = { {1, "sect163k1 (K-163)"}, {2, "sect163r1"}, {3, "sect163r2 (B-163)"}, {4, "sect193r1"}, {5, "sect193r2"}, {6, "sect233k1 (K-233)"}, {7, "sect233r1 (B-233)"}, {8, "sect239k1"}, {9, "sect283k1 (K-283)"}, {10, "sect283r1 (B-283)"}, {11, "sect409k1 (K-409)"}, {12, "sect409r1 (B-409)"}, {13, "sect571k1 (K-571)"}, {14, "sect571r1 (B-571)"}, {15, "secp160k1"}, {16, "secp160r1"}, {17, "secp160r2"}, {18, "secp192k1"}, {19, "secp192r1 (P-192)"}, {20, "secp224k1"}, {21, "secp224r1 (P-224)"}, {22, "secp256k1"}, {23, "secp256r1 (P-256)"}, {24, "secp384r1 (P-384)"}, {25, "secp521r1 (P-521)"}, {26, "brainpoolP256r1"}, {27, "brainpoolP384r1"}, {28, "brainpoolP512r1"}, {29, "ecdh_x25519"}, {30, "ecdh_x448"}, {31, "brainpoolP256r1tls13"}, {32, "brainpoolP384r1tls13"}, {33, "brainpoolP512r1tls13"}, {34, "GC256A"}, {35, "GC256B"}, {36, "GC256C"}, {37, "GC256D"}, {38, "GC512A"}, {39, "GC512B"}, {40, "GC512C"}, {256, "ffdhe2048"}, {257, "ffdhe3072"}, {258, "ffdhe4096"}, {259, "ffdhe6144"}, {260, "ffdhe8192"}, + {512, "MLKEM512"}, + {513, "MLKEM768"}, + {514, "MLKEM1024"}, {4587, "SecP256r1MLKEM768"}, {4588, "X25519MLKEM768"}, + {4589, "SecP384r1MLKEM1024"}, {25497, "X25519Kyber768Draft00"}, {25498, "SecP256r1Kyber768Draft00"}, {0xFF01, "arbitrary_explicit_prime_curves"}, {0xFF02, "arbitrary_explicit_char2_curves"} }; static const ssl_trace_tbl ssl_point_tbl[] = { {0, "uncompressed"}, {1, "ansiX962_compressed_prime"}, {2, "ansiX962_compressed_char2"} }; static const ssl_trace_tbl ssl_mfl_tbl[] = { {0, "disabled"}, {1, "max_fragment_length := 2^9 (512 bytes)"}, {2, "max_fragment_length := 2^10 (1024 bytes)"}, {3, "max_fragment_length := 2^11 (2048 bytes)"}, {4, "max_fragment_length := 2^12 (4096 bytes)"} }; static const ssl_trace_tbl ssl_sigalg_tbl[] = { {TLSEXT_SIGALG_ecdsa_secp256r1_sha256, TLSEXT_SIGALG_ecdsa_secp256r1_sha256_name}, {TLSEXT_SIGALG_ecdsa_secp384r1_sha384, TLSEXT_SIGALG_ecdsa_secp384r1_sha384_name}, {TLSEXT_SIGALG_ecdsa_secp521r1_sha512,TLSEXT_SIGALG_ecdsa_secp521r1_sha512_name}, {TLSEXT_SIGALG_ecdsa_sha224, TLSEXT_SIGALG_ecdsa_sha224_name}, {TLSEXT_SIGALG_ed25519, TLSEXT_SIGALG_ed25519_name}, {TLSEXT_SIGALG_ed448, TLSEXT_SIGALG_ed448_name}, {TLSEXT_SIGALG_ecdsa_sha1, TLSEXT_SIGALG_ecdsa_sha1_name}, {TLSEXT_SIGALG_rsa_pss_rsae_sha256, TLSEXT_SIGALG_rsa_pss_rsae_sha256_name}, {TLSEXT_SIGALG_rsa_pss_rsae_sha384, TLSEXT_SIGALG_rsa_pss_rsae_sha384_name}, {TLSEXT_SIGALG_rsa_pss_rsae_sha512, TLSEXT_SIGALG_rsa_pss_rsae_sha512_name}, {TLSEXT_SIGALG_rsa_pss_pss_sha256, TLSEXT_SIGALG_rsa_pss_pss_sha256_name}, {TLSEXT_SIGALG_rsa_pss_pss_sha384, TLSEXT_SIGALG_rsa_pss_pss_sha384_name}, {TLSEXT_SIGALG_rsa_pss_pss_sha512, TLSEXT_SIGALG_rsa_pss_pss_sha512_name}, {TLSEXT_SIGALG_rsa_pkcs1_sha256, TLSEXT_SIGALG_rsa_pkcs1_sha256_name}, {TLSEXT_SIGALG_rsa_pkcs1_sha384, TLSEXT_SIGALG_rsa_pkcs1_sha384_name}, {TLSEXT_SIGALG_rsa_pkcs1_sha512, TLSEXT_SIGALG_rsa_pkcs1_sha512_name}, {TLSEXT_SIGALG_rsa_pkcs1_sha224, TLSEXT_SIGALG_rsa_pkcs1_sha224_name}, {TLSEXT_SIGALG_rsa_pkcs1_sha1, TLSEXT_SIGALG_rsa_pkcs1_sha1_name}, {TLSEXT_SIGALG_dsa_sha256, TLSEXT_SIGALG_dsa_sha256_name}, {TLSEXT_SIGALG_dsa_sha384, TLSEXT_SIGALG_dsa_sha384_name}, {TLSEXT_SIGALG_dsa_sha512, TLSEXT_SIGALG_dsa_sha512_name}, {TLSEXT_SIGALG_dsa_sha224, TLSEXT_SIGALG_dsa_sha224_name}, {TLSEXT_SIGALG_dsa_sha1, TLSEXT_SIGALG_dsa_sha1_name}, {TLSEXT_SIGALG_gostr34102012_256_intrinsic, TLSEXT_SIGALG_gostr34102012_256_intrinsic_name}, {TLSEXT_SIGALG_gostr34102012_512_intrinsic, TLSEXT_SIGALG_gostr34102012_512_intrinsic_name}, {TLSEXT_SIGALG_gostr34102012_256_gostr34112012_256, TLSEXT_SIGALG_gostr34102012_256_gostr34112012_256_name}, {TLSEXT_SIGALG_gostr34102012_512_gostr34112012_512, TLSEXT_SIGALG_gostr34102012_512_gostr34112012_512_name}, {TLSEXT_SIGALG_gostr34102001_gostr3411, TLSEXT_SIGALG_gostr34102001_gostr3411_name}, {TLSEXT_SIGALG_ecdsa_brainpoolP256r1_sha256, TLSEXT_SIGALG_ecdsa_brainpoolP256r1_sha256_name}, {TLSEXT_SIGALG_ecdsa_brainpoolP384r1_sha384, TLSEXT_SIGALG_ecdsa_brainpoolP384r1_sha384_name}, {TLSEXT_SIGALG_ecdsa_brainpoolP512r1_sha512, TLSEXT_SIGALG_ecdsa_brainpoolP512r1_sha512_name}, /* * Well known groups that we happen to know about, but only come from * provider capability declarations (hence no macros for the * codepoints/names) */ {0x0904, "mldsa44"}, {0x0905, "mldsa65"}, {0x0906, "mldsa87"} }; static const ssl_trace_tbl ssl_ctype_tbl[] = { {1, "rsa_sign"}, {2, "dss_sign"}, {3, "rsa_fixed_dh"}, {4, "dss_fixed_dh"}, {5, "rsa_ephemeral_dh"}, {6, "dss_ephemeral_dh"}, {20, "fortezza_dms"}, {64, "ecdsa_sign"}, {65, "rsa_fixed_ecdh"}, {66, "ecdsa_fixed_ecdh"}, {67, "gost_sign256"}, {68, "gost_sign512"}, }; static const ssl_trace_tbl ssl_psk_kex_modes_tbl[] = { {TLSEXT_KEX_MODE_KE, "psk_ke"}, {TLSEXT_KEX_MODE_KE_DHE, "psk_dhe_ke"} }; static const ssl_trace_tbl ssl_key_update_tbl[] = { {SSL_KEY_UPDATE_NOT_REQUESTED, "update_not_requested"}, {SSL_KEY_UPDATE_REQUESTED, "update_requested"} }; static const ssl_trace_tbl ssl_comp_cert_tbl[] = { {TLSEXT_comp_cert_none, "none"}, {TLSEXT_comp_cert_zlib, "zlib"}, {TLSEXT_comp_cert_brotli, "brotli"}, {TLSEXT_comp_cert_zstd, "zstd"} }; /* * "pgp" and "1609dot2" are defined in RFC7250, * although OpenSSL doesn't support them, it can * at least report them in traces */ static const ssl_trace_tbl ssl_cert_type_tbl[] = { {TLSEXT_cert_type_x509, "x509"}, {TLSEXT_cert_type_pgp, "pgp"}, {TLSEXT_cert_type_rpk, "rpk"}, {TLSEXT_cert_type_1609dot2, "1609dot2"} }; static void ssl_print_hex(BIO *bio, int indent, const char *name, const unsigned char *msg, size_t msglen) { size_t i; BIO_indent(bio, indent, 80); BIO_printf(bio, "%s (len=%d): ", name, (int)msglen); for (i = 0; i < msglen; i++) BIO_printf(bio, "%02X", msg[i]); BIO_puts(bio, "\n"); } static int ssl_print_hexbuf(BIO *bio, int indent, const char *name, size_t nlen, const unsigned char **pmsg, size_t *pmsglen) { size_t blen; const unsigned char *p = *pmsg; if (*pmsglen < nlen) return 0; blen = p[0]; if (nlen > 1) blen = (blen << 8) | p[1]; if (*pmsglen < nlen + blen) return 0; p += nlen; ssl_print_hex(bio, indent, name, p, blen); *pmsg += blen + nlen; *pmsglen -= blen + nlen; return 1; } static int ssl_print_version(BIO *bio, int indent, const char *name, const unsigned char **pmsg, size_t *pmsglen, unsigned int *version) { int vers; if (*pmsglen < 2) return 0; vers = ((*pmsg)[0] << 8) | (*pmsg)[1]; if (version != NULL) *version = vers; BIO_indent(bio, indent, 80); BIO_printf(bio, "%s=0x%x (%s)\n", name, vers, ssl_trace_str(vers, ssl_version_tbl)); *pmsg += 2; *pmsglen -= 2; return 1; } static int ssl_print_random(BIO *bio, int indent, const unsigned char **pmsg, size_t *pmsglen) { unsigned int tm; const unsigned char *p = *pmsg; if (*pmsglen < 32) return 0; tm = ((unsigned int)p[0] << 24) | ((unsigned int)p[1] << 16) | ((unsigned int)p[2] << 8) | (unsigned int)p[3]; p += 4; BIO_indent(bio, indent, 80); BIO_puts(bio, "Random:\n"); BIO_indent(bio, indent + 2, 80); BIO_printf(bio, "gmt_unix_time=0x%08X\n", tm); ssl_print_hex(bio, indent + 2, "random_bytes", p, 28); *pmsg += 32; *pmsglen -= 32; return 1; } static int ssl_print_signature(BIO *bio, int indent, const SSL_CONNECTION *sc, const unsigned char **pmsg, size_t *pmsglen) { if (*pmsglen < 2) return 0; if (SSL_USE_SIGALGS(sc)) { const unsigned char *p = *pmsg; unsigned int sigalg = (p[0] << 8) | p[1]; BIO_indent(bio, indent, 80); BIO_printf(bio, "Signature Algorithm: %s (0x%04x)\n", ssl_trace_str(sigalg, ssl_sigalg_tbl), sigalg); *pmsg += 2; *pmsglen -= 2; } return ssl_print_hexbuf(bio, indent, "Signature", 2, pmsg, pmsglen); } static int ssl_print_extension(BIO *bio, int indent, int server, unsigned char mt, int extype, const unsigned char *ext, size_t extlen) { size_t xlen, share_len; unsigned int sigalg; uint32_t max_early_data; BIO_indent(bio, indent, 80); BIO_printf(bio, "extension_type=%s(%d), length=%d\n", ssl_trace_str(extype, ssl_exts_tbl), extype, (int)extlen); switch (extype) { case TLSEXT_TYPE_compress_certificate: if (extlen < 1) return 0; xlen = ext[0]; if (extlen != xlen + 1) return 0; return ssl_trace_list(bio, indent + 2, ext + 1, xlen, 2, ssl_comp_cert_tbl); case TLSEXT_TYPE_max_fragment_length: if (extlen < 1) return 0; xlen = extlen; return ssl_trace_list(bio, indent + 2, ext, xlen, 1, ssl_mfl_tbl); case TLSEXT_TYPE_ec_point_formats: if (extlen < 1) return 0; xlen = ext[0]; if (extlen != xlen + 1) return 0; return ssl_trace_list(bio, indent + 2, ext + 1, xlen, 1, ssl_point_tbl); case TLSEXT_TYPE_supported_groups: if (extlen < 2) return 0; xlen = (ext[0] << 8) | ext[1]; if (extlen != xlen + 2) return 0; return ssl_trace_list(bio, indent + 2, ext + 2, xlen, 2, ssl_groups_tbl); case TLSEXT_TYPE_application_layer_protocol_negotiation: if (extlen < 2) return 0; xlen = (ext[0] << 8) | ext[1]; if (extlen != xlen + 2) return 0; ext += 2; while (xlen > 0) { size_t plen = *ext++; if (plen + 1 > xlen) return 0; BIO_indent(bio, indent + 2, 80); BIO_write(bio, ext, plen); BIO_puts(bio, "\n"); ext += plen; xlen -= plen + 1; } return 1; case TLSEXT_TYPE_signature_algorithms: if (extlen < 2) return 0; xlen = (ext[0] << 8) | ext[1]; if (extlen != xlen + 2) return 0; if (xlen & 1) return 0; ext += 2; while (xlen > 0) { BIO_indent(bio, indent + 2, 80); sigalg = (ext[0] << 8) | ext[1]; BIO_printf(bio, "%s (0x%04x)\n", ssl_trace_str(sigalg, ssl_sigalg_tbl), sigalg); xlen -= 2; ext += 2; } break; case TLSEXT_TYPE_renegotiate: if (extlen < 1) return 0; xlen = ext[0]; if (xlen + 1 != extlen) return 0; ext++; if (xlen) { if (server) { if (xlen & 1) return 0; xlen >>= 1; } ssl_print_hex(bio, indent + 4, "client_verify_data", ext, xlen); if (server) { ext += xlen; ssl_print_hex(bio, indent + 4, "server_verify_data", ext, xlen); } } else { BIO_indent(bio, indent + 4, 80); BIO_puts(bio, "\n"); } break; case TLSEXT_TYPE_session_ticket: if (extlen != 0) ssl_print_hex(bio, indent + 4, "ticket", ext, extlen); break; case TLSEXT_TYPE_key_share: if (server && extlen == 2) { int group_id; /* We assume this is an HRR, otherwise this is an invalid key_share */ group_id = (ext[0] << 8) | ext[1]; BIO_indent(bio, indent + 4, 80); BIO_printf(bio, "NamedGroup: %s (%d)\n", ssl_trace_str(group_id, ssl_groups_tbl), group_id); break; } if (extlen < 2) return 0; if (server) { xlen = extlen; } else { xlen = (ext[0] << 8) | ext[1]; if (extlen != xlen + 2) return 0; ext += 2; } for (; xlen > 0; ext += share_len, xlen -= share_len) { int group_id; if (xlen < 4) return 0; group_id = (ext[0] << 8) | ext[1]; share_len = (ext[2] << 8) | ext[3]; ext += 4; xlen -= 4; if (xlen < share_len) return 0; BIO_indent(bio, indent + 4, 80); BIO_printf(bio, "NamedGroup: %s (%d)\n", ssl_trace_str(group_id, ssl_groups_tbl), group_id); ssl_print_hex(bio, indent + 4, "key_exchange: ", ext, share_len); } break; case TLSEXT_TYPE_supported_versions: if (server) { int version; if (extlen != 2) return 0; version = (ext[0] << 8) | ext[1]; BIO_indent(bio, indent + 4, 80); BIO_printf(bio, "%s (%d)\n", ssl_trace_str(version, ssl_version_tbl), version); break; } if (extlen < 1) return 0; xlen = ext[0]; if (extlen != xlen + 1) return 0; return ssl_trace_list(bio, indent + 2, ext + 1, xlen, 2, ssl_version_tbl); case TLSEXT_TYPE_psk_kex_modes: if (extlen < 1) return 0; xlen = ext[0]; if (extlen != xlen + 1) return 0; return ssl_trace_list(bio, indent + 2, ext + 1, xlen, 1, ssl_psk_kex_modes_tbl); case TLSEXT_TYPE_early_data: if (mt != SSL3_MT_NEWSESSION_TICKET) break; if (extlen != 4) return 0; max_early_data = ((unsigned int)ext[0] << 24) | ((unsigned int)ext[1] << 16) | ((unsigned int)ext[2] << 8) | (unsigned int)ext[3]; BIO_indent(bio, indent + 2, 80); BIO_printf(bio, "max_early_data=%u\n", (unsigned int)max_early_data); break; case TLSEXT_TYPE_server_cert_type: case TLSEXT_TYPE_client_cert_type: if (server) { if (extlen != 1) return 0; return ssl_trace_list(bio, indent + 2, ext, 1, 1, ssl_cert_type_tbl); } if (extlen < 1) return 0; xlen = ext[0]; if (extlen != xlen + 1) return 0; return ssl_trace_list(bio, indent + 2, ext + 1, xlen, 1, ssl_cert_type_tbl); default: BIO_dump_indent(bio, (const char *)ext, extlen, indent + 2); } return 1; } static int ssl_print_extensions(BIO *bio, int indent, int server, unsigned char mt, const unsigned char **msgin, size_t *msginlen) { size_t extslen, msglen = *msginlen; const unsigned char *msg = *msgin; BIO_indent(bio, indent, 80); if (msglen == 0) { BIO_puts(bio, "No extensions\n"); return 1; } if (msglen < 2) return 0; extslen = (msg[0] << 8) | msg[1]; msglen -= 2; msg += 2; if (extslen == 0) { BIO_puts(bio, "No extensions\n"); *msgin = msg; *msginlen = msglen; return 1; } if (extslen > msglen) return 0; BIO_printf(bio, "extensions, length = %d\n", (int)extslen); msglen -= extslen; while (extslen > 0) { int extype; size_t extlen; if (extslen < 4) return 0; extype = (msg[0] << 8) | msg[1]; extlen = (msg[2] << 8) | msg[3]; if (extslen < extlen + 4) { BIO_printf(bio, "extensions, extype = %d, extlen = %d\n", extype, (int)extlen); BIO_dump_indent(bio, (const char *)msg, extslen, indent + 2); return 0; } msg += 4; if (!ssl_print_extension(bio, indent + 2, server, mt, extype, msg, extlen)) return 0; msg += extlen; extslen -= extlen + 4; } *msgin = msg; *msginlen = msglen; return 1; } static int ssl_print_client_hello(BIO *bio, const SSL_CONNECTION *sc, int indent, const unsigned char *msg, size_t msglen) { size_t len; unsigned int cs; if (!ssl_print_version(bio, indent, "client_version", &msg, &msglen, NULL)) return 0; if (!ssl_print_random(bio, indent, &msg, &msglen)) return 0; if (!ssl_print_hexbuf(bio, indent, "session_id", 1, &msg, &msglen)) return 0; if (SSL_CONNECTION_IS_DTLS(sc)) { if (!ssl_print_hexbuf(bio, indent, "cookie", 1, &msg, &msglen)) return 0; } if (msglen < 2) return 0; len = (msg[0] << 8) | msg[1]; msg += 2; msglen -= 2; BIO_indent(bio, indent, 80); BIO_printf(bio, "cipher_suites (len=%d)\n", (int)len); if (msglen < len || len & 1) return 0; while (len > 0) { cs = (msg[0] << 8) | msg[1]; BIO_indent(bio, indent + 2, 80); BIO_printf(bio, "{0x%02X, 0x%02X} %s\n", msg[0], msg[1], ssl_trace_str(cs, ssl_ciphers_tbl)); msg += 2; msglen -= 2; len -= 2; } if (msglen < 1) return 0; len = msg[0]; msg++; msglen--; if (msglen < len) return 0; BIO_indent(bio, indent, 80); BIO_printf(bio, "compression_methods (len=%d)\n", (int)len); while (len > 0) { BIO_indent(bio, indent + 2, 80); BIO_printf(bio, "%s (0x%02X)\n", ssl_trace_str(msg[0], ssl_comp_tbl), msg[0]); msg++; msglen--; len--; } if (!ssl_print_extensions(bio, indent, 0, SSL3_MT_CLIENT_HELLO, &msg, &msglen)) return 0; return 1; } static int dtls_print_hello_vfyrequest(BIO *bio, int indent, const unsigned char *msg, size_t msglen) { if (!ssl_print_version(bio, indent, "server_version", &msg, &msglen, NULL)) return 0; if (!ssl_print_hexbuf(bio, indent, "cookie", 1, &msg, &msglen)) return 0; return 1; } static int ssl_print_server_hello(BIO *bio, int indent, const unsigned char *msg, size_t msglen) { unsigned int cs; unsigned int vers; if (!ssl_print_version(bio, indent, "server_version", &msg, &msglen, &vers)) return 0; if (!ssl_print_random(bio, indent, &msg, &msglen)) return 0; if (vers != TLS1_3_VERSION && !ssl_print_hexbuf(bio, indent, "session_id", 1, &msg, &msglen)) return 0; if (msglen < 2) return 0; cs = (msg[0] << 8) | msg[1]; BIO_indent(bio, indent, 80); BIO_printf(bio, "cipher_suite {0x%02X, 0x%02X} %s\n", msg[0], msg[1], ssl_trace_str(cs, ssl_ciphers_tbl)); msg += 2; msglen -= 2; if (vers != TLS1_3_VERSION) { if (msglen < 1) return 0; BIO_indent(bio, indent, 80); BIO_printf(bio, "compression_method: %s (0x%02X)\n", ssl_trace_str(msg[0], ssl_comp_tbl), msg[0]); msg++; msglen--; } if (!ssl_print_extensions(bio, indent, 1, SSL3_MT_SERVER_HELLO, &msg, &msglen)) return 0; return 1; } static int ssl_get_keyex(const char **pname, const SSL_CONNECTION *sc) { unsigned long alg_k = sc->s3.tmp.new_cipher->algorithm_mkey; if (alg_k & SSL_kRSA) { *pname = "rsa"; return SSL_kRSA; } if (alg_k & SSL_kDHE) { *pname = "DHE"; return SSL_kDHE; } if (alg_k & SSL_kECDHE) { *pname = "ECDHE"; return SSL_kECDHE; } if (alg_k & SSL_kPSK) { *pname = "PSK"; return SSL_kPSK; } if (alg_k & SSL_kRSAPSK) { *pname = "RSAPSK"; return SSL_kRSAPSK; } if (alg_k & SSL_kDHEPSK) { *pname = "DHEPSK"; return SSL_kDHEPSK; } if (alg_k & SSL_kECDHEPSK) { *pname = "ECDHEPSK"; return SSL_kECDHEPSK; } if (alg_k & SSL_kSRP) { *pname = "SRP"; return SSL_kSRP; } if (alg_k & SSL_kGOST) { *pname = "GOST"; return SSL_kGOST; } if (alg_k & SSL_kGOST18) { *pname = "GOST18"; return SSL_kGOST18; } *pname = "UNKNOWN"; return 0; } static int ssl_print_client_keyex(BIO *bio, int indent, const SSL_CONNECTION *sc, const unsigned char *msg, size_t msglen) { const char *algname; int id = ssl_get_keyex(&algname, sc); BIO_indent(bio, indent, 80); BIO_printf(bio, "KeyExchangeAlgorithm=%s\n", algname); if (id & SSL_PSK) { if (!ssl_print_hexbuf(bio, indent + 2, "psk_identity", 2, &msg, &msglen)) return 0; } switch (id) { case SSL_kRSA: case SSL_kRSAPSK: if (TLS1_get_version(SSL_CONNECTION_GET_SSL(sc)) == SSL3_VERSION) { ssl_print_hex(bio, indent + 2, "EncryptedPreMasterSecret", msg, msglen); } else { if (!ssl_print_hexbuf(bio, indent + 2, "EncryptedPreMasterSecret", 2, &msg, &msglen)) return 0; } break; case SSL_kDHE: case SSL_kDHEPSK: if (!ssl_print_hexbuf(bio, indent + 2, "dh_Yc", 2, &msg, &msglen)) return 0; break; case SSL_kECDHE: case SSL_kECDHEPSK: if (!ssl_print_hexbuf(bio, indent + 2, "ecdh_Yc", 1, &msg, &msglen)) return 0; break; case SSL_kGOST: ssl_print_hex(bio, indent + 2, "GostKeyTransportBlob", msg, msglen); msglen = 0; break; case SSL_kGOST18: ssl_print_hex(bio, indent + 2, "GOST-wrapped PreMasterSecret", msg, msglen); msglen = 0; break; } return !msglen; } static int ssl_print_server_keyex(BIO *bio, int indent, const SSL_CONNECTION *sc, const unsigned char *msg, size_t msglen) { const char *algname; int id = ssl_get_keyex(&algname, sc); BIO_indent(bio, indent, 80); BIO_printf(bio, "KeyExchangeAlgorithm=%s\n", algname); if (id & SSL_PSK) { if (!ssl_print_hexbuf(bio, indent + 2, "psk_identity_hint", 2, &msg, &msglen)) return 0; } switch (id) { case SSL_kRSA: if (!ssl_print_hexbuf(bio, indent + 2, "rsa_modulus", 2, &msg, &msglen)) return 0; if (!ssl_print_hexbuf(bio, indent + 2, "rsa_exponent", 2, &msg, &msglen)) return 0; break; case SSL_kDHE: case SSL_kDHEPSK: if (!ssl_print_hexbuf(bio, indent + 2, "dh_p", 2, &msg, &msglen)) return 0; if (!ssl_print_hexbuf(bio, indent + 2, "dh_g", 2, &msg, &msglen)) return 0; if (!ssl_print_hexbuf(bio, indent + 2, "dh_Ys", 2, &msg, &msglen)) return 0; break; case SSL_kECDHE: case SSL_kECDHEPSK: if (msglen < 1) return 0; BIO_indent(bio, indent + 2, 80); if (msg[0] == EXPLICIT_PRIME_CURVE_TYPE) BIO_puts(bio, "explicit_prime\n"); else if (msg[0] == EXPLICIT_CHAR2_CURVE_TYPE) BIO_puts(bio, "explicit_char2\n"); else if (msg[0] == NAMED_CURVE_TYPE) { int curve; if (msglen < 3) return 0; curve = (msg[1] << 8) | msg[2]; BIO_printf(bio, "named_curve: %s (%d)\n", ssl_trace_str(curve, ssl_groups_tbl), curve); msg += 3; msglen -= 3; if (!ssl_print_hexbuf(bio, indent + 2, "point", 1, &msg, &msglen)) return 0; } else { BIO_printf(bio, "UNKNOWN CURVE PARAMETER TYPE %d\n", msg[0]); return 0; } break; case SSL_kPSK: case SSL_kRSAPSK: break; } if (!(id & SSL_PSK)) ssl_print_signature(bio, indent, sc, &msg, &msglen); return !msglen; } static int ssl_print_certificate(BIO *bio, const SSL_CONNECTION *sc, int indent, const unsigned char **pmsg, size_t *pmsglen) { size_t msglen = *pmsglen; size_t clen; X509 *x; const unsigned char *p = *pmsg, *q; SSL_CTX *ctx = SSL_CONNECTION_GET_CTX(sc); if (msglen < 3) return 0; clen = (p[0] << 16) | (p[1] << 8) | p[2]; if (msglen < clen + 3) return 0; q = p + 3; BIO_indent(bio, indent, 80); BIO_printf(bio, "ASN.1Cert, length=%d", (int)clen); x = X509_new_ex(ctx->libctx, ctx->propq); if (x != NULL && d2i_X509(&x, &q, clen) == NULL) { X509_free(x); x = NULL; } if (x == NULL) BIO_puts(bio, "\n"); else { BIO_puts(bio, "\n------details-----\n"); X509_print_ex(bio, x, XN_FLAG_ONELINE, 0); PEM_write_bio_X509(bio, x); /* Print certificate stuff */ BIO_puts(bio, "------------------\n"); X509_free(x); } if (q != p + 3 + clen) { BIO_puts(bio, "\n"); } *pmsg += clen + 3; *pmsglen -= clen + 3; return 1; } static int ssl_print_raw_public_key(BIO *bio, const SSL *ssl, int server, int indent, const unsigned char **pmsg, size_t *pmsglen) { EVP_PKEY *pkey; size_t clen; const unsigned char *msg = *pmsg; size_t msglen = *pmsglen; if (msglen < 3) return 0; clen = (msg[0] << 16) | (msg[1] << 8) | msg[2]; if (msglen < clen + 3) return 0; msg += 3; BIO_indent(bio, indent, 80); BIO_printf(bio, "raw_public_key, length=%d\n", (int)clen); pkey = d2i_PUBKEY_ex(NULL, &msg, clen, ssl->ctx->libctx, ssl->ctx->propq); if (pkey == NULL) return 0; EVP_PKEY_print_public(bio, pkey, indent + 2, NULL); EVP_PKEY_free(pkey); *pmsg += clen + 3; *pmsglen -= clen + 3; return 1; } static int ssl_print_certificates(BIO *bio, const SSL_CONNECTION *sc, int server, int indent, const unsigned char *msg, size_t msglen) { size_t clen; if (SSL_CONNECTION_IS_TLS13(sc) && !ssl_print_hexbuf(bio, indent, "context", 1, &msg, &msglen)) return 0; if (msglen < 3) return 0; clen = (msg[0] << 16) | (msg[1] << 8) | msg[2]; if (msglen != clen + 3) return 0; msg += 3; if ((server && sc->ext.server_cert_type == TLSEXT_cert_type_rpk) || (!server && sc->ext.client_cert_type == TLSEXT_cert_type_rpk)) { if (!ssl_print_raw_public_key(bio, &sc->ssl, server, indent, &msg, &clen)) return 0; if (SSL_CONNECTION_IS_TLS13(sc) && !ssl_print_extensions(bio, indent + 2, server, SSL3_MT_CERTIFICATE, &msg, &clen)) return 0; return 1; } BIO_indent(bio, indent, 80); BIO_printf(bio, "certificate_list, length=%d\n", (int)clen); while (clen > 0) { if (!ssl_print_certificate(bio, sc, indent + 2, &msg, &clen)) return 0; if (SSL_CONNECTION_IS_TLS13(sc) && !ssl_print_extensions(bio, indent + 2, server, SSL3_MT_CERTIFICATE, &msg, &clen)) return 0; } return 1; } static int ssl_print_compressed_certificates(BIO *bio, const SSL_CONNECTION *sc, int server, int indent, const unsigned char *msg, size_t msglen) { size_t uclen; size_t clen; unsigned int alg; int ret = 1; #ifndef OPENSSL_NO_COMP_ALG COMP_METHOD *method; COMP_CTX *comp = NULL; unsigned char* ucdata = NULL; #endif if (msglen < 8) return 0; alg = (msg[0] << 8) | msg[1]; uclen = (msg[2] << 16) | (msg[3] << 8) | msg[4]; clen = (msg[5] << 16) | (msg[6] << 8) | msg[7]; if (msglen != clen + 8) return 0; msg += 8; BIO_indent(bio, indent, 80); BIO_printf(bio, "Compression type=%s (0x%04x)\n", ssl_trace_str(alg, ssl_comp_cert_tbl), alg); BIO_indent(bio, indent, 80); BIO_printf(bio, "Uncompressed length=%d\n", (int)uclen); BIO_indent(bio, indent, 80); if (clen > 0) BIO_printf(bio, "Compressed length=%d, Ratio=%f:1\n", (int)clen, (float)uclen / (float)clen); else BIO_printf(bio, "Compressed length=%d, Ratio=unknown\n", (int)clen); BIO_dump_indent(bio, (const char *)msg, clen, indent); #ifndef OPENSSL_NO_COMP_ALG if (!ossl_comp_has_alg(alg)) return 0; /* Check against certificate maximum size (coverity) */ if (uclen == 0 || uclen > 0xFFFFFF || (ucdata = OPENSSL_malloc(uclen)) == NULL) return 0; switch (alg) { case TLSEXT_comp_cert_zlib: method = COMP_zlib(); break; case TLSEXT_comp_cert_brotli: method = COMP_brotli_oneshot(); break; case TLSEXT_comp_cert_zstd: method = COMP_zstd_oneshot(); break; default: goto err; } if ((comp = COMP_CTX_new(method)) == NULL || COMP_expand_block(comp, ucdata, uclen, (unsigned char*)msg, clen) != (int)uclen) goto err; ret = ssl_print_certificates(bio, sc, server, indent, ucdata, uclen); err: COMP_CTX_free(comp); OPENSSL_free(ucdata); #endif return ret; } static int ssl_print_cert_request(BIO *bio, int indent, const SSL_CONNECTION *sc, const unsigned char *msg, size_t msglen) { size_t xlen; unsigned int sigalg; if (SSL_CONNECTION_IS_TLS13(sc)) { if (!ssl_print_hexbuf(bio, indent, "request_context", 1, &msg, &msglen)) return 0; if (!ssl_print_extensions(bio, indent, 1, SSL3_MT_CERTIFICATE_REQUEST, &msg, &msglen)) return 0; return 1; } else { if (msglen < 1) return 0; xlen = msg[0]; if (msglen < xlen + 1) return 0; msg++; BIO_indent(bio, indent, 80); BIO_printf(bio, "certificate_types (len=%d)\n", (int)xlen); if (!ssl_trace_list(bio, indent + 2, msg, xlen, 1, ssl_ctype_tbl)) return 0; msg += xlen; msglen -= xlen + 1; } if (SSL_USE_SIGALGS(sc)) { if (msglen < 2) return 0; xlen = (msg[0] << 8) | msg[1]; if (msglen < xlen + 2 || (xlen & 1)) return 0; msg += 2; msglen -= xlen + 2; BIO_indent(bio, indent, 80); BIO_printf(bio, "signature_algorithms (len=%d)\n", (int)xlen); while (xlen > 0) { BIO_indent(bio, indent + 2, 80); sigalg = (msg[0] << 8) | msg[1]; BIO_printf(bio, "%s (0x%04x)\n", ssl_trace_str(sigalg, ssl_sigalg_tbl), sigalg); xlen -= 2; msg += 2; } msg += xlen; } if (msglen < 2) return 0; xlen = (msg[0] << 8) | msg[1]; BIO_indent(bio, indent, 80); if (msglen < xlen + 2) return 0; msg += 2; msglen -= 2 + xlen; BIO_printf(bio, "certificate_authorities (len=%d)\n", (int)xlen); while (xlen > 0) { size_t dlen; X509_NAME *nm; const unsigned char *p; if (xlen < 2) return 0; dlen = (msg[0] << 8) | msg[1]; if (xlen < dlen + 2) return 0; msg += 2; BIO_indent(bio, indent + 2, 80); BIO_printf(bio, "DistinguishedName (len=%d): ", (int)dlen); p = msg; nm = d2i_X509_NAME(NULL, &p, dlen); if (!nm) { BIO_puts(bio, "\n"); } else { X509_NAME_print_ex(bio, nm, 0, XN_FLAG_ONELINE); BIO_puts(bio, "\n"); X509_NAME_free(nm); } xlen -= dlen + 2; msg += dlen; } if (SSL_CONNECTION_IS_TLS13(sc)) { if (!ssl_print_hexbuf(bio, indent, "request_extensions", 2, &msg, &msglen)) return 0; } return msglen == 0; } static int ssl_print_ticket(BIO *bio, int indent, const SSL_CONNECTION *sc, const unsigned char *msg, size_t msglen) { unsigned int tick_life; if (msglen == 0) { BIO_indent(bio, indent + 2, 80); BIO_puts(bio, "No Ticket\n"); return 1; } if (msglen < 4) return 0; tick_life = ((unsigned int)msg[0] << 24) | ((unsigned int)msg[1] << 16) | ((unsigned int)msg[2] << 8) | (unsigned int)msg[3]; msglen -= 4; msg += 4; BIO_indent(bio, indent + 2, 80); BIO_printf(bio, "ticket_lifetime_hint=%u\n", tick_life); if (SSL_CONNECTION_IS_TLS13(sc)) { unsigned int ticket_age_add; if (msglen < 4) return 0; ticket_age_add = ((unsigned int)msg[0] << 24) | ((unsigned int)msg[1] << 16) | ((unsigned int)msg[2] << 8) | (unsigned int)msg[3]; msglen -= 4; msg += 4; BIO_indent(bio, indent + 2, 80); BIO_printf(bio, "ticket_age_add=%u\n", ticket_age_add); if (!ssl_print_hexbuf(bio, indent + 2, "ticket_nonce", 1, &msg, &msglen)) return 0; } if (!ssl_print_hexbuf(bio, indent + 2, "ticket", 2, &msg, &msglen)) return 0; if (SSL_CONNECTION_IS_TLS13(sc) && !ssl_print_extensions(bio, indent + 2, 0, SSL3_MT_NEWSESSION_TICKET, &msg, &msglen)) return 0; if (msglen) return 0; return 1; } static int ssl_print_handshake(BIO *bio, const SSL_CONNECTION *sc, int server, const unsigned char *msg, size_t msglen, int indent) { size_t hlen; unsigned char htype; if (msglen < 4) return 0; htype = msg[0]; hlen = (msg[1] << 16) | (msg[2] << 8) | msg[3]; BIO_indent(bio, indent, 80); BIO_printf(bio, "%s, Length=%d\n", ssl_trace_str(htype, ssl_handshake_tbl), (int)hlen); msg += 4; msglen -= 4; if (SSL_CONNECTION_IS_DTLS(sc)) { if (msglen < 8) return 0; BIO_indent(bio, indent, 80); BIO_printf(bio, "message_seq=%d, fragment_offset=%d, " "fragment_length=%d\n", (msg[0] << 8) | msg[1], (msg[2] << 16) | (msg[3] << 8) | msg[4], (msg[5] << 16) | (msg[6] << 8) | msg[7]); msg += 8; msglen -= 8; } if (msglen < hlen) return 0; switch (htype) { case SSL3_MT_CLIENT_HELLO: if (!ssl_print_client_hello(bio, sc, indent + 2, msg, msglen)) return 0; break; case DTLS1_MT_HELLO_VERIFY_REQUEST: if (!dtls_print_hello_vfyrequest(bio, indent + 2, msg, msglen)) return 0; break; case SSL3_MT_SERVER_HELLO: if (!ssl_print_server_hello(bio, indent + 2, msg, msglen)) return 0; break; case SSL3_MT_SERVER_KEY_EXCHANGE: if (!ssl_print_server_keyex(bio, indent + 2, sc, msg, msglen)) return 0; break; case SSL3_MT_CLIENT_KEY_EXCHANGE: if (!ssl_print_client_keyex(bio, indent + 2, sc, msg, msglen)) return 0; break; case SSL3_MT_CERTIFICATE: if (!ssl_print_certificates(bio, sc, server, indent + 2, msg, msglen)) return 0; break; case SSL3_MT_COMPRESSED_CERTIFICATE: if (!ssl_print_compressed_certificates(bio, sc, server, indent + 2, msg, msglen)) return 0; break; case SSL3_MT_CERTIFICATE_VERIFY: if (!ssl_print_signature(bio, indent + 2, sc, &msg, &msglen)) return 0; break; case SSL3_MT_CERTIFICATE_REQUEST: if (!ssl_print_cert_request(bio, indent + 2, sc, msg, msglen)) return 0; break; case SSL3_MT_FINISHED: ssl_print_hex(bio, indent + 2, "verify_data", msg, msglen); break; case SSL3_MT_END_OF_EARLY_DATA: case SSL3_MT_SERVER_DONE: if (msglen != 0) ssl_print_hex(bio, indent + 2, "unexpected value", msg, msglen); break; case SSL3_MT_NEWSESSION_TICKET: if (!ssl_print_ticket(bio, indent + 2, sc, msg, msglen)) return 0; break; case SSL3_MT_ENCRYPTED_EXTENSIONS: if (!ssl_print_extensions(bio, indent + 2, 1, SSL3_MT_ENCRYPTED_EXTENSIONS, &msg, &msglen)) return 0; break; case SSL3_MT_KEY_UPDATE: if (msglen != 1) { ssl_print_hex(bio, indent + 2, "unexpected value", msg, msglen); return 0; } if (!ssl_trace_list(bio, indent + 2, msg, msglen, 1, ssl_key_update_tbl)) return 0; break; default: BIO_indent(bio, indent + 2, 80); BIO_puts(bio, "Unsupported, hex dump follows:\n"); BIO_dump_indent(bio, (const char *)msg, msglen, indent + 4); } return 1; } void SSL_trace(int write_p, int version, int content_type, const void *buf, size_t msglen, SSL *ssl, void *arg) { const unsigned char *msg = buf; BIO *bio = arg; SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ssl); #ifndef OPENSSL_NO_QUIC QUIC_CONNECTION *qc = QUIC_CONNECTION_FROM_SSL(ssl); if (qc != NULL) { if (ossl_quic_trace(write_p, version, content_type, buf, msglen, ssl, arg)) return; /* * Otherwise ossl_quic_trace didn't handle this content_type so we * fallback to standard TLS handling */ } #endif if (sc == NULL) return; switch (content_type) { case SSL3_RT_HEADER: { int hvers; /* avoid overlapping with length at the end of buffer */ if (msglen < (size_t)(SSL_CONNECTION_IS_DTLS(sc) ? DTLS1_RT_HEADER_LENGTH : SSL3_RT_HEADER_LENGTH)) { BIO_puts(bio, write_p ? "Sent" : "Received"); ssl_print_hex(bio, 0, " too short message", msg, msglen); break; } hvers = msg[1] << 8 | msg[2]; BIO_puts(bio, write_p ? "Sent" : "Received"); BIO_printf(bio, " TLS Record\nHeader:\n Version = %s (0x%x)\n", ssl_trace_str(hvers, ssl_version_tbl), hvers); if (SSL_CONNECTION_IS_DTLS(sc)) { BIO_printf(bio, " epoch=%d, sequence_number=%04x%04x%04x\n", (msg[3] << 8 | msg[4]), (msg[5] << 8 | msg[6]), (msg[7] << 8 | msg[8]), (msg[9] << 8 | msg[10])); } BIO_printf(bio, " Content Type = %s (%d)\n Length = %d", ssl_trace_str(msg[0], ssl_content_tbl), msg[0], msg[msglen - 2] << 8 | msg[msglen - 1]); } break; case SSL3_RT_INNER_CONTENT_TYPE: BIO_printf(bio, " Inner Content Type = %s (%d)", ssl_trace_str(msg[0], ssl_content_tbl), msg[0]); break; case SSL3_RT_HANDSHAKE: if (!ssl_print_handshake(bio, sc, sc->server ? write_p : !write_p, msg, msglen, 4)) BIO_printf(bio, "Message length parse error!\n"); break; case SSL3_RT_CHANGE_CIPHER_SPEC: if (msglen == 1 && msg[0] == 1) BIO_puts(bio, " change_cipher_spec (1)\n"); else ssl_print_hex(bio, 4, "unknown value", msg, msglen); break; case SSL3_RT_ALERT: if (msglen != 2) BIO_puts(bio, " Illegal Alert Length\n"); else { BIO_printf(bio, " Level=%s(%d), description=%s(%d)\n", SSL_alert_type_string_long(msg[0] << 8), msg[0], SSL_alert_desc_string_long(msg[1]), msg[1]); } } BIO_puts(bio, "\n"); } #endif diff --git a/test/build.info b/test/build.info index 9d9be6b642e9..3dca6117796b 100644 --- a/test/build.info +++ b/test/build.info @@ -1,1320 +1,1321 @@ # TODO: use ../apps/libapps.a instead of direct ../apps/lib source. # This can't currently be done, because some of its units drag in too many # unresolved references that don't apply here. # Most of all, ../apps/lib/apps.c needs to be divided in smaller pieces to # be useful here. # IF[{- !$disabled{hqinterop} -}] SUBDIRS=quic-openssl-docker ENDIF # Auxiliary program source (copied from ../apps/build.info) IF[{- $config{target} =~ /^(?:VC-|mingw|BC-)/ -}] # It's called 'init', but doesn't have much 'init' in it... $AUXLIBAPPSSRC=../apps/lib/win32_init.c ENDIF IF[{- $config{target} =~ /^vms-/ -}] $AUXLIBAPPSSRC=../apps/lib/vms_term_sock.c ../apps/lib/vms_decc_argv.c ENDIF # Program init source, that don't have direct linkage with the rest of the # source, and can therefore not be part of a library. IF[{- !$disabled{uplink} -}] $INITSRC=../ms/applink.c ENDIF $LIBAPPSSRC=../apps/lib/opt.c $AUXLIBAPPSSRC IF[{- !$disabled{tests} -}] LIBS{noinst,has_main}=libtestutil.a SOURCE[libtestutil.a]=testutil/basic_output.c testutil/output.c \ testutil/driver.c testutil/tests.c testutil/cb.c testutil/stanza.c \ testutil/format_output.c testutil/load.c testutil/fake_random.c \ testutil/test_cleanup.c testutil/main.c testutil/testutil_init.c \ testutil/options.c testutil/test_options.c testutil/provider.c \ - testutil/apps_shims.c testutil/random.c testutil/helper.c $LIBAPPSSRC + testutil/apps_shims.c testutil/random.c testutil/helper.c \ + testutil/compare.c $LIBAPPSSRC INCLUDE[libtestutil.a]=../include ../apps/include .. DEPEND[libtestutil.a]=../libcrypto PROGRAMS{noinst}= \ confdump \ versions \ aborttest test_test pkcs12_format_test pkcs12_api_test \ sanitytest time_test rsa_complex exdatatest bntest \ ecstresstest gmdifftest pbelutest \ destest mdc2test sha_test \ exptest pbetest localetest evp_pkey_ctx_new_from_name \ evp_pkey_provided_test evp_test evp_extra_test evp_extra_test2 \ evp_fetch_prov_test evp_libctx_test ossl_store_test \ v3nametest v3ext byteorder_test punycode_test evp_byname_test \ crltest danetest bad_dtls_test lhash_test sparse_array_test \ conf_include_test params_api_test params_conversion_test \ constant_time_test safe_math_test verify_extra_test clienthellotest \ packettest asynctest secmemtest srptest memleaktest stack_test \ dtlsv1listentest ct_test threadstest afalgtest d2i_test \ ssl_test_ctx_test ssl_test x509aux cipherlist_test asynciotest \ bio_callback_test bio_memleak_test bio_core_test bio_dgram_test param_build_test \ bioprinttest sslapitest ssl_handshake_rtt_test dtlstest sslcorrupttest \ bio_base64_test bio_enc_test pkey_meth_test pkey_meth_kdf_test evp_kdf_test uitest \ cipherbytes_test threadstest_fips threadpool_test \ asn1_encode_test asn1_decode_test asn1_string_table_test asn1_stable_parse_test \ x509_time_test x509_dup_cert_test x509_check_cert_pkey_test \ recordlentest drbgtest rand_status_test sslbuffertest \ time_offset_test pemtest ssl_cert_table_internal_test ciphername_test \ servername_test ocspapitest fatalerrtest tls13ccstest \ sysdefaulttest errtest ssl_ctx_test build_wincrypt_test \ context_internal_test aesgcmtest params_test evp_pkey_dparams_test \ keymgmt_internal_test hexstr_test provider_status_test defltfips_test \ bio_readbuffer_test user_property_test pkcs7_test upcallstest \ provfetchtest prov_config_test rand_test \ ca_internals_test bio_tfo_test membio_test bio_dgram_test list_test \ fips_version_test x509_test hpke_test pairwise_fail_test \ nodefltctxtest evp_xof_test x509_load_cert_file_test bio_meth_test \ x509_acert_test x509_req_test strtoultest bio_pw_callback_test IF[{- !$disabled{'rpk'} -}] PROGRAMS{noinst}=rpktest ENDIF IF[{- !$disabled{'deprecated-3.0'} -}] PROGRAMS{noinst}=enginetest ENDIF IF[{- !$disabled{quic} -}] PROGRAMS{noinst}=priority_queue_test quicfaultstest quicapitest \ quic_newcid_test quic_srt_gen_test ENDIF IF[{- !$disabled{qlog} -}] PROGRAMS{noinst}=json_test quic_qlog_test ENDIF IF[{- !$disabled{comp} && (!$disabled{brotli} || !$disabled{zstd} || !$disabled{zlib}) -}] PROGRAMS{noinst}=cert_comp_test ENDIF SOURCE[confdump]=confdump.c INCLUDE[confdump]=../include ../apps/include DEPEND[confdump]=../libcrypto SOURCE[versions]=versions.c INCLUDE[versions]=../include ../apps/include DEPEND[versions]=../libcrypto SOURCE[aborttest]=aborttest.c INCLUDE[aborttest]=../include ../apps/include DEPEND[aborttest]=../libcrypto SOURCE[sanitytest]=sanitytest.c INCLUDE[sanitytest]=../include ../apps/include DEPEND[sanitytest]=../libcrypto.a libtestutil.a SOURCE[time_test]=time_test.c INCLUDE[time_test]=../include ../apps/include DEPEND[time_test]=../libcrypto.a libtestutil.a SOURCE[rand_test]=rand_test.c INCLUDE[rand_test]=../include ../apps/include DEPEND[rand_test]=../libcrypto.a libtestutil.a SOURCE[rsa_complex]=rsa_complex.c INCLUDE[rsa_complex]=../include ../apps/include SOURCE[test_test]=test_test.c INCLUDE[test_test]=../include ../apps/include DEPEND[test_test]=../libcrypto libtestutil.a SOURCE[exdatatest]=exdatatest.c INCLUDE[exdatatest]=../include ../apps/include DEPEND[exdatatest]=../libcrypto libtestutil.a SOURCE[bntest]=bntest.c INCLUDE[bntest]=../include ../apps/include DEPEND[bntest]=../libcrypto libtestutil.a SOURCE[ectest]=ectest.c INCLUDE[ectest]=../include ../apps/include DEPEND[ectest]=../libcrypto.a libtestutil.a SOURCE[ecstresstest]=ecstresstest.c INCLUDE[ecstresstest]=../include ../apps/include DEPEND[ecstresstest]=../libcrypto libtestutil.a SOURCE[gmdifftest]=gmdifftest.c INCLUDE[gmdifftest]=../include ../apps/include DEPEND[gmdifftest]=../libcrypto libtestutil.a SOURCE[pbelutest]=pbelutest.c INCLUDE[pbelutest]=../include ../apps/include DEPEND[pbelutest]=../libcrypto libtestutil.a SOURCE[mdc2test]=mdc2test.c INCLUDE[mdc2test]=../include ../apps/include DEPEND[mdc2test]=../libcrypto libtestutil.a SOURCE[sha_test]=sha_test.c INCLUDE[sha_test]=../include ../apps/include DEPEND[sha_test]=../libcrypto libtestutil.a SOURCE[enginetest]=enginetest.c INCLUDE[enginetest]=../include ../apps/include DEPEND[enginetest]=../libcrypto libtestutil.a SOURCE[exptest]=exptest.c INCLUDE[exptest]=../include ../apps/include DEPEND[exptest]=../libcrypto libtestutil.a SOURCE[localetest]=localetest.c INCLUDE[localetest]=../include ../apps/include DEPEND[localetest]=../libcrypto libtestutil.a SOURCE[evp_pkey_ctx_new_from_name]=evp_pkey_ctx_new_from_name.c INCLUDE[evp_pkey_ctx_new_from_name]=../include ../apps/include DEPEND[evp_pkey_ctx_new_from_name]=../libcrypto SOURCE[pbetest]=pbetest.c INCLUDE[pbetest]=../include ../apps/include DEPEND[pbetest]=../libcrypto libtestutil.a SOURCE[fatalerrtest]=fatalerrtest.c helpers/ssltestlib.c INCLUDE[fatalerrtest]=../include ../apps/include DEPEND[fatalerrtest]=../libcrypto ../libssl libtestutil.a SOURCE[tls13ccstest]=tls13ccstest.c helpers/ssltestlib.c INCLUDE[tls13ccstest]=../include ../apps/include DEPEND[tls13ccstest]=../libcrypto ../libssl libtestutil.a IF[{- !$disabled{ecx} && !$disabled{tls} && !$disabled{tls1_3} -}] PROGRAMS{noinst}=tls13groupselection_test SOURCE[tls13groupselection_test]=tls13groupselection_test.c helpers/ssltestlib.c INCLUDE[tls13groupselection_test]=../include ../apps/include DEPEND[tls13groupselection_test]=../libcrypto ../libssl libtestutil.a ENDIF SOURCE[upcallstest]=upcallstest.c INCLUDE[upcallstest]=../include ../apps/include DEPEND[upcallstest]=../libcrypto libtestutil.a SOURCE[user_property_test]=user_property_test.c INCLUDE[user_property_test]=../include ../apps/include DEPEND[user_property_test]=../libcrypto libtestutil.a SOURCE[evp_test]=evp_test.c INCLUDE[evp_test]=../include ../apps/include DEPEND[evp_test]=../libcrypto libtestutil.a IF[{- $disabled{legacy} || !$target{dso_scheme} -}] DEFINE[evp_test]=NO_LEGACY_MODULE ENDIF SOURCE[evp_extra_test]=evp_extra_test.c fake_rsaprov.c fake_pipelineprov.c INCLUDE[evp_extra_test]=../include ../apps/include \ ../providers/common/include \ ../providers/implementations/include DEPEND[evp_extra_test]=../libcrypto.a libtestutil.a IF[{- !$disabled{module} && !$disabled{legacy} -}] DEFINE[evp_extra_test]=STATIC_LEGACY SOURCE[evp_extra_test]=../providers/legacyprov.c DEPEND[evp_extra_test]=../providers/liblegacy.a \ ../providers/libcommon.a ENDIF SOURCE[hpke_test]=hpke_test.c INCLUDE[hpke_test]=../include ../apps/include DEPEND[hpke_test]=../libcrypto.a libtestutil.a SOURCE[evp_extra_test2]=evp_extra_test2.c $INITSRC tls-provider.c INCLUDE[evp_extra_test2]=../include ../apps/include DEPEND[evp_extra_test2]=../libcrypto libtestutil.a SOURCE[evp_libctx_test]=evp_libctx_test.c INCLUDE[evp_libctx_test]=../include ../apps/include DEPEND[evp_libctx_test]=../libcrypto.a libtestutil.a SOURCE[evp_fetch_prov_test]=evp_fetch_prov_test.c INCLUDE[evp_fetch_prov_test]=../include ../apps/include DEPEND[evp_fetch_prov_test]=../libcrypto libtestutil.a SOURCE[provfetchtest]=provfetchtest.c INCLUDE[provfetchtest]=../include ../apps/include DEPEND[provfetchtest]=../libcrypto.a libtestutil.a SOURCE[prov_config_test]=prov_config_test.c INCLUDE[prov_config_test]=../include ../apps/include DEPEND[prov_config_test]=../libcrypto.a libtestutil.a SOURCE[evp_pkey_provided_test]=evp_pkey_provided_test.c INCLUDE[evp_pkey_provided_test]=../include ../apps/include DEPEND[evp_pkey_provided_test]=../libcrypto.a libtestutil.a IF[{- !$disabled{'acvp-tests'} -}] PROGRAMS{noinst}=acvp_test SOURCE[acvp_test]=acvp_test.c INCLUDE[acvp_test]=../include ../apps/include DEPEND[acvp_test]=../libcrypto.a libtestutil.a ENDIF SOURCE[ossl_store_test]=ossl_store_test.c INCLUDE[ossl_store_test]=../include ../apps/include DEPEND[ossl_store_test]=../libcrypto.a libtestutil.a SOURCE[provider_status_test]=provider_status_test.c INCLUDE[provider_status_test]=../include ../apps/include DEPEND[provider_status_test]=../libcrypto.a libtestutil.a SOURCE[pairwise_fail_test]=pairwise_fail_test.c INCLUDE[pairwise_fail_test]=../include ../apps/include DEPEND[pairwise_fail_test]=../libcrypto.a libtestutil.a SOURCE[nodefltctxtest]=nodefltctxtest.c INCLUDE[nodefltctxtest]=../include ../apps/include DEPEND[nodefltctxtest]=../libcrypto.a libtestutil.a SOURCE[evp_pkey_dhkem_test]=evp_pkey_dhkem_test.c INCLUDE[evp_pkey_dhkem_test]=../include ../apps/include DEPEND[evp_pkey_dhkem_test]=../libcrypto.a libtestutil.a IF[{- !$disabled{'slh-dsa'} -}] PROGRAMS{noinst}=slh_dsa_test SOURCE[slh_dsa_test]=slh_dsa_test.c INCLUDE[slh_dsa_test]=../include ../apps/include DEPEND[slh_dsa_test]=../libcrypto.a libtestutil.a ENDIF IF[{- !$disabled{'deprecated-3.0'} -}] PROGRAMS{noinst}=igetest bftest casttest SOURCE[igetest]=igetest.c INCLUDE[igetest]=../include ../apps/include DEPEND[igetest]=../libcrypto libtestutil.a SOURCE[bftest]=bftest.c INCLUDE[bftest]=../include ../apps/include DEPEND[bftest]=../libcrypto libtestutil.a SOURCE[casttest]=casttest.c INCLUDE[casttest]=../include ../apps/include DEPEND[casttest]=../libcrypto libtestutil.a ENDIF IF[{- !$disabled{'ml-dsa'} -}] PROGRAMS{noinst}=ml_dsa_test SOURCE[ml_dsa_test]=ml_dsa_test.c INCLUDE[ml_dsa_test]=../include ../apps/include DEPEND[ml_dsa_test]=../libcrypto.a libtestutil.a ENDIF SOURCE[v3nametest]=v3nametest.c INCLUDE[v3nametest]=../include ../apps/include DEPEND[v3nametest]=../libcrypto libtestutil.a SOURCE[crltest]=crltest.c INCLUDE[crltest]=../include ../apps/include DEPEND[crltest]=../libcrypto libtestutil.a SOURCE[v3ext]=v3ext.c INCLUDE[v3ext]=../include ../apps/include DEPEND[v3ext]=../libcrypto libtestutil.a SOURCE[danetest]=danetest.c INCLUDE[danetest]=../include ../apps/include DEPEND[danetest]=../libcrypto ../libssl libtestutil.a SOURCE[constant_time_test]=constant_time_test.c INCLUDE[constant_time_test]=../include ../apps/include DEPEND[constant_time_test]=../libcrypto libtestutil.a SOURCE[safe_math_test]=safe_math_test.c INCLUDE[safe_math_test]=../include ../apps/include DEPEND[safe_math_test]=../libcrypto libtestutil.a SOURCE[verify_extra_test]=verify_extra_test.c INCLUDE[verify_extra_test]=../include ../apps/include DEPEND[verify_extra_test]=../libcrypto libtestutil.a SOURCE[clienthellotest]=clienthellotest.c INCLUDE[clienthellotest]=../include ../apps/include DEPEND[clienthellotest]=../libcrypto ../libssl libtestutil.a SOURCE[bad_dtls_test]=bad_dtls_test.c INCLUDE[bad_dtls_test]=../include ../apps/include DEPEND[bad_dtls_test]=../libcrypto ../libssl libtestutil.a SOURCE[packettest]=packettest.c ../crypto/quic_vlint.c INCLUDE[packettest]=../include ../apps/include DEPEND[packettest]=../libcrypto libtestutil.a IF[{- !$disabled{'quic'} -}] SOURCE[quic_wire_test]=quic_wire_test.c INCLUDE[quic_wire_test]=../include ../apps/include DEPEND[quic_wire_test]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[quic_record_test]=quic_record_test.c INCLUDE[quic_record_test]=../include ../apps/include DEPEND[quic_record_test]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[quic_fc_test]=quic_fc_test.c INCLUDE[quic_fc_test]=../include ../apps/include DEPEND[quic_fc_test]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[quic_stream_test]=quic_stream_test.c INCLUDE[quic_stream_test]=../include ../apps/include DEPEND[quic_stream_test]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[quic_cfq_test]=quic_cfq_test.c INCLUDE[quic_cfq_test]=../include ../apps/include DEPEND[quic_cfq_test]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[quic_txpim_test]=quic_txpim_test.c INCLUDE[quic_txpim_test]=../include ../apps/include DEPEND[quic_txpim_test]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[quic_srtm_test]=quic_srtm_test.c INCLUDE[quic_srtm_test]=../include ../apps/include DEPEND[quic_srtm_test]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[quic_lcidm_test]=quic_lcidm_test.c INCLUDE[quic_lcidm_test]=../include ../apps/include DEPEND[quic_lcidm_test]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[quic_rcidm_test]=quic_rcidm_test.c INCLUDE[quic_rcidm_test]=../include ../apps/include DEPEND[quic_rcidm_test]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[quic_fifd_test]=quic_fifd_test.c cc_dummy.c INCLUDE[quic_fifd_test]=../include ../apps/include DEPEND[quic_fifd_test]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[quic_txp_test]=quic_txp_test.c cc_dummy.c INCLUDE[quic_txp_test]=../include ../apps/include DEPEND[quic_txp_test]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[quic_tserver_test]=quic_tserver_test.c INCLUDE[quic_tserver_test]=../include ../apps/include DEPEND[quic_tserver_test]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[quic_client_test]=quic_client_test.c INCLUDE[quic_client_test]=../include ../apps/include DEPEND[quic_client_test]=../libcrypto.a ../libssl.a libtestutil.a $QUICTESTHELPERS=helpers/quictestlib.c helpers/noisydgrambio.c helpers/pktsplitbio.c SOURCE[quic_multistream_test]=quic_multistream_test.c helpers/ssltestlib.c $QUICTESTHELPERS INCLUDE[quic_multistream_test]=../include ../apps/include DEPEND[quic_multistream_test]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[quic_radix_test]=radix/quic_radix.c SOURCE[quic_radix_test]=helpers/ssltestlib.c $QUICTESTHELPERS INCLUDE[quic_radix_test]=../include ../apps/include DEPEND[quic_radix_test]=../libcrypto.a ../libssl.a libtestutil.a ENDIF IF[{- !$disabled{'qlog'} -}] SOURCE[quic_qlog_test]=quic_qlog_test.c INCLUDE[quic_qlog_test]=../include ../apps/include DEPEND[quic_qlog_test]=../libcrypto.a ../libssl.a libtestutil.a ENDIF SOURCE[asynctest]=asynctest.c INCLUDE[asynctest]=../include ../apps/include DEPEND[asynctest]=../libcrypto SOURCE[secmemtest]=secmemtest.c INCLUDE[secmemtest]=../include ../apps/include DEPEND[secmemtest]=../libcrypto libtestutil.a SOURCE[srptest]=srptest.c INCLUDE[srptest]=../include ../apps/include DEPEND[srptest]=../libcrypto libtestutil.a SOURCE[memleaktest]=memleaktest.c INCLUDE[memleaktest]=../include ../apps/include DEPEND[memleaktest]=../libcrypto libtestutil.a SOURCE[pkcs12_format_test]=pkcs12_format_test.c helpers/pkcs12.c INCLUDE[pkcs12_format_test]=../include ../apps/include DEPEND[pkcs12_format_test]=../libcrypto libtestutil.a SOURCE[pkcs12_api_test]=pkcs12_api_test.c helpers/pkcs12.c INCLUDE[pkcs12_api_test]=../include ../apps/include DEPEND[pkcs12_api_test]=../libcrypto libtestutil.a SOURCE[pkcs7_test]=pkcs7_test.c INCLUDE[pkcs7_test]=../include ../apps/include DEPEND[pkcs7_test]=../libcrypto libtestutil.a SOURCE[byteorder_test]=byteorder_test.c INCLUDE[byteorder_test]=../include ../apps/include DEPEND[byteorder_test]=../libcrypto.a libtestutil.a SOURCE[punycode_test]=punycode_test.c INCLUDE[punycode_test]=../include ../apps/include DEPEND[punycode_test]=../libcrypto.a libtestutil.a SOURCE[evp_byname_test]=evp_byname_test.c INCLUDE[evp_byname_test]=../include ../apps/include DEPEND[evp_byname_test]=../libcrypto libtestutil.a SOURCE[stack_test]=stack_test.c INCLUDE[stack_test]=../include ../apps/include DEPEND[stack_test]=../libcrypto libtestutil.a SOURCE[lhash_test]=lhash_test.c INCLUDE[lhash_test]=../include ../apps/include DEPEND[lhash_test]=../libcrypto.a libtestutil.a SOURCE[dtlsv1listentest]=dtlsv1listentest.c INCLUDE[dtlsv1listentest]=../include ../apps/include DEPEND[dtlsv1listentest]=../libssl libtestutil.a SOURCE[ct_test]=ct_test.c INCLUDE[ct_test]=../include ../apps/include DEPEND[ct_test]=../libcrypto libtestutil.a SOURCE[threadpool_test]=threadpool_test.c INCLUDE[threadpool_test]=.. ../include ../apps/include DEPEND[threadpool_test]=../libcrypto.a libtestutil.a SOURCE[threadstest]=threadstest.c INCLUDE[threadstest]=.. ../include ../apps/include DEPEND[threadstest]=../libcrypto.a libtestutil.a SOURCE[threadstest_fips]=threadstest_fips.c INCLUDE[threadstest_fips]=../include ../apps/include DEPEND[threadstest_fips]=../libcrypto libtestutil.a SOURCE[afalgtest]=afalgtest.c INCLUDE[afalgtest]=../include ../apps/include DEPEND[afalgtest]=../libcrypto libtestutil.a SOURCE[d2i_test]=d2i_test.c INCLUDE[d2i_test]=../include ../apps/include DEPEND[d2i_test]=../libcrypto libtestutil.a SOURCE[ssl_test_ctx_test]=ssl_test_ctx_test.c helpers/ssl_test_ctx.c INCLUDE[ssl_test_ctx_test]=../include ../apps/include DEPEND[ssl_test_ctx_test]=../libcrypto ../libssl libtestutil.a SOURCE[ssl_test]=ssl_test.c helpers/ssl_test_ctx.c helpers/handshake.c IF[{- !$disabled{'srp'} -}] SOURCE[ssl_test]=helpers/handshake_srp.c ENDIF INCLUDE[ssl_test]=../include ../apps/include DEPEND[ssl_test]=../libcrypto ../libssl libtestutil.a SOURCE[cipherlist_test]=cipherlist_test.c INCLUDE[cipherlist_test]=../include ../apps/include DEPEND[cipherlist_test]=../libcrypto ../libssl libtestutil.a INCLUDE[helpers/ssl_test_ctx.o]=../include INCLUDE[helpers/handshake.o]=.. ../include INCLUDE[helpers/pkcs12.o]=.. ../include INCLUDE[helpers/ssltestlib.o]=.. ../include INCLUDE[helpers/cmp_testlib.o]=.. ../include ../apps/include SOURCE[x509aux]=x509aux.c INCLUDE[x509aux]=../include ../apps/include DEPEND[x509aux]=../libcrypto libtestutil.a SOURCE[asynciotest]=asynciotest.c helpers/ssltestlib.c INCLUDE[asynciotest]=../include ../apps/include DEPEND[asynciotest]=../libcrypto ../libssl libtestutil.a SOURCE[bio_callback_test]=bio_callback_test.c INCLUDE[bio_callback_test]=../include ../apps/include DEPEND[bio_callback_test]=../libcrypto libtestutil.a SOURCE[bio_readbuffer_test]=bio_readbuffer_test.c INCLUDE[bio_readbuffer_test]=../include ../apps/include DEPEND[bio_readbuffer_test]=../libcrypto libtestutil.a SOURCE[bio_memleak_test]=bio_memleak_test.c INCLUDE[bio_memleak_test]=../include ../apps/include DEPEND[bio_memleak_test]=../libcrypto libtestutil.a SOURCE[bio_meth_test]=bio_meth_test.c INCLUDE[bio_meth_test]=../include ../apps/include DEPEND[bio_meth_test]=../libcrypto libtestutil.a SOURCE[bioprinttest]=bioprinttest.c INCLUDE[bioprinttest]=../include ../apps/include DEPEND[bioprinttest]=../libcrypto libtestutil.a SOURCE[bio_core_test]=bio_core_test.c INCLUDE[bio_core_test]=../include ../apps/include DEPEND[bio_core_test]=../libcrypto libtestutil.a SOURCE[bio_dgram_test]=bio_dgram_test.c INCLUDE[bio_dgram_test]=../include ../apps/include DEPEND[bio_dgram_test]=../libcrypto libtestutil.a SOURCE[bio_tfo_test]=bio_tfo_test.c INCLUDE[bio_tfo_test]=../include ../apps/include .. DEPEND[bio_tfo_test]=../libcrypto libtestutil.a SOURCE[membio_test]=membio_test.c INCLUDE[membio_test]=../include ../apps/include .. DEPEND[membio_test]=../libcrypto libtestutil.a SOURCE[bio_dgram_test]=bio_dgram_test.c INCLUDE[bio_dgram_test]=../include ../apps/include .. DEPEND[bio_dgram_test]=../libcrypto libtestutil.a SOURCE[params_api_test]=params_api_test.c INCLUDE[params_api_test]=../include ../apps/include DEPEND[params_api_test]=../libcrypto libtestutil.a SOURCE[params_conversion_test]=params_conversion_test.c INCLUDE[params_conversion_test]=../include ../apps/include DEPEND[params_conversion_test]=../libcrypto libtestutil.a SOURCE[param_build_test]=param_build_test.c INCLUDE[param_build_test]=../include ../apps/include DEPEND[param_build_test]=../libcrypto.a libtestutil.a SOURCE[sslapitest]=sslapitest.c helpers/ssltestlib.c filterprov.c tls-provider.c INCLUDE[sslapitest]=../include ../apps/include ../providers/common/include .. DEPEND[sslapitest]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[ssl_handshake_rtt_test]=ssl_handshake_rtt_test.c helpers/ssltestlib.c INCLUDE[ssl_handshake_rtt_test]=../include ../apps/include .. DEPEND[ssl_handshake_rtt_test]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[rpktest]=rpktest.c helpers/ssltestlib.c INCLUDE[rpktest]=../include ../apps/include .. DEPEND[rpktest]=../libcrypto ../libssl libtestutil.a SOURCE[defltfips_test]=defltfips_test.c INCLUDE[defltfips_test]=../include ../apps/include DEPEND[defltfips_test]=../libcrypto libtestutil.a SOURCE[fips_version_test]=fips_version_test.c INCLUDE[fips_version_test]=../include ../apps/include DEPEND[fips_version_test]=../libcrypto libtestutil.a SOURCE[ocspapitest]=ocspapitest.c INCLUDE[ocspapitest]=../include ../apps/include DEPEND[ocspapitest]=../libcrypto libtestutil.a IF[{- !$disabled{sock} -}] IF[{- !$disabled{http} -}] PROGRAMS{noinst}=http_test SOURCE[http_test]=http_test.c INCLUDE[http_test]=../include ../apps/include DEPEND[http_test]=../libcrypto libtestutil.a ENDIF PROGRAMS{noinst}=bio_addr_test SOURCE[bio_addr_test]=bio_addr_test.c INCLUDE[bio_addr_test]=../include ../apps/include DEPEND[bio_addr_test]=../libcrypto libtestutil.a ENDIF SOURCE[dtlstest]=dtlstest.c helpers/ssltestlib.c INCLUDE[dtlstest]=../include ../apps/include DEPEND[dtlstest]=../libcrypto ../libssl libtestutil.a SOURCE[sslcorrupttest]=sslcorrupttest.c helpers/ssltestlib.c INCLUDE[sslcorrupttest]=../include ../apps/include DEPEND[sslcorrupttest]=../libcrypto ../libssl libtestutil.a SOURCE[bio_base64_test]=bio_base64_test.c INCLUDE[bio_base64_test]=../include ../apps/include DEPEND[bio_base64_test]=../libcrypto libtestutil.a SOURCE[bio_enc_test]=bio_enc_test.c INCLUDE[bio_enc_test]=../include ../apps/include DEPEND[bio_enc_test]=../libcrypto libtestutil.a SOURCE[pkey_meth_test]=pkey_meth_test.c INCLUDE[pkey_meth_test]=../include ../apps/include DEPEND[pkey_meth_test]=../libcrypto libtestutil.a SOURCE[pkey_meth_kdf_test]=pkey_meth_kdf_test.c INCLUDE[pkey_meth_kdf_test]=../include ../apps/include DEPEND[pkey_meth_kdf_test]=../libcrypto libtestutil.a SOURCE[evp_kdf_test]=evp_kdf_test.c INCLUDE[evp_kdf_test]=../include ../apps/include DEPEND[evp_kdf_test]=../libcrypto libtestutil.a SOURCE[evp_xof_test]=evp_xof_test.c INCLUDE[evp_xof_test]=../include ../apps/include DEPEND[evp_xof_test]=../libcrypto libtestutil.a SOURCE[evp_pkey_dparams_test]=evp_pkey_dparams_test.c INCLUDE[evp_pkey_dparams_test]=../include ../apps/include DEPEND[evp_pkey_dparams_test]=../libcrypto libtestutil.a SOURCE[x509_time_test]=x509_time_test.c INCLUDE[x509_time_test]=../include ../apps/include DEPEND[x509_time_test]=../libcrypto libtestutil.a SOURCE[x509_test]=x509_test.c INCLUDE[x509_test]=../include ../apps/include DEPEND[x509_test]=../libcrypto libtestutil.a SOURCE[recordlentest]=recordlentest.c helpers/ssltestlib.c INCLUDE[recordlentest]=../include ../apps/include DEPEND[recordlentest]=../libcrypto ../libssl libtestutil.a SOURCE[drbgtest]=drbgtest.c INCLUDE[drbgtest]=../include ../apps/include ../providers/common/include \ ../providers/fips/include DEPEND[drbgtest]=../libcrypto.a libtestutil.a SOURCE[rand_status_test]=rand_status_test.c INCLUDE[rand_status_test]=../include ../apps/include DEPEND[rand_status_test]=../libcrypto libtestutil.a SOURCE[x509_dup_cert_test]=x509_dup_cert_test.c INCLUDE[x509_dup_cert_test]=../include ../apps/include DEPEND[x509_dup_cert_test]=../libcrypto libtestutil.a SOURCE[x509_load_cert_file_test]=x509_load_cert_file_test.c INCLUDE[x509_load_cert_file_test]=../include ../apps/include DEPEND[x509_load_cert_file_test]=../libcrypto libtestutil.a SOURCE[x509_check_cert_pkey_test]=x509_check_cert_pkey_test.c INCLUDE[x509_check_cert_pkey_test]=../include ../apps/include DEPEND[x509_check_cert_pkey_test]=../libcrypto libtestutil.a SOURCE[pemtest]=pemtest.c INCLUDE[pemtest]=../include ../apps/include DEPEND[pemtest]=../libcrypto libtestutil.a SOURCE[ssl_cert_table_internal_test]=ssl_cert_table_internal_test.c INCLUDE[ssl_cert_table_internal_test]=.. ../include ../apps/include DEPEND[ssl_cert_table_internal_test]=../libcrypto libtestutil.a SOURCE[ciphername_test]=ciphername_test.c INCLUDE[ciphername_test]=../include ../apps/include DEPEND[ciphername_test]=../libcrypto ../libssl libtestutil.a SOURCE[servername_test]=servername_test.c helpers/ssltestlib.c INCLUDE[servername_test]=../include ../apps/include DEPEND[servername_test]=../libcrypto ../libssl libtestutil.a IF[{- !$disabled{cms} -}] PROGRAMS{noinst}=cmsapitest SOURCE[cmsapitest]=cmsapitest.c INCLUDE[cmsapitest]=../include ../apps/include DEPEND[cmsapitest]=../libcrypto libtestutil.a ENDIF IF[{- !$disabled{psk} -}] PROGRAMS{noinst}=dtls_mtu_test SOURCE[dtls_mtu_test]=dtls_mtu_test.c helpers/ssltestlib.c INCLUDE[dtls_mtu_test]=.. ../include ../apps/include DEPEND[dtls_mtu_test]=../libcrypto ../libssl libtestutil.a ENDIF IF[{- !$disabled{shared} -}] PROGRAMS{noinst}=shlibloadtest SOURCE[shlibloadtest]=shlibloadtest.c simpledynamic.c INCLUDE[shlibloadtest]=../include ../apps/include PROGRAMS{noinst}=moduleloadtest SOURCE[moduleloadtest]=moduleloadtest.c simpledynamic.c INCLUDE[moduleloadtest]=../include ../apps/include ENDIF # cipher_overhead_test uses internal symbols, so it must be linked with # the static libraries PROGRAMS{noinst}=cipher_overhead_test SOURCE[cipher_overhead_test]=cipher_overhead_test.c INCLUDE[cipher_overhead_test]=.. ../include ../apps/include DEPEND[cipher_overhead_test]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[uitest]=uitest.c ../apps/lib/apps_ui.c INCLUDE[uitest]=.. ../include ../apps/include DEPEND[uitest]=../libcrypto ../libssl libtestutil.a SOURCE[cipherbytes_test]=cipherbytes_test.c INCLUDE[cipherbytes_test]=../include ../apps/include DEPEND[cipherbytes_test]=../libcrypto ../libssl libtestutil.a SOURCE[asn1_encode_test]=asn1_encode_test.c INCLUDE[asn1_encode_test]=../include ../apps/include DEPEND[asn1_encode_test]=../libcrypto libtestutil.a SOURCE[asn1_decode_test]=asn1_decode_test.c INCLUDE[asn1_decode_test]=../include ../apps/include DEPEND[asn1_decode_test]=../libcrypto libtestutil.a SOURCE[asn1_string_table_test]=asn1_string_table_test.c INCLUDE[asn1_string_table_test]=../include ../apps/include DEPEND[asn1_string_table_test]=../libcrypto libtestutil.a SOURCE[asn1_stable_parse_test]=asn1_stable_parse_test.c INCLUDE[asn1_stable_parse_test]=../include ../apps/include DEPEND[asn1_stable_parse_test]=../libcrypto libtestutil.a SOURCE[time_offset_test]=time_offset_test.c INCLUDE[time_offset_test]=../include ../apps/include DEPEND[time_offset_test]=../libcrypto libtestutil.a SOURCE[conf_include_test]=conf_include_test.c INCLUDE[conf_include_test]=../include ../apps/include DEPEND[conf_include_test]=../libcrypto libtestutil.a IF[{- !$disabled{cmp} -}] PROGRAMS{noinst}=cmp_asn_test cmp_ctx_test cmp_status_test cmp_hdr_test \ cmp_protect_test cmp_msg_test cmp_vfy_test \ cmp_server_test cmp_client_test ENDIF SOURCE[cmp_asn_test]=cmp_asn_test.c helpers/cmp_testlib.c INCLUDE[cmp_asn_test]=.. ../include ../apps/include DEPEND[cmp_asn_test]=../libcrypto.a libtestutil.a SOURCE[cmp_ctx_test]=cmp_ctx_test.c helpers/cmp_testlib.c INCLUDE[cmp_ctx_test]=.. ../include ../apps/include DEPEND[cmp_ctx_test]=../libcrypto.a libtestutil.a SOURCE[cmp_hdr_test]=cmp_hdr_test.c helpers/cmp_testlib.c INCLUDE[cmp_hdr_test]=.. ../include ../apps/include DEPEND[cmp_hdr_test]=../libcrypto.a libtestutil.a SOURCE[cmp_status_test]=cmp_status_test.c helpers/cmp_testlib.c INCLUDE[cmp_status_test]=.. ../include ../apps/include DEPEND[cmp_status_test]=../libcrypto.a libtestutil.a SOURCE[cmp_protect_test]=cmp_protect_test.c helpers/cmp_testlib.c INCLUDE[cmp_protect_test]=.. ../include ../apps/include DEPEND[cmp_protect_test]=../libcrypto.a libtestutil.a SOURCE[cmp_msg_test]=cmp_msg_test.c helpers/cmp_testlib.c INCLUDE[cmp_msg_test]=.. ../include ../apps/include DEPEND[cmp_msg_test]=../libcrypto.a libtestutil.a SOURCE[cmp_vfy_test]=cmp_vfy_test.c helpers/cmp_testlib.c INCLUDE[cmp_vfy_test]=.. ../include ../apps/include DEPEND[cmp_vfy_test]=../libcrypto.a libtestutil.a SOURCE[cmp_server_test]=cmp_server_test.c helpers/cmp_testlib.c INCLUDE[cmp_server_test]=.. ../include ../apps/include DEPEND[cmp_server_test]=../libcrypto.a libtestutil.a SOURCE[cmp_client_test]=cmp_client_test.c helpers/cmp_testlib.c ../apps/lib/cmp_mock_srv.c INCLUDE[cmp_client_test]=.. ../include ../apps/include DEPEND[cmp_client_test]=../libcrypto.a libtestutil.a SOURCE[ca_internals_test]=ca_internals_test.c ../apps/ca.c ../apps/lib/apps.c \ ../apps/lib/app_rand.c ../apps/lib/engine.c ../apps/lib/app_provider.c \ ../apps/lib/app_libctx.c ../apps/lib/fmt.c ../apps/lib/apps_ui.c \ ../apps/lib/app_x509.c ../crypto/asn1/a_time.c ../crypto/ctype.c INCLUDE[ca_internals_test]=.. ../include ../apps/include DEPEND[ca_internals_test]=libtestutil.a ../libssl # Internal test programs. These are essentially a collection of internal # test routines. Some of them need to reach internal symbols that aren't # available through the shared library (at least on Linux, Solaris, Windows # and VMS, where the exported symbols are those listed in util/*.num), these # programs are forcibly linked with the static libraries, where all symbols # are always available. IF[1] PROGRAMS{noinst}=asn1_internal_test modes_internal_test x509_internal_test \ tls13encryptiontest wpackettest ctype_internal_test \ rdcpu_sanitytest property_test ideatest rsa_mp_test \ rsa_sp800_56b_test bn_internal_test ecdsatest rsa_test \ rc2test rc4test rc5test hmactest ffc_internal_test \ asn1_dsa_internal_test dsatest dsa_no_digest_size_test \ dhtest ssl_old_test IF[{- !$disabled{poly1305} -}] PROGRAMS{noinst}=poly1305_internal_test ENDIF IF[{- !$disabled{chacha} -}] PROGRAMS{noinst}=chacha_internal_test ENDIF IF[{- !$disabled{siphash} -}] PROGRAMS{noinst}=siphash_internal_test ENDIF IF[{- !$disabled{sm2} -}] PROGRAMS{noinst}=sm2_internal_test ENDIF IF[{- !$disabled{sm3} -}] PROGRAMS{noinst}=sm3_internal_test ENDIF IF[{- !$disabled{sm4} -}] PROGRAMS{noinst}=sm4_internal_test ENDIF IF[{- !$disabled{ec} -}] PROGRAMS{noinst}=ectest ec_internal_test evp_pkey_dhkem_test ENDIF IF[{- !$disabled{ecx} -}] PROGRAMS{noinst}=curve448_internal_test ENDIF IF[{- !$disabled{cmac} -}] PROGRAMS{noinst}=cmactest ENDIF SOURCE[poly1305_internal_test]=poly1305_internal_test.c INCLUDE[poly1305_internal_test]=.. ../include ../apps/include DEPEND[poly1305_internal_test]=../libcrypto.a libtestutil.a SOURCE[chacha_internal_test]=chacha_internal_test.c INCLUDE[chacha_internal_test]=.. ../include ../apps/include DEPEND[chacha_internal_test]=../libcrypto.a libtestutil.a SOURCE[asn1_internal_test]=asn1_internal_test.c INCLUDE[asn1_internal_test]=.. ../include ../apps/include DEPEND[asn1_internal_test]=../libcrypto.a libtestutil.a SOURCE[modes_internal_test]=modes_internal_test.c INCLUDE[modes_internal_test]=.. ../include ../apps/include DEPEND[modes_internal_test]=../libcrypto.a libtestutil.a SOURCE[x509_internal_test]=x509_internal_test.c INCLUDE[x509_internal_test]=.. ../include ../apps/include DEPEND[x509_internal_test]=../libcrypto.a libtestutil.a SOURCE[rsa_test]=rsa_test.c INCLUDE[rsa_test]=../include ../apps/include DEPEND[rsa_test]=../libcrypto.a libtestutil.a SOURCE[rsa_mp_test]=rsa_mp_test.c INCLUDE[rsa_mp_test]=../include ../apps/include DEPEND[rsa_mp_test]=../libcrypto.a libtestutil.a SOURCE[ecdsatest]=ecdsatest.c INCLUDE[ecdsatest]=../include ../apps/include DEPEND[ecdsatest]=../libcrypto.a libtestutil.a SOURCE[dsatest]=dsatest.c INCLUDE[dsatest]=../include ../apps/include DEPEND[dsatest]=../libcrypto.a libtestutil.a SOURCE[dsa_no_digest_size_test]=dsa_no_digest_size_test.c INCLUDE[dsa_no_digest_size_test]=../include ../apps/include DEPEND[dsa_no_digest_size_test]=../libcrypto.a libtestutil.a SOURCE[tls13encryptiontest]=tls13encryptiontest.c INCLUDE[tls13encryptiontest]=.. ../include ../apps/include DEPEND[tls13encryptiontest]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[ideatest]=ideatest.c INCLUDE[ideatest]=../include ../apps/include DEPEND[ideatest]=../libcrypto.a libtestutil.a SOURCE[wpackettest]=wpackettest.c INCLUDE[wpackettest]=../include ../apps/include DEPEND[wpackettest]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[property_test]=property_test.c INCLUDE[property_test]=.. ../include ../apps/include DEPEND[property_test]=../libcrypto.a libtestutil.a SOURCE[ctype_internal_test]=ctype_internal_test.c INCLUDE[ctype_internal_test]=.. ../include ../apps/include DEPEND[ctype_internal_test]=../libcrypto.a libtestutil.a SOURCE[sparse_array_test]=sparse_array_test.c INCLUDE[sparse_array_test]=../include ../apps/include DEPEND[sparse_array_test]=../libcrypto.a libtestutil.a IF[{- !$disabled{quic} -}] SOURCE[priority_queue_test]=priority_queue_test.c INCLUDE[priority_queue_test]=../include ../apps/include DEPEND[priority_queue_test]=../libcrypto ../libssl.a libtestutil.a SOURCE[quicfaultstest]=quicfaultstest.c helpers/ssltestlib.c $QUICTESTHELPERS INCLUDE[quicfaultstest]=../include ../apps/include .. DEPEND[quicfaultstest]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[quicapitest]=quicapitest.c helpers/ssltestlib.c $QUICTESTHELPERS INCLUDE[quicapitest]=../include ../apps/include DEPEND[quicapitest]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[quic_newcid_test]=quic_newcid_test.c helpers/ssltestlib.c $QUICTESTHELPERS INCLUDE[quic_newcid_test]=../include ../apps/include .. DEPEND[quic_newcid_test]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[quic_srt_gen_test]=quic_srt_gen_test.c helpers/ssltestlib.c $QUICTESTHELPERS INCLUDE[quic_srt_gen_test]=../include ../apps/include .. DEPEND[quic_srt_gen_test]=../libcrypto.a ../libssl.a libtestutil.a ENDIF IF[{- !$disabled{qlog} -}] SOURCE[json_test]=json_test.c helpers/ssltestlib.c $QUICTESTHELPERS INCLUDE[json_test]=../include ../apps/include DEPEND[json_test]=../libcrypto.a ../libssl.a libtestutil.a ENDIF SOURCE[dhtest]=dhtest.c INCLUDE[dhtest]=../include ../apps/include DEPEND[dhtest]=../libcrypto.a libtestutil.a SOURCE[list_test]=list_test.c INCLUDE[list_test]=../include ../apps/include DEPEND[list_test]=libtestutil.a SOURCE[hmactest]=hmactest.c INCLUDE[hmactest]=../include ../apps/include DEPEND[hmactest]=../libcrypto.a libtestutil.a IF[{- !$disabled{cmac} -}] SOURCE[cmactest]=cmactest.c INCLUDE[cmactest]=../include ../apps/include DEPEND[cmactest]=../libcrypto.a libtestutil.a ENDIF SOURCE[siphash_internal_test]=siphash_internal_test.c INCLUDE[siphash_internal_test]=.. ../include ../apps/include DEPEND[siphash_internal_test]=../libcrypto.a libtestutil.a SOURCE[sm2_internal_test]=sm2_internal_test.c INCLUDE[sm2_internal_test]=../include ../apps/include DEPEND[sm2_internal_test]=../libcrypto.a libtestutil.a SOURCE[sm3_internal_test]=sm3_internal_test.c INCLUDE[sm3_internal_test]=../include ../apps/include DEPEND[sm3_internal_test]=../libcrypto.a libtestutil.a SOURCE[sm4_internal_test]=sm4_internal_test.c INCLUDE[sm4_internal_test]=.. ../include ../apps/include DEPEND[sm4_internal_test]=../libcrypto.a libtestutil.a SOURCE[destest]=destest.c INCLUDE[destest]=../include ../apps/include DEPEND[destest]=../libcrypto.a libtestutil.a SOURCE[rc2test]=rc2test.c INCLUDE[rc2test]=../include ../apps/include DEPEND[rc2test]=../libcrypto.a libtestutil.a SOURCE[rc4test]=rc4test.c INCLUDE[rc4test]=../include ../apps/include DEPEND[rc4test]=../libcrypto.a libtestutil.a SOURCE[rc5test]=rc5test.c INCLUDE[rc5test]=../include ../apps/include DEPEND[rc5test]=../libcrypto.a libtestutil.a SOURCE[ec_internal_test]=ec_internal_test.c $INITSRC INCLUDE[ec_internal_test]=../include ../crypto/ec ../apps/include DEPEND[ec_internal_test]=../libcrypto.a libtestutil.a IF[{- !$disabled{ecx} -}] SOURCE[curve448_internal_test]=curve448_internal_test.c INCLUDE[curve448_internal_test]=.. ../include ../apps/include ../crypto/ec/curve448 DEPEND[curve448_internal_test]=../libcrypto.a libtestutil.a ENDIF SOURCE[rc4test]=rc4test.c INCLUDE[rc4test]=../include ../apps/include DEPEND[rc4test]=../libcrypto.a libtestutil.a SOURCE[rdcpu_sanitytest]=rdcpu_sanitytest.c INCLUDE[rdcpu_sanitytest]=../include ../apps/include ../crypto DEPEND[rdcpu_sanitytest]=../libcrypto.a libtestutil.a SOURCE[rsa_sp800_56b_test]=rsa_sp800_56b_test.c INCLUDE[rsa_sp800_56b_test]=.. ../include ../crypto/rsa ../apps/include DEPEND[rsa_sp800_56b_test]=../libcrypto.a libtestutil.a IF[{- !$disabled{'deprecated-3.0'} -}] PROGRAMS{noinst}=rsa_x931_test SOURCE[rsa_x931_test]=rsa_x931_test.c INCLUDE[rsa_x931_test]=.. ../include ../apps/include DEPEND[rsa_x931_test]=../libcrypto.a libtestutil.a ENDIF SOURCE[bn_internal_test]=bn_internal_test.c INCLUDE[bn_internal_test]=.. ../include ../crypto/bn ../apps/include DEPEND[bn_internal_test]=../libcrypto.a libtestutil.a SOURCE[asn1_dsa_internal_test]=asn1_dsa_internal_test.c INCLUDE[asn1_dsa_internal_test]=.. ../include ../apps/include DEPEND[asn1_dsa_internal_test]=../libcrypto.a libtestutil.a IF[{- !$disabled{'ml-kem'} -}] PROGRAMS{noinst}=ml_kem_internal_test SOURCE[ml_kem_internal_test]=ml_kem_internal_test.c INCLUDE[ml_kem_internal_test]=../include ../apps/include DEPEND[ml_kem_internal_test]=../libcrypto.a libtestutil.a PROGRAMS{noinst}=ml_kem_evp_extra_test SOURCE[ml_kem_evp_extra_test]=ml_kem_evp_extra_test.c INCLUDE[ml_kem_evp_extra_test]=../include ../apps/include DEPEND[ml_kem_evp_extra_test]=../libcrypto.a libtestutil.a ENDIF SOURCE[keymgmt_internal_test]=keymgmt_internal_test.c INCLUDE[keymgmt_internal_test]=.. ../include ../apps/include DEPEND[keymgmt_internal_test]=../libcrypto.a libtestutil.a SOURCE[ffc_internal_test]=ffc_internal_test.c INCLUDE[ffc_internal_test]=.. ../include ../apps/include DEPEND[ffc_internal_test]=../libcrypto.a libtestutil.a IF[{- !$disabled{mdc2} -}] PROGRAMS{noinst}=mdc2_internal_test ENDIF SOURCE[mdc2_internal_test]=mdc2_internal_test.c INCLUDE[mdc2_internal_test]=.. ../include ../apps/include DEPEND[mdc2_internal_test]=../libcrypto.a libtestutil.a SOURCE[ssl_old_test]=ssl_old_test.c helpers/predefined_dhparams.c INCLUDE[ssl_old_test]=.. ../include ../apps/include DEPEND[ssl_old_test]=../libcrypto.a ../libssl.a libtestutil.a PROGRAMS{noinst}=ext_internal_test SOURCE[ext_internal_test]=ext_internal_test.c INCLUDE[ext_internal_test]=.. ../include ../apps/include DEPEND[ext_internal_test]=../libcrypto.a ../libssl.a libtestutil.a PROGRAMS{noinst}=algorithmid_test SOURCE[algorithmid_test]=algorithmid_test.c INCLUDE[algorithmid_test]=../include ../apps/include DEPEND[algorithmid_test]=../libcrypto.a libtestutil.a ENDIF PROGRAMS{noinst}=asn1_time_test SOURCE[asn1_time_test]=asn1_time_test.c ../crypto/ctype.c \ ../crypto/asn1/a_time.c INCLUDE[asn1_time_test]=../include ../apps/include DEPEND[asn1_time_test]=../libcrypto libtestutil.a # We disable this test completely in a shared build because it deliberately # redefines some internal libssl symbols. This doesn't work in a non-shared # build IF[{- !$disabled{shared} -}] PROGRAMS{noinst}=tls13secretstest SOURCE[tls13secretstest]=tls13secretstest.c DEFINE[tls13secretstest]=OPENSSL_NO_KTLS SOURCE[tls13secretstest]= ../ssl/tls13_enc.c ../crypto/packet.c ../crypto/quic_vlint.c INCLUDE[tls13secretstest]=.. ../include ../apps/include DEPEND[tls13secretstest]=../libcrypto ../libssl libtestutil.a ENDIF SOURCE[sslbuffertest]=sslbuffertest.c helpers/ssltestlib.c INCLUDE[sslbuffertest]=../include ../apps/include DEPEND[sslbuffertest]=../libcrypto ../libssl libtestutil.a SOURCE[sysdefaulttest]=sysdefaulttest.c INCLUDE[sysdefaulttest]=../include ../apps/include DEPEND[sysdefaulttest]=../libcrypto ../libssl libtestutil.a SOURCE[errtest]=errtest.c INCLUDE[errtest]=../include ../apps/include DEPEND[errtest]=../libcrypto libtestutil.a SOURCE[aesgcmtest]=aesgcmtest.c INCLUDE[aesgcmtest]=../include ../apps/include .. DEPEND[aesgcmtest]=../libcrypto libtestutil.a PROGRAMS{noinst}=context_internal_test SOURCE[context_internal_test]=context_internal_test.c INCLUDE[context_internal_test]=.. ../include ../apps/include DEPEND[context_internal_test]=../libcrypto.a libtestutil.a IF[{- !$disabled{zlib} || !$disabled{brotli} || !$disabled{zstd} -}] PROGRAMS{noinst}=bio_comp_test SOURCE[bio_comp_test]=bio_comp_test.c INCLUDE[bio_comp_test]=../include ../apps/include DEPEND[bio_comp_test]=../libcrypto.a libtestutil.a ENDIF PROGRAMS{noinst}=provider_internal_test DEFINE[provider_internal_test]=PROVIDER_INIT_FUNCTION_NAME=p_test_init SOURCE[provider_internal_test]=provider_internal_test.c p_test.c INCLUDE[provider_internal_test]=../include ../apps/include .. DEPEND[provider_internal_test]=../libcrypto.a libtestutil.a PROGRAMS{noinst}=provider_test DEFINE[provider_test]=PROVIDER_INIT_FUNCTION_NAME=p_test_init SOURCE[provider_test]=provider_test.c p_test.c INCLUDE[provider_test]=../include ../apps/include .. DEPEND[provider_test]=../libcrypto.a libtestutil.a IF[{- !$disabled{module} -}] MODULES{noinst}=p_test SOURCE[p_test]=p_test.c INCLUDE[p_test]=../include .. IF[{- defined $target{shared_defflag} -}] SOURCE[p_test]=p_test.ld GENERATE[p_test.ld]=../util/providers.num ENDIF MODULES{noinst}=p_minimal SOURCE[p_minimal]=p_minimal.c INCLUDE[p_minimal]=../include .. IF[{- defined $target{shared_defflag} -}] SOURCE[p_minimal]=p_minimal.ld GENERATE[p_minimal.ld]=../util/providers.num ENDIF ENDIF IF[{- $disabled{module} || !$target{dso_scheme} -}] DEFINE[provider_test]=NO_PROVIDER_MODULE DEFINE[prov_config_test]=NO_PROVIDER_MODULE DEFINE[provider_internal_test]=NO_PROVIDER_MODULE ENDIF DEPEND[]=provider_internal_test.cnf GENERATE[provider_internal_test.cnf]=provider_internal_test.cnf.in PROGRAMS{noinst}=provider_fallback_test SOURCE[provider_fallback_test]=provider_fallback_test.c INCLUDE[provider_fallback_test]=../include ../apps/include DEPEND[provider_fallback_test]=../libcrypto libtestutil.a PROGRAMS{noinst}=provider_pkey_test SOURCE[provider_pkey_test]=provider_pkey_test.c fake_rsaprov.c INCLUDE[provider_pkey_test]=../include ../apps/include DEPEND[provider_pkey_test]=../libcrypto libtestutil.a PROGRAMS{noinst}=evp_skey_test SOURCE[evp_skey_test]=evp_skey_test.c fake_cipherprov.c INCLUDE[evp_skey_test]=../include ../apps/include DEPEND[evp_skey_test]=../libcrypto libtestutil.a PROGRAMS{noinst}=provider_default_search_path_test SOURCE[provider_default_search_path_test]=provider_default_search_path_test.c INCLUDE[provider_default_search_path_test]=../include ../apps/include DEPEND[provider_default_search_path_test]=../libcrypto libtestutil.a PROGRAMS{noinst}=params_test SOURCE[params_test]=params_test.c INCLUDE[params_test]=.. ../include ../apps/include DEPEND[params_test]=../libcrypto.a libtestutil.a PROGRAMS{noinst}=hexstr_test SOURCE[hexstr_test]=hexstr_test.c INCLUDE[hexstr_test]=.. ../include ../apps/include DEPEND[hexstr_test]=../libcrypto.a libtestutil.a PROGRAMS{noinst}=trace_api_test SOURCE[trace_api_test]=trace_api_test.c INCLUDE[trace_api_test]=.. ../include ../apps/include DEPEND[trace_api_test]=../libcrypto.a libtestutil.a PROGRAMS{noinst}=endecode_test SOURCE[endecode_test]=endecode_test.c helpers/predefined_dhparams.c INCLUDE[endecode_test]=.. ../include ../apps/include DEPEND[endecode_test]=../libcrypto.a libtestutil.a IF[{- !$disabled{module} && !$disabled{legacy} -}] DEFINE[endecode_test]=STATIC_LEGACY SOURCE[endecode_test]=../providers/legacyprov.c INCLUDE[endecode_test]=../providers/common/include \ ../providers/implementations/include DEPEND[endecode_test]=../providers/liblegacy.a \ ../providers/libcommon.a ENDIF IF[{- !$disabled{'deprecated-3.0'} -}] PROGRAMS{noinst}=endecoder_legacy_test SOURCE[endecoder_legacy_test]=endecoder_legacy_test.c INCLUDE[endecoder_legacy_test]=.. ../include ../apps/include DEPEND[endecoder_legacy_test]=../libcrypto.a libtestutil.a ENDIF PROGRAMS{noinst}=decoder_propq_test SOURCE[decoder_propq_test]=decoder_propq_test.c INCLUDE[decoder_propq_test]=.. ../include ../apps/include DEPEND[decoder_propq_test]=../libcrypto.a libtestutil.a PROGRAMS{noinst}=namemap_internal_test SOURCE[namemap_internal_test]=namemap_internal_test.c INCLUDE[namemap_internal_test]=.. ../include ../apps/include DEPEND[namemap_internal_test]=../libcrypto.a libtestutil.a PROGRAMS{noinst}=bio_prefix_text SOURCE[bio_prefix_text]=bio_prefix_text.c INCLUDE[bio_prefix_text]=.. ../include ../apps/include DEPEND[bio_prefix_text]=../libcrypto libtestutil.a IF[{- !$disabled{'deprecated-3.0'} -}] PROGRAMS{noinst}=pem_read_depr_test SOURCE[pem_read_depr_test]=pem_read_depr_test.c INCLUDE[pem_read_depr_test]=../include ../apps/include DEPEND[pem_read_depr_test]=../libcrypto libtestutil.a ENDIF ENDIF SOURCE[ssl_ctx_test]=ssl_ctx_test.c INCLUDE[ssl_ctx_test]=../include ../apps/include DEPEND[ssl_ctx_test]=../libcrypto ../libssl libtestutil.a SOURCE[build_wincrypt_test]=build_wincrypt_test.c INCLUDE[build_wincrypt_test]=../include DEPEND[build_wincrypt_test]=../libssl ../libcrypto IF[{- !$disabled{shared} -}] PROGRAMS{noinst}=timing_load_creds SOURCE[timing_load_creds]=timing_load_creds.c INCLUDE[timing_load_creds]=../include DEPEND[timing_load_creds]=../libcrypto.a ENDIF IF[{- !$disabled{'quic'} -}] PROGRAMS{noinst}=quic_wire_test quic_ackm_test quic_record_test PROGRAMS{noinst}=quic_fc_test quic_stream_test quic_cfq_test quic_txpim_test PROGRAMS{noinst}=quic_srtm_test quic_lcidm_test quic_rcidm_test PROGRAMS{noinst}=quic_fifd_test quic_txp_test quic_tserver_test PROGRAMS{noinst}=quic_client_test quic_cc_test quic_multistream_test PROGRAMS{noinst}=quic_radix_test SOURCE[quic_ackm_test]=quic_ackm_test.c cc_dummy.c INCLUDE[quic_ackm_test]=../include ../apps/include DEPEND[quic_ackm_test]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[quic_cc_test]=quic_cc_test.c INCLUDE[quic_cc_test]=../include ../apps/include DEPEND[quic_cc_test]=../libcrypto.a ../libssl.a libtestutil.a ENDIF SOURCE[cert_comp_test]=cert_comp_test.c helpers/ssltestlib.c INCLUDE[cert_comp_test]=../include ../apps/include .. DEPEND[cert_comp_test]=../libcrypto.a ../libssl.a libtestutil.a SOURCE[x509_acert_test]=x509_acert_test.c INCLUDE[x509_acert_test]=../include ../apps/include DEPEND[x509_acert_test]=../libcrypto libtestutil.a SOURCE[x509_req_test]=x509_req_test.c INCLUDE[x509_req_test]=../include ../apps/include DEPEND[x509_req_test]=../libcrypto libtestutil.a SOURCE[strtoultest]=strtoultest.c INCLUDE[strtoultest]=../include ../apps/include DEPEND[strtoultest]=../libcrypto libtestutil.a SOURCE[bio_pw_callback_test]=bio_pw_callback_test.c INCLUDE[bio_pw_callback_test]=../include ../apps/include DEPEND[bio_pw_callback_test]=../libcrypto libtestutil.a {- use File::Spec::Functions; use File::Basename; use OpenSSL::Glob; my @nogo_headers = ( "opensslconf.h", "__decc_include_prologue.h", "__decc_include_epilogue.h" ); my @nogo_headers_re = ( qr/.*err\.h/ ); my @headerfiles = glob catfile($sourcedir, updir(), "include", "openssl", "*.h"); foreach my $headerfile (@headerfiles) { my $name = basename($headerfile, ".h"); next if $disabled{$name}; next if grep { $_ eq lc("$name.h") } @nogo_headers; next if grep { lc("$name.h") =~ m/$_/i } @nogo_headers_re; $OUT .= <<"_____"; PROGRAMS{noinst}=buildtest_c_$name SOURCE[buildtest_c_$name]=buildtest_$name.c GENERATE[buildtest_$name.c]=generate_buildtest.pl $name INCLUDE[buildtest_c_$name]=../include DEPEND[buildtest_c_$name]=../libssl ../libcrypto _____ $OUT .= <<"_____" if $config{CXX} && !$disabled{"buildtest-c++"}; PROGRAMS{noinst}=buildtest_cc_$name SOURCE[buildtest_cc_$name]=buildtest_$name.cc GENERATE[buildtest_$name.cc]=generate_buildtest.pl $name INCLUDE[buildtest_cc_$name]=../include DEPEND[buildtest_cc_$name]=../libssl ../libcrypto _____ } -} diff --git a/test/fake_rsaprov.c b/test/fake_rsaprov.c index 46fc9104ef95..6ed121554336 100644 --- a/test/fake_rsaprov.c +++ b/test/fake_rsaprov.c @@ -1,1287 +1,1289 @@ /* * Copyright 2021-2025 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 may obtain a copy of the License at * https://www.openssl.org/source/license.html * or in the file LICENSE in the source distribution. */ #include #include #include #include #include #include #include #include "testutil.h" #include "fake_rsaprov.h" #include "internal/asn1.h" static OSSL_FUNC_keymgmt_new_fn fake_rsa_keymgmt_new; static OSSL_FUNC_keymgmt_free_fn fake_rsa_keymgmt_free; static OSSL_FUNC_keymgmt_has_fn fake_rsa_keymgmt_has; static OSSL_FUNC_keymgmt_query_operation_name_fn fake_rsa_keymgmt_query; static OSSL_FUNC_keymgmt_import_fn fake_rsa_keymgmt_import; static OSSL_FUNC_keymgmt_import_types_fn fake_rsa_keymgmt_imptypes; static OSSL_FUNC_keymgmt_export_fn fake_rsa_keymgmt_export; static OSSL_FUNC_keymgmt_export_types_fn fake_rsa_keymgmt_exptypes; static OSSL_FUNC_keymgmt_load_fn fake_rsa_keymgmt_load; static int has_selection; static int imptypes_selection; static int exptypes_selection; static int query_id; static int key_deleted; +unsigned fake_rsa_query_operation_name = 0; + typedef struct { OSSL_LIB_CTX *libctx; } PROV_FAKE_RSA_CTX; #define PROV_FAKE_RSA_LIBCTX_OF(provctx) (((PROV_FAKE_RSA_CTX *)provctx)->libctx) #define FAKE_RSA_STATUS_IMPORTED 1 #define FAKE_RSA_STATUS_GENERATED 2 #define FAKE_RSA_STATUS_DECODED 3 struct fake_rsa_keydata { int selection; int status; }; void fake_rsa_restore_store_state(void) { key_deleted = 0; } static void *fake_rsa_keymgmt_new(void *provctx) { struct fake_rsa_keydata *key; if (!TEST_ptr(key = OPENSSL_zalloc(sizeof(struct fake_rsa_keydata)))) return NULL; /* clear test globals */ has_selection = 0; imptypes_selection = 0; exptypes_selection = 0; query_id = 0; return key; } static void fake_rsa_keymgmt_free(void *keydata) { OPENSSL_free(keydata); } static int fake_rsa_keymgmt_has(const void *key, int selection) { /* record global for checking */ has_selection = selection; return 1; } static const char *fake_rsa_keymgmt_query(int id) { /* record global for checking */ query_id = id; - return "RSA"; + return fake_rsa_query_operation_name ? NULL: "RSA"; } static int fake_rsa_keymgmt_import(void *keydata, int selection, const OSSL_PARAM *p) { struct fake_rsa_keydata *fake_rsa_key = keydata; /* key was imported */ fake_rsa_key->status = FAKE_RSA_STATUS_IMPORTED; return 1; } static unsigned char fake_rsa_n[] = "\x00\xAA\x36\xAB\xCE\x88\xAC\xFD\xFF\x55\x52\x3C\x7F\xC4\x52\x3F" "\x90\xEF\xA0\x0D\xF3\x77\x4A\x25\x9F\x2E\x62\xB4\xC5\xD9\x9C\xB5" "\xAD\xB3\x00\xA0\x28\x5E\x53\x01\x93\x0E\x0C\x70\xFB\x68\x76\x93" "\x9C\xE6\x16\xCE\x62\x4A\x11\xE0\x08\x6D\x34\x1E\xBC\xAC\xA0\xA1" "\xF5"; static unsigned char fake_rsa_e[] = "\x11"; static unsigned char fake_rsa_d[] = "\x0A\x03\x37\x48\x62\x64\x87\x69\x5F\x5F\x30\xBC\x38\xB9\x8B\x44" "\xC2\xCD\x2D\xFF\x43\x40\x98\xCD\x20\xD8\xA1\x38\xD0\x90\xBF\x64" "\x79\x7C\x3F\xA7\xA2\xCD\xCB\x3C\xD1\xE0\xBD\xBA\x26\x54\xB4\xF9" "\xDF\x8E\x8A\xE5\x9D\x73\x3D\x9F\x33\xB3\x01\x62\x4A\xFD\x1D\x51"; static unsigned char fake_rsa_p[] = "\x00\xD8\x40\xB4\x16\x66\xB4\x2E\x92\xEA\x0D\xA3\xB4\x32\x04\xB5" "\xCF\xCE\x33\x52\x52\x4D\x04\x16\xA5\xA4\x41\xE7\x00\xAF\x46\x12" "\x0D"; static unsigned char fake_rsa_q[] = "\x00\xC9\x7F\xB1\xF0\x27\xF4\x53\xF6\x34\x12\x33\xEA\xAA\xD1\xD9" "\x35\x3F\x6C\x42\xD0\x88\x66\xB1\xD0\x5A\x0F\x20\x35\x02\x8B\x9D" "\x89"; static unsigned char fake_rsa_dmp1[] = "\x59\x0B\x95\x72\xA2\xC2\xA9\xC4\x06\x05\x9D\xC2\xAB\x2F\x1D\xAF" "\xEB\x7E\x8B\x4F\x10\xA7\x54\x9E\x8E\xED\xF5\xB4\xFC\xE0\x9E\x05"; static unsigned char fake_rsa_dmq1[] = "\x00\x8E\x3C\x05\x21\xFE\x15\xE0\xEA\x06\xA3\x6F\xF0\xF1\x0C\x99" "\x52\xC3\x5B\x7A\x75\x14\xFD\x32\x38\xB8\x0A\xAD\x52\x98\x62\x8D" "\x51"; static unsigned char fake_rsa_iqmp[] = "\x36\x3F\xF7\x18\x9D\xA8\xE9\x0B\x1D\x34\x1F\x71\xD0\x9B\x76\xA8" "\xA9\x43\xE1\x1D\x10\xB2\x4D\x24\x9F\x2D\xEA\xFE\xF8\x0C\x18\x26"; OSSL_PARAM *fake_rsa_key_params(int priv) { if (priv) { OSSL_PARAM params[] = { OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_N, fake_rsa_n, sizeof(fake_rsa_n) -1), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_E, fake_rsa_e, sizeof(fake_rsa_e) -1), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_D, fake_rsa_d, sizeof(fake_rsa_d) -1), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_FACTOR1, fake_rsa_p, sizeof(fake_rsa_p) -1), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_FACTOR2, fake_rsa_q, sizeof(fake_rsa_q) -1), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_EXPONENT1, fake_rsa_dmp1, sizeof(fake_rsa_dmp1) -1), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_EXPONENT2, fake_rsa_dmq1, sizeof(fake_rsa_dmq1) -1), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_COEFFICIENT1, fake_rsa_iqmp, sizeof(fake_rsa_iqmp) -1), OSSL_PARAM_END }; return OSSL_PARAM_dup(params); } else { OSSL_PARAM params[] = { OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_N, fake_rsa_n, sizeof(fake_rsa_n) -1), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_E, fake_rsa_e, sizeof(fake_rsa_e) -1), OSSL_PARAM_END }; return OSSL_PARAM_dup(params); } } static int fake_rsa_keymgmt_export(void *keydata, int selection, OSSL_CALLBACK *param_callback, void *cbarg) { OSSL_PARAM *params = NULL; int ret; if (selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) return 0; if (!TEST_ptr(params = fake_rsa_key_params(0))) return 0; ret = param_callback(params, cbarg); OSSL_PARAM_free(params); return ret; } static const OSSL_PARAM fake_rsa_import_key_types[] = { OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_N, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_E, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_D, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_FACTOR1, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_FACTOR2, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_EXPONENT1, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_EXPONENT2, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_COEFFICIENT1, NULL, 0), OSSL_PARAM_END }; static const OSSL_PARAM *fake_rsa_keymgmt_imptypes(int selection) { /* record global for checking */ imptypes_selection = selection; return fake_rsa_import_key_types; } static const OSSL_PARAM fake_rsa_export_key_types[] = { OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_N, NULL, 0), OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_E, NULL, 0), OSSL_PARAM_END }; static const OSSL_PARAM *fake_rsa_keymgmt_exptypes(int selection) { /* record global for checking */ exptypes_selection = selection; return fake_rsa_export_key_types; } static void *fake_rsa_keymgmt_load(const void *reference, size_t reference_sz) { struct fake_rsa_keydata *key = NULL; if (reference_sz != sizeof(key)) return NULL; key = *(struct fake_rsa_keydata **)reference; if (key->status != FAKE_RSA_STATUS_IMPORTED && key->status != FAKE_RSA_STATUS_DECODED) return NULL; /* detach the reference */ *(struct fake_rsa_keydata **)reference = NULL; return key; } static void *fake_rsa_gen_init(void *provctx, int selection, const OSSL_PARAM params[]) { unsigned char *gctx = NULL; if (!TEST_ptr(gctx = OPENSSL_malloc(1))) return NULL; *gctx = 1; return gctx; } static void *fake_rsa_gen(void *genctx, OSSL_CALLBACK *osslcb, void *cbarg) { unsigned char *gctx = genctx; static const unsigned char inited[] = { 1 }; struct fake_rsa_keydata *keydata; if (!TEST_ptr(gctx) || !TEST_mem_eq(gctx, sizeof(*gctx), inited, sizeof(inited))) return NULL; if (!TEST_ptr(keydata = fake_rsa_keymgmt_new(NULL))) return NULL; keydata->status = FAKE_RSA_STATUS_GENERATED; return keydata; } static void fake_rsa_gen_cleanup(void *genctx) { OPENSSL_free(genctx); } static const OSSL_DISPATCH fake_rsa_keymgmt_funcs[] = { { OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))fake_rsa_keymgmt_new }, { OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))fake_rsa_keymgmt_free} , { OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))fake_rsa_keymgmt_has }, { OSSL_FUNC_KEYMGMT_QUERY_OPERATION_NAME, (void (*)(void))fake_rsa_keymgmt_query }, { OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))fake_rsa_keymgmt_import }, { OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))fake_rsa_keymgmt_imptypes }, { OSSL_FUNC_KEYMGMT_EXPORT, (void (*)(void))fake_rsa_keymgmt_export }, { OSSL_FUNC_KEYMGMT_EXPORT_TYPES, (void (*)(void))fake_rsa_keymgmt_exptypes }, { OSSL_FUNC_KEYMGMT_LOAD, (void (*)(void))fake_rsa_keymgmt_load }, { OSSL_FUNC_KEYMGMT_GEN_INIT, (void (*)(void))fake_rsa_gen_init }, { OSSL_FUNC_KEYMGMT_GEN, (void (*)(void))fake_rsa_gen }, { OSSL_FUNC_KEYMGMT_GEN_CLEANUP, (void (*)(void))fake_rsa_gen_cleanup }, OSSL_DISPATCH_END }; static const OSSL_ALGORITHM fake_rsa_keymgmt_algs[] = { { "RSA:rsaEncryption", "provider=fake-rsa", fake_rsa_keymgmt_funcs, "Fake RSA Key Management" }, { NULL, NULL, NULL, NULL } }; static OSSL_FUNC_signature_newctx_fn fake_rsa_sig_newctx; static OSSL_FUNC_signature_freectx_fn fake_rsa_sig_freectx; static OSSL_FUNC_signature_sign_init_fn fake_rsa_sig_sign_init; static OSSL_FUNC_signature_sign_fn fake_rsa_sig_sign; static void *fake_rsa_sig_newctx(void *provctx, const char *propq) { unsigned char *sigctx = OPENSSL_zalloc(1); TEST_ptr(sigctx); return sigctx; } static void fake_rsa_sig_freectx(void *sigctx) { OPENSSL_free(sigctx); } static int fake_rsa_sig_sign_init(void *ctx, void *provkey, const OSSL_PARAM params[]) { unsigned char *sigctx = ctx; struct fake_rsa_keydata *keydata = provkey; /* we must have a ctx */ if (!TEST_ptr(sigctx)) return 0; /* we must have some initialized key */ if (!TEST_ptr(keydata) || !TEST_int_gt(keydata->status, 0)) return 0; /* record that sign init was called */ *sigctx = 1; return 1; } static int fake_rsa_sig_sign(void *ctx, unsigned char *sig, size_t *siglen, size_t sigsize, const unsigned char *tbs, size_t tbslen) { unsigned char *sigctx = ctx; /* we must have a ctx and init was called upon it */ if (!TEST_ptr(sigctx) || !TEST_int_eq(*sigctx, 1)) return 0; *siglen = 256; /* record that the real sign operation was called */ if (sig != NULL) { if (!TEST_int_ge(sigsize, *siglen)) return 0; *sigctx = 2; /* produce a fake signature */ memset(sig, 'a', *siglen); } return 1; } #define FAKE_DGSTSGN_SIGN 0x01 #define FAKE_DGSTSGN_VERIFY 0x02 #define FAKE_DGSTSGN_UPDATED 0x04 #define FAKE_DGSTSGN_FINALISED 0x08 #define FAKE_DGSTSGN_NO_DUP 0xA0 static void *fake_rsa_sig_dupctx(void *ctx) { unsigned char *sigctx = ctx; unsigned char *newctx; if ((*sigctx & FAKE_DGSTSGN_NO_DUP) != 0) return NULL; if (!TEST_ptr(newctx = OPENSSL_zalloc(1))) return NULL; *newctx = *sigctx; return newctx; } static int fake_rsa_dgstsgnvfy_init(void *ctx, unsigned char type, void *provkey, const OSSL_PARAM params[]) { unsigned char *sigctx = ctx; struct fake_rsa_keydata *keydata = provkey; /* we must have a ctx */ if (!TEST_ptr(sigctx)) return 0; /* we must have some initialized key */ if (!TEST_ptr(keydata) || !TEST_int_gt(keydata->status, 0)) return 0; /* record that sign/verify init was called */ *sigctx = type; if (params) { const OSSL_PARAM *p; int dup; p = OSSL_PARAM_locate_const(params, "NO_DUP"); if (p != NULL) { if (OSSL_PARAM_get_int(p, &dup)) { *sigctx |= FAKE_DGSTSGN_NO_DUP; } } } return 1; } static int fake_rsa_dgstsgn_init(void *ctx, const char *mdname, void *provkey, const OSSL_PARAM params[]) { return fake_rsa_dgstsgnvfy_init(ctx, FAKE_DGSTSGN_SIGN, provkey, params); } static int fake_rsa_dgstvfy_init(void *ctx, const char *mdname, void *provkey, const OSSL_PARAM params[]) { return fake_rsa_dgstsgnvfy_init(ctx, FAKE_DGSTSGN_VERIFY, provkey, params); } static int fake_rsa_dgstsgnvfy_update(void *ctx, const unsigned char *data, size_t datalen) { unsigned char *sigctx = ctx; /* we must have a ctx */ if (!TEST_ptr(sigctx)) return 0; if (*sigctx == 0 || (*sigctx & FAKE_DGSTSGN_FINALISED) != 0) return 0; *sigctx |= FAKE_DGSTSGN_UPDATED; return 1; } static int fake_rsa_dgstsgnvfy_final(void *ctx, unsigned char *sig, size_t *siglen, size_t sigsize) { unsigned char *sigctx = ctx; /* we must have a ctx */ if (!TEST_ptr(sigctx)) return 0; if (*sigctx == 0 || (*sigctx & FAKE_DGSTSGN_FINALISED) != 0) return 0; if ((*sigctx & FAKE_DGSTSGN_SIGN) != 0 && (siglen == NULL)) return 0; if ((*sigctx & FAKE_DGSTSGN_VERIFY) != 0 && (siglen != NULL)) return 0; /* this is sign op */ if (siglen) { *siglen = 256; /* record that the real sign operation was called */ if (sig != NULL) { if (!TEST_int_ge(sigsize, *siglen)) return 0; /* produce a fake signature */ memset(sig, 'a', *siglen); } } /* simulate inability to duplicate context and finalise it */ if ((*sigctx & FAKE_DGSTSGN_NO_DUP) != 0) { *sigctx |= FAKE_DGSTSGN_FINALISED; } return 1; } static int fake_rsa_dgstvfy_final(void *ctx, unsigned char *sig, size_t siglen) { return fake_rsa_dgstsgnvfy_final(ctx, sig, NULL, siglen); } static int fake_rsa_dgstsgn(void *ctx, unsigned char *sig, size_t *siglen, size_t sigsize, const unsigned char *tbs, size_t tbslen) { if (!fake_rsa_dgstsgnvfy_update(ctx, tbs, tbslen)) return 0; return fake_rsa_dgstsgnvfy_final(ctx, sig, siglen, sigsize); } static int fake_rsa_dgstvfy(void *ctx, unsigned char *sig, size_t siglen, const unsigned char *tbv, size_t tbvlen) { if (!fake_rsa_dgstsgnvfy_update(ctx, tbv, tbvlen)) return 0; return fake_rsa_dgstvfy_final(ctx, sig, siglen); } static const OSSL_DISPATCH fake_rsa_sig_funcs[] = { { OSSL_FUNC_SIGNATURE_NEWCTX, (void (*)(void))fake_rsa_sig_newctx }, { OSSL_FUNC_SIGNATURE_FREECTX, (void (*)(void))fake_rsa_sig_freectx }, { OSSL_FUNC_SIGNATURE_SIGN_INIT, (void (*)(void))fake_rsa_sig_sign_init }, { OSSL_FUNC_SIGNATURE_SIGN, (void (*)(void))fake_rsa_sig_sign }, { OSSL_FUNC_SIGNATURE_DUPCTX, (void (*)(void))fake_rsa_sig_dupctx }, { OSSL_FUNC_SIGNATURE_DIGEST_SIGN_INIT, (void (*)(void))fake_rsa_dgstsgn_init }, { OSSL_FUNC_SIGNATURE_DIGEST_SIGN_UPDATE, (void (*)(void))fake_rsa_dgstsgnvfy_update }, { OSSL_FUNC_SIGNATURE_DIGEST_SIGN_FINAL, (void (*)(void))fake_rsa_dgstsgnvfy_final }, { OSSL_FUNC_SIGNATURE_DIGEST_SIGN, (void (*)(void))fake_rsa_dgstsgn }, { OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_INIT, (void (*)(void))fake_rsa_dgstvfy_init }, { OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_UPDATE, (void (*)(void))fake_rsa_dgstsgnvfy_update }, { OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_FINAL, (void (*)(void))fake_rsa_dgstvfy_final }, { OSSL_FUNC_SIGNATURE_DIGEST_VERIFY, (void (*)(void))fake_rsa_dgstvfy }, OSSL_DISPATCH_END }; static const OSSL_ALGORITHM fake_rsa_sig_algs[] = { { "RSA:rsaEncryption", "provider=fake-rsa", fake_rsa_sig_funcs, "Fake RSA Signature" }, { NULL, NULL, NULL, NULL } }; static OSSL_FUNC_store_open_fn fake_rsa_st_open; static OSSL_FUNC_store_open_ex_fn fake_rsa_st_open_ex; static OSSL_FUNC_store_settable_ctx_params_fn fake_rsa_st_settable_ctx_params; static OSSL_FUNC_store_set_ctx_params_fn fake_rsa_st_set_ctx_params; static OSSL_FUNC_store_load_fn fake_rsa_st_load; static OSSL_FUNC_store_eof_fn fake_rsa_st_eof; static OSSL_FUNC_store_close_fn fake_rsa_st_close; static OSSL_FUNC_store_delete_fn fake_rsa_st_delete; static const char fake_rsa_scheme[] = "fake_rsa:"; static const char fake_rsa_openpwtest[] = "fake_rsa:openpwtest"; static const char fake_rsa_prompt[] = "Fake Prompt Info"; static void *fake_rsa_st_open_ex(void *provctx, const char *uri, const OSSL_PARAM params[], OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg) { unsigned char *storectx = NULL; /* First check whether the uri is ours */ if (strncmp(uri, fake_rsa_scheme, sizeof(fake_rsa_scheme) - 1) != 0) return NULL; if (strncmp(uri, fake_rsa_openpwtest, sizeof(fake_rsa_openpwtest) - 1) == 0) { const char *pw_check = FAKE_PASSPHRASE; char fakepw[sizeof(FAKE_PASSPHRASE) + 1] = { 0 }; size_t fakepw_len = 0; OSSL_PARAM pw_params[2] = { OSSL_PARAM_utf8_string(OSSL_PASSPHRASE_PARAM_INFO, (void *)fake_rsa_prompt, sizeof(fake_rsa_prompt) - 1), OSSL_PARAM_END, }; if (pw_cb == NULL) { return NULL; } if (!pw_cb(fakepw, sizeof(fakepw), &fakepw_len, pw_params, pw_cbarg)) { TEST_info("fake_rsa_open_ex failed passphrase callback"); return NULL; } if (strncmp(pw_check, fakepw, sizeof(pw_check) - 1) != 0) { TEST_info("fake_rsa_open_ex failed passphrase check"); return NULL; } } storectx = OPENSSL_zalloc(1); if (!TEST_ptr(storectx)) return NULL; TEST_info("fake_rsa_open_ex called"); return storectx; } static void *fake_rsa_st_open(void *provctx, const char *uri) { unsigned char *storectx = NULL; storectx = fake_rsa_st_open_ex(provctx, uri, NULL, NULL, NULL); TEST_info("fake_rsa_open called"); return storectx; } static const OSSL_PARAM *fake_rsa_st_settable_ctx_params(void *provctx) { static const OSSL_PARAM known_settable_ctx_params[] = { OSSL_PARAM_END }; return known_settable_ctx_params; } static int fake_rsa_st_set_ctx_params(void *loaderctx, const OSSL_PARAM params[]) { return 1; } static int fake_rsa_st_load(void *loaderctx, OSSL_CALLBACK *object_cb, void *object_cbarg, OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg) { unsigned char *storectx = loaderctx; OSSL_PARAM params[4]; int object_type = OSSL_OBJECT_PKEY; struct fake_rsa_keydata *key = NULL; int rv = 0; switch (*storectx) { case 0: if (key_deleted == 1) { *storectx = 1; break; } /* Construct a new key using our keymgmt functions */ if (!TEST_ptr(key = fake_rsa_keymgmt_new(NULL))) break; if (!TEST_int_gt(fake_rsa_keymgmt_import(key, 0, NULL), 0)) break; params[0] = OSSL_PARAM_construct_int(OSSL_OBJECT_PARAM_TYPE, &object_type); params[1] = OSSL_PARAM_construct_utf8_string(OSSL_OBJECT_PARAM_DATA_TYPE, "RSA", 0); /* The address of the key becomes the octet string */ params[2] = OSSL_PARAM_construct_octet_string(OSSL_OBJECT_PARAM_REFERENCE, &key, sizeof(key)); params[3] = OSSL_PARAM_construct_end(); rv = object_cb(params, object_cbarg); *storectx = 1; break; case 2: TEST_info("fake_rsa_load() called in error state"); break; default: TEST_info("fake_rsa_load() called in eof state"); break; } TEST_info("fake_rsa_load called - rv: %d", rv); if (rv == 0 && key_deleted == 0) { fake_rsa_keymgmt_free(key); *storectx = 2; } return rv; } static int fake_rsa_st_delete(void *loaderctx, const char *uri, const OSSL_PARAM params[], OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg) { key_deleted = 1; return 1; } static int fake_rsa_st_eof(void *loaderctx) { unsigned char *storectx = loaderctx; /* just one key for now in the fake_rsa store */ return *storectx != 0; } static int fake_rsa_st_close(void *loaderctx) { OPENSSL_free(loaderctx); return 1; } static const OSSL_DISPATCH fake_rsa_store_funcs[] = { { OSSL_FUNC_STORE_OPEN, (void (*)(void))fake_rsa_st_open }, { OSSL_FUNC_STORE_OPEN_EX, (void (*)(void))fake_rsa_st_open_ex }, { OSSL_FUNC_STORE_SETTABLE_CTX_PARAMS, (void (*)(void))fake_rsa_st_settable_ctx_params }, { OSSL_FUNC_STORE_SET_CTX_PARAMS, (void (*)(void))fake_rsa_st_set_ctx_params }, { OSSL_FUNC_STORE_LOAD, (void (*)(void))fake_rsa_st_load }, { OSSL_FUNC_STORE_EOF, (void (*)(void))fake_rsa_st_eof }, { OSSL_FUNC_STORE_CLOSE, (void (*)(void))fake_rsa_st_close }, { OSSL_FUNC_STORE_DELETE, (void (*)(void))fake_rsa_st_delete }, OSSL_DISPATCH_END, }; static const OSSL_ALGORITHM fake_rsa_store_algs[] = { { "fake_rsa", "provider=fake-rsa", fake_rsa_store_funcs }, { NULL, NULL, NULL } }; struct der2key_ctx_st; /* Forward declaration */ typedef int check_key_fn(void *, struct der2key_ctx_st *ctx); typedef void adjust_key_fn(void *, struct der2key_ctx_st *ctx); typedef void free_key_fn(void *); typedef void *d2i_PKCS8_fn(void **, const unsigned char **, long, struct der2key_ctx_st *); struct keytype_desc_st { const char *keytype_name; const OSSL_DISPATCH *fns; /* Keymgmt (to pilfer functions from) */ /* The input structure name */ const char *structure_name; /* * The EVP_PKEY_xxx type macro. Should be zero for type specific * structures, non-zero when the outermost structure is PKCS#8 or * SubjectPublicKeyInfo. This determines which of the function * pointers below will be used. */ int evp_type; /* The selection mask for OSSL_FUNC_decoder_does_selection() */ int selection_mask; /* For type specific decoders, we use the corresponding d2i */ d2i_of_void *d2i_private_key; /* From type-specific DER */ d2i_of_void *d2i_public_key; /* From type-specific DER */ d2i_of_void *d2i_key_params; /* From type-specific DER */ d2i_PKCS8_fn *d2i_PKCS8; /* Wrapped in a PrivateKeyInfo */ d2i_of_void *d2i_PUBKEY; /* Wrapped in a SubjectPublicKeyInfo */ /* * For any key, we may need to check that the key meets expectations. * This is useful when the same functions can decode several variants * of a key. */ check_key_fn *check_key; /* * For any key, we may need to make provider specific adjustments, such * as ensure the key carries the correct library context. */ adjust_key_fn *adjust_key; /* {type}_free() */ free_key_fn *free_key; }; /* * Start blatant code steal. Alternative: Open up d2i_X509_PUBKEY_INTERNAL * as per https://github.com/openssl/openssl/issues/16697 (TBD) * Code from openssl/crypto/x509/x_pubkey.c as * ossl_d2i_X509_PUBKEY_INTERNAL is presently not public */ struct X509_pubkey_st { X509_ALGOR *algor; ASN1_BIT_STRING *public_key; EVP_PKEY *pkey; /* extra data for the callback, used by d2i_PUBKEY_ex */ OSSL_LIB_CTX *libctx; char *propq; }; ASN1_SEQUENCE(X509_PUBKEY_INTERNAL) = { ASN1_SIMPLE(X509_PUBKEY, algor, X509_ALGOR), ASN1_SIMPLE(X509_PUBKEY, public_key, ASN1_BIT_STRING) } static_ASN1_SEQUENCE_END_name(X509_PUBKEY, X509_PUBKEY_INTERNAL) static X509_PUBKEY *fake_rsa_d2i_X509_PUBKEY_INTERNAL(const unsigned char **pp, long len, OSSL_LIB_CTX *libctx) { X509_PUBKEY *xpub = OPENSSL_zalloc(sizeof(*xpub)); if (xpub == NULL) return NULL; return (X509_PUBKEY *)ASN1_item_d2i_ex((ASN1_VALUE **)&xpub, pp, len, ASN1_ITEM_rptr(X509_PUBKEY_INTERNAL), libctx, NULL); } /* end steal https://github.com/openssl/openssl/issues/16697 */ /* * Context used for DER to key decoding. */ struct der2key_ctx_st { PROV_FAKE_RSA_CTX *provctx; struct keytype_desc_st *desc; /* The selection that is passed to fake_rsa_der2key_decode() */ int selection; /* Flag used to signal that a failure is fatal */ unsigned int flag_fatal : 1; }; static int fake_rsa_read_der(PROV_FAKE_RSA_CTX *provctx, OSSL_CORE_BIO *cin, unsigned char **data, long *len) { BUF_MEM *mem = NULL; BIO *in = BIO_new_from_core_bio(provctx->libctx, cin); int ok = (asn1_d2i_read_bio(in, &mem) >= 0); if (ok) { *data = (unsigned char *)mem->data; *len = (long)mem->length; OPENSSL_free(mem); } BIO_free(in); return ok; } typedef void *key_from_pkcs8_t(const PKCS8_PRIV_KEY_INFO *p8inf, OSSL_LIB_CTX *libctx, const char *propq); static void *fake_rsa_der2key_decode_p8(const unsigned char **input_der, long input_der_len, struct der2key_ctx_st *ctx, key_from_pkcs8_t *key_from_pkcs8) { PKCS8_PRIV_KEY_INFO *p8inf = NULL; const X509_ALGOR *alg = NULL; void *key = NULL; if ((p8inf = d2i_PKCS8_PRIV_KEY_INFO(NULL, input_der, input_der_len)) != NULL && PKCS8_pkey_get0(NULL, NULL, NULL, &alg, p8inf) && OBJ_obj2nid(alg->algorithm) == ctx->desc->evp_type) key = key_from_pkcs8(p8inf, PROV_FAKE_RSA_LIBCTX_OF(ctx->provctx), NULL); PKCS8_PRIV_KEY_INFO_free(p8inf); return key; } static struct fake_rsa_keydata *fake_rsa_d2i_PUBKEY(struct fake_rsa_keydata **a, const unsigned char **pp, long length) { struct fake_rsa_keydata *key = NULL; X509_PUBKEY *xpk; xpk = fake_rsa_d2i_X509_PUBKEY_INTERNAL(pp, length, NULL); if (xpk == NULL) goto err_exit; key = fake_rsa_keymgmt_new(NULL); if (key == NULL) goto err_exit; key->status = FAKE_RSA_STATUS_DECODED; if (a != NULL) { fake_rsa_keymgmt_free(*a); *a = key; } err_exit: X509_PUBKEY_free(xpk); return key; } /* ---------------------------------------------------------------------- */ static OSSL_FUNC_decoder_freectx_fn der2key_freectx; static OSSL_FUNC_decoder_decode_fn fake_rsa_der2key_decode; static OSSL_FUNC_decoder_export_object_fn der2key_export_object; static struct der2key_ctx_st * der2key_newctx(void *provctx, struct keytype_desc_st *desc, const char *tls_name) { struct der2key_ctx_st *ctx = OPENSSL_zalloc(sizeof(*ctx)); if (ctx != NULL) { ctx->provctx = provctx; ctx->desc = desc; if (desc->evp_type == 0) ctx->desc->evp_type = OBJ_sn2nid(tls_name); } return ctx; } static void der2key_freectx(void *vctx) { struct der2key_ctx_st *ctx = vctx; OPENSSL_free(ctx); } static int der2key_check_selection(int selection, const struct keytype_desc_st *desc) { /* * The selections are kinda sorta "levels", i.e. each selection given * here is assumed to include those following. */ int checks[] = { OSSL_KEYMGMT_SELECT_PRIVATE_KEY, OSSL_KEYMGMT_SELECT_PUBLIC_KEY, OSSL_KEYMGMT_SELECT_ALL_PARAMETERS }; size_t i; /* The decoder implementations made here support guessing */ if (selection == 0) return 1; for (i = 0; i < OSSL_NELEM(checks); i++) { int check1 = (selection & checks[i]) != 0; int check2 = (desc->selection_mask & checks[i]) != 0; /* * If the caller asked for the currently checked bit(s), return * whether the decoder description says it's supported. */ if (check1) return check2; } /* This should be dead code, but just to be safe... */ return 0; } static int fake_rsa_der2key_decode(void *vctx, OSSL_CORE_BIO *cin, int selection, OSSL_CALLBACK *data_cb, void *data_cbarg, OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg) { struct der2key_ctx_st *ctx = vctx; unsigned char *der = NULL; const unsigned char *derp; long der_len = 0; void *key = NULL; int ok = 0; ctx->selection = selection; /* * The caller is allowed to specify 0 as a selection mark, to have the * structure and key type guessed. For type-specific structures, this * is not recommended, as some structures are very similar. * Note that 0 isn't the same as OSSL_KEYMGMT_SELECT_ALL, as the latter * signifies a private key structure, where everything else is assumed * to be present as well. */ if (selection == 0) selection = ctx->desc->selection_mask; if ((selection & ctx->desc->selection_mask) == 0) { ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } ok = fake_rsa_read_der(ctx->provctx, cin, &der, &der_len); if (!ok) goto next; ok = 0; /* Assume that we fail */ if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) { derp = der; if (ctx->desc->d2i_PKCS8 != NULL) { key = ctx->desc->d2i_PKCS8(NULL, &derp, der_len, ctx); if (ctx->flag_fatal) goto end; } else if (ctx->desc->d2i_private_key != NULL) { key = ctx->desc->d2i_private_key(NULL, &derp, der_len); } if (key == NULL && ctx->selection != 0) goto next; } if (key == NULL && (selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) { derp = der; if (ctx->desc->d2i_PUBKEY != NULL) key = ctx->desc->d2i_PUBKEY(NULL, &derp, der_len); else key = ctx->desc->d2i_public_key(NULL, &derp, der_len); if (key == NULL && ctx->selection != 0) goto next; } if (key == NULL && (selection & OSSL_KEYMGMT_SELECT_ALL_PARAMETERS) != 0) { derp = der; if (ctx->desc->d2i_key_params != NULL) key = ctx->desc->d2i_key_params(NULL, &derp, der_len); if (key == NULL && ctx->selection != 0) goto next; } /* * Last minute check to see if this was the correct type of key. This * should never lead to a fatal error, i.e. the decoding itself was * correct, it was just an unexpected key type. This is generally for * classes of key types that have subtle variants, like RSA-PSS keys as * opposed to plain RSA keys. */ if (key != NULL && ctx->desc->check_key != NULL && !ctx->desc->check_key(key, ctx)) { ctx->desc->free_key(key); key = NULL; } if (key != NULL && ctx->desc->adjust_key != NULL) ctx->desc->adjust_key(key, ctx); next: /* * Indicated that we successfully decoded something, or not at all. * Ending up "empty handed" is not an error. */ ok = 1; /* * We free memory here so it's not held up during the callback, because * we know the process is recursive and the allocated chunks of memory * add up. */ OPENSSL_free(der); der = NULL; if (key != NULL) { OSSL_PARAM params[4]; int object_type = OSSL_OBJECT_PKEY; params[0] = OSSL_PARAM_construct_int(OSSL_OBJECT_PARAM_TYPE, &object_type); params[1] = OSSL_PARAM_construct_utf8_string(OSSL_OBJECT_PARAM_DATA_TYPE, (char *)ctx->desc->keytype_name, 0); /* The address of the key becomes the octet string */ params[2] = OSSL_PARAM_construct_octet_string(OSSL_OBJECT_PARAM_REFERENCE, &key, sizeof(key)); params[3] = OSSL_PARAM_construct_end(); ok = data_cb(params, data_cbarg); } end: ctx->desc->free_key(key); OPENSSL_free(der); return ok; } static OSSL_FUNC_keymgmt_export_fn * fake_rsa_prov_get_keymgmt_export(const OSSL_DISPATCH *fns) { /* Pilfer the keymgmt dispatch table */ for (; fns->function_id != 0; fns++) if (fns->function_id == OSSL_FUNC_KEYMGMT_EXPORT) return OSSL_FUNC_keymgmt_export(fns); return NULL; } static int der2key_export_object(void *vctx, const void *reference, size_t reference_sz, OSSL_CALLBACK *export_cb, void *export_cbarg) { struct der2key_ctx_st *ctx = vctx; OSSL_FUNC_keymgmt_export_fn *export = fake_rsa_prov_get_keymgmt_export(ctx->desc->fns); void *keydata; if (reference_sz == sizeof(keydata) && export != NULL) { /* The contents of the reference is the address to our object */ keydata = *(void **)reference; return export(keydata, ctx->selection, export_cb, export_cbarg); } return 0; } /* ---------------------------------------------------------------------- */ static struct fake_rsa_keydata *fake_rsa_key_from_pkcs8(const PKCS8_PRIV_KEY_INFO *p8inf, OSSL_LIB_CTX *libctx, const char *propq) { struct fake_rsa_keydata *key = fake_rsa_keymgmt_new(NULL); if (key) key->status = FAKE_RSA_STATUS_DECODED; return key; } #define rsa_evp_type EVP_PKEY_RSA static void *fake_rsa_d2i_PKCS8(void **key, const unsigned char **der, long der_len, struct der2key_ctx_st *ctx) { return fake_rsa_der2key_decode_p8(der, der_len, ctx, (key_from_pkcs8_t *)fake_rsa_key_from_pkcs8); } static void fake_rsa_key_adjust(void *key, struct der2key_ctx_st *ctx) { } /* ---------------------------------------------------------------------- */ #define DO_PrivateKeyInfo(keytype) \ "PrivateKeyInfo", keytype##_evp_type, \ (OSSL_KEYMGMT_SELECT_PRIVATE_KEY), \ NULL, \ NULL, \ NULL, \ fake_rsa_d2i_PKCS8, \ NULL, \ NULL, \ fake_rsa_key_adjust, \ (free_key_fn *)fake_rsa_keymgmt_free #define DO_SubjectPublicKeyInfo(keytype) \ "SubjectPublicKeyInfo", keytype##_evp_type, \ (OSSL_KEYMGMT_SELECT_PUBLIC_KEY), \ NULL, \ NULL, \ NULL, \ NULL, \ (d2i_of_void *)fake_rsa_d2i_PUBKEY, \ NULL, \ fake_rsa_key_adjust, \ (free_key_fn *)fake_rsa_keymgmt_free /* * MAKE_DECODER is the single driver for creating OSSL_DISPATCH tables. * It takes the following arguments: * * keytype_name The implementation key type as a string. * keytype The implementation key type. This must correspond exactly * to our existing keymgmt keytype names... in other words, * there must exist an ossl_##keytype##_keymgmt_functions. * type The type name for the set of functions that implement the * decoder for the key type. This isn't necessarily the same * as keytype. For example, the key types ed25519, ed448, * x25519 and x448 are all handled by the same functions with * the common type name ecx. * kind The kind of support to implement. This translates into * the DO_##kind macros above, to populate the keytype_desc_st * structure. */ #define MAKE_DECODER(keytype_name, keytype, type, kind) \ static struct keytype_desc_st kind##_##keytype##_desc = \ { keytype_name, fake_rsa_keymgmt_funcs, \ DO_##kind(keytype) }; \ \ static OSSL_FUNC_decoder_newctx_fn kind##_der2##keytype##_newctx; \ \ static void *kind##_der2##keytype##_newctx(void *provctx) \ { \ return der2key_newctx(provctx, &kind##_##keytype##_desc, keytype_name);\ } \ static int kind##_der2##keytype##_does_selection(void *provctx, \ int selection) \ { \ return der2key_check_selection(selection, \ &kind##_##keytype##_desc); \ } \ static const OSSL_DISPATCH \ fake_rsa_##kind##_der_to_##keytype##_decoder_functions[] = { \ { OSSL_FUNC_DECODER_NEWCTX, \ (void (*)(void))kind##_der2##keytype##_newctx }, \ { OSSL_FUNC_DECODER_FREECTX, \ (void (*)(void))der2key_freectx }, \ { OSSL_FUNC_DECODER_DOES_SELECTION, \ (void (*)(void))kind##_der2##keytype##_does_selection }, \ { OSSL_FUNC_DECODER_DECODE, \ (void (*)(void))fake_rsa_der2key_decode }, \ { OSSL_FUNC_DECODER_EXPORT_OBJECT, \ (void (*)(void))der2key_export_object }, \ OSSL_DISPATCH_END \ } MAKE_DECODER("RSA", rsa, rsa, PrivateKeyInfo); MAKE_DECODER("RSA", rsa, rsa, SubjectPublicKeyInfo); static const OSSL_ALGORITHM fake_rsa_decoder_algs[] = { #define DECODER_PROVIDER "fake-rsa" #define DECODER_STRUCTURE_SubjectPublicKeyInfo "SubjectPublicKeyInfo" #define DECODER_STRUCTURE_PrivateKeyInfo "PrivateKeyInfo" /* Arguments are prefixed with '_' to avoid build breaks on certain platforms */ /* * Obviously this is not FIPS approved, but in order to test in conjunction * with the FIPS provider we pretend that it is. */ #define DECODER(_name, _input, _output) \ { _name, \ "provider=" DECODER_PROVIDER ",fips=yes,input=" #_input, \ (fake_rsa_##_input##_to_##_output##_decoder_functions) \ } #define DECODER_w_structure(_name, _input, _structure, _output) \ { _name, \ "provider=" DECODER_PROVIDER ",fips=yes,input=" #_input \ ",structure=" DECODER_STRUCTURE_##_structure, \ (fake_rsa_##_structure##_##_input##_to_##_output##_decoder_functions) \ } DECODER_w_structure("RSA:rsaEncryption", der, PrivateKeyInfo, rsa), DECODER_w_structure("RSA:rsaEncryption", der, SubjectPublicKeyInfo, rsa), #undef DECODER_PROVIDER { NULL, NULL, NULL } }; static const OSSL_ALGORITHM *fake_rsa_query(void *provctx, int operation_id, int *no_cache) { *no_cache = 0; switch (operation_id) { case OSSL_OP_SIGNATURE: return fake_rsa_sig_algs; case OSSL_OP_KEYMGMT: return fake_rsa_keymgmt_algs; case OSSL_OP_STORE: return fake_rsa_store_algs; case OSSL_OP_DECODER: return fake_rsa_decoder_algs; } return NULL; } static void fake_rsa_prov_teardown(void *provctx) { PROV_FAKE_RSA_CTX *pctx = (PROV_FAKE_RSA_CTX *)provctx; OSSL_LIB_CTX_free(pctx->libctx); OPENSSL_free(pctx); } /* Functions we provide to the core */ static const OSSL_DISPATCH fake_rsa_method[] = { { OSSL_FUNC_PROVIDER_TEARDOWN, (void (*)(void))fake_rsa_prov_teardown }, { OSSL_FUNC_PROVIDER_QUERY_OPERATION, (void (*)(void))fake_rsa_query }, OSSL_DISPATCH_END }; static int fake_rsa_provider_init(const OSSL_CORE_HANDLE *handle, const OSSL_DISPATCH *in, const OSSL_DISPATCH **out, void **provctx) { OSSL_LIB_CTX *libctx; PROV_FAKE_RSA_CTX *prov_ctx; if (!TEST_ptr(libctx = OSSL_LIB_CTX_new_from_dispatch(handle, in))) return 0; if (!TEST_ptr(prov_ctx = OPENSSL_malloc(sizeof(*prov_ctx)))) { OSSL_LIB_CTX_free(libctx); return 0; } prov_ctx->libctx = libctx; *provctx = prov_ctx; *out = fake_rsa_method; return 1; } OSSL_PROVIDER *fake_rsa_start(OSSL_LIB_CTX *libctx) { OSSL_PROVIDER *p; if (!TEST_true(OSSL_PROVIDER_add_builtin(libctx, "fake-rsa", fake_rsa_provider_init)) || !TEST_ptr(p = OSSL_PROVIDER_try_load(libctx, "fake-rsa", 1))) return NULL; return p; } void fake_rsa_finish(OSSL_PROVIDER *p) { OSSL_PROVIDER_unload(p); } diff --git a/test/fake_rsaprov.h b/test/fake_rsaprov.h index cb2e66eb68ef..00e7dccb4872 100644 --- a/test/fake_rsaprov.h +++ b/test/fake_rsaprov.h @@ -1,18 +1,27 @@ /* - * Copyright 2021-2023 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2021-2025 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 #define FAKE_PASSPHRASE "Passphrase Testing" /* Fake RSA provider implementation */ OSSL_PROVIDER *fake_rsa_start(OSSL_LIB_CTX *libctx); void fake_rsa_finish(OSSL_PROVIDER *p); + OSSL_PARAM *fake_rsa_key_params(int priv); void fake_rsa_restore_store_state(void); + +/* + * When fake_rsa_query_operation_name is set to a non-zero value, + * query_operation_name() will return NULL. + * + * By default, it is 0, in which case query_operation_name() will return "RSA". + */ +extern unsigned fake_rsa_query_operation_name; diff --git a/test/ml_kem_evp_extra_test.c b/test/ml_kem_evp_extra_test.c index bfa52c9af2e6..b867b14ad1d4 100644 --- a/test/ml_kem_evp_extra_test.c +++ b/test/ml_kem_evp_extra_test.c @@ -1,435 +1,445 @@ /* * Copyright 2015-2025 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 #include #include #include #include "testutil.h" static OSSL_LIB_CTX *testctx = NULL; typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_CONFIG_FILE, OPT_TEST_RAND, OPT_TEST_ENUM } OPTION_CHOICE; const OPTIONS *test_get_options(void) { static const OPTIONS options[] = { OPT_TEST_OPTIONS_DEFAULT_USAGE, { "test-rand", OPT_TEST_RAND, '-', "Test non-derandomised ML-KEM" }, { NULL } }; return options; } static uint8_t gen_seed[64] = { 0x7c, 0x99, 0x35, 0xa0, 0xb0, 0x76, 0x94, 0xaa, 0x0c, 0x6d, 0x10, 0xe4, 0xdb, 0x6b, 0x1a, 0xdd, 0x2f, 0xd8, 0x1a, 0x25, 0xcc, 0xb1, 0x48, 0x03, 0x2d, 0xcd, 0x73, 0x99, 0x36, 0x73, 0x7f, 0x2d, 0x86, 0x26, 0xed, 0x79, 0xd4, 0x51, 0x14, 0x08, 0x00, 0xe0, 0x3b, 0x59, 0xb9, 0x56, 0xf8, 0x21, 0x0e, 0x55, 0x60, 0x67, 0x40, 0x7d, 0x13, 0xdc, 0x90, 0xfa, 0x9e, 0x8b, 0x87, 0x2b, 0xfb, 0x8f }; static uint8_t enc_seed[32] = { 0x14, 0x7c, 0x03, 0xf7, 0xa5, 0xbe, 0xbb, 0xa4, 0x06, 0xc8, 0xfa, 0xe1, 0x87, 0x4d, 0x7f, 0x13, 0xc8, 0x0e, 0xfe, 0x79, 0xa3, 0xa9, 0xa8, 0x74, 0xcc, 0x09, 0xfe, 0x76, 0xf6, 0x99, 0x76, 0x15 }; static uint8_t dec_seed[32] = { 0x4e, 0x6f, 0x74, 0x20, 0x74, 0x68, 0x65, 0x20, 0x64, 0x72, 0x6f, 0x69, 0x64, 0x73, 0x20, 0x79, 0x6f, 0x75, 0x27, 0x72, 0x65, 0x20, 0x6c, 0x6f, 0x6f, 0x6b, 0x69, 0x6e, 0x67, 0x20, 0x66, 0x6f }; static uint8_t expected_rho[3][32] = { { 0x7e, 0xfb, 0x9e, 0x40, 0xc3, 0xbf, 0x0f, 0xf0, 0x43, 0x29, 0x86, 0xae, 0x4b, 0xc1, 0xa2, 0x42, 0xce, 0x99, 0x21, 0xaa, 0x9e, 0x22, 0x44, 0x88, 0x19, 0x58, 0x5d, 0xea, 0x30, 0x8e, 0xb0, 0x39 }, { 0x16, 0x2e, 0xc0, 0x98, 0xa9, 0x00, 0xb1, 0x2d, 0xd8, 0xfa, 0xbb, 0xfb, 0x3f, 0xe8, 0xcb, 0x1d, 0xc4, 0xe8, 0x31, 0x5f, 0x2a, 0xf0, 0xd3, 0x2f, 0x00, 0x17, 0xae, 0x13, 0x6e, 0x19, 0xf0, 0x28 }, { 0x29, 0xb4, 0xf9, 0xf8, 0xcf, 0xba, 0xdf, 0x2e, 0x41, 0x86, 0x9a, 0xbf, 0xba, 0xd1, 0x07, 0x38, 0xad, 0x04, 0xcc, 0x75, 0x2b, 0xc2, 0x0c, 0x39, 0x47, 0x46, 0x85, 0x0e, 0x0c, 0x48, 0x47, 0xdb } }; static uint8_t expected_ctext_sha256[3][32] = { { 0xbc, 0x29, 0xd7, 0xdf, 0x8b, 0xc5, 0x46, 0x5d, 0x98, 0x06, 0x01, 0xd8, 0x00, 0x25, 0x97, 0x93, 0xe2, 0x60, 0x38, 0x25, 0xa5, 0x72, 0xda, 0x6c, 0xd1, 0x98, 0xa5, 0x12, 0xcc, 0x6d, 0x1a, 0x34 }, { 0x36, 0x82, 0x9a, 0x2f, 0x35, 0xcb, 0xf4, 0xde, 0xb6, 0x2c, 0x0a, 0x12, 0xa1, 0x5c, 0x22, 0xda, 0xe9, 0xf8, 0xd2, 0xc2, 0x52, 0x56, 0x6f, 0xc2, 0x4f, 0x88, 0xab, 0xe8, 0x05, 0xcb, 0x57, 0x5e }, { 0x50, 0x81, 0x36, 0xa1, 0x3f, 0x8a, 0x79, 0x20, 0xe3, 0x43, 0x44, 0x98, 0xc6, 0x97, 0x5c, 0xbb, 0xab, 0x45, 0x7d, 0x80, 0x93, 0x09, 0xeb, 0x2f, 0x92, 0x45, 0x3e, 0x74, 0x09, 0x73, 0x82, 0x10 } }; static uint8_t expected_shared_secret[3][32] = { { 0x31, 0x98, 0x39, 0xe8, 0x2a, 0xb6, 0xb2, 0x22, 0xde, 0x7b, 0x61, 0x9e, 0x80, 0xda, 0x83, 0x91, 0x52, 0x2b, 0xbb, 0x37, 0x67, 0x70, 0x18, 0x49, 0x4a, 0x47, 0x42, 0xc5, 0x3f, 0x9a, 0xbf, 0xdf }, { 0xe7, 0x18, 0x4a, 0x09, 0x75, 0xee, 0x34, 0x70, 0x87, 0x8d, 0x2d, 0x15, 0x9e, 0xc8, 0x31, 0x29, 0xc8, 0xae, 0xc2, 0x53, 0xd4, 0xee, 0x17, 0xb4, 0x81, 0x03, 0x11, 0xd1, 0x98, 0xcd, 0x03, 0x68 }, { 0x48, 0x9d, 0xd1, 0xe9, 0xc2, 0xbe, 0x4a, 0xf3, 0x48, 0x2b, 0xdb, 0x35, 0xbb, 0x26, 0xce, 0x76, 0x0e, 0x6e, 0x41, 0x4d, 0xa6, 0xec, 0xbe, 0x48, 0x99, 0x85, 0x74, 0x8a, 0x82, 0x5f, 0x1c, 0xd6 }, }; static int test_ml_kem(void) { EVP_PKEY *akey, *bkey = NULL; int res = 0; size_t publen; unsigned char *rawpub = NULL; EVP_PKEY_CTX *ctx = NULL; unsigned char *wrpkey = NULL, *agenkey = NULL, *bgenkey = NULL; size_t wrpkeylen, agenkeylen, bgenkeylen, i; /* Generate Alice's key */ akey = EVP_PKEY_Q_keygen(testctx, NULL, "ML-KEM-768"); if (!TEST_ptr(akey)) goto err; /* Get the raw public key */ publen = EVP_PKEY_get1_encoded_public_key(akey, &rawpub); if (!TEST_size_t_gt(publen, 0)) goto err; /* Create Bob's key and populate it with Alice's public key data */ bkey = EVP_PKEY_new(); if (!TEST_ptr(bkey)) goto err; if (!TEST_int_gt(EVP_PKEY_copy_parameters(bkey, akey), 0)) goto err; + /* Bob's empty key is not equal to Alice's */ + if (!TEST_false(EVP_PKEY_eq(akey, bkey)) + || !TEST_false(EVP_PKEY_eq(bkey, akey))) + goto err; + if (!TEST_true(EVP_PKEY_set1_encoded_public_key(bkey, rawpub, publen))) goto err; + /* Bob's copy of Alice's public key makes the two equal */ + if (!TEST_true(EVP_PKEY_eq(akey, bkey)) + || !TEST_true(EVP_PKEY_eq(bkey, akey))) + goto err; + /* Encapsulate Bob's key */ ctx = EVP_PKEY_CTX_new_from_pkey(testctx, bkey, NULL); if (!TEST_ptr(ctx)) goto err; if (!TEST_int_gt(EVP_PKEY_encapsulate_init(ctx, NULL), 0)) goto err; if (!TEST_int_gt(EVP_PKEY_encapsulate(ctx, NULL, &wrpkeylen, NULL, &bgenkeylen), 0)) goto err; if (!TEST_size_t_gt(wrpkeylen, 0) || !TEST_size_t_gt(bgenkeylen, 0)) goto err; wrpkey = OPENSSL_zalloc(wrpkeylen); bgenkey = OPENSSL_zalloc(bgenkeylen); if (!TEST_ptr(wrpkey) || !TEST_ptr(bgenkey)) goto err; if (!TEST_int_gt(EVP_PKEY_encapsulate(ctx, wrpkey, &wrpkeylen, bgenkey, &bgenkeylen), 0)) goto err; EVP_PKEY_CTX_free(ctx); /* Alice now decapsulates Bob's key */ ctx = EVP_PKEY_CTX_new_from_pkey(testctx, akey, NULL); if (!TEST_ptr(ctx)) goto err; if (!TEST_int_gt(EVP_PKEY_decapsulate_init(ctx, NULL), 0)) goto err; if (!TEST_int_gt(EVP_PKEY_decapsulate(ctx, NULL, &agenkeylen, wrpkey, wrpkeylen), 0)) goto err; if (!TEST_size_t_gt(agenkeylen, 0)) goto err; agenkey = OPENSSL_zalloc(agenkeylen); if (!TEST_ptr(agenkey)) goto err; if (!TEST_int_gt(EVP_PKEY_decapsulate(ctx, agenkey, &agenkeylen, wrpkey, wrpkeylen), 0)) goto err; /* Hopefully we ended up with a shared key */ if (!TEST_mem_eq(agenkey, agenkeylen, bgenkey, bgenkeylen)) goto err; /* Verify we generated a non-zero shared key */ for (i = 0; i < agenkeylen; i++) if (agenkey[i] != 0) break; if (!TEST_size_t_ne(i, agenkeylen)) goto err; res = 1; err: EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(akey); EVP_PKEY_free(bkey); OPENSSL_free(rawpub); OPENSSL_free(wrpkey); OPENSSL_free(agenkey); OPENSSL_free(bgenkey); return res; } static int test_non_derandomised_ml_kem(void) { static const int alg[3] = { EVP_PKEY_ML_KEM_512, EVP_PKEY_ML_KEM_768, EVP_PKEY_ML_KEM_1024 }; EVP_RAND_CTX *privctx; EVP_RAND_CTX *pubctx; EVP_MD *sha256; int i, ret = 0; if (!TEST_ptr(privctx = RAND_get0_private(NULL)) || !TEST_ptr(pubctx = RAND_get0_public(NULL))) return 0; if (!TEST_ptr(sha256 = EVP_MD_fetch(NULL, "sha256", NULL))) return 0; for (i = 0; i < (int) OSSL_NELEM(alg); ++i) { const ML_KEM_VINFO *v; OSSL_PARAM params[3], *p; uint8_t hash[32]; EVP_PKEY *akey = NULL, *bkey = NULL; size_t publen; unsigned char *rawpub = NULL; EVP_PKEY_CTX *ctx = NULL; unsigned char *wrpkey = NULL, *agenkey = NULL, *bgenkey = NULL; size_t wrpkeylen, agenkeylen, bgenkeylen; unsigned int strength = 256; unsigned char c; int res = -1; if ((v = ossl_ml_kem_get_vinfo(alg[i])) == NULL) goto done; /* Configure the private RNG to output just the keygen seed */ p = params; *p++ = OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY, gen_seed, sizeof(gen_seed)); *p++ = OSSL_PARAM_construct_uint(OSSL_RAND_PARAM_STRENGTH, &strength); *p = OSSL_PARAM_construct_end(); if (!TEST_true(EVP_RAND_CTX_set_params(privctx, params))) goto done; res = -2; /* Generate Alice's key */ akey = EVP_PKEY_Q_keygen(testctx, NULL, v->algorithm_name); if (!TEST_ptr(akey)) goto done; /* Check that no more entropy is available! */ if (!TEST_int_le(RAND_priv_bytes(&c, 1), 0)) goto done; /* Get the raw public key */ publen = EVP_PKEY_get1_encoded_public_key(akey, &rawpub); if (!TEST_size_t_eq(publen, v->pubkey_bytes)) goto done; res = -3; /* Check that we got the expected 'rho' value in the ciphertext */ if (!TEST_mem_eq(rawpub + v->vector_bytes, ML_KEM_RANDOM_BYTES, expected_rho[i], ML_KEM_RANDOM_BYTES)) goto done; res = -4; /* Create Bob's key and populate it with Alice's public key data */ bkey = EVP_PKEY_new(); if (!TEST_ptr(bkey)) goto done; if (!TEST_int_gt(EVP_PKEY_copy_parameters(bkey, akey), 0)) goto done; if (!TEST_true(EVP_PKEY_set1_encoded_public_key(bkey, rawpub, publen))) goto done; /* Configure the public RNG to output just the encap seed */ p = params; *p = OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY, enc_seed, sizeof(enc_seed)); if (!TEST_true(EVP_RAND_CTX_set_params(pubctx, params))) goto done; /* Encapsulate Bob's key */ res = -5; ctx = EVP_PKEY_CTX_new_from_pkey(testctx, bkey, NULL); if (!TEST_ptr(ctx)) goto done; if (!TEST_int_gt(EVP_PKEY_encapsulate_init(ctx, NULL), 0)) goto done; if (!TEST_int_gt(EVP_PKEY_encapsulate(ctx, NULL, &wrpkeylen, NULL, &bgenkeylen), 0)) goto done; if (!TEST_size_t_eq(wrpkeylen, v->ctext_bytes) || !TEST_size_t_eq(bgenkeylen, ML_KEM_SHARED_SECRET_BYTES)) goto done; wrpkey = OPENSSL_zalloc(wrpkeylen); bgenkey = OPENSSL_zalloc(bgenkeylen); if (!TEST_ptr(wrpkey) || !TEST_ptr(bgenkey)) goto done; if (!TEST_true(EVP_PKEY_encapsulate(ctx, wrpkey, &wrpkeylen, bgenkey, &bgenkeylen))) goto done; EVP_PKEY_CTX_free(ctx); ctx = NULL; /* Check that no more public entropy is available! */ if (!TEST_int_le(RAND_bytes(&c, 1), 0)) goto done; res = -6; /* Check the ciphertext hash */ if (!TEST_true(EVP_Digest(wrpkey, v->ctext_bytes, hash, NULL, sha256, NULL)) || !TEST_mem_eq(hash, sizeof(hash), expected_ctext_sha256[i], sizeof(expected_ctext_sha256[i]))) goto done; /* Check for the expected shared secret */ if (!TEST_mem_eq(bgenkey, bgenkeylen, expected_shared_secret[i], ML_KEM_SHARED_SECRET_BYTES)) goto done; /* * Alice now decapsulates Bob's key. Decap should not need a seed if * the ciphertext length is good. */ res = -7; ctx = EVP_PKEY_CTX_new_from_pkey(testctx, akey, NULL); if (!TEST_ptr(ctx)) goto done; if (!TEST_int_gt(EVP_PKEY_decapsulate_init(ctx, NULL), 0)) goto done; if (!TEST_true(EVP_PKEY_decapsulate(ctx, NULL, &agenkeylen, wrpkey, wrpkeylen))) goto done; if (!TEST_size_t_eq(agenkeylen, ML_KEM_SHARED_SECRET_BYTES)) goto done; agenkey = OPENSSL_zalloc(agenkeylen); if (!TEST_ptr(agenkey)) goto done; if (!TEST_true(EVP_PKEY_decapsulate(ctx, agenkey, &agenkeylen, wrpkey, wrpkeylen))) goto done; /* Hopefully we ended up with a shared key */ if (!TEST_mem_eq(agenkey, agenkeylen, bgenkey, bgenkeylen)) goto done; res = -8; /* Now a quick negative test by zeroing the ciphertext */ memset(wrpkey, 0, v->ctext_bytes); if (!TEST_true(EVP_PKEY_decapsulate(ctx, agenkey, &agenkeylen, wrpkey, wrpkeylen))) goto done; if (!TEST_mem_ne(agenkey, agenkeylen, bgenkey, bgenkeylen)) goto done; res = -9; /* Configure decap entropy for a bad ciphertext length */ p = params; *p = OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY, dec_seed, sizeof(dec_seed)); if (!TEST_true(EVP_RAND_CTX_set_params(pubctx, params))) goto done; /* This time decap should fail, and return the decap entropy */ if (!TEST_false(EVP_PKEY_decapsulate(ctx, agenkey, &agenkeylen, wrpkey, wrpkeylen - 1))) goto done; if (!TEST_mem_eq(agenkey, agenkeylen, dec_seed, sizeof(dec_seed))) goto done; res = 0; done: EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(akey); EVP_PKEY_free(bkey); OPENSSL_free(rawpub); OPENSSL_free(wrpkey); OPENSSL_free(agenkey); OPENSSL_free(bgenkey); if (res != 0) ret = res; } EVP_MD_free(sha256); return ret == 0; } int setup_tests(void) { int test_rand = 0; OPTION_CHOICE o; while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_TEST_RAND: test_rand = 1; break; case OPT_TEST_CASES: break; default: return 0; } } if (test_rand != 0) { /* Cargo-culted from test/rand_test.c, this may need changes */ if (!TEST_true(RAND_set_DRBG_type(NULL, "TEST-RAND", "fips=no", NULL, NULL))) return 0; ADD_TEST(test_non_derandomised_ml_kem); return 1; } ADD_TEST(test_ml_kem); return 1; } diff --git a/test/property_test.c b/test/property_test.c index 18f8cc8740e0..e62ff247c42c 100644 --- a/test/property_test.c +++ b/test/property_test.c @@ -1,705 +1,722 @@ /* - * Copyright 2019-2023 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2019-2025 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 "testutil.h" #include "internal/nelem.h" #include "internal/property.h" #include "../crypto/property/property_local.h" /* * We make our OSSL_PROVIDER for testing purposes. All we really need is * a pointer. We know that as long as we don't try to use the method * cache flush functions, the provider pointer is merely a pointer being * passed around, and used as a tag of sorts. */ struct ossl_provider_st { int x; }; static int add_property_names(const char *n, ...) { va_list args; int res = 1; va_start(args, n); do { if (!TEST_int_ne(ossl_property_name(NULL, n, 1), 0)) res = 0; } while ((n = va_arg(args, const char *)) != NULL); va_end(args); return res; } static int up_ref(void *p) { return 1; } static void down_ref(void *p) { } static int test_property_string(void) { OSSL_LIB_CTX *ctx; OSSL_METHOD_STORE *store = NULL; int res = 0; OSSL_PROPERTY_IDX i, j; /*- * Use our own library context because we depend on ordering from a * pristine state. */ if (TEST_ptr(ctx = OSSL_LIB_CTX_new()) && TEST_ptr(store = ossl_method_store_new(ctx)) && TEST_int_eq(ossl_property_name(ctx, "fnord", 0), 0) && TEST_int_ne(ossl_property_name(ctx, "fnord", 1), 0) && TEST_int_ne(ossl_property_name(ctx, "name", 1), 0) /* Pre loaded names */ && TEST_str_eq(ossl_property_name_str(ctx, 1), "provider") && TEST_str_eq(ossl_property_name_str(ctx, 2), "version") && TEST_str_eq(ossl_property_name_str(ctx, 3), "fips") && TEST_str_eq(ossl_property_name_str(ctx, 4), "output") && TEST_str_eq(ossl_property_name_str(ctx, 5), "input") && TEST_str_eq(ossl_property_name_str(ctx, 6), "structure") /* The names we added */ && TEST_str_eq(ossl_property_name_str(ctx, 7), "fnord") && TEST_str_eq(ossl_property_name_str(ctx, 8), "name") /* Out of range */ && TEST_ptr_null(ossl_property_name_str(ctx, 0)) && TEST_ptr_null(ossl_property_name_str(ctx, 9)) /* Property value checks */ && TEST_int_eq(ossl_property_value(ctx, "fnord", 0), 0) && TEST_int_ne(i = ossl_property_value(ctx, "no", 0), 0) && TEST_int_ne(j = ossl_property_value(ctx, "yes", 0), 0) && TEST_int_ne(i, j) && TEST_int_eq(ossl_property_value(ctx, "yes", 1), j) && TEST_int_eq(ossl_property_value(ctx, "no", 1), i) && TEST_int_ne(i = ossl_property_value(ctx, "illuminati", 1), 0) && TEST_int_eq(j = ossl_property_value(ctx, "fnord", 1), i + 1) && TEST_int_eq(ossl_property_value(ctx, "fnord", 1), j) /* Pre loaded values */ && TEST_str_eq(ossl_property_value_str(ctx, 1), "yes") && TEST_str_eq(ossl_property_value_str(ctx, 2), "no") /* The value we added */ && TEST_str_eq(ossl_property_value_str(ctx, 3), "illuminati") && TEST_str_eq(ossl_property_value_str(ctx, 4), "fnord") /* Out of range */ && TEST_ptr_null(ossl_property_value_str(ctx, 0)) && TEST_ptr_null(ossl_property_value_str(ctx, 5)) /* Check name and values are distinct */ && TEST_int_eq(ossl_property_value(ctx, "cold", 0), 0) && TEST_int_ne(ossl_property_name(ctx, "fnord", 0), ossl_property_value(ctx, "fnord", 0))) res = 1; ossl_method_store_free(store); OSSL_LIB_CTX_free(ctx); return res; } static const struct { const char *defn; const char *query; int e; } parser_tests[] = { { "", "sky=blue", -1 }, { "", "sky!=blue", 1 }, { "groan", "", 0 }, { "cold=yes", "cold=yes", 1 }, { "cold=yes", "cold", 1 }, { "cold=yes", "cold!=no", 1 }, { "groan", "groan=yes", 1 }, { "groan", "groan=no", -1 }, { "groan", "groan!=yes", -1 }, { "cold=no", "cold", -1 }, { "cold=no", "?cold", 0 }, { "cold=no", "cold=no", 1 }, { "groan", "cold", -1 }, { "groan", "cold=no", 1 }, { "groan", "cold!=yes", 1 }, { "groan=blue", "groan=yellow", -1 }, { "groan=blue", "?groan=yellow", 0 }, { "groan=blue", "groan!=yellow", 1 }, { "groan=blue", "?groan!=yellow", 1 }, { "today=monday, tomorrow=3", "today!=2", 1 }, { "today=monday, tomorrow=3", "today!='monday'", -1 }, { "today=monday, tomorrow=3", "tomorrow=3", 1 }, { "n=0x3", "n=3", 1 }, { "n=0x3", "n=-3", -1 }, { "n=0x33", "n=51", 1 }, { "n=0x123456789abcdef", "n=0x123456789abcdef", 1 }, { "n=0x7fffffffffffffff", "n=0x7fffffffffffffff", 1 }, /* INT64_MAX */ { "n=9223372036854775807", "n=9223372036854775807", 1 }, /* INT64_MAX */ { "n=0777777777777777777777", "n=0777777777777777777777", 1 }, /* INT64_MAX */ { "n=033", "n=27", 1 }, { "n=0", "n=00", 1 }, { "n=0x0", "n=0", 1 }, { "n=0, sky=blue", "?n=0, sky=blue", 2 }, { "n=1, sky=blue", "?n=0, sky=blue", 1 }, }; static int test_property_parse(int n) { OSSL_METHOD_STORE *store; OSSL_PROPERTY_LIST *p = NULL, *q = NULL; int r = 0; if (TEST_ptr(store = ossl_method_store_new(NULL)) && add_property_names("sky", "groan", "cold", "today", "tomorrow", "n", NULL) && TEST_ptr(p = ossl_parse_property(NULL, parser_tests[n].defn)) && TEST_ptr(q = ossl_parse_query(NULL, parser_tests[n].query, 0)) && TEST_int_eq(ossl_property_match_count(q, p), parser_tests[n].e)) r = 1; ossl_property_free(p); ossl_property_free(q); ossl_method_store_free(store); return r; } static int test_property_query_value_create(void) { OSSL_METHOD_STORE *store; OSSL_PROPERTY_LIST *p = NULL, *q = NULL, *o = NULL; int r = 0; /* The property value used here must not be used in other test cases */ if (TEST_ptr(store = ossl_method_store_new(NULL)) && add_property_names("wood", NULL) && TEST_ptr(p = ossl_parse_query(NULL, "wood=oak", 0)) /* undefined */ && TEST_ptr(q = ossl_parse_query(NULL, "wood=oak", 1)) /* creates */ && TEST_ptr(o = ossl_parse_query(NULL, "wood=oak", 0)) /* defined */ && TEST_int_eq(ossl_property_match_count(q, p), -1) && TEST_int_eq(ossl_property_match_count(q, o), 1)) r = 1; ossl_property_free(o); ossl_property_free(p); ossl_property_free(q); ossl_method_store_free(store); return r; } static const struct { int query; const char *ps; } parse_error_tests[] = { { 0, "n=1, n=1" }, /* duplicate name */ { 0, "n=1, a=hi, n=1" }, /* duplicate name */ { 1, "n=1, a=bye, ?n=0" }, /* duplicate name */ { 0, "a=abc,#@!, n=1" }, /* non-ASCII character located */ { 1, "a='Hello" }, /* Unterminated string */ { 0, "a=\"World" }, /* Unterminated string */ { 0, "a=_abd_" }, /* Unquoted string not starting with alphabetic */ { 1, "a=2, n=012345678" }, /* Bad octal digit */ { 0, "n=0x28FG, a=3" }, /* Bad hex digit */ { 0, "n=145d, a=2" }, /* Bad decimal digit */ { 0, "n=0x8000000000000000, a=3" }, /* Hex overflow */ { 0, "n=922337203000000000d, a=2" }, /* Decimal overflow */ { 0, "a=2, n=1000000000000000000000" }, /* Octal overflow */ { 1, "@='hello'" }, /* Invalid name */ { 1, "n0123456789012345678901234567890123456789" "0123456789012345678901234567890123456789" "0123456789012345678901234567890123456789" "0123456789012345678901234567890123456789=yes" }, /* Name too long */ { 0, ".n=3" }, /* Invalid name */ { 1, "fnord.fnord.=3" } /* Invalid name */ }; static int test_property_parse_error(int n) { OSSL_METHOD_STORE *store; OSSL_PROPERTY_LIST *p = NULL; int r = 0; const char *ps; if (!TEST_ptr(store = ossl_method_store_new(NULL)) || !add_property_names("a", "n", NULL)) goto err; ps = parse_error_tests[n].ps; if (parse_error_tests[n].query) { if (!TEST_ptr_null(p = ossl_parse_query(NULL, ps, 1))) goto err; } else if (!TEST_ptr_null(p = ossl_parse_property(NULL, ps))) { goto err; } r = 1; err: ossl_property_free(p); ossl_method_store_free(store); return r; } static const struct { const char *q_global; const char *q_local; const char *prop; } merge_tests[] = { { "", "colour=blue", "colour=blue" }, { "colour=blue", "", "colour=blue" }, { "colour=red", "colour=blue", "colour=blue" }, { "clouds=pink, urn=red", "urn=blue, colour=green", "urn=blue, colour=green, clouds=pink" }, { "pot=gold", "urn=blue", "pot=gold, urn=blue" }, { "night", "day", "day=yes, night=yes" }, { "day", "night", "day=yes, night=yes" }, { "", "", "" }, /* * The following four leave 'day' unspecified in the query, and will match * any definition */ { "day=yes", "-day", "day=no" }, { "day=yes", "-day", "day=yes" }, { "day=yes", "-day", "day=arglebargle" }, { "day=yes", "-day", "pot=sesquioxidizing" }, { "day, night", "-night, day", "day=yes, night=no" }, { "-day", "day=yes", "day=yes" }, }; static int test_property_merge(int n) { OSSL_METHOD_STORE *store; OSSL_PROPERTY_LIST *q_global = NULL, *q_local = NULL; OSSL_PROPERTY_LIST *q_combined = NULL, *prop = NULL; int r = 0; if (TEST_ptr(store = ossl_method_store_new(NULL)) && add_property_names("colour", "urn", "clouds", "pot", "day", "night", NULL) && TEST_ptr(prop = ossl_parse_property(NULL, merge_tests[n].prop)) && TEST_ptr(q_global = ossl_parse_query(NULL, merge_tests[n].q_global, 0)) && TEST_ptr(q_local = ossl_parse_query(NULL, merge_tests[n].q_local, 0)) && TEST_ptr(q_combined = ossl_property_merge(q_local, q_global)) && TEST_int_ge(ossl_property_match_count(q_combined, prop), 0)) r = 1; ossl_property_free(q_global); ossl_property_free(q_local); ossl_property_free(q_combined); ossl_property_free(prop); ossl_method_store_free(store); return r; } static int test_property_defn_cache(void) { OSSL_METHOD_STORE *store; OSSL_PROPERTY_LIST *red = NULL, *blue = NULL, *blue2 = NULL; int r; r = TEST_ptr(store = ossl_method_store_new(NULL)) && add_property_names("red", "blue", NULL) && TEST_ptr(red = ossl_parse_property(NULL, "red")) && TEST_ptr(blue = ossl_parse_property(NULL, "blue")) && TEST_ptr_ne(red, blue) && TEST_true(ossl_prop_defn_set(NULL, "red", &red)); if (!r) { ossl_property_free(red); red = NULL; ossl_property_free(blue); blue = NULL; } r = r && TEST_true(ossl_prop_defn_set(NULL, "blue", &blue)); if (!r) { ossl_property_free(blue); blue = NULL; } r = r && TEST_ptr_eq(ossl_prop_defn_get(NULL, "red"), red) && TEST_ptr_eq(ossl_prop_defn_get(NULL, "blue"), blue) && TEST_ptr(blue2 = ossl_parse_property(NULL, "blue")) && TEST_ptr_ne(blue2, blue) && TEST_true(ossl_prop_defn_set(NULL, "blue", &blue2)); if (!r) { ossl_property_free(blue2); blue2 = NULL; } r = r && TEST_ptr_eq(blue2, blue) && TEST_ptr_eq(ossl_prop_defn_get(NULL, "blue"), blue); ossl_method_store_free(store); return r; } static const struct { const char *defn; const char *query; int e; } definition_tests[] = { { "alpha", "alpha=yes", 1 }, { "alpha=no", "alpha", -1 }, { "alpha=1", "alpha=1", 1 }, { "alpha=2", "alpha=1",-1 }, { "alpha", "omega", -1 }, { "alpha", "?omega", 0 }, { "alpha", "?omega=1", 0 }, { "alpha", "?omega=no", 1 }, { "alpha", "?omega=yes", 0 }, { "alpha, omega", "?omega=yes", 1 }, { "alpha, omega", "?omega=no", 0 } }; static int test_definition_compares(int n) { OSSL_METHOD_STORE *store; OSSL_PROPERTY_LIST *d = NULL, *q = NULL; int r; r = TEST_ptr(store = ossl_method_store_new(NULL)) && add_property_names("alpha", "omega", NULL) && TEST_ptr(d = ossl_parse_property(NULL, definition_tests[n].defn)) && TEST_ptr(q = ossl_parse_query(NULL, definition_tests[n].query, 0)) && TEST_int_eq(ossl_property_match_count(q, d), definition_tests[n].e); ossl_property_free(d); ossl_property_free(q); ossl_method_store_free(store); return r; } static int test_register_deregister(void) { static const struct { int nid; const char *prop; char *impl; } impls[] = { { 6, "position=1", "a" }, { 6, "position=2", "b" }, { 6, "position=3", "c" }, { 6, "position=4", "d" }, }; size_t i; int ret = 0; OSSL_METHOD_STORE *store; OSSL_PROVIDER prov = { 1 }; if (!TEST_ptr(store = ossl_method_store_new(NULL)) || !add_property_names("position", NULL)) goto err; for (i = 0; i < OSSL_NELEM(impls); i++) if (!TEST_true(ossl_method_store_add(store, &prov, impls[i].nid, impls[i].prop, impls[i].impl, &up_ref, &down_ref))) { TEST_note("iteration %zd", i + 1); goto err; } /* Deregister in a different order to registration */ for (i = 0; i < OSSL_NELEM(impls); i++) { const size_t j = (1 + i * 3) % OSSL_NELEM(impls); int nid = impls[j].nid; void *impl = impls[j].impl; if (!TEST_true(ossl_method_store_remove(store, nid, impl)) || !TEST_false(ossl_method_store_remove(store, nid, impl))) { TEST_note("iteration %zd, position %zd", i + 1, j + 1); goto err; } } if (TEST_false(ossl_method_store_remove(store, impls[0].nid, impls[0].impl))) ret = 1; err: ossl_method_store_free(store); return ret; } static int test_property(void) { static OSSL_PROVIDER fake_provider1 = { 1 }; static OSSL_PROVIDER fake_provider2 = { 2 }; static const OSSL_PROVIDER *fake_prov1 = &fake_provider1; static const OSSL_PROVIDER *fake_prov2 = &fake_provider2; static const struct { const OSSL_PROVIDER **prov; int nid; const char *prop; char *impl; } impls[] = { { &fake_prov1, 1, "fast=no, colour=green", "a" }, { &fake_prov1, 1, "fast, colour=blue", "b" }, { &fake_prov1, 1, "", "-" }, { &fake_prov2, 9, "sky=blue, furry", "c" }, { &fake_prov2, 3, NULL, "d" }, { &fake_prov2, 6, "sky.colour=blue, sky=green, old.data", "e" }, }; static struct { const OSSL_PROVIDER **prov; int nid; const char *prop; char *expected; } queries[] = { { &fake_prov1, 1, "fast", "b" }, { &fake_prov1, 1, "fast=yes", "b" }, { &fake_prov1, 1, "fast=no, colour=green", "a" }, { &fake_prov1, 1, "colour=blue, fast", "b" }, { &fake_prov1, 1, "colour=blue", "b" }, { &fake_prov2, 9, "furry", "c" }, { &fake_prov2, 6, "sky.colour=blue", "e" }, { &fake_prov2, 6, "old.data", "e" }, { &fake_prov2, 9, "furry=yes, sky=blue", "c" }, { &fake_prov1, 1, "", "a" }, { &fake_prov2, 3, "", "d" }, }; OSSL_METHOD_STORE *store; size_t i; int ret = 0; void *result; if (!TEST_ptr(store = ossl_method_store_new(NULL)) || !add_property_names("fast", "colour", "sky", "furry", NULL)) goto err; for (i = 0; i < OSSL_NELEM(impls); i++) if (!TEST_true(ossl_method_store_add(store, *impls[i].prov, impls[i].nid, impls[i].prop, impls[i].impl, &up_ref, &down_ref))) { TEST_note("iteration %zd", i + 1); goto err; } /* * The first check of queries is with NULL given as provider. All * queries are expected to succeed. */ for (i = 0; i < OSSL_NELEM(queries); i++) { const OSSL_PROVIDER *nullprov = NULL; OSSL_PROPERTY_LIST *pq = NULL; if (!TEST_true(ossl_method_store_fetch(store, queries[i].nid, queries[i].prop, &nullprov, &result)) || !TEST_str_eq((char *)result, queries[i].expected)) { TEST_note("iteration %zd", i + 1); ossl_property_free(pq); goto err; } ossl_property_free(pq); } /* * The second check of queries is with &address1 given as provider. */ for (i = 0; i < OSSL_NELEM(queries); i++) { OSSL_PROPERTY_LIST *pq = NULL; result = NULL; if (queries[i].prov == &fake_prov1) { if (!TEST_true(ossl_method_store_fetch(store, queries[i].nid, queries[i].prop, &fake_prov1, &result)) || !TEST_ptr_eq(fake_prov1, &fake_provider1) || !TEST_str_eq((char *)result, queries[i].expected)) { TEST_note("iteration %zd", i + 1); ossl_property_free(pq); goto err; } } else { if (!TEST_false(ossl_method_store_fetch(store, queries[i].nid, queries[i].prop, &fake_prov1, &result)) || !TEST_ptr_eq(fake_prov1, &fake_provider1) || !TEST_ptr_null(result)) { TEST_note("iteration %zd", i + 1); ossl_property_free(pq); goto err; } } ossl_property_free(pq); } /* * The third check of queries is with &address2 given as provider. */ for (i = 0; i < OSSL_NELEM(queries); i++) { OSSL_PROPERTY_LIST *pq = NULL; result = NULL; if (queries[i].prov == &fake_prov2) { if (!TEST_true(ossl_method_store_fetch(store, queries[i].nid, queries[i].prop, &fake_prov2, &result)) || !TEST_ptr_eq(fake_prov2, &fake_provider2) || !TEST_str_eq((char *)result, queries[i].expected)) { TEST_note("iteration %zd", i + 1); ossl_property_free(pq); goto err; } } else { if (!TEST_false(ossl_method_store_fetch(store, queries[i].nid, queries[i].prop, &fake_prov2, &result)) || !TEST_ptr_eq(fake_prov2, &fake_provider2) || !TEST_ptr_null(result)) { TEST_note("iteration %zd", i + 1); ossl_property_free(pq); goto err; } } ossl_property_free(pq); } ret = 1; err: ossl_method_store_free(store); return ret; } static int test_query_cache_stochastic(void) { const int max = 10000, tail = 10; OSSL_METHOD_STORE *store; int i, res = 0; char buf[50]; void *result; int errors = 0; int v[10001]; OSSL_PROVIDER prov = { 1 }; if (!TEST_ptr(store = ossl_method_store_new(NULL)) || !add_property_names("n", NULL)) goto err; for (i = 1; i <= max; i++) { v[i] = 2 * i; BIO_snprintf(buf, sizeof(buf), "n=%d\n", i); if (!TEST_true(ossl_method_store_add(store, &prov, i, buf, "abc", &up_ref, &down_ref)) || !TEST_true(ossl_method_store_cache_set(store, &prov, i, buf, v + i, &up_ref, &down_ref)) || !TEST_true(ossl_method_store_cache_set(store, &prov, i, "n=1234", "miss", &up_ref, &down_ref))) { TEST_note("iteration %d", i); goto err; } } for (i = 1; i <= max; i++) { BIO_snprintf(buf, sizeof(buf), "n=%d\n", i); if (!ossl_method_store_cache_get(store, NULL, i, buf, &result) || result != v + i) errors++; } /* There is a tiny probability that this will fail when it shouldn't */ res = TEST_int_gt(errors, tail) && TEST_int_lt(errors, max - tail); err: ossl_method_store_free(store); return res; } static int test_fips_mode(void) { int ret = 0; OSSL_LIB_CTX *ctx = NULL; if (!TEST_ptr(ctx = OSSL_LIB_CTX_new())) goto err; ret = TEST_true(EVP_set_default_properties(ctx, "default=yes,fips=yes")) && TEST_true(EVP_default_properties_is_fips_enabled(ctx)) && TEST_true(EVP_set_default_properties(ctx, "fips=no,default=yes")) && TEST_false(EVP_default_properties_is_fips_enabled(ctx)) && TEST_true(EVP_set_default_properties(ctx, "fips=no")) && TEST_false(EVP_default_properties_is_fips_enabled(ctx)) && TEST_true(EVP_set_default_properties(ctx, "fips!=no")) && TEST_true(EVP_default_properties_is_fips_enabled(ctx)) && TEST_true(EVP_set_default_properties(ctx, "fips=no")) && TEST_false(EVP_default_properties_is_fips_enabled(ctx)) && TEST_true(EVP_set_default_properties(ctx, "fips=no,default=yes")) && TEST_true(EVP_default_properties_enable_fips(ctx, 1)) && TEST_true(EVP_default_properties_is_fips_enabled(ctx)) && TEST_true(EVP_default_properties_enable_fips(ctx, 0)) && TEST_false(EVP_default_properties_is_fips_enabled(ctx)); err: OSSL_LIB_CTX_free(ctx); return ret; } static struct { const char *in; const char *out; } to_string_tests[] = { { "fips=yes", "fips=yes" }, { "fips!=yes", "fips!=yes" }, { "fips = yes", "fips=yes" }, { "fips", "fips=yes" }, { "fips=no", "fips=no" }, { "-fips", "-fips" }, { "?fips=yes", "?fips=yes" }, { "fips=yes,provider=fips", "fips=yes,provider=fips" }, { "fips = yes , provider = fips", "fips=yes,provider=fips" }, { "fips=yes,provider!=fips", "fips=yes,provider!=fips" }, { "fips=yes,?provider=fips", "fips=yes,?provider=fips" }, { "fips=yes,-provider", "fips=yes,-provider" }, /* foo is an unknown internal name */ { "foo=yes,fips=yes", "fips=yes"}, { "", "" }, { "fips=3", "fips=3" }, { "fips=-3", "fips=-3" }, { "provider='foo bar'", "provider='foo bar'" }, { "provider=\"foo bar'\"", "provider=\"foo bar'\"" }, { "provider=abc***", "provider='abc***'" }, { NULL, "" } }; static int test_property_list_to_string(int i) { OSSL_PROPERTY_LIST *pl = NULL; int ret = 0; size_t bufsize; char *buf = NULL; if (to_string_tests[i].in != NULL && !TEST_ptr(pl = ossl_parse_query(NULL, to_string_tests[i].in, 1))) goto err; bufsize = ossl_property_list_to_string(NULL, pl, NULL, 0); if (!TEST_size_t_gt(bufsize, 0)) goto err; buf = OPENSSL_malloc(bufsize); if (!TEST_ptr(buf) || !TEST_size_t_eq(ossl_property_list_to_string(NULL, pl, buf, bufsize), bufsize) || !TEST_str_eq(to_string_tests[i].out, buf) || !TEST_size_t_eq(bufsize, strlen(to_string_tests[i].out) + 1)) goto err; ret = 1; err: OPENSSL_free(buf); ossl_property_free(pl); return ret; } +static int test_property_list_to_string_bounds(void) +{ + OSSL_PROPERTY_LIST *pl = NULL; + char buf[16]; + int ret = 0; + + if (!TEST_ptr(pl = ossl_parse_query(NULL, "provider='$1'", 1))) + goto err; + if (!TEST_size_t_eq(ossl_property_list_to_string(NULL, pl, buf, 10), 14)) + goto err; + ret = 1; + err: + ossl_property_free(pl); + return ret; +} + int setup_tests(void) { ADD_TEST(test_property_string); ADD_TEST(test_property_query_value_create); ADD_ALL_TESTS(test_property_parse, OSSL_NELEM(parser_tests)); ADD_ALL_TESTS(test_property_parse_error, OSSL_NELEM(parse_error_tests)); ADD_ALL_TESTS(test_property_merge, OSSL_NELEM(merge_tests)); ADD_TEST(test_property_defn_cache); ADD_ALL_TESTS(test_definition_compares, OSSL_NELEM(definition_tests)); ADD_TEST(test_register_deregister); ADD_TEST(test_property); ADD_TEST(test_query_cache_stochastic); ADD_TEST(test_fips_mode); ADD_ALL_TESTS(test_property_list_to_string, OSSL_NELEM(to_string_tests)); + ADD_TEST(test_property_list_to_string_bounds); return 1; } diff --git a/test/provider_pkey_test.c b/test/provider_pkey_test.c index cb656a62a650..9ffe3581d62a 100644 --- a/test/provider_pkey_test.c +++ b/test/provider_pkey_test.c @@ -1,733 +1,805 @@ /* * Copyright 2021-2025 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 "testutil.h" #include "fake_rsaprov.h" static OSSL_LIB_CTX *libctx = NULL; extern int key_deleted; /* From fake_rsaprov.c */ /* Fetch SIGNATURE method using a libctx and propq */ static int fetch_sig(OSSL_LIB_CTX *ctx, const char *alg, const char *propq, OSSL_PROVIDER *expected_prov) { OSSL_PROVIDER *prov; EVP_SIGNATURE *sig = EVP_SIGNATURE_fetch(ctx, "RSA", propq); int ret = 0; if (!TEST_ptr(sig)) return 0; if (!TEST_ptr(prov = EVP_SIGNATURE_get0_provider(sig))) goto end; if (!TEST_ptr_eq(prov, expected_prov)) { TEST_info("Fetched provider: %s, Expected provider: %s", OSSL_PROVIDER_get0_name(prov), OSSL_PROVIDER_get0_name(expected_prov)); goto end; } ret = 1; end: EVP_SIGNATURE_free(sig); return ret; } static int test_pkey_sig(void) { OSSL_PROVIDER *deflt = NULL; OSSL_PROVIDER *fake_rsa = NULL; int i, ret = 0; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; if (!TEST_ptr(fake_rsa = fake_rsa_start(libctx))) return 0; if (!TEST_ptr(deflt = OSSL_PROVIDER_load(libctx, "default"))) goto end; /* Do a direct fetch to see it works */ if (!TEST_true(fetch_sig(libctx, "RSA", "provider=fake-rsa", fake_rsa)) || !TEST_true(fetch_sig(libctx, "RSA", "?provider=fake-rsa", fake_rsa))) goto end; /* Construct a pkey using precise propq to use our provider */ if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(libctx, "RSA", "provider=fake-rsa")) || !TEST_true(EVP_PKEY_fromdata_init(ctx)) || !TEST_true(EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEYPAIR, NULL)) || !TEST_ptr(pkey)) goto end; EVP_PKEY_CTX_free(ctx); ctx = NULL; /* try exercising signature_init ops a few times */ for (i = 0; i < 3; i++) { size_t siglen; /* * Create a signing context for our pkey with optional propq. * The sign init should pick both keymgmt and signature from * fake-rsa as the key is not exportable. */ if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, "?provider=default"))) goto end; /* * If this picks the wrong signature without realizing it * we can get a segfault or some internal error. At least watch * whether fake-rsa sign_init is exercised by calling sign. */ if (!TEST_int_eq(EVP_PKEY_sign_init(ctx), 1)) goto end; if (!TEST_int_eq(EVP_PKEY_sign(ctx, NULL, &siglen, NULL, 0), 1) || !TEST_size_t_eq(siglen, 256)) goto end; EVP_PKEY_CTX_free(ctx); ctx = NULL; } ret = 1; end: fake_rsa_finish(fake_rsa); OSSL_PROVIDER_unload(deflt); EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); return ret; } static int test_alternative_keygen_init(void) { EVP_PKEY_CTX *ctx = NULL; OSSL_PROVIDER *deflt = NULL; OSSL_PROVIDER *fake_rsa = NULL; const OSSL_PROVIDER *provider; const char *provname; int ret = 0; if (!TEST_ptr(deflt = OSSL_PROVIDER_load(libctx, "default"))) goto end; /* first try without the fake RSA provider loaded */ if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(libctx, "RSA", NULL))) goto end; if (!TEST_int_gt(EVP_PKEY_keygen_init(ctx), 0)) goto end; if (!TEST_ptr(provider = EVP_PKEY_CTX_get0_provider(ctx))) goto end; if (!TEST_ptr(provname = OSSL_PROVIDER_get0_name(provider))) goto end; if (!TEST_str_eq(provname, "default")) goto end; EVP_PKEY_CTX_free(ctx); ctx = NULL; /* now load fake RSA and try again */ if (!TEST_ptr(fake_rsa = fake_rsa_start(libctx))) return 0; if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(libctx, "RSA", "?provider=fake-rsa"))) goto end; if (!TEST_int_gt(EVP_PKEY_keygen_init(ctx), 0)) goto end; if (!TEST_ptr(provider = EVP_PKEY_CTX_get0_provider(ctx))) goto end; if (!TEST_ptr(provname = OSSL_PROVIDER_get0_name(provider))) goto end; if (!TEST_str_eq(provname, "fake-rsa")) goto end; ret = 1; end: fake_rsa_finish(fake_rsa); OSSL_PROVIDER_unload(deflt); EVP_PKEY_CTX_free(ctx); return ret; } static int test_pkey_eq(void) { OSSL_PROVIDER *deflt = NULL; OSSL_PROVIDER *fake_rsa = NULL; EVP_PKEY *pkey_fake = NULL; EVP_PKEY *pkey_dflt = NULL; EVP_PKEY_CTX *ctx = NULL; OSSL_PARAM *params = NULL; int ret = 0; if (!TEST_ptr(fake_rsa = fake_rsa_start(libctx))) return 0; if (!TEST_ptr(deflt = OSSL_PROVIDER_load(libctx, "default"))) goto end; /* Construct a public key for fake-rsa */ if (!TEST_ptr(params = fake_rsa_key_params(0)) || !TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(libctx, "RSA", "provider=fake-rsa")) || !TEST_true(EVP_PKEY_fromdata_init(ctx)) || !TEST_true(EVP_PKEY_fromdata(ctx, &pkey_fake, EVP_PKEY_PUBLIC_KEY, params)) || !TEST_ptr(pkey_fake)) goto end; EVP_PKEY_CTX_free(ctx); ctx = NULL; OSSL_PARAM_free(params); params = NULL; /* Construct a public key for default */ if (!TEST_ptr(params = fake_rsa_key_params(0)) || !TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(libctx, "RSA", "provider=default")) || !TEST_true(EVP_PKEY_fromdata_init(ctx)) || !TEST_true(EVP_PKEY_fromdata(ctx, &pkey_dflt, EVP_PKEY_PUBLIC_KEY, params)) || !TEST_ptr(pkey_dflt)) goto end; EVP_PKEY_CTX_free(ctx); ctx = NULL; OSSL_PARAM_free(params); params = NULL; /* now test for equality */ if (!TEST_int_eq(EVP_PKEY_eq(pkey_fake, pkey_dflt), 1)) goto end; ret = 1; end: fake_rsa_finish(fake_rsa); OSSL_PROVIDER_unload(deflt); EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey_fake); EVP_PKEY_free(pkey_dflt); OSSL_PARAM_free(params); return ret; } +static int test_pkey_can_sign(void) +{ + OSSL_PROVIDER *fake_rsa = NULL; + EVP_PKEY *pkey_fake = NULL; + EVP_PKEY_CTX *ctx = NULL; + OSSL_PARAM *params = NULL; + int ret = 0; + + if (!TEST_ptr(fake_rsa = fake_rsa_start(libctx))) + return 0; + + /* + * Ensure other tests did not forget to reset fake_rsa_query_operation_name + * to its default value: 0 + */ + if (!TEST_int_eq(fake_rsa_query_operation_name, 0)) + goto end; + + if (!TEST_ptr(params = fake_rsa_key_params(0)) + || !TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(libctx, "RSA", + "provider=fake-rsa")) + || !TEST_true(EVP_PKEY_fromdata_init(ctx)) + || !TEST_true(EVP_PKEY_fromdata(ctx, &pkey_fake, EVP_PKEY_PUBLIC_KEY, + params)) + || !TEST_true(EVP_PKEY_can_sign(pkey_fake)) + || !TEST_ptr(pkey_fake)) + goto end; + + EVP_PKEY_CTX_free(ctx); + ctx = NULL; + EVP_PKEY_free(pkey_fake); + pkey_fake = NULL; + OSSL_PARAM_free(params); + params = NULL; + + /* + * Documented behavior for OSSL_FUNC_keymgmt_query_operation_name() + * allows it to return NULL, in which case the fallback should be to use + * EVP_KEYMGMT_get0_name(). That is exactly the thing we are testing here. + */ + fake_rsa_query_operation_name = 1; + + if (!TEST_ptr(params = fake_rsa_key_params(0)) + || !TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(libctx, "RSA", + "provider=fake-rsa")) + || !TEST_true(EVP_PKEY_fromdata_init(ctx)) + || !TEST_true(EVP_PKEY_fromdata(ctx, &pkey_fake, EVP_PKEY_PUBLIC_KEY, + params)) + || !TEST_true(EVP_PKEY_can_sign(pkey_fake)) + || !TEST_ptr(pkey_fake)) + goto end; + + EVP_PKEY_CTX_free(ctx); + ctx = NULL; + EVP_PKEY_free(pkey_fake); + pkey_fake = NULL; + OSSL_PARAM_free(params); + params = NULL; + + ret = 1; +end: + + EVP_PKEY_CTX_free(ctx); + EVP_PKEY_free(pkey_fake); + OSSL_PARAM_free(params); + fake_rsa_query_operation_name = 0; + + fake_rsa_finish(fake_rsa); + return ret; +} + static int test_pkey_store(int idx) { OSSL_PROVIDER *deflt = NULL; OSSL_PROVIDER *fake_rsa = NULL; int ret = 0; EVP_PKEY *pkey = NULL; OSSL_STORE_LOADER *loader = NULL; OSSL_STORE_CTX *ctx = NULL; OSSL_STORE_INFO *info; const char *propq = idx == 0 ? "?provider=fake-rsa" : "?provider=default"; /* It's important to load the default provider first for this test */ if (!TEST_ptr(deflt = OSSL_PROVIDER_load(libctx, "default"))) goto end; if (!TEST_ptr(fake_rsa = fake_rsa_start(libctx))) goto end; if (!TEST_ptr(loader = OSSL_STORE_LOADER_fetch(libctx, "fake_rsa", propq))) goto end; OSSL_STORE_LOADER_free(loader); if (!TEST_ptr(ctx = OSSL_STORE_open_ex("fake_rsa:test", libctx, propq, NULL, NULL, NULL, NULL, NULL))) goto end; while (!OSSL_STORE_eof(ctx) && (info = OSSL_STORE_load(ctx)) != NULL && pkey == NULL) { if (OSSL_STORE_INFO_get_type(info) == OSSL_STORE_INFO_PKEY) pkey = OSSL_STORE_INFO_get1_PKEY(info); OSSL_STORE_INFO_free(info); info = NULL; } if (!TEST_ptr(pkey) || !TEST_int_eq(EVP_PKEY_is_a(pkey, "RSA"), 1)) goto end; ret = 1; end: fake_rsa_finish(fake_rsa); OSSL_PROVIDER_unload(deflt); OSSL_STORE_close(ctx); EVP_PKEY_free(pkey); return ret; } static int test_pkey_delete(void) { OSSL_PROVIDER *deflt = NULL; OSSL_PROVIDER *fake_rsa = NULL; int ret = 0; EVP_PKEY *pkey = NULL; OSSL_STORE_LOADER *loader = NULL; OSSL_STORE_CTX *ctx = NULL; OSSL_STORE_INFO *info; const char *propq = "?provider=fake-rsa"; /* It's important to load the default provider first for this test */ if (!TEST_ptr(deflt = OSSL_PROVIDER_load(libctx, "default"))) goto end; if (!TEST_ptr(fake_rsa = fake_rsa_start(libctx))) goto end; if (!TEST_ptr(loader = OSSL_STORE_LOADER_fetch(libctx, "fake_rsa", propq))) goto end; OSSL_STORE_LOADER_free(loader); /* First iteration: load key, check it, delete it */ if (!TEST_ptr(ctx = OSSL_STORE_open_ex("fake_rsa:test", libctx, propq, NULL, NULL, NULL, NULL, NULL))) goto end; while (!OSSL_STORE_eof(ctx) && (info = OSSL_STORE_load(ctx)) != NULL && pkey == NULL) { if (OSSL_STORE_INFO_get_type(info) == OSSL_STORE_INFO_PKEY) pkey = OSSL_STORE_INFO_get1_PKEY(info); OSSL_STORE_INFO_free(info); info = NULL; } if (!TEST_ptr(pkey) || !TEST_int_eq(EVP_PKEY_is_a(pkey, "RSA"), 1)) goto end; EVP_PKEY_free(pkey); pkey = NULL; if (!TEST_int_eq(OSSL_STORE_delete("fake_rsa:test", libctx, propq, NULL, NULL, NULL), 1)) goto end; if (!TEST_int_eq(OSSL_STORE_close(ctx), 1)) goto end; /* Second iteration: load key should fail */ if (!TEST_ptr(ctx = OSSL_STORE_open_ex("fake_rsa:test", libctx, propq, NULL, NULL, NULL, NULL, NULL))) goto end; while (!OSSL_STORE_eof(ctx)) { info = OSSL_STORE_load(ctx); if (!TEST_ptr_null(info)) goto end; } ret = 1; end: fake_rsa_finish(fake_rsa); OSSL_PROVIDER_unload(deflt); OSSL_STORE_close(ctx); fake_rsa_restore_store_state(); return ret; } static int fake_pw_read_string(UI *ui, UI_STRING *uis) { const char *passphrase = FAKE_PASSPHRASE; if (UI_get_string_type(uis) == UIT_PROMPT) { UI_set_result(ui, uis, passphrase); return 1; } return 0; } static int test_pkey_store_open_ex(void) { OSSL_PROVIDER *deflt = NULL; OSSL_PROVIDER *fake_rsa = NULL; int ret = 0; EVP_PKEY *pkey = NULL; OSSL_STORE_LOADER *loader = NULL; OSSL_STORE_CTX *ctx = NULL; const char *propq = "?provider=fake-rsa"; UI_METHOD *ui_method = NULL; /* It's important to load the default provider first for this test */ if (!TEST_ptr(deflt = OSSL_PROVIDER_load(libctx, "default"))) goto end; if (!TEST_ptr(fake_rsa = fake_rsa_start(libctx))) goto end; if (!TEST_ptr(loader = OSSL_STORE_LOADER_fetch(libctx, "fake_rsa", propq))) goto end; OSSL_STORE_LOADER_free(loader); if (!TEST_ptr(ui_method= UI_create_method("PW Callbacks"))) goto end; if (UI_method_set_reader(ui_method, fake_pw_read_string)) goto end; if (!TEST_ptr(ctx = OSSL_STORE_open_ex("fake_rsa:openpwtest", libctx, propq, ui_method, NULL, NULL, NULL, NULL))) goto end; /* retry w/o ui_method to ensure we actually enter pw checks and fail */ OSSL_STORE_close(ctx); if (!TEST_ptr_null(ctx = OSSL_STORE_open_ex("fake_rsa:openpwtest", libctx, propq, NULL, NULL, NULL, NULL, NULL))) goto end; ret = 1; end: UI_destroy_method(ui_method); fake_rsa_finish(fake_rsa); OSSL_PROVIDER_unload(deflt); OSSL_STORE_close(ctx); EVP_PKEY_free(pkey); return ret; } #define DEFAULT_PROVIDER_IDX 0 #define FAKE_RSA_PROVIDER_IDX 1 static int reset_ctx_providers(OSSL_LIB_CTX **ctx, OSSL_PROVIDER *providers[2], const char *prop) { OSSL_PROVIDER_unload(providers[DEFAULT_PROVIDER_IDX]); providers[DEFAULT_PROVIDER_IDX] = NULL; fake_rsa_finish(providers[FAKE_RSA_PROVIDER_IDX]); providers[FAKE_RSA_PROVIDER_IDX] = NULL; OSSL_LIB_CTX_free(*ctx); *ctx = NULL; if (!TEST_ptr(*ctx = OSSL_LIB_CTX_new()) || !TEST_ptr(providers[DEFAULT_PROVIDER_IDX] = OSSL_PROVIDER_load(*ctx, "default")) || !TEST_ptr(providers[FAKE_RSA_PROVIDER_IDX] = fake_rsa_start(*ctx)) || !TEST_true(EVP_set_default_properties(*ctx, prop))) return 0; return 1; } struct test_pkey_decoder_properties_t { const char *provider_props; const char *explicit_props; int curr_provider_idx; }; static int test_pkey_provider_decoder_props(void) { OSSL_LIB_CTX *my_libctx = NULL; OSSL_PROVIDER *providers[2] = { NULL }; struct test_pkey_decoder_properties_t properties_test[] = { { "?provider=fake-rsa", NULL, FAKE_RSA_PROVIDER_IDX }, { "?provider=default", NULL, DEFAULT_PROVIDER_IDX }, { NULL, "?provider=fake-rsa", FAKE_RSA_PROVIDER_IDX }, { NULL, "?provider=default", DEFAULT_PROVIDER_IDX }, { NULL, "provider=fake-rsa", FAKE_RSA_PROVIDER_IDX }, { NULL, "provider=default", DEFAULT_PROVIDER_IDX }, }; EVP_PKEY *pkey = NULL; BIO *bio_priv = NULL; unsigned char *encoded_pub = NULL; int len_pub; const unsigned char *p; PKCS8_PRIV_KEY_INFO *p8 = NULL; size_t i; int ret = 0; const char pem_rsa_priv_key[] = { 0x2D, 0x2D, 0x2D, 0x2D, 0x2D, 0x42, 0x45, 0x47, 0x49, 0x4E, 0x20, 0x50, 0x52, 0x49, 0x56, 0x41, 0x54, 0x45, 0x20, 0x4B, 0x45, 0x59, 0x2D, 0x2D, 0x2D, 0x2D, 0x2D, 0x0A, 0x4D, 0x49, 0x49, 0x45, 0x76, 0x51, 0x49, 0x42, 0x41, 0x44, 0x41, 0x4E, 0x42, 0x67, 0x6B, 0x71, 0x68, 0x6B, 0x69, 0x47, 0x39, 0x77, 0x30, 0x42, 0x41, 0x51, 0x45, 0x46, 0x41, 0x41, 0x53, 0x43, 0x42, 0x4B, 0x63, 0x77, 0x67, 0x67, 0x53, 0x6A, 0x41, 0x67, 0x45, 0x41, 0x41, 0x6F, 0x49, 0x42, 0x41, 0x51, 0x44, 0x45, 0x6B, 0x43, 0x34, 0x5A, 0x57, 0x76, 0x33, 0x75, 0x63, 0x46, 0x62, 0x55, 0x0A, 0x46, 0x38, 0x59, 0x77, 0x6C, 0x55, 0x72, 0x6D, 0x51, 0x6C, 0x4C, 0x43, 0x5A, 0x77, 0x41, 0x67, 0x72, 0x34, 0x44, 0x50, 0x55, 0x41, 0x46, 0x56, 0x48, 0x6C, 0x2B, 0x77, 0x46, 0x63, 0x58, 0x79, 0x70, 0x56, 0x67, 0x53, 0x63, 0x56, 0x59, 0x34, 0x4B, 0x37, 0x51, 0x6D, 0x64, 0x57, 0x4B, 0x73, 0x59, 0x71, 0x62, 0x38, 0x74, 0x70, 0x4F, 0x78, 0x71, 0x77, 0x30, 0x4E, 0x77, 0x5A, 0x57, 0x58, 0x0A, 0x4F, 0x2B, 0x74, 0x61, 0x34, 0x2B, 0x79, 0x32, 0x37, 0x43, 0x4F, 0x75, 0x66, 0x6F, 0x4F, 0x68, 0x52, 0x54, 0x4D, 0x77, 0x4E, 0x79, 0x4E, 0x32, 0x4C, 0x77, 0x53, 0x4E, 0x54, 0x50, 0x4E, 0x33, 0x65, 0x45, 0x6B, 0x34, 0x65, 0x65, 0x35, 0x51, 0x6E, 0x70, 0x70, 0x45, 0x79, 0x44, 0x72, 0x71, 0x6F, 0x43, 0x67, 0x76, 0x54, 0x6C, 0x41, 0x41, 0x64, 0x54, 0x6F, 0x46, 0x61, 0x58, 0x76, 0x6A, 0x0A, 0x78, 0x31, 0x33, 0x59, 0x62, 0x6A, 0x37, 0x6A, 0x66, 0x68, 0x77, 0x4E, 0x37, 0x34, 0x71, 0x4B, 0x64, 0x71, 0x73, 0x53, 0x45, 0x74, 0x50, 0x57, 0x79, 0x67, 0x67, 0x65, 0x6F, 0x74, 0x69, 0x51, 0x53, 0x50, 0x79, 0x36, 0x4B, 0x79, 0x42, 0x49, 0x75, 0x57, 0x74, 0x49, 0x78, 0x50, 0x41, 0x41, 0x38, 0x6A, 0x41, 0x76, 0x66, 0x41, 0x6E, 0x51, 0x6A, 0x31, 0x65, 0x58, 0x68, 0x67, 0x68, 0x46, 0x0A, 0x4E, 0x32, 0x4E, 0x78, 0x6B, 0x71, 0x67, 0x78, 0x76, 0x42, 0x59, 0x64, 0x4E, 0x79, 0x31, 0x6D, 0x33, 0x2B, 0x6A, 0x58, 0x41, 0x43, 0x50, 0x4C, 0x52, 0x7A, 0x63, 0x31, 0x31, 0x5A, 0x62, 0x4E, 0x48, 0x4B, 0x69, 0x77, 0x68, 0x43, 0x59, 0x31, 0x2F, 0x48, 0x69, 0x53, 0x42, 0x6B, 0x77, 0x48, 0x6C, 0x49, 0x4B, 0x2B, 0x2F, 0x56, 0x4C, 0x6A, 0x32, 0x73, 0x6D, 0x43, 0x4B, 0x64, 0x55, 0x51, 0x0A, 0x67, 0x76, 0x4C, 0x58, 0x53, 0x6E, 0x6E, 0x56, 0x67, 0x51, 0x75, 0x6C, 0x48, 0x69, 0x6F, 0x44, 0x36, 0x55, 0x67, 0x59, 0x38, 0x78, 0x41, 0x32, 0x61, 0x34, 0x4D, 0x31, 0x72, 0x68, 0x59, 0x75, 0x54, 0x56, 0x38, 0x42, 0x72, 0x50, 0x52, 0x5A, 0x34, 0x42, 0x46, 0x78, 0x32, 0x6F, 0x30, 0x6A, 0x59, 0x57, 0x76, 0x47, 0x62, 0x41, 0x2F, 0x48, 0x6C, 0x70, 0x37, 0x66, 0x54, 0x4F, 0x79, 0x2B, 0x0A, 0x46, 0x35, 0x4F, 0x6B, 0x69, 0x48, 0x53, 0x37, 0x41, 0x67, 0x4D, 0x42, 0x41, 0x41, 0x45, 0x43, 0x67, 0x67, 0x45, 0x41, 0x59, 0x67, 0x43, 0x75, 0x38, 0x31, 0x5A, 0x69, 0x51, 0x42, 0x56, 0x44, 0x76, 0x57, 0x69, 0x44, 0x47, 0x4B, 0x72, 0x2B, 0x31, 0x70, 0x49, 0x66, 0x32, 0x43, 0x78, 0x70, 0x72, 0x47, 0x4A, 0x45, 0x6D, 0x31, 0x68, 0x38, 0x36, 0x5A, 0x63, 0x45, 0x78, 0x33, 0x4C, 0x37, 0x0A, 0x71, 0x46, 0x44, 0x57, 0x2B, 0x67, 0x38, 0x48, 0x47, 0x57, 0x64, 0x30, 0x34, 0x53, 0x33, 0x71, 0x76, 0x68, 0x39, 0x4C, 0x75, 0x62, 0x6C, 0x41, 0x4A, 0x7A, 0x65, 0x74, 0x41, 0x50, 0x78, 0x52, 0x58, 0x4C, 0x39, 0x7A, 0x78, 0x33, 0x50, 0x58, 0x6A, 0x4A, 0x5A, 0x73, 0x37, 0x65, 0x33, 0x48, 0x4C, 0x45, 0x75, 0x6E, 0x79, 0x33, 0x54, 0x61, 0x57, 0x65, 0x7A, 0x30, 0x58, 0x49, 0x30, 0x4F, 0x0A, 0x34, 0x4C, 0x53, 0x59, 0x38, 0x53, 0x38, 0x64, 0x36, 0x70, 0x56, 0x42, 0x50, 0x6D, 0x55, 0x45, 0x74, 0x77, 0x47, 0x57, 0x4E, 0x34, 0x76, 0x59, 0x71, 0x48, 0x6E, 0x4B, 0x4C, 0x58, 0x4F, 0x62, 0x34, 0x51, 0x51, 0x41, 0x58, 0x73, 0x34, 0x4D, 0x7A, 0x66, 0x6B, 0x4D, 0x2F, 0x4D, 0x65, 0x2F, 0x62, 0x2B, 0x7A, 0x64, 0x75, 0x31, 0x75, 0x6D, 0x77, 0x6A, 0x4D, 0x6C, 0x33, 0x44, 0x75, 0x64, 0x0A, 0x35, 0x72, 0x56, 0x68, 0x6B, 0x67, 0x76, 0x74, 0x38, 0x75, 0x68, 0x44, 0x55, 0x47, 0x33, 0x58, 0x53, 0x48, 0x65, 0x6F, 0x4A, 0x59, 0x42, 0x4D, 0x62, 0x54, 0x39, 0x69, 0x6B, 0x4A, 0x44, 0x56, 0x4D, 0x4A, 0x35, 0x31, 0x72, 0x72, 0x65, 0x2F, 0x31, 0x52, 0x69, 0x64, 0x64, 0x67, 0x78, 0x70, 0x38, 0x53, 0x6B, 0x74, 0x56, 0x6B, 0x76, 0x47, 0x6D, 0x4D, 0x6C, 0x39, 0x6B, 0x51, 0x52, 0x38, 0x0A, 0x38, 0x64, 0x76, 0x33, 0x50, 0x78, 0x2F, 0x6B, 0x54, 0x4E, 0x39, 0x34, 0x45, 0x75, 0x52, 0x67, 0x30, 0x43, 0x6B, 0x58, 0x42, 0x68, 0x48, 0x70, 0x6F, 0x47, 0x6F, 0x34, 0x71, 0x6E, 0x4D, 0x33, 0x51, 0x33, 0x42, 0x35, 0x50, 0x6C, 0x6D, 0x53, 0x4B, 0x35, 0x67, 0x6B, 0x75, 0x50, 0x76, 0x57, 0x79, 0x39, 0x6C, 0x38, 0x4C, 0x2F, 0x54, 0x56, 0x74, 0x38, 0x4C, 0x62, 0x36, 0x2F, 0x7A, 0x4C, 0x0A, 0x42, 0x79, 0x51, 0x57, 0x2B, 0x67, 0x30, 0x32, 0x77, 0x78, 0x65, 0x4E, 0x47, 0x68, 0x77, 0x31, 0x66, 0x6B, 0x44, 0x2B, 0x58, 0x46, 0x48, 0x37, 0x4B, 0x6B, 0x53, 0x65, 0x57, 0x6C, 0x2B, 0x51, 0x6E, 0x72, 0x4C, 0x63, 0x65, 0x50, 0x4D, 0x30, 0x68, 0x51, 0x4B, 0x42, 0x67, 0x51, 0x44, 0x78, 0x6F, 0x71, 0x55, 0x6B, 0x30, 0x50, 0x4C, 0x4F, 0x59, 0x35, 0x57, 0x67, 0x4F, 0x6B, 0x67, 0x72, 0x0A, 0x75, 0x6D, 0x67, 0x69, 0x65, 0x2F, 0x4B, 0x31, 0x57, 0x4B, 0x73, 0x2B, 0x69, 0x7A, 0x54, 0x74, 0x41, 0x70, 0x6A, 0x7A, 0x63, 0x4D, 0x37, 0x36, 0x73, 0x7A, 0x61, 0x36, 0x33, 0x62, 0x35, 0x52, 0x39, 0x77, 0x2B, 0x50, 0x2B, 0x4E, 0x73, 0x73, 0x4D, 0x56, 0x34, 0x61, 0x65, 0x56, 0x39, 0x65, 0x70, 0x45, 0x47, 0x5A, 0x4F, 0x36, 0x38, 0x49, 0x55, 0x6D, 0x69, 0x30, 0x51, 0x6A, 0x76, 0x51, 0x0A, 0x6E, 0x70, 0x6C, 0x75, 0x51, 0x6F, 0x61, 0x64, 0x46, 0x59, 0x77, 0x65, 0x46, 0x77, 0x53, 0x51, 0x31, 0x31, 0x42, 0x58, 0x48, 0x6F, 0x65, 0x51, 0x42, 0x41, 0x34, 0x6E, 0x4E, 0x70, 0x6B, 0x72, 0x56, 0x35, 0x38, 0x68, 0x67, 0x7A, 0x5A, 0x4E, 0x33, 0x6D, 0x39, 0x4A, 0x4C, 0x52, 0x37, 0x4A, 0x78, 0x79, 0x72, 0x49, 0x71, 0x58, 0x73, 0x52, 0x6E, 0x55, 0x7A, 0x6C, 0x31, 0x33, 0x4B, 0x6A, 0x0A, 0x47, 0x7A, 0x5A, 0x42, 0x43, 0x4A, 0x78, 0x43, 0x70, 0x4A, 0x6A, 0x66, 0x54, 0x7A, 0x65, 0x2F, 0x79, 0x6D, 0x65, 0x38, 0x64, 0x33, 0x70, 0x61, 0x35, 0x51, 0x4B, 0x42, 0x67, 0x51, 0x44, 0x51, 0x50, 0x35, 0x6D, 0x42, 0x34, 0x6A, 0x49, 0x2B, 0x67, 0x33, 0x58, 0x48, 0x33, 0x4D, 0x75, 0x4C, 0x79, 0x42, 0x6A, 0x4D, 0x6F, 0x54, 0x49, 0x76, 0x6F, 0x79, 0x37, 0x43, 0x59, 0x4D, 0x68, 0x5A, 0x0A, 0x36, 0x2F, 0x2B, 0x4B, 0x6B, 0x70, 0x77, 0x31, 0x33, 0x32, 0x4A, 0x31, 0x36, 0x6D, 0x71, 0x6B, 0x4C, 0x72, 0x77, 0x55, 0x4F, 0x5A, 0x66, 0x54, 0x30, 0x65, 0x31, 0x72, 0x4A, 0x42, 0x73, 0x43, 0x55, 0x6B, 0x45, 0x6F, 0x42, 0x6D, 0x67, 0x4B, 0x4E, 0x74, 0x52, 0x6B, 0x48, 0x6F, 0x33, 0x2F, 0x53, 0x6A, 0x55, 0x49, 0x2F, 0x39, 0x66, 0x48, 0x6A, 0x33, 0x75, 0x53, 0x74, 0x50, 0x48, 0x56, 0x0A, 0x6F, 0x50, 0x63, 0x66, 0x58, 0x6A, 0x2F, 0x67, 0x46, 0x52, 0x55, 0x6B, 0x44, 0x44, 0x7A, 0x59, 0x2B, 0x61, 0x75, 0x42, 0x33, 0x64, 0x48, 0x4F, 0x4E, 0x46, 0x31, 0x55, 0x31, 0x7A, 0x30, 0x36, 0x45, 0x41, 0x4E, 0x6B, 0x6B, 0x50, 0x43, 0x43, 0x33, 0x61, 0x35, 0x33, 0x38, 0x55, 0x41, 0x4E, 0x42, 0x49, 0x61, 0x50, 0x6A, 0x77, 0x70, 0x52, 0x64, 0x42, 0x7A, 0x4E, 0x77, 0x31, 0x78, 0x6C, 0x0A, 0x62, 0x76, 0x6E, 0x35, 0x61, 0x43, 0x74, 0x33, 0x48, 0x77, 0x4B, 0x42, 0x67, 0x42, 0x66, 0x4F, 0x6C, 0x34, 0x6A, 0x47, 0x45, 0x58, 0x59, 0x6D, 0x4E, 0x36, 0x4B, 0x2B, 0x75, 0x30, 0x65, 0x62, 0x71, 0x52, 0x44, 0x6B, 0x74, 0x32, 0x67, 0x49, 0x6F, 0x57, 0x36, 0x62, 0x46, 0x6F, 0x37, 0x58, 0x64, 0x36, 0x78, 0x63, 0x69, 0x2F, 0x67, 0x46, 0x57, 0x6A, 0x6F, 0x56, 0x43, 0x4F, 0x42, 0x59, 0x0A, 0x67, 0x43, 0x38, 0x47, 0x4C, 0x4D, 0x6E, 0x77, 0x33, 0x7A, 0x32, 0x71, 0x67, 0x61, 0x76, 0x34, 0x63, 0x51, 0x49, 0x67, 0x38, 0x45, 0x44, 0x59, 0x70, 0x62, 0x70, 0x45, 0x34, 0x46, 0x48, 0x51, 0x6E, 0x6E, 0x74, 0x50, 0x6B, 0x4B, 0x57, 0x2F, 0x62, 0x72, 0x75, 0x30, 0x4E, 0x74, 0x33, 0x79, 0x61, 0x4E, 0x62, 0x38, 0x69, 0x67, 0x79, 0x31, 0x61, 0x5A, 0x4F, 0x52, 0x66, 0x49, 0x76, 0x5A, 0x0A, 0x71, 0x54, 0x4D, 0x4C, 0x45, 0x33, 0x6D, 0x65, 0x6C, 0x63, 0x5A, 0x57, 0x37, 0x4C, 0x61, 0x69, 0x71, 0x65, 0x4E, 0x31, 0x56, 0x30, 0x76, 0x48, 0x2F, 0x4D, 0x43, 0x55, 0x64, 0x70, 0x58, 0x39, 0x59, 0x31, 0x34, 0x4B, 0x39, 0x43, 0x4A, 0x59, 0x78, 0x7A, 0x73, 0x52, 0x4F, 0x67, 0x50, 0x71, 0x64, 0x45, 0x67, 0x4D, 0x57, 0x59, 0x44, 0x46, 0x41, 0x6F, 0x47, 0x41, 0x41, 0x65, 0x39, 0x6C, 0x0A, 0x58, 0x4D, 0x69, 0x65, 0x55, 0x4F, 0x68, 0x6C, 0x30, 0x73, 0x71, 0x68, 0x64, 0x5A, 0x59, 0x52, 0x62, 0x4F, 0x31, 0x65, 0x69, 0x77, 0x54, 0x49, 0x4C, 0x58, 0x51, 0x36, 0x79, 0x47, 0x4D, 0x69, 0x42, 0x38, 0x61, 0x65, 0x2F, 0x76, 0x30, 0x70, 0x62, 0x42, 0x45, 0x57, 0x6C, 0x70, 0x6E, 0x38, 0x6B, 0x32, 0x2B, 0x4A, 0x6B, 0x71, 0x56, 0x54, 0x77, 0x48, 0x67, 0x67, 0x62, 0x43, 0x41, 0x5A, 0x0A, 0x6A, 0x4F, 0x61, 0x71, 0x56, 0x74, 0x58, 0x31, 0x6D, 0x55, 0x79, 0x54, 0x59, 0x7A, 0x6A, 0x73, 0x54, 0x7A, 0x34, 0x5A, 0x59, 0x6A, 0x68, 0x61, 0x48, 0x4A, 0x33, 0x6A, 0x31, 0x57, 0x6C, 0x65, 0x67, 0x6F, 0x4D, 0x63, 0x73, 0x74, 0x64, 0x66, 0x54, 0x2B, 0x74, 0x78, 0x4D, 0x55, 0x37, 0x34, 0x6F, 0x67, 0x64, 0x4F, 0x71, 0x4D, 0x7A, 0x68, 0x78, 0x53, 0x55, 0x4F, 0x34, 0x35, 0x67, 0x38, 0x0A, 0x66, 0x39, 0x57, 0x38, 0x39, 0x6D, 0x70, 0x61, 0x38, 0x62, 0x42, 0x6A, 0x4F, 0x50, 0x75, 0x2B, 0x79, 0x46, 0x79, 0x36, 0x36, 0x74, 0x44, 0x61, 0x5A, 0x36, 0x73, 0x57, 0x45, 0x37, 0x63, 0x35, 0x53, 0x58, 0x45, 0x48, 0x58, 0x6C, 0x38, 0x43, 0x67, 0x59, 0x45, 0x41, 0x74, 0x41, 0x57, 0x77, 0x46, 0x50, 0x6F, 0x44, 0x53, 0x54, 0x64, 0x7A, 0x6F, 0x58, 0x41, 0x77, 0x52, 0x6F, 0x66, 0x30, 0x0A, 0x51, 0x4D, 0x4F, 0x30, 0x38, 0x2B, 0x50, 0x6E, 0x51, 0x47, 0x6F, 0x50, 0x62, 0x4D, 0x4A, 0x54, 0x71, 0x72, 0x67, 0x78, 0x72, 0x48, 0x59, 0x43, 0x53, 0x38, 0x75, 0x34, 0x63, 0x59, 0x53, 0x48, 0x64, 0x44, 0x4D, 0x4A, 0x44, 0x43, 0x4F, 0x4D, 0x6F, 0x35, 0x67, 0x46, 0x58, 0x79, 0x43, 0x2B, 0x35, 0x46, 0x66, 0x54, 0x69, 0x47, 0x77, 0x42, 0x68, 0x79, 0x35, 0x38, 0x7A, 0x35, 0x62, 0x37, 0x0A, 0x67, 0x42, 0x77, 0x46, 0x4B, 0x49, 0x39, 0x52, 0x67, 0x52, 0x66, 0x56, 0x31, 0x44, 0x2F, 0x4E, 0x69, 0x6D, 0x78, 0x50, 0x72, 0x6C, 0x6A, 0x33, 0x57, 0x48, 0x79, 0x65, 0x63, 0x31, 0x2F, 0x43, 0x73, 0x2B, 0x42, 0x72, 0x2B, 0x2F, 0x76, 0x65, 0x6B, 0x4D, 0x56, 0x46, 0x67, 0x35, 0x67, 0x65, 0x6B, 0x65, 0x48, 0x72, 0x34, 0x61, 0x47, 0x53, 0x46, 0x34, 0x62, 0x6B, 0x30, 0x41, 0x6A, 0x56, 0x0A, 0x54, 0x76, 0x2F, 0x70, 0x51, 0x6A, 0x79, 0x52, 0x75, 0x5A, 0x41, 0x74, 0x36, 0x36, 0x49, 0x62, 0x52, 0x5A, 0x64, 0x6C, 0x32, 0x49, 0x49, 0x3D, 0x0A, 0x2D, 0x2D, 0x2D, 0x2D, 0x2D, 0x45, 0x4E, 0x44, 0x20, 0x50, 0x52, 0x49, 0x56, 0x41, 0x54, 0x45, 0x20, 0x4B, 0x45, 0x59, 0x2D, 0x2D, 0x2D, 0x2D, 0x2D }; /* * PEM of pem_rsa_priv_key: * -----BEGIN PRIVATE KEY----- * MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDEkC4ZWv3ucFbU * F8YwlUrmQlLCZwAgr4DPUAFVHl+wFcXypVgScVY4K7QmdWKsYqb8tpOxqw0NwZWX * O+ta4+y27COufoOhRTMwNyN2LwSNTPN3eEk4ee5QnppEyDrqoCgvTlAAdToFaXvj * x13Ybj7jfhwN74qKdqsSEtPWyggeotiQSPy6KyBIuWtIxPAA8jAvfAnQj1eXhghF * N2NxkqgxvBYdNy1m3+jXACPLRzc11ZbNHKiwhCY1/HiSBkwHlIK+/VLj2smCKdUQ * gvLXSnnVgQulHioD6UgY8xA2a4M1rhYuTV8BrPRZ4BFx2o0jYWvGbA/Hlp7fTOy+ * F5OkiHS7AgMBAAECggEAYgCu81ZiQBVDvWiDGKr+1pIf2CxprGJEm1h86ZcEx3L7 * qFDW+g8HGWd04S3qvh9LublAJzetAPxRXL9zx3PXjJZs7e3HLEuny3TaWez0XI0O * 4LSY8S8d6pVBPmUEtwGWN4vYqHnKLXOb4QQAXs4MzfkM/Me/b+zdu1umwjMl3Dud * 5rVhkgvt8uhDUG3XSHeoJYBMbT9ikJDVMJ51rre/1Riddgxp8SktVkvGmMl9kQR8 * 8dv3Px/kTN94EuRg0CkXBhHpoGo4qnM3Q3B5PlmSK5gkuPvWy9l8L/TVt8Lb6/zL * ByQW+g02wxeNGhw1fkD+XFH7KkSeWl+QnrLcePM0hQKBgQDxoqUk0PLOY5WgOkgr * umgie/K1WKs+izTtApjzcM76sza63b5R9w+P+NssMV4aeV9epEGZO68IUmi0QjvQ * npluQoadFYweFwSQ11BXHoeQBA4nNpkrV58hgzZN3m9JLR7JxyrIqXsRnUzl13Kj * GzZBCJxCpJjfTze/yme8d3pa5QKBgQDQP5mB4jI+g3XH3MuLyBjMoTIvoy7CYMhZ * 6/+Kkpw132J16mqkLrwUOZfT0e1rJBsCUkEoBmgKNtRkHo3/SjUI/9fHj3uStPHV * oPcfXj/gFRUkDDzY+auB3dHONF1U1z06EANkkPCC3a538UANBIaPjwpRdBzNw1xl * bvn5aCt3HwKBgBfOl4jGEXYmN6K+u0ebqRDkt2gIoW6bFo7Xd6xci/gFWjoVCOBY * gC8GLMnw3z2qgav4cQIg8EDYpbpE4FHQnntPkKW/bru0Nt3yaNb8igy1aZORfIvZ * qTMLE3melcZW7LaiqeN1V0vH/MCUdpX9Y14K9CJYxzsROgPqdEgMWYDFAoGAAe9l * XMieUOhl0sqhdZYRbO1eiwTILXQ6yGMiB8ae/v0pbBEWlpn8k2+JkqVTwHggbCAZ * jOaqVtX1mUyTYzjsTz4ZYjhaHJ3j1WlegoMcstdfT+txMU74ogdOqMzhxSUO45g8 * f9W89mpa8bBjOPu+yFy66tDaZ6sWE7c5SXEHXl8CgYEAtAWwFPoDSTdzoXAwRof0 * QMO08+PnQGoPbMJTqrgxrHYCS8u4cYSHdDMJDCOMo5gFXyC+5FfTiGwBhy58z5b7 * gBwFKI9RgRfV1D/NimxPrlj3WHyec1/Cs+Br+/vekMVFg5gekeHr4aGSF4bk0AjV * Tv/pQjyRuZAt66IbRZdl2II= * -----END PRIVATE KEY----- */ /* Load private key BIO, DER-encoded public key and PKCS#8 private key for testing */ if (!TEST_ptr(bio_priv = BIO_new(BIO_s_mem())) || !TEST_int_gt(BIO_write(bio_priv, pem_rsa_priv_key, sizeof(pem_rsa_priv_key)), 0) || !TEST_ptr(pkey = PEM_read_bio_PrivateKey_ex(bio_priv, NULL, NULL, NULL, NULL, NULL)) || !TEST_int_ge(BIO_seek(bio_priv, 0), 0) || !TEST_int_gt((len_pub = i2d_PUBKEY(pkey, &encoded_pub)), 0) || !TEST_ptr(p8 = EVP_PKEY2PKCS8(pkey))) goto end; EVP_PKEY_free(pkey); pkey = NULL; for (i = 0; i < OSSL_NELEM(properties_test); i++) { const char *libctx_prop = properties_test[i].provider_props; const char *explicit_prop = properties_test[i].explicit_props; /* *curr_provider will be updated in reset_ctx_providers */ OSSL_PROVIDER **curr_provider = &providers[properties_test[i].curr_provider_idx]; /* * Decoding a PEM-encoded key uses the properties to select the right provider. * Using a PEM-encoding adds an extra decoder before the key is created. */ if (!TEST_int_eq(reset_ctx_providers(&my_libctx, providers, libctx_prop), 1)) goto end; if (!TEST_int_ge(BIO_seek(bio_priv, 0), 0) || !TEST_ptr(pkey = PEM_read_bio_PrivateKey_ex(bio_priv, NULL, NULL, NULL, my_libctx, explicit_prop)) || !TEST_ptr_eq(EVP_PKEY_get0_provider(pkey), *curr_provider)) goto end; EVP_PKEY_free(pkey); pkey = NULL; /* Decoding a DER-encoded X509_PUBKEY uses the properties to select the right provider */ if (!TEST_int_eq(reset_ctx_providers(&my_libctx, providers, libctx_prop), 1)) goto end; p = encoded_pub; if (!TEST_ptr(pkey = d2i_PUBKEY_ex(NULL, &p, len_pub, my_libctx, explicit_prop)) || !TEST_ptr_eq(EVP_PKEY_get0_provider(pkey), *curr_provider)) goto end; EVP_PKEY_free(pkey); pkey = NULL; /* Decoding a PKCS8_PRIV_KEY_INFO uses the properties to select the right provider */ if (!TEST_int_eq(reset_ctx_providers(&my_libctx, providers, libctx_prop), 1)) goto end; if (!TEST_ptr(pkey = EVP_PKCS82PKEY_ex(p8, my_libctx, explicit_prop)) || !TEST_ptr_eq(EVP_PKEY_get0_provider(pkey), *curr_provider)) goto end; EVP_PKEY_free(pkey); pkey = NULL; } ret = 1; end: PKCS8_PRIV_KEY_INFO_free(p8); BIO_free(bio_priv); OPENSSL_free(encoded_pub); EVP_PKEY_free(pkey); OSSL_PROVIDER_unload(providers[DEFAULT_PROVIDER_IDX]); fake_rsa_finish(providers[FAKE_RSA_PROVIDER_IDX]); OSSL_LIB_CTX_free(my_libctx); return ret; } int setup_tests(void) { libctx = OSSL_LIB_CTX_new(); if (libctx == NULL) return 0; ADD_TEST(test_pkey_sig); ADD_TEST(test_alternative_keygen_init); ADD_TEST(test_pkey_eq); + ADD_TEST(test_pkey_can_sign); ADD_ALL_TESTS(test_pkey_store, 2); ADD_TEST(test_pkey_delete); ADD_TEST(test_pkey_store_open_ex); ADD_TEST(test_pkey_provider_decoder_props); return 1; } void cleanup_tests(void) { OSSL_LIB_CTX_free(libctx); } diff --git a/test/quicapitest.c b/test/quicapitest.c index f665c511bb72..4e887c13d14c 100644 --- a/test/quicapitest.c +++ b/test/quicapitest.c @@ -1,3041 +1,2964 @@ /* * Copyright 2022-2025 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 "helpers/ssltestlib.h" #include "helpers/quictestlib.h" #include "testutil.h" #include "testutil/output.h" #include "../ssl/ssl_local.h" #include "internal/quic_error.h" static OSSL_LIB_CTX *libctx = NULL; static OSSL_PROVIDER *defctxnull = NULL; static char *certsdir = NULL; static char *cert = NULL; static char *ccert = NULL; static char *cauthca = NULL; static char *privkey = NULL; static char *cprivkey = NULL; static char *datadir = NULL; static int is_fips = 0; /* The ssltrace test assumes some options are switched on/off */ #if !defined(OPENSSL_NO_SSL_TRACE) \ && defined(OPENSSL_NO_BROTLI) && defined(OPENSSL_NO_ZSTD) \ && !defined(OPENSSL_NO_ECX) && !defined(OPENSSL_NO_DH) \ && !defined(OPENSSL_NO_ML_DSA) && !defined(OPENSSL_NO_ML_KEM) # define DO_SSL_TRACE_TEST #endif /* * Test that we read what we've written. * Test 0: Non-blocking * Test 1: Blocking * Test 2: Blocking, introduce socket error, test error handling. */ static int test_quic_write_read(int idx) { SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()); SSL_CTX *sctx = NULL; SSL *clientquic = NULL; QUIC_TSERVER *qtserv = NULL; int j, k, ret = 0; unsigned char buf[20], scratch[64]; static char *msg = "A test message"; size_t msglen = strlen(msg); size_t numbytes = 0; int ssock = 0, csock = 0; uint64_t sid = UINT64_MAX; SSL_SESSION *sess = NULL; if (idx >= 1 && !qtest_supports_blocking()) return TEST_skip("Blocking tests not supported in this build"); for (k = 0; k < 2; k++) { if (!TEST_ptr(cctx) || !TEST_true(qtest_create_quic_objects(libctx, cctx, sctx, cert, privkey, idx >= 1 ? QTEST_FLAG_BLOCK : 0, &qtserv, &clientquic, NULL, NULL)) || !TEST_true(SSL_set_tlsext_host_name(clientquic, "localhost"))) goto end; if (sess != NULL && !TEST_true(SSL_set_session(clientquic, sess))) goto end; if (!TEST_true(qtest_create_quic_connection(qtserv, clientquic))) goto end; if (idx >= 1) { if (!TEST_true(BIO_get_fd(ossl_quic_tserver_get0_rbio(qtserv), &ssock))) goto end; if (!TEST_int_gt(csock = SSL_get_rfd(clientquic), 0)) goto end; } sid = 0; /* client-initiated bidirectional stream */ for (j = 0; j < 2; j++) { /* Check that sending and receiving app data is ok */ if (!TEST_true(SSL_write_ex(clientquic, msg, msglen, &numbytes)) || !TEST_size_t_eq(numbytes, msglen)) goto end; if (idx >= 1) { do { if (!TEST_true(wait_until_sock_readable(ssock))) goto end; ossl_quic_tserver_tick(qtserv); if (!TEST_true(ossl_quic_tserver_read(qtserv, sid, buf, sizeof(buf), &numbytes))) goto end; } while (numbytes == 0); if (!TEST_mem_eq(buf, numbytes, msg, msglen)) goto end; } if (idx >= 2 && j > 0) /* Introduce permanent socket error */ BIO_closesocket(csock); ossl_quic_tserver_tick(qtserv); if (!TEST_true(ossl_quic_tserver_write(qtserv, sid, (unsigned char *)msg, msglen, &numbytes))) goto end; ossl_quic_tserver_tick(qtserv); SSL_handle_events(clientquic); if (idx >= 2 && j > 0) { if (!TEST_false(SSL_read_ex(clientquic, buf, 1, &numbytes)) || !TEST_int_eq(SSL_get_error(clientquic, 0), SSL_ERROR_SYSCALL) || !TEST_false(SSL_write_ex(clientquic, msg, msglen, &numbytes)) || !TEST_int_eq(SSL_get_error(clientquic, 0), SSL_ERROR_SYSCALL)) goto end; break; } /* * In blocking mode the SSL_read_ex call will block until the socket * is readable and has our data. In non-blocking mode we're doing * everything in memory, so it should be immediately available */ if (!TEST_true(SSL_read_ex(clientquic, buf, 1, &numbytes)) || !TEST_size_t_eq(numbytes, 1) || !TEST_true(SSL_has_pending(clientquic)) || !TEST_int_eq(SSL_pending(clientquic), msglen - 1) || !TEST_true(SSL_read_ex(clientquic, buf + 1, sizeof(buf) - 1, &numbytes)) || !TEST_mem_eq(buf, numbytes + 1, msg, msglen)) goto end; } /* Test that exporters work. */ if (!TEST_true(SSL_export_keying_material(clientquic, scratch, sizeof(scratch), "test", 4, (unsigned char *)"ctx", 3, 1))) goto end; if (sess == NULL) { /* We didn't supply a session so we're not expecting resumption */ if (!TEST_false(SSL_session_reused(clientquic))) goto end; /* We should have a session ticket by now */ sess = SSL_get1_session(clientquic); if (!TEST_ptr(sess)) goto end; } else { /* We supplied a session so we should have resumed */ if (!TEST_true(SSL_session_reused(clientquic))) goto end; } if (!TEST_true(qtest_shutdown(qtserv, clientquic))) goto end; if (sctx == NULL) { sctx = ossl_quic_tserver_get0_ssl_ctx(qtserv); if (!TEST_true(SSL_CTX_up_ref(sctx))) { sctx = NULL; goto end; } } ossl_quic_tserver_free(qtserv); qtserv = NULL; SSL_free(clientquic); clientquic = NULL; if (idx >= 2) break; } ret = 1; end: SSL_SESSION_free(sess); ossl_quic_tserver_free(qtserv); SSL_free(clientquic); SSL_CTX_free(cctx); SSL_CTX_free(sctx); return ret; } /* * Test that sending FIN with no data to a client blocking in SSL_read_ex() will * wake up the client. */ static int test_fin_only_blocking(void) { SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()); SSL_CTX *sctx = NULL; SSL *clientquic = NULL; QUIC_TSERVER *qtserv = NULL; const char *msg = "Hello World"; uint64_t sid; size_t numbytes; unsigned char buf[32]; int ret = 0; OSSL_TIME timer, timediff; if (!qtest_supports_blocking()) return TEST_skip("Blocking tests not supported in this build"); if (!TEST_ptr(cctx) || !TEST_true(qtest_create_quic_objects(libctx, cctx, sctx, cert, privkey, QTEST_FLAG_BLOCK, &qtserv, &clientquic, NULL, NULL)) || !TEST_true(SSL_set_tlsext_host_name(clientquic, "localhost"))) goto end; if (!TEST_true(qtest_create_quic_connection(qtserv, clientquic))) goto end; if (!TEST_true(ossl_quic_tserver_stream_new(qtserv, 0, &sid)) || !TEST_true(ossl_quic_tserver_write(qtserv, sid, (unsigned char *)msg, strlen(msg), &numbytes)) || !TEST_size_t_eq(strlen(msg), numbytes)) goto end; ossl_quic_tserver_tick(qtserv); if (!TEST_true(SSL_read_ex(clientquic, buf, sizeof(buf), &numbytes)) || !TEST_mem_eq(msg, strlen(msg), buf, numbytes)) goto end; if (!TEST_true(ossl_quic_tserver_conclude(qtserv, sid))) goto end; timer = ossl_time_now(); if (!TEST_false(SSL_read_ex(clientquic, buf, sizeof(buf), &numbytes))) goto end; timediff = ossl_time_subtract(ossl_time_now(), timer); if (!TEST_int_eq(SSL_get_error(clientquic, 0), SSL_ERROR_ZERO_RETURN) /* * We expect the SSL_read_ex to not have blocked so this should * be very fast. 40ms should be plenty. */ || !TEST_uint64_t_le(ossl_time2ms(timediff), 40)) goto end; if (!TEST_true(qtest_shutdown(qtserv, clientquic))) goto end; ret = 1; end: ossl_quic_tserver_free(qtserv); SSL_free(clientquic); SSL_CTX_free(cctx); SSL_CTX_free(sctx); return ret; } /* Test that a vanilla QUIC SSL object has the expected ciphersuites available */ static int test_ciphersuites(void) { SSL_CTX *ctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()); SSL *ssl = NULL; int testresult = 0; const STACK_OF(SSL_CIPHER) *ciphers = NULL; const SSL_CIPHER *cipher; /* We expect this exact list of ciphersuites by default */ int cipherids[] = { TLS1_3_CK_AES_256_GCM_SHA384, #if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305) TLS1_3_CK_CHACHA20_POLY1305_SHA256, #endif TLS1_3_CK_AES_128_GCM_SHA256 }; size_t i, j; if (!TEST_ptr(ctx)) return 0; /* * Attempting to set TLSv1.2 ciphersuites should succeed, even though they * aren't used in QUIC. */ if (!TEST_true(SSL_CTX_set_cipher_list(ctx, "DEFAULT"))) goto err; ssl = SSL_new(ctx); if (!TEST_ptr(ssl)) goto err; if (!TEST_true(SSL_set_cipher_list(ssl, "DEFAULT"))) goto err; ciphers = SSL_get_ciphers(ssl); for (i = 0, j = 0; i < OSSL_NELEM(cipherids); i++) { if (cipherids[i] == TLS1_3_CK_CHACHA20_POLY1305_SHA256 && is_fips) continue; cipher = sk_SSL_CIPHER_value(ciphers, j++); if (!TEST_ptr(cipher)) goto err; if (!TEST_uint_eq(SSL_CIPHER_get_id(cipher), cipherids[i])) goto err; } /* We should have checked all the ciphers in the stack */ if (!TEST_int_eq(sk_SSL_CIPHER_num(ciphers), j)) goto err; testresult = 1; err: SSL_free(ssl); SSL_CTX_free(ctx); return testresult; } static int test_cipher_find(void) { SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()); SSL *clientquic = NULL; struct { const unsigned char *cipherbytes; int ok; } testciphers[] = { { TLS13_AES_128_GCM_SHA256_BYTES, 1 }, { TLS13_AES_256_GCM_SHA384_BYTES, 1 }, { TLS13_CHACHA20_POLY1305_SHA256_BYTES, 1 }, { TLS13_AES_128_CCM_SHA256_BYTES, 0 }, { TLS13_AES_128_CCM_8_SHA256_BYTES, 0 }, #if !defined(OPENSSL_NO_INTEGRITY_ONLY_CIPHERS) { TLS13_SHA256_SHA256_BYTES, 0 }, { TLS13_SHA384_SHA384_BYTES, 0 } #endif }; size_t i; int testresult = 0; if (!TEST_ptr(cctx)) goto err; clientquic = SSL_new(cctx); if (!TEST_ptr(clientquic)) goto err; for (i = 0; i < OSSL_NELEM(testciphers); i++) if (testciphers[i].ok) { if (!TEST_ptr(SSL_CIPHER_find(clientquic, testciphers[i].cipherbytes))) goto err; } else { if (!TEST_ptr_null(SSL_CIPHER_find(clientquic, testciphers[i].cipherbytes))) goto err; } testresult = 1; err: SSL_free(clientquic); SSL_CTX_free(cctx); return testresult; } /* * Test that SSL_version, SSL_get_version, SSL_is_quic, SSL_is_tls and * SSL_is_dtls return the expected results for a QUIC connection. Compare with * test_version() in sslapitest.c which does the same thing for TLS/DTLS * connections. */ static int test_version(void) { SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()); SSL *clientquic = NULL; QUIC_TSERVER *qtserv = NULL; int testresult = 0; if (!TEST_ptr(cctx) || !TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, cert, privkey, 0, &qtserv, &clientquic, NULL, NULL)) || !TEST_true(qtest_create_quic_connection(qtserv, clientquic))) goto err; if (!TEST_int_eq(SSL_version(clientquic), OSSL_QUIC1_VERSION) || !TEST_str_eq(SSL_get_version(clientquic), "QUICv1")) goto err; if (!TEST_true(SSL_is_quic(clientquic)) || !TEST_false(SSL_is_tls(clientquic)) || !TEST_false(SSL_is_dtls(clientquic))) goto err; testresult = 1; err: ossl_quic_tserver_free(qtserv); SSL_free(clientquic); SSL_CTX_free(cctx); return testresult; } #if defined(DO_SSL_TRACE_TEST) -static void strip_line_ends(char *str) -{ - size_t i; - - for (i = strlen(str); - i > 0 && (str[i - 1] == '\n' || str[i - 1] == '\r'); - i--); - - str[i] = '\0'; -} - -static int compare_with_file(BIO *membio) -{ - BIO *file = NULL, *newfile = NULL; - char buf1[8192], buf2[8192]; - char *reffile; - int ret = 0; - size_t i; - -#ifdef OPENSSL_NO_ZLIB - reffile = test_mk_file_path(datadir, "ssltraceref.txt"); -#else - reffile = test_mk_file_path(datadir, "ssltraceref-zlib.txt"); -#endif - if (!TEST_ptr(reffile)) - goto err; - - file = BIO_new_file(reffile, "rb"); - if (!TEST_ptr(file)) - goto err; - - newfile = BIO_new_file("ssltraceref-new.txt", "wb"); - if (!TEST_ptr(newfile)) - goto err; - - while (BIO_gets(membio, buf2, sizeof(buf2)) > 0) - if (BIO_puts(newfile, buf2) <= 0) { - TEST_error("Failed writing new file data"); - goto err; - } - - if (!TEST_int_ge(BIO_seek(membio, 0), 0)) - goto err; - - while (BIO_gets(file, buf1, sizeof(buf1)) > 0) { - size_t line_len; - - if (BIO_gets(membio, buf2, sizeof(buf2)) <= 0) { - TEST_error("Failed reading mem data"); - goto err; - } - strip_line_ends(buf1); - strip_line_ends(buf2); - line_len = strlen(buf1); - if (line_len > 0 && buf1[line_len - 1] == '?') { - /* Wildcard at the EOL means ignore anything after it */ - if (strlen(buf2) > line_len) - buf2[line_len] = '\0'; - } - if (line_len != strlen(buf2)) { - TEST_error("Actual and ref line data length mismatch"); - TEST_info("%s", buf1); - TEST_info("%s", buf2); - goto err; - } - for (i = 0; i < line_len; i++) { - /* '?' is a wild card character in the reference text */ - if (buf1[i] == '?') - buf2[i] = '?'; - } - if (!TEST_str_eq(buf1, buf2)) - goto err; - } - if (!TEST_true(BIO_eof(file)) - || !TEST_true(BIO_eof(membio))) - goto err; - - ret = 1; - err: - OPENSSL_free(reffile); - BIO_free(file); - BIO_free(newfile); - return ret; -} - /* * Tests that the SSL_trace() msg_callback works as expected with a QUIC * connection. This also provides testing of the msg_callback at the same time. */ static int test_ssl_trace(void) { SSL_CTX *cctx = NULL; SSL *clientquic = NULL; QUIC_TSERVER *qtserv = NULL; int testresult = 0; BIO *bio = NULL; + char *reffile = NULL; if (!TEST_ptr(cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method())) || !TEST_ptr(bio = BIO_new(BIO_s_mem())) || !TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_128_GCM_SHA256")) || !TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, cert, privkey, QTEST_FLAG_FAKE_TIME, &qtserv, &clientquic, NULL, NULL))) goto err; SSL_set_msg_callback(clientquic, SSL_trace); SSL_set_msg_callback_arg(clientquic, bio); if (!TEST_true(qtest_create_quic_connection(qtserv, clientquic))) goto err; /* Skip the comparison of the trace when the fips provider is used. */ if (is_fips) { /* Check whether there was something written. */ if (!TEST_int_gt(BIO_pending(bio), 0)) goto err; } else { - if (!TEST_true(compare_with_file(bio))) + +# ifdef OPENSSL_NO_ZLIB + reffile = test_mk_file_path(datadir, "ssltraceref.txt"); +# else + reffile = test_mk_file_path(datadir, "ssltraceref-zlib.txt"); +# endif + if (!TEST_true(compare_with_reference_file(bio, reffile))) goto err; } testresult = 1; err: ossl_quic_tserver_free(qtserv); SSL_free(clientquic); SSL_CTX_free(cctx); BIO_free(bio); + OPENSSL_free(reffile); return testresult; } #endif #ifndef OPENSSL_NO_SSL_TRACE enum { INITIAL = 0, GATHER_TOKEN = 1, CHECK_TOKEN = 2, SUCCESS = 3, FAILED = 4 }; static int find_new_token_data(BIO *membio) { char buf[1024]; int state = INITIAL; char *tmpstring; char *tokenval = NULL; /* * This is a state machine, in which we traverse the ssl trace * looking for a sequence of items * The states are: * +---Current State---|----------Action-------------|---Next State---+ * | INITIAL | "Received Frame: New token" | GATHER_TOKEN | * | | !"Received Frame: New token"| INITIAL | * |-------------------|-----------------------------|----------------| * | GATHER_TOKEN | "Token: " | CHECK_TOKEN | * | | !"Token: " | FAILED | * |-------------------|-----------------------------|----------------| * | CHECK_TOKEN | "Token: " | SUCCESS | * | | EOF | FAILED | * +-------------------|-----------------------------|----------------| */ while (state != SUCCESS && state != FAILED && BIO_gets(membio, buf, sizeof(buf)) > 0) { switch (state) { case INITIAL: if (strstr(buf, "Received Frame: New token")) state = GATHER_TOKEN; break; case GATHER_TOKEN: TEST_info("Found New Token Marker\n"); tmpstring = strstr(buf, "Token: "); if (tmpstring == NULL) { TEST_info("Next line did not contain a new token\n"); state = FAILED; } else { if (!TEST_ptr(tokenval = OPENSSL_strdup(tmpstring))) return 0; state = CHECK_TOKEN; TEST_info("Recorded Token %s\n", tokenval); } break; case CHECK_TOKEN: tmpstring = strstr(buf, "Token: "); if (tmpstring != NULL && !strcmp(tmpstring, tokenval)) { state = SUCCESS; TEST_info("Matched next connection token %s\n", tmpstring); } default: break; } } OPENSSL_free(tokenval); return (state == SUCCESS); } static int test_new_token(void) { SSL_CTX *cctx = NULL; SSL *clientquic = NULL; SSL *clientquic2 = NULL; QUIC_TSERVER *qtserv = NULL; QUIC_TSERVER *qtserv2 = NULL; int testresult = 0; BIO *bio = NULL; char msg[] = "The Quic Brown Fox"; size_t written; if (!TEST_ptr(cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method())) || !TEST_ptr(bio = BIO_new(BIO_s_mem())) || !TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, cert, privkey, QTEST_FLAG_FAKE_TIME, &qtserv, &clientquic, NULL, NULL))) goto err; SSL_set_msg_callback(clientquic, SSL_trace); SSL_set_msg_callback_arg(clientquic, bio); if (!TEST_true(qtest_create_quic_connection(qtserv, clientquic))) goto err; /* Send data from the client */ if (!SSL_write_ex(clientquic, msg, sizeof(msg), &written)) goto err; if (written != sizeof(msg)) goto err; /* Receive data at the server */ ossl_quic_tserver_tick(qtserv); if (!TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, cert, privkey, QTEST_FLAG_FAKE_TIME, &qtserv2, &clientquic2, NULL, NULL))) goto err; SSL_set_msg_callback(clientquic2, SSL_trace); SSL_set_msg_callback_arg(clientquic2, bio); /* once we have our new token, create the subsequent connection */ if (!TEST_true(qtest_create_quic_connection(qtserv2, clientquic2))) goto err; /* Skip the comparison of the trace when the fips provider is used. */ if (!TEST_true(find_new_token_data(bio))) goto err; testresult = 1; err: ossl_quic_tserver_free(qtserv); ossl_quic_tserver_free(qtserv2); SSL_free(clientquic); SSL_free(clientquic2); SSL_CTX_free(cctx); BIO_free(bio); return testresult; } #endif static int ensure_valid_ciphers(const STACK_OF(SSL_CIPHER) *ciphers) { size_t i; /* Ensure ciphersuite list is suitably subsetted. */ for (i = 0; i < (size_t)sk_SSL_CIPHER_num(ciphers); ++i) { const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(ciphers, i); switch (SSL_CIPHER_get_id(cipher)) { case TLS1_3_CK_AES_128_GCM_SHA256: case TLS1_3_CK_AES_256_GCM_SHA384: case TLS1_3_CK_CHACHA20_POLY1305_SHA256: break; default: TEST_error("forbidden cipher: %s", SSL_CIPHER_get_name(cipher)); return 0; } } return 1; } /* * Test that handshake-layer APIs which shouldn't work don't work with QUIC. */ static int test_quic_forbidden_apis_ctx(void) { int testresult = 0; SSL_CTX *ctx = NULL; if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()))) goto err; #ifndef OPENSSL_NO_SRTP /* This function returns 0 on success and 1 on error, and should fail. */ if (!TEST_true(SSL_CTX_set_tlsext_use_srtp(ctx, "SRTP_AEAD_AES_128_GCM"))) goto err; #endif /* * List of ciphersuites we do and don't allow in QUIC. */ #define QUIC_CIPHERSUITES \ "TLS_AES_128_GCM_SHA256:" \ "TLS_AES_256_GCM_SHA384:" \ "TLS_CHACHA20_POLY1305_SHA256" #define NON_QUIC_CIPHERSUITES \ "TLS_AES_128_CCM_SHA256:" \ "TLS_AES_256_CCM_SHA384:" \ "TLS_AES_128_CCM_8_SHA256:" \ "TLS_SHA256_SHA256:" \ "TLS_SHA384_SHA384" /* Set TLSv1.3 ciphersuite list for the SSL_CTX. */ if (!TEST_true(SSL_CTX_set_ciphersuites(ctx, QUIC_CIPHERSUITES ":" NON_QUIC_CIPHERSUITES))) goto err; /* * Forbidden ciphersuites should show up in SSL_CTX accessors, they are only * filtered in SSL_get1_supported_ciphers, so we don't check for * non-inclusion here. */ testresult = 1; err: SSL_CTX_free(ctx); return testresult; } static int test_quic_forbidden_apis(void) { int testresult = 0; SSL_CTX *ctx = NULL; SSL *ssl = NULL; STACK_OF(SSL_CIPHER) *ciphers = NULL; if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()))) goto err; if (!TEST_ptr(ssl = SSL_new(ctx))) goto err; #ifndef OPENSSL_NO_SRTP /* This function returns 0 on success and 1 on error, and should fail. */ if (!TEST_true(SSL_set_tlsext_use_srtp(ssl, "SRTP_AEAD_AES_128_GCM"))) goto err; #endif /* Set TLSv1.3 ciphersuite list for the SSL_CTX. */ if (!TEST_true(SSL_set_ciphersuites(ssl, QUIC_CIPHERSUITES ":" NON_QUIC_CIPHERSUITES))) goto err; /* Non-QUIC ciphersuites must not appear in supported ciphers list. */ if (!TEST_ptr(ciphers = SSL_get1_supported_ciphers(ssl)) || !TEST_true(ensure_valid_ciphers(ciphers))) goto err; testresult = 1; err: sk_SSL_CIPHER_free(ciphers); SSL_free(ssl); SSL_CTX_free(ctx); return testresult; } static int test_quic_forbidden_options(void) { int testresult = 0; SSL_CTX *ctx = NULL; SSL *ssl = NULL; char buf[16]; size_t len; if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()))) goto err; /* QUIC options restrictions do not affect SSL_CTX */ SSL_CTX_set_options(ctx, UINT64_MAX); if (!TEST_uint64_t_eq(SSL_CTX_get_options(ctx), UINT64_MAX)) goto err; /* Set options on CTX which should not be inherited (tested below). */ SSL_CTX_set_read_ahead(ctx, 1); SSL_CTX_set_max_early_data(ctx, 1); SSL_CTX_set_recv_max_early_data(ctx, 1); SSL_CTX_set_quiet_shutdown(ctx, 1); if (!TEST_ptr(ssl = SSL_new(ctx))) goto err; /* Only permitted options get transferred to SSL object */ if (!TEST_uint64_t_eq(SSL_get_options(ssl), OSSL_QUIC_PERMITTED_OPTIONS)) goto err; /* Try again using SSL_set_options */ SSL_set_options(ssl, UINT64_MAX); if (!TEST_uint64_t_eq(SSL_get_options(ssl), OSSL_QUIC_PERMITTED_OPTIONS)) goto err; /* Clear everything */ SSL_clear_options(ssl, UINT64_MAX); if (!TEST_uint64_t_eq(SSL_get_options(ssl), 0)) goto err; /* Readahead */ if (!TEST_false(SSL_get_read_ahead(ssl))) goto err; SSL_set_read_ahead(ssl, 1); if (!TEST_false(SSL_get_read_ahead(ssl))) goto err; /* Block padding */ if (!TEST_true(SSL_set_block_padding(ssl, 0)) || !TEST_true(SSL_set_block_padding(ssl, 1)) || !TEST_false(SSL_set_block_padding(ssl, 2))) goto err; /* Max fragment length */ if (!TEST_true(SSL_set_tlsext_max_fragment_length(ssl, TLSEXT_max_fragment_length_DISABLED)) || !TEST_false(SSL_set_tlsext_max_fragment_length(ssl, TLSEXT_max_fragment_length_512))) goto err; /* Max early data */ if (!TEST_false(SSL_set_recv_max_early_data(ssl, 1)) || !TEST_false(SSL_set_max_early_data(ssl, 1))) goto err; /* Read/Write */ if (!TEST_false(SSL_read_early_data(ssl, buf, sizeof(buf), &len)) || !TEST_false(SSL_write_early_data(ssl, buf, sizeof(buf), &len))) goto err; /* Buffer Management */ if (!TEST_true(SSL_alloc_buffers(ssl)) || !TEST_false(SSL_free_buffers(ssl))) goto err; /* Pipelining */ if (!TEST_false(SSL_set_max_send_fragment(ssl, 2)) || !TEST_false(SSL_set_split_send_fragment(ssl, 2)) || !TEST_false(SSL_set_max_pipelines(ssl, 2))) goto err; /* HRR */ if (!TEST_false(SSL_stateless(ssl))) goto err; /* Quiet Shutdown */ if (!TEST_false(SSL_get_quiet_shutdown(ssl))) goto err; /* No duplication */ if (!TEST_ptr_null(SSL_dup(ssl))) goto err; /* No clear */ if (!TEST_false(SSL_clear(ssl))) goto err; testresult = 1; err: SSL_free(ssl); SSL_CTX_free(ctx); return testresult; } static int test_quic_set_fd(int idx) { int testresult = 0; SSL_CTX *ctx = NULL; SSL *ssl = NULL; int fd = -1, resfd = -1; BIO *bio = NULL; if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()))) goto err; if (!TEST_ptr(ssl = SSL_new(ctx))) goto err; if (!TEST_int_ge(fd = BIO_socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP, 0), 0)) goto err; if (idx == 0) { if (!TEST_true(SSL_set_fd(ssl, fd))) goto err; if (!TEST_ptr(bio = SSL_get_rbio(ssl))) goto err; if (!TEST_ptr_eq(bio, SSL_get_wbio(ssl))) goto err; } else if (idx == 1) { if (!TEST_true(SSL_set_rfd(ssl, fd))) goto err; if (!TEST_ptr(bio = SSL_get_rbio(ssl))) goto err; if (!TEST_ptr_null(SSL_get_wbio(ssl))) goto err; } else { if (!TEST_true(SSL_set_wfd(ssl, fd))) goto err; if (!TEST_ptr(bio = SSL_get_wbio(ssl))) goto err; if (!TEST_ptr_null(SSL_get_rbio(ssl))) goto err; } if (!TEST_int_eq(BIO_method_type(bio), BIO_TYPE_DGRAM)) goto err; if (!TEST_true(BIO_get_fd(bio, &resfd)) || !TEST_int_eq(resfd, fd)) goto err; testresult = 1; err: SSL_free(ssl); SSL_CTX_free(ctx); if (fd >= 0) BIO_closesocket(fd); return testresult; } #define MAXLOOPS 1000 static int test_bio_ssl(void) { /* * We just use OSSL_QUIC_client_method() rather than * OSSL_QUIC_client_thread_method(). We will never leave the connection idle * so we will always be implicitly handling time events anyway via other * IO calls. */ SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()); SSL *clientquic = NULL, *stream = NULL; QUIC_TSERVER *qtserv = NULL; int testresult = 0; BIO *cbio = NULL, *strbio = NULL, *thisbio; const char *msg = "Hello world"; int abortctr = 0, err, clienterr = 0, servererr = 0, retc = 0, rets = 0; size_t written, readbytes, msglen; int sid = 0, i; unsigned char buf[80]; if (!TEST_ptr(cctx)) goto err; cbio = BIO_new_ssl(cctx, 1); if (!TEST_ptr(cbio)) goto err; /* * We must configure the ALPN/peer address etc so we get the SSL object in * order to pass it to qtest_create_quic_objects for configuration. */ if (!TEST_int_eq(BIO_get_ssl(cbio, &clientquic), 1)) goto err; if (!TEST_true(qtest_create_quic_objects(libctx, NULL, NULL, cert, privkey, QTEST_FLAG_FAKE_TIME, &qtserv, &clientquic, NULL, NULL))) goto err; msglen = strlen(msg); do { err = BIO_FLAGS_WRITE; while (!clienterr && !retc && err == BIO_FLAGS_WRITE) { retc = BIO_write_ex(cbio, msg, msglen, &written); if (!retc) { if (BIO_should_retry(cbio)) err = BIO_retry_type(cbio); else err = 0; } } if (!clienterr && retc <= 0 && err != BIO_FLAGS_READ) { TEST_info("BIO_write_ex() failed %d, %d", retc, err); TEST_openssl_errors(); clienterr = 1; } if (!servererr && rets <= 0) { ossl_quic_tserver_tick(qtserv); qtest_add_time(100); servererr = ossl_quic_tserver_is_term_any(qtserv); if (!servererr) rets = ossl_quic_tserver_is_handshake_confirmed(qtserv); } if (clienterr && servererr) goto err; if (++abortctr == MAXLOOPS) { TEST_info("No progress made"); goto err; } } while ((!retc && !clienterr) || (rets <= 0 && !servererr)); /* * 2 loops: The first using the default stream, and the second using a new * client initiated bidi stream. */ for (i = 0, thisbio = cbio; i < 2; i++) { if (!TEST_true(ossl_quic_tserver_read(qtserv, sid, buf, sizeof(buf), &readbytes)) || !TEST_mem_eq(msg, msglen, buf, readbytes)) goto err; if (!TEST_true(ossl_quic_tserver_write(qtserv, sid, (unsigned char *)msg, msglen, &written))) goto err; ossl_quic_tserver_tick(qtserv); if (!TEST_true(BIO_read_ex(thisbio, buf, sizeof(buf), &readbytes)) || !TEST_mem_eq(msg, msglen, buf, readbytes)) goto err; if (i == 1) break; if (!TEST_true(SSL_set_mode(clientquic, 0))) goto err; /* * Now create a new stream and repeat. The bottom two bits of the stream * id represents whether the stream is bidi and whether it is client * initiated or not. For client initiated bidi they are both 0. So the * first client initiated bidi stream is 0 and the next one is 4. */ sid = 4; stream = SSL_new_stream(clientquic, 0); if (!TEST_ptr(stream)) goto err; if (!TEST_true(SSL_set_mode(stream, 0))) goto err; thisbio = strbio = BIO_new(BIO_f_ssl()); if (!TEST_ptr(strbio)) goto err; if (!TEST_int_eq(BIO_set_ssl(thisbio, stream, BIO_CLOSE), 1)) goto err; stream = NULL; if (!TEST_true(BIO_write_ex(thisbio, msg, msglen, &written))) goto err; ossl_quic_tserver_tick(qtserv); } testresult = 1; err: BIO_free_all(cbio); BIO_free_all(strbio); SSL_free(stream); ossl_quic_tserver_free(qtserv); SSL_CTX_free(cctx); return testresult; } #define BACK_PRESSURE_NUM_LOOPS 10000 /* * Test that sending data from the client to the server faster than the server * can process it eventually results in back pressure on the client. */ static int test_back_pressure(void) { SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()); SSL *clientquic = NULL; QUIC_TSERVER *qtserv = NULL; int testresult = 0; unsigned char *msg = NULL; const size_t msglen = 1024; unsigned char buf[64]; size_t readbytes, written; int i; if (!TEST_ptr(cctx) || !TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, cert, privkey, 0, &qtserv, &clientquic, NULL, NULL)) || !TEST_true(qtest_create_quic_connection(qtserv, clientquic))) goto err; msg = OPENSSL_malloc(msglen); if (!TEST_ptr(msg)) goto err; if (!TEST_int_eq(RAND_bytes_ex(libctx, msg, msglen, 0), 1)) goto err; /* * Limit to 10000 loops. If we've not seen any back pressure after that * we're going to run out of memory, so abort. */ for (i = 0; i < BACK_PRESSURE_NUM_LOOPS; i++) { /* Send data from the client */ if (!SSL_write_ex(clientquic, msg, msglen, &written)) { /* Check if we are seeing back pressure */ if (SSL_get_error(clientquic, 0) == SSL_ERROR_WANT_WRITE) break; TEST_error("Unexpected client failure"); goto err; } /* Receive data at the server */ ossl_quic_tserver_tick(qtserv); if (!TEST_true(ossl_quic_tserver_read(qtserv, 0, buf, sizeof(buf), &readbytes))) goto err; } if (i == BACK_PRESSURE_NUM_LOOPS) { TEST_error("No back pressure seen"); goto err; } testresult = 1; err: SSL_free(clientquic); ossl_quic_tserver_free(qtserv); SSL_CTX_free(cctx); OPENSSL_free(msg); return testresult; } static int dgram_ctr = 0; static void dgram_cb(int write_p, int version, int content_type, const void *buf, size_t msglen, SSL *ssl, void *arg) { if (!write_p) return; if (content_type != SSL3_RT_QUIC_DATAGRAM) return; dgram_ctr++; } /* Test that we send multiple datagrams in one go when appropriate */ static int test_multiple_dgrams(void) { SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()); SSL *clientquic = NULL; QUIC_TSERVER *qtserv = NULL; int testresult = 0; unsigned char *buf; const size_t buflen = 1400; size_t written; buf = OPENSSL_zalloc(buflen); if (!TEST_ptr(cctx) || !TEST_ptr(buf) || !TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, cert, privkey, 0, &qtserv, &clientquic, NULL, NULL)) || !TEST_true(qtest_create_quic_connection(qtserv, clientquic))) goto err; dgram_ctr = 0; SSL_set_msg_callback(clientquic, dgram_cb); if (!TEST_true(SSL_write_ex(clientquic, buf, buflen, &written)) || !TEST_size_t_eq(written, buflen) /* We wrote enough data for 2 datagrams */ || !TEST_int_eq(dgram_ctr, 2)) goto err; testresult = 1; err: OPENSSL_free(buf); SSL_free(clientquic); ossl_quic_tserver_free(qtserv); SSL_CTX_free(cctx); return testresult; } static int non_io_retry_cert_verify_cb(X509_STORE_CTX *ctx, void *arg) { int idx = SSL_get_ex_data_X509_STORE_CTX_idx(); SSL *ssl; const int *allow = (int *)arg; /* this should not happen but check anyway */ if (idx < 0 || (ssl = X509_STORE_CTX_get_ex_data(ctx, idx)) == NULL) return 0; /* If this is our first attempt then retry */ if (*allow == 0) return SSL_set_retry_verify(ssl); /* Otherwise do nothing - verification succeeds. Continue as normal */ return 1; } /* Test that we can handle a non-io related retry error * Test 0: Non-blocking * Test 1: Blocking */ static int test_non_io_retry(int idx) { SSL_CTX *cctx; SSL *clientquic = NULL; QUIC_TSERVER *qtserv = NULL; int testresult = 0; int flags = 0, allow = 0; if (idx >= 1 && !qtest_supports_blocking()) return TEST_skip("Blocking tests not supported in this build"); cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()); if (!TEST_ptr(cctx)) goto err; SSL_CTX_set_cert_verify_callback(cctx, non_io_retry_cert_verify_cb, &allow); flags = (idx >= 1) ? QTEST_FLAG_BLOCK : 0; if (!TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, cert, privkey, flags, &qtserv, &clientquic, NULL, NULL)) || !TEST_true(qtest_create_quic_connection_ex(qtserv, clientquic, SSL_ERROR_WANT_RETRY_VERIFY)) || !TEST_int_eq(SSL_want(clientquic), SSL_RETRY_VERIFY)) goto err; allow = 1; if (!TEST_true(qtest_create_quic_connection(qtserv, clientquic))) goto err; testresult = 1; err: SSL_free(clientquic); ossl_quic_tserver_free(qtserv); SSL_CTX_free(cctx); return testresult; } static int use_session_cb_cnt = 0; static int find_session_cb_cnt = 0; static const char *pskid = "Identity"; static SSL_SESSION *serverpsk = NULL, *clientpsk = NULL; static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id, size_t *idlen, SSL_SESSION **sess) { use_session_cb_cnt++; if (clientpsk == NULL || !SSL_SESSION_up_ref(clientpsk)) return 0; *sess = clientpsk; *id = (const unsigned char *)pskid; *idlen = strlen(pskid); return 1; } static int find_session_cb(SSL *ssl, const unsigned char *identity, size_t identity_len, SSL_SESSION **sess) { find_session_cb_cnt++; if (serverpsk == NULL || !SSL_SESSION_up_ref(serverpsk)) return 0; /* Identity should match that set by the client */ if (strlen(pskid) != identity_len || strncmp(pskid, (const char *)identity, identity_len) != 0) { SSL_SESSION_free(serverpsk); return 0; } *sess = serverpsk; return 1; } static int test_quic_psk(void) { SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()); SSL *clientquic = NULL; QUIC_TSERVER *qtserv = NULL; int testresult = 0; if (!TEST_ptr(cctx) /* No cert or private key for the server, i.e. PSK only */ || !TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, NULL, NULL, 0, &qtserv, &clientquic, NULL, NULL))) goto end; SSL_set_psk_use_session_callback(clientquic, use_session_cb); ossl_quic_tserver_set_psk_find_session_cb(qtserv, find_session_cb); use_session_cb_cnt = 0; find_session_cb_cnt = 0; clientpsk = serverpsk = create_a_psk(clientquic, SHA384_DIGEST_LENGTH); /* We already had one ref. Add another one */ if (!TEST_ptr(clientpsk) || !TEST_true(SSL_SESSION_up_ref(clientpsk))) goto end; if (!TEST_true(qtest_create_quic_connection(qtserv, clientquic)) || !TEST_int_eq(1, find_session_cb_cnt) || !TEST_int_eq(1, use_session_cb_cnt) /* Check that we actually used the PSK */ || !TEST_true(SSL_session_reused(clientquic))) goto end; testresult = 1; end: SSL_free(clientquic); ossl_quic_tserver_free(qtserv); SSL_CTX_free(cctx); SSL_SESSION_free(clientpsk); SSL_SESSION_free(serverpsk); clientpsk = serverpsk = NULL; return testresult; } static int test_client_auth(int idx) { SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()); SSL_CTX *sctx = SSL_CTX_new_ex(libctx, NULL, TLS_method()); SSL *clientquic = NULL; QUIC_TSERVER *qtserv = NULL; int testresult = 0; unsigned char buf[20]; static char *msg = "A test message"; size_t msglen = strlen(msg); size_t numbytes = 0; if (!TEST_ptr(cctx) || !TEST_ptr(sctx)) goto err; SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE, NULL); if (!TEST_true(SSL_CTX_load_verify_file(sctx, cauthca))) goto err; if (idx > 0 && (!TEST_true(SSL_CTX_use_certificate_chain_file(cctx, ccert)) || !TEST_true(SSL_CTX_use_PrivateKey_file(cctx, cprivkey, SSL_FILETYPE_PEM)))) goto err; if (!TEST_true(qtest_create_quic_objects(libctx, cctx, sctx, cert, privkey, 0, &qtserv, &clientquic, NULL, NULL))) goto err; if (idx > 1) { if (!TEST_true(ssl_ctx_add_large_cert_chain(libctx, cctx, ccert)) || !TEST_true(ssl_ctx_add_large_cert_chain(libctx, sctx, cert))) goto err; } if (idx == 0) { if (!TEST_false(qtest_create_quic_connection(qtserv, clientquic))) goto err; /* negative test passed */ testresult = 1; goto err; } if (!TEST_true(qtest_create_quic_connection(qtserv, clientquic))) goto err; /* Check that sending and receiving app data is ok */ if (!TEST_true(SSL_write_ex(clientquic, msg, msglen, &numbytes)) || !TEST_size_t_eq(numbytes, msglen)) goto err; ossl_quic_tserver_tick(qtserv); if (!TEST_true(ossl_quic_tserver_write(qtserv, 0, (unsigned char *)msg, msglen, &numbytes))) goto err; ossl_quic_tserver_tick(qtserv); SSL_handle_events(clientquic); if (!TEST_true(SSL_read_ex(clientquic, buf, sizeof(buf), &numbytes)) || !TEST_size_t_eq(numbytes, msglen) || !TEST_mem_eq(buf, numbytes, msg, msglen)) goto err; if (!TEST_true(qtest_shutdown(qtserv, clientquic))) goto err; testresult = 1; err: SSL_free(clientquic); ossl_quic_tserver_free(qtserv); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } /* * Test that we correctly handle ALPN supplied by the application * Test 0: ALPN is provided * Test 1: No ALPN is provided */ static int test_alpn(int idx) { SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()); SSL *clientquic = NULL; QUIC_TSERVER *qtserv = NULL; int testresult = 0; int ret; /* * Ensure we only configure ciphersuites that are available with both the * default and fips providers to get the same output in both cases */ if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_128_GCM_SHA256"))) goto err; if (!TEST_ptr(cctx) || !TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, cert, privkey, QTEST_FLAG_FAKE_TIME, &qtserv, &clientquic, NULL, NULL))) goto err; if (idx == 0) { /* * Clear the ALPN we set in qtest_create_quic_objects. We use TEST_false * because SSL_set_alpn_protos returns 0 for success. */ if (!TEST_false(SSL_set_alpn_protos(clientquic, NULL, 0))) goto err; } ret = SSL_connect(clientquic); if (!TEST_int_le(ret, 0)) goto err; if (idx == 0) { /* We expect an immediate error due to lack of ALPN */ if (!TEST_int_eq(SSL_get_error(clientquic, ret), SSL_ERROR_SSL)) goto err; } else { /* ALPN was provided so we expect the connection to succeed */ if (!TEST_int_eq(SSL_get_error(clientquic, ret), SSL_ERROR_WANT_READ) || !TEST_true(qtest_create_quic_connection(qtserv, clientquic))) goto err; } testresult = 1; err: ossl_quic_tserver_free(qtserv); SSL_free(clientquic); SSL_CTX_free(cctx); return testresult; } /* * Test SSL_get_shutdown() behavior. */ static int test_get_shutdown(void) { SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()); SSL *clientquic = NULL; QUIC_TSERVER *qtserv = NULL; int testresult = 0; if (!TEST_ptr(cctx) || !TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, cert, privkey, QTEST_FLAG_FAKE_TIME, &qtserv, &clientquic, NULL, NULL)) || !TEST_true(qtest_create_quic_connection(qtserv, clientquic))) goto err; if (!TEST_int_eq(SSL_get_shutdown(clientquic), 0)) goto err; if (!TEST_int_eq(SSL_shutdown(clientquic), 0)) goto err; if (!TEST_int_eq(SSL_get_shutdown(clientquic), SSL_SENT_SHUTDOWN)) goto err; do { ossl_quic_tserver_tick(qtserv); qtest_add_time(100); } while (SSL_shutdown(clientquic) == 0); if (!TEST_int_eq(SSL_get_shutdown(clientquic), SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN)) goto err; testresult = 1; err: ossl_quic_tserver_free(qtserv); SSL_free(clientquic); SSL_CTX_free(cctx); return testresult; } #define MAX_LOOPS 2000 /* * Keep retrying SSL_read_ex until it succeeds or we give up. Accept a stream * if we don't already have one */ static int unreliable_client_read(SSL *clientquic, SSL **stream, void *buf, size_t buflen, size_t *readbytes, QUIC_TSERVER *qtserv) { int abortctr; /* We just do this in a loop with a sleep for simplicity */ for (abortctr = 0; abortctr < MAX_LOOPS; abortctr++) { if (*stream == NULL) { SSL_handle_events(clientquic); *stream = SSL_accept_stream(clientquic, 0); } if (*stream != NULL) { if (SSL_read_ex(*stream, buf, buflen, readbytes)) return 1; if (!TEST_int_eq(SSL_get_error(*stream, 0), SSL_ERROR_WANT_READ)) return 0; } ossl_quic_tserver_tick(qtserv); qtest_add_time(1); qtest_wait_for_timeout(clientquic, qtserv); } TEST_error("No progress made"); return 0; } /* Keep retrying ossl_quic_tserver_read until it succeeds or we give up */ static int unreliable_server_read(QUIC_TSERVER *qtserv, uint64_t sid, void *buf, size_t buflen, size_t *readbytes, SSL *clientquic) { int abortctr; /* We just do this in a loop with a sleep for simplicity */ for (abortctr = 0; abortctr < MAX_LOOPS; abortctr++) { if (ossl_quic_tserver_read(qtserv, sid, buf, buflen, readbytes) && *readbytes > 1) return 1; ossl_quic_tserver_tick(qtserv); SSL_handle_events(clientquic); qtest_add_time(1); qtest_wait_for_timeout(clientquic, qtserv); } TEST_error("No progress made"); return 0; } /* * Create a connection and send data using an unreliable transport. We introduce * random noise to drop, delay and duplicate datagrams. * Test 0: Introduce random noise to datagrams * Test 1: As with test 0 but also split datagrams containing multiple packets * into individual datagrams so that individual packets can be affected * by noise - not just a whole datagram. */ static int test_noisy_dgram(int idx) { SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()); SSL *clientquic = NULL, *stream[2] = { NULL, NULL }; QUIC_TSERVER *qtserv = NULL; int testresult = 0; uint64_t sid = 0; char *msg = "Hello world!"; size_t msglen = strlen(msg), written, readbytes, i, j; unsigned char buf[80]; int flags = QTEST_FLAG_NOISE | QTEST_FLAG_FAKE_TIME; QTEST_FAULT *fault = NULL; if (idx == 1) flags |= QTEST_FLAG_PACKET_SPLIT; if (!TEST_ptr(cctx) || !TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, cert, privkey, flags, &qtserv, &clientquic, &fault, NULL))) goto err; if (!TEST_true(qtest_create_quic_connection(qtserv, clientquic))) goto err; if (!TEST_true(SSL_set_incoming_stream_policy(clientquic, SSL_INCOMING_STREAM_POLICY_ACCEPT, 0)) || !TEST_true(SSL_set_default_stream_mode(clientquic, SSL_DEFAULT_STREAM_MODE_NONE))) goto err; for (j = 0; j < 2; j++) { if (!TEST_true(ossl_quic_tserver_stream_new(qtserv, 0, &sid))) goto err; ossl_quic_tserver_tick(qtserv); qtest_add_time(1); /* * Send data from the server to the client. Some datagrams may get * lost, modified, dropped or re-ordered. We repeat 20 times to ensure * we are sending enough datagrams for problems to be noticed. */ for (i = 0; i < 20; i++) { if (!TEST_true(ossl_quic_tserver_write(qtserv, sid, (unsigned char *)msg, msglen, &written)) || !TEST_size_t_eq(msglen, written)) goto err; ossl_quic_tserver_tick(qtserv); qtest_add_time(1); /* * Since the underlying BIO is now noisy we may get failures that * need to be retried - so we use unreliable_client_read() to * handle that */ if (!TEST_true(unreliable_client_read(clientquic, &stream[j], buf, sizeof(buf), &readbytes, qtserv)) || !TEST_mem_eq(msg, msglen, buf, readbytes)) goto err; } /* Send data from the client to the server */ for (i = 0; i < 20; i++) { if (!TEST_true(SSL_write_ex(stream[j], (unsigned char *)msg, msglen, &written)) || !TEST_size_t_eq(msglen, written)) goto err; ossl_quic_tserver_tick(qtserv); qtest_add_time(1); /* * Since the underlying BIO is now noisy we may get failures that * need to be retried - so we use unreliable_server_read() to * handle that */ if (!TEST_true(unreliable_server_read(qtserv, sid, buf, sizeof(buf), &readbytes, clientquic)) || !TEST_mem_eq(msg, msglen, buf, readbytes)) goto err; } } testresult = 1; err: ossl_quic_tserver_free(qtserv); SSL_free(stream[0]); SSL_free(stream[1]); SSL_free(clientquic); SSL_CTX_free(cctx); qtest_fault_free(fault); return testresult; } /* * Create a connection and send some big data using a transport with limited bandwidth. */ #define TEST_TRANSFER_DATA_SIZE (2*1024*1024) /* 2 MBytes */ #define TEST_SINGLE_WRITE_SIZE (16*1024) /* 16 kBytes */ #define TEST_BW_LIMIT 1000 /* 1000 Bytes/ms */ static int test_bw_limit(void) { SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()); SSL *clientquic = NULL; QUIC_TSERVER *qtserv = NULL; int testresult = 0; unsigned char *msg = NULL, *recvbuf = NULL; size_t sendlen = TEST_TRANSFER_DATA_SIZE; size_t recvlen = TEST_TRANSFER_DATA_SIZE; size_t written, readbytes; int flags = QTEST_FLAG_NOISE | QTEST_FLAG_FAKE_TIME; QTEST_FAULT *fault = NULL; uint64_t real_bw; if (!TEST_ptr(cctx) || !TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, cert, privkey, flags, &qtserv, &clientquic, &fault, NULL))) goto err; if (!TEST_ptr(msg = OPENSSL_zalloc(TEST_SINGLE_WRITE_SIZE)) || !TEST_ptr(recvbuf = OPENSSL_zalloc(TEST_SINGLE_WRITE_SIZE))) goto err; /* Set BW to 1000 Bytes/ms -> 1MByte/s both ways */ if (!TEST_true(qtest_fault_set_bw_limit(fault, 1000, 1000, 0))) goto err; if (!TEST_true(qtest_create_quic_connection(qtserv, clientquic))) goto err; qtest_start_stopwatch(); while (recvlen > 0) { qtest_add_time(1); if (sendlen > 0) { if (!SSL_write_ex(clientquic, msg, sendlen > TEST_SINGLE_WRITE_SIZE ? TEST_SINGLE_WRITE_SIZE : sendlen, &written)) { TEST_info("Retrying to send: %llu", (unsigned long long) sendlen); if (!TEST_int_eq(SSL_get_error(clientquic, 0), SSL_ERROR_WANT_WRITE)) goto err; } else { sendlen -= written; TEST_info("Remaining to send: %llu", (unsigned long long) sendlen); } } else { SSL_handle_events(clientquic); } if (ossl_quic_tserver_read(qtserv, 0, recvbuf, recvlen > TEST_SINGLE_WRITE_SIZE ? TEST_SINGLE_WRITE_SIZE : recvlen, &readbytes) && readbytes > 1) { recvlen -= readbytes; TEST_info("Remaining to recv: %llu", (unsigned long long) recvlen); } else { TEST_info("No progress on recv: %llu", (unsigned long long) recvlen); } ossl_quic_tserver_tick(qtserv); } real_bw = TEST_TRANSFER_DATA_SIZE / qtest_get_stopwatch_time(); TEST_info("BW limit: %d Bytes/ms Real bandwidth reached: %llu Bytes/ms", TEST_BW_LIMIT, (unsigned long long)real_bw); if (!TEST_uint64_t_lt(real_bw, TEST_BW_LIMIT)) goto err; testresult = 1; err: OPENSSL_free(msg); OPENSSL_free(recvbuf); ossl_quic_tserver_free(qtserv); SSL_free(clientquic); SSL_CTX_free(cctx); qtest_fault_free(fault); return testresult; } enum { TPARAM_OP_DUP, TPARAM_OP_DROP, TPARAM_OP_INJECT, TPARAM_OP_INJECT_TWICE, TPARAM_OP_INJECT_RAW, TPARAM_OP_DROP_INJECT, TPARAM_OP_MUTATE }; #define TPARAM_CHECK_DUP(name, reason) \ { QUIC_TPARAM_##name, TPARAM_OP_DUP, (reason) }, #define TPARAM_CHECK_DROP(name, reason) \ { QUIC_TPARAM_##name, TPARAM_OP_DROP, (reason) }, #define TPARAM_CHECK_INJECT(name, buf, buf_len, reason) \ { QUIC_TPARAM_##name, TPARAM_OP_INJECT, (reason), \ (buf), (buf_len) }, #define TPARAM_CHECK_INJECT_A(name, buf, reason) \ TPARAM_CHECK_INJECT(name, buf, sizeof(buf), reason) #define TPARAM_CHECK_DROP_INJECT(name, buf, buf_len, reason) \ { QUIC_TPARAM_##name, TPARAM_OP_DROP_INJECT, (reason), \ (buf), (buf_len) }, #define TPARAM_CHECK_DROP_INJECT_A(name, buf, reason) \ TPARAM_CHECK_DROP_INJECT(name, buf, sizeof(buf), reason) #define TPARAM_CHECK_INJECT_TWICE(name, buf, buf_len, reason) \ { QUIC_TPARAM_##name, TPARAM_OP_INJECT_TWICE, (reason), \ (buf), (buf_len) }, #define TPARAM_CHECK_INJECT_TWICE_A(name, buf, reason) \ TPARAM_CHECK_INJECT_TWICE(name, buf, sizeof(buf), reason) #define TPARAM_CHECK_INJECT_RAW(buf, buf_len, reason) \ { 0, TPARAM_OP_INJECT_RAW, (reason), \ (buf), (buf_len) }, #define TPARAM_CHECK_INJECT_RAW_A(buf, reason) \ TPARAM_CHECK_INJECT_RAW(buf, sizeof(buf), reason) #define TPARAM_CHECK_MUTATE(name, reason) \ { QUIC_TPARAM_##name, TPARAM_OP_MUTATE, (reason) }, #define TPARAM_CHECK_INT(name, reason) \ TPARAM_CHECK_DROP_INJECT(name, NULL, 0, reason) \ TPARAM_CHECK_DROP_INJECT_A(name, bogus_int, reason) \ TPARAM_CHECK_DROP_INJECT_A(name, int_with_trailer, reason) struct tparam_test { uint64_t id; int op; const char *expect_fail; /* substring to expect in reason */ const void *buf; size_t buf_len; }; static const unsigned char disable_active_migration_1[] = { 0x00 }; static const unsigned char malformed_stateless_reset_token_1[] = { 0x02, 0xff }; static const unsigned char malformed_stateless_reset_token_2[] = { 0x01 }; static const unsigned char malformed_stateless_reset_token_3[15] = { 0 }; static const unsigned char malformed_stateless_reset_token_4[17] = { 0 }; static const unsigned char malformed_preferred_addr_1[] = { 0x0d, 0xff }; static const unsigned char malformed_preferred_addr_2[42] = { 0x0d, 0x28, /* too short */ }; static const unsigned char malformed_preferred_addr_3[64] = { 0x0d, 0x3e, /* too long */ }; static const unsigned char malformed_preferred_addr_4[] = { /* TPARAM too short for CID length indicated */ 0x0d, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const unsigned char malformed_unknown_1[] = { 0xff }; static const unsigned char malformed_unknown_2[] = { 0x55, 0x55, }; static const unsigned char malformed_unknown_3[] = { 0x55, 0x55, 0x01, }; static const unsigned char ack_delay_exp[] = { 0x03 }; static const unsigned char stateless_reset_token[16] = { 0x42 }; static const unsigned char preferred_addr[] = { 0x44, 0x44, 0x44, 0x44, 0x55, 0x55, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x77, 0x77, 0x02, 0xAA, 0xBB, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, }; static const unsigned char long_cid[21] = { 0x42 }; static const unsigned char excess_ack_delay_exp[] = { 0x15, }; static const unsigned char excess_max_ack_delay[] = { 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, }; static const unsigned char excess_initial_max_streams[] = { 0xD0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, }; static const unsigned char undersize_udp_payload_size[] = { 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0xaf, }; static const unsigned char undersize_active_conn_id_limit[] = { 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, }; static const unsigned char bogus_int[9] = { 0 }; static const unsigned char int_with_trailer[2] = { 0x01 }; #define QUIC_TPARAM_UNKNOWN_1 0xf1f1 static const struct tparam_test tparam_tests[] = { TPARAM_CHECK_DUP(ORIG_DCID, "ORIG_DCID appears multiple times") TPARAM_CHECK_DUP(INITIAL_SCID, "INITIAL_SCID appears multiple times") TPARAM_CHECK_DUP(INITIAL_MAX_DATA, "INITIAL_MAX_DATA appears multiple times") TPARAM_CHECK_DUP(INITIAL_MAX_STREAM_DATA_BIDI_LOCAL, "INITIAL_MAX_STREAM_DATA_BIDI_LOCAL appears multiple times") TPARAM_CHECK_DUP(INITIAL_MAX_STREAM_DATA_BIDI_REMOTE, "INITIAL_MAX_STREAM_DATA_BIDI_REMOTE appears multiple times") TPARAM_CHECK_DUP(INITIAL_MAX_STREAM_DATA_UNI, "INITIAL_MAX_STREAM_DATA_UNI appears multiple times") TPARAM_CHECK_DUP(INITIAL_MAX_STREAMS_BIDI, "INITIAL_MAX_STREAMS_BIDI appears multiple times") TPARAM_CHECK_DUP(INITIAL_MAX_STREAMS_UNI, "INITIAL_MAX_STREAMS_UNI appears multiple times") TPARAM_CHECK_DUP(MAX_IDLE_TIMEOUT, "MAX_IDLE_TIMEOUT appears multiple times") TPARAM_CHECK_DUP(MAX_UDP_PAYLOAD_SIZE, "MAX_UDP_PAYLOAD_SIZE appears multiple times") TPARAM_CHECK_DUP(ACTIVE_CONN_ID_LIMIT, "ACTIVE_CONN_ID_LIMIT appears multiple times") TPARAM_CHECK_DUP(DISABLE_ACTIVE_MIGRATION, "DISABLE_ACTIVE_MIGRATION appears multiple times") TPARAM_CHECK_DROP(INITIAL_SCID, "INITIAL_SCID was not sent but is required") TPARAM_CHECK_DROP(ORIG_DCID, "ORIG_DCID was not sent but is required") TPARAM_CHECK_DROP_INJECT_A(DISABLE_ACTIVE_MIGRATION, disable_active_migration_1, "DISABLE_ACTIVE_MIGRATION is malformed") TPARAM_CHECK_INJECT(UNKNOWN_1, NULL, 0, NULL) TPARAM_CHECK_INJECT_RAW_A(malformed_stateless_reset_token_1, "STATELESS_RESET_TOKEN is malformed") TPARAM_CHECK_INJECT_A(STATELESS_RESET_TOKEN, malformed_stateless_reset_token_2, "STATELESS_RESET_TOKEN is malformed") TPARAM_CHECK_INJECT_A(STATELESS_RESET_TOKEN, malformed_stateless_reset_token_3, "STATELESS_RESET_TOKEN is malformed") TPARAM_CHECK_INJECT_A(STATELESS_RESET_TOKEN, malformed_stateless_reset_token_4, "STATELESS_RESET_TOKEN is malformed") TPARAM_CHECK_INJECT(STATELESS_RESET_TOKEN, NULL, 0, "STATELESS_RESET_TOKEN is malformed") TPARAM_CHECK_INJECT_RAW_A(malformed_preferred_addr_1, "PREFERRED_ADDR is malformed") TPARAM_CHECK_INJECT_RAW_A(malformed_preferred_addr_2, "PREFERRED_ADDR is malformed") TPARAM_CHECK_INJECT_RAW_A(malformed_preferred_addr_3, "PREFERRED_ADDR is malformed") TPARAM_CHECK_INJECT_RAW_A(malformed_preferred_addr_4, "PREFERRED_ADDR is malformed") TPARAM_CHECK_INJECT_RAW_A(malformed_unknown_1, "bad transport parameter") TPARAM_CHECK_INJECT_RAW_A(malformed_unknown_2, "bad transport parameter") TPARAM_CHECK_INJECT_RAW_A(malformed_unknown_3, "bad transport parameter") TPARAM_CHECK_INJECT_A(ACK_DELAY_EXP, excess_ack_delay_exp, "ACK_DELAY_EXP is malformed") TPARAM_CHECK_INJECT_A(MAX_ACK_DELAY, excess_max_ack_delay, "MAX_ACK_DELAY is malformed") TPARAM_CHECK_DROP_INJECT_A(INITIAL_MAX_STREAMS_BIDI, excess_initial_max_streams, "INITIAL_MAX_STREAMS_BIDI is malformed") TPARAM_CHECK_DROP_INJECT_A(INITIAL_MAX_STREAMS_UNI, excess_initial_max_streams, "INITIAL_MAX_STREAMS_UNI is malformed") TPARAM_CHECK_DROP_INJECT_A(MAX_UDP_PAYLOAD_SIZE, undersize_udp_payload_size, "MAX_UDP_PAYLOAD_SIZE is malformed") TPARAM_CHECK_DROP_INJECT_A(ACTIVE_CONN_ID_LIMIT, undersize_active_conn_id_limit, "ACTIVE_CONN_ID_LIMIT is malformed") TPARAM_CHECK_INJECT_TWICE_A(ACK_DELAY_EXP, ack_delay_exp, "ACK_DELAY_EXP appears multiple times") TPARAM_CHECK_INJECT_TWICE_A(MAX_ACK_DELAY, ack_delay_exp, "MAX_ACK_DELAY appears multiple times") TPARAM_CHECK_INJECT_TWICE_A(STATELESS_RESET_TOKEN, stateless_reset_token, "STATELESS_RESET_TOKEN appears multiple times") TPARAM_CHECK_INJECT_TWICE_A(PREFERRED_ADDR, preferred_addr, "PREFERRED_ADDR appears multiple times") TPARAM_CHECK_MUTATE(ORIG_DCID, "ORIG_DCID does not match expected value") TPARAM_CHECK_MUTATE(INITIAL_SCID, "INITIAL_SCID does not match expected value") TPARAM_CHECK_DROP_INJECT_A(ORIG_DCID, long_cid, "ORIG_DCID is malformed") TPARAM_CHECK_DROP_INJECT_A(INITIAL_SCID, long_cid, "INITIAL_SCID is malformed") TPARAM_CHECK_INT(INITIAL_MAX_DATA, "INITIAL_MAX_DATA is malformed") TPARAM_CHECK_INT(INITIAL_MAX_STREAM_DATA_BIDI_LOCAL, "INITIAL_MAX_STREAM_DATA_BIDI_LOCAL is malformed") TPARAM_CHECK_INT(INITIAL_MAX_STREAM_DATA_BIDI_REMOTE, "INITIAL_MAX_STREAM_DATA_BIDI_REMOTE is malformed") TPARAM_CHECK_INT(INITIAL_MAX_STREAM_DATA_UNI, "INITIAL_MAX_STREAM_DATA_UNI is malformed") TPARAM_CHECK_INT(ACK_DELAY_EXP, "ACK_DELAY_EXP is malformed") TPARAM_CHECK_INT(MAX_ACK_DELAY, "MAX_ACK_DELAY is malformed") TPARAM_CHECK_INT(INITIAL_MAX_STREAMS_BIDI, "INITIAL_MAX_STREAMS_BIDI is malformed") TPARAM_CHECK_INT(INITIAL_MAX_STREAMS_UNI, "INITIAL_MAX_STREAMS_UNI is malformed") TPARAM_CHECK_INT(MAX_IDLE_TIMEOUT, "MAX_IDLE_TIMEOUT is malformed") TPARAM_CHECK_INT(MAX_UDP_PAYLOAD_SIZE, "MAX_UDP_PAYLOAD_SIZE is malformed") TPARAM_CHECK_INT(ACTIVE_CONN_ID_LIMIT, "ACTIVE_CONN_ID_LIMIT is malformed") }; struct tparam_ctx { const struct tparam_test *t; }; static int tparam_handle(struct tparam_ctx *ctx, uint64_t id, unsigned char *data, size_t data_len, WPACKET *wpkt) { const struct tparam_test *t = ctx->t; switch (t->op) { case TPARAM_OP_DUP: if (!TEST_ptr(ossl_quic_wire_encode_transport_param_bytes(wpkt, id, data, data_len))) return 0; /* * If this is the matching ID, write it again, duplicating the TPARAM. */ if (id == t->id && !TEST_ptr(ossl_quic_wire_encode_transport_param_bytes(wpkt, id, data, data_len))) return 0; return 1; case TPARAM_OP_DROP: case TPARAM_OP_DROP_INJECT: /* Pass through unless ID matches. */ if (id != t->id && !TEST_ptr(ossl_quic_wire_encode_transport_param_bytes(wpkt, id, data, data_len))) return 0; return 1; case TPARAM_OP_INJECT: case TPARAM_OP_INJECT_TWICE: case TPARAM_OP_INJECT_RAW: /* Always pass through. */ if (!TEST_ptr(ossl_quic_wire_encode_transport_param_bytes(wpkt, id, data, data_len))) return 0; return 1; case TPARAM_OP_MUTATE: if (id == t->id) { if (!TEST_size_t_gt(data_len, 0)) return 0; data[0] ^= 1; } if (!TEST_ptr(ossl_quic_wire_encode_transport_param_bytes(wpkt, id, data, data_len))) return 0; if (id == t->id) data[0] ^= 1; return 1; default: return 0; } } static int tparam_on_enc_ext(QTEST_FAULT *qtf, QTEST_ENCRYPTED_EXTENSIONS *ee, size_t ee_len, void *arg) { int rc = 0; struct tparam_ctx *ctx = arg; PACKET pkt = {0}; WPACKET wpkt; int have_wpkt = 0; BUF_MEM *old_bufm = NULL, *new_bufm = NULL; unsigned char *tp_p; size_t tp_len, written, old_len, eb_len; uint64_t id; if (!TEST_ptr(old_bufm = BUF_MEM_new())) goto err; /* * Delete transport parameters TLS extension and capture the contents of the * extension which was removed. */ if (!TEST_true(qtest_fault_delete_extension(qtf, TLSEXT_TYPE_quic_transport_parameters, ee->extensions, &ee->extensionslen, old_bufm))) goto err; if (!TEST_true(PACKET_buf_init(&pkt, (unsigned char *)old_bufm->data, old_bufm->length)) || !TEST_ptr(new_bufm = BUF_MEM_new()) || !TEST_true(WPACKET_init(&wpkt, new_bufm))) goto err; have_wpkt = 1; /* * Open transport parameters TLS extension: * * u16 Extension ID (quic_transport_parameters) * u16 Extension Data Length * ... Extension Data * */ if (!TEST_true(WPACKET_put_bytes_u16(&wpkt, TLSEXT_TYPE_quic_transport_parameters)) || !TEST_true(WPACKET_start_sub_packet_u16(&wpkt))) goto err; for (; PACKET_remaining(&pkt) > 0; ) { tp_p = (unsigned char *)ossl_quic_wire_decode_transport_param_bytes(&pkt, &id, &tp_len); if (!TEST_ptr(tp_p)) { TEST_mem_eq(PACKET_data(&pkt), PACKET_remaining(&pkt), NULL, 0); goto err; } if (!TEST_true(tparam_handle(ctx, id, tp_p, tp_len, &wpkt))) goto err; } if (ctx->t->op == TPARAM_OP_INJECT || ctx->t->op == TPARAM_OP_DROP_INJECT || ctx->t->op == TPARAM_OP_INJECT_TWICE) { if (!TEST_ptr(ossl_quic_wire_encode_transport_param_bytes(&wpkt, ctx->t->id, ctx->t->buf, ctx->t->buf_len))) goto err; if (ctx->t->op == TPARAM_OP_INJECT_TWICE && !TEST_ptr(ossl_quic_wire_encode_transport_param_bytes(&wpkt, ctx->t->id, ctx->t->buf, ctx->t->buf_len))) goto err; } else if (ctx->t->op == TPARAM_OP_INJECT_RAW) { if (!TEST_true(WPACKET_memcpy(&wpkt, ctx->t->buf, ctx->t->buf_len))) goto err; } if (!TEST_true(WPACKET_close(&wpkt))) /* end extension data, set length */ goto err; if (!TEST_true(WPACKET_get_total_written(&wpkt, &written))) goto err; WPACKET_finish(&wpkt); have_wpkt = 0; /* * Append the constructed extension blob to the extension block. */ old_len = ee->extensionslen; if (!qtest_fault_resize_message(qtf, ee->extensionslen + written)) goto err; memcpy(ee->extensions + old_len, new_bufm->data, written); /* Fixup the extension block header (u16 length of entire block). */ eb_len = (((uint16_t)ee->extensions[0]) << 8) + (uint16_t)ee->extensions[1]; eb_len += written; ee->extensions[0] = (unsigned char)((eb_len >> 8) & 0xFF); ee->extensions[1] = (unsigned char)( eb_len & 0xFF); rc = 1; err: if (have_wpkt) WPACKET_cleanup(&wpkt); BUF_MEM_free(old_bufm); BUF_MEM_free(new_bufm); return rc; } static int test_tparam(int idx) { int testresult = 0; SSL_CTX *c_ctx = NULL; SSL *c_ssl = NULL; QUIC_TSERVER *s = NULL; QTEST_FAULT *qtf = NULL; struct tparam_ctx ctx = {0}; ctx.t = &tparam_tests[idx]; if (!TEST_ptr(c_ctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()))) goto err; if (!TEST_true(qtest_create_quic_objects(libctx, c_ctx, NULL, cert, privkey, 0, &s, &c_ssl, &qtf, NULL))) goto err; if (!TEST_true(qtest_fault_set_hand_enc_ext_listener(qtf, tparam_on_enc_ext, &ctx))) goto err; if (!TEST_true(qtest_create_quic_connection_ex(s, c_ssl, ctx.t->expect_fail != NULL))) goto err; if (ctx.t->expect_fail != NULL) { SSL_CONN_CLOSE_INFO info = {0}; if (!TEST_true(SSL_get_conn_close_info(c_ssl, &info, sizeof(info)))) goto err; if (!TEST_true((info.flags & SSL_CONN_CLOSE_FLAG_TRANSPORT) != 0) || !TEST_uint64_t_eq(info.error_code, OSSL_QUIC_ERR_TRANSPORT_PARAMETER_ERROR) || !TEST_ptr(strstr(info.reason, ctx.t->expect_fail))) { TEST_error("expected connection closure information mismatch" " during TPARAM test: flags=%llu ec=%llu reason='%s'", (unsigned long long)info.flags, (unsigned long long)info.error_code, info.reason); goto err; } } testresult = 1; err: if (!testresult) { if (ctx.t->expect_fail != NULL) TEST_info("failed during test for id=%llu, op=%d, bl=%zu, " "expected failure='%s'", (unsigned long long)ctx.t->id, ctx.t->op, ctx.t->buf_len, ctx.t->expect_fail); else TEST_info("failed during test for id=%llu, op=%d, bl=%zu", (unsigned long long)ctx.t->id, ctx.t->op, ctx.t->buf_len); } ossl_quic_tserver_free(s); SSL_free(c_ssl); SSL_CTX_free(c_ctx); qtest_fault_free(qtf); return testresult; } static int new_called = 0; static SSL *cbssl = NULL; static int new_session_cb(SSL *ssl, SSL_SESSION *sess) { new_called++; /* * Remember the SSL ref we were called with. No need to up-ref this. It * should remain valid for the duration of the test. */ cbssl = ssl; /* * sess has been up-refed for us, but we don't actually need it so free it * immediately. */ SSL_SESSION_free(sess); return 1; } /* Test using a new_session_cb with a QUIC SSL object works as expected */ static int test_session_cb(void) { SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()); SSL *clientquic = NULL; QUIC_TSERVER *qtserv = NULL; int testresult = 0; if (!TEST_ptr(cctx)) goto err; new_called = 0; cbssl = NULL; SSL_CTX_sess_set_new_cb(cctx, new_session_cb); SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT); if (!TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, cert, privkey, QTEST_FLAG_FAKE_TIME, &qtserv, &clientquic, NULL, NULL))) goto err; if (!TEST_true(qtest_create_quic_connection(qtserv, clientquic))) goto err; /* Process the pending NewSessionTickets */ if (!TEST_true(SSL_handle_events(clientquic))) goto err; if (!TEST_int_eq(SSL_shutdown(clientquic), 0)) goto err; /* * Check the callback was called twice (we expect 2 tickets), and with the * correct SSL reference */ if (!TEST_int_eq(new_called, 2) || !TEST_ptr_eq(clientquic, cbssl)) goto err; testresult = 1; err: cbssl = NULL; ossl_quic_tserver_free(qtserv); SSL_free(clientquic); SSL_CTX_free(cctx); return testresult; } static int test_domain_flags(void) { int testresult = 0; SSL_CTX *ctx = NULL; SSL *domain = NULL, *listener = NULL, *other_conn = NULL; uint64_t domain_flags = 0; if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method())) || !TEST_true(SSL_CTX_get_domain_flags(ctx, &domain_flags)) || !TEST_uint64_t_ne(domain_flags, 0) || !TEST_uint64_t_ne(domain_flags & (SSL_DOMAIN_FLAG_SINGLE_THREAD | SSL_DOMAIN_FLAG_MULTI_THREAD), 0) || !TEST_uint64_t_ne(domain_flags & SSL_DOMAIN_FLAG_LEGACY_BLOCKING, 0) || !TEST_true(SSL_CTX_set_domain_flags(ctx, SSL_DOMAIN_FLAG_SINGLE_THREAD)) || !TEST_true(SSL_CTX_get_domain_flags(ctx, &domain_flags)) || !TEST_uint64_t_eq(domain_flags, SSL_DOMAIN_FLAG_SINGLE_THREAD) || !TEST_ptr(domain = SSL_new_domain(ctx, 0)) || !TEST_true(SSL_get_domain_flags(domain, &domain_flags)) || !TEST_uint64_t_eq(domain_flags, SSL_DOMAIN_FLAG_SINGLE_THREAD) || !TEST_true(other_conn = SSL_new(ctx)) || !TEST_true(SSL_get_domain_flags(other_conn, &domain_flags)) || !TEST_uint64_t_eq(domain_flags, SSL_DOMAIN_FLAG_SINGLE_THREAD) || !TEST_true(SSL_is_domain(domain)) || !TEST_false(SSL_is_domain(other_conn)) || !TEST_ptr_eq(SSL_get0_domain(domain), domain) || !TEST_ptr_null(SSL_get0_domain(other_conn)) || !TEST_ptr(listener = SSL_new_listener_from(domain, 0)) || !TEST_true(SSL_is_listener(listener)) || !TEST_false(SSL_is_domain(listener)) || !TEST_ptr_eq(SSL_get0_domain(listener), domain) || !TEST_ptr_eq(SSL_get0_listener(listener), listener)) goto err; testresult = 1; err: SSL_free(domain); SSL_free(listener); SSL_free(other_conn); SSL_CTX_free(ctx); return testresult; } /* * Test that calling SSL_handle_events() early behaves as expected */ static int test_early_ticks(void) { SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()); SSL *clientquic = NULL; QUIC_TSERVER *qtserv = NULL; int testresult = 0; struct timeval tv; int inf = 0; if (!TEST_ptr(cctx) || !TEST_true(qtest_create_quic_objects(libctx, cctx, NULL, cert, privkey, QTEST_FLAG_FAKE_TIME, &qtserv, &clientquic, NULL, NULL))) goto err; if (!TEST_true(SSL_in_before(clientquic))) goto err; if (!TEST_true(SSL_handle_events(clientquic))) goto err; if (!TEST_true(SSL_get_event_timeout(clientquic, &tv, &inf)) || !TEST_true(inf)) goto err; if (!TEST_false(SSL_has_pending(clientquic)) || !TEST_int_eq(SSL_pending(clientquic), 0)) goto err; if (!TEST_true(SSL_in_before(clientquic))) goto err; if (!TEST_true(qtest_create_quic_connection(qtserv, clientquic))) goto err; if (!TEST_false(SSL_in_before(clientquic))) goto err; testresult = 1; err: SSL_free(clientquic); SSL_CTX_free(cctx); ossl_quic_tserver_free(qtserv); return testresult; } static int select_alpn(SSL *ssl, const unsigned char **out, unsigned char *out_len, const unsigned char *in, unsigned int in_len, void *arg) { static unsigned char alpn[] = { 8, 'o', 's', 's', 'l', 't', 'e', 's', 't' }; if (SSL_select_next_proto((unsigned char **)out, out_len, alpn, sizeof(alpn), in, in_len) == OPENSSL_NPN_NEGOTIATED) return SSL_TLSEXT_ERR_OK; return SSL_TLSEXT_ERR_ALERT_FATAL; } static SSL_CTX *create_client_ctx(void) { SSL_CTX *ssl_ctx; if (!TEST_ptr(ssl_ctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method()))) { SSL_CTX_free(ssl_ctx); ssl_ctx = NULL; } return ssl_ctx; } static SSL_CTX *create_server_ctx(void) { SSL_CTX *ssl_ctx; if (!TEST_ptr(ssl_ctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_server_method())) || !TEST_true(SSL_CTX_use_certificate_file(ssl_ctx, cert, SSL_FILETYPE_PEM)) || !TEST_true(SSL_CTX_use_PrivateKey_file(ssl_ctx, privkey, SSL_FILETYPE_PEM))) { SSL_CTX_free(ssl_ctx); ssl_ctx = NULL; } else { SSL_CTX_set_alpn_select_cb(ssl_ctx, select_alpn, NULL); SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_NONE, NULL); } return ssl_ctx; } static BIO_ADDR *create_addr(struct in_addr *ina, short int port) { BIO_ADDR *addr = NULL; if (!TEST_ptr(addr = BIO_ADDR_new())) return NULL; if (!TEST_true(BIO_ADDR_rawmake(addr, AF_INET, ina, sizeof(struct in_addr), htons(port)))) { BIO_ADDR_free(addr); return NULL; } return addr; } static int bio_addr_bind(BIO *bio, BIO_ADDR *addr) { int bio_caps = BIO_DGRAM_CAP_HANDLES_DST_ADDR | BIO_DGRAM_CAP_HANDLES_SRC_ADDR; if (!TEST_true(BIO_dgram_set_caps(bio, bio_caps))) return 0; if (!TEST_int_eq(BIO_dgram_set0_local_addr(bio, addr), 1)) return 0; return 1; } static SSL *ql_create(SSL_CTX *ssl_ctx, BIO *bio) { SSL *qserver; if (!TEST_ptr(qserver = SSL_new_listener(ssl_ctx, 0))) { BIO_free(bio); return NULL; } SSL_set_bio(qserver, bio, bio); if (!TEST_true(SSL_listen(qserver))) { SSL_free(qserver); return NULL; } return qserver; } static int qc_init(SSL *qconn, BIO_ADDR *dst_addr) { static unsigned char alpn[] = { 8, 'o', 's', 's', 'l', 't', 'e', 's', 't' }; if (!TEST_true(SSL_set1_initial_peer_addr(qconn, dst_addr))) return 0; if (!TEST_false(SSL_set_alpn_protos(qconn, alpn, sizeof(alpn)))) return 0; return 1; } static int test_ssl_new_from_listener(void) { SSL_CTX *lctx = NULL, *sctx = NULL; SSL *qlistener = NULL, *qserver = NULL, *qconn = 0; int testresult = 0; int chk; BIO *lbio = NULL, *sbio = NULL; BIO_ADDR *addr = NULL; struct in_addr ina; ina.s_addr = htonl(0x1f000001); if (!TEST_ptr(lctx = create_server_ctx()) || !TEST_ptr(sctx = create_server_ctx()) || !TEST_true(BIO_new_bio_dgram_pair(&lbio, 0, &sbio, 0))) goto err; if (!TEST_ptr(addr = create_addr(&ina, 8040))) goto err; if (!TEST_true(bio_addr_bind(lbio, addr))) goto err; addr = NULL; if (!TEST_ptr(addr = create_addr(&ina, 4080))) goto err; if (!TEST_true(bio_addr_bind(sbio, addr))) goto err; addr = NULL; qlistener = ql_create(lctx, lbio); lbio = NULL; if (!TEST_ptr(qlistener)) goto err; qserver = ql_create(sctx, sbio); sbio = NULL; if (!TEST_ptr(qserver)) goto err; if (!TEST_ptr(qconn = SSL_new_from_listener(qlistener, 0))) goto err; if (!TEST_ptr(addr = create_addr(&ina, 4080))) goto err; chk = qc_init(qconn, addr); if (!TEST_true(chk)) goto err; while ((chk = SSL_do_handshake(qconn)) == -1) { SSL_handle_events(qserver); SSL_handle_events(qlistener); } if (!TEST_int_gt(chk, 0)) { TEST_info("SSL_do_handshake() failed\n"); goto err; } testresult = 1; err: SSL_free(qconn); SSL_free(qlistener); SSL_free(qserver); BIO_free(lbio); BIO_free(sbio); SSL_CTX_free(sctx); SSL_CTX_free(lctx); BIO_ADDR_free(addr); return testresult; } static int test_server_method_with_ssl_new(void) { SSL_CTX *ctx = NULL; SSL *ssl = NULL; int ret = 0; unsigned long err; /* Create a new SSL_CTX using the QUIC server method */ ctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_server_method()); if (!TEST_ptr(ctx)) goto end; /* Try to create a new SSL object - this should fail */ ssl = SSL_new(ctx); /* Check that SSL_new() returned NULL */ if (!TEST_ptr_null(ssl)) goto end; /* Check for the expected error */ err = ERR_peek_error(); if (!TEST_true(ERR_GET_LIB(err) == ERR_LIB_SSL && ERR_GET_REASON(err) == ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED)) goto end; ret = 1; end: SSL_free(ssl); SSL_CTX_free(ctx); return ret; } static int create_quic_ssl_objects(SSL_CTX *sctx, SSL_CTX *cctx, SSL **lssl, SSL **cssl) { BIO_ADDR *addr = NULL; struct in_addr ina; BIO *cbio = NULL, *sbio = NULL; int ret = 0; *cssl = *lssl = NULL; ina.s_addr = htonl(0x1f000001); if (!TEST_true(BIO_new_bio_dgram_pair(&cbio, 0, &sbio, 0))) goto err; if (!TEST_ptr(addr = create_addr(&ina, 8040))) goto err; if (!TEST_true(bio_addr_bind(sbio, addr))) goto err; addr = NULL; *lssl = ql_create(sctx, sbio); sbio = NULL; if (!TEST_ptr(*lssl)) goto err; if (!TEST_ptr(*cssl = SSL_new(cctx))) goto err; if (!TEST_ptr(addr = create_addr(&ina, 8040))) goto err; if (!TEST_true(bio_addr_bind(cbio, addr))) goto err; if (!TEST_true(qc_init(*cssl, addr))) { addr = NULL; goto err; } addr = NULL; SSL_set_bio(*cssl, cbio, cbio); cbio = NULL; ret = 1; err: if (!ret) { SSL_free(*cssl); SSL_free(*lssl); *cssl = *lssl = NULL; } BIO_free(cbio); BIO_free(sbio); BIO_ADDR_free(addr); return ret; } static int test_ssl_accept_connection(void) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL, *qlistener = NULL; int testresult = 0; int ret, i; if (!TEST_ptr(sctx = create_server_ctx()) || !TEST_ptr(cctx = create_client_ctx())) goto err; if (!create_quic_ssl_objects(sctx, cctx, &qlistener, &clientssl)) goto err; /* Calling SSL_accept() on a listener is expected to fail */ ret = SSL_accept(qlistener); if (!TEST_int_le(ret, 0) || !TEST_int_eq(SSL_get_error(qlistener, ret), SSL_ERROR_SSL)) goto err; /* Send ClientHello and server retry */ for (i = 0; i < 2; i++) { ret = SSL_connect(clientssl); if (!TEST_int_le(ret, 0) || !TEST_int_eq(SSL_get_error(clientssl, ret), SSL_ERROR_WANT_READ)) goto err; SSL_handle_events(qlistener); } /* We expect a server SSL object which has not yet completed its handshake */ serverssl = SSL_accept_connection(qlistener, 0); if (!TEST_ptr(serverssl) || !TEST_false(SSL_is_init_finished(serverssl))) goto err; /* Call SSL_accept() and SSL_connect() until we are connected */ if (!TEST_true(create_bare_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE, 0, 0))) goto err; testresult = 1; err: SSL_free(serverssl); SSL_free(clientssl); SSL_free(qlistener); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } static SSL *quic_verify_ssl = NULL; static int quic_verify_cb(int ok, X509_STORE_CTX *ctx) { SSL *cssl = (SSL *)X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); /* Confirm we got the SSL object we were expecting */ return TEST_ptr_eq(cssl, quic_verify_ssl); } static int test_ssl_set_verify(void) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL, *qlistener = NULL; int testresult = 0; int ret, i; if (!TEST_ptr(sctx = create_server_ctx()) || !TEST_ptr(cctx = create_client_ctx())) goto err; if (!create_quic_ssl_objects(sctx, cctx, &qlistener, &clientssl)) goto err; quic_verify_ssl = clientssl; SSL_set_verify(clientssl, SSL_VERIFY_PEER, quic_verify_cb); /* Send ClientHello and server retry */ for (i = 0; i < 2; i++) { ret = SSL_connect(clientssl); if (!TEST_int_le(ret, 0) || !TEST_int_eq(SSL_get_error(clientssl, ret), SSL_ERROR_WANT_READ)) goto err; SSL_handle_events(qlistener); } /* We expect a server SSL object which has not yet completed its handshake */ serverssl = SSL_accept_connection(qlistener, 0); /* Call SSL_accept() and SSL_connect() until we are connected */ if (!TEST_true(create_bare_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE, 0, 0))) goto err; testresult = 1; err: SSL_free(serverssl); SSL_free(clientssl); SSL_free(qlistener); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } /* * When the server has a different primary group than the client, the server * should not fail on the client hello retry. */ static int test_client_hello_retry(void) { #if !defined(OPENSSL_NO_EC) && !defined(OPENSSL_NO_ECX) SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL, *qlistener = NULL; int testresult = 0, i = 0, ret = 0; if (!TEST_ptr(sctx = create_server_ctx()) || !TEST_ptr(cctx = create_client_ctx())) goto err; /* * set the specific groups for the test */ if (!TEST_true(SSL_CTX_set1_groups_list(cctx, "secp384r1:secp256r1"))) goto err; if (!TEST_true(SSL_CTX_set1_groups_list(sctx, "secp256r1"))) goto err; if (!create_quic_ssl_objects(sctx, cctx, &qlistener, &clientssl)) goto err; /* Send ClientHello and server retry */ for (i = 0; i < 2; i++) { ret = SSL_connect(clientssl); if (!TEST_int_le(ret, 0) || !TEST_int_eq(SSL_get_error(clientssl, ret), SSL_ERROR_WANT_READ)) goto err; SSL_handle_events(qlistener); } /* We expect a server SSL object which has not yet completed its handshake */ serverssl = SSL_accept_connection(qlistener, 0); /* Call SSL_accept() and SSL_connect() until we are connected */ if (!TEST_true(create_bare_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE, 0, 0))) goto err; testresult = 1; err: SSL_CTX_free(cctx); SSL_CTX_free(sctx); SSL_free(clientssl); SSL_free(serverssl); SSL_free(qlistener); return testresult; #else return TEST_skip("EC(X) keys are not supported in this build"); #endif } /***********************************************************************************/ OPT_TEST_DECLARE_USAGE("provider config certsdir datadir\n") int setup_tests(void) { char *modulename; char *configfile; libctx = OSSL_LIB_CTX_new(); if (!TEST_ptr(libctx)) return 0; defctxnull = OSSL_PROVIDER_load(NULL, "null"); /* * Verify that the default and fips providers in the default libctx are not * available */ if (!TEST_false(OSSL_PROVIDER_available(NULL, "default")) || !TEST_false(OSSL_PROVIDER_available(NULL, "fips"))) goto err; if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); goto err; } if (!TEST_ptr(modulename = test_get_argument(0)) || !TEST_ptr(configfile = test_get_argument(1)) || !TEST_ptr(certsdir = test_get_argument(2)) || !TEST_ptr(datadir = test_get_argument(3))) goto err; if (!TEST_true(OSSL_LIB_CTX_load_config(libctx, configfile))) goto err; /* Check we have the expected provider available */ if (!TEST_true(OSSL_PROVIDER_available(libctx, modulename))) goto err; /* Check the default provider is not available */ if (strcmp(modulename, "default") != 0 && !TEST_false(OSSL_PROVIDER_available(libctx, "default"))) goto err; if (strcmp(modulename, "fips") == 0) is_fips = 1; cert = test_mk_file_path(certsdir, "servercert.pem"); if (cert == NULL) goto err; ccert = test_mk_file_path(certsdir, "ee-client-chain.pem"); if (ccert == NULL) goto err; cauthca = test_mk_file_path(certsdir, "root-cert.pem"); if (cauthca == NULL) goto err; privkey = test_mk_file_path(certsdir, "serverkey.pem"); if (privkey == NULL) goto err; cprivkey = test_mk_file_path(certsdir, "ee-key.pem"); if (privkey == NULL) goto err; ADD_ALL_TESTS(test_quic_write_read, 3); ADD_TEST(test_fin_only_blocking); ADD_TEST(test_ciphersuites); ADD_TEST(test_cipher_find); ADD_TEST(test_version); #if defined(DO_SSL_TRACE_TEST) ADD_TEST(test_ssl_trace); #endif ADD_TEST(test_quic_forbidden_apis_ctx); ADD_TEST(test_quic_forbidden_apis); ADD_TEST(test_quic_forbidden_options); ADD_ALL_TESTS(test_quic_set_fd, 3); ADD_TEST(test_bio_ssl); ADD_TEST(test_back_pressure); ADD_TEST(test_multiple_dgrams); ADD_ALL_TESTS(test_non_io_retry, 2); ADD_TEST(test_quic_psk); ADD_ALL_TESTS(test_client_auth, 3); ADD_ALL_TESTS(test_alpn, 2); ADD_ALL_TESTS(test_noisy_dgram, 2); ADD_TEST(test_bw_limit); ADD_TEST(test_get_shutdown); ADD_ALL_TESTS(test_tparam, OSSL_NELEM(tparam_tests)); ADD_TEST(test_session_cb); ADD_TEST(test_domain_flags); ADD_TEST(test_early_ticks); ADD_TEST(test_ssl_new_from_listener); #ifndef OPENSSL_NO_SSL_TRACE ADD_TEST(test_new_token); #endif ADD_TEST(test_server_method_with_ssl_new); ADD_TEST(test_ssl_accept_connection); ADD_TEST(test_ssl_set_verify); ADD_TEST(test_client_hello_retry); return 1; err: cleanup_tests(); return 0; } void cleanup_tests(void) { bio_f_noisy_dgram_filter_free(); bio_f_pkt_split_dgram_filter_free(); OPENSSL_free(cert); OPENSSL_free(privkey); OPENSSL_free(ccert); OPENSSL_free(cauthca); OPENSSL_free(cprivkey); OSSL_PROVIDER_unload(defctxnull); OSSL_LIB_CTX_free(libctx); } diff --git a/test/radix/terp.c b/test/radix/terp.c index 3c83fd9b18b0..41d3bdeb9fd4 100644 --- a/test/radix/terp.c +++ b/test/radix/terp.c @@ -1,882 +1,884 @@ /* * Copyright 2024-2025 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 "../testutil.h" #include "internal/numbers.h" /* UINT64_C */ #include "internal/time.h" /* OSSL_TIME */ static const char *cert_file, *key_file; /* * TERP - Test Executive Script Interpreter * ======================================== */ typedef struct gen_ctx_st GEN_CTX; typedef void (*script_gen_t)(GEN_CTX *ctx); typedef struct script_info_st { /* name: A symbolic name, like simple_conn. */ const char *name; /* desc: A short, one-line description. */ const char *desc; const char *file; int line; /* gen_func: The script generation function. */ script_gen_t gen_func; } SCRIPT_INFO; struct gen_ctx_st { SCRIPT_INFO *script_info; const char *cur_file; int error, cur_line; const char *first_error_msg, *first_error_file; int first_error_line; uint8_t *build_buf_beg, *build_buf_cur, *build_buf_end; }; static int GEN_CTX_init(GEN_CTX *ctx, SCRIPT_INFO *script_info) { ctx->script_info = script_info; ctx->error = 0; ctx->cur_file = NULL; ctx->cur_line = 0; ctx->first_error_msg = NULL; ctx->first_error_line = 0; ctx->build_buf_beg = NULL; ctx->build_buf_cur = NULL; ctx->build_buf_end = NULL; return 1; } static void GEN_CTX_cleanup(GEN_CTX *ctx) { OPENSSL_free(ctx->build_buf_beg); ctx->build_buf_beg = ctx->build_buf_cur = ctx->build_buf_end = NULL; } typedef struct terp_st TERP; #define F_RET_SPIN_AGAIN 2 #define F_RET_SKIP_REST 3 #define F_SPIN_AGAIN() \ do { \ ok = F_RET_SPIN_AGAIN; \ fctx->spin_again = 1; \ goto err; \ } while (0) #define F_SKIP_REST() \ do { \ ok = F_RET_SKIP_REST; \ fctx->skip_rest = 1; \ goto err; \ } while (0) typedef struct func_ctx_st { TERP *terp; /* * Set to 1 inside a user function if the function should spin again. * Cleared automatically after the user function returns. */ int spin_again; /* * Immediately exit script successfully. Useful for skipping. */ int skip_rest; } FUNC_CTX; static ossl_inline int TERP_stk_pop(TERP *terp, void *buf, size_t buf_len); #define TERP_STK_PUSH(terp, v) \ do { \ if (!TEST_true(TERP_stk_push((terp), &(v), sizeof(v)))) \ goto err; \ } while (0) #define TERP_STK_POP(terp, v) \ do { \ memset(&(v), 0, sizeof(v)); /* quiet warnings */ \ if (!TEST_true(TERP_stk_pop((terp), &(v), sizeof(v)))) \ goto err; \ } while (0) #define TERP_STK_POP2(terp, a, b) \ do { \ TERP_STK_POP((terp), (b)); \ TERP_STK_POP((terp), (a)); \ } while (0) #define F_PUSH(v) TERP_STK_PUSH(fctx->terp, (v)) #define F_POP(v) TERP_STK_POP (fctx->terp, (v)) #define F_POP2(a, b) TERP_STK_POP2(fctx->terp, (a), (b)) typedef int (*helper_func_t)(FUNC_CTX *fctx); #define DEF_FUNC(name) ossl_unused static int name(FUNC_CTX *fctx) #define DEF_SCRIPT(name, desc) \ static void script_gen_##name(GEN_CTX *ctx); \ static SCRIPT_INFO script_info_##name = { \ #name, desc, __FILE__, __LINE__, \ script_gen_##name \ }; \ static void script_gen_##name(GEN_CTX *ctx) enum { OPK_INVALID, OPK_END, OPK_PUSH_P, /* * This is exactly like PUSH_P, but the script dumper knows the pointer * points to a static NUL-terminated string and can therefore print it. */ OPK_PUSH_PZ, OPK_PUSH_U64, /* * Could use OPK_PUSH_U64 for this but it's annoying to have to avoid using * size_t in case it is a different size. */ OPK_PUSH_SIZE, OPK_FUNC, OPK_LABEL }; static void *openc_alloc_space(GEN_CTX *ctx, size_t num_bytes); #define DEF_ENCODER(name, type) \ static void name(GEN_CTX *ctx, type v) \ { \ void *dst = openc_alloc_space(ctx, sizeof(v)); \ if (dst == NULL) \ return; \ \ memcpy(dst, &v, sizeof(v)); \ } DEF_ENCODER(openc_u64, uint64_t) DEF_ENCODER(openc_size, size_t) DEF_ENCODER(openc_p, void *) DEF_ENCODER(openc_fp, helper_func_t) #define openc_opcode openc_u64 static void opgen_END(GEN_CTX *ctx) { openc_opcode(ctx, OPK_END); } static ossl_unused void opgen_PUSH_P(GEN_CTX *ctx, void *p) { openc_opcode(ctx, OPK_PUSH_P); openc_p(ctx, p); } static void opgen_PUSH_PZ(GEN_CTX *ctx, void *p) { openc_opcode(ctx, OPK_PUSH_PZ); openc_p(ctx, p); } static void opgen_PUSH_U64(GEN_CTX *ctx, uint64_t v) { openc_opcode(ctx, OPK_PUSH_U64); openc_u64(ctx, v); } ossl_unused static void opgen_PUSH_SIZE(GEN_CTX *ctx, size_t v) { openc_opcode(ctx, OPK_PUSH_SIZE); openc_size(ctx, v); } ossl_unused static void opgen_FUNC(GEN_CTX *ctx, helper_func_t f, const char *f_name) { openc_opcode(ctx, OPK_FUNC); openc_fp(ctx, f); openc_p(ctx, (void *)f_name); } ossl_unused static void opgen_LABEL(GEN_CTX *ctx, const char *name) { openc_opcode(ctx, OPK_LABEL); openc_p(ctx, (void *)name); } static void opgen_set_line(GEN_CTX *ctx, const char *file, int line) { ctx->cur_file = file; ctx->cur_line = line; } static ossl_unused void opgen_fail(GEN_CTX *ctx, const char *msg) { if (!ctx->error) { ctx->first_error_file = ctx->cur_file; ctx->first_error_line = ctx->cur_line; ctx->first_error_msg = msg; } ctx->error = 1; } #define OPGEN(n) (opgen_set_line(ctx, __FILE__, __LINE__), \ opgen_##n) #define OP_END() OPGEN(END) (ctx) #define OP_PUSH_P(v) OPGEN(PUSH_P) (ctx, (v)) #define OP_PUSH_PZ(v) OPGEN(PUSH_PZ) (ctx, (v)) #define OP_PUSH_U64(v) OPGEN(PUSH_U64) (ctx, (v)) #define OP_PUSH_SIZE(v) OPGEN(PUSH_SIZE) (ctx, (v)) #define OP_PUSH_BUFP(p, l) (OP_PUSH_P(p), OP_PUSH_SIZE(l)) #define OP_PUSH_BUF(v) OP_PUSH_BUFP(&(v), sizeof(v)) #define OP_PUSH_LREF(v) OPGEN(PUSH_LREF)(ctx, (lref)) #define OP_FUNC(f) OPGEN(FUNC) (ctx, (f), #f) #define OP_LABEL(name) OPGEN(LABEL) (ctx, (name)) #define GEN_FAIL(msg) OPGEN(fail) (ctx, (msg)) static void *openc_alloc_space(GEN_CTX *ctx, size_t num_bytes) { void *p; size_t cur_spare, old_size, new_size, off; cur_spare = ctx->build_buf_end - ctx->build_buf_cur; if (cur_spare < num_bytes) { off = ctx->build_buf_cur - ctx->build_buf_beg; old_size = ctx->build_buf_end - ctx->build_buf_beg; new_size = (old_size == 0) ? 1024 : old_size * 2; p = OPENSSL_realloc(ctx->build_buf_beg, new_size); if (!TEST_ptr(p)) return NULL; ctx->build_buf_beg = p; ctx->build_buf_cur = ctx->build_buf_beg + off; ctx->build_buf_end = ctx->build_buf_beg + new_size; } p = ctx->build_buf_cur; ctx->build_buf_cur += num_bytes; return p; } /* * Script Interpreter * ============================================================================ */ typedef struct gen_script_st { const uint8_t *buf; size_t buf_len; } GEN_SCRIPT; static int GEN_CTX_finish(GEN_CTX *ctx, GEN_SCRIPT *script) { script->buf = ctx->build_buf_beg; script->buf_len = ctx->build_buf_cur - ctx->build_buf_beg; ctx->build_buf_beg = ctx->build_buf_cur = ctx->build_buf_end = NULL; return 1; } static void GEN_SCRIPT_cleanup(GEN_SCRIPT *script) { OPENSSL_free((char *)script->buf); script->buf = NULL; script->buf_len = 0; } static int GEN_SCRIPT_init(GEN_SCRIPT *gen_script, SCRIPT_INFO *script_info) { int ok = 0; GEN_CTX gctx; if (!TEST_true(GEN_CTX_init(&gctx, script_info))) return 0; script_info->gen_func(&gctx); opgen_END(&gctx); if (!TEST_false(gctx.error)) goto err; if (!TEST_true(GEN_CTX_finish(&gctx, gen_script))) goto err; ok = 1; err: if (!ok) { if (gctx.error) TEST_error("script generation failed: %s (at %s:%d)", gctx.first_error_msg, gctx.first_error_file, gctx.first_error_line); GEN_CTX_cleanup(&gctx); } return ok; } typedef struct srdr_st { const uint8_t *beg, *cur, *end, *save_cur; } SRDR; static void SRDR_init(SRDR *rdr, const uint8_t *buf, size_t buf_len) { rdr->beg = rdr->cur = buf; rdr->end = rdr->beg + buf_len; rdr->save_cur = NULL; } static ossl_inline int SRDR_get_operand(SRDR *srdr, void *buf, size_t buf_len) { if (!TEST_size_t_ge(srdr->end - srdr->cur, buf_len)) return 0; /* malformed script */ memcpy(buf, srdr->cur, buf_len); srdr->cur += buf_len; return 1; } static ossl_inline void SRDR_save(SRDR *srdr) { srdr->save_cur = srdr->cur; } static ossl_inline void SRDR_restore(SRDR *srdr) { srdr->cur = srdr->save_cur; } #define GET_OPERAND(srdr, v) \ do { \ memset(&(v), 0, sizeof(v)); /* quiet uninitialized warn */ \ if (!TEST_true(SRDR_get_operand(srdr, &(v), sizeof(v)))) \ goto err; \ } while (0) static void print_opc(BIO *bio, size_t op_num, size_t offset, const char *name) { if (op_num != SIZE_MAX) BIO_printf(bio, "%3zu- %4zx>\t%-8s \t", op_num, offset, name); else BIO_printf(bio, " %4zx>\t%-8s \t", offset, name); } static int SRDR_print_one(SRDR *srdr, BIO *bio, size_t i, int *was_end) { int ok = 0; const uint8_t *opc_start; uint64_t opc; if (was_end != NULL) *was_end = 0; opc_start = srdr->cur; GET_OPERAND(srdr, opc); #define PRINT_OPC(name) print_opc(bio, i, (size_t)(opc_start - srdr->beg), #name) switch (opc) { case OPK_END: PRINT_OPC(END); opc_start = srdr->cur; if (was_end != NULL) *was_end = 1; break; case OPK_PUSH_P: { void *v; GET_OPERAND(srdr, v); PRINT_OPC(PUSH_P); BIO_printf(bio, "%20p", v); } break; case OPK_PUSH_PZ: { void *v; GET_OPERAND(srdr, v); PRINT_OPC(PUSH_PZ); if (v != NULL && strlen((const char *)v) == 1) BIO_printf(bio, "%20p (%s)", v, (const char *)v); else BIO_printf(bio, "%20p (\"%s\")", v, (const char *)v); } break; case OPK_PUSH_U64: { uint64_t v; GET_OPERAND(srdr, v); PRINT_OPC(PUSH_U64); BIO_printf(bio, "%#20llx (%llu)", (unsigned long long)v, (unsigned long long)v); } break; case OPK_PUSH_SIZE: { size_t v; GET_OPERAND(srdr, v); PRINT_OPC(PUSH_SIZE); BIO_printf(bio, "%#20llx (%llu)", (unsigned long long)v, (unsigned long long)v); } break; case OPK_FUNC: { helper_func_t v; void *f_name = NULL, *x = NULL; GET_OPERAND(srdr, v); GET_OPERAND(srdr, f_name); PRINT_OPC(FUNC); memcpy(&x, &v, sizeof(x) < sizeof(v) ? sizeof(x) : sizeof(v)); BIO_printf(bio, "%s", (const char *)f_name); } break; case OPK_LABEL: { void *l_name; GET_OPERAND(srdr, l_name); BIO_printf(bio, "\n%s:\n", (const char *)l_name); PRINT_OPC(LABEL); } break; default: TEST_error("unsupported opcode while printing: %llu", (unsigned long long)opc); goto err; } ok = 1; err: return ok; } static int GEN_SCRIPT_print(GEN_SCRIPT *gen_script, BIO *bio, const SCRIPT_INFO *script_info) { int ok = 0; size_t i; SRDR srdr_v, *srdr = &srdr_v; int was_end = 0; SRDR_init(srdr, gen_script->buf, gen_script->buf_len); if (script_info != NULL) { BIO_printf(bio, "\nGenerated script for '%s':\n", script_info->name); BIO_printf(bio, "\n--GENERATED-------------------------------------" "----------------------\n"); BIO_printf(bio, " # NAME:\n # %s\n", script_info->name); BIO_printf(bio, " # SOURCE:\n # %s:%d\n", script_info->file, script_info->line); BIO_printf(bio, " # DESCRIPTION:\n # %s\n", script_info->desc); } for (i = 0; !was_end; ++i) { BIO_printf(bio, "\n"); if (!TEST_true(SRDR_print_one(srdr, bio, i, &was_end))) goto err; } if (script_info != NULL) { const unsigned char *opc_start = srdr->cur; BIO_printf(bio, "\n"); PRINT_OPC(+++); BIO_printf(bio, "\n------------------------------------------------" "----------------------\n\n"); } ok = 1; err: return ok; } static void SCRIPT_INFO_print(SCRIPT_INFO *script_info, BIO *bio, int error, const char *msg) { if (error) TEST_error("%s: script '%s' (%s)", msg, script_info->name, script_info->desc); else TEST_info("%s: script '%s' (%s)", msg, script_info->name, script_info->desc); } typedef struct terp_config_st { BIO *debug_bio; OSSL_TIME (*now_cb)(void *arg); void *now_cb_arg; int (*per_op_cb)(TERP *terp, void *arg); void *per_op_cb_arg; OSSL_TIME max_execution_time; /* duration */ } TERP_CONFIG; #define TERP_DEFAULT_MAX_EXECUTION_TIME (ossl_ms2time(3000)) struct terp_st { TERP_CONFIG cfg; const SCRIPT_INFO *script_info; const GEN_SCRIPT *gen_script; SRDR srdr; uint8_t *stk_beg, *stk_cur, *stk_end, *stk_save_cur; FUNC_CTX fctx; uint64_t ops_executed; int log_execute; OSSL_TIME start_time, deadline_time; }; static int TERP_init(TERP *terp, const TERP_CONFIG *cfg, const SCRIPT_INFO *script_info, const GEN_SCRIPT *gen_script) { if (!TEST_true(cfg->now_cb != NULL)) return 0; terp->cfg = *cfg; terp->script_info = script_info; terp->gen_script = gen_script; terp->fctx.terp = terp; terp->fctx.spin_again = 0; terp->fctx.skip_rest = 0; terp->stk_beg = NULL; terp->stk_cur = NULL; terp->stk_end = NULL; terp->stk_save_cur = NULL; terp->ops_executed = 0; terp->log_execute = 1; if (ossl_time_is_zero(terp->cfg.max_execution_time)) terp->cfg.max_execution_time = TERP_DEFAULT_MAX_EXECUTION_TIME; return 1; } static void TERP_cleanup(TERP *terp) { if (terp->script_info == NULL) return; OPENSSL_free(terp->stk_beg); terp->stk_beg = terp->stk_cur = terp->stk_end = NULL; terp->script_info = NULL; } static int TERP_stk_ensure_capacity(TERP *terp, size_t spare) { uint8_t *p; size_t old_size, new_size, off; old_size = terp->stk_end - terp->stk_beg; if (old_size >= spare) return 1; off = terp->stk_end - terp->stk_cur; new_size = old_size != 0 ? old_size * 2 : 256; p = OPENSSL_realloc(terp->stk_beg, new_size); if (!TEST_ptr(p)) return 0; terp->stk_beg = p; terp->stk_end = terp->stk_beg + new_size; terp->stk_cur = terp->stk_end - off; return 1; } static ossl_inline int TERP_stk_push(TERP *terp, const void *buf, size_t buf_len) { if (!TEST_true(TERP_stk_ensure_capacity(terp, buf_len))) return 0; terp->stk_cur -= buf_len; memcpy(terp->stk_cur, buf, buf_len); return 1; } static ossl_inline int TERP_stk_pop(TERP *terp, void *buf, size_t buf_len) { if (!TEST_size_t_ge(terp->stk_end - terp->stk_cur, buf_len)) return 0; memcpy(buf, terp->stk_cur, buf_len); terp->stk_cur += buf_len; return 1; } static void TERP_print_stack(TERP *terp, BIO *bio, const char *header) { test_output_memory(header, terp->stk_cur, terp->stk_end - terp->stk_cur); BIO_printf(bio, " (%zu bytes)\n", (size_t)(terp->stk_end - terp->stk_cur)); BIO_printf(bio, "\n"); } #define TERP_GET_OPERAND(v) GET_OPERAND(&terp->srdr, (v)) #define TERP_SPIN_AGAIN() \ do { \ SRDR_restore(&terp->srdr); \ terp->stk_cur = terp->stk_save_cur; \ ++spin_count; \ goto spin_again; \ } while (0) static OSSL_TIME TERP_now(TERP *terp) { return terp->cfg.now_cb(terp->cfg.now_cb_arg); } static void TERP_log_spin(TERP *terp, size_t spin_count) { if (spin_count > 0) BIO_printf(terp->cfg.debug_bio, " \t\t(span %zu times)\n", spin_count); } static int TERP_execute(TERP *terp) { int ok = 0; uint64_t opc; size_t op_num = 0; int in_debug_output = 0; size_t spin_count = 0; BIO *debug_bio = terp->cfg.debug_bio; SRDR_init(&terp->srdr, terp->gen_script->buf, terp->gen_script->buf_len); terp->start_time = TERP_now(terp); terp->deadline_time = ossl_time_add(terp->start_time, terp->cfg.max_execution_time); for (;;) { if (terp->log_execute) { SRDR srdr_copy = terp->srdr; if (!in_debug_output) { BIO_printf(debug_bio, "\n--EXECUTION-----------------------------" "------------------------------\n"); in_debug_output = 1; } TERP_log_spin(terp, spin_count); if (!TEST_true(SRDR_print_one(&srdr_copy, debug_bio, SIZE_MAX, NULL))) goto err; BIO_printf(debug_bio, "\n"); } TERP_GET_OPERAND(opc); ++op_num; SRDR_save(&terp->srdr); terp->stk_save_cur = terp->stk_cur; spin_count = 0; ++terp->ops_executed; spin_again: if (ossl_time_compare(TERP_now(terp), terp->deadline_time) >= 0) { TEST_error("timed out while executing op %zu", op_num); if (terp->log_execute) TERP_log_spin(terp, spin_count); goto err; } if (terp->cfg.per_op_cb != NULL) if (!TEST_true(terp->cfg.per_op_cb(terp, terp->cfg.per_op_cb_arg))) { TEST_error("pre-operation processing failed at op %zu", op_num); if (terp->log_execute) TERP_log_spin(terp, spin_count); goto err; } switch (opc) { case OPK_END: goto stop; case OPK_PUSH_P: case OPK_PUSH_PZ: { void *v; TERP_GET_OPERAND(v); TERP_STK_PUSH(terp, v); } break; case OPK_PUSH_U64: { uint64_t v; TERP_GET_OPERAND(v); TERP_STK_PUSH(terp, v); } break; case OPK_PUSH_SIZE: { size_t v; TERP_GET_OPERAND(v); TERP_STK_PUSH(terp, v); } break; case OPK_LABEL: { const char *l_name; TERP_GET_OPERAND(l_name); /* no-op */ } break; case OPK_FUNC: { helper_func_t v; const void *f_name; int ret; TERP_GET_OPERAND(v); TERP_GET_OPERAND(f_name); if (!TEST_true(v != NULL)) goto err; ret = v(&terp->fctx); if (terp->fctx.skip_rest) { if (!TEST_int_eq(ret, F_RET_SKIP_REST)) goto err; if (terp->log_execute) BIO_printf(terp->cfg.debug_bio, " \t\t(skipping)\n"); terp->fctx.skip_rest = 0; goto stop; } else if (terp->fctx.spin_again) { if (!TEST_int_eq(ret, F_RET_SPIN_AGAIN)) goto err; terp->fctx.spin_again = 0; TERP_SPIN_AGAIN(); } else { if (!TEST_false(terp->fctx.spin_again)) goto err; if (ret != 1) { TEST_error("op %zu (FUNC %s) failed with return value %d", op_num, (const char *)f_name, ret); goto err; } } } break; default: TEST_error("unknown opcode: %llu", (unsigned long long)opc); goto err; } } stop: ok = 1; err: if (in_debug_output) BIO_printf(debug_bio, "----------------------------------------" "------------------------------\n"); if (!ok) { TEST_error("FAILED while executing script: %s at op %zu, error stack:", terp->script_info->name, op_num); ERR_print_errors(terp->cfg.debug_bio); BIO_printf(debug_bio, "\n"); } else if (ERR_peek_last_error() != 0) { TEST_info("WARNING: errors on error stack despite success:"); ERR_print_errors(terp->cfg.debug_bio); BIO_printf(debug_bio, "\n"); } return ok; } static int TERP_run(SCRIPT_INFO *script_info, TERP_CONFIG *cfg) { int ok = 0, have_terp = 0; TERP terp; GEN_SCRIPT gen_script = {0}; BIO *debug_bio = cfg->debug_bio; SCRIPT_INFO_print(script_info, debug_bio, /*error=*/0, "generating script"); /* Generate the script by calling the generator function. */ if (!TEST_true(GEN_SCRIPT_init(&gen_script, script_info))) { SCRIPT_INFO_print(script_info, debug_bio, /*error=*/1, "error while generating script"); goto err; } /* Output the script for debugging purposes. */ if (!TEST_true(GEN_SCRIPT_print(&gen_script, debug_bio, script_info))) { SCRIPT_INFO_print(script_info, debug_bio, /*error=*/1, "error while printing script"); goto err; } /* Execute the script. */ if (!TEST_true(TERP_init(&terp, cfg, script_info, &gen_script))) goto err; have_terp = 1; SCRIPT_INFO_print(script_info, debug_bio, /*error=*/0, "executing script"); if (!TERP_execute(&terp)) goto err; if (terp.stk_end - terp.stk_cur != 0) { TEST_error("stack not empty: %zu bytes left", (size_t)(terp.stk_end - terp.stk_cur)); goto err; } ok = 1; err: if (have_terp) { TERP_print_stack(&terp, debug_bio, "Final state of stack"); TERP_cleanup(&terp); } GEN_SCRIPT_cleanup(&gen_script); - BIO_printf(debug_bio, "Stats:\n Ops executed: %16llu\n\n", - (unsigned long long)terp.ops_executed); + if (have_terp) { + BIO_printf(debug_bio, "Stats:\n Ops executed: %16llu\n\n", + (unsigned long long)terp.ops_executed); + } SCRIPT_INFO_print(script_info, debug_bio, /*error=*/!ok, ok ? "completed" : "failed, exiting"); return ok; } #define SCRIPT(name) (&script_info_##name) #define USE(name) SCRIPT(name), diff --git a/test/recipes/03-test_fipsinstall.t b/test/recipes/03-test_fipsinstall.t index 1f9110ef600a..3dcbe67c6d55 100644 --- a/test/recipes/03-test_fipsinstall.t +++ b/test/recipes/03-test_fipsinstall.t @@ -1,517 +1,527 @@ #! /usr/bin/env perl # Copyright 2019-2025 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; use warnings; use File::Spec::Functions qw(:DEFAULT abs2rel); use File::Copy; use OpenSSL::Glob; use OpenSSL::Test qw/:DEFAULT srctop_dir srctop_file bldtop_dir bldtop_file/; use OpenSSL::Test::Utils; BEGIN { setup("test_fipsinstall"); } use lib srctop_dir('Configurations'); use lib bldtop_dir('.'); use platform; plan skip_all => "Test only supported in a fips build" if disabled("fips"); # Compatible options for pedantic FIPS compliance my @pedantic_okay = ( 'ems_check', 'no_drbg_truncated_digests', 'self_test_onload', 'signature_digest_check' ); # Incompatible options for pedantic FIPS compliance my @pedantic_fail = ( 'no_conditional_errors', 'no_security_checks', 'self_test_oninstall', 'no_pbkdf2_lower_bound_check' ); # Command line options my @commandline = ( ( 'ems_check', 'tls1-prf-ems-check' ), ( 'no_short_mac', 'no-short-mac' ), ( 'no_drbg_truncated_digests', 'drbg-no-trunc-md' ), ( 'signature_digest_check', 'signature-digest-check' ), ( 'hkdf_digest_check', 'hkdf-digest-check' ), ( 'tls13_kdf_digest_check', 'tls13-kdf-digest-check' ), ( 'tls1_prf_digest_check', 'tls1-prf-digest-check' ), ( 'sshkdf_digest_check', 'sshkdf-digest-check' ), ( 'sskdf_digest_check', 'sskdf-digest-check' ), ( 'x963kdf_digest_check', 'x963kdf-digest-check' ), ( 'dsa_sign_disabled', 'dsa-sign-disabled' ), ( 'tdes_encrypt_disabled', 'tdes-encrypt-disabled' ), ( 'rsa_pkcs15_pad_disabled', 'rsa-pkcs15-pad-disabled' ), ( 'rsa_pss_saltlen_check', 'rsa-pss-saltlen-check' ), ( 'rsa_sign_x931_disabled', 'rsa-sign-x931-pad-disabled' ), ( 'hkdf_key_check', 'hkdf-key-check' ), ( 'kbkdf_key_check', 'kbkdf-key-check' ), ( 'tls13_kdf_key_check', 'tls13-kdf-key-check' ), ( 'tls1_prf_key_check', 'tls1-prf-key-check' ), ( 'sshkdf_key_check', 'sshkdf-key-check' ), ( 'sskdf_key_check', 'sskdf-key-check' ), ( 'x963kdf_key_check', 'x963kdf-key-check' ), ( 'x942kdf_key_check', 'x942kdf-key-check' ) ); -plan tests => 40 + (scalar @pedantic_okay) + (scalar @pedantic_fail) +plan tests => 41 + (scalar @pedantic_okay) + (scalar @pedantic_fail) + 4 * (scalar @commandline); my $infile = bldtop_file('providers', platform->dso('fips')); my $fipskey = $ENV{FIPSKEY} // config('FIPSKEY') // '00'; my $provconf = srctop_file("test", "fips-and-base.cnf"); # Read in a text $infile and replace the regular expression in $srch with the # value in $repl and output to a new file $outfile. sub replace_line_file_internal { my ($infile, $srch, $repl, $outfile) = @_; my $msg; open(my $in, "<", $infile) or return 0; read($in, $msg, 1024); close $in; $msg =~ s/$srch/$repl/; open(my $fh, ">", $outfile) or return 0; print $fh $msg; close $fh; return 1; } # Read in the text input file 'fips.cnf' # and replace a single Key = Value line with a new value in $value. # OR remove the Key = Value line if the passed in $value is empty. # and then output a new file $outfile. # $key is the Key to find sub replace_line_file { my ($key, $value, $outfile) = @_; my $srch = qr/$key\s*=\s*\S*\n/; my $rep; if ($value eq "") { $rep = ""; } else { $rep = "$key = $value\n"; } return replace_line_file_internal('fips.cnf', $srch, $rep, $outfile); } # Read in the text input file 'test/fips.cnf' # and replace the .cnf file used in # .include fipsmodule.cnf with a new value in $value. # and then output a new file $outfile. # $key is the Key to find sub replace_parent_line_file { my ($value, $outfile) = @_; my $srch = qr/fipsmodule.cnf/; my $rep = "$value"; return replace_line_file_internal(srctop_file("test", 'fips.cnf'), $srch, $rep, $outfile); } # Check if the specified pattern occurs in the given file # Returns 1 if the pattern is found and 0 if not sub find_line_file { my ($key, $file) = @_; open(my $in, $file) or return -1; while (my $line = <$in>) { if ($line =~ /$key/) { close($in); return 1; } } close($in); return 0; } # fail if no module name ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', '-provider_name', 'fips', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect'])), "fipsinstall fail"); # fail to verify if the configuration file is missing ok(!run(app(['openssl', 'fipsinstall', '-in', 'dummy.tmp', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-verify'])), "fipsinstall verify fail"); # output a fips.cnf file containing mac data ok(run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect'])), "fipsinstall"); # verify the fips.cnf file ok(run(app(['openssl', 'fipsinstall', '-in', 'fips.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-verify'])), "fipsinstall verify"); # Test that default options for fipsinstall output the 'install-status' for # FIPS 140-2 providers. SKIP: { run(test(["fips_version_test", "-config", $provconf, "<3.1.0"]), capture => 1, statusvar => \my $exit); skip "Skipping FIPS 140-3 provider", 2 if !$exit; ok(find_line_file('install-mac = ', 'fips.cnf') == 1, 'FIPS 140-2 should output install-mac'); ok(find_line_file('install-status = INSTALL_SELF_TEST_KATS_RUN', 'fips.cnf') == 1, 'FIPS 140-2 should output install-status'); } # Skip Tests if POST is disabled SKIP: { skip "Skipping POST checks", 13 if disabled("fips-post"); ok(replace_line_file('module-mac', '', 'fips_no_module_mac.cnf') && !run(app(['openssl', 'fipsinstall', '-in', 'fips_no_module_mac.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:01", '-section_name', 'fips_sect', '-verify'])), "fipsinstall verify fail no module mac"); ok(replace_line_file('install-mac', '', 'fips_no_install_mac.cnf') && !run(app(['openssl', 'fipsinstall', '-in', 'fips_no_install_mac.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:01", '-section_name', 'fips_sect', '-verify'])), "fipsinstall verify fail no install indicator mac"); ok(replace_line_file('module-mac', '00:00:00:00:00:00', 'fips_bad_module_mac.cnf') && !run(app(['openssl', 'fipsinstall', '-in', 'fips_bad_module_mac.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:01", '-section_name', 'fips_sect', '-verify'])), "fipsinstall verify fail if invalid module integrity value"); ok(replace_line_file('install-mac', '00:00:00:00:00:00', 'fips_bad_install_mac.cnf') && !run(app(['openssl', 'fipsinstall', '-in', 'fips_bad_install_mac.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:01", '-section_name', 'fips_sect', '-verify'])), "fipsinstall verify fail if invalid install indicator integrity value"); ok(replace_line_file('install-status', 'INCORRECT_STATUS_STRING', 'fips_bad_indicator.cnf') && !run(app(['openssl', 'fipsinstall', '-in', 'fips_bad_indicator.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:01", '-section_name', 'fips_sect', '-verify'])), "fipsinstall verify fail if invalid install indicator status"); # fail to verify the fips.cnf file if a different key is used ok(!run(app(['openssl', 'fipsinstall', '-in', 'fips.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:01", '-section_name', 'fips_sect', '-verify'])), "fipsinstall verify fail bad key"); # fail to verify the fips.cnf file if a different mac digest is used ok(!run(app(['openssl', 'fipsinstall', '-in', 'fips.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA512', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-verify'])), "fipsinstall verify fail incorrect digest"); # corrupt the module hmac ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-corrupt_desc', 'HMAC'])), "fipsinstall fails when the module integrity is corrupted"); # corrupt the first digest ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips_fail.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-corrupt_desc', 'SHA2'])), "fipsinstall fails when the digest result is corrupted"); # corrupt another digest ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips_fail.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-corrupt_desc', 'SHA3'])), "fipsinstall fails when the digest result is corrupted"); # corrupt cipher encrypt test ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips_fail.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-corrupt_desc', 'AES_GCM'])), "fipsinstall fails when the AES_GCM result is corrupted"); # corrupt cipher decrypt test ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips_fail.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-corrupt_desc', 'AES_ECB_Decrypt'])), "fipsinstall fails when the AES_ECB result is corrupted"); # corrupt DRBG ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips_fail.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-corrupt_desc', 'CTR'])), "fipsinstall fails when the DRBG CTR result is corrupted"); } # corrupt a KAS test SKIP: { skip "Skipping KAS DH corruption test because of no dh in this build", 1 if disabled("dh") || disabled("fips-post"); ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-corrupt_desc', 'DH', '-corrupt_type', 'KAT_KA'])), "fipsinstall fails when the kas result is corrupted"); } # corrupt a Signature test - 140-3 requires a known answer test SKIP: { skip "Skipping Signature DSA corruption test because of no dsa in this build", 1 if disabled("dsa") || disabled("fips-post"); run(test(["fips_version_test", "-config", $provconf, ">=3.1.0"]), capture => 1, statusvar => \my $exit); skip "FIPS provider version is too old for KAT DSA signature test", 1 if !$exit; ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-self_test_oninstall', '-corrupt_desc', 'DSA', '-corrupt_type', 'KAT_Signature'])), "fipsinstall fails when the signature result is corrupted"); } # corrupt a Signature test - 140-2 allows a pairwise consistency test SKIP: { skip "Skipping Signature DSA corruption test because of no dsa in this build", 1 if disabled("dsa") || disabled("fips-post"); run(test(["fips_version_test", "-config", $provconf, "<3.1.0"]), capture => 1, statusvar => \my $exit); skip "FIPS provider version is too new for PCT DSA signature test", 1 if !$exit; ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-corrupt_desc', 'DSA', '-corrupt_type', 'PCT_Signature'])), "fipsinstall fails when the signature result is corrupted"); } # corrupt ML-KEM tests SKIP: { skip "Skipping ML_KEM corruption tests because of no ML-KEM in this build", 4 if disabled("ml-kem") || disabled("fips-post"); run(test(["fips_version_test", "-config", $provconf, ">=3.5.0"]), capture => 1, statusvar => \my $exit); skip "FIPS provider version doesn't support ML-KEM", 4 if !$exit; ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-corrupt_desc', 'ML-KEM', '-corrupt_type', 'KAT_AsymmetricKeyGeneration'])), "fipsinstall fails when the ML-KEM key generation result is corrupted"); ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-corrupt_desc', 'KEM_Encap', '-corrupt_type', 'KAT_KEM'])), "fipsinstall fails when the ML-KEM encapsulate result is corrupted"); ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-corrupt_desc', 'KEM_Decap', '-corrupt_type', 'KAT_KEM'])), "fipsinstall fails when the ML-KEM decapsulate result is corrupted"); ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-corrupt_desc', 'KEM_Decap_Reject', '-corrupt_type', 'KAT_KEM'])), "fipsinstall fails when the ML-KEM decapsulate implicit failure result is corrupted"); } +# corrupt an Asymmetric cipher test +SKIP: { + skip "Skipping Asymmetric RSA corruption test because of no rsa in this build", 1 + if disabled("rsa") || disabled("fips-post"); + ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', $infile, + '-corrupt_desc', 'RSA_Encrypt', + '-corrupt_type', 'KAT_AsymmetricCipher'])), + "fipsinstall fails when the asymmetric cipher result is corrupted"); +} + # 'local' ensures that this change is only done in this file. local $ENV{OPENSSL_CONF_INCLUDE} = abs2rel(curdir()); ok(replace_parent_line_file('fips.cnf', 'fips_parent.cnf') && run(app(['openssl', 'fipsinstall', '-config', 'fips_parent.cnf'])), "verify fips provider loads from a configuration file"); ok(replace_parent_line_file('fips_no_module_mac.cnf', 'fips_parent_no_module_mac.cnf') && !run(app(['openssl', 'fipsinstall', '-config', 'fips_parent_no_module_mac.cnf'])), "verify load config fail no module mac"); SKIP: { run(test(["fips_version_test", "-config", $provconf, "<3.1.0"]), capture => 1, statusvar => \my $exit); skip "FIPS provider version doesn't support self test indicator", 3 if !$exit; ok(replace_parent_line_file('fips_no_install_mac.cnf', 'fips_parent_no_install_mac.cnf') && !run(app(['openssl', 'fipsinstall', '-config', 'fips_parent_no_install_mac.cnf'])), "verify load config fail no install mac"); ok(replace_parent_line_file('fips_bad_indicator.cnf', 'fips_parent_bad_indicator.cnf') && !run(app(['openssl', 'fipsinstall', '-config', 'fips_parent_bad_indicator.cnf'])), "verify load config fail bad indicator"); ok(replace_parent_line_file('fips_bad_install_mac.cnf', 'fips_parent_bad_install_mac.cnf') && !run(app(['openssl', 'fipsinstall', '-config', 'fips_parent_bad_install_mac.cnf'])), "verify load config fail bad install mac"); } ok(replace_parent_line_file('fips_bad_module_mac.cnf', 'fips_parent_bad_module_mac.cnf') && !run(app(['openssl', 'fipsinstall', '-config', 'fips_parent_bad_module_mac.cnf'])), "verify load config fail bad module mac"); SKIP: { run(test(["fips_version_test", "-config", $provconf, "<3.1.0"]), capture => 1, statusvar => \my $exit); skip "FIPS provider version doesn't support self test indicator", 3 if !$exit; my $stconf = "fipsmodule_selftest.cnf"; ok(run(app(['openssl', 'fipsinstall', '-out', $stconf, '-module', $infile, '-self_test_onload'])), "fipsinstall config saved without self test indicator"); ok(!run(app(['openssl', 'fipsinstall', '-in', $stconf, '-module', $infile, '-verify'])), "fipsinstall config verify fails without self test indicator"); ok(run(app(['openssl', 'fipsinstall', '-in', $stconf, '-module', $infile, '-self_test_onload', '-verify'])), "fipsinstall config verify passes when self test indicator is not present"); } SKIP: { run(test(["fips_version_test", "-config", $provconf, ">=3.1.0"]), capture => 1, statusvar => \my $exit); skip "FIPS provider version can run self tests on install", 1 if !$exit; ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-self_test_oninstall', '-ems_check'])), "fipsinstall fails when attempting to run self tests on install"); } ok(find_line_file('drbg-no-trunc-md = 0', 'fips.cnf') == 1, 'fipsinstall defaults to not banning truncated digests with DRBGs'); ok(run(app(['openssl', 'fipsinstall', '-out', 'fips.cnf', '-module', $infile, '-provider_name', 'fips', '-mac_name', 'HMAC', '-macopt', 'digest:SHA256', '-macopt', "hexkey:$fipskey", '-section_name', 'fips_sect', '-no_drbg_truncated_digests'])), "fipsinstall knows about allowing truncated digests in DRBGs"); ok(find_line_file('drbg-no-trunc-md = 1', 'fips.cnf') == 1, 'fipsinstall will allow option for truncated digests with DRBGs'); ok(run(app(['openssl', 'fipsinstall', '-out', 'fips-pedantic.cnf', '-module', $infile, '-pedantic'])), "fipsinstall accepts -pedantic option"); foreach my $o (@pedantic_okay) { ok(run(app(['openssl', 'fipsinstall', '-out', "fips-${o}.cnf", '-module', $infile, '-pedantic', "-${o}"])), "fipsinstall accepts -${o} after -pedantic option"); } foreach my $o (@pedantic_fail) { ok(!run(app(['openssl', 'fipsinstall', '-out', 'fips_fail.cnf', '-module', $infile, '-pedantic', "-${o}"])), "fipsinstall disallows -${o} after -pedantic option"); } foreach my $cp (@commandline) { my $o = $commandline[0]; my $l = $commandline[1]; ok(find_line_file("${l} = 1", 'fips-pedantic.cnf') == 1, "fipsinstall enables ${l} with -pendantic option"); ok(find_line_file("${l} = 0", 'fips.cnf') == 1, "fipsinstall disables ${l} without -pendantic option"); ok(run(app(['openssl', 'fipsinstall', '-out', "fips-${o}.cnf", '-module', $infile, "-${o}"])), "fipsinstall accepts -${o} option"); ok(find_line_file("${l} = 1", "fips-${o}.cnf") == 1, "fipsinstall enables ${l} with -${o} option"); } diff --git a/test/recipes/25-test_verify.t b/test/recipes/25-test_verify.t index 271f499690bf..673c3d5f1772 100644 --- a/test/recipes/25-test_verify.t +++ b/test/recipes/25-test_verify.t @@ -1,623 +1,624 @@ #! /usr/bin/env perl # Copyright 2015-2025 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; use warnings; use Cwd qw(abs_path); use File::Spec::Functions qw/canonpath/; use File::Copy; use OpenSSL::Test qw/:DEFAULT srctop_file bldtop_dir ok_nofips with/; use OpenSSL::Test::Utils; setup("test_verify"); my @certspath = qw(test certs); sub verify { my ($cert, $purpose, $trusted, $untrusted, @opts) = @_; my @args = qw(openssl verify -auth_level 1); push(@args, "-purpose", $purpose) if $purpose ne ""; push(@args, @opts); for (@$trusted) { push(@args, "-trusted", srctop_file(@certspath, "$_.pem")) } for (@$untrusted) { push(@args, "-untrusted", srctop_file(@certspath, "$_.pem")) } push(@args, srctop_file(@certspath, "$cert.pem")); run(app([@args])); } plan tests => 203; # Canonical success ok(verify("ee-cert", "sslserver", ["root-cert"], ["ca-cert"]), "accept compat trust"); # Root CA variants ok(!verify("ee-cert", "sslserver", [qw(root-nonca)], [qw(ca-cert)]), "fail trusted non-ca root"); ok(!verify("ee-cert", "sslserver", [qw(nroot+serverAuth)], [qw(ca-cert)]), "fail server trust non-ca root"); ok(!verify("ee-cert", "sslserver", [qw(nroot+anyEKU)], [qw(ca-cert)]), "fail wildcard trust non-ca root"); ok(!verify("ee-cert", "sslserver", [qw(root-cert2)], [qw(ca-cert)]), "fail wrong root key"); ok(!verify("ee-cert", "sslserver", [qw(root-name2)], [qw(ca-cert)]), "fail wrong root DN"); # Critical extensions ok(verify("ee-cert-noncrit-unknown-ext", "", ["root-cert"], ["ca-cert"]), "accept non-critical unknown extension"); ok(!verify("ee-cert-crit-unknown-ext", "", ["root-cert"], ["ca-cert"]), "reject critical unknown extension"); ok(verify("ee-cert-ocsp-nocheck", "", ["root-cert"], ["ca-cert"]), "accept critical OCSP No Check"); # Explicit trust/purpose combinations # ok(verify("ee-cert", "sslserver", [qw(sroot-cert)], [qw(ca-cert)]), "accept server purpose"); ok(!verify("ee-cert", "sslserver", [qw(croot-cert)], [qw(ca-cert)]), "fail client purpose"); # beware, questionable non-standard EKU check on trust anchor ok(verify("ee-cert", "sslserver", [qw(root+serverAuth)], [qw(ca-cert)]), "accept server trust"); ok(verify("ee-cert", "sslserver", [qw(sroot+serverAuth)], [qw(ca-cert)]), "accept server trust with server purpose"); ok(verify("ee-cert", "sslserver", [qw(croot+serverAuth)], [qw(ca-cert)]), "accept server trust with client purpose"); # Wildcard trust ok(verify("ee-cert", "sslserver", [qw(root+anyEKU)], [qw(ca-cert)]), "accept wildcard trust"); ok(verify("ee-cert", "sslserver", [qw(sroot+anyEKU)], [qw(ca-cert)]), "accept wildcard trust with server purpose"); ok(verify("ee-cert", "sslserver", [qw(croot+anyEKU)], [qw(ca-cert)]), "accept wildcard trust with client purpose"); # Inapplicable mistrust ok(verify("ee-cert", "sslserver", [qw(root-clientAuth)], [qw(ca-cert)]), "accept client mistrust"); ok(verify("ee-cert", "sslserver", [qw(sroot-clientAuth)], [qw(ca-cert)]), "accept client mistrust with server purpose"); ok(!verify("ee-cert", "sslserver", [qw(croot-clientAuth)], [qw(ca-cert)]), "fail client mistrust with client purpose"); # beware, questionable non-standard EKU check on trust anchor # Inapplicable trust ok(!verify("ee-cert", "sslserver", [qw(root+clientAuth)], [qw(ca-cert)]), "fail client trust"); ok(!verify("ee-cert", "sslserver", [qw(sroot+clientAuth)], [qw(ca-cert)]), "fail client trust with server purpose"); ok(!verify("ee-cert", "sslserver", [qw(croot+clientAuth)], [qw(ca-cert)]), "fail client trust with client purpose"); # Server mistrust ok(!verify("ee-cert", "sslserver", [qw(root-serverAuth)], [qw(ca-cert)]), "fail rejected EKU"); ok(!verify("ee-cert", "sslserver", [qw(sroot-serverAuth)], [qw(ca-cert)]), "fail server mistrust with server purpose"); ok(!verify("ee-cert", "sslserver", [qw(croot-serverAuth)], [qw(ca-cert)]), "fail server mistrust with client purpose"); # Wildcard mistrust ok(!verify("ee-cert", "sslserver", [qw(root-anyEKU)], [qw(ca-cert)]), "fail wildcard mistrust"); ok(!verify("ee-cert", "sslserver", [qw(sroot-anyEKU)], [qw(ca-cert)]), "fail wildcard mistrust with server purpose"); ok(!verify("ee-cert", "sslserver", [qw(croot-anyEKU)], [qw(ca-cert)]), "fail wildcard mistrust with client purpose"); # Check that trusted-first is on by setting up paths to different roots # depending on whether the intermediate is the trusted or untrusted one. # ok(verify("ee-cert", "sslserver", [qw(root-serverAuth root-cert2 ca-root2)], [qw(ca-cert)]), "accept trusted-first path"); ok(verify("ee-cert", "sslserver", [qw(root-cert root2+serverAuth ca-root2)], [qw(ca-cert)]), "accept trusted-first path with server trust"); ok(!verify("ee-cert", "sslserver", [qw(root-cert root2-serverAuth ca-root2)], [qw(ca-cert)]), "fail trusted-first path with server mistrust"); ok(!verify("ee-cert", "sslserver", [qw(root-cert root2+clientAuth ca-root2)], [qw(ca-cert)]), "fail trusted-first path with client trust"); # CA variants ok(!verify("ee-cert", "sslserver", [qw(root-cert)], [qw(ca-nonca)]), "fail non-CA untrusted intermediate"); ok(!verify("ee-cert", "sslserver", [qw(root-cert)], [qw(ca-nonbc)]), "fail non-CA untrusted intermediate"); ok(!verify("ee-cert", "sslserver", [qw(root-cert ca-nonca)], []), "fail non-CA trust-store intermediate"); ok(!verify("ee-cert", "sslserver", [qw(root-cert ca-nonbc)], []), "fail non-CA trust-store intermediate"); ok(!verify("ee-cert", "sslserver", [qw(root-cert nca+serverAuth)], []), "fail non-CA server trust intermediate"); ok(!verify("ee-cert", "sslserver", [qw(root-cert nca+anyEKU)], []), "fail non-CA wildcard trust intermediate"); ok(!verify("ee-cert", "sslserver", [qw(root-cert)], [qw(ca-cert2)]), "fail wrong intermediate CA key"); ok(!verify("ee-cert", "sslserver", [qw(root-cert)], [qw(ca-name2)]), "fail wrong intermediate CA DN"); ok(!verify("ee-cert", "sslserver", [qw(root-cert)], [qw(ca-root2)]), "fail wrong intermediate CA issuer"); ok(!verify("ee-cert", "sslserver", [], [qw(ca-cert)], "-partial_chain"), "fail untrusted partial chain"); ok(verify("ee-cert", "sslserver", [qw(ca-cert)], [], "-partial_chain"), "accept trusted partial chain"); ok(!verify("ee-cert", "sslserver", [qw(ca-expired)], [], "-partial_chain"), "reject expired trusted partial chain"); # this check is beyond RFC 5280 ok(!verify("ee-cert", "sslserver", [qw(root-expired)], [qw(ca-cert)]), "reject expired trusted root"); # this check is beyond RFC 5280 ok(verify("ee-cert", "sslserver", [qw(sca-cert)], [], "-partial_chain"), "accept partial chain with server purpose"); ok(!verify("ee-cert", "sslserver", [qw(cca-cert)], [], "-partial_chain"), "fail partial chain with client purpose"); # beware, questionable non-standard EKU check on trust anchor ok(verify("ee-cert", "sslserver", [qw(ca+serverAuth)], [], "-partial_chain"), "accept server trust partial chain"); ok(verify("ee-cert", "sslserver", [qw(cca+serverAuth)], [], "-partial_chain"), "accept server trust client purpose partial chain"); ok(verify("ee-cert", "sslserver", [qw(ca-clientAuth)], [], "-partial_chain"), "accept client mistrust partial chain"); ok(verify("ee-cert", "sslserver", [qw(ca+anyEKU)], [], "-partial_chain"), "accept wildcard trust partial chain"); ok(!verify("ee-cert", "sslserver", [], [qw(ca+serverAuth)], "-partial_chain"), "fail untrusted partial issuer with ignored server trust"); ok(!verify("ee-cert", "sslserver", [qw(ca-serverAuth)], [], "-partial_chain"), "fail server mistrust partial chain"); ok(!verify("ee-cert", "sslserver", [qw(ca+clientAuth)], [], "-partial_chain"), "fail client trust partial chain"); ok(!verify("ee-cert", "sslserver", [qw(ca-anyEKU)], [], "-partial_chain"), "fail wildcard mistrust partial chain"); # We now test auxiliary trust even for intermediate trusted certs without # -partial_chain. Note that "-trusted_first" is now always on and cannot # be disabled. ok(verify("ee-cert", "sslserver", [qw(root-cert ca+serverAuth)], [qw(ca-cert)]), "accept server trust"); ok(verify("ee-cert", "sslserver", [qw(root-cert ca+anyEKU)], [qw(ca-cert)]), "accept wildcard trust"); ok(verify("ee-cert", "sslserver", [qw(root-cert sca-cert)], [qw(ca-cert)]), "accept server purpose"); ok(verify("ee-cert", "sslserver", [qw(root-cert sca+serverAuth)], [qw(ca-cert)]), "accept server trust and purpose"); ok(verify("ee-cert", "sslserver", [qw(root-cert sca+anyEKU)], [qw(ca-cert)]), "accept wildcard trust and server purpose"); ok(verify("ee-cert", "sslserver", [qw(root-cert sca-clientAuth)], [qw(ca-cert)]), "accept client mistrust and server purpose"); ok(verify("ee-cert", "sslserver", [qw(root-cert cca+serverAuth)], [qw(ca-cert)]), "accept server trust and client purpose"); ok(verify("ee-cert", "sslserver", [qw(root-cert cca+anyEKU)], [qw(ca-cert)]), "accept wildcard trust and client purpose"); ok(!verify("ee-cert", "sslserver", [qw(root-cert cca-cert)], [qw(ca-cert)]), "fail client purpose intermediate trusted"); # beware, questionable non-standard EKU check on trust anchor ok(!verify("ee-cert", "sslserver", [qw(root-cert ca-anyEKU)], [qw(ca-cert)]), "fail wildcard mistrust"); ok(!verify("ee-cert", "sslserver", [qw(root-cert ca-serverAuth)], [qw(ca-cert)]), "fail server mistrust"); ok(!verify("ee-cert", "sslserver", [qw(root-cert ca+clientAuth)], [qw(ca-cert)]), "fail client trust"); ok(!verify("ee-cert", "sslserver", [qw(root-cert sca+clientAuth)], [qw(ca-cert)]), "fail client trust and server purpose"); ok(!verify("ee-cert", "sslserver", [qw(root-cert cca+clientAuth)], [qw(ca-cert)]), "fail client trust and client purpose"); ok(!verify("ee-cert", "sslserver", [qw(root-cert cca-serverAuth)], [qw(ca-cert)]), "fail server mistrust and client purpose"); ok(!verify("ee-cert", "sslserver", [qw(root-cert cca-clientAuth)], [qw(ca-cert)]), "fail client mistrust and client purpose"); ok(!verify("ee-cert", "sslserver", [qw(root-cert sca-serverAuth)], [qw(ca-cert)]), "fail server mistrust and server purpose"); ok(!verify("ee-cert", "sslserver", [qw(root-cert sca-anyEKU)], [qw(ca-cert)]), "fail wildcard mistrust and server purpose"); ok(!verify("ee-cert", "sslserver", [qw(root-cert cca-anyEKU)], [qw(ca-cert)]), "fail wildcard mistrust and client purpose"); # EE variants ok(verify("ee-client", "sslclient", [qw(root-cert)], [qw(ca-cert)]), "accept client chain"); ok(!verify("ee-client", "sslserver", [qw(root-cert)], [qw(ca-cert)]), "fail server leaf purpose"); ok(!verify("ee-cert", "sslclient", [qw(root-cert)], [qw(ca-cert)]), "fail client leaf purpose"); ok(!verify("ee-cert2", "sslserver", [qw(root-cert)], [qw(ca-cert)]), "fail wrong intermediate CA key"); ok(!verify("ee-name2", "sslserver", [qw(root-cert)], [qw(ca-cert)]), "fail wrong intermediate CA DN"); ok(!verify("ee-expired", "sslserver", [qw(root-cert)], [qw(ca-cert)]), "fail expired leaf"); ok(verify("ee-cert", "sslserver", [qw(ee-cert)], [], "-partial_chain"), "accept last-resort direct leaf match"); ok(verify("ee-client", "sslclient", [qw(ee-client)], [], "-partial_chain"), "accept last-resort direct leaf match"); ok(!verify("ee-cert", "sslserver", [qw(ee-client)], [], "-partial_chain"), "fail last-resort direct leaf non-match"); ok(verify("ee-cert", "sslserver", [qw(ee+serverAuth)], [], "-partial_chain"), "accept direct match with server trust"); ok(!verify("ee-cert", "sslserver", [qw(ee-serverAuth)], [], "-partial_chain"), "fail direct match with server mistrust"); ok(verify("ee-client", "sslclient", [qw(ee+clientAuth)], [], "-partial_chain"), "accept direct match with client trust"); ok(!verify("ee-client", "sslclient", [qw(ee-clientAuth)], [], "-partial_chain"), "reject direct match with client mistrust"); ok(verify("ee-pathlen", "sslserver", [qw(root-cert)], [qw(ca-cert)]), "accept non-ca with pathlen:0 by default"); ok(!verify("ee-pathlen", "sslserver", [qw(root-cert)], [qw(ca-cert)], "-x509_strict"), "reject non-ca with pathlen:0 with strict flag"); # EE veaiants wrt timestamp signing ok(verify("ee-timestampsign-CABforum", "timestampsign", [qw(root-cert)], [qw(ca-cert)]), "accept timestampsign according to CAB forum"); ok(!verify("ee-timestampsign-CABforum-noncritxku", "timestampsign", [qw(root-cert)], [qw(ca-cert)]), "fail timestampsign according to CAB forum with extendedKeyUsage not critical"); ok(!verify("ee-timestampsign-CABforum-serverauth", "timestampsign", [qw(root-cert)], [qw(ca-cert)]), "fail timestampsign according to CAB forum with serverAuth"); ok(!verify("ee-timestampsign-CABforum-anyextkeyusage", "timestampsign", [qw(root-cert)], [qw(ca-cert)]), "fail timestampsign according to CAB forum with anyExtendedKeyUsage"); ok(!verify("ee-timestampsign-CABforum-crlsign", "timestampsign", [qw(root-cert)], [qw(ca-cert)]), "fail timestampsign according to CAB forum with cRLSign"); ok(!verify("ee-timestampsign-CABforum-keycertsign", "timestampsign", [qw(root-cert)], [qw(ca-cert)]), "fail timestampsign according to CAB forum with keyCertSign"); ok(verify("ee-timestampsign-rfc3161", "timestampsign", [qw(root-cert)], [qw(ca-cert)]), "accept timestampsign according to RFC 3161"); ok(!verify("ee-timestampsign-rfc3161-noncritxku", "timestampsign", [qw(root-cert)], [qw(ca-cert)]), "fail timestampsign according to RFC 3161 with extendedKeyUsage not critical"); ok(verify("ee-timestampsign-rfc3161-digsig", "timestampsign", [qw(root-cert)], [qw(ca-cert)]), "accept timestampsign according to RFC 3161 with digitalSignature"); # EE variants wrt code signing ok(verify("ee-codesign", "codesign", [qw(root-cert)], [qw(ca-cert)]), "accept codesign"); ok(!verify("ee-codesign-serverauth", "codesign", [qw(root-cert)], [qw(ca-cert)]), "fail codesign with additional serverAuth"); ok(!verify("ee-codesign-anyextkeyusage", "codesign", [qw(root-cert)], [qw(ca-cert)]), "fail codesign with additional anyExtendedKeyUsage"); ok(!verify("ee-codesign-crlsign", "codesign", [qw(root-cert)], [qw(ca-cert)]), "fail codesign with additional cRLSign"); ok(!verify("ee-codesign-keycertsign", "codesign", [qw(root-cert)], [qw(ca-cert)]), "fail codesign with additional keyCertSign"); ok(!verify("ee-codesign-noncritical", "codesign", [qw(root-cert)], [qw(ca-cert)]), "fail codesign without critical KU"); ok(!verify("ee-cert", "codesign", [qw(root-cert)], [qw(ca-cert)]), "fail sslserver as code sign"); ok(!verify("ee-client", "codesign", [qw(root-cert)], [qw(ca-cert)]), "fail sslclient as codesign"); ok(!verify("ee-timestampsign-CABforum", "codesign", [qw(root-cert)], [qw(ca-cert)]), "fail timestampsign according to CAB forum as codesign"); ok(!verify("ee-timestampsign-rfc3161", "codesign", [qw(root-cert)], [qw(ca-cert)]), "fail timestampsign according to RFC 3161 as codesign"); # Proxy certificates ok(!verify("pc1-cert", "sslclient", [qw(root-cert)], [qw(ee-client ca-cert)]), "fail to accept proxy cert without -allow_proxy_certs"); ok(verify("pc1-cert", "sslclient", [qw(root-cert)], [qw(ee-client ca-cert)], "-allow_proxy_certs"), "accept proxy cert 1"); ok(verify("pc2-cert", "sslclient", [qw(root-cert)], [qw(pc1-cert ee-client ca-cert)], "-allow_proxy_certs"), "accept proxy cert 2"); ok(!verify("bad-pc3-cert", "sslclient", [qw(root-cert)], [qw(pc1-cert ee-client ca-cert)], "-allow_proxy_certs"), "fail proxy cert with incorrect subject"); ok(!verify("bad-pc4-cert", "sslclient", [qw(root-cert)], [qw(pc1-cert ee-client ca-cert)], "-allow_proxy_certs"), "fail proxy cert with incorrect pathlen"); ok(verify("pc5-cert", "sslclient", [qw(root-cert)], [qw(pc1-cert ee-client ca-cert)], "-allow_proxy_certs"), "accept proxy cert missing proxy policy"); ok(!verify("pc6-cert", "sslclient", [qw(root-cert)], [qw(pc1-cert ee-client ca-cert)], "-allow_proxy_certs"), "failed proxy cert where last CN was added as a multivalue RDN component"); # Security level tests ok(verify("ee-cert", "", ["root-cert"], ["ca-cert"], "-auth_level", "2"), "accept RSA 2048 chain at auth level 2"); ok(!verify("ee-cert", "", ["root-cert"], ["ca-cert"], "-auth_level", "3"), "reject RSA 2048 root at auth level 3"); ok(verify("ee-cert", "", ["root-cert-768"], ["ca-cert-768i"], "-auth_level", "0"), "accept RSA 768 root at auth level 0"); ok(!verify("ee-cert", "", ["root-cert-768"], ["ca-cert-768i"]), "reject RSA 768 root at auth level 1"); ok(verify("ee-cert-768i", "", ["root-cert"], ["ca-cert-768"], "-auth_level", "0"), "accept RSA 768 intermediate at auth level 0"); ok(!verify("ee-cert-768i", "", ["root-cert"], ["ca-cert-768"]), "reject RSA 768 intermediate at auth level 1"); ok(verify("ee-cert-768", "", ["root-cert"], ["ca-cert"], "-auth_level", "0"), "accept RSA 768 leaf at auth level 0"); ok(!verify("ee-cert-768", "", ["root-cert"], ["ca-cert"]), "reject RSA 768 leaf at auth level 1"); # ok(verify("ee-cert", "", ["root-cert-md5"], ["ca-cert"], "-auth_level", "2"), "accept md5 self-signed TA at auth level 2"); ok(verify("ee-cert", "", ["ca-cert-md5-any"], [], "-auth_level", "2"), "accept md5 intermediate TA at auth level 2"); ok(verify("ee-cert", "", ["root-cert"], ["ca-cert-md5"], "-auth_level", "0"), "accept md5 intermediate at auth level 0"); ok(!verify("ee-cert", "", ["root-cert"], ["ca-cert-md5"]), "reject md5 intermediate at auth level 1"); ok(verify("ee-cert-md5", "", ["root-cert"], ["ca-cert"], "-auth_level", "0"), "accept md5 leaf at auth level 0"); ok(!verify("ee-cert-md5", "", ["root-cert"], ["ca-cert"]), "reject md5 leaf at auth level 1"); # Explicit vs named curve tests SKIP: { skip "EC is not supported by this OpenSSL build", 7 if disabled("ec"); ok(!verify("ee-cert-ec-explicit", "", ["root-cert"], ["ca-cert-ec-named"]), "reject explicit curve leaf with named curve intermediate"); ok(!verify("ee-cert-ec-named-explicit", "", ["root-cert"], ["ca-cert-ec-explicit"]), "reject named curve leaf with explicit curve intermediate"); ok(verify("ee-cert-ec-named-named", "", ["root-cert"], ["ca-cert-ec-named"]), "accept named curve leaf with named curve intermediate"); ok(verify("ee-cert-ec-sha3-224", "", ["root-cert"], ["ca-cert-ec-named"], ), "accept cert generated with EC and SHA3-224"); ok(verify("ee-cert-ec-sha3-256", "", ["root-cert"], ["ca-cert-ec-named"], ), "accept cert generated with EC and SHA3-256"); ok(verify("ee-cert-ec-sha3-384", "", ["root-cert"], ["ca-cert-ec-named"], ), "accept cert generated with EC and SHA3-384"); ok(verify("ee-cert-ec-sha3-512", "", ["root-cert"], ["ca-cert-ec-named"], ), "accept cert generated with EC and SHA3-512"); } # Same as above but with base provider used for decoding SKIP: { my $no_fips = disabled('fips') || ($ENV{NO_FIPS} // 0); my $provconf = srctop_file("test", "fips-and-base.cnf"); my $provpath = bldtop_dir("providers"); my @prov = ("-provider-path", $provpath); skip "EC is not supported or FIPS is disabled", 7 if disabled("ec") || $no_fips; $ENV{OPENSSL_CONF} = $provconf; ok(verify("ee-cert-ec-sha3-224", "", ["root-cert"], ["ca-cert-ec-named"], @prov), "accept cert generated with EC and SHA3-224 w/fips"); ok(verify("ee-cert-ec-sha3-256", "", ["root-cert"], ["ca-cert-ec-named"], @prov), "accept cert generated with EC and SHA3-256 w/fips"); ok(verify("ee-cert-ec-sha3-384", "", ["root-cert"], ["ca-cert-ec-named"], @prov), "accept cert generated with EC and SHA3-384 w/fips"); ok(verify("ee-cert-ec-sha3-512", "", ["root-cert"], ["ca-cert-ec-named"], @prov), "accept cert generated with EC and SHA3-512 w/fips"); delete $ENV{OPENSSL_CONF}; run(test(["fips_version_test", "-config", $provconf, ">3.0.0"]), capture => 1, statusvar => \my $exit); skip "FIPS provider version is too old", 3 if !$exit; $ENV{OPENSSL_CONF} = $provconf; ok(!verify("ee-cert-ec-explicit", "", ["root-cert"], ["ca-cert-ec-named"], @prov), "reject explicit curve leaf with named curve intermediate w/fips"); ok(!verify("ee-cert-ec-named-explicit", "", ["root-cert"], ["ca-cert-ec-explicit"], @prov), "reject named curve leaf with explicit curve intermediate w/fips"); ok(verify("ee-cert-ec-named-named", "", ["root-cert"], ["ca-cert-ec-named"], @prov), "accept named curve leaf with named curve intermediate w/fips"); delete $ENV{OPENSSL_CONF}; } # Depth tests, note the depth limit bounds the number of CA certificates # between the trust-anchor and the leaf, so, for example, with a root->ca->leaf # chain, depth = 1 is sufficient, but depth == 0 is not. # ok(verify("ee-cert", "", ["root-cert"], ["ca-cert"], "-verify_depth", "2"), "accept chain with verify_depth 2"); ok(verify("ee-cert", "", ["root-cert"], ["ca-cert"], "-verify_depth", "1"), "accept chain with verify_depth 1"); ok(!verify("ee-cert", "", ["root-cert"], ["ca-cert"], "-verify_depth", "0"), "reject chain with verify_depth 0"); ok(verify("ee-cert", "", ["ca-cert-md5-any"], [], "-verify_depth", "0"), "accept md5 intermediate TA with verify_depth 0"); # Name Constraints tests. ok(verify("alt1-cert", "", ["root-cert"], ["ncca1-cert"], ), "Name Constraints everything permitted"); ok(verify("alt2-cert", "", ["root-cert"], ["ncca2-cert"], ), "Name Constraints nothing excluded"); ok(verify("alt3-cert", "", ["root-cert"], ["ncca1-cert", "ncca3-cert"], ), "Name Constraints nested test all permitted"); ok(verify("goodcn1-cert", "", ["root-cert"], ["ncca1-cert"], ), "Name Constraints CNs permitted"); ok(verify("goodcn2-cert", "", ["root-cert"], ["ncca1-cert"], ), "Name Constraints CNs permitted - no SAN extension"); ok(!verify("badcn1-cert", "", ["root-cert"], ["ncca1-cert"], ), "Name Constraints CNs not permitted"); ok(!verify("badalt1-cert", "", ["root-cert"], ["ncca1-cert"], ), "Name Constraints hostname not permitted"); ok(!verify("badalt2-cert", "", ["root-cert"], ["ncca2-cert"], ), "Name Constraints hostname excluded"); ok(!verify("badalt3-cert", "", ["root-cert"], ["ncca1-cert"], ), "Name Constraints email address not permitted"); ok(!verify("badalt4-cert", "", ["root-cert"], ["ncca1-cert"], ), "Name Constraints subject email address not permitted"); ok(!verify("badalt5-cert", "", ["root-cert"], ["ncca1-cert"], ), "Name Constraints IP address not permitted"); ok(!verify("badalt6-cert", "", ["root-cert"], ["ncca1-cert"], ), "Name Constraints CN hostname not permitted"); ok(!verify("badalt7-cert", "", ["root-cert"], ["ncca1-cert"], ), "Name Constraints CN BMPSTRING hostname not permitted"); ok(!verify("badalt8-cert", "", ["root-cert"], ["ncca1-cert", "ncca3-cert"], ), "Name constraints nested DNS name not permitted 1"); ok(!verify("badalt9-cert", "", ["root-cert"], ["ncca1-cert", "ncca3-cert"], ), "Name constraints nested DNS name not permitted 2"); ok(!verify("badalt10-cert", "", ["root-cert"], ["ncca1-cert", "ncca3-cert"], ), "Name constraints nested DNS name excluded"); ok(!verify("bad-othername-cert", "", ["root-cert"], ["nccaothername-cert"], ), "CVE-2022-4203 type confusion test"); ok(verify("nc-uri-cert", "", ["root-cert"], ["ncca4-cert"], ), "Name constraints URI with userinfo"); #Check that we get the expected failure return code with({ exit_checker => sub { return shift == 2; } }, sub { ok(verify("bad-othername-namec", "", ["bad-othername-namec-inter"], [], "-partial_chain", "-attime", "1623060000"), "Name constraints bad othername name constraint"); }); ok(verify("ee-pss-sha1-cert", "", ["root-cert"], ["ca-cert"], "-auth_level", "0"), "Accept PSS signature using SHA1 at auth level 0"); ok(verify("ee-pss-sha256-cert", "", ["root-cert"], ["ca-cert"], ), "CA with PSS signature using SHA256"); ok(!verify("ee-pss-sha1-cert", "", ["root-cert"], ["ca-cert"], "-auth_level", "1"), "Reject PSS signature using SHA1 and auth level 1"); ok(verify("ee-pss-sha256-cert", "", ["root-cert"], ["ca-cert"], "-auth_level", "2"), "PSS signature using SHA256 and auth level 2"); ok(verify("ee-pss-cert", "", ["root-cert"], ["ca-pss-cert"], ), "CA PSS signature"); ok(!verify("ee-pss-wrong1.5-cert", "", ["root-cert"], ["ca-pss-cert"], ), "CA producing regular PKCS#1 v1.5 signature with PSA-PSS key"); ok(!verify("many-names1", "", ["many-constraints"], ["many-constraints"], ), "Too many names and constraints to check (1)"); ok(!verify("many-names2", "", ["many-constraints"], ["many-constraints"], ), "Too many names and constraints to check (2)"); ok(!verify("many-names3", "", ["many-constraints"], ["many-constraints"], ), "Too many names and constraints to check (3)"); ok(verify("some-names1", "", ["many-constraints"], ["many-constraints"], ), "Not too many names and constraints to check (1)"); ok(verify("some-names2", "", ["many-constraints"], ["many-constraints"], ), "Not too many names and constraints to check (2)"); ok(verify("some-names2", "", ["many-constraints"], ["many-constraints"], ), "Not too many names and constraints to check (3)"); ok(verify("root-cert-rsa2", "", ["root-cert-rsa2"], [], "-check_ss_sig"), "Public Key Algorithm rsa instead of rsaEncryption"); ok(verify("ee-self-signed", "", ["ee-self-signed"], [], "-attime", "1593565200"), "accept trusted self-signed EE cert excluding key usage keyCertSign"); ok(verify("ee-ss-with-keyCertSign", "", ["ee-ss-with-keyCertSign"], []), "accept trusted self-signed EE cert with key usage keyCertSign also when strict"); SKIP: { skip "Ed25519 is not supported by this OpenSSL build", 6 if disabled("ecx"); # ED25519 certificate from draft-ietf-curdle-pkix-04 ok(verify("ee-ed25519", "", ["root-ed25519"], []), "accept X25519 EE cert issued by trusted Ed25519 self-signed CA cert"); ok(!verify("ee-ed25519", "", ["root-ed25519"], [], "-x509_strict"), "reject X25519 EE cert in strict mode since AKID is missing"); ok(!verify("root-ed25519", "", ["ee-ed25519"], []), "fail Ed25519 CA and EE certs swapped"); ok(verify("root-ed25519", "", ["root-ed25519"], []), "accept trusted Ed25519 self-signed CA cert"); ok(!verify("ee-ed25519", "", ["ee-ed25519"], []), "fail trusted Ed25519-signed self-issued X25519 cert"); ok(verify("ee-ed25519", "", ["ee-ed25519"], [], "-partial_chain"), "accept last-resort direct leaf match Ed25519-signed self-issued cert"); } SKIP: { skip "SM2 is not supported by this OpenSSL build", 2 if disabled("sm2"); ok_nofips(verify("sm2", "", ["sm2-ca-cert"], [], "-vfyopt", "distid:1234567812345678"), "SM2 ID test"); ok_nofips(verify("sm2", "", ["sm2-ca-cert"], [], "-vfyopt", "hexdistid:31323334353637383132333435363738"), "SM2 hex ID test"); } # Mixed content tests my $cert_file = srctop_file('test', 'certs', 'root-cert.pem'); my $rsa_file = srctop_file('test', 'certs', 'key-pass-12345.pem'); SKIP: { my $certplusrsa_file = 'certplusrsa.pem'; my $certplusrsa; skip "Couldn't create certplusrsa.pem", 1 unless ( open $certplusrsa, '>', $certplusrsa_file and copy($cert_file, $certplusrsa) and copy($rsa_file, $certplusrsa) and close $certplusrsa ); ok(run(app([ qw(openssl verify -trusted), $certplusrsa_file, $cert_file ])), 'Mixed cert + key file test'); } SKIP: { my $rsapluscert_file = 'rsapluscert.pem'; my $rsapluscert; skip "Couldn't create rsapluscert.pem", 1 unless ( open $rsapluscert, '>', $rsapluscert_file and copy($rsa_file, $rsapluscert) and copy($cert_file, $rsapluscert) and close $rsapluscert ); ok(run(app([ qw(openssl verify -trusted), $rsapluscert_file, $cert_file ])), 'Mixed key + cert file test'); } # Certificate Policies ok(verify("ee-cert-policies", "", ["root-cert"], ["ca-pol-cert"], "-policy_check", "-policy", "1.3.6.1.4.1.16604.998855.1", "-explicit_policy"), "Certificate policy"); ok(!verify("ee-cert-policies-bad", "", ["root-cert"], ["ca-pol-cert"], "-policy_check", "-policy", "1.3.6.1.4.1.16604.998855.1", "-explicit_policy"), "Bad certificate policy"); # CAstore option my $rootcertname = "root-cert"; my $rootcert = srctop_file(@certspath, "${rootcertname}.pem"); sub vfy_root { verify($rootcertname, "", [], [], @_) } ok(vfy_root("-CAfile", $rootcert), "CAfile"); ok(vfy_root("-CAstore", $rootcert), "CAstore"); ok(vfy_root("-CAstore", $rootcert, "-CAfile", $rootcert), "CAfile and existing CAstore"); ok(!vfy_root("-CAstore", "non-existing", "-CAfile", $rootcert), "CAfile and non-existing CAstore"); + SKIP: { - skip "file names with colons aren't supported on Windows and VMS", 2 - if $^O =~ /^(MsWin32|VMS)$/; + skip "file names with colons aren't supported on Windows and VMS", 1 + if $^O =~ /^(MSWin32|VMS)$/; my $foo_file = "foo:cert.pem"; copy($rootcert, $foo_file); ok(vfy_root("-CAstore", $foo_file), "CAstore foo:file"); } my $foo_file = "cert.pem"; copy($rootcert, $foo_file); ok(vfy_root("-CAstore", $foo_file), "CAstore foo:file"); my $abs_cert = abs_path($rootcert); # Windows file: URIs should have a path part starting with a slash, i.e. # file://authority/C:/what/ever/foo.pem and file:///C:/what/ever/foo.pem # file://C:/what/ever/foo.pem is non-standard and may not be accepted. # See RFC 8089 for details. $abs_cert = "/" . $abs_cert if ($^O eq "MSWin32"); ok(vfy_root("-CAstore", "file://".$abs_cert), "CAstore file:///path"); ok(vfy_root("-CAstore", "file://localhost".$abs_cert), "CAstore file://localhost/path"); ok(!vfy_root("-CAstore", "file://otherhost".$abs_cert), "CAstore file://otherhost/path"); diff --git a/test/recipes/30-test_evp_data/evpkdf_krb5.txt b/test/recipes/30-test_evp_data/evpkdf_krb5.txt index d8f6aa72a175..e2de4754fa74 100644 --- a/test/recipes/30-test_evp_data/evpkdf_krb5.txt +++ b/test/recipes/30-test_evp_data/evpkdf_krb5.txt @@ -1,131 +1,139 @@ # -# Copyright 2001-2020 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 2001-2025 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 # Tests start with one of these keywords # Cipher Decrypt Derive Digest Encoding KDF MAC PBE # PrivPubKeyPair Sign Verify VerifyRecover # and continue until a blank line. Lines starting with a pound sign are ignored. Title = KRB5KDF tests (from RFC 3961 test vectors and krb5 sources) #RFC3961 KDF = KRB5KDF Ctrl.cipher = cipher:DES-EDE3-CBC Ctrl.hexkey = hexkey:dce06b1f64c857a11c3db57c51899b2cc1791008ce973b92 Ctrl.hexconstant = hexconstant:0000000155 Output = 925179d04591a79b5d3192c4a7e9c289b049c71f6ee604cd KDF = KRB5KDF Ctrl.cipher = cipher:DES-EDE3-CBC Ctrl.hexkey = hexkey:5e13d31c70ef765746578531cb51c15bf11ca82c97cee9f2 Ctrl.hexconstant = hexconstant:00000001aa Output = 9e58e5a146d9942a101c469845d67a20e3c4259ed913f207 KDF = KRB5KDF Ctrl.cipher = cipher:DES-EDE3-CBC Ctrl.hexkey = hexkey:98e6fd8a04a4b6859b75a176540b9752bad3ecd610a252bc Ctrl.hexconstant = hexconstant:0000000155 Output = 13fef80d763e94ec6d13fd2ca1d085070249dad39808eabf KDF = KRB5KDF Ctrl.cipher = cipher:DES-EDE3-CBC Ctrl.hexkey = hexkey:622aec25a2fe2cad7094680b7c64940280084c1a7cec92b5 Ctrl.hexconstant = hexconstant:00000001aa Output = f8dfbf04b097e6d9dc0702686bcb3489d91fd9a4516b703e KDF = KRB5KDF Ctrl.cipher = cipher:DES-EDE3-CBC Ctrl.hexkey = hexkey:d3f8298ccb166438dcb9b93ee5a7629286a491f838f802fb Ctrl.hexconstant = hexconstant:6b65726265726f73 Output = 2370da575d2a3da864cebfdc5204d56df779a7df43d9da43 KDF = KRB5KDF Ctrl.cipher = cipher:DES-EDE3-CBC Ctrl.hexkey = hexkey:c1081649ada74362e6a1459d01dfd30d67c2234c940704da Ctrl.hexconstant = hexconstant:0000000155 Output = 348057ec98fdc48016161c2a4c7a943e92ae492c989175f7 KDF = KRB5KDF Ctrl.cipher = cipher:DES-EDE3-CBC Ctrl.hexkey = hexkey:5d154af238f46713155719d55e2f1f790dd661f279a7917c Ctrl.hexconstant = hexconstant:00000001aa Output = a8808ac267dada3dcbe9a7c84626fbc761c294b01315e5c1 KDF = KRB5KDF Ctrl.cipher = cipher:DES-EDE3-CBC Ctrl.hexkey = hexkey:798562e049852f57dc8c343ba17f2ca1d97394efc8adc443 Ctrl.hexconstant = hexconstant:0000000155 Output = c813f88a3be3b334f75425ce9175fbe3c8493b89c8703b49 KDF = KRB5KDF Ctrl.cipher = cipher:DES-EDE3-CBC Ctrl.hexkey = hexkey:26dce334b545292f2feab9a8701a89a4b99eb9942cecd016 Ctrl.hexconstant = hexconstant:00000001aa Output = f48ffd6e83f83e7354e694fd252cf83bfe58f7d5ba37ec5d #Krb5 sources KDF = KRB5KDF Ctrl.cipher = cipher:DES-EDE3-CBC Ctrl.hexkey = hexkey:850BB51358548CD05E86768C313E3BFEF7511937DCF72C3E Ctrl.hexconstant = hexconstant:0000000299 Output = F78C496D16E6C2DAE0E0B6C24057A84C0426AEEF26FD6DCE KDF = KRB5KDF Ctrl.cipher = cipher:DES-EDE3-CBC Ctrl.hexkey = hexkey:850BB51358548CD05E86768C313E3BFEF7511937DCF72C3E Ctrl.hexconstant = hexconstant:00000002AA Output = 5B5723D0B634CB684C3EBA5264E9A70D52E683231AD3C4CE KDF = KRB5KDF Ctrl.cipher = cipher:DES-EDE3-CBC Ctrl.hexkey = hexkey:850BB51358548CD05E86768C313E3BFEF7511937DCF72C3E Ctrl.hexconstant = hexconstant:0000000255 Output = A77C94980E9B7345A81525C423A737CE67F4CD91B6B3DA45 KDF = KRB5KDF Ctrl.cipher = cipher:AES-128-CBC Ctrl.hexkey = hexkey:42263C6E89F4FC28B8DF68EE09799F15 Ctrl.hexconstant = hexconstant:0000000299 Output = 34280A382BC92769B2DA2F9EF066854B KDF = KRB5KDF Ctrl.cipher = cipher:AES-128-CBC Ctrl.hexkey = hexkey:42263C6E89F4FC28B8DF68EE09799F15 Ctrl.hexconstant = hexconstant:00000002AA Output = 5B14FC4E250E14DDF9DCCF1AF6674F53 KDF = KRB5KDF Ctrl.cipher = cipher:AES-128-CBC Ctrl.hexkey = hexkey:42263C6E89F4FC28B8DF68EE09799F15 Ctrl.hexconstant = hexconstant:0000000255 Output = 4ED31063621684F09AE8D89991AF3E8F KDF = KRB5KDF Ctrl.cipher = cipher:AES-256-CBC Ctrl.hexkey = hexkey:FE697B52BC0D3CE14432BA036A92E65BBB52280990A2FA27883998D72AF30161 Ctrl.hexconstant = hexconstant:0000000299 Output = BFAB388BDCB238E9F9C98D6A878304F04D30C82556375AC507A7A852790F4674 KDF = KRB5KDF Ctrl.cipher = cipher:AES-256-CBC Ctrl.hexkey = hexkey:FE697B52BC0D3CE14432BA036A92E65BBB52280990A2FA27883998D72AF30161 Ctrl.hexconstant = hexconstant:00000002AA Output = C7CFD9CD75FE793A586A542D87E0D1396F1134A104BB1A9190B8C90ADA3DDF37 KDF = KRB5KDF Ctrl.cipher = cipher:AES-256-CBC Ctrl.hexkey = hexkey:FE697B52BC0D3CE14432BA036A92E65BBB52280990A2FA27883998D72AF30161 Ctrl.hexconstant = hexconstant:0000000255 Output = 97151B4C76945063E2EB0529DC067D97D7BBA90776D8126D91F34F3101AEA8BA #Same as the first but with no "fixup" KDF = KRB5KDF Ctrl.cipher = cipher:DES-EDE3-CBC Ctrl.hexkey = hexkey:dce06b1f64c857a11c3db57c51899b2cc1791008ce973b92 Ctrl.hexconstant = hexconstant:0000000155 Output = 935079d14490a75c3093c4a6e8c3b049c71e6ee705 + +#Erroneous key size for the cipher as XTS has double key size +KDF = KRB5KDF +Ctrl.cipher = cipher:AES-256-XTS +Ctrl.hexkey = hexkey:FE697B52BC0D3CE14432BA036A92E65BBB52280990A2FA27883998D72AF30161 +Ctrl.hexconstant = hexconstant:0000000255 +Output = 97151B4C76945063E2EB0529DC067D97D7BBA90776D8126D91F34F3101AEA8BA +Result = KDF_DERIVE_ERROR diff --git a/test/recipes/30-test_evp_data/evppkey_rsa_sigalg.txt b/test/recipes/30-test_evp_data/evppkey_rsa_sigalg.txt index 5083cc2bde24..f258700670ab 100644 --- a/test/recipes/30-test_evp_data/evppkey_rsa_sigalg.txt +++ b/test/recipes/30-test_evp_data/evppkey_rsa_sigalg.txt @@ -1,189 +1,189 @@ # -# Copyright 2001-2024 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 2001-2025 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 # Tests start with one of these keywords # Cipher Decrypt Derive Digest Encoding KDF MAC PBE # PrivPubKeyPair Sign Verify VerifyRecover # and continue until a blank line. Lines starting with a pound sign are ignored. # The keyword Availablein must appear before the test name if needed. # Private keys used for PKEY operations. # RSA 2048 bit key. PrivateKey = RSA-2048 -----BEGIN PRIVATE KEY----- MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDNAIHqeyrh6gbV n3xz2f+5SglhXC5Lp8Y2zvCN01M+wxhVJbAVx2m5mnfWclv5w1Mqm25fZifV+4UW B2jT3anL01l0URcX3D0wnS/EfuQfl+Mq23+d2GShxHZ6Zm7NcbwarPXnUX9LOFlP 6psF5C1a2pkSAIAT5FMWpNm7jtCGuI0odYusr5ItRqhotIXSOcm66w4rZFknEPQr LR6gpLSALAvsqzKPimiwBzvbVG/uqYCdKEmRKzkMFTK8finHZY+BdfrkbzQzL/h7 yrPkBkm5hXeGnaDqcYNT8HInVIhpE2SHYNEivmduD8SD3SD/wxvalqMZZsmqLnWt A95H4cRPAgMBAAECggEAYCl6x5kbFnoG1rJHWLjL4gi+ubLZ7Jc4vYD5Ci41AF3X ziktnim6iFvTFv7x8gkTvArJDWsICLJBTYIQREHYYkozzgIzyPeApIs3Wv8C12cS IopwJITbP56+zM+77hcJ26GCgA2Unp5CFuC/81WDiPi9kNo3Oh2CdD7D+90UJ/0W glplejFpEuhpU2URfKL4RckJQF/KxV+JX8FdIDhsJu54yemQdQKaF4psHkzwwgDo qc+yfp0Vb4bmwq3CKxqEoc1cpbJ5CHXXlAfISzUjlcuBzD/tW7BDtp7eDAcgRVAC XO6MX0QBcLYSC7SOD3R7zY9SIRCFDfBDxCjf0YcFMQKBgQD2+WG0fLwDXTrt68fe hQqVa2Xs25z2B2QGPxWqSFU8WNly/mZ1BW413f3De/O58vYi7icTNyVoScm+8hdv 6PfD+LuRujdN1TuvPeyBTSvewQwf3IjN0Wh28mse36PwlBl+301C/x+ylxEDuJjK hZxCcocIaoQqtBC7ac8tNa9r4wKBgQDUfnJKf/QQSLJwwlJKQQGHi3MVm7c9PbwY eyIOY1s1NPluJDoYTZP4YLa/u2txwe2aHh9FhYMCPDAelqaSwaCLU9DsnKkQEA2A RR47fcagG6xK7O+N95iEa8I1oIy7os9MBoBMwRIZ6VYIxxTj8UMNSR+tu6MqV1Gg T5d0WDTJpQKBgCHyRSu5uV39AoyRS/eZ8cp36JqV1Q08FtOE+EVfi9evnrPfo9WR 2YQt7yNfdjCo5IwIj/ZkLhAXlFNakz4el2+oUJ/HKLLaDEoaCNf883q6rh/zABrK HcG7sF2d/7qhoJ9/se7zgjfZ68zHIrkzhDbd5xGREnmMJoCcGo3sQyBhAoGAH3UQ qmLC2N5KPFMoJ4H0HgLQ6LQCrnhDLkScSBEBYaEUA/AtAYgKjcyTgVLXlyGkcRpg esRHHr+WSBD5W+R6ReYEmeKfTJdzyDdzQE9gZjdyjC0DUbsDwybIu3OnIef6VEDq IXK7oUZfzDDcsNn4mTDoFaoff5cpqFfgDgM43VkCgYBNHw11b+d+AQmaZS9QqIt7 aF3FvwCYHV0jdv0Mb+Kc1bY4c0R5MFpzrTwVmdOerjuuA1+9b+0Hwo3nBZM4eaBu SOamA2hu2OJWCl9q8fLCT69KqWDjghhvFe7c6aJJGucwaA3Uz3eLcPqoaCarMiNH fMkTd7GabVourqIZdgvu1Q== -----END PRIVATE KEY----- # Corresponding public key PublicKey = RSA-2048-PUBLIC -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzQCB6nsq4eoG1Z98c9n/ uUoJYVwuS6fGNs7wjdNTPsMYVSWwFcdpuZp31nJb+cNTKptuX2Yn1fuFFgdo092p y9NZdFEXF9w9MJ0vxH7kH5fjKtt/ndhkocR2emZuzXG8Gqz151F/SzhZT+qbBeQt WtqZEgCAE+RTFqTZu47QhriNKHWLrK+SLUaoaLSF0jnJuusOK2RZJxD0Ky0eoKS0 gCwL7Ksyj4posAc721Rv7qmAnShJkSs5DBUyvH4px2WPgXX65G80My/4e8qz5AZJ uYV3hp2g6nGDU/ByJ1SIaRNkh2DRIr5nbg/Eg90g/8Mb2pajGWbJqi51rQPeR+HE TwIDAQAB -----END PUBLIC KEY----- PrivPubKeyPair = RSA-2048:RSA-2048-PUBLIC Title = RSA tests with EVP_PKEY_sign, EVP_PKEY_verify, EVP_PKEY_verify_recover # Demonstrate the possibility to use the RSA (not RSA-SHA1) signature # implementation with EVP_PKEY_sign_init_ex2() the same way as with # EVP_PKEY_sign_init_ex(). Availablein = default Sign = RSA:RSA-2048 Ctrl = digest:SHA1 Input = "0123456789ABCDEF1234" Output = c09d402423cbf233d26cae21f954547bc43fe80fd41360a0336cfdbe9aedad05bef6fd2eaee6cd60089a52482d4809a238149520df3bdde4cb9e23d9307b05c0a6f327052325a29adf2cc95b66523be7024e2a585c3d4db15dfbe146efe0ecdc0402e33fe5d40324ee96c5c3edd374a15cdc0f5d84aa243c0f07e188c6518fbfceae158a9943be398e31097da81b62074f626eff738be6160741d5a26957a482b3251fd85d8df78b98148459de10aa93305dbb4a5230aa1da291a9b0e481918f99b7638d72bb687f97661d304ae145d64a474437a4ef39d7b8059332ddeb07e92bf6e0e3acaf8afedc93795e4511737ec1e7aab6d5bc9466afc950c1c17b48ad Availablein = default Sign = RSA-SHA1:RSA-2048 Input = "0123456789ABCDEF1234" Output = c09d402423cbf233d26cae21f954547bc43fe80fd41360a0336cfdbe9aedad05bef6fd2eaee6cd60089a52482d4809a238149520df3bdde4cb9e23d9307b05c0a6f327052325a29adf2cc95b66523be7024e2a585c3d4db15dfbe146efe0ecdc0402e33fe5d40324ee96c5c3edd374a15cdc0f5d84aa243c0f07e188c6518fbfceae158a9943be398e31097da81b62074f626eff738be6160741d5a26957a482b3251fd85d8df78b98148459de10aa93305dbb4a5230aa1da291a9b0e481918f99b7638d72bb687f97661d304ae145d64a474437a4ef39d7b8059332ddeb07e92bf6e0e3acaf8afedc93795e4511737ec1e7aab6d5bc9466afc950c1c17b48ad # Digest too long Availablein = default Sign = RSA-SHA1:RSA-2048 Input = "0123456789ABCDEF12345" Output = 00 Result = KEYOP_ERROR # Digest too short Availablein = default Sign = RSA-SHA1:RSA-2048 Input = "0123456789ABCDEF12345" Output = 00 Result = KEYOP_ERROR Availablein = default VerifyRecover = RSA-SHA1:RSA-2048 Input = 49525db4d44c755e560cba980b1d85ea604b0e077fcadd4ba44072a3487bbddb835016200a7d8739cce2dc3223d9c20cbdd25059ab02277f1f21318efd18e21038ec89aa9d40680987129e8b41ba33bceb86518bdf47268b921cce2037acabca6575d832499538d6f40cdba0d40bd7f4d8ea6ca6e2eec87f294efc971407857f5d7db09f6a7b31e301f571c6d82a5e3d08d2bb3a36e673d28b910f5bec57f0fcc4d968fd7c94d0b9226dec17f5192ad8b42bcab6f26e1bea1fdc3b958199acb00f14ebcb2a352f3afcedd4c09000128a603bbeb9696dea13040445253972d46237a25c7845e3b464e6984c2348ea1f1210a9ff0b00d2d72b50db00c009bb39f9 Result = KEYOP_ERROR # Truncated digest [copy from evppkey_rsa_common.txt] FIPSversion = >= 3.4.0 Sign = RSA-SHA512-224:RSA-2048 Input = "0123456789ABCDEF123456789ABC" Output = 5f720e9488139bb21e1c2f027fd5ce5993e6d31c5a8faaee833487b3a944d66891178868ace8070cad3ee2ffbe54aa4885a15fd1a7cc5166970fe1fd8c0423e72bd3e3b56fc4a53ed80aaaeca42497f0ec3c62113edc05cd006608f5eef7ce3ad4cba1069f68731dd28a524a1f93fcdc5547112d48d45586dd943ba0d443be9635720d8a61697c54c96627f0d85c5fbeaa3b4af86a65cf2fc3800dd5de34c046985f25d0efc0bb6edccc1d08b3a4fb9c8faffe181c7e68b31e374ad1440a4a664eec9ca0dc53a9d2f5bc7d9940d866f64201bcbc63612754df45727ea24b531d7de83d1bb707444859fa35521320c33bf6f4dbeb6fb56e653adbf7af15843f17 FIPSversion = >= 3.4.0 Verify = RSA-SHA512-224:RSA-2048 Input = "0123456789ABCDEF123456789ABC" Output = 5f720e9488139bb21e1c2f027fd5ce5993e6d31c5a8faaee833487b3a944d66891178868ace8070cad3ee2ffbe54aa4885a15fd1a7cc5166970fe1fd8c0423e72bd3e3b56fc4a53ed80aaaeca42497f0ec3c62113edc05cd006608f5eef7ce3ad4cba1069f68731dd28a524a1f93fcdc5547112d48d45586dd943ba0d443be9635720d8a61697c54c96627f0d85c5fbeaa3b4af86a65cf2fc3800dd5de34c046985f25d0efc0bb6edccc1d08b3a4fb9c8faffe181c7e68b31e374ad1440a4a664eec9ca0dc53a9d2f5bc7d9940d866f64201bcbc63612754df45727ea24b531d7de83d1bb707444859fa35521320c33bf6f4dbeb6fb56e653adbf7af15843f17 Title = RSA with EVP_PKEY_sign_message, EVP_PKEY_verify_message Availablein = default Sign-Message = RSA-SHA1:RSA-2048 Input = "Hello World" Output = 3da3ca2bdd1b23a231b0e3c49d95d5959f9398c27a1e534c7e6baf1d2682304d3b6b229385b1edf483f5ef6f9b35bf10c519a302bb2f79c564e1a59ba71aa2fa36df96c942c43e8d9bd4702b5f61c12a078ae2b34d0de221fc8f9f936b79a67c89d11ba5da8c63a1370d0e824c6b661123e9b58b143ff533cf362cbdad70e65b419a6d45723bf22db3c76bb8f5337c5c5c93cb6f38b30d0c835b54c23405ca4217dd0b755f3712ebad285d9e0c02655f6ce5ce6fed78f3c81843de325f628055eef57f280dee0c3170050137ee599b9ab7f2b5d3c5f831777ea05a5eb097c70bad1a7214dadae12d7960bb9425390c7d25a79985e1e3c28ad422ff93c808f4b5 FIPSversion = >= 3.4.0 Sign-Message = RSA-SHA256:RSA-2048 Input = "Hello World" Output = ba8c24b86f18633767ed1778ef12d283a508d0bef32dd50b4a67cbd6b75df0f4ef6e69bfafbc809b01b93ab34aad9a33908644efca6eca04db1afda1016d1c1603183d2263597cf85ce5b7acd6a4872cbcc401b90b221d85aa0a2d0e1f159fc0843e0a55c47dc108c3f207d000e954605fabbb8c938050f280e29653aa1438109d02e53dfbdcb8cb9b46d372dd39ba7317a3f4c0020dba1ddd247b3d58addb1df7208785a62a8e3e4372c1fa6d24a17cd6413f7f5c046ba40a881c21875fde848b3b56fea7264430eca15b27c5c3b72fedcbcc124f8d939ffc11e6d3172c7eb491d378902093fcc3bf3a2835a1fcfabf457c13abf7b37f08595ed72332e27034 # As there dont seem to be test vectors for these - they were just generated # to verify that all digests are supported. # # The following can easily be verified manually with this or similar # command, provided that the RSA-2048 private key is stored in key.pem, # and that {hashname} is replaced with the actual hash name: # # echo -n 'Hello World' | openssl dgst -hex -sign key.pem -{hashname} # # That command uses the EVP_DigestSign API. Title = Test RSA with different digests FIPSversion = >= 3.4.0 Sign-Message = RSA-SHA224:RSA-2048 Input = "Hello World" Output = 4bae2cf892733233985102eb7117303e49994a8a97b3de64597c33f15a689502ba4dcea20f0ada460b262bd0c92db23dd090453f95debbfd7a835b51d1923ede76f4f66ba04d9ba0715b333a747c8d469283af653f286a307a3c46cd91f51ca2d597f9d3951fc068ff3ed45ba6b3540801159c7c890a252183de9e4aeb0512eb9ae681ac1d436c9efef9f265dcdf64ce67dce73d8a88bcb0008211bc6cd5493822818bfc208b8737ae38874184f834301de26e537694cfdc0abaccc2702820ee58cbba243aac685681329705999f4d77e596615293eb642ec450f149caabfab55092fc0315ec4157d322813ba9790c0f46c6805b8e1c0f21b6211c3529e6d7cc FIPSversion = >= 3.4.0 Sign-Message = RSA-SHA384:RSA-2048 Input = "Hello World" Output = 041348caa7ffaa7dce1ac67567c408967a1736dd44ff73076570a63c4c7128ff09f716918b81fdfaa160368bc8b85c23466f8c0d4172da880386b75065f541c0fb6c9355a1731532ebab9cf5026cafe03a790bc1698586fbdff5f6e8f1a7148b07f1f895a99d0f041b8b36d8ffdd5e77ba36e5177610e0825ba78594f95826dabdc95f682da04edf0d133c55e78fa386dea9dbc1cf748e768e9116976476e75a84b5510d869beac9a1a9ffc579a28629154b24ee9df8d51fee479f4dca5646a2032c27206ad30f4937fc096c41362562bee74562132a4f471bb4b4c76e774be0e9eca9412809665ab13951d3699b3a7ccb6714a0f070345f6f3e037bd0f8ae52 FIPSversion = >= 3.4.0 Sign-Message = RSA-SHA512:RSA-2048 Input = "Hello World" Output = 32e1f87fcd81a9d5a9f988087cdb3931fe0b12197d501b9c958cc1614a236e71a00ee7c96f7d5b3ae5ae3f11e40df5d06b0a818ee2a573aa1459f7f14dc22ca0b0b0ad2d47f4ab9e479baa084973b69f74f691ee700af102aceaf788e513f0e942a862bc6884ef1efb993b11d2ebd95139c61c37f8eac3edd94a4d8a358842f17da6d2971b8141a70097a1de569751eb4533e27880206fb8f8e1ac995688ca6facc85ed116becea9d3c4d0e96b2cb4b422b21c81328a335441d897c7deebf0f605ef086cfc5d81d1ab30ac04f674993511b142ea7ad43a8d3b7b1d2d26ce4a93413b690afdb1718408379fbd002a3c569bf11f0c10ce7cb46e257ce6b62ef62b FIPSversion = >= 3.4.0 Sign-Message = RSA-SHA512-224:RSA-2048 Input = "Hello World" Output = 8f20f0f2389408cfb7f4b47c299ca610c34a2ad20664378530ecf977c3243ce5f01c71296d2101dc962853a27f64a228eea92fee05780be31cdd7fe648d39f136de1dd857609d0d54d0de52c5cdf09d95986d808d1c92dcb3e8e96848af788c959927196316fcc56b884d34711a2a947b7e806caf7a2b05314f0c726b5e083baa0b341ac6515529bf6b3a7098a635c865e8d4b05af68fb3e893feb12ac7c4d667e1233f2e39449c285d4ad2a809e687f68ef66daf710e7d21e97833372c251bc0b45bc79c8bfe4087f16662875c2fc91a02d11078556a2b3232617406fbd947b9d95c193742ac4bb1858934ed7288cd0327c678b5295c682a4d2ba91d8fafae7 FIPSversion = >= 3.4.0 Sign-Message = RSA-SHA512-256:RSA-2048 Input = "Hello World" Output = 00904130234e4e1a51060f7747ab26ca766c64cff1df97e4d0f432169046da422305ddea16b96e0d8fcc5ab651ac247d1b65283f2f27e7e97538e9f6b77f9558c9885d5ddacaf4d6ca600ad61693766498fa815361cd1debe2d71a5af77da71f8bd72d2f5cf741aa177a2dc44107f5887d95b217c67dbc5a4874f9aa8de1fc8a5645815c561edcb348db6458018096a99a98f5d2e677f068c9093618e28f532a97e8d6161aec002d5273884ce8b46f077d37b1e158de682a927126952bdbb6b6dfdf47d7e34a7d9c9b1395315586a11ceadfb72c021b28e28b8397bc9086418a45cb8c1ad46ef47f1c2bedb14b50e50b58bd607992e1d19b895119c6a62471b4 FIPSversion = >= 3.4.0 Sign-Message = RSA-SHA3-224:RSA-2048 Input = "Hello World" Output = 5b6f6834356ba08ef649d822592d7a3d889995283e3752760b0728ed99aa05af901298159485a690f8dab21c850946ef2376bedcc87f403288039e1eb18dfdf4ac1075753528c94b5a8b11f74513ef64eddc215f7df97d977e788fd93db4063529fd87f583c1c98d39cd79178330bae7980d9a846acdf3bdd77a864f85b77941b375c076ff86def44b8da19b5de6131bb8894c870d4deeb62361bd429faad97530abab33795912d63f2fb886b25f1a1d9583fae3b7cf6dd6a5addd1b28320ab88a4dac2d938fb50b6c9115c7a0a4edd6b7b3453e435605839703f0b0c6e58f7bb73ef0fb38cab4f2d9dc1fd8b8b77b36ae945dea7563eaa33608781ce5ac181b FIPSversion = >= 3.4.0 Sign-Message = RSA-SHA3-256:RSA-2048 Input = "Hello World" Output = c531d0db6635b7c58c7118641565796c3d61323e303246cfc39e4e697727fede52b029407f82aa07e25c4833d18ec6ef6b585f3f078ca1494ae80a696fec701e1c2386196100cc5879fb8ea77f07b7019185258e1ad632c28cc672a61296787bb16a0e4f259d6eac1960f7eaaee1f7ab7eea3cf2d9e11435859630f0c71c48c8655b1252e072f18831731b2bc8e788a722c77db57583c7456e9b7fd5273e6781e214616620084dfefffe506910a39087912c3a8586fce65d8a0b1e5803ffe59b53537119653d708a55ef17d2721b9c8c183fe6750991b0e77b79d8d208ad750b2bc3426fbeeebf9b090bfc19f6534e44bf6d7d2f2e1dc2594b38ceda420553c9 FIPSversion = >= 3.4.0 Sign-Message = RSA-SHA3-384:RSA-2048 Input = "Hello World" Output = 78bc11342fd44b4c047a365cc6ef78476bf28547da4eafec09f6bdf68a5593e993716662801b313515d80ddd232dfcc414cf896349a0237976dd89a97a9c88a92cd86992996d9c2747bf4e5dff5acb2fc67aa51ceb27ed1b95edd952d8eab3055cdc576a860593308c426f7ea73e01bd05fb20a4fcb64b10945e1684da67a8367826535344ad25057b4840e138909668c2423669b51f2fec631fd7e919f6e8b82ee293878894cac6a58b21f2168ba6335197e39e587fd60076a369f0b8e779c045c507654fbb98f5ffc998f720ab48bdbfe6d397aa63c7209b45068e24b65371180ff6d775851b2aaceac393082920fffb9e8b6999c682875bd0eff231dfaadf FIPSversion = >= 3.4.0 Sign-Message = RSA-SHA3-512:RSA-2048 Input = "Hello World" Output = 4681312b0e27e4e5f2dd3165ea5bdc98210d4883709a842239cef72099d71855fc322c3d2f74a7e7357647de153c22e4c4f9a0e4f1ce9b7f993242df5ee778ca949e6e184551e87e0aac8440ae990ef76a14f6056a16181390ad3a150bfdbb985cfe4cca3255b5eb0871116654d59fc89f69adb46c307b927c51a5f34069a2f43c854fde8e2df0ded10f8e257d1d800aa44bf31981f93c062128cc551ad7f5f7ba68e9d7c917c8fc51bcda3ce9192680c1e5308bd5c571ac0a5ae7347a897e8698ea94059562cd3035e3ed5fcf6c4ca8c20f58a079dfcdb175242a5726237d1b92378ec7dc4f2db09a0fbd62d1ab6d1a3d0be7afd34ed9c3ecd1bc5a3d2c448c Availablein = default Sign-Message = RSA-RIPEMD160:RSA-2048 Input = "Hello World" Output = 6a7fc08e9999fc9d50cda476e973a01a06efeb52eece1c78cb1422950476cbff67408c6f5c0a5749a70d3b505d9b6ad84f6854cb290fab18b28c13233030964ce81e3cf4f34bd606322e44534c335994c9761ae989936fd33be4c53e43cc54f027e4d3eb48563be6242ffcb831d4382e5b3f155c345e6f4367ae40d92cb70376942f45ce9fde97eb282ff3767b7972821381e1c3443b0e595bc968c16119dbdeef9f91d9f15f61feb0a0a25c66c2e72513a853d6cc797e83c8719d82ed951ccce06292f07696c7f97a52a7048bd4c70c5a70dbab0470be3b75af0f28dd39535bb8fee899cb69d3b6970cc59c773c0c15122931b6904d3c5c98011650bb8283d6 Availablein = default Sign-Message = RSA-SM3:RSA-2048 Input = "Hello World" -Output = 92657e22036214c343d8e95d129c0c47430d5a1ae452371a7847a963f533f96e018aa6658958e6a584cf0d380aa9435175cf2de3dfa60100aca893b76aa6d8f0cc9154ee982cb5ea8f19153fe8a9c801aa2da8bb4451c7ec6fd836e81ecdacf022b68294db068efa47decf3a7c548ea7088a16433029b8733b9573053b7e7122ea10b662726fc97bd149c663617434a9707b672b024f95865d91077edfb79c8ed4c8528032204c46c984a6c82b17794cbf9c4dfe4c1af1d59535f7755540ff36d6a2b55accbf046896c4aae9287a33f38c2a269a02abdac46c17b1b55ee89cc9eb3011a84916596f982c5375dd2110633be6dc43532919466d83bd0f3e406978 +Output = b74e03c18050807541bde949aa0ac91d43fb9730f0b529d5100d5776f4f446d0ca0f0992359dc5f89386ed45bc3bf52cac1f75fbcc088fc2ea77624fd962569d2d317e90886dec424fb6757c4eba1e881ddf4f7942e8003b54e05cc974558dea171ce23a2fc158f71a5621c9a2c3ce45c9af4c706d3f60efe0c0f087a6ec504f771b08e2a1d78e0316c74706c678869bf121d5da00e2e8c8dc1cd273315b4ad8ab9962c62f81cebc5fb393b7f8860ee68545578413feada82b1c2bbfabfa157e298f0354bffc1cc6aa68f058a5d34b6b70ffacd3532c6b2c6a0de059bf605edf392ac8adbf1769555a0a50b2b13c63cae98a461498fae7f0d1729b710f05f39e diff --git a/test/recipes/90-test_sslapi.t b/test/recipes/90-test_sslapi.t index 650e0d1ffb16..70c2c24d8661 100644 --- a/test/recipes/90-test_sslapi.t +++ b/test/recipes/90-test_sslapi.t @@ -1,149 +1,158 @@ #! /usr/bin/env perl -# Copyright 2016-2024 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 2016-2025 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 OpenSSL::Test::Utils; use OpenSSL::Test qw/:DEFAULT srctop_file srctop_dir bldtop_dir bldtop_file result_dir result_file/; use File::Temp qw(tempfile); BEGIN { setup("test_sslapi"); } my $no_fips = disabled('fips') || ($ENV{NO_FIPS} // 0); my $fipsmodcfg_filename = "fipsmodule.cnf"; my $fipsmodcfg = bldtop_file("test", $fipsmodcfg_filename); my $provconf = srctop_file("test", "fips-and-base.cnf"); # A modified copy of "fipsmodule.cnf" my $fipsmodcfgnew_filename = "fipsmodule_mod.cnf"; my $fipsmodcfgnew = result_file($fipsmodcfgnew_filename); # An interum modified copy of "fipsmodule.cnf" my $fipsmodcfgtmp_filename = "fipsmodule_tmp.cnf"; my $fipsmodcfgtmp = result_file($fipsmodcfgtmp_filename); # A modified copy of "fips-and-base.cnf" my $provconfnew = result_file("fips-and-base-temp.cnf"); plan skip_all => "No TLS/SSL protocols are supported by this OpenSSL build" if alldisabled(grep { $_ ne "ssl3" } available_protocols("tls")); plan tests => 4; (undef, my $tmpfilename) = tempfile(); ok(run(test(["sslapitest", srctop_dir("test", "certs"), srctop_file("test", "recipes", "90-test_sslapi_data", "passwd.txt"), $tmpfilename, "default", srctop_file("test", "default.cnf"), srctop_file("test", "recipes", "90-test_sslapi_data", - "dhparams.pem")])), + "dhparams.pem"), + srctop_dir("test", + "recipes", + "90-test_sslapi_data")])), "running sslapitest"); SKIP: { skip "Skipping FIPS tests", 2 if $no_fips; # NOTE that because by default we setup fips provider in pedantic mode, # with >= 3.1.0 this just runs test_no_ems() to check that the connection # fails if ems is not used and the fips check is enabled. ok(run(test(["sslapitest", srctop_dir("test", "certs"), srctop_file("test", "recipes", "90-test_sslapi_data", "passwd.txt"), $tmpfilename, "fips", $provconf, srctop_file("test", "recipes", "90-test_sslapi_data", - "dhparams.pem")])), + "dhparams.pem"), + srctop_dir("test", + "recipes", + "90-test_sslapi_data")])), "running sslapitest with default fips config"); run(test(["fips_version_test", "-config", $provconf, ">=3.1.0"]), capture => 1, statusvar => \my $exit); skip "FIPS provider version is too old for TLS_PRF EMS option test", 1 if !$exit; # Read in a text $infile and replace the regular expression in $srch with the # value in $repl and output to a new file $outfile. sub replace_line_file_internal { my ($infile, $srch, $repl, $outfile) = @_; my $msg; open(my $in, "<", $infile) or return 0; read($in, $msg, 1024); close $in; $msg =~ s/$srch/$repl/; open(my $fh, ">", $outfile) or return 0; print $fh $msg; close $fh; return 1; } # Read in the text input file $infile # and replace a single Key = Value line with a new value in $value. # OR remove the Key = Value line if the passed in $value is empty. # and then output a new file $outfile. # $key is the Key to find sub replace_kv_file { my ($infile, $key, $value, $outfile) = @_; my $srch = qr/$key\s*=\s*\S*\n/; my $rep; if ($value eq "") { $rep = ""; } else { $rep = "$key = $value\n"; } return replace_line_file_internal($infile, $srch, $rep, $outfile); } # Read in the text $input file # and search for the $key and replace with $newkey # and then output a new file $outfile. sub replace_line_file { my ($infile, $key, $newkey, $outfile) = @_; my $srch = qr/$key/; my $rep = "$newkey"; return replace_line_file_internal($infile, $srch, $rep, $outfile); } # The default fipsmodule.cnf in tests is set with -pedantic. # In order to enable the tls1-prf-ems-check=0 in a fips config file # copy the existing fipsmodule.cnf and modify it. # Then copy fips-and-base.cfg to make a file that includes the changed file $ENV{OPENSSL_CONF_INCLUDE} = result_dir(); ok(replace_kv_file($fipsmodcfg, 'tls1-prf-ems-check', '0', $fipsmodcfgtmp) && replace_kv_file($fipsmodcfgtmp, 'rsa-pkcs15-pad-disabled', '0', $fipsmodcfgnew) && replace_line_file($provconf, $fipsmodcfg_filename, $fipsmodcfgnew_filename, $provconfnew) && run(test(["sslapitest", srctop_dir("test", "certs"), srctop_file("test", "recipes", "90-test_sslapi_data", "passwd.txt"), $tmpfilename, "fips", $provconfnew, srctop_file("test", "recipes", "90-test_sslapi_data", - "dhparams.pem")])), + "dhparams.pem"), + srctop_dir("test", + "recipes", + "90-test_sslapi_data")])), "running sslapitest with modified fips config"); } ok(run(test(["ssl_handshake_rtt_test"])),"running ssl_handshake_rtt_test"); unlink $tmpfilename; diff --git a/test/recipes/90-test_sslapi_data/ssltraceref-zlib.txt b/test/recipes/90-test_sslapi_data/ssltraceref-zlib.txt new file mode 100644 index 000000000000..05aed8299b0e --- /dev/null +++ b/test/recipes/90-test_sslapi_data/ssltraceref-zlib.txt @@ -0,0 +1,255 @@ +Sent TLS Record +Header: + Version = TLS 1.0 (0x301) + Content Type = Handshake (22) + Length = ? + ClientHello, Length=? + client_version=0x303 (TLS 1.2) + Random: + gmt_unix_time=0x? + random_bytes (len=28): ? + session_id (len=? + cipher_suites (len=2) + {0x13, 0x01} TLS_AES_128_GCM_SHA256 + compression_methods (len=1) + No Compression (0x00) + extensions, length = ? + extension_type=ec_point_formats(11), length=4 + uncompressed (0) + ansiX962_compressed_prime (1) + ansiX962_compressed_char2 (2) + extension_type=supported_groups(10), length=20 + MLKEM512 (512) + MLKEM768 (513) + MLKEM1024 (514) + X25519MLKEM768 (4588) + SecP256r1MLKEM768 (4587) + SecP384r1MLKEM1024 (4589) + secp521r1 (P-521) (25) + secp384r1 (P-384) (24) + secp256r1 (P-256) (23) + extension_type=session_ticket(35), length=0 + extension_type=encrypt_then_mac(22), length=0 + extension_type=extended_master_secret(23), length=0 + extension_type=signature_algorithms(13), length=? + mldsa65 (0x0905) + mldsa87 (0x0906) + mldsa44 (0x0904) + ecdsa_secp256r1_sha256 (0x0403) + ecdsa_secp384r1_sha384 (0x0503) + ecdsa_secp521r1_sha512 (0x0603) + ed25519 (0x0807) + ed448 (0x0808) + ecdsa_brainpoolP256r1tls13_sha256 (0x081a) + ecdsa_brainpoolP384r1tls13_sha384 (0x081b) + ecdsa_brainpoolP512r1tls13_sha512 (0x081c) + rsa_pss_pss_sha256 (0x0809) + rsa_pss_pss_sha384 (0x080a) + rsa_pss_pss_sha512 (0x080b) + rsa_pss_rsae_sha256 (0x0804) + rsa_pss_rsae_sha384 (0x0805) + rsa_pss_rsae_sha512 (0x0806) + rsa_pkcs1_sha256 (0x0401) + rsa_pkcs1_sha384 (0x0501) + rsa_pkcs1_sha512 (0x0601) + extension_type=supported_versions(43), length=3 + TLS 1.3 (772) + extension_type=psk_key_exchange_modes(45), length=2 + psk_dhe_ke (1) + extension_type=key_share(51), length=806 + NamedGroup: MLKEM512 (512) + key_exchange: (len=800): ? + extension_type=compress_certificate(27), length=3 + zlib (1) + +Received TLS Record +Header: + Version = TLS 1.2 (0x303) + Content Type = Handshake (22) + Length = 858 + ServerHello, Length=854 + server_version=0x303 (TLS 1.2) + Random: + gmt_unix_time=0x? + random_bytes (len=28): ? + session_id (len=? + cipher_suite {0x13, 0x01} TLS_AES_128_GCM_SHA256 + compression_method: No Compression (0x00) + extensions, length = ? + extension_type=supported_versions(43), length=2 + TLS 1.3 (772) + extension_type=key_share(51), length=772 + NamedGroup: MLKEM512 (512) + key_exchange: (len=768): ? + +Received TLS Record +Header: + Version = TLS 1.2 (0x303) + Content Type = ChangeCipherSpec (20) + Length = 1 + change_cipher_spec (1) + +Received TLS Record +Header: + Version = TLS 1.2 (0x303) + Content Type = ApplicationData (23) + Length = 23 + Inner Content Type = Handshake (22) + EncryptedExtensions, Length=2 + No extensions + +Received TLS Record +Header: + Version = TLS 1.2 (0x303) + Content Type = ApplicationData (23) + Length = 839 + Inner Content Type = Handshake (22) + Certificate, Length=818 + context (len=0): + certificate_list, length=814 + ASN.1Cert, length=809 +------details----- +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 2 (0x2) + Signature Algorithm: sha256WithRSAEncryption + Issuer: CN = Root CA + Validity + Not Before: Jan 14 22:29:46 2016 GMT + Not After : Jan 15 22:29:46 2116 GMT + Subject: CN = server.example + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:d5:5d:60:6a:df:fc:61:ee:48:aa:8c:11:48:43: + a5:6d:b6:52:5d:aa:98:49:b1:61:92:35:b1:fc:3a: + 04:25:0c:6d:79:ff:b4:d5:c9:e9:5c:1c:3b:e0:ab: + b3:b8:7d:a3:de:6d:bd:e0:dd:d7:5a:bf:14:47:11: + 42:5e:a6:82:d0:61:c1:7f:dd:13:46:e6:09:85:07: + 0e:f2:d4:fc:1a:64:d2:0a:ad:20:ab:20:6b:96:f0: + ad:cc:c4:19:53:55:dc:01:1d:a4:b3:ef:8a:b4:49: + 53:5d:8a:05:1c:f1:dc:e1:44:bf:c5:d7:e2:77:19: + 57:5c:97:0b:75:ee:88:43:71:0f:ca:6c:c1:b4:b2: + 50:a7:77:46:6c:58:0f:11:bf:f1:76:24:5a:ae:39: + 42:b7:51:67:29:e1:d0:55:30:6f:17:e4:91:ea:ad: + f8:28:c2:43:6f:a2:64:a9:fb:9d:98:92:62:48:3e: + eb:0d:4f:82:4a:8a:ff:3f:72:ee:96:b5:ae:a1:c1: + 98:ba:ef:7d:90:75:6d:ff:5a:52:9e:ab:f5:c0:7e: + d0:87:43:db:85:07:07:0f:7d:38:7a:fd:d1:d3:ee: + 65:1d:d3:ea:39:6a:87:37:ee:4a:d3:e0:0d:6e:f5: + 70:ac:c2:bd:f1:6e:f3:92:95:5e:a9:f0:a1:65:95: + 93:8d + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Subject Key Identifier: + C0:E7:84:BF:E8:59:27:33:10:B0:52:4F:51:52:2F:06:D6:C0:7A:CD + X509v3 Authority Key Identifier: + 70:7F:2E:AE:83:68:59:98:04:23:2A:CD:EB:3E:17:CD:24:DD:01:49 + X509v3 Basic Constraints: + CA:FALSE + X509v3 Extended Key Usage: + TLS Web Server Authentication + X509v3 Subject Alternative Name: + DNS:server.example + Signature Algorithm: sha256WithRSAEncryption + Signature Value: + 7b:d3:04:43:75:8a:0f:11:ae:c4:fb:d7:a1:a2:9e:fe:20:18: + d5:f4:2f:31:88:46:b6:75:8c:ee:e5:9b:97:a6:b9:a3:cd:60: + 9a:46:c3:48:97:e5:97:68:f7:5a:86:35:73:d9:69:9e:f9:5f: + 74:b9:e6:94:13:01:cb:6a:dc:e3:c4:04:e9:65:da:9c:a4:8b: + 28:f3:f9:9a:7f:bf:97:1f:45:92:e5:05:b1:56:e6:0b:f6:47: + de:1e:89:b6:2b:e1:4d:df:4a:7e:01:d3:23:dc:97:8c:47:fe: + 5f:c7:cc:98:46:0e:c4:83:5b:ca:8a:f1:52:09:be:6b:ec:3f: + 09:8b:d0:93:02:bf:e1:51:e7:d1:7e:34:56:19:74:d0:ff:28: + 25:de:b7:9f:56:52:91:7d:20:29:85:0a:80:44:5f:71:32:25: + 71:0f:c2:16:e2:5f:6b:1d:3f:32:5b:0a:3c:74:1c:b9:62:f1: + ed:07:50:a3:6d:b4:b4:31:0a:c0:53:44:6a:3a:88:84:8b:2d: + a9:b0:37:8e:e6:18:36:bd:9a:20:40:0f:01:92:8b:3d:aa:61: + e7:ae:2c:ed:36:cd:3a:07:86:74:3a:29:b3:d7:3a:b4:00:a9: + c2:f5:92:78:0e:e2:0f:a3:fe:bb:be:e0:06:53:84:59:1d:90: + 69:e5:b6:f9 +-----BEGIN CERTIFICATE----- +MIIDJTCCAg2gAwIBAgIBAjANBgkqhkiG9w0BAQsFADASMRAwDgYDVQQDDAdSb290 +IENBMCAXDTE2MDExNDIyMjk0NloYDzIxMTYwMTE1MjIyOTQ2WjAZMRcwFQYDVQQD +DA5zZXJ2ZXIuZXhhbXBsZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +ANVdYGrf/GHuSKqMEUhDpW22Ul2qmEmxYZI1sfw6BCUMbXn/tNXJ6VwcO+Crs7h9 +o95tveDd11q/FEcRQl6mgtBhwX/dE0bmCYUHDvLU/Bpk0gqtIKsga5bwrczEGVNV +3AEdpLPvirRJU12KBRzx3OFEv8XX4ncZV1yXC3XuiENxD8pswbSyUKd3RmxYDxG/ +8XYkWq45QrdRZynh0FUwbxfkkeqt+CjCQ2+iZKn7nZiSYkg+6w1PgkqK/z9y7pa1 +rqHBmLrvfZB1bf9aUp6r9cB+0IdD24UHBw99OHr90dPuZR3T6jlqhzfuStPgDW71 +cKzCvfFu85KVXqnwoWWVk40CAwEAAaN9MHswHQYDVR0OBBYEFMDnhL/oWSczELBS +T1FSLwbWwHrNMB8GA1UdIwQYMBaAFHB/Lq6DaFmYBCMqzes+F80k3QFJMAkGA1Ud +EwQCMAAwEwYDVR0lBAwwCgYIKwYBBQUHAwEwGQYDVR0RBBIwEIIOc2VydmVyLmV4 +YW1wbGUwDQYJKoZIhvcNAQELBQADggEBAHvTBEN1ig8RrsT716Ginv4gGNX0LzGI +RrZ1jO7lm5emuaPNYJpGw0iX5Zdo91qGNXPZaZ75X3S55pQTActq3OPEBOll2pyk +iyjz+Zp/v5cfRZLlBbFW5gv2R94eibYr4U3fSn4B0yPcl4xH/l/HzJhGDsSDW8qK +8VIJvmvsPwmL0JMCv+FR59F+NFYZdND/KCXet59WUpF9ICmFCoBEX3EyJXEPwhbi +X2sdPzJbCjx0HLli8e0HUKNttLQxCsBTRGo6iISLLamwN47mGDa9miBADwGSiz2q +YeeuLO02zToHhnQ6KbPXOrQAqcL1kngO4g+j/ru+4AZThFkdkGnltvk= +-----END CERTIFICATE----- +------------------ + No extensions + +Received TLS Record +Header: + Version = TLS 1.2 (0x303) + Content Type = ApplicationData (23) + Length = 281 + Inner Content Type = Handshake (22) + CertificateVerify, Length=260 + Signature Algorithm: rsa_pss_rsae_sha256 (0x0804) + Signature (len=256): ? + +Received TLS Record +Header: + Version = TLS 1.2 (0x303) + Content Type = ApplicationData (23) + Length = 53 + Inner Content Type = Handshake (22) + Finished, Length=32 + verify_data (len=32): ? + +Sent TLS Record +Header: + Version = TLS 1.2 (0x303) + Content Type = ChangeCipherSpec (20) + Length = 1 + change_cipher_spec (1) + +Sent TLS Record +Header: + Version = TLS 1.2 (0x303) + Content Type = ApplicationData (23) + Length = 53 + Inner Content Type = Handshake (22) + Finished, Length=32 + verify_data (len=32): ? + +Received TLS Record +Header: + Version = TLS 1.2 (0x303) + Content Type = ApplicationData (23) + Length = 234 + Inner Content Type = Handshake (22) + NewSessionTicket, Length=213 + ticket_lifetime_hint=7200 + ticket_age_add=? + ticket_nonce (len=8): ? + ticket (len=192): ? + No extensions + +Received TLS Record +Header: + Version = TLS 1.2 (0x303) + Content Type = ApplicationData (23) + Length = 234 + Inner Content Type = Handshake (22) + NewSessionTicket, Length=213 + ticket_lifetime_hint=7200 + ticket_age_add=? + ticket_nonce (len=8): ? + ticket (len=192): ? + No extensions + diff --git a/test/recipes/90-test_sslapi_data/ssltraceref.txt b/test/recipes/90-test_sslapi_data/ssltraceref.txt new file mode 100644 index 000000000000..5d332da235fb --- /dev/null +++ b/test/recipes/90-test_sslapi_data/ssltraceref.txt @@ -0,0 +1,253 @@ +Sent TLS Record +Header: + Version = TLS 1.0 (0x301) + Content Type = Handshake (22) + Length = ? + ClientHello, Length=? + client_version=0x303 (TLS 1.2) + Random: + gmt_unix_time=0x? + random_bytes (len=28): ? + session_id (len=? + cipher_suites (len=2) + {0x13, 0x01} TLS_AES_128_GCM_SHA256 + compression_methods (len=1) + No Compression (0x00) + extensions, length = ? + extension_type=ec_point_formats(11), length=4 + uncompressed (0) + ansiX962_compressed_prime (1) + ansiX962_compressed_char2 (2) + extension_type=supported_groups(10), length=20 + MLKEM512 (512) + MLKEM768 (513) + MLKEM1024 (514) + X25519MLKEM768 (4588) + SecP256r1MLKEM768 (4587) + SecP384r1MLKEM1024 (4589) + secp521r1 (P-521) (25) + secp384r1 (P-384) (24) + secp256r1 (P-256) (23) + extension_type=session_ticket(35), length=0 + extension_type=encrypt_then_mac(22), length=0 + extension_type=extended_master_secret(23), length=0 + extension_type=signature_algorithms(13), length=? + mldsa65 (0x0905) + mldsa87 (0x0906) + mldsa44 (0x0904) + ecdsa_secp256r1_sha256 (0x0403) + ecdsa_secp384r1_sha384 (0x0503) + ecdsa_secp521r1_sha512 (0x0603) + ed25519 (0x0807) + ed448 (0x0808) + ecdsa_brainpoolP256r1tls13_sha256 (0x081a) + ecdsa_brainpoolP384r1tls13_sha384 (0x081b) + ecdsa_brainpoolP512r1tls13_sha512 (0x081c) + rsa_pss_pss_sha256 (0x0809) + rsa_pss_pss_sha384 (0x080a) + rsa_pss_pss_sha512 (0x080b) + rsa_pss_rsae_sha256 (0x0804) + rsa_pss_rsae_sha384 (0x0805) + rsa_pss_rsae_sha512 (0x0806) + rsa_pkcs1_sha256 (0x0401) + rsa_pkcs1_sha384 (0x0501) + rsa_pkcs1_sha512 (0x0601) + extension_type=supported_versions(43), length=3 + TLS 1.3 (772) + extension_type=psk_key_exchange_modes(45), length=2 + psk_dhe_ke (1) + extension_type=key_share(51), length=806 + NamedGroup: MLKEM512 (512) + key_exchange: (len=800): ? + +Received TLS Record +Header: + Version = TLS 1.2 (0x303) + Content Type = Handshake (22) + Length = 858 + ServerHello, Length=854 + server_version=0x303 (TLS 1.2) + Random: + gmt_unix_time=0x? + random_bytes (len=28): ? + session_id (len=? + cipher_suite {0x13, 0x01} TLS_AES_128_GCM_SHA256 + compression_method: No Compression (0x00) + extensions, length = ? + extension_type=supported_versions(43), length=2 + TLS 1.3 (772) + extension_type=key_share(51), length=772 + NamedGroup: MLKEM512 (512) + key_exchange: (len=768): ? + +Received TLS Record +Header: + Version = TLS 1.2 (0x303) + Content Type = ChangeCipherSpec (20) + Length = 1 + change_cipher_spec (1) + +Received TLS Record +Header: + Version = TLS 1.2 (0x303) + Content Type = ApplicationData (23) + Length = 23 + Inner Content Type = Handshake (22) + EncryptedExtensions, Length=2 + No extensions + +Received TLS Record +Header: + Version = TLS 1.2 (0x303) + Content Type = ApplicationData (23) + Length = 839 + Inner Content Type = Handshake (22) + Certificate, Length=818 + context (len=0): + certificate_list, length=814 + ASN.1Cert, length=809 +------details----- +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 2 (0x2) + Signature Algorithm: sha256WithRSAEncryption + Issuer: CN = Root CA + Validity + Not Before: Jan 14 22:29:46 2016 GMT + Not After : Jan 15 22:29:46 2116 GMT + Subject: CN = server.example + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:d5:5d:60:6a:df:fc:61:ee:48:aa:8c:11:48:43: + a5:6d:b6:52:5d:aa:98:49:b1:61:92:35:b1:fc:3a: + 04:25:0c:6d:79:ff:b4:d5:c9:e9:5c:1c:3b:e0:ab: + b3:b8:7d:a3:de:6d:bd:e0:dd:d7:5a:bf:14:47:11: + 42:5e:a6:82:d0:61:c1:7f:dd:13:46:e6:09:85:07: + 0e:f2:d4:fc:1a:64:d2:0a:ad:20:ab:20:6b:96:f0: + ad:cc:c4:19:53:55:dc:01:1d:a4:b3:ef:8a:b4:49: + 53:5d:8a:05:1c:f1:dc:e1:44:bf:c5:d7:e2:77:19: + 57:5c:97:0b:75:ee:88:43:71:0f:ca:6c:c1:b4:b2: + 50:a7:77:46:6c:58:0f:11:bf:f1:76:24:5a:ae:39: + 42:b7:51:67:29:e1:d0:55:30:6f:17:e4:91:ea:ad: + f8:28:c2:43:6f:a2:64:a9:fb:9d:98:92:62:48:3e: + eb:0d:4f:82:4a:8a:ff:3f:72:ee:96:b5:ae:a1:c1: + 98:ba:ef:7d:90:75:6d:ff:5a:52:9e:ab:f5:c0:7e: + d0:87:43:db:85:07:07:0f:7d:38:7a:fd:d1:d3:ee: + 65:1d:d3:ea:39:6a:87:37:ee:4a:d3:e0:0d:6e:f5: + 70:ac:c2:bd:f1:6e:f3:92:95:5e:a9:f0:a1:65:95: + 93:8d + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Subject Key Identifier: + C0:E7:84:BF:E8:59:27:33:10:B0:52:4F:51:52:2F:06:D6:C0:7A:CD + X509v3 Authority Key Identifier: + 70:7F:2E:AE:83:68:59:98:04:23:2A:CD:EB:3E:17:CD:24:DD:01:49 + X509v3 Basic Constraints: + CA:FALSE + X509v3 Extended Key Usage: + TLS Web Server Authentication + X509v3 Subject Alternative Name: + DNS:server.example + Signature Algorithm: sha256WithRSAEncryption + Signature Value: + 7b:d3:04:43:75:8a:0f:11:ae:c4:fb:d7:a1:a2:9e:fe:20:18: + d5:f4:2f:31:88:46:b6:75:8c:ee:e5:9b:97:a6:b9:a3:cd:60: + 9a:46:c3:48:97:e5:97:68:f7:5a:86:35:73:d9:69:9e:f9:5f: + 74:b9:e6:94:13:01:cb:6a:dc:e3:c4:04:e9:65:da:9c:a4:8b: + 28:f3:f9:9a:7f:bf:97:1f:45:92:e5:05:b1:56:e6:0b:f6:47: + de:1e:89:b6:2b:e1:4d:df:4a:7e:01:d3:23:dc:97:8c:47:fe: + 5f:c7:cc:98:46:0e:c4:83:5b:ca:8a:f1:52:09:be:6b:ec:3f: + 09:8b:d0:93:02:bf:e1:51:e7:d1:7e:34:56:19:74:d0:ff:28: + 25:de:b7:9f:56:52:91:7d:20:29:85:0a:80:44:5f:71:32:25: + 71:0f:c2:16:e2:5f:6b:1d:3f:32:5b:0a:3c:74:1c:b9:62:f1: + ed:07:50:a3:6d:b4:b4:31:0a:c0:53:44:6a:3a:88:84:8b:2d: + a9:b0:37:8e:e6:18:36:bd:9a:20:40:0f:01:92:8b:3d:aa:61: + e7:ae:2c:ed:36:cd:3a:07:86:74:3a:29:b3:d7:3a:b4:00:a9: + c2:f5:92:78:0e:e2:0f:a3:fe:bb:be:e0:06:53:84:59:1d:90: + 69:e5:b6:f9 +-----BEGIN CERTIFICATE----- +MIIDJTCCAg2gAwIBAgIBAjANBgkqhkiG9w0BAQsFADASMRAwDgYDVQQDDAdSb290 +IENBMCAXDTE2MDExNDIyMjk0NloYDzIxMTYwMTE1MjIyOTQ2WjAZMRcwFQYDVQQD +DA5zZXJ2ZXIuZXhhbXBsZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +ANVdYGrf/GHuSKqMEUhDpW22Ul2qmEmxYZI1sfw6BCUMbXn/tNXJ6VwcO+Crs7h9 +o95tveDd11q/FEcRQl6mgtBhwX/dE0bmCYUHDvLU/Bpk0gqtIKsga5bwrczEGVNV +3AEdpLPvirRJU12KBRzx3OFEv8XX4ncZV1yXC3XuiENxD8pswbSyUKd3RmxYDxG/ +8XYkWq45QrdRZynh0FUwbxfkkeqt+CjCQ2+iZKn7nZiSYkg+6w1PgkqK/z9y7pa1 +rqHBmLrvfZB1bf9aUp6r9cB+0IdD24UHBw99OHr90dPuZR3T6jlqhzfuStPgDW71 +cKzCvfFu85KVXqnwoWWVk40CAwEAAaN9MHswHQYDVR0OBBYEFMDnhL/oWSczELBS +T1FSLwbWwHrNMB8GA1UdIwQYMBaAFHB/Lq6DaFmYBCMqzes+F80k3QFJMAkGA1Ud +EwQCMAAwEwYDVR0lBAwwCgYIKwYBBQUHAwEwGQYDVR0RBBIwEIIOc2VydmVyLmV4 +YW1wbGUwDQYJKoZIhvcNAQELBQADggEBAHvTBEN1ig8RrsT716Ginv4gGNX0LzGI +RrZ1jO7lm5emuaPNYJpGw0iX5Zdo91qGNXPZaZ75X3S55pQTActq3OPEBOll2pyk +iyjz+Zp/v5cfRZLlBbFW5gv2R94eibYr4U3fSn4B0yPcl4xH/l/HzJhGDsSDW8qK +8VIJvmvsPwmL0JMCv+FR59F+NFYZdND/KCXet59WUpF9ICmFCoBEX3EyJXEPwhbi +X2sdPzJbCjx0HLli8e0HUKNttLQxCsBTRGo6iISLLamwN47mGDa9miBADwGSiz2q +YeeuLO02zToHhnQ6KbPXOrQAqcL1kngO4g+j/ru+4AZThFkdkGnltvk= +-----END CERTIFICATE----- +------------------ + No extensions + +Received TLS Record +Header: + Version = TLS 1.2 (0x303) + Content Type = ApplicationData (23) + Length = 281 + Inner Content Type = Handshake (22) + CertificateVerify, Length=260 + Signature Algorithm: rsa_pss_rsae_sha256 (0x0804) + Signature (len=256): ? + +Received TLS Record +Header: + Version = TLS 1.2 (0x303) + Content Type = ApplicationData (23) + Length = 53 + Inner Content Type = Handshake (22) + Finished, Length=32 + verify_data (len=32): ? + +Sent TLS Record +Header: + Version = TLS 1.2 (0x303) + Content Type = ChangeCipherSpec (20) + Length = 1 + change_cipher_spec (1) + +Sent TLS Record +Header: + Version = TLS 1.2 (0x303) + Content Type = ApplicationData (23) + Length = 53 + Inner Content Type = Handshake (22) + Finished, Length=32 + verify_data (len=32): ? + +Received TLS Record +Header: + Version = TLS 1.2 (0x303) + Content Type = ApplicationData (23) + Length = 234 + Inner Content Type = Handshake (22) + NewSessionTicket, Length=213 + ticket_lifetime_hint=7200 + ticket_age_add=? + ticket_nonce (len=8): ? + ticket (len=192): ? + No extensions + +Received TLS Record +Header: + Version = TLS 1.2 (0x303) + Content Type = ApplicationData (23) + Length = 234 + Inner Content Type = Handshake (22) + NewSessionTicket, Length=213 + ticket_lifetime_hint=7200 + ticket_age_add=? + ticket_nonce (len=8): ? + ticket (len=192): ? + No extensions + diff --git a/test/sslapitest.c b/test/sslapitest.c index b83dd6c552de..fbe284b9ff1e 100644 --- a/test/sslapitest.c +++ b/test/sslapitest.c @@ -1,13633 +1,13720 @@ /* * Copyright 2016-2025 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 access to the deprecated low level HMAC APIs for legacy purposes * when the deprecated calls are not hidden */ #ifndef OPENSSL_NO_DEPRECATED_3_0 # define OPENSSL_SUPPRESS_DEPRECATED #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "helpers/ssltestlib.h" #include "testutil.h" #include "testutil/output.h" #include "internal/nelem.h" #include "internal/tlsgroups.h" #include "internal/ktls.h" #include "internal/ssl_unwrap.h" #include "../ssl/ssl_local.h" #include "../ssl/record/methods/recmethod_local.h" #include "filterprov.h" #undef OSSL_NO_USABLE_TLS1_3 #if defined(OPENSSL_NO_TLS1_3) \ || (defined(OPENSSL_NO_EC) && defined(OPENSSL_NO_DH)) /* * If we don't have ec or dh then there are no built-in groups that are usable * with TLSv1.3 */ # define OSSL_NO_USABLE_TLS1_3 #endif /* Defined in tls-provider.c */ int tls_provider_init(const OSSL_CORE_HANDLE *handle, const OSSL_DISPATCH *in, const OSSL_DISPATCH **out, void **provctx); static OSSL_LIB_CTX *libctx = NULL; static OSSL_PROVIDER *defctxnull = NULL; #ifndef OSSL_NO_USABLE_TLS1_3 static SSL_SESSION *clientpsk = NULL; static SSL_SESSION *serverpsk = NULL; static const char *pskid = "Identity"; static const char *srvid; static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id, size_t *idlen, SSL_SESSION **sess); static int find_session_cb(SSL *ssl, const unsigned char *identity, size_t identity_len, SSL_SESSION **sess); static int use_session_cb_cnt = 0; static int find_session_cb_cnt = 0; static int end_of_early_data = 0; #endif static char *certsdir = NULL; static char *cert = NULL; static char *privkey = NULL; static char *cert2 = NULL; static char *privkey2 = NULL; static char *cert1024 = NULL; static char *privkey1024 = NULL; static char *cert3072 = NULL; static char *privkey3072 = NULL; static char *cert4096 = NULL; static char *privkey4096 = NULL; static char *cert8192 = NULL; static char *privkey8192 = NULL; static char *srpvfile = NULL; static char *tmpfilename = NULL; static char *dhfile = NULL; +static char *datadir = NULL; static int is_fips = 0; static int fips_ems_check = 0; #define LOG_BUFFER_SIZE 2048 static char server_log_buffer[LOG_BUFFER_SIZE + 1] = {0}; static size_t server_log_buffer_index = 0; static char client_log_buffer[LOG_BUFFER_SIZE + 1] = {0}; static size_t client_log_buffer_index = 0; static int error_writing_log = 0; #ifndef OPENSSL_NO_OCSP static const unsigned char orespder[] = "Dummy OCSP Response"; static int ocsp_server_called = 0; static int ocsp_client_called = 0; static int cdummyarg = 1; static X509 *ocspcert = NULL; #endif #define CLIENT_VERSION_LEN 2 +/* The ssltrace test assumes some options are switched on/off */ +#if !defined(OPENSSL_NO_SSL_TRACE) \ + && defined(OPENSSL_NO_BROTLI) && defined(OPENSSL_NO_ZSTD) \ + && !defined(OPENSSL_NO_ECX) && !defined(OPENSSL_NO_DH) \ + && !defined(OPENSSL_NO_ML_DSA) && !defined(OPENSSL_NO_ML_KEM) \ + && !defined(OPENSSL_NO_TLS1_3) +# define DO_SSL_TRACE_TEST +#endif + /* * This structure is used to validate that the correct number of log messages * of various types are emitted when emitting secret logs. */ struct sslapitest_log_counts { unsigned int rsa_key_exchange_count; unsigned int master_secret_count; unsigned int client_early_secret_count; unsigned int client_handshake_secret_count; unsigned int server_handshake_secret_count; unsigned int client_application_secret_count; unsigned int server_application_secret_count; unsigned int early_exporter_secret_count; unsigned int exporter_secret_count; }; static int hostname_cb(SSL *s, int *al, void *arg) { const char *hostname = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name); if (hostname != NULL && (strcmp(hostname, "goodhost") == 0 || strcmp(hostname, "altgoodhost") == 0)) return SSL_TLSEXT_ERR_OK; return SSL_TLSEXT_ERR_NOACK; } static void client_keylog_callback(const SSL *ssl, const char *line) { int line_length = strlen(line); /* If the log doesn't fit, error out. */ if (client_log_buffer_index + line_length > sizeof(client_log_buffer) - 1) { TEST_info("Client log too full"); error_writing_log = 1; return; } strcat(client_log_buffer, line); client_log_buffer_index += line_length; client_log_buffer[client_log_buffer_index++] = '\n'; } static void server_keylog_callback(const SSL *ssl, const char *line) { int line_length = strlen(line); /* If the log doesn't fit, error out. */ if (server_log_buffer_index + line_length > sizeof(server_log_buffer) - 1) { TEST_info("Server log too full"); error_writing_log = 1; return; } strcat(server_log_buffer, line); server_log_buffer_index += line_length; server_log_buffer[server_log_buffer_index++] = '\n'; } static int compare_hex_encoded_buffer(const char *hex_encoded, size_t hex_length, const uint8_t *raw, size_t raw_length) { size_t i, j; char hexed[3]; if (!TEST_size_t_eq(raw_length * 2, hex_length)) return 1; for (i = j = 0; i < raw_length && j + 1 < hex_length; i++, j += 2) { BIO_snprintf(hexed, sizeof(hexed), "%02x", raw[i]); if (!TEST_int_eq(hexed[0], hex_encoded[j]) || !TEST_int_eq(hexed[1], hex_encoded[j + 1])) return 1; } return 0; } static int test_keylog_output(char *buffer, const SSL *ssl, const SSL_SESSION *session, struct sslapitest_log_counts *expected) { char *token = NULL; unsigned char actual_client_random[SSL3_RANDOM_SIZE] = {0}; size_t client_random_size = SSL3_RANDOM_SIZE; unsigned char actual_master_key[SSL_MAX_MASTER_KEY_LENGTH] = {0}; size_t master_key_size = SSL_MAX_MASTER_KEY_LENGTH; unsigned int rsa_key_exchange_count = 0; unsigned int master_secret_count = 0; unsigned int client_early_secret_count = 0; unsigned int client_handshake_secret_count = 0; unsigned int server_handshake_secret_count = 0; unsigned int client_application_secret_count = 0; unsigned int server_application_secret_count = 0; unsigned int early_exporter_secret_count = 0; unsigned int exporter_secret_count = 0; for (token = strtok(buffer, " \n"); token != NULL; token = strtok(NULL, " \n")) { if (strcmp(token, "RSA") == 0) { /* * Premaster secret. Tokens should be: 16 ASCII bytes of * hex-encoded encrypted secret, then the hex-encoded pre-master * secret. */ if (!TEST_ptr(token = strtok(NULL, " \n"))) return 0; if (!TEST_size_t_eq(strlen(token), 16)) return 0; if (!TEST_ptr(token = strtok(NULL, " \n"))) return 0; /* * We can't sensibly check the log because the premaster secret is * transient, and OpenSSL doesn't keep hold of it once the master * secret is generated. */ rsa_key_exchange_count++; } else if (strcmp(token, "CLIENT_RANDOM") == 0) { /* * Master secret. Tokens should be: 64 ASCII bytes of hex-encoded * client random, then the hex-encoded master secret. */ client_random_size = SSL_get_client_random(ssl, actual_client_random, SSL3_RANDOM_SIZE); if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE)) return 0; if (!TEST_ptr(token = strtok(NULL, " \n"))) return 0; if (!TEST_size_t_eq(strlen(token), 64)) return 0; if (!TEST_false(compare_hex_encoded_buffer(token, 64, actual_client_random, client_random_size))) return 0; if (!TEST_ptr(token = strtok(NULL, " \n"))) return 0; master_key_size = SSL_SESSION_get_master_key(session, actual_master_key, master_key_size); if (!TEST_size_t_ne(master_key_size, 0)) return 0; if (!TEST_false(compare_hex_encoded_buffer(token, strlen(token), actual_master_key, master_key_size))) return 0; master_secret_count++; } else if (strcmp(token, "CLIENT_EARLY_TRAFFIC_SECRET") == 0 || strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0 || strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0 || strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0 || strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0 || strcmp(token, "EARLY_EXPORTER_SECRET") == 0 || strcmp(token, "EXPORTER_SECRET") == 0) { /* * TLSv1.3 secret. Tokens should be: 64 ASCII bytes of hex-encoded * client random, and then the hex-encoded secret. In this case, * we treat all of these secrets identically and then just * distinguish between them when counting what we saw. */ if (strcmp(token, "CLIENT_EARLY_TRAFFIC_SECRET") == 0) client_early_secret_count++; else if (strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0) client_handshake_secret_count++; else if (strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0) server_handshake_secret_count++; else if (strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0) client_application_secret_count++; else if (strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0) server_application_secret_count++; else if (strcmp(token, "EARLY_EXPORTER_SECRET") == 0) early_exporter_secret_count++; else if (strcmp(token, "EXPORTER_SECRET") == 0) exporter_secret_count++; client_random_size = SSL_get_client_random(ssl, actual_client_random, SSL3_RANDOM_SIZE); if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE)) return 0; if (!TEST_ptr(token = strtok(NULL, " \n"))) return 0; if (!TEST_size_t_eq(strlen(token), 64)) return 0; if (!TEST_false(compare_hex_encoded_buffer(token, 64, actual_client_random, client_random_size))) return 0; if (!TEST_ptr(token = strtok(NULL, " \n"))) return 0; } else { TEST_info("Unexpected token %s\n", token); return 0; } } /* Got what we expected? */ if (!TEST_size_t_eq(rsa_key_exchange_count, expected->rsa_key_exchange_count) || !TEST_size_t_eq(master_secret_count, expected->master_secret_count) || !TEST_size_t_eq(client_early_secret_count, expected->client_early_secret_count) || !TEST_size_t_eq(client_handshake_secret_count, expected->client_handshake_secret_count) || !TEST_size_t_eq(server_handshake_secret_count, expected->server_handshake_secret_count) || !TEST_size_t_eq(client_application_secret_count, expected->client_application_secret_count) || !TEST_size_t_eq(server_application_secret_count, expected->server_application_secret_count) || !TEST_size_t_eq(early_exporter_secret_count, expected->early_exporter_secret_count) || !TEST_size_t_eq(exporter_secret_count, expected->exporter_secret_count)) return 0; return 1; } #if !defined(OPENSSL_NO_TLS1_2) || defined(OSSL_NO_USABLE_TLS1_3) static int test_keylog(void) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; struct sslapitest_log_counts expected; /* Clean up logging space */ memset(&expected, 0, sizeof(expected)); memset(client_log_buffer, 0, sizeof(client_log_buffer)); memset(server_log_buffer, 0, sizeof(server_log_buffer)); client_log_buffer_index = 0; server_log_buffer_index = 0; error_writing_log = 0; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey))) return 0; /* We cannot log the master secret for TLSv1.3, so we should forbid it. */ SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3); SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3); /* We also want to ensure that we use RSA-based key exchange. */ if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "RSA"))) goto end; if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL) || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL)) goto end; SSL_CTX_set_keylog_callback(cctx, client_keylog_callback); if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == client_keylog_callback)) goto end; SSL_CTX_set_keylog_callback(sctx, server_keylog_callback); if (!TEST_true(SSL_CTX_get_keylog_callback(sctx) == server_keylog_callback)) goto end; /* Now do a handshake and check that the logs have been written to. */ if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_false(error_writing_log) || !TEST_int_gt(client_log_buffer_index, 0) || !TEST_int_gt(server_log_buffer_index, 0)) goto end; /* * Now we want to test that our output data was vaguely sensible. We * do that by using strtok and confirming that we have more or less the * data we expect. For both client and server, we expect to see one master * secret. The client should also see an RSA key exchange. */ expected.rsa_key_exchange_count = 1; expected.master_secret_count = 1; if (!TEST_true(test_keylog_output(client_log_buffer, clientssl, SSL_get_session(clientssl), &expected))) goto end; expected.rsa_key_exchange_count = 0; if (!TEST_true(test_keylog_output(server_log_buffer, serverssl, SSL_get_session(serverssl), &expected))) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #endif #ifndef OSSL_NO_USABLE_TLS1_3 static int test_keylog_no_master_key(void) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; SSL_SESSION *sess = NULL; int testresult = 0; struct sslapitest_log_counts expected; unsigned char buf[1]; size_t readbytes, written; /* Clean up logging space */ memset(&expected, 0, sizeof(expected)); memset(client_log_buffer, 0, sizeof(client_log_buffer)); memset(server_log_buffer, 0, sizeof(server_log_buffer)); client_log_buffer_index = 0; server_log_buffer_index = 0; error_writing_log = 0; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey)) || !TEST_true(SSL_CTX_set_max_early_data(sctx, SSL3_RT_MAX_PLAIN_LENGTH))) return 0; if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL) || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL)) goto end; SSL_CTX_set_keylog_callback(cctx, client_keylog_callback); if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == client_keylog_callback)) goto end; SSL_CTX_set_keylog_callback(sctx, server_keylog_callback); if (!TEST_true(SSL_CTX_get_keylog_callback(sctx) == server_keylog_callback)) goto end; /* Now do a handshake and check that the logs have been written to. */ if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_false(error_writing_log)) goto end; /* * Now we want to test that our output data was vaguely sensible. For this * test, we expect no CLIENT_RANDOM entry because it doesn't make sense for * TLSv1.3, but we do expect both client and server to emit keys. */ expected.client_handshake_secret_count = 1; expected.server_handshake_secret_count = 1; expected.client_application_secret_count = 1; expected.server_application_secret_count = 1; expected.exporter_secret_count = 1; if (!TEST_true(test_keylog_output(client_log_buffer, clientssl, SSL_get_session(clientssl), &expected)) || !TEST_true(test_keylog_output(server_log_buffer, serverssl, SSL_get_session(serverssl), &expected))) goto end; /* Terminate old session and resume with early data. */ sess = SSL_get1_session(clientssl); SSL_shutdown(clientssl); SSL_shutdown(serverssl); SSL_free(serverssl); SSL_free(clientssl); serverssl = clientssl = NULL; /* Reset key log */ memset(client_log_buffer, 0, sizeof(client_log_buffer)); memset(server_log_buffer, 0, sizeof(server_log_buffer)); client_log_buffer_index = 0; server_log_buffer_index = 0; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(SSL_set_session(clientssl, sess)) /* Here writing 0 length early data is enough. */ || !TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written)) || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf), &readbytes), SSL_READ_EARLY_DATA_ERROR) || !TEST_int_eq(SSL_get_early_data_status(serverssl), SSL_EARLY_DATA_ACCEPTED) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_true(SSL_session_reused(clientssl))) goto end; /* In addition to the previous entries, expect early secrets. */ expected.client_early_secret_count = 1; expected.early_exporter_secret_count = 1; if (!TEST_true(test_keylog_output(client_log_buffer, clientssl, SSL_get_session(clientssl), &expected)) || !TEST_true(test_keylog_output(server_log_buffer, serverssl, SSL_get_session(serverssl), &expected))) goto end; testresult = 1; end: SSL_SESSION_free(sess); SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #endif static int verify_retry_cb(X509_STORE_CTX *ctx, void *arg) { int res = X509_verify_cert(ctx); int idx = SSL_get_ex_data_X509_STORE_CTX_idx(); SSL *ssl; /* this should not happen but check anyway */ if (idx < 0 || (ssl = X509_STORE_CTX_get_ex_data(ctx, idx)) == NULL) return 0; if (res == 0 && X509_STORE_CTX_get_error(ctx) == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY) /* indicate SSL_ERROR_WANT_RETRY_VERIFY */ return SSL_set_retry_verify(ssl); return res; } static int test_client_cert_verify_cb(void) { /* server key, cert, chain, and root */ char *skey = test_mk_file_path(certsdir, "leaf.key"); char *leaf = test_mk_file_path(certsdir, "leaf.pem"); char *int2 = test_mk_file_path(certsdir, "subinterCA.pem"); char *int1 = test_mk_file_path(certsdir, "interCA.pem"); char *root = test_mk_file_path(certsdir, "rootCA.pem"); X509 *crt1 = NULL, *crt2 = NULL; STACK_OF(X509) *server_chain; SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, NULL, NULL))) goto end; if (!TEST_int_eq(SSL_CTX_use_certificate_chain_file(sctx, leaf), 1) || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(sctx, skey, SSL_FILETYPE_PEM), 1) || !TEST_int_eq(SSL_CTX_check_private_key(sctx), 1)) goto end; if (!TEST_true(SSL_CTX_load_verify_locations(cctx, root, NULL))) goto end; SSL_CTX_set_verify(cctx, SSL_VERIFY_PEER, NULL); SSL_CTX_set_cert_verify_callback(cctx, verify_retry_cb, NULL); if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; /* attempt SSL_connect() with incomplete server chain */ if (!TEST_false(create_ssl_connection(serverssl, clientssl, SSL_ERROR_WANT_RETRY_VERIFY))) goto end; /* application provides intermediate certs needed to verify server cert */ if (!TEST_ptr((crt1 = load_cert_pem(int1, libctx))) || !TEST_ptr((crt2 = load_cert_pem(int2, libctx))) || !TEST_ptr((server_chain = SSL_get_peer_cert_chain(clientssl)))) goto end; /* add certs in reverse order to demonstrate real chain building */ if (!TEST_true(sk_X509_push(server_chain, crt1))) goto end; crt1 = NULL; if (!TEST_true(sk_X509_push(server_chain, crt2))) goto end; crt2 = NULL; /* continue SSL_connect(), must now succeed with completed server chain */ if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; testresult = 1; end: X509_free(crt1); X509_free(crt2); if (clientssl != NULL) { SSL_shutdown(clientssl); SSL_free(clientssl); } if (serverssl != NULL) { SSL_shutdown(serverssl); SSL_free(serverssl); } SSL_CTX_free(sctx); SSL_CTX_free(cctx); OPENSSL_free(skey); OPENSSL_free(leaf); OPENSSL_free(int2); OPENSSL_free(int1); OPENSSL_free(root); return testresult; } static int test_ssl_build_cert_chain(void) { int ret = 0; SSL_CTX *ssl_ctx = NULL; SSL *ssl = NULL; char *skey = test_mk_file_path(certsdir, "leaf.key"); char *leaf_chain = test_mk_file_path(certsdir, "leaf-chain.pem"); if (!TEST_ptr(ssl_ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method()))) goto end; if (!TEST_ptr(ssl = SSL_new(ssl_ctx))) goto end; /* leaf_chain contains leaf + subinterCA + interCA + rootCA */ if (!TEST_int_eq(SSL_use_certificate_chain_file(ssl, leaf_chain), 1) || !TEST_int_eq(SSL_use_PrivateKey_file(ssl, skey, SSL_FILETYPE_PEM), 1) || !TEST_int_eq(SSL_check_private_key(ssl), 1)) goto end; if (!TEST_true(SSL_build_cert_chain(ssl, SSL_BUILD_CHAIN_FLAG_NO_ROOT | SSL_BUILD_CHAIN_FLAG_CHECK))) goto end; ret = 1; end: SSL_free(ssl); SSL_CTX_free(ssl_ctx); OPENSSL_free(leaf_chain); OPENSSL_free(skey); return ret; } static int get_password_cb(char *buf, int size, int rw_flag, void *userdata) { static const char pass[] = "testpass"; if (!TEST_int_eq(size, PEM_BUFSIZE)) return -1; memcpy(buf, pass, sizeof(pass) - 1); return sizeof(pass) - 1; } static int test_ssl_ctx_build_cert_chain(void) { int ret = 0; SSL_CTX *ctx = NULL; char *skey = test_mk_file_path(certsdir, "leaf-encrypted.key"); char *leaf_chain = test_mk_file_path(certsdir, "leaf-chain.pem"); if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method()))) goto end; SSL_CTX_set_default_passwd_cb(ctx, get_password_cb); /* leaf_chain contains leaf + subinterCA + interCA + rootCA */ if (!TEST_int_eq(SSL_CTX_use_certificate_chain_file(ctx, leaf_chain), 1) || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(ctx, skey, SSL_FILETYPE_PEM), 1) || !TEST_int_eq(SSL_CTX_check_private_key(ctx), 1)) goto end; if (!TEST_true(SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT | SSL_BUILD_CHAIN_FLAG_CHECK))) goto end; ret = 1; end: SSL_CTX_free(ctx); OPENSSL_free(leaf_chain); OPENSSL_free(skey); return ret; } #ifndef OPENSSL_NO_TLS1_2 static int full_client_hello_callback(SSL *s, int *al, void *arg) { int *ctr = arg; const unsigned char *p; int *exts; #ifdef OPENSSL_NO_EC const unsigned char expected_ciphers[] = {0x00, 0x9d}; #else const unsigned char expected_ciphers[] = {0x00, 0x9d, 0xc0, 0x2c}; #endif const int expected_extensions[] = { 65281, #ifndef OPENSSL_NO_EC 11, 10, #endif 35, 22, 23, 13}; size_t len; /* Make sure we can defer processing and get called back. */ if ((*ctr)++ == 0) return SSL_CLIENT_HELLO_RETRY; len = SSL_client_hello_get0_ciphers(s, &p); if (!TEST_mem_eq(p, len, expected_ciphers, sizeof(expected_ciphers)) || !TEST_size_t_eq( SSL_client_hello_get0_compression_methods(s, &p), 1) || !TEST_int_eq(*p, 0)) return SSL_CLIENT_HELLO_ERROR; if (!SSL_client_hello_get1_extensions_present(s, &exts, &len)) return SSL_CLIENT_HELLO_ERROR; if (len != OSSL_NELEM(expected_extensions) || memcmp(exts, expected_extensions, len * sizeof(*exts)) != 0) { printf("ClientHello callback expected extensions mismatch\n"); OPENSSL_free(exts); return SSL_CLIENT_HELLO_ERROR; } OPENSSL_free(exts); return SSL_CLIENT_HELLO_SUCCESS; } static int test_client_hello_cb(void) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testctr = 0, testresult = 0; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey))) goto end; SSL_CTX_set_client_hello_cb(sctx, full_client_hello_callback, &testctr); /* The gimpy cipher list we configure can't do TLS 1.3. */ SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION); /* Avoid problems where the default seclevel has been changed */ SSL_CTX_set_security_level(cctx, 2); if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384")) || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_false(create_ssl_connection(serverssl, clientssl, SSL_ERROR_WANT_CLIENT_HELLO_CB)) /* * Passing a -1 literal is a hack since * the real value was lost. * */ || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_WANT_CLIENT_HELLO_CB) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } static int test_no_ems(void) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0, status; if (!create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, TLS1_2_VERSION, &sctx, &cctx, cert, privkey)) { printf("Unable to create SSL_CTX pair\n"); goto end; } SSL_CTX_set_options(sctx, SSL_OP_NO_EXTENDED_MASTER_SECRET); if (!create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) { printf("Unable to create SSL objects\n"); goto end; } status = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE); if (fips_ems_check) { if (status == 1) { printf("When FIPS uses the EMS check a connection that doesn't use EMS should fail\n"); goto end; } } else { if (!status) { printf("Creating SSL connection failed\n"); goto end; } if (SSL_get_extms_support(serverssl)) { printf("Server reports Extended Master Secret support\n"); goto end; } if (SSL_get_extms_support(clientssl)) { printf("Client reports Extended Master Secret support\n"); goto end; } } testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } /* * Very focused test to exercise a single case in the server-side state * machine, when the ChangeCipherState message needs to actually change * from one cipher to a different cipher (i.e., not changing from null * encryption to real encryption). */ static int test_ccs_change_cipher(void) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; SSL_SESSION *sess = NULL, *sesspre, *sesspost; int testresult = 0; int i; unsigned char buf; size_t readbytes; /* * Create a connection so we can resume and potentially (but not) use * a different cipher in the second connection. */ if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, TLS1_2_VERSION, &sctx, &cctx, cert, privkey)) || !TEST_true(SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET)) || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(SSL_set_cipher_list(clientssl, "AES128-GCM-SHA256")) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_ptr(sesspre = SSL_get0_session(serverssl)) || !TEST_ptr(sess = SSL_get1_session(clientssl))) goto end; shutdown_ssl_connection(serverssl, clientssl); serverssl = clientssl = NULL; /* Resume, preferring a different cipher. Our server will force the * same cipher to be used as the initial handshake. */ if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(SSL_set_session(clientssl, sess)) || !TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384:AES128-GCM-SHA256")) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_true(SSL_session_reused(clientssl)) || !TEST_true(SSL_session_reused(serverssl)) || !TEST_ptr(sesspost = SSL_get0_session(serverssl)) || !TEST_ptr_eq(sesspre, sesspost) || !TEST_int_eq(TLS1_CK_RSA_WITH_AES_128_GCM_SHA256, SSL_CIPHER_get_id(SSL_get_current_cipher(clientssl)))) goto end; shutdown_ssl_connection(serverssl, clientssl); serverssl = clientssl = NULL; /* * Now create a fresh connection and try to renegotiate a different * cipher on it. */ if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(SSL_set_cipher_list(clientssl, "AES128-GCM-SHA256")) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_ptr(sesspre = SSL_get0_session(serverssl)) || !TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384")) || !TEST_true(SSL_renegotiate(clientssl)) || !TEST_true(SSL_renegotiate_pending(clientssl))) goto end; /* Actually drive the renegotiation. */ for (i = 0; i < 3; i++) { if (SSL_read_ex(clientssl, &buf, sizeof(buf), &readbytes) > 0) { if (!TEST_ulong_eq(readbytes, 0)) goto end; } else if (!TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_WANT_READ)) { goto end; } if (SSL_read_ex(serverssl, &buf, sizeof(buf), &readbytes) > 0) { if (!TEST_ulong_eq(readbytes, 0)) goto end; } else if (!TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_WANT_READ)) { goto end; } } /* sesspre and sesspost should be different since the cipher changed. */ if (!TEST_false(SSL_renegotiate_pending(clientssl)) || !TEST_false(SSL_session_reused(clientssl)) || !TEST_false(SSL_session_reused(serverssl)) || !TEST_ptr(sesspost = SSL_get0_session(serverssl)) || !TEST_ptr_ne(sesspre, sesspost) || !TEST_int_eq(TLS1_CK_RSA_WITH_AES_256_GCM_SHA384, SSL_CIPHER_get_id(SSL_get_current_cipher(clientssl)))) goto end; shutdown_ssl_connection(serverssl, clientssl); serverssl = clientssl = NULL; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); SSL_SESSION_free(sess); return testresult; } #endif static int execute_test_large_message(const SSL_METHOD *smeth, const SSL_METHOD *cmeth, int min_version, int max_version, int read_ahead) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, min_version, max_version, &sctx, &cctx, cert, privkey))) goto end; #ifdef OPENSSL_NO_DTLS1_2 if (smeth == DTLS_server_method()) { /* * Default sigalgs are SHA1 based in rlayer.wrl->sequence, SEQ_NUM_SIZE); memcpy(srec_wseq_before, &serversc->rlayer.wrl->sequence, SEQ_NUM_SIZE); memcpy(crec_rseq_before, &clientsc->rlayer.rrl->sequence, SEQ_NUM_SIZE); memcpy(srec_rseq_before, &serversc->rlayer.rrl->sequence, SEQ_NUM_SIZE); if (!TEST_true(SSL_write(clientssl, cbuf, sizeof(cbuf)) == sizeof(cbuf))) goto end; while ((err = SSL_read(serverssl, &sbuf, sizeof(sbuf))) != sizeof(sbuf)) { if (SSL_get_error(serverssl, err) != SSL_ERROR_WANT_READ) { goto end; } } if (!TEST_true(SSL_write(serverssl, sbuf, sizeof(sbuf)) == sizeof(sbuf))) goto end; while ((err = SSL_read(clientssl, &cbuf, sizeof(cbuf))) != sizeof(cbuf)) { if (SSL_get_error(clientssl, err) != SSL_ERROR_WANT_READ) { goto end; } } memcpy(crec_wseq_after, &clientsc->rlayer.wrl->sequence, SEQ_NUM_SIZE); memcpy(srec_wseq_after, &serversc->rlayer.wrl->sequence, SEQ_NUM_SIZE); memcpy(crec_rseq_after, &clientsc->rlayer.rrl->sequence, SEQ_NUM_SIZE); memcpy(srec_rseq_after, &serversc->rlayer.rrl->sequence, SEQ_NUM_SIZE); /* verify the payload */ if (!TEST_mem_eq(cbuf, sizeof(cbuf), sbuf, sizeof(sbuf))) goto end; /* * If ktls is used then kernel sequences are used instead of * OpenSSL sequences */ if (!BIO_get_ktls_send(clientsc->wbio)) { if (!TEST_mem_ne(crec_wseq_before, SEQ_NUM_SIZE, crec_wseq_after, SEQ_NUM_SIZE)) goto end; } else { if (!TEST_mem_eq(crec_wseq_before, SEQ_NUM_SIZE, crec_wseq_after, SEQ_NUM_SIZE)) goto end; } if (!BIO_get_ktls_send(serversc->wbio)) { if (!TEST_mem_ne(srec_wseq_before, SEQ_NUM_SIZE, srec_wseq_after, SEQ_NUM_SIZE)) goto end; } else { if (!TEST_mem_eq(srec_wseq_before, SEQ_NUM_SIZE, srec_wseq_after, SEQ_NUM_SIZE)) goto end; } if (!BIO_get_ktls_recv(clientsc->wbio)) { if (!TEST_mem_ne(crec_rseq_before, SEQ_NUM_SIZE, crec_rseq_after, SEQ_NUM_SIZE)) goto end; } else { if (!TEST_mem_eq(crec_rseq_before, SEQ_NUM_SIZE, crec_rseq_after, SEQ_NUM_SIZE)) goto end; } if (!BIO_get_ktls_recv(serversc->wbio)) { if (!TEST_mem_ne(srec_rseq_before, SEQ_NUM_SIZE, srec_rseq_after, SEQ_NUM_SIZE)) goto end; } else { if (!TEST_mem_eq(srec_rseq_before, SEQ_NUM_SIZE, srec_rseq_after, SEQ_NUM_SIZE)) goto end; } return 1; end: return 0; } static int execute_test_ktls(int cis_ktls, int sis_ktls, int tls_version, const char *cipher) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int ktls_used = 0, testresult = 0; int cfd = -1, sfd = -1; int rx_supported; SSL_CONNECTION *clientsc, *serversc; unsigned char *buf = NULL; const size_t bufsz = SSL3_RT_MAX_PLAIN_LENGTH + 16; int ret; size_t offset = 0, i; if (!TEST_true(create_test_sockets(&cfd, &sfd, SOCK_STREAM, NULL))) goto end; /* Skip this test if the platform does not support ktls */ if (!ktls_chk_platform(cfd)) { testresult = TEST_skip("Kernel does not support KTLS"); goto end; } if (is_fips && strstr(cipher, "CHACHA") != NULL) { testresult = TEST_skip("CHACHA is not supported in FIPS"); goto end; } /* Create a session based on SHA-256 */ if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), tls_version, tls_version, &sctx, &cctx, cert, privkey))) goto end; if (tls_version == TLS1_3_VERSION) { if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, cipher)) || !TEST_true(SSL_CTX_set_ciphersuites(sctx, cipher))) goto end; } else { if (!TEST_true(SSL_CTX_set_cipher_list(cctx, cipher)) || !TEST_true(SSL_CTX_set_cipher_list(sctx, cipher))) goto end; } if (!TEST_true(create_ssl_objects2(sctx, cctx, &serverssl, &clientssl, sfd, cfd))) goto end; if (!TEST_ptr(clientsc = SSL_CONNECTION_FROM_SSL_ONLY(clientssl)) || !TEST_ptr(serversc = SSL_CONNECTION_FROM_SSL_ONLY(serverssl))) goto end; if (cis_ktls) { if (!TEST_true(SSL_set_options(clientssl, SSL_OP_ENABLE_KTLS))) goto end; } if (sis_ktls) { if (!TEST_true(SSL_set_options(serverssl, SSL_OP_ENABLE_KTLS))) goto end; } if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; /* * The running kernel may not support a given cipher suite * or direction, so just check that KTLS isn't used when it * isn't enabled. */ if (!cis_ktls) { if (!TEST_false(BIO_get_ktls_send(clientsc->wbio))) goto end; } else { if (BIO_get_ktls_send(clientsc->wbio)) ktls_used = 1; } if (!sis_ktls) { if (!TEST_false(BIO_get_ktls_send(serversc->wbio))) goto end; } else { if (BIO_get_ktls_send(serversc->wbio)) ktls_used = 1; } #if defined(OPENSSL_NO_KTLS_RX) rx_supported = 0; #else rx_supported = 1; #endif if (!cis_ktls || !rx_supported) { if (!TEST_false(BIO_get_ktls_recv(clientsc->rbio))) goto end; } else { if (BIO_get_ktls_send(clientsc->rbio)) ktls_used = 1; } if (!sis_ktls || !rx_supported) { if (!TEST_false(BIO_get_ktls_recv(serversc->rbio))) goto end; } else { if (BIO_get_ktls_send(serversc->rbio)) ktls_used = 1; } if ((cis_ktls || sis_ktls) && !ktls_used) { testresult = TEST_skip("KTLS not supported for %s cipher %s", tls_version == TLS1_3_VERSION ? "TLS 1.3" : "TLS 1.2", cipher); goto end; } if (!TEST_true(ping_pong_query(clientssl, serverssl))) goto end; buf = OPENSSL_zalloc(bufsz); if (!TEST_ptr(buf)) goto end; /* * Write some data that exceeds the maximum record length. KTLS may choose * to coalesce this data into a single buffer when we read it again. */ while ((ret = SSL_write(clientssl, buf, bufsz)) != (int)bufsz) { if (!TEST_true(SSL_get_error(clientssl, ret) == SSL_ERROR_WANT_WRITE)) goto end; } /* Now check that we can read all the data we wrote */ do { ret = SSL_read(serverssl, buf + offset, bufsz - offset); if (ret <= 0) { if (!TEST_true(SSL_get_error(serverssl, ret) == SSL_ERROR_WANT_READ)) goto end; } else { offset += ret; } } while (offset < bufsz); if (!TEST_true(offset == bufsz)) goto end; for (i = 0; i < bufsz; i++) if (!TEST_true(buf[i] == 0)) goto end; testresult = 1; end: OPENSSL_free(buf); if (clientssl) { SSL_shutdown(clientssl); SSL_free(clientssl); } if (serverssl) { SSL_shutdown(serverssl); SSL_free(serverssl); } SSL_CTX_free(sctx); SSL_CTX_free(cctx); serverssl = clientssl = NULL; if (cfd != -1) close(cfd); if (sfd != -1) close(sfd); return testresult; } #define SENDFILE_SZ (16 * 4096) #define SENDFILE_CHUNK (4 * 4096) #define min(a,b) ((a) > (b) ? (b) : (a)) static int execute_test_ktls_sendfile(int tls_version, const char *cipher, int zerocopy) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; unsigned char *buf, *buf_dst; BIO *out = NULL, *in = NULL; int cfd = -1, sfd = -1, ffd, err; ssize_t chunk_size = 0; off_t chunk_off = 0; int testresult = 0; FILE *ffdp; SSL_CONNECTION *serversc; buf = OPENSSL_zalloc(SENDFILE_SZ); buf_dst = OPENSSL_zalloc(SENDFILE_SZ); if (!TEST_ptr(buf) || !TEST_ptr(buf_dst) || !TEST_true(create_test_sockets(&cfd, &sfd, SOCK_STREAM, NULL))) goto end; /* Skip this test if the platform does not support ktls */ if (!ktls_chk_platform(sfd)) { testresult = TEST_skip("Kernel does not support KTLS"); goto end; } if (is_fips && strstr(cipher, "CHACHA") != NULL) { testresult = TEST_skip("CHACHA is not supported in FIPS"); goto end; } /* Create a session based on SHA-256 */ if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), tls_version, tls_version, &sctx, &cctx, cert, privkey))) goto end; if (tls_version == TLS1_3_VERSION) { if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, cipher)) || !TEST_true(SSL_CTX_set_ciphersuites(sctx, cipher))) goto end; } else { if (!TEST_true(SSL_CTX_set_cipher_list(cctx, cipher)) || !TEST_true(SSL_CTX_set_cipher_list(sctx, cipher))) goto end; } if (!TEST_true(create_ssl_objects2(sctx, cctx, &serverssl, &clientssl, sfd, cfd))) goto end; if (!TEST_ptr(serversc = SSL_CONNECTION_FROM_SSL_ONLY(serverssl))) goto end; if (!TEST_true(SSL_set_options(serverssl, SSL_OP_ENABLE_KTLS))) goto end; if (zerocopy) { if (!TEST_true(SSL_set_options(serverssl, SSL_OP_ENABLE_KTLS_TX_ZEROCOPY_SENDFILE))) goto end; } if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; if (!BIO_get_ktls_send(serversc->wbio)) { testresult = TEST_skip("Failed to enable KTLS for %s cipher %s", tls_version == TLS1_3_VERSION ? "TLS 1.3" : "TLS 1.2", cipher); goto end; } if (!TEST_int_gt(RAND_bytes_ex(libctx, buf, SENDFILE_SZ, 0), 0)) goto end; out = BIO_new_file(tmpfilename, "wb"); if (!TEST_ptr(out)) goto end; if (BIO_write(out, buf, SENDFILE_SZ) != SENDFILE_SZ) goto end; BIO_free(out); out = NULL; in = BIO_new_file(tmpfilename, "rb"); BIO_get_fp(in, &ffdp); ffd = fileno(ffdp); while (chunk_off < SENDFILE_SZ) { chunk_size = min(SENDFILE_CHUNK, SENDFILE_SZ - chunk_off); while ((err = SSL_sendfile(serverssl, ffd, chunk_off, chunk_size, 0)) != chunk_size) { if (SSL_get_error(serverssl, err) != SSL_ERROR_WANT_WRITE) goto end; } while ((err = SSL_read(clientssl, buf_dst + chunk_off, chunk_size)) != chunk_size) { if (SSL_get_error(clientssl, err) != SSL_ERROR_WANT_READ) goto end; } /* verify the payload */ if (!TEST_mem_eq(buf_dst + chunk_off, chunk_size, buf + chunk_off, chunk_size)) goto end; chunk_off += chunk_size; } testresult = 1; end: if (clientssl) { SSL_shutdown(clientssl); SSL_free(clientssl); } if (serverssl) { SSL_shutdown(serverssl); SSL_free(serverssl); } SSL_CTX_free(sctx); SSL_CTX_free(cctx); serverssl = clientssl = NULL; BIO_free(out); BIO_free(in); if (cfd != -1) close(cfd); if (sfd != -1) close(sfd); OPENSSL_free(buf); OPENSSL_free(buf_dst); return testresult; } static struct ktls_test_cipher { int tls_version; const char *cipher; } ktls_test_ciphers[] = { # if !defined(OPENSSL_NO_TLS1_2) # ifdef OPENSSL_KTLS_AES_GCM_128 { TLS1_2_VERSION, "AES128-GCM-SHA256" }, # endif # ifdef OPENSSL_KTLS_AES_CCM_128 { TLS1_2_VERSION, "AES128-CCM"}, # endif # ifdef OPENSSL_KTLS_AES_GCM_256 { TLS1_2_VERSION, "AES256-GCM-SHA384"}, # endif # ifdef OPENSSL_KTLS_CHACHA20_POLY1305 # ifndef OPENSSL_NO_EC { TLS1_2_VERSION, "ECDHE-RSA-CHACHA20-POLY1305"}, # endif # endif # endif # if !defined(OSSL_NO_USABLE_TLS1_3) # ifdef OPENSSL_KTLS_AES_GCM_128 { TLS1_3_VERSION, "TLS_AES_128_GCM_SHA256" }, # endif # ifdef OPENSSL_KTLS_AES_CCM_128 { TLS1_3_VERSION, "TLS_AES_128_CCM_SHA256" }, # endif # ifdef OPENSSL_KTLS_AES_GCM_256 { TLS1_3_VERSION, "TLS_AES_256_GCM_SHA384" }, # endif # ifdef OPENSSL_KTLS_CHACHA20_POLY1305 { TLS1_3_VERSION, "TLS_CHACHA20_POLY1305_SHA256" }, # endif # endif }; #define NUM_KTLS_TEST_CIPHERS OSSL_NELEM(ktls_test_ciphers) static int test_ktls(int test) { struct ktls_test_cipher *cipher; int cis_ktls, sis_ktls; OPENSSL_assert(test / 4 < (int)NUM_KTLS_TEST_CIPHERS); cipher = &ktls_test_ciphers[test / 4]; cis_ktls = (test & 1) != 0; sis_ktls = (test & 2) != 0; return execute_test_ktls(cis_ktls, sis_ktls, cipher->tls_version, cipher->cipher); } static int test_ktls_sendfile(int test) { struct ktls_test_cipher *cipher; int tst = test >> 1; OPENSSL_assert(tst < (int)NUM_KTLS_TEST_CIPHERS); cipher = &ktls_test_ciphers[tst]; return execute_test_ktls_sendfile(cipher->tls_version, cipher->cipher, test & 1); } #endif static int test_large_message_tls(void) { return execute_test_large_message(TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, 0); } static int test_large_message_tls_read_ahead(void) { return execute_test_large_message(TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, 1); } #ifndef OPENSSL_NO_DTLS static int test_large_message_dtls(void) { # ifdef OPENSSL_NO_DTLS1_2 /* Not supported in the FIPS provider */ if (is_fips) return 1; # endif /* * read_ahead is not relevant to DTLS because DTLS always acts as if * read_ahead is set. */ return execute_test_large_message(DTLS_server_method(), DTLS_client_method(), DTLS1_VERSION, 0, 0); } #endif /* * Test we can successfully send the maximum amount of application data. We * test each protocol version individually, each with and without EtM enabled. * TLSv1.3 doesn't use EtM so technically it is redundant to test both but it is * simpler this way. We also test all combinations with and without the * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS option which affects the size of the * underlying buffer. */ static int test_large_app_data(int tst) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0, prot; unsigned char *msg, *buf = NULL; size_t written, readbytes; const SSL_METHOD *smeth = TLS_server_method(); const SSL_METHOD *cmeth = TLS_client_method(); switch (tst >> 2) { case 0: #ifndef OSSL_NO_USABLE_TLS1_3 prot = TLS1_3_VERSION; break; #else return TEST_skip("TLS 1.3 not supported"); #endif case 1: #ifndef OPENSSL_NO_TLS1_2 prot = TLS1_2_VERSION; break; #else return TEST_skip("TLS 1.2 not supported"); #endif case 2: #ifndef OPENSSL_NO_TLS1_1 prot = TLS1_1_VERSION; break; #else return TEST_skip("TLS 1.1 not supported"); #endif case 3: #ifndef OPENSSL_NO_TLS1 prot = TLS1_VERSION; break; #else return TEST_skip("TLS 1 not supported"); #endif case 4: #ifndef OPENSSL_NO_SSL3 prot = SSL3_VERSION; break; #else return TEST_skip("SSL 3 not supported"); #endif case 5: #ifndef OPENSSL_NO_DTLS1_2 prot = DTLS1_2_VERSION; smeth = DTLS_server_method(); cmeth = DTLS_client_method(); break; #else return TEST_skip("DTLS 1.2 not supported"); #endif case 6: #ifndef OPENSSL_NO_DTLS1 if (is_fips) return TEST_skip("DTLS 1 not supported by FIPS provider"); prot = DTLS1_VERSION; smeth = DTLS_server_method(); cmeth = DTLS_client_method(); break; #else return TEST_skip("DTLS 1 not supported"); #endif default: /* Shouldn't happen */ return 0; } if (is_fips && prot < TLS1_2_VERSION) return TEST_skip("TLS versions < 1.2 not supported by FIPS provider"); /* Maximal sized message of zeros */ msg = OPENSSL_zalloc(SSL3_RT_MAX_PLAIN_LENGTH); if (!TEST_ptr(msg)) goto end; buf = OPENSSL_malloc(SSL3_RT_MAX_PLAIN_LENGTH + 1); if (!TEST_ptr(buf)) goto end; /* Set whole buffer to all bits set */ memset(buf, 0xff, SSL3_RT_MAX_PLAIN_LENGTH + 1); if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, prot, prot, &sctx, &cctx, cert, privkey))) goto end; if (prot < TLS1_2_VERSION || prot == DTLS1_VERSION) { /* Older protocol versions need SECLEVEL=0 due to SHA1 usage */ if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "DEFAULT:@SECLEVEL=0")) || !TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))) goto end; } if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if ((tst & 1) != 0) { /* Setting this option gives us a minimally sized underlying buffer */ if (!TEST_true(SSL_set_options(serverssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)) || !TEST_true(SSL_set_options(clientssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS))) goto end; } if ((tst & 2) != 0) { /* * Setting this option means the MAC is added before encryption * giving us a larger record for the encryption process */ if (!TEST_true(SSL_set_options(serverssl, SSL_OP_NO_ENCRYPT_THEN_MAC)) || !TEST_true(SSL_set_options(clientssl, SSL_OP_NO_ENCRYPT_THEN_MAC))) goto end; } if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; if (!TEST_true(SSL_write_ex(clientssl, msg, SSL3_RT_MAX_PLAIN_LENGTH, &written)) || !TEST_size_t_eq(written, SSL3_RT_MAX_PLAIN_LENGTH)) goto end; /* We provide a buffer slightly larger than what we are actually expecting */ if (!TEST_true(SSL_read_ex(serverssl, buf, SSL3_RT_MAX_PLAIN_LENGTH + 1, &readbytes))) goto end; if (!TEST_mem_eq(msg, written, buf, readbytes)) goto end; testresult = 1; end: OPENSSL_free(msg); OPENSSL_free(buf); SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3) \ || !defined(OPENSSL_NO_DTLS) static int execute_cleanse_plaintext(const SSL_METHOD *smeth, const SSL_METHOD *cmeth, int min_version, int max_version) { size_t i; SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; const unsigned char *zbuf; SSL_CONNECTION *serversc; TLS_RECORD *rr; static unsigned char cbuf[16000]; static unsigned char sbuf[16000]; if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, min_version, max_version, &sctx, &cctx, cert, privkey))) goto end; # ifdef OPENSSL_NO_DTLS1_2 if (smeth == DTLS_server_method()) { /* Not supported in the FIPS provider */ if (is_fips) { testresult = 1; goto end; }; /* * Default sigalgs are SHA1 based in rlayer.tlsrecs; zbuf = &rr->data[rr->off]; if (!TEST_int_eq(rr->length, sizeof(cbuf))) goto end; /* * After SSL_peek() the plaintext must still be stored in the * record. */ if (!TEST_mem_eq(cbuf, sizeof(cbuf), zbuf, sizeof(cbuf))) goto end; memset(sbuf, 0, sizeof(sbuf)); if (!TEST_int_eq(SSL_read(serverssl, &sbuf, sizeof(sbuf)), sizeof(sbuf))) goto end; if (!TEST_mem_eq(cbuf, sizeof(cbuf), sbuf, sizeof(cbuf))) goto end; /* Check if rbuf is cleansed */ memset(cbuf, 0, sizeof(cbuf)); if (!TEST_mem_eq(cbuf, sizeof(cbuf), zbuf, sizeof(cbuf))) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #endif /* * !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3) * || !defined(OPENSSL_NO_DTLS) */ static int test_cleanse_plaintext(void) { #if !defined(OPENSSL_NO_TLS1_2) if (!TEST_true(execute_cleanse_plaintext(TLS_server_method(), TLS_client_method(), TLS1_2_VERSION, TLS1_2_VERSION))) return 0; #endif #if !defined(OSSL_NO_USABLE_TLS1_3) if (!TEST_true(execute_cleanse_plaintext(TLS_server_method(), TLS_client_method(), TLS1_3_VERSION, TLS1_3_VERSION))) return 0; #endif #if !defined(OPENSSL_NO_DTLS) if (!TEST_true(execute_cleanse_plaintext(DTLS_server_method(), DTLS_client_method(), DTLS1_VERSION, 0))) return 0; #endif return 1; } #ifndef OPENSSL_NO_OCSP static int ocsp_server_cb(SSL *s, void *arg) { int *argi = (int *)arg; unsigned char *copy = NULL; STACK_OF(OCSP_RESPID) *ids = NULL; OCSP_RESPID *id = NULL; if (*argi == 2) { /* In this test we are expecting exactly 1 OCSP_RESPID */ SSL_get_tlsext_status_ids(s, &ids); if (ids == NULL || sk_OCSP_RESPID_num(ids) != 1) return SSL_TLSEXT_ERR_ALERT_FATAL; id = sk_OCSP_RESPID_value(ids, 0); if (id == NULL || !OCSP_RESPID_match_ex(id, ocspcert, libctx, NULL)) return SSL_TLSEXT_ERR_ALERT_FATAL; } else if (*argi != 1) { return SSL_TLSEXT_ERR_ALERT_FATAL; } if (!TEST_ptr(copy = OPENSSL_memdup(orespder, sizeof(orespder)))) return SSL_TLSEXT_ERR_ALERT_FATAL; if (!TEST_true(SSL_set_tlsext_status_ocsp_resp(s, copy, sizeof(orespder)))) { OPENSSL_free(copy); return SSL_TLSEXT_ERR_ALERT_FATAL; } ocsp_server_called = 1; return SSL_TLSEXT_ERR_OK; } static int ocsp_client_cb(SSL *s, void *arg) { int *argi = (int *)arg; const unsigned char *respderin; size_t len; if (*argi != 1 && *argi != 2) return 0; len = SSL_get_tlsext_status_ocsp_resp(s, &respderin); if (!TEST_mem_eq(orespder, len, respderin, len)) return 0; ocsp_client_called = 1; return 1; } static int test_tlsext_status_type(void) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; STACK_OF(OCSP_RESPID) *ids = NULL; OCSP_RESPID *id = NULL; BIO *certbio = NULL; if (!create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey)) return 0; if (SSL_CTX_get_tlsext_status_type(cctx) != -1) goto end; /* First just do various checks getting and setting tlsext_status_type */ clientssl = SSL_new(cctx); if (!TEST_ptr(clientssl)) goto end; if (!TEST_int_eq(SSL_get_tlsext_status_type(clientssl), -1) || !TEST_true(SSL_set_tlsext_status_type(clientssl, TLSEXT_STATUSTYPE_ocsp)) || !TEST_int_eq(SSL_get_tlsext_status_type(clientssl), TLSEXT_STATUSTYPE_ocsp)) goto end; SSL_free(clientssl); clientssl = NULL; if (!SSL_CTX_set_tlsext_status_type(cctx, TLSEXT_STATUSTYPE_ocsp) || SSL_CTX_get_tlsext_status_type(cctx) != TLSEXT_STATUSTYPE_ocsp) goto end; clientssl = SSL_new(cctx); if (!TEST_ptr(clientssl)) goto end; if (SSL_get_tlsext_status_type(clientssl) != TLSEXT_STATUSTYPE_ocsp) goto end; SSL_free(clientssl); clientssl = NULL; /* * Now actually do a handshake and check OCSP information is exchanged and * the callbacks get called */ SSL_CTX_set_tlsext_status_cb(cctx, ocsp_client_cb); SSL_CTX_set_tlsext_status_arg(cctx, &cdummyarg); SSL_CTX_set_tlsext_status_cb(sctx, ocsp_server_cb); SSL_CTX_set_tlsext_status_arg(sctx, &cdummyarg); if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_true(ocsp_client_called) || !TEST_true(ocsp_server_called)) goto end; SSL_free(serverssl); SSL_free(clientssl); serverssl = NULL; clientssl = NULL; /* Try again but this time force the server side callback to fail */ ocsp_client_called = 0; ocsp_server_called = 0; cdummyarg = 0; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) /* This should fail because the callback will fail */ || !TEST_false(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_false(ocsp_client_called) || !TEST_false(ocsp_server_called)) goto end; SSL_free(serverssl); SSL_free(clientssl); serverssl = NULL; clientssl = NULL; /* * This time we'll get the client to send an OCSP_RESPID that it will * accept. */ ocsp_client_called = 0; ocsp_server_called = 0; cdummyarg = 2; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; /* * We'll just use any old cert for this test - it doesn't have to be an OCSP * specific one. We'll use the server cert. */ if (!TEST_ptr(certbio = BIO_new_file(cert, "r")) || !TEST_ptr(id = OCSP_RESPID_new()) || !TEST_ptr(ids = sk_OCSP_RESPID_new_null()) || !TEST_ptr(ocspcert = X509_new_ex(libctx, NULL)) || !TEST_ptr(PEM_read_bio_X509(certbio, &ocspcert, NULL, NULL)) || !TEST_true(OCSP_RESPID_set_by_key_ex(id, ocspcert, libctx, NULL)) || !TEST_true(sk_OCSP_RESPID_push(ids, id))) goto end; id = NULL; SSL_set_tlsext_status_ids(clientssl, ids); /* Control has been transferred */ ids = NULL; BIO_free(certbio); certbio = NULL; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_true(ocsp_client_called) || !TEST_true(ocsp_server_called)) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); sk_OCSP_RESPID_pop_free(ids, OCSP_RESPID_free); OCSP_RESPID_free(id); BIO_free(certbio); X509_free(ocspcert); ocspcert = NULL; return testresult; } #endif #if !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2) static int new_called, remove_called, get_called; static int new_session_cb(SSL *ssl, SSL_SESSION *sess) { new_called++; /* * sess has been up-refed for us, but we don't actually need it so free it * immediately. */ SSL_SESSION_free(sess); return 1; } static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *sess) { remove_called++; } static SSL_SESSION *get_sess_val = NULL; static SSL_SESSION *get_session_cb(SSL *ssl, const unsigned char *id, int len, int *copy) { get_called++; *copy = 1; return get_sess_val; } static int execute_test_session(int maxprot, int use_int_cache, int use_ext_cache, long s_options) { SSL_CTX *sctx = NULL, *cctx = NULL; SSL *serverssl1 = NULL, *clientssl1 = NULL; SSL *serverssl2 = NULL, *clientssl2 = NULL; # ifndef OPENSSL_NO_TLS1_1 SSL *serverssl3 = NULL, *clientssl3 = NULL; # endif SSL_SESSION *sess1 = NULL, *sess2 = NULL; int testresult = 0, numnewsesstick = 1; new_called = remove_called = 0; /* TLSv1.3 sends 2 NewSessionTickets */ if (maxprot == TLS1_3_VERSION) numnewsesstick = 2; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey))) return 0; /* * Only allow the max protocol version so we can force a connection failure * later */ SSL_CTX_set_min_proto_version(cctx, maxprot); SSL_CTX_set_max_proto_version(cctx, maxprot); /* Set up session cache */ if (use_ext_cache) { SSL_CTX_sess_set_new_cb(cctx, new_session_cb); SSL_CTX_sess_set_remove_cb(cctx, remove_session_cb); } if (use_int_cache) { /* Also covers instance where both are set */ SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT); } else { SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE); } if (s_options) { SSL_CTX_set_options(sctx, s_options); } if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl1, clientssl1, SSL_ERROR_NONE)) || !TEST_ptr(sess1 = SSL_get1_session(clientssl1))) goto end; /* Should fail because it should already be in the cache */ if (use_int_cache && !TEST_false(SSL_CTX_add_session(cctx, sess1))) goto end; if (use_ext_cache && (!TEST_int_eq(new_called, numnewsesstick) || !TEST_int_eq(remove_called, 0))) goto end; new_called = remove_called = 0; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2, &clientssl2, NULL, NULL)) || !TEST_true(SSL_set_session(clientssl2, sess1)) || !TEST_true(create_ssl_connection(serverssl2, clientssl2, SSL_ERROR_NONE)) || !TEST_true(SSL_session_reused(clientssl2))) goto end; if (maxprot == TLS1_3_VERSION) { /* * In TLSv1.3 we should have created a new session even though we have * resumed. Since we attempted a resume we should also have removed the * old ticket from the cache so that we try to only use tickets once. */ if (use_ext_cache && (!TEST_int_eq(new_called, 1) || !TEST_int_eq(remove_called, 1))) goto end; } else { /* * In TLSv1.2 we expect to have resumed so no sessions added or * removed. */ if (use_ext_cache && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 0))) goto end; } SSL_SESSION_free(sess1); if (!TEST_ptr(sess1 = SSL_get1_session(clientssl2))) goto end; shutdown_ssl_connection(serverssl2, clientssl2); serverssl2 = clientssl2 = NULL; new_called = remove_called = 0; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2, &clientssl2, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl2, clientssl2, SSL_ERROR_NONE))) goto end; if (!TEST_ptr(sess2 = SSL_get1_session(clientssl2))) goto end; if (use_ext_cache && (!TEST_int_eq(new_called, numnewsesstick) || !TEST_int_eq(remove_called, 0))) goto end; new_called = remove_called = 0; /* * This should clear sess2 from the cache because it is a "bad" session. * See SSL_set_session() documentation. */ if (!TEST_true(SSL_set_session(clientssl2, sess1))) goto end; if (use_ext_cache && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1))) goto end; if (!TEST_ptr_eq(SSL_get_session(clientssl2), sess1)) goto end; if (use_int_cache) { /* Should succeeded because it should not already be in the cache */ if (!TEST_true(SSL_CTX_add_session(cctx, sess2)) || !TEST_true(SSL_CTX_remove_session(cctx, sess2))) goto end; } new_called = remove_called = 0; /* This shouldn't be in the cache so should fail */ if (!TEST_false(SSL_CTX_remove_session(cctx, sess2))) goto end; if (use_ext_cache && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1))) goto end; # if !defined(OPENSSL_NO_TLS1_1) new_called = remove_called = 0; /* Force a connection failure */ SSL_CTX_set_max_proto_version(sctx, TLS1_1_VERSION); if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl3, &clientssl3, NULL, NULL)) || !TEST_true(SSL_set_session(clientssl3, sess1)) /* This should fail because of the mismatched protocol versions */ || !TEST_false(create_ssl_connection(serverssl3, clientssl3, SSL_ERROR_NONE))) goto end; /* We should have automatically removed the session from the cache */ if (use_ext_cache && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1))) goto end; /* Should succeed because it should not already be in the cache */ if (use_int_cache && !TEST_true(SSL_CTX_add_session(cctx, sess2))) goto end; # endif /* Now do some tests for server side caching */ if (use_ext_cache) { SSL_CTX_sess_set_new_cb(cctx, NULL); SSL_CTX_sess_set_remove_cb(cctx, NULL); SSL_CTX_sess_set_new_cb(sctx, new_session_cb); SSL_CTX_sess_set_remove_cb(sctx, remove_session_cb); SSL_CTX_sess_set_get_cb(sctx, get_session_cb); get_sess_val = NULL; } SSL_CTX_set_session_cache_mode(cctx, 0); /* Internal caching is the default on the server side */ if (!use_int_cache) SSL_CTX_set_session_cache_mode(sctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_INTERNAL_STORE); SSL_free(serverssl1); SSL_free(clientssl1); serverssl1 = clientssl1 = NULL; SSL_free(serverssl2); SSL_free(clientssl2); serverssl2 = clientssl2 = NULL; SSL_SESSION_free(sess1); sess1 = NULL; SSL_SESSION_free(sess2); sess2 = NULL; SSL_CTX_set_max_proto_version(sctx, maxprot); if (maxprot == TLS1_2_VERSION) SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET); new_called = remove_called = get_called = 0; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl1, clientssl1, SSL_ERROR_NONE)) || !TEST_ptr(sess1 = SSL_get1_session(clientssl1)) || !TEST_ptr(sess2 = SSL_get1_session(serverssl1))) goto end; if (use_int_cache) { if (maxprot == TLS1_3_VERSION && !use_ext_cache) { /* * In TLSv1.3 it should not have been added to the internal cache, * except in the case where we also have an external cache (in that * case it gets added to the cache in order to generate remove * events after timeout). */ if (!TEST_false(SSL_CTX_remove_session(sctx, sess2))) goto end; } else { /* Should fail because it should already be in the cache */ if (!TEST_false(SSL_CTX_add_session(sctx, sess2))) goto end; } } if (use_ext_cache) { SSL_SESSION *tmp = sess2; if (!TEST_int_eq(new_called, numnewsesstick) || !TEST_int_eq(remove_called, 0) || !TEST_int_eq(get_called, 0)) goto end; /* * Delete the session from the internal cache to force a lookup from * the external cache. We take a copy first because * SSL_CTX_remove_session() also marks the session as non-resumable. */ if (use_int_cache && maxprot != TLS1_3_VERSION) { if (!TEST_ptr(tmp = SSL_SESSION_dup(sess2)) || !TEST_true(sess2->owner != NULL) || !TEST_true(tmp->owner == NULL) || !TEST_true(SSL_CTX_remove_session(sctx, sess2))) goto end; SSL_SESSION_free(sess2); } sess2 = tmp; } new_called = remove_called = get_called = 0; get_sess_val = sess2; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2, &clientssl2, NULL, NULL)) || !TEST_true(SSL_set_session(clientssl2, sess1)) || !TEST_true(create_ssl_connection(serverssl2, clientssl2, SSL_ERROR_NONE)) || !TEST_true(SSL_session_reused(clientssl2))) goto end; if (use_ext_cache) { if (!TEST_int_eq(remove_called, 0)) goto end; if (maxprot == TLS1_3_VERSION) { if (!TEST_int_eq(new_called, 1) || !TEST_int_eq(get_called, 0)) goto end; } else { if (!TEST_int_eq(new_called, 0) || !TEST_int_eq(get_called, 1)) goto end; } } /* * Make a small cache, force out all other sessions but * sess2, try to add sess1, which should succeed. Then * make sure it's there by checking the owners. Despite * the timeouts, sess1 should have kicked out sess2 */ /* Make sess1 expire before sess2 */ if (!TEST_time_t_gt(SSL_SESSION_set_time_ex(sess1, 1000), 0) || !TEST_long_gt(SSL_SESSION_set_timeout(sess1, 1000), 0) || !TEST_time_t_gt(SSL_SESSION_set_time_ex(sess2, 2000), 0) || !TEST_long_gt(SSL_SESSION_set_timeout(sess2, 2000), 0)) goto end; if (!TEST_long_ne(SSL_CTX_sess_set_cache_size(sctx, 1), 0)) goto end; /* Don't care about results - cache should only be sess2 at end */ SSL_CTX_add_session(sctx, sess1); SSL_CTX_add_session(sctx, sess2); /* Now add sess1, and make sure it remains, despite timeout */ if (!TEST_true(SSL_CTX_add_session(sctx, sess1)) || !TEST_ptr(sess1->owner) || !TEST_ptr_null(sess2->owner)) goto end; testresult = 1; end: SSL_free(serverssl1); SSL_free(clientssl1); SSL_free(serverssl2); SSL_free(clientssl2); # ifndef OPENSSL_NO_TLS1_1 SSL_free(serverssl3); SSL_free(clientssl3); # endif SSL_SESSION_free(sess1); SSL_SESSION_free(sess2); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #endif /* !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2) */ static int test_session_with_only_int_cache(void) { #ifndef OSSL_NO_USABLE_TLS1_3 if (!execute_test_session(TLS1_3_VERSION, 1, 0, 0)) return 0; #endif #ifndef OPENSSL_NO_TLS1_2 return execute_test_session(TLS1_2_VERSION, 1, 0, 0); #else return 1; #endif } static int test_session_with_only_ext_cache(void) { #ifndef OSSL_NO_USABLE_TLS1_3 if (!execute_test_session(TLS1_3_VERSION, 0, 1, 0)) return 0; #endif #ifndef OPENSSL_NO_TLS1_2 return execute_test_session(TLS1_2_VERSION, 0, 1, 0); #else return 1; #endif } static int test_session_with_both_cache(void) { #ifndef OSSL_NO_USABLE_TLS1_3 if (!execute_test_session(TLS1_3_VERSION, 1, 1, 0)) return 0; #endif #ifndef OPENSSL_NO_TLS1_2 return execute_test_session(TLS1_2_VERSION, 1, 1, 0); #else return 1; #endif } static int test_session_wo_ca_names(void) { #ifndef OSSL_NO_USABLE_TLS1_3 if (!execute_test_session(TLS1_3_VERSION, 1, 0, SSL_OP_DISABLE_TLSEXT_CA_NAMES)) return 0; #endif #ifndef OPENSSL_NO_TLS1_2 return execute_test_session(TLS1_2_VERSION, 1, 0, SSL_OP_DISABLE_TLSEXT_CA_NAMES); #else return 1; #endif } #ifndef OSSL_NO_USABLE_TLS1_3 static SSL_SESSION *sesscache[6]; static int do_cache; static int new_cachesession_cb(SSL *ssl, SSL_SESSION *sess) { if (do_cache) { sesscache[new_called] = sess; } else { /* We don't need the reference to the session, so free it */ SSL_SESSION_free(sess); } new_called++; return 1; } static int post_handshake_verify(SSL *sssl, SSL *cssl) { SSL_set_verify(sssl, SSL_VERIFY_PEER, NULL); if (!TEST_true(SSL_verify_client_post_handshake(sssl))) return 0; /* Start handshake on the server and client */ if (!TEST_int_eq(SSL_do_handshake(sssl), 1) || !TEST_int_le(SSL_read(cssl, NULL, 0), 0) || !TEST_int_le(SSL_read(sssl, NULL, 0), 0) || !TEST_true(create_ssl_connection(sssl, cssl, SSL_ERROR_NONE))) return 0; return 1; } static int setup_ticket_test(int stateful, int idx, SSL_CTX **sctx, SSL_CTX **cctx) { int sess_id_ctx = 1; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, sctx, cctx, cert, privkey)) || !TEST_true(SSL_CTX_set_num_tickets(*sctx, idx)) || !TEST_true(SSL_CTX_set_session_id_context(*sctx, (void *)&sess_id_ctx, sizeof(sess_id_ctx)))) return 0; if (stateful) SSL_CTX_set_options(*sctx, SSL_OP_NO_TICKET); SSL_CTX_set_session_cache_mode(*cctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE); SSL_CTX_sess_set_new_cb(*cctx, new_cachesession_cb); return 1; } static int check_resumption(int idx, SSL_CTX *sctx, SSL_CTX *cctx, int succ) { SSL *serverssl = NULL, *clientssl = NULL; int i; /* Test that we can resume with all the tickets we got given */ for (i = 0; i < idx * 2; i++) { new_called = 0; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(SSL_set_session(clientssl, sesscache[i]))) goto end; SSL_set_post_handshake_auth(clientssl, 1); if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; /* * Following a successful resumption we only get 1 ticket. After a * failed one we should get idx tickets. */ if (succ) { if (!TEST_true(SSL_session_reused(clientssl)) || !TEST_int_eq(new_called, 1)) goto end; } else { if (!TEST_false(SSL_session_reused(clientssl)) || !TEST_int_eq(new_called, idx)) goto end; } new_called = 0; /* After a post-handshake authentication we should get 1 new ticket */ if (succ && (!post_handshake_verify(serverssl, clientssl) || !TEST_int_eq(new_called, 1))) goto end; SSL_shutdown(clientssl); SSL_shutdown(serverssl); SSL_free(serverssl); SSL_free(clientssl); serverssl = clientssl = NULL; SSL_SESSION_free(sesscache[i]); sesscache[i] = NULL; } return 1; end: SSL_free(clientssl); SSL_free(serverssl); return 0; } static int test_tickets(int stateful, int idx) { SSL_CTX *sctx = NULL, *cctx = NULL; SSL *serverssl = NULL, *clientssl = NULL; int testresult = 0; size_t j; /* idx is the test number, but also the number of tickets we want */ new_called = 0; do_cache = 1; if (!setup_ticket_test(stateful, idx, &sctx, &cctx)) goto end; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) /* Check we got the number of tickets we were expecting */ || !TEST_int_eq(idx, new_called)) goto end; SSL_shutdown(clientssl); SSL_shutdown(serverssl); SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); clientssl = serverssl = NULL; sctx = cctx = NULL; /* * Now we try to resume with the tickets we previously created. The * resumption attempt is expected to fail (because we're now using a new * SSL_CTX). We should see idx number of tickets issued again. */ /* Stop caching sessions - just count them */ do_cache = 0; if (!setup_ticket_test(stateful, idx, &sctx, &cctx)) goto end; if (!check_resumption(idx, sctx, cctx, 0)) goto end; /* Start again with caching sessions */ new_called = 0; do_cache = 1; SSL_CTX_free(sctx); SSL_CTX_free(cctx); sctx = cctx = NULL; if (!setup_ticket_test(stateful, idx, &sctx, &cctx)) goto end; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; SSL_set_post_handshake_auth(clientssl, 1); if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) /* Check we got the number of tickets we were expecting */ || !TEST_int_eq(idx, new_called)) goto end; /* After a post-handshake authentication we should get new tickets issued */ if (!post_handshake_verify(serverssl, clientssl) || !TEST_int_eq(idx * 2, new_called)) goto end; SSL_shutdown(clientssl); SSL_shutdown(serverssl); SSL_free(serverssl); SSL_free(clientssl); serverssl = clientssl = NULL; /* Stop caching sessions - just count them */ do_cache = 0; /* * Check we can resume with all the tickets we created. This time around the * resumptions should all be successful. */ if (!check_resumption(idx, sctx, cctx, 1)) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); for (j = 0; j < OSSL_NELEM(sesscache); j++) { SSL_SESSION_free(sesscache[j]); sesscache[j] = NULL; } SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } static int test_stateless_tickets(int idx) { return test_tickets(0, idx); } static int test_stateful_tickets(int idx) { return test_tickets(1, idx); } static int test_psk_tickets(void) { SSL_CTX *sctx = NULL, *cctx = NULL; SSL *serverssl = NULL, *clientssl = NULL; int testresult = 0; int sess_id_ctx = 1; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, NULL, NULL)) || !TEST_true(SSL_CTX_set_session_id_context(sctx, (void *)&sess_id_ctx, sizeof(sess_id_ctx)))) goto end; SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE); SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb); SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb); SSL_CTX_sess_set_new_cb(cctx, new_session_cb); use_session_cb_cnt = 0; find_session_cb_cnt = 0; srvid = pskid; new_called = 0; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; clientpsk = serverpsk = create_a_psk(clientssl, SHA384_DIGEST_LENGTH); if (!TEST_ptr(clientpsk) || !TEST_true(SSL_SESSION_up_ref(clientpsk))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_int_eq(1, find_session_cb_cnt) || !TEST_int_eq(1, use_session_cb_cnt) /* We should always get 1 ticket when using external PSK */ || !TEST_int_eq(1, new_called)) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); SSL_SESSION_free(clientpsk); SSL_SESSION_free(serverpsk); clientpsk = serverpsk = NULL; return testresult; } static int test_extra_tickets(int idx) { SSL_CTX *sctx = NULL, *cctx = NULL; SSL *serverssl = NULL, *clientssl = NULL; BIO *bretry = BIO_new(bio_s_always_retry()); BIO *tmp = NULL; int testresult = 0; int stateful = 0; size_t nbytes; unsigned char c, buf[1]; new_called = 0; do_cache = 1; if (idx >= 3) { idx -= 3; stateful = 1; } if (!TEST_ptr(bretry) || !setup_ticket_test(stateful, idx, &sctx, &cctx)) goto end; SSL_CTX_sess_set_new_cb(sctx, new_session_cb); /* setup_ticket_test() uses new_cachesession_cb which we don't need. */ SSL_CTX_sess_set_new_cb(cctx, new_session_cb); if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; /* * Note that we have new_session_cb on both sctx and cctx, so new_called is * incremented by both client and server. */ if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) /* Check we got the number of tickets we were expecting */ || !TEST_int_eq(idx * 2, new_called) || !TEST_true(SSL_new_session_ticket(serverssl)) || !TEST_true(SSL_new_session_ticket(serverssl)) || !TEST_int_eq(idx * 2, new_called)) goto end; /* Now try a (real) write to actually send the tickets */ c = '1'; if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes)) || !TEST_size_t_eq(1, nbytes) || !TEST_int_eq(idx * 2 + 2, new_called) || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)) || !TEST_int_eq(idx * 2 + 4, new_called) || !TEST_int_eq(sizeof(buf), nbytes) || !TEST_int_eq(c, buf[0]) || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))) goto end; /* Try with only requesting one new ticket, too */ c = '2'; new_called = 0; if (!TEST_true(SSL_new_session_ticket(serverssl)) || !TEST_true(SSL_write_ex(serverssl, &c, sizeof(c), &nbytes)) || !TEST_size_t_eq(sizeof(c), nbytes) || !TEST_int_eq(1, new_called) || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)) || !TEST_int_eq(2, new_called) || !TEST_size_t_eq(sizeof(buf), nbytes) || !TEST_int_eq(c, buf[0])) goto end; /* Do it again but use dummy writes to drive the ticket generation */ c = '3'; new_called = 0; if (!TEST_true(SSL_new_session_ticket(serverssl)) || !TEST_true(SSL_new_session_ticket(serverssl)) || !TEST_true(SSL_write_ex(serverssl, &c, 0, &nbytes)) || !TEST_size_t_eq(0, nbytes) || !TEST_int_eq(2, new_called) || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)) || !TEST_int_eq(4, new_called)) goto end; /* Once more, but with SSL_do_handshake() to drive the ticket generation */ c = '4'; new_called = 0; if (!TEST_true(SSL_new_session_ticket(serverssl)) || !TEST_true(SSL_new_session_ticket(serverssl)) || !TEST_true(SSL_do_handshake(serverssl)) || !TEST_int_eq(2, new_called) || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)) || !TEST_int_eq(4, new_called)) goto end; /* * Use the always-retry BIO to exercise the logic that forces ticket * generation to wait until a record boundary. */ c = '5'; new_called = 0; tmp = SSL_get_wbio(serverssl); if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) { tmp = NULL; goto end; } SSL_set0_wbio(serverssl, bretry); bretry = NULL; if (!TEST_false(SSL_write_ex(serverssl, &c, 1, &nbytes)) || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_WANT_WRITE) || !TEST_size_t_eq(nbytes, 0)) goto end; /* Restore a BIO that will let the write succeed */ SSL_set0_wbio(serverssl, tmp); tmp = NULL; /* * These calls should just queue the request and not send anything * even if we explicitly try to hit the state machine. */ if (!TEST_true(SSL_new_session_ticket(serverssl)) || !TEST_true(SSL_new_session_ticket(serverssl)) || !TEST_int_eq(0, new_called) || !TEST_true(SSL_do_handshake(serverssl)) || !TEST_int_eq(0, new_called)) goto end; /* Re-do the write; still no tickets sent */ if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes)) || !TEST_size_t_eq(1, nbytes) || !TEST_int_eq(0, new_called) || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)) || !TEST_int_eq(0, new_called) || !TEST_int_eq(sizeof(buf), nbytes) || !TEST_int_eq(c, buf[0]) || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))) goto end; /* Even trying to hit the state machine now will still not send tickets */ if (!TEST_true(SSL_do_handshake(serverssl)) || !TEST_int_eq(0, new_called)) goto end; /* Now the *next* write should send the tickets */ c = '6'; if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes)) || !TEST_size_t_eq(1, nbytes) || !TEST_int_eq(2, new_called) || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)) || !TEST_int_eq(4, new_called) || !TEST_int_eq(sizeof(buf), nbytes) || !TEST_int_eq(c, buf[0]) || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))) goto end; SSL_shutdown(clientssl); SSL_shutdown(serverssl); testresult = 1; end: BIO_free(bretry); BIO_free(tmp); SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); clientssl = serverssl = NULL; sctx = cctx = NULL; return testresult; } #endif #define USE_NULL 0 #define USE_BIO_1 1 #define USE_BIO_2 2 #define USE_DEFAULT 3 #define CONNTYPE_CONNECTION_SUCCESS 0 #define CONNTYPE_CONNECTION_FAIL 1 #define CONNTYPE_NO_CONNECTION 2 #define TOTAL_NO_CONN_SSL_SET_BIO_TESTS (3 * 3 * 3 * 3) #define TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS (2 * 2) #if !defined(OSSL_NO_USABLE_TLS1_3) && !defined(OPENSSL_NO_TLS1_2) # define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS (2 * 2) #else # define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS 0 #endif #define TOTAL_SSL_SET_BIO_TESTS TOTAL_NO_CONN_SSL_SET_BIO_TESTS \ + TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS \ + TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS static void setupbio(BIO **res, BIO *bio1, BIO *bio2, int type) { switch (type) { case USE_NULL: *res = NULL; break; case USE_BIO_1: *res = bio1; break; case USE_BIO_2: *res = bio2; break; } } /* * Tests calls to SSL_set_bio() under various conditions. * * For the first 3 * 3 * 3 * 3 = 81 tests we do 2 calls to SSL_set_bio() with * various combinations of valid BIOs or NULL being set for the rbio/wbio. We * then do more tests where we create a successful connection first using our * standard connection setup functions, and then call SSL_set_bio() with * various combinations of valid BIOs or NULL. We then repeat these tests * following a failed connection. In this last case we are looking to check that * SSL_set_bio() functions correctly in the case where s->bbio is not NULL. */ static int test_ssl_set_bio(int idx) { SSL_CTX *sctx = NULL, *cctx = NULL; BIO *bio1 = NULL; BIO *bio2 = NULL; BIO *irbio = NULL, *iwbio = NULL, *nrbio = NULL, *nwbio = NULL; SSL *serverssl = NULL, *clientssl = NULL; int initrbio, initwbio, newrbio, newwbio, conntype; int testresult = 0; if (idx < TOTAL_NO_CONN_SSL_SET_BIO_TESTS) { initrbio = idx % 3; idx /= 3; initwbio = idx % 3; idx /= 3; newrbio = idx % 3; idx /= 3; newwbio = idx % 3; conntype = CONNTYPE_NO_CONNECTION; } else { idx -= TOTAL_NO_CONN_SSL_SET_BIO_TESTS; initrbio = initwbio = USE_DEFAULT; newrbio = idx % 2; idx /= 2; newwbio = idx % 2; idx /= 2; conntype = idx % 2; } if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey))) goto end; if (conntype == CONNTYPE_CONNECTION_FAIL) { /* * We won't ever get here if either TLSv1.3 or TLSv1.2 is disabled * because we reduced the number of tests in the definition of * TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS to avoid this scenario. By setting * mismatched protocol versions we will force a connection failure. */ SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION); SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION); } if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (initrbio == USE_BIO_1 || initwbio == USE_BIO_1 || newrbio == USE_BIO_1 || newwbio == USE_BIO_1) { if (!TEST_ptr(bio1 = BIO_new(BIO_s_mem()))) goto end; } if (initrbio == USE_BIO_2 || initwbio == USE_BIO_2 || newrbio == USE_BIO_2 || newwbio == USE_BIO_2) { if (!TEST_ptr(bio2 = BIO_new(BIO_s_mem()))) goto end; } if (initrbio != USE_DEFAULT) { setupbio(&irbio, bio1, bio2, initrbio); setupbio(&iwbio, bio1, bio2, initwbio); SSL_set_bio(clientssl, irbio, iwbio); /* * We want to maintain our own refs to these BIO, so do an up ref for * each BIO that will have ownership transferred in the SSL_set_bio() * call */ if (irbio != NULL && !BIO_up_ref(irbio)) goto end; if (iwbio != NULL && iwbio != irbio && !BIO_up_ref(iwbio)) { BIO_free(irbio); goto end; } } if (conntype != CONNTYPE_NO_CONNECTION && !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE) == (conntype == CONNTYPE_CONNECTION_SUCCESS))) goto end; setupbio(&nrbio, bio1, bio2, newrbio); setupbio(&nwbio, bio1, bio2, newwbio); /* * We will (maybe) transfer ownership again so do more up refs. * SSL_set_bio() has some really complicated ownership rules where BIOs have * already been set! */ if (nrbio != NULL && nrbio != irbio && (nwbio != iwbio || nrbio != nwbio)) if (!TEST_true(BIO_up_ref(nrbio))) goto end; if (nwbio != NULL && nwbio != nrbio && (nwbio != iwbio || (nwbio == iwbio && irbio == iwbio))) if (!TEST_true(BIO_up_ref(nwbio))) { if (nrbio != irbio && (nwbio != iwbio || nrbio != nwbio)) BIO_free(nrbio); goto end; } SSL_set_bio(clientssl, nrbio, nwbio); testresult = 1; end: BIO_free(bio1); BIO_free(bio2); /* * This test is checking that the ref counting for SSL_set_bio is correct. * If we get here and we did too many frees then we will fail in the above * functions. */ SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } typedef enum { NO_BIO_CHANGE, CHANGE_RBIO, CHANGE_WBIO } bio_change_t; static int execute_test_ssl_bio(int pop_ssl, bio_change_t change_bio) { BIO *sslbio = NULL, *membio1 = NULL, *membio2 = NULL; SSL_CTX *ctx; SSL *ssl = NULL; int testresult = 0; if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_method())) || !TEST_ptr(ssl = SSL_new(ctx)) || !TEST_ptr(sslbio = BIO_new(BIO_f_ssl())) || !TEST_ptr(membio1 = BIO_new(BIO_s_mem()))) goto end; BIO_set_ssl(sslbio, ssl, BIO_CLOSE); /* * If anything goes wrong here then we could leak memory. */ BIO_push(sslbio, membio1); /* Verify changing the rbio/wbio directly does not cause leaks */ if (change_bio != NO_BIO_CHANGE) { if (!TEST_ptr(membio2 = BIO_new(BIO_s_mem()))) { ssl = NULL; goto end; } if (change_bio == CHANGE_RBIO) SSL_set0_rbio(ssl, membio2); else SSL_set0_wbio(ssl, membio2); } ssl = NULL; if (pop_ssl) BIO_pop(sslbio); else BIO_pop(membio1); testresult = 1; end: BIO_free(membio1); BIO_free(sslbio); SSL_free(ssl); SSL_CTX_free(ctx); return testresult; } static int test_ssl_bio_pop_next_bio(void) { return execute_test_ssl_bio(0, NO_BIO_CHANGE); } static int test_ssl_bio_pop_ssl_bio(void) { return execute_test_ssl_bio(1, NO_BIO_CHANGE); } static int test_ssl_bio_change_rbio(void) { return execute_test_ssl_bio(0, CHANGE_RBIO); } static int test_ssl_bio_change_wbio(void) { return execute_test_ssl_bio(0, CHANGE_WBIO); } #if !defined(OPENSSL_NO_TLS1_2) || defined(OSSL_NO_USABLE_TLS1_3) typedef struct { /* The list of sig algs */ const int *list; /* The length of the list */ size_t listlen; /* A sigalgs list in string format */ const char *liststr; /* Whether setting the list should succeed */ int valid; /* Whether creating a connection with the list should succeed */ int connsuccess; } sigalgs_list; static const int validlist1[] = {NID_sha256, EVP_PKEY_RSA}; # ifndef OPENSSL_NO_EC static const int validlist2[] = {NID_sha256, EVP_PKEY_RSA, NID_sha512, EVP_PKEY_EC}; static const int validlist3[] = {NID_sha512, EVP_PKEY_EC}; # endif static const int invalidlist1[] = {NID_undef, EVP_PKEY_RSA}; static const int invalidlist2[] = {NID_sha256, NID_undef}; static const int invalidlist3[] = {NID_sha256, EVP_PKEY_RSA, NID_sha256}; static const int invalidlist4[] = {NID_sha256}; static const sigalgs_list testsigalgs[] = { {validlist1, OSSL_NELEM(validlist1), NULL, 1, 1}, # ifndef OPENSSL_NO_EC {validlist2, OSSL_NELEM(validlist2), NULL, 1, 1}, {validlist3, OSSL_NELEM(validlist3), NULL, 1, 0}, # endif {NULL, 0, "RSA+SHA256", 1, 1}, {NULL, 0, "RSA+SHA256:?Invalid", 1, 1}, # ifndef OPENSSL_NO_EC {NULL, 0, "RSA+SHA256:ECDSA+SHA512", 1, 1}, {NULL, 0, "ECDSA+SHA512", 1, 0}, # endif {invalidlist1, OSSL_NELEM(invalidlist1), NULL, 0, 0}, {invalidlist2, OSSL_NELEM(invalidlist2), NULL, 0, 0}, {invalidlist3, OSSL_NELEM(invalidlist3), NULL, 0, 0}, {invalidlist4, OSSL_NELEM(invalidlist4), NULL, 0, 0}, {NULL, 0, "RSA", 0, 0}, {NULL, 0, "SHA256", 0, 0}, {NULL, 0, "RSA+SHA256:SHA256", 0, 0}, {NULL, 0, "Invalid", 0, 0} }; static int test_set_sigalgs(int idx) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; const sigalgs_list *curr; int testctx; /* Should never happen */ if (!TEST_size_t_le((size_t)idx, OSSL_NELEM(testsigalgs) * 2)) return 0; testctx = ((size_t)idx < OSSL_NELEM(testsigalgs)); curr = testctx ? &testsigalgs[idx] : &testsigalgs[idx - OSSL_NELEM(testsigalgs)]; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey))) return 0; SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION); if (testctx) { int ret; if (curr->list != NULL) ret = SSL_CTX_set1_sigalgs(cctx, curr->list, curr->listlen); else ret = SSL_CTX_set1_sigalgs_list(cctx, curr->liststr); if (!ret) { if (curr->valid) TEST_info("Failure setting sigalgs in SSL_CTX (%d)\n", idx); else testresult = 1; goto end; } if (!curr->valid) { TEST_info("Not-failed setting sigalgs in SSL_CTX (%d)\n", idx); goto end; } } if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (!testctx) { int ret; if (curr->list != NULL) ret = SSL_set1_sigalgs(clientssl, curr->list, curr->listlen); else ret = SSL_set1_sigalgs_list(clientssl, curr->liststr); if (!ret) { if (curr->valid) TEST_info("Failure setting sigalgs in SSL (%d)\n", idx); else testresult = 1; goto end; } if (!curr->valid) goto end; } if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE), curr->connsuccess)) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #endif #ifndef OSSL_NO_USABLE_TLS1_3 static int psk_client_cb_cnt = 0; static int psk_server_cb_cnt = 0; static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id, size_t *idlen, SSL_SESSION **sess) { switch (++use_session_cb_cnt) { case 1: /* The first call should always have a NULL md */ if (md != NULL) return 0; break; case 2: /* The second call should always have an md */ if (md == NULL) return 0; break; default: /* We should only be called a maximum of twice */ return 0; } if (clientpsk != NULL && !SSL_SESSION_up_ref(clientpsk)) return 0; *sess = clientpsk; *id = (const unsigned char *)pskid; *idlen = strlen(pskid); return 1; } #ifndef OPENSSL_NO_PSK static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *id, unsigned int max_id_len, unsigned char *psk, unsigned int max_psk_len) { unsigned int psklen = 0; psk_client_cb_cnt++; if (strlen(pskid) + 1 > max_id_len) return 0; /* We should only ever be called a maximum of twice per connection */ if (psk_client_cb_cnt > 2) return 0; if (clientpsk == NULL) return 0; /* We'll reuse the PSK we set up for TLSv1.3 */ if (SSL_SESSION_get_master_key(clientpsk, NULL, 0) > max_psk_len) return 0; psklen = SSL_SESSION_get_master_key(clientpsk, psk, max_psk_len); strncpy(id, pskid, max_id_len); return psklen; } #endif /* OPENSSL_NO_PSK */ static int find_session_cb(SSL *ssl, const unsigned char *identity, size_t identity_len, SSL_SESSION **sess) { find_session_cb_cnt++; /* We should only ever be called a maximum of twice per connection */ if (find_session_cb_cnt > 2) return 0; if (serverpsk == NULL) return 0; /* Identity should match that set by the client */ if (strlen(srvid) != identity_len || strncmp(srvid, (const char *)identity, identity_len) != 0) { /* No PSK found, continue but without a PSK */ *sess = NULL; return 1; } if (!SSL_SESSION_up_ref(serverpsk)) return 0; *sess = serverpsk; return 1; } #ifndef OPENSSL_NO_PSK static unsigned int psk_server_cb(SSL *ssl, const char *identity, unsigned char *psk, unsigned int max_psk_len) { unsigned int psklen = 0; psk_server_cb_cnt++; /* We should only ever be called a maximum of twice per connection */ if (find_session_cb_cnt > 2) return 0; if (serverpsk == NULL) return 0; /* Identity should match that set by the client */ if (strcmp(srvid, identity) != 0) { return 0; } /* We'll reuse the PSK we set up for TLSv1.3 */ if (SSL_SESSION_get_master_key(serverpsk, NULL, 0) > max_psk_len) return 0; psklen = SSL_SESSION_get_master_key(serverpsk, psk, max_psk_len); return psklen; } #endif /* OPENSSL_NO_PSK */ #define MSG1 "Hello" #define MSG2 "World." #define MSG3 "This" #define MSG4 "is" #define MSG5 "a" #define MSG6 "test" #define MSG7 "message." static int artificial_ticket_time = 0; static int sub_session_time(SSL_SESSION *sess) { OSSL_TIME tick_time; tick_time = ossl_time_from_time_t(SSL_SESSION_get_time_ex(sess)); tick_time = ossl_time_subtract(tick_time, ossl_seconds2time(10)); return SSL_SESSION_set_time_ex(sess, ossl_time_to_time_t(tick_time)) != 0; } static int ed_gen_cb(SSL *s, void *arg) { SSL_SESSION *sess = SSL_get0_session(s); if (sess == NULL) return 0; /* * Artificially give the ticket some age. Just do it for the number of * tickets we've been told to do. */ if (artificial_ticket_time == 0) return 1; artificial_ticket_time--; return sub_session_time(sess); } /* * Helper method to setup objects for early data test. Caller frees objects on * error. */ static int setupearly_data_test(SSL_CTX **cctx, SSL_CTX **sctx, SSL **clientssl, SSL **serverssl, SSL_SESSION **sess, int idx, size_t mdsize) { int artificial = (artificial_ticket_time > 0); if (*sctx == NULL && !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, sctx, cctx, cert, privkey))) return 0; if (artificial) SSL_CTX_set_session_ticket_cb(*sctx, ed_gen_cb, NULL, NULL); if (!TEST_true(SSL_CTX_set_max_early_data(*sctx, SSL3_RT_MAX_PLAIN_LENGTH))) return 0; if (idx == 1) { /* When idx == 1 we repeat the tests with read_ahead set */ SSL_CTX_set_read_ahead(*cctx, 1); SSL_CTX_set_read_ahead(*sctx, 1); } else if (idx == 2) { /* When idx == 2 we are doing early_data with a PSK. Set up callbacks */ SSL_CTX_set_psk_use_session_callback(*cctx, use_session_cb); SSL_CTX_set_psk_find_session_callback(*sctx, find_session_cb); use_session_cb_cnt = 0; find_session_cb_cnt = 0; srvid = pskid; } if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl, clientssl, NULL, NULL))) return 0; /* * For one of the run throughs (doesn't matter which one), we'll try sending * some SNI data in the initial ClientHello. This will be ignored (because * there is no SNI cb set up by the server), so it should not impact * early_data. */ if (idx == 1 && !TEST_true(SSL_set_tlsext_host_name(*clientssl, "localhost"))) return 0; if (idx == 2) { clientpsk = create_a_psk(*clientssl, mdsize); if (!TEST_ptr(clientpsk) /* * We just choose an arbitrary value for max_early_data which * should be big enough for testing purposes. */ || !TEST_true(SSL_SESSION_set_max_early_data(clientpsk, 0x100)) || !TEST_true(SSL_SESSION_up_ref(clientpsk))) { SSL_SESSION_free(clientpsk); clientpsk = NULL; return 0; } serverpsk = clientpsk; if (sess != NULL) { if (!TEST_true(SSL_SESSION_up_ref(clientpsk))) { SSL_SESSION_free(clientpsk); SSL_SESSION_free(serverpsk); clientpsk = serverpsk = NULL; return 0; } *sess = clientpsk; } return 1; } if (sess == NULL) return 1; if (!TEST_true(create_ssl_connection(*serverssl, *clientssl, SSL_ERROR_NONE))) return 0; *sess = SSL_get1_session(*clientssl); SSL_shutdown(*clientssl); SSL_shutdown(*serverssl); SSL_free(*serverssl); SSL_free(*clientssl); *serverssl = *clientssl = NULL; /* * Artificially give the ticket some age to match the artificial age we * gave it on the server side */ if (artificial && !TEST_true(sub_session_time(*sess))) return 0; if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl, clientssl, NULL, NULL)) || !TEST_true(SSL_set_session(*clientssl, *sess))) return 0; return 1; } static int check_early_data_timeout(OSSL_TIME timer) { int res = 0; /* * Early data is time sensitive. We have an approx 8 second allowance * between writing the early data and reading it. If we exceed that time * then this test will fail. This can sometimes (rarely) occur in normal CI * operation. We can try and detect this and just ignore the result of this * test if it has taken too long. We assume anything over 7 seconds is too * long */ timer = ossl_time_subtract(ossl_time_now(), timer); if (ossl_time_compare(timer, ossl_seconds2time(7)) >= 0) res = TEST_skip("Test took too long, ignoring result"); return res; } static int test_early_data_read_write(int idx) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; SSL_SESSION *sess = NULL; unsigned char buf[20], data[1024]; size_t readbytes, written, eoedlen, rawread, rawwritten; BIO *rbio; OSSL_TIME timer; /* Artificially give the next 2 tickets some age for non PSK sessions */ if (idx != 2) artificial_ticket_time = 2; if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl, &sess, idx, SHA384_DIGEST_LENGTH))) { artificial_ticket_time = 0; goto end; } artificial_ticket_time = 0; /* Write and read some early data */ timer = ossl_time_now(); if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1), &written)) || !TEST_size_t_eq(written, strlen(MSG1))) goto end; if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf), &readbytes), SSL_READ_EARLY_DATA_SUCCESS)) { testresult = check_early_data_timeout(timer); goto end; } if (!TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1)) || !TEST_int_eq(SSL_get_early_data_status(serverssl), SSL_EARLY_DATA_ACCEPTED)) goto end; /* * Server should be able to write data, and client should be able to * read it. */ if (!TEST_true(SSL_write_early_data(serverssl, MSG2, strlen(MSG2), &written)) || !TEST_size_t_eq(written, strlen(MSG2)) || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)) || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2))) goto end; /* Even after reading normal data, client should be able write early data */ if (!TEST_true(SSL_write_early_data(clientssl, MSG3, strlen(MSG3), &written)) || !TEST_size_t_eq(written, strlen(MSG3))) goto end; /* Server should still be able read early data after writing data */ if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf), &readbytes), SSL_READ_EARLY_DATA_SUCCESS) || !TEST_mem_eq(buf, readbytes, MSG3, strlen(MSG3))) goto end; /* Write more data from server and read it from client */ if (!TEST_true(SSL_write_early_data(serverssl, MSG4, strlen(MSG4), &written)) || !TEST_size_t_eq(written, strlen(MSG4)) || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)) || !TEST_mem_eq(buf, readbytes, MSG4, strlen(MSG4))) goto end; /* * If client writes normal data it should mean writing early data is no * longer possible. */ if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written)) || !TEST_size_t_eq(written, strlen(MSG5)) || !TEST_int_eq(SSL_get_early_data_status(clientssl), SSL_EARLY_DATA_ACCEPTED)) goto end; /* * At this point the client has written EndOfEarlyData, ClientFinished and * normal (fully protected) data. We are going to cause a delay between the * arrival of EndOfEarlyData and ClientFinished. We read out all the data * in the read BIO, and then just put back the EndOfEarlyData message. */ rbio = SSL_get_rbio(serverssl); if (!TEST_true(BIO_read_ex(rbio, data, sizeof(data), &rawread)) || !TEST_size_t_lt(rawread, sizeof(data)) || !TEST_size_t_gt(rawread, SSL3_RT_HEADER_LENGTH)) goto end; /* Record length is in the 4th and 5th bytes of the record header */ eoedlen = SSL3_RT_HEADER_LENGTH + (data[3] << 8 | data[4]); if (!TEST_true(BIO_write_ex(rbio, data, eoedlen, &rawwritten)) || !TEST_size_t_eq(rawwritten, eoedlen)) goto end; /* Server should be told that there is no more early data */ if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf), &readbytes), SSL_READ_EARLY_DATA_FINISH) || !TEST_size_t_eq(readbytes, 0)) goto end; /* * Server has not finished init yet, so should still be able to write early * data. */ if (!TEST_true(SSL_write_early_data(serverssl, MSG6, strlen(MSG6), &written)) || !TEST_size_t_eq(written, strlen(MSG6))) goto end; /* Push the ClientFinished and the normal data back into the server rbio */ if (!TEST_true(BIO_write_ex(rbio, data + eoedlen, rawread - eoedlen, &rawwritten)) || !TEST_size_t_eq(rawwritten, rawread - eoedlen)) goto end; /* Server should be able to read normal data */ if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes)) || !TEST_size_t_eq(readbytes, strlen(MSG5))) goto end; /* Client and server should not be able to write/read early data now */ if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6), &written))) goto end; ERR_clear_error(); if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf), &readbytes), SSL_READ_EARLY_DATA_ERROR)) goto end; ERR_clear_error(); /* Client should be able to read the data sent by the server */ if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)) || !TEST_mem_eq(buf, readbytes, MSG6, strlen(MSG6))) goto end; /* * Make sure we process the two NewSessionTickets. These arrive * post-handshake. We attempt reads which we do not expect to return any * data. */ if (!TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)) || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))) goto end; /* Server should be able to write normal data */ if (!TEST_true(SSL_write_ex(serverssl, MSG7, strlen(MSG7), &written)) || !TEST_size_t_eq(written, strlen(MSG7)) || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)) || !TEST_mem_eq(buf, readbytes, MSG7, strlen(MSG7))) goto end; SSL_SESSION_free(sess); sess = SSL_get1_session(clientssl); use_session_cb_cnt = 0; find_session_cb_cnt = 0; SSL_shutdown(clientssl); SSL_shutdown(serverssl); SSL_free(serverssl); SSL_free(clientssl); serverssl = clientssl = NULL; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(SSL_set_session(clientssl, sess))) goto end; /* Write and read some early data */ if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1), &written)) || !TEST_size_t_eq(written, strlen(MSG1)) || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf), &readbytes), SSL_READ_EARLY_DATA_SUCCESS) || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))) goto end; if (!TEST_int_gt(SSL_connect(clientssl), 0) || !TEST_int_gt(SSL_accept(serverssl), 0)) goto end; /* Client and server should not be able to write/read early data now */ if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6), &written))) goto end; ERR_clear_error(); if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf), &readbytes), SSL_READ_EARLY_DATA_ERROR)) goto end; ERR_clear_error(); /* Client and server should be able to write/read normal data */ if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written)) || !TEST_size_t_eq(written, strlen(MSG5)) || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes)) || !TEST_size_t_eq(readbytes, strlen(MSG5))) goto end; testresult = 1; end: SSL_SESSION_free(sess); SSL_SESSION_free(clientpsk); SSL_SESSION_free(serverpsk); clientpsk = serverpsk = NULL; SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } static int allow_ed_cb_called = 0; static int allow_early_data_cb(SSL *s, void *arg) { int *usecb = (int *)arg; allow_ed_cb_called++; if (*usecb == 1) return 0; return 1; } /* * idx == 0: Standard early_data setup * idx == 1: early_data setup using read_ahead * usecb == 0: Don't use a custom early data callback * usecb == 1: Use a custom early data callback and reject the early data * usecb == 2: Use a custom early data callback and accept the early data * confopt == 0: Configure anti-replay directly * confopt == 1: Configure anti-replay using SSL_CONF */ static int test_early_data_replay_int(int idx, int usecb, int confopt) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; SSL_SESSION *sess = NULL; size_t readbytes, written; unsigned char buf[20]; OSSL_TIME timer; allow_ed_cb_called = 0; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey))) return 0; if (usecb > 0) { if (confopt == 0) { SSL_CTX_set_options(sctx, SSL_OP_NO_ANTI_REPLAY); } else { SSL_CONF_CTX *confctx = SSL_CONF_CTX_new(); if (!TEST_ptr(confctx)) goto end; SSL_CONF_CTX_set_flags(confctx, SSL_CONF_FLAG_FILE | SSL_CONF_FLAG_SERVER); SSL_CONF_CTX_set_ssl_ctx(confctx, sctx); if (!TEST_int_eq(SSL_CONF_cmd(confctx, "Options", "-AntiReplay"), 2)) { SSL_CONF_CTX_free(confctx); goto end; } SSL_CONF_CTX_free(confctx); } SSL_CTX_set_allow_early_data_cb(sctx, allow_early_data_cb, &usecb); } if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl, &sess, idx, SHA384_DIGEST_LENGTH))) goto end; /* * The server is configured to accept early data. Create a connection to * "use up" the ticket */ if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_true(SSL_session_reused(clientssl))) goto end; SSL_shutdown(clientssl); SSL_shutdown(serverssl); SSL_free(serverssl); SSL_free(clientssl); serverssl = clientssl = NULL; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(SSL_set_session(clientssl, sess))) goto end; /* Write and read some early data */ timer = ossl_time_now(); if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1), &written)) || !TEST_size_t_eq(written, strlen(MSG1))) goto end; if (usecb <= 1) { if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf), &readbytes), SSL_READ_EARLY_DATA_FINISH) /* * The ticket was reused, so the we should have rejected the * early data */ || !TEST_int_eq(SSL_get_early_data_status(serverssl), SSL_EARLY_DATA_REJECTED)) goto end; } else { /* In this case the callback decides to accept the early data */ if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf), &readbytes), SSL_READ_EARLY_DATA_SUCCESS)) { testresult = check_early_data_timeout(timer); goto end; } if (!TEST_mem_eq(MSG1, strlen(MSG1), buf, readbytes) /* * Server will have sent its flight so client can now send * end of early data and complete its half of the handshake */ || !TEST_int_gt(SSL_connect(clientssl), 0) || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf), &readbytes), SSL_READ_EARLY_DATA_FINISH) || !TEST_int_eq(SSL_get_early_data_status(serverssl), SSL_EARLY_DATA_ACCEPTED)) goto end; } /* Complete the connection */ if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_int_eq(SSL_session_reused(clientssl), (usecb > 0) ? 1 : 0) || !TEST_int_eq(allow_ed_cb_called, usecb > 0 ? 1 : 0)) goto end; testresult = 1; end: SSL_SESSION_free(sess); SSL_SESSION_free(clientpsk); SSL_SESSION_free(serverpsk); clientpsk = serverpsk = NULL; SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } static int test_early_data_replay(int idx) { int ret = 1, usecb, confopt; for (usecb = 0; usecb < 3; usecb++) { for (confopt = 0; confopt < 2; confopt++) ret &= test_early_data_replay_int(idx, usecb, confopt); } return ret; } static const char *ciphersuites[] = { "TLS_AES_128_CCM_8_SHA256", "TLS_AES_128_GCM_SHA256", "TLS_AES_256_GCM_SHA384", "TLS_AES_128_CCM_SHA256", #if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305) "TLS_CHACHA20_POLY1305_SHA256", #else NULL, #endif #if !defined(OPENSSL_NO_INTEGRITY_ONLY_CIPHERS) "TLS_SHA256_SHA256", "TLS_SHA384_SHA384" #endif }; /* * Helper function to test that a server attempting to read early data can * handle a connection from a client where the early data should be skipped. * testtype: 0 == No HRR * testtype: 1 == HRR * testtype: 2 == HRR, invalid early_data sent after HRR * testtype: 3 == recv_max_early_data set to 0 */ static int early_data_skip_helper(int testtype, int cipher, int idx) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; SSL_SESSION *sess = NULL; unsigned char buf[20]; size_t readbytes, written; if (is_fips && cipher >= 4) return 1; if (ciphersuites[cipher] == NULL) return TEST_skip("Cipher not supported"); if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey))) goto end; if (cipher == 0 || cipher == 5 || cipher == 6) { SSL_CTX_set_security_level(sctx, 0); SSL_CTX_set_security_level(cctx, 0); } if (!TEST_true(SSL_CTX_set_ciphersuites(sctx, ciphersuites[cipher])) || !TEST_true(SSL_CTX_set_ciphersuites(cctx, ciphersuites[cipher]))) goto end; if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl, &sess, idx, (cipher == 2 || cipher == 6) ? SHA384_DIGEST_LENGTH : SHA256_DIGEST_LENGTH))) goto end; if (testtype == 1 || testtype == 2) { /* Force an HRR to occur */ #if defined(OPENSSL_NO_EC) if (!TEST_true(SSL_set1_groups_list(serverssl, "ffdhe3072"))) goto end; #else if (!TEST_true(SSL_set1_groups_list(serverssl, "P-384"))) goto end; #endif } else if (idx == 2) { /* * We force early_data rejection by ensuring the PSK identity is * unrecognised */ srvid = "Dummy Identity"; } else { /* * Deliberately corrupt the creation time. We take 20 seconds off the * time. It could be any value as long as it is not within tolerance. * This should mean the ticket is rejected. */ if (!TEST_true(SSL_SESSION_set_time_ex(sess, time(NULL) - 20))) goto end; } if (testtype == 3 && !TEST_true(SSL_set_recv_max_early_data(serverssl, 0))) goto end; /* Write some early data */ if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1), &written)) || !TEST_size_t_eq(written, strlen(MSG1))) goto end; /* Server should reject the early data */ if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf), &readbytes), SSL_READ_EARLY_DATA_FINISH) || !TEST_size_t_eq(readbytes, 0) || !TEST_int_eq(SSL_get_early_data_status(serverssl), SSL_EARLY_DATA_REJECTED)) goto end; switch (testtype) { case 0: /* Nothing to do */ break; case 1: /* * Finish off the handshake. We perform the same writes and reads as * further down but we expect them to fail due to the incomplete * handshake. */ if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written)) || !TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))) goto end; break; case 2: { BIO *wbio = SSL_get_wbio(clientssl); /* A record that will appear as bad early_data */ const unsigned char bad_early_data[] = { 0x17, 0x03, 0x03, 0x00, 0x01, 0x00 }; /* * We force the client to attempt a write. This will fail because * we're still in the handshake. It will cause the second * ClientHello to be sent. */ if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))) goto end; /* * Inject some early_data after the second ClientHello. This should * cause the server to fail */ if (!TEST_true(BIO_write_ex(wbio, bad_early_data, sizeof(bad_early_data), &written))) goto end; } /* FALLTHROUGH */ case 3: /* * This client has sent more early_data than we are willing to skip * (case 3) or sent invalid early_data (case 2) so the connection should * abort. */ if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes)) || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_SSL)) goto end; /* Connection has failed - nothing more to do */ testresult = 1; goto end; default: TEST_error("Invalid test type"); goto end; } ERR_clear_error(); /* * Should be able to send normal data despite rejection of early data. The * early_data should be skipped. */ if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written)) || !TEST_size_t_eq(written, strlen(MSG2)) || !TEST_int_eq(SSL_get_early_data_status(clientssl), SSL_EARLY_DATA_REJECTED) || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes)) || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2))) goto end; /* * Failure to decrypt early data records should not leave spurious errors * on the error stack */ if (!TEST_long_eq(ERR_peek_error(), 0)) goto end; testresult = 1; end: SSL_SESSION_free(clientpsk); SSL_SESSION_free(serverpsk); clientpsk = serverpsk = NULL; SSL_SESSION_free(sess); SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } /* * Test that a server attempting to read early data can handle a connection * from a client where the early data is not acceptable. */ static int test_early_data_skip(int idx) { return early_data_skip_helper(0, idx % OSSL_NELEM(ciphersuites), idx / OSSL_NELEM(ciphersuites)); } /* * Test that a server attempting to read early data can handle a connection * from a client where an HRR occurs. */ static int test_early_data_skip_hrr(int idx) { return early_data_skip_helper(1, idx % OSSL_NELEM(ciphersuites), idx / OSSL_NELEM(ciphersuites)); } /* * Test that a server attempting to read early data can handle a connection * from a client where an HRR occurs and correctly fails if early_data is sent * after the HRR */ static int test_early_data_skip_hrr_fail(int idx) { return early_data_skip_helper(2, idx % OSSL_NELEM(ciphersuites), idx / OSSL_NELEM(ciphersuites)); } /* * Test that a server attempting to read early data will abort if it tries to * skip over too much. */ static int test_early_data_skip_abort(int idx) { return early_data_skip_helper(3, idx % OSSL_NELEM(ciphersuites), idx / OSSL_NELEM(ciphersuites)); } /* * Test that a server attempting to read early data can handle a connection * from a client that doesn't send any. */ static int test_early_data_not_sent(int idx) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; SSL_SESSION *sess = NULL; unsigned char buf[20]; size_t readbytes, written; if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl, &sess, idx, SHA384_DIGEST_LENGTH))) goto end; /* Write some data - should block due to handshake with server */ SSL_set_connect_state(clientssl); if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))) goto end; /* Server should detect that early data has not been sent */ if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf), &readbytes), SSL_READ_EARLY_DATA_FINISH) || !TEST_size_t_eq(readbytes, 0) || !TEST_int_eq(SSL_get_early_data_status(serverssl), SSL_EARLY_DATA_NOT_SENT) || !TEST_int_eq(SSL_get_early_data_status(clientssl), SSL_EARLY_DATA_NOT_SENT)) goto end; /* Continue writing the message we started earlier */ if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)) || !TEST_size_t_eq(written, strlen(MSG1)) || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes)) || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)) || !SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written) || !TEST_size_t_eq(written, strlen(MSG2))) goto end; if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)) || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2))) goto end; testresult = 1; end: SSL_SESSION_free(sess); SSL_SESSION_free(clientpsk); SSL_SESSION_free(serverpsk); clientpsk = serverpsk = NULL; SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } static const char *servalpn; static int alpn_select_cb(SSL *ssl, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg) { unsigned int protlen = 0; const unsigned char *prot; for (prot = in; prot < in + inlen; prot += protlen) { protlen = *prot++; if (in + inlen < prot + protlen) return SSL_TLSEXT_ERR_NOACK; if (protlen == strlen(servalpn) && memcmp(prot, servalpn, protlen) == 0) { *out = prot; *outlen = protlen; return SSL_TLSEXT_ERR_OK; } } return SSL_TLSEXT_ERR_NOACK; } /* Test that a PSK can be used to send early_data */ static int test_early_data_psk(int idx) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; SSL_SESSION *sess = NULL; unsigned char alpnlist[] = { 0x08, 'g', 'o', 'o', 'd', 'a', 'l', 'p', 'n', 0x07, 'b', 'a', 'd', 'a', 'l', 'p', 'n' }; #define GOODALPNLEN 9 #define BADALPNLEN 8 #define GOODALPN (alpnlist) #define BADALPN (alpnlist + GOODALPNLEN) int err = 0; unsigned char buf[20]; size_t readbytes, written; int readearlyres = SSL_READ_EARLY_DATA_SUCCESS, connectres = 1; int edstatus = SSL_EARLY_DATA_ACCEPTED; /* We always set this up with a final parameter of "2" for PSK */ if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl, &sess, 2, SHA384_DIGEST_LENGTH))) goto end; servalpn = "goodalpn"; /* * Note: There is no test for inconsistent SNI with late client detection. * This is because servers do not acknowledge SNI even if they are using * it in a resumption handshake - so it is not actually possible for a * client to detect a problem. */ switch (idx) { case 0: /* Set inconsistent SNI (early client detection) */ err = SSL_R_INCONSISTENT_EARLY_DATA_SNI; if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost")) || !TEST_true(SSL_set_tlsext_host_name(clientssl, "badhost"))) goto end; break; case 1: /* Set inconsistent ALPN (early client detection) */ err = SSL_R_INCONSISTENT_EARLY_DATA_ALPN; /* SSL_set_alpn_protos returns 0 for success and 1 for failure */ if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN, GOODALPNLEN)) || !TEST_false(SSL_set_alpn_protos(clientssl, BADALPN, BADALPNLEN))) goto end; break; case 2: /* * Set invalid protocol version. Technically this affects PSKs without * early_data too, but we test it here because it is similar to the * SNI/ALPN consistency tests. */ err = SSL_R_BAD_PSK; if (!TEST_true(SSL_SESSION_set_protocol_version(sess, TLS1_2_VERSION))) goto end; break; case 3: /* * Set inconsistent SNI (server side). In this case the connection * will succeed and accept early_data. In TLSv1.3 on the server side SNI * is associated with each handshake - not the session. Therefore it * should not matter that we used a different server name last time. */ SSL_SESSION_free(serverpsk); serverpsk = SSL_SESSION_dup(clientpsk); if (!TEST_ptr(serverpsk) || !TEST_true(SSL_SESSION_set1_hostname(serverpsk, "badhost"))) goto end; /* Fall through */ case 4: /* Set consistent SNI */ if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost")) || !TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost")) || !TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, hostname_cb))) goto end; break; case 5: /* * Set inconsistent ALPN (server detected). In this case the connection * will succeed but reject early_data. */ servalpn = "badalpn"; edstatus = SSL_EARLY_DATA_REJECTED; readearlyres = SSL_READ_EARLY_DATA_FINISH; /* Fall through */ case 6: /* * Set consistent ALPN. * SSL_set_alpn_protos returns 0 for success and 1 for failure. It * accepts a list of protos (each one length prefixed). * SSL_set1_alpn_selected accepts a single protocol (not length * prefixed) */ if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN + 1, GOODALPNLEN - 1)) || !TEST_false(SSL_set_alpn_protos(clientssl, GOODALPN, GOODALPNLEN))) goto end; SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL); break; case 7: /* Set inconsistent ALPN (late client detection) */ SSL_SESSION_free(serverpsk); serverpsk = SSL_SESSION_dup(clientpsk); if (!TEST_ptr(serverpsk) || !TEST_true(SSL_SESSION_set1_alpn_selected(clientpsk, BADALPN + 1, BADALPNLEN - 1)) || !TEST_true(SSL_SESSION_set1_alpn_selected(serverpsk, GOODALPN + 1, GOODALPNLEN - 1)) || !TEST_false(SSL_set_alpn_protos(clientssl, alpnlist, sizeof(alpnlist)))) goto end; SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL); edstatus = SSL_EARLY_DATA_ACCEPTED; readearlyres = SSL_READ_EARLY_DATA_SUCCESS; /* SSL_connect() call should fail */ connectres = -1; break; default: TEST_error("Bad test index"); goto end; } SSL_set_connect_state(clientssl); if (err != 0) { if (!TEST_false(SSL_write_early_data(clientssl, MSG1, strlen(MSG1), &written)) || !TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_SSL) || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()), err)) goto end; } else { OSSL_TIME timer = ossl_time_now(); if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1), &written))) goto end; if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf), &readbytes), readearlyres)) { testresult = check_early_data_timeout(timer); goto end; } if ((readearlyres == SSL_READ_EARLY_DATA_SUCCESS && !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))) || !TEST_int_eq(SSL_get_early_data_status(serverssl), edstatus) || !TEST_int_eq(SSL_connect(clientssl), connectres)) goto end; } testresult = 1; end: SSL_SESSION_free(sess); SSL_SESSION_free(clientpsk); SSL_SESSION_free(serverpsk); clientpsk = serverpsk = NULL; SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } /* * Test TLSv1.3 PSK can be used to send early_data with all 7 ciphersuites * idx == 0: Test with TLS1_3_RFC_AES_128_GCM_SHA256 * idx == 1: Test with TLS1_3_RFC_AES_256_GCM_SHA384 * idx == 2: Test with TLS1_3_RFC_CHACHA20_POLY1305_SHA256, * idx == 3: Test with TLS1_3_RFC_AES_128_CCM_SHA256 * idx == 4: Test with TLS1_3_RFC_AES_128_CCM_8_SHA256 * idx == 5: Test with TLS1_3_RFC_SHA256_SHA256 * idx == 6: Test with TLS1_3_RFC_SHA384_SHA384 */ static int test_early_data_psk_with_all_ciphers(int idx) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; SSL_SESSION *sess = NULL; unsigned char buf[20]; size_t readbytes, written; const SSL_CIPHER *cipher; OSSL_TIME timer; const char *cipher_str[] = { TLS1_3_RFC_AES_128_GCM_SHA256, TLS1_3_RFC_AES_256_GCM_SHA384, # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305) TLS1_3_RFC_CHACHA20_POLY1305_SHA256, # else NULL, # endif TLS1_3_RFC_AES_128_CCM_SHA256, TLS1_3_RFC_AES_128_CCM_8_SHA256, # if !defined(OPENSSL_NO_INTEGRITY_ONLY_CIPHERS) TLS1_3_RFC_SHA256_SHA256, TLS1_3_RFC_SHA384_SHA384 #else NULL, NULL #endif }; const unsigned char *cipher_bytes[] = { TLS13_AES_128_GCM_SHA256_BYTES, TLS13_AES_256_GCM_SHA384_BYTES, # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305) TLS13_CHACHA20_POLY1305_SHA256_BYTES, # else NULL, # endif TLS13_AES_128_CCM_SHA256_BYTES, TLS13_AES_128_CCM_8_SHA256_BYTES, # if !defined(OPENSSL_NO_INTEGRITY_ONLY_CIPHERS) TLS13_SHA256_SHA256_BYTES, TLS13_SHA384_SHA384_BYTES #else NULL, NULL #endif }; if (cipher_str[idx] == NULL) return 1; /* * Skip ChaCha20Poly1305 and TLS_SHA{256,384}_SHA{256,384} ciphers * as currently FIPS module does not support them. */ if ((idx == 2 || idx == 5 || idx == 6) && is_fips == 1) return 1; /* We always set this up with a final parameter of "2" for PSK */ if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl, &sess, 2, SHA384_DIGEST_LENGTH))) goto end; if (idx == 4 || idx == 5 || idx == 6) { /* * CCM8 ciphers are considered low security due to their short tag. * Integrity-only cipher do not provide any confidentiality. */ SSL_set_security_level(clientssl, 0); SSL_set_security_level(serverssl, 0); } if (!TEST_true(SSL_set_ciphersuites(clientssl, cipher_str[idx])) || !TEST_true(SSL_set_ciphersuites(serverssl, cipher_str[idx]))) goto end; /* * 'setupearly_data_test' creates only one instance of SSL_SESSION * and assigns to both client and server with incremented reference * and the same instance is updated in 'sess'. * So updating ciphersuite in 'sess' which will get reflected in * PSK handshake using psk use sess and find sess cb. */ cipher = SSL_CIPHER_find(clientssl, cipher_bytes[idx]); if (!TEST_ptr(cipher) || !TEST_true(SSL_SESSION_set_cipher(sess, cipher))) goto end; SSL_set_connect_state(clientssl); timer = ossl_time_now(); if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1), &written))) goto end; if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf), &readbytes), SSL_READ_EARLY_DATA_SUCCESS)) { testresult = check_early_data_timeout(timer); goto end; } if (!TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)) || !TEST_int_eq(SSL_get_early_data_status(serverssl), SSL_EARLY_DATA_ACCEPTED) || !TEST_int_eq(SSL_connect(clientssl), 1) || !TEST_int_eq(SSL_accept(serverssl), 1)) goto end; /* Send some normal data from client to server */ if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written)) || !TEST_size_t_eq(written, strlen(MSG2))) goto end; if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes)) || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2))) goto end; testresult = 1; end: SSL_SESSION_free(sess); SSL_SESSION_free(clientpsk); SSL_SESSION_free(serverpsk); clientpsk = serverpsk = NULL; if (clientssl != NULL) SSL_shutdown(clientssl); if (serverssl != NULL) SSL_shutdown(serverssl); SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } /* * Test that a server that doesn't try to read early data can handle a * client sending some. */ static int test_early_data_not_expected(int idx) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; SSL_SESSION *sess = NULL; unsigned char buf[20]; size_t readbytes, written; if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl, &sess, idx, SHA384_DIGEST_LENGTH))) goto end; /* Write some early data */ if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1), &written))) goto end; /* * Server should skip over early data and then block waiting for client to * continue handshake */ if (!TEST_int_le(SSL_accept(serverssl), 0) || !TEST_int_gt(SSL_connect(clientssl), 0) || !TEST_int_eq(SSL_get_early_data_status(serverssl), SSL_EARLY_DATA_REJECTED) || !TEST_int_gt(SSL_accept(serverssl), 0) || !TEST_int_eq(SSL_get_early_data_status(clientssl), SSL_EARLY_DATA_REJECTED)) goto end; /* Send some normal data from client to server */ if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written)) || !TEST_size_t_eq(written, strlen(MSG2))) goto end; if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes)) || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2))) goto end; testresult = 1; end: SSL_SESSION_free(sess); SSL_SESSION_free(clientpsk); SSL_SESSION_free(serverpsk); clientpsk = serverpsk = NULL; SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } # ifndef OPENSSL_NO_TLS1_2 /* * Test that a server attempting to read early data can handle a connection * from a TLSv1.2 client. */ static int test_early_data_tls1_2(int idx) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; unsigned char buf[20]; size_t readbytes, written; if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl, NULL, idx, SHA384_DIGEST_LENGTH))) goto end; /* Write some data - should block due to handshake with server */ SSL_set_max_proto_version(clientssl, TLS1_2_VERSION); SSL_set_connect_state(clientssl); if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))) goto end; /* * Server should do TLSv1.2 handshake. First it will block waiting for more * messages from client after ServerDone. Then SSL_read_early_data should * finish and detect that early data has not been sent */ if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf), &readbytes), SSL_READ_EARLY_DATA_ERROR)) goto end; /* * Continue writing the message we started earlier. Will still block waiting * for the CCS/Finished from server */ if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)) || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf), &readbytes), SSL_READ_EARLY_DATA_FINISH) || !TEST_size_t_eq(readbytes, 0) || !TEST_int_eq(SSL_get_early_data_status(serverssl), SSL_EARLY_DATA_NOT_SENT)) goto end; /* Continue writing the message we started earlier */ if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)) || !TEST_size_t_eq(written, strlen(MSG1)) || !TEST_int_eq(SSL_get_early_data_status(clientssl), SSL_EARLY_DATA_NOT_SENT) || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes)) || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)) || !TEST_true(SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written)) || !TEST_size_t_eq(written, strlen(MSG2)) || !SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes) || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2))) goto end; testresult = 1; end: SSL_SESSION_free(clientpsk); SSL_SESSION_free(serverpsk); clientpsk = serverpsk = NULL; SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } # endif /* OPENSSL_NO_TLS1_2 */ /* * Test configuring the TLSv1.3 ciphersuites * * Test 0: Set a default ciphersuite in the SSL_CTX (no explicit cipher_list) * Test 1: Set a non-default ciphersuite in the SSL_CTX (no explicit cipher_list) * Test 2: Set a default ciphersuite in the SSL (no explicit cipher_list) * Test 3: Set a non-default ciphersuite in the SSL (no explicit cipher_list) * Test 4: Set a default ciphersuite in the SSL_CTX (SSL_CTX cipher_list) * Test 5: Set a non-default ciphersuite in the SSL_CTX (SSL_CTX cipher_list) * Test 6: Set a default ciphersuite in the SSL (SSL_CTX cipher_list) * Test 7: Set a non-default ciphersuite in the SSL (SSL_CTX cipher_list) * Test 8: Set a default ciphersuite in the SSL (SSL cipher_list) * Test 9: Set a non-default ciphersuite in the SSL (SSL cipher_list) */ static int test_set_ciphersuite(int idx) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey)) || !TEST_true(SSL_CTX_set_ciphersuites(sctx, "TLS_AES_128_GCM_SHA256:TLS_AES_128_CCM_SHA256"))) goto end; if (idx >=4 && idx <= 7) { /* SSL_CTX explicit cipher list */ if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "AES256-GCM-SHA384"))) goto end; } if (idx == 0 || idx == 4) { /* Default ciphersuite */ if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_128_GCM_SHA256"))) goto end; } else if (idx == 1 || idx == 5) { /* Non default ciphersuite */ if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_128_CCM_SHA256"))) goto end; } if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (idx == 8 || idx == 9) { /* SSL explicit cipher list */ if (!TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384"))) goto end; } if (idx == 2 || idx == 6 || idx == 8) { /* Default ciphersuite */ if (!TEST_true(SSL_set_ciphersuites(clientssl, "TLS_AES_128_GCM_SHA256"))) goto end; } else if (idx == 3 || idx == 7 || idx == 9) { /* Non default ciphersuite */ if (!TEST_true(SSL_set_ciphersuites(clientssl, "TLS_AES_128_CCM_SHA256"))) goto end; } if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } static int test_ciphersuite_change(void) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; SSL_SESSION *clntsess = NULL; int testresult = 0; const SSL_CIPHER *aes_128_gcm_sha256 = NULL; /* Create a session based on SHA-256 */ if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey)) || !TEST_true(SSL_CTX_set_ciphersuites(sctx, "TLS_AES_128_GCM_SHA256:" "TLS_AES_256_GCM_SHA384:" "TLS_AES_128_CCM_SHA256")) || !TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_128_GCM_SHA256"))) goto end; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; clntsess = SSL_get1_session(clientssl); /* Save for later */ aes_128_gcm_sha256 = SSL_SESSION_get0_cipher(clntsess); SSL_shutdown(clientssl); SSL_shutdown(serverssl); SSL_free(serverssl); SSL_free(clientssl); serverssl = clientssl = NULL; /* Check we can resume a session with a different SHA-256 ciphersuite */ if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_128_CCM_SHA256")) || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(SSL_set_session(clientssl, clntsess)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_true(SSL_session_reused(clientssl))) goto end; SSL_SESSION_free(clntsess); clntsess = SSL_get1_session(clientssl); SSL_shutdown(clientssl); SSL_shutdown(serverssl); SSL_free(serverssl); SSL_free(clientssl); serverssl = clientssl = NULL; /* * Check attempting to resume a SHA-256 session with no SHA-256 ciphersuites * succeeds but does not resume. */ if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384")) || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(SSL_set_session(clientssl, clntsess)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_SSL)) || !TEST_false(SSL_session_reused(clientssl))) goto end; SSL_SESSION_free(clntsess); clntsess = NULL; SSL_shutdown(clientssl); SSL_shutdown(serverssl); SSL_free(serverssl); SSL_free(clientssl); serverssl = clientssl = NULL; /* Create a session based on SHA384 */ if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384")) || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; clntsess = SSL_get1_session(clientssl); SSL_shutdown(clientssl); SSL_shutdown(serverssl); SSL_free(serverssl); SSL_free(clientssl); serverssl = clientssl = NULL; if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384")) || !TEST_true(SSL_CTX_set_ciphersuites(sctx, "TLS_AES_256_GCM_SHA384")) || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(SSL_set_session(clientssl, clntsess)) /* * We use SSL_ERROR_WANT_READ below so that we can pause the * connection after the initial ClientHello has been sent to * enable us to make some session changes. */ || !TEST_false(create_ssl_connection(serverssl, clientssl, SSL_ERROR_WANT_READ))) goto end; /* Trick the client into thinking this session is for a different digest */ clntsess->cipher = aes_128_gcm_sha256; clntsess->cipher_id = clntsess->cipher->id; /* * Continue the previously started connection. Server has selected a SHA-384 * ciphersuite, but client thinks the session is for SHA-256, so it should * bail out. */ if (!TEST_false(create_ssl_connection(serverssl, clientssl, SSL_ERROR_SSL)) || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()), SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED)) goto end; testresult = 1; end: SSL_SESSION_free(clntsess); SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } /* * Test TLSv1.3 Key exchange * Test 0 = Test all ECDHE Key exchange with TLSv1.3 client and server * Test 1 = Test NID_X9_62_prime256v1 with TLSv1.3 client and server * Test 2 = Test NID_secp384r1 with TLSv1.3 client and server * Test 3 = Test NID_secp521r1 with TLSv1.3 client and server * Test 4 = Test NID_X25519 with TLSv1.3 client and server * Test 5 = Test NID_X448 with TLSv1.3 client and server * Test 6 = Test all FFDHE Key exchange with TLSv1.3 client and server * Test 7 = Test NID_ffdhe2048 with TLSv1.3 client and server * Test 8 = Test NID_ffdhe3072 with TLSv1.3 client and server * Test 9 = Test NID_ffdhe4096 with TLSv1.3 client and server * Test 10 = Test NID_ffdhe6144 with TLSv1.3 client and server * Test 11 = Test NID_ffdhe8192 with TLSv1.3 client and server * Test 12 = Test all ML-KEM with TLSv1.3 client and server * Test 13 = Test MLKEM512 * Test 14 = Test MLKEM768 * Test 15 = Test MLKEM1024 * Test 16 = Test X25519MLKEM768 * Test 17 = Test SecP256r1MLKEM768 * Test 18 = Test SecP384r1MLKEM1024 * Test 19 = Test all ML-KEM with TLSv1.2 client and server * Test 20 = Test all FFDHE with TLSv1.2 client and server * Test 21 = Test all ECDHE with TLSv1.2 client and server */ # ifndef OPENSSL_NO_EC static int ecdhe_kexch_groups[] = {NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, # ifndef OPENSSL_NO_ECX NID_X25519, NID_X448 # endif }; # endif # ifndef OPENSSL_NO_DH static int ffdhe_kexch_groups[] = {NID_ffdhe2048, NID_ffdhe3072, NID_ffdhe4096, NID_ffdhe6144, NID_ffdhe8192}; # endif static int test_key_exchange(int idx) { SSL_CTX *sctx = NULL, *cctx = NULL; SSL *serverssl = NULL, *clientssl = NULL; int testresult = 0; int kexch_alg = NID_undef; int *kexch_groups = &kexch_alg; int kexch_groups_size = 1; int max_version = TLS1_3_VERSION; char *kexch_name0 = NULL; const char *kexch_names = NULL; int shared_group0; switch (idx) { # ifndef OPENSSL_NO_EC # ifndef OPENSSL_NO_TLS1_2 case 21: max_version = TLS1_2_VERSION; # endif /* Fall through */ case 0: kexch_groups = ecdhe_kexch_groups; kexch_groups_size = OSSL_NELEM(ecdhe_kexch_groups); kexch_name0 = "secp256r1"; break; case 1: kexch_alg = NID_X9_62_prime256v1; kexch_name0 = "secp256r1"; break; case 2: kexch_alg = NID_secp384r1; kexch_name0 = "secp384r1"; break; case 3: kexch_alg = NID_secp521r1; kexch_name0 = "secp521r1"; break; # ifndef OPENSSL_NO_ECX case 4: if (is_fips) return TEST_skip("X25519 might not be supported by fips provider."); kexch_alg = NID_X25519; kexch_name0 = "x25519"; break; case 5: if (is_fips) return TEST_skip("X448 might not be supported by fips provider."); kexch_alg = NID_X448; kexch_name0 = "x448"; break; # endif # endif # ifndef OPENSSL_NO_DH # ifndef OPENSSL_NO_TLS1_2 case 20: max_version = TLS1_2_VERSION; kexch_name0 = "ffdhe2048"; # endif /* Fall through */ case 6: kexch_groups = ffdhe_kexch_groups; kexch_groups_size = OSSL_NELEM(ffdhe_kexch_groups); kexch_name0 = "ffdhe2048"; break; case 7: kexch_alg = NID_ffdhe2048; kexch_name0 = "ffdhe2048"; break; case 8: kexch_alg = NID_ffdhe3072; kexch_name0 = "ffdhe3072"; break; case 9: kexch_alg = NID_ffdhe4096; kexch_name0 = "ffdhe4096"; break; case 10: kexch_alg = NID_ffdhe6144; kexch_name0 = "ffdhe6144"; break; case 11: kexch_alg = NID_ffdhe8192; kexch_name0 = "ffdhe8192"; break; # endif # ifndef OPENSSL_NO_ML_KEM # if !defined(OPENSSL_NO_TLS1_2) case 19: max_version = TLS1_2_VERSION; # if !defined(OPENSSL_NO_EC) /* Set at least one EC group so the handshake completes */ kexch_names = "MLKEM512:MLKEM768:MLKEM1024:secp256r1"; # elif !defined(OPENSSL_NO_DH) kexch_names = "MLKEM512:MLKEM768:MLKEM1024"; # else /* With neither EC nor DH TLS 1.2 can't happen */ return 1; # endif # endif /* Fall through */ case 12: kexch_groups = NULL; if (kexch_names == NULL) kexch_names = "MLKEM512:MLKEM768:MLKEM1024"; kexch_name0 = "MLKEM512"; break; case 13: kexch_groups = NULL; kexch_name0 = "MLKEM512"; kexch_names = kexch_name0; break; case 14: kexch_groups = NULL; kexch_name0 = "MLKEM768"; kexch_names = kexch_name0; break; case 15: kexch_groups = NULL; kexch_name0 = "MLKEM1024"; kexch_names = kexch_name0; break; # ifndef OPENSSL_NO_EC # ifndef OPENSSL_NO_ECX case 16: kexch_groups = NULL; kexch_name0 = "X25519MLKEM768"; kexch_names = kexch_name0; break; # endif case 17: kexch_groups = NULL; kexch_name0 = "SecP256r1MLKEM768"; kexch_names = kexch_name0; break; case 18: kexch_groups = NULL; kexch_name0 = "SecP384r1MLKEM1024"; kexch_names = kexch_name0; break; # endif # endif default: /* We're skipping this test */ return 1; } if (is_fips && fips_provider_version_lt(libctx, 3, 5, 0) && idx >= 12 && idx <= 19) return TEST_skip("ML-KEM not supported in this version of fips provider"); if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, max_version, &sctx, &cctx, cert, privkey))) goto end; if (!TEST_true(SSL_CTX_set_ciphersuites(sctx, TLS1_3_RFC_AES_128_GCM_SHA256))) goto end; if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, TLS1_3_RFC_AES_128_GCM_SHA256))) goto end; if (!TEST_true(SSL_CTX_set_cipher_list(sctx, TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":" TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256)) || !TEST_true(SSL_CTX_set_dh_auto(sctx, 1))) goto end; /* * Must include an EC ciphersuite so that we send supported groups in * TLSv1.2 */ # ifndef OPENSSL_NO_TLS1_2 if (!TEST_true(SSL_CTX_set_cipher_list(cctx, TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":" TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256))) goto end; # endif if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (kexch_groups != NULL) { if (!TEST_true(SSL_set1_groups(serverssl, kexch_groups, kexch_groups_size)) || !TEST_true(SSL_set1_groups(clientssl, kexch_groups, kexch_groups_size))) goto end; } else { if (!TEST_true(SSL_set1_groups_list(serverssl, kexch_names)) || !TEST_true(SSL_set1_groups_list(clientssl, kexch_names))) goto end; } if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; /* * If the handshake succeeds the negotiated kexch alg should be the first * one in configured, except in the case of "all" FFDHE and "all" ML-KEM * groups (idx == 19, 20), which are TLSv1.3 only so we expect no shared * group to exist. */ shared_group0 = SSL_get_shared_group(serverssl, 0); switch (idx) { case 19: # if !defined(OPENSSL_NO_EC) /* MLKEM + TLS 1.2 and no DH => "secp526r1" */ if (!TEST_int_eq(shared_group0, NID_X9_62_prime256v1)) goto end; break; # endif /* Fall through */ case 20: if (!TEST_int_eq(shared_group0, 0)) goto end; break; default: if (kexch_groups != NULL && !TEST_int_eq(shared_group0, kexch_groups[0])) goto end; if (!TEST_str_eq(SSL_group_to_name(serverssl, shared_group0), kexch_name0)) goto end; if (!TEST_str_eq(SSL_get0_group_name(serverssl), kexch_name0) || !TEST_str_eq(SSL_get0_group_name(clientssl), kexch_name0)) goto end; if (!TEST_int_eq(SSL_get_negotiated_group(serverssl), shared_group0)) goto end; if (!TEST_int_eq(SSL_get_negotiated_group(clientssl), shared_group0)) goto end; break; } testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } # if !defined(OPENSSL_NO_TLS1_2) \ && !defined(OPENSSL_NO_EC) \ && !defined(OPENSSL_NO_DH) static int set_ssl_groups(SSL *serverssl, SSL *clientssl, int clientmulti, int isecdhe, int idx) { int kexch_alg; int *kexch_groups = &kexch_alg; int numec, numff; numec = OSSL_NELEM(ecdhe_kexch_groups); numff = OSSL_NELEM(ffdhe_kexch_groups); if (isecdhe) kexch_alg = ecdhe_kexch_groups[idx]; else kexch_alg = ffdhe_kexch_groups[idx]; if (clientmulti) { if (!TEST_true(SSL_set1_groups(serverssl, kexch_groups, 1))) return 0; if (isecdhe) { if (!TEST_true(SSL_set1_groups(clientssl, ecdhe_kexch_groups, numec))) return 0; } else { if (!TEST_true(SSL_set1_groups(clientssl, ffdhe_kexch_groups, numff))) return 0; } } else { if (!TEST_true(SSL_set1_groups(clientssl, kexch_groups, 1))) return 0; if (isecdhe) { if (!TEST_true(SSL_set1_groups(serverssl, ecdhe_kexch_groups, numec))) return 0; } else { if (!TEST_true(SSL_set1_groups(serverssl, ffdhe_kexch_groups, numff))) return 0; } } return 1; } /*- * Test the SSL_get_negotiated_group() API across a battery of scenarios. * Run through both the ECDHE and FFDHE group lists used in the previous * test, for both TLS 1.2 and TLS 1.3, negotiating each group in turn, * confirming the expected result; then perform a resumption handshake * while offering the same group list, and another resumption handshake * offering a different group list. The returned value should be the * negotiated group for the initial handshake; for TLS 1.3 resumption * handshakes the returned value will be negotiated on the resumption * handshake itself, but for TLS 1.2 resumption handshakes the value will * be cached in the session from the original handshake, regardless of what * was offered in the resumption ClientHello. * * Using E for the number of EC groups and F for the number of FF groups: * E tests of ECDHE with TLS 1.3, server only has one group * F tests of FFDHE with TLS 1.3, server only has one group * E tests of ECDHE with TLS 1.2, server only has one group * F tests of FFDHE with TLS 1.2, server only has one group * E tests of ECDHE with TLS 1.3, client sends only one group * F tests of FFDHE with TLS 1.3, client sends only one group * E tests of ECDHE with TLS 1.2, client sends only one group * F tests of FFDHE with TLS 1.2, client sends only one group */ static int test_negotiated_group(int idx) { int clientmulti, istls13, isecdhe, numec, numff, numgroups; int expectednid; SSL_CTX *sctx = NULL, *cctx = NULL; SSL *serverssl = NULL, *clientssl = NULL; SSL_SESSION *origsess = NULL; int testresult = 0; int kexch_alg; int max_version = TLS1_3_VERSION; numec = OSSL_NELEM(ecdhe_kexch_groups); numff = OSSL_NELEM(ffdhe_kexch_groups); numgroups = numec + numff; clientmulti = (idx < 2 * numgroups); idx = idx % (2 * numgroups); istls13 = (idx < numgroups); idx = idx % numgroups; isecdhe = (idx < numec); if (!isecdhe) idx -= numec; /* Now 'idx' is an index into ecdhe_kexch_groups or ffdhe_kexch_groups */ if (isecdhe) kexch_alg = ecdhe_kexch_groups[idx]; else kexch_alg = ffdhe_kexch_groups[idx]; /* We expect nothing for the unimplemented TLS 1.2 FFDHE named groups */ if (!istls13 && !isecdhe) expectednid = NID_undef; else expectednid = kexch_alg; if (is_fips && (kexch_alg == NID_X25519 || kexch_alg == NID_X448)) return TEST_skip("X25519 and X448 might not be available in fips provider."); if (!istls13) max_version = TLS1_2_VERSION; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, max_version, &sctx, &cctx, cert, privkey))) goto end; /* * Force (EC)DHE ciphers for TLS 1.2. * Be sure to enable auto tmp DH so that FFDHE can succeed. */ if (!TEST_true(SSL_CTX_set_cipher_list(sctx, TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":" TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256)) || !TEST_true(SSL_CTX_set_dh_auto(sctx, 1))) goto end; if (!TEST_true(SSL_CTX_set_cipher_list(cctx, TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":" TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256))) goto end; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (!TEST_true(set_ssl_groups(serverssl, clientssl, clientmulti, isecdhe, idx))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; /* Initial handshake; always the configured one */ if (!TEST_uint_eq(SSL_get_negotiated_group(clientssl), expectednid) || !TEST_uint_eq(SSL_get_negotiated_group(serverssl), expectednid)) goto end; if (!TEST_ptr((origsess = SSL_get1_session(clientssl)))) goto end; SSL_shutdown(clientssl); SSL_shutdown(serverssl); SSL_free(serverssl); SSL_free(clientssl); serverssl = clientssl = NULL; /* First resumption attempt; use the same config as initial handshake */ if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(SSL_set_session(clientssl, origsess)) || !TEST_true(set_ssl_groups(serverssl, clientssl, clientmulti, isecdhe, idx))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_true(SSL_session_reused(clientssl))) goto end; /* Still had better agree, since nothing changed... */ if (!TEST_uint_eq(SSL_get_negotiated_group(clientssl), expectednid) || !TEST_uint_eq(SSL_get_negotiated_group(serverssl), expectednid)) goto end; SSL_shutdown(clientssl); SSL_shutdown(serverssl); SSL_free(serverssl); SSL_free(clientssl); serverssl = clientssl = NULL; /*- * Second resumption attempt * The party that picks one group changes it, which we effectuate by * changing 'idx' and updating what we expect. */ if (idx == 0) idx = 1; else idx--; if (istls13) { if (isecdhe) expectednid = ecdhe_kexch_groups[idx]; else expectednid = ffdhe_kexch_groups[idx]; /* Verify that we are changing what we expect. */ if (!TEST_int_ne(expectednid, kexch_alg)) goto end; } else { /* TLS 1.2 only supports named groups for ECDHE. */ if (isecdhe) expectednid = kexch_alg; else expectednid = 0; } if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(SSL_set_session(clientssl, origsess)) || !TEST_true(set_ssl_groups(serverssl, clientssl, clientmulti, isecdhe, idx))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_true(SSL_session_reused(clientssl))) goto end; /* Check that we get what we expected */ if (!TEST_uint_eq(SSL_get_negotiated_group(clientssl), expectednid) || !TEST_uint_eq(SSL_get_negotiated_group(serverssl), expectednid)) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); SSL_SESSION_free(origsess); return testresult; } # endif /* !defined(OPENSSL_NO_EC) && !defined(OPENSSL_NO_DH) */ /* * Test TLSv1.3 Cipher Suite * Test 0 = Set TLS1.3 cipher on context * Test 1 = Set TLS1.3 cipher on SSL * Test 2 = Set TLS1.3 and TLS1.2 cipher on context * Test 3 = Set TLS1.3 and TLS1.2 cipher on SSL */ static int test_tls13_ciphersuite(int idx) { SSL_CTX *sctx = NULL, *cctx = NULL; SSL *serverssl = NULL, *clientssl = NULL; static const struct { const char *ciphername; int fipscapable; int low_security; } t13_ciphers[] = { { TLS1_3_RFC_AES_128_GCM_SHA256, 1, 0 }, { TLS1_3_RFC_AES_256_GCM_SHA384, 1, 0 }, { TLS1_3_RFC_AES_128_CCM_SHA256, 1, 0 }, # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305) { TLS1_3_RFC_CHACHA20_POLY1305_SHA256, 0, 0 }, { TLS1_3_RFC_AES_256_GCM_SHA384 ":" TLS1_3_RFC_CHACHA20_POLY1305_SHA256, 0, 0 }, # endif /* CCM8 ciphers are considered low security due to their short tag */ { TLS1_3_RFC_AES_128_CCM_8_SHA256 ":" TLS1_3_RFC_AES_128_CCM_SHA256, 1, 1 }, # if !defined(OPENSSL_NO_INTEGRITY_ONLY_CIPHERS) /* Integrity-only cipher do not provide any confidentiality */ { TLS1_3_RFC_SHA256_SHA256, 0, 1 }, { TLS1_3_RFC_SHA384_SHA384, 0, 1 } # endif }; const char *t13_cipher = NULL; const char *t12_cipher = NULL; const char *negotiated_scipher; const char *negotiated_ccipher; int set_at_ctx = 0; int set_at_ssl = 0; int testresult = 0; int max_ver; size_t i; switch (idx) { case 0: set_at_ctx = 1; break; case 1: set_at_ssl = 1; break; case 2: set_at_ctx = 1; t12_cipher = TLS1_TXT_RSA_WITH_AES_128_SHA256; break; case 3: set_at_ssl = 1; t12_cipher = TLS1_TXT_RSA_WITH_AES_128_SHA256; break; } for (max_ver = TLS1_2_VERSION; max_ver <= TLS1_3_VERSION; max_ver++) { # ifdef OPENSSL_NO_TLS1_2 if (max_ver == TLS1_2_VERSION) continue; # endif for (i = 0; i < OSSL_NELEM(t13_ciphers); i++) { if (is_fips && !t13_ciphers[i].fipscapable) continue; t13_cipher = t13_ciphers[i].ciphername; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, max_ver, &sctx, &cctx, cert, privkey))) goto end; if (t13_ciphers[i].low_security) { SSL_CTX_set_security_level(sctx, 0); SSL_CTX_set_security_level(cctx, 0); } if (set_at_ctx) { if (!TEST_true(SSL_CTX_set_ciphersuites(sctx, t13_cipher)) || !TEST_true(SSL_CTX_set_ciphersuites(cctx, t13_cipher))) goto end; if (t12_cipher != NULL) { if (!TEST_true(SSL_CTX_set_cipher_list(sctx, t12_cipher)) || !TEST_true(SSL_CTX_set_cipher_list(cctx, t12_cipher))) goto end; } } if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (set_at_ssl) { if (!TEST_true(SSL_set_ciphersuites(serverssl, t13_cipher)) || !TEST_true(SSL_set_ciphersuites(clientssl, t13_cipher))) goto end; if (t12_cipher != NULL) { if (!TEST_true(SSL_set_cipher_list(serverssl, t12_cipher)) || !TEST_true(SSL_set_cipher_list(clientssl, t12_cipher))) goto end; } } if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; negotiated_scipher = SSL_CIPHER_get_name(SSL_get_current_cipher( serverssl)); negotiated_ccipher = SSL_CIPHER_get_name(SSL_get_current_cipher( clientssl)); if (!TEST_str_eq(negotiated_scipher, negotiated_ccipher)) goto end; /* * TEST_strn_eq is used below because t13_cipher can contain * multiple ciphersuites */ if (max_ver == TLS1_3_VERSION && !TEST_strn_eq(t13_cipher, negotiated_scipher, strlen(negotiated_scipher))) goto end; # ifndef OPENSSL_NO_TLS1_2 /* Below validation is not done when t12_cipher is NULL */ if (max_ver == TLS1_2_VERSION && t12_cipher != NULL && !TEST_str_eq(t12_cipher, negotiated_scipher)) goto end; # endif SSL_free(serverssl); serverssl = NULL; SSL_free(clientssl); clientssl = NULL; SSL_CTX_free(sctx); sctx = NULL; SSL_CTX_free(cctx); cctx = NULL; } } testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } /* * Test TLSv1.3 PSKs * Test 0 = Test new style callbacks * Test 1 = Test both new and old style callbacks * Test 2 = Test old style callbacks * Test 3 = Test old style callbacks with no certificate */ static int test_tls13_psk(int idx) { SSL_CTX *sctx = NULL, *cctx = NULL; SSL *serverssl = NULL, *clientssl = NULL; const SSL_CIPHER *cipher = NULL; const unsigned char key[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f }; int testresult = 0; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, idx == 3 ? NULL : cert, idx == 3 ? NULL : privkey))) goto end; if (idx != 3) { /* * We use a ciphersuite with SHA256 to ease testing old style PSK * callbacks which will always default to SHA256. This should not be * necessary if we have no cert/priv key. In that case the server should * prefer SHA256 automatically. */ if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_128_GCM_SHA256"))) goto end; } else { /* * As noted above the server should prefer SHA256 automatically. However * we are careful not to offer TLS_CHACHA20_POLY1305_SHA256 so this same * code works even if we are testing with only the FIPS provider loaded. */ if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384:" "TLS_AES_128_GCM_SHA256"))) goto end; } /* * Test 0: New style callbacks only * Test 1: New and old style callbacks (only the new ones should be used) * Test 2: Old style callbacks only */ if (idx == 0 || idx == 1) { SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb); SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb); } #ifndef OPENSSL_NO_PSK if (idx >= 1) { SSL_CTX_set_psk_client_callback(cctx, psk_client_cb); SSL_CTX_set_psk_server_callback(sctx, psk_server_cb); } #endif srvid = pskid; use_session_cb_cnt = 0; find_session_cb_cnt = 0; psk_client_cb_cnt = 0; psk_server_cb_cnt = 0; if (idx != 3) { /* * Check we can create a connection if callback decides not to send a * PSK */ if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_false(SSL_session_reused(clientssl)) || !TEST_false(SSL_session_reused(serverssl))) goto end; if (idx == 0 || idx == 1) { if (!TEST_true(use_session_cb_cnt == 1) || !TEST_true(find_session_cb_cnt == 0) /* * If no old style callback then below should be 0 * otherwise 1 */ || !TEST_true(psk_client_cb_cnt == idx) || !TEST_true(psk_server_cb_cnt == 0)) goto end; } else { if (!TEST_true(use_session_cb_cnt == 0) || !TEST_true(find_session_cb_cnt == 0) || !TEST_true(psk_client_cb_cnt == 1) || !TEST_true(psk_server_cb_cnt == 0)) goto end; } shutdown_ssl_connection(serverssl, clientssl); serverssl = clientssl = NULL; use_session_cb_cnt = psk_client_cb_cnt = 0; } if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; /* Create the PSK */ cipher = SSL_CIPHER_find(clientssl, TLS13_AES_128_GCM_SHA256_BYTES); clientpsk = SSL_SESSION_new(); if (!TEST_ptr(clientpsk) || !TEST_ptr(cipher) || !TEST_true(SSL_SESSION_set1_master_key(clientpsk, key, sizeof(key))) || !TEST_true(SSL_SESSION_set_cipher(clientpsk, cipher)) || !TEST_true(SSL_SESSION_set_protocol_version(clientpsk, TLS1_3_VERSION)) || !TEST_true(SSL_SESSION_up_ref(clientpsk))) goto end; serverpsk = clientpsk; /* Check we can create a connection and the PSK is used */ if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_true(SSL_session_reused(clientssl)) || !TEST_true(SSL_session_reused(serverssl))) goto end; if (idx == 0 || idx == 1) { if (!TEST_true(use_session_cb_cnt == 1) || !TEST_true(find_session_cb_cnt == 1) || !TEST_true(psk_client_cb_cnt == 0) || !TEST_true(psk_server_cb_cnt == 0)) goto end; } else { if (!TEST_true(use_session_cb_cnt == 0) || !TEST_true(find_session_cb_cnt == 0) || !TEST_true(psk_client_cb_cnt == 1) || !TEST_true(psk_server_cb_cnt == 1)) goto end; } shutdown_ssl_connection(serverssl, clientssl); serverssl = clientssl = NULL; use_session_cb_cnt = find_session_cb_cnt = 0; psk_client_cb_cnt = psk_server_cb_cnt = 0; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; /* Force an HRR */ #if defined(OPENSSL_NO_EC) if (!TEST_true(SSL_set1_groups_list(serverssl, "ffdhe3072"))) goto end; #else if (!TEST_true(SSL_set1_groups_list(serverssl, "P-384"))) goto end; #endif /* * Check we can create a connection, the PSK is used and the callbacks are * called twice. */ if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_true(SSL_session_reused(clientssl)) || !TEST_true(SSL_session_reused(serverssl))) goto end; if (idx == 0 || idx == 1) { if (!TEST_true(use_session_cb_cnt == 2) || !TEST_true(find_session_cb_cnt == 2) || !TEST_true(psk_client_cb_cnt == 0) || !TEST_true(psk_server_cb_cnt == 0)) goto end; } else { if (!TEST_true(use_session_cb_cnt == 0) || !TEST_true(find_session_cb_cnt == 0) || !TEST_true(psk_client_cb_cnt == 2) || !TEST_true(psk_server_cb_cnt == 2)) goto end; } shutdown_ssl_connection(serverssl, clientssl); serverssl = clientssl = NULL; use_session_cb_cnt = find_session_cb_cnt = 0; psk_client_cb_cnt = psk_server_cb_cnt = 0; if (idx != 3) { /* * Check that if the server rejects the PSK we can still connect, but with * a full handshake */ srvid = "Dummy Identity"; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_false(SSL_session_reused(clientssl)) || !TEST_false(SSL_session_reused(serverssl))) goto end; if (idx == 0 || idx == 1) { if (!TEST_true(use_session_cb_cnt == 1) || !TEST_true(find_session_cb_cnt == 1) || !TEST_true(psk_client_cb_cnt == 0) /* * If no old style callback then below should be 0 * otherwise 1 */ || !TEST_true(psk_server_cb_cnt == idx)) goto end; } else { if (!TEST_true(use_session_cb_cnt == 0) || !TEST_true(find_session_cb_cnt == 0) || !TEST_true(psk_client_cb_cnt == 1) || !TEST_true(psk_server_cb_cnt == 1)) goto end; } shutdown_ssl_connection(serverssl, clientssl); serverssl = clientssl = NULL; } testresult = 1; end: SSL_SESSION_free(clientpsk); SSL_SESSION_free(serverpsk); clientpsk = serverpsk = NULL; SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #ifndef OSSL_NO_USABLE_TLS1_3 /* * Test TLS1.3 connection establishment succeeds with various configurations of * the options `SSL_OP_ALLOW_NO_DHE_KEX` and `SSL_OP_PREFER_NO_DHE_KEX`. * The verification of whether the right KEX mode is chosen is not covered by * this test but by `test_tls13kexmodes`. * * Tests (idx & 1): Server has `SSL_OP_ALLOW_NO_DHE_KEX` set. * Tests (idx & 2): Server has `SSL_OP_PREFER_NO_DHE_KEX` set. * Tests (idx & 4): Client has `SSL_OP_ALLOW_NO_DHE_KEX` set. */ static int test_tls13_no_dhe_kex(const int idx) { SSL_CTX *sctx = NULL, *cctx = NULL; SSL *serverssl = NULL, *clientssl = NULL; int testresult = 0; size_t j; SSL_SESSION *saved_session; int server_allow_no_dhe = (idx & 1) != 0; int server_prefer_no_dhe = (idx & 2) != 0; int client_allow_no_dhe = (idx & 4) != 0; uint64_t server_options = 0 | (server_allow_no_dhe ? SSL_OP_ALLOW_NO_DHE_KEX : 0) | (server_prefer_no_dhe ? SSL_OP_PREFER_NO_DHE_KEX : 0); uint64_t client_options = 0 | (client_allow_no_dhe ? SSL_OP_ALLOW_NO_DHE_KEX : 0); new_called = 0; do_cache = 1; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_3_VERSION, 0, &sctx, &cctx, cert, privkey))) goto end; SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE); SSL_CTX_set_options(sctx, server_options); SSL_CTX_set_options(cctx, client_options); SSL_CTX_sess_set_new_cb(cctx, new_cachesession_cb); if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) /* Check we got the number of tickets we were expecting */ || !TEST_int_eq(2, new_called)) goto end; /* We'll reuse the last ticket. */ saved_session = sesscache[new_called - 1]; SSL_shutdown(clientssl); SSL_shutdown(serverssl); SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(cctx); clientssl = serverssl = NULL; cctx = NULL; /* * Now we resume with the last ticket we created. */ /* The server context already exists, so we only create the client. */ if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_3_VERSION, 0, NULL, &cctx, cert, privkey))) goto end; SSL_CTX_set_options(cctx, client_options); if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(SSL_set_session(clientssl, saved_session))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; /* * Make sure, the session was resumed. */ if (!TEST_true(SSL_session_reused(clientssl))) goto end; SSL_shutdown(clientssl); SSL_shutdown(serverssl); testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); for (j = 0; j < OSSL_NELEM(sesscache); j++) { SSL_SESSION_free(sesscache[j]); sesscache[j] = NULL; } SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #endif /* OSSL_NO_USABLE_TLS1_3 */ static unsigned char cookie_magic_value[] = "cookie magic"; static int generate_cookie_callback(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len) { /* * Not suitable as a real cookie generation function but good enough for * testing! */ memcpy(cookie, cookie_magic_value, sizeof(cookie_magic_value) - 1); *cookie_len = sizeof(cookie_magic_value) - 1; return 1; } static int verify_cookie_callback(SSL *ssl, const unsigned char *cookie, unsigned int cookie_len) { if (cookie_len == sizeof(cookie_magic_value) - 1 && memcmp(cookie, cookie_magic_value, cookie_len) == 0) return 1; return 0; } static int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie, size_t *cookie_len) { unsigned int temp; int res = generate_cookie_callback(ssl, cookie, &temp); *cookie_len = temp; return res; } static int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie, size_t cookie_len) { return verify_cookie_callback(ssl, cookie, cookie_len); } static int test_stateless(void) { SSL_CTX *sctx = NULL, *cctx = NULL; SSL *serverssl = NULL, *clientssl = NULL; int testresult = 0; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey))) goto end; /* The arrival of CCS messages can confuse the test */ SSL_CTX_clear_options(cctx, SSL_OP_ENABLE_MIDDLEBOX_COMPAT); if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) /* Send the first ClientHello */ || !TEST_false(create_ssl_connection(serverssl, clientssl, SSL_ERROR_WANT_READ)) /* * This should fail with a -1 return because we have no callbacks * set up */ || !TEST_int_eq(SSL_stateless(serverssl), -1)) goto end; /* Fatal error so abandon the connection from this client */ SSL_free(clientssl); clientssl = NULL; /* Set up the cookie generation and verification callbacks */ SSL_CTX_set_stateless_cookie_generate_cb(sctx, generate_stateless_cookie_callback); SSL_CTX_set_stateless_cookie_verify_cb(sctx, verify_stateless_cookie_callback); /* * Create a new connection from the client (we can reuse the server SSL * object). */ if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) /* Send the first ClientHello */ || !TEST_false(create_ssl_connection(serverssl, clientssl, SSL_ERROR_WANT_READ)) /* This should fail because there is no cookie */ || !TEST_int_eq(SSL_stateless(serverssl), 0)) goto end; /* Abandon the connection from this client */ SSL_free(clientssl); clientssl = NULL; /* * Now create a connection from a new client but with the same server SSL * object */ if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) /* Send the first ClientHello */ || !TEST_false(create_ssl_connection(serverssl, clientssl, SSL_ERROR_WANT_READ)) /* This should fail because there is no cookie */ || !TEST_int_eq(SSL_stateless(serverssl), 0) /* Send the second ClientHello */ || !TEST_false(create_ssl_connection(serverssl, clientssl, SSL_ERROR_WANT_READ)) /* This should succeed because a cookie is now present */ || !TEST_int_eq(SSL_stateless(serverssl), 1) /* Complete the connection */ || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; shutdown_ssl_connection(serverssl, clientssl); serverssl = clientssl = NULL; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #endif /* OSSL_NO_USABLE_TLS1_3 */ static int clntaddoldcb = 0; static int clntparseoldcb = 0; static int srvaddoldcb = 0; static int srvparseoldcb = 0; static int clntaddnewcb = 0; static int clntparsenewcb = 0; static int srvaddnewcb = 0; static int srvparsenewcb = 0; static int snicb = 0; #define TEST_EXT_TYPE1 0xff00 static int old_add_cb(SSL *s, unsigned int ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg) { int *server = (int *)add_arg; unsigned char *data; if (SSL_is_server(s)) srvaddoldcb++; else clntaddoldcb++; if (*server != SSL_is_server(s) || (data = OPENSSL_malloc(sizeof(*data))) == NULL) return -1; *data = 1; *out = data; *outlen = sizeof(char); return 1; } static void old_free_cb(SSL *s, unsigned int ext_type, const unsigned char *out, void *add_arg) { OPENSSL_free((unsigned char *)out); } static int old_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg) { int *server = (int *)parse_arg; if (SSL_is_server(s)) srvparseoldcb++; else clntparseoldcb++; if (*server != SSL_is_server(s) || inlen != sizeof(char) || *in != 1) return -1; return 1; } static int new_add_cb(SSL *s, unsigned int ext_type, unsigned int context, const unsigned char **out, size_t *outlen, X509 *x, size_t chainidx, int *al, void *add_arg) { int *server = (int *)add_arg; unsigned char *data; if (SSL_is_server(s)) srvaddnewcb++; else clntaddnewcb++; if (*server != SSL_is_server(s) || (data = OPENSSL_malloc(sizeof(*data))) == NULL) return -1; *data = 1; *out = data; *outlen = sizeof(*data); return 1; } static void new_free_cb(SSL *s, unsigned int ext_type, unsigned int context, const unsigned char *out, void *add_arg) { OPENSSL_free((unsigned char *)out); } static int new_parse_cb(SSL *s, unsigned int ext_type, unsigned int context, const unsigned char *in, size_t inlen, X509 *x, size_t chainidx, int *al, void *parse_arg) { int *server = (int *)parse_arg; if (SSL_is_server(s)) srvparsenewcb++; else clntparsenewcb++; if (*server != SSL_is_server(s) || inlen != sizeof(char) || *in != 1) return -1; return 1; } static int sni_cb(SSL *s, int *al, void *arg) { SSL_CTX *ctx = (SSL_CTX *)arg; if (SSL_set_SSL_CTX(s, ctx) == NULL) { *al = SSL_AD_INTERNAL_ERROR; return SSL_TLSEXT_ERR_ALERT_FATAL; } snicb++; return SSL_TLSEXT_ERR_OK; } static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx) { return 1; } /* * Custom call back tests. * Test 0: Old style callbacks in TLSv1.2 * Test 1: New style callbacks in TLSv1.2 * Test 2: New style callbacks in TLSv1.2 with SNI * Test 3: New style callbacks in TLSv1.3. Extensions in CH and EE * Test 4: New style callbacks in TLSv1.3. Extensions in CH, SH, EE, Cert + NST * Test 5: New style callbacks in TLSv1.3. Extensions in CR + Client Cert */ static int test_custom_exts(int tst) { SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; static int server = 1; static int client = 0; SSL_SESSION *sess = NULL; unsigned int context; #if defined(OPENSSL_NO_TLS1_2) && !defined(OSSL_NO_USABLE_TLS1_3) /* Skip tests for TLSv1.2 and below in this case */ if (tst < 3) return 1; #endif /* Reset callback counters */ clntaddoldcb = clntparseoldcb = srvaddoldcb = srvparseoldcb = 0; clntaddnewcb = clntparsenewcb = srvaddnewcb = srvparsenewcb = 0; snicb = 0; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey))) goto end; if (tst == 2 && !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), NULL, TLS1_VERSION, 0, &sctx2, NULL, cert, privkey))) goto end; if (tst < 3) { SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3); SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3); if (sctx2 != NULL) SSL_CTX_set_options(sctx2, SSL_OP_NO_TLSv1_3); } if (tst == 5) { context = SSL_EXT_TLS1_3_CERTIFICATE_REQUEST | SSL_EXT_TLS1_3_CERTIFICATE; SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb); if (!TEST_int_eq(SSL_CTX_use_certificate_file(cctx, cert, SSL_FILETYPE_PEM), 1) || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(cctx, privkey, SSL_FILETYPE_PEM), 1) || !TEST_int_eq(SSL_CTX_check_private_key(cctx), 1)) goto end; } else if (tst == 4) { context = SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO | SSL_EXT_TLS1_3_SERVER_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS | SSL_EXT_TLS1_3_CERTIFICATE | SSL_EXT_TLS1_3_NEW_SESSION_TICKET; } else { context = SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS; } /* Create a client side custom extension */ if (tst == 0) { if (!TEST_true(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1, old_add_cb, old_free_cb, &client, old_parse_cb, &client))) goto end; } else { if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1, context, new_add_cb, new_free_cb, &client, new_parse_cb, &client))) goto end; } /* Should not be able to add duplicates */ if (!TEST_false(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1, old_add_cb, old_free_cb, &client, old_parse_cb, &client)) || !TEST_false(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1, context, new_add_cb, new_free_cb, &client, new_parse_cb, &client))) goto end; /* Create a server side custom extension */ if (tst == 0) { if (!TEST_true(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1, old_add_cb, old_free_cb, &server, old_parse_cb, &server))) goto end; } else { if (!TEST_true(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1, context, new_add_cb, new_free_cb, &server, new_parse_cb, &server))) goto end; if (sctx2 != NULL && !TEST_true(SSL_CTX_add_custom_ext(sctx2, TEST_EXT_TYPE1, context, new_add_cb, new_free_cb, &server, new_parse_cb, &server))) goto end; } /* Should not be able to add duplicates */ if (!TEST_false(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1, old_add_cb, old_free_cb, &server, old_parse_cb, &server)) || !TEST_false(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1, context, new_add_cb, new_free_cb, &server, new_parse_cb, &server))) goto end; if (tst == 2) { /* Set up SNI */ if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb)) || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2))) goto end; } if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; if (tst == 0) { if (clntaddoldcb != 1 || clntparseoldcb != 1 || srvaddoldcb != 1 || srvparseoldcb != 1) goto end; } else if (tst == 1 || tst == 2 || tst == 3) { if (clntaddnewcb != 1 || clntparsenewcb != 1 || srvaddnewcb != 1 || srvparsenewcb != 1 || (tst != 2 && snicb != 0) || (tst == 2 && snicb != 1)) goto end; } else if (tst == 5) { if (clntaddnewcb != 1 || clntparsenewcb != 1 || srvaddnewcb != 1 || srvparsenewcb != 1) goto end; } else { /* In this case there 2 NewSessionTicket messages created */ if (clntaddnewcb != 1 || clntparsenewcb != 5 || srvaddnewcb != 5 || srvparsenewcb != 1) goto end; } sess = SSL_get1_session(clientssl); SSL_shutdown(clientssl); SSL_shutdown(serverssl); SSL_free(serverssl); SSL_free(clientssl); serverssl = clientssl = NULL; if (tst == 3 || tst == 5) { /* We don't bother with the resumption aspects for these tests */ testresult = 1; goto end; } if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(SSL_set_session(clientssl, sess)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; /* * For a resumed session we expect to add the ClientHello extension. For the * old style callbacks we ignore it on the server side because they set * SSL_EXT_IGNORE_ON_RESUMPTION. The new style callbacks do not ignore * them. */ if (tst == 0) { if (clntaddoldcb != 2 || clntparseoldcb != 1 || srvaddoldcb != 1 || srvparseoldcb != 1) goto end; } else if (tst == 1 || tst == 2 || tst == 3) { if (clntaddnewcb != 2 || clntparsenewcb != 2 || srvaddnewcb != 2 || srvparsenewcb != 2) goto end; } else { /* * No Certificate message extensions in the resumption handshake, * 2 NewSessionTickets in the initial handshake, 1 in the resumption */ if (clntaddnewcb != 2 || clntparsenewcb != 8 || srvaddnewcb != 8 || srvparsenewcb != 2) goto end; } testresult = 1; end: SSL_SESSION_free(sess); SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx2); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #if !defined(OPENSSL_NO_TLS1_2) && !defined(OSSL_NO_USABLE_TLS1_3) #define SYNTHV1CONTEXT (SSL_EXT_TLS1_2_AND_BELOW_ONLY \ | SSL_EXT_CLIENT_HELLO \ | SSL_EXT_TLS1_2_SERVER_HELLO \ | SSL_EXT_IGNORE_ON_RESUMPTION) #define TLS13CONTEXT (SSL_EXT_TLS1_3_CERTIFICATE \ | SSL_EXT_TLS1_2_SERVER_HELLO \ | SSL_EXT_CLIENT_HELLO) #define SERVERINFO_CUSTOM \ 0x00, (char)TLSEXT_TYPE_signed_certificate_timestamp, \ 0x00, 0x03, \ 0x04, 0x05, 0x06 \ static const unsigned char serverinfo_custom_tls13[] = { 0x00, 0x00, (TLS13CONTEXT >> 8) & 0xff, TLS13CONTEXT & 0xff, SERVERINFO_CUSTOM }; static const unsigned char serverinfo_custom_v2[] = { 0x00, 0x00, (SYNTHV1CONTEXT >> 8) & 0xff, SYNTHV1CONTEXT & 0xff, SERVERINFO_CUSTOM }; static const unsigned char serverinfo_custom_v1[] = { SERVERINFO_CUSTOM }; static const size_t serverinfo_custom_tls13_len = sizeof(serverinfo_custom_tls13); static const size_t serverinfo_custom_v2_len = sizeof(serverinfo_custom_v2); static const size_t serverinfo_custom_v1_len = sizeof(serverinfo_custom_v1); static int serverinfo_custom_parse_cb(SSL *s, unsigned int ext_type, unsigned int context, const unsigned char *in, size_t inlen, X509 *x, size_t chainidx, int *al, void *parse_arg) { const size_t len = serverinfo_custom_v1_len; const unsigned char *si = &serverinfo_custom_v1[len - 3]; int *p_cb_result = (int*)parse_arg; *p_cb_result = TEST_mem_eq(in, inlen, si, 3); return 1; } static int test_serverinfo_custom(const int idx) { SSL_CTX *sctx = NULL, *cctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; int cb_result = 0; /* * Following variables are set in the switch statement * according to the test iteration. * Default values do not make much sense: test would fail with them. */ int serverinfo_version = 0; int protocol_version = 0; unsigned int extension_context = 0; const unsigned char *si = NULL; size_t si_len = 0; const int call_use_serverinfo_ex = idx > 0; switch (idx) { case 0: /* FALLTHROUGH */ case 1: serverinfo_version = SSL_SERVERINFOV1; protocol_version = TLS1_2_VERSION; extension_context = SYNTHV1CONTEXT; si = serverinfo_custom_v1; si_len = serverinfo_custom_v1_len; break; case 2: serverinfo_version = SSL_SERVERINFOV2; protocol_version = TLS1_2_VERSION; extension_context = SYNTHV1CONTEXT; si = serverinfo_custom_v2; si_len = serverinfo_custom_v2_len; break; case 3: serverinfo_version = SSL_SERVERINFOV2; protocol_version = TLS1_3_VERSION; extension_context = TLS13CONTEXT; si = serverinfo_custom_tls13; si_len = serverinfo_custom_tls13_len; break; } if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_method(), TLS_method(), protocol_version, protocol_version, &sctx, &cctx, cert, privkey))) goto end; if (call_use_serverinfo_ex) { if (!TEST_true(SSL_CTX_use_serverinfo_ex(sctx, serverinfo_version, si, si_len))) goto end; } else { if (!TEST_true(SSL_CTX_use_serverinfo(sctx, si, si_len))) goto end; } if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TLSEXT_TYPE_signed_certificate_timestamp, extension_context, NULL, NULL, NULL, serverinfo_custom_parse_cb, &cb_result)) || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_int_eq(SSL_do_handshake(clientssl), 1)) goto end; if (!TEST_true(cb_result)) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #endif /* * Test that SSL_export_keying_material() produces expected results. There are * no test vectors so all we do is test that both sides of the communication * produce the same results for different protocol versions. */ #define SMALL_LABEL_LEN 10 #define LONG_LABEL_LEN 249 static int test_export_key_mat(int tst) { int testresult = 0; SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL; SSL *clientssl = NULL, *serverssl = NULL; const char label[LONG_LABEL_LEN + 1] = "test label"; const unsigned char context[] = "context"; const unsigned char *emptycontext = NULL; unsigned char longcontext[1280]; int test_longcontext = fips_provider_version_ge(libctx, 3, 3, 0); unsigned char ckeymat1[80], ckeymat2[80], ckeymat3[80], ckeymat4[80]; unsigned char skeymat1[80], skeymat2[80], skeymat3[80], skeymat4[80]; size_t labellen; const int protocols[] = { TLS1_VERSION, TLS1_1_VERSION, TLS1_2_VERSION, TLS1_3_VERSION, TLS1_3_VERSION, TLS1_3_VERSION }; #ifdef OPENSSL_NO_TLS1 if (tst == 0) return 1; #endif #ifdef OPENSSL_NO_TLS1_1 if (tst == 1) return 1; #endif if (is_fips && (tst == 0 || tst == 1)) return 1; #ifdef OPENSSL_NO_TLS1_2 if (tst == 2) return 1; #endif #ifdef OSSL_NO_USABLE_TLS1_3 if (tst >= 3) return 1; #endif if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey))) goto end; OPENSSL_assert(tst >= 0 && (size_t)tst < OSSL_NELEM(protocols)); SSL_CTX_set_max_proto_version(cctx, protocols[tst]); SSL_CTX_set_min_proto_version(cctx, protocols[tst]); if ((protocols[tst] < TLS1_2_VERSION) && (!SSL_CTX_set_cipher_list(cctx, "DEFAULT:@SECLEVEL=0") || !SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))) goto end; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; /* * Premature call of SSL_export_keying_material should just fail. */ if (!TEST_int_le(SSL_export_keying_material(clientssl, ckeymat1, sizeof(ckeymat1), label, SMALL_LABEL_LEN + 1, context, sizeof(context) - 1, 1), 0)) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; if (tst == 5) { /* * TLSv1.3 imposes a maximum label len of 249 bytes. Check we fail if we * go over that. */ if (!TEST_int_le(SSL_export_keying_material(clientssl, ckeymat1, sizeof(ckeymat1), label, LONG_LABEL_LEN + 1, context, sizeof(context) - 1, 1), 0)) goto end; testresult = 1; goto end; } else if (tst == 4) { labellen = LONG_LABEL_LEN; } else { labellen = SMALL_LABEL_LEN; } memset(longcontext, 1, sizeof(longcontext)); if (!TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat1, sizeof(ckeymat1), label, labellen, context, sizeof(context) - 1, 1), 1) || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat2, sizeof(ckeymat2), label, labellen, emptycontext, 0, 1), 1) || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat3, sizeof(ckeymat3), label, labellen, NULL, 0, 0), 1) || (test_longcontext && !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat4, sizeof(ckeymat4), label, labellen, longcontext, sizeof(longcontext), 1), 1)) || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat1, sizeof(skeymat1), label, labellen, context, sizeof(context) -1, 1), 1) || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat2, sizeof(skeymat2), label, labellen, emptycontext, 0, 1), 1) || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat3, sizeof(skeymat3), label, labellen, NULL, 0, 0), 1) || (test_longcontext && !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat4, sizeof(skeymat4), label, labellen, longcontext, sizeof(longcontext), 1), 1)) /* * Check that both sides created the same key material with the * same context. */ || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1, sizeof(skeymat1)) /* * Check that both sides created the same key material with an * empty context. */ || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2, sizeof(skeymat2)) /* * Check that both sides created the same key material without a * context. */ || !TEST_mem_eq(ckeymat3, sizeof(ckeymat3), skeymat3, sizeof(skeymat3)) /* * Check that both sides created the same key material with a * long context. */ || (test_longcontext && !TEST_mem_eq(ckeymat4, sizeof(ckeymat4), skeymat4, sizeof(skeymat4))) /* Different contexts should produce different results */ || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2, sizeof(ckeymat2))) goto end; /* * Check that an empty context and no context produce different results in * protocols less than TLSv1.3. In TLSv1.3 they should be the same. */ if ((tst < 3 && !TEST_mem_ne(ckeymat2, sizeof(ckeymat2), ckeymat3, sizeof(ckeymat3))) || (tst >= 3 && !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), ckeymat3, sizeof(ckeymat3)))) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx2); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #ifndef OSSL_NO_USABLE_TLS1_3 /* * Test that SSL_export_keying_material_early() produces expected * results. There are no test vectors so all we do is test that both * sides of the communication produce the same results for different * protocol versions. */ static int test_export_key_mat_early(int idx) { static const char label[] = "test label"; static const unsigned char context[] = "context"; int testresult = 0; SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; SSL_SESSION *sess = NULL; const unsigned char *emptycontext = NULL; unsigned char ckeymat1[80], ckeymat2[80]; unsigned char skeymat1[80], skeymat2[80]; unsigned char buf[1]; size_t readbytes, written; if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl, &sess, idx, SHA384_DIGEST_LENGTH))) goto end; /* Here writing 0 length early data is enough. */ if (!TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written)) || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf), &readbytes), SSL_READ_EARLY_DATA_ERROR) || !TEST_int_eq(SSL_get_early_data_status(serverssl), SSL_EARLY_DATA_ACCEPTED)) goto end; if (!TEST_int_eq(SSL_export_keying_material_early( clientssl, ckeymat1, sizeof(ckeymat1), label, sizeof(label) - 1, context, sizeof(context) - 1), 1) || !TEST_int_eq(SSL_export_keying_material_early( clientssl, ckeymat2, sizeof(ckeymat2), label, sizeof(label) - 1, emptycontext, 0), 1) || !TEST_int_eq(SSL_export_keying_material_early( serverssl, skeymat1, sizeof(skeymat1), label, sizeof(label) - 1, context, sizeof(context) - 1), 1) || !TEST_int_eq(SSL_export_keying_material_early( serverssl, skeymat2, sizeof(skeymat2), label, sizeof(label) - 1, emptycontext, 0), 1) /* * Check that both sides created the same key material with the * same context. */ || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1, sizeof(skeymat1)) /* * Check that both sides created the same key material with an * empty context. */ || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2, sizeof(skeymat2)) /* Different contexts should produce different results */ || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2, sizeof(ckeymat2))) goto end; testresult = 1; end: SSL_SESSION_free(sess); SSL_SESSION_free(clientpsk); SSL_SESSION_free(serverpsk); clientpsk = serverpsk = NULL; SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #define NUM_KEY_UPDATE_MESSAGES 40 /* * Test KeyUpdate. */ static int test_key_update(void) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0, i, j; char buf[20]; static char *mess = "A test message"; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_3_VERSION, 0, &sctx, &cctx, cert, privkey)) || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; for (j = 0; j < 2; j++) { /* Send lots of KeyUpdate messages */ for (i = 0; i < NUM_KEY_UPDATE_MESSAGES; i++) { if (!TEST_true(SSL_key_update(clientssl, (j == 0) ? SSL_KEY_UPDATE_NOT_REQUESTED : SSL_KEY_UPDATE_REQUESTED)) || !TEST_true(SSL_do_handshake(clientssl))) goto end; } /* Check that sending and receiving app data is ok */ if (!TEST_int_eq(SSL_write(clientssl, mess, strlen(mess)), strlen(mess)) || !TEST_int_eq(SSL_read(serverssl, buf, sizeof(buf)), strlen(mess))) goto end; if (!TEST_int_eq(SSL_write(serverssl, mess, strlen(mess)), strlen(mess)) || !TEST_int_eq(SSL_read(clientssl, buf, sizeof(buf)), strlen(mess))) goto end; } testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } /* * Test we can handle a KeyUpdate (update requested) message while * write data is pending in peer. * Test 0: Client sends KeyUpdate while Server is writing * Test 1: Server sends KeyUpdate while Client is writing */ static int test_key_update_peer_in_write(int tst) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; char buf[20]; static char *mess = "A test message"; BIO *bretry = BIO_new(bio_s_always_retry()); BIO *tmp = NULL; SSL *peerupdate = NULL, *peerwrite = NULL; if (!TEST_ptr(bretry) || !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_3_VERSION, 0, &sctx, &cctx, cert, privkey)) || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; peerupdate = tst == 0 ? clientssl : serverssl; peerwrite = tst == 0 ? serverssl : clientssl; if (!TEST_true(SSL_key_update(peerupdate, SSL_KEY_UPDATE_REQUESTED)) || !TEST_int_eq(SSL_do_handshake(peerupdate), 1)) goto end; /* Swap the writing endpoint's write BIO to force a retry */ tmp = SSL_get_wbio(peerwrite); if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) { tmp = NULL; goto end; } SSL_set0_wbio(peerwrite, bretry); bretry = NULL; /* Write data that we know will fail with SSL_ERROR_WANT_WRITE */ if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), -1) || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_WRITE) || !TEST_true(SSL_want_write(peerwrite)) || !TEST_true(SSL_net_write_desired(peerwrite))) goto end; /* Reinstate the original writing endpoint's write BIO */ SSL_set0_wbio(peerwrite, tmp); tmp = NULL; /* Now read some data - we will read the key update */ if (!TEST_int_eq(SSL_read(peerwrite, buf, sizeof(buf)), -1) || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_READ) || !TEST_true(SSL_want_read(peerwrite)) || !TEST_true(SSL_net_read_desired(peerwrite))) goto end; /* * Complete the write we started previously and read it from the other * endpoint */ if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess)) || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess))) goto end; /* Write more data to ensure we send the KeyUpdate message back */ if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess)) || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess))) goto end; if (!TEST_false(SSL_net_read_desired(peerwrite)) || !TEST_false(SSL_net_write_desired(peerwrite)) || !TEST_int_eq(SSL_want(peerwrite), SSL_NOTHING)) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); BIO_free(bretry); BIO_free(tmp); return testresult; } /* * Test we can handle a KeyUpdate (update requested) message while * peer read data is pending after peer accepted keyupdate(the msg header * had been read 5 bytes). * Test 0: Client sends KeyUpdate while Server is reading * Test 1: Server sends KeyUpdate while Client is reading */ static int test_key_update_peer_in_read(int tst) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; char prbuf[515], lwbuf[515] = {0}; static char *mess = "A test message"; BIO *lbio = NULL, *pbio = NULL; SSL *local = NULL, *peer = NULL; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_3_VERSION, 0, &sctx, &cctx, cert, privkey)) || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; local = tst == 0 ? clientssl : serverssl; peer = tst == 0 ? serverssl : clientssl; if (!TEST_int_eq(BIO_new_bio_pair(&lbio, 512, &pbio, 512), 1)) goto end; SSL_set_bio(local, lbio, lbio); SSL_set_bio(peer, pbio, pbio); /* * we first write keyupdate msg then appdata in local * write data in local will fail with SSL_ERROR_WANT_WRITE,because * lwbuf app data msg size + key updata msg size > 512(the size of * the bio pair buffer) */ if (!TEST_true(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED)) || !TEST_int_eq(SSL_write(local, lwbuf, sizeof(lwbuf)), -1) || !TEST_int_eq(SSL_get_error(local, -1), SSL_ERROR_WANT_WRITE)) goto end; /* * first read keyupdate msg in peer in peer * then read appdata that we know will fail with SSL_ERROR_WANT_READ */ if (!TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), -1) || !TEST_int_eq(SSL_get_error(peer, -1), SSL_ERROR_WANT_READ)) goto end; /* Now write some data in peer - we will write the key update */ if (!TEST_int_eq(SSL_write(peer, mess, strlen(mess)), strlen(mess))) goto end; /* * write data in local previously that we will complete * read data in peer previously that we will complete */ if (!TEST_int_eq(SSL_write(local, lwbuf, sizeof(lwbuf)), sizeof(lwbuf)) || !TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), sizeof(prbuf))) goto end; /* check that sending and receiving appdata ok */ if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess)) || !TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), strlen(mess))) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } /* * Test we can't send a KeyUpdate (update requested) message while * local write data is pending. * Test 0: Client sends KeyUpdate while Client is writing * Test 1: Server sends KeyUpdate while Server is writing */ static int test_key_update_local_in_write(int tst) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; char buf[20]; static char *mess = "A test message"; BIO *bretry = BIO_new(bio_s_always_retry()); BIO *tmp = NULL; SSL *local = NULL, *peer = NULL; if (!TEST_ptr(bretry) || !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_3_VERSION, 0, &sctx, &cctx, cert, privkey)) || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; local = tst == 0 ? clientssl : serverssl; peer = tst == 0 ? serverssl : clientssl; /* Swap the writing endpoint's write BIO to force a retry */ tmp = SSL_get_wbio(local); if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) { tmp = NULL; goto end; } SSL_set0_wbio(local, bretry); bretry = NULL; /* write data in local will fail with SSL_ERROR_WANT_WRITE */ if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), -1) || !TEST_int_eq(SSL_get_error(local, -1), SSL_ERROR_WANT_WRITE)) goto end; /* Reinstate the original writing endpoint's write BIO */ SSL_set0_wbio(local, tmp); tmp = NULL; /* SSL_key_update will fail, because writing in local*/ if (!TEST_false(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED)) || !TEST_int_eq(ERR_GET_REASON(ERR_peek_error()), SSL_R_BAD_WRITE_RETRY)) goto end; ERR_clear_error(); /* write data in local previously that we will complete */ if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess))) goto end; /* SSL_key_update will succeed because there is no pending write data */ if (!TEST_true(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED)) || !TEST_int_eq(SSL_do_handshake(local), 1)) goto end; /* * we write some appdata in local * read data in peer - we will read the keyupdate msg */ if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess)) || !TEST_int_eq(SSL_read(peer, buf, sizeof(buf)), strlen(mess))) goto end; /* Write more peer more data to ensure we send the keyupdate message back */ if (!TEST_int_eq(SSL_write(peer, mess, strlen(mess)), strlen(mess)) || !TEST_int_eq(SSL_read(local, buf, sizeof(buf)), strlen(mess))) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); BIO_free(bretry); BIO_free(tmp); return testresult; } /* * Test we can handle a KeyUpdate (update requested) message while * local read data is pending(the msg header had been read 5 bytes). * Test 0: Client sends KeyUpdate while Client is reading * Test 1: Server sends KeyUpdate while Server is reading */ static int test_key_update_local_in_read(int tst) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; char lrbuf[515], pwbuf[515] = {0}, prbuf[20]; static char *mess = "A test message"; BIO *lbio = NULL, *pbio = NULL; SSL *local = NULL, *peer = NULL; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_3_VERSION, 0, &sctx, &cctx, cert, privkey)) || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; local = tst == 0 ? clientssl : serverssl; peer = tst == 0 ? serverssl : clientssl; if (!TEST_int_eq(BIO_new_bio_pair(&lbio, 512, &pbio, 512), 1)) goto end; SSL_set_bio(local, lbio, lbio); SSL_set_bio(peer, pbio, pbio); /* write app data in peer will fail with SSL_ERROR_WANT_WRITE */ if (!TEST_int_eq(SSL_write(peer, pwbuf, sizeof(pwbuf)), -1) || !TEST_int_eq(SSL_get_error(peer, -1), SSL_ERROR_WANT_WRITE)) goto end; /* read appdata in local will fail with SSL_ERROR_WANT_READ */ if (!TEST_int_eq(SSL_read(local, lrbuf, sizeof(lrbuf)), -1) || !TEST_int_eq(SSL_get_error(local, -1), SSL_ERROR_WANT_READ)) goto end; /* SSL_do_handshake will send keyupdate msg */ if (!TEST_true(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED)) || !TEST_int_eq(SSL_do_handshake(local), 1)) goto end; /* * write data in peer previously that we will complete * read data in local previously that we will complete */ if (!TEST_int_eq(SSL_write(peer, pwbuf, sizeof(pwbuf)), sizeof(pwbuf)) || !TEST_int_eq(SSL_read(local, lrbuf, sizeof(lrbuf)), sizeof(lrbuf))) goto end; /* * write data in local * read data in peer - we will read the key update */ if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess)) || !TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), strlen(mess))) goto end; /* Write more peer data to ensure we send the keyupdate message back */ if (!TEST_int_eq(SSL_write(peer, mess, strlen(mess)), strlen(mess)) || !TEST_int_eq(SSL_read(local, lrbuf, sizeof(lrbuf)), strlen(mess))) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #endif /* OSSL_NO_USABLE_TLS1_3 */ /* * Test clearing a connection via SSL_clear(), or resetting it via * SSL_set_connect_state()/SSL_set_accept_state() * Test 0: SSL_set_connect_state, TLSv1.3 * Test 1: SSL_set_connect_state, TLSv1.2 * Test 2: SSL_set_accept_state, TLSv1.3 * Test 3: SSL_set_accept_state, TLSv1.2 * Test 4: SSL_clear (client), TLSv1.3 * Test 5: SSL_clear (client), TLSv1.2 * Test 6: SSL_clear (server), TLSv1.3 * Test 7: SSL_clear (server), TLSv1.2 */ static int test_ssl_clear(int idx) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; SSL *writer, *reader; int testresult = 0; int tls12test, servertest, cleartest; size_t written, readbytes; const char *msg = "Hello World"; unsigned char buf[5]; tls12test = idx & 1; idx >>= 1; servertest = idx & 1; idx >>= 1; cleartest = idx & 1; #ifdef OPENSSL_NO_TLS1_2 if (tls12test == 1) return TEST_skip("No TLSv1.2 in this build"); #endif /* Create an initial connection */ if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey)) || (tls12test && !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION))) || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; if (servertest) { writer = clientssl; reader = serverssl; } else { writer = serverssl; reader = clientssl; } /* Write some data */ if (!TEST_true(SSL_write_ex(writer, msg, strlen(msg), &written)) || written != strlen(msg)) goto end; /* * Read a partial record. The remaining buffered data should be cleared by * the subsequent clear/reset */ if (!TEST_true(SSL_read_ex(reader, buf, sizeof(buf), &readbytes)) || readbytes != sizeof(buf)) goto end; SSL_shutdown(clientssl); SSL_shutdown(serverssl); /* Reset/clear one SSL object in order to reuse it. We free the other one */ if (servertest) { if (cleartest) { if (!TEST_true(SSL_clear(serverssl))) goto end; } else { SSL_set_accept_state(serverssl); } SSL_free(clientssl); clientssl = NULL; } else { if (cleartest) { if (!TEST_true(SSL_clear(clientssl))) goto end; } else { SSL_set_connect_state(clientssl); } SSL_free(serverssl); serverssl = NULL; } if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_true(servertest || SSL_session_reused(clientssl))) goto end; SSL_shutdown(clientssl); SSL_shutdown(serverssl); testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } /* Parse CH and retrieve any MFL extension value if present */ static int get_MFL_from_client_hello(BIO *bio, int *mfl_codemfl_code) { long len; unsigned char *data; PACKET pkt, pkt2, pkt3; unsigned int MFL_code = 0, type = 0; if (!TEST_uint_gt(len = BIO_get_mem_data(bio, (char **) &data), 0)) goto end; memset(&pkt, 0, sizeof(pkt)); memset(&pkt2, 0, sizeof(pkt2)); memset(&pkt3, 0, sizeof(pkt3)); if (!TEST_long_gt(len, 0) || !TEST_true(PACKET_buf_init(&pkt, data, len)) /* Skip the record header */ || !PACKET_forward(&pkt, SSL3_RT_HEADER_LENGTH) /* Skip the handshake message header */ || !TEST_true(PACKET_forward(&pkt, SSL3_HM_HEADER_LENGTH)) /* Skip client version and random */ || !TEST_true(PACKET_forward(&pkt, CLIENT_VERSION_LEN + SSL3_RANDOM_SIZE)) /* Skip session id */ || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2)) /* Skip ciphers */ || !TEST_true(PACKET_get_length_prefixed_2(&pkt, &pkt2)) /* Skip compression */ || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2)) /* Extensions len */ || !TEST_true(PACKET_as_length_prefixed_2(&pkt, &pkt2))) goto end; /* Loop through all extensions */ while (PACKET_remaining(&pkt2)) { if (!TEST_true(PACKET_get_net_2(&pkt2, &type)) || !TEST_true(PACKET_get_length_prefixed_2(&pkt2, &pkt3))) goto end; if (type == TLSEXT_TYPE_max_fragment_length) { if (!TEST_uint_ne(PACKET_remaining(&pkt3), 0) || !TEST_true(PACKET_get_1(&pkt3, &MFL_code))) goto end; *mfl_codemfl_code = MFL_code; return 1; } } end: return 0; } /* Maximum-Fragment-Length TLS extension mode to test */ static const unsigned char max_fragment_len_test[] = { TLSEXT_max_fragment_length_512, TLSEXT_max_fragment_length_1024, TLSEXT_max_fragment_length_2048, TLSEXT_max_fragment_length_4096 }; static int test_max_fragment_len_ext(int idx_tst) { SSL_CTX *ctx = NULL; SSL *con = NULL; int testresult = 0, MFL_mode = 0; BIO *rbio, *wbio; if (!TEST_true(create_ssl_ctx_pair(libctx, NULL, TLS_client_method(), TLS1_VERSION, 0, NULL, &ctx, NULL, NULL))) return 0; if (!TEST_true(SSL_CTX_set_tlsext_max_fragment_length( ctx, max_fragment_len_test[idx_tst]))) goto end; con = SSL_new(ctx); if (!TEST_ptr(con)) goto end; rbio = BIO_new(BIO_s_mem()); wbio = BIO_new(BIO_s_mem()); if (!TEST_ptr(rbio)|| !TEST_ptr(wbio)) { BIO_free(rbio); BIO_free(wbio); goto end; } SSL_set_bio(con, rbio, wbio); if (!TEST_int_le(SSL_connect(con), 0)) { /* This shouldn't succeed because we don't have a server! */ goto end; } if (!TEST_true(get_MFL_from_client_hello(wbio, &MFL_mode))) /* no MFL in client hello */ goto end; if (!TEST_true(max_fragment_len_test[idx_tst] == MFL_mode)) goto end; testresult = 1; end: SSL_free(con); SSL_CTX_free(ctx); return testresult; } #ifndef OSSL_NO_USABLE_TLS1_3 static int test_pha_key_update(void) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey))) return 0; if (!TEST_true(SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION)) || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_3_VERSION)) || !TEST_true(SSL_CTX_set_min_proto_version(cctx, TLS1_3_VERSION)) || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_3_VERSION))) goto end; SSL_CTX_set_post_handshake_auth(cctx, 1); if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL); if (!TEST_true(SSL_verify_client_post_handshake(serverssl))) goto end; if (!TEST_true(SSL_key_update(clientssl, SSL_KEY_UPDATE_NOT_REQUESTED))) goto end; /* Start handshake on the server */ if (!TEST_int_eq(SSL_do_handshake(serverssl), 1)) goto end; /* Starts with SSL_connect(), but it's really just SSL_do_handshake() */ if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; SSL_shutdown(clientssl); SSL_shutdown(serverssl); testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #endif #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2) static SRP_VBASE *vbase = NULL; static int ssl_srp_cb(SSL *s, int *ad, void *arg) { int ret = SSL3_AL_FATAL; char *username; SRP_user_pwd *user = NULL; username = SSL_get_srp_username(s); if (username == NULL) { *ad = SSL_AD_INTERNAL_ERROR; goto err; } user = SRP_VBASE_get1_by_user(vbase, username); if (user == NULL) { *ad = SSL_AD_INTERNAL_ERROR; goto err; } if (SSL_set_srp_server_param(s, user->N, user->g, user->s, user->v, user->info) <= 0) { *ad = SSL_AD_INTERNAL_ERROR; goto err; } ret = 0; err: SRP_user_pwd_free(user); return ret; } static int create_new_vfile(char *userid, char *password, const char *filename) { char *gNid = NULL; OPENSSL_STRING *row = OPENSSL_zalloc(sizeof(row) * (DB_NUMBER + 1)); TXT_DB *db = NULL; int ret = 0; BIO *out = NULL, *dummy = BIO_new_mem_buf("", 0); size_t i; if (!TEST_ptr(dummy) || !TEST_ptr(row)) goto end; gNid = SRP_create_verifier_ex(userid, password, &row[DB_srpsalt], &row[DB_srpverifier], NULL, NULL, libctx, NULL); if (!TEST_ptr(gNid)) goto end; /* * The only way to create an empty TXT_DB is to provide a BIO with no data * in it! */ db = TXT_DB_read(dummy, DB_NUMBER); if (!TEST_ptr(db)) goto end; out = BIO_new_file(filename, "w"); if (!TEST_ptr(out)) goto end; row[DB_srpid] = OPENSSL_strdup(userid); row[DB_srptype] = OPENSSL_strdup("V"); row[DB_srpgN] = OPENSSL_strdup(gNid); if (!TEST_ptr(row[DB_srpid]) || !TEST_ptr(row[DB_srptype]) || !TEST_ptr(row[DB_srpgN]) || !TEST_true(TXT_DB_insert(db, row))) goto end; row = NULL; if (TXT_DB_write(out, db) <= 0) goto end; ret = 1; end: if (row != NULL) { for (i = 0; i < DB_NUMBER; i++) OPENSSL_free(row[i]); } OPENSSL_free(row); BIO_free(dummy); BIO_free(out); TXT_DB_free(db); return ret; } static int create_new_vbase(char *userid, char *password) { BIGNUM *verifier = NULL, *salt = NULL; const SRP_gN *lgN = NULL; SRP_user_pwd *user_pwd = NULL; int ret = 0; lgN = SRP_get_default_gN(NULL); if (!TEST_ptr(lgN)) goto end; if (!TEST_true(SRP_create_verifier_BN_ex(userid, password, &salt, &verifier, lgN->N, lgN->g, libctx, NULL))) goto end; user_pwd = OPENSSL_zalloc(sizeof(*user_pwd)); if (!TEST_ptr(user_pwd)) goto end; user_pwd->N = lgN->N; user_pwd->g = lgN->g; user_pwd->id = OPENSSL_strdup(userid); if (!TEST_ptr(user_pwd->id)) goto end; user_pwd->v = verifier; user_pwd->s = salt; verifier = salt = NULL; if (sk_SRP_user_pwd_insert(vbase->users_pwd, user_pwd, 0) == 0) goto end; user_pwd = NULL; ret = 1; end: SRP_user_pwd_free(user_pwd); BN_free(salt); BN_free(verifier); return ret; } /* * SRP tests * * Test 0: Simple successful SRP connection, new vbase * Test 1: Connection failure due to bad password, new vbase * Test 2: Simple successful SRP connection, vbase loaded from existing file * Test 3: Connection failure due to bad password, vbase loaded from existing * file * Test 4: Simple successful SRP connection, vbase loaded from new file * Test 5: Connection failure due to bad password, vbase loaded from new file */ static int test_srp(int tst) { char *userid = "test", *password = "password", *tstsrpfile; SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int ret, testresult = 0; vbase = SRP_VBASE_new(NULL); if (!TEST_ptr(vbase)) goto end; if (tst == 0 || tst == 1) { if (!TEST_true(create_new_vbase(userid, password))) goto end; } else { if (tst == 4 || tst == 5) { if (!TEST_true(create_new_vfile(userid, password, tmpfilename))) goto end; tstsrpfile = tmpfilename; } else { tstsrpfile = srpvfile; } if (!TEST_int_eq(SRP_VBASE_init(vbase, tstsrpfile), SRP_NO_ERROR)) goto end; } if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey))) goto end; if (!TEST_int_gt(SSL_CTX_set_srp_username_callback(sctx, ssl_srp_cb), 0) || !TEST_true(SSL_CTX_set_cipher_list(cctx, "SRP-AES-128-CBC-SHA")) || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_2_VERSION)) || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION)) || !TEST_int_gt(SSL_CTX_set_srp_username(cctx, userid), 0)) goto end; if (tst % 2 == 1) { if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, "badpass"), 0)) goto end; } else { if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, password), 0)) goto end; } if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE); if (ret) { if (!TEST_true(tst % 2 == 0)) goto end; } else { if (!TEST_true(tst % 2 == 1)) goto end; } testresult = 1; end: SRP_VBASE_free(vbase); vbase = NULL; SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #endif static int info_cb_failed = 0; static int info_cb_offset = 0; static int info_cb_this_state = -1; static struct info_cb_states_st { int where; const char *statestr; } info_cb_states[][60] = { { /* TLSv1.2 server followed by resumption */ {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"}, {SSL_CB_LOOP, "TWSC"}, {SSL_CB_LOOP, "TWSKE"}, {SSL_CB_LOOP, "TWSD"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWSD"}, {SSL_CB_LOOP, "TRCKE"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWST"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {0, NULL}, }, { /* TLSv1.2 client followed by resumption */ {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRSC"}, {SSL_CB_LOOP, "TRSKE"}, {SSL_CB_LOOP, "TRSD"}, {SSL_CB_LOOP, "TWCKE"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TRST"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {0, NULL}, }, { /* TLSv1.3 server followed by resumption */ {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWSC"}, {SSL_CB_LOOP, "TWSCV"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TED"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"}, {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TED"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {0, NULL}, }, { /* TLSv1.3 client followed by resumption */ {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"}, {SSL_CB_LOOP, "TRSC"}, {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {0, NULL}, }, { /* TLSv1.3 server, early_data */ {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TWEOED"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {0, NULL}, }, { /* TLSv1.3 client, early_data */ {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TPEDE"}, {SSL_CB_LOOP, "TWEOED"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {0, NULL}, }, { /* TLSv1.3 server, certificate compression, followed by resumption */ {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWSCC"}, {SSL_CB_LOOP, "TWSCV"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TED"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"}, {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TED"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {0, NULL}, }, { /* TLSv1.3 client, certificate compression, followed by resumption */ {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"}, {SSL_CB_LOOP, "TRSCC"}, {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {0, NULL}, }, { {0, NULL}, } }; static void sslapi_info_callback(const SSL *s, int where, int ret) { struct info_cb_states_st *state = info_cb_states[info_cb_offset]; /* We do not ever expect a connection to fail in this test */ if (!TEST_false(ret == 0)) { info_cb_failed = 1; return; } /* * Do some sanity checks. We never expect these things to happen in this * test */ if (!TEST_false((SSL_is_server(s) && (where & SSL_ST_CONNECT) != 0)) || !TEST_false(!SSL_is_server(s) && (where & SSL_ST_ACCEPT) != 0) || !TEST_int_ne(state[++info_cb_this_state].where, 0)) { info_cb_failed = 1; return; } /* Now check we're in the right state */ if (!TEST_true((where & state[info_cb_this_state].where) != 0)) { info_cb_failed = 1; return; } if ((where & SSL_CB_LOOP) != 0 && !TEST_int_eq(strcmp(SSL_state_string(s), state[info_cb_this_state].statestr), 0)) { info_cb_failed = 1; return; } /* * Check that, if we've got SSL_CB_HANDSHAKE_DONE we are not in init */ if ((where & SSL_CB_HANDSHAKE_DONE) && SSL_in_init((SSL *)s) != 0) { info_cb_failed = 1; return; } } /* * Test the info callback gets called when we expect it to. * * Test 0: TLSv1.2, server * Test 1: TLSv1.2, client * Test 2: TLSv1.3, server * Test 3: TLSv1.3, client * Test 4: TLSv1.3, server, early_data * Test 5: TLSv1.3, client, early_data * Test 6: TLSv1.3, server, compressed certificate * Test 7: TLSv1.3, client, compressed certificate */ static int test_info_callback(int tst) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; SSL_SESSION *clntsess = NULL; int testresult = 0; int tlsvers; if (tst < 2) { /* We need either ECDHE or DHE for the TLSv1.2 test to work */ #if !defined(OPENSSL_NO_TLS1_2) && (!defined(OPENSSL_NO_EC) \ || !defined(OPENSSL_NO_DH)) tlsvers = TLS1_2_VERSION; #else return 1; #endif } else { #ifndef OSSL_NO_USABLE_TLS1_3 tlsvers = TLS1_3_VERSION; #else return 1; #endif } /* Reset globals */ info_cb_failed = 0; info_cb_this_state = -1; info_cb_offset = tst; #ifndef OSSL_NO_USABLE_TLS1_3 if (tst >= 4 && tst < 6) { SSL_SESSION *sess = NULL; size_t written, readbytes; unsigned char buf[80]; OSSL_TIME timer; /* early_data tests */ if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl, &sess, 0, SHA384_DIGEST_LENGTH))) goto end; /* We don't actually need this reference */ SSL_SESSION_free(sess); SSL_set_info_callback((tst % 2) == 0 ? serverssl : clientssl, sslapi_info_callback); /* Write and read some early data and then complete the connection */ timer = ossl_time_now(); if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1), &written)) || !TEST_size_t_eq(written, strlen(MSG1))) goto end; if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf), &readbytes), SSL_READ_EARLY_DATA_SUCCESS)) { testresult = check_early_data_timeout(timer); goto end; } if (!TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1)) || !TEST_int_eq(SSL_get_early_data_status(serverssl), SSL_EARLY_DATA_ACCEPTED) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_false(info_cb_failed)) goto end; testresult = 1; goto end; } #endif if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), tlsvers, tlsvers, &sctx, &cctx, cert, privkey))) goto end; if (!TEST_true(SSL_CTX_set_dh_auto(sctx, 1))) goto end; /* * For even numbered tests we check the server callbacks. For odd numbers we * check the client. */ SSL_CTX_set_info_callback((tst % 2) == 0 ? sctx : cctx, sslapi_info_callback); if (tst >= 6) { if (!SSL_CTX_compress_certs(sctx, 0)) goto end; } if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_false(info_cb_failed)) goto end; clntsess = SSL_get1_session(clientssl); SSL_shutdown(clientssl); SSL_shutdown(serverssl); SSL_free(serverssl); SSL_free(clientssl); serverssl = clientssl = NULL; /* Now do a resumption */ if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(SSL_set_session(clientssl, clntsess)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_true(SSL_session_reused(clientssl)) || !TEST_false(info_cb_failed)) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_SESSION_free(clntsess); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } static int test_ssl_pending(int tst) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; char msg[] = "A test message"; char buf[5]; size_t written, readbytes; if (tst == 0) { if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey))) goto end; } else { #ifndef OPENSSL_NO_DTLS if (!TEST_true(create_ssl_ctx_pair(libctx, DTLS_server_method(), DTLS_client_method(), DTLS1_VERSION, 0, &sctx, &cctx, cert, privkey))) goto end; # ifdef OPENSSL_NO_DTLS1_2 /* Not supported in the FIPS provider */ if (is_fips) { testresult = 1; goto end; }; /* * Default sigalgs are SHA1 based in = 8 && tst <= 13) return 1; #endif gen_tick_called = dec_tick_called = tick_key_cb_called = 0; /* Which tests the ticket key callback should request renewal for */ if (tst == 10 || tst == 11 || tst == 16 || tst == 17) tick_key_renew = 1; else if (tst == 12 || tst == 13 || tst == 18 || tst == 19) tick_key_renew = -1; /* abort sending the ticket/0-length ticket */ else tick_key_renew = 0; /* Which tests the decrypt ticket callback should request renewal for */ switch (tst) { case 0: case 1: tick_dec_ret = SSL_TICKET_RETURN_IGNORE; break; case 2: case 3: tick_dec_ret = SSL_TICKET_RETURN_IGNORE_RENEW; break; case 4: case 5: tick_dec_ret = SSL_TICKET_RETURN_USE; break; case 6: case 7: tick_dec_ret = SSL_TICKET_RETURN_USE_RENEW; break; default: tick_dec_ret = SSL_TICKET_RETURN_ABORT; } if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, ((tst % 2) == 0) ? TLS1_2_VERSION : TLS1_3_VERSION, &sctx, &cctx, cert, privkey))) goto end; /* * We only want sessions to resume from tickets - not the session cache. So * switch the cache off. */ if (!TEST_true(SSL_CTX_set_session_cache_mode(sctx, SSL_SESS_CACHE_OFF))) goto end; if (!TEST_true(SSL_CTX_set_session_ticket_cb(sctx, gen_tick_cb, dec_tick_cb, NULL))) goto end; if (tst >= 14) { if (!TEST_true(SSL_CTX_set_tlsext_ticket_key_evp_cb(sctx, tick_key_evp_cb))) goto end; #ifndef OPENSSL_NO_DEPRECATED_3_0 } else if (tst >= 8) { if (!TEST_true(SSL_CTX_set_tlsext_ticket_key_cb(sctx, tick_key_cb))) goto end; #endif } if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; /* * The decrypt ticket key callback in TLSv1.2 should be called even though * we have no ticket yet, because it gets called with a status of * SSL_TICKET_EMPTY (the client indicates support for tickets but does not * actually send any ticket data). This does not happen in TLSv1.3 because * it is not valid to send empty ticket data in TLSv1.3. */ if (!TEST_int_eq(gen_tick_called, 1) || !TEST_int_eq(dec_tick_called, ((tst % 2) == 0) ? 1 : 0)) goto end; gen_tick_called = dec_tick_called = 0; clntsess = SSL_get1_session(clientssl); SSL_shutdown(clientssl); SSL_shutdown(serverssl); SSL_free(serverssl); SSL_free(clientssl); serverssl = clientssl = NULL; /* Now do a resumption */ if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(SSL_set_session(clientssl, clntsess)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; if (tick_dec_ret == SSL_TICKET_RETURN_IGNORE || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW || tick_key_renew == -1) { if (!TEST_false(SSL_session_reused(clientssl))) goto end; } else { if (!TEST_true(SSL_session_reused(clientssl))) goto end; } if (!TEST_int_eq(gen_tick_called, (tick_key_renew || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW || tick_dec_ret == SSL_TICKET_RETURN_USE_RENEW) ? 1 : 0) /* There is no ticket to decrypt in tests 13 and 19 */ || !TEST_int_eq(dec_tick_called, (tst == 13 || tst == 19) ? 0 : 1)) goto end; testresult = 1; end: SSL_SESSION_free(clntsess); SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } /* * Test incorrect shutdown. * Test 0: client does not shutdown properly, * server does not set SSL_OP_IGNORE_UNEXPECTED_EOF, * server should get SSL_ERROR_SSL * Test 1: client does not shutdown properly, * server sets SSL_OP_IGNORE_UNEXPECTED_EOF, * server should get SSL_ERROR_ZERO_RETURN */ static int test_incorrect_shutdown(int tst) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; char buf[80]; BIO *c2s; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), 0, 0, &sctx, &cctx, cert, privkey))) goto end; if (tst == 1) SSL_CTX_set_options(sctx, SSL_OP_IGNORE_UNEXPECTED_EOF); if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; c2s = SSL_get_rbio(serverssl); BIO_set_mem_eof_return(c2s, 0); if (!TEST_false(SSL_read(serverssl, buf, sizeof(buf)))) goto end; if (tst == 0 && !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_SSL) ) goto end; if (tst == 1 && !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_ZERO_RETURN) ) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } /* * Test bi-directional shutdown. * Test 0: TLSv1.2 * Test 1: TLSv1.2, server continues to read/write after client shutdown * Test 2: TLSv1.3, no pending NewSessionTicket messages * Test 3: TLSv1.3, pending NewSessionTicket messages * Test 4: TLSv1.3, server continues to read/write after client shutdown, server * sends key update, client reads it * Test 5: TLSv1.3, server continues to read/write after client shutdown, server * sends CertificateRequest, client reads and ignores it * Test 6: TLSv1.3, server continues to read/write after client shutdown, client * doesn't read it */ static int test_shutdown(int tst) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; char msg[] = "A test message"; char buf[80]; size_t written, readbytes; SSL_SESSION *sess; #ifdef OPENSSL_NO_TLS1_2 if (tst <= 1) return 1; #endif #ifdef OSSL_NO_USABLE_TLS1_3 if (tst >= 2) return 1; #endif if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, (tst <= 1) ? TLS1_2_VERSION : TLS1_3_VERSION, &sctx, &cctx, cert, privkey))) goto end; if (tst == 5) SSL_CTX_set_post_handshake_auth(cctx, 1); if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (tst == 3) { if (!TEST_true(create_bare_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE, 1, 0)) || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL) || !TEST_false(SSL_SESSION_is_resumable(sess))) goto end; } else if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL) || !TEST_true(SSL_SESSION_is_resumable(sess))) { goto end; } if (!TEST_int_eq(SSL_shutdown(clientssl), 0)) goto end; if (tst >= 4) { /* * Reading on the server after the client has sent close_notify should * fail and provide SSL_ERROR_ZERO_RETURN */ if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes)) || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_ZERO_RETURN) || !TEST_int_eq(SSL_get_shutdown(serverssl), SSL_RECEIVED_SHUTDOWN) /* * Even though we're shutdown on receive we should still be * able to write. */ || !TEST_true(SSL_write(serverssl, msg, sizeof(msg)))) goto end; if (tst == 4 && !TEST_true(SSL_key_update(serverssl, SSL_KEY_UPDATE_REQUESTED))) goto end; if (tst == 5) { SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL); if (!TEST_true(SSL_verify_client_post_handshake(serverssl))) goto end; } if ((tst == 4 || tst == 5) && !TEST_true(SSL_write(serverssl, msg, sizeof(msg)))) goto end; if (!TEST_int_eq(SSL_shutdown(serverssl), 1)) goto end; if (tst == 4 || tst == 5) { /* Should still be able to read data from server */ if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)) || !TEST_size_t_eq(readbytes, sizeof(msg)) || !TEST_int_eq(memcmp(msg, buf, readbytes), 0) || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)) || !TEST_size_t_eq(readbytes, sizeof(msg)) || !TEST_int_eq(memcmp(msg, buf, readbytes), 0)) goto end; } } /* Writing on the client after sending close_notify shouldn't be possible */ if (!TEST_false(SSL_write_ex(clientssl, msg, sizeof(msg), &written))) goto end; if (tst < 4) { /* * For these tests the client has sent close_notify but it has not yet * been received by the server. The server has not sent close_notify * yet. */ if (!TEST_int_eq(SSL_shutdown(serverssl), 0) /* * Writing on the server after sending close_notify shouldn't * be possible. */ || !TEST_false(SSL_write_ex(serverssl, msg, sizeof(msg), &written)) || !TEST_int_eq(SSL_shutdown(clientssl), 1) || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL) || !TEST_true(SSL_SESSION_is_resumable(sess)) || !TEST_int_eq(SSL_shutdown(serverssl), 1)) goto end; } else if (tst == 4 || tst == 5) { /* * In this test the client has sent close_notify and it has been * received by the server which has responded with a close_notify. The * client needs to read the close_notify sent by the server. */ if (!TEST_int_eq(SSL_shutdown(clientssl), 1) || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL) || !TEST_true(SSL_SESSION_is_resumable(sess))) goto end; } else { /* * tst == 6 * * The client has sent close_notify and is expecting a close_notify * back, but instead there is application data first. The shutdown * should fail with a fatal error. */ if (!TEST_int_eq(SSL_shutdown(clientssl), -1) || !TEST_int_eq(SSL_get_error(clientssl, -1), SSL_ERROR_SSL)) goto end; } testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } /* * Test that sending close_notify alerts works correctly in the case of a * retryable write failure. */ static int test_async_shutdown(void) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; BIO *bretry = BIO_new(bio_s_always_retry()), *tmp = NULL; if (!TEST_ptr(bretry)) goto end; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), 0, 0, &sctx, &cctx, cert, privkey))) goto end; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; /* Close write side of clientssl */ if (!TEST_int_eq(SSL_shutdown(clientssl), 0)) goto end; tmp = SSL_get_wbio(serverssl); if (!TEST_true(BIO_up_ref(tmp))) { tmp = NULL; goto end; } SSL_set0_wbio(serverssl, bretry); bretry = NULL; /* First server shutdown should fail because of a retrable write failure */ if (!TEST_int_eq(SSL_shutdown(serverssl), -1) || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_WANT_WRITE)) goto end; /* Second server shutdown should fail for the same reason */ if (!TEST_int_eq(SSL_shutdown(serverssl), -1) || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_WANT_WRITE)) goto end; SSL_set0_wbio(serverssl, tmp); tmp = NULL; /* Third server shutdown should send close_notify */ if (!TEST_int_eq(SSL_shutdown(serverssl), 0)) goto end; /* Fourth server shutdown should read close_notify from client and finish */ if (!TEST_int_eq(SSL_shutdown(serverssl), 1)) goto end; /* Client should also successfully fully shutdown */ if (!TEST_int_eq(SSL_shutdown(clientssl), 1)) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); BIO_free(bretry); BIO_free(tmp); return testresult; } #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3) static int cert_cb_cnt; static int load_chain(const char *file, EVP_PKEY **pkey, X509 **x509, STACK_OF(X509) *chain) { char *path = test_mk_file_path(certsdir, file); BIO *in = NULL; X509 *x = NULL; int ok = 0; if (path == NULL) return 0; if ((in = BIO_new(BIO_s_file())) == NULL || BIO_read_filename(in, path) <= 0) goto out; if (pkey == NULL) { if ((x = X509_new_ex(libctx, NULL)) == NULL || PEM_read_bio_X509(in, &x, NULL, NULL) == NULL) goto out; if (chain == NULL) *x509 = x; else if (!sk_X509_push(chain, x)) goto out; } else if (PEM_read_bio_PrivateKey_ex(in, pkey, NULL, NULL, libctx, NULL) == NULL) { goto out; } x = NULL; ok = 1; out: X509_free(x); BIO_free(in); OPENSSL_free(path); return ok; } static int cert_cb(SSL *s, void *arg) { SSL_CTX *ctx = (SSL_CTX *)arg; EVP_PKEY *pkey = NULL; X509 *x509 = NULL, *x = NULL; STACK_OF(X509) *chain = NULL; int ret = 0; if (cert_cb_cnt == 0) { /* Suspend the handshake */ cert_cb_cnt++; return -1; } else if (cert_cb_cnt == 1) { /* * Update the SSL_CTX, set the certificate and private key and then * continue the handshake normally. */ if (ctx != NULL && !TEST_ptr(SSL_set_SSL_CTX(s, ctx))) return 0; if (!TEST_true(SSL_use_certificate_file(s, cert, SSL_FILETYPE_PEM)) || !TEST_true(SSL_use_PrivateKey_file(s, privkey, SSL_FILETYPE_PEM)) || !TEST_true(SSL_check_private_key(s))) return 0; cert_cb_cnt++; return 1; } else if (cert_cb_cnt == 3) { int rv; chain = sk_X509_new_null(); if (!TEST_ptr(chain) || !TEST_true(load_chain("ca-cert.pem", NULL, NULL, chain)) || !TEST_true(load_chain("root-cert.pem", NULL, NULL, chain)) || !TEST_true(load_chain("p256-ee-rsa-ca-cert.pem", NULL, &x509, NULL)) || !TEST_true(load_chain("p256-ee-rsa-ca-key.pem", &pkey, NULL, NULL))) goto out; rv = SSL_check_chain(s, x509, pkey, chain); /* * If the cert doesn't show as valid here (e.g., because we don't * have any shared sigalgs), then we will not set it, and there will * be no certificate at all on the SSL or SSL_CTX. This, in turn, * will cause tls_choose_sigalgs() to fail the connection. */ if ((rv & (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE)) == (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE)) { if (!SSL_use_cert_and_key(s, x509, pkey, NULL, 1)) goto out; } ret = 1; } /* Abort the handshake */ out: EVP_PKEY_free(pkey); X509_free(x509); X509_free(x); OSSL_STACK_OF_X509_free(chain); return ret; } /* * Test the certificate callback. * Test 0: Callback fails * Test 1: Success - no SSL_set_SSL_CTX() in the callback * Test 2: Success - SSL_set_SSL_CTX() in the callback * Test 3: Success - Call SSL_check_chain from the callback * Test 4: Failure - SSL_check_chain fails from callback due to bad cert in the * chain * Test 5: Failure - SSL_check_chain fails from callback due to bad ee cert */ static int test_cert_cb_int(int prot, int tst) { SSL_CTX *cctx = NULL, *sctx = NULL, *snictx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0, ret; #ifdef OPENSSL_NO_EC /* We use an EC cert in these tests, so we skip in a no-ec build */ if (tst >= 3) return 1; #endif if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), prot, prot, &sctx, &cctx, NULL, NULL))) goto end; if (tst == 0) cert_cb_cnt = -1; else if (tst >= 3) cert_cb_cnt = 3; else cert_cb_cnt = 0; if (tst == 2) { snictx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method()); if (!TEST_ptr(snictx)) goto end; } SSL_CTX_set_cert_cb(sctx, cert_cb, snictx); if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (tst == 4) { /* * We cause SSL_check_chain() to fail by specifying sig_algs that * the chain doesn't meet (the root uses an RSA cert) */ if (!TEST_true(SSL_set1_sigalgs_list(clientssl, "ecdsa_secp256r1_sha256"))) goto end; } else if (tst == 5) { /* * We cause SSL_check_chain() to fail by specifying sig_algs that * the ee cert doesn't meet (the ee uses an ECDSA cert) */ if (!TEST_true(SSL_set1_sigalgs_list(clientssl, "rsa_pss_rsae_sha256:rsa_pkcs1_sha256"))) goto end; } ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE); if (!TEST_true(tst == 0 || tst == 4 || tst == 5 ? !ret : ret) || (tst > 0 && !TEST_int_eq((cert_cb_cnt - 2) * (cert_cb_cnt - 3), 0))) { goto end; } testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); SSL_CTX_free(snictx); return testresult; } #endif static int test_cert_cb(int tst) { int testresult = 1; #ifndef OPENSSL_NO_TLS1_2 testresult &= test_cert_cb_int(TLS1_2_VERSION, tst); #endif #ifndef OSSL_NO_USABLE_TLS1_3 testresult &= test_cert_cb_int(TLS1_3_VERSION, tst); #endif return testresult; } static int client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey) { X509 *xcert; EVP_PKEY *privpkey; BIO *in = NULL; BIO *priv_in = NULL; /* Check that SSL_get0_peer_certificate() returns something sensible */ if (!TEST_ptr(SSL_get0_peer_certificate(ssl))) return 0; in = BIO_new_file(cert, "r"); if (!TEST_ptr(in)) return 0; if (!TEST_ptr(xcert = X509_new_ex(libctx, NULL)) || !TEST_ptr(PEM_read_bio_X509(in, &xcert, NULL, NULL)) || !TEST_ptr(priv_in = BIO_new_file(privkey, "r")) || !TEST_ptr(privpkey = PEM_read_bio_PrivateKey_ex(priv_in, NULL, NULL, NULL, libctx, NULL))) goto err; *x509 = xcert; *pkey = privpkey; BIO_free(in); BIO_free(priv_in); return 1; err: X509_free(xcert); BIO_free(in); BIO_free(priv_in); return 0; } static int test_client_cert_cb(int tst) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; #ifdef OPENSSL_NO_TLS1_2 if (tst == 0) return 1; #endif #ifdef OSSL_NO_USABLE_TLS1_3 if (tst == 1) return 1; #endif if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, tst == 0 ? TLS1_2_VERSION : TLS1_3_VERSION, &sctx, &cctx, cert, privkey))) goto end; /* * Test that setting a client_cert_cb results in a client certificate being * sent. */ SSL_CTX_set_client_cert_cb(cctx, client_cert_cb); SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb); if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3) /* * Test setting certificate authorities on both client and server. * * Test 0: SSL_CTX_set0_CA_list() only * Test 1: Both SSL_CTX_set0_CA_list() and SSL_CTX_set_client_CA_list() * Test 2: Only SSL_CTX_set_client_CA_list() */ static int test_ca_names_int(int prot, int tst) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; size_t i; X509_NAME *name[] = { NULL, NULL, NULL, NULL }; char *strnames[] = { "Jack", "Jill", "John", "Joanne" }; STACK_OF(X509_NAME) *sk1 = NULL, *sk2 = NULL; const STACK_OF(X509_NAME) *sktmp = NULL; for (i = 0; i < OSSL_NELEM(name); i++) { name[i] = X509_NAME_new(); if (!TEST_ptr(name[i]) || !TEST_true(X509_NAME_add_entry_by_txt(name[i], "CN", MBSTRING_ASC, (unsigned char *) strnames[i], -1, -1, 0))) goto end; } if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, prot, &sctx, &cctx, cert, privkey))) goto end; SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER, NULL); if (tst == 0 || tst == 1) { if (!TEST_ptr(sk1 = sk_X509_NAME_new_null()) || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[0]))) || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[1]))) || !TEST_ptr(sk2 = sk_X509_NAME_new_null()) || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[0]))) || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[1])))) goto end; SSL_CTX_set0_CA_list(sctx, sk1); SSL_CTX_set0_CA_list(cctx, sk2); sk1 = sk2 = NULL; } if (tst == 1 || tst == 2) { if (!TEST_ptr(sk1 = sk_X509_NAME_new_null()) || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[2]))) || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[3]))) || !TEST_ptr(sk2 = sk_X509_NAME_new_null()) || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[2]))) || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[3])))) goto end; SSL_CTX_set_client_CA_list(sctx, sk1); SSL_CTX_set_client_CA_list(cctx, sk2); sk1 = sk2 = NULL; } if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; /* * We only expect certificate authorities to have been sent to the server * if we are using TLSv1.3 and SSL_set0_CA_list() was used */ sktmp = SSL_get0_peer_CA_list(serverssl); if (prot == TLS1_3_VERSION && (tst == 0 || tst == 1)) { if (!TEST_ptr(sktmp) || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2) || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0), name[0]), 0) || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1), name[1]), 0)) goto end; } else if (!TEST_ptr_null(sktmp)) { goto end; } /* * In all tests we expect certificate authorities to have been sent to the * client. However, SSL_set_client_CA_list() should override * SSL_set0_CA_list() */ sktmp = SSL_get0_peer_CA_list(clientssl); if (!TEST_ptr(sktmp) || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2) || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0), name[tst == 0 ? 0 : 2]), 0) || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1), name[tst == 0 ? 1 : 3]), 0)) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); for (i = 0; i < OSSL_NELEM(name); i++) X509_NAME_free(name[i]); sk_X509_NAME_pop_free(sk1, X509_NAME_free); sk_X509_NAME_pop_free(sk2, X509_NAME_free); return testresult; } #endif static int test_ca_names(int tst) { int testresult = 1; #ifndef OPENSSL_NO_TLS1_2 testresult &= test_ca_names_int(TLS1_2_VERSION, tst); #endif #ifndef OSSL_NO_USABLE_TLS1_3 testresult &= test_ca_names_int(TLS1_3_VERSION, tst); #endif return testresult; } #ifndef OPENSSL_NO_TLS1_2 static const char *multiblock_cipherlist_data[]= { "AES128-SHA", "AES128-SHA256", "AES256-SHA", "AES256-SHA256", }; /* Reduce the fragment size - so the multiblock test buffer can be small */ # define MULTIBLOCK_FRAGSIZE 512 static int test_multiblock_write(int test_index) { static const char *fetchable_ciphers[]= { "AES-128-CBC-HMAC-SHA1", "AES-128-CBC-HMAC-SHA256", "AES-256-CBC-HMAC-SHA1", "AES-256-CBC-HMAC-SHA256" }; const char *cipherlist = multiblock_cipherlist_data[test_index]; const SSL_METHOD *smeth = TLS_server_method(); const SSL_METHOD *cmeth = TLS_client_method(); int min_version = TLS1_VERSION; int max_version = TLS1_2_VERSION; /* Don't select TLS1_3 */ SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; /* * Choose a buffer large enough to perform a multi-block operation * i.e: write_len >= 4 * frag_size * 9 * is chosen so that multiple multiblocks are used + some leftover. */ unsigned char msg[MULTIBLOCK_FRAGSIZE * 9]; unsigned char buf[sizeof(msg)], *p = buf; size_t readbytes, written, len; EVP_CIPHER *ciph = NULL; /* * Check if the cipher exists before attempting to use it since it only has * a hardware specific implementation. */ ciph = EVP_CIPHER_fetch(libctx, fetchable_ciphers[test_index], ""); if (ciph == NULL) { TEST_skip("Multiblock cipher is not available for %s", cipherlist); return 1; } EVP_CIPHER_free(ciph); /* Set up a buffer with some data that will be sent to the client */ RAND_bytes(msg, sizeof(msg)); if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, min_version, max_version, &sctx, &cctx, cert, privkey))) goto end; if (!TEST_true(SSL_CTX_set_max_send_fragment(sctx, MULTIBLOCK_FRAGSIZE))) goto end; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; /* settings to force it to use AES-CBC-HMAC_SHA */ SSL_set_options(serverssl, SSL_OP_NO_ENCRYPT_THEN_MAC); if (!TEST_true(SSL_CTX_set_cipher_list(cctx, cipherlist))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; if (!TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written)) || !TEST_size_t_eq(written, sizeof(msg))) goto end; len = written; while (len > 0) { if (!TEST_true(SSL_read_ex(clientssl, p, MULTIBLOCK_FRAGSIZE, &readbytes))) goto end; p += readbytes; len -= readbytes; } if (!TEST_mem_eq(msg, sizeof(msg), buf, sizeof(buf))) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #endif /* OPENSSL_NO_TLS1_2 */ static int test_session_timeout(int test) { /* * Test session ordering and timeout * Can't explicitly test performance of the new code, * but can test to see if the ordering of the sessions * are correct, and they are removed as expected */ SSL_SESSION *early = NULL; SSL_SESSION *middle = NULL; SSL_SESSION *late = NULL; SSL_CTX *ctx; int testresult = 0; time_t now = time(NULL); #define TIMEOUT 10 if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_method())) || !TEST_ptr(early = SSL_SESSION_new()) || !TEST_ptr(middle = SSL_SESSION_new()) || !TEST_ptr(late = SSL_SESSION_new())) goto end; /* assign unique session ids */ early->session_id_length = SSL3_SSL_SESSION_ID_LENGTH; memset(early->session_id, 1, SSL3_SSL_SESSION_ID_LENGTH); middle->session_id_length = SSL3_SSL_SESSION_ID_LENGTH; memset(middle->session_id, 2, SSL3_SSL_SESSION_ID_LENGTH); late->session_id_length = SSL3_SSL_SESSION_ID_LENGTH; memset(late->session_id, 3, SSL3_SSL_SESSION_ID_LENGTH); if (!TEST_int_eq(SSL_CTX_add_session(ctx, early), 1) || !TEST_int_eq(SSL_CTX_add_session(ctx, middle), 1) || !TEST_int_eq(SSL_CTX_add_session(ctx, late), 1)) goto end; /* Make sure they are all added */ if (!TEST_ptr(early->prev) || !TEST_ptr(middle->prev) || !TEST_ptr(late->prev)) goto end; if (!TEST_time_t_ne(SSL_SESSION_set_time_ex(early, now - 10), 0) || !TEST_time_t_ne(SSL_SESSION_set_time_ex(middle, now), 0) || !TEST_time_t_ne(SSL_SESSION_set_time_ex(late, now + 10), 0)) goto end; if (!TEST_int_ne(SSL_SESSION_set_timeout(early, TIMEOUT), 0) || !TEST_int_ne(SSL_SESSION_set_timeout(middle, TIMEOUT), 0) || !TEST_int_ne(SSL_SESSION_set_timeout(late, TIMEOUT), 0)) goto end; /* Make sure they are all still there */ if (!TEST_ptr(early->prev) || !TEST_ptr(middle->prev) || !TEST_ptr(late->prev)) goto end; /* Make sure they are in the expected order */ if (!TEST_ptr_eq(late->next, middle) || !TEST_ptr_eq(middle->next, early) || !TEST_ptr_eq(early->prev, middle) || !TEST_ptr_eq(middle->prev, late)) goto end; /* This should remove "early" */ SSL_CTX_flush_sessions_ex(ctx, now + TIMEOUT - 1); if (!TEST_ptr_null(early->prev) || !TEST_ptr(middle->prev) || !TEST_ptr(late->prev)) goto end; /* This should remove "middle" */ SSL_CTX_flush_sessions_ex(ctx, now + TIMEOUT + 1); if (!TEST_ptr_null(early->prev) || !TEST_ptr_null(middle->prev) || !TEST_ptr(late->prev)) goto end; /* This should remove "late" */ SSL_CTX_flush_sessions_ex(ctx, now + TIMEOUT + 11); if (!TEST_ptr_null(early->prev) || !TEST_ptr_null(middle->prev) || !TEST_ptr_null(late->prev)) goto end; /* Add them back in again */ if (!TEST_int_eq(SSL_CTX_add_session(ctx, early), 1) || !TEST_int_eq(SSL_CTX_add_session(ctx, middle), 1) || !TEST_int_eq(SSL_CTX_add_session(ctx, late), 1)) goto end; /* Make sure they are all added */ if (!TEST_ptr(early->prev) || !TEST_ptr(middle->prev) || !TEST_ptr(late->prev)) goto end; /* This should remove all of them */ SSL_CTX_flush_sessions_ex(ctx, 0); if (!TEST_ptr_null(early->prev) || !TEST_ptr_null(middle->prev) || !TEST_ptr_null(late->prev)) goto end; (void)SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_UPDATE_TIME | SSL_CTX_get_session_cache_mode(ctx)); /* make sure |now| is NOT equal to the current time */ now -= 10; if (!TEST_time_t_ne(SSL_SESSION_set_time_ex(early, now), 0) || !TEST_int_eq(SSL_CTX_add_session(ctx, early), 1) || !TEST_time_t_ne(SSL_SESSION_get_time_ex(early), now)) goto end; testresult = 1; end: SSL_CTX_free(ctx); SSL_SESSION_free(early); SSL_SESSION_free(middle); SSL_SESSION_free(late); return testresult; } /* * Test that a session cache overflow works as expected * Test 0: TLSv1.3, timeout on new session later than old session * Test 1: TLSv1.2, timeout on new session later than old session * Test 2: TLSv1.3, timeout on new session earlier than old session * Test 3: TLSv1.2, timeout on new session earlier than old session */ #if !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2) static int test_session_cache_overflow(int idx) { SSL_CTX *sctx = NULL, *cctx = NULL; SSL *serverssl = NULL, *clientssl = NULL; int testresult = 0; SSL_SESSION *sess = NULL; #ifdef OSSL_NO_USABLE_TLS1_3 /* If no TLSv1.3 available then do nothing in this case */ if (idx % 2 == 0) return TEST_skip("No TLSv1.3 available"); #endif #ifdef OPENSSL_NO_TLS1_2 /* If no TLSv1.2 available then do nothing in this case */ if (idx % 2 == 1) return TEST_skip("No TLSv1.2 available"); #endif if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, (idx % 2 == 0) ? TLS1_3_VERSION : TLS1_2_VERSION, &sctx, &cctx, cert, privkey)) || !TEST_true(SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET))) goto end; SSL_CTX_sess_set_get_cb(sctx, get_session_cb); get_sess_val = NULL; SSL_CTX_sess_set_cache_size(sctx, 1); if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; if (idx > 1) { sess = SSL_get_session(serverssl); if (!TEST_ptr(sess)) goto end; /* * Cause this session to have a longer timeout than the next session to * be added. */ if (!TEST_true(SSL_SESSION_set_timeout(sess, LONG_MAX))) { sess = NULL; goto end; } sess = NULL; } SSL_shutdown(serverssl); SSL_shutdown(clientssl); SSL_free(serverssl); SSL_free(clientssl); serverssl = clientssl = NULL; /* * Session cache size is 1 and we already populated the cache with a session * so the next connection should cause an overflow. */ if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; /* * The session we just negotiated may have been already removed from the * internal cache - but we will return it anyway from our external cache. */ get_sess_val = SSL_get_session(serverssl); if (!TEST_ptr(get_sess_val)) goto end; sess = SSL_get1_session(clientssl); if (!TEST_ptr(sess)) goto end; SSL_shutdown(serverssl); SSL_shutdown(clientssl); SSL_free(serverssl); SSL_free(clientssl); serverssl = clientssl = NULL; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (!TEST_true(SSL_set_session(clientssl, sess))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); SSL_SESSION_free(sess); return testresult; } #endif /* !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2) */ /* * Test 0: Client sets servername and server acknowledges it (TLSv1.2) * Test 1: Client sets servername and server does not acknowledge it (TLSv1.2) * Test 2: Client sets inconsistent servername on resumption (TLSv1.2) * Test 3: Client does not set servername on initial handshake (TLSv1.2) * Test 4: Client does not set servername on resumption handshake (TLSv1.2) * Test 5: Client sets servername and server acknowledges it (TLSv1.3) * Test 6: Client sets servername and server does not acknowledge it (TLSv1.3) * Test 7: Client sets inconsistent servername on resumption (TLSv1.3) * Test 8: Client does not set servername on initial handshake(TLSv1.3) * Test 9: Client does not set servername on resumption handshake (TLSv1.3) */ static int test_servername(int tst) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; SSL_SESSION *sess = NULL; const char *sexpectedhost = NULL, *cexpectedhost = NULL; #ifdef OPENSSL_NO_TLS1_2 if (tst <= 4) return 1; #endif #ifdef OSSL_NO_USABLE_TLS1_3 if (tst >= 5) return 1; #endif if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, (tst <= 4) ? TLS1_2_VERSION : TLS1_3_VERSION, &sctx, &cctx, cert, privkey)) || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (tst != 1 && tst != 6) { if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, hostname_cb))) goto end; } if (tst != 3 && tst != 8) { if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost"))) goto end; sexpectedhost = cexpectedhost = "goodhost"; } if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; if (!TEST_str_eq(SSL_get_servername(clientssl, TLSEXT_NAMETYPE_host_name), cexpectedhost) || !TEST_str_eq(SSL_get_servername(serverssl, TLSEXT_NAMETYPE_host_name), sexpectedhost)) goto end; /* Now repeat with a resumption handshake */ if (!TEST_int_eq(SSL_shutdown(clientssl), 0) || !TEST_ptr_ne(sess = SSL_get1_session(clientssl), NULL) || !TEST_true(SSL_SESSION_is_resumable(sess)) || !TEST_int_eq(SSL_shutdown(serverssl), 0)) goto end; SSL_free(clientssl); SSL_free(serverssl); clientssl = serverssl = NULL; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (!TEST_true(SSL_set_session(clientssl, sess))) goto end; sexpectedhost = cexpectedhost = "goodhost"; if (tst == 2 || tst == 7) { /* Set an inconsistent hostname */ if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "altgoodhost"))) goto end; /* * In TLSv1.2 we expect the hostname from the original handshake, in * TLSv1.3 we expect the hostname from this handshake */ if (tst == 7) sexpectedhost = cexpectedhost = "altgoodhost"; if (!TEST_str_eq(SSL_get_servername(clientssl, TLSEXT_NAMETYPE_host_name), "altgoodhost")) goto end; } else if (tst == 4 || tst == 9) { /* * A TLSv1.3 session does not associate a session with a servername, * but a TLSv1.2 session does. */ if (tst == 9) sexpectedhost = cexpectedhost = NULL; if (!TEST_str_eq(SSL_get_servername(clientssl, TLSEXT_NAMETYPE_host_name), cexpectedhost)) goto end; } else { if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost"))) goto end; /* * In a TLSv1.2 resumption where the hostname was not acknowledged * we expect the hostname on the server to be empty. On the client we * return what was requested in this case. * * Similarly if the client didn't set a hostname on an original TLSv1.2 * session but is now, the server hostname will be empty, but the client * is as we set it. */ if (tst == 1 || tst == 3) sexpectedhost = NULL; if (!TEST_str_eq(SSL_get_servername(clientssl, TLSEXT_NAMETYPE_host_name), "goodhost")) goto end; } if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; if (!TEST_true(SSL_session_reused(clientssl)) || !TEST_true(SSL_session_reused(serverssl)) || !TEST_str_eq(SSL_get_servername(clientssl, TLSEXT_NAMETYPE_host_name), cexpectedhost) || !TEST_str_eq(SSL_get_servername(serverssl, TLSEXT_NAMETYPE_host_name), sexpectedhost)) goto end; testresult = 1; end: SSL_SESSION_free(sess); SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } static int test_unknown_sigalgs_groups(void) { int ret = 0; SSL_CTX *ctx = NULL; if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method()))) goto end; if (!TEST_int_gt(SSL_CTX_set1_sigalgs_list(ctx, "RSA+SHA256:?nonexistent:?RSA+SHA512"), 0)) goto end; if (!TEST_size_t_eq(ctx->cert->conf_sigalgslen, 2) || !TEST_int_eq(ctx->cert->conf_sigalgs[0], TLSEXT_SIGALG_rsa_pkcs1_sha256) || !TEST_int_eq(ctx->cert->conf_sigalgs[1], TLSEXT_SIGALG_rsa_pkcs1_sha512)) goto end; if (!TEST_int_gt(SSL_CTX_set1_client_sigalgs_list(ctx, "RSA+SHA256:?nonexistent:?RSA+SHA512"), 0)) goto end; if (!TEST_size_t_eq(ctx->cert->client_sigalgslen, 2) || !TEST_int_eq(ctx->cert->client_sigalgs[0], TLSEXT_SIGALG_rsa_pkcs1_sha256) || !TEST_int_eq(ctx->cert->client_sigalgs[1], TLSEXT_SIGALG_rsa_pkcs1_sha512)) goto end; if (!TEST_int_le(SSL_CTX_set1_groups_list(ctx, "nonexistent"), 0)) goto end; if (!TEST_int_gt(SSL_CTX_set1_groups_list(ctx, "?nonexistent1:?nonexistent2:?nonexistent3"), 0)) goto end; #ifndef OPENSSL_NO_EC if (!TEST_int_le(SSL_CTX_set1_groups_list(ctx, "P-256:nonexistent"), 0)) goto end; if (!TEST_int_gt(SSL_CTX_set1_groups_list(ctx, "P-384:?nonexistent:?P-521"), 0)) goto end; if (!TEST_size_t_eq(ctx->ext.supportedgroups_len, 2) || !TEST_int_eq(ctx->ext.supportedgroups[0], OSSL_TLS_GROUP_ID_secp384r1) || !TEST_int_eq(ctx->ext.supportedgroups[1], OSSL_TLS_GROUP_ID_secp521r1)) goto end; #endif ret = 1; end: SSL_CTX_free(ctx); return ret; } #if (!defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)) || !defined(OPENSSL_NO_ML_KEM) static int test_configuration_of_groups(void) { int ret = 0; SSL_CTX *ctx = NULL; size_t groups_len; if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method()))) goto end; groups_len = ctx->ext.supportedgroups_len; if (!TEST_size_t_gt(groups_len, 0) || !TEST_int_gt(SSL_CTX_set1_groups_list(ctx, "DEFAULT"), 0) || !TEST_size_t_eq(ctx->ext.supportedgroups_len, groups_len)) goto end; if (!TEST_int_gt(SSL_CTX_set1_groups_list(ctx, "DEFAULT:-?P-256"), 0) # if !defined(OPENSSL_NO_EC) || !TEST_size_t_eq(ctx->ext.supportedgroups_len, groups_len - 1) # else || !TEST_size_t_eq(ctx->ext.supportedgroups_len, groups_len) # endif ) goto end; # if !defined(OPENSSL_NO_EC) if (!TEST_int_gt(SSL_CTX_set1_groups_list(ctx, "?P-256:?P-521:-?P-256"), 0) || !TEST_size_t_eq(ctx->ext.supportedgroups_len, 1) || !TEST_int_eq(ctx->ext.supportedgroups[0], OSSL_TLS_GROUP_ID_secp521r1) ) goto end; # endif ret = 1; end: SSL_CTX_free(ctx); return ret; } #endif #if !defined(OPENSSL_NO_EC) \ && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)) /* * Test that if signature algorithms are not available, then we do not offer or * accept them. * Test 0: Two RSA sig algs available: both RSA sig algs shared * Test 1: The client only has SHA2-256: only SHA2-256 algorithms shared * Test 2: The server only has SHA2-256: only SHA2-256 algorithms shared * Test 3: An RSA and an ECDSA sig alg available: both sig algs shared * Test 4: The client only has an ECDSA sig alg: only ECDSA algorithms shared * Test 5: The server only has an ECDSA sig alg: only ECDSA algorithms shared */ static int test_sigalgs_available(int idx) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; OSSL_LIB_CTX *tmpctx = OSSL_LIB_CTX_new(); OSSL_LIB_CTX *clientctx = libctx, *serverctx = libctx; OSSL_PROVIDER *filterprov = NULL; int sig, hash, numshared, numshared_expected, hash_expected, sig_expected; const char *sigalg_name, *signame_expected; if (!TEST_ptr(tmpctx)) goto end; if (idx != 0 && idx != 3) { if (!TEST_true(OSSL_PROVIDER_add_builtin(tmpctx, "filter", filter_provider_init))) goto end; filterprov = OSSL_PROVIDER_load(tmpctx, "filter"); if (!TEST_ptr(filterprov)) goto end; if (idx < 3) { /* * Only enable SHA2-256 so rsa_pss_rsae_sha384 should not be offered * or accepted for the peer that uses this libctx. Note that libssl * *requires* SHA2-256 to be available so we cannot disable that. We * also need SHA1 for our certificate. */ if (!TEST_true(filter_provider_set_filter(OSSL_OP_DIGEST, "SHA2-256:SHA1"))) goto end; } else { if (!TEST_true(filter_provider_set_filter(OSSL_OP_SIGNATURE, "ECDSA")) # ifdef OPENSSL_NO_ECX || !TEST_true(filter_provider_set_filter(OSSL_OP_KEYMGMT, "EC")) # else || !TEST_true(filter_provider_set_filter(OSSL_OP_KEYMGMT, "EC:X25519:X448")) # endif ) goto end; } if (idx == 1 || idx == 4) clientctx = tmpctx; else serverctx = tmpctx; } cctx = SSL_CTX_new_ex(clientctx, NULL, TLS_client_method()); sctx = SSL_CTX_new_ex(serverctx, NULL, TLS_server_method()); if (!TEST_ptr(cctx) || !TEST_ptr(sctx)) goto end; /* Avoid MLKEM groups that depend on possibly filtered-out digests */ if (!TEST_true(SSL_CTX_set1_groups_list(cctx, "?X25519:?secp256r1:?ffdhe2048:?ffdhe3072")) || !TEST_true(SSL_CTX_set1_groups_list(sctx, "?X25519:?secp256r1:?ffdhe2048:?ffdhe3072"))) goto end; if (idx != 5) { /* RSA first server key */ if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert, privkey))) goto end; } else { /* ECDSA P-256 first server key */ if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, 0, &sctx, &cctx, cert2, privkey2))) goto end; } /* Ensure we only use TLSv1.2 ciphersuites based on SHA256 */ if (idx < 4) { if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "ECDHE-RSA-AES128-GCM-SHA256"))) goto end; } else { if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "ECDHE-ECDSA-AES128-GCM-SHA256"))) goto end; } if (idx < 3) { if (!SSL_CTX_set1_sigalgs_list(cctx, "rsa_pss_rsae_sha384" ":rsa_pss_rsae_sha256") || !SSL_CTX_set1_sigalgs_list(sctx, "rsa_pss_rsae_sha384" ":rsa_pss_rsae_sha256")) goto end; } else { if (!SSL_CTX_set1_sigalgs_list(cctx, "rsa_pss_rsae_sha256:ECDSA+SHA256") || !SSL_CTX_set1_sigalgs_list(sctx, "rsa_pss_rsae_sha256:ECDSA+SHA256")) goto end; } /* ECDSA P-256 second server key, unless already first */ if (idx != 5 && (!TEST_int_eq(SSL_CTX_use_certificate_file(sctx, cert2, SSL_FILETYPE_PEM), 1) || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(sctx, privkey2, SSL_FILETYPE_PEM), 1) || !TEST_int_eq(SSL_CTX_check_private_key(sctx), 1))) goto end; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; /* For tests 0 and 3 we expect 2 shared sigalgs, otherwise exactly 1 */ numshared = SSL_get_shared_sigalgs(serverssl, 0, &sig, &hash, NULL, NULL, NULL); numshared_expected = 1; hash_expected = NID_sha256; sig_expected = NID_rsassaPss; signame_expected = "rsa_pss_rsae_sha256"; switch (idx) { case 0: hash_expected = NID_sha384; signame_expected = "rsa_pss_rsae_sha384"; /* FALLTHROUGH */ case 3: numshared_expected = 2; break; case 4: case 5: sig_expected = EVP_PKEY_EC; signame_expected = "ecdsa_secp256r1_sha256"; break; } if (!TEST_int_eq(numshared, numshared_expected) || !TEST_int_eq(hash, hash_expected) || !TEST_int_eq(sig, sig_expected) || !TEST_true(SSL_get0_peer_signature_name(clientssl, &sigalg_name)) || !TEST_ptr(sigalg_name) || !TEST_str_eq(sigalg_name, signame_expected)) goto end; testresult = filter_provider_check_clean_finish(); end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); OSSL_PROVIDER_unload(filterprov); OSSL_LIB_CTX_free(tmpctx); return testresult; } #endif /* * !defined(OPENSSL_NO_EC) \ * && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)) */ #ifndef OPENSSL_NO_TLS1_3 /* This test can run in TLSv1.3 even if ec and dh are disabled */ static int test_pluggable_group(int idx) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; OSSL_PROVIDER *tlsprov = OSSL_PROVIDER_load(libctx, "tls-provider"); /* Check that we are not impacted by a provider without any groups */ OSSL_PROVIDER *legacyprov = OSSL_PROVIDER_load(libctx, "legacy"); const char *group_name = idx == 0 ? "xorkemgroup" : "xorgroup"; if (!TEST_ptr(tlsprov)) goto end; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_3_VERSION, TLS1_3_VERSION, &sctx, &cctx, cert, privkey)) || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; /* ensure GROUPLIST_INCREMENT (=40) logic triggers: */ if (!TEST_true(SSL_set1_groups_list(serverssl, "xorgroup:xorkemgroup:dummy1:dummy2:dummy3:dummy4:dummy5:dummy6:dummy7:dummy8:dummy9:dummy10:dummy11:dummy12:dummy13:dummy14:dummy15:dummy16:dummy17:dummy18:dummy19:dummy20:dummy21:dummy22:dummy23:dummy24:dummy25:dummy26:dummy27:dummy28:dummy29:dummy30:dummy31:dummy32:dummy33:dummy34:dummy35:dummy36:dummy37:dummy38:dummy39:dummy40:dummy41:dummy42:dummy43")) /* removing a single algorithm from the list makes the test pass */ || !TEST_true(SSL_set1_groups_list(clientssl, group_name))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; if (!TEST_str_eq(group_name, SSL_group_to_name(serverssl, SSL_get_shared_group(serverssl, 0)))) goto end; if (!TEST_str_eq(group_name, SSL_get0_group_name(serverssl)) || !TEST_str_eq(group_name, SSL_get0_group_name(clientssl))) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); OSSL_PROVIDER_unload(tlsprov); OSSL_PROVIDER_unload(legacyprov); return testresult; } /* * This function triggers encode, decode and sign functions * of the artificial "xorhmacsig" algorithm implemented in tls-provider * creating private key and certificate files for use in TLS testing. */ static int create_cert_key(int idx, char *certfilename, char *privkeyfilename) { EVP_PKEY_CTX *evpctx = EVP_PKEY_CTX_new_from_name(libctx, (idx == 0) ? "xorhmacsig" : "xorhmacsha2sig", NULL); EVP_PKEY *pkey = NULL; X509 *x509 = X509_new(); X509_NAME *name = NULL; BIO *keybio = NULL, *certbio = NULL; int ret = 1; if (!TEST_ptr(evpctx) || !TEST_int_gt(EVP_PKEY_keygen_init(evpctx), 0) || !TEST_true(EVP_PKEY_generate(evpctx, &pkey)) || !TEST_ptr(pkey) || !TEST_ptr(x509) || !TEST_true(ASN1_INTEGER_set(X509_get_serialNumber(x509), 1)) || !TEST_true(X509_gmtime_adj(X509_getm_notBefore(x509), 0)) || !TEST_true(X509_gmtime_adj(X509_getm_notAfter(x509), 31536000L)) || !TEST_true(X509_set_pubkey(x509, pkey)) || !TEST_ptr(name = X509_get_subject_name(x509)) || !TEST_true(X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (unsigned char *)"CH", -1, -1, 0)) || !TEST_true(X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, (unsigned char *)"test.org", -1, -1, 0)) || !TEST_true(X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned char *)"localhost", -1, -1, 0)) || !TEST_true(X509_set_issuer_name(x509, name)) || !TEST_true(X509_sign(x509, pkey, EVP_sha1())) || !TEST_ptr(keybio = BIO_new_file(privkeyfilename, "wb")) || !TEST_true(PEM_write_bio_PrivateKey(keybio, pkey, NULL, NULL, 0, NULL, NULL)) || !TEST_ptr(certbio = BIO_new_file(certfilename, "wb")) || !TEST_true(PEM_write_bio_X509(certbio, x509))) ret = 0; EVP_PKEY_free(pkey); X509_free(x509); EVP_PKEY_CTX_free(evpctx); BIO_free(keybio); BIO_free(certbio); return ret; } /* * Test that signature algorithms loaded via the provider interface can * correctly establish a TLS (1.3) connection. * Test 0: Signature algorithm with built-in hashing functionality: "xorhmacsig" * Test 1: Signature algorithm using external SHA2 hashing: "xorhmacsha2sig" * Test 2: Signature algorithm with built-in hashing configured via SSL_CONF_cmd * Test 3: Test 0 using RPK * Test 4: Test 1 using RPK * Test 5: Test 2 using RPK */ static int test_pluggable_signature(int idx) { static const unsigned char cert_type_rpk[] = { TLSEXT_cert_type_rpk, TLSEXT_cert_type_x509 }; SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; OSSL_PROVIDER *tlsprov = OSSL_PROVIDER_load(libctx, "tls-provider"); OSSL_PROVIDER *defaultprov = OSSL_PROVIDER_load(libctx, "default"); char *certfilename = "tls-prov-cert.pem"; char *privkeyfilename = "tls-prov-key.pem"; const char *sigalg_name = NULL, *expected_sigalg_name; int sigidx = idx % 3; int rpkidx = idx / 3; int do_conf_cmd = 0; if (sigidx == 2) { sigidx = 0; do_conf_cmd = 1; } /* See create_cert_key() above */ expected_sigalg_name = (sigidx == 0) ? "xorhmacsig" : "xorhmacsha2sig"; /* create key and certificate for the different algorithm types */ if (!TEST_ptr(tlsprov) || !TEST_true(create_cert_key(sigidx, certfilename, privkeyfilename))) goto end; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_3_VERSION, TLS1_3_VERSION, &sctx, &cctx, NULL, NULL))) goto end; if (do_conf_cmd) { SSL_CONF_CTX *confctx = SSL_CONF_CTX_new(); if (!TEST_ptr(confctx)) goto end; SSL_CONF_CTX_set_flags(confctx, SSL_CONF_FLAG_FILE | SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CERTIFICATE | SSL_CONF_FLAG_REQUIRE_PRIVATE | SSL_CONF_FLAG_SHOW_ERRORS); SSL_CONF_CTX_set_ssl_ctx(confctx, sctx); if (!TEST_int_gt(SSL_CONF_cmd(confctx, "Certificate", certfilename), 0) || !TEST_int_gt(SSL_CONF_cmd(confctx, "PrivateKey", privkeyfilename), 0) || !TEST_true(SSL_CONF_CTX_finish(confctx))) { SSL_CONF_CTX_free(confctx); goto end; } SSL_CONF_CTX_free(confctx); } else { if (!TEST_int_eq(SSL_CTX_use_certificate_file(sctx, certfilename, SSL_FILETYPE_PEM), 1) || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(sctx, privkeyfilename, SSL_FILETYPE_PEM), 1)) goto end; } if (!TEST_int_eq(SSL_CTX_check_private_key(sctx), 1)) goto end; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; /* Enable RPK for server cert */ if (rpkidx) { if (!TEST_true(SSL_set1_server_cert_type(serverssl, cert_type_rpk, sizeof(cert_type_rpk))) || !TEST_true(SSL_set1_server_cert_type(clientssl, cert_type_rpk, sizeof(cert_type_rpk)))) goto end; } /* This is necessary to pass minimal setup w/o other groups configured */ if (!TEST_true(SSL_set1_groups_list(serverssl, "xorgroup")) || !TEST_true(SSL_set1_groups_list(clientssl, "xorgroup"))) goto end; /* * If this connection gets established, it must have been completed * via the tls-provider-implemented "hmacsig" algorithm, testing * both sign and verify functions during handshake. */ if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; /* If using RPK, make sure we got one */ if (rpkidx && !TEST_long_eq(SSL_get_verify_result(clientssl), X509_V_ERR_RPK_UNTRUSTED)) goto end; if (!TEST_true(SSL_get0_peer_signature_name(clientssl, &sigalg_name)) || !TEST_str_eq(sigalg_name, expected_sigalg_name) || !TEST_ptr(sigalg_name)) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); OSSL_PROVIDER_unload(tlsprov); OSSL_PROVIDER_unload(defaultprov); return testresult; } #endif #ifndef OPENSSL_NO_TLS1_2 static int test_ssl_dup(void) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL, *client2ssl = NULL; int testresult = 0; BIO *rbio = NULL, *wbio = NULL; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), 0, 0, &sctx, &cctx, cert, privkey))) goto end; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (!TEST_true(SSL_set_min_proto_version(clientssl, TLS1_2_VERSION)) || !TEST_true(SSL_set_max_proto_version(clientssl, TLS1_2_VERSION))) goto end; client2ssl = SSL_dup(clientssl); rbio = SSL_get_rbio(clientssl); if (!TEST_ptr(rbio) || !TEST_true(BIO_up_ref(rbio))) goto end; SSL_set0_rbio(client2ssl, rbio); rbio = NULL; wbio = SSL_get_wbio(clientssl); if (!TEST_ptr(wbio) || !TEST_true(BIO_up_ref(wbio))) goto end; SSL_set0_wbio(client2ssl, wbio); rbio = NULL; if (!TEST_ptr(client2ssl) /* Handshake not started so pointers should be different */ || !TEST_ptr_ne(clientssl, client2ssl)) goto end; if (!TEST_int_eq(SSL_get_min_proto_version(client2ssl), TLS1_2_VERSION) || !TEST_int_eq(SSL_get_max_proto_version(client2ssl), TLS1_2_VERSION)) goto end; if (!TEST_true(create_ssl_connection(serverssl, client2ssl, SSL_ERROR_NONE))) goto end; SSL_free(clientssl); clientssl = SSL_dup(client2ssl); if (!TEST_ptr(clientssl) /* Handshake has finished so pointers should be the same */ || !TEST_ptr_eq(clientssl, client2ssl)) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_free(client2ssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } static int secret_cb(SSL *s, void *secretin, int *secret_len, STACK_OF(SSL_CIPHER) *peer_ciphers, const SSL_CIPHER **cipher, void *arg) { int i; unsigned char *secret = secretin; /* Just use a fixed master secret */ for (i = 0; i < *secret_len; i++) secret[i] = 0xff; /* We don't set a preferred cipher */ return 1; } /* * Test the session_secret_cb which is designed for use with EAP-FAST */ static int test_session_secret_cb(void) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; SSL_SESSION *secret_sess = NULL; int testresult = 0; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), 0, 0, &sctx, &cctx, cert, privkey))) goto end; /* Create an initial connection and save the session */ if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; /* session_secret_cb does not support TLSv1.3 */ if (!TEST_true(SSL_set_min_proto_version(clientssl, TLS1_2_VERSION)) || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; if (!TEST_ptr(secret_sess = SSL_get1_session(clientssl))) goto end; shutdown_ssl_connection(serverssl, clientssl); serverssl = clientssl = NULL; /* Resume the earlier session */ if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; /* * No session ids for EAP-FAST - otherwise the state machine gets very * confused. */ if (!TEST_true(SSL_SESSION_set1_id(secret_sess, NULL, 0))) goto end; if (!TEST_true(SSL_set_min_proto_version(clientssl, TLS1_2_VERSION)) || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION)) || !TEST_true(SSL_set_session_secret_cb(serverssl, secret_cb, NULL)) || !TEST_true(SSL_set_session_secret_cb(clientssl, secret_cb, NULL)) || !TEST_true(SSL_set_session(clientssl, secret_sess))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; testresult = 1; end: SSL_SESSION_free(secret_sess); SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } # ifndef OPENSSL_NO_DH static EVP_PKEY *tmp_dh_params = NULL; /* Helper function for the test_set_tmp_dh() tests */ static EVP_PKEY *get_tmp_dh_params(void) { if (tmp_dh_params == NULL) { BIGNUM *p = NULL; OSSL_PARAM_BLD *tmpl = NULL; EVP_PKEY_CTX *pctx = NULL; OSSL_PARAM *params = NULL; EVP_PKEY *dhpkey = NULL; p = BN_get_rfc3526_prime_2048(NULL); if (!TEST_ptr(p)) goto end; pctx = EVP_PKEY_CTX_new_from_name(libctx, "DH", NULL); if (!TEST_ptr(pctx) || !TEST_int_eq(EVP_PKEY_fromdata_init(pctx), 1)) goto end; tmpl = OSSL_PARAM_BLD_new(); if (!TEST_ptr(tmpl) || !TEST_true(OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p)) || !TEST_true(OSSL_PARAM_BLD_push_uint(tmpl, OSSL_PKEY_PARAM_FFC_G, 2))) goto end; params = OSSL_PARAM_BLD_to_param(tmpl); if (!TEST_ptr(params) || !TEST_int_eq(EVP_PKEY_fromdata(pctx, &dhpkey, EVP_PKEY_KEY_PARAMETERS, params), 1)) goto end; tmp_dh_params = dhpkey; end: BN_free(p); EVP_PKEY_CTX_free(pctx); OSSL_PARAM_BLD_free(tmpl); OSSL_PARAM_free(params); } if (tmp_dh_params != NULL && !EVP_PKEY_up_ref(tmp_dh_params)) return NULL; return tmp_dh_params; } # ifndef OPENSSL_NO_DEPRECATED_3_0 /* Callback used by test_set_tmp_dh() */ static DH *tmp_dh_callback(SSL *s, int is_export, int keylen) { EVP_PKEY *dhpkey = get_tmp_dh_params(); DH *ret = NULL; if (!TEST_ptr(dhpkey)) return NULL; /* * libssl does not free the returned DH, so we free it now knowing that even * after we free dhpkey, there will still be a reference to the owning * EVP_PKEY in tmp_dh_params, and so the DH object will live for the length * of time we need it for. */ ret = EVP_PKEY_get1_DH(dhpkey); DH_free(ret); EVP_PKEY_free(dhpkey); return ret; } # endif /* * Test the various methods for setting temporary DH parameters * * Test 0: Default (no auto) setting * Test 1: Explicit SSL_CTX auto off * Test 2: Explicit SSL auto off * Test 3: Explicit SSL_CTX auto on * Test 4: Explicit SSL auto on * Test 5: Explicit SSL_CTX auto off, custom DH params via EVP_PKEY * Test 6: Explicit SSL auto off, custom DH params via EVP_PKEY * * The following are testing deprecated APIs, so we only run them if available * Test 7: Explicit SSL_CTX auto off, custom DH params via DH * Test 8: Explicit SSL auto off, custom DH params via DH * Test 9: Explicit SSL_CTX auto off, custom DH params via callback * Test 10: Explicit SSL auto off, custom DH params via callback */ static int test_set_tmp_dh(int idx) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; int dhauto = (idx == 3 || idx == 4) ? 1 : 0; int expected = (idx <= 2) ? 0 : 1; EVP_PKEY *dhpkey = NULL; # ifndef OPENSSL_NO_DEPRECATED_3_0 DH *dh = NULL; # else if (idx >= 7) return 1; # endif if (idx >= 5 && idx <= 8) { dhpkey = get_tmp_dh_params(); if (!TEST_ptr(dhpkey)) goto end; } # ifndef OPENSSL_NO_DEPRECATED_3_0 if (idx == 7 || idx == 8) { dh = EVP_PKEY_get1_DH(dhpkey); if (!TEST_ptr(dh)) goto end; } # endif if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), 0, 0, &sctx, &cctx, cert, privkey))) goto end; if ((idx & 1) == 1) { if (!TEST_true(SSL_CTX_set_dh_auto(sctx, dhauto))) goto end; } if (idx == 5) { if (!TEST_true(SSL_CTX_set0_tmp_dh_pkey(sctx, dhpkey))) goto end; dhpkey = NULL; } # ifndef OPENSSL_NO_DEPRECATED_3_0 else if (idx == 7) { if (!TEST_true(SSL_CTX_set_tmp_dh(sctx, dh))) goto end; } else if (idx == 9) { SSL_CTX_set_tmp_dh_callback(sctx, tmp_dh_callback); } # endif if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if ((idx & 1) == 0 && idx != 0) { if (!TEST_true(SSL_set_dh_auto(serverssl, dhauto))) goto end; } if (idx == 6) { if (!TEST_true(SSL_set0_tmp_dh_pkey(serverssl, dhpkey))) goto end; dhpkey = NULL; } # ifndef OPENSSL_NO_DEPRECATED_3_0 else if (idx == 8) { if (!TEST_true(SSL_set_tmp_dh(serverssl, dh))) goto end; } else if (idx == 10) { SSL_set_tmp_dh_callback(serverssl, tmp_dh_callback); } # endif if (!TEST_true(SSL_set_min_proto_version(serverssl, TLS1_2_VERSION)) || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION)) || !TEST_true(SSL_set_cipher_list(serverssl, "DHE-RSA-AES128-SHA"))) goto end; /* * If autoon then we should succeed. Otherwise we expect failure because * there are no parameters */ if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE), expected)) goto end; testresult = 1; end: # ifndef OPENSSL_NO_DEPRECATED_3_0 DH_free(dh); # endif SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); EVP_PKEY_free(dhpkey); return testresult; } /* * Test the auto DH keys are appropriately sized */ static int test_dh_auto(int idx) { SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, TLS_client_method()); SSL_CTX *sctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method()); SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; EVP_PKEY *tmpkey = NULL; char *thiscert = NULL, *thiskey = NULL; size_t expdhsize = 0; const char *ciphersuite = "DHE-RSA-AES128-SHA"; if (!TEST_ptr(sctx) || !TEST_ptr(cctx)) goto end; switch (idx) { case 0: /* The FIPS provider doesn't support this DH size - so we ignore it */ if (is_fips) { testresult = 1; goto end; } thiscert = cert1024; thiskey = privkey1024; expdhsize = 1024; SSL_CTX_set_security_level(sctx, 1); SSL_CTX_set_security_level(cctx, 1); break; case 1: /* 2048 bit prime */ thiscert = cert; thiskey = privkey; expdhsize = 2048; break; case 2: thiscert = cert3072; thiskey = privkey3072; expdhsize = 3072; break; case 3: thiscert = cert4096; thiskey = privkey4096; expdhsize = 4096; break; case 4: thiscert = cert8192; thiskey = privkey8192; expdhsize = 8192; break; /* No certificate cases */ case 5: /* The FIPS provider doesn't support this DH size - so we ignore it */ if (is_fips) { testresult = 1; goto end; } ciphersuite = "ADH-AES128-SHA256:@SECLEVEL=0"; expdhsize = 1024; break; case 6: ciphersuite = "ADH-AES256-SHA256:@SECLEVEL=0"; expdhsize = 3072; break; default: TEST_error("Invalid text index"); goto end; } if (!TEST_true(create_ssl_ctx_pair(libctx, NULL, NULL, 0, 0, &sctx, &cctx, thiscert, thiskey))) goto end; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (!TEST_true(SSL_set_dh_auto(serverssl, 1)) || !TEST_true(SSL_set_min_proto_version(serverssl, TLS1_2_VERSION)) || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION)) || !TEST_true(SSL_set_cipher_list(serverssl, ciphersuite)) || !TEST_true(SSL_set_cipher_list(clientssl, ciphersuite))) goto end; /* * Send the server's first flight. At this point the server has created the * temporary DH key but hasn't finished using it yet. Once used it is * removed, so we cannot test it. */ if (!TEST_int_le(SSL_connect(clientssl), 0) || !TEST_int_le(SSL_accept(serverssl), 0)) goto end; if (!TEST_int_gt(SSL_get_tmp_key(serverssl, &tmpkey), 0)) goto end; if (!TEST_size_t_eq(EVP_PKEY_get_bits(tmpkey), expdhsize)) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); EVP_PKEY_free(tmpkey); return testresult; } # endif /* OPENSSL_NO_DH */ #endif /* OPENSSL_NO_TLS1_2 */ #ifndef OSSL_NO_USABLE_TLS1_3 /* * Test that setting an SNI callback works with TLSv1.3. Specifically we check * that it works even without a certificate configured for the original * SSL_CTX */ static int test_sni_tls13(void) { SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; /* Reset callback counter */ snicb = 0; /* Create an initial SSL_CTX with no certificate configured */ sctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method()); if (!TEST_ptr(sctx)) goto end; /* Require TLSv1.3 as a minimum */ if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_3_VERSION, 0, &sctx2, &cctx, cert, privkey))) goto end; /* Set up SNI */ if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb)) || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2))) goto end; /* * Connection should still succeed because the final SSL_CTX has the right * certificates configured. */ if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; /* We should have had the SNI callback called exactly once */ if (!TEST_int_eq(snicb, 1)) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx2); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } /* * Test that the lifetime hint of a TLSv1.3 ticket is no more than 1 week * 0 = TLSv1.2 * 1 = TLSv1.3 */ static int test_ticket_lifetime(int idx) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; int version = TLS1_3_VERSION; #define ONE_WEEK_SEC (7 * 24 * 60 * 60) #define TWO_WEEK_SEC (2 * ONE_WEEK_SEC) if (idx == 0) { #ifdef OPENSSL_NO_TLS1_2 return TEST_skip("TLS 1.2 is disabled."); #else version = TLS1_2_VERSION; #endif } if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), version, version, &sctx, &cctx, cert, privkey))) goto end; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; /* * Set the timeout to be more than 1 week * make sure the returned value is the default */ if (!TEST_long_eq(SSL_CTX_set_timeout(sctx, TWO_WEEK_SEC), SSL_get_default_timeout(serverssl))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; if (idx == 0) { /* TLSv1.2 uses the set value */ if (!TEST_ulong_eq(SSL_SESSION_get_ticket_lifetime_hint(SSL_get_session(clientssl)), TWO_WEEK_SEC)) goto end; } else { /* TLSv1.3 uses the limited value */ if (!TEST_ulong_le(SSL_SESSION_get_ticket_lifetime_hint(SSL_get_session(clientssl)), ONE_WEEK_SEC)) goto end; } testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #endif /* * Test that setting an ALPN does not violate RFC */ static int test_set_alpn(void) { SSL_CTX *ctx = NULL; SSL *ssl = NULL; int testresult = 0; unsigned char bad0[] = { 0x00, 'b', 'a', 'd' }; unsigned char good[] = { 0x04, 'g', 'o', 'o', 'd' }; unsigned char bad1[] = { 0x01, 'b', 'a', 'd' }; unsigned char bad2[] = { 0x03, 'b', 'a', 'd', 0x00}; unsigned char bad3[] = { 0x03, 'b', 'a', 'd', 0x01, 'b', 'a', 'd'}; unsigned char bad4[] = { 0x03, 'b', 'a', 'd', 0x06, 'b', 'a', 'd'}; /* Create an initial SSL_CTX with no certificate configured */ ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method()); if (!TEST_ptr(ctx)) goto end; /* the set_alpn functions return 0 (false) on success, non-zero (true) on failure */ if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, NULL, 2))) goto end; if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, good, 0))) goto end; if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, good, sizeof(good)))) goto end; if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, good, 1))) goto end; if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad0, sizeof(bad0)))) goto end; if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad1, sizeof(bad1)))) goto end; if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad2, sizeof(bad2)))) goto end; if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad3, sizeof(bad3)))) goto end; if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad4, sizeof(bad4)))) goto end; ssl = SSL_new(ctx); if (!TEST_ptr(ssl)) goto end; if (!TEST_false(SSL_set_alpn_protos(ssl, NULL, 2))) goto end; if (!TEST_false(SSL_set_alpn_protos(ssl, good, 0))) goto end; if (!TEST_false(SSL_set_alpn_protos(ssl, good, sizeof(good)))) goto end; if (!TEST_true(SSL_set_alpn_protos(ssl, good, 1))) goto end; if (!TEST_true(SSL_set_alpn_protos(ssl, bad0, sizeof(bad0)))) goto end; if (!TEST_true(SSL_set_alpn_protos(ssl, bad1, sizeof(bad1)))) goto end; if (!TEST_true(SSL_set_alpn_protos(ssl, bad2, sizeof(bad2)))) goto end; if (!TEST_true(SSL_set_alpn_protos(ssl, bad3, sizeof(bad3)))) goto end; if (!TEST_true(SSL_set_alpn_protos(ssl, bad4, sizeof(bad4)))) goto end; testresult = 1; end: SSL_free(ssl); SSL_CTX_free(ctx); return testresult; } /* * Test SSL_CTX_set1_verify/chain_cert_store and SSL_CTX_get_verify/chain_cert_store. */ static int test_set_verify_cert_store_ssl_ctx(void) { SSL_CTX *ctx = NULL; int testresult = 0; X509_STORE *store = NULL, *new_store = NULL, *cstore = NULL, *new_cstore = NULL; /* Create an initial SSL_CTX. */ ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method()); if (!TEST_ptr(ctx)) goto end; /* Retrieve verify store pointer. */ if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store))) goto end; /* Retrieve chain store pointer. */ if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore))) goto end; /* We haven't set any yet, so this should be NULL. */ if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore)) goto end; /* Create stores. We use separate stores so pointers are different. */ new_store = X509_STORE_new(); if (!TEST_ptr(new_store)) goto end; new_cstore = X509_STORE_new(); if (!TEST_ptr(new_cstore)) goto end; /* Set stores. */ if (!TEST_true(SSL_CTX_set1_verify_cert_store(ctx, new_store))) goto end; if (!TEST_true(SSL_CTX_set1_chain_cert_store(ctx, new_cstore))) goto end; /* Should be able to retrieve the same pointer. */ if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store))) goto end; if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore))) goto end; if (!TEST_ptr_eq(store, new_store) || !TEST_ptr_eq(cstore, new_cstore)) goto end; /* Should be able to unset again. */ if (!TEST_true(SSL_CTX_set1_verify_cert_store(ctx, NULL))) goto end; if (!TEST_true(SSL_CTX_set1_chain_cert_store(ctx, NULL))) goto end; /* Should now be NULL. */ if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store))) goto end; if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore))) goto end; if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore)) goto end; testresult = 1; end: X509_STORE_free(new_store); X509_STORE_free(new_cstore); SSL_CTX_free(ctx); return testresult; } /* * Test SSL_set1_verify/chain_cert_store and SSL_get_verify/chain_cert_store. */ static int test_set_verify_cert_store_ssl(void) { SSL_CTX *ctx = NULL; SSL *ssl = NULL; int testresult = 0; X509_STORE *store = NULL, *new_store = NULL, *cstore = NULL, *new_cstore = NULL; /* Create an initial SSL_CTX. */ ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method()); if (!TEST_ptr(ctx)) goto end; /* Create an SSL object. */ ssl = SSL_new(ctx); if (!TEST_ptr(ssl)) goto end; /* Retrieve verify store pointer. */ if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store))) goto end; /* Retrieve chain store pointer. */ if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore))) goto end; /* We haven't set any yet, so this should be NULL. */ if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore)) goto end; /* Create stores. We use separate stores so pointers are different. */ new_store = X509_STORE_new(); if (!TEST_ptr(new_store)) goto end; new_cstore = X509_STORE_new(); if (!TEST_ptr(new_cstore)) goto end; /* Set stores. */ if (!TEST_true(SSL_set1_verify_cert_store(ssl, new_store))) goto end; if (!TEST_true(SSL_set1_chain_cert_store(ssl, new_cstore))) goto end; /* Should be able to retrieve the same pointer. */ if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store))) goto end; if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore))) goto end; if (!TEST_ptr_eq(store, new_store) || !TEST_ptr_eq(cstore, new_cstore)) goto end; /* Should be able to unset again. */ if (!TEST_true(SSL_set1_verify_cert_store(ssl, NULL))) goto end; if (!TEST_true(SSL_set1_chain_cert_store(ssl, NULL))) goto end; /* Should now be NULL. */ if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store))) goto end; if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore))) goto end; if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore)) goto end; testresult = 1; end: X509_STORE_free(new_store); X509_STORE_free(new_cstore); SSL_free(ssl); SSL_CTX_free(ctx); return testresult; } static int test_inherit_verify_param(void) { int testresult = 0; SSL_CTX *ctx = NULL; X509_VERIFY_PARAM *cp = NULL; SSL *ssl = NULL; X509_VERIFY_PARAM *sp = NULL; int hostflags = X509_CHECK_FLAG_NEVER_CHECK_SUBJECT; ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method()); if (!TEST_ptr(ctx)) goto end; cp = SSL_CTX_get0_param(ctx); if (!TEST_ptr(cp)) goto end; if (!TEST_int_eq(X509_VERIFY_PARAM_get_hostflags(cp), 0)) goto end; X509_VERIFY_PARAM_set_hostflags(cp, hostflags); ssl = SSL_new(ctx); if (!TEST_ptr(ssl)) goto end; sp = SSL_get0_param(ssl); if (!TEST_ptr(sp)) goto end; if (!TEST_int_eq(X509_VERIFY_PARAM_get_hostflags(sp), hostflags)) goto end; testresult = 1; end: SSL_free(ssl); SSL_CTX_free(ctx); return testresult; } static int test_load_dhfile(void) { #ifndef OPENSSL_NO_DH int testresult = 0; SSL_CTX *ctx = NULL; SSL_CONF_CTX *cctx = NULL; if (dhfile == NULL) return 1; if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_client_method())) || !TEST_ptr(cctx = SSL_CONF_CTX_new())) goto end; SSL_CONF_CTX_set_ssl_ctx(cctx, ctx); SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CERTIFICATE | SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_FILE); if (!TEST_int_eq(SSL_CONF_cmd(cctx, "DHParameters", dhfile), 2)) goto end; testresult = 1; end: SSL_CONF_CTX_free(cctx); SSL_CTX_free(ctx); return testresult; #else return TEST_skip("DH not supported by this build"); #endif } #ifndef OSSL_NO_USABLE_TLS1_3 /* Test that read_ahead works across a key change */ static int test_read_ahead_key_change(void) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; char *msg = "Hello World"; size_t written, readbytes; char buf[80]; int i; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_3_VERSION, 0, &sctx, &cctx, cert, privkey))) goto end; SSL_CTX_set_read_ahead(sctx, 1); if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; /* Write some data, send a key update, write more data */ if (!TEST_true(SSL_write_ex(clientssl, msg, strlen(msg), &written)) || !TEST_size_t_eq(written, strlen(msg))) goto end; if (!TEST_true(SSL_key_update(clientssl, SSL_KEY_UPDATE_NOT_REQUESTED))) goto end; if (!TEST_true(SSL_write_ex(clientssl, msg, strlen(msg), &written)) || !TEST_size_t_eq(written, strlen(msg))) goto end; /* * Since read_ahead is on the first read below should read the record with * the first app data, the second record with the key update message, and * the third record with the app data all in one go. We should be able to * still process the read_ahead data correctly even though it crosses * epochs */ for (i = 0; i < 2; i++) { if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf) - 1, &readbytes))) goto end; buf[readbytes] = '\0'; if (!TEST_str_eq(buf, msg)) goto end; } testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } static size_t record_pad_cb(SSL *s, int type, size_t len, void *arg) { int *called = arg; switch ((*called)++) { case 0: /* Add some padding to first record */ return 512; case 1: /* Maximally pad the second record */ return SSL3_RT_MAX_PLAIN_LENGTH - len; case 2: /* * Exceeding the maximum padding should be fine. It should just pad to * the maximum anyway */ return SSL3_RT_MAX_PLAIN_LENGTH + 1 - len; case 3: /* * Very large padding should also be ok. Should just pad to the maximum * allowed */ return SIZE_MAX; default: return 0; } } /* * Test that setting record padding in TLSv1.3 works as expected * Test 0: Record padding callback on the SSL_CTX * Test 1: Record padding callback on the SSL * Test 2: Record block padding on the SSL_CTX * Test 3: Record block padding on the SSL * Test 4: Extended record block padding on the SSL_CTX * Test 5: Extended record block padding on the SSL */ static int test_tls13_record_padding(int idx) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; char *msg = "Hello World"; size_t written, readbytes; char buf[80]; int i; int called = 0; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_3_VERSION, 0, &sctx, &cctx, cert, privkey))) goto end; if (idx == 0) { SSL_CTX_set_record_padding_callback(cctx, record_pad_cb); SSL_CTX_set_record_padding_callback_arg(cctx, &called); if (!TEST_ptr_eq(SSL_CTX_get_record_padding_callback_arg(cctx), &called)) goto end; } else if (idx == 2) { /* Exceeding the max plain length should fail */ if (!TEST_false(SSL_CTX_set_block_padding(cctx, SSL3_RT_MAX_PLAIN_LENGTH + 1))) goto end; if (!TEST_true(SSL_CTX_set_block_padding(cctx, 512))) goto end; } else if (idx == 4) { /* pad only handshake/alert messages */ if (!TEST_true(SSL_CTX_set_block_padding_ex(cctx, 0, 512))) goto end; } if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (idx == 1) { SSL_set_record_padding_callback(clientssl, record_pad_cb); SSL_set_record_padding_callback_arg(clientssl, &called); if (!TEST_ptr_eq(SSL_get_record_padding_callback_arg(clientssl), &called)) goto end; } else if (idx == 3) { /* Exceeding the max plain length should fail */ if (!TEST_false(SSL_set_block_padding(clientssl, SSL3_RT_MAX_PLAIN_LENGTH + 1))) goto end; if (!TEST_true(SSL_set_block_padding(clientssl, 512))) goto end; } else if (idx == 5) { /* Exceeding the max plain length should fail */ if (!TEST_false(SSL_set_block_padding_ex(clientssl, 0, SSL3_RT_MAX_PLAIN_LENGTH + 1))) goto end; /* pad server and client handshake only */ if (!TEST_true(SSL_set_block_padding_ex(clientssl, 0, 512))) goto end; if (!TEST_true(SSL_set_block_padding_ex(serverssl, 0, 512))) goto end; } if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; called = 0; /* * Write some data, then check we can read it. Do this four times to check * we can continue to write and read padded data after the initial record * padding has been added. We don't actually check that the padding has * been applied to the record - just that we can continue to communicate * normally and that the callback has been called (if appropriate). */ for (i = 0; i < 4; i++) { if (!TEST_true(SSL_write_ex(clientssl, msg, strlen(msg), &written)) || !TEST_size_t_eq(written, strlen(msg))) goto end; if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf) - 1, &readbytes)) || !TEST_size_t_eq(written, readbytes)) goto end; buf[readbytes] = '\0'; if (!TEST_str_eq(buf, msg)) goto end; } if ((idx == 0 || idx == 1) && !TEST_int_eq(called, 4)) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #endif /* OSSL_NO_USABLE_TLS1_3 */ #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE) /* * Test TLSv1.2 with a pipeline capable cipher. TLSv1.3 and DTLS do not * support this yet. The only pipeline capable cipher that we have is in the * dasync engine (providers don't support this yet), so we have to use * deprecated APIs for this test. * * Test 0: Client has pipelining enabled, server does not * Test 1: Server has pipelining enabled, client does not * Test 2: Client has pipelining enabled, server does not: not enough data to * fill all the pipelines * Test 3: Client has pipelining enabled, server does not: not enough data to * fill all the pipelines by more than a full pipeline's worth * Test 4: Client has pipelining enabled, server does not: more data than all * the available pipelines can take * Test 5: Client has pipelining enabled, server does not: Maximum size pipeline * Test 6: Repeat of test 0, but the engine is loaded late (after the SSL_CTX * is created) */ static int test_pipelining(int idx) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL, *peera, *peerb; int testresult = 0, numreads; /* A 55 byte message */ unsigned char *msg = (unsigned char *) "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123"; size_t written, readbytes, offset, msglen, fragsize = 10, numpipes = 5; size_t expectedreads; unsigned char *buf = NULL; ENGINE *e = NULL; if (idx != 6) { e = load_dasync(); if (e == NULL) return 0; } if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), 0, TLS1_2_VERSION, &sctx, &cctx, cert, privkey))) goto end; if (idx == 6) { e = load_dasync(); if (e == NULL) goto end; /* Now act like test 0 */ idx = 0; } if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (!TEST_true(SSL_set_cipher_list(clientssl, "AES128-SHA"))) goto end; /* peera is always configured for pipelining, while peerb is not. */ if (idx == 1) { peera = serverssl; peerb = clientssl; } else { peera = clientssl; peerb = serverssl; } if (idx == 5) { numpipes = 2; /* Maximum allowed fragment size */ fragsize = SSL3_RT_MAX_PLAIN_LENGTH; msglen = fragsize * numpipes; msg = OPENSSL_malloc(msglen); if (!TEST_ptr(msg)) goto end; if (!TEST_int_gt(RAND_bytes_ex(libctx, msg, msglen, 0), 0)) goto end; } else if (idx == 4) { msglen = 55; } else { msglen = 50; } if (idx == 2) msglen -= 2; /* Send 2 less bytes */ else if (idx == 3) msglen -= 12; /* Send 12 less bytes */ buf = OPENSSL_malloc(msglen); if (!TEST_ptr(buf)) goto end; if (idx == 5) { /* * Test that setting a split send fragment longer than the maximum * allowed fails */ if (!TEST_false(SSL_set_split_send_fragment(peera, fragsize + 1))) goto end; } /* * In the normal case. We have 5 pipelines with 10 bytes per pipeline * (50 bytes in total). This is a ridiculously small number of bytes - * but sufficient for our purposes */ if (!TEST_true(SSL_set_max_pipelines(peera, numpipes)) || !TEST_true(SSL_set_split_send_fragment(peera, fragsize))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; /* Write some data from peera to peerb */ if (!TEST_true(SSL_write_ex(peera, msg, msglen, &written)) || !TEST_size_t_eq(written, msglen)) goto end; /* * If the pipelining code worked, then we expect all |numpipes| pipelines to * have been used - except in test 3 where only |numpipes - 1| pipelines * will be used. This will result in |numpipes| records (|numpipes - 1| for * test 3) having been sent to peerb. Since peerb is not using read_ahead we * expect this to be read in |numpipes| or |numpipes - 1| separate * SSL_read_ex calls. In the case of test 4, there is then one additional * read for left over data that couldn't fit in the previous pipelines */ for (offset = 0, numreads = 0; offset < msglen; offset += readbytes, numreads++) { if (!TEST_true(SSL_read_ex(peerb, buf + offset, msglen - offset, &readbytes))) goto end; } expectedreads = idx == 4 ? numpipes + 1 : (idx == 3 ? numpipes - 1 : numpipes); if (!TEST_mem_eq(msg, msglen, buf, offset) || !TEST_int_eq(numreads, expectedreads)) goto end; /* * Write some data from peerb to peera. We do this in up to |numpipes + 1| * chunks to exercise the read pipelining code on peera. */ for (offset = 0; offset < msglen; offset += fragsize) { size_t sendlen = msglen - offset; if (sendlen > fragsize) sendlen = fragsize; if (!TEST_true(SSL_write_ex(peerb, msg + offset, sendlen, &written)) || !TEST_size_t_eq(written, sendlen)) goto end; } /* * The data was written in |numpipes|, |numpipes - 1| or |numpipes + 1| * separate chunks (depending on which test we are running). If the * pipelining is working then we expect peera to read up to numpipes chunks * and process them in parallel, giving back the complete result in a single * call to SSL_read_ex */ if (!TEST_true(SSL_read_ex(peera, buf, msglen, &readbytes)) || !TEST_size_t_le(readbytes, msglen)) goto end; if (idx == 4) { size_t readbytes2; if (!TEST_true(SSL_read_ex(peera, buf + readbytes, msglen - readbytes, &readbytes2))) goto end; readbytes += readbytes2; if (!TEST_size_t_le(readbytes, msglen)) goto end; } if (!TEST_mem_eq(msg, msglen, buf, readbytes)) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); if (e != NULL) { ENGINE_unregister_ciphers(e); ENGINE_finish(e); ENGINE_free(e); } OPENSSL_free(buf); if (fragsize == SSL3_RT_MAX_PLAIN_LENGTH) OPENSSL_free(msg); return testresult; } #endif /* !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE) */ static int check_version_string(SSL *s, int version) { const char *verstr = NULL; switch (version) { case SSL3_VERSION: verstr = "SSLv3"; break; case TLS1_VERSION: verstr = "TLSv1"; break; case TLS1_1_VERSION: verstr = "TLSv1.1"; break; case TLS1_2_VERSION: verstr = "TLSv1.2"; break; case TLS1_3_VERSION: verstr = "TLSv1.3"; break; case DTLS1_VERSION: verstr = "DTLSv1"; break; case DTLS1_2_VERSION: verstr = "DTLSv1.2"; } return TEST_str_eq(verstr, SSL_get_version(s)); } /* * Test that SSL_version, SSL_get_version, SSL_is_quic, SSL_is_tls and * SSL_is_dtls return the expected results for a (D)TLS connection. Compare with * test_version() in quicapitest.c which does the same thing for QUIC * connections. */ static int test_version(int idx) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0, version; const SSL_METHOD *servmeth = TLS_server_method(); const SSL_METHOD *clientmeth = TLS_client_method(); switch (idx) { #if !defined(OPENSSL_NO_SSL3) case 0: version = SSL3_VERSION; break; #endif #if !defined(OPENSSL_NO_TLS1) case 1: version = TLS1_VERSION; break; #endif #if !defined(OPENSSL_NO_TLS1_2) case 2: version = TLS1_2_VERSION; break; #endif #if !defined(OSSL_NO_USABLE_TLS1_3) case 3: version = TLS1_3_VERSION; break; #endif #if !defined(OPENSSL_NO_DTLS1) case 4: version = DTLS1_VERSION; break; #endif #if !defined(OPENSSL_NO_DTLS1_2) case 5: version = DTLS1_2_VERSION; break; #endif /* * NB we do not support QUIC in this test. That is covered by quicapitest.c * We also don't support DTLS1_BAD_VER since we have no server support for * that. */ default: TEST_skip("Unsupported protocol version"); return 1; } if (is_fips && (version == SSL3_VERSION || version == TLS1_VERSION || version == DTLS1_VERSION)) { TEST_skip("Protocol version not supported with FIPS"); return 1; } #if !defined(OPENSSL_NO_DTLS) if (version == DTLS1_VERSION || version == DTLS1_2_VERSION) { servmeth = DTLS_server_method(); clientmeth = DTLS_client_method(); } #endif if (!TEST_true(create_ssl_ctx_pair(libctx, servmeth, clientmeth, version, version, &sctx, &cctx, cert, privkey))) goto end; if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0")) || !TEST_true(SSL_CTX_set_cipher_list(cctx, "DEFAULT:@SECLEVEL=0"))) goto end; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; if (!TEST_int_eq(SSL_version(serverssl), version) || !TEST_int_eq(SSL_version(clientssl), version) || !TEST_true(check_version_string(serverssl, version)) || !TEST_true(check_version_string(clientssl, version))) goto end; if (version == DTLS1_VERSION || version == DTLS1_2_VERSION) { if (!TEST_true(SSL_is_dtls(serverssl)) || !TEST_true(SSL_is_dtls(clientssl)) || !TEST_false(SSL_is_tls(serverssl)) || !TEST_false(SSL_is_tls(clientssl)) || !TEST_false(SSL_is_quic(serverssl)) || !TEST_false(SSL_is_quic(clientssl))) goto end; } else { if (!TEST_true(SSL_is_tls(serverssl)) || !TEST_true(SSL_is_tls(clientssl)) || !TEST_false(SSL_is_dtls(serverssl)) || !TEST_false(SSL_is_dtls(clientssl)) || !TEST_false(SSL_is_quic(serverssl)) || !TEST_false(SSL_is_quic(clientssl))) goto end; } testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } /* * Test that the SSL_rstate_string*() APIs return sane results */ static int test_rstate_string(void) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0, version; const SSL_METHOD *servmeth = TLS_server_method(); const SSL_METHOD *clientmeth = TLS_client_method(); size_t written, readbytes; unsigned char buf[2]; unsigned char dummyheader[SSL3_RT_HEADER_LENGTH] = { SSL3_RT_APPLICATION_DATA, TLS1_2_VERSION_MAJOR, 0, /* To be filled in later */ 0, 1 }; if (!TEST_true(create_ssl_ctx_pair(libctx, servmeth, clientmeth, 0, 0, &sctx, &cctx, cert, privkey))) goto end; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (!TEST_str_eq(SSL_rstate_string(serverssl), "RH") || !TEST_str_eq(SSL_rstate_string_long(serverssl), "read header")) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; if (!TEST_str_eq(SSL_rstate_string(serverssl), "RH") || !TEST_str_eq(SSL_rstate_string_long(serverssl), "read header")) goto end; /* Fill in the correct version for the record header */ version = SSL_version(serverssl); if (version == TLS1_3_VERSION) version = TLS1_2_VERSION; dummyheader[2] = version & 0xff; /* * Send a dummy header. If we continued to read the body as well this * would fail with a bad record mac, but we're not going to go that far. */ if (!TEST_true(BIO_write_ex(SSL_get_rbio(serverssl), dummyheader, sizeof(dummyheader), &written)) || !TEST_size_t_eq(written, SSL3_RT_HEADER_LENGTH)) goto end; if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))) goto end; if (!TEST_str_eq(SSL_rstate_string(serverssl), "RB") || !TEST_str_eq(SSL_rstate_string_long(serverssl), "read body")) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } /* * Force a write retry during handshaking. We test various combinations of * scenarios. We test a large certificate message which will fill the buffering * BIO used in the handshake. We try with client auth on and off. Finally we * also try a BIO that indicates retry via a 0 return. BIO_write() is documented * to indicate retry via -1 - but sometimes BIOs don't do that. * * Test 0: Standard certificate message * Test 1: Large certificate message * Test 2: Standard cert, verify peer * Test 3: Large cert, verify peer * Test 4: Standard cert, BIO returns 0 on retry * Test 5: Large cert, BIO returns 0 on retry * Test 6: Standard cert, verify peer, BIO returns 0 on retry * Test 7: Large cert, verify peer, BIO returns 0 on retry * Test 8-15: Repeat of above with TLSv1.2 */ static int test_handshake_retry(int idx) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; BIO *tmp = NULL, *bretry = BIO_new(bio_s_always_retry()); int maxversion = 0; if (!TEST_ptr(bretry)) goto end; #ifndef OPENSSL_NO_TLS1_2 if ((idx & 8) == 8) maxversion = TLS1_2_VERSION; #else if ((idx & 8) == 8) return TEST_skip("No TLSv1.2"); #endif if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), 0, maxversion, &sctx, &cctx, cert, privkey))) goto end; /* * Add a large amount of data to fill the buffering BIO used by the SSL * object */ if ((idx & 1) == 1 && !ssl_ctx_add_large_cert_chain(libctx, sctx, cert)) goto end; /* * We don't actually configure a client cert, but neither do we fail if one * isn't present. */ if ((idx & 2) == 2) SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER, NULL); if ((idx & 4) == 4) set_always_retry_err_val(0); if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; tmp = SSL_get_wbio(serverssl); if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) { tmp = NULL; goto end; } SSL_set0_wbio(serverssl, bretry); bretry = NULL; if (!TEST_int_eq(SSL_connect(clientssl), -1)) goto end; if (!TEST_int_eq(SSL_accept(serverssl), -1) || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_WANT_WRITE)) goto end; /* Restore a BIO that will let the write succeed */ SSL_set0_wbio(serverssl, tmp); tmp = NULL; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); BIO_free(bretry); BIO_free(tmp); set_always_retry_err_val(-1); return testresult; } /* * Test that receiving retries when writing application data works as expected */ static int test_data_retry(void) { SSL_CTX *cctx = NULL, *sctx = NULL; SSL *clientssl = NULL, *serverssl = NULL; int testresult = 0; unsigned char inbuf[1200], outbuf[1200]; size_t i; BIO *tmp = NULL; BIO *bretry = BIO_new(bio_s_maybe_retry()); size_t written, readbytes, totread = 0; if (!TEST_ptr(bretry)) goto end; for (i = 0; i < sizeof(inbuf); i++) inbuf[i] = (unsigned char)(0xff & i); memset(outbuf, 0, sizeof(outbuf)); if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), 0, 0, &sctx, &cctx, cert, privkey))) goto end; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; /* Smallest possible max send fragment is 512 */ if (!TEST_true(SSL_set_max_send_fragment(clientssl, 512))) goto end; tmp = SSL_get_wbio(clientssl); if (!TEST_ptr(tmp)) goto end; if (!TEST_true(BIO_up_ref(tmp))) goto end; BIO_push(bretry, tmp); tmp = NULL; SSL_set0_wbio(clientssl, bretry); if (!BIO_up_ref(bretry)) { bretry = NULL; goto end; } for (i = 0; i < 3; i++) { /* We expect this call to make no progress and indicate retry */ if (!TEST_false(SSL_write_ex(clientssl, inbuf, sizeof(inbuf), &written))) goto end; if (!TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_WANT_WRITE)) goto end; /* Allow one write to progress, but the next one to signal retry */ if (!TEST_true(BIO_ctrl(bretry, MAYBE_RETRY_CTRL_SET_RETRY_AFTER_CNT, 1, NULL))) goto end; if (i == 2) break; /* * This call will hopefully make progress but will still indicate retry * because there is more data than will fit into a single record. */ if (!TEST_false(SSL_write_ex(clientssl, inbuf, sizeof(inbuf), &written))) goto end; if (!TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_WANT_WRITE)) goto end; } /* The final call should write the last chunk of data and succeed */ if (!TEST_true(SSL_write_ex(clientssl, inbuf, sizeof(inbuf), &written))) goto end; /* Read all the data available */ while (SSL_read_ex(serverssl, outbuf + totread, sizeof(outbuf) - totread, &readbytes)) totread += readbytes; if (!TEST_mem_eq(inbuf, sizeof(inbuf), outbuf, totread)) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); BIO_free_all(bretry); BIO_free(tmp); return testresult; } struct resume_servername_cb_data { int i; SSL_CTX *cctx; SSL_CTX *sctx; SSL_SESSION *sess; int recurse; }; /* * Servername callback. We use it here to run another complete handshake using * the same session - and mark the session as not_resuamble at the end */ static int resume_servername_cb(SSL *s, int *ad, void *arg) { struct resume_servername_cb_data *cbdata = arg; SSL *serverssl = NULL, *clientssl = NULL; int ret = SSL_TLSEXT_ERR_ALERT_FATAL; if (cbdata->recurse) return SSL_TLSEXT_ERR_ALERT_FATAL; if ((cbdata->i % 3) != 1) return SSL_TLSEXT_ERR_OK; cbdata->recurse = 1; if (!TEST_true(create_ssl_objects(cbdata->sctx, cbdata->cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(SSL_set_session(clientssl, cbdata->sess))) goto end; ERR_set_mark(); /* * We expect this to fail - because the servername cb will fail. This will * mark the session as not_resumable. */ if (!TEST_false(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) { ERR_clear_last_mark(); goto end; } ERR_pop_to_mark(); ret = SSL_TLSEXT_ERR_OK; end: SSL_free(serverssl); SSL_free(clientssl); cbdata->recurse = 0; return ret; } /* * Test multiple resumptions and cache size handling * Test 0: TLSv1.3 (max_early_data set) * Test 1: TLSv1.3 (SSL_OP_NO_TICKET set) * Test 2: TLSv1.3 (max_early_data and SSL_OP_NO_TICKET set) * Test 3: TLSv1.3 (SSL_OP_NO_TICKET, simultaneous resumes) * Test 4: TLSv1.2 */ static int test_multi_resume(int idx) { SSL_CTX *sctx = NULL, *cctx = NULL; SSL *serverssl = NULL, *clientssl = NULL; SSL_SESSION *sess = NULL; int max_version = TLS1_3_VERSION; int i, testresult = 0; struct resume_servername_cb_data cbdata; #if defined(OPENSSL_NO_TLS1_2) if (idx == 4) return TEST_skip("TLSv1.2 is disabled in this build"); #else if (idx == 4) max_version = TLS1_2_VERSION; #endif #if defined(OSSL_NO_USABLE_TLS1_3) if (idx != 4) return TEST_skip("No usable TLSv1.3 in this build"); #endif if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_VERSION, max_version, &sctx, &cctx, cert, privkey))) goto end; /* * TLSv1.3 only uses a session cache if either max_early_data > 0 (used for * replay protection), or if SSL_OP_NO_TICKET is in use */ if (idx == 0 || idx == 2) { if (!TEST_true(SSL_CTX_set_max_early_data(sctx, 1024))) goto end; } if (idx == 1 || idx == 2 || idx == 3) SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET); SSL_CTX_sess_set_cache_size(sctx, 5); if (idx == 3) { SSL_CTX_set_tlsext_servername_callback(sctx, resume_servername_cb); SSL_CTX_set_tlsext_servername_arg(sctx, &cbdata); cbdata.cctx = cctx; cbdata.sctx = sctx; cbdata.recurse = 0; } for (i = 0; i < 30; i++) { if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(SSL_set_session(clientssl, sess))) goto end; /* * Check simultaneous resumes. We pause the connection part way through * the handshake by (mis)using the servername_cb. The pause occurs after * session resumption has already occurred, but before any session * tickets have been issued. While paused we run another complete * handshake resuming the same session. */ if (idx == 3) { cbdata.i = i; cbdata.sess = sess; } /* * Recreate a bug where dynamically changing the max_early_data value * can cause sessions in the session cache which cannot be deleted. */ if ((idx == 0 || idx == 2) && (i % 3) == 2) SSL_set_max_early_data(serverssl, 0); if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; if (sess == NULL || (idx == 0 && (i % 3) == 2)) { if (!TEST_false(SSL_session_reused(clientssl))) goto end; } else { if (!TEST_true(SSL_session_reused(clientssl))) goto end; } SSL_SESSION_free(sess); /* Do a full handshake, followed by two resumptions */ if ((i % 3) == 2) { sess = NULL; } else { if (!TEST_ptr((sess = SSL_get1_session(clientssl)))) goto end; } SSL_shutdown(clientssl); SSL_shutdown(serverssl); SSL_free(serverssl); SSL_free(clientssl); serverssl = clientssl = NULL; } /* We should never exceed the session cache size limit */ if (!TEST_long_le(SSL_CTX_sess_number(sctx), 5)) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); SSL_SESSION_free(sess); return testresult; } static struct next_proto_st { int serverlen; unsigned char server[40]; int clientlen; unsigned char client[40]; int expected_ret; size_t selectedlen; unsigned char selected[40]; } next_proto_tests[] = { { 4, { 3, 'a', 'b', 'c' }, 4, { 3, 'a', 'b', 'c' }, OPENSSL_NPN_NEGOTIATED, 3, { 'a', 'b', 'c' } }, { 7, { 3, 'a', 'b', 'c', 2, 'a', 'b' }, 4, { 3, 'a', 'b', 'c' }, OPENSSL_NPN_NEGOTIATED, 3, { 'a', 'b', 'c' } }, { 7, { 2, 'a', 'b', 3, 'a', 'b', 'c', }, 4, { 3, 'a', 'b', 'c' }, OPENSSL_NPN_NEGOTIATED, 3, { 'a', 'b', 'c' } }, { 4, { 3, 'a', 'b', 'c' }, 7, { 3, 'a', 'b', 'c', 2, 'a', 'b', }, OPENSSL_NPN_NEGOTIATED, 3, { 'a', 'b', 'c' } }, { 4, { 3, 'a', 'b', 'c' }, 7, { 2, 'a', 'b', 3, 'a', 'b', 'c'}, OPENSSL_NPN_NEGOTIATED, 3, { 'a', 'b', 'c' } }, { 7, { 2, 'b', 'c', 3, 'a', 'b', 'c' }, 7, { 2, 'a', 'b', 3, 'a', 'b', 'c'}, OPENSSL_NPN_NEGOTIATED, 3, { 'a', 'b', 'c' } }, { 10, { 2, 'b', 'c', 3, 'a', 'b', 'c', 2, 'a', 'b' }, 7, { 2, 'a', 'b', 3, 'a', 'b', 'c'}, OPENSSL_NPN_NEGOTIATED, 3, { 'a', 'b', 'c' } }, { 4, { 3, 'b', 'c', 'd' }, 4, { 3, 'a', 'b', 'c' }, OPENSSL_NPN_NO_OVERLAP, 3, { 'a', 'b', 'c' } }, { 0, { 0 }, 4, { 3, 'a', 'b', 'c' }, OPENSSL_NPN_NO_OVERLAP, 3, { 'a', 'b', 'c' } }, { -1, { 0 }, 4, { 3, 'a', 'b', 'c' }, OPENSSL_NPN_NO_OVERLAP, 3, { 'a', 'b', 'c' } }, { 4, { 3, 'a', 'b', 'c' }, 0, { 0 }, OPENSSL_NPN_NO_OVERLAP, 0, { 0 } }, { 4, { 3, 'a', 'b', 'c' }, -1, { 0 }, OPENSSL_NPN_NO_OVERLAP, 0, { 0 } }, { 3, { 3, 'a', 'b', 'c' }, 4, { 3, 'a', 'b', 'c' }, OPENSSL_NPN_NO_OVERLAP, 3, { 'a', 'b', 'c' } }, { 4, { 3, 'a', 'b', 'c' }, 3, { 3, 'a', 'b', 'c' }, OPENSSL_NPN_NO_OVERLAP, 0, { 0 } } }; static int test_select_next_proto(int idx) { struct next_proto_st *np = &next_proto_tests[idx]; int ret = 0; unsigned char *out, *client, *server; unsigned char outlen; unsigned int clientlen, serverlen; if (np->clientlen == -1) { client = NULL; clientlen = 0; } else { client = np->client; clientlen = (unsigned int)np->clientlen; } if (np->serverlen == -1) { server = NULL; serverlen = 0; } else { server = np->server; serverlen = (unsigned int)np->serverlen; } if (!TEST_int_eq(SSL_select_next_proto(&out, &outlen, server, serverlen, client, clientlen), np->expected_ret)) goto err; if (np->selectedlen == 0) { if (!TEST_ptr_null(out) || !TEST_uchar_eq(outlen, 0)) goto err; } else { if (!TEST_mem_eq(out, outlen, np->selected, np->selectedlen)) goto err; } ret = 1; err: return ret; } static const unsigned char fooprot[] = {3, 'f', 'o', 'o' }; static const unsigned char barprot[] = {3, 'b', 'a', 'r' }; #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_NEXTPROTONEG) static int npn_advert_cb(SSL *ssl, const unsigned char **out, unsigned int *outlen, void *arg) { int *idx = (int *)arg; switch (*idx) { default: case 0: *out = fooprot; *outlen = sizeof(fooprot); return SSL_TLSEXT_ERR_OK; case 1: *out = NULL; *outlen = 0; return SSL_TLSEXT_ERR_OK; case 2: return SSL_TLSEXT_ERR_NOACK; } } static int npn_select_cb(SSL *s, unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg) { int *idx = (int *)arg; switch (*idx) { case 0: case 1: *out = (unsigned char *)(fooprot + 1); *outlen = *fooprot; return SSL_TLSEXT_ERR_OK; case 3: *out = (unsigned char *)(barprot + 1); *outlen = *barprot; return SSL_TLSEXT_ERR_OK; case 4: *outlen = 0; return SSL_TLSEXT_ERR_OK; default: case 2: return SSL_TLSEXT_ERR_ALERT_FATAL; } } /* * Test the NPN callbacks * Test 0: advert = foo, select = foo * Test 1: advert = , select = foo * Test 2: no advert * Test 3: advert = foo, select = bar * Test 4: advert = foo, select = (should fail) */ static int test_npn(int idx) { SSL_CTX *sctx = NULL, *cctx = NULL; SSL *serverssl = NULL, *clientssl = NULL; int testresult = 0; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), 0, TLS1_2_VERSION, &sctx, &cctx, cert, privkey))) goto end; SSL_CTX_set_next_protos_advertised_cb(sctx, npn_advert_cb, &idx); SSL_CTX_set_next_proto_select_cb(cctx, npn_select_cb, &idx); if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (idx == 4) { /* We don't allow empty selection of NPN, so this should fail */ if (!TEST_false(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; } else { const unsigned char *prot; unsigned int protlen; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; SSL_get0_next_proto_negotiated(serverssl, &prot, &protlen); switch (idx) { case 0: case 1: if (!TEST_mem_eq(prot, protlen, fooprot + 1, *fooprot)) goto end; break; case 2: if (!TEST_uint_eq(protlen, 0)) goto end; break; case 3: if (!TEST_mem_eq(prot, protlen, barprot + 1, *barprot)) goto end; break; default: TEST_error("Should not get here"); goto end; } } testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #endif /* !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_NEXTPROTONEG) */ static int alpn_select_cb2(SSL *ssl, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg) { int *idx = (int *)arg; switch (*idx) { case 0: *out = (unsigned char *)(fooprot + 1); *outlen = *fooprot; return SSL_TLSEXT_ERR_OK; case 2: *out = (unsigned char *)(barprot + 1); *outlen = *barprot; return SSL_TLSEXT_ERR_OK; case 3: *outlen = 0; return SSL_TLSEXT_ERR_OK; default: case 1: return SSL_TLSEXT_ERR_ALERT_FATAL; } return 0; } /* * Test the ALPN callbacks * Test 0: client = foo, select = foo * Test 1: client = , select = none * Test 2: client = foo, select = bar (should fail) * Test 3: client = foo, select = (should fail) */ static int test_alpn(int idx) { SSL_CTX *sctx = NULL, *cctx = NULL; SSL *serverssl = NULL, *clientssl = NULL; int testresult = 0; const unsigned char *prots = fooprot; unsigned int protslen = sizeof(fooprot); if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), 0, 0, &sctx, &cctx, cert, privkey))) goto end; SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb2, &idx); if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (idx == 1) { prots = NULL; protslen = 0; } /* SSL_set_alpn_protos returns 0 for success! */ if (!TEST_false(SSL_set_alpn_protos(clientssl, prots, protslen))) goto end; if (idx == 2 || idx == 3) { /* We don't allow empty selection of NPN, so this should fail */ if (!TEST_false(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; } else { const unsigned char *prot; unsigned int protlen; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; SSL_get0_alpn_selected(clientssl, &prot, &protlen); switch (idx) { case 0: if (!TEST_mem_eq(prot, protlen, fooprot + 1, *fooprot)) goto end; break; case 1: if (!TEST_uint_eq(protlen, 0)) goto end; break; default: TEST_error("Should not get here"); goto end; } } testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #if !defined(OSSL_NO_USABLE_TLS1_3) struct quic_tls_test_data { struct quic_tls_test_data *peer; uint32_t renc_level; uint32_t wenc_level; unsigned char rcd_data[4][2048]; size_t rcd_data_len[4]; unsigned char rsecret[3][48]; size_t rsecret_len[3]; unsigned char wsecret[3][48]; size_t wsecret_len[3]; unsigned char params[3]; size_t params_len; int alert; int err; int forcefail; int sm_count; }; static int clientquicdata = 0xff, serverquicdata = 0xfe; static int check_app_data(SSL *s) { int *data, *comparedata; /* Check app data works */ data = (int *)SSL_get_app_data(s); comparedata = SSL_is_server(s) ? &serverquicdata : &clientquicdata; if (!TEST_true(comparedata == data)) return 0; return 1; } static int crypto_send_cb(SSL *s, const unsigned char *buf, size_t buf_len, size_t *consumed, void *arg) { struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg; struct quic_tls_test_data *peer = data->peer; size_t max_len = sizeof(peer->rcd_data[data->wenc_level]) - peer->rcd_data_len[data->wenc_level]; if (!check_app_data(s)) { data->err = 1; return 0; } if (buf_len > max_len) buf_len = max_len; if (buf_len == 0) { *consumed = 0; return 1; } memcpy(peer->rcd_data[data->wenc_level] + peer->rcd_data_len[data->wenc_level], buf, buf_len); peer->rcd_data_len[data->wenc_level] += buf_len; *consumed = buf_len; return 1; } static int crypto_recv_rcd_cb(SSL *s, const unsigned char **buf, size_t *bytes_read, void *arg) { struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg; if (!check_app_data(s)) { data->err = 1; return 0; } *bytes_read = data->rcd_data_len[data->renc_level]; *buf = data->rcd_data[data->renc_level]; return 1; } static int crypto_release_rcd_cb(SSL *s, size_t bytes_read, void *arg) { struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg; if (!check_app_data(s)) { data->err = 1; return 0; } /* See if we need to force a failure in this callback */ if (data->forcefail) { data->forcefail = 0; data->err = 1; return 0; } if (!TEST_size_t_eq(bytes_read, data->rcd_data_len[data->renc_level]) || !TEST_size_t_gt(bytes_read, 0)) { data->err = 1; return 0; } data->rcd_data_len[data->renc_level] = 0; return 1; } struct secret_yield_entry { uint8_t recorded; int prot_level; int direction; int sm_generation; SSL *ssl; }; static struct secret_yield_entry secret_history[16]; static int secret_history_idx = 0; /* * Note, this enum needs to match the direction values passed * to yield_secret_cb */ typedef enum { LAST_DIR_READ = 0, LAST_DIR_WRITE = 1, LAST_DIR_UNSET = 2 } last_dir_history_state; static int check_secret_history(SSL *s) { int i; int ret = 0; last_dir_history_state last_state = LAST_DIR_UNSET; int last_prot_level = 0; int last_generation = 0; TEST_info("Checking history for %p\n", (void *)s); for (i = 0; secret_history[i].recorded == 1; i++) { if (secret_history[i].ssl != s) continue; TEST_info("Got %s(%d) secret for level %d, last level %d, last state %d, gen %d\n", secret_history[i].direction == 1 ? "Write" : "Read", secret_history[i].direction, secret_history[i].prot_level, last_prot_level, last_state, secret_history[i].sm_generation); if (last_state == LAST_DIR_UNSET) { last_prot_level = secret_history[i].prot_level; last_state = secret_history[i].direction; last_generation = secret_history[i].sm_generation; continue; } switch(secret_history[i].direction) { case 1: /* * write case * NOTE: There is an odd corner case here. It may occur that * in a single iteration of the state machine, the read key is yielded * prior to the write key for the same level. This is undesireable * for quic, but it is ok, as the general implementation of every 3rd * party quic stack while prefering write keys before read, allows * for read before write if both keys are yielded in the same call * to SSL_do_handshake, as the tls adaptation code for that quic stack * can then cache keys until both are available, so we allow read before * write here iff they occur in the same iteration of SSL_do_handshake * as represented by the recorded sm_generation value. */ if (last_prot_level == secret_history[i].prot_level && last_state == LAST_DIR_READ) { if (last_generation == secret_history[i].sm_generation) { TEST_info("Read before write key in same SSL state machine iteration is ok"); } else { TEST_error("Got read key before write key"); goto end; } } /* FALLTHROUGH */ case 0: /* * Read case */ break; default: TEST_error("Unknown direction"); goto end; } last_prot_level = secret_history[i].prot_level; last_state = secret_history[i].direction; last_generation = secret_history[i].sm_generation; } ret = 1; end: return ret; } static int yield_secret_cb(SSL *s, uint32_t prot_level, int direction, const unsigned char *secret, size_t secret_len, void *arg) { struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg; if (!check_app_data(s)) goto err; if (prot_level < OSSL_RECORD_PROTECTION_LEVEL_EARLY || prot_level > OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) goto err; switch (direction) { case 0: /* read */ if (!TEST_size_t_le(secret_len, sizeof(data->rsecret))) goto err; data->renc_level = prot_level; memcpy(data->rsecret[prot_level - 1], secret, secret_len); data->rsecret_len[prot_level - 1] = secret_len; break; case 1: /* write */ if (!TEST_size_t_le(secret_len, sizeof(data->wsecret))) goto err; data->wenc_level = prot_level; memcpy(data->wsecret[prot_level - 1], secret, secret_len); data->wsecret_len[prot_level - 1] = secret_len; break; default: goto err; } secret_history[secret_history_idx].direction = direction; secret_history[secret_history_idx].prot_level = (int)prot_level; secret_history[secret_history_idx].recorded = 1; secret_history[secret_history_idx].ssl = s; secret_history[secret_history_idx].sm_generation = data->sm_count; secret_history_idx++; return 1; err: data->err = 1; return 0; } static int yield_secret_cb_fail(SSL *s, uint32_t prot_level, int direction, const unsigned char *secret, size_t secret_len, void *arg) { (void)s; (void)prot_level; (void)direction; (void)secret; (void)secret_len; (void)arg; /* * This callback is to test double free in quic tls */ return 0; } static int got_transport_params_cb(SSL *s, const unsigned char *params, size_t params_len, void *arg) { struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg; if (!check_app_data(s)) { data->err = 1; return 0; } if (!TEST_size_t_le(params_len, sizeof(data->params))) { data->err = 1; return 0; } memcpy(data->params, params, params_len); data->params_len = params_len; return 1; } static int alert_cb(SSL *s, unsigned char alert_code, void *arg) { struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg; if (!check_app_data(s)) { data->err = 1; return 0; } data->alert = 1; return 1; } /* * Test the QUIC TLS API * Test 0: Normal run * Test 1: Force a failure * Test 3: Use a CCM based ciphersuite * Test 4: fail yield_secret_cb to see double free * Test 5: Normal run with SNI */ static int test_quic_tls(int idx) { SSL_CTX *sctx = NULL, *sctx2 = NULL, *cctx = NULL; SSL *serverssl = NULL, *clientssl = NULL; int testresult = 0; OSSL_DISPATCH qtdis[] = { {OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_SEND, (void (*)(void))crypto_send_cb}, {OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_RECV_RCD, (void (*)(void))crypto_recv_rcd_cb}, {OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_RELEASE_RCD, (void (*)(void))crypto_release_rcd_cb}, {OSSL_FUNC_SSL_QUIC_TLS_YIELD_SECRET, (void (*)(void))yield_secret_cb}, {OSSL_FUNC_SSL_QUIC_TLS_GOT_TRANSPORT_PARAMS, (void (*)(void))got_transport_params_cb}, {OSSL_FUNC_SSL_QUIC_TLS_ALERT, (void (*)(void))alert_cb}, {0, NULL} }; struct quic_tls_test_data sdata, cdata; const unsigned char cparams[] = { 0xff, 0x01, 0x00 }; const unsigned char sparams[] = { 0xfe, 0x01, 0x00 }; int i; if (idx == 4) qtdis[3].function = (void (*)(void))yield_secret_cb_fail; snicb = 0; memset(secret_history, 0, sizeof(secret_history)); secret_history_idx = 0; memset(&sdata, 0, sizeof(sdata)); memset(&cdata, 0, sizeof(cdata)); sdata.peer = &cdata; cdata.peer = &sdata; if (idx == 1) sdata.forcefail = 1; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_3_VERSION, 0, &sctx, &cctx, cert, privkey))) goto end; if (idx == 5) { if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), NULL, TLS1_3_VERSION, 0, &sctx2, NULL, cert, privkey))) goto end; /* Set up SNI */ if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb)) || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2))) goto end; } if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; /* Reset the BIOs we set in create_ssl_objects. We should not need them */ SSL_set_bio(serverssl, NULL, NULL); SSL_set_bio(clientssl, NULL, NULL); if (idx == 2) { if (!TEST_true(SSL_set_ciphersuites(serverssl, "TLS_AES_128_CCM_SHA256")) || !TEST_true(SSL_set_ciphersuites(clientssl, "TLS_AES_128_CCM_SHA256"))) goto end; } if (!TEST_true(SSL_set_app_data(clientssl, &clientquicdata)) || !TEST_true(SSL_set_app_data(serverssl, &serverquicdata))) goto end; if (!TEST_true(SSL_set_quic_tls_cbs(clientssl, qtdis, &cdata)) || !TEST_true(SSL_set_quic_tls_cbs(serverssl, qtdis, &sdata)) || !TEST_true(SSL_set_quic_tls_transport_params(clientssl, cparams, sizeof(cparams))) || !TEST_true(SSL_set_quic_tls_transport_params(serverssl, sparams, sizeof(sparams)))) goto end; if (idx != 1 && idx != 4) { if (!TEST_true(create_ssl_connection_ex(serverssl, clientssl, SSL_ERROR_NONE, &cdata.sm_count, &sdata.sm_count))) goto end; } else { /* We expect this connection to fail */ if (!TEST_false(create_ssl_connection_ex(serverssl, clientssl, SSL_ERROR_NONE, &cdata.sm_count, &sdata.sm_count))) goto end; testresult = 1; sdata.err = 0; goto end; } /* We should have had the SNI callback called exactly once */ if (idx == 5) { if (!TEST_int_eq(snicb, 1)) goto end; } /* Check no problems during the handshake */ if (!TEST_false(sdata.alert) || !TEST_false(cdata.alert) || !TEST_false(sdata.err) || !TEST_false(cdata.err)) goto end; /* Check the secrets all match */ for (i = OSSL_RECORD_PROTECTION_LEVEL_EARLY - 1; i < OSSL_RECORD_PROTECTION_LEVEL_APPLICATION; i++) { if (!TEST_mem_eq(sdata.wsecret[i], sdata.wsecret_len[i], cdata.rsecret[i], cdata.rsecret_len[i])) goto end; } /* * Check that our secret history yields write secrets before read secrets */ if (!TEST_int_eq(check_secret_history(serverssl), 1)) goto end; if (!TEST_int_eq(check_secret_history(clientssl), 1)) goto end; /* Check the transport params */ if (!TEST_mem_eq(sdata.params, sdata.params_len, cparams, sizeof(cparams)) || !TEST_mem_eq(cdata.params, cdata.params_len, sparams, sizeof(sparams))) goto end; /* Check the encryption levels are what we expect them to be */ if (!TEST_true(sdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) || !TEST_true(sdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) || !TEST_true(cdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) || !TEST_true(cdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx2); SSL_CTX_free(sctx); SSL_CTX_free(cctx); /* Check that we didn't suddenly hit an unexpected failure during cleanup */ if (!TEST_false(sdata.err) || !TEST_false(cdata.err)) testresult = 0; return testresult; } static void assert_no_end_of_early_data(int write_p, int version, int content_type, const void *buf, size_t msglen, SSL *ssl, void *arg) { const unsigned char *msg = buf; if (content_type == SSL3_RT_HANDSHAKE && msg[0] == SSL3_MT_END_OF_EARLY_DATA) end_of_early_data = 1; } static int test_quic_tls_early_data(void) { SSL_CTX *sctx = NULL, *cctx = NULL; SSL *serverssl = NULL, *clientssl = NULL; int testresult = 0; SSL_SESSION *sess = NULL; const OSSL_DISPATCH qtdis[] = { {OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_SEND, (void (*)(void))crypto_send_cb}, {OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_RECV_RCD, (void (*)(void))crypto_recv_rcd_cb}, {OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_RELEASE_RCD, (void (*)(void))crypto_release_rcd_cb}, {OSSL_FUNC_SSL_QUIC_TLS_YIELD_SECRET, (void (*)(void))yield_secret_cb}, {OSSL_FUNC_SSL_QUIC_TLS_GOT_TRANSPORT_PARAMS, (void (*)(void))got_transport_params_cb}, {OSSL_FUNC_SSL_QUIC_TLS_ALERT, (void (*)(void))alert_cb}, {0, NULL} }; struct quic_tls_test_data sdata, cdata; const unsigned char cparams[] = { 0xff, 0x01, 0x00 }; const unsigned char sparams[] = { 0xfe, 0x01, 0x00 }; int i; memset(secret_history, 0, sizeof(secret_history)); secret_history_idx = 0; memset(&sdata, 0, sizeof(sdata)); memset(&cdata, 0, sizeof(cdata)); sdata.peer = &cdata; cdata.peer = &sdata; end_of_early_data = 0; if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(), TLS1_3_VERSION, 0, &sctx, &cctx, cert, privkey))) goto end; SSL_CTX_set_max_early_data(sctx, 0xffffffff); SSL_CTX_set_max_early_data(cctx, 0xffffffff); if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; sess = SSL_get1_session(clientssl); SSL_shutdown(clientssl); SSL_shutdown(serverssl); SSL_free(serverssl); SSL_free(clientssl); serverssl = clientssl = NULL; if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) || !TEST_true(SSL_set_session(clientssl, sess))) goto end; /* Reset the BIOs we set in create_ssl_objects. We should not need them */ SSL_set_bio(serverssl, NULL, NULL); SSL_set_bio(clientssl, NULL, NULL); if (!TEST_true(SSL_set_app_data(clientssl, &clientquicdata)) || !TEST_true(SSL_set_app_data(serverssl, &serverquicdata))) goto end; if (!TEST_true(SSL_set_quic_tls_cbs(clientssl, qtdis, &cdata)) || !TEST_true(SSL_set_quic_tls_cbs(serverssl, qtdis, &sdata)) || !TEST_true(SSL_set_quic_tls_transport_params(clientssl, cparams, sizeof(cparams))) || !TEST_true(SSL_set_quic_tls_transport_params(serverssl, sparams, sizeof(sparams)))) goto end; /* * Reset our secret history so we get the record of the second connection */ memset(secret_history, 0, sizeof(secret_history)); secret_history_idx = 0; SSL_set_quic_tls_early_data_enabled(serverssl, 1); SSL_set_quic_tls_early_data_enabled(clientssl, 1); SSL_set_msg_callback(serverssl, assert_no_end_of_early_data); SSL_set_msg_callback(clientssl, assert_no_end_of_early_data); if (!TEST_int_eq(SSL_connect(clientssl), -1) || !TEST_int_eq(SSL_accept(serverssl), -1) || !TEST_int_eq(SSL_get_early_data_status(serverssl), SSL_EARLY_DATA_ACCEPTED) || !TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_WANT_READ) || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_WANT_READ)) goto end; /* Check the encryption levels are what we expect them to be */ if (!TEST_true(sdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE) || !TEST_true(sdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) || !TEST_true(cdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_NONE) || !TEST_true(cdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_EARLY)) goto end; sdata.sm_count = 0; cdata.sm_count = 0; if (!TEST_true(create_ssl_connection_ex(serverssl, clientssl, SSL_ERROR_NONE, &cdata.sm_count, &sdata.sm_count))) goto end; /* Check no problems during the handshake */ if (!TEST_false(sdata.alert) || !TEST_false(cdata.alert) || !TEST_false(sdata.err) || !TEST_false(cdata.err)) goto end; /* Check the secrets all match */ for (i = OSSL_RECORD_PROTECTION_LEVEL_EARLY - 1; i < OSSL_RECORD_PROTECTION_LEVEL_APPLICATION; i++) { if (!TEST_mem_eq(sdata.wsecret[i], sdata.wsecret_len[i], cdata.rsecret[i], cdata.rsecret_len[i])) goto end; } if (!TEST_int_eq(check_secret_history(serverssl), 1)) goto end; if (!TEST_int_eq(check_secret_history(clientssl), 1)) goto end; /* Check the transport params */ if (!TEST_mem_eq(sdata.params, sdata.params_len, cparams, sizeof(cparams)) || !TEST_mem_eq(cdata.params, cdata.params_len, sparams, sizeof(sparams))) goto end; /* Check the encryption levels are what we expect them to be */ if (!TEST_true(sdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) || !TEST_true(sdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) || !TEST_true(cdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) || !TEST_true(cdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)) goto end; /* Check there is no EndOfEearlyData in handshake */ if (!TEST_int_eq(end_of_early_data, 0)) goto end; testresult = 1; end: SSL_SESSION_free(sess); SSL_SESSION_free(clientpsk); SSL_SESSION_free(serverpsk); clientpsk = serverpsk = NULL; SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } #endif /* !defined(OSSL_NO_USABLE_TLS1_3) */ static int test_no_renegotiation(int idx) { SSL_CTX *sctx = NULL, *cctx = NULL; SSL *serverssl = NULL, *clientssl = NULL; int testresult = 0, ret; int max_proto; const SSL_METHOD *sm, *cm; unsigned char buf[5]; if (idx == 0) { #ifndef OPENSSL_NO_TLS1_2 max_proto = TLS1_2_VERSION; sm = TLS_server_method(); cm = TLS_client_method(); #else return TEST_skip("TLSv1.2 is disabled in this build"); #endif } else { #ifndef OPENSSL_NO_DTLS1_2 max_proto = DTLS1_2_VERSION; sm = DTLS_server_method(); cm = DTLS_client_method(); #else return TEST_skip("DTLSv1.2 is disabled in this build"); #endif } if (!TEST_true(create_ssl_ctx_pair(libctx, sm, cm, 0, max_proto, &sctx, &cctx, cert, privkey))) goto end; SSL_CTX_set_options(sctx, SSL_OP_NO_RENEGOTIATION); if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL))) goto end; if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) goto end; if (!TEST_true(SSL_renegotiate(clientssl)) || !TEST_int_le(ret = SSL_connect(clientssl), 0) || !TEST_int_eq(SSL_get_error(clientssl, ret), SSL_ERROR_WANT_READ)) goto end; /* * We've not sent any application data, so we expect this to fail. It should * also read the renegotiation attempt, and send back a no_renegotiation * warning alert because we have renegotiation disabled. */ if (!TEST_int_le(ret = SSL_read(serverssl, buf, sizeof(buf)), 0)) goto end; if (!TEST_int_eq(SSL_get_error(serverssl, ret), SSL_ERROR_WANT_READ)) goto end; /* * The client should now see the no_renegotiation warning and fail the * connection */ if (!TEST_int_le(ret = SSL_connect(clientssl), 0) || !TEST_int_eq(SSL_get_error(clientssl, ret), SSL_ERROR_SSL) || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()), SSL_R_NO_RENEGOTIATION)) goto end; testresult = 1; end: SSL_free(serverssl); SSL_free(clientssl); SSL_CTX_free(sctx); SSL_CTX_free(cctx); return testresult; } +#if defined(DO_SSL_TRACE_TEST) +/* + * Tests that the SSL_trace() msg_callback works as expected with a PQ Groups. + */ +static int test_ssl_trace(void) +{ + SSL_CTX *sctx = NULL, *cctx = NULL; + SSL *serverssl = NULL, *clientssl = NULL; + int testresult = 0; + BIO *bio = NULL; + char *reffile = NULL; + char *grouplist = "MLKEM512:MLKEM768:MLKEM1024:X25519MLKEM768:SecP256r1MLKEM768" + ":SecP384r1MLKEM1024:secp521r1:secp384r1:secp256r1"; + + if (!fips_provider_version_ge(libctx, 3, 5, 0)) + return TEST_skip("FIPS provider does not support MLKEM algorithms"); + + if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), + TLS_client_method(), + TLS1_3_VERSION, TLS1_3_VERSION, + &sctx, &cctx, cert, privkey)) + || !TEST_ptr(bio = BIO_new(BIO_s_mem())) + || !TEST_true(SSL_CTX_set1_groups_list(sctx, grouplist)) + || !TEST_true(SSL_CTX_set1_groups_list(cctx, grouplist)) + || !TEST_true(SSL_CTX_set_ciphersuites(cctx, + "TLS_AES_128_GCM_SHA256")) + || !TEST_true(SSL_CTX_set_ciphersuites(sctx, + "TLS_AES_128_GCM_SHA256")) +# ifdef SSL_OP_LEGACY_EC_POINT_FORMATS + || !TEST_true(SSL_CTX_set_options(cctx, SSL_OP_LEGACY_EC_POINT_FORMATS)) + || !TEST_true(SSL_CTX_set_options(sctx, SSL_OP_LEGACY_EC_POINT_FORMATS)) +# endif + || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, + NULL, NULL))) + goto err; + + SSL_set_msg_callback(clientssl, SSL_trace); + SSL_set_msg_callback_arg(clientssl, bio); + + if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) + goto err; + + /* Skip the comparison of the trace when the fips provider is used. */ + if (is_fips) { + /* Check whether there was something written. */ + if (!TEST_int_gt(BIO_pending(bio), 0)) + goto err; + } else { + +# ifdef OPENSSL_NO_ZLIB + reffile = test_mk_file_path(datadir, "ssltraceref.txt"); +# else + reffile = test_mk_file_path(datadir, "ssltraceref-zlib.txt"); +# endif + if (!TEST_true(compare_with_reference_file(bio, reffile))) + goto err; + } + + testresult = 1; + err: + BIO_free(bio); + SSL_free(serverssl); + SSL_free(clientssl); + SSL_CTX_free(sctx); + SSL_CTX_free(cctx); + OPENSSL_free(reffile); + + return testresult; +} +#endif + OPT_TEST_DECLARE_USAGE("certfile privkeyfile srpvfile tmpfile provider config dhfile\n") int setup_tests(void) { char *modulename; char *configfile; libctx = OSSL_LIB_CTX_new(); if (!TEST_ptr(libctx)) return 0; defctxnull = OSSL_PROVIDER_load(NULL, "null"); /* * Verify that the default and fips providers in the default libctx are not * available */ if (!TEST_false(OSSL_PROVIDER_available(NULL, "default")) || !TEST_false(OSSL_PROVIDER_available(NULL, "fips"))) return 0; if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); return 0; } if (!TEST_ptr(certsdir = test_get_argument(0)) || !TEST_ptr(srpvfile = test_get_argument(1)) || !TEST_ptr(tmpfilename = test_get_argument(2)) || !TEST_ptr(modulename = test_get_argument(3)) || !TEST_ptr(configfile = test_get_argument(4)) || !TEST_ptr(dhfile = test_get_argument(5))) return 0; + datadir = test_get_argument(6); + if (!TEST_true(OSSL_LIB_CTX_load_config(libctx, configfile))) return 0; /* Check we have the expected provider available */ if (!TEST_true(OSSL_PROVIDER_available(libctx, modulename))) return 0; /* Check the default provider is not available */ if (strcmp(modulename, "default") != 0 && !TEST_false(OSSL_PROVIDER_available(libctx, "default"))) return 0; if (strcmp(modulename, "fips") == 0) { OSSL_PROVIDER *prov = NULL; OSSL_PARAM params[2]; is_fips = 1; prov = OSSL_PROVIDER_load(libctx, "fips"); if (prov != NULL) { /* Query the fips provider to check if the check ems option is enabled */ params[0] = OSSL_PARAM_construct_int(OSSL_PROV_PARAM_TLS1_PRF_EMS_CHECK, &fips_ems_check); params[1] = OSSL_PARAM_construct_end(); OSSL_PROVIDER_get_params(prov, params); OSSL_PROVIDER_unload(prov); } } /* * We add, but don't load the test "tls-provider". We'll load it when we * need it. */ if (!TEST_true(OSSL_PROVIDER_add_builtin(libctx, "tls-provider", tls_provider_init))) return 0; if (getenv("OPENSSL_TEST_GETCOUNTS") != NULL) { #ifdef OPENSSL_NO_CRYPTO_MDEBUG TEST_error("not supported in this build"); return 0; #else int i, mcount, rcount, fcount; for (i = 0; i < 4; i++) test_export_key_mat(i); CRYPTO_get_alloc_counts(&mcount, &rcount, &fcount); test_printf_stdout("malloc %d realloc %d free %d\n", mcount, rcount, fcount); return 1; #endif } cert = test_mk_file_path(certsdir, "servercert.pem"); if (cert == NULL) goto err; privkey = test_mk_file_path(certsdir, "serverkey.pem"); if (privkey == NULL) goto err; cert2 = test_mk_file_path(certsdir, "server-ecdsa-cert.pem"); if (cert2 == NULL) goto err; privkey2 = test_mk_file_path(certsdir, "server-ecdsa-key.pem"); if (privkey2 == NULL) goto err; cert1024 = test_mk_file_path(certsdir, "ee-cert-1024.pem"); if (cert1024 == NULL) goto err; privkey1024 = test_mk_file_path(certsdir, "ee-key-1024.pem"); if (privkey1024 == NULL) goto err; cert3072 = test_mk_file_path(certsdir, "ee-cert-3072.pem"); if (cert3072 == NULL) goto err; privkey3072 = test_mk_file_path(certsdir, "ee-key-3072.pem"); if (privkey3072 == NULL) goto err; cert4096 = test_mk_file_path(certsdir, "ee-cert-4096.pem"); if (cert4096 == NULL) goto err; privkey4096 = test_mk_file_path(certsdir, "ee-key-4096.pem"); if (privkey4096 == NULL) goto err; cert8192 = test_mk_file_path(certsdir, "ee-cert-8192.pem"); if (cert8192 == NULL) goto err; privkey8192 = test_mk_file_path(certsdir, "ee-key-8192.pem"); if (privkey8192 == NULL) goto err; if (fips_ems_check) { #ifndef OPENSSL_NO_TLS1_2 ADD_TEST(test_no_ems); #endif return 1; } #if !defined(OPENSSL_NO_KTLS) && !defined(OPENSSL_NO_SOCK) # if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3) ADD_ALL_TESTS(test_ktls, NUM_KTLS_TEST_CIPHERS * 4); ADD_ALL_TESTS(test_ktls_sendfile, NUM_KTLS_TEST_CIPHERS * 2); # endif #endif ADD_TEST(test_large_message_tls); ADD_TEST(test_large_message_tls_read_ahead); #ifndef OPENSSL_NO_DTLS ADD_TEST(test_large_message_dtls); #endif ADD_ALL_TESTS(test_large_app_data, 28); ADD_TEST(test_cleanse_plaintext); #ifndef OPENSSL_NO_OCSP ADD_TEST(test_tlsext_status_type); #endif ADD_TEST(test_session_with_only_int_cache); ADD_TEST(test_session_with_only_ext_cache); ADD_TEST(test_session_with_both_cache); ADD_TEST(test_session_wo_ca_names); #ifndef OSSL_NO_USABLE_TLS1_3 ADD_ALL_TESTS(test_stateful_tickets, 3); ADD_ALL_TESTS(test_stateless_tickets, 3); ADD_TEST(test_psk_tickets); ADD_ALL_TESTS(test_extra_tickets, 6); #endif ADD_ALL_TESTS(test_ssl_set_bio, TOTAL_SSL_SET_BIO_TESTS); ADD_TEST(test_ssl_bio_pop_next_bio); ADD_TEST(test_ssl_bio_pop_ssl_bio); ADD_TEST(test_ssl_bio_change_rbio); ADD_TEST(test_ssl_bio_change_wbio); #if !defined(OPENSSL_NO_TLS1_2) || defined(OSSL_NO_USABLE_TLS1_3) ADD_ALL_TESTS(test_set_sigalgs, OSSL_NELEM(testsigalgs) * 2); ADD_TEST(test_keylog); #endif #ifndef OSSL_NO_USABLE_TLS1_3 ADD_TEST(test_keylog_no_master_key); #endif ADD_TEST(test_client_cert_verify_cb); ADD_TEST(test_ssl_build_cert_chain); ADD_TEST(test_ssl_ctx_build_cert_chain); #ifndef OPENSSL_NO_TLS1_2 ADD_TEST(test_client_hello_cb); ADD_TEST(test_no_ems); ADD_TEST(test_ccs_change_cipher); #endif #ifndef OSSL_NO_USABLE_TLS1_3 ADD_ALL_TESTS(test_early_data_read_write, 6); /* * We don't do replay tests for external PSK. Replay protection isn't used * in that scenario. */ ADD_ALL_TESTS(test_early_data_replay, 2); ADD_ALL_TESTS(test_early_data_skip, OSSL_NELEM(ciphersuites) * 3); ADD_ALL_TESTS(test_early_data_skip_hrr, OSSL_NELEM(ciphersuites) * 3); ADD_ALL_TESTS(test_early_data_skip_hrr_fail, OSSL_NELEM(ciphersuites) * 3); ADD_ALL_TESTS(test_early_data_skip_abort, OSSL_NELEM(ciphersuites) * 3); ADD_ALL_TESTS(test_early_data_not_sent, 3); ADD_ALL_TESTS(test_early_data_psk, 8); ADD_ALL_TESTS(test_early_data_psk_with_all_ciphers, 7); ADD_ALL_TESTS(test_early_data_not_expected, 3); # ifndef OPENSSL_NO_TLS1_2 ADD_ALL_TESTS(test_early_data_tls1_2, 3); # endif #endif #ifndef OSSL_NO_USABLE_TLS1_3 ADD_ALL_TESTS(test_set_ciphersuite, 10); ADD_TEST(test_ciphersuite_change); ADD_ALL_TESTS(test_tls13_ciphersuite, 4); # ifdef OPENSSL_NO_PSK ADD_ALL_TESTS(test_tls13_psk, 1); # else ADD_ALL_TESTS(test_tls13_psk, 4); # endif /* OPENSSL_NO_PSK */ #ifndef OSSL_NO_USABLE_TLS1_3 ADD_ALL_TESTS(test_tls13_no_dhe_kex, 8); #endif /* OSSL_NO_USABLE_TLS1_3 */ # ifndef OPENSSL_NO_TLS1_2 /* Test with both TLSv1.3 and 1.2 versions */ ADD_ALL_TESTS(test_key_exchange, 21); # if !defined(OPENSSL_NO_EC) && !defined(OPENSSL_NO_DH) ADD_ALL_TESTS(test_negotiated_group, 4 * (OSSL_NELEM(ecdhe_kexch_groups) + OSSL_NELEM(ffdhe_kexch_groups))); # endif # else /* Test with only TLSv1.3 versions */ ADD_ALL_TESTS(test_key_exchange, 18); # endif ADD_ALL_TESTS(test_custom_exts, 6); ADD_TEST(test_stateless); ADD_TEST(test_pha_key_update); #else ADD_ALL_TESTS(test_custom_exts, 3); #endif ADD_ALL_TESTS(test_export_key_mat, 6); #ifndef OSSL_NO_USABLE_TLS1_3 ADD_ALL_TESTS(test_export_key_mat_early, 3); ADD_TEST(test_key_update); ADD_ALL_TESTS(test_key_update_peer_in_write, 2); ADD_ALL_TESTS(test_key_update_peer_in_read, 2); ADD_ALL_TESTS(test_key_update_local_in_write, 2); ADD_ALL_TESTS(test_key_update_local_in_read, 2); #endif ADD_ALL_TESTS(test_ssl_clear, 8); ADD_ALL_TESTS(test_max_fragment_len_ext, OSSL_NELEM(max_fragment_len_test)); #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2) ADD_ALL_TESTS(test_srp, 6); #endif #if !defined(OPENSSL_NO_COMP_ALG) /* Add compression case */ ADD_ALL_TESTS(test_info_callback, 8); #else ADD_ALL_TESTS(test_info_callback, 6); #endif ADD_ALL_TESTS(test_ssl_pending, 2); ADD_ALL_TESTS(test_ssl_get_shared_ciphers, OSSL_NELEM(shared_ciphers_data)); ADD_ALL_TESTS(test_ticket_callbacks, 20); ADD_ALL_TESTS(test_shutdown, 7); ADD_TEST(test_async_shutdown); ADD_ALL_TESTS(test_incorrect_shutdown, 2); ADD_ALL_TESTS(test_cert_cb, 6); ADD_ALL_TESTS(test_client_cert_cb, 2); ADD_ALL_TESTS(test_ca_names, 3); #ifndef OPENSSL_NO_TLS1_2 ADD_ALL_TESTS(test_multiblock_write, OSSL_NELEM(multiblock_cipherlist_data)); #endif ADD_ALL_TESTS(test_servername, 10); ADD_TEST(test_unknown_sigalgs_groups); #if (!defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)) || !defined(OPENSSL_NO_ML_KEM) ADD_TEST(test_configuration_of_groups); #endif #if !defined(OPENSSL_NO_EC) \ && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)) ADD_ALL_TESTS(test_sigalgs_available, 6); #endif #ifndef OPENSSL_NO_TLS1_3 ADD_ALL_TESTS(test_pluggable_group, 2); ADD_ALL_TESTS(test_pluggable_signature, 6); #endif #ifndef OPENSSL_NO_TLS1_2 ADD_TEST(test_ssl_dup); ADD_TEST(test_session_secret_cb); # ifndef OPENSSL_NO_DH ADD_ALL_TESTS(test_set_tmp_dh, 11); ADD_ALL_TESTS(test_dh_auto, 7); # endif #endif #ifndef OSSL_NO_USABLE_TLS1_3 ADD_TEST(test_sni_tls13); ADD_ALL_TESTS(test_ticket_lifetime, 2); #endif ADD_TEST(test_inherit_verify_param); ADD_TEST(test_set_alpn); ADD_TEST(test_set_verify_cert_store_ssl_ctx); ADD_TEST(test_set_verify_cert_store_ssl); ADD_ALL_TESTS(test_session_timeout, 1); #if !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2) ADD_ALL_TESTS(test_session_cache_overflow, 4); #endif ADD_TEST(test_load_dhfile); #ifndef OSSL_NO_USABLE_TLS1_3 ADD_TEST(test_read_ahead_key_change); ADD_ALL_TESTS(test_tls13_record_padding, 6); #endif #if !defined(OPENSSL_NO_TLS1_2) && !defined(OSSL_NO_USABLE_TLS1_3) ADD_ALL_TESTS(test_serverinfo_custom, 4); #endif #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE) ADD_ALL_TESTS(test_pipelining, 7); #endif ADD_ALL_TESTS(test_version, 6); ADD_TEST(test_rstate_string); ADD_ALL_TESTS(test_handshake_retry, 16); ADD_TEST(test_data_retry); ADD_ALL_TESTS(test_multi_resume, 5); ADD_ALL_TESTS(test_select_next_proto, OSSL_NELEM(next_proto_tests)); #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_NEXTPROTONEG) ADD_ALL_TESTS(test_npn, 5); #endif ADD_ALL_TESTS(test_alpn, 4); #if !defined(OSSL_NO_USABLE_TLS1_3) ADD_ALL_TESTS(test_quic_tls, 6); ADD_TEST(test_quic_tls_early_data); #endif ADD_ALL_TESTS(test_no_renegotiation, 2); +#if defined(DO_SSL_TRACE_TEST) + if (datadir != NULL) + ADD_TEST(test_ssl_trace); +#endif return 1; err: OPENSSL_free(cert); OPENSSL_free(privkey); OPENSSL_free(cert2); OPENSSL_free(privkey2); return 0; } void cleanup_tests(void) { # if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DH) EVP_PKEY_free(tmp_dh_params); #endif OPENSSL_free(cert); OPENSSL_free(privkey); OPENSSL_free(cert2); OPENSSL_free(privkey2); OPENSSL_free(cert1024); OPENSSL_free(privkey1024); OPENSSL_free(cert3072); OPENSSL_free(privkey3072); OPENSSL_free(cert4096); OPENSSL_free(privkey4096); OPENSSL_free(cert8192); OPENSSL_free(privkey8192); bio_s_mempacket_test_free(); bio_s_always_retry_free(); bio_s_maybe_retry_free(); OSSL_PROVIDER_unload(defctxnull); OSSL_LIB_CTX_free(libctx); } diff --git a/test/testutil.h b/test/testutil.h index f02dcdfba6f9..a262d9371955 100644 --- a/test/testutil.h +++ b/test/testutil.h @@ -1,655 +1,657 @@ /* * Copyright 2014-2025 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_TESTUTIL_H # define OSSL_TESTUTIL_H # include # include "internal/common.h" /* for HAS_PREFIX */ # include # include # include # include # include # include "opt.h" /*- * Simple unit tests should implement setup_tests(). * This function should return zero if the registration process fails. * To register tests, call ADD_TEST or ADD_ALL_TESTS: * * int setup_tests(void) * { * ADD_TEST(test_foo); * ADD_ALL_TESTS(test_bar, num_test_bar); * return 1; * } * * Tests that require clean up after execution should implement: * * void cleanup_tests(void); * * The cleanup_tests function will be called even if setup_tests() * returns failure. * * In some cases, early initialization before the framework is set up * may be needed. In such a case, this should be implemented: * * int global_init(void); * * This function should return zero if there is an unrecoverable error and * non-zero if the initialization was successful. */ /* Adds a simple test case. */ # define ADD_TEST(test_function) add_test(#test_function, test_function) /* * Simple parameterized tests. Calls test_function(idx) for each 0 <= idx < num. */ # define ADD_ALL_TESTS(test_function, num) \ add_all_tests(#test_function, test_function, num, 1) /* * A variant of the same without TAP output. */ # define ADD_ALL_TESTS_NOSUBTEST(test_function, num) \ add_all_tests(#test_function, test_function, num, 0) /*- * Test cases that share common setup should use the helper * SETUP_TEST_FIXTURE and EXECUTE_TEST macros for test case functions. * * SETUP_TEST_FIXTURE will call set_up() to create a new TEST_FIXTURE_TYPE * object called "fixture". It will also allocate the "result" variable used * by EXECUTE_TEST. set_up() should take a const char* specifying the test * case name and return a TEST_FIXTURE_TYPE by reference. * If case set_up() fails then 0 is returned. * * EXECUTE_TEST will pass fixture to execute_func() by reference, call * tear_down(), and return the result of execute_func(). execute_func() should * take a TEST_FIXTURE_TYPE by reference and return 1 on success and 0 on * failure. The tear_down function is responsible for deallocation of the * result variable, if required. * * Unit tests can define their own SETUP_TEST_FIXTURE and EXECUTE_TEST * variations like so: * * #define SETUP_FOOBAR_TEST_FIXTURE()\ * SETUP_TEST_FIXTURE(FOOBAR_TEST_FIXTURE, set_up_foobar) * * #define EXECUTE_FOOBAR_TEST()\ * EXECUTE_TEST(execute_foobar, tear_down_foobar) * * Then test case functions can take the form: * * static int test_foobar_feature() * { * SETUP_FOOBAR_TEST_FIXTURE(); * [...set individual members of fixture...] * EXECUTE_FOOBAR_TEST(); * } */ # define SETUP_TEST_FIXTURE(TEST_FIXTURE_TYPE, set_up)\ TEST_FIXTURE_TYPE *fixture = set_up(TEST_CASE_NAME); \ int result = 0; \ \ if (fixture == NULL) \ return 0 # define EXECUTE_TEST(execute_func, tear_down)\ if (fixture != NULL) {\ result = execute_func(fixture);\ tear_down(fixture);\ } /* * TEST_CASE_NAME is defined as the name of the test case function where * possible; otherwise we get by with the file name and line number. */ # if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L # if defined(_MSC_VER) # define TEST_CASE_NAME __FUNCTION__ # else # define testutil_stringify_helper(s) #s # define testutil_stringify(s) testutil_stringify_helper(s) # define TEST_CASE_NAME __FILE__ ":" testutil_stringify(__LINE__) # endif /* _MSC_VER */ # else # define TEST_CASE_NAME __func__ # endif /* __STDC_VERSION__ */ /* The default test enum which should be common to all tests */ # define OPT_TEST_ENUM \ OPT_TEST_HELP = 500, \ OPT_TEST_LIST, \ OPT_TEST_SINGLE, \ OPT_TEST_ITERATION, \ OPT_TEST_INDENT, \ OPT_TEST_SEED /* The Default test OPTIONS common to all tests (without a usage string) */ # define OPT_TEST_OPTIONS \ { OPT_HELP_STR, 1, '-', "Valid options are:\n" }, \ { "help", OPT_TEST_HELP, '-', "Display this summary" }, \ { "list", OPT_TEST_LIST, '-', "Display the list of tests available" }, \ { "test", OPT_TEST_SINGLE, 's', "Run a single test by id or name" }, \ { "iter", OPT_TEST_ITERATION, 'n', "Run a single iteration of a test" }, \ { "indent", OPT_TEST_INDENT,'p', "Number of tabs added to output" }, \ { "seed", OPT_TEST_SEED, 'n', "Seed value to randomize tests with" } /* The Default test OPTIONS common to all tests starting with an additional usage string */ # define OPT_TEST_OPTIONS_WITH_EXTRA_USAGE(usage) \ { OPT_HELP_STR, 1, '-', "Usage: %s [options] " usage }, \ OPT_TEST_OPTIONS /* The Default test OPTIONS common to all tests with an default usage string */ # define OPT_TEST_OPTIONS_DEFAULT_USAGE \ { OPT_HELP_STR, 1, '-', "Usage: %s [options]\n" }, \ OPT_TEST_OPTIONS /* * Optional Cases that need to be ignored by the test app when using opt_next(), * (that are handled internally). */ # define OPT_TEST_CASES \ OPT_TEST_HELP: \ case OPT_TEST_LIST: \ case OPT_TEST_SINGLE: \ case OPT_TEST_ITERATION: \ case OPT_TEST_INDENT: \ case OPT_TEST_SEED /* * Tests that use test_get_argument() that dont have any additional options * (i.e- dont use opt_next()) can use this to set the usage string. * It embeds test_get_options() which gives default command line options for * the test system. * * Tests that need to use opt_next() need to specify * (1) test_get_options() containing an options[] which should include either * OPT_TEST_OPTIONS_DEFAULT_USAGE or * OPT_TEST_OPTIONS_WITH_EXTRA_USAGE(...). * (2) An enum outside the test_get_options() which contains OPT_TEST_ENUM, as * well as the additional options that need to be handled. * (3) case OPT_TEST_CASES: break; inside the opt_next() handling code. */ # define OPT_TEST_DECLARE_USAGE(usage_str) \ const OPTIONS *test_get_options(void) \ { \ enum { OPT_TEST_ENUM }; \ static const OPTIONS options[] = { \ OPT_TEST_OPTIONS_WITH_EXTRA_USAGE(usage_str), \ { NULL } \ }; \ return options; \ } /* * Used to read non optional command line values that follow after the options. * Returns NULL if there is no argument. */ char *test_get_argument(size_t n); /* Return the number of additional non optional command line arguments */ size_t test_get_argument_count(void); /* * Skip over common test options. Should be called before calling * test_get_argument() */ int test_skip_common_options(void); /* * Get a library context for the tests, populated with the specified provider * and configuration. If default_null_prov is not NULL, a "null" provider is * loaded into the default library context to prevent it being used. * If libctx is NULL, the specified provider is loaded into the default library * context. */ int test_get_libctx(OSSL_LIB_CTX **libctx, OSSL_PROVIDER **default_null_prov, const char *config_file, OSSL_PROVIDER **provider, const char *module_name); int test_arg_libctx(OSSL_LIB_CTX **libctx, OSSL_PROVIDER **default_null_prov, OSSL_PROVIDER **provider, int argn, const char *usage); /* * Internal helpers. Test programs shouldn't use these directly, but should * rather link to one of the helper main() methods. */ void add_test(const char *test_case_name, int (*test_fn) (void)); void add_all_tests(const char *test_case_name, int (*test_fn)(int idx), int num, int subtest); /* * Declarations for user defined functions. * The first two return a boolean indicating that the test should not proceed. */ int global_init(void); int setup_tests(void); void cleanup_tests(void); /* * Helper functions to detect specific versions of the FIPS provider being in use. * Because of FIPS rules, code changes after a module has been validated are * difficult and because we provide a hard guarantee of ABI and behavioural * stability going forwards, it is a requirement to have tests be conditional * on specific FIPS provider versions. Without this, bug fixes cannot be tested * in later releases. * * The reason for not including e.g. a less than test is to help avoid any * temptation to use FIPS provider version numbers that don't exist. Until the * `new' provider is validated, its version isn't set in stone. Thus a change * in test behaviour must depend on already validated module versions only. * * In all cases, the function returns true if: * 1. the FIPS provider version matches the criteria specified or * 2. the FIPS provider isn't being used. */ int fips_provider_version_eq(OSSL_LIB_CTX *libctx, int major, int minor, int patch); int fips_provider_version_ne(OSSL_LIB_CTX *libctx, int major, int minor, int patch); int fips_provider_version_le(OSSL_LIB_CTX *libctx, int major, int minor, int patch); int fips_provider_version_lt(OSSL_LIB_CTX *libctx, int major, int minor, int patch); int fips_provider_version_gt(OSSL_LIB_CTX *libctx, int major, int minor, int patch); int fips_provider_version_ge(OSSL_LIB_CTX *libctx, int major, int minor, int patch); /* * This function matches fips provider version with (potentially multiple) * maj.min.patch version strings in versions. * The operator can be one of = ! <= or > comparison symbols. * If the fips provider matches all the version comparisons (or if there is no * fips provider available) the function returns 1. * If the fips provider does not match the version comparisons, it returns 0. * On error the function returns -1. */ int fips_provider_version_match(OSSL_LIB_CTX *libctx, const char *versions); /* * Used to supply test specific command line options, * If non optional parameters are used, then the first entry in the OPTIONS[] * should contain: * { OPT_HELP_STR, 1, '-', "\n"}, * The last entry should always be { NULL }. * * Run the test locally using './test/test_name -help' to check the usage. */ const OPTIONS *test_get_options(void); /* * Test assumption verification helpers. */ # define PRINTF_FORMAT(a, b) # if defined(__GNUC__) && defined(__STDC_VERSION__) \ && !defined(__MINGW32__) && !defined(__MINGW64__) \ && !defined(__APPLE__) /* * Because we support the 'z' modifier, which made its appearance in C99, * we can't use __attribute__ with pre C99 dialects. */ # if __STDC_VERSION__ >= 199901L # undef PRINTF_FORMAT # define PRINTF_FORMAT(a, b) __attribute__ ((format(printf, a, b))) # endif # endif # define DECLARE_COMPARISON(type, name, opname) \ int test_ ## name ## _ ## opname(const char *, int, \ const char *, const char *, \ const type, const type); # define DECLARE_COMPARISONS(type, name) \ DECLARE_COMPARISON(type, name, eq) \ DECLARE_COMPARISON(type, name, ne) \ DECLARE_COMPARISON(type, name, lt) \ DECLARE_COMPARISON(type, name, le) \ DECLARE_COMPARISON(type, name, gt) \ DECLARE_COMPARISON(type, name, ge) DECLARE_COMPARISONS(int, int) DECLARE_COMPARISONS(unsigned int, uint) DECLARE_COMPARISONS(char, char) DECLARE_COMPARISONS(unsigned char, uchar) DECLARE_COMPARISONS(long, long) DECLARE_COMPARISONS(unsigned long, ulong) DECLARE_COMPARISONS(int64_t, int64_t) DECLARE_COMPARISONS(uint64_t, uint64_t) DECLARE_COMPARISONS(double, double) DECLARE_COMPARISONS(time_t, time_t) /* * Because this comparison uses a printf format specifier that's not * universally known (yet), we provide an option to not have it declared. */ # ifndef TESTUTIL_NO_size_t_COMPARISON DECLARE_COMPARISONS(size_t, size_t) # endif /* * Pointer comparisons against other pointers and null. * These functions return 1 if the test is true. * Otherwise, they return 0 and pretty-print diagnostics. * These should not be called directly, use the TEST_xxx macros below instead. */ DECLARE_COMPARISON(void *, ptr, eq) DECLARE_COMPARISON(void *, ptr, ne) int test_ptr(const char *file, int line, const char *s, const void *p); int test_ptr_null(const char *file, int line, const char *s, const void *p); /* * Equality tests for strings where NULL is a legitimate value. * These calls return 1 if the two passed strings compare true. * Otherwise, they return 0 and pretty-print diagnostics. * These should not be called directly, use the TEST_xxx macros below instead. */ DECLARE_COMPARISON(char *, str, eq) DECLARE_COMPARISON(char *, str, ne) /* * Same as above, but for strncmp. */ int test_strn_eq(const char *file, int line, const char *, const char *, const char *a, size_t an, const char *b, size_t bn); int test_strn_ne(const char *file, int line, const char *, const char *, const char *a, size_t an, const char *b, size_t bn); /* * Equality test for memory blocks where NULL is a legitimate value. * These calls return 1 if the two memory blocks compare true. * Otherwise, they return 0 and pretty-print diagnostics. * These should not be called directly, use the TEST_xxx macros below instead. */ int test_mem_eq(const char *, int, const char *, const char *, const void *, size_t, const void *, size_t); int test_mem_ne(const char *, int, const char *, const char *, const void *, size_t, const void *, size_t); /* * Check a boolean result for being true or false. * They return 1 if the condition is true (i.e. the value is non-zero). * Otherwise, they return 0 and pretty-prints diagnostics using |s|. * These should not be called directly, use the TEST_xxx macros below instead. */ int test_true(const char *file, int line, const char *s, int b); int test_false(const char *file, int line, const char *s, int b); /* * Comparisons between BIGNUMs. * BIGNUMS can be compared against other BIGNUMs or zero. * Some additional equality tests against 1 & specific values are provided. * Tests for parity are included as well. */ DECLARE_COMPARISONS(BIGNUM *, BN) int test_BN_eq_zero(const char *file, int line, const char *s, const BIGNUM *a); int test_BN_ne_zero(const char *file, int line, const char *s, const BIGNUM *a); int test_BN_lt_zero(const char *file, int line, const char *s, const BIGNUM *a); int test_BN_le_zero(const char *file, int line, const char *s, const BIGNUM *a); int test_BN_gt_zero(const char *file, int line, const char *s, const BIGNUM *a); int test_BN_ge_zero(const char *file, int line, const char *s, const BIGNUM *a); int test_BN_eq_one(const char *file, int line, const char *s, const BIGNUM *a); int test_BN_odd(const char *file, int line, const char *s, const BIGNUM *a); int test_BN_even(const char *file, int line, const char *s, const BIGNUM *a); int test_BN_eq_word(const char *file, int line, const char *bns, const char *ws, const BIGNUM *a, BN_ULONG w); int test_BN_abs_eq_word(const char *file, int line, const char *bns, const char *ws, const BIGNUM *a, BN_ULONG w); /* * Pretty print a failure message. * These should not be called directly, use the TEST_xxx macros below instead. */ void test_error(const char *file, int line, const char *desc, ...) PRINTF_FORMAT(3, 4); void test_error_c90(const char *desc, ...) PRINTF_FORMAT(1, 2); void test_info(const char *file, int line, const char *desc, ...) PRINTF_FORMAT(3, 4); void test_info_c90(const char *desc, ...) PRINTF_FORMAT(1, 2); void test_note(const char *desc, ...) PRINTF_FORMAT(1, 2); int test_skip(const char *file, int line, const char *desc, ...) PRINTF_FORMAT(3, 4); int test_skip_c90(const char *desc, ...) PRINTF_FORMAT(1, 2); void test_openssl_errors(void); void test_perror(const char *s); /* * The following macros provide wrapper calls to the test functions with * a default description that indicates the file and line number of the error. * * The following macros guarantee to evaluate each argument exactly once. * This allows constructs such as: if (!TEST_ptr(ptr = OPENSSL_malloc(..))) * to produce better contextual output than: * ptr = OPENSSL_malloc(..); * if (!TEST_ptr(ptr)) */ # define TEST_int_eq(a, b) test_int_eq(__FILE__, __LINE__, #a, #b, a, b) # define TEST_int_ne(a, b) test_int_ne(__FILE__, __LINE__, #a, #b, a, b) # define TEST_int_lt(a, b) test_int_lt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_int_le(a, b) test_int_le(__FILE__, __LINE__, #a, #b, a, b) # define TEST_int_gt(a, b) test_int_gt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_int_ge(a, b) test_int_ge(__FILE__, __LINE__, #a, #b, a, b) # define TEST_uint_eq(a, b) test_uint_eq(__FILE__, __LINE__, #a, #b, a, b) # define TEST_uint_ne(a, b) test_uint_ne(__FILE__, __LINE__, #a, #b, a, b) # define TEST_uint_lt(a, b) test_uint_lt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_uint_le(a, b) test_uint_le(__FILE__, __LINE__, #a, #b, a, b) # define TEST_uint_gt(a, b) test_uint_gt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_uint_ge(a, b) test_uint_ge(__FILE__, __LINE__, #a, #b, a, b) # define TEST_char_eq(a, b) test_char_eq(__FILE__, __LINE__, #a, #b, a, b) # define TEST_char_ne(a, b) test_char_ne(__FILE__, __LINE__, #a, #b, a, b) # define TEST_char_lt(a, b) test_char_lt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_char_le(a, b) test_char_le(__FILE__, __LINE__, #a, #b, a, b) # define TEST_char_gt(a, b) test_char_gt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_char_ge(a, b) test_char_ge(__FILE__, __LINE__, #a, #b, a, b) # define TEST_uchar_eq(a, b) test_uchar_eq(__FILE__, __LINE__, #a, #b, a, b) # define TEST_uchar_ne(a, b) test_uchar_ne(__FILE__, __LINE__, #a, #b, a, b) # define TEST_uchar_lt(a, b) test_uchar_lt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_uchar_le(a, b) test_uchar_le(__FILE__, __LINE__, #a, #b, a, b) # define TEST_uchar_gt(a, b) test_uchar_gt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_uchar_ge(a, b) test_uchar_ge(__FILE__, __LINE__, #a, #b, a, b) # define TEST_long_eq(a, b) test_long_eq(__FILE__, __LINE__, #a, #b, a, b) # define TEST_long_ne(a, b) test_long_ne(__FILE__, __LINE__, #a, #b, a, b) # define TEST_long_lt(a, b) test_long_lt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_long_le(a, b) test_long_le(__FILE__, __LINE__, #a, #b, a, b) # define TEST_long_gt(a, b) test_long_gt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_long_ge(a, b) test_long_ge(__FILE__, __LINE__, #a, #b, a, b) # define TEST_ulong_eq(a, b) test_ulong_eq(__FILE__, __LINE__, #a, #b, a, b) # define TEST_ulong_ne(a, b) test_ulong_ne(__FILE__, __LINE__, #a, #b, a, b) # define TEST_ulong_lt(a, b) test_ulong_lt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_ulong_le(a, b) test_ulong_le(__FILE__, __LINE__, #a, #b, a, b) # define TEST_ulong_gt(a, b) test_ulong_gt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_ulong_ge(a, b) test_ulong_ge(__FILE__, __LINE__, #a, #b, a, b) # define TEST_int64_t_eq(a, b) test_int64_t_eq(__FILE__, __LINE__, #a, #b, a, b) # define TEST_int64_t_ne(a, b) test_int64_t_ne(__FILE__, __LINE__, #a, #b, a, b) # define TEST_int64_t_lt(a, b) test_int64_t_lt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_int64_t_le(a, b) test_int64_t_le(__FILE__, __LINE__, #a, #b, a, b) # define TEST_int64_t_gt(a, b) test_int64_t_gt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_int64_t_ge(a, b) test_int64_t_ge(__FILE__, __LINE__, #a, #b, a, b) # define TEST_uint64_t_eq(a, b) test_uint64_t_eq(__FILE__, __LINE__, #a, #b, a, b) # define TEST_uint64_t_ne(a, b) test_uint64_t_ne(__FILE__, __LINE__, #a, #b, a, b) # define TEST_uint64_t_lt(a, b) test_uint64_t_lt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_uint64_t_le(a, b) test_uint64_t_le(__FILE__, __LINE__, #a, #b, a, b) # define TEST_uint64_t_gt(a, b) test_uint64_t_gt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_uint64_t_ge(a, b) test_uint64_t_ge(__FILE__, __LINE__, #a, #b, a, b) # define TEST_size_t_eq(a, b) test_size_t_eq(__FILE__, __LINE__, #a, #b, a, b) # define TEST_size_t_ne(a, b) test_size_t_ne(__FILE__, __LINE__, #a, #b, a, b) # define TEST_size_t_lt(a, b) test_size_t_lt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_size_t_le(a, b) test_size_t_le(__FILE__, __LINE__, #a, #b, a, b) # define TEST_size_t_gt(a, b) test_size_t_gt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_size_t_ge(a, b) test_size_t_ge(__FILE__, __LINE__, #a, #b, a, b) # define TEST_double_eq(a, b) test_double_eq(__FILE__, __LINE__, #a, #b, a, b) # define TEST_double_ne(a, b) test_double_ne(__FILE__, __LINE__, #a, #b, a, b) # define TEST_double_lt(a, b) test_double_lt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_double_le(a, b) test_double_le(__FILE__, __LINE__, #a, #b, a, b) # define TEST_double_gt(a, b) test_double_gt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_double_ge(a, b) test_double_ge(__FILE__, __LINE__, #a, #b, a, b) # define TEST_time_t_eq(a, b) test_time_t_eq(__FILE__, __LINE__, #a, #b, a, b) # define TEST_time_t_ne(a, b) test_time_t_ne(__FILE__, __LINE__, #a, #b, a, b) # define TEST_time_t_lt(a, b) test_time_t_lt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_time_t_le(a, b) test_time_t_le(__FILE__, __LINE__, #a, #b, a, b) # define TEST_time_t_gt(a, b) test_time_t_gt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_time_t_ge(a, b) test_time_t_ge(__FILE__, __LINE__, #a, #b, a, b) # define TEST_ptr_eq(a, b) test_ptr_eq(__FILE__, __LINE__, #a, #b, a, b) # define TEST_ptr_ne(a, b) test_ptr_ne(__FILE__, __LINE__, #a, #b, a, b) # define TEST_ptr(a) test_ptr(__FILE__, __LINE__, #a, a) # define TEST_ptr_null(a) test_ptr_null(__FILE__, __LINE__, #a, a) # define TEST_str_eq(a, b) test_str_eq(__FILE__, __LINE__, #a, #b, a, b) # define TEST_str_ne(a, b) test_str_ne(__FILE__, __LINE__, #a, #b, a, b) # define TEST_strn_eq(a, b, n) test_strn_eq(__FILE__, __LINE__, #a, #b, a, n, b, n) # define TEST_strn_ne(a, b, n) test_strn_ne(__FILE__, __LINE__, #a, #b, a, n, b, n) # define TEST_strn2_eq(a, m, b, n) test_strn_eq(__FILE__, __LINE__, #a, #b, a, m, b, n) # define TEST_strn2_ne(a, m, b, n) test_strn_ne(__FILE__, __LINE__, #a, #b, a, m, b, n) # define TEST_mem_eq(a, m, b, n) test_mem_eq(__FILE__, __LINE__, #a, #b, a, m, b, n) # define TEST_mem_ne(a, m, b, n) test_mem_ne(__FILE__, __LINE__, #a, #b, a, m, b, n) # define TEST_true(a) test_true(__FILE__, __LINE__, #a, (a) != 0) # define TEST_false(a) test_false(__FILE__, __LINE__, #a, (a) != 0) # define TEST_BN_eq(a, b) test_BN_eq(__FILE__, __LINE__, #a, #b, a, b) # define TEST_BN_ne(a, b) test_BN_ne(__FILE__, __LINE__, #a, #b, a, b) # define TEST_BN_lt(a, b) test_BN_lt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_BN_gt(a, b) test_BN_gt(__FILE__, __LINE__, #a, #b, a, b) # define TEST_BN_le(a, b) test_BN_le(__FILE__, __LINE__, #a, #b, a, b) # define TEST_BN_ge(a, b) test_BN_ge(__FILE__, __LINE__, #a, #b, a, b) # define TEST_BN_eq_zero(a) test_BN_eq_zero(__FILE__, __LINE__, #a, a) # define TEST_BN_ne_zero(a) test_BN_ne_zero(__FILE__, __LINE__, #a, a) # define TEST_BN_lt_zero(a) test_BN_lt_zero(__FILE__, __LINE__, #a, a) # define TEST_BN_gt_zero(a) test_BN_gt_zero(__FILE__, __LINE__, #a, a) # define TEST_BN_le_zero(a) test_BN_le_zero(__FILE__, __LINE__, #a, a) # define TEST_BN_ge_zero(a) test_BN_ge_zero(__FILE__, __LINE__, #a, a) # define TEST_BN_eq_one(a) test_BN_eq_one(__FILE__, __LINE__, #a, a) # define TEST_BN_eq_word(a, w) test_BN_eq_word(__FILE__, __LINE__, #a, #w, a, w) # define TEST_BN_abs_eq_word(a, w) test_BN_abs_eq_word(__FILE__, __LINE__, #a, #w, a, w) # define TEST_BN_odd(a) test_BN_odd(__FILE__, __LINE__, #a, a) # define TEST_BN_even(a) test_BN_even(__FILE__, __LINE__, #a, a) /* * TEST_error(desc, ...) prints an informative error message in the standard * format. |desc| is a printf format string. */ # if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L # define TEST_error test_error_c90 # define TEST_info test_info_c90 # define TEST_skip test_skip_c90 # else # define TEST_error(...) test_error(__FILE__, __LINE__, __VA_ARGS__) # define TEST_info(...) test_info(__FILE__, __LINE__, __VA_ARGS__) # define TEST_skip(...) test_skip(__FILE__, __LINE__, __VA_ARGS__) # endif # define TEST_note test_note # define TEST_openssl_errors test_openssl_errors # define TEST_perror test_perror extern BIO *bio_out; extern BIO *bio_err; /* Thread local BIO overrides. */ int set_override_bio_out(BIO *bio); int set_override_bio_err(BIO *bio); /* * Formatted output for strings, memory and bignums. */ void test_output_string(const char *name, const char *m, size_t l); void test_output_bignum(const char *name, const BIGNUM *bn); void test_output_memory(const char *name, const unsigned char *m, size_t l); /* * Utilities to parse a test file. */ # define TESTMAXPAIRS 150 typedef struct pair_st { char *key; char *value; } PAIR; typedef struct stanza_st { const char *test_file; /* Input file name */ BIO *fp; /* Input file */ int curr; /* Current line in file */ int start; /* Line where test starts */ int errors; /* Error count */ int numtests; /* Number of tests */ int numskip; /* Number of skipped tests */ int numpairs; PAIR pairs[TESTMAXPAIRS]; BIO *key; /* temp memory BIO for reading in keys */ } STANZA; /* * Prepare to start reading the file |testfile| as input. */ int test_start_file(STANZA *s, const char *testfile); int test_end_file(STANZA *s); /* * Read a stanza from the test file. A stanza consists of a block * of lines of the form * key = value * The block is terminated by EOF or a blank line. * Return 1 if found, 0 on EOF or error. */ int test_readstanza(STANZA *s); /* * Clear a stanza, release all allocated memory. */ void test_clearstanza(STANZA *s); /* * Glue an array of strings together and return it as an allocated string. * Optionally return the whole length of this string in |out_len| */ char *glue_strings(const char *list[], size_t *out_len); /* * Pseudo random number generator of low quality but having repeatability * across platforms. The two calls are replacements for random(3) and * srandom(3). */ uint32_t test_random(void); void test_random_seed(uint32_t sd); /* Fake non-secure random number generator */ typedef int fake_random_generate_cb(unsigned char *out, size_t outlen, const char *name, EVP_RAND_CTX *ctx); OSSL_PROVIDER *fake_rand_start(OSSL_LIB_CTX *libctx); void fake_rand_finish(OSSL_PROVIDER *p); void fake_rand_set_callback(EVP_RAND_CTX *ctx, int (*cb)(unsigned char *out, size_t outlen, const char *name, EVP_RAND_CTX *ctx)); void fake_rand_set_public_private_callbacks(OSSL_LIB_CTX *libctx, fake_random_generate_cb *cb); /* Create a file path from a directory and a filename */ char *test_mk_file_path(const char *dir, const char *file); EVP_PKEY *load_pkey_pem(const char *file, OSSL_LIB_CTX *libctx); X509 *load_cert_pem(const char *file, OSSL_LIB_CTX *libctx); X509 *load_cert_der(const unsigned char *bytes, int len); STACK_OF(X509) *load_certs_pem(const char *file); X509_REQ *load_csr_der(const char *file, OSSL_LIB_CTX *libctx); time_t test_asn1_string_to_time_t(const char *asn1_string); + +int compare_with_reference_file(BIO *membio, const char *reffile); #endif /* OSSL_TESTUTIL_H */ diff --git a/test/testutil/compare.c b/test/testutil/compare.c new file mode 100644 index 000000000000..067fb878b58e --- /dev/null +++ b/test/testutil/compare.c @@ -0,0 +1,88 @@ +/* + * Copyright 2017-2025 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 "../testutil.h" + +static void strip_line_ends(char *str) +{ + size_t i; + + for (i = strlen(str); + i > 0 && (str[i - 1] == '\n' || str[i - 1] == '\r'); + i--); + + str[i] = '\0'; +} + +int compare_with_reference_file(BIO *membio, const char *reffile) +{ + BIO *file = NULL, *newfile = NULL; + char buf1[8192], buf2[8192]; + int ret = 0; + size_t i; + + if (!TEST_ptr(reffile)) + goto err; + + file = BIO_new_file(reffile, "rb"); + if (!TEST_ptr(file)) + goto err; + + newfile = BIO_new_file("ssltraceref-new.txt", "wb"); + if (!TEST_ptr(newfile)) + goto err; + + while (BIO_gets(membio, buf2, sizeof(buf2)) > 0) + if (BIO_puts(newfile, buf2) <= 0) { + TEST_error("Failed writing new file data"); + goto err; + } + + if (!TEST_int_ge(BIO_seek(membio, 0), 0)) + goto err; + + while (BIO_gets(file, buf1, sizeof(buf1)) > 0) { + size_t line_len; + + if (BIO_gets(membio, buf2, sizeof(buf2)) <= 0) { + TEST_error("Failed reading mem data"); + goto err; + } + strip_line_ends(buf1); + strip_line_ends(buf2); + line_len = strlen(buf1); + if (line_len > 0 && buf1[line_len - 1] == '?') { + /* Wildcard at the EOL means ignore anything after it */ + if (strlen(buf2) > line_len) + buf2[line_len] = '\0'; + } + if (line_len != strlen(buf2)) { + TEST_error("Actual and ref line data length mismatch"); + TEST_info("%s", buf1); + TEST_info("%s", buf2); + goto err; + } + for (i = 0; i < line_len; i++) { + /* '?' is a wild card character in the reference text */ + if (buf1[i] == '?') + buf2[i] = '?'; + } + if (!TEST_str_eq(buf1, buf2)) + goto err; + } + if (!TEST_true(BIO_eof(file)) + || !TEST_true(BIO_eof(membio))) + goto err; + + ret = 1; + err: + BIO_free(file); + BIO_free(newfile); + return ret; +} diff --git a/test/threadstest.c b/test/threadstest.c index 38401911d87f..d33ad46999c6 100644 --- a/test/threadstest.c +++ b/test/threadstest.c @@ -1,1458 +1,1461 @@ /* * Copyright 2016-2025 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 */ /* * The test_multi_downgrade_shared_pkey function tests the thread safety of a * deprecated function. */ #ifndef OPENSSL_NO_DEPRECATED_3_0 # define OPENSSL_SUPPRESS_DEPRECATED #endif #if defined(_WIN32) # include #endif #include #include #include #include #include #include #include #include #include "internal/tsan_assist.h" #include "internal/nelem.h" #include "internal/time.h" #include "internal/rcu.h" #include "testutil.h" #include "threadstest.h" #ifdef __SANITIZE_THREAD__ #include #define TSAN_ACQUIRE(s) __tsan_acquire(s) #else #define TSAN_ACQUIRE(s) #endif /* Limit the maximum number of threads */ #define MAXIMUM_THREADS 10 /* Limit the maximum number of providers loaded into a library context */ #define MAXIMUM_PROVIDERS 4 static int do_fips = 0; static char *privkey; static char *storedir; static char *config_file = NULL; static int multidefault_run = 0; static const char *default_provider[] = { "default", NULL }; static const char *fips_provider[] = { "fips", NULL }; static const char *fips_and_default_providers[] = { "default", "fips", NULL }; static CRYPTO_RWLOCK *global_lock; #ifdef TSAN_REQUIRES_LOCKING static CRYPTO_RWLOCK *tsan_lock; #endif /* Grab a globally unique integer value, return 0 on failure */ static int get_new_uid(void) { /* * Start with a nice large number to avoid potential conflicts when * we generate a new OID. */ static TSAN_QUALIFIER int current_uid = 1 << (sizeof(int) * 8 - 2); #ifdef TSAN_REQUIRES_LOCKING int r; if (!TEST_true(CRYPTO_THREAD_write_lock(tsan_lock))) return 0; r = ++current_uid; if (!TEST_true(CRYPTO_THREAD_unlock(tsan_lock))) return 0; return r; #else return tsan_counter(¤t_uid); #endif } static int test_lock(void) { CRYPTO_RWLOCK *lock = CRYPTO_THREAD_lock_new(); int res; if (!TEST_ptr(lock)) return 0; res = TEST_true(CRYPTO_THREAD_read_lock(lock)) && TEST_true(CRYPTO_THREAD_unlock(lock)) && TEST_true(CRYPTO_THREAD_write_lock(lock)) && TEST_true(CRYPTO_THREAD_unlock(lock)); CRYPTO_THREAD_lock_free(lock); return res; } #if defined(OPENSSL_THREADS) static int contention = 0; static int rwwriter1_done = 0; static int rwwriter2_done = 0; static int rwreader1_iterations = 0; static int rwreader2_iterations = 0; static int rwwriter1_iterations = 0; static int rwwriter2_iterations = 0; static int *rwwriter_ptr = NULL; static int rw_torture_result = 1; static CRYPTO_RWLOCK *rwtorturelock = NULL; static CRYPTO_RWLOCK *atomiclock = NULL; static void rwwriter_fn(int id, int *iterations) { int count; int *old, *new; OSSL_TIME t1, t2; t1 = ossl_time_now(); for (count = 0; ; count++) { new = CRYPTO_zalloc(sizeof (int), NULL, 0); if (contention == 0) OSSL_sleep(1000); if (!CRYPTO_THREAD_write_lock(rwtorturelock)) abort(); if (rwwriter_ptr != NULL) { *new = *rwwriter_ptr + 1; } else { *new = 0; } old = rwwriter_ptr; rwwriter_ptr = new; if (!CRYPTO_THREAD_unlock(rwtorturelock)) abort(); if (old != NULL) CRYPTO_free(old, __FILE__, __LINE__); t2 = ossl_time_now(); if ((ossl_time2seconds(t2) - ossl_time2seconds(t1)) >= 4) break; } *iterations = count; return; } static void rwwriter1_fn(void) { int local; TEST_info("Starting writer1"); rwwriter_fn(1, &rwwriter1_iterations); CRYPTO_atomic_add(&rwwriter1_done, 1, &local, atomiclock); } static void rwwriter2_fn(void) { int local; TEST_info("Starting writer 2"); rwwriter_fn(2, &rwwriter2_iterations); CRYPTO_atomic_add(&rwwriter2_done, 1, &local, atomiclock); } static void rwreader_fn(int *iterations) { unsigned int count = 0; int old = 0; int lw1 = 0; int lw2 = 0; if (CRYPTO_THREAD_read_lock(rwtorturelock) == 0) abort(); while (lw1 != 1 || lw2 != 1) { CRYPTO_atomic_add(&rwwriter1_done, 0, &lw1, atomiclock); CRYPTO_atomic_add(&rwwriter2_done, 0, &lw2, atomiclock); count++; - if (rwwriter_ptr != NULL && old > *rwwriter_ptr) { - TEST_info("rwwriter pointer went backwards\n"); - rw_torture_result = 0; + if (rwwriter_ptr != NULL) { + if (old > *rwwriter_ptr) { + TEST_info("rwwriter pointer went backwards! %d : %d\n", + old, *rwwriter_ptr); + rw_torture_result = 0; + } + old = *rwwriter_ptr; } if (CRYPTO_THREAD_unlock(rwtorturelock) == 0) abort(); - *iterations = count; if (rw_torture_result == 0) { *iterations = count; return; } if (CRYPTO_THREAD_read_lock(rwtorturelock) == 0) abort(); } *iterations = count; if (CRYPTO_THREAD_unlock(rwtorturelock) == 0) abort(); } static void rwreader1_fn(void) { TEST_info("Starting reader 1"); rwreader_fn(&rwreader1_iterations); } static void rwreader2_fn(void) { TEST_info("Starting reader 2"); rwreader_fn(&rwreader2_iterations); } static thread_t rwwriter1; static thread_t rwwriter2; static thread_t rwreader1; static thread_t rwreader2; static int _torture_rw(void) { double tottime = 0; int ret = 0; double avr, avw; OSSL_TIME t1, t2; struct timeval dtime; rwtorturelock = CRYPTO_THREAD_lock_new(); atomiclock = CRYPTO_THREAD_lock_new(); if (!TEST_ptr(rwtorturelock) || !TEST_ptr(atomiclock)) goto out; rwwriter1_iterations = 0; rwwriter2_iterations = 0; rwreader1_iterations = 0; rwreader2_iterations = 0; rwwriter1_done = 0; rwwriter2_done = 0; rw_torture_result = 1; memset(&rwwriter1, 0, sizeof(thread_t)); memset(&rwwriter2, 0, sizeof(thread_t)); memset(&rwreader1, 0, sizeof(thread_t)); memset(&rwreader2, 0, sizeof(thread_t)); TEST_info("Staring rw torture"); t1 = ossl_time_now(); if (!TEST_true(run_thread(&rwreader1, rwreader1_fn)) || !TEST_true(run_thread(&rwreader2, rwreader2_fn)) || !TEST_true(run_thread(&rwwriter1, rwwriter1_fn)) || !TEST_true(run_thread(&rwwriter2, rwwriter2_fn)) || !TEST_true(wait_for_thread(rwwriter1)) || !TEST_true(wait_for_thread(rwwriter2)) || !TEST_true(wait_for_thread(rwreader1)) || !TEST_true(wait_for_thread(rwreader2))) goto out; t2 = ossl_time_now(); dtime = ossl_time_to_timeval(ossl_time_subtract(t2, t1)); tottime = dtime.tv_sec + (dtime.tv_usec / 1e6); TEST_info("rw_torture_result is %d\n", rw_torture_result); TEST_info("performed %d reads and %d writes over 2 read and 2 write threads in %e seconds", rwreader1_iterations + rwreader2_iterations, rwwriter1_iterations + rwwriter2_iterations, tottime); if ((rwreader1_iterations + rwreader2_iterations == 0) || (rwwriter1_iterations + rwwriter2_iterations == 0)) { TEST_info("Threads did not iterate\n"); goto out; } avr = tottime / (rwreader1_iterations + rwreader2_iterations); avw = (tottime / (rwwriter1_iterations + rwwriter2_iterations)); TEST_info("Average read time %e/read", avr); TEST_info("Averate write time %e/write", avw); if (TEST_int_eq(rw_torture_result, 1)) ret = 1; out: CRYPTO_THREAD_lock_free(rwtorturelock); CRYPTO_THREAD_lock_free(atomiclock); rwtorturelock = NULL; return ret; } static int torture_rw_low(void) { contention = 0; return _torture_rw(); } static int torture_rw_high(void) { contention = 1; return _torture_rw(); } static CRYPTO_RCU_LOCK *rcu_lock = NULL; static int writer1_done = 0; static int writer2_done = 0; static int reader1_iterations = 0; static int reader2_iterations = 0; static int writer1_iterations = 0; static int writer2_iterations = 0; static uint64_t *writer_ptr = NULL; static uint64_t global_ctr = 0; static int rcu_torture_result = 1; static void free_old_rcu_data(void *data) { CRYPTO_free(data, NULL, 0); } static void writer_fn(int id, int *iterations) { int count; OSSL_TIME t1, t2; uint64_t *old, *new; t1 = ossl_time_now(); for (count = 0; ; count++) { new = CRYPTO_malloc(sizeof(uint64_t), NULL, 0); *new = (uint64_t)0xBAD; if (contention == 0) OSSL_sleep(1000); ossl_rcu_write_lock(rcu_lock); old = ossl_rcu_deref(&writer_ptr); TSAN_ACQUIRE(&writer_ptr); *new = global_ctr++; ossl_rcu_assign_ptr(&writer_ptr, &new); if (contention == 0) ossl_rcu_call(rcu_lock, free_old_rcu_data, old); ossl_rcu_write_unlock(rcu_lock); if (contention != 0) { ossl_synchronize_rcu(rcu_lock); CRYPTO_free(old, NULL, 0); } t2 = ossl_time_now(); if ((ossl_time2seconds(t2) - ossl_time2seconds(t1)) >= 4) break; } *iterations = count; return; } static void writer1_fn(void) { int local; TEST_info("Starting writer1"); writer_fn(1, &writer1_iterations); CRYPTO_atomic_add(&writer1_done, 1, &local, atomiclock); } static void writer2_fn(void) { int local; TEST_info("Starting writer2"); writer_fn(2, &writer2_iterations); CRYPTO_atomic_add(&writer2_done, 1, &local, atomiclock); } static void reader_fn(int *iterations) { unsigned int count = 0; uint64_t *valp; uint64_t val; uint64_t oldval = 0; int lw1 = 0; int lw2 = 0; while (lw1 != 1 || lw2 != 1) { CRYPTO_atomic_add(&writer1_done, 0, &lw1, atomiclock); CRYPTO_atomic_add(&writer2_done, 0, &lw2, atomiclock); count++; ossl_rcu_read_lock(rcu_lock); valp = ossl_rcu_deref(&writer_ptr); val = (valp == NULL) ? 0 : *valp; if (oldval > val) { TEST_info("rcu torture value went backwards! %llu : %llu", (unsigned long long)oldval, (unsigned long long)val); if (valp == NULL) TEST_info("ossl_rcu_deref did return NULL!"); rcu_torture_result = 0; } oldval = val; /* just try to deref the pointer */ ossl_rcu_read_unlock(rcu_lock); if (rcu_torture_result == 0) { *iterations = count; return; } } *iterations = count; } static void reader1_fn(void) { TEST_info("Starting reader 1"); reader_fn(&reader1_iterations); } static void reader2_fn(void) { TEST_info("Starting reader 2"); reader_fn(&reader2_iterations); } static thread_t writer1; static thread_t writer2; static thread_t reader1; static thread_t reader2; static int _torture_rcu(void) { OSSL_TIME t1, t2; struct timeval dtime; double tottime; double avr, avw; int rc = 0; atomiclock = CRYPTO_THREAD_lock_new(); if (!TEST_ptr(atomiclock)) goto out; memset(&writer1, 0, sizeof(thread_t)); memset(&writer2, 0, sizeof(thread_t)); memset(&reader1, 0, sizeof(thread_t)); memset(&reader2, 0, sizeof(thread_t)); writer1_iterations = 0; writer2_iterations = 0; reader1_iterations = 0; reader2_iterations = 0; writer1_done = 0; writer2_done = 0; rcu_torture_result = 1; rcu_lock = ossl_rcu_lock_new(contention == 2 ? 4 : 1, NULL); if (rcu_lock == NULL) goto out; TEST_info("Staring rcu torture"); t1 = ossl_time_now(); if (!TEST_true(run_thread(&reader1, reader1_fn)) || !TEST_true(run_thread(&reader2, reader2_fn)) || !TEST_true(run_thread(&writer1, writer1_fn)) || !TEST_true(run_thread(&writer2, writer2_fn)) || !TEST_true(wait_for_thread(writer1)) || !TEST_true(wait_for_thread(writer2)) || !TEST_true(wait_for_thread(reader1)) || !TEST_true(wait_for_thread(reader2))) goto out; t2 = ossl_time_now(); dtime = ossl_time_to_timeval(ossl_time_subtract(t2, t1)); tottime = dtime.tv_sec + (dtime.tv_usec / 1e6); TEST_info("rcu_torture_result is %d\n", rcu_torture_result); TEST_info("performed %d reads and %d writes over 2 read and 2 write threads in %e seconds", reader1_iterations + reader2_iterations, writer1_iterations + writer2_iterations, tottime); if ((reader1_iterations + reader2_iterations == 0) || (writer1_iterations + writer2_iterations == 0)) { TEST_info("Threads did not iterate\n"); goto out; } avr = tottime / (reader1_iterations + reader2_iterations); avw = tottime / (writer1_iterations + writer2_iterations); TEST_info("Average read time %e/read", avr); TEST_info("Average write time %e/write", avw); if (!TEST_int_eq(rcu_torture_result, 1)) goto out; rc = 1; out: ossl_rcu_lock_free(rcu_lock); CRYPTO_THREAD_lock_free(atomiclock); if (!TEST_int_eq(rcu_torture_result, 1)) return 0; return rc; } static int torture_rcu_low(void) { contention = 0; return _torture_rcu(); } static int torture_rcu_high(void) { contention = 1; return _torture_rcu(); } static int torture_rcu_high2(void) { contention = 2; return _torture_rcu(); } #endif static CRYPTO_ONCE once_run = CRYPTO_ONCE_STATIC_INIT; static unsigned once_run_count = 0; static void once_do_run(void) { once_run_count++; } static void once_run_thread_cb(void) { CRYPTO_THREAD_run_once(&once_run, once_do_run); } static int test_once(void) { thread_t thread; if (!TEST_true(run_thread(&thread, once_run_thread_cb)) || !TEST_true(wait_for_thread(thread)) || !CRYPTO_THREAD_run_once(&once_run, once_do_run) || !TEST_int_eq(once_run_count, 1)) return 0; return 1; } static CRYPTO_THREAD_LOCAL thread_local_key; static unsigned destructor_run_count = 0; static int thread_local_thread_cb_ok = 0; static void thread_local_destructor(void *arg) { unsigned *count; if (arg == NULL) return; count = arg; (*count)++; } static void thread_local_thread_cb(void) { void *ptr; ptr = CRYPTO_THREAD_get_local(&thread_local_key); if (!TEST_ptr_null(ptr) || !TEST_true(CRYPTO_THREAD_set_local(&thread_local_key, &destructor_run_count))) return; ptr = CRYPTO_THREAD_get_local(&thread_local_key); if (!TEST_ptr_eq(ptr, &destructor_run_count)) return; thread_local_thread_cb_ok = 1; } static int test_thread_local(void) { thread_t thread; void *ptr = NULL; if (!TEST_true(CRYPTO_THREAD_init_local(&thread_local_key, thread_local_destructor))) return 0; ptr = CRYPTO_THREAD_get_local(&thread_local_key); if (!TEST_ptr_null(ptr) || !TEST_true(run_thread(&thread, thread_local_thread_cb)) || !TEST_true(wait_for_thread(thread)) || !TEST_int_eq(thread_local_thread_cb_ok, 1)) return 0; #if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) ptr = CRYPTO_THREAD_get_local(&thread_local_key); if (!TEST_ptr_null(ptr)) return 0; # if !defined(OPENSSL_SYS_WINDOWS) if (!TEST_int_eq(destructor_run_count, 1)) return 0; # endif #endif if (!TEST_true(CRYPTO_THREAD_cleanup_local(&thread_local_key))) return 0; return 1; } /* * Basic test to ensure that we can repeatedly create and * destroy local keys without leaking anything */ static int test_thread_local_multi_key(void) { int dummy; int i; for (i = 0; i < 1000; i++) { if (!TEST_true(CRYPTO_THREAD_init_local(&thread_local_key, thread_local_destructor))) return 0; if (!TEST_true(CRYPTO_THREAD_set_local(&thread_local_key, &dummy))) return 0; if (!TEST_true(CRYPTO_THREAD_cleanup_local(&thread_local_key))) return 0; } return 1; } static int test_atomic(void) { int val = 0, ret = 0, testresult = 0; uint64_t val64 = 1, ret64 = 0; CRYPTO_RWLOCK *lock = CRYPTO_THREAD_lock_new(); if (!TEST_ptr(lock)) return 0; if (CRYPTO_atomic_add(&val, 1, &ret, NULL)) { /* This succeeds therefore we're on a platform with lockless atomics */ if (!TEST_int_eq(val, 1) || !TEST_int_eq(val, ret)) goto err; } else { /* This failed therefore we're on a platform without lockless atomics */ if (!TEST_int_eq(val, 0) || !TEST_int_eq(val, ret)) goto err; } val = 0; ret = 0; if (!TEST_true(CRYPTO_atomic_add(&val, 1, &ret, lock))) goto err; if (!TEST_int_eq(val, 1) || !TEST_int_eq(val, ret)) goto err; if (CRYPTO_atomic_or(&val64, 2, &ret64, NULL)) { /* This succeeds therefore we're on a platform with lockless atomics */ if (!TEST_uint_eq((unsigned int)val64, 3) || !TEST_uint_eq((unsigned int)val64, (unsigned int)ret64)) goto err; } else { /* This failed therefore we're on a platform without lockless atomics */ if (!TEST_uint_eq((unsigned int)val64, 1) || !TEST_int_eq((unsigned int)ret64, 0)) goto err; } val64 = 1; ret64 = 0; if (!TEST_true(CRYPTO_atomic_or(&val64, 2, &ret64, lock))) goto err; if (!TEST_uint_eq((unsigned int)val64, 3) || !TEST_uint_eq((unsigned int)val64, (unsigned int)ret64)) goto err; ret64 = 0; if (CRYPTO_atomic_load(&val64, &ret64, NULL)) { /* This succeeds therefore we're on a platform with lockless atomics */ if (!TEST_uint_eq((unsigned int)val64, 3) || !TEST_uint_eq((unsigned int)val64, (unsigned int)ret64)) goto err; } else { /* This failed therefore we're on a platform without lockless atomics */ if (!TEST_uint_eq((unsigned int)val64, 3) || !TEST_int_eq((unsigned int)ret64, 0)) goto err; } ret64 = 0; if (!TEST_true(CRYPTO_atomic_load(&val64, &ret64, lock))) goto err; if (!TEST_uint_eq((unsigned int)val64, 3) || !TEST_uint_eq((unsigned int)val64, (unsigned int)ret64)) goto err; ret64 = 0; if (CRYPTO_atomic_and(&val64, 5, &ret64, NULL)) { /* This succeeds therefore we're on a platform with lockless atomics */ if (!TEST_uint_eq((unsigned int)val64, 1) || !TEST_uint_eq((unsigned int)val64, (unsigned int)ret64)) goto err; } else { /* This failed therefore we're on a platform without lockless atomics */ if (!TEST_uint_eq((unsigned int)val64, 3) || !TEST_int_eq((unsigned int)ret64, 0)) goto err; } val64 = 3; ret64 = 0; if (!TEST_true(CRYPTO_atomic_and(&val64, 5, &ret64, lock))) goto err; if (!TEST_uint_eq((unsigned int)val64, 1) || !TEST_uint_eq((unsigned int)val64, (unsigned int)ret64)) goto err; ret64 = 0; if (CRYPTO_atomic_add64(&val64, 2, &ret64, NULL)) { /* This succeeds therefore we're on a platform with lockless atomics */ if (!TEST_uint_eq((unsigned int)val64, 3) || !TEST_uint_eq((unsigned int)val64, (unsigned int)ret64)) goto err; } else { /* This failed therefore we're on a platform without lockless atomics */ if (!TEST_uint_eq((unsigned int)val64, 1) || !TEST_int_eq((unsigned int)ret64, 0)) goto err; } val64 = 1; ret64 = 0; if (!TEST_true(CRYPTO_atomic_add64(&val64, 2, &ret64, lock))) goto err; if (!TEST_uint_eq((unsigned int)val64, 3) || !TEST_uint_eq((unsigned int)val64, (unsigned int)ret64)) goto err; testresult = 1; err: CRYPTO_THREAD_lock_free(lock); return testresult; } static OSSL_LIB_CTX *multi_libctx = NULL; static int multi_success; static OSSL_PROVIDER *multi_provider[MAXIMUM_PROVIDERS + 1]; static size_t multi_num_threads; static thread_t multi_threads[MAXIMUM_THREADS]; static void multi_intialise(void) { multi_success = 1; multi_libctx = NULL; multi_num_threads = 0; memset(multi_threads, 0, sizeof(multi_threads)); memset(multi_provider, 0, sizeof(multi_provider)); } static void multi_set_success(int ok) { if (CRYPTO_THREAD_write_lock(global_lock) == 0) { /* not synchronized, but better than not reporting failure */ multi_success = ok; return; } multi_success = ok; CRYPTO_THREAD_unlock(global_lock); } static void thead_teardown_libctx(void) { OSSL_PROVIDER **p; for (p = multi_provider; *p != NULL; p++) OSSL_PROVIDER_unload(*p); OSSL_LIB_CTX_free(multi_libctx); multi_intialise(); } static int thread_setup_libctx(int libctx, const char *providers[]) { size_t n; if (libctx && !TEST_true(test_get_libctx(&multi_libctx, NULL, config_file, NULL, NULL))) return 0; if (providers != NULL) for (n = 0; providers[n] != NULL; n++) if (!TEST_size_t_lt(n, MAXIMUM_PROVIDERS) || !TEST_ptr(multi_provider[n] = OSSL_PROVIDER_load(multi_libctx, providers[n]))) { thead_teardown_libctx(); return 0; } return 1; } static int teardown_threads(void) { size_t i; for (i = 0; i < multi_num_threads; i++) if (!TEST_true(wait_for_thread(multi_threads[i]))) return 0; return 1; } static int start_threads(size_t n, void (*thread_func)(void)) { size_t i; if (!TEST_size_t_le(multi_num_threads + n, MAXIMUM_THREADS)) return 0; for (i = 0 ; i < n; i++) if (!TEST_true(run_thread(multi_threads + multi_num_threads++, thread_func))) return 0; return 1; } /* Template multi-threaded test function */ static int thread_run_test(void (*main_func)(void), size_t num_threads, void (*thread_func)(void), int libctx, const char *providers[]) { int testresult = 0; multi_intialise(); if (!thread_setup_libctx(libctx, providers) || !start_threads(num_threads, thread_func)) goto err; if (main_func != NULL) main_func(); if (!teardown_threads() || !TEST_true(multi_success)) goto err; testresult = 1; err: thead_teardown_libctx(); return testresult; } static void thread_general_worker(void) { EVP_MD_CTX *mdctx = EVP_MD_CTX_new(); EVP_MD *md = EVP_MD_fetch(multi_libctx, "SHA2-256", NULL); EVP_CIPHER_CTX *cipherctx = EVP_CIPHER_CTX_new(); EVP_CIPHER *ciph = EVP_CIPHER_fetch(multi_libctx, "AES-128-CBC", NULL); const char *message = "Hello World"; size_t messlen = strlen(message); /* Should be big enough for encryption output too */ unsigned char out[EVP_MAX_MD_SIZE]; const unsigned char key[AES_BLOCK_SIZE] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; const unsigned char iv[AES_BLOCK_SIZE] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; unsigned int mdoutl; int ciphoutl; EVP_PKEY *pkey = NULL; int testresult = 0; int i, isfips; isfips = OSSL_PROVIDER_available(multi_libctx, "fips"); if (!TEST_ptr(mdctx) || !TEST_ptr(md) || !TEST_ptr(cipherctx) || !TEST_ptr(ciph)) goto err; /* Do some work */ for (i = 0; i < 5; i++) { if (!TEST_true(EVP_DigestInit_ex(mdctx, md, NULL)) || !TEST_true(EVP_DigestUpdate(mdctx, message, messlen)) || !TEST_true(EVP_DigestFinal(mdctx, out, &mdoutl))) goto err; } for (i = 0; i < 5; i++) { if (!TEST_true(EVP_EncryptInit_ex(cipherctx, ciph, NULL, key, iv)) || !TEST_true(EVP_EncryptUpdate(cipherctx, out, &ciphoutl, (unsigned char *)message, messlen)) || !TEST_true(EVP_EncryptFinal(cipherctx, out, &ciphoutl))) goto err; } /* * We want the test to run quickly - not securely. * Therefore we use an insecure bit length where we can (512). * In the FIPS module though we must use a longer length. */ pkey = EVP_PKEY_Q_keygen(multi_libctx, NULL, "RSA", (size_t)(isfips ? 2048 : 512)); if (!TEST_ptr(pkey)) goto err; testresult = 1; err: EVP_MD_CTX_free(mdctx); EVP_MD_free(md); EVP_CIPHER_CTX_free(cipherctx); EVP_CIPHER_free(ciph); EVP_PKEY_free(pkey); if (!testresult) multi_set_success(0); } static void thread_multi_simple_fetch(void) { EVP_MD *md = EVP_MD_fetch(multi_libctx, "SHA2-256", NULL); if (md != NULL) EVP_MD_free(md); else multi_set_success(0); } static EVP_PKEY *shared_evp_pkey = NULL; static void thread_shared_evp_pkey(void) { char *msg = "Hello World"; unsigned char ctbuf[256]; unsigned char ptbuf[256]; size_t ptlen, ctlen = sizeof(ctbuf); EVP_PKEY_CTX *ctx = NULL; int success = 0; int i; for (i = 0; i < 1 + do_fips; i++) { if (i > 0) EVP_PKEY_CTX_free(ctx); ctx = EVP_PKEY_CTX_new_from_pkey(multi_libctx, shared_evp_pkey, i == 0 ? "provider=default" : "provider=fips"); if (!TEST_ptr(ctx)) goto err; if (!TEST_int_ge(EVP_PKEY_encrypt_init(ctx), 0) || !TEST_int_ge(EVP_PKEY_encrypt(ctx, ctbuf, &ctlen, (unsigned char *)msg, strlen(msg)), 0)) goto err; EVP_PKEY_CTX_free(ctx); ctx = EVP_PKEY_CTX_new_from_pkey(multi_libctx, shared_evp_pkey, NULL); if (!TEST_ptr(ctx)) goto err; ptlen = sizeof(ptbuf); if (!TEST_int_ge(EVP_PKEY_decrypt_init(ctx), 0) || !TEST_int_gt(EVP_PKEY_decrypt(ctx, ptbuf, &ptlen, ctbuf, ctlen), 0) || !TEST_mem_eq(msg, strlen(msg), ptbuf, ptlen)) goto err; } success = 1; err: EVP_PKEY_CTX_free(ctx); if (!success) multi_set_success(0); } static void thread_provider_load_unload(void) { OSSL_PROVIDER *deflt = OSSL_PROVIDER_load(multi_libctx, "default"); if (!TEST_ptr(deflt) || !TEST_true(OSSL_PROVIDER_available(multi_libctx, "default"))) multi_set_success(0); OSSL_PROVIDER_unload(deflt); } static int test_multi_general_worker_default_provider(void) { return thread_run_test(&thread_general_worker, 2, &thread_general_worker, 1, default_provider); } static int test_multi_general_worker_fips_provider(void) { if (!do_fips) return TEST_skip("FIPS not supported"); return thread_run_test(&thread_general_worker, 2, &thread_general_worker, 1, fips_provider); } static int test_multi_fetch_worker(void) { return thread_run_test(&thread_multi_simple_fetch, 2, &thread_multi_simple_fetch, 1, default_provider); } static int test_multi_shared_pkey_common(void (*worker)(void)) { int testresult = 0; multi_intialise(); if (!thread_setup_libctx(1, do_fips ? fips_and_default_providers : default_provider) || !TEST_ptr(shared_evp_pkey = load_pkey_pem(privkey, multi_libctx)) || !start_threads(1, &thread_shared_evp_pkey) || !start_threads(1, worker)) goto err; thread_shared_evp_pkey(); if (!teardown_threads() || !TEST_true(multi_success)) goto err; testresult = 1; err: EVP_PKEY_free(shared_evp_pkey); thead_teardown_libctx(); return testresult; } #ifndef OPENSSL_NO_DEPRECATED_3_0 static void thread_downgrade_shared_evp_pkey(void) { /* * This test is only relevant for deprecated functions that perform * downgrading */ if (EVP_PKEY_get0_RSA(shared_evp_pkey) == NULL) multi_set_success(0); } static int test_multi_downgrade_shared_pkey(void) { return test_multi_shared_pkey_common(&thread_downgrade_shared_evp_pkey); } #endif static int test_multi_shared_pkey(void) { return test_multi_shared_pkey_common(&thread_shared_evp_pkey); } static void thread_release_shared_pkey(void) { OSSL_sleep(0); EVP_PKEY_free(shared_evp_pkey); } static int test_multi_shared_pkey_release(void) { int testresult = 0; size_t i = 1; multi_intialise(); shared_evp_pkey = NULL; if (!thread_setup_libctx(1, do_fips ? fips_and_default_providers : default_provider) || !TEST_ptr(shared_evp_pkey = load_pkey_pem(privkey, multi_libctx))) goto err; for (; i < 10; ++i) { if (!TEST_true(EVP_PKEY_up_ref(shared_evp_pkey))) goto err; } if (!start_threads(10, &thread_release_shared_pkey)) goto err; i = 0; if (!teardown_threads() || !TEST_true(multi_success)) goto err; testresult = 1; err: while (i > 0) { EVP_PKEY_free(shared_evp_pkey); --i; } thead_teardown_libctx(); return testresult; } static int test_multi_load_unload_provider(void) { EVP_MD *sha256 = NULL; OSSL_PROVIDER *prov = NULL; int testresult = 0; multi_intialise(); if (!thread_setup_libctx(1, NULL) || !TEST_ptr(prov = OSSL_PROVIDER_load(multi_libctx, "default")) || !TEST_ptr(sha256 = EVP_MD_fetch(multi_libctx, "SHA2-256", NULL)) || !TEST_true(OSSL_PROVIDER_unload(prov))) goto err; prov = NULL; if (!start_threads(2, &thread_provider_load_unload)) goto err; thread_provider_load_unload(); if (!teardown_threads() || !TEST_true(multi_success)) goto err; testresult = 1; err: OSSL_PROVIDER_unload(prov); EVP_MD_free(sha256); thead_teardown_libctx(); return testresult; } static char *multi_load_provider = "legacy"; /* * This test attempts to load several providers at the same time, and if * run with a thread sanitizer, should crash if the core provider code * doesn't synchronize well enough. */ static void test_multi_load_worker(void) { OSSL_PROVIDER *prov; if (!TEST_ptr(prov = OSSL_PROVIDER_load(multi_libctx, multi_load_provider)) || !TEST_true(OSSL_PROVIDER_unload(prov))) multi_set_success(0); } static int test_multi_default(void) { /* Avoid running this test twice */ if (multidefault_run) { TEST_skip("multi default test already run"); return 1; } multidefault_run = 1; return thread_run_test(&thread_multi_simple_fetch, 2, &thread_multi_simple_fetch, 0, NULL); } static int test_multi_load(void) { int res = 1; OSSL_PROVIDER *prov; /* The multidefault test must run prior to this test */ if (!multidefault_run) { TEST_info("Running multi default test first"); res = test_multi_default(); } /* * We use the legacy provider in test_multi_load_worker because it uses a * child libctx that might hit more codepaths that might be sensitive to * threading issues. But in a no-legacy build that won't be loadable so * we use the default provider instead. */ prov = OSSL_PROVIDER_load(NULL, "legacy"); if (prov == NULL) { TEST_info("Cannot load legacy provider - assuming this is a no-legacy build"); multi_load_provider = "default"; } OSSL_PROVIDER_unload(prov); return thread_run_test(NULL, MAXIMUM_THREADS, &test_multi_load_worker, 0, NULL) && res; } static void test_obj_create_one(void) { char tids[12], oid[40], sn[30], ln[30]; int id = get_new_uid(); BIO_snprintf(tids, sizeof(tids), "%d", id); BIO_snprintf(oid, sizeof(oid), "1.3.6.1.4.1.16604.%s", tids); BIO_snprintf(sn, sizeof(sn), "short-name-%s", tids); BIO_snprintf(ln, sizeof(ln), "long-name-%s", tids); if (!TEST_int_ne(id, 0) || !TEST_true(id = OBJ_create(oid, sn, ln)) || !TEST_true(OBJ_add_sigid(id, NID_sha3_256, NID_rsa))) multi_set_success(0); } static int test_obj_add(void) { return thread_run_test(&test_obj_create_one, MAXIMUM_THREADS, &test_obj_create_one, 1, default_provider); } #if !defined(OPENSSL_NO_DGRAM) && !defined(OPENSSL_NO_SOCK) static BIO *multi_bio1, *multi_bio2; static void test_bio_dgram_pair_worker(void) { ossl_unused int r; int ok = 0; uint8_t ch = 0; uint8_t scratch[64]; BIO_MSG msg = {0}; size_t num_processed = 0; if (!TEST_int_eq(RAND_bytes_ex(multi_libctx, &ch, 1, 64), 1)) goto err; msg.data = scratch; msg.data_len = sizeof(scratch); /* * We do not test for failure here as recvmmsg may fail if no sendmmsg * has been called yet. The purpose of this code is to exercise tsan. */ if (ch & 2) r = BIO_sendmmsg(ch & 1 ? multi_bio2 : multi_bio1, &msg, sizeof(BIO_MSG), 1, 0, &num_processed); else r = BIO_recvmmsg(ch & 1 ? multi_bio2 : multi_bio1, &msg, sizeof(BIO_MSG), 1, 0, &num_processed); ok = 1; err: if (ok == 0) multi_set_success(0); } static int test_bio_dgram_pair(void) { int r; BIO *bio1 = NULL, *bio2 = NULL; r = BIO_new_bio_dgram_pair(&bio1, 0, &bio2, 0); if (!TEST_int_eq(r, 1)) goto err; multi_bio1 = bio1; multi_bio2 = bio2; r = thread_run_test(&test_bio_dgram_pair_worker, MAXIMUM_THREADS, &test_bio_dgram_pair_worker, 1, default_provider); err: BIO_free(bio1); BIO_free(bio2); return r; } #endif static const char *pemdataraw[] = { "-----BEGIN RSA PRIVATE KEY-----\n", "MIIBOgIBAAJBAMFcGsaxxdgiuuGmCkVImy4h99CqT7jwY3pexPGcnUFtR2Fh36Bp\n", "oncwtkZ4cAgtvd4Qs8PkxUdp6p/DlUmObdkCAwEAAQJAUR44xX6zB3eaeyvTRzms\n", "kHADrPCmPWnr8dxsNwiDGHzrMKLN+i/HAam+97HxIKVWNDH2ba9Mf1SA8xu9dcHZ\n", "AQIhAOHPCLxbtQFVxlnhSyxYeb7O323c3QulPNn3bhOipElpAiEA2zZpBE8ZXVnL\n", "74QjG4zINlDfH+EOEtjJJ3RtaYDugvECIBtsQDxXytChsRgDQ1TcXdStXPcDppie\n", "dZhm8yhRTTBZAiAZjE/U9rsIDC0ebxIAZfn3iplWh84yGB3pgUI3J5WkoQIhAInE\n", "HTUY5WRj5riZtkyGnbm3DvF+1eMtO2lYV+OuLcfE\n", "-----END RSA PRIVATE KEY-----\n", NULL }; static void test_pem_read_one(void) { EVP_PKEY *key = NULL; BIO *pem = NULL; char *pemdata; size_t len; pemdata = glue_strings(pemdataraw, &len); if (pemdata == NULL) { multi_set_success(0); goto err; } pem = BIO_new_mem_buf(pemdata, len); if (pem == NULL) { multi_set_success(0); goto err; } key = PEM_read_bio_PrivateKey(pem, NULL, NULL, NULL); if (key == NULL) multi_set_success(0); err: EVP_PKEY_free(key); BIO_free(pem); OPENSSL_free(pemdata); } /* Test reading PEM files in multiple threads */ static int test_pem_read(void) { return thread_run_test(&test_pem_read_one, MAXIMUM_THREADS, &test_pem_read_one, 1, default_provider); } static X509_STORE *store = NULL; static void test_x509_store_by_subject(void) { X509_STORE_CTX *ctx; X509_OBJECT *obj = NULL; X509_NAME *name = NULL; int success = 0; ctx = X509_STORE_CTX_new(); if (!TEST_ptr(ctx)) goto err; if (!TEST_true(X509_STORE_CTX_init(ctx, store, NULL, NULL))) goto err; name = X509_NAME_new(); if (!TEST_ptr(name)) goto err; if (!TEST_true(X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned char *)"Root CA", -1, -1, 0))) goto err; obj = X509_STORE_CTX_get_obj_by_subject(ctx, X509_LU_X509, name); if (!TEST_ptr(obj)) goto err; success = 1; err: X509_OBJECT_free(obj); X509_STORE_CTX_free(ctx); X509_NAME_free(name); if (!success) multi_set_success(0); } /* Test accessing an X509_STORE from multiple threads */ static int test_x509_store(void) { int ret = 0; store = X509_STORE_new(); if (!TEST_ptr(store)) return 0; if (!TEST_true(X509_STORE_load_store(store, storedir))) goto err; ret = thread_run_test(&test_x509_store_by_subject, MAXIMUM_THREADS, &test_x509_store_by_subject, 0, NULL); err: X509_STORE_free(store); store = NULL; return ret; } typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_FIPS, OPT_CONFIG_FILE, OPT_TEST_ENUM } OPTION_CHOICE; const OPTIONS *test_get_options(void) { static const OPTIONS options[] = { OPT_TEST_OPTIONS_DEFAULT_USAGE, { "fips", OPT_FIPS, '-', "Test the FIPS provider" }, { "config", OPT_CONFIG_FILE, '<', "The configuration file to use for the libctx" }, { NULL } }; return options; } int setup_tests(void) { OPTION_CHOICE o; char *datadir; while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_FIPS: do_fips = 1; break; case OPT_CONFIG_FILE: config_file = opt_arg(); break; case OPT_TEST_CASES: break; default: return 0; } } if (!TEST_ptr(datadir = test_get_argument(0))) return 0; privkey = test_mk_file_path(datadir, "rsakey.pem"); if (!TEST_ptr(privkey)) return 0; storedir = test_mk_file_path(datadir, "store"); if (!TEST_ptr(storedir)) return 0; if (!TEST_ptr(global_lock = CRYPTO_THREAD_lock_new())) return 0; #ifdef TSAN_REQUIRES_LOCKING if (!TEST_ptr(tsan_lock = CRYPTO_THREAD_lock_new())) return 0; #endif /* Keep first to validate auto creation of default library context */ ADD_TEST(test_multi_default); ADD_TEST(test_lock); #if defined(OPENSSL_THREADS) ADD_TEST(torture_rw_low); ADD_TEST(torture_rw_high); ADD_TEST(torture_rcu_low); ADD_TEST(torture_rcu_high); ADD_TEST(torture_rcu_high2); #endif ADD_TEST(test_once); ADD_TEST(test_thread_local); ADD_TEST(test_thread_local_multi_key); ADD_TEST(test_atomic); ADD_TEST(test_multi_load); ADD_TEST(test_multi_general_worker_default_provider); ADD_TEST(test_multi_general_worker_fips_provider); ADD_TEST(test_multi_fetch_worker); ADD_TEST(test_multi_shared_pkey); #ifndef OPENSSL_NO_DEPRECATED_3_0 ADD_TEST(test_multi_downgrade_shared_pkey); #endif ADD_TEST(test_multi_shared_pkey_release); ADD_TEST(test_multi_load_unload_provider); ADD_TEST(test_obj_add); #if !defined(OPENSSL_NO_DGRAM) && !defined(OPENSSL_NO_SOCK) ADD_TEST(test_bio_dgram_pair); #endif ADD_TEST(test_pem_read); ADD_TEST(test_x509_store); return 1; } void cleanup_tests(void) { OPENSSL_free(privkey); OPENSSL_free(storedir); #ifdef TSAN_REQUIRES_LOCKING CRYPTO_THREAD_lock_free(tsan_lock); #endif CRYPTO_THREAD_lock_free(global_lock); } diff --git a/test/wpackettest.c b/test/wpackettest.c index bd696e007407..c6d6faf5c485 100644 --- a/test/wpackettest.c +++ b/test/wpackettest.c @@ -1,654 +1,654 @@ /* * Copyright 2016-2025 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 "internal/packet_quic.h" #include "testutil.h" static const unsigned char simple1[] = { 0xff }; static const unsigned char simple2[] = { 0x01, 0xff }; static const unsigned char simple3[] = { 0x00, 0x00, 0x00, 0x01, 0xff }; static const unsigned char nestedsub[] = { 0x03, 0xff, 0x01, 0xff }; static const unsigned char seqsub[] = { 0x01, 0xff, 0x01, 0xff }; static const unsigned char empty[] = { 0x00 }; static const unsigned char alloc[] = { 0x02, 0xfe, 0xff }; static const unsigned char submem[] = { 0x03, 0x02, 0xfe, 0xff }; static const unsigned char fixed[] = { 0xff, 0xff, 0xff }; static const unsigned char simpleder[] = { 0xfc, 0x04, 0x00, 0x01, 0x02, 0x03, 0xff, 0xfe, 0xfd }; #ifndef OPENSSL_NO_QUIC /* QUIC sub-packet with 4-byte length prefix, containing a 1-byte vlint */ static const unsigned char quic1[] = { 0x80, 0x00, 0x00, 0x01, 0x09 }; /* QUIC sub-packet with 1-byte length prefix, containing a 1-byte vlint */ static const unsigned char quic2[] = { 0x01, 0x09 }; /* QUIC sub-packet with 2-byte length prefix, containing a 2-byte vlint */ static const unsigned char quic3[] = { 0x40, 0x02, 0x40, 0x41 }; /* QUIC sub-packet with 8-byte length prefix, containing a 4-byte vlint */ static const unsigned char quic4[] = { 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x80, 0x01, 0x3c, 0x6a }; /* QUIC sub-packet with 8-byte length prefix, containing a 8-byte vlint */ static const unsigned char quic5[] = { 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0xef, 0x77, 0x21, 0x3f, 0x3f, 0x50, 0x5b, 0xa5 }; /* QUIC sub-packet, length known up-front */ static const unsigned char quic6[] = { 0x03, 0x55, 0x66, 0x77 }; /* Nested and sequential sub-packets with length prefixes */ static const unsigned char quic7[] = { 0x07, 0x80, 0x00, 0x00, 0x08, 0x65, 0x14, 0x40, 0x01, 0x05, 0x40, 0x01, 0x11, 0x40, 0x01, 0x12, 0x40, 0x01, 0x13 }; #endif static BUF_MEM *buf; static int cleanup(WPACKET *pkt) { WPACKET_cleanup(pkt); return 0; } static int test_WPACKET_init(void) { WPACKET pkt; int i; size_t written; unsigned char sbuf[3]; if (!TEST_true(WPACKET_init(&pkt, buf)) || !TEST_true(WPACKET_put_bytes_u8(&pkt, 0xff)) /* Closing a top level WPACKET should fail */ || !TEST_false(WPACKET_close(&pkt)) /* Finishing a top level WPACKET should succeed */ || !TEST_true(WPACKET_finish(&pkt)) /* * Can't call close or finish on a WPACKET that's already * finished. */ || !TEST_false(WPACKET_close(&pkt)) || !TEST_false(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, simple1, sizeof(simple1))) return cleanup(&pkt); /* Now try with a one byte length prefix */ if (!TEST_true(WPACKET_init_len(&pkt, buf, 1)) || !TEST_true(WPACKET_put_bytes_u8(&pkt, 0xff)) || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, simple2, sizeof(simple2))) return cleanup(&pkt); /* And a longer length prefix */ if (!TEST_true(WPACKET_init_len(&pkt, buf, 4)) || !TEST_true(WPACKET_put_bytes_u8(&pkt, 0xff)) || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, simple3, sizeof(simple3))) return cleanup(&pkt); if (!TEST_true(WPACKET_init_len(&pkt, buf, 1))) return cleanup(&pkt); for (i = 1; i < 257; i++) { /* * Putting more bytes in than fit for the size of the length prefix * should fail */ if (!TEST_int_eq(WPACKET_put_bytes_u8(&pkt, 0xff), i < 256)) return cleanup(&pkt); } if (!TEST_true(WPACKET_finish(&pkt))) return cleanup(&pkt); /* Test initialising from a fixed size buffer */ if (!TEST_true(WPACKET_init_static_len(&pkt, sbuf, sizeof(sbuf), 0)) /* Adding 3 bytes should succeed */ || !TEST_true(WPACKET_put_bytes_u24(&pkt, 0xffffff)) /* Adding 1 more byte should fail */ || !TEST_false(WPACKET_put_bytes_u8(&pkt, 0xff)) /* Finishing the top level WPACKET should succeed */ || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(sbuf, written, fixed, sizeof(sbuf)) /* Initialise with 1 len byte */ || !TEST_true(WPACKET_init_static_len(&pkt, sbuf, sizeof(sbuf), 1)) /* Adding 2 bytes should succeed */ || !TEST_true(WPACKET_put_bytes_u16(&pkt, 0xfeff)) /* Adding 1 more byte should fail */ || !TEST_false(WPACKET_put_bytes_u8(&pkt, 0xff)) || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(sbuf, written, alloc, sizeof(alloc))) return cleanup(&pkt); return 1; } static int test_WPACKET_set_max_size(void) { WPACKET pkt; size_t written; if (!TEST_true(WPACKET_init(&pkt, buf)) /* * No previous lenbytes set so we should be ok to set the max * possible max size */ || !TEST_true(WPACKET_set_max_size(&pkt, SIZE_MAX)) /* We should be able to set it smaller too */ || !TEST_true(WPACKET_set_max_size(&pkt, SIZE_MAX -1)) /* And setting it bigger again should be ok */ || !TEST_true(WPACKET_set_max_size(&pkt, SIZE_MAX)) || !TEST_true(WPACKET_finish(&pkt))) return cleanup(&pkt); if (!TEST_true(WPACKET_init_len(&pkt, buf, 1)) /* * Should fail because we already consumed 1 byte with the * length */ || !TEST_false(WPACKET_set_max_size(&pkt, 0)) /* * Max size can't be bigger than biggest that will fit in * lenbytes */ || !TEST_false(WPACKET_set_max_size(&pkt, 0x0101)) /* It can be the same as the maximum possible size */ || !TEST_true(WPACKET_set_max_size(&pkt, 0x0100)) /* Or it can be less */ || !TEST_true(WPACKET_set_max_size(&pkt, 0x01)) /* Should fail because packet is already filled */ || !TEST_false(WPACKET_put_bytes_u8(&pkt, 0xff)) /* You can't put in more bytes than max size */ || !TEST_true(WPACKET_set_max_size(&pkt, 0x02)) || !TEST_true(WPACKET_put_bytes_u8(&pkt, 0xff)) || !TEST_false(WPACKET_put_bytes_u8(&pkt, 0xff)) || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, simple2, sizeof(simple2))) return cleanup(&pkt); return 1; } static int test_WPACKET_start_sub_packet(void) { WPACKET pkt; size_t written; size_t len; if (!TEST_true(WPACKET_init(&pkt, buf)) || !TEST_true(WPACKET_start_sub_packet(&pkt)) || !TEST_true(WPACKET_put_bytes_u8(&pkt, 0xff)) /* Can't finish because we have a sub packet */ || !TEST_false(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_close(&pkt)) /* Sub packet is closed so can't close again */ || !TEST_false(WPACKET_close(&pkt)) /* Now a top level so finish should succeed */ || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, simple1, sizeof(simple1))) return cleanup(&pkt); /* Single sub-packet with length prefix */ if (!TEST_true(WPACKET_init(&pkt, buf)) || !TEST_true(WPACKET_start_sub_packet_u8(&pkt)) || !TEST_true(WPACKET_put_bytes_u8(&pkt, 0xff)) || !TEST_true(WPACKET_close(&pkt)) || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, simple2, sizeof(simple2))) return cleanup(&pkt); /* Nested sub-packets with length prefixes */ if (!TEST_true(WPACKET_init(&pkt, buf)) || !TEST_true(WPACKET_start_sub_packet_u8(&pkt)) || !TEST_true(WPACKET_put_bytes_u8(&pkt, 0xff)) || !TEST_true(WPACKET_start_sub_packet_u8(&pkt)) || !TEST_true(WPACKET_put_bytes_u8(&pkt, 0xff)) || !TEST_true(WPACKET_get_length(&pkt, &len)) || !TEST_size_t_eq(len, 1) || !TEST_true(WPACKET_close(&pkt)) || !TEST_true(WPACKET_get_length(&pkt, &len)) || !TEST_size_t_eq(len, 3) || !TEST_true(WPACKET_close(&pkt)) || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, nestedsub, sizeof(nestedsub))) return cleanup(&pkt); /* Sequential sub-packets with length prefixes */ if (!TEST_true(WPACKET_init(&pkt, buf)) || !TEST_true(WPACKET_start_sub_packet_u8(&pkt)) || !TEST_true(WPACKET_put_bytes_u8(&pkt, 0xff)) || !TEST_true(WPACKET_close(&pkt)) || !TEST_true(WPACKET_start_sub_packet_u8(&pkt)) || !TEST_true(WPACKET_put_bytes_u8(&pkt, 0xff)) || !TEST_true(WPACKET_close(&pkt)) || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, seqsub, sizeof(seqsub))) return cleanup(&pkt); /* Nested sub-packets with lengths filled before finish */ if (!TEST_true(WPACKET_init(&pkt, buf)) || !TEST_true(WPACKET_start_sub_packet_u8(&pkt)) || !TEST_true(WPACKET_put_bytes_u8(&pkt, 0xff)) || !TEST_true(WPACKET_start_sub_packet_u8(&pkt)) || !TEST_true(WPACKET_put_bytes_u8(&pkt, 0xff)) || !TEST_true(WPACKET_get_length(&pkt, &len)) || !TEST_size_t_eq(len, 1) || !TEST_true(WPACKET_close(&pkt)) || !TEST_true(WPACKET_get_length(&pkt, &len)) || !TEST_size_t_eq(len, 3) || !TEST_true(WPACKET_close(&pkt)) || !TEST_true(WPACKET_fill_lengths(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, nestedsub, sizeof(nestedsub)) || !TEST_true(WPACKET_finish(&pkt))) return cleanup(&pkt); return 1; } static int test_WPACKET_set_flags(void) { WPACKET pkt; size_t written; /* Set packet to be non-zero length */ if (!TEST_true(WPACKET_init(&pkt, buf)) || !TEST_true(WPACKET_set_flags(&pkt, WPACKET_FLAGS_NON_ZERO_LENGTH)) /* Should fail because of zero length */ || !TEST_false(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_put_bytes_u8(&pkt, 0xff)) || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, simple1, sizeof(simple1))) return cleanup(&pkt); /* Repeat above test in a sub-packet */ if (!TEST_true(WPACKET_init(&pkt, buf)) || !TEST_true(WPACKET_start_sub_packet(&pkt)) || !TEST_true(WPACKET_set_flags(&pkt, WPACKET_FLAGS_NON_ZERO_LENGTH)) /* Should fail because of zero length */ || !TEST_false(WPACKET_close(&pkt)) || !TEST_true(WPACKET_put_bytes_u8(&pkt, 0xff)) || !TEST_true(WPACKET_close(&pkt)) || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, simple1, sizeof(simple1))) return cleanup(&pkt); /* Set packet to abandon non-zero length */ if (!TEST_true(WPACKET_init_len(&pkt, buf, 1)) || !TEST_true(WPACKET_set_flags(&pkt, WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH)) || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_size_t_eq(written, 0)) return cleanup(&pkt); /* Repeat above test but only abandon a sub-packet */ if (!TEST_true(WPACKET_init_len(&pkt, buf, 1)) || !TEST_true(WPACKET_start_sub_packet_u8(&pkt)) || !TEST_true(WPACKET_set_flags(&pkt, WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH)) || !TEST_true(WPACKET_close(&pkt)) || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, empty, sizeof(empty))) return cleanup(&pkt); /* And repeat with a non empty sub-packet */ if (!TEST_true(WPACKET_init(&pkt, buf)) || !TEST_true(WPACKET_start_sub_packet_u8(&pkt)) || !TEST_true(WPACKET_set_flags(&pkt, WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH)) || !TEST_true(WPACKET_put_bytes_u8(&pkt, 0xff)) || !TEST_true(WPACKET_close(&pkt)) || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, simple2, sizeof(simple2))) return cleanup(&pkt); return 1; } static int test_WPACKET_allocate_bytes(void) { WPACKET pkt; size_t written; unsigned char *bytes; if (!TEST_true(WPACKET_init_len(&pkt, buf, 1)) || !TEST_true(WPACKET_allocate_bytes(&pkt, 2, &bytes))) return cleanup(&pkt); bytes[0] = 0xfe; bytes[1] = 0xff; if (!TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, alloc, sizeof(alloc))) return cleanup(&pkt); /* Repeat with WPACKET_sub_allocate_bytes */ if (!TEST_true(WPACKET_init_len(&pkt, buf, 1)) || !TEST_true(WPACKET_sub_allocate_bytes_u8(&pkt, 2, &bytes))) return cleanup(&pkt); bytes[0] = 0xfe; bytes[1] = 0xff; if (!TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, submem, sizeof(submem))) return cleanup(&pkt); return 1; } static int test_WPACKET_memcpy(void) { WPACKET pkt; size_t written; const unsigned char bytes[] = { 0xfe, 0xff }; if (!TEST_true(WPACKET_init_len(&pkt, buf, 1)) || !TEST_true(WPACKET_memcpy(&pkt, bytes, sizeof(bytes))) || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, alloc, sizeof(alloc))) return cleanup(&pkt); /* Repeat with WPACKET_sub_memcpy() */ if (!TEST_true(WPACKET_init_len(&pkt, buf, 1)) || !TEST_true(WPACKET_sub_memcpy_u8(&pkt, bytes, sizeof(bytes))) || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, submem, sizeof(submem))) return cleanup(&pkt); return 1; } static int test_WPACKET_init_der(void) { WPACKET pkt; unsigned char sbuf[1024]; unsigned char testdata[] = { 0x00, 0x01, 0x02, 0x03 }; unsigned char testdata2[259] = { 0x82, 0x01, 0x00 }; size_t written[2]; size_t size1, size2; int flags = WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH; int i; /* Test initialising for writing DER */ if (!TEST_true(WPACKET_init_der(&pkt, sbuf, sizeof(sbuf))) || !TEST_true(WPACKET_put_bytes_u24(&pkt, 0xfffefd)) /* Test writing data in a length prefixed sub-packet */ || !TEST_true(WPACKET_start_sub_packet(&pkt)) || !TEST_true(WPACKET_memcpy(&pkt, testdata, sizeof(testdata))) || !TEST_true(WPACKET_close(&pkt)) || !TEST_true(WPACKET_put_bytes_u8(&pkt, 0xfc)) /* this sub-packet is empty, and should render zero bytes */ || (!TEST_true(WPACKET_start_sub_packet(&pkt)) || !TEST_true(WPACKET_set_flags(&pkt, flags)) || !TEST_true(WPACKET_get_total_written(&pkt, &size1)) || !TEST_true(WPACKET_close(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &size2)) || !TEST_size_t_eq(size1, size2)) || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written[0])) || !TEST_mem_eq(WPACKET_get_curr(&pkt), written[0], simpleder, sizeof(simpleder))) return cleanup(&pkt); /* Generate random packet data for test */ if (!TEST_int_gt(RAND_bytes(&testdata2[3], sizeof(testdata2) - 3), 0)) return 0; /* * Test with a sub-packet that has 2 length bytes. We do 2 passes - first * with a NULL buffer, just to calculate lengths, and a second pass with a * real buffer to actually generate a packet */ for (i = 0; i < 2; i++) { if (i == 0) { if (!TEST_true(WPACKET_init_null_der(&pkt))) return 0; } else { if (!TEST_true(WPACKET_init_der(&pkt, sbuf, sizeof(sbuf)))) return 0; } if (!TEST_true(WPACKET_start_sub_packet(&pkt)) || !TEST_true(WPACKET_memcpy(&pkt, &testdata2[3], sizeof(testdata2) - 3)) || !TEST_true(WPACKET_close(&pkt)) || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written[i]))) return cleanup(&pkt); } /* * Check that the size calculated in the first pass equals the size of the * packet actually generated in the second pass. Also check the generated * packet looks as we expect it to. */ if (!TEST_size_t_eq(written[0], written[1]) || !TEST_mem_eq(WPACKET_get_curr(&pkt), written[1], testdata2, sizeof(testdata2))) return 0; return 1; } #ifndef OPENSSL_NO_QUIC static int test_WPACKET_quic(void) { WPACKET pkt; size_t written, len; unsigned char *bytes; /* QUIC sub-packet with 4-byte length prefix, containing a 1-byte vlint */ if (!TEST_true(WPACKET_init(&pkt, buf)) || !TEST_true(WPACKET_start_quic_sub_packet(&pkt)) || !TEST_true(WPACKET_quic_write_vlint(&pkt, 0x09)) /* Can't finish because we have a sub packet */ || !TEST_false(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_close(&pkt)) /* Sub packet is closed so can't close again */ || !TEST_false(WPACKET_close(&pkt)) /* Now a top level so finish should succeed */ || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, quic1, sizeof(quic1))) return cleanup(&pkt); /* QUIC sub-packet with 1-byte length prefix, containing a 1-byte vlint */ if (!TEST_true(WPACKET_init(&pkt, buf)) || !TEST_true(WPACKET_start_quic_sub_packet_bound(&pkt, OSSL_QUIC_VLINT_1B_MAX)) || !TEST_true(WPACKET_quic_write_vlint(&pkt, 0x09)) || !TEST_false(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_close(&pkt)) || !TEST_false(WPACKET_close(&pkt)) || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, quic2, sizeof(quic2))) return cleanup(&pkt); /* QUIC sub-packet with 2-byte length prefix, containing a 2-byte vlint */ if (!TEST_true(WPACKET_init(&pkt, buf)) || !TEST_true(WPACKET_start_quic_sub_packet_bound(&pkt, OSSL_QUIC_VLINT_2B_MIN)) || !TEST_true(WPACKET_quic_write_vlint(&pkt, 0x41)) || !TEST_false(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_close(&pkt)) || !TEST_false(WPACKET_close(&pkt)) || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, quic3, sizeof(quic3))) return cleanup(&pkt); /* QUIC sub-packet with 8-byte length prefix, containing a 4-byte vlint */ if (!TEST_true(WPACKET_init(&pkt, buf)) || !TEST_true(WPACKET_start_quic_sub_packet_bound(&pkt, OSSL_QUIC_VLINT_8B_MIN)) || !TEST_true(WPACKET_quic_write_vlint(&pkt, 0x13c6a)) || !TEST_false(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_close(&pkt)) || !TEST_false(WPACKET_close(&pkt)) || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, quic4, sizeof(quic4))) return cleanup(&pkt); /* QUIC sub-packet with 8-byte length prefix, containing a 8-byte vlint */ if (!TEST_true(WPACKET_init(&pkt, buf)) || !TEST_true(WPACKET_start_quic_sub_packet_bound(&pkt, OSSL_QUIC_VLINT_8B_MIN)) || !TEST_true(WPACKET_quic_write_vlint(&pkt, 0x2f77213f3f505ba5ULL)) || !TEST_false(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_close(&pkt)) || !TEST_false(WPACKET_close(&pkt)) || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, quic5, sizeof(quic5))) return cleanup(&pkt); /* QUIC sub-packet, length known up-front */ if (!TEST_true(WPACKET_init(&pkt, buf)) || !TEST_true(WPACKET_quic_sub_allocate_bytes(&pkt, 3, &bytes))) return cleanup(&pkt); bytes[0] = 0x55; bytes[1] = 0x66; bytes[2] = 0x77; if (!TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, quic6, sizeof(quic6))) return cleanup(&pkt); /* Nested and sequential sub-packets with length prefixes */ if (!TEST_true(WPACKET_init(&pkt, buf)) || !TEST_true(WPACKET_quic_write_vlint(&pkt, 0x07)) || !TEST_true(WPACKET_get_length(&pkt, &len)) || !TEST_size_t_eq(len, 1) || !TEST_true(WPACKET_start_quic_sub_packet_bound(&pkt, OSSL_QUIC_VLINT_4B_MIN)) || !TEST_true(WPACKET_quic_write_vlint(&pkt, 0x2514)) || !TEST_true(WPACKET_get_length(&pkt, &len)) || !TEST_size_t_eq(len, 2) || !TEST_true(WPACKET_start_quic_sub_packet_bound(&pkt, OSSL_QUIC_VLINT_2B_MIN)) || !TEST_true(WPACKET_quic_write_vlint(&pkt, 0x05)) || !TEST_true(WPACKET_get_length(&pkt, &len)) || !TEST_size_t_eq(len, 1) || !TEST_true(WPACKET_close(&pkt)) || !TEST_true(WPACKET_start_quic_sub_packet_bound(&pkt, OSSL_QUIC_VLINT_2B_MIN)) || !TEST_true(WPACKET_quic_write_vlint(&pkt, 0x11)) || !TEST_true(WPACKET_close(&pkt)) || !TEST_true(WPACKET_get_length(&pkt, &len)) || !TEST_size_t_eq(len, 8) || !TEST_true(WPACKET_close(&pkt)) || !TEST_true(WPACKET_start_quic_sub_packet_bound(&pkt, OSSL_QUIC_VLINT_2B_MIN)) || !TEST_true(WPACKET_quic_write_vlint(&pkt, 0x12)) || !TEST_true(WPACKET_close(&pkt)) || !TEST_true(WPACKET_start_quic_sub_packet_bound(&pkt, OSSL_QUIC_VLINT_2B_MIN)) || !TEST_true(WPACKET_quic_write_vlint(&pkt, 0x13)) || !TEST_true(WPACKET_close(&pkt)) || !TEST_true(WPACKET_finish(&pkt)) || !TEST_true(WPACKET_get_total_written(&pkt, &written)) || !TEST_mem_eq(buf->data, written, quic7, sizeof(quic7))) return cleanup(&pkt); /* Trying to encode a value above OSSL_QUIC_VLINT_MAX should fail */ if (!TEST_true(WPACKET_init(&pkt, buf)) || !TEST_false(WPACKET_quic_write_vlint(&pkt, OSSL_QUIC_VLINT_MAX+1)) || !TEST_true(WPACKET_quic_write_vlint(&pkt, OSSL_QUIC_VLINT_MAX))) return cleanup(&pkt); WPACKET_cleanup(&pkt); return 1; } static int test_WPACKET_quic_vlint_random(void) { size_t i, written; uint64_t expected, actual = 0; unsigned char rand_data[9]; WPACKET pkt; PACKET read_pkt = {0}; for (i = 0; i < 10000; ++i) { if (!TEST_int_gt(RAND_bytes(rand_data, sizeof(rand_data)), 0)) - return cleanup(&pkt); + return 0; memcpy(&expected, rand_data, sizeof(expected)); /* * Ensure that all size classes get tested with equal probability. */ switch (rand_data[8] & 3) { case 0: expected &= OSSL_QUIC_VLINT_1B_MAX; break; case 1: expected &= OSSL_QUIC_VLINT_2B_MAX; break; case 2: expected &= OSSL_QUIC_VLINT_4B_MAX; break; case 3: expected &= OSSL_QUIC_VLINT_8B_MAX; break; } if (!TEST_true(WPACKET_init(&pkt, buf)) || !TEST_true(WPACKET_quic_write_vlint(&pkt, expected)) || !TEST_true(WPACKET_get_total_written(&pkt, &written))) return cleanup(&pkt); if (!TEST_true(PACKET_buf_init(&read_pkt, (unsigned char *)buf->data, written)) || !TEST_true(PACKET_get_quic_vlint(&read_pkt, &actual)) || !TEST_uint64_t_eq(expected, actual)) return cleanup(&pkt); WPACKET_cleanup(&pkt); } WPACKET_cleanup(&pkt); return 1; } #endif int setup_tests(void) { if (!TEST_ptr(buf = BUF_MEM_new())) return 0; ADD_TEST(test_WPACKET_init); ADD_TEST(test_WPACKET_set_max_size); ADD_TEST(test_WPACKET_start_sub_packet); ADD_TEST(test_WPACKET_set_flags); ADD_TEST(test_WPACKET_allocate_bytes); ADD_TEST(test_WPACKET_memcpy); ADD_TEST(test_WPACKET_init_der); #ifndef OPENSSL_NO_QUIC ADD_TEST(test_WPACKET_quic); ADD_TEST(test_WPACKET_quic_vlint_random); #endif return 1; } void cleanup_tests(void) { BUF_MEM_free(buf); }